An open source design system that's fully customizable and agent ready
TypeScript
docs(blog): post headings get copy-link anchors (#7384)
Cindy Zhang19b1c00b5ab6
diff --git a/apps/docsite/e2e/blog-heading-links.spec.ts b/apps/docsite/e2e/blog-heading-links.spec.tsnew file mode 100644index 0000000000..0e79ad0a91--- /dev/null+++ b/apps/docsite/e2e/blog-heading-links.spec.ts@@ -0,0 +1,121 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file blog-heading-links.spec.ts+ * @input Production docsite blog post (the 0.6.0 release post)+ * @output Proof that post headings reveal a copy-link control, that it copies+ * the heading's permalink, and that a copied link lands the heading below+ * the sticky header, left to right and right to left+ * @position Docsite browser tests; jsdom has no hover, clipboard, or layout+ */++import {expect, test, type Page} from '@playwright/test';++const POST = '/blog/astryx-v0-6-0';+const HEADING = 'Themes respond in CSS';+const HEADING_ID = 'themes-respond-in-css';++function copyButton(page: Page, heading: string) {+ return page.getByRole('button', {name: `Copy link to ${heading}`});+}++test.use({+ permissions: ['clipboard-read', 'clipboard-write'],+ // Headless Chromium reports no hover-capable pointer; give it the desktop+ // mouse a reader has, so the hover reveal is what gets exercised.+ launchOptions: {+ args: [+ '--blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4',+ ],+ },+});++async function opacity(locator: ReturnType<Page['getByRole']>) {+ return Number(await locator.evaluate(el => getComputedStyle(el).opacity));+}++test('hovering a post heading reveals a control that copies its permalink', async ({+ page,+}) => {+ await page.setViewportSize({width: 1280, height: 900});+ await page.goto(POST);++ const heading = page.getByRole('heading', {name: HEADING});+ await expect(heading).toHaveAttribute('id', HEADING_ID);++ expect(await page.evaluate(() => matchMedia('(hover: hover)').matches)).toBe(+ true,+ );+ const button = copyButton(page, HEADING);+ await page.mouse.move(0, 0);+ await expect.poll(() => opacity(button)).toBe(0);+ await heading.hover();+ await expect.poll(() => opacity(button)).toBe(1);+ await button.click();++ const copied = await page.evaluate(() => navigator.clipboard.readText());+ expect(new URL(copied).pathname).toBe(POST);+ expect(new URL(copied).hash).toBe(`#${HEADING_ID}`);+});++for (const [dir, colorScheme] of [+ ['ltr', 'light'],+ ['rtl', 'dark'],+] as const) {+ test(`a copied heading link lands below the sticky header (${dir}, ${colorScheme})`, async ({+ page,+ }, testInfo) => {+ await page.setViewportSize({width: 1280, height: 900});+ await page.emulateMedia({colorScheme});+ await page.goto(POST);+ await page.evaluate(+ ([d, id]) => {+ document.documentElement.setAttribute('dir', d);+ // Follow the copied link the way a reader does: by its fragment.+ window.location.hash = '';+ window.location.hash = id;+ },+ [dir, HEADING_ID] as const,+ );++ const heading = page.getByRole('heading', {name: HEADING});+ const header = page.locator('.astryx-app-shell-header').first();+ await expect(heading).toBeInViewport();+ const headerBox = await header.boundingBox();+ const headingTop = (await heading.boundingBox())?.y ?? -1;+ expect(headingTop).toBeGreaterThanOrEqual(+ (headerBox?.y ?? 0) + (headerBox?.height ?? 0) - 1,+ );++ await heading.hover();+ const button = copyButton(page, HEADING);+ await expect(button).toBeVisible();+ // The control trails the heading text on the inline-end side.+ const textBox = await heading.evaluate(el => {+ const range = document.createRange();+ range.selectNodeContents(el);+ const r = range.getBoundingClientRect();+ return {x: r.x, y: r.y, width: r.width, height: r.height};+ });+ const buttonBox = await button.boundingBox();+ if (buttonBox == null) {+ throw new Error('missing layout');+ }+ if (dir === 'rtl') {+ expect(buttonBox.x + buttonBox.width).toBeLessThanOrEqual(textBox.x + 1);+ } else {+ expect(buttonBox.x).toBeGreaterThanOrEqual(textBox.x + textBox.width - 1);+ }++ // Review evidence: the revealed control beside its heading.+ await page.screenshot({+ path: testInfo.outputPath(`heading-link-${dir}-${colorScheme}.png`),+ clip: {+ x: Math.max(0, Math.min(textBox.x, buttonBox.x) - 24),+ y: Math.max(0, textBox.y - 24),+ width: textBox.width + buttonBox.width + 64,+ height: textBox.height + 48,+ },+ });+ });+}diff --git a/apps/docsite/src/__tests__/blog-heading-links.test.tsx b/apps/docsite/src/__tests__/blog-heading-links.test.tsxnew file mode 100644index 0000000000..7314ea0e8e--- /dev/null+++ b/apps/docsite/src/__tests__/blog-heading-links.test.tsx@@ -0,0 +1,94 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Blog post headings carry copy-link anchors.+ *+ * Renders a real post through BlogArticle the way the static build does+ * (server markup) and checks that each post heading gets the id a reader+ * would link to, plus the heading-links copy control beside it.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {renderToStaticMarkup} from 'react-dom/server';+import {describe, expect, it, vi} from 'vitest';+import {BlogArticle} from '../components/blog/BlogArticle';+import type {BlogPost} from '../lib/blog/schema';+import {discoverPosts} from '../lib/blog/posts.mjs';++// The docsite's own StyleX is compiled by its Babel build, not by Vitest.+vi.mock('@stylexjs/stylex', () => ({+ create: <T,>(styles: T) => styles,+ props: () => ({}),+ firstThatWorks: <T,>(...values: T[]) => values[0],+ defineMarker: () => ({}),+ defineConsts: <T,>(values: T) => values,+ defineVars: <T,>(values: T) => values,+ keyframes: () => 'keyframes',+ when: {ancestor: () => ':hover', descendant: () => ':hover'},+}));++const POSTS_DIR = path.resolve(__dirname, '../content/blog/posts');+const RELEASE_POST_SLUG = 'astryx-v0-6-0';++function renderPost(slug: string): string {+ const post = (discoverPosts(POSTS_DIR) as BlogPost[]).find(+ p => p.slug === slug,+ );+ if (post == null) {+ throw new Error(`missing post ${slug}`);+ }+ return renderToStaticMarkup(<BlogArticle post={post} />);+}++/** Each post heading in the markup: its id, its text, and what follows it. */+function postHeadings(html: string) {+ return Array.from(+ html.matchAll(+ /<h([2-6]) id="([^"]+)" class="astryx-markdown-heading"[^>]*>([^<]*)<\/h\1>([\s\S]{0,600})/g,+ ),+ ([, , id, text, after]) => ({id, text, after}),+ );+}++describe('blog post headings', () => {+ it('give every section heading the id a reader links to and a copy-link control', () => {+ const headings = postHeadings(renderPost(RELEASE_POST_SLUG));+ expect(headings.map(h => h.id)).toEqual(+ expect.arrayContaining([+ 'themes-respond-in-css',+ 'migrate-to-0-6-0',+ 'thank-you',+ ]),+ );+ for (const heading of headings) {+ expect(heading.after).toContain(+ `aria-label="Copy link to ${heading.text}"`,+ );+ }+ });++ it('keep ids unique across the post', () => {+ const ids = Array.from(+ renderPost(RELEASE_POST_SLUG).matchAll(/\bid="([^"]+)"/g),+ m => m[1],+ );+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('create the heading-links plugin in a client module, never in the server-rendered article', () => {+ // A plugin passed from a Server Component to the client Markdown arrives+ // as a plain object and silently does nothing.+ const read = (file: string) =>+ fs.readFileSync(+ path.resolve(__dirname, '../components/blog', file),+ 'utf8',+ );+ const body = read('BlogPostBody.tsx');+ expect(body).toMatch(/^(\/\/[^\n]*\n|\s)*'use client';/);+ expect(body).toContain('createMarkdownHeadingLinks(');+ expect(read('BlogArticle.tsx')).not.toMatch(+ /Markdown\/plugins|createMarkdownHeadingLinks/,+ );+ });+});diff --git a/apps/docsite/src/components/blog/BlogArticle.tsx b/apps/docsite/src/components/blog/BlogArticle.tsxindex 22cd078694..d50cf173c7 100644--- a/apps/docsite/src/components/blog/BlogArticle.tsx+++ b/apps/docsite/src/components/blog/BlogArticle.tsx@@ -6,7 +6,6 @@*/import * as stylex from '@stylexjs/stylex';-import {Markdown} from '@astryxdesign/core/Markdown';import {Text, Heading} from '@astryxdesign/core/Text';import {VStack, HStack} from '@astryxdesign/core/Layout';import {Grid} from '@astryxdesign/core/Grid';@@ -23,7 +22,7 @@ import {POST_TYPE_LABELS} from '../../lib/blog/schema';import {MarkdownText} from '../MarkdownText';import {AuthorByline} from './AuthorByline';import {ReleaseCoverArt} from './ReleaseCoverArt';-import {MarkdownImage} from './ThemedImage';+import {BlogPostBody} from './BlogPostBody';import {parseReleaseVersion} from '../../lib/blog/release';import {layout} from '../../layout.stylex';@@ -108,12 +107,7 @@ export function BlogArticle({post}: BlogArticleProps) {</AspectRatio>) : null}- <Markdown- headingLevelStart={2}- contentWidth="100%"- components={{image: MarkdownImage}}>- {post.body}- </Markdown>+ <BlogPostBody body={post.body} />{post.tags.length > 0 ? (<HStack gap={1} xstyle={styles.tagRow}>diff --git a/apps/docsite/src/components/blog/BlogPostBody.module.css b/apps/docsite/src/components/blog/BlogPostBody.module.cssnew file mode 100644index 0000000000..057055ceda--- /dev/null+++ b/apps/docsite/src/components/blog/BlogPostBody.module.css@@ -0,0 +1,10 @@+/* Copyright (c) Meta Platforms, Inc. and affiliates. */++/*+ * A heading reached through its copied link scrolls clear of the sticky app+ * header, as docs section headings do (AnchorHeading). The window is what+ * scrolls on a blog page, so the header offset goes on the target itself.+ */+.body :is(h1, h2, h3, h4, h5, h6)[id] {+ scroll-margin-top: calc(var(--appshell-header-height, 0px) + 16px);+}diff --git a/apps/docsite/src/components/blog/BlogPostBody.tsx b/apps/docsite/src/components/blog/BlogPostBody.tsxnew file mode 100644index 0000000000..2902e3d992--- /dev/null+++ b/apps/docsite/src/components/blog/BlogPostBody.tsx@@ -0,0 +1,41 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file BlogPostBody.tsx+ * A blog post's Markdown body. Every heading gets a stable id and the+ * hover-revealed copy-link control (createMarkdownHeadingLinks).+ *+ * The plugin list is created here, in the client module, because a Markdown+ * plugin is a registered handle: passed from the server-rendered BlogArticle+ * it would be serialized into a plain object that Markdown no longer+ * recognizes, and the plugin would silently not run.+ */++import {Markdown} from '@astryxdesign/core/Markdown';+import {createMarkdownHeadingLinks} from '@astryxdesign/core/Markdown/plugins';+import {MarkdownImage} from './ThemedImage';+import css from './BlogPostBody.module.css';++// One post per page, so ids are unprefixed and match each heading's own text.+const POST_MARKDOWN_PLUGINS = [createMarkdownHeadingLinks()];++export interface BlogPostBodyProps {+ /** Markdown body (frontmatter stripped). */+ body: string;+}++export function BlogPostBody({body}: BlogPostBodyProps) {+ return (+ <div className={css.body}>+ <Markdown+ headingLevelStart={2}+ contentWidth="100%"+ components={{image: MarkdownImage}}+ plugins={POST_MARKDOWN_PLUGINS}>+ {body}+ </Markdown>+ </div>+ );+}