An open source design system that's fully customizable and agent ready
TypeScript
docs(core): smaller, realistic playing-card demo for motion and gesture examples, with a usage hint (#9607)
Cindy Zhange0eac233d8e7
diff --git a/.changeset/playing-card-demo-hint.md b/.changeset/playing-card-demo-hint.mdnew file mode 100644index 0000000000..64fd32e06c--- /dev/null+++ b/.changeset/playing-card-demo-hint.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[docs] The `usePressFeedback — Pressable Card` example now shows a small card in real playing-card proportions, with corner indices, a full face and a patterned back, and a line under it that says what to try: press and hold to see the press, tap, click, Enter or Space to flip. Copying the example (`astryx template`, the docsite's Code tab and Install) still gives you only the hook on a Card (`width={120}`, `padding={1}`) with one `<Text>` placeholder: the hint line is left out, not replaced.++@cixzhangdiff --git a/apps/docsite/src/templateDemoContent/demoContent.tsx b/apps/docsite/src/templateDemoContent/demoContent.tsxindex 6d066305e7..0e931b3ef6 100644--- a/apps/docsite/src/templateDemoContent/demoContent.tsx+++ b/apps/docsite/src/templateDemoContent/demoContent.tsx@@ -2,25 +2,29 @@/*** @file Docs-only demo content that catalog templates may show inside real- * Astryx components: a lightweight playing card's face and back.- * @input A rank and suit, and whether the card lies face down.- * @output Token-styled card contents sized to fill their container.+ * Astryx components: a playing card's face and back, and a hint under a demo.+ * @input A rank and suit, and whether the card lies face down; a hint's text.+ * @output Token-styled card contents sized to fill their container, and a+ * centered demo with a muted hint line under it.* @position The one demo-content module templates import, as* `@astryx-docs/demo-content` (mapped by the docsite, sandbox, template* viewer, test, and CLI type-check configs). It is not part of any package:* every copy and every surface that hands out template source replace each- * element imported from it with a generic `<Text>` placeholder (the CLI's- * `replaceDemoContent`), so only live previews ever render it. Elements are- * used with no children, and each prop is a literal or a variable the- * template also reads elsewhere, so that replacement stays safe.+ * element imported from it (the CLI's `replaceDemoContent`), so only live+ * previews ever render it. An element with no children becomes a generic+ * `<Text>` placeholder. `DemoHint` wraps one element and is removed, so its+ * child stays as written. Each prop is a literal or a variable the template+ * also reads elsewhere, so that replacement stays safe.*/+import type {ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';+import {Text} from '@astryxdesign/core/Text';import {colorVars,+ fontWeightVars,radiusVars,spacingVars,- textSizeVars,typographyVars,} from '@astryxdesign/core/theme/tokens.stylex';@@ -33,6 +37,100 @@ const SUIT_SYMBOLS = {export type PlayingCardSuit = keyof typeof SUIT_SYMBOLS;+const RANK_NAMES: Record<string, string> = {+ A: 'Ace',+ J: 'Jack',+ Q: 'Queen',+ K: 'King',+};++/**+ * Where each pip of a number card sits, as percentages of the pip field:+ * `[left, top]`. These are the traditional layouts. A pip below the middle is+ * printed upside down, as on a real card.+ */+const PIP_LAYOUTS: Record<string, ReadonlyArray<readonly [number, number]>> = {+ '2': [+ [50, 0],+ [50, 100],+ ],+ '3': [+ [50, 0],+ [50, 50],+ [50, 100],+ ],+ '4': [+ [0, 0],+ [100, 0],+ [0, 100],+ [100, 100],+ ],+ '5': [+ [0, 0],+ [100, 0],+ [50, 50],+ [0, 100],+ [100, 100],+ ],+ '6': [+ [0, 0],+ [100, 0],+ [0, 50],+ [100, 50],+ [0, 100],+ [100, 100],+ ],+ '7': [+ [0, 0],+ [100, 0],+ [50, 25],+ [0, 50],+ [100, 50],+ [0, 100],+ [100, 100],+ ],+ '8': [+ [0, 0],+ [100, 0],+ [50, 25],+ [0, 50],+ [100, 50],+ [50, 75],+ [0, 100],+ [100, 100],+ ],+ '9': [+ [0, 0],+ [100, 0],+ [0, 33.3],+ [100, 33.3],+ [50, 50],+ [0, 66.7],+ [100, 66.7],+ [0, 100],+ [100, 100],+ ],+ '10': [+ [0, 0],+ [100, 0],+ [50, 16.7],+ [0, 33.3],+ [100, 33.3],+ [0, 66.7],+ [100, 66.7],+ [50, 83.3],+ [0, 100],+ [100, 100],+ ],+};++/** A crown or cap for each court card, drawn in a 24 × 16 box. */+const COURT_HEADDRESS: Record<string, string> = {+ K: 'M2 15 L3.5 4 L8 9 L12 1.5 L16 9 L20.5 4 L22 15 Z',+ Q: 'M3 15 L4 6 L9 10.5 L12 4 L15 10.5 L20 6 L21 15 Z',+ J: 'M2 15 L4 9 C6 4 18 4 20 9 L22 15 Z M11 4.5 C12 1.5 15 0.5 18 1 C16 2 14 3.5 13 5 Z',+};+export interface PlayingCardContentsProps {/** The card's rank as printed in its corner: `A`, `2`–`10`, `J`, `Q`, `K`. */rank: string;@@ -42,8 +140,11 @@ export interface PlayingCardContentsProps {}/**- * A playing card: rank and suit in the corner and the suit at center, or its- * back when `faceDown`.+ * A playing card in real-card proportions (5 : 7). The face has its rank and+ * suit in the top-left corner and again, upside down, in the bottom-right+ * corner; number cards lay out their pips, aces show one large pip, and court+ * cards show a framed, two-headed portrait. `faceDown` shows the back. Every+ * size scales with the card's width, so give its container a width.*/export function PlayingCardContents({rank,@@ -52,64 +153,270 @@ export function PlayingCardContents({}: PlayingCardContentsProps) {if (faceDown) {return (- <span role="img" aria-label="Card back" {...stylex.props(styles.back)} />+ <span role="img" aria-label="Card back" {...stylex.props(styles.card)}>+ <span {...stylex.props(styles.back)} />+ </span>);}const symbol = SUIT_SYMBOLS[suit];+ const isRed = suit === 'hearts' || suit === 'diamonds';return (<spanrole="img"- aria-label={`${rank} of ${suit}`}+ aria-label={`${RANK_NAMES[rank] ?? rank} of ${suit}`}+ {...stylex.props(styles.card, styles.face, isRed && styles.red)}>+ <CornerIndex rank={rank} symbol={symbol} />+ <CardCenter rank={rank} symbol={symbol} isRed={isRed} />+ <CornerIndex rank={rank} symbol={symbol} isUpsideDown />+ </span>+ );+}++function CornerIndex({+ rank,+ symbol,+ isUpsideDown = false,+}: {+ rank: string;+ symbol: string;+ isUpsideDown?: boolean;+}) {+ return (+ <span+ aria-hidden{...stylex.props(- styles.face,- (suit === 'hearts' || suit === 'diamonds') && styles.red,+ styles.corner,+ isUpsideDown ? styles.cornerEnd : styles.cornerStart,)}>- <span aria-hidden {...stylex.props(styles.corner)}>- <span>{rank}</span>- <span>{symbol}</span>+ <span {...stylex.props(styles.cornerRank)}>{rank}</span>+ <span {...stylex.props(styles.cornerSuit)}>{symbol}</span>+ </span>+ );+}++function CardCenter({+ rank,+ symbol,+ isRed,+}: {+ rank: string;+ symbol: string;+ isRed: boolean;+}) {+ const headdress = COURT_HEADDRESS[rank];+ if (headdress != null) {+ return (+ <span+ aria-hidden+ {...stylex.props(styles.court, isRed && styles.courtRed)}>+ <CourtHalf rank={rank} symbol={symbol} headdress={headdress} />+ <CourtHalf+ rank={rank}+ symbol={symbol}+ headdress={headdress}+ isUpsideDown+ /></span>- <span aria-hidden {...stylex.props(styles.center)}>+ );+ }+ const pips = PIP_LAYOUTS[rank];+ if (pips == null) {+ return (+ <span aria-hidden {...stylex.props(styles.acePip)}>{symbol}</span>+ );+ }+ return (+ <span aria-hidden {...stylex.props(styles.pipField)}>+ {pips.map(([left, top]) => (+ <span+ key={`${left}-${top}`}+ {...stylex.props(+ styles.pip,+ styles.pipAt(`${left}%`, `${top}%`),+ top > 50 && styles.upsideDown,+ )}>+ {symbol}+ </span>+ ))}+ </span>+ );+}++function CourtHalf({+ rank,+ symbol,+ headdress,+ isUpsideDown = false,+}: {+ rank: string;+ symbol: string;+ headdress: string;+ isUpsideDown?: boolean;+}) {+ return (+ <span+ {...stylex.props(styles.courtHalf, isUpsideDown && styles.upsideDown)}>+ <svg viewBox="0 0 24 16" {...stylex.props(styles.headdress)}>+ <path d={headdress} fill="currentColor" />+ </svg>+ <span {...stylex.props(styles.courtRank)}>+ {rank}+ <span {...stylex.props(styles.courtSuit)}>{symbol}</span>+ </span></span>);}+export interface DemoHintProps {+ /** One short sentence: what to do with the demo to see what it shows. */+ text: string;+ /** The demo: one element. */+ children: ReactNode;+}++/**+ * Center a demo and put a muted line under it that tells the reader what to+ * try. Copies drop the hint and keep the demo as written.+ */+export function DemoHint({text, children}: DemoHintProps) {+ return (+ <div {...stylex.props(styles.hinted)}>+ {children}+ <Text type="supporting" color="secondary" xstyle={styles.hint}>+ {text}+ </Text>+ </div>+ );+}++// A card face is a picture of a physical object, so it does not mirror in+// right-to-left text: its corners and pips use physical sides.const styles = stylex.create({- face: {+ card: {position: 'relative',- display: 'grid',- placeItems: 'center',+ display: 'block',aspectRatio: '5 / 7',inlineSize: '100%',+ containerType: 'inline-size',+ userSelect: 'none',+ },+ face: {color: colorVars['--color-text-primary'],fontFamily: typographyVars['--font-family-heading'],- userSelect: 'none',},red: {color: colorVars['--color-text-red'],},corner: {position: 'absolute',- insetBlockStart: 0,- insetInlineStart: 0,display: 'flex',flexDirection: 'column',alignItems: 'center',- fontSize: textSizeVars['--font-size-lg'],+ minInlineSize: '12cqi',+ lineHeight: 1,+ },+ cornerStart: {+ top: '3cqi',+ left: '3cqi',+ },+ cornerEnd: {+ bottom: '3cqi',+ right: '3cqi',+ transform: 'rotate(180deg)',+ },+ cornerRank: {+ fontSize: '14cqi',+ fontWeight: fontWeightVars['--font-weight-semibold'],+ letterSpacing: '-0.05em',+ },+ cornerSuit: {+ fontSize: '12cqi',+ },+ acePip: {+ position: 'absolute',+ inset: 0,+ display: 'grid',+ placeItems: 'center',+ fontSize: '48cqi',+ lineHeight: 1,+ },+ pipField: {+ position: 'absolute',+ top: '16%',+ bottom: '16%',+ left: '30%',+ right: '30%',+ },+ pip: {+ position: 'absolute',+ fontSize: '18cqi',lineHeight: 1,- fontWeight: 600,+ translate: '-50% -50%',},- center: {- fontSize: textSizeVars['--font-size-4xl'],+ pipAt: (left: string, top: string) => ({left, top}),+ upsideDown: {+ rotate: '180deg',+ },+ court: {+ position: 'absolute',+ top: '13%',+ bottom: '13%',+ left: '17%',+ right: '17%',+ display: 'grid',+ gridTemplateRows: '1fr 1fr',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: 'currentColor',+ borderRadius: radiusVars['--radius-inner'],+ backgroundColor: colorVars['--color-background-gray'],+ overflow: 'hidden',+ },+ courtRed: {+ backgroundColor: colorVars['--color-background-red'],+ },+ courtHalf: {+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '1cqi',+ paddingBlockStart: '2cqi',+ },+ headdress: {+ inlineSize: '28cqi',+ blockSize: 'auto',+ },+ courtRank: {+ display: 'flex',+ alignItems: 'baseline',+ gap: '1cqi',+ fontSize: '22cqi',+ fontWeight: fontWeightVars['--font-weight-semibold'],lineHeight: 1,},+ courtSuit: {+ fontSize: '14cqi',+ },back: {- display: 'block',- aspectRatio: '5 / 7',- inlineSize: '100%',+ position: 'absolute',+ inset: 0,borderRadius: radiusVars['--radius-inner'],backgroundColor: colorVars['--color-accent'],- backgroundImage: `repeating-linear-gradient(45deg, transparent 0 ${spacingVars['--spacing-1']}, ${colorVars['--color-accent-muted']} ${spacingVars['--spacing-1']} ${spacingVars['--spacing-2']})`,+ backgroundImage: `repeating-linear-gradient(45deg, transparent 0 3cqi, color-mix(in srgb, ${colorVars['--color-on-accent']} 22%, transparent) 3cqi 4cqi), repeating-linear-gradient(-45deg, transparent 0 3cqi, color-mix(in srgb, ${colorVars['--color-on-accent']} 22%, transparent) 3cqi 4cqi)`,+ boxShadow: `inset 0 0 0 4cqi ${colorVars['--color-accent']}, inset 0 0 0 5cqi ${colorVars['--color-on-accent']}`,+ },+ hinted: {+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: spacingVars['--spacing-3'],+ },+ hint: {+ maxInlineSize: '40ch',+ textAlign: 'center',+ textWrap: 'balance',},});diff --git a/docs/architecture/template-authoring.md b/docs/architecture/template-authoring.mdindex ad20fbdd18..ca499a753b 100644--- a/docs/architecture/template-authoring.md+++ b/docs/architecture/template-authoring.md@@ -151,10 +151,12 @@ authoring check; it does not replace runtime catalog validation.purpose. The contributor guide owns the exact root-component recipe.- **INV8 — Copying is a self-contained snapshot.** The emitted source belongs to theadopting project. Repository-only demo assets and demo-content elements are- replaced with generic placeholders during copy; `template copy` and the- docsite's shadcn Install item are copies. `template show` returns the same- source a copy writes. Other example source handed out without a copy- replaces only demo-content elements. Live previews render the originals.+ replaced with generic placeholders, and docs-only presentation wrappers are+ removed, during copy; `template copy` and the docsite's shadcn Install item+ are copies. `template show` returns the same source a copy writes. Other+ example source handed out without a copy replaces only demo-content elements+ and removes docs-only presentation wrappers. Live previews render the+ originals.Later catalog updates do not mutate copied projects.- **INV9 — Catalog values may evolve.** Template ids, labels, metadata, categories,example data, and starter source are mutable catalog data underdiff --git a/docs/specs/AST-028/spec.md b/docs/specs/AST-028/spec.mdindex 9b0742291a..e8e7560828 100644--- a/docs/specs/AST-028/spec.md+++ b/docs/specs/AST-028/spec.md@@ -123,7 +123,12 @@ concerns require a separate contract.replace repository-only demo assets (FR7–FR10) and every demo-content elementwith generic placeholders, keeping the outer component and its props, and thecopied source MUST NOT reference the repository-only code that defines a- demo-content element. The copies are `template copy` and the docsite's shadcn+ demo-content element. A demo-content wrapper that only adds docs-only+ presentation around a real component, such as a usage hint, is removed rather+ than replaced: the copy keeps the wrapped component and its props as if the+ wrapper were absent, and `demoContentReplaced` counts only the placeholders,+ since only they need the consumer's own content.+ The copies are `template copy` and the docsite's shadcnInstall item, which writes the example into the consumer's project. The copyreceipt (FR11) MUST count the replaced elements as `demoContentReplaced`.Until the next minor, the persisted `.astryx/<item>.json` receipt keeps its@@ -164,16 +169,14 @@ published location. The portable source keeps the root-relative fixture path.The CLI copy path currently recognizes Astryx's fixture namespace and replacesimages with a self-contained SVG placeholder. It strips recognized video sources-to an empty string rather than place image data in a video element. This behavior-established the core preview-versus-copy split, while this record adds the-previously unwritten requirements for why assets are fixtures, which references-may be transformed, what a safe fallback means, how unsupported formats fail,-and why icons are separate.+to an empty string rather than place image data in a video element.`template copy` and `template show` replace each demo-content element (FR13)with a `<Text>Card content</Text>` placeholder, import Astryx's `Text` for itwhen the source does not already import it, and remove the demo-content import.-Both responses report the count as `demoContentReplaced`.+They remove a docs-only presentation wrapper, such as a usage hint, and keep+the component it wraps. Both responses report the placeholder count as+`demoContentReplaced`.`astryx template <name> --skeleton` outlines that replaced source and listsits components. `astryx component <Name> --showcase` prints the showcase sourcewith each demo-content element replaced and its fixture media kept. The shadcn@@ -182,21 +185,17 @@ fixture media both replaced, each as a visibly marked placeholder, and itsregistry item description says how many were replaced. Its`.astryx/<item>.json` receipt keeps the v2 shape until CLN-0027.-This specification-only change alters no package, template, asset, preview,-runtime, or public CLI behavior. Remaining implementation and verification-follow separately.-## Verification-| Contract | Verification | Representative cases | Failure expectation |-| -------- | -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| FR1–FR3 | Template-source and copy-boundary tests | built-in page, block, integration template; Astryx fixture; consumer path; third-party URL | Copied source retains a preview runtime dependency or rewrites consumer-owned content |-| FR4–FR6 | Real preview request and rendered-media checks | local, docsite, main sandbox, PR preview; image and video; missing fixture | Representative media 404s, resolves to another file, or silently uses the wrong kind |-| FR7–FR8 | End-to-end CLI copy tests | image-only, video-only, and no-media template | Generated source retains `/template-assets/` or does not parse/render without setup |-| FR9–FR10 | Classifier and mixed-source mutation tests | upper/lower case; multi-dot filename; image poster plus video; unknown suffix | Last suffix is misread, image data enters video, or an unsupported kind is guessed |-| FR11 | Human and structured copy-receipt tests | no replacement; one image; mixed media | The consumer is not told what must be replaced or is told assets were installed |-| FR12 | Scope guard tests and review | Icon prop, registry icon, imported SVG component, static hero image | Icon behavior is silently folded into the static-fixture transformer |-| FR13 | End-to-end CLI copy, show, and `--showcase` tests, a shadcn install test, and a real preview check | a motion or gesture example whose `Card` wraps one demo-content element; one with two; an example with none; its `template show` response; its `--showcase` output; its shadcn install into a project, its registry item description, and its `.astryx/<item>.json` receipt; its live preview | Copied, shown, or installed output still references a demo-content element, the code that defines it, or `/template-assets/`; `--showcase` output references a demo-content element or changes its fixture media; the outer component or its props change; the copy receipt or the `template show` response omits or miscounts `demoContentReplaced`; a shadcn install leaves a replaced element or media reference without a visibly marked placeholder, or its registry item description does not disclose the replacement; the installed `.astryx/<item>.json` receipt gains a field or fails the released strict v2 reader before CLN-0027; or the live preview stops rendering the original |+| Contract | Verification | Representative cases | Failure expectation |+| -------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1–FR3 | Template-source and copy-boundary tests | built-in page, block, integration template; Astryx fixture; consumer path; third-party URL | Copied source retains a preview runtime dependency or rewrites consumer-owned content |+| FR4–FR6 | Real preview request and rendered-media checks | local, docsite, main sandbox, PR preview; image and video; missing fixture | Representative media 404s, resolves to another file, or silently uses the wrong kind |+| FR7–FR8 | End-to-end CLI copy tests | image-only, video-only, and no-media template | Generated source retains `/template-assets/` or does not parse/render without setup |+| FR9–FR10 | Classifier and mixed-source mutation tests | upper/lower case; multi-dot filename; image poster plus video; unknown suffix | Last suffix is misread, image data enters video, or an unsupported kind is guessed |+| FR11 | Human and structured copy-receipt tests | no replacement; one image; mixed media | The consumer is not told what must be replaced or is told assets were installed |+| FR12 | Scope guard tests and review | Icon prop, registry icon, imported SVG component, static hero image | Icon behavior is silently folded into the static-fixture transformer |+| FR13 | End-to-end CLI copy, show, and `--showcase` tests, a shadcn install test, and a real preview check | a motion or gesture example whose `Card` wraps one demo-content element; one with two; one whose `Card` sits in a docs-only hint wrapper; an example with none; its `template show` response; its `--showcase` output; its shadcn install into a project, its registry item description, and its `.astryx/<item>.json` receipt; its live preview | Copied, shown, or installed output still references a demo-content element or keeps a docs-only wrapper or its hint text (a hinted example copies to exactly the `Card` plus its placeholder), the code that defines it, or `/template-assets/`; `--showcase` output references a demo-content element or changes its fixture media; the outer component or its props change; the copy receipt or the `template show` response omits or miscounts `demoContentReplaced`; a shadcn install leaves a replaced element or media reference without a visibly marked placeholder, or its registry item description does not disclose the replacement; the installed `.astryx/<item>.json` receipt gains a field or fails the released strict v2 reader before CLN-0027; or the live preview stops rendering the original |### Completion criteria@@ -265,7 +264,9 @@ Motion and gesture examples can show docs-only demo contents, such as aplaying-card face, inside a real Astryx component without a second copy of eachexample to maintain. Those contents are fixtures in the DEC-1 sense: copyreplaces each demo-content element with a generic placeholder and keeps the-outer component, and previews render the originals (DEC-2). The shadcn Install+outer component, removes a wrapper that only adds docs-only presentation (such+as a usage hint) and keeps what it wraps, and previews render the originals+(DEC-2). The shadcn Installitem writes the example into the consumer's project, so it is a copy andreplaces fixture media and demo-content elements as `template copy` does.`template show` returns the same source a copy writes; other surfaces thatdiff --git a/docs/specs/AST-033/spec.md b/docs/specs/AST-033/spec.mdindex f2a199aee9..399c406e75 100644--- a/docs/specs/AST-033/spec.md+++ b/docs/specs/AST-033/spec.md@@ -284,7 +284,10 @@ for each bug.carries it after the demo-content element replacement of `spec:AST-028`FR13: each demo-content element becomes a generic placeholder, the sourcekeeps no reference to the code that defines it, and the outer component keeps- its props and behavior. Surfaces that only hand out source run that+ its props and behavior. A demo-content wrapper that only adds docs-only+ presentation around a real component, such as a usage hint, is removed rather+ than replaced: the source keeps the wrapped component and its props as if the+ wrapper were absent. Surfaces that only hand out source run thatreplacement alone, so each keeps its fixture media:the Code tab and its copy action; Open in Playground, which opens and runsthat replaced source, so the playground shows the placeholder; the Sandbox@@ -368,17 +371,17 @@ exact source already serving those public surfaces.## Verification-| Contract | Verification | Representative states | Mutation or failure expectation |-| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| FR1–FR3 | generator/data-extraction tests plus cross-projection inventory; search endpoint parity with `astryx search --json` | package, component, template, theme; gallery, sidebar, search, direct route, preview, playground | a local map changes membership or a canonical item fact, or availability and visibility collapse into one projection |-| FR4–FR6 | latest/canary generation and projection tests | stable package, canary-only package, ready/unready item, overview-hidden item, invalid integration metadata | latest exposes canary package docs, workspace-backed content is called release-pinned, a second readiness state appears, or projections disagree |-| FR7–FR9 | navigation-family checks plus real-browser navigation/history tests | direct link, modified click, new tab, deep link, primary selection, secondary tab/filter, canonicalization, Back/Forward | Docsite misclassifies a destination, canonical identity diverges, primary selections replace one another, or secondary state clutters history |-| FR10–FR12 | selection/transition tests plus real-browser visible-content checks | initial open, reopen, deep link, direct selection, pending previous/next, close, supersede, reject, unmount | header/body/actions disagree, stale content paints without its owning pending state, or obsolete selection work commits after supersession |-| FR13–FR15 | analytics schema and interaction tests with transport spies | navigation intent, successful/failed copy, cancel, URL restoration, render/effect, duplicate activation | event names/properties drift, free-form/high-cardinality data is logged, a passive lifecycle emits, success logs on failure, or one action emits twice |-| FR16 | production-browser playground isolation and recovery tests | direct load, reload, hostile navigation, storage and parent-DOM denial | preview code reaches parent/storage or trusted recovery restores stale source/theme |-| FR17–FR21 | exact-head Vercel build, route/asset probes, metadata checks, and Pages landing contract | production and PR Preview; Storybook manager/frame; Sandbox route/embed; old root/deep path; desktop/mobile; light/dark | one app is absent or stale, a direct asset/route fails, metadata claims the wrong owner, identity drifts, or Pages hosts more than the compatibility page |-| FR22 | `e2e/blog-live-examples.spec.ts` (real-browser post, plain-text route, feed, sitemap, and index checks) and `blog-live-examples.test.tsx` (fence rule, static fallback, fixture listing, runner) | a post with a `tsx live` block; that post's plain-text route; a block importing a post-local asset; a block that fails to compile or throws; live fences in a blockquote, a list item, and quoted inside a longer fence | the live block does not run in the browser, the text route shows anything but the source fallback for a fence the page runs, a post-local import fails to resolve, a broken example breaks the page outside its frame, or the feed, sitemap, or index lists the fixture |-| FR23 | Output checks for each surface plus real-browser live-example check | a motion or gesture example whose `Card` wraps a demo-content element; its Code tab and copied text; its Open in Playground source; its Sandbox code view and copied source; its MCP `get()` component and template results; its shadcn registry item and the `.astryx/<item>.json` receipt it installs; an example with fixture media; an integration-package block's displayed code; its live preview | any of those surfaces still references a demo-content element or the code that defines it; the outer component or its props change; fixture media changes on a surface that only hands out source; the shadcn registry item or an integration-package block's displayed code still references `/template-assets/`, or the installed receipt is not the released v2 shape; or the live preview stops rendering the original |+| Contract | Verification | Representative states | Mutation or failure expectation |+| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1–FR3 | generator/data-extraction tests plus cross-projection inventory; search endpoint parity with `astryx search --json` | package, component, template, theme; gallery, sidebar, search, direct route, preview, playground | a local map changes membership or a canonical item fact, or availability and visibility collapse into one projection |+| FR4–FR6 | latest/canary generation and projection tests | stable package, canary-only package, ready/unready item, overview-hidden item, invalid integration metadata | latest exposes canary package docs, workspace-backed content is called release-pinned, a second readiness state appears, or projections disagree |+| FR7–FR9 | navigation-family checks plus real-browser navigation/history tests | direct link, modified click, new tab, deep link, primary selection, secondary tab/filter, canonicalization, Back/Forward | Docsite misclassifies a destination, canonical identity diverges, primary selections replace one another, or secondary state clutters history |+| FR10–FR12 | selection/transition tests plus real-browser visible-content checks | initial open, reopen, deep link, direct selection, pending previous/next, close, supersede, reject, unmount | header/body/actions disagree, stale content paints without its owning pending state, or obsolete selection work commits after supersession |+| FR13–FR15 | analytics schema and interaction tests with transport spies | navigation intent, successful/failed copy, cancel, URL restoration, render/effect, duplicate activation | event names/properties drift, free-form/high-cardinality data is logged, a passive lifecycle emits, success logs on failure, or one action emits twice |+| FR16 | production-browser playground isolation and recovery tests | direct load, reload, hostile navigation, storage and parent-DOM denial | preview code reaches parent/storage or trusted recovery restores stale source/theme |+| FR17–FR21 | exact-head Vercel build, route/asset probes, metadata checks, and Pages landing contract | production and PR Preview; Storybook manager/frame; Sandbox route/embed; old root/deep path; desktop/mobile; light/dark | one app is absent or stale, a direct asset/route fails, metadata claims the wrong owner, identity drifts, or Pages hosts more than the compatibility page |+| FR22 | `e2e/blog-live-examples.spec.ts` (real-browser post, plain-text route, feed, sitemap, and index checks) and `blog-live-examples.test.tsx` (fence rule, static fallback, fixture listing, runner) | a post with a `tsx live` block; that post's plain-text route; a block importing a post-local asset; a block that fails to compile or throws; live fences in a blockquote, a list item, and quoted inside a longer fence | the live block does not run in the browser, the text route shows anything but the source fallback for a fence the page runs, a post-local import fails to resolve, a broken example breaks the page outside its frame, or the feed, sitemap, or index lists the fixture |+| FR23 | Output checks for each surface plus real-browser live-example check | a motion or gesture example whose `Card` wraps a demo-content element; one whose `Card` sits in a docs-only hint wrapper; its Code tab and copied text; its Open in Playground source; its Sandbox code view and copied source; its MCP `get()` component and template results; its shadcn registry item and the `.astryx/<item>.json` receipt it installs; an example with fixture media; an integration-package block's displayed code; its live preview | any of those surfaces still references a demo-content element or the code that defines it, or keeps a docs-only wrapper or its hint text; the outer component or its props change; fixture media changes on a surface that only hands out source; the shadcn registry item or an integration-package block's displayed code still references `/template-assets/`, or the installed receipt is not the released v2 shape; or the live preview stops rendering the original |## Decision logdiff --git a/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.test.tsx b/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.test.tsxindex 6fcea8819b..d9c2da4bab 100644--- a/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.test.tsx+++ b/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.test.tsx@@ -10,7 +10,7 @@*/import * as stylex from '@stylexjs/stylex';-import {act} from 'react';+import {act, type ReactNode} from 'react';import {createRoot, type Root} from 'react-dom/client';import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest';import {focusOutlineStyles} from '@astryxdesign/core/utils';@@ -19,6 +19,7 @@ import UsePressFeedbackHookUsage from './usePressFeedbackHookUsage';// The docs-only card is not what this checks; stand it in with a plain// element so the test needs no StyleX compilation.vi.mock('@astryx-docs/demo-content', () => ({+ DemoHint: ({children}: {children: ReactNode}) => children,PlayingCardContents: ({faceDown}: {faceDown?: boolean}) => (<span>{faceDown === true ? 'back' : 'face'}</span>),diff --git a/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.tsxindex e6e2f61757..e74f53d29c 100644--- a/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.tsx+++ b/packages/cli/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.tsx@@ -9,7 +9,7 @@ import {focusOutlineStyles,interactionOverlayStyles,} from '@astryxdesign/core/utils';-import {PlayingCardContents} from '@astryx-docs/demo-content';+import {DemoHint, PlayingCardContents} from '@astryx-docs/demo-content';export default function UsePressFeedbackHookUsage() {const pressable = usePressFeedback();@@ -17,25 +17,28 @@ export default function UsePressFeedbackHookUsage() {const flip = () => setIsFaceUp(faceUp => !faceUp);return (- <Card- {...pressable}- xstyle={[- interactionOverlayStyles.backgroundImage,- focusOutlineStyles.focusVisible,- ]}- width={160}- role="button"- tabIndex={0}- aria-label="Flip card"- aria-pressed={!isFaceUp}- onClick={flip}- onKeyDown={event => {- if (event.key === 'Enter' || event.key === ' ') {- event.preventDefault();- flip();- }- }}>- <PlayingCardContents rank="Q" suit="hearts" faceDown={!isFaceUp} />- </Card>+ <DemoHint text="Press and hold the card to see the press; tap, click, Enter or Space to flip it.">+ <Card+ {...pressable}+ xstyle={[+ interactionOverlayStyles.backgroundImage,+ focusOutlineStyles.focusVisible,+ ]}+ width={120}+ padding={1}+ role="button"+ tabIndex={0}+ aria-label="Flip card"+ aria-pressed={!isFaceUp}+ onClick={flip}+ onKeyDown={event => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault();+ flip();+ }+ }}>+ <PlayingCardContents rank="Q" suit="hearts" faceDown={!isFaceUp} />+ </Card>+ </DemoHint>);}diff --git a/packages/cli/foundation/discovery/template-adapter.demo-content.test.mjs b/packages/cli/foundation/discovery/template-adapter.demo-content.test.mjsindex 36056c53d3..278865ff08 100644--- a/packages/cli/foundation/discovery/template-adapter.demo-content.test.mjs+++ b/packages/cli/foundation/discovery/template-adapter.demo-content.test.mjs@@ -169,6 +169,88 @@ describe('replaceDemoContent', () => {});});+ it('removes a wrapper, keeping the element it wraps at the indentation it would have without it', () => {+ const source =+ CARD ++ `import {DemoHint, PlayingCardContents} from '${DEMO_CONTENT_MODULE}';\n` ++ 'export default function Example() {\n' ++ ' return (\n' ++ ' <DemoHint text="Press the card.">\n' ++ ' <Card\n' ++ ' width={120}>\n' ++ ' <PlayingCardContents rank="Q" suit="hearts" />\n' ++ ' </Card>\n' ++ ' </DemoHint>\n' ++ ' );\n' ++ '}\n';+ expect(replaceDemoContent(source)).toEqual({+ source:+ CARD ++ "import {Text} from '@astryxdesign/core/Text';\n" ++ 'export default function Example() {\n' ++ ' return (\n' ++ ' <Card\n' ++ ' width={120}>\n' ++ ' <Text>Card content</Text>\n' ++ ' </Card>\n' ++ ' );\n' ++ '}\n',+ demoContentReplaced: 1,+ });+ });++ it('removes a wrapper with no placeholder and no Text import when it wraps no demo element', () => {+ const source =+ CARD ++ `import {DemoHint} from '${DEMO_CONTENT_MODULE}';\n` ++ 'export const a = <DemoHint text="Hover it."><Card /></DemoHint>;\n';+ expect(replaceDemoContent(source)).toEqual({+ source: CARD + 'export const a = <Card />;\n',+ demoContentReplaced: 0,+ });+ });++ it('keeps the whitespace of a multiline string inside the element a wrapper holds', () => {+ const source =+ `import {DemoHint} from '${DEMO_CONTENT_MODULE}';\n` ++ 'const a = (\n' ++ ' <DemoHint text="Read it.">\n' ++ ' <pre>\n' ++ ' {`one\n' ++ ' two`}\n' ++ ' </pre>\n' ++ ' </DemoHint>\n' ++ ');\n';+ expect(replaceDemoContent(source).source).toBe(+ 'const a = (\n' ++ ' <pre>\n' ++ ' {`one\n' ++ ' two`}\n' ++ ' </pre>\n' ++ ');\n',+ );+ });++ it.each([+ [+ 'a wrapper with two elements',+ `import {DemoHint} from '${DEMO_CONTENT_MODULE}';\nconst a = <DemoHint text="x"><b /><i /></DemoHint>;\n`,+ /has children other than one element/u,+ ],+ [+ 'a wrapper with text beside its element',+ `import {DemoHint} from '${DEMO_CONTENT_MODULE}';\nconst a = <DemoHint text="x">Try it <b /></DemoHint>;\n`,+ /has children other than one element/u,+ ],+ [+ 'a wrapper prop whose variable nothing else reads',+ `import {DemoHint} from '${DEMO_CONTENT_MODULE}';\nconst hint = 'Press it.';\nconst a = <DemoHint text={hint}><b /></DemoHint>;\n`,+ /<DemoHint> reads hint, and nothing else in the file reads it/u,+ ],+ ])('fails closed on %s', (_label, source, reason) => {+ expect(() => replaceDemoContent(source)).toThrow(reason);+ });+it.each([['a spread prop',@@ -283,16 +365,20 @@ describe('catalog blocks', () => {expect(files.length).toBeGreaterThan(100);});- it('copies the usePressFeedback block as one Text placeholder in its Card, with no branch on the face', () => {+ it('copies the usePressFeedback block as its Card with one Text placeholder, no hint and no branch on the face', () => {const file = files.find(f => f.endsWith('/usePressFeedbackHookUsage.tsx'));expect(file).toBeDefined();- const {source, demoContentReplaced} = replaceTemplateDemos(- fs.readFileSync(/** @type {string} */ (file), 'utf8'),- );+ const original = fs.readFileSync(/** @type {string} */ (file), 'utf8');+ const hint = /<DemoHint text="([^"]+)">/u.exec(original)?.[1];+ expect(hint).toBeDefined();+ const {source, demoContentReplaced} = replaceTemplateDemos(original);expect(demoContentReplaced).toBe(1);+ expect(source).toContain(' return (\n <Card\n {...pressable}');expect(source).toContain(- ' }}>\n <Text>Card content</Text>\n </Card>',+ ' }}>\n <Text>Card content</Text>\n </Card>\n );',);+ expect(source).not.toContain('DemoHint');+ expect(source).not.toContain(/** @type {string} */ (hint));expect(source).not.toMatch(/\?\s*\(/u);});diff --git a/packages/cli/foundation/discovery/template-adapter.mjs b/packages/cli/foundation/discovery/template-adapter.mjsindex 778a8e1dd1..af4b22975b 100644--- a/packages/cli/foundation/discovery/template-adapter.mjs+++ b/packages/cli/foundation/discovery/template-adapter.mjs@@ -409,7 +409,11 @@ const TEXT_ALIAS = 'AstryxText';/*** Replace each JSX element imported from {@link DEMO_CONTENT_MODULE} with a* generic `<Text>` placeholder and remove that import, so emitted source never- * depends on content only Astryx's previews provide.+ * depends on content only Astryx's previews provide. An element that wraps one+ * element, such as a hint shown under a demo, is removed instead: its child+ * takes its place, with the indentation the child would have had without it.+ * `demoContentReplaced` counts the placeholders, because only they need the+ * consumer's own content.** Every check resolves a name to its binding through the module's scope, so a* local declaration or parameter with the same name never counts as the same@@ -419,12 +423,12 @@ const TEXT_ALIAS = 'AstryxText';* writes the name `Text`.** Only a plain static use is replaced: a named import used only as a JSX tag- * whose children, if any, are whitespace, and whose props are literal values or+ * whose children are whitespace or one element, and whose props are literal values or* read only bindings that code outside the replaced elements still reads. So* `faceDown={!isOpen}` is safe when the same `isOpen` is also read elsewhere.* Anything else (a namespace or type import, a re-export, a dynamic import, the* element used as a value or a type, a spread or computed prop, a prop whose- * binding nothing else reads, children) throws, naming the element, rather than+ * binding nothing else reads, other children) throws, naming the element, rather than* leaving a reference behind, leaving a binding unused, or dropping code the* rest of the file relies on. Source that never names the module is returned* as is.@@ -520,6 +524,13 @@ export function replaceDemoContent(source) {},});+ const wrappers = elements.filter(+ element => wrappedElement(element.node) !== null,+ );+ if (wrappers.length > 0) {+ return replaceDemoContent(unwrapDemoWrappers(source, wrappers));+ }+/** @param {any} node */const isReplaced = node =>elements.some(@@ -638,14 +649,147 @@ function uniqueName(base, written) {return name;}+/**+ * Replace each outermost demo-content wrapper with the element it wraps.+ * Wrappers inside a kept child go on the next pass, when they are outermost.+ * Throws when a wrapper's prop reads a binding that nothing outside the+ * wrappers' opening tags reads, so the removal would leave it unused.+ * @param {string} source+ * @param {any[]} wrappers - Element paths whose element wraps one element.+ * @returns {string}+ */+function unwrapDemoWrappers(source, wrappers) {+ /** @param {any} node */+ const isInWrapperTag = node =>+ wrappers.some(+ wrapper =>+ wrapper.node.openingElement.start <= node.start &&+ node.end <= wrapper.node.openingElement.end,+ );+ for (const wrapper of wrappers) {+ for (const variable of staticPropReads(wrapper.node)) {+ const binding = wrapper.scope.getBinding(variable);+ if (!binding || isExportedDeclaration(binding)) continue;+ if (+ binding.referencePaths.every((/** @type {any} */ ref) =>+ isInWrapperTag(ref.node),+ )+ ) {+ throw unsafeDemoContent(+ `<${wrapper.node.openingElement.name.name}> reads ${variable}, and nothing else in the file reads it, so the copy would leave it unused`,+ );+ }+ }+ }+ const outermost = wrappers.filter(+ wrapper =>+ !wrappers.some(+ other =>+ other !== wrapper &&+ other.node.start <= wrapper.node.start &&+ wrapper.node.end <= other.node.end,+ ),+ );+ let output = source;+ for (const wrapper of outermost.sort((a, b) => b.node.start - a.node.start)) {+ output =+ output.slice(0, wrapper.node.start) ++ dedentedChild(source, wrapper) ++ output.slice(wrapper.node.end);+ }+ return output;+}++/**+ * The source of the element a wrapper holds, with each of its later lines+ * moved left by the indent the wrapper added. A line that starts inside a+ * string keeps its whitespace, because that whitespace is part of the value.+ * @param {string} source+ * @param {any} wrapper - An element path whose element wraps one element.+ * @returns {string}+ */+function dedentedChild(source, wrapper) {+ const child = /** @type {any} */ (wrappedElement(wrapper.node));+ /** @param {number} offset */+ const indentOfLine = offset => {+ const lineStart = source.lastIndexOf('\n', offset - 1) + 1;+ return /^[ \t]*/u.exec(source.slice(lineStart))?.[0].length ?? 0;+ };+ const depth = indentOfLine(child.start) - indentOfLine(wrapper.node.start);+ /** @type {any[]} */+ const strings = [];+ wrapper.traverse({+ 'StringLiteral|TemplateLiteral'(/** @type {any} */ path) {+ strings.push(path.node);+ },+ });+ const leadingIndent = new RegExp(`^[ \\t]{0,${Math.max(depth, 0)}}`, 'u');+ let lineStart = child.start;+ return source+ .slice(child.start, child.end)+ .split('\n')+ .map((line, index) => {+ const start = lineStart;+ lineStart += line.length + 1;+ if (+ index === 0 ||+ strings.some(string => string.start < start && start < string.end)+ ) {+ return line;+ }+ return line.replace(leadingIndent, '');+ })+ .join('\n');+}++/**+ * The one element a demo-content element wraps, or null when its children are+ * only whitespace. Throws for any other children.+ * @param {any} element+ * @returns {any}+ */+function wrappedElement(element) {+ const content = element.children.filter(+ (/** @type {any} */ child) =>+ !(child.type === 'JSXText' && child.value.trim() === ''),+ );+ if (content.length === 0) return null;+ if (+ content.length === 1 &&+ (content[0].type === 'JSXElement' || content[0].type === 'JSXFragment')+ ) {+ return content[0];+ }+ throw unsafeDemoContent(+ `<${element.openingElement.name.name}> has children other than one element`,+ );+}+/*** Throw unless a demo-content element can be replaced without dropping code:- * each prop a literal or a read of variables (see {@link isVariableRead}), and- * no children but whitespace.+ * each prop a literal or a read of variables (see {@link staticPropReads}),+ * and no children but whitespace.* @param {any} element* @returns {string[]} The variables its props read.*/function assertStaticDemoElement(element) {+ const variables = staticPropReads(element);+ for (const child of element.children) {+ if (child.type === 'JSXText' && child.value.trim() === '') continue;+ throw unsafeDemoContent(+ `<${element.openingElement.name.name}> has children`,+ );+ }+ return variables;+}++/**+ * Throw unless each prop of a demo-content element is a literal or a read of+ * variables (see {@link isVariableRead}).+ * @param {any} element+ * @returns {string[]} The variables its props read.+ */+function staticPropReads(element) {const name = element.openingElement.name.name;/** @type {string[]} */const variables = [];@@ -666,10 +810,6 @@ function assertStaticDemoElement(element) {`<${name}> prop ${attribute.name.name ?? ''} is not a literal value or a variable read`,);}- for (const child of element.children) {- if (child.type === 'JSXText' && child.value.trim() === '') continue;- throw unsafeDemoContent(`<${name}> has children`);- }return variables;}@@ -715,7 +855,7 @@ function isLiteralExpression(node) {/** @param {string} reason */function unsafeDemoContent(reason) {return new Error(- `Demo content from ${DEMO_CONTENT_MODULE} cannot be replaced safely: ${reason}. Use each element as a JSX tag with no children, and give each prop a literal or a variable the file also reads elsewhere.`,+ `Demo content from ${DEMO_CONTENT_MODULE} cannot be replaced safely: ${reason}. Use each element as a JSX tag with no children or with one element child, and give each prop a literal or a variable the file also reads elsewhere.`,);}