@aleph-alpha/ui-library 2.6.2 → 2.7.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.
@@ -0,0 +1,481 @@
1
+ <script setup lang="ts">
2
+ import type { AcceptableValue } from 'reka-ui';
3
+ import { useFilter } from 'reka-ui';
4
+ import { computed, ref } from 'vue';
5
+ import {
6
+ Popover as ShadcnPopover,
7
+ PopoverAnchor as ShadcnPopoverAnchor,
8
+ PopoverContent as ShadcnPopoverContent,
9
+ } from '@/components/core/popover';
10
+ import { UiIcon } from '@/components/UiIcon';
11
+ import { cn } from '@/lib/utils';
12
+ import { provideUiAutocompleteContext } from './context';
13
+ import type { UiAutocompleteEmits, UiAutocompleteProps } from './types';
14
+
15
+ defineOptions({
16
+ name: 'UiAutocomplete',
17
+ });
18
+
19
+ const props = withDefaults(defineProps<UiAutocompleteProps>(), {
20
+ modelValue: undefined,
21
+ defaultValue: undefined,
22
+ placeholder: undefined,
23
+ ariaLabel: undefined,
24
+ inputValue: undefined,
25
+ defaultInputValue: '',
26
+ open: undefined,
27
+ defaultOpen: false,
28
+ multiple: false,
29
+ disabled: false,
30
+ required: false,
31
+ name: undefined,
32
+ dir: 'ltr',
33
+ size: 'default',
34
+ emptyText: 'No results found.',
35
+ startIcon: undefined,
36
+ showIndicator: true,
37
+ });
38
+
39
+ const emit = defineEmits<UiAutocompleteEmits>();
40
+
41
+ const inputEl = ref<HTMLInputElement | null>(null);
42
+ const itemLabels = ref<Map<string, string>>(new Map());
43
+ const highlightedIndex = ref(-1);
44
+ const internalOpen = ref(props.defaultOpen);
45
+ const internalInputValue = ref(props.defaultInputValue);
46
+ const internalValue = ref<string | string[]>(
47
+ props.defaultValue ?? (props.multiple ? [] : ''),
48
+ );
49
+ const { contains } = useFilter({ sensitivity: 'base' });
50
+
51
+ const isValueControlled = computed(() => props.modelValue !== undefined);
52
+ const isInputControlled = computed(() => props.inputValue !== undefined);
53
+ const options = computed(() => props.options ?? []);
54
+
55
+ const openState = computed({
56
+ get() {
57
+ return props.open ?? internalOpen.value;
58
+ },
59
+ set(value: boolean) {
60
+ internalOpen.value = value;
61
+ emit('update:open', value);
62
+ },
63
+ });
64
+
65
+ const inputText = computed({
66
+ get() {
67
+ return props.inputValue ?? internalInputValue.value;
68
+ },
69
+ set(value: string) {
70
+ if (!isInputControlled.value) {
71
+ internalInputValue.value = value;
72
+ }
73
+ emit('update:inputValue', value);
74
+ },
75
+ });
76
+
77
+ const selectedValues = computed<string[]>(() => {
78
+ const value = isValueControlled.value
79
+ ? props.modelValue
80
+ : internalValue.value;
81
+ if (Array.isArray(value)) return value;
82
+ if (typeof value === 'string' && value.length > 0) return [value];
83
+ return [];
84
+ });
85
+
86
+ const selectedOptions = computed(() =>
87
+ selectedValues.value.map(
88
+ (value) =>
89
+ options.value.find((option) => option.value === value) ?? {
90
+ value,
91
+ label: itemLabels.value.get(value) ?? value,
92
+ },
93
+ ),
94
+ );
95
+
96
+ const displayText = computed(() =>
97
+ selectedOptions.value.map((option) => option.label).join(', '),
98
+ );
99
+
100
+ const showSelectionDisplay = computed(
101
+ () => inputText.value.length === 0 && selectedValues.value.length > 0,
102
+ );
103
+
104
+ const filteredOptions = computed(() => {
105
+ const query = inputText.value.trim();
106
+ if (!query) return options.value;
107
+ return options.value.filter((option) => contains(option.label, query));
108
+ });
109
+
110
+ const hasInternalOptions = computed(() => props.options !== undefined);
111
+ const keyboardValues = computed(() =>
112
+ hasInternalOptions.value
113
+ ? filteredOptions.value
114
+ .filter((option) => !option.disabled)
115
+ .map((option) => option.value)
116
+ : Array.from(itemLabels.value.keys()),
117
+ );
118
+ const highlightedValue = computed(
119
+ () => keyboardValues.value[highlightedIndex.value],
120
+ );
121
+
122
+ const formHiddenValues = computed(() => {
123
+ if (!props.name) return [];
124
+ return props.multiple
125
+ ? selectedValues.value
126
+ : selectedValues.value.slice(0, 1);
127
+ });
128
+
129
+ const inputSlotProps = computed(() => ({
130
+ value: inputText.value,
131
+ placeholder: props.placeholder,
132
+ ariaLabel: props.ariaLabel ?? props.placeholder ?? 'Autocomplete',
133
+ disabled: props.disabled,
134
+ selectedValues: selectedValues.value,
135
+ selectedOptions: selectedOptions.value,
136
+ displayText: displayText.value,
137
+ showSelectionDisplay: showSelectionDisplay.value,
138
+ open: openState.value,
139
+ setInputValue,
140
+ setOpen,
141
+ }));
142
+
143
+ const shellClasses = computed(() =>
144
+ cn(
145
+ 'border-input focus-within:border-border-surface-focus-ring focus-within:ring-ring/50 focus-within:shadow-xs aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive flex w-full min-w-0 items-center gap-2 rounded-md border bg-background-input-default px-3 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-within:ring-[3px]',
146
+ props.size === 'default' ? 'h-9 py-2' : 'h-8 py-1.5',
147
+ props.disabled && 'pointer-events-none cursor-not-allowed opacity-50',
148
+ ),
149
+ );
150
+
151
+ function setOpen(value: boolean) {
152
+ if (props.disabled) return;
153
+ const wasOpen = openState.value;
154
+ openState.value = value;
155
+ if (value && !wasOpen) {
156
+ syncHighlightToSelection();
157
+ }
158
+ }
159
+
160
+ function setInputValue(value: string) {
161
+ inputText.value = value;
162
+ highlightedIndex.value = -1;
163
+ if (value.length > 0) {
164
+ setOpen(true);
165
+ }
166
+ }
167
+
168
+ function focusInput() {
169
+ inputEl.value?.focus();
170
+ }
171
+
172
+ function normalizeSelection(value: AcceptableValue | AcceptableValue[]) {
173
+ if (Array.isArray(value)) {
174
+ return value.filter((item): item is string => typeof item === 'string');
175
+ }
176
+ return typeof value === 'string' && value.length > 0 ? value : '';
177
+ }
178
+
179
+ function updateSelection(value: AcceptableValue | AcceptableValue[]) {
180
+ applySelectionValue(value, true);
181
+
182
+ inputText.value = '';
183
+ highlightedIndex.value = -1;
184
+ if (!props.multiple) {
185
+ setOpen(false);
186
+ return;
187
+ }
188
+ focusInput();
189
+ }
190
+
191
+ function isSelected(value: string) {
192
+ return selectedValues.value.includes(value);
193
+ }
194
+
195
+ function highlightOption(value: string) {
196
+ setHighlightedIndex(keyboardValues.value.indexOf(value));
197
+ }
198
+
199
+ function handleInput(event: Event) {
200
+ emit('input', event);
201
+ setInputValue((event.target as HTMLInputElement).value);
202
+ }
203
+
204
+ function handleKeydown(event: KeyboardEvent) {
205
+ emit('keydown', event);
206
+ handleKeyboardNavigation(event);
207
+ }
208
+
209
+ function handleListboxKeydown(event: KeyboardEvent) {
210
+ handleKeyboardNavigation(event);
211
+ }
212
+
213
+ function handleKeyboardNavigation(event: KeyboardEvent) {
214
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
215
+ event.preventDefault();
216
+ setOpen(true);
217
+ moveHighlight(event.key === 'ArrowDown' ? 1 : -1);
218
+ }
219
+
220
+ if (event.key === 'Escape') {
221
+ setOpen(false);
222
+ }
223
+
224
+ if (event.key === 'Enter' && openState.value) {
225
+ const value =
226
+ highlightedValue.value ??
227
+ (hasInternalOptions.value
228
+ ? filteredOptions.value.find((option) => !option.disabled)?.value
229
+ : keyboardValues.value[0]);
230
+
231
+ if (!value) return;
232
+
233
+ event.preventDefault();
234
+ selectOption(value);
235
+ }
236
+ }
237
+
238
+ function selectOption(value: string) {
239
+ if (props.multiple) {
240
+ const next = isSelected(value)
241
+ ? selectedValues.value.filter((item) => item !== value)
242
+ : [...selectedValues.value, value];
243
+ updateSelection(next);
244
+ setOpen(true);
245
+ return;
246
+ }
247
+
248
+ updateSelection(value);
249
+ }
250
+
251
+ function handleFocus(event: FocusEvent) {
252
+ emit('focus', event);
253
+ setOpen(true);
254
+ }
255
+
256
+ function handleBlur(event: FocusEvent) {
257
+ emit('blur', event);
258
+ }
259
+
260
+ function moveHighlight(delta: 1 | -1) {
261
+ const values = keyboardValues.value;
262
+ if (values.length === 0) return;
263
+
264
+ if (highlightedIndex.value === -1) {
265
+ setHighlightedIndex(delta === 1 ? 0 : values.length - 1);
266
+ return;
267
+ }
268
+
269
+ setHighlightedIndex(
270
+ (highlightedIndex.value + delta + values.length) % values.length,
271
+ );
272
+ }
273
+
274
+ function syncHighlightToSelection() {
275
+ const values = keyboardValues.value;
276
+ const selectedValue = selectedValues.value.find((value) =>
277
+ values.includes(value),
278
+ );
279
+
280
+ highlightedIndex.value = selectedValue ? values.indexOf(selectedValue) : -1;
281
+ }
282
+
283
+ function setHighlightedIndex(index: number) {
284
+ highlightedIndex.value = index;
285
+ const value = keyboardValues.value[index];
286
+ if (!props.multiple && value) {
287
+ applySelectionValue(value, false);
288
+ }
289
+ }
290
+
291
+ function applySelectionValue(
292
+ value: AcceptableValue | AcceptableValue[],
293
+ shouldEmitSelect: boolean,
294
+ ) {
295
+ const next = normalizeSelection(value);
296
+ if (!isValueControlled.value) {
297
+ internalValue.value = next;
298
+ }
299
+ emit('update:modelValue', next);
300
+ if (shouldEmitSelect) {
301
+ emit('select', next);
302
+ }
303
+ }
304
+
305
+ provideUiAutocompleteContext({
306
+ multiple: computed(() => props.multiple),
307
+ selectedValues,
308
+ itemLabels,
309
+ highlightedValue,
310
+ isSelected,
311
+ selectOption,
312
+ highlightOption,
313
+ });
314
+ </script>
315
+
316
+ <template>
317
+ <div class="flex flex-col" :dir="props.dir">
318
+ <ShadcnPopover v-model:open="openState">
319
+ <ShadcnPopoverAnchor as-child>
320
+ <div data-slot="autocomplete-trigger" :class="shellClasses">
321
+ <UiIcon
322
+ v-if="props.startIcon"
323
+ :name="props.startIcon"
324
+ :size="16"
325
+ class="text-muted-foreground shrink-0"
326
+ />
327
+
328
+ <div class="relative flex min-w-0 flex-1 items-center">
329
+ <slot name="input" v-bind="inputSlotProps">
330
+ <span
331
+ v-if="showSelectionDisplay"
332
+ data-slot="autocomplete-value"
333
+ class="pointer-events-none min-w-0 flex-1 truncate"
334
+ >
335
+ {{ displayText }}
336
+ </span>
337
+ <input
338
+ ref="inputEl"
339
+ data-slot="autocomplete-input"
340
+ :value="inputText"
341
+ :placeholder="
342
+ showSelectionDisplay ? undefined : props.placeholder
343
+ "
344
+ :aria-label="
345
+ props.ariaLabel ?? props.placeholder ?? 'Autocomplete'
346
+ "
347
+ :disabled="props.disabled"
348
+ :required="props.required && selectedValues.length === 0"
349
+ class="placeholder:text-muted-foreground min-w-0 bg-transparent outline-none disabled:cursor-not-allowed"
350
+ :class="
351
+ showSelectionDisplay
352
+ ? 'absolute inset-0 size-full cursor-text opacity-0'
353
+ : 'flex-1'
354
+ "
355
+ @input="handleInput"
356
+ @focus="handleFocus"
357
+ @blur="handleBlur"
358
+ @keydown="handleKeydown"
359
+ />
360
+ </slot>
361
+ </div>
362
+
363
+ <button
364
+ type="button"
365
+ class="text-muted-foreground flex size-5 shrink-0 items-center justify-center rounded-sm outline-none"
366
+ :disabled="props.disabled"
367
+ :aria-expanded="openState"
368
+ aria-haspopup="listbox"
369
+ :aria-label="openState ? 'Close suggestions' : 'Open suggestions'"
370
+ @mousedown.prevent.stop
371
+ @click.stop="
372
+ setOpen(!openState);
373
+ focusInput();
374
+ "
375
+ >
376
+ <UiIcon
377
+ name="chevron-down"
378
+ :size="16"
379
+ class="transition-transform duration-200"
380
+ :class="{ 'rotate-180': openState }"
381
+ />
382
+ </button>
383
+ </div>
384
+ </ShadcnPopoverAnchor>
385
+
386
+ <ShadcnPopoverContent
387
+ data-slot="autocomplete-content"
388
+ side="bottom"
389
+ :side-offset="4"
390
+ align="start"
391
+ :force-mount="true"
392
+ class="min-w-(--reka-popper-anchor-width) w-(--reka-popper-anchor-width) max-w-(--reka-popper-available-width) p-1 data-[state=closed]:hidden data-[state=closed]:pointer-events-none"
393
+ @open-auto-focus.prevent
394
+ >
395
+ <div
396
+ role="listbox"
397
+ aria-label="Options"
398
+ :aria-multiselectable="props.multiple"
399
+ data-slot="listbox-content"
400
+ tabindex="-1"
401
+ class="max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto"
402
+ @keydown.capture="handleListboxKeydown"
403
+ >
404
+ <div
405
+ v-for="option in hasInternalOptions ? filteredOptions : []"
406
+ :key="option.value"
407
+ role="option"
408
+ :aria-selected="isSelected(option.value)"
409
+ :aria-disabled="option.disabled || undefined"
410
+ :data-disabled="option.disabled ? '' : undefined"
411
+ :data-autocomplete-value="option.value"
412
+ :data-highlighted="
413
+ highlightedValue === option.value ? '' : undefined
414
+ "
415
+ :data-state="isSelected(option.value) ? 'checked' : 'unchecked'"
416
+ tabindex="-1"
417
+ 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 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
418
+ :class="{
419
+ 'pr-12': props.showIndicator,
420
+ 'pr-2': !props.showIndicator,
421
+ }"
422
+ @pointermove="highlightOption(option.value)"
423
+ @click="!option.disabled && selectOption(option.value)"
424
+ @keydown.enter.prevent="
425
+ !option.disabled && selectOption(option.value)
426
+ "
427
+ @keydown.space.prevent="
428
+ !option.disabled && selectOption(option.value)
429
+ "
430
+ >
431
+ <span class="min-w-0 flex-1 truncate">
432
+ <slot
433
+ name="item"
434
+ :option="option"
435
+ :selected="isSelected(option.value)"
436
+ :disabled="option.disabled ?? false"
437
+ >
438
+ {{ option.label }}
439
+ </slot>
440
+ </span>
441
+ <span
442
+ v-if="props.showIndicator"
443
+ class="!absolute right-2 flex items-center justify-center"
444
+ data-slot="autocomplete-item-end"
445
+ >
446
+ <span v-if="isSelected(option.value)">
447
+ <slot name="indicator-icon">
448
+ <UiIcon name="check" :size="16" />
449
+ </slot>
450
+ </span>
451
+ </span>
452
+ </div>
453
+
454
+ <div
455
+ v-if="hasInternalOptions && filteredOptions.length === 0"
456
+ class="text-muted-foreground px-2 py-1.5 text-sm"
457
+ >
458
+ {{ props.emptyText }}
459
+ </div>
460
+
461
+ <slot
462
+ v-else-if="!hasInternalOptions"
463
+ :input-value="inputText"
464
+ :selected-values="selectedValues"
465
+ :selected-options="selectedOptions"
466
+ :is-selected="isSelected"
467
+ :set-open="setOpen"
468
+ />
469
+ </div>
470
+ </ShadcnPopoverContent>
471
+ </ShadcnPopover>
472
+
473
+ <input
474
+ v-for="value in formHiddenValues"
475
+ :key="value"
476
+ type="hidden"
477
+ :name="props.name"
478
+ :value="value"
479
+ />
480
+ </div>
481
+ </template>
@@ -0,0 +1,98 @@
1
+ <script setup lang="ts">
2
+ import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
3
+ import { UiIcon } from '@/components/UiIcon';
4
+ import { useUiAutocompleteContext } from './context';
5
+ import type { UiAutocompleteItemProps } from './types';
6
+
7
+ defineOptions({
8
+ name: 'UiAutocompleteItem',
9
+ });
10
+
11
+ const props = withDefaults(defineProps<UiAutocompleteItemProps>(), {
12
+ disabled: false,
13
+ textValue: undefined,
14
+ });
15
+
16
+ const emit = defineEmits<{
17
+ /** Emitted when the item is selected. */
18
+ select: [event: Event];
19
+ }>();
20
+
21
+ const ctx = useUiAutocompleteContext();
22
+ const labelEl = ref<HTMLElement | null>(null);
23
+
24
+ function readLabel() {
25
+ return labelEl.value?.textContent?.trim() || props.textValue || props.value;
26
+ }
27
+
28
+ function syncLabel() {
29
+ ctx.itemLabels.value.set(props.value, readLabel());
30
+ }
31
+
32
+ onMounted(syncLabel);
33
+
34
+ watch(
35
+ () => props.value,
36
+ (next, prev) => {
37
+ if (prev !== undefined && prev !== next) {
38
+ ctx.itemLabels.value.delete(prev);
39
+ }
40
+ ctx.itemLabels.value.set(next, readLabel());
41
+ },
42
+ );
43
+
44
+ watch(() => props.textValue, syncLabel);
45
+
46
+ onBeforeUnmount(() => {
47
+ ctx.itemLabels.value.delete(props.value);
48
+ });
49
+ </script>
50
+
51
+ <template>
52
+ <div
53
+ role="option"
54
+ :aria-selected="ctx.isSelected(props.value)"
55
+ :aria-disabled="props.disabled || undefined"
56
+ :data-disabled="props.disabled ? '' : undefined"
57
+ :data-autocomplete-value="props.value"
58
+ :data-highlighted="
59
+ ctx.highlightedValue.value === props.value ? '' : undefined
60
+ "
61
+ :data-state="ctx.isSelected(props.value) ? 'checked' : 'unchecked'"
62
+ tabindex="-1"
63
+ 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 pr-12 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
64
+ @pointermove="ctx.highlightOption(props.value)"
65
+ @click="
66
+ if (!props.disabled) {
67
+ ctx.selectOption(props.value);
68
+ emit('select', $event);
69
+ }
70
+ "
71
+ @keydown.enter.prevent="
72
+ if (!props.disabled) {
73
+ ctx.selectOption(props.value);
74
+ emit('select', $event);
75
+ }
76
+ "
77
+ @keydown.space.prevent="
78
+ if (!props.disabled) {
79
+ ctx.selectOption(props.value);
80
+ emit('select', $event);
81
+ }
82
+ "
83
+ >
84
+ <span ref="labelEl" class="min-w-0 flex-1 truncate">
85
+ <slot />
86
+ </span>
87
+ <span
88
+ class="!absolute right-2 flex items-center justify-center"
89
+ data-slot="autocomplete-item-end"
90
+ >
91
+ <span v-if="ctx.isSelected(props.value)">
92
+ <slot name="indicator-icon">
93
+ <UiIcon name="check" :size="16" />
94
+ </slot>
95
+ </span>
96
+ </span>
97
+ </div>
98
+ </template>