feat: add Checkbox and Radio field families

This commit is contained in:
maoyingjie
2026-10-22 09:15:27 +08:00
parent a4fb3c550a
commit bcadbeaf8c
75 changed files with 5293 additions and 22 deletions
@@ -0,0 +1,11 @@
<script lang="ts">
import { defineComponent, h } from "vue";
import ChoiceContent from "../choice/ChoiceContent.vue";
export default defineComponent({
name: "CheckboxContent",
inheritAttrs: false,
setup(_, { attrs, slots }) {
return () => h(ChoiceContent, attrs, slots);
},
});
</script>
@@ -0,0 +1,16 @@
<script setup lang="ts">
import { inject } from "vue";
import { choiceKey } from "../choice/context";
defineOptions({ inheritAttrs: false });
const context = inject(choiceKey);
if (!context) throw new Error("CheckboxControl must be inside Checkbox");
</script>
<template>
<span
v-bind="$attrs"
:class="[context.slots.value.control(), $attrs.class]"
data-slot="checkbox-control"
>
<slot v-bind="context.state()"></slot>
</span>
</template>
@@ -0,0 +1,49 @@
<script setup lang="ts">
// Default SVGs adapted from HeroUI ce90ea3 checkbox.tsx, Copyright 2025 NextUI Inc.
// See third-party/HEROUI-LICENSE (Apache-2.0).
import { inject } from "vue";
import { choiceKey } from "../choice/context";
defineOptions({ inheritAttrs: false });
const context = inject(choiceKey);
if (!context) throw new Error("CheckboxIndicator must be inside Checkbox");
</script>
<template>
<span
v-bind="$attrs"
:class="[context.slots.value.indicator(), $attrs.class]"
aria-hidden="true"
data-slot="checkbox-indicator"
>
<slot v-bind="context.state()">
<svg
v-if="context.state().isIndeterminate"
aria-hidden="true"
data-slot="checkbox-default-indicator--indeterminate"
fill="none"
role="presentation"
stroke="currentColor"
stroke-linecap="round"
stroke-width="3"
viewBox="0 0 24 24"
>
<line x1="21" x2="3" y1="12" y2="12" />
</svg>
<svg
v-else
aria-hidden="true"
data-slot="checkbox-default-indicator--checkmark"
fill="none"
role="presentation"
stroke="currentColor"
stroke-dasharray="22"
:stroke-dashoffset="context.state().isSelected ? 44 : 66"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 17 18"
>
<polyline points="1 9 7 14 15 4" />
</svg>
</slot>
</span>
</template>
@@ -0,0 +1,61 @@
<script setup lang="ts">
import { inject } from "vue";
import { choiceKey } from "./context";
defineOptions({ inheritAttrs: false });
const context = inject(choiceKey);
if (!context) throw new Error("ChoiceContent must be inside Checkbox or Radio");
</script>
<template>
<label
v-bind="$attrs"
:class="[context.slots.value.content(), $attrs.class]"
:data-slot="`${context.kind}-content`"
:data-selected="context.state().isSelected || undefined"
:data-indeterminate="context.state().isIndeterminate || undefined"
:data-disabled="context.field.disabled.value || undefined"
:data-hovered="context.hover.value || undefined"
:data-pressed="context.pressed.value || undefined"
:data-focus-visible="context.focusVisible.value || undefined"
@pointerenter="context.hover.value = !context.field.disabled.value"
@pointerleave="
context.hover.value = false;
context.pressed.value = false;
"
@pointerdown="
context.pressed.value =
!context.field.disabled.value && !context.field.readOnly.value
"
@pointerup="context.pressed.value = false"
>
<input
:ref="
(el) =>
context &&
(context.input.value = el ? (el as HTMLInputElement) : undefined)
"
@click.capture="context.guard"
@keydown.capture="context.keydown"
@keydown.space="
context.pressed.value =
!context.field.disabled.value && !context.field.readOnly.value
"
@keyup="context.pressed.value = false"
v-bind="context.inputAttrs()"
class="hv-choice-input"
@change="context.onChange"
@invalid="context.onInvalid"
@focus="
context.focused.value = true;
context.focusVisible.value = ($event.target as HTMLElement).matches(
':focus-visible',
);
"
@blur="
context.focused.value = false;
context.focusVisible.value = false;
context.pressed.value = false;
"
/>
<slot v-bind="context.state()" />
</label>
</template>
@@ -0,0 +1,60 @@
import type { ComputedRef, InjectionKey, Ref } from "vue";
import type { checkboxVariants, radioVariants } from "@heroui-vue/styles";
import type { FieldContext } from "../field/context";
export interface ChoiceState {
isSelected: boolean;
isIndeterminate: boolean;
isDisabled: boolean;
isReadOnly: boolean;
isRequired: boolean;
isInvalid: boolean;
isHovered: boolean;
isPressed: boolean;
isFocused: boolean;
isFocusVisible: boolean;
}
export interface ChoiceMember {
value: () => string;
disabled: ComputedRef<boolean>;
readOnly: ComputedRef<boolean>;
input: Ref<HTMLInputElement | undefined>;
}
export interface ChoiceGroupContext {
kind: "checkbox" | "radio";
field: FieldContext;
behavior: ComputedRef<import("../field/context").ValidationBehavior>;
name: () => string | undefined;
form: () => string | undefined;
variant: ComputedRef<"primary" | "secondary" | undefined>;
selected: (value: string) => boolean;
select: (value: string) => void;
register: (member: ChoiceMember) => () => void;
tabIndex: (member: ChoiceMember) => number;
keydown: (event: KeyboardEvent, member: ChoiceMember) => void;
describedBy: () => string | undefined;
restore: () => void;
}
export const choiceGroupKey: InjectionKey<ChoiceGroupContext> = Symbol(
"HeroUIVue.ChoiceGroup",
);
export interface ChoiceContext {
kind: "checkbox" | "radio";
field: FieldContext;
slots: ComputedRef<
ReturnType<typeof checkboxVariants> | ReturnType<typeof radioVariants>
>;
state: () => ChoiceState;
input: Ref<HTMLInputElement | undefined>;
rootAttrs: () => Record<string, unknown>;
inputAttrs: () => Record<string, unknown>;
onChange: (event: Event) => void;
onInvalid: (event: Event) => void;
guard: (event: Event) => void;
keydown: (event: KeyboardEvent) => void;
hover: Ref<boolean>;
pressed: Ref<boolean>;
focused: Ref<boolean>;
focusVisible: Ref<boolean>;
}
export const choiceKey: InjectionKey<ChoiceContext> =
Symbol("HeroUIVue.Choice");
+420
View File
@@ -0,0 +1,420 @@
import {
computed,
defineComponent,
h,
mergeProps,
isVNode,
nextTick,
onMounted,
onUpdated,
provide,
ref,
shallowRef,
watchEffect,
type PropType,
type VNodeChild,
} from "vue";
import { checkboxGroupVariants, radioGroupVariants } from "@heroui-vue/styles";
import {
choiceGroupKey,
type ChoiceGroupContext,
type ChoiceMember,
} from "./context";
import {
useChoiceField,
useChoiceForm,
useChoiceValue,
validationInput,
type ChoiceFieldProps,
type ChoiceSetupContext,
} from "./shared";
import type { ValidateResult, ValidationBehavior } from "../field/context";
export const choiceGroupProps = {
id: String,
name: String,
form: String,
isDisabled: Boolean,
disabled: Boolean,
isReadOnly: Boolean,
isRequired: Boolean,
isInvalid: Boolean,
validationBehavior: String as PropType<ValidationBehavior>,
variant: String as PropType<"primary" | "secondary">,
};
interface GroupProps<T> extends ChoiceFieldProps {
modelValue?: T;
defaultValue?: T;
validate?: (value: T) => ValidateResult;
variant?: "primary" | "secondary";
orientation?: "horizontal" | "vertical";
dir?: "ltr" | "rtl";
loop?: boolean;
}
function setupGroup<T extends string[] | string | undefined>(
kind: "checkbox" | "radio",
props: GroupProps<T>,
context: ChoiceSetupContext,
config: {
initial: () => T;
read: () => T;
change: (value: T) => void;
selected: (model: T, value: string) => boolean;
toggle: (model: T, value: string) => T;
},
) {
const { attrs, slots, expose } = context;
const model = useChoiceValue(
config.read,
config.initial,
["modelValue", "model-value"],
config.change,
);
const root = ref<HTMLElement>(),
proxy = ref<HTMLInputElement>();
const members = shallowRef(new Map<symbol, ChoiceMember>());
const planned = shallowRef<{ value: string; disabled: boolean }[]>([]),
mounted = ref(false);
const order = ref<HTMLInputElement[]>([]);
const eligible = () =>
[...members.value.values()].filter(
(member) =>
!member.disabled.value && !member.input.value?.matches(":disabled"),
);
const selected = (value: string) => config.selected(model.value.value, value);
const validator = useChoiceField(props, attrs, {
kind: "group",
value: model.value,
validate: (value) => props.validate?.(value),
satisfied: () =>
(mounted.value
? eligible().map((member) => ({
value: member.value(),
disabled: false,
}))
: planned.value
).some((member) => !member.disabled && selected(member.value)),
requiredMessage:
kind === "checkbox" ? "请选择至少一个选项。" : "请选择一个选项。",
});
const field = validator.field;
function ordered() {
const available = eligible();
return available.sort(
(a, b) =>
order.value.indexOf(a.input.value!) -
order.value.indexOf(b.input.value!),
);
}
function focus() {
const member =
ordered().find((member) => selected(member.value())) ?? ordered()[0];
if (member?.input.value) member.input.value.focus();
else root.value?.focus();
}
function restore() {
for (const member of members.value.values())
if (member.input.value)
member.input.value.checked = selected(member.value());
}
function select(value: string) {
const member = [...members.value.values()].find(
(item) => item.value() === value,
);
if (
field.disabled.value ||
field.readOnly.value ||
member?.disabled.value ||
member?.readOnly.value
)
return;
validator.edit();
model.request(config.toggle(model.value.value, value));
void nextTick(restore);
}
function syncOrder() {
const own = new Set(
[...members.value.values()].map((member) => member.input.value),
);
const current = [
...(root.value?.querySelectorAll<HTMLInputElement>(
"input[data-choice-input]",
) ?? []),
].filter((input) => own.has(input));
if (
current.length !== order.value.length ||
current.some((input, index) => input !== order.value[index])
)
order.value = current;
}
function register(member: ChoiceMember) {
if (
[...members.value.values()].some(
(item) => item.value() === member.value(),
)
)
throw new Error(`${kind} group values must be unique: ${member.value()}`);
const key = Symbol();
members.value = new Map(members.value).set(key, member);
return () => {
const next = new Map(members.value);
next.delete(key);
members.value = next;
};
}
function tabIndex(member: ChoiceMember) {
if (kind === "checkbox") return member.disabled.value ? -1 : 0;
if (!mounted.value && planned.value.length) {
const available = planned.value.filter((item) => !item.disabled);
const target =
available.find((item) => selected(item.value)) ?? available[0];
return !member.disabled.value && target?.value === member.value()
? 0
: -1;
}
const available = ordered();
const target =
available.find((item) => selected(item.value())) ?? available[0];
return !member.disabled.value && target === member ? 0 : -1;
}
function keydown(event: KeyboardEvent, member: ChoiceMember) {
if (
kind !== "radio" ||
event.defaultPrevented ||
event.isComposing ||
event.keyCode === 229 ||
![
"ArrowLeft",
"ArrowRight",
"ArrowUp",
"ArrowDown",
"Home",
"End",
].includes(event.key)
)
return;
event.preventDefault();
if (field.disabled.value || field.readOnly.value || member.disabled.value)
return;
const available = ordered();
if (!available.length) return;
const current = available.indexOf(member);
const rtl =
(props.dir ?? root.value?.closest<HTMLElement>("[dir]")?.dir) === "rtl";
const previous =
event.key === "ArrowUp" ||
event.key === (rtl ? "ArrowRight" : "ArrowLeft");
let index =
event.key === "Home"
? 0
: event.key === "End"
? available.length - 1
: current + (previous ? -1 : 1);
index =
props.loop === false
? Math.max(0, Math.min(available.length - 1, index))
: (index + available.length) % available.length;
available[index].input.value?.focus();
select(available[index].value());
}
const group: ChoiceGroupContext = {
kind,
field,
behavior: validator.behavior,
name: () => props.name,
form: () => props.form,
variant: computed(() => props.variant),
selected,
select,
register,
tabIndex,
keydown,
describedBy: validator.describedBy,
restore,
};
provide(choiceGroupKey, group);
useChoiceForm(
proxy,
() => {
model.reset();
validator.reset();
},
restore,
);
watchEffect(() => validator.validity(proxy.value), { flush: "post" });
onMounted(() => {
mounted.value = true;
syncOrder();
validator.validity(proxy.value);
});
onUpdated(syncOrder);
// Re-check dynamic member values, not only registration-time values.
watchEffect(() => {
const values = [...members.value.values()].map((member) => member.value());
if (new Set(values).size !== values.length)
throw new Error(`${kind} group values must be unique`);
});
expose({ element: root, focus });
return () => {
const children =
slots.default?.({
isDisabled: field.disabled.value,
isReadOnly: field.readOnly.value,
isRequired: field.required.value,
isInvalid: field.invalid.value,
validationErrors: field.errors.value,
value: model.value.value,
state: {
value: model.value.value,
setValue: (value: T) => {
if (!field.disabled.value && !field.readOnly.value) {
validator.edit();
model.request(value);
void nextTick(restore);
}
},
},
}) ?? [];
const found: { value: string; disabled: boolean }[] = [];
function scan(nodes: VNodeChild[]) {
for (const node of nodes) {
if (!isVNode(node)) continue;
const type = node.type as { name?: string; __name?: string };
const name = type.name ?? type.__name;
if (name === (kind === "checkbox" ? "Checkbox" : "Radio"))
found.push({
value: String(node.props?.value ?? "on"),
disabled: Boolean(
node.props?.isDisabled ||
node.props?.["is-disabled"] ||
node.props?.disabled,
),
});
else if (Array.isArray(node.children))
scan(node.children as VNodeChild[]);
}
}
scan(children);
if (JSON.stringify(found) !== JSON.stringify(planned.value))
planned.value = found;
const prepared = validator.prepare(children, true);
return h(
"div",
mergeProps(
{
...attrs,
ref: root,
id: field.controlId.value,
class: [
kind === "checkbox"
? checkboxGroupVariants({ variant: props.variant })
: radioGroupVariants({ variant: props.variant }),
attrs.class,
],
role: kind === "checkbox" ? "group" : "radiogroup",
tabindex: attrs.tabindex ?? -1,
dir: props.dir,
"aria-labelledby": validator.labelledBy(),
"aria-describedby": validator.describedBy(),
"aria-invalid": field.invalid.value || undefined,
"aria-disabled": field.disabled.value || undefined,
"aria-readonly":
kind === "radio" ? field.readOnly.value || undefined : undefined,
"aria-required":
kind === "radio" ? field.required.value || undefined : undefined,
"data-slot": `${kind}-group`,
"data-orientation":
kind === "radio" ? (props.orientation ?? "vertical") : undefined,
"data-disabled": field.disabled.value || undefined,
"data-readonly": field.readOnly.value || undefined,
"data-required": field.required.value || undefined,
"data-invalid": field.invalid.value || undefined,
},
{
onKeydown: (event: KeyboardEvent) => {
const member = [...members.value.values()].find(
(item) => item.input.value === event.target,
);
if (member) keydown(event, member);
},
},
),
[
...prepared,
validationInput(
proxy,
props,
field.disabled.value,
validator.behavior.value,
(event) => validator.invalidEvent(event, focus),
field.required.value &&
!field.readOnly.value &&
validator.behavior.value === "native",
!validator.constraints.value.length,
),
],
);
};
}
export const CheckboxGroup = defineComponent({
name: "CheckboxGroup",
inheritAttrs: false,
props: {
...choiceGroupProps,
modelValue: Array as PropType<string[]>,
defaultValue: Array as PropType<string[]>,
validate: Function as PropType<(value: string[]) => ValidateResult>,
},
emits: {
"update:modelValue": (_value: string[]) => true,
change: (_value: string[]) => true,
},
setup(props, ctx) {
return setupGroup("checkbox", props, ctx, {
initial: () => props.defaultValue ?? [],
read: () => props.modelValue ?? [],
change: (value) => {
ctx.emit("update:modelValue", value);
ctx.emit("change", value);
},
selected: (model, value) => model.includes(value),
toggle: (model, value) =>
model.includes(value)
? model.filter((item) => item !== value)
: [...model, value],
});
},
});
export const RadioGroup = defineComponent({
name: "RadioGroup",
inheritAttrs: false,
props: {
...choiceGroupProps,
modelValue: String,
defaultValue: String,
validate: Function as PropType<
(value: string | undefined) => ValidateResult
>,
orientation: {
type: String as PropType<"horizontal" | "vertical">,
default: "vertical",
},
dir: String as PropType<"ltr" | "rtl">,
loop: { type: Boolean, default: true },
},
emits: {
"update:modelValue": (_value: string | undefined) => true,
change: (_value: string | undefined) => true,
},
setup(props, ctx) {
return setupGroup("radio", props, ctx, {
initial: () => props.defaultValue,
read: () => props.modelValue,
change: (value) => {
ctx.emit("update:modelValue", value);
ctx.emit("change", value);
},
selected: (model, value) => model === value,
toggle: (_model, value) => value,
});
},
});
+333
View File
@@ -0,0 +1,333 @@
import {
computed,
defineComponent,
h,
inject,
nextTick,
onBeforeUnmount,
onMounted,
provide,
ref,
watchEffect,
type PropType,
} from "vue";
import { checkboxVariants, radioVariants } from "@heroui-vue/styles";
import {
choiceGroupKey,
choiceKey,
type ChoiceContext,
type ChoiceMember,
} from "./context";
import { choiceGroupProps } from "./group";
import {
useChoiceField,
useChoiceForm,
useChoiceValue,
type ChoiceSetupContext,
} from "./shared";
import { mergeIds, type ValidateResult } from "../field/context";
import CheckboxContent from "../checkbox/CheckboxContent.vue";
import CheckboxControl from "../checkbox/CheckboxControl.vue";
import CheckboxIndicator from "../checkbox/CheckboxIndicator.vue";
import RadioContent from "../radio/RadioContent.vue";
import RadioControl from "../radio/RadioControl.vue";
import RadioIndicator from "../radio/RadioIndicator.vue";
interface ItemProps {
id?: string;
name?: string;
form?: string;
value?: string;
checked?: boolean;
isSelected?: boolean;
defaultChecked?: boolean;
defaultSelected?: boolean;
isIndeterminate?: boolean;
isDisabled?: boolean;
disabled?: boolean;
isReadOnly?: boolean;
isRequired?: boolean;
isInvalid?: boolean;
validationBehavior?: "native" | "aria";
variant?: "primary" | "secondary";
validate?: (value: boolean) => ValidateResult;
}
function setupItem(
kind: "checkbox" | "radio",
props: ItemProps,
ctx: ChoiceSetupContext,
emit: (value: boolean) => void,
) {
const group = inject(choiceGroupKey, undefined);
if (kind === "radio" && group?.kind !== "radio")
throw new Error("Radio must be inside RadioGroup");
if (group && group.kind !== kind)
throw new Error(
`${kind} cannot be placed directly in a ${group.kind} group`,
);
const input = ref<HTMLInputElement>();
const model = useChoiceValue(
() => props.checked ?? props.isSelected ?? false,
() => props.defaultChecked ?? props.defaultSelected ?? false,
["checked", "isSelected", "is-selected"],
emit,
);
const selected = computed(() =>
group ? group.selected(props.value ?? "on") : model.value.value,
);
const validator = useChoiceField(props, ctx.attrs, {
kind: "toggle",
value: selected,
validate: (value) => props.validate?.(value),
satisfied: () => selected.value,
requiredMessage: "请选择此选项。",
parent: group?.field,
parentBehavior: group?.behavior,
});
const field = validator.field;
const hovered = ref(false),
pressed = ref(false),
focused = ref(false),
focusVisible = ref(false);
const member: ChoiceMember = {
value: () => props.value ?? "on",
disabled: field.disabled,
readOnly: field.readOnly,
input,
};
const unregister = group?.register(member);
onBeforeUnmount(() => unregister?.());
const slots = computed(() =>
kind === "checkbox"
? checkboxVariants({ variant: props.variant ?? group?.variant.value })
: radioVariants(),
);
function restore() {
if (input.value) {
input.value.checked = selected.value;
input.value.indeterminate =
kind === "checkbox" && Boolean(props.isIndeterminate);
}
}
function change(event: Event) {
if (field.disabled.value || field.readOnly.value) {
restore();
return;
}
validator.edit();
if (group) group.select(member.value());
else model.request((event.target as HTMLInputElement).checked);
void nextTick(() => {
restore();
group?.restore();
});
}
function guard(event: Event) {
if (field.disabled.value || field.readOnly.value) {
event.preventDefault();
event.stopImmediatePropagation();
}
}
const state = () => ({
isSelected: selected.value,
isIndeterminate: kind === "checkbox" && Boolean(props.isIndeterminate),
isDisabled: field.disabled.value,
isReadOnly: field.readOnly.value,
isRequired: field.required.value,
isInvalid: field.invalid.value,
isHovered: hovered.value,
isPressed: pressed.value,
isFocused: focused.value,
isFocusVisible: focusVisible.value,
});
const controlAttrs = () =>
Object.fromEntries(
Object.entries(ctx.attrs).filter(
([key]) =>
key !== "class" && key !== "style" && !key.startsWith("data-"),
),
);
const rootAttrs = () =>
Object.fromEntries(
Object.entries(ctx.attrs).filter(
([key]) =>
key === "class" || key === "style" || key.startsWith("data-"),
),
);
const context: ChoiceContext = {
kind,
field,
slots,
state,
input,
rootAttrs,
inputAttrs: () => ({
...controlAttrs(),
id: field.controlId.value,
type: kind,
name: group ? group.name() : props.name,
form: group ? group.form() : props.form,
value: props.value ?? "on",
checked: selected.value,
disabled: field.disabled.value,
required:
field.required.value &&
!field.readOnly.value &&
validator.behavior.value === "native",
tabindex: group ? group.tabIndex(member) : (ctx.attrs.tabindex ?? 0),
"aria-readonly":
kind === "checkbox" ? field.readOnly.value || undefined : undefined,
"aria-invalid": field.invalid.value || undefined,
"aria-required": field.required.value || undefined,
"aria-describedby": mergeIds(
validator.describedBy(),
group?.describedBy(),
),
"data-validation-behavior": validator.behavior.value,
"data-choice-input": "",
}),
onChange: change,
onInvalid: (event) =>
validator.invalidEvent(event, () => input.value?.focus()),
guard,
keydown: (event) => {
if (event.defaultPrevented) return;
if (
[
" ",
"Enter",
"ArrowUp",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"Home",
"End",
].includes(event.key) &&
(field.readOnly.value || field.disabled.value)
) {
guard(event);
return;
}
},
hover: hovered,
pressed,
focused,
focusVisible,
};
provide(choiceKey, context);
if (!group)
useChoiceForm(
input,
() => {
model.reset();
validator.reset();
},
restore,
);
watchEffect(
() => {
restore();
validator.validity(input.value);
if (field.disabled.value || field.readOnly.value) {
hovered.value = false;
pressed.value = false;
}
},
{ flush: "post" },
);
onMounted(() => {
restore();
validator.validity(input.value);
});
ctx.expose({ element: input, focus: () => input.value?.focus() });
return () =>
h(
"div",
{
...rootAttrs(),
class: [slots.value.base(), ctx.attrs.class],
"data-slot": kind,
"data-selected": selected.value || undefined,
"data-indeterminate":
(kind === "checkbox" && props.isIndeterminate) || undefined,
"data-disabled": field.disabled.value || undefined,
"data-readonly": field.readOnly.value || undefined,
"data-required": field.required.value || undefined,
"data-invalid": field.invalid.value || undefined,
},
validator.prepare(
ctx.slots.default?.({
...state(),
state: {
isSelected: selected.value,
setSelected: (value: boolean) => {
if (field.disabled.value || field.readOnly.value) return;
validator.edit();
if (group) {
if (selected.value !== value) group.select(member.value());
} else model.request(value);
void nextTick(restore);
},
toggle: () => {
if (field.disabled.value || field.readOnly.value) return;
validator.edit();
if (group) group.select(member.value());
else model.request(!selected.value);
void nextTick(restore);
},
},
}) ?? [
h(kind === "checkbox" ? CheckboxContent : RadioContent, {}, () =>
h(kind === "checkbox" ? CheckboxControl : RadioControl, {}, () =>
h(kind === "checkbox" ? CheckboxIndicator : RadioIndicator),
),
),
],
false,
"",
state(),
),
);
}
export const Checkbox = defineComponent({
name: "Checkbox",
inheritAttrs: false,
props: {
...choiceGroupProps,
value: String,
checked: { type: Boolean, default: undefined },
isSelected: { type: Boolean, default: undefined },
defaultChecked: { type: Boolean, default: undefined },
defaultSelected: Boolean,
isIndeterminate: Boolean,
validate: Function as PropType<(value: boolean) => ValidateResult>,
},
emits: {
"update:checked": (_value: boolean) => true,
"update:isSelected": (_value: boolean) => true,
change: (_value: boolean) => true,
},
setup(props, ctx) {
return setupItem("checkbox", props, ctx, (value) => {
ctx.emit("update:checked", value);
ctx.emit("update:isSelected", value);
ctx.emit("change", value);
});
},
});
export const Radio = defineComponent({
name: "Radio",
inheritAttrs: false,
props: {
id: String,
value: { type: String, required: true },
name: String,
form: String,
isDisabled: Boolean,
disabled: Boolean,
isReadOnly: Boolean,
isInvalid: Boolean,
},
setup(props, ctx) {
return setupItem("radio", props, ctx, () => {});
},
});
@@ -0,0 +1,326 @@
import {
Comment,
Fragment,
cloneVNode,
computed,
getCurrentInstance,
h,
inject,
isVNode,
nextTick,
onBeforeUnmount,
onBeforeUpdate,
onMounted,
onUpdated,
provide,
ref,
shallowRef,
useId,
watchEffect,
type ComputedRef,
type Ref,
type Slots,
type VNode,
type VNodeChild,
} from "vue";
import {
errorMessages,
fieldContextKey,
formContextKey,
mergeIds,
type FieldContext,
type ValidateResult,
type ValidationBehavior,
} from "../field/context";
import { useInheritedDisabled } from "../field/disabled";
export interface ChoiceFieldProps {
id?: string;
name?: string;
form?: string;
isDisabled?: boolean;
disabled?: boolean;
isReadOnly?: boolean;
isRequired?: boolean;
isInvalid?: boolean;
validationBehavior?: ValidationBehavior;
}
export interface ChoiceSetupContext {
attrs: Record<string, unknown>;
slots: Slots;
expose: (value: Record<string, unknown>) => void;
}
export function useChoiceValue<T>(
read: () => T,
defaults: () => T,
keys: string[],
emit: (value: T) => void,
) {
const instance = getCurrentInstance();
const copy = (value: T): T =>
Array.isArray(value) ? ([...value] as T) : value;
const initial = copy(defaults());
const internal = ref<T>(copy(initial)) as Ref<T>;
const controlled = () =>
keys.some((key) => Object.hasOwn(instance?.vnode.props ?? {}, key));
const isControlled = ref(controlled());
onBeforeUpdate(() => {
isControlled.value = controlled();
});
const value = computed(() => {
const external = read();
return isControlled.value ? external : internal.value;
});
function request(next: T) {
if (!controlled()) internal.value = copy(next);
emit(copy(next));
}
function reset() {
if (!controlled()) internal.value = copy(initial);
}
return { value, request, reset };
}
export function useChoiceField<T>(
props: ChoiceFieldProps,
attrs: Record<string, unknown>,
options: {
kind: "group" | "toggle";
value: ComputedRef<T>;
validate?: (value: T) => ValidateResult;
satisfied: () => boolean;
requiredMessage: string;
parent?: FieldContext;
parentBehavior?: ComputedRef<ValidationBehavior>;
},
) {
const form = inject(formContextKey, undefined);
const id = useId();
const disabled = useInheritedDisabled(
() => props.isDisabled || props.disabled || options.parent?.disabled.value,
);
const readOnly = computed(() =>
Boolean(props.isReadOnly || options.parent?.readOnly.value),
);
const required = computed(() => Boolean(props.isRequired));
const behavior = computed(
() =>
props.validationBehavior ??
options.parentBehavior?.value ??
form?.validationBehavior.value ??
"native",
);
const touched = ref(false),
dismissed = shallowRef<object>();
const registeredDescriptions = ref<string[]>([]),
registeredErrors = ref<string[]>([]),
labels = ref<string[]>([]);
const planned = shallowRef({
labels: [] as string[],
descriptions: [] as string[],
errors: [] as string[],
});
const server = computed(() => {
const source = form?.validationErrors.value;
return props.name && source && source !== dismissed.value
? errorMessages(source[props.name])
: [];
});
const constraints = computed(() =>
disabled.value || readOnly.value
? []
: [
...server.value,
...errorMessages(options.validate?.(options.value.value)),
...(required.value && !options.satisfied()
? [options.requiredMessage]
: []),
],
);
const errors = computed(() =>
disabled.value || readOnly.value
? []
: [
...server.value,
...(touched.value || behavior.value === "aria"
? constraints.value.filter(
(message) => !server.value.includes(message),
)
: []),
],
);
const invalid = computed(() =>
Boolean(
props.isInvalid || options.parent?.invalid.value || errors.value.length,
),
);
const field: FieldContext = {
kind: options.kind,
controlId: computed(() => props.id ?? id),
disabled,
readOnly,
required,
invalid,
errors,
descriptionIds: registeredDescriptions,
errorIds: registeredErrors,
labelIds: labels,
};
provide(fieldContextKey, field);
const describedBy = () =>
mergeIds(
attrs["aria-describedby"] as string | undefined,
registeredDescriptions.value,
planned.value.descriptions,
invalid.value ? [...registeredErrors.value, ...planned.value.errors] : [],
);
const labelledBy = () =>
mergeIds(
attrs["aria-labelledby"] as string | undefined,
labels.value,
planned.value.labels,
);
function edit() {
dismissed.value = form?.validationErrors.value;
}
function reset() {
touched.value = false;
dismissed.value = form?.validationErrors.value;
}
function invalidEvent(event: Event, focus: () => void) {
event.preventDefault();
touched.value = true;
void nextTick(focus);
}
function validity(control: HTMLInputElement | undefined) {
control?.setCustomValidity(
behavior.value === "native" ? constraints.value.join(" ") : "",
);
}
function prepare(
nodes: VNodeChild[],
groupLabels = false,
path = "",
slotState: Record<string, unknown> = {},
): VNodeChild[] {
const found = {
labels: [] as string[],
descriptions: [] as string[],
errors: [] as string[],
};
function walk(children: VNodeChild[], position: string): VNodeChild[] {
return children.map((node, index) => {
if (!isVNode(node) || node.type === Comment) return node;
const at = `${position}-${index}`;
const type = node.type as { name?: string; __name?: string };
const name = type.name ?? type.__name;
const part =
name === "Description"
? "descriptions"
: name === "FieldError"
? "errors"
: groupLabels && name === "Label"
? "labels"
: undefined;
if (part) {
const partId = String(node.props?.id ?? `${id}-${part}${at}`);
found[part].push(partId);
return cloneVNode(node, { id: partId });
}
if (
(name === "CheckboxContent" || name === "RadioContent") &&
node.children &&
typeof node.children === "object"
) {
const contentSlots = node.children as {
default?: (
state: Record<string, unknown>,
) => VNodeChild | VNodeChild[];
};
if (contentSlots.default) {
const raw = contentSlots.default(slotState);
const prepared = walk(Array.isArray(raw) ? raw : [raw], at);
const clone = cloneVNode(node);
clone.children = { ...contentSlots, default: () => prepared };
return clone;
}
}
if (
(node.type === Fragment || typeof node.type === "string") &&
Array.isArray(node.children)
) {
const clone = cloneVNode(node);
clone.children = walk(node.children as VNodeChild[], at) as VNode[];
return clone;
}
return node;
});
}
const result = walk(nodes, path);
if (JSON.stringify(found) !== JSON.stringify(planned.value))
planned.value = found;
return result;
}
return {
field,
behavior,
constraints,
describedBy,
labelledBy,
edit,
reset,
invalidEvent,
validity,
prepare,
};
}
export function useChoiceForm(
input: Ref<HTMLInputElement | undefined>,
reset: () => void,
restore: () => void,
) {
let owner: HTMLFormElement | null = null;
function onReset(event: Event) {
void nextTick(() => {
if (event.defaultPrevented) return;
reset();
restore();
});
}
function bind() {
const next = input.value?.form ?? null;
if (next !== owner) {
owner?.removeEventListener("reset", onReset);
owner = next;
owner?.addEventListener("reset", onReset);
}
}
onMounted(bind);
onUpdated(bind);
onBeforeUnmount(() => owner?.removeEventListener("reset", onReset));
}
export function validationInput(
input: Ref<HTMLInputElement | undefined>,
props: ChoiceFieldProps,
disabled: boolean,
behavior: ValidationBehavior,
invalid: (event: Event) => void,
required = false,
checked = true,
) {
return h("input", {
ref: input,
type: "checkbox",
checked,
required,
class: "hv-choice-validation",
tabindex: -1,
"aria-hidden": "true",
form: props.form,
disabled,
"data-validation-behavior": behavior,
onInvalid: invalid,
});
}
+3 -2
View File
@@ -3,15 +3,16 @@ 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 type FieldPart = "description" | "error" | "label";
export interface FieldContext {
controlId: ComputedRef<string>;
kind: "text" | "toggle";
kind: "text" | "toggle" | "group";
disabled: ComputedRef<boolean>;
readOnly: ComputedRef<boolean>;
required: ComputedRef<boolean>;
invalid: ComputedRef<boolean>;
errors: ComputedRef<string[]>;
labelIds?: Ref<string[]>;
descriptionIds: Ref<string[]>;
errorIds: Ref<string[]>;
}
@@ -8,7 +8,12 @@ export function useFieldPart(part: FieldPart, attrs: Record<string, unknown>) {
const id = computed(() =>
typeof attrs.id === "string" ? attrs.id : generated,
);
const ids = part === "description" ? field?.descriptionIds : field?.errorIds;
const ids =
part === "label"
? field?.labelIds
: part === "description"
? field?.descriptionIds
: field?.errorIds;
const stop = watch(
id,
(current, _, cleanup) => {
+9 -1
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { inject, useAttrs } from "vue";
import { useFieldPart } from "../field/useFieldPart";
import { useInheritedDisabled } from "../field/disabled";
import { fieldContextKey } from "../field/context";
defineOptions({ inheritAttrs: false });
@@ -10,14 +11,21 @@ const props = defineProps<{
isDisabled?: boolean;
isInvalid?: boolean;
}>();
const labelPart =
field?.kind === "group" ? useFieldPart("label", attrs) : undefined;
const disabled = useInheritedDisabled(
() => props.isDisabled || field?.disabled.value,
);
</script>
<template>
<component
:is="field?.kind === 'toggle' && !attrs.for ? 'span' : 'label'"
:is="
(field?.kind === 'toggle' || field?.kind === 'group') && !attrs.for
? 'span'
: 'label'
"
v-bind="attrs"
:id="labelPart?.id.value ?? attrs.id"
:for="
attrs.for ?? (field?.kind === 'text' ? field.controlId.value : undefined)
"
@@ -0,0 +1,11 @@
<script lang="ts">
import { defineComponent, h } from "vue";
import ChoiceContent from "../choice/ChoiceContent.vue";
export default defineComponent({
name: "RadioContent",
inheritAttrs: false,
setup(_, { attrs, slots }) {
return () => h(ChoiceContent, attrs, slots);
},
});
</script>
@@ -0,0 +1,16 @@
<script setup lang="ts">
import { inject } from "vue";
import { choiceKey } from "../choice/context";
defineOptions({ inheritAttrs: false });
const context = inject(choiceKey);
if (!context) throw new Error("RadioControl must be inside Radio");
</script>
<template>
<span
v-bind="$attrs"
:class="[context.slots.value.control(), $attrs.class]"
data-slot="radio-control"
>
<slot v-bind="context.state()"></slot>
</span>
</template>
@@ -0,0 +1,23 @@
<script lang="ts">
import { defineComponent, h, inject } from "vue";
import { choiceKey } from "../choice/context";
export default defineComponent({
name: "RadioIndicator",
inheritAttrs: false,
setup(_, { attrs, slots }) {
const context = inject(choiceKey);
if (!context) throw new Error("RadioIndicator must be inside Radio");
return () =>
h(
"span",
{
...attrs,
class: [context.slots.value.indicator(), attrs.class],
"aria-hidden": "true",
"data-slot": "radio-indicator",
},
slots.default?.(context.state()),
);
},
});
</script>
+29
View File
@@ -233,3 +233,32 @@ export {
type FieldsetVariants,
type SearchFieldVariants,
} from "@heroui-vue/styles";
export { Checkbox, Radio } from "./components/choice/item";
export { CheckboxGroup, RadioGroup } from "./components/choice/group";
export type { CheckboxProps } from "./types";
export type { RadioProps } from "./types";
export type { CheckboxGroupProps } from "./types";
export type { RadioGroupProps } from "./types";
export { default as CheckboxContent } from "./components/checkbox/CheckboxContent.vue";
export type { CheckboxContentProps } from "./types";
export { default as CheckboxControl } from "./components/checkbox/CheckboxControl.vue";
export type { CheckboxControlProps } from "./types";
export { default as CheckboxIndicator } from "./components/checkbox/CheckboxIndicator.vue";
export type { CheckboxIndicatorProps } from "./types";
export { default as RadioContent } from "./components/radio/RadioContent.vue";
export type { RadioContentProps } from "./types";
export { default as RadioControl } from "./components/radio/RadioControl.vue";
export type { RadioControlProps } from "./types";
export { default as RadioIndicator } from "./components/radio/RadioIndicator.vue";
export type { RadioIndicatorProps } from "./types";
export {
checkboxVariants,
checkboxGroupVariants,
radioVariants,
radioGroupVariants,
type CheckboxVariants,
type CheckboxGroupVariants,
type RadioVariants,
type RadioGroupVariants,
} from "@heroui-vue/styles";
+25
View File
@@ -138,3 +138,28 @@ import type SearchFieldClearButton from "./components/search-field/SearchFieldCl
export type SearchFieldClearButtonProps = InstanceType<
typeof SearchFieldClearButton
>["$props"];
import type { Checkbox, Radio } from "./components/choice/item";
import type { CheckboxGroup, RadioGroup } from "./components/choice/group";
export type CheckboxProps = InstanceType<typeof Checkbox>["$props"];
export type RadioProps = InstanceType<typeof Radio>["$props"];
export type CheckboxGroupProps = InstanceType<typeof CheckboxGroup>["$props"];
export type RadioGroupProps = InstanceType<typeof RadioGroup>["$props"];
import type CheckboxContent from "./components/checkbox/CheckboxContent.vue";
export type CheckboxContentProps = InstanceType<
typeof CheckboxContent
>["$props"];
import type CheckboxControl from "./components/checkbox/CheckboxControl.vue";
export type CheckboxControlProps = InstanceType<
typeof CheckboxControl
>["$props"];
import type CheckboxIndicator from "./components/checkbox/CheckboxIndicator.vue";
export type CheckboxIndicatorProps = InstanceType<
typeof CheckboxIndicator
>["$props"];
import type RadioContent from "./components/radio/RadioContent.vue";
export type RadioContentProps = InstanceType<typeof RadioContent>["$props"];
import type RadioControl from "./components/radio/RadioControl.vue";
export type RadioControlProps = InstanceType<typeof RadioControl>["$props"];
import type RadioIndicator from "./components/radio/RadioIndicator.vue";
export type RadioIndicatorProps = InstanceType<typeof RadioIndicator>["$props"];