@fiorejs/signals 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) [2026] [Vangel Trajkovski]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,158 @@
1
- # Temporary Holding Version
1
+ # @fiorejs/signals
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Signals for [fiorejs](https://github.com/vrtexe/fiore). Bind a signal to a property, attribute or child, and only that spot in the DOM updates when the signal changes. Nothing re-renders and nothing is diffed.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install fiorejs @fiorejs/signals
9
+ ```
10
+
11
+ Importing the package registers it with fiorejs, so there is no setup step.
12
+
13
+ ## Usage
14
+
15
+ ```js
16
+ import { div, button, span } from 'fiorejs';
17
+ import { state, computed } from '@fiorejs/signals';
18
+
19
+ const count = state(0);
20
+ const double = computed(() => count.get() * 2);
21
+
22
+ document.body.append(
23
+ div({
24
+ attributes: { class: () => (count.get() > 5 ? 'many' : 'few') },
25
+ children: [
26
+ button({ event: { click: () => count.set(count.get() + 1) }, children: '+1' }),
27
+ span({ children: count }),
28
+ span({ children: () => ` doubled: ${double.get()}` }),
29
+ ],
30
+ }),
31
+ );
32
+ ```
33
+
34
+ ## Primitives
35
+
36
+ | Function | What it does |
37
+ | --- | --- |
38
+ | `state(value)` | A value with `get()`, `set(value)`, `update(fn)` and `mutate(fn)`. `update` sets the value `fn` returns, `mutate` changes the value in place. Reading it inside an effect, a computed or a binding subscribes to it. Setting an equal value (`Object.is`) does nothing. |
39
+ | `computed(fn)` | A value derived from other signals. It is calculated on first read and again on the next read after an input changed. It keeps its value while an effect or binding reads it, also when that reader reruns for another reason. If `fn` throws, the error is kept like a value and thrown on every read until an input changes; a reader that catches it stays subscribed and recovers then. While nothing reads it inside an effect or binding, it does not stay subscribed to its inputs and is recalculated on every read. |
40
+ | `effect(fn)` | Runs `fn` now and whenever a signal it read changes. Returns a function that stops it. If `fn` returns a function, that function runs before the next run and when the effect stops. |
41
+ | `untrack(fn)` | Runs `fn` without subscribing to the signals it reads. |
42
+ | `read(value)` | Returns the current value of a signal, a getter function or a plain value. |
43
+ | `resource(source, fetcher)` | Loads a value asynchronously, like Solid's `createResource`; see [Loading data](#loading-data). |
44
+ | `each(items, render, key)` | Renders a list and reuses the nodes of items whose key is unchanged. `render` gets the item's index at the time its row is created. |
45
+
46
+ Setting a signal runs its effects before `set()` returns. A signal set while an effect runs, including its first run, is handled after that run has finished, so an effect is never re-entered.
47
+
48
+ An effect or binding that throws is stopped, and its error is reported with `reportError` (`console.error` where that does not exist); the other effects keep running, and `set()` and `effect()` never throw because of an effect. A cleanup that throws is reported and does not stop its effect. An effect that runs more than 100 times in one update, usually because it sets a signal it reads, is reported and stopped the same way.
49
+
50
+ ## Loading data
51
+
52
+ `resource(source, fetcher)` calls `fetcher` with the value of `source` and loads again whenever `source` changes; while `source` gives `null`, `undefined` or `false`, nothing is loaded. `resource(fetcher)` loads once. The fetcher runs untracked and gets an `AbortSignal` that aborts when a newer load starts or the effect or list row the resource was created in goes away; the result of an older load is ignored.
53
+
54
+ The resource is a signal of the last loaded value, which it keeps while it reloads, with `loading` and `error` as signals, `refetch()` to load again and `mutate(value)` to set the value without loading. `error` is cleared when a new load starts.
55
+
56
+ ```js
57
+ import { div } from 'fiorejs';
58
+ import { resource, state } from '@fiorejs/signals';
59
+
60
+ const userId = state(1);
61
+ const user = resource(userId, (id, { signal }) => fetch(`/users/${id}`, { signal }).then((response) => response.json()));
62
+
63
+ div({
64
+ children: () => (user.error.get() ? 'Could not load' : user.loading.get() ? 'Loading…' : user.get().name),
65
+ });
66
+ ```
67
+
68
+ ## Binding to the DOM
69
+
70
+ A value is live when it is a signal or a function:
71
+
72
+ - a signal binds to its current value: `children: count`, `props: { value: name }`
73
+ - a function is called inside an effect and binds to its result: `attributes: { class: () => ... }`, `children: () => ...`
74
+
75
+ Functions in `event`, and properties or attributes whose name starts with `on` in any case, are listeners and never bindings. A live child can return text, a node, a list of nodes or nothing.
76
+
77
+ ## Components
78
+
79
+ A component is a function that runs once, so pass signals or getters to it, not their current values. `Reactive<T>` accepts all three forms, and `read()` unwraps them:
80
+
81
+ ```ts
82
+ import { div } from 'fiorejs';
83
+ import { computed, read, type Reactive } from '@fiorejs/signals';
84
+
85
+ function Price(props: { amount: Reactive<number> }) {
86
+ const label = computed(() => `${read(props.amount).toFixed(2)} CHF`);
87
+ return div({ children: label });
88
+ }
89
+
90
+ Price({ amount: 12 });
91
+ Price({ amount: total });
92
+ Price({ amount: () => total.get() * 1.081 });
93
+ ```
94
+
95
+ ## Lists
96
+
97
+ `each` reuses the node of every item whose key it has seen before and only renders new items. Without a key, the item itself is the key; a key that appears more than once gets one row per occurrence. When the order changes, only the rows that are out of place are moved, so a focused input in an unmoved row keeps its focus; browsers with `moveBefore` keep it in moved rows too. If `render` throws, the error is reported and the list keeps the rows it had, but stops updating like any binding that throws.
98
+
99
+ `each(...)` returns a getter, so put it directly into `children`. Inside a live child, call it: `() => (show.get() ? each(items, render)() : null)`; rows are then reused only while that live child does not rerun.
100
+
101
+ ```js
102
+ import { ul, li } from 'fiorejs';
103
+ import { each, state } from '@fiorejs/signals';
104
+
105
+ const todos = state([{ id: 1, text: 'Write docs' }]);
106
+
107
+ ul({ children: each(todos, (todo) => li({ children: todo.text }), (todo) => todo.id) });
108
+
109
+ todos.set([...todos.get(), { id: 2, text: 'Publish' }]);
110
+ ```
111
+
112
+ Lists of a few thousand rows are fine: in Chromium, 1,000 rows with three bound inputs each render in about 40 ms including layout, a change to one row takes well under a millisecond, and adding, removing or swapping rows moves only the rows involved. For much longer lists the number of DOM nodes becomes the limit, so paginate or render only the visible rows.
113
+
114
+ ## Arrays and objects
115
+
116
+ A signal tracks its value, not what is inside it. Replace arrays and objects instead of changing them:
117
+
118
+ ```js
119
+ todos.set([...todos.get(), next]); // updates
120
+ todos.get().push(next); // does not update
121
+ user.set({ ...user.get(), name: 'Grace' }); // updates
122
+ ```
123
+
124
+ Copying is cheap for most lists, because only references are copied. For very large arrays or objects, `mutate(fn)` changes the value in place and notifies even though it is still the same array; the return value of `fn` is ignored:
125
+
126
+ ```js
127
+ todos.mutate((list) => list.push(next));
128
+ ```
129
+
130
+ For deeply nested data, give the fields that change on their own their own signal.
131
+
132
+ ## Global state
133
+
134
+ A signal created at the top of a module is shared by everything that imports it:
135
+
136
+ ```js
137
+ // store.js
138
+ export const user = state(null);
139
+ ```
140
+
141
+ ## Cleanup
142
+
143
+ Bindings are stopped automatically:
144
+
145
+ - when a live child replaces its content, the bindings inside the old content stop for good
146
+ - when `each` drops an item, or the effect around the list reruns, the bindings inside its rows stop for good
147
+ - when an element is removed from the document, its bindings pause; if it is inserted again, they resume with the current values
148
+ - a live child follows its own nodes, so it pauses and resumes correctly also when it was built in one place and moved, for example out of a JSX fragment
149
+
150
+ Removal and insertion are detected with a `MutationObserver` on the document, so elements inside a shadow root are not paused.
151
+
152
+ An element that is created but never inserted keeps its bindings for as long as its signals live. Bindings are held weakly, so once the element and its signals are no longer referenced, everything can be garbage-collected.
153
+
154
+ ## Limits
155
+
156
+ - Functions passed as properties are treated as bindings, so a custom element property that expects a function has to be set in code.
157
+ - There is no `batch()` yet: outside an effect, every `set()` runs its effects immediately.
158
+ - `refetch()` on a resource whose effect or list row has gone away still starts a load; call it only while the resource is in use.
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@fiorejs/signals",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Signals for fiorejs. Bind state to properties, attributes and children, and only the bound DOM spot updates.",
5
+ "license": "MIT",
6
+ "author": "vrtexe",
7
+ "type": "module",
8
+ "keywords": [
9
+ "fiore",
10
+ "fiorejs",
11
+ "signals",
12
+ "reactivity",
13
+ "state",
14
+ "dom"
15
+ ],
16
+ "exports": {
17
+ ".": {
18
+ "types": "./src/signals.d.ts",
19
+ "default": "./src/signals.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "src"
24
+ ],
25
+ "scripts": {
26
+ "test": "tsc -p test && node --expose-gc --test test/signals.test.js"
27
+ },
28
+ "peerDependencies": {
29
+ "fiorejs": "^1.2.0"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "homepage": "https://github.com/vrtexe/fiore/tree/main/packages/signals#readme",
35
+ "bugs": {
36
+ "url": "https://github.com/vrtexe/fiore/issues"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/vrtexe/fiore.git",
41
+ "directory": "packages/signals"
42
+ },
43
+ "devDependencies": {
44
+ "fiorejs": "file:../..",
45
+ "jsdom": "^31.0.1",
46
+ "typescript": "~5.9"
47
+ }
48
+ }
@@ -0,0 +1,66 @@
1
+ import type { Plugin } from 'fiorejs/type/base.dom.d.ts';
2
+
3
+ declare const SIGNAL: unique symbol;
4
+
5
+ export interface Signal<T> {
6
+ readonly [SIGNAL]: true;
7
+ get(): T;
8
+ }
9
+
10
+ export interface State<T> extends Signal<T> {
11
+ set(value: T): void;
12
+ /** Sets the value that `fn` returns for the current value, for example `(count) => count + 1`. */
13
+ update(fn: (value: T) => T): void;
14
+ /** Changes the value in place, for example with `list.push(item)`, and always notifies; the return value is ignored. */
15
+ mutate(fn: (value: T) => unknown): void;
16
+ }
17
+
18
+ export interface Computed<T> extends Signal<T> {}
19
+
20
+ /** A plain value, a signal or a getter; components that accept it work with static and live data. */
21
+ export type Reactive<T> = T | Signal<T> | (() => T);
22
+
23
+ export function state<T>(value: T): State<T>;
24
+ export function computed<T>(fn: () => T): Computed<T>;
25
+ export function effect(fn: () => void | (() => void)): () => void;
26
+ export function untrack<T>(fn: () => T): T;
27
+ export function isSignal(value: unknown): value is Signal<unknown>;
28
+ export function read<T>(value: Reactive<T>): T;
29
+ export function each<T, N extends Node = Node>(
30
+ items: Reactive<readonly T[]>,
31
+ render: (item: T, index: number) => N,
32
+ key?: (item: T) => unknown,
33
+ ): () => N[];
34
+
35
+ export interface Resource<T> extends Signal<T | undefined> {
36
+ /** True while a load is running. */
37
+ readonly loading: Signal<boolean>;
38
+ /** The error of the last load, cleared when a new load starts. */
39
+ readonly error: Signal<unknown>;
40
+ /** Loads again with the last source value. */
41
+ refetch(): void;
42
+ /** Sets the value without loading. */
43
+ mutate(value: T): void;
44
+ }
45
+
46
+ export interface ResourceInfo {
47
+ /** Aborts when a newer load starts or the resource is stopped. */
48
+ signal: AbortSignal;
49
+ }
50
+
51
+ export function resource<T>(fetcher: (value: true, info: ResourceInfo) => T | Promise<T>): Resource<T>;
52
+ export function resource<S, T>(
53
+ source: Signal<S | null | undefined | false> | (() => S | null | undefined | false),
54
+ fetcher: (value: S, info: ResourceInfo) => T | Promise<T>,
55
+ ): Resource<T>;
56
+
57
+ export const plugin: Plugin;
58
+
59
+ declare module 'fiorejs/type/base.dom.d.ts' {
60
+ interface LiveValues<T> {
61
+ signal: Signal<T>;
62
+ getter: () => T;
63
+ }
64
+ }
65
+
66
+ export {};
package/src/signals.js ADDED
@@ -0,0 +1,674 @@
1
+ import { use } from 'fiorejs';
2
+
3
+ const SIGNAL = Symbol.for('fiorejs.signal');
4
+
5
+ /**
6
+ * @typedef {{ subs: Set<Computation>, release?(): void, missed?: boolean }} Source
7
+ * @typedef {{ sources: Set<Source>, stale(): void }} Computation
8
+ * @typedef {{ owned: (() => void)[] }} Owner
9
+ */
10
+
11
+ /** @type {Computation | null} */
12
+ let current = null;
13
+ /** @type {Owner | null} */
14
+ let owner = null;
15
+ /** @type {Set<{ run(): void, stop(): void }>} */
16
+ const pending = new Set();
17
+ let flushing = false;
18
+
19
+ /** How often one effect may run in a single update before it counts as a loop. */
20
+ const MAX_RUNS = 100;
21
+
22
+ /** @param {Source} source */
23
+ function track(source) {
24
+ if (current) {
25
+ source.subs.add(current);
26
+ current.sources.add(source);
27
+ }
28
+ }
29
+
30
+ /** @param {Source} source */
31
+ function notify(source) {
32
+ for (const sub of source.subs) {
33
+ sub.stale();
34
+ }
35
+ flush();
36
+ }
37
+
38
+ function flush() {
39
+ if (flushing) {
40
+ return;
41
+ }
42
+ flushing = true;
43
+ /** @type {Map<object, number>} */
44
+ const runs = new Map();
45
+ try {
46
+ for (const effect of pending) {
47
+ pending.delete(effect);
48
+ const count = (runs.get(effect) ?? 0) + 1;
49
+ runs.set(effect, count);
50
+ if (count > MAX_RUNS) {
51
+ // Only the looping effect stops; the others still run.
52
+ report(new Error(`An effect ran more than ${MAX_RUNS} times in one update; it probably sets a signal it reads.`));
53
+ effect.stop();
54
+ continue;
55
+ }
56
+ effect.run();
57
+ }
58
+ } finally {
59
+ flushing = false;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Unsubscribes a computation from sources; a source left without subscribers releases its own sources.
65
+ * @param {Computation} computation
66
+ * @param {Iterable<Source>} sources
67
+ */
68
+ function unsubscribe(computation, sources) {
69
+ for (const source of sources) {
70
+ source.subs.delete(computation);
71
+ if (source.subs.size === 0) {
72
+ source.release?.();
73
+ }
74
+ }
75
+ }
76
+
77
+ /** @param {Computation} computation */
78
+ function untrackSources(computation) {
79
+ const sources = computation.sources;
80
+ computation.sources = new Set();
81
+ unsubscribe(computation, sources);
82
+ }
83
+
84
+ /**
85
+ * @template T
86
+ * @param {Computation | null} computation
87
+ * @param {Owner | null} nextOwner
88
+ * @param {() => T} fn
89
+ * @returns {T}
90
+ */
91
+ function runIn(computation, nextOwner, fn) {
92
+ const [previous, previousOwner] = [current, owner];
93
+ current = computation;
94
+ owner = nextOwner;
95
+ try {
96
+ return fn();
97
+ } finally {
98
+ current = previous;
99
+ owner = previousOwner;
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Runs `fn` for a computation, then unsubscribes only from the sources this run no longer read, so a source that
105
+ * is read again, a computed in particular, keeps its subscription and its cached value.
106
+ * @template T
107
+ * @param {Computation} computation
108
+ * @param {Owner | null} nextOwner
109
+ * @param {() => T} fn
110
+ * @returns {T}
111
+ */
112
+ function runTracked(computation, nextOwner, fn) {
113
+ const previous = computation.sources;
114
+ computation.sources = new Set();
115
+ let completed = false;
116
+ try {
117
+ const result = runIn(computation, nextOwner, fn);
118
+ completed = true;
119
+ return result;
120
+ } finally {
121
+ if (completed) {
122
+ unsubscribe(
123
+ computation,
124
+ [...previous].filter((source) => !computation.sources.has(source)),
125
+ );
126
+ } else {
127
+ // A run that threw may have stopped before reading its sources; it keeps following them, and a computed among
128
+ // them that is still dirty passes its next change on, so the next change runs it again.
129
+ for (const source of previous) {
130
+ if (!computation.sources.has(source)) {
131
+ computation.sources.add(source);
132
+ source.missed = true;
133
+ }
134
+ }
135
+ }
136
+ }
137
+ }
138
+
139
+ /**
140
+ * A value that can be read and written; reading it inside an effect or computed subscribes.
141
+ * @template T
142
+ * @param {T} value
143
+ */
144
+ export function state(value) {
145
+ /** @type {Source} */
146
+ const source = { subs: new Set() };
147
+
148
+ /** @param {T} next */
149
+ function set(next) {
150
+ if (!Object.is(next, value)) {
151
+ value = next;
152
+ notify(source);
153
+ }
154
+ }
155
+
156
+ return {
157
+ [SIGNAL]: true,
158
+ get() {
159
+ track(source);
160
+ return value;
161
+ },
162
+ set,
163
+ /**
164
+ * Sets the value that `fn` returns for the current value, for example `(count) => count + 1`.
165
+ * @param {(value: T) => T} fn
166
+ */
167
+ update(fn) {
168
+ set(fn(value));
169
+ },
170
+ /**
171
+ * Changes the value in place, for example with `list.push(item)`, and always notifies.
172
+ * @param {(value: T) => unknown} fn
173
+ */
174
+ mutate(fn) {
175
+ // The value may already have changed when fn throws, so readers are notified either way.
176
+ try {
177
+ fn(value);
178
+ } finally {
179
+ notify(source);
180
+ }
181
+ },
182
+ };
183
+ }
184
+
185
+ /**
186
+ * A cached value derived from other signals; recalculated on read after an input changed.
187
+ * @template T
188
+ * @param {() => T} fn
189
+ */
190
+ export function computed(fn) {
191
+ /** @type {T} */
192
+ let value;
193
+ /** @type {{ error: unknown } | undefined} An error from the last calculation, cached like a value. */
194
+ let failure;
195
+ let dirty = true;
196
+ /** @type {Source & Computation} */
197
+ const node = {
198
+ subs: new Set(),
199
+ sources: new Set(),
200
+ stale() {
201
+ // Already dirty means the readers heard of the change, unless one of them failed before reading it again.
202
+ if (dirty && !node.missed) {
203
+ return;
204
+ }
205
+ node.missed = false;
206
+ dirty = true;
207
+ for (const sub of node.subs) {
208
+ sub.stale();
209
+ }
210
+ },
211
+ release,
212
+ };
213
+
214
+ // Without readers a computed lets go of its sources, so it can be collected and is not visited on every set.
215
+ function release() {
216
+ untrackSources(node);
217
+ dirty = true;
218
+ }
219
+
220
+ return {
221
+ [SIGNAL]: true,
222
+ get() {
223
+ // The reader subscribes first, so it stays subscribed even when the calculation throws.
224
+ track(node);
225
+ if (dirty) {
226
+ try {
227
+ value = runTracked(node, null, fn);
228
+ failure = undefined;
229
+ } catch (error) {
230
+ failure = { error };
231
+ }
232
+ dirty = false;
233
+ }
234
+ if (node.subs.size === 0) {
235
+ release();
236
+ }
237
+ if (failure) {
238
+ throw failure.error;
239
+ }
240
+ return value;
241
+ },
242
+ };
243
+ }
244
+
245
+ /**
246
+ * Runs `fn` now and again whenever a signal it read changes; returns a function that stops it.
247
+ * `fn` may return a cleanup function, called before the next run and when stopped.
248
+ * If a run throws, the error is reported and the effect is stopped.
249
+ * @param {() => void | (() => void)} fn
250
+ * @returns {() => void}
251
+ */
252
+ export function effect(fn) {
253
+ /** @type {(() => void) | undefined} */
254
+ let cleanup;
255
+ let stopped = false;
256
+ /** @type {Owner} */
257
+ const scope = { owned: [] };
258
+ /** @type {Computation & { run(): void, stop(): void }} */
259
+ const node = {
260
+ sources: new Set(),
261
+ stale: () => pending.add(node),
262
+ run() {
263
+ if (stopped) {
264
+ return;
265
+ }
266
+ reset();
267
+ try {
268
+ const result = runTracked(node, scope, fn);
269
+ cleanup = typeof result === 'function' ? result : undefined;
270
+ } catch (error) {
271
+ report(error);
272
+ stopped = true;
273
+ }
274
+ // Stopped by its error or during its own run: undo what the run set up.
275
+ if (stopped) {
276
+ stop();
277
+ }
278
+ },
279
+ stop,
280
+ };
281
+
282
+ /**
283
+ * Stops the effects created by the last run and calls its cleanup, keeping the subscriptions. A cleanup that
284
+ * throws is reported and does not keep this effect from running.
285
+ */
286
+ function reset() {
287
+ scope.owned.splice(0).forEach((stopOwned) => stopOwned());
288
+ const done = cleanup;
289
+ cleanup = undefined;
290
+ try {
291
+ done?.();
292
+ } catch (error) {
293
+ report(error);
294
+ }
295
+ }
296
+
297
+ function stop() {
298
+ stopped = true;
299
+ pending.delete(node);
300
+ reset();
301
+ untrackSources(node);
302
+ }
303
+
304
+ owner?.owned.push(stop);
305
+ // Writes during the first run are queued until it has finished, so the run is never re-entered and no cleanup
306
+ // is overwritten.
307
+ const outermost = !flushing;
308
+ flushing = true;
309
+ try {
310
+ node.run();
311
+ } finally {
312
+ if (outermost) {
313
+ flushing = false;
314
+ }
315
+ }
316
+ if (outermost) {
317
+ flush();
318
+ }
319
+ return stop;
320
+ }
321
+
322
+ /**
323
+ * Runs `fn` without subscribing to the signals it reads and without an owning effect.
324
+ * @template T
325
+ * @param {() => T} fn
326
+ * @returns {T}
327
+ */
328
+ export function untrack(fn) {
329
+ return runIn(null, null, fn);
330
+ }
331
+
332
+ /**
333
+ * @param {unknown} value
334
+ * @returns {value is { get(): unknown }}
335
+ */
336
+ export function isSignal(value) {
337
+ return typeof value === 'object' && value !== null && SIGNAL in value;
338
+ }
339
+
340
+ /**
341
+ * Returns the current value of a signal, a getter or a plain value.
342
+ * @template T
343
+ * @param {import('./signals.d.ts').Reactive<T>} value
344
+ * @returns {T}
345
+ */
346
+ export function read(value) {
347
+ if (isSignal(value)) {
348
+ return /** @type {T} */ (value.get());
349
+ }
350
+ return typeof value === 'function' ? /** @type {() => T} */ (value)() : /** @type {T} */ (value);
351
+ }
352
+
353
+ /**
354
+ * Loads a value with `fetcher`, and again whenever `source` changes, like Solid's createResource. While `source`
355
+ * gives null, undefined or false nothing is loaded. `fetcher` gets the source value and an AbortSignal that aborts
356
+ * when a newer load starts or the resource is stopped with its owner; the result of an older load is ignored.
357
+ * @param {unknown} source a signal or getter, or the fetcher when there is no source
358
+ * @param {(value: any, info: { signal: AbortSignal }) => unknown} [fetcher]
359
+ */
360
+ export function resource(source, fetcher) {
361
+ if (!fetcher) {
362
+ fetcher = /** @type {(value: any, info: { signal: AbortSignal }) => unknown} */ (source);
363
+ source = () => true;
364
+ }
365
+ const load = fetcher;
366
+ const value = state(/** @type {unknown} */ (undefined));
367
+ const loading = state(false);
368
+ const error = state(/** @type {unknown} */ (undefined));
369
+ /** @type {unknown} */
370
+ let input;
371
+ /** @type {AbortController | undefined} */
372
+ let controller;
373
+
374
+ function start() {
375
+ controller?.abort();
376
+ const own = new AbortController();
377
+ controller = own;
378
+ loading.set(true);
379
+ error.set(undefined);
380
+ // Called inside the promise, so a synchronous throw from the fetcher becomes the error too.
381
+ new Promise((resolve) => resolve(untrack(() => load(input, { signal: own.signal })))).then(
382
+ (result) => {
383
+ if (controller === own) {
384
+ value.set(result);
385
+ loading.set(false);
386
+ }
387
+ },
388
+ (reason) => {
389
+ if (controller === own) {
390
+ error.set(reason);
391
+ loading.set(false);
392
+ }
393
+ },
394
+ );
395
+ }
396
+
397
+ const active = () => input != null && input !== false;
398
+
399
+ effect(() => {
400
+ input = read(/** @type {import('./signals.d.ts').Reactive<unknown>} */ (source));
401
+ if (!active()) {
402
+ loading.set(false);
403
+ return;
404
+ }
405
+ start();
406
+ return () => {
407
+ controller?.abort();
408
+ controller = undefined;
409
+ };
410
+ });
411
+
412
+ return {
413
+ [SIGNAL]: true,
414
+ get: value.get,
415
+ loading: { [SIGNAL]: true, get: loading.get },
416
+ error: { [SIGNAL]: true, get: error.get },
417
+ /** Loads again with the last source value. */
418
+ refetch() {
419
+ if (active()) {
420
+ start();
421
+ }
422
+ },
423
+ /** Sets the value without loading, for example after an optimistic change. */
424
+ mutate: value.set,
425
+ };
426
+ }
427
+
428
+ /**
429
+ * @typedef {{ node: Node, stop: () => void }} Row
430
+ */
431
+
432
+ /**
433
+ * Renders a list and reuses the nodes of items whose key is unchanged. `index` is the item's index when its row
434
+ * was created; a reused row keeps it.
435
+ * @template T
436
+ * @param {import('./signals.d.ts').Reactive<readonly T[]>} items
437
+ * @param {(item: T, index: number) => Node} render
438
+ * @param {(item: T) => unknown} [key]
439
+ */
440
+ export function each(items, render, key = (item) => item) {
441
+ /** @type {Map<unknown, Row[]>} Rows by key; a repeated key keeps one row per occurrence. */
442
+ let rows = new Map();
443
+
444
+ owner?.owned.push(() => {
445
+ const old = rows;
446
+ rows = new Map();
447
+ [...old.values()].flat().forEach((row) => row.stop());
448
+ });
449
+
450
+ return () => {
451
+ /** @type {Map<unknown, Row[]>} */
452
+ const next = new Map();
453
+ /** @type {Map<unknown, number>} */
454
+ const taken = new Map();
455
+ /** @type {Row[]} */
456
+ const created = [];
457
+ /** @type {Node[]} */
458
+ let nodes;
459
+ try {
460
+ nodes = read(items).map((item, index) => {
461
+ const id = key(item);
462
+ const used = taken.get(id) ?? 0;
463
+ let row = rows.get(id)?.[used];
464
+ if (row) {
465
+ taken.set(id, used + 1);
466
+ } else {
467
+ row = createRow(() => render(item, index));
468
+ created.push(row);
469
+ }
470
+ const list = next.get(id);
471
+ if (list) {
472
+ list.push(row);
473
+ } else {
474
+ next.set(id, [row]);
475
+ }
476
+ return row.node;
477
+ });
478
+ } catch (error) {
479
+ // The old rows stay as they were; only the rows made in this failed pass are stopped.
480
+ created.forEach((row) => row.stop());
481
+ throw error;
482
+ }
483
+
484
+ const kept = new Set([...next.values()].flat());
485
+ const old = rows;
486
+ rows = next;
487
+ for (const row of [...old.values()].flat()) {
488
+ if (!kept.has(row)) {
489
+ row.stop();
490
+ }
491
+ }
492
+ return nodes;
493
+ };
494
+ }
495
+
496
+ /**
497
+ * @param {() => Node} render
498
+ * @returns {Row}
499
+ */
500
+ function createRow(render) {
501
+ /** @type {Owner} */
502
+ const scope = { owned: [] };
503
+ const stop = () => scope.owned.splice(0).forEach((stopOwned) => stopOwned());
504
+ try {
505
+ return { node: runIn(null, scope, render), stop };
506
+ } catch (error) {
507
+ stop();
508
+ throw error;
509
+ }
510
+ }
511
+
512
+ /**
513
+ * @typedef {{
514
+ * anchor: () => Node | undefined,
515
+ * keyed?: Node,
516
+ * start: () => () => void,
517
+ * stop?: () => void,
518
+ * }} Binding
519
+ */
520
+
521
+ /**
522
+ * Bindings by the node whose place in the document they follow: the element for a property or attribute, the first
523
+ * node of the slot for a child, which moves with the slot, for example out of a fragment.
524
+ * @type {WeakMap<Node, Set<Binding>>}
525
+ */
526
+ const bindings = new WeakMap();
527
+ let observing = false;
528
+
529
+ /** Pauses the bindings of nodes that leave the document and resumes them when they come back. */
530
+ function observe() {
531
+ if (observing || typeof MutationObserver === 'undefined') {
532
+ return;
533
+ }
534
+ observing = true;
535
+ new MutationObserver((records) => {
536
+ /** @type {Set<Node>} */
537
+ const removed = new Set();
538
+ /** @type {Set<Node>} */
539
+ const added = new Set();
540
+ for (const record of records) {
541
+ record.removedNodes.forEach((node) => removed.add(node));
542
+ record.addedNodes.forEach((node) => added.add(node));
543
+ }
544
+ roots(removed).forEach((node) => visit(node, pause));
545
+ roots(added).forEach((node) => visit(node, resume));
546
+ }).observe(document, { childList: true, subtree: true });
547
+ }
548
+
549
+ /**
550
+ * Drops nodes with an ancestor in the same batch, because walking the ancestor covers them; a deep tree appended
551
+ * level by level is then walked once instead of once per level.
552
+ * @param {Set<Node>} nodes
553
+ */
554
+ function roots(nodes) {
555
+ return [...nodes].filter((node) => {
556
+ for (let parent = node.parentNode; parent; parent = parent.parentNode) {
557
+ if (nodes.has(parent)) {
558
+ return false;
559
+ }
560
+ }
561
+ return true;
562
+ });
563
+ }
564
+
565
+ /**
566
+ * Calls `fn` for every binding that follows `node` or a node below it; an error is reported and does not stop the
567
+ * others.
568
+ * @param {Node} node
569
+ * @param {(binding: Binding) => void} fn
570
+ */
571
+ function visit(node, fn) {
572
+ const walker = document.createTreeWalker(node, 1 | 4 | 128 /* elements, text and comments */);
573
+ for (let current = /** @type {Node | null} */ (node); current; current = walker.nextNode()) {
574
+ const set = bindings.get(current);
575
+ if (!set) {
576
+ continue;
577
+ }
578
+ for (const binding of [...set]) {
579
+ try {
580
+ fn(binding);
581
+ } catch (error) {
582
+ report(error);
583
+ }
584
+ }
585
+ }
586
+ }
587
+
588
+ /** @param {unknown} error */
589
+ function report(error) {
590
+ if (typeof globalThis.reportError === 'function') {
591
+ globalThis.reportError(error);
592
+ } else {
593
+ console.error(error);
594
+ }
595
+ }
596
+
597
+ /** @param {Binding} binding */
598
+ function pause(binding) {
599
+ if (!binding.anchor()?.isConnected) {
600
+ // Cleared first, so a stop that throws still leaves the binding ready to resume.
601
+ const stop = binding.stop;
602
+ binding.stop = undefined;
603
+ stop?.();
604
+ }
605
+ }
606
+
607
+ /** @param {Binding} binding */
608
+ function resume(binding) {
609
+ if (!binding.stop && binding.anchor()?.isConnected) {
610
+ binding.stop = binding.start();
611
+ }
612
+ }
613
+
614
+ /**
615
+ * Files the binding under the node it currently follows.
616
+ * @param {Binding} binding
617
+ */
618
+ function follow(binding) {
619
+ const node = binding.anchor();
620
+ if (!node || node === binding.keyed) {
621
+ return;
622
+ }
623
+ forget(binding);
624
+ let set = bindings.get(node);
625
+ if (!set) {
626
+ set = new Set();
627
+ bindings.set(node, set);
628
+ }
629
+ set.add(binding);
630
+ binding.keyed = node;
631
+ }
632
+
633
+ /** @param {Binding} binding */
634
+ function forget(binding) {
635
+ if (binding.keyed) {
636
+ bindings.get(binding.keyed)?.delete(binding);
637
+ binding.keyed = undefined;
638
+ }
639
+ }
640
+
641
+ /** @type {import('fiorejs/type/base.dom.d.ts').Plugin} */
642
+ export const plugin = {
643
+ name: 'fiorejs-signals',
644
+ bind(value, apply, context) {
645
+ const isListener = context.kind !== 'child' && /^on/i.test(context.name);
646
+ if (!isSignal(value) && (typeof value !== 'function' || isListener)) {
647
+ return false;
648
+ }
649
+ const getter = isSignal(value) ? () => value.get() : /** @type {() => unknown} */ (value);
650
+
651
+ /** @type {Binding} */
652
+ const binding = {
653
+ anchor: () => (context.kind === 'child' ? context.nodes()[0] : context.element),
654
+ start: () =>
655
+ runIn(null, null, () =>
656
+ effect(() => {
657
+ apply(getter());
658
+ follow(binding);
659
+ }),
660
+ ),
661
+ };
662
+ binding.stop = binding.start();
663
+ // The surrounding effect or list row ends the binding for good when it reruns or is removed.
664
+ owner?.owned.push(() => {
665
+ forget(binding);
666
+ binding.stop?.();
667
+ binding.stop = undefined;
668
+ });
669
+ observe();
670
+ return true;
671
+ },
672
+ };
673
+
674
+ use(plugin);