@ark-ui/vue
Version:
A collection of unstyled, accessible UI components for Vue, utilizing state machines for seamless interaction.
90 lines (89 loc) • 2.74 kB
JavaScript
import { parts } from "./fieldset.anatomy.js";
import { unrefElement } from "../../utils/unref-element.js";
import { DEFAULT_ENVIRONMENT, useEnvironmentContext } from "../../providers/environment/use-environment-context.js";
import { computed, onBeforeUnmount, onMounted, reactive, ref, toValue, useId } from "vue";
import { dataAttr } from "@zag-js/dom-query";
//#region src/components/fieldset/use-fieldset.ts
var useFieldset = (props = {}) => {
const env = useEnvironmentContext(DEFAULT_ENVIRONMENT);
const state = reactive({
hasErrorText: false,
hasHelperText: false
});
const rootRef = ref(null);
const uuid = useId();
const ids = computed(() => {
const id = toValue(props).id ?? uuid;
return {
legendId: `fieldset::${id}::legend`,
errorTextId: `fieldset::${id}::error-text`,
helperTextId: `fieldset::${id}::helper-text`
};
});
onMounted(() => {
const rootNode = unrefElement(rootRef);
if (!rootNode) return;
const checkTextElements = () => {
const { errorTextId, helperTextId } = ids.value;
const docOrShadowRoot = env.value.getRootNode();
state.hasErrorText = !!docOrShadowRoot.getElementById(errorTextId);
state.hasHelperText = !!docOrShadowRoot.getElementById(helperTextId);
};
checkTextElements();
const observer = new (env.value.getWindow()).MutationObserver(checkTextElements);
observer.observe(rootNode, {
childList: true,
subtree: true
});
onBeforeUnmount(() => {
observer.disconnect();
});
});
return computed(() => {
const { disabled, invalid } = toValue(props);
const { legendId, errorTextId, helperTextId } = ids.value;
const describedByIds = [];
if (state.hasErrorText && invalid) describedByIds.push(errorTextId);
if (state.hasHelperText) describedByIds.push(helperTextId);
const describedBy = describedByIds.length > 0 ? describedByIds.join(" ") : void 0;
const getRootProps = () => ({
...parts.root.attrs,
disabled,
"data-disabled": dataAttr(!!disabled),
"data-invalid": dataAttr(invalid),
"aria-labelledby": legendId,
"aria-describedby": describedBy
});
const getLegendProps = () => ({
id: legendId,
...parts.legend.attrs,
"data-disabled": dataAttr(!!disabled),
"data-invalid": dataAttr(invalid)
});
const getHelperTextProps = () => ({
id: helperTextId,
...parts.helperText.attrs
});
const getErrorTextProps = () => ({
id: errorTextId,
...parts.errorText.attrs,
"aria-live": "polite"
});
return {
refs: { rootRef },
ids: {
legend: legendId,
errorText: errorTextId,
helperText: helperTextId
},
disabled,
invalid,
getRootProps,
getLegendProps,
getHelperTextProps,
getErrorTextProps
};
});
};
//#endregion
export { useFieldset };