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

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 });
@@ -387,13 +405,20 @@ function useFieldValidation(path, config) {
387
405
  validate: validateField,
388
406
  touch: touchField,
389
407
  clear: clearField,
390
- registerField
408
+ registerField,
409
+ unregisterField
391
410
  } = useValidation();
411
+ const configKey = config === void 0 ? void 0 : JSON.stringify(config);
412
+ const configRef = import_react3.default.useRef(config);
413
+ configRef.current = config;
392
414
  import_react3.default.useEffect(() => {
393
- if (path && config) {
394
- registerField(path, config);
415
+ const current = configRef.current;
416
+ if (path && current) {
417
+ registerField(path, current);
418
+ return () => unregisterField(path);
395
419
  }
396
- }, [path, config, registerField]);
420
+ return void 0;
421
+ }, [path, configKey, registerField, unregisterField]);
397
422
  const state = fieldStates[path] ?? {
398
423
  touched: false,
399
424
  validated: false,
@@ -587,9 +612,8 @@ function ActionProvider({
587
612
  handler,
588
613
  setState: set,
589
614
  navigate,
590
- executeAction: async (name) => {
591
- const subBinding = { action: name };
592
- await execute(subBinding);
615
+ executeAction: async (binding2) => {
616
+ await execute(binding2);
593
617
  }
594
618
  });
595
619
  } finally {
@@ -608,9 +632,8 @@ function ActionProvider({
608
632
  handler,
609
633
  setState: set,
610
634
  navigate,
611
- executeAction: async (name) => {
612
- const subBinding = { action: name };
613
- await execute(subBinding);
635
+ executeAction: async (binding2) => {
636
+ await execute(binding2);
614
637
  }
615
638
  });
616
639
  } finally {
@@ -813,8 +836,11 @@ var schema = (0, import_core5.defineSchema)(
813
836
  props: s.propsOf("catalog.components"),
814
837
  /** Child element keys (flat reference) */
815
838
  children: s.array(s.string()),
839
+ slots: { ...s.record(s.array(s.string())), ...s.optional() },
816
840
  /** Visibility condition */
817
- visible: s.any()
841
+ visible: { ...s.any(), ...s.optional() },
842
+ /** Repeat children from a state array */
843
+ repeat: { ...s.any(), ...s.optional() }
818
844
  })
819
845
  )
820
846
  }),
