feat: add Checkbox and Radio field families
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
/* Adapted from HeroUI ce90ea3. Copyright 2025 NextUI Inc.
|
||||
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
|
||||
.hv-checkbox-group {
|
||||
@apply flex flex-col;
|
||||
|
||||
[data-slot="checkbox"] {
|
||||
@apply mt-4;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
/* Adapted from HeroUI ce90ea3. Copyright 2025 NextUI Inc.
|
||||
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix; native reduced-motion media. */
|
||||
/* ==========================================================================
|
||||
Base checkbox styles
|
||||
========================================================================== */
|
||||
|
||||
.hv-checkbox {
|
||||
@apply flex flex-col items-start gap-1 outline-none no-highlight;
|
||||
|
||||
cursor: var(--cursor-interactive);
|
||||
|
||||
/* Field-level help text (siblings of the button), indented to align under the label */
|
||||
& > [data-slot="description"],
|
||||
& > [data-slot="field-error"] {
|
||||
@apply w-full min-w-0 cursor-default ps-7 text-xs text-wrap wrap-break-word text-muted select-none;
|
||||
}
|
||||
|
||||
[data-slot="label"] {
|
||||
@apply select-none;
|
||||
}
|
||||
|
||||
.hv-checkbox__content [data-slot="label"] {
|
||||
cursor: var(--cursor-interactive);
|
||||
}
|
||||
|
||||
/* Disabled state */
|
||||
&[data-disabled="true"] {
|
||||
@apply status-disabled;
|
||||
|
||||
[data-slot="description"],
|
||||
[data-slot="field-error"] {
|
||||
@apply status-disabled;
|
||||
}
|
||||
}
|
||||
|
||||
/* Indicator styles */
|
||||
&[data-selected="true"],
|
||||
&[data-indeterminate="true"] {
|
||||
.hv-checkbox__indicator {
|
||||
border-color: var(--accent-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
/* Checkmark SVG indicator */
|
||||
[data-slot="checkbox-default-indicator--checkmark"] {
|
||||
@apply size-2.5 stroke-[2.5px] text-accent-foreground;
|
||||
|
||||
/**
|
||||
* Transitions
|
||||
*/
|
||||
@apply transition-all duration-200 motion-reduce:transition-none;
|
||||
}
|
||||
|
||||
&[data-selected="true"] [data-slot="checkbox-default-indicator--checkmark"] {
|
||||
transition: stroke-dashoffset 150ms linear 15ms;
|
||||
}
|
||||
|
||||
/* Invalid + Selected: checkmark icon color */
|
||||
&[data-invalid="true"][data-selected="true"]
|
||||
[data-slot="checkbox-default-indicator--checkmark"],
|
||||
&[data-invalid="true"][aria-checked="true"]
|
||||
[data-slot="checkbox-default-indicator--checkmark"],
|
||||
&[aria-invalid="true"][data-selected="true"]
|
||||
[data-slot="checkbox-default-indicator--checkmark"],
|
||||
&[aria-invalid="true"][aria-checked="true"]
|
||||
[data-slot="checkbox-default-indicator--checkmark"] {
|
||||
@apply text-danger-foreground;
|
||||
}
|
||||
|
||||
/* Indeterminate line indicator */
|
||||
&[data-indeterminate="true"] {
|
||||
[data-slot="checkbox-default-indicator--indeterminate"] {
|
||||
@apply size-3;
|
||||
}
|
||||
}
|
||||
|
||||
/* Invalid + Indeterminate: indeterminate icon color */
|
||||
&[data-indeterminate="true"][data-invalid="true"]
|
||||
[data-slot="checkbox-default-indicator--indeterminate"],
|
||||
&[data-indeterminate="true"][aria-invalid="true"]
|
||||
[data-slot="checkbox-default-indicator--indeterminate"] {
|
||||
@apply text-danger-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Checkbox control (the square button)
|
||||
========================================================================== */
|
||||
|
||||
.hv-checkbox__control {
|
||||
@apply relative inline-flex size-4 shrink-0 items-center justify-center overflow-hidden rounded-md border [border-width:var(--border-width-field)] border-field-border bg-field shadow-field outline-none no-highlight;
|
||||
|
||||
/**
|
||||
* Transitions
|
||||
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
|
||||
*/
|
||||
transition:
|
||||
background-color 200ms var(--ease-out),
|
||||
border-color 200ms var(--ease-out),
|
||||
transform 100ms var(--ease-out);
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
cursor: var(--cursor-interactive);
|
||||
|
||||
/* Background indicator pseudo-element */
|
||||
&::before {
|
||||
@apply pointer-events-none absolute inset-0 z-0 origin-center scale-70 rounded-md bg-accent opacity-0 content-[''];
|
||||
|
||||
/**
|
||||
* Transitions
|
||||
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
|
||||
*/
|
||||
transition:
|
||||
scale 100ms var(--ease-linear),
|
||||
opacity 200ms var(--ease-linear),
|
||||
background-color 200ms var(--ease-out);
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Interactive states */
|
||||
/* Focus */
|
||||
.hv-checkbox:focus-visible &,
|
||||
.hv-checkbox:has([data-slot="checkbox-content"][data-focus-visible="true"]) &,
|
||||
.hv-checkbox [data-slot="checkbox-content"][data-focus-visible="true"] & {
|
||||
@apply status-focused;
|
||||
}
|
||||
|
||||
/* Hover */
|
||||
.hv-checkbox:hover &,
|
||||
.hv-checkbox:has([data-slot="checkbox-content"][data-hovered="true"]) &,
|
||||
.hv-checkbox [data-slot="checkbox-content"][data-hovered="true"] & {
|
||||
@apply border-field-border-hover;
|
||||
|
||||
&::before {
|
||||
@apply bg-accent-hover;
|
||||
}
|
||||
}
|
||||
|
||||
/* Pressed */
|
||||
.hv-checkbox:active &,
|
||||
.hv-checkbox:has([data-slot="checkbox-content"][data-pressed="true"]) &,
|
||||
.hv-checkbox [data-slot="checkbox-content"][data-pressed="true"] & {
|
||||
}
|
||||
|
||||
/* Selection states */
|
||||
/* Selected */
|
||||
.hv-checkbox[aria-checked="true"] &,
|
||||
.hv-checkbox[data-selected="true"] & {
|
||||
@apply border-transparent text-accent-foreground;
|
||||
|
||||
&::before {
|
||||
@apply scale-100 opacity-100;
|
||||
}
|
||||
}
|
||||
|
||||
/* Indeterminate */
|
||||
.hv-checkbox[data-indeterminate="true"] & {
|
||||
@apply bg-accent text-accent-foreground;
|
||||
}
|
||||
|
||||
/* Indeterminate + Pressed */
|
||||
.hv-checkbox:active[data-indeterminate="true"] &,
|
||||
.hv-checkbox[data-pressed="true"][data-indeterminate="true"] &,
|
||||
.hv-checkbox:has(
|
||||
[data-slot="checkbox-content"][data-pressed="true"]
|
||||
)[data-indeterminate="true"]
|
||||
& {
|
||||
@apply bg-accent-hover;
|
||||
}
|
||||
|
||||
/* Validation states */
|
||||
/* Invalid (only when not selected/indeterminate) */
|
||||
.hv-checkbox[data-invalid="true"]:not([aria-checked="true"]):not(
|
||||
[data-selected="true"]
|
||||
):not([data-indeterminate="true"])
|
||||
&,
|
||||
.hv-checkbox[aria-invalid="true"]:not([aria-checked="true"]):not(
|
||||
[data-selected="true"]
|
||||
):not([data-indeterminate="true"])
|
||||
& {
|
||||
@apply status-invalid-field;
|
||||
}
|
||||
|
||||
/* Invalid + Selected */
|
||||
.hv-checkbox[data-invalid="true"][aria-checked="true"] &,
|
||||
.hv-checkbox[data-invalid="true"][data-selected="true"] &,
|
||||
.hv-checkbox[aria-invalid="true"][aria-checked="true"] &,
|
||||
.hv-checkbox[aria-invalid="true"][data-selected="true"] & {
|
||||
@apply border-transparent bg-danger text-danger-foreground;
|
||||
|
||||
&::before {
|
||||
@apply scale-100 bg-danger opacity-100;
|
||||
}
|
||||
}
|
||||
|
||||
/* Invalid + Indeterminate */
|
||||
.hv-checkbox[data-indeterminate="true"][aria-invalid="true"] &,
|
||||
.hv-checkbox[data-indeterminate="true"][data-invalid="true"] & {
|
||||
@apply bg-danger text-danger-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Checkbox indicator
|
||||
========================================================================== */
|
||||
|
||||
.hv-checkbox__indicator {
|
||||
@apply relative z-10 flex size-3 items-center justify-center;
|
||||
|
||||
& svg {
|
||||
@apply size-full transform-gpu;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Variant property definitions
|
||||
========================================================================== */
|
||||
|
||||
.hv-checkbox--primary {
|
||||
/* Default styles */
|
||||
}
|
||||
|
||||
.hv-checkbox--secondary .hv-checkbox__control {
|
||||
@apply shadow-none;
|
||||
background-color: var(--checkbox-control-bg);
|
||||
|
||||
--checkbox-control-bg: var(--default);
|
||||
|
||||
/* Hover state */
|
||||
.hv-checkbox:hover &,
|
||||
.hv-checkbox:has([data-slot="checkbox-content"][data-hovered="true"]) &,
|
||||
.hv-checkbox [data-slot="checkbox-content"][data-hovered="true"] & {
|
||||
@apply border-field-border-hover;
|
||||
}
|
||||
}
|
||||
|
||||
/* Checkbox content — the clickable label (control + label text) */
|
||||
.hv-checkbox__content {
|
||||
@apply relative inline-flex cursor-[inherit] items-center gap-3 text-sm font-medium text-foreground outline-none select-none no-highlight;
|
||||
}
|
||||
|
||||
/* Unselected state background for secondary variant */
|
||||
.hv-checkbox--secondary:not([aria-checked="true"]):not(
|
||||
[data-selected="true"]
|
||||
):not([data-indeterminate="true"])
|
||||
.hv-checkbox__control {
|
||||
background-color: var(--checkbox-control-bg);
|
||||
}
|
||||
|
||||
/* Selected state on secondary variant */
|
||||
.hv-checkbox--secondary[aria-checked="true"] .hv-checkbox__control,
|
||||
.hv-checkbox--secondary[data-selected="true"] .hv-checkbox__control {
|
||||
&::before {
|
||||
@apply bg-accent;
|
||||
}
|
||||
}
|
||||
|
||||
/* Indeterminate state on secondary variant */
|
||||
.hv-checkbox--secondary[data-indeterminate="true"] .hv-checkbox__control {
|
||||
@apply bg-accent;
|
||||
|
||||
&::before {
|
||||
@apply bg-accent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/* Adapted from HeroUI ce90ea3. Copyright 2025 NextUI Inc.
|
||||
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
|
||||
/* Radio Group base styles */
|
||||
.hv-radio-group {
|
||||
@apply flex flex-col;
|
||||
|
||||
/* Default orientation */
|
||||
&[data-orientation="vertical"] {
|
||||
[data-slot="radio"] {
|
||||
@apply mt-4;
|
||||
}
|
||||
}
|
||||
|
||||
&[data-orientation="horizontal"] {
|
||||
@apply flex-row flex-wrap gap-4;
|
||||
}
|
||||
}
|
||||
|
||||
/* Variant property definitions */
|
||||
.hv-radio-group--primary {
|
||||
/* Default styles */
|
||||
}
|
||||
|
||||
.hv-radio-group--secondary .hv-radio__control {
|
||||
@apply shadow-none;
|
||||
background-color: var(--radio-control-bg);
|
||||
|
||||
--radio-control-bg: var(--default);
|
||||
--radio-control-bg-hover: var(--default-hover);
|
||||
|
||||
/* Hover state */
|
||||
.hv-radio:has([data-slot="radio-content"][data-hovered="true"]) &,
|
||||
.hv-radio [data-slot="radio-content"][data-hovered="true"] & {
|
||||
@apply border-field-border-hover;
|
||||
}
|
||||
|
||||
/* Default indicator color (unselected) */
|
||||
.hv-radio:not([data-selected]):not(:has(input:checked))
|
||||
&
|
||||
.hv-radio__indicator:empty::before {
|
||||
background-color: var(--radio-control-bg);
|
||||
}
|
||||
|
||||
/* Hover indicator color (unselected) */
|
||||
.hv-radio:has([data-slot="radio-content"][data-hovered="true"]):not(
|
||||
[data-selected]
|
||||
):not(:has(input:checked))
|
||||
& {
|
||||
.hv-radio__indicator:empty::before {
|
||||
background-color: var(--radio-control-bg-hover);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
/* Adapted from HeroUI ce90ea3. Copyright 2025 NextUI Inc.
|
||||
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix; native reduced-motion media. */
|
||||
/* ==========================================================================
|
||||
Base radio styles
|
||||
|
||||
Structure (explicit composition):
|
||||
.hv-radio → RadioField wrapper (column)
|
||||
.hv-radio__content → RadioButton: the clickable row (control + label)
|
||||
.hv-radio__control
|
||||
[data-slot="label"]
|
||||
[data-slot="description"] → field-level sibling, below the row
|
||||
[data-slot="field-error"]
|
||||
========================================================================== */
|
||||
|
||||
.hv-radio {
|
||||
@apply flex flex-col items-start gap-1 outline-none no-highlight;
|
||||
|
||||
cursor: var(--cursor-interactive);
|
||||
|
||||
[data-slot="label"] {
|
||||
@apply select-none;
|
||||
}
|
||||
|
||||
.hv-radio__content [data-slot="label"] {
|
||||
cursor: var(--cursor-interactive);
|
||||
}
|
||||
|
||||
/* Field-level help text (siblings of the button), indented to align under the label */
|
||||
& > [data-slot="description"],
|
||||
& > [data-slot="field-error"] {
|
||||
@apply w-full min-w-0 cursor-default ps-7 text-xs text-wrap wrap-break-word text-muted select-none;
|
||||
}
|
||||
|
||||
/* Disabled state */
|
||||
&:disabled,
|
||||
&[data-disabled="true"],
|
||||
&[aria-disabled="true"] {
|
||||
@apply status-disabled;
|
||||
|
||||
[data-slot="description"],
|
||||
[data-slot="field-error"] {
|
||||
@apply status-disabled;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Radio content — the clickable label (control + label text) */
|
||||
.hv-radio__content {
|
||||
@apply relative inline-flex cursor-[inherit] items-center gap-3 text-sm font-medium text-foreground outline-none select-none no-highlight;
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Radio control (the circular button)
|
||||
========================================================================== */
|
||||
|
||||
.hv-radio__control {
|
||||
@apply relative inline-flex size-4 shrink-0 items-center justify-center rounded-lg border [border-width:var(--border-width-field)] border-field-border bg-field shadow-field outline-none no-highlight;
|
||||
|
||||
/**
|
||||
* Transitions
|
||||
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
|
||||
*/
|
||||
transition:
|
||||
background-color 200ms var(--ease-out),
|
||||
border-color 200ms var(--ease-out),
|
||||
transform 100ms var(--ease-out);
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
cursor: var(--cursor-interactive);
|
||||
|
||||
/* Interactive states */
|
||||
/* Focus */
|
||||
.hv-radio:has([data-slot="radio-content"][data-focus-visible="true"]) &,
|
||||
.hv-radio [data-slot="radio-content"][data-focus-visible="true"] & {
|
||||
@apply status-focused;
|
||||
}
|
||||
|
||||
/* Hover */
|
||||
.hv-radio:has([data-slot="radio-content"][data-hovered="true"]) &,
|
||||
.hv-radio [data-slot="radio-content"][data-hovered="true"] & {
|
||||
@apply border-field-border-hover;
|
||||
}
|
||||
|
||||
/* Hover - only when not selected */
|
||||
.hv-radio:has([data-slot="radio-content"][data-hovered="true"]):not(
|
||||
[data-selected]
|
||||
):not(:has(input:checked))
|
||||
& {
|
||||
.hv-radio__indicator:empty::before {
|
||||
@apply bg-field-hover;
|
||||
}
|
||||
}
|
||||
|
||||
/* Pressed */
|
||||
.hv-radio:has([data-slot="radio-content"][data-pressed="true"]) &,
|
||||
.hv-radio [data-slot="radio-content"][data-pressed="true"] & {
|
||||
@apply scale-95;
|
||||
}
|
||||
|
||||
/* Selection states */
|
||||
/* Selected */
|
||||
.hv-radio[data-selected] &,
|
||||
.hv-radio:has([data-slot="radio-content"][aria-checked="true"]) &,
|
||||
.hv-radio:has(input:checked) & {
|
||||
@apply border-transparent bg-accent;
|
||||
}
|
||||
|
||||
/* Selected + Pressed */
|
||||
.hv-radio[data-selected]:has([data-slot="radio-content"][data-pressed="true"])
|
||||
&,
|
||||
.hv-radio:has(
|
||||
[data-slot="radio-content"][data-pressed="true"][aria-checked="true"]
|
||||
)
|
||||
&,
|
||||
.hv-radio:has(input:checked):has(
|
||||
[data-slot="radio-content"][data-pressed="true"]
|
||||
)
|
||||
& {
|
||||
@apply bg-accent-hover;
|
||||
}
|
||||
|
||||
/* Validation states */
|
||||
/* Invalid */
|
||||
.hv-radio[data-invalid="true"] &,
|
||||
.hv-radio[aria-invalid="true"] & {
|
||||
@apply status-invalid-field;
|
||||
}
|
||||
|
||||
/* Invalid + Selected */
|
||||
.hv-radio[data-invalid="true"][data-selected] &,
|
||||
.hv-radio[aria-invalid="true"][data-selected] &,
|
||||
.hv-radio[data-invalid="true"]:has(input:checked) &,
|
||||
.hv-radio[aria-invalid="true"]:has(input:checked) & {
|
||||
@apply status-invalid-field;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Radio indicator (the inner dot)
|
||||
========================================================================== */
|
||||
|
||||
.hv-radio__indicator {
|
||||
@apply absolute inset-0 flex items-center justify-center;
|
||||
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* :empty pseudo-class ensures these styles only apply when the indicator has no custom children
|
||||
(e.g., custom icon). When custom content is present, these default dot styles are not applied. */
|
||||
.hv-radio__indicator:empty::before {
|
||||
content: "";
|
||||
@apply rounded-lg bg-field;
|
||||
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
scale: 1;
|
||||
|
||||
/**
|
||||
* Transitions
|
||||
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
|
||||
*/
|
||||
transition:
|
||||
scale 200ms var(--ease-out),
|
||||
background-color 200ms var(--ease-out);
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Selected state */
|
||||
.hv-radio[data-selected] .hv-radio__indicator:empty::before,
|
||||
.hv-radio:has([data-slot="radio-content"][aria-checked="true"])
|
||||
.hv-radio__indicator:empty::before,
|
||||
.hv-radio:has(input:checked) .hv-radio__indicator:empty::before {
|
||||
@apply bg-accent-foreground;
|
||||
scale: 0.4286; /* 6px */
|
||||
}
|
||||
|
||||
/* Selected + Pressed state */
|
||||
.hv-radio[data-selected]:has([data-slot="radio-content"][data-pressed="true"])
|
||||
.hv-radio__indicator:empty::before,
|
||||
.hv-radio:has(
|
||||
[data-slot="radio-content"][data-pressed="true"][aria-checked="true"]
|
||||
)
|
||||
.hv-radio__indicator:empty::before,
|
||||
.hv-radio:has(input:checked):has(
|
||||
[data-slot="radio-content"][data-pressed="true"]
|
||||
)
|
||||
.hv-radio__indicator:empty::before {
|
||||
scale: 0.5714; /* 8px */
|
||||
}
|
||||
@@ -77,3 +77,26 @@
|
||||
pointer-events: auto;
|
||||
}
|
||||
}
|
||||
|
||||
@import "./components/checkbox.css" layer(components);
|
||||
|
||||
@import "./components/checkbox-group.css" layer(components);
|
||||
|
||||
@import "./components/radio.css" layer(components);
|
||||
|
||||
@import "./components/radio-group.css" layer(components);
|
||||
|
||||
@layer components {
|
||||
.hv-choice-input,
|
||||
.hv-choice-validation {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -574,3 +574,68 @@ export const searchFieldVariants = tv({
|
||||
});
|
||||
|
||||
export type SearchFieldVariants = VariantProps<typeof searchFieldVariants>;
|
||||
|
||||
export const checkboxVariants = tv({
|
||||
defaultVariants: {
|
||||
variant: "primary",
|
||||
},
|
||||
slots: {
|
||||
base: "hv-checkbox",
|
||||
content: "hv-checkbox__content",
|
||||
control: "hv-checkbox__control",
|
||||
indicator: "hv-checkbox__indicator",
|
||||
},
|
||||
variants: {
|
||||
variant: {
|
||||
primary: {
|
||||
base: "hv-checkbox--primary",
|
||||
},
|
||||
secondary: {
|
||||
base: "hv-checkbox--secondary",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export type CheckboxVariants = VariantProps<typeof checkboxVariants>;
|
||||
|
||||
export const checkboxGroupVariants = tv({
|
||||
base: "hv-checkbox-group",
|
||||
defaultVariants: {
|
||||
variant: "primary",
|
||||
},
|
||||
variants: {
|
||||
variant: {
|
||||
primary: "hv-checkbox-group--primary",
|
||||
secondary: "hv-checkbox-group--secondary",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export type CheckboxGroupVariants = VariantProps<typeof checkboxGroupVariants>;
|
||||
|
||||
export const radioVariants = tv({
|
||||
slots: {
|
||||
base: "hv-radio",
|
||||
content: "hv-radio__content",
|
||||
control: "hv-radio__control",
|
||||
indicator: "hv-radio__indicator",
|
||||
},
|
||||
});
|
||||
|
||||
export type RadioVariants = VariantProps<typeof radioVariants>;
|
||||
|
||||
export const radioGroupVariants = tv({
|
||||
base: "hv-radio-group",
|
||||
defaultVariants: {
|
||||
variant: "primary",
|
||||
},
|
||||
variants: {
|
||||
variant: {
|
||||
primary: "hv-radio-group--primary",
|
||||
secondary: "hv-radio-group--secondary",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export type RadioGroupVariants = VariantProps<typeof radioGroupVariants>;
|
||||
|
||||
@@ -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");
|
||||
@@ -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,
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -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,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) => {
|
||||
|
||||
@@ -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>
|
||||
@@ -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";
|
||||
|
||||
@@ -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"];
|
||||
|
||||
Reference in New Issue
Block a user