@lacecms/content 0.1.0-alpha.7 → 0.1.0-rc1

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
@@ -1,4 +1,9 @@
1
+ import { parseVideoEmbed } from "./video-embeds.js";
1
2
  import * as v from "valibot";
3
+ import { decodeEntryLink, MAX_INTERNAL_LINK_REFERENCES } from "./internal-links.js";
4
+ export * from "./internal-links.js";
5
+ export * from "./video-embeds.js";
6
+ export * from "./list-query-policy.js";
2
7
  /** Validates, detaches and freezes optional sibling layout metadata. */
3
8
  export function normalizeFormLayout(value, fields, path = "layout") {
4
9
  if (value === undefined)
@@ -39,6 +44,50 @@ export function formFieldKeys(fields, layout) {
39
44
  const placed = layout?.groups.flatMap((group) => group.fields) ?? [];
40
45
  return [...placed, ...Object.keys(fields).filter((key) => !placed.includes(key))];
41
46
  }
47
+ /** Validates, detaches and freezes the conditional-field rules of one owner. */
48
+ export function normalizeFieldVisibility(value, fields, path = "visibility") {
49
+ if (value === undefined)
50
+ return undefined;
51
+ const raw = normalizeJsonValue(value, path, new WeakSet());
52
+ if (!isRecord(raw))
53
+ fail(path, "must be a plain object of field rules.");
54
+ for (const [target, rule] of Object.entries(raw)) {
55
+ const at = `${path}.${target}`;
56
+ if (!Object.hasOwn(fields, target))
57
+ fail(at, "must target a declared sibling field.");
58
+ if (!isRecord(rule) ||
59
+ Object.keys(rule).some((key) => !["field", "values"].includes(key)) ||
60
+ typeof rule.field !== "string")
61
+ fail(at, "must contain only field and values.");
62
+ if (rule.field === target)
63
+ fail(`${at}.field`, "must name another sibling field.");
64
+ if (Object.hasOwn(raw, rule.field))
65
+ fail(`${at}.field`, "must name an unconditional controller; chains and cycles are not allowed.");
66
+ const controller = Object.hasOwn(fields, rule.field) ? fields[rule.field] : undefined;
67
+ if (controller?.type !== "select" && controller?.type !== "boolean")
68
+ fail(`${at}.field`, "must name a sibling select or boolean field.");
69
+ const allowed = controller.type === "select" ? controller.options : [true, false];
70
+ if (!Array.isArray(rule.values) ||
71
+ rule.values.length === 0 ||
72
+ new Set(rule.values).size !== rule.values.length ||
73
+ rule.values.some((entry) => !allowed.includes(entry)))
74
+ fail(`${at}.values`, "must be a nonempty unique subset of the controller's values.");
75
+ }
76
+ return deepFreeze(raw);
77
+ }
78
+ /**
79
+ * Whether `target` applies in one normalized object occurrence: a target
80
+ * without a rule is visible; otherwise its controller's value (present or
81
+ * materialized default) must be listed. An absent controller matches nothing.
82
+ */
83
+ export function isFieldVisible(visibility, target, values) {
84
+ const rule = visibility !== undefined && Object.hasOwn(visibility, target) ? visibility[target] : undefined;
85
+ if (rule === undefined)
86
+ return true;
87
+ if (!Object.hasOwn(values, rule.field))
88
+ return false;
89
+ return rule.values.includes(values[rule.field]);
90
+ }
42
91
  /** Maximum containers along a descriptor branch. */
43
92
  export const MAX_FIELD_CONTAINER_DEPTH = 6;
44
93
  /** Maximum directly nested groups. */
@@ -266,11 +315,31 @@ function buildStringValueField(type, input) {
266
315
  "description",
267
316
  "label",
268
317
  "required",
269
- ...(type === "url" ? ["placeholder"] : []),
318
+ ...(type === "url" ? ["placeholder", "embedProviders"] : []),
270
319
  ]);
271
320
  const definition = { type };
272
321
  addCommonOptions(definition, options);
273
- addDefault(definition, options, (value) => typeof value === "string", "must be a string.");
322
+ if (type === "url" && options.embedProviders !== undefined) {
323
+ const providers = options.embedProviders;
324
+ if (!Array.isArray(providers) ||
325
+ providers.length === 0 ||
326
+ providers.some((provider) => provider !== "youtube" && provider !== "vimeo") ||
327
+ new Set(providers).size !== providers.length)
328
+ fail("options.embedProviders", "must be a non-empty unique list of youtube and vimeo.");
329
+ definition.embedProviders = ["youtube", "vimeo"].filter((provider) => providers.includes(provider));
330
+ }
331
+ addDefault(definition, options, (value) => {
332
+ if (typeof value !== "string")
333
+ return false;
334
+ if (definition.embedProviders === undefined)
335
+ return true;
336
+ const embed = parseVideoEmbed(value);
337
+ return (isSafeUrl(value) &&
338
+ embed !== undefined &&
339
+ definition.embedProviders.includes(embed.provider));
340
+ }, definition.embedProviders === undefined
341
+ ? "must be a string."
342
+ : "must be a string matching the declared embed providers.");
274
343
  return deepFreeze(definition);
275
344
  }
276
345
  /** Builders for portable Lace field descriptors. */
@@ -362,6 +431,7 @@ export const field = {
362
431
  "description",
363
432
  "label",
364
433
  "options",
434
+ "presentation",
365
435
  "placeholder",
366
436
  "required",
367
437
  ]);
@@ -383,10 +453,12 @@ export const field = {
383
453
  }
384
454
  const definition = { options: choices, type: "select" };
385
455
  addCommonOptions(definition, normalized);
456
+ if (normalized.presentation !== undefined)
457
+ definition.presentation = normalizeSelectPresentation(normalized.presentation, choices);
386
458
  addDefault(definition, normalized, (value) => typeof value === "string" && seen.has(value), "must be one of the declared select choices.");
