@aleph-alpha/ui-library 5.8.0 → 5.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +8 -7
  2. package/dist/system/__tests__/test-utils.d.ts +24 -0
  3. package/dist/system/components/UiAutocomplete/UiAutocomplete.vue.d.ts +8 -4
  4. package/dist/system/components/UiAutocomplete/types.d.ts +11 -0
  5. package/dist/system/components/UiFadeMask/UiFadeMask.vue.d.ts +21 -0
  6. package/dist/system/components/UiFadeMask/index.d.ts +2 -0
  7. package/dist/system/components/UiFadeMask/types.d.ts +33 -0
  8. package/dist/system/components/UiListbox/UiListboxVirtualizer.vue.d.ts +21 -0
  9. package/dist/system/components/UiListbox/index.d.ts +1 -0
  10. package/dist/system/components/UiListbox/types.d.ts +36 -0
  11. package/dist/system/components/UiSelect/UiSelectVirtualizer.vue.d.ts +21 -0
  12. package/dist/system/components/UiSelect/index.d.ts +1 -0
  13. package/dist/system/components/UiSelect/types.d.ts +36 -0
  14. package/dist/system/components/core/native-select/NativeSelectOptGroup.vue.d.ts +2 -2
  15. package/dist/system/components/core/native-select/NativeSelectOption.vue.d.ts +2 -2
  16. package/dist/system/components/index.d.ts +1 -0
  17. package/dist/system/lib.js +22249 -21090
  18. package/dist/system/mobile-device-frame.png +0 -0
  19. package/dist/system/patterns/UiFloatActions/types.d.ts +2 -1
  20. package/dist/system/patterns/UiProfileCard/index.d.ts +7 -0
  21. package/dist/system/patterns/UiTopBar/UiTopBar.vue.d.ts +23 -0
  22. package/dist/system/patterns/UiTopBar/index.d.ts +2 -0
  23. package/dist/system/patterns/UiTopBar/types.d.ts +28 -0
  24. package/dist/system/patterns/index.d.ts +2 -0
  25. package/dist/system/story-sidebar-icons.json +4 -1
  26. package/package.json +2 -1
  27. package/src/__tests__/test-utils.ts +74 -0
  28. package/src/components/UiAutocomplete/UiAutocomplete.stories.ts +94 -0
  29. package/src/components/UiAutocomplete/UiAutocomplete.vue +164 -44
  30. package/src/components/UiAutocomplete/__tests__/UiAutocompleteVirtualized.test.ts +107 -0
  31. package/src/components/UiAutocomplete/types.ts +11 -0
  32. package/src/components/UiDropdownMenu/UiDropdownMenu.stories.ts +760 -0
  33. package/src/components/UiFadeMask/UiFadeMask.stories.ts +563 -0
  34. package/src/components/UiFadeMask/UiFadeMask.vue +86 -0
  35. package/src/components/UiFadeMask/__tests__/UiFadeMask.test.ts +52 -0
  36. package/src/components/UiFadeMask/index.ts +6 -0
  37. package/src/components/UiFadeMask/types.ts +35 -0
  38. package/src/components/UiListbox/UiListbox.stories.ts +121 -0
  39. package/src/components/UiListbox/UiListboxVirtualizer.vue +42 -0
  40. package/src/components/UiListbox/__tests__/UiListboxVirtualizer.test.ts +96 -0
  41. package/src/components/UiListbox/index.ts +1 -0
  42. package/src/components/UiListbox/types.ts +42 -0
  43. package/src/components/UiSelect/UiSelect.stories.ts +109 -1
  44. package/src/components/UiSelect/UiSelectVirtualizer.vue +373 -0
  45. package/src/components/UiSelect/__tests__/UiSelectVirtualizer.test.ts +185 -0
  46. package/src/components/UiSelect/index.ts +1 -0
  47. package/src/components/UiSelect/types.ts +38 -0
  48. package/src/components/core/dropdown-menu/DropdownMenuCheckboxItem.vue +8 -2
  49. package/src/components/core/dropdown-menu/DropdownMenuItem.vue +1 -1
  50. package/src/components/core/dropdown-menu/DropdownMenuRadioItem.vue +8 -2
  51. package/src/components/core/dropdown-menu/DropdownMenuSubTrigger.vue +1 -1
  52. package/src/components/core/listbox/ListboxItem.vue +1 -1
  53. package/src/components/index.ts +1 -0
  54. package/src/patterns/UiFloatActions/UiFloatActions.stories.ts +4 -5
  55. package/src/patterns/UiFloatActions/UiFloatActions.vue +23 -11
  56. package/src/patterns/UiFloatActions/__tests__/UiFloatActions.test.ts +23 -0
  57. package/src/patterns/UiFloatActions/types.ts +2 -1
  58. package/src/patterns/UiProfileCard/UiProfileCard.stories.ts +1064 -0
  59. package/src/patterns/UiProfileCard/index.ts +7 -0
  60. package/src/patterns/UiTopBar/UiTopBar.stories.ts +1121 -0
  61. package/src/patterns/UiTopBar/UiTopBar.vue +166 -0
  62. package/src/patterns/UiTopBar/__tests__/UiTopBar.test.ts +245 -0
  63. package/src/patterns/UiTopBar/index.ts +2 -0
  64. package/src/patterns/UiTopBar/types.ts +29 -0
  65. package/src/patterns/index.ts +2 -0