@@ -863,12 +889,15 @@ var schema = (0, import_core5.defineSchema)(
863
889
  // Element integrity
864
890
  "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
891
  "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.",
892
+ 'REQUIRED FIELDS: Every element MUST include a "children" array. Leaf elements (text, badges, inputs, images) use an empty array: "children": []. Omitting "children" fails validation.',
893
+ '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.',
894
+ '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
895
  // Field placement
867
896
  'CRITICAL: The "visible" field goes on the ELEMENT object, NOT inside "props". Correct: {"type":"<ComponentName>","props":{},"visible":{"$state":"/tab","eq":"home"},"children":[...]}.',
868
897
  '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
898
  // State and data
870
899
  "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.',
900
+ '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
901
  // Design quality
873
902
  "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
903
  "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 +914,18 @@ var import_core8 = require("@xmachines/json-render-core");
885
914
  var import_react6 = __toESM(require("react"));
886
915
  var import_core6 = require("@xmachines/json-render-core");
887
916
  var import_jsx_runtime6 = require("react/jsx-runtime");
917
+ var registryMetadata = /* @__PURE__ */ new WeakMap();
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
+ const metadata = registryMetadata.get(registry);
926
+ if (metadata) registryMetadata.set(next, metadata);
927
+ return next;
928
+ }
888
929
  function reportRenderError(registry, elementType, error, componentStack) {
889
930
  const onRenderError = registry?.onRenderError;
890
931
  if (typeof onRenderError === "function") {
@@ -964,7 +1005,9 @@ var ElementRenderer = import_react6.default.memo(function ElementRenderer2({
964
1005
  base.directives = directives;
965
1006
  return base;
966
1007
  }, [ctx, repeatScope, functions, directives]);
967
- const isVisible = element.visible === void 0 ? true : (0, import_core6.evaluateVisibility)(element.visible, fullCtx);
1008
+ const repeatVisibility = element.repeat !== void 0 && repeatScope == null ? (0, import_core6.splitRepeatVisibility)(element.visible) : { container: element.visible, itemFilter: void 0 };
1009
+ const repeatItemFilter = repeatVisibility.itemFilter;
1010
+ const isVisible = repeatVisibility.container === void 0 ? true : (0, import_core6.evaluateVisibility)(repeatVisibility.container, fullCtx);
968
1011
  const onBindings = element.on;
969
1012
  const emit = (0, import_react6.useCallback)(
970
1013
  async (eventName) => {
@@ -1077,21 +1120,28 @@ var ElementRenderer = import_react6.default.memo(function ElementRenderer2({
1077
1120
  console.warn(`No renderer for component type: ${resolvedElement.type}`);
1078
1121
  return null;
1079
1122
  }
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
1123
+ const metadata = registryMetadata.get(registry)?.[resolvedElement.type];
1124
+ if (resolvedElement.slots && metadata?.slots) {
1125
+ const availableSlots = new Set(metadata.slots);
1126
+ for (const slotName of Object.keys(resolvedElement.slots)) {
1127
+ if (slotName === "default") {
1128
+ console.warn(
1129
+ `[json-render] Component "${resolvedElement.type}" uses slots.default. Use "children" for default slot content.`
1130
+ );
1131
+ } else if (!availableSlots.has(slotName)) {
1132
+ console.warn(
1133
+ `[json-render] Unknown slot "${slotName}" on component "${resolvedElement.type}". Available slots: ${metadata.slots.join(", ")}`
1134
+ );
1135
+ }
1088
1136
  }
1089
- ) : resolvedElement.children?.map((childKey) => {
1137
+ }
1138
+ const renderChildKeys = (childKeys, slotName) => childKeys.map((childKey) => {
1090
1139
  const childElement = spec.elements[childKey];
1091
1140
  if (!childElement) {
1092
1141
  if (!loading) {
1142
+ const location = slotName ? `in slot "${slotName}" of "${resolvedElement.type}"` : `as child of "${resolvedElement.type}"`;
1093
1143
  console.warn(
1094
- `[json-render] Missing element "${childKey}" referenced as child of "${resolvedElement.type}". This element will not render.`
1144
+ `[json-render] Missing element "${childKey}" referenced ${location}. This element will not render.`
1095
1145
  );
1096
1146
  }
1097
1147
  return null;
@@ -1109,10 +1159,28 @@ var ElementRenderer = import_react6.default.memo(function ElementRenderer2({
1109
1159
  childKey
1110
1160
  );
1111
1161
  });
1162
+ const children = resolvedElement.repeat ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1163
+ RepeatChildren,
1164
+ {
1165
+ element: resolvedElement,
1166
+ spec,
1167
+ registry,
1168
+ loading,
1169
+ fallback,
1170
+ itemFilter: repeatItemFilter
1171
+ }
1172
+ ) : resolvedElement.children ? renderChildKeys(resolvedElement.children) : void 0;
1173
+ const slots = resolvedElement.slots ? Object.fromEntries(
1174
+ Object.entries(resolvedElement.slots).map(([slotName, childKeys]) => [
1175
+ slotName,
1176
+ renderChildKeys(childKeys, slotName)
1177
+ ])
1178
+ ) : void 0;
1112
1179
  const rendered = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1113
1180
  Component,
1114
1181
  {
1115
1182
  element: resolvedElement,
1183
+ slots,
1116
1184
  emit,
1117
1185
  on,
1118
1186
  bindings: elementBindings,
@@ -1135,13 +1203,32 @@ function RepeatChildren({
1135
1203
  spec,
1136
1204
  registry,
1137
1205
  loading,
1138
- fallback
1206
+ fallback,
1207
+ itemFilter
1139
1208
  }) {
1140
1209
  const { state } = useStateStore();
1210
+ const { ctx } = useVisibility();
1211
+ const parentScope = useRepeatScope();
1141
1212
  const repeat = element.repeat;
1142
- const statePath = repeat.statePath;
1213
+ const statePath = (0, import_core6.resolveRepeatStatePath)(
1214
+ repeat.statePath,
1215
+ parentScope?.basePath
1216
+ );
1217
+ if (statePath === void 0) {
1218
+ console.warn(
1219
+ "[json-render] $item in repeat.statePath used outside of a repeat scope"
1220
+ );
1221
+ return null;
1222
+ }
1143
1223
  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) => {
1224
+ const entries = items.map((itemValue, index) => ({ itemValue, index })).filter(
1225
+ ({ itemValue, index }) => itemFilter === void 0 || (0, import_core6.evaluateVisibility)(itemFilter, {
1226
+ ...ctx,
1227
+ repeatItem: itemValue,
1228
+ repeatIndex: index
1229
+ })
1230
+ );
1231
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.Fragment, { children: entries.map(({ itemValue, index }) => {
1145
1232
  const key = repeat.key && typeof itemValue === "object" && itemValue !== null ? String(
1146
1233
  itemValue[repeat.key] ?? index
1147
1234
  ) : String(index);
@@ -1150,7 +1237,7 @@ function RepeatChildren({
1150
1237
  {
1151
1238
  item: itemValue,
1152
1239
  index,
1153
- basePath: `${statePath}/${index}`,
1240
+ basePath: (0, import_core6.resolveRepeatItemStatePath)(statePath, index),
1154
1241
  children: element.children?.map((childKey) => {
1155
1242
  const childElement = spec.elements[childKey];
1156
1243
  if (!childElement) {
@@ -1186,16 +1273,10 @@ function Renderer({
1186
1273
  fallback,
1187
1274
  onRenderError
1188
1275
  }) {
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]);
1276
+ const rendererRegistry = (0, import_react6.useMemo)(
1277
+ () => onRenderError ? withRenderErrorHandler(registry, onRenderError) : registry,
1278
+ [registry, onRenderError]
1279
+ );
1199
1280
  if (!spec || !spec.root) {
1200
1281
  return null;
1201
1282
  }
@@ -1258,13 +1339,14 @@ function ConfirmationDialogManager() {
1258
1339
  }
1259
1340
  );
1260
1341
  }
1261
- function defineRegistry(_catalog, options) {
1342
+ function defineRegistry(catalog, options) {
1262
1343
  const registry = {};
1263
1344
  if (options.components) {
1264
1345
  for (const [name, componentFn] of Object.entries(options.components)) {
1265
1346
  registry[name] = ({
1266
1347
  element,
1267
1348
  children,
1349
+ slots,
1268
1350
  emit,
1269
1351
  on,
1270
1352
  bindings,
@@ -1273,6 +1355,7 @@ function defineRegistry(_catalog, options) {
1273
1355
  return componentFn({
1274
1356
  props: element.props,
1275
1357
  children,
1358
+ slots,
1276
1359
  emit,
1277
1360
  on,
1278
1361
  bindings,
@@ -1281,6 +1364,10 @@ function defineRegistry(_catalog, options) {
1281
1364
  };
1282
1365
  }
1283
1366
  }
1367
+ const catalogComponents = catalog.data.components;
1368
+ if (catalogComponents) {
1369
+ registryMetadata.set(registry, catalogComponents);
1370
+ }
1284
1371
  const actionMap = options.actions ? Object.entries(options.actions) : [];
1285
1372
  const handlers = (getSetState, getState) => {
1286
1373
  const result = {};
@@ -1314,6 +1401,10 @@ function defineRegistry(_catalog, options) {
1314
1401
  }
1315
1402
  function createRenderer(catalog, components) {
1316
1403
  const registry = components;
1404
+ const catalogComponents = catalog.data.components;
1405
+ if (catalogComponents) {
1406
+ registryMetadata.set(registry, catalogComponents);
1407
+ }
1317
1408
  return function CatalogRenderer({
1318
1409
  spec,
1319
1410
  store,
@@ -1330,16 +1421,10 @@ function createRenderer(catalog, components) {
1330
1421
  () => directives ? (0, import_core6.createDirectiveRegistry)(directives) : void 0,
1331
1422
  [directives]
1332
1423
  );
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]);
1424
+ const rendererRegistry = (0, import_react6.useMemo)(
1425
+ () => onRenderError ? withRenderErrorHandler(registry, onRenderError) : registry,
1426
+ [onRenderError]
1427
+ );
1343
1428
  const actionHandlers = onAction ? new Proxy(
1344
1429
  {},
1345
1430
  {