alpha2 0.3.0 → 0.4.0

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/project.js CHANGED
@@ -14,7 +14,8 @@
14
14
  * Timeline values are integer ticks at {@link TICKS_PER_SECOND}. Ranges are
15
15
  * half-open: `[start, end)`.
16
16
  */
17
- import { AUDIO_EFFECT_STATE_MARGIN_MS, MAX_CANVAS_DIMENSION, MAX_CANVAS_PIXELS, MAX_TEXT_CONTENT_BYTES, MAX_FONT_FAMILY_BYTES, MAX_COMPOSITIONS, MAX_COMPOSITION_NODES, MAX_COMPOSITION_CONTROLS, MAX_COMPOSITION_DEPTH, MAX_GROUP_INPUTS, MAX_EFFECT_INPUTS, MAX_FRAME_INLINED_NODES, MAX_INLINED_NODES, MAX_MERGE_LAYERS, MAX_CLIP_MASKS, MAX_DASH_ENTRIES, MAX_GRADIENT_STOPS, MAX_PATH_SUBPATHS, MAX_PATH_VERTICES, MAX_POLYSTAR_POINTS, MAX_SHAPE_DEPTH, MAX_SHAPE_ITEMS, MIN_POLYSTAR_POINTS, MAX_CLIPS, MAX_CLIPS_PER_TRACK, MAX_AUDIO_DELAY_MS, MAX_AUDIO_EFFECTS, MAX_CAPTION_FONT_SIZE, MAX_TEXT_GENERATOR_FONT_SIZE, MAX_LINE_HEIGHT, MAX_TEXT_OUTLINE_WIDTH, MAX_TEXT_PADDING, MAX_CHAIN_EFFECTS, MAX_COMPRESSOR_RATIO, MAX_ENVELOPE_MS, MAX_EQ_BANDS, MAX_LOOKAHEAD_MS, MIN_LINE_HEIGHT, MIN_LEVEL_DB, MAX_EQ_FREQUENCY_HZ, MAX_EQ_GAIN_DB, MAX_EQ_Q, MAX_GAIN, MAX_PROJECT_JSON_BYTES, MAX_SAMPLE_RATE, MAX_TRACKS, MAX_TRANSITIONS_PER_TRACK, MIN_EQ_FREQUENCY_HZ, MIN_EQ_Q, MIN_SAMPLE_RATE, MIN_HDR_PEAK_NITS, MAX_HDR_PEAK_NITS, MAX_SEQUENCE_FRAMES, REVERB_DELAY_MS, TICKS_PER_SECOND, } from "./generated/project-schema.js";
17
+ import { parseHex, parseInsets, parseLength, parseOffset, parsePlacement, parseSize, parseTrackList, } from "./layout-values.js";
18
+ import { AUDIO_EFFECT_STATE_MARGIN_MS, MAX_CANVAS_DIMENSION, MAX_CANVAS_PIXELS, MAX_TEXT_CONTENT_BYTES, MAX_FONT_FAMILY_BYTES, MAX_COMPOSITIONS, MAX_COMPOSITION_NODES, MAX_COMPOSITION_CONTROLS, MAX_COMPOSITION_DEPTH, MAX_GROUP_INPUTS, MAX_EFFECT_INPUTS, MAX_FRAME_INLINED_NODES, MAX_INLINED_NODES, MAX_MERGE_LAYERS, MAX_CLIP_MASKS, MAX_DASH_ENTRIES, MAX_GRADIENT_STOPS, MAX_PATH_SUBPATHS, MAX_PATH_VERTICES, MAX_POLYSTAR_POINTS, MAX_SHAPE_DEPTH, MAX_SHAPE_ITEMS, MAX_LAYOUT_DEPTH, MAX_LAYOUT_FONT_SIZE, MAX_LAYOUT_ISOLATED, MAX_LAYOUT_NODES, MAX_LAYOUT_TEXTS, MAX_GRID_TRACKS, MIN_POLYSTAR_POINTS, MAX_CLIPS, MAX_CLIPS_PER_TRACK, MAX_AUDIO_DELAY_MS, MAX_AUDIO_EFFECTS, MAX_CAPTION_FONT_SIZE, MAX_TEXT_GENERATOR_FONT_SIZE, MAX_LINE_HEIGHT, MAX_TEXT_OUTLINE_WIDTH, MAX_TEXT_PADDING, MAX_CHAIN_EFFECTS, MAX_COMPRESSOR_RATIO, MAX_ENVELOPE_MS, MAX_EQ_BANDS, MAX_LOOKAHEAD_MS, MIN_LINE_HEIGHT, MIN_LEVEL_DB, MAX_EQ_FREQUENCY_HZ, MAX_EQ_GAIN_DB, MAX_EQ_Q, MAX_GAIN, MAX_PROJECT_JSON_BYTES, MAX_SAMPLE_RATE, MAX_TRACKS, MAX_TRANSITIONS_PER_TRACK, MIN_EQ_FREQUENCY_HZ, MIN_EQ_Q, MIN_SAMPLE_RATE, MIN_HDR_PEAK_NITS, MAX_HDR_PEAK_NITS, MAX_SEQUENCE_FRAMES, REVERB_DELAY_MS, TICKS_PER_SECOND, } from "./generated/project-schema.js";
18
19
  import { PROJECT_SHAPE } from "./generated/project-shape.js";
19
20
  import { MAX_JSON_DEPTH, hasLoneSurrogate, readJsonText, } from "./json-text.js";
20
21
  export * from "./generated/project-schema.js";
@@ -141,7 +142,7 @@ function invariantProblems(value) {
141
142
  return problems;
142
143
  }
143
144
  const resourceList = list(project.effect_resources, "effect_resources", false);
144
- const catalog = catalogOf(sourceList, resourceList, compositionList);
145
+ const catalog = catalogOf(sourceList, resourceList, compositionList, canvasOf(project));
145
146
  for (const problem of catalog.problems)
146
147
  problems.push(problem);
147
148
  const trackIds = new Set();
@@ -218,7 +219,14 @@ function headerProblems(project) {
218
219
  }
219
220
  return problems;
220
221
  }
