@vectoriox/iox-ui 5.154.0 → 5.156.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.
@@ -6,7 +6,7 @@ import { patternLinkSlots, patternOptionalParts, patternSlots, SITE_PATTERNS } f
6
6
  import { withDerivedSources } from './plan-derived';
7
7
  import { DEFAULT_HEADER_PATTERN, HeaderIngredient, headerMeaning, headerMix, headerMixFromWords, headerMixOfPlan, headerMixWords, headerPatternIdOf, headerWireWords } from './header-mix';
8
8
  import { DEFAULT_FOOTER_PATTERN, FooterIngredient, footerMeaning, footerMix, footerMixFromWords, footerMixOfPlan, footerMixWords, footerPatternIdOf, footerWireWords, footerWords } from './footer-mix';
9
- import { OpeningIngredient, openingMeaning, openingWireWords, openingWordTier } from './opening-mix';
9
+ import { openingHarnessWord, OpeningIngredient, openingMeaning, openingWireWords, openingWordTier } from './opening-mix';
10
10
  import { BodyIngredient, bodyMeaning, bodyMix, bodyMixWords, bodyWireWords } from './body-mix';
11
11
  import { shopCategoriesOf } from './shop-plan';
12
12
  import { ContentFieldControl, FIELD_TYPE_OF_CONTROL,
@@ -118,7 +118,7 @@ const OPENING_WIRE_TEXT = "string[] — the home page's opening (its first scree
118
118
  + "section as written. The opening takes the place of the home page's first section when that is a hero (its words and pictures carried in); "
119
119
  + 'a word marked (award) is worn by an award build only — elsewhere it is mended. '
120
120
  + Object.values(OpeningIngredient).map(k => `${k}: ${openingWireWords(GenerationTier.Award).filter(w => w.startsWith(`${k}:`)).map(w => w.slice(k.length + 1))
121
- .map(w => `${w} (${openingMeaning(k, w)}${openingWordTier(k, w) === 'pro' ? ', award' : ''})`).join(' | ')}`).join('; ');
121
+ .map(w => `${w} (${openingMeaning(k, w)}${openingWordTier(k, w) === 'pro' ? ', award' : ''}${openingHarnessWord(k, w) ? ', the build\'s own — keep it where the plan has it, never choose it' : ''})`).join(' | ')}`).join('; ');
122
122
 
123
123
  /** The header's words as the model reads them (HI1): each ingredient, the words the product draws and their meanings,
124
124
  * from the contract's header table. */
@@ -51,6 +51,7 @@ export * from './stock-photos';
51
51
  export * from './film';
52
52
  export * from './art-direction';
53
53
  export * from './pictures';
54
+ export * from './type-led';
54
55
  export * from './layout-language';
55
56
  export * from './compose-layout';
56
57
  export * from './layout-look';
@@ -8983,7 +8983,8 @@ export const SPEC_SITE_LAYOUT = {
8983
8983
  "object",
8984
8984
  "diptych",
8985
8985
  "material",
8986
- "live"
8986
+ "live",
8987
+ "none"
8987
8988
  ],
8988
8989
  "words": [
8989
8990
  "headline",
@@ -9020,6 +9021,7 @@ export const SPEC_SITE_LAYOUT = {
9020
9021
  "media.diptych": "two full-height pictures side by side; a phone keeps the first",
9021
9022
  "media.material": "an ambient ground drawn from the look's tokens (a glow behind ribs, a dotted grid, a slow light)",
9022
9023
  "media.live": "a working form of the site's own in the first screen (a lead form, a booking)",
9024
+ "media.none": "no picture: the look's own ground, and the words carry the first screen",
9023
9025
  "words.headline": "a heading, a line and one action",
9024
9026
  "words.on-edge": "one display line at screen size sitting on the bottom edge, cropped by it",
9025
9027
  "words.apart": "two or three giant words placed apart across the screen",
@@ -9045,6 +9047,7 @@ export const SPEC_SITE_LAYOUT = {
9045
9047
  "media.diptych": "שתי תמונות בגובה מלא זו לצד זו; בטלפון נשארת הראשונה",
9046
9048
  "media.material": "רקע מהמראה של האתר (זוהר מאחורי פסים, רשת נקודות, אור איטי)",
9047
9049
  "media.live": "טופס אמיתי של האתר במסך הראשון (פנייה, הזמנה)",
9050
+ "media.none": "בלי תמונה: הרקע של המראה, והמילים נושאות את המסך הראשון",
9048
9051
  "words.headline": "כותרת, שורה ופעולה אחת",
9049
9052
  "words.on-edge": "שורה אחת בגודל המסך שיושבת על הקצה התחתון, חתוכה בו",
9050
9053
  "words.apart": "שתיים או שלוש מילים ענקיות, מפוזרות על המסך",
@@ -9079,6 +9082,48 @@ export const SPEC_SITE_LAYOUT = {
9079
9082
  "extras": [],
9080
9083
  "motion": []
9081
9084
  },
9085
+ "harness": [
9086
+ "media.none"
9087
+ ],
9088
+ "typeLed": [
9089
+ {
9090
+ "frame": "full",
9091
+ "words": "wordmark"
9092
+ },
9093
+ {
9094
+ "frame": "inset",
9095
+ "words": "headline"
9096
+ },
9097
+ {
9098
+ "frame": "full",
9099
+ "words": "on-edge"
9100
+ },
9101
+ {
9102
+ "frame": "shrinks",
9103
+ "words": "headline"
9104
+ },
9105
+ {
9106
+ "frame": "inset",
9107
+ "words": "wordmark"
9108
+ },
9109
+ {
9110
+ "frame": "full",
9111
+ "words": "apart"
9112
+ },
9113
+ {
9114
+ "frame": "inset",
9115
+ "words": "on-edge"
9116
+ },
9117
+ {
9118
+ "frame": "shrinks",
9119
+ "words": "wordmark"
9120
+ },
9121
+ {
9122
+ "frame": "full",
9123
+ "words": "headline"
9124
+ }
9125
+ ],
9126
+ "typeLedEveryTier": true,
9082
9127
  "named": {
9083
9128
  "hero.split": {},
9084
9129
  "hero.full-bleed-media": {
@@ -9214,6 +9259,7 @@ export const SPEC_SITE_LAYOUT = {
9214
9259
  "media.film": "all",
9215
9260
  "media.slideshow": "all",
9216
9261
  "media.object": "all",
9262
+ "media.none": "all",
9217
9263
  "words.headline": "all",
9218
9264
  "rules.wordsNeverCut": "all",
9219
9265
  "rules.badgeOwnersOnly": "all",
@@ -0,0 +1,435 @@
1
+ import { ComposedItem, ComposedPlaceholder, ComposedSite, openingContextOf, PlaceholderKind } from './compose-site';
2
+ import { FingerprintedPage, wornOpenings } from './layout-fingerprint';
3
+ import { LayoutIssue, LayoutIssueCode, LayoutLayerKind, LayoutPage, LayoutSection } from './layout-language';
4
+ import { fallBackBySection, SectionFallbackLastResort, SectionSwapAction } from './layout-section-fallback';
5
+ import {
6
+ checkOpening, drawnOpeningMix, OPENING_MIX_PROP, OpeningMedia, OpeningMix, OpeningMotion, openingMixOfPlan, openingMixWords, openingTokenOf, typeLedOpeningSection,
7
+ typeLedOpeningWays,
8
+ } from './opening-mix';
9
+ import type { GenerationTier } from './site-plan.model';
10
+ import { patternById, patternLinkSlots, patternOptionalParts, patternSlots, slotBudget } from './patterns';
11
+ import { SerializedNode, walkSerialized } from './serialized-node';
12
+ import { SHOP_ROLES } from './shop-plan';
13
+ import { ContentRole, PagePlan, PageSectionPlan, roleField, ShopResource, SitePlan } from './site-plan.model';
14
+
15
+ /**
16
+ * TYPE IS THE PICTURE (vectoriox/iox-ui#129, the J10 verdict's emptiness 2 · first impression 3). Every Home of the six
17
+ * stored sites opened on an empty picture box or an empty dark band: the composer stamped a PICTURE-LED section (a split
18
+ * hero, a story beside a photo, an opening on a photo or a film) where nothing — the owner's photo, a made picture, a
19
+ * stock photo — fills its picture. The award references' lesson is that type carries a first screen on its own.
20
+ *
21
+ * So, when the caller says which picture slots a picture fills (`PictureSupply`), a section whose picture stays empty is
22
+ * composed TYPE-LED instead: the same words in the library's type-led pattern for that place (`TYPE_LED_SWAPS` — every
23
+ * slot carried, never cut), an opening on a photo or film with nothing to show is left out (the page opens on its
24
+ * type-led hero), a model-laid section holding an empty photo is given to the plan's ready-made section for its place (the
25
+ * ONE fallback picker, `fallBackBySection`), and a list whose items have no picture at all shows its cards without the
26
+ * picture part. Nothing is dropped from a pattern page: plan indices, section ids and every other slot's node id stay as
27
+ * they were, so the caller's filled slots and its placements still name the same nodes.
28
+ *
29
+ * Pure: `composeSite` runs it when `ComposeContext.pictures` is given — absent, the plan composes exactly as it says.
30
+ * The plan the caller stores is never rewritten: the picture-led choice stays in it, so a later build or redesign that
31
+ * HAS pictures composes picture-led again (`TypeLed.plan` is what this composition wore, for a Re-fit to recompose).
32
+ */
33
+
34
+ /** What fills a composed site's pictures, as the caller knows it after placing them on the picture-led composition. */
35
+ export interface PictureSupply {
36
+ /** The picture slots a picture fills, by `pictureSlotKey` (`page:<owner>:<nodeId>`, `item:<type>:<i>:<field>`) — the
37
+ * owner's photos, the made pictures, the stock photos the build placed. Empty: no picture anywhere. */
38
+ filled: Iterable<string>;
39
+ /** The studio's memory (#119 C): the pages its sites already are, as the layout gate reads them (iox-cms's recent
40
+ * fingerprints). A type-led first screen opens a way no OTHER site of the studio opens (`wornOpenings`). */
41
+ studio?: ReadonlyArray<FingerprintedPage>;
42
+ }
43
+
44
+ /** One type-led place for a picture-led pattern: the pattern, and where each of the source's slots goes. */
45
+ export interface TypeLedTarget {
46
+ pattern: string;
47
+ /** source slot → target slot. Every slot of the source is carried (a spec proves it). */
48
+ slots: Readonly<Record<string, string>>;
49
+ }
50
+
51
+ /** The type-led patterns a picture-led one becomes, best first: the first whose budgets hold every carried word wins. */
52
+ export const TYPE_LED_SWAPS: Readonly<Record<string, ReadonlyArray<TypeLedTarget>>> = {
53
+ 'hero.split': [{ pattern: 'hero.centered', slots: { eyebrow: 'eyebrow', headline: 'headline', lead: 'lead', primary: 'primary', secondary: 'secondary' } }],
54
+ 'hero.stacked-editorial': [{ pattern: 'hero.centered', slots: { eyebrow: 'eyebrow', headline: 'headline', lead: 'lead', primary: 'primary' } }],
55
+ 'hero.full-bleed-media': [{ pattern: 'hero.centered', slots: { title: 'headline', lead: 'lead', cta: 'primary' } }],
56
+ 'hero.scene-depth': [{ pattern: 'hero.centered', slots: { headline: 'headline', lead: 'lead', cta: 'primary' } }],
57
+ 'hero.scene-object': [{ pattern: 'hero.centered', slots: { headline: 'headline', lead: 'lead', cta: 'primary' } }],
58
+ 'about.story': [{ pattern: 'story.long-form', slots: { title: 'title', story: 'body1' } }],
59
+ 'feature.alternating-rows': [{
60
+ pattern: 'feature.triad',
61
+ slots: { title: 'title', row1: 'item1', row1Text: 'item1Text', row2: 'item2', row2Text: 'item2Text', row3: 'item3', row3Text: 'item3Text' },
62
+ }],
63
+ 'story.scene-chapters': [{
64
+ pattern: 'feature.triad',
65
+ slots: { eyebrow: 'title', title: 'item1', text: 'item1Text', title2: 'item2', text2: 'item2Text', title3: 'item3', text3: 'item3Text' },
66
+ }],
67
+ };
68
+
69
+ /** Picture-led patterns kept as they are with an empty picture: their pictures are the owner's by nature (a row of the
70
+ * studio's own client logos) — no type-led section says what they say. A spec holds every static-picture pattern to
71
+ * one of the two lists. */
72
+ export const TYPE_LED_KEPT: ReadonlySet<string> = new Set(['proof.logo-strip']);
73
+
74
+ export enum TypeLedChangeKind {
75
+ /** A pattern section became its type-led pattern. */
76
+ Section = 'section',
77
+ /** The home page's first screen had no picture to show: it opens type-led (`media:none`), a way no other site of the
78
+ * studio opens — or, when its first section cannot give its words slot by slot, on that section (the mix left out). */
79
+ Opening = 'opening',
80
+ /** A model-laid section holding an empty photo was given to the plan's ready-made section. */
81
+ LayoutSection = 'layout-section',
82
+ /** A model-laid section holding an empty photo that no ready-made section fits keeps its words, its photos left out
83
+ * (it is never dropped: the owner's or the model's copy is content). */
84
+ LayoutWords = 'layout-words',
85
+ /** A model-laid page that could not give its empty photos away section by section is made from its plan sections. */
86
+ Layout = 'layout',
87
+ /** A list's items have no picture at all: its cards show no picture part. */
88
+ List = 'list',
89
+ }
90
+
91
+ export interface TypeLedChange {
92
+ kind: `${TypeLedChangeKind}`;
93
+ /** The page key (absent for a list). */
94
+ page?: string;
95
+ /** The section's place: the plan section's (Section), the model's section's (LayoutSection). */
96
+ at?: number;
97
+ from?: string;
98
+ to?: string;
99
+ /** The list's content type (List). */
100
+ contentType?: string;
101
+ /** In plain words, for the log and the run. */
102
+ said: string;
103
+ }
104
+
105
+ /** What the composition wore once its empty pictures were made type-led. */
106
+ /** How a type-led home opens, for the studio's memory (iox-cms records it as the home's fingerprint opening). */
107
+ export interface TypeLedOpening {
108
+ /** The mix's words, as `plan.mixes.opening` holds them. */
109
+ words: string[];
110
+ /** `opening:<frame>/none/<words>` — what the memory records and compares (`openingTokenOf`). */
111
+ token: string;
112
+ /** Set when every way the site can carry is already another site's: it opens on the first of them anyway. */
113
+ worn?: true;
114
+ }
115
+
116
+ export interface TypeLed {
117
+ /** The plan as composed (the stored plan is never rewritten). */
118
+ plan: SitePlan;
119
+ changes: TypeLedChange[];
120
+ /** Content types whose items show no picture (their cards are composed without one). */
121
+ pictureless: string[];
122
+ /** The home page's type-led first screen, when it opens on one. */
123
+ opening?: TypeLedOpening;
124
+ }
125
+
126
+ /** A picture placeholder (read at call time: the composer imports this module, so its enum is not ready at load). */
127
+ const isPictureKind = (kind: `${PlaceholderKind}`) => kind === PlaceholderKind.Image || kind === PlaceholderKind.Video;
128
+
129
+ /** A picture slot's key as `pictureSlotKey` makes it (kept here: pictures.ts imports the composer). */
130
+ const pageSlotKey = (owner: string, nodeId: string) => `page:${owner}:${nodeId}`;
131
+ const itemSlotKey = (type: string, index: number, field: string) => `item:${type}:${index}:${field}`;
132
+
133
+ /** The empty pictures nothing fills: an image placeholder no filled slot names, every video placeholder (a clip is the
134
+ * studio's own, never stock). Only a page's — a global's are its own concern. */
135
+ export function emptyPictures(composed: Pick<ComposedSite, 'pages' | 'placeholders'>, filled: ReadonlySet<string>): ComposedPlaceholder[] {
136
+ const pages = new Set(composed.pages.map(p => p.key));
137
+ return composed.placeholders.filter(p => isPictureKind(p.kind) && pages.has(p.owner)
138
+ && !(p.kind === PlaceholderKind.Image && filled.has(pageSlotKey(p.owner, p.nodeId))));
139
+ }
140
+
141
+ /** The content types whose items would show no picture: every item's picture empty and none filled (a type with no items
142
+ * yet keeps its picture — the owner's first items bring theirs). The shop's products read as their resource's name. */
143
+ export function picturelessTypes(plan: Pick<SitePlan, 'contentTypes'>, composed: Pick<ComposedSite, 'items' | 'shop'>, filled: ReadonlySet<string>): string[] {
144
+ const out: string[] = [];
145
+ const judge = (type: string, field: string | undefined, items: ReadonlyArray<Record<string, unknown>>) => {
146
+ if (!field || !items.length) return;
147
+ if (items.every((item, i) => !item[field] && !filled.has(itemSlotKey(type, i, field)))) out.push(type);
148
+ };
149
+ judge(ShopResource.Products, SHOP_ROLES[ShopResource.Products].image, (composed.shop?.products ?? []) as unknown as ReadonlyArray<Record<string, unknown>>);
150
+ for (const type of plan.contentTypes) judge(type.name, roleField(type, ContentRole.Image), (composed.items[type.name] ?? []) as ReadonlyArray<ComposedItem>);
151
+ return out;
152
+ }
153
+
154
+ /** The type-led place for a section, or null: no swap names its pattern, or no target's budgets hold its words. */
155
+ export function typeLedSection(section: PageSectionPlan, density: string | null): { section: PageSectionPlan; to: string } | null {
156
+ for (const target of TYPE_LED_SWAPS[section.pattern] ?? []) {
157
+ const pattern = patternById(target.pattern);
158
+ if (!pattern) continue;
159
+ const declared = new Set(patternSlots(pattern));
160
+ const slots: Record<string, string> = {};
161
+ let fits = true;
162
+ for (const [slot, value] of Object.entries(section.slots ?? {})) {
163
+ const to = target.slots[slot];
164
+ const budget = to ? slotBudget(pattern, to, density) : null;
165
+ if (!to || !declared.has(to) || (budget !== null && value.length > budget)) { fits = false; break; }
166
+ slots[to] = value;
167
+ }
168
+ if (!fits) continue;
169
+ const linkSlots = new Set(patternLinkSlots(pattern));
170
+ const links = Object.fromEntries(Object.entries(section.links ?? {}).map(([slot, route]) => [target.slots[slot], route] as const).filter(([slot]) => !!slot && linkSlots.has(slot)));
171
+ const parts = new Set(patternOptionalParts(pattern));
172
+ const without = (section.without ?? []).filter(w => parts.has(w));
173
+ const next: PageSectionPlan = {
174
+ pattern: target.pattern,
175
+ ...(Object.keys(slots).length ? { slots } : {}),
176
+ ...(Object.keys(links).length ? { links } : {}),
177
+ ...(without.length ? { without } : {}),
178
+ ...(section.enter ? { enter: section.enter } : {}),
179
+ };
180
+ return { section: next, to: target.pattern };
181
+ }
182
+ return null;
183
+ }
184
+
185
+ /** Which root of a composed page a node is in, and what that root is: the opening, a model-laid section, a plan
186
+ * section's pattern (a pattern page's section, or a ready-made place on a model-laid page). */
187
+ interface RootOf {
188
+ /** The root's place on the page (0: the first screen). */
189
+ pos: number;
190
+ opening: boolean;
191
+ /** The model-laid section's index (`page.layout.sections`), -1 when the root is not one the model laid. */
192
+ laid: number;
193
+ /** The plan section whose pattern the root is (`page.sections`), -1 when none. */
194
+ planAt: number;
195
+ }
196
+
197
+ function rootsOf(page: PagePlan, layout: ReadonlyArray<SerializedNode>): Map<string, RootOf> {
198
+ const out = new Map<string, RootOf>();
199
+ const sections = page.layout?.sections ?? [];
200
+ // A model-laid page keeps one root per layout section, in order (an opening it could not replace stands first).
201
+ const offset = page.layout ? Math.max(0, layout.length - sections.length) : 0;
202
+ const whereOf = (root: SerializedNode, pos: number): RootOf => {
203
+ const opening = typeof root.props?.[OPENING_MIX_PROP] === 'string';
204
+ if (!page.layout) {
205
+ const m = /-(\d+)$/.exec(root.id);
206
+ return { pos, opening, laid: -1, planAt: m && root.id === `${page.key}-${m[1]}` ? Number(m[1]) : -1 };
207
+ }
208
+ // Its stamp names its layout section (M2-1); a ready-made place is stamped with its plan section's pattern.
209
+ if (root.composed?.layout) return { pos, opening, laid: sections.findIndex(s => s.id === root.composed!.layout), planAt: -1 };
210
+ const readyMade = sections[pos - offset]?.readyMade;
211
+ return { pos, opening, laid: -1, planAt: readyMade ? readyMade.at : -1 };
212
+ };
213
+ layout.forEach((root, pos) => {
214
+ const where = whereOf(root, pos);
215
+ walkSerialized([root], n => { out.set(n.id, where); });
216
+ });
217
+ return out;
218
+ }
219
+
220
+ /** The layer a composed layout node belongs to (`<page>-s<section>-l<layer>…`), or null. */
221
+ function layerOf(nodeId: string): { section: number; layer: number } | null {
222
+ const m = /-s(\d+)-l(\d+)(?:-|$)/.exec(nodeId);
223
+ return m ? { section: Number(m[1]), layer: Number(m[2]) } : null;
224
+ }
225
+
226
+ /** The layers that hold words (what a section must keep when its photos go). */
227
+ const WORD_LAYERS: ReadonlySet<string> = new Set([
228
+ LayoutLayerKind.Word, LayoutLayerKind.Heading, LayoutLayerKind.Text, LayoutLayerKind.Label, LayoutLayerKind.Number,
229
+ LayoutLayerKind.Button, LayoutLayerKind.List, LayoutLayerKind.Form, LayoutLayerKind.Marquee,
230
+ ]);
231
+ const GRID_COLUMNS = 12;
232
+ /** The widest the words of a section whose photos went may grow to (columns): a reading measure, never the full grid. */
233
+ const WORDS_MEASURE = 10;
234
+ const BOX_PHOTO = 'photo:box:';
235
+ const PLAIN_GROUND = 'ground';
236
+
237
+ /**
238
+ * A model-laid section with its empty photos left out — its words kept where the model put them, given the width the
239
+ * photos held beside them (centred, at most a reading measure) and the rows they held under them (empty rows close up,
240
+ * the section's height following unless it is pinned). Null when it says nothing without its photos. Pure.
241
+ */
242
+ export function typeLedLayoutSection(section: LayoutSection, gone: ReadonlySet<number>): LayoutSection | null {
243
+ const kept = section.layers.map((layer, i) => ({ layer, i })).filter(x => !gone.has(x.i));
244
+ if (!kept.some(x => WORD_LAYERS.has(x.layer.kind))) return null;
245
+ const index = new Map(kept.map((x, n) => [x.i, n] as const));
246
+ const photos = [...gone].map(i => section.layers[i]).filter(Boolean);
247
+ const words = kept.filter(x => x.layer.kind !== LayoutLayerKind.Shape).map(x => x.layer);
248
+ const from = Math.min(...words.map(l => l.col[0]));
249
+ const to = Math.max(...words.map(l => l.col[1]));
250
+ const beside = photos.length > 0 && photos.every(p => p.col[0] >= to || p.col[1] <= from);
251
+ const width = Math.max(1, to - from);
252
+ const grown = beside ? Math.min(WORDS_MEASURE, GRID_COLUMNS, width + Math.max(...photos.map(p => p.col[1] - p.col[0]))) : width;
253
+ const start = beside ? 1 + Math.floor((GRID_COLUMNS - grown) / 2) : from;
254
+ const col = (c: number): number => (beside ? start + Math.round(((c - from) * grown) / width) : c);
255
+ const used = new Set<number>();
256
+ for (const { layer } of kept) for (let r = layer.row[0]; r < layer.row[1]; r++) used.add(r);
257
+ const line = (r: number): number => 1 + [...used].filter(u => u < r).length;
258
+ const rows = used.size;
259
+ const layers = kept.map(({ layer }) => {
260
+ const c0 = col(layer.col[0]);
261
+ return { ...layer, col: [c0, Math.max(c0 + 1, col(layer.col[1]))] as [number, number], row: [line(layer.row[0]), line(layer.row[1])] as [number, number] };
262
+ });
263
+ const screens = section.pin ? section.screens : Math.max(1, Math.round((section.screens * rows) / Math.max(1, section.rows)));
264
+ const ground = section.ground?.startsWith(BOX_PHOTO) ? PLAIN_GROUND : section.ground;
265
+ const { phone, ...rest } = section;
266
+ const order = phone?.filter(i => index.has(i)).map(i => index.get(i)!);
267
+ return { ...rest, ...(ground !== undefined ? { ground } : {}), screens, rows, layers, ...(order?.length ? { phone: order } : {}) };
268
+ }
269
+
270
+ const SAID_LAYOUT = 'holds a photo nothing fills';
271
+ /** A model-laid page that would lose more than a third of its sections to empty photos is made from its plan sections
272
+ * instead: a page of three survivors is thinner than the plan's own page (its type-led sections). Only a section that
273
+ * says nothing without its photos is lost now. */
274
+ const THIN_SHARE = 3;
275
+ const keepAsLaid = (page: LayoutPage) => ({ page, issues: [] as LayoutIssue[] });
276
+
277
+ /** What a type-led round needs of the build beyond the plan: its tier and the studio's memory. */
278
+ export interface TypeLedRoundContext {
279
+ tier?: `${GenerationTier}`;
280
+ studio?: ReadonlyArray<FingerprintedPage>;
281
+ }
282
+
283
+ /** The tier a build is at when none is said (GenerationTier.Basic — a value import of site-plan.model here reorders the
284
+ * generation-core load). */
285
+ const BASIC = 'basic' as `${GenerationTier}`;
286
+
287
+ const isHome = (page: PagePlan) => page.isHome === true || page.route === '/';
288
+
289
+ /**
290
+ * The type-led first screen for a home page: the plan's own frame and words first, then the contract's ways
291
+ * (`typeLedOpeningWays`), the first the site carries unmended (its tier, the business name's fit) that no OTHER site of
292
+ * the studio opens on — else the first it carries, said as worn. Pure.
293
+ */
294
+ export function chooseTypeLedOpening(plan: SitePlan, context: TypeLedRoundContext = {}): { mix: OpeningMix; token: string; worn: boolean } {
295
+ const own = openingMixOfPlan(plan);
296
+ // The plan's own frame and words, on no picture (a slow zoom has nothing to move: it goes with the picture).
297
+ const mine = own ? [{ ...own, media: OpeningMedia.None, extras: [...own.extras], motion: own.motion.filter(m => m !== OpeningMotion.SlowZoom) }] : [];
298
+ const ways = [...mine, ...typeLedOpeningWays()];
299
+ const site = openingContextOf({ business: plan.business, design: plan.design, tier: context.tier ?? BASIC, badge: null, cutOut: false });
300
+ const carried = ways.map(m => drawnOpeningMix(m).drawn).filter(m => !checkOpening(m, site).repairs.length);
301
+ const worn = wornOpenings(context.studio ?? []);
302
+ const free = carried.find(m => !worn.has(openingTokenOf(m)));
303
+ // The contract's last way is every tier's and fits any name (a heading): there is always one.
304
+ const mix = free ?? carried[0] ?? checkOpening(ways[ways.length - 1], site).mix;
305
+ return { mix, token: openingTokenOf(mix), worn: !free };
306
+ }
307
+
308
+ /**
309
+ * One round: the plan a composition should have been composed from, given what fills its pictures — or no changes. The
310
+ * caller composes again and asks once more (an opening left out shows the first section's own picture, judged next).
311
+ */
312
+ export function typeLedRound(
313
+ plan: SitePlan, composed: Pick<ComposedSite, 'pages' | 'placeholders' | 'items' | 'shop'>, filled: ReadonlySet<string>, context: TypeLedRoundContext = {},
314
+ ): { plan: SitePlan; changes: TypeLedChange[]; pictureless: string[]; opening?: TypeLedOpening } {
315
+ const changes: TypeLedChange[] = [];
316
+ const empty = emptyPictures(composed, filled);
317
+ const density = typeof plan.design?.density === 'string' ? plan.design.density : null;
318
+ let firstScreen: PagePlan | null = null;
319
+ let homeAt = -1;
320
+ const swapSection = (page: PagePlan, sections: PageSectionPlan[], i: number): boolean => {
321
+ const section = sections[i];
322
+ if (!section || TYPE_LED_KEPT.has(section.pattern)) return false;
323
+ const led = typeLedSection(section, density);
324
+ if (!led) return false;
325
+ sections[i] = led.section;
326
+ changes.push({ kind: TypeLedChangeKind.Section, page: page.key, at: i, from: section.pattern, to: led.to, said: `${page.name}: ${section.pattern} has no picture — ${led.to} says its words` });
327
+ return true;
328
+ };
329
+ const pages = plan.pages.map((page, p) => {
330
+ const made = composed.pages.find(c => c.key === page.key) ?? composed.pages[p];
331
+ const mine = empty.filter(e => e.owner === page.key);
332
+ if (!made || !mine.length) return page;
333
+ const roots = rootsOf(page, made.layout);
334
+ const laid = new Map<number, Set<number>>();
335
+ const planAt = new Set<number>();
336
+ let first = false;
337
+ for (const e of mine) {
338
+ const where = roots.get(e.nodeId);
339
+ if (!where) continue;
340
+ if (where.pos === 0 && isHome(page)) first = true;
341
+ if (where.opening) continue;
342
+ if (where.laid >= 0) {
343
+ const at = layerOf(e.nodeId);
344
+ const layers = laid.get(where.laid) ?? new Set<number>();
345
+ if (at && at.section === where.laid) layers.add(at.layer);
346
+ laid.set(where.laid, layers);
347
+ } else if (where.planAt >= 0) planAt.add(where.planAt);
348
+ }
349
+ let next: PagePlan = page;
350
+ // A plan section's pattern (a pattern page's, a ready-made place's) whose picture nothing fills: its type-led pattern.
351
+ let sections: PageSectionPlan[] | null = null;
352
+ for (const i of [...planAt].sort((a, b) => a - b)) {
353
+ const copy: PageSectionPlan[] = sections ?? [...page.sections];
354
+ if (swapSection(page, copy, i)) sections = copy;
355
+ }
356
+ if (sections) next = { ...next, sections };
357
+ // A section the model laid with a photo nothing fills: the plan's ready-made section for its place (the ONE
358
+ // fallback picker); one no ready-made section fits keeps its words with its photos left out (never dropped); the
359
+ // whole page from its sections when no place can be given away.
360
+ if (page.layout && laid.size) {
361
+ const issues: LayoutIssue[] = [...laid.keys()].map(i => ({ code: LayoutIssueCode.Content, path: `sections[${i}]`, message: `sections[${i}] ${SAID_LAYOUT}` }));
362
+ const fallback = fallBackBySection(page.layout, next.sections, issues, keepAsLaid);
363
+ const words = new Map<number, LayoutSection>();
364
+ for (const w of fallback.swaps) {
365
+ if (w.action !== SectionSwapAction.Dropped) continue;
366
+ const kept = typeLedLayoutSection(page.layout.sections[w.at], laid.get(w.at) ?? new Set());
367
+ if (kept) words.set(w.at, kept);
368
+ }
369
+ const dropped = fallback.swaps.filter(w => w.action === SectionSwapAction.Dropped && !words.has(w.at)).length;
370
+ const thin = dropped * THIN_SHARE > page.layout.sections.length;
371
+ if (fallback.lastResort || thin) {
372
+ const why = thin ? `${dropped} of its ${page.layout.sections.length} sections would be left out`
373
+ : fallback.lastResort === SectionFallbackLastResort.NoReadyMade ? 'no ready-made section left for a place' : 'its empty photos could not be given away';
374
+ changes.push({ kind: TypeLedChangeKind.Layout, page: page.key, said: `${page.name}: made from its sections — ${why}` });
375
+ const { layout: _laid, ...rest } = next;
376
+ next = rest as PagePlan;
377
+ } else {
378
+ for (const swap of fallback.swaps) {
379
+ const kept = words.get(swap.at);
380
+ changes.push({
381
+ kind: kept ? TypeLedChangeKind.LayoutWords : TypeLedChangeKind.LayoutSection, page: page.key, at: swap.at, ...(swap.readyMade ? { to: swap.readyMade.pattern } : {}),
382
+ said: `${page.name}: section ${swap.at + 1} ${SAID_LAYOUT} — ${swap.readyMade ? `the ready-made ${swap.readyMade.pattern} stands there` : kept ? 'its words stay, its photos left out' : 'left out (it says nothing without its photos)'}`,
383
+ });
384
+ }
385
+ // The dropped places that keep their words go back where the model laid them.
386
+ const swapped = new Set(fallback.swaps.filter(w => w.action === SectionSwapAction.Dropped).map(w => w.at));
387
+ const left = [...fallback.page.sections];
388
+ const sectionsBack: LayoutSection[] = [];
389
+ page.layout.sections.forEach((_, i) => {
390
+ if (words.has(i)) sectionsBack.push(words.get(i)!);
391
+ else if (!swapped.has(i)) sectionsBack.push(left.shift()!);
392
+ });
393
+ const givenAway = (fallback.page.givenAway ?? []).filter(g => !words.has(g.at));
394
+ next = { ...next, layout: { ...fallback.page, sections: sectionsBack, ...(givenAway.length ? { givenAway } : {}) } };
395
+ if (!givenAway.length) delete (next.layout as { givenAway?: unknown }).givenAway;
396
+ }
397
+ }
398
+ if (first) { firstScreen = next; homeAt = p; }
399
+ return next;
400
+ });
401
+ let next: SitePlan = changes.length ? { ...plan, pages } : plan;
402
+ let opening: TypeLedOpening | undefined;
403
+ if (firstScreen) {
404
+ // The home page's first screen shows no picture: it opens type-led, its hero's words slot by slot — when the hero
405
+ // that stands first (after this round's swaps) can give them so; else as v1: the page opens on that section.
406
+ const home = firstScreen as PagePlan;
407
+ const sections = [...home.sections];
408
+ const at = home.layout ? home.layout.sections[0]?.readyMade?.at ?? -1 : 0;
409
+ const chosen = chooseTypeLedOpening(plan, context);
410
+ const plain = at >= 0 ? sections[at] : undefined;
411
+ if (plain && !typeLedOpeningSection(chosen.mix, plain)) swapSection(home, sections, at);
412
+ const hero = at >= 0 ? sections[at] : undefined;
413
+ const takes = !!hero && !!typeLedOpeningSection(chosen.mix, hero);
414
+ const nextPages = [...pages];
415
+ nextPages[homeAt] = { ...home, sections };
416
+ next = { ...next, pages: nextPages };
417
+ if (takes) {
418
+ const words = openingMixWords(chosen.mix);
419
+ next = { ...next, mixes: { ...next.mixes, opening: words } };
420
+ opening = { words, token: chosen.token, ...(chosen.worn ? { worn: true as const } : {}) };
421
+ const was = plan.mixes?.opening?.join(' ');
422
+ if (was !== words.join(' ')) {
423
+ changes.push({
424
+ kind: TypeLedChangeKind.Opening, page: home.key, to: chosen.token,
425
+ said: `${home.name}: the first screen has no picture — it opens on its words (${words.join(' ')})${chosen.worn ? ', a way another site of the studio already opens' : ''}`,
426
+ });
427
+ }
428
+ } else if (plan.mixes?.opening?.length) {
429
+ const { opening: _left, ...mixes } = plan.mixes;
430
+ next = { ...next, mixes };
431
+ changes.push({ kind: TypeLedChangeKind.Opening, page: home.key, said: `the opening (${plan.mixes.opening.join(' ')}) has no picture — the home page opens on its first section` });
432
+ }
433
+ }
434
+ return { plan: next, changes, pictureless: picturelessTypes(plan, composed, filled), ...(opening ? { opening } : {}) };
435
+ }