@krapwoo/ds-viewer 0.2.0 → 0.3.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.
@@ -0,0 +1,283 @@
1
+ /** Approved geometry. `cellPadding` equals CATALOG_SPACE.lg (asserted in tests). The laptop
2
+ * content width is a 1280px viewport minus the 264px sidebar and 32px side padding. */
3
+ export const MATRIX_LAYOUT = {
4
+ rowHeaderWidth: 120,
5
+ columnMaxWidth: 402,
6
+ cellPadding: 16,
7
+ rowMinHeight: 150,
8
+ laptopContentWidth: 952,
9
+ };
10
+ /** Component previews never render wider than a phone. */
11
+ export const PREVIEW_MAX_WIDTH = 402;
12
+ /** Two blocks share a row only when that saves at least this much page height. */
13
+ export const PLACEMENT_MIN_SAVING = 120;
14
+ /** A Props column is never narrower than this; below it the Props box uses one column. */
15
+ export const PROPS_MIN_COLUMN_WIDTH = 360;
16
+ /** Gap between the two Props columns (CATALOG_SPACE['2xl']). */
17
+ export const PROPS_COLUMN_GAP = 32;
18
+ /** Smallest column or cell width per specimen size. Wide specimens are fixed at phone width. */
19
+ export const COLUMN_MIN_WIDTH = { compact: 160, regular: 240, wide: 402 };
20
+ /** `Array.isArray`'s built-in type guard narrows to a mutable `any[]`, which a `readonly T[]`
21
+ * union member is never assignable to — so the `else` branch of `Array.isArray(axis) ? ... :
22
+ * ...` keeps `axis`'s full union type instead of narrowing away the array member. This explicit
23
+ * predicate sidesteps that (never caught before Task 4: this file had never been typechecked by
24
+ * `tsc` until `cli/doctor.ts`'s import pulled it into the root `tsconfig.json`'s program). */
25
+ function isBoundAxis(axis) {
26
+ return !Array.isArray(axis);
27
+ }
28
+ /** A `GridAxis`'s own items, whether it's a plain array or bound to a prop — every reader of
29
+ * `ComparisonDef.rows`/`columns` goes through this (never `Array.isArray` directly), so a future
30
+ * third axis shape only needs to change this one function. */
31
+ export function axisItems(axis) {
32
+ return isBoundAxis(axis) ? [...axis.items] : [...axis];
33
+ }
34
+ /** The prop name a `GridAxis` is bound to, or undefined for a plain, unbound axis. */
35
+ export function axisProp(axis) {
36
+ return isBoundAxis(axis) ? axis.prop : undefined;
37
+ }
38
+ /**
39
+ * Shared page-authoring helper (design §1 "Page shape", §4 "Binding examples to props"). Every
40
+ * grid comparison in the starter kit builds its `ComparisonDef` with this instead of its own local
41
+ * copy, so `cli/staticPage.ts`'s static reader has exactly one call shape to recognize anywhere a
42
+ * page's `comparison` field is produced by a function call rather than written as a plain object
43
+ * literal. `rows`/`columns` accept either a plain item array (unbound) or `{ prop, items }` (bound)
44
+ * — the cell grid itself is unaffected either way, since cells are always keyed by each axis's own
45
+ * items regardless of whether that axis names a prop. Lives here, beside `axisItems`/`axisProp`,
46
+ * rather than in its own `grid.ts` — every other file in this module has only *type-only* relative
47
+ * imports; a bare, no-extension value import would be the first of its kind in `native/catalog`.
48
+ *
49
+ * Each cell is a real instance with exactly the props its row and column name. Never build these by
50
+ * multiplying `variants` with `states` — those are pre-rendered nodes and cannot be combined.
51
+ */
52
+ export function grid(rowLabel, columnLabel, rows, columns, cell, size) {
53
+ const rowItems = axisItems(rows);
54
+ const columnItems = axisItems(columns);
55
+ return {
56
+ rowLabel,
57
+ columnLabel,
58
+ rows,
59
+ columns,
60
+ cells: rowItems.flatMap((row) => columnItems.map((column) => ({ rowKey: row.key, columnKey: column.key, node: cell(row.key, column.key) }))),
61
+ size,
62
+ };
63
+ }
64
+ /** How many grid columns fit beside the row header on a 1280px laptop without scrolling. */
65
+ export function gridColumnLimit(size) {
66
+ return Math.floor((MATRIX_LAYOUT.laptopContentWidth - MATRIX_LAYOUT.rowHeaderWidth) / COLUMN_MIN_WIDTH[size]);
67
+ }
68
+ export function gridWidthBounds(columnCount, size) {
69
+ const n = Math.max(0, columnCount);
70
+ return {
71
+ minWidth: MATRIX_LAYOUT.rowHeaderWidth + n * COLUMN_MIN_WIDTH[size],
72
+ maxWidth: MATRIX_LAYOUT.rowHeaderWidth + n * MATRIX_LAYOUT.columnMaxWidth,
73
+ };
74
+ }
75
+ /** Balanced wrapping for a one-axis list inside a single bordered card (1px outer border). Each
76
+ * cell's 1px divider sits inside its own width, so no cell is ever wider than 402px. Uses as few
77
+ * rows as fit, then spreads items evenly across them so a short last row leaves as little empty
78
+ * space as possible. `fillers` blank cells complete the last row. */
79
+ export function listGeometry(itemCount, availableWidth, size) {
80
+ if (itemCount <= 0)
81
+ return { columns: 0, rows: 0, fillers: 0, cellWidth: 0, containerWidth: 0 };
82
+ const inner = Math.max(0, availableWidth - 2);
83
+ const min = COLUMN_MIN_WIDTH[size];
84
+ const maxColumns = Math.max(1, Math.min(itemCount, Math.floor(inner / min)));
85
+ const rows = Math.ceil(itemCount / maxColumns);
86
+ const columns = Math.ceil(itemCount / rows);
87
+ const fitted = Math.floor(inner / columns);
88
+ const cellWidth = size === 'wide' ? MATRIX_LAYOUT.columnMaxWidth : Math.max(min, Math.min(MATRIX_LAYOUT.columnMaxWidth, fitted));
89
+ return {
90
+ columns,
91
+ rows,
92
+ fillers: rows * columns - itemCount,
93
+ cellWidth,
94
+ containerWidth: columns * cellWidth + 2,
95
+ };
96
+ }
97
+ export function cellKey(rowKey, columnKey) {
98
+ return `${rowKey}\u0000${columnKey}`;
99
+ }
100
+ export function indexCells(def) {
101
+ const index = new Map();
102
+ for (const cell of def.cells) {
103
+ const key = cellKey(cell.rowKey, cell.columnKey);
104
+ if (!index.has(key))
105
+ index.set(key, cell);
106
+ }
107
+ return index;
108
+ }
109
+ /** Human-readable problems in a stable order: axis duplicates, column fit, each cell in
110
+ * declaration order, then missing coordinates in row-major order. Empty when valid. */
111
+ export function validateComparison(def) {
112
+ const rowItems = axisItems(def.rows);
113
+ const columnItems = axisItems(def.columns);
114
+ if (rowItems.length === 0 || columnItems.length === 0) {
115
+ return ['Comparison needs at least one row and one column.'];
116
+ }
117
+ const issues = [];
118
+ const rowKeys = new Set();
119
+ for (const row of rowItems) {
120
+ if (rowKeys.has(row.key))
121
+ issues.push(`Duplicate row key "${row.key}".`);
122
+ rowKeys.add(row.key);
123
+ }
124
+ const columnKeys = new Set();
125
+ for (const column of columnItems) {
126
+ if (columnKeys.has(column.key))
127
+ issues.push(`Duplicate column key "${column.key}".`);
128
+ columnKeys.add(column.key);
129
+ }
130
+ const size = def.size ?? 'regular';
131
+ const limit = gridColumnLimit(size);
132
+ if (columnKeys.size > limit) {
133
+ issues.push(`Grid has ${columnKeys.size} columns; at most ${limit} ${size} columns fit a 1280px laptop. Swap the axes or use two lists.`);
134
+ }
135
+ const seen = new Set();
136
+ for (const cell of def.cells) {
137
+ const key = cellKey(cell.rowKey, cell.columnKey);
138
+ if (seen.has(key)) {
139
+ issues.push(`Duplicate cell for row "${cell.rowKey}" and column "${cell.columnKey}".`);
140
+ continue;
141
+ }
142
+ seen.add(key);
143
+ if (!rowKeys.has(cell.rowKey)) {
144
+ issues.push(`Cell references undeclared row "${cell.rowKey}".`);
145
+ continue;
146
+ }
147
+ if (!columnKeys.has(cell.columnKey)) {
148
+ issues.push(`Cell references undeclared column "${cell.columnKey}".`);
149
+ continue;
150
+ }
151
+ const hasNode = cell.node !== undefined;
152
+ const hasReason = typeof cell.unavailableReason === 'string' && cell.unavailableReason.length > 0;
153
+ if (hasNode === hasReason) {
154
+ issues.push(`Cell for row "${cell.rowKey}" and column "${cell.columnKey}" must provide exactly one of node or unavailableReason.`);
155
+ }
156
+ }
157
+ for (const rowKey of rowKeys) {
158
+ for (const columnKey of columnKeys) {
159
+ if (!seen.has(cellKey(rowKey, columnKey))) {
160
+ issues.push(`Missing cell for row "${rowKey}" and column "${columnKey}".`);
161
+ }
162
+ }
163
+ }
164
+ return issues;
165
+ }
166
+ /** `states` minus items whose key is already a grid row or column. */
167
+ export function remainingStates(states, comparison) {
168
+ if (!states)
169
+ return undefined;
170
+ if (!comparison)
171
+ return states;
172
+ const covered = new Set([...axisItems(comparison.rows).map((row) => row.key), ...axisItems(comparison.columns).map((column) => column.key)]);
173
+ const items = states.items.filter((item) => !covered.has(item.key));
174
+ return items.length > 0 ? { ...states, items } : undefined;
175
+ }
176
+ /** Specimen size for a one-axis slot: the section's explicit size, else wide for full-width
177
+ * (itemsFill) slots, else regular. */
178
+ export function slotSize(def, slot) {
179
+ return def.specimenSize ?? (slot.itemsFill ? 'wide' : 'regular');
180
+ }
181
+ function slotItems(slot) {
182
+ return slot.items.map((item) => ({ key: item.key, label: item.name, node: item.node, fill: item.fill || slot.itemsFill }));
183
+ }
184
+ /** Preview widths, each capped at phone width. 'full' is kept for catalog chrome and token pages. */
185
+ function previewWidths(requested, fallback) {
186
+ const widths = requested ?? fallback ?? [PREVIEW_MAX_WIDTH];
187
+ return widths === 'full' ? 'full' : widths.map((w) => Math.min(w, PREVIEW_MAX_WIDTH));
188
+ }
189
+ /** Grouped rows when at least one state names a variant through `group`. Every variant gets a row:
190
+ * its grouped states, or the variant's own example when it has none. States without a matching
191
+ * group are returned as leftovers for "Other configurations". */
192
+ function groupStates(variants, states) {
193
+ const variantKeys = new Set(variants.items.map((v) => v.key));
194
+ if (!states.items.some((s) => s.group !== undefined && variantKeys.has(s.group)))
195
+ return undefined;
196
+ const fill = (item, slot) => item.fill || slot.itemsFill;
197
+ const groups = variants.items.map((variant) => {
198
+ const own = states.items.filter((s) => s.group === variant.key);
199
+ const items = own.length > 0
200
+ ? own.map((s) => ({ key: s.key, label: s.name, node: s.node, fill: fill(s, states) }))
201
+ : [{ key: variant.key, label: variant.name, node: variant.node, fill: fill(variant, variants) }];
202
+ return { key: variant.key, label: variant.name, items };
203
+ });
204
+ const rest = states.items.filter((s) => s.group === undefined || !variantKeys.has(s.group));
205
+ for (const s of rest) {
206
+ if (s.group !== undefined && globalThis.__DEV__) {
207
+ console.warn(`[Catalog] state "${s.key}" names group "${s.group}", which matches no variant key; it is shown under "Other configurations".`);
208
+ }
209
+ }
210
+ return { groups, leftovers: rest.length > 0 ? { ...states, items: rest } : undefined };
211
+ }
212
+ /** The visual blocks of one page, in reading order. Reference details are not included. A page
213
+ * never shows an empty block next to a real one; with nothing documented at all it shows one
214
+ * "No examples documented." block. */
215
+ export function presentationBlocks(def, options = {}) {
216
+ if (def.tokenGallery) {
217
+ const title = def.fullWidthLabel ?? 'Tokens';
218
+ return [def.render ? { kind: 'preview', title, widths: 'full' } : { kind: 'empty', title, message: 'Nothing to preview.' }];
219
+ }
220
+ const hide = def.hide ?? {};
221
+ const blocks = [];
222
+ let states = hide.states ? undefined : remainingStates(def.states, def.comparison);
223
+ if (!hide.variants) {
224
+ const grouped = !def.comparison && def.variants && states ? groupStates(def.variants, states) : undefined;
225
+ if (def.comparison) {
226
+ blocks.push({
227
+ kind: 'grid',
228
+ title: `${def.comparison.rowLabel} × ${def.comparison.columnLabel}`,
229
+ size: def.comparison.size ?? def.specimenSize ?? 'regular',
230
+ comparison: def.comparison,
231
+ });
232
+ }
233
+ else if (grouped && def.variants) {
234
+ // Grouped rows place several cells beside a row header, so full-width (itemsFill) slots do
235
+ // not force 402px cells here; a cell's own `fill` still stretches its specimen.
236
+ blocks.push({ kind: 'grouped', title: 'Variant × configuration', size: def.specimenSize ?? 'regular', groups: grouped.groups });
237
+ states = grouped.leftovers;
238
+ }
239
+ else if (def.variants) {
240
+ blocks.push({ kind: 'list', title: 'Variants', size: slotSize(def, def.variants), items: slotItems(def.variants) });
241
+ }
242
+ else if (def.render) {
243
+ blocks.push({ kind: 'preview', title: 'Preview', widths: previewWidths(def.previewWidths, options.defaultPreviewWidths) });
244
+ }
245
+ }
246
+ if (states) {
247
+ const secondary = blocks.length > 0 && blocks[0].kind !== 'list';
248
+ blocks.push({
249
+ kind: 'list',
250
+ title: secondary ? 'Other configurations' : 'States / configurations',
251
+ size: slotSize(def, states),
252
+ items: slotItems(states),
253
+ });
254
+ }
255
+ if (blocks.length === 0 && !hide.variants && !hide.states) {
256
+ blocks.push({ kind: 'empty', title: 'Examples', message: 'No examples documented.' });
257
+ }
258
+ return blocks;
259
+ }
260
+ /** Side by side or stacked, for a page with exactly two blocks. Tries both and keeps the shorter;
261
+ * stays stacked unless side by side saves at least PLACEMENT_MIN_SAVING. Only a list can move
262
+ * beside a first block that hugs its content, and only when its cells keep their minimum width. */
263
+ export function choosePlacement({ available, gap, first, second }) {
264
+ if (second.kind !== 'list' || !second.itemCount || !second.size)
265
+ return 'stacked';
266
+ const firstWidth = first.width ?? available;
267
+ if (firstWidth > available * 0.7)
268
+ return 'stacked';
269
+ const room = available - firstWidth - gap;
270
+ const minCell = second.size === 'wide' ? MATRIX_LAYOUT.columnMaxWidth : COLUMN_MIN_WIDTH[second.size];
271
+ if (room < minCell + 2)
272
+ return 'stacked';
273
+ const stackedRows = listGeometry(second.itemCount, available, second.size).rows;
274
+ const sideRows = listGeometry(second.itemCount, room, second.size).rows;
275
+ const rowHeight = second.height / Math.max(1, stackedRows);
276
+ const sideHeight = Math.max(first.height, sideRows * rowHeight);
277
+ const stackedHeight = first.height + gap + second.height;
278
+ return sideHeight <= stackedHeight - PLACEMENT_MIN_SAVING ? 'side' : 'stacked';
279
+ }
280
+ /** Props box columns: two, filled across first, for 4+ props when each column keeps its minimum. */
281
+ export function propsColumns(count, width) {
282
+ return count >= 4 && width >= 2 * PROPS_MIN_COLUMN_WIDTH + PROPS_COLUMN_GAP ? 2 : 1;
283
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Catalog-only design tokens — the visual system of the catalog interface itself.
3
+ *
4
+ * Deliberately independent of any host app's design-system tokens (DS_SEMANTIC / DS_PALETTE /
5
+ * DS_SPACING): the catalog documents a design system, it does not consume one. Keeping its chrome
6
+ * on its own tokens means a change to the host app's tokens never restyles the catalog, and this
7
+ * folder can be copied into another app's repo unchanged.
8
+ *
9
+ * Values match the approved Studio Matrix references
10
+ * (docs/design/2026-10-06-catalog-studio-matrix-*.html), with one deliberate exception:
11
+ * `textMuted` stays #666666 because the references' #777777 fails WCAG AA contrast.
12
+ */
13
+ export const CATALOG_TYPE = {
14
+ xs: 10,
15
+ tableHeader: 11,
16
+ sm: 12,
17
+ panelHeading: 13,
18
+ md: 14,
19
+ lg: 16,
20
+ brand: 17,
21
+ xl: 20,
22
+ '2xl': 24,
23
+ pageTitle: 28,
24
+ '3xl': 32,
25
+ '4xl': 40,
26
+ };
27
+ export const CATALOG_SPACE = {
28
+ xs: 4,
29
+ sm: 8,
30
+ md: 12,
31
+ lg: 16,
32
+ xl: 24,
33
+ '2xl': 32,
34
+ '3xl': 40,
35
+ };
36
+ export const CATALOG_RADIUS = {
37
+ sm: 8,
38
+ control: 9,
39
+ md: 12,
40
+ card: 14,
41
+ };
42
+ /** Exact chrome measurements from the approved references that are not spacing-scale steps. */
43
+ export const CATALOG_LAYOUT = {
44
+ sidebarWidth: 264,
45
+ sidebarPaddingTop: 24,
46
+ sidebarPaddingX: 18,
47
+ mainPaddingTop: 28,
48
+ mainPaddingX: 32,
49
+ controlSize: 44,
50
+ focusRingWidth: 3,
51
+ navItemPaddingY: 8,
52
+ navItemPaddingX: 10,
53
+ panelPadding: 20,
54
+ factPaddingY: 9,
55
+ blockLabelGap: 14,
56
+ blockGap: 28,
57
+ /** Sidebar logo header (design `docs/design/2026-10-08-ds-viewer-sidebar-logo-approved.html`,
58
+ * "C · Adaptive", approved 2026-10-08) — see `native/catalog/logoLayout.ts`. */
59
+ logoMark: 32,
60
+ logoWordmarkHeight: 28,
61
+ logoCaptionGap: 6,
62
+ };
63
+ /** Max width of the main content column. */
64
+ export const CATALOG_MAX_CONTENT_WIDTH = 1200;
65
+ /** When to reach for each catalog-chrome type size. Rendered in the framework catalog's Type
66
+ * Scale page. */
67
+ export const CATALOG_TYPE_USE = {
68
+ xs: 'Sidebar group labels (uppercase); a prop\'s type annotation.',
69
+ tableHeader: 'Grid column headers and list cell captions (uppercase).',
70
+ sm: 'Breadcrumb, catalog caption, block labels, prop names and descriptions.',
71
+ panelHeading: 'Reference-panel headings: Guidance, Quick reference, Props (uppercase).',
72
+ md: 'Default body text: descriptions, nav links, grid row headers, quick-reference rows, the filter field.',
73
+ lg: 'Pager arrows and the filter field\'s clear (×) glyph.',
74
+ brand: 'The app name at the top of the sidebar.',
75
+ xl: 'Reserved — no current consumer.',
76
+ '2xl': 'Reserved — no current consumer.',
77
+ pageTitle: 'The selected page\'s title.',
78
+ '3xl': 'Reserved — no current consumer.',
79
+ '4xl': 'Reserved — no current consumer.',
80
+ };
81
+ /** When to reach for each catalog-chrome spacing step. Rendered in the framework catalog's
82
+ * Spacing page. */
83
+ export const CATALOG_SPACE_USE = {
84
+ xs: 'Tight gap — e.g. between a token\'s rendered value and its use-note.',
85
+ sm: 'Small gap — below the filter field; between a preview frame\'s label and its demo.',
86
+ md: 'Medium gap — between a card\'s contents; token-row divider padding.',
87
+ lg: 'Grid and list cell padding (16px); row gap in scale galleries.',
88
+ xl: 'Preview-card padding; gap between preview frames.',
89
+ '2xl': 'Gap between the reference panel\'s Guidance and Quick reference columns.',
90
+ '3xl': 'Bottom padding of the main column.',
91
+ };
92
+ export const CATALOG_COLOR = {
93
+ text: '#181818',
94
+ // #666666, not the references' #777777: #777 is 4.14–4.48:1 on this file's surfaces (WCAG AA
95
+ // needs 4.5:1); #666 is 5.3–5.7:1.
96
+ textMuted: '#666666',
97
+ /** Dividers inside grids, lists, props tables, token rows. */
98
+ border: '#e4e4e4',
99
+ /** Sidebar edge, reference card, filter field. */
100
+ borderHairline: '#dddddd',
101
+ /** Grid, list, and preview cards; pager buttons. */
102
+ borderStrong: '#d7d7d7',
103
+ /** Quick-reference row dividers. */
104
+ borderSubtle: '#eeeeee',
105
+ surface: '#ffffff',
106
+ /** Table headers, row headers, cell captions, filter field. */
107
+ surfaceMuted: '#fafafa',
108
+ /** Hover and pressed feedback on nav rows and buttons. */
109
+ surfacePressed: '#f1f3f8',
110
+ pageBackground: '#f6f6f4',
111
+ chip: '#eeeeee',
112
+ /** Active nav label, prop types, scale bars. */
113
+ accent: '#174dc6',
114
+ /** Active nav row background. */
115
+ accentSubtle: '#e9efff',
116
+ /** 3px keyboard focus ring on every catalog control. */
117
+ focusRing: '#c9d7ff',
118
+ code: 'Menlo',
119
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -1,7 +1,7 @@
1
1
  import React from 'react';
2
2
  import { View, Text, ScrollView, StyleSheet } from 'react-native';
3
3
  import { CATALOG_COLOR, CATALOG_RADIUS, CATALOG_TYPE } from './tokens';
4
- import { COLUMN_MIN_WIDTH, MATRIX_LAYOUT, cellKey, gridWidthBounds, indexCells, validateComparison } from './comparison';
4
+ import { COLUMN_MIN_WIDTH, MATRIX_LAYOUT, axisItems, cellKey, gridWidthBounds, indexCells, validateComparison } from './comparison';
5
5
  import type { ComparisonDef, SpecimenSize } from './types';
6
6
 
7
7
  /**
@@ -14,7 +14,9 @@ export function ComparisonGrid({ def, size, sectionId }: { def: ComparisonDef; s
14
14
  for (const issue of validateComparison({ ...def, size })) console.warn(`[Catalog] ${sectionId}: ${issue}`);
15
15
  }
16
16
  const cells = indexCells(def);
17
- const bounds = gridWidthBounds(def.columns.length, size);
17
+ const rows = axisItems(def.rows);
18
+ const columns = axisItems(def.columns);
19
+ const bounds = gridWidthBounds(columns.length, size);
18
20
  const column = {
19
21
  flexGrow: 1,
20
22
  flexShrink: 1,
@@ -22,7 +24,7 @@ export function ComparisonGrid({ def, size, sectionId }: { def: ComparisonDef; s
22
24
  minWidth: COLUMN_MIN_WIDTH[size],
23
25
  maxWidth: MATRIX_LAYOUT.columnMaxWidth,
24
26
  };
25
- const lastColumn = def.columns.length - 1;
27
+ const lastColumn = columns.length - 1;
26
28
 
27
29
  return (
28
30
  <ScrollView horizontal style={styles.scroller} contentContainerStyle={styles.scrollContent}>
@@ -35,18 +37,18 @@ export function ComparisonGrid({ def, size, sectionId }: { def: ComparisonDef; s
35
37
  <View role="columnheader" style={[styles.cell, styles.rowHeader, styles.headerCell]}>
36
38
  <Text style={styles.headerText}>{def.rowLabel}</Text>
37
39
  </View>
38
- {def.columns.map((c, ci) => (
40
+ {columns.map((c, ci) => (
39
41
  <View key={c.key} role="columnheader" style={[styles.cell, column, styles.headerCell, ci === lastColumn && styles.lastColumn]}>
40
42
  <Text style={styles.headerText}>{c.label}</Text>
41
43
  </View>
42
44
  ))}
43
45
  </View>
44
- {def.rows.map((row, ri) => (
45
- <View key={row.key} role="row" style={[styles.row, ri === def.rows.length - 1 && styles.lastRow]}>
46
+ {rows.map((row, ri) => (
47
+ <View key={row.key} role="row" style={[styles.row, ri === rows.length - 1 && styles.lastRow]}>
46
48
  <View role="rowheader" style={[styles.cell, styles.rowHeader, styles.bodyRow]}>
47
49
  <Text style={styles.rowHeaderText}>{row.label}</Text>
48
50
  </View>
49
- {def.columns.map((c, ci) => {
51
+ {columns.map((c, ci) => {
50
52
  const cell = cells.get(cellKey(row.key, c.key));
51
53
  return (
52
54
  <View key={c.key} role="cell" style={[styles.cell, column, styles.bodyRow, styles.specimenCell, ci === lastColumn && styles.lastColumn]}>
@@ -8,7 +8,7 @@ import { CATALOG_TYPE, CATALOG_COLOR, CATALOG_SPACE, CATALOG_RADIUS } from './to
8
8
  * framework's own, and any host app's). Generic over the step-name type so it works for any scale
9
9
  * (the host app's `DS_SPACING`, this framework's own `CATALOG_SPACE`, or a third-party one).
10
10
  */
11
- export function SpacingScaleGallery<TStep extends string>({
11
+ export function SpacingScaleGallery<TStep extends string | number>({
12
12
  steps,
13
13
  values,
14
14
  useNotes,
@@ -3,7 +3,7 @@
3
3
  * runner. CatalogShell, CatalogSidebar, and SectionBlock all derive page order from here, so the
4
4
  * sidebar order, previous/next order, and fragment fallback can never drift apart.
5
5
  */
6
- import type { NavGroup } from './types';
6
+ import type { NavGroup } from './types.ts';
7
7
 
8
8
  /** THE canonical within-group ordering of section ids. */
9
9
  export function sortIds<TId extends string>(ids: readonly TId[]): TId[] {
@@ -8,7 +8,8 @@
8
8
  * It also decides whether two blocks sit side by side (choosePlacement) and how many columns the
9
9
  * Props box uses (propsColumns). ComparisonGrid, ComparisonGroups, and ComparisonList render it.
10
10
  */
11
- import type { ComparisonDef, PreviewWidths, SectionDef, SpecimenSize, VariantSlot } from './types';
11
+ import type { ComparisonAxisItem, ComparisonDef, GridAxis, PreviewWidths, SectionDef, SpecimenSize, VariantSlot } from './types.ts';
12
+ import type React from 'react';
12
13
 
13
14
  /** Approved geometry. `cellPadding` equals CATALOG_SPACE.lg (asserted in tests). The laptop
14
15
  * content width is a 1280px viewport minus the 264px sidebar and 32px side padding. */
@@ -35,6 +36,61 @@ export const PROPS_COLUMN_GAP = 32;
35
36
  /** Smallest column or cell width per specimen size. Wide specimens are fixed at phone width. */
36
37
  export const COLUMN_MIN_WIDTH: Record<SpecimenSize, number> = { compact: 160, regular: 240, wide: 402 };
37
38
 
39
+ /** `Array.isArray`'s built-in type guard narrows to a mutable `any[]`, which a `readonly T[]`
40
+ * union member is never assignable to — so the `else` branch of `Array.isArray(axis) ? ... :
41
+ * ...` keeps `axis`'s full union type instead of narrowing away the array member. This explicit
42
+ * predicate sidesteps that (never caught before Task 4: this file had never been typechecked by
43
+ * `tsc` until `cli/doctor.ts`'s import pulled it into the root `tsconfig.json`'s program). */
44
+ function isBoundAxis(axis: GridAxis): axis is { prop: string; items: readonly ComparisonAxisItem[] } {
45
+ return !Array.isArray(axis);
46
+ }
47
+
48
+ /** A `GridAxis`'s own items, whether it's a plain array or bound to a prop — every reader of
49
+ * `ComparisonDef.rows`/`columns` goes through this (never `Array.isArray` directly), so a future
50
+ * third axis shape only needs to change this one function. */
51
+ export function axisItems(axis: GridAxis): ComparisonAxisItem[] {
52
+ return isBoundAxis(axis) ? [...axis.items] : [...axis];
53
+ }
54
+
55
+ /** The prop name a `GridAxis` is bound to, or undefined for a plain, unbound axis. */
56
+ export function axisProp(axis: GridAxis): string | undefined {
57
+ return isBoundAxis(axis) ? axis.prop : undefined;
58
+ }
59
+
60
+ /**
61
+ * Shared page-authoring helper (design §1 "Page shape", §4 "Binding examples to props"). Every
62
+ * grid comparison in the starter kit builds its `ComparisonDef` with this instead of its own local
63
+ * copy, so `cli/staticPage.ts`'s static reader has exactly one call shape to recognize anywhere a
64
+ * page's `comparison` field is produced by a function call rather than written as a plain object
65
+ * literal. `rows`/`columns` accept either a plain item array (unbound) or `{ prop, items }` (bound)
66
+ * — the cell grid itself is unaffected either way, since cells are always keyed by each axis's own
67
+ * items regardless of whether that axis names a prop. Lives here, beside `axisItems`/`axisProp`,
68
+ * rather than in its own `grid.ts` — every other file in this module has only *type-only* relative
69
+ * imports; a bare, no-extension value import would be the first of its kind in `native/catalog`.
70
+ *
71
+ * Each cell is a real instance with exactly the props its row and column name. Never build these by
72
+ * multiplying `variants` with `states` — those are pre-rendered nodes and cannot be combined.
73
+ */
74
+ export function grid(
75
+ rowLabel: string,
76
+ columnLabel: string,
77
+ rows: GridAxis,
78
+ columns: GridAxis,
79
+ cell: (row: string, column: string) => React.ReactNode,
80
+ size?: SpecimenSize,
81
+ ): ComparisonDef {
82
+ const rowItems = axisItems(rows);
83
+ const columnItems = axisItems(columns);
84
+ return {
85
+ rowLabel,
86
+ columnLabel,
87
+ rows,
88
+ columns,
89
+ cells: rowItems.flatMap((row) => columnItems.map((column) => ({ rowKey: row.key, columnKey: column.key, node: cell(row.key, column.key) }))),
90
+ size,
91
+ };
92
+ }
93
+
38
94
  /** How many grid columns fit beside the row header on a 1280px laptop without scrolling. */
39
95
  export function gridColumnLimit(size: SpecimenSize): number {
40
96
  return Math.floor((MATRIX_LAYOUT.laptopContentWidth - MATRIX_LAYOUT.rowHeaderWidth) / COLUMN_MIN_WIDTH[size]);
@@ -94,17 +150,19 @@ export function indexCells(def: ComparisonDef): Map<string, ComparisonDef['cells
94
150
  /** Human-readable problems in a stable order: axis duplicates, column fit, each cell in
95
151
  * declaration order, then missing coordinates in row-major order. Empty when valid. */
96
152
  export function validateComparison(def: ComparisonDef): string[] {
97
- if (def.rows.length === 0 || def.columns.length === 0) {
153
+ const rowItems = axisItems(def.rows);
154
+ const columnItems = axisItems(def.columns);
155
+ if (rowItems.length === 0 || columnItems.length === 0) {
98
156
  return ['Comparison needs at least one row and one column.'];
99
157
  }
100
158
  const issues: string[] = [];
101
159
  const rowKeys = new Set<string>();
102
- for (const row of def.rows) {
160
+ for (const row of rowItems) {
103
161
  if (rowKeys.has(row.key)) issues.push(`Duplicate row key "${row.key}".`);
104
162
  rowKeys.add(row.key);
105
163
  }
106
164
  const columnKeys = new Set<string>();
107
- for (const column of def.columns) {
165
+ for (const column of columnItems) {
108
166
  if (columnKeys.has(column.key)) issues.push(`Duplicate column key "${column.key}".`);
109
167
  columnKeys.add(column.key);
110
168
  }
@@ -149,7 +207,7 @@ export function validateComparison(def: ComparisonDef): string[] {
149
207
  export function remainingStates(states: VariantSlot | undefined, comparison: ComparisonDef | undefined): VariantSlot | undefined {
150
208
  if (!states) return undefined;
151
209
  if (!comparison) return states;
152
- const covered = new Set([...comparison.rows.map((row) => row.key), ...comparison.columns.map((column) => column.key)]);
210
+ const covered = new Set([...axisItems(comparison.rows).map((row) => row.key), ...axisItems(comparison.columns).map((column) => column.key)]);
153
211
  const items = states.items.filter((item) => !covered.has(item.key));
154
212
  return items.length > 0 ? { ...states, items } : undefined;
155
213
  }
@@ -17,6 +17,7 @@ export { CatalogSidebar } from './CatalogSidebar';
17
17
  export { CatalogSearchInput } from './CatalogSearchInput';
18
18
  export { SectionBlock } from './SectionBlock';
19
19
  export { ComparisonGrid } from './ComparisonGrid';
20
+ export { grid, axisItems, axisProp } from './comparison';
20
21
  export { ComparisonGroups } from './ComparisonGroups';
21
22
  export { ComparisonList } from './ComparisonList';
22
23
  export { ReferenceDetails } from './ReferenceDetails';
@@ -32,7 +33,7 @@ export { buildComponentManifest } from './manifest';
32
33
  export type { ComponentManifestEntry, ManifestExample } from './manifest';
33
34
  export { defineCatalogPage, buildCatalogSections } from './pageApi';
34
35
  export type { CatalogPage, CatalogPageInput, GeneratedComponent, GeneratedPropRecord } from './pageApi';
35
- export type { PropDef, SectionDef, NavGroup, SpecimenSize, ComparisonDef, ComparisonCell, ComparisonAxisItem, PreviewWidths } from './types';
36
+ export type { PropDef, SectionDef, NavGroup, SpecimenSize, ComparisonDef, ComparisonCell, ComparisonAxisItem, GridAxis, PreviewWidths } from './types';
36
37
  export type { ListGroup, ListItem } from './comparison';
37
38
  export {
38
39
  CATALOG_TYPE,
@@ -77,7 +77,7 @@ function mergePropNotes(component: GeneratedComponent, propNotes: Record<string,
77
77
  return [...own, ...inherited];
78
78
  }
79
79
 
80
- function orderGroups(groupIds: Map<string, string[]>, groupOrder: string[] | undefined): { label: string; ids: string[] }[] {
80
+ function orderGroups<TId extends string>(groupIds: Map<string, TId[]>, groupOrder: string[] | undefined): NavGroup<TId>[] {
81
81
  const listed = groupOrder ?? [];
82
82
  const labels = [...groupIds.keys()];
83
83
  const ordered = [...listed.filter((label) => groupIds.has(label)), ...labels.filter((label) => !listed.includes(label)).sort()];
@@ -103,7 +103,16 @@ export function buildCatalogSections<TId extends string>(
103
103
  const groupIds = new Map<string, TId[]>();
104
104
  const addToGroup = (group: string, id: TId) => groupIds.set(group, [...(groupIds.get(group) ?? []), id]);
105
105
 
106
+ // Design §4 "duplicate-page-id" rule's viewer-side equivalent — this is the one place in the
107
+ // whole viewer that already resolves every page's id to build sections/groups, so it costs
108
+ // nothing extra to also notice two pages claiming the same one (`sectionsById` in
109
+ // `CatalogShell.tsx` would otherwise just let the last one silently win).
110
+ const seenIds = new Set<TId>();
106
111
  const sections: SectionDef<TId>[] = pages.map((page) => {
112
+ if ((globalThis as { __DEV__?: boolean }).__DEV__) {
113
+ if (seenIds.has(page.id)) console.warn(`[Catalog] Page id "${page.id}" is used by more than one page; only the last one will show. Give one of them its own "id".`);
114
+ seenIds.add(page.id);
115
+ }
107
116
  const componentName = page.component ?? page.id;
108
117
  const component = componentByName.get(componentName);
109
118
  addToGroup(page.group, page.id);
@@ -136,5 +145,5 @@ export function buildCatalogSections<TId extends string>(
136
145
  addToGroup('Components', id);
137
146
  }
138
147
 
139
- return { sections, groups: orderGroups(groupIds, groupOrder) as NavGroup<TId>[] };
148
+ return { sections, groups: orderGroups(groupIds, groupOrder) };
140
149
  }
@@ -65,6 +65,13 @@ export interface ComparisonAxisItem {
65
65
  label: string;
66
66
  }
67
67
 
68
+ /** A grid axis's rows or columns: a plain list of items (today's shape, unchanged), or items bound
69
+ * to a real prop so `doctor` can check each item's key against that prop's actual options (design
70
+ * §4 "Binding examples to props"). Only a prop typed as a string-literal union can be bound —
71
+ * binding any other prop is a `doctor` error, never a runtime check here (the viewer renders a
72
+ * bound and an unbound axis identically; see `native/catalog/comparison.ts`'s `axisItems`). */
73
+ export type GridAxis = readonly ComparisonAxisItem[] | { prop: string; items: readonly ComparisonAxisItem[] };
74
+
68
75
  /** One authored row × column specimen. Provide exactly one of `node` (a real instance of the
69
76
  * documented component) or `unavailableReason` (the combination genuinely does not exist). */
70
77
  export interface ComparisonCell {
@@ -83,8 +90,8 @@ export interface ComparisonDef {
83
90
  rowLabel: string;
84
91
  /** Names the column axis (e.g. "State"). */
85
92
  columnLabel: string;
86
- rows: ComparisonAxisItem[];
87
- columns: ComparisonAxisItem[];
93
+ rows: GridAxis;
94
+ columns: GridAxis;
88
95
  cells: ComparisonCell[];
89
96
  /** Defaults to the section's `specimenSize`, then 'regular'. */
90
97
  size?: SpecimenSize;
@@ -188,7 +195,3 @@ export interface NavGroup<TId extends string = string> {
188
195
  label: string;
189
196
  ids: readonly TId[];
190
197
  }
191
-
192
- /** Canonical within-group ordering — implemented in ./catalogNavigation (pure, unit-tested) and
193
- * re-exported here so existing imports keep working. */
194
- export { sortIds } from './catalogNavigation';