feat: establish shared field and form foundation
This commit is contained in:
@@ -1,17 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { inject, onBeforeUnmount, useId, useAttrs } from "vue";
|
||||
import { switchKey } from "../switch/context";
|
||||
const ctx = inject(switchKey, undefined);
|
||||
import { useAttrs } from "vue";
|
||||
import { useFieldPart } from "../field/useFieldPart";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const attrs = useAttrs();
|
||||
const id = String(attrs.id ?? useId());
|
||||
if (ctx) ctx.descriptionIds.value = [...ctx.descriptionIds.value, id];
|
||||
onBeforeUnmount(() => {
|
||||
if (ctx)
|
||||
ctx.descriptionIds.value = ctx.descriptionIds.value.filter(
|
||||
(value) => value !== id,
|
||||
);
|
||||
});
|
||||
const { id } = useFieldPart("description", attrs);
|
||||
</script>
|
||||
<template>
|
||||
<p :id="id" class="hv-description" data-slot="description"><slot /></p>
|
||||
<p v-bind="attrs" :id="id" class="hv-description" data-slot="description">
|
||||
<slot />
|
||||
</p>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import { useAttrs } from "vue";
|
||||
import { useFieldPart } from "./useFieldPart";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const attrs = useAttrs();
|
||||
const { field, id } = useFieldPart("error", attrs);
|
||||
</script>
|
||||
<template>
|
||||
<p
|
||||
v-if="!field || field.invalid.value"
|
||||
v-bind="attrs"
|
||||
:id="id"
|
||||
data-slot="field-error"
|
||||
data-visible
|
||||
class="hv-field-error"
|
||||
role="alert"
|
||||
>
|
||||
<slot
|
||||
:validation-errors="field?.errors.value ?? []"
|
||||
:is-invalid="field?.invalid.value ?? false"
|
||||
>
|
||||
{{ field?.errors.value.join(" ") }}
|
||||
</slot>
|
||||
</p>
|
||||
</template>
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { ComputedRef, InjectionKey, Ref } from "vue";
|
||||
|
||||
export type ValidationBehavior = "native" | "aria";
|
||||
export type ValidationErrors = Record<string, string | string[]>;
|
||||
export type ValidateResult = string | string[] | true | null | undefined;
|
||||
export type FieldPart = "description" | "error";
|
||||
export interface FieldContext {
|
||||
controlId: ComputedRef<string>;
|
||||
kind: "text" | "toggle";
|
||||
disabled: ComputedRef<boolean>;
|
||||
readOnly: ComputedRef<boolean>;
|
||||
required: ComputedRef<boolean>;
|
||||
invalid: ComputedRef<boolean>;
|
||||
errors: ComputedRef<string[]>;
|
||||
descriptionIds: Ref<string[]>;
|
||||
errorIds: Ref<string[]>;
|
||||
}
|
||||
export const fieldContextKey: InjectionKey<FieldContext> =
|
||||
Symbol("HeroUIVue.Field");
|
||||
export interface FormContext {
|
||||
validationBehavior: ComputedRef<ValidationBehavior>;
|
||||
validationErrors: ComputedRef<ValidationErrors>;
|
||||
}
|
||||
export const formContextKey: InjectionKey<FormContext> =
|
||||
Symbol("HeroUIVue.Form");
|
||||
|
||||
export function mergeIds(...values: (string | string[] | undefined)[]) {
|
||||
const ids = values
|
||||
.flatMap((value) =>
|
||||
typeof value === "string" ? value.split(/\s+/) : (value ?? []),
|
||||
)
|
||||
.filter(Boolean);
|
||||
return [...new Set(ids)].join(" ") || undefined;
|
||||
}
|
||||
export function errorMessages(result: ValidateResult | false): string[] {
|
||||
return (
|
||||
typeof result === "string" ? [result] : Array.isArray(result) ? result : []
|
||||
).filter(Boolean);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { computed, inject, onBeforeUnmount, useId, watch } from "vue";
|
||||
import { fieldContextKey, type FieldPart } from "./context";
|
||||
|
||||
/** IDs stay reactive when a caller replaces an explicit id; registration is instance-owned. */
|
||||
export function useFieldPart(part: FieldPart, attrs: Record<string, unknown>) {
|
||||
const field = inject(fieldContextKey, undefined);
|
||||
const generated = useId();
|
||||
const id = computed(() =>
|
||||
typeof attrs.id === "string" ? attrs.id : generated,
|
||||
);
|
||||
const ids = part === "description" ? field?.descriptionIds : field?.errorIds;
|
||||
const stop = watch(
|
||||
id,
|
||||
(current, _, cleanup) => {
|
||||
if (!ids) return;
|
||||
if (!ids.value.includes(current)) ids.value = [...ids.value, current];
|
||||
cleanup(() => {
|
||||
ids.value = ids.value.filter((value) => value !== current);
|
||||
});
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
onBeforeUnmount(stop);
|
||||
return { field, id };
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import {
|
||||
computed,
|
||||
inject,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
onUpdated,
|
||||
ref,
|
||||
watch,
|
||||
} from "vue";
|
||||
import { mergeIds, formContextKey } from "./context";
|
||||
import { textFieldContextKey } from "../textfield/context";
|
||||
|
||||
interface TextControlProps {
|
||||
modelValue?: string;
|
||||
defaultValue?: string;
|
||||
invalid?: boolean;
|
||||
variant?: "primary" | "secondary";
|
||||
fullWidth?: boolean;
|
||||
type?: string;
|
||||
}
|
||||
export function useTextControl(
|
||||
props: TextControlProps,
|
||||
attrs: Record<string, unknown>,
|
||||
emit: (event: "update:modelValue", value: string) => void,
|
||||
) {
|
||||
const field = inject(textFieldContextKey, undefined);
|
||||
const formContext = inject(formContextKey, undefined);
|
||||
const behavior = () =>
|
||||
field?.validationBehavior.value ?? formContext?.validationBehavior.value;
|
||||
const element = ref<HTMLInputElement | HTMLTextAreaElement>();
|
||||
const initial = props.defaultValue ?? "";
|
||||
const internal = ref(initial);
|
||||
field?.initialize(props.modelValue ?? initial);
|
||||
watch(
|
||||
() => (typeof attrs.id === "string" ? attrs.id : undefined),
|
||||
(id) => field?.setControlId(id),
|
||||
{ immediate: true },
|
||||
);
|
||||
const value = computed(
|
||||
() => props.modelValue ?? field?.value.value ?? internal.value,
|
||||
);
|
||||
const attrBoolean = (value: unknown) => value != null && value !== false;
|
||||
const disabled = () =>
|
||||
attrBoolean(attrs.disabled) || Boolean(field?.disabled.value);
|
||||
const readOnly = () =>
|
||||
attrBoolean(attrs.readonly ?? attrs.readOnly) ||
|
||||
Boolean(field?.readOnly.value);
|
||||
const required = () =>
|
||||
behavior() !== "aria" &&
|
||||
!readOnly() &&
|
||||
(attrBoolean(attrs.required) || Boolean(field?.required.value));
|
||||
const invalid = () =>
|
||||
Boolean(
|
||||
props.invalid ||
|
||||
field?.invalid.value ||
|
||||
attrs["aria-invalid"] === true ||
|
||||
attrs["aria-invalid"] === "true",
|
||||
);
|
||||
const variant = computed(() => props.variant ?? field?.variant.value);
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(next) => {
|
||||
if (next !== undefined) field?.syncValue(next);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
watch(element, (next) => field?.setControl(next), { flush: "post" });
|
||||
function update(event: Event) {
|
||||
const next = (event.target as HTMLInputElement).value;
|
||||
if (!disabled() && !readOnly()) {
|
||||
internal.value = next;
|
||||
field?.setValue(next);
|
||||
emit("update:modelValue", next);
|
||||
}
|
||||
void nextTick(() => {
|
||||
if (element.value) {
|
||||
element.value.value = value.value;
|
||||
if (props.modelValue !== undefined) field?.syncValue(value.value);
|
||||
}
|
||||
});
|
||||
}
|
||||
function reset(event: Event) {
|
||||
void nextTick(() => {
|
||||
if (event.defaultPrevented) return;
|
||||
internal.value = initial;
|
||||
field?.onReset();
|
||||
if (props.modelValue !== undefined) field?.syncValue(props.modelValue);
|
||||
if (element.value) element.value.value = value.value;
|
||||
});
|
||||
}
|
||||
let form: HTMLFormElement | null = null;
|
||||
function bindForm() {
|
||||
const next = element.value?.form ?? null;
|
||||
if (next === form) return;
|
||||
form?.removeEventListener("reset", reset);
|
||||
form = next;
|
||||
form?.addEventListener("reset", reset);
|
||||
}
|
||||
onMounted(bindForm);
|
||||
onUpdated(bindForm);
|
||||
onBeforeUnmount(() => {
|
||||
form?.removeEventListener("reset", reset);
|
||||
field?.setControl(undefined);
|
||||
});
|
||||
return {
|
||||
inheritedAttrs: () => field?.controlAttrs() ?? {},
|
||||
element,
|
||||
value,
|
||||
update,
|
||||
variant,
|
||||
invalid,
|
||||
disabled,
|
||||
readOnly,
|
||||
required,
|
||||
id: () =>
|
||||
typeof attrs.id === "string" ? attrs.id : field?.controlId.value,
|
||||
name: () =>
|
||||
typeof attrs.name === "string" ? attrs.name : field?.name.value,
|
||||
type: () => props.type ?? field?.type.value ?? "text",
|
||||
describedBy: () =>
|
||||
mergeIds(
|
||||
attrs["aria-describedby"] as string | undefined,
|
||||
field?.describedBy(),
|
||||
),
|
||||
onInvalid: (event: Event) => field?.onInvalid(event),
|
||||
validationBehavior: behavior,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, provide, ref, useAttrs } from "vue";
|
||||
import {
|
||||
formContextKey,
|
||||
type ValidationBehavior,
|
||||
type ValidationErrors,
|
||||
} from "../field/context";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
validationBehavior?: ValidationBehavior;
|
||||
validationErrors?: ValidationErrors;
|
||||
}>(),
|
||||
{ validationBehavior: "native", validationErrors: () => ({}) },
|
||||
);
|
||||
const attrs = useAttrs();
|
||||
provide(formContextKey, {
|
||||
validationBehavior: computed(() => props.validationBehavior),
|
||||
validationErrors: computed(() => props.validationErrors),
|
||||
});
|
||||
const element = ref<HTMLFormElement>();
|
||||
function checkValidity(report = false) {
|
||||
let first:
|
||||
HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | undefined;
|
||||
for (const control of Array.from(element.value?.elements ?? [])) {
|
||||
if (
|
||||
!("checkValidity" in control) ||
|
||||
(control.getAttribute("data-validation-behavior") ??
|
||||
props.validationBehavior) === "aria"
|
||||
)
|
||||
continue;
|
||||
const field = control as
|
||||
HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
|
||||
if (!field.checkValidity() && !first) first = field;
|
||||
}
|
||||
if (report && first) {
|
||||
first.focus();
|
||||
first.reportValidity();
|
||||
}
|
||||
return !first;
|
||||
}
|
||||
function submit(event: Event) {
|
||||
const submitter = (event as SubmitEvent).submitter as
|
||||
HTMLButtonElement | HTMLInputElement | null;
|
||||
const skip =
|
||||
attrs.novalidate === "" ||
|
||||
attrs.novalidate === true ||
|
||||
attrs.noValidate === true;
|
||||
if (!skip && !submitter?.formNoValidate && !checkValidity(true)) {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
}
|
||||
}
|
||||
// Native auto-validation is disabled so per-field aria/native modes can coexist.
|
||||
// The submit guard still uses each native control's Constraint Validation API.
|
||||
defineExpose({
|
||||
element,
|
||||
checkValidity: () => checkValidity(),
|
||||
reportValidity: () => checkValidity(true),
|
||||
reset: () => element.value?.reset(),
|
||||
});
|
||||
</script>
|
||||
<template>
|
||||
<form ref="element" @submit.capture="submit" v-bind="attrs" novalidate>
|
||||
<slot />
|
||||
</form>
|
||||
</template>
|
||||
@@ -1,13 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { useAttrs } from "vue";
|
||||
import { inputVariants, type InputVariants } from "@heroui-vue/styles";
|
||||
import {
|
||||
computed,
|
||||
ref,
|
||||
onMounted,
|
||||
onBeforeUnmount,
|
||||
nextTick,
|
||||
useAttrs,
|
||||
} from "vue";
|
||||
import { useTextControl } from "../field/useTextControl";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const props = defineProps<{
|
||||
modelValue?: string;
|
||||
@@ -17,57 +11,31 @@ const props = defineProps<{
|
||||
fullWidth?: boolean;
|
||||
type?: string;
|
||||
}>();
|
||||
const attrs = useAttrs();
|
||||
const invalidState = computed(
|
||||
() =>
|
||||
props.invalid ||
|
||||
attrs["aria-invalid"] === true ||
|
||||
attrs["aria-invalid"] === "true",
|
||||
);
|
||||
const emit = defineEmits<{ "update:modelValue": [value: string] }>();
|
||||
const internal = ref(props.defaultValue ?? "");
|
||||
const value = computed(() => props.modelValue ?? internal.value);
|
||||
const element = ref<HTMLInputElement>();
|
||||
function update(event: Event) {
|
||||
const next = (event.target as HTMLInputElement).value;
|
||||
internal.value = next;
|
||||
emit("update:modelValue", next);
|
||||
void nextTick(() => {
|
||||
if (element.value && element.value.value !== value.value)
|
||||
element.value.value = value.value;
|
||||
});
|
||||
}
|
||||
function reset(event: Event) {
|
||||
void nextTick(() => {
|
||||
if (event.defaultPrevented) return;
|
||||
internal.value = props.defaultValue ?? "";
|
||||
if (element.value) element.value.value = value.value;
|
||||
});
|
||||
}
|
||||
let form: HTMLFormElement | null = null;
|
||||
onMounted(() => {
|
||||
form = element.value?.form ?? null;
|
||||
form?.addEventListener("reset", reset);
|
||||
});
|
||||
onBeforeUnmount(() => form?.removeEventListener("reset", reset));
|
||||
const attrs = useAttrs();
|
||||
const control = useTextControl(props, attrs, emit);
|
||||
const { element, value, variant } = control;
|
||||
defineExpose({ focus: () => element.value?.focus(), element });
|
||||
</script>
|
||||
<template>
|
||||
<input
|
||||
ref="element"
|
||||
v-bind="$attrs"
|
||||
v-bind="{ ...control.inheritedAttrs(), ...attrs }"
|
||||
:value="value"
|
||||
:id="control.id()"
|
||||
:name="control.name()"
|
||||
:type="control.type()"
|
||||
:disabled="control.disabled()"
|
||||
:readonly="control.readOnly()"
|
||||
:required="control.required()"
|
||||
:class="inputVariants({ variant, fullWidth })"
|
||||
:type="type ?? 'text'"
|
||||
:data-invalid="invalidState || undefined"
|
||||
:aria-invalid="invalidState || undefined"
|
||||
:aria-readonly="
|
||||
$attrs.readonly === '' ||
|
||||
$attrs.readonly === true ||
|
||||
$attrs.readOnly === true ||
|
||||
undefined
|
||||
"
|
||||
:data-invalid="control.invalid() || undefined"
|
||||
:aria-invalid="control.invalid() || undefined"
|
||||
:aria-readonly="control.readOnly() || undefined"
|
||||
:aria-describedby="control.describedBy()"
|
||||
:data-validation-behavior="control.validationBehavior()"
|
||||
data-slot="input"
|
||||
@input="update"
|
||||
@input="control.update"
|
||||
@invalid="control.onInvalid"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { inject, useAttrs } from "vue";
|
||||
import { switchKey } from "../switch/context";
|
||||
const ctx = inject(switchKey, undefined);
|
||||
import { fieldContextKey } from "../field/context";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const field = inject(fieldContextKey, undefined);
|
||||
const attrs = useAttrs();
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
isRequired?: boolean;
|
||||
isDisabled?: boolean;
|
||||
isInvalid?: boolean;
|
||||
@@ -11,12 +12,16 @@ defineProps<{
|
||||
</script>
|
||||
<template>
|
||||
<component
|
||||
:is="ctx && !attrs.for ? 'span' : 'label'"
|
||||
:is="field?.kind === 'toggle' && !attrs.for ? 'span' : 'label'"
|
||||
v-bind="attrs"
|
||||
:for="
|
||||
attrs.for ?? (field?.kind === 'text' ? field.controlId.value : undefined)
|
||||
"
|
||||
class="hv-label"
|
||||
:class="{
|
||||
'hv-label--required': isRequired,
|
||||
'hv-label--disabled': isDisabled,
|
||||
'hv-label--invalid': isInvalid,
|
||||
'hv-label--required': props.isRequired || field?.required.value,
|
||||
'hv-label--disabled': props.isDisabled || field?.disabled.value,
|
||||
'hv-label--invalid': props.isInvalid || field?.invalid.value,
|
||||
}"
|
||||
data-slot="label"
|
||||
>
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { inject, onBeforeUnmount, useId } from "vue";
|
||||
import { switchKey } from "./context";
|
||||
const ctx = inject(switchKey, undefined);
|
||||
const id = useId();
|
||||
if (ctx) ctx.errorIds.value = [...ctx.errorIds.value, id];
|
||||
onBeforeUnmount(() => {
|
||||
if (ctx)
|
||||
ctx.errorIds.value = ctx.errorIds.value.filter((value) => value !== id);
|
||||
});
|
||||
</script>
|
||||
<template>
|
||||
<p
|
||||
v-if="!ctx || ctx.invalid.value"
|
||||
:id="id"
|
||||
data-slot="field-error"
|
||||
class="hv-field-error"
|
||||
role="alert"
|
||||
>
|
||||
<slot :validation-errors="ctx?.error.value ? [ctx.error.value] : []">
|
||||
{{ ctx?.error.value }}
|
||||
</slot>
|
||||
</p>
|
||||
</template>
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
computed,
|
||||
inject,
|
||||
provide,
|
||||
ref,
|
||||
useId,
|
||||
@@ -14,6 +15,11 @@ import {
|
||||
import { switchVariants, type SwitchVariants } from "@heroui-vue/styles";
|
||||
import { Primitive } from "reka-ui";
|
||||
import { switchKey } from "./context";
|
||||
import {
|
||||
fieldContextKey,
|
||||
formContextKey,
|
||||
errorMessages,
|
||||
} from "../field/context";
|
||||
import SwitchContent from "./SwitchContent.vue";
|
||||
import SwitchControl from "./SwitchControl.vue";
|
||||
import SwitchThumb from "./SwitchThumb.vue";
|
||||
@@ -51,6 +57,13 @@ const emit = defineEmits<{
|
||||
change: [value: boolean];
|
||||
}>();
|
||||
const attrs = useAttrs();
|
||||
const formContext = inject(formContextKey, undefined);
|
||||
const validationMode = computed(
|
||||
() =>
|
||||
props.validationBehavior ??
|
||||
formContext?.validationBehavior.value ??
|
||||
"native",
|
||||
);
|
||||
const rootAttrs = () =>
|
||||
Object.fromEntries(
|
||||
Object.entries(attrs).filter(
|
||||
@@ -74,6 +87,13 @@ const hovered = ref(false),
|
||||
focusVisible = ref(false);
|
||||
const error = ref("");
|
||||
const showError = ref(false);
|
||||
const dismissedErrors = ref<object>();
|
||||
const serverMessages = computed(() => {
|
||||
const source = formContext?.validationErrors.value;
|
||||
return source && source !== dismissedErrors.value && props.name
|
||||
? errorMessages(source[props.name])
|
||||
: [];
|
||||
});
|
||||
const checked = computed(
|
||||
() => props.isSelected ?? props.checked ?? internal.value,
|
||||
);
|
||||
@@ -88,6 +108,7 @@ const descriptionIds = ref<string[]>([]);
|
||||
const errorIds = ref<string[]>([]);
|
||||
function update(value: boolean) {
|
||||
if (disabled.value || readOnly.value) return;
|
||||
dismissedErrors.value = formContext?.validationErrors.value;
|
||||
internal.value = value;
|
||||
emit("update:checked", value);
|
||||
emit("update:isSelected", value);
|
||||
@@ -97,6 +118,17 @@ watch([disabled, readOnly], () => {
|
||||
hovered.value = false;
|
||||
pressed.value = false;
|
||||
});
|
||||
provide(fieldContextKey, {
|
||||
controlId: computed(() => props.id ?? generated),
|
||||
kind: "toggle",
|
||||
disabled,
|
||||
readOnly,
|
||||
required,
|
||||
invalid,
|
||||
errors: computed(() => (error.value ? [error.value] : [])),
|
||||
descriptionIds,
|
||||
errorIds,
|
||||
});
|
||||
provide(switchKey, {
|
||||
hovered,
|
||||
pressed,
|
||||
@@ -114,7 +146,9 @@ provide(switchKey, {
|
||||
update,
|
||||
});
|
||||
watchEffect(() => {
|
||||
const result = props.validate?.(checked.value);
|
||||
const result = serverMessages.value.length
|
||||
? serverMessages.value
|
||||
: props.validate?.(checked.value);
|
||||
error.value =
|
||||
typeof result === "string"
|
||||
? result
|
||||
@@ -123,9 +157,10 @@ watchEffect(() => {
|
||||
: required.value && !checked.value
|
||||
? "请开启此选项。"
|
||||
: "";
|
||||
if (props.validationBehavior === "aria") showError.value = true;
|
||||
if (validationMode.value === "aria" || serverMessages.value.length)
|
||||
showError.value = true;
|
||||
input.value?.setCustomValidity(
|
||||
props.validationBehavior === "aria" || disabled.value || readOnly.value
|
||||
validationMode.value === "aria" || disabled.value || readOnly.value
|
||||
? ""
|
||||
: error.value,
|
||||
);
|
||||
@@ -138,6 +173,7 @@ function onInvalid(event: Event) {
|
||||
function reset(event: Event) {
|
||||
void nextTick(() => {
|
||||
if (event.defaultPrevented) return;
|
||||
dismissedErrors.value = formContext?.validationErrors.value;
|
||||
internal.value = initial;
|
||||
showError.value = false;
|
||||
if (input.value) input.value.checked = checked.value;
|
||||
@@ -188,13 +224,14 @@ defineExpose({
|
||||
ref="input"
|
||||
class="hv-switch__input"
|
||||
type="checkbox"
|
||||
:data-validation-behavior="validationMode"
|
||||
tabindex="-1"
|
||||
aria-hidden="true"
|
||||
:name="name"
|
||||
:value="value ?? 'on'"
|
||||
:checked="checked"
|
||||
:disabled="disabled"
|
||||
:required="required && !readOnly && validationBehavior !== 'aria'"
|
||||
:required="required && !readOnly && validationMode !== 'aria'"
|
||||
@invalid="onInvalid"
|
||||
@change="update(($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
|
||||
@@ -1,16 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
computed,
|
||||
ref,
|
||||
onMounted,
|
||||
onBeforeUnmount,
|
||||
nextTick,
|
||||
useAttrs,
|
||||
} from "vue";
|
||||
import { useAttrs } from "vue";
|
||||
import { textAreaVariants, type TextAreaVariants } from "@heroui-vue/styles";
|
||||
|
||||
import { useTextControl } from "../field/useTextControl";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue?: string;
|
||||
defaultValue?: string;
|
||||
@@ -18,62 +10,30 @@ const props = defineProps<{
|
||||
variant?: TextAreaVariants["variant"];
|
||||
fullWidth?: boolean;
|
||||
}>();
|
||||
|
||||
const attrs = useAttrs();
|
||||
const invalidState = computed(
|
||||
() =>
|
||||
props.invalid ||
|
||||
attrs["aria-invalid"] === true ||
|
||||
attrs["aria-invalid"] === "true",
|
||||
);
|
||||
const emit = defineEmits<{ "update:modelValue": [value: string] }>();
|
||||
const internal = ref(props.defaultValue ?? "");
|
||||
const value = computed(() => props.modelValue ?? internal.value);
|
||||
const element = ref<HTMLTextAreaElement>();
|
||||
|
||||
function update(event: Event) {
|
||||
const next = (event.target as HTMLTextAreaElement).value;
|
||||
internal.value = next;
|
||||
emit("update:modelValue", next);
|
||||
void nextTick(() => {
|
||||
if (element.value && element.value.value !== value.value)
|
||||
element.value.value = value.value;
|
||||
});
|
||||
}
|
||||
|
||||
function reset(event: Event) {
|
||||
void nextTick(() => {
|
||||
if (event.defaultPrevented) return;
|
||||
internal.value = props.defaultValue ?? "";
|
||||
if (element.value) element.value.value = value.value;
|
||||
});
|
||||
}
|
||||
|
||||
let form: HTMLFormElement | null = null;
|
||||
onMounted(() => {
|
||||
form = element.value?.form ?? null;
|
||||
form?.addEventListener("reset", reset);
|
||||
});
|
||||
onBeforeUnmount(() => form?.removeEventListener("reset", reset));
|
||||
|
||||
const attrs = useAttrs();
|
||||
const control = useTextControl(props, attrs, emit);
|
||||
const { element, value, variant } = control;
|
||||
defineExpose({ focus: () => element.value?.focus(), element });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<textarea
|
||||
ref="element"
|
||||
v-bind="$attrs"
|
||||
v-bind="{ ...control.inheritedAttrs(), ...attrs }"
|
||||
:value="value"
|
||||
:id="control.id()"
|
||||
:name="control.name()"
|
||||
:disabled="control.disabled()"
|
||||
:readonly="control.readOnly()"
|
||||
:required="control.required()"
|
||||
:class="textAreaVariants({ variant, fullWidth })"
|
||||
:data-invalid="invalidState || undefined"
|
||||
:aria-invalid="invalidState || undefined"
|
||||
:aria-readonly="
|
||||
$attrs.readonly === '' ||
|
||||
$attrs.readonly === true ||
|
||||
$attrs.readOnly === true ||
|
||||
undefined
|
||||
"
|
||||
:data-invalid="control.invalid() || undefined"
|
||||
:aria-invalid="control.invalid() || undefined"
|
||||
:aria-readonly="control.readOnly() || undefined"
|
||||
:aria-describedby="control.describedBy()"
|
||||
:data-validation-behavior="control.validationBehavior()"
|
||||
data-slot="textarea"
|
||||
@input="update"
|
||||
@input="control.update"
|
||||
@invalid="control.onInvalid"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Comment,
|
||||
Fragment,
|
||||
cloneVNode,
|
||||
computed,
|
||||
defineComponent,
|
||||
h,
|
||||
inject,
|
||||
isVNode,
|
||||
provide,
|
||||
ref,
|
||||
shallowRef,
|
||||
useId,
|
||||
watchEffect,
|
||||
type PropType,
|
||||
type VNode,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import {
|
||||
fieldContextKey,
|
||||
formContextKey,
|
||||
errorMessages,
|
||||
mergeIds,
|
||||
type ValidateResult,
|
||||
type ValidationBehavior,
|
||||
} from "../field/context";
|
||||
import { textFieldContextKey, type TextFieldContext } from "./context";
|
||||
|
||||
export default defineComponent({
|
||||
name: "TextField",
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
modelValue: String,
|
||||
defaultValue: String,
|
||||
name: String,
|
||||
id: String,
|
||||
type: String,
|
||||
minLength: Number,
|
||||
maxLength: Number,
|
||||
pattern: String,
|
||||
autoComplete: String,
|
||||
inputMode: String,
|
||||
form: String,
|
||||
isDisabled: Boolean,
|
||||
isReadOnly: Boolean,
|
||||
isRequired: Boolean,
|
||||
isInvalid: Boolean,
|
||||
fullWidth: Boolean,
|
||||
variant: String as PropType<"primary" | "secondary">,
|
||||
validationBehavior: String as PropType<ValidationBehavior>,
|
||||
validate: Function as PropType<(value: string) => ValidateResult>,
|
||||
},
|
||||
emits: { "update:modelValue": (_value: string) => true },
|
||||
setup(props, { attrs, slots, emit, expose }) {
|
||||
const form = inject(formContextKey, undefined);
|
||||
const generated = useId();
|
||||
const leafId = ref<string>();
|
||||
const controlId = computed(() => leafId.value ?? props.id ?? generated);
|
||||
const internal = ref(props.defaultValue ?? "");
|
||||
let initialized =
|
||||
props.modelValue !== undefined || props.defaultValue !== undefined;
|
||||
let initialValue = props.defaultValue ?? "";
|
||||
const value = computed(() => props.modelValue ?? internal.value);
|
||||
const control = shallowRef<HTMLInputElement | HTMLTextAreaElement>();
|
||||
const touched = ref(false),
|
||||
nativeError = ref("");
|
||||
const dismissed = shallowRef<object>();
|
||||
const descriptionIds = ref<string[]>([]),
|
||||
errorIds = ref<string[]>([]);
|
||||
// Pre-plan direct/native-wrapped parts before rendering controls, so SSR has
|
||||
// complete ID associations even when Description follows Input.
|
||||
const plannedDescriptions = ref<string[]>([]),
|
||||
plannedErrors = ref<string[]>([]);
|
||||
let lastPlan = "";
|
||||
const behavior = computed(
|
||||
() =>
|
||||
props.validationBehavior ?? form?.validationBehavior.value ?? "native",
|
||||
);
|
||||
const disabled = computed(() => props.isDisabled),
|
||||
readOnly = computed(() => props.isReadOnly);
|
||||
const required = computed(() => props.isRequired);
|
||||
const serverErrors = computed(() => {
|
||||
const source = form?.validationErrors.value;
|
||||
return source && source !== dismissed.value && props.name
|
||||
? errorMessages(source[props.name])
|
||||
: [];
|
||||
});
|
||||
const customErrors = computed(() =>
|
||||
errorMessages(props.validate?.(value.value)),
|
||||
);
|
||||
const errors = computed(() => [
|
||||
...serverErrors.value,
|
||||
...(touched.value || behavior.value === "aria" ? customErrors.value : []),
|
||||
...((touched.value || behavior.value === "aria") && nativeError.value
|
||||
? [nativeError.value]
|
||||
: []),
|
||||
]);
|
||||
const invalid = computed(
|
||||
() =>
|
||||
props.isInvalid ||
|
||||
attrs["aria-invalid"] === true ||
|
||||
attrs["aria-invalid"] === "true" ||
|
||||
errors.value.length > 0,
|
||||
);
|
||||
function setValue(next: string) {
|
||||
if (disabled.value || readOnly.value) return;
|
||||
internal.value = next;
|
||||
dismissed.value = form?.validationErrors.value;
|
||||
nativeError.value = "";
|
||||
emit("update:modelValue", next);
|
||||
}
|
||||
function initialize(next: string) {
|
||||
if (!initialized) {
|
||||
internal.value = next;
|
||||
initialValue = next;
|
||||
initialized = true;
|
||||
}
|
||||
}
|
||||
const field: TextFieldContext = {
|
||||
controlId,
|
||||
kind: "text",
|
||||
disabled,
|
||||
readOnly,
|
||||
required,
|
||||
invalid,
|
||||
errors,
|
||||
descriptionIds,
|
||||
errorIds,
|
||||
value,
|
||||
name: computed(() => props.name),
|
||||
type: computed(() => props.type),
|
||||
variant: computed(() => props.variant),
|
||||
validationBehavior: behavior,
|
||||
controlAttrs: () => ({
|
||||
minlength: props.minLength,
|
||||
maxlength: props.maxLength,
|
||||
pattern: props.pattern,
|
||||
autocomplete: props.autoComplete,
|
||||
inputmode: props.inputMode,
|
||||
form: props.form,
|
||||
...Object.fromEntries(
|
||||
Object.entries(attrs).filter(([key]) => key.startsWith("aria-")),
|
||||
),
|
||||
}),
|
||||
describedBy: () =>
|
||||
mergeIds(
|
||||
attrs["aria-describedby"] as string | undefined,
|
||||
descriptionIds.value,
|
||||
plannedDescriptions.value,
|
||||
invalid.value ? [...errorIds.value, ...plannedErrors.value] : [],
|
||||
),
|
||||
setControlId: (id) => {
|
||||
leafId.value = id;
|
||||
},
|
||||
initialize,
|
||||
setValue,
|
||||
syncValue: (next) => {
|
||||
internal.value = next;
|
||||
},
|
||||
setControl: (next) => {
|
||||
control.value = next;
|
||||
},
|
||||
onInvalid(event) {
|
||||
if (behavior.value === "aria") return;
|
||||
touched.value = true;
|
||||
const element = event.target as HTMLInputElement | HTMLTextAreaElement;
|
||||
nativeError.value =
|
||||
customErrors.value.length || serverErrors.value.length
|
||||
? ""
|
||||
: element.validationMessage;
|
||||
},
|
||||
onReset() {
|
||||
internal.value = initialValue;
|
||||
touched.value = false;
|
||||
nativeError.value = "";
|
||||
dismissed.value = form?.validationErrors.value;
|
||||
},
|
||||
};
|
||||
provide(fieldContextKey, field);
|
||||
provide(textFieldContextKey, field);
|
||||
watchEffect(
|
||||
() => {
|
||||
const currentValue = value.value;
|
||||
control.value?.setCustomValidity(
|
||||
behavior.value === "native" && !disabled.value && !readOnly.value
|
||||
? [...serverErrors.value, ...customErrors.value].join(" ")
|
||||
: "",
|
||||
);
|
||||
if (behavior.value === "native" && touched.value)
|
||||
nativeError.value =
|
||||
customErrors.value.length || serverErrors.value.length
|
||||
? ""
|
||||
: (control.value?.validationMessage ?? "");
|
||||
if (behavior.value === "aria")
|
||||
nativeError.value =
|
||||
disabled.value || readOnly.value
|
||||
? ""
|
||||
: required.value && !currentValue
|
||||
? "请填写此字段。"
|
||||
: (control.value?.validationMessage ?? "");
|
||||
},
|
||||
{ flush: "post" },
|
||||
);
|
||||
expose({ focus: () => control.value?.focus(), element: control });
|
||||
function prepare(
|
||||
nodes: VNodeChild[],
|
||||
found: { description: string[]; error: string[]; controlId?: string },
|
||||
path = "",
|
||||
): VNodeChild[] {
|
||||
return nodes.map((node, index) => {
|
||||
if (!isVNode(node) || node.type === Comment) return node;
|
||||
const position = `${path}-${index}`;
|
||||
const type = node.type as { name?: string; __name?: string };
|
||||
const name = type?.name ?? type?.__name;
|
||||
if (name === "Input" || name === "TextArea")
|
||||
found.controlId = node.props?.id;
|
||||
if (name === "Description" || name === "FieldError") {
|
||||
const kind = name === "Description" ? "description" : "error";
|
||||
const id = node.props?.id ?? `${generated}-${kind}${position}`;
|
||||
found[kind].push(String(id));
|
||||
return cloneVNode(node, { id });
|
||||
}
|
||||
if (
|
||||
(typeof node.type === "string" || node.type === Fragment) &&
|
||||
Array.isArray(node.children)
|
||||
) {
|
||||
const clone = cloneVNode(node);
|
||||
clone.children = prepare(
|
||||
node.children as VNodeChild[],
|
||||
found,
|
||||
position,
|
||||
) as VNode[];
|
||||
return clone;
|
||||
}
|
||||
return node;
|
||||
});
|
||||
}
|
||||
return () => {
|
||||
const found: {
|
||||
description: string[];
|
||||
error: string[];
|
||||
controlId?: string;
|
||||
} = { description: [], error: [] };
|
||||
const children = prepare(
|
||||
slots.default?.({
|
||||
isDisabled: disabled.value,
|
||||
isReadOnly: readOnly.value,
|
||||
isRequired: required.value,
|
||||
isInvalid: invalid.value,
|
||||
validationErrors: errors.value,
|
||||
}) ?? [],
|
||||
found,
|
||||
);
|
||||
if (found.controlId !== undefined && leafId.value !== found.controlId)
|
||||
leafId.value = found.controlId;
|
||||
const nextPlan = JSON.stringify(found);
|
||||
if (lastPlan !== nextPlan) {
|
||||
lastPlan = nextPlan;
|
||||
plannedDescriptions.value = found.description;
|
||||
plannedErrors.value = found.error;
|
||||
}
|
||||
return h(
|
||||
"div",
|
||||
{
|
||||
...Object.fromEntries(
|
||||
Object.entries(attrs).filter(([key]) => !key.startsWith("aria-")),
|
||||
),
|
||||
class: [
|
||||
"hv-textfield",
|
||||
props.fullWidth && "hv-textfield--full-width",
|
||||
attrs.class,
|
||||
],
|
||||
"data-slot": "textfield",
|
||||
"data-invalid": invalid.value || undefined,
|
||||
"data-disabled": disabled.value || undefined,
|
||||
"data-required": required.value || undefined,
|
||||
"data-readonly": readOnly.value || undefined,
|
||||
},
|
||||
children,
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { ComputedRef, InjectionKey } from "vue";
|
||||
import type { FieldContext, ValidationBehavior } from "../field/context";
|
||||
export interface TextFieldContext extends FieldContext {
|
||||
value: ComputedRef<string>;
|
||||
name: ComputedRef<string | undefined>;
|
||||
type: ComputedRef<string | undefined>;
|
||||
variant: ComputedRef<"primary" | "secondary" | undefined>;
|
||||
validationBehavior: ComputedRef<ValidationBehavior>;
|
||||
controlAttrs: () => Record<string, unknown>;
|
||||
describedBy: () => string | undefined;
|
||||
setControlId: (id: string | undefined) => void;
|
||||
initialize: (value: string) => void;
|
||||
setValue: (value: string) => void;
|
||||
syncValue: (value: string) => void;
|
||||
setControl: (
|
||||
control: HTMLInputElement | HTMLTextAreaElement | undefined,
|
||||
) => void;
|
||||
onInvalid: (event: Event) => void;
|
||||
onReset: () => void;
|
||||
}
|
||||
export const textFieldContextKey: InjectionKey<TextFieldContext> = Symbol(
|
||||
"HeroUIVue.TextField",
|
||||
);
|
||||
Reference in New Issue
Block a user