@linxin666/dsh-client-ui-task-board 0.4.2 → 0.4.3

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.
package/src/mount-once.ts CHANGED
@@ -5,44 +5,138 @@
5
5
  * the loader accepts a standalone install of the same package side by side;
6
6
  * without this guard the second instance would still re-register the same
7
7
  * webserver routes, tools, settings namespaces, and system-prompt sections
8
- * and fail the boot. mountOnce makes the second host apply a no-op for the
9
- * lifetime of the first instance (the browser half is already deduped by
10
- * package name in the client module host).
8
+ * and fail the boot. mountOnce makes a mount of an already-mounted package a
9
+ * no-op for as long as the first instance lives (the browser half is already
10
+ * deduped by package name in the client module host).
11
+ *
12
+ * A no-op is only safe while the holder is ALIVE. The holder can be disposed
13
+ * long after the refused mount ran its course: the Host reloads a profile by
14
+ * creating the new loader entries before the old ones are torn down (a
15
+ * plugin-manager enable/disable/install write, a settings-driven row reload,
16
+ * HMR), so the new aggregate shell entry mounts its family plugin while the
17
+ * previous entry still owns the name. Dropping that refused mount lost the
18
+ * plugin for good - the previous entry then disposed its own mount, releasing
19
+ * the name with nobody left to take it, and the family row stayed listed as
20
+ * active while its host routes 404ed (the task-board panel showed
21
+ * "board.hostError.notMounted", no degraded record appeared, and only a Host
22
+ * restart recovered it).
23
+ *
24
+ * The refused mount is therefore QUEUED, not dropped, and replayed the moment
25
+ * the holder releases the name - if the waiting fiber is still alive then. The
26
+ * single-instance guarantee is unchanged: exactly one mount is live per
27
+ * package name, and the replay re-enters the guard so a later mount still
28
+ * dedupes against it.
11
29
  *
12
30
  * The registry rides a global symbol so two module instances of the same
13
- * package (npm copy vs repository link) still share one verdict. cordis
14
- * `ctx.effect` runs its callback immediately and treats the callback's
31
+ * package (npm copy vs repository link) still share one verdict. That symbol
32
+ * is a CROSS-REPOSITORY contract, not this file's private state: the four
33
+ * satellite packages (dsh-skins / dsh-pet / dsh-presets /
34
+ * dsh-community-plugins) are separate repositories carrying their own copy of
35
+ * this guard, rebuilt on their own schedule, so the value under `MOUNTED`
36
+ * must keep the shape every published copy reads (a `Set` of package names
37
+ * with `has`/`add`/`delete`). The wait queues this guard added therefore live
38
+ * under their own additive key, and the registry reads back a `Set` even when
39
+ * some other build left a different value there. Changing `MOUNTED`'s shape
40
+ * in place broke that contract once: a satellite's legacy copy created a
41
+ * `Set`, the family's new copy read it as a `Map`, and every family row
42
+ * mounted after it failed with "claims.get is not a function".
43
+ *
44
+ * cordis `ctx.effect` runs its callback immediately and treats the callback's
15
45
  * return value as the fiber disposer, so the unmarker is returned, not run.
16
46
  */
17
47
 
48
+ /** Published cross-repository contract: package names currently mounted. */
18
49
  const MOUNTED = Symbol.for('dsh-web.mounted-plugins')
19
50
 
51
+ /** Additive key this guard owns: refused mounts waiting for the name. */
52
+ const WAITERS = Symbol.for('dsh-web.mounted-plugins.waiters')
53
+
54
+ /** The slice of a cordis context this guard touches. */
55
+ interface MountContext {
56
+ effect?: (effect: () => unknown) => unknown
57
+ }
58
+
59
+ /** One mount that was refused while another fiber owned the package name. */
60
+ interface PendingMount {
61
+ /** Replay the refused mount; a no-op once its own fiber has been disposed. */
62
+ run(): void
63
+ }
64
+
20
65
  interface MountRegistry {
21
- [MOUNTED]?: Set<string>
66
+ [MOUNTED]?: unknown
67
+ [WAITERS]?: Map<string, PendingMount[]>
22
68
  }
