@fiorejs/signals 0.0.9 → 2.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/README.md +64 -29
- package/package.json +3 -2
- package/src/signals.d.ts +34 -19
- package/src/signals.js +493 -253
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ Signals for [fiorejs](https://github.com/vrtexe/fiore). Bind a signal to a prope
|
|
|
8
8
|
npm install fiorejs @fiorejs/signals
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
Signals carry the live-value method fiorejs looks for, so there is no setup step.
|
|
12
12
|
|
|
13
13
|
## Usage
|
|
14
14
|
|
|
@@ -20,14 +20,11 @@ const count = state(0);
|
|
|
20
20
|
const double = computed(() => count.get() * 2);
|
|
21
21
|
|
|
22
22
|
document.body.append(
|
|
23
|
-
div({
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
span({ children: () => ` doubled: ${double.get()}` }),
|
|
29
|
-
],
|
|
30
|
-
}),
|
|
23
|
+
div.attrs({ class: computed(() => (count.get() > 5 ? 'many' : 'few')) }).create([
|
|
24
|
+
button.on({ click: () => count.update((n) => n + 1) }).create('+1'),
|
|
25
|
+
span(count),
|
|
26
|
+
span(computed(() => ` doubled: ${double.get()}`)),
|
|
27
|
+
]),
|
|
31
28
|
);
|
|
32
29
|
```
|
|
33
30
|
|
|
@@ -36,12 +33,16 @@ document.body.append(
|
|
|
36
33
|
| Function | What it does |
|
|
37
34
|
| --- | --- |
|
|
38
35
|
| `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
|
|
36
|
+
| `signal.computed(fn)` | A computed value derived from one signal's value: `count.computed((n) => n * 2)`. |
|
|
37
|
+
| `signal.map(render)`, `signal.for(key).map(render)` | A list that reuses the rows of items it has seen; see [Lists](#lists). |
|
|
38
|
+
| `signal.if(then).else(otherwise)` | Shows one of two branches by the signal's truthiness; see [Conditions](#conditions). |
|
|
39
|
+
| `signal.with(fn)` | Passes the signal to `fn` and returns its result, for reusable steps such as `todos.with(byId)`. |
|
|
40
|
+
| `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. `fn` derives a value and must not set signals: `set`, `update` or `mutate` inside it throws. To correct a value, derive the corrected one (`computed(() => Math.min(page.get(), last.get()))`) or correct it where it is set. |
|
|
40
41
|
| `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
42
|
| `untrack(fn)` | Runs `fn` without subscribing to the signals it reads. |
|
|
42
43
|
| `read(value)` | Returns the current value of a signal, a getter function or a plain value. |
|
|
44
|
+
| `classList(entries)` | A computed value for `className` or the `class` attribute that lists classes by condition; see [Classes](#classes). |
|
|
43
45
|
| `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
|
|
|
46
47
|
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
|
|
|
@@ -55,28 +56,43 @@ The resource is a signal of the last loaded value, which it keeps while it reloa
|
|
|
55
56
|
|
|
56
57
|
```js
|
|
57
58
|
import { div } from 'fiorejs';
|
|
58
|
-
import { resource, state } from '@fiorejs/signals';
|
|
59
|
+
import { computed, resource, state } from '@fiorejs/signals';
|
|
59
60
|
|
|
60
61
|
const userId = state(1);
|
|
61
62
|
const user = resource(userId, (id, { signal }) => fetch(`/users/${id}`, { signal }).then((response) => response.json()));
|
|
62
63
|
|
|
63
|
-
div(
|
|
64
|
-
children: () => (user.error.get() ? 'Could not load' : user.loading.get() ? 'Loading…' : user.get().name),
|
|
65
|
-
});
|
|
64
|
+
div(computed(() => (user.error.get() ? 'Could not load' : user.loading.get() ? 'Loading…' : user.get().name)));
|
|
66
65
|
```
|
|
67
66
|
|
|
68
67
|
## Binding to the DOM
|
|
69
68
|
|
|
70
|
-
A value is live
|
|
69
|
+
A signal is live: it binds to its current value, for example `span(count)`, `input.props({ value: name })` or `div.attrs({ class: computed(() => ...) })`. A function is not live; wherever it appears it is a callback, so a value derived from signals is written `computed(() => ...)`.
|
|
71
70
|
|
|
72
|
-
|
|
73
|
-
- a function is called inside an effect and binds to its result: `attributes: { class: () => ... }`, `children: () => ...`
|
|
71
|
+
A value inside a nested prop binds too, for example `props({ style: { color: computed(() => ...) } })`. Bindings start when the element is created, so a builder used as a template binds once for every element it creates. A live child can return text, a node, a list of nodes or nothing.
|
|
74
72
|
|
|
75
|
-
|
|
73
|
+
A computed that builds elements owns the bindings and effects it creates: they stop before it recalculates and when nothing reads it any more, as they do inside an effect.
|
|
74
|
+
|
|
75
|
+
## Classes
|
|
76
|
+
|
|
77
|
+
`classList` builds the class text from strings, which are always on, and objects whose keys are on while their value is truthy. A value can be a boolean, a signal or a getter:
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
import { div } from 'fiorejs';
|
|
81
|
+
import { circle } from 'fiorejs/svg';
|
|
82
|
+
import { classList, state } from '@fiorejs/signals';
|
|
83
|
+
|
|
84
|
+
const active = state(false);
|
|
85
|
+
const enabled = state(true);
|
|
86
|
+
|
|
87
|
+
div.props({ className: classList(['card', { active, disabled: () => !enabled.get() }]) }).create();
|
|
88
|
+
circle.attrs({ class: classList({ hot: active }) }).create();
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
A condition that is derived from a signal needs a getter or a `computed`: `{ disabled: !enabled.get() }` is evaluated once, when the object is created, and never updates.
|
|
76
92
|
|
|
77
93
|
## Components
|
|
78
94
|
|
|
79
|
-
A component is a function that runs once, so pass signals
|
|
95
|
+
A component is a function that runs once, so pass signals to it, not their current values. `Reactive<T>` accepts a plain value or a signal, and `read()` unwraps both:
|
|
80
96
|
|
|
81
97
|
```ts
|
|
82
98
|
import { div } from 'fiorejs';
|
|
@@ -84,27 +100,44 @@ import { computed, read, type Reactive } from '@fiorejs/signals';
|
|
|
84
100
|
|
|
85
101
|
function Price(props: { amount: Reactive<number> }) {
|
|
86
102
|
const label = computed(() => `${read(props.amount).toFixed(2)} CHF`);
|
|
87
|
-
return div(
|
|
103
|
+
return div(label);
|
|
88
104
|
}
|
|
89
105
|
|
|
90
106
|
Price({ amount: 12 });
|
|
91
107
|
Price({ amount: total });
|
|
92
|
-
Price({ amount: () => total.get() * 1.081 });
|
|
108
|
+
Price({ amount: computed(() => total.get() * 1.081) });
|
|
93
109
|
```
|
|
94
110
|
|
|
111
|
+
## Conditions
|
|
112
|
+
|
|
113
|
+
A component runs once, so `open.get() ? a : b` in markup is read once and never switches. `signal.if(then)` is the live version: it shows what `then` returns while the signal's value is truthy, and nothing otherwise; `.else(otherwise)` adds the other branch.
|
|
114
|
+
|
|
115
|
+
```js
|
|
116
|
+
import { div, em } from 'fiorejs';
|
|
117
|
+
import { state } from '@fiorejs/signals';
|
|
118
|
+
|
|
119
|
+
const open = state(false);
|
|
120
|
+
|
|
121
|
+
div(open.if(() => Details()).else(() => em('closed')));
|
|
122
|
+
div(open.if(() => Details())); // nothing while closed
|
|
123
|
+
div(count.computed((n) => n > 10).if(() => em('many')));
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Both branches are functions, so only the shown branch is built. It is built once and rebuilt only when the truthiness flips, so `count.if(...)` does not rebuild when `count` goes from 1 to 2. When the branch changes, the bindings and effects the old branch created stop. For a condition other than truthiness, derive it first with `signal.computed(...)`. A branch returns text, nodes or nothing; to show a live value in a branch, put it in an element: `.else(() => span(user.computed(...)))`.
|
|
127
|
+
|
|
95
128
|
## Lists
|
|
96
129
|
|
|
97
|
-
`
|
|
130
|
+
`signal.map(render)` renders a list from a signal of an array and reuses the rows of items it has seen before, so it only renders new items. The item itself is the key, so an item replaced by a copy gets a new row. `signal.for().map(render)` keys rows by `item.key`, and `signal.for((item) => item.id).map(render)` by what the function returns. A row is rendered once, for the item it was created with: a copy with the same key reuses the row as it is, so put the fields that change in signals (`{ id, text, done: state(false) }`) when you key a list. A key that appears more than once gets one row per occurrence; items without a `key` field all get the key `undefined` and are matched by position, so such a row keeps showing the item it was created for. A row can be a node or a fragment. 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
131
|
|
|
99
|
-
|
|
132
|
+
A list is a live value, so pass it directly as the children. Each place it is bound keeps its own rows. Inside a computed child, give it its own element: `computed(() => (show.get() ? ul(todos.map(render)) : null))`; rows are then reused only while that computed does not recalculate. `render` gets the item's index at the time its row is created.
|
|
100
133
|
|
|
101
134
|
```js
|
|
102
135
|
import { ul, li } from 'fiorejs';
|
|
103
|
-
import {
|
|
136
|
+
import { state } from '@fiorejs/signals';
|
|
104
137
|
|
|
105
138
|
const todos = state([{ id: 1, text: 'Write docs' }]);
|
|
106
139
|
|
|
107
|
-
ul(
|
|
140
|
+
ul(todos.for((todo) => todo.id).map((todo) => li.create(todo.text)));
|
|
108
141
|
|
|
109
142
|
todos.set([...todos.get(), { id: 2, text: 'Publish' }]);
|
|
110
143
|
```
|
|
@@ -143,16 +176,18 @@ export const user = state(null);
|
|
|
143
176
|
Bindings are stopped automatically:
|
|
144
177
|
|
|
145
178
|
- when a live child replaces its content, the bindings inside the old content stop for good
|
|
146
|
-
- when
|
|
179
|
+
- when a list drops an item, or the effect or computed around the list reruns, the bindings inside its rows stop for good
|
|
147
180
|
- 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
|
|
181
|
+
- a live child among other children keeps its place between two comments, so it pauses and resumes correctly also when its nodes are moved, for example out of a JSX fragment; a live child that is the only child follows its element
|
|
149
182
|
|
|
150
183
|
Removal and insertion are detected with a `MutationObserver` on the document, so elements inside a shadow root are not paused.
|
|
151
184
|
|
|
185
|
+
A page that loads two copies of `@fiorejs/signals` can bind signals from both, but a `computed` or `effect` only tracks signals from its own copy.
|
|
186
|
+
|
|
152
187
|
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
188
|
|
|
154
189
|
## Limits
|
|
155
190
|
|
|
156
|
-
-
|
|
191
|
+
- A computed that returns a nested object, such as `style: computed(() => ({ color }))`, merges that object into the element on every update and never clears a key that disappears from it. Bind each key on its own instead: `style: { color: computed(() => ...) }`.
|
|
157
192
|
- There is no `batch()` yet: outside an effect, every `set()` runs its effects immediately.
|
|
158
193
|
- `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,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fiorejs/signals",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Signals for fiorejs. Bind state to properties, attributes and children, and only the bound DOM spot updates.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "vrtexe",
|
|
7
7
|
"type": "module",
|
|
8
|
+
"sideEffects": false,
|
|
8
9
|
"keywords": [
|
|
9
10
|
"fiore",
|
|
10
11
|
"fiorejs",
|
|
@@ -26,7 +27,7 @@
|
|
|
26
27
|
"test": "tsc -p test && node --expose-gc --test test/signals.test.js"
|
|
27
28
|
},
|
|
28
29
|
"peerDependencies": {
|
|
29
|
-
"fiorejs": "^
|
|
30
|
+
"fiorejs": "^2.0.0"
|
|
30
31
|
},
|
|
31
32
|
"publishConfig": {
|
|
32
33
|
"access": "public"
|
package/src/signals.d.ts
CHANGED
|
@@ -1,10 +1,32 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { LiveValue } from 'fiorejs/type/base.dom.d.ts';
|
|
2
2
|
|
|
3
3
|
declare const SIGNAL: unique symbol;
|
|
4
4
|
|
|
5
|
-
export interface Signal<T> {
|
|
5
|
+
export interface Signal<T> extends LiveValue<T> {
|
|
6
6
|
readonly [SIGNAL]: true;
|
|
7
7
|
get(): T;
|
|
8
|
+
/** A computed value derived from this signal's value. */
|
|
9
|
+
computed<U>(fn: (value: T) => U): Computed<U>;
|
|
10
|
+
/** Passes the signal to `fn` and returns its result, for reusable steps. */
|
|
11
|
+
with<R>(fn: (signal: this) => R): R;
|
|
12
|
+
/** Renders a list and reuses the rows of items it has seen; the item itself is the key. */
|
|
13
|
+
map<U>(this: Signal<readonly U[]>, render: (item: U, index: number) => Node): LiveValue<Node[]>;
|
|
14
|
+
/** Keys the rows of a list by `item.key`, or by what `key` returns. */
|
|
15
|
+
for<U>(this: Signal<readonly U[]>, key?: (item: U) => unknown): Keyed<U>;
|
|
16
|
+
/** Shows what `then` returns while the value is truthy, and nothing otherwise; add `.else(fn)` for the other case. */
|
|
17
|
+
if<A>(then: () => A): When<A, null>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A live value that shows one of two branches; only the shown branch is built. */
|
|
21
|
+
export interface When<A, B> extends LiveValue<A | B> {
|
|
22
|
+
/** Shows what `otherwise` returns while the value is falsy. */
|
|
23
|
+
else<C>(otherwise: () => C): When<A, C>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A signal of a list with its key, waiting for `map`. */
|
|
27
|
+
export interface Keyed<T> {
|
|
28
|
+
/** Renders the list and reuses the rows of items whose key it has seen. */
|
|
29
|
+
map(render: (item: T, index: number) => Node): LiveValue<Node[]>;
|
|
8
30
|
}
|
|
9
31
|
|
|
10
32
|
export interface State<T> extends Signal<T> {
|
|
@@ -17,20 +39,22 @@ export interface State<T> extends Signal<T> {
|
|
|
17
39
|
|
|
18
40
|
export interface Computed<T> extends Signal<T> {}
|
|
19
41
|
|
|
20
|
-
/** A plain value
|
|
21
|
-
export type Reactive<T> = T | Signal<T
|
|
42
|
+
/** A plain value or a signal; components that accept it work with static and live data. */
|
|
43
|
+
export type Reactive<T> = T | Signal<T>;
|
|
22
44
|
|
|
23
45
|
export function state<T>(value: T): State<T>;
|
|
24
46
|
export function computed<T>(fn: () => T): Computed<T>;
|
|
25
47
|
export function effect(fn: () => void | (() => void)): () => void;
|
|
26
48
|
export function untrack<T>(fn: () => T): T;
|
|
27
49
|
export function isSignal(value: unknown): value is Signal<unknown>;
|
|
28
|
-
export function read<T>(value: Reactive<T>): T;
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
50
|
+
export function read<T>(value: Reactive<T> | (() => T)): T;
|
|
51
|
+
/** A class list for `className` or the `class` attribute: strings are always on, object keys while their value is truthy. */
|
|
52
|
+
export function classList(
|
|
53
|
+
entries:
|
|
54
|
+
| string
|
|
55
|
+
| Record<string, Reactive<unknown> | (() => unknown)>
|
|
56
|
+
| readonly (string | Record<string, Reactive<unknown> | (() => unknown)>)[],
|
|
57
|
+
): Computed<string>;
|
|
34
58
|
|
|
35
59
|
export interface Resource<T> extends Signal<T | undefined> {
|
|
36
60
|
/** True while a load is running. */
|
|
@@ -54,13 +78,4 @@ export function resource<S, T>(
|
|
|
54
78
|
fetcher: (value: S, info: ResourceInfo) => T | Promise<T>,
|
|
55
79
|
): Resource<T>;
|
|
56
80
|
|
|
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
81
|
export {};
|
package/src/signals.js
CHANGED
|
@@ -1,7 +1,83 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { LIVE } from 'fiorejs';
|
|
2
2
|
|
|
3
3
|
const SIGNAL = Symbol.for('fiorejs.signal');
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* The base of every signal. Signals inherit their brand, so a signal is not a plain object: fiorejs reads plain objects
|
|
7
|
+
* as data or as nested props.
|
|
8
|
+
* @template T
|
|
9
|
+
*/
|
|
10
|
+
class Signal {
|
|
11
|
+
/** @returns {true} */
|
|
12
|
+
get [SIGNAL]() {
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** @returns {T} */
|
|
17
|
+
get() {
|
|
18
|
+
throw new TypeError('get() is implemented by State, Computed and Resource');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Binds the signal to a property, an attribute or a child of an element.
|
|
23
|
+
* @param {(value: unknown) => void} apply
|
|
24
|
+
* @param {import('fiorejs/type/base.dom.d.ts').BindContext} context
|
|
25
|
+
*/
|
|
26
|
+
[LIVE](apply, context) {
|
|
27
|
+
attach(() => this.get(), apply, context);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A computed value derived from this signal's value.
|
|
32
|
+
* @template U
|
|
33
|
+
* @param {(value: T) => U} fn
|
|
34
|
+
*/
|
|
35
|
+
computed(fn) {
|
|
36
|
+
return computed(() => fn(this.get()));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Passes the signal to `fn` and returns its result, for reusable steps.
|
|
41
|
+
* @template R
|
|
42
|
+
* @param {(signal: this) => R} fn
|
|
43
|
+
* @returns {R}
|
|
44
|
+
*/
|
|
45
|
+
with(fn) {
|
|
46
|
+
return fn(this);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Renders a list and reuses the rows of items it has seen; the item itself is the key.
|
|
51
|
+
* @template U
|
|
52
|
+
* @this {Signal<readonly U[]>}
|
|
53
|
+
* @param {(item: U, index: number) => Node} render
|
|
54
|
+
*/
|
|
55
|
+
map(render) {
|
|
56
|
+
return new List(this, render, (item) => item);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Keys the rows of a list by `item.key`, or by what `key` returns.
|
|
61
|
+
* @template U
|
|
62
|
+
* @this {Signal<readonly U[]>}
|
|
63
|
+
* @param {(item: U) => unknown} [key]
|
|
64
|
+
*/
|
|
65
|
+
for(key = itemKey) {
|
|
66
|
+
return new Keyed(this, key);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Shows what `then` returns while the signal's value is truthy, and nothing otherwise; add `.else(fn)` for the other
|
|
71
|
+
* case. Only the shown branch is built.
|
|
72
|
+
* @template A
|
|
73
|
+
* @param {() => A} then
|
|
74
|
+
* @returns {When<A, null>}
|
|
75
|
+
*/
|
|
76
|
+
if(then) {
|
|
77
|
+
return new When(this, then, () => null);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
5
81
|
/**
|
|
6
82
|
* @typedef {{ subs: Set<Computation>, release?(): void, missed?: boolean }} Source
|
|
7
83
|
* @typedef {{ sources: Set<Source>, stale(): void }} Computation
|
|
@@ -136,50 +212,152 @@ function runTracked(computation, nextOwner, fn) {
|
|
|
136
212
|
}
|
|
137
213
|
}
|
|
138
214
|
|
|
215
|
+
/** A computed derives a value; a write from its run would loop through its own inputs, so it throws instead. */
|
|
216
|
+
function forbidInComputed() {
|
|
217
|
+
if (current instanceof Computed) {
|
|
218
|
+
throw new Error('A computed cannot set a signal; derive the value, or set it in an effect or an event handler.');
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* A value that can be read and written; reading it inside an effect or computed subscribes. The instance is its own
|
|
224
|
+
* source.
|
|
225
|
+
* @template T
|
|
226
|
+
* @extends {Signal<T>}
|
|
227
|
+
*/
|
|
228
|
+
class State extends Signal {
|
|
229
|
+
/** @param {T} value */
|
|
230
|
+
constructor(value) {
|
|
231
|
+
super();
|
|
232
|
+
this._value = value;
|
|
233
|
+
/** @type {Set<Computation>} */
|
|
234
|
+
this.subs = new Set();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
get() {
|
|
238
|
+
track(this);
|
|
239
|
+
return this._value;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** @param {T} next */
|
|
243
|
+
set(next) {
|
|
244
|
+
forbidInComputed();
|
|
245
|
+
if (!Object.is(next, this._value)) {
|
|
246
|
+
this._value = next;
|
|
247
|
+
notify(this);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Sets the value that `fn` returns for the current value, for example `(count) => count + 1`.
|
|
253
|
+
* @param {(value: T) => T} fn
|
|
254
|
+
*/
|
|
255
|
+
update(fn) {
|
|
256
|
+
this.set(fn(this._value));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Changes the value in place, for example with `list.push(item)`, and always notifies.
|
|
261
|
+
* @param {(value: T) => unknown} fn
|
|
262
|
+
*/
|
|
263
|
+
mutate(fn) {
|
|
264
|
+
forbidInComputed();
|
|
265
|
+
// The value may already have changed when fn throws, so readers are notified either way.
|
|
266
|
+
try {
|
|
267
|
+
fn(this._value);
|
|
268
|
+
} finally {
|
|
269
|
+
notify(this);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
139
274
|
/**
|
|
140
275
|
* A value that can be read and written; reading it inside an effect or computed subscribes.
|
|
141
276
|
* @template T
|
|
142
277
|
* @param {T} value
|
|
143
278
|
*/
|
|
144
279
|
export function state(value) {
|
|
145
|
-
|
|
146
|
-
|
|
280
|
+
return new State(value);
|
|
281
|
+
}
|
|
147
282
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
283
|
+
/**
|
|
284
|
+
* A cached value derived from other signals; recalculated on read after an input changed. The instance is its own
|
|
285
|
+
* source, computation and owner: bindings and effects created by a run stop before the next run and when it loses its
|
|
286
|
+
* readers. No cached result means it is dirty.
|
|
287
|
+
* @template T
|
|
288
|
+
* @extends {Signal<T>}
|
|
289
|
+
*/
|
|
290
|
+
class Computed extends Signal {
|
|
291
|
+
/** @param {() => T} fn */
|
|
292
|
+
constructor(fn) {
|
|
293
|
+
super();
|
|
294
|
+
this._fn = fn;
|
|
295
|
+
/** @type {{ value: T } | { error: unknown } | undefined} The last result, an error cached like a value. */
|
|
296
|
+
this._result = undefined;
|
|
297
|
+
/** @type {Set<Computation>} */
|
|
298
|
+
this.subs = new Set();
|
|
299
|
+
/** @type {Set<Source>} */
|
|
300
|
+
this.sources = new Set();
|
|
301
|
+
this.missed = false;
|
|
302
|
+
/** @type {(() => void)[]} */
|
|
303
|
+
this.owned = [];
|
|
304
|
+
/** True while the computed runs, so a change during its own run still reaches its readers. */
|
|
305
|
+
this._running = false;
|
|
306
|
+
/** Set when an input changes during the current run, so that run is not cached. */
|
|
307
|
+
this._changed = false;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
stale() {
|
|
311
|
+
// Already dirty means the readers heard of the change, unless one of them failed before reading it again, or the
|
|
312
|
+
// change came during this computed's own run.
|
|
313
|
+
if (!this._result && !this.missed && !this._running) {
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
this.missed = false;
|
|
317
|
+
this._result = undefined;
|
|
318
|
+
this._changed = this._running;
|
|
319
|
+
for (const sub of this.subs) {
|
|
320
|
+
sub.stale();
|
|
153
321
|
}
|
|
154
322
|
}
|
|
155
323
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
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.
|
|
324
|
+
/** Without readers a computed lets go of its sources, so it can be collected and is not visited on every set. */
|
|
325
|
+
release() {
|
|
326
|
+
untrackSources(this);
|
|
327
|
+
this._result = undefined;
|
|
328
|
+
this.owned.splice(0).forEach((stopOwned) => stopOwned());
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
get() {
|
|
332
|
+
// The reader subscribes first, so it stays subscribed even when the calculation throws.
|
|
333
|
+
track(this);
|
|
334
|
+
let result = this._result;
|
|
335
|
+
if (!result) {
|
|
336
|
+
this.owned.splice(0).forEach((stopOwned) => stopOwned());
|
|
337
|
+
this._running = true;
|
|
338
|
+
this._changed = false;
|
|
176
339
|
try {
|
|
177
|
-
|
|
340
|
+
// Without a reader the computed releases right after this read, so what the run creates belongs to the caller.
|
|
341
|
+
result = { value: runTracked(this, this.subs.size > 0 ? this : owner, this._fn) };
|
|
342
|
+
} catch (error) {
|
|
343
|
+
this.owned.splice(0).forEach((stopOwned) => stopOwned());
|
|
344
|
+
result = { error };
|
|
178
345
|
} finally {
|
|
179
|
-
|
|
346
|
+
this._running = false;
|
|
180
347
|
}
|
|
181
|
-
|
|
182
|
-
|
|
348
|
+
// An input changed during the run: the readers were told, so the next read runs again instead of using this.
|
|
349
|
+
if (!this._changed) {
|
|
350
|
+
this._result = result;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
if (this.subs.size === 0) {
|
|
354
|
+
this.release();
|
|
355
|
+
}
|
|
356
|
+
if ('error' in result) {
|
|
357
|
+
throw result.error;
|
|
358
|
+
}
|
|
359
|
+
return result.value;
|
|
360
|
+
}
|
|
183
361
|
}
|
|
184
362
|
|
|
185
363
|
/**
|
|
@@ -188,58 +366,7 @@ export function state(value) {
|
|
|
188
366
|
* @param {() => T} fn
|
|
189
367
|
*/
|
|
190
368
|
export function computed(fn) {
|
|
191
|
-
|
|
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
|
-
};
|
|
369
|
+
return new Computed(fn);
|
|
243
370
|
}
|
|
244
371
|
|
|
245
372
|
/**
|
|
@@ -351,146 +478,288 @@ export function read(value) {
|
|
|
351
478
|
}
|
|
352
479
|
|
|
353
480
|
/**
|
|
354
|
-
*
|
|
355
|
-
*
|
|
356
|
-
*
|
|
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]
|
|
481
|
+
* A computed value for `className` or the `class` attribute that lists classes by condition: strings are always on, and
|
|
482
|
+
* the keys of an object are on while their value, a boolean, signal or getter, is truthy.
|
|
483
|
+
* @param {string | Record<string, unknown> | readonly (string | Record<string, unknown>)[]} entries
|
|
359
484
|
*/
|
|
360
|
-
export function
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
485
|
+
export function classList(entries) {
|
|
486
|
+
const list = Array.isArray(entries) ? entries : [entries];
|
|
487
|
+
return computed(() =>
|
|
488
|
+
list
|
|
489
|
+
.flatMap((entry) => (typeof entry === 'string' ? [entry] : Object.keys(entry).filter((name) => read(entry[name]))))
|
|
490
|
+
.join(' '),
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* A value loaded by a fetcher, with `loading` and `error` signals.
|
|
496
|
+
* @extends {Signal<unknown>}
|
|
497
|
+
*/
|
|
498
|
+
class Resource extends Signal {
|
|
499
|
+
/** @param {(value: unknown, info: { signal: AbortSignal }) => unknown} load */
|
|
500
|
+
constructor(load) {
|
|
501
|
+
super();
|
|
502
|
+
this._load = load;
|
|
503
|
+
this._value = state(/** @type {unknown} */ (undefined));
|
|
504
|
+
this.loading = state(false);
|
|
505
|
+
this.error = state(/** @type {unknown} */ (undefined));
|
|
506
|
+
/** @type {unknown} The last source value. */
|
|
507
|
+
this._input = undefined;
|
|
508
|
+
/** @type {AbortController | undefined} */
|
|
509
|
+
this._controller = undefined;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
get() {
|
|
513
|
+
return this._value.get();
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** Loads again with the last source value. */
|
|
517
|
+
refetch() {
|
|
518
|
+
if (this._active()) {
|
|
519
|
+
this._start();
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Sets the value without loading, for example after an optimistic change.
|
|
525
|
+
* @param {unknown} value
|
|
526
|
+
*/
|
|
527
|
+
mutate(value) {
|
|
528
|
+
this._value.set(value);
|
|
364
529
|
}
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
let controller;
|
|
373
|
-
|
|
374
|
-
function start() {
|
|
375
|
-
controller?.abort();
|
|
530
|
+
|
|
531
|
+
_active() {
|
|
532
|
+
return this._input != null && this._input !== false;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
_start() {
|
|
536
|
+
this._controller?.abort();
|
|
376
537
|
const own = new AbortController();
|
|
377
|
-
|
|
378
|
-
loading.set(true);
|
|
379
|
-
error.set(undefined);
|
|
538
|
+
this._controller = own;
|
|
539
|
+
this.loading.set(true);
|
|
540
|
+
this.error.set(undefined);
|
|
541
|
+
const input = this._input;
|
|
380
542
|
// Called inside the promise, so a synchronous throw from the fetcher becomes the error too.
|
|
381
|
-
new Promise((resolve) => resolve(untrack(() =>
|
|
543
|
+
new Promise((resolve) => resolve(untrack(() => this._load(input, { signal: own.signal })))).then(
|
|
382
544
|
(result) => {
|
|
383
|
-
if (
|
|
384
|
-
|
|
385
|
-
loading.set(false);
|
|
545
|
+
if (this._controller === own) {
|
|
546
|
+
this._value.set(result);
|
|
547
|
+
this.loading.set(false);
|
|
386
548
|
}
|
|
387
549
|
},
|
|
388
550
|
(reason) => {
|
|
389
|
-
if (
|
|
390
|
-
error.set(reason);
|
|
391
|
-
loading.set(false);
|
|
551
|
+
if (this._controller === own) {
|
|
552
|
+
this.error.set(reason);
|
|
553
|
+
this.loading.set(false);
|
|
392
554
|
}
|
|
393
555
|
},
|
|
394
556
|
);
|
|
395
557
|
}
|
|
558
|
+
}
|
|
396
559
|
|
|
397
|
-
|
|
398
|
-
|
|
560
|
+
/**
|
|
561
|
+
* Loads a value with `fetcher`, and again whenever `source` changes, like Solid's createResource. While `source`
|
|
562
|
+
* gives null, undefined or false nothing is loaded. `fetcher` gets the source value and an AbortSignal that aborts
|
|
563
|
+
* when a newer load starts or the resource is stopped with its owner; the result of an older load is ignored.
|
|
564
|
+
* @param {unknown} source a signal or getter, or the fetcher when there is no source
|
|
565
|
+
* @param {(value: any, info: { signal: AbortSignal }) => unknown} [fetcher]
|
|
566
|
+
*/
|
|
567
|
+
export function resource(source, fetcher) {
|
|
568
|
+
if (!fetcher) {
|
|
569
|
+
fetcher = /** @type {(value: any, info: { signal: AbortSignal }) => unknown} */ (source);
|
|
570
|
+
source = () => true;
|
|
571
|
+
}
|
|
572
|
+
const result = new Resource(fetcher);
|
|
399
573
|
effect(() => {
|
|
400
|
-
|
|
401
|
-
if (!
|
|
402
|
-
loading.set(false);
|
|
574
|
+
result._input = read(/** @type {import('./signals.d.ts').Reactive<unknown>} */ (source));
|
|
575
|
+
if (!result._active()) {
|
|
576
|
+
result.loading.set(false);
|
|
403
577
|
return;
|
|
404
578
|
}
|
|
405
|
-
|
|
579
|
+
result._start();
|
|
406
580
|
return () => {
|
|
407
|
-
|
|
408
|
-
|
|
581
|
+
result._controller?.abort();
|
|
582
|
+
result._controller = undefined;
|
|
409
583
|
};
|
|
410
584
|
});
|
|
585
|
+
return result;
|
|
586
|
+
}
|
|
411
587
|
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
},
|
|
423
|
-
/** Sets the value without loading, for example after an optimistic change. */
|
|
424
|
-
mutate: value.set,
|
|
425
|
-
};
|
|
588
|
+
/**
|
|
589
|
+
* @typedef {{ first: Node | null, last: Node | null, stop: () => void }} Row
|
|
590
|
+
*/
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* The default list key: the item's `key` field.
|
|
594
|
+
* @param {unknown} item
|
|
595
|
+
*/
|
|
596
|
+
function itemKey(item) {
|
|
597
|
+
return typeof item === 'object' && item !== null && 'key' in item ? item.key : undefined;
|
|
426
598
|
}
|
|
427
599
|
|
|
428
600
|
/**
|
|
429
|
-
*
|
|
601
|
+
* A signal of a list with its key, waiting for `map`.
|
|
602
|
+
* @template T
|
|
430
603
|
*/
|
|
604
|
+
class Keyed {
|
|
605
|
+
/**
|
|
606
|
+
* @param {Signal<readonly T[]>} source
|
|
607
|
+
* @param {(item: T) => unknown} key
|
|
608
|
+
*/
|
|
609
|
+
constructor(source, key) {
|
|
610
|
+
this._source = source;
|
|
611
|
+
this._key = key;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* Renders the list and reuses the rows of items whose key it has seen.
|
|
616
|
+
* @param {(item: T, index: number) => Node} render
|
|
617
|
+
*/
|
|
618
|
+
map(render) {
|
|
619
|
+
return new List(this._source, render, this._key);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
431
622
|
|
|
432
623
|
/**
|
|
433
|
-
*
|
|
434
|
-
* was created; a reused row keeps it.
|
|
624
|
+
* A live list: every binding keeps its own rows by key and only renders new items. `index` is the item's index when its
|
|
625
|
+
* row was created; a reused row keeps it.
|
|
435
626
|
* @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
627
|
*/
|
|
440
|
-
|
|
441
|
-
/**
|
|
442
|
-
|
|
628
|
+
class List {
|
|
629
|
+
/**
|
|
630
|
+
* @param {Signal<readonly T[]>} source
|
|
631
|
+
* @param {(item: T, index: number) => Node} render
|
|
632
|
+
* @param {(item: T) => unknown} key
|
|
633
|
+
*/
|
|
634
|
+
constructor(source, render, key) {
|
|
635
|
+
this._source = source;
|
|
636
|
+
this._render = render;
|
|
637
|
+
this._key = key;
|
|
638
|
+
}
|
|
443
639
|
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
640
|
+
/**
|
|
641
|
+
* @param {(value: unknown) => void} apply
|
|
642
|
+
* @param {import('fiorejs/type/base.dom.d.ts').BindContext} context
|
|
643
|
+
*/
|
|
644
|
+
[LIVE](apply, context) {
|
|
645
|
+
/** @type {Map<unknown, Row[]>} Rows by key; a repeated key keeps one row per occurrence. */
|
|
646
|
+
let rows = new Map();
|
|
449
647
|
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
const
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
648
|
+
owner?.owned.push(() => {
|
|
649
|
+
const old = rows;
|
|
650
|
+
rows = new Map();
|
|
651
|
+
[...old.values()].flat().forEach((row) => row.stop());
|
|
652
|
+
});
|
|
653
|
+
|
|
654
|
+
attach(
|
|
655
|
+
() => {
|
|
656
|
+
/** @type {Map<unknown, Row[]>} */
|
|
657
|
+
const next = new Map();
|
|
658
|
+
/** @type {Map<unknown, number>} */
|
|
659
|
+
const taken = new Map();
|
|
660
|
+
/** @type {Row[]} */
|
|
661
|
+
const created = [];
|
|
662
|
+
/** @type {Node[]} */
|
|
663
|
+
const nodes = [];
|
|
664
|
+
try {
|
|
665
|
+
this._source.get().forEach((item, index) => {
|
|
666
|
+
const id = this._key(item);
|
|
667
|
+
const used = taken.get(id) ?? 0;
|
|
668
|
+
let row = rows.get(id)?.[used];
|
|
669
|
+
if (row) {
|
|
670
|
+
taken.set(id, used + 1);
|
|
671
|
+
} else {
|
|
672
|
+
row = createRow(() => this._render(item, index));
|
|
673
|
+
created.push(row);
|
|
674
|
+
}
|
|
675
|
+
const list = next.get(id);
|
|
676
|
+
if (list) {
|
|
677
|
+
list.push(row);
|
|
678
|
+
} else {
|
|
679
|
+
next.set(id, [row]);
|
|
680
|
+
}
|
|
681
|
+
for (let node = row.first; node; node = node === row.last ? null : node.nextSibling) {
|
|
682
|
+
nodes.push(node);
|
|
683
|
+
}
|
|
684
|
+
});
|
|
685
|
+
} catch (error) {
|
|
686
|
+
// The old rows stay as they were; only the rows made in this failed pass are stopped.
|
|
687
|
+
created.forEach((row) => row.stop());
|
|
688
|
+
throw error;
|
|
469
689
|
}
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
690
|
+
|
|
691
|
+
const kept = new Set([...next.values()].flat());
|
|
692
|
+
const old = rows;
|
|
693
|
+
rows = next;
|
|
694
|
+
for (const row of [...old.values()].flat()) {
|
|
695
|
+
if (!kept.has(row)) {
|
|
696
|
+
row.stop();
|
|
697
|
+
}
|
|
475
698
|
}
|
|
476
|
-
return
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
699
|
+
return nodes;
|
|
700
|
+
},
|
|
701
|
+
apply,
|
|
702
|
+
context,
|
|
703
|
+
);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
483
706
|
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
707
|
+
/**
|
|
708
|
+
* A live value that shows one branch while a signal is truthy and the other otherwise. A branch is built once when it is
|
|
709
|
+
* shown, outside the binding's tracking, so it is rebuilt only when the truthiness flips; what it builds stops then.
|
|
710
|
+
* @template A, B
|
|
711
|
+
*/
|
|
712
|
+
class When {
|
|
713
|
+
/**
|
|
714
|
+
* @param {Signal<unknown>} source
|
|
715
|
+
* @param {() => A} then
|
|
716
|
+
* @param {() => B} otherwise
|
|
717
|
+
*/
|
|
718
|
+
constructor(source, then, otherwise) {
|
|
719
|
+
this._source = source;
|
|
720
|
+
this._then = then;
|
|
721
|
+
this._otherwise = otherwise;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/**
|
|
725
|
+
* Shows what `otherwise` returns while the signal's value is falsy.
|
|
726
|
+
* @template C
|
|
727
|
+
* @param {() => C} otherwise
|
|
728
|
+
* @returns {When<A, C>}
|
|
729
|
+
*/
|
|
730
|
+
else(otherwise) {
|
|
731
|
+
return new When(this._source, this._then, otherwise);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/**
|
|
735
|
+
* @param {(value: unknown) => void} apply
|
|
736
|
+
* @param {import('fiorejs/type/base.dom.d.ts').BindContext} context
|
|
737
|
+
*/
|
|
738
|
+
[LIVE](apply, context) {
|
|
739
|
+
/** @type {boolean | undefined} */
|
|
740
|
+
let shown;
|
|
741
|
+
/** @type {A | B | undefined} */
|
|
742
|
+
let value;
|
|
743
|
+
/** @type {Owner} */
|
|
744
|
+
let scope = { owned: [] };
|
|
745
|
+
const stopBranch = () => scope.owned.splice(0).forEach((stopOwned) => stopOwned());
|
|
746
|
+
owner?.owned.push(stopBranch);
|
|
747
|
+
|
|
748
|
+
attach(
|
|
749
|
+
() => {
|
|
750
|
+
const visible = Boolean(this._source.get());
|
|
751
|
+
if (visible !== shown) {
|
|
752
|
+
stopBranch();
|
|
753
|
+
shown = visible;
|
|
754
|
+
scope = { owned: [] };
|
|
755
|
+
value = visible ? runIn(null, scope, this._then) : runIn(null, scope, this._otherwise);
|
|
756
|
+
}
|
|
757
|
+
return value;
|
|
758
|
+
},
|
|
759
|
+
apply,
|
|
760
|
+
context,
|
|
761
|
+
);
|
|
762
|
+
}
|
|
494
763
|
}
|
|
495
764
|
|
|
496
765
|
/**
|
|
@@ -502,7 +771,11 @@ function createRow(render) {
|
|
|
502
771
|
const scope = { owned: [] };
|
|
503
772
|
const stop = () => scope.owned.splice(0).forEach((stopOwned) => stopOwned());
|
|
504
773
|
try {
|
|
505
|
-
|
|
774
|
+
const node = runIn(null, scope, render);
|
|
775
|
+
// A fragment empties when it is inserted, so the row keeps its first and last node; a live child between them can
|
|
776
|
+
// change the nodes in between.
|
|
777
|
+
const fragment = node.nodeType === Node.DOCUMENT_FRAGMENT_NODE;
|
|
778
|
+
return { first: fragment ? node.firstChild : node, last: fragment ? node.lastChild : node, stop };
|
|
506
779
|
} catch (error) {
|
|
507
780
|
stop();
|
|
508
781
|
throw error;
|
|
@@ -511,16 +784,15 @@ function createRow(render) {
|
|
|
511
784
|
|
|
512
785
|
/**
|
|
513
786
|
* @typedef {{
|
|
514
|
-
* anchor:
|
|
515
|
-
* keyed?: Node,
|
|
787
|
+
* anchor: Node,
|
|
516
788
|
* start: () => () => void,
|
|
517
789
|
* stop?: () => void,
|
|
518
790
|
* }} Binding
|
|
519
791
|
*/
|
|
520
792
|
|
|
521
793
|
/**
|
|
522
|
-
* Bindings by the node whose place in the document they follow: the element for a property
|
|
523
|
-
*
|
|
794
|
+
* Bindings by the node whose place in the document they follow: the element for a property, an attribute or an only
|
|
795
|
+
* child, the start comment for any other child, which moves with its nodes, for example out of a fragment.
|
|
524
796
|
* @type {WeakMap<Node, Set<Binding>>}
|
|
525
797
|
*/
|
|
526
798
|
const bindings = new WeakMap();
|
|
@@ -569,7 +841,7 @@ function roots(nodes) {
|
|
|
569
841
|
* @param {(binding: Binding) => void} fn
|
|
570
842
|
*/
|
|
571
843
|
function visit(node, fn) {
|
|
572
|
-
const walker = document.createTreeWalker(node, 1 |
|
|
844
|
+
const walker = document.createTreeWalker(node, 1 | 128 /* elements and comments */);
|
|
573
845
|
for (let current = /** @type {Node | null} */ (node); current; current = walker.nextNode()) {
|
|
574
846
|
const set = bindings.get(current);
|
|
575
847
|
if (!set) {
|
|
@@ -596,7 +868,7 @@ function report(error) {
|
|
|
596
868
|
|
|
597
869
|
/** @param {Binding} binding */
|
|
598
870
|
function pause(binding) {
|
|
599
|
-
if (!binding.anchor
|
|
871
|
+
if (!binding.anchor.isConnected) {
|
|
600
872
|
// Cleared first, so a stop that throws still leaves the binding ready to resume.
|
|
601
873
|
const stop = binding.stop;
|
|
602
874
|
binding.stop = undefined;
|
|
@@ -606,69 +878,37 @@ function pause(binding) {
|
|
|
606
878
|
|
|
607
879
|
/** @param {Binding} binding */
|
|
608
880
|
function resume(binding) {
|
|
609
|
-
if (!binding.stop && binding.anchor
|
|
881
|
+
if (!binding.stop && binding.anchor.isConnected) {
|
|
610
882
|
binding.stop = binding.start();
|
|
611
883
|
}
|
|
612
884
|
}
|
|
613
885
|
|
|
614
886
|
/**
|
|
615
|
-
*
|
|
616
|
-
*
|
|
887
|
+
* Binds `read` to an element: `apply` gets its value now and whenever a signal it read changes, while its anchor is in
|
|
888
|
+
* the document.
|
|
889
|
+
* @param {() => unknown} read
|
|
890
|
+
* @param {(value: unknown) => void} apply
|
|
891
|
+
* @param {import('fiorejs/type/base.dom.d.ts').BindContext} context
|
|
617
892
|
*/
|
|
618
|
-
function
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
893
|
+
function attach(read, apply, context) {
|
|
894
|
+
/** @type {Binding} */
|
|
895
|
+
const binding = {
|
|
896
|
+
anchor: context.kind === 'child' ? context.anchor : context.element,
|
|
897
|
+
start: () => runIn(null, null, () => effect(() => apply(read()))),
|
|
898
|
+
};
|
|
899
|
+
// Filed under its anchor, so the observer finds it when the anchor is added or removed.
|
|
900
|
+
let set = bindings.get(binding.anchor);
|
|
625
901
|
if (!set) {
|
|
626
902
|
set = new Set();
|
|
627
|
-
bindings.set(
|
|
903
|
+
bindings.set(binding.anchor, set);
|
|
628
904
|
}
|
|
629
905
|
set.add(binding);
|
|
630
|
-
binding.
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
}
|
|
906
|
+
binding.stop = binding.start();
|
|
907
|
+
// The surrounding effect or list row ends the binding for good when it reruns or is removed.
|
|
908
|
+
owner?.owned.push(() => {
|
|
909
|
+
bindings.get(binding.anchor)?.delete(binding);
|
|
910
|
+
binding.stop?.();
|
|
911
|
+
binding.stop = undefined;
|
|
912
|
+
});
|
|
913
|
+
observe();
|
|
639
914
|
}
|
|
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);
|