@vectoriox/iox-ui 5.97.0 → 5.98.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.
@@ -97,6 +97,8 @@ export interface PatternNode {
97
97
  readonly phoneTracks?: ReadonlyArray<PatternTrack>;
98
98
  /** SC6b: the Video a film pattern plays the owner's film in (its `frames`). */
99
99
  readonly film?: boolean;
100
+ /** Commerce G1: a Repeater shows at most this many rows of its source (`commerce.featured`: the newest one). */
101
+ readonly limit?: number;
100
102
  }
101
103
 
102
104
  /**
@@ -126,6 +128,19 @@ export enum PatternRecipe {
126
128
  Carousel = 'carousel',
127
129
  /** CC3: the Lightbox — a Dialog holding a Slider over the node's `src` (the gallery's own source). */
128
130
  Lightbox = 'lightbox',
131
+ /** Commerce G1 (E1c `SHOP_RECIPES`): the product's price — its own on a product page (`$variant`), the row's in a
132
+ * list (`binds`: `price`, `compareAt`). */
133
+ Price = 'price',
134
+ Variants = 'variants',
135
+ Quantity = 'quantity',
136
+ Add = 'add',
137
+ BuyNow = 'buyNow',
138
+ }
139
+
140
+ /** A price recipe's `binds` keys → the part each binds (E1c `ShopBindTarget`). */
141
+ export enum PriceBindTarget {
142
+ Price = 'price',
143
+ CompareAt = 'compareAt',
129
144
  }
130
145
 
131
146
  /** A recipe node's `binds` keys → the part each binds (Card v2). */
@@ -162,6 +177,9 @@ export interface SitePattern {
162
177
  readonly scene?: boolean;
163
178
  /** SC6b: a Scene that plays the owner's film. Placed by `placeFilm`, never chosen: no manifest or wire lists it. */
164
179
  readonly film?: boolean;
180
+ /** Commerce G1: a store section — it reads the shop (its products, a product's price and variants). Listed only to
181
+ * a business that sells. */
182
+ readonly shop?: boolean;
165
183
  readonly node: PatternNode;
166
184
  }
167
185
 
@@ -347,11 +365,15 @@ export interface PatternManifestEntry {
347
365
  form: boolean;
348
366
  /** SC6: it holds the page as it scrolls — one per page, the home page and at most one other. */
349
367
  scene?: boolean;
368
+ /** Commerce G1: a store section — it binds the shop's sources. */
369
+ shop?: boolean;
350
370
  }
351
371
 
352
372
  export interface PatternManifestOptions {
353
373
  /** The site's How animated: below `SCENE_LEVEL` the Scenes are left out — a model cannot choose what it never sees. */
354
374
  animate?: string | null;
375
+ /** Commerce G1: whether the business sells — when false the store sections are left out; absent, all of them. */
376
+ sells?: boolean;
355
377
  }
356
378
 
357
379
  /**
@@ -360,7 +382,8 @@ export interface PatternManifestOptions {
360
382
  */
