dsh-sidebar-fold 0.1.6 → 0.1.13

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.
@@ -1,657 +1,1031 @@
1
- /**
2
- * The fold itself: locate the shipped "More" row, decide which sibling panel
3
- * rows belong to the group, and mount a 28×28 toggle that folds them away.
4
- *
5
- * Why DOM and not a slot (findings §1/§2): the row is hardcoded in
6
- * `SidebarRoot` (`dsh-client-ui-sidebar/lib/client.js:479`) and no slot projects
7
- * into it — `sidebar.panellist` only projects icons, `sidebar.panellist.actions`
8
- * only fills the dropdown menu, and registering the `sidebar` single slot would
9
- * shadow the whole column. A client plugin that owns only DOM additions is the
10
- * one distributable route.
11
- *
12
- * The header is found **structurally**: within the "Global panels" nav the
13
- * `panelRow` carrying `aria-haspopup="menu"` is the More row (it is the last
14
- * child by construction), which keeps the logic free of localised text.
15
- */
16
- import {
17
- ALIGN_MODES,
18
- ATTR,
19
- CLS,
20
- ICON_PATH,
21
- ICON_PX,
22
- PANELS_LABELS,
23
- SEL,
24
- SHEET,
25
- STORAGE_KEY,
26
- STYLE_TAG_ID,
27
- type AlignMode,
28
- } from './constants.ts'
29
- import { pickDictionary } from './locales.ts'
30
-
31
- /** Minimal DOM surface we touch — keeps the tests free of a DOM dependency. */
32
- type ConfigLike = { defaultFolded: boolean; keepLabels: string[]; align: AlignMode }
33
-
34
- /**
35
- * Coerce a served alignment value into a mode the sheet has a rule for.
36
- *
37
- * The host config is a plain string (schemastery cannot express a closed union
38
- * across every line this plugin supports), so the value reaching the browser is
39
- * untrusted input: anything unknown must fall back to the shipped layout rather
40
- * than leaving the nav carrying an attribute no CSS matches.
41
- * @param value - whatever the config surface served.
42
- * @returns one of `ALIGN_MODES`, defaulting to `start`.
43
- */
44
- export function normalizeAlign(value: unknown): AlignMode {
45
- return typeof value === 'string' && (ALIGN_MODES as readonly string[]).includes(value)
46
- ? (value as AlignMode)
47
- : 'start'
48
- }
49
-
50
- /**
51
- * The row surface this plugin actually uses.
52
- *
53
- * Deliberately narrower than `HTMLElement`: the pure seams (row split, nav
54
- * lookup) are unit-tested against stubs of exactly this shape, and every real
55
- * `HTMLElement` satisfies it. Anything wider would be an untested promise.
56
- */
57
- /** One sidebar panel row as the settings card shows it. */
58
- export interface RowInfo {
59
- /** The row's accessible name (its aria-label), which is also what config stores. */
60
- label: string
61
- /** True when the row is kept visible while the group is folded. */
62
- keep: boolean
63
- }
64
-
65
- export interface RowLike {
66
- getAttribute(name: string): string | null
67
- setAttribute(name: string, value: string): void
68
- removeAttribute(name: string): void
69
- addEventListener(type: string, listener: (event: any) => void): void
70
- readonly textContent: string | null
71
- readonly isConnected: boolean
72
- readonly parentElement?: RowLike | null
73
- querySelector?(selector: string): RowLike | null
74
- querySelectorAll?(selector: string): NodeListOf<Element>
75
- matches?(selector: string): boolean
76
- closest?(selector: string): Element | null
77
- }
78
-
79
- /** A queryable subtree (the real `document`, or a stub with the two query faces). */
80
- type QueryRoot = {
81
- querySelector(sel: string): unknown
82
- querySelectorAll(sel: string): readonly unknown[]
83
- }
84
- type ElementLike = RowLike
85
-
86
- /** What a mounted nav remembers so a re-scan is idempotent. */
87
- interface Mount {
88
- nav: ElementLike
89
- header: ElementLike
90
- toggle: ElementLike
91
- dispose: () => void
92
- }
93
-
94
- /** The single live mount (this plugin owns exactly one sidebar). */
95
- let mount: Mount | null = null
96
- /** Whether the group is folded; `null` = never decided in this window yet. */
97
- let folded: boolean | null = null
98
- /** Last config the fold was applied with (also read by the settings card). */
99
- let config: ConfigLike = { defaultFolded: false, keepLabels: [], align: 'start' }
100
- /** Registered so `index.ts` can notify the fold after a settings write. */
101
- const configListeners = new Set<() => void>()
102
-
103
- /**
104
- * Read the folded flag for this window.
105
- * @returns the stored flag, or the configured default when nothing is stored.
106
- */
107
- function currentFolded(): boolean {
108
- return folded === null ? config.defaultFolded : folded
109
- }
110
-
111
- /** Write the folded flag through to `localStorage` (window-level UI state). */
112
- function persist(next: boolean): void {
113
- try {
114
- window.localStorage.setItem(STORAGE_KEY, next ? '1' : '0')
115
- } catch {
116
- // Private mode / disabled storage: the session still folds, it just won't
117
- // survive a reload. Never let storage break the sidebar.
118
- }
119
- }
120
-
121
- /** Parse the persisted flag once per window. */
122
- function readStored(): void {
123
- let raw: string | null = null
124
- try {
125
- raw = window.localStorage.getItem(STORAGE_KEY)
126
- } catch {
127
- raw = null
128
- }
129
- folded = raw === '1' ? true : raw === '0' ? false : null
130
- }
131
-
132
- /** The accessible name of a row: `aria-label` first, then its text content. */
133
- function labelOf(row: ElementLike): string {
134
- return (row.getAttribute('aria-label') || row.textContent || '').trim()
135
- }
136
-
137
- /** True when a label is in the "never fold" list (case/whitespace tolerant). */
138
- export function isKept(label: string, keepLabels: readonly string[]): boolean {
139
- const needle = label.trim().toLowerCase()
140
- if (needle === '') return true
141
- return keepLabels.some((item) => item.trim().toLowerCase() === needle)
142
- }
143
-
144
- /**
145
- * Split an ordered row list into the fold header and the fold group.
146
- *
147
- * The header is the row with `aria-haspopup="menu"` (the More launcher); with
148
- * the shipped DOM that is also always the last child, so the fallback keeps
149
- * working if a host ever drops the attribute. The group is every other row,
150
- * minus the `keepLabels` whitelist.
151
- * @param rows - the nav's `panelRow` buttons, in document order.
152
- * @param keepLabels - accessible names that are never folded.
153
- * @returns the header plus the foldable group, or `null` when there is nothing to fold.
154
- */
155
- export function splitRows(
156
- rows: readonly ElementLike[],
157
- keepLabels: readonly string[],
158
- ): { header: ElementLike; group: ElementLike[] } | null {
159
- if (rows.length < 2) return null
160
- const header = rows.find((row) => row.getAttribute('aria-haspopup') === 'menu') ?? rows[rows.length - 1]
161
- const group = rows.filter((row) => row !== header && !isKept(labelOf(row), keepLabels))
162
- return { header, group }
163
- }
164
-
165
- /**
166
- * Locate the "Global panels" nav.
167
- *
168
- * Three levels, most semantic first: the nav's own accessible name, any element
169
- * whose CSS-module fragment is `_panelList`, then any `<nav>` holding a
170
- * `_panelRow` button. Returns `null` when nothing matches — the caller then
171
- * leaves the sidebar exactly as shipped.
172
- */
173
- export function findPanelNav(root: QueryRoot): ElementLike | null {
174
- for (const label of PANELS_LABELS) {
175
- const byLabel = root.querySelector(`nav[aria-label="${label}"]`)
176
- if (byLabel !== null) return byLabel as ElementLike
177
- }
178
- const byFragment = root.querySelectorAll(SEL.panelList)
179
- for (const candidate of Array.from(byFragment) as ElementLike[]) {
180
- if (candidate.querySelector?.(SEL.panelRow) !== null) return candidate
181
- }
182
- for (const candidate of Array.from(root.querySelectorAll('nav')) as ElementLike[]) {
183
- if (candidate.querySelector?.(SEL.panelRow) !== null) return candidate
184
- }
185
- return null
186
- }
187
-
188
- /** Read the nav's panel rows, in document order. */
189
- function rowsOf(nav: ElementLike): ElementLike[] {
190
- return Array.from(nav.querySelectorAll?.(SEL.panelRow) ?? []) as ElementLike[]
191
- }
192
-
193
- /** Apply {@link splitRows} to a live nav. */
194
- function resolveNavGroup(nav: ElementLike, keepLabels: readonly string[]) {
195
- return splitRows(rowsOf(nav), keepLabels)
196
- }
197
-
198
- /**
199
- * What one apply pass should do — computed without touching the DOM.
200
- *
201
- * Pulled out of `applyFold` so the decision (which rows fold, whether the control
202
- * is idle, whether the rail suppresses it) is testable without a browser. The
203
- * renderer below only writes what this returns.
204
- */
205
- export interface FoldPlan {
206
- /** The row that carries the toggle (the shipped More row). */
207
- header: ElementLike
208
- /** Sibling rows that are not kept visible. */
209
- group: ElementLike[]
210
- /** True when every sibling is kept: nothing to fold, control reports itself idle. */
211
- idle: boolean
212
- /** The fold actually takes effect (folded, not idle, not in the 36px rail). */
213
- active: boolean
214
- /** Rows that must carry the folded mark. */
215
- folded: ElementLike[]
216
- /** Nav-level state mark, or null when the attribute should be absent. */
217
- state: 'folded' | null
218
- /** False in the rail: a 36px column has no room for a second 28px square. */
219
- toggleVisible: boolean
220
- }
221
-
222
- /**
223
- * Decide the fold for one scan.
224
- * @param rows - the nav's panel rows, in document order.
225
- * @param keepLabels - rows that stay visible while the group folds.
226
- * @param folded - the window's current fold choice.
227
- * @param rail - whether the sidebar is currently the 36px icon rail.
228
- * @returns the plan, or `null` when there is no header/group to work with.
229
- */
230
- export function planFold(
231
- rows: readonly ElementLike[],
232
- keepLabels: readonly string[],
233
- folded: boolean,
234
- rail: boolean,
235
- ): FoldPlan | null {
236
- const resolved = splitRows(rows, keepLabels)
237
- if (resolved === null) return null
238
- const { header, group } = resolved
239
- const idle = group.length === 0
240
- const active = folded && !rail && !idle
241
- return {
242
- header,
243
- group,
244
- idle,
245
- active,
246
- folded: active ? group : [],
247
- state: active ? 'folded' : null,
248
- toggleVisible: !rail,
249
- }
250
- }
251
-
252
- /** Listeners the settings card registers to repaint when the sidebar changes. */
253
- const rosterListeners = new Set<() => void>()
254
- /** Last roster fingerprint, so we only notify on real change. */
255
- let rosterKey = ''
256
-
257
- /**
258
- * The fold group as the settings card shows it: every sibling panel row of the
259
- * "More" header, with whether it is currently kept visible.
260
- *
261
- * This is read from the **live DOM**, not from config: the point of the card is
262
- * to offer switches for whatever entries this profile actually has, including
263
- * ones installed after the card was written.
264
- * @returns one entry per foldable row, in document order.
265
- */
266
- export function roster(): RowInfo[] {
267
- const nav = findPanelNav(document as unknown as QueryRoot)
268
- if (nav === null) return []
269
- return rosterFrom(rowsOf(nav), config.keepLabels)
270
- }
271
-
272
- /**
273
- * The card's row list, computed from a row array instead of the live DOM.
274
- * @param rows - the nav's panel rows, in document order.
275
- * @param keepLabels - rows currently kept visible.
276
- * @returns one entry per sibling of the header, unnamed rows dropped.
277
- */
278
- export function rosterFrom(rows: readonly ElementLike[], keepLabels: readonly string[]): RowInfo[] {
279
- const resolved = splitRows(rows, keepLabels)
280
- const header = resolved?.header
281
- return rows
282
- .filter((row) => row !== header)
283
- .map((row) => ({ label: labelOf(row), keep: isKept(labelOf(row), keepLabels) }))
284
- .filter((row) => row.label !== '')
285
- }
286
-
287
- /**
288
- * Fold the per-row switches into the stored keep list.
289
- *
290
- * The switch state IS the storage: switched-on rows are the kept ones, so a row
291
- * that disappeared from the sidebar drops out and a new row starts folded.
292
- * @param rows - the roster the card rendered.
293
- * @param label - the row whose switch moved.
294
- * @param next - its new state.
295
- * @returns the labels to write to `keepLabels`.
296
- */
297
- export function deriveKeep(rows: readonly RowInfo[], label: string, next: boolean): string[] {
298
- return rows
299
- .filter((row) => (row.label === label ? next : row.keep))
300
- .map((row) => row.label)
301
- }
302
-
303
- /**
304
- * Subscribe to roster changes (rows added/removed, or keep flags recomputed).
305
- * @param listener - called whenever the card should repaint.
306
- * @returns an unsubscribe function.
307
- */
308
- export function subscribeRoster(listener: () => void): () => void {
309
- rosterListeners.add(listener)
310
- return () => {
311
- rosterListeners.delete(listener)
312
- }
313
- }
314
-
315
- /** Tell the card that the row inventory (or its keep flags) changed. */
316
- function notifyRoster(rows: RowInfo[]): void {
317
- const key = rows.map((row) => `${row.label}:${row.keep ? 1 : 0}`).join('|')
318
- if (key === rosterKey) return
319
- rosterKey = key
320
- for (const listener of Array.from(rosterListeners)) {
321
- try {
322
- listener()
323
- } catch {
324
- // A broken card must not take the fold with it.
325
- }
326
- }
327
- }
328
-
329
- /** The narrow-rail state: the host hides labels and every row is 36px wide. */
330
- function isRail(nav: ElementLike): boolean {
331
- return nav.closest?.(SEL.collapsed) !== null && nav.closest?.(SEL.collapsed) !== undefined
332
- }
333
-
334
- /** Inject (once) the sheet that draws the toggle and hides folded rows. */
335
- function ensureSheet(): HTMLStyleElement | null {
336
- const existing = document.head.querySelector(`style[data-plugin-css="${STYLE_TAG_ID}"]`)
337
- if (existing !== null) return existing as HTMLStyleElement
338
- const tag = document.createElement('style')
339
- tag.dataset.pluginCss = STYLE_TAG_ID
340
- tag.dataset.plugin = STYLE_TAG_ID.split('/')[0] as string
341
- tag.textContent = SHEET
342
- document.head.appendChild(tag)
343
- return tag
344
- }
345
-
346
- /** Build the chevron SVG (self-drawn: the host `primitives` package is off-limits). */
347
- function buildIcon(pointUp: boolean): SVGSVGElement {
348
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
349
- svg.setAttribute('width', String(ICON_PX))
350
- svg.setAttribute('height', String(ICON_PX))
351
- svg.setAttribute('viewBox', '0 0 16 16')
352
- svg.setAttribute('fill', 'none')
353
- svg.setAttribute('stroke', 'currentColor')
354
- svg.setAttribute('stroke-width', '1.25')
355
- svg.setAttribute('stroke-linecap', 'round')
356
- svg.setAttribute('stroke-linejoin', 'round')
357
- svg.setAttribute('aria-hidden', 'true')
358
- svg.classList.add(CLS.icon)
359
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
360
- path.setAttribute('d', pointUp ? ICON_PATH.up : ICON_PATH.down)
361
- svg.appendChild(path)
362
- return svg
363
- }
364
-
365
- /** What the toggle currently shows, so a repaint only happens when it must. */
366
- let paintedKey = ''
367
- /** When a pointer gesture last activated us (guards against a second `click`). */
368
- let lastPointerActivation = 0
369
-
370
- /**
371
- * Repaint the toggle: arrow up = "can collapse", arrow down = "can expand".
372
- *
373
- * Repainting is **idempotent and skipped when nothing changed**. The first
374
- * implementation rebuilt the chevron on every scan; scans run on every DOM
375
- * mutation, so the `<svg>` could be replaced between `mousedown` and `mouseup` —
376
- * and a click whose press/release targets no longer exist is dropped by the
377
- * browser (measured: ~half of real clicks silently ignored).
378
- */
379
- function paintToggle(toggle: ElementLike, options: { idle?: boolean }): void {
380
- const lang = document.documentElement.lang ?? ''
381
- const isFolded = currentFolded()
382
- const key = `${isFolded ? '1' : '0'}|${lang}|${options.idle === true ? 'idle' : 'live'}`
383
- if (key === paintedKey && (toggle as HTMLElement).firstElementChild !== null) return
384
- paintedKey = key
385
- const dict = pickDictionary(lang)
386
- ;(toggle as HTMLElement).replaceChildren(buildIcon(!isFolded))
387
- const label = options.idle === true
388
- ? dict['fold.nothing']
389
- : isFolded ? dict['fold.expand'] : dict['fold.collapse']
390
- toggle.setAttribute('aria-expanded', String(!isFolded))
391
- toggle.setAttribute('aria-label', label)
392
- toggle.setAttribute('title', label)
393
- }
394
-
395
- /**
396
- * Write the fold marks. Only attributes we own are touched: no host class,
397
- * no host attribute, and never the anchor's `aria-expanded` (that one is the
398
- * dropdown menu's state, not ours).
399
- */
400
- function applyFold(): void {
401
- if (mount === null) return
402
- const rows = rowsOf(mount.nav)
403
- const plan = planFold(rows, config.keepLabels, currentFolded(), isRail(mount.nav))
404
- if (plan === null) return
405
- const { header } = plan
406
- if (header.getAttribute(ATTR.header) === null) header.setAttribute(ATTR.header, '')
407
- // Alignment is one nav-level mark with three rule sets behind it. Written on
408
- // every scan (and only when it differs) so a settings write repaints the row
409
- // content without a remount.
410
- const align = normalizeAlign(config.align)
411
- if (mount.nav.getAttribute(ATTR.align) !== align) mount.nav.setAttribute(ATTR.align, align)
412
-
413
- // The settings card renders whatever is on screen right now; keep it in sync.
414
- notifyRoster(rosterFrom(rows, config.keepLabels))
415
-
416
- // Nothing to fold (every sibling is kept): say so on the control instead of
417
- // flipping the arrow over an unchanged list — the first report of "arrow moves
418
- // but nothing collapses" was exactly this state, caused by a config write.
419
- ;(mount.toggle as HTMLElement).classList.toggle(CLS.toggleIdle, plan.idle)
420
- mount.toggle.setAttribute('aria-disabled', plan.idle ? 'true' : 'false')
421
-
422
- for (const row of rows) {
423
- const want = plan.folded.includes(row)
424
- // Touch an attribute only when it actually changes: every write is a
425
- // mutation, and every mutation triggers the rescan that caused this write.
426
- if (want && !row.getAttribute(ATTR.folded)) row.setAttribute(ATTR.folded, '')
427
- else if (!want && row.getAttribute(ATTR.folded) !== null) row.removeAttribute(ATTR.folded)
428
- }
429
- // The plan owns the idle case too: an idle control carries no state mark.
430
- if (plan.state !== null && mount.nav.getAttribute(ATTR.state) !== plan.state) mount.nav.setAttribute(ATTR.state, plan.state)
431
- else if (plan.state === null && mount.nav.getAttribute(ATTR.state) !== null) mount.nav.removeAttribute(ATTR.state)
432
- // A 36px rail has no room for a second 28px square: hand the row back to the host.
433
- ;(mount.toggle as HTMLElement).style.display = plan.toggleVisible ? 'inline-flex' : 'none'
434
- paintToggle(mount.toggle, { idle: plan.idle })
435
- }
436
- /** Toggle the group and persist the choice. */
437
- function toggleFold(): void {
438
- // An empty group must not pretend to fold: ignore the gesture entirely.
439
- if (mount !== null) {
440
- const resolved = resolveNavGroup(mount.nav, config.keepLabels)
441
- if (resolved !== null && resolved.group.length === 0) return
442
- }
443
- folded = !currentFolded()
444
- persist(folded)
445
- applyFold()
446
- }
447
-
448
- /**
449
- * Bind the toggle's input surface.
450
- *
451
- * Activation rides on **`pointerup`**, not on `click`: the host re-renders the
452
- * sidebar constantly, and a click whose press target was replaced mid-gesture is
453
- * never dispatched. `pointerup` always fires on the element under the pointer.
454
- * The `click` handler stays for keyboard activation (Enter/Space) and as the
455
- * fallback when this run predates Pointer Events.
456
- */
457
- function bindToggle(toggle: ElementLike): void {
458
- const stop = (event: Event): void => {
459
- event.stopPropagation()
460
- }
461
- const activate = (event: Event): void => {
462
- event.preventDefault()
463
- event.stopPropagation()
464
- lastPointerActivation = Date.now()
465
- toggleFold()
466
- }
467
- // Keep the host's own menu/dismiss logic out of our gesture.
468
- for (const type of ['pointerdown', 'mousedown', 'dblclick']) toggle.addEventListener(type, stop as (event: Event) => void)
469
- toggle.addEventListener('pointerup', (event: PointerEvent) => {
470
- if (event.button !== 0 && event.button !== undefined) return
471
- activate(event)
472
- })
473
- if (typeof PointerEvent === 'undefined') {
474
- toggle.addEventListener('mouseup', activate as (event: Event) => void)
475
- }
476
- toggle.addEventListener('click', (event: MouseEvent) => {
477
- event.stopPropagation()
478
- // A click that follows our own pointerup is the same gesture — ignore it.
479
- if (Date.now() - lastPointerActivation < 500) return
480
- event.preventDefault()
481
- toggleFold()
482
- })
483
- toggle.addEventListener('keydown', (event: KeyboardEvent) => {
484
- if (event.key === 'Enter' || event.key === ' ' || event.key === 'Spacebar') activate(event)
485
- })
486
- }
487
-
488
- /** Create the toggle as a sibling of the More anchor, inside the `_moreAnchor` span. */
489
- function buildToggle(): ElementLike {
490
- const toggle = document.createElement('div')
491
- toggle.className = CLS.toggle
492
- toggle.setAttribute('role', 'button')
493
- toggle.setAttribute('tabindex', '0')
494
- toggle.setAttribute(ATTR.own, '')
495
- // A fresh node has no icon yet, so the paint-dedupe key must not suppress it.
496
- paintedKey = ''
497
- bindToggle(toggle as ElementLike)
498
- return toggle as ElementLike
499
- }
500
-
501
- /** Tear down a live mount: remove our nodes and every attribute we wrote. */
502
- function unmount(): void {
503
- if (mount === null) return
504
- const { nav, header, toggle, dispose } = mount
505
- dispose()
506
- ;(toggle as HTMLElement).remove()
507
- nav.removeAttribute(ATTR.state)
508
- nav.removeAttribute(ATTR.align)
509
- header.removeAttribute(ATTR.header)
510
- for (const row of Array.from(nav.querySelectorAll?.(`[${ATTR.folded}]`) ?? []) as ElementLike[]) {
511
- row.removeAttribute(ATTR.folded)
512
- }
513
- mount = null
514
- }
515
-
516
- /**
517
- * Mount (or re-mount) the fold over the current sidebar DOM.
518
- *
519
- * Called on activation and after every DOM mutation. Idempotent: an existing
520
- * healthy mount whose header is still in the document is left untouched.
521
- * @returns whether a mount is live after the call.
522
- */
523
- export function rescan(): boolean {
524
- const nav = findPanelNav(document as unknown as QueryRoot)
525
- if (nav === null) {
526
- unmount()
527
- return false
528
- }
529
- const resolved = resolveNavGroup(nav, config.keepLabels)
530
- if (resolved === null) {
531
- unmount()
532
- return false
533
- }
534
- const stillHealthy =
535
- mount !== null && mount.nav === nav && mount.header.isConnected && mount.toggle.isConnected
536
- if (stillHealthy && mount !== null) {
537
- applyFold()
538
- return true
539
- }
540
- unmount()
541
- const { header } = resolved
542
- const anchor = header.parentElement as ElementLike | null
543
- if (anchor === null || anchor === undefined || anchor.matches?.(SEL.moreAnchor) !== true) {
544
- // Without the Menu host element we would have to nest a button inside the
545
- // host's button, or restyle a flex column: refuse rather than guess.
546
- return false
547
- }
548
- ensureSheet()
549
- const toggle = buildToggle()
550
- // The anchor span is the `Menu` host element: React only re-sets its *class*
551
- // there, so appending a sibling survives re-renders — and because we position
552
- // the toggle off the header row instead, the Menu's own anchor box (and thus
553
- // the portal menu's offset) keeps the exact height the host measures.
554
- ;(anchor as HTMLElement).appendChild(toggle as HTMLElement)
555
- mount = { nav, header, toggle, dispose: () => {} }
556
- applyFold()
557
- return true
558
- }
559
-
560
- /**
561
- * Remove every artifact this plugin may have left in the DOM, including ones a
562
- * previous activation left behind.
563
- *
564
- * Disable→enable (or any HMR remount) runs `apply` again without a guaranteed
565
- * teardown of the old mount first; without this sweep each cycle stacked another
566
- * invisible toggle on the same coordinate (measured: 3 ghosts after 2 cycles).
567
- */
568
- function sweep(): void {
569
- for (const node of Array.from(document.querySelectorAll(`.${CLS.toggle}[${ATTR.own}]`))) node.remove()
570
- for (const nav of Array.from(document.querySelectorAll(`[${ATTR.header}], [${ATTR.state}], [${ATTR.align}]`)) as ElementLike[]) {
571
- nav.removeAttribute(ATTR.header)
572
- nav.removeAttribute(ATTR.state)
573
- nav.removeAttribute(ATTR.align)
574
- }
575
- for (const row of Array.from(document.querySelectorAll(`[${ATTR.folded}]`)) as ElementLike[]) {
576
- row.removeAttribute(ATTR.folded)
577
- }
578
- mount = null
579
- }
580
-
581
- /**
582
- * Install the fold and keep it installed across re-renders.
583
- * @param cfg - the effective configuration.
584
- * @returns a disposer that leaves the sidebar exactly as shipped.
585
- */
586
- export function installFold(cfg: ConfigLike): () => void {
587
- config = { defaultFolded: cfg.defaultFolded, keepLabels: [...cfg.keepLabels], align: normalizeAlign(cfg.align) }
588
- readStored()
589
- sweep()
590
- let observer: MutationObserver | null = null
591
- let queued = false
592
- let retryTimer: ReturnType<typeof setTimeout> | null = null
593
- let attempts = 0
594
- const schedule = (): void => {
595
- if (queued) return
596
- queued = true
597
- setTimeout(() => {
598
- queued = false
599
- rescan()
600
- }, 16)
601
- }
602
- /**
603
- * Boot retry: the sidebar can mount after this plugin, and a hidden/background
604
- * window never fires `requestAnimationFrame` (measured: the first scan missed
605
- * and every later rescan was queued on a frozen rAF, leaving the plugin inert
606
- * until a manual remount). A plain timer has no such freeze.
607
- */
608
- const retryUntilMounted = (): void => {
609
- if (mount !== null || attempts >= 40) return
610
- attempts += 1
611
- rescan()
612
- if (mount === null) retryTimer = setTimeout(retryUntilMounted, 250)
613
- }
614
- rescan()
615
- retryTimer = setTimeout(retryUntilMounted, 100)
616
- if (typeof MutationObserver === 'function') {
617
- // `attributes` matters: collapsing the sidebar only flips a `class` on an
618
- // ancestor, and the childList mutations of that same commit can land before
619
- // the class change (measured) — watching only children read a stale rail.
620
- observer = new MutationObserver(schedule)
621
- observer.observe(document.body, {
622
- childList: true,
623
- subtree: true,
624
- attributes: true,
625
- attributeFilter: ['class'],
626
- })
627
- }
628
- const onConfig = (): void => {
629
- schedule()
630
- }
631
- configListeners.add(onConfig)
632
- return () => {
633
- configListeners.delete(onConfig)
634
- if (retryTimer !== null) clearTimeout(retryTimer)
635
- observer?.disconnect()
636
- unmount()
637
- document.head.querySelector(`style[data-plugin-css="${STYLE_TAG_ID}"]`)?.remove()
638
- }
639
- }
640
-
641
- /**
642
- * Adopt a freshly served configuration (settings write, or first read) and
643
- * repaint immediately — no restart, no reload.
644
- */
645
- export function applyConfig(cfg: ConfigLike): void {
646
- config = { defaultFolded: cfg.defaultFolded, keepLabels: [...cfg.keepLabels], align: normalizeAlign(cfg.align) }
647
- for (const listener of Array.from(configListeners)) listener()
648
- applyFold()
649
- }
650
-
651
- /** The configuration the fold is currently running with (settings card reads it). */
652
- export function effectiveConfig(): ConfigLike {
653
- return { defaultFolded: config.defaultFolded, keepLabels: [...config.keepLabels], align: normalizeAlign(config.align) }
654
- }
655
-
656
- /** Built-in defaults, used when a host serves no writable configuration surface. */
657
- export const BUILTIN_CONFIG: ConfigLike = { defaultFolded: false, keepLabels: ['插件', 'Plugins'], align: 'start' }
1
+ /**
2
+ * The fold itself: locate the shipped "More" row, decide which sibling panel
3
+ * rows belong to the group, and mount a 28×28 toggle that folds them away.
4
+ *
5
+ * Why DOM and not a slot (findings §1/§2): the row is hardcoded in
6
+ * `SidebarRoot` (`dsh-client-ui-sidebar/lib/client.js:479`) and no slot projects
7
+ * into it — `sidebar.panellist` only projects icons, `sidebar.panellist.actions`
8
+ * only fills the dropdown menu, and registering the `sidebar` single slot would
9
+ * shadow the whole column. A client plugin that owns only DOM additions is the
10
+ * one distributable route.
11
+ *
12
+ * The header is found **structurally**: within the "Global panels" nav the
13
+ * `panelRow` carrying `aria-haspopup="menu"` is the More row (it is the last
14
+ * child by construction), which keeps the logic free of localised text.
15
+ */
16
+ import {
17
+ ALIGN_MODES,
18
+ ATTR,
19
+ CLS,
20
+ FIXED_LABELS,
21
+ ICON_PATH,
22
+ ICON_PX,
23
+ PANELS_LABELS,
24
+ SEL,
25
+ SHEET,
26
+ STORAGE_KEY,
27
+ STYLE_TAG_ID,
28
+ type AlignMode,
29
+ } from './constants.ts'
30
+ import { pickDictionary } from './locales.ts'
31
+
32
+ /** Minimal DOM surface we touch — keeps the tests free of a DOM dependency. */
33
+ type ConfigLike = { defaultFolded: boolean; keepLabels: string[]; hideLabels: string[]; align: AlignMode }
34
+
35
+ /**
36
+ * Coerce a served alignment value into a mode the sheet has a rule for.
37
+ *
38
+ * The host config is a plain string (schemastery cannot express a closed union
39
+ * across every line this plugin supports), so the value reaching the browser is
40
+ * untrusted input: anything unknown must fall back to the shipped layout rather
41
+ * than leaving the nav carrying an attribute no CSS matches.
42
+ * @param value - whatever the config surface served.
43
+ * @returns one of `ALIGN_MODES`, defaulting to `start`.
44
+ */
45
+ export function normalizeAlign(value: unknown): AlignMode {
46
+ return typeof value === 'string' && (ALIGN_MODES as readonly string[]).includes(value)
47
+ ? (value as AlignMode)
48
+ : 'start'
49
+ }
50
+
51
+ /**
52
+ * What a sidebar row is set to do — the card's three-state control.
53
+ *
54
+ * `always` keeps the row in the column at all times, `foldable` lets the fold hide
55
+ * it, and `more` hands it to the host's own "More" list (the 0.2.2 pin feature).
56
+ */
57
+ export type RowState = 'always' | 'foldable' | 'more'
58
+
59
+ /** One sidebar panel row as the settings card shows it. */
60
+ export interface RowInfo {
61
+ /** The row's accessible name (its aria-label), which is also what config stores. */
62
+ label: string
63
+ /** The row's current three-state setting. */
64
+ state: RowState
65
+ }
66
+
67
+ /**
68
+ * The row surface this plugin actually uses.
69
+ *
70
+ * Deliberately narrower than `HTMLElement`: the pure seams (row split, nav
71
+ * lookup) are unit-tested against stubs of exactly this shape, and every real
72
+ * `HTMLElement` satisfies it. Anything wider would be an untested promise.
73
+ */
74
+ export interface RowLike {
75
+ getAttribute(name: string): string | null
76
+ setAttribute(name: string, value: string): void
77
+ removeAttribute(name: string): void
78
+ addEventListener(type: string, listener: (event: any) => void): void
79
+ readonly textContent: string | null
80
+ readonly isConnected: boolean
81
+ readonly parentElement?: RowLike | null
82
+ querySelector?(selector: string): RowLike | null
83
+ querySelectorAll?(selector: string): NodeListOf<Element>
84
+ matches?(selector: string): boolean
85
+ closest?(selector: string): Element | null
86
+ /** DOM `Node.contains`, used to tell “the nav itself” from “a row inside it”. */
87
+ contains?(node: unknown): boolean
88
+ }
89
+
90
+ /** A queryable subtree (the real `document`, or a stub with the two query faces). */
91
+ type QueryRoot = {
92
+ querySelector(sel: string): unknown
93
+ querySelectorAll(sel: string): readonly unknown[]
94
+ }
95
+ type ElementLike = RowLike
96
+
97
+ /** What a mounted nav remembers so a re-scan is idempotent. */
98
+ interface Mount {
99
+ nav: ElementLike
100
+ header: ElementLike
101
+ toggle: ElementLike
102
+ dispose: () => void
103
+ }
104
+
105
+ /** The single live mount (this plugin owns exactly one sidebar). */
106
+ let mount: Mount | null = null
107
+ /** Whether the group is folded; `null` = never decided in this window yet. */
108
+ let folded: boolean | null = null
109
+ /** Last config the fold was applied with (also read by the settings card). */
110
+ let config: ConfigLike = { defaultFolded: false, keepLabels: [], hideLabels: [], align: 'start' }
111
+ /** Registered so `index.ts` can notify the fold after a settings write. */
112
+ const configListeners = new Set<() => void>()
113
+
114
+ /**
115
+ * Read the folded flag for this window.
116
+ * @returns the stored flag, or the configured default when nothing is stored.
117
+ */
118
+ function currentFolded(): boolean {
119
+ return folded === null ? config.defaultFolded : folded
120
+ }
121
+
122
+ /** Write the folded flag through to `localStorage` (window-level UI state). */
123
+ function persist(next: boolean): void {
124
+ try {
125
+ window.localStorage.setItem(STORAGE_KEY, next ? '1' : '0')
126
+ } catch {
127
+ // Private mode / disabled storage: the session still folds, it just won't
128
+ // survive a reload. Never let storage break the sidebar.
129
+ }
130
+ }
131
+
132
+ /** Parse the persisted flag once per window. */
133
+ function readStored(): void {
134
+ let raw: string | null = null
135
+ try {
136
+ raw = window.localStorage.getItem(STORAGE_KEY)
137
+ } catch {
138
+ raw = null
139
+ }
140
+ folded = raw === '1' ? true : raw === '0' ? false : null
141
+ }
142
+
143
+ /** The accessible name of a row: `aria-label` first, then its text content. */
144
+ function labelOf(row: ElementLike): string {
145
+ return (row.getAttribute('aria-label') || row.textContent || '').trim()
146
+ }
147
+
148
+ /** True when a label is in the "never fold" list (case/whitespace tolerant). */
149
+ export function isKept(label: string, keepLabels: readonly string[]): boolean {
150
+ const needle = label.trim().toLowerCase()
151
+ if (needle === '') return true
152
+ return keepLabels.some((item) => item.trim().toLowerCase() === needle)
153
+ }
154
+
155
+ /**
156
+ * True when a label belongs to the host's fixed panel row.
157
+ *
158
+ * The host never unpins that row (`FIXED_PANEL_ID`), so the third state is not
159
+ * available for it on any line — offering it would be a promise the host
160
+ * silently refuses.
161
+ */
162
+ export function isFixedLabel(label: string): boolean {
163
+ const needle = label.trim().toLowerCase()
164
+ if (needle === '') return false
165
+ return FIXED_LABELS.some((item) => item.toLowerCase() === needle)
166
+ }
167
+
168
+ /**
169
+ * Whether one row may be handed to the host's "More" list.
170
+ *
171
+ * Two gates: the host must ship the pin mechanism at all, and the row must not
172
+ * be the fixed one.
173
+ * @param label - the row's accessible name.
174
+ * @param hostCanPin - whether this host renders the 0.2.2 row structure.
175
+ */
176
+ export function canMoveToMore(label: string, hostCanPin: boolean): boolean {
177
+ return hostCanPin && !isFixedLabel(label)
178
+ }
179
+
180
+ /**
181
+ * Drop fixed labels from a stored hide list.
182
+ *
183
+ * A config written by an older build (or hand-edited) may list the fixed row;
184
+ * ignoring it here keeps the fold from chasing a move the host will never do.
185
+ * @param hideLabels - the served hide list.
186
+ * @returns the same list without the host's fixed labels.
187
+ */
188
+ export function pruneHidden(hideLabels: readonly string[]): string[] {
189
+ return hideLabels.filter((label) => !isFixedLabel(label))
190
+ }
191
+
192
+ /**
193
+ * True when a label belongs to the host's "More" list (case/whitespace tolerant).
194
+ *
195
+ * An unnamed row is never hidden: the pin control is addressed by name, so a row
196
+ * we cannot name is a row we cannot move.
197
+ */
198
+ export function isHidden(label: string, hideLabels: readonly string[]): boolean {
199
+ const needle = label.trim().toLowerCase()
200
+ if (needle === '' || isFixedLabel(label)) return false
201
+ return hideLabels.some((item) => item.trim().toLowerCase() === needle)
202
+ }
203
+
204
+ /**
205
+ * One label's three-state setting, resolved from the two stored lists.
206
+ *
207
+ * `more` wins over `always`: a label that somehow sits in both lists must leave
208
+ * the column rather than be silently resurrected by the keep list.
209
+ */
210
+ export function stateOf(label: string, keepLabels: readonly string[], hideLabels: readonly string[]): RowState {
211
+ if (isHidden(label, hideLabels)) return 'more'
212
+ return isKept(label, keepLabels) ? 'always' : 'foldable'
213
+ }
214
+
215
+ /**
216
+ * Split an ordered row list into the fold header and the fold group.
217
+ *
218
+ * The header is the row with `aria-haspopup="menu"` (the More launcher); with
219
+ * the shipped DOM that is also always the last child, so the fallback keeps
220
+ * working if a host ever drops the attribute. The group is every other row,
221
+ * minus the `keepLabels` whitelist and minus the `hideLabels` rows (those are on
222
+ * their way into the host's More list and must not count as foldable).
223
+ * @param rows - the nav's `panelRow` buttons, in document order.
224
+ * @param keepLabels - accessible names that are never folded.
225
+ * @param hideLabels - accessible names that live in the host's "More" list.
226
+ * @returns the header plus the foldable group, or `null` when there is nothing to fold.
227
+ */
228
+ export function splitRows(
229
+ rows: readonly ElementLike[],
230
+ keepLabels: readonly string[],
231
+ hideLabels: readonly string[] = [],
232
+ ): { header: ElementLike; group: ElementLike[] } | null {
233
+ if (rows.length < 2) return null
234
+ const header = rows.find((row) => row.getAttribute('aria-haspopup') === 'menu') ?? rows[rows.length - 1]
235
+ const group = rows.filter((row) => {
236
+ if (row === header) return false
237
+ const label = labelOf(row)
238
+ return !isKept(label, keepLabels) && !isHidden(label, hideLabels)
239
+ })
240
+ return { header, group }
241
+ }
242
+
243
+ /**
244
+ * Locate the "Global panels" nav.
245
+ *
246
+ * Three levels, most semantic first: the nav's own accessible name, any element
247
+ * whose CSS-module fragment is `_panelList`, then any `<nav>` holding a
248
+ * `_panelRow` button. Returns `null` when nothing matches — the caller then
249
+ * leaves the sidebar exactly as shipped.
250
+ */
251
+ export function findPanelNav(root: QueryRoot): ElementLike | null {
252
+ for (const label of PANELS_LABELS) {
253
+ const byLabel = root.querySelector(`nav[aria-label="${label}"]`)
254
+ if (byLabel !== null) return byLabel as ElementLike
255
+ }
256
+ const byFragment = root.querySelectorAll(SEL.panelList)
257
+ for (const candidate of Array.from(byFragment) as ElementLike[]) {
258
+ if (candidate.querySelector?.(SEL.panelRow) !== null) return candidate
259
+ }
260
+ for (const candidate of Array.from(root.querySelectorAll('nav')) as ElementLike[]) {
261
+ if (candidate.querySelector?.(SEL.panelRow) !== null) return candidate
262
+ }
263
+ return null
264
+ }
265
+
266
+ /** Read the nav's panel rows, in document order. */
267
+ function rowsOf(nav: ElementLike): ElementLike[] {
268
+ return Array.from(nav.querySelectorAll?.(SEL.panelRow) ?? []) as ElementLike[]
269
+ }
270
+
271
+ /** Apply {@link splitRows} to a live nav. */
272
+ function resolveNavGroup(nav: ElementLike, keepLabels: readonly string[], hideLabels: readonly string[]) {
273
+ return splitRows(rowsOf(nav), keepLabels, hideLabels)
274
+ }
275
+
276
+ /**
277
+ * What one apply pass should do — computed without touching the DOM.
278
+ *
279
+ * Pulled out of `applyFold` so the decision (which rows fold, whether the control
280
+ * is idle, whether the rail suppresses it) is testable without a browser. The
281
+ * renderer below only writes what this returns.
282
+ */
283
+ export interface FoldPlan {
284
+ /** The row that carries the toggle (the shipped More row). */
285
+ header: ElementLike
286
+ /** Sibling rows that are not kept visible. */
287
+ group: ElementLike[]
288
+ /** True when every sibling is kept: nothing to fold, control reports itself idle. */
289
+ idle: boolean
290
+ /** The fold actually takes effect (folded, not idle, not in the 36px rail). */
291
+ active: boolean
292
+ /** Rows that must carry the folded mark. */
293
+ folded: ElementLike[]
294
+ /** Nav-level state mark, or null when the attribute should be absent. */
295
+ state: 'folded' | null
296
+ /** False in the rail: a 36px column has no room for a second 28px square. */
297
+ toggleVisible: boolean
298
+ }
299
+
300
+ /**
301
+ * Decide the fold for one scan.
302
+ * @param rows - the nav's panel rows, in document order.
303
+ * @param keepLabels - rows that stay visible while the group folds.
304
+ * @param hideLabels - rows handed to the host's "More" list; never folded.
305
+ * @param folded - the window's current fold choice.
306
+ * @param rail - whether the sidebar is currently the 36px icon rail.
307
+ * @returns the plan, or `null` when there is no header/group to work with.
308
+ */
309
+ export function planFold(
310
+ rows: readonly ElementLike[],
311
+ keepLabels: readonly string[],
312
+ hideLabels: readonly string[],
313
+ folded: boolean,
314
+ rail: boolean,
315
+ ): FoldPlan | null {
316
+ const resolved = splitRows(rows, keepLabels, hideLabels)
317
+ if (resolved === null) return null
318
+ const { header, group } = resolved
319
+ const idle = group.length === 0
320
+ const active = folded && !rail && !idle
321
+ return {
322
+ header,
323
+ group,
324
+ idle,
325
+ active,
326
+ folded: active ? group : [],
327
+ state: active ? 'folded' : null,
328
+ toggleVisible: !rail,
329
+ }
330
+ }
331
+
332
+ /** Listeners the settings card registers to repaint when the sidebar changes. */
333
+ const rosterListeners = new Set<() => void>()
334
+ /** Last roster fingerprint, so we only notify on real change. */
335
+ let rosterKey = ''
336
+
337
+ /**
338
+ * The rows the settings card shows: the sidebar's own panel rows, the entries the
339
+ * host already holds in its "More" list, and every label we still hide but whose
340
+ * row is not on screen right now (the More list is portalled, so it only exists
341
+ * while it is open).
342
+ *
343
+ * This is read from the **live DOM**, not from config: the point of the card is
344
+ * to offer controls for whatever this profile actually has, including entries
345
+ * installed after the card was written.
346
+ * @returns one entry per manageable row, in document order.
347
+ */
348
+ export function roster(): RowInfo[] {
349
+ const nav = findPanelNav(document as unknown as QueryRoot)
350
+ const rows = nav === null ? [] : rosterFrom(rowsOf(nav), config.keepLabels, config.hideLabels)
351
+ const seen = new Set(rows.map((row) => row.label.toLowerCase()))
352
+ for (const entry of moreMenuRows()) {
353
+ if (seen.has(entry.label.toLowerCase())) continue
354
+ rows.push(entry)
355
+ seen.add(entry.label.toLowerCase())
356
+ }
357
+ // A label we still hide whose row is gone from both surfaces keeps its control:
358
+ // dropping it would silently drop the setting with it.
359
+ for (const label of config.hideLabels) {
360
+ const trimmed = label.trim()
361
+ if (trimmed === '' || seen.has(trimmed.toLowerCase())) continue
362
+ rows.push({ label: trimmed, state: 'more' })
363
+ seen.add(trimmed.toLowerCase())
364
+ }
365
+ return rows
366
+ }
367
+
368
+ /**
369
+ * The host's own "More" list, read from the portalled menu when it is open.
370
+ *
371
+ * The menu is rendered under `document.body`, so its rows never sit inside the
372
+ * nav and the nav scan can never see them. Each row is a menu item plus a
373
+ * `_pinButton` whose enclosing `div` owns the label text.
374
+ * @returns one entry per entry the host currently keeps out of the column.
375
+ */
376
+ export function moreMenuRows(): RowInfo[] {
377
+ const out: RowInfo[] = []
378
+ for (const button of Array.from(document.querySelectorAll(SEL.pinButton))) {
379
+ const label = ((button as Element).closest('div')?.textContent ?? '').trim()
380
+ if (label !== '') out.push({ label, state: 'more' })
381
+ }
382
+ return out
383
+ }
384
+
385
+ /**
386
+ * The card's row list, computed from a row array instead of the live DOM.
387
+ * @param rows - the nav's panel rows, in document order.
388
+ * @param keepLabels - rows set to stay visible.
389
+ * @param hideLabels - rows set to live in the host's "More" list.
390
+ * @returns one entry per sibling of the header, unnamed rows dropped.
391
+ */
392
+ export function rosterFrom(
393
+ rows: readonly ElementLike[],
394
+ keepLabels: readonly string[],
395
+ hideLabels: readonly string[] = [],
396
+ ): RowInfo[] {
397
+ const resolved = splitRows(rows, keepLabels, hideLabels)
398
+ const header = resolved?.header
399
+ return rows
400
+ .filter((row) => row !== header)
401
+ .map((row) => {
402
+ const label = labelOf(row)
403
+ return { label, state: stateOf(label, keepLabels, hideLabels) }
404
+ })
405
+ .filter((row) => row.label !== '')
406
+ }
407
+
408
+ /**
409
+ * Fold one row's moved control into the two stored lists.
410
+ *
411
+ * The control state IS the storage: `always` rows are the keep list, `more` rows
412
+ * are the hide list, and `foldable` rows appear in neither. A row that dropped
413
+ * out of the roster loses its entry, and a row that appears starts foldable —
414
+ * which is what the shipped default means.
415
+ * @param rows - the roster the card rendered.
416
+ * @param label - the row whose control moved.
417
+ * @param next - its new state.
418
+ * @returns the two label lists to write to config.
419
+ */
420
+ export function deriveLists(
421
+ rows: readonly RowInfo[],
422
+ label: string,
423
+ next: RowState,
424
+ ): { keepLabels: string[]; hideLabels: string[] } {
425
+ const keepLabels: string[] = []
426
+ const hideLabels: string[] = []
427
+ for (const row of rows) {
428
+ const state = row.label === label ? next : row.state
429
+ if (state === 'always') keepLabels.push(row.label)
430
+ else if (state === 'more') hideLabels.push(row.label)
431
+ }
432
+ return { keepLabels, hideLabels }
433
+ }
434
+
435
+ /**
436
+ * Subscribe to roster changes (rows added/removed, or keep flags recomputed).
437
+ * @param listener - called whenever the card should repaint.
438
+ * @returns an unsubscribe function.
439
+ */
440
+ export function subscribeRoster(listener: () => void): () => void {
441
+ rosterListeners.add(listener)
442
+ return () => {
443
+ rosterListeners.delete(listener)
444
+ }
445
+ }
446
+
447
+ /** Tell the card that the row inventory (or one row's state) changed. */
448
+ function notifyRoster(rows: RowInfo[]): void {
449
+ const key = rows.map((row) => `${row.label}:${row.state}`).join('|')
450
+ if (key === rosterKey) return
451
+ rosterKey = key
452
+ for (const listener of Array.from(rosterListeners)) {
453
+ try {
454
+ listener()
455
+ } catch {
456
+ // A broken card must not take the fold with it.
457
+ }
458
+ }
459
+ }
460
+
461
+ /** The narrow-rail state: the host hides labels and every row is 36px wide. */
462
+ function isRail(nav: ElementLike): boolean {
463
+ return nav.closest?.(SEL.collapsed) !== null && nav.closest?.(SEL.collapsed) !== undefined
464
+ }
465
+
466
+ /**
467
+ * True when this row holds the panel the host marks as current.
468
+ *
469
+ * Two signals, because the line changed shape: the shipped rows carry
470
+ * `aria-current="page"`, and from 0.2.2 on the wrapper carries
471
+ * `_panelEntryActive`.
472
+ * @param row - one panel-row button.
473
+ */
474
+ function isActiveRow(row: ElementLike): boolean {
475
+ if (row.getAttribute('aria-current') === 'page') return true
476
+ const entry = row.closest?.(SEL.panelEntry) as Element | null | undefined
477
+ return (entry?.className ?? '').includes('_panelEntryActive')
478
+ }
479
+
480
+ /**
481
+ * Whether a mutation batch could concern the sidebar at all.
482
+ *
483
+ * The observer sees the whole body, so the first thing every batch gets is this
484
+ * cheap filter: a streaming reply mutates the tree dozens of times per second,
485
+ * and none of it can change the fold. Only added/removed nodes that are (or
486
+ * contain) a panel row count.
487
+ * @param records - one observer batch.
488
+ * @returns true when at least one record adds or removes a panel row.
489
+ */
490
+ export function recordsTouchRows(
491
+ records: readonly { type?: string; addedNodes?: ArrayLike<unknown> | null; removedNodes?: ArrayLike<unknown> | null }[],
492
+ ): boolean {
493
+ for (const record of records) {
494
+ if (record.type !== undefined && record.type !== 'childList') continue
495
+ const nodes = [...Array.from(record.addedNodes ?? []), ...Array.from(record.removedNodes ?? [])]
496
+ for (const node of nodes) {
497
+ const element = node as ElementLike | null
498
+ if (element === null || typeof element !== 'object' || (element as unknown as Node).nodeType !== 1) continue
499
+ if (element.matches?.(SEL.panelRow) === true) return true
500
+ const inside = element.querySelector?.(SEL.panelRow)
501
+ if (inside !== null && inside !== undefined) return true
502
+ }
503
+ }
504
+ return false
505
+ }
506
+
507
+ /** Inject (once) the sheet that draws the toggle and hides folded rows. */
508
+ function ensureSheet(): HTMLStyleElement | null {
509
+ const existing = document.head.querySelector(`style[data-plugin-css="${STYLE_TAG_ID}"]`)
510
+ if (existing !== null) return existing as HTMLStyleElement
511
+ const tag = document.createElement('style')
512
+ tag.dataset.pluginCss = STYLE_TAG_ID
513
+ tag.dataset.plugin = STYLE_TAG_ID.split('/')[0] as string
514
+ tag.textContent = SHEET
515
+ document.head.appendChild(tag)
516
+ return tag
517
+ }
518
+
519
+ /** Build the chevron SVG (self-drawn: the host `primitives` package is off-limits). */
520
+ function buildIcon(pointUp: boolean): SVGSVGElement {
521
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
522
+ svg.setAttribute('width', String(ICON_PX))
523
+ svg.setAttribute('height', String(ICON_PX))
524
+ svg.setAttribute('viewBox', '0 0 16 16')
525
+ svg.setAttribute('fill', 'none')
526
+ svg.setAttribute('stroke', 'currentColor')
527
+ svg.setAttribute('stroke-width', '1.25')
528
+ svg.setAttribute('stroke-linecap', 'round')
529
+ svg.setAttribute('stroke-linejoin', 'round')
530
+ svg.setAttribute('aria-hidden', 'true')
531
+ svg.classList.add(CLS.icon)
532
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
533
+ path.setAttribute('d', pointUp ? ICON_PATH.up : ICON_PATH.down)
534
+ svg.appendChild(path)
535
+ return svg
536
+ }
537
+
538
+ /** What the toggle currently shows, so a repaint only happens when it must. */
539
+ let paintedKey = ''
540
+ /** When a pointer gesture last activated us (guards against a second `click`). */
541
+ let lastPointerActivation = 0
542
+
543
+ /**
544
+ * Repaint the toggle: arrow up = "can collapse", arrow down = "can expand".
545
+ *
546
+ * Repainting is **idempotent and skipped when nothing changed**. The first
547
+ * implementation rebuilt the chevron on every scan; scans run on every DOM
548
+ * mutation, so the `<svg>` could be replaced between `mousedown` and `mouseup` —
549
+ * and a click whose press/release targets no longer exist is dropped by the
550
+ * browser (measured: ~half of real clicks silently ignored).
551
+ */
552
+ function paintToggle(toggle: ElementLike, options: { idle?: boolean }): void {
553
+ const lang = document.documentElement.lang ?? ''
554
+ const isFolded = currentFolded()
555
+ const key = `${isFolded ? '1' : '0'}|${lang}|${options.idle === true ? 'idle' : 'live'}`
556
+ if (key === paintedKey && (toggle as HTMLElement).firstElementChild !== null) return
557
+ paintedKey = key
558
+ const dict = pickDictionary(lang)
559
+ ;(toggle as HTMLElement).replaceChildren(buildIcon(!isFolded))
560
+ const label = options.idle === true
561
+ ? dict['fold.nothing']
562
+ : isFolded ? dict['fold.expand'] : dict['fold.collapse']
563
+ toggle.setAttribute('aria-expanded', String(!isFolded))
564
+ toggle.setAttribute('aria-label', label)
565
+ toggle.setAttribute('title', label)
566
+ }
567
+
568
+ /**
569
+ * True when this host ships the 0.2.2 row wrapper, i.e. it owns the pin feature.
570
+ *
571
+ * The third state ("hide into More") is not ours to draw: the host removes the
572
+ * row from the column and renders it in its own menu. What we own is driving it,
573
+ * and the wrapper is the structure that says the host can be driven.
574
+ */
575
+ export function hostHasPin(): boolean {
576
+ return document.querySelector(SEL.panelEntry) !== null
577
+ }
578
+
579
+ /**
580
+ * The element a fold mark must hide.
581
+ *
582
+ * From the 0.2.2 line on, a row button is wrapped in `div._panelEntry` that also
583
+ * carries the host's own pin control; hiding only the button left an empty entry
584
+ * with a hover-visible pin behind (measured on 0.2.2-rc.3). Hiding the wrapper
585
+ * takes the whole row with it and leaves the shipped DOM untouched on older lines.
586
+ *
587
+ * Exported as a seam: it is the one line that decides whether the host's
588
+ * `.panelList { gap: 2px }` still sees an item, so the test has to reach it.
589
+ */
590
+ export function foldTarget(row: ElementLike): ElementLike {
591
+ return (row.closest?.(SEL.panelEntry) ?? row) as ElementLike
592
+ }
593
+
594
+ /** The host's own "unpin" control of one row, or `null` in the 36px rail. */
595
+ function unpinControl(row: ElementLike): HTMLElement | null {
596
+ const scope = foldTarget(row)
597
+ return (scope.querySelector?.(SEL.panelUnpin) ?? null) as HTMLElement | null
598
+ }
599
+
600
+ /** The label text of one row inside the portalled "More" list. */
601
+ function menuRowLabel(control: Element): string {
602
+ return (control.closest('div')?.textContent ?? '').trim()
603
+ }
604
+
605
+ /** One key form for label matching (the host writes labels, we compare them). */
606
+ function labelKey(label: string): string {
607
+ return label.trim().toLowerCase()
608
+ }
609
+
610
+ /** The "More" list's pin-back control for one label, when that list is on screen. */
611
+ function pinControl(label: string): HTMLElement | null {
612
+ const key = labelKey(label)
613
+ if (key === '') return null
614
+ for (const control of Array.from(document.querySelectorAll(SEL.pinButton))) {
615
+ if (labelKey(menuRowLabel(control)) === key) return control as HTMLElement
616
+ }
617
+ return null
618
+ }
619
+
620
+ /** One label we owe the host a move, with how many times we asked and when. */
621
+ const pinMoves = new Map<string, { tries: number; at: number }>()
622
+ /** Labels waiting for the host to put their row back into the column. */
623
+ const restoreWanted = new Map<string, number>()
624
+ /** One label is moved at most this often: every click re-renders the sidebar. */
625
+ const PIN_COOLDOWN_MS = 1000
626
+ /** Moves per label before this window gives up (a rail refuses, so stop asking). */
627
+ const PIN_MAX_TRIES = 3
628
+ /** How long a pin-back request waits for the list's pin control to render. */
629
+ const RESTORE_WINDOW_MS = 2000
630
+
631
+ /**
632
+ * Ask the host to move every `more` row out of the column.
633
+ *
634
+ * Only the host owns that decision (`setPinned` is not a plugin surface), so the
635
+ * move rides its own pin control. The call is bounded: at most {@link PIN_MAX_TRIES}
636
+ * clicks per label per window, at most one per {@link PIN_COOLDOWN_MS}, and never
637
+ * while the row is missing its control (the 36px rail renders none).
638
+ * @param rows - the nav's panel rows, in document order.
639
+ */
640
+ function moveRowsToMore(rows: readonly ElementLike[]): void {
641
+ if (!hostHasPin() || config.hideLabels.length === 0) return
642
+ const now = Date.now()
643
+ for (const row of rows) {
644
+ const label = labelOf(row)
645
+ if (!isHidden(label, config.hideLabels)) continue
646
+ const key = labelKey(label)
647
+ const move = pinMoves.get(key)
648
+ if (move !== undefined && (move.tries >= PIN_MAX_TRIES || now - move.at < PIN_COOLDOWN_MS)) continue
649
+ const control = unpinControl(row)
650
+ if (control === null) continue
651
+ pinMoves.set(key, { tries: (move?.tries ?? 0) + 1, at: now })
652
+ control.click()
653
+ }
654
+ }
655
+
656
+ /**
657
+ * Ask the host to pin rows back into the column.
658
+ *
659
+ * The pin-back control exists only inside the host's portalled "More" list, so
660
+ * this opens that list when needed and waits for the control to render: the
661
+ * sidebar's own mutation stream drives the retry, no timer of ours.
662
+ * @param rows - the nav's panel rows, in document order.
663
+ */
664
+ function pinRowsBack(rows: readonly ElementLike[]): void {
665
+ if (restoreWanted.size === 0) return
666
+ if (!hostHasPin()) {
667
+ restoreWanted.clear()
668
+ return
669
+ }
670
+ const now = Date.now()
671
+ const present = new Set(rows.map((row) => labelKey(labelOf(row))))
672
+ let missing = 0
673
+ for (const [key, at] of Array.from(restoreWanted)) {
674
+ // The row already came back (a restart drops the host's in-memory pins).
675
+ if (present.has(key)) {
676
+ restoreWanted.delete(key)
677
+ continue
678
+ }
679
+ if (now - at > RESTORE_WINDOW_MS) {
680
+ restoreWanted.delete(key)
681
+ continue
682
+ }
683
+ const control = pinControl(key)
684
+ if (control !== null) {
685
+ control.click()
686
+ restoreWanted.delete(key)
687
+ continue
688
+ }
689
+ missing += 1
690
+ }
691
+ if (missing > 0) openMoreList()
692
+ }
693
+
694
+ /** Open the host's "More" list if it is closed (idempotent through aria-expanded). */
695
+ function openMoreList(): void {
696
+ const anchor = document.querySelector(`${SEL.panelRow}[aria-haspopup="menu"]`)
697
+ if (anchor === null || anchor.getAttribute('aria-expanded') === 'true') return
698
+ ;(anchor as HTMLElement).click()
699
+ }
700
+
701
+ /**
702
+ * Write the fold marks. Only attributes we own are touched: no host class,
703
+ * no host attribute, and never the anchor's `aria-expanded` (that one is the
704
+ * dropdown menu's state, not ours).
705
+ */
706
+ function applyFold(): void {
707
+ if (mount === null) return
708
+ const rows = rowsOf(mount.nav)
709
+ const plan = planFold(rows, config.keepLabels, config.hideLabels, currentFolded(), isRail(mount.nav))
710
+ if (plan === null) return
711
+ const { header } = plan
712
+ if (header.getAttribute(ATTR.header) === null) header.setAttribute(ATTR.header, '')
713
+ // Alignment is one nav-level mark with three rule sets behind it. Written on
714
+ // every scan (and only when it differs) so a settings write repaints the row
715
+ // content without a remount.
716
+ const align = normalizeAlign(config.align)
717
+ if (mount.nav.getAttribute(ATTR.align) !== align) mount.nav.setAttribute(ATTR.align, align)
718
+
719
+ // The settings card renders whatever is on screen right now; keep it in sync.
720
+ notifyRoster(rosterFrom(rows, config.keepLabels, config.hideLabels))
721
+
722
+ // Nothing to fold (every sibling is kept): say so on the control instead of
723
+ // flipping the arrow over an unchanged list — the first report of "arrow moves
724
+ // but nothing collapses" was exactly this state, caused by a config write.
725
+ ;(mount.toggle as HTMLElement).classList.toggle(CLS.toggleIdle, plan.idle)
726
+ mount.toggle.setAttribute('aria-disabled', plan.idle ? 'true' : 'false')
727
+
728
+ for (const row of rows) {
729
+ const want = plan.folded.includes(row)
730
+ // The mark lands on the row's wrapper where the host ships one (0.2.2 on),
731
+ // so an emptied `_panelEntry` cannot outlive its row.
732
+ const target = foldTarget(row)
733
+ // Touch an attribute only when it actually changes: every write is a
734
+ // mutation, and every mutation triggers the rescan that caused this write.
735
+ if (want && !target.getAttribute(ATTR.folded)) target.setAttribute(ATTR.folded, '')
736
+ else if (!want && target.getAttribute(ATTR.folded) !== null) target.removeAttribute(ATTR.folded)
737
+ }
738
+ // The plan owns the idle case too: an idle control carries no state mark.
739
+ if (plan.state !== null && mount.nav.getAttribute(ATTR.state) !== plan.state) mount.nav.setAttribute(ATTR.state, plan.state)
740
+ else if (plan.state === null && mount.nav.getAttribute(ATTR.state) !== null) mount.nav.removeAttribute(ATTR.state)
741
+ // A 36px rail has no room for a second 28px square: hand the row back to the host.
742
+ ;(mount.toggle as HTMLElement).style.display = plan.toggleVisible ? 'inline-flex' : 'none'
743
+ paintToggle(mount.toggle, { idle: plan.idle })
744
+ // Folded while the current panel is one of the folded rows: mark the control so
745
+ // a 5px dot can say “what you are reading lives in here”.
746
+ const holdsActive = plan.active && plan.group.some((row) => isActiveRow(row))
747
+ if (holdsActive && mount.toggle.getAttribute(ATTR.activeInside) === null) mount.toggle.setAttribute(ATTR.activeInside, '')
748
+ else if (!holdsActive && mount.toggle.getAttribute(ATTR.activeInside) !== null) mount.toggle.removeAttribute(ATTR.activeInside)
749
+ // Last, because both hand the sidebar back to the host and every click causes a
750
+ // re-render: the third state and its recovery ride on the host's own pin controls.
751
+ moveRowsToMore(rows)
752
+ pinRowsBack(rows)
753
+ }
754
+ /** Toggle the group and persist the choice. */
755
+ function toggleFold(): void {
756
+ // An empty group must not pretend to fold: ignore the gesture entirely.
757
+ if (mount !== null) {
758
+ const resolved = resolveNavGroup(mount.nav, config.keepLabels, config.hideLabels)
759
+ if (resolved !== null && resolved.group.length === 0) return
760
+ }
761
+ folded = !currentFolded()
762
+ persist(folded)
763
+ applyFold()
764
+ }
765
+
766
+ /**
767
+ * Bind the toggle's input surface.
768
+ *
769
+ * Activation rides on **`pointerup`**, not on `click`: the host re-renders the
770
+ * sidebar constantly, and a click whose press target was replaced mid-gesture is
771
+ * never dispatched. `pointerup` always fires on the element under the pointer.
772
+ * The `click` handler stays for keyboard activation (Enter/Space) and as the
773
+ * fallback when this run predates Pointer Events.
774
+ */
775
+ function bindToggle(toggle: ElementLike): void {
776
+ const stop = (event: Event): void => {
777
+ event.stopPropagation()
778
+ }
779
+ const activate = (event: Event): void => {
780
+ event.preventDefault()
781
+ event.stopPropagation()
782
+ lastPointerActivation = Date.now()
783
+ toggleFold()
784
+ }
785
+ // Keep the host's own menu/dismiss logic out of our gesture.
786
+ for (const type of ['pointerdown', 'mousedown', 'dblclick']) toggle.addEventListener(type, stop as (event: Event) => void)
787
+ toggle.addEventListener('pointerup', (event: PointerEvent) => {
788
+ if (event.button !== 0 && event.button !== undefined) return
789
+ activate(event)
790
+ })
791
+ if (typeof PointerEvent === 'undefined') {
792
+ toggle.addEventListener('mouseup', activate as (event: Event) => void)
793
+ }
794
+ toggle.addEventListener('click', (event: MouseEvent) => {
795
+ event.stopPropagation()
796
+ // A click that follows our own pointerup is the same gesture — ignore it.
797
+ if (Date.now() - lastPointerActivation < 500) return
798
+ event.preventDefault()
799
+ toggleFold()
800
+ })
801
+ toggle.addEventListener('keydown', (event: KeyboardEvent) => {
802
+ if (event.key === 'Enter' || event.key === ' ' || event.key === 'Spacebar') activate(event)
803
+ })
804
+ }
805
+
806
+ /** Create the toggle as a sibling of the More anchor, inside the `_moreAnchor` span. */
807
+ function buildToggle(): ElementLike {
808
+ const toggle = document.createElement('div')
809
+ toggle.className = CLS.toggle
810
+ toggle.setAttribute('role', 'button')
811
+ toggle.setAttribute('tabindex', '0')
812
+ toggle.setAttribute(ATTR.own, '')
813
+ // A fresh node has no icon yet, so the paint-dedupe key must not suppress it.
814
+ paintedKey = ''
815
+ bindToggle(toggle as ElementLike)
816
+ return toggle as ElementLike
817
+ }
818
+
819
+ /** Tear down a live mount: remove our nodes and every attribute we wrote. */
820
+ function unmount(): void {
821
+ if (mount === null) return
822
+ const { nav, header, toggle, dispose } = mount
823
+ dispose()
824
+ ;(toggle as HTMLElement).remove()
825
+ nav.removeAttribute(ATTR.state)
826
+ nav.removeAttribute(ATTR.align)
827
+ header.removeAttribute(ATTR.header)
828
+ for (const row of Array.from(nav.querySelectorAll?.(`[${ATTR.folded}]`) ?? []) as ElementLike[]) {
829
+ row.removeAttribute(ATTR.folded)
830
+ }
831
+ mount = null
832
+ }
833
+
834
+ /**
835
+ * Mount (or re-mount) the fold over the current sidebar DOM.
836
+ *
837
+ * Called on activation and after every DOM mutation. Idempotent: an existing
838
+ * healthy mount whose header is still in the document is left untouched.
839
+ * @returns whether a mount is live after the call.
840
+ */
841
+ export function rescan(): boolean {
842
+ const nav = findPanelNav(document as unknown as QueryRoot)
843
+ if (nav === null) {
844
+ unmount()
845
+ return false
846
+ }
847
+ const resolved = resolveNavGroup(nav, config.keepLabels, config.hideLabels)
848
+ if (resolved === null) {
849
+ unmount()
850
+ return false
851
+ }
852
+ const stillHealthy =
853
+ mount !== null && mount.nav === nav && mount.header.isConnected && mount.toggle.isConnected
854
+ if (stillHealthy && mount !== null) {
855
+ applyFold()
856
+ return true
857
+ }
858
+ unmount()
859
+ const { header } = resolved
860
+ const anchor = header.parentElement as ElementLike | null
861
+ if (anchor === null || anchor === undefined || anchor.matches?.(SEL.moreAnchor) !== true) {
862
+ // Without the Menu host element we would have to nest a button inside the
863
+ // host's button, or restyle a flex column: refuse rather than guess.
864
+ return false
865
+ }
866
+ ensureSheet()
867
+ const toggle = buildToggle()
868
+ // The anchor span is the `Menu` host element: React only re-sets its *class*
869
+ // there, so appending a sibling survives re-renders — and because we position
870
+ // the toggle off the header row instead, the Menu's own anchor box (and thus
871
+ // the portal menu's offset) keeps the exact height the host measures.
872
+ ;(anchor as HTMLElement).appendChild(toggle as HTMLElement)
873
+ mount = { nav, header, toggle, dispose: () => {} }
874
+ applyFold()
875
+ return true
876
+ }
877
+
878
+ /**
879
+ * Remove every artifact this plugin may have left in the DOM, including ones a
880
+ * previous activation left behind.
881
+ *
882
+ * Disable→enable (or any HMR remount) runs `apply` again without a guaranteed
883
+ * teardown of the old mount first; without this sweep each cycle stacked another
884
+ * invisible toggle on the same coordinate (measured: 3 ghosts after 2 cycles).
885
+ */
886
+ function sweep(): void {
887
+ for (const node of Array.from(document.querySelectorAll(`.${CLS.toggle}[${ATTR.own}]`))) node.remove()
888
+ for (const nav of Array.from(document.querySelectorAll(`[${ATTR.header}], [${ATTR.state}], [${ATTR.align}]`)) as ElementLike[]) {
889
+ nav.removeAttribute(ATTR.header)
890
+ nav.removeAttribute(ATTR.state)
891
+ nav.removeAttribute(ATTR.align)
892
+ }
893
+ for (const row of Array.from(document.querySelectorAll(`[${ATTR.folded}]`)) as ElementLike[]) {
894
+ row.removeAttribute(ATTR.folded)
895
+ }
896
+ mount = null
897
+ // The pin bookkeeping belongs to one window's DOM; a remount starts from what
898
+ // the host shows now, never from a count that may no longer refer to it.
899
+ pinMoves.clear()
900
+ restoreWanted.clear()
901
+ }
902
+
903
+ /**
904
+ * Install the fold and keep it installed across re-renders.
905
+ * @param cfg - the effective configuration.
906
+ * @returns a disposer that leaves the sidebar exactly as shipped.
907
+ */
908
+ export function installFold(cfg: ConfigLike): () => void {
909
+ config = copyConfig(cfg)
910
+ readStored()
911
+ sweep()
912
+ let observer: MutationObserver | null = null
913
+ let queued = false
914
+ let retryTimer: ReturnType<typeof setTimeout> | null = null
915
+ let attempts = 0
916
+ const schedule = (): void => {
917
+ if (queued) return
918
+ queued = true
919
+ // 50ms, not 16: the sidebar re-renders on every pin/selection and a streaming
920
+ // reply mutates the tree many times per frame. One scan per burst is enough.
921
+ setTimeout(() => {
922
+ queued = false
923
+ rescan()
924
+ }, 50)
925
+ }
926
+ /**
927
+ * Feed the observer's batches through a relevance filter before scanning.
928
+ *
929
+ * A batch matters when it adds/removes a panel row, or when a `class` flips on
930
+ * the nav, one of its ancestors (the 36px rail switch) or a row inside it (the
931
+ * wrapper's active mark, which the dot follows).
932
+ */
933
+ const onMutations = (records: MutationRecord[]): void => {
934
+ if (recordsTouchRows(records)) {
935
+ schedule()
936
+ return
937
+ }
938
+ const nav = mount?.nav ?? findPanelNav(document as unknown as QueryRoot)
939
+ if (nav === null) return
940
+ for (const record of records) {
941
+ if (record.type !== 'attributes') continue
942
+ const target = record.target as unknown as ElementLike
943
+ if (target === nav || target.contains?.(nav) === true || nav.contains?.(target) === true) {
944
+ schedule()
945
+ return
946
+ }
947
+ }
948
+ }
949
+ /**
950
+ * Boot retry: the sidebar can mount after this plugin, and a hidden/background
951
+ * window never fires `requestAnimationFrame` (measured: the first scan missed
952
+ * and every later rescan was queued on a frozen rAF, leaving the plugin inert
953
+ * until a manual remount). A plain timer has no such freeze.
954
+ */
955
+ const retryUntilMounted = (): void => {
956
+ if (mount !== null || attempts >= 40) return
957
+ attempts += 1
958
+ rescan()
959
+ if (mount === null) retryTimer = setTimeout(retryUntilMounted, 250)
960
+ }
961
+ rescan()
962
+ retryTimer = setTimeout(retryUntilMounted, 100)
963
+ if (typeof MutationObserver === 'function') {
964
+ // `attributes` matters: collapsing the sidebar only flips a `class` on an
965
+ // ancestor, and the childList mutations of that same commit can land before
966
+ // the class change (measured) — watching only children read a stale rail.
967
+ observer = new MutationObserver(onMutations)
968
+ observer.observe(document.body, {
969
+ childList: true,
970
+ subtree: true,
971
+ attributes: true,
972
+ attributeFilter: ['class'],
973
+ })
974
+ }
975
+ const onConfig = (): void => {
976
+ schedule()
977
+ }
978
+ configListeners.add(onConfig)
979
+ return () => {
980
+ configListeners.delete(onConfig)
981
+ if (retryTimer !== null) clearTimeout(retryTimer)
982
+ observer?.disconnect()
983
+ unmount()
984
+ document.head.querySelector(`style[data-plugin-css="${STYLE_TAG_ID}"]`)?.remove()
985
+ }
986
+ }
987
+
988
+ /**
989
+ * Adopt a freshly served configuration (settings write, or first read) and
990
+ * repaint immediately — no restart, no reload.
991
+ *
992
+ * A label that left `hideLabels` is queued for a pin-back: the host put the row
993
+ * in its own "More" list, and only that list's control can bring it back.
994
+ */
995
+ export function applyConfig(cfg: ConfigLike): void {
996
+ const previousHide = config.hideLabels
997
+ config = copyConfig(cfg)
998
+ const now = Date.now()
999
+ for (const label of previousHide) {
1000
+ if (isHidden(label, config.hideLabels)) continue
1001
+ const key = labelKey(label)
1002
+ if (key !== '') restoreWanted.set(key, now)
1003
+ }
1004
+ for (const listener of Array.from(configListeners)) listener()
1005
+ applyFold()
1006
+ }
1007
+
1008
+ /** One deep copy of a served configuration, with the alignment coerced. */
1009
+ function copyConfig(cfg: ConfigLike): ConfigLike {
1010
+ return {
1011
+ defaultFolded: cfg.defaultFolded,
1012
+ keepLabels: [...cfg.keepLabels],
1013
+ // The fixed row can never be handed to the host, so a stale entry for it is
1014
+ // dropped on the way in instead of being retried on every scan.
1015
+ hideLabels: pruneHidden(cfg.hideLabels),
1016
+ align: normalizeAlign(cfg.align),
1017
+ }
1018
+ }
1019
+
1020
+ /** The configuration the fold is currently running with (settings card reads it). */
1021
+ export function effectiveConfig(): ConfigLike {
1022
+ return copyConfig(config)
1023
+ }
1024
+
1025
+ /** Built-in defaults, used when a host serves no writable configuration surface. */
1026
+ export const BUILTIN_CONFIG: ConfigLike = {
1027
+ defaultFolded: false,
1028
+ keepLabels: ['插件', 'Plugins'],
1029
+ hideLabels: [],
1030
+ align: 'start',
1031
+ }