511 lines
17 KiB
Vue
511 lines
17 KiB
Vue
<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>
|