@@ -19,7 +19,8 @@ export type UiFloatActionsOffset = number | AnchorFloatOffset;
19
19
  export interface UiFloatActionsProps {
20
20
  /**
21
21
  * How the floating panel opens.
22
- * - `hover` — pointer hover and keyboard focus on a focusable `button` anchor
22
+ * - `hover` — pointer hover and keyboard focus on a focusable non-button
23
+ * anchor (text inside remains selectable/copyable)
23
24
  * - `focus` — keyboard focus on the `button` anchor
24
25
  * - `click` — click or Enter/Space on the `button` anchor
25
26
  * - `manual` — controlled via `v-model:open`
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `UiProfileCard` is a composition pattern rather than a component: it is
3
+ * assembled from `UiDropdownMenu` parts in `UiProfileCard.stories.ts`, so there
4
+ * is nothing to export. This file exists because the generated pattern barrel
5
+ * re-exports every folder under `src/patterns`.
6
+ */
7
+ export {};
@@ -0,0 +1,23 @@
1
+ import { UiTopBarProps } from './types';
2
+ declare function __VLS_template(): {
3
+ attrs: Partial<{}>;
4
+ slots: Partial<Record<string, (_: {}) => any>> & Partial<Record<string, (_: {}) => any>> & Partial<Record<string, (_: {}) => any>> & Partial<Record<string, (_: {}) => any>> & {
5
+ default?(_: {
6
+ isMobile: boolean;
7
+ }): any;
8
+ };
9
+ refs: {};
10
+ rootEl: any;
11
+ };
12
+ type __VLS_TemplateResult = ReturnType<typeof __VLS_template>;
13
+ declare const __VLS_component: import('vue').DefineComponent<UiTopBarProps, {}, {}, {}, {}, import('vue').ComponentOptionsMixin, import('vue').ComponentOptionsMixin, {}, string, import('vue').PublicProps, Readonly<UiTopBarProps> & Readonly<{}>, {
14
+ ariaLabel: string;
15
+ leadingWidth: number | string;
16
+ }, {}, {}, {}, string, import('vue').ComponentProvideOptions, false, {}, any>;
17
+ declare const _default: __VLS_WithTemplateSlots<typeof __VLS_component, __VLS_TemplateResult["slots"]>;
18
+ export default _default;
19
+ type __VLS_WithTemplateSlots<T, S> = T & {
20
+ new (): {
21
+ $slots: S;
22
+ };
23
+ };
@@ -0,0 +1,2 @@
1
+ export { default as UiTopBar } from './UiTopBar.vue';
2
+ export * from './types';
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Application top bar shell. Owns the padded bar, its leading gutter and
3
+ * trailing region, and the mobile/desktop mode — the controls themselves are
4
+ * passed in as slots, each with a `mobile-` counterpart. The default slot wraps
5
+ * the whole layout so it can be replaced outright.
6
+ * @category Patterns
7
+ * @useCases app shell header, dashboard top bar, workspace chrome, banner landmark
8
+ * @keywords topbar, top bar, header, banner, app shell, chrome, layout, responsive
9
+ * @related UiSidebar, UiSidebarTrigger, UiFloatActionItems, UiAvatar
10
+ */
11
+ export interface UiTopBarProps {
12
+ /**
13
+ * Width of the leading gutter that holds the `logo` and `sidebar-toggle`
14
+ * slots. Numbers are pixels; strings pass through as a raw CSS length, so the
15
+ * gutter can track a resizable sidebar (for example `'var(--sidebar-width)'`).
16
+ *
17
+ * Desktop mode only. In mobile mode the gutter sizes to its content, since
18
+ * the sidebar is off-canvas and a fixed gutter would push the trailing
19
+ * actions outside a 320px viewport.
20
+ * @default 238
21
+ */
22
+ leadingWidth?: number | string;
23
+ /**
24
+ * Accessible name for the top bar's `banner` landmark.
25
+ * @default 'Top bar'
26
+ */
27
+ ariaLabel?: string;
28
+ }
@@ -7,4 +7,6 @@ export * from './UiDatePicker';
7
7
  export * from './UiFileUpload';
8
8
  export * from './UiFloatActions';
9
9
  export * from './UiPlaceholder';
10
+ export * from './UiProfileCard';
10
11
  export * from './UiSidebar';
12
+ export * from './UiTopBar';
@@ -4,6 +4,7 @@
4
4
  "components-uibuttongroup--accessibility": "accessibility",
5
5
  "components-uicheckbox--design-notes": "palette",
6
6
  "components-uicheckbox--accessibility": "accessibility",
7
+ "components-uidropdownmenu--accessibility": "accessibility",
7
8
  "components-uifield--design-notes": "palette",
8
9
  "components-uifield--accessibility": "accessibility",
9
10
  "components-uiitem--design-notes": "palette",
@@ -19,5 +20,7 @@
19
20
  "components-uiautocomplete--accessibility": "accessibility",
20
21
  "components-uibreadcrumb--accessibility": "accessibility",
21
22
  "patterns-uifloatactions--accessibility": "accessibility",
22
- "patterns-uidatatable--accessibility": "accessibility"
23
+ "patterns-uidatatable--accessibility": "accessibility",
24
+ "patterns-uiprofilecard--accessibility": "accessibility",
25
+ "patterns-uitopbar--accessibility": "accessibility"
23
26
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aleph-alpha/ui-library",
3
- "version": "5.8.0",
3
+ "version": "5.9.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "main": "dist/system/lib.js",
@@ -107,6 +107,7 @@
107
107
  "@floating-ui/vue": "1.1.9",
108
108
  "@internationalized/date": "^3.10.1",
109
109
  "@tanstack/vue-table": "^8.21.3",
110
+ "@tanstack/vue-virtual": "^3.13.23",
110
111
  "@vueuse/core": "14.1.0",
111
112
  "class-variance-authority": "^0.7.1",
112
113
  "clsx": "^2.1.1",
@@ -44,3 +44,77 @@ export function createMockIcon(testId = 'mock-icon'): Component {
44
44
  * ```
45
45
  */
46
46
  export const MockIcon = createMockIcon('mock-icon');
47
+
48
+ /**
49
+ * Stubs the layout and scrolling that jsdom leaves unimplemented, so that a
50
+ * virtualized list can measure its scroll container and move through it.
51
+ *
52
+ * Heights come from the stub rather than from layout, and the scrolled height
53
+ * is read off the spacer every virtualizer renders as its first child.
54
+ * @param viewportHeight - The visible height every element reports
55
+ * @returns A teardown restoring the stubbed properties
56
+ * @example
57
+ * ```ts
58
+ * import { stubScrollLayout } from '@/__tests__/test-utils';
59
+ *
60
+ * let restoreScrollLayout: () => void;
61
+ *
62
+ * beforeAll(() => {
63
+ * restoreScrollLayout = stubScrollLayout();
64
+ * });
65
+ *
66
+ * afterAll(() => {
67
+ * restoreScrollLayout();
68
+ * });
69
+ * ```
70
+ */
71
+ export function stubScrollLayout(viewportHeight = 300) {
72
+ const offsets = new WeakMap<Element, number>();
73
+
74
+ Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
75
+ configurable: true,
76
+ get: () => viewportHeight,
77
+ });
78
+
79
+ Object.defineProperty(Element.prototype, 'clientHeight', {
80
+ configurable: true,
81
+ get: () => viewportHeight,
82
+ });
83
+
84
+ Object.defineProperty(Element.prototype, 'scrollHeight', {
85
+ configurable: true,
86
+ get(this: Element) {
87
+ const spacer = this.firstElementChild;
88
+ return spacer instanceof HTMLElement
89
+ ? Number.parseFloat(spacer.style.height || '0')
90
+ : 0;
91
+ },
92
+ });
93
+
94
+ Object.defineProperty(Element.prototype, 'scrollTop', {
95
+ configurable: true,
96
+ get(this: Element) {
97
+ return offsets.get(this) ?? 0;
98
+ },
99
+ set(this: Element, offset: number) {
100
+ offsets.set(this, offset);
101
+ this.dispatchEvent(new Event('scroll'));
102
+ },
103
+ });
104
+
105
+ Element.prototype.scrollTo = function scrollTo(
106
+ this: Element,
107
+ optionsOrX?: ScrollToOptions | number,
108
+ y?: number,
109
+ ) {
110
+ this.scrollTop =
111
+ typeof optionsOrX === 'number' ? (y ?? 0) : (optionsOrX?.top ?? 0);
112
+ };
113
+
114
+ return () => {
115
+ Reflect.deleteProperty(HTMLElement.prototype, 'offsetHeight');
116
+ Reflect.deleteProperty(Element.prototype, 'clientHeight');
117
+ Reflect.deleteProperty(Element.prototype, 'scrollHeight');
118
+ Reflect.deleteProperty(Element.prototype, 'scrollTop');
119
+ };
120
+ }
@@ -446,6 +446,100 @@ async function findOpenListbox(body: ReturnType<typeof within>) {
446
446
  return body.getByRole('listbox');
447
447
  }
448
448
 
449
+ /**
450
+ * `virtualized` mounts only the options in view, for lists too long to render
451
+ * at once. Filtering and keyboard navigation still run over the full list, and
452
+ * the highlighted option is scrolled into view as it moves.
453
+ */
454
+ export const Virtualized: Story = {
455
+ render: () => ({
456
+ components: { UiAutocomplete },
457
+ setup() {
458
+ const selected = ref('');
459
+ const options = Array.from({ length: 10000 }, (_, index) => ({
460
+ value: `option-${index + 1}`,
461
+ label: `Option ${index + 1}`,
462
+ }));
463
+ return { selected, options };
464
+ },
465
+ template: `
466
+ <div class="w-[260px]">
467
+ <UiAutocomplete
468
+ v-model="selected"
469
+ :options="options"
470
+ virtualized
471
+ placeholder="Search options"
472
+ />
473
+ </div>
474
+ `,
475
+ }),
476
+ play: async ({ canvasElement, step }) => {
477
+ // Scenario (UiAutocomplete): a 10,000 option list keeps only the visible
478
+ // options in the DOM, while filtering and the keyboard still work over the
479
+ // full list.
480
+ const canvas = within(canvasElement);
481
+ const body = within(document.body);
482
+ const input = canvas.getByRole('textbox');
483
+
484
+ await userEvent.click(input);
485
+ const list = await findOpenListbox(body);
486
+
487
+ await step(
488
+ 'interaction: only the options in view are in the DOM',
489
+ async () => {
490
+ const rendered = body.getAllByRole('option');
491
+ await expect(rendered.length).toBeGreaterThan(0);
492
+ await expect(rendered.length).toBeLessThan(100);
493
+ },
494
+ );
495
+
496
+ await step(
497
+ 'screen-reader: an option announces its place in the full list (WCAG 4.1.2)',
498
+ async () => {
499
+ const first = body.getByRole('option', { name: 'Option 1' });
500
+ await expect(first).toHaveAttribute('aria-setsize', '10000');
501
+ await expect(first).toHaveAttribute('aria-posinset', '1');
502
+ },
503
+ );
504
+
505
+ await step(
506
+ 'interaction: scrolling mounts the options further down the list',
507
+ async () => {
508
+ list.scrollTop = list.scrollHeight;
509
+ await waitFor(async () => {
510
+ await expect(
511
+ body.getByRole('option', { name: 'Option 10000' }),
512
+ ).toBeVisible();
513
+ });
514
+ },
515
+ );
516
+
517
+ await step(
518
+ 'interaction: filtering searches the full list, not the mounted options',
519
+ async () => {
520
+ await userEvent.type(input, 'Option 9999');
521
+ await waitFor(async () => {
522
+ await expect(
523
+ body.getByRole('option', { name: 'Option 9999' }),
524
+ ).toBeVisible();
525
+ });
526
+ },
527
+ );
528
+
529
+ await step(
530
+ 'keyboard: the highlighted option is selected with Enter (WCAG 2.1.1)',
531
+ async () => {
532
+ await userEvent.keyboard('{ArrowDown}{Enter}');
533
+ await waitFor(async () => {
534
+ await expect(selectionDisplay(canvasElement)).toHaveTextContent(
535
+ 'Option 9999',
536
+ );
537
+ });
538
+ },
539
+ );
540
+ },
541
+ };
542
+
449
543
  /**
450
544
  * Accessibility guidance for the autocomplete: a labelled input and visible
451
545
  * disabled options — shown side by side in the default and accessible themes.
@@ -1,7 +1,8 @@
1
1
  <script setup lang="ts">
2
2
  import type { AcceptableValue } from 'reka-ui';
3
+ import { useVirtualizer } from '@tanstack/vue-virtual';
3
4
  import { useFilter } from 'reka-ui';
4
- import { computed, ref } from 'vue';
5
+ import { computed, ref, watch, type CSSProperties } from 'vue';
5
6
  import {
6
7
  Popover as ShadcnPopover,
7
8
  PopoverAnchor as ShadcnPopoverAnchor,
@@ -10,7 +11,11 @@ import {
10
11
  import { UiIcon } from '@/components/UiIcon';
11
12
  import { cn } from '@/lib/utils';
12
13
  import { provideUiAutocompleteContext } from './context';
13
- import type { UiAutocompleteEmits, UiAutocompleteProps } from './types';
14
+ import type {
15
+ UiAutocompleteEmits,
16
+ UiAutocompleteOption,
17
+ UiAutocompleteProps,
18
+ } from './types';
14
19
 
15
20
  defineOptions({
16
21
  name: 'UiAutocomplete',
@@ -33,12 +38,15 @@ const props = withDefaults(defineProps<UiAutocompleteProps>(), {
33
38
  emptyText: 'No results found.',
34
39
  startIcon: undefined,
35
40
  showIndicator: true,
41
+ virtualized: false,
42
+ estimateSize: 32,
36
43
  });
37
44
 
38
45
  const emit = defineEmits<UiAutocompleteEmits>();
39
46
 
40
47
  const rootEl = ref<HTMLElement | null>(null);
41
48
  const inputEl = ref<HTMLInputElement | null>(null);
49
+ const listboxEl = ref<HTMLElement | null>(null);
42
50
  const itemLabels = ref<Map<string, string>>(new Map());
43
51
  const highlightedIndex = ref(-1);
44
52
  const internalOpen = ref(props.defaultOpen);
@@ -121,6 +129,98 @@ const highlightedValue = computed(
121
129
  () => keyboardValues.value[highlightedIndex.value],
122
130
  );
123
131
 
132
+ const isVirtualized = computed(
133
+ () => props.virtualized && hasInternalOptions.value,
134
+ );
135
+
136
+ const virtualizer = useVirtualizer(
137
+ computed(() => ({
138
+ count: isVirtualized.value ? filteredOptions.value.length : 0,
139
+ getScrollElement: () => listboxEl.value,
140
+ estimateSize: () => props.estimateSize,
141
+ overscan: 12,
142
+ })),
143
+ );
144
+
145
+ type RenderedOption = {
146
+ /** The option to render. */
147
+ option: UiAutocompleteOption;
148
+ /** The position of the option in the filtered list, starting at 0. */
149
+ index: number;
150
+ /** The offset the option is placed at while virtualizing. */
151
+ style?: CSSProperties;
152
+ };
153
+
154
+ /**
155
+ * The options to render, with the offset each one needs while virtualizing.
156
+ * Off the virtualized path this is the plain filtered list.
157
+ */
158
+ const renderedOptions = computed<RenderedOption[]>(() => {
159
+ if (!hasInternalOptions.value) {
160
+ return [];
161
+ }
162
+
163
+ if (!isVirtualized.value) {
164
+ return filteredOptions.value.map((option, index) => ({ option, index }));
165
+ }
166
+
167
+ return virtualizer.value.getVirtualItems().flatMap((item) => {
168
+ const option = filteredOptions.value[item.index];
169
+ if (!option) {
170
+ return [];
171
+ }
172
+
173
+ return {
174
+ option,
175
+ index: item.index,
176
+ style: {
177
+ position: 'absolute',
178
+ top: 0,
179
+ left: 0,
180
+ width: '100%',
181
+ transform: `translateY(${item.start}px)`,
182
+ },
183
+ };
184
+ });
185
+ });
186
+
187
+ /**
188
+ * Brings the highlighted option into view.
189
+ *
190
+ * Keyboard navigation moves a highlight rather than focus, so the browser never
191
+ * scrolls for us, and while virtualizing the option may not even be mounted.
192
+ * @param align Where to place the option in the viewport.
193
+ */
194
+ function scrollHighlightIntoView(align: 'auto' | 'center') {
195
+ if (!isVirtualized.value || highlightedValue.value === undefined) {
196
+ return;
197
+ }
198
+
199
+ const index = filteredOptions.value.findIndex(
200
+ (option) => option.value === highlightedValue.value,
201
+ );
202
+ if (index !== -1) {
203
+ virtualizer.value.scrollToIndex(index, { align });
204
+ }
205
+ }
206
+
207
+ watch(highlightedValue, () => scrollHighlightIntoView('auto'));
208
+
209
+ // The list is only in the DOM while open, so the selection a freshly opened
210
+ // list starts on can only be scrolled to once the scroll container exists.
211
+ watch(listboxEl, (element) => {
212
+ if (element) {
213
+ scrollHighlightIntoView('center');
214
+ }
215
+ });
216
+
217
+ // A new query means a new list, which has to start from the top.
218
+ watch(filteredOptions, () => {
219
+ if (isVirtualized.value) {
220
+ virtualizer.value.scrollToOffset(0);
221
+ }
222
+ });
223
+
124
224
  const formHiddenValues = computed(() => {
125
225
  if (!props.name) return [];
126
226
  return props.multiple
@@ -418,6 +518,7 @@ provideUiAutocompleteContext({
418
518
  @interact-outside="handleInteractOutside"
419
519
  >
420
520
  <div
521
+ ref="listboxEl"
421
522
  role="listbox"
422
523
  aria-label="Options"
423
524
  :aria-multiselectable="props.multiple"
@@ -426,54 +527,73 @@ provideUiAutocompleteContext({
426
527
  class="max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto"
427
528
  @keydown.capture="handleListboxKeydown"
428
529
  >
530
+ <!--
531
+ The sizing container is presentational so that the options stay the
532
+ listbox's own children for assistive technology.
533
+ -->
429
534
  <div
430
- v-for="option in hasInternalOptions ? filteredOptions : []"
431
- :key="option.value"
432
- role="option"
433
- :aria-selected="isSelected(option.value)"
434
- :aria-disabled="option.disabled || undefined"
435
- :data-disabled="option.disabled ? '' : undefined"
436
- :data-autocomplete-value="option.value"
437
- :data-highlighted="
438
- highlightedValue === option.value ? '' : undefined
439
- "
440
- :data-state="isSelected(option.value) ? 'checked' : 'unchecked'"
441
- tabindex="-1"
442
- class="hover-layer hover-layer-default focus:text-foreground data-[highlighted]:bg-background-surface-muted-subtle data-[highlighted]:text-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pl-2 label-14-regular outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
443
- :class="{
444
- 'pr-12': props.showIndicator,
445
- 'pr-2': !props.showIndicator,
446
- }"
447
- @pointermove="highlightOption(option.value)"
448
- @click="!option.disabled && selectOption(option.value)"
449
- @keydown.enter.prevent="
450
- !option.disabled && selectOption(option.value)
451
- "
452
- @keydown.space.prevent="
453
- !option.disabled && selectOption(option.value)
535
+ role="presentation"
536
+ :style="
537
+ isVirtualized
538
+ ? {
539
+ position: 'relative',
540
+ height: `${virtualizer.getTotalSize()}px`,
541
+ }
542
+ : undefined
454
543
  "
455
544
  >
456
- <span class="min-w-0 flex-1 truncate">
457
- <slot
458
- name="item"
459
- :option="option"
460
- :selected="isSelected(option.value)"
461
- :disabled="option.disabled ?? false"
462
- >
463
- {{ option.label }}
464
- </slot>
465
- </span>
466
- <span
467
- v-if="props.showIndicator"
468
- class="!absolute right-2 flex items-center justify-center"
469
- data-slot="autocomplete-item-end"
545
+ <div
546
+ v-for="{ option, index, style } in renderedOptions"
547
+ :key="option.value"
548
+ :style="style"
549
+ role="option"
550
+ :aria-selected="isSelected(option.value)"
551
+ :aria-disabled="option.disabled || undefined"
552
+ :aria-setsize="isVirtualized ? filteredOptions.length : undefined"
553
+ :aria-posinset="isVirtualized ? index + 1 : undefined"
554
+ :data-disabled="option.disabled ? '' : undefined"
555
+ :data-autocomplete-value="option.value"
556
+ :data-highlighted="
557
+ highlightedValue === option.value ? '' : undefined
558
+ "
559
+ :data-state="isSelected(option.value) ? 'checked' : 'unchecked'"
560
+ tabindex="-1"
561
+ class="hover-layer hover-layer-default focus:text-foreground data-[highlighted]:bg-background-surface-muted-subtle data-[highlighted]:text-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pl-2 label-14-regular outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
562
+ :class="{
563
+ 'pr-12': props.showIndicator,
564
+ 'pr-2': !props.showIndicator,
565
+ }"
566
+ @pointermove="highlightOption(option.value)"
567
+ @click="!option.disabled && selectOption(option.value)"
568
+ @keydown.enter.prevent="
569
+ !option.disabled && selectOption(option.value)
570
+ "
571
+ @keydown.space.prevent="
572
+ !option.disabled && selectOption(option.value)
573
+ "
470
574
  >
471
- <span v-if="isSelected(option.value)">
472
- <slot name="indicator-icon">
473
- <UiIcon name="check" :size="16" />
575
+ <span class="min-w-0 flex-1 truncate">
576
+ <slot
577
+ name="item"
578
+ :option="option"
579
+ :selected="isSelected(option.value)"
580
+ :disabled="option.disabled ?? false"
581
+ >
582
+ {{ option.label }}
474
583
  </slot>
475
584
  </span>
476
- </span>
585
+ <span
586
+ v-if="props.showIndicator"
587
+ class="!absolute right-2 flex items-center justify-center"
588
+ data-slot="autocomplete-item-end"
589
+ >
590
+ <span v-if="isSelected(option.value)">
591
+ <slot name="indicator-icon">
592
+ <UiIcon name="check" :size="16" />
593
+ </slot>
594
+ </span>
595
+ </span>
596
+ </div>
477
597
  </div>
478
598
 
479
599
  <div
@@ -0,0 +1,107 @@
1
+ import '@testing-library/jest-dom/vitest';
2
+ import { render, waitFor } from '@testing-library/vue';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { afterAll, beforeAll, describe, expect, test } from 'vitest';
5
+ import { nextTick } from 'vue';
6
+ import { stubScrollLayout } from '@/__tests__/test-utils';
7
+ import { UiAutocomplete } from '../index';
8
+
9
+ const OPTION_COUNT = 500;
10
+ const VIEWPORT_HEIGHT = 300;
11
+
12
+ const options = Array.from({ length: OPTION_COUNT }, (_, index) => ({
13
+ value: `option-${index + 1}`,
14
+ label: `Option ${index + 1}`,
15
+ }));
16
+
17
+ let restoreScrollLayout: () => void;
18
+
19
+ // jsdom neither lays elements out nor scrolls them, so without a stand-in the
20
+ // virtualizer would measure a zero-height container and never see the scrolling
21
+ // that brings the options further down the list into range.
22
+ beforeAll(() => {
23
+ restoreScrollLayout = stubScrollLayout(VIEWPORT_HEIGHT);
24
+ });
25
+
26
+ afterAll(() => {
27
+ restoreScrollLayout();
28
+ });
29
+
30
+ /**
31
+ * Renders an open autocomplete over a long option list.
32
+ * @param virtualized Whether to mount only the options in view.
33
+ * @returns The testing-library render result.
34
+ */
35
+ async function renderAutocomplete(virtualized: boolean) {
36
+ const result = render(UiAutocomplete, {
37
+ props: { options, virtualized, defaultOpen: true, placeholder: 'Search' },
38
+ });
39
+
40
+ // The scroll container is only measurable once mounted, so the first render
41
+ // still comes out empty.
42
+ await nextTick();
43
+
44
+ return result;
45
+ }
46
+
47
+ describe('UiAutocomplete virtualized', () => {
48
+ test('mounts only the options in view instead of the whole list', async () => {
49
+ const { getAllByRole } = await renderAutocomplete(true);
50
+
51
+ const rendered = getAllByRole('option');
52
+ expect(rendered.length).toBeGreaterThan(0);
53
+ expect(rendered.length).toBeLessThan(OPTION_COUNT);
54
+ });
55
+
56
+ test('mounts the whole list when virtualization is off', async () => {
57
+ const { getAllByRole } = await renderAutocomplete(false);
58
+
59
+ expect(getAllByRole('option')).toHaveLength(OPTION_COUNT);
60
+ });
61
+
62
+ // Only a fraction of the options is in the DOM, so each one has to carry its
63
+ // place in the full list for screen readers to announce it correctly.
64
+ test('announces the position of an option within the full list', async () => {
65
+ const { getAllByRole } = await renderAutocomplete(true);
66
+
67
+ const [first] = getAllByRole('option');
68
+ expect(first).toHaveAttribute('aria-setsize', String(OPTION_COUNT));
69
+ expect(first).toHaveAttribute('aria-posinset', '1');
70
+ });
71
+
72
+ test('leaves the option list unannotated when virtualization is off', async () => {
73
+ const { getAllByRole } = await renderAutocomplete(false);
74
+
75
+ const [first] = getAllByRole('option');
76
+ expect(first).not.toHaveAttribute('aria-setsize');
77
+ });
78
+
79
+ // The options are stacked by transform inside a spacer, so the listbox has to
80
+ // scroll over the full list rather than only the mounted slice.
81
+ test('sizes the scroll container for the full list', async () => {
82
+ const { getByRole } = await renderAutocomplete(true);
83
+
84
+ const spacer = getByRole('listbox').firstElementChild as HTMLElement;
85
+ expect(spacer.style.height).toBe(`${OPTION_COUNT * 32}px`);
86
+ });
87
+
88
+ // The list opens on the selected option, which under virtualization is only
89
+ // in the DOM once it has been scrolled to.
90
+ test('opens on a selection that sits outside the mounted range', async () => {
91
+ const user = userEvent.setup();
92
+ const { getByRole } = render(UiAutocomplete, {
93
+ props: {
94
+ options,
95
+ virtualized: true,
96
+ defaultValue: 'option-400',
97
+ placeholder: 'Search',
98
+ },
99
+ });
100
+
101
+ await user.click(getByRole('textbox'));
102
+
103
+ await waitFor(() => {
104
+ expect(getByRole('option', { name: 'Option 400' })).toBeInTheDocument();
105
+ });
106
+ });
107
+ });