@tschk/moonshine-vue 0.4.4 → 0.4.80

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/lifecycle.ts CHANGED
@@ -11,30 +11,157 @@ import {
11
11
  getComponentContext,
12
12
  onComponentReady,
13
13
  withComponentConsumer,
14
+ type ComponentContext,
14
15
  } from "@tschk/moonshine-dom/component";
15
16
  import { flushComponentReferences } from "@tschk/moonshine-dom/component-instance";
17
+ import { registerErrorCaptured, type ErrorCapturedHook } from "./error-context";
18
+ export type { ErrorCapturedHook } from "./error-context";
16
19
 
17
- function component(fn: () => void) {
20
+ type FrameMountQueue = {
21
+ before: Array<() => void>;
22
+ mounted: Array<() => void>;
23
+ beforeUpdate: Array<() => void>;
24
+ updated: Array<() => void>;
25
+ activated: Array<() => void>;
26
+ deactivated: Array<() => void>;
27
+ serverPrefetch: Array<() => Promise<unknown>>;
28
+ };
29
+ const frameQueues = /* @__PURE__ */ new WeakMap<
30
+ ComponentContext,
31
+ FrameMountQueue
32
+ >();
33
+
34
+ function component(fn: (...args: any[]) => unknown) {
18
35
  const frame = getComponentContext();
19
36
  if (typeof fn !== "function")
20
37
  throw new TypeError("Lifecycle callback must be a function");
21
38
  return frame;
22
39
  }
40
+ function ensureMountQueue(frame: ComponentContext): FrameMountQueue {
41
+ let queue = frameQueues.get(frame);
42
+ if (!queue) {
43
+ queue = {
44
+ before: [],
45
+ mounted: [],
46
+ beforeUpdate: [],
47
+ updated: [],
48
+ activated: [],
49
+ deactivated: [],
50
+ serverPrefetch: [],
51
+ };
52
+ frameQueues.set(frame, queue);
53
+ const post = getRenderScheduler()?.post ?? queuePostCommit;
54
+ onComponentReady(() => {
55
+ if (frame.owner.disposed) return;
56
+ let failed = false;
57
+ let failure: unknown;
58
+ while (queue!.before.length > 0 && !frame.owner.disposed) {
59
+ const callback = queue!.before.shift()!;
60
+ try {
61
+ runWithOwner(frame.owner, () =>
62
+ untrack(() => {
63
+ if (!frame.owner.disposed) withComponentConsumer(frame, callback);
64
+ }),
65
+ );
66
+ } catch (error) {
67
+ if (!failed) failure = error;
68
+ failed = true;
69
+ }
70
+ }
71
+ if (!frame.owner.disposed) {
72
+ for (const callback of queue!.mounted.splice(0)) {
73
+ post(() => {
74
+ if (frame.owner.disposed) return;
75
+ runWithOwner(frame.owner, () =>
76
+ untrack(() => {
77
+ flushComponentReferences();
78
+ if (!frame.owner.disposed)
79
+ withComponentConsumer(frame, callback);
80
+ }),
81
+ );
82
+ });
83
+ }
84
+ }
85
+ if (failed) throw failure;
86
+ });
87
+ }
88
+ return queue;
89
+ }
90
+ export function onBeforeMount(fn: () => void): void {
91
+ const frame = component(fn);
92
+ if (frame.mode === "ssr") return;
93
+ ensureMountQueue(frame).before.push(fn);
94
+ }
23
95
  export function onMounted(fn: () => void): void {
24
96
  const frame = component(fn);
25
97
  if (frame.mode === "ssr") return;
26
- const post = getRenderScheduler()?.post ?? queuePostCommit;
27
- onComponentReady(() =>
28
- post(() => {
29
- if (frame.owner.disposed) return;
30
- runWithOwner(frame.owner, () =>
31
- untrack(() => {
32
- flushComponentReferences();
33
- if (!frame.owner.disposed) withComponentConsumer(frame, fn);
34
- }),
98
+ ensureMountQueue(frame).mounted.push(fn);
99
+ }
100
+ export function onBeforeUpdate(fn: () => void): void {
101
+ const frame = component(fn);
102
+ if (frame.mode === "ssr") return;
103
+ ensureMountQueue(frame).beforeUpdate.push(fn);
104
+ }
105
+ export function onUpdated(fn: () => void): void {
106
+ const frame = component(fn);
107
+ if (frame.mode === "ssr") return;
108
+ ensureMountQueue(frame).updated.push(fn);
109
+ }
110
+ export function onActivated(fn: () => void): void {
111
+ const frame = component(fn);
112
+ if (frame.mode === "ssr") return;
113
+ const queue = ensureMountQueue(frame);
114
+ queue.activated.push(fn);
115
+ queue.mounted.push(fn);
116
+ }
117
+ export function onDeactivated(fn: () => void): void {
118
+ const frame = component(fn);
119
+ if (frame.mode === "ssr") return;
120
+ ensureMountQueue(frame).deactivated.push(fn);
121
+ onBeforeUnmount(fn);
122
+ }
123
+ export interface ServerPrefetchSession {
124
+ phase: "collect" | "awaiting" | "replay";
125
+ hooks: Array<() => Promise<unknown> | unknown>;
126
+ cells: unknown[];
127
+ cursor: number;
128
+ }
129
+
130
+ let activeServerPrefetchSession: ServerPrefetchSession | undefined;
131
+
132
+ export function peekServerPrefetchSession(): ServerPrefetchSession | undefined {
133
+ return activeServerPrefetchSession;
134
+ }
135
+
136
+ export function withServerPrefetchSession<T>(
137
+ session: ServerPrefetchSession,
138
+ fn: () => T,
139
+ ): T {
140
+ const prev = activeServerPrefetchSession;
141
+ activeServerPrefetchSession = session;
142
+ try {
143
+ return fn();
144
+ } finally {
145
+ activeServerPrefetchSession = prev;
146
+ }
147
+ }
148
+
149
+ export function onServerPrefetch(fn: () => Promise<any>): void {
150
+ const frame = component(fn);
151
+ if (frame.mode !== "ssr") return;
152
+ if (activeServerPrefetchSession) {
153
+ if (activeServerPrefetchSession.phase === "collect") {
154
+ activeServerPrefetchSession.hooks.push(() =>
155
+ Promise.resolve().then(() => untrack(() => fn())),
35
156
  );
36
- }),
37
- );
157
+ }
158
+ return;
159
+ }
160
+ if (!frame.owner.disposed) {
161
+ void Promise.resolve()
162
+ .then(() => untrack(() => fn()))
163
+ .catch(() => {});
164
+ }
38
165
  }
39
166
  export function onBeforeUnmount(fn: () => void): void {
40
167
  const frame = component(fn);
@@ -57,3 +184,9 @@ export function onUnmounted(fn: () => void): void {
57
184
  }),
58
185
  );
59
186
  }