23
69
 
70
+ /**
71
+ * The shared name registry, always a `Set` whatever another build stored here:
72
+ * a foreign value (an interim shape, a hand-written global) must not take every
73
+ * family plugin down with it.
74
+ * @returns the process-wide set of mounted package names.
75
+ */
24
76
  function mountedSet(): Set<string> {
25
77
  const registry = globalThis as MountRegistry
26
- return (registry[MOUNTED] ??= new Set())
78
+ const existing = registry[MOUNTED]
79
+ if (existing instanceof Set) return existing as Set<string>
80
+ const created = new Set<string>()
81
+ registry[MOUNTED] = created
82
+ return created
83
+ }
84
+
85
+ /** Queue per package name for mounts refused while a holder was alive. */
86
+ function mountWaiters(): Map<string, PendingMount[]> {
87
+ const registry = globalThis as MountRegistry
88
+ return (registry[WAITERS] ??= new Map())
27
89
  }
28
90
 
29
91
  /**
30
92
  * Wrap a cordis plugin apply so the package runs at most once per process.
31
- * The first mount registers normally and unmarks when its fiber disposes;
32
- * any later mount of the same package name is a no-op.
93
+ * The first mount registers normally and releases the name when its fiber
94
+ * disposes; a mount refused while that name is held waits for the release and
95
+ * then runs, unless its own fiber disposes first.
33
96
  * @param packageName - npm package identity shared by every install source.
34
97
  * @param fn - the original plugin apply.
35
98
  * @returns an apply of the same shape.
36
99
  */
37
100
  export function mountOnce<T extends (...args: any[]) => unknown>(packageName: string, fn: T): T {
38
- return ((...args: unknown[]) => {
101
+ const mount = (...args: unknown[]): unknown => {
39
102
  const mounted = mountedSet()
40
- if (mounted.has(packageName)) return
103
+ const ctx = args[0] as MountContext | undefined
104
+ if (mounted.has(packageName)) {
105
+ // Another fiber (the aggregate row, a standalone install, or a copy built
106
+ // from an older revision of this guard) owns the name. Queue instead of
107
+ // dropping: dropping lost the plugin for the rest of the process when the
108
+ // holder was disposed by a reload.
109
+ const waiters = mountWaiters()
110
+ const queue = waiters.get(packageName) ?? []
111
+ let alive = true
112
+ const pending: PendingMount = {
113
+ run: () => {
114
+ if (alive) mount(...args)
115
+ },
116
+ }
117
+ // A fiber that dies while it waits must not be replayed afterwards: its
118
+ // context is disposed and registering effects on it would throw.
119
+ ctx?.effect?.(() => () => {
120
+ alive = false
121
+ const index = queue.indexOf(pending)
122
+ if (index >= 0) queue.splice(index, 1)
123
+ })
124
+ queue.push(pending)
125
+ waiters.set(packageName, queue)
126
+ return
127
+ }
41
128
  mounted.add(packageName)
42
- const ctx = args[0] as { effect?: (effect: () => unknown) => unknown } | undefined
43
129
  ctx?.effect?.(() => () => {
44
130
  mounted.delete(packageName)
131
+ const waiters = mountWaiters()
132
+ const queue = waiters.get(packageName)
133
+ if (queue === undefined) return
134
+ waiters.delete(packageName)
135
+ // Defer the handover one microtask so the disposing mount's own effects
136
+ // (routes, ledger, timers) are torn down before the next one registers.
137
+ for (const waiter of queue.splice(0)) queueMicrotask(() => { waiter.run() })
45
138
  })
46
139
  return fn(...args)
47
- }) as T
140
+ }
141
+ return mount as T
48
142
  }
