@expressive/react 0.74.1 → 0.75.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.
@@ -0,0 +1,185 @@
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 { unbind, watch } from "@expressive/state";
5
+
6
+ //#region src/component.ts
7
+ const PENDING = /* @__PURE__ */ new WeakMap();
8
+ var Component = class extends State {
9
+ static {
10
+ this.contextType = Layers;
11
+ }
12
+ constructor(nextProps, ...rest) {
13
+ const { is, ...props } = nextProps;
14
+ rest = rest.filter((x) => !(x instanceof Context$1));
15
+ super(props, rest, is && ((x) => void is(x)));
16
+ this.fallback = null;
17
+ const existing = PENDING.get(nextProps);
18
+ if (existing) return existing;
19
+ PENDING.set(nextProps, this);
20
+ this.props = nextProps;
21
+ this.set("props", () => {
22
+ this.set(this.props);
23
+ });
24
+ }
25
+ /**
26
+ * Output for this component. Override to define custom JSX.
27
+ *
28
+ * Properties accessed via `this` are reactive and will trigger a render when , in addition to props.
29
+ *
30
+ * Accepts optional parameter to receive extra props
31
+ * from JSX, beyond those merged to state properties.
32
+ *
33
+ * To declare extra props use `props = {} as { ... }` with expected shape.
34
+ * A default is required to satisfy TypeScript but safely ignored.
35
+ *
36
+ * ```ts
37
+ * render(props = {} as { label: string }) {
38
+ * return <span>{props.label}</span>;
39
+ * }
40
+ * ```
41
+ * Usable as:
42
+ * ```tsx
43
+ * <MyComponent label="Hello" />
44
+ * ```
45
+ *
46
+ * These must be compatible with State-derived properties, or be unused.
47
+ * Props you declare as not-optional will be required by the JSX element.
48
+ *
49
+ * Without a parameter, children are accepted by default and passed through provider.
50
+ */
51
+ render(props) {
52
+ return this.props.children || null;
53
+ }
54
+ };
55
+ Object.defineProperties(Component.prototype, {
56
+ isReactComponent: { get: () => true },
57
+ state: {
58
+ get() {
59
+ return this.get();
60
+ },
61
+ set() {}
62
+ },
63
+ context: {
64
+ configurable: true,
65
+ set: bootstrap
66
+ }
67
+ });
68
+ function bootstrap(context) {
69
+ const self = this.is;
70
+ const render = unbind(this.render);
71
+ context = context.push(self);
72
+ let ready = false;
73
+ let active;
74
+ function Render() {
75
+ return render.call(active, self.props);
76
+ }
77
+ function AsComponent() {
78
+ useMount((refresh) => {
79
+ watch(self, (current) => {
80
+ active = current;
81
+ if (ready) refresh();
82
+ });
83
+ return () => {
84
+ self.set(null);
85
+ context.pop();
86
+ };
87
+ });
88
+ useEffect(() => {
89
+ ready = true;
90
+ }, []);
91
+ const children = createElement(Layers.Provider, {
92
+ value: context,
93
+ children: createElement(Suspense, {
94
+ fallback: active.fallback,
95
+ name: String(self)
96
+ }, createElement(Render))
97
+ });
98
+ if (active.catch) return createElement(ErrorBoundary, {
99
+ fallback: () => self.fallback,
100
+ onError(error, reset) {
101
+ const { fallback } = self;
102
+ Promise.resolve(self.catch(error)).then(() => ready && reset(), reset).finally(() => self.set({ fallback }, true));
103
+ },
104
+ children
105
+ });
106
+ return children;
107
+ }
108
+ Object.defineProperties(self, {
109
+ context: {
110
+ get: () => context,
111
+ set() {}
112
+ },
113
+ render: { value: () => createElement(AsComponent) }
114
+ });
115
+ }
116
+ var ErrorBoundary = class extends React.Component {
117
+ constructor(..._args) {
118
+ super(..._args);
119
+ this.state = {};
120
+ this.recovering = false;
121
+ }
122
+ static getDerivedStateFromError(error) {
123
+ return { error };
124
+ }
125
+ componentDidCatch(error) {
126
+ this.props.onError(error, (error) => {
127
+ this.recovering = true;
128
+ this.setState({ error });
129
+ });
130
+ }
131
+ componentDidUpdate() {
132
+ this.recovering = false;
133
+ }
134
+ render() {
135
+ if (!this.state.error) return this.props.children;
136
+ if (this.recovering) throw this.state.error;
137
+ return this.props.fallback();
138
+ }
139
+ };
140
+ const SEEN = /* @__PURE__ */ new WeakSet();
141
+ function subcomponents(proto) {
142
+ for (const key of Object.getOwnPropertyNames(proto)) {
143
+ if (!/^[A-Z]/.test(key)) continue;
144
+ const { get, value } = Object.getOwnPropertyDescriptor(proto, key);
145
+ if (!get && typeof value !== "function") continue;
146
+ Object.defineProperty(proto, key, {
147
+ configurable: true,
148
+ get() {
149
+ const self = this.is;
150
+ let render = unbind(get ? get.call(this) : value);
151
+ function Sub(props) {
152
+ const ref = useRef(null);
153
+ useMount((refresh) => watch(self, (current) => {
154
+ ref.current = current;
155
+ refresh();
156
+ }));
157
+ return render.call(ref.current, props);
158
+ }
159
+ Object.defineProperty(self, key, {
160
+ configurable: true,
161
+ get: () => Sub,
162
+ set(fn) {
163
+ render = fn;
164
+ }
165
+ });
166
+ return Sub;
167
+ }
168
+ });
169
+ }
170
+ }
171
+ Component.on((self) => {
172
+ let Type = self.constructor;
173
+ while (Type !== Component) {
174
+ const proto = Type.prototype;
175
+ if (SEEN.has(Type)) break;
176
+ SEEN.add(Type);
177
+ subcomponents(proto);
178
+ Type = Object.getPrototypeOf(Type);
179
+ }
180
+ subcomponents(self);
181
+ });
182
+
183
+ //#endregion
184
+ export { Component };
185
+ //# sourceMappingURL=component.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"component.js","names":["Context"],"sources":["../../src/component.ts"],"sourcesContent":["import { watch, unbind } 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>();\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 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 = 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: any) => void is(x)));\n\n const existing = PENDING.get(nextProps);\n if (existing) return existing;\n PENDING.set(nextProps, this);\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 if (active.catch)\n return createElement(ErrorBoundary, {\n fallback: () => self.fallback,\n onError(error: Error, reset: (failed?: Error) => void) {\n const { fallback } = self;\n Promise.resolve(self.catch!(error))\n .then(() => ready && reset(), reset)\n .finally(() => self.set({ fallback }, true));\n },\n children\n });\n\n return 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 children: ReactNode;\n fallback: () => ReactNode;\n onError: (error: Error, reset: (failed?: Error) => void) => void;\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 this.props.onError(error, (error) => {\n this.recovering = true;\n this.setState({ error });\n });\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.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;AA8BhD,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,MAAW,KAAK,GAAG,EAAE,EAAE;kBAL9B;EAOpB,MAAM,WAAW,QAAQ,IAAI,UAAU;AACvC,MAAI,SAAU,QAAO;AACrB,UAAQ,IAAI,WAAW,KAAK;AAE5B,OAAK,QAAQ;AACb,OAAK,IAAI,eAAe;AACtB,QAAK,IAAI,KAAK,MAAY;IAC1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BJ,OAAO,OAAuB;AAC5B,SAAO,KAAK,MAAM,YAAY;;;AAelC,OAAO,iBAA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AK;EACnB"}
@@ -1,38 +1,42 @@
1
- import { Context } from "@expressive/state";
2
- import { Suspense, createContext, createElement, useContext, useEffect, useMemo } from "react";
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";
3
4
 
