From 0a3b121fd628aff19603b013d5ae605cc1d34ac5 Mon Sep 17 00:00:00 2001 From: Eric Chernuka Date: Mon, 9 Nov 2026 23:06:56 -0600 Subject: [PATCH 1/3] Build Help, Copy's confirmation and the format radios from the platform Base UI was 135 KB of a 492 KB script, and we used it for three small parts. Help is now a , the confirmation is a manual popover anchored to Copy, and the format picker is plain radio inputs. The script drops to 357 KB (165 KB to 118 KB gzipped). I ran the same script against master and this branch. The animations match frame for frame, Help's screenshots match pixel for pixel, and the new Help and card tests pass on both. Two Base UI behaviours had to be added by hand: focus moves to the link when Help opens, and goes back to Help after a click outside or a Tab out. What we give up: the confirmation is no longer a focusable dialog in a Notifications landmark, so F6, swipe to dismiss and pause on hover are gone. Screen readers now hear it through the app's announcer. ADR 0007 has the reasoning, and CODING_STANDARDS no longer points at Base UI. --- .agents/skills/verify-huebo/SKILL.md | 2 +- .agents/skills/verify-huebo/features/card.md | 5 +- .../verify-huebo/features/page-and-layout.md | 2 +- CODING_STANDARDS.md | 5 +- docs/adr/0007-popups-from-the-platform.md | 20 +++ package.json | 1 - pnpm-lock.yaml | 93 +----------- src/picker/Header.tsx | 142 ++++++++++++------ src/picker/__tests__/Header.test.tsx | 62 ++++++++ src/picker/color-card/ColorCardRoot.tsx | 127 ++++++++++------ src/picker/color-card/Copy.tsx | 25 +-- src/picker/color-card/Format.tsx | 42 +++--- .../color-card/__tests__/ColorCard.test.tsx | 33 +++- .../color-card/__tests__/confirmation.test.ts | 59 ++++++++ src/picker/color-card/confirmation.ts | 51 +++++++ src/shared/transition.ts | 22 --- 16 files changed, 436 insertions(+), 255 deletions(-) create mode 100644 docs/adr/0007-popups-from-the-platform.md create mode 100644 src/picker/__tests__/Header.test.tsx create mode 100644 src/picker/color-card/__tests__/confirmation.test.ts create mode 100644 src/picker/color-card/confirmation.ts delete mode 100644 src/shared/transition.ts diff --git a/.agents/skills/verify-huebo/SKILL.md b/.agents/skills/verify-huebo/SKILL.md index 80106e3..5474d96 100644 --- a/.agents/skills/verify-huebo/SKILL.md +++ b/.agents/skills/verify-huebo/SKILL.md @@ -69,7 +69,7 @@ These are the stable handles. Use them, not CSS classes or the order of elements | The picked square | `td[aria-selected="true"]`, whose `button` carries the name | | Format | `find role radio click --name "RGB"` (or `HSB`, `Hex`) | | Copy | `find role button click --name "Copy Hex"`. The name follows the format | -| Copy confirmation | the dialog `Copied Hex #4998BF` inside the region `Notifications` | +| Copy confirmation | the text `Copied Hex #4998BF` inside the region `Selected colour`, and the same words in the page's polite live region | | Help | `find role button click --name "Help"`, which opens the dialog `Picking a colour` | Read state through what a person or the browser sees: `agent-browser get url`, `agent-browser get attr '[role="slider"]' aria-valuenow`, `agent-browser eval "history.length"`, `agent-browser eval "document.title"`, and `agent-browser snapshot -c`. diff --git a/.agents/skills/verify-huebo/features/card.md b/.agents/skills/verify-huebo/features/card.md index cd20c44..85c29ad 100644 --- a/.agents/skills/verify-huebo/features/card.md +++ b/.agents/skills/verify-huebo/features/card.md @@ -22,7 +22,7 @@ Preconditions: - **Values.** Run `agent-browser get text '[aria-label="Selected colour"]'`. It includes `#4998BF`, `HSB 200,62,75`, `RGB 73,152,191`, `White text 3.2:1, AA large` and `Black text 6.5:1, AA`. - **Copy (`card-copy`).** Run `agent-browser find role button click --name "Copy Hex"` and `agent-browser wait --text "Copied Hex #4998BF"`. Then `.agents/skills/verify-huebo/input.mjs read-clipboard` prints `#4998BF`. -- **Dedupe (`card-copy-dedupe`).** Click `Copy Hex` three times in a row. `agent-browser snapshot -s '[aria-label="Notifications"]'` lists exactly one dialog, `Copied Hex #4998BF`. +- **Dedupe (`card-copy-dedupe`).** Click `Copy Hex` three times in a row. `agent-browser eval "[...document.querySelector('[aria-label=\"Selected colour\"]').querySelectorAll(':popover-open')].map(e => e.textContent)"` lists exactly one confirmation, `Copied Hex #4998BF`. - **Format (`card-format`).** Run `agent-browser find role radio click --name "RGB"`. The copy button's name becomes `Copy RGB`. Then `agent-browser reload`, and the `RGB` radio is still checked (`snapshot -c` shows `checked=true`). - **Empty (`card-empty`).** Open `"$URL/200"`. The card reads `Pick a colour`. - **Proof.** Run `snapshot -c > $EVIDENCE/card/.aria.txt` and `screenshot $EVIDENCE/card/.png`. Put the clipboard output in `steps.txt`. @@ -30,6 +30,7 @@ Preconditions: ## Gotchas - `agent-browser clipboard read` is denied in this browser. Use `input.mjs read-clipboard`, which grants the permission for this tab's origin and reads. -- The toast closes on its own after a few seconds. Snapshot it right after the click. +- The toast closes on its own after 1.8 seconds. Snapshot it right after the click. +- The toast is hidden from screen readers, which hear it through the page's live region instead, so `snapshot -c` doesn't list it. Read it with `get text` or the `:popover-open` query above. - A failed write shows `Couldn't copy ` and no tick. agent-browser can't make the clipboard fail on demand, so that path is `not driven`. `src/picker/color-card/__tests__/ColorCard.test.tsx` covers it. - The format persists in `localStorage`, so clear it before a recipe that expects Hex. diff --git a/.agents/skills/verify-huebo/features/page-and-layout.md b/.agents/skills/verify-huebo/features/page-and-layout.md index 621cefc..0021b1e 100644 --- a/.agents/skills/verify-huebo/features/page-and-layout.md +++ b/.agents/skills/verify-huebo/features/page-and-layout.md @@ -31,5 +31,5 @@ Preconditions: - Change the viewport before `open`, or `reload` after, so the layout query is evaluated fresh. - The `html` background has a 500 ms transition. Without `input.mjs front`, the tab is hidden, the transition never runs, and the background reads `rgba(0, 0, 0, 0)`. Wait about 600 ms after a change before reading it. -- Help that's still in the snapshot after Escape means the tab is hidden. Base UI waits for the close transition, which only runs in a visible tab. Run `input.mjs front`. +- An Escape that the page doesn't swallow hides agent-browser's tab, and closing Help with Escape is one. Run `input.mjs front` after every Escape, or later transitions freeze at their first frame and Help reads as invisible while open. - The status-bar and toolbar strip only shows on a real phone browser. Here, `page-tint` checks the root background and `theme-color`, which are what that strip uses. diff --git a/CODING_STANDARDS.md b/CODING_STANDARDS.md index 1940b36..99aa851 100644 --- a/CODING_STANDARDS.md +++ b/CODING_STANDARDS.md @@ -15,8 +15,9 @@ How code in Huebo is written. The terms come from `GLOSSARY.md`, and the decisio - The React Compiler is on. Don't write `useMemo`, `useCallback` or `memo`. - Use `useEffectEvent` for callbacks that an effect calls but shouldn't re-run on. - An effect only connects to something outside React, such as a DOM listener, history or the motion store. If it sets state from other state, derive the value instead. -- Build related parts as compound components (`HueDial.Root`, `HueDial.Ring`, …), sharing through context, not with boolean props. Use Base UI for popovers, toasts and radios. -- Base UI popups that portal need a container inside the themed tree, as in `Header.tsx`, or they lose the hue theme's variables. +- Build related parts as compound components (`HueDial.Root`, `HueDial.Ring`, …), sharing through context, not with boolean props. +- Build popups and form controls from the platform: the `popover` attribute, CSS anchor positioning, and native inputs. Help in `Header.tsx`, Copy's confirmation in `ColorCardRoot.tsx`, and the radios in `Format.tsx` are the pattern. Don't add a component library for them (ADR-0007). +- A popover stays in the themed tree, so it keeps the hue theme's variables. Don't portal it. ## Styling diff --git a/docs/adr/0007-popups-from-the-platform.md b/docs/adr/0007-popups-from-the-platform.md new file mode 100644 index 0000000..acb27f9 --- /dev/null +++ b/docs/adr/0007-popups-from-the-platform.md @@ -0,0 +1,20 @@ +# Popups and radios come from the platform, not a component library + +Help, Copy's confirmation and the format radios were built on Base UI. Together they cost 135 KB of a 492 KB script, more than a quarter of it, for three small parts. They are now built on the platform instead: + +- **Help** is a `` opened by `popovertarget`. The browser gives the toggle, Escape, light dismiss, the top layer and `aria-expanded`. CSS anchor positioning hangs it below Help and flips or shifts it to stay on screen. `@starting-style` and `transition-behavior: allow-discrete` animate it in and out. Huebo adds two things Base UI did: focus moves to the link on open, and back to Help after a click outside or a Tab out. +- **Copy's confirmation** is a `popover="manual"` anchored to Copy, shown and hidden by a timer store (`confirmation.ts`) read through `useSyncExternalStore`. Screen readers hear it through the app's `Announcer`. +- **The format radios** are ``, so arrow keys, wrapping and Tab already behave as they should. + +The animations, timings and positions match Base UI's frame for frame, and the Help and card tests pass against both. + +## Considered options + +- **Keep Base UI.** It costs nothing to maintain, but a quarter of the script ships for three parts, and it stays in the bundle however few parts are used, because its popover pulls in hover, safe-polygon and focus-trap code that Huebo never runs. +- **Lazy-load Help.** That would shrink the first load, not the total, and the toast and radios would still need Base UI. + +## Consequences + +- Copy's confirmation is no longer a focusable dialog in a `Notifications` landmark. It loses Base UI's swipe to dismiss, its pause on hover, and F6. It lasts 1.8 s and repeats nothing a person needs to act on. +- In browsers without CSS anchor positioning, Help and the confirmation fall back to the centre of the screen. In browsers without `overlay` transitions, they leave the top layer as soon as they start to close. +- Base UI used to fix edge cases for us. Now we fix them. diff --git a/package.json b/package.json index e82b74e..f8f7aba 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,6 @@ "vitest-browser-react": "^2.3.0" }, "dependencies": { - "@base-ui/react": "^1.9.0", "@fontsource-variable/bricolage-grotesque": "^5.3.0", "@stylexjs/stylex": "^0.19.1", "@tanstack/react-router": "^1.170.46", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 780d684..905da22 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -169,9 +169,6 @@ importers: .: dependencies: - '@base-ui/react': - specifier: ^1.9.0 - version: 1.9.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@fontsource-variable/bricolage-grotesque': specifier: ^5.3.0 version: 5.3.0 @@ -350,33 +347,6 @@ packages: resolution: {integrity: sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==} engines: {node: '>=6.9.0'} - '@base-ui/react@1.9.0': - resolution: {integrity: sha512-S8CSYosASBKtpL8SWUfS78rFElfLijiCgA7oHOK22jCJ95FULsYyKwBNFOgudt0RA+/7yNc7F81bOvQnRgbBiQ==} - engines: {node: '>=14.0.0'} - peerDependencies: - '@date-fns/tz': ^1.2.0 - '@types/react': ^17 || ^18 || ^19 - date-fns: ^4.0.0 - react: ^17 || ^18 || ^19 - react-dom: ^17 || ^18 || ^19 - peerDependenciesMeta: - '@date-fns/tz': - optional: true - '@types/react': - optional: true - date-fns: - optional: true - - '@base-ui/utils@0.5.0': - resolution: {integrity: sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A==} - peerDependencies: - '@types/react': ^17 || ^18 || ^19 - react: ^17 || ^18 || ^19 - react-dom: ^17 || ^18 || ^19 - peerDependenciesMeta: - '@types/react': - optional: true - '@blazediff/core@1.10.0': resolution: {integrity: sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ==} @@ -468,21 +438,6 @@ packages: cpu: [x64] os: [win32] - '@floating-ui/core@1.8.0': - resolution: {integrity: sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==} - - '@floating-ui/dom@1.8.0': - resolution: {integrity: sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==} - - '@floating-ui/react-dom@2.1.9': - resolution: {integrity: sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==} - peerDependencies: - react: '>=16.8.0' - react-dom: '>=16.8.0' - - '@floating-ui/utils@0.2.12': - resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==} - '@fontsource-variable/bricolage-grotesque@5.3.0': resolution: {integrity: sha512-TLi9Q4hJjS2UvoTMRSS2nHu6c4R56lAw60NR9QYtVRCHn0XtsFpiEhNffZ8Glsoxu6wEEwLKBP8lb94J52PNBA==} @@ -1899,9 +1854,6 @@ packages: resolution: {integrity: sha512-PNaGjoCnw9DBA2Kl8D+8po957z778q/HOPuY2u3Bkw/JO3eC8MDx7jn/PgMtSgpcBbs+6UOjDbwReGpXmRvs0g==} engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} - reselect@5.3.0: - resolution: {integrity: sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg==} - rolldown@1.2.16: resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -2323,7 +2275,8 @@ snapshots: '@babel/core': 7.29.13(supports-color@7.2.0) '@babel/helper-plugin-utils': 7.29.7 - '@babel/runtime@7.29.13': {} + '@babel/runtime@7.29.13': + optional: true '@babel/template@7.29.7': dependencies: @@ -2348,29 +2301,6 @@ snapshots: '@babel/helper-string-parser': 7.29.13 '@babel/helper-validator-identifier': 7.29.7 - '@base-ui/react@1.9.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': - dependencies: - '@babel/runtime': 7.29.13 - '@base-ui/utils': 0.5.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) - '@floating-ui/react-dom': 2.1.9(react-dom@19.3.1(react@19.3.1))(react@19.3.1) - '@floating-ui/utils': 0.2.12 - react: 19.3.1 - react-dom: 19.3.1(react@19.3.1) - use-sync-external-store: 1.7.0(react@19.3.1) - optionalDependencies: - '@types/react': 19.3.0 - - '@base-ui/utils@0.5.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': - dependencies: - '@babel/runtime': 7.29.13 - '@floating-ui/utils': 0.2.12 - react: 19.3.1 - react-dom: 19.3.1(react@19.3.1) - reselect: 5.3.0 - use-sync-external-store: 1.7.0(react@19.3.1) - optionalDependencies: - '@types/react': 19.3.0 - '@blazediff/core@1.10.0': {} '@cacheable/memory@2.2.0': @@ -2444,23 +2374,6 @@ snapshots: '@fallow-cli/win32-x64-msvc@3.39.0': optional: true - '@floating-ui/core@1.8.0': - dependencies: - '@floating-ui/utils': 0.2.12 - - '@floating-ui/dom@1.8.0': - dependencies: - '@floating-ui/core': 1.8.0 - '@floating-ui/utils': 0.2.12 - - '@floating-ui/react-dom@2.1.9(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': - dependencies: - '@floating-ui/dom': 1.8.0 - react: 19.3.1 - react-dom: 19.3.1(react@19.3.1) - - '@floating-ui/utils@0.2.12': {} - '@fontsource-variable/bricolage-grotesque@5.3.0': {} '@humanfs/core@0.19.2': @@ -3593,8 +3506,6 @@ snapshots: json-parse-even-better-errors: 6.0.0 npm-normalize-package-bin: 6.0.0 - reselect@5.3.0: {} - rolldown@1.2.16: dependencies: '@oxc-project/types': 0.156.0 diff --git a/src/picker/Header.tsx b/src/picker/Header.tsx index ec5fcb4..4ae8b9a 100644 --- a/src/picker/Header.tsx +++ b/src/picker/Header.tsx @@ -1,9 +1,7 @@ -import { Popover } from '@base-ui/react/popover' import * as stylex from '@stylexjs/stylex' -import { useRef } from 'react' +import { useId, type FocusEvent, type ToggleEvent } from 'react' import { shared } from '../shared/styles' import { colors, motion, radii } from '../shared/tokens.stylex' -import { transitionClass } from '../shared/transition' import type { Color } from './color' import { Wordmark } from './Wordmark' @@ -17,57 +15,92 @@ export function Header({ color }: { readonly color: Color }) { } function Help() { - const themedContainer = useRef(null) + const popup = useId() + const heading = useId() + const description = useId() return ( - - + + +

+ Picking a colour +

+
+

+ Turn the dial to choose a hue, then pick one of its 64 steps. Copy + it as HSB, RGB or Hex. +

+

+ On the dial, the arrow keys step 5° and Shift steps 45°. In the + grid, the arrow keys move, Enter picks and Escape clears. +

+

+ Based on a design by{' '} + -

- Turn the dial to choose a hue, then pick one of its 64 steps. - Copy it as HSB, RGB or Hex. -

-

- On the dial, the arrow keys step 5° and Shift steps 45°. In the - grid, the arrow keys move, Enter picks and Escape clears. -

-

- Based on a design by{' '} - - Louie Mantia - - . -

- - - - - + Louie Mantia + + . +

+
+
+ ) } +// The browser hands focus back to Help on Escape, but not after a click +// outside, which leaves it on the page, so that case puts it back on Help. +function moveFocus(event: ToggleEvent) { + const help = event.currentTarget + + if (event.newState === 'open') { + help.querySelector('a')?.focus({ preventScroll: true }) + } else if (document.activeElement === document.body) { + document + .querySelector(`[popovertarget="${help.id}"]`) + ?.focus({ preventScroll: true }) + } +} + +function closeOnFocusOut(event: FocusEvent) { + const next = event.relatedTarget + const help = event.currentTarget.closest('dialog') + + if ( + help !== null && + next instanceof Node && + !help.contains(next) && + !(next instanceof HTMLButtonElement && next.popoverTargetElement === help) + ) { + help.hidePopover() + } +} + +const POPUP_GAP_PX = 8 +const POPUP_EDGE_PX = 5 + const styles = stylex.create({ content: { display: 'grid', fontSize: 15, gap: 8, lineHeight: 1.45 }, credit: { @@ -80,19 +113,32 @@ const styles = stylex.create({ paddingTop: 10, }, heading: { fontSize: 17, fontWeight: 800, margin: '0 0 6px' }, - hidden: { opacity: 0, transform: 'scale(0.96)' }, + // A popover sits in the top layer but stays in the themed tree, so it keeps + // the hue's variables without a portal. popup: { backgroundColor: '#fff', + borderStyle: 'none', borderRadius: 16, boxShadow: '0 12px 32px rgb(0 0 0 / 0.18)', color: colors.ink, + inset: 'auto', + margin: `${POPUP_GAP_PX}px ${POPUP_EDGE_PX}px`, maxWidth: 'min(320px, calc(100vw - 24px))', + opacity: { default: 0, ':popover-open': 1 }, outline: 'none', padding: '14px 16px 16px', + positionAnchor: '--help', + positionArea: 'bottom', + positionTryFallbacks: 'flip-block', textAlign: 'start', - transformOrigin: 'var(--transform-origin)', + transform: { default: 'scale(0.96)', ':popover-open': 'none' }, + transformOrigin: 'top', + transitionBehavior: 'allow-discrete', transitionDuration: motion.quick, - transitionProperty: 'opacity, transform', + transitionProperty: 'opacity, transform, display, overlay', + }, + popupStarting: { + '@starting-style': { opacity: 0, transform: 'scale(0.96)' }, }, link: { borderRadius: 4, @@ -102,10 +148,10 @@ const styles = stylex.create({ textDecorationThickness: 2, textUnderlineOffset: 3, }, - positioner: { zIndex: 10 }, text: { margin: 0 }, trigger: { alignItems: 'center', + anchorName: '--help', backgroundColor: { default: colors.panel, ':hover': '#fff' }, borderColor: colors.inkMuted, borderRadius: radii.pill, diff --git a/src/picker/__tests__/Header.test.tsx b/src/picker/__tests__/Header.test.tsx new file mode 100644 index 0000000..acaa28c --- /dev/null +++ b/src/picker/__tests__/Header.test.tsx @@ -0,0 +1,62 @@ +import { describe, expect, test } from 'vitest' +import { page, userEvent } from 'vitest/browser' +import { openAt } from '../../__tests__/app' + +const help = () => page.getByRole('button', { name: 'Help' }) +const dialog = () => page.getByRole('dialog', { name: 'Picking a colour' }) + +describe('help', () => { + test('given help is shut, when Help is pressed, then the help opens with focus inside it', async () => { + await openAt('/200') + + await help().click() + + await expect.element(dialog()).toBeVisible() + await expect.element(help()).toHaveAttribute('aria-haspopup', 'dialog') + expect(document.activeElement).toBe( + page.getByRole('link', { name: /^Louie Mantia/ }).element(), + ) + }) + + test('given help is open, when Escape is pressed, then it shuts and focus is back on Help', async () => { + await openAt('/200') + await help().click() + await expect.element(dialog()).toBeVisible() + + await userEvent.keyboard('{Escape}') + + await expect.element(dialog()).not.toBeInTheDocument() + expect(document.activeElement).toBe(help().element()) + }) + + test('given help is open, when the page outside it is clicked, then it shuts and focus is back on Help', async () => { + await openAt('/200') + await help().click() + await expect.element(dialog()).toBeVisible() + + await page.getByRole('heading', { name: 'Huebo' }).click() + + await expect.element(dialog()).not.toBeInTheDocument() + expect(document.activeElement).toBe(help().element()) + }) + + test('given help is open, when focus tabs out of it, then it shuts', async () => { + await openAt('/200') + await help().click() + await expect.element(dialog()).toBeVisible() + + await userEvent.tab() + + await expect.element(dialog()).not.toBeInTheDocument() + }) + + test('given help is open, when Help is pressed again, then it shuts', async () => { + await openAt('/200') + await help().click() + await expect.element(dialog()).toBeVisible() + + await help().click() + + await expect.element(dialog()).not.toBeInTheDocument() + }) +}) diff --git a/src/picker/color-card/ColorCardRoot.tsx b/src/picker/color-card/ColorCardRoot.tsx index 30ad691..8bcfd77 100644 --- a/src/picker/color-card/ColorCardRoot.tsx +++ b/src/picker/color-card/ColorCardRoot.tsx @@ -1,14 +1,26 @@ import * as stylex from '@stylexjs/stylex' -import { Toast } from '@base-ui/react/toast' -import { createContext, use, useState, type ReactNode } from 'react' +import { + createContext, + use, + useEffect, + useRef, + useState, + useSyncExternalStore, + type ReactNode, +} from 'react' +import { useAnnounce } from '../../shared/announcer' import { colors, easing, motion, radii } from '../../shared/tokens.stylex' -import { transitionClass } from '../../shared/transition' import { useFormatTool } from '../agent/tools' import type { Color } from '../color' import { valuesOf, type Format, type Values } from '../formats' +import { createConfirmation, type Confirmation } from './confirmation' import { readFormat, saveFormat } from './stored-format' +const CONFIRMATION_SHOWN_MS = 1800 + export type CardState = { + readonly confirm: (text: string, copied: boolean) => void + readonly confirmation: Confirmation | null readonly format: Format readonly setFormat: (format: Format) => void readonly values: Values | null @@ -24,6 +36,21 @@ export type RootProps = { export function Root({ children, color }: RootProps) { const [format, setFormat] = useState(readFormat) const values = valuesOf(color) + const announce = useAnnounce() + + const [confirmations] = useState(() => + createConfirmation(CONFIRMATION_SHOWN_MS), + ) + + const confirmation = useSyncExternalStore( + confirmations.subscribe, + confirmations.get, + ) + + const confirm = (text: string, copied: boolean) => { + confirmations.show(text, copied) + announce(text) + } const choose = (next: Format) => { setFormat(next) @@ -33,13 +60,13 @@ export function Root({ children, color }: RootProps) { useFormatTool(choose, values?.text ?? null) return ( - - -
- {children} - -
-
+ +
+ {children} + +
) } @@ -54,55 +81,69 @@ export function useCard(): CardState { return card } -function Toasts() { - const { toasts } = Toast.useToastManager() +/** + * Screen readers hear the confirmation from the announcer. A live region that + * has only just appeared isn't read, so this copy is hidden to avoid saying it + * twice. + */ +function ConfirmationPopover({ + confirmation, +}: { + readonly confirmation: Confirmation | null +}) { + const popover = useRef(null) + const shown = confirmation?.shown ?? false + + useEffect(() => { + popover.current?.togglePopover(shown) + }, [shown]) return ( - - {toasts.map(toast => ( - - - - - - ))} - + ) } +const CONFIRMATION_GAP_PX = 10 +const CONFIRMATION_EDGE_PX = 5 + const styles = stylex.create({ card: { width: '100%' }, - positioner: { zIndex: 9 }, toast: { backgroundColor: colors.ink, + borderStyle: 'none', borderRadius: radii.pill, boxShadow: '0 8px 24px rgb(0 0 0 / 0.2)', color: '#fff', fontSize: 15, - fontWeight: 600, + fontWeight: 700, + inset: 'auto', + margin: `0 ${CONFIRMATION_EDGE_PX}px ${CONFIRMATION_GAP_PX}px`, + opacity: { default: 0, ':popover-open': 1 }, padding: '8px 16px', - transformOrigin: 'var(--transform-origin)', + positionAnchor: '--copy', + positionArea: 'top', + transform: { + default: 'translateY(-6px) scale(0.96)', + ':popover-open': 'none', + }, + transformOrigin: `50% calc(100% + ${CONFIRMATION_GAP_PX}px)`, + transitionBehavior: 'allow-discrete', transitionDuration: motion.pop, - transitionProperty: 'opacity, transform', - transitionTimingFunction: easing.pop, + transitionProperty: 'opacity, transform, display, overlay', + transitionTimingFunction: { + default: 'ease-in', + ':popover-open': easing.pop, + }, whiteSpace: 'nowrap', }, - toastEnding: { - opacity: 0, - transform: 'translateY(-6px) scale(0.96)', - transitionTimingFunction: 'ease-in', + toastStarting: { + '@starting-style': { opacity: 0, transform: 'translateY(8px) scale(0.6)' }, }, - toastStarting: { opacity: 0, transform: 'translateY(8px) scale(0.6)' }, - toastTitle: { fontSize: 'inherit', margin: 0 }, }) diff --git a/src/picker/color-card/Copy.tsx b/src/picker/color-card/Copy.tsx index 2f564e8..0f0c45c 100644 --- a/src/picker/color-card/Copy.tsx +++ b/src/picker/color-card/Copy.tsx @@ -1,5 +1,4 @@ import * as stylex from '@stylexjs/stylex' -import { Toast } from '@base-ui/react/toast' import { shared } from '../../shared/styles' import { colors, motion, radii } from '../../shared/tokens.stylex' import { useCard } from './ColorCardRoot' @@ -10,33 +9,20 @@ const draw = stylex.keyframes({ }) export function Copy() { - const { format, values } = useCard() - const toasts = Toast.useToastManager() + const { confirm, confirmation, format, values } = useCard() const value = values?.text[format] + const copied = confirmation?.shown === true && confirmation.copied - const copied = toasts.toasts.some( - toast => toast.type === 'copied' && toast.transitionStatus !== 'ending', - ) - - const copy = async (text: string, button: HTMLButtonElement) => { + const copy = async (text: string) => { const ok = await writeToClipboard(text) - // One confirmation at a time: copying again while it's up updates it and - // restarts its timer rather than stacking another. - toasts.add({ - id: 'copy', - positionerProps: { anchor: button, side: 'top', sideOffset: 10 }, - title: ok ? `Copied ${format} ${text}` : `Couldn't copy ${format}`, - type: ok ? 'copied' : 'failed', - }) + confirm(ok ? `Copied ${format} ${text}` : `Couldn't copy ${format}`, ok) } return (