@astryxdesign/cli 0.7.7-canary.fc68123 → 0.7.7

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/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # @xds/cli
2
2
 
3
+ # 0.7.7
4
+
5
+ #### New Components
6
+
7
+ - `astryx discover` no longer lists `InfoTip` among the components `@astryxdesign/lab` contributes: InfoTip is a Core component now, described by `astryx component InfoTip`.
8
+
9
+ #### Performance
10
+
11
+ - With TypeScript 5.3 or later, `validateIntegration()`, `integrationComponentConflicts()` and `integrationCheck()` from `@astryxdesign/cli/api`, and the commands that run them, reuse each TypeScript file a check parsed for later checks in the same process that parse it the same way, while the file is unchanged, instead of parsing it again for every check. Their results are unchanged.
12
+
13
+ #### Documentation
14
+
15
+ - Hook docs for `useOutlineFromMarkdown`, so `astryx hook useOutlineFromMarkdown` and `astryx search` return it, and a `useOutlineFromMarkdown — Docs Article` example block: a Markdown article and an Outline built from the same string through the hook, with a button that adds a section and its linked entry.
16
+ - 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.
17
+ - A new `useCombobox — Assign To Field` example block spreads the field, listbox and option props from `useCombobox` onto a `TextInput` and a list of `Item` rows: typing filters a list of teammates, ArrowUp and ArrowDown move the active option while focus stays in the input, Enter or a press picks one, and Escape closes the list. Copy it with `astryx template useComboboxHookUsage <path>`.
18
+ - A new `useGridFocus — Color Swatch Grid` example block wires `useGridFocus` to a color swatch picker in rows of eight: the grid has one Tab stop, the arrow keys move focus cell to cell, Home and End jump within a row, Ctrl+Home and Ctrl+End jump to the corners. Each swatch is a button, so Enter or a click picks it. Copy it with `astryx template useGridFocusHookUsage <path>`.
19
+ - A new `useListFocus — Recent Files` example block gives a list of buttons keyboard navigation from `useListFocus`: ArrowUp and ArrowDown move between rows, Home and End jump to the first and last row, focus wraps at the ends, and only one row is in the tab order. Copy it with `astryx template useListFocusHookUsage <path>`.
20
+ - A new `useOverflow — Editor Toolbar` example block shows the hook on its own: eight toolbar actions sit in a card you can resize, a hidden copy of the row holds every action plus the `More` menu marked `data-overflow-indicator`, and the actions that do not fit move into the `More` menu with no flicker. Copy it with `astryx template useOverflowHookUsage <path>`.
21
+
22
+ #### Contributors
23
+
24
+ Thanks to everyone who contributed to this release:
25
+
26
+ - @cixzhang
27
+ - @hskl18
28
+ - @kyu-rong
29
+ - @maheshrijal
30
+ - @vjeux
31
+
32
+ ---
33
+
3
34
  # 0.7.6
4
35
 
5
36
  #### New Features
@@ -27,7 +27,6 @@ import {
27
27
  packageReferenceProblems,
28
28
  } from '../docs/_adapter.mjs';
29
29
  import {findProjectCoreDir} from '../../foundation/fs/paths.mjs';
