lostcoords-ui 0.5.0 → 0.6.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 (69) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +102 -48
  3. data/app/assets/tailwind/lostcoords/ui/card.css +5 -2
  4. data/app/assets/tailwind/lostcoords/ui/{disclosure.css → collapsible.css} +1 -1
  5. data/app/assets/tailwind/lostcoords/ui/components/code-block.css +5 -0
  6. data/app/assets/tailwind/lostcoords/ui/components/collapsible.css +5 -0
  7. data/app/assets/tailwind/lostcoords/ui/components/dialog.css +9 -0
  8. data/app/assets/tailwind/lostcoords/ui/components/emoji-picker.css +5 -0
  9. data/app/assets/tailwind/lostcoords/ui/components/menu.css +5 -0
  10. data/app/assets/tailwind/lostcoords/ui/components/prose.css +3 -0
  11. data/app/assets/tailwind/lostcoords/ui/components/table.css +3 -0
  12. data/app/assets/tailwind/lostcoords/ui/components/toast.css +5 -0
  13. data/app/assets/tailwind/lostcoords/ui/components/tooltip.css +4 -0
  14. data/app/assets/tailwind/lostcoords/ui/components.css +12 -25
  15. data/app/assets/tailwind/lostcoords/ui/core.css +21 -0
  16. data/app/assets/tailwind/lostcoords/ui/emoji-picker.css +45 -47
  17. data/app/assets/tailwind/lostcoords/ui/{reading.css → prose.css} +6 -0
  18. data/app/assets/tailwind/lostcoords/ui/sheet.css +3 -4
  19. data/app/assets/tailwind/lostcoords/ui/theme.css +16 -1
  20. data/app/assets/tailwind/lostcoords/ui/toast.css +23 -0
  21. data/app/assets/tailwind/lostcoords/ui/tooltip.css +12 -11
  22. data/app/assets/tailwind/lostcoords/ui/typography.css +1 -7
  23. data/app/helpers/lostcoords/ui/badge_helper.rb +2 -2
  24. data/app/helpers/lostcoords/ui/button_helper.rb +12 -6
  25. data/app/helpers/lostcoords/ui/choice_helper.rb +11 -7
  26. data/app/helpers/lostcoords/ui/collapsible_helper.rb +9 -0
  27. data/app/helpers/lostcoords/ui/dialog_helper.rb +10 -5
  28. data/app/helpers/lostcoords/ui/emoji_picker_helper.rb +6 -0
  29. data/app/helpers/lostcoords/ui/feedback_helper.rb +2 -2
  30. data/app/helpers/lostcoords/ui/form_helper.rb +1 -1
  31. data/app/helpers/lostcoords/ui/glass_helper.rb +1 -1
  32. data/app/helpers/lostcoords/ui/menu_helper.rb +37 -2
  33. data/app/helpers/lostcoords/ui/navigation_helper.rb +17 -4
  34. data/app/helpers/lostcoords/ui/render_attributes_helper.rb +17 -1
  35. data/app/helpers/lostcoords/ui/sheet_helper.rb +4 -0
  36. data/app/helpers/lostcoords/ui/structures_helper.rb +2 -92
  37. data/app/helpers/lostcoords/ui/toast_helper.rb +22 -0
  38. data/app/helpers/lostcoords/ui/{overlay_helper.rb → tooltip_helper.rb} +3 -3
  39. data/app/helpers/lostcoords/ui/typography_helper.rb +30 -0
  40. data/app/javascript/lostcoords/ui/controllers/lc_collapsible_controller.js +1 -1
  41. data/app/javascript/lostcoords/ui/controllers/lc_emoji_picker_controller.js +34 -6
  42. data/app/javascript/lostcoords/ui/controllers/lc_kbd_controller.js +12 -0
  43. data/app/javascript/lostcoords/ui/controllers/lc_menu_controller.js +23 -1
  44. data/app/javascript/lostcoords/ui/controllers/lc_selection_controller.js +6 -14
  45. data/app/javascript/lostcoords/ui/controllers/lc_sheet_controller.js +2 -2
  46. data/app/javascript/lostcoords/ui/controllers/lc_shortcut_controller.js +45 -0
  47. data/app/javascript/lostcoords/ui/controllers/lc_tabs_controller.js +18 -15
  48. data/app/javascript/lostcoords/ui/controllers/lc_toast_region_controller.js +62 -0
  49. data/app/javascript/lostcoords/ui/controllers/lc_tooltip_controller.js +46 -6
  50. data/app/javascript/lostcoords/ui/helpers/catalog_picker.js +72 -20
  51. data/app/javascript/lostcoords/ui/helpers/dismiss_stack.js +23 -0
  52. data/app/javascript/lostcoords/ui/helpers/floating_panel.js +6 -7
  53. data/app/javascript/lostcoords/ui/helpers/menu_keys.js +19 -18
  54. data/app/javascript/lostcoords/ui/helpers/roving_focus.js +175 -0
  55. data/app/javascript/lostcoords/ui/helpers/shortcuts.js +162 -0
  56. data/app/javascript/lostcoords/ui/helpers/top_layer.js +48 -10
  57. data/app/javascript/lostcoords/ui/index.js +6 -0
  58. data/app/views/lostcoords/ui/components/_emoji_picker.html.erb +27 -27
  59. data/app/views/lostcoords/ui/components/_emoji_picker_grid.html.erb +3 -3
  60. data/app/views/lostcoords/ui/components/_lc_code_block.html.erb +1 -1
  61. data/lib/lostcoords/ui/action_view.rb +1 -0
  62. data/lib/lostcoords/ui/builders.rb +2 -2
  63. data/lib/lostcoords/ui/form_builder.rb +23 -10
  64. data/lib/lostcoords/ui/stylesheets.rb +25 -0
  65. data/lib/lostcoords/ui/version.rb +1 -1
  66. data/lib/tasks/lostcoords_ui.rake +11 -0
  67. metadata +23 -6
  68. data/config/helper_renames.json +0 -111
  69. data/script/migrate_helpers.rb +0 -136
