ember-primitives 0.61.1 → 0.63.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 (93) hide show
  1. package/README.md +8 -1
  2. package/declarations/components/accordion/content.d.ts +2 -1
  3. package/declarations/components/accordion/content.d.ts.map +1 -1
  4. package/declarations/components/accordion/header.d.ts +2 -1
  5. package/declarations/components/accordion/header.d.ts.map +1 -1
  6. package/declarations/components/accordion/item.d.ts +7 -0
  7. package/declarations/components/accordion/item.d.ts.map +1 -1
  8. package/declarations/components/accordion/public.d.ts +3 -3
  9. package/declarations/components/accordion/public.d.ts.map +1 -1
  10. package/declarations/components/accordion/trigger.d.ts +2 -1
  11. package/declarations/components/accordion/trigger.d.ts.map +1 -1
  12. package/declarations/components/command-palette.d.ts +329 -0
  13. package/declarations/components/command-palette.d.ts.map +1 -0
  14. package/declarations/components/dialog.d.ts +65 -7
  15. package/declarations/components/dialog.d.ts.map +1 -1
  16. package/declarations/components/drawer.d.ts +14 -6
  17. package/declarations/components/drawer.d.ts.map +1 -1
  18. package/declarations/components/link.d.ts.map +1 -1
  19. package/declarations/components/menu.d.ts.map +1 -1
  20. package/declarations/components/one-time-password/otp.d.ts +1 -1
  21. package/declarations/components/one-time-password/utils.d.ts.map +1 -1
  22. package/declarations/components/rating/range.d.ts +1 -0
  23. package/declarations/components/rating/range.d.ts.map +1 -1
  24. package/declarations/components/rating/rating.d.ts +1 -1
  25. package/declarations/components/rating/rating.d.ts.map +1 -1
  26. package/declarations/components/rating/stars.d.ts.map +1 -1
  27. package/declarations/components/rating/state.d.ts +1 -0
  28. package/declarations/components/rating/state.d.ts.map +1 -1
  29. package/declarations/components/slider.d.ts +2 -0
  30. package/declarations/components/slider.d.ts.map +1 -1
  31. package/declarations/components/switch.d.ts +5 -1
  32. package/declarations/components/switch.d.ts.map +1 -1
  33. package/declarations/components/tabs.d.ts +30 -1
  34. package/declarations/components/tabs.d.ts.map +1 -1
  35. package/declarations/components/zoetrope/index.d.ts.map +1 -1
  36. package/declarations/index.d.ts +2 -1
  37. package/declarations/index.d.ts.map +1 -1
  38. package/dist/components/accordion.js +12 -4
  39. package/dist/components/accordion.js.map +1 -1
  40. package/dist/components/command-palette.js +370 -0
  41. package/dist/components/command-palette.js.map +1 -0
  42. package/dist/components/dialog.js +59 -3
  43. package/dist/components/dialog.js.map +1 -1
  44. package/dist/components/drawer.js +9 -2
  45. package/dist/components/drawer.js.map +1 -1
  46. package/dist/components/link.js +1 -1
  47. package/dist/components/link.js.map +1 -1
  48. package/dist/components/menu.js +5 -1
  49. package/dist/components/menu.js.map +1 -1
  50. package/dist/components/one-time-password.js +1 -1
  51. package/dist/components/rating.js +1 -1
  52. package/dist/components/slider.js +6 -1
  53. package/dist/components/switch.js +1 -1
  54. package/dist/components/switch.js.map +1 -1
  55. package/dist/components/tabs.js +18 -5
  56. package/dist/components/tabs.js.map +1 -1
  57. package/dist/components/zoetrope/styles.css +6 -1
  58. package/dist/components/zoetrope.js +1 -1
  59. package/dist/{index-gRO4Cvlf.js → index-B-yrfUe9.js} +10 -3
  60. package/dist/index-B-yrfUe9.js.map +1 -0
  61. package/dist/index.js +5 -4
  62. package/dist/index.js.map +1 -1
  63. package/dist/{otp-H5a4B4yu.js → otp-C8c1EIw6.js} +27 -15
  64. package/dist/otp-C8c1EIw6.js.map +1 -0
  65. package/dist/{rating-BrIiwDLw.js → rating-CKWhrr-L.js} +9 -5
  66. package/dist/rating-CKWhrr-L.js.map +1 -0
  67. package/package.json +2 -1
  68. package/src/components/accordion/content.gts +4 -2
  69. package/src/components/accordion/header.gts +8 -2
  70. package/src/components/accordion/item.gts +18 -2
  71. package/src/components/accordion/public.ts +12 -3
  72. package/src/components/accordion/trigger.gts +5 -3
  73. package/src/components/command-palette.gts +741 -0
  74. package/src/components/dialog.gts +86 -4
  75. package/src/components/drawer.gts +15 -3
  76. package/src/components/link.gts +1 -0
  77. package/src/components/menu.gts +7 -0
  78. package/src/components/one-time-password/input.gts +1 -1
  79. package/src/components/one-time-password/otp.gts +1 -1
  80. package/src/components/one-time-password/utils.ts +26 -13
  81. package/src/components/rating/range.gts +3 -0
  82. package/src/components/rating/rating.gts +7 -2
  83. package/src/components/rating/stars.gts +0 -1
  84. package/src/components/rating/state.gts +9 -0
  85. package/src/components/slider.gts +8 -0
  86. package/src/components/switch.gts +5 -2
  87. package/src/components/tabs.gts +35 -4
  88. package/src/components/zoetrope/index.gts +12 -3
  89. package/src/components/zoetrope/styles.css +6 -1
  90. package/src/index.ts +2 -1
  91. package/dist/index-gRO4Cvlf.js.map +0 -1
  92. package/dist/otp-H5a4B4yu.js.map +0 -1
  93. package/dist/rating-BrIiwDLw.js.map +0 -1
