Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

test(Markdown): lock heading-link browser contract (#6922)

Cindy Zhang31b67dab803e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b4454d609e..28a3fde5cb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1215,6 +1215,40 @@ jobs:
retention-days: 30
if-no-files-found: ignore
+ # The heading-links module contract is broader than axe: exact fragments,
+ # native sibling anchors, hover/focus/touch discovery, forced colors,
+ # reduced motion, dark mode, and RTL geometry all need a real engine.
+ # Keep it scoped to Markdown plugin changes and bind its receipt to the verified head.
+ - name: Run heading-links module browser evidence
+ id: markdown-heading-links
+ if: github.event_name == 'pull_request'
+ env:
+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: |
+ COMPONENTS=$(node .github/scripts/a11y-pr-scope.mjs analysis.json)
+ case ",${COMPONENTS}," in
+ *,core/Markdown,*)
+ echo 'should_run=true' >> "$GITHUB_OUTPUT"
+ pnpm exec playwright test \
+ packages/core/src/Markdown/plugins/headingLinks.a11y.chromium.spec.ts \
+ --project chromium \
+ --output markdown-heading-links-output
+ ;;
+ *)
+ echo 'should_run=false' >> "$GITHUB_OUTPUT"
+ echo "Markdown not in PR scope; skipping heading-link evidence."
+ ;;
+ esac
+
+ - name: Upload heading-links module browser evidence
+ if: always() && github.event_name == 'pull_request' && steps.markdown-heading-links.outputs.should_run == 'true'
+ uses: actions/upload-artifact@v7
+ with:
+ name: markdown-heading-links-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: test-results/markdown-heading-links/
+ retention-days: 30
+ if-no-files-found: error
+
# ChatMessageBubble is nested under the shared Chat source directory, so
# the generic stable-visual owner cannot select its dedicated fixture.
# Run the component's bounded evidence matrix only when the PR scope names
diff --git a/apps/storybook/stories/MarkdownHeadingLinks.stories.tsx b/apps/storybook/stories/MarkdownHeadingLinks.stories.tsx
new file mode 100644
index 0000000000..4019a9ba5c
--- /dev/null
+++ b/apps/storybook/stories/MarkdownHeadingLinks.stories.tsx
@@ -0,0 +1,163 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {Meta, StoryObj} from '@storybook/react';
+import * as stylex from '@stylexjs/stylex';
+import {Markdown} from '@astryxdesign/core/Markdown';
+import {createMarkdownHeadingLinks} from '@astryxdesign/core/Markdown/plugins';
+import {expect, userEvent, within} from 'storybook/test';
+
+const styles = stylex.create({
+ geometryReference: {
+ position: 'absolute',
+ visibility: 'hidden',
+ pointerEvents: 'none',
+ },
+});
+
+const meta: Meta<typeof Markdown> = {
+ title: 'Core/Markdown/Plugins/Heading links',
+ component: Markdown,
+};
+
+export default meta;
+type Story = StoryObj<typeof Markdown>;
+
+const SOURCE = [
+ '# Linkable headings',
+ '',
+ 'Hover a heading area or move keyboard focus to reveal the `#` copy button. On touch it stays visible. Activating it copies the full permalink without changing the current hash, scroll position, or page.',
+ '',
+ '> ## Nested heading',
+ '',
+ '## Read the [guide](https://example.com/guide)',
+ '',
+ '### Third-level heading',
+ '',
+ '#### Fourth-level heading',
+ '',
+ '##### Fifth-level heading',
+ '',
+ '###### Sixth-level heading',
+ '',
+ '## A narrow heading whose trailing control stays with its final text line',
+ '',
+ '## Hello Привет 你好 😄 123',
+ '',
+ '## Repeat',
+ '',
+ '## Repeat',
+ '',
+ '## Repeat-1',
+].join('\n');
+
+const ltrPlugins = [
+ createMarkdownHeadingLinks({headingIdPrefix: 'heading-links-ltr'}),
+];
+const rtlPlugins = [
+ createMarkdownHeadingLinks({headingIdPrefix: 'heading-links-rtl'}),
+];
+const compactPlugins = [
+ createMarkdownHeadingLinks({headingIdPrefix: 'heading-links-compact'}),
+];
+
+export const Overview: Story = {
+ name: 'Heading links',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'The opt-in first-party module gives every built-in h1–h6 an inline trailing # copy button. It is hidden at fine-pointer rest, reveals when the heading row is hovered or receives keyboard focus, and follows useContainerReveal touch behavior. Activating it copies the canonical permalink without navigation, hash mutation, or scrolling; the fixed-space # becomes a check for ~1.5 seconds. The coarse target keeps the 24px AA floor while its painted control remains centered on the heading line box. Nested headings share the depth-first allocator, authored heading links remain valid, Unicode ids remain readable, and a caller-owned namespace keeps multiple documents distinct.',
+ },
+ },
+ },
+ render: () => (
+ <>
+ <Markdown id="heading-links-ltr" plugins={ltrPlugins}>
+ {SOURCE}
+ </Markdown>
+ <section dir="rtl" aria-label="Right-to-left heading links">
+ <Markdown id="heading-links-rtl" plugins={rtlPlugins}>
+ {'# عنوان قابل للربط\n\n## تفاصيل'}
+ </Markdown>
+ </section>
+ <section aria-label="Compact heading links">
+ <Markdown
+ id="heading-links-compact"
+ density="compact"
+ plugins={compactPlugins}>
+ {
+ '# Compact first-level heading\n\n###### Compact sixth-level heading\n\n###### Compact sixth-level heading'
+ }
+ </Markdown>
+ </section>
+ <div aria-hidden="true" {...stylex.props(styles.geometryReference)}>
+ <Markdown id="heading-links-reference">{SOURCE}</Markdown>
+ </div>
+ </>
+ ),
+ play: async ({canvasElement}) => {
+ const canvas = within(canvasElement);
+ const ltr = canvasElement.querySelector<HTMLElement>('#heading-links-ltr');
+ if (ltr == null) {
+ throw new Error('missing namespaced Markdown root');
+ }
+
+ const firstHeading = within(ltr).getByRole('heading', {
+ name: 'Linkable headings',
+ });
+ await expect(firstHeading).toHaveAttribute(
+ 'id',
+ 'heading-links-ltr--linkable-headings',
+ );
+ const firstPermalink = within(ltr).getByRole('button', {
+ name: 'Copy link to Linkable headings',
+ });
+ await expect(firstPermalink).toHaveAttribute('type', 'button');
+ await expect(firstPermalink).not.toHaveAttribute('href');
+ await expect(firstHeading.parentElement).toContainElement(firstPermalink);
+ await expect(firstHeading).not.toContainElement(firstPermalink);
+
+ for (const [level, name] of [
+ [1, 'Linkable headings'],
+ [2, 'Read the guide'],
+ [3, 'Third-level heading'],
+ [4, 'Fourth-level heading'],
+ [5, 'Fifth-level heading'],
+ [6, 'Sixth-level heading'],
+ ] as const) {
+ const heading = within(ltr).getByRole('heading', {level, name});
+ const button = within(heading.parentElement as HTMLElement).getByRole(
+ 'button',
+ );
+ await expect(button).toHaveAccessibleName(`Copy link to ${name}`);
+ }
+
+ await expect(
+ within(ltr).getByRole('heading', {name: 'Nested heading'}),
+ ).toHaveAttribute('id', 'heading-links-ltr--nested-heading');
+ await expect(
+ within(ltr).getByRole('heading', {name: 'Read the guide'}),
+ ).toContainElement(within(ltr).getByRole('link', {name: 'guide'}));
+ await expect(ltr.querySelector('a a')).toBeNull();
+ await expect(
+ within(ltr).getByRole('heading', {name: /Hello Привет 你好/}),
+ ).toHaveAttribute('id', 'heading-links-ltr--hello-привет-你好-123');
+ await expect(
+ Array.from(ltr.querySelectorAll('h1,h2'))
+ .slice(-3)
+ .map(node => node.id),
+ ).toEqual([
+ 'heading-links-ltr--repeat',
+ 'heading-links-ltr--repeat-1',
+ 'heading-links-ltr--repeat-1-1',
+ ]);
+
+ await userEvent.tab();
+ await expect(firstPermalink).toHaveFocus();
+ await expect(
+ canvas.getByRole('button', {name: 'Copy link to عنوان قابل للربط'}),
+ ).toHaveAttribute('type', 'button');
+ firstPermalink.blur();
+ ltr.dataset.headingLinksPlayComplete = 'true';
+ },
+};
diff --git a/packages/core/src/Markdown/plugins/headingLinks.a11y.chromium.spec.ts b/packages/core/src/Markdown/plugins/headingLinks.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..26ee1f3cc6
--- /dev/null
+++ b/packages/core/src/Markdown/plugins/headingLinks.a11y.chromium.spec.ts
@@ -0,0 +1,834 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file headingLinks.a11y.chromium.spec.ts
+ * @input Heading-link copy-button Storybook story in real Chromium
+ * @output Reveal, geometry, copy, no-navigation, modality, theme, and screenshot evidence
+ * @position Browser proof for module:Markdown/headingLinks
+ *
+ * Build Storybook first:
+ *
+ * pnpm storybook:build
+ * pnpm exec playwright test headingLinks.a11y.chromium.spec.ts
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {expect, test, type Locator, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+const STORY = 'core-markdown-plugins-heading-links--overview';
+const OUTPUT = path.resolve('test-results/markdown-heading-links');
+const GEOMETRY_TOLERANCE_PX = 1;
+let storybook: StaticServer;
+const evidence: Record<string, unknown> = {};
+
+interface RectGeometry {
+ readonly x: number;
+ readonly y: number;
+ readonly width: number;
+ readonly height: number;
+ readonly right: number;
+ readonly bottom: number;
+}
+
+interface HeadingGeometry {
+ readonly row: RectGeometry;
+ readonly heading: RectGeometry;
+ readonly slot: RectGeometry;
+ readonly button: RectGeometry;
+ readonly glyph: RectGeometry;
+ readonly headingBaseline: number;
+ readonly slotBaseline: number;
+ readonly lineHeight: number;
+ readonly alignItems: string;
+ readonly flexWrap: string;
+ readonly outlineExtent: number;
+}
+
+test.beforeAll(async () => {
+ fs.rmSync(OUTPUT, {recursive: true, force: true});
+ fs.mkdirSync(OUTPUT, {recursive: true});
+ evidence.headSha = process.env.ASTRYX_HEAD_SHA ?? null;
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ fs.writeFileSync(
+ path.join(OUTPUT, 'manifest.json'),
+ `${JSON.stringify({version: 1, ...evidence}, null, 2)}\n`,
+ );
+ await storybook?.close();
+});
+
+async function openStory(
+ page: Page,
+ globals = 'astryxTheme:neutral;colorMode:light;direction:ltr',
+): Promise<void> {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story&globals=${globals}`,
+ {waitUntil: 'load'},
+ );
+ await page.locator('#heading-links-ltr h1').waitFor({state: 'visible'});
+ await page
+ .locator('#heading-links-ltr[data-heading-links-play-complete="true"]')
+ .waitFor();
+}
+
+function copyButtonForHeading(heading: Locator): Locator {
+ return heading.locator('..').locator('button').first();
+}
+
+async function copyButtonOpacity(page: Page): Promise<number> {
+ const heading = page
+ .locator('#heading-links-ltr')
+ .getByRole('heading', {name: 'Linkable headings'});
+ return copyButtonForHeading(heading).evaluate(element =>
+ Number(getComputedStyle(element).opacity),
+ );
+}
+
+async function blurActiveElement(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const active = document.activeElement;
+ if (active instanceof HTMLElement) {
+ active.blur();
+ }
+ });
+}
+
+async function measureHeading(heading: Locator): Promise<HeadingGeometry> {
+ return heading.evaluate(element => {
+ const headingElement = element as HTMLElement;
+ const rowElement = headingElement.parentElement;
+ const buttonElement = rowElement?.querySelector('button');
+ const slotElement = buttonElement?.parentElement;
+ const glyphElement = buttonElement?.querySelector('[aria-hidden="true"]');
+ if (
+ rowElement == null ||
+ buttonElement == null ||
+ slotElement == null ||
+ glyphElement == null
+ ) {
+ throw new Error(
+ 'Heading-link geometry requires its complete rendered row',
+ );
+ }
+
+ const makeBaselineProbe = (): HTMLSpanElement => {
+ const probe = document.createElement('span');
+ probe.setAttribute('aria-hidden', 'true');
+ Object.assign(probe.style, {
+ display: 'inline-block',
+ width: '0px',
+ height: '0px',
+ margin: '0px',
+ padding: '0px',
+ verticalAlign: 'baseline',
+ });
+ return probe;
+ };
+ const headingProbe = makeBaselineProbe();
+ const slotProbe = makeBaselineProbe();
+ headingElement.append(headingProbe);
+ slotElement.append(slotProbe);
+
+ const round = (value: number): number => Math.round(value * 1000) / 1000;
+ const readRect = (target: Element): RectGeometry => {
+ const rect = target.getBoundingClientRect();
+ return {
+ x: round(rect.x),
+ y: round(rect.y),
+ width: round(rect.width),
+ height: round(rect.height),
+ right: round(rect.right),
+ bottom: round(rect.bottom),
+ };
+ };
+ const buttonStyle = getComputedStyle(buttonElement);
+ const outlineWidth = Number.parseFloat(buttonStyle.outlineWidth) || 0;
+ const outlineOffset = Number.parseFloat(buttonStyle.outlineOffset) || 0;
+ const geometry = {
+ row: readRect(rowElement),
+ heading: readRect(headingElement),
+ slot: readRect(slotElement),
+ button: readRect(buttonElement),
+ glyph: readRect(glyphElement),
+ headingBaseline: round(headingProbe.getBoundingClientRect().top),
+ slotBaseline: round(slotProbe.getBoundingClientRect().top),
+ lineHeight: round(
+ Number.parseFloat(getComputedStyle(headingElement).lineHeight),
+ ),
+ alignItems: getComputedStyle(rowElement).alignItems,
+ flexWrap: getComputedStyle(rowElement).flexWrap,
+ outlineExtent: round(outlineWidth + Math.max(0, outlineOffset)),
+ };
+
+ headingProbe.remove();
+ slotProbe.remove();
+ return geometry;
+ });
+}
+
+async function measureReferenceHeading(heading: Locator): Promise<{
+ readonly height: number;
+ readonly lineHeight: number;
+ readonly fontSize: string;
+}> {
+ return heading.evaluate(element => {
+ const style = getComputedStyle(element);
+ return {
+ height: Math.round(element.getBoundingClientRect().height * 1000) / 1000,
+ lineHeight: Math.round(Number.parseFloat(style.lineHeight) * 1000) / 1000,
+ fontSize: style.fontSize,
+ };
+ });
+}
+
+async function readFocusRing(button: Locator): Promise<{
+ readonly focusVisible: boolean;
+ readonly outlineWidth: string;
+ readonly outlineStyle: string;
+ readonly outlineOffset: string;
+ readonly boxShadow: string;
+ readonly slotOutlineWidth: string;
+ readonly slotOutlineStyle: string;
+}> {
+ return button.evaluate(element => {
+ const style = getComputedStyle(element);
+ const slotStyle = getComputedStyle(element.parentElement as HTMLElement);
+ return {
+ focusVisible: element.matches(':focus-visible'),
+ outlineWidth: style.outlineWidth,
+ outlineStyle: style.outlineStyle,
+ outlineOffset: style.outlineOffset,
+ boxShadow: style.boxShadow,
+ slotOutlineWidth: slotStyle.outlineWidth,
+ slotOutlineStyle: slotStyle.outlineStyle,
+ };
+ });
+}
+
+function expectAlignedGeometry(geometry: HeadingGeometry): void {
+ expect(
+ Math.abs(geometry.row.height - geometry.heading.height),
+ ).toBeLessThanOrEqual(GEOMETRY_TOLERANCE_PX);
+ expect(
+ Math.abs(geometry.headingBaseline - geometry.slotBaseline),
+ ).toBeLessThanOrEqual(GEOMETRY_TOLERANCE_PX);
+ expect(
+ Math.abs(
+ geometry.glyph.y +
+ geometry.glyph.height / 2 -
+ (geometry.slot.y + geometry.slot.height / 2),
+ ),
+ ).toBeLessThanOrEqual(GEOMETRY_TOLERANCE_PX);
+ expect(geometry.alignItems).toMatch(/baseline/u);
+ expect(geometry.flexWrap).toBe('nowrap');
+}
+
+function expectSameRect(before: RectGeometry, after: RectGeometry): void {
+ for (const key of ['x', 'y', 'width', 'height'] as const) {
+ expect(Math.abs(before[key] - after[key])).toBeLessThanOrEqual(
+ GEOMETRY_TOLERANCE_PX,
+ );
+ }
+}
+
+function rectsIntersect(a: RectGeometry, b: RectGeometry): boolean {
+ return !(
+ a.right <= b.x ||
+ b.right <= a.x ||
+ a.bottom <= b.y ||
+ b.bottom <= a.y
+ );
+}
+
+test('heading copy buttons are honest, aligned, discoverable, and stable in every required state', async ({
+ browser,
+ page,
+}) => {
+ test.setTimeout(3 * 60 * 1000);
+ await page.context().grantPermissions(['clipboard-read', 'clipboard-write'], {
+ origin: storybook.origin,
+ });
+ await openStory(page);
+
+ const root = page.locator('#heading-links-ltr');
+ const heading = root.getByRole('heading', {name: 'Linkable headings'});
+ const row = heading.locator('..');
+ // This DOM relationship remains stable while the localized accessible name
+ // intentionally changes from the copy action to its success confirmation.
+ const copyButton = copyButtonForHeading(heading);
+
+ await expect(heading).toHaveAttribute(
+ 'id',
+ 'heading-links-ltr--linkable-headings',
+ );
+ await expect(copyButton).toHaveAccessibleName(
+ 'Copy link to Linkable headings',
+ );
+ await expect(copyButton).toHaveAttribute('type', 'button');
+ await expect(copyButton).not.toHaveAttribute('href', /.+/u);
+ expect(await copyButton.evaluate(element => element.tagName)).toBe('BUTTON');
+ expect(await heading.locator('button').count()).toBe(0);
+ expect(await root.locator('a[href^="#heading-links-ltr"]').count()).toBe(0);
+
+ await blurActiveElement(page);
+ await page.mouse.move(0, 0);
+ await expect(copyButton).not.toBeFocused();
+ expect(
+ await row.evaluate(element => ({
+ focusWithin: element.matches(':focus-within'),
+ hover: element.matches(':hover'),
+ })),
+ ).toEqual({focusWithin: false, hover: false});
+ await expect.poll(async () => copyButtonOpacity(page)).toBe(0);
+ evidence.restOpacity = await copyButtonOpacity(page);
+ await root.screenshot({path: path.join(OUTPUT, 'light-rest.png')});
+
+ await heading.hover();
+ await expect.poll(async () => copyButtonOpacity(page)).toBe(1);
+ evidence.headingHoverOpacity = await copyButtonOpacity(page);
+ await root.screenshot({path: path.join(OUTPUT, 'light-heading-hover.png')});
+
+ const headingCases = [
+ [1, 'Linkable headings'],
+ [2, 'Read the guide'],
+ [3, 'Third-level heading'],
+ [4, 'Fourth-level heading'],
+ [5, 'Fifth-level heading'],
+ [6, 'Sixth-level heading'],
+ ] as const;
+ const headingGeometry: Record<
+ string,
+ {
+ linked: HeadingGeometry;
+ reference: Awaited<ReturnType<typeof measureReferenceHeading>>;
+ }
+ > = {};
+ const referenceRoot = page.locator('#heading-links-reference');
+ for (const [level, name] of headingCases) {
+ const caseHeading = root.getByRole('heading', {level, name});
+ const referenceHeading = referenceRoot
+ .locator(`h${level}`)
+ .filter({hasText: name})
+ .first();
+ await caseHeading.hover();
+ const geometry = await measureHeading(caseHeading);
+ const referenceGeometry = await measureReferenceHeading(referenceHeading);
+ expectAlignedGeometry(geometry);
+ expect(
+ Math.abs(geometry.row.height - referenceGeometry.height),
+ ).toBeLessThanOrEqual(GEOMETRY_TOLERANCE_PX);
+ expect(
+ Math.abs(geometry.slot.height - referenceGeometry.lineHeight),
+ ).toBeLessThanOrEqual(GEOMETRY_TOLERANCE_PX);
+ headingGeometry[`h${level}`] = {
+ linked: geometry,
+ reference: referenceGeometry,
+ };
+ }
+ evidence.headingGeometry = headingGeometry;
+
+ const compactRoot = page.locator('#heading-links-compact');
+ const compactH1Geometry = await measureHeading(
+ compactRoot.getByRole('heading', {name: 'Compact first-level heading'}),
+ );
+ const compactH6Geometry = await measureHeading(
+ compactRoot
+ .getByRole('heading', {name: 'Compact sixth-level heading'})
+ .first(),
+ );
+ expectAlignedGeometry(compactH1Geometry);
+ expectAlignedGeometry(compactH6Geometry);
+ expect(
+ rectsIntersect(compactH1Geometry.button, compactH6Geometry.button),
+ ).toBe(false);
+ evidence.compactGeometry = {
+ h1: compactH1Geometry,
+ h6: compactH6Geometry,
+ };
+
+ const authoredHeading = root.getByRole('heading', {name: 'Read the guide'});
+ const authoredLink = authoredHeading.getByRole('link', {name: 'guide'});
+ const authoredCopyButton = copyButtonForHeading(authoredHeading);
+ await expect(authoredCopyButton).toHaveAccessibleName(
+ 'Copy link to Read the guide',
+ );
+ await page.mouse.move(1200, 800);
+ await authoredLink.focus();
+ await expect(authoredLink).toBeFocused();
+ await expect
+ .poll(async () =>
+ authoredCopyButton.evaluate(element =>
+ Number(getComputedStyle(element).opacity),
+ ),
+ )
+ .toBe(1);
+ evidence.focusWithinOpacity = await authoredCopyButton.evaluate(element =>
+ Number(getComputedStyle(element).opacity),
+ );
+
+ await page.mouse.move(1200, 800);
+ await page.keyboard.press('Tab');
+ await expect(authoredCopyButton).toBeFocused();
+ await expect
+ .poll(async () =>
+ authoredCopyButton.evaluate(element =>
+ Number(getComputedStyle(element).opacity),
+ ),
+ )
+ .toBe(1);
+ evidence.keyboardTabOpacity = await authoredCopyButton.evaluate(element =>
+ Number(getComputedStyle(element).opacity),
+ );
+
+ await copyButton.focus();
+ await expect(copyButton).toBeFocused();
+ await expect.poll(async () => copyButtonOpacity(page)).toBe(1);
+ evidence.keyboardFocusOpacity = await copyButtonOpacity(page);
+ const focusedGeometry = await measureHeading(heading);
+ expectAlignedGeometry(focusedGeometry);
+ expect(
+ focusedGeometry.button.x - focusedGeometry.outlineExtent,
+ ).toBeGreaterThanOrEqual(focusedGeometry.heading.right);
+ expect(
+ await copyButton.evaluate(element => {
+ let ancestor = element.parentElement;
+ while (ancestor != null) {
+ const style = getComputedStyle(ancestor);
+ if (
+ ['hidden', 'clip'].includes(style.overflowX) ||
+ ['hidden', 'clip'].includes(style.overflowY)
+ ) {
+ return false;
+ }
+ ancestor = ancestor.parentElement;
+ }
+ return true;
+ }),
+ ).toBe(true);
+ evidence.focusGeometry = focusedGeometry;
+ await root.screenshot({path: path.join(OUTPUT, 'light-focus.png')});
+
+ await blurActiveElement(page);
+ await heading.hover();
+ const restGeometry = await measureHeading(heading);
+ const restGlyphWidth = restGeometry.glyph.width;
+ const canonicalUrl = new URL(
+ '#heading-links-ltr--linkable-headings',
+ page.url(),
+ ).href;
+ const locationBeforeCopy = page.url();
+ const scrollBeforeCopy = await page.evaluate(() => ({
+ x: window.scrollX,
+ y: window.scrollY,
+ }));
+ await page.evaluate(() => {
+ (
+ window as typeof window & {__headingLinksNoReload?: string}
+ ).__headingLinksNoReload = 'alive';
+ });
+ await copyButton.click();
+ await expect(page).toHaveURL(locationBeforeCopy);
+ expect(
+ await page.evaluate(() => ({x: window.scrollX, y: window.scrollY})),
+ ).toEqual(scrollBeforeCopy);
+ await expect(copyButton).toHaveAccessibleName('Link copied');
+ await expect(copyButton.locator('.astryx-icon')).toHaveCount(1);
+ const pointerRing = await readFocusRing(copyButton);
+ expect(pointerRing.focusVisible).toBe(false);
+ expect(pointerRing.outlineWidth).toBe('0px');
+ expect(pointerRing.outlineStyle).toBe('none');
+ const copiedGeometry = await measureHeading(heading);
+ expectAlignedGeometry(copiedGeometry);
+ expectSameRect(restGeometry.row, copiedGeometry.row);
+ expectSameRect(restGeometry.heading, copiedGeometry.heading);
+ expectSameRect(restGeometry.slot, copiedGeometry.slot);
+ expectSameRect(restGeometry.button, copiedGeometry.button);
+ expectSameRect(restGeometry.glyph, copiedGeometry.glyph);
+ evidence.glyphWidths = {
+ rest: restGlyphWidth,
+ copied: copiedGeometry.glyph.width,
+ };
+ evidence.stateGeometry = {rest: restGeometry, copied: copiedGeometry};
+ evidence.pointerRing = pointerRing;
+ evidence.desktopClipboard = await page.evaluate(async () =>
+ navigator.clipboard.readText(),
+ );
+ expect(evidence.desktopClipboard).toBe(canonicalUrl);
+ expect(
+ await page.evaluate(
+ () =>
+ (window as typeof window & {__headingLinksNoReload?: string})
+ .__headingLinksNoReload,
+ ),
+ ).toBe('alive');
+ await root.screenshot({path: path.join(OUTPUT, 'light-pointer-copied.png')});
+ await expect(copyButton).toHaveAccessibleName(
+ 'Copy link to Linkable headings',
+ {timeout: 3000},
+ );
+ await expect(copyButton).toHaveText('#');
+ expectSameRect(restGeometry.row, (await measureHeading(heading)).row);
+
+ await blurActiveElement(page);
+ await page.evaluate(() => {
+ document.body.tabIndex = -1;
+ document.body.focus();
+ });
+ await page.keyboard.press('Tab');
+ await expect(copyButton).toBeFocused();
+ await page.evaluate(() => {
+ document.body.removeAttribute('tabindex');
+ });
+ expect(
+ await copyButton.evaluate(element => element.matches(':focus-visible')),
+ ).toBe(true);
+ await page.keyboard.press('Enter');
+ await expect(copyButton).toHaveAccessibleName('Link copied');
+ const keyboardRing = await readFocusRing(copyButton);
+ expect(keyboardRing.focusVisible).toBe(true);
+ expect(keyboardRing.outlineWidth).toBe('2px');
+ expect(keyboardRing.outlineStyle).toBe('solid');
+ expect(keyboardRing.slotOutlineStyle).toBe('none');
+ expect(keyboardRing.boxShadow).toBe('none');
+ const keyboardCopiedGeometry = await measureHeading(heading);
+ expectSameRect(restGeometry.row, keyboardCopiedGeometry.row);
+ expectSameRect(restGeometry.heading, keyboardCopiedGeometry.heading);
+ expectSameRect(restGeometry.slot, keyboardCopiedGeometry.slot);
+ expectSameRect(restGeometry.button, keyboardCopiedGeometry.button);
+ expectSameRect(restGeometry.glyph, keyboardCopiedGeometry.glyph);
+ evidence.keyboardRing = keyboardRing;
+ await root.screenshot({path: path.join(OUTPUT, 'light-keyboard-copied.png')});
+
+ await page.waitForTimeout(1000);
+ await page.keyboard.press('Space');
+ await page.waitForTimeout(700);
+ await expect(copyButton).toHaveAccessibleName('Link copied');
+ expect(
+ await copyButton.evaluate(element => element.matches(':focus-visible')),
+ ).toBe(true);
+ await expect(copyButton).toHaveAccessibleName(
+ 'Copy link to Linkable headings',
+ {timeout: 2500},
+ );
+ await expect(copyButton).toHaveText('#');
+
+ await page.evaluate(async () => navigator.clipboard.writeText('sentinel'));
+ await copyButton.click({modifiers: ['Control']});
+ expect(await page.evaluate(async () => navigator.clipboard.readText())).toBe(
+ 'sentinel',
+ );
+ await copyButton.dispatchEvent('contextmenu');
+ expect(await page.evaluate(async () => navigator.clipboard.readText())).toBe(
+ 'sentinel',
+ );
+ await expect(page).toHaveURL(locationBeforeCopy);
+
+ const narrowHeading = root.getByRole('heading', {
+ name: 'A narrow heading whose trailing control stays with its final text line',
+ });
+ await root.evaluate(element => {
+ element.style.inlineSize = '240px';
+ });
+ await narrowHeading.hover();
+ const narrowGeometry = await measureHeading(narrowHeading);
+ expectAlignedGeometry(narrowGeometry);
+ expect(narrowGeometry.heading.height).toBeGreaterThan(
+ narrowGeometry.lineHeight * 1.5,
+ );
+ expect(narrowGeometry.slot.x).toBeGreaterThanOrEqual(
+ narrowGeometry.heading.right,
+ );
+ evidence.narrowGeometry = narrowGeometry;
+ await root.screenshot({path: path.join(OUTPUT, 'narrow-wrap.png')});
+ await root.evaluate(element => {
+ element.style.removeProperty('inline-size');
+ });
+
+ for (const target of [root, referenceRoot]) {
+ await target.evaluate(element => {
+ element.style.setProperty(
+ '--text-heading-1-size',
+ 'var(--text-body-size)',
+ );
+ element.style.setProperty(
+ '--text-heading-1-leading',
+ 'var(--text-body-leading)',
+ );
+ });
+ }
+ const bodyScaleGeometry = await measureHeading(heading);
+ const bodyScaleReference = await measureReferenceHeading(
+ referenceRoot.locator('h1').first(),
+ );
+ expectAlignedGeometry(bodyScaleGeometry);
+ expect(
+ Math.abs(bodyScaleGeometry.row.height - bodyScaleReference.height),
+ ).toBeLessThanOrEqual(GEOMETRY_TOLERANCE_PX);
+ expect(
+ Math.abs(bodyScaleGeometry.slot.height - bodyScaleReference.lineHeight),
+ ).toBeLessThanOrEqual(GEOMETRY_TOLERANCE_PX);
+ evidence.bodyScaleGeometry = {
+ linked: bodyScaleGeometry,
+ reference: bodyScaleReference,
+ };
+ await root.screenshot({path: path.join(OUTPUT, 'body-scale-heading.png')});
+ for (const target of [root, referenceRoot]) {
+ await target.evaluate(element => {
+ element.style.removeProperty('--text-heading-1-size');
+ element.style.removeProperty('--text-heading-1-leading');
+ });
+ }
+
+ await page.evaluate(() => {
+ document.body.style.zoom = '2';
+ });
+ const zoomGeometry = await measureHeading(heading);
+ expectAlignedGeometry(zoomGeometry);
+ evidence.zoom200Geometry = zoomGeometry;
+ await root.screenshot({path: path.join(OUTPUT, 'zoom-200.png')});
+ await page.evaluate(() => {
+ document.body.style.removeProperty('zoom');
+ });
+
+ await page.emulateMedia({forcedColors: 'active'});
+ await blurActiveElement(page);
+ await page.mouse.move(1200, 800);
+ await expect.poll(async () => copyButtonOpacity(page)).toBe(0);
+ evidence.forcedColorsRestOpacity = await copyButtonOpacity(page);
+ await copyButton.focus();
+ await expect.poll(async () => copyButtonOpacity(page)).toBe(1);
+ evidence.forcedColorsFocusOpacity = await copyButtonOpacity(page);
+ await root.screenshot({path: path.join(OUTPUT, 'forced-colors-focus.png')});
+
+ await page.emulateMedia({forcedColors: 'none', reducedMotion: 'reduce'});
+ evidence.reducedMotionDuration = await copyButton.evaluate(
+ element => getComputedStyle(element).transitionDuration,
+ );
+ expect(evidence.reducedMotionDuration).toBe('0s');
+
+ await openStory(page, 'astryxTheme:neutral;colorMode:dark;direction:ltr');
+ const darkRoot = page.locator('#heading-links-ltr');
+ const darkHeading = darkRoot.getByRole('heading', {
+ name: 'Linkable headings',
+ });
+ const darkCopyButton = copyButtonForHeading(darkHeading);
+ await darkHeading.hover();
+ await expect.poll(async () => copyButtonOpacity(page)).toBe(1);
+ evidence.darkColor = await darkCopyButton.evaluate(
+ element => getComputedStyle(element).color,
+ );
+ await darkRoot.screenshot({path: path.join(OUTPUT, 'dark-hover.png')});
+
+ const rtlHeading = page.getByRole('heading', {
+ name: 'عنوان قابل للربط',
+ });
+ const rtlCopyButton = copyButtonForHeading(rtlHeading);
+ await expect(rtlCopyButton).toHaveAccessibleName(
+ 'Copy link to عنوان قابل للربط',
+ );
+ await rtlHeading.hover();
+ const [rtlHeadingBox, rtlButtonBox] = await Promise.all([
+ rtlHeading.boundingBox(),
+ rtlCopyButton.boundingBox(),
+ ]);
+ if (rtlHeadingBox == null || rtlButtonBox == null) {
+ throw new Error('RTL heading and copy button must have layout boxes');
+ }
+ expect(rtlButtonBox.x).toBeLessThan(rtlHeadingBox.x);
+ const rtlGeometry = await measureHeading(rtlHeading);
+ expectAlignedGeometry(rtlGeometry);
+ expect(
+ rtlGeometry.button.right + rtlGeometry.outlineExtent,
+ ).toBeLessThanOrEqual(rtlGeometry.heading.x);
+ evidence.rtl = {
+ heading: rtlHeadingBox,
+ button: rtlButtonBox,
+ geometry: rtlGeometry,
+ };
+
+ const singleProcessProof = process.env.ASTRYX_SINGLE_PROCESS_CHROMIUM === '1';
+ const touchContext = singleProcessProof
+ ? page.context()
+ : await browser.newContext({
+ hasTouch: true,
+ isMobile: true,
+ viewport: {width: 390, height: 844},
+ });
+ let touchCdp: Awaited<ReturnType<typeof touchContext.newCDPSession>> | null =
+ null;
+ if (singleProcessProof) {
+ touchCdp = await touchContext.newCDPSession(page);
+ await touchCdp.send('Emulation.setTouchEmulationEnabled', {
+ enabled: true,
+ maxTouchPoints: 5,
+ });
+ await page.setViewportSize({width: 390, height: 844});
+ } else {
+ await touchContext.grantPermissions(['clipboard-read', 'clipboard-write'], {
+ origin: storybook.origin,
+ });
+ }
+ const touchPage = singleProcessProof ? page : await touchContext.newPage();
+ await openStory(touchPage);
+ const touchRoot = touchPage.locator('#heading-links-ltr');
+ const touchHeading = touchRoot.getByRole('heading', {
+ name: 'Linkable headings',
+ });
+ const touchCopyButton = copyButtonForHeading(touchHeading);
+ await expect(touchCopyButton).toHaveAccessibleName(
+ 'Copy link to Linkable headings',
+ );
+ evidence.touchOpacity = await copyButtonOpacity(touchPage);
+ expect(evidence.touchOpacity).toBe(1);
+ await expect(touchCopyButton).toHaveText('#');
+ const touchTarget = await touchCopyButton.boundingBox();
+ if (touchTarget == null) {
+ throw new Error('Touch copy button must have a layout box');
+ }
+ expect(touchTarget.width).toBeGreaterThanOrEqual(24);
+ expect(touchTarget.height).toBeGreaterThanOrEqual(24);
+ evidence.touchTarget = touchTarget;
+ const touchGeometry = await measureHeading(touchHeading);
+ expect(
+ Math.abs(touchGeometry.headingBaseline - touchGeometry.slotBaseline),
+ ).toBeLessThanOrEqual(GEOMETRY_TOLERANCE_PX);
+ expect(touchGeometry.button.x).toBeGreaterThanOrEqual(
+ touchGeometry.heading.right,
+ );
+ expect(
+ Math.abs(touchGeometry.row.height - touchGeometry.heading.height),
+ ).toBeLessThanOrEqual(GEOMETRY_TOLERANCE_PX);
+ expect(
+ Math.abs(touchGeometry.row.height - touchGeometry.lineHeight),
+ ).toBeLessThanOrEqual(GEOMETRY_TOLERANCE_PX);
+ evidence.touchGeometry = touchGeometry;
+
+ const touchCompactRoot = touchPage.locator('#heading-links-compact');
+ const touchCompactH1 = await measureHeading(
+ touchCompactRoot.getByRole('heading', {
+ name: 'Compact first-level heading',
+ }),
+ );
+ const touchCompactH6Headings = touchCompactRoot.getByRole('heading', {
+ name: 'Compact sixth-level heading',
+ });
+ const touchCompactH6 = await measureHeading(touchCompactH6Headings.first());
+ const touchCompactH6Sibling = await measureHeading(
+ touchCompactH6Headings.nth(1),
+ );
+ evidence.touchCompactGeometry = {
+ h1: touchCompactH1,
+ h6: touchCompactH6,
+ h6Sibling: touchCompactH6Sibling,
+ };
+ expect(rectsIntersect(touchCompactH1.button, touchCompactH6.button)).toBe(
+ false,
+ );
+ expect(
+ rectsIntersect(touchCompactH6.button, touchCompactH6Sibling.button),
+ ).toBe(false);
+ await touchRoot.screenshot({path: path.join(OUTPUT, 'touch-rest.png')});
+
+ const touchCanonicalUrl = new URL(
+ '#heading-links-ltr--linkable-headings',
+ touchPage.url(),
+ ).href;
+ const touchLocationBeforeCopy = touchPage.url();
+ const touchScrollBeforeCopy = await touchPage.evaluate(() => ({
+ x: window.scrollX,
+ y: window.scrollY,
+ }));
+ await touchPage.evaluate(() => {
+ (
+ window as typeof window & {__headingLinksNoReload?: string}
+ ).__headingLinksNoReload = 'alive';
+ });
+ if (singleProcessProof) {
+ await touchCopyButton.click();
+ } else {
+ await touchCopyButton.tap();
+ }
+ await expect(touchPage).toHaveURL(touchLocationBeforeCopy);
+ expect(
+ await touchPage.evaluate(() => ({x: window.scrollX, y: window.scrollY})),
+ ).toEqual(touchScrollBeforeCopy);
+ await expect(touchCopyButton).toHaveAccessibleName('Link copied');
+ const touchRing = await readFocusRing(touchCopyButton);
+ expect(touchRing.focusVisible).toBe(false);
+ expect(touchRing.outlineWidth).toBe('0px');
+ expect(touchRing.outlineStyle).toBe('none');
+ evidence.touchRing = touchRing;
+ evidence.touchClipboard = await touchPage.evaluate(async () =>
+ navigator.clipboard.readText(),
+ );
+ expect(evidence.touchClipboard).toBe(touchCanonicalUrl);
+ expect(
+ await touchPage.evaluate(
+ () =>
+ (window as typeof window & {__headingLinksNoReload?: string})
+ .__headingLinksNoReload,
+ ),
+ ).toBe('alive');
+ await touchRoot.screenshot({path: path.join(OUTPUT, 'touch-copied.png')});
+ if (singleProcessProof) {
+ await touchCdp?.send('Emulation.setTouchEmulationEnabled', {
+ enabled: false,
+ });
+ await page.setViewportSize({width: 1280, height: 900});
+ } else {
+ await touchContext.close();
+ }
+
+ const failureContext = singleProcessProof
+ ? page.context()
+ : await browser.newContext({
+ viewport: {width: 1280, height: 900},
+ });
+ await failureContext.addInitScript(() => {
+ Object.defineProperty(Navigator.prototype, 'clipboard', {
+ configurable: true,
+ get: () => ({
+ writeText: async () =>
+ Promise.reject(new Error('clipboard denied for proof')),
+ }),
+ });
+ });
+ const failurePage = singleProcessProof
+ ? page
+ : await failureContext.newPage();
+ await openStory(failurePage);
+ const failureHeading = failurePage
+ .locator('#heading-links-ltr')
+ .getByRole('heading', {name: 'Linkable headings'});
+ const failureButton = copyButtonForHeading(failureHeading);
+ const failureLocation = failurePage.url();
+ const failureGeometryBefore = await measureHeading(failureHeading);
+ await failureButton.click();
+ await expect(failureButton).toHaveAccessibleName(
+ 'Copy link to Linkable headings',
+ );
+ await expect(failureButton).toHaveText('#');
+ await expect(failurePage).toHaveURL(failureLocation);
+ const failureGeometryAfter = await measureHeading(failureHeading);
+ expectSameRect(failureGeometryBefore.row, failureGeometryAfter.row);
+ expectSameRect(failureGeometryBefore.heading, failureGeometryAfter.heading);
+ expectSameRect(failureGeometryBefore.slot, failureGeometryAfter.slot);
+ expectSameRect(failureGeometryBefore.button, failureGeometryAfter.button);
+ evidence.failureGeometry = {
+ before: failureGeometryBefore,
+ after: failureGeometryAfter,
+ };
+ if (!singleProcessProof) {
+ await failureContext.close();
+ }
+});