@expressive/react 0.76.0 → 0.77.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/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import { State, State as State$1 } from "./state";
1
+ import { t as use } from "./use-_Es6cU25.js";
2
2
  import * as react from "react";
3
3
  import React, { ReactNode } from "react";
4
- import { Context, Context as Context$1, Observable, State as State$2, def, get, ref, set } from "@expressive/state";
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";
5
6
 
6
7
  //#region src/context.d.ts
7
8
  declare namespace Consumer {
@@ -38,27 +39,27 @@ declare namespace Provider {
38
39
  is: (instance: T) => void;
39
40
  } & { [K in State$2.Field<T>]?: T[K] };
40
41
  type ForMultipleProps<T extends State$2> = SharedProps & {
41
- for: Context$1.Accept<T>;
42
+ for: Context$2.Accept<T>;
42
43
  is?: ForEach<T>;
43
44
  };
44
45
  type Props<T extends State$2 = State$2> = ForSingleProps<T> | ForMultipleProps<T>;
45
46
  }
46
- declare function Provider<T extends State$2>(props: Provider.Props<T>): react.FunctionComponentElement<react.ProviderProps<Context$1>>;
47
+ declare function Provider<T extends State$2>(props: Provider.Props<T>): react.FunctionComponentElement<react.ProviderProps<Context$2>>;
47
48
  //#endregion
48
49
  //#region src/component.d.ts
49
50
  type StateProps<T extends State$1> = { [K in Exclude<keyof T, keyof Component>]?: T[K] };
50
51
  type RenderProps<T> = T extends {
51
52
  render(props: infer P): any;
52
53
  } ? {} extends P ? {
53
- children?: ReactNode;
54
+ children?: React.ReactNode;
54
55
  } : P : {
55
- children?: ReactNode;
56
+ children?: React.ReactNode;
56
57
  };
57
58
  interface ComponentProps<T extends Component> {
58
59
  /** Callback for newly created instance. Only called once. */
59
60
  is?: (instance: T) => void;
60
61
  /** Fallback to show when suspended or in error recovery. */
61
- fallback?: ReactNode;
62
+ fallback?: React.ReactNode;
62
63
  }
63
64
  type Props<T extends Component> = StateProps<T> & ComponentProps<T> & RenderProps<T>;
64
65
  declare module '@expressive/state' {
@@ -67,7 +68,7 @@ declare module '@expressive/state' {
67
68
  }
68
69
  }
