@xmachines/json-render-react 0.21.0-xm.1 → 0.21.0-xm.3

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)({
@@ -914,36 +928,25 @@ var import_core8 = require("@xmachines/json-render-core");
914
928
  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
- var registryMetadata = /* @__PURE__ */ new WeakMap();
918
931
  var EMPTY_ELEMENT_PROPS = {};
919
- function withRenderErrorHandler(registry, onRenderError) {
920
- const next = { ...registry };
921
- Object.defineProperty(next, "onRenderError", {
922
- value: onRenderError,
923
- enumerable: false,
924
- configurable: true
925
- });
926
- const metadata = registryMetadata.get(registry);
927
- if (metadata) registryMetadata.set(next, metadata);
928
- return next;
929
- }
930
932
  function useRenderErrorRegistry(registry, onRenderError) {
931
933
  const handlerRef = (0, import_react6.useRef)(onRenderError);
932
934
  handlerRef.current = onRenderError;
933
935
  const hasHandler = onRenderError !== void 0;
934
936
  return (0, import_react6.useMemo)(
935
- () => hasHandler ? withRenderErrorHandler(registry, (error, elementType) => {
937
+ () => hasHandler ? (0, import_core6.withRenderErrorHandler)(registry, (error, elementType) => {
936
938
  handlerRef.current?.(error, elementType);
937
939
  }) : registry,
938
940
  [registry, hasHandler]
939
941
  );
940
942
  }
941
943
  function reportRenderError(registry, elementType, error, componentStack) {
942
- const onRenderError = registry?.onRenderError;
943
- if (typeof onRenderError === "function") {
944
+ const onRenderError = (0, import_core6.getRenderErrorHandler)(registry);
945
+ if (onRenderError !== void 0) {
944
946
  onRenderError(error, elementType);
945
947
  return;
946
948
  }
949
+ (0, import_core6.warnUnusedRenderErrorHandler)(registry);
947
950
  console.error(
948
951
  `[json-render] Rendering error in <${elementType}>:`,
949
952
  error,
@@ -1197,23 +1200,27 @@ function ReactiveElementRenderer({
1197
1200
  const binding = onBindings?.[eventName];
1198
1201
  if (!binding) return;
1199
1202
  const actionBindings = Array.isArray(binding) ? binding : [binding];
1200
- for (const b of actionBindings) {
1201
- if (!b.params) {
1202
- await execute(b);
1203
- continue;
1204
- }
1205
- const liveCtx = {
1206
- ...fullCtx,
1207
- stateModel: getSnapshot()
1208
- };
1209
- const resolved = {};
1210
- for (const [key, val] of Object.entries(b.params)) {
1211
- 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
+ );
1212
1213
  }
1213
- 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
+ );
1214
1221
  }
1215
1222
  },
1216
- [onBindings, execute, fullCtx, getSnapshot]
1223
+ [onBindings, execute, fullCtx, getSnapshot, registry]
1217
1224
  );
1218
1225
  const on = (0, import_react6.useCallback)(
1219
1226
  (eventName) => {
@@ -1233,6 +1240,20 @@ function ReactiveElementRenderer({
1233
1240
  [onBindings, emit]
1234
1241
  );
1235
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
+ };
1236
1257
  const prevWatchValues = (0, import_react6.useRef)(null);
1237
1258
  const stableWatchRef = (0, import_react6.useRef)(void 0);
1238
1259
  const stableBindingsRef = (0, import_react6.useRef)(
@@ -1240,61 +1261,48 @@ function ReactiveElementRenderer({
1240
1261
  );
1241
1262
  const stableResolvedPropsRef = (0, import_react6.useRef)({});
1242
1263
  const watchedValues = (0, import_react6.useMemo)(() => {
1243
- if (!watchConfig) return void 0;
1244
- const values = {};
1245
- for (const path of Object.keys(watchConfig)) {
1246
- values[path] = (0, import_core6.getByPath)(watchState, path);
1247
- }
1248
- const prev = stableWatchRef.current;
1249
- if (prev) {
1250
- const keys = Object.keys(values);
1251
- if (keys.length === Object.keys(prev).length && keys.every((k) => values[k] === prev[k])) {
1252
- return prev;
1253
- }
1254
- }
1264
+ const values = (0, import_core6.readWatchedValues)(
1265
+ watchConfig,
1266
+ watchState,
1267
+ stableWatchRef.current
1268
+ );
1255
1269
  stableWatchRef.current = values;
1256
1270
  return values;
1257
1271
  }, [watchConfig, watchState]);
1258
1272
  (0, import_react6.useEffect)(() => {
1259
- if (!watchConfig || !watchedValues) return;
1260
- const paths = Object.keys(watchConfig);
1261
- if (paths.length === 0) return;
1262
1273
  const prev = prevWatchValues.current;
1263
- prevWatchValues.current = watchedValues;
1264
- 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;
1265
1278
  let cancelled = false;
1266
- void (async () => {
1267
- for (const path of paths) {
1268
- if (cancelled) break;
1269
- if (watchedValues[path] !== prev[path]) {
1270
- const binding = watchConfig[path];
1271
- if (!binding) continue;
1272
- const bindings = Array.isArray(binding) ? binding : [binding];
1273
- for (const b of bindings) {
1274
- if (cancelled) break;
1275
- if (!b.params) {
1276
- await execute(b);
1277
- if (cancelled) break;
1278
- continue;
1279
- }
1280
- const liveCtx = {
1281
- ...fullCtx,
1282
- stateModel: getSnapshot()
1283
- };
1284
- const resolved = {};
1285
- for (const [key, val] of Object.entries(b.params)) {
1286
- resolved[key] = (0, import_core6.resolveActionParam)(val, liveCtx);
1287
- }
1288
- await execute({ ...b, params: resolved });
1289
- if (cancelled) break;
1290
- }
1291
- }
1292
- }
1293
- })().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
+ });
1294
1302
  return () => {
1295
1303
  cancelled = true;
1296
1304
  };
1297
- }, [watchConfig, watchedValues, execute, fullCtx, getSnapshot]);
1305
+ }, [watchedValues]);
1298
1306
  if (!isVisible) {
1299
1307
  return null;
1300
1308
  }
@@ -1309,26 +1317,12 @@ function ReactiveElementRenderer({
1309
1317
  );
1310
1318
  stableResolvedPropsRef.current = resolvedProps;
1311
1319
  const resolvedElement = resolvedProps !== element.props ? { ...element, props: resolvedProps } : element;
1312
- const Component = registry[resolvedElement.type] ?? fallback;
1320
+ const Component = (0, import_core6.getRegistryComponent)(registry, resolvedElement.type) ?? fallback;
1313
1321
  if (!Component) {
1314
1322
  console.warn(`No renderer for component type: ${resolvedElement.type}`);
1315
1323
  return null;
1316
1324
  }
1317
- const metadata = registryMetadata.get(registry)?.[resolvedElement.type];
1318
- if (resolvedElement.slots && metadata?.slots) {
1319
- const availableSlots = new Set(metadata.slots);
1320
- for (const slotName of Object.keys(resolvedElement.slots)) {
1321
- if (slotName === "default") {
1322
- console.warn(
1323
- `[json-render] Component "${resolvedElement.type}" uses slots.default. Use "children" for default slot content.`
1324
- );
1325
- } else if (!availableSlots.has(slotName)) {
1326
- console.warn(
1327
- `[json-render] Unknown slot "${slotName}" on component "${resolvedElement.type}". Available slots: ${metadata.slots.join(", ")}`
1328
- );
1329
- }
1330
- }
1331
- }
1325
+ (0, import_core6.warnElementSlots)(registry, resolvedElement.type, resolvedElement.slots);
1332
1326
  const renderChildKeys = (childKeys, slotName) => childKeys.map((childKey) => {
1333
1327
  const childElement = spec.elements[childKey];
1334
1328
  if (!childElement) {
@@ -1550,7 +1544,9 @@ function ConfirmationDialogManager() {
1550
1544
  );
1551
1545
  }
1552
1546
  function defineRegistry(catalog, options) {
1553
- const registry = {};
1547
+ const registry = (0, import_core6.createComponentRegistry)(
1548
+ options.components
1549
+ );
1554
1550
  if (options.components) {
1555
1551
  for (const [name, componentFn] of Object.entries(options.components)) {
1556
1552
  registry[name] = ({
@@ -1574,10 +1570,7 @@ function defineRegistry(catalog, options) {
1574
1570
  };
1575
1571
  }
1576
1572
  }
1577
- const catalogComponents = catalog.data.components;
1578
- if (catalogComponents) {
1579
- registryMetadata.set(registry, catalogComponents);
1580
- }
1573
+ (0, import_core6.setCatalogSlotMetadata)(registry, catalog);
1581
1574
  const actionMap = options.actions ? Object.entries(options.actions) : [];
1582
1575
  const handlers = (getSetState, getState) => {
1583
1576
  const result = {};
@@ -1601,20 +1594,13 @@ function defineRegistry(catalog, options) {
1601
1594
  }
1602
1595
  };
1603
1596
  if (options.onRenderError) {
1604
- Object.defineProperty(registry, "onRenderError", {
1605
- value: options.onRenderError,
1606
- enumerable: false,
1607
- configurable: true
1608
- });
1597
+ (0, import_core6.setRenderErrorHandler)(registry, options.onRenderError);
1609
1598
  }
1610
1599
  return { registry, handlers, executeAction: executeAction2 };
1611
1600
  }
1612
1601
  function createRenderer(catalog, components) {
1613
1602
  const registry = components;
1614
- const catalogComponents = catalog.data.components;
1615
- if (catalogComponents) {
1616
- registryMetadata.set(registry, catalogComponents);
1617
- }
1603
+ (0, import_core6.setCatalogSlotMetadata)(registry, catalog);
1618
1604
  return function CatalogRenderer({
1619
1605
  spec,
1620
1606
  store,