187
+ export function onErrorCaptured<TError = unknown>(
188
+ hook: ErrorCapturedHook<TError>,
189
+ ): void {
190
+ const frame = component(hook);
191
+ registerErrorCaptured(frame, hook);
192
+ }
package/src/map.ts ADDED
@@ -0,0 +1,196 @@
1
+ /** Independent Map instrumentation on the native graph. */
2
+ import { isTracking } from "@tschk/moonshine/tracking";
3
+ import { batch, createSignal } from "@tschk/moonshine-dom/reactive";
4
+
5
+ type Cell = ReturnType<typeof createSignal<number>>;
6
+ type State = {
7
+ target: Map<unknown, unknown>;
8
+ wrap: (value: unknown) => unknown;
9
+ raw: (value: unknown) => unknown;
10
+ keys: Map<unknown, Cell>;
11
+ objects: WeakMap<object, Cell>;
12
+ iteration?: Cell;
13
+ cleared?: Cell;
14
+ };
15
+ const states = new WeakMap<object, State>();
16
+ function state(value: object): State {
17
+ const found = states.get(value);
18
+ if (!found) throw new TypeError("Map method requires a native reactive Map");
19
+ return found;
20
+ }
21
+ const objectKey = (key: unknown): key is object =>
22
+ (typeof key === "object" && key !== null) || typeof key === "function";
23
+ function cell(s: State, key: unknown, create = false): Cell | undefined {
24
+ let found = objectKey(key) ? s.objects.get(key) : s.keys.get(key);
25
+ if (!found && create) {
26
+ found = createSignal(0);
27
+ if (objectKey(key)) s.objects.set(key, found);
28
+ else s.keys.set(key, found);
29
+ }
30
+ return found;
31
+ }
32
+ function trackKey(s: State, key: unknown): void {
33
+ if (!isTracking()) return;
34
+ (s.cleared ??= createSignal(0))[0]();
35
+ cell(s, key, true)![0]();
36
+ }
37
+ function trackIteration(s: State): void {
38
+ if (isTracking()) (s.iteration ??= createSignal(0))[0]();
39
+ }
40
+ function bump(signal: Cell | undefined): void {
41
+ signal?.[1]((version) => version + 1);
42
+ }
43
+ function resolveTargetKey(
44
+ target: Map<unknown, unknown>,
45
+ key: unknown,
46
+ rawKey: unknown,
47
+ ): { found: boolean; targetKey: unknown } {
48
+ if (target.has(key)) return { found: true, targetKey: key };
49
+ if (!Object.is(key, rawKey) && target.has(rawKey)) {
50
+ return { found: true, targetKey: rawKey };
51
+ }
52
+ return { found: false, targetKey: rawKey };
53
+ }
54
+ function iterator(
55
+ receiver: Map<unknown, unknown>,
56
+ mode: "keys" | "values" | "entries",
57
+ ): MapIterator<any> {
58
+ const s = state(receiver);
59
+ trackIteration(s);
60
+ return (function* () {
61
+ for (const [key, value] of s.target) {
62
+ if (mode === "keys") {
63
+ yield s.wrap(key);
64
+ } else if (mode === "values") {
65
+ yield s.wrap(value);
66
+ } else {
67
+ yield [s.wrap(key), s.wrap(value)];
68
+ }
69
+ }
70
+ return undefined;
71
+ })();
72
+ }
73
+ const methods = {
74
+ get size() {
75
+ const s = state(this);
76
+ trackIteration(s);
77
+ return s.target.size;
78
+ },
79
+ has(this: Map<unknown, unknown>, key: unknown) {
80
+ const s = state(this);
81
+ const rawKey = s.raw(key);
82
+ trackKey(s, key);
83
+ if (!Object.is(key, rawKey)) trackKey(s, rawKey);
84
+ return s.target.has(key) || s.target.has(rawKey);
85
+ },
86
+ get(this: Map<unknown, unknown>, key: unknown) {
87
+ const s = state(this);
88
+ const rawKey = s.raw(key);
89
+ trackKey(s, key);
90
+ if (!Object.is(key, rawKey)) trackKey(s, rawKey);
91
+ const { found, targetKey } = resolveTargetKey(s.target, key, rawKey);
92
+ if (!found) return undefined;
93
+ return s.wrap(s.target.get(targetKey));
94
+ },
95
+ set(this: Map<unknown, unknown>, key: unknown, value: unknown) {
96
+ const s = state(this);
97
+ const rawKey = s.raw(key);
98
+ const rawValue = s.raw(value);
99
+ const { found, targetKey } = resolveTargetKey(s.target, key, rawKey);
100
+ if (found) {
101
+ const oldValue = s.target.get(targetKey);
102
+ s.target.set(targetKey, rawValue);
103
+ if (!Object.is(oldValue, rawValue)) {
104
+ batch(() => {
105
+ bump(cell(s, targetKey));
106
+ if (!Object.is(targetKey, rawKey)) bump(cell(s, rawKey));
107
+ if (!Object.is(targetKey, key)) bump(cell(s, key));
108
+ bump(s.iteration);
109
+ });
110
+ }
111
+ } else {
112
+ s.target.set(rawKey, rawValue);
113
+ batch(() => {
114
+ bump(cell(s, rawKey));
115
+ if (!Object.is(key, rawKey)) bump(cell(s, key));
116
+ bump(s.iteration);
117
+ });
118
+ }
119
+ return this;
120
+ },
121
+ delete(this: Map<unknown, unknown>, key: unknown) {
122
+ const s = state(this);
123
+ const rawKey = s.raw(key);
124
+ const { found, targetKey } = resolveTargetKey(s.target, key, rawKey);
125
+ if (!found) return false;
126
+ const deleted = s.target.delete(targetKey);
127
+ if (deleted) {
128
+ batch(() => {
129
+ bump(cell(s, targetKey));
130
+ if (!Object.is(targetKey, rawKey)) bump(cell(s, rawKey));
131
+ if (!Object.is(targetKey, key)) bump(cell(s, key));
132
+ bump(s.iteration);
133
+ });
134
+ }
135
+ return deleted;
136
+ },
137
+ clear(this: Map<unknown, unknown>) {
138
+ const s = state(this);
139
+ if (!s.target.size) return;
140
+ s.target.clear();
141
+ batch(() => {
142
+ bump(s.cleared);
143
+ bump(s.iteration);
144
+ });
145
+ },
146
+ keys(this: Map<unknown, unknown>) {
147
+ return iterator(this, "keys");
148
+ },
149
+ values(this: Map<unknown, unknown>) {
150
+ return iterator(this, "values");
151
+ },
152
+ entries(this: Map<unknown, unknown>) {
153
+ return iterator(this, "entries");
154
+ },
155
+ [Symbol.iterator](this: Map<unknown, unknown>) {
156
+ return iterator(this, "entries");
157
+ },
158
+ forEach(
159
+ this: Map<unknown, unknown>,
160
+ callback: (
161
+ value: unknown,
162
+ key: unknown,
163
+ map: Map<unknown, unknown>,
164
+ ) => void,
165
+ thisArg?: unknown,
166
+ ) {
167
+ if (typeof callback !== "function")
168
+ throw new TypeError("Map callback must be a function");
169
+ const s = state(this);
170
+ trackIteration(s);
171
+ s.target.forEach((value, key) => {
172
+ callback.call(thisArg, s.wrap(value), s.wrap(key), this);
173
+ });
174
+ },
175
+ };
176
+ export function createTrackedMap(
177
+ target: Map<unknown, unknown>,
178
+ wrap: State["wrap"],
179
+ raw: State["raw"],
180
+ ): Map<unknown, unknown> {
181
+ const proxy = new Proxy(target, {
182
+ get(source, key, receiver) {
183
+ return Object.hasOwn(methods, key) && key in source
184
+ ? Reflect.get(methods, key, receiver)
185
+ : Reflect.get(source, key, receiver);
186
+ },
187
+ });
188
+ states.set(proxy, {
189
+ target,
190
+ wrap,
191
+ raw,
192
+ keys: new Map(),
193
+ objects: new WeakMap(),
194
+ });
195
+ return proxy;
196
+ }
@@ -0,0 +1,43 @@
1
+ /** Value comparison for native form models; Set membership stays identity-based. */
2
+ export function equalModelValue(left: unknown, right: unknown): boolean {
3
+ if (left === right) return true;
4
+ if (left instanceof Date || right instanceof Date)
5
+ return left instanceof Date && right instanceof Date && +left === +right;
6
+ if (typeof left === "symbol" || typeof right === "symbol") return false;
7
+ if (Array.isArray(left) || Array.isArray(right)) {
8
+ if (
9
+ !Array.isArray(left) ||
10
+ !Array.isArray(right) ||
11
+ left.length !== right.length
12
+ )
13
+ return false;
14
+ for (let index = 0; index < left.length; index++)
15
+ if (!equalModelValue(left[index], right[index])) return false;
16
+ return true;
17
+ }
18
+ if (
19
+ left !== null &&
20
+ right !== null &&
21
+ typeof left === "object" &&
22
+ typeof right === "object"
23
+ ) {
24
+ const keys = Object.keys(left);
25
+ return (
26
+ keys.length === Object.keys(right).length &&
27
+ keys.every(
28
+ (key) =>
29
+ Object.prototype.hasOwnProperty.call(right, key) &&
30
+ equalModelValue(
31
+ (left as Record<string, unknown>)[key],
32
+ (right as Record<string, unknown>)[key],
33
+ ),
34
+ )
35
+ );
36
+ }
37
+ if (
38
+ (left !== null && typeof left === "object") ||
39
+ (right !== null && typeof right === "object")
40
+ )
41
+ return false;
42
+ return String(left) === String(right);
43
+ }
@@ -0,0 +1,39 @@
1
+ /** Compiler-facing server form models; no DOM or directive runtime. */
2
+ import { h, type SSRChild } from "@tschk/moonshine-dom/ssr";
3
+ import { equalModelValue } from "./model-equality";
4
+ export function createServerTextModel(
5
+ tag: "input" | "textarea",
6
+ props: Record<string, unknown>,
7
+ read: () => unknown,
8
+ ): SSRChild {
9
+ const attributes: Record<string, unknown> = Object.create(null);
10
+ for (const key of Object.keys(props)) attributes[key] = () => props[key];
11
+ const value = read();
12
+ if (tag === "textarea" || value != null) attributes.value = value;
13
+ return h(tag, attributes);
14
+ }
15
+
16
+ /** Checkbox/radio SSR follows the source model policy, including scalar truthiness. */
17
+ export function createServerCheckedModel(
18
+ type: "checkbox" | "radio",
19
+ props: Record<string, unknown>,
20
+ read: () => unknown,
21
+ // Vue source SSR treats fallthrough roots differently from nested inputs.
22
+ nested = false,
23
+ ): SSRChild {
24
+ const attributes: Record<string, unknown> = Object.create(null);
25
+ for (const key of Object.keys(props))
26
+ if (!nested || (key !== "true-value" && key !== "false-value"))
27
+ attributes[key] = () => props[key];
28
+ attributes.type = type;
29
+ const model = read();
30
+ if (type === "radio")
31
+ attributes.checked = equalModelValue(model, props.value);
32
+ else if (nested && "true-value" in props) {
33
+ if (equalModelValue(model, props["true-value"])) attributes.checked = true;
34
+ } else if (Array.isArray(model)) {
35
+ if (model.some((value) => equalModelValue(value, props.value)))
36
+ attributes.checked = true;
37
+ } else if (model || model === "") attributes.checked = true;
38
+ return h("input", attributes);
39
+ }
package/src/model.ts ADDED
@@ -0,0 +1,222 @@
1
+ /** Opt-in form model policy; independent of Vue directives and compiler ABI. */
2
+ import { h } from "@tschk/moonshine-dom/dom";
3
+ import { equalModelValue } from "./model-equality";
4
+ import {
5
+ createRenderEffect,
6
+ getOwner,
7
+ onCleanup,
8
+ untrack,
9
+ } from "@tschk/moonshine-dom/reactive";
10
+
11
+ export type TextModelModifiers = Readonly<{
12
+ lazy?: boolean;
13
+ trim?: boolean;
14
+ number?: boolean;
15
+ }>;
16
+ const numeric = (value: string): string | number => {
17
+ const number = Number.parseFloat(value);
18
+ return Number.isNaN(number) ? value : number;
19
+ };
20
+
21
+ /** Install after attributes, before user input listeners, inside a live owner. */
22
+ export function bindTextModel(
23
+ element: HTMLInputElement | HTMLTextAreaElement,
24
+ read: () => unknown,
25
+ write: (value: string | number) => void,
26
+ modifiers: TextModelModifiers = {},
27
+ ): void {
28
+ const owner = getOwner();
29
+ if (!owner || owner.disposed)
30
+ throw new Error("Text models require a live native owner");
31
+ if (
32
+ !(element instanceof HTMLTextAreaElement) &&
33
+ (!(element instanceof HTMLInputElement) ||
34
+ ![
35
+ "text",
36
+ "search",
37
+ "tel",
38
+ "url",
39
+ "email",
40
+ "password",
41
+ "number",
42
+ "range",
43
+ ].includes(element.type))
44
+ )
45
+ throw new TypeError(
46
+ "Text models require a text or numeric input or textarea",
47
+ );
48
+ if (typeof read !== "function" || typeof write !== "function")
49
+ throw new TypeError("Text models require getter/setter functions");
50
+ const { lazy = false, trim = false, number = false } = modifiers;
51
+ const castNumber = number || element.type === "number";
52
+ let composing = false;
53
+ const listen = (event: string, handler: () => void) => {
54
+ element.addEventListener(event, handler);
55
+ onCleanup(() => element.removeEventListener(event, handler));
56
+ };
57
+ listen(lazy ? "change" : "input", () => {
58
+ if (composing) return;
59
+ let value: string | number = trim ? element.value.trim() : element.value;
60
+ if (castNumber) value = numeric(value);
61
+ untrack(() => write(value));
62
+ });
63
+ if (trim)
64
+ listen("change", () => {
65
+ element.value = element.value.trim();
66
+ });
67
+ if (!lazy) {
68
+ listen("compositionstart", () => {
69
+ composing = true;
70
+ });
71
+ const end = () => {
72
+ if (!composing) return;
73
+ composing = false;
74
+ element.dispatchEvent(
75
+ new element.ownerDocument.defaultView!.Event("input"),
76
+ );
77
+ };
78
+ listen("compositionend", end);
79
+ listen("change", end);
80
+ }
81
+ let mounted = false;
82
+ let previous: unknown;
83
+ createRenderEffect(() => {
84
+ const value = read();
85
+ const oldValue = previous;
86
+ previous = value;
87
+ const next = value ?? "";
88
+ if (mounted) {
89
+ if (composing) return;
90
+ const current =
91
+ (number || element.type === "number") && !/^0\d/.test(element.value)
92
+ ? numeric(element.value)
93
+ : element.value;
94
+ if (current === next) return;
95
+ if (
96
+ element.ownerDocument.activeElement === element &&
97
+ element.type !== "range"
98
+ ) {
99
+ if (lazy && value === oldValue) return;
100
+ if (trim && element.value.trim() === next) return;
101
+ }
102
+ }
103
+ mounted = true;
104
+ element.value = String(next);
105
+ });
106
+ }
107
+
108
+ /** Compiler-facing element factory; props retain their live component accessors. */
109
+ export function createTextModel(
110
+ tag: "input" | "textarea",
111
+ props: Record<string, unknown>,
112
+ read: () => unknown,
113
+ write: (value: string | number) => void,
114
+ modifiers: TextModelModifiers = {},
115
+ ): HTMLInputElement | HTMLTextAreaElement {
116
+ const attributes: Record<string, unknown> = Object.create(null);
117
+ for (const key of Object.keys(props))
118
+ if (!key.startsWith("on") && key !== "ref")
119
+ attributes[key] = () => props[key];
120
+ attributes.ref = (element: HTMLInputElement | HTMLTextAreaElement) => {
121
+ bindTextModel(element, read, write, modifiers);
122
+ if (typeof props.ref === "function")
123
+ (props.ref as (node: HTMLInputElement | HTMLTextAreaElement) => void)(
124
+ element,
125
+ );
126
+ };
127
+ for (const key of Object.keys(props))
128
+ if (key.startsWith("on")) attributes[key] = props[key];
129
+ return h(tag, attributes) as HTMLInputElement | HTMLTextAreaElement;
130
+ }
131
+
132
+ /** Install after attributes; logical values retain their JavaScript types. */
133
+ export function bindCheckedModel(
134
+ element: HTMLInputElement,
135
+ read: () => unknown,
136
+ write: (value: unknown) => void,
137
+ props: Record<string, unknown> = {},
138
+ ): void {
139
+ const owner = getOwner();
140
+ if (!owner || owner.disposed)
141
+ throw new Error("Checked models require a live native owner");
142
+ if (
143
+ !(element instanceof HTMLInputElement) ||
144
+ (element.type !== "checkbox" && element.type !== "radio")
145
+ )
146
+ throw new TypeError("Checked models require a checkbox or radio input");
147
+ if (typeof read !== "function" || typeof write !== "function")
148
+ throw new TypeError("Checked models require getter/setter functions");
149
+ const radio = element.type === "radio";
150
+ const checkedValue = (checked: boolean) => {
151
+ const key = checked ? "true-value" : "false-value";
152
+ return key in props ? props[key] : checked;
153
+ };
154
+ const change = () =>
155
+ untrack(() => {
156
+ const value = "value" in props ? props.value : element.value;
157
+ if (radio) {
158
+ write(value);
159
+ return;
160
+ }
161
+ const model = read();
162
+ const checked = element.checked;
163
+ if (Array.isArray(model)) {
164
+ const index = model.findIndex((entry) => equalModelValue(entry, value));
165
+ if (checked && index < 0) write([...model, value]);
166
+ else if (!checked && index >= 0) {
167
+ const next = model.slice();
168
+ next.splice(index, 1);
169
+ write(next);
170
+ }
171
+ } else if (model instanceof Set) {
172
+ const next = new Set(model);
173
+ if (checked) next.add(value);
174
+ else next.delete(value);
175
+ write(next);
176
+ } else write(checkedValue(checked));
177
+ });
178
+ element.addEventListener("change", change);
179
+ onCleanup(() => element.removeEventListener("change", change));
180
+ let previous: unknown;
181
+ createRenderEffect(() => {
182
+ const model = read();
183
+ const value = props.value;
184
+ const oldValue = previous;
185
+ previous = model;
186
+ if (radio) element.checked = equalModelValue(model, value);
187
+ else if (Array.isArray(model))
188
+ element.checked = model.some((entry) => equalModelValue(entry, value));
189
+ else if (model instanceof Set) element.checked = model.has(value);
190
+ else if (model !== oldValue)
191
+ element.checked = equalModelValue(model, checkedValue(true));
192
+ });
193
+ }
194
+
195
+ /** Compiler-facing checked input factory, with model handlers before user handlers. */
196
+ export function createCheckedModel(
197
+ type: "checkbox" | "radio",
198
+ props: Record<string, unknown>,
199
+ read: () => unknown,
200
+ write: (value: unknown) => void,
201
+ ): HTMLInputElement {
202
+ const attributes: Record<string, unknown> = Object.create(null);
203
+ for (const key of Object.keys(props))
204
+ if (
205
+ !key.startsWith("on") &&
206
+ key !== "checked" &&
207
+ key !== "value" &&
208
+ key !== "ref"
209
+ )
210
+ attributes[key] = () => props[key];
211
+ if (props.value != null) attributes.value = () => props.value;
212
+ attributes.type = type;
213
+ attributes.ref = (element: HTMLInputElement) => {
214
+ if ("checked" in props) element.checked = Boolean(props.checked);
215
+ bindCheckedModel(element, read, write, props);
216
+ if (typeof props.ref === "function")
217
+ (props.ref as (node: HTMLInputElement) => void)(element);
218
+ };
219
+ for (const key of Object.keys(props))
220
+ if (key.startsWith("on")) attributes[key] = props[key];
221
+ return h("input", attributes) as HTMLInputElement;
222
+ }