@expressive/react 0.88.0 → 0.90.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 +20 -46
- package/dist/adapter.d.ts +3 -3
- package/dist/adapter.js +14 -14
- package/dist/adapter.js.map +1 -1
- package/dist/{chunk-component-Bu6E8zDP.js → chunk-component-BZoZVrRW.js} +56 -77
- package/dist/chunk-component-BZoZVrRW.js.map +1 -0
- package/dist/{chunk-element-BwZN13A8.js → chunk-element-CrZVk-LG.js} +2 -2
- package/dist/{chunk-element-BwZN13A8.js.map → chunk-element-CrZVk-LG.js.map} +1 -1
- package/dist/{chunk-runtime-Cn_ynxAT.d.ts → chunk-runtime-Cp1W-hQO.d.ts} +27 -79
- package/dist/has.js +2 -2
- package/dist/index.d.ts +5 -5
- package/dist/index.js +28 -19
- package/dist/index.js.map +1 -1
- package/dist/map.js +2 -2
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +39 -31
- package/dist/vite.js.map +1 -1
- package/package.json +7 -5
- package/dist/chunk-component-Bu6E8zDP.js.map +0 -1
package/README.md
CHANGED
|
@@ -17,14 +17,14 @@ The React adapter for [Expressive MVC](https://github.com/gabeklein/expressive-m
|
|
|
17
17
|
npm install @expressive/mvc @expressive/react
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
-
`@expressive/mvc` is a peer dependency: import `
|
|
20
|
+
`@expressive/mvc` is a peer dependency: import `Model`, `Component` and instructions from it, and import `@expressive/react` once from your entry so the host registers. Provide an instance to a subtree with `<Component for={Model}>` - `Provider` and `Consumer` were removed. The adapter's re-exports of the core are deprecated.
|
|
21
21
|
|
|
22
22
|
Works on React DOM, and on React Native and Expo - the adapter imports only `react` and `react/jsx-runtime`, so there is nothing renderer-specific to port. Exercised on an iOS simulator and an Android emulator in both Debug and Release builds, and gated per release on Metro resolution and a Hermes build (Expo SDK 57, React Native 0.86). Under Jest, add `@expressive` to `transformIgnorePatterns`.
|
|
23
23
|
|
|
24
24
|
```tsx
|
|
25
|
-
import {
|
|
25
|
+
import { Model } from '@expressive/mvc';
|
|
26
26
|
|
|
27
|
-
class Counter extends
|
|
27
|
+
class Counter extends Model {
|
|
28
28
|
count = 0;
|
|
29
29
|
increment = () => this.count++;
|
|
30
30
|
decrement = () => this.count--;
|
|
@@ -45,10 +45,10 @@ function CounterWidget() {
|
|
|
45
45
|
|
|
46
46
|
## Component
|
|
47
47
|
|
|
48
|
-
`Component` is a `
|
|
48
|
+
`Component` is a `Model` usable in JSX - a persistent class instance with lifecycle, context, suspense, and error handling baked in. Reach for it when state is intrinsic to a rendered unit: form inputs, layout shells, route controls, media players.
|
|
49
49
|
|
|
50
50
|
```tsx
|
|
51
|
-
import { Component } from '@expressive/
|
|
51
|
+
import { Component } from '@expressive/mvc';
|
|
52
52
|
|
|
53
53
|
class Counter extends Component {
|
|
54
54
|
count = 0;
|
|
@@ -60,35 +60,7 @@ class Counter extends Component {
|
|
|
60
60
|
<Counter />;
|
|
61
61
|
```
|
|
62
62
|
|
|
63
|
-
Anything read through `this` in `render()` is reactive; the instance survives across renders, so refs, sockets, and Maps held on `this` persist.
|
|
64
|
-
|
|
65
|
-
### Render composition
|
|
66
|
-
|
|
67
|
-
When a subclass overrides `render()`, it **composes** with its base rather than replacing it - no `super.render()`. Each `render()` up the prototype chain wraps the one below, base-outermost, with the inner output arriving as `props.children`.
|
|
68
|
-
|
|
69
|
-
```tsx
|
|
70
|
-
class Frame extends Component {
|
|
71
|
-
render(props = {} as { children?: React.ReactNode }) {
|
|
72
|
-
return (
|
|
73
|
-
<section className="frame">
|
|
74
|
-
<header>Frame</header>
|
|
75
|
-
{props.children}
|
|
76
|
-
</section>
|
|
77
|
-
);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
class Page extends Frame {
|
|
82
|
-
body = 'Hello';
|
|
83
|
-
render() {
|
|
84
|
-
return <p>{this.body}</p>;
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// <Page /> -> <section class="frame"><header>Frame</header><p>Hello</p></section>
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
Every layer binds to the same live instance, so all read the same reactive `this`. A base that wraps must declare a `props` parameter and render `props.children` - a layer that ignores it silently drops everything below. (A base can also choose to *defer* to a subclass's render, e.g. a leaf `<a>` that's overridable; the base detects the subclass content by identity and returns it as-is.)
|
|
63
|
+
Anything read through `this` in `render()` is reactive; the instance survives across renders, so refs, sockets, and Maps held on `this` persist. Model fields also become optional JSX props (`<Counter count={5} />`).
|
|
92
64
|
|
|
93
65
|
### Subcomponents
|
|
94
66
|
|
|
@@ -122,9 +94,11 @@ class DarkModeSwitch extends Toggle {
|
|
|
122
94
|
|
|
123
95
|
The base owns behavior and structure; subclasses author only the rendering. Override a subcomponent as a **method** when it takes no props, or as an **arrow field** when you want its props type inferred from the base - which is how `@expressive/router`'s [`NavLinks`](https://github.com/gabeklein/expressive-mvc/blob/main/packages/router/README.md#generated-navigation) exposes its overridable `Item` / `List` / `Group` members.
|
|
124
96
|
|
|
97
|
+
A subclass `render()` replaces the base's like any method - `super.render(props)` wraps it.
|
|
98
|
+
|
|
125
99
|
### Self-providing context
|
|
126
100
|
|
|
127
|
-
A `Component` provides *itself* to context automatically - no
|
|
101
|
+
A `Component` provides *itself* to context automatically - no provider element needed. Both its own render output and any `children` passed in can read it with `get()`.
|
|
128
102
|
|
|
129
103
|
```tsx
|
|
130
104
|
class Tabs extends Component {
|
|
@@ -155,7 +129,7 @@ It works the same whether the consumer is part of the Component's own render or
|
|
|
155
129
|
|
|
156
130
|
### Props
|
|
157
131
|
|
|
158
|
-
|
|
132
|
+
Model fields become optional JSX props, **merged onto the instance every render** - passing `count={5}` is the same as assigning `this.count = 5`. Extra props beyond fields are read through a parameter on `render`:
|
|
159
133
|
|
|
160
134
|
```tsx
|
|
161
135
|
class Greeting extends Component {
|
|
@@ -180,7 +154,7 @@ Every Component also accepts three special props:
|
|
|
180
154
|
A value that isn't ready yet suspends the render; `fallback` shows in the meantime.
|
|
181
155
|
|
|
182
156
|
```tsx
|
|
183
|
-
import { Component, set } from '@expressive/
|
|
157
|
+
import { Component, set } from '@expressive/mvc';
|
|
184
158
|
|
|
185
159
|
class Profile extends Component {
|
|
186
160
|
user = set<User>(); // undefined until set - suspends render
|
|
@@ -194,20 +168,20 @@ class Profile extends Component {
|
|
|
194
168
|
|
|
195
169
|
## Shared state via context
|
|
196
170
|
|
|
197
|
-
Provide
|
|
171
|
+
Provide an instance once; descendants read it with `Model.get()` - no props, no selectors.
|
|
198
172
|
|
|
199
173
|
```tsx
|
|
200
|
-
import {
|
|
174
|
+
import { Component } from '@expressive/mvc';
|
|
201
175
|
|
|
202
|
-
class Session extends
|
|
176
|
+
class Session extends Model {
|
|
203
177
|
user = 'guest';
|
|
204
178
|
}
|
|
205
179
|
|
|
206
180
|
function App() {
|
|
207
181
|
return (
|
|
208
|
-
<
|
|
182
|
+
<Component for={Session}>
|
|
209
183
|
<Profile />
|
|
210
|
-
</
|
|
184
|
+
</Component>
|
|
211
185
|
);
|
|
212
186
|
}
|
|
213
187
|
|
|
@@ -219,10 +193,10 @@ function Profile() {
|
|
|
219
193
|
|
|
220
194
|
**At a glance**
|
|
221
195
|
|
|
222
|
-
- **`
|
|
223
|
-
- **`
|
|
224
|
-
-
|
|
225
|
-
- **`Component`** - smart
|
|
196
|
+
- **`Model.use()`** - create an instance bound to a component's lifecycle.
|
|
197
|
+
- **`Model.get()`** - read shared state from context, no prop drilling.
|
|
198
|
+
- **`<Component for={Model}>`** - explicit hierarchical dependency injection.
|
|
199
|
+
- **`Component`** - smart widgets and shells whose behavior lives in the tree.
|
|
226
200
|
- **Suspense & error boundaries** - async values suspend; `catch()` handles child errors.
|
|
227
201
|
|
|
228
202
|
Full guide and API reference → **[github.com/gabeklein/expressive-mvc](https://github.com/gabeklein/expressive-mvc)**
|
package/dist/adapter.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { State } from "@expressive/mvc";
|
|
3
|
-
export {
|
|
1
|
+
import { t as Runtime } from "./chunk-runtime-Cp1W-hQO.js";
|
|
2
|
+
import { Model, State } from "@expressive/mvc";
|
|
3
|
+
export { Model, Runtime, State };
|
package/dist/adapter.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import { Context,
|
|
1
|
+
import { a as useSettle, c as useWeak, i as useFactory, o as useSetup, r as Runtime, s as useWatch } from "./chunk-component-BZoZVrRW.js";
|
|
2
|
+
import { Context, Model, Model as Model$1, State } from "@expressive/mvc";
|
|
3
3
|
import { observer, watch } from "@expressive/mvc/observable";
|
|
4
4
|
|
|
5
5
|
//#region src/state.get.ts
|
|
6
|
-
|
|
6
|
+
Model$1.get = function get(argument) {
|
|
7
7
|
const Type = this;
|
|
8
8
|
const [tick, next] = Runtime.useState(0);
|
|
9
9
|
const claim = useSettle(tick);
|
|
10
10
|
const local = Context.get();
|
|
11
|
+
const dispatch = useWeak(next);
|
|
11
12
|
return useFactory(() => {
|
|
12
13
|
let unwatch;
|
|
13
14
|
let mounted = false;
|
|
@@ -16,7 +17,7 @@ State$1.get = function get(argument) {
|
|
|
16
17
|
let force;
|
|
17
18
|
function update() {
|
|
18
19
|
pending = false;
|
|
19
|
-
|
|
20
|
+
dispatch.deref()((x) => x + 1);
|
|
20
21
|
}
|
|
21
22
|
function observed() {
|
|
22
23
|
if (mounted) {
|
|
@@ -54,7 +55,7 @@ State$1.get = function get(argument) {
|
|
|
54
55
|
return (update) => {
|
|
55
56
|
if (update === true) force();
|
|
56
57
|
};
|
|
57
|
-
}, argument === true, Runtime.
|
|
58
|
+
}, argument === true, Runtime.startTransition);
|
|
58
59
|
if (mounted) {
|
|
59
60
|
pending = true;
|
|
60
61
|
queueMicrotask(() => pending && update());
|
|
@@ -98,7 +99,7 @@ State$1.get = function get(argument) {
|
|
|
98
99
|
|
|
99
100
|
//#endregion
|
|
100
101
|
//#region src/state.use.ts
|
|
101
|
-
|
|
102
|
+
Model$1.use = function use(...args) {
|
|
102
103
|
const outer = Context.get();
|
|
103
104
|
return useFactory(() => {
|
|
104
105
|
const add = (arg) => typeof arg == "object" && instance.set(arg);
|
|
@@ -110,6 +111,10 @@ State$1.use = function use(...args) {
|
|
|
110
111
|
} else return args;
|
|
111
112
|
});
|
|
112
113
|
const context = outer.push(instance);
|
|
114
|
+
const teardown = () => {
|
|
115
|
+
context.pop();
|
|
116
|
+
instance.set(null);
|
|
117
|
+
};
|
|
113
118
|
let ready = false;
|
|
114
119
|
return (args) => {
|
|
115
120
|
if (ready) {
|
|
@@ -120,17 +125,12 @@ State$1.use = function use(...args) {
|
|
|
120
125
|
}
|
|
121
126
|
return useWatch(instance, () => {
|
|
122
127
|
ready = true;
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
if (typeof release == "function") release();
|
|
126
|
-
context.pop();
|
|
127
|
-
instance.set(null);
|
|
128
|
-
};
|
|
129
|
-
});
|
|
128
|
+
return instance.mount?.();
|
|
129
|
+
}, teardown);
|
|
130
130
|
};
|
|
131
131
|
})(args);
|
|
132
132
|
};
|
|
133
133
|
|
|
134
134
|
//#endregion
|
|
135
|
-
export {
|
|
135
|
+
export { Model, Runtime, State };
|
|
136
136
|
//# sourceMappingURL=adapter.js.map
|
package/dist/adapter.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.js","names":[],"sources":["../src/state.get.ts","../src/state.use.ts"],"sourcesContent":["import { State, Context } from '@expressive/mvc';\nimport { observer, watch } from '@expressive/mvc/observable';\nimport { Runtime, useFactory, useSettle, useSetup } from './runtime';\n\n/** Type may not be undefined - instead will be null. */\ntype NoVoid<T> = T extends undefined | void ? null : T;\n\ndeclare module '@expressive/mvc' {\n namespace State {\n type ForceRefresh = {\n /** Request a refresh for current component. */\n (): void;\n\n /**\n * Request a refresh and again after promise either resolves or rejects.\n *\n * @param waitFor Promise to wait for.\n * @returns Promise which resolves, after refresh, to same value as `waitFor`.\n */\n <T = void>(waitFor: Promise<T>): Promise<T>;\n\n /**\n * Request refresh before and after async function.\n * A refresh will occur both before and after the given function.\n *\n * **Note:** Any actions performed before first `await` will occur prior to refresh.\n *\n * @param invoke Async function to invoke.\n * @returns Promise which resolves returned value after refresh.\n */\n <T = void>(invoke: () => Promise<T>): Promise<T>;\n };\n\n type GetFactory<T extends State, R> = (\n this: T,\n current: T,\n refresh: ForceRefresh\n ) => R;\n\n type GetEffect<T extends State> = (\n this: T,\n current: T,\n refresh: ForceRefresh\n ) => null;\n\n /** Fetch instance of this class from context. */\n function get<T extends State>(this: State.Extends<T>): T;\n\n /** Fetch instance of this class optionally. */\n function get<T extends State>(\n this: State.Extends<T>,\n required: false\n ): T | undefined;\n\n /** Fetch instance of this class from context. */\n function get<T extends State>(\n this: State.Extends<T>,\n requireValues: true\n ): Required<T>;\n\n function get<T extends State, R>(\n this: State.Extends<T>,\n factory: GetFactory<T, Promise<R> | R>\n ): NoVoid<R>;\n\n function get<T extends State>(\n this: State.Extends<T>,\n factory: GetEffect<T>\n ): null;\n }\n}\n\nState.get = function get<T extends State>(\n this: State.Extends<T>,\n argument?: boolean | State.GetFactory<T, unknown>\n) {\n const Type = this;\n const [tick, next] = Runtime.useState(0);\n const claim = useSettle(tick);\n const local = Context.get();\n const render = useFactory(() => {\n let unwatch: (() => void) | undefined;\n let mounted = false;\n let pending = false;\n let value: any;\n let force!: () => void;\n\n function update() {\n pending = false;\n next((x) => x + 1);\n }\n\n function observed() {\n if (mounted) {\n claim();\n update();\n }\n else pending = true;\n }\n\n function refresh<T>(action?: Promise<T> | (() => Promise<T>)): any {\n if (typeof action == 'function') action = action();\n update();\n if (action instanceof Promise) return action.finally(update);\n }\n\n function release() {\n unsubscribe();\n unwatch?.();\n unwatch = undefined;\n }\n\n function attach(next: T) {\n if (local.get(Type, false) !== next) return;\n\n unwatch?.();\n\n if (observer(next) === null) {\n value = typeof argument === 'function'\n ? argument.call(next, next, refresh)\n : next;\n unwatch = () => {};\n return release;\n }\n\n let first = true;\n\n unwatch = watch(\n next,\n (current) => {\n if (typeof argument === 'function') {\n const next = argument.call(current, current, refresh);\n if (next === value) return;\n value = next;\n } else {\n value = current;\n }\n\n if (!first) observed();\n first = false;\n\n return (update) => {\n if (update === true) force();\n };\n },\n argument === true,\n Runtime.transition\n );\n\n if (mounted) {\n pending = true;\n queueMicrotask(() => pending && update());\n }\n\n return release;\n }\n\n const unsubscribe = local.get(Type, attach);\n\n if (!unwatch) {\n unsubscribe();\n if (argument === false) return () => undefined;\n throw new Error(`Could not find ${Type} in context.`);\n }\n\n if (value === null) {\n release();\n return () => null;\n }\n\n if (value instanceof Promise) {\n let error: Error | undefined;\n\n release();\n\n value\n .then(\n (x) => (value = x),\n (e) => (error = e)\n )\n .finally(update);\n\n value = null;\n\n return () => {\n if (error) throw error;\n return value === undefined ? null : value;\n };\n }\n\n return () => {\n pending = false;\n useSetup((_self, reset) => {\n force = reset;\n\n return () => {\n mounted = true;\n if (pending) update();\n return release;\n };\n });\n return value === undefined ? null : value;\n };\n });\n\n return render();\n};\n","import { State, Context } from '@expressive/mvc';\nimport type { UseState } from '@expressive/mvc';\nimport { useFactory, useWatch } from './runtime';\n\ndeclare module '@expressive/mvc' {\n interface UseState extends State {\n /**\n * Optional hook called when State.use() is invoked within a React component.\n *\n * This is called *every render* of the component, and will intercept\n * arguments which would otherwise be passed into the State constructor.\n *\n * @param props Arguments passed to State.use().\n */\n use?(...props: any[]): Promise<void> | void;\n\n /**\n * Optional hook called once the host component commits. Return a function\n * to run when it unmounts.\n *\n * Not called during server render, nor for an instance merely observed or\n * placed: `.get()` and `{instance}` reach one a component does not own, and\n * `State.new()` has no component at all.\n *\n * Client-only effects belong here - setup which must accompany the instance\n * itself belongs in `new()`.\n */\n mount?(): (() => void) | void;\n }\n\n namespace State {\n type UseArgs<T extends State> = T extends {\n use(...props: infer P): any;\n }\n ? P\n : State.Args<T>;\n\n /**\n * Create and manage instance of this State within React component.\n *\n * @param args Arguments to pass to constructor or `use` method (if defined).\n * @returns Managed instance of this State.\n */\n function use<T extends UseState>(\n this: State.Type<T>,\n ...args: UseArgs<T>\n ): T;\n }\n}\n\nState.use = function use<T extends State>(\n this: State.Type<T>,\n ...args: State.UseArgs<T>\n) {\n const outer = Context.get();\n const render = useFactory(() => {\n const add = (arg: unknown) =>\n typeof arg == 'object' && instance.set(arg as State.Assign<T>);\n\n let use = (...args: State.Args<T>) => Promise.all(args.flat().map(add));\n\n const instance = new this((x) => {\n if ('use' in x && typeof x.use == 'function') {\n use = x.use.bind(x);\n use(...args);\n }\n else return args;\n });\n\n const context = outer.push(instance);\n\n let ready = false;\n\n return (args: State.Args<T>) => {\n if (ready) {\n ready = false;\n Promise.resolve(use(...args)).finally(() => {\n ready = true;\n });\n }\n\n return useWatch(instance, () => {\n ready = true;\n\n const release = (instance as UseState).mount?.();\n\n return () => {\n if (typeof release == 'function') release();\n context.pop();\n instance.set(null);\n };\n });\n };\n });\n\n return render(args);\n};\n"],"mappings":";;;;;AAwEA,QAAM,MAAM,SAAS,IAEnB,UACA;CACA,MAAM,OAAO;CACb,MAAM,CAAC,MAAM,QAAQ,QAAQ,SAAS,EAAE;CACxC,MAAM,QAAQ,UAAU,KAAK;CAC7B,MAAM,QAAQ,QAAQ,KAAK;AA8H3B,QA7He,iBAAiB;EAC9B,IAAI;EACJ,IAAI,UAAU;EACd,IAAI,UAAU;EACd,IAAI;EACJ,IAAI;EAEJ,SAAS,SAAS;AAChB,aAAU;AACV,SAAM,MAAM,IAAI,EAAE;;EAGpB,SAAS,WAAW;AAClB,OAAI,SAAS;AACX,WAAO;AACP,YAAQ;SAEL,WAAU;;EAGjB,SAAS,QAAW,QAA+C;AACjE,OAAI,OAAO,UAAU,WAAY,UAAS,QAAQ;AAClD,WAAQ;AACR,OAAI,kBAAkB,QAAS,QAAO,OAAO,QAAQ,OAAO;;EAG9D,SAAS,UAAU;AACjB,gBAAa;AACb,cAAW;AACX,aAAU;;EAGZ,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AAQ,KAAK;AAyC3B,QAxCe,iBAAiB;EAC9B,MAAM,OAAO,QACX,OAAO,OAAO,YAAY,SAAS,IAAI,IAAuB;EAEhE,IAAI,OAAO,GAAG,SAAwB,QAAQ,IAAI,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC;EAEvE,MAAM,WAAW,IAAI,MAAM,MAAM;AAC/B,OAAI,SAAS,KAAK,OAAO,EAAE,OAAO,YAAY;AAC5C,UAAM,EAAE,IAAI,KAAK,EAAE;AACnB,QAAI,GAAG,KAAK;SAET,QAAO;IACZ;EAEF,MAAM,UAAU,MAAM,KAAK,SAAS;EAEpC,IAAI,QAAQ;AAEZ,UAAQ,SAAwB;AAC9B,OAAI,OAAO;AACT,YAAQ;AACR,YAAQ,QAAQ,IAAI,GAAG,KAAK,CAAC,CAAC,cAAc;AAC1C,aAAQ;MACR;;AAGJ,UAAO,SAAS,gBAAgB;AAC9B,YAAQ;IAER,MAAM,UAAW,SAAsB,SAAS;AAEhD,iBAAa;AACX,SAAI,OAAO,WAAW,WAAY,UAAS;AAC3C,aAAQ,KAAK;AACb,cAAS,IAAI,KAAK;;KAEpB;;GAEJ,CAEY,KAAK"}
|
|
1
|
+
{"version":3,"file":"adapter.js","names":[],"sources":["../src/state.get.ts","../src/state.use.ts"],"sourcesContent":["import { Model, Context } from '@expressive/mvc';\nimport { observer, watch } from '@expressive/mvc/observable';\nimport { Runtime, useFactory, useSettle, useSetup, useWeak } from './runtime';\n\n/** Type may not be undefined - instead will be null. */\ntype NoVoid<T> = T extends undefined | void ? null : T;\n\ndeclare module '@expressive/mvc' {\n namespace Model {\n type ForceRefresh = {\n /** Request a refresh for current component. */\n (): void;\n\n /**\n * Request a refresh and again after promise either resolves or rejects.\n *\n * @param waitFor Promise to wait for.\n * @returns Promise which resolves, after refresh, to same value as `waitFor`.\n */\n <T = void>(waitFor: Promise<T>): Promise<T>;\n\n /**\n * Request refresh before and after async function.\n * A refresh will occur both before and after the given function.\n *\n * **Note:** Any actions performed before first `await` will occur prior to refresh.\n *\n * @param invoke Async function to invoke.\n * @returns Promise which resolves returned value after refresh.\n */\n <T = void>(invoke: () => Promise<T>): Promise<T>;\n };\n\n type GetFactory<T extends Model, R> = (\n this: T,\n current: T,\n refresh: ForceRefresh\n ) => R;\n\n type GetEffect<T extends Model> = (\n this: T,\n current: T,\n refresh: ForceRefresh\n ) => null;\n\n /** Fetch instance of this class from context. */\n function get<T extends Model>(this: Model.Extends<T>): T;\n\n /** Fetch instance of this class optionally. */\n function get<T extends Model>(\n this: Model.Extends<T>,\n required: false\n ): T | undefined;\n\n /** Fetch instance of this class from context. */\n function get<T extends Model>(\n this: Model.Extends<T>,\n requireValues: true\n ): Required<T>;\n\n function get<T extends Model, R>(\n this: Model.Extends<T>,\n factory: GetFactory<T, Promise<R> | R>\n ): NoVoid<R>;\n\n function get<T extends Model>(\n this: Model.Extends<T>,\n factory: GetEffect<T>\n ): null;\n }\n}\n\nModel.get = function get<T extends Model>(\n this: Model.Extends<T>,\n argument?: boolean | Model.GetFactory<T, unknown>\n) {\n const Type = this;\n const [tick, next] = Runtime.useState(0);\n const claim = useSettle(tick);\n const local = Context.get();\n const dispatch = useWeak(next);\n const render = useFactory(() => {\n let unwatch: (() => void) | undefined;\n let mounted = false;\n let pending = false;\n let value: any;\n let force!: () => void;\n\n function update() {\n pending = false;\n dispatch.deref()!((x) => x + 1);\n }\n\n function observed() {\n if (mounted) {\n claim();\n update();\n }\n else pending = true;\n }\n\n function refresh<T>(action?: Promise<T> | (() => Promise<T>)): any {\n if (typeof action == 'function') action = action();\n update();\n if (action instanceof Promise) return action.finally(update);\n }\n\n function release() {\n unsubscribe();\n unwatch?.();\n unwatch = undefined;\n }\n\n function attach(next: T) {\n if (local.get(Type, false) !== next) return;\n\n unwatch?.();\n\n if (observer(next) === null) {\n value = typeof argument === 'function'\n ? argument.call(next, next, refresh)\n : next;\n unwatch = () => {};\n return release;\n }\n\n let first = true;\n\n unwatch = watch(\n next,\n (current) => {\n if (typeof argument === 'function') {\n const next = argument.call(current, current, refresh);\n if (next === value) return;\n value = next;\n } else {\n value = current;\n }\n\n if (!first) observed();\n first = false;\n\n return (update) => {\n if (update === true) force();\n };\n },\n argument === true,\n Runtime.startTransition\n );\n\n if (mounted) {\n pending = true;\n queueMicrotask(() => pending && update());\n }\n\n return release;\n }\n\n const unsubscribe = local.get(Type, attach);\n\n if (!unwatch) {\n unsubscribe();\n if (argument === false) return () => undefined;\n throw new Error(`Could not find ${Type} in context.`);\n }\n\n if (value === null) {\n release();\n return () => null;\n }\n\n if (value instanceof Promise) {\n let error: Error | undefined;\n\n release();\n\n value\n .then(\n (x) => (value = x),\n (e) => (error = e)\n )\n .finally(update);\n\n value = null;\n\n return () => {\n if (error) throw error;\n return value === undefined ? null : value;\n };\n }\n\n return () => {\n pending = false;\n useSetup((_self, reset) => {\n force = reset;\n\n return () => {\n mounted = true;\n if (pending) update();\n return release;\n };\n });\n return value === undefined ? null : value;\n };\n });\n\n return render();\n};\n","import { Model, Context } from '@expressive/mvc';\nimport type { UseModel } from '@expressive/mvc';\nimport { useFactory, useWatch } from './runtime';\n\ndeclare module '@expressive/mvc' {\n interface UseModel extends Model {\n /**\n * Optional hook called when Model.use() is invoked within a React component.\n *\n * This is called *every render* of the component, and will intercept\n * arguments which would otherwise be passed into the Model constructor.\n *\n * @param props Arguments passed to Model.use().\n */\n use?(...props: any[]): Promise<void> | void;\n\n /**\n * Optional hook called once the host component commits. Return a function\n * to run when it unmounts.\n *\n * Not called during server render, nor for an instance merely observed or\n * placed: `.get()` and `{instance}` reach one a component does not own, and\n * `Model.new()` has no component at all.\n *\n * Client-only effects belong here - setup which must accompany the instance\n * itself belongs in `new()`.\n */\n mount?(): (() => void) | void;\n }\n\n namespace Model {\n type UseArgs<T extends Model> = T extends {\n use(...props: infer P): any;\n }\n ? P\n : Model.Args<T>;\n\n /**\n * Create and manage instance of this Model within React component.\n *\n * @param args Arguments to pass to constructor or `use` method (if defined).\n * @returns Managed instance of this Model.\n */\n function use<T extends UseModel>(\n this: Model.Type<T>,\n ...args: UseArgs<T>\n ): T;\n }\n}\n\nModel.use = function use<T extends Model>(\n this: Model.Type<T>,\n ...args: Model.UseArgs<T>\n) {\n const outer = Context.get();\n const render = useFactory(() => {\n const add = (arg: unknown) =>\n typeof arg == 'object' && instance.set(arg as Model.Assign<T>);\n\n let use = (...args: Model.Args<T>) => Promise.all(args.flat().map(add));\n\n const instance = new this((x) => {\n if ('use' in x && typeof x.use == 'function') {\n use = x.use.bind(x);\n use(...args);\n }\n else return args;\n });\n\n const context = outer.push(instance);\n const teardown = () => {\n context.pop();\n instance.set(null);\n };\n\n let ready = false;\n\n return (args: Model.Args<T>) => {\n if (ready) {\n ready = false;\n Promise.resolve(use(...args)).finally(() => {\n ready = true;\n });\n }\n\n return useWatch(instance, () => {\n ready = true;\n return (instance as UseModel).mount?.();\n }, teardown);\n };\n });\n\n return render(args);\n};\n"],"mappings":";;;;;AAwEA,QAAM,MAAM,SAAS,IAEnB,UACA;CACA,MAAM,OAAO;CACb,MAAM,CAAC,MAAM,QAAQ,QAAQ,SAAS,EAAE;CACxC,MAAM,QAAQ,UAAU,KAAK;CAC7B,MAAM,QAAQ,QAAQ,KAAK;CAC3B,MAAM,WAAW,QAAQ,KAAK;AA8H9B,QA7He,iBAAiB;EAC9B,IAAI;EACJ,IAAI,UAAU;EACd,IAAI,UAAU;EACd,IAAI;EACJ,IAAI;EAEJ,SAAS,SAAS;AAChB,aAAU;AACV,YAAS,OAAO,EAAG,MAAM,IAAI,EAAE;;EAGjC,SAAS,WAAW;AAClB,OAAI,SAAS;AACX,WAAO;AACP,YAAQ;SAEL,WAAU;;EAGjB,SAAS,QAAW,QAA+C;AACjE,OAAI,OAAO,UAAU,WAAY,UAAS,QAAQ;AAClD,WAAQ;AACR,OAAI,kBAAkB,QAAS,QAAO,OAAO,QAAQ,OAAO;;EAG9D,SAAS,UAAU;AACjB,gBAAa;AACb,cAAW;AACX,aAAU;;EAGZ,SAAS,OAAO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K;AAsC3B,QArCe,iBAAiB;EAC9B,MAAM,OAAO,QACX,OAAO,OAAO,YAAY,SAAS,IAAI,IAAuB;EAEhE,IAAI,OAAO,GAAG,SAAwB,QAAQ,IAAI,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC;EAEvE,MAAM,WAAW,IAAI,MAAM,MAAM;AAC/B,OAAI,SAAS,KAAK,OAAO,EAAE,OAAO,YAAY;AAC5C,UAAM,EAAE,IAAI,KAAK,EAAE;AACnB,QAAI,GAAG,KAAK;SAET,QAAO;IACZ;EAEF,MAAM,UAAU,MAAM,KAAK,SAAS;EACpC,MAAM,iBAAiB;AACrB,WAAQ,KAAK;AACb,YAAS,IAAI,KAAK;;EAGpB,IAAI,QAAQ;AAEZ,UAAQ,SAAwB;AAC9B,OAAI,OAAO;AACT,YAAQ;AACR,YAAQ,QAAQ,IAAI,GAAG,KAAK,CAAC,CAAC,cAAc;AAC1C,aAAQ;MACR;;AAGJ,UAAO,SAAS,gBAAgB;AAC9B,YAAQ;AACR,WAAQ,SAAsB,SAAS;MACtC,SAAS;;GAEd,CAEY,KAAK"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Component, Context as Context$1,
|
|
1
|
+
import { Component, Context as Context$1, pending, unbind } from "@expressive/mvc";
|
|
2
2
|
import { watch } from "@expressive/mvc/observable";
|
|
3
3
|
|
|
4
4
|
//#region src/runtime.ts
|
|
@@ -44,7 +44,7 @@ function useSettle(tick) {
|
|
|
44
44
|
*
|
|
45
45
|
* @returns The hook's own record, plus the render counter and its setter.
|
|
46
46
|
*/
|
|
47
|
-
function useSetup(init) {
|
|
47
|
+
function useSetup(init, teardown) {
|
|
48
48
|
const { current } = Runtime.useRef({
|
|
49
49
|
rendered: 0,
|
|
50
50
|
revision: 0
|
|
@@ -55,6 +55,7 @@ function useSetup(init) {
|
|
|
55
55
|
});
|
|
56
56
|
return current.rendered++;
|
|
57
57
|
});
|
|
58
|
+
useReap(current, teardown);
|
|
58
59
|
const getRevision = current.getRevision ||= () => current.revision;
|
|
59
60
|
current.fresh = true;
|
|
60
61
|
Runtime.useSyncExternalStore?.(noop, getRevision, getRevision);
|
|
@@ -70,12 +71,12 @@ function useSetup(init) {
|
|
|
70
71
|
}
|
|
71
72
|
return () => {
|
|
72
73
|
if (!current.fresh) {
|
|
73
|
-
if (--current.rendered <= 0)
|
|
74
|
+
if (--current.rendered <= 0) release(current);
|
|
74
75
|
return;
|
|
75
76
|
}
|
|
76
77
|
current.lapsed = true;
|
|
77
78
|
queueMicrotask(() => {
|
|
78
|
-
if (current.lapsed)
|
|
79
|
+
if (current.lapsed) release(current);
|
|
79
80
|
});
|
|
80
81
|
};
|
|
81
82
|
}, []);
|
|
@@ -85,6 +86,25 @@ function useSetup(init) {
|
|
|
85
86
|
update
|
|
86
87
|
];
|
|
87
88
|
}
|
|
89
|
+
function release(setup) {
|
|
90
|
+
setup.release?.();
|
|
91
|
+
setup.teardown?.();
|
|
92
|
+
}
|
|
93
|
+
let reaper;
|
|
94
|
+
function useReap(setup, teardown) {
|
|
95
|
+
const token = Runtime.useRef(null);
|
|
96
|
+
if (!teardown || setup.teardown) return;
|
|
97
|
+
setup.teardown = teardown;
|
|
98
|
+
if (reaper === void 0) reaper = typeof FinalizationRegistry == "function" ? new FinalizationRegistry((setup) => setup.mounted || setup.teardown()) : null;
|
|
99
|
+
reaper?.register(token.current = {}, setup);
|
|
100
|
+
}
|
|
101
|
+
function weak(value) {
|
|
102
|
+
return typeof WeakRef == "function" ? new WeakRef(value) : { deref: () => value };
|
|
103
|
+
}
|
|
104
|
+
function useWeak(value) {
|
|
105
|
+
const ref = Runtime.useRef(null);
|
|
106
|
+
return ref.current ||= weak(value);
|
|
107
|
+
}
|
|
88
108
|
/**
|
|
89
109
|
* Mount-effect with a refreshable return value. Publishing a value before mount
|
|
90
110
|
* defers the update to it, and one published after claims the update being
|
|
@@ -92,44 +112,44 @@ function useSetup(init) {
|
|
|
92
112
|
*
|
|
93
113
|
* @returns Latest value published via the setter (`undefined` until set).
|
|
94
114
|
*/
|
|
95
|
-
function useHook(callback) {
|
|
115
|
+
function useHook(callback, teardown) {
|
|
96
116
|
const [current, tick, update] = useSetup((self, reset) => {
|
|
97
117
|
const mount = callback((next) => {
|
|
98
118
|
self.output = next;
|
|
99
119
|
if (self.mounted) {
|
|
100
120
|
claim();
|
|
101
|
-
self.update?.((x) => x + 1);
|
|
121
|
+
self.update?.deref()((x) => x + 1);
|
|
102
122
|
} else if (self.update) self.queued = true;
|
|
103
123
|
}, reset);
|
|
104
124
|
return () => {
|
|
105
125
|
const cleanup = mount();
|
|
106
126
|
if (self.queued) {
|
|
107
127
|
self.queued = false;
|
|
108
|
-
self.update((x) => x + 1);
|
|
128
|
+
self.update.deref()((x) => x + 1);
|
|
109
129
|
}
|
|
110
130
|
return cleanup;
|
|
111
131
|
};
|
|
112
|
-
});
|
|
132
|
+
}, teardown);
|
|
113
133
|
const claim = useSettle(tick);
|
|
114
|
-
current.update
|
|
134
|
+
current.update ||= weak(update);
|
|
115
135
|
return current.output;
|
|
116
136
|
}
|
|
117
|
-
function useWatch(from, mount) {
|
|
137
|
+
function useWatch(from, mount, teardown) {
|
|
118
138
|
return useHook((refresh, reset) => {
|
|
119
139
|
const release = watch(from, (current) => {
|
|
120
140
|
refresh(current);
|
|
121
141
|
return (update) => {
|
|
122
142
|
if (update === true) reset();
|
|
123
143
|
};
|
|
124
|
-
}, void 0, Runtime.
|
|
144
|
+
}, void 0, Runtime.startTransition);
|
|
125
145
|
return () => {
|
|
126
146
|
const cleanup = mount?.();
|
|
127
147
|
return () => {
|
|
128
148
|
release();
|
|
129
|
-
cleanup
|
|
149
|
+
if (typeof cleanup == "function") cleanup();
|
|
130
150
|
};
|
|
131
151
|
};
|
|
132
|
-
}) ?? from;
|
|
152
|
+
}, teardown) ?? from;
|
|
133
153
|
}
|
|
134
154
|
|
|
135
155
|
//#endregion
|
|
@@ -165,42 +185,6 @@ Context$1.get = (state) => {
|
|
|
165
185
|
} catch {}
|
|
166
186
|
return _get(state);
|
|
167
187
|
};
|
|
168
|
-
function Consumer(props) {
|
|
169
|
-
return props.for.get((i) => props.children(i));
|
|
170
|
-
}
|
|
171
|
-
function Provider({ children, fallback, name, ...props }) {
|
|
172
|
-
const ambient = useAmbient();
|
|
173
|
-
return createProvider(useHook((returns) => {
|
|
174
|
-
const context = new Context$1(ambient);
|
|
175
|
-
const fresh = [];
|
|
176
|
-
let applied;
|
|
177
|
-
let solo;
|
|
178
|
-
returns(({ is, for: input, ...rest }) => {
|
|
179
|
-
if (input !== applied) {
|
|
180
|
-
const single = State.is(input) || input instanceof State;
|
|
181
|
-
applied = input;
|
|
182
|
-
solo = void 0;
|
|
183
|
-
context.set(input, (state, owned) => {
|
|
184
|
-
if (single) solo = state;
|
|
185
|
-
if (owned) fresh.push(state);
|
|
186
|
-
if (is) is(state);
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
|
-
if (solo && Object.keys(rest).length) solo.set(rest);
|
|
190
|
-
return context;
|
|
191
|
-
});
|
|
192
|
-
return () => {
|
|
193
|
-
const release = fresh.map((state) => state.mount?.());
|
|
194
|
-
return () => {
|
|
195
|
-
for (const done of release) if (typeof done == "function") done();
|
|
196
|
-
context.pop();
|
|
197
|
-
};
|
|
198
|
-
};
|
|
199
|
-
})(props), fallback !== void 0 ? Runtime.createElement(Runtime.Suspense, {
|
|
200
|
-
fallback,
|
|
201
|
-
name
|
|
202
|
-
}, children) : children);
|
|
203
|
-
}
|
|
204
188
|
|
|
205
189
|
//#endregion
|
|
206
190
|
//#region src/component.ts
|
|
@@ -218,22 +202,16 @@ Object.defineProperty(Component, "use", {
|
|
|
218
202
|
}
|
|
219
203
|
});
|
|
220
204
|
/**
|
|
221
|
-
*
|
|
222
|
-
*
|
|
223
|
-
*
|
|
224
|
-
* - On the root Component, host own-property keys are trapped so each lands as a
|
|
225
|
-
* plain own property (out of observed state); each adapter assigns its own set.
|
|
226
|
-
* - capitalized methods are rewritten into subcomponents as get/set accessors,
|
|
227
|
-
* so bootstrap skips them too.
|
|
228
|
-
*
|
|
229
|
-
* (Sealing `render` as the content-render seam is handled by core itself.)
|
|
230
|
-
*
|
|
231
|
-
* `before` covers the per-instance case: a capitalized function assigned as an
|
|
232
|
-
* instance field (e.g. `Sidebar = Sidebar` to inject or override one), promoted
|
|
233
|
-
* before `observe` so it is not mistaken for reactive state.
|
|
205
|
+
* On the root Component, host own-property keys are trapped so each lands as a
|
|
206
|
+
* plain own property (out of observed state); each adapter assigns its own set.
|
|
234
207
|
*/
|
|
235
208
|
Component.on({
|
|
236
209
|
type(type) {
|
|
210
|
+
const render = Object.getOwnPropertyDescriptor(type.prototype, "render");
|
|
211
|
+
if (typeof render?.value == "function") Object.defineProperty(type.prototype, "render", {
|
|
212
|
+
...render,
|
|
213
|
+
configurable: false
|
|
214
|
+
});
|
|
237
215
|
if (type === Component) for (const key of Runtime.ignore) Object.defineProperty(Component.prototype, key, { set(value) {
|
|
238
216
|
Object.defineProperty(this, key, {
|
|
239
217
|
value,
|
|
@@ -242,7 +220,7 @@ Component.on({
|
|
|
242
220
|
} });
|
|
243
221
|
subcomponents(type.prototype);
|
|
244
222
|
},
|
|
245
|
-
|
|
223
|
+
setup(self) {
|
|
246
224
|
subcomponents(self);
|
|
247
225
|
}
|
|
248
226
|
});
|
|
@@ -274,7 +252,7 @@ function createFrame(from, context, children) {
|
|
|
274
252
|
name: String(from)
|
|
275
253
|
}, children);
|
|
276
254
|
children = createProvider(context, children);
|
|
277
|
-
return from.catch ? createElement(Runtime.ErrorBoundary, {
|
|
255
|
+
return from.props.catch || from.catch ? createElement(Runtime.ErrorBoundary, {
|
|
278
256
|
self: from,
|
|
279
257
|
children
|
|
280
258
|
}) : children;
|
|
@@ -286,20 +264,21 @@ function createFrame(from, context, children) {
|
|
|
286
264
|
* unmount.
|
|
287
265
|
*/
|
|
288
266
|
function render(from, context) {
|
|
289
|
-
const { createElement } = Runtime;
|
|
290
|
-
const
|
|
291
|
-
const { is: owner
|
|
292
|
-
const
|
|
267
|
+
const { createElement, dedupe } = Runtime;
|
|
268
|
+
const attempt = dedupe?.(from, context);
|
|
269
|
+
const { is: owner } = from;
|
|
270
|
+
const own = Object.prototype.hasOwnProperty.call(owner, "render") && owner.render;
|
|
271
|
+
const teardown = () => {
|
|
272
|
+
attempt?.remove();
|
|
273
|
+
context.pop();
|
|
274
|
+
};
|
|
275
|
+
const Render = () => (own || Object.getPrototypeOf(owner).render).call(from, from.props);
|
|
293
276
|
const Component = () => {
|
|
294
277
|
from = useWatch(from, () => {
|
|
295
278
|
const release = owner.mount?.();
|
|
296
|
-
commit();
|
|
297
|
-
return
|
|
298
|
-
|
|
299
|
-
remove();
|
|
300
|
-
context.pop();
|
|
301
|
-
};
|
|
302
|
-
});
|
|
279
|
+
attempt?.commit();
|
|
280
|
+
return release;
|
|
281
|
+
}, teardown);
|
|
303
282
|
return createFrame(from, context, createElement(Render));
|
|
304
283
|
};
|
|
305
284
|
return () => createElement(Component);
|
|
@@ -339,5 +318,5 @@ function subcomponents(target) {
|
|
|
339
318
|
}
|
|
340
319
|
|
|
341
320
|
//#endregion
|
|
342
|
-
export {
|
|
343
|
-
//# sourceMappingURL=chunk-component-
|
|
321
|
+
export { useSettle as a, useWeak as c, useFactory as i, weak as l, Context$1 as n, useSetup as o, Runtime as r, useWatch as s, createFrame as t };
|
|
322
|
+
//# sourceMappingURL=chunk-component-BZoZVrRW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chunk-component-BZoZVrRW.js","names":["Context"],"sources":["../src/runtime.ts","../src/context.ts","../src/component.ts"],"sourcesContent":["import type { Component } from '@expressive/mvc';\nimport { watch } from '@expressive/mvc/observable';\nimport { pending } from '@expressive/mvc';\nimport type { Context } from './context';\n\ninterface Settle {\n waiting?: (() => void)[];\n claim(): void;\n release(): void;\n}\n\ninterface Setup {\n rendered: number;\n revision: number;\n mounted?: boolean;\n fresh?: boolean;\n getRevision?: () => number;\n lapsed?: boolean;\n commit?: () => (() => void) | void;\n release?: (() => void) | void;\n teardown?: () => void;\n}\n\ninterface Hook<T> extends Setup {\n queued?: boolean;\n update?: Weak<(next: (previous: number) => number) => void>;\n output: T;\n}\n\ninterface Weak<T> {\n deref(): T | undefined;\n}\n\nexport const Runtime = {} as {\n /** Host own-property keys to trap out of observed state; assigned by each adapter. */\n ignore: string[];\n createElement(type: any, props?: any, ...children: any[]): any;\n createContext<T>(value: T): any;\n useContext(context: any): any;\n useState<S>(initial: S | (() => S)): [S, (next: (previous: S) => S) => void];\n useEffect(effect: () => (() => void) | void, deps?: any[]): void;\n useRef<T>(initial: T): { current: T };\n /** Non-urgent bracket a subscriber replays through; absent where the host\n * cannot defer, which keeps normal timing. */\n startTransition?(work: () => void): void;\n /** Consumed for pre-commit revision validation; absent where commits\n * cannot interleave with writes. */\n useSyncExternalStore?(\n subscribe: (notify: () => void) => () => void,\n getSnapshot: () => number,\n getServerSnapshot?: () => number\n ): number;\n /** Per-render-attempt lifecycle; absent where render attempts do not stack. */\n dedupe?(from: Component, context: Context): { commit(): void; remove(): void };\n /** Host error-boundary component, wrapping a Component whose `catch` is set. */\n ErrorBoundary: unknown;\n Suspense: any;\n};\n\nconst noop = () => () => {};\n\nexport function useFactory<T extends object>(factory: () => T) {\n const ref = Runtime.useRef<T | null>(null);\n return ref.current || (ref.current = factory());\n}\n\n/**\n * Returns a claim on the update being replayed, held until this hook commits\n * carrying it - or until unmount, where it never will. Keyed on `tick` so an\n * urgent commit in the meantime, which leaves the deferred update queued, does\n * not release it.\n */\nexport function useSettle(tick: number) {\n const ref = Runtime.useRef<Settle | null>(null);\n const settle = ref.current || (ref.current = {\n claim() {\n const held = pending();\n\n if (held) (settle.waiting ||= []).push(held);\n },\n release() {\n const { waiting } = settle;\n\n if (!waiting) return;\n settle.waiting = undefined;\n\n for (const held of waiting) held();\n }\n });\n\n Runtime.useEffect(() => {\n settle.release();\n return settle.release;\n }, [tick]);\n\n return settle.claim;\n}\n\n/**\n * Run `init` once for the life of a hook and clean up when it unmounts, safe\n * under React StrictMode - a remount shares the render counter, so neither the\n * setup nor its cleanup repeats. A cleanup following a render not yet committed\n * - Fast Refresh re-running effects - defers a microtask, and is dropped if the\n * effect runs again. `reset` invalidates the rendered value so in-flight render\n * attempts revalidate.\n *\n * @returns The hook's own record, plus the render counter and its setter.\n */\nexport function useSetup<T extends Setup>(\n init: (self: T, reset: () => void) => () => (() => void) | void,\n teardown?: () => void\n) {\n const { current } = Runtime.useRef({ rendered: 0, revision: 0 } as T);\n\n const [tick, update] = Runtime.useState(() => {\n if (!current.rendered)\n current.commit = init(current, () => {\n current.revision++;\n });\n\n return current.rendered++;\n });\n\n useReap(current, teardown);\n\n const getRevision = (current.getRevision ||= () => current.revision);\n\n current.fresh = true;\n\n Runtime.useSyncExternalStore?.(noop, getRevision, getRevision);\n\n Runtime.useEffect(() => {\n current.fresh = false;\n });\n\n Runtime.useEffect(() => {\n current.mounted = true;\n current.lapsed = false;\n\n if (current.commit) {\n current.release = current.commit();\n current.commit = undefined;\n }\n\n return () => {\n if (!current.fresh) {\n if (--current.rendered <= 0) release(current);\n return;\n }\n\n current.lapsed = true;\n\n queueMicrotask(() => {\n if (current.lapsed) release(current);\n });\n }\n }, []);\n\n return [current, tick, update] as const;\n}\n\nfunction release(setup: Setup) {\n setup.release?.();\n setup.teardown?.();\n}\n\nlet reaper: FinalizationRegistry<Setup> | null | undefined;\n\nfunction useReap(setup: Setup, teardown?: () => void) {\n const token = Runtime.useRef<object | null>(null);\n\n if (!teardown || setup.teardown) return;\n\n setup.teardown = teardown;\n\n if (reaper === undefined)\n reaper = typeof FinalizationRegistry == 'function'\n ? new FinalizationRegistry((setup) => setup.mounted || setup.teardown!())\n : null;\n\n reaper?.register((token.current = {}), setup);\n}\n\nexport function weak<T extends object>(value: T): Weak<T> {\n return typeof WeakRef == 'function' ? new WeakRef(value) : { deref: () => value };\n}\n\nexport function useWeak<T extends object>(value: T) {\n const ref = Runtime.useRef<Weak<T> | null>(null);\n return (ref.current ||= weak(value));\n}\n\n/**\n * Mount-effect with a refreshable return value. Publishing a value before mount\n * defers the update to it, and one published after claims the update being\n * replayed until this hook commits carrying it.\n *\n * @returns Latest value published via the setter (`undefined` until set).\n */\nexport function useHook<T = void>(\n callback: (\n refresh: (next: T) => void,\n reset: () => void\n ) => () => (() => void) | void,\n teardown?: () => void\n) {\n const [current, tick, update] = useSetup<Hook<T>>((self, reset) => {\n const mount = callback((next) => {\n self.output = next;\n\n if (self.mounted) {\n claim();\n self.update?.deref()!((x) => x + 1);\n }\n else if (self.update) self.queued = true;\n }, reset);\n\n return () => {\n const cleanup = mount();\n\n if (self.queued) {\n self.queued = false;\n self.update!.deref()!((x) => x + 1);\n }\n\n return cleanup;\n };\n }, teardown);\n\n const claim = useSettle(tick);\n\n current.update ||= weak(update);\n\n return current.output;\n}\n\nexport function useWatch<T extends object>(\n from: T,\n mount?: () => (() => void) | void,\n teardown?: () => void\n) {\n return useHook<T>((refresh, reset) => {\n const release = watch(from, (current) => {\n refresh(current);\n\n return (update) => {\n if (update === true) reset();\n };\n }, undefined, Runtime.startTransition);\n\n return () => {\n const cleanup = mount?.();\n\n return () => {\n release();\n if (typeof cleanup == 'function') cleanup();\n };\n };\n }, teardown) ?? from;\n}\n","import { Model, Context, Component } from '@expressive/mvc';\nimport { Runtime } from './runtime';\n\nlet shared: any;\n\n/**\n * Lazily-created context carrying the active {@link Context} down the tree.\n * Lazy because the framework's `createContext` arrives via {@link Runtime},\n * which an adapter's entry populates at load - after this module evaluates.\n */\nfunction Layers() {\n return shared || (shared = Runtime.createContext(Context.root));\n}\n\n/** Read the ambient {@link Context} from the nearest Layers provider. */\nfunction useAmbient() {\n return Runtime.useContext(Layers());\n}\n\n/** Wrap `children` in a {@link Layers} provider carrying `context` down the tree. */\nfunction createProvider(context: Context, children: any) {\n return Runtime.createElement(Layers().Provider, { value: context, children });\n}\n\n// Class components consume the active Context through the host's `contextType`\nObject.defineProperty(Component, 'contextType', { configurable: true, get: Layers });\n\nconst _get = Context.get;\n\nContext.get = (state?: Model) => {\n if (!state)\n try {\n return useAmbient();\n } catch { }\n\n return _get(state);\n};\n\nexport { Context, createProvider };\n","import { Component, unbind } from '@expressive/mvc';\nimport { createProvider, type Context } from './context';\nimport { Runtime, useWatch } from './runtime';\n\ndeclare module '@expressive/mvc' {\n namespace Component {\n /**\n * Not available - a Component is rendered, not a hook.\n * Render it with `<Component />` or `{component}`.\n * For a bare instance use `Component.new()`.\n */\n const use: never;\n }\n\n interface Component {\n /**\n * Optional hook called once this Component commits. Return a function to\n * run when it unmounts.\n *\n * Not called during server render, nor for an instance placed as\n * `{component}` - a placement does not own what it renders. Client-only\n * effects belong here; setup which must accompany the instance itself\n * belongs in `new()`.\n */\n mount?(): (() => void) | void;\n\n /** @deprecated Only to satisfy host JSX. Use `this.get(Model)` instead. */\n readonly context: Context;\n /** @deprecated Only to satisfy host JSX. Use `this.get()` instead. */\n readonly state: {};\n /** @deprecated Only to satisfy host JSX. Use `this.set({})` instead. */\n setState: (state: any, callback?: () => void) => void;\n /** @deprecated Only to satisfy host JSX. Use `this.set(key)` instead. */\n forceUpdate: (callback?: () => void) => void;\n }\n}\n\n// Host-agnostic seams: `state` is a read-only values bag; `context`'s setter\n// pushes a child context, registers the instance for teardown, and installs its\n// per-instance render host. Host-specific descriptors stay in each adapter.\nObject.defineProperties(Component.prototype, {\n state: {\n set() {},\n get: Component.prototype.get\n },\n context: {\n set: bootstrap\n }\n});\n\nObject.defineProperty(Component, 'use', {\n configurable: true,\n value() {\n throw new Error(\n `${this} is a Component - render as an element instead of calling use().`\n );\n }\n});\n\n/**\n * On the root Component, host own-property keys are trapped so each lands as a\n * plain own property (out of observed state); each adapter assigns its own set.\n */\nComponent.on({\n type(type) {\n const render = Object.getOwnPropertyDescriptor(type.prototype, 'render');\n\n if (typeof render?.value == 'function')\n Object.defineProperty(type.prototype, 'render', { ...render, configurable: false });\n\n if (type === Component)\n for (const key of Runtime.ignore)\n Object.defineProperty(Component.prototype, key, {\n set(value) {\n Object.defineProperty(this, key, { value, writable: true });\n }\n });\n\n subcomponents(type.prototype);\n },\n setup(self) {\n subcomponents(self);\n }\n});\n\nfunction bootstrap(this: Component, context: Context){\n context = context.push();\n context.set(this, () => () => this.set(null));\n\n Object.defineProperties(this, {\n context: {\n get: () => context,\n set() {}\n },\n render: {\n value: render(this, context)\n }\n });\n\n this.set(null, () => {\n Object.defineProperty(this, 'props', {\n value: this.props,\n writable: true\n });\n })\n}\n\n/**\n * Wrap a content element in its context provider, a Suspense boundary (unless\n * `fallback` is `false`) and, when `catch` is set, the host error boundary.\n */\nfunction createFrame(from: Component, context: Context, children: unknown) {\n const { createElement } = Runtime;\n\n if(from.fallback !== false)\n children = createElement(\n Runtime.Suspense,\n { fallback: from.fallback, name: String(from) },\n children\n )\n\n children = createProvider(context, children);\n\n return from.props.catch || from.catch\n ? createElement(Runtime.ErrorBoundary, { self: from, children })\n : children;\n}\n\n/**\n * Ownership host for `<Component/>`: React owns the instance, so its render\n * threads the bootstrap-pushed context through `Runtime.dedupe` (React stacks\n * render attempts) and tears that context down - destroying the instance - on\n * unmount.\n */\nfunction render(from: Component, context: Context) {\n const { createElement, dedupe } = Runtime;\n const attempt = dedupe?.(from, context);\n const { is: owner } = from;\n // Read before bootstrap shadows an instance `render` with this host.\n const own = Object.prototype.hasOwnProperty.call(owner, 'render') && owner.render;\n const teardown = () => {\n attempt?.remove();\n context.pop();\n };\n\n const Render = () => (own || Object.getPrototypeOf(owner).render).call(from, from.props);\n const Component = () => {\n from = useWatch(from, () => {\n const release = owner.mount?.();\n\n attempt?.commit();\n\n return release;\n }, teardown);\n\n return createFrame(from, context, createElement(Render));\n };\n\n return () => createElement(Component);\n}\n\n/** Rewrite each own capitalized function on `target` into a subcomponent. */\nfunction subcomponents(target: object) {\n for (const key of Object.getOwnPropertyNames(target)) {\n if (!/^[A-Z]/.test(key)) continue;\n const { value } = Object.getOwnPropertyDescriptor(target, key)!;\n if (typeof value != 'function') continue;\n Object.defineProperty(target, key, {\n configurable: true,\n get(this: Component) {\n const owner = this.is;\n let render = unbind(value);\n const Component = (props: unknown) =>\n render.call(useWatch(owner), props);\n\n Object.defineProperty(owner, key, {\n configurable: true,\n get: () => Component,\n set(fn: Function) {\n render = fn;\n }\n });\n\n return Component;\n },\n set(this: Component, value: unknown) {\n Object.defineProperty(this, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n\n subcomponents(this);\n }\n });\n }\n}\n\nexport { createFrame };\n"],"mappings":";;;;AAiCA,MAAa,UAAU,EAAE;AA0BzB,MAAM,mBAAmB;AAEzB,SAAgB,WAA6B,SAAkB;CAC7D,MAAM,MAAM,QAAQ,OAAiB,KAAK;AAC1C,QAAO,IAAI,YAAY,IAAI,UAAU,SAAS;;;;;;;;AAShD,SAAgB,UAAU,MAAc;CACtC,MAAM,MAAM,QAAQ,OAAsB,KAAK;CAC/C,MAAM,SAAS,IAAI,YAAY,IAAI,UAAU;EAC3C,QAAQ;GACN,MAAM,OAAO,SAAS;AAEtB,OAAI,KAAM,EAAC,OAAO,YAAY,EAAE,EAAE,KAAK,KAAK;;EAE9C,UAAU;GACR,MAAM,EAAE,YAAY;AAEpB,OAAI,CAAC,QAAS;AACd,UAAO,UAAU;AAEjB,QAAK,MAAM,QAAQ,QAAS,OAAM;;EAErC;AAED,SAAQ,gBAAgB;AACtB,SAAO,SAAS;AAChB,SAAO,OAAO;IACb,CAAC,KAAK,CAAC;AAEV,QAAO,OAAO;;;;;;;;;;;;AAahB,SAAgB,SACd,MACA,UACA;CACA,MAAM,EAAE,YAAY,QAAQ,OAAO;EAAE,UAAU;EAAG,UAAU;EAAG,CAAM;CAErE,MAAM,CAAC,MAAM,UAAU,QAAQ,eAAe;AAC5C,MAAI,CAAC,QAAQ,SACX,SAAQ,SAAS,KAAK,eAAe;AACnC,WAAQ;IACR;AAEJ,SAAO,QAAQ;GACf;AAEF,SAAQ,SAAS,SAAS;CAE1B,MAAM,cAAe,QAAQ,sBAAsB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
import { i as useFactory, n as Context$1, r as Runtime, s as useWatch, t as createFrame } from "./chunk-component-BZoZVrRW.js";
|
|
2
2
|
import { Component } from "@expressive/mvc";
|
|
3
3
|
|
|
4
4
|
//#region src/element.ts
|
|
@@ -42,4 +42,4 @@ function Element() {
|
|
|
42
42
|
|
|
43
43
|
//#endregion
|
|
44
44
|
export { seam as t };
|
|
45
|
-
//# sourceMappingURL=chunk-element-
|
|
45
|
+
//# sourceMappingURL=chunk-element-CrZVk-LG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunk-element-
|
|
1
|
+
{"version":3,"file":"chunk-element-CrZVk-LG.js","names":["Context"],"sources":["../src/element.ts"],"sourcesContent":["import { Component } from '@expressive/mvc';\nimport { Context } from './context';\nimport { Runtime, useFactory, useWatch } from './runtime';\nimport { createFrame } from './component';\n\ndeclare module '@expressive/mvc' {\n interface Component {\n /** @deprecated Only to satisfy host JSX. */\n readonly type: typeof Component;\n }\n}\n\nlet template: any;\n\n/**\n * Borrow a host element's descriptors so `self` passes as a React element.\n * `props` false keeps the target's own `props` (Component supplies its own);\n * an object installs it as the element's props (collections have none).\n */\nexport function seam(\n self: object,\n props: object | false,\n type: Function,\n key: unknown\n) {\n if (!template) template = Runtime.createElement('template');\n\n const descriptors = Object.getOwnPropertyDescriptors(template);\n const store = descriptors._store?.value;\n\n if (props === false) delete (descriptors as any).props;\n\n if (store)\n descriptors._store.value = Object.create(\n Object.getPrototypeOf(store),\n Object.getOwnPropertyDescriptors(store)\n );\n\n Object.defineProperties(self, {\n ...descriptors,\n $$typeof: { value: template.$$typeof },\n ...(props ? { props: { value: props } } : undefined),\n key: { value: key },\n type: { value: type }\n });\n\n return template.$$typeof;\n}\n\nObject.defineProperty(Component.prototype, '$$typeof', {\n get(this: Component) {\n const self = this.is;\n return seam(self, false, Element.bind(self), self.key);\n }\n});\n\nfunction Element(this: Component){\n const outer = Context.get();\n const render = useFactory(() => {\n let from = this;\n const context = outer.push(this);\n const Content = () => from.render(from.props);\n\n return () => {\n from = useWatch(this, () => () => context.pop());\n\n return createFrame(from, context, Runtime.createElement(Content));\n };\n });\n\n return render();\n}\n"],"mappings":";;;;AAYA,IAAI;;;;;;AAOJ,SAAgB,KACd,MACA,OACA,MACA,KACA;AACA,KAAI,CAAC,SAAU,YAAW,QAAQ,cAAc,WAAW;CAE3D,MAAM,cAAc,OAAO,0BAA0B,SAAS;CAC9D,MAAM,QAAQ,YAAY,QAAQ;AAElC,KAAI,UAAU,MAAO,QAAQ,YAAoB;AAEjD,KAAI,MACF,aAAY,OAAO,QAAQ,OAAO,OAChC,OAAO,eAAe,MAAM,EAC5B,OAAO,0BAA0B,MAAM,CACxC;AAEH,QAAO,iBAAiB,MAAM;EAC5B,GAAG;EACH,UAAU,EAAE,OAAO,SAAS,UAAU;EACtC,GAAI,QAAQ,EAAE,OAAO,EAAE,OAAO,OAAO,EAAE,GAAG;EAC1C,KAAK,EAAE,OAAO,KAAK;EACnB,MAAM,EAAE,OAAO,MAAM;EACtB,CAAC;AAEF,QAAO,SAAS;;AAGlB,OAAO,eAAe,UAAU,WAAW,YAAY,EACrD,MAAqB;CACnB,MAAM,OAAO,KAAK;AAClB,QAAO,KAAK,MAAM,OAAO,QAAQ,KAAK,KAAK,EAAE,KAAK,IAAI;GAEzD,CAAC;AAEF,SAAS,UAAwB;CAC/B,MAAM,QAAQA,UAAQ,KAAK;AAa3B,QAZe,iBAAiB;EAC9B,IAAI,OAAO;EACX,MAAM,UAAU,MAAM,KAAK,KAAK;EAChC,MAAM,gBAAgB,KAAK,OAAO,KAAK,MAAM;AAE7C,eAAa;AACX,UAAO,SAAS,kBAAkB,QAAQ,KAAK,CAAC;AAEhD,UAAO,YAAY,MAAM,SAAS,QAAQ,cAAc,QAAQ,CAAC;;GAEnE,EAEa"}
|
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import { Component, Context as Context$1
|
|
2
|
-
import * as react from "react";
|
|
1
|
+
import { Component, Context as Context$1 } from "@expressive/mvc";
|
|
3
2
|
|
|
4
3
|
//#region src/state.get.d.ts
|
|
5
4
|
/** Type may not be undefined - instead will be null. */
|
|
6
5
|
type NoVoid<T> = T extends undefined | void ? null : T;
|
|
7
6
|
declare module '@expressive/mvc' {
|
|
8
|
-
namespace
|
|
7
|
+
namespace Model {
|
|
9
8
|
type ForceRefresh = {
|
|
10
9
|
/** Request a refresh for current component. */(): void;
|
|
11
10
|
/**
|
|
@@ -26,29 +25,29 @@ declare module '@expressive/mvc' {
|
|
|
26
25
|
*/
|
|
27
26
|
<T = void>(invoke: () => Promise<T>): Promise<T>;
|
|
28
27
|
};
|
|
29
|
-
type GetFactory<T extends
|
|
30
|
-
type GetEffect<T extends
|
|
28
|
+
type GetFactory<T extends Model, R> = (this: T, current: T, refresh: ForceRefresh) => R;
|
|
29
|
+
type GetEffect<T extends Model> = (this: T, current: T, refresh: ForceRefresh) => null;
|
|
31
30
|
/** Fetch instance of this class from context. */
|
|
32
|
-
function get<T extends
|
|
31
|
+
function get<T extends Model>(this: Model.Extends<T>): T;
|
|
33
32
|
/** Fetch instance of this class optionally. */
|
|
34
|
-
function get<T extends
|
|
33
|
+
function get<T extends Model>(this: Model.Extends<T>, required: false): T | undefined;
|
|
35
34
|
/** Fetch instance of this class from context. */
|
|
36
|
-
function get<T extends
|
|
37
|
-
function get<T extends
|
|
38
|
-
function get<T extends
|
|
35
|
+
function get<T extends Model>(this: Model.Extends<T>, requireValues: true): Required<T>;
|
|
36
|
+
function get<T extends Model, R>(this: Model.Extends<T>, factory: GetFactory<T, Promise<R> | R>): NoVoid<R>;
|
|
37
|
+
function get<T extends Model>(this: Model.Extends<T>, factory: GetEffect<T>): null;
|
|
39
38
|
}
|
|
40
39
|
}
|
|
41
40
|
//#endregion
|
|
42
41
|
//#region src/state.use.d.ts
|
|
43
42
|
declare module '@expressive/mvc' {
|
|
44
|
-
interface
|
|
43
|
+
interface UseModel extends Model {
|
|
45
44
|
/**
|
|
46
|
-
* Optional hook called when
|
|
45
|
+
* Optional hook called when Model.use() is invoked within a React component.
|
|
47
46
|
*
|
|
48
47
|
* This is called *every render* of the component, and will intercept
|
|
49
|
-
* arguments which would otherwise be passed into the
|
|
48
|
+
* arguments which would otherwise be passed into the Model constructor.
|
|
50
49
|
*
|
|
51
|
-
* @param props Arguments passed to
|
|
50
|
+
* @param props Arguments passed to Model.use().
|
|
52
51
|
*/
|
|
53
52
|
use?(...props: any[]): Promise<void> | void;
|
|
54
53
|
/**
|
|
@@ -57,78 +56,27 @@ declare module '@expressive/mvc' {
|
|
|
57
56
|
*
|
|
58
57
|
* Not called during server render, nor for an instance merely observed or
|
|
59
58
|
* placed: `.get()` and `{instance}` reach one a component does not own, and
|
|
60
|
-
* `
|
|
59
|
+
* `Model.new()` has no component at all.
|
|
61
60
|
*
|
|
62
61
|
* Client-only effects belong here - setup which must accompany the instance
|
|
63
62
|
* itself belongs in `new()`.
|
|
64
63
|
*/
|
|
65
64
|
mount?(): (() => void) | void;
|
|
66
65
|
}
|
|
67
|
-
namespace
|
|
68
|
-
type UseArgs<T extends
|
|
66
|
+
namespace Model {
|
|
67
|
+
type UseArgs<T extends Model> = T extends {
|
|
69
68
|
use(...props: infer P): any;
|
|
70
|
-
} ? P :
|
|
69
|
+
} ? P : Model.Args<T>;
|
|
71
70
|
/**
|
|
72
|
-
* Create and manage instance of this
|
|
71
|
+
* Create and manage instance of this Model within React component.
|
|
73
72
|
*
|
|
74
73
|
* @param args Arguments to pass to constructor or `use` method (if defined).
|
|
75
|
-
* @returns Managed instance of this
|
|
74
|
+
* @returns Managed instance of this Model.
|
|
76
75
|
*/
|
|
77
|
-
function use<T extends
|
|
76
|
+
function use<T extends UseModel>(this: Model.Type<T>, ...args: UseArgs<T>): T;
|
|
78
77
|
}
|
|
79
78
|
}
|
|
80
79
|
//#endregion
|
|
81
|
-
//#region src/context.d.ts
|
|
82
|
-
declare namespace Consumer {
|
|
83
|
-
type Props<T extends State$1> = {
|
|
84
|
-
/** Type of controller to fetch from context. */for: State$1.Extends<T>;
|
|
85
|
-
/**
|
|
86
|
-
* Render function, will receive instance of desired controller.
|
|
87
|
-
*
|
|
88
|
-
* Called every render of parent component.
|
|
89
|
-
* Similar to `State.get()`, updates to properties accessed in
|
|
90
|
-
* this function will cause a refresh when they change.
|
|
91
|
-
*/
|
|
92
|
-
children: (value: T) => Component.Node | void;
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
declare function Consumer<T extends State$1>(props: Consumer.Props<T>): string | number | bigint | boolean | react.ReactElement<unknown, string | react.JSXElementConstructor<any>> | Iterable<react.ReactNode> | react.ReactPortal | null;
|
|
96
|
-
declare namespace Provider {
|
|
97
|
-
/**
|
|
98
|
-
* Runs for each State registered by this Provider. Return value is ignored -
|
|
99
|
-
* to run teardown with a State, use `state.set(null, callback)`.
|
|
100
|
-
*/
|
|
101
|
-
type ForEach<T> = (state: T) => void;
|
|
102
|
-
interface SharedProps {
|
|
103
|
-
/**
|
|
104
|
-
* Children to render within this Provider.
|
|
105
|
-
*/
|
|
106
|
-
children?: Component.Node;
|
|
107
|
-
/** A fallback tree to show when suspended. */
|
|
108
|
-
fallback?: Component.Node;
|
|
109
|
-
/**
|
|
110
|
-
* A name for this Suspense boundary for instrumentation purposes.
|
|
111
|
-
* The name will help identify this boundary in React DevTools.
|
|
112
|
-
*/
|
|
113
|
-
name?: string | undefined;
|
|
114
|
-
}
|
|
115
|
-
type ForSingleProps<T extends State$1> = SharedProps & {
|
|
116
|
-
for: T | State$1.Type<T>;
|
|
117
|
-
is: (instance: T) => void;
|
|
118
|
-
} & { [K in State$1.Property<T>]?: T[K] };
|
|
119
|
-
type ForMultipleProps<T extends State$1> = SharedProps & {
|
|
120
|
-
for: Context$1.Accept<T>;
|
|
121
|
-
is?: ForEach<T>;
|
|
122
|
-
};
|
|
123
|
-
type Props<T extends State$1 = State$1> = ForSingleProps<T> | ForMultipleProps<T>;
|
|
124
|
-
}
|
|
125
|
-
declare function Provider<T extends State$1>({
|
|
126
|
-
children,
|
|
127
|
-
fallback,
|
|
128
|
-
name,
|
|
129
|
-
...props
|
|
130
|
-
}: Provider.Props<T>): any;
|
|
131
|
-
//#endregion
|
|
132
80
|
//#region src/component.d.ts
|
|
133
81
|
declare module '@expressive/mvc' {
|
|
134
82
|
namespace Component {
|
|
@@ -150,10 +98,10 @@ declare module '@expressive/mvc' {
|
|
|
150
98
|
* belongs in `new()`.
|
|
151
99
|
*/
|
|
152
100
|
mount?(): (() => void) | void;
|
|
153
|
-
/** @deprecated Only to satisfy host JSX. Use `this.get(
|
|
101
|
+
/** @deprecated Only to satisfy host JSX. Use `this.get(Model)` instead. */
|
|
154
102
|
readonly context: Context$1;
|
|
155
103
|
/** @deprecated Only to satisfy host JSX. Use `this.get()` instead. */
|
|
156
|
-
readonly state:
|
|
104
|
+
readonly state: {};
|
|
157
105
|
/** @deprecated Only to satisfy host JSX. Use `this.set({})` instead. */
|
|
158
106
|
setState: (state: any, callback?: () => void) => void;
|
|
159
107
|
/** @deprecated Only to satisfy host JSX. Use `this.set(key)` instead. */
|
|
@@ -178,11 +126,11 @@ declare const Runtime: {
|
|
|
178
126
|
};
|
|
179
127
|
/** Non-urgent bracket a subscriber replays through; absent where the host
|
|
180
128
|
* cannot defer, which keeps normal timing. */
|
|
181
|
-
|
|
129
|
+
startTransition?(work: () => void): void;
|
|
182
130
|
/** Consumed for pre-commit revision validation; absent where commits
|
|
183
131
|
* cannot interleave with writes. */
|
|
184
|
-
useSyncExternalStore?(subscribe: (notify: () => void) => () => void, getSnapshot: () => number, getServerSnapshot?: () => number): number; /** Per-render-attempt lifecycle
|
|
185
|
-
dedupe(from: Component, context: Context$1): {
|
|
132
|
+
useSyncExternalStore?(subscribe: (notify: () => void) => () => void, getSnapshot: () => number, getServerSnapshot?: () => number): number; /** Per-render-attempt lifecycle; absent where render attempts do not stack. */
|
|
133
|
+
dedupe?(from: Component, context: Context$1): {
|
|
186
134
|
commit(): void;
|
|
187
135
|
remove(): void;
|
|
188
136
|
}; /** Host error-boundary component, wrapping a Component whose `catch` is set. */
|
|
@@ -190,5 +138,5 @@ declare const Runtime: {
|
|
|
190
138
|
Suspense: any;
|
|
191
139
|
};
|
|
192
140
|
//#endregion
|
|
193
|
-
export {
|
|
194
|
-
//# sourceMappingURL=chunk-runtime-
|
|
141
|
+
export { Runtime as t };
|
|
142
|
+
//# sourceMappingURL=chunk-runtime-Cp1W-hQO.d.ts.map
|
package/dist/has.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as seam } from "./chunk-element-
|
|
1
|
+
import { s as useWatch } from "./chunk-component-BZoZVrRW.js";
|
|
2
|
+
import { t as seam } from "./chunk-element-CrZVk-LG.js";
|
|
3
3
|
import { has } from "@expressive/mvc";
|
|
4
4
|
|
|
5
5
|
//#region src/has.ts
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { State } from "./adapter.js";
|
|
1
|
+
import { Model, State } from "./adapter.js";
|
|
3
2
|
import { has } from "./has.js";
|
|
4
3
|
import { map } from "./map.js";
|
|
5
4
|
import { Component as Component$1, Context, def, get, pending, ref, set } from "@expressive/mvc";
|
|
6
|
-
import { JSX, ReactNode } from "react";
|
|
5
|
+
import { Component as Component$3, JSX, ReactNode } from "react";
|
|
7
6
|
|
|
8
7
|
//#region src/element.d.ts
|
|
9
8
|
declare module '@expressive/mvc' {
|
|
@@ -19,12 +18,13 @@ declare module '@expressive/mvc' {
|
|
|
19
18
|
*/
|
|
20
19
|
//#endregion
|
|
21
20
|
//#region src/jsx-runtime.d.ts
|
|
22
|
-
declare module '@expressive/mvc/runtime' {
|
|
21
|
+
declare module '@expressive/mvc/jsx-runtime' {
|
|
23
22
|
interface Host {
|
|
24
23
|
node: ReactNode;
|
|
25
24
|
intrinsics: JSX.IntrinsicElements;
|
|
25
|
+
elementClass: Component$3<any, any>;
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
28
|
//#endregion
|
|
29
|
-
export { Component$1 as Component,
|
|
29
|
+
export { Component$1 as Component, Context, State, def, Model as default, get, has, map, pending, ref, set };
|
|
30
30
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { State } from "./adapter.js";
|
|
3
|
-
import "./chunk-element-
|
|
1
|
+
import { l as weak, r as Runtime } from "./chunk-component-BZoZVrRW.js";
|
|
2
|
+
import { Model as Model$1, State } from "./adapter.js";
|
|
3
|
+
import "./chunk-element-CrZVk-LG.js";
|
|
4
4
|
import { has } from "./has.js";
|
|
5
5
|
import { map } from "./map.js";
|
|
6
6
|
import { Component, Component as Component$1, Context, def, get, pending, ref, set } from "@expressive/mvc";
|
|
7
|
-
import
|
|
7
|
+
import * as React$1 from "react";
|
|
8
|
+
import React, { Children, isValidElement } from "react";
|
|
8
9
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
9
|
-
import { host } from "@expressive/mvc/runtime";
|
|
10
|
+
import { host } from "@expressive/mvc/jsx-runtime";
|
|
10
11
|
|
|
11
12
|
//#region src/jsx-runtime.ts
|
|
12
13
|
host({
|
|
@@ -73,7 +74,7 @@ var ErrorBoundary = class extends React.Component {
|
|
|
73
74
|
this.recovering = true;
|
|
74
75
|
this.setState({ error });
|
|
75
76
|
};
|
|
76
|
-
Promise.resolve(self.catch(error)).then(() => reset(), reset).finally(() => self.set({ fallback }, true));
|
|
77
|
+
Promise.resolve((self.props.catch || self.catch).call(self, error, self.is)).then(() => reset(), reset).finally(() => self.set({ fallback }, true));
|
|
77
78
|
}
|
|
78
79
|
componentDidUpdate() {
|
|
79
80
|
this.recovering = false;
|
|
@@ -88,28 +89,36 @@ var ErrorBoundary = class extends React.Component {
|
|
|
88
89
|
//#endregion
|
|
89
90
|
//#region src/index.ts
|
|
90
91
|
Object.defineProperty(Component$1.prototype, "isReactComponent", { value: true });
|
|
92
|
+
const FIBER = /* @__PURE__ */ new WeakMap();
|
|
93
|
+
Object.defineProperty(Component$1.prototype, "_reactInternals", {
|
|
94
|
+
get() {
|
|
95
|
+
return FIBER.get(this)?.deref();
|
|
96
|
+
},
|
|
97
|
+
set(fiber) {
|
|
98
|
+
FIBER.set(this, weak(fiber));
|
|
99
|
+
}
|
|
100
|
+
});
|
|
91
101
|
Object.assign(Runtime, {
|
|
92
102
|
dedupe,
|
|
93
103
|
ErrorBoundary,
|
|
94
|
-
createElement,
|
|
95
|
-
createContext,
|
|
96
|
-
useContext,
|
|
97
|
-
useEffect,
|
|
98
|
-
useState,
|
|
99
|
-
useRef,
|
|
100
|
-
useSyncExternalStore: React.useSyncExternalStore,
|
|
101
|
-
|
|
102
|
-
Suspense,
|
|
104
|
+
createElement: React$1.createElement,
|
|
105
|
+
createContext: React$1.createContext,
|
|
106
|
+
useContext: React$1.useContext,
|
|
107
|
+
useEffect: React$1.useEffect,
|
|
108
|
+
useState: React$1.useState,
|
|
109
|
+
useRef: React$1.useRef,
|
|
110
|
+
useSyncExternalStore: React$1.useSyncExternalStore,
|
|
111
|
+
startTransition: React$1.startTransition,
|
|
112
|
+
Suspense: React$1.Suspense,
|
|
103
113
|
ignore: [
|
|
104
114
|
"updater",
|
|
105
115
|
"refs",
|
|
106
|
-
"_reactInternals",
|
|
107
116
|
"_reactInternalInstance"
|
|
108
117
|
]
|
|
109
118
|
});
|
|
110
|
-
/** @deprecated Import `{
|
|
111
|
-
var src_default =
|
|
119
|
+
/** @deprecated Import `{ Model }` from `@expressive/mvc`. The default export will be removed. */
|
|
120
|
+
var src_default = Model$1;
|
|
112
121
|
|
|
113
122
|
//#endregion
|
|
114
|
-
export { Component,
|
|
123
|
+
export { Component, Context, State, def, src_default as default, get, has, map, pending, ref, set };
|
|
115
124
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Component"],"sources":["../src/jsx-runtime.ts","../src/boundary.ts","../src/index.ts"],"sourcesContent":["import { Children, isValidElement } from 'react';\nimport { Fragment, jsx, jsxs } from 'react/jsx-runtime';\nimport { host } from '@expressive/mvc/runtime';\n\nimport type { JSX as ReactJSX, ReactNode } from 'react';\n\ndeclare module '@expressive/mvc/runtime' {\n interface Host {\n node: ReactNode;\n intrinsics: ReactJSX.IntrinsicElements;\n }\n}\n\nhost({\n jsx,\n jsxs,\n Fragment,\n isElement: isValidElement,\n childrenOf: Children.toArray,\n typeOf(node){\n return isValidElement(node) ? node.type : undefined;\n },\n propsOf(node){\n return isValidElement(node) ? node.props as Record<string, unknown> : {};\n }\n});\n","import { Component } from '@expressive/mvc';\nimport React from 'react';\nimport { Context } from './context';\n\ninterface Entry {\n committed?: boolean;\n context: Context;\n commit: () => void;\n remove: () => void;\n};\n\n/** In-flight render attempts by tree position, per ambient context.\n * When one commits, older uncommitted attempts at its slot are provably dead. */\nconst SLOTS = new WeakMap<Context, Map<string, Set<Entry>>>();\n\n/**\n * React's attempt lifecycle: fiber-keyed stacking so a superseded (uncommitted)\n * render attempt at a tree position is discarded when a later one commits.\n */\nexport function dedupe(on: Component, context: Context) {\n let slots = SLOTS.get(context.parent!);\n if (!slots) SLOTS.set(context.parent!, (slots = new Map()));\n\n // key/index path to root: stable across render attempts of this element\n let slot = '';\n for (let f = (on as any)._reactInternals; f; f = f.return)\n slot += (f.key ?? f.index) + '.';\n\n let list = slots.get(slot);\n if (!list) slots.set(slot, (list = new Set()));\n\n const entry: Entry = {\n context,\n commit() {\n entry.committed = true;\n\n for (const e of list) {\n if (e === entry) break;\n if (e.committed) continue;\n e.context.pop();\n list.delete(e);\n }\n },\n remove() {\n list.delete(entry);\n }\n };\n\n list.add(entry);\n return entry;\n};\n\nexport class ErrorBoundary extends React.Component<{\n self: Component;\n children: React.ReactNode;\n}> {\n state = {} as { error?: Error };\n recovering = false;\n\n constructor(props: ErrorBoundary['props']) {\n super(props);\n }\n\n static getDerivedStateFromError(error: Error) {\n return { error };\n }\n\n componentDidCatch(error: Error) {\n const { self } = this.props;\n const { fallback } = self;\n const reset = (error?: Error) => {\n this.recovering = true;\n this.setState({ error });\n };\n\n Promise.resolve(self.catch
|
|
1
|
+
{"version":3,"file":"index.js","names":["Component","React","Model"],"sources":["../src/jsx-runtime.ts","../src/boundary.ts","../src/index.ts"],"sourcesContent":["import { Children, isValidElement } from 'react';\nimport { Fragment, jsx, jsxs } from 'react/jsx-runtime';\nimport { host } from '@expressive/mvc/jsx-runtime';\n\nimport type { Component as ReactComponent, JSX as ReactJSX, ReactNode } from 'react';\n\ndeclare module '@expressive/mvc/jsx-runtime' {\n interface Host {\n node: ReactNode;\n intrinsics: ReactJSX.IntrinsicElements;\n elementClass: ReactComponent<any, any>;\n }\n}\n\nhost({\n jsx,\n jsxs,\n Fragment,\n isElement: isValidElement,\n childrenOf: Children.toArray,\n typeOf(node){\n return isValidElement(node) ? node.type : undefined;\n },\n propsOf(node){\n return isValidElement(node) ? node.props as Record<string, unknown> : {};\n }\n});\n","import { Component } from '@expressive/mvc';\nimport React from 'react';\nimport { Context } from './context';\n\ninterface Entry {\n committed?: boolean;\n context: Context;\n commit: () => void;\n remove: () => void;\n};\n\n/** In-flight render attempts by tree position, per ambient context.\n * When one commits, older uncommitted attempts at its slot are provably dead. */\nconst SLOTS = new WeakMap<Context, Map<string, Set<Entry>>>();\n\n/**\n * React's attempt lifecycle: fiber-keyed stacking so a superseded (uncommitted)\n * render attempt at a tree position is discarded when a later one commits.\n */\nexport function dedupe(on: Component, context: Context) {\n let slots = SLOTS.get(context.parent!);\n if (!slots) SLOTS.set(context.parent!, (slots = new Map()));\n\n // key/index path to root: stable across render attempts of this element\n let slot = '';\n for (let f = (on as any)._reactInternals; f; f = f.return)\n slot += (f.key ?? f.index) + '.';\n\n let list = slots.get(slot);\n if (!list) slots.set(slot, (list = new Set()));\n\n const entry: Entry = {\n context,\n commit() {\n entry.committed = true;\n\n for (const e of list) {\n if (e === entry) break;\n if (e.committed) continue;\n e.context.pop();\n list.delete(e);\n }\n },\n remove() {\n list.delete(entry);\n }\n };\n\n list.add(entry);\n return entry;\n};\n\nexport class ErrorBoundary extends React.Component<{\n self: Component;\n children: React.ReactNode;\n}> {\n state = {} as { error?: Error };\n recovering = false;\n\n constructor(props: ErrorBoundary['props']) {\n super(props);\n }\n\n static getDerivedStateFromError(error: Error) {\n return { error };\n }\n\n componentDidCatch(error: Error) {\n const { self } = this.props;\n const { fallback } = self;\n const reset = (error?: Error) => {\n this.recovering = true;\n this.setState({ error });\n };\n\n Promise.resolve((self.props.catch || self.catch)!.call(self, error, self.is))\n .then(() => reset(), reset)\n .finally(() => self.set({ fallback }, true));\n }\n\n componentDidUpdate() {\n this.recovering = false;\n }\n\n render() {\n if (!this.state.error) return this.props.children;\n if (this.recovering) throw this.state.error;\n return this.props.self.fallback;\n }\n};\n","import { Component } from '@expressive/mvc';\nimport { Model } from './adapter';\nimport * as React from 'react';\n\nimport './element';\nimport './jsx-runtime';\n\nimport { Runtime } from './adapter';\nimport { weak } from './runtime';\nimport { ErrorBoundary, dedupe } from './boundary';\n\n// React detects class components by this brand (preact reads `prototype.render`).\nObject.defineProperty(Component.prototype, 'isReactComponent', {\n value: true\n});\n\nconst FIBER = new WeakMap<Component, { deref(): unknown }>();\n\nObject.defineProperty(Component.prototype, '_reactInternals', {\n get(this: Component) {\n return FIBER.get(this)?.deref();\n },\n set(this: Component, fiber: object) {\n FIBER.set(this, weak(fiber));\n }\n});\n\nObject.assign(Runtime, {\n dedupe,\n ErrorBoundary,\n createElement: React.createElement,\n createContext: React.createContext,\n useContext: React.useContext,\n useEffect: React.useEffect,\n useState: React.useState,\n useRef: React.useRef,\n useSyncExternalStore: React.useSyncExternalStore,\n startTransition: React.startTransition,\n Suspense: React.Suspense,\n ignore: [\n 'updater',\n 'refs',\n '_reactInternalInstance'\n ]\n});\n\n/** @deprecated Import `{ Model }` from `@expressive/mvc`. This re-export will be removed. */\nexport { State } from './adapter';\n\n/** @deprecated Import `{ Model }` from `@expressive/mvc`. The default export will be removed. */\nexport default Model;\n\n/** @deprecated Import from `@expressive/mvc`. These re-exports will be removed. */\nexport { Component, Context, def, get, ref, set, pending } from '@expressive/mvc';\n\n/** @deprecated Import `has` from `@expressive/mvc`. This re-export will be removed. */\nexport { has } from './has';\n\n/** @deprecated Import `map` from `@expressive/mvc`. This re-export will be removed. */\nexport { map } from './map';\n"],"mappings":";;;;;;;;;;;;AAcA,KAAK;CACH;CACA;CACA;CACA,WAAW;CACX,YAAY,SAAS;CACrB,OAAO,MAAK;AACV,SAAO,eAAe,KAAK,GAAG,KAAK,OAAO;;CAE5C,QAAQ,MAAK;AACX,SAAO,eAAe,KAAK,GAAG,KAAK,QAAmC,EAAE;;CAE3E,CAAC;;;;;;ACbF,MAAM,wBAAQ,IAAI,SAA2C;;;;;AAM7D,SAAgB,OAAO,IAAe,SAAkB;CACtD,IAAI,QAAQ,MAAM,IAAI,QAAQ,OAAQ;AACtC,KAAI,CAAC,MAAO,OAAM,IAAI,QAAQ,QAAU,wBAAQ,IAAI,KAAK,CAAE;CAG3D,IAAI,OAAO;AACX,MAAK,IAAI,IAAK,GAAW,iBAAiB,GAAG,IAAI,EAAE,OACjD,UAAS,EAAE,OAAO,EAAE,SAAS;CAE/B,IAAI,OAAO,MAAM,IAAI,KAAK;AAC1B,KAAI,CAAC,KAAM,OAAM,IAAI,MAAO,uBAAO,IAAI,KAAK,CAAE;CAE9C,MAAM,QAAe;EACnB;EACA,SAAS;AACP,SAAM,YAAY;AAElB,QAAK,MAAM,KAAK,MAAM;AACpB,QAAI,MAAM,MAAO;AACjB,QAAI,EAAE,UAAW;AACjB,MAAE,QAAQ,KAAK;AACf,SAAK,OAAO,EAAE;;;EAGlB,SAAS;AACP,QAAK,OAAO,MAAM;;EAErB;AAED,MAAK,IAAI,MAAM;AACf,QAAO;;AAGT,IAAa,gBAAb,cAAmC,MAAM,UAGtC;CACD,QAAQ,EAAE;CACV,aAAa;CAEb,YAAY,OAA+B;AACzC,QAAM,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useWatch } from "./chunk-component-BZoZVrRW.js";
|
|
2
|
+
import { t as seam } from "./chunk-element-CrZVk-LG.js";
|
|
3
3
|
import { map } from "@expressive/mvc";
|
|
4
4
|
|
|
5
5
|
//#region src/map.ts
|
package/dist/vite.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Plugin } from "vite";
|
|
2
2
|
|
|
3
3
|
//#region src/vite.d.ts
|
|
4
|
-
/** Hot-patch
|
|
4
|
+
/** Hot-patch Model and Component classes in place during `vite` dev. */
|
|
5
5
|
declare function expressive(): Plugin;
|
|
6
6
|
//#endregion
|
|
7
7
|
export { expressive as default };
|
package/dist/vite.js
CHANGED
|
@@ -40,19 +40,8 @@ function scan(body) {
|
|
|
40
40
|
exports
|
|
41
41
|
};
|
|
42
42
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
* reloads the page; after an update, a changed component is left to React
|
|
46
|
-
* Refresh and any other changed export invalidates importers.
|
|
47
|
-
*/
|
|
48
|
-
function inject(id, body, ssr = false) {
|
|
49
|
-
const { classes, hidden, exports } = scan(body);
|
|
50
|
-
if (!classes.length) return "";
|
|
51
|
-
const list = classes.join(", ");
|
|
52
|
-
const record = Object.entries(exports).map(([name, local]) => `${JSON.stringify(name)}: ${local}`);
|
|
53
|
-
const effect = ssr ? "replace it instead of patching" : "will trigger a full reload";
|
|
54
|
-
const notes = hidden.map((name) => `${JSON.stringify(name)}: ${JSON.stringify(`[expressive] ${name} (${id}) declares #private members, so edits to its module ${effect}. Use _ properties instead to keep HMR.`)}`);
|
|
55
|
-
const replace = ssr ? ` const __notes = { ${notes.join(", ")} };
|
|
43
|
+
const server = (notes, list) => `\
|
|
44
|
+
const __notes = ${JSON.stringify(notes)};
|
|
56
45
|
const __before = import.meta.hot.data.expressive;
|
|
57
46
|
const __classes = (import.meta.hot.data.expressive = { ${list} });
|
|
58
47
|
const __warned = (import.meta.hot.data.warned ||= {});
|
|
@@ -60,9 +49,10 @@ function inject(id, body, ssr = false) {
|
|
|
60
49
|
if (__before && __classes[key] !== __before[key] && !__warned[key]) {
|
|
61
50
|
__warned[key] = true;
|
|
62
51
|
console.warn(__notes[key]);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
const
|
|
52
|
+
}`;
|
|
53
|
+
const browser = (id, notes, list) => `\
|
|
54
|
+
const __notes = ${JSON.stringify(notes)};
|
|
55
|
+
const __flag = (key) => 'expressive:private:' + ${id} + ':' + key;
|
|
66
56
|
for (const key in __notes)
|
|
67
57
|
try {
|
|
68
58
|
if (sessionStorage.getItem(__flag(key)) == 'due') {
|
|
@@ -73,7 +63,7 @@ function inject(id, body, ssr = false) {
|
|
|
73
63
|
const __before = import.meta.hot.data.expressive;
|
|
74
64
|
const __classes = (import.meta.hot.data.expressive = { ${list} });
|
|
75
65
|
for (const key in __before)
|
|
76
|
-
if (__classes[key] !== __before[key] && __classes[key]?.prototype instanceof
|
|
66
|
+
if (__classes[key] !== __before[key] && __classes[key]?.prototype instanceof __Model) {
|
|
77
67
|
const note = __notes[key];
|
|
78
68
|
if (note)
|
|
79
69
|
try {
|
|
@@ -81,32 +71,50 @@ function inject(id, body, ssr = false) {
|
|
|
81
71
|
} catch {
|
|
82
72
|
console.warn(note);
|
|
83
73
|
}
|
|
84
|
-
dispatchEvent(new CustomEvent('expressive:reload', { detail: { module: ${
|
|
74
|
+
dispatchEvent(new CustomEvent('expressive:reload', { detail: { module: ${id}, class: key, reason: note ? 'private members' : 'class changed shape' } }));
|
|
85
75
|
location.reload();
|
|
86
76
|
break;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
return `
|
|
90
|
-
import { hot as __expressive } from '@expressive/mvc/runtime';
|
|
91
|
-
import { State as __State } from '@expressive/mvc';
|
|
77
|
+
}`;
|
|
78
|
+
const patchClasses = (id, classes) => `\
|
|
92
79
|
{
|
|
93
|
-
const __hot =
|
|
80
|
+
const __hot = __accept(${id}, { ${classes.join(", ")} });
|
|
94
81
|
${classes.map((name) => `${name} = __hot.${name};`).join("\n ")}
|
|
95
|
-
}
|
|
82
|
+
}`;
|
|
83
|
+
const acceptUpdates = (replace, record) => `\
|
|
96
84
|
if (import.meta.hot) {
|
|
97
|
-
${replace}
|
|
85
|
+
${replace}
|
|
86
|
+
const __exports = { ${record} };
|
|
98
87
|
import.meta.hot.accept((next) => {
|
|
99
88
|
if (!next) return;
|
|
100
89
|
for (const key in __exports) {
|
|
101
90
|
const after = next[key];
|
|
102
|
-
if (after !== __exports[key] && !(after?.prototype instanceof
|
|
91
|
+
if (after !== __exports[key] && !(after?.prototype instanceof __Model) && (typeof after != 'function' || !/^[A-Z]/.test(after.name)))
|
|
103
92
|
return import.meta.hot.invalidate(\`"\${key}" export cannot be hot-patched.\`);
|
|
104
93
|
}
|
|
105
94
|
});
|
|
95
|
+
}`;
|
|
96
|
+
/**
|
|
97
|
+
* Bind a module's classes to `hot.accept`. A Model class it could not patch
|
|
98
|
+
* reloads the page; after an update, a changed component is left to React
|
|
99
|
+
* Refresh and any other changed export invalidates importers.
|
|
100
|
+
*/
|
|
101
|
+
function inject(id, body, ssr = false) {
|
|
102
|
+
const { classes, hidden, exports } = scan(body);
|
|
103
|
+
if (!classes.length) return "";
|
|
104
|
+
const key = JSON.stringify(id);
|
|
105
|
+
const list = classes.join(", ");
|
|
106
|
+
const record = Object.entries(exports).map(([name, local]) => `${JSON.stringify(name)}: ${local}`);
|
|
107
|
+
const effect = ssr ? "replace it instead of patching" : "will trigger a full reload";
|
|
108
|
+
const notes = Object.fromEntries(hidden.map((name) => [name, `[expressive] ${name} (${id}) declares #private members, so edits to its module ${effect}. Use _ properties instead to keep HMR.`]));
|
|
109
|
+
const replace = ssr ? server(notes, list) : browser(key, notes, list);
|
|
110
|
+
return `\n${[
|
|
111
|
+
`import { Model as __Model } from '@expressive/mvc';`,
|
|
112
|
+
`import { accept as __accept } from '@expressive/mvc/hot';`,
|
|
113
|
+
patchClasses(key, classes),
|
|
114
|
+
acceptUpdates(replace, record.join(", "))
|
|
115
|
+
].join("\n")}\n`;
|
|
106
116
|
}
|
|
107
|
-
|
|
108
|
-
}
|
|
109
|
-
/** Hot-patch State and Component classes in place during `vite` dev. */
|
|
117
|
+
/** Hot-patch Model and Component classes in place during `vite` dev. */
|
|
110
118
|
function expressive() {
|
|
111
119
|
let root = "";
|
|
112
120
|
let runtime;
|
|
@@ -120,7 +128,7 @@ function expressive() {
|
|
|
120
128
|
async transform(code, id, options) {
|
|
121
129
|
const [file] = id.split("?");
|
|
122
130
|
if (!SOURCE.test(file) || file.includes("/node_modules/") || !code.includes("class")) return;
|
|
123
|
-
runtime ||= this.resolve("@expressive/mvc/
|
|
131
|
+
runtime ||= this.resolve("@expressive/mvc/hot").then((found) => found && dirname(found.id));
|
|
124
132
|
const own = await runtime;
|
|
125
133
|
if (own && file.startsWith(own)) return;
|
|
126
134
|
const output = inject(file.startsWith(root + "/") ? file.slice(root.length) : file, this.parse(code).body, options?.ssr);
|
package/dist/vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.js","names":[],"sources":["../src/vite.ts"],"sourcesContent":["import { dirname } from 'node:path';\nimport type { Plugin } from 'vite';\n\ntype Node = { type: string; [key: string]: any };\n\nconst SOURCE = /\\.[cm]?[jt]sx?$/;\n\n/**\n * Top-level classes a module can reassign, those declaring private members,\n * and its exports by local binding.\n */\nfunction scan(body: Node[]) {\n const classes: string[] = [];\n const hidden: string[] = [];\n const exports: Record<string, string> = {};\n\n function add(name: string, node: Node) {\n classes.push(name);\n\n if (node.body.body.some((member: Node) => member.key?.type == 'PrivateIdentifier')) hidden.push(name);\n }\n\n function collect(node: Node) {\n if (node.type == 'ClassDeclaration' && node.id) add(node.id.name, node);\n else if (node.type == 'VariableDeclaration' && node.kind != 'const')\n for (const { id, init } of node.declarations)\n if (id.type == 'Identifier' && init?.type == 'ClassExpression') add(id.name, init);\n }\n\n function names(node: Node): string[] {\n if (node.type == 'VariableDeclaration')\n return node.declarations.flatMap(({ id }: Node) => (id.type == 'Identifier' ? [id.name] : []));\n\n return [node.id.name];\n }\n\n for (const node of body) {\n if (node.type == 'ExportNamedDeclaration') {\n if (node.declaration) {\n collect(node.declaration);\n for (const name of names(node.declaration)) exports[name] = name;\n } else if (!node.source)\n for (const { local, exported } of node.specifiers)\n exports[exported.name ?? exported.value] = local.name;\n } else if (node.type == 'ExportDefaultDeclaration') {\n const { declaration } = node;\n\n collect(declaration);\n\n if (declaration.id) exports.default = declaration.id.name;\n } else collect(node);\n }\n\n return { classes, hidden, exports };\n}\n\
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../src/vite.ts"],"sourcesContent":["import { dirname } from 'node:path';\nimport type { Plugin } from 'vite';\n\ntype Node = { type: string; [key: string]: any };\n\nconst SOURCE = /\\.[cm]?[jt]sx?$/;\n\n/**\n * Top-level classes a module can reassign, those declaring private members,\n * and its exports by local binding.\n */\nfunction scan(body: Node[]) {\n const classes: string[] = [];\n const hidden: string[] = [];\n const exports: Record<string, string> = {};\n\n function add(name: string, node: Node) {\n classes.push(name);\n\n if (node.body.body.some((member: Node) => member.key?.type == 'PrivateIdentifier')) hidden.push(name);\n }\n\n function collect(node: Node) {\n if (node.type == 'ClassDeclaration' && node.id) add(node.id.name, node);\n else if (node.type == 'VariableDeclaration' && node.kind != 'const')\n for (const { id, init } of node.declarations)\n if (id.type == 'Identifier' && init?.type == 'ClassExpression') add(id.name, init);\n }\n\n function names(node: Node): string[] {\n if (node.type == 'VariableDeclaration')\n return node.declarations.flatMap(({ id }: Node) => (id.type == 'Identifier' ? [id.name] : []));\n\n return [node.id.name];\n }\n\n for (const node of body) {\n if (node.type == 'ExportNamedDeclaration') {\n if (node.declaration) {\n collect(node.declaration);\n for (const name of names(node.declaration)) exports[name] = name;\n } else if (!node.source)\n for (const { local, exported } of node.specifiers)\n exports[exported.name ?? exported.value] = local.name;\n } else if (node.type == 'ExportDefaultDeclaration') {\n const { declaration } = node;\n\n collect(declaration);\n\n if (declaration.id) exports.default = declaration.id.name;\n } else collect(node);\n }\n\n return { classes, hidden, exports };\n}\n\nconst server = (notes: Record<string, string>, list: string) => `\\\n const __notes = ${JSON.stringify(notes)};\n const __before = import.meta.hot.data.expressive;\n const __classes = (import.meta.hot.data.expressive = { ${list} });\n const __warned = (import.meta.hot.data.warned ||= {});\n for (const key in __notes)\n if (__before && __classes[key] !== __before[key] && !__warned[key]) {\n __warned[key] = true;\n console.warn(__notes[key]);\n }`;\n\nconst browser = (id: string, notes: Record<string, string>, list: string) => `\\\n const __notes = ${JSON.stringify(notes)};\n const __flag = (key) => 'expressive:private:' + ${id} + ':' + key;\n for (const key in __notes)\n try {\n if (sessionStorage.getItem(__flag(key)) == 'due') {\n console.warn(__notes[key]);\n sessionStorage.setItem(__flag(key), 'shown');\n }\n } catch {}\n const __before = import.meta.hot.data.expressive;\n const __classes = (import.meta.hot.data.expressive = { ${list} });\n for (const key in __before)\n if (__classes[key] !== __before[key] && __classes[key]?.prototype instanceof __Model) {\n const note = __notes[key];\n if (note)\n try {\n if (!sessionStorage.getItem(__flag(key))) sessionStorage.setItem(__flag(key), 'due');\n } catch {\n console.warn(note);\n }\n dispatchEvent(new CustomEvent('expressive:reload', { detail: { module: ${id}, class: key, reason: note ? 'private members' : 'class changed shape' } }));\n location.reload();\n break;\n }`;\n\nconst patchClasses = (id: string, classes: string[]) => `\\\n{\n const __hot = __accept(${id}, { ${classes.join(', ')} });\n ${classes.map((name) => `${name} = __hot.${name};`).join('\\n ')}\n}`;\n\nconst acceptUpdates = (replace: string, record: string) => `\\\nif (import.meta.hot) {\n${replace}\n const __exports = { ${record} };\n import.meta.hot.accept((next) => {\n if (!next) return;\n for (const key in __exports) {\n const after = next[key];\n if (after !== __exports[key] && !(after?.prototype instanceof __Model) && (typeof after != 'function' || !/^[A-Z]/.test(after.name)))\n return import.meta.hot.invalidate(\\`\"\\${key}\" export cannot be hot-patched.\\`);\n }\n });\n}`;\n\n/**\n * Bind a module's classes to `hot.accept`. A Model class it could not patch\n * reloads the page; after an update, a changed component is left to React\n * Refresh and any other changed export invalidates importers.\n */\nfunction inject(id: string, body: Node[], ssr = false) {\n const { classes, hidden, exports } = scan(body);\n\n if (!classes.length) return '';\n\n const key = JSON.stringify(id);\n const list = classes.join(', ');\n const record = Object.entries(exports).map(([name, local]) => `${JSON.stringify(name)}: ${local}`);\n const effect = ssr ? 'replace it instead of patching' : 'will trigger a full reload';\n const notes = Object.fromEntries(\n hidden.map((name) => [name, `[expressive] ${name} (${id}) declares #private members, so edits to its module ${effect}. Use _ properties instead to keep HMR.`])\n );\n const replace = ssr ? server(notes, list) : browser(key, notes, list);\n\n const lines = [\n `import { Model as __Model } from '@expressive/mvc';`,\n `import { accept as __accept } from '@expressive/mvc/hot';`,\n patchClasses(key, classes),\n acceptUpdates(replace, record.join(', '))\n ];\n\n return `\\n${lines.join('\\n')}\\n`;\n}\n\n/** Hot-patch Model and Component classes in place during `vite` dev. */\nexport default function expressive(): Plugin {\n let root = '';\n let runtime: Promise<string | null | undefined> | undefined;\n\n return {\n name: '@expressive/react:hot',\n apply: 'serve',\n enforce: 'post',\n configResolved(config) {\n root = config.root;\n },\n async transform(code, id, options) {\n const [file] = id.split('?');\n\n if (!SOURCE.test(file) || file.includes('/node_modules/') || !code.includes('class'))\n return;\n\n runtime ||= this.resolve('@expressive/mvc/hot').then((found) => found && dirname(found.id));\n\n const own = await runtime;\n\n if (own && file.startsWith(own)) return;\n\n const output = inject(file.startsWith(root + '/') ? file.slice(root.length) : file, this.parse(code).body as Node[], options?.ssr);\n\n if (output) return { code: code + output, map: null };\n }\n };\n}\n"],"mappings":";;;AAKA,MAAM,SAAS;;;;;AAMf,SAAS,KAAK,MAAc;CAC1B,MAAM,UAAoB,EAAE;CAC5B,MAAM,SAAmB,EAAE;CAC3B,MAAM,UAAkC,EAAE;CAE1C,SAAS,IAAI,MAAc,MAAY;AACrC,UAAQ,KAAK,KAAK;AAElB,MAAI,KAAK,KAAK,KAAK,MAAM,WAAiB,OAAO,KAAK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AAU,SAAS,QAAQ,MAAM,GAAG,CAAC;GAE3F,MAAM,MAAM,MAAM;AAElB,OAAI,OAAO,KAAK,WAAW,IAAI,CAAE;GAEjC,MAAM,SAAS,OAAO,KAAK,WAAW,OAAO,IAAI,GAAG,KAAK,MAAM,KAAK,OAAO,GAAG,MAAM,KAAK,MAAM,KAAK,CAAC,MAAgB,SAAS,IAAI;AAElI,OAAI,OAAQ,QAAO;IAAE,MAAM,OAAO;IAAQ,KAAK;IAAM;;EAExD"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@expressive/react",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Class-based reactive state for React. Define
|
|
3
|
+
"version": "0.90.0",
|
|
4
|
+
"description": "Class-based reactive state for React. Define state and logic as plain classes; components update when the values they read change.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"expressive",
|
|
7
7
|
"mvc",
|
|
@@ -58,10 +58,12 @@
|
|
|
58
58
|
},
|
|
59
59
|
"scripts": {
|
|
60
60
|
"build": "tsdown",
|
|
61
|
-
"
|
|
61
|
+
"typecheck": "tsc --noEmit --incremental",
|
|
62
|
+
"coverage": "vitest run --coverage",
|
|
63
|
+
"test": "bun run typecheck && bun run coverage"
|
|
62
64
|
},
|
|
63
65
|
"devDependencies": {
|
|
64
|
-
"@expressive/mvc": "^0.
|
|
66
|
+
"@expressive/mvc": "^0.89.0",
|
|
65
67
|
"@testing-library/react": "^16.3.0",
|
|
66
68
|
"@types/react": "^19",
|
|
67
69
|
"@types/react-dom": "^19",
|
|
@@ -73,7 +75,7 @@
|
|
|
73
75
|
"vite": "^7.3.1"
|
|
74
76
|
},
|
|
75
77
|
"peerDependencies": {
|
|
76
|
-
"@expressive/mvc": "^0.
|
|
78
|
+
"@expressive/mvc": "^0.89.0",
|
|
77
79
|
"react": ">=16.14.0 <20.0.0",
|
|
78
80
|
"vite": ">=5"
|
|
79
81
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"chunk-component-Bu6E8zDP.js","names":["Context"],"sources":["../src/runtime.ts","../src/context.ts","../src/component.ts"],"sourcesContent":["import type { Component } from '@expressive/mvc';\nimport { watch } from '@expressive/mvc/observable';\nimport { pending } from '@expressive/mvc';\nimport type { Context } from './context';\n\ninterface Settle {\n waiting?: (() => void)[];\n claim(): void;\n release(): void;\n}\n\ninterface Setup {\n rendered: number;\n revision: number;\n mounted?: boolean;\n fresh?: boolean;\n getRevision?: () => number;\n lapsed?: boolean;\n commit?: () => (() => void) | void;\n release?: (() => void) | void;\n}\n\ninterface Hook<T> extends Setup {\n queued?: boolean;\n update?: (next: (previous: number) => number) => void;\n output: T;\n}\n\nexport const Runtime = {} as {\n /** Host own-property keys to trap out of observed state; assigned by each adapter. */\n ignore: string[];\n createElement(type: any, props?: any, ...children: any[]): any;\n createContext<T>(value: T): any;\n useContext(context: any): any;\n useState<S>(initial: S | (() => S)): [S, (next: (previous: S) => S) => void];\n useEffect(effect: () => (() => void) | void, deps?: any[]): void;\n useRef<T>(initial: T): { current: T };\n /** Non-urgent bracket a subscriber replays through; absent where the host\n * cannot defer, which keeps normal timing. */\n transition?(work: () => void): void;\n /** Consumed for pre-commit revision validation; absent where commits\n * cannot interleave with writes. */\n useSyncExternalStore?(\n subscribe: (notify: () => void) => () => void,\n getSnapshot: () => number,\n getServerSnapshot?: () => number\n ): number;\n /** Per-render-attempt lifecycle, set by each adapter (React stacks attempts; others no-op). */\n dedupe(from: Component, context: Context): { commit(): void; remove(): void };\n /** Host error-boundary component, wrapping a Component whose `catch` is set. */\n ErrorBoundary: unknown;\n Suspense: any;\n};\n\nconst noop = () => () => {};\n\nexport function useFactory<T extends Function>(factory: () => T) {\n const ref = Runtime.useRef<T | null>(null);\n return ref.current || (ref.current = factory());\n}\n\n/**\n * Returns a claim on the update being replayed, held until this hook commits\n * carrying it - or until unmount, where it never will. Keyed on `tick` so an\n * urgent commit in the meantime, which leaves the deferred update queued, does\n * not release it.\n */\nexport function useSettle(tick: number) {\n const ref = Runtime.useRef<Settle | null>(null);\n const settle = ref.current || (ref.current = {\n claim() {\n const held = pending();\n\n if (held) (settle.waiting ||= []).push(held);\n },\n release() {\n const { waiting } = settle;\n\n if (!waiting) return;\n settle.waiting = undefined;\n\n for (const held of waiting) held();\n }\n });\n\n Runtime.useEffect(() => {\n settle.release();\n return settle.release;\n }, [tick]);\n\n return settle.claim;\n}\n\n/**\n * Run `init` once for the life of a hook and clean up when it unmounts, safe\n * under React StrictMode - a remount shares the render counter, so neither the\n * setup nor its cleanup repeats. A cleanup following a render not yet committed\n * - Fast Refresh re-running effects - defers a microtask, and is dropped if the\n * effect runs again. `reset` invalidates the rendered value so in-flight render\n * attempts revalidate.\n *\n * @returns The hook's own record, plus the render counter and its setter.\n */\nexport function useSetup<T extends Setup>(\n init: (self: T, reset: () => void) => () => (() => void) | void\n) {\n const { current } = Runtime.useRef({ rendered: 0, revision: 0 } as T);\n\n const [tick, update] = Runtime.useState(() => {\n if (!current.rendered)\n current.commit = init(current, () => {\n current.revision++;\n });\n\n return current.rendered++;\n });\n\n const getRevision = (current.getRevision ||= () => current.revision);\n\n current.fresh = true;\n\n Runtime.useSyncExternalStore?.(noop, getRevision, getRevision);\n\n Runtime.useEffect(() => {\n current.fresh = false;\n });\n\n Runtime.useEffect(() => {\n current.mounted = true;\n current.lapsed = false;\n\n if (current.commit) {\n current.release = current.commit();\n current.commit = undefined;\n }\n\n return () => {\n if (!current.fresh) {\n if (--current.rendered <= 0) current.release?.();\n return;\n }\n\n current.lapsed = true;\n\n queueMicrotask(() => {\n if (current.lapsed) current.release?.();\n });\n }\n }, []);\n\n return [current, tick, update] as const;\n}\n\n/**\n * Mount-effect with a refreshable return value. Publishing a value before mount\n * defers the update to it, and one published after claims the update being\n * replayed until this hook commits carrying it.\n *\n * @returns Latest value published via the setter (`undefined` until set).\n */\nexport function useHook<T = void>(\n callback: (\n refresh: (next: T) => void,\n reset: () => void\n ) => () => (() => void) | void\n) {\n const [current, tick, update] = useSetup<Hook<T>>((self, reset) => {\n const mount = callback((next) => {\n self.output = next;\n\n if (self.mounted) {\n claim();\n self.update?.((x) => x + 1);\n }\n else if (self.update) self.queued = true;\n }, reset);\n\n return () => {\n const cleanup = mount();\n\n if (self.queued) {\n self.queued = false;\n self.update!((x) => x + 1);\n }\n\n return cleanup;\n };\n });\n\n const claim = useSettle(tick);\n\n current.update = update;\n\n return current.output;\n}\n\nexport function useWatch<T extends object>(\n from: T,\n mount?: () => (() => void) | void\n) {\n return useHook<T>((refresh, reset) => {\n const release = watch(from, (current) => {\n refresh(current);\n\n return (update) => {\n if (update === true) reset();\n };\n }, undefined, Runtime.transition);\n\n return () => {\n const cleanup = mount?.();\n\n return () => {\n release();\n cleanup?.();\n };\n };\n }) ?? from;\n}\n","import { State, Context, Component } from '@expressive/mvc';\nimport type { UseState } from '@expressive/mvc';\nimport { Runtime, useHook } from './runtime';\n\nlet shared: any;\n\n/**\n * Lazily-created context carrying the active {@link Context} down the tree.\n * Lazy because the framework's `createContext` arrives via {@link Runtime},\n * which an adapter's entry populates at load - after this module evaluates.\n */\nfunction Layers() {\n return shared || (shared = Runtime.createContext(Context.root));\n}\n\n/** Read the ambient {@link Context} from the nearest Layers provider. */\nfunction useAmbient() {\n return Runtime.useContext(Layers());\n}\n\n/** Wrap `children` in a {@link Layers} provider carrying `context` down the tree. */\nfunction createProvider(context: Context, children: any) {\n return Runtime.createElement(Layers().Provider, { value: context, children });\n}\n\n// Class components consume the active Context through the host's `contextType`\nObject.defineProperty(Component, 'contextType', { configurable: true, get: Layers });\n\nconst _get = Context.get;\n\nContext.get = (state?: State) => {\n if (!state)\n try {\n return useAmbient();\n } catch { }\n\n return _get(state);\n};\n\ndeclare namespace Consumer {\n type Props<T extends State> = {\n /** Type of controller to fetch from context. */\n for: State.Extends<T>;\n\n /**\n * Render function, will receive instance of desired controller.\n *\n * Called every render of parent component.\n * Similar to `State.get()`, updates to properties accessed in\n * this function will cause a refresh when they change.\n */\n children: (value: T) => Component.Node | void;\n };\n}\n\nfunction Consumer<T extends State>(props: Consumer.Props<T>) {\n return props.for.get((i) => props.children(i));\n}\n\ndeclare namespace Provider {\n /**\n * Runs for each State registered by this Provider. Return value is ignored -\n * to run teardown with a State, use `state.set(null, callback)`.\n */\n type ForEach<T> = (state: T) => void;\n\n interface SharedProps {\n /**\n * Children to render within this Provider.\n */\n children?: Component.Node;\n\n /** A fallback tree to show when suspended. */\n fallback?: Component.Node;\n\n /**\n * A name for this Suspense boundary for instrumentation purposes.\n * The name will help identify this boundary in React DevTools.\n */\n name?: string | undefined;\n }\n\n type ForSingleProps<T extends State> = SharedProps & {\n for: T | State.Type<T>;\n is: (instance: T) => void;\n } & { [K in State.Property<T>]?: T[K] };\n\n type ForMultipleProps<T extends State> = SharedProps & {\n for: Context.Accept<T>;\n is?: ForEach<T>;\n };\n\n type Props<T extends State = State> = ForSingleProps<T> | ForMultipleProps<T>;\n}\n\ntype Digest<T extends State> = (props: Provider.Props<T>) => Context;\n\nfunction Provider<T extends State>({\n children,\n fallback,\n name,\n ...props\n}: Provider.Props<T>) {\n const ambient = useAmbient();\n const digest: Digest<T> = useHook((returns) => {\n const context = new Context(ambient);\n const fresh: State[] = [];\n\n let applied: Context.Accept<T> | undefined;\n let solo: State | undefined;\n\n returns(({ is, for: input, ...rest }) => {\n if (input !== applied) {\n const single = State.is(input) || input instanceof State;\n\n applied = input;\n solo = undefined;\n\n context.set(input, (state, owned) => {\n if (single) solo = state;\n if (owned) fresh.push(state);\n if (is) is(state);\n });\n }\n\n if (solo && Object.keys(rest).length) solo.set(rest);\n\n return context;\n });\n\n return () => {\n const release = fresh.map((state) => (state as UseState).mount?.());\n\n return () => {\n for (const done of release) if (typeof done == 'function') done();\n context.pop();\n };\n };\n });\n\n return createProvider(\n digest(props),\n fallback !== undefined\n ? Runtime.createElement(Runtime.Suspense, { fallback, name }, children)\n : children\n );\n}\n\nexport { Consumer, Provider, Context, createProvider };\n","import { Component, unbind } from '@expressive/mvc';\nimport { createProvider, type Context } from './context';\nimport { Runtime, useWatch } from './runtime';\n\ndeclare module '@expressive/mvc' {\n namespace Component {\n /**\n * Not available - a Component is rendered, not a hook.\n * Render it with `<Component />` or `{component}`.\n * For a bare instance use `Component.new()`.\n */\n const use: never;\n }\n\n interface Component {\n /**\n * Optional hook called once this Component commits. Return a function to\n * run when it unmounts.\n *\n * Not called during server render, nor for an instance placed as\n * `{component}` - a placement does not own what it renders. Client-only\n * effects belong here; setup which must accompany the instance itself\n * belongs in `new()`.\n */\n mount?(): (() => void) | void;\n\n /** @deprecated Only to satisfy host JSX. Use `this.get(State)` instead. */\n readonly context: Context;\n /** @deprecated Only to satisfy host JSX. Use `this.get()` instead. */\n readonly state: State.Values<this>;\n /** @deprecated Only to satisfy host JSX. Use `this.set({})` instead. */\n setState: (state: any, callback?: () => void) => void;\n /** @deprecated Only to satisfy host JSX. Use `this.set(key)` instead. */\n forceUpdate: (callback?: () => void) => void;\n }\n}\n\n// Host-agnostic seams: `state` is a read-only values bag; `context`'s setter\n// pushes a child context, registers the instance for teardown, and installs its\n// per-instance render host. Host-specific descriptors stay in each adapter.\nObject.defineProperties(Component.prototype, {\n state: {\n set() {},\n get: Component.prototype.get\n },\n context: {\n set: bootstrap\n }\n});\n\nObject.defineProperty(Component, 'use', {\n configurable: true,\n value() {\n throw new Error(\n `${this} is a Component - render as an element instead of calling use().`\n );\n }\n});\n\n/**\n * `State.on` handler that prepares a Component's prototype at bootstrap, before\n * mvc classifies its members:\n *\n * - On the root Component, host own-property keys are trapped so each lands as a\n * plain own property (out of observed state); each adapter assigns its own set.\n * - capitalized methods are rewritten into subcomponents as get/set accessors,\n * so bootstrap skips them too.\n *\n * (Sealing `render` as the content-render seam is handled by core itself.)\n *\n * `before` covers the per-instance case: a capitalized function assigned as an\n * instance field (e.g. `Sidebar = Sidebar` to inject or override one), promoted\n * before `observe` so it is not mistaken for reactive state.\n */\nComponent.on({\n type(type) {\n if (type === Component)\n for (const key of Runtime.ignore)\n Object.defineProperty(Component.prototype, key, {\n set(value) {\n Object.defineProperty(this, key, { value, writable: true });\n }\n });\n\n // capitalized methods into subcomponents\n subcomponents(type.prototype);\n },\n before(self){\n // capitalized instance fields into subcomponents\n subcomponents(self);\n }\n});\n\nfunction bootstrap(this: Component, context: Context){\n context = context.push();\n context.set(this, () => () => this.set(null));\n\n Object.defineProperties(this, {\n context: {\n get: () => context,\n set() {}\n },\n render: {\n value: render(this, context)\n }\n });\n\n this.set(null, () => {\n Object.defineProperty(this, 'props', {\n value: this.props,\n writable: true\n });\n })\n}\n\n/**\n * Wrap a content element in its context provider, a Suspense boundary (unless\n * `fallback` is `false`) and, when `catch` is set, the host error boundary.\n */\nfunction createFrame(from: Component, context: Context, children: unknown) {\n const { createElement } = Runtime;\n\n if(from.fallback !== false)\n children = createElement(\n Runtime.Suspense,\n { fallback: from.fallback, name: String(from) },\n children\n )\n\n children = createProvider(context, children);\n\n return from.catch\n ? createElement(Runtime.ErrorBoundary, { self: from, children })\n : children;\n}\n\n/**\n * Ownership host for `<Component/>`: React owns the instance, so its render\n * threads the bootstrap-pushed context through `Runtime.dedupe` (React stacks\n * render attempts) and tears that context down - destroying the instance - on\n * unmount.\n */\nfunction render(from: Component, context: Context) {\n const { createElement } = Runtime;\n const { commit, remove } = Runtime.dedupe(from, context);\n const { is: owner, render } = from;\n\n const Render = () => render.call(from, from.props);\n const Component = () => {\n from = useWatch(from, () => {\n const release = owner.mount?.();\n\n commit();\n\n return () => {\n if (typeof release == 'function') release();\n remove();\n context.pop();\n };\n });\n\n return createFrame(from, context, createElement(Render));\n };\n\n return () => createElement(Component);\n}\n\n/** Rewrite each own capitalized function on `target` into a subcomponent. */\nfunction subcomponents(target: object) {\n for (const key of Object.getOwnPropertyNames(target)) {\n if (!/^[A-Z]/.test(key)) continue;\n const { value } = Object.getOwnPropertyDescriptor(target, key)!;\n if (typeof value != 'function') continue;\n Object.defineProperty(target, key, {\n configurable: true,\n get(this: Component) {\n const owner = this.is;\n let render = unbind(value);\n const Component = (props: unknown) =>\n render.call(useWatch(owner), props);\n\n Object.defineProperty(owner, key, {\n configurable: true,\n get: () => Component,\n set(fn: Function) {\n render = fn;\n }\n });\n\n return Component;\n },\n set(this: Component, value: unknown) {\n Object.defineProperty(this, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n\n subcomponents(this);\n }\n });\n }\n}\n\nexport { createFrame };\n"],"mappings":";;;;AA4BA,MAAa,UAAU,EAAE;AA0BzB,MAAM,mBAAmB;AAEzB,SAAgB,WAA+B,SAAkB;CAC/D,MAAM,MAAM,QAAQ,OAAiB,KAAK;AAC1C,QAAO,IAAI,YAAY,IAAI,UAAU,SAAS;;;;;;;;AAShD,SAAgB,UAAU,MAAc;CACtC,MAAM,MAAM,QAAQ,OAAsB,KAAK;CAC/C,MAAM,SAAS,IAAI,YAAY,IAAI,UAAU;EAC3C,QAAQ;GACN,MAAM,OAAO,SAAS;AAEtB,OAAI,KAAM,EAAC,OAAO,YAAY,EAAE,EAAE,KAAK,KAAK;;EAE9C,UAAU;GACR,MAAM,EAAE,YAAY;AAEpB,OAAI,CAAC,QAAS;AACd,UAAO,UAAU;AAEjB,QAAK,MAAM,QAAQ,QAAS,OAAM;;EAErC;AAED,SAAQ,gBAAgB;AACtB,SAAO,SAAS;AAChB,SAAO,OAAO;IACb,CAAC,KAAK,CAAC;AAEV,QAAO,OAAO;;;;;;;;;;;;AAahB,SAAgB,SACd,MACA;CACA,MAAM,EAAE,YAAY,QAAQ,OAAO;EAAE,UAAU;EAAG,UAAU;EAAG,CAAM;CAErE,MAAM,CAAC,MAAM,UAAU,QAAQ,eAAe;AAC5C,MAAI,CAAC,QAAQ,SACX,SAAQ,SAAS,KAAK,eAAe;AACnC,WAAQ;IACR;AAEJ,SAAO,QAAQ;GACf;CAEF,MAAM,cAAe,QAAQ,sBAAsB,QAAQ;AAE3D,SAAQ,QAAQ;AAEhB,SAAQ,uBAAuB,MAAM,aAAa,YA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