4
5
  //#region src/context.ts
5
- const Layers = createContext(new Context());
6
- Context.use = (create) => {
7
- const ambient = useContext(Layers);
8
- return create ? useMemo(() => ambient.push(), [ambient]) : ambient;
6
+ const Layers = createContext(new Context$1());
7
+ const _get = Context$1.get;
8
+ Context$1.get = (state) => {
9
+ if (state) return _get(state);
10
+ try {
11
+ return useContext(Layers);
12
+ } catch {
13
+ return Context$1.root;
14
+ }
9
15
  };
10
16
  function Consumer(props) {
11
17
  return props.for.get((i) => props.children(i));
12
18
  }
13
19
  function Provider(props) {
14
- const context = Context.use(true);
15
- useEffect(() => () => context.pop(), [context]);
16
- context.use(props.for, (state) => {
17
- if (props.forEach) {
18
- const cleanup = props.forEach(state);
19
- if (cleanup) state.set(cleanup, null);
20
- }
21
- });
22
- return provide(context, props.children, props.fallback, props.name);
23
- }
24
- function provide(context, children, fallback, name) {
20
+ const ambient = useContext(Layers);
21
+ const ref = useRef(null);
22
+ const context = ref.current || (ref.current = new Context$1(ambient));
23
+ let { for: input, children, fallback, name, ...rest } = props;
24
+ context.set(input, (added) => rest.is?.(added));
25
+ if (Object.keys(rest).length) {
26
+ if (State$1.is(input)) input = context.get(input);
27
+ if (input instanceof State$1) input.set(rest);
28
+ }
29
+ useMount(() => () => context.pop());
25
30
  if (fallback !== void 0) children = createElement(Suspense, {
26
31
  fallback,
27
32
  name
28
33
  }, children);
29
34
  return createElement(Layers.Provider, {
30
- key: context.id,
31
35
  value: context,
32
36
  children
33
37
  });
34
38
  }
35
39
 
36
40
  //#endregion
37
- export { Consumer, Layers, Provider, provide };
41
+ export { Consumer, Context$1 as Context, Layers, Provider };
38
42
  //# sourceMappingURL=context.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../../src/context.ts"],"sourcesContent":["import State, { Context } from '@expressive/state';\nimport {\n createContext,\n createElement,\n ReactNode,\n Suspense,\n useContext,\n useEffect,\n useMemo\n} from 'react';\n\nexport const Layers = createContext(new Context());\n\ndeclare module '@expressive/state' {\n namespace Context {\n function use(create?: true): Context;\n function use(create: boolean): Context | null | undefined;\n }\n}\n\nContext.use = (create?: boolean) => {\n const ambient = useContext(Layers);\n\n return create ? useMemo(() => ambient.push(), [ambient]) : ambient;\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 interface Props<T extends State> {\n /** State or group of States to provide to descendant Consumers. */\n for: Context.Accept<T>;\n\n /**\n * Callback to run for each provided State.\n */\n forEach?: Context.Expect<T>;\n\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\nfunction Provider<T extends State>(props: Provider.Props<T>) {\n const context = Context.use(true);\n\n useEffect(() => () => context.pop(), [context]);\n\n context.use(props.for, (state) => {\n if (props.forEach) {\n const cleanup = props.forEach(state);\n\n if (cleanup) state.set(cleanup, null);\n }\n });\n\n return provide(context, props.children, props.fallback, props.name);\n}\n\nfunction provide(\n context: Context,\n children: ReactNode,\n fallback?: ReactNode,\n name?: string | undefined\n): ReactNode {\n if (fallback !== undefined)\n children = createElement(Suspense, { fallback, name }, children);\n\n return createElement(Layers.Provider, {\n key: context.id,\n value: context,\n children\n });\n}\n\nexport { Consumer, Provider, provide };\n"],"mappings":";;;;AAWA,MAAa,SAAS,cAAc,IAAI,SAAS,CAAC;AASlD,QAAQ,OAAO,WAAqB;CAClC,MAAM,UAAU,WAAW,OAAO;AAElC,QAAO,SAAS,cAAc,QAAQ,MAAM,EAAE,CAAC,QAAQ,CAAC,GAAG;;AAmB7D,SAAS,SAA0B,OAA0B;AAC3D,QAAO,MAAM,IAAI,KAAK,MAAM,MAAM,SAAS,EAAE,CAAC;;AA6BhD,SAAS,SAA0B,OAA0B;CAC3D,MAAM,UAAU,QAAQ,IAAI,KAAK;AAEjC,uBAAsB,QAAQ,KAAK,EAAE,CAAC,QAAQ,CAAC;AAE/C,SAAQ,IAAI,MAAM,MAAM,UAAU;AAChC,MAAI,MAAM,SAAS;GACjB,MAAM,UAAU,MAAM,QAAQ,MAAM;AAEpC,OAAI,QAAS,OAAM,IAAI,SAAS,KAAK;;GAEvC;AAEF,QAAO,QAAQ,SAAS,MAAM,UAAU,MAAM,UAAU,MAAM,KAAK;;AAGrE,SAAS,QACP,SACA,UACA,UACA,MACW;AACX,KAAI,aAAa,OACf,YAAW,cAAc,UAAU;EAAE;EAAU;EAAM,EAAE,SAAS;AAElE,QAAO,cAAc,OAAO,UAAU;EACpC,KAAK,QAAQ;EACb,OAAO;EACP;EACD,CAAC"}
1
+ {"version":3,"file":"context.js","names":["Context","State"],"sources":["../../src/context.ts"],"sourcesContent":["import { State, Context } from '@expressive/state';\nimport {\n createContext,\n createElement,\n ReactNode,\n Suspense,\n useContext,\n useRef\n} from 'react';\nimport { useMount } from './state';\n\nconst Layers = createContext(new Context());\n\nconst _get = Context.get;\n\nContext.get = (state?: State) => {\n if (state) return _get(state);\n try {\n return useContext(Layers);\n } catch {\n return Context.root;\n }\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":";;;;;AAWA,MAAM,SAAS,cAAc,IAAIA,WAAS,CAAC;AAE3C,MAAM,OAAOA,UAAQ;AAErB,UAAQ,OAAO,UAAkB;AAC/B,KAAI,MAAO,QAAO,KAAK,MAAM;AAC7B,KAAI;AACF,SAAO,WAAW,OAAO;SACnB;AACN,SAAOA,UAAQ;;;AAoBnB,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 CHANGED
@@ -1,16 +1,15 @@
1
1
  import { Consumer, Provider } from "./context.js";
2
- import { Context, Observable, State, get, ref, set, use } from "@expressive/state";
3
- import { Fragment, createElement, createElement as createElement$1, useEffect, useState } from "react";
4
- import { Pragma, ReactState } from "./state";
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";
5
6
 
6
7
  //#region src/index.ts
7
8
  Pragma.useEffect = useEffect;
8
9
  Pragma.useState = useState;
9
- Pragma.createElement = createElement$1;
10
- State.get = ReactState.get;
11
- State.use = ReactState.use;
12
- State.as = ReactState.as;
10
+ Pragma.createElement = createElement;
11
+ Pragma.useRef = useRef;
13
12
 
14
13
  //#endregion
15
- export { Consumer, Context, Fragment, Observable, Pragma, Provider, ReactState as State, ReactState as default, createElement, get, ref, set, use };
14
+ export { Component, Consumer, Context, Observable, Provider, State, State as default, def, get, ref, set };
16
15
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["createElement"],"sources":["../../src/index.ts"],"sourcesContent":["import { State } from '@expressive/state';\n\nimport { createElement, useEffect, useState } from 'react';\n\nimport { ReactState, Pragma } from './state';\n\nPragma.useEffect = useEffect;\nPragma.useState = useState;\nPragma.createElement = createElement;\n\n/**\n * Augmented State namespace to include ReactState hooks as static methods.\n *\n * This retroactively adds React support to agnostic State defined\n * by component libraries which import `@expressive/state` directly.\n */\ndeclare module '@expressive/state' {\n namespace State {\n export import as = ReactState.as;\n export import get = ReactState.get;\n export import use = ReactState.use;\n }\n}\n\nState.get = ReactState.get;\nState.use = ReactState.use;\nState.as = ReactState.as;\n\nexport { ReactState as State, ReactState as default };\nexport { Context, Observable, get, use, ref, set } from '@expressive/state';\nexport { Consumer, Provider } from './context';\nexport { Fragment, createElement } from 'react';\nexport { Pragma };\n"],"mappings":";;;;;;AAMA,OAAO,YAAY;AACnB,OAAO,WAAW;AAClB,OAAO,gBAAgBA;AAgBvB,MAAM,MAAM,WAAW;AACvB,MAAM,MAAM,WAAW;AACvB,MAAM,KAAK,WAAW"}
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 CHANGED
@@ -1,173 +1,138 @@
1
- import { Layers, provide } from "./context.js";
2
- import { Context, State, event, watch } from "@expressive/state";
1
+ import { Context, State, watch } from "@expressive/state";
3
2
 
4
3
  //#region src/state.ts
5
4
  const Pragma = {};
6
- const OUTER = /* @__PURE__ */ new WeakMap();
7
- const PROPS = /* @__PURE__ */ new WeakMap();
8
- var ReactState = class ReactState extends State {
9
- /**
10
- * Create and manage instance of this State within React component.
11
- *
12
- * @param args Arguments to pass to constructor or `use` method (if defined).
13
- * @returns Managed instance of this State.
14
- */
15
- static use(...args) {
16
- const ambient = Context.use();
17
- const state = Pragma.useState(() => {
18
- let ready;
19
- let active;
20
- let use = (...args) => Promise.all(args.flat().map((arg) => typeof arg == "object" && instance.set(arg)));
21
- const instance = new this((x) => {
22
- if (x instanceof ReactState && x.use) {
23
- use = x.use?.bind(x);
24
- use(...args);
25
- } else return args;
26
- });
27
- const context = ambient.push(instance);
28
- watch(instance, (current) => {
29
- active = current;
30
- if (ready) state[1]((x) => x.bind(null));
31
- });
32
- function didMount() {
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(() => {
33
21
  ready = true;
22
+ }, []);
23
+ useMount((refresh) => {
24
+ watch(instance, (current) => {
25
+ active = current;
26
+ if (ready) refresh();
27
+ });
34
28
  return () => {
35
29
  context.pop();
36
30
  instance.set(null);
37
31
  };
32
+ });
33
+ if (ready) {
34
+ ready = false;
35
+ Promise.resolve(use(...args)).finally(() => {
36
+ ready = true;
37
+ });
38
38
  }
39
- return (...args) => {
40
- Pragma.useEffect(didMount, []);
41
- if (ready) {
42
- ready = false;
43
- Promise.resolve(use(...args)).finally(() => ready = true);
44
- }
45
- return active;
46
- };
47
- });
48
- return state[0](...args);
39
+ return active;
40
+ };
49
41
  }
50
- static get(argument) {
51
- const context = Context.use();
52
- const state = Pragma.useState(() => {
53
- const instance = context.get(this);
54
- if (!instance) if (argument === false) return () => void 0;
55
- else throw new Error(`Could not find ${this} in context.`);
56
- let ready;
57
- let value;
58
- function render() {
59
- state[1]((x) => x.bind(null));
60
- }
61
- function refresh(action) {
62
- if (typeof action == "function") action = action();
63
- render();
64
- if (action) return action.finally(render);
65
- }
66
- const unwatch = watch(instance, (current) => {
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) => {
67
72
  if (typeof argument === "function") {
68
73
  const next = argument.call(current, current, refresh);
69
74
  if (next === value) return;
70
75
  value = next;
71
76
  } else value = current;
72
- if (ready) render();
77
+ if (changed.length) update();
73
78
  }, argument === true);
74
- if (value instanceof Promise) {
75
- let error;
76
- unwatch();
77
- value.then((x) => value = x, (e) => error = e).finally(render);
78
- value = null;
79
- return () => {
80
- if (error) throw error;
81
- return value === void 0 ? null : value;
82
- };
83
- }
84
- if (value === null) {
85
- unwatch();
86
- return () => null;
87
- }
88
- function onMount() {
89
- ready = true;
90
- return unwatch;
79
+ if (mounted) {
80
+ pending = true;
81
+ queueMicrotask(() => pending && update());
91
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;
92
95
  return () => {
93
- Pragma.useEffect(onMount, []);
96
+ if (error) throw error;
94
97
  return value === void 0 ? null : value;
95
98
  };
96
- });
97
- return state[0]();
98
- }
99
- static as(argument) {
100
- const Type = this;
101
- const render = typeof argument === "function" ? argument : void 0;
102
- class ReactType extends Type {
103
- static {
104
- this.contextType = Layers;
105
- }
106
- get props() {
107
- return PROPS.get(this);
108
- }
109
- set props(props) {
110
- PROPS.set(this, props);
111
- this.set(props);
112
- }
113
- get context() {
114
- return Context.get(this);
115
- }
116
- set context(context) {
117
- if (OUTER.get(this) === context) return;
118
- OUTER.set(this, context);
119
- context.push(this);
120
- }
121
- get state() {
122
- return this.get();
123
- }
124
- set state(_state) {}
125
- constructor(nextProps, ...rest) {
126
- const { is } = nextProps;
127
- const defaults = typeof argument === "object" ? argument : {};
128
- if (rest[0] instanceof Context) rest.shift();
129
- super(nextProps, defaults, is, rest);
130
- this.fallback = void 0;
131
- PROPS.set(this, nextProps);
132
- if (render) {
133
- const Self = Render.bind(this, render);
134
- this.render = () => Pragma.createElement(Self);
135
- } else if (!this.render) this.render = () => provide(this.context, this.props.children || null, this.props.fallback, String(this));
136
- }
137
99
  }
138
- Object.defineProperty(ReactType, "name", { value: "React" + this.name });
139
- Object.defineProperty(ReactType.prototype, "isReactComponent", { get: () => true });
140
- return ReactType;
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
+ };
141
112
  }
142
113
  };
143
- function Render(render) {
144
- const state = Pragma.useState(() => {
145
- event(this);
146
- const { context } = this;
147
- let ready;
148
- let active;
149
- watch(this, (current) => {
150
- active = current;
151
- if (ready) state[1]((x) => x.bind(null));
152
- });
153
- const didMount = () => {
154
- ready = true;
155
- return () => {
156
- context.pop();
157
- this.set(null);
158
- };
159
- };
160
- const View = () => render.call(active, this.props, active);
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;
161
130
  return () => {
162
- ready = false;
163
- Pragma.useEffect(didMount, []);
164
- setTimeout(() => ready = true, 0);
165
- return provide(context, Pragma.createElement(View), this.props.fallback, String(this));
131
+ if (!--current.mounts) current.unmount?.();
166
132
  };
167
- });
168
- return state[0]();
133
+ }, []);
169
134
  }
170
135
 
171
136
  //#endregion
172
- export { Pragma, ReactState };
137
+ export { Pragma, State, useMount };
173
138
  //# sourceMappingURL=state.js.map