@@ -0,0 +1,741 @@
1
+ /**
2
+ * References:
3
+ * - https://www.w3.org/WAI/ARIA/apg/patterns/combobox/
4
+ * - https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-activedescendant
5
+ *
6
+ * A combobox (the input) over a listbox (the results).
7
+ *
8
+ * Focus never leaves the input; `aria-activedescendant` is what moves. This is
9
+ * why there is no tabster mover here: the arrow keys must not move focus, or
10
+ * the user stops being able to type. Tabster still does the finding.
11
+ *
12
+ * Filtering is not this component's job. Render the results you want, in the
13
+ * order you want.
14
+ */
15
+ import Component from "@glimmer/component";
16
+ import { tracked } from "@glimmer/tracking";
17
+ import { assert } from "@ember/debug";
18
+ import { registerDestructor } from "@ember/destroyable";
19
+ import { hash } from "@ember/helper";
20
+ import { on } from "@ember/modifier";
21
+ import { guidFor } from "@ember/object/internals";
22
+
23
+ import { modifier as eModifier } from "ember-modifier";
24
+ import { getTabster } from "tabster";
25
+ // temp
26
+ // https://github.com/tracked-tools/tracked-toolbox/issues/38
27
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
28
+ // @ts-expect-error
29
+ import { localCopy } from "tracked-toolbox";
30
+
31
+ import { Link, type Signature as LinkSignature } from "./link.gts";
32
+ import { VisuallyHidden } from "./visually-hidden.gts";
33
+
34
+ import type { TOC } from "@ember/component/template-only";
35
+ import type Owner from "@ember/owner";
36
+ import type { ModifierLike, WithBoundArgs } from "@glint/template";
37
+
38
+ const OPTION = '[role="option"]';
39
+
40
+ function isMac() {
41
+ return navigator.userAgent.includes("Mac OS");
42
+ }
43
+
44
+ /**
45
+ * Matches a hotkey description, such as `"mod+k"`, against a keyboard event.
46
+ *
47
+ * `mod` is <kbd>Meta</kbd> on macOS and <kbd>Control</kbd> everywhere else,
48
+ * the same normalization `<KeyCombo>` uses to render one.
49
+ */
50
+ function matches(event: KeyboardEvent, hotkey: string) {
51
+ const parts = hotkey
52
+ .toLowerCase()
53
+ .split("+")
54
+ .map((part) => part.trim());
55
+ const key = parts.pop();
56
+ const modifiers = new Set(parts);
57
+ const mod = modifiers.has("mod");
58
+
59
+ return (
60
+ event.key.toLowerCase() === key &&
61
+ event.metaKey === (modifiers.has("meta") || (mod && isMac())) &&
62
+ event.ctrlKey === (modifiers.has("ctrl") || (mod && !isMac())) &&
63
+ event.altKey === modifiers.has("alt") &&
64
+ event.shiftKey === modifiers.has("shift")
65
+ );
66
+ }
67
+
68
+ export interface ItemSignature {
69
+ Element: HTMLDivElement;
70
+ Blocks: { default: [] };
71
+ }
72
+
73
+ interface PrivateItemSignature {
74
+ Element: ItemSignature["Element"];
75
+ Args: { activeId: string | undefined };
76
+ Blocks: ItemSignature["Blocks"];
77
+ }
78
+
79
+ class Item extends Component<PrivateItemSignature> {
80
+ id = guidFor(this);
81
+
82
+ get isActive() {
83
+ return this.args.activeId === this.id;
84
+ }
85
+
86
+ <template>
87
+ <div
88
+ id={{this.id}}
89
+ role="option"
90
+ tabindex="-1"
91
+ aria-selected="{{this.isActive}}"
92
+ data-active="{{this.isActive}}"
93
+ ...attributes
94
+ >
95
+ {{yield}}
96
+ </div>
97
+ </template>
98
+ }
99
+
100
+ export interface LinkItemSignature {
101
+ Element: HTMLAnchorElement;
102
+ Args: LinkSignature["Args"];
103
+ Blocks: { default: [] };
104
+ }
105
+
106
+ interface PrivateLinkItemSignature {
107
+ Element: LinkItemSignature["Element"];
108
+ Args: LinkItemSignature["Args"] & { activeId: string | undefined };
109
+ Blocks: LinkItemSignature["Blocks"];
110
+ }
111
+
112
+ /**
113
+ * An option that is also a link. <kbd>Enter</kbd> dispatches a real click on
114
+ * the anchor, so the router navigates exactly as it would have for a mouse.
115
+ */
116
+ class LinkItem extends Component<PrivateLinkItemSignature> {
117
+ id = guidFor(this);
118
+
119
+ get isActive() {
120
+ return this.args.activeId === this.id;
121
+ }
122
+
123
+ <template>
124
+ <Link
125
+ id={{this.id}}
126
+ role="option"
127
+ tabindex="-1"
128
+ aria-selected="{{this.isActive}}"
129
+ data-active="{{this.isActive}}"
130
+ @href={{@href}}
131
+ @includeActiveQueryParams={{@includeActiveQueryParams}}
132
+ @activeOnSubPaths={{@activeOnSubPaths}}
133
+ ...attributes
134
+ >
135
+ {{yield}}
136
+ </Link>
137
+ </template>
138
+ }
139
+
140
+ export interface ListSignature {
141
+ Element: HTMLDivElement;
142
+ Blocks: {
143
+ default: [
144
+ {
145
+ Item: WithBoundArgs<typeof Item, "activeId">;
146
+ LinkItem: WithBoundArgs<typeof LinkItem, "activeId">;
147
+ },
148
+ ];
149
+ };
150
+ }
151
+
152
+ interface PrivateListSignature {
153
+ Element: ListSignature["Element"];
154
+ Args: {
155
+ id: string;
156
+ register: ModifierLike<{ Element: HTMLElement }>;
157
+ onPointerMove: (event: PointerEvent) => void;
158
+ onClick: (event: MouseEvent) => void;
159
+ Item: ListSignature["Blocks"]["default"][0]["Item"];
160
+ LinkItem: ListSignature["Blocks"]["default"][0]["LinkItem"];
161
+ };
162
+ Blocks: ListSignature["Blocks"];
163
+ }
164
+
165
+ /**
166
+ * The pointer is handled here rather than on each option, and on
167
+ * `pointermove` rather than `pointerenter`, so that an option under a resting
168
+ * cursor re-activates when the cursor moves after the keyboard has activated
169
+ * something else. Native menus behave this way.
170
+ *
171
+ * `:hover` cannot do this job. There is one active option, it is what
172
+ * <kbd>Enter</kbd> chooses, and it is what `aria-activedescendant` reports.
173
+ * Hovering while the keyboard has a different option active would light two
174
+ * rows and tell a screen reader about neither, so the pointer sets the same
175
+ * state the arrow keys do instead of painting its own.
176
+ */
177
+ const List: TOC<PrivateListSignature> = <template>
178
+ <div
179
+ id={{@id}}
180
+ role="listbox"
181
+ {{@register}}
182
+ {{on "click" @onClick}}
183
+ {{on "pointermove" @onPointerMove}}
184
+ ...attributes
185
+ >
186
+ {{yield (hash Item=@Item LinkItem=@LinkItem)}}
187
+ </div>
188
+ </template>;
189
+
190
+ export interface InputSignature {
191
+ Element: HTMLInputElement;
192
+ }
193
+
194
+ interface PrivateInputSignature {
195
+ Element: InputSignature["Element"];
196
+ Args: {
197
+ listId: string;
198
+ activeId: string | undefined;
199
+ query: string;
200
+ onInput: (event: Event) => void;
201
+ onKeydown: (event: KeyboardEvent) => void;
202
+ };
203
+ }
204
+
205
+ const Input: TOC<PrivateInputSignature> = <template>
206
+ <input
207
+ type="text"
208
+ role="combobox"
209
+ autocomplete="off"
210
+ autocorrect="off"
211
+ autocapitalize="off"
212
+ spellcheck="false"
213
+ aria-autocomplete="list"
214
+ aria-expanded="true"
215
+ aria-controls={{@listId}}
216
+ aria-activedescendant={{@activeId}}
217
+ value={{@query}}
218
+ {{on "input" @onInput}}
219
+ {{on "keydown" @onKeydown}}
220
+ ...attributes
221
+ />
222
+ </template>;
223
+
224
+ /**
225
+ * One entry in the default layout. A bare string is the label.
226
+ */
227
+ export type PaletteItem =
228
+ | string
229
+ | {
230
+ label: string;
231
+ description?: string;
232
+ icon?: string;
233
+ };
234
+
235
+ const labelOf = (item: PaletteItem) => (typeof item === "string" ? item : item.label);
236
+ const descriptionOf = (item: PaletteItem) =>
237
+ typeof item === "string" ? undefined : item.description;
238
+ const iconOf = (item: PaletteItem) => (typeof item === "string" ? undefined : item.icon);
239
+
240
+ /**
241
+ * The default layout: hand it the rows and it renders the whole palette.
242
+ */
243
+ export interface ItemsSignature {
244
+ Args: {
245
+ /**
246
+ * The text in the input.
247
+ *
248
+ * The state is managed internally, so this does not need to be a
249
+ * maintained value, but whenever it changes, the input reflects it. Pair
250
+ * it with `@onQueryChange` to keep the query somewhere else, such as a
251
+ * query param.
252
+ */
253
+ query?: string;
254
+ /**
255
+ * Called with the input's text every time it changes.
256
+ */
257
+ onQueryChange?: (query: string) => void;
258
+ /**
259
+ * A key combination that calls `@onOpen` from anywhere on the page, such
260
+ * as `"mod+k"`. `mod` is <kbd>Meta</kbd> on macOS and <kbd>Control</kbd>
261
+ * everywhere else.
262
+ *
263
+ * Needs `@onOpen` to have anything to do. No listener is installed
264
+ * without both.
265
+ */
266
+ hotkey?: string;
267
+ /**
268
+ * Called when `@hotkey` is pressed. Hand it the `open` of whatever the
269
+ * palette is in:
270
+ *
271
+ * ```hbs
272
+ * <CommandPalette @hotkey="mod+k" @onOpen={{d.open}} />
273
+ * ```
274
+ */
275
+ onOpen?: () => void;
276
+ /**
277
+ * The entries to render. Each is a string, or an object with a `label`
278
+ * and optionally a `description` and an `icon`.
279
+ */
280
+ items: PaletteItem[];
281
+ /**
282
+ * Called every time a row is chosen, with the entry that was chosen.
283
+ * This is where a modal palette closes itself:
284
+ *
285
+ * ```hbs
286
+ * <Dialog as |d|>
287
+ * <CommandPalette @items={{this.commands}} @onSelect={{d.close}} />
288
+ * </Dialog>
289
+ * ```
290
+ *
291
+ * Also where a row's own action goes, since the entry it is handed says
292
+ * which row was chosen.
293
+ */
294
+ onSelect?: (item: PaletteItem, event: Event) => void;
295
+ /**
296
+ * The input's placeholder, and its accessible name.
297
+ *
298
+ * Defaults to "Search".
299
+ */
300
+ placeholder?: string;
301
+ /**
302
+ * What a screen reader announces when the number of results changes.
303
+ *
304
+ * Defaults to "1 result" and "3 results".
305
+ */
306
+ resultsText?: (count: number) => string;
307
+ };
308
+ /**
309
+ * No blocks: this form renders the rows. Passing one is an error.
310
+ */
311
+ Blocks: Record<string, never>;
312
+ }
313
+
314
+ /**
315
+ * The composed form: you render the rows.
316
+ */
317
+ export interface BlockSignature {
318
+ Args: {
319
+ /**
320
+ * The text in the input.
321
+ *
322
+ * The state is managed internally, so this does not need to be a
323
+ * maintained value, but whenever it changes, the input reflects it. Pair
324
+ * it with `@onQueryChange` to keep the query somewhere else, such as a
325
+ * query param.
326
+ */
327
+ query?: string;
328
+ /**
329
+ * Called with the input's text every time it changes.
330
+ */
331
+ onQueryChange?: (query: string) => void;
332
+ /**
333
+ * A key combination that calls `@onOpen` from anywhere on the page, such
334
+ * as `"mod+k"`. `mod` is <kbd>Meta</kbd> on macOS and <kbd>Control</kbd>
335
+ * everywhere else.
336
+ *
337
+ * Needs `@onOpen` to have anything to do. No listener is installed
338
+ * without both.
339
+ */
340
+ hotkey?: string;
341
+ /**
342
+ * Called when `@hotkey` is pressed. Hand it the `open` of whatever the
343
+ * palette is in:
344
+ *
345
+ * ```hbs
346
+ * <CommandPalette @hotkey="mod+k" @onOpen={{d.open}} />
347
+ * ```
348
+ */
349
+ onOpen?: () => void;
350
+ /**
351
+ * Not for this form: the rows come from the block.
352
+ */
353
+ items?: never;
354
+ /**
355
+ * Not for this form: set it on `Input` yourself.
356
+ */
357
+ placeholder?: never;
358
+ /**
359
+ * Not for this form: the rows are yours, and so is announcing them.
360
+ */
361
+ resultsText?: never;
362
+ /**
363
+ * Called every time a row is chosen. Hand it `close` to make a modal
364
+ * palette close itself.
365
+ *
366
+ * The rows are yours here, so there is no entry to hand back. Which row
367
+ * was chosen is `event.target.closest("[role=option]")`.
368
+ */
369
+ onSelect?: (event: Event) => void;
370
+ };
371
+ Blocks: {
372
+ default: [
373
+ {
374
+ /**
375
+ * The current text of the input.
376
+ */
377
+ query: string;
378
+ /**
379
+ * Sets the text of the input, for a "clear" button or a suggestion.
380
+ */
381
+ setQuery: (query: string) => void;
382
+ /**
383
+ * The `<input>`, wired as a combobox over `List`.
384
+ *
385
+ * It needs a name: pass `aria-label`, or an `id` and a `<label>`.
386
+ */
387
+ Input: WithBoundArgs<
388
+ typeof Input,
389
+ "listId" | "activeId" | "query" | "onInput" | "onKeydown"
390
+ >;
391
+ /**
392
+ * The listbox the rows are rendered into.
393
+ */
394
+ List: WithBoundArgs<
395
+ typeof List,
396
+ "id" | "register" | "onPointerMove" | "onClick" | "Item" | "LinkItem"
397
+ >;
398
+ },
399
+ ];
400
+ };
401
+ }
402
+
403
+ export type Signature = ItemsSignature | BlockSignature;
404
+
405
+ export class CommandPalette extends Component<Signature> {
406
+ listId = guidFor(this);
407
+
408
+ /**
409
+ * Held rather than looked up by id, because `document.getElementById` does
410
+ * not cross into a shadow root. A plain field: it is read when a key is
411
+ * pressed, never while rendering.
412
+ */
413
+ #list: HTMLElement | undefined;
414
+
415
+ /**
416
+ * Which row is active, as an id rather than an element or a focus state.
417
+ *
418
+ * This is unusual for this library, where keyboard navigation means tabster
419
+ * moving focus. A combobox cannot do that: focus has to stay in the
420
+ * `<input>` or the reader stops being able to type. So nothing among the
421
+ * rows is ever focused, there is no focus for tabster to track, and what
422
+ * moves instead is `aria-activedescendant` -- which is an id, on the input,
423
+ * pointing at a row. Holding the id is holding exactly what that attribute
424
+ * needs.
425
+ *
426
+ * Tabster still does the finding, in `#find`. This only remembers which of
427
+ * the rows it landed on.
428
+ */
429
+ @tracked activeId: string | undefined;
430
+
431
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
432
+ @localCopy("args.query") declare _query: string;
433
+
434
+ constructor(owner: Owner, args: Signature["Args"]) {
435
+ super(owner, args);
436
+
437
+ document.addEventListener("keydown", this.handleHotkey);
438
+
439
+ registerDestructor(this, () => {
440
+ document.removeEventListener("keydown", this.handleHotkey);
441
+ });
442
+ }
443
+
444
+ get placeholder() {
445
+ return this.args.placeholder ?? "Search";
446
+ }
447
+
448
+ get resultsText() {
449
+ const count = this.args.items?.length ?? 0;
450
+ const custom = this.args.resultsText?.(count);
451
+
452
+ return custom ?? (count === 1 ? "1 result" : `${count} results`);
453
+ }
454
+
455
+ /**
456
+ * Whether `@items` was passed, not whether it has anything in it: an empty
457
+ * array is falsy in a template, and a palette whose results have gone away
458
+ * still has to render the input they would be typed into.
459
+ */
460
+ get hasItems() {
461
+ return this.args.items !== undefined;
462
+ }
463
+
464
+ /**
465
+ * Each form is called the way its own type describes: with the entry that
466
+ * was chosen, or with the event alone when the rows are the caller's.
467
+ *
468
+ * `@items` is what tells the two apart, and it is `never` on the form that
469
+ * does not take it, so testing it narrows `this.args` to one of them.
470
+ */
471
+ #select(option: HTMLElement, event: Event) {
472
+ if (this.args.items === undefined) {
473
+ this.args.onSelect?.(event);
474
+
475
+ return;
476
+ }
477
+
478
+ const entry = this.#entryFor(option, this.args.items);
479
+
480
+ assert(
481
+ "[BUG] a row of the default layout was chosen, but is not among `@items`",
482
+ entry !== undefined,
483
+ );
484
+
485
+ this.args.onSelect?.(entry, event);
486
+ }
487
+
488
+ /**
489
+ * `@items` and a block are two ways to say the same thing, and saying both
490
+ * means one of them is being quietly ignored.
491
+ */
492
+ get bothGiven() {
493
+ assert(
494
+ "<CommandPalette> was given both `@items` and a block. Use one: `@items` renders the rows for you, a block renders them yourself.",
495
+ false,
496
+ );
497
+
498
+ return "";
499
+ }
500
+
501
+ get query() {
502
+ return this._query ?? "";
503
+ }
504
+ set query(value: string) {
505
+ this._query = value;
506
+ }
507
+
508
+ registerList = eModifier((element: HTMLElement) => {
509
+ this.#list = element;
510
+ });
511
+
512
+ get #activeElement() {
513
+ const { activeId } = this;
514
+
515
+ if (!activeId) return undefined;
516
+
517
+ // scoped to the listbox, so this works inside a shadow root
518
+ return this.#list?.querySelector<HTMLElement>(`[id="${activeId}"]`) ?? undefined;
519
+ }
520
+
521
+ /**
522
+ * The next, previous, first or last option.
523
+ *
524
+ * Tabster does the finding, so hidden and inert options are skipped by the
525
+ * same rules as everything else that moves around the page. It has to be
526
+ * set up by the app, the same way `<Menu>` requires it.
527
+ */
528
+ #find(direction: "next" | "prev" | "first" | "last") {
529
+ const container = this.#list;
530
+
531
+ if (!container) return undefined;
532
+
533
+ const tabster = getTabster(window);
534
+
535
+ assert(
536
+ "<CommandPalette> needs tabster, which the application sets up. " +
537
+ "Call `setupTabster` from 'ember-primitives/tabster' in your application route. " +
538
+ "See https://tabster.io/docs/core",
539
+ tabster,
540
+ );
541
+
542
+ const options = { container, includeProgrammaticallyFocusable: true };
543
+ const currentElement = this.#activeElement;
544
+ const { focusable } = tabster;
545
+
546
+ if (direction === "first") return focusable.findFirst(options);
547
+ if (direction === "last") return focusable.findLast(options);
548
+
549
+ if (!currentElement) {
550
+ return direction === "next" ? focusable.findFirst(options) : focusable.findLast(options);
551
+ }
552
+
553
+ const found =
554
+ direction === "next"
555
+ ? focusable.findNext({ ...options, currentElement })
556
+ : focusable.findPrev({ ...options, currentElement });
557
+
558
+ // wrap, rather than stop, at either end
559
+ return (
560
+ found ?? (direction === "next" ? focusable.findFirst(options) : focusable.findLast(options))
561
+ );
562
+ }
563
+
564
+ #activate(element: HTMLElement | null | undefined) {
565
+ if (!element) return;
566
+
567
+ this.activeId = element.id;
568
+ element.scrollIntoView({ block: "nearest" });
569
+ }
570
+
571
+ setQuery = (query: string) => {
572
+ this.query = query;
573
+ // the results are about to be somebody else's; whatever was active is not
574
+ this.activeId = undefined;
575
+ this.args.onQueryChange?.(query);
576
+ };
577
+
578
+ handleInput = (event: Event) => {
579
+ const { target } = event;
580
+
581
+ assert("[BUG] input event without an input", target instanceof HTMLInputElement);
582
+
583
+ this.setQuery(target.value);
584
+ };
585
+
586
+ handlePointerMove = (event: PointerEvent) => {
587
+ const { target } = event;
588
+
589
+ if (!(target instanceof Element)) return;
590
+
591
+ const option = target.closest<HTMLElement>(OPTION);
592
+
593
+ if (option) {
594
+ this.activeId = option.id;
595
+ }
596
+ };
597
+
598
+ handleKeydown = (event: KeyboardEvent) => {
599
+ // mid-composition (IME), the arrow keys belong to the candidate window
600
+ if (event.isComposing) return;
601
+
602
+ switch (event.key) {
603
+ case "ArrowDown": {
604
+ event.preventDefault();
605
+ this.#activate(this.#find("next"));
606
+
607
+ return;
608
+ }
609
+ case "ArrowUp": {
610
+ event.preventDefault();
611
+ this.#activate(this.#find("prev"));
612
+
613
+ return;
614
+ }
615
+ case "Enter": {
616
+ // nothing arrowed yet chooses the first result, so a reader can type
617
+ // and press Enter without leaving the keys they were already on
618
+ const active = this.#activeElement ?? this.#find("first");
619
+
620
+ if (!active) return;
621
+
622
+ event.preventDefault();
623
+ // a real click, so one handler covers the mouse and the keyboard, and
624
+ // an anchor navigates the way the browser would have
625
+ active.click();
626
+
627
+ return;
628
+ }
629
+ /**
630
+ * Home and End are left to the browser: in an editable combobox they
631
+ * move the caret, which is what the APG asks for.
632
+ */
633
+ }
634
+ };
635
+
636
+ handleHotkey = (event: KeyboardEvent) => {
637
+ const { hotkey, onOpen } = this.args;
638
+
639
+ if (!hotkey || !onOpen) return;
640
+ if (!matches(event, hotkey)) return;
641
+
642
+ event.preventDefault();
643
+ onOpen();
644
+ };
645
+
646
+ /**
647
+ * The entry a row came from, for the default layout. Rows are rendered one
648
+ * per entry and in order, so a row's position among the options is its
649
+ * entry's position in `@items`. A block form has no entries, and gets
650
+ * `undefined`.
651
+ */
652
+ #entryFor(option: HTMLElement, items: PaletteItem[]) {
653
+ const options = this.#list?.querySelectorAll<HTMLElement>(OPTION);
654
+
655
+ for (let i = 0; i < (options?.length ?? 0); i++) {
656
+ if (options?.[i] === option) return items[i];
657
+ }
658
+
659
+ return undefined;
660
+ }
661
+
662
+ /**
663
+ * Choosing is delegated, so a row is markup rather than a listener, and
664
+ * `@onSelect` is reached the same way however the rows were rendered.
665
+ */
666
+ handleClick = (event: MouseEvent) => {
667
+ const { target } = event;
668
+
669
+ if (!(target instanceof Element)) return;
670
+
671
+ const option = target.closest<HTMLElement>(OPTION);
672
+
673
+ if (!option) return;
674
+
675
+ /**
676
+ * A modified click on a link opens it somewhere else and leaves the
677
+ * reader where they are, so the palette stays where they left it.
678
+ */
679
+ if (option.closest("a")) {
680
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
681
+ if (event.button !== 0) return;
682
+ }
683
+
684
+ this.#select(option, event);
685
+ };
686
+
687
+ <template>
688
+ {{#let
689
+ (component
690
+ Input
691
+ listId=this.listId
692
+ activeId=this.activeId
693
+ query=this.query
694
+ onInput=this.handleInput
695
+ onKeydown=this.handleKeydown
696
+ )
697
+ (component
698
+ List
699
+ id=this.listId
700
+ register=this.registerList
701
+ onPointerMove=this.handlePointerMove
702
+ onClick=this.handleClick
703
+ Item=(component Item activeId=this.activeId)
704
+ LinkItem=(component LinkItem activeId=this.activeId)
705
+ )
706
+ as |PaletteInput PaletteList|
707
+ }}
708
+ {{#if this.hasItems}}
709
+ {{#if (has-block)}}{{this.bothGiven}}{{/if}}
710
+
711
+ <PaletteInput
712
+ class="ember-primitives__command-palette__input"
713
+ placeholder={{this.placeholder}}
714
+ aria-label={{this.placeholder}}
715
+ />
716
+
717
+ <PaletteList class="ember-primitives__command-palette__list" as |l|>
718
+ {{#each @items as |item|}}
719
+ <l.Item class="ember-primitives__command-palette__item">
720
+ {{#if (iconOf item)}}
721
+ <span class="ember-primitives__command-palette__icon">{{iconOf item}}</span>
722
+ {{/if}}
723
+ <span class="ember-primitives__command-palette__label">{{labelOf item}}</span>
724
+ {{#if (descriptionOf item)}}
725
+ <span class="ember-primitives__command-palette__description">{{descriptionOf
726
+ item
727
+ }}</span>
728
+ {{/if}}
729
+ </l.Item>
730
+ {{/each}}
731
+ </PaletteList>
732
+
733
+ <VisuallyHidden role="status">{{this.resultsText}}</VisuallyHidden>
734
+ {{else}}
735
+ {{yield (hash query=this.query setQuery=this.setQuery Input=PaletteInput List=PaletteList)}}
736
+ {{/if}}
737
+ {{/let}}
738
+ </template>
739
+ }
740
+
741
+ export default CommandPalette;