feat: add Fieldset and SearchField infrastructure

This commit is contained in:
maoyingjie
2026-10-22 08:46:02 +08:00
parent 116056832c
commit a4fb3c550a
59 changed files with 3131 additions and 331 deletions
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { useInheritedDisabled } from "../field/disabled";
import { computed, ref, watch } from "vue";
import { Primitive } from "reka-ui";
import type { ButtonHTMLAttributes } from "vue";
@@ -21,7 +22,7 @@ const props = withDefaults(
{ type: "button" },
);
const pending = computed(() => props.isPending || props.loading);
const disabled = computed(() => props.isDisabled || props.disabled);
const disabled = useInheritedDisabled(() => props.isDisabled || props.disabled);
const hovered = ref(false),
pressed = ref(false),
focused = ref(false),
@@ -37,7 +38,7 @@ watch(
{ flush: "sync" },
);
function guard(e: MouseEvent) {
if (pending.value) {
if (pending.value || disabled.value) {
e.preventDefault();
e.stopImmediatePropagation();
}
@@ -49,6 +50,7 @@ function focus(e: FocusEvent) {
</script>
<template>
<Primitive
@click.capture="guard"
as="button"
:as-child="asChild"
v-bind="$attrs"
@@ -63,7 +65,6 @@ function focus(e: FocusEvent) {
:data-focused="focused || undefined"
:data-focus-visible="focusVisible || undefined"
data-slot="button"
@click.capture="guard"
@pointerenter="hovered = !pending && !disabled"
@pointerleave="
hovered = false;
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { useInheritedDisabled } from "../field/disabled";
import { computed, ref, useAttrs, watch } from "vue";
import {
closeButtonVariants,
@@ -17,7 +18,7 @@ const props = withDefaults(
);
const attrs = useAttrs();
const disabled = computed(() => props.isDisabled || props.disabled);
const disabled = useInheritedDisabled(() => props.isDisabled || props.disabled);
const ariaLabel = computed(() =>
typeof attrs["aria-label"] === "string" ? attrs["aria-label"] : "Close",
);
@@ -62,6 +63,8 @@ function focus(e: FocusEvent) {
<template>
<button
@click.capture="guard"
@keydown.capture="onKeydownGuard"
v-bind="attrs"
:type="'button'"
:class="closeButtonVariants({ variant })"
@@ -72,9 +75,7 @@ function focus(e: FocusEvent) {
:data-pressed="(!disabled && pressed) || undefined"
:data-focused="focused || undefined"
:data-focus-visible="focusVisible || undefined"
data-slot="close-button"
@click.capture="guard"
@keydown.capture="onKeydownGuard"
:data-slot="attrs['data-slot'] ?? 'close-button'"
@pointerenter="hovered = !disabled"
@pointerleave="
hovered = false;
@@ -0,0 +1,9 @@
import { computed, inject, type ComputedRef, type InjectionKey } from "vue";
/** Semantic disabled scope, including controls with no native disabled attribute. */
export const disabledContextKey: InjectionKey<ComputedRef<boolean>> =
Symbol("HeroUIVue.Disabled");
export function useInheritedDisabled(local: () => unknown = () => false) {
const parent = inject(disabledContextKey, undefined);
return computed(() => Boolean(local() || parent?.value));
}
@@ -8,6 +8,7 @@ import {
ref,
watch,
} from "vue";
import { useInheritedDisabled } from "./disabled";
import { mergeIds, formContextKey } from "./context";
import { textFieldContextKey } from "../textfield/context";
@@ -41,8 +42,11 @@ export function useTextControl(
() => props.modelValue ?? field?.value.value ?? internal.value,
);
const attrBoolean = (value: unknown) => value != null && value !== false;
const inheritedDisabled = useInheritedDisabled();
const disabled = () =>
attrBoolean(attrs.disabled) || Boolean(field?.disabled.value);
inheritedDisabled.value ||
attrBoolean(attrs.disabled) ||
Boolean(field?.disabled.value);
const readOnly = () =>
attrBoolean(attrs.readonly ?? attrs.readOnly) ||
Boolean(field?.readOnly.value);
@@ -97,7 +101,10 @@ export function useTextControl(
form = next;
form?.addEventListener("reset", reset);
}
onMounted(bindForm);
onMounted(() => {
field?.setControl(element.value);
bindForm();
});
onUpdated(bindForm);
onBeforeUnmount(() => {
form?.removeEventListener("reset", reset);
@@ -0,0 +1,346 @@
import {
Comment,
Fragment,
cloneVNode,
computed,
h,
mergeProps,
inject,
isVNode,
provide,
ref,
shallowRef,
useId,
watchEffect,
type PropType,
type ExtractPropTypes,
type Slots,
type VNode,
type VNodeChild,
} from "vue";
import {
fieldContextKey,
formContextKey,
errorMessages,
mergeIds,
type ValidateResult,
type ValidationBehavior,
} from "./context";
import {
textFieldContextKey,
type TextFieldContext,
} from "../textfield/context";
import { useInheritedDisabled } from "./disabled";
export const textFieldProps = {
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>,
} as const;
export function useTextField(
props: Readonly<ExtractPropTypes<typeof textFieldProps>>,
{
attrs,
slots,
emit,
expose,
}: {
attrs: Record<string, unknown>;
slots: Slots;
emit: (event: "update:modelValue", value: string) => void;
expose: (exposed: Record<string, unknown>) => void;
},
options: {
rootSlot?: string;
rootClass?: () => unknown;
rootAttrs?: () => Record<string, unknown>;
slotState?: () => Record<string, unknown>;
} = {},
) {
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 = useInheritedDisabled(() => props.isDisabled);
const 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;
controlValue?: string;
hasControl?: boolean;
},
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" ||
name === "InputGroupInput" ||
name === "InputGroupTextArea" ||
name === "SearchFieldInput"
) {
found.hasControl = true;
found.controlId = node.props?.id;
found.controlValue = node.props?.modelValue ?? node.props?.defaultValue;
}
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 });
}
// InputGroup is a library-owned transparent field wrapper. Prepare its
// default slot once, preserving the current render's values and keys.
// Arbitrary consumer components remain opaque to SSR planning.
if (
(name === "InputGroup" || name === "SearchFieldGroup") &&
node.children &&
typeof node.children === "object"
) {
const groupSlots = node.children as { default?: () => VNodeChild[] };
if (typeof groupSlots.default === "function") {
const prepared = prepare(groupSlots.default(), found, position);
const clone = cloneVNode(node);
clone.children = { ...groupSlots, default: () => prepared };
return clone;
}
}
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;
});
}
const render = () => {
const found: {
description: string[];
error: string[];
controlId?: string;
controlValue?: string;
hasControl?: boolean;
} = { description: [], error: [] };
const children = prepare(
slots.default?.({
isDisabled: disabled.value,
isReadOnly: readOnly.value,
isRequired: required.value,
isInvalid: invalid.value,
validationErrors: errors.value,
...options.slotState?.(),
}) ?? [],
found,
);
if (found.hasControl && leafId.value !== found.controlId)
leafId.value = found.controlId;
if (found.controlValue !== undefined) initialize(found.controlValue);
const nextPlan = JSON.stringify(found);
if (lastPlan !== nextPlan) {
lastPlan = nextPlan;
plannedDescriptions.value = found.description;
plannedErrors.value = found.error;
}
return h(
"div",
mergeProps(
{
...Object.fromEntries(
Object.entries(attrs).filter(([key]) => !key.startsWith("aria-")),
),
class: [
options.rootClass?.() ?? [
"hv-textfield",
props.fullWidth && "hv-textfield--full-width",
],
attrs.class,
],
"data-slot": options.rootSlot ?? "textfield",
"data-invalid": invalid.value || undefined,
"data-disabled": disabled.value || undefined,
"data-required": required.value || undefined,
"data-readonly": readOnly.value || undefined,
},
options.rootAttrs?.() ?? {},
),
children,
);
};
return { field, element: control, render };
}
@@ -0,0 +1,14 @@
<script setup lang="ts">
import { fieldsetVariants } from "@heroui-vue/styles";
defineOptions({ inheritAttrs: false });
const styles = fieldsetVariants();
</script>
<template>
<div
v-bind="$attrs"
:class="[styles.fieldGroup(), $attrs.class]"
data-slot="fieldset-field-group"
>
<slot />
</div>
</template>
@@ -0,0 +1,80 @@
<script lang="ts">
import {
computed,
defineComponent,
Fragment,
h,
inject,
isVNode,
provide,
type VNode,
type VNodeChild,
} from "vue";
import { fieldsetVariants } from "@heroui-vue/styles";
import { disabledContextKey } from "../field/disabled";
// A renderless scope preserves the native first direct legend exemption.
const LegendScope = defineComponent({
props: { disabled: Boolean },
setup(props, { slots }) {
provide(
disabledContextKey,
computed(() => props.disabled),
);
return () => slots.default?.();
},
});
export default defineComponent({
name: "Fieldset",
inheritAttrs: false,
props: { disabled: Boolean },
setup(props, { attrs, slots }) {
const parent = inject(disabledContextKey, undefined);
const disabled = computed(() => props.disabled || Boolean(parent?.value));
provide(disabledContextKey, disabled);
const styles = fieldsetVariants();
return () => {
let firstLegend = true;
function prepare(nodes: VNodeChild[]): VNodeChild[] {
return nodes.flatMap((node) => {
if (!isVNode(node)) return [node];
if (node.type === Fragment && Array.isArray(node.children))
return prepare(node.children as VNode[]);
const type = node.type as { name?: string; __name?: string };
if (
node.type === "legend" ||
(type.name ?? type.__name) === "FieldsetLegend"
) {
const legendDisabled = firstLegend
? Boolean(parent?.value)
: disabled.value;
firstLegend = false;
return [
h(
LegendScope,
{
key: node.key ?? undefined,
disabled: legendDisabled,
},
() => node,
),
];
}
return [node];
});
}
return h(
"fieldset",
{
...attrs,
disabled: props.disabled,
"data-disabled": disabled.value || undefined,
"data-slot": "fieldset",
class: [styles.base(), attrs.class],
},
prepare(slots.default?.() ?? []),
);
};
},
});
</script>
@@ -0,0 +1,14 @@
<script setup lang="ts">
import { fieldsetVariants } from "@heroui-vue/styles";
defineOptions({ inheritAttrs: false });
const styles = fieldsetVariants();
</script>
<template>
<div
v-bind="$attrs"
:class="[styles.actions(), $attrs.class]"
data-slot="fieldset-actions"
>
<slot />
</div>
</template>
@@ -0,0 +1,14 @@
<script setup lang="ts">
import { fieldsetVariants } from "@heroui-vue/styles";
defineOptions({ inheritAttrs: false });
const styles = fieldsetVariants();
</script>
<template>
<legend
v-bind="$attrs"
:class="[styles.legend(), $attrs.class]"
data-slot="fieldset-legend"
>
<slot />
</legend>
</template>
+5 -1
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { inject, useAttrs } from "vue";
import { useInheritedDisabled } from "../field/disabled";
import { fieldContextKey } from "../field/context";
defineOptions({ inheritAttrs: false });
const field = inject(fieldContextKey, undefined);
@@ -9,6 +10,9 @@ const props = defineProps<{
isDisabled?: boolean;
isInvalid?: boolean;
}>();
const disabled = useInheritedDisabled(
() => props.isDisabled || field?.disabled.value,
);
</script>
<template>
<component
@@ -20,7 +24,7 @@ const props = defineProps<{
class="hv-label"
:class="{
'hv-label--required': props.isRequired || field?.required.value,
'hv-label--disabled': props.isDisabled || field?.disabled.value,
'hv-label--disabled': disabled,
'hv-label--invalid': props.isInvalid || field?.invalid.value,
}"
data-slot="label"
+21 -11
View File
@@ -1,10 +1,12 @@
<script setup lang="ts">
import { useInheritedDisabled } from "../field/disabled";
import {
provide,
ref,
computed,
useAttrs,
onMounted,
watch,
onBeforeUnmount,
} from "vue";
import { Primitive } from "reka-ui";
@@ -30,6 +32,7 @@ const props = withDefaults(
},
);
const disabled = useInheritedDisabled(() => props.isDisabled);
const slots = linkVariants();
provide(linkContextKey, { slots });
@@ -39,6 +42,13 @@ const hovered = ref(false),
focused = ref(false),
focusVisible = ref(false);
watch(disabled, (value) => {
if (value) {
hovered.value = false;
pressed.value = false;
}
});
const element = ref<HTMLElement>();
function resolveElement(raw: unknown): HTMLElement | undefined {
@@ -110,7 +120,7 @@ function liveAttr(name: string): MaybeHandlers {
}
function guardClick(e: Event, parent: MaybeHandlers) {
if (props.isDisabled) {
if (disabled.value) {
e.preventDefault();
e.stopImmediatePropagation();
return;
@@ -121,7 +131,7 @@ function guardClick(e: Event, parent: MaybeHandlers) {
/** Disabled-only gate for key events that must not synthesize activation. */
function guardKeyPassthrough(e: Event, parent: MaybeHandlers) {
const ke = e as KeyboardEvent;
if (props.isDisabled && isActivationKey(ke)) {
if (disabled.value && isActivationKey(ke)) {
ke.preventDefault();
ke.stopImmediatePropagation();
return;
@@ -131,7 +141,7 @@ function guardKeyPassthrough(e: Event, parent: MaybeHandlers) {
function guardKeydownBubble(e: Event, parent: MaybeHandlers) {
const ke = e as KeyboardEvent;
if (props.isDisabled && isActivationKey(ke)) {
if (disabled.value && isActivationKey(ke)) {
ke.preventDefault();
ke.stopImmediatePropagation();
return;
@@ -139,7 +149,7 @@ function guardKeydownBubble(e: Event, parent: MaybeHandlers) {
callHandlers(parent, e);
if (
!props.asChild ||
props.isDisabled ||
disabled.value ||
!isEnterKey(ke) ||
ke.defaultPrevented ||
wasImmediateStopped(e)
@@ -254,19 +264,19 @@ defineExpose({
:download="downloadAttr"
:class="slots.base()"
:role="asChild ? 'link' : undefined"
:tabindex="asChild ? 0 : undefined"
:aria-disabled="isDisabled || undefined"
:data-hovered="(!isDisabled && hovered) || undefined"
:data-pressed="(!isDisabled && pressed) || undefined"
:tabindex="disabled ? -1 : asChild ? 0 : undefined"
:aria-disabled="disabled || undefined"
:data-hovered="(!disabled && hovered) || undefined"
:data-pressed="(!disabled && pressed) || undefined"
:data-focused="focused || undefined"
:data-focus-visible="focusVisible || undefined"
data-slot="link"
@pointerenter="hovered = !isDisabled"
@pointerenter="hovered = !disabled"
@pointerleave="
hovered = false;
pressed = false;
"
@pointerdown="pressed = !isDisabled"
@pointerdown="pressed = !disabled"
@pointerup="pressed = false"
@focus="focus"
@blur="
@@ -276,7 +286,7 @@ defineExpose({
"
>
<slot
:is-disabled="isDisabled"
:is-disabled="Boolean(disabled)"
:is-hovered="hovered"
:is-pressed="pressed"
:is-focused="focused"
@@ -0,0 +1,121 @@
<script lang="ts">
import {
computed,
defineComponent,
getCurrentInstance,
nextTick,
onMounted,
provide,
ref,
} from "vue";
import { searchFieldVariants } from "@heroui-vue/styles";
import { textFieldProps, useTextField } from "../field/useTextField";
import { searchFieldContextKey } from "./context";
export default defineComponent({
name: "SearchField",
inheritAttrs: false,
props: {
...textFieldProps,
type: { type: String, default: "search" },
autoFocus: Boolean,
},
emits: {
"update:modelValue": (_value: string) => true,
submit: (_value: string) => true,
clear: () => true,
},
setup(props, context) {
const instance = getCurrentInstance();
const hovered = ref(false),
focused = ref(false),
focusVisible = ref(false);
const slots = computed(() =>
searchFieldVariants({
variant: props.variant,
fullWidth: props.fullWidth,
}),
);
const { field, element, render } = useTextField(props, context, {
rootSlot: "search-field",
rootClass: () => slots.value.base(),
rootAttrs: () => ({
onKeydown: keydown,
"data-empty": !field.value.value || undefined,
"data-focus-within": focused.value || undefined,
"data-focus-visible": focusVisible.value || undefined,
"data-hovered": (!field.disabled.value && hovered.value) || undefined,
}),
slotState: () => ({
isEmpty: !field.value.value,
isHovered: !field.disabled.value && hovered.value,
isFocusWithin: focused.value,
isFocusVisible: focusVisible.value,
}),
});
function clear(event?: Event) {
const input = element.value;
if (
event?.defaultPrevented ||
!input ||
field.disabled.value ||
field.readOnly.value ||
!field.value.value
)
return;
// The native input path also updates an explicitly controlled leaf and
// restores rejected values through the same useTextControl adapter.
input.value = "";
input.dispatchEvent(new Event("input", { bubbles: true }));
context.emit("clear");
void nextTick(() => input.focus());
}
function keydown(event: KeyboardEvent) {
if (event.target !== element.value) return;
if (
event.defaultPrevented ||
event.isComposing ||
event.keyCode === 229 ||
event.repeat ||
field.disabled.value
)
return;
if (
event.key === "Escape" &&
!field.readOnly.value &&
field.value.value
) {
event.preventDefault();
clear();
} else if (
event.key === "Enter" &&
(instance?.vnode.props?.onSubmit || instance?.vnode.props?.onSubmitOnce)
) {
event.preventDefault();
if (
field.validationBehavior.value === "native" &&
element.value &&
!element.value.reportValidity()
)
return;
context.emit("submit", field.value.value);
}
// Without @submit, let the browser perform the enclosing form's normal
// implicit submission. Never synthesize a second form submission.
}
provide(searchFieldContextKey, {
field,
slots,
hovered,
focused,
focusVisible,
clear,
keydown,
});
onMounted(() => {
if (props.autoFocus && !field.disabled.value) element.value?.focus();
});
return render;
},
});
</script>
@@ -0,0 +1,45 @@
<script setup lang="ts">
import { inject } from "vue";
import {
searchFieldVariants,
type CloseButtonVariants,
} from "@heroui-vue/styles";
import CloseButton from "../close-button/CloseButton.vue";
import { searchFieldContextKey } from "./context";
defineOptions({ inheritAttrs: false });
defineProps<{
variant?: CloseButtonVariants["variant"];
isDisabled?: boolean;
disabled?: boolean;
}>();
const context = inject(searchFieldContextKey, undefined);
const fallback = searchFieldVariants();
</script>
<template>
<CloseButton
v-bind="$attrs"
:class="[
context?.slots.value.clearButton() ?? fallback.clearButton(),
$attrs.class,
]"
:variant="variant"
:is-disabled="
isDisabled ||
disabled ||
context?.field.disabled.value ||
context?.field.readOnly.value
"
:aria-label="$attrs['aria-label'] ?? 'Clear'"
:aria-hidden="!context?.field.value.value || undefined"
:tabindex="
!context?.field.value.value ? -1 : ($attrs.tabindex as number | undefined)
"
data-slot="search-field-clear-button"
slot="clear"
@click="context?.clear"
>
<template v-if="$slots.default" #default="state">
<slot v-bind="state" />
</template>
</CloseButton>
</template>
@@ -0,0 +1,50 @@
<script setup lang="ts">
import { inject, watch } from "vue";
import { searchFieldVariants } from "@heroui-vue/styles";
import { searchFieldContextKey } from "./context";
defineOptions({ inheritAttrs: false });
const context = inject(searchFieldContextKey, undefined);
const fallback = searchFieldVariants();
watch(
() => context?.field.disabled.value,
(disabled) => {
if (disabled && context) {
context.hovered.value = false;
context.focused.value = false;
context.focusVisible.value = false;
}
},
);
function blur(event: FocusEvent) {
if (
context &&
!(event.currentTarget as HTMLElement).contains(
event.relatedTarget as Node | null,
)
) {
context.focused.value = false;
context.focusVisible.value = false;
}
}
</script>
<template>
<div
v-bind="$attrs"
:class="[context?.slots.value.group() ?? fallback.group(), $attrs.class]"
:role="typeof $attrs.role === 'string' ? $attrs.role : 'group'"
data-slot="search-field-group"
:data-disabled="context?.field.disabled.value || undefined"
:data-invalid="context?.field.invalid.value || undefined"
:data-hovered="context?.hovered.value || undefined"
:data-focus-within="context?.focused.value || undefined"
:aria-disabled="context?.field.disabled.value || undefined"
@pointerenter="
context && (context.hovered.value = !context.field.disabled.value)
"
@pointerleave="context && (context.hovered.value = false)"
@focusin="context && (context.focused.value = true)"
@focusout="blur"
>
<slot />
</div>
</template>
@@ -0,0 +1,51 @@
<script setup lang="ts">
import { inject, useAttrs } from "vue";
import { useTextControl } from "../field/useTextControl";
import { searchFieldContextKey } from "./context";
defineOptions({ inheritAttrs: false });
const props = defineProps<{
modelValue?: string;
defaultValue?: string;
invalid?: boolean;
type?: string;
}>();
const emit = defineEmits<{ "update:modelValue": [value: string] }>();
const attrs = useAttrs();
const group = inject(searchFieldContextKey, undefined);
const control = useTextControl(props, attrs, emit);
const { element, value } = control;
defineExpose({ focus: () => element.value?.focus(), element });
</script>
<template>
<input
ref="element"
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="[group?.slots.value.input(), attrs.class]"
: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="search-field-input"
@input="control.update"
@invalid="control.onInvalid"
@focus="
group &&
(group.focusVisible.value = ($event.target as HTMLElement).matches(
':focus-visible',
))
"
/>
</template>
@@ -0,0 +1,48 @@
<script setup lang="ts">
import { inject } from "vue";
import { Primitive } from "reka-ui";
import { searchFieldVariants } from "@heroui-vue/styles";
import { searchFieldContextKey } from "./context";
defineOptions({ inheritAttrs: false });
const context = inject(searchFieldContextKey, undefined);
const fallback = searchFieldVariants();
</script>
<template>
<Primitive
v-if="$slots.default"
as-child
v-bind="$attrs"
:class="[
context?.slots.value.searchIcon() ?? fallback.searchIcon(),
$attrs.class,
]"
aria-hidden="true"
data-slot="search-field-search-icon"
>
<slot />
</Primitive>
<!-- Default IconSearch ported from the fixed HeroUI icons.tsx baseline; see HEROUI-LICENSE. -->
<svg
v-else
v-bind="$attrs"
:class="[
context?.slots.value.searchIcon() ?? fallback.searchIcon(),
$attrs.class,
]"
aria-hidden="true"
fill="none"
height="16"
role="presentation"
viewBox="0 0 16 16"
width="16"
xmlns="http://www.w3.org/2000/svg"
data-slot="search-field-search-icon"
>
<path
clip-rule="evenodd"
d="M11.5 7a4.5 4.5 0 1 1-9 0a4.5 4.5 0 0 1 9 0m-.82 4.74a6 6 0 1 1 1.06-1.06l2.79 2.79a.75.75 0 1 1-1.06 1.06z"
fill="currentColor"
fill-rule="evenodd"
/>
</svg>
</template>
@@ -0,0 +1,15 @@
import type { ComputedRef, InjectionKey, Ref } from "vue";
import type { searchFieldVariants } from "@heroui-vue/styles";
import type { TextFieldContext } from "../textfield/context";
export interface SearchFieldContext {
field: TextFieldContext;
slots: ComputedRef<ReturnType<typeof searchFieldVariants>>;
hovered: Ref<boolean>;
focused: Ref<boolean>;
focusVisible: Ref<boolean>;
clear: (event?: Event) => void;
keydown: (event: KeyboardEvent) => void;
}
export const searchFieldContextKey: InjectionKey<SearchFieldContext> = Symbol(
"HeroUIVue.SearchField",
);
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { useInheritedDisabled } from "../field/disabled";
import {
computed,
inject,
@@ -97,7 +98,7 @@ const serverMessages = computed(() => {
const checked = computed(
() => props.isSelected ?? props.checked ?? internal.value,
);
const disabled = computed(() => props.isDisabled || props.disabled);
const disabled = useInheritedDisabled(() => props.isDisabled || props.disabled);
const readOnly = computed(() => props.isReadOnly);
const required = computed(() => props.isRequired || props.required);
const invalid = computed(
@@ -1,306 +1,13 @@
<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";
import { defineComponent } from "vue";
import { textFieldProps, useTextField } from "../field/useTextField";
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>,
},
props: textFieldProps,
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" ||
name === "InputGroupInput" ||
name === "InputGroupTextArea"
)
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 });
}
// InputGroup is a library-owned transparent field wrapper. Prepare its
// default slot once, preserving the current render's values and keys.
// Arbitrary consumer components remain opaque to SSR planning.
if (
name === "InputGroup" &&
node.children &&
typeof node.children === "object"
) {
const groupSlots = node.children as { default?: () => VNodeChild[] };
if (typeof groupSlots.default === "function") {
const prepared = prepare(groupSlots.default(), found, position);
const clone = cloneVNode(node);
clone.children = { ...groupSlots, default: () => prepared };
return clone;
}
}
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,
);
};
setup(props, context) {
return useTextField(props, context).render;
},
});
</script>