@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.mjs CHANGED
@@ -194,8 +194,8 @@ import { memo as _$memo } from "solid-js/web";
194
194
  import { insert as _$insert } from "solid-js/web";
195
195
  import { addEventListener as _$addEventListener } from "solid-js/web";
196
196
  import { createComponent as _$createComponent4 } from "solid-js/web";
197
- import { createContext as createContext4, useContext as useContext4, createSignal as createSignal3 } from "solid-js";
198
- import { resolveAction, executeAction, nextActionDispatchId, notifyActionDispatch, notifyActionSettle } from "@xmachines/json-render-core";
197
+ import { batch, createContext as createContext4, useContext as useContext4, createSignal as createSignal3, createMemo as createMemo3 } from "solid-js";
198
+ import { resolveAction, mergeActionHandlers, executeAction, isBuiltInAction, nextActionDispatchId, notifyActionDispatch, notifyActionSettle } from "@xmachines/json-render-core";
199
199
 
200
200
  // src/contexts/validation.tsx
201
201
  import { createComponent as _$createComponent3 } from "solid-js/web";
@@ -440,12 +440,18 @@ function ActionProvider(props) {
440
440
  set,
441
441
  getSnapshot
442
442
  } = useStateStore();
443
+ const writeTogether = (updates) => {
444
+ batch(() => {
445
+ for (const [path, value] of Object.entries(updates)) set(path, value);
446
+ });
447
+ };
443
448
  const validation = useOptionalValidation();
444
- const [handlers, setHandlers] = createSignal3(props.handlers ?? {});
449
+ const [registered, setRegistered] = createSignal3({});
450
+ const handlers = createMemo3(() => mergeActionHandlers(props.handlers ?? {}, registered()));
445
451
  const [loadingActions, setLoadingActions] = createSignal3(/* @__PURE__ */ new Set());
446
452
  const [pendingConfirmation, setPendingConfirmation] = createSignal3(null);
