@xmachines/json-render-react 0.19.0-xm.3 → 0.20.0-xm.2

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.js CHANGED
@@ -272,8 +272,10 @@ function ValidationProvider({
272
272
  const [fieldStates, setFieldStates] = (0, import_react3.useState)({});
273
273
  const fieldStatesRef = (0, import_react3.useRef)({});
274
274
  const [fieldConfigs, setFieldConfigs] = (0, import_react3.useState)({});
275
+ const registrationCounts = (0, import_react3.useRef)({});
275
276
  const registerField = (0, import_react3.useCallback)(
276
277
  (path, config) => {
278
+ registrationCounts.current[path] = (registrationCounts.current[path] ?? 0) + 1;
277
279
  setFieldConfigs((prev) => {
278
280
  const existing = prev[path];
279
281
  if (existing && validationConfigEqual(existing, config)) {
@@ -284,6 +286,20 @@ function ValidationProvider({
284
286
  },
285
287
  []
286
288
  );
289
+ const unregisterField = (0, import_react3.useCallback)((path) => {
290
+ const next = (registrationCounts.current[path] ?? 0) - 1;
291
+ if (next > 0) {
292
+ registrationCounts.current[path] = next;
293
+ return;
294
+ }
295
+ delete registrationCounts.current[path];
296
+ delete fieldStatesRef.current[path];
297
+ setFieldConfigs((prev) => {
298
+ if (!(path in prev)) return prev;
299
+ const { [path]: _removed, ...rest } = prev;
300
+ return rest;
301
+ });
302
+ }, []);
287
303
  const validate = (0, import_react3.useCallback)(
288
304
  (path, config) => {
289
305
  const currentState = getSnapshot();
@@ -355,7 +371,8 @@ function ValidationProvider({
355
371
  touch,
356
372
  clear,
357
373
  validateAll,
358
- registerField
374
+ registerField,
375
+ unregisterField
359
376
  }),
360
377
  [
361
378
  customFunctions,
@@ -366,7 +383,8 @@ function ValidationProvider({
366
383
  touch,
367
384
  clear,
368
385
  validateAll,
369
- registerField
386
+ registerField,
387
+ unregisterField
370
388
  ]
371
389
  );
372
390
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ValidationContext.Provider, { value, children });
@@ -381,19 +399,27 @@ function useValidation() {
381
399
  function useOptionalValidation() {
382
400
  return (0, import_react3.useContext)(ValidationContext);
383
401
  }
402
+ var useIsomorphicLayoutEffect = typeof document !== "undefined" ? import_react3.default.useLayoutEffect : import_react3.default.useEffect;
384
403
  function useFieldValidation(path, config) {
385
404
  const {
386
405
  fieldStates,
387
406
  validate: validateField,
388
407
  touch: touchField,
389
408
  clear: clearField,
390
- registerField
409
+ registerField,
410
+ unregisterField
391
411
  } = useValidation();
392
- import_react3.default.useEffect(() => {
393
- if (path && config) {
394
- registerField(path, config);
412
+ const configKey = config === void 0 ? void 0 : JSON.stringify(config);
413
+ const configRef = import_react3.default.useRef(config);
414
+ configRef.current = config;
415
+ useIsomorphicLayoutEffect(() => {
416
+ const current = configRef.current;
417
+ if (path && current) {
418
+ registerField(path, current);
419
+ return () => unregisterField(path);
395
420
  }
396
- }, [path, config, registerField]);
421
+ return void 0;
422
+ }, [path, configKey, registerField, unregisterField]);
397
423
  const state = fieldStates[path] ?? {
398
424
  touched: false,
399
425
  validated: false,
@@ -587,9 +613,8 @@ function ActionProvider({
587
613
  handler,
588
614
  setState: set,
589
615
  navigate,
590
- executeAction: async (name) => {
591
- const subBinding = { action: name };
592
- await execute(subBinding);
616
+ executeAction: async (binding2) => {
617
+ await execute(binding2);
593
618
  }
594
619
  });
595
620
  } finally {
@@ -608,9 +633,8 @@ function ActionProvider({
608
633
  handler,
609
634
  setState: set,
610
635
  navigate,
611
- executeAction: async (name) => {
612
- const subBinding = { action: name };
613
- await execute(subBinding);
636
+ executeAction: async (binding2) => {
637
+ await execute(binding2);
614
638
  }
615
639
  });
616
640
  } finally {
@@ -813,8 +837,11 @@ var schema = (0, import_core5.defineSchema)(
813
837
  props: s.propsOf("catalog.components"),
814
838
  /** Child element keys (flat reference) */
815
839
  children: s.array(s.string()),
840
+ slots: { ...s.record(s.array(s.string())), ...s.optional() },
816
841
  /** Visibility condition */
817
- visible: s.any()
842
+ visible: { ...s.any(), ...s.optional() },
843
+ /** Repeat children from a state array */
844
+ repeat: { ...s.any(), ...s.optional() }
818
845
  })
819
846
  )
820
847
  }),
@@ -863,12 +890,15 @@ var schema = (0, import_core5.defineSchema)(
863
890
  // Element integrity
864
891
  "CRITICAL INTEGRITY CHECK: Before outputting ANY element that references children, you MUST have already output (or will output) each child as its own element. If an element has children: ['a', 'b'], then elements 'a' and 'b' MUST exist. A missing child element causes that entire branch of the UI to be invisible.",
865
892
  "SELF-CHECK: After generating all elements, mentally walk the tree from root. Every key in every children array must resolve to a defined element. If you find a gap, output the missing element immediately.",
893
+ 'REQUIRED FIELDS: Every element MUST include a "children" array. Leaf elements (text, badges, inputs, images) use an empty array: "children": []. Omitting "children" fails validation.',
894
+ 'NAMED SLOTS: Use "children" for the default slot. For other slots declared by the component, use a top-level "slots" object that maps each slot name to child element keys, for example {"slots":{"header":["heading"],"footer":["actions"]}}. Never use "slots.default". Every referenced key must exist.',
895
+ 'FILTERED LISTS: To render only the items matching a field value (kanban columns, tabbed lists, status sections), put "repeat" and a "visible" condition with $item on the same container element: {"repeat": {"statePath": "/tasks", "key": "id"}, "visible": {"$item": "status", "eq": "todo"}} renders one child per matching item. A visible condition object must use exactly one of $state, $item, or $index \u2014 never combine them in one object.',
866
896
  // Field placement
867
897
  'CRITICAL: The "visible" field goes on the ELEMENT object, NOT inside "props". Correct: {"type":"<ComponentName>","props":{},"visible":{"$state":"/tab","eq":"home"},"children":[...]}.',
868
898
  'CRITICAL: The "on" field goes on the ELEMENT object, NOT inside "props". Use on.press, on.change, on.submit etc. NEVER put action/actionParams inside props.',
869
899
  // State and data
870
900
  "When the user asks for a UI that displays data (e.g. blog posts, products, users), ALWAYS include a state field with realistic sample data. The state field is a top-level field on the spec (sibling of root/elements).",
871
- 'When building repeating content backed by a state array (e.g. posts, products, items), use the "repeat" field on a container element. Example: { "type": "<ContainerComponent>", "props": {}, "repeat": { "statePath": "/posts", "key": "id" }, "children": ["post-card"] }. Replace <ContainerComponent> with an appropriate component from the AVAILABLE COMPONENTS list. Inside repeated children, use { "$item": "field" } to read a field from the current item, and { "$index": true } for the current array index. For two-way binding to an item field use { "$bindItem": "completed" }. Do NOT hardcode individual elements for each array item.',
901
+ 'When building repeating content backed by a state array (e.g. posts, products, items), use the "repeat" field on a container element. Example: { "type": "<ContainerComponent>", "props": {}, "repeat": { "statePath": "/posts", "key": "id" }, "children": ["post-card"] }. For a nested list stored on the enclosing item, use "repeat": { "statePath": { "$item": "comments" }, "key": "id" }. The $item statePath form is valid only inside another repeat. Replace <ContainerComponent> with an appropriate component from the AVAILABLE COMPONENTS list. Inside repeated children, use { "$item": "field" } to read a field from the current item, and { "$index": true } for the current array index. For two-way binding to an item field use { "$bindItem": "completed" }. Do NOT hardcode individual elements for each array item.',
872
902
  // Design quality
873
903
  "Design with visual hierarchy: use container components to group content, heading components for section titles, proper spacing, and status indicators. ONLY use components from the AVAILABLE COMPONENTS list.",
874
904
  "For data-rich UIs, use multi-column layout components if available. For forms and single-column content, use vertical layout components. ONLY use components from the AVAILABLE COMPONENTS list.",
@@ -885,6 +915,18 @@ var import_core8 = require("@xmachines/json-render-core");
885
915
  var import_react6 = __toESM(require("react"));
886
916
  var import_core6 = require("@xmachines/json-render-core");
887
917
  var import_jsx_runtime6 = require("react/jsx-runtime");
918
+ var registryMetadata = /* @__PURE__ */ new WeakMap();
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
+ }
888
930
  function reportRenderError(registry, elementType, error, componentStack) {
889
931
  const onRenderError = registry?.onRenderError;
890
932
  if (typeof onRenderError === "function") {
@@ -964,7 +1006,9 @@ var ElementRenderer = import_react6.default.memo(function ElementRenderer2({
964
1006
  base.directives = directives;
965
1007
  return base;
966
1008
  }, [ctx, repeatScope, functions, directives]);
967
- const isVisible = element.visible === void 0 ? true : (0, import_core6.evaluateVisibility)(element.visible, fullCtx);
1009
+ const repeatVisibility = element.repeat !== void 0 && repeatScope == null ? (0, import_core6.splitRepeatVisibility)(element.visible) : { container: element.visible, itemFilter: void 0 };
1010
+ const repeatItemFilter = repeatVisibility.itemFilter;
1011
+ const isVisible = repeatVisibility.container === void 0 ? true : (0, import_core6.evaluateVisibility)(repeatVisibility.container, fullCtx);
968
1012
  const onBindings = element.on;
969
1013
  const emit = (0, import_react6.useCallback)(
970
1014
  async (eventName) => {
@@ -1077,21 +1121,28 @@ var ElementRenderer = import_react6.default.memo(function ElementRenderer2({
1077
1121
  console.warn(`No renderer for component type: ${resolvedElement.type}`);
1078
1122
  return null;
1079
1123
  }
1080
- const children = resolvedElement.repeat ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1081
- RepeatChildren,
1082
- {
1083
- element: resolvedElement,
1084
- spec,
1085
- registry,
1086
- loading,
1087
- fallback
1124
+ const metadata = registryMetadata.get(registry)?.[resolvedElement.type];
1125
+ if (resolvedElement.slots && metadata?.slots) {
1126
+ const availableSlots = new Set(metadata.slots);
1127
+ for (const slotName of Object.keys(resolvedElement.slots)) {
1128
+ if (slotName === "default") {
1129
+ console.warn(
1130
+ `[json-render] Component "${resolvedElement.type}" uses slots.default. Use "children" for default slot content.`
1131
+ );
1132
+ } else if (!availableSlots.has(slotName)) {
1133
+ console.warn(
1134
+ `[json-render] Unknown slot "${slotName}" on component "${resolvedElement.type}". Available slots: ${metadata.slots.join(", ")}`
1135
+ );
1136
+ }
1088
1137
  }
1089
- ) : resolvedElement.children?.map((childKey) => {
1138
+ }
1139
+ const renderChildKeys = (childKeys, slotName) => childKeys.map((childKey) => {
1090
1140
  const childElement = spec.elements[childKey];
1091
1141
  if (!childElement) {
1092
1142
  if (!loading) {
1143
+ const location = slotName ? `in slot "${slotName}" of "${resolvedElement.type}"` : `as child of "${resolvedElement.type}"`;
1093
1144
  console.warn(
1094
- `[json-render] Missing element "${childKey}" referenced as child of "${resolvedElement.type}". This element will not render.`
1145
+ `[json-render] Missing element "${childKey}" referenced ${location}. This element will not render.`
1095
1146
  );
1096
1147
  }
1097
1148
  return null;
@@ -1109,10 +1160,28 @@ var ElementRenderer = import_react6.default.memo(function ElementRenderer2({
1109
1160
  childKey
1110
1161
  );
1111
1162
  });
1163
+ const children = resolvedElement.repeat ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1164
+ RepeatChildren,
1165
+ {
1166
+ element: resolvedElement,
1167
+ spec,
1168
+ registry,
1169
+ loading,
1170
+ fallback,
1171
+ itemFilter: repeatItemFilter
1172
+ }
1173
+ ) : resolvedElement.children ? renderChildKeys(resolvedElement.children) : void 0;
1174
+ const slots = resolvedElement.slots ? Object.fromEntries(
1175
+ Object.entries(resolvedElement.slots).map(([slotName, childKeys]) => [
1176
+ slotName,
1177
+ renderChildKeys(childKeys, slotName)
1178
+ ])
1179
+ ) : void 0;
1112
1180
  const rendered = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1113
1181
  Component,
1114
1182
  {
1115
1183
  element: resolvedElement,
1184
+ slots,
1116
1185
  emit,
1117
1186
  on,
1118
1187
  bindings: elementBindings,
@@ -1135,13 +1204,32 @@ function RepeatChildren({
1135
1204
  spec,
1136
1205
  registry,
1137
1206
  loading,
1138
- fallback
1207
+ fallback,
1208
+ itemFilter
1139
1209
  }) {
1140
1210
  const { state } = useStateStore();
1211
+ const { ctx } = useVisibility();
1212
+ const parentScope = useRepeatScope();
1141
1213
  const repeat = element.repeat;
1142
- const statePath = repeat.statePath;
1214
+ const statePath = (0, import_core6.resolveRepeatStatePath)(
1215
+ repeat.statePath,
1216
+ parentScope?.basePath
1217
+ );
1218
+ if (statePath === void 0) {
1219
+ console.warn(
1220
+ "[json-render] $item in repeat.statePath used outside of a repeat scope"
1221
+ );
1222
+ return null;
1223
+ }
1143
1224
  const items = (0, import_core6.getByPath)(state, statePath) ?? [];
1144
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.Fragment, { children: items.map((itemValue, index) => {
1225
+ const entries = items.map((itemValue, index) => ({ itemValue, index })).filter(
1226
+ ({ itemValue, index }) => itemFilter === void 0 || (0, import_core6.evaluateVisibility)(itemFilter, {
1227
+ ...ctx,
1228
+ repeatItem: itemValue,
1229
+ repeatIndex: index
1230
+ })
1231
+ );
1232
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.Fragment, { children: entries.map(({ itemValue, index }) => {
1145
1233
  const key = repeat.key && typeof itemValue === "object" && itemValue !== null ? String(
1146
1234
  itemValue[repeat.key] ?? index
1147
1235
  ) : String(index);
@@ -1150,7 +1238,7 @@ function RepeatChildren({
1150
1238
  {
1151
1239
  item: itemValue,
1152
1240
  index,
1153
- basePath: `${statePath}/${index}`,
1241
+ basePath: (0, import_core6.resolveRepeatItemStatePath)(statePath, index),
1154
1242
  children: element.children?.map((childKey) => {
1155
1243
  const childElement = spec.elements[childKey];
1156
1244
  if (!childElement) {
@@ -1186,16 +1274,10 @@ function Renderer({
1186
1274
  fallback,
1187
1275
  onRenderError
1188
1276
  }) {
1189
- const rendererRegistry = (0, import_react6.useMemo)(() => {
1190
- if (!onRenderError) return registry;
1191
- const next = { ...registry };
1192
- Object.defineProperty(next, "onRenderError", {
1193
- value: onRenderError,
1194
- enumerable: false,
1195
- configurable: true
1196
- });
1197
- return next;
1198
- }, [registry, onRenderError]);
1277
+ const rendererRegistry = (0, import_react6.useMemo)(
1278
+ () => onRenderError ? withRenderErrorHandler(registry, onRenderError) : registry,
1279
+ [registry, onRenderError]
1280
+ );
1199
1281
  if (!spec || !spec.root) {
1200
1282
  return null;
1201
1283
  }
@@ -1258,13 +1340,14 @@ function ConfirmationDialogManager() {
1258
1340
  }
1259
1341
  );
1260
1342
  }
1261
- function defineRegistry(_catalog, options) {
1343
+ function defineRegistry(catalog, options) {
1262
1344
  const registry = {};
1263
1345
  if (options.components) {
1264
1346
  for (const [name, componentFn] of Object.entries(options.components)) {
1265
1347
  registry[name] = ({
1266
1348
  element,
1267
1349
  children,
1350
+ slots,
1268
1351
  emit,
1269
1352
  on,
1270
1353
  bindings,
@@ -1273,6 +1356,7 @@ function defineRegistry(_catalog, options) {
1273
1356
  return componentFn({
1274
1357
  props: element.props,
1275
1358
  children,
1359
+ slots,
1276
1360
  emit,
1277
1361
  on,
1278
1362
  bindings,
@@ -1281,6 +1365,10 @@ function defineRegistry(_catalog, options) {
1281
1365
  };
1282
1366
  }
1283
1367
  }
1368
+ const catalogComponents = catalog.data.components;
1369
+ if (catalogComponents) {
1370
+ registryMetadata.set(registry, catalogComponents);
1371
+ }
1284
1372
  const actionMap = options.actions ? Object.entries(options.actions) : [];
1285
1373
  const handlers = (getSetState, getState) => {
1286
1374
  const result = {};
@@ -1314,6 +1402,10 @@ function defineRegistry(_catalog, options) {
1314
1402
  }
1315
1403
  function createRenderer(catalog, components) {
1316
1404
  const registry = components;
1405
+ const catalogComponents = catalog.data.components;
1406
+ if (catalogComponents) {
1407
+ registryMetadata.set(registry, catalogComponents);
1408
+ }
1317
1409
  return function CatalogRenderer({
1318
1410
  spec,
1319
1411
  store,
@@ -1330,16 +1422,10 @@ function createRenderer(catalog, components) {
1330
1422
  () => directives ? (0, import_core6.createDirectiveRegistry)(directives) : void 0,
1331
1423
  [directives]
1332
1424
  );
1333
- const rendererRegistry = (0, import_react6.useMemo)(() => {
1334
- if (!onRenderError) return registry;
1335
- const next = { ...registry };
1336
- Object.defineProperty(next, "onRenderError", {
1337
- value: onRenderError,
1338
- enumerable: false,
1339
- configurable: true
1340
- });
1341
- return next;
1342
- }, [onRenderError]);
1425
+ const rendererRegistry = (0, import_react6.useMemo)(
1426
+ () => onRenderError ? withRenderErrorHandler(registry, onRenderError) : registry,
1427
+ [onRenderError]
1428
+ );
1343
1429
  const actionHandlers = onAction ? new Proxy(
1344
1430
  {},
1345
1431
  {