openproject-primer_view_components 0.95.0 → 0.96.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 (176) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +18 -0
  3. data/app/assets/javascripts/primer_view_components.js +11 -1
  4. data/app/assets/javascripts/primer_view_components.js.map +1 -1
  5. data/app/assets/styles/primer_view_components.css +1 -1
  6. data/app/assets/styles/primer_view_components.css.map +1 -1
  7. data/app/components/primer/alpha/action_bar.css +1 -1
  8. data/app/components/primer/alpha/action_bar.css.map +1 -1
  9. data/app/components/primer/alpha/action_list/item.rb +5 -1
  10. data/app/components/primer/alpha/action_list.css +1 -1
  11. data/app/components/primer/alpha/action_list.css.json +13 -11
  12. data/app/components/primer/alpha/action_list.css.map +1 -1
  13. data/app/components/primer/alpha/action_list.pcss +12 -0
  14. data/app/components/primer/alpha/action_menu/action_menu_element.d.ts +6 -0
  15. data/app/components/primer/alpha/action_menu/action_menu_element.js +389 -84
  16. data/app/components/primer/alpha/action_menu/action_menu_element.ts +439 -78
  17. data/app/components/primer/alpha/action_menu/action_menu_focus_zone_stack.d.ts +4 -1
  18. data/app/components/primer/alpha/action_menu/action_menu_focus_zone_stack.js +37 -13
  19. data/app/components/primer/alpha/action_menu/action_menu_focus_zone_stack.ts +41 -12
  20. data/app/components/primer/alpha/action_menu/menu.html.erb +27 -19
  21. data/app/components/primer/alpha/action_menu/menu.rb +7 -0
  22. data/app/components/primer/alpha/action_menu/primary_menu.rb +15 -0
  23. data/app/components/primer/alpha/action_menu.rb +55 -0
  24. data/app/components/primer/alpha/auto_complete.css +1 -1
  25. data/app/components/primer/alpha/auto_complete.css.map +1 -1
  26. data/app/components/primer/alpha/banner.css +1 -1
  27. data/app/components/primer/alpha/banner.css.map +1 -1
  28. data/app/components/primer/alpha/button_marketing.css +1 -1
  29. data/app/components/primer/alpha/button_marketing.css.map +1 -1
  30. data/app/components/primer/alpha/dialog.css +1 -1
  31. data/app/components/primer/alpha/dialog.css.map +1 -1
  32. data/app/components/primer/alpha/dropdown/menu.rb +1 -1
  33. data/app/components/primer/alpha/dropdown.css +1 -1
  34. data/app/components/primer/alpha/dropdown.css.json +1 -1
  35. data/app/components/primer/alpha/dropdown.css.map +1 -1
  36. data/app/components/primer/alpha/layout.css +1 -1
  37. data/app/components/primer/alpha/layout.css.json +3 -3
  38. data/app/components/primer/alpha/layout.css.map +1 -1
  39. data/app/components/primer/alpha/menu.css +1 -1
  40. data/app/components/primer/alpha/menu.css.json +3 -3
  41. data/app/components/primer/alpha/menu.css.map +1 -1
  42. data/app/components/primer/alpha/overlay.css +1 -1
  43. data/app/components/primer/alpha/overlay.css.map +1 -1
  44. data/app/components/primer/alpha/segmented_control.css +1 -1
  45. data/app/components/primer/alpha/segmented_control.css.json +1 -1
  46. data/app/components/primer/alpha/segmented_control.css.map +1 -1
  47. data/app/components/primer/alpha/select_panel.css +1 -1
  48. data/app/components/primer/alpha/select_panel.css.map +1 -1
  49. data/app/components/primer/alpha/skeleton_box.css +1 -1
  50. data/app/components/primer/alpha/skeleton_box.css.map +1 -1
  51. data/app/components/primer/alpha/stack.css +1 -1
  52. data/app/components/primer/alpha/stack.css.map +1 -1
  53. data/app/components/primer/alpha/stack_item.css +1 -1
  54. data/app/components/primer/alpha/stack_item.css.map +1 -1
  55. data/app/components/primer/alpha/tab_nav.css +1 -1
  56. data/app/components/primer/alpha/tab_nav.css.map +1 -1
  57. data/app/components/primer/alpha/text_field.css +1 -1
  58. data/app/components/primer/alpha/text_field.css.map +1 -1
  59. data/app/components/primer/alpha/toggle_switch.css +1 -1
  60. data/app/components/primer/alpha/toggle_switch.css.map +1 -1
  61. data/app/components/primer/alpha/tree_view.css +1 -1
  62. data/app/components/primer/alpha/tree_view.css.json +3 -3
  63. data/app/components/primer/alpha/tree_view.css.map +1 -1
  64. data/app/components/primer/alpha/underline_nav.css +1 -1
  65. data/app/components/primer/alpha/underline_nav.css.map +1 -1
  66. data/app/components/primer/beta/border_box.css +1 -1
  67. data/app/components/primer/beta/border_box.css.json +5 -5
  68. data/app/components/primer/beta/border_box.css.map +1 -1
  69. data/app/components/primer/beta/button.css +1 -1
  70. data/app/components/primer/beta/button.css.map +1 -1
  71. data/app/components/primer/beta/button.pcss +97 -0
  72. data/app/components/primer/beta/button.rb +15 -3
  73. data/app/components/primer/beta/counter.css +1 -1
  74. data/app/components/primer/beta/counter.css.map +1 -1
  75. data/app/components/primer/beta/flash.css +1 -1
  76. data/app/components/primer/beta/flash.css.map +1 -1
  77. data/app/components/primer/beta/link.css +1 -1
  78. data/app/components/primer/beta/link.css.json +1 -1
  79. data/app/components/primer/beta/link.css.map +1 -1
  80. data/app/components/primer/beta/popover.css +1 -1
  81. data/app/components/primer/beta/popover.css.map +1 -1
  82. data/app/components/primer/beta/progress_bar.css +1 -1
  83. data/app/components/primer/beta/progress_bar.css.map +1 -1
  84. data/app/components/primer/beta/relative_time.rb +7 -1
  85. data/app/components/primer/beta/state.css +1 -1
  86. data/app/components/primer/beta/state.css.json +2 -2
  87. data/app/components/primer/beta/state.css.map +1 -1
  88. data/app/components/primer/beta/timeline_item.css +1 -1
  89. data/app/components/primer/beta/timeline_item.css.map +1 -1
  90. data/app/components/primer/open_project/border_grid.css +1 -1
  91. data/app/components/primer/open_project/border_grid.css.map +1 -1
  92. data/app/components/primer/open_project/color_field.css +1 -1
  93. data/app/components/primer/open_project/color_field.css.map +1 -1
  94. data/app/components/primer/open_project/inline_message.css +1 -1
  95. data/app/components/primer/open_project/inline_message.css.map +1 -1
  96. data/app/components/primer/open_project/input_group.css +1 -1
  97. data/app/components/primer/open_project/input_group.css.map +1 -1
  98. data/app/components/primer/open_project/keybinding_hint/chords.d.ts +5 -0
  99. data/app/components/primer/open_project/keybinding_hint/chords.js +29 -0
  100. data/app/components/primer/open_project/keybinding_hint/chords.ts +38 -0
  101. data/app/components/primer/open_project/keybinding_hint/key_names.d.ts +16 -0
  102. data/app/components/primer/open_project/keybinding_hint/key_names.js +107 -0
  103. data/app/components/primer/open_project/keybinding_hint/key_names.ts +116 -0
  104. data/app/components/primer/open_project/keybinding_hint/localized_names.d.ts +22 -0
  105. data/app/components/primer/open_project/keybinding_hint/localized_names.js +47 -0
  106. data/app/components/primer/open_project/keybinding_hint/localized_names.ts +71 -0
  107. data/app/components/primer/open_project/keybinding_hint/names.rb +92 -0
  108. data/app/components/primer/open_project/keybinding_hint/names_from_scope.d.ts +21 -0
  109. data/app/components/primer/open_project/keybinding_hint/names_from_scope.js +81 -0
  110. data/app/components/primer/open_project/keybinding_hint/names_from_scope.ts +96 -0
  111. data/app/components/primer/open_project/keybinding_hint/platform.d.ts +10 -0
  112. data/app/components/primer/open_project/keybinding_hint/platform.js +24 -0
  113. data/app/components/primer/open_project/keybinding_hint/platform.ts +34 -0
  114. data/app/components/primer/open_project/keybinding_hint/platform_override.d.ts +2 -0
  115. data/app/components/primer/open_project/keybinding_hint/platform_override.js +4 -0
  116. data/app/components/primer/open_project/keybinding_hint/platform_override.ts +7 -0
  117. data/app/components/primer/open_project/keybinding_hint.css +1 -0
  118. data/app/components/primer/open_project/keybinding_hint.css.json +10 -0
  119. data/app/components/primer/open_project/keybinding_hint.css.map +1 -0
  120. data/app/components/primer/open_project/keybinding_hint.html.erb +4 -0
  121. data/app/components/primer/open_project/keybinding_hint.pcss +65 -0
  122. data/app/components/primer/open_project/keybinding_hint.rb +112 -0
  123. data/app/components/primer/open_project/keybinding_hint_element.d.ts +31 -0
  124. data/app/components/primer/open_project/keybinding_hint_element.js +183 -0
  125. data/app/components/primer/open_project/keybinding_hint_element.ts +152 -0
  126. data/app/components/primer/open_project/page_header.css +1 -1
  127. data/app/components/primer/open_project/page_header.css.json +2 -2
  128. data/app/components/primer/open_project/page_header.css.map +1 -1
  129. data/app/components/primer/open_project/pagination.css +1 -1
  130. data/app/components/primer/open_project/pagination.css.json +1 -1
  131. data/app/components/primer/open_project/pagination.css.map +1 -1
  132. data/app/components/primer/open_project/sub_header.css +1 -1
  133. data/app/components/primer/open_project/sub_header.css.map +1 -1
  134. data/app/components/primer/primer.d.ts +1 -0
  135. data/app/components/primer/primer.js +1 -0
  136. data/app/components/primer/primer.pcss +1 -0
  137. data/app/components/primer/primer.ts +1 -0
  138. data/app/components/primer/truncate.css +1 -1
  139. data/app/components/primer/truncate.css.json +3 -4
  140. data/app/components/primer/truncate.css.map +1 -1
  141. data/app/controllers/primer/view_components/action_menu_controller.rb +35 -0
  142. data/app/views/primer/view_components/action_menu/deferred.html.erb +25 -11
  143. data/app/views/primer/view_components/action_menu/deferred_form.html.erb +10 -0
  144. data/app/views/primer/view_components/action_menu/deferred_preload.html.erb +7 -1
  145. data/config/locales/en.yml +179 -0
  146. data/config/routes.rb +1 -0
  147. data/lib/primer/accessibility.rb +1 -2
  148. data/lib/primer/classify.rb +1 -2
  149. data/lib/primer/view_components/version.rb +1 -1
  150. data/previews/primer/alpha/action_menu_preview/deferred_refresh.html.erb +34 -0
  151. data/previews/primer/alpha/action_menu_preview/deferred_refresh_form.html.erb +9 -0
  152. data/previews/primer/alpha/action_menu_preview.rb +14 -0
  153. data/previews/primer/open_project/keybinding_hint_preview/full_format.html.erb +3 -0
  154. data/previews/primer/open_project/keybinding_hint_preview/in_action_list.html.erb +12 -0
  155. data/previews/primer/open_project/keybinding_hint_preview/in_button.html.erb +24 -0
  156. data/previews/primer/open_project/keybinding_hint_preview/platforms.html.erb +8 -0
  157. data/previews/primer/open_project/keybinding_hint_preview/playground.html.erb +4 -0
  158. data/previews/primer/open_project/keybinding_hint_preview/prose.html.erb +3 -0
  159. data/previews/primer/open_project/keybinding_hint_preview/schemes.html.erb +6 -0
  160. data/previews/primer/open_project/keybinding_hint_preview/sequence.html.erb +1 -0
  161. data/previews/primer/open_project/keybinding_hint_preview/sizes.html.erb +4 -0
  162. data/previews/primer/open_project/keybinding_hint_preview.rb +71 -0
  163. data/static/arguments.json +53 -1
  164. data/static/audited_at.json +1 -0
  165. data/static/classes.json +12 -0
  166. data/static/classnames.cjs +4 -0
  167. data/static/classnames.js +4 -0
  168. data/static/constants.json +35 -0
  169. data/static/info_arch.json +234 -8
  170. data/static/previews.json +164 -0
  171. data/static/statuses.json +1 -0
  172. metadata +42 -5
  173. data/app/components/primer/alpha/text_field.css.json +0 -134
  174. data/app/components/primer/alpha/toggle_switch.css.json +0 -40
  175. data/app/components/primer/alpha/underline_nav.css.json +0 -26
  176. data/app/components/primer/beta/button.css.json +0 -86