@@ -1,29 +1,32 @@
1
1
  import { Controller } from "@hotwired/stimulus"
2
+ import { navigate } from "lostcoords/ui/helpers/roving_focus"
2
3
 
3
- // Tabs with automatic activation: arrow keys, Home and End move focus and select.
4
+ // The ARIA tabs pattern. Arrow keys follow the tab list's aria-orientation, and
5
+ // Home and End jump to the ends. With automatic activation, moving focus selects
6
+ // the tab; with manual activation, Enter or Space does.
4
7
  export default class extends Controller {
5
8
  static targets = ["tab", "panel"]
9
+ static values = { activation: { type: String, default: "automatic" } }
6
10
 
7
11
  select(event) {
8
12
  this.show(event.currentTarget)
9
13
  }
10
14
 
11
15
  navigate(event) {
12
- const tabs = this.tabTargets.filter((tab) => !tab.disabled)
13
- const index = tabs.indexOf(event.currentTarget)
14
- const step = getComputedStyle(this.element).direction === "rtl" ? -1 : 1
15
- const next = {
16
- ArrowRight: index + step,
17
- ArrowLeft: index - step,
18
- Home: 0,
19
- End: tabs.length - 1,
20
- }[event.key]
21
- if (next === undefined) return
16
+ const list = event.currentTarget.closest('[role="tablist"]')
17
+ const tab = navigate(event, this.tabTargets, {
18
+ orientation:
19
+ list?.getAttribute("aria-orientation") === "vertical" ? "vertical" : "horizontal",
20
+ wrap: true,
21
+ })
22
+ if (!tab) return
22
23
 
23
- event.preventDefault()
24
- const tab = tabs[(next + tabs.length) % tabs.length]
25
- tab.focus()
26
- this.show(tab)
24
+ if (this.activationValue === "manual") this.focusOnly(tab)
25
+ else this.show(tab)
26
+ }
27
+
28
+ focusOnly(tab) {
29
+ for (const candidate of this.tabTargets) candidate.tabIndex = candidate === tab ? 0 : -1
27
30
  }
28
31
 
29
32
  show(tab) {
@@ -0,0 +1,62 @@
1
+ import { Controller } from "@hotwired/stimulus"
2
+ import { topModalElement } from "lostcoords/ui/helpers/dismiss_stack"
3
+ import { hideTopLayer, showTopLayer, supportsTopLayer } from "lostcoords/ui/helpers/top_layer"
4
+
5
+ // Shows the region in the top layer while it holds toasts, so no sticky header,
6
+ // sheet or dialog paints over them. Each new toast re-opens the region, which
7
+ // moves it above anything opened since. A modal dialog makes the rest of the
8
+ // page inert, so while one is open the region moves inside it, keeping toasts
9
+ // clickable and announced, and moves back when it closes. Without the Popover
10
+ // API the region stays fixed at --lc-z-toast.
11
+ const homes = new WeakMap()
12
+
13
+ export default class extends Controller {
14
+ connect() {
15
+ if (!supportsTopLayer()) return
16
+
17
+ this.observer = new MutationObserver((records) => {
18
+ if (records.some((record) => record.addedNodes.length > 0)) this.raise()
19
+ else if (this.element.childElementCount === 0) this.lower()
20
+ })
21
+ this.observer.observe(this.element, { childList: true })
22
+ if (this.element.childElementCount > 0) this.raise()
23
+ }
24
+
25
+ // A modal removed right after closing (before its close event) takes the
26
+ // region with it; put the region back in the page.
27
+ disconnect() {
28
+ this.observer?.disconnect()
29
+ hideTopLayer(this.element)
30
+ if (!this.element.isConnected) this.goHome()
31
+ }
32
+
33
+ raise() {
34
+ const modal = topModalElement()
35
+ if (modal && !modal.contains(this.element)) return this.moveInto(modal)
36
+
37
+ hideTopLayer(this.element)
38
+ showTopLayer(this.element)
39
+ }
40
+
41
+ lower() {
42
+ hideTopLayer(this.element)
43
+ this.goHome()
44
+ }
45
+
46
+ // Moving the region reconnects this controller, which raises it again.
47
+ moveInto(modal) {
48
+ if (!homes.has(this.element))
49
+ homes.set(this.element, { parent: this.element.parentNode, next: this.element.nextSibling })
50
+ const region = this.element
51
+ modal.addEventListener("close", () => this.goHome(region), { once: true })
52
+ modal.append(region)
53
+ }
54
+
55
+ goHome(region = this.element) {
56
+ const home = homes.get(region)
57
+ if (!home?.parent.isConnected) return
58
+
59
+ homes.delete(region)
60
+ home.parent.insertBefore(region, home.next?.parentNode === home.parent ? home.next : null)
61
+ }
62
+ }
@@ -1,14 +1,54 @@
1
1
  import { Controller } from "@hotwired/stimulus"
2
+ import { registerDismissable } from "lostcoords/ui/helpers/dismiss_stack"
3
+ import { liftToTopLayer, onPageLeave } from "lostcoords/ui/helpers/top_layer"
2
4
 
3
- // Escape hides a visible tooltip without moving the pointer or focus. It shows
4
- // again after the pointer leaves or focus moves away.
5
+ // Opens the tooltip in the top layer, so no stacking context or overflow clip
6
+ // covers it. Without the Popover API it stays in place. Escape closes it before
7
+ // any menu or dialog around it, and it stays hidden until the pointer leaves
8
+ // and focus moves away.
5
9
  export default class extends Controller {
6
- dismiss(event) {
7
- if (event.key !== "Escape" || !this.element.matches(":hover, :focus-within")) return
8
- this.element.dataset.dismissed = ""
10
+ static targets = ["content"]
11
+
12
+ connect() {
13
+ this.stopPageLeave = onPageLeave(() => this.close({ immediate: true }))
14
+ }
15
+
16
+ disconnect() {
17
+ this.stopPageLeave?.()
18
+ this.close({ immediate: true })
19
+ }
20
+
21
+ show(event) {
22
+ if (event.type === "focusin" && !event.target.matches(":focus-visible")) return
23
+ if (this.release || this.element.hasAttribute("data-dismissed")) return
24
+
25
+ this.element.toggleAttribute("data-open", true)
26
+ this.release = liftToTopLayer(this.contentTarget, this.element)
27
+ this.unregister = registerDismissable({
28
+ type: "tooltip",
29
+ element: this.element,
30
+ isOpen: () => this.element.hasAttribute("data-open"),
31
+ close: () => this.dismiss(),
32
+ })
9
33
  }
10
34
 
11
- reset() {
35
+ hide() {
36
+ if (this.element.matches(":hover") || this.element.querySelector(":focus-visible")) return
37
+
12
38
  delete this.element.dataset.dismissed
39
+ this.close()
40
+ }
41
+
42
+ dismiss() {
43
+ this.element.dataset.dismissed = ""
44
+ this.close({ immediate: true })
45
+ }
46
+
47
+ close({ immediate = false } = {}) {
48
+ this.element.toggleAttribute("data-open", false)
49
+ this.release?.({ immediate })
50
+ this.release = null
51
+ this.unregister?.()
52
+ this.unregister = null
13
53
  }
14
54
  }
@@ -1,6 +1,8 @@
1
1
  import { holdDocumentScroll } from "lostcoords/ui/helpers/dismiss_stack"
2
2
  import { FloatingPanel } from "lostcoords/ui/helpers/floating_panel"
3
+ import { navigableItems, navigate, rove } from "lostcoords/ui/helpers/roving_focus"
3
4
  import { SHEET_TIMING, sheetDuration } from "lostcoords/ui/helpers/sheet_motion"
5
+ import { hideTopLayer, showTopLayer, supportsTopLayer } from "lostcoords/ui/helpers/top_layer"
4
6
  import { isSheetViewport } from "lostcoords/ui/helpers/viewport"
5
7
 
6
8
  const catalogs = new Map()
@@ -133,24 +135,14 @@ export class CatalogPicker extends FloatingPanel {
133
135
  }
134
136
 
135
137
  showSheet() {
136
- if (!this.supportsPopover) return
137
-
138
- if (this.popoverTarget.getAttribute("popover") !== "manual") {
138
+ if (this.popoverTarget.getAttribute("popover") !== "manual")
139
139
  this.popoverTarget.setAttribute("popover", "manual")
140
- }
141
- try {
142
- if (!this.popoverTarget.matches(":popover-open")) this.popoverTarget.showPopover()
143
- } catch {}
140
+ showTopLayer(this.popoverTarget)
144
141
  }
145
142
 
146
143
  hideSheet() {
147
- if (this.supportsPopover && this.popoverTarget.matches(":popover-open")) {
148
- try {
149
- this.popoverTarget.hidePopover()
150
- } catch {}
151
- } else {
152
- this.popoverTarget.hidden = true
153
- }
144
+ if (this.supportsPopover) hideTopLayer(this.popoverTarget)
145
+ else this.popoverTarget.hidden = true
154
146
  }
155
147
 
156
148
  // A non-modal popover's ::backdrop doesn't block input, so a tap in the dimmed
@@ -179,13 +171,71 @@ export class CatalogPicker extends FloatingPanel {
179
171
  this.applyFilter(this.searchQuery)
180
172
  }
181
173
 
174
+ // Arrow Down leaves the search for the first option in view; Enter picks
175
+ // the best match.
182
176
  onSearchKeydown(event) {
183
- if (event.key !== "Escape" || !this.searchQuery) return
177
+ if (event.isComposing) return
178
+
179
+ if (event.key === "ArrowDown") {
180
+ const top = this.bodyTarget.getBoundingClientRect().top
181
+ const option = this.gridOptions().find((item) => item.getBoundingClientRect().bottom > top)
182
+ if (!option) return
183
+ event.preventDefault()
184
+ rove(this.allOptions(), option)
185
+ option.focus()
186
+ } else if (event.key === "Enter" && this.searchQuery) {
187
+ const first = this.gridOptions()[0]
188
+ if (!first) return
189
+ event.preventDefault()
190
+ first.click()
191
+ }
192
+ }
193
+
194
+ // The options are one Tab stop. Arrows move through them as a grid that
195
+ // flows in rows, across section breaks; Arrow Up from the top row returns
196
+ // to the search field.
197
+ navigateGrid(event) {
198
+ if (!event.target.matches(this.optionSelector)) return
199
+
200
+ const options = this.gridOptions()
201
+ const option = navigate(event, options, { orientation: "grid", flow: "row" })
202
+ if (option) {
203
+ rove(this.allOptions(), option)
204
+ return
205
+ }
206
+ if (event.key === "ArrowUp" && this.hasSearchInputTarget && !event.defaultPrevented) {
207
+ event.preventDefault()
208
+ this.searchInputTarget.focus()
209
+ }
210
+ }
211
+
212
+ // Keeps the Tab stop on the option focus last landed on.
213
+ trackGridFocus(event) {
214
+ if (event.target.matches?.(this.optionSelector)) rove(this.allOptions(), event.target)
215
+ }
216
+
217
+ syncGridStop() {
218
+ const options = this.allOptions()
219
+ const stop = this.gridStop(options)
220
+ rove(options, stop)
221
+ }
222
+
223
+ gridStop(options = this.allOptions()) {
224
+ const visible = (option) => option.getClientRects().length > 0
225
+ return (
226
+ options.find((option) => option.getAttribute("tabindex") === "0" && visible(option)) ||
227
+ options.find((option) => option.getAttribute("aria-current") === "true" && visible(option)) ||
228
+ options.find(visible) ||
229
+ null
230
+ )
231
+ }
232
+
233
+ gridOptions() {
234
+ return navigableItems(this.allOptions())
235
+ }
184
236
 
185
- event.preventDefault()
186
- event.stopPropagation()
187
- this.searchInputTarget.value = ""
188
- this.applyFilter("")
237
+ allOptions() {
238
+ return [...this.bodyTarget.querySelectorAll(this.optionSelector)]
189
239
  }
190
240
 
191
241
  applyFilter(query) {
@@ -195,6 +245,7 @@ export class CatalogPicker extends FloatingPanel {
195
245
  if (!normalizedQuery) {
196
246
  if (this.hasResultsTarget) this.resultsTarget.hidden = true
197
247
  if (this.hasEmptyTarget) this.emptyTarget.hidden = true
248
+ this.syncGridStop()
198
249
  return
199
250
  }
200
251
 
@@ -216,6 +267,7 @@ export class CatalogPicker extends FloatingPanel {
216
267
  this.resultsTarget.hidden = matches.length === 0
217
268
  if (this.hasEmptyTarget) this.emptyTarget.hidden = matches.length > 0
218
269
  this.bodyTarget.scrollTop = 0
270
+ this.syncGridStop()
219
271
  }
220
272
 
221
273
  score(entry, query) {
@@ -446,7 +498,7 @@ export class CatalogPicker extends FloatingPanel {
446
498
  }
447
499
 
448
500
  get supportsPopover() {
449
- return typeof this.popoverTarget.showPopover === "function"
501
+ return supportsTopLayer()
450
502
  }
451
503
 
452
504
  get searchQuery() {
@@ -47,6 +47,7 @@ export function closeTopDismissable(event) {
47
47
 
48
48
  function dismissOnEscape(event) {
49
49
  if (event.key !== "Escape" && event.key !== "Esc") return
50
+ if (clearSearchField(event)) return
50
51
  if (!closeTopDismissable(event)) return
51
52
 
52
53
  event.preventDefault()
@@ -54,6 +55,21 @@ function dismissOnEscape(event) {
54
55
  event.stopImmediatePropagation()
55
56
  }
56
57
 
58
+ // Escape in a search field that has text clears it, as a native search field
59
+ // does, and only the next Escape closes the panel around it.
60
+ function clearSearchField(event) {
61
+ const field = event.target
62
+ if (!(field instanceof HTMLInputElement) || field.type !== "search" || field.value === "")
63
+ return false
64
+ if (!topDismissable()?.element.contains(field)) return false
65
+
66
+ event.preventDefault()
67
+ event.stopImmediatePropagation()
68
+ field.value = ""
69
+ field.dispatchEvent(new Event("input", { bubbles: true }))
70
+ return true
71
+ }
72
+
57
73
  function cancelDialog(event, dialogEntry) {
58
74
  const entry = topDismissable(dialogEntry.element)
59
75
  if (!entry) return
@@ -84,6 +100,12 @@ function topModal() {
84
100
  .at(-1)
85
101
  }
86
102
 
103
+ // The modal the page is limited to, if any: the top open lc-dialog, or a native
104
+ // modal <dialog> opened without one. Shortcuts and toasts stay inside it.
105
+ export function topModalElement() {
106
+ return topModal()?.element ?? [...document.querySelectorAll("dialog:modal")].at(-1) ?? null
107
+ }
108
+
87
109
  function openEntries() {
88
110
  return stack.filter((entry) => entry.element?.isConnected && entry.isOpen.call(entry))
89
111
  }
@@ -108,6 +130,7 @@ function defaultIsOpen() {
108
130
  }
109
131
 
110
132
  function priorityFor(type) {
133
+ if (type === "tooltip") return 40
111
134
  if (type === "popover") return 30
112
135
  if (type === "panel") return 20
113
136
  return 10
@@ -1,9 +1,8 @@
1
1
  import { Controller } from "@hotwired/stimulus"
2
2
  import { registerDismissable } from "lostcoords/ui/helpers/dismiss_stack"
3
- import { liftToTopLayer } from "lostcoords/ui/helpers/top_layer"
3
+ import { liftToTopLayer, onPageLeave } from "lostcoords/ui/helpers/top_layer"
4
4
 
5
5
  const BEFORE_OPEN = "overlay:before-open"
6
- const PAGE_LEAVES = ["turbo:before-cache", "turbo:before-visit", "turbo:before-render"]
7
6
 
8
7
  export class FloatingPanel extends Controller {
9
8
  static targets = ["trigger", "popover"]
@@ -14,7 +13,9 @@ export class FloatingPanel extends Controller {
14
13
 
15
14
  initialize() {
16
15
  this.closeForOther = (event) => {
17
- if (event.detail?.source !== this) this.close()
16
+ // A panel opened inside this one (a menu in a popover form) keeps it open.
17
+ const source = event.detail?.source
18
+ if (source !== this && !this.element.contains(source?.element)) this.close()
18
19
  }
19
20
  this.closeOnOutsideClick = (event) => {
20
21
  if (!this.element.contains(event.target)) this.close()
@@ -24,14 +25,12 @@ export class FloatingPanel extends Controller {
24
25
 
25
26
  connect() {
26
27
  document.addEventListener(BEFORE_OPEN, this.closeForOther)
27
- for (const type of PAGE_LEAVES) document.addEventListener(type, this.closeForPageLeave)
28
- window.addEventListener("pagehide", this.closeForPageLeave)
28
+ this.stopPageLeave = onPageLeave(this.closeForPageLeave)
29
29
  }
30
30
 
31
31
  disconnect() {
32
32
  document.removeEventListener(BEFORE_OPEN, this.closeForOther)
33
- for (const type of PAGE_LEAVES) document.removeEventListener(type, this.closeForPageLeave)
34
- window.removeEventListener("pagehide", this.closeForPageLeave)
33
+ this.stopPageLeave?.()
35
34
  this.release({ immediate: true })
36
35
  }
37
36
 
@@ -1,27 +1,28 @@
1
- const ITEMS = '[role^="menuitem"]:not([disabled]):not([aria-disabled="true"])'
1
+ import { navigableItems, navigate } from "lostcoords/ui/helpers/roving_focus"
2
2
 
3
- function items(menu) {
4
- return [...menu.querySelectorAll(ITEMS)].filter((item) => item.getClientRects().length > 0)
3
+ const ITEMS = '[role^="menuitem"]'
4
+
5
+ export function menuItems(menu) {
6
+ return navigableItems(menu.querySelectorAll(ITEMS))
5
7
  }
6
8
 
7
9
  export function focusFirstMenuItem(menu) {
8
- items(menu)[0]?.focus()
10
+ menuItems(menu)[0]?.focus()
9
11
  }
10
12
 
11
- // The ARIA menu pattern: arrows move between items and wrap, Home/End jump.
12
- export function navigateMenu(event, menu) {
13
- const list = items(menu)
14
- if (list.length === 0) return
13
+ export function focusLastMenuItem(menu) {
14
+ menuItems(menu).at(-1)?.focus()
15
+ }
15
16
 
16
- const index = list.indexOf(document.activeElement)
17
- const next = {
18
- ArrowDown: (index + 1) % list.length,
19
- ArrowUp: (index - 1 + list.length) % list.length,
20
- Home: 0,
21
- End: list.length - 1,
22
- }[event.key]
23
- if (next === undefined) return
17
+ // The ARIA menu pattern: arrows move between items and wrap, Home/End jump,
18
+ // typing a letter jumps to the next item that starts with it, and Space
19
+ // activates a link item as Enter does.
20
+ export function navigateMenu(event, menu, { orientation = "vertical" } = {}) {
21
+ if (event.key === " " && event.target.matches(`a${ITEMS}`)) {
22
+ event.preventDefault()
23
+ event.target.click()
24
+ return
25
+ }
24
26
 
25
- event.preventDefault()
26
- list[next].focus()
27
+ navigate(event, menuItems(menu), { orientation, wrap: true, typeahead: true })
27
28
  }
@@ -0,0 +1,175 @@
1
+ // Arrow-key navigation shared by every list, toolbar and grid in the library.
2
+ //
3
+ // orientation:
4
+ // "vertical" ArrowUp/ArrowDown move through the items in order.
5
+ // "horizontal" ArrowLeft/ArrowRight do, flipped in right-to-left text.
6
+ // "both" All four arrows do, for toolbars that wrap onto two lines.
7
+ // "grid" Items laid out in rows (flow: "row") or columns (flow: "column").
8
+ // Arrows along the flow move in order; arrows across it move to
9
+ // the nearest item in the next row or column, by position on screen.
10
+ // wrap: the ends lead back round to the other end. Grids never wrap.
11
+ // typeahead: typing a letter moves to the next item whose label starts with it.
12
+ //
13
+ // navigate() moves focus and returns the item it moved to, or null when the key
14
+ // is not one it handles. rove() keeps a single Tab stop on the current item.
15
+
16
+ const TYPEAHEAD_RESET = 500
17
+ const typeaheads = new WeakMap()
18
+
19
+ export function navigableItems(items) {
20
+ return [...items].filter(
21
+ (item) =>
22
+ !item.disabled &&
23
+ item.getAttribute("aria-disabled") !== "true" &&
24
+ !item.closest("[inert]") &&
25
+ item.getClientRects().length > 0,
26
+ )
27
+ }
28
+
29
+ export function rove(items, current) {
30
+ for (const item of items) item.tabIndex = item === current ? 0 : -1
31
+ }
32
+
33
+ export function navigate(
34
+ event,
35
+ items,
36
+ {
37
+ orientation = "vertical",
38
+ flow = "row",
39
+ wrap = orientation !== "grid",
40
+ typeahead = false,
41
+ label = defaultLabel,
42
+ focus = true,
43
+ } = {},
44
+ ) {
45
+ if (event.defaultPrevented || event.isComposing || event.altKey || event.metaKey) return null
46
+
47
+ const list = navigableItems(items)
48
+ if (list.length === 0) return null
49
+
50
+ const index = list.findIndex((item) => item === event.target || item.contains(event.target))
51
+ const editing = isEditable(event.target)
52
+ let target = null
53
+
54
+ if (event.key === "Home" || event.key === "End") {
55
+ if (editing) return null
56
+ if (event.ctrlKey && orientation !== "grid") return null
57
+ target = event.key === "Home" ? list[0] : list.at(-1)
58
+ } else if (event.key.startsWith("Arrow")) {
59
+ if (event.ctrlKey) return null
60
+ if (editing && (event.key === "ArrowLeft" || event.key === "ArrowRight")) return null
61
+ target = arrowTarget(event.key, list, index, {
62
+ orientation,
63
+ flow,
64
+ wrap,
65
+ rtl: isRtl(event.target),
66
+ })
67
+ } else if (typeahead && !editing && !event.ctrlKey) {
68
+ target = typeaheadTarget(event.key, list, index, label)
69
+ }
70
+
71
+ if (!target) return null
72
+ event.preventDefault()
73
+ if (focus) target.focus()
74
+ return target
75
+ }
76
+
77
+ function arrowTarget(key, list, index, { orientation, flow, wrap, rtl }) {
78
+ const vertical = key === "ArrowUp" || key === "ArrowDown"
79
+ const forward = key === "ArrowDown" || key === (rtl ? "ArrowLeft" : "ArrowRight")
80
+
81
+ if (orientation === "vertical" && !vertical) return null
82
+ if (orientation === "horizontal" && vertical) return null
83
+ if (orientation === "grid" && vertical !== (flow === "column")) {
84
+ return index < 0 ? list[0] : nearestAcross(list, list[index], key)
85
+ }
86
+
87
+ if (index < 0) return forward ? list[0] : list.at(-1)
88
+ const next = index + (forward ? 1 : -1)
89
+ if (next >= 0 && next < list.length) return list[next]
90
+ if (!wrap) return null
91
+ return list[(next + list.length) % list.length]
92
+ }
93
+
94
+ // The nearest row (or column) in the arrow's direction first, then the item in
95
+ // it closest to the current one, so a short last row still has a landing spot.
96
+ function nearestAcross(list, from, key) {
97
+ const vertical = key === "ArrowUp" || key === "ArrowDown"
98
+ const sign = key === "ArrowDown" || key === "ArrowRight" ? 1 : -1
99
+ const origin = centre(from.getBoundingClientRect())
100
+ const reach = (vertical ? from.offsetHeight : from.offsetWidth) / 2
101
+
102
+ const ahead = []
103
+ for (const item of list) {
104
+ if (item === from) continue
105
+ const point = centre(item.getBoundingClientRect())
106
+ const along = (vertical ? point.y - origin.y : point.x - origin.x) * sign
107
+ if (along < reach) continue
108
+ ahead.push({
109
+ item,
110
+ along,
111
+ across: Math.abs(vertical ? point.x - origin.x : point.y - origin.y),
112
+ })
113
+ }
114
+ if (ahead.length === 0) return null
115
+
116
+ const line = Math.min(...ahead.map((candidate) => candidate.along)) + reach
117
+ const sameLine = ahead.filter((candidate) => candidate.along <= line)
118
+ return sameLine.reduce((best, candidate) => (candidate.across < best.across ? candidate : best))
119
+ .item
120
+ }
121
+
122
+ // Repeating one letter cycles through the items that start with it; typing a
123
+ // word quickly matches the whole prefix.
124
+ function typeaheadTarget(key, list, index, label) {
125
+ if (key.length !== 1) return null
126
+
127
+ const state = typeaheads.get(list[0].parentElement) ?? { text: "", timer: null }
128
+ if (key === " " && state.text === "") return null
129
+
130
+ clearTimeout(state.timer)
131
+ state.text += key.toLocaleLowerCase()
132
+ state.timer = setTimeout(() => {
133
+ state.text = ""
134
+ }, TYPEAHEAD_RESET)
135
+ typeaheads.set(list[0].parentElement, state)
136
+
137
+ const repeated = [...state.text].every((letter) => letter === state.text[0])
138
+ const query = repeated ? state.text[0] : state.text
139
+ const start = repeated ? index + 1 : Math.max(index, 0)
140
+ for (let offset = 0; offset < list.length; offset++) {
141
+ const item = list[(start + offset) % list.length]
142
+ if (label(item).startsWith(query)) return item
143
+ }
144
+ return null
145
+ }
146
+
147
+ function defaultLabel(item) {
148
+ return (item.getAttribute("aria-label") || item.textContent).trim().toLocaleLowerCase()
149
+ }
150
+
151
+ function centre(rect) {
152
+ return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }
153
+ }
154
+
155
+ function isRtl(element) {
156
+ return getComputedStyle(element).direction === "rtl"
157
+ }
158
+
159
+ export function isEditable(element) {
160
+ if (!(element instanceof Element)) return false
161
+ if (element.isContentEditable || element.tagName === "TEXTAREA" || element.tagName === "SELECT")
162
+ return true
163
+ if (element.tagName !== "INPUT") return false
164
+ return ![
165
+ "button",
166
+ "checkbox",
167
+ "radio",
168
+ "range",
169
+ "reset",
170
+ "submit",
171
+ "color",
172
+ "file",
173
+ "image",
174
+ ].includes(element.type)
175
+ }