feat: migrate Select with field, collection and SSR contracts
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import type { ComputedRef, InjectionKey } from "vue";
|
||||
import type { CollectionKey } from "./keys";
|
||||
export interface CollectionRecord {
|
||||
key: CollectionKey;
|
||||
text: string;
|
||||
disabled: boolean;
|
||||
}
|
||||
export interface OwnedCollection {
|
||||
items: () => CollectionRecord[];
|
||||
focus: (edge: "first" | "last" | "selected") => Promise<void>;
|
||||
}
|
||||
/** A field composite may own a ListBox, without adding another value store. */
|
||||
export interface CollectionOwner {
|
||||
keys: ComputedRef<readonly CollectionKey[]>;
|
||||
mode: ComputedRef<"single" | "multiple">;
|
||||
disabled: ComputedRef<boolean>;
|
||||
readOnly: ComputedRef<boolean>;
|
||||
disabledKeys: ComputedRef<readonly CollectionKey[]>;
|
||||
id: string;
|
||||
labelledBy: () => string | undefined;
|
||||
ariaLabel: () => string | undefined;
|
||||
request: (keys: CollectionKey[]) => void;
|
||||
action: (key: CollectionKey) => void;
|
||||
leave: () => void;
|
||||
connect: (collection: OwnedCollection) => () => void;
|
||||
}
|
||||
export const collectionOwnerKey: InjectionKey<CollectionOwner | undefined> =
|
||||
Symbol("hv-collection-owner");
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts" generic="T extends ListBoxDataItem = ListBoxDataItem">
|
||||
import {
|
||||
computed,
|
||||
inject,
|
||||
getCurrentInstance,
|
||||
mergeProps,
|
||||
nextTick,
|
||||
@@ -17,6 +18,7 @@ import { useConfig } from "../../providers/context";
|
||||
import { useInheritedDisabled, disabledContextKey } from "../field/disabled";
|
||||
import { useCollectionSelection } from "../collection/selection";
|
||||
import { useCollectionRegistry } from "../collection/registry";
|
||||
import { collectionOwnerKey } from "../collection/owner";
|
||||
import { assertKey } from "../collection/keys";
|
||||
import {
|
||||
listBoxKey,
|
||||
@@ -36,6 +38,21 @@ const props = withDefaults(defineProps<ListBoxOptions<T>>(), {
|
||||
rowHeight: 50,
|
||||
overscan: 5,
|
||||
});
|
||||
const owner = inject(collectionOwnerKey, undefined);
|
||||
provide(collectionOwnerKey, undefined);
|
||||
const mode = computed(() => owner?.mode.value ?? props.selectionMode);
|
||||
const behavior = computed(() =>
|
||||
owner
|
||||
? mode.value === "single"
|
||||
? "replace"
|
||||
: "toggle"
|
||||
: props.selectionBehavior,
|
||||
);
|
||||
const readOnly = computed(() => props.isReadOnly || !!owner?.readOnly.value);
|
||||
const disabledKeys = computed(() => [
|
||||
...(props.disabledKeys ?? []),
|
||||
...(owner?.disabledKeys.value ?? []),
|
||||
]);
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [keys: ListBoxKey[]];
|
||||
selectionChange: [keys: ListBoxKey[]];
|
||||
@@ -62,13 +79,32 @@ onBeforeUpdate(() => {
|
||||
controlled.value = hasModel.value || selectedPresence();
|
||||
});
|
||||
const config = useConfig();
|
||||
const disabled = useInheritedDisabled(() => props.isDisabled);
|
||||
const disabled = useInheritedDisabled(
|
||||
() => props.isDisabled || owner?.disabled.value,
|
||||
);
|
||||
provide(disabledContextKey, disabled);
|
||||
const dir = computed(() => props.dir ?? config?.dir.value ?? "ltr");
|
||||
const registry = useCollectionRegistry<ListBoxMember>();
|
||||
const mounted = ref(false);
|
||||
let disconnectOwner: (() => void) | undefined;
|
||||
onMounted(() => {
|
||||
mounted.value = true;
|
||||
if (owner)
|
||||
disconnectOwner = owner.connect({
|
||||
items: known,
|
||||
focus: async (edge) => {
|
||||
const available = eligible();
|
||||
const key =
|
||||
edge === "last"
|
||||
? available.at(-1)?.key
|
||||
: edge === "first"
|
||||
? available[0]?.key
|
||||
: (available.find((item) => selection.selected(item.key))?.key ??
|
||||
available[0]?.key);
|
||||
if (key !== undefined) await focus(key);
|
||||
else root.value?.focus();
|
||||
},
|
||||
});
|
||||
});
|
||||
const data = computed(() => {
|
||||
const seen = new Set<ListBoxKey>();
|
||||
@@ -79,14 +115,14 @@ const data = computed(() => {
|
||||
seen.add(item.id);
|
||||
return {
|
||||
key: item.id,
|
||||
disabled: !!item.isDisabled || !!props.disabledKeys?.includes(item.id),
|
||||
disabled: !!item.isDisabled || !!disabledKeys.value.includes(item.id),
|
||||
text: item.textValue ?? "",
|
||||
};
|
||||
});
|
||||
});
|
||||
const keyDisabled = (key: ListBoxKey) =>
|
||||
disabled.value ||
|
||||
!!props.disabledKeys?.includes(key) ||
|
||||
!!disabledKeys.value.includes(key) ||
|
||||
!!data.value?.find((item) => item.key === key)?.disabled;
|
||||
const known = () => {
|
||||
const members = registry.ordered();
|
||||
@@ -115,15 +151,18 @@ const blockedKeys = computed(() =>
|
||||
.map((item) => item.key),
|
||||
);
|
||||
const selection = useCollectionSelection({
|
||||
mode: () => props.selectionMode,
|
||||
controlled: () => controlled.value,
|
||||
value: () => (hasModel.value ? props.modelValue : props.selectedKeys),
|
||||
mode: () => mode.value,
|
||||
controlled: () => !!owner || controlled.value,
|
||||
value: () =>
|
||||
owner?.keys.value ??
|
||||
(hasModel.value ? props.modelValue : props.selectedKeys),
|
||||
defaultValue: props.defaultValue ?? props.defaultSelectedKeys,
|
||||
disabled: () => disabled.value,
|
||||
readOnly: () => props.isReadOnly,
|
||||
readOnly: () => readOnly.value,
|
||||
disabledKeys: () => blockedKeys.value,
|
||||
disallowEmptySelection: () => props.disallowEmptySelection,
|
||||
onChange: (keys) => {
|
||||
owner?.request(keys);
|
||||
emit("update:modelValue", [...keys]);
|
||||
emit("selectionChange", [...keys]);
|
||||
},
|
||||
@@ -137,9 +176,8 @@ const active = computed(() => {
|
||||
const items = eligible();
|
||||
return (
|
||||
items.find((item) => item.key === lastFocused.value)?.key ??
|
||||
items.find(
|
||||
(item) => props.selectionMode !== "none" && selection.selected(item.key),
|
||||
)?.key ??
|
||||
items.find((item) => mode.value !== "none" && selection.selected(item.key))
|
||||
?.key ??
|
||||
items[0]?.key
|
||||
);
|
||||
});
|
||||
@@ -165,6 +203,7 @@ function restoreFocus() {
|
||||
let focusRequest = 0;
|
||||
let disposing = false;
|
||||
onBeforeUnmount(() => {
|
||||
disconnectOwner?.();
|
||||
disposing = true;
|
||||
focusRequest++;
|
||||
});
|
||||
@@ -203,22 +242,19 @@ function activate(key: ListBoxKey, event: MouseEvent | KeyboardEvent) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
disabled.value ||
|
||||
props.isReadOnly ||
|
||||
readOnly.value ||
|
||||
!item ||
|
||||
item.disabled
|
||||
)
|
||||
return;
|
||||
if (props.selectionMode === "multiple" && event.shiftKey) {
|
||||
if (mode.value === "multiple" && event.shiftKey) {
|
||||
anchor ??= selection.keys.value[0] ?? active.value ?? key;
|
||||
selectRange(anchor, key);
|
||||
} else if (
|
||||
props.selectionBehavior === "replace" &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey
|
||||
)
|
||||
} else if (behavior.value === "replace" && !event.ctrlKey && !event.metaKey)
|
||||
selection.replace(key);
|
||||
else selection.toggle(key);
|
||||
if (!event.shiftKey) anchor = key;
|
||||
owner?.action(key);
|
||||
emit("action", key);
|
||||
}
|
||||
function selectRange(startKey: ListBoxKey, endKey: ListBoxKey) {
|
||||
@@ -245,13 +281,23 @@ function keydown(event: KeyboardEvent) {
|
||||
(event.target as Element).closest("[data-hv-listbox]") !== root.value
|
||||
)
|
||||
return;
|
||||
if (
|
||||
owner &&
|
||||
event.key === "Tab" &&
|
||||
!event.altKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey
|
||||
) {
|
||||
owner.leave();
|
||||
return;
|
||||
}
|
||||
keyboard.value = true;
|
||||
const items = eligible();
|
||||
if (!items.length) return;
|
||||
if (
|
||||
(event.ctrlKey || event.metaKey) &&
|
||||
event.key.toLowerCase() === "a" &&
|
||||
props.selectionMode === "multiple"
|
||||
mode.value === "multiple"
|
||||
) {
|
||||
event.preventDefault();
|
||||
selection.selectAll(items.map((item) => item.key));
|
||||
@@ -296,11 +342,11 @@ function keydown(event: KeyboardEvent) {
|
||||
? (target + items.length) % items.length
|
||||
: Math.max(0, Math.min(target, items.length - 1));
|
||||
const key = items[target].key;
|
||||
if (event.shiftKey && props.selectionMode === "multiple") {
|
||||
if (event.shiftKey && mode.value === "multiple") {
|
||||
anchor ??= active.value;
|
||||
if (anchor !== undefined) selectRange(anchor, key);
|
||||
} else if (
|
||||
props.selectionBehavior === "replace" &&
|
||||
behavior.value === "replace" &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey
|
||||
) {
|
||||
@@ -318,7 +364,7 @@ function keydown(event: KeyboardEvent) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (props.isReadOnly) {
|
||||
if (readOnly.value) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
@@ -380,8 +426,8 @@ function contextOwnsEvent(event: KeyboardEvent) {
|
||||
return (event.target as Element).closest("[data-hv-listbox]") === root.value;
|
||||
}
|
||||
provide(listBoxKey, {
|
||||
mode: computed(() => props.selectionMode),
|
||||
readOnly: computed(() => props.isReadOnly),
|
||||
mode: computed(() => mode.value),
|
||||
readOnly: computed(() => readOnly.value),
|
||||
keyboard,
|
||||
focused,
|
||||
noteFocus: (key) => {
|
||||
@@ -390,7 +436,7 @@ provide(listBoxKey, {
|
||||
},
|
||||
pressed,
|
||||
active,
|
||||
selected: (key) => props.selectionMode !== "none" && selection.selected(key),
|
||||
selected: (key) => mode.value !== "none" && selection.selected(key),
|
||||
disabled: keyDisabled,
|
||||
register: registry.register,
|
||||
activate,
|
||||
@@ -406,7 +452,7 @@ provide(listBoxKey, {
|
||||
: undefined,
|
||||
});
|
||||
function rootAttrs() {
|
||||
if (props.selectionMode === "single" && selection.keys.value.length > 1)
|
||||
if (mode.value === "single" && selection.keys.value.length > 1)
|
||||
throw new TypeError("Single ListBox accepts at most one selected key.");
|
||||
if (
|
||||
props.virtualized &&
|
||||
@@ -418,6 +464,13 @@ function rootAttrs() {
|
||||
// Force duplicate validation even when a scoped item renderer is absent.
|
||||
void data.value;
|
||||
return mergeProps(attrs, {
|
||||
id: owner?.id ?? attrs.id,
|
||||
"aria-label": attrs["aria-label"] ?? owner?.ariaLabel(),
|
||||
"aria-labelledby":
|
||||
attrs["aria-labelledby"] ??
|
||||
((attrs["aria-label"] ?? owner?.ariaLabel())
|
||||
? undefined
|
||||
: owner?.labelledBy()),
|
||||
class: listboxVariants({ variant: props.variant }),
|
||||
role: "listbox",
|
||||
dir: dir.value,
|
||||
@@ -425,12 +478,10 @@ function rootAttrs() {
|
||||
"data-hv-listbox": "",
|
||||
"data-disabled": disabled.value || undefined,
|
||||
"aria-disabled": disabled.value || undefined,
|
||||
"aria-readonly": props.isReadOnly || undefined,
|
||||
"aria-readonly": readOnly.value || undefined,
|
||||
"aria-orientation": props.orientation,
|
||||
"aria-multiselectable":
|
||||
props.selectionMode === "none"
|
||||
? undefined
|
||||
: props.selectionMode === "multiple",
|
||||
mode.value === "none" ? undefined : mode.value === "multiple",
|
||||
tabindex:
|
||||
disabled.value ||
|
||||
(mounted.value &&
|
||||
|
||||
@@ -108,7 +108,7 @@ function escape(event: KeyboardEvent) {
|
||||
:side-flip="shouldFlip"
|
||||
:collision-padding="containerPadding"
|
||||
class="hv-popover"
|
||||
data-slot="popover-content"
|
||||
:data-slot="$attrs['data-slot'] ?? 'popover-content'"
|
||||
:data-entering="entering || undefined"
|
||||
:data-exiting="exiting || undefined"
|
||||
:lang="($attrs.lang as string | undefined) ?? config?.locale.value"
|
||||
@@ -123,6 +123,7 @@ function escape(event: KeyboardEvent) {
|
||||
<component
|
||||
:is="as"
|
||||
ref="contentElement"
|
||||
:role="($attrs.role as string | undefined) ?? 'dialog'"
|
||||
:aria-label="
|
||||
($attrs['aria-label'] as string | undefined) ??
|
||||
(ctx.dialogAttrs.value['aria-label'] as string | undefined)
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
getCurrentInstance,
|
||||
h,
|
||||
mergeProps,
|
||||
nextTick,
|
||||
provide,
|
||||
ref,
|
||||
shallowRef,
|
||||
watchEffect,
|
||||
type PropType,
|
||||
type SlotsType,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import { selectVariants } from "@heroui-vue/styles";
|
||||
import Popover from "../popover/Popover";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import {
|
||||
useChoiceField,
|
||||
useChoiceForm,
|
||||
useChoiceValue,
|
||||
validationInput,
|
||||
} from "../choice/shared";
|
||||
import { disabledContextKey } from "../field/disabled";
|
||||
import type { ValidationBehavior, ValidateResult } from "../field/context";
|
||||
import {
|
||||
assertKey,
|
||||
copyKeys,
|
||||
encodeKey,
|
||||
type CollectionKey,
|
||||
} from "../collection/keys";
|
||||
import {
|
||||
collectionOwnerKey,
|
||||
type CollectionRecord,
|
||||
type OwnedCollection,
|
||||
} from "../collection/owner";
|
||||
import { planSelectItems } from "./metadata";
|
||||
import { selectKey, type SelectValue, type SelectItem } from "./context";
|
||||
|
||||
export default defineComponent({
|
||||
name: "Select",
|
||||
inheritAttrs: false,
|
||||
slots: Object as SlotsType<{
|
||||
default?: (state: {
|
||||
value: SelectValue;
|
||||
isOpen: boolean;
|
||||
selectedItems: { key: CollectionKey; textValue: string }[];
|
||||
}) => VNodeChild;
|
||||
}>,
|
||||
props: {
|
||||
modelValue: {
|
||||
type: [String, Number, Array, null] as PropType<SelectValue>,
|
||||
default: undefined,
|
||||
},
|
||||
value: {
|
||||
type: [String, Number, Array, null] as PropType<SelectValue>,
|
||||
default: undefined,
|
||||
},
|
||||
defaultValue: [String, Number, Array, null] as PropType<SelectValue>,
|
||||
selectionMode: {
|
||||
type: String as PropType<"single" | "multiple">,
|
||||
default: "single",
|
||||
},
|
||||
disabledKeys: Array as PropType<readonly CollectionKey[]>,
|
||||
items: Array as PropType<readonly SelectItem[]>,
|
||||
open: { type: Boolean, default: undefined },
|
||||
isOpen: { type: Boolean, default: undefined },
|
||||
defaultOpen: Boolean,
|
||||
placeholder: { type: String, default: "Select an item" },
|
||||
autoComplete: String,
|
||||
fullWidth: Boolean,
|
||||
variant: {
|
||||
type: String as PropType<"primary" | "secondary">,
|
||||
default: "primary",
|
||||
},
|
||||
as: { type: String, default: "div" },
|
||||
id: String,
|
||||
name: String,
|
||||
form: String,
|
||||
isDisabled: Boolean,
|
||||
disabled: Boolean,
|
||||
isReadOnly: Boolean,
|
||||
isRequired: Boolean,
|
||||
isInvalid: Boolean,
|
||||
validationBehavior: String as PropType<ValidationBehavior>,
|
||||
validate: Function as PropType<(value: SelectValue) => ValidateResult>,
|
||||
},
|
||||
emits: {
|
||||
"update:modelValue": (_value: SelectValue) => true,
|
||||
change: (_value: SelectValue) => true,
|
||||
"update:open": (_value: boolean) => true,
|
||||
openChange: (_value: boolean) => true,
|
||||
clear: () => true,
|
||||
},
|
||||
setup(props, { attrs, slots, emit, expose }) {
|
||||
const instance = getCurrentInstance()!;
|
||||
const config = useConfig();
|
||||
const hasModel = () =>
|
||||
["modelValue", "model-value"].some((key) =>
|
||||
Object.hasOwn(instance.vnode.props ?? {}, key),
|
||||
);
|
||||
const model = useChoiceValue<SelectValue | undefined>(
|
||||
() => (hasModel() ? props.modelValue : props.value),
|
||||
() =>
|
||||
props.defaultValue ?? (props.selectionMode === "multiple" ? [] : null),
|
||||
["modelValue", "model-value", "value"],
|
||||
(value) => {
|
||||
const next = value ?? (props.selectionMode === "multiple" ? [] : null);
|
||||
emit("update:modelValue", next);
|
||||
emit("change", next);
|
||||
},
|
||||
);
|
||||
const value = computed<SelectValue>(() => {
|
||||
const raw = model.value.value;
|
||||
const controlled = ["modelValue", "model-value", "value"].some((key) =>
|
||||
Object.hasOwn(instance.vnode.props ?? {}, key),
|
||||
);
|
||||
if (controlled)
|
||||
return raw ?? (props.selectionMode === "multiple" ? [] : null);
|
||||
// Uncontrolled mode changes adapt the accepted value's public shape,
|
||||
// without emitting an edit or mutating the captured reset baseline.
|
||||
if (props.selectionMode === "multiple")
|
||||
return raw == null ? [] : Array.isArray(raw) ? raw : [raw];
|
||||
return Array.isArray(raw) ? (raw[0] ?? null) : (raw ?? null);
|
||||
});
|
||||
const keys = computed(() => {
|
||||
const raw = value.value;
|
||||
if (
|
||||
props.selectionMode === "multiple" &&
|
||||
raw !== null &&
|
||||
!Array.isArray(raw)
|
||||
)
|
||||
throw new TypeError("Multiple Select expects a key array.");
|
||||
const keys = copyKeys(
|
||||
raw === null ? [] : Array.isArray(raw) ? raw : [raw],
|
||||
);
|
||||
if (props.selectionMode === "single" && keys.length > 1)
|
||||
throw new TypeError("Single Select expects one key or null.");
|
||||
return Object.freeze(keys);
|
||||
});
|
||||
const planned = shallowRef<CollectionRecord[]>([]),
|
||||
discovered = shallowRef<CollectionRecord[]>([]);
|
||||
const collection = shallowRef<OwnedCollection>();
|
||||
const plannedComplete = ref(false);
|
||||
const records = computed(() => {
|
||||
const explicit = new Set<CollectionKey>();
|
||||
const result = new Map(
|
||||
(props.items || plannedComplete.value ? [] : discovered.value).map(
|
||||
(record) => [record.key, record],
|
||||
),
|
||||
);
|
||||
if (!props.items)
|
||||
planned.value.forEach((record) => result.set(record.key, record));
|
||||
props.items?.forEach((item) => {
|
||||
assertKey(item.id);
|
||||
if (explicit.has(item.id))
|
||||
throw new Error(`Duplicate collection key: ${item.id}`);
|
||||
explicit.add(item.id);
|
||||
result.set(item.id, {
|
||||
key: item.id,
|
||||
text: item.textValue,
|
||||
disabled:
|
||||
!!item.isDisabled ||
|
||||
!!planned.value.find((record) => record.key === item.id)?.disabled,
|
||||
});
|
||||
});
|
||||
return [...result.values()].map((record) => ({
|
||||
...record,
|
||||
disabled: record.disabled || !!props.disabledKeys?.includes(record.key),
|
||||
}));
|
||||
});
|
||||
watchEffect(() => {
|
||||
if (!collection.value) return;
|
||||
const next = collection.value.items();
|
||||
if (JSON.stringify(next) !== JSON.stringify(discovered.value))
|
||||
discovered.value = next;
|
||||
});
|
||||
const successful = computed(() =>
|
||||
keys.value.filter((key) =>
|
||||
records.value.some((record) => record.key === key && !record.disabled),
|
||||
),
|
||||
);
|
||||
const field = useChoiceField(props, attrs, {
|
||||
kind: "group",
|
||||
value,
|
||||
validate: (value) => props.validate?.(value),
|
||||
satisfied: () => successful.value.length > 0,
|
||||
requiredMessage: "请选择一个选项。",
|
||||
});
|
||||
provide(disabledContextKey, field.field.disabled);
|
||||
const nativeSelect = ref<HTMLSelectElement>();
|
||||
function restoreNative() {
|
||||
if (!nativeSelect.value) return;
|
||||
[...nativeSelect.value.options].forEach((option) => {
|
||||
const key = records.value[Number(option.dataset.index)]?.key;
|
||||
option.selected =
|
||||
option.dataset.index === undefined
|
||||
? !successful.value.length
|
||||
: key !== undefined && successful.value.includes(key);
|
||||
});
|
||||
}
|
||||
const trigger = ref<HTMLElement>(),
|
||||
proxy = ref<HTMLInputElement>();
|
||||
const openModel = useChoiceValue<boolean | undefined>(
|
||||
() =>
|
||||
Object.hasOwn(instance.vnode.props ?? {}, "open")
|
||||
? props.open
|
||||
: props.isOpen,
|
||||
() => props.defaultOpen,
|
||||
["open", "isOpen", "is-open"],
|
||||
(open) => {
|
||||
emit("update:open", !!open);
|
||||
emit("openChange", !!open);
|
||||
},
|
||||
);
|
||||
const open = computed(() => !!openModel.value.value);
|
||||
const slotsMap = computed(() =>
|
||||
selectVariants({ variant: props.variant, fullWidth: props.fullWidth }),
|
||||
);
|
||||
const listId = `${field.field.controlId.value}-listbox`,
|
||||
valueId = `${field.field.controlId.value}-value`;
|
||||
const clearCount = ref(0),
|
||||
intent = ref<"first" | "last" | "selected">("selected");
|
||||
function setOpen(next: boolean) {
|
||||
if (next && (field.field.disabled.value || field.field.readOnly.value))
|
||||
return;
|
||||
if (next !== open.value) openModel.request(next);
|
||||
}
|
||||
function request(next: CollectionKey[]) {
|
||||
if (field.field.disabled.value || field.field.readOnly.value) return;
|
||||
if (
|
||||
next.some(
|
||||
(key) =>
|
||||
records.value.find((record) => record.key === key)?.disabled &&
|
||||
!keys.value.includes(key),
|
||||
)
|
||||
)
|
||||
return;
|
||||
if (
|
||||
next.length === keys.value.length &&
|
||||
next.every((key) => keys.value.includes(key))
|
||||
)
|
||||
return;
|
||||
field.edit();
|
||||
model.request(
|
||||
props.selectionMode === "multiple" ? [...next] : (next[0] ?? null),
|
||||
);
|
||||
}
|
||||
let query = "",
|
||||
lastSearch = 0;
|
||||
function search(character: string) {
|
||||
const now = Date.now();
|
||||
query = now - lastSearch > 1000 ? character : query + character;
|
||||
lastSearch = now;
|
||||
const needle = [...query].every((c) => c === query[0]) ? query[0] : query;
|
||||
const available = records.value.filter((record) => !record.disabled);
|
||||
const index = available.findIndex((record) =>
|
||||
keys.value.includes(record.key),
|
||||
);
|
||||
const ordered =
|
||||
needle.length > 1 && index >= 0
|
||||
? [...available.slice(index), ...available.slice(0, index)]
|
||||
: [...available.slice(index + 1), ...available.slice(0, index + 1)];
|
||||
const collator = new Intl.Collator(config?.locale.value, {
|
||||
usage: "search",
|
||||
sensitivity: "base",
|
||||
});
|
||||
const match = ordered.find(
|
||||
(record) =>
|
||||
collator.compare(record.text.slice(0, needle.length), needle) === 0,
|
||||
);
|
||||
if (match)
|
||||
request(
|
||||
props.selectionMode === "multiple"
|
||||
? [...new Set([...keys.value, match.key])]
|
||||
: [match.key],
|
||||
);
|
||||
}
|
||||
async function focusCollection() {
|
||||
await nextTick();
|
||||
if (open.value) await collection.value?.focus(intent.value);
|
||||
}
|
||||
provide(collectionOwnerKey, {
|
||||
keys,
|
||||
mode: computed(() => props.selectionMode),
|
||||
disabled: field.field.disabled,
|
||||
readOnly: field.field.readOnly,
|
||||
disabledKeys: computed(() => [
|
||||
...(props.disabledKeys ?? []),
|
||||
...(props.items
|
||||
?.filter((item) => item.isDisabled)
|
||||
.map((item) => item.id) ?? []),
|
||||
]),
|
||||
id: listId,
|
||||
ariaLabel: () => attrs["aria-label"] as string | undefined,
|
||||
labelledBy: () =>
|
||||
field.labelledBy() ??
|
||||
(attrs["aria-label"] ? undefined : trigger.value?.id),
|
||||
request,
|
||||
leave: () => {
|
||||
// Move the native Tab starting point back to the trigger before default
|
||||
// traversal, avoiding Popover FocusScope's loop and Teleport DOM order.
|
||||
trigger.value?.focus({ preventScroll: true });
|
||||
setOpen(false);
|
||||
},
|
||||
action: () => {
|
||||
if (props.selectionMode === "single") setOpen(false);
|
||||
},
|
||||
connect: (next) => {
|
||||
if (collection.value && collection.value !== next)
|
||||
throw new Error("Select supports one ListBox.");
|
||||
collection.value = next;
|
||||
return () => {
|
||||
if (collection.value === next) collection.value = undefined;
|
||||
};
|
||||
},
|
||||
});
|
||||
provide(selectKey, {
|
||||
field,
|
||||
slots: slotsMap,
|
||||
keys,
|
||||
records,
|
||||
open,
|
||||
setOpen,
|
||||
trigger,
|
||||
valueId,
|
||||
listId,
|
||||
collection,
|
||||
intent,
|
||||
focusCollection,
|
||||
placeholder: () => props.placeholder,
|
||||
ariaLabel: () => attrs["aria-label"] as string | undefined,
|
||||
selectedItems: computed(() =>
|
||||
keys.value.map((key) => ({
|
||||
key,
|
||||
textValue:
|
||||
records.value.find((record) => record.key === key)?.text ??
|
||||
String(key),
|
||||
})),
|
||||
),
|
||||
clearCount,
|
||||
search,
|
||||
registerClear: () => {
|
||||
clearCount.value++;
|
||||
let active = true;
|
||||
return () => {
|
||||
if (active) {
|
||||
active = false;
|
||||
clearCount.value--;
|
||||
}
|
||||
};
|
||||
},
|
||||
clear: () => {
|
||||
if (
|
||||
keys.value.length &&
|
||||
!field.field.disabled.value &&
|
||||
!field.field.readOnly.value
|
||||
) {
|
||||
request([]);
|
||||
emit("clear");
|
||||
}
|
||||
},
|
||||
});
|
||||
useChoiceForm(
|
||||
proxy,
|
||||
() => {
|
||||
model.reset();
|
||||
field.reset();
|
||||
setOpen(false);
|
||||
},
|
||||
() => {
|
||||
field.validity(proxy.value);
|
||||
void nextTick(restoreNative);
|
||||
},
|
||||
);
|
||||
watchEffect(() => {
|
||||
field.validity(proxy.value);
|
||||
});
|
||||
expose({
|
||||
element: trigger,
|
||||
focus: () => trigger.value?.focus(),
|
||||
open: () => setOpen(true),
|
||||
close: () => setOpen(false),
|
||||
});
|
||||
return () => {
|
||||
const rendered = slots.default?.({
|
||||
isOpen: open.value,
|
||||
value: value.value,
|
||||
selectedItems: keys.value.map((key) => ({
|
||||
key,
|
||||
textValue:
|
||||
records.value.find((item) => item.key === key)?.text ?? String(key),
|
||||
})),
|
||||
});
|
||||
const children = Array.isArray(rendered)
|
||||
? rendered
|
||||
: rendered == null
|
||||
? []
|
||||
: [rendered];
|
||||
const plan = planSelectItems(children);
|
||||
if (JSON.stringify(plan.records) !== JSON.stringify(planned.value))
|
||||
planned.value = plan.records;
|
||||
plannedComplete.value = plan.complete;
|
||||
// Touch keys now: reject malformed models during SSR as well as on edit.
|
||||
void keys.value;
|
||||
const nodes = field.prepare(children, true);
|
||||
return h(
|
||||
Popover,
|
||||
{ open: open.value, isNonModal: true, "onUpdate:open": setOpen },
|
||||
{
|
||||
default: () =>
|
||||
h(
|
||||
props.as,
|
||||
mergeProps(attrs, {
|
||||
class: slotsMap.value.base(),
|
||||
"data-slot": "select",
|
||||
"data-invalid": field.field.invalid.value || undefined,
|
||||
"data-disabled": field.field.disabled.value || undefined,
|
||||
onClick: (event: MouseEvent) => {
|
||||
if (event.defaultPrevented) return;
|
||||
const label = (event.target as Element).closest?.(
|
||||
'[data-slot="label"]',
|
||||
);
|
||||
if (
|
||||
label?.id &&
|
||||
field.labelledBy()?.split(" ").includes(label.id)
|
||||
)
|
||||
trigger.value?.focus();
|
||||
},
|
||||
}),
|
||||
[
|
||||
...nodes,
|
||||
validationInput(
|
||||
proxy,
|
||||
props,
|
||||
field.field.disabled.value || field.field.readOnly.value,
|
||||
field.behavior.value,
|
||||
(event) =>
|
||||
field.invalidEvent(event, () => trigger.value?.focus()),
|
||||
props.isRequired && field.behavior.value === "native",
|
||||
successful.value.length > 0,
|
||||
),
|
||||
h(
|
||||
"select",
|
||||
{
|
||||
ref: nativeSelect,
|
||||
id: `${field.field.controlId.value}-native`,
|
||||
class: "hv-choice-input",
|
||||
"aria-hidden": "true",
|
||||
tabindex: -1,
|
||||
name: successful.value.length ? props.name : undefined,
|
||||
form: props.form,
|
||||
multiple: props.selectionMode === "multiple",
|
||||
autocomplete: props.autoComplete,
|
||||
disabled: field.field.disabled.value,
|
||||
onChange: (event: Event) => {
|
||||
const element = event.currentTarget as HTMLSelectElement;
|
||||
const next = [...element.selectedOptions]
|
||||
.filter((option) => !option.disabled)
|
||||
.map(
|
||||
(option) =>
|
||||
records.value[Number(option.dataset.index)]?.key,
|
||||
)
|
||||
.filter(
|
||||
(key): key is CollectionKey => key !== undefined,
|
||||
);
|
||||
request(next);
|
||||
// Autofill is a proposal too: restore the parent's accepted value.
|
||||
void nextTick(restoreNative);
|
||||
},
|
||||
},
|
||||
[
|
||||
...(props.selectionMode === "single"
|
||||
? [
|
||||
h(
|
||||
"option",
|
||||
{
|
||||
value: "",
|
||||
disabled: true,
|
||||
selected: !successful.value.length,
|
||||
},
|
||||
props.placeholder,
|
||||
),
|
||||
]
|
||||
: []),
|
||||
...records.value.map((record, index) =>
|
||||
h(
|
||||
"option",
|
||||
{
|
||||
key: encodeKey(record.key),
|
||||
value: String(record.key),
|
||||
"data-index": index,
|
||||
disabled: record.disabled,
|
||||
selected: successful.value.includes(record.key),
|
||||
},
|
||||
record.text,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
},
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,51 @@
|
||||
<script setup lang="ts">
|
||||
import { inject, mergeProps, onScopeDispose, useAttrs } from "vue";
|
||||
import { selectTriggerDisabledKey, useSelect } from "./context";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
withDefaults(defineProps<{ as?: string }>(), { as: "span" });
|
||||
const ctx = useSelect(),
|
||||
attrs = useAttrs();
|
||||
const disabled = inject(selectTriggerDisabledKey, ctx.field.field.disabled);
|
||||
onScopeDispose(ctx.registerClear());
|
||||
function click(event: MouseEvent) {
|
||||
// Always isolate this pointer-only affordance from its enclosing trigger.
|
||||
event.stopPropagation();
|
||||
if (!event.defaultPrevented && event.button === 0 && !disabled.value)
|
||||
ctx.clear();
|
||||
event.preventDefault();
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<component
|
||||
:is="as"
|
||||
v-bind="
|
||||
mergeProps(attrs, {
|
||||
onClick: click,
|
||||
onPointerdown: (event: PointerEvent) => event.stopPropagation(),
|
||||
})
|
||||
"
|
||||
:class="[ctx.slots.value.clearButton(), attrs.class]"
|
||||
aria-hidden="true"
|
||||
data-slot="select-clear-button"
|
||||
:data-empty="!ctx.keys.value.length || undefined"
|
||||
>
|
||||
<slot>
|
||||
<svg
|
||||
fill="none"
|
||||
width="16"
|
||||
height="16"
|
||||
role="presentation"
|
||||
viewBox="0 0 16 16"
|
||||
aria-hidden="true"
|
||||
data-slot="select-clear-button-icon"
|
||||
>
|
||||
<path
|
||||
d="M3.47 3.47a.75.75 0 0 1 1.06 0L8 6.94l3.47-3.47a.75.75 0 1 1 1.06 1.06L9.06 8l3.47 3.47a.75.75 0 1 1-1.06 1.06L8 9.06l-3.47 3.47a.75.75 0 0 1-1.06-1.06L6.94 8 3.47 4.53a.75.75 0 0 1 0-1.06Z"
|
||||
fill="currentColor"
|
||||
fill-rule="evenodd"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</slot>
|
||||
</component>
|
||||
</template>
|
||||
@@ -0,0 +1,46 @@
|
||||
<script lang="ts">
|
||||
import { cloneVNode, defineComponent, h, mergeProps } from "vue";
|
||||
import { useSelect } from "./context";
|
||||
import { overlayNodes } from "../overlay/OverlayAction";
|
||||
// Default icon adapted from HeroUI ce90ea3 icons.tsx (Apache-2.0).
|
||||
export default defineComponent({
|
||||
name: "SelectIndicator",
|
||||
inheritAttrs: false,
|
||||
setup(_props, { attrs, slots }) {
|
||||
const ctx = useSelect();
|
||||
return () => {
|
||||
const children = overlayNodes(slots.default?.());
|
||||
const props = mergeProps(attrs, {
|
||||
class: ctx.slots.value.indicator(),
|
||||
"data-open": ctx.open.value || undefined,
|
||||
"aria-hidden": "true",
|
||||
});
|
||||
if (children.length === 1)
|
||||
return cloneVNode(children[0], {
|
||||
...props,
|
||||
"data-slot": "select-indicator",
|
||||
});
|
||||
return h(
|
||||
"svg",
|
||||
{
|
||||
...props,
|
||||
"data-slot": "select-default-indicator",
|
||||
fill: "none",
|
||||
height: 16,
|
||||
width: 16,
|
||||
role: "presentation",
|
||||
viewBox: "0 0 16 16",
|
||||
},
|
||||
[
|
||||
h("path", {
|
||||
d: "M2.97 5.47a.75.75 0 0 1 1.06 0L8 9.44l3.97-3.97a.75.75 0 1 1 1.06 1.06l-4.5 4.5a.75.75 0 0 1-1.06 0l-4.5-4.5a.75.75 0 0 1 0-1.06",
|
||||
fill: "currentColor",
|
||||
"fill-rule": "evenodd",
|
||||
"clip-rule": "evenodd",
|
||||
}),
|
||||
],
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
import { mergeProps, useAttrs } from "vue";
|
||||
import PopoverContent from "../popover/PopoverContent.vue";
|
||||
import { useSelect } from "./context";
|
||||
import type { OverlayPlacement } from "../overlay/placement";
|
||||
defineOptions({ name: "SelectPopover", inheritAttrs: false });
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
placement?: OverlayPlacement;
|
||||
offset?: number;
|
||||
to?: string | HTMLElement;
|
||||
shouldFlip?: boolean;
|
||||
containerPadding?: number;
|
||||
}>(),
|
||||
{ placement: "bottom", offset: 8, shouldFlip: true, containerPadding: 12 },
|
||||
);
|
||||
const ctx = useSelect(),
|
||||
attrs = useAttrs();
|
||||
function openFocus(event: Event) {
|
||||
if (!event.defaultPrevented) {
|
||||
event.preventDefault();
|
||||
void ctx.focusCollection();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<PopoverContent
|
||||
:placement="placement"
|
||||
:offset="offset"
|
||||
:to="to"
|
||||
:should-flip="shouldFlip"
|
||||
:container-padding="containerPadding"
|
||||
v-bind="mergeProps(attrs, { onOpenAutoFocus: openFocus })"
|
||||
:id="`${ctx.listId}-popover`"
|
||||
role="presentation"
|
||||
:class="[ctx.slots.value.popover(), attrs.class]"
|
||||
data-slot="select-popover"
|
||||
:aria-labelledby="
|
||||
ctx.field.labelledBy() ??
|
||||
ctx.trigger.value?.id ??
|
||||
ctx.field.field.controlId.value
|
||||
"
|
||||
:style="{
|
||||
'--trigger-width': 'var(--reka-popover-trigger-width)',
|
||||
'--trigger-anchor-point': 'var(--reka-popper-transform-origin)',
|
||||
}"
|
||||
>
|
||||
<slot />
|
||||
</PopoverContent>
|
||||
</template>
|
||||
@@ -0,0 +1,158 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
h,
|
||||
mergeProps,
|
||||
provide,
|
||||
ref,
|
||||
watch,
|
||||
} from "vue";
|
||||
import { PopoverAnchor, injectPopoverRootContext } from "reka-ui";
|
||||
import OverlayAction from "../overlay/OverlayAction";
|
||||
import { usePopover } from "../popover/context";
|
||||
import { mergeIds } from "../field/context";
|
||||
import { selectTriggerDisabledKey, useSelect } from "./context";
|
||||
export default defineComponent({
|
||||
name: "SelectTrigger",
|
||||
inheritAttrs: false,
|
||||
props: { as: { type: String, default: "button" }, isDisabled: Boolean },
|
||||
setup(props, { attrs, slots, expose }) {
|
||||
const ctx = useSelect();
|
||||
const popup = usePopover(),
|
||||
root = injectPopoverRootContext();
|
||||
watch(
|
||||
ctx.trigger,
|
||||
(element) => {
|
||||
root.triggerElement.value = element;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
root.triggerId = ctx.field.field.controlId.value;
|
||||
const disabled = computed(
|
||||
() =>
|
||||
props.isDisabled ||
|
||||
ctx.field.field.disabled.value ||
|
||||
attrs.disabled === true ||
|
||||
attrs.disabled === "",
|
||||
);
|
||||
provide(selectTriggerDisabledKey, disabled);
|
||||
const focused = ref(false),
|
||||
keyboard = ref(true);
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.isComposing ||
|
||||
event.keyCode === 229 ||
|
||||
disabled.value
|
||||
)
|
||||
return;
|
||||
keyboard.value = true;
|
||||
if (
|
||||
!ctx.open.value &&
|
||||
["Backspace", "Delete"].includes(event.key) &&
|
||||
ctx.clearCount.value &&
|
||||
ctx.keys.value.length
|
||||
) {
|
||||
event.preventDefault();
|
||||
ctx.clear();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!ctx.open.value &&
|
||||
event.key.length === 1 &&
|
||||
event.key !== " " &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.altKey
|
||||
) {
|
||||
event.preventDefault();
|
||||
ctx.search(event.key);
|
||||
return;
|
||||
}
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
ctx.intent.value = ctx.keys.value.length
|
||||
? "selected"
|
||||
: event.key === "ArrowUp"
|
||||
? "last"
|
||||
: "first";
|
||||
if (ctx.open.value) void ctx.focusCollection();
|
||||
else ctx.setOpen(true);
|
||||
}
|
||||
}
|
||||
expose({ focus: () => ctx.trigger.value?.focus(), element: ctx.trigger });
|
||||
return () =>
|
||||
h(
|
||||
PopoverAnchor,
|
||||
{ asChild: true },
|
||||
{
|
||||
default: () =>
|
||||
h(
|
||||
OverlayAction,
|
||||
{
|
||||
asChild: true,
|
||||
isDisabled: disabled.value,
|
||||
activate: popup.state.toggle,
|
||||
},
|
||||
{
|
||||
default: () =>
|
||||
h(
|
||||
props.as,
|
||||
mergeProps(attrs, {
|
||||
ref: ctx.trigger,
|
||||
id: attrs.id ?? ctx.field.field.controlId.value,
|
||||
type:
|
||||
props.as === "button"
|
||||
? (attrs.type ?? "button")
|
||||
: undefined,
|
||||
role: "combobox",
|
||||
"aria-haspopup": "listbox",
|
||||
"aria-expanded": ctx.open.value,
|
||||
"aria-controls": ctx.open.value ? ctx.listId : undefined,
|
||||
"aria-required":
|
||||
ctx.field.field.required.value || undefined,
|
||||
"aria-invalid":
|
||||
ctx.field.field.invalid.value || undefined,
|
||||
"aria-disabled": disabled.value || undefined,
|
||||
"aria-label": attrs["aria-label"] ?? ctx.ariaLabel(),
|
||||
"aria-labelledby":
|
||||
attrs["aria-labelledby"] ??
|
||||
((attrs["aria-label"] ?? ctx.ariaLabel())
|
||||
? undefined
|
||||
: mergeIds(ctx.field.labelledBy(), ctx.valueId)),
|
||||
"aria-describedby": mergeIds(
|
||||
attrs["aria-describedby"] as string | undefined,
|
||||
ctx.field.describedBy(),
|
||||
),
|
||||
disabled: disabled.value || undefined,
|
||||
class: ctx.slots.value.trigger(),
|
||||
"data-slot": "select-trigger",
|
||||
"data-disabled": disabled.value || undefined,
|
||||
"data-focused": focused.value || undefined,
|
||||
"data-focus-visible":
|
||||
(focused.value &&
|
||||
(keyboard.value ||
|
||||
ctx.trigger.value?.matches(":focus-visible"))) ||
|
||||
undefined,
|
||||
onKeydown: keydown,
|
||||
onPointerdown: () => {
|
||||
keyboard.value = false;
|
||||
ctx.intent.value = "selected";
|
||||
},
|
||||
onFocus: () => {
|
||||
focused.value = true;
|
||||
},
|
||||
onBlur: () => {
|
||||
focused.value = false;
|
||||
},
|
||||
}),
|
||||
slots.default?.(),
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,40 @@
|
||||
<script setup lang="ts">
|
||||
import { useSelect, type SelectSelectedItem } from "./context";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
withDefaults(defineProps<{ as?: string }>(), { as: "span" });
|
||||
defineSlots<{
|
||||
default?: (state: {
|
||||
defaultChildren: string;
|
||||
isPlaceholder: boolean;
|
||||
selectedItems: SelectSelectedItem[];
|
||||
state: { selectedItems: SelectSelectedItem[]; isOpen: boolean };
|
||||
}) => unknown;
|
||||
}>();
|
||||
const ctx = useSelect();
|
||||
const valueText = () =>
|
||||
ctx.keys.value.length
|
||||
? ctx.selectedItems.value.map((item) => item.textValue).join(", ")
|
||||
: ctx.placeholder();
|
||||
</script>
|
||||
<template>
|
||||
<component
|
||||
:is="as"
|
||||
v-bind="$attrs"
|
||||
:id="ctx.valueId"
|
||||
:class="[ctx.slots.value.value(), $attrs.class]"
|
||||
data-slot="select-value"
|
||||
:data-placeholder="!ctx.keys.value.length || undefined"
|
||||
>
|
||||
<slot
|
||||
:default-children="valueText()"
|
||||
:is-placeholder="!ctx.keys.value.length"
|
||||
:selected-items="ctx.selectedItems.value"
|
||||
:state="{
|
||||
selectedItems: ctx.selectedItems.value,
|
||||
isOpen: ctx.open.value,
|
||||
}"
|
||||
>
|
||||
{{ valueText() }}
|
||||
</slot>
|
||||
</component>
|
||||
</template>
|
||||
@@ -0,0 +1,44 @@
|
||||
import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue";
|
||||
import type { CollectionKey } from "../collection/keys";
|
||||
import type { CollectionRecord, OwnedCollection } from "../collection/owner";
|
||||
import type { useChoiceField } from "../choice/shared";
|
||||
import type { selectVariants } from "@heroui-vue/styles";
|
||||
export type SelectValue = CollectionKey | CollectionKey[] | null;
|
||||
export interface SelectItem {
|
||||
id: CollectionKey;
|
||||
textValue: string;
|
||||
isDisabled?: boolean;
|
||||
}
|
||||
export interface SelectSelectedItem {
|
||||
key: CollectionKey;
|
||||
textValue: string;
|
||||
}
|
||||
export interface SelectContext {
|
||||
field: ReturnType<typeof useChoiceField<SelectValue>>;
|
||||
slots: ComputedRef<ReturnType<typeof selectVariants>>;
|
||||
keys: ComputedRef<readonly CollectionKey[]>;
|
||||
selectedItems: ComputedRef<SelectSelectedItem[]>;
|
||||
records: ComputedRef<CollectionRecord[]>;
|
||||
open: ComputedRef<boolean>;
|
||||
setOpen: (open: boolean) => void;
|
||||
trigger: Ref<HTMLElement | undefined>;
|
||||
valueId: string;
|
||||
listId: string;
|
||||
placeholder: () => string;
|
||||
ariaLabel: () => string | undefined;
|
||||
clearCount: Ref<number>;
|
||||
registerClear: () => () => void;
|
||||
clear: () => void;
|
||||
search: (key: string) => void;
|
||||
collection: Ref<OwnedCollection | undefined>;
|
||||
intent: Ref<"first" | "last" | "selected">;
|
||||
focusCollection: () => Promise<void>;
|
||||
}
|
||||
export const selectKey: InjectionKey<SelectContext> = Symbol("hv-select");
|
||||
export const selectTriggerDisabledKey: InjectionKey<ComputedRef<boolean>> =
|
||||
Symbol("hv-select-trigger-disabled");
|
||||
export function useSelect() {
|
||||
const context = inject(selectKey);
|
||||
if (!context) throw new Error("Select parts require Select.");
|
||||
return context;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { Fragment, Text, isVNode, type VNode, type VNodeChild } from "vue";
|
||||
import { assertKey, type CollectionKey } from "../collection/keys";
|
||||
import type { CollectionRecord } from "../collection/owner";
|
||||
function name(node: VNode) {
|
||||
const type = node.type as { name?: string; __name?: string };
|
||||
return type.name ?? type.__name;
|
||||
}
|
||||
function children(node: VNode): VNodeChild[] {
|
||||
if (Array.isArray(node.children)) return node.children as VNodeChild[];
|
||||
if (node.children && typeof node.children === "object") {
|
||||
const result = (
|
||||
node.children as { default?: () => VNodeChild }
|
||||
).default?.();
|
||||
return Array.isArray(result) ? result : result == null ? [] : [result];
|
||||
}
|
||||
return typeof node.children === "string" ? [node.children] : [];
|
||||
}
|
||||
function text(nodes: VNodeChild[]): string {
|
||||
return nodes
|
||||
.map((node) => {
|
||||
if (typeof node === "string" || typeof node === "number")
|
||||
return String(node);
|
||||
if (Array.isArray(node)) return text(node);
|
||||
if (!isVNode(node)) return "";
|
||||
if (node.type === Text) return String(node.children);
|
||||
// Descriptions/icons and arbitrary components are not option name sources.
|
||||
if (
|
||||
node.type === Fragment ||
|
||||
typeof node.type === "string" ||
|
||||
name(node) === "Label"
|
||||
)
|
||||
return text(children(node));
|
||||
return "";
|
||||
})
|
||||
.join("")
|
||||
.trim();
|
||||
}
|
||||
/** Inspect known collection slots only; never execute arbitrary setup/render. */
|
||||
export function planSelectItems(nodes: VNodeChild[]) {
|
||||
const records: CollectionRecord[] = [];
|
||||
let found = false,
|
||||
opaque = false;
|
||||
function add(record: CollectionRecord) {
|
||||
assertKey(record.key);
|
||||
if (records.some((item) => item.key === record.key))
|
||||
throw new Error(`Duplicate collection key: ${record.key}`);
|
||||
records.push(record);
|
||||
}
|
||||
function walk(
|
||||
nodes: VNodeChild[],
|
||||
inside = false,
|
||||
blocked: readonly CollectionKey[] = [],
|
||||
) {
|
||||
for (const node of nodes) {
|
||||
if (Array.isArray(node)) {
|
||||
walk(node, inside, blocked);
|
||||
continue;
|
||||
}
|
||||
if (!isVNode(node)) continue;
|
||||
const component = name(node);
|
||||
if (component === "ListBoxItem") {
|
||||
const key = node.props?.id;
|
||||
const disabled = node.props?.isDisabled ?? node.props?.["is-disabled"];
|
||||
add({
|
||||
key,
|
||||
text:
|
||||
node.props?.textValue ??
|
||||
node.props?.["text-value"] ??
|
||||
text(children(node)),
|
||||
disabled:
|
||||
disabled === true || disabled === "" || blocked.includes(key),
|
||||
});
|
||||
} else if (component === "ListBox") {
|
||||
found = true;
|
||||
const disabledKeys =
|
||||
node.props?.disabledKeys ?? node.props?.["disabled-keys"] ?? [];
|
||||
const keys = [...blocked, ...disabledKeys] as CollectionKey[];
|
||||
if (node.props?.items) {
|
||||
const slot = (
|
||||
node.children as { default?: (state: unknown) => VNodeChild[] }
|
||||
)?.default;
|
||||
const items = node.props.items as {
|
||||
id: CollectionKey;
|
||||
textValue?: string;
|
||||
isDisabled?: boolean;
|
||||
}[];
|
||||
items.forEach((item, index) => {
|
||||
const before = records.length;
|
||||
if (slot) {
|
||||
const rendered = slot({ item, index });
|
||||
walk(Array.isArray(rendered) ? rendered : [rendered], true, keys);
|
||||
}
|
||||
if (records.length === before)
|
||||
add({
|
||||
key: item.id,
|
||||
text: item.textValue ?? String(item.id),
|
||||
disabled: !!item.isDisabled || keys.includes(item.id),
|
||||
});
|
||||
else if (item.isDisabled)
|
||||
records.slice(before).forEach((record) => {
|
||||
record.disabled = true;
|
||||
});
|
||||
});
|
||||
} else walk(children(node), true, keys);
|
||||
} else if (
|
||||
node.type === Fragment ||
|
||||
typeof node.type === "string" ||
|
||||
["SelectPopover", "ListBoxSection"].includes(component ?? "")
|
||||
)
|
||||
walk(children(node), inside, blocked);
|
||||
else if (
|
||||
inside &&
|
||||
component &&
|
||||
!["Header", "Separator"].includes(component)
|
||||
)
|
||||
opaque = true;
|
||||
}
|
||||
}
|
||||
walk(nodes);
|
||||
return { records, complete: found && !opaque };
|
||||
}
|
||||
Reference in New Issue
Block a user