@astryxdesign/cli 0.7.9-canary.e2b522f → 0.7.9-canary.e423ffa

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.
Files changed (36) hide show
  1. package/README.md +1 -1
  2. package/api/component/__fixtures__/resolutions/modules.txt +2 -2
  3. package/api/search/_candidate-score.mjs +25 -23
  4. package/api/search/_words.d.mts +44 -7
  5. package/api/search/_words.mjs +113 -21
  6. package/api/swizzle/_adapter.d.mts +10 -0
  7. package/api/swizzle/_adapter.mjs +24 -1
  8. package/api/swizzle/copy/copy.d.mts +17 -1
  9. package/api/swizzle/copy/copy.mjs +249 -9
  10. package/api/swizzle/swizzle.doc.mjs +1 -1
  11. package/api/swizzle/swizzle.type.mjs +1 -1
  12. package/assets/discover/official-packages.json +4 -0
  13. package/assets/docs/tree/calendars.doc.mjs +1 -1
  14. package/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.doc.mjs +14 -0
  15. package/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.tsx +94 -0
  16. package/assets/templates/blocks/components/Icon/useIconHookUsage.doc.mjs +19 -0
  17. package/assets/templates/blocks/components/Icon/useIconHookUsage.tsx +68 -0
  18. package/assets/templates/blocks/components/Link/useLinkComponentHookUsage.doc.mjs +14 -0
  19. package/assets/templates/blocks/components/Link/useLinkComponentHookUsage.tsx +89 -0
  20. package/assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla.doc.mjs +14 -0
  21. package/assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla.tsx +156 -0
  22. package/assets/templates/blocks/components/usePanGesture/PanPlayingCard.doc.mjs +14 -0
  23. package/assets/templates/blocks/components/usePanGesture/PanPlayingCard.tsx +143 -0
  24. package/clients/cli/commands/swizzle.mjs +10 -0
  25. package/foundation/config/project.mjs +15 -2
  26. package/foundation/discovery/component-discovery.mjs +17 -6
  27. package/foundation/env/search-path.d.mts +12 -0
  28. package/foundation/env/search-path.mjs +71 -43
  29. package/foundation/integrations/manifest-writer.d.mts +3 -4
  30. package/foundation/integrations/manifest-writer.mjs +5 -3
  31. package/foundation/response/response-types.doc.mjs +1 -1
  32. package/foundation/text/levenshtein.d.mts +4 -1
  33. package/foundation/text/levenshtein.mjs +44 -1
  34. package/package.json +9 -9
  35. package/api/swizzle/_github.d.mts +0 -8
  36. package/api/swizzle/_github.mjs +0 -22
@@ -15,9 +15,12 @@
15
15
 
16
16
  import * as fs from 'node:fs';
17
17
  import * as path from 'node:path';
18
- import {resolveComponentReplacement, resolveCore} from '../_adapter.mjs';
18
+ import {
19
+ checkGhCli,
20
+ resolveComponentReplacement,
21
+ resolveCore,
22
+ } from '../_adapter.mjs';
19
23
  import {assertWithin, sanitizeName, PathSafetyError} from '../../../foundation/fs/path-safety.mjs';
20
- import {checkGhCli} from '../_github.mjs';
21
24
  import {Project} from '../../../foundation/config/project.mjs';
