@expressive/react 0.71.0 → 0.73.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.
@@ -1,93 +1,29 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/jsx-runtime.ts
31
- var jsx_runtime_exports = {};
32
- __export(jsx_runtime_exports, {
33
- Fragment: () => import_react2.Fragment,
34
- compat: () => compat,
35
- jsx: () => jsx,
36
- jsxs: () => jsxs
37
- });
38
- module.exports = __toCommonJS(jsx_runtime_exports);
39
- var import_mvc2 = require("@expressive/mvc");
40
- var import_jsx_runtime = __toESM(require("react/jsx-runtime"));
1
+ const require_chunk = require('./chunk-kSYXY2_d.js');
2
+ let _expressive_mvc = require("@expressive/mvc");
3
+ _expressive_mvc = require_chunk.__toESM(_expressive_mvc);
4
+ let react = require("react");
5
+ let src_state = require("./state");
6
+ let react_jsx_runtime = require("react/jsx-runtime");
7
+ react_jsx_runtime = require_chunk.__toESM(react_jsx_runtime);
41
8
 
42
- // src/context.ts
43
- var import_mvc = __toESM(require("@expressive/mvc"));
44
- var import_react = require("react");
45
- var Lookup = (0, import_react.createContext)(new import_mvc.Context());
46
- import_mvc.Context.use = (create) => {
47
- const ambient = (0, import_react.useContext)(Lookup);
48
- return create ? (0, import_react.useMemo)(() => ambient.push(), []) : ambient;
49
- };
50
- function createProvider(context, children, fallback, name) {
51
- if (context instanceof import_mvc.default)
52
- context = import_mvc.Context.get(context);
53
- const element = (0, import_react.createElement)(Lookup.Provider, {
54
- key: context.id,
55
- value: context,
56
- children
57
- });
58
- return fallback !== void 0 ? (0, import_react.createElement)(import_react.Suspense, { fallback, name }, element) : element;
9
+ //#region src/jsx-runtime.ts
10
+ const RENDER = /* @__PURE__ */ new WeakMap();
11
+ function patch(type, ...args) {
12
+ if (_expressive_mvc.default.is(type)) if (RENDER.has(type)) type = RENDER.get(type);
13
+ else RENDER.set(type, type = src_state.Render.bind(type));
14
+ return this(type, ...args);
59
15
  }
16
+ const jsx = patch.bind(react_jsx_runtime.default.jsx);
17
+ const jsxs = patch.bind(react_jsx_runtime.default.jsxs);
60
18
 
61
- // src/jsx-runtime.ts
62
- var import_react2 = require("react");
63
- function MC({ is, ...props }) {
64
- const model = this.use((self) => {
65
- self.set(props);
66
- if (is)
67
- is(self);
68
- });
69
- model.set(props);
70
- const render = import_mvc2.METHOD.get(model.render) || props.render || model.render;
71
- const children = render ? render.call(model, props, model) : props.children;
72
- return createProvider(model, children, props.fallback || model.fallback, String(model));
73
- }
74
- var RENDER = /* @__PURE__ */ new WeakMap();
75
- function compat(type, ...args) {
76
- if (typeof type == "function") {
77
- if (RENDER.has(type))
78
- type = RENDER.get(type);
79
- else if (typeof type == "function")
80
- RENDER.set(type, type = type.prototype instanceof import_mvc2.Model ? MC.bind(type) : type);
19
+ //#endregion
20
+ Object.defineProperty(exports, 'Fragment', {
21
+ enumerable: true,
22
+ get: function () {
23
+ return react.Fragment;
81
24
  }
82
- return this(type, ...args);
83
- }
84
- var jsx = compat.bind(import_jsx_runtime.default.jsx);
85
- var jsxs = compat.bind(import_jsx_runtime.default.jsxs);
86
- // Annotate the CommonJS export names for ESM import in node:
87
- 0 && (module.exports = {
88
- Fragment,
89
- compat,
90
- jsx,
91
- jsxs
92
25
  });
26
+ exports.jsx = jsx;
27
+ exports.jsxs = jsxs;
28
+ exports.patch = patch;
93
29
  //# sourceMappingURL=jsx-runtime.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/jsx-runtime.ts","../src/context.ts"],"sourcesContent":["import { METHOD, Model } from '@expressive/mvc';\nimport React from 'react';\nimport Runtime from 'react/jsx-runtime';\n\nimport { createProvider } from './context';\n\ndeclare module \"@expressive/mvc\" {\n namespace Model {\n /**\n * Use this to define a component which wraps a Model, intended to forward props.\n * This is to be used explicity, in JSDoc types or type annotations.\n * The second type parameter is additional props the component expects to receive.\n * \n * @example\n * ```tsx\n * import { Model } from '@expressive/react';\n * \n * class MyModel extends Model {\n * foo: string;\n * bar: number;\n * }\n * \n * const MyComponent: Model.FC<MyModel, { label: string }> =\n * ({ label, ...rest }) => (\n * <div>\n * <span>{label}</span>\n * <MyModel {...rest} />\n * </div>\n * );\n * ```\n */\n type FC<T extends Model, P extends {} = {}> = React.FC<Props<T> & P>;\n }\n}\n\nexport declare namespace JSX {\n type ElementType = \n | Model.Type<Model.Compat>\n | React.JSX.ElementType\n | ((props: {}, ref?: any) => void);\n\n type LibraryManagedAttributes<C, P> =\n // For normal class components, pull from props property explicitly because we dorked up ElementAttributesProperty.\n C extends new (...args: any[]) => { props: infer U } ? U :\n C extends Model.Type<infer U> ? Model.Props<U> :\n React.JSX.LibraryManagedAttributes<C, P>;\n\n interface Element extends React.JSX.Element {}\n interface ElementClass extends React.JSX.ElementClass {}\n // This is a hack to make TypeScript happy - React one insists on `props` property existing.\n // I await the \"Find Out\" phase of this experiment in git issues.\n interface ElementAttributesProperty {}\n interface ElementChildrenAttribute extends React.JSX.ElementChildrenAttribute {}\n\n interface IntrinsicAttributes extends React.JSX.IntrinsicAttributes {}\n interface IntrinsicClassAttributes<T> extends React.JSX.IntrinsicClassAttributes<T> {}\n interface IntrinsicElements extends React.JSX.IntrinsicElements {}\n}\n\nfunction MC<T extends Model.Compat>(\n this: Model.Init<T>,\n { is, ...props }: Model.Props<T>\n) {\n const model = this.use((self) => {\n self.set(props as Model.Assign<T>);\n\n if(is)\n is(self);\n });\n\n model.set(props as Model.Assign<T>);\n\n const render = METHOD.get(model.render) || props.render || model.render;\n const children = render\n ? render.call(model, props as Model.HasProps<T>, model)\n : props.children;\n\n return createProvider(model, children, props.fallback || model.fallback, String(model));\n}\n\nconst RENDER = new WeakMap<Function, React.ComponentType>();\n\nexport function compat(\n this: (type: React.ElementType, ...args: any[]) => React.ReactElement,\n type: React.ElementType | Model.Init, ...args: any[]): React.ReactElement {\n\n if(typeof type == \"function\")\n if(RENDER.has(type))\n type = RENDER.get(type)!;\n else if(typeof type == \"function\")\n RENDER.set(type, type = (\n type.prototype instanceof Model ?\n MC.bind(type as Model.Init) :\n type as React.ComponentType\n ));\n\n return this(type, ...args);\n}\n\nexport const jsx = compat.bind(Runtime.jsx);\nexport const jsxs = compat.bind(Runtime.jsxs);\n\nexport { Fragment } from \"react\";","import Model, { Context } from '@expressive/mvc';\nimport { createContext, createElement, ReactNode, Suspense, useContext, useEffect, useMemo } from 'react';\n\nconst Lookup = createContext(new Context());\n\ndeclare module '@expressive/mvc' {\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(Lookup);\n\n return create ?\n useMemo(() => ambient.push(), []) :\n ambient;\n}\n\ndeclare namespace Consumer {\n type Props<T extends Model> = {\n /** Type of controller to fetch from context. */\n for: Model.Type<T>;\n\n /**\n * Render function, will receive instance of desired controller.\n *\n * Called every render of parent component.\n * Similar to `Model.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 Model>(props: Consumer.Props<T>){\n return props.for.get(i => props.children(i));\n}\n\ndeclare namespace Provider {\n interface Props<T extends Model> {\n /** Model or group of Models to provide to descendant Consumers. */\n for: Context.Accept<T>;\n\n forEach?: Context.Expect<T>;\n children?: ReactNode;\n\n /** A fallback react 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 Model>(props: Provider.Props<T>){\n const context = Context.use(true);\n\n useEffect(() => () => context.pop(), [context]);\n\n context.include(props.for, (model) => {\n if(props.forEach){\n const cleanup = props.forEach(model);\n\n if(cleanup)\n model.set(cleanup, null);\n }\n });\n \n return createProvider(context, props.children, props.fallback, props.name);\n}\n\nexport function createProvider(\n context: Context | Model,\n children: ReactNode,\n fallback?: ReactNode,\n name?: string | undefined){\n\n if(context instanceof Model)\n context = Context.get(context)!;\n\n const element = createElement(Lookup.Provider, {\n key: context.id,\n value: context,\n children\n });\n\n return fallback !== undefined ?\n createElement(Suspense, { fallback, name }, element) :\n element;\n}\n\nexport { Consumer, Provider, Context }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,cAA8B;AAE9B,yBAAoB;;;ACFpB,iBAA+B;AAC/B,mBAAkG;AAElG,IAAM,aAAS,4BAAc,IAAI,mBAAQ,CAAC;AAS1C,mBAAQ,MAAM,CAAC,WAAqB;AAClC,QAAM,cAAU,yBAAW,MAAM;AAEjC,SAAO,aACL,sBAAQ,MAAM,QAAQ,KAAK,GAAG,CAAC,CAAC,IAChC;AACJ;AA0DO,SAAS,eACd,SACA,UACA,UACA,MAA0B;AAE1B,MAAG,mBAAmB,WAAAC;AACpB,cAAU,mBAAQ,IAAI,OAAO;AAE/B,QAAM,cAAU,4BAAc,OAAO,UAAU;AAAA,IAC7C,KAAK,QAAQ;AAAA,IACb,OAAO;AAAA,IACP;AAAA,EACF,CAAC;AAED,SAAO,aAAa,aAClB,4BAAc,uBAAU,EAAE,UAAU,KAAK,GAAG,OAAO,IACnD;AACJ;;;ADQA,IAAAC,gBAAyB;AA3CzB,SAAS,GAEP,EAAE,IAAI,GAAG,MAAM,GACf;AACA,QAAM,QAAQ,KAAK,IAAI,CAAC,SAAS;AAC/B,SAAK,IAAI,KAAwB;AAEjC,QAAG;AACD,SAAG,IAAI;AAAA,EACX,CAAC;AAED,QAAM,IAAI,KAAwB;AAElC,QAAM,SAAS,mBAAO,IAAI,MAAM,MAAM,KAAK,MAAM,UAAU,MAAM;AACjE,QAAM,WAAW,SACb,OAAO,KAAK,OAAO,OAA4B,KAAK,IACpD,MAAM;AAEV,SAAO,eAAe,OAAO,UAAU,MAAM,YAAY,MAAM,UAAU,OAAO,KAAK,CAAC;AACxF;AAEA,IAAM,SAAS,oBAAI,QAAuC;AAEnD,SAAS,OAEd,SAAyC,MAAiC;AAE1E,MAAG,OAAO,QAAQ;AAChB,QAAG,OAAO,IAAI,IAAI;AAChB,aAAO,OAAO,IAAI,IAAI;AAAA,aAChB,OAAO,QAAQ;AACrB,aAAO,IAAI,MAAM,OACf,KAAK,qBAAqB,oBACxB,GAAG,KAAK,IAAkB,IAC5B,IACD;AAAA;AAEL,SAAO,KAAK,MAAM,GAAG,IAAI;AAC3B;AAEO,IAAM,MAAM,OAAO,KAAK,mBAAAC,QAAQ,GAAG;AACnC,IAAM,OAAO,OAAO,KAAK,mBAAAA,QAAQ,IAAI;","names":["import_mvc","Model","import_react","Runtime"]}
1
+ {"version":3,"file":"jsx-runtime.js","names":["State","Render","Runtime"],"sources":["../src/jsx-runtime.ts"],"sourcesContent":["import State from '@expressive/mvc';\nimport Runtime from 'react/jsx-runtime';\nimport React from 'react';\n\nimport { Render, AsComponent, Props } from './state';\n\nexport declare namespace JSX {\n type ElementType =\n | State.Extends<AsComponent>\n | React.JSX.ElementType\n | ((props: {}, ref?: any) => void);\n\n type LibraryManagedAttributes<C, P> =\n // For normal class components, pull from props property explicitly because we dorked up ElementAttributesProperty.\n C extends new (...args: any[]) => { props: infer U }\n ? U\n : C extends State.Extends<infer U>\n ? Props<U>\n : React.JSX.LibraryManagedAttributes<C, P>;\n\n interface Element extends React.JSX.Element {}\n interface ElementClass extends React.JSX.ElementClass {}\n\n // This is a hack to make TypeScript happy - React's interface insists on `props` property existing.\n // I await the \"Find Out\" phase of this in git issues.\n interface ElementAttributesProperty {}\n interface ElementChildrenAttribute\n extends React.JSX.ElementChildrenAttribute {}\n\n interface IntrinsicAttributes extends React.JSX.IntrinsicAttributes {}\n interface IntrinsicClassAttributes<T> extends React.JSX\n .IntrinsicClassAttributes<T> {}\n interface IntrinsicElements extends React.JSX.IntrinsicElements {}\n}\n\nconst RENDER = new WeakMap<Function, React.ComponentType>();\n\nexport function patch(\n this: (type: React.ElementType, ...args: any[]) => React.ReactElement,\n type: React.ElementType | State.Type,\n ...args: any[]\n): React.ReactElement {\n if (State.is(type))\n if (RENDER.has(type)) type = RENDER.get(type)!;\n else RENDER.set(type, (type = Render.bind(type)));\n\n return this(type, ...args);\n}\n\nexport const jsx = patch.bind(Runtime.jsx);\nexport const jsxs = patch.bind(Runtime.jsxs);\n\nexport { Fragment } from 'react';\n"],"mappings":";;;;;;;;;AAmCA,MAAM,yBAAS,IAAI,SAAwC;AAE3D,SAAgB,MAEd,MACA,GAAG,MACiB;AACpB,KAAIA,wBAAM,GAAG,KAAK,CAChB,KAAI,OAAO,IAAI,KAAK,CAAE,QAAO,OAAO,IAAI,KAAK;KACxC,QAAO,IAAI,MAAO,OAAOC,iBAAO,KAAK,KAAK,CAAE;AAEnD,QAAO,KAAK,MAAM,GAAG,KAAK;;AAG5B,MAAa,MAAM,MAAM,KAAKC,0BAAQ,IAAI;AAC1C,MAAa,OAAO,MAAM,KAAKA,0BAAQ,KAAK"}
@@ -0,0 +1,88 @@
1
+ import { _ as Props, g as HasProps, h as FC, p as AsComponent } from "./index-zVvhW0uD.js";
2
+ import { State } from "@expressive/mvc";
3
+ import { ReactNode } from "react";
4
+
5
+ //#region src/state.d.ts
6
+ declare const Pragma: {
7
+ useState<S>(initial: () => S): [S, (next: (previous: S) => S) => void];
8
+ useEffect(effect: () => () => void, deps?: any[]): void;
9
+ createElement(type: any, props?: any, ...children: any[]): any;
10
+ };
11
+ /** Type may not be undefined - instead will be null. */
12
+ type NoVoid<T> = T extends undefined | void ? null : T;
13
+ type ForceRefresh = {
14
+ /** Request a refresh for current component. */(): void;
15
+ /**
16
+ * Request a refresh and again after promise either resolves or rejects.
17
+ *
18
+ * @param waitFor Promise to wait for.
19
+ * @returns Promise which resolves, after refresh, to same value as `waitFor`.
20
+ */
21
+ <T = void>(waitFor: Promise<T>): Promise<T>;
22
+ /**
23
+ * Request refresh before and after async function.
24
+ * A refresh will occur both before and after the given function.
25
+ *
26
+ * **Note:** Any actions performed before first `await` will occur prior to refresh.
27
+ *
28
+ * @param invoke Async function to invoke.
29
+ * @returns Promise which resolves returned value after refresh.
30
+ */
31
+ <T = void>(invoke: () => Promise<T>): Promise<T>;
32
+ };
33
+ type GetFactory<T extends State, R> = (this: T, current: T, refresh: ForceRefresh) => R;
34
+ type GetEffect<T extends State> = (this: T, current: T, refresh: ForceRefresh) => null;
35
+ type UseArgs<T extends State> = T extends {
36
+ use(...props: infer P): any;
37
+ } ? P : State.Args<T>;
38
+ declare namespace ReactState {
39
+ export import Extends = State.Extends;
40
+ export import Type = State.Type;
41
+ export import Args = State.Args;
42
+ export import Init = State.Init;
43
+ export import Assign = State.Assign;
44
+ export import Field = State.Field;
45
+ export import Event = State.Event;
46
+ export import Export = State.Export;
47
+ export import Value = State.Value;
48
+ export import Setter = State.Setter;
49
+ export import OnEvent = State.OnEvent;
50
+ export import OnUpdate = State.OnUpdate;
51
+ export import Values = State.Values;
52
+ export import Partial = State.Partial;
53
+ export import Ref = State.Ref;
54
+ export import Effect = State.Effect;
55
+ export import EffectCallback = State.EffectCallback;
56
+ export { GetFactory, GetEffect, UseArgs, HasProps };
57
+ }
58
+ declare abstract class ReactState extends State {
59
+ /**
60
+ * Optional hook is 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 merged into the State.
64
+ *
65
+ * @param props Arguments passed to State.use().
66
+ */
67
+ protected use?(...props: any[]): Promise<void> | void;
68
+ /**
69
+ * Create and manage instance of this State within React component.
70
+ *
71
+ * @param args Arguments to pass to constructor or `use` method (if defined).
72
+ * @returns Managed instance of this State.
73
+ */
74
+ static use<T extends ReactState>(this: State.Type<T>, ...args: UseArgs<T>): T;
75
+ /** Fetch instance of this class from context. */
76
+ static get<T extends State>(this: State.Extends<T>): T;
77
+ /** Fetch instance of this class optionally. */
78
+ static get<T extends State>(this: State.Extends<T>, required: false): T | undefined;
79
+ /** Fetch instance of this class from context. */
80
+ static get<T extends State>(this: State.Extends<T>, requireValues: true): Required<T>;
81
+ static get<T extends State, R>(this: State.Extends<T>, factory: GetFactory<T, Promise<R> | R>): NoVoid<R>;
82
+ static get<T extends State>(this: State.Extends<T>, factory: GetEffect<T>): null;
83
+ static as<T extends AsComponent, P extends State.Assign<T>>(this: State.Type<T>, render: (props: P, self: T) => ReactNode): FC<T, P>;
84
+ }
85
+ declare function Render<T extends AsComponent>(this: State.Type<T>, props: Props<T>, props2?: Props<T>): any;
86
+ //#endregion
87
+ export { AsComponent, Pragma, Props, ReactState, Render };
88
+ //# sourceMappingURL=state.d.ts.map
package/dist/state.js ADDED
@@ -0,0 +1,148 @@
1
+ const require_chunk = require('./chunk-kSYXY2_d.js');
2
+ const require_context = require('./context-DpbK9_2_.js');
3
+ let _expressive_mvc = require("@expressive/mvc");
4
+
5
+ //#region src/state.ts
6
+ const Pragma = {};
7
+ var ReactState = class ReactState extends _expressive_mvc.State {
8
+ /**
9
+ * Create and manage instance of this State within React component.
10
+ *
11
+ * @param args Arguments to pass to constructor or `use` method (if defined).
12
+ * @returns Managed instance of this State.
13
+ */
14
+ static use(...args) {
15
+ const ambient = _expressive_mvc.Context.use();
16
+ const state = Pragma.useState(() => {
17
+ let ready;
18
+ let active;
19
+ let use = (...args) => Promise.all(args.flat().map((arg) => typeof arg == "object" && instance.set(arg)));
20
+ const instance = new this((x) => {
21
+ if (x instanceof ReactState && x.use) {
22
+ use = x.use?.bind(x);
23
+ use(...args);
24
+ } else return args;
25
+ });
26
+ const context = ambient.push(instance);
27
+ (0, _expressive_mvc.watch)(instance, (current) => {
28
+ active = current;
29
+ if (ready) state[1]((x) => x.bind(null));
30
+ });
31
+ function didMount() {
32
+ ready = true;
33
+ return () => {
34
+ context.pop();
35
+ instance.set(null);
36
+ };
37
+ }
38
+ return (...args) => {
39
+ Pragma.useEffect(didMount, []);
40
+ if (ready) {
41
+ ready = false;
42
+ Promise.resolve(use(...args)).finally(() => ready = true);
43
+ }
44
+ return active;
45
+ };
46
+ });
47
+ return state[0](...args);
48
+ }
49
+ static get(argument) {
50
+ const context = _expressive_mvc.Context.use();
51
+ const state = Pragma.useState(() => {
52
+ const instance = context.get(this);
53
+ if (!instance) if (argument === false) return () => void 0;
54
+ else throw new Error(`Could not find ${this} in context.`);
55
+ let ready;
56
+ let value;
57
+ function render() {
58
+ state[1]((x) => x.bind(null));
59
+ }
60
+ function refresh(action) {
61
+ if (typeof action == "function") action = action();
62
+ render();
63
+ if (action) return action.finally(render);
64
+ }
65
+ const unwatch = (0, _expressive_mvc.watch)(instance, (current) => {
66
+ if (typeof argument === "function") {
67
+ const next = argument.call(current, current, refresh);
68
+ if (next === value) return;
69
+ value = next;
70
+ } else value = current;
71
+ if (ready) render();
72
+ }, argument === true);
73
+ if (value instanceof Promise) {
74
+ let error;
75
+ unwatch();
76
+ value.then((x) => value = x, (e) => error = e).finally(render);
77
+ value = null;
78
+ return () => {
79
+ if (error) throw error;
80
+ return value === void 0 ? null : value;
81
+ };
82
+ }
83
+ if (value === null) {
84
+ unwatch();
85
+ return () => null;
86
+ }
87
+ function onMount() {
88
+ ready = true;
89
+ return unwatch;
90
+ }
91
+ return () => {
92
+ Pragma.useEffect(onMount, []);
93
+ return value === void 0 ? null : value;
94
+ };
95
+ });
96
+ return state[0]();
97
+ }
98
+ static as(render) {
99
+ const FC = Render.bind(this, { render });
100
+ return Object.assign(FC, {
101
+ displayName: this.name,
102
+ State: this
103
+ });
104
+ }
105
+ };
106
+ function Render(props, props2) {
107
+ const { is, ...rest } = {
108
+ ...props,
109
+ ...props2
110
+ };
111
+ const ambient = _expressive_mvc.Context.use();
112
+ const state = Pragma.useState(() => {
113
+ const instance = this.new(rest, is && ((x) => void is(x)));
114
+ const context = ambient.push(instance);
115
+ let ready;
116
+ let active;
117
+ (0, _expressive_mvc.watch)(instance, (current) => {
118
+ active = current;
119
+ if (ready) state[1]((x) => x.bind(null));
120
+ });
121
+ function didMount() {
122
+ ready = true;
123
+ return () => {
124
+ context.pop();
125
+ instance.set(null);
126
+ };
127
+ }
128
+ function Render(props) {
129
+ const render = _expressive_mvc.METHOD.get(active.render) || props.render || active.render;
130
+ return render ? render.call(active, props, active) : props.children;
131
+ }
132
+ return (props) => {
133
+ ready = false;
134
+ Pragma.useEffect(didMount, []);
135
+ Promise.resolve(instance.set(props)).finally(() => {
136
+ ready = true;
137
+ });
138
+ return require_context.provide(context, Pragma.createElement(Render, props), props.fallback || active.fallback, String(instance));
139
+ };
140
+ });
141
+ return state[0](rest);
142
+ }
143
+
144
+ //#endregion
145
+ exports.Pragma = Pragma;
146
+ exports.ReactState = ReactState;
147
+ exports.Render = Render;
148
+ //# sourceMappingURL=state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.js","names":["State","Context","METHOD","provide"],"sources":["../src/state.ts"],"sourcesContent":["import { State, Context, watch, METHOD } from '@expressive/mvc';\nimport { ReactNode } from 'react';\nimport { provide } from './context';\nimport type { AsComponent, FC, HasProps, Props, RenderProps } from './component';\n\nexport const Pragma = {} as {\n useState<S>(initial: () => S): [S, (next: (previous: S) => S) => void];\n useEffect(effect: () => () => void, deps?: any[]): void;\n createElement(type: any, props?: any, ...children: any[]): any;\n};\n\n/** Type may not be undefined - instead will be null. */\ntype NoVoid<T> = T extends undefined | void ? null : T;\n\ntype 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\ntype GetFactory<T extends State, R> = (\n this: T,\n current: T,\n refresh: ForceRefresh\n) => R;\n\ntype GetEffect<T extends State> = (\n this: T,\n current: T,\n refresh: ForceRefresh\n) => null;\n\ntype UseArgs<T extends State> = T extends {\n use(...props: infer P): any;\n}\n ? P\n : State.Args<T>;\n\ndeclare namespace ReactState {\n export import Extends = State.Extends;\n export import Type = State.Type;\n export import Args = State.Args;\n export import Init = State.Init;\n export import Assign = State.Assign;\n export import Field = State.Field;\n export import Event = State.Event;\n export import Export = State.Export;\n export import Value = State.Value;\n export import Setter = State.Setter;\n export import OnEvent = State.OnEvent;\n export import OnUpdate = State.OnUpdate;\n export import Values = State.Values;\n export import Partial = State.Partial;\n export import Ref = State.Ref;\n export import Effect = State.Effect;\n export import EffectCallback = State.EffectCallback;\n\n export { GetFactory, GetEffect, UseArgs, HasProps };\n}\n\nabstract class ReactState extends State {\n /**\n * Optional hook is 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 merged into the State.\n *\n * @param props Arguments passed to State.use().\n */\n protected use?(...props: any[]): Promise<void> | void;\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 static use<T extends ReactState>(\n this: State.Type<T>,\n ...args: UseArgs<T>\n ): T {\n const ambient = Context.use();\n const state = Pragma.useState(() => {\n let ready: boolean | undefined;\n let active: T;\n\n let use = (...args: State.Args<T>): Promise<unknown> | void =>\n Promise.all(\n args\n .flat()\n .map(\n (arg) =>\n typeof arg == 'object' && instance.set(arg as State.Assign<T>)\n )\n );\n\n // Create instance - pass args to constructor if no use method\n const instance = new this((x) => {\n if (x instanceof ReactState && x.use) {\n use = x.use?.bind(x);\n use(...args);\n } else return args;\n });\n\n const context = ambient.push(instance);\n\n watch(instance, (current) => {\n active = current;\n\n if (ready) state[1]((x) => x.bind(null));\n });\n\n function didMount() {\n ready = true;\n return () => {\n context.pop();\n instance.set(null);\n };\n }\n\n return (...args: State.Args<T>) => {\n Pragma.useEffect(didMount, []);\n\n if (ready) {\n ready = false;\n\n Promise.resolve(use(...args)).finally(() => (ready = true));\n }\n\n return active;\n };\n });\n\n return state[0](...args);\n }\n\n /** Fetch instance of this class from context. */\n static get<T extends State>(this: State.Extends<T>): T;\n\n /** Fetch instance of this class optionally. */\n static 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 static get<T extends State>(\n this: State.Extends<T>,\n requireValues: true\n ): Required<T>;\n\n static get<T extends State, R>(\n this: State.Extends<T>,\n factory: GetFactory<T, Promise<R> | R>\n ): NoVoid<R>;\n\n // TODO: eagerly match this so any nulls are caught - would prevent updates.\n static get<T extends State>(\n this: State.Extends<T>,\n factory: GetEffect<T>\n ): null;\n\n static get<T extends State, R>(\n this: State.Extends<T>,\n argument?: boolean | GetFactory<T, unknown>\n ) {\n const context = Context.use();\n const state = Pragma.useState(() => {\n const instance = context.get(this);\n\n if (!instance)\n if (argument === false) return () => undefined;\n else throw new Error(`Could not find ${this} in context.`);\n\n let ready: boolean | undefined;\n let value: any;\n\n function render() {\n state[1]((x) => x.bind(null));\n }\n\n function refresh<T>(action?: Promise<T> | (() => Promise<T>)): any {\n if (typeof action == 'function') action = action();\n\n render();\n\n if (action) return action.finally(render);\n }\n\n const unwatch = watch(\n instance,\n (current) => {\n if (typeof argument === 'function') {\n const next = argument.call(current, current, refresh);\n\n if (next === value) return;\n\n value = next;\n } else value = current;\n\n if (ready) render();\n },\n argument === true\n );\n\n if (value instanceof Promise) {\n let error: Error | undefined;\n\n unwatch();\n\n value\n .then(\n (x) => (value = x),\n (e) => (error = e)\n )\n .finally(render);\n\n value = null;\n\n return () => {\n if (error) throw error;\n\n return value === undefined ? null : value;\n };\n }\n\n if (value === null) {\n unwatch();\n return () => null;\n }\n\n function onMount() {\n ready = true;\n return unwatch;\n }\n\n return () => {\n Pragma.useEffect(onMount, []);\n return value === undefined ? null : value;\n };\n });\n\n return state[0]() as R;\n }\n\n static as<T extends AsComponent, P extends State.Assign<T>>(\n this: State.Type<T>,\n render: (props: P, self: T) => ReactNode\n ): FC<T, P> {\n const FC = Render.bind(this as State.Type, { render } as {});\n\n return Object.assign(FC, {\n displayName: this.name,\n State: this\n });\n }\n}\n\nexport function Render<T extends AsComponent>(\n this: State.Type<T>,\n props: Props<T>,\n props2?: Props<T>\n) {\n const { is, ...rest } = { ...props, ...props2 };\n\n const ambient = Context.use();\n const state = Pragma.useState<(props: any) => any>(() => {\n const instance = this.new(rest as {}, is && ((x) => void is(x)));\n const context = ambient.push(instance);\n\n let ready: boolean | undefined;\n let active: T;\n\n watch(instance, (current) => {\n active = current;\n\n if (ready) state[1]((x) => x.bind(null));\n });\n\n function didMount() {\n ready = true;\n return () => {\n context.pop();\n instance.set(null);\n };\n }\n\n function Render(props: Props<T>) {\n const render = METHOD.get(active.render) || props.render || active.render;\n\n return render\n ? render.call(active, props as HasProps<T>, active)\n : props.children;\n }\n\n return (props: RenderProps<T>) => {\n ready = false;\n\n Pragma.useEffect(didMount, []);\n Promise.resolve(instance.set(props as {})).finally(() => {\n ready = true;\n });\n\n return provide(\n context,\n Pragma.createElement(Render, props as any),\n props.fallback || active.fallback,\n String(instance)\n );\n };\n });\n\n return state[0](rest);\n}\n\nexport { ReactState };\nexport { AsComponent, Props };\n"],"mappings":"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"}
package/package.json CHANGED
@@ -18,16 +18,17 @@
18
18
  ],
19
19
  "main": "dist/index.js",
20
20
  "types": "dist/index.d.ts",
21
+ "type": "module",
21
22
  "exports": {
22
23
  ".": {
23
24
  "types": "./dist/index.d.ts",
24
25
  "require": "./dist/index.js",
25
26
  "import": "./dist/esm/index.js"
26
27
  },
27
- "./adapter": {
28
- "types": "./dist/adapter.d.ts",
29
- "require": "./dist/adapter.js",
30
- "import": "./dist/esm/adapter.js"
28
+ "./state": {
29
+ "types": "./dist/state.d.ts",
30
+ "require": "./dist/state.js",
31
+ "import": "./dist/esm/state.js"
31
32
  },
32
33
  "./jsx-runtime": {
33
34
  "types": "./dist/jsx-runtime.d.ts",
@@ -44,12 +45,12 @@
44
45
  "dist"
45
46
  ],
46
47
  "scripts": {
47
- "build": "tsup",
48
+ "build": "tsdown",
48
49
  "test": "tsc --noEmit && jest --collectCoverage",
49
50
  "preversion": "npm run test && npm run build"
50
51
  },
51
52
  "dependencies": {
52
- "@expressive/mvc": "^0.71.0"
53
+ "@expressive/mvc": "^0.73.0"
53
54
  },
54
55
  "peerDependencies": {
55
56
  "react": ">=16.8.0 <20.0.0"
@@ -60,13 +61,15 @@
60
61
  }
61
62
  },
62
63
  "devDependencies": {
63
- "@testing-library/jest-dom": "^6.6.4",
64
+ "@testing-library/jest-dom": "^6.8.0",
64
65
  "@testing-library/react": "^16.3.0",
65
- "@types/react": "^18.2.14",
66
+ "@types/react": "^19",
67
+ "@types/react-dom": "^19",
66
68
  "jest": "^27.5.1",
67
- "react": "^18.2.0",
68
- "tsup": "^8.0.2"
69
+ "react": "^19",
70
+ "react-dom": "^19",
71
+ "tsdown": "^0.20.1"
69
72
  },
70
- "version": "0.71.0",
71
- "gitHead": "4d1f02e2c64ae6a993d6fa1384d385bd58a26e37"
73
+ "version": "0.73.0",
74
+ "gitHead": "c5a755934bc66896216eb508f00e6fa7e3efec3b"
72
75
  }
package/dist/adapter.d.ts DELETED
@@ -1,105 +0,0 @@
1
- import { Context } from '@expressive/mvc';
2
- import React__default, { FunctionComponent } from 'react';
3
-
4
- declare module '@expressive/mvc' {
5
- namespace Model {
6
- interface Component<T extends Model, P extends Model.Assign<T>> extends FunctionComponent<P & Model.Props<T>> {
7
- displayName?: string;
8
- Model: Model.Type<T>;
9
- }
10
- function as<T extends Model, P extends Model.Assign<T>>(this: Model.Init<T>, render: (props: P, self: T) => React__default.ReactNode): Component<T, P>;
11
- }
12
- }
13
-
14
- declare module '@expressive/mvc' {
15
- namespace Model {
16
- function use<T extends Model>(this: Model.Init<T>, apply?: Model.Assign<T>, repeat?: boolean): T;
17
- function use<T extends Model>(this: Model.Init<T>, callback?: Model.Callback<T>, repeat?: boolean): T;
18
- }
19
- }
20
-
21
- /** Type may not be undefined - instead will be null. */
22
- type NoVoid<T> = T extends undefined | void ? null : T;
23
- type ForceRefresh = {
24
- /** Request a refresh for current component. */
25
- (): void;
26
- /**
27
- * Request a refresh and again after promise either resolves or rejects.
28
- *
29
- * @param waitFor Promise to wait for.
30
- * @returns Promise which resolves, after refresh, to same value as `waitFor`.
31
- */
32
- <T = void>(waitFor: Promise<T>): Promise<T>;
33
- /**
34
- * Request refresh before and after async function.
35
- * A refresh will occur both before and after the given function.
36
- *
37
- * **Note:** Any actions performed before first `await` will occur prior to refresh.
38
- *
39
- * @param invoke Async function to invoke.
40
- * @returns Promise which resolves returned value after refresh.
41
- */
42
- <T = void>(invoke: () => Promise<T>): Promise<T>;
43
- };
44
- declare module '@expressive/mvc' {
45
- namespace Model {
46
- type GetFactory<T extends Model, R> = (this: T, current: T, refresh: ForceRefresh) => R;
47
- type GetEffect<T extends Model> = (this: T, current: T, refresh: ForceRefresh) => null;
48
- /** Fetch instance of this class from context. */
49
- function get<T extends Model>(this: Model.Type<T>): T;
50
- /** Fetch instance of this class optionally. */
51
- function get<T extends Model>(this: Model.Type<T>, required: false): T | undefined;
52
- /** Fetch instance of this class from context. */
53
- function get<T extends Model>(this: Model.Type<T>, requireValues: true): Required<T>;
54
- function get<T extends Model, R>(this: Model.Type<T>, factory: GetFactory<T, Promise<R> | R>): NoVoid<R>;
55
- function get<T extends Model>(this: Model.Type<T>, factory: GetEffect<T>): null;
56
- }
57
- }
58
-
59
- declare module '@expressive/mvc' {
60
- namespace Model {
61
- type HasProps<T extends Model> = {
62
- [K in Exclude<keyof T, keyof Model>]?: T[K];
63
- };
64
- /**
65
- * Props which will not conflict with a Model's use as a Component.
66
- *
67
- * Built-in properties must be optional, as they will always be omitted.
68
- */
69
- type RenderProps<T extends Model> = HasProps<T> & {
70
- is?: undefined;
71
- get?: undefined;
72
- set?: undefined;
73
- };
74
- /** Model which is not incompatable as Component in React. */
75
- interface Compat extends Model {
76
- render?(props: RenderProps<this>, self: this): React.ReactNode;
77
- fallback?: React.ReactNode;
78
- }
79
- interface BaseProps<T extends Model> {
80
- /**
81
- * Callback for newly created instance. Only called once.
82
- * @returns Callback to run when instance is destroyed.
83
- */
84
- is?: (instance: T) => void;
85
- render?(props: HasProps<T>, self: T): React.ReactNode;
86
- /**
87
- * A fallback react tree to show when suspended.
88
- * If not provided, `fallback` property of the Model will be used.
89
- */
90
- fallback?: React.ReactNode;
91
- }
92
- type Props<T extends Model> = T extends {
93
- render(props: infer P, self: any): any;
94
- } ? BaseProps<T> & HasProps<T> & Omit<P, keyof Model> : BaseProps<T> & HasProps<T> & {
95
- children?: React.ReactNode;
96
- };
97
- }
98
- }
99
- declare const Pragma: {
100
- useContext(): Context;
101
- useFactory<T extends Function>(factory: (refresh: () => void) => T): T;
102
- useLifecycle(callback: () => () => void): void;
103
- };
104
-
105
- export { Pragma };