@astryxdesign/cli 0.7.9-canary.7d6481e → 0.7.9-canary.7e69f91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -499,7 +499,7 @@ Every response has a `type` discriminant. The full set is below (generated from
499
499
  | `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |
500
500
  | `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, package, command, basis, reason, alternatives, ...} (the start and each alternative name the package that owns the template), pages (search's closest templates), blocks and domain as SearchResultEntry[] (each naming its package), frame and foundation (Core component names), and hint {reason, commands} when thin. |
501
501
  | `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. The envelope's package is @astryxdesign/core. |
502
- | `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope's package names the same owning package. |
502
+ | `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the copied file names (relative to the component folder; owner modules copied beside it start with ../), whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope's package names the same owning package. |
503
503
  | `gap-report.categories` | The fixed gap category values and human-readable labels; when a loaded integration names its own issues URL, meta.destinations lists every destination ({to, default, issuesUrl}) and meta.ask tells an agent to ask the person. |
504
504
  | `gap-report.file` | An aggregate receipt: overall status, the selected package, issuesUrl (or null), deliveries in handler order, each {handlerType: project \| integration \| fallback, handler, audience, status, url, message}, and filedCount/routedOnlyCount totals; without --to, when a loaded integration names its own issues URL, destinations and ask as on gap-report.categories. |
505
505
  | `template.list` | The effective discovered TemplateListEntry[] for pages and blocks. A winning replacement entry includes optional `replaces`, naming the Core id omitted from the default list. |
@@ -271,7 +271,7 @@ useIsHydrating useIsHydrating hooks/useAnimatedLayout.doc.mjs hooks/useIsHydrati
271
271
  useIsomorphicLayoutEffect useIsomorphicLayoutEffect hooks/useAnimatedLayout.doc.mjs hooks/useIsomorphicLayoutEffect.ts
272
272
  useLayerDismissal useLayerDismissal Layer/Layer.doc.mjs Layer/useLayerDismissal.ts
273
273
  useLightbox useLightbox Lightbox/useLightbox.doc.mjs Lightbox/useLightbox.tsx
274
- useLinkComponent useLinkComponent Link/Link.doc.mjs Link/useLinkComponent.ts
274
+ useLinkComponent useLinkComponent Link/useLinkComponent.doc.mjs Link/useLinkComponent.ts
275
275
  useLinkify useLinkify Link/Link.doc.mjs Link/useLinkify.tsx
276
276
  useListFormatter useListFormatter i18n/InternationalizationProvider.doc.mjs i18n/useListFormatter.ts
277
277
  useMenuDrillIn useMenuDrillIn DropdownMenu/DropdownMenu.doc.mjs DropdownMenu/useMenuDrillIn.tsx
@@ -25,8 +25,24 @@
25
25
  *
26
26
  * @param {string} content
27
27
  * @param {string} [ownerPackage]
28
+ * @param {(importPath: string) => boolean} [keep] Imports to leave relative:
29
+ * the modules the copy carries in the same layout (see `sharedModulesOf`).
28
30
  */
29
- export function rewriteImports(content: string, ownerPackage?: string): string;
31
+ export function rewriteImports(content: string, ownerPackage?: string, keep?: (importPath: string) => boolean): string;
32
+ /**
33
+ * The modules a copy carries beside the component, in the package's own
34
+ * layout under the output directory (`spec:AST-110` FR4): each private
35
+ * attribute owner module the component imports, and every unexported StyleX
36
+ * module such a carried module imports, transitively. The component's own
37
+ * imports of them, and theirs of each other, stay relative.
38
+ *
39
+ * @param {string} srcRoot the owner package's source root
40
+ * @param {string} componentDir
41
+ * @param {string[]} componentFiles files of the component that are copied
42
+ * @returns {Map<string, string>} module path (relative to srcRoot, no
43
+ * extension) -> its file path relative to srcRoot
44
+ */
45
+ export function sharedModulesOf(srcRoot: string, componentDir: string, componentFiles: string[]): Map<string, string>;
30
46
  /**
31
47
  * Copy one component's source into the consumer project for customization,
32
48
  * rewriting escaping relative imports to the owner package's subpaths.
@@ -59,10 +59,16 @@ const DEFAULT_ISSUES_URL = 'https://github.com/meta/astryx/issues/new';
59
59
  *
60
60
  * @param {string} content
61
61
  * @param {string} [ownerPackage]
62
+ * @param {(importPath: string) => boolean} [keep] Imports to leave relative:
63
+ * the modules the copy carries in the same layout (see `sharedModulesOf`).
62
64
  */
63
- export function rewriteImports(content, ownerPackage = CORE_PACKAGE) {
65
+ export function rewriteImports(content, ownerPackage = CORE_PACKAGE, keep = () => false) {
64
66
  /** @param {string} importPath */
65
67
  const mapTarget = importPath => {
68
+ // A module the copy carries beside the component keeps its relative path.
69
+ if (keep(importPath)) {
70
+ return importPath;
71
+ }
66
72
  // Strip ALL leading `../` so a two-levels-up path never yields `<pkg>/..`.
67
73
  const rest = importPath.replace(/^(?:\.\.\/)+/, '');
68
74
  const parts = rest.split('/');
@@ -90,6 +96,153 @@ export function rewriteImports(content, ownerPackage = CORE_PACKAGE) {
90
96
  );
91
97
  }
92
98
 
99
+ /** A private data attribute's owner module (`architecture:public-component-api` INV23). */
100
+ const OWNER_MODULE = /^privateAttributes\/[^/]+\.stylex$/;
101
+ /** A StyleX module, with or without its file extension. */
102
+ const STYLEX_MODULE = /\.stylex(?:\.[cm]?[jt]sx?)?$/;
103
+ /** The extensions an extensionless import may name, in resolution order. */
104
+ const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.mjs', '.js'];
105
+
106
+ /**
107
+ * The relative import specifiers in a module's source.
108
+ * @param {string} content
109
+ * @returns {string[]}
110
+ */
111
+ function relativeImportsOf(content) {
112
+ const found = [];
113
+ for (const re of [
114
+ /from\s+['"](\.\.?\/[^'"]+)['"]/g,
115
+ /import\(\s*['"](\.\.?\/[^'"]+)['"]/g,
116
+ ]) {
117
+ for (const m of content.matchAll(re)) found.push(m[1]);
118
+ }
119
+ return found;
120
+ }
121
+
122
+ /**
123
+ * The source file an import resolves to under `srcRoot`, as a path relative to
124
+ * `srcRoot` without its extension (`privateAttributes/press.stylex`), and the
125
+ * file's own relative path; null when it resolves outside `srcRoot` or to no
126
+ * file.
127
+ * @param {string} srcRoot
128
+ * @param {string} fromDir directory of the importing file, relative to srcRoot
129
+ * @param {string} importPath
130
+ * @returns {{module: string, file: string} | null}
131
+ */
132
+ function resolveSourceModule(srcRoot, fromDir, importPath) {
133
+ const module = path.posix.normalize(path.posix.join(fromDir, importPath));
134
+ if (module.startsWith('..') || path.posix.isAbsolute(module)) return null;
135
+ for (const ext of ['', ...SOURCE_EXTENSIONS]) {
136
+ const file = module + ext;
137
+ const abs = path.join(srcRoot, file);
138
+ if (fs.existsSync(abs) && fs.statSync(abs).isFile()) {
139
+ return {
140
+ module: ext ? module : module.replace(/\.[cm]?[jt]sx?$/, ''),
141
+ file,
142
+ };
143
+ }
144
+ }
145
+ return null;
146
+ }
147
+
148
+ /**
149
+ * The subpaths the owner package exports (`./theme/tokens.stylex`), read from
150
+ * the nearest package.json above its source root.
151
+ * @param {string} srcRoot
152
+ * @returns {Set<string>}
153
+ */
154
+ function exportedSubpathsOf(srcRoot) {
155
+ let dir = srcRoot;
156
+ for (;;) {
157
+ const manifest = path.join(dir, 'package.json');
158
+ if (fs.existsSync(manifest)) {
159
+ try {
160
+ const {exports} = JSON.parse(fs.readFileSync(manifest, 'utf-8'));
161
+ return new Set(
162
+ exports && typeof exports === 'object' ? Object.keys(exports) : [],
163
+ );
164
+ } catch {
165
+ return new Set();
166
+ }
167
+ }
168
+ const parent = path.dirname(dir);
169
+ if (parent === dir) return new Set();
170
+ dir = parent;
171
+ }
172
+ }
173
+
174
+ /**
175
+ * The modules a copy carries beside the component, in the package's own
176
+ * layout under the output directory (`spec:AST-110` FR4): each private
177
+ * attribute owner module the component imports, and every unexported StyleX
178
+ * module such a carried module imports, transitively. The component's own
179
+ * imports of them, and theirs of each other, stay relative.
180
+ *
181
+ * @param {string} srcRoot the owner package's source root
182
+ * @param {string} componentDir
183
+ * @param {string[]} componentFiles files of the component that are copied
184
+ * @returns {Map<string, string>} module path (relative to srcRoot, no
185
+ * extension) -> its file path relative to srcRoot
186
+ */
187
+ export function sharedModulesOf(srcRoot, componentDir, componentFiles) {
188
+ const exported = exportedSubpathsOf(srcRoot);
189
+ const componentRel = path
190
+ .relative(srcRoot, componentDir)
191
+ .split(path.sep)
192
+ .join('/');
193
+ /** @type {Map<string, string>} */
194
+ const carried = new Map();
195
+ /** @type {Array<{fromDir: string, content: string, owner: boolean}>} */
196
+ const queue = componentFiles
197
+ .filter(f => /\.[cm]?[jt]sx?$/.test(f))
198
+ .map(f => ({
199
+ fromDir: componentRel,
200
+ content: fs.readFileSync(path.join(componentDir, f), 'utf-8'),
201
+ owner: false,
202
+ }));
203
+ while (queue.length > 0) {
204
+ const {fromDir, content, owner} = /** @type {typeof queue[number]} */ (
205
+ queue.shift()
206
+ );
207
+ for (const importPath of relativeImportsOf(content)) {
208
+ const target = resolveSourceModule(srcRoot, fromDir, importPath);
209
+ if (target == null || carried.has(target.module)) continue;
210
+ if (target.module.startsWith(componentRel + '/')) continue;
211
+ const isOwner = OWNER_MODULE.test(target.module);
212
+ // A carried module's unexported StyleX dependency travels with it; a
213
+ // component's own imports of other modules are rewritten as before.
214
+ const isPrivateStyle =
215
+ owner &&
216
+ STYLEX_MODULE.test(target.module) &&
217
+ !exported.has(`./${target.module}`);
218
+ if (!isOwner && !isPrivateStyle) continue;
219
+ carried.set(target.module, target.file);
220
+ queue.push({
221
+ fromDir: path.posix.dirname(target.module),
222
+ content: fs.readFileSync(path.join(srcRoot, target.file), 'utf-8'),
223
+ owner: true,
224
+ });
225
+ }
226
+ }
227
+ return carried;
228
+ }
229
+
230
+ /**
231
+ * A `keep` predicate for `rewriteImports`: true for an import that names one
232
+ * of the carried modules from a file in `fromDir`.
233
+ * @param {Map<string, string>} carried
234
+ * @param {string} fromDir relative to the source root
235
+ * @returns {(importPath: string) => boolean}
236
+ */
237
+ function keepCarried(carried, fromDir) {
238
+ return importPath => {
239
+ const module = path.posix
240
+ .normalize(path.posix.join(fromDir, importPath))
241
+ .replace(/\.[cm]?[jt]sx?$/, '');
242
+ return carried.has(module);
243
+ };
244
+ }
245
+
93
246
  /**
94
247
  * Build the maintainer feedback note for a swizzled component.
95
248
  * @param {string} component
@@ -317,19 +470,64 @@ export async function swizzleCopy(component, options = {}) {
317
470
  label: 'output file',
318
471
  });
319
472
  }
473
+ // The owner modules the component imports, and their unexported StyleX
474
+ // dependencies, travel with it in the package's layout (spec:AST-110 FR4).
475
+ const srcRoot = path.dirname(componentDir);
476
+ const componentRel = path
477
+ .relative(srcRoot, componentDir)
478
+ .split(path.sep)
479
+ .join('/');
480
+ const carried = sharedModulesOf(srcRoot, componentDir, sourceFiles);
481
+ const shared = [...carried.values()].map(file => {
482
+ const content = rewriteImports(
483
+ fs.readFileSync(path.join(srcRoot, file), 'utf-8'),
484
+ owner.ownerPackage,
485
+ keepCarried(carried, path.posix.dirname(file)),
486
+ );
487
+ const dest = confineWrite(path.join(outputBase, file), cwd, {
488
+ allowAbsolute: true,
489
+ label: 'output file',
490
+ });
491
+ // Something that is not a readable file in its place counts as changed.
492
+ let existing = null;
493
+ if (fs.existsSync(dest)) {
494
+ try {
495
+ existing = fs.readFileSync(dest, 'utf-8');
496
+ } catch {
497
+ existing = '';
498
+ }
499
+ }
500
+ // A copy another component's swizzle already wrote is reused when it is
501
+ // the same; a changed one is a file this run would overwrite.
502
+ return {
503
+ file,
504
+ dest,
505
+ content,
506
+ unchanged: existing === content,
507
+ exists: existing != null,
508
+ };
509
+ });
320
510
  const existingFiles = sourceFiles.filter(f =>
321
511
  fs.existsSync(path.join(outputDir, f)),
322
512
  );
323
- if (existingFiles.length > 0 && !overwrite) {
513
+ const changedShared = shared.filter(s => s.exists && !s.unchanged);
514
+ if ((existingFiles.length > 0 || changedShared.length > 0) && !overwrite) {
324
515
  const relOutputForMsg = path.relative(cwd, outputDir) || '.';
516
+ const sharedNote =
517
+ changedShared.length > 0
518
+ ? ` and ${changedShared.length} changed shared module(s) (${changedShared
519
+ .map(s => path.relative(cwd, s.dest))
520
+ .join(', ')})`
521
+ : '';
325
522
  throw new AstryxError(
326
- `Refusing to overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/. ` +
523
+ `Refusing to overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/${sharedNote}. ` +
327
524
  `Re-run with --overwrite (or -f) to replace them.`,
328
525
  [],
329
526
  ERROR_CODES.ERR_FILE_EXISTS,
330
527
  );
331
528
  }
332
529
 
530
+
333
531
  const outputDirExisted = fs.existsSync(outputDir);
334
532
  try {
335
533
  fs.mkdirSync(outputDir, {recursive: true});
@@ -351,7 +549,7 @@ export async function swizzleCopy(component, options = {}) {
351
549
  if (!fs.statSync(srcPath).isFile()) continue;
352
550
  let content = fs.readFileSync(srcPath, 'utf-8');
353
551
  if (file.endsWith('.ts') || file.endsWith('.tsx')) {
354
- content = rewriteImports(content, owner.ownerPackage);
552
+ content = rewriteImports(content, owner.ownerPackage, keepCarried(carried, componentRel));
355
553
  }
356
554
  if (
357
555
  (file.endsWith('.ts') || file.endsWith('.tsx')) &&
@@ -381,6 +579,38 @@ export async function swizzleCopy(component, options = {}) {
381
579
  copied++;
382
580
  }
383
581
 
582
+ /** @type {string[]} folders this run created for carried modules, outermost first */
583
+ const createdDirs = [];
584
+ for (const module of shared) {
585
+ // An identical copy is already in place: it is part of this copy, unwritten.
586
+ if (module.unchanged) {
587
+ copied++;
588
+ continue;
589
+ }
590
+ try {
591
+ const original = fs.existsSync(module.dest)
592
+ ? fs.readFileSync(module.dest)
593
+ : null;
594
+ const firstCreated = fs.mkdirSync(path.dirname(module.dest), {recursive: true});
595
+ if (firstCreated != null) createdDirs.push(firstCreated);
596
+ written.push({dest: module.dest, original});
597
+ fs.writeFileSync(module.dest, module.content);
598
+ copied++;
599
+ } catch (err) {
600
+ const unrestored = undoCopy(written);
601
+ // Remove the folders this run created, as a failed component-file write
602
+ // does, so a retry finds the output as it was.
603
+ for (const dir of [...createdDirs].reverse()) {
604
+ fs.rmSync(dir, {recursive: true, force: true});
605
+ }
606
+ if (!outputDirExisted) {
607
+ fs.rmSync(outputDir, {recursive: true, force: true});
608
+ }
609
+ throw writeFailed(module.dest, cwd, err, unrestored);
610
+ }
611
+ }
612
+ if (shared.length > 0) usesStyleX = true;
613
+
384
614
  const relOutput = path.relative(cwd, outputDir);
385
615
  const copiedFiles = files.filter(
386
616
  f =>
@@ -393,7 +623,12 @@ export async function swizzleCopy(component, options = {}) {
393
623
  package: owner.package,
394
624
  outputDir: relOutput,
395
625
  filesCopied: copied,
396
- files: copiedFiles.map(f => f),
626
+ // The owner modules and their unexported style dependencies the copy
627
+ // carries beside the component (spec:AST-110 FR4) are its files too.
628
+ files: [
629
+ ...copiedFiles.map(f => f),
630
+ ...shared.map(m => path.relative(outputDir, m.dest).split(path.sep).join('/')),
631
+ ],
397
632
  usesStyleX,
398
633
  };
399
634
  if (feedback) data.feedback = feedback;
@@ -76,7 +76,7 @@ export const doc = {
76
76
  {
77
77
  type: 'swizzle.copy',
78
78
  description:
79
- 'A receipt after copying the component into the project: the component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling.',
79
+ 'A receipt after copying the component into the project: the component name, owning package, output directory, files-copied count, the copied file names (relative to the component folder, including the private attribute owner modules and their unexported style modules copied beside it, e.g. `../privateAttributes/press.stylex.ts`), whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling.',
80
80
  },
81
81
  ],
82
82
  throws: [
@@ -34,7 +34,7 @@
34
34
  * @property {string} data.package Owner package the component source was copied from.
35
35
  * @property {string} data.outputDir
36
36
  * @property {number} data.filesCopied
37
- * @property {string[]} data.files
37
+ * @property {string[]} data.files Copied file names, relative to the component folder; owner modules and their unexported style modules copied beside it start with `../` (spec:AST-110 FR4).
38
38
  * @property {boolean} data.usesStyleX Whether any copied file uses StyleX (requires build-time setup).
39
39
  * @property {SwizzleFeedback} [data.feedback]
40
40
  */
@@ -41,7 +41,7 @@ export const docs = {
41
41
  ['typography.scale', '--text-heading-*-size/weight/leading, --text-body-size/weight/leading', 'base (px), ratio'],
42
42
  ['typography.body/heading/code', '--font-family-body, --font-family-heading, --font-family-code', 'family, fallbacks?, url?, weight?'],
43
43
  ['radius', '--radius-inner, --radius-element, --radius-container, --radius-page, --radius-chat', 'base (px), multiplier (0–2)'],
44
- ['motion', 'Every --duration-* token, --ease-entrance and --ease-move (springs don\'t read them yet)', 'tempo? (0.75–1.5), character? (crisp|standard|expressive); and/or a duration scale: fast (ms), medium (ms), ratio, slow?, easing?. The scale wins over tempo for the durations it sets, and explicit tokens win over both. Fixed whatever the knobs say: drags and momentum, rubber band, keyboard, press onset/cancel/flash, hover intent, gesture thresholds, Spinner/Skeleton loops, the 200 ms Reduce Motion cap. See {@link generic:motion}.'],
44
+ ['motion', 'Every --duration-* token, --ease-entrance and --ease-move (tempo also times the touch springs)', 'tempo? (0.75–1.5), character? (crisp|standard|expressive); and/or a duration scale: fast (ms), medium (ms), ratio, slow?, easing?. The scale wins over tempo for the durations it sets, and explicit tokens win over both. Fixed whatever the knobs say: drags and momentum, rubber band, keyboard, press onset/cancel/flash, hover intent, gesture thresholds, Spinner/Skeleton loops, the 200 ms Reduce Motion cap. See {@link generic:motion}.'],
45
45
  ]},
46
46
  {type: 'prose', text: 'For dark mode tuples in token values, see the Dark mode section of {@link generic:use-a-theme}.'},
47
47
  ],
@@ -150,7 +150,7 @@ const styles = stylex.create({
150
150
  content: [
151
151
  {
152
152
  type: 'prose',
153
- text: "A theme sets how motion feels with two knobs in `defineTheme`'s `motion`. They drive the CSS motion tokens; the springs of touch motion don't read them yet. Every theme follows each person's Reduce Motion setting; no theme loosens it.",
153
+ text: "A theme sets how motion feels with two knobs in `defineTheme`'s `motion`. They drive the CSS motion tokens, and `tempo` also times the springs of touch motion; those springs don't follow `character` yet. Every theme follows each person's Reduce Motion setting; no theme loosens it.",
154
154
  },
155
155
  {
156
156
  type: 'list',
@@ -0,0 +1,14 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
4
+ export const doc = {
5
+ type: 'block',
6
+ exampleFor: 'useMergedRefs',
7
+ name: 'useMergedRefs — AutoGrowTextArea',
8
+ displayName: 'useMergedRefs — AutoGrowTextArea',
9
+ description:
10
+ "An AutoGrowTextArea that forwards the caller's ref and also keeps its own ref to measure scrollHeight. The merged ref attaches both to the same textarea: it resizes itself while a parent button focuses it through the forwarded ref.",
11
+ isReady: true,
12
+ aspectRatio: 4 / 3,
13
+ componentsUsed: ['Card', 'Button', 'Layout'],
14
+ };
@@ -0,0 +1,78 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ import {forwardRef, useEffect, useRef, useState} from 'react';
6
+ import {Button} from '@astryxdesign/core/Button';
7
+ import {Card} from '@astryxdesign/core/Card';
8
+ import {useMergedRefs} from '@astryxdesign/core/hooks';
9
+ import {VStack} from '@astryxdesign/core/Layout';
10
+
11
+ type AutoGrowTextAreaProps = {
12
+ value: string;
13
+ onChange: (value: string) => void;
14
+ };
15
+
16
+ // Forwards the caller's ref and also keeps its own ref to measure
17
+ // scrollHeight; useMergedRefs attaches both to the same textarea.
18
+ const AutoGrowTextArea = forwardRef<HTMLTextAreaElement, AutoGrowTextAreaProps>(
19
+ function AutoGrowTextArea({value, onChange}, forwardedRef) {
20
+ const keptRef = useRef<HTMLTextAreaElement>(null);
21
+ const mergedRef = useMergedRefs(forwardedRef, keptRef);
22
+
23
+ // Syncs the textarea's inline height with the committed value.
24
+ // scrollHeight is right only after React writes the new text.
25
+ useEffect(() => {
26
+ const el = keptRef.current;
27
+ if (!el) {
28
+ return;
29
+ }
30
+ el.style.height = 'auto';
31
+ el.style.height = `${el.scrollHeight}px`;
32
+ }, [value]);
33
+
34
+ return (
35
+ <textarea
36
+ ref={mergedRef}
37
+ value={value}
38
+ onChange={event => onChange(event.target.value)}
39
+ rows={1}
40
+ aria-label="Auto-growing message"
41
+ placeholder="Type — the box grows itself"
42
+ style={{
43
+ width: '100%',
44
+ padding: 8,
45
+ borderRadius: 8,
46
+ border: '1px solid',
47
+ resize: 'none',
48
+ overflow: 'hidden',
49
+ fontFamily: 'inherit',
50
+ fontSize: 14,
51
+ lineHeight: '20px',
52
+ color: 'inherit',
53
+ background: 'transparent',
54
+ }}
55
+ />
56
+ );
57
+ },
58
+ );
59
+
60
+ export default function UseMergedRefsHookUsage() {
61
+ const areaRef = useRef<HTMLTextAreaElement>(null);
62
+ const [value, setValue] = useState(
63
+ 'This box keeps its own ref to measure and grow. The button focuses it through the forwarded ref.',
64
+ );
65
+
66
+ return (
67
+ <Card width={360} padding={4}>
68
+ <VStack gap={3}>
69
+ <AutoGrowTextArea ref={areaRef} value={value} onChange={setValue} />
70
+ <Button
71
+ label="Focus via forwarded ref"
72
+ size="sm"
73
+ onClick={() => areaRef.current?.focus()}
74
+ />
75
+ </VStack>
76
+ </Card>
77
+ );
78
+ }
@@ -0,0 +1,14 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
4
+ export const doc = {
5
+ type: 'block',
6
+ exampleFor: 'useScrollOverflow',
7
+ name: 'useScrollOverflow — Filter Strip Edge Fades',
8
+ displayName: 'useScrollOverflow — Filter Strip Edge Fades',
9
+ description:
10
+ 'A row of active filters that scrolls sideways. useScrollOverflow reports which edge has hidden filters, and the strip fades only that edge: none while every filter fits, the end at the start, both mid-scroll and the start at the end. Adding or removing a filter updates the fades, and in a right-to-left layout the start edge is on the right.',
11
+ isReady: true,
12
+ aspectRatio: 4 / 3,
13
+ componentsUsed: ['Token', 'Button', 'Switch', 'Layout'],
14
+ };
@@ -0,0 +1,94 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ import {useState} from 'react';
6
+ import * as stylex from '@stylexjs/stylex';
7
+ import {Button} from '@astryxdesign/core/Button';
8
+ import {useScrollOverflow} from '@astryxdesign/core/hooks';
9
+ import {HStack, VStack} from '@astryxdesign/core/Layout';
10
+ import {Switch} from '@astryxdesign/core/Switch';
11
+ import {Token} from '@astryxdesign/core/Token';
12
+ import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
13
+
14
+ const FADE = spacingVars['--spacing-8'];
15
+ const FADE_FROM_LEFT = `linear-gradient(to right, transparent, black ${FADE})`;
16
+ const FADE_FROM_RIGHT = `linear-gradient(to left, transparent, black ${FADE})`;
17
+
18
+ const styles = stylex.create({
19
+ strip: {
20
+ display: 'flex',
21
+ gap: spacingVars['--spacing-2'],
22
+ overflowX: 'auto',
23
+ },
24
+ filter: {
25
+ flexShrink: 0,
26
+ },
27
+ fadeLeft: {
28
+ maskImage: FADE_FROM_LEFT,
29
+ },
30
+ fadeRight: {
31
+ maskImage: FADE_FROM_RIGHT,
32
+ },
33
+ fadeBoth: {
34
+ maskImage: `linear-gradient(to right, transparent, black ${FADE}, black calc(100% - ${FADE}), transparent)`,
35
+ },
36
+ });
37
+
38
+ const FILTERS = [
39
+ 'Open now',
40
+ 'Free delivery',
41
+ 'Vegetarian',
42
+ 'Under $15',
43
+ 'Top rated',
44
+ 'Outdoor seating',
45
+ 'Pet friendly',
46
+ ];
47
+
48
+ export default function UseScrollOverflowHookUsage() {
49
+ const [filters, setFilters] = useState(FILTERS.slice(0, 2));
50
+ const [isRtl, setIsRtl] = useState(false);
51
+ const {scrollRef, overflowStart, overflowEnd} = useScrollOverflow();
52
+ const nextFilter = FILTERS.find(filter => !filters.includes(filter));
53
+ const fadeStart = isRtl ? styles.fadeRight : styles.fadeLeft;
54
+ const fadeEnd = isRtl ? styles.fadeLeft : styles.fadeRight;
55
+
56
+ return (
57
+ <VStack gap={3} width={320}>
58
+ <div dir={isRtl ? 'rtl' : 'ltr'}>
59
+ <div
60
+ ref={scrollRef}
61
+ role="group"
62
+ aria-label="Active filters"
63
+ {...stylex.props(
64
+ styles.strip,
65
+ overflowStart && overflowEnd
66
+ ? styles.fadeBoth
67
+ : overflowStart
68
+ ? fadeStart
69
+ : overflowEnd && fadeEnd,
70
+ )}>
71
+ {filters.map(filter => (
72
+ <Token
73
+ key={filter}
74
+ label={filter}
75
+ xstyle={styles.filter}
76
+ onRemove={() =>
77
+ setFilters(current => current.filter(item => item !== filter))
78
+ }
79
+ />
80
+ ))}
81
+ </div>
82
+ </div>
83
+ <HStack gap={3} vAlign="center">
84
+ <Button
85
+ label="Add filter"
86
+ variant="secondary"
87
+ isDisabled={nextFilter == null}
88
+ onClick={() => nextFilter && setFilters([...filters, nextFilter])}
89
+ />
90
+ <Switch label="Right to left" value={isRtl} onChange={setIsRtl} />
91
+ </HStack>
92
+ </VStack>
93
+ );
94
+ }
@@ -0,0 +1,14 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
4
+ export const doc = {
5
+ type: 'block',
6
+ exampleFor: 'useLinkComponent',
7
+ name: 'useLinkComponent — Article Cards',
8
+ displayName: 'useLinkComponent — Article Cards',
9
+ description:
10
+ 'A custom Article card renders its title link with the component useLinkComponent resolves: the as prop first, then the nearest LinkProvider, then a native anchor. Inside a LinkProvider wired to a client-side router, the title navigates without a page load and updates the router location. With as="a" the title is a native anchor even inside the provider, and outside the provider it falls back to the next provider up or a native anchor.',
11
+ isReady: true,
12
+ aspectRatio: 4 / 3,
13
+ componentsUsed: ['LinkProvider', 'Card', 'Layout', 'Text'],
14
+ };
@@ -0,0 +1,89 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ import {createContext, use, useState, type AnchorHTMLAttributes} from 'react';
6
+ import {Card} from '@astryxdesign/core/Card';
7
+ import {VStack} from '@astryxdesign/core/Layout';
8
+ import {
9
+ LinkProvider,
10
+ useLinkComponent,
11
+ type LinkComponentType,
12
+ } from '@astryxdesign/core/Link';
13
+ import {Text} from '@astryxdesign/core/Text';
14
+
15
+ const NavigateContext = createContext<(to: string) => void>(() => {});
16
+
17
+ function RouterLink({
18
+ to,
19
+ href: _href,
20
+ ...props
21
+ }: AnchorHTMLAttributes<HTMLAnchorElement> & {to: string}) {
22
+ const navigate = use(NavigateContext);
23
+ return (
24
+ <a
25
+ {...props}
26
+ href={to}
27
+ onClick={event => {
28
+ event.preventDefault();
29
+ navigate(to);
30
+ }}
31
+ />
32
+ );
33
+ }
34
+
35
+ function ArticleCard({
36
+ title,
37
+ href,
38
+ resolvedBy,
39
+ linkAs,
40
+ }: {
41
+ title: string;
42
+ href: string;
43
+ resolvedBy: string;
44
+ linkAs?: LinkComponentType;
45
+ }) {
46
+ const LinkComponent = useLinkComponent(linkAs);
47
+ return (
48
+ <Card padding={3}>
49
+ <VStack gap={1}>
50
+ <Text type="body" weight="bold">
51
+ <LinkComponent href={href}>{title}</LinkComponent>
52
+ </Text>
53
+ <Text type="supporting" color="secondary">
54
+ {resolvedBy}
55
+ </Text>
56
+ </VStack>
57
+ </Card>
58
+ );
59
+ }
60
+
61
+ export default function UseLinkComponentHookUsage() {
62
+ const [route, setRoute] = useState('/');
63
+
64
+ return (
65
+ <VStack gap={3}>
66
+ <Text type="body">Router location: {route}</Text>
67
+ <NavigateContext value={setRoute}>
68
+ <LinkProvider component={RouterLink}>
69
+ <ArticleCard
70
+ title="Getting started"
71
+ href="/articles/getting-started"
72
+ resolvedBy="LinkProvider: the router's link, no page load"
73
+ />
74
+ <ArticleCard
75
+ title="Style guide (PDF)"
76
+ href="#style-guide"
77
+ resolvedBy='as="a": a native anchor, even inside the provider'
78
+ linkAs="a"
79
+ />
80
+ </LinkProvider>
81
+ </NavigateContext>
82
+ <ArticleCard
83
+ title="Release notes"
84
+ href="#release-notes"
85
+ resolvedBy="Outside the provider: the app's LinkProvider, or a native anchor"
86
+ />
87
+ </VStack>
88
+ );
89
+ }
@@ -181,8 +181,8 @@ export const myTheme = defineTheme({
181
181
  radius: {base: 4, multiplier: 1},
182
182
 
183
183
  /**
184
- * Motion. Two knobs set how its CSS feels (touch springs don't read them
185
- * yet):
184
+ * Motion. Two knobs set how it feels. tempo also times the touch springs;
185
+ * character sets only the CSS curves for now:
186
186
  * tempo — 1 is Astryx's own; 0.75 the quickest, 1.5 the slowest.
187
187
  * character — 'crisp' | 'standard' | 'expressive': the entrance and move
188
188
  * curves (--ease-entrance, --ease-move). --ease-exit, the curve for
@@ -90,6 +90,16 @@ export function registerSwizzle(program) {
90
90
  ].join('\n'),
91
91
  ),
92
92
  ];
93
+ // Files the copy wrote outside the component folder: the owner modules
94
+ // and their unexported style modules (spec:AST-110 FR4).
95
+ const shared = (result.data.files ?? []).filter(f => f.startsWith('../'));
96
+ if (shared.length > 0) {
97
+ out.push(
98
+ text(
99
+ `Shared modules: ${shared.join(', ')} (copied whole; their imports between each other stay relative)`,
100
+ ),
101
+ );
102
+ }
93
103
 
94
104
  // StyleX build requirement — swizzled StyleX source throws on import
95
105
  // ("Unexpected 'stylex.create' call at runtime") unless the consumer's
@@ -262,7 +262,7 @@ export const doc = {
262
262
  {
263
263
  value: 'swizzle.copy',
264
264
  description:
265
- "An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope's package names the same owning package.",
265
+ "An eject receipt: component name, owning package, output directory, files-copied count, the copied file names (relative to the component folder; owner modules copied beside it start with ../), whether any file uses StyleX, and, when the owner has an issues URL, feedback ({issuesUrl, ghCommand?}): where to report the gap that led to swizzling. The envelope's package names the same owning package.",
266
266
  },
267
267
 
268
268
  // gap reports
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astryxdesign/cli",
3
- "version": "0.7.9-canary.7d6481e",
3
+ "version": "0.7.9-canary.7e69f91",
4
4
  "displayName": "CLI",
5
5
  "description": "Scaffold projects, browse templates, generate themes, and get agent-ready docs from the command line.",
6
6
  "author": "Meta Open Source",
@@ -124,10 +124,10 @@
124
124
  "zod": "^4.4.3"
125
125
  },
126
126
  "peerDependencies": {
127
- "@astryxdesign/charts": "0.7.9-canary.7d6481e",
128
- "@astryxdesign/core": "0.7.9-canary.7d6481e",
129
- "@astryxdesign/lab": "0.7.9-canary.7d6481e",
130
- "@astryxdesign/theme-neutral": "0.7.9-canary.7d6481e"
127
+ "@astryxdesign/charts": "0.7.9-canary.7e69f91",
128
+ "@astryxdesign/core": "0.7.9-canary.7e69f91",
129
+ "@astryxdesign/lab": "0.7.9-canary.7e69f91",
130
+ "@astryxdesign/theme-neutral": "0.7.9-canary.7e69f91"
131
131
  },
132
132
  "peerDependenciesMeta": {
133
133
  "@astryxdesign/charts": {
@@ -144,10 +144,10 @@
144
144
  }
145
145
  },
146
146
  "devDependencies": {
147
- "@astryxdesign/charts": "0.7.9-canary.7d6481e",
148
- "@astryxdesign/core": "0.7.9-canary.7d6481e",
149
- "@astryxdesign/lab": "0.7.9-canary.7d6481e",
150
- "@astryxdesign/theme-neutral": "0.7.9-canary.7d6481e",
147
+ "@astryxdesign/charts": "0.7.9-canary.7e69f91",
148
+ "@astryxdesign/core": "0.7.9-canary.7e69f91",
149
+ "@astryxdesign/lab": "0.7.9-canary.7e69f91",
150
+ "@astryxdesign/theme-neutral": "0.7.9-canary.7e69f91",
151
151
  "@heroicons/react": "^2.2.0",
152
152
  "@stylexjs/stylex": "^0.19.0",
153
153
  "@types/babel__core": "^7.20.5",