An open source design system that's fully customizable and agent ready
TypeScript
fix(Markdown): each prose block lays out in its own text's direction (#10293)
Cindy Zhangb8cc3f41e8e3
diff --git a/.changeset/markdown-block-own-direction.md b/.changeset/markdown-block-own-direction.mdnew file mode 100644index 0000000000..1fab5e09e3--- /dev/null+++ b/.changeset/markdown-block-own-direction.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Markdown: each paragraph, heading, quote and list item lays out in the direction of its own text. A Hebrew or Arabic paragraph in a left-to-right page now starts on the right, and an English paragraph in a right-to-left page starts on the left. A block with no letters, such as digits, punctuation or an image, takes the page's direction from the `InternationalizationProvider`, also inside a quote or list item that reads the other way. Lists, code blocks and tables keep the direction around them too, and the text in each table cell reads in its own direction. A numbered item that reads against its list shows its number beside its own text, and a table cell that reads against its table keeps the table's column lines and any explicit column alignment. A task list now keeps to the same prose width as other lists.++@potatowagon @cixzhangdiff --git a/.changeset/richtext-editor-theme-direction-comment.md b/.changeset/richtext-editor-theme-direction-comment.mdnew file mode 100644index 0000000000..e6cf3eb2c4--- /dev/null+++ b/.changeset/richtext-editor-theme-direction-comment.md@@ -0,0 +1,7 @@+---+'@astryxdesign/richtext': patch+---++[docs] A source comment in the editor theme now says that core `Markdown` gives each block the direction of its own text, while the editor keeps blocks in the surface's direction.++@cixzhangdiff --git a/apps/docsite/e2e/blog-heading-links.spec.ts b/apps/docsite/e2e/blog-heading-links.spec.tsindex 13b7ee36a4..55dfbe1628 100644--- a/apps/docsite/e2e/blog-heading-links.spec.ts+++ b/apps/docsite/e2e/blog-heading-links.spec.ts@@ -111,7 +111,12 @@ for (const [dir, colorScheme] of [await heading.hover();const button = copyButton(page, HEADING);await expect(button).toBeVisible();- // The control trails the heading text on the inline-end side.+ // The control trails the heading text on the heading's own inline-end+ // side. The heading lays out in the direction of its own text, so an+ // English heading keeps it on its right in a right-to-left page too.+ const headingDirection = await heading.evaluate(+ el => getComputedStyle(el).direction,+ );const textBox = await heading.evaluate(el => {const range = document.createRange();range.selectNodeContents(el);@@ -122,7 +127,7 @@ for (const [dir, colorScheme] of [if (buttonBox == null) {throw new Error('missing layout');}- if (dir === 'rtl') {+ if (headingDirection === 'rtl') {expect(buttonBox.x + buttonBox.width).toBeLessThanOrEqual(textBox.x + 1);} else {expect(buttonBox.x).toBeGreaterThanOrEqual(textBox.x + textBox.width - 1);diff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.jsonindex 300733359c..b3404db88d 100644--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json@@ -2593,7 +2593,6 @@"FR4","FR4","FR5",- "FR6","FR9","spec quote","spec quote",@@ -2603,7 +2602,6 @@"spec:AST-061","spec:AST-061","spec:AST-061",- "spec:AST-061","spec:AST-061"],"packages/richtext/src/index.ts": ["spec quote", "spec:AST-061/DEC-8"],diff --git a/packages/core/src/List/ListContext.tsx b/packages/core/src/List/ListContext.tsxindex 0efecc2904..99df9cacad 100644--- a/packages/core/src/List/ListContext.tsx+++ b/packages/core/src/List/ListContext.tsx@@ -64,6 +64,14 @@ export interface ListContextValue {* on their List, so its text starts match RichText without a width threshold.*/hasMarkerGutter?: boolean;+ /**+ * Whether a numbered item lays out outside the List's shared number+ * columns, with its counter beside its own text as a bullet row has it; set+ * by ListMarkerScope; internal. Markdown sets it on an item that reads+ * against its list, so that item's text never widens the shared counter+ * column for the other rows.+ */+ isOutsideNumberColumns?: boolean;/*** The list's `animatedLayout` handle, for its rows.*/@@ -82,25 +90,30 @@ ListContext.displayName = 'ListContext';* List's `listStyle` names, or `task`'s read-only checkbox in place of either;* internal, for Markdown's nested lists and task items in mixed lists. With* `hasMarkerGutter`, counters keep the ordinary marker column and may paint- * outside it toward inline-start. Outside a List, or in a List without markers, it- * changes nothing.+ * outside it toward inline-start. With `isOutsideNumberColumns`, a numbered+ * item keeps its counter beside its own text instead of in the shared column.+ * Outside a List, or in a List without markers, it changes nothing.*/export function ListMarkerScope({marker,task,hasMarkerGutter = false,+ isOutsideNumberColumns = false,children,}: {readonly marker: ListMarker;readonly task?: ListTaskMarker;readonly hasMarkerGutter?: boolean;+ readonly isOutsideNumberColumns?: boolean;readonly children: ReactNode;}): ReactNode {const context = use(ListContext);const value = useMemo(() =>- context == null ? null : {...context, marker, task, hasMarkerGutter},- [context, marker, task, hasMarkerGutter],+ context == null+ ? null+ : {...context, marker, task, hasMarkerGutter, isOutsideNumberColumns},+ [context, marker, task, hasMarkerGutter, isOutsideNumberColumns],);return value == null ? (childrendiff --git a/packages/core/src/List/ListItem.tsx b/packages/core/src/List/ListItem.tsxindex 1b10d8586b..a6c5f32f18 100644--- a/packages/core/src/List/ListItem.tsx+++ b/packages/core/src/List/ListItem.tsx@@ -182,6 +182,10 @@ const styles = stylex.create({gridTemplateColumns: 'subgrid',gridColumn: '1 / -1',},+ // A numbered row outside the shared columns still spans the List's grid.+ spanNumberColumns: {+ gridColumn: '1 / -1',+ },withCounter: {counterIncrement: 'astryx-list',},@@ -469,6 +473,8 @@ export function ListItem({const task = markerKind == null ? undefined : ctx?.task;const hasMarkerGutter = ctx?.hasMarkerGutter === true;+ const usesNumberColumns =+ listStyle === 'decimal' && ctx?.isOutsideNumberColumns !== true;const marker = useMemo(() =>task != null ? (@@ -527,7 +533,10 @@ export function ListItem({density={density}xstyle={[- listStyle === 'decimal' && styles.numberColumns,+ usesNumberColumns && styles.numberColumns,+ listStyle === 'decimal' &&+ !usesNumberColumns &&+ styles.spanNumberColumns,hasMarkers && styles.withCounter,travellingStyles.row,hasDividers && styles.withDivider,@@ -550,7 +559,7 @@ export function ListItem({const row = <ItemListRowContext value>{item}</ItemListRowContext>;// Only numbered rows contribute two cells to List's shared counter grid.// Passing the marker identity keeps this request off unrelated Items in slots.- return listStyle === 'decimal' ? (+ return usesNumberColumns ? (<ItemMarkerColumnsContext value={marker}>{row}</ItemMarkerColumnsContext>) : (rowdiff --git a/packages/core/src/List/ListMarkers.a11y.chromium.spec.ts b/packages/core/src/List/ListMarkers.a11y.chromium.spec.tsindex 9e03567387..0bb6d8c0b4 100644--- a/packages/core/src/List/ListMarkers.a11y.chromium.spec.ts+++ b/packages/core/src/List/ListMarkers.a11y.chromium.spec.ts@@ -242,7 +242,11 @@ for (const {width, mode} of [1,);for (const item of items) {- expect(item.direction).toBe(dir);+ // Markdown lays each item out in the direction of its own text,+ // and this story's items are English.+ expect(item.direction).toBe(+ story === 'core-markdown--long-number-markers' ? 'ltr' : dir,+ );expect(item.markerHeight).toBeLessThanOrEqual(item.lineHeight + 1);expect(item.markerScrollWidth).toBeLessThanOrEqual(item.markerWidth + 1,@@ -291,16 +295,20 @@ for (const {width, mode} of [const clipped = await page.screenshot({fullPage: true});await page.addStyleTag({content: UNCLIPPED});const whole = await page.screenshot({fullPage: true});+ // The English Markdown story's items read left to right on either+ // page, so their counters end on the left-to-right edge.+ const itemDir =+ story === 'core-markdown--long-number-markers' ? 'ltr' : dir;for (const [index, list] of boxes.entries()) {- const ink = await inkOf(page, clipped, list, dir);+ const ink = await inkOf(page, clipped, list, itemDir);expect(ink, `list ${index}: whole counters`).toEqual(- await inkOf(page, whole, list, dir),+ await inkOf(page, whole, list, itemDir),);for (const {start, end} of ink) {expect(Number.isFinite(start) && Number.isFinite(end)).toBe(true);}const edges = ink.map(({start, end}) =>- dir === 'rtl' ? start : end,+ itemDir === 'rtl' ? start : end,);expect(Math.max(...edges) - Math.min(...edges),@@ -330,6 +338,10 @@ for (const {width, mode} of [page,browser,}, testInfo) => {+ test.fixme(+ dir === 'rtl',+ 'Markdown lays these English items out left to right in a right-to-left page; RichText still lays them out in the page direction, so the surfaces differ until RichText gives each block its own direction.',+ );const errors: string[] = [];page.on('pageerror', error => errors.push(error.message));await page.setViewportSize({width, height: 900});@@ -647,6 +659,10 @@ for (const {name, story, probe, hasTasks} of [test(`${name} nested counter stays whole (${dir})`, async ({page,}, testInfo) => {+ test.fixme(+ dir === 'rtl',+ 'Markdown lays these English items out left to right in a right-to-left page; RichText still lays them out in the page direction, so the surfaces differ until RichText gives each block its own direction.',+ );await page.setViewportSize({width: 1440, height: 900});await page.goto(`${storybook.origin}/iframe.html?id=richtext-richtexteditor--markdown-parity-${story}&viewMode=story&globals=direction:${dir};colorMode:light`,diff --git a/packages/core/src/Markdown/Markdown.tsx b/packages/core/src/Markdown/Markdown.tsxindex dcb462d8e8..4e73469fe9 100644--- a/packages/core/src/Markdown/Markdown.tsx+++ b/packages/core/src/Markdown/Markdown.tsx@@ -65,11 +65,17 @@ import {} from './parser';import type {IncrementalState, MathParseOptions, ParseOptions} from './parser';import {getMarkdownAstLegacyCodeLanguage, markdownAstText} from './ast';+import {+ blockDirection,+ innerDirectionScope,+ type BlockDirectionScope,+} from './blockDirection';import type {MarkdownAstBlockContent,MarkdownAstPhrasingContent,MarkdownAstPosition,MarkdownAstTable,+ MarkdownAstTableAlignment,} from './ast';import {applyMarkdownTransforms,@@ -103,6 +109,7 @@ import {registerEnglishFallback,useComponentTranslator,} from '../i18n/useComponentTranslator';+import {useDirection} from '../i18n/useDirection';import english from '../i18n/generated-english/Markdown/Markdown.generated';registerEnglishFallback(english);@@ -376,6 +383,7 @@ const dynamicStyles = stylex.create({});const cellAlignStyles = stylex.create({+ start: {textAlign: 'start'},center: {textAlign: 'center'},end: {textAlign: 'end'},});@@ -428,6 +436,17 @@ const markdownTableCellStyles = stylex.create({code: {wordBreak: 'normal',},+ // A cell that reads against its table draws the column rule on the table's+ // inline-end side, which is the cell's own inline-start.+ ruleOnTableEnd: {+ borderInlineEndWidth: 0,+ borderInlineStartWidth: {+ default: borderVars['--border-width'],+ ':last-child': '0',+ },+ borderInlineStartStyle: 'solid',+ borderInlineStartColor: colorVars['--color-border'],+ },// The grid's outer edge. `dividers="grid"` draws the lines *between* cells// and stops at the table's rim, so without this the top, bottom, and sides// stay open and the grid reads as unfinished. On the table element, not the@@ -1344,6 +1363,24 @@ function computeTableColumnMinWidths(node: RenderTable): number[] {});}+/**+ * The alignment and column-rule styles for a Markdown table cell. For a cell+ * that reads against its table, the table's start is the cell's end, so an+ * explicit alignment and the rule swap logical sides.+ */+function tableCellSideStyles(+ align: MarkdownAstTableAlignment | undefined,+ isAgainstTable: boolean,+): ReadonlyArray<StyleXStyles | false> {+ return [+ align === 'center' && cellAlignStyles.center,+ align === 'right' &&+ (isAgainstTable ? cellAlignStyles.start : cellAlignStyles.end),+ align === 'left' && isAgainstTable && cellAlignStyles.end,+ isAgainstTable && markdownTableCellStyles.ruleOnTableEnd,+ ];+}+function renderBlock(node: RenderBlockNode,index: number,@@ -1365,6 +1402,7 @@ function renderBlock(headingProjection?: MarkdownHeadingProjection,// How many lists enclose this block (spec:AST-061 DEC-6).listDepth = 0,+ directionScope?: BlockDirectionScope,): SyncReactNode {const blockAlignMargin = BLOCK_ALIGN_MARGIN[contentAlign];const blockAlignStyle =@@ -1415,6 +1453,7 @@ function renderBlock(<Tagkey={index}id={headingId}+ dir={blockDirection(node, directionScope)}{...mergeProps(themeProps('markdown-heading', {density, level}),stylex.props(@@ -1439,6 +1478,7 @@ function renderBlock(return (<HeadingLinksRendererkey={index}+ dir={blockDirection(node, directionScope)}headingId={headingId}headingLabel={headingLabel}permalinkUrl={permalinkUrl}@@ -1501,6 +1541,7 @@ function renderBlock(<divkey={index}role="paragraph"+ dir={blockDirection(node, directionScope)}{...mergeProps(themeProps('markdown-paragraph', {density}),stylex.props(@@ -1660,6 +1701,7 @@ function renderBlock(codeLanguages,headingProjection,listDepth,+ directionScope,),);return (@@ -1671,6 +1713,7 @@ function renderBlock(return (<Blockquotekey={index}+ dir={blockDirection(node, directionScope)}{...themeProps('markdown-blockquote', {density})}{...lineStamps}xstyle={[@@ -1704,6 +1747,7 @@ function renderBlock(codeLanguages,headingProjection,listDepth,+ innerDirectionScope(node, directionScope),),)}</Blockquote>@@ -1735,6 +1779,12 @@ function renderBlock(themeProps('markdown-list', {density}),stylex.props(spacing,+ contentWidthValue != null+ ? dynamicStyles.proseWidth(contentWidthValue)+ : null,+ contentAlign !== 'start'+ ? dynamicStyles.proseAlign(ALIGN_MARGIN[contentAlign])+ : null,isFirst && styles.noMarginBlockStart,isLast && styles.noMarginBlockEnd,),@@ -1790,6 +1840,7 @@ function renderBlock(codeLanguages,headingProjection,listDepth + 1,+ innerDirectionScope(item, directionScope),),)}</>@@ -1801,6 +1852,7 @@ function renderBlock(key={i}value={`task-${i}`}label={label}+ dir={blockDirection(item, directionScope)}{...(recordsSourceLines? sourceLineAttributes(blockSourceLines(item)): undefined)}@@ -1880,6 +1932,7 @@ function renderBlock(codeLanguages,headingProjection,listDepth + 1,+ innerDirectionScope(item, directionScope),),)}</>@@ -1909,6 +1962,16 @@ function renderBlock(: t('@astryx.markdown.taskList'),};+ const itemDirection = blockDirection(item, directionScope);+ // A numbered item that reads against its list keeps its counter+ // beside its own text, so its text never widens the counter+ // column that the other rows share.+ const readsAgainstList =+ node.ordered &&+ itemDirection != null &&+ directionScope != null &&+ itemDirection !== directionScope.around;+return (<ListMarkerScope// eslint-disable-next-line @eslint-react/no-array-index-key -- markdown list items are rendered from positional AST nodes@@ -1919,9 +1982,11 @@ function renderBlock(]}task={task}- hasMarkerGutter={node.ordered}>+ hasMarkerGutter={node.ordered}+ isOutsideNumberColumns={readsAgainstList}><ListItemlabel={label}+ dir={itemDirection}{...(recordsSourceLines? sourceLineAttributes(blockSourceLines(item)): undefined)}@@ -1935,6 +2000,19 @@ function renderBlock(}case 'table': {const colMinWidths = computeTableColumnMinWidths(node);+ // A cell whose text reads against its table keeps the table's sides: the+ // column rule and an explicit alignment resolve in the table's+ // direction, not the cell's.+ const readsAgainstTable = (+ cell: Parameters<typeof blockDirection>[0],+ ): boolean => {+ const cellDirection = blockDirection(cell, directionScope);+ return (+ cellDirection != null &&+ directionScope != null &&+ cellDirection !== directionScope.around+ );+ };const [header, ...rows] = node.children;// Inline code inside a cell keeps its token whole, through the same// `components` seam consumers use. A supplied renderer owns its own@@ -1977,11 +2055,14 @@ function renderBlock(<TableHeaderCell// eslint-disable-next-line @eslint-react/no-array-index-key -- markdown table columns are positional by definitionkey={i}+ dir={blockDirection(h, directionScope)}xstyle={[markdownTableCellStyles.headerCell,dynamicStyles.cellMinWidth(`${colMinWidths[i]}ch`),- node.align[i] === 'center' && cellAlignStyles.center,- node.align[i] === 'right' && cellAlignStyles.end,+ ...tableCellSideStyles(+ node.align[i],+ readsAgainstTable(h),+ ),]}>{h.children.map((c, j) =>renderInline(@@ -2006,10 +2087,13 @@ function renderBlock(<TableCell// eslint-disable-next-line @eslint-react/no-array-index-key -- markdown table cells are positional by row and columnkey={j}+ dir={blockDirection(cell, directionScope)}xstyle={[markdownTableCellStyles.cell,- node.align[j] === 'center' && cellAlignStyles.center,- node.align[j] === 'right' && cellAlignStyles.end,+ ...tableCellSideStyles(+ node.align[j],+ readsAgainstTable(cell),+ ),]}>{cell.children.map((c, k) =>renderInline(@@ -2174,6 +2258,7 @@ export function Markdown<...props}: MarkdownProps<Plugins>): React.ReactElement {const t = useComponentTranslator();+ const direction = useDirection();// Keep one list while it names the same values, so an inline// `codeLanguages={[…]}` does not re-render every block on each parent// render (adjusting state during render, not in an Effect).@@ -2445,6 +2530,8 @@ export function Markdown<t,codeLanguages,headingProjection,+ undefined,+ {provider: direction, around: direction},),);}, [@@ -2466,6 +2553,7 @@ export function Markdown<t,headingProjection,codeLanguages,+ direction,]);if (display === 'inline') {diff --git a/packages/core/src/Markdown/__tests__/MarkdownBlockDirection.a11y.chromium.spec.ts b/packages/core/src/Markdown/__tests__/MarkdownBlockDirection.a11y.chromium.spec.tsnew file mode 100644index 0000000000..74ebf83b31--- /dev/null+++ b/packages/core/src/Markdown/__tests__/MarkdownBlockDirection.a11y.chromium.spec.ts@@ -0,0 +1,346 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y release-only++/**+ * @file MarkdownBlockDirection.a11y.chromium.spec.ts+ * @input Uses the Core/Markdown Default story, given mixed-direction input+ * through its `children` arg, in a left-to-right and a right-to-left page+ * @output Real-Chromium evidence that each prose block lays out in its own+ * text's direction, that a block with no strongly directional character+ * keeps its parent's, that lists, code and tables keep their parent's, and+ * that an item or cell reading against its list or table keeps the list's+ * counter column and the table's column lines and alignment+ * @position Browser evidence that Markdown blocks follow their own text's+ * direction+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const STORYBOOK_DIR = process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR;+const STORY = 'core-markdown--default';++const MIXED = [+ '# English heading',+ '',+ 'An English paragraph that runs long enough to wrap onto a second line at a phone width.',+ '',+ 'פסקה בעברית שמתחילה מימין ונמשכת מספיק כדי לעבור לשורה שנייה ברוחב של טלפון.',+ '',+ 'Short English line.',+ '',+ 'שורה קצרה.',+ '',+ '12345 — 67%',+ '',+ '- First item',+ '- פריט שני',+ ' - nested English item',+ '',+ '> ציטוט בעברית',+ '',+ '```',+ 'const a = 1;',+ '```',+ '',+ '| Name | שם |',+ '| - | - |',+ '| Alice | אליס |',+ '',+ '1. Step one',+ '2. שלב שני',+ '3. Step three',+ '',+ '| Item | Count |',+ '| :--- | ---: |',+ '| Apples | 12 |',+ '| תפוחים | מאה |',+ '',+ '98. Step ninety-eight',+ '99. Step ninety-nine',+ '100. Step one hundred',+ '101. Step one hundred one',+ '',+ '- [ ] English task',+ '- [x] משימה בעברית',+].join('\n');++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(STORYBOOK_DIR);+});++test.afterAll(async () => {+ await storybook?.close();+});++async function renderMixed(page: Page, direction: 'ltr' | 'rtl') {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story&globals=astryxTheme:neutral;colorMode:light;direction:${direction}`,+ {waitUntil: 'load'},+ );+ await expect(page.locator('#storybook-root')).not.toBeEmpty();+ await page.evaluate(+ ({storyId, children}) => {+ const channel = (+ window as Window & {+ __STORYBOOK_ADDONS_CHANNEL__?: {+ emit(event: string, payload: unknown): void;+ };+ }+ ).__STORYBOOK_ADDONS_CHANNEL__;+ channel?.emit('updateStoryArgs', {storyId, updatedArgs: {children}});+ },+ {storyId: STORY, children: MIXED},+ );+ // The Default story's own sample also has a blockquote, so wait for the+ // mixed document's last block, which only the mixed document has.+ await expect(+ page.locator('#storybook-root').getByText('משימה בעברית').first(),+ ).toBeVisible();+}++/**+ * For the block holding `text`: its computed direction, and on which edge its+ * first line starts.+ */+async function measure(page: Page, selector: string, text: string) {+ return page.evaluate(+ ({selector, text}) => {+ const block = Array.from(+ document.querySelectorAll<HTMLElement>(`#storybook-root ${selector}`),+ ).find(element => element.textContent?.includes(text));+ if (block == null) {+ throw new Error(`No ${selector} holds ${text}`);+ }+ const range = document.createRange();+ range.selectNodeContents(block);+ const firstLine = range.getClientRects()[0];+ const box = block.getBoundingClientRect();+ const fromLeft = firstLine.left - box.left;+ const fromRight = box.right - firstLine.right;+ return {+ direction: getComputedStyle(block).direction,+ startsAt: fromLeft <= fromRight ? 'left' : 'right',+ };+ },+ {selector, text},+ );+}++for (const pageDirection of ['ltr', 'rtl'] as const) {+ test.describe(`in a ${pageDirection} page`, () => {+ test('a prose block lays out in its own text direction', async ({page}) => {+ await renderMixed(page, pageDirection);+ const direction = async (selector: string, text: string) =>+ (await measure(page, selector, text)).direction;+ expect(+ await direction('[role="paragraph"]', 'An English paragraph'),+ ).toBe('ltr');+ expect(await direction('[role="paragraph"]', 'פסקה בעברית')).toBe('rtl');+ expect(await direction('h1', 'English heading')).toBe('ltr');+ expect(await direction('blockquote', 'ציטוט')).toBe('rtl');+ expect(await direction('li', 'פריט שני')).toBe('rtl');+ expect(await direction('li', 'First item')).toBe('ltr');+ expect(await direction('td', 'אליס')).toBe('rtl');+ expect(await direction('td', 'Alice')).toBe('ltr');+ });++ test('a short line starts on its own text edge', async ({page}) => {+ await renderMixed(page, pageDirection);+ expect(+ (await measure(page, '[role="paragraph"]', 'Short English line'))+ .startsAt,+ ).toBe('left');+ expect(+ (await measure(page, '[role="paragraph"]', 'שורה קצרה')).startsAt,+ ).toBe('right');+ });++ test('a block with no strongly directional character keeps the page direction', async ({+ page,+ }) => {+ await renderMixed(page, pageDirection);+ expect(+ (await measure(page, '[role="paragraph"]', '12345')).direction,+ ).toBe(pageDirection);+ });++ test('a list, a code block and a table keep the page direction', async ({+ page,+ }) => {+ await renderMixed(page, pageDirection);+ expect((await measure(page, 'ul', 'First item')).direction).toBe(+ pageDirection,+ );+ expect((await measure(page, 'pre', 'const a')).direction).toBe(+ pageDirection,+ );+ expect((await measure(page, 'table', 'Alice')).direction).toBe(+ pageDirection,+ );+ });++ test('a numbered item that reads against its list leaves the counter column alone', async ({+ page,+ }) => {+ await renderMixed(page, pageDirection);+ // How far each item's text starts from the edge its own text starts+ // at. The shared counter column is about 32 px wide at this size.+ const textInset = async (text: string) =>+ page.evaluate(+ ({text}) => {+ const item = Array.from(+ document.querySelectorAll<HTMLElement>('#storybook-root ol li'),+ ).find(element => element.textContent?.includes(text));+ if (item == null) {+ throw new Error(`No numbered item holds ${text}`);+ }+ const walker = document.createTreeWalker(+ item,+ NodeFilter.SHOW_TEXT,+ );+ let node = walker.nextNode();+ while (node != null && !(node.textContent ?? '').includes(text)) {+ node = walker.nextNode();+ }+ if (node == null) {+ throw new Error(`No text node holds ${text}`);+ }+ const range = document.createRange();+ range.selectNodeContents(node);+ const line = range.getClientRects()[0];+ const box = item.getBoundingClientRect();+ return getComputedStyle(item).direction === 'rtl'+ ? box.right - line.right+ : line.left - box.left;+ },+ {text},+ );+ const withList =+ pageDirection === 'ltr' ? ['Step one', 'Step three'] : ['שלב שני'];+ const insets = await Promise.all(withList.map(textInset));+ for (const inset of insets) {+ expect(inset).toBeLessThanOrEqual(40);+ }+ expect(Math.max(...insets) - Math.min(...insets)).toBeLessThanOrEqual(1);+ const against = pageDirection === 'ltr' ? 'שלב שני' : 'Step one';+ expect(await textInset(against)).toBeLessThanOrEqual(40);+ });++ test('a cell that reads against its table keeps the table column line and alignment', async ({+ page,+ }) => {+ await renderMixed(page, pageDirection);+ const cell = async (text: string) =>+ page.evaluate(+ ({text, tableDirection}) => {+ const element = Array.from(+ document.querySelectorAll<HTMLElement>('#storybook-root td'),+ ).find(candidate => candidate.textContent?.trim() === text);+ if (element == null) {+ throw new Error(`No cell holds ${text}`);+ }+ const style = getComputedStyle(element);+ const range = document.createRange();+ range.selectNodeContents(element);+ const line = range.getClientRects()[0];+ const box = element.getBoundingClientRect();+ const toEnd =+ tableDirection === 'ltr'+ ? box.right - parseFloat(style.paddingRight) - line.right+ : line.left - box.left - parseFloat(style.paddingLeft);+ return {+ direction: style.direction,+ ruleOnTableEnd: parseFloat(+ tableDirection === 'ltr'+ ? style.borderRightWidth+ : style.borderLeftWidth,+ ),+ toEnd,+ };+ },+ {text, tableDirection: pageDirection},+ );+ const againstFirst = pageDirection === 'ltr' ? 'תפוחים' : 'Apples';+ const againstAligned = pageDirection === 'ltr' ? 'מאה' : '12';+ const first = await cell(againstFirst);+ expect(first.direction).not.toBe(pageDirection);+ expect(first.ruleOnTableEnd).toBeGreaterThan(0);+ // The Count column is end-aligned: its text touches the table's end.+ const aligned = await cell(againstAligned);+ expect(Math.abs(aligned.toEnd)).toBeLessThanOrEqual(1);+ });++ test('a wide counter does not move its item text', async ({page}) => {+ await renderMixed(page, pageDirection);+ const starts = await page.evaluate(() =>+ ['ninety-eight', 'ninety-nine', 'one hundred', 'one hundred one'].map(+ text => {+ const item = Array.from(+ document.querySelectorAll<HTMLElement>('#storybook-root ol li'),+ ).find(element => element.textContent?.trim().endsWith(text));+ if (item == null) {+ throw new Error(`No numbered item ends with ${text}`);+ }+ const walker = document.createTreeWalker(+ item,+ NodeFilter.SHOW_TEXT,+ );+ let node = walker.nextNode();+ while (node != null && !(node.textContent ?? '').includes(text)) {+ node = walker.nextNode();+ }+ const range = document.createRange();+ range.selectNodeContents(node ?? item);+ return range.getClientRects()[0].left;+ },+ ),+ );+ expect(Math.max(...starts) - Math.min(...starts)).toBeLessThanOrEqual(+ 0.5,+ );+ });++ test('a task item that reads against the page stays in the prose column', async ({+ page,+ }) => {+ await renderMixed(page, pageDirection);+ const fit = await page.evaluate(() => {+ const prose = Array.from(+ document.querySelectorAll<HTMLElement>(+ '#storybook-root [role="paragraph"]',+ ),+ )+ .find(element => element.textContent?.includes('Short English line'))+ ?.getBoundingClientRect();+ if (prose == null) {+ throw new Error('No prose paragraph');+ }+ return ['English task', 'משימה בעברית'].map(text => {+ const label = Array.from(+ document.querySelectorAll<HTMLElement>('#storybook-root li'),+ ).find(element => element.textContent?.includes(text));+ if (label == null) {+ throw new Error(`No task holds ${text}`);+ }+ const walker = document.createTreeWalker(label, NodeFilter.SHOW_TEXT);+ let node = walker.nextNode();+ while (node != null && !(node.textContent ?? '').includes(text)) {+ node = walker.nextNode();+ }+ const range = document.createRange();+ range.selectNodeContents(node ?? label);+ const box = range.getBoundingClientRect();+ return box.left >= prose.left - 1 && box.right <= prose.right + 1;+ });+ });+ expect(fit).toEqual([true, true]);+ });+ });+}diff --git a/packages/core/src/Markdown/blockDirection.test.tsx b/packages/core/src/Markdown/blockDirection.test.tsxnew file mode 100644index 0000000000..d32c780158--- /dev/null+++ b/packages/core/src/Markdown/blockDirection.test.tsx@@ -0,0 +1,212 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {render} from '@testing-library/react';+import {Markdown} from './Markdown';+import {firstStrongDirection} from '../i18n/firstStrongDirection';+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';++function renderIn(dir: 'ltr' | 'rtl', markdown: string) {+ return render(+ <div dir={dir}>+ <Markdown>{markdown}</Markdown>+ </div>,+ );+}++function renderInProvider(dir: 'ltr' | 'rtl', markdown: string) {+ return render(+ <InternationalizationProvider locale="en" dir={dir}>+ <Markdown>{markdown}</Markdown>+ </InternationalizationProvider>,+ );+}++function blockContaining(+ container: HTMLElement,+ selector: string,+ text: string,+) {+ const match = Array.from(+ container.querySelectorAll<HTMLElement>(selector),+ ).find(element => element.textContent?.includes(text));+ if (match == null) {+ throw new Error(`No ${selector} contains "${text}"`);+ }+ return match;+}++describe('firstStrongDirection', () => {+ it('reads the first strongly directional character', () => {+ expect(firstStrongDirection('Hello שלום')).toBe('ltr');+ expect(firstStrongDirection('שלום Hello')).toBe('rtl');+ expect(firstStrongDirection('مرحبا')).toBe('rtl');+ });++ it('skips digits, punctuation, symbols and combining marks', () => {+ expect(firstStrongDirection('123 — מזל טוב')).toBe('rtl');+ expect(firstStrongDirection('🎉 مرحبا')).toBe('rtl');+ expect(firstStrongDirection('۱۴۰۳ Annual report')).toBe('ltr');+ expect(firstStrongDirection('\u05B0Annual report')).toBe('ltr');+ });++ it('is null for text with no strongly directional character', () => {+ expect(firstStrongDirection('')).toBeNull();+ expect(firstStrongDirection('42 — 7%')).toBeNull();+ });+});++describe('Markdown block direction', () => {+ it('lays a Hebrew paragraph out right to left in a left-to-right page', () => {+ const {container} = renderIn(+ 'ltr',+ 'English first.\n\nשלום עולם, זו פסקה.',+ );+ expect(+ blockContaining(container, '[role="paragraph"]', 'שלום').getAttribute(+ 'dir',+ ),+ ).toBe('rtl');+ expect(+ blockContaining(container, '[role="paragraph"]', 'English').getAttribute(+ 'dir',+ ),+ ).toBe('ltr');+ });++ it('lays an English paragraph out left to right in a right-to-left page', () => {+ const {container} = renderIn('rtl', 'שלום עולם.\n\nAn English paragraph.');+ expect(+ blockContaining(container, '[role="paragraph"]', 'English').getAttribute(+ 'dir',+ ),+ ).toBe('ltr');+ expect(+ blockContaining(container, '[role="paragraph"]', 'שלום').getAttribute(+ 'dir',+ ),+ ).toBe('rtl');+ });++ it('gives a heading its own direction', () => {+ const {container} = renderIn('ltr', '# כותרת ראשית');+ expect(container.querySelector('h1')?.getAttribute('dir')).toBe('rtl');+ });++ it('gives each list item and a blockquote their own direction, and none to the list', () => {+ const {container} = renderIn(+ 'ltr',+ '- First item\n- פריט שני\n\n> ציטוט בעברית',+ );+ expect(blockContaining(container, 'li', 'First').getAttribute('dir')).toBe(+ 'ltr',+ );+ expect(blockContaining(container, 'li', 'פריט').getAttribute('dir')).toBe(+ 'rtl',+ );+ expect(container.querySelector('ul')?.hasAttribute('dir')).toBe(false);+ expect(container.querySelector('blockquote')?.getAttribute('dir')).toBe(+ 'rtl',+ );+ });++ it('gives a block with no strongly directional character no direction of its own', () => {+ const {container} = renderIn(+ 'rtl',+ '12345 — 67%\n\n',+ );+ expect(+ blockContaining(container, '[role="paragraph"]', '12345').hasAttribute(+ 'dir',+ ),+ ).toBe(false);+ expect(+ container.querySelector('img')?.closest('[dir]')?.getAttribute('dir'),+ ).not.toBe('ltr');+ });++ it('gives a table cell the direction of its own text, and none to the table', () => {+ const {container} = renderIn(+ 'ltr',+ '| Name | שם |\n| - | - |\n| Alice | אליס |\n| 42 | — |',+ );+ expect(blockContaining(container, 'th', 'Name').getAttribute('dir')).toBe(+ 'ltr',+ );+ expect(blockContaining(container, 'th', 'שם').getAttribute('dir')).toBe(+ 'rtl',+ );+ expect(blockContaining(container, 'td', 'אליס').getAttribute('dir')).toBe(+ 'rtl',+ );+ expect(blockContaining(container, 'td', '42').hasAttribute('dir')).toBe(+ false,+ );+ expect(container.querySelector('table')?.hasAttribute('dir')).toBe(false);+ });++ it('gives a code block and a table no direction of their own', () => {+ const {container} = renderIn(+ 'rtl',+ '```\nconst a = 1;\n```\n\n| A | B |\n| - | - |\n| one | two |',+ );+ expect(+ container.querySelector('pre')?.closest('[dir]')?.getAttribute('dir'),+ ).not.toBe('ltr');+ expect(+ container.querySelector('table')?.closest('[dir]')?.getAttribute('dir'),+ ).not.toBe('ltr');+ });++ it('gives a neutral paragraph inside a Hebrew list item the provider direction', () => {+ const {container} = renderInProvider(+ 'ltr',+ '- פריט ראשון\n\n 2026\n- Second item',+ );+ expect(blockContaining(container, 'li', 'פריט').getAttribute('dir')).toBe(+ 'rtl',+ );+ expect(+ blockContaining(container, '[role="paragraph"]', '2026').getAttribute(+ 'dir',+ ),+ ).toBe('ltr');+ });++ it('gives a neutral paragraph inside an English quote the provider direction', () => {+ const {container} = renderInProvider(+ 'rtl',+ '> An English quote.\n>\n> 42 — 7%',+ );+ expect(container.querySelector('blockquote')?.getAttribute('dir')).toBe(+ 'ltr',+ );+ expect(+ blockContaining(container, '[role="paragraph"]', '42').getAttribute(+ 'dir',+ ),+ ).toBe('rtl');+ });++ it('gives a neutral cell in a table under a Hebrew item the provider direction', () => {+ const {container} = renderInProvider(+ 'ltr',+ '- פריט עם טבלה\n\n | שם | 2026 |\n | - | - |\n | אליס | 42 |',+ );+ expect(blockContaining(container, 'td', 'אליס').getAttribute('dir')).toBe(+ 'rtl',+ );+ expect(blockContaining(container, 'td', '42').getAttribute('dir')).toBe(+ 'ltr',+ );+ });++ it('leaves a neutral block with no attribute where the block around it already reads the provider direction', () => {+ const {container} = renderInProvider('ltr', '- English item\n\n 2026');+ expect(+ blockContaining(container, '[role="paragraph"]', '2026').hasAttribute(+ 'dir',+ ),+ ).toBe(false);+ });+});diff --git a/packages/core/src/Markdown/blockDirection.ts b/packages/core/src/Markdown/blockDirection.tsnew file mode 100644index 0000000000..28102071e1--- /dev/null+++ b/packages/core/src/Markdown/blockDirection.ts@@ -0,0 +1,100 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file blockDirection.ts+ * @input A Markdown AST prose block (a paragraph, heading, blockquote or list+ * item) or a table cell+ * @output The `dir` for the block: its own text's direction, or the+ * provider's for a block whose text has no strongly directional character+ * @position Read by Markdown.tsx to set each block's `dir`.+ */++import {firstStrongDirection} from '../i18n/firstStrongDirection';++interface DirectionalNode {+ readonly type: string;+ readonly value?: unknown;+ readonly children?: ReadonlyArray<DirectionalNode>;+}++/**+ * Nodes whose text does not count. An image, a code block, math and a table+ * read on their own terms. An extension node or a citation shows text that is+ * not in the tree.+ */+const SKIPPED_TYPES = new Set([+ 'image',+ 'code',+ 'math',+ 'inlineMath',+ 'table',+ 'thematicBreak',+ 'citation',+ 'break',+ 'extension',+]);++function nodeDirection(node: DirectionalNode): 'ltr' | 'rtl' | null {+ if (SKIPPED_TYPES.has(node.type)) {+ return null;+ }+ if (typeof node.value === 'string') {+ return firstStrongDirection(node.value);+ }+ for (const child of node.children ?? []) {+ const direction = nodeDirection(child);+ if (direction != null) {+ return direction;+ }+ }+ return null;+}++/**+ * The direction of a prose block's own text. A list item and a blockquote read+ * everything under them, nested lists included, so a nested step resolves+ * against the item that holds it.+ */+export function markdownBlockDirection(+ node: DirectionalNode,+): 'ltr' | 'rtl' | undefined {+ return nodeDirection(node) ?? undefined;+}++/** The provider's direction, and the direction of the block around this one. */+export interface BlockDirectionScope {+ readonly provider: 'ltr' | 'rtl';+ readonly around: 'ltr' | 'rtl';+}++/**+ * The `dir` for a prose block or a table cell. A block with no direction of+ * its own takes the provider's. It needs the attribute only where the block+ * around it reads the other way; elsewhere it inherits the same direction.+ */+export function blockDirection(+ node: DirectionalNode,+ scope: BlockDirectionScope | undefined,+): 'ltr' | 'rtl' | undefined {+ const own = markdownBlockDirection(node);+ if (own != null) {+ return own;+ }+ return scope != null && scope.around !== scope.provider+ ? scope.provider+ : undefined;+}++/** The scope for the blocks inside a quote or a list item. */+export function innerDirectionScope(+ node: DirectionalNode,+ scope: BlockDirectionScope | undefined,+): BlockDirectionScope | undefined {+ if (scope == null) {+ return undefined;+ }+ return {+ provider: scope.provider,+ around: markdownBlockDirection(node) ?? scope.provider,+ };+}diff --git a/packages/core/src/Markdown/plugins/HeadingLinksRenderer.tsx b/packages/core/src/Markdown/plugins/HeadingLinksRenderer.tsxindex fa5a1bc768..6cd69f2a5c 100644--- a/packages/core/src/Markdown/plugins/HeadingLinksRenderer.tsx+++ b/packages/core/src/Markdown/plugins/HeadingLinksRenderer.tsx@@ -113,6 +113,8 @@ interface HeadingLinksRendererProps {readonly contentAlign: 'start' | 'center';readonly headingTextStyle: StyleXStyles;readonly blockSpacingStyle: StyleXStyles;+ /** The heading's own direction; the copy control follows its inline end. */+ readonly dir?: 'ltr' | 'rtl';}function isUnmodifiedPrimaryActivation(@@ -137,6 +139,7 @@ export function HeadingLinksRenderer({contentAlign,headingTextStyle,blockSpacingStyle,+ dir,}: HeadingLinksRendererProps): ReactElement {const t = useComponentTranslator();const copiedLabel = t('@astryx.markdownHeadingLinks.copied');@@ -163,6 +166,7 @@ export function HeadingLinksRenderer({return (<div+ dir={dir}{...mergeProps(getContainerProps(),stylex.props(diff --git a/packages/core/src/i18n/firstStrongDirection.ts b/packages/core/src/i18n/firstStrongDirection.tsnew file mode 100644index 0000000000..998d55e1e1--- /dev/null+++ b/packages/core/src/i18n/firstStrongDirection.ts@@ -0,0 +1,69 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file firstStrongDirection.ts+ * @input A string of text+ * @output 'ltr' | 'rtl' | null — the direction of the text's first strongly+ * directional character, or null when it has none+ * @position Shared classifier for components that give a block of prose the+ * direction of its own text (Markdown blocks). Server-safe: it reads no+ * context.+ */++// Each expression with a Unicode property escape is built at runtime: a+// source build may rewrite a regular expression literal with one, and the+// Babel copy that Next.js bundles has no Unicode data to do that.++/**+ * The strongly right-to-left characters of the Unicode Bidirectional+ * Algorithm: Bidi_Class `R` and `AL`. The living scripts are named. The two+ * ranges cover the historic right-to-left scripts in the Supplementary+ * Multilingual Plane, which have no script escapes that every engine knows.+ */+const STRONG_RTL = new RegExp(+ String.raw`[\p{Script=Adlam}\p{Script=Arabic}\p{Script=Hebrew}\p{Script=Mandaic}\p{Script=Nko}\p{Script=Samaritan}\p{Script=Syriac}\p{Script=Thaana}\u200F\u061C\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]`,+ 'u',+);++/**+ * The weak characters of the Arabic script: its digits, the number signs+ * before them, and the currency and per-cent marks beside them. They are+ * Bidi_Class `AN`, `EN` or `ET`, so the scan skips them. NKo and Adlam digits+ * are Bidi_Class `R` and are not here.+ */+const WEAK_ARABIC_NUMBER =+ /[\u0600-\u0605\u0609\u060A\u0660-\u0669\u066A-\u066C\u06DD\u06F0-\u06F9\u0890\u0891\u08E2]/u;++/**+ * Bidi_Class `L`: every other letter, the letter numbers (`\p{Letter}` does+ * not include them), and the left-to-right mark. Digits, punctuation and+ * symbols are not here, so the scan skips them.+ */+const STRONG_LTR = new RegExp(String.raw`[\p{Letter}\p{Nl}\u200E]`, 'u');++/**+ * Bidi_Class `NSM`: a combining mark takes the direction of its base+ * character. A mark has its base letter's script, so without this check a+ * leading Hebrew point would read as right-to-left.+ */+const COMBINING_MARK = new RegExp(String.raw`\p{Mark}`, 'u');++/**+ * Rules P2 and P3 of the Unicode Bidirectional Algorithm: the direction of+ * the first strongly directional character, or null when there is none. The+ * loop reads whole code points, so a surrogate pair counts as one character.+ */+export function firstStrongDirection(text: string): 'ltr' | 'rtl' | null {+ for (const character of text) {+ if (COMBINING_MARK.test(character) || WEAK_ARABIC_NUMBER.test(character)) {+ continue;+ }+ if (STRONG_RTL.test(character)) {+ return 'rtl';+ }+ if (STRONG_LTR.test(character)) {+ return 'ltr';+ }+ }+ return null;+}diff --git a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.tsindex 2da4d9bcff..d51b13c685 100644--- a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts+++ b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts@@ -1931,10 +1931,13 @@ for (const [viewport, colorMode] of [});}-// spec:AST-061 FR6: every block takes the direction of the surface around-// it, whatever its first strong character, on both surfaces.+// RichText blocks take the direction of the surface around them, whatever+// their first strong character. Markdown blocks take the direction of their+// own text, and the provider's when their text has no strong character.for (const direction of ['ltr', 'rtl'] as const) {- test(`blocks take the provider direction (${direction})`, async ({page}) => {+ test(`blocks take their surface's direction rule (${direction})`, async ({+ page,+ }) => {const errors = await openStory(page,STORY.sideBySide,@@ -1944,24 +1947,43 @@ for (const direction of ['ltr', 'rtl'] as const) {await waitForDocument(page, MARKDOWN);await waitForDocument(page, RICH_TEXT);for (const surface of [MARKDOWN, RICH_TEXT]) {- const geometry = await surfaceGeometry(page, surface);- const otherDirection = geometry.blocks- .filter(block => block.direction !== direction)- .map(block => block.key);- expect(otherDirection, surface).toEqual([]);- // Inside blocks too: table rows and cells, list items, and paragraphs.- const nested = await page.evaluate(- ({selector, expected}) =>- [+ const ownText = surface === MARKDOWN;+ // RichText: every block, and inside blocks too: table rows and cells,+ // list items, and paragraphs. Markdown: every prose block and table+ // cell, read against its own text; a container or wrapper is not+ // checked, because it takes its parent's direction.+ const mismatched = await page.evaluate(+ ({selector, provider, isOwnText}) => {+ const strong =+ /[A-Za-z\u00C0-\u024F\u0370-\u03FF\u0400-\u04FF\u3040-\u9FFF\uAC00-\uD7AF]|([\u0590-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF])/u;+ const expectedFor = (element: Element): string => {+ if (!isOwnText) {+ return provider;+ }+ const match = strong.exec(element.textContent ?? '');+ return match == null ? provider : match[1] != null ? 'rtl' : 'ltr';+ };+ const targets = isOwnText+ ? ':is([role="paragraph"], p, h1, h2, h3, h4, h5, h6, blockquote, li, th, td)'+ : ':is([data-parity-block], tr, th, td, li, p)';+ return [...document.querySelectorAll(- `${selector} [data-parity-body] :is(tr, th, td, li, p)`,+ `${selector} [data-parity-body] ${targets}`,),]- .filter(element => getComputedStyle(element).direction !== expected)- .map(element => element.tagName),- {selector: surface, expected: direction},+ .filter(+ element =>+ getComputedStyle(element).direction !== expectedFor(element),+ )+ .map(+ element =>+ (element as HTMLElement).dataset.parityBlock ??+ `${element.tagName} ${(element.textContent ?? '').slice(0, 24)}`,+ );+ },+ {selector: surface, provider: direction, isOwnText: ownText},);- expect(nested, `${surface} nested`).toEqual([]);+ expect(mismatched, surface).toEqual([]);}expect(errors).toEqual([]);});diff --git a/packages/richtext/src/editorTheme.ts b/packages/richtext/src/editorTheme.tsindex e9d8ce2831..933f0c6dc2 100644--- a/packages/richtext/src/editorTheme.ts+++ b/packages/richtext/src/editorTheme.ts@@ -62,9 +62,10 @@ const editorTheme = stylex.create({// Lexical marks every top-level block `dir="auto"`, which picks each// block's direction from its first strong character: a Hebrew paragraph in// an English document flips to the right, an English one in an Arabic- // document to the left. Blocks take the direction of the surface around- // them instead, as core Markdown's do, and bidi inside a block still- // follows the Unicode algorithm (spec:AST-061 FR6).+ // document to the left. Here blocks take the direction of the surface+ // around them, and bidi inside a block still follows the Unicode+ // algorithm. Core Markdown differs: it gives each block the direction of+ // its own text.providerDirection: {direction: 'inherit',},