@astryxdesign/cli 0.7.9-canary.de1be1f → 0.7.9-canary.dedecd0

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 (44) 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/_main-searcher.mjs +1 -1
  5. package/api/search/_words.d.mts +44 -7
  6. package/api/search/_words.mjs +113 -21
  7. package/api/swizzle/_adapter.d.mts +10 -0
  8. package/api/swizzle/_adapter.mjs +24 -1
  9. package/api/swizzle/copy/copy.d.mts +17 -1
  10. package/api/swizzle/copy/copy.mjs +249 -9
  11. package/api/swizzle/swizzle.doc.mjs +1 -1
  12. package/api/swizzle/swizzle.type.mjs +1 -1
  13. package/api/theme/build/build.mjs +21 -1
  14. package/assets/discover/official-packages.json +4 -0
  15. package/assets/docs/tree/calendar-systems.doc.mjs +146 -0
  16. package/assets/docs/tree/calendars.doc.mjs +46 -0
  17. package/assets/docs/tree/i18n-calendars.doc.mjs +51 -0
  18. package/assets/docs/tree/internationalization.doc.mjs +3 -3
  19. package/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.doc.mjs +14 -0
  20. package/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.tsx +94 -0
  21. package/assets/templates/blocks/components/Icon/useIconHookUsage.doc.mjs +19 -0
  22. package/assets/templates/blocks/components/Icon/useIconHookUsage.tsx +68 -0
  23. package/assets/templates/blocks/components/Link/useLinkComponentHookUsage.doc.mjs +14 -0
  24. package/assets/templates/blocks/components/Link/useLinkComponentHookUsage.tsx +89 -0
  25. package/assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla.doc.mjs +14 -0
  26. package/assets/templates/blocks/components/createPanGesture/PanPlayingCardVanilla.tsx +156 -0
  27. package/assets/templates/blocks/components/usePanGesture/PanPlayingCard.doc.mjs +14 -0
  28. package/assets/templates/blocks/components/usePanGesture/PanPlayingCard.tsx +143 -0
  29. package/clients/cli/commands/ensure-core-built.mjs +399 -43
  30. package/clients/cli/commands/swizzle.mjs +10 -0
  31. package/foundation/config/project.mjs +27 -9
  32. package/foundation/discovery/component-discovery.mjs +56 -10
  33. package/foundation/env/search-path.d.mts +12 -0
  34. package/foundation/env/search-path.mjs +71 -43
  35. package/foundation/integrations/manifest-writer.d.mts +3 -4
  36. package/foundation/integrations/manifest-writer.mjs +5 -3
  37. package/foundation/release/cache.d.mts +11 -4
  38. package/foundation/release/cache.mjs +15 -7
  39. package/foundation/response/response-types.doc.mjs +1 -1
  40. package/foundation/text/levenshtein.d.mts +4 -1
  41. package/foundation/text/levenshtein.mjs +44 -1
  42. package/package.json +9 -9
  43. package/api/swizzle/_github.d.mts +0 -8
  44. package/api/swizzle/_github.mjs +0 -22