69
70
  declare class Component extends State$1 {
70
- static contextType: React.Context<Context$1>;
71
+ static contextType: React.Context<Context$2>;
71
72
  /**
72
73
  * All JSX attributes passed to this component.
73
74
  * Includes state-derived props, render props, and built-in props like `is` and `fallback`.
@@ -76,7 +77,7 @@ declare class Component extends State$1 {
76
77
  */
77
78
  readonly props: Props<this>;
78
79
  /** @deprecated Only to satisfy React JSX. Use `this.get(State)` instead. */
79
- readonly context: Context$1;
80
+ readonly context: Context$2;
80
81
  /** @deprecated Only to satisfy React JSX. Use `this.get()` instead. */
81
82
  readonly state: State$1.Values<this>;
82
83
  /** @deprecated Only to satisfy React JSX. Not implemented. */
@@ -90,7 +91,7 @@ declare class Component extends State$1 {
90
91
  *
91
92
  * Defaults to null - nothing will be rendered.
92
93
  */
93
- fallback: ReactNode;
94
+ fallback: React.ReactNode;
94
95
  constructor(nextProps: any, ...rest: any[]);
95
96
  /**
96
97
  * Output for this component. Override to define custom JSX.
@@ -118,7 +119,7 @@ declare class Component extends State$1 {
118
119
  *
119
120
  * Without a parameter, children are accepted by default and passed through provider.
120
121
  */
121
- render(props?: {}): ReactNode;
122
+ render(props?: {}): React.ReactNode;
122
123
  /**
123
124
  * Called when a child component throws during render.
124
125
  * While this is pending, `fallback` is displayed.
@@ -131,5 +132,5 @@ declare class Component extends State$1 {
131
132
  catch?(error: Error): Promise<void> | void;
132
133
  }
133
134
  //#endregion
134
- export { Component, Consumer, Context, Observable, Provider, State, State as default, def, get, ref, set };
135
+ export { Component, Consumer, Context, Observable, Provider, State, State as default, def, get, hot, ref, set, use };
135
136
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,42 +1,14 @@
1
- Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
2
- //#region \0rolldown/runtime.js
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
- key = keys[i];
13
- if (!__hasOwnProp.call(to, key) && key !== except) {
14
- __defProp(to, key, {
15
- get: ((k) => from[k]).bind(null, key),
16
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
- });
18
- }
19
- }
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
24
- value: mod,
25
- enumerable: true
26
- }) : target, mod));
27
-
28
- //#endregion
29
- let react = require("react");
30
- react = __toESM(react);
31
- let src_state = require("./state");
32
- let _expressive_state = require("@expressive/state");
1
+ import { i as useHook, n as Runtime, t as use } from "./use-AIA25P7A.js";
2
+ import React, { Suspense, createContext, createElement, useContext, useEffect, useRef, useState } from "react";
3
+ import { State, State as State$1 } from "./state";
4
+ import { Context, Context as Context$2, Observable, State as State$2, def, get, hot, ref, set, set as set$1, unbind, watch } from "@expressive/state";
33
5
 
34
6
  //#region src/context.ts
35
- const Layers = (0, react.createContext)(_expressive_state.Context.root);
36
- const _get = _expressive_state.Context.get;
37
- _expressive_state.Context.get = (state) => {
7
+ const Layers = createContext(Context$2.root);
8
+ const _get = Context$2.get;
9
+ Context$2.get = (state) => {
38
10
  if (!state) try {
39
- return (0, react.useContext)(Layers);
11
+ return useContext(Layers);
40
12
  } catch {}
41
13
  return _get(state);
42
14
  };
@@ -44,23 +16,23 @@ function Consumer(props) {
44
16
  return props.for.get((i) => props.children(i));
45
17
  }
46
18
  function Provider(props) {
47
- const ambient = (0, react.useContext)(Layers);
48
- const ref = (0, react.useRef)(null);
49
- const context = ref.current || (ref.current = new _expressive_state.Context(ambient));
50
- let { for: input, children, fallback, name, ...rest } = props;
51
- context.set(input, (added) => rest.is?.(added));
19
+ const { for: input, children, fallback, name, is, ...rest } = props;
20
+ const ambient = useContext(Layers);
21
+ const context = useHook((set) => {
22
+ set(new Context$2(ambient));
23
+ return () => context.pop();
24
+ });
25
+ context.set(input, is);
52
26
  if (Object.keys(rest).length) {
53
- if (_expressive_state.State.is(input)) input = context.get(input);
54
- if (input instanceof _expressive_state.State) input.set(rest);
27
+ const i = State$2.is(input) ? context.get(input) : input;
28
+ if (i instanceof State$2) i.set(rest);
55
29
  }
56
- (0, src_state.useMount)(() => () => context.pop());
57
- if (fallback !== void 0) children = (0, react.createElement)(react.Suspense, {
58
- fallback,
59
- name
60
- }, children);
61
- return (0, react.createElement)(Layers.Provider, {
30
+ return createElement(Layers.Provider, {
62
31
  value: context,
63
- children
32
+ children: fallback !== void 0 ? createElement(Suspense, {
33
+ fallback,
34
+ name
35
+ }, children) : children
64
36
  });
65
37
  }
66
38
 
@@ -73,17 +45,17 @@ const INTERNAL = [
73
45
  "_reactInternals",
74
46
  "_reactInternalInstance"
75
47
  ];
76
- var Component = class extends src_state.State {
48
+ var Component = class extends State$1 {
77
49
  static {
78
50
  this.contextType = Layers;
79
51
  }
80
52
  constructor(nextProps, ...rest) {
81
53
  const { is, ...props } = nextProps;
82
- rest = rest.filter((x) => !(x instanceof _expressive_state.Context));
54
+ rest = rest.filter((x) => !(x instanceof Context$2));
83
55
  super(props, rest, is && ((x) => void is(x)), () => {
84
56
  Object.defineProperty(this, "props", { enumerable: false });
85
57
  });
86
- this.fallback = (0, _expressive_state.set)(null);
58
+ this.fallback = set$1(null);
87
59
  const existing = PENDING.get(nextProps);
88
60
  if (existing) return existing;
89
61
  PENDING.set(nextProps, this);
@@ -141,35 +113,31 @@ Object.defineProperties(Component.prototype, {
141
113
  });
142
114
  function bootstrap(context) {
143
115
  const self = this.is;
144
- const render = (0, _expressive_state.unbind)(this.render);
116
+ const render = unbind(this.render);
145
117
  context = context.push(self);
146
- let ready = false;
147
118
  let active;
148
119
  function Render() {
149
120
  return render.call(active, self.props);
150
121
  }
151
122
  function AsComponent() {
152
- (0, src_state.useMount)((refresh) => {
153
- (0, _expressive_state.watch)(self, (current) => {
123
+ useHook((refresh) => {
124
+ watch(self, (current) => {
154
125
  active = current;
155
- if (ready) refresh();
126
+ refresh();
156
127
  });
157
128
  return () => {
158
129
  self.set(null);
159
130
  context.pop();
160
131
  };
161
132
  });
162
- (0, react.useEffect)(() => {
163
- ready = true;
164
- }, []);
165
- const children = (0, react.createElement)(Layers.Provider, {
133
+ const children = createElement(Layers.Provider, {
166
134
  value: context,
167
- children: (0, react.createElement)(react.Suspense, {
135
+ children: createElement(Suspense, {
168
136
  fallback: active.fallback,
169
137
  name: String(self)
170
- }, (0, react.createElement)(Render))
138
+ }, createElement(Render))
171
139
  });
172
- return active.catch ? (0, react.createElement)(ErrorBoundary, {
140
+ return active.catch ? createElement(ErrorBoundary, {
173
141
  self,
174
142
  children
175
143
  }) : children;
@@ -179,10 +147,10 @@ function bootstrap(context) {
179
147
  get: () => context,
180
148
  set() {}
181
149
  },
182
- render: { value: () => (0, react.createElement)(AsComponent) }
150
+ render: { value: () => createElement(AsComponent) }
183
151
  });
184
152
  }
185
- var ErrorBoundary = class extends react.default.Component {
153
+ var ErrorBoundary = class extends React.Component {
186
154
  constructor(..._args) {
187
155
  super(..._args);
188
156
  this.state = {};
@@ -210,96 +178,48 @@ var ErrorBoundary = class extends react.default.Component {
210
178
  }
211
179
  };
212
180
  const SEEN = /* @__PURE__ */ new WeakSet();
213
- function subcomponents(proto) {
214
- for (const key of Object.getOwnPropertyNames(proto)) {
215
- if (!/^[A-Z]/.test(key)) continue;
216
- const { get, value } = Object.getOwnPropertyDescriptor(proto, key);
217
- if (!get && typeof value !== "function") continue;
218
- Object.defineProperty(proto, key, {
219
- configurable: true,
220
- get() {
221
- const self = this.is;
222
- let render = (0, _expressive_state.unbind)(get ? get.call(this) : value);
223
- function Sub(props) {
224
- const ref = (0, react.useRef)(null);
225
- (0, src_state.useMount)((refresh) => (0, _expressive_state.watch)(self, (current) => {
226
- ref.current = current;
227
- refresh();
228
- }));
229
- return render.call(ref.current, props);
230
- }
231
- Object.defineProperty(self, key, {
232
- configurable: true,
233
- get: () => Sub,
234
- set(fn) {
235
- render = fn;
236
- }
237
- });
238
- return Sub;
239
- }
240
- });
241
- }
242
- }
243
181
  Component.on((self) => {
244
182
  let Type = self.constructor;
245
183
  while (Type !== Component) {
246
- const proto = Type.prototype;
247
184
  if (SEEN.has(Type)) break;
248
185
  SEEN.add(Type);
249
- subcomponents(proto);
186
+ subcomponents(Type.prototype);
250
187
  Type = Object.getPrototypeOf(Type);
251
188
  }
252
189
  subcomponents(self);
253
190
  });
191
+ function subcomponents(self) {
192
+ for (const key of Object.getOwnPropertyNames(self)) {
193
+ if (!/^[A-Z]/.test(key)) continue;
194
+ const { get, value } = Object.getOwnPropertyDescriptor(self, key);
195
+ if (!get && typeof value !== "function") continue;
196
+ function subcomponent() {
197
+ const self = this.is;
198
+ let render = unbind(get ? get.call(self) : value);
199
+ const Component = (props) => render.call(useHook((set) => watch(self, set)), props);
200
+ Object.defineProperty(self, key, {
201
+ configurable: true,
202
+ get: () => Component,
203
+ set(fn) {
204
+ render = fn;
205
+ }
206
+ });
207
+ return Component;
208
+ }
209
+ Object.defineProperty(self, key, {
210
+ configurable: true,
211
+ get: subcomponent
212
+ });
213
+ }
214
+ }
254
215
 
255
216
  //#endregion
256
217
  //#region src/index.ts
257
- src_state.Pragma.useEffect = react.useEffect;
258
- src_state.Pragma.useState = react.useState;
259
- src_state.Pragma.createElement = react.createElement;
260
- src_state.Pragma.useRef = react.useRef;
218
+ Runtime.createElement = createElement;
219
+ Runtime.useEffect = useEffect;
220
+ Runtime.useState = useState;
221
+ Runtime.useRef = useRef;
261
222
 
262
223
  //#endregion
263
- exports.Component = Component;
264
- exports.Consumer = Consumer;
265
- Object.defineProperty(exports, 'Context', {
266
- enumerable: true,
267
- get: function () {
268
- return _expressive_state.Context;
269
- }
270
- });
271
- Object.defineProperty(exports, 'Observable', {
272
- enumerable: true,
273
- get: function () {
274
- return _expressive_state.Observable;
275
- }
276
- });
277
- exports.Provider = Provider;
278
- exports.State = src_state.State;
279
- exports.default = src_state.State;
280
- exports.__toESM = __toESM;
281
- Object.defineProperty(exports, 'def', {
282
- enumerable: true,
283
- get: function () {
284
- return _expressive_state.def;
285
- }
286
- });
287
- Object.defineProperty(exports, 'get', {
288
- enumerable: true,
289
- get: function () {
290
- return _expressive_state.get;
291
- }
292
- });
293
- Object.defineProperty(exports, 'ref', {
294
- enumerable: true,
295
- get: function () {
296
- return _expressive_state.ref;
297
- }
298
- });
299
- Object.defineProperty(exports, 'set', {
300
- enumerable: true,
301
- get: function () {
302
- return _expressive_state.set;
303
- }
304
- });
224
+ export { Component, Consumer, Context, Observable, Provider, State, State as default, def, get, hot, ref, set, use };
305
225
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Context","State","Suspense","State","Context","Suspense","React","useEffect","useState","createElement","useRef"],"sources":["../src/context.ts","../src/component.ts","../src/index.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","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","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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAI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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;;;;AC1SF,iBAAO,YAAYC;AACnB,iBAAO,WAAWC;AAClB,iBAAO,gBAAgBC;AACvB,iBAAO,SAASC"}
1
+ {"version":3,"file":"index.js","names":["Context","State","State","Context","set"],"sources":["../src/context.ts","../src/component.ts","../src/index.ts"],"sourcesContent":["import { State, Context } from '@expressive/state';\nimport {\n createContext,\n createElement,\n ReactNode,\n Suspense,\n useContext\n} from 'react';\nimport { useHook } from './runtime';\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 {\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 = useContext(Layers);\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 createElement(Layers.Provider, {\n value: context,\n children:\n fallback !== undefined\n ? createElement(Suspense, { fallback, name }, children)\n : children\n });\n}\n\nexport { Consumer, Provider, Context, Layers };\n","import { watch, unbind, set } from '@expressive/state';\nimport React, { createElement, Suspense } from 'react';\nimport { Context, Layers } from './context';\nimport { useHook } from './runtime';\nimport { State } 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?: React.ReactNode }\n : P\n : { children?: React.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?: React.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\nexport class 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: React.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?: {}): React.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 active: Component;\n\n function Render() {\n return render.call(active, self.props);\n }\n\n function AsComponent() {\n useHook((refresh) => {\n watch(self, (current) => {\n active = current;\n refresh();\n });\n\n return () => {\n self.set(null);\n context.pop();\n };\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: React.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\nComponent.on((self) => {\n let Type = self.constructor as State.Extends;\n\n while (Type !== Component) {\n if (SEEN.has(Type)) break;\n SEEN.add(Type);\n subcomponents(Type.prototype);\n Type = Object.getPrototypeOf(Type);\n }\n\n subcomponents(self);\n});\n\nfunction subcomponents(self: State) {\n for (const key of Object.getOwnPropertyNames(self)) {\n if (!/^[A-Z]/.test(key)) continue;\n\n const { get, value } = Object.getOwnPropertyDescriptor(self, key)!;\n\n if (!get && typeof value !== 'function') continue;\n\n function subcomponent(this: Component) {\n const self = this.is;\n\n let render = unbind(get ? get.call(self) : value);\n\n const Component = (props: unknown) =>\n render.call(\n useHook<Component>((set) => watch(self, set)),\n props\n );\n\n Object.defineProperty(self, key, {\n configurable: true,\n get: () => Component,\n set(fn: Function) {\n render = fn;\n }\n });\n\n return Component;\n }\n\n Object.defineProperty(self, key, {\n configurable: true,\n get: subcomponent\n });\n }\n}","import { createElement, useEffect, useRef, useState } from 'react';\n\nimport { State } from './state';\nimport { Runtime } from './runtime';\nimport { Consumer, Provider } from './context';\n\nRuntime.createElement = createElement;\nRuntime.useEffect = useEffect;\nRuntime.useState = useState;\nRuntime.useRef = useRef;\n\nexport { State, State as default };\nexport { Context, Observable, def, get, ref, set, hot } from '@expressive/state';\nexport { Component } from './component';\nexport { use } from './use';\nexport { Consumer, Provider };\n"],"mappings":";;;;;;AAUA,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,EACJ,KAAK,OACL,UACA,UACA,MACA,IACA,GAAG,SACD;CAEJ,MAAM,UAAU,WAAW,OAAO;CAClC,MAAM,UAAU,SAAkB,QAAQ;AACxC,MAAI,IAAIA,UAAQ,QAAQ,CAAC;AACzB,eAAa,QAAQ,KAAK;GAC1B;AAEF,SAAQ,IAAI,OAAO,GAAG;AAEtB,KAAI,OA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,uBAAO,IAAI,SAAmB;AAEpC,UAAU,IAAI,SAAS;CACrB,IAAI,OAAO,KAAK;AAEhB,QAAO,SAAS,WAAW;AACzB,MAAI,KAAK,IAAI,KAAK,CAAE;AACpB,OAAK,IAAI,KAAK;AACd,gBAAc,KAAK,UAAU;AAC7B,SAAO,OAAO,eAAe,KAAK;;AAGpC,eAAc,KAAK;EACnB;AAEF,SAAS,cAAc,MAAa;AAClC,MAAK,MAAM,OAAO,OAAO,oBAAoB,KAAK,EAAE;AAClD,MAAI,CAAC,SAAS,KAAK,IAAI,CAAE;EAEzB,MAAM,EAAE,KAAK,UAAU,OAAO,yBAAyB,MAAM,IAAI;AAEjE,MAAI,CAAC,OAAO,OAAO,UAAU,WAAY;EAEzC,SAAS,eAA8B;GACrC,MAAM,OAAO,KAAK;GAElB,IAAI,SAAS,OAAO,MAAM,IAAI,KAAK,KAAK,GAAG,MAAM;GAEjD,MAAM,aAAa,UACjB,OAAO,KACL,SAAoB,QAAQ,MAAM,MAAM,IAAI,CAAC,EAC7C,MACD;AAEH,UAAO,eAAe,MAAM,KAAK;IAC/B,cAAc;IACd,WAAW;IACX,IAAI,IAAc;AAChB,cAAS;;IAEZ,CAAC;AAEF,UAAO;;AAGT,SAAO,eAAe,MAAM,KAAK;GAC/B,cAAc;GACd,KAAK;GACN,CAAC;;;;;;ACtRN,QAAQ,gBAAgB;AACxB,QAAQ,YAAY;AACpB,QAAQ,WAAW;AACnB,QAAQ,SAAS"}
package/dist/state.d.ts CHANGED
@@ -1,7 +1,8 @@
1
+ import { t as use } from "./use-_Es6cU25.js";
1
2
  import { State } from "@expressive/state";
2
3
 
3
- //#region src/state.d.ts
4
- declare const Pragma: {
4
+ //#region src/runtime.d.ts
5
+ declare const Runtime: {
5
6
  createElement(type: any, props?: any, ...children: any[]): any;
6
7
  useState<S>(initial: S | (() => S)): [S, (next: (previous: S) => S) => void];
7
8
  useEffect(effect: () => (() => void) | void, deps?: any[]): void;
@@ -9,6 +10,8 @@ declare const Pragma: {
9
10
  current: T;
10
11
  };
11
12
  };
13
+ //#endregion
14
+ //#region src/state.d.ts
12
15
  /** Type may not be undefined - instead will be null. */
13
16
  type NoVoid<T> = T extends undefined | void ? null : T;
14
17
  declare module '@expressive/state' {
@@ -66,10 +69,6 @@ declare module '@expressive/state' {
66
69
  function get<T extends State>(this: State.Extends<T>, factory: GetEffect<T>): null;
67
70
  }
68
71
  }
69
- /**
70
- * useEffect which tolerates react StrictMode double-invoking effects on mount.
71
- */
72
- declare function useMount(callback: (refresh: () => void) => (() => void) | void): void;
73
72
  //#endregion
74
- export { Pragma, State, useMount };
73
+ export { Runtime, State, use };
75
74
  //# sourceMappingURL=state.d.ts.map
package/dist/state.js CHANGED
@@ -1,54 +1,42 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_index = require('./index.js');
3
- let _expressive_state = require("@expressive/state");
1
+ import { a as useReady, i as useHook, n as Runtime, r as useFactory, t as use } from "./use-AIA25P7A.js";
2
+ import { Context, State, watch } from "@expressive/state";
4
3
 
5
4
  //#region src/state.ts
6
- const Pragma = {};
7
- _expressive_state.State.use = function(...args) {
8
- const outer = _expressive_state.Context.get();
9
- const ref = Pragma.useRef(null);
10
- return (ref.current || (ref.current = init(this)))(args);
11
- function init(Type) {
5
+ State.use = function use(...args) {
6
+ const outer = Context.get();
7
+ return useFactory(() => {
12
8
  const add = (arg) => typeof arg == "object" && instance.set(arg);
13
9
  let use = (...args) => Promise.all(args.flat().map(add));
14
- const instance = new Type((x) => {
15
- if ("use" in x && typeof x.use == "function") (use = x.use.bind(x))(...args);
16
- else return args;
10
+ const instance = new this((x) => {
11
+ if ("use" in x && typeof x.use == "function") {
12
+ use = x.use.bind(x);
13
+ use(...args);
14
+ } else return args;
17
15
  });
18
16
  const context = outer.push(instance);
19
17
  let ready = false;
20
- let active;
21
18
  return (args) => {
22
- Pragma.useEffect(() => {
23
- ready = true;
24
- }, []);
25
- useMount((refresh) => {
26
- (0, _expressive_state.watch)(instance, (current) => {
27
- active = current;
28
- if (ready) refresh();
29
- });
30
- return () => {
31
- context.pop();
32
- instance.set(null);
33
- };
34
- });
35
19
  if (ready) {
36
20
  ready = false;
37
21
  Promise.resolve(use(...args)).finally(() => {
38
22
  ready = true;
39
23
  });
40
24
  }
41
- return active;
25
+ useReady(() => ready = true);
26
+ return useHook((update) => {
27
+ watch(instance, update);
28
+ return () => {
29
+ context.pop();
30
+ instance.set(null);
31
+ };
32
+ });
42
33
  };
43
- }
34
+ })(args);
44
35
  };
45
- _expressive_state.State.get = function(argument) {
46
- const ref = Pragma.useRef(null);
47
- const next = Pragma.useState(0)[1];
48
- const context = _expressive_state.Context.get();
49
- return (ref.current || (ref.current = init(this)))();
50
- function init(Type) {
51
- let instance;
36
+ State.get = function get(argument) {
37
+ const next = Runtime.useState(0)[1];
38
+ const local = Context.get();
39
+ return useFactory(() => {
52
40
  let unwatch;
53
41
  let mounted = false;
54
42
  let pending = false;
@@ -63,14 +51,13 @@ _expressive_state.State.get = function(argument) {
63
51
  if (action instanceof Promise) return action.finally(update);
64
52
  }
65
53
  function release() {
66
- unwatch?.();
67
54
  unsubscribe();
55
+ unwatch?.();
68
56
  unwatch = void 0;
69
- instance = void 0;
70
57
  }
71
- const unsubscribe = context.get(Type, (next) => {
58
+ function attach(next) {
72
59
  unwatch?.();
73
- unwatch = (0, _expressive_state.watch)(instance = next, (current, changed) => {
60
+ unwatch = watch(next, (current, changed) => {
74
61
  if (typeof argument === "function") {
75
62
  const next = argument.call(current, current, refresh);
76
63
  if (next === value) return;
@@ -83,11 +70,16 @@ _expressive_state.State.get = function(argument) {
83
70
  queueMicrotask(() => pending && update());
84
71
  }
85
72
  return release;
86
- });
87
- if (!instance) {
88
- release();
73
+ }
74
+ const unsubscribe = local.get(this, attach);
75
+ if (!unwatch) {
76
+ unsubscribe();
89
77
  if (argument === false) return () => void 0;
90
- throw new Error(`Could not find ${Type} in context.`);
78
+ throw new Error(`Could not find ${this} in context.`);
79
+ }
80
+ if (value === null) {
81
+ release();
82
+ return () => null;
91
83
  }
92
84
  if (value instanceof Promise) {
93
85
  let error;
@@ -99,44 +91,15 @@ _expressive_state.State.get = function(argument) {
99
91
  return value === void 0 ? null : value;
100
92
  };
101
93
  }
102
- if (value === null) {
103
- release();
104
- return () => null;
105
- }
106
94
  return () => {
107
95
  pending = false;
108
- Pragma.useEffect(() => {
109
- mounted = true;
110
- }, []);
111
- useMount(() => release);
96
+ useReady(() => mounted = true);
97
+ useHook(() => release);
112
98
  return value === void 0 ? null : value;
113
99
  };
114
- }
100
+ })();
115
101
  };
116
- /**
117
- * useEffect which tolerates react StrictMode double-invoking effects on mount.
118
- */
119
- function useMount(callback) {
120
- const { current } = Pragma.useRef({});
121
- current.update = Pragma.useState(() => {
122
- if (!current.mounts) {
123
- current.mounts = 0;
124
- current.unmount = callback(() => {
125
- if (current.ready) current.update((x) => x + 1);
126
- });
127
- }
128
- return current.mounts++;
129
- })[1];
130
- Pragma.useEffect(() => {
131
- current.ready = true;
132
- return () => {
133
- if (!--current.mounts) current.unmount?.();
134
- };
135
- }, []);
136
- }
137
102
 
138
103
  //#endregion
139
- exports.Pragma = Pragma;
140
- exports.State = _expressive_state.State;
141
- exports.useMount = useMount;
104
+ export { Runtime, State, use };
142
105
  //# sourceMappingURL=state.js.map
package/dist/state.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"state.js","names":["Context"],"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,wBAAM,MAAM,SAEV,GAAG,MACH;CACA,MAAM,QAAQA,0BAAQ,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,M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AS;AACX,cAAU;AACV,yBAAqB,WAAW,QAAQ,CAAC;;AAG3C,UAAO;IACP;AAEF,MAAI,CAAC,UAAU;AACb,YAAS;AACT,OAAI,aAAa,MAAO,cAAa;AACrC,SAAM,IAAI,MAAM,kBAAkB,KAAK,cAAc;;AAGvD,MAAI,iBAAiB,SAAS;GAC5B,IAAI;AAEJ,YAAS;AAET,SACG,MACE,MAAO,QAAQ,IACf,MAAO,QAAQ,EACjB,CACA,QAAQ,OAAO;AAElB,WAAQ;AAER,gBAAa;AACX,QAAI,MAAO,OAAM;AACjB,WAAO,UAAU,SAAY,OAAO;;;AAIxC,MAAI,UAAU,MAAM;AAClB,YAAS;AACT,gBAAa;;AAGf,eAAa;AACX,aAAU;AACV,UAAO,gBAAgB;AACrB,cAAU;MACT,EAAE,CAAC;AACN,kBAAe,QAAQ;AACvB,UAAO,UAAU,SAAY,OAAO;;;;;;;AAQ1C,SAAgB,SACd,UACA;CACA,MAAM,EAAE,YAAY,OAAO,OACzB,EAAE,CAMH;AAED,SAAQ,SAAS,OAAO,eAAe;AACrC,MAAI,CAAC,QAAQ,QAAQ;AACnB,WAAQ,SAAS;AACjB,WAAQ,UAAU,eAAe;AAC/B,QAAI,QAAQ,MAAO,SAAQ,QAAQ,MAAM,IAAI,EAAE;KAC/C;;AAEJ,SAAO,QAAQ;GACf,CAAC;AAEH,QAAO,gBAAgB;AACrB,UAAQ,QAAQ;AAChB,eAAa;AACX,OAAI,CAAC,EAAE,QAAQ,OAAQ,SAAQ,WAAW;;IAE3C,EAAE,CAAC"}
1
+ {"version":3,"file":"state.js","names":[],"sources":["../src/state.ts"],"sourcesContent":["import { State, Context, watch } from '@expressive/state';\nimport { Runtime, useFactory, useHook, useReady } from './runtime';\n\nexport { Runtime };\nexport { use } from './use';\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 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 useReady(() => ready = true);\n\n return useHook<T>((update) => {\n watch(instance, update);\n return () => {\n context.pop();\n instance.set(null);\n };\n });\n };\n });\n\n return render(args);\n};\n\nState.get = function get<T extends State>(\n this: State.Extends<T>,\n argument?: boolean | State.GetFactory<T, unknown>\n) {\n const next = Runtime.useState(0)[1];\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\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 unsubscribe();\n unwatch?.();\n unwatch = undefined;\n }\n\n function attach(next: T) {\n unwatch?.();\n unwatch = watch(\n 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 const unsubscribe = local.get(this, attach);\n\n if (!unwatch) {\n unsubscribe();\n if (argument === false) return () => undefined;\n throw new Error(`Could not find ${this} 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 useReady(() => mounted = true);\n useHook(() => release);\n return value === undefined ? null : value;\n };\n });\n\n return render();\n};\n\nexport { State };\n"],"mappings":";;;;AAuGA,MAAM,MAAM,SAAS,IAEnB,GAAG,MACH;CACA,MAAM,QAAQ,QAAQ,KAAK;AAuC3B,QAtCe,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,kBAAe,QAAQ,KAAK;AAE5B,UAAO,SAAY,WAAW;AAC5B,UAAM,UAAU,OAAO;AACvB,iBAAa;AACX,aAAQ,KAAK;AACb,cAAS,IAAI,KAAK;;KAEpB;;GAEJ,CAEY,KAAK;;AAGrB,MAAM,MAAM,SAAS,IAEnB,UACA;CACA,MAAM,OAAO,QAAQ,SAAS,EAAE,CAAC;CACjC,MAAM,QAAQ,QAAQ,KAAK;AA2F3B,QA1Fe,iBAAiB;EAC9B,IAAI;EACJ,IAAI,UAAU;EACd,IAAI,UAAU;EACd,IAAI;EAEJ,SAAS,SAAS;AAChB,aAAU;AACV,SAAM,MAAM,IAAI,EAAE;;EAGpB,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,MAAS;AACvB,cAAW;AACX,aAAU,MACR,OACC,SAAS,YAAY;AACpB,QAAI,OAAO,aAAa,YAAY;KAClC,MAAM,OAAO,SAAS,KAAK,SAAS,SAAS,QAAQ;AACrD,SAAI,SAAS,MAAO;AACpB,aAAQ;UAER,SAAQ;AAGV,QAAI,QAAQ,OAAQ,SAAQ;MAE9B,aAAa,KACd;AAED,OAAI,SAAS;AACX,cAAU;AACV,yBAAqB,WAAW,QAAQ,CAAC;;AAG3C,UAAO;;EAGT,MAAM,cAAc,MAAM,IAAI,MAAM,OAAO;AAE3C,MAAI,CAAC,SAAS;AACZ,gBAAa;AACb,OAAI,aAAa,MAAO,cAAa;AACrC,SAAM,IAAI,MAAM,kBAAkB,KAAK,cAAc;;AAGvD,MAAI,UAAU,MAAM;AAClB,YAAS;AACT,gBAAa;;AAGf,MAAI,iBAAiB,SAAS;GAC5B,IAAI;AAEJ,YAAS;AAET,SACG,MACE,MAAO,QAAQ,IACf,MAAO,QAAQ,EACjB,CACA,QAAQ,OAAO;AAElB,WAAQ;AAER,gBAAa;AACX,QAAI,MAAO,OAAM;AACjB,WAAO,UAAU,SAAY,OAAO;;;AAIxC,eAAa;AACX,aAAU;AACV,kBAAe,UAAU,KAAK;AAC9B,iBAAc,QAAQ;AACtB,UAAO,UAAU,SAAY,OAAO;;GAEtC,EAEa"}
@@ -0,0 +1,63 @@
1
+ import { event, observer, watch } from "@expressive/state";
2
+
3
+ //#region src/runtime.ts
4
+ const Runtime = {};
5
+ function useFactory(factory) {
6
+ const ref = Runtime.useRef(null);
7
+ return ref.current || (ref.current = factory());
8
+ }
9
+ function useReady(callback) {
10
+ return Runtime.useEffect(() => void callback(), []);
11
+ }
12
+ /**
13
+ * Mount-effect with a refreshable return value, safe under React StrictMode.
14
+ *
15
+ * @param callback Setup handler; receives a setter, must return a cleanup.
16
+ * @returns Latest value published via the setter (`undefined` until set).
17
+ */
18
+ function useHook(callback) {
19
+ const { current } = Runtime.useRef({ mounted: 0 });
20
+ current.update = Runtime.useState(() => {
21
+ if (!current.mounted) current.unmount = callback((next) => {
22
+ current.output = next;
23
+ current.update?.((x) => x + 1);
24
+ });
25
+ return current.mounted++;
26
+ })[1];
27
+ Runtime.useEffect(() => () => {
28
+ if (--current.mounted < 1) current.unmount();
29
+ }, []);
30
+ return current.output;
31
+ }
32
+
33
+ //#endregion
34
+ //#region src/use.ts
35
+ function use(subject) {
36
+ const { current } = Runtime.useRef({
37
+ mounted: 0,
38
+ proxy: subject
39
+ });
40
+ const update = Runtime.useState(() => current.mounted++)[1];
41
+ if (current.source !== subject) {
42
+ const status = observer(subject);
43
+ if (status === null) throw new Error("Provided object is no longer observable.");
44
+ if (!status) throw new Error("Provided object is not observable.");
45
+ if (!status.ready) event(subject);
46
+ current.unwatch?.();
47
+ current.source = subject;
48
+ let init = true;
49
+ current.unwatch = watch(subject, (next, changed) => {
50
+ current.proxy = next;
51
+ if (changed.length && !init) update((x) => x + 1);
52
+ });
53
+ init = false;
54
+ }
55
+ Runtime.useEffect(() => () => {
56
+ if (--current.mounted < 1) current.unwatch?.();
57
+ }, []);
58
+ return current.proxy;
59
+ }
60
+
61
+ //#endregion
62
+ export { useReady as a, useHook as i, Runtime as n, useFactory as r, use as t };
63
+ //# sourceMappingURL=use-AIA25P7A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-AIA25P7A.js","names":[],"sources":["../src/runtime.ts","../src/use.ts"],"sourcesContent":["export const Runtime = {} 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\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 { mounted: 0 } as {\n mounted: number;\n unmount: () => void;\n update: (next: (previous: number) => number) => void;\n output: T;\n }\n );\n\n current.update = Runtime.useState(() => {\n if (!current.mounted)\n current.unmount = callback((next) => {\n current.output = next;\n current.update?.((x) => x + 1);\n });\n\n return current.mounted++;\n })[1];\n\n Runtime.useEffect(() => () => {\n if (--current.mounted < 1) current.unmount();\n }, []);\n\n return current.output;\n}","import { event, observer, watch } from '@expressive/state';\nimport { Runtime } from './runtime';\n\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 === null)\n throw new Error('Provided object is no longer observable.');\n\n if (!status)\n throw new Error('Provided object is not observable.');\n\n if (!status.ready) event(subject);\n\n current.unwatch?.();\n current.source = 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 Runtime.useEffect(() => () => {\n if (--current.mounted < 1) current.unwatch?.();\n }, []);\n\n return current.proxy;\n}\n"],"mappings":";;;AAAA,MAAa,UAAU,EAAE;AAOzB,SAAgB,WAA+B,SAAkB;CAC/D,MAAM,MAAM,QAAQ,OAAiB,KAAK;AAC1C,QAAO,IAAI,YAAY,IAAI,UAAU,SAAS;;AAGhD,SAAgB,SAAY,UAAsB;AAChD,QAAO,QAAQ,gBAAgB,KAAK,UAAU,EAAE,EAAE,CAAC;;;;;;;;AASrD,SAAgB,QACd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expressive/react",
3
- "version": "0.76.0",
3
+ "version": "0.77.0",
4
4
  "description": "Use classes to define state in React!",
5
5
  "keywords": [
6
6
  "expressive",
@@ -26,15 +26,16 @@
26
26
  "exports": {
27
27
  ".": {
28
28
  "types": "./dist/index.d.ts",
29
- "require": "./dist/index.js",
30
- "import": "./dist/esm/index.js"
29
+ "default": "./dist/index.js"
31
30
  },
32
31
  "./state": {
33
32
  "types": "./dist/state.d.ts",
34
- "require": "./dist/state.js",
35
- "import": "./dist/esm/state.js"
33
+ "default": "./dist/state.js"
36
34
  }
37
35
  },
36
+ "engines": {
37
+ "node": ">=20"
38
+ },
38
39
  "publishConfig": {
39
40
  "access": "public"
40
41
  },
@@ -44,7 +45,7 @@
44
45
  "preversion": "npm run test && npm run build"
45
46
  },
46
47
  "dependencies": {
47
- "@expressive/state": "^0.76.0"
48
+ "@expressive/state": "^0.77.0"
48
49
  },
49
50
  "devDependencies": {
50
51
  "@testing-library/react": "^16.3.0",
@@ -54,7 +55,6 @@
54
55
  "react": "^19",
55
56
  "react-dom": "^19",
56
57
  "tsdown": "^0.20.1",
57
- "tsup": "^8.0.2",
58
58
  "vitest": "^4.0.18"
59
59
  },
60
60
  "peerDependencies": {
@@ -65,5 +65,5 @@
65
65
  "optional": true
66
66
  }
67
67
  },
68
- "gitHead": "cba88d572c670c823cf270dd5eab16b02b1f4f37"
68
+ "gitHead": "785b18c626b96cd2a51fb33386b3bdeded0afceb"
69
69
  }
@@ -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,WAAW,MACZ;CACD,OAAO;EACL,MAAqB;AACnB,UAAO,KAAK,KAAK;;EAEnB,MAAM;EACP;CACD,SAAS;EACP,cAAc;EACd,KAAK;EACN;CACF,CAAC;AAEF,SAAS,UAA2B,SAAkB;CACpD,MAAM,OAAO,KAAK;CAClB,MAAM,SAAS,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K,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;AAC9B,UAAO,gBAAgB;AACrB,YAAQ;MACP,EAAE,CAAC;AAEN,aAAU,YAAY;AACpB,UAAM,WAAW,YAAY;AAC3B,cAAS;AAET,SAAI,MAAO,UAAS;MACpB;AAEF,iBAAa;AACX,aAAQ,KAAK;AACb,cAAS,IAAI,KAAK;;KAEpB;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