@jxsuite/studio 2.4.3 → 4.0.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 (208) hide show
  1. package/README.md +5 -5
  2. package/dist/chunks/Overlay.dev-723bv0df.js +23 -0
  3. package/dist/chunks/cf-settings-45fgyx8y.js +21 -0
  4. package/dist/chunks/{components-z6cnkyy1.js → components-zmx10t62.js} +6 -5
  5. package/dist/chunks/content-source-t88vb2dr.js +49 -0
  6. package/dist/chunks/{convert-to-repeater-k10dvcc7.js → convert-to-repeater-dhw1nrz9.js} +27 -18
  7. package/dist/chunks/entry-commands-6z6bhxg0.js +46 -0
  8. package/dist/chunks/{extension-sections-0ada0xcw.js → extension-sections-3ydgjbdy.js} +32 -23
  9. package/dist/chunks/file-ops-rskmhxyq.js +48 -0
  10. package/dist/chunks/files-0cratsr0.js +92 -0
  11. package/dist/chunks/{format-host-wewba4nq.js → format-host-tgcmfs4p.js} +3 -3
  12. package/dist/chunks/fs-events-hrrg328g.js +21 -0
  13. package/dist/chunks/{git-panel-2dh1aw50.js → git-panel-0yywyk76.js} +21 -15
  14. package/dist/chunks/{jx-validate-jj9rnt4n.js → jx-validate-8q2g05x1.js} +6 -4
  15. package/dist/chunks/layers-panel-z3tqe5cd.js +67 -0
  16. package/dist/chunks/layers-q75tj2mf.js +45 -0
  17. package/dist/chunks/lit-html-j055mkh8.js +22 -0
  18. package/dist/chunks/monaco-buffer-dqw0xxpx.js +25 -0
  19. package/dist/chunks/{monaco-setup-a5wkmbgh.js → monaco-setup-rws7k4br.js} +4 -4
  20. package/dist/chunks/notify-yjm79n4s.js +30 -0
  21. package/dist/chunks/parse-24d0gay3.js +19 -0
  22. package/dist/chunks/platform-ba1j1gbh.js +16 -0
  23. package/dist/chunks/publish-panel-54jvhskq.js +28 -0
  24. package/dist/chunks/quick-search-cgfmjwq5.js +65 -0
  25. package/dist/chunks/references-3qx8fkyp.js +29 -0
  26. package/dist/chunks/right-panel-cqp8bc4v.js +46 -0
  27. package/dist/chunks/sp-overlay.dev-yztmtrs1.js +18 -0
  28. package/dist/chunks/sp-popover.dev-n2etmqdp.js +9 -0
  29. package/dist/chunks/sp-progress-circle.dev-hryhj0es.js +15 -0
  30. package/dist/chunks/sp-tooltip.dev-xcvpnqr0.js +15 -0
  31. package/dist/chunks/{sp-tray.dev-64v4pxw8.js → sp-tray.dev-tkbscm06.js} +5 -5
  32. package/dist/chunks/{studio-f5yyvqxv.js → studio-1hbqnt19.js} +37 -31
  33. package/dist/chunks/studio-2zkz8evn.js +3163 -0
  34. package/dist/chunks/{studio-0b6fs05q.js → studio-4pqqxbrt.js} +23 -15
  35. package/dist/chunks/{studio-kvfx9z2c.js → studio-4rzyrtjz.js} +70 -31
  36. package/dist/chunks/{studio-ef8t53vc.js → studio-5q69gfag.js} +60 -56
  37. package/dist/chunks/{studio-v2c5pmjj.js → studio-5rywrkxz.js} +565 -133
  38. package/dist/chunks/{studio-6kv3apa9.js → studio-68n67094.js} +25 -9
  39. package/dist/chunks/{studio-0rqqhrdy.js → studio-7nte2hj4.js} +2 -2
  40. package/dist/chunks/{studio-hyn3vhwr.js → studio-8swrjbny.js} +31 -18
  41. package/dist/chunks/studio-92ab2jqe.js +282 -0
  42. package/dist/chunks/{studio-sas7mt3k.js → studio-9ab8gqsm.js} +2 -2
  43. package/dist/chunks/{studio-28xc8ws4.js → studio-9c4k4vhv.js} +14 -10
  44. package/dist/chunks/studio-9n4mrmnb.js +184 -0
  45. package/dist/chunks/{studio-tr20m8g8.js → studio-9r6j5ev1.js} +37 -2
  46. package/dist/chunks/{studio-aweyr4v1.js → studio-ahjfdy6e.js} +9 -7
  47. package/dist/chunks/{studio-s519zc99.js → studio-bgxt93ga.js} +3 -3
  48. package/dist/chunks/{studio-26sv44br.js → studio-cb12yz9w.js} +8543 -8784
  49. package/dist/chunks/studio-cft9r4r7.js +119 -0
  50. package/dist/chunks/{studio-rqemfhz6.js → studio-eenfkt4e.js} +6 -6
  51. package/dist/chunks/studio-eesa1myv.js +498 -0
  52. package/dist/chunks/{studio-ay8wcr2b.js → studio-eqq1w638.js} +7 -9
  53. package/dist/chunks/{studio-ke244pam.js → studio-ex8zyp98.js} +51 -25
  54. package/dist/chunks/studio-gv8vvshc.js +118 -0
  55. package/dist/chunks/studio-hbtp0eh1.js +1315 -0
  56. package/dist/chunks/{studio-cz2j1c0g.js → studio-htsf0w6m.js} +75 -123
  57. package/dist/chunks/{studio-pyrw8h0w.js → studio-kjjsjak4.js} +528 -212
  58. package/dist/chunks/{studio-5x5774ak.js → studio-kryvsw6j.js} +3 -3
  59. package/dist/chunks/studio-kyh9avvv.js +28 -0
  60. package/dist/chunks/{studio-jnakhg87.js → studio-kyk2v92a.js} +14 -14
  61. package/dist/chunks/{studio-twsafr1e.js → studio-m3hwn7y1.js} +3 -3
  62. package/dist/chunks/{studio-tzx3xmvx.js → studio-mmv72a27.js} +8 -8
  63. package/dist/chunks/{studio-vhk5fmfv.js → studio-n8b9wqwy.js} +5 -5
  64. package/dist/chunks/{studio-cjm7fdjf.js → studio-p4ngc046.js} +8 -104
  65. package/dist/chunks/{studio-sccge2wf.js → studio-p8j86wag.js} +2 -2
  66. package/dist/chunks/{studio-v1va0vhd.js → studio-pdfjntbk.js} +75 -139
  67. package/dist/chunks/studio-q43a5y9h.js +394 -0
  68. package/dist/chunks/studio-q7v10cg2.js +106 -0
  69. package/dist/chunks/{studio-2w11grav.js → studio-qq6jym04.js} +3 -3
  70. package/dist/chunks/studio-r1r7afxx.js +1066 -0
  71. package/dist/chunks/{studio-3fk1ac9z.js → studio-rdx8jcxy.js} +4 -4
  72. package/dist/chunks/{studio-4mqb9a0j.js → studio-rn9ta2mz.js} +4 -4
  73. package/dist/chunks/studio-sf7zjgv1.js +91 -0
  74. package/dist/chunks/studio-t7qb9db8.js +665 -0
  75. package/dist/chunks/studio-tmc5emrw.js +8 -0
  76. package/dist/chunks/{studio-wdt9y92a.js → studio-txwkm6p9.js} +2 -2
  77. package/dist/chunks/{studio-dgj7gq44.js → studio-v38hmvx1.js} +7 -7
  78. package/dist/chunks/{studio-7ejemhej.js → studio-vadzgkrz.js} +6 -6
  79. package/dist/chunks/studio-wcy8trfx.js +263 -0
  80. package/dist/chunks/{studio-hb7c46jy.js → studio-wx5609xd.js} +21 -15
  81. package/dist/chunks/studio-xrapxwwc.js +1539 -0
  82. package/dist/chunks/{studio-ws6ef6js.js → studio-yxrkyv8a.js} +41 -29
  83. package/dist/chunks/{studio-xm3dbxvn.js → studio-zczps70q.js} +2 -2
  84. package/dist/chunks/workspace-xpres40v.js +89 -0
  85. package/dist/iframe-entry.js +450 -48
  86. package/dist/studio.js +2455 -1761
  87. package/package.json +16 -15
  88. package/src/browse/library-layouts.ts +3 -3
  89. package/src/browse/library-pane.ts +59 -5
  90. package/src/browse/library-preview.ts +19 -3
  91. package/src/canvas/asset-refs.ts +119 -0
  92. package/src/canvas/asset-resolve.ts +256 -0
  93. package/src/canvas/canvas-live-render.ts +23 -15
  94. package/src/canvas/canvas-render.ts +23 -1
  95. package/src/canvas/iframe-entry.ts +1 -0
  96. package/src/canvas/iframe-host.ts +4 -0
  97. package/src/canvas/iframe-patch.ts +47 -21
  98. package/src/canvas/iframe-protocol.ts +9 -0
  99. package/src/canvas/iframe-render.ts +50 -16
  100. package/src/commands/app-commands.ts +4 -0
  101. package/src/commands/command-args.ts +29 -0
  102. package/src/commands/context.ts +15 -1
  103. package/src/commands/defaults.ts +29 -1
  104. package/src/commands/levels.ts +16 -0
  105. package/src/commands/live-context.ts +3 -0
  106. package/src/content/collection-match.ts +267 -0
  107. package/src/content/entry-commands.ts +38 -29
  108. package/src/content/entry-fields.ts +6 -0
  109. package/src/editor/file-drop-action.ts +2 -1
  110. package/src/editor/shortcuts.ts +5 -0
  111. package/src/files/file-ops.ts +10 -42
  112. package/src/files/files.ts +487 -61
  113. package/src/files/fs-events.ts +9 -0
  114. package/src/files/gitignore.ts +432 -0
  115. package/src/files/media-paths.ts +37 -14
  116. package/src/files/media-upload.ts +47 -6
  117. package/src/files/serialize-document.ts +60 -0
  118. package/src/format/convert-file.ts +511 -0
  119. package/src/format/format-choices.ts +199 -0
  120. package/src/grid/grid-idle.ts +45 -0
  121. package/src/grid/grid-view.ts +35 -0
  122. package/src/grid/schema-columns.ts +2 -1
  123. package/src/grid/sources/content-source.ts +24 -3
  124. package/src/media/media-open.ts +58 -0
  125. package/src/media/media-pane.ts +310 -0
  126. package/src/new-project/import-tab.ts +333 -160
  127. package/src/new-project/new-project-modal.ts +27 -34
  128. package/src/packages/ensure-deps.ts +14 -7
  129. package/src/packages/jxsuite-update.ts +11 -11
  130. package/src/page-params.ts +10 -46
  131. package/src/panels/activity-bar.ts +45 -16
  132. package/src/panels/ai-chat/attached-context.ts +6 -1
  133. package/src/panels/ai-chat/chat-view.ts +255 -13
  134. package/src/panels/ai-chat/composer.ts +21 -80
  135. package/src/panels/ai-panel.ts +116 -2
  136. package/src/panels/frontmatter-fields.ts +6 -2
  137. package/src/panels/navigator-panels.ts +7 -6
  138. package/src/panels/properties-panel.ts +8 -2
  139. package/src/panels/seo-modal.ts +5 -6
  140. package/src/panels/settings-menu.ts +799 -0
  141. package/src/panels/signals-panel.ts +2 -1
  142. package/src/panels/toolbar.ts +135 -15
  143. package/src/platforms/cloud.ts +34 -3
  144. package/src/platforms/devserver.ts +72 -34
  145. package/src/preview/preview-overlay.ts +226 -0
  146. package/src/services/ai-ask.ts +247 -0
  147. package/src/services/ai-import-tools.ts +494 -0
  148. package/src/services/ai-models.ts +101 -11
  149. package/src/services/ai-project-tools.ts +20 -26
  150. package/src/services/ai-settings.ts +69 -71
  151. package/src/services/ai-system-prompt.ts +88 -2
  152. package/src/services/ai-turn-signal.ts +70 -0
  153. package/src/services/cf-settings.ts +19 -37
  154. package/src/services/connection.ts +74 -0
  155. package/src/services/context-manager.ts +89 -0
  156. package/src/services/document-assistant.ts +49 -7
  157. package/src/services/idle.ts +6 -1
  158. package/src/services/import-client.ts +33 -6
  159. package/src/services/import-run.ts +158 -0
  160. package/src/services/import-seed.ts +120 -0
  161. package/src/services/jx-validate.ts +58 -6
  162. package/src/services/project-adoption.ts +71 -0
  163. package/src/services/references.ts +0 -0
  164. package/src/services/settings/definitions.ts +181 -0
  165. package/src/services/settings/kernel.ts +335 -0
  166. package/src/services/settings/write-queue.ts +116 -0
  167. package/src/services/tool-executor.ts +34 -2
  168. package/src/settings/contexts-section.ts +45 -3
  169. package/src/settings/dependencies-editor.ts +43 -23
  170. package/src/settings/general-settings.ts +30 -12
  171. package/src/settings/preferences-accounts.ts +6 -19
  172. package/src/settings/preferences-dialog.ts +18 -41
  173. package/src/settings/preferences-keymap.ts +8 -18
  174. package/src/settings/preferences-sections.ts +57 -0
  175. package/src/settings/schema-field-ui.ts +2 -2
  176. package/src/settings/settings-document.ts +65 -9
  177. package/src/shell.ts +6 -14
  178. package/src/studio.ts +65 -7
  179. package/src/tabs/transact.ts +42 -19
  180. package/src/types.ts +164 -8
  181. package/src/ui/ai-credentials-form.ts +52 -27
  182. package/src/ui/ai-model-picker.ts +162 -0
  183. package/src/ui/choice-field.ts +72 -0
  184. package/src/ui/layers.ts +83 -5
  185. package/src/ui/media-picker.ts +6 -11
  186. package/src/utils/studio-utils.ts +43 -31
  187. package/styles/forced-colors.css +7 -0
  188. package/styles/overlays.css +256 -0
  189. package/styles/panels.css +13 -1
  190. package/styles/shell.css +111 -0
  191. package/dist/chunks/Overlay.dev-d2ajy6sj.js +0 -23
  192. package/dist/chunks/cf-settings-g5fbf2zp.js +0 -17
  193. package/dist/chunks/content-source-k9724vcv.js +0 -39
  194. package/dist/chunks/files-yew27sn9.js +0 -69
  195. package/dist/chunks/layers-panel-qnsghwwd.js +0 -59
  196. package/dist/chunks/publish-panel-a0pdft5w.js +0 -21
  197. package/dist/chunks/quick-search-9avyc4pc.js +0 -54
  198. package/dist/chunks/right-panel-kcnhtc5j.js +0 -38
  199. package/dist/chunks/sp-overlay.dev-s18hymn9.js +0 -18
  200. package/dist/chunks/sp-popover.dev-dj9x7e7a.js +0 -9
  201. package/dist/chunks/sp-progress-circle.dev-0zxcyz3r.js +0 -15
  202. package/dist/chunks/sp-tooltip.dev-5c6d1kjz.js +0 -15
  203. package/dist/chunks/studio-a7pzveq1.js +0 -110
  204. package/dist/chunks/studio-c31yb4t6.js +0 -55
  205. package/dist/chunks/studio-ra7ar50f.js +0 -6682
  206. package/src/canvas/content-assets.ts +0 -263
  207. package/src/canvas/site-style-css.ts +0 -121
  208. package/src/services/settings-store.ts +0 -99
