@astryxdesign/cli 0.7.7-canary.c0929c8 → 0.7.7-canary.c19ca12

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 (25) hide show
  1. package/api/integration/authoring-checks.mjs +31 -0
  2. package/api/integration/check/check.mjs +8 -3
  3. package/assets/discover/official-packages.json +0 -4
  4. package/assets/templates/blocks/components/Hooks/useGridFocusHookUsage.doc.mjs +14 -0
  5. package/assets/templates/blocks/components/Hooks/useGridFocusHookUsage.tsx +86 -0
  6. package/assets/templates/blocks/components/Hooks/useOverflowHookUsage.doc.mjs +14 -0
  7. package/assets/templates/blocks/components/Hooks/useOverflowHookUsage.tsx +89 -0
  8. package/assets/templates/blocks/components/Hooks/usePressFeedbackHookUsage.tsx +24 -21
  9. package/assets/templates/blocks/components/Outline/useOutlineFromMarkdownHookUsage.doc.mjs +14 -0
  10. package/assets/templates/blocks/components/Outline/useOutlineFromMarkdownHookUsage.tsx +69 -0
  11. package/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.doc.mjs +14 -0
  12. package/assets/templates/blocks/components/createAnimator/AnimatorPlayingCardsVanilla.tsx +199 -0
  13. package/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.doc.mjs +21 -0
  14. package/assets/templates/blocks/components/useAnimator/AnimatorPlayingCards.tsx +210 -0
  15. package/foundation/discovery/component-discovery.mjs +26 -6
  16. package/foundation/discovery/doc-types.mjs +4 -2
  17. package/foundation/discovery/prop-drift.mjs +6 -0
  18. package/foundation/discovery/source-file-cache.d.mts +15 -0
  19. package/foundation/discovery/source-file-cache.mjs +140 -0
  20. package/foundation/discovery/template-adapter.d.mts +7 -3
  21. package/foundation/discovery/template-adapter.mjs +150 -10
  22. package/foundation/fs/listing-cache.d.mts +15 -0
  23. package/foundation/fs/listing-cache.mjs +50 -1
  24. package/foundation/fs/paths.mjs +50 -5
  25. package/package.json +9 -9
