An open source design system that's fully customizable and agent ready
TypeScript
fix(Layer): keep decorator portals outside renderer-managed DOM (#7633)
freddymeta1c8292c42fa7
diff --git a/.changeset/add-explicit-local-portal-hosts-for-renderer-int-p0sz.md b/.changeset/add-explicit-local-portal-hosts-for-renderer-int-p0sz.mdnew file mode 100644index 0000000000..3d8ebbf7e0--- /dev/null+++ b/.changeset/add-explicit-local-portal-hosts-for-renderer-int-p0sz.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+'@astryxdesign/richtext': patch+---++[fix] Declare renderer-owned DOM boundaries so decorator overlays mount outside managed content without changing safe inline hosting. RichTextEditor also mirrors its `dir` prop onto the wrapper around the editable surface, so the editing surface and its content blocks, the placeholder, UI rendered through `plugins`, and relocated overlays follow `dir`; the editing surface previously kept the surrounding direction.+@freddymetadiff --git a/.github/scripts/story-play-guard.js b/.github/scripts/story-play-guard.jsindex 17883bc7c3..dec6b08451 100644--- a/.github/scripts/story-play-guard.js+++ b/.github/scripts/story-play-guard.js@@ -44,6 +44,28 @@ const TARGETS = [guards:'under align="first-line" every start and end slot centers on the label\'s first line (wrapped, clamped, dense, spacious, avatar, interactive, RTL, ListItem, RadioListItem) and never rises into the row padding',},+ {+ component: 'Tooltip',+ story: 'core-tooltip--decorator-unmount',+ guards:+ 'decorator tooltip survives reconciliation and cleans up on deselection',+ },+ {+ component: 'Tooltip',+ story: 'core-tooltip--decorator-read-only-unmount',+ guards:+ 'read-only decorator tooltip survives reconciliation and editor unmount',+ },+ {+ component: 'Layer',+ story: 'core-layer--boundary-nested-focus-guard',+ guards: 'nested decorator popup remains inside its parent focus owner',+ },+ {+ component: 'Layer',+ story: 'core-layer--boundary-live-direction-guard',+ guards: 'editor overlay direction follows live prop changes',+ },{component: 'Selector',story: 'core-selector--size-variants',diff --git a/apps/storybook/stories/LayerBoundaryProbe.stories.tsx b/apps/storybook/stories/LayerBoundaryProbe.stories.tsxnew file mode 100644index 0000000000..f3fab9ebb5--- /dev/null+++ b/apps/storybook/stories/LayerBoundaryProbe.stories.tsx@@ -0,0 +1,146 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @input Real block DecoratorNode inside RichTextEditor, Popover and Tooltip.+ * @output Browser fixtures for owned popup containment and live editor direction.+ * @position Core Layer integration regression stories.+ */+import {useState, type ReactNode} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {expect, userEvent, waitFor, within} from 'storybook/test';+import {DecoratorNode, type NodeKey} from 'lexical';+import {RichTextEditor} from '@astryxdesign/richtext';+import {Popover} from '@astryxdesign/core/Popover';+import {Tooltip} from '@astryxdesign/core/Tooltip';+import {Button} from '@astryxdesign/core/Button';++class BoundaryControlsNode extends DecoratorNode<ReactNode> {+ static getType() {+ return 'boundary-controls';+ }+ static clone(node: BoundaryControlsNode) {+ return new BoundaryControlsNode(node.__key);+ }+ constructor(key?: NodeKey) {+ super(key);+ }+ static importJSON() {+ return new BoundaryControlsNode();+ }+ isInline() {+ return false;+ }+ createDOM() {+ const element = document.createElement('div');+ element.contentEditable = 'false';+ return element;+ }+ updateDOM() {+ return false;+ }+ decorate() {+ return (+ <>+ <Popover+ label="Outer"+ content={+ <span>+ <Popover+ label="Inner"+ content={+ <>+ <Button label="Inner first" />+ <Button label="Inner second" />+ </>+ }>+ <Button label="Open inner" />+ </Popover>+ </span>+ }>+ <Button label="Open outer" />+ </Popover>+ <span>+ <Tooltip content="Direction hint" isOpen>+ <Button label="Direction trigger" />+ </Tooltip>+ </span>+ </>+ );+ }+}+const nodes = [BoundaryControlsNode];+const INITIAL_CONTROLS = JSON.stringify({+ root: {+ type: 'root',+ version: 1,+ direction: null,+ format: '',+ indent: 0,+ children: [{type: 'boundary-controls', version: 1}],+ },+});+const meta: Meta = {title: 'Core/Layer', tags: ['no-visual']};+export default meta;+export const BoundaryNestedFocus: StoryObj = {+ render: () => (+ <RichTextEditor+ label="Popup editor"+ nodes={nodes}+ defaultValue={INITIAL_CONTROLS}+ />+ ),+};+function DirectionProbe() {+ const [direction, setDirection] = useState('rtl');+ return (+ <>+ <Button label="Change direction" onClick={() => setDirection('ltr')} />+ <RichTextEditor+ label="Direction editor"+ nodes={nodes}+ defaultValue={INITIAL_CONTROLS}+ dir={direction}+ />+ </>+ );+}+export const BoundaryLiveDirection: StoryObj = {+ render: () => <DirectionProbe />,+};++export const BoundaryNestedFocusGuard: StoryObj = {+ ...BoundaryNestedFocus,+ play: async ({canvasElement}) => {+ const canvas = within(canvasElement);+ await userEvent.click(+ await canvas.findByRole('button', {name: 'Open outer'}),+ );+ await userEvent.click(+ await canvas.findByRole('button', {name: 'Open inner'}),+ );+ await waitFor(() => {+ const outer = canvas.getByRole('dialog', {name: 'Outer'});+ const inner = canvas.getByRole('dialog', {name: 'Inner'});+ expect(outer).toContainElement(inner);+ });+ },+};++export const BoundaryLiveDirectionGuard: StoryObj = {+ ...BoundaryLiveDirection,+ play: async ({canvasElement}) => {+ const canvas = within(canvasElement);+ const tooltip = await canvas.findByRole('tooltip', {+ name: 'Direction hint',+ });+ await waitFor(() =>+ expect(getComputedStyle(tooltip).direction).toBe('rtl'),+ );+ await userEvent.click(+ canvas.getByRole('button', {name: 'Change direction'}),+ );+ await waitFor(() =>+ expect(getComputedStyle(tooltip).direction).toBe('ltr'),+ );+ },+};diff --git a/apps/storybook/stories/TooltipDecorator.stories.tsx b/apps/storybook/stories/TooltipDecorator.stories.tsxnew file mode 100644index 0000000000..09d77f6807--- /dev/null+++ b/apps/storybook/stories/TooltipDecorator.stories.tsx@@ -0,0 +1,249 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TooltipDecorator.stories.tsx+ * @input Real Lexical decorator selection, an explicit managed-root boundary, and Astryx Button tooltips.+ * @output A selectable image whose controls mount and unmount inside an editor.+ * @position Browser regression fixture for TooltipDecorator.a11y.browser.spec.ts.+ */++import {useState, type ReactNode} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {expect, userEvent, waitFor, within} from 'storybook/test';+import {LexicalComposer} from '@lexical/react/LexicalComposer';+import {RichTextPlugin} from '@lexical/react/LexicalRichTextPlugin';+import {ContentEditable} from '@lexical/react/LexicalContentEditable';+import {LexicalErrorBoundary} from '@lexical/react/LexicalErrorBoundary';+import {useLexicalNodeSelection} from '@lexical/react/useLexicalNodeSelection';+import {DecoratorNode, type NodeKey, type SerializedLexicalNode} from 'lexical';+import {Button} from '@astryxdesign/core/Button';+import {VStack, HStack} from '@astryxdesign/core/Layout';+import {Text} from '@astryxdesign/core/Text';+import {RichTextEditor} from '@astryxdesign/richtext';++const IMAGE = `data:image/svg+xml,${encodeURIComponent(+ '<svg xmlns="http://www.w3.org/2000/svg" width="240" height="120" viewBox="0 0 240 120"><rect width="240" height="120" fill="silver"/><path d="M0 120 80 30 140 90 180 50 240 120" fill="gray"/></svg>',+)}`;++function ImageControls({nodeKey}: {nodeKey: NodeKey}) {+ const [isSelected, setSelected, clearSelection] =+ useLexicalNodeSelection(nodeKey);+ return (+ <span>+ <img+ src={IMAGE}+ alt="Selectable landscape"+ width={240}+ height={120}+ onClick={() => {+ clearSelection();+ setSelected(true);+ }}+ />+ {isSelected && (+ <span>+ <Button label="Smaller" size="sm" tooltip="Narrow it" />+ <Button label="Larger" size="sm" tooltip="Widen it" />+ </span>+ )}+ </span>+ );+}++class ImageNode extends DecoratorNode<ReactNode> {+ static getType() {+ return 'tooltip-image';+ }++ static clone(node: ImageNode) {+ return new ImageNode(node.__key);+ }++ constructor(key?: NodeKey) {+ super(key);+ }++ createDOM() {+ const element = document.createElement('span');+ element.contentEditable = 'false';+ return element;+ }++ updateDOM() {+ return false;+ }++ static importJSON() {+ return new ImageNode();+ }++ exportJSON(): SerializedLexicalNode {+ return {...super.exportJSON(), type: 'tooltip-image', version: 1};+ }++ decorate() {+ return <ImageControls nodeKey={this.getKey()} />;+ }+}++const INITIAL_DOCUMENT = JSON.stringify({+ root: {+ type: 'root',+ version: 1,+ direction: null,+ format: '',+ indent: 0,+ children: [+ {+ type: 'paragraph',+ version: 1,+ direction: null,+ format: '',+ indent: 0,+ children: [+ {+ type: 'text',+ version: 1,+ text: 'Click this text to deselect the image.',+ detail: 0,+ format: 0,+ mode: 'normal',+ style: '',+ },+ ],+ },+ {+ type: 'paragraph',+ version: 1,+ direction: null,+ format: '',+ indent: 0,+ children: [{type: 'tooltip-image', version: 1}],+ },+ ],+ },+});++function TooltipDecoratorFixture({+ isReadOnly = false,+ useRichText = false,+}: {+ isReadOnly?: boolean;+ useRichText?: boolean;+}) {+ const [isMounted, setMounted] = useState(true);+ return (+ <VStack gap={4}>+ <Text>+ Select the image, hover a control, then click the editor text.+ </Text>+ <HStack gap={2}>+ <Button label="Toggle editor" onClick={() => setMounted(!isMounted)} />+ <Button label="Outside control" tooltip="Outside the editor" />+ </HStack>+ {isMounted &&+ (useRichText ? (+ <RichTextEditor+ label="Image editor"+ nodes={[ImageNode]}+ defaultValue={INITIAL_DOCUMENT}+ isReadOnly={isReadOnly}+ />+ ) : (+ <LexicalComposer+ initialConfig={{+ namespace: 'TooltipDecorator',+ editable: !isReadOnly,+ nodes: [ImageNode],+ onError: error => {+ throw error;+ },+ editorState: INITIAL_DOCUMENT,+ }}>+ <section>+ <RichTextPlugin+ contentEditable={+ <ContentEditable+ data-astryx-layer-portal-boundary="external"+ aria-label="Image editor"+ />+ }+ placeholder={null}+ ErrorBoundary={LexicalErrorBoundary}+ />+ </section>+ </LexicalComposer>+ ))}+ </VStack>+ );+}++const meta: Meta = {+ title: 'Core/Tooltip',+ tags: ['no-visual'],+ parameters: {+ docs: {+ description: {+ component:+ 'Select the image to mount its tooltipped controls, then click the text or toggle the editor off. The browser regression tests drive this real Lexical composition.',+ },+ },+ },+};+export default meta;++async function verifyDecoratorUnmount(+ canvasElement: HTMLElement,+ isReadOnly: boolean,+) {+ const canvas = within(canvasElement);+ await userEvent.click(+ await canvas.findByRole('img', {name: 'Selectable landscape'}),+ );+ const control = await canvas.findByRole('button', {name: 'Smaller'});+ const id = control.getAttribute('aria-describedby');+ await waitFor(() => expect(id && document.getElementById(id)).toBeTruthy());+ await userEvent.hover(control);+ await waitFor(() =>+ expect(document.getElementById(id ?? '')?.matches(':popover-open')).toBe(+ true,+ ),+ );+ await userEvent.click(+ isReadOnly+ ? canvas.getByRole('button', {name: 'Toggle editor'})+ : canvas.getByText('Click this text to deselect the image.', {+ exact: true,+ }),+ );+ await waitFor(() => {+ expect(canvas.queryByRole('button', {name: 'Smaller'})).toBeNull();+ expect(document.getElementById(id ?? '')).toBeNull();+ });+}++export const DecoratorSelection: StoryObj = {+ render: () => <TooltipDecoratorFixture />,+};++export const DecoratorReadOnly: StoryObj = {+ render: () => <TooltipDecoratorFixture isReadOnly />,+};++export const IntegratedEditor: StoryObj = {+ render: () => <TooltipDecoratorFixture useRichText />,+};++export const IntegratedReadOnly: StoryObj = {+ render: () => <TooltipDecoratorFixture useRichText isReadOnly />,+};++export const DecoratorUnmount: StoryObj = {+ render: () => <TooltipDecoratorFixture />,+ play: ({canvasElement}) => verifyDecoratorUnmount(canvasElement, false),+};++export const DecoratorReadOnlyUnmount: StoryObj = {+ render: () => <TooltipDecoratorFixture isReadOnly />,+ play: ({canvasElement}) => verifyDecoratorUnmount(canvasElement, true),+};diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.mdindex a61af7c5a2..17dfb41865 100644--- a/docs/architecture/layer-runtime.md+++ b/docs/architecture/layer-runtime.md@@ -493,10 +493,20 @@ layers use Layer rendering without joining Escape/platform dismissal.## Boundaries and invariants- **INV1 — Corrective portals preserve locality.** A context layer stays inline- when safe and otherwise moves only outside the outermost unsafe ancestor.+ when safe and otherwise moves only outside the outermost unsafe ancestor+ (see INV19 for renderer-managed DOM).- **INV2 — Hosting and promotion are separate.** A React portal moves DOM. NativePopover or modal Dialog APIs control top-layer participation and modalboundaries.+- **INV19 — A renderer never reconciles a layer's nodes.** A layer whose host+ sits inside DOM a renderer manages (a declared managed root, such as+ RichTextEditor's editable area) portals its surface outside that root, so the+ renderer's reconciliation never meets foreign nodes; a layer nested in+ another layer stays in that layer's root, which the renderer does not+ reconcile, even when that root sits inside the managed root; an inline layer+ that is safe in place never moves; the moved wrapper mirrors the host's+ `dir`. The managed-root declaration is internal: not exported, not a prop.+ (Owner decision, Nov 6 2026 (Cindy).)- **INV3 — Positioning modes do not leak.** Anchor mode owns logical placement,fallbacks, and the viewport inset; custom mode owns its geometry; fixed modeowns explicit coordinates.@@ -819,6 +829,7 @@ this current architecture record.| Invariant | Evidence | Failure signal || ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || INV1, INV2 | `useLayer.test.tsx` and `layerHost.test.ts` | Invalid DOM, stale host, lost theme/writing context, or portal mistaken for top-layer promotion |+| INV19 | `layerPortalBoundary.test.ts`, `RichTextEditor.portalHost.test.tsx`, and `LayerBoundary.a11y.browser.spec.ts`, `TooltipDecorator.a11y.browser.spec.ts` and `DecoratorPortal.a11y.browser.spec.ts` in Chromium and WebKit | A corrected layer whose host is inside an editor-managed root, and that has no nearer layer root, rendered inside that root; a nested layer moved out of its parent layer's root; a layer that is safe inline moved; a moved wrapper whose `dir` differs from its host's || INV3–INV5 | `useLayer.test.tsx` and `anchorName.test.ts` | A mode leaks geometry, RTL resolves from the wrong context, fallback clips, or a sibling anchor is lost || INV11 | `layerViewportInset.test.ts`, `useLayer.test.tsx`, and the `Core/Layer` viewport-inset stories under the story play guard at a desktop and a phone viewport; `BaseTypeahead.incremental.test.tsx` and the Typeahead incremental-results stories for the `spec:AST-092` FR6 exception | A second gutter definition, a `100%`-of-span cap, a layer narrower than its explicit size, a layer box wider than the viewport, a layer inside the gutter, or a layer that slides toward an off-screen anchor; for an open Typeahead popup, a later list for the same query that flips it to the other side or grows it past the room on its side, or a first list for a query that is capped to the span beside the trigger || INV12 | The `Core/Layer` viewport-inset stories' first-frame comparison, and `useLayer.test.tsx`'s synchronous anchor read; for the check after a scroll stops, `useLayer.test.tsx`'s `scrollend` and 150 ms fallback cases (one check, in the first painted frame after the stop, with no read in the scroll handler) and the Tooltip suites' scroll-edge cases; a Chromium trace at 4× CPU of a wheel scroll that carries a Tooltip's trigger to the scroll edge counts the forced layouts per scroll before and after DEC-8: page scroll 27–42 → 5, a scrolling panel 7 → 5, the Slider value bubble 12–22 → 5 | A layer whose first painted rectangle differs from its settled one; a box check, a re-pick or a forced layout for a layer in a scroll frame or a scroll handler; a re-pick before the first painted frame after a scroll stops, or more than one per stop; a painted frame that shows a layer that keeps its anchor clear over its anchor |diff --git a/packages/core/src/Layer/LayerBoundary.a11y.browser.spec.ts b/packages/core/src/Layer/LayerBoundary.a11y.browser.spec.tsnew file mode 100644index 0000000000..d9ccc95bae--- /dev/null+++ b/packages/core/src/Layer/LayerBoundary.a11y.browser.spec.ts@@ -0,0 +1,46 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+import {expect, test} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';+let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});+test('nested popup retains keyboard focus inside its parent', async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-layer--boundary-nested-focus&viewMode=story`,+ );+ await page.getByRole('button', {name: 'Open outer', exact: true}).click();+ await page.getByRole('button', {name: 'Open inner', exact: true}).click();+ await expect(page.getByRole('button', {name: 'Inner first'})).toBeFocused();+ await page.keyboard.press('Tab');+ await expect(page.getByRole('button', {name: 'Inner second'})).toBeFocused();+});+test('safe writing scope continues to inherit direction changes', async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-layer--boundary-live-direction&viewMode=story`,+ );+ const tooltip = page.getByRole('tooltip', {name: 'Direction hint'});+ await expect(tooltip).toBeVisible();+ expect(+ await tooltip.evaluate(element => getComputedStyle(element).direction),+ ).toBe('rtl');+ await page.getByRole('button', {name: 'Change direction'}).click();+ await expect+ .poll(async () =>+ tooltip.evaluate(element => getComputedStyle(element).direction),+ )+ .toBe('ltr');+});diff --git a/packages/core/src/Layer/layerHost.ts b/packages/core/src/Layer/layerHost.tsindex 5eb7313a0d..ec677261af 100644--- a/packages/core/src/Layer/layerHost.ts+++ b/packages/core/src/Layer/layerHost.ts@@ -2,14 +2,17 @@/*** @file layerHost.ts- * @input Uses the layer's intended inline parent element- * @output Exports resolveLayerPortalTarget, the corrective portal target+ * @input Uses the intended inline parent, renderer-managed roots and layer roots+ * @output Exports the corrective portal resolver* @position Layer utility; used by useLayer to place the popover in the DOM** SYNC: When modified, update:* - /packages/core/src/Layer/layerHost.test.ts*/+import {isRendererManagedRoot} from '../privateAttributes/layerPortalBoundary.stylex';+import {isLayerRoot} from '../privateAttributes/layerRoot.stylex';+/*** Ancestors a layer must not be hosted inside.*@@ -102,9 +105,8 @@ const UNSAFE_HOSTS = new Set([/*** Return the corrective portal target for a layer's intended inline parent.*- * A null result means the inline parent and all of its ancestors are safe, so- * the layer should stay at its JSX position. Otherwise the result is the- * nearest element outside every unsafe ancestor around that position.+ * A null result means the layer stays inline. A corrective portal escapes+ * unsafe ancestors and explicitly marked integration-managed DOM.** Walking up from the actual render position (rather than the trigger, or* portaling to `document.body`) keeps the two things a layer inherits there:@@ -132,14 +134,26 @@ export function resolveLayerPortalTarget(}let outermostUnsafe: HTMLElement | null = null;+ let isTargetLayerOwned = false;let node: HTMLElement | null = inlineParent;while (node) {const tagName = node.tagName.toLowerCase();if (tagName === 'dialog') {break;}+ if (isLayerRoot(node)) {+ isTargetLayerOwned = true;+ }if (UNSAFE_HOSTS.has(tagName)) {outermostUnsafe = node;+ // Escaping this ancestor also leaves any nearer layer-owned scope.+ isTargetLayerOwned = false;+ } else if (+ outermostUnsafe !== null &&+ isRendererManagedRoot(node) &&+ !isTargetLayerOwned+ ) {+ outermostUnsafe = node;}node = node.parentElement;}diff --git a/packages/core/src/Layer/layerPortalBoundary.test.ts b/packages/core/src/Layer/layerPortalBoundary.test.tsnew file mode 100644index 0000000000..6f3946fd54--- /dev/null+++ b/packages/core/src/Layer/layerPortalBoundary.test.ts@@ -0,0 +1,104 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file layerPortalBoundary.test.ts+ * @input The portal resolver and the integration boundary protocol.+ * @output Corrective targets avoid managed DOM without changing safe inline hosting.+ * @position Focused ownership-boundary regression tests.+ */++import {afterEach, describe, expect, it} from 'vitest';+import {resolveLayerPortalTarget} from './layerHost';+import {layerRootProps} from '../privateAttributes/layerRoot.stylex';+import {rendererManagedRootProps} from '../privateAttributes/layerPortalBoundary.stylex';+const roots: HTMLElement[] = [];+function mount(html: string) {+ const root = document.createElement('div');+ root.innerHTML = html;+ document.body.appendChild(root);+ roots.push(root);+ const managed = root.querySelector('#managed');+ if (managed) {+ for (const [name, value] of Object.entries(rendererManagedRootProps)) {+ managed.setAttribute(name, value);+ }+ }+ const popup = root.querySelector('#popup');+ if (popup) {+ for (const [name, value] of Object.entries(layerRootProps)) {+ popup.setAttribute(name, value);+ }+ }+ return root;+}+afterEach(() => {+ for (const root of roots.splice(0)) {+ root.remove();+ }+});+describe('integration portal boundary', () => {+ it('moves a corrective portal outside the managed root', () => {+ const root = mount(+ '<section id="safe"><div id="managed"><p><template></template></p></div></section>',+ );+ expect(+ resolveLayerPortalTarget(+ root.querySelector('template')?.parentElement ?? null,+ ),+ ).toBe(root.querySelector('#safe'));+ });+ it('does not move safe inline JSX merely because it is inside a managed tree', () => {+ const root = mount(+ '<div id="managed"><div id="inline"><template></template></div></div>',+ );+ expect(resolveLayerPortalTarget(root.querySelector('#inline'))).toBeNull();+ });+ it('does not infer ownership from a non-editable wrapper', () => {+ const root = mount(+ '<div contenteditable="false" id="inline"><template></template></div>',+ );+ expect(resolveLayerPortalTarget(root.querySelector('#inline'))).toBeNull();+ });+ it('keeps corrections within the nearest native popup focus owner', () => {+ const root = mount(+ '<div id="managed"><div id="popup" popover="auto"><span><template></template></span></div></div>',+ );+ expect(+ resolveLayerPortalTarget(+ root.querySelector('template')?.parentElement ?? null,+ ),+ ).toBe(root.querySelector('#popup'));+ });+ it('still escapes an unsafe link above a fixed layer root', () => {+ const root = mount(+ '<a href="#test"><div id="popup"><span><template></template></span></div></a>',+ );+ expect(+ resolveLayerPortalTarget(+ root.querySelector('template')?.parentElement ?? null,+ ),+ ).toBe(root);+ });++ it('respects an older managed root after escaping an unsafe ancestor above a layer', () => {+ const root = mount(+ '<section id="safe"><div id="managed"><a href="#test"><div id="popup"><span><template></template></span></div></a></div></section>',+ );+ expect(+ resolveLayerPortalTarget(+ root.querySelector('template')?.parentElement ?? null,+ ),+ ).toBe(root.querySelector('#safe'));+ });++ it('keeps corrections within a native dialog', () => {+ const root = mount(+ '<dialog id="dialog"><div id="managed"><p><template></template></p></div></dialog>',+ );+ expect(+ resolveLayerPortalTarget(+ root.querySelector('template')?.parentElement ?? null,+ ),+ ).toBe(root.querySelector('#dialog'));+ });+});diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsxindex eda855fde9..e013648f4b 100644--- a/packages/core/src/Layer/useLayer.tsx+++ b/packages/core/src/Layer/useLayer.tsx@@ -4,7 +4,7 @@/*** @file useLayer.tsx- * @input Uses React hooks, Popover API (its `beforetoggle`/`toggle` events through the popoverOperations ledger), CSS anchor positioning, shared text/provider boundaries+ * @input Uses React hooks, Popover API (its `beforetoggle`/`toggle` events through the popoverOperations ledger), CSS anchor positioning, owned DOM boundaries, shared text/provider boundaries* @output Exports the public useLayer hook plus internal trigger helpers.* @position Core layer utility; used by useHoverCard, useTooltip, etc.*diff --git a/packages/core/src/Tooltip/__tests__/TooltipDecorator.a11y.browser.spec.ts b/packages/core/src/Tooltip/__tests__/TooltipDecorator.a11y.browser.spec.tsnew file mode 100644index 0000000000..de4941012b--- /dev/null+++ b/packages/core/src/Tooltip/__tests__/TooltipDecorator.a11y.browser.spec.ts@@ -0,0 +1,102 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TooltipDecorator.a11y.browser.spec.ts+ * @input A built Storybook and the real Lexical decorator fixture.+ * @output Tooltips survive editor mutation reconciliation and unmount cleanly.+ * @position Browser-only regression for corrective layer portals in editors.+ */++import {expect, test} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++for (const direction of ['ltr', 'rtl']) {+ test(`selected decorator controls keep their tooltips and unmount cleanly (${direction})`, async ({+ page,+ }) => {+ const errors: string[] = [];+ page.on('pageerror', error => errors.push(error.message));+ page.on('console', message => {+ if (message.type() === 'error') {+ errors.push(message.text());+ }+ });+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-tooltip--decorator-selection&viewMode=story&globals=direction:${direction}`,+ );+ const image = page.getByRole('img', {name: 'Selectable landscape'});+ const smaller = page.getByRole('button', {name: 'Smaller', exact: true});+ const text = page.getByText('Click this text to deselect the image.', {+ exact: true,+ });++ for (let cycle = 0; cycle < 2; cycle++) {+ await image.click();+ await expect(smaller).toBeVisible();+ await smaller.hover();+ await expect(+ page.getByRole('tooltip', {name: 'Narrow it'}),+ ).toBeVisible();+ await text.click();+ await expect(smaller).toHaveCount(0);+ await expect(page.getByRole('tooltip', {name: 'Narrow it'})).toHaveCount(+ 0,+ );+ await expect(image).toBeVisible();+ expect(errors).toEqual([]);+ }++ await image.click();+ await smaller.hover();+ await expect(page.getByRole('tooltip', {name: 'Narrow it'})).toBeVisible();+ await page.getByRole('button', {name: 'Toggle editor'}).click();+ await expect(image).toHaveCount(0);+ await expect(page.getByRole('tooltip', {name: 'Narrow it'})).toHaveCount(0);+ await page.getByRole('button', {name: 'Outside control'}).hover();+ await expect(+ page.getByRole('tooltip', {name: 'Outside the editor'}),+ ).toBeVisible();+ expect(errors).toEqual([]);+ });+}++test('read-only editor controls keep their tooltip and release it on unmount', async ({+ page,+}) => {+ const errors: string[] = [];+ page.on('pageerror', error => errors.push(error.message));+ page.on('console', message => {+ if (message.type() === 'error') {+ errors.push(message.text());+ }+ });+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-tooltip--decorator-read-only&viewMode=story`,+ );+ await expect(+ page.getByRole('textbox', {name: 'Image editor'}),+ ).toHaveAttribute('contenteditable', 'false');+ await page.getByRole('img', {name: 'Selectable landscape'}).click();+ await page.getByRole('button', {name: 'Smaller', exact: true}).hover();+ await expect(page.getByRole('tooltip', {name: 'Narrow it'})).toBeVisible();+ await page.getByRole('button', {name: 'Toggle editor'}).click();+ await expect(page.getByRole('textbox', {name: 'Image editor'})).toHaveCount(+ 0,+ );+ await expect(page.getByRole('tooltip', {name: 'Narrow it'})).toHaveCount(0);+ expect(errors).toEqual([]);+});diff --git a/packages/core/src/privateAttributes/layerPortalBoundary.stylex.ts b/packages/core/src/privateAttributes/layerPortalBoundary.stylex.tsnew file mode 100644index 0000000000..7bea3061aa--- /dev/null+++ b/packages/core/src/privateAttributes/layerPortalBoundary.stylex.ts@@ -0,0 +1,27 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file privateAttributes/layerPortalBoundary.stylex.ts+ * @input An element whose DOM a renderer reconciles+ * @output rendererManagedRootProps, which marks such a root, and+ * isRendererManagedRoot, which reads the mark+ * @position Owner module of the private layer-portal-boundary attribute in+ * Core: the only Core file that writes its name. Layer's corrective portal+ * resolver reads it. RichText writes the same mark from its own owner+ * module. No package entry exports it.+ */++const LAYER_PORTAL_BOUNDARY = 'data-astryx-layer-portal-boundary';+const RENDERER_MANAGED = 'external';++/** Spread on the root of DOM a renderer reconciles. */+export const rendererManagedRootProps: Readonly<+ Record<`data-${string}`, string>+> = {+ [LAYER_PORTAL_BOUNDARY]: RENDERER_MANAGED,+};++/** Whether `element` is the root of DOM a renderer reconciles. */+export function isRendererManagedRoot(element: Element): boolean {+ return element.getAttribute(LAYER_PORTAL_BOUNDARY) === RENDERER_MANAGED;+}diff --git a/packages/core/src/privateAttributes/layerRoot.stylex.ts b/packages/core/src/privateAttributes/layerRoot.stylex.tsindex b6d8f9cd40..7e8717ce2d 100644--- a/packages/core/src/privateAttributes/layerRoot.stylex.ts+++ b/packages/core/src/privateAttributes/layerRoot.stylex.ts@@ -3,12 +3,14 @@/*** @file privateAttributes/layerRoot.stylex.ts* @input A layer content root- * @output layerRootProps, which marks an element as a layer root, and- * closestLayerRoot, which finds the nearest marked root+ * @output layerRootProps, which marks an element as a layer root,+ * closestLayerRoot, which finds the nearest marked root, and isLayerRoot,+ * which reads the mark on one element* @position Owner module of the private layer-root attribute: the only* file that writes its name. Layer's click boundary spreads the mark on* every layer root; SelectableCard reads it for its compatibility path- * until the next minor. No package entry exports it.+ * until the next minor; Layer's corrective portal resolver reads it to stop+ * at the nearest layer root. No package entry exports it.*/const LAYER_ROOT = 'data-astryx-layer-root';@@ -26,3 +28,8 @@ export const layerRootProps: Readonly<Record<`data-${string}`, string>> = {export function closestLayerRoot(target: Element): Element | null {return target.closest(`[${LAYER_ROOT}]`);}++/** Whether `element` itself is a marked layer root. */+export function isLayerRoot(element: Element): boolean {+ return element.hasAttribute(LAYER_ROOT);+}diff --git a/packages/richtext/src/RichTextEditor.portalHost.test.tsx b/packages/richtext/src/RichTextEditor.portalHost.test.tsxnew file mode 100644index 0000000000..6f2f77f080--- /dev/null+++ b/packages/richtext/src/RichTextEditor.portalHost.test.tsx@@ -0,0 +1,95 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file RichTextEditor.portalHost.test.tsx+ * @input Real Lexical decorator nodes and the RichTextEditor ref API.+ * @output Decorator tooltips survive editor reconciliation and clean up on unmount.+ * @position Regression for the RichText integration's declared portal host.+ */++import {describe, expect, it} from 'vitest';+import {act, render, screen, waitFor} from '@testing-library/react';+import {createRef, StrictMode, type ReactNode} from 'react';+import {+ DecoratorNode,+ $getRoot,+ $createParagraphNode,+ type NodeKey,+} from 'lexical';+import {Button} from '@astryxdesign/core/Button';+import {RichTextEditor, type RichTextEditorRef} from './RichTextEditor';++class TooltipNode extends DecoratorNode<ReactNode> {+ static getType() {+ return 'tooltip-control';+ }+ static clone(node: TooltipNode) {+ return new TooltipNode(node.__key);+ }+ constructor(key?: NodeKey) {+ super(key);+ }+ static importJSON() {+ return new TooltipNode();+ }+ createDOM() {+ const element = document.createElement('span');+ element.contentEditable = 'false';+ return element;+ }+ updateDOM() {+ return false;+ }+ decorate() {+ return <Button label="Decorator action" tooltip="Decorator hint" />;+ }+}++const nodes = [TooltipNode];++describe('RichTextEditor portal ownership', () => {+ it.each([false, true])(+ 'keeps decorator tooltips outside its managed root (read-only=%s)',+ async isReadOnly => {+ const ref = createRef<RichTextEditorRef>();+ const view = render(+ <StrictMode>+ <RichTextEditor+ ref={ref}+ label="Editor"+ nodes={nodes}+ isReadOnly={isReadOnly}+ />+ </StrictMode>,+ );+ const editor = ref.current?.getEditor();+ expect(editor).toBeDefined();+ if (!editor) {+ throw new Error('Editor did not mount');+ }+ await act(async () => {+ editor.update(+ () => {+ $getRoot()+ .clear()+ .append($createParagraphNode().append(new TooltipNode()));+ },+ {discrete: true},+ );+ });+ const trigger = await screen.findByRole('button', {+ name: 'Decorator action',+ });+ const id = trigger.getAttribute('aria-describedby');+ await waitFor(() => {+ const tooltip = id ? document.getElementById(id) : null;+ expect(tooltip).not.toBeNull();+ expect(+ screen.getByRole('textbox', {name: 'Editor'}),+ ).not.toContainElement(tooltip);+ });+ view.unmount();+ expect(id && document.getElementById(id)).toBeNull();+ },+ );+});diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsxindex 710cbfaa12..f4da33c6a8 100644--- a/packages/richtext/src/RichTextEditor.tsx+++ b/packages/richtext/src/RichTextEditor.tsx@@ -4,7 +4,7 @@/*** @file RichTextEditor.tsx- * @input Uses React, useId, Lexical (lexical + @lexical/react, composed through+ * @input Uses React, useId, a declared DOM boundary, Lexical (lexical + @lexical/react, composed through* LexicalExtensionComposer), Field, VisuallyHidden, useInputStatusIcon,* mergeProps, design tokens* @output Exports an accessibly labelled RichTextEditor component with a flush@@ -106,6 +106,7 @@ import {type LexicalNode,type EditorThemeClasses,} from 'lexical';+import {rendererManagedRootProps} from './privateAttributes/layerPortalBoundary.stylex';/*** Serialized state for an empty editor: a root containing a single empty@@ -687,7 +688,7 @@ export const RichTextEditor = function RichTextEditor({!!statusIcon && styles.editorBodyWithStatus,size === 'lg' && editorBodySizeStyles.lg,)}>- <div {...stylex.props(styles.editorRoot)}>+ <div {...stylex.props(styles.editorRoot)} dir={rest.dir}><RichTextPlugincontentEditable={<EditorContentEditable@@ -1065,6 +1066,8 @@ function EditorContentEditable({dynamicStyles.contentEditableMinHeight(minHeight),),...rest,+ // Lexical reconciles this DOM, so Layer keeps corrective portals out.+ ...rendererManagedRootProps,};if (placeholderText) {return (diff --git a/packages/richtext/src/__tests__/DecoratorPortal.a11y.browser.spec.ts b/packages/richtext/src/__tests__/DecoratorPortal.a11y.browser.spec.tsnew file mode 100644index 0000000000..c4c97df3d1--- /dev/null+++ b/packages/richtext/src/__tests__/DecoratorPortal.a11y.browser.spec.ts@@ -0,0 +1,112 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @input Built Storybook with real RichTextEditor and Lexical image decorators.+ * @output Repeated decorator deselection and editor teardown remain error-free.+ * @position Browser E2E regression for renderer-owned corrective portals.+ */+import {expect, test} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';+let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});+for (const isReadOnly of [false, true]) {+ for (const direction of ['ltr', 'rtl']) {+ test(`RichTextEditor decorator lifecycle (${direction}, read-only=${isReadOnly})`, async ({+ page,+ }, testInfo) => {+ const errors: string[] = [];+ page.on('pageerror', error => errors.push(error.message));+ page.on('console', message => {+ if (message.type() === 'error') {+ errors.push(message.text());+ }+ });+ const story = isReadOnly ? 'integrated-read-only' : 'integrated-editor';+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-tooltip--${story}&viewMode=story&globals=direction:${direction}`,+ );+ const editor = page.getByRole('textbox', {name: 'Image editor'});+ await expect(editor).toHaveAttribute(+ 'contenteditable',+ String(!isReadOnly),+ );+ const image = page.getByRole('img', {name: 'Selectable landscape'});+ const trigger = page.getByRole('button', {name: 'Smaller', exact: true});+ const tooltip = page.getByRole('tooltip', {name: 'Narrow it'});+ let tooltipId: string;+ const expectTooltipRemoved = async () => {+ await expect(tooltip).toHaveCount(0);+ await expect+ .poll(async () =>+ page.evaluate(+ id => document.getElementById(id) === null,+ tooltipId,+ ),+ )+ .toBe(true);+ };+ const showTooltip = async () => {+ await image.click();+ await trigger.hover();+ await expect(tooltip).toBeVisible();+ tooltipId = (await tooltip.getAttribute('id')) ?? '';+ expect(tooltipId).not.toBe('');+ expect(+ await trigger.evaluate(element => {+ const id = element.getAttribute('aria-describedby');+ const popup = id && document.getElementById(id);+ return (+ !!popup &&+ !document.querySelector('[data-lexical-editor]')?.contains(popup)+ );+ }),+ ).toBe(true);+ };+ await showTooltip();+ await testInfo.attach('selected', {+ body: await page.screenshot(),+ contentType: 'image/png',+ });+ if (!isReadOnly) {+ for (let cycle = 0; cycle < 3; cycle++) {+ await page+ .getByText('Click this text to deselect the image.', {exact: true})+ .click();+ await expect(trigger).toHaveCount(0);+ await expectTooltipRemoved();+ await expect(image).toBeVisible();+ expect(errors).toEqual([]);+ await showTooltip();+ }+ }+ await page.getByRole('button', {name: 'Toggle editor'}).click();+ await expect(editor).toHaveCount(0);+ await expect(image).toHaveCount(0);+ await expectTooltipRemoved();+ await testInfo.attach('unmounted', {+ body: await page.screenshot(),+ contentType: 'image/png',+ });+ await page.getByRole('button', {name: 'Outside control'}).hover();+ await expect(+ page.getByRole('tooltip', {name: 'Outside the editor'}),+ ).toBeVisible();+ expect(errors).toEqual([]);+ await testInfo.attach('console-errors', {+ body: JSON.stringify(errors),+ contentType: 'application/json',+ });+ });+ }+}diff --git a/packages/richtext/src/privateAttributes/layerPortalBoundary.stylex.ts b/packages/richtext/src/privateAttributes/layerPortalBoundary.stylex.tsnew file mode 100644index 0000000000..ffa38e6cf9--- /dev/null+++ b/packages/richtext/src/privateAttributes/layerPortalBoundary.stylex.ts@@ -0,0 +1,18 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file privateAttributes/layerPortalBoundary.stylex.ts+ * @input The editable root Lexical reconciles+ * @output rendererManagedRootProps, which marks that root+ * @position Owner module of the private layer-portal-boundary attribute in+ * RichText: the only RichText file that writes its name. Core's Layer reads+ * the mark through its own owner module of the same name. No package entry+ * exports it.+ */++/** Spread on the editable root, whose DOM Lexical reconciles. */+export const rendererManagedRootProps: Readonly<+ Record<`data-${string}`, string>+> = {+ 'data-astryx-layer-portal-boundary': 'external',+};