@@ -0,0 +1,799 @@
1
+ /// <reference lib="dom" />
2
+ /**
3
+ * The rail foot's ⚙ Settings menu — a RENDERING of the `settings/menu` placement.
4
+ *
5
+ * The gear used to run one command. That was the right shape for a pinned slot and the wrong shape
6
+ * for the question people bring to it: Studio has two settings families at two containment levels —
7
+ * `app.preferences` (the application, ⌘,) and `settings.open` (this project, ⌘⇧,) — plus a third
8
+ * editor over the same project document, `styles.open`. A slot can hold one of those and must lie
9
+ * about the rest by omission. A menu can hold all three and say what each one is, because it prints
10
+ * every row's own name, chord and gate beside it (§12.3). That is the whole argument for the matrix
11
+ * row `settings/menu` admitting two levels, and for the divider this file draws where the level
12
+ * changes.
13
+ *
14
+ * **Nothing here is a list of actions.** The rows are `registry.forPlacement("settings/menu")`, so
15
+ * a record joins the menu by declaring the placement and leaves by not declaring it. The submenus
16
+ * are the enumeration of each parent command's own `section` ARGUMENT, read from that argument's
17
+ * own definition site — which is state the command already validates, not a second vocabulary
18
+ * (§12.5).
19
+ *
20
+ * **A parent row runs its own command AND owns a submenu**, which the APG menu pattern does not
21
+ * describe and Spectrum's stock `slot="submenu"` forbids outright:
22
+ * `Menu.handlePointerBasedSelection` bails on `hasSubmenu`, so a parent emits no `change`, and
23
+ * `MenuItem.handleSubmenuChange` reports the PARENT's value to the outer menu, which would break
24
+ * the deep link as well. So the submenu is a second `renderPopover` and the parent keeps its own
25
+ * `@click`. The deviation is recorded in `specs/studio-ui-guidelines.md` §8.4 and §14; nothing is
26
+ * unreachable by keyboard because Enter runs the row, ArrowRight reaches every child, and every
27
+ * child is also in the settings document's own inner nav.
28
+ *
29
+ * **There is no hover-intent timer, deliberately.** A timer is this suite's largest flake source
30
+ * and buys a nicety rather than a capability; a submenu closes when the pointer enters a SIBLING
31
+ * row, so diagonal travel into an open submenu crosses nothing that would shut it. Do not "fix"
32
+ * this by adding one.
33
+ *
34
+ * The machinery is `editor/context-menu.ts:828-1094`'s, with its function names kept, so folding
35
+ * both onto a shared `ui/menu.ts` is a move rather than a rewrite.
36
+ *
37
+ * @docs studio/interface/preferences
38
+ * @docs studio/projects/settings
39
+ */
40
+
41
+ import { html, nothing } from "lit-html";
42
+ import { errorMessage } from "@jxsuite/schema/parse";
43
+ import { activeRegistry } from "../commands/active-registry";
44
+ import { LEVELS } from "../commands/levels";
45
+ import { notify } from "../services/notify";
46
+ import { onSettingsDocumentChanged, sortedSettingsSections } from "../settings/section-registry";
47
+ import { PREFERENCES_SECTIONS } from "../settings/preferences-sections";
48
+ import { renderPopover } from "../ui/layers";
49
+ import { REGION_ATTR } from "../ui/regions";
50
+ import { rectOf } from "../utils/geometry";
51
+
52
+ import type { TemplateResult } from "lit-html";
53
+ import type { AnyCommand, CommandRegistry } from "../commands/registry";
54
+ import type { Level } from "../commands/levels";
55
+
56
+ /** The placement the rail's gear renders. One definition site for the string. */
57
+ export const SETTINGS_MENU_PLACEMENT = "settings/menu" as const;
58
+
59
+ /** One value a parent command's `section` argument accepts. */
60
+ interface MenuSection {
61
+ key: string;
62
+ label: string;
63
+ }
64
+
65
+ /** One row of the root menu. Everything it prints comes off the record. */
66
+ interface MenuRow {
67
+ command: AnyCommand;
68
+ enabled: boolean;
69
+ reason: string | undefined;
70
+ chord: string | undefined;
71
+ /** Whether a divider opens this row's LEVEL group. */
72
+ dividerAbove: boolean;
73
+ /** The values this command's own `section` argument accepts. Empty ⇒ no submenu. */
74
+ sections: readonly MenuSection[];
75
+ }
76
+
77
+ type PopoverHandle = ReturnType<typeof renderPopover>;
78
+
79
+ let _root: PopoverHandle | null = null;
80
+ let _sub: PopoverHandle | null = null;
81
+ let _rows: MenuRow[] = [];
82
+ let _activeIdx = 0;
83
+ /** Which root row owns the open submenu; -1 = none. */
84
+ let _subIdx = -1;
85
+ let _subActiveIdx = 0;
86
+ let _focus: "root" | "sub" = "root";
87
+ let _opener: HTMLElement | null = null;
88
+ let _rerender: (() => void) | null = null;
89
+ let _unsubscribe: (() => void) | null = null;
90
+ let _outside: ((e: MouseEvent) => void) | null = null;
91
+ let _x = 0;
92
+ let _y = 0;
93
+ let _sx = 0;
94
+ let _sy = 0;
95
+
96
+ // ─── Where a submenu's rows come from ─────────────────────────────────────────
97
+
98
+ /**
99
+ * A command's `section` argument, enumerated from that argument's OWN definition site.
100
+ *
101
+ * NOT the second list of actions §12.5 forbids: it holds no titles, no handlers and no ordering of
102
+ * its own. Each entry points at the array the command's validation already reads —
103
+ * `app.preferences` refuses anything `isPreferencesSection` rejects, `settings.open` refuses
104
+ * anything absent from `settingsSectionKeys()` — so a submenu row can never name a value its own
105
+ * command would refuse.
106
+ */
107
+ const SECTION_SOURCES: Readonly<Record<string, () => readonly MenuSection[]>> = {
108
+ "app.preferences": () =>
109
+ PREFERENCES_SECTIONS.map((section) => ({ key: section.id, label: section.title })),
110
+ "settings.open": () =>
111
+ sortedSettingsSections().map((section) => ({ key: section.key, label: section.label })),
112
+ };
113
+
114
+ /** The sections a row offers, or none. */
115
+ function menuSectionsFor(id: string): readonly MenuSection[] {
116
+ return SECTION_SOURCES[id]?.() ?? [];
117
+ }
118
+
119
+ // ─── Rows ─────────────────────────────────────────────────────────────────────
120
+
121
+ /**
122
+ * Ask the registry what belongs in the gear right now, ordered level-first.
123
+ *
124
+ * `forPlacement` already filters by `when` and sorts by `group` then title; `toSorted` is stable,
125
+ * so that order survives inside each level group. The divider falls where the LEVEL changes, which
126
+ * is the same boundary the rail's own panel groups draw — and the reason a menu may hold two levels
127
+ * where a pinned slot may not.
128
+ */
129
+ function buildSettingsMenuRows(registry: CommandRegistry): MenuRow[] {
130
+ const commands = [...registry.forPlacement(SETTINGS_MENU_PLACEMENT)].toSorted(
131
+ (a, b) => LEVELS.indexOf(a.level) - LEVELS.indexOf(b.level),
132
+ );
133
+ let level: Level | undefined;
134
+ return commands.map((command, index) => {
135
+ const dividerAbove = index > 0 && command.level !== level;
136
+ ({ level } = command);
137
+ const enabled = registry.isEnabled(command.id);
138
+ const chord = registry.keymap.formatBinding(command.id);
139
+ return {
140
+ // A chord that just restates the row's own name teaches nothing and reads as a stutter.
141
+ chord: chord?.toLowerCase() === command.title.toLowerCase() ? undefined : chord,
142
+ command,
143
+ dividerAbove,
144
+ enabled,
145
+ reason: enabled ? undefined : registry.disabledReason(command.id),
146
+ // A row whose command cannot run offers no sections: every one of them runs that same refusal.
147
+ sections: enabled ? menuSectionsFor(command.id) : [],
148
+ };
149
+ });
150
+ }
151
+
152
+ // ─── Running ──────────────────────────────────────────────────────────────────
153
+
154
+ /**
155
+ * Run a row's command, surfacing a refusal instead of stranding it.
156
+ *
157
+ * `settings.open`'s `run` is async and throws a `RangeError` AFTER awaiting the contributed-section
158
+ * sync, and `registry.run` does not catch. `editor/context-menu.ts`'s bare `void result` is safe
159
+ * only because every element verb is synchronous; here an unknown section would reject into
160
+ * nothing.
161
+ */
162
+ function runRow(id: string, args?: Record<string, unknown>): void {
163
+ const registry = activeRegistry();
164
+ if (!registry) {
165
+ return;
166
+ }
167
+ let result: unknown;
168
+ try {
169
+ result = registry.run(id, args as never);
170
+ } catch (error) {
171
+ notify.error(errorMessage(error), { source: id });
172
+ return;
173
+ }
174
+ void Promise.resolve(result).catch((error: unknown) => {
175
+ notify.error(errorMessage(error), { source: id });
176
+ });
177
+ }
178
+
179
+ // ─── Focus ────────────────────────────────────────────────────────────────────
180
+
181
+ /** The rendered root rows, in order. */
182
+ function rootItems(): HTMLElement[] {
183
+ return _root
184
+ ? [..._root.host.querySelectorAll<HTMLElement>("sp-menu-item[data-command-id]")]
185
+ : [];
186
+ }
187
+
188
+ /** The rendered submenu rows, in order. */
189
+ function subItems(): HTMLElement[] {
190
+ return _sub ? [..._sub.host.querySelectorAll<HTMLElement>("sp-menu-item[data-section-key]")] : [];
191
+ }
192
+
193
+ /**
194
+ * Move the roving tabindex (and the caret) to `index`, wrapping at both ends.
195
+ *
196
+ * `tabIndex` is written BEFORE `.focus()`: an `sp-menu-item` is an undefined custom element until
197
+ * `ui/spectrum.ts` loads, and a plain unknown element is only focusable once it has one.
198
+ */
199
+ function focusItem(items: HTMLElement[], index: number): number {
200
+ if (items.length === 0) {
201
+ return 0;
202
+ }
203
+ const next = ((index % items.length) + items.length) % items.length;
204
+ for (const [at, item] of items.entries()) {
205
+ item.tabIndex = at === next ? 0 : -1;
206
+ item.toggleAttribute("focused", at === next);
207
+ }
208
+ items[next]?.focus();
209
+ return next;
210
+ }
211
+
212
+ function focusRoot(index: number): void {
213
+ _activeIdx = focusItem(rootItems(), index);
214
+ }
215
+
216
+ function focusSub(index: number): void {
217
+ _subActiveIdx = focusItem(subItems(), index);
218
+ }
219
+
220
+ /** How many frames to keep re-applying a freshly opened submenu's caret before giving up. */
221
+ const FOCUS_SETTLE_FRAMES = 8;
222
+
223
+ /**
224
+ * Move a freshly opened submenu's caret, and keep asking until it lands.
225
+ *
226
+ * `sp-menu-item.focus()` is a no-op until Spectrum has finished setting the item up, and `sp-menu`
227
+ * runs its own roving-tabindex pass over its items after they connect — so applying once, even a
228
+ * frame later, is still too early. The symptom is precise and bad: the logical caret is right
229
+ * (Enter runs the correct section) while the focus RING stays on the parent row, so the keyboard
230
+ * and the screen disagree about where you are. `panels/tab-strip.ts` records meeting the same
231
+ * component behaviour from the other side.
232
+ *
233
+ * Rather than guess the settle point, this re-applies on each of the next few frames and stops the
234
+ * moment the browser agrees. The first pass is synchronous so a test in happy-dom — where the
235
+ * element is inert and focus is immediate — sees it on the same tick and never schedules a second.
236
+ * Every pass is guarded, so a pointer that has since moved to another row is not yanked back.
237
+ *
238
+ * @param owner Which root row's submenu this is — the guard against a stale deferral.
239
+ */
240
+ function focusSubSettled(index: number, owner: number): void {
241
+ focusSub(index);
242
+ let attempts = 0;
243
+ const settle = () => {
244
+ if (_focus !== "sub" || _subIdx !== owner || !_sub) {
245
+ return;
246
+ }
247
+ const wanted = subItems()[_subActiveIdx];
248
+ if (!wanted || document.activeElement === wanted) {
249
+ return;
250
+ }
251
+ focusSub(_subActiveIdx);
252
+ attempts += 1;
253
+ if (attempts < FOCUS_SETTLE_FRAMES) {
254
+ requestAnimationFrame(settle);
255
+ }
256
+ };
257
+ requestAnimationFrame(settle);
258
+ }
259
+
260
+ // ─── Geometry ─────────────────────────────────────────────────────────────────
261
+
262
+ /**
263
+ * Clamp a rendered popover into the viewport, writing the result back into module state.
264
+ *
265
+ * The predecessor mutated the `x`/`y` its own render had closed over, which is why
266
+ * `editor/context-menu.ts:851-861` says re-rendering to move focus would re-run the placement from
267
+ * stale coordinates. Writing into `_x`/`_y` makes `renderRoot()` idempotent instead, which is what
268
+ * lets the section subscription repaint an open submenu freely.
269
+ *
270
+ * **Both axes are floored**, not just capped. Project Settings has ~16 sections once extensions
271
+ * have contributed, and a submenu taller than the viewport would otherwise be pushed to a negative
272
+ * `top` — its first rows off the top of the window, unreachable. The floor plus the
273
+ * `.settings-submenu` height cap is what keeps the whole list reachable.
274
+ */
275
+ /**
276
+ * The lowest edge any menu in this stack may reach.
277
+ *
278
+ * The trigger's REGION, not the viewport. The gear sits in the rail, whose bottom is the status
279
+ * bar's top — so clamping to the viewport lets a tall submenu run down over the status bar while
280
+ * the root menu sits neatly above it. One floor for both levels is what keeps the stack looking
281
+ * like one surface.
282
+ */
283
+ function menuFloor(): number {
284
+ const host = _opener?.closest<HTMLElement>(`[${REGION_ATTR}]`);
285
+ return host ? rectOf(host).bottom : window.innerHeight;
286
+ }
287
+
288
+ /** Keep a popover inside the menu area — floored as well as capped, on both axes. */
289
+ function clampIntoMenuArea(
290
+ box: DOMRect,
291
+ origin: { x: number; y: number },
292
+ ): { x: number; y: number } {
293
+ return {
294
+ x: Math.max(4, Math.min(origin.x, window.innerWidth - box.width - 4)),
295
+ y: Math.max(4, Math.min(origin.y, menuFloor() - box.height)),
296
+ };
297
+ }
298
+
299
+ /**
300
+ * Where the root menu wants to sit: hanging off the trigger's right edge, with its BOTTOM flush
301
+ * with the bottom of the region the trigger lives in.
302
+ *
303
+ * Not the trigger's own bottom, and not "below the trigger". The gear is the last control in a
304
+ * full-height rail whose foot abuts the status bar, so a menu dropped below it would be off-screen
305
+ * and one aligned to the button would float six pixels of `.rail-footer` padding clear of the
306
+ * status bar. Aligning to the REGION is what puts it flush, and it is expressed through the shell's
307
+ * own addressing grammar rather than a selector into markup — so a menu button in another region
308
+ * would align to that one without this function learning about it.
309
+ */
310
+ function rootOrigin(box: DOMRect): { x: number; y: number } {
311
+ if (!_opener) {
312
+ return { x: _x, y: _y };
313
+ }
314
+ const anchor = rectOf(_opener);
315
+ return { x: anchor.right + 4, y: menuFloor() - box.height };
316
+ }
317
+
318
+ /**
319
+ * Place a popover, now and again after the browser has laid it out.
320
+ *
321
+ * **The second pass is the one that works.** A popover measures 0×0 until layout runs, and layout
322
+ * does not run inside the call that rendered it — so the synchronous pass clamps against a
323
+ * zero-height box and parks the menu at the bottom edge of the window, which is precisely where a
324
+ * control at the foot of a full-height rail puts it. `editor/context-menu.ts` does its clamp inside
325
+ * a `requestAnimationFrame` for this reason; keeping the first pass as well costs nothing and means
326
+ * a caller that CAN measure (a repaint of an already-open menu) is right immediately.
327
+ *
328
+ * Running twice is safe because the clamp is idempotent and reads its own output: a first pass that
329
+ * parked the origin too low is pulled back up by the second pass's `Math.min`.
330
+ *
331
+ * @param apply Receives the clamped origin — it writes module state and the element's style.
332
+ */
333
+ function placePopover(
334
+ el: HTMLElement,
335
+ desired: (box: DOMRect) => { x: number; y: number },
336
+ apply: (at: { x: number; y: number }) => void,
337
+ ): void {
338
+ const pass = () => {
339
+ const box = rectOf(el);
340
+ apply(clampIntoMenuArea(box, desired(box)));
341
+ };
342
+ pass();
343
+ requestAnimationFrame(() => {
344
+ if (el.isConnected) {
345
+ pass();
346
+ }
347
+ });
348
+ }
349
+
350
+ // ─── Templates ────────────────────────────────────────────────────────────────
351
+
352
+ /**
353
+ * The row's trailing cell: its chord, its chevron, or both.
354
+ *
355
+ * ONE slotted node, not two. Spectrum's menu-item grid gives `[slot=value]` a single cell with
356
+ * `justify-self: end`, and that applies to each assigned node independently — so a `<kbd>` and a
357
+ * chevron both slotted directly land on top of each other. Wrapping them makes the cell one flex
358
+ * row, which is also where the gap between the title and the chord comes from.
359
+ */
360
+ function valueTpl(chord: string | undefined, hasSections: boolean) {
361
+ if (!chord && !hasSections) {
362
+ return nothing;
363
+ }
364
+ return html`<span slot="value" class="settings-menu-value"
365
+ >${chord ? html`<kbd class="cmd-chord">${chord}</kbd>` : nothing}${
366
+ hasSections
367
+ ? html`<sp-icon-chevron-right size="s" aria-hidden="true"></sp-icon-chevron-right>`
368
+ : nothing
369
+ }</span
370
+ >`;
371
+ }
372
+
373
+ /**
374
+ * One root row.
375
+ *
376
+ * A row that owns sections still ACTIVATES — `@click` runs its own command with no arguments, so
377
+ * "Open Project Settings" opens Project Settings on its default section and the submenu is a second
378
+ * way in rather than a replacement for the first. `aria-haspopup`/`aria-expanded` bind to `nothing`
379
+ * on a row without sections so lit removes the attributes rather than emitting
380
+ * `aria-haspopup="false"`.
381
+ */
382
+ function rowTemplate(row: MenuRow, index: number): TemplateResult {
383
+ const hasSections = row.sections.length > 0;
384
+ const expanded = hasSections ? (_subIdx === index ? "true" : "false") : nothing;
385
+ return html`${row.dividerAbove ? html`<sp-menu-divider role="separator"></sp-menu-divider>` : nothing}<sp-menu-item
386
+ role="menuitem"
387
+ data-command-id=${row.command.id}
388
+ tabindex=${index === _activeIdx ? 0 : -1}
389
+ ?focused=${index === _activeIdx}
390
+ ?disabled=${!row.enabled}
391
+ aria-disabled=${row.enabled ? "false" : "true"}
392
+ aria-haspopup=${hasSections ? "menu" : nothing}
393
+ aria-expanded=${expanded}
394
+ @mouseenter=${() => {
395
+ if (hasSections) {
396
+ openSubmenu(index);
397
+ } else {
398
+ closeSubmenu({ restoreFocus: false });
399
+ }
400
+ }}
401
+ @click=${() => activateRow(index)}
402
+ >${row.command.title}${valueTpl(row.chord, hasSections)}${
403
+ row.reason ? html`<span slot="description">Needs ${row.reason}</span>` : nothing
404
+ }</sp-menu-item
405
+ >`;
406
+ }
407
+
408
+ /** One submenu row — named by the argument value it passes, never by a reworded command title. */
409
+ function sectionTemplate(parent: MenuRow, section: MenuSection, index: number): TemplateResult {
410
+ return html`<sp-menu-item
411
+ role="menuitem"
412
+ data-section-key=${section.key}
413
+ tabindex=${index === _subActiveIdx ? 0 : -1}
414
+ ?focused=${index === _subActiveIdx}
415
+ @click=${() => activateSection(parent, section)}
416
+ >${section.label}</sp-menu-item
417
+ >`;
418
+ }
419
+
420
+ // ─── Rendering ────────────────────────────────────────────────────────────────
421
+
422
+ /** Draw (or redraw) the root menu at `_x`/`_y`, clamping once the nodes exist. */
423
+ function renderRoot(): void {
424
+ if (!_root) {
425
+ return;
426
+ }
427
+ _root.update(html`<sp-popover open style="position:fixed;z-index:10000;left:${_x}px;top:${_y}px">
428
+ <sp-menu class="settings-menu" role="menu" aria-label="Settings"
429
+ >${_rows.map((row, index) => rowTemplate(row, index))}</sp-menu
430
+ >
431
+ </sp-popover>`);
432
+ const popover = _root.host.querySelector<HTMLElement>("sp-popover");
433
+ if (popover) {
434
+ placePopover(popover, rootOrigin, (at) => {
435
+ ({ x: _x, y: _y } = at);
436
+ popover.style.left = `${_x}px`;
437
+ popover.style.top = `${_y}px`;
438
+ });
439
+ }
440
+ }
441
+
442
+ /** Draw (or redraw) the open submenu. Re-applies the roving focus at a clamped index. */
443
+ function renderSub(): void {
444
+ const parent = _rows[_subIdx];
445
+ if (!_sub || !parent) {
446
+ return;
447
+ }
448
+ const { sections } = parent;
449
+ _subActiveIdx = Math.min(_subActiveIdx, Math.max(0, sections.length - 1));
450
+ _sub.update(html`<sp-popover
451
+ open
452
+ class="settings-submenu"
453
+ style="position:fixed;z-index:10001;left:${_sx}px;top:${_sy}px"
454
+ >
455
+ <sp-menu role="menu" aria-label=${`Sections of ${parent.command.title}`}
456
+ >${sections.map((section, index) => sectionTemplate(parent, section, index))}</sp-menu
457
+ >
458
+ </sp-popover>`);
459
+ const popover = _sub.host.querySelector<HTMLElement>("sp-popover");
460
+ if (popover) {
461
+ placePopover(
462
+ popover,
463
+ () => ({ x: _sx, y: _sy }),
464
+ (at) => {
465
+ ({ x: _sx, y: _sy } = at);
466
+ popover.style.left = `${_sx}px`;
467
+ popover.style.top = `${_sy}px`;
468
+ },
469
+ );
470
+ }
471
+ }
472
+
473
+ // ─── Activation ───────────────────────────────────────────────────────────────
474
+
475
+ /** Run the row's own command, with no arguments, then dismiss. Disabled rows do nothing. */
476
+ function activateRow(index: number): void {
477
+ const row = _rows[index];
478
+ if (!row?.enabled) {
479
+ return;
480
+ }
481
+ const { id } = row.command;
482
+ dismissSettingsMenu();
483
+ runRow(id);
484
+ }
485
+
486
+ /** Run the PARENT's command with the section this row names, then dismiss both levels. */
487
+ function activateSection(parent: MenuRow, section: MenuSection): void {
488
+ const { id } = parent.command;
489
+ dismissSettingsMenu();
490
+ runRow(id, { section: section.key });
491
+ }
492
+
493
+ // ─── The submenu level ────────────────────────────────────────────────────────
494
+
495
+ /**
496
+ * Open the submenu for root row `index`, replacing whichever one was open.
497
+ *
498
+ * It subscribes to the section registry for as long as it is up. Six of Project Settings' sections
499
+ * are contributed by extensions and register a tick after the built-ins
500
+ * (`settings/extension-sections.ts`, fired by `format/format-host.ts`'s `refreshExtensionUi` on
501
+ * project activation and after every `project.json` write), so a submenu opened in that window
502
+ * would otherwise be permanently short. It deliberately does NOT call the sync itself: opening a
503
+ * menu must not do IO.
504
+ */
505
+ function openSubmenu(index: number): void {
506
+ if (_subIdx === index) {
507
+ return;
508
+ }
509
+ const row = _rows[index];
510
+ if (!_root || !row || row.sections.length === 0) {
511
+ return;
512
+ }
513
+ closeSubmenu({ restoreFocus: false });
514
+ _subIdx = index;
515
+ _subActiveIdx = 0;
516
+ /* The root repaints FIRST, before the submenu exists.
517
+ `aria-expanded` on the parent row is a binding, so the root has to be redrawn either way — but
518
+ doing it afterwards let `sp-menu` re-assert focus on its own focused item and take it straight
519
+ back off the submenu we had just handed it to. The caret and the focus ring then disagreed:
520
+ ArrowRight ran the right section on Enter while the ring stayed on the parent row. */
521
+ renderRoot();
522
+
523
+ const rootRect = rectOf(_root.host.querySelector<HTMLElement>("sp-popover") ?? _root.host);
524
+ const parentRow = rootItems()[index];
525
+ _sx = rootRect.right - 2;
526
+ _sy = parentRow ? rectOf(parentRow).top : rootRect.top;
527
+
528
+ _sub = renderPopover(html`${nothing}`, {
529
+ // One handler for two popovers — see `onOutsideMousedown`.
530
+ dismissOnOutsideClick: false,
531
+ region: "settings-sections",
532
+ });
533
+ renderSub();
534
+ /* Flip to the menu's left when the submenu would leave the viewport on the right — after layout,
535
+ for the same reason `placePopover` runs twice: an unlaid-out popover is 0 wide and would never
536
+ appear to overflow anything. */
537
+ const popover = _sub.host.querySelector<HTMLElement>("sp-popover");
538
+ requestAnimationFrame(() => {
539
+ if (!popover?.isConnected) {
540
+ return;
541
+ }
542
+ const box = rectOf(popover);
543
+ if (_sx + box.width > window.innerWidth - 4) {
544
+ ({ x: _sx, y: _sy } = clampIntoMenuArea(box, {
545
+ x: rootRect.left - box.width + 2,
546
+ y: _sy,
547
+ }));
548
+ popover.style.left = `${_sx}px`;
549
+ popover.style.top = `${_sy}px`;
550
+ }
551
+ });
552
+
553
+ _unsubscribe = onSettingsDocumentChanged(() => {
554
+ const registry = activeRegistry();
555
+ if (!registry) {
556
+ return;
557
+ }
558
+ _rows = buildSettingsMenuRows(registry);
559
+ renderRoot();
560
+ renderSub();
561
+ });
562
+ }
563
+
564
+ /** Close the submenu level, optionally handing focus back to the row that owns it. */
565
+ function closeSubmenu(opts: { restoreFocus: boolean }): void {
566
+ _unsubscribe?.();
567
+ _unsubscribe = null;
568
+ const owner = _subIdx;
569
+ _sub?.dismiss();
570
+ _sub = null;
571
+ _subIdx = -1;
572
+ _subActiveIdx = 0;
573
+ if (owner !== -1) {
574
+ _focus = "root";
575
+ renderRoot();
576
+ if (opts.restoreFocus) {
577
+ focusRoot(owner);
578
+ }
579
+ }
580
+ }
581
+
582
+ // ─── Keyboard ─────────────────────────────────────────────────────────────────
583
+
584
+ /**
585
+ * The menu keyboard contract, acting on the deepest open level.
586
+ *
587
+ * Bound on `document` in the CAPTURE phase, the shape `editor/slash-menu.ts` and
588
+ * `editor/context-menu.ts` both use, and for the two reasons the latter states: the app's own
589
+ * Escape walks the selection ladder and the canvas nudges on arrows, so neither must also fire; and
590
+ * a bubble-phase handler on the popover would race Spectrum's own menu key handling.
591
+ *
592
+ * An unhandled key returns BEFORE `preventDefault`, so nothing else is swallowed.
593
+ */
594
+ function onMenuKeydown(e: KeyboardEvent): void {
595
+ if (!_root) {
596
+ return;
597
+ }
598
+ const inSub = _focus === "sub" && _sub !== null;
599
+ const count = inSub ? subItems().length : _rows.length;
600
+ const move = (index: number) => (inSub ? focusSub(index) : focusRoot(index));
601
+ const active = inSub ? _subActiveIdx : _activeIdx;
602
+
603
+ switch (e.key) {
604
+ case "ArrowDown": {
605
+ move(active + 1);
606
+ break;
607
+ }
608
+ case "ArrowUp": {
609
+ move(active - 1);
610
+ break;
611
+ }
612
+ case "Home": {
613
+ move(0);
614
+ break;
615
+ }
616
+ case "End": {
617
+ move(count - 1);
618
+ break;
619
+ }
620
+ case "ArrowRight": {
621
+ if (inSub || !(_rows[_activeIdx]?.sections.length ?? 0)) {
622
+ return;
623
+ }
624
+ const owner = _activeIdx;
625
+ openSubmenu(owner);
626
+ _focus = "sub";
627
+ focusSubSettled(0, owner);
628
+ break;
629
+ }
630
+ case "ArrowLeft": {
631
+ if (!inSub) {
632
+ return;
633
+ }
634
+ closeSubmenu({ restoreFocus: true });
635
+ break;
636
+ }
637
+ case "Enter":
638
+ case " ": {
639
+ if (inSub) {
640
+ const parent = _rows[_subIdx];
641
+ const section = parent?.sections[_subActiveIdx];
642
+ if (parent && section) {
643
+ activateSection(parent, section);
644
+ }
645
+ } else {
646
+ activateRow(_activeIdx);
647
+ }
648
+ break;
649
+ }
650
+ case "Escape": {
651
+ // One level at a time: the submenu first, the whole menu second.
652
+ if (inSub) {
653
+ closeSubmenu({ restoreFocus: true });
654
+ } else {
655
+ dismissSettingsMenu();
656
+ }
657
+ break;
658
+ }
659
+ case "Tab": {
660
+ dismissSettingsMenu();
661
+ break;
662
+ }
663
+ default: {
664
+ return;
665
+ }
666
+ }
667
+ e.preventDefault();
668
+ e.stopPropagation();
669
+ }
670
+
671
+ // ─── Dismissal ────────────────────────────────────────────────────────────────
672
+
673
+ /**
674
+ * One outside-click handler for BOTH popovers, which is why neither uses `renderPopover`'s.
675
+ *
676
+ * `dismissOnOutsideClick` tests `slot.contains(e.target)` for ONE slot, so with two popovers a
677
+ * mousedown in the submenu is "outside" the root — and `dismiss()` removes the node, so the submenu
678
+ * row's own `click` would never arrive. The opener is inside too: the gear's `@click` owns the
679
+ * toggle, and dismissing here first would make every second click re-open.
680
+ */
681
+ function onOutsideMousedown(e: MouseEvent): void {
682
+ const target = e.target as Node;
683
+ if (_root?.host.contains(target) || _sub?.host.contains(target) || _opener?.contains(target)) {
684
+ return;
685
+ }
686
+ dismissSettingsMenu();
687
+ }
688
+
689
+ /** Drop the menu's global state and hand the keyboard back to whatever opened it. */
690
+ function teardown(): void {
691
+ document.removeEventListener("keydown", onMenuKeydown, true);
692
+ /* Disarm the PENDING arm as well as the armed listener. The arm is deferred a frame so the click
693
+ that opened the menu cannot immediately close it, so a menu dismissed inside that frame would
694
+ otherwise arm AFTER its own death: a document-wide capture listener on a detached slot that
695
+ answers the next mousedown by dismissing the LIVE menu. `ui/layers.ts` documents the same
696
+ hazard at length; this is the same fix. */
697
+ if (_outside) {
698
+ document.removeEventListener("mousedown", _outside, true);
699
+ _outside = null;
700
+ }
701
+ _unsubscribe?.();
702
+ _unsubscribe = null;
703
+ const opener = _opener;
704
+ const rerender = _rerender;
705
+ _rows = [];
706
+ _activeIdx = 0;
707
+ _subIdx = -1;
708
+ _subActiveIdx = 0;
709
+ _focus = "root";
710
+ _opener = null;
711
+ _rerender = null;
712
+ // Only when the menu still held the keyboard: an outside CLICK has already moved focus somewhere
713
+ // The author chose, and yanking it back to the gear would fight them.
714
+ const active = document.activeElement;
715
+ if (opener?.isConnected && (!active || active === document.body)) {
716
+ opener.focus();
717
+ }
718
+ // Last, so `aria-expanded` repaints against the cleared state.
719
+ rerender?.();
720
+ }
721
+
722
+ // ─── Public surface ───────────────────────────────────────────────────────────
723
+
724
+ /** Whether the gear menu is on screen. The rail reads it for `aria-expanded`. */
725
+ export function isSettingsMenuOpen(): boolean {
726
+ return _root !== null;
727
+ }
728
+
729
+ /** Dismiss the menu and any open submenu. Idempotent. */
730
+ export function dismissSettingsMenu(): void {
731
+ if (!_root) {
732
+ return;
733
+ }
734
+ _sub?.dismiss();
735
+ _sub = null;
736
+ const root = _root;
737
+ _root = null;
738
+ root.dismiss();
739
+ teardown();
740
+ }
741
+
742
+ /**
743
+ * Open the gear menu anchored to `anchor` — or close it, when it is already open.
744
+ *
745
+ * `rerender` is called on open and on dismiss so the trigger's `aria-expanded` and its open-state
746
+ * class stay lit BINDINGS rather than imperative attribute writes; a stale `aria-expanded` is a
747
+ * defect this app has shipped before. Same seam as `showContextMenu(e, path, { rerender })`.
748
+ *
749
+ * @param anchor The control the menu hangs off — the rail's gear.
750
+ */
751
+ export function openSettingsMenu(anchor: HTMLElement, opts: { rerender?: () => void } = {}): void {
752
+ if (_root) {
753
+ dismissSettingsMenu();
754
+ return;
755
+ }
756
+ const registry = activeRegistry();
757
+ if (!registry) {
758
+ return;
759
+ }
760
+ const rows = buildSettingsMenuRows(registry);
761
+ if (rows.length === 0) {
762
+ return;
763
+ }
764
+ _rows = rows;
765
+ _activeIdx = 0;
766
+ _subIdx = -1;
767
+ _focus = "root";
768
+ _opener = anchor;
769
+ _rerender = opts.rerender ?? null;
770
+
771
+ // A seed only: `rootOrigin` recomputes both axes from the measured box on every placement pass.
772
+ const rect = rectOf(anchor);
773
+ _x = rect.right + 4;
774
+ _y = rect.top;
775
+
776
+ _root = renderPopover(html`${nothing}`, {
777
+ dismissOnOutsideClick: false,
778
+ region: "settings",
779
+ });
780
+ renderRoot();
781
+
782
+ document.addEventListener("keydown", onMenuKeydown, true);
783
+ _outside = onOutsideMousedown;
784
+ requestAnimationFrame(() => {
785
+ if (_outside) {
786
+ document.addEventListener("mousedown", _outside, true);
787
+ }
788
+ });
789
+ /* A frame later: lit has committed the items, and focusing the first row is what makes the whole
790
+ keyboard contract reachable at all. Guarded, because it is a DEFERRED write of an INITIAL
791
+ value — an arrow pressed inside that frame has already moved the caret, and re-applying row 0
792
+ on top of it would undo the first keystroke after opening. */
793
+ requestAnimationFrame(() => {
794
+ if (_root && _focus === "root" && _subIdx === -1 && _activeIdx === 0) {
795
+ focusRoot(0);
796
+ }
797
+ });
798
+ _rerender?.();
799
+ }