387
459
  return deepFreeze(definition);
388
460
  },
389
- /** Define a URL string field; URL protocol validation is added in Session 2B. */
461
+ /** Define a safe URL field, optionally restricted to supported video providers. */
390
462
  url(options) {
391
463
  return buildStringValueField("url", options);
392
464
  },
@@ -395,6 +467,76 @@ export const field = {
395
467
  return buildStringValueField("media", options);
396
468
  },
397
469
  };
470
+ function normalizeSelectPresentation(value, options) {
471
+ const path = "options.presentation";
472
+ const exact = (raw, keys, at) => {
473
+ const record = descriptorRecord(raw, at);
474
+ for (const key of Object.keys(record))
475
+ if (!keys.includes(key))
476
+ fail(`${at}.${key}`, "is not supported.");
477
+ return record;
478
+ };
479
+ const text = (raw, at) => {
480
+ if (typeof raw !== "string" ||
481
+ !raw.trim() ||
482
+ /[<>]/u.test(raw) ||
483
+ [...raw].some((character) => character.charCodeAt(0) < 32))
484
+ fail(at, "must be nonempty plain text.");
485
+ return raw;
486
+ };
487
+ const raw = exact(value, ["control", "choices"], path);
488
+ if (raw.control !== "cards")
489
+ fail(`${path}.control`, 'must be "cards".');
490
+ if (!Array.isArray(raw.choices) || raw.choices.length !== options.length)
491
+ fail(`${path}.choices`, "must cover every select option exactly once.");
492
+ const seen = new Set();
493
+ const choices = raw.choices.map((choice, index) => {
494
+ const at = `${path}.choices[${index}]`;
495
+ const entry = exact(choice, ["value", "label", "description", "diagram"], at);
496
+ if (typeof entry.value !== "string" || !options.includes(entry.value) || seen.has(entry.value))
497
+ fail(`${at}.value`, "must name a unique declared select option.");
498
+ seen.add(entry.value);
499
+ const result = {
500
+ value: entry.value,
501
+ label: text(entry.label, `${at}.label`),
502
+ ...(entry.description !== undefined
503
+ ? { description: text(entry.description, `${at}.description`) }
504
+ : {}),
505
+ ...(entry.diagram !== undefined ? { diagram: diagram(entry.diagram, `${at}.diagram`) } : {}),
506
+ };
507
+ return result;
508
+ });
509
+ return deepFreeze({ control: "cards", choices });
510
+ function diagram(input, at) {
511
+ const rawDiagram = exact(input, ["cells"], at);
512
+ if (!Array.isArray(rawDiagram.cells) ||
513
+ rawDiagram.cells.length < 1 ||
514
+ rawDiagram.cells.length > 16)
515
+ fail(`${at}.cells`, "must contain 1–16 rectangles.");
516
+ const cells = [];
517
+ for (const [index, inputCell] of rawDiagram.cells.entries()) {
518
+ const cellPath = `${at}.cells[${index}]`;
519
+ const rawCell = exact(inputCell, ["x", "y", "width", "height"], cellPath);
520
+ for (const key of ["x", "y", "width", "height"]) {
521
+ const n = rawCell[key];
522
+ if (typeof n !== "number" ||
523
+ !Number.isInteger(n) ||
524
+ n < (key === "x" || key === "y" ? 0 : 1))
525
+ fail(`${cellPath}.${key}`, "must be an integer within the 12 by 12 canvas.");
526
+ }
527
+ const cell = rawCell;
528
+ if (cell.x + cell.width > 12 || cell.y + cell.height > 12)
529
+ fail(cellPath, "must fit within the 12 by 12 canvas.");
530
+ if (cells.some((other) => cell.x < other.x + other.width &&
531
+ cell.x + cell.width > other.x &&
532
+ cell.y < other.y + other.height &&
533
+ cell.y + cell.height > other.y))
534
+ fail(cellPath, "must not overlap another rectangle.");
535
+ cells.push({ ...cell });
536
+ }
537
+ return { cells };
538
+ }
539
+ }
398
540
  /**
399
541
  * Project a field descriptor into a detached, immutable JSON-safe admin form
400
542
  * representation. Runtime schemas and callbacks are deliberately absent.
@@ -475,7 +617,9 @@ function normalizeDescriptor(value, path, depth, groups, ancestors) {
475
617
  "required",
476
618
  "defaultValue",
477
619
  "renamedFrom",
478
- ...(type === "group" ? ["fields", "layout"] : ["item", "minItems", "maxItems", "itemLabel"]),
620
+ ...(type === "group"
621
+ ? ["fields", "layout", "visibility"]
622
+ : ["item", "minItems", "maxItems", "itemLabel"]),
479
623
  ];
480
624
  for (const key of Object.keys(options))
481
625
  if (!allowed.includes(key))
@@ -501,6 +645,9 @@ function normalizeDescriptor(value, path, depth, groups, ancestors) {
501
645
  const layout = normalizeFormLayout(options.layout, output, `${path}.layout`);
502
646
  if (layout !== undefined)
503
647
  result.layout = layout;
648
+ const visibility = normalizeFieldVisibility(options.visibility, output, `${path}.visibility`);
649
+ if (visibility !== undefined)
650
+ result.visibility = visibility;
504
651
  }
505
652
  else {
506
653
  const child = descriptorRecord(item, `${path}.item`);
@@ -585,7 +732,7 @@ function assertExactKeys(value, required, optional, path) {
585
732
  }
586
733
  }
587
734
  }
588
- /** Returns whether a URL is permitted in Lace URL fields and rich-text links. */
735
+ /** Returns whether a URL is permitted as an href, including rich-text links. */
589
736
  export function isSafeUrl(value) {
590
737
  if (typeof value !== "string" ||
591
738
  value.length === 0 ||
@@ -601,6 +748,10 @@ export function isSafeUrl(value) {
601
748
  }
602
749
  return /^(?:https?:\/\/[^/?#\s]+(?:[/?#][^\s]*)?|mailto:[^\s@]+@[^\s@]+|tel:\+?[0-9(). -]+)$/u.test(value);
603
750
  }
751
+ /** Ordinary URL fields support safe manual URLs and canonical entry tokens. */
752
+ export function isUrlFieldTarget(value) {
753
+ return isSafeUrl(value) || decodeEntryLink(value) !== undefined;
754
+ }
604
755
  function assertMarks(value, path) {
605
756
  if (!Array.isArray(value)) {
606
757
  invalid(path, "invalid_marks", "must be an array.");
@@ -811,7 +962,14 @@ function isFieldValue(definition, value) {
811
962
  textarea: (fieldDefinition) => typeof value === "string" &&
812
963
  (fieldDefinition.minLength === undefined || textLength(value) >= fieldDefinition.minLength) &&
813
964
  (fieldDefinition.maxLength === undefined || textLength(value) <= fieldDefinition.maxLength),
814
- url: () => isSafeUrl(value),
965
+ url: (descriptor) => {
966
+ if (descriptor.embedProviders === undefined)
967
+ return isUrlFieldTarget(value);
968
+ if (!isSafeUrl(value))
969
+ return false;
970
+ const embed = parseVideoEmbed(value);
971
+ return embed !== undefined && descriptor.embedProviders.includes(embed.provider);
972
+ },
815
973
  });
816
974
  }
817
975
  /** Compiles a field definition with the same normalization as aggregate validation. */
@@ -841,7 +999,7 @@ function normalizeFieldValue(definition, value, mode, path, budget) {
841
999
  if (definition.type === "group") {
842
1000
  if (!isRecord(value))
843
1001
  invalid(path, "invalid_field_value", "must be a group object.");
844
- return normalizeFieldMap(definition.fields, value, mode, path, budget);
1002
+ return normalizeFieldMap(definition.fields, value, mode, path, budget, definition.visibility);
845
1003
  }
846
1004
  if (definition.type === "list") {
847
1005
  if (!Array.isArray(value))
@@ -861,34 +1019,84 @@ function normalizeFieldValue(definition, value, mode, path, budget) {
861
1019
  invalid(path, "invalid_field_value", "does not conform to its field definition.");
862
1020
  return value;
863
1021
  }
864
- function normalizeFieldMap(definitions, value, mode, path, budget) {
1022
+ function normalizeFieldMap(definitions, value, mode, path, budget, visibility) {
865
1023
  if (!isRecord(value))
866
1024
  invalid(path, "invalid_fields", "must be an object.");
867
1025
  for (const key of Object.keys(value))
868
1026
  if (!Object.hasOwn(definitions, key))
869
1027
  invalid([...path, key], "unknown_field", "is not defined by this model.");
870
- const output = {};
871
- for (const [key, definition] of Object.entries(definitions)) {
1028
+ const normalized = new Map();
1029
+ const normalize = (key, definition, fieldMode) => {
872
1030
  let present;
873
1031
  if (Object.hasOwn(value, key))
874
1032
  present = value[key];
875
1033
  else if (Object.hasOwn(definition, "defaultValue"))
876
1034
  present = definition.defaultValue;
877
1035
  else {
878
- if (mode === "publish" && definition.required)
1036
+ if (fieldMode === "publish" && definition.required)
879
1037
  invalid([...path, key], "missing_required_field", "is required for publication.");
880
- continue;
1038
+ return;
881
1039
  }
1040
+ normalized.set(key, normalizeFieldValue(definition, present, fieldMode, [...path, key], budget));
1041
+ };
1042
+ const conditional = (key) => visibility !== undefined && Object.hasOwn(visibility, key);
1043
+ // Controllers are unconditional, so their normalized values decide every target.
1044
+ for (const [key, definition] of Object.entries(definitions))
1045
+ if (!conditional(key))
1046
+ normalize(key, definition, mode);
1047
+ const controllers = Object.fromEntries(normalized);
1048
+ for (const [key, definition] of Object.entries(definitions))
1049
+ if (conditional(key))
1050
+ normalize(key, definition, isFieldVisible(visibility, key, controllers) ? mode : "draft");
1051
+ const output = {};
1052
+ for (const key of Object.keys(definitions))
1053
+ if (normalized.has(key))
1054
+ Object.defineProperty(output, key, { value: normalized.get(key), enumerable: true });
1055
+ return output;
1056
+ }
1057
+ /** Validates field data for either an incomplete draft or a publish candidate. */
1058
+ export function validateModelFields(definitions, value, mode, path = [], visibility) {
1059
+ return normalizeFieldMap(definitions, value, mode, path, { count: 0 }, visibility);
1060
+ }
1061
+ /**
1062
+ * Removes every hidden target from already normalized values, recursively
1063
+ * through visible groups and list items, without inserting or reordering.
1064
+ */
1065
+ export function publishedFieldValues(definitions, values, visibility) {
1066
+ const project = (definition, value) => {
1067
+ if (definition.type === "group" && isRecord(value))
1068
+ return publishedFieldValues(definition.fields, value, definition.visibility);
1069
+ if (definition.type === "list" && Array.isArray(value))
1070
+ return value.map((item) => project(definition.item, item));
1071
+ return value;
1072
+ };
1073
+ const output = {};
1074
+ for (const [key, value] of Object.entries(values)) {
1075
+ if (!isFieldVisible(visibility, key, values))
1076
+ continue;
1077
+ const definition = Object.hasOwn(definitions, key) ? definitions[key] : undefined;
882
1078
  Object.defineProperty(output, key, {
883
- value: normalizeFieldValue(definition, present, mode, [...path, key], budget),
1079
+ value: definition === undefined ? value : project(definition, value),
884
1080
  enumerable: true,
885
1081
  });
886
1082
  }
887
1083
  return output;
888
1084
  }
889
- /** Validates field data for either an incomplete draft or a publish candidate. */
890
- export function validateModelFields(definitions, value, mode, path = []) {
891
- return normalizeFieldMap(definitions, value, mode, path, { count: 0 });
1085
+ /**
1086
+ * Whether an owner or any nested group, including list-item groups, declares
1087
+ * conditional-field rules, so its published projection can differ from its values.
1088
+ */
1089
+ export function declaresFieldVisibility(definitions, visibility) {
1090
+ if (visibility !== undefined && Object.keys(visibility).length > 0)
1091
+ return true;
1092
+ const visit = (definition) => definition.type === "group"
1093
+ ? declaresFieldVisibility(definition.fields, definition.visibility)
1094
+ : definition.type === "list" && visit(definition.item);
1095
+ return Object.values(definitions).some(visit);
1096
+ }
1097
+ /** The published projection of one block's normalized data. */
1098
+ export function publishedBlockData(definition, data) {
1099
+ return publishedFieldValues(definition.fields, data, definition.visibility);
892
1100
  }
893
1101
  /** Checks already normalized model/block values against one snapshot-wide budget. */
894
1102
  export function validateSnapshotListBudget(fields, values, blocks) {
@@ -908,6 +1116,55 @@ export function validateSnapshotListBudget(fields, values, blocks) {
908
1116
  walk(fields, values, ["fields"]);
909
1117
  blocks.forEach((block) => walk(block.fields, block.data, block.path));
910
1118
  }
1119
+ /** Discover references only in normalized ordinary URL descriptors. */
1120
+ export function collectFieldInternalLinks(definitions, values) {
1121
+ const references = [];
1122
+ function visit(definition, value, path) {
1123
+ if (definition.type === "url" && definition.embedProviders === undefined) {
1124
+ const targetId = decodeEntryLink(value);
1125
+ if (targetId !== undefined)
1126
+ references.push({ targetId, path });
1127
+ }
1128
+ else if (definition.type === "group" && isRecord(value)) {
1129
+ walk(definition.fields, value, path);
1130
+ }
1131
+ else if (definition.type === "list" && Array.isArray(value)) {
1132
+ value.forEach((item, index) => visit(definition.item, item, [...path, index]));
1133
+ }
1134
+ }
1135
+ function walk(fields, data, path) {
1136
+ for (const [key, definition] of Object.entries(fields))
1137
+ visit(definition, data[key], [...path, key]);
1138
+ }
1139
+ walk(definitions, values, []);
1140
+ return deepFreeze(references);
1141
+ }
1142
+ /** Collect and bound every declared internal URL in one normalized snapshot. */
1143
+ export function collectSnapshotInternalLinks(fields, values, blocks, visibility) {
1144
+ const references = [];
1145
+ const pointerOf = (path) => `/${path.map((part) => String(part).replaceAll("~", "~0").replaceAll("/", "~1")).join("/")}`;
1146
+ function add(definitions, data, sourceKey, area, delivered, rootPath, rules) {
1147
+ // The projection keeps paths, so a link is visible exactly when it survives it.
1148
+ const visible = declaresFieldVisibility(definitions, rules)
1149
+ ? new Set(collectFieldInternalLinks(definitions, publishedFieldValues(definitions, data, rules)).map((reference) => pointerOf(reference.path)))
1150
+ : undefined;
1151
+ for (const reference of collectFieldInternalLinks(definitions, data)) {
1152
+ if (references.length === MAX_INTERNAL_LINK_REFERENCES)
1153
+ invalid([...rootPath, ...reference.path], "too_many_internal_links", `must not contain more than ${MAX_INTERNAL_LINK_REFERENCES} internal links.`);
1154
+ const pointer = pointerOf(reference.path);
1155
+ references.push({
1156
+ sourceKey,
1157
+ area,
1158
+ delivered: delivered && (visible === undefined || visible.has(pointer)),
1159
+ targetId: reference.targetId,
1160
+ pointer,
1161
+ });
1162
+ }
1163
+ }
1164
+ add(fields, values, "$fields", "fields", true, ["fields"], visibility);
1165
+ blocks.forEach((block, index) => add(block.fields, block.data, block.key, "data", block.hidden !== true, ["blocks", index, "data"], block.visibility));
1166
+ return deepFreeze(references);
1167
+ }
911
1168
  /** Finds declared media leaves only; ordinary strings never become references. */
912
1169
  export function collectFieldMedia(definitions, values) {
913
1170
  const references = [];
@@ -1037,6 +1294,40 @@ export const BLOCK_SETTING_FIELD_TYPES = Object.freeze([
1037
1294
  "select",
1038
1295
  "text",
1039
1296
  ]);
1297
+ /** Validates and detaches settings-only visibility metadata. */
1298
+ export function normalizeSettingsVisibility(value, settings, path = "settingsVisibility") {
1299
+ if (value === undefined)
1300
+ return undefined;
1301
+ const raw = normalizeJsonValue(value, path, new WeakSet());
1302
+ if (!isRecord(raw))
1303
+ fail(path, "must be a plain object of setting rules.");
1304
+ for (const [target, rule] of Object.entries(raw)) {
1305
+ const at = `${path}.${target}`;
1306
+ if (!Object.hasOwn(settings, target))
1307
+ fail(at, "must target a declared scalar setting.");
1308
+ if (!isRecord(rule) ||
1309
+ Object.keys(rule).some((key) => !["setting", "values"].includes(key)) ||
1310
+ typeof rule.setting !== "string")
1311
+ fail(at, "must contain only setting and values.");
1312
+ if (rule.setting === target || Object.hasOwn(raw, rule.setting))
1313
+ fail(`${at}.setting`, "must be an unconditional sibling select; self references, chains and cycles are not allowed.");
1314
+ const controller = Object.hasOwn(settings, rule.setting)
1315
+ ? settings[rule.setting]
1316
+ : undefined;
1317
+ if (controller?.type !== "select" ||
1318
+ !controller.required ||
1319
+ !Object.hasOwn(controller, "defaultValue") ||
1320
+ typeof controller.defaultValue !== "string" ||
1321
+ !controller.options.includes(controller.defaultValue))
1322
+ fail(`${at}.setting`, "must name a required select setting with a valid default.");
1323
+ if (!Array.isArray(rule.values) ||
1324
+ rule.values.length === 0 ||
1325
+ new Set(rule.values).size !== rule.values.length ||
1326
+ rule.values.some((option) => typeof option !== "string" || !controller.options.includes(option)))
1327
+ fail(`${at}.values`, "must be a nonempty unique subset of the controller options.");
1328
+ }
1329
+ return deepFreeze(raw);
1330
+ }
1040
1331
  function blockFail(message) {
1041
1332
  throw new BlockConfigurationError(message);
1042
1333
  }
@@ -1137,9 +1428,11 @@ export function defineBlock(input) {
1137
1428
  "migrations",
1138
1429
  "layout",
1139
1430
  "settingsLayout",
1431
+ "settingsVisibility",
1140
1432
  "settings",
1141
1433
  "type",
1142
1434
  "version",
1435
+ "visibility",
1143
1436
  ]).has(key)) {
1144
1437
  blockFail(`block.${key} is not permitted.`);
1145
1438
  }
@@ -1163,6 +1456,8 @@ export function defineBlock(input) {
1163
1456
  const settings = normalizeBlockSettings(input.settings);
1164
1457
  const layout = normalizeFormLayout(input.layout, fields, `block.${input.type}.layout`);
1165
1458
  const settingsLayout = normalizeFormLayout(input.settingsLayout, settings ?? {}, `block.${input.type}.settingsLayout`);
1459
+ const settingsVisibility = normalizeSettingsVisibility(input.settingsVisibility, settings ?? {}, `block.${input.type}.settingsVisibility`);
1460
+ const visibility = normalizeFieldVisibility(input.visibility, fields, `block.${input.type}.visibility`);
1166
1461
  let defaultValue;
1167
1462
  if (input.defaultValue !== undefined) {
1168
1463
  try {
@@ -1170,7 +1465,7 @@ export function defineBlock(input) {
1170
1465
  if (!isRecord(normalized)) {
1171
1466
  blockFail("defaultValue must be a plain object.");
1172
1467
  }
1173
- defaultValue = deepFreeze(validateModelFields(fields, normalized, "draft"));
1468
+ defaultValue = deepFreeze(validateModelFields(fields, normalized, "draft", [], visibility));
1174
1469
  }
1175
1470
  catch (error) {
1176
1471
  if (error instanceof ContentValidationError) {
@@ -1187,16 +1482,19 @@ export function defineBlock(input) {
1187
1482
  ...(migrations === undefined ? {} : { migrations }),
1188
1483
  ...(layout === undefined ? {} : { layout }),
1189
1484
  ...(settingsLayout === undefined ? {} : { settingsLayout }),
1485
+ ...(settingsVisibility === undefined ? {} : { settingsVisibility }),
1190
1486
  ...(settings === undefined ? {} : { settings }),
1191
1487
  type: input.type,
1192
1488
  validate: (value, mode) => {
1489
+ const rules = visibility;
1193
1490
  if (!isRecord(value)) {
1194
- return validateModelFields(fields, value, mode);
1491
+ return validateModelFields(fields, value, mode, [], rules);
1195
1492
  }
1196
1493
  const withDefault = defaultValue === undefined ? value : { ...defaultValue, ...value };
1197
- return validateModelFields(fields, withDefault, mode);
1494
+ return validateModelFields(fields, withDefault, mode, [], rules);
1198
1495
  },
1199
1496
  version: input.version,
1497
+ ...(visibility === undefined ? {} : { visibility }),
1200
1498
  };
1201
1499
  return deepFreeze(definition);
1202
1500
  }
@@ -1218,6 +1516,11 @@ export function toBlockMetadata(definition) {
1218
1516
  : {
1219
1517
  settingsLayout: normalizeFormLayout(definition.settingsLayout, definition.settings ?? {}),
1220
1518
  }),
1519
+ ...(definition.settingsVisibility === undefined
1520
+ ? {}
1521
+ : {
1522
+ settingsVisibility: normalizeSettingsVisibility(definition.settingsVisibility, definition.settings ?? {}),
1523
+ }),
1221
1524
  ...(definition.settings === undefined
1222
1525
  ? {}
1223
1526
  : {
@@ -1228,6 +1531,9 @@ export function toBlockMetadata(definition) {
1228
1531
  }),
1229
1532
  type: definition.type,
1230
1533
  version: definition.version,
1534
+ ...(definition.visibility === undefined
1535
+ ? {}
1536
+ : { visibility: normalizeFieldVisibility(definition.visibility, definition.fields) }),
1231
1537
  };
1232
1538
  return deepFreeze(metadata);
1233
1539
  }
@@ -1252,11 +1558,12 @@ export function toBlockRegistryMetadata(registry) {
1252
1558
  }
1253
1559
  /** Validates one block's field record, applying its whole-record default first. */
1254
1560
  export function validateBlockData(definition, value, mode, path = []) {
1561
+ const rules = definition.visibility;
1255
1562
  if (!isRecord(value)) {
1256
- return validateModelFields(definition.fields, value, mode, path);
1563
+ return validateModelFields(definition.fields, value, mode, path, rules);
1257
1564
  }
1258
1565
  const withDefault = definition.defaultValue === undefined ? value : { ...definition.defaultValue, ...value };
1259
- return validateModelFields(definition.fields, withDefault, mode, path);
1566
+ return validateModelFields(definition.fields, withDefault, mode, path, rules);
1260
1567
  }
1261
1568
  /**
1262
1569
  * Validates a block's settings record against its declared settings, filling
@@ -1367,6 +1674,143 @@ export function effectiveAltText(usageAlt, mediaAlt) {
1367
1674
  return mediaAlt;
1368
1675
  return "";
1369
1676
  }
1677
+ /** Shared presentation rules for the independent scalar list settings. */
1678
+ export function listLayoutSettingsVisibility() {
1679
+ return deepFreeze({
1680
+ layoutWrap: { setting: "layoutMode", values: ["flex-row", "flex-column"] },
1681
+ layoutPreset: { setting: "layoutMode", values: ["grid"] },
1682
+ });
1683
+ }
1684
+ /** Shared scalar settings for one explicitly adopted list, in any block. */
1685
+ export function listLayoutSettings() {
1686
+ const cells = (rects) => ({
1687
+ cells: rects.map(([x, y, width, height]) => ({ x, y, width, height })),
1688
+ });
1689
+ const columns = (count) => cells(Array.from({ length: count }, (_, i) => [i * (12 / count), 0, 12 / count - 1, 12]));
1690
+ return deepFreeze({
1691
+ layoutMode: field.select({
1692
+ options: ["flex-row", "flex-column", "grid"],
1693
+ required: true,
1694
+ defaultValue: "grid",
1695
+ label: "Arrangement",
1696
+ presentation: {
1697
+ control: "cards",
1698
+ choices: [
1699
+ {
1700
+ value: "flex-row",
1701
+ label: "Horizontal",
1702
+ description: "Items flow across rows.",
1703
+ diagram: columns(3),
1704
+ },
1705
+ {
1706
+ value: "flex-column",
1707
+ label: "Vertical",
1708
+ description: "Items flow down columns. Wrapping needs a height set in site CSS.",
1709
+ diagram: cells([
1710
+ [0, 0, 12, 3],
1711
+ [0, 4, 12, 3],
1712
+ [0, 8, 12, 3],
1713
+ ]),
1714
+ },
1715
+ {
1716
+ value: "grid",
1717
+ label: "Grid",
1718
+ description: "Items use the selected grid preset.",
1719
+ diagram: cells([
1720
+ [0, 0, 5, 5],
1721
+ [6, 0, 5, 5],
1722
+ [0, 6, 5, 5],
1723
+ [6, 6, 5, 5],
1724
+ ]),
1725
+ },
1726
+ ],
1727
+ },
1728
+ }),
1729
+ layoutWrap: field.boolean({
1730
+ defaultValue: true,
1731
+ label: "Wrap items",
1732
+ description: "Applies to horizontal and vertical flex lists. Vertical wrapping requires a height set in site CSS.",
1733
+ }),
1734
+ layoutPreset: field.select({
1735
+ options: [
1736
+ "auto",
1737
+ "columns-2",
1738
+ "columns-3",
1739
+ "columns-4",
1740
+ "narrow-wide",
1741
+ "wide-narrow",
1742
+ "featured-first",
1743
+ ],
1744
+ required: true,
1745
+ defaultValue: "auto",
1746
+ label: "Grid preset",
1747
+ description: "Applies when Grid is selected. Schematics show composition; your site controls styling.",
1748
+ presentation: {
1749
+ control: "cards",
1750
+ choices: [
1751
+ {
1752
+ value: "auto",
1753
+ label: "Auto",
1754
+ description: "As many equal columns as fit.",
1755
+ diagram: cells([
1756
+ [0, 0, 3, 5],
1757
+ [4, 0, 3, 5],
1758
+ [8, 0, 3, 5],
1759
+ [0, 6, 3, 5],
1760
+ [4, 6, 3, 5],
1761
+ ]),
1762
+ },
1763
+ {
1764
+ value: "columns-2",
1765
+ label: "Two columns",
1766
+ description: "Two equal columns from 32rem.",
1767
+ diagram: columns(2),
1768
+ },
1769
+ {
1770
+ value: "columns-3",
1771
+ label: "Three columns",
1772
+ description: "Two from 32rem, three from 48rem.",
1773
+ diagram: columns(3),
1774
+ },
1775
+ {
1776
+ value: "columns-4",
1777
+ label: "Four columns",
1778
+ description: "Two from 32rem, three from 48rem, four from 64rem.",
1779
+ diagram: columns(4),
1780
+ },
1781
+ {
1782
+ value: "narrow-wide",
1783
+ label: "Narrow + wide",
1784
+ description: "Alternating 1:2 columns from 32rem.",
1785
+ diagram: cells([
1786
+ [0, 0, 3, 12],
1787
+ [4, 0, 8, 12],
1788
+ ]),
1789
+ },
1790
+ {
1791
+ value: "wide-narrow",
1792
+ label: "Wide + narrow",
1793
+ description: "Alternating 2:1 columns from 32rem.",
1794
+ diagram: cells([
1795
+ [0, 0, 8, 12],
1796
+ [9, 0, 3, 12],
1797
+ ]),
1798
+ },
1799
+ {
1800
+ value: "featured-first",
1801
+ label: "Featured first",
1802
+ description: "First item spans two columns from 32rem.",
1803
+ diagram: cells([
1804
+ [0, 0, 12, 5],
1805
+ [0, 6, 5, 5],
1806
+ [6, 6, 5, 5],
1807
+ ]),
1808
+ },
1809
+ ],
1810
+ },
1811
+ }),
1812
+ });
1813
+ }
1370
1814
  // The opt-in full-screen original of the `image` and `gallery` blocks.
1371
1815
  const lightboxSetting = field.boolean({
1372
1816
  defaultValue: false,
@@ -1378,6 +1822,68 @@ const imageLinkField = field.url({
1378
1822
  description: "Selecting the image opens this link instead of the full-screen view.",
1379
1823
  label: "Link",
1380
1824
  });
1825
+ // The aspect ratio of a `videoEmbed` block and of each `gallery` video item.
1826
+ const videoAspectRatioField = field.select({
1827
+ options: ["16:9", "4:3", "1:1", "4:5", "9:16"],
1828
+ required: true,
1829
+ defaultValue: "16:9",
1830
+ label: "Aspect ratio",
1831
+ description: "Reserves the video area before the player loads.",
1832
+ presentation: {
1833
+ control: "cards",
1834
+ choices: [
1835
+ {
1836
+ value: "16:9",
1837
+ label: "16:9",
1838
+ description: "Wide landscape.",
1839
+ diagram: { cells: [{ x: 0, y: 2, width: 12, height: 7 }] },
1840
+ },
1841
+ {
1842
+ value: "4:3",
1843
+ label: "4:3",
1844
+ description: "Classic landscape.",
1845
+ diagram: { cells: [{ x: 0, y: 1, width: 12, height: 9 }] },
1846
+ },
1847
+ {
1848
+ value: "1:1",
1849
+ label: "1:1",
1850
+ description: "Square.",
1851
+ diagram: { cells: [{ x: 1, y: 1, width: 9, height: 9 }] },
1852
+ },
1853
+ {
1854
+ value: "4:5",
1855
+ label: "4:5",
1856
+ description: "Portrait.",
1857
+ diagram: { cells: [{ x: 2, y: 1, width: 8, height: 10 }] },
1858
+ },
1859
+ {
1860
+ value: "9:16",
1861
+ label: "9:16",
1862
+ description: "Tall portrait.",
1863
+ diagram: { cells: [{ x: 3, y: 0, width: 6, height: 11 }] },
1864
+ },
1865
+ ],
1866
+ },
1867
+ });
1868
+ // The playback mode of a `videoEmbed` block and of each `gallery` video item.
1869
+ const videoPlaybackField = field.select({
1870
+ options: ["player", "ambient"],
1871
+ required: true,
1872
+ defaultValue: "player",
1873
+ label: "Playback",
1874
+ description: "Ambient videos play muted and loop without controls.",
1875
+ presentation: {
1876
+ control: "cards",
1877
+ choices: [
1878
+ { value: "player", label: "Player", description: "Visitors start the video." },
1879
+ {
1880
+ value: "ambient",
1881
+ label: "Ambient",
1882
+ description: "Muted, looping, no controls; respects reduced motion.",
1883
+ },
1884
+ ],
1885
+ },
1886
+ });
1381
1887
  /** Starter blocks implemented exclusively through the public block and field DSL. */
1382
1888
  export const builtInBlocks = deepFreeze({
1383
1889
  cta: defineBlock({
@@ -1393,38 +1899,95 @@ export const builtInBlocks = deepFreeze({
1393
1899
  version: 1,
1394
1900
  }),
1395
1901
  gallery: defineBlock({
1396
- description: "A grid of images with optional captions.",
1902
+ description: "A list of images and videos with selectable layouts and optional captions.",
1397
1903
  fields: {
1398
1904
  images: field.list({
1399
1905
  defaultValue: [],
1400
1906
  item: field.group({
1907
+ // The kind comes first, then each kind reads image (or video) before
1908
+ // its overrides: media, alt, caption, link or URL, title, caption,
1909
+ // playback, aspect ratio.
1401
1910
  fields: {
1911
+ kind: field.select({
1912
+ options: ["image", "video"],
1913
+ required: true,
1914
+ defaultValue: "image",
1915
+ label: "Type",
1916
+ presentation: {
1917
+ control: "cards",
1918
+ choices: [
1919
+ {
1920
+ value: "image",
1921
+ label: "Image",
1922
+ description: "A picture from the media library.",
1923
+ },
1924
+ { value: "video", label: "Video", description: "A YouTube or Vimeo video." },
1925
+ ],
1926
+ },
1927
+ }),
1928
+ media: field.media({ label: "Image", required: true }),
1929
+ videoUrl: field.url({
1930
+ required: true,
1931
+ embedProviders: ["youtube", "vimeo"],
1932
+ label: "Video URL",
1933
+ description: "Paste a YouTube or Vimeo video link, not iframe code.",
1934
+ }),
1402
1935
  alt: field.text({
1403
1936
  description: "Leave empty to use the media item's alt text.",
1404
1937
  label: "Alt text",
1405
1938
  }),
1939
+ videoTitle: field.text({
1940
+ required: true,
1941
+ minLength: 1,
1942
+ label: "Video title",
1943
+ description: "Names the video for visitors using assistive technology.",
1944
+ }),
1406
1945
  caption: field.text({
1407
- description: "Leave empty to use the media item's caption.",
1946
+ description: "An empty image caption uses the media item's caption.",
1408
1947
  label: "Caption",
1409
1948
  }),
1410
1949
  link: imageLinkField,
1411
- media: field.media({ label: "Image", required: true }),
1950
+ playback: videoPlaybackField,
1951
+ aspectRatio: videoAspectRatioField,
1952
+ },
1953
+ visibility: {
1954
+ media: { field: "kind", values: ["image"] },
1955
+ alt: { field: "kind", values: ["image"] },
1956
+ link: { field: "kind", values: ["image"] },
1957
+ videoUrl: { field: "kind", values: ["video"] },
1958
+ videoTitle: { field: "kind", values: ["video"] },
1959
+ playback: { field: "kind", values: ["video"] },
1960
+ aspectRatio: { field: "kind", values: ["video"] },
1412
1961
  },
1413
1962
  }),
1414
1963
  itemLabel: "caption",
1415
- label: "Images",
1964
+ label: "Images and videos",
1416
1965
  maxItems: 50,
1417
1966
  minItems: 1,
1418
1967
  }),
1419
1968
  title: field.text({ label: "Title" }),
1420
1969
  },
1421
1970
  label: "Gallery",
1422
- // Version 2 only added the lightbox setting and version 3 only the optional
1423
- // item link, so earlier data is already valid.
1424
- migrations: { 2: (block) => block, 3: (block) => block },
1425
- settings: { lightbox: lightboxSetting },
1971
+ // Version 2 only added the lightbox setting, version 3 only the optional
1972
+ // item link and version 4 scalar layout defaults. Version 5 adds item kinds
1973
+ // whose default makes every stored item an image; data stays valid.
1974
+ migrations: {
1975
+ 2: (block) => block,
1976
+ 3: (block) => block,
1977
+ 4: (block) => block,
1978
+ 5: (block) => block,
1979
+ },
1980
+ settings: { ...listLayoutSettings(), lightbox: lightboxSetting },
1981
+ settingsVisibility: listLayoutSettingsVisibility(),
1982
+ settingsLayout: {
1983
+ mode: "sections",
1984
+ groups: [
1985
+ { key: "layout", label: "Layout", fields: ["layoutMode", "layoutWrap", "layoutPreset"] },
1986
+ { key: "behavior", label: "Behavior", fields: ["lightbox"] },
1987
+ ],
1988
+ },
1426
1989
  type: "gallery",
1427
- version: 3,
1990
+ version: 5,
1428
1991
  }),
1429
1992
  hero: defineBlock({
1430
1993
  description: "Large heading with optional text, image, and action.",
@@ -1442,11 +2005,12 @@ export const builtInBlocks = deepFreeze({
1442
2005
  }),
1443
2006
  image: defineBlock({
1444
2007
  description: "A single image with an optional caption and alt text that overrides the media alt.",
2008
+ // Media comes first so editors show the image before its overrides.
1445
2009
  fields: {
2010
+ media: field.media({ required: true }),
1446
2011
  alt: field.text(),
1447
2012
  caption: field.text(),
1448
2013
  link: imageLinkField,
1449
- media: field.media({ required: true }),
1450
2014
  },
1451
2015
  label: "Image",
1452
2016
  // Version 2 only made `alt` optional, version 3 only added the lightbox
@@ -1456,6 +2020,25 @@ export const builtInBlocks = deepFreeze({
1456
2020
  type: "image",
1457
2021
  version: 4,
1458
2022
  }),
2023
+ link: defineBlock({
2024
+ description: "A link to a page or URL, presented as a button or text.",
2025
+ fields: {
2026
+ label: field.text({ label: "Label", minLength: 1, maxLength: 200, required: true }),
2027
+ url: field.url({ label: "Destination", required: true }),
2028
+ },
2029
+ settings: {
2030
+ appearance: field.select({
2031
+ label: "Appearance",
2032
+ options: ["button", "text"],
2033
+ defaultValue: "button",
2034
+ required: true,
2035
+ }),
2036
+ newTab: field.boolean({ label: "Open in new tab", defaultValue: false, required: true }),
2037
+ },
2038
+ label: "Link",
2039
+ type: "link",
2040
+ version: 1,
2041
+ }),
1459
2042
  navigation: defineBlock({
1460
2043
  description: "A list of links with optional one-level submenus.",
1461
2044
  fields: {
@@ -1512,6 +2095,36 @@ export const builtInBlocks = deepFreeze({
1512
2095
  type: "richText",
1513
2096
  version: 1,
1514
2097
  }),
2098
+ videoEmbed: defineBlock({
2099
+ type: "videoEmbed",
2100
+ version: 2,
2101
+ label: "Video embed",
2102
+ description: "A YouTube or Vimeo video with an optional image preview.",
2103
+ migrations: { 2: (block) => block },
2104
+ settings: {
2105
+ aspectRatio: videoAspectRatioField,
2106
+ playback: videoPlaybackField,
2107
+ },
2108
+ fields: {
2109
+ url: field.url({
2110
+ required: true,
2111
+ embedProviders: ["youtube", "vimeo"],
2112
+ label: "Video URL",
2113
+ description: "Paste a YouTube or Vimeo video link, not iframe code.",
2114
+ }),
2115
+ title: field.text({
2116
+ required: true,
2117
+ minLength: 1,
2118
+ label: "Title",
2119
+ description: "Names the video for visitors using assistive technology.",
2120
+ }),
2121
+ poster: field.media({
2122
+ label: "Preview image",
2123
+ description: "Optional. Defers player loading until selected in Player mode; stays underneath Ambient playback.",
2124
+ }),
2125
+ caption: field.text({ label: "Caption" }),
2126
+ },
2127
+ }),
1515
2128
  });
1516
2129
  /** Maximum title length shared by draft, publish, REST, and admin validation. */
1517
2130
  export const MAX_TITLE_LENGTH = 200;
@@ -1617,7 +2230,7 @@ export function validateEntryAggregate(input, model, registry, mode) {
1617
2230
  ...(input.slug === undefined ? {} : { slug: input.slug }),
1618
2231
  title: input.title,
1619
2232
  }, mode);
1620
- const fields = validateModelFields(model.fields, input.fields, mode, ["fields"]);
2233
+ const fields = validateModelFields(model.fields, input.fields, mode, ["fields"], model.visibility);
1621
2234
  assertJsonSize(fields, ["fields"]);
1622
2235
  const keys = new Set();
1623
2236
  const anchors = new Set();
@@ -1692,6 +2305,12 @@ export function validateEntryAggregate(input, model, registry, mode) {
1692
2305
  data: block.data,
1693
2306
  path: ["blocks", index, "data"],
1694
2307
  })));
2308
+ collectSnapshotInternalLinks(model.fields, fields, blocks.map((block) => ({
2309
+ key: block.key,
2310
+ fields: registry.get(block.type).fields,
2311
+ data: block.data,
2312
+ hidden: block.hidden,
2313
+ })));
1695
2314
  return deepFreeze({
1696
2315
  blocks: deepFreeze(blocks),
1697
2316
  fields,