30
- import {withListingCache} from '../../foundation/fs/listing-cache.mjs';
31
30
  import {
32
31
  discoverIntegrationComponents,
33
32
  discoverOwnedComponents,
@@ -155,16 +154,6 @@ function addErrors(issues, errors, code) {
155
154
  * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationTemplateConflictResponse>}
156
155
  */
157
156
  export async function integrationTemplateConflicts(pkg, options = {}) {
158
- // Read-only: one listing of each folder serves the whole check.
159
- return withListingCache(() => templateConflicts(pkg, options));
160
- }
161
-
162
- /**
163
- * @param {string | undefined} pkg
164
- * @param {import('./authoring-checks.type.mjs').IntegrationAuthoringOptions} options
165
- * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationTemplateConflictResponse>}
166
- */
167
- async function templateConflicts(pkg, options) {
168
157
  const {cwd = process.cwd()} = options;
169
158
  const resolved = await resolveIntegration(pkg, cwd);
170
159
  const validated = resolved.found;
@@ -302,16 +291,6 @@ async function templateConflicts(pkg, options) {
302
291
  * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationComponentConflictResponse>}
303
292
  */
304
293
  export async function integrationComponentConflicts(pkg, options = {}) {
305
- // Read-only: one listing of each folder serves the whole check.
306
- return withListingCache(() => componentConflicts(pkg, options));
307
- }
308
-
309
- /**
310
- * @param {string | undefined} pkg
311
- * @param {import('./authoring-checks.type.mjs').IntegrationAuthoringOptions} options
312
- * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationComponentConflictResponse>}
313
- */
314
- async function componentConflicts(pkg, options) {
315
294
  const {cwd = process.cwd()} = options;
316
295
  const resolved = await resolveIntegration(pkg, cwd);
317
296
  const validated = resolved.found;
@@ -408,16 +387,6 @@ async function componentConflicts(pkg, options) {
408
387
  * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationDocConflictResponse>}
409
388
  */
410
389
  export async function integrationDocConflicts(pkg, options = {}) {
411
- // Read-only: one listing of each folder serves the whole check.
412
- return withListingCache(() => docConflicts(pkg, options));
413
- }
414
-
415
- /**
416
- * @param {string | undefined} pkg
417
- * @param {import('./authoring-checks.type.mjs').IntegrationAuthoringOptions} options
418
- * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationDocConflictResponse>}
419
- */
420
- async function docConflicts(pkg, options) {
421
390
  const {cwd = process.cwd()} = options;
422
391
  const resolved = await resolveIntegration(pkg, cwd);
423
392
  const validated = resolved.found;
@@ -36,7 +36,6 @@ import {
36
36
  summarizeIssues,
37
37
  validateIntegration,
38
38
  } from '../validate-integration.mjs';
39
- import {withListingCache} from '../../../foundation/fs/listing-cache.mjs';
40
39
 
41
40
  /** @typedef {import('../integration-check.type.mjs').IntegrationCheckName} IntegrationCheckName */
42
41
  /** @typedef {import('../integration-check.type.mjs').IntegrationCheckReport} IntegrationCheckReport */
@@ -245,13 +244,9 @@ export async function integrationCheck(options = {}) {
245
244
  /** @type {IntegrationCheckResponse[]} */
246
245
  const responses = [];
247
246
  responses.push(await validateIntegration(undefined, {cwd}));
248
- // The three authoring checks only read, so they share one listing of each
249
- // folder.
250
- await withListingCache(async () => {
251
- responses.push(await integrationComponentConflicts(undefined, {cwd}));
252
- responses.push(await integrationTemplateConflicts(undefined, {cwd}));
253
- responses.push(await integrationDocConflicts(undefined, {cwd}));
254
- });
247
+ responses.push(await integrationComponentConflicts(undefined, {cwd}));
248
+ responses.push(await integrationTemplateConflicts(undefined, {cwd}));
249
+ responses.push(await integrationDocConflicts(undefined, {cwd}));
255
250
 
256
251
  const [validation] = responses;
257
252
  return {
@@ -8,12 +8,7 @@ import * as fs from 'node:fs';
8
8
  import {createRequire} from 'node:module';
9
9
  import * as path from 'node:path';
10
10
  import {DOC_EXPORTS} from '../doc-compiler/read.mjs';
11
- import {
12
- listDir,
13
- listDirEntries,
14
- pathExists,
15
- withListingCache,
16
- } from '../fs/listing-cache.mjs';
11
+ import {listDir, listDirEntries, pathExists} from '../fs/listing-cache.mjs';
17
12
  import {existsCaseExact} from '../fs/paths.mjs';
18
13
  import {CORE_PROVIDER_ID} from '../identity/providers.mjs';
19
14
  import {loadComponentDoc} from './component-loader.mjs';
@@ -600,25 +595,20 @@ export function findComponentSource(coreDir, name) {
600
595
  * @param {string} dirPath
601
596
  * @returns {string | null}
602
597
  */
603
- function searchDir(dirPath, listed = false) {
604
- // A folder from its parent's listing exists; only a starting folder
605
- // needs the check.
606
- if (!listed && !pathExists(dirPath)) return null;
598
+ function searchDir(dirPath) {
599
+ if (!pathExists(dirPath)) return null;
607
600
  const entries = listDirEntries(dirPath);
608
601
 
609
- // Check for an exact match (prefixed or bare) first. The listing in hand
610
- // holds every name in the folder, so no name is probed on disk.
602
+ // Check for an exact match (prefixed or bare) first
611
603
  for (const candidate of candidateFiles) {
612
- const entry = entries.find(e => e.name === candidate);
613
- if (!entry) continue;
614
604
  const exact = path.join(dirPath, candidate);
615
- if (!entry.isSymbolicLink() || pathExists(exact)) return exact;
605
+ if (existsCaseExact(exact, dirPath)) return exact;
616
606
  }
617
607
 
618
608
  // Recurse into subdirectories
619
609
  for (const entry of entries) {
620
610
  if (entry.isDirectory()) {
621
- const found = searchDir(path.join(dirPath, entry.name), true);
611
+ const found = searchDir(path.join(dirPath, entry.name));
622
612
  if (found) return found;
623
613
  }
624
614
  }
@@ -1713,16 +1703,6 @@ export function unscopedComponentOwners(owners) {
1713
1703
  * @returns {Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>}
1714
1704
  */
1715
1705
  export function discoverOwnedComponents(coreDir, loadedIntegrations = []) {
1716
- // Read-only: one listing of each folder serves the whole discovery.
1717
- return withListingCache(() => ownedComponents(coreDir, loadedIntegrations));
1718
- }
1719
-
1720
- /**
1721
- * @param {string} coreDir
1722
- * @param {Array<{name: string, components?: string, issuesUrl?: string}>} loadedIntegrations
1723
- * @returns {Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>}
1724
- */
1725
- function ownedComponents(coreDir, loadedIntegrations) {
1726
1706
  /** @type {Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>} */
1727
1707
  const records = [];
1728
1708
 
@@ -9,11 +9,6 @@
9
9
  * @returns {T}
10
10
  */
11
11
  export function withListingCache<T>(fn: () => T): T;
12
- /**
13
- * Whether an operation's listing cache is active.
14
- * @returns {boolean}
15
- */
16
- export function listingCacheActive(): boolean;
17
12
  /**
18
13
  * `fs.readdirSync(dir)`, read once per operation. Returns a fresh array, so a
19
14
  * caller that sorts it cannot reorder another caller's listing.
@@ -27,15 +22,6 @@ export function listDir(dir: string): string[];
27
22
  * @returns {fs.Dirent[]}
28
23
  */
29
24
  export function listDirEntries(dir: string): fs.Dirent[];
30
- /**
31
- * The entry named exactly `name` in `dir`'s listing, or null when the folder
32
- * holds no such name or cannot be read. Inside an operation, a name the
33
- * listing lacks costs no probe of the disk.
34
- * @param {string} dir
35
- * @param {string} name
36
- * @returns {fs.Dirent | null}
37
- */
38
- export function findEntry(dir: string, name: string): fs.Dirent | null;
39
25
  /**
40
26
  * `fs.existsSync(target)`, probed once per operation.
41
27
  * @param {string} target
@@ -45,7 +31,6 @@ export function pathExists(target: string): boolean;
45
31
  export type ListingCache = {
46
32
  names: Map<string, string[]>;
47
33
  entries: Map<string, fs.Dirent[]>;
48
- byName: Map<string, Map<string, fs.Dirent>>;
49
34
  exists: Map<string, boolean>;
50
35
  };
51
36
  import * as fs from 'node:fs';
@@ -23,7 +23,6 @@ import * as fs from 'node:fs';
23
23
  * @typedef {{
24
24
  * names: Map<string, string[]>,
25
25
  * entries: Map<string, fs.Dirent[]>,
26
- * byName: Map<string, Map<string, fs.Dirent>>,
27
26
  * exists: Map<string, boolean>,
28
27
  * }} ListingCache
29
28
  */
@@ -41,24 +40,11 @@ const scope = new AsyncLocalStorage();
41
40
  export function withListingCache(fn) {
42
41
  if (scope.getStore()) return fn();
43
42
  return scope.run(
44
- {
45
- names: new Map(),
46
- entries: new Map(),
47
- byName: new Map(),
48
- exists: new Map(),
49
- },
43
+ {names: new Map(), entries: new Map(), exists: new Map()},
50
44
  fn,
51
45
  );
52
46
  }
53
47
 
54
- /**
55
- * Whether an operation's listing cache is active.
56
- * @returns {boolean}
57
- */
58
- export function listingCacheActive() {
59
- return scope.getStore() != null;
60
- }
61
-
62
48
  /**
63
49
  * `fs.readdirSync(dir)`, read once per operation. Returns a fresh array, so a
64
50
  * caller that sorts it cannot reorder another caller's listing.
@@ -92,41 +78,6 @@ export function listDirEntries(dir) {
92
78
  return entries.slice();
93
79
  }
94
80
 
95
- /**
96
- * The entry named exactly `name` in `dir`'s listing, or null when the folder
97
- * holds no such name or cannot be read. Inside an operation, a name the
98
- * listing lacks costs no probe of the disk.
99
- * @param {string} dir
100
- * @param {string} name
101
- * @returns {fs.Dirent | null}
102
- */
103
- export function findEntry(dir, name) {
104
- const cache = scope.getStore();
105
- if (!cache) {
106
- try {
107
- return (
108
- fs
109
- .readdirSync(dir, {withFileTypes: true})
110
- .find(entry => entry.name === name) ?? null
111
- );
112
- } catch {
113
- return null;
114
- }
115
- }
116
- let byName = cache.byName.get(dir);
117
- if (!byName) {
118
- let entries;
119
- try {
120
- entries = listDirEntries(dir);
121
- } catch {
122
- return null;
123
- }
124
- byName = new Map(entries.map(entry => [entry.name, entry]));
125
- cache.byName.set(dir, byName);
126
- }
127
- return byName.get(name) ?? null;
128
- }
129
-
130
81
  /**
131
82
  * `fs.existsSync(target)`, probed once per operation.
132
83
  * @param {string} target
@@ -13,12 +13,7 @@ import {createRequire} from 'node:module';
13
13
  import * as os from 'node:os';
14
14
  import * as path from 'node:path';
15
15
  import {fileURLToPath} from 'node:url';
16
- import {
17
- findEntry,
18
- listDir,
19
- listingCacheActive,
20
- pathExists,
21
- } from './listing-cache.mjs';
16
+ import {listDir, pathExists} from './listing-cache.mjs';
22
17
  import {ERROR_CODES} from '../response/error-codes.mjs';
23
18
  import {carriedCore, runChoice} from '../release/run-context.mjs';
24
19
  import {findDeclaringPackage} from '../release/project.mjs';
@@ -872,31 +867,6 @@ export function listComponents(coreDir) {
872
867
  .sort();
873
868
  }
874
869
 
875
- /**
876
- * `path.relative(root, target)`, read straight off the string when `target`
877
- * is a plain path under `root`. A resolver probes tens of thousands of such
878
- * paths, and `path.relative` normalizes both on every call.
879
- * @param {string} root
880
- * @param {string} target
881
- * @returns {string}
882
- */
883
- function relativeInside(root, target) {
884
- const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;
885
- if (path.isAbsolute(root) && target.startsWith(prefix)) {
886
- const rest = target.slice(prefix.length);
887
- const plain =
888
- rest !== '' &&
889
- !(path.sep === '\\' && rest.includes('/')) &&
890
- rest
891
- .split(path.sep)
892
- .every(
893
- segment => segment !== '' && segment !== '.' && segment !== '..',
894
- );
895
- if (plain) return rest;
896
- }
897
- return path.relative(root, target);
898
- }
899
-
900
870
  /**
901
871
  * Does `targetPath` exist with EXACTLY this spelling?
902
872
  *
@@ -913,28 +883,13 @@ function relativeInside(root, target) {
913
883
  * @returns {boolean}
914
884
  */
915
885
  export function existsCaseExact(targetPath, rootDir) {
916
- const rel = relativeInside(rootDir, targetPath);
917
- if (rel === '') return pathExists(targetPath);
886
+ if (!pathExists(targetPath)) return false;
887
+
888
+ const rel = path.relative(rootDir, targetPath);
889
+ if (rel === '') return true;
918
890
  if (path.isAbsolute(rel) || rel === '..' || rel.startsWith(`..${path.sep}`))
919
891
  return false;
920
892
 
921
- if (listingCacheActive()) {
922
- // Inside an operation the folders' listings answer, so a name that a
923
- // listing lacks costs no probe of the disk. A symbolic link still needs
924
- // its target.
925
- let folder = rootDir;
926
- let entry = null;
927
- for (const segment of rel.split(path.sep)) {
928
- entry = findEntry(folder, segment);
929
- if (!entry) return false;
930
- folder = folder.endsWith(path.sep)
931
- ? `${folder}${segment}`
932
- : `${folder}${path.sep}${segment}`;
933
- }
934
- return !entry?.isSymbolicLink() || pathExists(targetPath);
935
- }
936
-
937
- if (!pathExists(targetPath)) return false;
938
893
  let dir = rootDir;
939
894
  for (const segment of rel.split(path.sep)) {
940
895
  let entries;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astryxdesign/cli",
3
- "version": "0.7.7-canary.fc68123",
3
+ "version": "0.7.7",
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.7-canary.fc68123",
128
- "@astryxdesign/core": "0.7.7-canary.fc68123",
129
- "@astryxdesign/lab": "0.7.7-canary.fc68123",
130
- "@astryxdesign/theme-neutral": "0.7.7-canary.fc68123"
127
+ "@astryxdesign/charts": "*",
128
+ "@astryxdesign/core": "*",
129
+ "@astryxdesign/lab": "*",
130
+ "@astryxdesign/theme-neutral": "*"
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.7-canary.fc68123",
148
- "@astryxdesign/core": "0.7.7-canary.fc68123",
149
- "@astryxdesign/lab": "0.7.7-canary.fc68123",
150
- "@astryxdesign/theme-neutral": "0.7.7-canary.fc68123",
147
+ "@astryxdesign/charts": "*",
148
+ "@astryxdesign/core": "*",
149
+ "@astryxdesign/lab": "*",
150
+ "@astryxdesign/theme-neutral": "*",
151
151
  "@heroicons/react": "^2.2.0",
152
152
  "@stylexjs/stylex": "^0.19.0",
153
153
  "@types/babel__core": "^7.20.5",
@@ -1,14 +0,0 @@
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: 'createAnimator',
7
- name: 'createAnimator — Playing cards in plain JavaScript',
8
- displayName: 'createAnimator — Playing cards in plain JavaScript',
9
- description:
10
- 'The playing card from the useAnimator example, built in plain JavaScript with createAnimator and pointer events: it follows a drag, springs back on a gentle release, flies off with momentum on a quick flick, and a button discards it from the keyboard. React only mounts it.',
11
- isReady: true,
12
- aspectRatio: 4 / 3,
13
- componentsUsed: [],
14
- };
@@ -1,199 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- 'use client';
4
-
5
- import {createAnimator} from '@astryxdesign/core';
6
-
7
- const DECK = [
8
- {face: 'A\u2660', name: 'Ace of spades'},
9
- {face: 'K\u2665', name: 'King of hearts'},
10
- {face: 'Q\u2663', name: 'Queen of clubs'},
11
- {face: 'J\u2666', name: 'Jack of diamonds'},
12
- ];
13
- /** A release faster than this (px/s) throws the card away. */
14
- const THROW_SPEED = 1000;
15
- /** The slowest throw, so a thrown card always leaves the table. */
16
- const MIN_THROW = 1600;
17
-
18
- /**
19
- * A deck on a table, in plain JavaScript: no React below this line. It
20
- * returns a function that takes it down again.
21
- */
22
- function mountDeck(table: HTMLElement, discardButton: HTMLButtonElement) {
23
- let top = 0;
24
- const card = document.createElement('div');
25
- card.textContent = DECK[0].face;
26
- // An image's name is all a screen reader announces, so it names the card.
27
- card.setAttribute('role', 'img');
28
- card.setAttribute('aria-label', DECK[0].name);
29
- Object.assign(card.style, {
30
- width: '120px',
31
- height: '170px',
32
- display: 'grid',
33
- placeItems: 'center',
34
- font: 'bold 40px system-ui, sans-serif',
35
- // The theme's surface and text, so the rank reads in light and dark.
36
- borderRadius: 'var(--radius-container)',
37
- backgroundColor: 'var(--color-background-surface)',
38
- color: 'var(--color-text-primary)',
39
- boxShadow: '0 2px 8px var(--color-shadow)',
40
- touchAction: 'none',
41
- cursor: 'grab',
42
- userSelect: 'none',
43
- });
44
- // Announces each discard to screen readers.
45
- const status = document.createElement('div');
46
- status.setAttribute('aria-live', 'polite');
47
- Object.assign(status.style, {
48
- position: 'absolute',
49
- width: '1px',
50
- height: '1px',
51
- overflow: 'hidden',
52
- clipPath: 'inset(50%)',
53
- whiteSpace: 'nowrap',
54
- });
55
- table.append(card, status);
56
- const animator = createAnimator(card);
57
- // One discard at a time: a press while a card leaves deals no second card.
58
- let isDiscarding = false;
59
-
60
- // Announces the discard and deals the next card in place of the old one.
61
- async function dealNext() {
62
- status.textContent = `${DECK[top % DECK.length].name} discarded`;
63
- top += 1;
64
- const next = DECK[top % DECK.length];
65
- card.textContent = next.face;
66
- card.setAttribute('aria-label', next.name);
67
- animator.set({x: 0, y: 0, rotate: 0, scale: 0.9, opacity: 0});
68
- isDiscarding = false;
69
- await animator.animate({scale: 1, opacity: 1});
70
- }
71
-
72
- // Starts a discard unless one runs. It also ends a drag in progress: the
73
- // drag's next move would take the discard's motion over and drag the dealt
74
- // card.
75
- function startDiscard() {
76
- if (isDiscarding) {
77
- return false;
78
- }
79
- isDiscarding = true;
80
- origin = null;
81
- return true;
82
- }
83
-
84
- async function discard(vx: number, vy: number) {
85
- if (!startDiscard()) {
86
- return;
87
- }
88
- const speed = Math.hypot(vx, vy);
89
- const boost = speed < MIN_THROW ? MIN_THROW / Math.max(speed, 1) : 1;
90
- // The card coasts on while it fades; once it is gone, the next card is
91
- // dealt in place, which ends the coast. A coast continues the person's
92
- // throw, so Reduce Motion keeps it.
93
- void animator.decay({x: speed < 1 ? MIN_THROW : vx * boost, y: vy * boost});
94
- await animator.animate({opacity: 0});
95
- await dealNext();
96
- }
97
-
98
- // The drag: follow the pointer, then read the 80 ms before the release, so
99
- // a pointer that held still before letting go releases at rest.
100
- let origin: {x: number; y: number} | null = null;
101
- let samples: {t: number; x: number; y: number}[] = [];
102
- function onDown(event: PointerEvent) {
103
- // A leaving card takes no press. Pinning it would end its discard and deal
104
- // the next card under the finger.
105
- if (isDiscarding) {
106
- return;
107
- }
108
- card.setPointerCapture(event.pointerId);
109
- // Pins the card where it shows, so the drag starts there. Only the
110
- // position stops, so a card fading in keeps fading in.
111
- const {x, y, rotate} = animator.get();
112
- animator.set({x, y, rotate});
113
- origin = {x: event.clientX - x, y: event.clientY - y};
114
- samples = [];
115
- }
116
- function onMove(event: PointerEvent) {
117
- if (origin == null) {
118
- return;
119
- }
120
- const x = event.clientX - origin.x;
121
- const y = event.clientY - origin.y;
122
- samples.push({t: event.timeStamp, x, y});
123
- animator.set({x, y, rotate: x / 18});
124
- }
125
- // A cancelled pointer was not let go, so the card springs back.
126
- function onCancel() {
127
- if (origin == null) {
128
- return;
129
- }
130
- origin = null;
131
- void animator.animate({x: 0, y: 0, rotate: 0});
132
- }
133
- function onUp(event: PointerEvent) {
134
- if (origin == null) {
135
- return;
136
- }
137
- origin = null;
138
- const recent = samples.filter(s => event.timeStamp - s.t <= 80);
139
- const first = recent[0];
140
- const last = recent.at(-1);
141
- const seconds = last && first ? (last.t - first.t) / 1000 : 0;
142
- const vx = seconds > 0 && last && first ? (last.x - first.x) / seconds : 0;
143
- const vy = seconds > 0 && last && first ? (last.y - first.y) / seconds : 0;
144
- if (Math.abs(vx) > THROW_SPEED) {
145
- void discard(vx, vy);
146
- } else {
147
- void animator.animate(
148
- {x: 0, y: 0, rotate: 0},
149
- {velocity: {x: vx, y: vy}},
150
- );
151
- }
152
- }
153
- // The button moves the card off on the state-change motion: a planned
154
- // move, which Reduce Motion turns into a fade where the card is.
155
- async function discardWithButton() {
156
- if (!startDiscard()) {
157
- return;
158
- }
159
- await animator.animate({x: 400, opacity: 0});
160
- await dealNext();
161
- }
162
- const onDiscard = () => void discardWithButton();
163
-
164
- card.addEventListener('pointerdown', onDown);
165
- card.addEventListener('pointermove', onMove);
166
- card.addEventListener('pointerup', onUp);
167
- card.addEventListener('pointercancel', onCancel);
168
- discardButton.addEventListener('click', onDiscard);
169
- return () => {
170
- discardButton.removeEventListener('click', onDiscard);
171
- animator.destroy();
172
- card.remove();
173
- status.remove();
174
- };
175
- }
176
-
177
- /**
178
- * Mounts the deck when the wrapper attaches, and takes it down when it
179
- * detaches: its cleanup is the callback ref's.
180
- */
181
- function mountTable(wrapper: HTMLDivElement | null) {
182
- if (wrapper == null) {
183
- return undefined;
184
- }
185
- const table = wrapper.firstElementChild as HTMLElement;
186
- const button = wrapper.querySelector('button') as HTMLButtonElement;
187
- return mountDeck(table, button);
188
- }
189
-
190
- export default function AnimatorPlayingCardsVanilla() {
191
- return (
192
- <div
193
- ref={mountTable}
194
- style={{display: 'grid', gap: 16, padding: 16, maxWidth: 360}}>
195
- <div style={{height: 200, display: 'grid', placeItems: 'center'}} />
196
- <button type="button">Discard the top card</button>
197
- </div>
198
- );
199
- }
@@ -1,21 +0,0 @@
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: 'useAnimator',
7
- name: 'useAnimator — Playing cards',
8
- displayName: 'useAnimator — Playing cards',
9
- description:
10
- 'A playing card that follows a drag: a gentle release springs it back on its release velocity, and a quick flick throws it away with momentum before the next card is dealt. A Discard button moves it off from the keyboard, fading it in place under Reduce Motion, and the discard is announced. Built only on the public useAnimator hook.',
11
- isReady: true,
12
- aspectRatio: 4 / 3,
13
- componentsUsed: [
14
- 'Card',
15
- 'Button',
16
- 'Layout',
17
- 'Text',
18
- 'VisuallyHidden',
19
- 'useAnimator',
20
- ],
21
- };
@@ -1,210 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- 'use client';
4
-
5
- import {useRef, useState} from 'react';
6
- import type {PointerEvent} from 'react';
7
- import {Button} from '@astryxdesign/core/Button';
8
- import {Card} from '@astryxdesign/core/Card';
9
- import {useAnimator} from '@astryxdesign/core/hooks';
10
- import {HStack, VStack} from '@astryxdesign/core/Layout';
11
- import {Text} from '@astryxdesign/core/Text';
12
- import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
13
-
14
- const DECK = [
15
- {rank: 'A', suit: '\u2660', name: 'Ace of spades'},
16
- {rank: 'K', suit: '\u2665', name: 'King of hearts'},
17
- {rank: 'Q', suit: '\u2663', name: 'Queen of clubs'},
18
- {rank: 'J', suit: '\u2666', name: 'Jack of diamonds'},
19
- ];
20
-
21
- /** A release faster than this (px/s) throws the card away. */
22
- const THROW_SPEED = 1000;
23
- /** The slowest throw, so a thrown card always leaves the table. */
24
- const MIN_THROW = 1600;
25
-
26
- interface Sample {
27
- t: number;
28
- x: number;
29
- y: number;
30
- }
31
-
32
- /**
33
- * The release velocity in px/s, over the 80 ms before the release: a finger
34
- * that held still before letting go releases at rest.
35
- */
36
- function releaseVelocity(
37
- samples: Sample[],
38
- releasedAt: number,
39
- ): {x: number; y: number} {
40
- const recent = samples.filter(s => releasedAt - s.t <= 80);
41
- const first = recent[0];
42
- const last = recent.at(-1);
43
- if (last == null || first == null || last.t === first.t) {
44
- return {x: 0, y: 0};
45
- }
46
- const seconds = (last.t - first.t) / 1000;
47
- return {x: (last.x - first.x) / seconds, y: (last.y - first.y) / seconds};
48
- }
49
-
50
- export default function AnimatorPlayingCards() {
51
- const ref = useRef<HTMLDivElement>(null);
52
- const animator = useAnimator(ref);
53
- const [top, setTop] = useState(0);
54
- const [status, setStatus] = useState('');
55
- const drag = useRef<{start: Sample; samples: Sample[]} | null>(null);
56
- // One discard at a time: a press while a card leaves deals no second card.
57
- const discarding = useRef(false);
58
- const card = DECK[top % DECK.length];
59
-
60
- // Announces the discard and deals the next card in place of the old one.
61
- const dealNext = async () => {
62
- setStatus(`${card.name} discarded`);
63
- setTop(index => index + 1);
64
- animator.set({x: 0, y: 0, rotate: 0, scale: 0.9, opacity: 0});
65
- discarding.current = false;
66
- await animator.animate({scale: 1, opacity: 1});
67
- };
68
-
69
- // Starts a discard unless one runs. It also ends a drag in progress: the
70
- // drag's next move would take the discard's motion over and drag the dealt
71
- // card.
72
- const startDiscard = () => {
73
- if (discarding.current) {
74
- return false;
75
- }
76
- discarding.current = true;
77
- drag.current = null;
78
- return true;
79
- };
80
-
81
- // Throws the card away on its release velocity, then deals the next one.
82
- const discard = async (velocity: {x: number; y: number}) => {
83
- if (!startDiscard()) {
84
- return;
85
- }
86
- const speed = Math.hypot(velocity.x, velocity.y);
87
- const boost = speed < MIN_THROW ? MIN_THROW / Math.max(speed, 1) : 1;
88
- const throwX = speed < 1 ? MIN_THROW : velocity.x * boost;
89
- // The card coasts on while it fades; once it is gone, the next card is
90
- // dealt in place, which ends the coast. A coast continues the person's
91
- // throw, so Reduce Motion keeps it.
92
- void animator.decay({x: throwX, y: velocity.y * boost});
93
- await animator.animate({opacity: 0});
94
- await dealNext();
95
- };
96
-
97
- // The button moves the card off on the state-change motion: a planned
98
- // move, which Reduce Motion turns into a fade where the card is.
99
- const discardWithButton = async () => {
100
- if (!startDiscard()) {
101
- return;
102
- }
103
- await animator.animate({x: 400, opacity: 0});
104
- await dealNext();
105
- };
106
-
107
- const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
108
- // A leaving card takes no press. Pinning it would end its discard and deal
109
- // the next card under the finger.
110
- if (discarding.current) {
111
- return;
112
- }
113
- event.currentTarget.setPointerCapture(event.pointerId);
114
- // Pins the card where it shows, so the drag starts there. Only the
115
- // position stops, so a card fading in keeps fading in.
116
- const {x, y, rotate} = animator.get();
117
- animator.set({x, y, rotate});
118
- const start = {
119
- t: event.timeStamp,
120
- x: event.clientX - x,
121
- y: event.clientY - y,
122
- };
123
- drag.current = {start, samples: []};
124
- };
125
-
126
- const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
127
- const current = drag.current;
128
- if (current == null) {
129
- return;
130
- }
131
- const x = event.clientX - current.start.x;
132
- const y = event.clientY - current.start.y;
133
- current.samples.push({t: event.timeStamp, x, y});
134
- // The card follows the finger, turning a little with the drag.
135
- animator.set({x, y, rotate: x / 18});
136
- };
137
-
138
- // A cancelled pointer was not let go, so the card springs back.
139
- const onPointerCancel = () => {
140
- if (drag.current == null) {
141
- return;
142
- }
143
- drag.current = null;
144
- void animator.animate({x: 0, y: 0, rotate: 0});
145
- };
146
-
147
- const onPointerUp = (event: PointerEvent<HTMLDivElement>) => {
148
- const current = drag.current;
149
- drag.current = null;
150
- if (current == null) {
151
- return;
152
- }
153
- const velocity = releaseVelocity(current.samples, event.timeStamp);
154
- if (Math.abs(velocity.x) > THROW_SPEED) {
155
- void discard(velocity);
156
- } else {
157
- // A gentle release springs back, carrying on as it was let go.
158
- void animator.animate({x: 0, y: 0, rotate: 0}, {velocity});
159
- }
160
- };
161
-
162
- return (
163
- <VStack gap={4} style={{maxWidth: 360, padding: 16}}>
164
- <Text type="body">
165
- Drag the card and let go. A gentle release springs it back; a quick
166
- flick throws it away.
167
- </Text>
168
- <div style={{height: 200, display: 'grid', placeItems: 'center'}}>
169
- <Card
170
- ref={ref}
171
- width={120}
172
- minHeight={170}
173
- onPointerDown={onPointerDown}
174
- onPointerMove={onPointerMove}
175
- onPointerUp={onPointerUp}
176
- onPointerCancel={onPointerCancel}
177
- style={{touchAction: 'none', cursor: 'grab', userSelect: 'none'}}
178
- role="img"
179
- aria-label={card.name}>
180
- <VStack gap={1} hAlign="center" style={{paddingBlock: 40}}>
181
- <Text type="display-2" weight="bold">
182
- {card.rank}
183
- </Text>
184
- <Text type="display-3">{card.suit}</Text>
185
- </VStack>
186
- </Card>
187
- </div>
188
- <HStack gap={2}>
189
- <Button
190
- label={`Discard ${card.name}`}
191
- variant="secondary"
192
- onClick={() => void discardWithButton()}
193
- />
194
- <Button
195
- label="Shake"
196
- variant="ghost"
197
- onClick={() =>
198
- void animator.animate(
199
- {x: 0, rotate: 0},
200
- {velocity: {x: 900, rotate: 300}},
201
- )
202
- }
203
- />
204
- </HStack>
205
- <VisuallyHidden as="div" aria-live="polite">
206
- {status}
207
- </VisuallyHidden>
208
- </VStack>
209
- );
210
- }