361
383
  export function patternManifest(density?: string | null, options: PatternManifestOptions = {}): PatternManifestEntry[] {
362
384
  const scenes = !('animate' in options) || options.animate === SCENE_LEVEL;
363
- return Object.entries(SITE_PATTERNS).filter(([, p]) => !p.film && (scenes || !p.scene)).map(([id, p]) => ({
385
+ const store = options.sells !== false;
386
+ return Object.entries(SITE_PATTERNS).filter(([, p]) => !p.film && (scenes || !p.scene) && (store || !p.shop)).map(([id, p]) => ({
364
387
  id, family: p.family, label: p.label, intent: p.intent, ...(p.global ? { global: p.global } : {}),
365
388
  slots: Object.fromEntries(Object.keys(patternSlotBudgets(p)).map(slot => [slot, slotBudget(p, slot, density) as number])),
366
389
  links: patternLinkSlots(p),
@@ -369,6 +392,7 @@ export function patternManifest(density?: string | null, options: PatternManifes
369
392
  optionalParts: patternOptionalParts(p),
370
393
  form: patternHasForm(p),
371
394
  ...(p.scene ? { scene: true } : {}),
395
+ ...(p.shop ? { shop: true } : {}),
372
396
  }));
373
397
  }
374
398
 
@@ -105,7 +105,7 @@ export interface PicturePlanOptions {
105
105
  }
106
106
 
107
107
  /** The ONE list of picture slots a build fills — its composed sections' empty pictures, then its sample items'. */
108
- export function pictureTargets(plan: SitePlan, composed: Pick<ComposedSite, 'pages' | 'placeholders' | 'items'>): StockTarget[] {
108
+ export function pictureTargets(plan: SitePlan, composed: Pick<ComposedSite, 'pages' | 'placeholders' | 'items'> & Partial<Pick<ComposedSite, 'shop'>>): StockTarget[] {
109
109
  return [...stockSlots(plan, composed), ...stockItemSlots(plan, composed)];
110
110
  }
111
111
 
@@ -1,6 +1,7 @@
1
1
  import { BindScope, patternById, patternScopes } from './patterns';
2
2
  import { DataSourcePlan, PlanDataSourceMode, PlanDataSourceType, RelativeOp } from './site-plan.model';
3
3
  import { isNonEmptyString, isPlainObject, PlainObject } from './shape-check';
4
+ import { derivedShopSources } from './shop-plan';
4
5
  import { nextSourceOf } from './validate-site-plan';
5
6
 
6
7
  /**
@@ -75,10 +76,14 @@ export function derivedDataSources(plan: unknown): DataSourcePlan[] {
75
76
  return derived;
76
77
  }
77
78
 
78
- /** `plan` with the data sources its pages need appended (`derivedDataSources`); the same object when it lacks none. */
79
+ /**
80
+ * `plan` with the data sources that follow from it appended: a selling plan's shop sources (`derivedShopSources`, commerce
81
+ * C-D21), then those its pages need (`derivedDataSources`). The same object when it lacks none.
82
+ */
79
83
  export function withDerivedSources<T>(plan: T): T {
80
- const derived = derivedDataSources(plan);
81
- if (!derived.length) return plan;
82
- const own = plan as unknown as PlainObject;
83
- return { ...own, dataSources: [...(own['dataSources'] as unknown[]), ...derived] } as T;
84
+ const shop = derivedShopSources(plan);
85
+ const withShop = shop.length ? { ...(plan as unknown as PlainObject), dataSources: [...((plan as unknown as PlainObject)['dataSources'] as unknown[]), ...shop] } : plan as unknown as PlainObject;
86
+ const derived = derivedDataSources(withShop);
87
+ if (!derived.length) return withShop as unknown as T;
88
+ return { ...withShop, dataSources: [...(withShop['dataSources'] as unknown[]), ...derived] } as T;
84
89
  }
@@ -2,7 +2,7 @@ import {
2
2
  jsonAnyOf, jsonInteger, jsonListOf, jsonOneOf, JsonSchema, jsonShapedObject, jsonText,
3
3
  } from './json-schema';
4
4
  import { patternById, patternOptionalParts, patternSlots, patternTakesBinding } from './patterns';
5
- import { derivedDataSources } from './plan-derived';
5
+ import { withDerivedSources } from './plan-derived';
6
6
  import {
7
7
  contentTypeToWire, dataSourceToWire, expandWireContentType, expandWireDataSource, expandWireField, expandWirePage, expandWireSection, fieldToWire,
8
8
  pageToWire, PLAN_PARTS, PlanPart, PlanWireShapeError, sectionPatternIds, sectionToWire, wireContentTypeJsonSchema, wireDataSourceJsonSchema,
@@ -365,7 +365,7 @@ const APPLY: Readonly<Record<`${PlanEditOp}`, Apply>> = {
365
365
  const at = findPage(d, e.page, c, `${path}.page`);
366
366
  if (at < 0 || !findSection(d, at, e.index, c, `${path}.index`)) return;
367
367
  const source = d.dataSources.find(s => s.alias === e.binding);
368
- if (!source || source.type !== PlanDataSourceType.Cms || source.mode !== PlanDataSourceMode.Query) {
368
+ if (!source || source.type === PlanDataSourceType.Relative || source.mode !== PlanDataSourceMode.Query) {
369
369
  return c.add(PlanEditIssueCode.UnknownDataSource, `${path}.binding`, `no list source "${String(e.binding)}" in the plan`);
370
370
  }
371
371
  setSections(d, at, d.pages[at].sections.map((s, i) => (i === e.index ? { ...s, binding: e.binding } : s)));
@@ -391,7 +391,7 @@ export function recomposeAsks(edits: ReadonlyArray<PlanEdit>): Record<string, st
391
391
  /**
392
392
  * Apply a set of edits to a plan — all of them, or none (any issue refuses the set and returns the plan unchanged). The
393
393
  * sources only removed pages and sections read are dropped with them; sources nothing read before are kept; the sources
394
- * the pages now need and no model writes are derived (`derivedDataSources` — a page edit adding `project.next`, as the
394
+ * the pages now need and no model writes are derived (`withDerivedSources` — a page edit adding `project.next`, as the
395
395
  * plan wire's expansion does, vectoriox/iox-cms#49). The result still has to pass `validateSitePlan`.
396
396
  */
397
397
  export function applyPlanEdits(plan: SitePlan, edits: ReadonlyArray<PlanEdit>): PlanEditResult {
@@ -406,13 +406,14 @@ export function applyPlanEdits(plan: SitePlan, edits: ReadonlyArray<PlanEdit>):
406
406
  const before = withDependencies(aliasesOf(plan.pages), plan.dataSources);
407
407
  const after = withDependencies(aliasesOf(draft.pages), draft.dataSources);
408
408
  const added = new Set(changed.filter(ch => ch.kind === PlanChangeKind.DataSource).map(ch => ch.name));
409
- const dataSources = draft.dataSources.filter(s => after.has(s.alias) || !before.has(s.alias) || added.has(s.alias));
409
+ // A shop source follows from what the business sells, never from which page reads it (commerce G1): it stays.
410
+ const dataSources = draft.dataSources.filter(s => s.type === PlanDataSourceType.Shop || after.has(s.alias) || !before.has(s.alias) || added.has(s.alias));
410
411
  for (const s of draft.dataSources) if (!dataSources.includes(s)) changed.push({ kind: PlanChangeKind.DataSource, action: PlanChangeAction.Removed, name: s.alias });
411
412
  const edited = { ...plan, pages: draft.pages, contentTypes: draft.contentTypes, dataSources };
412
- const derived = derivedDataSources(edited);
413
- for (const s of derived) changed.push({ kind: PlanChangeKind.DataSource, action: PlanChangeAction.Added, name: s.alias });
413
+ const whole = withDerivedSources(edited);
414
+ for (const s of whole.dataSources.slice(dataSources.length)) changed.push({ kind: PlanChangeKind.DataSource, action: PlanChangeAction.Added, name: s.alias });
414
415
 
415
- return { plan: derived.length ? { ...edited, dataSources: [...dataSources, ...derived] } : edited, changed, issues: [] };
416
+ return { plan: whole, changed, issues: [] };
416
417
  }
417
418
 
418
419
  // ── The format a model writes edits in ─────────────────────────────────────────────────────────────────
@@ -4,9 +4,10 @@ import { planFormPresetIds } from '@vectoriox/iox-ui/forms-core';
4
4
  import { describeShapeKey, jsonAnyOf, jsonBoolean, jsonInteger, jsonListOf, jsonOneOf, JsonSchema, jsonShapedObject, jsonText } from './json-schema';
5
5
  import { patternLinkSlots, patternOptionalParts, patternSlots, PatternGlobalPosition, SITE_PATTERNS } from './patterns';
6
6
  import { withDerivedSources } from './plan-derived';
7
+ import { shopCategoriesOf } from './shop-plan';
7
8
  import { ContentFieldControl, FIELD_TYPE_OF_CONTROL,
8
9
  ContentFieldPlan, ContentTypePlan, DataSourcePlan, FactKey, GlobalSlot, PAGE_ARCHETYPES, PagePlan, PageSectionPlan, PlanDataSourceMode, PlanDataSourceType,
9
- RelativeOp, SITE_NEED_IDS, SITE_PLAN_VERSION, SitePlan, SitePlanSource, SiteLocale,
10
+ RelativeOp, ShopProductPlan, SITE_NEED_IDS, SITE_PLAN_VERSION, SitePlan, SitePlanSource, SiteLocale,
10
11
  } from './site-plan.model';
11
12
  import { SPEC_SITE_PLAN_SHAPE } from './site-spec.generated';
12
13
  import { isPlainObject, PlainObject, ShapeEntry, shapeKeys } from './shape-check';
@@ -71,6 +72,9 @@ export enum PlanWireEntry {
71
72
  SlotLink = 'slotLink',
72
73
  Globals = 'globals',
73
74
  Direction = 'direction',
75
+ /** Commerce C-D21: one product the business sells, by name. */
76
+ ShopProduct = 'shopProduct',
77
+ ShopOption = 'shopOption',
74
78
  }
75
79
 
76
80
  type PlanShapeName = keyof typeof SPEC_SITE_PLAN_SHAPE;
@@ -97,7 +101,11 @@ const WIRE_KEYS: Readonly<Record<`${PlanWireEntry}`, Readonly<Record<string, Wir
97
101
  plan: {
98
102
  business: inPart(PlanPart.Structure, key('plan.business')),
99
103
  contentTypes: inPart(PlanPart.Structure, key('plan.contentTypes')),
100
- dataSources: inPart(PlanPart.Structure, { refs: ['plan.dataSources'], text: "dataSource[] — merged by alias into the org library; a per-item page's $siblings.next source (what a section reading the next item needs) is added for you" }),
104
+ dataSources: inPart(PlanPart.Structure, { refs: ['plan.dataSources'], text: "dataSource[] — merged by alias into the org library; a per-item page's $siblings.next source (what a section reading the next item needs) is added for you, and so are the shop's sources when the business sells" }),
105
+ shop: inPart(PlanPart.Structure, {
106
+ refs: ['plan.shop', 'shop.products'],
107
+ text: `shopProduct[] — what the business sells, when it sells (the need "products"): at most 6 sample products by name, each in a category — never a price, stock or a fee. [] = it sells nothing. Its categories, the shop's data sources (the products, the newest, one product by its :slug) and the store's parts are added for you`,
108
+ }),
101
109
  pages: inPart(PlanPart.Pages, key('plan.pages')),
102
110
  globals: inPart(PlanPart.Pages, key('plan.globals')),
103
111
  direction: inPart(PlanPart.Pages, key('plan.direction')),
@@ -141,13 +149,13 @@ const WIRE_KEYS: Readonly<Record<`${PlanWireEntry}`, Readonly<Record<string, Wir
141
149
  each: { refs: ['seed.perItem'], text: 'string[] — one value per sample, in order, when each sample has its own content', none: '[]' },
142
150
  },
143
151
  dataSource: {
144
- alias: { refs: ['cmsDataSource.alias', 'relativeDataSource.alias'] },
145
- type: { refs: ['cmsDataSource.type', 'relativeDataSource.type'], text: "'cms' | 'relative' — which of the keys below are read" },
146
- mode: key('cmsDataSource.mode', "'' (relative)"),
147
- contentType: key('cmsDataSource.contentType', "'' (relative)"),
148
- limit: key('cmsDataSource.limit', '0 (all, or relative)'),
149
- filterField: { refs: ['cmsDataSource.filterByRouteParam'], text: "string — single only: the field that holds the route param's value (e.g. slug)", none: "''" },
150
- routeParam: { refs: ['cmsDataSource.filterByRouteParam'], text: 'string — single only: the route param that picks the item (the :param of its page route)', none: "''" },
152
+ alias: { refs: ['cmsDataSource.alias', 'relativeDataSource.alias', 'shopDataSource.alias'] },
153
+ type: { refs: ['cmsDataSource.type', 'relativeDataSource.type', 'shopDataSource.type'], text: "'cms' | 'relative' | 'shop' — which of the keys below are read ('shop' sources are added for you)" },
154
+ mode: { refs: ['cmsDataSource.mode', 'shopDataSource.mode'], none: "'' (relative)" },
155
+ contentType: { refs: ['cmsDataSource.contentType', 'shopDataSource.resource'], text: "string — a content type of the plan (cms); the shop's list, 'products' or 'categories' (shop)", none: "'' (relative)" },
156
+ limit: { refs: ['cmsDataSource.limit', 'shopDataSource.limit'], none: '0 (all, or relative)' },
157
+ filterField: { refs: ['cmsDataSource.filterByRouteParam', 'shopDataSource.filterByRouteParam'], text: "string — single only: the field that holds the route param's value (e.g. slug)", none: "''" },
158
+ routeParam: { refs: ['cmsDataSource.filterByRouteParam', 'shopDataSource.filterByRouteParam'], text: 'string — single only: the route param that picks the item (the :param of its page route)', none: "''" },
151
159
  of: key('relativeDataSource.of', "'' (cms)"),
152
160
  op: key('relativeDataSource.op', "'' (cms)"),
153
161
  within: key('relativeDataSource.within', "'' (cms)"),
@@ -190,6 +198,16 @@ const WIRE_KEYS: Readonly<Record<`${PlanWireEntry}`, Readonly<Record<string, Wir
190
198
  header: key('globals.header'),
191
199
  footer: key('globals.footer'),
192
200
  },
201
+ shopProduct: {
202
+ name: key('shopProduct.name'),
203
+ category: key('shopProduct.category'),
204
+ description: key('shopProduct.description'),
205
+ options: key('shopProduct.options'),
206
+ },
207
+ shopOption: {
208
+ name: key('shopOption.name'),
209
+ values: key('shopOption.values'),
210
+ },
193
211
  };
194
212
 
195
213
  /** The plan keys the model does not write, and where the expander takes each from. */
@@ -210,6 +228,7 @@ export const PLAN_WIRE_DERIVED: Readonly<Record<string, string>> = {
210
228
  'plan.artDirection': 'the generation, from the business type and the look (M7 — artDirectionFor)',
211
229
  artDirection: 'the generation, from the business type and the look (M7 — artDirectionFor)',
212
230
  'page.layout': 'the layout step: one request per composed page, after the pages (M8 gate 2)',
231
+ 'shop.categories': "the products' own categories, in order (shopCategoriesOf)",
213
232
  layoutPage: 'the layout step: one request per composed page, after the pages (M8 gate 2)',
214
233
  };
215
234
 
@@ -364,8 +383,17 @@ const PLAN_TOP_SCHEMAS: Readonly<Record<string, () => JsonSchema>> = {
364
383
  [GlobalSlot.Footer]: jsonOneOf(globalIds(PatternGlobalPosition.After)),
365
384
  }),
366
385
  direction: () => shaped(PlanWireEntry.Direction, { idea: jsonText(), cliche: jsonText(), flip: jsonText(), rules: jsonListOf(jsonText()) }),
386
+ shop: () => jsonListOf(wireShopProductJsonSchema()),
367
387
  };
368
388
 
389
+ /** Commerce C-D21: one product the business sells, as the structure writes it — never a price, stock or a fee. */
390
+ export function wireShopProductJsonSchema(): JsonSchema {
391
+ return shaped(PlanWireEntry.ShopProduct, {
392
+ name: jsonText(), category: jsonText(), description: jsonText(),
393
+ options: jsonListOf(shaped(PlanWireEntry.ShopOption, { name: jsonText(), values: jsonListOf(jsonText()) })),
394
+ });
395
+ }
396
+
369
397
  /** The plan's top-level shape for one part (its keys only) — what that part's request shows and is built from. */
370
398
  export function planWirePartShape(part: PlanPart): ShapeEntry {
371
399
  return Object.fromEntries(Object.entries(PLAN_WIRE_SHAPE.plan).filter(([k]) => PLAN_PART_KEYS[part].includes(k)));
@@ -450,9 +478,21 @@ export function expandWireDataSource(wire: unknown): DataSourcePlan | unknown {
450
478
  return { ...rest, alias, type, mode, contentType, ...optional('limit', limit, v => v === undefined || v === 0), ...filter };
451
479
  }
452
480
  if (type === PlanDataSourceType.Relative) return { ...rest, alias, type, of, op, within };
481
+ if (type === PlanDataSourceType.Shop) {
482
+ const filter = isNone(filterField) && isNone(routeParam) ? {} : { filterByRouteParam: { field: filterField, routeParam } };
483
+ return { ...rest, alias, type, mode, resource: contentType, ...optional('limit', limit, v => v === undefined || v === 0), ...filter };
484
+ }
453
485
  return wire;
454
486
  }
455
487
 
488
+ /** The structure's products → the plan's `shop`: the products as written, their categories derived; `[]` = it sells nothing. */
489
+ export function expandWireShop(wire: unknown): unknown {
490
+ if (!Array.isArray(wire)) return wire;
491
+ if (!wire.length) return undefined;
492
+ const products = wire.filter(isPlainObject) as unknown as ShopProductPlan[];
493
+ return { categories: products.length === wire.length ? shopCategoriesOf(products) : [], products: wire };
494
+ }
495
+
456
496
  export function expandWireSection(wire: unknown): PageSectionPlan | unknown {
457
497
  if (!isPlainObject(wire)) return wire;
458
498
  const { slots, links, binding, without, form, enter, ...rest } = wire;
@@ -505,9 +545,11 @@ export function expandPlanWire(parts: PlanWireParts, context: PlanWireContext):
505
545
  const odd = written.find(value => !isPlainObject(value));
506
546
  if (odd !== undefined) return odd;
507
547
  const wire: PlainObject = Object.assign({}, ...(written as PlainObject[]));
508
- const { business, contentTypes, dataSources, pages, direction, ...rest } = wire;
548
+ const { business, contentTypes, dataSources, pages, direction, shop, ...rest } = wire;
549
+ const sells = expandWireShop(shop);
509
550
  return withDerivedSources({
510
551
  ...rest,
552
+ ...(sells === undefined ? {} : { shop: sells }),
511
553
  ...(isPlainObject(direction) && direction['idea'] === NONE ? {} : direction === undefined ? {} : { direction }),
512
554
  version: SITE_PLAN_VERSION,
513
555
  source: { ...context.source },
@@ -539,6 +581,12 @@ export function contentTypeToWire(type: ContentTypePlan, options: WireOptions =
539
581
  export function dataSourceToWire(source: DataSourcePlan): PlainObject {
540
582
  const blank = { alias: source.alias, type: source.type, mode: NONE, contentType: NONE, limit: 0, filterField: NONE, routeParam: NONE, of: NONE, op: NONE, within: NONE };
541
583
  if (source.type === PlanDataSourceType.Relative) return { ...blank, of: source.of, op: source.op, within: source.within };
584
+ if (source.type === PlanDataSourceType.Shop) {
585
+ return {
586
+ ...blank, mode: source.mode, contentType: source.resource, limit: source.limit ?? 0,
587
+ filterField: source.filterByRouteParam?.field ?? NONE, routeParam: source.filterByRouteParam?.routeParam ?? NONE,
588
+ };
589
+ }
542
590
  return {
543
591
  ...blank, mode: source.mode, contentType: source.contentType, limit: source.limit ?? 0,
544
592
  filterField: source.filterByRouteParam?.field ?? NONE, routeParam: source.filterByRouteParam?.routeParam ?? NONE,
@@ -569,6 +617,7 @@ const PLAN_TO_WIRE: Readonly<Record<string, (plan: SitePlan) => unknown>> = {
569
617
  pages: plan => plan.pages.map(page => pageToWire(page)),
570
618
  globals: plan => ({ ...plan.globals }),
571
619
  direction: plan => ({ idea: plan.direction?.idea ?? NONE, cliche: plan.direction?.cliche ?? NONE, flip: plan.direction?.flip ?? NONE, rules: [...(plan.direction?.rules ?? [])] }),
620
+ shop: plan => (plan.shop?.products ?? []).map(p => ({ name: p.name, category: p.category, description: p.description, options: p.options.map(o => ({ name: o.name, values: [...o.values] })) })),
572
621
  };
573
622
 
574
623
  /** One part of the plan on the wire: what that part's request would have answered. */
@@ -52,6 +52,16 @@ export function writtenTexts(plan: SitePlan): WrittenText[] {
52
52
  values.forEach((v, k) => add(`contentTypes[${t}].seed.${field}${Array.isArray(value) ? `[${k}]` : ''}`, v));
53
53
  }
54
54
  });
55
+ plan.shop?.products?.forEach((product, i) => {
56
+ const at = `shop.products[${i}]`;
57
+ add(`${at}.name`, product.name);
58
+ add(`${at}.category`, product.category);
59
+ add(`${at}.description`, product.description);
60
+ product.options?.forEach((option, j) => {
61
+ add(`${at}.options[${j}].name`, option.name);
62
+ option.values?.forEach((v, k) => add(`${at}.options[${j}].values[${k}]`, v));
63
+ });
64
+ });
55
65
  return out;
56
66
  }
57
67
 
@@ -69,14 +79,21 @@ export function wordPattern(word: string): RegExp {
69
79
  return new RegExp(`(?<![\\p{L}\\p{N}])${prefix}${w}(?![\\p{L}\\p{N}])`, 'u');
70
80
  }
71
81
 
82
+ const PRICE_SHAPE = { kind: 'price', pattern: /(?:[$€£₪]\s?\d[\d,.]*|\d[\d,.]*\s?(?:[$€£₪]|ש"ח|NIS|USD|EUR|GBP))/gu, key: (m: string) => m.replace(/[^\d]/g, '') };
83
+
72
84
  /** What a fact looks like when a model writes one — each judged against the owner's facts. */
73
85
  const FACT_SHAPES: ReadonlyArray<{ kind: string; pattern: RegExp; key: (match: string) => string }> = [
74
86
  { kind: 'email', pattern: /[\p{L}\p{N}._%+-]+@[\p{L}\p{N}-]+(?:\.[\p{L}\p{N}-]+)+/gu, key: m => m.toLowerCase() },
75
87
  { kind: 'phone', pattern: /\+?\d[\d\s().-]{6,}\d/g, key: m => m.replace(/\D/g, '') },
76
- { kind: 'price', pattern: /(?:[$€£₪]\s?\d[\d,.]*|\d[\d,.]*\s?(?:[$€£₪]|ש"ח|NIS|USD|EUR|GBP))/gu, key: m => m.replace(/[^\d]/g, '') },
88
+ PRICE_SHAPE,
77
89
  { kind: 'time', pattern: /(?<!\d)\d{1,2}[:.]\d{2}(?!\d)/g, key: m => m.replace(/\D/g, '') },
78
90
  ];
79
91
 
92
+ /** Every price written in `text` (commerce C-D21: what a business sells never carries one — the owner sets prices). */
93
+ export function pricesIn(text: string): string[] {
94
+ return (text.match(PRICE_SHAPE.pattern) ?? []).map(m => m.trim());
95
+ }
96
+
80
97
  const MIN_PHONE_DIGITS = 8;
81
98
  /** "2019 – 2024" is two years, not a phone number. */
82
99
  const YEAR_RANGE = /^\s*\d{4}\s*[-–]\s*\d{4}\s*$/;
@@ -29,6 +29,7 @@ export * from './site-build-run';
29
29
  export * from './ai-run';
30
30
  export * from './recipe-fields';
31
31
  export * from './plan-derived';
32
+ export * from './shop-plan';
32
33
  export * from './plan-wire';
33
34
  export * from './strict-schema';
34
35
  export * from './plan-edits';
@@ -0,0 +1,165 @@
1
+ import { VARIANT_NAME_SEPARATOR } from '@vectoriox/iox-ui/commerce-core';
2
+
3
+ import { isNonEmptyString, isPlainObject, PlainObject } from './shape-check';
4
+ import {
5
+ ContentFieldControl, ContentFieldPlan, ContentRoles, ContentTypePlan, DataSourcePlan, FIELD_TYPE_OF_CONTROL, PlanDataSourceMode, PlanDataSourceType,
6
+ ShopDataSourcePlan, ShopProductPlan, ShopResource, SitePlan,
7
+ } from './site-plan.model';
8
+
9
+ /**
10
+ * Commerce C-D21 (track G1; shop-aware A-D1, A-D2): a selling business's products are the studio's SHOP — never a
11
+ * content type of the plan. What a plan says about the shop is only WHAT the business sells (`plan.shop`: up to six
12
+ * sample products by name, their categories, how they vary — never a price, stock or a fee). Everything that follows
13
+ * from selling is derived here, never asked: the shop's data sources (the list, the newest, one product by its slug), the
14
+ * roles its rows play (fixed — the shop's own fields), and that the site is a whole store (the composer's cart button and
15
+ * cart drawer). Pure.
16
+ */
17
+
18
+ /** The need a reading names for a business that sells (harness-core `NEEDS.products`). */
19
+ export const SHOP_NEED = 'products';
20
+
21
+ /** At most this many sample products in a plan (commerce §3j: "≤ 6 sample products by name"). */
22
+ export const SHOP_PRODUCTS_MAX = 6;
23
+
24
+ /** The field each role is on a shop row — the storefront's own fields (iox-cms `storefront-projection.ts`). */
25
+ export const SHOP_ROLES: Readonly<Record<`${ShopResource}`, ContentRoles>> = {
26
+ [ShopResource.Products]: {
27
+ title: 'title', summary: 'description', image: 'mainImage', gallery: 'media', price: 'pricing.price', compareAt: 'pricing.compareat',
28
+ },
29
+ [ShopResource.Categories]: { title: 'label' },
30
+ };
31
+
32
+ const field = (name: string, controller: ContentFieldControl): ContentFieldPlan => ({ name, type: FIELD_TYPE_OF_CONTROL[controller], controller });
33
+
34
+ /** The shop's fields as a pattern's list rules read them (`patternListGap`): its own, fixed. */
35
+ export const SHOP_FIELDS: Readonly<Record<`${ShopResource}`, ReadonlyArray<ContentFieldPlan>>> = {
36
+ [ShopResource.Products]: [
37
+ field('title', ContentFieldControl.Text), field('slug', ContentFieldControl.Text), field('description', ContentFieldControl.Textarea),
38
+ field('mainImage', ContentFieldControl.Media), field('media', ContentFieldControl.Gallery),
39
+ field('pricing.price', ContentFieldControl.Number), field('pricing.compareat', ContentFieldControl.Number),
40
+ ],
41
+ [ShopResource.Categories]: [field('label', ContentFieldControl.Text), field('slug', ContentFieldControl.Text)],
42
+ };
43
+
44
+ const SHOP_LABELS: Readonly<Record<`${ShopResource}`, string>> = { [ShopResource.Products]: 'Products', [ShopResource.Categories]: 'Categories' };
45
+
46
+ /** The shop list as the composer and the validator read a content type: its fixed roles and fields. Never written. */
47
+ export function shopContentType(resource: `${ShopResource}`): ContentTypePlan {
48
+ return { name: resource, label: SHOP_LABELS[resource], roles: SHOP_ROLES[resource], fields: SHOP_FIELDS[resource] };
49
+ }
50
+
51
+ export const isShopResource = (value: unknown): value is `${ShopResource}` => (Object.values(ShopResource) as unknown[]).includes(value);
52
+
53
+ /** The field a product page's route param matches (the shop's slug, shop-aware §3d). */
54
+ export const SHOP_SLUG_FIELD = 'slug';
55
+ /** How many products the shop's list shows (shop-aware §8: one page, no paging until Plan B). */
56
+ export const SHOP_LIST_LIMIT = 24;
57
+ /** How many the newest list shows (a home page's row of cards). */
58
+ export const SHOP_LATEST_LIMIT = 3;
59
+
60
+ /** The shop's sources a selling plan holds — derived (`derivedShopSources`), each by its part in the store. */
61
+ export enum ShopSourceRole {
62
+ /** Every product (the shop page). */
63
+ List = 'list',
64
+ /** The newest few (the home page). */
65
+ Latest = 'latest',
66
+ /** One product, by the route's `:slug` (the product page). */
67
+ Item = 'item',
68
+ }
69
+
70
+ interface ShopSourceSpec {
71
+ alias: string;
72
+ mode: `${PlanDataSourceMode}`;
73
+ limit?: number;
74
+ byRoute?: boolean;
75
+ }
76
+
77
+ const SHOP_SOURCE_SPECS: Readonly<Record<ShopSourceRole, ShopSourceSpec>> = {
78
+ [ShopSourceRole.List]: { alias: 'products', mode: PlanDataSourceMode.Query, limit: SHOP_LIST_LIMIT },
79
+ [ShopSourceRole.Latest]: { alias: 'productsLatest', mode: PlanDataSourceMode.Query, limit: SHOP_LATEST_LIMIT },
80
+ [ShopSourceRole.Item]: { alias: 'product', mode: PlanDataSourceMode.Single, byRoute: true },
81
+ };
82
+
83
+ const SHOP_ROUTE_PARAM = 'slug';
84
+
85
+ /** The source a role is: the products list it reads, its mode, its limit, its route lookup. */
86
+ function shopSourceOf(role: ShopSourceRole, alias: string): ShopDataSourcePlan {
87
+ const spec = SHOP_SOURCE_SPECS[role];
88
+ return {
89
+ alias, type: PlanDataSourceType.Shop, mode: spec.mode, resource: ShopResource.Products,
90
+ ...(spec.limit ? { limit: spec.limit } : {}),
91
+ ...(spec.byRoute ? { filterByRouteParam: { field: SHOP_SLUG_FIELD, routeParam: SHOP_ROUTE_PARAM } } : {}),
92
+ };
93
+ }
94
+
95
+ /** The role a source plays in the store, or null (a source of some other shape stays the plan's own). */
96
+ function roleOfSource(raw: unknown): ShopSourceRole | null {
97
+ if (!isPlainObject(raw) || raw['type'] !== PlanDataSourceType.Shop || raw['resource'] !== ShopResource.Products) return null;
98
+ for (const [role, spec] of Object.entries(SHOP_SOURCE_SPECS) as Array<[ShopSourceRole, ShopSourceSpec]>) {
99
+ if (raw['mode'] !== spec.mode) continue;
100
+ const byRoute = isPlainObject(raw['filterByRouteParam']);
101
+ if (spec.byRoute ? byRoute : !byRoute && raw['limit'] === spec.limit) return role;
102
+ }
103
+ return null;
104
+ }
105
+
106
+ /** True when `plan` (a plan, or a part of one being written) says the business sells: its `shop` names a product. */
107
+ export function planSells(plan: unknown): boolean {
108
+ const shop = isPlainObject(plan) ? plan['shop'] : undefined;
109
+ return isPlainObject(shop) && Array.isArray(shop['products']) && shop['products'].length > 0;
110
+ }
111
+
112
+ /** The store's sources a plan holds, by role (the first of each) — the aliases the pages bind. */
113
+ export function shopSourceAliases(plan: unknown): Partial<Record<ShopSourceRole, string>> {
114
+ const out: Partial<Record<ShopSourceRole, string>> = {};
115
+ const list = isPlainObject(plan) && Array.isArray(plan['dataSources']) ? plan['dataSources'] : [];
116
+ for (const raw of list) {
117
+ const role = roleOfSource(raw);
118
+ if (role && !out[role] && isNonEmptyString((raw as PlainObject)['alias'])) out[role] = (raw as PlainObject)['alias'] as string;
119
+ }
120
+ return out;
121
+ }
122
+
123
+ /** The alias itself, else the first of `<alias>2`, `<alias>3`… no source has. */
124
+ function freeAlias(base: string, taken: ReadonlySet<string>): string {
125
+ let alias = base;
126
+ for (let n = 2; taken.has(alias); n++) alias = `${base}${n}`;
127
+ return alias;
128
+ }
129
+
130
+ /**
131
+ * The shop sources a selling plan lacks (shop-aware A-D1, the derived-not-asked rule of `plan-derived.ts`): the list,
132
+ * the newest and one product by its slug. Idempotent — a plan holding one of each gains nothing; a plan that sells
133
+ * nothing gains nothing. Tolerates any value.
134
+ */
135
+ export function derivedShopSources(plan: unknown): DataSourcePlan[] {
136
+ if (!planSells(plan) || !Array.isArray((plan as PlainObject)['dataSources'])) return [];
137
+ const have = shopSourceAliases(plan);
138
+ const taken = new Set(((plan as PlainObject)['dataSources'] as unknown[]).map(d => (isPlainObject(d) ? d['alias'] : undefined)).filter(isNonEmptyString));
139
+ const out: DataSourcePlan[] = [];
140
+ for (const role of Object.values(ShopSourceRole)) {
141
+ if (have[role]) continue;
142
+ const alias = freeAlias(SHOP_SOURCE_SPECS[role].alias, taken);
143
+ taken.add(alias);
144
+ out.push(shopSourceOf(role, alias));
145
+ }
146
+ return out;
147
+ }
148
+
149
+ /** The categories of a plan's products, in order, each once (what the wire derives from the products). */
150
+ export function shopCategoriesOf(products: ReadonlyArray<Pick<ShopProductPlan, 'category'>>): string[] {
151
+ return [...new Set(products.map(p => p.category).filter(isNonEmptyString).map(c => c.trim()))];
152
+ }
153
+
154
+ /** True when `plan` holds a shop source (a whole store's data). */
155
+ export function planHasShopSource(plan: Pick<SitePlan, 'dataSources'>): boolean {
156
+ return plan.dataSources.some(d => d.type === PlanDataSourceType.Shop);
157
+ }
158
+
159
+ /** A product's variants by name — one per combination of its options' values, in order (`Glaze-Sand-24 cm`'s shape, the
160
+ * shop's own: `VARIANT_NAME_SEPARATOR`). No options: none (the shop keeps its one Default). */
161
+ export function variantNamesOf(options: ReadonlyArray<{ readonly values: ReadonlyArray<string> }>): string[] {
162
+ const lists = options.map(o => o.values).filter(v => v.length);
163
+ if (!lists.length) return [];
164
+ return lists.reduce<string[][]>((combos, values) => combos.flatMap(c => values.map(v => [...c, v])), [[]]).map(c => c.join(VARIANT_NAME_SEPARATOR));
165
+ }
@@ -2,7 +2,9 @@ import type { DesignChoices } from '@vectoriox/iox-ui/design-core';
2
2
  import { FILM_PREPARED_PICTURES, FrameExtension, FrameSequence } from '@vectoriox/iox-ui/media-core';
3
3
 
4
4
  import { BindScope, patternNeedsBinding, PatternGlobalPosition, patternScopes, SCENE_LEVEL, SITE_PATTERNS } from './patterns';
5
- import { GlobalSlot, PagePlan, PageSectionPlan, SiteBusiness, SiteLocale, SitePlan, SitePlanSourceKind, SITE_PLAN_VERSION } from './site-plan.model';
5
+ import { withDerivedSources } from './plan-derived';
6
+ import { GlobalSlot, PagePlan, PageSectionPlan, ShopPlan, ShopResource, SiteBusiness, SiteLocale, SitePlan, SitePlanSourceKind, SITE_PLAN_VERSION } from './site-plan.model';
7
+ import { shopCategoriesOf, ShopSourceRole, shopSourceAliases } from './shop-plan';
6
8
  import { STUDIO_TEMPLATE } from './templates';
7
9
 
8
10
  /**
@@ -49,7 +51,7 @@ export function showcasePages(): PagePlan[] {
49
51
  const byFamily = new Map<string, string[]>();
50
52
  const onItemPage: string[] = [];
51
53
  for (const [id, p] of Object.entries(SITE_PATTERNS)) {
52
- if (p.global || p.scene) continue;
54
+ if (p.global || p.scene || p.shop) continue;
53
55
  if (readsRouteItem(id)) { onItemPage.push(id); continue; }
54
56
  byFamily.set(p.family, [...(byFamily.get(p.family) ?? []), id]);
55
57
  }
@@ -77,10 +79,31 @@ export function showcaseScenes(): string[] {
77
79
  return Object.entries(SITE_PATTERNS).filter(([, p]) => p.scene && !p.global).map(([id]) => id);
78
80
  }
79
81
 
82
+ /** Commerce G1: what the showcase's store sells — three samples in two categories, one with options; never a price. */
83
+ const SHOWCASE_PRODUCTS: ShopPlan['products'] = [
84
+ { name: 'Tall speckled vase', category: 'Vases', description: 'Thrown by hand, glazed in two tones.', options: [{ name: 'Glaze', values: ['Sand', 'Charcoal'] }, { name: 'Size', values: ['24 cm', '32 cm'] }] },
85
+ { name: 'Low serving bowl', category: 'Tableware', description: 'Wide and shallow, for the middle of the table.', options: [] },
86
+ { name: 'Bud vase', category: 'Vases', description: 'One stem, one shelf.', options: [] },
87
+ ];
88
+ export const SHOWCASE_SHOP: ShopPlan = { categories: shopCategoriesOf(SHOWCASE_PRODUCTS), products: SHOWCASE_PRODUCTS };
89
+
90
+ /** The store patterns (`shop`), each on the page a store shows it on: a list on the shop page, one product on its own. */
91
+ export function showcaseStorePages(sources: Partial<Record<ShopSourceRole, string>>): PagePlan[] {
92
+ const store = Object.entries(SITE_PATTERNS).filter(([, p]) => p.shop && !p.global);
93
+ const list = store.filter(([id]) => !readsRouteItem(id)).map(([id]) => ({ pattern: id, binding: sources[ShopSourceRole.List] }));
94
+ const item = store.filter(([id]) => readsRouteItem(id)).map(([id]) => ({ pattern: id }));
95
+ return [
96
+ { key: 'home', name: 'Home', route: '/', isHome: true, inNav: false, sections: [] },
97
+ { key: 'shop', name: 'Shop', route: '/shop', inNav: true, sections: list },
98
+ { key: 'product', name: 'Product', route: '/shop/:slug', inNav: false, template: ShopResource.Products, routeSource: sources[ShopSourceRole.Item], sections: item },
99
+ ];
100
+ }
101
+
80
102
  /**
81
103
  * The showcase as Site Plans — as many as it takes for every header and every footer to be composed once, then one per
82
104
  * Scene pattern (SC6): its home page holds that Scene and nothing else, at How animated Expressive, the only level a
83
- * Scene is composed at; the film's Scene with a film (SC6b).
105
+ * Scene is composed at; the film's Scene with a film (SC6b); then the store (commerce G1): the store patterns over the
106
+ * shop's derived sources, with the bag in the header and the cart drawer.
84
107
  */
85
108
  export function showcasePlans(input: ShowcaseInput): SitePlan[] {
86
109
  const { headers, footers } = showcaseGlobals();
@@ -102,5 +125,7 @@ export function showcasePlans(input: ShowcaseInput): SitePlan[] {
102
125
  // A film's Scene plays a film (SC6b): the plan carries one, as the build's would.
103
126
  return SITE_PATTERNS[id].film ? { ...scene, film: { sequence: JSON.parse(JSON.stringify(input.film ?? SHOWCASE_FILM)) } } : scene;
104
127
  });
105
- return [...Array.from({ length: count }, (_, i) => plan(i, pages, input.design)), ...scenes];
128
+ const selling = withDerivedSources({ ...plan(0, [], input.design), shop: JSON.parse(JSON.stringify(SHOWCASE_SHOP)) as ShopPlan });
129
+ const store: SitePlan = { ...selling, pages: showcaseStorePages(shopSourceAliases(selling)) };
130
+ return [...Array.from({ length: count }, (_, i) => plan(i, pages, input.design)), ...scenes, store];
106
131
  }