@expressive/react 0.77.0 → 0.79.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 +228 -0
- package/dist/adapter.d.ts +147 -0
- package/dist/adapter.js +120 -0
- package/dist/adapter.js.map +1 -0
- package/dist/index.d.ts +9 -131
- package/dist/index.js +72 -188
- package/dist/index.js.map +1 -1
- package/package.json +14 -13
- package/LICENSE +0 -21
- package/dist/state.d.ts +0 -74
- package/dist/state.js +0 -105
- package/dist/state.js.map +0 -1
- package/dist/use-AIA25P7A.js +0 -63
- package/dist/use-AIA25P7A.js.map +0 -1
- package/dist/use-_Es6cU25.d.ts +0 -5
package/README.md
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
<h1 align="center">@expressive/react</h1>
|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
React adapter for Expressive MVC - class-based reactive state.
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<a href="https://www.npmjs.com/package/@expressive/react"><img alt="NPM" src="https://badge.fury.io/js/%40expressive%2Freact.svg"></a>
|
|
9
|
+
<img src="https://img.shields.io/badge/Coverage-100%25-brightgreen.svg">
|
|
10
|
+
</p>
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
The React adapter for [Expressive MVC](https://github.com/gabeklein/expressive-mvc). Define state as a class, use it in a component, and reads automatically subscribe - components re-render only when accessed values change.
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install @expressive/react react
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
```tsx
|
|
21
|
+
import { State } from '@expressive/react';
|
|
22
|
+
|
|
23
|
+
class Counter extends State {
|
|
24
|
+
count = 0;
|
|
25
|
+
increment = () => this.count++;
|
|
26
|
+
decrement = () => this.count--;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function CounterWidget() {
|
|
30
|
+
const { count, increment, decrement } = Counter.use();
|
|
31
|
+
|
|
32
|
+
return (
|
|
33
|
+
<div>
|
|
34
|
+
<button onClick={decrement}>-</button>
|
|
35
|
+
<span>{count}</span>
|
|
36
|
+
<button onClick={increment}>+</button>
|
|
37
|
+
</div>
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Component
|
|
43
|
+
|
|
44
|
+
`Component` is a `State` that owns its own rendering - 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 controls, layout shells, route controllers, media players.
|
|
45
|
+
|
|
46
|
+
```tsx
|
|
47
|
+
import { Component } from '@expressive/react';
|
|
48
|
+
|
|
49
|
+
class Counter extends Component {
|
|
50
|
+
count = 0;
|
|
51
|
+
render() {
|
|
52
|
+
return <button onClick={() => this.count++}>{this.count}</button>;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
<Counter />;
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Anything read through `this` in `render()` is reactive; the instance survives across renders, so refs, sockets, and Maps held on `this` persist. State fields also become optional JSX props (`<Counter count={5} />`).
|
|
60
|
+
|
|
61
|
+
### Render composition
|
|
62
|
+
|
|
63
|
+
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`.
|
|
64
|
+
|
|
65
|
+
```tsx
|
|
66
|
+
class Frame extends Component {
|
|
67
|
+
render(props = {} as { children?: React.ReactNode }) {
|
|
68
|
+
return (
|
|
69
|
+
<section className="frame">
|
|
70
|
+
<header>Frame</header>
|
|
71
|
+
{props.children}
|
|
72
|
+
</section>
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
class Page extends Frame {
|
|
78
|
+
body = 'Hello';
|
|
79
|
+
render() {
|
|
80
|
+
return <p>{this.body}</p>;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// <Page /> -> <section class="frame"><header>Frame</header><p>Hello</p></section>
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
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.)
|
|
88
|
+
|
|
89
|
+
### Subcomponents
|
|
90
|
+
|
|
91
|
+
PascalCase members become their own reactive React components scoped to the live instance. They read the parent's reactive `this` directly - no props plumbing - yet each is an isolated component with its own hooks and boundary. Subclasses override them to customize pieces without touching behavior.
|
|
92
|
+
|
|
93
|
+
```tsx
|
|
94
|
+
abstract class Toggle extends Component {
|
|
95
|
+
active = false;
|
|
96
|
+
|
|
97
|
+
toggle = () => {
|
|
98
|
+
this.active = !this.active;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
Active() { return null; } // subclasses fill these in
|
|
102
|
+
Inactive() { return null; }
|
|
103
|
+
|
|
104
|
+
render() {
|
|
105
|
+
return (
|
|
106
|
+
<div onClick={this.toggle}>
|
|
107
|
+
{this.active ? <this.Active /> : <this.Inactive />}
|
|
108
|
+
</div>
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
class DarkModeSwitch extends Toggle {
|
|
114
|
+
Active() { return <span>Dark</span>; }
|
|
115
|
+
Inactive() { return <span>Light</span>; }
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
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.
|
|
120
|
+
|
|
121
|
+
### Self-providing context
|
|
122
|
+
|
|
123
|
+
A `Component` provides *itself* to context automatically - no `Provider` needed. Both its own render output and any `children` passed in can read it with `get()`.
|
|
124
|
+
|
|
125
|
+
```tsx
|
|
126
|
+
class Tabs extends Component {
|
|
127
|
+
active = 0;
|
|
128
|
+
render(props = {} as { children?: React.ReactNode }) {
|
|
129
|
+
return <div className="tabs">{props.children}</div>;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function Tab({ index, label }: { index: number; label: string }) {
|
|
134
|
+
const tabs = Tabs.get(); // reads the enclosing Tabs instance
|
|
135
|
+
return (
|
|
136
|
+
<button
|
|
137
|
+
className={tabs.active === index ? 'on' : undefined}
|
|
138
|
+
onClick={() => (tabs.active = index)}>
|
|
139
|
+
{label}
|
|
140
|
+
</button>
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
<Tabs>
|
|
145
|
+
<Tab index={0} label="One" />
|
|
146
|
+
<Tab index={1} label="Two" />
|
|
147
|
+
</Tabs>;
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
It works the same whether the consumer is part of the Component's own render or is passed in as `children` - both sit under the instance's context. A render-less `Component` still self-provides, which is what makes it useful purely as a context/boundary placement.
|
|
151
|
+
|
|
152
|
+
### Props
|
|
153
|
+
|
|
154
|
+
State 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`:
|
|
155
|
+
|
|
156
|
+
```tsx
|
|
157
|
+
class Greeting extends Component {
|
|
158
|
+
name = 'World'; // -> optional `name` prop
|
|
159
|
+
|
|
160
|
+
render(props = {} as { loud?: boolean }) { // extra render prop
|
|
161
|
+
return <h1>Hello {this.name}{props.loud && '!!!'}</h1>;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
<Greeting name="React" loud />;
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Every Component also accepts three special props:
|
|
169
|
+
|
|
170
|
+
- **`is`** - callback handed the instance once, at creation.
|
|
171
|
+
- **`ref`** - standard React ref; set after mount, cleared on unmount.
|
|
172
|
+
- **`fallback`** - Suspense/error UI, overriding the instance's own.
|
|
173
|
+
|
|
174
|
+
### Suspense
|
|
175
|
+
|
|
176
|
+
A value that isn't ready yet suspends the render; `fallback` shows in the meantime.
|
|
177
|
+
|
|
178
|
+
```tsx
|
|
179
|
+
import { Component, set } from '@expressive/react';
|
|
180
|
+
|
|
181
|
+
class Profile extends Component {
|
|
182
|
+
user = set<User>(); // undefined until set - suspends render
|
|
183
|
+
fallback = <Spinner />;
|
|
184
|
+
|
|
185
|
+
render() {
|
|
186
|
+
return <span>{this.user.name}</span>;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
## Shared state via context
|
|
192
|
+
|
|
193
|
+
Provide a model once; descendants read it with `State.get()` - no props, no selectors.
|
|
194
|
+
|
|
195
|
+
```tsx
|
|
196
|
+
import { Provider } from '@expressive/react';
|
|
197
|
+
|
|
198
|
+
class Session extends State {
|
|
199
|
+
user = 'guest';
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function App() {
|
|
203
|
+
return (
|
|
204
|
+
<Provider for={Session}>
|
|
205
|
+
<Profile />
|
|
206
|
+
</Provider>
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function Profile() {
|
|
211
|
+
const { user } = Session.get(); // nearest Session in context
|
|
212
|
+
return <p>Signed in as {user}</p>;
|
|
213
|
+
}
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
**At a glance**
|
|
217
|
+
|
|
218
|
+
- **`State.use()`** - create an instance bound to a component's lifecycle.
|
|
219
|
+
- **`State.get()`** - read shared state from context, no prop drilling.
|
|
220
|
+
- **`Provider` / `Consumer`** - explicit hierarchical dependency injection.
|
|
221
|
+
- **`Component`** - smart controls and shells whose behavior lives in the tree.
|
|
222
|
+
- **Suspense & error boundaries** - async values suspend; `catch()` handles child errors.
|
|
223
|
+
|
|
224
|
+
Full guide and API reference → **[github.com/gabeklein/expressive-mvc](https://github.com/gabeklein/expressive-mvc)**
|
|
225
|
+
|
|
226
|
+
## License
|
|
227
|
+
|
|
228
|
+
MIT
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { Component, Context, State as State$1, State as State$2 } from "@expressive/mvc";
|
|
2
|
+
import * as react from "react";
|
|
3
|
+
|
|
4
|
+
//#region src/state.get.d.ts
|
|
5
|
+
/** Type may not be undefined - instead will be null. */
|
|
6
|
+
type NoVoid<T> = T extends undefined | void ? null : T;
|
|
7
|
+
declare module '@expressive/mvc' {
|
|
8
|
+
namespace State {
|
|
9
|
+
type ForceRefresh = {
|
|
10
|
+
/** Request a refresh for current component. */(): void;
|
|
11
|
+
/**
|
|
12
|
+
* Request a refresh and again after promise either resolves or rejects.
|
|
13
|
+
*
|
|
14
|
+
* @param waitFor Promise to wait for.
|
|
15
|
+
* @returns Promise which resolves, after refresh, to same value as `waitFor`.
|
|
16
|
+
*/
|
|
17
|
+
<T = void>(waitFor: Promise<T>): Promise<T>;
|
|
18
|
+
/**
|
|
19
|
+
* Request refresh before and after async function.
|
|
20
|
+
* A refresh will occur both before and after the given function.
|
|
21
|
+
*
|
|
22
|
+
* **Note:** Any actions performed before first `await` will occur prior to refresh.
|
|
23
|
+
*
|
|
24
|
+
* @param invoke Async function to invoke.
|
|
25
|
+
* @returns Promise which resolves returned value after refresh.
|
|
26
|
+
*/
|
|
27
|
+
<T = void>(invoke: () => Promise<T>): Promise<T>;
|
|
28
|
+
};
|
|
29
|
+
type GetFactory<T extends State, R> = (this: T, current: T, refresh: ForceRefresh) => R;
|
|
30
|
+
type GetEffect<T extends State> = (this: T, current: T, refresh: ForceRefresh) => null;
|
|
31
|
+
/** Fetch instance of this class from context. */
|
|
32
|
+
function get<T extends State>(this: State.Extends<T>): T;
|
|
33
|
+
/** Fetch instance of this class optionally. */
|
|
34
|
+
function get<T extends State>(this: State.Extends<T>, required: false): T | undefined;
|
|
35
|
+
/** Fetch instance of this class from context. */
|
|
36
|
+
function get<T extends State>(this: State.Extends<T>, requireValues: true): Required<T>;
|
|
37
|
+
function get<T extends State, R>(this: State.Extends<T>, factory: GetFactory<T, Promise<R> | R>): NoVoid<R>;
|
|
38
|
+
function get<T extends State>(this: State.Extends<T>, factory: GetEffect<T>): null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/state.use.d.ts
|
|
43
|
+
declare module '@expressive/mvc' {
|
|
44
|
+
interface UseState extends State {
|
|
45
|
+
/**
|
|
46
|
+
* Optional hook called when State.use() is invoked within a React component.
|
|
47
|
+
*
|
|
48
|
+
* This is called *every render* of the component, and will intercept
|
|
49
|
+
* arguments which would otherwise be passed into the State constructor.
|
|
50
|
+
*
|
|
51
|
+
* @param props Arguments passed to State.use().
|
|
52
|
+
*/
|
|
53
|
+
use?(...props: any[]): Promise<void> | void;
|
|
54
|
+
}
|
|
55
|
+
namespace State {
|
|
56
|
+
type UseArgs<T extends State> = T extends {
|
|
57
|
+
use(...props: infer P): any;
|
|
58
|
+
} ? P : State.Args<T>;
|
|
59
|
+
/**
|
|
60
|
+
* Create and manage instance of this State within React component.
|
|
61
|
+
*
|
|
62
|
+
* @param args Arguments to pass to constructor or `use` method (if defined).
|
|
63
|
+
* @returns Managed instance of this State.
|
|
64
|
+
*/
|
|
65
|
+
function use<T extends UseState>(this: State.Type<T>, ...args: UseArgs<T>): T;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
//#endregion
|
|
69
|
+
//#region src/context.d.ts
|
|
70
|
+
declare namespace Consumer {
|
|
71
|
+
type Props<T extends State$2> = {
|
|
72
|
+
/** Type of controller to fetch from context. */for: State$2.Extends<T>;
|
|
73
|
+
/**
|
|
74
|
+
* Render function, will receive instance of desired controller.
|
|
75
|
+
*
|
|
76
|
+
* Called every render of parent component.
|
|
77
|
+
* Similar to `State.get()`, updates to properties accessed in
|
|
78
|
+
* this function will cause a refresh when they change.
|
|
79
|
+
*/
|
|
80
|
+
children: (value: T) => Component.Node | void;
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
declare function Consumer<T extends State$2>(props: Consumer.Props<T>): string | number | bigint | boolean | react.ReactElement<unknown, string | react.JSXElementConstructor<any>> | Iterable<react.ReactNode> | react.ReactPortal | null;
|
|
84
|
+
declare namespace Provider {
|
|
85
|
+
type ForEach<T> = (state: T) => void | (() => void);
|
|
86
|
+
interface SharedProps {
|
|
87
|
+
/**
|
|
88
|
+
* Children to render within this Provider.
|
|
89
|
+
*/
|
|
90
|
+
children?: Component.Node;
|
|
91
|
+
/** A fallback tree to show when suspended. */
|
|
92
|
+
fallback?: Component.Node;
|
|
93
|
+
/**
|
|
94
|
+
* A name for this Suspense boundary for instrumentation purposes.
|
|
95
|
+
* The name will help identify this boundary in React DevTools.
|
|
96
|
+
*/
|
|
97
|
+
name?: string | undefined;
|
|
98
|
+
}
|
|
99
|
+
type ForSingleProps<T extends State$2> = SharedProps & {
|
|
100
|
+
for: T | State$2.Type<T>;
|
|
101
|
+
is: (instance: T) => void;
|
|
102
|
+
} & { [K in State$2.Field<T>]?: T[K] };
|
|
103
|
+
type ForMultipleProps<T extends State$2> = SharedProps & {
|
|
104
|
+
for: Context.Accept<T>;
|
|
105
|
+
is?: ForEach<T>;
|
|
106
|
+
};
|
|
107
|
+
type Props<T extends State$2 = State$2> = ForSingleProps<T> | ForMultipleProps<T>;
|
|
108
|
+
}
|
|
109
|
+
declare function Provider<T extends State$2>(props: Provider.Props<T>): any;
|
|
110
|
+
//#endregion
|
|
111
|
+
//#region src/component.d.ts
|
|
112
|
+
declare module '@expressive/mvc' {
|
|
113
|
+
interface Component {
|
|
114
|
+
/** @deprecated Only to satisfy host JSX. Use `this.get(State)` instead. */
|
|
115
|
+
readonly context: Context;
|
|
116
|
+
/** @deprecated Only to satisfy host JSX. Use `this.get()` instead. */
|
|
117
|
+
readonly state: State.Values<this>;
|
|
118
|
+
/** @deprecated Only to satisfy host JSX. Use `this.set({})` instead. */
|
|
119
|
+
setState: (state: any, callback?: () => void) => void;
|
|
120
|
+
/** @deprecated Only to satisfy host JSX. Use `this.set(key)` instead. */
|
|
121
|
+
forceUpdate: (callback?: () => void) => void;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
//#endregion
|
|
125
|
+
//#region src/runtime.d.ts
|
|
126
|
+
declare const Runtime: {
|
|
127
|
+
/** Host own-property keys to trap out of observed state; assigned by each adapter. */ignore: string[];
|
|
128
|
+
createElement(type: any, props?: any, ...children: any[]): any;
|
|
129
|
+
createContext<T>(value: T): any;
|
|
130
|
+
useContext(context: any): any;
|
|
131
|
+
useState<S>(initial: S | (() => S)): [S, (next: (previous: S) => S) => void];
|
|
132
|
+
useEffect(effect: () => (() => void) | void, deps?: any[]): void;
|
|
133
|
+
useRef<T>(initial: T): {
|
|
134
|
+
current: T;
|
|
135
|
+
}; /** Per-render-attempt lifecycle, set by each adapter (React stacks attempts; others no-op). */
|
|
136
|
+
dedupe(from: Component, context: Context): {
|
|
137
|
+
commit(): void;
|
|
138
|
+
remove(): void;
|
|
139
|
+
}; /** Host error-boundary component, wrapping a Component whose `catch` is set. */
|
|
140
|
+
ErrorBoundary: unknown;
|
|
141
|
+
Suspense: any;
|
|
142
|
+
};
|
|
143
|
+
/** Subscribe to an existing observable instance within a component. */
|
|
144
|
+
declare function use<T extends object>(subject: T): T;
|
|
145
|
+
//#endregion
|
|
146
|
+
export { Consumer, Provider, Runtime, State$1 as State, use };
|
|
147
|
+
//# sourceMappingURL=adapter.d.ts.map
|
package/dist/adapter.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { Component, Context, State, State as State$1, event, observer, watch } from "@expressive/mvc";
|
|
2
|
+
|
|
3
|
+
//#region src/runtime.ts
|
|
4
|
+
const Runtime = {};
|
|
5
|
+
/**
|
|
6
|
+
* Mount-effect with a refreshable return value, safe under React StrictMode.
|
|
7
|
+
*
|
|
8
|
+
* @param callback Setup handler; receives a setter, must return a cleanup.
|
|
9
|
+
* @returns Latest value published via the setter (`undefined` until set).
|
|
10
|
+
*/
|
|
11
|
+
function useHook(callback) {
|
|
12
|
+
const { current } = Runtime.useRef({ rendered: 0 });
|
|
13
|
+
current.update = Runtime.useState(() => {
|
|
14
|
+
if (!current.rendered) current.unmount = callback((next) => {
|
|
15
|
+
current.output = next;
|
|
16
|
+
if (current.mounted) current.update?.((x) => x + 1);
|
|
17
|
+
else if (current.update) current.pending = true;
|
|
18
|
+
});
|
|
19
|
+
return current.rendered++;
|
|
20
|
+
})[1];
|
|
21
|
+
Runtime.useEffect(() => {
|
|
22
|
+
current.mounted = true;
|
|
23
|
+
if (current.pending) {
|
|
24
|
+
current.pending = false;
|
|
25
|
+
current.update((x) => x + 1);
|
|
26
|
+
}
|
|
27
|
+
return () => {
|
|
28
|
+
if (--current.rendered < 1) current.unmount();
|
|
29
|
+
};
|
|
30
|
+
}, []);
|
|
31
|
+
return current.output;
|
|
32
|
+
}
|
|
33
|
+
/** Subscribe to an existing observable instance within a component. */
|
|
34
|
+
function use(subject) {
|
|
35
|
+
const { current } = Runtime.useRef({
|
|
36
|
+
mounted: 0,
|
|
37
|
+
proxy: subject
|
|
38
|
+
});
|
|
39
|
+
const update = Runtime.useState(() => current.mounted++)[1];
|
|
40
|
+
if (current.source !== subject) {
|
|
41
|
+
const status = observer(subject);
|
|
42
|
+
if (status === void 0) throw new Error("Provided object is not observable.");
|
|
43
|
+
current.unwatch?.();
|
|
44
|
+
current.source = subject;
|
|
45
|
+
if (status === null) {
|
|
46
|
+
current.unwatch = void 0;
|
|
47
|
+
current.proxy = subject;
|
|
48
|
+
} else {
|
|
49
|
+
if (!status.ready) event(subject);
|
|
50
|
+
let init = true;
|
|
51
|
+
current.unwatch = watch(subject, (next, changed) => {
|
|
52
|
+
current.proxy = next;
|
|
53
|
+
if (changed.length && !init) update((x) => x + 1);
|
|
54
|
+
});
|
|
55
|
+
init = false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
Runtime.useEffect(() => () => {
|
|
59
|
+
if (--current.mounted < 1) current.unwatch?.();
|
|
60
|
+
}, []);
|
|
61
|
+
return current.proxy;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region src/context.ts
|
|
66
|
+
let shared;
|
|
67
|
+
/**
|
|
68
|
+
* Lazily-created context carrying the active {@link Context} down the tree.
|
|
69
|
+
* Lazy because the framework's `createContext` arrives via {@link Runtime},
|
|
70
|
+
* which an adapter's entry populates at load - after this module evaluates.
|
|
71
|
+
*/
|
|
72
|
+
function Layers() {
|
|
73
|
+
return shared || (shared = Runtime.createContext(Context.root));
|
|
74
|
+
}
|
|
75
|
+
/** Read the ambient {@link Context} from the nearest Layers provider. */
|
|
76
|
+
function useAmbient() {
|
|
77
|
+
return Runtime.useContext(Layers());
|
|
78
|
+
}
|
|
79
|
+
/** Wrap `children` in a {@link Layers} provider carrying `context` down the tree. */
|
|
80
|
+
function provide(context, children) {
|
|
81
|
+
return Runtime.createElement(Layers().Provider, {
|
|
82
|
+
value: context,
|
|
83
|
+
children
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
Object.defineProperty(Component, "contextType", {
|
|
87
|
+
configurable: true,
|
|
88
|
+
get: Layers
|
|
89
|
+
});
|
|
90
|
+
const _get = Context.get;
|
|
91
|
+
Context.get = (state) => {
|
|
92
|
+
if (!state) try {
|
|
93
|
+
return useAmbient();
|
|
94
|
+
} catch {}
|
|
95
|
+
return _get(state);
|
|
96
|
+
};
|
|
97
|
+
function Consumer(props) {
|
|
98
|
+
return props.for.get((i) => props.children(i));
|
|
99
|
+
}
|
|
100
|
+
function Provider(props) {
|
|
101
|
+
const { for: input, children, fallback, name, is, ...rest } = props;
|
|
102
|
+
const ambient = useAmbient();
|
|
103
|
+
const context = useHook((set) => {
|
|
104
|
+
set(new Context(ambient));
|
|
105
|
+
return () => context.pop();
|
|
106
|
+
});
|
|
107
|
+
context.set(input, is);
|
|
108
|
+
if (Object.keys(rest).length) {
|
|
109
|
+
const i = State$1.is(input) ? context.get(input) : input;
|
|
110
|
+
if (i instanceof State$1) i.set(rest);
|
|
111
|
+
}
|
|
112
|
+
return provide(context, fallback !== void 0 ? Runtime.createElement(Runtime.Suspense, {
|
|
113
|
+
fallback,
|
|
114
|
+
name
|
|
115
|
+
}, children) : children);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
//#endregion
|
|
119
|
+
export { Consumer, Provider, Runtime, State, use };
|
|
120
|
+
//# sourceMappingURL=adapter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter.js","names":["State"],"sources":["../src/runtime.ts","../src/context.ts"],"sourcesContent":["import { event, watch, observer } from '@expressive/mvc';\nimport type { Component } from '@expressive/mvc';\nimport type { Context } from './context';\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 /** 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\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\nexport function useReady<T>(callback: () => void) {\n return Runtime.useEffect(() => void callback(), []);\n}\n\n/**\n * Mount-effect with a refreshable return value, safe under React StrictMode.\n *\n * @param callback Setup handler; receives a setter, must return a cleanup.\n * @returns Latest value published via the setter (`undefined` until set).\n */\nexport function useHook<T = void>(\n callback: (refresh: (next: T) => void) => () => void\n) {\n const { current } = Runtime.useRef(\n { rendered: 0 } as {\n rendered: number;\n mounted?: boolean;\n pending?: boolean;\n unmount: () => void;\n update?: (next: (previous: number) => number) => void;\n output: T;\n }\n );\n\n current.update = Runtime.useState(() => {\n if (!current.rendered)\n current.unmount = callback((next) => {\n current.output = next;\n if (current.mounted) current.update?.((x) => x + 1);\n else if (current.update) current.pending = true;\n });\n\n return current.rendered++;\n })[1];\n\n Runtime.useEffect(() => {\n current.mounted = true;\n if (current.pending) {\n current.pending = false;\n current.update!((x) => x + 1);\n }\n return () => {\n if (--current.rendered < 1) current.unmount();\n }\n }, []);\n\n return current.output;\n}\n\n/** Subscribe to an existing observable instance within a component. */\nexport function use<T extends object>(subject: T) {\n const { current } = Runtime.useRef<{\n proxy: T;\n source?: T;\n mounted: number;\n unwatch?: () => void;\n }>({ mounted: 0, proxy: subject });\n\n const update = Runtime.useState(() => current.mounted++)[1];\n\n if (current.source !== subject) {\n const status = observer(subject);\n\n if (status === undefined)\n throw new Error('Provided object is not observable.');\n\n current.unwatch?.();\n current.source = subject;\n\n if (status === null) {\n current.unwatch = undefined;\n current.proxy = subject;\n } else {\n if (!status.ready) event(subject);\n\n let init = true;\n\n current.unwatch = watch(subject, (next, changed) => {\n current.proxy = next;\n if (changed.length && !init)\n update((x) => x + 1);\n });\n\n init = false;\n }\n }\n\n Runtime.useEffect(() => () => {\n if (--current.mounted < 1) current.unwatch?.();\n }, []);\n\n return current.proxy;\n}\n","import { State, Context, Component } 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 provide(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 type ForEach<T> = (state: T) => void | (() => 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.Field<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\nfunction Provider<T extends State>(props: Provider.Props<T>) {\n const {\n for: input,\n children,\n fallback,\n name,\n is,\n ...rest\n } = props as Provider.ForSingleProps<T> & Provider.ForMultipleProps<T>;\n\n const ambient = useAmbient();\n const context = useHook<Context>((set) => {\n set(new Context(ambient));\n return () => context.pop();\n });\n\n context.set(input, is);\n\n if (Object.keys(rest).length) {\n const i = State.is(input) ? context.get(input) : input;\n if (i instanceof State) i.set(rest);\n }\n\n return provide(context,\n fallback !== undefined\n ? Runtime.createElement(Runtime.Suspense, { fallback, name }, children)\n : children\n );\n}\n\nexport { Consumer, Provider, Context,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
|
4
|
-
import { State, State as State$1 } from "./state";
|
|
5
|
-
import { Context, Context as Context$2, Observable, State as State$2, def, get, hot, ref, set } from "@expressive/state";
|
|
1
|
+
import { Component, Context, Observer, def, get, hot, ref, set } from "@expressive/mvc";
|
|
2
|
+
import { JSX, ReactNode } from "react";
|
|
3
|
+
import { Consumer, Provider, State, State as adapter_default, use } from "./adapter";
|
|
6
4
|
|
|
7
|
-
//#region src/
|
|
8
|
-
declare
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
* Render function, will receive instance of desired controller.
|
|
13
|
-
*
|
|
14
|
-
* Called every render of parent component.
|
|
15
|
-
* Similar to `State.get()`, updates to properties accessed in
|
|
16
|
-
* this function will cause a refresh when they change.
|
|
17
|
-
*/
|
|
18
|
-
children: (value: T) => ReactNode | void;
|
|
19
|
-
};
|
|
20
|
-
}
|
|
21
|
-
declare function Consumer<T extends State$2>(props: Consumer.Props<T>): string | number | bigint | boolean | react.ReactElement<unknown, string | react.JSXElementConstructor<any>> | Iterable<ReactNode> | react.ReactPortal | null;
|
|
22
|
-
declare namespace Provider {
|
|
23
|
-
type ForEach<T> = (state: T) => void | (() => void);
|
|
24
|
-
interface SharedProps {
|
|
25
|
-
/**
|
|
26
|
-
* Children to render within this Provider.
|
|
27
|
-
*/
|
|
28
|
-
children?: ReactNode;
|
|
29
|
-
/** A fallback tree to show when suspended. */
|
|
30
|
-
fallback?: ReactNode;
|
|
31
|
-
/**
|
|
32
|
-
* A name for this Suspense boundary for instrumentation purposes.
|
|
33
|
-
* The name will help identify this boundary in React DevTools.
|
|
34
|
-
*/
|
|
35
|
-
name?: string | undefined;
|
|
36
|
-
}
|
|
37
|
-
type ForSingleProps<T extends State$2> = SharedProps & {
|
|
38
|
-
for: T | State$2.Type<T>;
|
|
39
|
-
is: (instance: T) => void;
|
|
40
|
-
} & { [K in State$2.Field<T>]?: T[K] };
|
|
41
|
-
type ForMultipleProps<T extends State$2> = SharedProps & {
|
|
42
|
-
for: Context$2.Accept<T>;
|
|
43
|
-
is?: ForEach<T>;
|
|
44
|
-
};
|
|
45
|
-
type Props<T extends State$2 = State$2> = ForSingleProps<T> | ForMultipleProps<T>;
|
|
46
|
-
}
|
|
47
|
-
declare function Provider<T extends State$2>(props: Provider.Props<T>): react.FunctionComponentElement<react.ProviderProps<Context$2>>;
|
|
48
|
-
//#endregion
|
|
49
|
-
//#region src/component.d.ts
|
|
50
|
-
type StateProps<T extends State$1> = { [K in Exclude<keyof T, keyof Component>]?: T[K] };
|
|
51
|
-
type RenderProps<T> = T extends {
|
|
52
|
-
render(props: infer P): any;
|
|
53
|
-
} ? {} extends P ? {
|
|
54
|
-
children?: React.ReactNode;
|
|
55
|
-
} : P : {
|
|
56
|
-
children?: React.ReactNode;
|
|
57
|
-
};
|
|
58
|
-
interface ComponentProps<T extends Component> {
|
|
59
|
-
/** Callback for newly created instance. Only called once. */
|
|
60
|
-
is?: (instance: T) => void;
|
|
61
|
-
/** Fallback to show when suspended or in error recovery. */
|
|
62
|
-
fallback?: React.ReactNode;
|
|
63
|
-
}
|
|
64
|
-
type Props<T extends Component> = StateProps<T> & ComponentProps<T> & RenderProps<T>;
|
|
65
|
-
declare module '@expressive/state' {
|
|
66
|
-
namespace State {
|
|
67
|
-
export type { Component, Props };
|
|
5
|
+
//#region src/jsx-runtime.d.ts
|
|
6
|
+
declare module '@expressive/mvc/jsx-runtime' {
|
|
7
|
+
interface Host {
|
|
8
|
+
node: ReactNode;
|
|
9
|
+
intrinsics: JSX.IntrinsicElements;
|
|
68
10
|
}
|
|
69
11
|
}
|
|
70
|
-
declare class Component extends State$1 {
|
|
71
|
-
static contextType: React.Context<Context$2>;
|
|
72
|
-
/**
|
|
73
|
-
* All JSX attributes passed to this component.
|
|
74
|
-
* Includes state-derived props, render props, and built-in props like `is` and `fallback`.
|
|
75
|
-
*
|
|
76
|
-
* Will incorperate extra props you declare as props parameter in `render` method.
|
|
77
|
-
*/
|
|
78
|
-
readonly props: Props<this>;
|
|
79
|
-
/** @deprecated Only to satisfy React JSX. Use `this.get(State)` instead. */
|
|
80
|
-
readonly context: Context$2;
|
|
81
|
-
/** @deprecated Only to satisfy React JSX. Use `this.get()` instead. */
|
|
82
|
-
readonly state: State$1.Values<this>;
|
|
83
|
-
/** @deprecated Only to satisfy React JSX. Not implemented. */
|
|
84
|
-
setState: (state: any, callback?: () => void) => void;
|
|
85
|
-
/** @deprecated Only to satisfy React JSX. Not implemented. */
|
|
86
|
-
forceUpdate: (callback?: () => void) => void;
|
|
87
|
-
/**
|
|
88
|
-
* Content to display while this component or its children are suspended.
|
|
89
|
-
* Will cover suspense by pending properties in `this.render` as well.
|
|
90
|
-
* Can be set as a class property or overridden via the `fallback` JSX prop.
|
|
91
|
-
*
|
|
92
|
-
* Defaults to null - nothing will be rendered.
|
|
93
|
-
*/
|
|
94
|
-
fallback: React.ReactNode;
|
|
95
|
-
constructor(nextProps: any, ...rest: any[]);
|
|
96
|
-
/**
|
|
97
|
-
* Output for this component. Override to define custom JSX.
|
|
98
|
-
*
|
|
99
|
-
* Properties accessed via `this` are reactive and will trigger a render when , in addition to props.
|
|
100
|
-
*
|
|
101
|
-
* Accepts optional parameter to receive extra props
|
|
102
|
-
* from JSX, beyond those merged to state properties.
|
|
103
|
-
*
|
|
104
|
-
* To declare extra props use `props = {} as { ... }` with expected shape.
|
|
105
|
-
* A default is required to satisfy TypeScript but safely ignored.
|
|
106
|
-
*
|
|
107
|
-
* ```ts
|
|
108
|
-
* render(props = {} as { label: string }) {
|
|
109
|
-
* return <span>{props.label}</span>;
|
|
110
|
-
* }
|
|
111
|
-
* ```
|
|
112
|
-
* Usable as:
|
|
113
|
-
* ```tsx
|
|
114
|
-
* <MyComponent label="Hello" />
|
|
115
|
-
* ```
|
|
116
|
-
*
|
|
117
|
-
* These must be compatible with State-derived properties, or be unused.
|
|
118
|
-
* Props you declare as not-optional will be required by the JSX element.
|
|
119
|
-
*
|
|
120
|
-
* Without a parameter, children are accepted by default and passed through provider.
|
|
121
|
-
*/
|
|
122
|
-
render(props?: {}): React.ReactNode;
|
|
123
|
-
/**
|
|
124
|
-
* Called when a child component throws during render.
|
|
125
|
-
* While this is pending, `fallback` is displayed.
|
|
126
|
-
* When resolved, the error boundary resets and `render` is called again.
|
|
127
|
-
*
|
|
128
|
-
* Override to handle errors - set `this.fallback` for error-specific UI,
|
|
129
|
-
* await async recovery, or await user interaction before retrying. If you
|
|
130
|
-
* assign a fallback within catch, it will be reverted after resolved.
|
|
131
|
-
*/
|
|
132
|
-
catch?(error: Error): Promise<void> | void;
|
|
133
|
-
}
|
|
134
12
|
//#endregion
|
|
135
|
-
export { Component, Consumer, Context,
|
|
13
|
+
export { Component, Consumer, Context, Observer, Provider, State, def, adapter_default as default, get, hot, ref, set, use };
|
|
136
14
|
//# sourceMappingURL=index.d.ts.map
|