@@ -27,6 +27,7 @@ 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';
30
31
  import {
31
32
  discoverIntegrationComponents,
32
33
  discoverOwnedComponents,
@@ -154,6 +155,16 @@ function addErrors(issues, errors, code) {
154
155
  * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationTemplateConflictResponse>}
155
156
  */
156
157
  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) {
157
168
  const {cwd = process.cwd()} = options;
158
169
  const resolved = await resolveIntegration(pkg, cwd);
159
170
  const validated = resolved.found;
@@ -291,6 +302,16 @@ export async function integrationTemplateConflicts(pkg, options = {}) {
291
302
  * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationComponentConflictResponse>}
292
303
  */
293
304
  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) {
294
315
  const {cwd = process.cwd()} = options;
295
316
  const resolved = await resolveIntegration(pkg, cwd);
296
317
  const validated = resolved.found;
@@ -387,6 +408,16 @@ export async function integrationComponentConflicts(pkg, options = {}) {
387
408
  * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationDocConflictResponse>}
388
409
  */
389
410
  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) {
390
421
  const {cwd = process.cwd()} = options;
391
422
  const resolved = await resolveIntegration(pkg, cwd);
392
423
  const validated = resolved.found;
@@ -36,6 +36,7 @@ import {
36
36
  summarizeIssues,
37
37
  validateIntegration,
38
38
  } from '../validate-integration.mjs';
39
+ import {withListingCache} from '../../../foundation/fs/listing-cache.mjs';
39
40
 
40
41
  /** @typedef {import('../integration-check.type.mjs').IntegrationCheckName} IntegrationCheckName */
41
42
  /** @typedef {import('../integration-check.type.mjs').IntegrationCheckReport} IntegrationCheckReport */
@@ -244,9 +245,13 @@ export async function integrationCheck(options = {}) {
244
245
  /** @type {IntegrationCheckResponse[]} */
245
246
  const responses = [];
246
247
  responses.push(await validateIntegration(undefined, {cwd}));
247
- responses.push(await integrationComponentConflicts(undefined, {cwd}));
248
- responses.push(await integrationTemplateConflicts(undefined, {cwd}));
249
- responses.push(await integrationDocConflicts(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
+ });
250
255
 
251
256
  const [validation] = responses;
252
257
  return {
@@ -132,10 +132,6 @@
132
132
  "kind": "component",
133
133
  "name": "EmojiPicker"
134
134
  },
135
- {
136
- "kind": "component",
137
- "name": "InfoTip"
138
- },
139
135
  {
140
136
  "kind": "component",
141
137
  "name": "ListInput"
@@ -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: 'useGridFocus',
7
+ name: 'useGridFocus — Color Swatch Grid',
8
+ displayName: 'useGridFocus — Color Swatch Grid',
9
+ description:
10
+ 'A color swatch picker in rows of eight with one Tab stop. useGridFocus moves focus with the arrow keys, Home and End, and Ctrl+Home and Ctrl+End. Each swatch is a button, so Enter or a click picks it.',
11
+ isReady: true,
12
+ aspectRatio: 4 / 3,
13
+ componentsUsed: ['Card', 'Text', 'Layout'],
14
+ };
@@ -0,0 +1,86 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ import {useState} from 'react';
6
+ import {Card} from '@astryxdesign/core/Card';
7
+ import {useGridFocus} from '@astryxdesign/core/hooks';
8
+ import {VStack} from '@astryxdesign/core/Layout';
9
+ import {Text} from '@astryxdesign/core/Text';
10
+
11
+ const COLUMNS = 8;
12
+
13
+ const SWATCHES = [
14
+ {name: 'Red', value: '#e5484d'},
15
+ {name: 'Tomato', value: '#f76b15'},
16
+ {name: 'Amber', value: '#ffc53d'},
17
+ {name: 'Lime', value: '#bdee63'},
18
+ {name: 'Green', value: '#30a46c'},
19
+ {name: 'Teal', value: '#12a594'},
20
+ {name: 'Cyan', value: '#00a2c7'},
21
+ {name: 'Blue', value: '#0090ff'},
22
+ {name: 'Indigo', value: '#3e63dd'},
23
+ {name: 'Violet', value: '#6e56cf'},
24
+ {name: 'Purple', value: '#8e4ec6'},
25
+ {name: 'Plum', value: '#ab4aba'},
26
+ {name: 'Pink', value: '#d6409f'},
27
+ {name: 'Brown', value: '#ad7f58'},
28
+ {name: 'Gray', value: '#8d8d8d'},
29
+ {name: 'Black', value: '#111111'},
30
+ ];
31
+
32
+ const ROWS = Array.from({length: SWATCHES.length / COLUMNS}, (_, row) =>
33
+ SWATCHES.slice(row * COLUMNS, (row + 1) * COLUMNS),
34
+ );
35
+
36
+ export default function UseGridFocusHookUsage() {
37
+ const [selected, setSelected] = useState(SWATCHES[0].name);
38
+ const {gridRef, handleKeyDown, handleFocus} = useGridFocus<HTMLDivElement>({
39
+ columns: COLUMNS,
40
+ cellSelector: '[role="gridcell"]',
41
+ getFocusTarget: cell => cell.querySelector('button'),
42
+ hasRovingTabIndex: true,
43
+ });
44
+
45
+ return (
46
+ <Card padding={4}>
47
+ <VStack gap={3}>
48
+ <Text type="body">Selected: {selected}</Text>
49
+ <div
50
+ ref={gridRef}
51
+ role="grid"
52
+ aria-label="Colors"
53
+ onKeyDown={handleKeyDown}
54
+ onFocus={handleFocus}
55
+ style={{display: 'flex', flexDirection: 'column', gap: 4}}>
56
+ {ROWS.map((row, index) => (
57
+ <div key={index} role="row" style={{display: 'flex', gap: 4}}>
58
+ {row.map(swatch => (
59
+ <div
60
+ key={swatch.name}
61
+ role="gridcell"
62
+ aria-selected={swatch.name === selected}>
63
+ <button
64
+ type="button"
65
+ aria-label={swatch.name}
66
+ aria-pressed={swatch.name === selected}
67
+ onClick={() => setSelected(swatch.name)}
68
+ style={{
69
+ width: 28,
70
+ height: 28,
71
+ border: 'none',
72
+ boxShadow:
73
+ 'inset 0 0 0 1px var(--color-border-emphasized)',
74
+ borderRadius: 4,
75
+ background: swatch.value,
76
+ }}
77
+ />
78
+ </div>
79
+ ))}
80
+ </div>
81
+ ))}
82
+ </div>
83
+ </VStack>
84
+ </Card>
85
+ );
86
+ }
@@ -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: 'useOverflow',
7
+ name: 'useOverflow — Editor Toolbar',
8
+ displayName: 'useOverflow — Editor Toolbar',
9
+ description:
10
+ 'Resize the card: useOverflow moves the toolbar actions that do not fit into a More menu, and shows them again when the card gets wider.',
11
+ isReady: true,
12
+ aspectRatio: 16 / 9,
13
+ componentsUsed: ['Card', 'Button', 'DropdownMenu'],
14
+ };
@@ -0,0 +1,89 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ import * as stylex from '@stylexjs/stylex';
6
+ import {useOverflow} from '@astryxdesign/core/hooks';
7
+ import {Button} from '@astryxdesign/core/Button';
8
+ import {Card} from '@astryxdesign/core/Card';
9
+ import {DropdownMenu} from '@astryxdesign/core/DropdownMenu';
10
+
11
+ const actions = [
12
+ 'Bold',
13
+ 'Italic',
14
+ 'Underline',
15
+ 'Strikethrough',
16
+ 'Link',
17
+ 'Quote',
18
+ 'Code',
19
+ 'Clear formatting',
20
+ ];
21
+
22
+ const GAP = 4;
23
+
24
+ const styles = stylex.create({
25
+ box: {
26
+ resize: 'horizontal',
27
+ overflow: 'hidden',
28
+ width: 480,
29
+ minWidth: 120,
30
+ maxWidth: '100%',
31
+ },
32
+ row: {
33
+ display: 'flex',
34
+ gap: GAP,
35
+ },
36
+ // Takes no space and paints nothing, so the hook measures every item
37
+ // without a flicker. Do not use display: none, which stops measurement.
38
+ measure: {
39
+ position: 'absolute',
40
+ visibility: 'hidden',
41
+ height: 0,
42
+ overflow: 'hidden',
43
+ whiteSpace: 'nowrap',
44
+ pointerEvents: 'none',
45
+ },
46
+ });
47
+
48
+ function MoreMenu({items}: {items: string[]}) {
49
+ return (
50
+ <DropdownMenu
51
+ button={{label: 'More', variant: 'ghost', size: 'sm'}}
52
+ items={items.map(label => ({label}))}
53
+ />
54
+ );
55
+ }
56
+
57
+ export default function UseOverflowHookUsage() {
58
+ const {containerRef, measureRef, visibleCount, hasOverflow} = useOverflow(
59
+ actions.length,
60
+ {gap: GAP},
61
+ );
62
+
63
+ return (
64
+ <Card padding={2} xstyle={styles.box}>
65
+ <div
66
+ ref={measureRef}
67
+ aria-hidden="true"
68
+ inert
69
+ {...stylex.props(styles.row, styles.measure)}>
70
+ {actions.map(label => (
71
+ <Button key={label} label={label} variant="ghost" size="sm" />
72
+ ))}
73
+ <div data-overflow-indicator>
74
+ <MoreMenu items={actions} />
75
+ </div>
76
+ </div>
77
+ <div
78
+ ref={containerRef}
79
+ role="group"
80
+ aria-label="Text formatting"
81
+ {...stylex.props(styles.row)}>
82
+ {actions.slice(0, visibleCount).map(label => (
83
+ <Button key={label} label={label} variant="ghost" size="sm" />
84
+ ))}
85
+ {hasOverflow && <MoreMenu items={actions.slice(visibleCount)} />}
86
+ </div>
87
+ </Card>
88
+ );
89
+ }
@@ -9,7 +9,7 @@ import {
9
9
  focusOutlineStyles,
10
10
  interactionOverlayStyles,
11
11
  } from '@astryxdesign/core/utils';
12
- import {PlayingCardContents} from '@astryx-docs/demo-content';
12
+ import {DemoHint, PlayingCardContents} from '@astryx-docs/demo-content';
13
13
 
14
14
  export default function UsePressFeedbackHookUsage() {
15
15
  const pressable = usePressFeedback();
@@ -17,25 +17,28 @@ export default function UsePressFeedbackHookUsage() {
17
17
  const flip = () => setIsFaceUp(faceUp => !faceUp);
18
18
 
19
19
  return (
20
- <Card
21
- {...pressable}
22
- xstyle={[
23
- interactionOverlayStyles.backgroundImage,
24
- focusOutlineStyles.focusVisible,
25
- ]}
26
- width={160}
27
- role="button"
28
- tabIndex={0}
29
- aria-label="Flip card"
30
- aria-pressed={!isFaceUp}
31
- onClick={flip}
32
- onKeyDown={event => {
33
- if (event.key === 'Enter' || event.key === ' ') {
34
- event.preventDefault();
35
- flip();
36
- }
37
- }}>
38
- <PlayingCardContents rank="Q" suit="hearts" faceDown={!isFaceUp} />
39
- </Card>
20
+ <DemoHint text="Press and hold the card to see the press; tap, click, Enter or Space to flip it.">
21
+ <Card
22
+ {...pressable}
23
+ xstyle={[
24
+ interactionOverlayStyles.backgroundImage,
25
+ focusOutlineStyles.focusVisible,
26
+ ]}
27
+ width={120}
28
+ padding={1}
29
+ role="button"
30
+ tabIndex={0}
31
+ aria-label="Flip card"
32
+ aria-pressed={!isFaceUp}
33
+ onClick={flip}
34
+ onKeyDown={event => {
35
+ if (event.key === 'Enter' || event.key === ' ') {
36
+ event.preventDefault();
37
+ flip();
38
+ }
39
+ }}>
40
+ <PlayingCardContents rank="Q" suit="hearts" faceDown={!isFaceUp} />
41
+ </Card>
42
+ </DemoHint>
40
43
  );
41
44
  }
@@ -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: 'useOutlineFromMarkdown',
7
+ name: 'useOutlineFromMarkdown — Docs Article',
8
+ displayName: 'useOutlineFromMarkdown — Docs Article',
9
+ description:
10
+ 'A docs-style article with an Outline next to it, built from the same Markdown string through useOutlineFromMarkdown. "Add section" appends a heading to the string, and a new entry that links to it appears in the outline.',
11
+ isReady: true,
12
+ aspectRatio: 16 / 9,
13
+ componentsUsed: ['Markdown', 'Outline', 'ScrollableArea', 'Button', 'Layout'],
14
+ };
@@ -0,0 +1,69 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ import {useRef, useState} from 'react';
6
+ import {Button} from '@astryxdesign/core/Button';
7
+ import {HStack, VStack} from '@astryxdesign/core/Layout';
8
+ import {Markdown} from '@astryxdesign/core/Markdown';
9
+ import {Outline, useOutlineFromMarkdown} from '@astryxdesign/core/Outline';
10
+ import {ScrollableArea} from '@astryxdesign/core/ScrollableArea';
11
+
12
+ const ARTICLE = `## Before you start
13
+
14
+ Check that your project builds on the current release. Commit your work, so
15
+ that you can compare the result of the upgrade.
16
+
17
+ ## Run the upgrade
18
+
19
+ Update the packages, then rebuild the project. The upgrade changes no source
20
+ files.
21
+
22
+ ### Update the packages
23
+
24
+ Install the new version of every package at the same time. Mixed versions fail
25
+ the build.
26
+
27
+ ### Rebuild the project
28
+
29
+ Delete the build output first. A stale cache can hide a real error.
30
+
31
+ ## Check the result
32
+
33
+ Open the pages that you use most, and compare them with the earlier build.
34
+ `;
35
+
36
+ const NEW_SECTION = `
37
+ ## New section
38
+
39
+ The button added this heading to the Markdown string.
40
+ `;
41
+
42
+ export default function UseOutlineFromMarkdownHookUsage() {
43
+ const [markdown, setMarkdown] = useState(ARTICLE);
44
+ const items = useOutlineFromMarkdown(markdown);
45
+ const articleRef = useRef<HTMLDivElement>(null);
46
+
47
+ return (
48
+ <HStack gap={6} align="start" width="100%">
49
+ <ScrollableArea
50
+ ref={articleRef}
51
+ label="Article"
52
+ height={320}
53
+ width="100%">
54
+ <Markdown>{markdown}</Markdown>
55
+ </ScrollableArea>
56
+ <VStack gap={3} align="start" width={220}>
57
+ {/* A non-zero offset moves only the article. With 0, a click also moves
58
+ the page around the article. */}
59
+ <Outline items={items} scrollContainerRef={articleRef} offset={8} />
60
+ <Button
61
+ label="Add section"
62
+ variant="secondary"
63
+ size="sm"
64
+ onClick={() => setMarkdown(current => current + NEW_SECTION)}
65
+ />
66
+ </VStack>
67
+ </HStack>
68
+ );
69
+ }
@@ -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: '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
+ };
@@ -0,0 +1,199 @@
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
+ }
@@ -0,0 +1,21 @@
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
+ };