@tschk/moonshine-dom 0.0.0-stage → 0.4.4

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/binding.ts ADDED
@@ -0,0 +1,380 @@
1
+ /** Optional compiler-facing element bindings; no hydration or compiler ABI. */
2
+ import {
3
+ createRenderEffect,
4
+ createRoot,
5
+ getOwner,
6
+ onCleanup,
7
+ untrack,
8
+ } from "./reactive";
9
+
10
+ export type InputValue = string | number | null | undefined;
11
+
12
+ /** Install after user toggle listeners; nullish state closes rather than adopts. */
13
+ export function bindOpen(
14
+ element: HTMLDetailsElement,
15
+ read: () => boolean | null | undefined,
16
+ write: (value: boolean) => void,
17
+ ): void {
18
+ const owner = getOwner();
19
+ if (!owner || owner.disposed)
20
+ throw new Error("Open bindings require a live native owner");
21
+ if (
22
+ !(element instanceof HTMLDetailsElement) ||
23
+ typeof read !== "function" ||
24
+ typeof write !== "function"
25
+ )
26
+ throw new TypeError(
27
+ "Open bindings require details and getter/setter functions",
28
+ );
29
+ const toggle = () => untrack(() => write(element.open));
30
+ element.addEventListener("toggle", toggle);
31
+ onCleanup(() => element.removeEventListener("toggle", toggle));
32
+ createRenderEffect(() => {
33
+ element.open = Boolean(read());
34
+ });
35
+ }
36
+
37
+ /** Call after element attributes and user listeners are installed, under a live owner. */
38
+ export function bindValue(
39
+ element: HTMLInputElement | HTMLTextAreaElement,
40
+ read: () => InputValue,
41
+ write: (value: string | number | undefined, reset?: true) => void,
42
+ ): void {
43
+ const owner = getOwner();
44
+ if (!owner || owner.disposed)
45
+ throw new Error("Value bindings require a live native owner");
46
+ if (
47
+ !(element instanceof HTMLTextAreaElement) &&
48
+ (!(element instanceof HTMLInputElement) ||
49
+ ![
50
+ "text",
51
+ "search",
52
+ "tel",
53
+ "url",
54
+ "email",
55
+ "password",
56
+ "number",
57
+ "range",
58
+ "date",
59
+ "datetime-local",
60
+ "month",
61
+ "week",
62
+ "time",
63
+ "color",
64
+ ].includes(element.type))
65
+ )
66
+ throw new TypeError(
67
+ "Value bindings support text, numeric, date/time and color inputs or textarea",
68
+ );
69
+ const numberlike = () =>
70
+ element instanceof HTMLInputElement &&
71
+ (element.type === "number" || element.type === "range");
72
+ function value(text = element.value): string | number | undefined {
73
+ if (!numberlike()) return text;
74
+ const number = text === "" ? NaN : Number(text);
75
+ return Number.isNaN(number) ? undefined : number;
76
+ }
77
+ function apply(): void {
78
+ const next = read();
79
+ // Preserve numeric formatting/caret when the represented number is unchanged.
80
+ if (numberlike() && next === value()) return;
81
+ const text = String(next ?? "");
82
+ if (element.value !== text) element.value = text;
83
+ }
84
+ const input = (reset?: true) =>
85
+ untrack(() => {
86
+ if (reset) write(value(element.defaultValue), true);
87
+ else write(value());
88
+ apply();
89
+ });
90
+ listen(element, "input", input);
91
+ untrack(() => {
92
+ if (read() == null && element.value) write(value());
93
+ });
94
+ createRenderEffect(apply);
95
+ }
96
+
97
+ function listen(
98
+ element: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,
99
+ eventName: "input" | "change",
100
+ handler: (reset?: true) => void,
101
+ ): void {
102
+ let active = true;
103
+ const reset = (event: Event) => {
104
+ if (event.target !== element.form || !element.form) return;
105
+ queueMicrotask(() => {
106
+ if (!active || event.defaultPrevented) return;
107
+ handler(true);
108
+ });
109
+ };
110
+ const document = element.ownerDocument;
111
+ const listener = () => handler();
112
+ element.addEventListener(eventName, listener);
113
+ // shortcut: connected forms only; add form-local tracking if detached-form support is required.
114
+ document.addEventListener("reset", reset, true);
115
+ onCleanup(() => {
116
+ active = false;
117
+ element.removeEventListener(eventName, listener);
118
+ document.removeEventListener("reset", reset, true);
119
+ });
120
+ }
121
+
122
+ /** Checkbox checked binding; call after attributes and user change listeners. */
123
+ export function bindChecked(
124
+ element: HTMLInputElement,
125
+ read: () => boolean | null | undefined,
126
+ write: (value: boolean) => void,
127
+ ): void {
128
+ const owner = getOwner();
129
+ if (!owner || owner.disposed)
130
+ throw new Error("Checked bindings require a live native owner");
131
+ if (!(element instanceof HTMLInputElement) || element.type !== "checkbox")
132
+ throw new TypeError("Checked bindings support checkbox inputs only");
133
+ const apply = () => {
134
+ element.checked = Boolean(read());
135
+ };
136
+ listen(element, "change", () =>
137
+ untrack(() => {
138
+ write(element.checked);
139
+ apply();
140
+ }),
141
+ );
142
+ untrack(() => {
143
+ if (read() == null) write(element.checked);
144
+ });
145
+ createRenderEffect(apply);
146
+ }
147
+
148
+ const optionValues = new WeakMap<HTMLOptionElement, unknown>();
149
+ const selectUpdates = new WeakMap<HTMLSelectElement, () => void>();
150
+
151
+ /** Preserve source-level option identity; plain h(option,{value}) stays string-valued. */
152
+ export function setOptionValue(
153
+ option: HTMLOptionElement,
154
+ value: unknown,
155
+ ): void {
156
+ if (!(option instanceof HTMLOptionElement))
157
+ throw new TypeError("Option values require an option element");
158
+ const text = value == null ? "" : String(value);
159
+ optionValues.set(option, value);
160
+ option.value = text;
161
+ const select = option.closest("select");
162
+ if (select) untrack(() => selectUpdates.get(select)?.());
163
+ }
164
+ function optionValue(option: HTMLOptionElement): unknown {
165
+ return optionValues.has(option) ? optionValues.get(option) : option.value;
166
+ }
167
+
168
+ /** Typed single/multiple select binding, after options and user listeners are installed. */
169
+ export function bindSelectValue(
170
+ select: HTMLSelectElement,
171
+ read: () => unknown,
172
+ write: (value: unknown) => void,
173
+ equal: (left: unknown, right: unknown) => boolean = Object.is,
174
+ ): void {
175
+ const owner = getOwner();
176
+ if (!owner || owner.disposed)
177
+ throw new Error("Select bindings require a live native owner");
178
+ if (!(select instanceof HTMLSelectElement))
179
+ throw new TypeError("Select bindings require a select element");
180
+ if (selectUpdates.has(select))
181
+ throw new Error("Select already has a value binding");
182
+ function selected(reset = false): unknown {
183
+ const options = Array.from(select.options).filter((option) =>
184
+ reset ? option.hasAttribute("selected") : option.selected,
185
+ );
186
+ if (select.multiple) return options.map(optionValue);
187
+ const option =
188
+ options[0] ??
189
+ Array.from(select.options).find((candidate) => !candidate.disabled);
190
+ return option ? optionValue(option) : null;
191
+ }
192
+ function apply(): void {
193
+ const next = read();
194
+ if (select.multiple) {
195
+ if (next == null) return;
196
+ if (!Array.isArray(next))
197
+ throw new TypeError(
198
+ "Multiple select bindings require an array or nullish value",
199
+ );
200
+ for (const option of select.options)
201
+ option.selected = next.includes(optionValue(option));
202
+ } else {
203
+ let found = false;
204
+ for (const option of select.options) {
205
+ const matches = !found && equal(optionValue(option), next);
206
+ option.selected = matches;
207
+ if (matches) found = true;
208
+ }
209
+ if (!found) select.selectedIndex = -1;
210
+ }
211
+ }
212
+ listen(select, "change", (reset) =>
213
+ untrack(() => {
214
+ const value = selected(reset);
215
+ write(value);
216
+ // An unchanged accepted value preserves the user's duplicate option choice.
217
+ // Rejected/transformed writes still reconcile the DOM with the actual model.
218
+ if (select.multiple || !equal(read(), value)) apply();
219
+ }),
220
+ );
221
+ let active = true;
222
+ const observer = new MutationObserver(() => {
223
+ if (active) untrack(apply);
224
+ });
225
+ selectUpdates.set(select, apply);
226
+ onCleanup(() => {
227
+ active = false;
228
+ observer.disconnect();
229
+ selectUpdates.delete(select);
230
+ });
231
+ untrack(() => {
232
+ // Typed undefined is a real option value; match it before default adoption.
233
+ if (!select.multiple && read() === undefined) {
234
+ const match = Array.from(select.options).find((option) =>
235
+ equal(optionValue(option), undefined),
236
+ );
237
+ if (match) match.selected = true;
238
+ }
239
+ if (
240
+ read() === undefined &&
241
+ (select.multiple ||
242
+ Array.from(select.options).some((option) => option.selected))
243
+ )
244
+ write(selected());
245
+ });
246
+ createRenderEffect(apply);
247
+ observer.observe(select, {
248
+ childList: true,
249
+ subtree: true,
250
+ characterData: true,
251
+ attributes: true,
252
+ attributeFilter: ["value", "selected"],
253
+ });
254
+ }
255
+
256
+ const inputValues = /* @__PURE__ */ new WeakMap<HTMLInputElement, unknown>();
257
+ const inputUpdates = /* @__PURE__ */ new WeakMap<
258
+ HTMLInputElement,
259
+ () => void
260
+ >();
261
+
262
+ /** Compiler hook for typed radio/checkbox values; ordinary DOM values stay strings. */
263
+ export function setInputValue(input: HTMLInputElement, value: unknown): void {
264
+ if (!(input instanceof HTMLInputElement))
265
+ throw new TypeError("Input values require an input element");
266
+ const text = value == null ? "" : String(value);
267
+ inputValues.set(input, value);
268
+ input.value = text;
269
+ untrack(() => inputUpdates.get(input)?.());
270
+ }
271
+ function inputValue(input: HTMLInputElement): unknown {
272
+ return inputValues.has(input) ? inputValues.get(input) : input.value;
273
+ }
274
+
275
+ /** One explicit token per compiler binding target; never inferred from HTML names. */
276
+ export function createInputGroup(
277
+ kind: "radio" | "checkbox",
278
+ read: () => unknown,
279
+ write: (value: unknown) => void,
280
+ equal: (left: unknown, right: unknown) => boolean = Object.is,
281
+ ): { bind(input: HTMLInputElement): void } {
282
+ const owner = getOwner();
283
+ if (!owner || owner.disposed || owner.disposing)
284
+ throw new Error("Input groups require a live native owner");
285
+ if (kind !== "radio" && kind !== "checkbox")
286
+ throw new TypeError("Input groups support radio or checkbox inputs only");
287
+ type Member = { input: HTMLInputElement; stop: () => void };
288
+ const members = new Set<Member>();
289
+ let active = true;
290
+ function release(member: Member): void {
291
+ if (!members.delete(member)) return;
292
+ inputUpdates.delete(member.input);
293
+ member.stop();
294
+ }
295
+ onCleanup(() => {
296
+ active = false;
297
+ let failed = false,
298
+ failure: unknown;
299
+ for (const member of members) {
300
+ try {
301
+ release(member);
302
+ } catch (error) {
303
+ if (!failed) failure = error;
304
+ failed = true;
305
+ }
306
+ }
307
+ if (failed) throw failure;
308
+ });
309
+ function apply(member: Member): void {
310
+ if (!active || !members.has(member)) return;
311
+ const value = read();
312
+ if (kind === "checkbox") {
313
+ if (value != null && !Array.isArray(value))
314
+ throw new TypeError(
315
+ "Checkbox groups require an array or nullish value",
316
+ );
317
+ member.input.checked =
318
+ (value as unknown[] | null | undefined)?.includes(
319
+ inputValue(member.input),
320
+ ) ?? false;
321
+ } else member.input.checked = equal(inputValue(member.input), value);
322
+ }
323
+ return {
324
+ bind(input) {
325
+ const current = getOwner();
326
+ if (!active || !current || current.disposed || current.disposing)
327
+ throw new Error(
328
+ "Input group members require a live group and native owner",
329
+ );
330
+ if (!(input instanceof HTMLInputElement) || input.type !== kind)
331
+ throw new TypeError(`Input group requires ${kind} inputs`);
332
+ if (inputUpdates.has(input))
333
+ throw new Error("Input already belongs to a group");
334
+ const member: Member = { input, stop: () => {} };
335
+ onCleanup(() => release(member));
336
+ try {
337
+ createRoot((stop) => {
338
+ member.stop = stop;
339
+ members.add(member);
340
+ inputUpdates.set(input, () => apply(member));
341
+ listen(input, "change", (reset) =>
342
+ untrack(() => {
343
+ if (!active || !members.has(member)) return;
344
+ if (reset) write(kind === "checkbox" ? [] : null);
345
+ else if (kind === "radio") write(inputValue(input));
346
+ else {
347
+ const ordered = [...members].toSorted((a, b) => {
348
+ const position = a.input.compareDocumentPosition(b.input);
349
+ return position & Node.DOCUMENT_POSITION_DISCONNECTED
350
+ ? 0
351
+ : position & Node.DOCUMENT_POSITION_FOLLOWING
352
+ ? -1
353
+ : position & Node.DOCUMENT_POSITION_PRECEDING
354
+ ? 1
355
+ : 0;
356
+ });
357
+ const values = new Set(
358
+ ordered
359
+ .filter((entry) => entry.input.checked)
360
+ .map((entry) => inputValue(entry.input)),
361
+ );
362
+ if (!input.checked) values.delete(inputValue(input));
363
+ write([...values]);
364
+ }
365
+ for (const entry of members) apply(entry);
366
+ }),
367
+ );
368
+ createRenderEffect(() => apply(member));
369
+ });
370
+ } catch (error) {
371
+ try {
372
+ release(member);
373
+ } catch {
374
+ /* Preserve binding setup failure. */
375
+ }
376
+ throw error;
377
+ }
378
+ },
379
+ };
380
+ }
@@ -0,0 +1,16 @@
1
+ export const cleanupOrderKey = /* @__PURE__ */ Symbol(
2
+ "moonshine.cleanup-order",
3
+ );
4
+ export interface CleanupPolicy {
5
+ reverse: boolean;
6
+ deferRemoval(
7
+ owned: readonly Node[],
8
+ anchor: Node,
9
+ retain: ((node: Node) => boolean) | undefined,
10
+ remove: (
11
+ owned: readonly Node[],
12
+ retained?: ReadonlySet<Node>,
13
+ retain?: (node: Node) => boolean,
14
+ ) => void,
15
+ ): void;
16
+ }
@@ -0,0 +1,290 @@
1
+ /** Native exported-instance references; not a Svelte class/component ABI. */
2
+ import {
3
+ getComponentContext,
4
+ peekComponentContext,
5
+ type ComponentContext,
6
+ } from "./component";
7
+ import {
8
+ batch,
9
+ getRenderScheduler,
10
+ createComputed,
11
+ onCleanup,
12
+ queuePostCommit,
13
+ runWithOwner,
14
+ untrack,
15
+ type Owner,
16
+ } from "./reactive";
17
+
18
+ export const componentRef = /* @__PURE__ */ Symbol("moonshine.component.ref");
19
+ /** Optional compiler-supplied paths retain tuple types; fixed cells keep zero arguments. */
20
+ export type ComponentReference<
21
+ T extends object,
22
+ Parts extends readonly unknown[] = [],
23
+ Current = T,
24
+ > = {
25
+ /** Opt into clearing after the enclosing DOM commit; default is a microtask. */
26
+ cleanup?: "commit";
27
+ /** Compiler opt-in: publish after child lifecycle posts, before ancestor posts.
28
+ * Requires a render scheduler; default references publish before mounts. */
29
+ publication?: "post";
30
+ get: (...parts: Parts) => Current | null | undefined;
31
+ set: (value: T | null, ...parts: Parts) => void;
32
+ } & (Parts extends readonly []
33
+ ? { parts?: () => Parts }
34
+ : { parts: () => Parts });
35
+ const exposed = new WeakSet<ComponentContext>();
36
+ const instancePrototype = /* @__PURE__ */ Object.freeze(
37
+ /* @__PURE__ */ Object.create(null),
38
+ );
39
+
40
+ const publications = new Set<() => void>();
41
+ let scheduled = false;
42
+ let flushing = false;
43
+
44
+ /** Commit all pending instance references before post-DOM lifecycle callbacks. */
45
+ export function flushComponentReferences(): void {
46
+ if (flushing || !publications.size || peekComponentContext()?.active) return;
47
+ flushing = true;
48
+ let failed = false;
49
+ let failure: unknown;
50
+ let waves = 0;
51
+ try {
52
+ while (publications.size) {
53
+ // Fresh publishers can perpetuate feedback without repeating a callback.
54
+ if (++waves > 1000) {
55
+ if (!failed)
56
+ failure = new Error("Component reference update limit exceeded");
57
+ failed = true;
58
+ publications.clear();
59
+ break;
60
+ }
61
+ // oxlint-disable-next-line unicorn/no-useless-spread -- Freeze the wave so newly queued callbacks count toward the limit.
62
+ for (const publish of [...publications]) {
63
+ if (!publications.delete(publish)) continue;
64
+ try {
65
+ publish();
66
+ } catch (error) {
67
+ if (!failed) failure = error;
68
+ failed = true;
69
+ }
70
+ }
71
+ }
72
+ } finally {
73
+ flushing = false;
74
+ }
75
+ if (failed) throw failure;
76
+ }
77
+
78
+ /** Preserve export descriptors in an opaque instance; publish and clear in microtasks. */
79
+ export function exposeComponent<T extends object>(exports: T): T {
80
+ const frame = getComponentContext();
81
+ if (
82
+ exports === null ||
83
+ typeof exports !== "object" ||
84
+ (Object.getPrototypeOf(exports) !== Object.prototype &&
85
+ Object.getPrototypeOf(exports) !== null)
86
+ )
87
+ throw new TypeError(
88
+ "Component exports must be a plain object of named exports",
89
+ );
90
+ if (exposed.has(frame))
91
+ throw new Error("Component exports may be exposed only once per instance");
92
+ const instance = Object.create(
93
+ instancePrototype,
94
+ Object.getOwnPropertyDescriptors(exports),
95
+ ) as T;
96
+ if (frame.mode === "ssr") {
97
+ exposed.add(frame);
98
+ return instance;
99
+ }
100
+ const props = frame.props;
101
+ const reference =
102
+ props && (typeof props === "object" || typeof props === "function")
103
+ ? Reflect.get(props, componentRef)
104
+ : undefined;
105
+ if (
106
+ reference !== undefined &&
107
+ (!reference ||
108
+ typeof reference.get !== "function" ||
109
+ typeof reference.set !== "function")
110
+ )
111
+ throw new TypeError("Component reference requires get and set functions");
112
+ if (reference?.cleanup !== undefined && reference.cleanup !== "commit")
113
+ throw new TypeError(
114
+ "Component reference cleanup must be commit when provided",
115
+ );
116
+ const publication = reference?.publication;
117
+ if (publication !== undefined && publication !== "post")
118
+ throw new TypeError(
119
+ "Component reference publication must be post when provided",
120
+ );
121
+ const enqueue = publisher(publication);
122
+ exposed.add(frame);
123
+ frame.capture?.(instance);
124
+ if (!reference) return instance;
125
+ if ("parts" in reference) {
126
+ enqueue(bindOwnedReference(frame.owner, instance, reference, enqueue));
127
+ return instance;
128
+ }
129
+ const binding = reference as ComponentReference<T>;
130
+ let published = false;
131
+ const clear = () =>
132
+ untrack(() => {
133
+ if (binding.get() === instance) binding.set(null);
134
+ });
135
+ const publish = () => {
136
+ if (frame.owner.disposed) return;
137
+ const commit = () =>
138
+ untrack(() => {
139
+ published = true;
140
+ try {
141
+ binding.set(instance);
142
+ } catch (error) {
143
+ try {
144
+ clear();
145
+ } catch {
146
+ /* Preserve the publishing failure. */
147
+ }
148
+ throw error;
149
+ }
150
+ });
151
+ runPublication(binding, commit);
152
+ };
153
+ onCleanup(() => {
154
+ publications.delete(publish);
155
+ if (published) scheduleClear(binding, clear);
156
+ });
157
+ enqueue(publish);
158
+ return instance;
159
+ }
160
+
161
+ function enqueuePublication(publish: () => void): void {
162
+ publications.add(publish);
163
+ if (!scheduled && !flushing) {
164
+ scheduled = true;
165
+ queueMicrotask(() => {
166
+ scheduled = false;
167
+ flushComponentReferences();
168
+ });
169
+ }
170
+ }
171
+
172
+ function runPublication(
173
+ binding: { cleanup?: "commit" },
174
+ publish: () => void,
175
+ ): void {
176
+ if (binding.cleanup === "commit") batch(publish);
177
+ else publish();
178
+ }
179
+
180
+ function scheduleClear(
181
+ binding: { cleanup?: "commit" },
182
+ clear: () => void,
183
+ enqueueClear?: (clear: () => void) => void,
184
+ ): void {
185
+ if (enqueueClear) enqueueClear(clear);
186
+ else if (binding.cleanup === "commit") queuePostCommit(clear);
187
+ else queueMicrotask(clear);
188
+ }
189
+
190
+ export type OwnedReference<T extends object> = {
191
+ cleanup?: "commit";
192
+ publication?: "post";
193
+ parts?: () => readonly unknown[];
194
+ get: (...parts: unknown[]) => T | null | undefined;
195
+ set: (value: T | null, ...parts: unknown[]) => void;
196
+ };
197
+ /** Internal shared target protocol; the caller chooses when parts initialize. */
198
+ export function bindOwnedReference<T extends object>(
199
+ owner: Owner,
200
+ instance: T,
201
+ binding: OwnedReference<T>,
202
+ enqueue: (fn: () => void) => void,
203
+ policy?: {
204
+ cleanup?: "commit";
205
+ previousCheck?: "after-set";
206
+ enqueueClear?: (clear: () => void) => void;
207
+ },
208
+ ): () => void {
209
+ const cleanupPolicy = policy ?? binding;
210
+ let current: readonly unknown[] | undefined;
211
+ let next: readonly unknown[] | undefined;
212
+ const clear = (parts: readonly unknown[]) =>
213
+ untrack(() => {
214
+ if (binding.get(...parts) === instance) binding.set(null, ...parts);
215
+ });
216
+ const publish = () => {
217
+ if (owner.disposed || !next) return;
218
+ const target = next;
219
+ next = undefined;
220
+ const commit = () =>
221
+ untrack(() => {
222
+ // Distinct path tuples can address the same actual cell.
223
+ if (binding.get(...target) === instance) {
224
+ current = target;
225
+ return;
226
+ }
227
+ const previous = current;
228
+ const ownedPrevious =
229
+ previous &&
230
+ (policy?.previousCheck === "after-set" ||
231
+ binding.get(...previous) === instance);
232
+ try {
233
+ binding.set(instance, ...target);
234
+ } catch (error) {
235
+ try {
236
+ clear(target);
237
+ } catch {
238
+ /* Preserve the publishing failure. */
239
+ }
240
+ throw error;
241
+ }
242
+ current = target;
243
+ // The setter can dispose its component before the new path is recorded.
244
+ if (owner.disposed)
245
+ scheduleClear(
246
+ cleanupPolicy,
247
+ () => clear(target),
248
+ policy?.enqueueClear,
249
+ );
250
+ if (ownedPrevious) clear(previous);
251
+ });
252
+ // A setter can synchronously dispose the component. Keep its final target
253
+ // cleanup inside the same native commit, after ancestor teardown callbacks.
254
+ runPublication(cleanupPolicy, commit);
255
+ };
256
+ const initialize = () => {
257
+ if (owner.disposed) return;
258
+ runWithOwner(owner, () =>
259
+ createComputed(() => {
260
+ const parts = binding.parts;
261
+ if (parts !== undefined && typeof parts !== "function")
262
+ throw new TypeError("Component reference parts must be a function");
263
+ const values = parts ? parts.call(binding) : [];
264
+ if (!Array.isArray(values))
265
+ throw new TypeError("Component reference parts must return an array");
266
+ next = Array.from(values);
267
+ enqueue(publish);
268
+ }),
269
+ );
270
+ };
271
+ onCleanup(() => {
272
+ publications.delete(initialize);
273
+ publications.delete(publish);
274
+ next = undefined;
275
+ const last = current;
276
+ if (last)
277
+ scheduleClear(cleanupPolicy, () => clear(last), policy?.enqueueClear);
278
+ });
279
+ return initialize;
280
+ }
281
+
282
+ function publisher(publication?: "post"): (fn: () => void) => void {
283
+ if (publication !== "post") return enqueuePublication;
284
+ const scheduler = getRenderScheduler();
285
+ if (!scheduler)
286
+ throw new Error(
287
+ "Post component reference publication requires an opt-in render scheduler",
288
+ );
289
+ return (fn) => scheduler.post(fn, true);
290
+ }