@salmonui/dropdowns 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +41 -2
- package/dist/combobox/Combobox.d.ts +54 -0
- package/dist/combobox/Combobox.d.ts.map +1 -0
- package/dist/combobox/Combobox.js +485 -0
- package/dist/combobox/Combobox.js.map +1 -0
- package/dist/combobox/ComboboxField.d.ts +9 -0
- package/dist/combobox/ComboboxField.d.ts.map +1 -0
- package/dist/combobox/ComboboxField.js +13 -0
- package/dist/combobox/ComboboxField.js.map +1 -0
- package/dist/combobox/columns-grid.d.ts +20 -0
- package/dist/combobox/columns-grid.d.ts.map +1 -0
- package/dist/combobox/columns-grid.js +106 -0
- package/dist/combobox/columns-grid.js.map +1 -0
- package/dist/combobox/columns.d.ts +45 -0
- package/dist/combobox/columns.d.ts.map +1 -0
- package/dist/combobox/columns.js +42 -0
- package/dist/combobox/columns.js.map +1 -0
- package/dist/combobox.css +706 -0
- package/dist/combobox.d.ts +6 -0
- package/dist/combobox.d.ts.map +1 -0
- package/dist/combobox.js +10 -0
- package/dist/combobox.js.map +1 -0
- package/dist/dropdown/core.d.ts +178 -0
- package/dist/dropdown/core.d.ts.map +1 -0
- package/dist/dropdown/core.js +591 -0
- package/dist/dropdown/core.js.map +1 -0
- package/dist/dropdown/field.d.ts +19 -0
- package/dist/dropdown/field.d.ts.map +1 -0
- package/dist/dropdown/field.js +48 -0
- package/dist/dropdown/field.js.map +1 -0
- package/dist/dropdown/locale.d.ts +3 -0
- package/dist/dropdown/locale.d.ts.map +1 -0
- package/dist/dropdown/locale.js +23 -0
- package/dist/dropdown/locale.js.map +1 -0
- package/dist/dropdown/overlay.d.ts +14 -0
- package/dist/dropdown/overlay.d.ts.map +1 -0
- package/dist/dropdown/overlay.js +46 -0
- package/dist/dropdown/overlay.js.map +1 -0
- package/dist/dropdown/popup.d.ts +44 -0
- package/dist/dropdown/popup.d.ts.map +1 -0
- package/dist/dropdown/popup.js +183 -0
- package/dist/dropdown/popup.js.map +1 -0
- package/dist/dropdown/types.d.ts +197 -0
- package/dist/dropdown/types.d.ts.map +1 -0
- package/dist/dropdown/types.js +4 -0
- package/dist/dropdown/types.js.map +1 -0
- package/dist/internal/caret.d.ts +18 -0
- package/dist/internal/caret.d.ts.map +1 -0
- package/dist/internal/caret.js +73 -0
- package/dist/internal/caret.js.map +1 -0
- package/dist/internal/collection/collection.d.ts +53 -0
- package/dist/internal/collection/collection.d.ts.map +1 -0
- package/dist/internal/collection/collection.js +161 -0
- package/dist/internal/collection/collection.js.map +1 -0
- package/dist/internal/collection/fold.d.ts +15 -0
- package/dist/internal/collection/fold.d.ts.map +1 -0
- package/dist/internal/collection/fold.js +33 -0
- package/dist/internal/collection/fold.js.map +1 -0
- package/dist/internal/collection/remote.d.ts +76 -0
- package/dist/internal/collection/remote.d.ts.map +1 -0
- package/dist/internal/collection/remote.js +261 -0
- package/dist/internal/collection/remote.js.map +1 -0
- package/dist/internal/collection/search.d.ts +28 -0
- package/dist/internal/collection/search.d.ts.map +1 -0
- package/dist/internal/collection/search.js +119 -0
- package/dist/internal/collection/search.js.map +1 -0
- package/dist/internal/collection/selection.d.ts +33 -0
- package/dist/internal/collection/selection.d.ts.map +1 -0
- package/dist/internal/collection/selection.js +82 -0
- package/dist/internal/collection/selection.js.map +1 -0
- package/dist/internal/collection/view.d.ts +22 -0
- package/dist/internal/collection/view.d.ts.map +1 -0
- package/dist/internal/collection/view.js +83 -0
- package/dist/internal/collection/view.js.map +1 -0
- package/dist/internal/select.d.ts +2 -0
- package/dist/internal/select.d.ts.map +1 -0
- package/dist/internal/select.js +7 -0
- package/dist/internal/select.js.map +1 -0
- package/dist/listbox/Listbox.d.ts +8 -0
- package/dist/listbox/Listbox.d.ts.map +1 -0
- package/dist/listbox/Listbox.js +887 -0
- package/dist/listbox/Listbox.js.map +1 -0
- package/dist/listbox/drag-types.d.ts +50 -0
- package/dist/listbox/drag-types.d.ts.map +1 -0
- package/dist/listbox/drag-types.js +6 -0
- package/dist/listbox/drag-types.js.map +1 -0
- package/dist/listbox/drag.d.ts +33 -0
- package/dist/listbox/drag.d.ts.map +1 -0
- package/dist/listbox/drag.js +201 -0
- package/dist/listbox/drag.js.map +1 -0
- package/dist/listbox/grid.d.ts +28 -0
- package/dist/listbox/grid.d.ts.map +1 -0
- package/dist/listbox/grid.js +165 -0
- package/dist/listbox/grid.js.map +1 -0
- package/dist/listbox/locale.d.ts +30 -0
- package/dist/listbox/locale.d.ts.map +1 -0
- package/dist/listbox/locale.js +25 -0
- package/dist/listbox/locale.js.map +1 -0
- package/dist/listbox/move.d.ts +16 -0
- package/dist/listbox/move.d.ts.map +1 -0
- package/dist/listbox/move.js +70 -0
- package/dist/listbox/move.js.map +1 -0
- package/dist/listbox/types.d.ts +210 -0
- package/dist/listbox/types.d.ts.map +1 -0
- package/dist/listbox/types.js +2 -0
- package/dist/listbox/types.js.map +1 -0
- package/dist/listbox.css +330 -0
- package/dist/listbox.d.ts +6 -0
- package/dist/listbox.d.ts.map +1 -0
- package/dist/listbox.js +7 -0
- package/dist/listbox.js.map +1 -0
- package/dist/mention/Mention.d.ts +5 -0
- package/dist/mention/Mention.d.ts.map +1 -0
- package/dist/mention/Mention.js +530 -0
- package/dist/mention/Mention.js.map +1 -0
- package/dist/mention/query.d.ts +27 -0
- package/dist/mention/query.d.ts.map +1 -0
- package/dist/mention/query.js +53 -0
- package/dist/mention/query.js.map +1 -0
- package/dist/mention/store.d.ts +22 -0
- package/dist/mention/store.d.ts.map +1 -0
- package/dist/mention/store.js +25 -0
- package/dist/mention/store.js.map +1 -0
- package/dist/mention/types.d.ts +183 -0
- package/dist/mention/types.d.ts.map +1 -0
- package/dist/mention/types.js +2 -0
- package/dist/mention/types.js.map +1 -0
- package/dist/mention.css +116 -0
- package/dist/mention.d.ts +3 -0
- package/dist/mention.d.ts.map +1 -0
- package/dist/mention.js +7 -0
- package/dist/mention.js.map +1 -0
- package/dist/select/Select.d.ts +31 -0
- package/dist/select/Select.d.ts.map +1 -0
- package/dist/select/Select.js +362 -0
- package/dist/select/Select.js.map +1 -0
- package/dist/select/SelectField.d.ts +9 -0
- package/dist/select/SelectField.d.ts.map +1 -0
- package/dist/select/SelectField.js +13 -0
- package/dist/select/SelectField.js.map +1 -0
- package/dist/select.css +536 -0
- package/dist/select.d.ts +5 -0
- package/dist/select.d.ts.map +1 -0
- package/dist/select.js +9 -0
- package/dist/select.js.map +1 -0
- package/dist/styles.css +1590 -0
- package/dist/tree-select/TreeSelect.d.ts +69 -0
- package/dist/tree-select/TreeSelect.d.ts.map +1 -0
- package/dist/tree-select/TreeSelect.js +597 -0
- package/dist/tree-select/TreeSelect.js.map +1 -0
- package/dist/tree-select/filter.d.ts +24 -0
- package/dist/tree-select/filter.d.ts.map +1 -0
- package/dist/tree-select/filter.js +74 -0
- package/dist/tree-select/filter.js.map +1 -0
- package/dist/tree-select/locale.d.ts +3 -0
- package/dist/tree-select/locale.d.ts.map +1 -0
- package/dist/tree-select/locale.js +8 -0
- package/dist/tree-select/locale.js.map +1 -0
- package/dist/tree-select/popup.d.ts +19 -0
- package/dist/tree-select/popup.d.ts.map +1 -0
- package/dist/tree-select/popup.js +418 -0
- package/dist/tree-select/popup.js.map +1 -0
- package/dist/tree-select/types.d.ts +152 -0
- package/dist/tree-select/types.d.ts.map +1 -0
- package/dist/tree-select/types.js +4 -0
- package/dist/tree-select/types.js.map +1 -0
- package/dist/tree-select.css +601 -0
- package/dist/tree-select.d.ts +5 -0
- package/dist/tree-select.d.ts.map +1 -0
- package/dist/tree-select.js +10 -0
- package/dist/tree-select.js.map +1 -0
- package/package.json +65 -4
|
@@ -0,0 +1,887 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
// Listbox: a persistent APG listbox over the shared collection
|
|
4
|
+
// primitives (internal/collection). Single or multiple selection,
|
|
5
|
+
// aria-activedescendant focus, type-ahead, grouping, search, a fixed-height
|
|
6
|
+
// virtual list above 100 items, remote sources, keyboard reorder, and pointer
|
|
7
|
+
// drag and drop in a lazy chunk.
|
|
8
|
+
import { memo, use, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, } from 'react';
|
|
9
|
+
import { createCollection, defaultItemDisabled, defaultItemLabel, defaultItemValue, groupAtEntry, } from '../internal/collection/collection.js';
|
|
10
|
+
import { selectAllValues } from '../internal/collection/selection.js';
|
|
11
|
+
import { createCollectionStore } from '@salmonui/core/internal/collection/store';
|
|
12
|
+
import { isTypeaheadKey, useTypeahead } from '@salmonui/core/internal/roving';
|
|
13
|
+
import { nextWindow, OVERSCAN, revealOffset, windowRange } from '@salmonui/core/internal/collection/virtual';
|
|
14
|
+
import { localView, remoteView } from '../internal/collection/view.js';
|
|
15
|
+
import { DEV, warnOnce } from '@salmonui/core/internal/dev';
|
|
16
|
+
import { dropTargets } from './drag-types.js';
|
|
17
|
+
import { formatListboxText, LISTBOX_DEFAULT_LOCALE_TEXT } from './locale.js';
|
|
18
|
+
import { LocaleContext } from '@salmonui/core/internal/locale';
|
|
19
|
+
const DEFAULT_ITEM_HEIGHT = 32;
|
|
20
|
+
const VIRTUAL_THRESHOLD = 100;
|
|
21
|
+
const EMPTY_ITEMS = [];
|
|
22
|
+
const NO_VALUES = [];
|
|
23
|
+
function cx(...parts) {
|
|
24
|
+
return parts.filter(Boolean).join(' ');
|
|
25
|
+
}
|
|
26
|
+
function setRef(ref, value) {
|
|
27
|
+
if (typeof ref === 'function')
|
|
28
|
+
ref(value);
|
|
29
|
+
else if (ref)
|
|
30
|
+
ref.current = value;
|
|
31
|
+
}
|
|
32
|
+
function sourceOf(event) {
|
|
33
|
+
if (!event)
|
|
34
|
+
return 'keyboard';
|
|
35
|
+
return event.pointerType === 'touch' ? 'touch' : 'pointer';
|
|
36
|
+
}
|
|
37
|
+
const noopSubscribe = () => () => { };
|
|
38
|
+
const nullSnapshot = () => null;
|
|
39
|
+
/** Option element. Memoized: moving the active option re-renders two options. */
|
|
40
|
+
const ListboxOption = memo(function ListboxOption(props) {
|
|
41
|
+
if (props.placeholder) {
|
|
42
|
+
return (_jsx("div", { id: props.id, role: props.cell ? 'gridcell' : 'option', "aria-selected": false, "aria-disabled": true, "aria-setsize": props.cell ? undefined : props.setsize, "aria-posinset": props.cell ? undefined : props.posinset, className: "salmon-listbox-option", "data-placeholder": "", "data-entry": props.entry, style: props.top === null ? undefined : { position: 'absolute', insetBlockStart: props.top, insetInline: 0 }, children: _jsx("span", { className: "salmon-listbox-label", children: props.loadingText }) }));
|
|
43
|
+
}
|
|
44
|
+
const matches = props.highlight && props.search && props.matchRanges ? props.matchRanges(props.label, props.search, props.highlight, { matchCase: props.matchCase, ignoreAccents: props.ignoreAccents }) : [];
|
|
45
|
+
const extra = props.getItemProps?.(props.item, { selected: props.selected, disabled: props.disabled });
|
|
46
|
+
const { className: extraClass, style: extraStyle, ...rest } = extra ?? {};
|
|
47
|
+
let content;
|
|
48
|
+
if (props.renderItem) {
|
|
49
|
+
content = props.renderItem({
|
|
50
|
+
item: props.item,
|
|
51
|
+
value: props.value,
|
|
52
|
+
label: props.label,
|
|
53
|
+
selected: props.selected,
|
|
54
|
+
active: props.active,
|
|
55
|
+
disabled: props.disabled,
|
|
56
|
+
matches,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
else if (matches.length > 0) {
|
|
60
|
+
const [start, end] = matches[0];
|
|
61
|
+
content = (_jsxs(_Fragment, { children: [props.label.slice(0, start), _jsx("mark", { className: "salmon-listbox__match", children: props.label.slice(start, end) }), props.label.slice(end)] }));
|
|
62
|
+
}
|
|
63
|
+
else
|
|
64
|
+
content = props.label;
|
|
65
|
+
const icon = props.getItemIcon?.(props.item);
|
|
66
|
+
const positioned = props.top === null ? undefined : { position: 'absolute', insetBlockStart: props.top, insetInline: 0 };
|
|
67
|
+
return (_jsxs("div", { ...rest, id: props.id, role: props.cell ? 'gridcell' : 'option', "aria-selected": props.selected, "aria-disabled": props.disabled || undefined, "aria-setsize": props.cell ? undefined : props.setsize, "aria-posinset": props.cell ? undefined : props.posinset, className: cx('salmon-listbox-option', props.className, extraClass), style: positioned || props.style || extraStyle ? { ...props.style, ...extraStyle, ...positioned } : undefined, "data-entry": props.entry, "data-active": props.active ? '' : undefined, "data-selected": props.selected ? '' : undefined, "data-disabled": props.disabled ? '' : undefined, "data-draggable": props.draggable ? '' : undefined, children: [props.indicator === 'checkbox' ? (_jsx("span", { className: "salmon-listbox-checkbox", "aria-hidden": "true", "data-checked": props.selected ? '' : undefined })) : (_jsx("span", { className: "salmon-listbox-check", "aria-hidden": "true" })), icon != null && icon !== false ? (_jsx("span", { className: "salmon-listbox-icon", "aria-hidden": "true", children: icon })) : null, _jsx("span", { className: "salmon-listbox-label", children: content })] }));
|
|
68
|
+
});
|
|
69
|
+
function useStoreField(store, key) {
|
|
70
|
+
return useSyncExternalStore(store.subscribe, () => store.getState()[key], () => store.getState()[key]);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* A persistent list of options (WAI-ARIA APG listbox) with single or
|
|
74
|
+
* multiple selection. `ref` receives the `role="listbox"` element.
|
|
75
|
+
*/
|
|
76
|
+
export function Listbox(props) {
|
|
77
|
+
const { data, getItemValue, getItemLabel, getItemGroup, getItemIcon, isItemDisabled, multiple: multipleProp, value: valueProp, defaultValue, onValueChange, layout, columns: columnsProp, indicator = 'check', indicatorPosition, showSelectAll = false, maxSelected, searchable = false, searchOperator = 'startsWith', matchCase = false, ignoreAccents = false, searchPlaceholder, onSearchChange, debounce, minSearchLength, maxResults, query, searchFields, virtualization, maxVisibleItems = 8, highlightMatches = false, renderItem, renderGroupHeader, renderEmpty, renderError, renderLoading, getItemProps, onLoadError, loading: loadingProp, name, required, form, disabled = false, readOnly = false, reorderable = false, onReorder, dragGroup, onItemDragStart, onItemDrag, onItemDrop, localeText: ownText, className, style, classNames, styles, ref, id: idProp, onKeyDown: userKeyDown, onFocus: userFocus, onClick: userClick, onPointerDown: userPointerDown, onScroll: userScroll, ...dom } = props;
|
|
78
|
+
const multiple = multipleProp === true;
|
|
79
|
+
const grid = layout === 'grid';
|
|
80
|
+
const columns = grid ? Math.max(1, Math.floor(columnsProp ?? 1)) : 1;
|
|
81
|
+
const generatedId = useId();
|
|
82
|
+
const id = idProp ?? generatedId;
|
|
83
|
+
const localeText = use(LocaleContext)?.('listbox', ownText) ?? ownText;
|
|
84
|
+
const locale = use(LocaleContext)?.locale;
|
|
85
|
+
const text = useMemo(() => ({ ...LISTBOX_DEFAULT_LOCALE_TEXT, ...localeText }), [localeText]);
|
|
86
|
+
// --- value (controlled / uncontrolled) -----------------------------------
|
|
87
|
+
const controlled = valueProp !== undefined;
|
|
88
|
+
const [initialValue] = useState(() => (defaultValue !== undefined ? defaultValue : multiple ? NO_VALUES : null));
|
|
89
|
+
const [innerValue, setInnerValue] = useState(initialValue);
|
|
90
|
+
const current = (controlled ? valueProp : innerValue);
|
|
91
|
+
const values = useMemo(() => (multiple ? (current ?? NO_VALUES) : current === null || current === undefined ? NO_VALUES : [current]), [current, multiple]);
|
|
92
|
+
const selectedSet = useMemo(() => new Set(values), [values]);
|
|
93
|
+
const [wasControlled] = useState(controlled);
|
|
94
|
+
// --- data ------------------------------------------------------------------
|
|
95
|
+
const remoteSource = Array.isArray(data) ? null : data;
|
|
96
|
+
const items = remoteSource ? EMPTY_ITEMS : data;
|
|
97
|
+
const collection = useMemo(() => createCollection(items, { getItemValue, getItemLabel, getItemGroup: grid ? undefined : getItemGroup }), [items, getItemValue, getItemLabel, getItemGroup, grid]);
|
|
98
|
+
// The search index is a lazy chunk, loaded and built after the first paint.
|
|
99
|
+
const [searchModule, setSearchModule] = useState(null);
|
|
100
|
+
const searchIndex = useMemo(() => (searchModule && searchable ? searchModule.createSearchIndex(collection, { matchCase, ignoreAccents }) : null), [searchModule, searchable, collection, matchCase, ignoreAccents]);
|
|
101
|
+
const [search, setSearch] = useState('');
|
|
102
|
+
const matched = useMemo(() => {
|
|
103
|
+
if (remoteSource)
|
|
104
|
+
return null;
|
|
105
|
+
let hits = searchIndex ? searchIndex.search(search, searchOperator) : null;
|
|
106
|
+
if (maxResults !== undefined && (hits ? hits.length : collection.size) > maxResults) {
|
|
107
|
+
hits = hits ? hits.subarray(0, maxResults) : Int32Array.from({ length: maxResults }, (_, i) => i);
|
|
108
|
+
}
|
|
109
|
+
return hits;
|
|
110
|
+
}, [remoteSource, searchable, searchIndex, search, searchOperator, maxResults, collection]);
|
|
111
|
+
const entries = useMemo(() => collection.entries(matched), [collection, matched]);
|
|
112
|
+
const [remote, setRemote] = useState(null);
|
|
113
|
+
// Keyed by value: inline literals (`searchFields={['a']}`, `query={{ ... }}`) must not re-create the adapter on every render.
|
|
114
|
+
const remoteKey = JSON.stringify([searchFields, query]);
|
|
115
|
+
useEffect(() => {
|
|
116
|
+
if (!remoteSource)
|
|
117
|
+
return;
|
|
118
|
+
// The remote adapter is a lazy chunk: local lists never load it.
|
|
119
|
+
let r = null;
|
|
120
|
+
let live = true;
|
|
121
|
+
void import('../internal/collection/remote.js').then((m) => {
|
|
122
|
+
if (!live)
|
|
123
|
+
return;
|
|
124
|
+
r = m.createRemoteCollection(remoteSource, {
|
|
125
|
+
searchFields,
|
|
126
|
+
operator: typeof searchOperator === 'string' ? searchOperator : 'startsWith',
|
|
127
|
+
matchCase,
|
|
128
|
+
ignoreAccents,
|
|
129
|
+
query,
|
|
130
|
+
maxResults,
|
|
131
|
+
minSearchLength,
|
|
132
|
+
debounce,
|
|
133
|
+
});
|
|
134
|
+
setRemote(r);
|
|
135
|
+
});
|
|
136
|
+
return () => {
|
|
137
|
+
live = false;
|
|
138
|
+
r?.dispose();
|
|
139
|
+
setRemote(null);
|
|
140
|
+
};
|
|
141
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
142
|
+
}, [remoteSource, remoteKey, searchOperator, matchCase, ignoreAccents, maxResults, minSearchLength, debounce]);
|
|
143
|
+
const snapshot = useSyncExternalStore(remote ? remote.subscribe : noopSubscribe, remote ? remote.getSnapshot : nullSnapshot, nullSnapshot);
|
|
144
|
+
const valueOf = (getItemValue ?? defaultItemValue);
|
|
145
|
+
const labelOf = (getItemLabel ?? defaultItemLabel);
|
|
146
|
+
const disabledOf = (isItemDisabled ?? defaultItemDisabled);
|
|
147
|
+
const view = remoteSource ? remoteView(snapshot, valueOf, labelOf, disabledOf) : localView(collection, entries, disabledOf);
|
|
148
|
+
const count = view.count;
|
|
149
|
+
// The virtual list windows rows: one entry per row, or `columns` cells per grid row.
|
|
150
|
+
const rows = Math.ceil(count / columns);
|
|
151
|
+
const virtual = virtualization ?? count > VIRTUAL_THRESHOLD;
|
|
152
|
+
// --- store: active entry, mounted window ------------------------------------
|
|
153
|
+
const [store] = useState(() => createCollectionStore({ active: -1, first: 0, last: maxVisibleItems + OVERSCAN * 2, itemHeight: DEFAULT_ITEM_HEIGHT, sticky: null }));
|
|
154
|
+
const active = useStoreField(store, 'active');
|
|
155
|
+
const storeFirst = useStoreField(store, 'first');
|
|
156
|
+
const storeLast = useStoreField(store, 'last');
|
|
157
|
+
const itemHeight = useStoreField(store, 'itemHeight');
|
|
158
|
+
const sticky = useStoreField(store, 'sticky');
|
|
159
|
+
let first = 0;
|
|
160
|
+
let last = rows;
|
|
161
|
+
if (virtual) {
|
|
162
|
+
const win = storeLast <= rows && storeLast - storeFirst >= Math.min(rows, maxVisibleItems + OVERSCAN * 2) ? { first: storeFirst, last: storeLast } : windowRange(rows, storeFirst, maxVisibleItems);
|
|
163
|
+
first = win.first;
|
|
164
|
+
last = win.last;
|
|
165
|
+
}
|
|
166
|
+
const activeEntry = active < count ? active : -1;
|
|
167
|
+
const listRef = useRef(null);
|
|
168
|
+
const searchRef = useRef(null);
|
|
169
|
+
const liveRef = useRef(null);
|
|
170
|
+
const nativeRef = useRef(null);
|
|
171
|
+
const typeahead = useTypeahead();
|
|
172
|
+
const latest = useRef({ view, values, current, count, rows, virtual, props, collection, itemHeight, multiple, search, remote });
|
|
173
|
+
useLayoutEffect(() => {
|
|
174
|
+
latest.current = { view, values, current, count, rows, virtual, props, collection, itemHeight, multiple, search, remote };
|
|
175
|
+
});
|
|
176
|
+
const anchor = useRef(-1);
|
|
177
|
+
const pendingMove = useRef(null);
|
|
178
|
+
const activeValue = useRef(undefined);
|
|
179
|
+
// --- development checks ----------------------------------------------------
|
|
180
|
+
useEffect(() => {
|
|
181
|
+
if (!DEV)
|
|
182
|
+
return;
|
|
183
|
+
if (wasControlled !== controlled)
|
|
184
|
+
warnOnce(`listbox-controlled-${id}`, `Listbox "${id}" switched between controlled and uncontrolled value; pass value (or undefined) for the whole lifetime.`);
|
|
185
|
+
if (grid && (getItemGroup || reorderable || dragGroup !== undefined))
|
|
186
|
+
warnOnce(`listbox-grid-${id}`, `Listbox "${id}": layout="grid" has no group headers or reordering; getItemGroup, reorderable and dragGroup are ignored.`);
|
|
187
|
+
}, [controlled, wasControlled, id, grid, getItemGroup, reorderable, dragGroup]);
|
|
188
|
+
useEffect(() => {
|
|
189
|
+
if (!DEV || remoteSource)
|
|
190
|
+
return;
|
|
191
|
+
const dupes = collection.duplicates();
|
|
192
|
+
if (dupes.length > 0)
|
|
193
|
+
warnOnce(`listbox-dupes-${id}`, `Listbox "${id}": item values must be unique; duplicates: ${dupes.slice(0, 5).map(String).join(', ')}.`);
|
|
194
|
+
const split = collection.splitGroups();
|
|
195
|
+
if (split.length > 0)
|
|
196
|
+
warnOnce(`listbox-groups-${id}`, `Listbox "${id}": items of a group must be contiguous; split groups: ${split.slice(0, 5).join(', ')}.`);
|
|
197
|
+
}, [collection, remoteSource, id]);
|
|
198
|
+
// --- search index after the first paint ------------------------
|
|
199
|
+
useEffect(() => {
|
|
200
|
+
if (!searchable || remoteSource)
|
|
201
|
+
return;
|
|
202
|
+
if (!searchModule) {
|
|
203
|
+
let live = true;
|
|
204
|
+
void import('../internal/collection/search.js').then((m) => {
|
|
205
|
+
if (live)
|
|
206
|
+
setSearchModule(m);
|
|
207
|
+
});
|
|
208
|
+
return () => {
|
|
209
|
+
live = false;
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
if (!searchIndex || searchIndex.built)
|
|
213
|
+
return;
|
|
214
|
+
const handle = setTimeout(() => searchIndex.build(), 0);
|
|
215
|
+
return () => clearTimeout(handle);
|
|
216
|
+
}, [searchable, remoteSource, searchModule, searchIndex]);
|
|
217
|
+
// --- grid layout: keyboard and tab stops are a lazy chunk ---------
|
|
218
|
+
const [gridModule, setGridModule] = useState(null);
|
|
219
|
+
useEffect(() => {
|
|
220
|
+
if (!grid || gridModule)
|
|
221
|
+
return;
|
|
222
|
+
let live = true;
|
|
223
|
+
void import('./grid.js').then((m) => {
|
|
224
|
+
if (live)
|
|
225
|
+
setGridModule(m);
|
|
226
|
+
});
|
|
227
|
+
return () => {
|
|
228
|
+
live = false;
|
|
229
|
+
};
|
|
230
|
+
}, [grid, gridModule]);
|
|
231
|
+
// --- item height measured once per mount from the first option -------------
|
|
232
|
+
useLayoutEffect(() => {
|
|
233
|
+
const el = listRef.current?.querySelector('.salmon-listbox-option');
|
|
234
|
+
const h = el?.offsetHeight ?? 0;
|
|
235
|
+
if (h > 0)
|
|
236
|
+
store.set({ itemHeight: h });
|
|
237
|
+
}, [store, count > 0, virtual]);
|
|
238
|
+
// --- a new entry set (search, data) starts at the top; active follows its value
|
|
239
|
+
const prevEntries = useRef(null);
|
|
240
|
+
useLayoutEffect(() => {
|
|
241
|
+
const key = remoteSource ? snapshot?.generation : entries;
|
|
242
|
+
if (prevEntries.current === key)
|
|
243
|
+
return;
|
|
244
|
+
const searchChanged = prevEntries.current !== null;
|
|
245
|
+
prevEntries.current = key;
|
|
246
|
+
const el = listRef.current;
|
|
247
|
+
const v = latest.current.view;
|
|
248
|
+
let nextActive = -1;
|
|
249
|
+
if (activeValue.current !== undefined && !remoteSource) {
|
|
250
|
+
const index = collection.indexOf(activeValue.current);
|
|
251
|
+
nextActive = index >= 0 ? v.entryOf(index) : -1;
|
|
252
|
+
}
|
|
253
|
+
if (nextActive < 0 && searchChanged && search) {
|
|
254
|
+
for (let e = 0; e < v.count; e++) {
|
|
255
|
+
const code = v.code(e);
|
|
256
|
+
if (code >= 0 && !v.disabled(code)) {
|
|
257
|
+
nextActive = e;
|
|
258
|
+
break;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (searchChanged && search && el)
|
|
263
|
+
el.scrollTop = 0;
|
|
264
|
+
const range = windowRange(Math.ceil(v.count / columns), el ? Math.floor(el.scrollTop / store.getState().itemHeight) : 0, maxVisibleItems);
|
|
265
|
+
store.set({ active: nextActive, first: range.first, last: range.last, sticky: v.count > 0 && collection.grouped ? (groupAtEntry(entries, range.first) ?? null) : null });
|
|
266
|
+
});
|
|
267
|
+
// --- remote window reads -----------------------------------------------------
|
|
268
|
+
useEffect(() => {
|
|
269
|
+
if (!remote)
|
|
270
|
+
return;
|
|
271
|
+
remote.ensure(first * columns, (last + OVERSCAN) * columns);
|
|
272
|
+
}, [remote, first, last, columns, snapshot?.generation]);
|
|
273
|
+
const remoteError = snapshot?.error ?? null;
|
|
274
|
+
useEffect(() => {
|
|
275
|
+
if (remoteError !== null)
|
|
276
|
+
onLoadError?.(remoteError);
|
|
277
|
+
// Once per error: an inline `onLoadError` must not re-fire it on every render.
|
|
278
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
279
|
+
}, [remoteError]);
|
|
280
|
+
// --- announcements ----------------------------------------------------------
|
|
281
|
+
const announce = (message, params) => {
|
|
282
|
+
const el = liveRef.current;
|
|
283
|
+
if (el)
|
|
284
|
+
el.textContent = formatListboxText(message, params, locale);
|
|
285
|
+
};
|
|
286
|
+
const searchDone = useRef('');
|
|
287
|
+
useEffect(() => {
|
|
288
|
+
if (!searchable || search === searchDone.current)
|
|
289
|
+
return;
|
|
290
|
+
// The count is known once the matches are: the remote page for this search, or the local search index.
|
|
291
|
+
if (search && (remoteSource ? !snapshot || snapshot.loading || snapshot.search !== search : !searchIndex))
|
|
292
|
+
return;
|
|
293
|
+
searchDone.current = search;
|
|
294
|
+
if (!search)
|
|
295
|
+
return announce('');
|
|
296
|
+
announce(text.resultCount, { count: view.itemCount });
|
|
297
|
+
});
|
|
298
|
+
useEffect(() => {
|
|
299
|
+
const move = pendingMove.current;
|
|
300
|
+
if (!move || remoteSource)
|
|
301
|
+
return;
|
|
302
|
+
const index = collection.indexOf(move.value);
|
|
303
|
+
if (index < 0)
|
|
304
|
+
return;
|
|
305
|
+
pendingMove.current = null;
|
|
306
|
+
announce(text.moved, { label: move.label, position: index + 1, count: collection.size });
|
|
307
|
+
}, [collection, remoteSource, text]);
|
|
308
|
+
// --- form: owning form reset ------------------------------------------------
|
|
309
|
+
useEffect(() => {
|
|
310
|
+
const form = nativeRef.current?.form;
|
|
311
|
+
if (!form)
|
|
312
|
+
return;
|
|
313
|
+
const onReset = () => {
|
|
314
|
+
const initial = initialValue;
|
|
315
|
+
const now = latest.current.current;
|
|
316
|
+
const same = Array.isArray(initial) && Array.isArray(now) ? initial.length === now.length && initial.every((v, i) => v === now[i]) : initial === now;
|
|
317
|
+
if (!same && !controlled)
|
|
318
|
+
commit(initial, 'reset', 'api');
|
|
319
|
+
// The browser resets the native options after this event; re-sync them.
|
|
320
|
+
setTimeout(() => {
|
|
321
|
+
const select = nativeRef.current;
|
|
322
|
+
if (!select)
|
|
323
|
+
return;
|
|
324
|
+
const set = new Set(latest.current.values.map(String));
|
|
325
|
+
for (const option of Array.from(select.options))
|
|
326
|
+
option.selected = set.has(option.value) || (set.size === 0 && option.value === '');
|
|
327
|
+
}, 0);
|
|
328
|
+
};
|
|
329
|
+
form.addEventListener('reset', onReset);
|
|
330
|
+
return () => form.removeEventListener('reset', onReset);
|
|
331
|
+
});
|
|
332
|
+
// --- value commits -----------------------------------------------------------
|
|
333
|
+
function commit(next, reason, source) {
|
|
334
|
+
const { props: p, current: previousValue, view: v, collection: c } = latest.current;
|
|
335
|
+
if (!controlled)
|
|
336
|
+
setInnerValue(next);
|
|
337
|
+
const handler = p.onValueChange;
|
|
338
|
+
if (!handler)
|
|
339
|
+
return;
|
|
340
|
+
let materialized = null;
|
|
341
|
+
const nextValues = Array.isArray(next) ? next : next === null ? [] : [next];
|
|
342
|
+
const event = Object.freeze({
|
|
343
|
+
reason,
|
|
344
|
+
source,
|
|
345
|
+
previousValue,
|
|
346
|
+
get items() {
|
|
347
|
+
if (materialized)
|
|
348
|
+
return materialized;
|
|
349
|
+
const out = [];
|
|
350
|
+
if (!v.remote) {
|
|
351
|
+
for (const val of nextValues) {
|
|
352
|
+
const i = c.indexOf(val);
|
|
353
|
+
if (i >= 0)
|
|
354
|
+
out.push(c.items[i]);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
else {
|
|
358
|
+
const set = new Set(nextValues);
|
|
359
|
+
for (let i = 0; i < v.count; i++) {
|
|
360
|
+
const item = v.item(i);
|
|
361
|
+
if (item !== undefined && set.has(valueOf(item)))
|
|
362
|
+
out.push(item);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
materialized = Object.freeze(out);
|
|
366
|
+
return materialized;
|
|
367
|
+
},
|
|
368
|
+
});
|
|
369
|
+
handler(next, event);
|
|
370
|
+
}
|
|
371
|
+
const canChange = !disabled && !readOnly;
|
|
372
|
+
const selectOnly = (index, source) => {
|
|
373
|
+
const v = view.value(index);
|
|
374
|
+
if (v === undefined || !canChange || view.disabled(index))
|
|
375
|
+
return;
|
|
376
|
+
if (multiple) {
|
|
377
|
+
if (values.length === 1 && values[0] === v)
|
|
378
|
+
return;
|
|
379
|
+
commit([v], 'select', source);
|
|
380
|
+
}
|
|
381
|
+
else if (current !== v)
|
|
382
|
+
commit(v, 'select', source);
|
|
383
|
+
};
|
|
384
|
+
const limitReached = (adding) => {
|
|
385
|
+
if (!multiple || maxSelected === undefined || values.length + adding <= maxSelected)
|
|
386
|
+
return false;
|
|
387
|
+
announce(text.selectionLimit, { count: maxSelected, max: maxSelected });
|
|
388
|
+
return true;
|
|
389
|
+
};
|
|
390
|
+
const toggle = (index, source) => {
|
|
391
|
+
const v = view.value(index);
|
|
392
|
+
if (v === undefined || !canChange || view.disabled(index))
|
|
393
|
+
return;
|
|
394
|
+
if (!multiple) {
|
|
395
|
+
if (current !== v)
|
|
396
|
+
commit(v, 'select', source);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
if (selectedSet.has(v))
|
|
400
|
+
commit(values.filter((x) => x !== v), 'deselect', source);
|
|
401
|
+
else if (!limitReached(1))
|
|
402
|
+
commit([...values, v], 'select', source);
|
|
403
|
+
};
|
|
404
|
+
const selectRange = (fromEntry, toEntry, source) => {
|
|
405
|
+
if (!multiple || !canChange)
|
|
406
|
+
return;
|
|
407
|
+
const lo = Math.max(0, Math.min(fromEntry, toEntry));
|
|
408
|
+
const hi = Math.min(count - 1, Math.max(fromEntry, toEntry));
|
|
409
|
+
const next = values.slice();
|
|
410
|
+
const set = new Set(values);
|
|
411
|
+
for (let e = lo; e <= hi; e++) {
|
|
412
|
+
const code = view.code(e);
|
|
413
|
+
if (code < 0 || view.disabled(code))
|
|
414
|
+
continue;
|
|
415
|
+
const v = view.value(code);
|
|
416
|
+
if (v === undefined || set.has(v))
|
|
417
|
+
continue;
|
|
418
|
+
if (maxSelected !== undefined && next.length >= maxSelected) {
|
|
419
|
+
announce(text.selectionLimit, { count: maxSelected, max: maxSelected });
|
|
420
|
+
break;
|
|
421
|
+
}
|
|
422
|
+
set.add(v);
|
|
423
|
+
next.push(v);
|
|
424
|
+
}
|
|
425
|
+
if (next.length !== values.length)
|
|
426
|
+
commit(next, 'select', source);
|
|
427
|
+
};
|
|
428
|
+
const allSelectable = useMemo(() => {
|
|
429
|
+
if (!multiple || !showSelectAll || remoteSource)
|
|
430
|
+
return { all: false, some: false };
|
|
431
|
+
let selectable = 0;
|
|
432
|
+
let selected = 0;
|
|
433
|
+
for (let i = 0; i < collection.size; i++) {
|
|
434
|
+
if (disabledOf(collection.items[i]))
|
|
435
|
+
continue;
|
|
436
|
+
selectable++;
|
|
437
|
+
if (selectedSet.has(collection.value(i)))
|
|
438
|
+
selected++;
|
|
439
|
+
}
|
|
440
|
+
return { all: selectable > 0 && selected === selectable, some: selected > 0 };
|
|
441
|
+
// disabledOf follows isItemDisabled.
|
|
442
|
+
}, [multiple, showSelectAll, remoteSource, collection, selectedSet, isItemDisabled]);
|
|
443
|
+
const selectAll = (source) => {
|
|
444
|
+
if (!multiple || !canChange)
|
|
445
|
+
return;
|
|
446
|
+
let all = true;
|
|
447
|
+
if (remoteSource) {
|
|
448
|
+
// Remote: the loaded items (the value holds item values, which need the items).
|
|
449
|
+
const next = new Set(values);
|
|
450
|
+
for (let i = 0; i < count; i++) {
|
|
451
|
+
const item = view.item(i);
|
|
452
|
+
if (item !== undefined && !disabledOf(item))
|
|
453
|
+
next.add(valueOf(item));
|
|
454
|
+
}
|
|
455
|
+
if (next.size !== values.length)
|
|
456
|
+
return commit([...next].slice(0, maxSelected ?? Infinity), 'selectAll', source);
|
|
457
|
+
all = true;
|
|
458
|
+
}
|
|
459
|
+
else {
|
|
460
|
+
const next = selectAllValues({ ...collection, disabled: (i) => disabledOf(collection.items[i]) }, selectedSet, maxSelected === undefined ? Infinity : maxSelected);
|
|
461
|
+
if (next.length !== values.length)
|
|
462
|
+
return commit(next, 'selectAll', source);
|
|
463
|
+
for (let i = 0; i < collection.size; i++) {
|
|
464
|
+
if (!disabledOf(collection.items[i]) && !selectedSet.has(collection.value(i)))
|
|
465
|
+
all = false;
|
|
466
|
+
}
|
|
467
|
+
if (!all) {
|
|
468
|
+
// Not everything is selected, but maxSelected is reached.
|
|
469
|
+
limitReached(1);
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
// Everything selectable is selected: clear (disabled values keep their state).
|
|
474
|
+
const keep = values.filter((v) => {
|
|
475
|
+
const i = remoteSource ? -1 : collection.indexOf(v);
|
|
476
|
+
return i >= 0 && disabledOf(collection.items[i]);
|
|
477
|
+
});
|
|
478
|
+
commit(keep, 'clear', source);
|
|
479
|
+
};
|
|
480
|
+
// --- active entry ------------------------------------------------------------
|
|
481
|
+
const optionId = (index) => `${id}-opt-${index}`;
|
|
482
|
+
const setActive = (entry, reveal) => {
|
|
483
|
+
const code = entry >= 0 ? view.code(entry) : -1;
|
|
484
|
+
activeValue.current = code >= 0 ? view.value(code) : undefined;
|
|
485
|
+
store.set({ active: entry });
|
|
486
|
+
if (!reveal)
|
|
487
|
+
return;
|
|
488
|
+
const el = listRef.current;
|
|
489
|
+
if (!el)
|
|
490
|
+
return;
|
|
491
|
+
const top = revealOffset(Math.floor(entry / columns), itemHeight, el.scrollTop, el.clientHeight || maxVisibleItems * itemHeight);
|
|
492
|
+
if (top !== null) {
|
|
493
|
+
el.scrollTop = top;
|
|
494
|
+
onScroll();
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
const step = (from, dir, distance = 1) => {
|
|
498
|
+
let e = from;
|
|
499
|
+
let found = from;
|
|
500
|
+
let moved = 0;
|
|
501
|
+
while (moved < distance) {
|
|
502
|
+
e += dir;
|
|
503
|
+
if (e < 0 || e >= count)
|
|
504
|
+
break;
|
|
505
|
+
const code = view.code(e);
|
|
506
|
+
if (code < 0 || view.disabled(code))
|
|
507
|
+
continue;
|
|
508
|
+
found = e;
|
|
509
|
+
moved++;
|
|
510
|
+
}
|
|
511
|
+
if (found === from && distance > 1) {
|
|
512
|
+
// Page moves stop at the last enabled entry in that direction.
|
|
513
|
+
for (let k = from + dir; k >= 0 && k < count; k += dir) {
|
|
514
|
+
const code = view.code(k);
|
|
515
|
+
if (code >= 0 && !view.disabled(code))
|
|
516
|
+
found = k;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
return found;
|
|
520
|
+
};
|
|
521
|
+
const edge = (dir) => step(dir === 1 ? -1 : count, dir);
|
|
522
|
+
// --- scroll: the mounted window moves about once per overscan ---------------
|
|
523
|
+
function onScroll() {
|
|
524
|
+
const el = listRef.current;
|
|
525
|
+
const l = latest.current;
|
|
526
|
+
if (!el || !l.virtual)
|
|
527
|
+
return;
|
|
528
|
+
const h = store.getState().itemHeight;
|
|
529
|
+
const start = Math.floor(el.scrollTop / h);
|
|
530
|
+
const visible = Math.max(1, Math.ceil((el.clientHeight || maxVisibleItems * h) / h));
|
|
531
|
+
const s = store.getState();
|
|
532
|
+
const next = nextWindow({ first: s.first, last: s.last }, l.rows, start, visible);
|
|
533
|
+
const stickyGroup = l.collection.grouped && !l.view.remote ? (l.view.group(Math.min(start, l.count - 1)) ?? null) : null;
|
|
534
|
+
store.set({ first: next.first, last: next.last, sticky: stickyGroup });
|
|
535
|
+
}
|
|
536
|
+
// --- keyboard ------------------------------------------------------------------
|
|
537
|
+
const onKeyDown = (event, fromSearch) => {
|
|
538
|
+
if (disabled || count === 0)
|
|
539
|
+
return;
|
|
540
|
+
// The grid keys (lazy chunk); other keys of a control inside a cell belong to it.
|
|
541
|
+
if (grid && !fromSearch && (gridModule?.gridKeyDown(event, listRef.current, view, count, columns, activeEntry, maxVisibleItems, setActive) || event.target !== listRef.current))
|
|
542
|
+
return;
|
|
543
|
+
const mod = event.ctrlKey || event.metaKey;
|
|
544
|
+
const from = activeEntry >= 0 ? activeEntry : -1;
|
|
545
|
+
let target = -1;
|
|
546
|
+
switch (event.key) {
|
|
547
|
+
case 'ArrowDown':
|
|
548
|
+
case 'ArrowUp': {
|
|
549
|
+
const dir = event.key === 'ArrowDown' ? 1 : -1;
|
|
550
|
+
if (event.altKey) {
|
|
551
|
+
if (reorderable && !fromSearch)
|
|
552
|
+
keyboardReorder(dir);
|
|
553
|
+
event.preventDefault();
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
target = from < 0 ? edge(dir) : step(from, dir);
|
|
557
|
+
event.preventDefault();
|
|
558
|
+
setActive(target, true);
|
|
559
|
+
const code = view.code(target);
|
|
560
|
+
if (code < 0)
|
|
561
|
+
return;
|
|
562
|
+
// Shift+Arrow toggles the option it lands on, which becomes the anchor; a plain move keeps the anchor (APG listbox).
|
|
563
|
+
if (multiple && event.shiftKey)
|
|
564
|
+
toggle(code, 'keyboard'), (anchor.current = target);
|
|
565
|
+
else if (!multiple && !mod && !grid)
|
|
566
|
+
selectOnly(code, 'keyboard');
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
case 'PageDown':
|
|
570
|
+
case 'PageUp': {
|
|
571
|
+
const dir = event.key === 'PageDown' ? 1 : -1;
|
|
572
|
+
target = step(from < 0 ? (dir === 1 ? -1 : count) : from, dir, maxVisibleItems);
|
|
573
|
+
event.preventDefault();
|
|
574
|
+
setActive(target, true);
|
|
575
|
+
if (!multiple && !mod && !grid)
|
|
576
|
+
selectOnly(view.code(target), 'keyboard');
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
case 'Home':
|
|
580
|
+
case 'End': {
|
|
581
|
+
if (fromSearch)
|
|
582
|
+
return;
|
|
583
|
+
target = event.key === 'End' ? edge(-1) : edge(1);
|
|
584
|
+
event.preventDefault();
|
|
585
|
+
if (multiple && mod && event.shiftKey && from >= 0)
|
|
586
|
+
selectRange(from, target, 'keyboard');
|
|
587
|
+
setActive(target, true);
|
|
588
|
+
if (!multiple && !mod && !grid)
|
|
589
|
+
selectOnly(view.code(target), 'keyboard');
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
case ' ':
|
|
593
|
+
case 'Enter': {
|
|
594
|
+
if (fromSearch && event.key === ' ')
|
|
595
|
+
return;
|
|
596
|
+
if (from < 0)
|
|
597
|
+
return;
|
|
598
|
+
event.preventDefault();
|
|
599
|
+
const code = view.code(from);
|
|
600
|
+
if (code < 0)
|
|
601
|
+
return;
|
|
602
|
+
if (multiple && event.shiftKey && anchor.current >= 0)
|
|
603
|
+
selectRange(anchor.current, from, 'keyboard');
|
|
604
|
+
else
|
|
605
|
+
toggle(code, 'keyboard');
|
|
606
|
+
anchor.current = from;
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
case 'Escape': {
|
|
610
|
+
if (fromSearch && search) {
|
|
611
|
+
event.preventDefault();
|
|
612
|
+
changeSearch('');
|
|
613
|
+
}
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
case 'a':
|
|
617
|
+
case 'A': {
|
|
618
|
+
if (mod && multiple && !fromSearch) {
|
|
619
|
+
event.preventDefault();
|
|
620
|
+
selectAll('keyboard');
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
break;
|
|
624
|
+
}
|
|
625
|
+
default:
|
|
626
|
+
break;
|
|
627
|
+
}
|
|
628
|
+
if (!fromSearch && isTypeaheadKey(event)) {
|
|
629
|
+
const found = typeahead(event.key, event.timeStamp || Date.now(), count, from, (e) => {
|
|
630
|
+
const code = view.code(e);
|
|
631
|
+
return code < 0 ? '' : view.label(code);
|
|
632
|
+
}, (e) => {
|
|
633
|
+
const code = view.code(e);
|
|
634
|
+
return code >= 0 && !view.disabled(code);
|
|
635
|
+
});
|
|
636
|
+
if (found >= 0) {
|
|
637
|
+
event.preventDefault();
|
|
638
|
+
setActive(found, true);
|
|
639
|
+
if (!multiple && !grid)
|
|
640
|
+
selectOnly(view.code(found), 'keyboard');
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
};
|
|
644
|
+
const keyboardReorder = (dir) => {
|
|
645
|
+
if (remoteSource || activeEntry < 0 || readOnly)
|
|
646
|
+
return;
|
|
647
|
+
const code = view.code(activeEntry);
|
|
648
|
+
if (code < 0)
|
|
649
|
+
return;
|
|
650
|
+
const activeVal = view.value(code);
|
|
651
|
+
const moving = multiple && selectedSet.has(activeVal) ? values : [activeVal];
|
|
652
|
+
const indexes = moving.map((v) => collection.indexOf(v)).filter((i) => i >= 0).sort((a, b) => a - b);
|
|
653
|
+
if (indexes.length === 0)
|
|
654
|
+
return;
|
|
655
|
+
const firstIndex = indexes[0];
|
|
656
|
+
const lastIndex = indexes[indexes.length - 1];
|
|
657
|
+
if ((dir < 0 && firstIndex === 0) || (dir > 0 && lastIndex === collection.size - 1))
|
|
658
|
+
return;
|
|
659
|
+
const toIndex = dir < 0 ? firstIndex - 1 : lastIndex + 2;
|
|
660
|
+
pendingMove.current = { value: activeVal, label: view.label(code) };
|
|
661
|
+
const moved = indexes.map((i) => collection.value(i));
|
|
662
|
+
onReorder?.({ values: moved, items: indexes.map((i) => collection.items[i]), toIndex, delta: dir, source: 'keyboard' });
|
|
663
|
+
};
|
|
664
|
+
// --- search ---------------------------------------------------------------------
|
|
665
|
+
const changeSearch = (next) => {
|
|
666
|
+
setSearch(next);
|
|
667
|
+
onSearchChange?.({ text: next });
|
|
668
|
+
remote?.setSearch(next);
|
|
669
|
+
};
|
|
670
|
+
// --- pointer ----------------------------------------------------------------------
|
|
671
|
+
const entryFromEvent = (target) => {
|
|
672
|
+
const option = target?.closest?.('[data-entry]');
|
|
673
|
+
if (!option || !listRef.current?.contains(option))
|
|
674
|
+
return -1;
|
|
675
|
+
const entry = Number(option.getAttribute('data-entry'));
|
|
676
|
+
return Number.isFinite(entry) ? entry : -1;
|
|
677
|
+
};
|
|
678
|
+
const suppressClick = useRef(false);
|
|
679
|
+
const pressing = useRef(false);
|
|
680
|
+
const onClick = (event) => {
|
|
681
|
+
userClick?.(event);
|
|
682
|
+
if (event.defaultPrevented || disabled)
|
|
683
|
+
return;
|
|
684
|
+
if (suppressClick.current) {
|
|
685
|
+
suppressClick.current = false;
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
const entry = entryFromEvent(event.target);
|
|
689
|
+
if (entry < 0)
|
|
690
|
+
return;
|
|
691
|
+
const code = view.code(entry);
|
|
692
|
+
if (code < 0 || view.disabled(code))
|
|
693
|
+
return;
|
|
694
|
+
const source = sourceOf(event.nativeEvent);
|
|
695
|
+
setActive(entry, false);
|
|
696
|
+
// A click on a control inside a grid cell only makes the cell active.
|
|
697
|
+
if (grid && gridModule?.controlOf(event.target, listRef.current))
|
|
698
|
+
return;
|
|
699
|
+
if (multiple && event.shiftKey && anchor.current >= 0)
|
|
700
|
+
selectRange(anchor.current, entry, source);
|
|
701
|
+
else if (multiple || event.ctrlKey || event.metaKey)
|
|
702
|
+
toggle(code, source);
|
|
703
|
+
else
|
|
704
|
+
selectOnly(code, source);
|
|
705
|
+
anchor.current = entry;
|
|
706
|
+
};
|
|
707
|
+
const dragging = useRef(null);
|
|
708
|
+
const draggable = !grid && (reorderable || dragGroup !== undefined) && canChange && !remoteSource;
|
|
709
|
+
const onPointerDown = (event) => {
|
|
710
|
+
userPointerDown?.(event);
|
|
711
|
+
pressing.current = true;
|
|
712
|
+
setTimeout(() => {
|
|
713
|
+
pressing.current = false;
|
|
714
|
+
}, 0);
|
|
715
|
+
if (event.defaultPrevented || !draggable || event.button !== 0 || dragging.current)
|
|
716
|
+
return;
|
|
717
|
+
const entry = entryFromEvent(event.target);
|
|
718
|
+
const code = entry < 0 ? -1 : view.code(entry);
|
|
719
|
+
const list = listRef.current;
|
|
720
|
+
const target = list ? dropTargets.get(list) : undefined;
|
|
721
|
+
if (code < 0 || view.disabled(code) || !list || !target)
|
|
722
|
+
return;
|
|
723
|
+
const { clientX, clientY, pointerId, pointerType } = event;
|
|
724
|
+
const win = list.ownerDocument.defaultView;
|
|
725
|
+
if (!win)
|
|
726
|
+
return;
|
|
727
|
+
// The drag chunk loads on the first press of a draggable option; a
|
|
728
|
+
// release before it arrives is a click, not a drag.
|
|
729
|
+
let released = false;
|
|
730
|
+
const onRelease = () => {
|
|
731
|
+
released = true;
|
|
732
|
+
};
|
|
733
|
+
win.addEventListener('pointerup', onRelease, { once: true });
|
|
734
|
+
win.addEventListener('pointercancel', onRelease, { once: true });
|
|
735
|
+
dragging.current = () => { };
|
|
736
|
+
void import('./drag.js').then((m) => {
|
|
737
|
+
win.removeEventListener('pointerup', onRelease);
|
|
738
|
+
win.removeEventListener('pointercancel', onRelease);
|
|
739
|
+
if (released) {
|
|
740
|
+
dragging.current = null;
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
const l = latest.current;
|
|
744
|
+
const c = l.collection;
|
|
745
|
+
const pressed = c.value(code);
|
|
746
|
+
const moving = l.multiple && l.values.includes(pressed) ? c.items.map((_, i) => i).filter((i) => l.values.includes(c.value(i))) : [code];
|
|
747
|
+
dragging.current = m.armDrag(list, target, {
|
|
748
|
+
pointerId,
|
|
749
|
+
pointerType,
|
|
750
|
+
startX: clientX,
|
|
751
|
+
startY: clientY,
|
|
752
|
+
values: moving.map((i) => c.value(i)),
|
|
753
|
+
items: moving.map((i) => c.items[i]),
|
|
754
|
+
label: c.label(code),
|
|
755
|
+
onDragStart: (e) => latest.current.props.onItemDragStart?.(e),
|
|
756
|
+
onDrag: (e) => latest.current.props.onItemDrag?.(e),
|
|
757
|
+
onStart: () => {
|
|
758
|
+
suppressClick.current = true;
|
|
759
|
+
},
|
|
760
|
+
onEnd: () => {
|
|
761
|
+
dragging.current = null;
|
|
762
|
+
setTimeout(() => {
|
|
763
|
+
suppressClick.current = false;
|
|
764
|
+
}, 0);
|
|
765
|
+
},
|
|
766
|
+
});
|
|
767
|
+
});
|
|
768
|
+
};
|
|
769
|
+
// Drop target registration: the drag chunk loads after mount for a list
|
|
770
|
+
// that reorders or shares a dragGroup, and registers it in its WeakMap.
|
|
771
|
+
useEffect(() => {
|
|
772
|
+
const list = listRef.current;
|
|
773
|
+
if (!list || (!reorderable && dragGroup === undefined) || remoteSource || grid)
|
|
774
|
+
return;
|
|
775
|
+
let live = true;
|
|
776
|
+
let unregister = () => { };
|
|
777
|
+
void import('./drag.js').then((m) => {
|
|
778
|
+
if (live)
|
|
779
|
+
unregister = m.registerDropTarget(list, id, dragGroup ?? null, reorderable, latest);
|
|
780
|
+
});
|
|
781
|
+
return () => {
|
|
782
|
+
live = false;
|
|
783
|
+
unregister();
|
|
784
|
+
};
|
|
785
|
+
}, [id, reorderable, dragGroup, remoteSource, grid]);
|
|
786
|
+
useEffect(() => () => {
|
|
787
|
+
dragging.current?.();
|
|
788
|
+
}, []);
|
|
789
|
+
// --- render --------------------------------------------------------------------
|
|
790
|
+
const busy = loadingProp === true || (snapshot?.loading ?? false) || (remoteSource !== null && snapshot === null);
|
|
791
|
+
const setsize = view.itemCount;
|
|
792
|
+
const highlight = highlightMatches && typeof searchOperator === 'string' ? searchOperator : null;
|
|
793
|
+
const limitHit = multiple && maxSelected !== undefined && values.length >= maxSelected;
|
|
794
|
+
const renderOption = (entry, top) => {
|
|
795
|
+
const code = view.code(entry);
|
|
796
|
+
const item = view.item(code);
|
|
797
|
+
const placeholder = item === undefined;
|
|
798
|
+
const value = placeholder ? undefined : view.value(code);
|
|
799
|
+
const selected = value !== undefined && selectedSet.has(value);
|
|
800
|
+
const itemDisabled = placeholder ? true : view.disabled(code) || (limitHit && !selected);
|
|
801
|
+
return (_jsx(ListboxOption, { id: optionId(code), entry: entry, index: code, item: item, value: value, label: placeholder ? '' : view.label(code), selected: selected, active: entry === activeEntry, disabled: itemDisabled, placeholder: placeholder, posinset: view.posinset(entry), setsize: setsize, indicator: indicator, cell: grid, draggable: draggable && !itemDisabled, top: top, search: search, highlight: highlight, matchRanges: searchModule?.matchRanges, matchCase: matchCase, ignoreAccents: ignoreAccents, loadingText: formatListboxText(text.loading), className: classNames?.option, style: styles?.option, renderItem: renderItem, getItemIcon: getItemIcon, getItemProps: getItemProps }, placeholder ? `p${code}` : String(value)));
|
|
802
|
+
};
|
|
803
|
+
const renderHeader = (group, key) => (_jsx("div", { className: cx('salmon-listbox-group-header', classNames?.groupHeader), style: styles?.groupHeader, "aria-hidden": "true", children: renderGroupHeader ? renderGroupHeader({ group }) : group }, key));
|
|
804
|
+
// Entries of the window, wrapped per group in role="group" containers.
|
|
805
|
+
const body = [];
|
|
806
|
+
let chunk = [];
|
|
807
|
+
let chunkGroup;
|
|
808
|
+
let chunkStart = first;
|
|
809
|
+
const flush = () => {
|
|
810
|
+
if (chunk.length === 0)
|
|
811
|
+
return;
|
|
812
|
+
if (chunkGroup === undefined)
|
|
813
|
+
body.push(...chunk);
|
|
814
|
+
else
|
|
815
|
+
body.push(_jsx("div", { role: "group", "aria-label": chunkGroup, className: cx('salmon-listbox-group', classNames?.group), style: styles?.group, children: chunk }, `g${chunkStart}`));
|
|
816
|
+
chunk = [];
|
|
817
|
+
};
|
|
818
|
+
const renderRow = (r, top) => {
|
|
819
|
+
const cells = [];
|
|
820
|
+
for (let e = r * columns; e < Math.min(count, (r + 1) * columns); e++)
|
|
821
|
+
cells.push(renderOption(e, null));
|
|
822
|
+
return (_jsx("div", { role: "row", "aria-rowindex": r + 1, className: "salmon-listbox-row", style: top === null ? undefined : { position: 'absolute', insetBlockStart: top, insetInline: 0 }, children: cells }, `r${r}`));
|
|
823
|
+
};
|
|
824
|
+
for (let e = first; e < last; e++) {
|
|
825
|
+
if (grid) {
|
|
826
|
+
body.push(renderRow(e, null));
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
const code = view.code(e);
|
|
830
|
+
const group = collection.grouped && !view.remote ? view.group(e) : undefined;
|
|
831
|
+
if (e === first || group !== chunkGroup) {
|
|
832
|
+
flush();
|
|
833
|
+
chunkGroup = group;
|
|
834
|
+
chunkStart = e;
|
|
835
|
+
}
|
|
836
|
+
chunk.push(code < 0 ? renderHeader(group ?? '', `h${e}`) : renderOption(e, null));
|
|
837
|
+
}
|
|
838
|
+
flush();
|
|
839
|
+
// The active option stays mounted outside the window.
|
|
840
|
+
const activeRow = Math.floor(activeEntry / columns);
|
|
841
|
+
const outOfBand = virtual && activeEntry >= 0 && (activeRow < first || activeRow >= last) && view.code(activeEntry) >= 0
|
|
842
|
+
? grid
|
|
843
|
+
? renderRow(activeRow, activeRow * itemHeight)
|
|
844
|
+
: renderOption(activeEntry, activeEntry * itemHeight)
|
|
845
|
+
: null;
|
|
846
|
+
const listHeight = Math.max(1, Math.min(rows, maxVisibleItems)) * itemHeight;
|
|
847
|
+
const emptyReason = count === 0 && !busy && remoteError === null ? (search || (snapshot?.held ?? false) ? 'noMatch' : 'noData') : null;
|
|
848
|
+
const activeId = activeEntry >= 0 && view.code(activeEntry) >= 0 ? optionId(view.code(activeEntry)) : undefined;
|
|
849
|
+
const userSized = style?.height !== undefined || style?.blockSize !== undefined;
|
|
850
|
+
useLayoutEffect(() => {
|
|
851
|
+
if (gridModule && listRef.current)
|
|
852
|
+
gridModule.syncTabStops(listRef.current, activeId);
|
|
853
|
+
});
|
|
854
|
+
return (_jsxs("div", { className: cx('salmon-listbox', className, classNames?.root), style: style || styles?.root ? { ...styles?.root, ...style } : undefined, "data-multiple": multiple ? '' : undefined, "data-disabled": disabled ? '' : undefined, "data-readonly": readOnly ? '' : undefined, "data-virtual": virtual ? '' : undefined, "data-layout": grid ? 'grid' : undefined, "data-indicator-position": indicatorPosition === 'end' ? 'end' : undefined, children: [searchable ? (_jsx("div", { className: cx('salmon-listbox-search', classNames?.search), style: styles?.search, children: _jsx("input", { ref: searchRef, type: "search", className: "salmon-listbox-search-input", value: search, placeholder: searchPlaceholder, "aria-label": formatListboxText(text.searchLabel), "aria-controls": id, "aria-activedescendant": activeId, autoComplete: "off", disabled: disabled, onChange: (event) => changeSearch(event.target.value), onKeyDown: (event) => onKeyDown(event, true) }) })) : null, multiple && showSelectAll ? (_jsxs("label", { className: cx('salmon-listbox-select-all', classNames?.selectAll), style: styles?.selectAll, children: [_jsx("input", { type: "checkbox", checked: allSelectable.all, ref: (el) => {
|
|
855
|
+
if (el)
|
|
856
|
+
el.indeterminate = allSelectable.some && !allSelectable.all;
|
|
857
|
+
}, "aria-controls": id, disabled: disabled || readOnly, onChange: () => selectAll('pointer') }), _jsx("span", { children: formatListboxText(text.selectAll) })] })) : null, _jsxs("div", { ...dom, ref: (el) => {
|
|
858
|
+
listRef.current = el;
|
|
859
|
+
setRef(ref, el);
|
|
860
|
+
}, id: id, role: grid ? 'grid' : 'listbox', tabIndex: disabled ? -1 : 0, "aria-multiselectable": multiple || undefined, "aria-activedescendant": activeId, "aria-disabled": disabled || undefined, "aria-readonly": readOnly || undefined, "aria-required": (required && !grid) || undefined, "aria-rowcount": grid ? rows : undefined, "aria-busy": busy || undefined, className: cx('salmon-listbox-list', classNames?.list), style: {
|
|
861
|
+
...(userSized ? undefined : { maxBlockSize: listHeight }),
|
|
862
|
+
...(virtual && count > 0 ? { blockSize: listHeight } : undefined),
|
|
863
|
+
...(grid ? { '--salmon-listbox-columns': columns } : undefined),
|
|
864
|
+
...styles?.list,
|
|
865
|
+
}, "data-count": count, onScroll: virtual || userScroll
|
|
866
|
+
? (event) => {
|
|
867
|
+
userScroll?.(event);
|
|
868
|
+
if (virtual)
|
|
869
|
+
onScroll();
|
|
870
|
+
}
|
|
871
|
+
: undefined, onKeyDown: (event) => {
|
|
872
|
+
userKeyDown?.(event);
|
|
873
|
+
if (!event.defaultPrevented)
|
|
874
|
+
onKeyDown(event, false);
|
|
875
|
+
}, onFocus: (event) => {
|
|
876
|
+
userFocus?.(event);
|
|
877
|
+
// Focus on a control inside a grid cell (Tab, click) makes its cell active.
|
|
878
|
+
if (grid && event.target !== event.currentTarget)
|
|
879
|
+
return setActive(entryFromEvent(event.target), false);
|
|
880
|
+
if (activeEntry >= 0 || count === 0)
|
|
881
|
+
return;
|
|
882
|
+
const firstSelected = values.length > 0 && !remoteSource ? view.entryOf(collection.indexOf(values[0])) : -1;
|
|
883
|
+
// A pointer press focuses without scrolling: the click picks the option under the pointer.
|
|
884
|
+
setActive(firstSelected >= 0 ? firstSelected : edge(1), !pressing.current);
|
|
885
|
+
}, onClick: onClick, onPointerDown: onPointerDown, children: [virtual && sticky !== null ? (_jsx("div", { className: "salmon-listbox-sticky", "aria-hidden": "true", style: { blockSize: itemHeight, marginBlockEnd: -itemHeight }, children: renderGroupHeader ? renderGroupHeader({ group: sticky }) : sticky })) : null, virtual ? (_jsxs("div", { className: "salmon-listbox-sizer", role: "presentation", style: { blockSize: count * itemHeight }, children: [_jsx("div", { role: "presentation", style: { transform: `translateY(${first * itemHeight}px)` }, children: body }), outOfBand] })) : (_jsx("div", { className: "salmon-listbox-items", role: "presentation", children: body }))] }), emptyReason ? (_jsx("div", { className: cx('salmon-listbox-empty', classNames?.empty), style: styles?.empty, children: renderEmpty ? renderEmpty({ reason: emptyReason }) : formatListboxText(emptyReason === 'noMatch' ? text.noResults : text.noData) })) : null, busy && count === 0 ? _jsx("div", { className: "salmon-listbox-loading", children: renderLoading ? renderLoading() : formatListboxText(text.loading) }) : null, remoteError !== null ? (_jsx("div", { className: "salmon-listbox-error", role: "alert", children: renderError ? (renderError({ error: remoteError, retry: () => remote?.retry() })) : (_jsxs(_Fragment, { children: [_jsx("span", { children: formatListboxText(text.loadError) }), ' ', _jsx("button", { type: "button", className: "salmon-listbox-retry", onClick: () => remote?.retry(), children: formatListboxText(text.retry) })] })) })) : null, _jsx("div", { ref: liveRef, className: "salmon-listbox-live", role: "status", "aria-live": "polite" }), name !== undefined ? (_jsxs("select", { ref: nativeRef, className: "salmon-listbox-native", name: name, form: form, multiple: multiple, required: required, disabled: disabled, tabIndex: -1, "aria-hidden": "true", value: multiple ? values.map(String) : values.length > 0 ? String(values[0]) : '', onChange: () => { }, children: [multiple ? null : _jsx("option", { value: "" }), values.map((v) => (_jsx("option", { value: String(v) }, String(v))))] })) : null] }));
|
|
886
|
+
}
|
|
887
|
+
//# sourceMappingURL=Listbox.js.map
|