@@ -1,23 +0,0 @@
1
- /**
2
- * Board view mounting (dsh-task-board wrapper).
3
- *
4
- * The single-occupant takeover lifecycle — container injection into the
5
- * center column, sibling eviction, remount resilience, sidebar click-out —
6
- * lives exactly once in shared/client/panel-mount-core.ts (synced copy); this
7
- * wrapper supplies the board tree, view dataset key, CSS module, and the html
8
- * attribute names. Those names are pinned by board.module.css, skins, and the
9
- * semantic attributes contract.
10
- */
11
- import type { BoardController } from '../core/controller.ts';
12
- import type { LocaleRefreshSource } from './sidebar-entry.ts';
13
- /** The injected board container (kept in the DOM, hidden when inactive). */
14
- export declare const BOARD_VIEW_SELECTOR = "[data-dsh-taskboard-view]";
15
- /**
16
- * Mount the board React tree into the center column and bind its visibility
17
- * to the controller's boardOpen state.
18
- * @param controller - the board controller driving the view.
19
- * @param locale - locale-change source; when given, re-renders a mounted board
20
- * on a Language switch.
21
- * @returns disposer unmounting the tree and restoring the column.
22
- */
23
- export declare function mountBoard(controller: BoardController, locale?: LocaleRefreshSource): () => void;
@@ -1,45 +0,0 @@
1
- /**
2
- * One `document.body` MutationObserver per page, shared by every family
3
- * plugin bundle.
4
- *
5
- * Family plugins that inject at the DOM level must notice when the shell
6
- * re-renders around their injected node: the sidebar entry rows
7
- * (sidebar-entry-core), the center-column panel containers
8
- * (panel-mount-core), and the aggregate shell's column shims. Each consumer
9
- * used to install its OWN `MutationObserver` on `document.body` with
10
- * `{ childList: true, subtree: true }`, so a page carrying N family plugins
11
- * paid N native observers and N callback invocations for EVERY mutation batch
12
- * the app produced — chat token streaming alone produces many per second, and
13
- * the count grows with the number of installed plugins.
14
- *
15
- * This module keeps exactly ONE body observer per page. The registry lives on
16
- * `globalThis` under a `Symbol.for` key, so the per-package generated copies
17
- * of this file (scripts/sync-shared.mjs) and separately bundled plugins all
18
- * reach the same hub at runtime instead of one hub per module instance.
19
- * Record subscribers receive the mutations accumulated since the last flush.
20
- * Consumers that only re-check their DOM use subscribeBodyInvalidations:
21
- * when all subscribers use that path, the hub retains no mutation records
22
- * (or detached subtrees) while a background page's animation frames pause.
23
- * Both paths run at most once per frame. The last subscriber disconnects the
24
- * observer, cancels the pending frame and releases its records.
25
- *
26
- * Failure policy: without a DOM or `MutationObserver` the subscription is a
27
- * no-op disposer (the same silence the per-consumer observers had), and when
28
- * `requestAnimationFrame` is unavailable the flush runs synchronously so a
29
- * subscriber is never silently dropped. A throwing subscriber cannot stop the
30
- * others.
31
- */
32
- /**
33
- * Subscribe to a coalesced DOM re-check without retaining mutation records.
34
- * The marked wrapper also works with an older hub, which delivers records
35
- * that it simply ignores until a page reload picks up the updated hub.
36
- */
37
- export declare function subscribeBodyInvalidations(subscriber: () => void): () => void;
38
- /**
39
- * Subscribe to body-level childList mutations.
40
- * @param subscriber - called at most once per animation frame with the records
41
- * collected since the previous flush; must be safe to run repeatedly.
42
- * @returns the disposer removing this subscriber (and the observer when it was
43
- * the last one).
44
- */
45
- export declare function subscribeBodyMutations(subscriber: (records: MutationRecord[]) => void): () => void;
@@ -1,56 +0,0 @@
1
- /**
2
- * Center-column panel takeover lifecycle.
3
- *
4
- * The `conversation` slot is single-occupant (ui-conversation) and external
5
- * plugins cannot declare slots, so a family panel takes over the center
6
- * column at the DOM level: a container is appended inside the center column
7
- * (`[class*="centerCol"]`, the 0.1.0-rc.6+ AppFrame layout; previously
8
- * `[data-pane="conversation"]` on older shells — the mount selector keeps
9
- * both, ssh #243 / task-board #107) as an extra trailing child React never
10
- * manages, and a stylesheet rule hides the conversation content while the
11
- * panel is active. Toggling is a data attribute on <html> — no React
12
- * involvement, so the conversation subtree underneath stays mounted and
13
- * stateful.
14
- *
15
- * Consuming plugins keep a thin wrapper that supplies the panel tree,
16
- * container attribute names, and stylesheet class; those names are pinned by
17
- * each package's CSS, skins, and the semantic-attributes contract. The
18
- * sidebar row toggling the panel shares its core the same way
19
- * (shared/client/sidebar-entry-core.ts, synced copy).
20
- */
21
- import { type Root } from 'react-dom/client';
22
- /** Options for mountCenterPanel; dsh-ssh mount.tsx and dsh-task-board board-mount.tsx are the canonical consumers. */
23
- export interface CenterPanelMountOptions {
24
- /** Render the panel tree (first open, remount while open, locale refresh). */
25
- render: (root: Root) => void;
26
- /** dataset key of the injected container's view attribute, e.g. `dshSshView` for `data-dsh-ssh-view`. */
27
- viewDatasetKey: string;
28
- /** value of the container's L2 `data-dsh-plugin` semantic attribute. */
29
- pluginName: string;
30
- /** stylesheet class applied to the injected container. */
31
- viewClassName: string;
32
- /** <html> attribute set while this panel is active. */
33
- activeAttribute: string;
34
- /** the sibling panel's active attribute, removed from <html> when this panel opens. */
35
- siblingActiveAttribute: string;
36
- /** detail value this panel broadcasts on the cross-plugin activation event. */
37
- panelName: string;
38
- /** sibling detail value whose activation closes this panel. */
39
- siblingPanelName: string;
40
- /** open flag of the owning controller. */
41
- isOpen: () => boolean;
42
- /** close the panel, handing the center column back to the conversation. */
43
- close: () => void;
44
- /** subscribe to the owning controller's open-state changes; returns an unsubscriber. */
45
- subscribe: (listener: () => void) => () => void;
46
- /** locale-change source; when given, re-renders an open panel on a Language switch. */
47
- locale?: {
48
- subscribe(listener: () => void): () => void;
49
- };
50
- }
51
- /**
52
- * Mount a family panel into the center column and bind its visibility to the
53
- * owning controller's open state.
54
- * @returns disposer unmounting the tree and restoring the column.
55
- */
56
- export declare function mountCenterPanel(options: CenterPanelMountOptions): () => void;
@@ -1,55 +0,0 @@
1
- /** Per-package configuration for one sidebar entry row. */
2
- export interface SidebarEntryOptions {
3
- /** Full attribute name identifying the injected row (idempotency key), e.g. 'data-dsh-ssh-entry'. */
4
- rowAttribute: string;
5
- /** CSS selector matching the injected row, e.g. '[data-dsh-ssh-entry]'. */
6
- rowSelector: string;
7
- /**
8
- * L2 semantic-attribute plugin id (issue #506, enum table:
9
- * skins/skin-center/contracts/semantic-attrs-v1.md). When set, the row also
10
- * outputs data-dsh-plugin="<id>" and data-dsh-part="sidebar-entry"; unset
11
- * leaves the row without semantic attributes.
12
- */
13
- plugin?: string;
14
- /** Inline icon markup (matches the shell's 16px nav-icon look). */
15
- icon: string;
16
- /** CSS module class names for the row and its two spans (entry / entryIcon / entryLabel). */
17
- css: Record<string, string>;
18
- /** Localized row label (aria-label + visible text). */
19
- label(): string;
20
- /** Optional localized tooltip (title attribute). */
21
- tooltip?(): string;
22
- /**
23
- * Optional locale-change subscription: re-applies label / aria-label /
24
- * tooltip whenever the active locale changes. Plain-DOM rows would
25
- * otherwise keep the label captured at mount; pass the SDK locale runtime
26
- * subscription (ctx.locale.subscribe) so the row follows the language
27
- * switch without a reload.
28
- */
29
- refresh?: {
30
- subscribe(listener: () => void): () => void;
31
- };
32
- /** Click action (open/toggle the owning panel). */
33
- onToggle(): void;
34
- /** Family-block position: 'before' inserts ahead of sibling plugin rows, 'after' behind them. */
35
- position: 'before' | 'after';
36
- /**
37
- * Selectors of the sibling plugin entry rows this package orders against
38
- * (its own row included — the placement guard excludes a row that is
39
- * already inside the root). Each package passes the same list it used
40
- * before the consolidation so the rendered order stays stable.
41
- */
42
- familySelectors: readonly string[];
43
- /** Optional active-state bridge; highlights the row while the panel is open. */
44
- active?: {
45
- subscribe(listener: () => void): () => void;
46
- isOpen(): boolean;
47
- };
48
- }
49
- /**
50
- * Mount the sidebar entry, waiting for the shell to render and self-healing
51
- * on later React re-renders.
52
- * @param options - the row's attribute/icon/copy/action/ordering configuration.
53
- * @returns disposer removing the entry and its observers.
54
- */
55
- export declare function mountSidebarEntry(options: SidebarEntryOptions): () => void;
@@ -1,29 +0,0 @@
1
- /**
2
- * Sidebar entry injection — package-specific wiring over the shared core.
3
- *
4
- * dsh's sidebar shell exposes no slot an external plugin can register into
5
- * (`sidebar.workspaces` / `sidebar.settings` are single-occupant and already
6
- * taken), so the entry row is injected between the shell's New Session button
7
- * and the workspace browser. The DOM injection / self-healing / idempotency
8
- * logic lives exactly once in shared/client/sidebar-entry-core.ts (synced
9
- * copy); this wrapper supplies the task-board icon, copy, CSS module, and the
10
- * board toggle. The row is plain DOM (no React tree); the board view it
11
- * toggles is a separate React root mounted in the center column
12
- * (see board-mount.ts).
13
- */
14
- import type { BoardController } from '../core/controller.ts';
15
- /** Stable data attribute identifying the injected entry row. */
16
- export declare const ENTRY_SELECTOR = "[data-dsh-taskboard-entry]";
17
- /** Locale-change subscription the shared core asks for (ctx.locale.subscribe shape). */
18
- export interface LocaleRefreshSource {
19
- subscribe(listener: () => void): () => void;
20
- }
21
- /**
22
- * Mount the sidebar entry, waiting for the shell to render and self-healing
23
- * on later React re-renders.
24
- * @param controller - the board controller the entry toggles.
25
- * @param locale - locale-change source; when given, re-applies the label on
26
- * a Language switch (the plain-DOM row otherwise keeps the mount-time copy).
27
- * @returns disposer removing the entry and its observers.
28
- */
29
- export declare function mountSidebarEntry(controller: BoardController, locale?: LocaleRefreshSource): () => void;
@@ -1,43 +0,0 @@
1
- /**
2
- * Board view mounting (dsh-task-board wrapper).
3
- *
4
- * The single-occupant takeover lifecycle — container injection into the
5
- * center column, sibling eviction, remount resilience, sidebar click-out —
6
- * lives exactly once in shared/client/panel-mount-core.ts (synced copy); this
7
- * wrapper supplies the board tree, view dataset key, CSS module, and the html
8
- * attribute names. Those names are pinned by board.module.css, skins, and the
9
- * semantic attributes contract.
10
- */
11
- import type { BoardController } from '../core/controller.ts'
12
- import { TaskBoard } from './board/TaskBoard.tsx'
13
- import { mountCenterPanel } from './panel-mount-core.ts'
14
- import type { LocaleRefreshSource } from './sidebar-entry.ts'
15
- import css from './board.module.css'
16
-
17
- /** The injected board container (kept in the DOM, hidden when inactive). */
18
- export const BOARD_VIEW_SELECTOR = '[data-dsh-taskboard-view]'
19
-
20
- /**
21
- * Mount the board React tree into the center column and bind its visibility
22
- * to the controller's boardOpen state.
23
- * @param controller - the board controller driving the view.
24
- * @param locale - locale-change source; when given, re-renders a mounted board
25
- * on a Language switch.
26
- * @returns disposer unmounting the tree and restoring the column.
27
- */
28
- export function mountBoard(controller: BoardController, locale?: LocaleRefreshSource): () => void {
29
- return mountCenterPanel({
30
- render: root => root.render(<TaskBoard controller={controller} />),
31
- viewDatasetKey: 'dshTaskboardView',
32
- pluginName: 'task-board',
33
- viewClassName: css.boardView,
34
- activeAttribute: 'data-dsh-taskboard-active',
35
- siblingActiveAttribute: 'data-dsh-ssh-active',
36
- panelName: 'taskboard',
37
- siblingPanelName: 'ssh',
38
- isOpen: () => controller.getSnapshot().boardOpen,
39
- close: () => controller.closeBoard(),
40
- subscribe: listener => controller.subscribe(listener),
41
- locale,
42
- })
43
- }
@@ -1,133 +0,0 @@
1
- // Generated by scripts/sync-shared.mjs from shared/client/body-mutations.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
- /**
3
- * One `document.body` MutationObserver per page, shared by every family
4
- * plugin bundle.
5
- *
6
- * Family plugins that inject at the DOM level must notice when the shell
7
- * re-renders around their injected node: the sidebar entry rows
8
- * (sidebar-entry-core), the center-column panel containers
9
- * (panel-mount-core), and the aggregate shell's column shims. Each consumer
10
- * used to install its OWN `MutationObserver` on `document.body` with
11
- * `{ childList: true, subtree: true }`, so a page carrying N family plugins
12
- * paid N native observers and N callback invocations for EVERY mutation batch
13
- * the app produced — chat token streaming alone produces many per second, and
14
- * the count grows with the number of installed plugins.
15
- *
16
- * This module keeps exactly ONE body observer per page. The registry lives on
17
- * `globalThis` under a `Symbol.for` key, so the per-package generated copies
18
- * of this file (scripts/sync-shared.mjs) and separately bundled plugins all
19
- * reach the same hub at runtime instead of one hub per module instance.
20
- * Record subscribers receive the mutations accumulated since the last flush.
21
- * Consumers that only re-check their DOM use subscribeBodyInvalidations:
22
- * when all subscribers use that path, the hub retains no mutation records
23
- * (or detached subtrees) while a background page's animation frames pause.
24
- * Both paths run at most once per frame. The last subscriber disconnects the
25
- * observer, cancels the pending frame and releases its records.
26
- *
27
- * Failure policy: without a DOM or `MutationObserver` the subscription is a
28
- * no-op disposer (the same silence the per-consumer observers had), and when
29
- * `requestAnimationFrame` is unavailable the flush runs synchronously so a
30
- * subscriber is never silently dropped. A throwing subscriber cannot stop the
31
- * others.
32
- */
33
-
34
- /** The page-wide hub: one observer plus its subscribers and pending records. */
35
- interface BodyMutationHub {
36
- observer: MutationObserver
37
- subscribers: Set<(records: MutationRecord[]) => void>
38
- pending: MutationRecord[]
39
- scheduled: boolean
40
- frame?: number
41
- }
42
-
43
- /** Cross-bundle registry key; `Symbol.for` so every module copy agrees. */
44
- const HUB_KEY = Symbol.for('dsh-web.body-mutation-hub')
45
- const INVALIDATION_ONLY = Symbol.for('dsh-web.body-mutation-invalidation')
46
- type Subscriber = ((records: MutationRecord[]) => void) & { [INVALIDATION_ONLY]?: true }
47
-
48
- function needsRecords(subscribers: Set<(records: MutationRecord[]) => void>): boolean {
49
- for (const listener of subscribers) {
50
- if (!(listener as Subscriber)[INVALIDATION_ONLY]) return true
51
- }
52
- return false
53
- }
54
-
55
- /**
56
- * Subscribe to a coalesced DOM re-check without retaining mutation records.
57
- * The marked wrapper also works with an older hub, which delivers records
58
- * that it simply ignores until a page reload picks up the updated hub.
59
- */
60
- export function subscribeBodyInvalidations(subscriber: () => void): () => void {
61
- const listener: Subscriber = () => { subscriber() }
62
- listener[INVALIDATION_ONLY] = true
63
- return subscribeBodyMutations(listener)
64
- }
65
-
66
- /**
67
- * Subscribe to body-level childList mutations.
68
- * @param subscriber - called at most once per animation frame with the records
69
- * collected since the previous flush; must be safe to run repeatedly.
70
- * @returns the disposer removing this subscriber (and the observer when it was
71
- * the last one).
72
- */
73
- export function subscribeBodyMutations(subscriber: (records: MutationRecord[]) => void): () => void {
74
- if (typeof globalThis === 'undefined' || typeof document === 'undefined') return () => {}
75
- if (typeof MutationObserver !== 'function') return () => {}
76
- const registry = globalThis as unknown as Record<symbol, unknown>
77
- let hub = registry[HUB_KEY] as BodyMutationHub | undefined
78
- if (hub === undefined) {
79
- const subscribers = new Set<(records: MutationRecord[]) => void>()
80
- const created: BodyMutationHub = {
81
- observer: undefined as unknown as MutationObserver,
82
- subscribers,
83
- pending: [],
84
- scheduled: false,
85
- }
86
- const flush = (): void => {
87
- created.frame = undefined
88
- created.scheduled = false
89
- const batch = created.pending
90
- created.pending = []
91
- for (const listener of [...subscribers]) {
92
- if (!subscribers.has(listener)) continue
93
- try {
94
- listener(batch)
95
- } catch {
96
- // One subscriber must never break the others; the next flush retries it.
97
- }
98
- }
99
- }
100
- const schedule = (): void => {
101
- if (created.scheduled) return
102
- created.scheduled = true
103
- if (typeof requestAnimationFrame === 'function') created.frame = requestAnimationFrame(flush)
104
- else flush()
105
- }
106
- created.observer = new MutationObserver((records) => {
107
- if (needsRecords(subscribers)) {
108
- for (const record of records) created.pending.push(record)
109
- }
110
- schedule()
111
- })
112
- created.observer.observe(document.body ?? document.documentElement, { childList: true, subtree: true })
113
- registry[HUB_KEY] = created
114
- hub = created
115
- }
116
- const active = hub
117
- active.subscribers.add(subscriber)
118
- let subscribed = true
119
- return () => {
120
- if (!subscribed) return
121
- subscribed = false
122
- active.subscribers.delete(subscriber)
123
- if (!needsRecords(active.subscribers)) active.pending = []
124
- if (active.subscribers.size === 0 && registry[HUB_KEY] === active) {
125
- active.observer.disconnect()
126
- if (active.frame !== undefined && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(active.frame)
127
- active.frame = undefined
128
- active.pending = []
129
- active.scheduled = false
130
- delete registry[HUB_KEY]
131
- }
132
- }
133
- }