An open source design system that's fully customizable and agent ready
TypeScript
fix(core): never render <p> by default; render <div> for composition safety (#3151)
Cindy Zhang27b6a3f13e56
diff --git a/.changeset/no-default-paragraph-element.md b/.changeset/no-default-paragraph-element.mdnew file mode 100644index 0000000000..b81152a34a--- /dev/null+++ b/.changeset/no-default-paragraph-element.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Core components (`Banner`, `EmptyState`, `Markdown`) no longer render a `<p>` by default — they render `<div>` (appearance unchanged). This avoids hydration mismatches when block content lands in a `<p>`. `Markdown` paragraphs use `role="paragraph"`; pass `components={{paragraph: 'p'}}` to opt back into `<p>`.+@cixzhangdiff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.jsindex 7ffb1a61bf..86e0137ed7 100644--- a/internal/eslint-plugin-astryx/index.js+++ b/internal/eslint-plugin-astryx/index.js@@ -8,6 +8,7 @@* - no-hardcoded-styles: Enforces usage of design tokens instead of hardcoded values in StyleX* - boolean-prop-naming: Enforces is/has prefix on boolean props in *Props interfaces* - docblock-example-format: Enforces @example blocks use ``` fenced code on a separate line+ * - no-raw-paragraph: Disallows components from rendering a <p> by default (render <div> so any content composes)** Philosophy: Strict for agents (CI), lenient for humans (local dev)* - "strict" config: All rules as errors - use in CI/agent environments@@ -21,6 +22,7 @@ import noStylexNullOverrideRule from './no-stylex-null-override.js';import noReactIntrospectionRule from './no-react-introspection.js';import noClassnameClobberRule from './no-classname-clobber.js';import noHardcodedAnchorRule from './no-hardcoded-anchor.js';+import noRawParagraphRule from './no-raw-paragraph.js';import noBorderShorthandRule from './no-border-shorthand.js';import noReactNamespaceHooksRule from './no-react-namespace-hooks.js';import copyrightHeaderRule from './copyright-header.js';@@ -234,6 +236,7 @@ const plugin = {'no-react-introspection': noReactIntrospectionRule,'no-classname-clobber': noClassnameClobberRule,'no-hardcoded-anchor': noHardcodedAnchorRule,+ 'no-raw-paragraph': noRawParagraphRule,'no-border-shorthand': noBorderShorthandRule,'no-react-namespace-hooks': noReactNamespaceHooksRule,'require-base-props': requireBasePropsRule,@@ -258,6 +261,7 @@ plugin.configs.strict = {'@astryx/no-react-introspection': 'error','@astryx/no-classname-clobber': 'error','@astryx/no-hardcoded-anchor': 'error',+ '@astryx/no-raw-paragraph': 'error','@astryx/no-border-shorthand': 'error','@astryx/no-react-namespace-hooks': 'error','@astryx/require-base-props': 'error',@@ -280,6 +284,7 @@ plugin.configs.recommended = {'@astryx/no-react-introspection': 'error','@astryx/no-classname-clobber': 'error','@astryx/no-hardcoded-anchor': 'warn',+ '@astryx/no-raw-paragraph': 'warn','@astryx/no-border-shorthand': 'warn','@astryx/no-react-namespace-hooks': 'error','@astryx/require-base-props': 'warn',diff --git a/internal/eslint-plugin-astryx/no-raw-paragraph.js b/internal/eslint-plugin-astryx/no-raw-paragraph.jsnew file mode 100644index 0000000000..b520474973--- /dev/null+++ b/internal/eslint-plugin-astryx/no-raw-paragraph.js@@ -0,0 +1,146 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file no-raw-paragraph.js+ * @description Disallow Astryx components from rendering a `<p>` by default.+ *+ * `<p>` is phrasing-content-only in HTML: it cannot legally contain+ * block-level children (`<div>`, layers, popovers, images-as-blocks, etc.).+ * When a block element ends up inside a `<p>`, the HTML parser silently+ * reparents it and closes the `<p>` early. Server-rendered markup and the+ * browser-parsed DOM then disagree, producing React hydration mismatches.+ *+ * Astryx components accept arbitrary `ReactNode` content into their slots, so+ * any component that emits a `<p>` can be handed block content and break. The+ * enforceable fix on our side: Astryx's own components never emit a `<p>` by+ * default. They render `<div>` (styled to preserve appearance) instead, which+ * can contain anything. Consumers who genuinely want paragraph semantics opt+ * in explicitly (a raw `<p>` they own, or a component override such as+ * Markdown's `components={{paragraph: 'p'}}`), and they own the composition+ * consequences.+ *+ * This rule flags two patterns in Astryx source:+ * 1. A raw `<p>` JSX element.+ * 2. An element-type prop whose DEFAULT resolves to `'p'`, e.g.+ * `as: Component = 'p'` or `const Tag = as ?? 'p'`.+ *+ * It does NOT forbid `'p'` as an opt-in value (e.g. `as="p"` passed by a+ * consumer, or `'p'` appearing in an `as?: ... | 'p' | ...` union type) — only+ * Astryx defaulting to `<p>` on its own.+ *+ * Bad:+ * <p {...stylex.props(styles.description)}>{description}</p>+ * function Text({as: Component = 'p'}) { ... }+ *+ * Good:+ * <div {...stylex.props(styles.description)}>{description}</div>+ * function Text({as: Component = 'div'}) { ... } // 'p' still allowed via prop+ */++const rule = {+ meta: {+ type: 'suggestion',+ docs: {+ description:+ 'Disallow Astryx components from rendering a <p> by default — render <div> so any content composes without hydration mismatches',+ category: 'Best Practices',+ recommended: true,+ },+ messages: {+ rawParagraph:+ 'Astryx components must not render a <p> by default. <p> cannot contain ' ++ 'block-level children, so block content nested inside it triggers React ' ++ 'hydration mismatches. Render <div> instead (style margin/line-height to ' ++ 'preserve appearance). Consumers who want paragraph semantics can opt in.',+ defaultParagraph:+ 'Element-type prop defaults to "p". Astryx components must not default to ' ++ 'rendering a <p> (it cannot contain block children — see hydration mismatch). ' ++ 'Default to "div" and keep "p" as an opt-in value consumers can pass.',+ },+ schema: [],+ },+ create(context) {+ const filename = context.filename;++ // Skip non-source files.+ if (filename.includes('.test.') || filename.includes('.stories.')) {+ return {};+ }++ /**+ * Is this assignment pattern an element-type prop (`as` / `component`)+ * that defaults to the literal 'p'?+ */+ function isElementTypeDefaultToP(pattern) {+ if (pattern.type !== 'AssignmentPattern') {+ return false;+ }+ // Default value must be the string literal 'p'.+ const right = pattern.right;+ if (right?.type !== 'Literal' || right.value !== 'p') {+ return false;+ }+ // Left side names an element-type prop. Covers both:+ // {as = 'p'} -> Identifier 'as'+ // {as: Component = 'p'} -> handled at the Property level (see below)+ const left = pattern.left;+ if (left?.type === 'Identifier') {+ return /^(as|component|tag|element)$/i.test(left.name);+ }+ return false;+ }++ return {+ JSXOpeningElement(node) {+ if (node.name?.type === 'JSXIdentifier' && node.name.name === 'p') {+ context.report({node, messageId: 'rawParagraph'});+ }+ },++ // `{as = 'p'}` — shorthand destructured prop with default.+ AssignmentPattern(node) {+ if (isElementTypeDefaultToP(node)) {+ context.report({node, messageId: 'defaultParagraph'});+ }+ },++ // `{as: Component = 'p'}` — renamed destructured prop with default.+ Property(node) {+ if (+ node.value?.type === 'AssignmentPattern' &&+ node.value.right?.type === 'Literal' &&+ node.value.right.value === 'p'+ ) {+ const key = node.key;+ const keyName =+ key?.type === 'Identifier'+ ? key.name+ : key?.type === 'Literal'+ ? String(key.value)+ : '';+ if (/^(as|component|tag|element)$/i.test(keyName)) {+ context.report({+ node: node.value.right,+ messageId: 'defaultParagraph',+ });+ }+ }+ },++ // `const Tag = as ?? 'p'` / `as || 'p'` — defaulting via fallback expr.+ LogicalExpression(node) {+ if (+ (node.operator === '??' || node.operator === '||') &&+ node.right?.type === 'Literal' &&+ node.right.value === 'p' &&+ node.left?.type === 'Identifier' &&+ /^(as|component|tag|element)$/i.test(node.left.name)+ ) {+ context.report({node: node.right, messageId: 'defaultParagraph'});+ }+ },+ };+ },+};++export default rule;diff --git a/internal/eslint-plugin-astryx/no-raw-paragraph.test.mjs b/internal/eslint-plugin-astryx/no-raw-paragraph.test.mjsnew file mode 100644index 0000000000..c340db5b03--- /dev/null+++ b/internal/eslint-plugin-astryx/no-raw-paragraph.test.mjs@@ -0,0 +1,74 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file no-raw-paragraph.test.mjs+ * @description Tests for the no-raw-paragraph ESLint rule.+ */++import {describe, it} from 'vitest';+import {RuleTester} from 'eslint';+import tseslint from 'typescript-eslint';+import noRawParagraphRule from './no-raw-paragraph.js';++const ruleTester = new RuleTester({+ languageOptions: {+ parser: tseslint.parser,+ parserOptions: {+ ecmaFeatures: {jsx: true},+ },+ },+});++describe('no-raw-paragraph', () => {+ it('passes the RuleTester', () => {+ ruleTester.run('no-raw-paragraph', noRawParagraphRule, {+ valid: [+ // <div> is the compositional default we want.+ {code: '<div>{children}</div>'},+ // Other phrasing/block elements are unaffected.+ {code: '<span>{text}</span>'},+ {code: '<section>{children}</section>'},+ // `as` defaulting to 'div' is correct.+ {code: 'function C({as: Component = "div"}) { return <Component/>; }'},+ {code: 'function C({as = "div"}) { return null; }'},+ // 'p' as an opt-in value (not a default) is allowed: it appears only+ // in the type union, never as the default the component renders.+ {code: 'const Tag = as ?? "div";'},+ {code: 'const Tag = as || "div";'},+ // A consumer passing as="p" is their choice — not flagged here (this+ // rule guards Astryx source defaults, not prop usage call sites).+ {code: '<Text as="p">{text}</Text>'},+ ],+ invalid: [+ // Raw <p> JSX.+ {+ code: '<p {...props}>{children}</p>',+ errors: [{messageId: 'rawParagraph'}],+ },+ {+ code: '<p>text</p>',+ errors: [{messageId: 'rawParagraph'}],+ },+ // `as` prop defaulting to 'p' (renamed).+ {+ code: 'function C({as: Component = "p"}) { return <Component/>; }',+ errors: [{messageId: 'defaultParagraph'}],+ },+ // `as` prop defaulting to 'p' (shorthand).+ {+ code: 'function C({as = "p"}) { return null; }',+ errors: [{messageId: 'defaultParagraph'}],+ },+ // Defaulting via nullish/or fallback expression.+ {+ code: 'const Tag = as ?? "p";',+ errors: [{messageId: 'defaultParagraph'}],+ },+ {+ code: 'const Tag = as || "p";',+ errors: [{messageId: 'defaultParagraph'}],+ },+ ],+ });+ });+});diff --git a/packages/core/src/Banner/Banner.test.tsx b/packages/core/src/Banner/Banner.test.tsxindex a754798b13..8b488e3180 100644--- a/packages/core/src/Banner/Banner.test.tsx+++ b/packages/core/src/Banner/Banner.test.tsx@@ -76,11 +76,22 @@ describe('Banner', () => {expect(screen.getByText('This is a description')).toBeInTheDocument();});+ it('renders title and description as <div> (never <p>) for composition safety', () => {+ const {container} = render(+ <Banner status="info" title="Title" description="Description" />,+ );+ // Block content can be nested inside Banner text slots without tripping+ // the phrasing-content trap that <p> imposes, so neither slot is a <p>.+ expect(container.querySelector('p')).toBeNull();+ expect(screen.getByText('Title').tagName).toBe('DIV');+ expect(screen.getByText('Description').tagName).toBe('DIV');+ });+it('does not render description when not provided', () => {- const {container} = render(<Banner status="info" title="Title Only" />);- // Only one <p> for the title, no description- const paragraphs = container.querySelectorAll('p');- expect(paragraphs).toHaveLength(1);+ render(<Banner status="info" title="Title Only" />);+ // Title renders; no description text is present.+ expect(screen.getByText('Title Only')).toBeInTheDocument();+ expect(screen.queryByText('This is a description')).not.toBeInTheDocument();});it('renders dismiss button when isDismissable', () => {@@ -158,9 +169,7 @@ describe('Banner', () => {});it('renders card container by default', () => {- const {container} = render(- <Banner status="info" title="Card Container" />,- );+ const {container} = render(<Banner status="info" title="Card Container" />);const root = container.firstElementChild;expect(root).toBeInTheDocument();});diff --git a/packages/core/src/Banner/Banner.tsx b/packages/core/src/Banner/Banner.tsxindex dd164be0c6..bb94a5f2bb 100644--- a/packages/core/src/Banner/Banner.tsx+++ b/packages/core/src/Banner/Banner.tsx@@ -16,6 +16,13 @@* - Each visual area owns its own border-radius (no overflow:clip on the container)* - When children are provided, a collapse/expand toggle button appears in the end area*+ * Title and description render as <div> (not <p>): they accept arbitrary+ * ReactNode content, and <p> cannot legally contain block-level children+ * (the HTML parser reparents them, desyncing SSR markup from the hydrated+ * DOM). Using <div> keeps these slots composable with any content. Their+ * StyleX styles set margin: 0 and explicit typography, so the rendered+ * appearance is identical to the previous <p>.+ ** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Banner/Banner.doc.mjs (props table, features, implementation notes)* - /packages/core/src/Banner/Banner.test.tsx (tests for new/changed behavior)@@ -441,9 +448,9 @@ export function Banner({)}</div><div {...stylex.props(styles.headerContent)}>- <p {...stylex.props(styles.title)}>{title}</p>+ <div {...stylex.props(styles.title)}>{title}</div>{description != null && (- <p {...stylex.props(styles.description)}>{description}</p>+ <div {...stylex.props(styles.description)}>{description}</div>)}</div>{showEndArea && (diff --git a/packages/core/src/EmptyState/EmptyState.test.tsx b/packages/core/src/EmptyState/EmptyState.test.tsxindex 62c170f0d0..300d4380f0 100644--- a/packages/core/src/EmptyState/EmptyState.test.tsx+++ b/packages/core/src/EmptyState/EmptyState.test.tsx@@ -45,11 +45,13 @@ describe('EmptyState', () => {/>,);expect(screen.getByText('Try adjusting your search.')).toBeInTheDocument();+ // Description renders as <div> (never <p>) so block content composes safely.+ expect(screen.getByText('Try adjusting your search.').tagName).toBe('DIV');});it('does not render description when not provided', () => {- const {container} = render(<EmptyState title="No results" />);- expect(container.querySelector('p')).not.toBeInTheDocument();+ render(<EmptyState title="No results" />);+ expect(screen.queryByText('Try adjusting your search.')).toBeNull();});it('renders with icon', () => {diff --git a/packages/core/src/EmptyState/EmptyState.tsx b/packages/core/src/EmptyState/EmptyState.tsxindex 6acfbb1d0f..6d88f7c9f1 100644--- a/packages/core/src/EmptyState/EmptyState.tsx+++ b/packages/core/src/EmptyState/EmptyState.tsx@@ -174,13 +174,17 @@ export function EmptyState({title,)}{description != null && (- <p+ // Rendered as <div> (not <p>): description accepts ReactNode and a+ // <p> cannot legally contain block children, which causes hydration+ // mismatches. The StyleX style sets margin: 0, so appearance is+ // unchanged.+ <div{...stylex.props(styles.description,isCompact && styles.descriptionCompact,)}>{description}- </p>+ </div>)}</div>{actions != null && (diff --git a/packages/core/src/Markdown/Markdown.test.tsx b/packages/core/src/Markdown/Markdown.test.tsxindex 34db1a06b6..cff51c13a3 100644--- a/packages/core/src/Markdown/Markdown.test.tsx+++ b/packages/core/src/Markdown/Markdown.test.tsx@@ -22,9 +22,16 @@ describe('Markdown', () => {expect(screen.getByText('Heading 2').tagName).toBe('H2');});- it('renders paragraphs', () => {+ it('renders paragraphs as block <div> (never <p>) for composition safety', () => {render(<Markdown>{'Hello world'}</Markdown>);- expect(screen.getByText('Hello world').tagName).toBe('P');+ // Markdown paragraphs render as <div> so block-level inline content+ // (images, custom inline components) never trips the phrasing-content+ // trap that a <p> would impose. role="paragraph" re-exposes the paragraph+ // role to assistive tech without the <p> hazard. Consumers who want a real+ // <p> element can pass `components={{paragraph: 'p'}}`.+ const para = screen.getByText('Hello world');+ expect(para.tagName).toBe('DIV');+ expect(para).toHaveAttribute('role', 'paragraph');});it('renders inline display without block wrappers', () => {@@ -201,9 +208,7 @@ describe('Markdown', () => {});it('shows streaming cursor when isStreaming is true', () => {- const {container} = render(- <Markdown isStreaming>{'Hello'}</Markdown>,- );+ const {container} = render(<Markdown isStreaming>{'Hello'}</Markdown>);// Streaming mode parses incrementally but no cursor elementexpect(container.querySelector('[role="document"]')).toBeInTheDocument();});@@ -243,9 +248,7 @@ describe('Markdown', () => {it('sanitizes data: URLs in images', () => {const {container} = render(- <Markdown>- {'</script>)'}- </Markdown>,+ <Markdown>{'</script>)'}</Markdown>,);const img = container.querySelector('img');expect(img).toBeNull();@@ -435,9 +438,7 @@ describe('inlinePlugins', () => {},};const {container} = render(- <Markdown inlinePlugins={[plugin]}>- {'See TAG:important here'}- </Markdown>,+ <Markdown inlinePlugins={[plugin]}>{'See TAG:important here'}</Markdown>,);const tag = container.querySelector('[data-testid="tag-match"]');expect(tag).toBeInTheDocument();@@ -446,9 +447,7 @@ describe('inlinePlugins', () => {it('renders identically when no inlinePlugins are provided', () => {const withPlugins = render(- <Markdown inlinePlugins={[]}>- {'Hello **world** and `code`'}- </Markdown>,+ <Markdown inlinePlugins={[]}>{'Hello **world** and `code`'}</Markdown>,);const withoutPlugins = render(<Markdown>{'Hello **world** and `code`'}</Markdown>,@@ -481,9 +480,7 @@ describe('inlinePlugins', () => {it('renders bare https URLs as links when autolink="gfm"', () => {const {container} = render(- <Markdown autolink="gfm">- {'see https://example.com here'}- </Markdown>,+ <Markdown autolink="gfm">{'see https://example.com here'}</Markdown>,);const link = container.querySelector('a');expect(link).not.toBeNull();@@ -503,9 +500,7 @@ describe('inlinePlugins', () => {it('renders bare emails with mailto: href', () => {const {container} = render(- <Markdown autolink="gfm">- {'ping [email protected] please'}- </Markdown>,+ <Markdown autolink="gfm">{'ping [email protected] please'}</Markdown>,);const link = container.querySelector('a');expect(link).not.toBeNull();@@ -515,9 +510,7 @@ describe('inlinePlugins', () => {it('does not autolink URLs inside code spans', () => {const {container} = render(- <Markdown autolink="gfm">- {'try `https://example.com` here'}- </Markdown>,+ <Markdown autolink="gfm">{'try `https://example.com` here'}</Markdown>,);expect(container.querySelector('a')).toBeNull();expect(container.querySelector('code')).not.toBeNull();@@ -525,9 +518,7 @@ describe('inlinePlugins', () => {it('does not autolink URLs inside code blocks', () => {const {container} = render(- <Markdown autolink="gfm">- {'```\nhttps://example.com\n```'}- </Markdown>,+ <Markdown autolink="gfm">{'```\nhttps://example.com\n```'}</Markdown>,);expect(container.querySelector('a')).toBeNull();expect(container.querySelector('pre')).not.toBeNull();diff --git a/packages/core/src/Markdown/Markdown.tsx b/packages/core/src/Markdown/Markdown.tsxindex f14b32074f..0cf7382333 100644--- a/packages/core/src/Markdown/Markdown.tsx+++ b/packages/core/src/Markdown/Markdown.tsx@@ -1113,9 +1113,19 @@ function renderBlock(if (ParagraphComp) {return <ParagraphComp key={index}>{paraChildren}</ParagraphComp>;}+ // Markdown paragraphs render as <div>, not <p>: inline content can+ // include block-level nodes (images, custom inline components), and a+ // <p> would reparent them, desyncing SSR markup from the hydrated DOM.+ // Block spacing comes from token-based StyleX margins, so the rendered+ // appearance is unchanged. role="paragraph" re-exposes the paragraph+ // role in the accessibility tree (a pure ARIA hint — it does not trigger+ // the parser's block-child reparenting) so prose semantics are preserved+ // without the <p> composition hazard. Consumers who want a real <p>+ // element can still pass components={{paragraph: 'p'}}.return (- <p+ <divkey={index}+ role="paragraph"{...stylex.props(spacing,contentWidthValue != null@@ -1128,7 +1138,7 @@ function renderBlock(isLast && styles.noMarginBlockEnd,)}>{paraChildren}- </p>+ </div>);}case 'codeblock': {@@ -1487,7 +1497,7 @@ function renderBlock(const safeSrc = sanitizeUrl(node.src);if (safeSrc == null) {return (- <p+ <divkey={index}{...stylex.props(spacing,@@ -1495,11 +1505,11 @@ function renderBlock(isLast && styles.noMarginBlockEnd,)}>[{node.alt}]- </p>+ </div>);}return (- <p+ <divkey={index}{...stylex.props(spacing,@@ -1507,7 +1517,7 @@ function renderBlock(isLast && styles.noMarginBlockEnd,)}><img src={safeSrc} alt={node.alt} {...stylex.props(styles.image)} />- </p>+ </div>);}}