@@ -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
+ }
@@ -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: 'createPanGesture',
7
+ name: 'createPanGesture — A playing card without React',
8
+ displayName: 'createPanGesture — A playing card without React',
9
+ description:
10
+ 'A playing card built in plain JavaScript with createPanGesture: it follows a drag from a finger, a mouse or a pen, snaps back on a gentle release, flies off 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,156 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ import {createPanGesture} 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
+ /** How far a thrown card travels before the next one is dealt, px. */
16
+ const THROW_DISTANCE = 480;
17
+ const SETTLE = 'translate 300ms cubic-bezier(0.2, 0.9, 0.3, 1.2)';
18
+ const THROW = 'translate 250ms ease-in, opacity 250ms ease-in';
19
+
20
+ /**
21
+ * A deck on a table, in plain JavaScript: no React below this line. The pan
22
+ * reports the drag; the card's own style moves it. Returns a function that
23
+ * takes it down again.
24
+ */
25
+ function mountDeck(table: HTMLElement, discardButton: HTMLButtonElement) {
26
+ let top = 0;
27
+ /** A throw is in flight: the next card is dealt when it ends. */
28
+ let isThrowing = false;
29
+ /** The drag in progress met a throw: the rest of it moves nothing. */
30
+ let isIgnoringDrag = false;
31
+ const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
32
+ const card = document.createElement('div');
33
+ card.textContent = DECK[0].face;
34
+ // An image's name is all a screen reader announces, so it names the card.
35
+ card.setAttribute('role', 'img');
36
+ card.setAttribute('aria-label', DECK[0].name);
37
+ Object.assign(card.style, {
38
+ width: '120px',
39
+ height: '170px',
40
+ display: 'grid',
41
+ placeItems: 'center',
42
+ font: 'bold 40px system-ui, sans-serif',
43
+ borderRadius: '12px',
44
+ backgroundColor: 'var(--color-background-surface)',
45
+ color: 'var(--color-text-primary)',
46
+ boxShadow: '0 2px 8px rgb(0 0 0 / 0.2)',
47
+ cursor: 'grab',
48
+ userSelect: 'none',
49
+ });
50
+ // Announces each discard to screen readers.
51
+ const status = document.createElement('div');
52
+ status.setAttribute('aria-live', 'polite');
53
+ Object.assign(status.style, {
54
+ position: 'absolute',
55
+ width: '1px',
56
+ height: '1px',
57
+ overflow: 'hidden',
58
+ clipPath: 'inset(50%)',
59
+ whiteSpace: 'nowrap',
60
+ });
61
+ table.append(card, status);
62
+
63
+ /** Move the card, with a transition unless the person reduces motion. */
64
+ function moveTo(x: number, y: number, transition: string) {
65
+ card.style.transition = reduceMotion.matches ? 'none' : transition;
66
+ card.style.translate = `${x}px ${y}px`;
67
+ }
68
+
69
+ function discard(direction: number) {
70
+ // One throw at a time: a second Discard during it would deal twice.
71
+ if (isThrowing) {
72
+ return;
73
+ }
74
+ isThrowing = true;
75
+ // The drag in progress, if any, moves nothing more.
76
+ isIgnoringDrag = true;
77
+ moveTo(direction * THROW_DISTANCE, 0, THROW);
78
+ card.style.opacity = '0';
79
+ const deal = () => {
80
+ isThrowing = false;
81
+ status.textContent = `${DECK[top % DECK.length].name} discarded`;
82
+ top += 1;
83
+ card.textContent = DECK[top % DECK.length].face;
84
+ card.setAttribute('aria-label', DECK[top % DECK.length].name);
85
+ moveTo(0, 0, 'none');
86
+ card.style.opacity = '1';
87
+ };
88
+ if (reduceMotion.matches) {
89
+ deal();
90
+ } else {
91
+ card.addEventListener('transitionend', deal, {once: true});
92
+ }
93
+ }
94
+
95
+ const pan = createPanGesture(card, {
96
+ onPan: ({state, translation, velocity}) => {
97
+ // A drag that meets a throw is ignored to its end. Its moves would
98
+ // cancel the throw's transitions, and the next card would jump to it.
99
+ if (state === 'began') {
100
+ isIgnoringDrag = isThrowing;
101
+ }
102
+ if (isIgnoringDrag) {
103
+ return;
104
+ }
105
+ if (state === 'began' || state === 'changed') {
106
+ // Follows the finger: translation leaves out the travel the drag
107
+ // needed to begin, so the card does not jump.
108
+ moveTo(translation.x, translation.y, 'none');
109
+ } else if (state === 'ended' && Math.abs(velocity.x) > THROW_SPEED) {
110
+ discard(Math.sign(velocity.x));
111
+ } else {
112
+ moveTo(0, 0, SETTLE);
113
+ }
114
+ },
115
+ });
116
+ // The drag's keyboard and assistive-technology path (WCAG 2.5.7).
117
+ const onDiscard = () => discard(1);
118
+ discardButton.addEventListener('click', onDiscard);
119
+ return () => {
120
+ discardButton.removeEventListener('click', onDiscard);
121
+ pan.destroy();
122
+ card.remove();
123
+ status.remove();
124
+ };
125
+ }
126
+
127
+ /**
128
+ * Mounts the deck when the wrapper attaches, and takes it down when it
129
+ * detaches: its cleanup is the callback ref's.
130
+ */
131
+ function mountTable(wrapper: HTMLDivElement | null) {
132
+ if (wrapper == null) {
133
+ return undefined;
134
+ }
135
+ const table = wrapper.firstElementChild as HTMLElement;
136
+ const button = wrapper.querySelector('button') as HTMLButtonElement;
137
+ return mountDeck(table, button);
138
+ }
139
+
140
+ export default function PanPlayingCardVanilla() {
141
+ return (
142
+ <div
143
+ ref={mountTable}
144
+ style={{display: 'grid', gap: 16, padding: 16, maxWidth: 360}}>
145
+ <div
146
+ style={{
147
+ height: 200,
148
+ display: 'grid',
149
+ placeItems: 'center',
150
+ overflow: 'hidden',
151
+ }}
152
+ />
153
+ <button type="button">Discard the top card</button>
154
+ </div>
155
+ );
156
+ }
@@ -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: 'usePanGesture',
7
+ name: 'usePanGesture — A playing card',
8
+ displayName: 'usePanGesture — A playing card',
9
+ description:
10
+ 'A playing card built with usePanGesture: it follows a drag from a finger, a mouse or a pen with no render per move, snaps back on a gentle release, flies off on a quick flick, and a button discards it from the keyboard.',
11
+ isReady: true,
12
+ aspectRatio: 4 / 3,
13
+ componentsUsed: [],
14
+ };
@@ -0,0 +1,143 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ import {useRef, useState} from 'react';
6
+ import {flushSync} from 'react-dom';
7
+ import {usePanGesture} from '@astryxdesign/core/hooks';
8
+
9
+ const DECK = [
10
+ {face: 'A\u2660', name: 'Ace of spades'},
11
+ {face: 'K\u2665', name: 'King of hearts'},
12
+ {face: 'Q\u2663', name: 'Queen of clubs'},
13
+ {face: 'J\u2666', name: 'Jack of diamonds'},
14
+ ];
15
+ /** A release faster than this (px/s) throws the card away. */
16
+ const THROW_SPEED = 1000;
17
+ /** How far a thrown card travels before the next one is dealt, px. */
18
+ const THROW_DISTANCE = 480;
19
+ const SETTLE = 'translate 300ms cubic-bezier(0.2, 0.9, 0.3, 1.2)';
20
+ const THROW = 'translate 250ms ease-in, opacity 250ms ease-in';
21
+
22
+ export default function PanPlayingCard() {
23
+ const card = useRef<HTMLDivElement>(null);
24
+ const [top, setTop] = useState(0);
25
+ const [announcement, setAnnouncement] = useState('');
26
+ /** A throw is in flight: the next card is dealt when it ends. */
27
+ const throwing = useRef(false);
28
+ /** The drag in progress met a throw: the rest of it moves nothing. */
29
+ const ignoringDrag = useRef(false);
30
+
31
+ /** Move the card, with a transition unless the person reduces motion. */
32
+ function moveTo(x: number, y: number, transition: string) {
33
+ const element = card.current;
34
+ if (element == null) {
35
+ return;
36
+ }
37
+ const reduced = window.matchMedia(
38
+ '(prefers-reduced-motion: reduce)',
39
+ ).matches;
40
+ element.style.transition = reduced ? 'none' : transition;
41
+ element.style.translate = `${x}px ${y}px`;
42
+ }
43
+
44
+ function discard(direction: number) {
45
+ const element = card.current;
46
+ // One throw at a time: a second Discard during it would deal twice.
47
+ if (element == null || throwing.current) {
48
+ return;
49
+ }
50
+ throwing.current = true;
51
+ // The drag in progress, if any, moves nothing more.
52
+ ignoringDrag.current = true;
53
+ moveTo(direction * THROW_DISTANCE, 0, THROW);
54
+ element.style.opacity = '0';
55
+ const deal = () => {
56
+ throwing.current = false;
57
+ // Commit the next card's face first. A reset before that paints the
58
+ // discarded card back at the centre for one frame.
59
+ flushSync(() => {
60
+ setAnnouncement(`${DECK[top % DECK.length].name} discarded`);
61
+ setTop(value => value + 1);
62
+ });
63
+ moveTo(0, 0, 'none');
64
+ element.style.opacity = '1';
65
+ };
66
+ if (element.style.transition === 'none') {
67
+ deal();
68
+ } else {
69
+ element.addEventListener('transitionend', deal, {once: true});
70
+ }
71
+ }
72
+
73
+ // The drag writes the card's style in onPan: no render per move.
74
+ usePanGesture(card, {
75
+ onPan: ({state, translation, velocity}) => {
76
+ // A drag that meets a throw is ignored to its end. Its moves would
77
+ // cancel the throw's transitions, and the next card would jump to it.
78
+ if (state === 'began') {
79
+ ignoringDrag.current = throwing.current;
80
+ }
81
+ if (ignoringDrag.current) {
82
+ return;
83
+ }
84
+ if (state === 'began' || state === 'changed') {
85
+ moveTo(translation.x, translation.y, 'none');
86
+ } else if (state === 'ended' && Math.abs(velocity.x) > THROW_SPEED) {
87
+ discard(Math.sign(velocity.x));
88
+ } else {
89
+ moveTo(0, 0, SETTLE);
90
+ }
91
+ },
92
+ });
93
+
94
+ return (
95
+ <div style={{display: 'grid', gap: 16, padding: 16, maxWidth: 360}}>
96
+ <div
97
+ style={{
98
+ height: 200,
99
+ display: 'grid',
100
+ placeItems: 'center',
101
+ overflow: 'hidden',
102
+ }}>
103
+ <div
104
+ ref={card}
105
+ // An image's name is all a screen reader announces, so it names the
106
+ // card.
107
+ role="img"
108
+ aria-label={DECK[top % DECK.length].name}
109
+ style={{
110
+ width: 120,
111
+ height: 170,
112
+ display: 'grid',
113
+ placeItems: 'center',
114
+ font: 'bold 40px system-ui, sans-serif',
115
+ borderRadius: 12,
116
+ backgroundColor: 'var(--color-background-surface)',
117
+ color: 'var(--color-text-primary)',
118
+ boxShadow: '0 2px 8px rgb(0 0 0 / 0.2)',
119
+ cursor: 'grab',
120
+ userSelect: 'none',
121
+ }}>
122
+ {DECK[top % DECK.length].face}
123
+ </div>
124
+ </div>
125
+ {/* The drag's keyboard and assistive-technology path (WCAG 2.5.7). */}
126
+ <button type="button" onClick={() => discard(1)}>
127
+ Discard the top card
128
+ </button>
129
+ <div
130
+ aria-live="polite"
131
+ style={{
132
+ position: 'absolute',
133
+ width: 1,
134
+ height: 1,
135
+ overflow: 'hidden',
136
+ clipPath: 'inset(50%)',
137
+ whiteSpace: 'nowrap',
138
+ }}>
139
+ {announcement}
140
+ </div>
141
+ </div>
142
+ );
143
+ }