@xmachines/json-render-solid 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
@@ -10,6 +10,12 @@ interface StateContextValue {
10
10
  set: (path: string, value: unknown) => void;
11
11
  update: (updates: Record<string, unknown>) => void;
12
12
  getSnapshot: () => StateModel;
13
+ /**
14
+ * Hear the paths that `set` and `update` of this context write. The watch
15
+ * of the renderer reads the reactive state and does not use it, because a
16
+ * write from the store or to a parent path emits no change here. It stays
17
+ * for hosts that use it.
18
+ */
13
19
  subscribeChanges: (listener: (changes: Array<{
14
20
  path: string;
15
21
  value: unknown;
@@ -39,7 +45,8 @@ declare function useIsVisible(condition: VisibilityCondition | undefined): boole
39
45
 
40
46
  interface PendingConfirmation {
41
47
  action: ResolvedAction;
42
- handler: ActionHandler;
48
+ /** The handler of the host, or undefined for a built-in action. */
49
+ handler: ActionHandler | undefined;
43
50
  resolve: () => void;
44
51
  reject: () => void;
45
52
  }
@@ -111,6 +118,13 @@ interface RepeatScopeValue {
111
118
  basePath: string;
112
119
  }
113
120
  declare function RepeatScopeProvider(props: ParentProps<RepeatScopeValue>): solid_js.JSX.Element;
121
+ /**
122
+ * The repeat scope of the row that renders now, or `null` outside a repeat.
123
+ *
124
+ * Read `item`, `index` and `basePath` in a tracked place: the JSX, a memo or
125
+ * an effect. A row stays mounted across a write to its own item, so a copy
126
+ * that the component makes when it is set up keeps the item of then.
127
+ */
114
128
  declare function useRepeatScope(): RepeatScopeValue | null;
115
129
 
116
130
  /**
package/dist/index.d.ts CHANGED
@@ -10,6 +10,12 @@ interface StateContextValue {
10
10
  set: (path: string, value: unknown) => void;
11
11
  update: (updates: Record<string, unknown>) => void;
12
12
  getSnapshot: () => StateModel;
13
+ /**
14
+ * Hear the paths that `set` and `update` of this context write. The watch
15
+ * of the renderer reads the reactive state and does not use it, because a
16
+ * write from the store or to a parent path emits no change here. It stays
17
+ * for hosts that use it.
18
+ */
13
19
  subscribeChanges: (listener: (changes: Array<{
14
20
  path: string;
15
21
  value: unknown;
@@ -39,7 +45,8 @@ declare function useIsVisible(condition: VisibilityCondition | undefined): boole
39
45
 
40
46
  interface PendingConfirmation {
41
47
  action: ResolvedAction;
42
- handler: ActionHandler;
48
+ /** The handler of the host, or undefined for a built-in action. */
49
+ handler: ActionHandler | undefined;
43
50
  resolve: () => void;
44
51
  reject: () => void;
45
52
  }
@@ -111,6 +118,13 @@ interface RepeatScopeValue {
111
118
  basePath: string;
112
119
  }
113
120
  declare function RepeatScopeProvider(props: ParentProps<RepeatScopeValue>): solid_js.JSX.Element;
121
+ /**
122
+ * The repeat scope of the row that renders now, or `null` outside a repeat.
123
+ *
124
+ * Read `item`, `index` and `basePath` in a tracked place: the JSX, a memo or
125
+ * an effect. A row stays mounted across a write to its own item, so a copy
126
+ * that the component makes when it is set up keeps the item of then.
127
+ */
114
128
  declare function useRepeatScope(): RepeatScopeValue | null;
115
129
 
116
130
  /**
package/dist/index.js CHANGED
@@ -491,12 +491,18 @@ function ActionProvider(props) {
491
491
  set,
492
492
  getSnapshot
493
493
  } = useStateStore();
494
+ const writeTogether = (updates) => {
495
+ (0, import_solid_js4.batch)(() => {
496
+ for (const [path, value] of Object.entries(updates)) set(path, value);
497
+ });
498
+ };
494
499
  const validation = useOptionalValidation();
495
- const [handlers, setHandlers] = (0, import_solid_js4.createSignal)(props.handlers ?? {});
500
+ const [registered, setRegistered] = (0, import_solid_js4.createSignal)({});
501
+ const handlers = (0, import_solid_js4.createMemo)(() => (0, import_core4.mergeActionHandlers)(props.handlers ?? {}, registered()));
496
502
  const [loadingActions, setLoadingActions] = (0, import_solid_js4.createSignal)(/* @__PURE__ */ new Set());
497
503
  const [pendingConfirmation, setPendingConfirmation] = (0, import_solid_js4.createSignal)(null);
498
504
  const registerHandler = (name, handler) => {
499
- setHandlers((prev) => ({
505
+ setRegistered((prev) => ({
500
506
  ...prev,
501
507
  [name]: handler
502
508
  }));
@@ -516,6 +522,35 @@ function ActionProvider(props) {
516
522
  let __cancelled = false;
517
523
  let __confirmMs = void 0;
518
524
  try {
525
+ const handler = handlers()[resolved.action];
526
+ if (!handler && !(0, import_core4.isBuiltInAction)(resolved.action)) {
527
+ console.warn(`No handler registered for action: ${resolved.action}`);
528
+ return;
529
+ }
530
+ if (resolved.confirm) {
531
+ pendingConfirmation()?.reject();
532
+ const confirmOpenedAt = Date.now();
533
+ const confirmed = await new Promise((res) => {
534
+ setPendingConfirmation({
535
+ action: resolved,
536
+ handler,
537
+ resolve: () => {
538
+ setPendingConfirmation(null);
539
+ res(true);
540
+ },
541
+ reject: () => {
542
+ setPendingConfirmation(null);
543
+ res(false);
544
+ }
545
+ });
546
+ });
547
+ __confirmMs = Date.now() - confirmOpenedAt;
548
+ if (!confirmed) {
549
+ __ok = false;
550
+ __cancelled = true;
551
+ return;
552
+ }
553
+ }
519
554
  if (resolved.action === "setState" && resolved.params) {
520
555
  const statePath = resolved.params.statePath;
521
556
  const value = resolved.params.value;
@@ -530,10 +565,14 @@ function ActionProvider(props) {
530
565
  if (statePath) {
531
566
  const resolvedValue = deepResolveValue(rawValue, get);
532
567
  const arr = get(statePath) ?? [];
533
- set(statePath, [...arr, resolvedValue]);
534
568
  const clearStatePath = resolved.params.clearStatePath;
535
569
  if (clearStatePath) {
536
- set(clearStatePath, "");
570
+ writeTogether({
571
+ [statePath]: [...arr, resolvedValue],
572
+ [clearStatePath]: ""
573
+ });
574
+ } else {
575
+ set(statePath, [...arr, resolvedValue]);
537
576
  }
538
577
  }
539
578
  return;
@@ -552,12 +591,10 @@ function ActionProvider(props) {
552
591
  if (screen) {
553
592
  const currentScreen = get("/currentScreen");
554
593
  const navStack = get("/navStack") ?? [];
555
- if (currentScreen) {
556
- set("/navStack", [...navStack, currentScreen]);
557
- } else {
558
- set("/navStack", [...navStack, ""]);
559
- }
560
- set("/currentScreen", screen);
594
+ writeTogether({
595
+ "/navStack": [...navStack, currentScreen ? currentScreen : ""],
596
+ "/currentScreen": screen
597
+ });
561
598
  }
562
599
  return;
563
600
  }
@@ -565,12 +602,10 @@ function ActionProvider(props) {
565
602
  const navStack = get("/navStack") ?? [];
566
603
  if (navStack.length > 0) {
567
604
  const previousScreen = navStack[navStack.length - 1];
568
- set("/navStack", navStack.slice(0, -1));
569
- if (previousScreen) {
570
- set("/currentScreen", previousScreen);
571
- } else {
572
- set("/currentScreen", void 0);
573
- }
605
+ writeTogether({
606
+ "/navStack": navStack.slice(0, -1),
607
+ "/currentScreen": previousScreen ? previousScreen : void 0
608
+ });
574
609
  }
575
610
  return;
576
611
  }
@@ -594,41 +629,14 @@ function ActionProvider(props) {
594
629
  });
595
630
  return;
596
631
  }
597
- const handler = handlers()[resolved.action];
598
- if (!handler) {
599
- console.warn(`No handler registered for action: ${resolved.action}`);
600
- return;
601
- }
602
- if (resolved.confirm) {
603
- pendingConfirmation()?.reject();
604
- const confirmOpenedAt = Date.now();
605
- const confirmed = await new Promise((res) => {
606
- setPendingConfirmation({
607
- action: resolved,
608
- handler,
609
- resolve: () => {
610
- setPendingConfirmation(null);
611
- res(true);
612
- },
613
- reject: () => {
614
- setPendingConfirmation(null);
615
- res(false);
616
- }
617
- });
618
- });
619
- __confirmMs = Date.now() - confirmOpenedAt;
620
- if (!confirmed) {
621
- __ok = false;
622
- __cancelled = true;
623
- return;
624
- }
625
- }
632
+ if (!handler) return;
626
633
  setLoadingActions((prev) => new Set(prev).add(resolved.action));
627
634
  try {
628
635
  await (0, import_core4.executeAction)({
629
636
  action: resolved,
630
637
  handler,
631
638
  setState: set,
639
+ updateState: writeTogether,
632
640
  navigate: props.navigate,
633
641
  executeAction: async (binding2) => {
634
642
  await execute(binding2);
@@ -727,12 +735,19 @@ var import_solid_js5 = require("solid-js");
727
735
  var RepeatScopeContext = (0, import_solid_js5.createContext)(null);
728
736
  function RepeatScopeProvider(props) {
729
737
  return (0, import_web12.createComponent)(RepeatScopeContext.Provider, {
730
- get value() {
731
- return {
732
- item: props.item,
733
- index: props.index,
734
- basePath: props.basePath
735
- };
738
+ value: {
739
+ // Getters, and not copies: a row that stays on the screen shows the
740
+ // item and the index of now, so a consumer that reads the scope in a
741
+ // tracked computation follows them.
742
+ get item() {
743
+ return props.item;
744
+ },
745
+ get index() {
746
+ return props.index;
747
+ },
748
+ get basePath() {
749
+ return props.basePath;
750
+ }
736
751
  },
737
752
  get children() {
738
753
  return props.children;
@@ -843,24 +858,13 @@ var import_web18 = require("solid-js/web");
843
858
  var import_solid_js6 = require("solid-js");
844
859
  var import_core6 = require("@xmachines/json-render-core");
845
860
  var _tmpl$2 = /* @__PURE__ */ (0, import_web13.template)(`<span style=display:contents>`);
846
- function withRenderErrorHandler(registry, onRenderError) {
847
- const next = {
848
- ...registry
849
- };
850
- Object.defineProperty(next, "onRenderError", {
851
- value: onRenderError,
852
- enumerable: false,
853
- configurable: true
854
- });
855
- (0, import_core6.copySlotMetadata)(registry, next);
856
- return next;
857
- }
858
861
  function reportRenderError(registry, elementType, error) {
859
- const onRenderError = registry?.onRenderError;
860
- if (typeof onRenderError === "function") {
862
+ const onRenderError = (0, import_core6.getRenderErrorHandler)(registry);
863
+ if (onRenderError !== void 0) {
861
864
  onRenderError(error, elementType);
862
865
  return;
863
866
  }
867
+ (0, import_core6.warnUnusedRenderErrorHandler)(registry);
864
868
  console.error(`[json-render] Rendering error in <${elementType}>:`, error);
865
869
  }
866
870
  var EMPTY_FUNCTIONS = {};
@@ -924,23 +928,17 @@ function ElementRenderer(props) {
924
928
  const binding = onBindings?.[eventName];
925
929
  if (!binding) return;
926
930
  const actionBindings = Array.isArray(binding) ? binding : [binding];
927
- for (const b of actionBindings) {
928
- if (!b.params) {
929
- await execute(b);
930
- continue;
931
- }
932
- const liveCtx = {
933
- ...fullCtx(),
934
- stateModel: getSnapshot()
935
- };
936
- const resolved = {};
937
- for (const [key, val] of Object.entries(b.params)) {
938
- resolved[key] = (0, import_core6.resolveActionParam)(val, liveCtx);
931
+ let action = "";
932
+ try {
933
+ for (const b of actionBindings) {
934
+ action = b.action;
935
+ await execute((0, import_core6.resolveBindingParams)(b, {
936
+ ...fullCtx(),
937
+ stateModel: getSnapshot()
938
+ }));
939
939
  }
940
- await execute({
941
- ...b,
942
- params: resolved
943
- });
940
+ } catch (err) {
941
+ (0, import_core6.reportActionError)((0, import_core6.getRenderErrorHandler)(props.registry), err, action, "event");
944
942
  }
945
943
  };
946
944
  const on = (eventName) => {
@@ -962,42 +960,35 @@ function ElementRenderer(props) {
962
960
  bound: true
963
961
  };
964
962
  };
963
+ let stableWatched;
964
+ const watchedValues = (0, import_solid_js6.createMemo)(() => {
965
+ const cfg = props.element.watch;
966
+ stableWatched = cfg ? (0, import_core6.readWatchedValues)(cfg, stateStore.state, stableWatched) : void 0;
967
+ return stableWatched;
968
+ });
969
+ let previousWatched = (0, import_solid_js6.untrack)(watchedValues);
965
970
  (0, import_solid_js6.createEffect)(() => {
966
- const watchConfig = props.element.watch;
967
- if (!watchConfig) return;
968
- const paths = Object.keys(watchConfig);
969
- if (paths.length === 0) return;
970
- const unsubscribe = stateStore.subscribeChanges((changes) => {
971
- const changedPaths = new Set(changes.map((change) => change.path));
972
- void (async () => {
973
- for (const path of paths) {
974
- if (!changedPaths.has(path)) continue;
975
- const binding = watchConfig[path];
976
- if (!binding) continue;
977
- const bindings = Array.isArray(binding) ? binding : [binding];
978
- for (const b of bindings) {
979
- if (!b.params) {
980
- await execute(b);
981
- continue;
982
- }
983
- const liveCtx = {
984
- ...fullCtx(),
985
- stateModel: getSnapshot()
986
- };
987
- const resolved = {};
988
- for (const [key, val] of Object.entries(b.params)) {
989
- resolved[key] = (0, import_core6.resolveActionParam)(val, liveCtx);
990
- }
991
- await execute({
992
- ...b,
993
- params: resolved
994
- });
995
- }
996
- }
997
- })().catch(console.error);
998
- });
971
+ const current = watchedValues();
972
+ const prev = previousWatched;
973
+ previousWatched = current;
974
+ const paths = (0, import_core6.changedWatchPaths)(current, prev);
975
+ const watchConfig = (0, import_solid_js6.untrack)(() => props.element.watch);
976
+ if (!watchConfig || paths.length === 0) return;
977
+ let cancelled = false;
999
978
  (0, import_solid_js6.onCleanup)(() => {
1000
- unsubscribe();
979
+ cancelled = true;
980
+ });
981
+ (0, import_solid_js6.untrack)(() => {
982
+ let action = "";
983
+ void (0, import_core6.runWatchBindings)(watchConfig, paths, async (b) => {
984
+ action = b.action;
985
+ await execute((0, import_core6.resolveBindingParams)(b, {
986
+ ...fullCtx(),
987
+ stateModel: getSnapshot()
988
+ }));
989
+ }, () => cancelled).catch((err) => {
990
+ (0, import_core6.reportActionError)((0, import_core6.getRenderErrorHandler)(props.registry), err, action, "watch");
991
+ });
1001
992
  });
1002
993
  });
1003
994
  const elementBindings = (0, import_solid_js6.createMemo)(() => {
@@ -1018,8 +1009,13 @@ function ElementRenderer(props) {
1018
1009
  },
1019
1010
  get children() {
1020
1011
  return (0, import_web18.createComponent)(import_solid_js6.ErrorBoundary, {
1021
- fallback: (err) => {
1012
+ fallback: (err, reset) => {
1022
1013
  reportRenderError(props.registry, props.element.type, err);
1014
+ const subtree = () => (0, import_core6.elementSubtreeJson)(props.spec, props.elementKey, props.element);
1015
+ const failed = (0, import_solid_js6.untrack)(subtree);
1016
+ (0, import_solid_js6.createEffect)(() => {
1017
+ if (subtree() !== failed) reset();
1018
+ });
1023
1019
  return null;
1024
1020
  },
1025
1021
  get children() {
@@ -1058,7 +1054,7 @@ function ElementRenderer(props) {
1058
1054
  }
1059
1055
  function ElementRendererContent(props) {
1060
1056
  const devtoolsActive = useDevtoolsActive();
1061
- const Comp = () => props.registry[props.resolvedElement.type] ?? props.fallback;
1057
+ const Comp = () => (0, import_core6.getRegistryComponent)(props.registry, props.resolvedElement.type) ?? props.fallback;
1062
1058
  return (0, import_web18.createComponent)(import_solid_js6.Show, {
1063
1059
  get when() {
1064
1060
  return Comp();
@@ -1267,23 +1263,44 @@ function RepeatChildren(props) {
1267
1263
  repeatItem: itemValue,
1268
1264
  repeatIndex: index
1269
1265
  }));
1266
+ const keyed = (0, import_solid_js6.createMemo)(() => {
1267
+ const r = repeat();
1268
+ const path = statePath();
1269
+ const byKey = /* @__PURE__ */ new Map();
1270
+ const keys = [];
1271
+ for (const entry of entries()) {
1272
+ const {
1273
+ itemValue,
1274
+ index
1275
+ } = entry;
1276
+ const itemKey = r.key && typeof itemValue === "object" && itemValue !== null ? String(itemValue[r.key] ?? "") : "";
1277
+ const key = JSON.stringify([path, index, itemKey]);
1278
+ byKey.set(key, entry);
1279
+ keys.push(key);
1280
+ }
1281
+ return {
1282
+ keys,
1283
+ byKey
1284
+ };
1285
+ });
1270
1286
  return (0, import_web18.createComponent)(import_solid_js6.For, {
1271
1287
  get each() {
1272
- return entries();
1288
+ return keyed().keys;
1273
1289
  },
1274
- children: ({
1275
- itemValue,
1276
- index
1277
- }) => {
1278
- const key = () => {
1279
- const r = repeat();
1280
- return r.key && typeof itemValue === "object" && itemValue !== null ? String(itemValue[r.key] ?? index) : String(index);
1281
- };
1290
+ children: (key) => {
1291
+ const entry = (0, import_solid_js6.createMemo)(() => keyed().byKey.get(key), void 0, {
1292
+ equals: (a, b) => a?.itemValue === b?.itemValue
1293
+ });
1294
+ const index = () => entry()?.index ?? 0;
1282
1295
  return (0, import_web18.createComponent)(RepeatScopeProvider, {
1283
- item: itemValue,
1284
- index,
1296
+ get item() {
1297
+ return entry()?.itemValue;
1298
+ },
1299
+ get index() {
1300
+ return index();
1301
+ },
1285
1302
  get basePath() {
1286
- return (0, import_core6.resolveRepeatItemStatePath)(statePath(), index);
1303
+ return (0, import_core6.resolveRepeatItemStatePath)(statePath(), index());
1287
1304
  },
1288
1305
  get children() {
1289
1306
  return (0, import_web18.createComponent)(import_solid_js6.For, {
@@ -1306,6 +1323,7 @@ function RepeatChildren(props) {
1306
1323
  get element() {
1307
1324
  return el();
1308
1325
  },
1326
+ elementKey: childKey,
1309
1327
  get spec() {
1310
1328
  return props.spec;
1311
1329
  },
@@ -1333,7 +1351,7 @@ function Renderer(props) {
1333
1351
  if (!spec || !spec.root) return void 0;
1334
1352
  return spec.elements[spec.root];
1335
1353
  });
1336
- const rendererRegistry = (0, import_solid_js6.createMemo)(() => props.onRenderError ? withRenderErrorHandler(props.registry, props.onRenderError) : props.registry);
1354
+ const rendererRegistry = (0, import_solid_js6.createMemo)(() => props.onRenderError ? (0, import_core6.withRenderErrorHandler)(props.registry, props.onRenderError) : props.registry);
1337
1355
  return (0, import_web18.createComponent)(import_solid_js6.Show, {
1338
1356
  get when() {
1339
1357
  return rootElement();
@@ -1432,7 +1450,7 @@ function ConfirmationDialogManager() {
1432
1450
  });
1433
1451
  }
1434
1452
  function defineRegistry(catalog, options) {
1435
- const registry = {};
1453
+ const registry = (0, import_core6.createComponentRegistry)(options.components);
1436
1454
  if (options.components) {
1437
1455
  for (const [name, componentFn] of Object.entries(options.components)) {
1438
1456
  registry[name] = (renderProps) => {
@@ -1482,11 +1500,7 @@ function defineRegistry(catalog, options) {
1482
1500
  }
1483
1501
  };
1484
1502
  if (options.onRenderError) {
1485
- Object.defineProperty(registry, "onRenderError", {
1486
- value: options.onRenderError,
1487
- enumerable: false,
1488
- configurable: true
1489
- });
1503
+ (0, import_core6.setRenderErrorHandler)(registry, options.onRenderError);
1490
1504
  }
1491
1505
  return {
1492
1506
  registry,
@@ -1499,7 +1513,7 @@ function createRenderer(catalog, components) {
1499
1513
  (0, import_core6.setCatalogSlotMetadata)(registry, catalog);
1500
1514
  return function CatalogRenderer(props) {
1501
1515
  const directiveRegistry = (0, import_solid_js6.createMemo)(() => props.directives ? (0, import_core6.createDirectiveRegistry)(props.directives) : void 0);
1502
- const rendererRegistry = (0, import_solid_js6.createMemo)(() => props.onRenderError ? withRenderErrorHandler(registry, props.onRenderError) : registry);
1516
+ const rendererRegistry = (0, import_solid_js6.createMemo)(() => props.onRenderError ? (0, import_core6.withRenderErrorHandler)(registry, props.onRenderError) : registry);
1503
1517
  const actionHandlers = () => props.onAction ? new Proxy({}, {
1504
1518
  get: (_target, prop) => {
1505
1519
  return (params) => props.onAction(prop, params);