@expressive/react 0.76.0 → 0.78.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,190 +1,64 @@
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");
33
-
34
- //#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) => {
38
- if (!state) try {
39
- return (0, react.useContext)(Layers);
40
- } catch {}
41
- return _get(state);
42
- };
43
- function Consumer(props) {
44
- return props.for.get((i) => props.children(i));
45
- }
46
- 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));
52
- 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);
55
- }
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, {
62
- value: context,
63
- children
64
- });
65
- }
1
+ import { r as Provider, t as Consumer } from "./context-BfeYQmAX.js";
2
+ import { Component, Component as Component$1, Context, Observer, def, get, hot, ref, set } from "@expressive/mvc";
3
+ import React, { Children, Suspense, createContext, createElement, isValidElement, useContext, useEffect, useRef, useState } from "react";
4
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
+ import { host } from "@expressive/mvc/jsx-runtime";
6
+ import { Runtime, State, State as runtime_default, use } from "./runtime";
66
7
 
67
- //#endregion
68
- //#region src/component.ts
69
- const PENDING = /* @__PURE__ */ new WeakMap();
70
- const INTERNAL = [
71
- "updater",
72
- "refs",
73
- "_reactInternals",
74
- "_reactInternalInstance"
75
- ];
76
- var Component = class extends src_state.State {
77
- static {
78
- this.contextType = Layers;
79
- }
80
- constructor(nextProps, ...rest) {
81
- const { is, ...props } = nextProps;
82
- rest = rest.filter((x) => !(x instanceof _expressive_state.Context));
83
- super(props, rest, is && ((x) => void is(x)), () => {
84
- Object.defineProperty(this, "props", { enumerable: false });
85
- });
86
- this.fallback = (0, _expressive_state.set)(null);
87
- const existing = PENDING.get(nextProps);
88
- if (existing) return existing;
89
- PENDING.set(nextProps, this);
90
- for (const key of INTERNAL) Object.defineProperty(this, key, {
91
- configurable: true,
92
- writable: true
93
- });
94
- this.props = nextProps;
95
- this.set("props", () => {
96
- this.set(this.props);
97
- });
98
- }
99
- /**
100
- * Output for this component. Override to define custom JSX.
101
- *
102
- * Properties accessed via `this` are reactive and will trigger a render when , in addition to props.
103
- *
104
- * Accepts optional parameter to receive extra props
105
- * from JSX, beyond those merged to state properties.
106
- *
107
- * To declare extra props use `props = {} as { ... }` with expected shape.
108
- * A default is required to satisfy TypeScript but safely ignored.
109
- *
110
- * ```ts
111
- * render(props = {} as { label: string }) {
112
- * return <span>{props.label}</span>;
113
- * }
114
- * ```
115
- * Usable as:
116
- * ```tsx
117
- * <MyComponent label="Hello" />
118
- * ```
119
- *
120
- * These must be compatible with State-derived properties, or be unused.
121
- * Props you declare as not-optional will be required by the JSX element.
122
- *
123
- * Without a parameter, children are accepted by default and passed through provider.
124
- */
125
- render(props) {
126
- return this.props.children || null;
127
- }
128
- };
129
- Object.defineProperties(Component.prototype, {
130
- isReactComponent: { get: () => true },
131
- state: {
132
- get() {
133
- return this.get();
134
- },
135
- set() {}
8
+ //#region src/jsx-runtime.ts
9
+ host({
10
+ jsx,
11
+ jsxs,
12
+ Fragment,
13
+ isElement: isValidElement,
14
+ childrenOf(children) {
15
+ return Children.toArray(children);
16
+ },
17
+ typeOf(node) {
18
+ return isValidElement(node) ? node.type : void 0;
136
19
  },
137
- context: {
138
- configurable: true,
139
- set: bootstrap
20
+ propsOf(node) {
21
+ return isValidElement(node) ? node.props : {};
140
22
  }
141
23
  });
142
- function bootstrap(context) {
143
- const self = this.is;
144
- const render = (0, _expressive_state.unbind)(this.render);
145
- context = context.push(self);
146
- let ready = false;
147
- let active;
148
- function Render() {
149
- return render.call(active, self.props);
150
- }
151
- function AsComponent() {
152
- (0, src_state.useMount)((refresh) => {
153
- (0, _expressive_state.watch)(self, (current) => {
154
- active = current;
155
- if (ready) refresh();
156
- });
157
- return () => {
158
- self.set(null);
159
- context.pop();
160
- };
161
- });
162
- (0, react.useEffect)(() => {
163
- ready = true;
164
- }, []);
165
- const children = (0, react.createElement)(Layers.Provider, {
166
- value: context,
167
- children: (0, react.createElement)(react.Suspense, {
168
- fallback: active.fallback,
169
- name: String(self)
170
- }, (0, react.createElement)(Render))
171
- });
172
- return active.catch ? (0, react.createElement)(ErrorBoundary, {
173
- self,
174
- children
175
- }) : children;
176
- }
177
- Object.defineProperties(self, {
178
- context: {
179
- get: () => context,
180
- set() {}
24
+
25
+ //#endregion
26
+ //#region src/boundary.ts
27
+ /** In-flight render attempts by tree position, per ambient context.
28
+ * When one commits, older uncommitted attempts at its slot are provably dead. */
29
+ const SLOTS = /* @__PURE__ */ new WeakMap();
30
+ /**
31
+ * React's attempt lifecycle: fiber-keyed stacking so a superseded (uncommitted)
32
+ * render attempt at a tree position is discarded when a later one commits.
33
+ */
34
+ function dedupe(on, context) {
35
+ let slots = SLOTS.get(context.parent);
36
+ if (!slots) SLOTS.set(context.parent, slots = /* @__PURE__ */ new Map());
37
+ let slot = "";
38
+ for (let f = on._reactInternals; f; f = f.return) slot += (f.key ?? f.index) + ".";
39
+ let list = slots.get(slot);
40
+ if (!list) slots.set(slot, list = /* @__PURE__ */ new Set());
41
+ const entry = {
42
+ context,
43
+ commit() {
44
+ entry.committed = true;
45
+ for (const e of list) {
46
+ if (e === entry) break;
47
+ if (e.committed) continue;
48
+ e.context.pop();
49
+ list.delete(e);
50
+ }
181
51
  },
182
- render: { value: () => (0, react.createElement)(AsComponent) }
183
- });
52
+ remove() {
53
+ list.delete(entry);
54
+ }
55
+ };
56
+ list.add(entry);
57
+ return entry;
184
58
  }
185
- var ErrorBoundary = class extends react.default.Component {
186
- constructor(..._args) {
187
- super(..._args);
59
+ var ErrorBoundary = class extends React.Component {
60
+ constructor(props) {
61
+ super(props);
188
62
  this.state = {};
189
63
  this.recovering = false;
190
64
  }
@@ -209,97 +83,28 @@ var ErrorBoundary = class extends react.default.Component {
209
83
  return this.props.self.fallback;
210
84
  }
211
85
  };
212
- 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
- Component.on((self) => {
244
- let Type = self.constructor;
245
- while (Type !== Component) {
246
- const proto = Type.prototype;
247
- if (SEEN.has(Type)) break;
248
- SEEN.add(Type);
249
- subcomponents(proto);
250
- Type = Object.getPrototypeOf(Type);
251
- }
252
- subcomponents(self);
253
- });
254
86
 
255
87
  //#endregion
256
88
  //#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;
89
+ Object.defineProperty(Component$1.prototype, "isReactComponent", { value: true });
90
+ Object.assign(Runtime, {
91
+ dedupe,
92
+ ErrorBoundary,
93
+ createElement,
94
+ createContext,
95
+ useContext,
96
+ useEffect,
97
+ useState,
98
+ useRef,
99
+ Suspense,
100
+ ignore: [
101
+ "updater",
102
+ "refs",
103
+ "_reactInternals",
104
+ "_reactInternalInstance"
105
+ ]
106
+ });
261
107
 
262
108
  //#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
- });
109
+ export { Component, Consumer, Context, Observer, Provider, State, def, runtime_default as default, get, hot, ref, set, use };
305
110
  //# 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,MAAM,kCAAuBA,0BAAQ,KAAK;AAE1C,MAAM,OAAOA,0BAAQ;AAErB,0BAAQ,OAAO,UAAkB;AAC/B,KAAI,CAAC,MACH,KAAI;AACF,+BAAkB,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,gCAAq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SF,iBAAO,YAAYC;AACnB,iBAAO,WAAWC;AAClB,iBAAO,gBAAgBC;AACvB,iBAAO,SAASC"}
1
+ {"version":3,"file":"index.js","names":["Component"],"sources":["../src/jsx-runtime.ts","../src/boundary.ts","../src/index.ts"],"sourcesContent":["import { Children, isValidElement } from 'react';\nimport { Fragment, jsx, jsxs } from 'react/jsx-runtime';\nimport { host } from '@expressive/mvc/jsx-runtime';\n\nimport type { Component } from '@expressive/mvc';\nimport type { JSX as ReactJSX, ReactNode } from 'react';\n\ndeclare module '@expressive/mvc/jsx-runtime' {\n interface Host {\n node: ReactNode;\n intrinsics: ReactJSX.IntrinsicElements;\n }\n}\n\nhost({\n jsx,\n jsxs,\n Fragment,\n isElement: isValidElement,\n childrenOf(children): Component.Node[] {\n return Children.toArray(children as React.ReactNode);\n },\n typeOf(node){\n return isValidElement(node) ? node.type : undefined;\n },\n propsOf(node){\n return isValidElement(node) ? node.props as Record<string, unknown> : {};\n }\n});\n","import { Component } from '@expressive/mvc';\nimport React from 'react';\nimport { Context } from './context';\n\ninterface Entry {\n committed?: boolean;\n context: Context;\n commit: () => void;\n remove: () => void;\n};\n\n/** In-flight render attempts by tree position, per ambient context.\n * When one commits, older uncommitted attempts at its slot are provably dead. */\nconst SLOTS = new WeakMap<Context, Map<string, Set<Entry>>>();\n\n/**\n * React's attempt lifecycle: fiber-keyed stacking so a superseded (uncommitted)\n * render attempt at a tree position is discarded when a later one commits.\n */\nexport function dedupe(on: Component, context: Context) {\n let slots = SLOTS.get(context.parent!);\n if (!slots) SLOTS.set(context.parent!, (slots = new Map()));\n\n // key/index path to root: stable across render attempts of this element\n let slot = '';\n for (let f = (on as any)._reactInternals; f; f = f.return)\n slot += (f.key ?? f.index) + '.';\n\n let list = slots.get(slot);\n if (!list) slots.set(slot, (list = new Set()));\n\n const entry: Entry = {\n context,\n commit() {\n entry.committed = true;\n\n for (const e of list) {\n if (e === entry) break;\n if (e.committed) continue;\n e.context.pop();\n list.delete(e);\n }\n },\n remove() {\n list.delete(entry);\n }\n };\n\n list.add(entry);\n return entry;\n};\n\nexport class ErrorBoundary extends React.Component<{\n self: Component;\n children: React.ReactNode;\n}> {\n state = {} as { error?: Error };\n recovering = false;\n\n constructor(props: ErrorBoundary['props']) {\n super(props);\n }\n\n static getDerivedStateFromError(error: Error) {\n return { error };\n }\n\n componentDidCatch(error: Error) {\n const { self } = this.props;\n const { fallback } = self;\n const reset = (error?: Error) => {\n this.recovering = true;\n this.setState({ error });\n };\n\n Promise.resolve(self.catch!(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","import { Component } from '@expressive/mvc';\nimport {\n createContext,\n createElement,\n Suspense,\n useContext,\n useEffect,\n useRef,\n useState\n} from 'react';\n\nimport './jsx-runtime';\nimport { Runtime } from './runtime';\nimport { ErrorBoundary, dedupe } from './boundary';\n\n// React detects class components by this brand (preact reads `prototype.render`).\nObject.defineProperty(Component.prototype, 'isReactComponent', {\n value: true\n});\n\nObject.assign(Runtime, {\n dedupe,\n ErrorBoundary,\n createElement,\n createContext,\n useContext,\n useEffect,\n useState,\n useRef,\n Suspense,\n ignore: [\n 'updater',\n 'refs',\n '_reactInternals',\n '_reactInternalInstance'\n ]\n});\n\nexport { State, State as default, use } from './runtime';\nexport { Component, Context, Observer, def, get, ref, set, hot } from '@expressive/mvc';\nexport { Consumer, Provider } from './context';\n"],"mappings":";;;;;;;;AAcA,KAAK;CACH;CACA;CACA;CACA,WAAW;CACX,WAAW,UAA4B;AACrC,SAAO,SAAS,QAAQ,SAA4B;;CAEtD,OAAO,MAAK;AACV,SAAO,eAAe,KAAK,GAAG,KAAK,OAAO;;CAE5C,QAAQ,MAAK;AACX,SAAO,eAAe,KAAK,GAAG,KAAK,QAAmC,EAAE;;CAE3E,CAAC;;;;;;ACfF,MAAM,wBAA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AM;AACtC,SAAO,KAAK,MAAM,KAAK;;;;;;ACvE3B,OAAO,eAAeA,YAAU,WAAW,oBAAoB,EAC7D,OAAO,MACR,CAAC;AAEF,OAAO,OAAO,SAAS;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,QAAQ;EACN;EACA;EACA;EACA;EACD;CACF,CAAC"}
@@ -1,28 +1,24 @@
1
- import { State } from "@expressive/state";
1
+ import { i as provide, n as Context, r as Provider, t as Consumer } from "./context-B-HNZeaN.js";
2
+ import { Component, State as State$1 } from "@expressive/mvc";
2
3
 
3
- //#region src/state.d.ts
4
- declare const Pragma: {
5
- createElement(type: any, props?: any, ...children: any[]): any;
6
- useState<S>(initial: S | (() => S)): [S, (next: (previous: S) => S) => void];
7
- useEffect(effect: () => (() => void) | void, deps?: any[]): void;
8
- useRef<T>(initial: T): {
9
- current: T;
10
- };
11
- };
4
+ //#region src/component.d.ts
5
+ declare module '@expressive/mvc' {
6
+ interface Component {
7
+ /** @deprecated Only to satisfy host JSX. Use `this.get(State)` instead. */
8
+ readonly context: Context;
9
+ /** @deprecated Only to satisfy host JSX. Use `this.get()` instead. */
10
+ readonly state: State.Values<this>;
11
+ /** @deprecated Only to satisfy host JSX. Use `this.set({})` instead. */
12
+ setState: (state: any, callback?: () => void) => void;
13
+ /** @deprecated Only to satisfy host JSX. Use `this.set(key)` instead. */
14
+ forceUpdate: (callback?: () => void) => void;
15
+ }
16
+ }
17
+ //#endregion
18
+ //#region src/state.get.d.ts
12
19
  /** Type may not be undefined - instead will be null. */
13
20
  type NoVoid<T> = T extends undefined | void ? null : T;
14
- declare module '@expressive/state' {
15
- interface UseState extends State {
16
- /**
17
- * Optional hook called when State.use() is invoked within a React component.
18
- *
19
- * This is called *every render* of the component, and will intercept
20
- * arguments which would otherwise be passed into the State constructor.
21
- *
22
- * @param props Arguments passed to State.use().
23
- */
24
- use?(...props: any[]): Promise<void> | void;
25
- }
21
+ declare module '@expressive/mvc' {
26
22
  namespace State {
27
23
  type ForceRefresh = {
28
24
  /** Request a refresh for current component. */(): void;
@@ -46,6 +42,31 @@ declare module '@expressive/state' {
46
42
  };
47
43
  type GetFactory<T extends State, R> = (this: T, current: T, refresh: ForceRefresh) => R;
48
44
  type GetEffect<T extends State> = (this: T, current: T, refresh: ForceRefresh) => null;
45
+ /** Fetch instance of this class from context. */
46
+ function get<T extends State>(this: State.Extends<T>): T;
47
+ /** Fetch instance of this class optionally. */
48
+ function get<T extends State>(this: State.Extends<T>, required: false): T | undefined;
49
+ /** Fetch instance of this class from context. */
50
+ function get<T extends State>(this: State.Extends<T>, requireValues: true): Required<T>;
51
+ function get<T extends State, R>(this: State.Extends<T>, factory: GetFactory<T, Promise<R> | R>): NoVoid<R>;
52
+ function get<T extends State>(this: State.Extends<T>, factory: GetEffect<T>): null;
53
+ }
54
+ }
55
+ //#endregion
56
+ //#region src/state.use.d.ts
57
+ declare module '@expressive/mvc' {
58
+ interface UseState extends State {
59
+ /**
60
+ * Optional hook called when State.use() is invoked within a React component.
61
+ *
62
+ * This is called *every render* of the component, and will intercept
63
+ * arguments which would otherwise be passed into the State constructor.
64
+ *
65
+ * @param props Arguments passed to State.use().
66
+ */
67
+ use?(...props: any[]): Promise<void> | void;
68
+ }
69
+ namespace State {
49
70
  type UseArgs<T extends State> = T extends {
50
71
  use(...props: infer P): any;
51
72
  } ? P : State.Args<T>;
@@ -56,20 +77,38 @@ declare module '@expressive/state' {
56
77
  * @returns Managed instance of this State.
57
78
  */
58
79
  function use<T extends UseState>(this: State.Type<T>, ...args: UseArgs<T>): T;
59
- /** Fetch instance of this class from context. */
60
- function get<T extends State>(this: State.Extends<T>): T;
61
- /** Fetch instance of this class optionally. */
62
- function get<T extends State>(this: State.Extends<T>, required: false): T | undefined;
63
- /** Fetch instance of this class from context. */
64
- function get<T extends State>(this: State.Extends<T>, requireValues: true): Required<T>;
65
- function get<T extends State, R>(this: State.Extends<T>, factory: GetFactory<T, Promise<R> | R>): NoVoid<R>;
66
- function get<T extends State>(this: State.Extends<T>, factory: GetEffect<T>): null;
67
80
  }
68
81
  }
82
+ //#endregion
83
+ //#region src/runtime.d.ts
84
+ declare const Runtime: {
85
+ /** Host own-property keys to trap out of observed state; assigned by each adapter. */ignore: string[];
86
+ createElement(type: any, props?: any, ...children: any[]): any;
87
+ createContext<T>(value: T): any;
88
+ useContext(context: any): any;
89
+ useState<S>(initial: S | (() => S)): [S, (next: (previous: S) => S) => void];
90
+ useEffect(effect: () => (() => void) | void, deps?: any[]): void;
91
+ useRef<T>(initial: T): {
92
+ current: T;
93
+ }; /** Per-render-attempt lifecycle, set by each adapter (React stacks attempts; others no-op). */
94
+ dedupe(from: Component, context: Context): {
95
+ commit(): void;
96
+ remove(): void;
97
+ }; /** Host error-boundary component, wrapping a Component whose `catch` is set. */
98
+ ErrorBoundary: unknown;
99
+ Suspense: any;
100
+ };
101
+ declare function useFactory<T extends Function>(factory: () => T): T;
102
+ declare function useReady<T>(callback: () => void): void;
69
103
  /**
70
- * useEffect which tolerates react StrictMode double-invoking effects on mount.
104
+ * Mount-effect with a refreshable return value, safe under React StrictMode.
105
+ *
106
+ * @param callback Setup handler; receives a setter, must return a cleanup.
107
+ * @returns Latest value published via the setter (`undefined` until set).
71
108
  */
72
- declare function useMount(callback: (refresh: () => void) => (() => void) | void): void;
109
+ declare function useHook<T = void>(callback: (refresh: (next: T) => void) => () => void): T;
110
+ /** Subscribe to an existing observable instance within a component. */
111
+ declare function use<T extends object>(subject: T): T;
73
112
  //#endregion
74
- export { Pragma, State, useMount };
75
- //# sourceMappingURL=state.d.ts.map
113
+ export { Consumer, Context, Provider, Runtime, State$1 as State, provide, use, useFactory, useHook, useReady };
114
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1,74 @@
1
+ import { i as provide, n as Context, r as Provider, t as Consumer } from "./context-BfeYQmAX.js";
2
+ import { State, event, observer, watch } from "@expressive/mvc";
3
+
4
+ //#region src/runtime.ts
5
+ const Runtime = {};
6
+ function useFactory(factory) {
7
+ const ref = Runtime.useRef(null);
8
+ return ref.current || (ref.current = factory());
9
+ }
10
+ function useReady(callback) {
11
+ return Runtime.useEffect(() => void callback(), []);
12
+ }
13
+ /**
14
+ * Mount-effect with a refreshable return value, safe under React StrictMode.
15
+ *
16
+ * @param callback Setup handler; receives a setter, must return a cleanup.
17
+ * @returns Latest value published via the setter (`undefined` until set).
18
+ */
19
+ function useHook(callback) {
20
+ const { current } = Runtime.useRef({ rendered: 0 });
21
+ current.update = Runtime.useState(() => {
22
+ if (!current.rendered) current.unmount = callback((next) => {
23
+ current.output = next;
24
+ if (current.mounted) current.update?.((x) => x + 1);
25
+ else if (current.update) current.pending = true;
26
+ });
27
+ return current.rendered++;
28
+ })[1];
29
+ Runtime.useEffect(() => {
30
+ current.mounted = true;
31
+ if (current.pending) {
32
+ current.pending = false;
33
+ current.update((x) => x + 1);
34
+ }
35
+ return () => {
36
+ if (--current.rendered < 1) current.unmount();
37
+ };
38
+ }, []);
39
+ return current.output;
40
+ }
41
+ /** Subscribe to an existing observable instance within a component. */
42
+ function use(subject) {
43
+ const { current } = Runtime.useRef({
44
+ mounted: 0,
45
+ proxy: subject
46
+ });
47
+ const update = Runtime.useState(() => current.mounted++)[1];
48
+ if (current.source !== subject) {
49
+ const status = observer(subject);
50
+ if (status === void 0) throw new Error("Provided object is not observable.");
51
+ current.unwatch?.();
52
+ current.source = subject;
53
+ if (status === null) {
54
+ current.unwatch = void 0;
55
+ current.proxy = subject;
56
+ } else {
57
+ if (!status.ready) event(subject);
58
+ let init = true;
59
+ current.unwatch = watch(subject, (next, changed) => {
60
+ current.proxy = next;
61
+ if (changed.length && !init) update((x) => x + 1);
62
+ });
63
+ init = false;
64
+ }
65
+ }
66
+ Runtime.useEffect(() => () => {
67
+ if (--current.mounted < 1) current.unwatch?.();
68
+ }, []);
69
+ return current.proxy;
70
+ }
71
+
72
+ //#endregion
73
+ export { Consumer, Context, Provider, Runtime, State, provide, use, useFactory, useHook, useReady };
74
+ //# sourceMappingURL=runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.js","names":[],"sources":["../src/runtime.ts"],"sourcesContent":["import { event, watch, observer } from '@expressive/mvc';\nimport type { Component } from '@expressive/mvc';\nimport type { Context } from './context';\nimport './component';\nimport './state.get';\nimport './state.use';\n\nexport { State } from '@expressive/mvc';\nexport { Consumer, Provider, Context, provide } from './context';\n\nexport const Runtime = {} as {\n /** Host own-property keys to trap out of observed state; assigned by each adapter. */\n ignore: string[];\n createElement(type: any, props?: any, ...children: any[]): any;\n createContext<T>(value: T): any;\n useContext(context: any): any;\n useState<S>(initial: S | (() => S)): [S, (next: (previous: S) => S) => void];\n useEffect(effect: () => (() => void) | void, deps?: any[]): void;\n useRef<T>(initial: T): { current: T };\n /** Per-render-attempt lifecycle, set by each adapter (React stacks attempts; others no-op). */\n dedupe(from: Component, context: Context): { commit(): void; remove(): void };\n /** Host error-boundary component, wrapping a Component whose `catch` is set. */\n ErrorBoundary: unknown;\n Suspense: any;\n};\n\nexport function useFactory<T extends Function>(factory: () => T) {\n const ref = Runtime.useRef<T | null>(null);\n return ref.current || (ref.current = factory());\n}\n\nexport function useReady<T>(callback: () => void) {\n return Runtime.useEffect(() => void callback(), []);\n}\n\n/**\n * Mount-effect with a refreshable return value, safe under React StrictMode.\n *\n * @param callback Setup handler; receives a setter, must return a cleanup.\n * @returns Latest value published via the setter (`undefined` until set).\n */\nexport function useHook<T = void>(\n callback: (refresh: (next: T) => void) => () => void\n) {\n const { current } = Runtime.useRef(\n { rendered: 0 } as {\n rendered: number;\n mounted?: boolean;\n pending?: boolean;\n unmount: () => void;\n update?: (next: (previous: number) => number) => void;\n output: T;\n }\n );\n\n current.update = Runtime.useState(() => {\n if (!current.rendered)\n current.unmount = callback((next) => {\n current.output = next;\n if (current.mounted) current.update?.((x) => x + 1);\n else if (current.update) current.pending = true;\n });\n\n return current.rendered++;\n })[1];\n\n Runtime.useEffect(() => {\n current.mounted = true;\n if (current.pending) {\n current.pending = false;\n current.update!((x) => x + 1);\n }\n return () => {\n if (--current.rendered < 1) current.unmount();\n }\n }, []);\n\n return current.output;\n}\n\n/** Subscribe to an existing observable instance within a component. */\nexport function use<T extends object>(subject: T) {\n const { current } = Runtime.useRef<{\n proxy: T;\n source?: T;\n mounted: number;\n unwatch?: () => void;\n }>({ mounted: 0, proxy: subject });\n\n const update = Runtime.useState(() => current.mounted++)[1];\n\n if (current.source !== subject) {\n const status = observer(subject);\n\n if (status === undefined)\n throw new Error('Provided object is not observable.');\n\n current.unwatch?.();\n current.source = subject;\n\n if (status === null) {\n current.unwatch = undefined;\n current.proxy = subject;\n } else {\n if (!status.ready) event(subject);\n\n let init = true;\n\n current.unwatch = watch(subject, (next, changed) => {\n current.proxy = next;\n if (changed.length && !init)\n update((x) => x + 1);\n });\n\n init = false;\n }\n }\n\n Runtime.useEffect(() => () => {\n if (--current.mounted < 1) current.unwatch?.();\n }, []);\n\n return current.proxy;\n}\n"],"mappings":";;;;AAUA,MAAa,UAAU,EAAE;AAgBzB,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,UACA;CACA,MAAM,EAAE,YAAY,QAAQ,OAC1B,EAAE,UAAU,GAAG,CAQhB;AAED,SAAQ,SAAS,QAAQ,eAAe;AACtC,MAAI,CAAC,QAAQ,SACX,SAAQ,UAAU,UAAU,SAAS;AACnC,WAAQ,SAAS;AACjB,OAAI,QAAQ,QAAS,SAAQ,UAAU,MAAM,IAAI,EAAE;YAC1C,QAAQ,OAAQ,SAAQ,UAAU;IAC3C;AAEJ,SAAO,QAAQ;GACf,CAAC;AAEH,SAAQ,gBAAgB;AACtB,UAAQ,UAAU;AAClB,MAAI,QAAQ,SAAS;AACnB,WAA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