@ilha/model 0.1.0 → 0.2.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 +27 -0
- package/README.md +92 -34
- package/dist/component-BlwL7V1h.d.ts +221 -0
- package/dist/index.d.ts +31 -4
- package/dist/index.js +273 -152
- package/dist/internal-DsyiAF5H.js +58 -0
- package/dist/rolldown-runtime-CNh9ExCG.js +17 -0
- package/dist/test.d.ts +32 -0
- package/dist/test.js +55 -0
- package/package.json +11 -7
- package/dist/app.d.ts +0 -126
- package/dist/submodel.d.ts +0 -28
package/LICENSE
CHANGED
|
@@ -19,3 +19,30 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
|
19
19
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
20
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
21
|
THE SOFTWARE.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
Portions of this software are adapted from Effect UI
|
|
26
|
+
(https://github.com/Effect-TS/ui), distributed under the following license:
|
|
27
|
+
|
|
28
|
+
MIT License
|
|
29
|
+
|
|
30
|
+
Copyright (c) 2023 Effectful Technologies Inc
|
|
31
|
+
|
|
32
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
33
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
34
|
+
in the Software without restriction, including without limitation the rights
|
|
35
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
36
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
37
|
+
furnished to do so, subject to the following conditions:
|
|
38
|
+
|
|
39
|
+
The above copyright notice and this permission notice shall be included in all
|
|
40
|
+
copies or substantial portions of the Software.
|
|
41
|
+
|
|
42
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
43
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
44
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
45
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
46
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
47
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
48
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
# `@ilha/model`
|
|
2
2
|
|
|
3
|
-
Elm-style
|
|
4
|
-
|
|
5
|
-
---
|
|
3
|
+
Elm-style model components for [Ilha](https://github.com/ilhajs/ilha) islands. Each component instance owns one model atom; every change flows through a single `update` function. Side effects run as Commands, ongoing work as Subscriptions.
|
|
6
4
|
|
|
7
5
|
## Installation
|
|
8
6
|
|
|
@@ -10,48 +8,108 @@ Elm-style Model, `update`, commands, and subscriptions for [Ilha](https://github
|
|
|
10
8
|
bun add @ilha/model
|
|
11
9
|
```
|
|
12
10
|
|
|
13
|
-
|
|
11
|
+
`ilha` and `effect` are peer dependencies.
|
|
14
12
|
|
|
15
13
|
## Usage
|
|
16
14
|
|
|
17
15
|
```tsx
|
|
18
|
-
import {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
16
|
+
import {
|
|
17
|
+
Command,
|
|
18
|
+
Subscription,
|
|
19
|
+
defineComponent,
|
|
20
|
+
attachModelRecorder,
|
|
21
|
+
} from "@ilha/model";
|
|
22
|
+
import type {
|
|
23
|
+
DispatchRecord,
|
|
24
|
+
ModelRecorder,
|
|
25
|
+
ModelComponent,
|
|
26
|
+
Step,
|
|
27
|
+
Issued,
|
|
28
|
+
} from "@ilha/model";
|
|
29
|
+
import { Story } from "@ilha/model/test";
|
|
30
|
+
import { Effect, Layer, Schema, Stream } from "effect";
|
|
31
|
+
import { mount } from "ilha";
|
|
32
|
+
|
|
33
|
+
const Msg = Schema.TaggedUnion({
|
|
34
|
+
ClickedAdd: { amount: Schema.Number },
|
|
35
|
+
ClickedReset: {},
|
|
36
|
+
CompletedReset: {},
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const DelayReset = Command.make("DelayReset", { mode: "switch" }, () =>
|
|
40
|
+
Effect.sleep("1 second").pipe(Effect.as(Msg.cases.CompletedReset.make({})))
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
export const Counter = defineComponent({
|
|
44
|
+
name: "Counter",
|
|
45
|
+
props: Schema.Struct({ label: Schema.String }), // optional
|
|
46
|
+
model: Schema.Struct({ count: Schema.Number }), // also the SSR snapshot codec
|
|
47
|
+
message: Msg,
|
|
48
|
+
events: Schema.TaggedUnion({ Reached: { count: Schema.Number } }), // optional
|
|
49
|
+
}).make({
|
|
50
|
+
init: ($, props) => ({ count: 0 }), // Model | Step
|
|
51
|
+
update: {
|
|
52
|
+
// exhaustive record, one handler per tag
|
|
53
|
+
ClickedAdd: ($, { amount }) => $.evolve({ count: (c) => c + amount }),
|
|
54
|
+
ClickedReset: ($) => $.run(DelayReset()),
|
|
55
|
+
CompletedReset: ($) =>
|
|
56
|
+
$.set({ count: 0 }).emit({ _tag: "Reached", count: 0 }),
|
|
57
|
+
},
|
|
58
|
+
view: (h, model) => (
|
|
40
59
|
<div>
|
|
41
|
-
<
|
|
42
|
-
<
|
|
43
|
-
|
|
60
|
+
<span>{h.props.label}</span>
|
|
61
|
+
<output>{model.count}</output>
|
|
62
|
+
<button onclick={h.send(Msg.cases.ClickedAdd.make({ amount: 1 }))}>
|
|
63
|
+
+1
|
|
44
64
|
</button>
|
|
45
|
-
<button
|
|
46
|
-
|
|
65
|
+
<button
|
|
66
|
+
disabled={h.isRunning(DelayReset)}
|
|
67
|
+
onclick={h.send(Msg.cases.ClickedReset.make({}))}
|
|
68
|
+
>
|
|
69
|
+
Reset
|
|
47
70
|
</button>
|
|
48
71
|
</div>
|
|
49
72
|
),
|
|
73
|
+
subscriptions: (model, props) => [], // optional
|
|
74
|
+
layer: Layer.empty, // optional
|
|
50
75
|
});
|
|
51
76
|
|
|
52
|
-
|
|
77
|
+
// parent view: <Counter key="likes" props={{ label: "Likes" }} onEmit={h.send((e) => PageMsg.cases.Reached.make(e))} />
|
|
78
|
+
// root: mount(host, () => <Counter props={{ label: "Likes" }} />) — no root helper
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Notes:
|
|
82
|
+
|
|
83
|
+
- `$` in `init`/`update` has `props`, `set(model)`, `evolve(patch)` (each field a value or `(prev) => next`), `run(...issued)`, `emit(event)`; `update`'s `$` also has `model`. Handlers return a bare `Model` or a `Step`.
|
|
84
|
+
- `h` in `view` is Ilha's `h` plus `props`, `send(message | (arg) => message | undefined)`, and reactive `isRunning(command)`.
|
|
85
|
+
- `Command.make(name, body)` issues concurrently; `{ mode: "switch" }` interrupts the instance's running issue of the same command. Nothing runs during SSR; init commands run on the client after mount/hydration.
|
|
86
|
+
- `Subscription.make(name, stream)` or `make(name, deps, (deps) => stream)`; deps compared with `Equal.equals`, restarted on change, stopped when removed.
|
|
87
|
+
- `layer` is built once per component per mounted root; instances of that component share its services.
|
|
88
|
+
- Throws in `init`/`view` go through Ilha's normal error path (`ErrorBoundary` / mount `onError`); `update` throws and Command/Subscription defects are logged and the instance keeps its last model.
|
|
89
|
+
|
|
90
|
+
## Testing with Story
|
|
91
|
+
|
|
92
|
+
`Story` runs the loop synchronously with no Effect and no DOM: `init` runs (commands are recorded, never executed), `send` feeds messages through `update`, `emitted` collects events, `commands` lists pending `{ name, args }` issues, and `resolve(command, message?)` drops the oldest pending issue and optionally feeds a message back.
|
|
93
|
+
|
|
94
|
+
```tsx
|
|
95
|
+
const story = Story.make(Counter, { label: "Likes" });
|
|
96
|
+
story.send(Msg.cases.ClickedAdd.make({ amount: 2 }));
|
|
97
|
+
expect(story.model).toEqual({ count: 2 });
|
|
98
|
+
expect(story.commands).toEqual([{ name: "DelayReset", args: undefined }]);
|
|
99
|
+
story.resolve(DelayReset, Msg.cases.CompletedReset.make({}));
|
|
100
|
+
expect(story.model).toEqual({ count: 0 });
|
|
53
101
|
```
|
|
54
102
|
|
|
55
|
-
|
|
103
|
+
## Migration from 0.1
|
|
56
104
|
|
|
57
|
-
|
|
105
|
+
| 0.1 | 0.2.0 |
|
|
106
|
+
| --- | --- |
|
|
107
|
+
| `defineApp({ init, update, view })` + `app.component` | `defineComponent({ name, model, message, props?, events? }).make({ init, update, view })` |
|
|
108
|
+
| `update(model, message)` switch | `update` record, one handler per tag: `ClickedAdd: ($, { amount }) => ...` |
|
|
109
|
+
| `{ model, cmd }` returns | `$` steps: `$.set(...)`, `$.evolve(...)`, `$.run(...)`, `$.emit(...)`; or return a bare model |
|
|
110
|
+
| `keyed(key, cmd)` | `Command.make(name, { mode: "switch" }, body)` (`"concurrent"` is the default) |
|
|
111
|
+
| `subscription({ deps, stream })` | `Subscription.make(name, deps, (deps) => stream)` |
|
|
112
|
+
| `runCommands` / `simulate` in `@ilha/model/test` | `Story.make(Component, props?)` with `send` / `resolve` |
|
|
113
|
+
| `foldChild` / `combine` submodels | child components with `props` + `onEmit` |
|
|
114
|
+
| `Component.root`, typed `View<R>` | gone: mount a closure, `mount(host, () => <Counter props={...} />)` |
|
|
115
|
+
| Query, Validation, MessageLog, `./devtools`, shares/reads, slots, keepAlive, lazy, Feature, provide, clientOnly, headless parts, Mount/Dom*/Keyboard/DomFiles/DomImages, TaggedEnum, standalone `evolve`, Scene/Play/TestHost/locators/ssr harness | gone |
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import "effect/Cause";
|
|
2
|
+
import * as Effect from "effect/Effect";
|
|
3
|
+
import * as Layer from "effect/Layer";
|
|
4
|
+
import * as Schema from "effect/Schema";
|
|
5
|
+
import * as Stream from "effect/Stream";
|
|
6
|
+
import { View, h } from "ilha";
|
|
7
|
+
import { AtomRegistry } from "effect/reactivity/AtomRegistry";
|
|
8
|
+
declare namespace command_d_exports {
|
|
9
|
+
export { Command, CommandBody, CommandMode, CommandOptions, Issued, MakeCommand, MaybeMessage, make$1 as make };
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* One-shot work a component issues from `init` or `update`, started with
|
|
13
|
+
* `$.run(...)`. Resolves with a follow-up message or with nothing. The
|
|
14
|
+
* `never` error channel forces every expected failure into a message;
|
|
15
|
+
* defects are logged and the instance keeps running.
|
|
16
|
+
*/
|
|
17
|
+
type MaybeMessage<Msg> = Msg | void;
|
|
18
|
+
/** How the instance treats a new issue while one is still running. */
|
|
19
|
+
type CommandMode = "concurrent" | "switch";
|
|
20
|
+
interface CommandOptions {
|
|
21
|
+
readonly mode?: CommandMode;
|
|
22
|
+
}
|
|
23
|
+
/** A pending issue: the command plus the args it was issued with. */
|
|
24
|
+
interface Issued<Msg = never, R = never> {
|
|
25
|
+
/** The command's name, for `isRunning`, `Story.commands`, and `Story.resolve`. */
|
|
26
|
+
readonly name: string;
|
|
27
|
+
/** The args the command was issued with (`undefined` for a zero-arg command). */
|
|
28
|
+
readonly args: unknown;
|
|
29
|
+
/** Runs the body with the issued args; the runtime delivers the message. */
|
|
30
|
+
readonly body: () => Effect.Effect<MaybeMessage<Msg>, never, R>;
|
|
31
|
+
/** How a re-issue treats the running one. */
|
|
32
|
+
readonly mode: CommandMode;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* A command definition. Call it with its args to issue it from `$.run`
|
|
36
|
+
* (zero-arg when its body takes none). Carries `.name` for `isRunning`.
|
|
37
|
+
*/
|
|
38
|
+
interface Command<Msg = never, R = never, Args = never> {
|
|
39
|
+
readonly name: string;
|
|
40
|
+
(...args: [Args] extends [never] ? [] : [args: Args]): Issued<Msg, R>;
|
|
41
|
+
}
|
|
42
|
+
/** A command body: an effect resolving to a message or nothing. */
|
|
43
|
+
type CommandBody<Msg, R, Args> = (args: Args) => Effect.Effect<MaybeMessage<Msg>, never, R>;
|
|
44
|
+
/** Overloads for {@link make}: with or without command options. */
|
|
45
|
+
interface MakeCommand {
|
|
46
|
+
<Msg, R = never, Args = never>(name: string, body: CommandBody<Msg, R, Args>): Command<Msg, R, Args>;
|
|
47
|
+
<Msg, R = never, Args = never>(name: string, options: CommandOptions, body: CommandBody<Msg, R, Args>): Command<Msg, R, Args>;
|
|
48
|
+
}
|
|
49
|
+
/** Build a command from a body; issues run concurrently unless switched. */
|
|
50
|
+
declare const make$1: MakeCommand;
|
|
51
|
+
declare namespace subscription_d_exports {
|
|
52
|
+
export { MakeSubscription, Subscription, make };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Ongoing work whose lifetime follows slices of the model and props.
|
|
56
|
+
* Declarative: the runtime restarts the stream when `depsOf` changes
|
|
57
|
+
* (compared with `Equal.equals`), stops it when the entry leaves the
|
|
58
|
+
* list, and starts everything on the client only.
|
|
59
|
+
*/
|
|
60
|
+
interface Subscription<Model, Props, Msg, R, Deps> {
|
|
61
|
+
/** Subscription name; duplicates in one list throw at render. */
|
|
62
|
+
readonly name: string;
|
|
63
|
+
/** Values controlling the lifetime; the stream restarts when they change. */
|
|
64
|
+
readonly depsOf: (model: Model, props: Props) => Deps;
|
|
65
|
+
/** Stream of messages for the current deps. */
|
|
66
|
+
readonly run: (deps: Deps) => Stream.Stream<Msg, never, R>;
|
|
67
|
+
}
|
|
68
|
+
/** Overloads for {@link make}: constant stream or deps-driven stream. */
|
|
69
|
+
interface MakeSubscription {
|
|
70
|
+
<Msg, R = never>(name: string, stream: Stream.Stream<Msg, never, R>): Subscription<unknown, unknown, Msg, R, void>;
|
|
71
|
+
<Model, Props, Msg, R, Deps>(name: string, depsOf: (model: Model, props: Props) => Deps, run: (deps: Deps) => Stream.Stream<Msg, never, R>): Subscription<Model, Props, Msg, R, Deps>;
|
|
72
|
+
}
|
|
73
|
+
/** A subscription with constant deps: same stream for the instance's life. */
|
|
74
|
+
declare const make: MakeSubscription;
|
|
75
|
+
/**
|
|
76
|
+
* What `init` and `update` accumulate: the next model, commands to issue,
|
|
77
|
+
* and events to emit to the author's `onEmit`. Each builder returns a new
|
|
78
|
+
* step, so chains like `$.set(model).run(cmd).emit(event)` keep extending.
|
|
79
|
+
*/
|
|
80
|
+
interface Step<Model, Msg, R = never, Events = never> {
|
|
81
|
+
/** The model the step carries. */
|
|
82
|
+
readonly model: Model;
|
|
83
|
+
/**
|
|
84
|
+
* Pending issues, in order. The runner executes them; `Story` exposes
|
|
85
|
+
* them as `{ name, args }`.
|
|
86
|
+
*/
|
|
87
|
+
readonly commands: readonly Issued<Msg, R>[];
|
|
88
|
+
/** Emitted events, in order. */
|
|
89
|
+
readonly events: readonly Events[];
|
|
90
|
+
/** Replace the model, no merge. */
|
|
91
|
+
readonly set: (model: Model) => Step<Model, Msg, R, Events>;
|
|
92
|
+
/** Change some fields; each patch value replaces, or maps the previous. */
|
|
93
|
+
readonly evolve: (patch: EvolvePatch<Model>) => Step<Model, Msg, R, Events>;
|
|
94
|
+
/** Issue commands, owned by the instance. Results come back as messages. */
|
|
95
|
+
readonly run: <R2>(...issued: readonly Issued<Msg, R2>[]) => Step<Model, Msg, R | R2, Events>;
|
|
96
|
+
/** Report events to the author's `onEmit`, after the model commits. */
|
|
97
|
+
readonly emit: (...events: readonly Events[]) => Step<Model, Msg, R, Events>;
|
|
98
|
+
}
|
|
99
|
+
/** Shallow patch: each field is a value, or an updater from the previous. */
|
|
100
|
+
type EvolvePatch<Model> = { readonly [K in keyof Model]?: Model[K] | ((previous: Model[K]) => Model[K]) | undefined; };
|
|
101
|
+
/** `$` in `init`: the current props, and `set` to build the first model. */
|
|
102
|
+
interface InitDollar<Model, Msg, Props, Events> {
|
|
103
|
+
readonly props: Props;
|
|
104
|
+
readonly set: (model: Model) => Step<Model, Msg, never, Events>;
|
|
105
|
+
}
|
|
106
|
+
/** `$` in `update`: a step seeded with the current model, plus props. */
|
|
107
|
+
interface UpdateDollar<Model, Msg, Props, Events> extends Step<Model, Msg, never, Events> {
|
|
108
|
+
readonly props: Props;
|
|
109
|
+
}
|
|
110
|
+
/** Exhaustive record: one handler per message tag. */
|
|
111
|
+
type UpdateHandlers<Model, Msg extends {
|
|
112
|
+
readonly _tag: string;
|
|
113
|
+
}, Props, Events> = { readonly [Tag in Msg["_tag"]]: (dollar: UpdateDollar<Model, Msg, Props, Events>, message: Extract<Msg, {
|
|
114
|
+
readonly _tag: Tag;
|
|
115
|
+
}>) => Model | Step<Model, Msg, any, Events>; };
|
|
116
|
+
/** `h` in `view`: Ilha's `h`, plus the component's props and helpers. */
|
|
117
|
+
type Helper<Props, Msg> = typeof h & {
|
|
118
|
+
readonly props: Props;
|
|
119
|
+
readonly send: {
|
|
120
|
+
/** Send a fixed message; the argument is ignored. */
|
|
121
|
+
(message: Msg): () => void;
|
|
122
|
+
/** Map an argument to a message; `undefined` sends nothing. */
|
|
123
|
+
<A>(fromArg: (arg: A) => Msg | undefined): (arg?: A) => void;
|
|
124
|
+
};
|
|
125
|
+
/** Whether the command has a running issue in this instance. Reactive. */
|
|
126
|
+
readonly isRunning: (command: {
|
|
127
|
+
readonly name: string;
|
|
128
|
+
}) => boolean;
|
|
129
|
+
};
|
|
130
|
+
interface CallOptions<Props, Events> {
|
|
131
|
+
readonly props: Props;
|
|
132
|
+
readonly onEmit?: ((event: Events) => void) | undefined;
|
|
133
|
+
readonly key?: string | number | undefined;
|
|
134
|
+
}
|
|
135
|
+
type RenderOptions<Props, Events> = Record<never, never> extends Props ? {
|
|
136
|
+
readonly props?: Props | undefined;
|
|
137
|
+
readonly onEmit?: ((event: Events) => void) | undefined;
|
|
138
|
+
readonly key?: string | number | undefined;
|
|
139
|
+
} : CallOptions<Props, Events>;
|
|
140
|
+
/**
|
|
141
|
+
* A component built by `defineComponent(...).make(...)`: an ordinary Ilha
|
|
142
|
+
* typed-props component taking `{ props, onEmit? }` (`props` required iff
|
|
143
|
+
* a props schema was given; `key` is Ilha's). Each mounted instance owns
|
|
144
|
+
* its own model atom; a child re-renders without re-running its parent.
|
|
145
|
+
* The definition and impl travel on the component for `Story`.
|
|
146
|
+
*/
|
|
147
|
+
interface ModelComponent<Props = Record<never, never>, Events = never, Model = unknown, Msg = unknown> {
|
|
148
|
+
(options: RenderOptions<Props, Events>): View;
|
|
149
|
+
/** Definition and impl travel on the component for `Story`. */
|
|
150
|
+
readonly definition: Definition<Props, Model, Msg, Events>;
|
|
151
|
+
readonly impl: unknown;
|
|
152
|
+
}
|
|
153
|
+
interface Definition<Props, Model, Msg, Events> {
|
|
154
|
+
readonly name: string;
|
|
155
|
+
readonly props: Schema.ConstraintDecoder<Props>;
|
|
156
|
+
readonly model: Schema.ConstraintCodec<Model, unknown>;
|
|
157
|
+
readonly message: Schema.Schema<Msg>;
|
|
158
|
+
readonly events: Schema.Schema<Events>;
|
|
159
|
+
}
|
|
160
|
+
interface MakeImpl<Model, Msg extends {
|
|
161
|
+
readonly _tag: string;
|
|
162
|
+
}, Props, Events> {
|
|
163
|
+
readonly init: (dollar: InitDollar<Model, Msg, Props, Events>, props: Props) => Model | Step<Model, Msg, any, Events>;
|
|
164
|
+
readonly update: UpdateHandlers<Model, Msg, Props, Events>;
|
|
165
|
+
readonly view: (h: Helper<Props, Msg>, model: Model) => View;
|
|
166
|
+
readonly subscriptions?: ((model: Model, props: Props) => readonly Subscription<Model, Props, Msg, any, any>[]) | undefined;
|
|
167
|
+
}
|
|
168
|
+
/** Services an `init` or `update` return still requires. */
|
|
169
|
+
type StepServices<S> = S extends {
|
|
170
|
+
readonly commands: readonly Issued<unknown, infer R>[];
|
|
171
|
+
} ? R : never;
|
|
172
|
+
type UpdateServices<U> = U extends Record<string, (dollar: never, message: never) => infer Ret> ? StepServices<Ret> : never;
|
|
173
|
+
type InitServices<F> = F extends ((dollar: never, props: never) => infer Ret) ? StepServices<Ret> : never;
|
|
174
|
+
type SubServices<S> = S extends ((model: never, props: never) => readonly (infer E)[]) ? E extends {
|
|
175
|
+
readonly run: (deps: never) => Stream.Stream<unknown, never, infer R>;
|
|
176
|
+
} ? R : never : never;
|
|
177
|
+
/** Every service the component's commands and subscriptions still require. */
|
|
178
|
+
type ImplNeeds<I> = I extends {
|
|
179
|
+
readonly update: infer U;
|
|
180
|
+
readonly init: infer F;
|
|
181
|
+
} ? UpdateServices<U> | InitServices<F> | (I extends {
|
|
182
|
+
readonly subscriptions: infer S;
|
|
183
|
+
} ? SubServices<Exclude<S, undefined>> : never) : never;
|
|
184
|
+
/**
|
|
185
|
+
* Reject commands and subscriptions that need services outside the layer.
|
|
186
|
+
* The runtime always provides `AtomRegistry`; anything else must come
|
|
187
|
+
* from `layer`.
|
|
188
|
+
*/
|
|
189
|
+
type CheckServices<Needs, L extends Layer.Any> = [Needs] extends [Layer.Success<L> | AtomRegistry] ? unknown : {
|
|
190
|
+
"services missing from layer": Exclude<Needs, Layer.Success<L> | AtomRegistry>;
|
|
191
|
+
};
|
|
192
|
+
/**
|
|
193
|
+
* What `defineComponent` returns: `make(impl)` builds the component.
|
|
194
|
+
* `layer` defaults to empty; `CheckServices` proves the layer covers
|
|
195
|
+
* every service `init`, Commands, and Subscriptions need.
|
|
196
|
+
*/
|
|
197
|
+
interface ComponentMaker<Model, Msg extends {
|
|
198
|
+
readonly _tag: string;
|
|
199
|
+
}, Props, Events> {
|
|
200
|
+
make: <L extends Layer.Any = Layer.Layer<never, never>, I extends MakeImpl<Model, Msg, Props, Events> = MakeImpl<Model, Msg, Props, Events>>(impl: MakeImpl<Model, Msg, Props, Events> & I & {
|
|
201
|
+
readonly layer?: L | undefined;
|
|
202
|
+
} & CheckServices<ImplNeeds<I>, L>) => ModelComponent<Props, Events, Model, Msg>;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Define a component. `model` is also the SSR snapshot codec; `message`
|
|
206
|
+
* is usually a `Schema.TaggedUnion`. Returns `{ make(impl) }`; `make`
|
|
207
|
+
* returns a `ModelComponent` usable as an Ilha component or JSX tag.
|
|
208
|
+
*/
|
|
209
|
+
declare const defineComponent: <const Name extends string, Props, Model, Msg extends {
|
|
210
|
+
readonly _tag: string;
|
|
211
|
+
}, Events = never>(options: {
|
|
212
|
+
readonly name: Name;
|
|
213
|
+
readonly model: Schema.ConstraintCodec<Model, unknown>;
|
|
214
|
+
readonly message: Schema.Schema<Msg>;
|
|
215
|
+
readonly events?: Schema.Schema<Events> | undefined;
|
|
216
|
+
} & (Record<never, never> extends Props ? {
|
|
217
|
+
readonly props?: Schema.ConstraintDecoder<Props> | undefined;
|
|
218
|
+
} : {
|
|
219
|
+
readonly props: Schema.ConstraintDecoder<Props>;
|
|
220
|
+
})) => ComponentMaker<Model, Msg, Props, Events>;
|
|
221
|
+
export { Issued as a, subscription_d_exports as i, defineComponent as n, command_d_exports as o, Step as r, ModelComponent as t };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,31 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
import { a as Issued, i as subscription_d_exports, n as defineComponent, o as command_d_exports, r as Step, t as ModelComponent } from "./component-BlwL7V1h.js";
|
|
2
|
+
/**
|
|
3
|
+
* One dispatch as an attached recorder sees it: raw values, nothing copied
|
|
4
|
+
* or summarized. Summarizing, diffing, and buffering belong to the
|
|
5
|
+
* recorder, so apps never ship that code.
|
|
6
|
+
*/
|
|
7
|
+
interface DispatchRecord {
|
|
8
|
+
/**
|
|
9
|
+
* The island instance's model atom. Join it against `atomsOf(id)` from
|
|
10
|
+
* `ilha/debug` to find which island dispatched.
|
|
11
|
+
*/
|
|
12
|
+
readonly instance: object;
|
|
13
|
+
/** The dispatched message. */
|
|
14
|
+
readonly message: unknown;
|
|
15
|
+
/** The model `update` received. */
|
|
16
|
+
readonly before: unknown;
|
|
17
|
+
/** The model `update` returned. */
|
|
18
|
+
readonly after: unknown;
|
|
19
|
+
/** How many commands the message started. */
|
|
20
|
+
readonly commands: number;
|
|
21
|
+
}
|
|
22
|
+
/** Receives every dispatch while attached. */
|
|
23
|
+
type ModelRecorder = (record: DispatchRecord) => void;
|
|
24
|
+
/**
|
|
25
|
+
* Hand every `dispatch` of every model island to `recorder` until the
|
|
26
|
+
* returned detach runs. The devtools page script attaches one for you.
|
|
27
|
+
* Detached, `dispatch` pays one size check: no record, no allocation. A
|
|
28
|
+
* recorder that throws is logged and never breaks `dispatch`.
|
|
29
|
+
*/
|
|
30
|
+
export declare const attachModelRecorder: (recorder: ModelRecorder) => (() => void);
|
|
31
|
+
export { command_d_exports as Command, type DispatchRecord, type Issued, type ModelComponent, type ModelRecorder, type Step, subscription_d_exports as Subscription, defineComponent };
|
package/dist/index.js
CHANGED
|
@@ -1,177 +1,298 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-CNh9ExCG.js";
|
|
2
|
+
import { a as reportCause, i as quietStream, n as initDollar, o as updateDollar, r as isStepValue, t as createStep } from "./internal-DsyiAF5H.js";
|
|
1
3
|
import * as Cause from "effect/Cause";
|
|
2
|
-
import * as Context from "effect/Context";
|
|
3
4
|
import * as Effect from "effect/Effect";
|
|
4
5
|
import * as Equal from "effect/Equal";
|
|
5
|
-
import * as Exit from "effect/Exit";
|
|
6
6
|
import * as Fiber from "effect/Fiber";
|
|
7
|
-
import * as FiberMap from "effect/FiberMap";
|
|
8
7
|
import * as Layer from "effect/Layer";
|
|
9
8
|
import * as Queue from "effect/Queue";
|
|
10
9
|
import * as Atom from "effect/reactivity/Atom";
|
|
11
|
-
import * as
|
|
10
|
+
import * as Schema from "effect/Schema";
|
|
12
11
|
import * as Stream from "effect/Stream";
|
|
13
|
-
import { atom, untrack, watch } from "ilha";
|
|
12
|
+
import { atom, h, untrack, watch } from "ilha";
|
|
14
13
|
|
|
15
|
-
// src/
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
* command; `keyed` reads it back without adding a service requirement.
|
|
31
|
-
*/
|
|
32
|
-
const KeyedScope = Context.Service("ilha/model/KeyedScope");
|
|
33
|
-
/**
|
|
34
|
-
* Latest-wins command: starting one interrupts the running command with the
|
|
35
|
-
* same key, so only the latest result dispatches. Different keys run
|
|
36
|
-
* independently. Keys are per app instance: two mounted instances never
|
|
37
|
-
* share them.
|
|
38
|
-
*/
|
|
39
|
-
const keyed = (key, cmd) => Effect.flatMap(Effect.serviceOption(KeyedScope), (scope) => scope._tag === "None" ? cmd : Effect.flatMap(FiberMap.run(scope.value, key, cmd), (fiber) => Fiber.join(fiber)));
|
|
40
|
-
/**
|
|
41
|
-
* Report an unexpected cause through the Effect logger. Interruption
|
|
42
|
-
* (unmount, keyed supersede, subscription restart) is silent; anything else
|
|
43
|
-
* is a defect worth logging.
|
|
44
|
-
*/
|
|
45
|
-
const reportCause = (cause) => Cause.hasInterruptsOnly(cause) ? Effect.void : Effect.logError(Cause.pretty(cause));
|
|
46
|
-
const makeInstanceCells = () => {
|
|
47
|
-
const keyedScope = Effect.runSync(Scope.make());
|
|
48
|
-
return {
|
|
49
|
-
alive: true,
|
|
50
|
-
keyedMap: Effect.runSync(Effect.provideService(FiberMap.make(), Scope.Scope, keyedScope)),
|
|
51
|
-
keyedScope,
|
|
52
|
-
queue: Effect.runSync(Queue.unbounded()),
|
|
53
|
-
started: false
|
|
54
|
-
};
|
|
14
|
+
// src/command.ts
|
|
15
|
+
var command_exports = /* @__PURE__ */ __exportAll({ make: () => make$1 });
|
|
16
|
+
/** Build a command from a body; issues run concurrently unless switched. */
|
|
17
|
+
const make$1 = (name, second, third) => {
|
|
18
|
+
const hasOptions = third !== void 0;
|
|
19
|
+
const options = hasOptions ? second : {};
|
|
20
|
+
const body = hasOptions ? third : second;
|
|
21
|
+
const command = (...args) => ({
|
|
22
|
+
args: args[0],
|
|
23
|
+
body: () => body(args[0]),
|
|
24
|
+
mode: options.mode ?? "concurrent",
|
|
25
|
+
name
|
|
26
|
+
});
|
|
27
|
+
Object.defineProperty(command, "name", { value: name });
|
|
28
|
+
return command;
|
|
55
29
|
};
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
*/
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
*/
|
|
68
|
-
const watchOne = (stateAtom, sub) => Atom.toStream(stateAtom).pipe(Stream.map((model) => sub.deps(model)), Stream.changesWith(Equal.equals), Stream.switchMap((deps) => Stream.suspend(() => sub.stream(deps)).pipe(Stream.catchCause(quietOnDefect))), Stream.catchCause(quietOnDefect));
|
|
69
|
-
/**
|
|
70
|
-
* Merge every subscription into one stream, built once per app instance.
|
|
71
|
-
* Each entry restarts only on its own deps; entries never disturb each
|
|
72
|
-
* other.
|
|
73
|
-
*/
|
|
74
|
-
const mergeSubscriptions = (stateAtom, subscriptions) => Stream.mergeAll(subscriptions.map((sub) => watchOne(stateAtom, sub)), { concurrency: "unbounded" });
|
|
75
|
-
/**
|
|
76
|
-
* Define an Elm-style app. One atom holds the whole model; `dispatch` runs
|
|
77
|
-
* `update` and rerenders; commands run concurrently inside the app runtime;
|
|
78
|
-
* each subscription restarts only when its own deps change and stops on
|
|
79
|
-
* unmount.
|
|
80
|
-
*/
|
|
81
|
-
const defineApp = (options) => {
|
|
82
|
-
const { init, update, view } = options;
|
|
83
|
-
const subscriptions = options.subscriptions ?? [];
|
|
84
|
-
const provided = options.layer ?? Layer.empty;
|
|
85
|
-
const runtime = Atom.runtime(provided);
|
|
86
|
-
const component = () => {
|
|
87
|
-
const initResult = atom.lazy(() => init(), { snapshot: false });
|
|
88
|
-
const state = atom.lazy(() => untrack(() => initResult()).model, { schema: options.schema });
|
|
89
|
-
const cells = atom.lazy(() => makeInstanceCells(), { snapshot: false });
|
|
90
|
-
const merged = atom.lazy(() => ({ stream: mergeSubscriptions(state.atom, subscriptions) }), { snapshot: false });
|
|
91
|
-
const isAlive = () => {
|
|
92
|
-
try {
|
|
93
|
-
return untrack(() => cells()).alive;
|
|
94
|
-
} catch {
|
|
95
|
-
return false;
|
|
96
|
-
}
|
|
97
|
-
};
|
|
98
|
-
const dispatch = (message) => {
|
|
99
|
-
if (!isAlive()) return;
|
|
100
|
-
const result = update(untrack(() => state()), message);
|
|
101
|
-
state.set(result.model);
|
|
102
|
-
if (result.cmd !== void 0) {
|
|
103
|
-
const { queue } = untrack(() => cells());
|
|
104
|
-
for (const cmd of eachCmd(result.cmd)) Queue.offerUnsafe(queue, cmd);
|
|
105
|
-
}
|
|
30
|
+
|
|
31
|
+
// src/subscription.ts
|
|
32
|
+
var subscription_exports = /* @__PURE__ */ __exportAll({ make: () => make });
|
|
33
|
+
/** A subscription with constant deps: same stream for the instance's life. */
|
|
34
|
+
const make = (name, second, third) => {
|
|
35
|
+
if (third === void 0) {
|
|
36
|
+
const stream = second;
|
|
37
|
+
return {
|
|
38
|
+
depsOf: () => void 0,
|
|
39
|
+
name,
|
|
40
|
+
run: () => stream
|
|
106
41
|
};
|
|
107
|
-
|
|
108
|
-
const runOne = (cmd) => Effect.provideService(Effect.catchCause(cmd.pipe(Effect.flatMap((out) => out === void 0 ? Effect.void : Effect.sync(() => dispatch(out)))), reportCause), KeyedScope, keyedMap);
|
|
109
|
-
const runner = atom(Atom.fn((queue, get) => Effect.flatMap(get.result(runtime), (services) => Effect.provideContext(Effect.forever(Effect.flatMap(Queue.take(queue), (cmd) => Effect.forkChild(runOne(cmd)))), services))));
|
|
110
|
-
const runnerFailure = atom(runner.atom.pipe(Atom.map((result) => result._tag === "Failure" && !Cause.hasInterruptsOnly(result.cause) ? Cause.pretty(result.cause) : "")));
|
|
111
|
-
runner();
|
|
112
|
-
watch(runnerFailure, (failure) => {
|
|
113
|
-
if (failure !== "") Effect.runSync(Effect.logError(failure));
|
|
114
|
-
});
|
|
115
|
-
watch.once(({ ssr }) => {
|
|
116
|
-
const helpers = untrack(() => cells());
|
|
117
|
-
if (!ssr && !helpers.started) {
|
|
118
|
-
helpers.started = true;
|
|
119
|
-
const begin = untrack(() => initResult()).cmd;
|
|
120
|
-
if (begin !== void 0) for (const cmd of eachCmd(begin)) Queue.offerUnsafe(helpers.queue, cmd);
|
|
121
|
-
if (subscriptions.length > 0) Queue.offerUnsafe(helpers.queue, Stream.runForEach(untrack(() => merged()).stream, (message) => Effect.catchCause(Effect.sync(() => dispatch(message)), reportCause)));
|
|
122
|
-
runner.set(helpers.queue);
|
|
123
|
-
}
|
|
124
|
-
return () => {
|
|
125
|
-
helpers.alive = false;
|
|
126
|
-
Effect.runFork(Scope.close(helpers.keyedScope, Exit.void));
|
|
127
|
-
};
|
|
128
|
-
});
|
|
129
|
-
return view(state(), dispatch);
|
|
130
|
-
};
|
|
131
|
-
Object.defineProperty(component, "name", { value: options.name ?? "ModelApp" });
|
|
42
|
+
}
|
|
132
43
|
return {
|
|
133
|
-
|
|
134
|
-
|
|
44
|
+
depsOf: second,
|
|
45
|
+
name,
|
|
46
|
+
run: third
|
|
135
47
|
};
|
|
136
48
|
};
|
|
137
49
|
|
|
138
|
-
// src/
|
|
50
|
+
// src/log.ts
|
|
51
|
+
/** Attached recorders; `dispatch` builds a record only while non-empty. */
|
|
52
|
+
const recorders = /* @__PURE__ */ new Set();
|
|
139
53
|
/**
|
|
140
|
-
*
|
|
141
|
-
*
|
|
142
|
-
*
|
|
54
|
+
* Hand every `dispatch` of every model island to `recorder` until the
|
|
55
|
+
* returned detach runs. The devtools page script attaches one for you.
|
|
56
|
+
* Detached, `dispatch` pays one size check: no record, no allocation. A
|
|
57
|
+
* recorder that throws is logged and never breaks `dispatch`.
|
|
143
58
|
*/
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
current = result.model;
|
|
150
|
-
if (result.cmd !== void 0) cmds.push(...eachCmd(result.cmd));
|
|
151
|
-
}
|
|
152
|
-
if (cmds.length === 0) return { model: current };
|
|
153
|
-
return {
|
|
154
|
-
cmd: cmds.length === 1 ? cmds[0] : cmds,
|
|
155
|
-
model: current
|
|
59
|
+
const attachModelRecorder = (recorder) => {
|
|
60
|
+
const entry = { recorder };
|
|
61
|
+
recorders.add(entry);
|
|
62
|
+
return () => {
|
|
63
|
+
recorders.delete(entry);
|
|
156
64
|
};
|
|
157
65
|
};
|
|
66
|
+
/** Whether any recorder is attached. Internal: `dispatch` checks it first. */
|
|
67
|
+
const isRecording = () => recorders.size > 0;
|
|
68
|
+
/** Deliver one dispatch to every recorder. Internal: `dispatch` calls it. */
|
|
69
|
+
const recordDispatch = (record) => {
|
|
70
|
+
for (const { recorder } of recorders) try {
|
|
71
|
+
recorder(record);
|
|
72
|
+
} catch (error) {
|
|
73
|
+
Effect.runSync(Effect.logError("@ilha/model recorder failed", error));
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// src/component.ts
|
|
78
|
+
const isSendMapper = (value) => typeof value === "function";
|
|
158
79
|
/**
|
|
159
|
-
*
|
|
160
|
-
*
|
|
80
|
+
* Define a component. `model` is also the SSR snapshot codec; `message`
|
|
81
|
+
* is usually a `Schema.TaggedUnion`. Returns `{ make(impl) }`; `make`
|
|
82
|
+
* returns a `ModelComponent` usable as an Ilha component or JSX tag.
|
|
161
83
|
*/
|
|
162
|
-
const
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
84
|
+
const defineComponent = (options) => {
|
|
85
|
+
const withProps = options;
|
|
86
|
+
const emptyProps = Schema.Struct({});
|
|
87
|
+
const propsSchema = withProps.props ?? emptyProps;
|
|
88
|
+
const definition = {
|
|
89
|
+
events: options.events ?? Schema.Never,
|
|
90
|
+
message: options.message,
|
|
91
|
+
model: options.model,
|
|
92
|
+
name: options.name,
|
|
93
|
+
props: propsSchema
|
|
94
|
+
};
|
|
95
|
+
const make = (impl) => {
|
|
96
|
+
const modelSchema = definition.model;
|
|
97
|
+
const provided = impl.layer ?? Layer.empty;
|
|
98
|
+
const runtime = Atom.runtime(provided);
|
|
99
|
+
const render = (callOptions) => {
|
|
100
|
+
const rawProps = { ...callOptions?.props };
|
|
101
|
+
const onEmit = callOptions?.onEmit;
|
|
102
|
+
const propsState = atom.lazy(() => ({
|
|
103
|
+
onEmit,
|
|
104
|
+
props: Schema.decodeSync(propsSchema)(rawProps),
|
|
105
|
+
raw: rawProps
|
|
106
|
+
}), { snapshot: false });
|
|
107
|
+
const known = untrack(() => propsState());
|
|
108
|
+
if (known.onEmit !== onEmit || !Equal.equals(known.raw, rawProps)) propsState.set({
|
|
109
|
+
onEmit,
|
|
110
|
+
props: Schema.decodeSync(propsSchema)(rawProps),
|
|
111
|
+
raw: rawProps
|
|
112
|
+
});
|
|
113
|
+
const initResult = atom.lazy(() => {
|
|
114
|
+
const { props } = untrack(() => propsState());
|
|
115
|
+
const dollar = initDollar(props);
|
|
116
|
+
const out = impl.init(dollar, props);
|
|
117
|
+
return isStepValue(out) ? out : createStep(out);
|
|
118
|
+
}, { snapshot: false });
|
|
119
|
+
const state = atom.lazy(() => untrack(() => initResult()).model, { schema: modelSchema });
|
|
120
|
+
const cells = atom.lazy(() => ({
|
|
121
|
+
alive: true,
|
|
122
|
+
generations: /* @__PURE__ */ new Map(),
|
|
123
|
+
queue: Effect.runSync(Queue.unbounded()),
|
|
124
|
+
started: false,
|
|
125
|
+
switches: /* @__PURE__ */ new Map()
|
|
126
|
+
}), { snapshot: false });
|
|
127
|
+
const counts = atom.lazy(() => ({}), { snapshot: false });
|
|
128
|
+
const combo = atom.lazy(() => {
|
|
129
|
+
const live = untrack(() => state());
|
|
130
|
+
const { props: liveProps } = untrack(() => propsState());
|
|
131
|
+
return {
|
|
132
|
+
model: live,
|
|
133
|
+
props: liveProps,
|
|
134
|
+
subs: impl.subscriptions?.(live, liveProps) ?? []
|
|
135
|
+
};
|
|
136
|
+
}, { snapshot: false });
|
|
137
|
+
const activeSubs = /* @__PURE__ */ new Map();
|
|
138
|
+
const manageEntries = (latest, outbox) => Effect.gen(function* manage() {
|
|
139
|
+
const seen = /* @__PURE__ */ new Set();
|
|
140
|
+
for (const entry of latest.subs) {
|
|
141
|
+
seen.add(entry.name);
|
|
142
|
+
const deps = entry.depsOf(latest.model, latest.props);
|
|
143
|
+
const current = activeSubs.get(entry.name);
|
|
144
|
+
if (current !== void 0 && Equal.equals(current.deps, deps)) continue;
|
|
145
|
+
if (current !== void 0) yield* Fiber.interrupt(current.fiber);
|
|
146
|
+
const fiber = yield* Effect.forkScoped(Stream.runForEach(Stream.suspend(() => entry.run(deps)).pipe(Stream.catchCause(quietStream)), (message) => Queue.offer(outbox, message)));
|
|
147
|
+
activeSubs.set(entry.name, {
|
|
148
|
+
deps,
|
|
149
|
+
fiber
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
for (const [name, current] of activeSubs) if (!seen.has(name)) {
|
|
153
|
+
yield* Fiber.interrupt(current.fiber);
|
|
154
|
+
activeSubs.delete(name);
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
const isAlive = () => {
|
|
158
|
+
try {
|
|
159
|
+
return untrack(() => cells()).alive;
|
|
160
|
+
} catch {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
const toJob = (issued, deliver) => {
|
|
165
|
+
let guarded = deliver;
|
|
166
|
+
if (issued.mode === "switch") {
|
|
167
|
+
const { generations } = untrack(() => cells());
|
|
168
|
+
const generation = (generations.get(issued.name) ?? 0) + 1;
|
|
169
|
+
generations.set(issued.name, generation);
|
|
170
|
+
guarded = (message) => {
|
|
171
|
+
if (untrack(() => cells()).generations.get(issued.name) === generation) deliver(message);
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
const run = Effect.catchCause(Effect.flatMap(issued.body(), (outcome) => outcome === void 0 ? Effect.void : Effect.sync(() => guarded(outcome))), reportCause);
|
|
175
|
+
return {
|
|
176
|
+
mode: issued.mode,
|
|
177
|
+
name: issued.name,
|
|
178
|
+
run
|
|
179
|
+
};
|
|
180
|
+
};
|
|
181
|
+
const dispatch = (message) => {
|
|
182
|
+
if (!isAlive()) return;
|
|
183
|
+
const { props: liveProps } = untrack(() => propsState());
|
|
184
|
+
const before = untrack(() => state());
|
|
185
|
+
const handler = impl.update[message._tag];
|
|
186
|
+
if (handler === void 0) throw new Error(`${definition.name}: no update for "${message._tag}"`);
|
|
187
|
+
const dollar = updateDollar(before, liveProps);
|
|
188
|
+
let out;
|
|
189
|
+
try {
|
|
190
|
+
out = handler(dollar, message);
|
|
191
|
+
} catch (error) {
|
|
192
|
+
Effect.runSync(Effect.logError(Cause.pretty(Cause.die(error))));
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const step = isStepValue(out) ? out : createStep(out);
|
|
196
|
+
state.set(step.model);
|
|
197
|
+
let started = 0;
|
|
198
|
+
if (step.commands.length > 0) {
|
|
199
|
+
const { queue } = untrack(() => cells());
|
|
200
|
+
for (const issued of step.commands) Queue.offerUnsafe(queue, toJob(issued, dispatch));
|
|
201
|
+
started = step.commands.length;
|
|
202
|
+
}
|
|
203
|
+
if (isRecording()) recordDispatch({
|
|
204
|
+
after: step.model,
|
|
205
|
+
before,
|
|
206
|
+
commands: started,
|
|
207
|
+
instance: state.atom,
|
|
208
|
+
message
|
|
209
|
+
});
|
|
210
|
+
if (step.events.length > 0) {
|
|
211
|
+
const emit = untrack(() => propsState()).onEmit;
|
|
212
|
+
if (emit !== void 0) for (const event of step.events) emit(event);
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
const bump = (name, delta) => {
|
|
216
|
+
counts.update((previous) => ({
|
|
217
|
+
...previous,
|
|
218
|
+
[name]: (previous[name] ?? 0) + delta
|
|
219
|
+
}));
|
|
220
|
+
};
|
|
221
|
+
const runJob = (job) => job.mode === "switch" ? Effect.gen(function* runSwitch() {
|
|
222
|
+
const { switches } = untrack(() => cells());
|
|
223
|
+
const previous = switches.get(job.name);
|
|
224
|
+
if (previous !== void 0) yield* Fiber.interrupt(previous);
|
|
225
|
+
bump(job.name, 1);
|
|
226
|
+
const cell = {};
|
|
227
|
+
const fiber = yield* Effect.forkScoped(Effect.ensuring(job.run, Effect.sync(() => {
|
|
228
|
+
bump(job.name, -1);
|
|
229
|
+
if (switches.get(job.name) === cell.current) switches.delete(job.name);
|
|
230
|
+
})));
|
|
231
|
+
cell.current = fiber;
|
|
232
|
+
switches.set(job.name, fiber);
|
|
233
|
+
}) : Effect.flatMap(Effect.sync(() => bump(job.name, 1)), () => Effect.forkScoped(Effect.ensuring(job.run, Effect.sync(() => bump(job.name, -1)))));
|
|
234
|
+
const subEffect = Effect.flatMap(Queue.unbounded(), (outbox) => Stream.runForEach(Stream.mergeAll([Stream.fromQueue(outbox), Atom.toStream(combo.atom).pipe(Stream.tap((latest) => manageEntries(latest, outbox)), Stream.flatMap(() => Stream.empty))], { concurrency: "unbounded" }), (message) => Effect.catchCause(Effect.sync(() => dispatch(message)), reportCause)));
|
|
235
|
+
const runner = atom(Atom.fn((queue, get) => Effect.flatMap(get.result(runtime), (services) => Effect.provideContext(Effect.scoped(Effect.flatMap(Effect.forkScoped(subEffect), () => Effect.forever(Effect.flatMap(Queue.take(queue), runJob)))), services))));
|
|
236
|
+
const runnerFailure = atom(runner.atom.pipe(Atom.map((result) => result._tag === "Failure" && !Cause.hasInterruptsOnly(result.cause) ? Cause.pretty(result.cause) : "")));
|
|
237
|
+
runner();
|
|
238
|
+
watch(runnerFailure, (failure) => {
|
|
239
|
+
if (failure !== "") Effect.runSync(Effect.logError(failure));
|
|
240
|
+
});
|
|
241
|
+
watch.once(({ ssr }) => {
|
|
242
|
+
const helpers = untrack(() => cells());
|
|
243
|
+
if (!ssr && !helpers.started) {
|
|
244
|
+
helpers.started = true;
|
|
245
|
+
const begun = untrack(() => initResult());
|
|
246
|
+
for (const issued of begun.commands) Queue.offerUnsafe(helpers.queue, toJob(issued, dispatch));
|
|
247
|
+
if (begun.events.length > 0) {
|
|
248
|
+
const emit = untrack(() => propsState()).onEmit;
|
|
249
|
+
if (emit !== void 0) for (const event of begun.events) emit(event);
|
|
250
|
+
}
|
|
251
|
+
runner.set(helpers.queue);
|
|
252
|
+
}
|
|
253
|
+
return () => {
|
|
254
|
+
helpers.alive = false;
|
|
255
|
+
};
|
|
256
|
+
});
|
|
257
|
+
const model = state();
|
|
258
|
+
const { props } = untrack(() => propsState());
|
|
259
|
+
const subs = impl.subscriptions?.(model, props) ?? [];
|
|
260
|
+
const seen = /* @__PURE__ */ new Set();
|
|
261
|
+
for (const sub of subs) {
|
|
262
|
+
if (seen.has(sub.name)) throw new Error(`${definition.name}: duplicate subscription "${sub.name}"`);
|
|
263
|
+
seen.add(sub.name);
|
|
264
|
+
}
|
|
265
|
+
combo.set({
|
|
266
|
+
model,
|
|
267
|
+
props,
|
|
268
|
+
subs
|
|
269
|
+
});
|
|
270
|
+
const send = ((input) => {
|
|
271
|
+
if (isSendMapper(input)) return (arg) => {
|
|
272
|
+
const resolved = input(arg);
|
|
273
|
+
if (resolved !== void 0) dispatch(resolved);
|
|
274
|
+
};
|
|
275
|
+
return () => {
|
|
276
|
+
dispatch(input);
|
|
277
|
+
};
|
|
278
|
+
});
|
|
279
|
+
const isRunning = (command) => (counts()[command.name] ?? 0) > 0;
|
|
280
|
+
const callH = ((node, attrs, ...rest) => h(node, attrs, ...rest));
|
|
281
|
+
const viewH = Object.assign(callH, {
|
|
282
|
+
isRunning,
|
|
283
|
+
props,
|
|
284
|
+
send
|
|
285
|
+
});
|
|
286
|
+
return impl.view(viewH, model);
|
|
173
287
|
};
|
|
288
|
+
const component = render;
|
|
289
|
+
Object.defineProperty(component, "name", { value: definition.name });
|
|
290
|
+
return Object.assign(component, {
|
|
291
|
+
definition,
|
|
292
|
+
impl
|
|
293
|
+
});
|
|
174
294
|
};
|
|
295
|
+
return { make };
|
|
175
296
|
};
|
|
176
297
|
|
|
177
|
-
export {
|
|
298
|
+
export { command_exports as Command, subscription_exports as Subscription, attachModelRecorder, defineComponent };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import * as Cause from "effect/Cause";
|
|
2
|
+
import * as Effect from "effect/Effect";
|
|
3
|
+
import * as Stream from "effect/Stream";
|
|
4
|
+
|
|
5
|
+
// src/internal.ts
|
|
6
|
+
/**
|
|
7
|
+
* Shared runtime bits for the component loop and the `Story` test helper.
|
|
8
|
+
* Everything here is generic over the component's own types, so no value
|
|
9
|
+
* is ever erased to `unknown`: each bundle keeps full static evidence.
|
|
10
|
+
*/
|
|
11
|
+
/** Log a defect through the Effect logger; interruption stays silent. */
|
|
12
|
+
const reportCause = (cause) => Cause.hasInterruptsOnly(cause) ? Effect.void : Effect.logError(Cause.pretty(cause));
|
|
13
|
+
/**
|
|
14
|
+
* A defect inside a subscription stream is logged and silences only that
|
|
15
|
+
* stream, so the next deps change starts a fresh one. Interruption passes
|
|
16
|
+
* through so restarts and unmount stay silent.
|
|
17
|
+
*/
|
|
18
|
+
const quietStream = (cause) => Cause.hasInterruptsOnly(cause) ? Stream.failCause(cause) : Stream.unwrap(Effect.as(Effect.logError(Cause.pretty(cause)), Stream.empty));
|
|
19
|
+
/** Whether `value` is a non-null object. */
|
|
20
|
+
const isObject = (value) => typeof value === "object" && value !== null;
|
|
21
|
+
const isUpdater = (change) => typeof change === "function";
|
|
22
|
+
/** Brand marking step values built by {@link createStep}. */
|
|
23
|
+
const stepMarker = "__ilhaModelStep";
|
|
24
|
+
/** Whether `value` is a step built by {@link createStep}. */
|
|
25
|
+
const isStepValue = (value) => isObject(value) && Object.getOwnPropertyDescriptor(value, stepMarker)?.value === true;
|
|
26
|
+
/** Replace every field listed in `patch`; a function receives the previous value. */
|
|
27
|
+
const applyEvolve = (model, patch) => {
|
|
28
|
+
if (!isObject(model) || Array.isArray(model)) throw new Error("@ilha/model evolve needs an object model");
|
|
29
|
+
const out = { ...model };
|
|
30
|
+
const keys = Object.keys(patch);
|
|
31
|
+
for (const key of keys) {
|
|
32
|
+
const change = patch[key];
|
|
33
|
+
if (change === void 0) continue;
|
|
34
|
+
out[key] = isUpdater(change) ? change(model[key]) : change;
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
};
|
|
38
|
+
/** Build a step; every builder returns a new step with the change applied. */
|
|
39
|
+
const createStep = (model, commands = [], events = []) => {
|
|
40
|
+
return Object.assign({
|
|
41
|
+
commands,
|
|
42
|
+
emit: (...emitted) => createStep(model, commands, [...events, ...emitted]),
|
|
43
|
+
events,
|
|
44
|
+
evolve: (patch) => createStep(applyEvolve(model, patch), commands, events),
|
|
45
|
+
model,
|
|
46
|
+
run: (...issued) => createStep(model, [...commands, ...issued], events),
|
|
47
|
+
set: (next) => createStep(next, commands, events)
|
|
48
|
+
}, { [stepMarker]: true });
|
|
49
|
+
};
|
|
50
|
+
/** `$` for `init`: the current props, and `set` to build the first model. */
|
|
51
|
+
const initDollar = (props) => ({
|
|
52
|
+
props,
|
|
53
|
+
set: (model) => createStep(model)
|
|
54
|
+
});
|
|
55
|
+
/** `$` for `update`: a step seeded with the current model, plus props. */
|
|
56
|
+
const updateDollar = (model, props) => Object.assign(createStep(model), { props });
|
|
57
|
+
|
|
58
|
+
export { reportCause as a, quietStream as i, initDollar as n, updateDollar as o, isStepValue as r, createStep as t };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// \0rolldown/runtime.js
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __exportAll = (all, no_symbols) => {
|
|
4
|
+
let target = {};
|
|
5
|
+
for (var name in all) {
|
|
6
|
+
__defProp(target, name, {
|
|
7
|
+
get: all[name],
|
|
8
|
+
enumerable: true
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
if (!no_symbols) {
|
|
12
|
+
__defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
13
|
+
}
|
|
14
|
+
return target;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export { __exportAll as t };
|
package/dist/test.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { t as ModelComponent } from "./component-BlwL7V1h.js";
|
|
2
|
+
/**
|
|
3
|
+
* Synchronous, pure component tests: no Effect, no DOM. Runs `init`
|
|
4
|
+
* (commands are recorded, never executed), then `send` feeds messages
|
|
5
|
+
* through `update`. Step commands accumulate as pending issues;
|
|
6
|
+
* `resolve` drops one and optionally feeds a message back.
|
|
7
|
+
*/
|
|
8
|
+
export interface StoryHandle<Model, Msg, Events> {
|
|
9
|
+
/** The current model. */
|
|
10
|
+
readonly model: Model;
|
|
11
|
+
/** Emitted events, in order. */
|
|
12
|
+
readonly emitted: readonly Events[];
|
|
13
|
+
/** Pending command issues, in order, as `{ name, args }`. */
|
|
14
|
+
readonly commands: readonly {
|
|
15
|
+
readonly name: string;
|
|
16
|
+
readonly args: unknown;
|
|
17
|
+
}[];
|
|
18
|
+
/** Run one message through `update`. Throws on an unknown tag. */
|
|
19
|
+
readonly send: (message: Msg) => void;
|
|
20
|
+
/**
|
|
21
|
+
* Drop the oldest pending issue of `command`, then send `message` when
|
|
22
|
+
* given (as if that issue resolved with it).
|
|
23
|
+
*/
|
|
24
|
+
readonly resolve: (command: {
|
|
25
|
+
readonly name: string;
|
|
26
|
+
}, message?: Msg) => void;
|
|
27
|
+
}
|
|
28
|
+
export declare const Story: {
|
|
29
|
+
make<Props, Events, Model, Msg extends {
|
|
30
|
+
readonly _tag: string;
|
|
31
|
+
}>(component: ModelComponent<Props, Events, Model, Msg>, ...args: Record<never, never> extends Props ? [props?: Props] : [props: Props]): StoryHandle<Model, Msg, Events>;
|
|
32
|
+
};
|
package/dist/test.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { n as initDollar, o as updateDollar, r as isStepValue, t as createStep } from "./internal-DsyiAF5H.js";
|
|
2
|
+
import * as Schema from "effect/Schema";
|
|
3
|
+
|
|
4
|
+
// src/test.ts
|
|
5
|
+
const Story = { make(component, ...args) {
|
|
6
|
+
const { definition } = component;
|
|
7
|
+
const impl = component.impl;
|
|
8
|
+
const decoded = Schema.decodeSync(definition.props)(args[0] ?? {});
|
|
9
|
+
let pending = [];
|
|
10
|
+
const emitted = [];
|
|
11
|
+
const commitInit = () => {
|
|
12
|
+
const out = impl.init(initDollar(decoded), decoded);
|
|
13
|
+
const step = isStepValue(out) ? out : createStep(out);
|
|
14
|
+
pending = step.commands.map(({ args: commandArgs, name }) => ({
|
|
15
|
+
args: commandArgs,
|
|
16
|
+
name
|
|
17
|
+
}));
|
|
18
|
+
for (const event of step.events) emitted.push(event);
|
|
19
|
+
return step.model;
|
|
20
|
+
};
|
|
21
|
+
let model = commitInit();
|
|
22
|
+
const send = (message) => {
|
|
23
|
+
const { _tag: tag } = message;
|
|
24
|
+
const handler = impl.update[tag];
|
|
25
|
+
if (handler === void 0) throw new Error(`${definition.name}: no update for "${tag}"`);
|
|
26
|
+
const out = handler(updateDollar(model, decoded), message);
|
|
27
|
+
const step = isStepValue(out) ? out : createStep(out);
|
|
28
|
+
const { model: next } = step;
|
|
29
|
+
model = next;
|
|
30
|
+
for (const { args: commandArgs, name } of step.commands) pending.push({
|
|
31
|
+
args: commandArgs,
|
|
32
|
+
name
|
|
33
|
+
});
|
|
34
|
+
for (const event of step.events) emitted.push(event);
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
get commands() {
|
|
38
|
+
return [...pending];
|
|
39
|
+
},
|
|
40
|
+
get emitted() {
|
|
41
|
+
return [...emitted];
|
|
42
|
+
},
|
|
43
|
+
get model() {
|
|
44
|
+
return model;
|
|
45
|
+
},
|
|
46
|
+
resolve(command, message) {
|
|
47
|
+
const at = pending.findIndex((issue) => issue.name === command.name);
|
|
48
|
+
if (at !== -1) pending.splice(at, 1);
|
|
49
|
+
if (message !== void 0) send(message);
|
|
50
|
+
},
|
|
51
|
+
send
|
|
52
|
+
};
|
|
53
|
+
} };
|
|
54
|
+
|
|
55
|
+
export { Story };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ilha/model",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Elm-style
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Elm-style model components for Ilha islands: one atom per instance, commands, and subscriptions",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"effect",
|
|
7
7
|
"elm-architecture",
|
|
@@ -34,24 +34,28 @@
|
|
|
34
34
|
".": {
|
|
35
35
|
"types": "./dist/index.d.ts",
|
|
36
36
|
"import": "./dist/index.js"
|
|
37
|
+
},
|
|
38
|
+
"./test": {
|
|
39
|
+
"types": "./dist/test.d.ts",
|
|
40
|
+
"import": "./dist/test.js"
|
|
37
41
|
}
|
|
38
42
|
},
|
|
39
43
|
"publishConfig": {
|
|
40
44
|
"access": "public"
|
|
41
45
|
},
|
|
42
46
|
"scripts": {
|
|
43
|
-
"build": "tsdown
|
|
47
|
+
"build": "tsdown",
|
|
44
48
|
"cleanup": "rimraf dist node_modules",
|
|
45
49
|
"test": "bun test",
|
|
46
50
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
47
51
|
},
|
|
48
52
|
"devDependencies": {
|
|
49
53
|
"@types/bun": "^1.4.4",
|
|
50
|
-
"effect": "^4.1.
|
|
51
|
-
"ilha": "^0.
|
|
54
|
+
"effect": "^4.1.4",
|
|
55
|
+
"ilha": "^0.17.0"
|
|
52
56
|
},
|
|
53
57
|
"peerDependencies": {
|
|
54
|
-
"effect": "^4.1.
|
|
55
|
-
"ilha": ">=0.16.
|
|
58
|
+
"effect": "^4.1.4",
|
|
59
|
+
"ilha": ">=0.16.3"
|
|
56
60
|
}
|
|
57
61
|
}
|
package/dist/app.d.ts
DELETED
|
@@ -1,126 +0,0 @@
|
|
|
1
|
-
import * as Effect from "effect/Effect";
|
|
2
|
-
import * as Layer from "effect/Layer";
|
|
3
|
-
import type { AtomRegistry } from "effect/reactivity/AtomRegistry";
|
|
4
|
-
import type * as Schema from "effect/Schema";
|
|
5
|
-
import * as Stream from "effect/Stream";
|
|
6
|
-
import type { Component, View } from "ilha";
|
|
7
|
-
/** Send a message into the app loop. */
|
|
8
|
-
export type Dispatch<Message> = (message: Message) => void;
|
|
9
|
-
/**
|
|
10
|
-
* One-shot work returned from `init` or `update`. Resolve with a follow-up
|
|
11
|
-
* message or with nothing. The `never` error channel forces every expected
|
|
12
|
-
* failure into a message; defects are logged and the island keeps running.
|
|
13
|
-
*/
|
|
14
|
-
export type Cmd<Message, R = never> = Effect.Effect<Message | void, never, R | AtomRegistry>;
|
|
15
|
-
/**
|
|
16
|
-
* What `init` and `update` return: the next model plus optional one-shot
|
|
17
|
-
* work. Several commands run concurrently with each other.
|
|
18
|
-
*/
|
|
19
|
-
export interface UpdateResult<Model, Message, R = never> {
|
|
20
|
-
readonly model: Model;
|
|
21
|
-
readonly cmd?: Cmd<Message, R> | readonly Cmd<Message, R>[] | undefined;
|
|
22
|
-
}
|
|
23
|
-
/**
|
|
24
|
-
* Ongoing work whose lifetime follows `deps(model)`. Build entries with
|
|
25
|
-
* {@link subscription} so each one keeps its own `Deps` type.
|
|
26
|
-
*/
|
|
27
|
-
export interface Subscription<Model, Message, Deps, R = never> {
|
|
28
|
-
/** Values controlling the lifetime; the stream restarts when they change. */
|
|
29
|
-
readonly deps: (model: Model) => Deps;
|
|
30
|
-
/** Stream of messages for the current deps. Restarted when deps change. */
|
|
31
|
-
readonly stream: (deps: Deps) => Stream.Stream<Message, never, R | AtomRegistry>;
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Name one subscription. Each entry infers its own `Deps` from its `deps`
|
|
35
|
-
* function, so `stream` receives the exact type its deps return. Annotate
|
|
36
|
-
* the model parameter; everything else infers.
|
|
37
|
-
*/
|
|
38
|
-
export declare const subscription: <Model, Message, Deps, R = never>(sub: Subscription<Model, Message, Deps, R>) => Subscription<Model, Message, Deps, R>;
|
|
39
|
-
/** Options for {@link defineApp}. */
|
|
40
|
-
export interface AppOptions<Model, Message, R = never, E = never> {
|
|
41
|
-
/** Component name shown in `ilha/debug` trees. Default `"ModelApp"`. */
|
|
42
|
-
readonly name?: string | undefined;
|
|
43
|
-
/**
|
|
44
|
-
* Build the first model, plus an optional start-up command. Must be pure.
|
|
45
|
-
* Runs once per instance; the command runs once per client mount, never
|
|
46
|
-
* during server rendering.
|
|
47
|
-
*/
|
|
48
|
-
readonly init: () => UpdateResult<Model, Message, R>;
|
|
49
|
-
/** The only place state changes. Must be pure. */
|
|
50
|
-
readonly update: (model: Model, message: Message) => UpdateResult<Model, Message, R>;
|
|
51
|
-
/** Render the model. Must be pure; report facts with `dispatch`. */
|
|
52
|
-
readonly view: (model: Model, dispatch: Dispatch<Message>) => View;
|
|
53
|
-
/** Ongoing work gated by slices of the model. */
|
|
54
|
-
readonly subscriptions?: readonly Subscription<Model, Message, any, R>[] | undefined;
|
|
55
|
-
/** Services available to commands and subscriptions. */
|
|
56
|
-
readonly layer?: Layer.Layer<R, E> | undefined;
|
|
57
|
-
/**
|
|
58
|
-
* Codec for the model snapshot. Without it the model must be JSON-safe;
|
|
59
|
-
* with it, values like `Date` survive server rendering into hydration.
|
|
60
|
-
*/
|
|
61
|
-
readonly schema?: Schema.ConstraintCodec<Model, unknown> | undefined;
|
|
62
|
-
}
|
|
63
|
-
/** An Elm-style app: mount `component` like any Ilha component. */
|
|
64
|
-
export interface ModelApp<Model, Message, R = never, E = never> {
|
|
65
|
-
readonly component: Component;
|
|
66
|
-
readonly options: AppOptions<Model, Message, R, E>;
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* Split one or many commands. Internal: shared with `submodel`, not part of
|
|
70
|
-
* the package surface. `Effect.isEffect` narrows the union where
|
|
71
|
-
* `Array.isArray` cannot, so no assertion is needed.
|
|
72
|
-
*/
|
|
73
|
-
export declare const eachCmd: <Message, R>(cmd: Cmd<Message, R> | readonly Cmd<Message, R>[]) => readonly Cmd<Message, R>[];
|
|
74
|
-
/**
|
|
75
|
-
* Latest-wins command: starting one interrupts the running command with the
|
|
76
|
-
* same key, so only the latest result dispatches. Different keys run
|
|
77
|
-
* independently. Keys are per app instance: two mounted instances never
|
|
78
|
-
* share them.
|
|
79
|
-
*/
|
|
80
|
-
export declare const keyed: <Message, R>(key: string, cmd: Cmd<Message, R>) => Cmd<Message, R>;
|
|
81
|
-
/** Services an effect still requires. */
|
|
82
|
-
type EffectNeeds<T> = T extends Effect.Effect<unknown, unknown, infer R> ? R : never;
|
|
83
|
-
/** Services one command, or one command list, still requires. */
|
|
84
|
-
type CmdNeeds<T> = T extends readonly (infer Each)[] ? EffectNeeds<Each> : EffectNeeds<T>;
|
|
85
|
-
/** Services an `init` or `update` result still requires. */
|
|
86
|
-
type UpdateNeeds<T> = T extends {
|
|
87
|
-
cmd?: infer C;
|
|
88
|
-
} ? CmdNeeds<Exclude<C, undefined>> : never;
|
|
89
|
-
/** Services one subscription entry still requires. */
|
|
90
|
-
type SubNeeds<T> = T extends {
|
|
91
|
-
stream: (...args: never[]) => Stream.Stream<unknown, unknown, infer R>;
|
|
92
|
-
} ? R : never;
|
|
93
|
-
/** Every service the app's commands and subscriptions still require. */
|
|
94
|
-
type OptionsNeeds<O> = (O extends {
|
|
95
|
-
init: (...args: never[]) => infer Ret;
|
|
96
|
-
} ? UpdateNeeds<Ret> : never) | (O extends {
|
|
97
|
-
update: (...args: never[]) => infer Ret;
|
|
98
|
-
} ? UpdateNeeds<Ret> : never) | (O extends {
|
|
99
|
-
subscriptions?: infer S;
|
|
100
|
-
} ? S extends readonly (infer Each)[] ? SubNeeds<Each> : never : never);
|
|
101
|
-
/**
|
|
102
|
-
* Reject commands and subscriptions that need services outside the layer.
|
|
103
|
-
* The runtime always provides `AtomRegistry`; anything else must come from
|
|
104
|
-
* `layer`. Evaluated after `O` and `L` are fixed, so inference never sees
|
|
105
|
-
* the layer's services through this check.
|
|
106
|
-
*/
|
|
107
|
-
type CheckServices<O, L extends Layer.Any> = OptionsNeeds<O> extends infer Needs ? [Needs] extends [Layer.Success<L> | AtomRegistry] ? unknown : {
|
|
108
|
-
"services missing from layer": Exclude<Needs, Layer.Success<L> | AtomRegistry>;
|
|
109
|
-
} : never;
|
|
110
|
-
/**
|
|
111
|
-
* What `defineApp` infers `Model` and `Message` from. Command and stream
|
|
112
|
-
* requirements stay permissive here so inference never forces the layer
|
|
113
|
-
* type early; `CheckServices` validates coverage after, and the layer
|
|
114
|
-
* itself is captured by `{ layer?: L }`.
|
|
115
|
-
*/
|
|
116
|
-
type LooseOptions<Model, Message> = Omit<AppOptions<Model, Message, any, any>, "layer">;
|
|
117
|
-
/**
|
|
118
|
-
* Define an Elm-style app. One atom holds the whole model; `dispatch` runs
|
|
119
|
-
* `update` and rerenders; commands run concurrently inside the app runtime;
|
|
120
|
-
* each subscription restarts only when its own deps change and stops on
|
|
121
|
-
* unmount.
|
|
122
|
-
*/
|
|
123
|
-
export declare const defineApp: <Model, Message, L extends Layer.Any = Layer.Layer<never, never>, O extends LooseOptions<Model, Message> = LooseOptions<Model, Message>>(options: LooseOptions<Model, Message> & O & {
|
|
124
|
-
layer?: L | undefined;
|
|
125
|
-
} & CheckServices<O, L>) => ModelApp<Model, Message, Layer.Success<L>, Layer.Error<L>>;
|
|
126
|
-
export {};
|
package/dist/submodel.d.ts
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import type { UpdateResult } from "./app";
|
|
2
|
-
/**
|
|
3
|
-
* One transform over a model, used with {@link combine}. A child fold
|
|
4
|
-
* returns a step; inline lambdas receive the model the previous step wrote.
|
|
5
|
-
*/
|
|
6
|
-
export type Step<Model, Message, R = never> = (model: Model) => UpdateResult<Model, Message, R>;
|
|
7
|
-
/**
|
|
8
|
-
* Run steps in order, threading each model into the next. The steps run in
|
|
9
|
-
* order, but the commands from all steps run concurrently, like any command
|
|
10
|
-
* list.
|
|
11
|
-
*/
|
|
12
|
-
export declare const combine: <Model, Message, R = never>(model: Model, steps: readonly Step<Model, Message, R>[]) => UpdateResult<Model, Message, R>;
|
|
13
|
-
/** Options for {@link foldChild}. */
|
|
14
|
-
export interface FoldChildOptions<ParentModel, ParentMessage, ChildModel, ChildMessage, R = never> {
|
|
15
|
-
/** The child's own update. The parent never touches the child model. */
|
|
16
|
-
readonly update: (model: ChildModel, message: ChildMessage) => UpdateResult<ChildModel, ChildMessage, R>;
|
|
17
|
-
/** Read the child slice. `undefined` leaves the parent unchanged. */
|
|
18
|
-
readonly read: (model: ParentModel) => ChildModel | undefined;
|
|
19
|
-
/** Write the child slice back. */
|
|
20
|
-
readonly write: (model: ParentModel, child: ChildModel) => ParentModel;
|
|
21
|
-
/** Lift child messages, usually into a `Got*` wrapper. */
|
|
22
|
-
readonly toParentMessage: (message: ChildMessage) => ParentMessage;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Embed a child update in a parent. Runs the child, writes its model back,
|
|
26
|
-
* and lifts its commands so results arrive wrapped for the parent.
|
|
27
|
-
*/
|
|
28
|
-
export declare const foldChild: <ParentModel, ParentMessage, ChildModel, ChildMessage, R = never>(options: FoldChildOptions<ParentModel, ParentMessage, ChildModel, ChildMessage, R>) => ((model: ParentModel, message: ChildMessage) => UpdateResult<ParentModel, ParentMessage, R>);
|