@expressive/react 0.76.0 → 0.78.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expressive/react",
3
- "version": "0.76.0",
3
+ "version": "0.78.0",
4
4
  "description": "Use classes to define state in React!",
5
5
  "keywords": [
6
6
  "expressive",
@@ -15,47 +15,52 @@
15
15
  },
16
16
  "repository": {
17
17
  "type": "git",
18
- "url": "git+https://github.com/gabeklein/expressive-state.git"
18
+ "url": "git+https://github.com/gabeklein/expressive-mvc.git"
19
19
  },
20
20
  "files": [
21
21
  "dist"
22
22
  ],
23
23
  "type": "module",
24
+ "sideEffects": [
25
+ "./dist/index.js",
26
+ "./dist/runtime.js",
27
+ "./dist/component.js",
28
+ "./dist/state.get.js",
29
+ "./dist/state.use.js",
30
+ "./src/jsx-runtime.ts"
31
+ ],
24
32
  "main": "dist/index.js",
25
33
  "types": "dist/index.d.ts",
26
34
  "exports": {
27
35
  ".": {
28
36
  "types": "./dist/index.d.ts",
29
- "require": "./dist/index.js",
30
- "import": "./dist/esm/index.js"
37
+ "default": "./dist/index.js"
31
38
  },
32
- "./state": {
33
- "types": "./dist/state.d.ts",
34
- "require": "./dist/state.js",
35
- "import": "./dist/esm/state.js"
39
+ "./runtime": {
40
+ "types": "./dist/runtime.d.ts",
41
+ "default": "./dist/runtime.js"
36
42
  }
37
43
  },
44
+ "engines": {
45
+ "node": ">=20"
46
+ },
38
47
  "publishConfig": {
39
48
  "access": "public"
40
49
  },
41
50
  "scripts": {
42
51
  "build": "tsdown",
43
- "test": "tsc --noEmit && vitest run --coverage",
44
- "preversion": "npm run test && npm run build"
52
+ "test": "tsc --noEmit && bun test --coverage --only-failures"
45
53
  },
46
54
  "dependencies": {
47
- "@expressive/state": "^0.76.0"
55
+ "@expressive/mvc": "^0.78.0"
48
56
  },
49
57
  "devDependencies": {
50
58
  "@testing-library/react": "^16.3.0",
51
59
  "@types/react": "^19",
52
60
  "@types/react-dom": "^19",
53
- "@vitest/browser": "^4.0.18",
54
61
  "react": "^19",
55
62
  "react-dom": "^19",
56
- "tsdown": "^0.20.1",
57
- "tsup": "^8.0.2",
58
- "vitest": "^4.0.18"
63
+ "tsdown": "^0.20.1"
59
64
  },
60
65
  "peerDependencies": {
61
66
  "react": ">=16.8.0 <20.0.0"
@@ -64,6 +69,5 @@
64
69
  "react": {
65
70
  "optional": true
66
71
  }
67
- },
68
- "gitHead": "cba88d572c670c823cf270dd5eab16b02b1f4f37"
72
+ }
69
73
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Gabe Klein
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1,195 +0,0 @@
1
- import { Context as Context$1, Layers } from "./context.js";
2
- import React, { Suspense, createElement, useEffect, useRef } from "react";
3
- import { State, useMount } from "./state";
4
- import { set, unbind, watch } from "@expressive/state";
5
-
6
- //#region src/component.ts
7
- const PENDING = /* @__PURE__ */ new WeakMap();
8
- const INTERNAL = [
9
- "updater",
10
- "refs",
11
- "_reactInternals",
12
- "_reactInternalInstance"
13
- ];
14
- var Component = class extends State {
15
- static {
16
- this.contextType = Layers;
17
- }
18
- constructor(nextProps, ...rest) {
19
- const { is, ...props } = nextProps;
20
- rest = rest.filter((x) => !(x instanceof Context$1));
21
- super(props, rest, is && ((x) => void is(x)), () => {
22
- Object.defineProperty(this, "props", { enumerable: false });
23
- });
24
- this.fallback = set(null);
25
- const existing = PENDING.get(nextProps);
26
- if (existing) return existing;
27
- PENDING.set(nextProps, this);
28
- for (const key of INTERNAL) Object.defineProperty(this, key, {
29
- configurable: true,
30
- writable: true
31
- });
32
- this.props = nextProps;
33
- this.set("props", () => {
34
- this.set(this.props);
35
- });
36
- }
37
- /**
38
- * Output for this component. Override to define custom JSX.
39
- *
40
- * Properties accessed via `this` are reactive and will trigger a render when , in addition to props.
41
- *
42
- * Accepts optional parameter to receive extra props
43
- * from JSX, beyond those merged to state properties.
44
- *
45
- * To declare extra props use `props = {} as { ... }` with expected shape.
46
- * A default is required to satisfy TypeScript but safely ignored.
47
- *
48
- * ```ts
49
- * render(props = {} as { label: string }) {
50
- * return <span>{props.label}</span>;
51
- * }
52
- * ```
53
- * Usable as:
54
- * ```tsx
55
- * <MyComponent label="Hello" />
56
- * ```
57
- *
58
- * These must be compatible with State-derived properties, or be unused.
59
- * Props you declare as not-optional will be required by the JSX element.
60
- *
61
- * Without a parameter, children are accepted by default and passed through provider.
62
- */
63
- render(props) {
64
- return this.props.children || null;
65
- }
66
- };
67
- Object.defineProperties(Component.prototype, {
68
- isReactComponent: { get: () => true },
69
- state: {
70
- get() {
71
- return this.get();
72
- },
73
- set() {}
74
- },
75
- context: {
76
- configurable: true,
77
- set: bootstrap
78
- }
79
- });
80
- function bootstrap(context) {
81
- const self = this.is;
82
- const render = unbind(this.render);
83
- context = context.push(self);
84
- let ready = false;
85
- let active;
86
- function Render() {
87
- return render.call(active, self.props);
88
- }
89
- function AsComponent() {
90
- useMount((refresh) => {
91
- watch(self, (current) => {
92
- active = current;
93
- if (ready) refresh();
94
- });
95
- return () => {
96
- self.set(null);
97
- context.pop();
98
- };
99
- });
100
- useEffect(() => {
101
- ready = true;
102
- }, []);
103
- const children = createElement(Layers.Provider, {
104
- value: context,
105
- children: createElement(Suspense, {
106
- fallback: active.fallback,
107
- name: String(self)
108
- }, createElement(Render))
109
- });
110
- return active.catch ? createElement(ErrorBoundary, {
111
- self,
112
- children
113
- }) : children;
114
- }
115
- Object.defineProperties(self, {
116
- context: {
117
- get: () => context,
118
- set() {}
119
- },
120
- render: { value: () => createElement(AsComponent) }
121
- });
122
- }
123
- var ErrorBoundary = class extends React.Component {
124
- constructor(..._args) {
125
- super(..._args);
126
- this.state = {};
127
- this.recovering = false;
128
- }
129
- static getDerivedStateFromError(error) {
130
- return { error };
131
- }
132
- componentDidCatch(error) {
133
- const { self } = this.props;
134
- const { fallback } = self;
135
- const reset = (error) => {
136
- this.recovering = true;
137
- this.setState({ error });
138
- };
139
- Promise.resolve(self.catch(error)).then(() => reset(), reset).finally(() => self.set({ fallback }, true));
140
- }
141
- componentDidUpdate() {
142
- this.recovering = false;
143
- }
144
- render() {
145
- if (!this.state.error) return this.props.children;
146
- if (this.recovering) throw this.state.error;
147
- return this.props.self.fallback;
148
- }
149
- };
150
- const SEEN = /* @__PURE__ */ new WeakSet();
151
- function subcomponents(proto) {
152
- for (const key of Object.getOwnPropertyNames(proto)) {
153
- if (!/^[A-Z]/.test(key)) continue;
154
- const { get, value } = Object.getOwnPropertyDescriptor(proto, key);
155
- if (!get && typeof value !== "function") continue;
156
- Object.defineProperty(proto, key, {
157
- configurable: true,
158
- get() {
159
- const self = this.is;
160
- let render = unbind(get ? get.call(this) : value);
161
- function Sub(props) {
162
- const ref = useRef(null);
163
- useMount((refresh) => watch(self, (current) => {
164
- ref.current = current;
165
- refresh();
166
- }));
167
- return render.call(ref.current, props);
168
- }
169
- Object.defineProperty(self, key, {
170
- configurable: true,
171
- get: () => Sub,
172
- set(fn) {
173
- render = fn;
174
- }
175
- });
176
- return Sub;
177
- }
178
- });
179
- }
180
- }
181
- Component.on((self) => {
182
- let Type = self.constructor;
183
- while (Type !== Component) {
184
- const proto = Type.prototype;
185
- if (SEEN.has(Type)) break;
186
- SEEN.add(Type);
187
- subcomponents(proto);
188
- Type = Object.getPrototypeOf(Type);
189
- }
190
- subcomponents(self);
191
- });
192
-
193
- //#endregion
194
- export { Component };
195
- //# sourceMappingURL=component.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"component.js","names":["Context"],"sources":["../../src/component.ts"],"sourcesContent":["import { watch, unbind, set } from '@expressive/state';\nimport React, {\n createElement,\n Suspense,\n useEffect,\n useRef,\n type ReactNode\n} from 'react';\nimport { Context, Layers } from './context';\nimport { State, useMount } from './state';\n\nconst PENDING = new WeakMap<object, Component>();\nconst INTERNAL = [\n 'updater',\n 'refs',\n '_reactInternals',\n '_reactInternalInstance'\n];\n\nexport type StateProps<T extends State> = {\n [K in Exclude<keyof T, keyof Component>]?: T[K];\n};\n\ntype RenderProps<T> = T extends { render(props: infer P): any }\n ? {} extends P\n ? { children?: ReactNode }\n : P\n : { children?: ReactNode };\n\ninterface ComponentProps<T extends Component> {\n /** Callback for newly created instance. Only called once. */\n is?: (instance: T) => void;\n\n /** Fallback to show when suspended or in error recovery. */\n fallback?: ReactNode;\n}\n\nexport type Props<T extends Component> = StateProps<T> &\n ComponentProps<T> &\n RenderProps<T>;\n\ndeclare module '@expressive/state' {\n namespace State {\n export type { Component, Props };\n }\n}\n\nclass Component extends State {\n static contextType = Layers;\n\n /**\n * All JSX attributes passed to this component.\n * Includes state-derived props, render props, and built-in props like `is` and `fallback`.\n *\n * Will incorperate extra props you declare as props parameter in `render` method.\n */\n declare readonly props: Props<this>;\n\n /** @deprecated Only to satisfy React JSX. Use `this.get(State)` instead. */\n declare readonly context: Context;\n /** @deprecated Only to satisfy React JSX. Use `this.get()` instead. */\n declare readonly state: State.Values<this>;\n /** @deprecated Only to satisfy React JSX. Not implemented. */\n declare setState: (state: any, callback?: () => void) => void;\n /** @deprecated Only to satisfy React JSX. Not implemented. */\n declare forceUpdate: (callback?: () => void) => void;\n\n /**\n * Content to display while this component or its children are suspended.\n * Will cover suspense by pending properties in `this.render` as well.\n * Can be set as a class property or overridden via the `fallback` JSX prop.\n *\n * Defaults to null - nothing will be rendered.\n */\n fallback: ReactNode = set(null);\n\n constructor(nextProps: any, ...rest: any[]) {\n const { is, ...props } = nextProps;\n rest = rest.filter((x) => !(x instanceof Context));\n super(props, rest, is && ((x) => void is(x)), () => {\n Object.defineProperty(this, 'props', { enumerable: false });\n });\n\n const existing = PENDING.get(nextProps);\n if (existing) return existing;\n PENDING.set(nextProps, this);\n\n for (const key of INTERNAL)\n Object.defineProperty(this, key, { configurable: true, writable: true });\n\n this.props = nextProps;\n this.set('props', () => {\n this.set(this.props as {});\n });\n }\n\n /**\n * Output for this component. Override to define custom JSX.\n *\n * Properties accessed via `this` are reactive and will trigger a render when , in addition to props.\n *\n * Accepts optional parameter to receive extra props\n * from JSX, beyond those merged to state properties.\n *\n * To declare extra props use `props = {} as { ... }` with expected shape.\n * A default is required to satisfy TypeScript but safely ignored.\n *\n * ```ts\n * render(props = {} as { label: string }) {\n * return <span>{props.label}</span>;\n * }\n * ```\n * Usable as:\n * ```tsx\n * <MyComponent label=\"Hello\" />\n * ```\n *\n * These must be compatible with State-derived properties, or be unused.\n * Props you declare as not-optional will be required by the JSX element.\n *\n * Without a parameter, children are accepted by default and passed through provider.\n */\n render(props?: {}): ReactNode {\n return this.props.children || null;\n }\n\n /**\n * Called when a child component throws during render.\n * While this is pending, `fallback` is displayed.\n * When resolved, the error boundary resets and `render` is called again.\n *\n * Override to handle errors - set `this.fallback` for error-specific UI,\n * await async recovery, or await user interaction before retrying. If you\n * assign a fallback within catch, it will be reverted after resolved.\n */\n catch?(error: Error): Promise<void> | void;\n}\n\nObject.defineProperties(Component.prototype, {\n isReactComponent: {\n get: () => true\n },\n state: {\n get(this: Component) {\n return this.get();\n },\n set() {}\n },\n context: {\n configurable: true,\n set: bootstrap\n }\n});\n\nfunction bootstrap(this: Component, context: Context) {\n const self = this.is;\n const render = unbind(this.render);\n\n context = context.push(self);\n\n let ready = false;\n let active: Component;\n\n function Render() {\n return render.call(active, self.props);\n }\n\n function AsComponent() {\n useMount((refresh) => {\n watch(self, (current) => {\n active = current;\n if (ready) refresh();\n });\n\n return () => {\n self.set(null);\n context.pop();\n };\n });\n\n useEffect(() => {\n ready = true;\n }, []);\n\n const children = createElement(Layers.Provider, {\n value: context,\n children: createElement(\n Suspense,\n { fallback: active.fallback, name: String(self) },\n createElement(Render)\n )\n });\n\n return active.catch\n ? createElement(ErrorBoundary, { self, children })\n : children;\n }\n\n Object.defineProperties(self, {\n context: {\n get: () => context,\n set() {}\n },\n render: {\n value: () => createElement(AsComponent)\n }\n });\n}\n\ninterface BoundaryProps {\n self: Component;\n children: ReactNode;\n}\n\nclass ErrorBoundary extends React.Component<BoundaryProps> {\n state = {} as { error?: Error };\n recovering = false;\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!(error))\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\nconst SEEN = new WeakSet<Function>();\n\nfunction subcomponents(proto: State) {\n for (const key of Object.getOwnPropertyNames(proto)) {\n if (!/^[A-Z]/.test(key)) continue;\n\n const { get, value } = Object.getOwnPropertyDescriptor(proto, key)!;\n\n if (!get && typeof value !== 'function') continue;\n\n Object.defineProperty(proto, key, {\n configurable: true,\n get(this: Component) {\n const self = this.is;\n\n let render = unbind(get ? get.call(this) : value);\n\n function Sub(props: any) {\n const ref = useRef<State>(null);\n\n useMount((refresh) =>\n watch(self, (current) => {\n ref.current = current;\n refresh();\n })\n );\n\n return render.call(ref.current, props);\n }\n\n Object.defineProperty(self, key, {\n configurable: true,\n get: () => Sub,\n set(fn: Function) {\n render = fn;\n }\n });\n\n return Sub;\n }\n });\n }\n}\n\nComponent.on((self) => {\n let Type = self.constructor as State.Extends;\n\n while (Type !== Component) {\n const proto = Type.prototype as any;\n\n if (SEEN.has(Type)) break;\n SEEN.add(Type);\n subcomponents(proto);\n Type = Object.getPrototypeOf(Type);\n }\n\n subcomponents(self);\n});\n\nexport { Component };\n"],"mappings":";;;;;;AAWA,MAAM,0BAAU,IAAI,SAA4B;AAChD,MAAM,WAAW;CACf;CACA;CACA;CACA;CACD;AA8BD,IAAM,YAAN,cAAwB,MAAM;;qBACP;;CA4BrB,YAAY,WAAgB,GAAG,MAAa;EAC1C,MAAM,EAAE,IAAI,GAAG,UAAU;AACzB,SAAO,KAAK,QAAQ,MAAM,EAAE,aAAaA,WAAS;AAClD,QAAM,OAAO,MAAM,QAAQ,MAAM,KAAK,GAAG,EAAE,SAAS;AAClD,UAAO,eAAe,MAAM,SAAS,EAAE,YAAY,OAAO,CAAC;IAC3D;kBAPkB,IAAI,KAAK;EAS7B,MAAM,WAAW,QAAQ,IAAI,UAAU;AACvC,MAAI,SAAU,QAAO;AACrB,UAAQ,IAAI,WAAW,KAAK;AAE5B,OAAK,MAAM,OAAO,SAChB,QAAO,eAAe,MAAM,KAAK;GAAE,cAAc;GAAM,UAAU;GAAM,CAAC;AAE1E,OAAK,QAAQ;AACb,OAAK,IAAI,eAAe;AACtB,QAAK,IAAI,KAAK,MAAY;IAC1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BJ,OAAO,OAAuB;AAC5B,SAAO,KAAK,MAAM,YAAY;;;AAelC,OAAO,iBAAiB,UAAU,WAAW;CAC3C,kBAAkB,EAChB,W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M,CAC1B,cAAc,KAAK,IAAI,EAAE,UAAU,EAAE,KAAK,CAAC;;CAGhD,qBAAqB;AACnB,OAAK,aAAa;;CAGpB,SAAS;AACP,MAAI,CAAC,KAAK,MAAM,MAAO,QAAO,KAAK,MAAM;AACzC,MAAI,KAAK,WAAY,OAAM,KAAK,MAAM;AACtC,SAAO,KAAK,MAAM,KAAK;;;AAI3B,MAAM,uBAAO,IAAI,SAAmB;AAEpC,SAAS,cAAc,OAAc;AACnC,MAAK,MAAM,OAAO,OAAO,oBAAoB,MAAM,EAAE;AACnD,MAAI,CAAC,SAAS,KAAK,IAAI,CAAE;EAEzB,MAAM,EAAE,KAAK,UAAU,OAAO,yBAAyB,OAAO,IAAI;AAElE,MAAI,CAAC,OAAO,OAAO,UAAU,WAAY;AAEzC,SAAO,eAAe,OAAO,KAAK;GAChC,cAAc;GACd,MAAqB;IACnB,MAAM,OAAO,KAAK;IAElB,IAAI,SAAS,OAAO,MAAM,IAAI,KAAK,KAAK,GAAG,MAAM;IAEjD,SAAS,IAAI,OAAY;KACvB,MAAM,MAAM,OAAc,KAAK;AAE/B,eAAU,YACR,MAAM,OAAO,YAAY;AACvB,UAAI,UAAU;AACd,eAAS;OACT,CACH;AAED,YAAO,OAAO,KAAK,IAAI,SAAS,MAAM;;AAGxC,WAAO,eAAe,MAAM,KAAK;KAC/B,cAAc;KACd,WAAW;KACX,IAAI,IAAc;AAChB,eAAS;;KAEZ,CAAC;AAEF,WAAO;;GAEV,CAAC;;;AAIN,UAAU,IAAI,SAAS;CACrB,IAAI,OAAO,KAAK;AAEhB,QAAO,SAAS,WAAW;EACzB,MAAM,QAAQ,KAAK;AAEnB,MAAI,KAAK,IAAI,KAAK,CAAE;AACpB,OAAK,IAAI,KAAK;AACd,gBAAc,MAAM;AACpB,SAAO,OAAO,eAAe,KAAK;;AAGpC,eAAc,KAAK;EACnB"}
@@ -1,40 +0,0 @@
1
- import { Suspense, createContext, createElement, useContext, useRef } from "react";
2
- import { useMount } from "./state";
3
- import { Context as Context$1, State as State$1 } from "@expressive/state";
4
-
5
- //#region src/context.ts
6
- const Layers = createContext(Context$1.root);
7
- const _get = Context$1.get;
8
- Context$1.get = (state) => {
9
- if (!state) try {
10
- return useContext(Layers);
11
- } catch {}
12
- return _get(state);
13
- };
14
- function Consumer(props) {
15
- return props.for.get((i) => props.children(i));
16
- }
17
- function Provider(props) {
18
- const ambient = useContext(Layers);
19
- const ref = useRef(null);
20
- const context = ref.current || (ref.current = new Context$1(ambient));
21
- let { for: input, children, fallback, name, ...rest } = props;
22
- context.set(input, (added) => rest.is?.(added));
23
- if (Object.keys(rest).length) {
24
- if (State$1.is(input)) input = context.get(input);
25
- if (input instanceof State$1) input.set(rest);
26
- }
27
- useMount(() => () => context.pop());
28
- if (fallback !== void 0) children = createElement(Suspense, {
29
- fallback,
30
- name
31
- }, children);
32
- return createElement(Layers.Provider, {
33
- value: context,
34
- children
35
- });
36
- }
37
-
38
- //#endregion
39
- export { Consumer, Context$1 as Context, Layers, Provider };
40
- //# sourceMappingURL=context.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"context.js","names":["Context","State"],"sources":["../../src/context.ts"],"sourcesContent":["import { State, Context } from \"@expressive/state\";\nimport { createContext, createElement, ReactNode, Suspense, useContext, useRef } from \"react\";\nimport { useMount } from \"./state\";\n\nconst Layers = createContext(Context.root);\n\nconst _get = Context.get;\n\nContext.get = (state?: State) => {\n if (!state)\n try {\n return useContext(Layers);\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) => ReactNode | 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?: ReactNode;\n\n /** A fallback tree to show when suspended. */\n fallback?: ReactNode;\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 ambient = useContext(Layers);\n const ref = useRef<Context | null>(null);\n const context = ref.current || (ref.current = new Context(ambient));\n\n let {\n for: input,\n children,\n fallback,\n name,\n ...rest\n } = props as Provider.ForSingleProps<T> & Provider.ForMultipleProps<T>;\n\n context.set(input, (added) => rest.is?.(added));\n\n if (Object.keys(rest).length) {\n if (State.is(input)) input = context.get(input) as T;\n if (input instanceof State) input.set(rest as State.Assign<T>);\n }\n\n useMount(() => () => context.pop());\n\n if (fallback !== undefined)\n children = createElement(Suspense, { fallback, name }, children);\n\n return createElement(Layers.Provider, { value: context, children });\n}\n\nexport { Consumer, Provider, Context, Layers };\n"],"mappings":";;;;;AAIA,MAAM,SAAS,cAAcA,UAAQ,KAAK;AAE1C,MAAM,OAAOA,UAAQ;AAErB,UAAQ,OAAO,UAAkB;AAC/B,KAAI,CAAC,MACH,KAAI;AACF,SAAO,WAAW,OAAO;SACnB;AAEV,QAAO,KAAK,MAAM;;AAmBpB,SAAS,SAA0B,OAA0B;AAC3D,QAAO,MAAM,IAAI,KAAK,MAAM,MAAM,SAAS,EAAE,CAAC;;AAmChD,SAAS,SAA0B,OAA0B;CAC3D,MAAM,UAAU,WAAW,OAAO;CAClC,MAAM,MAAM,OAAuB,KAAK;CACxC,MAAM,UAAU,IAAI,YAAY,IAAI,UAAU,IAAIA,UAAQ,QAAQ;CAElE,IAAI,EACF,KAAK,OACL,UACA,UACA,MACA,GAAG,SACD;AAEJ,SAAQ,IAAI,QAAQ,UAAU,KAAK,KAAK,MAAM,CAAC;AAE/C,KAAI,OAAO,KAAK,KAAK,CAAC,QAAQ;AAC5B,MAAIC,QAAM,GAAG,MAAM,CAAE,SAAQ,QAAQ,IAAI,MAAM;AAC/C,MAAI,iBAAiBA,QAAO,OAAM,IAAI,KAAwB;;AAGhE,sBAAqB,QAAQ,KAAK,CAAC;AAEnC,KAAI,aAAa,OACf,YAAW,cAAc,UAAU;EAAE;EAAU;EAAM,EAAE,SAAS;AAElE,QAAO,cAAc,OAAO,UAAU;EAAE,OAAO;EAAS;EAAU,CAAC"}
package/dist/esm/index.js DELETED
@@ -1,15 +0,0 @@
1
- import { Consumer, Provider } from "./context.js";
2
- import { Component } from "./component.js";
3
- import { createElement, useEffect, useRef, useState } from "react";
4
- import { Pragma, State } from "./state";
5
- import { Context, Observable, def, get, ref, set } from "@expressive/state";
6
-
7
- //#region src/index.ts
8
- Pragma.useEffect = useEffect;
9
- Pragma.useState = useState;
10
- Pragma.createElement = createElement;
11
- Pragma.useRef = useRef;
12
-
13
- //#endregion
14
- export { Component, Consumer, Context, Observable, Provider, State, State as default, def, get, ref, set };
15
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import { createElement, useEffect, useRef, useState } from 'react';\n\nimport { Pragma, State } from './state';\nimport { Consumer, Provider } from './context';\n\nPragma.useEffect = useEffect;\nPragma.useState = useState;\nPragma.createElement = createElement;\nPragma.useRef = useRef;\n\nexport { State, State as default };\nexport { Context, Observable, def, get, ref, set } from '@expressive/state';\nexport { Component } from './component';\nexport { Consumer, Provider };\n"],"mappings":";;;;;;;AAKA,OAAO,YAAY;AACnB,OAAO,WAAW;AAClB,OAAO,gBAAgB;AACvB,OAAO,SAAS"}
package/dist/esm/state.js DELETED
@@ -1,138 +0,0 @@
1
- import { Context, State, watch } from "@expressive/state";
2
-
3
- //#region src/state.ts
4
- const Pragma = {};
5
- State.use = function(...args) {
6
- const outer = Context.get();
7
- const ref = Pragma.useRef(null);
8
- return (ref.current || (ref.current = init(this)))(args);
9
- function init(Type) {
10
- const add = (arg) => typeof arg == "object" && instance.set(arg);
11
- let use = (...args) => Promise.all(args.flat().map(add));
12
- const instance = new Type((x) => {
13
- if ("use" in x && typeof x.use == "function") (use = x.use.bind(x))(...args);
14
- else return args;
15
- });
16
- const context = outer.push(instance);
17
- let ready = false;
18
- let active;
19
- return (args) => {
20
- Pragma.useEffect(() => {
21
- ready = true;
22
- }, []);
23
- useMount((refresh) => {
24
- watch(instance, (current) => {
25
- active = current;
26
- if (ready) refresh();
27
- });
28
- return () => {
29
- context.pop();
30
- instance.set(null);
31
- };
32
- });
33
- if (ready) {
34
- ready = false;
35
- Promise.resolve(use(...args)).finally(() => {
36
- ready = true;
37
- });
38
- }
39
- return active;
40
- };
41
- }
42
- };
43
- State.get = function(argument) {
44
- const ref = Pragma.useRef(null);
45
- const next = Pragma.useState(0)[1];
46
- const context = Context.get();
47
- return (ref.current || (ref.current = init(this)))();
48
- function init(Type) {
49
- let instance;
50
- let unwatch;
51
- let mounted = false;
52
- let pending = false;
53
- let value;
54
- function update() {
55
- pending = false;
56
- next((x) => x + 1);
57
- }
58
- function refresh(action) {
59
- if (typeof action == "function") action = action();
60
- update();
61
- if (action instanceof Promise) return action.finally(update);
62
- }
63
- function release() {
64
- unwatch?.();
65
- unsubscribe();
66
- unwatch = void 0;
67
- instance = void 0;
68
- }
69
- const unsubscribe = context.get(Type, (next) => {
70
- unwatch?.();
71
- unwatch = watch(instance = next, (current, changed) => {
72
- if (typeof argument === "function") {
73
- const next = argument.call(current, current, refresh);
74
- if (next === value) return;
75
- value = next;
76
- } else value = current;
77
- if (changed.length) update();
78
- }, argument === true);
79
- if (mounted) {
80
- pending = true;
81
- queueMicrotask(() => pending && update());
82
- }
83
- return release;
84
- });
85
- if (!instance) {
86
- release();
87
- if (argument === false) return () => void 0;
88
- throw new Error(`Could not find ${Type} in context.`);
89
- }
90
- if (value instanceof Promise) {
91
- let error;
92
- release();
93
- value.then((x) => value = x, (e) => error = e).finally(update);
94
- value = null;
95
- return () => {
96
- if (error) throw error;
97
- return value === void 0 ? null : value;
98
- };
99
- }
100
- if (value === null) {
101
- release();
102
- return () => null;
103
- }
104
- return () => {
105
- pending = false;
106
- Pragma.useEffect(() => {
107
- mounted = true;
108
- }, []);
109
- useMount(() => release);
110
- return value === void 0 ? null : value;
111
- };
112
- }
113
- };
114
- /**
115
- * useEffect which tolerates react StrictMode double-invoking effects on mount.
116
- */
117
- function useMount(callback) {
118
- const { current } = Pragma.useRef({});
119
- current.update = Pragma.useState(() => {
120
- if (!current.mounts) {
121
- current.mounts = 0;
122
- current.unmount = callback(() => {
123
- if (current.ready) current.update((x) => x + 1);
124
- });
125
- }
126
- return current.mounts++;
127
- })[1];
128
- Pragma.useEffect(() => {
129
- current.ready = true;
130
- return () => {
131
- if (!--current.mounts) current.unmount?.();
132
- };
133
- }, []);
134
- }
135
-
136
- //#endregion
137
- export { Pragma, State, useMount };
138
- //# sourceMappingURL=state.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"state.js","names":[],"sources":["../../src/state.ts"],"sourcesContent":["import { State, Context, watch } from '@expressive/state';\n\nexport const Pragma = {} as {\n createElement(type: any, props?: any, ...children: 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};\n\n/** Type may not be undefined - instead will be null. */\ntype NoVoid<T> = T extends undefined | void ? null : T;\n\ndeclare module '@expressive/state' {\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 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 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 /** 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.use = function <T extends State>(\n this: State.Type<T>,\n ...args: State.UseArgs<T>\n) {\n const outer = Context.get();\n const ref = Pragma.useRef<((args: State.Args<T>) => T) | null>(null);\n const render = ref.current || (ref.current = init(this));\n\n return render(args);\n\n function init(Type: State.Type<T>) {\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 Type((x) => {\n if ('use' in x && typeof x.use == 'function') {\n (use = x.use.bind(x))(...args);\n } else {\n return args;\n }\n });\n\n const context = outer.push(instance);\n\n let ready = false;\n let active: T;\n\n return (args: State.Args<T>) => {\n Pragma.useEffect(() => {\n ready = true;\n }, []);\n\n useMount((refresh) => {\n watch(instance, (current) => {\n active = current;\n\n if (ready) refresh();\n });\n\n return () => {\n context.pop();\n instance.set(null);\n };\n });\n\n if (ready) {\n ready = false;\n Promise.resolve(use(...args)).finally(() => {\n ready = true;\n });\n }\n\n return active;\n };\n }\n};\n\nState.get = function <T extends State>(\n this: State.Extends<T>,\n argument?: boolean | State.GetFactory<T, unknown>\n) {\n const ref = Pragma.useRef<(() => any) | null>(null);\n const next = Pragma.useState(0)[1];\n const context = Context.get();\n const render = ref.current || (ref.current = init(this));\n\n return render();\n\n function init(Type: State.Extends<T>) {\n let instance: T | undefined;\n let unwatch: (() => void) | undefined;\n let mounted = false;\n let pending = false;\n let value: any;\n\n function update() {\n pending = false;\n next((x) => x + 1);\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 unwatch?.();\n unsubscribe();\n unwatch = undefined;\n instance = undefined;\n }\n\n const unsubscribe = context.get(Type, (next) => {\n unwatch?.();\n unwatch = watch(\n (instance = next),\n (current, changed) => {\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 (changed.length) update();\n },\n argument === true\n );\n\n if (mounted) {\n pending = true;\n queueMicrotask(() => pending && update());\n }\n\n return release;\n });\n\n if (!instance) {\n release();\n if (argument === false) return () => undefined;\n throw new Error(`Could not find ${Type} in context.`);\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 if (value === null) {\n release();\n return () => null;\n }\n\n return () => {\n pending = false;\n Pragma.useEffect(() => {\n mounted = true;\n }, []);\n useMount(() => release);\n return value === undefined ? null : value;\n };\n }\n};\n\n/**\n * useEffect which tolerates react StrictMode double-invoking effects on mount.\n */\nexport function useMount(\n callback: (refresh: () => void) => (() => void) | void\n) {\n const { current } = Pragma.useRef(\n {} as {\n ready?: boolean;\n mounts: number;\n unmount: (() => void) | void;\n update: (next: (previous: number) => number) => void;\n }\n );\n\n current.update = Pragma.useState(() => {\n if (!current.mounts) {\n current.mounts = 0;\n current.unmount = callback(() => {\n if (current.ready) current.update((x) => x + 1);\n });\n }\n return current.mounts++;\n })[1];\n\n Pragma.useEffect(() => {\n current.ready = true;\n return () => {\n if (!--current.mounts) current.unmount?.();\n };\n }, []);\n}\n\nexport { State };\n"],"mappings":";;;AAEA,MAAa,SAAS,EAAE;AAwGxB,MAAM,MAAM,SAEV,GAAG,MACH;CACA,MAAM,QAAQ,QAAQ,KAAK;CAC3B,MAAM,MAAM,OAAO,OAA4C,KAAK;AAGpE,SAFe,IAAI,YAAY,IAAI,UAAU,KAAK,KAAK,GAEzC,KAAK;CAEnB,SAAS,KAAK,MAAqB;EACjC,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,WAChC,EAAC,MAAM,EAAE,IAAI,KAAK,EAAE,EAAE,GAAG,KAAK;OAE9B,QAAO;IAET;EAEF,MAAM,UAAU,MAAM,KAAK,SAAS;EAEpC,IAAI,QAAQ;EACZ,IAAI;AAEJ,UAAQ,SAAwB;AAC9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