@@ -13,11 +13,15 @@ type SelectedItem = {
13
13
  element: Element
14
14
  }
15
15
 
16
+ type LoaderRequest = Readonly<{loader: IncludeFragmentElement; src: string}>
17
+
16
18
  @controller('action-menu')
17
19
  export class ActionMenuElement extends HTMLElement {
18
20
  @target includeFragment: IncludeFragmentElement
19
21
  @target overlay: AnchoredPositionElement
20
22
  @target list: HTMLElement
23
+ @target overlayBody: HTMLElement | undefined
24
+ @target loaderTemplate: HTMLTemplateElement | undefined
21
25
 
22
26
  #abortController: AbortController
23
27
  #originalLabel = ''
@@ -26,6 +30,60 @@ export class ActionMenuElement extends HTMLElement {
26
30
  #intersectionObserver: IntersectionObserver
27
31
  #focusZoneStack: ActionMenuFocusZoneStack
28
32
 
33
+ // The current request of a deferred primary menu: the loader it was made
34
+ // with and the src it was made for. Never updated; a new request replaces it.
35
+ // The src is recorded because the loader's attribute is configuration a
36
+ // morph may rewrite while the request is in flight; the record is what was
37
+ // requested, so a rewritten loader cannot pass an old response off as new.
38
+ #request: LoaderRequest | null = null
39
+ // Every primary loader this element created or adopted, so completions of
40
+ // superseded ones can be told apart from sub-menu fragments.
41
+ #ownedLoaders = new WeakSet<IncludeFragmentElement>()
42
+ // Loaders whose response had no menu items, with the body they left
43
+ // empty. That body staying empty is not a reason to load again before the
44
+ // next open; a body other code puts in its place is.
45
+ #emptyLoaders = new WeakMap<IncludeFragmentElement, HTMLElement>()
46
+
47
+ #scrollUpdater = () => {
48
+ if (this.#isOpen()) {
49
+ this.overlay?.update()
50
+ }
51
+ }
52
+
53
+ constructor() {
54
+ super()
55
+
56
+ // Never disconnected: it observes the element's own subtree, so it keeps
57
+ // working while the element is detached. A local, not a field: the
58
+ // registration keeps it alive as long as the element is.
59
+ const observer = new MutationObserver(records => {
60
+ this.#onBodyMutation(records)
61
+ this.#updateLevels()
62
+ })
63
+ observer.observe(this, {childList: true, subtree: true})
64
+
65
+ this.#focusZoneStack = new ActionMenuFocusZoneStack()
66
+
67
+ // The code below updates the menu (i.e. overlay) position whenever the invoker button
68
+ // changes position within its scroll container.
69
+ //
70
+ // See: https://github.com/primer/view_components/issues/3175
71
+ this.#intersectionObserver = new IntersectionObserver(entries => {
72
+ for (const entry of entries) {
73
+ if (entry.target !== this.invokerElement) continue
74
+
75
+ if (entry.isIntersecting) {
76
+ // eslint-disable-next-line github/prefer-observers
77
+ window.addEventListener('scroll', this.#scrollUpdater, {capture: true})
78
+ } else {
79
+ window.removeEventListener('scroll', this.#scrollUpdater, {capture: true})
80
+ }
81
+ }
82
+ })
83
+ }
84
+
85
+ static observedAttributes = ['src']
86
+
29
87
  static validItemRoles = ['menuitem', 'menuitemcheckbox', 'menuitemradio']
30
88
  static validSelectors = ActionMenuElement.validItemRoles.map(role => `[role="${role}"]`)
31
89
  static menuItemSelectors = ActionMenuElement.validSelectors.map(selector => `:not([hidden]) > ${selector}`)
@@ -71,13 +129,12 @@ export class ActionMenuElement extends HTMLElement {
71
129
 
72
130
  get invokerElement(): HTMLButtonElement | null {
73
131
  const id = this.querySelector('[role=menu]')?.id
74
- if (!id) return null
75
- for (const el of this.querySelectorAll(`[aria-controls]`)) {
76
- if (el.getAttribute('aria-controls') === id) {
77
- return el as HTMLButtonElement
78
- }
132
+ if (id) {
133
+ const el = this.querySelector<HTMLButtonElement>(`[aria-controls="${CSS.escape(id)}"]`)
134
+ if (el) return el
79
135
  }
80
- return null
136
+ const overlayId = this.overlay?.id
137
+ return overlayId ? this.querySelector<HTMLButtonElement>(`[popovertarget="${CSS.escape(overlayId)}"]`) : null
81
138
  }
82
139
 
83
140
  get invokerLabel(): HTMLElement | null {
@@ -103,79 +160,290 @@ export class ActionMenuElement extends HTMLElement {
103
160
  }
104
161
 
105
162
  connectedCallback() {
163
+ this.#bindHostListeners()
164
+ this.#setDynamicLabel()
165
+ this.#updateInput()
166
+ this.#softDisableItems()
167
+ this.#setupSubMenuLoading()
168
+ this.#sync()
169
+ this.#observeInvokerPosition()
170
+
171
+ if (this.#noLoadPending()) {
172
+ this.setAttribute('data-ready', 'true')
173
+ }
174
+
175
+ this.#updateLevels()
176
+ }
177
+
178
+ disconnectedCallback() {
179
+ this.#abortController.abort()
180
+ this.#focusZoneStack.clear()
181
+ this.#intersectionObserver.disconnect()
182
+ window.removeEventListener('scroll', this.#scrollUpdater, {capture: true})
183
+ }
184
+
185
+ attributeChangedCallback(name: string) {
186
+ if (name === 'src') this.#sync()
187
+ }
188
+
189
+ // Forgets the current request so the menu loads again at the current src:
190
+ // at once when open or preloaded, otherwise when it next opens.
191
+ refresh() {
192
+ this.#invalidate()
193
+ this.#sync()
194
+ }
195
+
196
+ #bindHostListeners() {
106
197
  const {signal} = (this.#abortController = new AbortController())
107
198
  this.addEventListener('keydown', this, {signal})
108
199
  this.addEventListener('click', this, {signal})
109
200
  this.addEventListener('mouseover', this, {signal})
110
201
  this.addEventListener('focusout', this, {signal})
111
202
  this.addEventListener('mousedown', this, {signal})
203
+ this.addEventListener('beforetoggle', this, {signal, capture: true})
112
204
  this.addEventListener('toggle', this, {signal, capture: true})
113
- this.#setDynamicLabel()
114
- this.#updateInput()
115
- this.#softDisableItems()
116
-
117
- if (this.includeFragment) {
118
- this.includeFragment.addEventListener('include-fragment-replaced', this, {
119
- signal,
120
- })
121
- }
122
-
123
- // The code below updates the menu (i.e. overlay) position whenever the invoker button
124
- // changes position within its scroll container.
125
- //
126
- // See: https://github.com/primer/view_components/issues/3175
205
+ }
127
206
 
128
- const scrollUpdater = () => {
129
- if (this.#isOpen()) {
130
- this.overlay?.update()
131
- }
132
- }
207
+ // A static primary menu with a deferred sub-menu
208
+ #setupSubMenuLoading() {
209
+ if (this.#deferred || !this.includeFragment) return
133
210
 
134
- this.#intersectionObserver = new IntersectionObserver(entries => {
135
- for (const entry of entries) {
136
- const elem = entry.target
137
- if (elem === this.invokerElement) {
138
- if (entry.isIntersecting) {
139
- // eslint-disable-next-line github/prefer-observers
140
- window.addEventListener('scroll', scrollUpdater, {capture: true})
141
- } else {
142
- window.removeEventListener('scroll', scrollUpdater, {capture: true})
143
- }
144
- }
145
- }
211
+ this.includeFragment.addEventListener('include-fragment-replaced', this, {
212
+ signal: this.#abortController.signal,
146
213
  })
214
+ }
147
215
 
216
+ #observeInvokerPosition() {
148
217
  observeMutationsUntilConditionMet(
149
218
  this,
150
219
  () => Boolean(this.invokerElement),
151
220
  () => this.#intersectionObserver.observe(this.invokerElement!),
152
221
  )
222
+ }
223
+
224
+ #updateLevels() {
225
+ for (const [index, menu] of this.querySelectorAll('[role=menu]').entries()) {
226
+ menu.setAttribute('data-level', String(index + 1))
227
+ }
228
+ }
229
+
230
+ // A primary menu with `src` renders its loader as a template
231
+ get #deferred(): boolean {
232
+ return Boolean(this.loaderTemplate)
233
+ }
234
+
235
+ get #preload(): boolean {
236
+ return this.loaderTemplate?.content.firstElementChild?.getAttribute('loading') === 'eager'
237
+ }
238
+
239
+ // The primary overlay's body. Looked up on every call, since other code may
240
+ // replace the body or the overlay.
241
+ get #body(): HTMLElement | null {
242
+ return this.overlayBody ?? null
243
+ }
244
+
245
+ // The one rule: a load starts when there is no current request, when the
246
+ // host src differs from the current request's, or when the body holds no
247
+ // element (other code emptied it, or the last response was empty); the
248
+ // current loader still in the body is retried. A closed lazy menu waits
249
+ // for the open moment (`opening`) instead.
250
+ #sync(opening = false) {
251
+ const src = (this.getAttribute('src') ?? '').trim()
252
+ if (!this.#deferred || !src) return
253
+
254
+ if (!(opening || this.#isOpen() || this.#preload)) {
255
+ // A pending or failed loader for another src must not render meanwhile;
256
+ // a completed one is kept, so setting its src again does not reload
257
+ if (this.#request && src !== this.#request.src && this.#request.loader.parentElement === this.#body) {
258
+ this.#invalidate()
259
+ }
260
+ return
261
+ }
153
262
 
154
- // If there's no include fragment, then no async fetching will occur and we can
155
- // mark the component as ready.
156
- if (!this.includeFragment) {
263
+ const loader = this.#request?.loader
264
+ if (!this.#request || src !== this.#request.src || !this.#body?.firstElementChild) {
265
+ this.#load(src, opening)
266
+ } else if (loader?.isConnected) {
267
+ // A retry fetches the loader's own src, which a morph may have rewritten
268
+ if ((loader.getAttribute('src') ?? '').trim() === this.#request.src) {
269
+ loader.classList.remove('is-error')
270
+ loader.refetch()
271
+ } else {
272
+ this.#load(src, opening)
273
+ }
274
+ }
275
+ }
276
+
277
+ // Drops the current request. Its loader is removed even while the menu is
278
+ // detached, since upstream still completes the fetch there.
279
+ #invalidate() {
280
+ this.#request?.loader.remove()
281
+ this.#request = null
282
+ this.#updateReady()
283
+ }
284
+
285
+ // Starts a request for src with a fresh loader from the template, which
286
+ // replaces whatever the body holds.
287
+ #load(src: string, opening = false) {
288
+ const body = this.#body
289
+ const template = this.loaderTemplate?.content.firstElementChild
290
+ if (!body || !template) return
291
+
292
+ // Imported, not cloned, so the loader is upgraded before it connects
293
+ const loader = this.ownerDocument.importNode(template, true) as IncludeFragmentElement
294
+ loader.setAttribute('src', src)
295
+ loader.setAttribute('loading', 'eager')
296
+
297
+ this.#request = {loader, src}
298
+ this.#ownedLoaders.add(loader)
299
+ this.#listen(loader)
300
+ // The response decides the form field name
301
+ this.#inputName = ''
302
+ this.#keepInputs(body)
303
+
304
+ body.prepend(loader)
305
+ if (opening || this.#isOpen()) {
306
+ this.#keepOpenWhileLoading(loader)
307
+ // A focus handler may have started a newer load meanwhile
308
+ if (this.#request?.loader !== loader) return
309
+ }
310
+
311
+ for (const child of Array.from(body.childNodes)) {
312
+ if (child !== loader) child.remove()
313
+ }
314
+
315
+ this.#updateReady()
316
+ }
317
+
318
+ // Keeps the current form inputs submitting while a load replaces the body,
319
+ // also when it fails: they move to the host until a response brings its own
320
+ #keepInputs(body: HTMLElement) {
321
+ const inputs = body.querySelector('[data-list-inputs]')
322
+ if (!inputs) return
323
+
324
+ this.#dropKeptInputs()
325
+ this.append(inputs)
326
+ }
327
+
328
+ #dropKeptInputs() {
329
+ for (const inputs of this.querySelectorAll(':scope > [data-list-inputs]')) inputs.remove()
330
+ }
331
+
332
+ // Loaders are never reused, so the listeners need no lifetime of their own
333
+ #listen(fragment: IncludeFragmentElement) {
334
+ fragment.addEventListener('include-fragment-replace', this)
335
+ fragment.addEventListener('include-fragment-replaced', this)
336
+ }
337
+
338
+ // No primary loader still waiting in the body and, for a static menu, no
339
+ // sub-menu fragment. A deferred menu's sub-menus load when they open.
340
+ #noLoadPending(): boolean {
341
+ if (!this.#deferred && this.includeFragment?.isConnected) return false
342
+
343
+ const loader = this.#request?.loader
344
+ return !loader || loader.parentElement !== this.#body
345
+ }
346
+
347
+ // `data-ready` means no load is pending
348
+ #updateReady() {
349
+ if (this.#noLoadPending()) {
157
350
  this.setAttribute('data-ready', 'true')
351
+ } else {
352
+ this.removeAttribute('data-ready')
158
353
  }
