@shival99/z-ui-svelte 0.1.12 → 0.1.13

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.
@@ -1,1631 +1,1642 @@
1
- <script lang="ts" generics="O extends ZSelectOption<any> = ZSelectOption">
2
- import { untrack, type Snippet } from 'svelte';
3
- import { createVirtualizer } from '@tanstack/svelte-virtual';
4
- import type { ClassValue } from 'clsx';
5
- import { zTranslate } from '../../i18n/translate.svelte';
6
- import { zHoverGlide } from '../../interactions/z-hover-glide';
7
- import { zScrollEdges, type ZScrollEdges } from '../../interactions/z-scroll-edges';
8
- import {
9
- Z_ASYNC_OPTIONS_DEFAULT_PAGE_SIZE,
10
- zMergeAsyncOptions,
11
- zResolveAsyncOptionsHasMore,
12
- type ZAsyncOptionsCursor,
13
- } from '../../utils/async-options';
14
- import { zMergeClasses } from '../../utils/merge-classes';
15
- import { zRefAt } from '../../utils/refs';
16
- import { zHighlightParts } from '../../utils/text';
17
- import ZButton from '../z-button/ZButton.svelte';
18
- import ZIcon from '../z-icon/ZIcon.svelte';
19
- import type { ZIcon as ZIconName } from '../z-icon/z-icon.types';
20
- import ZPopover from '../z-popover/ZPopover.svelte';
21
- import type { ZPopoverPosition, ZPopoverWidth } from '../z-popover/z-popover.types';
22
- import { Z_SELECT_DEFAULT_CONFIG } from './z-select.define';
23
- import type {
24
- ZSelectAsyncValidateOn,
25
- ZSelectAsyncValidator,
26
- ZSelectConfig,
27
- ZSelectLoadMoreEvent,
28
- ZSelectMode,
29
- ZSelectOption,
30
- ZSelectSize,
31
- ZSelectTagWidth,
32
- ZSelectTreeLevel,
33
- ZSelectValidationValue,
34
- ZSelectValidator,
35
- ZSelectVariant,
36
- } from './z-select.types';
37
- import {
38
- filterOptions,
39
- getTagColor,
40
- zGetSelectTagTruncationIndex,
41
- zGetSelectTagVisibleCount,
42
- zGetSelectValueKey,
43
- zIsSelectValueEqual,
44
- } from './z-select.utils';
45
- import { zSelectOptionVariants, zSelectTagVariants, zSelectVariants } from './z-select.variants';
46
- import { zTooltip } from '../z-tooltip/z-tooltip.svelte';
47
- import type { ZTooltipOptions } from '../z-tooltip/z-tooltip.types';
48
-
49
- type V = O['value'];
50
-
51
- interface Props {
52
- class?: ClassValue;
53
- /** Extra classes for the check mark in the dropdown. */
54
- zClassSelect?: ClassValue;
55
- zMode?: ZSelectMode;
56
- zSize?: ZSelectSize;
57
- zVariant?: ZSelectVariant;
58
- zLabel?: string;
59
- zLabelClass?: ClassValue;
60
- zPlaceholder?: string;
61
- zRequired?: boolean;
62
- zDisabled?: boolean;
63
- zReadonly?: boolean;
64
- zLoading?: boolean;
65
- zLoadingOutline?: boolean;
66
- zPrefix?: ZIconName;
67
- zAllowClear?: boolean;
68
- zShowCheck?: boolean;
69
- /** Multiple mode: let tags wrap onto several lines (otherwise the crossing tag ellipsizes). */
70
- zWrap?: boolean;
71
- zShowSearch?: boolean;
72
- zPlaceholderSearch?: string;
73
- zDebounce?: number;
74
- zNotFoundText?: string;
75
- zEmptyText?: string;
76
- zEmptyIcon?: ZIconName;
77
- zMaxTagCount?: number | null;
78
- /** Width of every selected tag; numbers are pixels. */
79
- zTagWidth?: ZSelectTagWidth;
80
- zDropdownMaxHeight?: number;
81
- zDropdownWidth?: ZPopoverWidth;
82
- zOptionHeight?: number;
83
- zVirtualScroll?: boolean;
84
- /** Measure each virtual row (rich option snippets with varying height). */
85
- zDynamicSize?: boolean;
86
- zShowAction?: boolean;
87
- zOptions?: O[];
88
- zConfig?: Partial<ZSelectConfig<O>>;
89
- zTranslateLabels?: boolean;
90
- /** Compare object values by this key (`value.id`, …). */
91
- zKey?: string;
92
- /** Filtering happens outside: listen to `onSearch` and feed `zOptions`. */
93
- zSearchServer?: boolean;
94
- zLoadingMore?: boolean;
95
- zEnableLoadMore?: boolean;
96
- /** Virtual lists ask for more once within `clientHeight * zScrollDistance` of the end. */
97
- zScrollDistance?: number;
98
- /** Switch to virtual scrolling past this many options. */
99
- zMaxVisible?: number | null;
100
- zScrollClose?: boolean;
101
- zPosition?: ZPopoverPosition;
102
- zTree?: boolean;
103
- zTreeRootLabel?: string;
104
- zValidators?: ZSelectValidator<O>[];
105
- zAsyncValidators?: ZSelectAsyncValidator<O>[];
106
- zAsyncDebounce?: number;
107
- zAsyncValidateOn?: ZSelectAsyncValidateOn;
108
- /** Native form field name: renders hidden inputs so the value submits with a `<form>`. */
109
- name?: string;
110
- id?: string;
111
- /** `bind:value` — a value (single) or an array (multiple/tags). */
112
- value?: V | V[] | null;
113
- /** `bind:open` — dropdown visibility. */
114
- open?: boolean;
115
- onValueChange?: (value: V | V[] | null) => void;
116
- onSearch?: (keyword: string) => void;
117
- onLoadMore?: (event: ZSelectLoadMoreEvent) => void;
118
- onFocus?: () => void;
119
- onBlur?: () => void;
120
- /** Renders a dropdown option. */
121
- option?: Snippet<[O, boolean]>;
122
- /** Renders the chosen option(s) inside the trigger. */
123
- selection?: Snippet<[O]>;
124
- /** Replaces the footer (shown with `zShowAction`). */
125
- actions?: Snippet;
126
- }
127
-
128
- let {
129
- class: className,
130
- zClassSelect = '',
131
- zMode = 'single',
132
- zSize = 'default',
133
- zVariant = 'default',
134
- zLabel = '',
135
- zLabelClass = '',
136
- zPlaceholder = '',
137
- zRequired = false,
138
- zDisabled = false,
139
- zReadonly = false,
140
- zLoading = false,
141
- zLoadingOutline = false,
142
- zPrefix,
143
- zAllowClear = false,
144
- zShowCheck = true,
145
- zWrap = true,
146
- zShowSearch = true,
147
- zPlaceholderSearch = '',
148
- zDebounce = 300,
149
- zNotFoundText = '',
150
- zEmptyText = '',
151
- zEmptyIcon = 'lucideInbox',
152
- zMaxTagCount = null,
153
- zTagWidth = null,
154
- zDropdownMaxHeight = 256,
155
- zDropdownWidth = 'trigger',
156
- zOptionHeight = 32,
157
- zVirtualScroll = false,
158
- zDynamicSize = false,
159
- zShowAction = false,
160
- zOptions = [],
161
- zConfig = {},
162
- zTranslateLabels = true,
163
- zKey = '',
164
- zSearchServer = false,
165
- zLoadingMore = false,
166
- zEnableLoadMore = false,
167
- zScrollDistance = 2,
168
- zMaxVisible = null,
169
- zScrollClose = false,
170
- zPosition = 'bottom',
171
- zTree = false,
172
- zTreeRootLabel = '',
173
- zValidators = [],
174
- zAsyncValidators = [],
175
- zAsyncDebounce = 300,
176
- zAsyncValidateOn = 'change',
177
- name,
178
- id,
179
- value = $bindable(null),
180
- open = $bindable(false),
181
- onValueChange,
182
- onSearch,
183
- onLoadMore,
184
- onFocus,
185
- onBlur,
186
- option: optionSnippet,
187
- selection,
188
- actions,
189
- }: Props = $props();
190
-
191
- const uid = $props.id();
192
- const selectId = $derived(id ?? `z-select-${uid}`);
193
- const errorId = $derived(`${selectId}-error`);
194
- const dropdownId = $derived(`${selectId}-dropdown`);
195
-
196
- let trigger = $state<HTMLDivElement | null>(null);
197
- let tagsWrapper = $state<HTMLDivElement | null>(null);
198
- let arrow = $state<HTMLSpanElement | null>(null);
199
- let remainingMeasure = $state<HTMLSpanElement | null>(null);
200
- let searchInput = $state<HTMLInputElement | null>(null);
201
- let optionsEl = $state<HTMLDivElement | null>(null);
202
- let sentinel = $state<HTMLDivElement | null>(null);
203
- const tagEls: HTMLElement[] = [];
204
-
205
- let query = $state('');
206
- let searchText = $state('');
207
- let touched = $state(false);
208
- let dirty = $state(false);
209
- let validating = $state(false);
210
- let customError = $state<string | null>(null);
211
- let asyncErrors = $state<Record<string, string>>({});
212
-
213
- // ---------- config / options ----------
214
- const config = $derived<ZSelectConfig<O>>({ ...Z_SELECT_DEFAULT_CONFIG, ...zConfig });
215
- const asyncConfig = $derived(config.async);
216
- const hasAsync = $derived(!!asyncConfig?.load);
217
- const hasPaginated = $derived(hasAsync || zEnableLoadMore);
218
- const debounceTime = $derived(zConfig.debounceTime ?? zDebounce);
219
-
220
- let asyncOptions = $state.raw<O[]>([]);
221
- let asyncKeyword = $state('');
222
- let asyncPage = $state(1);
223
- let asyncCursor: ZAsyncOptionsCursor | null = null;
224
- let asyncHasMore = $state(false);
225
- let asyncLoading = $state(false);
226
- let asyncLoadingMore = $state(false);
227
- let knownOptionsRaw = $state.raw<O[]>([]);
228
-
229
- const translate = (option: O): O =>
230
- zTranslateLabels ? ({ ...option, label: zTranslate(option.label) } as O) : option;
231
-
232
- const sourceOptions = $derived(hasAsync ? asyncOptions : zOptions);
233
- const translatedOptions = $derived(zTranslateLabels ? sourceOptions.map(translate) : sourceOptions);
234
- const asyncSelected = $derived.by(() => {
235
- const selected = asyncConfig?.selectedOptions;
236
- if (!selected) {
237
- return [];
238
- }
239
- const list = Array.isArray(selected) ? selected : selected();
240
- return zTranslateLabels ? list.map(translate) : list;
241
- });
242
- const remote = $derived(zSearchServer || hasAsync);
243
- const knownOptions = $derived(
244
- remote ? zMergeAsyncOptions(knownOptionsRaw, asyncSelected, asyncConfig?.dedupeBy) : translatedOptions
245
- );
246
-
247
- // Remote options come and go page by page; remember every option seen so labels survive.
248
- $effect(() => {
249
- if (!remote) {
250
- return;
251
- }
252
- const next = translatedOptions;
253
- untrack(() => {
254
- const merged = zMergeAsyncOptions(knownOptionsRaw, next, asyncConfig?.dedupeBy);
255
- if (merged.length > knownOptionsRaw.length) {
256
- knownOptionsRaw = merged;
257
- }
258
- });
259
- });
260
-
261
- const isMultiple = $derived(zMode === 'multiple' || zMode === 'tags');
262
- const isTags = $derived(zMode === 'tags');
263
- const isDisabled = $derived(zDisabled);
264
- const isInteractionDisabled = $derived(zDisabled || zReadonly || zLoading);
265
- const isLoading = $derived(zLoading || asyncLoading);
266
- const isLoadingMore = $derived(zLoadingMore || asyncLoadingMore);
267
- const canLoadMore = $derived(hasAsync ? asyncHasMore : zEnableLoadMore);
268
-
269
- const isEqual = (left: unknown, right: unknown): boolean => zIsSelectValueEqual(left, right, zKey);
270
- /** Comparable identity of a value (respects `zKey` for object values). */
271
- const keyOf = (item: unknown): unknown => zGetSelectValueKey(item, zKey);
272
- const valueList = $derived<V[]>(Array.isArray(value) ? value : []);
273
- /** Every chosen value as a list, whatever the mode — single values become a one-item list. */
274
- const chosenValues = $derived.by<V[]>(() => {
275
- if (isMultiple) {
276
- return valueList;
277
- }
278
- return value == null ? [] : [value as V];
279
- });
280
-
281
- // O(1) lookups instead of scanning every option per selected value — matters with 10k options.
282
- const selectedKeys = $derived(new Set(chosenValues.map(keyOf)));
283
- const isSelected = (option: O): boolean => selectedKeys.has(keyOf(option.value));
284
-
285
- const optionIndex = $derived.by(() => {
286
- // Rebuilt whole on every run of this $derived, never mutated in place: no SvelteMap needed.
287
- // eslint-disable-next-line svelte/prefer-svelte-reactivity
288
- const index = new Map<unknown, O>();
289
- const visit = (options: O[]): void => {
290
- for (const option of options) {
291
- const key = keyOf(option.value);
292
- if (!index.has(key)) {
293
- index.set(key, option);
294
- }
295
- if (option.children?.length) {
296
- visit(option.children as O[]);
297
- }
298
- }
299
- };
300
- visit(knownOptions);
301
- return index;
302
- });
303
- const findOption = (target: unknown): O | undefined => optionIndex.get(keyOf(target));
304
-
305
- const selectedOption = $derived(
306
- isMultiple || value == null || Array.isArray(value) ? null : (findOption(value) ?? null)
307
- );
308
- const selectedOptions = $derived(
309
- isMultiple ? valueList.map(item => findOption(item)).filter((o): o is O => !!o) : []
310
- );
311
- const selected = $derived.by(() => {
312
- if (isMultiple) {
313
- return selectedOptions;
314
- }
315
- return selectedOption ? [selectedOption] : [];
316
- });
317
- const hasValue = $derived(selected.length > 0);
318
-
319
- const filteredOptions = $derived(remote ? translatedOptions : filterOptions(translatedOptions, searchText));
320
- const isEmptyData = $derived(remote && searchText.trim() ? false : translatedOptions.length === 0);
321
- const isAllSelected = $derived.by(() => {
322
- if (!isMultiple) {
323
- return false;
324
- }
325
- const enabled = translatedOptions.filter(option => !option.disabled);
326
- return enabled.length > 0 && enabled.every(isSelected);
327
- });
328
-
329
- const hasActionBar = $derived(zShowAction && (!!actions || isMultiple));
330
- const optionsMaxHeight = $derived(zDropdownMaxHeight - (zShowSearch ? 44 : 0) - (hasActionBar ? 40 : 0));
331
- const useVirtual = $derived.by(() => {
332
- if (zVirtualScroll) {
333
- return true;
334
- }
335
- if (zMaxVisible !== null && sourceOptions.length > zMaxVisible) {
336
- return true;
337
- }
338
- if (canLoadMore || (hasAsync && asyncPage > 1)) {
339
- return false;
340
- }
341
- return sourceOptions.length > 50;
342
- });
343
-
344
- const placeholder = $derived(zPlaceholder || zTranslate('i18n_z_ui_select_placeholder'));
345
- const searchPlaceholder = $derived(zPlaceholderSearch || zTranslate('i18n_z_ui_select_search'));
346
- const notFoundText = $derived(zNotFoundText || zTranslate('i18n_z_ui_select_no_results'));
347
- const emptyText = $derived(zEmptyText || zTranslate('i18n_z_ui_select_no_options'));
348
-
349
- // ---------- validation ----------
350
- const showValidation = $derived(dirty || touched);
351
- const validationErrors = $derived.by(() => {
352
- if (!showValidation) {
353
- return [];
354
- }
355
- const errors: string[] = [];
356
- if (zRequired && !hasValue) {
357
- errors.push(zTranslate('i18n_z_ui_select_required'));
358
- }
359
- const current = (isMultiple ? selectedOptions : selectedOption) as ZSelectValidationValue<O>;
360
- for (const validator of zValidators) {
361
- if (!validator.validate(current)) {
362
- errors.push(validator.message);
363
- }
364
- }
365
- return errors;
366
- });
367
- const asyncErrorList = $derived(Object.values(asyncErrors));
368
- const hasErrorState = $derived(
369
- !!customError || (asyncErrorList.length > 0 && showValidation) || validationErrors.length > 0
370
- );
371
- const errorText = $derived(customError || asyncErrorList[0] || validationErrors[0] || '');
372
-
373
- // First matching state wins: disabled beats readonly beats open beats error.
374
- const status = $derived.by(() => {
375
- if (isDisabled) {
376
- return 'disabled';
377
- }
378
- if (zReadonly) {
379
- return 'readonly';
380
- }
381
- if (open) {
382
- return 'open';
383
- }
384
- return hasErrorState ? 'error' : 'default';
385
- });
386
-
387
- const triggerClasses = $derived(
388
- zMergeClasses(
389
- zSelectVariants({ zVariant, zSize, zStatus: status }),
390
- zLoading && zLoadingOutline && 'z-loading-outline-active !ring-ring/50 !ring-[3px]',
391
- !zWrap && isMultiple && { 'h-8': zSize === 'sm', 'h-9': zSize === 'default', 'h-10': zSize === 'lg' },
392
- className
393
- )
394
- );
395
-
396
- // ---------- value changes ----------
397
- function commit(next: V | V[] | null): void {
398
- value = next;
399
- dirty = true;
400
- onValueChange?.(next);
401
- }
402
-
403
- function selectOption(option: O): void {
404
- if (option.disabled) {
405
- return;
406
- }
407
-
408
- if (isMultiple) {
409
- const exists = valueList.some(item => isEqual(item, option.value));
410
- const next = exists ? valueList.filter(item => !isEqual(item, option.value)) : [...valueList, option.value];
411
- commit(next);
412
- triggerAsyncValidation(next.map(item => findOption(item)).filter((o): o is O => !!o));
413
- return;
414
- }
415
-
416
- commit(option.value);
417
- triggerAsyncValidation(option);
418
- open = false;
419
- }
420
-
421
- function removeOption(event: MouseEvent, option: O): void {
422
- event.stopPropagation();
423
- commit(valueList.filter(item => !isEqual(item, option.value)));
424
- }
425
-
426
- function clearAll(event: MouseEvent): void {
427
- event.stopPropagation();
428
- commit(isMultiple ? [] : null);
429
- }
430
-
431
- function toggleSelectAll(): void {
432
- if (!isMultiple) {
433
- return;
434
- }
435
- commit(isAllSelected ? [] : translatedOptions.filter(option => !option.disabled).map(option => option.value));
436
- }
437
-
438
- // ---------- open / close ----------
439
- let wasOpen = false;
440
- $effect.pre(() => {
441
- const isOpen = open;
442
- untrack(() => {
443
- if (isOpen === wasOpen) {
444
- return;
445
- }
446
- wasOpen = isOpen;
447
- if (isOpen) {
448
- handleShow();
449
- } else {
450
- handleHide();
451
- }
452
- });
453
- });
454
-
455
- function handleShow(): void {
456
- if (isInteractionDisabled) {
457
- open = false;
458
- return;
459
- }
460
- keyboardNav = false;
461
- resetTagLayout();
462
- resetTree();
463
- query = '';
464
- searchText = '';
465
- onSearch?.('');
466
- if (asyncConfig?.loadOnFocus && !(asyncKeyword === '' && asyncOptions.length > 0)) {
467
- loadAsync('', false);
468
- }
469
- onFocus?.();
470
- }
471
-
472
- function handleHide(): void {
473
- clearTimeout(searchTimer);
474
- if (dirty) {
475
- touched = true;
476
- }
477
- if (zAsyncValidateOn === 'blur') {
478
- triggerAsyncValidation(isMultiple ? selectedOptions : selectedOption, true);
479
- }
480
- onBlur?.();
481
- trigger?.blur();
482
- }
483
-
484
- function handleClosed(): void {
485
- if (remote) {
486
- query = '';
487
- searchText = '';
488
- }
489
- }
490
-
491
- function toggle(): void {
492
- if (isInteractionDisabled) {
493
- return;
494
- }
495
- open = !open;
496
- }
497
-
498
- function onTriggerKeydown(event: KeyboardEvent): void {
499
- if (isInteractionDisabled) {
500
- return;
501
- }
502
- if (open && (event.key !== ' ' || !zShowSearch)) {
503
- // Search hidden: the trigger itself drives the list.
504
- if (event.key === ' ') {
505
- event.preventDefault();
506
- } else {
507
- return onListKeydown(event);
508
- }
509
- }
510
- if (event.key === 'Enter' || event.key === ' ' || event.key === 'ArrowDown') {
511
- event.preventDefault();
512
- toggle();
513
- }
514
- }
515
-
516
- /** Focus the search box once the panel is positioned, without scrolling the page. */
517
- function focusSearch(): void {
518
- if (!zShowSearch || window.matchMedia('(max-width: 767px)').matches) {
519
- return;
520
- }
521
- searchInput?.focus({ preventScroll: true });
522
- }
523
-
524
- // ---------- search ----------
525
- let searchTimer: ReturnType<typeof setTimeout> | undefined;
526
-
527
- function onSearchInput(text: string): void {
528
- query = text;
529
- clearTimeout(searchTimer);
530
- searchTimer = setTimeout(() => {
531
- searchText = text;
532
- onSearch?.(text);
533
- if (hasAsync) {
534
- loadAsync(text, false);
535
- } else if (zSearchServer) {
536
- pendingServerReset = true;
537
- } else {
538
- resetScrollTop();
539
- }
540
- }, debounceTime);
541
- }
542
-
543
- let pendingServerReset = false;
544
- $effect(() => {
545
- void zOptions;
546
- untrack(() => {
547
- if (!zSearchServer || !pendingServerReset) {
548
- return;
549
- }
550
- pendingServerReset = false;
551
- resetScrollTop();
552
- });
553
- });
554
-
555
- // ---------- scrolling / virtual ----------
556
- // TanStack Virtual, same engine as core-ui's @tanstack/angular-virtual.
557
- const virtualizer = createVirtualizer<HTMLDivElement, HTMLDivElement>({
558
- count: 0,
559
- getScrollElement: () => optionsEl,
560
- estimateSize: () => zOptionHeight,
561
- gap: 3,
562
- overscan: 5,
563
- });
564
-
565
- // Push the current list into the virtualizer; it re-attaches when the dropdown remounts the list.
566
- $effect(() => {
567
- const options = {
568
- count: useVirtual ? filteredOptions.length : 0,
569
- estimateSize: () => zOptionHeight,
570
- getScrollElement: () => optionsEl,
571
- getItemKey: (index: number) => {
572
- const option = filteredOptions[index];
573
- return option ? String(key(option)) : index;
574
- },
575
- };
576
- void optionsEl;
577
- untrack(() => $virtualizer.setOptions(options));
578
- });
579
-
580
- function resetScrollTop(): void {
581
- requestAnimationFrame(() => {
582
- if (!optionsEl) {
583
- return;
584
- }
585
- if (useVirtual) {
586
- $virtualizer.scrollToOffset(0);
587
- }
588
- optionsEl.scrollTop = 0;
589
- });
590
- }
591
-
592
- function onOptionsScroll(event: Event & { currentTarget: HTMLDivElement }): void {
593
- const el = event.currentTarget;
594
- if (!useVirtual || !canLoadMore || isLoadingMore) {
595
- return;
596
- }
597
- if (el.scrollHeight - el.scrollTop - el.clientHeight <= el.clientHeight * zScrollDistance) {
598
- loadMore(el.scrollTop);
599
- }
600
- }
601
-
602
- // Non-virtual lists load the next page when a sentinel nears the bottom.
603
- $effect(() => {
604
- const target = sentinel;
605
- const root = optionsEl;
606
- if (!target || !root || !open || !canLoadMore || useVirtual) {
607
- return;
608
- }
609
- const observer = new IntersectionObserver(
610
- entries => {
611
- if (entries[0]?.isIntersecting && !isLoadingMore) {
612
- loadMore(root.scrollTop);
613
- }
614
- },
615
- { root, rootMargin: '100px', threshold: 0 }
616
- );
617
- observer.observe(target);
618
- return () => observer.disconnect();
619
- });
620
-
621
- function loadMore(scrollTop: number): void {
622
- if (hasAsync) {
623
- if (canLoadMore) {
624
- loadAsync(asyncKeyword, true);
625
- }
626
- return;
627
- }
628
- onLoadMore?.({ currentCount: filteredOptions.length, scrollTop });
629
- }
630
-
631
- // ---------- async options ----------
632
- let requestId = 0;
633
- let abort: AbortController | null = null;
634
-
635
- function loadAsync(keyword: string, append: boolean): void {
636
- const cfg = asyncConfig;
637
- if (!cfg) {
638
- return;
639
- }
640
-
641
- const normalized = keyword.trim();
642
- const pageSize = cfg.pageSize ?? Z_ASYNC_OPTIONS_DEFAULT_PAGE_SIZE;
643
- const canLoadEmpty = cfg.loadOnFocus && normalized.length === 0;
644
-
645
- if (!append && normalized.length < config.minLength && !canLoadEmpty) {
646
- resetAsync();
647
- return;
648
- }
649
- if (append && (!asyncHasMore || asyncLoading || asyncLoadingMore)) {
650
- return;
651
- }
652
-
653
- const page = append ? asyncPage + 1 : 1;
654
- const cursor = append ? asyncCursor : null;
655
- const id = ++requestId;
656
- const scrollBefore = append ? (optionsEl?.scrollTop ?? null) : null;
657
-
658
- if (!append) {
659
- abort?.abort();
660
- asyncKeyword = normalized;
661
- asyncLoading = true;
662
- asyncHasMore = false;
663
- } else {
664
- asyncLoadingMore = true;
665
- }
666
- abort = new AbortController();
667
-
668
- Promise.resolve()
669
- .then(() => cfg.load({ keyword: normalized, page, pageSize, cursor, signal: abort!.signal }))
670
- .then(response => {
671
- if (id !== requestId) {
672
- return;
673
- }
674
- const items = response.items ?? [];
675
- const previous = asyncOptions.length;
676
- const merged = zMergeAsyncOptions(append ? asyncOptions : [], items, cfg.dedupeBy);
677
-
678
- if (append && merged.length <= previous) {
679
- asyncHasMore = false;
680
- } else {
681
- asyncOptions = merged;
682
- asyncPage = page;
683
- asyncCursor = response.nextCursor ?? null;
684
- asyncHasMore = zResolveAsyncOptionsHasMore(response, pageSize, merged.length, cfg.paging);
685
- }
686
-
687
- if (scrollBefore !== null) {
688
- requestAnimationFrame(() => optionsEl && (optionsEl.scrollTop = scrollBefore));
689
- } else if (!append) {
690
- resetScrollTop();
691
- }
692
- })
693
- .catch(error => {
694
- if (id !== requestId || (error as Error)?.name === 'AbortError') {
695
- return;
696
- }
697
- console.error('ZSelect async options load failed:', error);
698
- if (!append) {
699
- asyncOptions = [];
700
- asyncPage = 1;
701
- asyncCursor = null;
702
- }
703
- asyncHasMore = false;
704
- })
705
- .finally(() => {
706
- if (id !== requestId) {
707
- return;
708
- }
709
- asyncLoading = false;
710
- asyncLoadingMore = false;
711
- });
712
- }
713
-
714
- function resetAsync(): void {
715
- abort?.abort();
716
- requestId++;
717
- asyncOptions = [];
718
- asyncKeyword = '';
719
- asyncPage = 1;
720
- asyncCursor = null;
721
- asyncHasMore = false;
722
- asyncLoading = false;
723
- asyncLoadingMore = false;
724
- }
725
-
726
- // ---------- async validation ----------
727
- let validationTimer: ReturnType<typeof setTimeout> | undefined;
728
- let validationAbort: AbortController | null = null;
729
-
730
- function triggerAsyncValidation(current: ZSelectValidationValue<O>, force = false): void {
731
- if (!zAsyncValidators.length || (!force && zAsyncValidateOn !== 'change')) {
732
- return;
733
- }
734
- clearTimeout(validationTimer);
735
- validationTimer = setTimeout(() => void runAsyncValidation(current), zAsyncDebounce || 300);
736
- }
737
-
738
- async function runAsyncValidation(current: ZSelectValidationValue<O>): Promise<void> {
739
- validationAbort?.abort();
740
- if (current == null) {
741
- asyncErrors = {};
742
- validating = false;
743
- return;
744
- }
745
-
746
- const controller = new AbortController();
747
- validationAbort = controller;
748
- validating = true;
749
-
750
- const results = await Promise.all(
751
- zAsyncValidators.map(async validator => {
752
- try {
753
- return { validator, ok: await validator.validate(current, controller.signal) };
754
- } catch (error) {
755
- if (!controller.signal.aborted) {
756
- console.error(`Async validation error for ${validator.error}:`, error);
757
- }
758
- return { validator, ok: false };
759
- }
760
- })
761
- );
762
- if (controller.signal.aborted) {
763
- return;
764
- }
765
-
766
- const errors: Record<string, string> = {};
767
- for (const { validator, ok } of results) {
768
- if (!ok) {
769
- errors[validator.error] = validator.message;
770
- }
771
- }
772
- asyncErrors = errors;
773
- validating = false;
774
- }
775
-
776
- // ---------- tree ----------
777
- let treeStack = $state.raw<ZSelectTreeLevel<O>[]>([]);
778
- let treeIndex = $state(0);
779
- let treeQuery = $state('');
780
- // Which edges of the option lists have more to show: they fade while scrolled (see `fades`).
781
- let listEdges = $state<ZScrollEdges>({ atTop: true, atEnd: true });
782
- let treeEdges = $state<ZScrollEdges>({ atTop: true, atEnd: true });
783
- let treeDirection = $state<'none' | 'forward' | 'back'>('none');
784
-
785
- const treeLevel = $derived(treeStack[treeIndex] ?? { label: '', options: [] });
786
- const treeCrumbs = $derived(
787
- treeStack
788
- .slice(0, treeIndex + 1)
789
- .map((level, index) => (index === 0 ? zTreeRootLabel || zTranslate('i18n_z_ui_select_tree_root') : level.label))
790
- );
791
- /** Every option without children below `options`, in order: what a search in a tree looks through. */
792
- function collectLeaves(options: O[]): O[] {
793
- return options.flatMap(option => (option.children?.length ? collectLeaves(option.children as O[]) : [option]));
794
- }
795
- // A search looks through everything under the level being shown, not only its own rows.
796
- const treeOptions = $derived(
797
- treeQuery.trim()
798
- ? filterOptions(zTranslateLabels ? collectLeaves(treeLevel.options).map(translate) : collectLeaves(treeLevel.options), treeQuery)
799
- : (zTranslateLabels ? treeLevel.options.map(translate) : treeLevel.options)
800
- );
801
-
802
- function findTreePath(options: O[], target: unknown): O[] | null {
803
- for (const option of options) {
804
- if (isEqual(option.value, target)) {
805
- return [option];
806
- }
807
- if (option.children?.length) {
808
- const path = findTreePath(option.children as O[], target);
809
- if (path) {
810
- return [option, ...path];
811
- }
812
- }
813
- }
814
- return null;
815
- }
816
-
817
- function resetTree(): void {
818
- if (!zTree) {
819
- return;
820
- }
821
- const stack: ZSelectTreeLevel<O>[] = [{ label: '', options: zOptions }];
822
- if (!isMultiple && value != null) {
823
- for (const ancestor of findTreePath(zOptions, value)?.slice(0, -1) ?? []) {
824
- stack.push({ label: translate(ancestor).label, options: (ancestor.children ?? []) as O[] });
825
- }
826
- }
827
- treeStack = stack;
828
- treeIndex = stack.length - 1;
829
- treeQuery = '';
830
- treeDirection = 'none';
831
- }
832
-
833
- function onTreeOptionClick(option: O): void {
834
- if (option.disabled) {
835
- return;
836
- }
837
- if (!option.children?.length) {
838
- selectOption(option);
839
- return;
840
- }
841
- const kept = treeStack.slice(0, treeIndex + 1);
842
- treeStack = [...kept, { label: option.label, options: option.children as O[] }];
843
- treeDirection = 'forward';
844
- treeIndex = kept.length;
845
- treeQuery = '';
846
- }
847
-
848
- function treeNavigateTo(index: number): void {
849
- if (index === treeIndex) {
850
- return;
851
- }
852
- treeDirection = 'back';
853
- treeIndex = index;
854
- treeQuery = '';
855
- }
856
-
857
- // ---------- keyboard (combobox pattern: focus stays on the input, options via activedescendant) ----------
858
- let activeIndex = $state(-1);
859
- /** The keyboard highlight only shows once arrows are used; the pointer has its own glide. */
860
- let keyboardNav = $state(false);
861
- const navOptions = $derived(zTree ? treeOptions : filteredOptions);
862
- const optionId = (index: number): string => `${dropdownId}-opt-${index}`;
863
-
864
- // Start from the selected option (or the first) whenever the visible list changes.
865
- $effect(() => {
866
- const list = navOptions;
867
- if (!open) {
868
- return;
869
- }
870
- untrack(() => {
871
- const current = list.findIndex(option => isSelected(option) && !option.disabled);
872
- activeIndex = current !== -1 ? current : list.findIndex(option => !option.disabled);
873
- });
874
- });
875
-
876
- function moveActive(step: 1 | -1 | 'first' | 'last'): void {
877
- const list = navOptions;
878
- if (!list.length) {
879
- return;
880
- }
881
- // Home/End start just outside the list and walk inwards, so disabled edge options are skipped too.
882
- let index: number;
883
- let delta: number;
884
- switch (step) {
885
- case 'first':
886
- index = -1;
887
- delta = 1;
888
- break;
889
- case 'last':
890
- index = list.length;
891
- delta = -1;
892
- break;
893
- default:
894
- index = activeIndex;
895
- delta = step;
896
- }
897
- for (let tries = 0; tries < list.length; tries++) {
898
- index = (index + delta + list.length) % list.length;
899
- if (!list[index]?.disabled) {
900
- break;
901
- }
902
- }
903
- activeIndex = index;
904
- keyboardNav = true;
905
- revealActive();
906
- }
907
-
908
- function revealActive(): void {
909
- requestAnimationFrame(() => {
910
- const container = optionsEl ?? document.getElementById(`${dropdownId}-list`);
911
- if (!container || activeIndex < 0) {
912
- return;
913
- }
914
- if (useVirtual && !zTree) {
915
- $virtualizer.scrollToIndex(activeIndex, { align: 'auto' });
916
- return;
917
- }
918
- document.getElementById(optionId(activeIndex))?.scrollIntoView({ block: 'nearest' });
919
- });
920
- }
921
-
922
- function onListKeydown(event: KeyboardEvent): void {
923
- if (event.isComposing) {
924
- return;
925
- }
926
- const list = navOptions;
927
- switch (event.key) {
928
- case 'ArrowDown':
929
- event.preventDefault();
930
- moveActive(1);
931
- break;
932
- case 'ArrowUp':
933
- event.preventDefault();
934
- moveActive(-1);
935
- break;
936
- case 'Home':
937
- case 'End':
938
- if (event.currentTarget instanceof HTMLInputElement) {
939
- return;
940
- }
941
- event.preventDefault();
942
- moveActive(event.key === 'Home' ? 'first' : 'last');
943
- break;
944
- case 'Enter': {
945
- const option = list[activeIndex];
946
- if (!option) {
947
- return;
948
- }
949
- event.preventDefault();
950
- if (zTree) {
951
- onTreeOptionClick(option);
952
- } else {
953
- selectOption(option);
954
- }
955
- break;
956
- }
957
- case 'Backspace':
958
- if (zTree && !treeQuery && treeIndex > 0) {
959
- event.preventDefault();
960
- treeNavigateTo(treeIndex - 1);
961
- }
962
- break;
963
- case 'Tab':
964
- open = false;
965
- break;
966
- }
967
- }
968
-
969
- // ---------- tag layout (nowrap) ----------
970
- let visibleTagCount = $state<number | null>(null);
971
- let truncatedIndex = $state<number | null>(null);
972
- let truncatedMaxWidth = $state<number | null>(null);
973
- let layoutVersion = $state(0);
974
-
975
- const tagWidthStyle = $derived.by(() => {
976
- if (zTagWidth === null || zTagWidth === '') {
977
- return null;
978
- }
979
- return typeof zTagWidth === 'number' ? `${zTagWidth}px` : zTagWidth;
980
- });
981
- const displayedTags = $derived.by(() => {
982
- if (zMaxTagCount === null) {
983
- return selectedOptions;
984
- }
985
- const max = Math.max(0, zMaxTagCount);
986
- return selectedOptions.slice(0, Math.min(max, zWrap ? max : (visibleTagCount ?? max)));
987
- });
988
- const remainingCount = $derived(Math.max(0, selectedOptions.length - displayedTags.length));
989
- const contentClasses = $derived(
990
- zMergeClasses(
991
- 'z-select-selected-content min-w-0 max-w-full overflow-hidden text-ellipsis whitespace-nowrap',
992
- tagWidthStyle && 'flex-1'
993
- )
994
- );
995
-
996
- function resetTagLayout(): void {
997
- truncatedIndex = null;
998
- truncatedMaxWidth = null;
999
- layoutVersion++;
1000
- }
1001
-
1002
- // Inputs that change tag geometry invalidate the current truncation.
1003
- $effect(() => {
1004
- void [selectedOptions, tagWidthStyle, zWrap, zMaxTagCount, selection];
1005
- untrack(() => {
1006
- if (truncatedIndex !== null) {
1007
- resetTagLayout();
1008
- }
1009
- });
1010
- });
1011
-
1012
- $effect(() => {
1013
- const wrapper = tagsWrapper;
1014
- const triggerEl = trigger;
1015
- if (!wrapper || !triggerEl || !isMultiple || zWrap) {
1016
- return;
1017
- }
1018
- void selectedOptions.length;
1019
-
1020
- const observer = new ResizeObserver(entries => {
1021
- const outerResized = entries.some(entry => entry.target === wrapper || entry.target === triggerEl);
1022
- if (!outerResized && truncatedIndex !== null) {
1023
- return;
1024
- }
1025
- resetTagLayout();
1026
- });
1027
- observer.observe(wrapper);
1028
- observer.observe(triggerEl);
1029
- for (const tag of tagEls.slice(0, selectedOptions.length)) {
1030
- if (tag) {
1031
- observer.observe(tag);
1032
- }
1033
- }
1034
- return () => observer.disconnect();
1035
- });
1036
-
1037
- // Measures after the DOM is updated (effects run post-render, pre-paint).
1038
- $effect(() => {
1039
- void layoutVersion;
1040
- const wrapper = tagsWrapper;
1041
- const triggerEl = trigger;
1042
- const arrowEl = arrow;
1043
- const count = selectedOptions.length;
1044
- void [tagWidthStyle, selection];
1045
-
1046
- untrack(() => {
1047
- if (!wrapper || !triggerEl || !arrowEl || !isMultiple || zWrap) {
1048
- visibleTagCount = null;
1049
- truncatedIndex = null;
1050
- truncatedMaxWidth = null;
1051
- return;
1052
- }
1053
- if (count === 0) {
1054
- visibleTagCount = 0;
1055
- truncatedIndex = null;
1056
- truncatedMaxWidth = null;
1057
- return;
1058
- }
1059
-
1060
- if (zMaxTagCount === null) {
1061
- if (truncatedIndex !== null) {
1062
- return;
1063
- }
1064
- const tagRects = tagEls.slice(0, count).map(el => {
1065
- const rect = el.getBoundingClientRect();
1066
- // Strip the enter animation's scale so a tag mid-animation measures at its final size.
1067
- const dx = (rect.width - el.offsetWidth) / 2;
1068
- const dy = (rect.height - el.offsetHeight) / 2;
1069
- return { left: rect.left + dx, right: rect.right - dx, top: rect.top + dy, bottom: rect.bottom - dy };
1070
- });
1071
- const wrapperRect = wrapper.getBoundingClientRect();
1072
- const triggerRect = triggerEl.getBoundingClientRect();
1073
- const arrowRect = arrowEl.getBoundingClientRect();
1074
- const index = zGetSelectTagTruncationIndex(tagRects, wrapperRect, triggerRect, arrowRect);
1075
- const clippingRight = Math.min(wrapperRect.right, triggerRect.right, arrowRect.left);
1076
- const tolerance = Math.max(1, Math.max(0, arrowRect.left - wrapperRect.right));
1077
- truncatedIndex = index;
1078
- truncatedMaxWidth = index === null ? null : Math.max(0, clippingRight - tolerance - tagRects[index].left);
1079
- return;
1080
- }
1081
-
1082
- truncatedIndex = null;
1083
- truncatedMaxWidth = null;
1084
- const gap = Number.parseFloat(getComputedStyle(wrapper).columnGap) || 0;
1085
- visibleTagCount = zGetSelectTagVisibleCount(
1086
- tagEls.slice(0, count).map(el => el.offsetWidth),
1087
- wrapper.getBoundingClientRect().width,
1088
- zMaxTagCount,
1089
- remainingMeasure?.offsetWidth ?? 0,
1090
- gap
1091
- );
1092
- });
1093
- });
1094
-
1095
- $effect(() => () => {
1096
- clearTimeout(searchTimer);
1097
- clearTimeout(validationTimer);
1098
- abort?.abort();
1099
- validationAbort?.abort();
1100
- });
1101
-
1102
- // ---------- public API (bind:this) ----------
1103
- /** Marks the field touched and returns true when it is valid. */
1104
- export function valid(): boolean {
1105
- touched = true;
1106
- dirty = true;
1107
- return !hasErrorState;
1108
- }
1109
-
1110
- /** @deprecated Use `valid()`. Returns true when there is an error. */
1111
- export function validate(): boolean {
1112
- return !valid();
1113
- }
1114
-
1115
- export function reset(): void {
1116
- customError = null;
1117
- asyncErrors = {};
1118
- value = isMultiple ? [] : null;
1119
- onValueChange?.(value);
1120
- touched = false;
1121
- dirty = false;
1122
- query = '';
1123
- searchText = '';
1124
- }
1125
-
1126
- export function focus(): void {
1127
- trigger?.focus({ preventScroll: true });
1128
- }
1129
-
1130
- export function blur(): void {
1131
- trigger?.blur();
1132
- }
1133
-
1134
- /** Shows a custom (e.g. server-side) error; `null` clears it. */
1135
- export function setErrorMessage(message: string | null): void {
1136
- customError = message;
1137
- if (message) {
1138
- touched = dirty = true;
1139
- }
1140
- }
1141
-
1142
- export function hasError(): boolean {
1143
- return hasErrorState;
1144
- }
1145
-
1146
- export function errorMessage(): string {
1147
- return errorText;
1148
- }
1149
-
1150
- export function isValidating(): boolean {
1151
- return validating;
1152
- }
1153
-
1154
- export function getSelected(): O[] {
1155
- return selected;
1156
- }
1157
-
1158
- const optionClass = (option: O, custom: boolean): string =>
1159
- zSelectOptionVariants({ customTemplate: custom, selected: isSelected(option), disabled: !!option.disabled });
1160
-
1161
- const tagClass = (option: O): string => {
1162
- const base = zSelectTagVariants({ zSize });
1163
- if (!isTags) {
1164
- return zMergeClasses(base, 'bg-muted text-foreground border-border');
1165
- }
1166
- const color = getTagColor(option.value);
1167
- return zMergeClasses(base, color.bg, color.text, color.border);
1168
- };
1169
-
1170
- const key = (option: O): unknown => zGetSelectValueKey(option.value, zKey);
1171
-
1172
- // Truncated labels get a tooltip (core-ui parity): plain hints in the list, arrowed ones on the
1173
- // trigger — which stay quiet while the dropdown is open and already shows the full label.
1174
- const optionTip = (label: string): ZTooltipOptions => ({
1175
- content: label,
1176
- autoDetect: true,
1177
- showDelay: 300,
1178
- arrow: false,
1179
- offset: 5,
1180
- });
1181
- const labelTip = (label: string, offset: number): ZTooltipOptions => ({
1182
- content: label,
1183
- autoDetect: true,
1184
- showDelay: 300,
1185
- offset,
1186
- disabled: open,
1187
- });
1188
- </script>
1189
-
1190
- {#snippet highlighted(label: string, text: string)}
1191
- {#each zHighlightParts(label, text) as part, index (index)}
1192
- {#if part.match}<span class="text-primary">{part.text}</span>{:else}{part.text}{/if}
1193
- {/each}
1194
- {/snippet}
1195
-
1196
- {#snippet empty(icon: ZIconName, message: string)}
1197
- <div class="col-span-full flex flex-col items-center justify-center px-2 py-8">
1198
- <ZIcon zType={icon} zSize="40" class="text-muted-foreground/50 mb-2 text-center" />
1199
- <p class="text-muted-foreground text-center text-xs font-medium">{message}</p>
1200
- </div>
1201
- {/snippet}
1202
-
1203
- {#snippet check()}
1204
- <ZIcon
1205
- zType="lucideCheck"
1206
- zSize="16"
1207
- zStrokeWidth={4}
1208
- class={zMergeClasses('text-primary mt-0 shrink-0', zClassSelect)}
1209
- />
1210
- {/snippet}
1211
-
1212
- {#snippet optionBody(option: O, highlightText: string)}
1213
- {@const chosen = isSelected(option)}
1214
- {#if optionSnippet}
1215
- <div class="flex min-w-0 items-start gap-2">
1216
- <div class="min-w-0 flex-1">{@render optionSnippet(option, chosen)}</div>
1217
- {#if zShowCheck && chosen}{@render check()}{/if}
1218
- </div>
1219
- {:else}
1220
- {#if option.icon}
1221
- <ZIcon zType={option.icon} zSize="16" class="text-muted-foreground shrink-0" />
1222
- {/if}
1223
- <span class="min-w-0 flex-1 truncate" {@attach zTooltip(optionTip(option.label))}>
1224
- {@render highlighted(option.label, highlightText)}
1225
- </span>
1226
- {#if zShowCheck && chosen}{@render check()}{/if}
1227
- {/if}
1228
- {/snippet}
1229
-
1230
- {#snippet groupHeading(label: string)}
1231
- <!-- A divider with the group's name, above its first option (`option.group`). A virtual list does not draw groups. -->
1232
- <div
1233
- role="presentation"
1234
- class="text-muted-foreground z-select-group mt-1 flex shrink-0 items-center gap-2 px-2 pt-1 pb-0.5 text-[10px] font-medium tracking-wide uppercase first:mt-0"
1235
- >
1236
- <span class="truncate">{label}</span>
1237
- <span class="bg-border h-px flex-1"></span>
1238
- </div>
1239
- {/snippet}
1240
-
1241
- {#snippet fades(edges: ZScrollEdges)}
1242
- <!-- Soft edges while a list is scrolled: the top once it left the start, the bottom while there is more below. -->
1243
- {#if !edges.atTop}
1244
- <div class="pointer-events-none absolute inset-x-0 top-0 h-6 bg-gradient-to-b from-popover to-transparent" aria-hidden="true"></div>
1245
- {/if}
1246
- {#if !edges.atTop && !edges.atEnd}
1247
- <div class="pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-popover to-transparent" aria-hidden="true"></div>
1248
- {/if}
1249
- {/snippet}
1250
-
1251
- {#snippet loadingMore()}
1252
- <div
1253
- class="z-select-loading-more from-popover via-popover/95 sticky bottom-0 -mx-1 -mb-1 flex items-center justify-center bg-gradient-to-t to-transparent pt-6 pb-2"
1254
- >
1255
- <ZIcon zType="lucideLoaderCircle" zSize="16" class="text-primary animate-spin" />
1256
- </div>
1257
- {/snippet}
1258
-
1259
- {#snippet searchBox(text: string, onInput: (text: string) => void)}
1260
- <div class="border-border flex items-center border-b px-3">
1261
- <ZIcon zType="lucideSearch" zSize="18" class="text-muted-foreground/50 mr-2 shrink-0" />
1262
- <input
1263
- bind:this={searchInput}
1264
- type="text"
1265
- class="placeholder:text-muted-foreground text-foreground flex h-10 w-full min-w-0 overflow-hidden bg-transparent py-3 text-sm text-ellipsis whitespace-nowrap outline-none"
1266
- placeholder={searchPlaceholder}
1267
- value={text}
1268
- oninput={event => onInput(event.currentTarget.value)}
1269
- onkeydown={onListKeydown}
1270
- role="combobox"
1271
- aria-expanded="true"
1272
- aria-autocomplete="list"
1273
- aria-activedescendant={activeIndex >= 0 ? optionId(activeIndex) : undefined}
1274
- autocomplete="off"
1275
- autocorrect="off"
1276
- spellcheck="false"
1277
- aria-controls={`${dropdownId}-list`}
1278
- />
1279
- </div>
1280
- {/snippet}
1281
-
1282
- <div class="z-select-wrapper relative flex w-full flex-col gap-2">
1283
- {#if zLabel}
1284
- <label for={selectId} class={zMergeClasses('text-xs leading-none font-medium', zLabelClass)}>
1285
- {zTranslate(zLabel)}
1286
- {#if zRequired}<span class="text-destructive! ml-0.5">*</span>{/if}
1287
- </label>
1288
- {/if}
1289
-
1290
- <div class="relative">
1291
- <div
1292
- bind:this={trigger}
1293
- id={selectId}
1294
- class={['z-select-trigger cursor-pointer', triggerClasses, open && 'z-select-open']}
1295
- tabindex={isDisabled ? -1 : 0}
1296
- role="combobox"
1297
- aria-expanded={open}
1298
- aria-haspopup="listbox"
1299
- aria-controls={dropdownId}
1300
- aria-activedescendant={open && !zShowSearch && activeIndex >= 0 ? optionId(activeIndex) : undefined}
1301
- aria-disabled={isInteractionDisabled || undefined}
1302
- aria-invalid={hasErrorState || undefined}
1303
- aria-describedby={hasErrorState && errorText ? errorId : undefined}
1304
- aria-required={zRequired || undefined}
1305
- onclick={toggle}
1306
- onkeydown={onTriggerKeydown}
1307
- >
1308
- {#if zPrefix}
1309
- <ZIcon zType={zPrefix} zSize="18" class="text-muted-foreground shrink-0" />
1310
- {/if}
1311
-
1312
- <div
1313
- bind:this={tagsWrapper}
1314
- class={[
1315
- 'z-select-tags-wrapper flex min-w-0 flex-1 items-center gap-1',
1316
- zMaxTagCount !== null && 'relative',
1317
- zWrap ? 'flex-wrap' : 'overflow-hidden',
1318
- ]}
1319
- >
1320
- {#if isMultiple}
1321
- {#if selectedOptions.length === 0}
1322
- <span class="text-muted-foreground min-w-0 flex-1 truncate whitespace-nowrap">{placeholder}</span>
1323
- {:else}
1324
- {#each selectedOptions as option, index (key(option))}
1325
- {@const truncated = !zWrap && index === truncatedIndex}
1326
- <span
1327
- {@attach zRefAt(tagEls, index)}
1328
- class={[
1329
- 'z-select-tag',
1330
- tagClass(option),
1331
- (zWrap || truncated) && 'min-w-0',
1332
- !zWrap && !truncated && 'z-select-tag-nowrap shrink-0',
1333
- truncated && 'z-select-tag-truncatable',
1334
- !zWrap && truncatedIndex !== null && index > truncatedIndex && 'z-select-tag-after-truncation',
1335
- index >= displayedTags.length && 'z-select-tag-hidden',
1336
- ]}
1337
- style:width={tagWidthStyle}
1338
- style:max-width={truncated && truncatedMaxWidth !== null ? `${truncatedMaxWidth}px` : null}
1339
- >
1340
- {#if selection}
1341
- <div class={contentClasses}>{@render selection(option)}</div>
1342
- {:else}
1343
- <span class={contentClasses} {@attach zTooltip(labelTip(option.label, 6))}>{option.label}</span>
1344
- {/if}
1345
- {#if zAllowClear && !isDisabled}
1346
- <button
1347
- type="button"
1348
- tabindex="-1"
1349
- aria-label={`Remove ${option.label}`}
1350
- class="-mr-0.5 flex size-3.5 shrink-0 items-center justify-center rounded-sm transition-colors hover:bg-black/10"
1351
- onclick={event => removeOption(event, option)}
1352
- >
1353
- <ZIcon zType="lucideX" zSize="10" />
1354
- </button>
1355
- {/if}
1356
- </span>
1357
- {/each}
1358
- {#if remainingCount > 0}
1359
- <span
1360
- class="z-select-remaining text-muted-foreground bg-muted rounded-sm px-1.5 py-0.5 text-xs font-medium"
1361
- >
1362
- +{remainingCount}
1363
- </span>
1364
- {/if}
1365
- {#if zMaxTagCount !== null}
1366
- <span
1367
- bind:this={remainingMeasure}
1368
- class="z-select-remaining-measure z-select-remaining text-muted-foreground bg-muted rounded-sm px-1.5 py-0.5 text-xs font-medium"
1369
- aria-hidden="true"
1370
- >
1371
- +{selectedOptions.length}
1372
- </span>
1373
- {/if}
1374
- {/if}
1375
- {:else if selectedOption}
1376
- {#if selection}
1377
- {@render selection(selectedOption)}
1378
- {:else}
1379
- {#if selectedOption.icon}
1380
- <ZIcon zType={selectedOption.icon} zSize="16" class="text-muted-foreground shrink-0" />
1381
- {/if}
1382
- <span class="truncate" {@attach zTooltip(labelTip(selectedOption.label, 10))}>{selectedOption.label}</span>
1383
- {/if}
1384
- {:else}
1385
- <span class="text-muted-foreground min-w-0 flex-1 truncate whitespace-nowrap">{placeholder}</span>
1386
- {/if}
1387
- </div>
1388
-
1389
- {#if isLoading || isLoadingMore}
1390
- <ZIcon zType="lucideLoaderCircle" zSize="18" class="text-muted-foreground shrink-0 animate-spin" />
1391
- {/if}
1392
-
1393
- {#if !isLoading && zAllowClear && hasValue && !isDisabled && !zReadonly}
1394
- <button
1395
- type="button"
1396
- tabindex="-1"
1397
- aria-label={zTranslate('i18n_z_ui_select_clear_all')}
1398
- class="text-muted-foreground hover:text-foreground flex shrink-0 items-center justify-center transition-colors"
1399
- onclick={clearAll}
1400
- >
1401
- <ZIcon zType="lucideX" zSize="18" />
1402
- </button>
1403
- {/if}
1404
-
1405
- {#if validating}
1406
- <ZIcon zType="lucideLoaderCircle" zSize="18" class="text-muted-foreground shrink-0 animate-spin" />
1407
- {/if}
1408
-
1409
- <span
1410
- bind:this={arrow}
1411
- class={[
1412
- 'text-muted-foreground flex shrink-0 items-center justify-center transition-transform duration-200',
1413
- open && 'rotate-180',
1414
- ]}
1415
- >
1416
- <ZIcon zType="lucideChevronDown" zSize="18" />
1417
- </span>
1418
- </div>
1419
-
1420
- {#if hasErrorState && errorText}
1421
- <p
1422
- id={errorId}
1423
- class="text-destructive animate-in fade-in slide-in-from-top-1 m-0 pt-2 text-xs duration-200"
1424
- role="alert"
1425
- >
1426
- {errorText}
1427
- </p>
1428
- {/if}
1429
- </div>
1430
-
1431
- {#if name}
1432
- {#each chosenValues as item, index (index)}
1433
- <input type="hidden" {name} value={String(zGetSelectValueKey(item, zKey))} />
1434
- {/each}
1435
- {/if}
1436
- </div>
1437
-
1438
- <ZPopover
1439
- anchor={trigger}
1440
- bind:open
1441
- zTrigger="manual"
1442
- {zPosition}
1443
- zOffset={6}
1444
- zWidth={zDropdownWidth}
1445
- {zScrollClose}
1446
- id={dropdownId}
1447
- class="z-select-dropdown"
1448
- onOpen={focusSearch}
1449
- onClosed={handleClosed}
1450
- >
1451
- {#if zTree}
1452
- {#if zShowSearch}{@render searchBox(treeQuery, text => (treeQuery = text))}{/if}
1453
-
1454
- {#if treeIndex > 0}
1455
- <div class="z-select-tree-crumbs border-border flex items-center gap-1 border-b px-2 py-1.5">
1456
- <button
1457
- type="button"
1458
- aria-label={zTranslate('i18n_z_ui_select_back')}
1459
- class="text-muted-foreground hover:text-foreground hover:bg-accent flex size-6 shrink-0 items-center justify-center rounded-sm transition-colors"
1460
- onclick={() => treeNavigateTo(Math.max(0, treeIndex - 1))}
1461
- >
1462
- <ZIcon zType="lucideChevronLeft" zSize="14" />
1463
- </button>
1464
- <nav class="flex min-w-0 flex-1 items-center gap-1 overflow-hidden text-xs" aria-label="Breadcrumb">
1465
- {#each treeCrumbs as crumb, index (index)}
1466
- {#if index > 0}<span class="text-muted-foreground/60 shrink-0">/</span>{/if}
1467
- {#if index === treeCrumbs.length - 1}
1468
- <span class="text-foreground truncate font-medium" aria-current="location">{crumb}</span>
1469
- {:else}
1470
- <button
1471
- type="button"
1472
- class="text-muted-foreground hover:text-foreground shrink-0 truncate transition-colors"
1473
- onclick={() => treeNavigateTo(index)}
1474
- >
1475
- {crumb}
1476
- </button>
1477
- {/if}
1478
- {/each}
1479
- </nav>
1480
- </div>
1481
- {/if}
1482
-
1483
- <div class="z-select-tree-viewport relative overflow-hidden" style:height={`${optionsMaxHeight}px`}>
1484
- {#key treeIndex}
1485
- <div
1486
- {@attach zHoverGlide()}
1487
- {@attach zScrollEdges(edges => (treeEdges = edges))}
1488
- id={`${dropdownId}-list`}
1489
- role="listbox"
1490
- class={[
1491
- 'absolute inset-0 flex flex-col gap-0.75 overflow-x-hidden overflow-y-auto overscroll-y-contain p-1',
1492
- treeDirection === 'forward' && 'z-select-tree-slide-left',
1493
- treeDirection === 'back' && 'z-select-tree-slide-right',
1494
- ]}
1495
- >
1496
- {#each treeOptions as option, index (key(option))}
1497
- {#if option.group && option.group !== treeOptions[index - 1]?.group}{@render groupHeading(option.group)}{/if}
1498
- <!-- svelte-ignore a11y_click_events_have_key_events (keyboard is handled by the combobox input) -->
1499
- <div
1500
- id={optionId(index)}
1501
- data-glide-item
1502
- data-active={keyboardNav && index === activeIndex}
1503
- role="option"
1504
- tabindex="-1"
1505
- aria-selected={isSelected(option)}
1506
- aria-disabled={option.disabled || undefined}
1507
- class={['z-select-option relative flex min-w-0 items-center gap-2', optionClass(option, !!optionSnippet)]}
1508
- style:min-height={optionSnippet ? null : `${zOptionHeight}px`}
1509
- onclick={() => onTreeOptionClick(option)}
1510
- >
1511
- <!-- The same template as a flat list, for a branch and for a leaf: the snippet tells them apart by `option.children`. -->
1512
- <div class="flex min-w-0 flex-1 items-center gap-2">{@render optionBody(option, treeQuery)}</div>
1513
- {#if option.children?.length}
1514
- <ZIcon zType="lucideChevronRight" zSize="16" class="text-muted-foreground shrink-0" />
1515
- {/if}
1516
- </div>
1517
- {:else}
1518
- <div class="flex size-full items-center justify-center">{@render empty('lucideSearchX', notFoundText)}</div>
1519
- {/each}
1520
- </div>
1521
- {/key}
1522
- {@render fades(treeEdges)}
1523
- </div>
1524
- {:else}
1525
- {#if zShowSearch}{@render searchBox(query, onSearchInput)}{/if}
1526
-
1527
- {#if isLoading}
1528
- <div class="flex items-center justify-center" style:height={`${optionsMaxHeight}px`}>
1529
- <ZIcon zType="lucideLoaderCircle" zSize="24" class="text-primary animate-spin" />
1530
- </div>
1531
- {:else if filteredOptions.length > 0}
1532
- <div class="relative">
1533
- <div
1534
- bind:this={optionsEl}
1535
- {@attach zHoverGlide()}
1536
- {@attach zScrollEdges(edges => (listEdges = edges))}
1537
- id={`${dropdownId}-list`}
1538
- role="listbox"
1539
- aria-multiselectable={isMultiple || undefined}
1540
- class={[
1541
- 'z-select-options overflow-x-hidden overflow-y-auto overscroll-y-contain p-1',
1542
- useVirtual ? 'z-select-virtual-scroll' : 'flex flex-col gap-0.75',
1543
- ]}
1544
- style:height={useVirtual || hasPaginated ? `${optionsMaxHeight}px` : null}
1545
- style:max-height={`${optionsMaxHeight}px`}
1546
- onscroll={onOptionsScroll}
1547
- >
1548
- {#if useVirtual}
1549
- <div class="z-select-virtual-inner relative" style:height={`${$virtualizer.getTotalSize()}px`}>
1550
- {#each $virtualizer.getVirtualItems() as item (item.key)}
1551
- {@const option = filteredOptions[item.index]}
1552
- {#if option}
1553
- <!-- svelte-ignore a11y_click_events_have_key_events (keyboard is handled by the combobox input) -->
1554
- <div
1555
- id={optionId(item.index)}
1556
- data-glide-item
1557
- data-active={keyboardNav && item.index === activeIndex}
1558
- data-index={item.index}
1559
- role="option"
1560
- tabindex="-1"
1561
- aria-selected={isSelected(option)}
1562
- aria-disabled={option.disabled || undefined}
1563
- class={['z-select-option absolute right-0 left-0 min-w-0', optionClass(option, !!optionSnippet)]}
1564
- style:height={zDynamicSize ? null : `${zOptionHeight}px`}
1565
- style:min-height={zDynamicSize ? `${zOptionHeight}px` : null}
1566
- style:transform={`translateY(${item.start}px)`}
1567
- onclick={() => selectOption(option)}
1568
- {@attach zDynamicSize ? (node: HTMLDivElement) => $virtualizer.measureElement(node) : null}
1569
- >
1570
- {@render optionBody(option, searchText)}
1571
- </div>
1572
- {/if}
1573
- {/each}
1574
- </div>
1575
- {:else}
1576
- {#each filteredOptions as option, index (key(option))}
1577
- {#if option.group && option.group !== filteredOptions[index - 1]?.group}{@render groupHeading(option.group)}{/if}
1578
- <!-- svelte-ignore a11y_click_events_have_key_events (keyboard is handled by the combobox input) -->
1579
- <div
1580
- id={optionId(index)}
1581
- data-glide-item
1582
- data-active={keyboardNav && index === activeIndex}
1583
- role="option"
1584
- tabindex="-1"
1585
- aria-selected={isSelected(option)}
1586
- aria-disabled={option.disabled || undefined}
1587
- class={['z-select-option relative min-w-0', optionClass(option, !!optionSnippet)]}
1588
- style:min-height={optionSnippet ? null : `${zOptionHeight}px`}
1589
- onclick={() => selectOption(option)}
1590
- >
1591
- {@render optionBody(option, searchText)}
1592
- </div>
1593
- {/each}
1594
- {#if canLoadMore}<div bind:this={sentinel} class="h-px w-full shrink-0"></div>{/if}
1595
- {/if}
1596
- {#if isLoadingMore}{@render loadingMore()}{/if}
1597
- </div>
1598
- {@render fades(listEdges)}
1599
- </div>
1600
- {:else}
1601
- <div class="flex items-center justify-center p-1" style:height={`${optionsMaxHeight}px`}>
1602
- {#if isEmptyData}
1603
- {@render empty(zEmptyIcon, emptyText)}
1604
- {:else}
1605
- {@render empty('lucideSearchX', notFoundText)}
1606
- {/if}
1607
- </div>
1608
- {/if}
1609
-
1610
- {#if hasActionBar}
1611
- <div class="border-border flex items-center gap-2 border-t px-2 py-1.5">
1612
- {#if actions}
1613
- {@render actions()}
1614
- {:else}
1615
- <ZButton
1616
- zSize="xs"
1617
- zType={isAllSelected ? 'ghost-error' : 'ghost-info'}
1618
- class="min-w-0 flex-1"
1619
- zWave={false}
1620
- onclick={toggleSelectAll}
1621
- >
1622
- <ZIcon zType={isAllSelected ? 'lucideX' : 'lucideCheckCheck'} zSize="18" class="shrink-0" />
1623
- <span class="truncate">
1624
- {isAllSelected ? zTranslate('i18n_z_ui_select_clear_all') : zTranslate('i18n_z_ui_select_select_all')}
1625
- </span>
1626
- </ZButton>
1627
- {/if}
1628
- </div>
1629
- {/if}
1630
- {/if}
1631
- </ZPopover>
1
+ <script lang="ts" generics="O extends ZSelectOption<any> = ZSelectOption">
2
+ import { untrack, type Snippet } from 'svelte';
3
+ import { createVirtualizer } from '@tanstack/svelte-virtual';
4
+ import type { ClassValue } from 'clsx';
5
+ import { zTranslate } from '../../i18n/translate.svelte';
6
+ import { zHoverGlide } from '../../interactions/z-hover-glide';
7
+ import { zScrollEdges, type ZScrollEdges } from '../../interactions/z-scroll-edges';
8
+ import {
9
+ Z_ASYNC_OPTIONS_DEFAULT_PAGE_SIZE,
10
+ zMergeAsyncOptions,
11
+ zResolveAsyncOptionsHasMore,
12
+ type ZAsyncOptionsCursor,
13
+ } from '../../utils/async-options';
14
+ import { zMergeClasses } from '../../utils/merge-classes';
15
+ import { zRefAt } from '../../utils/refs';
16
+ import { zHighlightParts } from '../../utils/text';
17
+ import ZButton from '../z-button/ZButton.svelte';
18
+ import ZIcon from '../z-icon/ZIcon.svelte';
19
+ import type { ZIcon as ZIconName } from '../z-icon/z-icon.types';
20
+ import ZPopover from '../z-popover/ZPopover.svelte';
21
+ import type { ZPopoverPosition, ZPopoverWidth } from '../z-popover/z-popover.types';
22
+ import { Z_SELECT_DEFAULT_CONFIG } from './z-select.define';
23
+ import type {
24
+ ZSelectAsyncValidateOn,
25
+ ZSelectAsyncValidator,
26
+ ZSelectConfig,
27
+ ZSelectLoadMoreEvent,
28
+ ZSelectMode,
29
+ ZSelectOption,
30
+ ZSelectSize,
31
+ ZSelectTagWidth,
32
+ ZSelectTreeLevel,
33
+ ZSelectValidationValue,
34
+ ZSelectValidator,
35
+ ZSelectVariant,
36
+ } from './z-select.types';
37
+ import {
38
+ filterOptions,
39
+ getTagColor,
40
+ zGetSelectTagTruncationIndex,
41
+ zGetSelectTagVisibleCount,
42
+ zGetSelectValueKey,
43
+ zIsSelectValueEqual,
44
+ } from './z-select.utils';
45
+ import { zSelectOptionVariants, zSelectTagVariants, zSelectVariants } from './z-select.variants';
46
+ import { zTooltip } from '../z-tooltip/z-tooltip.svelte';
47
+ import type { ZTooltipOptions } from '../z-tooltip/z-tooltip.types';
48
+
49
+ type V = O['value'];
50
+
51
+ interface Props {
52
+ class?: ClassValue;
53
+ /** Extra classes for the check mark in the dropdown. */
54
+ zClassSelect?: ClassValue;
55
+ zMode?: ZSelectMode;
56
+ zSize?: ZSelectSize;
57
+ zVariant?: ZSelectVariant;
58
+ zLabel?: string;
59
+ zLabelClass?: ClassValue;
60
+ zPlaceholder?: string;
61
+ zRequired?: boolean;
62
+ zDisabled?: boolean;
63
+ zReadonly?: boolean;
64
+ zLoading?: boolean;
65
+ zLoadingOutline?: boolean;
66
+ zPrefix?: ZIconName;
67
+ zAllowClear?: boolean;
68
+ zShowCheck?: boolean;
69
+ /** Multiple mode: let tags wrap onto several lines (otherwise the crossing tag ellipsizes). */
70
+ zWrap?: boolean;
71
+ zShowSearch?: boolean;
72
+ zPlaceholderSearch?: string;
73
+ zDebounce?: number;
74
+ zNotFoundText?: string;
75
+ zEmptyText?: string;
76
+ zEmptyIcon?: ZIconName;
77
+ zMaxTagCount?: number | null;
78
+ /** Width of every selected tag; numbers are pixels. */
79
+ zTagWidth?: ZSelectTagWidth;
80
+ zDropdownMaxHeight?: number;
81
+ zDropdownWidth?: ZPopoverWidth;
82
+ zOptionHeight?: number;
83
+ zVirtualScroll?: boolean;
84
+ /** Measure each virtual row (rich option snippets with varying height). */
85
+ zDynamicSize?: boolean;
86
+ zShowAction?: boolean;
87
+ zOptions?: O[];
88
+ zConfig?: Partial<ZSelectConfig<O>>;
89
+ zTranslateLabels?: boolean;
90
+ /** Compare object values by this key (`value.id`, …). */
91
+ zKey?: string;
92
+ /** Filtering happens outside: listen to `onSearch` and feed `zOptions`. */
93
+ zSearchServer?: boolean;
94
+ zLoadingMore?: boolean;
95
+ zEnableLoadMore?: boolean;
96
+ /** Virtual lists ask for more once within `clientHeight * zScrollDistance` of the end. */
97
+ zScrollDistance?: number;
98
+ /** Switch to virtual scrolling past this many options. */
99
+ zMaxVisible?: number | null;
100
+ zScrollClose?: boolean;
101
+ zPosition?: ZPopoverPosition;
102
+ zTree?: boolean;
103
+ zTreeRootLabel?: string;
104
+ zValidators?: ZSelectValidator<O>[];
105
+ zAsyncValidators?: ZSelectAsyncValidator<O>[];
106
+ zAsyncDebounce?: number;
107
+ zAsyncValidateOn?: ZSelectAsyncValidateOn;
108
+ /** Native form field name: renders hidden inputs so the value submits with a `<form>`. */
109
+ name?: string;
110
+ id?: string;
111
+ /** `bind:value` — a value (single) or an array (multiple/tags). */
112
+ value?: V | V[] | null;
113
+ /** `bind:open` — dropdown visibility. */
114
+ open?: boolean;
115
+ onValueChange?: (value: V | V[] | null) => void;
116
+ onSearch?: (keyword: string) => void;
117
+ onLoadMore?: (event: ZSelectLoadMoreEvent) => void;
118
+ onFocus?: () => void;
119
+ onBlur?: () => void;
120
+ /** Renders a dropdown option. */
121
+ option?: Snippet<[O, boolean]>;
122
+ /** Renders the chosen option(s) inside the trigger. */
123
+ selection?: Snippet<[O]>;
124
+ /** Replaces the footer (shown with `zShowAction`). */
125
+ actions?: Snippet;
126
+ }
127
+
128
+ let {
129
+ class: className,
130
+ zClassSelect = '',
131
+ zMode = 'single',
132
+ zSize = 'default',
133
+ zVariant = 'default',
134
+ zLabel = '',
135
+ zLabelClass = '',
136
+ zPlaceholder = '',
137
+ zRequired = false,
138
+ zDisabled = false,
139
+ zReadonly = false,
140
+ zLoading = false,
141
+ zLoadingOutline = false,
142
+ zPrefix,
143
+ zAllowClear = false,
144
+ zShowCheck = true,
145
+ zWrap = true,
146
+ zShowSearch = true,
147
+ zPlaceholderSearch = '',
148
+ zDebounce = 300,
149
+ zNotFoundText = '',
150
+ zEmptyText = '',
151
+ zEmptyIcon = 'lucideInbox',
152
+ zMaxTagCount = null,
153
+ zTagWidth = null,
154
+ zDropdownMaxHeight = 256,
155
+ zDropdownWidth = 'trigger',
156
+ zOptionHeight = 32,
157
+ zVirtualScroll = false,
158
+ zDynamicSize = false,
159
+ zShowAction = false,
160
+ zOptions = [],
161
+ zConfig = {},
162
+ zTranslateLabels = true,
163
+ zKey = '',
164
+ zSearchServer = false,
165
+ zLoadingMore = false,
166
+ zEnableLoadMore = false,
167
+ zScrollDistance = 2,
168
+ zMaxVisible = null,
169
+ zScrollClose = false,
170
+ zPosition = 'bottom',
171
+ zTree = false,
172
+ zTreeRootLabel = '',
173
+ zValidators = [],
174
+ zAsyncValidators = [],
175
+ zAsyncDebounce = 300,
176
+ zAsyncValidateOn = 'change',
177
+ name,
178
+ id,
179
+ value = $bindable(null),
180
+ open = $bindable(false),
181
+ onValueChange,
182
+ onSearch,
183
+ onLoadMore,
184
+ onFocus,
185
+ onBlur,
186
+ option: optionSnippet,
187
+ selection,
188
+ actions,
189
+ }: Props = $props();
190
+
191
+ const uid = $props.id();
192
+ const selectId = $derived(id ?? `z-select-${uid}`);
193
+ const errorId = $derived(`${selectId}-error`);
194
+ const dropdownId = $derived(`${selectId}-dropdown`);
195
+
196
+ let trigger = $state<HTMLDivElement | null>(null);
197
+ let tagsWrapper = $state<HTMLDivElement | null>(null);
198
+ let arrow = $state<HTMLSpanElement | null>(null);
199
+ let remainingMeasure = $state<HTMLSpanElement | null>(null);
200
+ let searchInput = $state<HTMLInputElement | null>(null);
201
+ let optionsEl = $state<HTMLDivElement | null>(null);
202
+ let sentinel = $state<HTMLDivElement | null>(null);
203
+ const tagEls: HTMLElement[] = [];
204
+
205
+ let query = $state('');
206
+ let searchText = $state('');
207
+ let touched = $state(false);
208
+ let dirty = $state(false);
209
+ let validating = $state(false);
210
+ let customError = $state<string | null>(null);
211
+ let asyncErrors = $state<Record<string, string>>({});
212
+
213
+ // ---------- config / options ----------
214
+ const config = $derived<ZSelectConfig<O>>({ ...Z_SELECT_DEFAULT_CONFIG, ...zConfig });
215
+ const asyncConfig = $derived(config.async);
216
+ const hasAsync = $derived(!!asyncConfig?.load);
217
+ const hasPaginated = $derived(hasAsync || zEnableLoadMore);
218
+ const debounceTime = $derived(zConfig.debounceTime ?? zDebounce);
219
+
220
+ let asyncOptions = $state.raw<O[]>([]);
221
+ let asyncKeyword = $state('');
222
+ let asyncPage = $state(1);
223
+ let asyncCursor: ZAsyncOptionsCursor | null = null;
224
+ let asyncHasMore = $state(false);
225
+ let asyncLoading = $state(false);
226
+ let asyncLoadingMore = $state(false);
227
+ let knownOptionsRaw = $state.raw<O[]>([]);
228
+
229
+ const translate = (option: O): O =>
230
+ zTranslateLabels ? ({ ...option, label: zTranslate(option.label) } as O) : option;
231
+
232
+ const sourceOptions = $derived(hasAsync ? asyncOptions : zOptions);
233
+ const translatedOptions = $derived(zTranslateLabels ? sourceOptions.map(translate) : sourceOptions);
234
+ const asyncSelected = $derived.by(() => {
235
+ const selected = asyncConfig?.selectedOptions;
236
+ if (!selected) {
237
+ return [];
238
+ }
239
+ const list = Array.isArray(selected) ? selected : selected();
240
+ return zTranslateLabels ? list.map(translate) : list;
241
+ });
242
+ const remote = $derived(zSearchServer || hasAsync);
243
+ const knownOptions = $derived(
244
+ remote ? zMergeAsyncOptions(knownOptionsRaw, asyncSelected, asyncConfig?.dedupeBy) : translatedOptions
245
+ );
246
+
247
+ // Remote options come and go page by page; remember every option seen so labels survive.
248
+ $effect(() => {
249
+ if (!remote) {
250
+ return;
251
+ }
252
+ const next = translatedOptions;
253
+ untrack(() => {
254
+ const merged = zMergeAsyncOptions(knownOptionsRaw, next, asyncConfig?.dedupeBy);
255
+ if (merged.length > knownOptionsRaw.length) {
256
+ knownOptionsRaw = merged;
257
+ }
258
+ });
259
+ });
260
+
261
+ const isMultiple = $derived(zMode === 'multiple' || zMode === 'tags');
262
+ const isTags = $derived(zMode === 'tags');
263
+ const isDisabled = $derived(zDisabled);
264
+ const isInteractionDisabled = $derived(zDisabled || zReadonly || zLoading);
265
+ const isLoading = $derived(zLoading || asyncLoading);
266
+ const isLoadingMore = $derived(zLoadingMore || asyncLoadingMore);
267
+ const canLoadMore = $derived(hasAsync ? asyncHasMore : zEnableLoadMore);
268
+
269
+ const isEqual = (left: unknown, right: unknown): boolean => zIsSelectValueEqual(left, right, zKey);
270
+ /** Comparable identity of a value (respects `zKey` for object values). */
271
+ const keyOf = (item: unknown): unknown => zGetSelectValueKey(item, zKey);
272
+ const valueList = $derived<V[]>(Array.isArray(value) ? value : []);
273
+ /** Every chosen value as a list, whatever the mode — single values become a one-item list. */
274
+ const chosenValues = $derived.by<V[]>(() => {
275
+ if (isMultiple) {
276
+ return valueList;
277
+ }
278
+ return value == null ? [] : [value as V];
279
+ });
280
+
281
+ // O(1) lookups instead of scanning every option per selected value — matters with 10k options.
282
+ const selectedKeys = $derived(new Set(chosenValues.map(keyOf)));
283
+ const isSelected = (option: O): boolean => selectedKeys.has(keyOf(option.value));
284
+
285
+ const optionIndex = $derived.by(() => {
286
+ // Rebuilt whole on every run of this $derived, never mutated in place: no SvelteMap needed.
287
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
288
+ const index = new Map<unknown, O>();
289
+ const visit = (options: O[]): void => {
290
+ for (const option of options) {
291
+ const key = keyOf(option.value);
292
+ if (!index.has(key)) {
293
+ index.set(key, option);
294
+ }
295
+ if (option.children?.length) {
296
+ visit(option.children as O[]);
297
+ }
298
+ }
299
+ };
300
+ visit(knownOptions);
301
+ return index;
302
+ });
303
+ const findOption = (target: unknown): O | undefined => optionIndex.get(keyOf(target));
304
+
305
+ const selectedOption = $derived(
306
+ isMultiple || value == null || Array.isArray(value) ? null : (findOption(value) ?? null)
307
+ );
308
+ const selectedOptions = $derived(
309
+ isMultiple ? valueList.map(item => findOption(item)).filter((o): o is O => !!o) : []
310
+ );
311
+ const selected = $derived.by(() => {
312
+ if (isMultiple) {
313
+ return selectedOptions;
314
+ }
315
+ return selectedOption ? [selectedOption] : [];
316
+ });
317
+ const hasValue = $derived(selected.length > 0);
318
+
319
+ const filteredOptions = $derived(remote ? translatedOptions : filterOptions(translatedOptions, searchText));
320
+ const isEmptyData = $derived(remote && searchText.trim() ? false : translatedOptions.length === 0);
321
+ const isAllSelected = $derived.by(() => {
322
+ if (!isMultiple) {
323
+ return false;
324
+ }
325
+ const enabled = translatedOptions.filter(option => !option.disabled);
326
+ return enabled.length > 0 && enabled.every(isSelected);
327
+ });
328
+
329
+ const hasActionBar = $derived(zShowAction && (!!actions || isMultiple));
330
+ const optionsMaxHeight = $derived(zDropdownMaxHeight - (zShowSearch ? 44 : 0) - (hasActionBar ? 40 : 0));
331
+ const useVirtual = $derived.by(() => {
332
+ if (zVirtualScroll) {
333
+ return true;
334
+ }
335
+ if (zMaxVisible !== null && sourceOptions.length > zMaxVisible) {
336
+ return true;
337
+ }
338
+ if (canLoadMore || (hasAsync && asyncPage > 1)) {
339
+ return false;
340
+ }
341
+ return sourceOptions.length > 50;
342
+ });
343
+
344
+ const placeholder = $derived(zPlaceholder || zTranslate('i18n_z_ui_select_placeholder'));
345
+ const searchPlaceholder = $derived(zPlaceholderSearch || zTranslate('i18n_z_ui_select_search'));
346
+ const notFoundText = $derived(zNotFoundText || zTranslate('i18n_z_ui_select_no_results'));
347
+ const emptyText = $derived(zEmptyText || zTranslate('i18n_z_ui_select_no_options'));
348
+
349
+ // ---------- validation ----------
350
+ const showValidation = $derived(dirty || touched);
351
+ const validationErrors = $derived.by(() => {
352
+ if (!showValidation) {
353
+ return [];
354
+ }
355
+ const errors: string[] = [];
356
+ if (zRequired && !hasValue) {
357
+ errors.push(zTranslate('i18n_z_ui_select_required'));
358
+ }
359
+ const current = (isMultiple ? selectedOptions : selectedOption) as ZSelectValidationValue<O>;
360
+ for (const validator of zValidators) {
361
+ if (!validator.validate(current)) {
362
+ errors.push(validator.message);
363
+ }
364
+ }
365
+ return errors;
366
+ });
367
+ const asyncErrorList = $derived(Object.values(asyncErrors));
368
+ const hasErrorState = $derived(
369
+ !!customError || (asyncErrorList.length > 0 && showValidation) || validationErrors.length > 0
370
+ );
371
+ const errorText = $derived(customError || asyncErrorList[0] || validationErrors[0] || '');
372
+
373
+ // First matching state wins: disabled beats readonly beats open beats error.
374
+ const status = $derived.by(() => {
375
+ if (isDisabled) {
376
+ return 'disabled';
377
+ }
378
+ if (zReadonly) {
379
+ return 'readonly';
380
+ }
381
+ if (open) {
382
+ return 'open';
383
+ }
384
+ return hasErrorState ? 'error' : 'default';
385
+ });
386
+
387
+ const triggerClasses = $derived(
388
+ zMergeClasses(
389
+ zSelectVariants({ zVariant, zSize, zStatus: status }),
390
+ zLoading && zLoadingOutline && 'z-loading-outline-active !ring-ring/50 !ring-[3px]',
391
+ !zWrap && isMultiple && { 'h-8': zSize === 'sm', 'h-9': zSize === 'default', 'h-10': zSize === 'lg' },
392
+ className
393
+ )
394
+ );
395
+
396
+ // ---------- value changes ----------
397
+ function commit(next: V | V[] | null): void {
398
+ value = next;
399
+ dirty = true;
400
+ onValueChange?.(next);
401
+ }
402
+
403
+ function selectOption(option: O): void {
404
+ if (option.disabled) {
405
+ return;
406
+ }
407
+
408
+ if (isMultiple) {
409
+ const exists = valueList.some(item => isEqual(item, option.value));
410
+ const next = exists ? valueList.filter(item => !isEqual(item, option.value)) : [...valueList, option.value];
411
+ commit(next);
412
+ triggerAsyncValidation(next.map(item => findOption(item)).filter((o): o is O => !!o));
413
+ return;
414
+ }
415
+
416
+ commit(option.value);
417
+ triggerAsyncValidation(option);
418
+ open = false;
419
+ }
420
+
421
+ function removeOption(event: MouseEvent, option: O): void {
422
+ event.stopPropagation();
423
+ commit(valueList.filter(item => !isEqual(item, option.value)));
424
+ }
425
+
426
+ function clearAll(event: MouseEvent): void {
427
+ event.stopPropagation();
428
+ commit(isMultiple ? [] : null);
429
+ }
430
+
431
+ function toggleSelectAll(): void {
432
+ if (!isMultiple) {
433
+ return;
434
+ }
435
+ commit(isAllSelected ? [] : translatedOptions.filter(option => !option.disabled).map(option => option.value));
436
+ }
437
+
438
+ // ---------- open / close ----------
439
+ let wasOpen = false;
440
+ $effect.pre(() => {
441
+ const isOpen = open;
442
+ untrack(() => {
443
+ if (isOpen === wasOpen) {
444
+ return;
445
+ }
446
+ wasOpen = isOpen;
447
+ if (isOpen) {
448
+ handleShow();
449
+ } else {
450
+ handleHide();
451
+ }
452
+ });
453
+ });
454
+
455
+ function handleShow(): void {
456
+ if (isInteractionDisabled) {
457
+ open = false;
458
+ return;
459
+ }
460
+ keyboardNav = false;
461
+ resetTagLayout();
462
+ resetTree();
463
+ query = '';
464
+ searchText = '';
465
+ onSearch?.('');
466
+ if (asyncConfig?.loadOnFocus && !(asyncKeyword === '' && asyncOptions.length > 0)) {
467
+ loadAsync('', false);
468
+ }
469
+ onFocus?.();
470
+ }
471
+
472
+ function handleHide(): void {
473
+ clearTimeout(searchTimer);
474
+ if (dirty) {
475
+ touched = true;
476
+ }
477
+ if (zAsyncValidateOn === 'blur') {
478
+ triggerAsyncValidation(isMultiple ? selectedOptions : selectedOption, true);
479
+ }
480
+ onBlur?.();
481
+ trigger?.blur();
482
+ }
483
+
484
+ function handleClosed(): void {
485
+ if (remote) {
486
+ query = '';
487
+ searchText = '';
488
+ }
489
+ }
490
+
491
+ function toggle(): void {
492
+ if (isInteractionDisabled) {
493
+ return;
494
+ }
495
+ open = !open;
496
+ }
497
+
498
+ function onTriggerKeydown(event: KeyboardEvent): void {
499
+ if (isInteractionDisabled) {
500
+ return;
501
+ }
502
+ if (open && (event.key !== ' ' || !zShowSearch)) {
503
+ // Search hidden: the trigger itself drives the list.
504
+ if (event.key === ' ') {
505
+ event.preventDefault();
506
+ } else {
507
+ return onListKeydown(event);
508
+ }
509
+ }
510
+ if (event.key === 'Enter' || event.key === ' ' || event.key === 'ArrowDown') {
511
+ event.preventDefault();
512
+ toggle();
513
+ }
514
+ }
515
+
516
+ /** Focus the search box once the panel is positioned, without scrolling the page. */
517
+ function focusSearch(): void {
518
+ if (!zShowSearch || window.matchMedia('(max-width: 767px)').matches) {
519
+ return;
520
+ }
521
+ searchInput?.focus({ preventScroll: true });
522
+ }
523
+
524
+ // ---------- search ----------
525
+ let searchTimer: ReturnType<typeof setTimeout> | undefined;
526
+
527
+ function onSearchInput(text: string): void {
528
+ query = text;
529
+ clearTimeout(searchTimer);
530
+ searchTimer = setTimeout(() => {
531
+ searchText = text;
532
+ onSearch?.(text);
533
+ if (hasAsync) {
534
+ loadAsync(text, false);
535
+ } else if (zSearchServer) {
536
+ pendingServerReset = true;
537
+ } else {
538
+ resetScrollTop();
539
+ }
540
+ }, debounceTime);
541
+ }
542
+
543
+ let pendingServerReset = false;
544
+ $effect(() => {
545
+ void zOptions;
546
+ untrack(() => {
547
+ if (!zSearchServer || !pendingServerReset) {
548
+ return;
549
+ }
550
+ pendingServerReset = false;
551
+ resetScrollTop();
552
+ });
553
+ });
554
+
555
+ // ---------- scrolling / virtual ----------
556
+ // TanStack Virtual, same engine as core-ui's @tanstack/angular-virtual.
557
+ const virtualizer = createVirtualizer<HTMLDivElement, HTMLDivElement>({
558
+ count: 0,
559
+ getScrollElement: () => optionsEl,
560
+ estimateSize: () => zOptionHeight,
561
+ gap: 3,
562
+ overscan: 5,
563
+ });
564
+
565
+ // Push the current list into the virtualizer; it re-attaches when the dropdown remounts the list.
566
+ $effect(() => {
567
+ const options = {
568
+ count: useVirtual ? filteredOptions.length : 0,
569
+ estimateSize: () => zOptionHeight,
570
+ getScrollElement: () => optionsEl,
571
+ getItemKey: (index: number) => {
572
+ const option = filteredOptions[index];
573
+ return option ? String(key(option)) : index;
574
+ },
575
+ };
576
+ void optionsEl;
577
+ untrack(() => $virtualizer.setOptions(options));
578
+ });
579
+
580
+ function resetScrollTop(): void {
581
+ requestAnimationFrame(() => {
582
+ if (!optionsEl) {
583
+ return;
584
+ }
585
+ if (useVirtual) {
586
+ $virtualizer.scrollToOffset(0);
587
+ }
588
+ optionsEl.scrollTop = 0;
589
+ });
590
+ }
591
+
592
+ function onOptionsScroll(event: Event & { currentTarget: HTMLDivElement }): void {
593
+ const el = event.currentTarget;
594
+ if (!useVirtual || !canLoadMore || isLoadingMore) {
595
+ return;
596
+ }
597
+ if (el.scrollHeight - el.scrollTop - el.clientHeight <= el.clientHeight * zScrollDistance) {
598
+ loadMore(el.scrollTop);
599
+ }
600
+ }
601
+
602
+ // Non-virtual lists load the next page when a sentinel nears the bottom.
603
+ $effect(() => {
604
+ const target = sentinel;
605
+ const root = optionsEl;
606
+ if (!target || !root || !open || !canLoadMore || useVirtual) {
607
+ return;
608
+ }
609
+ const observer = new IntersectionObserver(
610
+ entries => {
611
+ if (entries[0]?.isIntersecting && !isLoadingMore) {
612
+ loadMore(root.scrollTop);
613
+ }
614
+ },
615
+ { root, rootMargin: '100px', threshold: 0 }
616
+ );
617
+ observer.observe(target);
618
+ return () => observer.disconnect();
619
+ });
620
+
621
+ function loadMore(scrollTop: number): void {
622
+ if (hasAsync) {
623
+ if (canLoadMore) {
624
+ loadAsync(asyncKeyword, true);
625
+ }
626
+ return;
627
+ }
628
+ onLoadMore?.({ currentCount: filteredOptions.length, scrollTop });
629
+ }
630
+
631
+ // ---------- async options ----------
632
+ let requestId = 0;
633
+ let abort: AbortController | null = null;
634
+
635
+ function loadAsync(keyword: string, append: boolean): void {
636
+ const cfg = asyncConfig;
637
+ if (!cfg) {
638
+ return;
639
+ }
640
+
641
+ const normalized = keyword.trim();
642
+ const pageSize = cfg.pageSize ?? Z_ASYNC_OPTIONS_DEFAULT_PAGE_SIZE;
643
+ const canLoadEmpty = cfg.loadOnFocus && normalized.length === 0;
644
+
645
+ if (!append && normalized.length < config.minLength && !canLoadEmpty) {
646
+ resetAsync();
647
+ return;
648
+ }
649
+ if (append && (!asyncHasMore || asyncLoading || asyncLoadingMore)) {
650
+ return;
651
+ }
652
+
653
+ const page = append ? asyncPage + 1 : 1;
654
+ const cursor = append ? asyncCursor : null;
655
+ const id = ++requestId;
656
+ const scrollBefore = append ? (optionsEl?.scrollTop ?? null) : null;
657
+
658
+ if (!append) {
659
+ abort?.abort();
660
+ asyncKeyword = normalized;
661
+ asyncLoading = true;
662
+ asyncHasMore = false;
663
+ } else {
664
+ asyncLoadingMore = true;
665
+ }
666
+ abort = new AbortController();
667
+
668
+ Promise.resolve()
669
+ .then(() => cfg.load({ keyword: normalized, page, pageSize, cursor, signal: abort!.signal }))
670
+ .then(response => {
671
+ if (id !== requestId) {
672
+ return;
673
+ }
674
+ const items = response.items ?? [];
675
+ const previous = asyncOptions.length;
676
+ const merged = zMergeAsyncOptions(append ? asyncOptions : [], items, cfg.dedupeBy);
677
+
678
+ if (append && merged.length <= previous) {
679
+ asyncHasMore = false;
680
+ } else {
681
+ asyncOptions = merged;
682
+ asyncPage = page;
683
+ asyncCursor = response.nextCursor ?? null;
684
+ asyncHasMore = zResolveAsyncOptionsHasMore(response, pageSize, merged.length, cfg.paging);
685
+ }
686
+
687
+ if (scrollBefore !== null) {
688
+ requestAnimationFrame(() => optionsEl && (optionsEl.scrollTop = scrollBefore));
689
+ } else if (!append) {
690
+ resetScrollTop();
691
+ }
692
+ })
693
+ .catch(error => {
694
+ if (id !== requestId || (error as Error)?.name === 'AbortError') {
695
+ return;
696
+ }
697
+ console.error('ZSelect async options load failed:', error);
698
+ if (!append) {
699
+ asyncOptions = [];
700
+ asyncPage = 1;
701
+ asyncCursor = null;
702
+ }
703
+ asyncHasMore = false;
704
+ })
705
+ .finally(() => {
706
+ if (id !== requestId) {
707
+ return;
708
+ }
709
+ asyncLoading = false;
710
+ asyncLoadingMore = false;
711
+ });
712
+ }
713
+
714
+ function resetAsync(): void {
715
+ abort?.abort();
716
+ requestId++;
717
+ asyncOptions = [];
718
+ asyncKeyword = '';
719
+ asyncPage = 1;
720
+ asyncCursor = null;
721
+ asyncHasMore = false;
722
+ asyncLoading = false;
723
+ asyncLoadingMore = false;
724
+ }
725
+
726
+ // ---------- async validation ----------
727
+ let validationTimer: ReturnType<typeof setTimeout> | undefined;
728
+ let validationAbort: AbortController | null = null;
729
+
730
+ function triggerAsyncValidation(current: ZSelectValidationValue<O>, force = false): void {
731
+ if (!zAsyncValidators.length || (!force && zAsyncValidateOn !== 'change')) {
732
+ return;
733
+ }
734
+ clearTimeout(validationTimer);
735
+ validationTimer = setTimeout(() => void runAsyncValidation(current), zAsyncDebounce || 300);
736
+ }
737
+
738
+ async function runAsyncValidation(current: ZSelectValidationValue<O>): Promise<void> {
739
+ validationAbort?.abort();
740
+ if (current == null) {
741
+ asyncErrors = {};
742
+ validating = false;
743
+ return;
744
+ }
745
+
746
+ const controller = new AbortController();
747
+ validationAbort = controller;
748
+ validating = true;
749
+
750
+ const results = await Promise.all(
751
+ zAsyncValidators.map(async validator => {
752
+ try {
753
+ return { validator, ok: await validator.validate(current, controller.signal) };
754
+ } catch (error) {
755
+ if (!controller.signal.aborted) {
756
+ console.error(`Async validation error for ${validator.error}:`, error);
757
+ }
758
+ return { validator, ok: false };
759
+ }
760
+ })
761
+ );
762
+ if (controller.signal.aborted) {
763
+ return;
764
+ }
765
+
766
+ const errors: Record<string, string> = {};
767
+ for (const { validator, ok } of results) {
768
+ if (!ok) {
769
+ errors[validator.error] = validator.message;
770
+ }
771
+ }
772
+ asyncErrors = errors;
773
+ validating = false;
774
+ }
775
+
776
+ // ---------- tree ----------
777
+ let treeStack = $state.raw<ZSelectTreeLevel<O>[]>([]);
778
+ let treeIndex = $state(0);
779
+ let treeQuery = $state('');
780
+ // Which edges of the option lists have more to show: they fade while scrolled (see `fades`).
781
+ let listEdges = $state<ZScrollEdges>({ atTop: true, atEnd: true });
782
+ let treeEdges = $state<ZScrollEdges>({ atTop: true, atEnd: true });
783
+ let treeDirection = $state<'none' | 'forward' | 'back'>('none');
784
+
785
+ const treeLevel = $derived(treeStack[treeIndex] ?? { label: '', options: [] });
786
+ const treeCrumbs = $derived(
787
+ treeStack
788
+ .slice(0, treeIndex + 1)
789
+ .map((level, index) => (index === 0 ? zTreeRootLabel || zTranslate('i18n_z_ui_select_tree_root') : level.label))
790
+ );
791
+ /** Every option without children below `options`, in order: what a search in a tree looks through. */
792
+ function collectLeaves(options: O[]): O[] {
793
+ return options.flatMap(option => (option.children?.length ? collectLeaves(option.children as O[]) : [option]));
794
+ }
795
+ // A search looks through everything under the level being shown, not only its own rows.
796
+ const treeOptions = $derived.by(() => {
797
+ const searching = treeQuery.trim() !== '';
798
+ const options = searching ? collectLeaves(treeLevel.options) : treeLevel.options;
799
+ const shown = zTranslateLabels ? options.map(translate) : options;
800
+ return searching ? filterOptions(shown, treeQuery) : shown;
801
+ });
802
+
803
+ function findTreePath(options: O[], target: unknown): O[] | null {
804
+ for (const option of options) {
805
+ if (isEqual(option.value, target)) {
806
+ return [option];
807
+ }
808
+ if (option.children?.length) {
809
+ const path = findTreePath(option.children as O[], target);
810
+ if (path) {
811
+ return [option, ...path];
812
+ }
813
+ }
814
+ }
815
+ return null;
816
+ }
817
+
818
+ function resetTree(): void {
819
+ if (!zTree) {
820
+ return;
821
+ }
822
+ const stack: ZSelectTreeLevel<O>[] = [{ label: '', options: zOptions }];
823
+ if (!isMultiple && value != null) {
824
+ for (const ancestor of findTreePath(zOptions, value)?.slice(0, -1) ?? []) {
825
+ stack.push({ label: translate(ancestor).label, options: (ancestor.children ?? []) as O[] });
826
+ }
827
+ }
828
+ treeStack = stack;
829
+ treeIndex = stack.length - 1;
830
+ treeQuery = '';
831
+ treeDirection = 'none';
832
+ }
833
+
834
+ function onTreeOptionClick(option: O): void {
835
+ if (option.disabled) {
836
+ return;
837
+ }
838
+ if (!option.children?.length) {
839
+ selectOption(option);
840
+ return;
841
+ }
842
+ const kept = treeStack.slice(0, treeIndex + 1);
843
+ treeStack = [...kept, { label: option.label, options: option.children as O[] }];
844
+ treeDirection = 'forward';
845
+ treeIndex = kept.length;
846
+ treeQuery = '';
847
+ }
848
+
849
+ function treeNavigateTo(index: number): void {
850
+ if (index === treeIndex) {
851
+ return;
852
+ }
853
+ treeDirection = 'back';
854
+ treeIndex = index;
855
+ treeQuery = '';
856
+ }
857
+
858
+ // ---------- keyboard (combobox pattern: focus stays on the input, options via activedescendant) ----------
859
+ let activeIndex = $state(-1);
860
+ /** The keyboard highlight only shows once arrows are used; the pointer has its own glide. */
861
+ let keyboardNav = $state(false);
862
+ const navOptions = $derived(zTree ? treeOptions : filteredOptions);
863
+ const optionId = (index: number): string => `${dropdownId}-opt-${index}`;
864
+
865
+ // Start from the selected option (or the first) whenever the visible list changes.
866
+ $effect(() => {
867
+ const list = navOptions;
868
+ if (!open) {
869
+ return;
870
+ }
871
+ untrack(() => {
872
+ const current = list.findIndex(option => isSelected(option) && !option.disabled);
873
+ activeIndex = current !== -1 ? current : list.findIndex(option => !option.disabled);
874
+ });
875
+ });
876
+
877
+ function moveActive(step: 1 | -1 | 'first' | 'last'): void {
878
+ const list = navOptions;
879
+ if (!list.length) {
880
+ return;
881
+ }
882
+ // Home/End start just outside the list and walk inwards, so disabled edge options are skipped too.
883
+ let index: number;
884
+ let delta: number;
885
+ switch (step) {
886
+ case 'first':
887
+ index = -1;
888
+ delta = 1;
889
+ break;
890
+ case 'last':
891
+ index = list.length;
892
+ delta = -1;
893
+ break;
894
+ default:
895
+ index = activeIndex;
896
+ delta = step;
897
+ }
898
+ for (let tries = 0; tries < list.length; tries++) {
899
+ index = (index + delta + list.length) % list.length;
900
+ if (!list[index]?.disabled) {
901
+ break;
902
+ }
903
+ }
904
+ activeIndex = index;
905
+ keyboardNav = true;
906
+ revealActive();
907
+ }
908
+
909
+ function revealActive(): void {
910
+ requestAnimationFrame(() => {
911
+ const container = optionsEl ?? document.getElementById(`${dropdownId}-list`);
912
+ if (!container || activeIndex < 0) {
913
+ return;
914
+ }
915
+ if (useVirtual && !zTree) {
916
+ $virtualizer.scrollToIndex(activeIndex, { align: 'auto' });
917
+ return;
918
+ }
919
+ document.getElementById(optionId(activeIndex))?.scrollIntoView({ block: 'nearest' });
920
+ });
921
+ }
922
+
923
+ function onListKeydown(event: KeyboardEvent): void {
924
+ if (event.isComposing) {
925
+ return;
926
+ }
927
+ const list = navOptions;
928
+ switch (event.key) {
929
+ case 'ArrowDown':
930
+ event.preventDefault();
931
+ moveActive(1);
932
+ break;
933
+ case 'ArrowUp':
934
+ event.preventDefault();
935
+ moveActive(-1);
936
+ break;
937
+ case 'Home':
938
+ case 'End':
939
+ if (event.currentTarget instanceof HTMLInputElement) {
940
+ return;
941
+ }
942
+ event.preventDefault();
943
+ moveActive(event.key === 'Home' ? 'first' : 'last');
944
+ break;
945
+ case 'Enter': {
946
+ const option = list[activeIndex];
947
+ if (!option) {
948
+ return;
949
+ }
950
+ event.preventDefault();
951
+ if (zTree) {
952
+ onTreeOptionClick(option);
953
+ } else {
954
+ selectOption(option);
955
+ }
956
+ break;
957
+ }
958
+ case 'Backspace':
959
+ if (zTree && !treeQuery && treeIndex > 0) {
960
+ event.preventDefault();
961
+ treeNavigateTo(treeIndex - 1);
962
+ }
963
+ break;
964
+ case 'Tab':
965
+ open = false;
966
+ break;
967
+ }
968
+ }
969
+
970
+ // ---------- tag layout (nowrap) ----------
971
+ let visibleTagCount = $state<number | null>(null);
972
+ let truncatedIndex = $state<number | null>(null);
973
+ let truncatedMaxWidth = $state<number | null>(null);
974
+ let layoutVersion = $state(0);
975
+
976
+ const tagWidthStyle = $derived.by(() => {
977
+ if (zTagWidth === null || zTagWidth === '') {
978
+ return null;
979
+ }
980
+ return typeof zTagWidth === 'number' ? `${zTagWidth}px` : zTagWidth;
981
+ });
982
+ const displayedTags = $derived.by(() => {
983
+ if (zMaxTagCount === null) {
984
+ return selectedOptions;
985
+ }
986
+ const max = Math.max(0, zMaxTagCount);
987
+ return selectedOptions.slice(0, Math.min(max, zWrap ? max : (visibleTagCount ?? max)));
988
+ });
989
+ const remainingCount = $derived(Math.max(0, selectedOptions.length - displayedTags.length));
990
+ const contentClasses = $derived(
991
+ zMergeClasses(
992
+ 'z-select-selected-content min-w-0 max-w-full overflow-hidden text-ellipsis whitespace-nowrap',
993
+ tagWidthStyle && 'flex-1'
994
+ )
995
+ );
996
+
997
+ function resetTagLayout(): void {
998
+ truncatedIndex = null;
999
+ truncatedMaxWidth = null;
1000
+ layoutVersion++;
1001
+ }
1002
+
1003
+ // Inputs that change tag geometry invalidate the current truncation.
1004
+ $effect(() => {
1005
+ void [selectedOptions, tagWidthStyle, zWrap, zMaxTagCount, selection];
1006
+ untrack(() => {
1007
+ if (truncatedIndex !== null) {
1008
+ resetTagLayout();
1009
+ }
1010
+ });
1011
+ });
1012
+
1013
+ $effect(() => {
1014
+ const wrapper = tagsWrapper;
1015
+ const triggerEl = trigger;
1016
+ if (!wrapper || !triggerEl || !isMultiple || zWrap) {
1017
+ return;
1018
+ }
1019
+ void selectedOptions.length;
1020
+
1021
+ const observer = new ResizeObserver(entries => {
1022
+ const outerResized = entries.some(entry => entry.target === wrapper || entry.target === triggerEl);
1023
+ if (!outerResized && truncatedIndex !== null) {
1024
+ return;
1025
+ }
1026
+ resetTagLayout();
1027
+ });
1028
+ observer.observe(wrapper);
1029
+ observer.observe(triggerEl);
1030
+ for (const tag of tagEls.slice(0, selectedOptions.length)) {
1031
+ if (tag) {
1032
+ observer.observe(tag);
1033
+ }
1034
+ }
1035
+ return () => observer.disconnect();
1036
+ });
1037
+
1038
+ // Measures after the DOM is updated (effects run post-render, pre-paint).
1039
+ $effect(() => {
1040
+ void layoutVersion;
1041
+ const wrapper = tagsWrapper;
1042
+ const triggerEl = trigger;
1043
+ const arrowEl = arrow;
1044
+ const count = selectedOptions.length;
1045
+ void [tagWidthStyle, selection];
1046
+
1047
+ untrack(() => {
1048
+ if (!wrapper || !triggerEl || !arrowEl || !isMultiple || zWrap) {
1049
+ visibleTagCount = null;
1050
+ truncatedIndex = null;
1051
+ truncatedMaxWidth = null;
1052
+ return;
1053
+ }
1054
+ if (count === 0) {
1055
+ visibleTagCount = 0;
1056
+ truncatedIndex = null;
1057
+ truncatedMaxWidth = null;
1058
+ return;
1059
+ }
1060
+
1061
+ if (zMaxTagCount === null) {
1062
+ if (truncatedIndex !== null) {
1063
+ return;
1064
+ }
1065
+ const tagRects = tagEls.slice(0, count).map(el => {
1066
+ const rect = el.getBoundingClientRect();
1067
+ // Strip the enter animation's scale so a tag mid-animation measures at its final size.
1068
+ const dx = (rect.width - el.offsetWidth) / 2;
1069
+ const dy = (rect.height - el.offsetHeight) / 2;
1070
+ return { left: rect.left + dx, right: rect.right - dx, top: rect.top + dy, bottom: rect.bottom - dy };
1071
+ });
1072
+ const wrapperRect = wrapper.getBoundingClientRect();
1073
+ const triggerRect = triggerEl.getBoundingClientRect();
1074
+ const arrowRect = arrowEl.getBoundingClientRect();
1075
+ const index = zGetSelectTagTruncationIndex(tagRects, wrapperRect, triggerRect, arrowRect);
1076
+ const clippingRight = Math.min(wrapperRect.right, triggerRect.right, arrowRect.left);
1077
+ const tolerance = Math.max(1, Math.max(0, arrowRect.left - wrapperRect.right));
1078
+ truncatedIndex = index;
1079
+ truncatedMaxWidth = index === null ? null : Math.max(0, clippingRight - tolerance - tagRects[index].left);
1080
+ return;
1081
+ }
1082
+
1083
+ truncatedIndex = null;
1084
+ truncatedMaxWidth = null;
1085
+ const gap = Number.parseFloat(getComputedStyle(wrapper).columnGap) || 0;
1086
+ visibleTagCount = zGetSelectTagVisibleCount(
1087
+ tagEls.slice(0, count).map(el => el.offsetWidth),
1088
+ wrapper.getBoundingClientRect().width,
1089
+ zMaxTagCount,
1090
+ remainingMeasure?.offsetWidth ?? 0,
1091
+ gap
1092
+ );
1093
+ });
1094
+ });
1095
+
1096
+ $effect(() => () => {
1097
+ clearTimeout(searchTimer);
1098
+ clearTimeout(validationTimer);
1099
+ abort?.abort();
1100
+ validationAbort?.abort();
1101
+ });
1102
+
1103
+ // ---------- public API (bind:this) ----------
1104
+ /** Marks the field touched and returns true when it is valid. */
1105
+ export function valid(): boolean {
1106
+ touched = true;
1107
+ dirty = true;
1108
+ return !hasErrorState;
1109
+ }
1110
+
1111
+ /** @deprecated Use `valid()`. Returns true when there is an error. */
1112
+ export function validate(): boolean {
1113
+ return !valid();
1114
+ }
1115
+
1116
+ export function reset(): void {
1117
+ customError = null;
1118
+ asyncErrors = {};
1119
+ value = isMultiple ? [] : null;
1120
+ onValueChange?.(value);
1121
+ touched = false;
1122
+ dirty = false;
1123
+ query = '';
1124
+ searchText = '';
1125
+ }
1126
+
1127
+ export function focus(): void {
1128
+ trigger?.focus({ preventScroll: true });
1129
+ }
1130
+
1131
+ export function blur(): void {
1132
+ trigger?.blur();
1133
+ }
1134
+
1135
+ /** Shows a custom (e.g. server-side) error; `null` clears it. */
1136
+ export function setErrorMessage(message: string | null): void {
1137
+ customError = message;
1138
+ if (message) {
1139
+ touched = dirty = true;
1140
+ }
1141
+ }
1142
+
1143
+ export function hasError(): boolean {
1144
+ return hasErrorState;
1145
+ }
1146
+
1147
+ export function errorMessage(): string {
1148
+ return errorText;
1149
+ }
1150
+
1151
+ export function isValidating(): boolean {
1152
+ return validating;
1153
+ }
1154
+
1155
+ export function getSelected(): O[] {
1156
+ return selected;
1157
+ }
1158
+
1159
+ const optionClass = (option: O, custom: boolean): string =>
1160
+ zSelectOptionVariants({ customTemplate: custom, selected: isSelected(option), disabled: !!option.disabled });
1161
+
1162
+ const tagClass = (option: O): string => {
1163
+ const base = zSelectTagVariants({ zSize });
1164
+ if (!isTags) {
1165
+ return zMergeClasses(base, 'bg-muted text-foreground border-border');
1166
+ }
1167
+ const color = getTagColor(option.value);
1168
+ return zMergeClasses(base, color.bg, color.text, color.border);
1169
+ };
1170
+
1171
+ const key = (option: O): unknown => zGetSelectValueKey(option.value, zKey);
1172
+
1173
+ // Truncated labels get a tooltip (core-ui parity): plain hints in the list, arrowed ones on the
1174
+ // trigger — which stay quiet while the dropdown is open and already shows the full label.
1175
+ const optionTip = (label: string): ZTooltipOptions => ({
1176
+ content: label,
1177
+ autoDetect: true,
1178
+ showDelay: 300,
1179
+ arrow: false,
1180
+ offset: 5,
1181
+ });
1182
+ const labelTip = (label: string, offset: number): ZTooltipOptions => ({
1183
+ content: label,
1184
+ autoDetect: true,
1185
+ showDelay: 300,
1186
+ offset,
1187
+ disabled: open,
1188
+ });
1189
+ </script>
1190
+
1191
+ {#snippet highlighted(label: string, text: string)}
1192
+ {#each zHighlightParts(label, text) as part, index (index)}
1193
+ {#if part.match}<span class="text-primary">{part.text}</span>{:else}{part.text}{/if}
1194
+ {/each}
1195
+ {/snippet}
1196
+
1197
+ {#snippet empty(icon: ZIconName, message: string)}
1198
+ <div class="col-span-full flex flex-col items-center justify-center px-2 py-8">
1199
+ <ZIcon zType={icon} zSize="40" class="text-muted-foreground/50 mb-2 text-center" />
1200
+ <p class="text-muted-foreground text-center text-xs font-medium">{message}</p>
1201
+ </div>
1202
+ {/snippet}
1203
+
1204
+ {#snippet check()}
1205
+ <ZIcon
1206
+ zType="lucideCheck"
1207
+ zSize="16"
1208
+ zStrokeWidth={4}
1209
+ class={zMergeClasses('text-primary mt-0 shrink-0', zClassSelect)}
1210
+ />
1211
+ {/snippet}
1212
+
1213
+ {#snippet optionBody(option: O, highlightText: string)}
1214
+ {@const chosen = isSelected(option)}
1215
+ {#if optionSnippet}
1216
+ <div class="flex min-w-0 items-start gap-2">
1217
+ <div class="min-w-0 flex-1">{@render optionSnippet(option, chosen)}</div>
1218
+ {#if zShowCheck && chosen}{@render check()}{/if}
1219
+ </div>
1220
+ {:else}
1221
+ {#if option.icon}
1222
+ <ZIcon zType={option.icon} zSize="16" class="text-muted-foreground shrink-0" />
1223
+ {/if}
1224
+ <span class="min-w-0 flex-1 truncate" {@attach zTooltip(optionTip(option.label))}>
1225
+ {@render highlighted(option.label, highlightText)}
1226
+ </span>
1227
+ {#if zShowCheck && chosen}{@render check()}{/if}
1228
+ {/if}
1229
+ {/snippet}
1230
+
1231
+ {#snippet groupHeading(label: string)}
1232
+ <!-- A divider with the group's name, above its first option (`option.group`). A virtual list does not draw groups. -->
1233
+ <div
1234
+ role="presentation"
1235
+ class="text-muted-foreground z-select-group mt-1 flex shrink-0 items-center gap-2 px-2 pt-1 pb-0.5 text-[10px] font-medium tracking-wide uppercase first:mt-0"
1236
+ >
1237
+ <span class="truncate">{label}</span>
1238
+ <span class="bg-border h-px flex-1"></span>
1239
+ </div>
1240
+ {/snippet}
1241
+
1242
+ {#snippet fades(edges: ZScrollEdges)}
1243
+ <!-- Soft edges while a list is scrolled: the top once it left the start, the bottom while there is more below. -->
1244
+ {#if !edges.atTop}
1245
+ <div
1246
+ class="from-popover pointer-events-none absolute inset-x-0 top-0 h-6 bg-gradient-to-b to-transparent"
1247
+ aria-hidden="true"
1248
+ ></div>
1249
+ {/if}
1250
+ {#if !edges.atTop && !edges.atEnd}
1251
+ <div
1252
+ class="from-popover pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t to-transparent"
1253
+ aria-hidden="true"
1254
+ ></div>
1255
+ {/if}
1256
+ {/snippet}
1257
+
1258
+ {#snippet loadingMore()}
1259
+ <div
1260
+ class="z-select-loading-more from-popover via-popover/95 sticky bottom-0 -mx-1 -mb-1 flex items-center justify-center bg-gradient-to-t to-transparent pt-6 pb-2"
1261
+ >
1262
+ <ZIcon zType="lucideLoaderCircle" zSize="16" class="text-primary animate-spin" />
1263
+ </div>
1264
+ {/snippet}
1265
+
1266
+ {#snippet searchBox(text: string, onInput: (text: string) => void)}
1267
+ <div class="border-border flex items-center border-b px-3">
1268
+ <ZIcon zType="lucideSearch" zSize="18" class="text-muted-foreground/50 mr-2 shrink-0" />
1269
+ <input
1270
+ bind:this={searchInput}
1271
+ type="text"
1272
+ class="placeholder:text-muted-foreground text-foreground flex h-10 w-full min-w-0 overflow-hidden bg-transparent py-3 text-sm text-ellipsis whitespace-nowrap outline-none"
1273
+ placeholder={searchPlaceholder}
1274
+ value={text}
1275
+ oninput={event => onInput(event.currentTarget.value)}
1276
+ onkeydown={onListKeydown}
1277
+ role="combobox"
1278
+ aria-expanded="true"
1279
+ aria-autocomplete="list"
1280
+ aria-activedescendant={activeIndex >= 0 ? optionId(activeIndex) : undefined}
1281
+ autocomplete="off"
1282
+ autocorrect="off"
1283
+ spellcheck="false"
1284
+ aria-controls={`${dropdownId}-list`}
1285
+ />
1286
+ </div>
1287
+ {/snippet}
1288
+
1289
+ <div class="z-select-wrapper relative flex w-full flex-col gap-2">
1290
+ {#if zLabel}
1291
+ <label for={selectId} class={zMergeClasses('text-xs leading-none font-medium', zLabelClass)}>
1292
+ {zTranslate(zLabel)}
1293
+ {#if zRequired}<span class="text-destructive! ml-0.5">*</span>{/if}
1294
+ </label>
1295
+ {/if}
1296
+
1297
+ <div class="relative">
1298
+ <div
1299
+ bind:this={trigger}
1300
+ id={selectId}
1301
+ class={['z-select-trigger cursor-pointer', triggerClasses, open && 'z-select-open']}
1302
+ tabindex={isDisabled ? -1 : 0}
1303
+ role="combobox"
1304
+ aria-expanded={open}
1305
+ aria-haspopup="listbox"
1306
+ aria-controls={dropdownId}
1307
+ aria-activedescendant={open && !zShowSearch && activeIndex >= 0 ? optionId(activeIndex) : undefined}
1308
+ aria-disabled={isInteractionDisabled || undefined}
1309
+ aria-invalid={hasErrorState || undefined}
1310
+ aria-describedby={hasErrorState && errorText ? errorId : undefined}
1311
+ aria-required={zRequired || undefined}
1312
+ onclick={toggle}
1313
+ onkeydown={onTriggerKeydown}
1314
+ >
1315
+ {#if zPrefix}
1316
+ <ZIcon zType={zPrefix} zSize="18" class="text-muted-foreground shrink-0" />
1317
+ {/if}
1318
+
1319
+ <div
1320
+ bind:this={tagsWrapper}
1321
+ class={[
1322
+ 'z-select-tags-wrapper flex min-w-0 flex-1 items-center gap-1',
1323
+ zMaxTagCount !== null && 'relative',
1324
+ zWrap ? 'flex-wrap' : 'overflow-hidden',
1325
+ ]}
1326
+ >
1327
+ {#if isMultiple}
1328
+ {#if selectedOptions.length === 0}
1329
+ <span class="text-muted-foreground min-w-0 flex-1 truncate whitespace-nowrap">{placeholder}</span>
1330
+ {:else}
1331
+ {#each selectedOptions as option, index (key(option))}
1332
+ {@const truncated = !zWrap && index === truncatedIndex}
1333
+ <span
1334
+ {@attach zRefAt(tagEls, index)}
1335
+ class={[
1336
+ 'z-select-tag',
1337
+ tagClass(option),
1338
+ (zWrap || truncated) && 'min-w-0',
1339
+ !zWrap && !truncated && 'z-select-tag-nowrap shrink-0',
1340
+ truncated && 'z-select-tag-truncatable',
1341
+ !zWrap && truncatedIndex !== null && index > truncatedIndex && 'z-select-tag-after-truncation',
1342
+ index >= displayedTags.length && 'z-select-tag-hidden',
1343
+ ]}
1344
+ style:width={tagWidthStyle}
1345
+ style:max-width={truncated && truncatedMaxWidth !== null ? `${truncatedMaxWidth}px` : null}
1346
+ >
1347
+ {#if selection}
1348
+ <div class={contentClasses}>{@render selection(option)}</div>
1349
+ {:else}
1350
+ <span class={contentClasses} {@attach zTooltip(labelTip(option.label, 6))}>{option.label}</span>
1351
+ {/if}
1352
+ {#if zAllowClear && !isDisabled}
1353
+ <button
1354
+ type="button"
1355
+ tabindex="-1"
1356
+ aria-label={`Remove ${option.label}`}
1357
+ class="-mr-0.5 flex size-3.5 shrink-0 items-center justify-center rounded-sm transition-colors hover:bg-black/10"
1358
+ onclick={event => removeOption(event, option)}
1359
+ >
1360
+ <ZIcon zType="lucideX" zSize="10" />
1361
+ </button>
1362
+ {/if}
1363
+ </span>
1364
+ {/each}
1365
+ {#if remainingCount > 0}
1366
+ <span
1367
+ class="z-select-remaining text-muted-foreground bg-muted rounded-sm px-1.5 py-0.5 text-xs font-medium"
1368
+ >
1369
+ +{remainingCount}
1370
+ </span>
1371
+ {/if}
1372
+ {#if zMaxTagCount !== null}
1373
+ <span
1374
+ bind:this={remainingMeasure}
1375
+ class="z-select-remaining-measure z-select-remaining text-muted-foreground bg-muted rounded-sm px-1.5 py-0.5 text-xs font-medium"
1376
+ aria-hidden="true"
1377
+ >
1378
+ +{selectedOptions.length}
1379
+ </span>
1380
+ {/if}
1381
+ {/if}
1382
+ {:else if selectedOption}
1383
+ {#if selection}
1384
+ {@render selection(selectedOption)}
1385
+ {:else}
1386
+ {#if selectedOption.icon}
1387
+ <ZIcon zType={selectedOption.icon} zSize="16" class="text-muted-foreground shrink-0" />
1388
+ {/if}
1389
+ <span class="truncate" {@attach zTooltip(labelTip(selectedOption.label, 10))}>{selectedOption.label}</span>
1390
+ {/if}
1391
+ {:else}
1392
+ <span class="text-muted-foreground min-w-0 flex-1 truncate whitespace-nowrap">{placeholder}</span>
1393
+ {/if}
1394
+ </div>
1395
+
1396
+ {#if isLoading || isLoadingMore}
1397
+ <ZIcon zType="lucideLoaderCircle" zSize="18" class="text-muted-foreground shrink-0 animate-spin" />
1398
+ {/if}
1399
+
1400
+ {#if !isLoading && zAllowClear && hasValue && !isDisabled && !zReadonly}
1401
+ <button
1402
+ type="button"
1403
+ tabindex="-1"
1404
+ aria-label={zTranslate('i18n_z_ui_select_clear_all')}
1405
+ class="text-muted-foreground hover:text-foreground flex shrink-0 items-center justify-center transition-colors"
1406
+ onclick={clearAll}
1407
+ >
1408
+ <ZIcon zType="lucideX" zSize="18" />
1409
+ </button>
1410
+ {/if}
1411
+
1412
+ {#if validating}
1413
+ <ZIcon zType="lucideLoaderCircle" zSize="18" class="text-muted-foreground shrink-0 animate-spin" />
1414
+ {/if}
1415
+
1416
+ <span
1417
+ bind:this={arrow}
1418
+ class={[
1419
+ 'text-muted-foreground flex shrink-0 items-center justify-center transition-transform duration-200',
1420
+ open && 'rotate-180',
1421
+ ]}
1422
+ >
1423
+ <ZIcon zType="lucideChevronDown" zSize="18" />
1424
+ </span>
1425
+ </div>
1426
+
1427
+ {#if hasErrorState && errorText}
1428
+ <p
1429
+ id={errorId}
1430
+ class="text-destructive animate-in fade-in slide-in-from-top-1 m-0 pt-2 text-xs duration-200"
1431
+ role="alert"
1432
+ >
1433
+ {errorText}
1434
+ </p>
1435
+ {/if}
1436
+ </div>
1437
+
1438
+ {#if name}
1439
+ {#each chosenValues as item, index (index)}
1440
+ <input type="hidden" {name} value={String(zGetSelectValueKey(item, zKey))} />
1441
+ {/each}
1442
+ {/if}
1443
+ </div>
1444
+
1445
+ <ZPopover
1446
+ anchor={trigger}
1447
+ bind:open
1448
+ zTrigger="manual"
1449
+ {zPosition}
1450
+ zOffset={6}
1451
+ zWidth={zDropdownWidth}
1452
+ {zScrollClose}
1453
+ id={dropdownId}
1454
+ class="z-select-dropdown"
1455
+ onOpen={focusSearch}
1456
+ onClosed={handleClosed}
1457
+ >
1458
+ {#if zTree}
1459
+ {#if zShowSearch}{@render searchBox(treeQuery, text => (treeQuery = text))}{/if}
1460
+
1461
+ {#if treeIndex > 0}
1462
+ <div class="z-select-tree-crumbs border-border flex items-center gap-1 border-b px-2 py-1.5">
1463
+ <button
1464
+ type="button"
1465
+ aria-label={zTranslate('i18n_z_ui_select_back')}
1466
+ class="text-muted-foreground hover:text-foreground hover:bg-accent flex size-6 shrink-0 items-center justify-center rounded-sm transition-colors"
1467
+ onclick={() => treeNavigateTo(Math.max(0, treeIndex - 1))}
1468
+ >
1469
+ <ZIcon zType="lucideChevronLeft" zSize="14" />
1470
+ </button>
1471
+ <nav class="flex min-w-0 flex-1 items-center gap-1 overflow-hidden text-xs" aria-label="Breadcrumb">
1472
+ {#each treeCrumbs as crumb, index (index)}
1473
+ {#if index > 0}<span class="text-muted-foreground/60 shrink-0">/</span>{/if}
1474
+ {#if index === treeCrumbs.length - 1}
1475
+ <span class="text-foreground truncate font-medium" aria-current="location">{crumb}</span>
1476
+ {:else}
1477
+ <button
1478
+ type="button"
1479
+ class="text-muted-foreground hover:text-foreground shrink-0 truncate transition-colors"
1480
+ onclick={() => treeNavigateTo(index)}
1481
+ >
1482
+ {crumb}
1483
+ </button>
1484
+ {/if}
1485
+ {/each}
1486
+ </nav>
1487
+ </div>
1488
+ {/if}
1489
+
1490
+ <div class="z-select-tree-viewport relative overflow-hidden" style:height={`${optionsMaxHeight}px`}>
1491
+ {#key treeIndex}
1492
+ <div
1493
+ {@attach zHoverGlide()}
1494
+ {@attach zScrollEdges(edges => (treeEdges = edges))}
1495
+ id={`${dropdownId}-list`}
1496
+ role="listbox"
1497
+ class={[
1498
+ 'absolute inset-0 flex flex-col gap-0.75 overflow-x-hidden overflow-y-auto overscroll-y-contain p-1',
1499
+ treeDirection === 'forward' && 'z-select-tree-slide-left',
1500
+ treeDirection === 'back' && 'z-select-tree-slide-right',
1501
+ ]}
1502
+ >
1503
+ {#each treeOptions as option, index (key(option))}
1504
+ {#if option.group && option.group !== treeOptions[index - 1]?.group}{@render groupHeading(
1505
+ option.group
1506
+ )}{/if}
1507
+ <!-- svelte-ignore a11y_click_events_have_key_events (keyboard is handled by the combobox input) -->
1508
+ <div
1509
+ id={optionId(index)}
1510
+ data-glide-item
1511
+ data-active={keyboardNav && index === activeIndex}
1512
+ role="option"
1513
+ tabindex="-1"
1514
+ aria-selected={isSelected(option)}
1515
+ aria-disabled={option.disabled || undefined}
1516
+ class={['z-select-option relative flex min-w-0 items-center gap-2', optionClass(option, !!optionSnippet)]}
1517
+ style:min-height={optionSnippet ? null : `${zOptionHeight}px`}
1518
+ onclick={() => onTreeOptionClick(option)}
1519
+ >
1520
+ <!-- The same template as a flat list, for a branch and for a leaf: the snippet tells them apart by `option.children`. -->
1521
+ <div class="flex min-w-0 flex-1 items-center gap-2">{@render optionBody(option, treeQuery)}</div>
1522
+ {#if option.children?.length}
1523
+ <ZIcon zType="lucideChevronRight" zSize="16" class="text-muted-foreground shrink-0" />
1524
+ {/if}
1525
+ </div>
1526
+ {:else}
1527
+ <div class="flex size-full items-center justify-center">{@render empty('lucideSearchX', notFoundText)}</div>
1528
+ {/each}
1529
+ </div>
1530
+ {/key}
1531
+ {@render fades(treeEdges)}
1532
+ </div>
1533
+ {:else}
1534
+ {#if zShowSearch}{@render searchBox(query, onSearchInput)}{/if}
1535
+
1536
+ {#if isLoading}
1537
+ <div class="flex items-center justify-center" style:height={`${optionsMaxHeight}px`}>
1538
+ <ZIcon zType="lucideLoaderCircle" zSize="24" class="text-primary animate-spin" />
1539
+ </div>
1540
+ {:else if filteredOptions.length > 0}
1541
+ <div class="relative">
1542
+ <div
1543
+ bind:this={optionsEl}
1544
+ {@attach zHoverGlide()}
1545
+ {@attach zScrollEdges(edges => (listEdges = edges))}
1546
+ id={`${dropdownId}-list`}
1547
+ role="listbox"
1548
+ aria-multiselectable={isMultiple || undefined}
1549
+ class={[
1550
+ 'z-select-options overflow-x-hidden overflow-y-auto overscroll-y-contain p-1',
1551
+ useVirtual ? 'z-select-virtual-scroll' : 'flex flex-col gap-0.75',
1552
+ ]}
1553
+ style:height={useVirtual || hasPaginated ? `${optionsMaxHeight}px` : null}
1554
+ style:max-height={`${optionsMaxHeight}px`}
1555
+ onscroll={onOptionsScroll}
1556
+ >
1557
+ {#if useVirtual}
1558
+ <div class="z-select-virtual-inner relative" style:height={`${$virtualizer.getTotalSize()}px`}>
1559
+ {#each $virtualizer.getVirtualItems() as item (item.key)}
1560
+ {@const option = filteredOptions[item.index]}
1561
+ {#if option}
1562
+ <!-- svelte-ignore a11y_click_events_have_key_events (keyboard is handled by the combobox input) -->
1563
+ <div
1564
+ id={optionId(item.index)}
1565
+ data-glide-item
1566
+ data-active={keyboardNav && item.index === activeIndex}
1567
+ data-index={item.index}
1568
+ role="option"
1569
+ tabindex="-1"
1570
+ aria-selected={isSelected(option)}
1571
+ aria-disabled={option.disabled || undefined}
1572
+ class={['z-select-option absolute right-0 left-0 min-w-0', optionClass(option, !!optionSnippet)]}
1573
+ style:height={zDynamicSize ? null : `${zOptionHeight}px`}
1574
+ style:min-height={zDynamicSize ? `${zOptionHeight}px` : null}
1575
+ style:transform={`translateY(${item.start}px)`}
1576
+ onclick={() => selectOption(option)}
1577
+ {@attach zDynamicSize ? (node: HTMLDivElement) => $virtualizer.measureElement(node) : null}
1578
+ >
1579
+ {@render optionBody(option, searchText)}
1580
+ </div>
1581
+ {/if}
1582
+ {/each}
1583
+ </div>
1584
+ {:else}
1585
+ {#each filteredOptions as option, index (key(option))}
1586
+ {#if option.group && option.group !== filteredOptions[index - 1]?.group}{@render groupHeading(
1587
+ option.group
1588
+ )}{/if}
1589
+ <!-- svelte-ignore a11y_click_events_have_key_events (keyboard is handled by the combobox input) -->
1590
+ <div
1591
+ id={optionId(index)}
1592
+ data-glide-item
1593
+ data-active={keyboardNav && index === activeIndex}
1594
+ role="option"
1595
+ tabindex="-1"
1596
+ aria-selected={isSelected(option)}
1597
+ aria-disabled={option.disabled || undefined}
1598
+ class={['z-select-option relative min-w-0', optionClass(option, !!optionSnippet)]}
1599
+ style:min-height={optionSnippet ? null : `${zOptionHeight}px`}
1600
+ onclick={() => selectOption(option)}
1601
+ >
1602
+ {@render optionBody(option, searchText)}
1603
+ </div>
1604
+ {/each}
1605
+ {#if canLoadMore}<div bind:this={sentinel} class="h-px w-full shrink-0"></div>{/if}
1606
+ {/if}
1607
+ {#if isLoadingMore}{@render loadingMore()}{/if}
1608
+ </div>
1609
+ {@render fades(listEdges)}
1610
+ </div>
1611
+ {:else}
1612
+ <div class="flex items-center justify-center p-1" style:height={`${optionsMaxHeight}px`}>
1613
+ {#if isEmptyData}
1614
+ {@render empty(zEmptyIcon, emptyText)}
1615
+ {:else}
1616
+ {@render empty('lucideSearchX', notFoundText)}
1617
+ {/if}
1618
+ </div>
1619
+ {/if}
1620
+
1621
+ {#if hasActionBar}
1622
+ <div class="border-border flex items-center gap-2 border-t px-2 py-1.5">
1623
+ {#if actions}
1624
+ {@render actions()}
1625
+ {:else}
1626
+ <ZButton
1627
+ zSize="xs"
1628
+ zType={isAllSelected ? 'ghost-error' : 'ghost-info'}
1629
+ class="min-w-0 flex-1"
1630
+ zWave={false}
1631
+ onclick={toggleSelectAll}
1632
+ >
1633
+ <ZIcon zType={isAllSelected ? 'lucideX' : 'lucideCheckCheck'} zSize="18" class="shrink-0" />
1634
+ <span class="truncate">
1635
+ {isAllSelected ? zTranslate('i18n_z_ui_select_clear_all') : zTranslate('i18n_z_ui_select_select_all')}
1636
+ </span>
1637
+ </ZButton>
1638
+ {/if}
1639
+ </div>
1640
+ {/if}
1641
+ {/if}
1642
+ </ZPopover>