@xmachines/json-render-react 0.21.0-xm.2 → 0.21.0-xm.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -102,8 +102,11 @@ declare function useIsVisible(condition: VisibilityCondition | undefined): boole
102
102
  interface PendingConfirmation {
103
103
  /** The resolved action */
104
104
  action: ResolvedAction;
105
- /** The action handler */
106
- handler: ActionHandler;
105
+ /**
106
+ * The handler of the host. A built-in action, such as `setState`, has
107
+ * none: the provider runs it itself.
108
+ */
109
+ handler: ActionHandler | undefined;
107
110
  /** Accept the confirmation — the action runs */
108
111
  resolve: () => void;
109
112
  /** Decline the confirmation — the action is skipped, nothing throws */
@@ -132,7 +135,10 @@ interface ActionContextValue {
132
135
  * Props for ActionProvider
133
136
  */
134
137
  interface ActionProviderProps {
135
- /** Initial action handlers */
138
+ /**
139
+ * Action handlers. The provider follows a new map on each render, and a
140
+ * handler that registerHandler added stays on top.
141
+ */
136
142
  handlers?: Record<string, ActionHandler>;
137
143
  /** Navigation function */
138
144
  navigate?: (path: string) => void;
@@ -141,7 +147,7 @@ interface ActionProviderProps {
141
147
  /**
142
148
  * Provider for action execution
143
149
  */
144
- declare function ActionProvider({ handlers: initialHandlers, navigate, children, }: ActionProviderProps): react_jsx_runtime.JSX.Element;
150
+ declare function ActionProvider({ handlers: handlersProp, navigate, children, }: ActionProviderProps): react_jsx_runtime.JSX.Element;
145
151
  /**
146
152
  * Hook to access action context
147
153
  */
package/dist/index.d.ts CHANGED
@@ -102,8 +102,11 @@ declare function useIsVisible(condition: VisibilityCondition | undefined): boole
102
102
  interface PendingConfirmation {
103
103
  /** The resolved action */
104
104
  action: ResolvedAction;
105
- /** The action handler */
106
- handler: ActionHandler;
105
+ /**
106
+ * The handler of the host. A built-in action, such as `setState`, has
107
+ * none: the provider runs it itself.
108
+ */
109
+ handler: ActionHandler | undefined;
107
110
  /** Accept the confirmation — the action runs */
108
111
  resolve: () => void;
109
112
  /** Decline the confirmation — the action is skipped, nothing throws */
@@ -132,7 +135,10 @@ interface ActionContextValue {
132
135
  * Props for ActionProvider
133
136
  */
134
137
  interface ActionProviderProps {
135
- /** Initial action handlers */
138
+ /**
139
+ * Action handlers. The provider follows a new map on each render, and a
140
+ * handler that registerHandler added stays on top.
141
+ */
136
142
  handlers?: Record<string, ActionHandler>;
137
143
  /** Navigation function */
138
144
  navigate?: (path: string) => void;
@@ -141,7 +147,7 @@ interface ActionProviderProps {
141
147
  /**
142
148
  * Provider for action execution
143
149
  */
144
- declare function ActionProvider({ handlers: initialHandlers, navigate, children, }: ActionProviderProps): react_jsx_runtime.JSX.Element;
150
+ declare function ActionProvider({ handlers: handlersProp, navigate, children, }: ActionProviderProps): react_jsx_runtime.JSX.Element;
145
151
  /**
146
152
  * Hook to access action context
147
153
  */
package/dist/index.js CHANGED
@@ -478,19 +478,32 @@ function deepResolveValue(value, get) {
478
478
  }
479
479
  var ActionContext = (0, import_react4.createContext)(null);
480
480
  function ActionProvider({
481
- handlers: initialHandlers = {},
481
+ handlers: handlersProp = {},
482
482
  navigate,
483
483
  children
484
484
  }) {
485
485
  const { get, set, getSnapshot } = useStateStore();
486
486
  const validation = useOptionalValidation();
487
- const [handlers, setHandlers] = (0, import_react4.useState)(initialHandlers);
487
+ const propRef = (0, import_react4.useRef)(handlersProp);
488
+ propRef.current = handlersProp;
489
+ const [registered, setRegistered] = (0, import_react4.useState)(
490
+ {}
491
+ );
492
+ const propNames = JSON.stringify([
493
+ Object.keys(handlersProp),
494
+ Reflect.has(handlersProp, "\0json-render:any-name")
495
+ ]);
496
+ const handlers = (0, import_react4.useMemo)(
497
+ () => (0, import_core4.mergeActionHandlers)(() => propRef.current, registered),
498
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- propNames is the change signal
499
+ [registered, propNames]
500
+ );
488
501
  const [loadingActions, setLoadingActions] = (0, import_react4.useState)(/* @__PURE__ */ new Set());
489
502
  const [pendingConfirmation, setPendingConfirmation] = (0, import_react4.useState)(null);
490
503
  const pendingRef = (0, import_react4.useRef)(null);
491
504
  const registerHandler = (0, import_react4.useCallback)(
492
505
  (name, handler) => {
493
- setHandlers((prev) => ({ ...prev, [name]: handler }));
506
+ setRegistered((prev) => ({ ...prev, [name]: handler }));
494
507
  },
495
508
  []
496
509
  );
@@ -510,6 +523,39 @@ function ActionProvider({
510
523
  let __cancelled = false;
511
524
  let __confirmMs = void 0;
512
525
  try {
526
+ const handler = handlers[resolved.action];
527
+ if (!handler && !(0, import_core4.isBuiltInAction)(resolved.action)) {
528
+ console.warn(`No handler registered for action: ${resolved.action}`);
529
+ return;
530
+ }
531
+ if (resolved.confirm) {
532
+ pendingRef.current?.reject();
533
+ const confirmOpenedAt = Date.now();
534
+ const confirmed = await new Promise((res) => {
535
+ const entry = {
536
+ action: resolved,
537
+ handler,
538
+ resolve: () => {
539
+ pendingRef.current = null;
540
+ setPendingConfirmation(null);
541
+ res(true);
542
+ },
543
+ reject: () => {
544
+ pendingRef.current = null;
545
+ setPendingConfirmation(null);
546
+ res(false);
547
+ }
548
+ };
549
+ pendingRef.current = entry;
550
+ setPendingConfirmation(entry);
551
+ });
552
+ __confirmMs = Date.now() - confirmOpenedAt;
553
+ if (!confirmed) {
554
+ __ok = false;
555
+ __cancelled = true;
556
+ return;
557
+ }
558
+ }
513
559
  if (resolved.action === "setState" && resolved.params) {
514
560
  const statePath = resolved.params.statePath;
515
561
  const value2 = resolved.params.value;
@@ -590,39 +636,7 @@ function ActionProvider({
590
636
  set(statePath, { valid, errors });
591
637
  return;
592
638
  }
593
- const handler = handlers[resolved.action];
594
- if (!handler) {
595
- console.warn(`No handler registered for action: ${resolved.action}`);
596
- return;
597
- }
598
- if (resolved.confirm) {
599
- pendingRef.current?.reject();
600
- const confirmOpenedAt = Date.now();
601
- const confirmed = await new Promise((res) => {
602
- const entry = {
603
- action: resolved,
604
- handler,
605
- resolve: () => {
606
- pendingRef.current = null;
607
- setPendingConfirmation(null);
608
- res(true);
609
- },
610
- reject: () => {
611
- pendingRef.current = null;
612
- setPendingConfirmation(null);
613
- res(false);
614
- }
615
- };
616
- pendingRef.current = entry;
617
- setPendingConfirmation(entry);
618
- });
619
- __confirmMs = Date.now() - confirmOpenedAt;
620
- if (!confirmed) {
621
- __ok = false;
622
- __cancelled = true;
623
- return;
624
- }
625
- }
639
+ if (!handler) return;
626
640
  setLoadingActions((prev) => new Set(prev).add(resolved.action));
627
641
  try {
628
642
  await (0, import_core4.executeAction)({
@@ -915,33 +929,24 @@ var import_react6 = __toESM(require("react"));
915
929
  var import_core6 = require("@xmachines/json-render-core");
916
930
  var import_jsx_runtime6 = require("react/jsx-runtime");
917
931
  var EMPTY_ELEMENT_PROPS = {};
918
- function withRenderErrorHandler(registry, onRenderError) {
919
- const next = { ...registry };
920
- Object.defineProperty(next, "onRenderError", {
921
- value: onRenderError,
922
- enumerable: false,
923
- configurable: true
924
- });
925
- (0, import_core6.copySlotMetadata)(registry, next);
926
- return next;
927
- }
928
932
  function useRenderErrorRegistry(registry, onRenderError) {
929
933
  const handlerRef = (0, import_react6.useRef)(onRenderError);
930
934
  handlerRef.current = onRenderError;
931
935
  const hasHandler = onRenderError !== void 0;
932
936
  return (0, import_react6.useMemo)(
933
- () => hasHandler ? withRenderErrorHandler(registry, (error, elementType) => {
937
+ () => hasHandler ? (0, import_core6.withRenderErrorHandler)(registry, (error, elementType) => {
934
938
  handlerRef.current?.(error, elementType);
935
939
  }) : registry,
936
940
  [registry, hasHandler]
937
941
  );
938
942
  }
939
943
  function reportRenderError(registry, elementType, error, componentStack) {
940
- const onRenderError = registry?.onRenderError;
941
- if (typeof onRenderError === "function") {
944
+ const onRenderError = (0, import_core6.getRenderErrorHandler)(registry);
945
+ if (onRenderError !== void 0) {
942
946
  onRenderError(error, elementType);
943
947
  return;
944
948
  }
949
+ (0, import_core6.warnUnusedRenderErrorHandler)(registry);
945
950
  console.error(
946
951
  `[json-render] Rendering error in <${elementType}>:`,
947
952
  error,
@@ -1195,23 +1200,27 @@ function ReactiveElementRenderer({
1195
1200
  const binding = onBindings?.[eventName];
1196
1201
  if (!binding) return;
1197
1202
  const actionBindings = Array.isArray(binding) ? binding : [binding];
1198
- for (const b of actionBindings) {
1199
- if (!b.params) {
1200
- await execute(b);
1201
- continue;
1202
- }
1203
- const liveCtx = {
1204
- ...fullCtx,
1205
- stateModel: getSnapshot()
1206
- };
1207
- const resolved = {};
1208
- for (const [key, val] of Object.entries(b.params)) {
1209
- resolved[key] = (0, import_core6.resolveActionParam)(val, liveCtx);
1203
+ let action = "";
1204
+ try {
1205
+ for (const b of actionBindings) {
1206
+ action = b.action;
1207
+ await execute(
1208
+ (0, import_core6.resolveBindingParams)(b, {
1209
+ ...fullCtx,
1210
+ stateModel: getSnapshot()
1211
+ })
1212
+ );
1210
1213
  }
1211
- await execute({ ...b, params: resolved });
1214
+ } catch (err) {
1215
+ (0, import_core6.reportActionError)(
1216
+ (0, import_core6.getRenderErrorHandler)(registry),
1217
+ err,
1218
+ action,
1219
+ "event"
1220
+ );
1212
1221
  }
1213
1222
  },
1214
- [onBindings, execute, fullCtx, getSnapshot]
1223
+ [onBindings, execute, fullCtx, getSnapshot, registry]
1215
1224
  );
1216
1225
  const on = (0, import_react6.useCallback)(
1217
1226
  (eventName) => {
@@ -1231,6 +1240,20 @@ function ReactiveElementRenderer({
1231
1240
  [onBindings, emit]
1232
1241
  );
1233
1242
  const watchConfig = element.watch;
1243
+ const watchDepsRef = (0, import_react6.useRef)({
1244
+ watchConfig,
1245
+ fullCtx,
1246
+ execute,
1247
+ getSnapshot,
1248
+ registry
1249
+ });
1250
+ watchDepsRef.current = {
1251
+ watchConfig,
1252
+ fullCtx,
1253
+ execute,
1254
+ getSnapshot,
1255
+ registry
1256
+ };
1234
1257
  const prevWatchValues = (0, import_react6.useRef)(null);
1235
1258
  const stableWatchRef = (0, import_react6.useRef)(void 0);
1236
1259
  const stableBindingsRef = (0, import_react6.useRef)(
@@ -1238,61 +1261,48 @@ function ReactiveElementRenderer({
1238
1261
  );
1239
1262
  const stableResolvedPropsRef = (0, import_react6.useRef)({});
1240
1263
  const watchedValues = (0, import_react6.useMemo)(() => {
1241
- if (!watchConfig) return void 0;
1242
- const values = {};
1243
- for (const path of Object.keys(watchConfig)) {
1244
- values[path] = (0, import_core6.getByPath)(watchState, path);
1245
- }
1246
- const prev = stableWatchRef.current;
1247
- if (prev) {
1248
- const keys = Object.keys(values);
1249
- if (keys.length === Object.keys(prev).length && keys.every((k) => values[k] === prev[k])) {
1250
- return prev;
1251
- }
1252
- }
1264
+ const values = (0, import_core6.readWatchedValues)(
1265
+ watchConfig,
1266
+ watchState,
1267
+ stableWatchRef.current
1268
+ );
1253
1269
  stableWatchRef.current = values;
1254
1270
  return values;
1255
1271
  }, [watchConfig, watchState]);
1256
1272
  (0, import_react6.useEffect)(() => {
1257
- if (!watchConfig || !watchedValues) return;
1258
- const paths = Object.keys(watchConfig);
1259
- if (paths.length === 0) return;
1260
1273
  const prev = prevWatchValues.current;
1261
- prevWatchValues.current = watchedValues;
1262
- if (prev === null) return;
1274
+ prevWatchValues.current = watchedValues ?? null;
1275
+ const paths = (0, import_core6.changedWatchPaths)(watchedValues, prev ?? void 0);
1276
+ const watch = watchDepsRef.current.watchConfig;
1277
+ if (!watch || paths.length === 0) return;
1263
1278
  let cancelled = false;
1264
- void (async () => {
1265
- for (const path of paths) {
1266
- if (cancelled) break;
1267
- if (watchedValues[path] !== prev[path]) {
1268
- const binding = watchConfig[path];
1269
- if (!binding) continue;
1270
- const bindings = Array.isArray(binding) ? binding : [binding];
1271
- for (const b of bindings) {
1272
- if (cancelled) break;
1273
- if (!b.params) {
1274
- await execute(b);
1275
- if (cancelled) break;
1276
- continue;
1277
- }
1278
- const liveCtx = {
1279
- ...fullCtx,
1280
- stateModel: getSnapshot()
1281
- };
1282
- const resolved = {};
1283
- for (const [key, val] of Object.entries(b.params)) {
1284
- resolved[key] = (0, import_core6.resolveActionParam)(val, liveCtx);
1285
- }
1286
- await execute({ ...b, params: resolved });
1287
- if (cancelled) break;
1288
- }
1289
- }
1290
- }
1291
- })().catch(console.error);
1279
+ let action = "";
1280
+ void (0, import_core6.runWatchBindings)(
1281
+ watch,
1282
+ paths,
1283
+ async (b) => {
1284
+ action = b.action;
1285
+ const { execute: execute2, fullCtx: fullCtx2, getSnapshot: getSnapshot2 } = watchDepsRef.current;
1286
+ await execute2(
1287
+ (0, import_core6.resolveBindingParams)(b, {
1288
+ ...fullCtx2,
1289
+ stateModel: getSnapshot2()
1290
+ })
1291
+ );
1292
+ },
1293
+ () => cancelled
1294
+ ).catch((err) => {
1295
+ (0, import_core6.reportActionError)(
1296
+ (0, import_core6.getRenderErrorHandler)(watchDepsRef.current.registry),
1297
+ err,
1298
+ action,
1299
+ "watch"
1300
+ );
1301
+ });
1292
1302
  return () => {
1293
1303
  cancelled = true;
1294
1304
  };
1295
- }, [watchConfig, watchedValues, execute, fullCtx, getSnapshot]);
1305
+ }, [watchedValues]);
1296
1306
  if (!isVisible) {
1297
1307
  return null;
1298
1308
  }
@@ -1307,7 +1317,7 @@ function ReactiveElementRenderer({
1307
1317
  );
1308
1318
  stableResolvedPropsRef.current = resolvedProps;
1309
1319
  const resolvedElement = resolvedProps !== element.props ? { ...element, props: resolvedProps } : element;
1310
- const Component = registry[resolvedElement.type] ?? fallback;
1320
+ const Component = (0, import_core6.getRegistryComponent)(registry, resolvedElement.type) ?? fallback;
1311
1321
  if (!Component) {
1312
1322
  console.warn(`No renderer for component type: ${resolvedElement.type}`);
1313
1323
  return null;
@@ -1534,7 +1544,9 @@ function ConfirmationDialogManager() {
1534
1544
  );
1535
1545
  }
1536
1546
  function defineRegistry(catalog, options) {
1537
- const registry = {};
1547
+ const registry = (0, import_core6.createComponentRegistry)(
1548
+ options.components
1549
+ );
1538
1550
  if (options.components) {
1539
1551
  for (const [name, componentFn] of Object.entries(options.components)) {
1540
1552
  registry[name] = ({
@@ -1582,11 +1594,7 @@ function defineRegistry(catalog, options) {
1582
1594
  }
1583
1595
  };
1584
1596
  if (options.onRenderError) {
1585
- Object.defineProperty(registry, "onRenderError", {
1586
- value: options.onRenderError,
1587
- enumerable: false,
1588
- configurable: true
1589
- });
1597
+ (0, import_core6.setRenderErrorHandler)(registry, options.onRenderError);
1590
1598
  }
1591
1599
  return { registry, handlers, executeAction: executeAction2 };
1592
1600
  }