354
+ }
159
355
 
160
- const levelObserver = new MutationObserver(() => this.#updateLevels())
161
- levelObserver.observe(this, {childList: true, subtree: true})
356
+ // Picks up loaders other code inserts into the body (the last one wins, so
357
+ // a loader appended next to a pending one supersedes it), and loads again
358
+ // when other code empties the body, such as a morph of the server markup,
359
+ // which renders the body empty.
360
+ #onBodyMutation(records: MutationRecord[]) {
361
+ // A replaced overlay may have taken open sub-menus with it
362
+ this.#pruneFocusZones()
363
+
364
+ if (!this.#deferred) return
365
+
366
+ const body = this.#body
367
+ if (!body) return
368
+
369
+ if (records.some(record => record.addedNodes.length > 0)) {
370
+ const fragments = Array.from(body.querySelectorAll<IncludeFragmentElement>(':scope > include-fragment')).filter(
371
+ fragment => !this.#ownedLoaders.has(fragment),
372
+ )
373
+ const fragment = fragments.at(-1)
374
+ if (fragment) this.#adopt(fragment)
375
+ }
162
376
 
163
- this.#updateLevels()
377
+ // An empty body was emptied or replaced by other code, unless it is the
378
+ // one the current loader left empty; loading again there would loop on a
379
+ // preloaded menu, so that one waits for the next open
380
+ const loader = this.#request?.loader
381
+ if (!body.firstElementChild && !(loader && this.#emptyLoaders.get(loader) === body)) this.#sync()
164
382
 
165
- this.#focusZoneStack = new ActionMenuFocusZoneStack()
383
+ this.#updateReady()
166
384
  }
167
385
 
168
- #updateLevels() {
169
- let idx = 1
386
+ // Makes an inserted loader the current request. Its src is reflected onto
387
+ // the host, so the rule sees the request as current: an open or preloaded
388
+ // menu loads it at once (upstream's busy guard drops the duplicate for an
389
+ // eager loader), a closed lazy one when it opens, unless the loader is eager
390
+ // and has already started itself. Idiomorph inserts a loader
391
+ // before setting its attributes, but sets them synchronously, so the loader
392
+ // arrives here with its src; one that gets its src only in a later task is
393
+ // replaced with a load at the host src. The template is not touched.
394
+ #adopt(fragment: IncludeFragmentElement) {
395
+ const body = this.#body
396
+ if (!body) return
397
+
398
+ const src = (fragment.getAttribute('src') ?? '').trim()
399
+
400
+ this.#request = {loader: fragment, src}
401
+ this.#ownedLoaders.add(fragment)
402
+ this.#listen(fragment)
403
+ // The response decides the form field name
404
+ this.#inputName = ''
405
+ this.#keepInputs(body)
406
+
407
+ if (this.#isOpen()) {
408
+ this.#keepOpenWhileLoading(fragment)
409
+ // A focus handler may have started a newer load meanwhile
410
+ if (this.#request?.loader !== fragment) return
411
+ }
412
+
413
+ for (const child of Array.from(body.childNodes)) {
414
+ if (child !== fragment) child.remove()
415
+ }
170
416
 
171
- for (const menu of this.querySelectorAll('[role=menu]')) {
172
- menu.setAttribute('data-level', idx.toString())
173
- idx++
417
+ if (src && src !== this.getAttribute('src')) {
418
+ this.setAttribute('src', src)
419
+ } else if (this.#isOpen() || this.#preload) {
420
+ // An unchanged src does not run the rule, and a lazy loader inserted
421
+ // before its attributes never starts on its own
422
+ this.#sync()
174
423
  }
175
424
  }
176
425
 
177
- disconnectedCallback() {
178
- this.#abortController.abort()
426
+ // Keeps the open (or opening) menu open while fragment loads into its
427
+ // body. Open sub-menus are torn down first, since their toggle events
428
+ // arrive after the nodes are gone, and focus moves to the fragment's
429
+ // spinner before the focusout frame runs, so it never drops to <body> and
430
+ // closes the menu. Called from beforetoggle, before the popover shows, the
431
+ // focus() is a no-op; the toggle frame then focuses the spinner.
432
+ #keepOpenWhileLoading(fragment: IncludeFragmentElement) {
433
+ this.#pruneFocusZones()
434
+ this.#focusZoneStack.popAbove(this.overlay)
435
+
436
+ for (const child of this.childPopoverElements) {
437
+ if (child.matches(':popover-open')) child.hidePopover()
438
+ }
439
+
440
+ fragment.querySelector<HTMLElement>('[role=menuitem]')?.focus()
441
+ }
442
+
443
+ // Drops focus zones of overlays other code removed, such as a replaced
444
+ // primary overlay and its sub-menus.
445
+ #pruneFocusZones() {
446
+ this.#focusZoneStack.prune(element => element.isConnected && this.contains(element))
179
447
  }
180
448
 
181
449
  #softDisableItems() {
@@ -241,6 +509,11 @@ export class ActionMenuElement extends HTMLElement {
241
509
  const targetIsInvoker = this.invokerElement?.contains(event.target as HTMLElement)
242
510
  const eventIsActivation = this.#isActivation(event)
243
511
 
512
+ if (event.type === 'beforetoggle' && event instanceof ToggleEvent) {
513
+ this.#handleBeforeToggleEvent(event)
514
+ return
515
+ }
516
+
244
517
  if (event.type === 'toggle' && event instanceof ToggleEvent) {
245
518
  this.#handleToggleEvent(event)
246
519
  return
@@ -315,7 +588,36 @@ export class ActionMenuElement extends HTMLElement {
315
588
  return
316
589
  }
317
590
 
591
+ if (event.type === 'include-fragment-replace') {
592
+ const loader = event.target as IncludeFragmentElement
593
+ if (loader !== this.#request?.loader) return
594
+
595
+ // Other code removed the current loader before it completed, eg. by
596
+ // emptying the body, or rewrote its src, eg. by a morph: its response is
597
+ // not the one requested and must not render or mark the menu ready
598
+ const body = this.#body
599
+ if (!body || loader.parentElement !== body || (loader.getAttribute('src') ?? '').trim() !== this.#request.src) {
600
+ event.preventDefault()
601
+ return
602
+ }
603
+
604
+ // A response without menu items is discarded, so the body stays empty
605
+ // and the menu loads again when it next opens
606
+ const fragment: unknown = event instanceof CustomEvent ? event.detail?.fragment : null
607
+ if (!(fragment instanceof DocumentFragment)) return
608
+
609
+ if (!fragment.querySelector(ActionMenuElement.menuItemSelectors.join(','))) {
610
+ fragment.replaceChildren()
611
+ this.#emptyLoaders.set(loader, body)
612
+ }
613
+ return
614
+ }
615
+
318
616
  if (event.type === 'include-fragment-replaced') {
617
+ // A superseded primary loader that completed late
618
+ const loader = event.target as IncludeFragmentElement
619
+ if (this.#ownedLoaders.has(loader) && loader !== this.#request?.loader) return
620
+
319
621
  this.#handleIncludeFragmentReplaced()
320
622
  return
321
623
  }
@@ -333,43 +635,73 @@ export class ActionMenuElement extends HTMLElement {
333
635
  break
334
636
  }
335
637
 
336
- case 'ArrowLeft':
337
- if (item.closest('role[menu]') !== this.list) {
338
- const overlay = item.closest('anchored-position') as AnchoredPositionElement | null
339
- overlay?.hidePopover()
638
+ case 'ArrowLeft': {
639
+ const overlay = item.closest('anchored-position') as AnchoredPositionElement | null
640
+ if (overlay && overlay !== this.overlay) {
641
+ overlay.hidePopover()
340
642
  }
341
643
 
342
644
  break
645
+ }
343
646
  }
344
647
  }
345
648
 
346
- #handleToggleEvent(event: ToggleEvent) {
347
- const subMenu = event.target as AnchoredPositionElement
649
+ #handleBeforeToggleEvent(event: ToggleEvent) {
650
+ if (event.newState === 'open') {
651
+ // A closed lazy menu catches up, and a failed load retries, as it opens
652
+ if (event.target === this.overlay) this.#sync(true)
653
+ return
654
+ }
655
+
656
+ if (event.newState !== 'closed') return
657
+
658
+ const menu = this.#toggledMenu(event)
659
+ if (!menu) return
348
660
 
349
- // Ignore toggle events from non-anchored-position elements (e.g. tooltips inside the menu)
350
- if (!(event.target instanceof AnchoredPositionElement)) return
661
+ this.#focusZoneStack.pop(menu)
662
+
663
+ // The primary menu's popover hands focus back to the invoker itself
664
+ if (menu === this.overlay) return
665
+
666
+ // A nested popover does not hand focus back when it closes, so a sub-menu closed
667
+ // with ArrowLeft or Escape would leave focus on the body and the focusout handler
668
+ // would then close the whole menu. Move focus to the sub-menu's item before the
669
+ // sub-menu hides, while focus is still inside it. Doing this synchronously, rather
670
+ // than in the async toggle event, keeps focus from ever reaching the body.
671
+ if (!menu.contains(document.activeElement)) return
672
+
673
+ this.#itemForSubMenu(menu)?.focus()
674
+ }
675
+
676
+ #handleToggleEvent(event: ToggleEvent) {
677
+ const menu = this.#toggledMenu(event)
678
+ if (!menu) return
351
679
 
352
680
  if (event.newState === 'open') {
353
681
  // allow tabbing away from primary menu, but trap focus in sub-menus
354
- const isPrimaryMenu = subMenu === this.overlay
355
- this.#focusZoneStack.push(subMenu, {trapFocus: !isPrimaryMenu})
682
+ const isPrimaryMenu = menu === this.overlay
683
+ this.#focusZoneStack.push(menu, {trapFocus: !isPrimaryMenu})
684
+
685
+ // Picks up a src set by a beforetoggle listener that ran after ours
686
+ if (isPrimaryMenu) this.#sync(true)
356
687
 
357
688
  window.requestAnimationFrame(() => {
358
- const firstItem = subMenu.querySelector(ActionMenuElement.menuItemSelectors.join(',')) as HTMLElement | null
689
+ const firstItem = menu.querySelector(ActionMenuElement.menuItemSelectors.join(',')) as HTMLElement | null
359
690
  firstItem?.focus()
360
691
  })
361
- } else {
362
- // Note that this will also cause focus to return to the invoker button, which is
363
- // desirable
364
- this.#focusZoneStack.pop(subMenu)
365
- const item = this.#itemForSubMenu(subMenu)
366
- const openPopover = document.querySelector(':popover-open')
367
- if (item && !openPopover) {
368
- item.focus()
369
- }
692
+ } else if (menu === this.overlay && !document.querySelector(':popover-open')) {
693
+ // A light-dismissed menu (e.g. a click outside it) leaves focus on the body;
694
+ // hand it back to the invoker so the menu stays reachable from the keyboard.
695
+ this.invokerElement?.focus()
370
696
  }
371
697
  }
372
698
 
699
+ // The primary menu or a sub-menu, or null for popovers that are not menus
700
+ // (e.g. tooltips inside the menu)
701
+ #toggledMenu(event: ToggleEvent): AnchoredPositionElement | null {
702
+ return event.target instanceof AnchoredPositionElement ? event.target : null
703
+ }
704
+
373
705
  #handleInvokerActivated(event: Event) {
374
706
  event.preventDefault()
375
707
  /* eslint-disable-next-line no-restricted-syntax */
@@ -470,12 +802,32 @@ export class ActionMenuElement extends HTMLElement {
470
802
  }
471
803
 
472
804
  #handleIncludeFragmentReplaced() {
473
- this.#firstItem?.focus()
805
+ // Content can finish loading while the menu is detached
806
+ if (this.isConnected) {
807
+ const firstItem = this.#firstItem
808
+
809
+ if (firstItem) {
810
+ firstItem.focus()
811
+ } else if (this.#isOpen()) {
812
+ // Nothing to focus in an empty response: close and return to the
813
+ // button.
814
+ this.overlay.hidePopover()
815
+ this.invokerElement?.focus()
816
+ }
817
+
818
+ this.overlay?.update()
819
+ }
820
+ if (this.#deferred) this.#dropKeptInputs()
821
+ this.#setDynamicLabel()
822
+ this.#updateInput()
474
823
  this.#softDisableItems()
475
- this.overlay?.update()
476
824
 
477
- // async items have loaded, so component is ready
478
- this.setAttribute('data-ready', 'true')
825
+ // Ready unless the focus moves above started another load
826
+ if (this.#deferred) {
827
+ this.#updateReady()
828
+ } else {
829
+ this.setAttribute('data-ready', 'true')
830
+ }
479
831
  }
480
832
 
481
833
  // Close when focus leaves menu
@@ -495,15 +847,20 @@ export class ActionMenuElement extends HTMLElement {
495
847
  }
496
848
  }
497
849
 
498
- #isOpen() {
499
- return this.popoverElement?.matches(':popover-open')
850
+ #isOpen(): boolean {
851
+ return this.overlay?.matches(':popover-open') ?? false
500
852
  }
501
853
 
502
854
  #setDynamicLabel() {
503
855
  if (!this.dynamicLabel) return
504
856
  const invokerLabel = this.invokerLabel
505
857
  if (!invokerLabel) return
506
- this.#originalLabel ||= invokerLabel.textContent || ''
858
+ // Kept on the host, since the button of a cloned or restored menu
859
+ // already shows a selection
860
+ if (!this.#originalLabel) {
861
+ this.#originalLabel = this.getAttribute('data-original-label') ?? (invokerLabel.textContent || '')
862
+ this.setAttribute('data-original-label', this.#originalLabel)
863
+ }
507
864
  let itemLabel: string | undefined
508
865
  if (this.selectVariant === 'single') {
509
866
  itemLabel = this.querySelector('[aria-checked=true] .ActionListItem-label')?.textContent?.trim()
@@ -549,6 +906,10 @@ export class ActionMenuElement extends HTMLElement {
549
906
  if (inputs.length > 0) {
550
907
  this.#inputName ||= (inputs[0] as HTMLInputElement).name
551
908
  }
909
+ // Kept on the container too, so a cloned or restored menu with nothing
910
+ // selected still names the inputs it creates
911
+ this.#inputName ||= inputList.getAttribute('data-input-name') ?? ''
912
+ if (this.#inputName) inputList.setAttribute('data-input-name', this.#inputName)
552
913
 
553
914
  for (const selectedItem of this.selectedItems) {
554
915
  const newInput = document.createElement('input')
@@ -1,7 +1,7 @@
1
1
  import AnchoredPositionElement from '../../anchored_position';
2
2
  type StackEntry = {
3
3
  element: AnchoredPositionElement;
4
- abortController?: AbortController;
4
+ abortController: AbortController;
5
5
  };
6
6
  export declare class ActionMenuFocusZoneStack {
7
7
  #private;
@@ -11,6 +11,9 @@ export declare class ActionMenuFocusZoneStack {
11
11
  trapFocus: boolean;
12
12
  }): void;
13
13
  pop(target?: AnchoredPositionElement): void;
14
+ popAbove(element: AnchoredPositionElement): void;
15
+ prune(isLive: (element: AnchoredPositionElement) => boolean): void;
16
+ clear(): void;
14
17
  elementIsMenuItem(element: HTMLElement): boolean;
15
18
  get isEmpty(): boolean;
16
19
  }