22
25
  import {
23
26
  CORE_PACKAGE,
@@ -56,10 +59,16 @@ const DEFAULT_ISSUES_URL = 'https://github.com/meta/astryx/issues/new';
56
59
  *
57
60
  * @param {string} content
58
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`).
59
64
  */
60
- export function rewriteImports(content, ownerPackage = CORE_PACKAGE) {
65
+ export function rewriteImports(content, ownerPackage = CORE_PACKAGE, keep = () => false) {
61
66
  /** @param {string} importPath */
62
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
+ }
63
72
  // Strip ALL leading `../` so a two-levels-up path never yields `<pkg>/..`.
64
73
  const rest = importPath.replace(/^(?:\.\.\/)+/, '');
65
74
  const parts = rest.split('/');
@@ -87,6 +96,153 @@ export function rewriteImports(content, ownerPackage = CORE_PACKAGE) {
87
96
  );
88
97
  }
89
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
+
90
246
  /**
91
247
  * Build the maintainer feedback note for a swizzled component.
92
248
  * @param {string} component
@@ -299,6 +455,10 @@ export async function swizzleCopy(component, options = {}) {
299
455
  const outputBase = confineWrite(output, cwd, {label: 'output directory'});
300
456
  const outputDir = path.join(outputBase, dirName);
301
457
 
458
+ // The receipt's feedback first: a swizzle that fails must fail before it
459
+ // writes anything.
460
+ const feedback = buildFeedback(dirName, owner.issuesUrl);
461
+
302
462
  // Pre-flight path and overwrite checks before any mkdir/writeFile.
303
463
  const sourceFiles = fs.readdirSync(componentDir).filter(file => {
304
464
  if (isExcludedFromCopy(file)) return false;
@@ -310,19 +470,64 @@ export async function swizzleCopy(component, options = {}) {
310
470
  label: 'output file',
311
471
  });
312
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
+ });
313
510
  const existingFiles = sourceFiles.filter(f =>
314
511
  fs.existsSync(path.join(outputDir, f)),
315
512
  );
316
- if (existingFiles.length > 0 && !overwrite) {
513
+ const changedShared = shared.filter(s => s.exists && !s.unchanged);
514
+ if ((existingFiles.length > 0 || changedShared.length > 0) && !overwrite) {
317
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
+ : '';
318
522
  throw new AstryxError(
319
- `Refusing to overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/. ` +
523
+ `Refusing to overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/${sharedNote}. ` +
320
524
  `Re-run with --overwrite (or -f) to replace them.`,
321
525
  [],
322
526
  ERROR_CODES.ERR_FILE_EXISTS,
323
527
  );
324
528
  }
325
529
 
530
+
326
531
  const outputDirExisted = fs.existsSync(outputDir);
327
532
  try {
328
533
  fs.mkdirSync(outputDir, {recursive: true});
@@ -344,7 +549,7 @@ export async function swizzleCopy(component, options = {}) {
344
549
  if (!fs.statSync(srcPath).isFile()) continue;
345
550
  let content = fs.readFileSync(srcPath, 'utf-8');
346
551
  if (file.endsWith('.ts') || file.endsWith('.tsx')) {
347
- content = rewriteImports(content, owner.ownerPackage);
552
+ content = rewriteImports(content, owner.ownerPackage, keepCarried(carried, componentRel));
348
553
  }
349
554
  if (
350
555
  (file.endsWith('.ts') || file.endsWith('.tsx')) &&
@@ -374,21 +579,56 @@ export async function swizzleCopy(component, options = {}) {
374
579
  copied++;
375
580
  }
376
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
+
377
614
  const relOutput = path.relative(cwd, outputDir);
378
615
  const copiedFiles = files.filter(
379
616
  f =>
380
617
  !isExcludedFromCopy(f) &&
381
618
  fs.statSync(path.join(componentDir, f)).isFile(),
382
619
  );
383
- const feedback = buildFeedback(dirName, owner.issuesUrl);
384
-
385
620
  /** @type {import('../swizzle.type.mjs').SwizzleCopyResponse['data']} */
386
621
  const data = {
387
622
  component: dirName,
388
623
  package: owner.package,
389
624
  outputDir: relOutput,
390
625
  filesCopied: copied,
391
- 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
+ ],
392
632
  usesStyleX,
393
633
  };
394
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
  */
@@ -100,6 +100,10 @@
100
100
  "kind": "component",
101
101
  "name": "ChatUnreadDivider"
102
102
  },
103
+ {
104
+ "kind": "component",
105
+ "name": "CircleCheckIndicator"
106
+ },
103
107
  {
104
108
  "kind": "component",
105
109
  "name": "CircularProgress"
@@ -40,7 +40,7 @@ export const docs = {
40
40
  blocks: [
41
41
  {
42
42
  type: 'prose',
43
- text: '`Calendar` shows the Gregorian calendar unless the application chooses another one; DateInput, DateRangeInput, and DateTimeInput stay Gregorian. Values never change with the calendar: they stay Gregorian ISO dates. {@link generic:i18n-calendars} has the short version.',
43
+ text: '`Calendar`, DateInput, DateRangeInput, and DateTimeInput show the Gregorian calendar unless the application chooses another one. Values never change with the calendar: they stay Gregorian ISO dates. {@link generic:i18n-calendars} has the short version.',
44
44
  },
45
45
  ],
46
46
  };
@@ -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,19 @@
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: 'useIcon',
7
+ name: 'useIcon — Status Row',
8
+ displayName: 'useIcon — Status Row',
9
+ description:
10
+ 'A custom status row that draws the semantic success, warning and error icons with useIcon. The same row renders under the current theme and under a Theme whose icons override those three, and its icons change with no change to the component.',
11
+ isReady: true,
12
+ aspectRatio: 4 / 3,
13
+ componentsUsed: ['Theme', 'Layout', 'Text'],
14
+ icons: {
15
+ CheckBadgeIcon: 'success',
16
+ ExclamationCircleIcon: 'warning',
17
+ NoSymbolIcon: 'error',
18
+ },
19
+ };
@@ -0,0 +1,68 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ import {
6
+ CheckBadgeIcon,
7
+ ExclamationCircleIcon,
8
+ NoSymbolIcon,
9
+ } from '@heroicons/react/24/solid';
10
+ import {useIcon} from '@astryxdesign/core/Icon';
11
+ import {HStack, VStack} from '@astryxdesign/core/Layout';
12
+ import {Text} from '@astryxdesign/core/Text';
13
+ import {Theme, defineTheme, useTheme} from '@astryxdesign/core/theme';
14
+
15
+ const statusIconTheme = defineTheme({
16
+ name: 'status-icons-docs',
17
+ icons: {
18
+ success: <CheckBadgeIcon width="1em" height="1em" />,
19
+ warning: <ExclamationCircleIcon width="1em" height="1em" />,
20
+ error: <NoSymbolIcon width="1em" height="1em" />,
21
+ },
22
+ });
23
+
24
+ function StatusRow() {
25
+ const success = useIcon('success');
26
+ const warning = useIcon('warning');
27
+ const error = useIcon('error');
28
+
29
+ return (
30
+ <HStack gap={4}>
31
+ <HStack gap={1} vAlign="center">
32
+ {success}
33
+ <Text type="body">Passed</Text>
34
+ </HStack>
35
+ <HStack gap={1} vAlign="center">
36
+ {warning}
37
+ <Text type="body">Flaky</Text>
38
+ </HStack>
39
+ <HStack gap={1} vAlign="center">
40
+ {error}
41
+ <Text type="body">Failed</Text>
42
+ </HStack>
43
+ </HStack>
44
+ );
45
+ }
46
+
47
+ export default function UseIconHookUsage() {
48
+ const {mode} = useTheme();
49
+
50
+ return (
51
+ <VStack gap={4}>
52
+ <VStack gap={2}>
53
+ <Text type="supporting" color="secondary">
54
+ Current theme
55
+ </Text>
56
+ <StatusRow />
57
+ </VStack>
58
+ <Theme theme={statusIconTheme} mode={mode}>
59
+ <VStack gap={2}>
60
+ <Text type="supporting" color="secondary">
61
+ Theme with its own status icons
62
+ </Text>
63
+ <StatusRow />
64
+ </VStack>
65
+ </Theme>
66
+ </VStack>
67
+ );
68
+ }
@@ -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
+ }