447
453
  const registerHandler = (name, handler) => {
448
- setHandlers((prev) => ({
454
+ setRegistered((prev) => ({
449
455
  ...prev,
450
456
  [name]: handler
451
457
  }));
@@ -465,6 +471,35 @@ function ActionProvider(props) {
465
471
  let __cancelled = false;
466
472
  let __confirmMs = void 0;
467
473
  try {
474
+ const handler = handlers()[resolved.action];
475
+ if (!handler && !isBuiltInAction(resolved.action)) {
476
+ console.warn(`No handler registered for action: ${resolved.action}`);
477
+ return;
478
+ }
479
+ if (resolved.confirm) {
480
+ pendingConfirmation()?.reject();
481
+ const confirmOpenedAt = Date.now();
482
+ const confirmed = await new Promise((res) => {
483
+ setPendingConfirmation({
484
+ action: resolved,
485
+ handler,
486
+ resolve: () => {
487
+ setPendingConfirmation(null);
488
+ res(true);
489
+ },
490
+ reject: () => {
491
+ setPendingConfirmation(null);
492
+ res(false);
493
+ }
494
+ });
495
+ });
496
+ __confirmMs = Date.now() - confirmOpenedAt;
497
+ if (!confirmed) {
498
+ __ok = false;
499
+ __cancelled = true;
500
+ return;
501
+ }
502
+ }
468
503
  if (resolved.action === "setState" && resolved.params) {
469
504
  const statePath = resolved.params.statePath;
470
505
  const value = resolved.params.value;
@@ -479,10 +514,14 @@ function ActionProvider(props) {
479
514
  if (statePath) {
480
515
  const resolvedValue = deepResolveValue(rawValue, get);
481
516
  const arr = get(statePath) ?? [];
482
- set(statePath, [...arr, resolvedValue]);
483
517
  const clearStatePath = resolved.params.clearStatePath;
484
518
  if (clearStatePath) {
485
- set(clearStatePath, "");
519
+ writeTogether({
520
+ [statePath]: [...arr, resolvedValue],
521
+ [clearStatePath]: ""
522
+ });
523
+ } else {
524
+ set(statePath, [...arr, resolvedValue]);
486
525
  }
487
526
  }
488
527
  return;
@@ -501,12 +540,10 @@ function ActionProvider(props) {
501
540
  if (screen) {
502
541
  const currentScreen = get("/currentScreen");
503
542
  const navStack = get("/navStack") ?? [];
504
- if (currentScreen) {
505
- set("/navStack", [...navStack, currentScreen]);
506
- } else {
507
- set("/navStack", [...navStack, ""]);
508
- }
509
- set("/currentScreen", screen);
543
+ writeTogether({
544
+ "/navStack": [...navStack, currentScreen ? currentScreen : ""],
545
+ "/currentScreen": screen
546
+ });
510
547
  }
511
548
  return;
512
549
  }
@@ -514,12 +551,10 @@ function ActionProvider(props) {
514
551
  const navStack = get("/navStack") ?? [];
515
552
  if (navStack.length > 0) {
516
553
  const previousScreen = navStack[navStack.length - 1];
517
- set("/navStack", navStack.slice(0, -1));
518
- if (previousScreen) {
519
- set("/currentScreen", previousScreen);
520
- } else {
521
- set("/currentScreen", void 0);
522
- }
554
+ writeTogether({
555
+ "/navStack": navStack.slice(0, -1),
556
+ "/currentScreen": previousScreen ? previousScreen : void 0
557
+ });
523
558
  }
524
559
  return;
525
560
  }
@@ -543,41 +578,14 @@ function ActionProvider(props) {
543
578
  });
544
579
  return;
545
580
  }
546
- const handler = handlers()[resolved.action];
547
- if (!handler) {
548
- console.warn(`No handler registered for action: ${resolved.action}`);
549
- return;
550
- }
551
- if (resolved.confirm) {
552
- pendingConfirmation()?.reject();
553
- const confirmOpenedAt = Date.now();
554
- const confirmed = await new Promise((res) => {
555
- setPendingConfirmation({
556
- action: resolved,
557
- handler,
558
- resolve: () => {
559
- setPendingConfirmation(null);
560
- res(true);
561
- },
562
- reject: () => {
563
- setPendingConfirmation(null);
564
- res(false);
565
- }
566
- });
567
- });
568
- __confirmMs = Date.now() - confirmOpenedAt;
569
- if (!confirmed) {
570
- __ok = false;
571
- __cancelled = true;
572
- return;
573
- }
574
- }
581
+ if (!handler) return;
575
582
  setLoadingActions((prev) => new Set(prev).add(resolved.action));
576
583
  try {
577
584
  await executeAction({
578
585
  action: resolved,
579
586
  handler,
580
587
  setState: set,
588
+ updateState: writeTogether,
581
589
  navigate: props.navigate,
582
590
  executeAction: async (binding2) => {
583
591
  await execute(binding2);
@@ -676,12 +684,19 @@ import { createContext as createContext5, useContext as useContext5 } from "soli
676
684
  var RepeatScopeContext = createContext5(null);
677
685
  function RepeatScopeProvider(props) {
678
686
  return _$createComponent5(RepeatScopeContext.Provider, {
679
- get value() {
680
- return {
681
- item: props.item,
682
- index: props.index,
683
- basePath: props.basePath
684
- };
687
+ value: {
688
+ // Getters, and not copies: a row that stays on the screen shows the
689
+ // item and the index of now, so a consumer that reads the scope in a
690
+ // tracked computation follows them.
691
+ get item() {
692
+ return props.item;
693
+ },
694
+ get index() {
695
+ return props.index;
696
+ },
697
+ get basePath() {
698
+ return props.basePath;
699
+ }
685
700
  },
686
701
  get children() {
687
702
  return props.children;
@@ -702,27 +717,16 @@ import { effect as _$effect2 } from "solid-js/web";
702
717
  import { insert as _$insert2 } from "solid-js/web";
703
718
  import { memo as _$memo2 } from "solid-js/web";
704
719
  import { createComponent as _$createComponent6 } from "solid-js/web";
705
- import { createContext as createContext6, useContext as useContext6, createMemo as createMemo3, createEffect as createEffect3, createRenderEffect, createSignal as createSignal4, untrack, onCleanup as onCleanup3, getOwner, runWithOwner, createRoot, ErrorBoundary, Show, For } from "solid-js";
706
- import { resolveElementProps, resolveBindings, resolveActionParam, resolveRepeatItemStatePath, resolveRepeatStatePath, evaluateVisibility as evaluateVisibility2, getByPath as getByPath2, isDevtoolsActive, subscribeDevtoolsActive, createDirectiveRegistry, copySlotMetadata, setCatalogSlotMetadata, warnElementSlots, splitRepeatVisibility } from "@xmachines/json-render-core";
720
+ import { createContext as createContext6, useContext as useContext6, createMemo as createMemo4, createEffect as createEffect3, createRenderEffect, createSignal as createSignal4, untrack, onCleanup as onCleanup3, getOwner, runWithOwner, createRoot, ErrorBoundary, Show, For } from "solid-js";
721
+ import { resolveElementProps, resolveBindings, resolveBindingParams, resolveRepeatItemStatePath, resolveRepeatStatePath, evaluateVisibility as evaluateVisibility2, getByPath as getByPath2, elementSubtreeJson, readWatchedValues, changedWatchPaths, runWatchBindings, isDevtoolsActive, subscribeDevtoolsActive, createDirectiveRegistry, withRenderErrorHandler, setRenderErrorHandler, createComponentRegistry, getRegistryComponent, warnUnusedRenderErrorHandler, getRenderErrorHandler, reportActionError, setCatalogSlotMetadata, warnElementSlots, splitRepeatVisibility } from "@xmachines/json-render-core";
707
722
  var _tmpl$2 = /* @__PURE__ */ _$template2(`<span style=display:contents>`);
708
- function withRenderErrorHandler(registry, onRenderError) {
709
- const next = {
710
- ...registry
711
- };
712
- Object.defineProperty(next, "onRenderError", {
713
- value: onRenderError,
714
- enumerable: false,
715
- configurable: true
716
- });
717
- copySlotMetadata(registry, next);
718
- return next;
719
- }
720
723
  function reportRenderError(registry, elementType, error) {
721
- const onRenderError = registry?.onRenderError;
722
- if (typeof onRenderError === "function") {
724
+ const onRenderError = getRenderErrorHandler(registry);
725
+ if (onRenderError !== void 0) {
723
726
  onRenderError(error, elementType);
724
727
  return;
725
728
  }
729
+ warnUnusedRenderErrorHandler(registry);
726
730
  console.error(`[json-render] Rendering error in <${elementType}>:`, error);
727
731
  }
728
732
  var EMPTY_FUNCTIONS = {};
@@ -752,7 +756,7 @@ function ElementRenderer(props) {
752
756
  const getSnapshot = () => stateStore.getSnapshot();
753
757
  const functions = useFunctions();
754
758
  const directives = useDirectives();
755
- const fullCtx = createMemo3(() => {
759
+ const fullCtx = createMemo4(() => {
756
760
  const repeatItem = repeatScope?.item;
757
761
  const repeatIndex = repeatScope?.index;
758
762
  const repeatBasePath = repeatScope?.basePath;
@@ -773,11 +777,11 @@ function ElementRenderer(props) {
773
777
  directives
774
778
  };
775
779
  });
776
- const repeatVisibility = createMemo3(() => props.element.repeat !== void 0 && !repeatScope ? splitRepeatVisibility(props.element.visible) : {
780
+ const repeatVisibility = createMemo4(() => props.element.repeat !== void 0 && !repeatScope ? splitRepeatVisibility(props.element.visible) : {
777
781
  container: props.element.visible,
778
782
  itemFilter: void 0
779
783
  });
780
- const isVisible = createMemo3(() => {
784
+ const isVisible = createMemo4(() => {
781
785
  const container = repeatVisibility().container;
782
786
  return container === void 0 ? true : evaluateVisibility2(container, fullCtx());
783
787
  });
@@ -786,23 +790,17 @@ function ElementRenderer(props) {
786
790
  const binding = onBindings?.[eventName];
787
791
  if (!binding) return;
788
792
  const actionBindings = Array.isArray(binding) ? binding : [binding];
789
- for (const b of actionBindings) {
790
- if (!b.params) {
791
- await execute(b);
792
- continue;
793
- }
794
- const liveCtx = {
795
- ...fullCtx(),
796
- stateModel: getSnapshot()
797
- };
798
- const resolved = {};
799
- for (const [key, val] of Object.entries(b.params)) {
800
- resolved[key] = resolveActionParam(val, liveCtx);
793
+ let action = "";
794
+ try {
795
+ for (const b of actionBindings) {
796
+ action = b.action;
797
+ await execute(resolveBindingParams(b, {
798
+ ...fullCtx(),
799
+ stateModel: getSnapshot()
800
+ }));
801
801
  }
802
- await execute({
803
- ...b,
804
- params: resolved
805
- });
802
+ } catch (err) {
803
+ reportActionError(getRenderErrorHandler(props.registry), err, action, "event");
806
804
  }
807
805
  };
808
806
  const on = (eventName) => {
@@ -824,49 +822,42 @@ function ElementRenderer(props) {
824
822
  bound: true
825
823
  };
826
824
  };
825
+ let stableWatched;
826
+ const watchedValues = createMemo4(() => {
827
+ const cfg = props.element.watch;
828
+ stableWatched = cfg ? readWatchedValues(cfg, stateStore.state, stableWatched) : void 0;
829
+ return stableWatched;
830
+ });
831
+ let previousWatched = untrack(watchedValues);
827
832
  createEffect3(() => {
828
- const watchConfig = props.element.watch;
829
- if (!watchConfig) return;
830
- const paths = Object.keys(watchConfig);
831
- if (paths.length === 0) return;
832
- const unsubscribe = stateStore.subscribeChanges((changes) => {
833
- const changedPaths = new Set(changes.map((change) => change.path));
834
- void (async () => {
835
- for (const path of paths) {
836
- if (!changedPaths.has(path)) continue;
837
- const binding = watchConfig[path];
838
- if (!binding) continue;
839
- const bindings = Array.isArray(binding) ? binding : [binding];
840
- for (const b of bindings) {
841
- if (!b.params) {
842
- await execute(b);
843
- continue;
844
- }
845
- const liveCtx = {
846
- ...fullCtx(),
847
- stateModel: getSnapshot()
848
- };
849
- const resolved = {};
850
- for (const [key, val] of Object.entries(b.params)) {
851
- resolved[key] = resolveActionParam(val, liveCtx);
852
- }
853
- await execute({
854
- ...b,
855
- params: resolved
856
- });
857
- }
858
- }
859
- })().catch(console.error);
860
- });
833
+ const current = watchedValues();
834
+ const prev = previousWatched;
835
+ previousWatched = current;
836
+ const paths = changedWatchPaths(current, prev);
837
+ const watchConfig = untrack(() => props.element.watch);
838
+ if (!watchConfig || paths.length === 0) return;
839
+ let cancelled = false;
861
840
  onCleanup3(() => {
862
- unsubscribe();
841
+ cancelled = true;
842
+ });
843
+ untrack(() => {
844
+ let action = "";
845
+ void runWatchBindings(watchConfig, paths, async (b) => {
846
+ action = b.action;
847
+ await execute(resolveBindingParams(b, {
848
+ ...fullCtx(),
849
+ stateModel: getSnapshot()
850
+ }));
851
+ }, () => cancelled).catch((err) => {
852
+ reportActionError(getRenderErrorHandler(props.registry), err, action, "watch");
853
+ });
863
854
  });
864
855
  });
865
- const elementBindings = createMemo3(() => {
856
+ const elementBindings = createMemo4(() => {
866
857
  const rawProps = props.element.props;
867
858
  return resolveBindings(rawProps, fullCtx());
868
859
  });
869
- const resolvedElement = createMemo3(() => {
860
+ const resolvedElement = createMemo4(() => {
870
861
  const rawProps = props.element.props;
871
862
  const resolvedProps = resolveElementProps(rawProps, fullCtx());
872
863
  return resolvedProps !== props.element.props ? {
@@ -880,8 +871,13 @@ function ElementRenderer(props) {
880
871
  },
881
872
  get children() {
882
873
  return _$createComponent6(ErrorBoundary, {
883
- fallback: (err) => {
874
+ fallback: (err, reset) => {
884
875
  reportRenderError(props.registry, props.element.type, err);
876
+ const subtree = () => elementSubtreeJson(props.spec, props.elementKey, props.element);
877
+ const failed = untrack(subtree);
878
+ createEffect3(() => {
879
+ if (subtree() !== failed) reset();
880
+ });
885
881
  return null;
886
882
  },
887
883
  get children() {
@@ -920,7 +916,7 @@ function ElementRenderer(props) {
920
916
  }
921
917
  function ElementRendererContent(props) {
922
918
  const devtoolsActive = useDevtoolsActive();
923
- const Comp = () => props.registry[props.resolvedElement.type] ?? props.fallback;
919
+ const Comp = () => getRegistryComponent(props.registry, props.resolvedElement.type) ?? props.fallback;
924
920
  return _$createComponent6(Show, {
925
921
  get when() {
926
922
  return Comp();
@@ -931,7 +927,7 @@ function ElementRendererContent(props) {
931
927
  return null;
932
928
  },
933
929
  children: (Component) => {
934
- const elementSlots = createMemo3(() => props.resolvedElement.slots);
930
+ const elementSlots = createMemo4(() => props.resolvedElement.slots);
935
931
  createRenderEffect(() => {
936
932
  const slotEntries = elementSlots();
937
933
  untrack(() => warnElementSlots(props.registry, props.resolvedElement.type, slotEntries));
@@ -1129,23 +1125,44 @@ function RepeatChildren(props) {
1129
1125
  repeatItem: itemValue,
1130
1126
  repeatIndex: index
1131
1127
  }));
1128
+ const keyed = createMemo4(() => {
1129
+ const r = repeat();
1130
+ const path = statePath();
1131
+ const byKey = /* @__PURE__ */ new Map();
1132
+ const keys = [];
1133
+ for (const entry of entries()) {
1134
+ const {
1135
+ itemValue,
1136
+ index
1137
+ } = entry;
1138
+ const itemKey = r.key && typeof itemValue === "object" && itemValue !== null ? String(itemValue[r.key] ?? "") : "";
1139
+ const key = JSON.stringify([path, index, itemKey]);
1140
+ byKey.set(key, entry);
1141
+ keys.push(key);
1142
+ }
1143
+ return {
1144
+ keys,
1145
+ byKey
1146
+ };
1147
+ });
1132
1148
  return _$createComponent6(For, {
1133
1149
  get each() {
1134
- return entries();
1150
+ return keyed().keys;
1135
1151
  },
1136
- children: ({
1137
- itemValue,
1138
- index
1139
- }) => {
1140
- const key = () => {
1141
- const r = repeat();
1142
- return r.key && typeof itemValue === "object" && itemValue !== null ? String(itemValue[r.key] ?? index) : String(index);
1143
- };
1152
+ children: (key) => {
1153
+ const entry = createMemo4(() => keyed().byKey.get(key), void 0, {
1154
+ equals: (a, b) => a?.itemValue === b?.itemValue
1155
+ });
1156
+ const index = () => entry()?.index ?? 0;
1144
1157
  return _$createComponent6(RepeatScopeProvider, {
1145
- item: itemValue,
1146
- index,
1158
+ get item() {
1159
+ return entry()?.itemValue;
1160
+ },
1161
+ get index() {
1162
+ return index();
1163
+ },
1147
1164
  get basePath() {
1148
- return resolveRepeatItemStatePath(statePath(), index);
1165
+ return resolveRepeatItemStatePath(statePath(), index());
1149
1166
  },
1150
1167
  get children() {
1151
1168
  return _$createComponent6(For, {
@@ -1168,6 +1185,7 @@ function RepeatChildren(props) {
1168
1185
  get element() {
1169
1186
  return el();
1170
1187
  },
1188
+ elementKey: childKey,
1171
1189
  get spec() {
1172
1190
  return props.spec;
1173
1191
  },
@@ -1190,12 +1208,12 @@ function RepeatChildren(props) {
1190
1208
  });
1191
1209
  }
1192
1210
  function Renderer(props) {
1193
- const rootElement = createMemo3(() => {
1211
+ const rootElement = createMemo4(() => {
1194
1212
  const spec = props.spec;
1195
1213
  if (!spec || !spec.root) return void 0;
1196
1214
  return spec.elements[spec.root];
1197
1215
  });
1198
- const rendererRegistry = createMemo3(() => props.onRenderError ? withRenderErrorHandler(props.registry, props.onRenderError) : props.registry);
1216
+ const rendererRegistry = createMemo4(() => props.onRenderError ? withRenderErrorHandler(props.registry, props.onRenderError) : props.registry);
1199
1217
  return _$createComponent6(Show, {
1200
1218
  get when() {
1201
1219
  return rootElement();
@@ -1223,7 +1241,7 @@ function Renderer(props) {
1223
1241
  });
1224
1242
  }
1225
1243
  function JSONUIProvider(props) {
1226
- const directiveRegistry = createMemo3(() => props.directives ? createDirectiveRegistry(props.directives) : void 0);
1244
+ const directiveRegistry = createMemo4(() => props.directives ? createDirectiveRegistry(props.directives) : void 0);
1227
1245
  return _$createComponent6(StateProvider, {
1228
1246
  get store() {
1229
1247
  return props.store;
@@ -1294,7 +1312,7 @@ function ConfirmationDialogManager() {
1294
1312
  });
1295
1313
  }
1296
1314
  function defineRegistry(catalog, options) {
1297
- const registry = {};
1315
+ const registry = createComponentRegistry(options.components);
1298
1316
  if (options.components) {
1299
1317
  for (const [name, componentFn] of Object.entries(options.components)) {
1300
1318
  registry[name] = (renderProps) => {
@@ -1344,11 +1362,7 @@ function defineRegistry(catalog, options) {
1344
1362
  }
1345
1363
  };
1346
1364
  if (options.onRenderError) {
1347
- Object.defineProperty(registry, "onRenderError", {
1348
- value: options.onRenderError,
1349
- enumerable: false,
1350
- configurable: true
1351
- });
1365
+ setRenderErrorHandler(registry, options.onRenderError);
1352
1366
  }
1353
1367
  return {
1354
1368
  registry,
@@ -1360,8 +1374,8 @@ function createRenderer(catalog, components) {
1360
1374
  const registry = components;
1361
1375
  setCatalogSlotMetadata(registry, catalog);
1362
1376
  return function CatalogRenderer(props) {
1363
- const directiveRegistry = createMemo3(() => props.directives ? createDirectiveRegistry(props.directives) : void 0);
1364
- const rendererRegistry = createMemo3(() => props.onRenderError ? withRenderErrorHandler(registry, props.onRenderError) : registry);
1377
+ const directiveRegistry = createMemo4(() => props.directives ? createDirectiveRegistry(props.directives) : void 0);
1378
+ const rendererRegistry = createMemo4(() => props.onRenderError ? withRenderErrorHandler(registry, props.onRenderError) : registry);
1365
1379
  const actionHandlers = () => props.onAction ? new Proxy({}, {
1366
1380
  get: (_target, prop) => {
1367
1381
  return (params) => props.onAction(prop, params);
@@ -1428,7 +1442,7 @@ function createRenderer(catalog, components) {
1428
1442
  }
1429
1443
 
1430
1444
  // src/hooks.ts
1431
- import { createSignal as createSignal5, onCleanup as onCleanup4, createMemo as createMemo4 } from "solid-js";
1445
+ import { createSignal as createSignal5, onCleanup as onCleanup4, createMemo as createMemo5 } from "solid-js";
1432
1446
  import {
1433
1447
  setByPath,
1434
1448
  getByPath as getByPath3,
@@ -1764,7 +1778,7 @@ function getTextFromParts(parts) {
1764
1778
  ).map((p) => p.text.trim()).filter(Boolean).join("\n\n");
1765
1779
  }
1766
1780
  function useJsonRenderMessage(getParts) {
1767
- const result = createMemo4(() => {
1781
+ const result = createMemo5(() => {
1768
1782
  const parts = getParts();
1769
1783
  return {
1770
1784
  spec: buildSpecFromParts(parts),