221
- function catalogOf(sourceList, resourceList, compositionList) {
222
+ /** The project's canvas, which its layouts' pixels are pixels of. */
223
+ function canvasOf(project) {
224
+ const settings = isRecord(project.settings)
225
+ ? project.settings
226
+ : {};
227
+ return [Number(settings.width), Number(settings.height)];
228
+ }
229
+ function catalogOf(sourceList, resourceList, compositionList, canvas) {
222
230
  const problems = [];
223
231
  const sources = new Map(sourceList.map((source) => [
224
232
  text(isRecord(source) ? source.id : ""),
@@ -264,9 +272,13 @@ function catalogOf(sourceList, resourceList, compositionList) {
264
272
  }
265
273
  else if (source.kind === "generated") {
266
274
  const issue = generatorShapeIssue(source.generator);
275
+ const layout = generatorLayoutIssue(source.generator, canvas);
267
276
  if (issue) {
268
277
  problems.push(shapeProblem(`source ${sourceId}`, issue));
269
278
  }
279
+ else if (layout) {
280
+ problems.push(layoutProblem(`source ${sourceId}`, layout));
281
+ }
270
282
  else if (!validGenerator(source.generator) ||
271
283
  text(source.locator).length > 0 ||
272
284
  source.color_metadata != null ||
@@ -315,7 +327,7 @@ function catalogOf(sourceList, resourceList, compositionList) {
315
327
  return names;
316
328
  };
317
329
  for (const composition of compositionList) {
318
- const found = compositionProblems(composition, sources, effectResources, compositionsById, controlNamesOf);
330
+ const found = compositionProblems(composition, sources, effectResources, compositionsById, controlNamesOf, canvas);
319
331
  for (const problem of found)
320
332
  problems.push(problem);
321
333
  }
@@ -549,7 +561,7 @@ function rememberShape(node, value, read) {
549
561
  readShapes.set(value, { node, read });
550
562
  }
551
563
  /** The catalog of the lists, the one made before when they are the same immutable lists. */
552
- function catalogFor(sources, resources, compositions) {
564
+ function catalogFor(sources, resources, compositions, canvas) {
553
565
  const reusable = typeof sources === "object" &&
554
566
  sources !== null &&
555
567
  immutable.has(sources) &&
@@ -559,12 +571,14 @@ function catalogFor(sources, resources, compositions) {
559
571
  const known = catalogs.get(sources);
560
572
  if (known !== undefined &&
561
573
  known.resources === resources &&
562
- known.compositions === compositions)
574
+ known.compositions === compositions &&
575
+ known.canvas[0] === canvas[0] &&
576
+ known.canvas[1] === canvas[1])
563
577
  return known.catalog;
564
578
  }
565
- const catalog = catalogOf(Array.isArray(sources) ? sources : [], Array.isArray(resources) ? resources : [], Array.isArray(compositions) ? compositions : []);
579
+ const catalog = catalogOf(Array.isArray(sources) ? sources : [], Array.isArray(resources) ? resources : [], Array.isArray(compositions) ? compositions : [], canvas);
566
580
  if (reusable && catalog.problems.length === 0)
567
- catalogs.set(sources, { resources, compositions, catalog });
581
+ catalogs.set(sources, { resources, compositions, canvas, catalog });
568
582
  return catalog;
569
583
  }
570
584
  function summaryOf(track, catalog) {
@@ -627,7 +641,7 @@ function invariantsHold(value) {
627
641
  if (countProblems(project.sources, project.compositions ?? [], tracks).length >
628
642
  0)
629
643
  return false;
630
- const catalog = catalogFor(project.sources, project.effect_resources, project.compositions);
644
+ const catalog = catalogFor(project.sources, project.effect_resources, project.compositions, canvasOf(project));
631
645
  if (catalog.problems.length > 0)
632
646
  return false;
633
647
  const trackIds = new Set();
@@ -899,9 +913,376 @@ function checkShape(node, value, path, problems, spelling, texts) {
899
913
  rememberShape(node, value, read);
900
914
  return read;
901
915
  }
916
+ /**
917
+ * The defs whose JSON is a CSS value form or an alternative spelling, read as the engine's parser
918
+ * reads them (`alpha2_model::layout_values`): each problem worded as the parser words it, and the
919
+ * value given to the model's checks in one form. A color is `{ red, green, blue, alpha }`, a paint
920
+ * tagged, a layout length `{ unit, value }`, sides `{ top, right, bottom, left }` of lengths, an
921
+ * offset `{ x, y }` of lengths, a track list its parsed components, a grid placement
922
+ * `{ start, end }` edges.
923
+ */
924
+ const SHAPE_DEFS = shapeRoot.$defs;
925
+ /** A value read by `parse`, its problem reported at `path` as the parser reports it. */
926
+ function parsedOr(parsed, path, problems, value) {
927
+ if (parsed.ok)
928
+ return parsed.value;
929
+ problems.push(`${path}: ${parsed.error}`);
930
+ return value;
931
+ }
932
+ /** A length: a number is a fraction, a string `"<n>px"` or (with `percent`) `"<n>%"`. */
933
+ function readLayoutLength(percent) {
934
+ return (value, path, problems) => {
935
+ if (typeof value === "number")
936
+ return { unit: "fraction", value: Math.fround(value) };
937
+ if (typeof value === "string")
938
+ return parsedOr(percent ? parseLength(value) : parseSize(value), path, problems, value);
939
+ problems.push(`${path} must be number or string`);
940
+ return value;
941
+ };
942
+ }
943
+ /** Fields of an object form: unknown ones refused, required ones present, each read by `read`. */
944
+ function readFields(value, path, problems, fields, required, read, spelling) {
945
+ for (const key of Object.keys(value)) {
946
+ if (!fields.includes(key))
947
+ problems.push(`${path} has unknown field ${describeValue(key)}`);
948
+ }
949
+ const out = {};
950
+ for (const field of fields) {
951
+ if (value[field] === undefined) {
952
+ if (required)
953
+ problems.push(`${path}.${field} is required`);
954
+ else
955
+ out[field] = { unit: "fraction", value: 0 };
956
+ continue;
957
+ }
958
+ out[field] = read(value[field], `${path}.${field}`, problems, spelling);
959
+ }
960
+ return out;
961
+ }
962
+ const readSize = readLayoutLength(false);
963
+ const SIDES = ["top", "right", "bottom", "left"];
964
+ const SHAPE_READERS = new Map([
965
+ [
966
+ SHAPE_DEFS.Rgba,
967
+ (value, path, problems, spelling) => {
968
+ if (typeof value === "string")
969
+ return parsedOr(parseHex(value), path, problems, value);
970
+ // The object form, or what is wrong with a value of neither form.
971
+ const object = SHAPE_DEFS.Rgba.anyOf[0];
972
+ return checkShape(object, value, path, problems, spelling);
973
+ },
974
+ ],
975
+ [
976
+ SHAPE_DEFS.Paint,
977
+ (value, path, problems, spelling) => {
978
+ // A color, hex or object, paints solid: told apart by its lack of a tag.
979
+ if (typeof value === "string" ||
980
+ (isRecord(value) && !("type" in value))) {
981
+ const color = checkShape(SHAPE_DEFS.Rgba, value, path, problems, spelling);
982
+ return { type: "solid", color };
983
+ }
984
+ const tagged = SHAPE_DEFS.Paint.oneOf.filter((variant) => variant.$ref === undefined);
985
+ return checkVariants(tagged, value, path, problems, spelling, undefined);
986
+ },
987
+ ],
988
+ [SHAPE_DEFS.LayoutLength, readLayoutLength(true)],
989
+ [SHAPE_DEFS.LayoutSize, readSize],
990
+ [
991
+ SHAPE_DEFS.Insets,
992
+ (value, path, problems, spelling) => {
993
+ const sides = (lengths) => Object.fromEntries(SIDES.map((side, index) => [side, lengths[index]]));
994
+ if (typeof value === "number")
995
+ return sides(Array(4).fill({ unit: "fraction", value: Math.fround(value) }));
996
+ if (typeof value === "string") {
997
+ const parsed = parseInsets(value);
998
+ return parsed.ok
999
+ ? sides(parsed.value)
1000
+ : parsedOr(parsed, path, problems, value);
1001
+ }
1002
+ if (isRecord(value))
1003
+ return readFields(value, path, problems, SIDES, false, readSize, spelling);
1004
+ problems.push(`${path} must be number, string, or object`);
1005
+ return value;
1006
+ },
1007
+ ],
1008
+ [
1009
+ SHAPE_DEFS.LayoutOffset,
1010
+ (value, path, problems, spelling) => {
1011
+ if (typeof value === "string")
1012
+ return parsedOr(parseOffset(value), path, problems, value);
1013
+ if (isRecord(value))
1014
+ return readFields(value, path, problems, ["x", "y"], true, readSize, spelling);
1015
+ problems.push(`${path} must be string or object`);
1016
+ return value;
1017
+ },
1018
+ ],
1019
+ [
1020
+ SHAPE_DEFS.TrackList,
1021
+ (value, path, problems) => {
1022
+ if (typeof value === "string")
1023
+ return parsedOr(parseTrackList(value), path, problems, value);
1024
+ problems.push(`${path} must be string`);
1025
+ return value;
1026
+ },
1027
+ ],
1028
+ [
1029
+ SHAPE_DEFS.GridPlacement,
1030
+ (value, path, problems) => {
1031
+ if (typeof value === "number" || typeof value === "string")
1032
+ return parsedOr(parsePlacement(value), path, problems, value);
1033
+ problems.push(`${path} must be integer or string`);
1034
+ return value;
1035
+ },
1036
+ ],
1037
+ ]);
1038
+ /** The shortest decimal that reads back as the same 32-bit float, as the engine writes one. */
1039
+ function shortestFloat32(value) {
1040
+ const target = Math.fround(value);
1041
+ for (let digits = 1; digits < 9; digits++) {
1042
+ const short = Number(target.toPrecision(digits));
1043
+ if (Math.fround(short) === target)
1044
+ return short;
1045
+ }
1046
+ return Number(target.toPrecision(9));
1047
+ }
1048
+ /**
1049
+ * `color` as the engine writes it: a CSS hex string becomes the components object, each
1050
+ * component the 32-bit value the engine reads, spelled shortest.
1051
+ *
1052
+ * @throws A `TypeError` for a string that is not CSS hex.
1053
+ */
1054
+ export function canonicalRgba(color) {
1055
+ if (typeof color !== "string")
1056
+ return color;
1057
+ const parsed = parseHex(color);
1058
+ if (!parsed.ok)
1059
+ throw new TypeError(parsed.error);
1060
+ const { red, green, blue, alpha } = parsed.value;
1061
+ return {
1062
+ red: shortestFloat32(red),
1063
+ green: shortestFloat32(green),
1064
+ blue: shortestFloat32(blue),
1065
+ alpha: shortestFloat32(alpha),
1066
+ };
1067
+ }
1068
+ /**
1069
+ * `paint` as the engine writes it: a color (hex or object) becomes a solid paint of it, and
1070
+ * every color in it the components object.
1071
+ *
1072
+ * @throws A `TypeError` for a color string that is not CSS hex.
1073
+ */
1074
+ export function canonicalPaint(paint) {
1075
+ if (typeof paint === "string" || !("type" in paint)) {
1076
+ return { type: "solid", color: canonicalRgba(paint) };
1077
+ }
1078
+ if (paint.type === "solid") {
1079
+ return { ...paint, color: canonicalRgba(paint.color) };
1080
+ }
1081
+ return {
1082
+ ...paint,
1083
+ stops: paint.stops.map((stop) => ({
1084
+ ...stop,
1085
+ color: canonicalRgba(stop.color),
1086
+ })),
1087
+ };
1088
+ }
1089
+ /** A length read from a CSS token, written back as the engine writes it. */
1090
+ function lengthWritten(length) {
1091
+ const value = shortestFloat32(length.value);
1092
+ return length.unit === "px" ? `${value}px` : value;
1093
+ }
1094
+ // The walk below reads what it can and leaves the rest as it is, for validation to report. Each
1095
+ // step returns its input itself when nothing in it changes, so a document already in canonical
1096
+ // form comes back as the same object, and a part that changes shares every part that did not.
1097
+ /** `color` as an object; a string that is not hex stays as it is. */
1098
+ function rgbaRead(color) {
1099
+ if (typeof color !== "string")
1100
+ return color;
1101
+ return parseHex(color).ok ? canonicalRgba(color) : color;
1102
+ }
1103
+ /** `paint` tagged, its colors objects; what is not a paint stays as it is. */
1104
+ function paintRead(paint) {
1105
+ if (typeof paint === "string" || (isRecord(paint) && !("type" in paint))) {
1106
+ const color = rgbaRead(paint);
1107
+ return isRecord(color) ? { type: "solid", color } : paint;
1108
+ }
1109
+ if (!isRecord(paint))
1110
+ return paint;
1111
+ if (paint.type === "solid") {
1112
+ const color = rgbaRead(paint.color);
1113
+ return color === paint.color ? paint : { ...paint, color };
1114
+ }
1115
+ if (!Array.isArray(paint.stops))
1116
+ return paint;
1117
+ const stops = paint.stops;
1118
+ const read = stops.map((stop) => {
1119
+ if (!isRecord(stop))
1120
+ return stop;
1121
+ const color = rgbaRead(stop.color);
1122
+ return color === stop.color ? stop : { ...stop, color };
1123
+ });
1124
+ return read.every((stop, index) => stop === stops[index])
1125
+ ? paint
1126
+ : { ...paint, stops: read };
1127
+ }
1128
+ const SIDE_NAMES = ["top", "right", "bottom", "left"];
1129
+ /** Sides as the four-side object; what cannot be read stays as it is. */
1130
+ function insetsRead(value) {
1131
+ if (typeof value === "number") {
1132
+ return { top: value, right: value, bottom: value, left: value };
1133
+ }
1134
+ if (typeof value === "string") {
1135
+ const parsed = parseInsets(value);
1136
+ if (!parsed.ok)
1137
+ return value;
1138
+ const [top, right, bottom, left] = parsed.value.map(lengthWritten);
1139
+ return { top, right, bottom, left };
1140
+ }
1141
+ if (!isRecord(value) || SIDE_NAMES.every((side) => value[side] !== undefined))
1142
+ return value;
1143
+ return Object.fromEntries([
1144
+ ...Object.entries(value),
1145
+ ...SIDE_NAMES.map((side) => [side, value[side] ?? 0]),
1146
+ ]);
1147
+ }
1148
+ /** An offset as `{ x, y }`; what cannot be read stays as it is. */
1149
+ function offsetRead(value) {
1150
+ if (typeof value !== "string")
1151
+ return value;
1152
+ const parsed = parseOffset(value);
1153
+ return parsed.ok
1154
+ ? { x: lengthWritten(parsed.value.x), y: lengthWritten(parsed.value.y) }
1155
+ : value;
1156
+ }
1157
+ /**
1158
+ * `project` in the forms the engine writes it back ({@link Canonical}): every color the
1159
+ * components object, every paint tagged, every padding and margin the four sides, every offset
1160
+ * `{ x, y }`. The forms the engine reads but never writes (CSS hex, a color as a paint, the
1161
+ * sides shorthand, a `translate` string) are gone, so code that reads the document can take the
1162
+ * one form. A value it cannot read (a string that is not hex, say) stays as it is, for
1163
+ * {@link validateProject} to report: give it a document that validates to get a document in
1164
+ * canonical form.
1165
+ *
1166
+ * The input is not changed. A part that is already canonical comes back as the same object, so
1167
+ * a document in canonical form is returned itself, and a frozen part met before is not walked
1168
+ * again: run on a changed copy of a document read before, it costs the parts that changed.
1169
+ */
1170
+ export function canonicalProject(project) {
1171
+ const reusing = reusingShapes;
1172
+ reusingShapes = true;
1173
+ try {
1174
+ return canonicalAt(shapeRoot, project);
1175
+ }
1176
+ finally {
1177
+ reusingShapes = reusing;
1178
+ }
1179
+ }
1180
+ /** The canonical form of frozen values met before, by the node they were read as. */
1181
+ const canonicalShapes = new WeakMap();
1182
+ /** The defs a value is put in canonical form at, and every def that can hold one of them. */
1183
+ const CANONICAL_DEFS = (() => {
1184
+ const holding = new Set(["Rgba", "Paint", "Insets", "LayoutOffset"]);
1185
+ const refs = Object.entries(SHAPE_DEFS).map(([name, def]) => [name, refsIn(def)]);
1186
+ for (let grew = true; grew;) {
1187
+ grew = false;
1188
+ for (const [name, names] of refs)
1189
+ if (!holding.has(name) && names.some((ref) => holding.has(ref))) {
1190
+ holding.add(name);
1191
+ grew = true;
1192
+ }
1193
+ }
1194
+ return holding;
1195
+ })();
1196
+ /** The defs `node` refers to anywhere in it. */
1197
+ function refsIn(node) {
1198
+ return [
1199
+ ...JSON.stringify(node).matchAll(/"\$ref":"#\/\$defs\/([^"]+)"/g),
1200
+ ].map((match) => match[1]);
1201
+ }
1202
+ const holdingNodes = new WeakMap();
1203
+ /**
1204
+ * Whether a value read as `node` can hold a color, paint, sides or offset. The walk does not
1205
+ * read a field that cannot: it costs nothing, and reads nothing it has no use for.
1206
+ */
1207
+ function mayHold(node) {
1208
+ let holds = holdingNodes.get(node);
1209
+ if (holds === undefined) {
1210
+ holds = refsIn(node).some((ref) => CANONICAL_DEFS.has(ref));
1211
+ holdingNodes.set(node, holds);
1212
+ }
1213
+ return holds;
1214
+ }
1215
+ function canonicalAt(node, value) {
1216
+ if (typeof node !== "object" || !mayHold(node))
1217
+ return value;
1218
+ if (typeof value !== "object" || value === null)
1219
+ return canonicalLeaf(node, value);
1220
+ const known = canonicalShapes.get(value);
1221
+ if (known?.node === node)
1222
+ return known.canonical;
1223
+ const canonical = canonicalWalk(node, value);
1224
+ if (Object.isFrozen(value))
1225
+ canonicalShapes.set(value, { node, canonical });
1226
+ return canonical;
1227
+ }
1228
+ /** A string or number where a color, paint, sides or offset lies, in its canonical form. */
1229
+ function canonicalLeaf(node, value) {
1230
+ if (typeof node !== "object" || value === null || value === undefined)
1231
+ return value;
1232
+ return canonicalWalk(node, value);
1233
+ }
1234
+ function canonicalWalk(node, value) {
1235
+ const schema = resolveShape(node);
1236
+ if (schema === SHAPE_DEFS.Rgba)
1237
+ return rgbaRead(value);
1238
+ if (schema === SHAPE_DEFS.Paint)
1239
+ return paintRead(value);
1240
+ if (schema === SHAPE_DEFS.Insets)
1241
+ return insetsRead(value);
1242
+ if (schema === SHAPE_DEFS.LayoutOffset)
1243
+ return offsetRead(value);
1244
+ const variants = (schema.oneOf ?? schema.anyOf);
1245
+ if (variants !== undefined) {
1246
+ // The form that fits, as the parser picks it.
1247
+ const fits = variants.find((variant) => {
1248
+ const found = [];
1249
+ checkShape(variant, value, "", found, undefined);
1250
+ return found.length === 0;
1251
+ });
1252
+ return fits === undefined ? value : canonicalAt(fits, value);
1253
+ }
1254
+ if (typeof value !== "object" || value === null)
1255
+ return value;
1256
+ if (Array.isArray(value)) {
1257
+ const items = value;
1258
+ const prefix = schema.prefixItems;
1259
+ const rest = (schema.items ?? true);
1260
+ const read = items.map((item, index) => canonicalAt(prefix !== undefined && index < prefix.length ? prefix[index] : rest, item));
1261
+ return read.every((item, index) => item === items[index]) ? value : read;
1262
+ }
1263
+ if (!isRecord(value))
1264
+ return value;
1265
+ const properties = (schema.properties ?? {});
1266
+ const extra = (schema.additionalProperties ?? true);
1267
+ let read;
1268
+ for (const key of Object.keys(value)) {
1269
+ const field = Object.hasOwn(properties, key) ? properties[key] : extra;
1270
+ // A field that cannot hold what is put in canonical form is not read.
1271
+ if (typeof field !== "object" || !mayHold(field))
1272
+ continue;
1273
+ const before = value[key];
1274
+ const canonical = canonicalAt(field, before);
1275
+ if (canonical !== before)
1276
+ (read ??= {})[key] = canonical;
1277
+ }
1278
+ return read === undefined ? value : { ...value, ...read };
1279
+ }
902
1280
  /** {@link checkShape} of a value not known to match `node`. */
903
1281
  function walkShape(node, value, path, problems, spelling, texts) {
904
1282
  const schema = resolveShape(node);
1283
+ const reader = SHAPE_READERS.get(schema);
1284
+ if (reader !== undefined)
1285
+ return reader(value, path, problems, spelling);
905
1286
  const variants = (schema.oneOf ?? schema.anyOf);
906
1287
  if (variants !== undefined) {
907
1288
  return checkVariants(variants, value, path, problems, spelling, texts);
@@ -1863,7 +2244,7 @@ function positive(value) {
1863
2244
  * ordered stops, a linear gradient's ends distinct, a radial radius positive. Or shapes whose
1864
2245
  * content tree is valid ({@link shapeItemsIssue}). Or text: non-empty, at most
1865
2246
  * {@link MAX_TEXT_CONTENT_BYTES} bytes, in a valid style whose font size is at most
1866
- * {@link MAX_TEXT_GENERATOR_FONT_SIZE}.
2247
+ * {@link MAX_TEXT_GENERATOR_FONT_SIZE}. Or a layout whose tree is valid ({@link layoutIssue}).
1867
2248
  */
1868
2249
  function validGenerator(generator) {
1869
2250
  if (!isRecord(generator))
@@ -1872,6 +2253,8 @@ function validGenerator(generator) {
1872
2253
  return validPaint(generator.paint);
1873
2254
  if (generator.type === "shapes")
1874
2255
  return shapeItemsIssue(generator.items) === undefined;
2256
+ if (generator.type === "layout")
2257
+ return layoutIssue(generator.root) === undefined;
1875
2258
  if (generator.type === "text")
1876
2259
  return (typeof generator.text === "string" &&
1877
2260
  generator.text.length > 0 &&
@@ -1901,6 +2284,458 @@ function generatorShapeIssue(generator) {
1901
2284
  function shapeProblem(owner, issue) {
1902
2285
  return `${owner} has an invalid shape: ${issue.at} ${issue.problem}`;
1903
2286
  }
2287
+ /** Mirrors `LayoutProblem`'s wording. */
2288
+ const LAYOUT_PROBLEM = {
2289
+ tooManyNodes: "has more nodes than a layout may hold",
2290
+ tooDeep: "nests nodes too deeply",
2291
+ tooManyTexts: "has more text nodes than a layout may hold",
2292
+ tooManyIsolated: "has more nodes with opacity, transforms, or hidden overflow than a layout may hold",
2293
+ mixedContent: "has more than one of children, text, and shape",
2294
+ displayOnLeaf: "sets display on a node with text or shape content",
2295
+ containerFieldOnLeaf: "sets a container field on a node with text or shape content",
2296
+ rootItemField: "sets a size, margin, position, or item field on the root",
2297
+ gridFieldOnFlex: (field) => `sets ${field}, a grid container field, without display grid`,
2298
+ flexFieldOnGrid: (field) => `sets ${field}, a flex container field, on a grid container`,
2299
+ flexItemFieldInGrid: (field) => `sets ${field}, a flex item field, in a grid container`,
2300
+ gridItemFieldInFlex: (field) => `sets ${field}, a grid item field, in a flex container`,
2301
+ tooManyTracks: "has more than 64 tracks",
2302
+ repeatCount: "repeats tracks a number of times outside 1 to 64",
2303
+ repeatInAutoTracks: "uses repeat() in implicit track sizes",
2304
+ autoRepeatNeedsFixedTracks: "repeats auto-fill or auto-fit beside another, or with a track without a fixed size",
2305
+ gridLineOutOfRange: "names a grid line outside -65 to 65 or line 0, or a span outside 1 to 64",
2306
+ invalidKeyframes: "has invalid keyframes",
2307
+ outOfRange: "has a value out of range",
2308
+ lengthKeyframesDiffer: "has size keyframes that differ in kind",
2309
+ paintKeyframesDiffer: "has paint keyframes that differ in kind or stops",
2310
+ textKeyframesInterpolate: "has text keyframes that do not hold",
2311
+ };
2312
+ /**
2313
+ * A generator's layout problem, if it is a layout generator with one; pixel font sizes are held
2314
+ * to the limit on `canvas` when it is known.
2315
+ */
2316
+ function generatorLayoutIssue(generator, canvas) {
2317
+ return isRecord(generator) && generator.type === "layout"
2318
+ ? layoutIssue(generator.root, canvas)
2319
+ : undefined;
2320
+ }
2321
+ /** `issue` as a problem of `owner`, worded as the engine words it. */
2322
+ function layoutProblem(owner, issue) {
2323
+ return issue.shape === true
2324
+ ? shapeProblem(owner, issue)
2325
+ : `${owner} has an invalid layout: ${issue.at} ${issue.problem}`;
2326
+ }
2327
+ const LAYOUT_FLEX_CONTAINER_FIELDS = ["flex_direction", "flex_wrap"];
2328
+ const LAYOUT_GRID_CONTAINER_FIELDS = [
2329
+ "grid_template_columns",
2330
+ "grid_template_rows",
2331
+ "grid_auto_columns",
2332
+ "grid_auto_rows",
2333
+ "grid_auto_flow",
2334
+ "justify_items",
2335
+ ];
2336
+ const LAYOUT_CONTAINER_FIELDS = [
2337
+ ...LAYOUT_FLEX_CONTAINER_FIELDS,
2338
+ ...LAYOUT_GRID_CONTAINER_FIELDS,
2339
+ "gap",
2340
+ "row_gap",
2341
+ "column_gap",
2342
+ "justify_content",
2343
+ "align_items",
2344
+ "align_content",
2345
+ ];
2346
+ const LAYOUT_FLEX_ITEM_FIELDS = [
2347
+ "flex_grow",
2348
+ "flex_shrink",
2349
+ "flex_basis",
2350
+ ];
2351
+ const LAYOUT_GRID_ITEM_FIELDS = [
2352
+ "grid_column",
2353
+ "grid_row",
2354
+ "justify_self",
2355
+ ];
2356
+ const LAYOUT_ITEM_FIELDS = [
2357
+ "width",
2358
+ "height",
2359
+ "min_width",
2360
+ "min_height",
2361
+ "max_width",
2362
+ "max_height",
2363
+ "aspect_ratio",
2364
+ "margin",
2365
+ ...LAYOUT_FLEX_ITEM_FIELDS,
2366
+ ...LAYOUT_GRID_ITEM_FIELDS,
2367
+ "align_self",
2368
+ "position",
2369
+ "inset",
2370
+ ];
2371
+ const LAYOUT_SIZE_FIELDS = [
2372
+ "width",
2373
+ "height",
2374
+ "min_width",
2375
+ "min_height",
2376
+ "max_width",
2377
+ "max_height",
2378
+ ];
2379
+ const LAYOUT_VISUAL_FIELDS = [
2380
+ "opacity",
2381
+ "translate",
2382
+ "scale",
2383
+ "rotation_degrees",
2384
+ ];
2385
+ /** Whether an optional field is present: the model reads `null` as absent. */
2386
+ function present(value) {
2387
+ return value !== undefined && value !== null;
2388
+ }
2389
+ /** The first of `fields` present on `node`. */
2390
+ function firstPresent(node, fields) {
2391
+ return fields.find((field) => present(node[field]));
2392
+ }
2393
+ /** A length as the shape walk reads it ({@link readLayoutLength}). */
2394
+ function lengthOf(value) {
2395
+ return isRecord(value) && typeof value.unit === "string"
2396
+ ? value
2397
+ : undefined;
2398
+ }
2399
+ /**
2400
+ * Mirrors `validate_layout`: the first problem of a layout tree in preorder, as the shape walk
2401
+ * reads it. Its limits ({@link MAX_LAYOUT_NODES} nodes, {@link MAX_LAYOUT_DEPTH} deep,
2402
+ * {@link MAX_LAYOUT_TEXTS} texts, {@link MAX_LAYOUT_ISOLATED} isolated nodes,
2403
+ * {@link MAX_SHAPE_ITEMS} shape items over every shape node), its structure, which fields apply
2404
+ * where, every value's range, and keyframes alike in kind. With `canvas`, a pixel font size is
2405
+ * held to the largest a layout's text may be.
2406
+ */
2407
+ function layoutIssue(root, canvas) {
2408
+ const node = isRecord(root) ? root : {};
2409
+ if (LAYOUT_ITEM_FIELDS.some((field) => present(node[field]))) {
2410
+ return { at: "root", problem: LAYOUT_PROBLEM.rootItemField };
2411
+ }
2412
+ const counts = { nodes: 0, texts: 0, isolated: 0, shapes: { count: 0 } };
2413
+ const shorterSide = canvas === undefined ? undefined : Math.min(canvas[0], canvas[1]);
2414
+ return layoutNodeIssue(root, "root", 1, counts, {
2415
+ shorterSide,
2416
+ parent: undefined,
2417
+ });
2418
+ }
2419
+ function layoutNodeIssue(value, at, depth, counts, context) {
2420
+ const issue = (problem) => ({ at, problem });
2421
+ const node = isRecord(value) ? value : {};
2422
+ counts.nodes += 1;
2423
+ if (counts.nodes > MAX_LAYOUT_NODES)
2424
+ return issue(LAYOUT_PROBLEM.tooManyNodes);
2425
+ if (depth > MAX_LAYOUT_DEPTH)
2426
+ return issue(LAYOUT_PROBLEM.tooDeep);
2427
+ const children = Array.isArray(node.children)
2428
+ ? node.children
2429
+ : [];
2430
+ const text = present(node.text);
2431
+ const shape = present(node.shape);
2432
+ if (Number(children.length > 0) + Number(text) + Number(shape) > 1) {
2433
+ return issue(LAYOUT_PROBLEM.mixedContent);
2434
+ }
2435
+ if ((text || shape) && present(node.display)) {
2436
+ return issue(LAYOUT_PROBLEM.displayOnLeaf);
2437
+ }
2438
+ if ((text || shape) &&
2439
+ LAYOUT_CONTAINER_FIELDS.some((field) => present(node[field]))) {
2440
+ return issue(LAYOUT_PROBLEM.containerFieldOnLeaf);
2441
+ }
2442
+ const display = node.display === "grid" ? "grid" : "flex";
2443
+ const mismatch = display === "flex"
2444
+ ? firstPresent(node, LAYOUT_GRID_CONTAINER_FIELDS)
2445
+ : firstPresent(node, LAYOUT_FLEX_CONTAINER_FIELDS);
2446
+ if (mismatch !== undefined) {
2447
+ return issue(display === "flex"
2448
+ ? LAYOUT_PROBLEM.gridFieldOnFlex(mismatch)
2449
+ : LAYOUT_PROBLEM.flexFieldOnGrid(mismatch));
2450
+ }
2451
+ if (context.parent === "flex") {
2452
+ const field = firstPresent(node, LAYOUT_GRID_ITEM_FIELDS);
2453
+ if (field !== undefined)
2454
+ return issue(LAYOUT_PROBLEM.gridItemFieldInFlex(field));
2455
+ }
2456
+ else if (context.parent === "grid") {
2457
+ const field = firstPresent(node, LAYOUT_FLEX_ITEM_FIELDS);
2458
+ if (field !== undefined)
2459
+ return issue(LAYOUT_PROBLEM.flexItemFieldInGrid(field));
2460
+ }
2461
+ if (text) {
2462
+ counts.texts += 1;
2463
+ if (counts.texts > MAX_LAYOUT_TEXTS)
2464
+ return issue(LAYOUT_PROBLEM.tooManyTexts);
2465
+ }
2466
+ if (LAYOUT_VISUAL_FIELDS.some((field) => present(node[field])) ||
2467
+ node.overflow === "hidden") {
2468
+ counts.isolated += 1;
2469
+ if (counts.isolated > MAX_LAYOUT_ISOLATED) {
2470
+ return issue(LAYOUT_PROBLEM.tooManyIsolated);
2471
+ }
2472
+ }
2473
+ const fields = layoutFieldsIssue(node, at) ??
2474
+ layoutGridIssue(node, at) ??
2475
+ layoutStyleIssue(node, at, context.shorterSide);
2476
+ if (fields)
2477
+ return fields;
2478
+ if (text) {
2479
+ const textIssue = layoutTextIssue(node.text, `${at}.text`);
2480
+ if (textIssue)
2481
+ return textIssue;
2482
+ }
2483
+ if (shape) {
2484
+ const items = isRecord(node.shape) ? node.shape.items : undefined;
2485
+ const shapeIssue = shapeGroupIssue(items, `${at}.shape.items`, 1, counts.shapes);
2486
+ if (shapeIssue)
2487
+ return { ...shapeIssue, shape: true };
2488
+ }
2489
+ for (const [index, child] of children.entries()) {
2490
+ const childIssue = layoutNodeIssue(child, `${at}.children[${index}]`, depth + 1, counts, { shorterSide: context.shorterSide, parent: display });
2491
+ if (childIssue)
2492
+ return childIssue;
2493
+ }
2494
+ return undefined;
2495
+ }
2496
+ /** An animated value's problem, as `checks::animated` finds it: keyframes, then values. */
2497
+ function layoutAnimatedIssue(animation, at, check) {
2498
+ if (!present(animation))
2499
+ return undefined;
2500
+ const values = animationValues(animation);
2501
+ if (values === undefined)
2502
+ return { at, problem: LAYOUT_PROBLEM.invalidKeyframes };
2503
+ return values.every(check)
2504
+ ? undefined
2505
+ : { at, problem: LAYOUT_PROBLEM.outOfRange };
2506
+ }
2507
+ function layoutScalarIssue(animation, at, check) {
2508
+ return layoutAnimatedIssue(animation, at, (value) => finiteNumber(value) && check(value));
2509
+ }
2510
+ /** A size that may not be a percent: each value's number. */
2511
+ function layoutSizeIssue(animation, at, check) {
2512
+ return layoutAnimatedIssue(animation, at, (value) => {
2513
+ const length = lengthOf(value);
2514
+ return (length !== undefined && finiteNumber(length.value) && check(length.value));
2515
+ });
2516
+ }
2517
+ function layoutInsetsIssue(animation, at, check) {
2518
+ return layoutAnimatedIssue(animation, at, (value) => isRecord(value) &&
2519
+ ["top", "right", "bottom", "left"].every((side) => {
2520
+ const length = lengthOf(value[side]);
2521
+ return (length !== undefined &&
2522
+ finiteNumber(length.value) &&
2523
+ check(length.value));
2524
+ }));
2525
+ }
2526
+ /** A size or inset: its values, then its keyframes one kind (a percent, or a length). */
2527
+ function layoutLengthIssue(animation, at, check) {
2528
+ const issue = layoutSizeIssue(animation, at, check);
2529
+ if (issue || !present(animation))
2530
+ return issue;
2531
+ const kinds = new Set((animationValues(animation) ?? []).map((value) => lengthOf(value)?.unit === "percent"));
2532
+ return kinds.size > 1
2533
+ ? { at, problem: LAYOUT_PROBLEM.lengthKeyframesDiffer }
2534
+ : undefined;
2535
+ }
2536
+ function layoutPaintIssue(animation, at) {
2537
+ if (!present(animation))
2538
+ return undefined;
2539
+ const issue = animatedPaintIssue(animation, at);
2540
+ if (issue === undefined)
2541
+ return undefined;
2542
+ const problem = issue.problem === SHAPE_PROBLEM.invalidKeyframes
2543
+ ? LAYOUT_PROBLEM.invalidKeyframes
2544
+ : issue.problem === SHAPE_PROBLEM.paintKeyframesDiffer
2545
+ ? LAYOUT_PROBLEM.paintKeyframesDiffer
2546
+ : LAYOUT_PROBLEM.outOfRange;
2547
+ return { at: issue.at, problem };
2548
+ }
2549
+ /** Mirrors `layout::validate_fields`, field by field in the same order. */
2550
+ function layoutFieldsIssue(node, at) {
2551
+ const field = (name) => `${at}.${name}`;
2552
+ const border = isRecord(node.border) ? node.border : undefined;
2553
+ for (const name of ["gap", "row_gap", "column_gap"]) {
2554
+ const issue = layoutSizeIssue(node[name], field(name), nonNegativeValue);
2555
+ if (issue)
2556
+ return issue;
2557
+ }
2558
+ const first = layoutInsetsIssue(node.padding, field("padding"), nonNegativeValue) ??
2559
+ layoutPaintIssue(node.background, field("background")) ??
2560
+ (border
2561
+ ? (layoutSizeIssue(border.width, field("border.width"), nonNegativeValue) ?? layoutPaintIssue(border.paint, field("border.paint")))
2562
+ : undefined) ??
2563
+ layoutSizeIssue(node.border_radius, field("border_radius"), nonNegativeValue);
2564
+ if (first)
2565
+ return first;
2566
+ for (const name of LAYOUT_SIZE_FIELDS) {
2567
+ const issue = layoutLengthIssue(node[name], field(name), nonNegativeValue);
2568
+ if (issue)
2569
+ return issue;
2570
+ }
2571
+ if (present(node.aspect_ratio) &&
2572
+ !(finiteNumber(node.aspect_ratio) && node.aspect_ratio > 0)) {
2573
+ return { at: field("aspect_ratio"), problem: LAYOUT_PROBLEM.outOfRange };
2574
+ }
2575
+ const item = layoutInsetsIssue(node.margin, field("margin"), anyValue) ??
2576
+ layoutScalarIssue(node.flex_grow, field("flex_grow"), nonNegativeValue) ??
2577
+ layoutScalarIssue(node.flex_shrink, field("flex_shrink"), nonNegativeValue) ??
2578
+ layoutLengthIssue(node.flex_basis, field("flex_basis"), nonNegativeValue);
2579
+ if (item)
2580
+ return item;
2581
+ if (isRecord(node.inset)) {
2582
+ for (const side of ["left", "top", "right", "bottom"]) {
2583
+ const issue = layoutLengthIssue(node.inset[side], field(`inset.${side}`), anyValue);
2584
+ if (issue)
2585
+ return issue;
2586
+ }
2587
+ }
2588
+ return (layoutScalarIssue(node.opacity, field("opacity"), unitValue) ??
2589
+ layoutAnimatedIssue(node.translate, field("translate"), (value) => isRecord(value) &&
2590
+ finiteNumber(lengthOf(value.x)?.value) &&
2591
+ finiteNumber(lengthOf(value.y)?.value)) ??
2592
+ layoutAnimatedIssue(node.scale, field("scale"), validVec2) ??
2593
+ layoutScalarIssue(node.rotation_degrees, field("rotation_degrees"), anyValue));
2594
+ }
2595
+ /** A track size's lengths and `fr` share, as the shape walk reads it. */
2596
+ function trackParts(size) {
2597
+ const breadths = size.kind === "breadth"
2598
+ ? [size.breadth]
2599
+ : size.kind === "minmax"
2600
+ ? [size.min, size.max]
2601
+ : [];
2602
+ const lengths = breadths.flatMap((breadth) => breadth.kind === "length" ? [breadth.length] : []);
2603
+ if (size.kind === "fit-content")
2604
+ lengths.push(size.limit);
2605
+ const last = breadths.at(-1);
2606
+ return { lengths, share: last?.kind === "fr" ? last.share : undefined };
2607
+ }
2608
+ /** Mirrors `TrackSize::is_fixed`: what `auto-fill` and `auto-fit` repeat. */
2609
+ function fixedTrack(size) {
2610
+ const fixed = (breadth) => breadth.kind === "length";
2611
+ if (size.kind === "breadth")
2612
+ return fixed(size.breadth);
2613
+ if (size.kind === "minmax")
2614
+ return fixed(size.min) || (fixed(size.max) && size.min.kind !== "fr");
2615
+ return false;
2616
+ }
2617
+ /** Mirrors `layout::track_problem`. */
2618
+ function trackProblem(tracks, explicit) {
2619
+ const sizes = tracks.flatMap((component) => component.kind === "single" ? [component.size] : component.tracks);
2620
+ const parts = sizes.map(trackParts);
2621
+ if (!parts.every(({ lengths, share }) => lengths.every((length) => Number.isFinite(length.value) && length.value >= 0) &&
2622
+ (share === undefined || (Number.isFinite(share) && share > 0)))) {
2623
+ return LAYOUT_PROBLEM.outOfRange;
2624
+ }
2625
+ const repeats = tracks.flatMap((component) => component.kind === "repeat" ? [component.count] : []);
2626
+ if (!explicit && repeats.length > 0)
2627
+ return LAYOUT_PROBLEM.repeatInAutoTracks;
2628
+ if (repeats.some((count) => typeof count === "number" && (count < 1 || count > 64)))
2629
+ return LAYOUT_PROBLEM.repeatCount;
2630
+ const count = tracks.reduce((total, component) => total +
2631
+ (component.kind === "single"
2632
+ ? 1
2633
+ : (typeof component.count === "number" ? component.count : 1) *
2634
+ component.tracks.length), 0);
2635
+ if (count > MAX_GRID_TRACKS)
2636
+ return LAYOUT_PROBLEM.tooManyTracks;
2637
+ const automatic = repeats.filter((count) => typeof count !== "number").length;
2638
+ if (automatic > 1 || (automatic === 1 && !sizes.every(fixedTrack)))
2639
+ return LAYOUT_PROBLEM.autoRepeatNeedsFixedTracks;
2640
+ return undefined;
2641
+ }
2642
+ /** Mirrors `layout::validate_grid`. */
2643
+ function layoutGridIssue(node, at) {
2644
+ for (const [name, explicit] of [
2645
+ ["grid_template_columns", true],
2646
+ ["grid_template_rows", true],
2647
+ ["grid_auto_columns", false],
2648
+ ["grid_auto_rows", false],
2649
+ ]) {
2650
+ const tracks = node[name];
2651
+ if (!Array.isArray(tracks))
2652
+ continue;
2653
+ const problem = trackProblem(tracks, explicit);
2654
+ if (problem)
2655
+ return { at: `${at}.${name}`, problem };
2656
+ }
2657
+ for (const name of ["grid_column", "grid_row"]) {
2658
+ const placement = node[name];
2659
+ if (!isRecord(placement))
2660
+ continue;
2661
+ const inRange = (edge) => edge.kind === "auto" ||
2662
+ (edge.kind === "line"
2663
+ ? edge.line !== 0 && Math.abs(edge.line) <= 65
2664
+ : edge.count >= 1 && edge.count <= 64);
2665
+ if (![placement.start, placement.end].every((edge) => inRange(edge))) {
2666
+ return {
2667
+ at: `${at}.${name}`,
2668
+ problem: LAYOUT_PROBLEM.gridLineOutOfRange,
2669
+ };
2670
+ }
2671
+ }
2672
+ return undefined;
2673
+ }
2674
+ /** Mirrors `layout::validate_style`: the text style a node writes, where it writes it. */
2675
+ function layoutStyleIssue(node, at, shorterSide) {
2676
+ const outOfRange = (name) => ({
2677
+ at: `${at}.${name}`,
2678
+ problem: LAYOUT_PROBLEM.outOfRange,
2679
+ });
2680
+ const family = node.font_family;
2681
+ if (present(family) &&
2682
+ !(typeof family === "string" &&
2683
+ family.length > 0 &&
2684
+ new TextEncoder().encode(family).length <= MAX_FONT_FAMILY_BYTES)) {
2685
+ return outOfRange("font_family");
2686
+ }
2687
+ const size = layoutAnimatedIssue(node.font_size, `${at}.font_size`, (value) => {
2688
+ const length = lengthOf(value);
2689
+ if (length === undefined ||
2690
+ !finiteNumber(length.value) ||
2691
+ length.value <= 0)
2692
+ return false;
2693
+ // Pixels compare with the limit on a known canvas only.
2694
+ const fraction = length.unit !== "px"
2695
+ ? length.value
2696
+ : shorterSide === undefined
2697
+ ? 0
2698
+ : Math.fround(length.value / shorterSide);
2699
+ return fraction <= MAX_LAYOUT_FONT_SIZE;
2700
+ });
2701
+ if (size)
2702
+ return size;
2703
+ if (present(node.color) && !validRgba(node.color)) {
2704
+ return outOfRange("color");
2705
+ }
2706
+ const lineHeight = node.line_height;
2707
+ if (present(lineHeight) &&
2708
+ !(finiteNumber(lineHeight) &&
2709
+ lineHeight >= MIN_LINE_HEIGHT &&
2710
+ lineHeight <= MAX_LINE_HEIGHT)) {
2711
+ return outOfRange("line_height");
2712
+ }
2713
+ const outline = node.outline;
2714
+ if (present(outline) &&
2715
+ !(isRecord(outline) &&
2716
+ validRgba(outline.color) &&
2717
+ finiteNumber(outline.width) &&
2718
+ outline.width > 0 &&
2719
+ outline.width <= MAX_TEXT_OUTLINE_WIDTH)) {
2720
+ return outOfRange("outline");
2721
+ }
2722
+ return undefined;
2723
+ }
2724
+ /** Mirrors `layout::validate_text`: a node's text content. */
2725
+ function layoutTextIssue(content, at) {
2726
+ const keyframes = layoutAnimatedIssue(content, at, () => true);
2727
+ if (keyframes)
2728
+ return keyframes;
2729
+ if (isRecord(content) &&
2730
+ content.mode === "keyframes" &&
2731
+ content.keyframes.some((keyframe) => !isRecord(keyframe) ||
2732
+ !isRecord(keyframe.interpolation) ||
2733
+ keyframe.interpolation.type !== "hold")) {
2734
+ return { at, problem: LAYOUT_PROBLEM.textKeyframesInterpolate };
2735
+ }
2736
+ return layoutAnimatedIssue(content, at, (value) => typeof value === "string" &&
2737
+ new TextEncoder().encode(value).length <= MAX_TEXT_CONTENT_BYTES);
2738
+ }
1904
2739
  /**
1905
2740
  * Mirrors `validate_shape_items`: the first problem of a content tree in document order. Its
1906
2741
  * limits ({@link MAX_SHAPE_ITEMS} items over every group, groups {@link MAX_SHAPE_DEPTH}
@@ -2396,7 +3231,7 @@ function frameNodesOver(tracks) {
2396
3231
  /**
2397
3232
  * A composition's node identities, settings, and connections, as the model checks them.
2398
3233
  */
2399
- function compositionProblems(composition, sources, effectResources, compositions, controlNamesOf) {
3234
+ function compositionProblems(composition, sources, effectResources, compositions, controlNamesOf, canvas) {
2400
3235
  if (!isRecord(composition))
2401
3236
  return ["each composition must be an object"];
2402
3237
  const id = text(composition.id);
@@ -2473,9 +3308,13 @@ function compositionProblems(composition, sources, effectResources, compositions
2473
3308
  }
2474
3309
  case "generator": {
2475
3310
  const issue = generatorShapeIssue(op.generator);
3311
+ const layout = generatorLayoutIssue(op.generator, canvas);
2476
3312
  if (issue) {
2477
3313
  problems.push(shapeProblem(`node ${nodeId} of composition ${id}`, issue));
2478
3314
  }
3315
+ else if (layout) {
3316
+ problems.push(layoutProblem(`node ${nodeId} of composition ${id}`, layout));
3317
+ }
2479
3318
  else if (!validGenerator(op.generator)) {
2480
3319
  invalid();
2481
3320
  }