Skip to content

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

TypeScript

fix(layer): mirror anchor-positioned popovers in RTL (#3486)

AK9612d7ba3e77
diff --git a/.changeset/layer-custom-positioning.md b/.changeset/layer-custom-positioning.md
new file mode 100644
index 0000000000..f7880e2ca8
--- /dev/null
+++ b/.changeset/layer-custom-positioning.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] useLayer: new `positioning: 'custom'` context render option for consumers that author their own position styles (explicit `anchor()` insets, `anchor-size()` covers). Keeps the popover behavior and `position-anchor` wiring but derives no position styles from `placement`/`alignment` — including the automatic RTL mirroring, which becomes the consumer's responsibility (#3389).
+@AKnassa
diff --git a/.changeset/layer-rtl-popover-position.md b/.changeset/layer-rtl-popover-position.md
new file mode 100644
index 0000000000..6c19e521d7
--- /dev/null
+++ b/.changeset/layer-rtl-popover-position.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Layer/Popover: anchor-positioned popovers now mirror in RTL. `placement`/`alignment` `start`/`end` are logical (inline-start/inline-end), so DropdownMenu, Selector, Typeahead, date inputs, and every other context-mode popover opens toward the correct side under RTL automatically via CSS. LTR behavior is unchanged (#3389).
+@AKnassa
diff --git a/apps/docsite/src/components/docs/TableBlock.tsx b/apps/docsite/src/components/docs/TableBlock.tsx
index c754fd806c..e354767a7d 100644
--- a/apps/docsite/src/components/docs/TableBlock.tsx
+++ b/apps/docsite/src/components/docs/TableBlock.tsx
@@ -4,7 +4,12 @@
import * as stylex from '@stylexjs/stylex';
import {Text} from '@astryxdesign/core/Text';
-import {Table, pixel, proportional, type TableColumn} from '@astryxdesign/core/Table';
+import {
+ Table,
+ pixel,
+ proportional,
+ type TableColumn,
+} from '@astryxdesign/core/Table';
import {Card} from '@astryxdesign/core/Card';
import {HStack} from '@astryxdesign/core/Layout';
import {Icon, getIconRegistry} from '@astryxdesign/core/Icon';
diff --git a/apps/storybook/stories/DropdownMenu.stories.tsx b/apps/storybook/stories/DropdownMenu.stories.tsx
index c0f53301f2..c5dcd873e0 100644
--- a/apps/storybook/stories/DropdownMenu.stories.tsx
+++ b/apps/storybook/stories/DropdownMenu.stories.tsx
@@ -515,3 +515,38 @@ export const PlacementAbove: Story = {
/>
),
};
+
+export const RTL: Story = {
+ render: () => (
+ <div style={{direction: 'rtl', display: 'flex', gap: '16px'}}>
+ <DropdownMenu
+ button={{label: 'CSS direction: rtl'}}
+ items={[
+ {label: 'Edit', onClick: () => console.log('Edit')},
+ {label: 'Duplicate', onClick: () => console.log('Duplicate')},
+ {label: 'Delete', onClick: () => console.log('Delete')},
+ ]}
+ />
+ <div dir="ltr">
+ <div dir="rtl">
+ <DropdownMenu
+ button={{label: 'dir="rtl" attribute'}}
+ items={[
+ {label: 'Edit', onClick: () => console.log('Edit')},
+ {label: 'Duplicate', onClick: () => console.log('Duplicate')},
+ {label: 'Delete', onClick: () => console.log('Delete')},
+ ]}
+ />
+ </div>
+ </div>
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'In RTL contexts (CSS direction property or dir attribute) the menu right-edge-aligns to the trigger and grows toward the left — the logical mirror of the LTR default (#3389). Both direction mechanisms are shown; the popover inherits direction from the trigger subtree and the self-* position-area keywords mirror it in pure CSS.',
+ },
+ },
+ },
+};
diff --git a/packages/cli/templates/pages/kanban-board/page.tsx b/packages/cli/templates/pages/kanban-board/page.tsx
index de190c3ca7..b4b63f0dbf 100644
--- a/packages/cli/templates/pages/kanban-board/page.tsx
+++ b/packages/cli/templates/pages/kanban-board/page.tsx
@@ -439,8 +439,11 @@ export default function KanbanBoardTemplate() {
let cb = columnRefCbs.current.get(id);
if (!cb) {
cb = el => {
- if (el) {columnEls.current.set(id, el);}
- else {columnEls.current.delete(id);}
+ if (el) {
+ columnEls.current.set(id, el);
+ } else {
+ columnEls.current.delete(id);
+ }
};
columnRefCbs.current.set(id, cb);
}
@@ -451,8 +454,11 @@ export default function KanbanBoardTemplate() {
let cb = cardRefCbs.current.get(id);
if (!cb) {
cb = el => {
- if (el) {cardEls.current.set(id, el);}
- else {cardEls.current.delete(id);}
+ if (el) {
+ cardEls.current.set(id, el);
+ } else {
+ cardEls.current.delete(id);
+ }
};
cardRefCbs.current.set(id, cb);
}
@@ -487,7 +493,9 @@ export default function KanbanBoardTemplate() {
): DropTarget | null => {
for (const [colId, el] of Array.from(columnEls.current.entries())) {
const r = el.getBoundingClientRect();
- if (px < r.left || px > r.right || py < r.top || py > r.bottom) {continue;}
+ if (px < r.left || px > r.right || py < r.top || py > r.bottom) {
+ continue;
+ }
const ids = itemsByColumn[colId]
.filter(it => it.id !== draggedId)
@@ -496,7 +504,9 @@ export default function KanbanBoardTemplate() {
let index = ids.length;
for (let i = 0; i < ids.length; i++) {
const cardEl = cardEls.current.get(ids[i]);
- if (!cardEl) {continue;}
+ if (!cardEl) {
+ continue;
+ }
const cr = cardEl.getBoundingClientRect();
if (py < cr.top + cr.height / 2) {
index = i;
@@ -513,21 +523,27 @@ export default function KanbanBoardTemplate() {
const commitDrag = (id: string, target: DropTarget) => {
setItems(prev => {
const moved = prev.find(it => it.id === id);
- if (!moved) {return prev;}
+ if (!moved) {
+ return prev;
+ }
const rest = prev.filter(it => it.id !== id);
const updated: WorkItem = {...moved, column: target.column};
const colItems = rest.filter(it => it.column === target.column);
const anchor = colItems[target.index];
- if (!anchor) {return [...rest, updated];}
+ if (!anchor) {
+ return [...rest, updated];
+ }
const at = rest.indexOf(anchor);
return [...rest.slice(0, at), updated, ...rest.slice(at)];
});
};
const onCardPointerDown = (e: ReactPointerEvent, id: string) => {
- if (e.button !== 0) {return;}
+ if (e.button !== 0) {
+ return;
+ }
// Let the card's own controls (the actions menu) handle the press.
if (
(e.target as HTMLElement).closest(
@@ -538,7 +554,9 @@ export default function KanbanBoardTemplate() {
}
const el = cardEls.current.get(id);
- if (!el) {return;}
+ if (!el) {
+ return;
+ }
const rect = el.getBoundingClientRect();
const startX = e.clientX;
@@ -574,7 +592,9 @@ export default function KanbanBoardTemplate() {
const onUp = () => {
teardownRef.current?.();
- if (started && target) {commitDrag(id, target);}
+ if (started && target) {
+ commitDrag(id, target);
+ }
setDrag(null);
};
@@ -594,7 +614,9 @@ export default function KanbanBoardTemplate() {
// Suppress selection while dragging and detach listeners on unmount.
useEffect(() => {
- if (!isDragging) {return;}
+ if (!isDragging) {
+ return;
+ }
const previous = document.body.style.userSelect;
document.body.style.userSelect = 'none';
return () => {
@@ -612,7 +634,9 @@ export default function KanbanBoardTemplate() {
const ghostTarget =
drag && drag.target && drag.target.column === colId ? drag : null;
- if (visible.length === 0 && !ghostTarget) {return null;}
+ if (visible.length === 0 && !ghostTarget) {
+ return null;
+ }
const nodes: ReactNode[] = visible.map(it => (
<BoardCard
diff --git a/packages/core/src/Calendar/dayCellUtils.ts b/packages/core/src/Calendar/dayCellUtils.ts
index 526c0620b4..eecf88ecfd 100644
--- a/packages/core/src/Calendar/dayCellUtils.ts
+++ b/packages/core/src/Calendar/dayCellUtils.ts
@@ -193,7 +193,9 @@ export function isRangeHighlighted(input: {
isDisabled: boolean;
isOutside: boolean;
}): boolean {
- if (input.mode !== 'range') {return false;}
+ if (input.mode !== 'range') {
+ return false;
+ }
return isSpanHighlighted({
date: input.date,
spanStart: input.rangeStart,
diff --git a/packages/core/src/Carousel/Carousel.tsx b/packages/core/src/Carousel/Carousel.tsx
index 78e3188323..d2f889a5fc 100644
--- a/packages/core/src/Carousel/Carousel.tsx
+++ b/packages/core/src/Carousel/Carousel.tsx
@@ -318,6 +318,8 @@ export function Carousel({
: null
: null;
+ // Self-authored position styles (positioning: 'custom' below): a cover
+ // centered on the anchor, sized to it — direction-neutral by construction.
const coverStyle: React.CSSProperties = {
positionArea: 'center',
width: 'anchor-size(width)',
@@ -398,8 +400,7 @@ export function Carousel({
</div>
</>,
{
- placement: 'below',
- alignment: 'center',
+ positioning: 'custom',
style: coverStyle,
xstyle: styles.buttonOverlay,
},
diff --git a/packages/core/src/Chat/ChatComposerInput.test.tsx b/packages/core/src/Chat/ChatComposerInput.test.tsx
index a65c0d53a3..5846465280 100644
--- a/packages/core/src/Chat/ChatComposerInput.test.tsx
+++ b/packages/core/src/Chat/ChatComposerInput.test.tsx
@@ -369,7 +369,9 @@ describe('ChatComposerInput', () => {
},
});
- expect(textbox.querySelector('[data-astryx-token]')).not.toBeInTheDocument();
+ expect(
+ textbox.querySelector('[data-astryx-token]'),
+ ).not.toBeInTheDocument();
expect(textbox.textContent).toBe(long);
});
});
diff --git a/packages/core/src/Chat/ChatComposerInput.tsx b/packages/core/src/Chat/ChatComposerInput.tsx
index 6814ea6eef..098e4a736b 100644
--- a/packages/core/src/Chat/ChatComposerInput.tsx
+++ b/packages/core/src/Chat/ChatComposerInput.tsx
@@ -43,10 +43,7 @@ import {
} from '../theme/tokens.stylex';
import {mergeProps} from '../utils';
import {useTriggerMenu} from './useTriggerMenu';
-import {
- useChatComposerTokens,
- isCustomToken,
-} from './useChatComposerTokens';
+import {useChatComposerTokens, isCustomToken} from './useChatComposerTokens';
import {ensureCaretInside, insertTextAtCursor} from './chatComposerSelection';
import {ChatPastedTextToken} from './ChatPastedTextToken';
import {
@@ -695,11 +692,7 @@ ChatComposerInput.displayName = 'ChatComposerInput';
// Token element helper (for custom rendering in stories/consumers)
// =============================================================================
-export function ChatComposerTokenElement({
- token,
-}: {
- token: ChatComposerToken;
-}) {
+export function ChatComposerTokenElement({token}: {token: ChatComposerToken}) {
return (
<span
data-astryx-token=""
@@ -709,11 +702,7 @@ export function ChatComposerTokenElement({
{isCustomToken(token) ? (
token.render()
) : (
- <Badge
- label={token.label}
- variant={token.variant}
- icon={token.icon}
- />
+ <Badge label={token.label} variant={token.variant} icon={token.icon} />
)}
</span>
);
diff --git a/packages/core/src/Chat/useTriggerMenu.tsx b/packages/core/src/Chat/useTriggerMenu.tsx
index fdd6722ee9..c9469fb20f 100644
--- a/packages/core/src/Chat/useTriggerMenu.tsx
+++ b/packages/core/src/Chat/useTriggerMenu.tsx
@@ -40,10 +40,7 @@ import {
import {mergeProps, groupItems} from '../utils';
import type {SearchableItem} from '../Typeahead/types';
import {themeProps} from '../utils/themeProps';
-import type {
- ChatComposerTrigger,
- ChatComposerToken,
-} from './ChatComposerInput';
+import type {ChatComposerTrigger, ChatComposerToken} from './ChatComposerInput';
// =============================================================================
// Types
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index 9e40a52124..66e6ca015d 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -89,7 +89,7 @@ describe('DropdownMenu', () => {
.getByRole('menu', {hidden: true})
.closest('[popover]');
expect(popover?.getAttribute('style')).toContain(
- 'position-area: bottom span-right',
+ 'position-area: self-block-end span-self-inline-end',
);
});
@@ -105,7 +105,27 @@ describe('DropdownMenu', () => {
.getByRole('menu', {hidden: true})
.closest('[popover]');
expect(popover?.getAttribute('style')).toContain(
- 'position-area: top span-right',
+ 'position-area: self-block-start span-self-inline-end',
+ );
+ });
+
+ it('emits the direction-independent logical mapping under an RTL ancestor (#3389)', async () => {
+ // The self-* position-area keywords resolve against the popover's own
+ // inherited direction in the browser, so RTL emits the same string as
+ // LTR and the mirroring is pure CSS. jsdom can't verify the geometry —
+ // the DropdownMenu RTL Storybook story is the visual proof surface.
+ const user = userEvent.setup();
+ const {container} = render(
+ <div style={{direction: 'rtl'}}>
+ <DropdownMenu button={{label: 'Actions'}} items={[{label: 'Item 1'}]} />
+ </div>,
+ );
+
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+
+ const popover = container.querySelector('[popover]');
+ expect(popover?.getAttribute('style')).toContain(
+ 'position-area: self-block-end span-self-inline-end',
);
});
diff --git a/packages/core/src/Field/Field.test.tsx b/packages/core/src/Field/Field.test.tsx
index 978d572bb5..9c739fe0be 100644
--- a/packages/core/src/Field/Field.test.tsx
+++ b/packages/core/src/Field/Field.test.tsx
@@ -137,10 +137,7 @@ describe('Field', () => {
it('renders description without ID attribute when descriptionID is not provided', () => {
render(
- <Field
- label="Email"
- inputID="email-input"
- description="Description text">
+ <Field label="Email" inputID="email-input" description="Description text">
<input id="email-input" />
</Field>,
);
diff --git a/packages/core/src/HoverCard/HoverCard.doc.mjs b/packages/core/src/HoverCard/HoverCard.doc.mjs
index 11478a930c..5069330c35 100644
--- a/packages/core/src/HoverCard/HoverCard.doc.mjs
+++ b/packages/core/src/HoverCard/HoverCard.doc.mjs
@@ -46,13 +46,13 @@ export const docs = {
{
name: 'placement',
type: "'above' | 'below' | 'start' | 'end'",
- description: 'Position relative to the anchor element.',
+ description: "Position relative to the anchor element. Logical: start/end resolve against the popover\'s own inherited direction (RTL mirrors in pure CSS).",
default: "'above'",
},
{
name: 'alignment',
type: "'start' | 'center' | 'end'",
- description: 'Alignment along the placement axis.',
+ description: "Alignment along the placement axis. Logical: start/end resolve against the popover\'s own inherited direction (RTL mirrors in pure CSS).",
default: "'center'",
},
{
@@ -155,13 +155,13 @@ export const docsZh = {
{
name: 'placement',
type: "'above' | 'below' | 'start' | 'end'",
- description: '相对于锚点元素的位置。',
+ description: '相对于锚点元素的位置。逻辑值:start/end 根据弹出层自身继承的方向解析(RTL 镜像)。',
default: "'above'",
},
{
name: 'alignment',
type: "'start' | 'center' | 'end'",
- description: '沿放置轴的对齐方式。',
+ description: '沿放置轴的对齐方式。逻辑值:start/end 根据弹出层自身继承的方向解析(RTL 镜像)。',
default: "'center'",
},
{
@@ -246,8 +246,8 @@ export const docsDense = {
propDescriptions: {
children: 'Trigger element; must accept ref.',
content: 'Hover card content.',
- placement: 'Position relative to anchor element.',
- alignment: 'Alignment along placement axis.',
+ placement: 'Position relative to anchor element. Logical: start/end follow the popover\'s inherited direction (RTL mirrors).',
+ alignment: 'Alignment along placement axis. Logical: start/end follow the popover\'s inherited direction (RTL mirrors).',
delay: 'Show delay in ms.',
hideDelay: 'Hide delay in ms.',
focusTrigger: 'Controls when focus events trigger hover card.',
diff --git a/packages/core/src/HoverCard/useHoverCard.doc.mjs b/packages/core/src/HoverCard/useHoverCard.doc.mjs
index d43fe48bb3..e0f7e0c845 100644
--- a/packages/core/src/HoverCard/useHoverCard.doc.mjs
+++ b/packages/core/src/HoverCard/useHoverCard.doc.mjs
@@ -7,8 +7,8 @@ export const docs = {
group: 'HoverCard',
keywords: ['hovercard', 'hover', 'preview', 'card', 'tooltip', 'popup', 'floating', 'anchor'],
params: [
- {name: 'placement', type: "'above' | 'below' | 'start' | 'end'", description: 'Position relative to the trigger.', default: "'above'"},
- {name: 'alignment', type: "'start' | 'center' | 'end'", description: 'Alignment along the placement axis.', default: "'center'"},
+ {name: 'placement', type: "'above' | 'below' | 'start' | 'end'", description: "Position relative to the trigger. Logical: start/end resolve against the popover\'s own inherited direction (RTL mirrors in pure CSS).", default: "'above'"},
+ {name: 'alignment', type: "'start' | 'center' | 'end'", description: "Alignment along the placement axis. Logical: start/end resolve against the popover\'s own inherited direction (RTL mirrors in pure CSS).", default: "'center'"},
{name: 'delay', type: 'number', description: 'Delay before showing the hover card on hover, in milliseconds.', default: '300'},
{name: 'hideDelay', type: 'number', description: 'Delay before hiding after mouse or focus leaves, in milliseconds.', default: '200'},
{name: 'focusTrigger', type: "'auto' | 'always' | 'never'", description: 'When focus should open the hover card. auto only attaches focus listeners to naturally focusable elements.', default: "'auto'"},
@@ -24,7 +24,7 @@ export const docs = {
{name: 'interactionRef', type: 'RefCallback<HTMLElement>', description: 'Ref for the hover/focus interaction element. Use with positionRef for split trigger patterns.'},
{name: 'anchorId', type: 'string', description: 'CSS anchor name for advanced positioning cases.'},
{name: 'describedBy', type: 'string', description: 'ID to compose into aria-describedby on the trigger.'},
- {name: 'renderHoverCard', type: '(children: ReactNode, props?: ContextRenderProps) => ReactNode', description: 'Render function for the anchor-positioned hover card content.'},
+ {name: 'renderHoverCard', type: "(children: ReactNode, props?: Omit<ContextRenderProps, 'positioning'>) => ReactNode", description: 'Render function for the anchor-positioned hover card content. The positioning opt-out is excluded: the hover card always derives its position from placement/alignment.'},
{name: 'show', type: '() => void', description: 'Imperatively show the hover card immediately.'},
{name: 'hide', type: '() => void', description: 'Imperatively hide the hover card immediately.'},
],
@@ -46,8 +46,8 @@ export const docs = {
export const docsDense = {
description: 'Headless hover-triggered floating cards. Builds on useLayer w/ hover/focus intent, delays, safe hover behavior, aria-describedby. Use for rich previews when trigger/content rendering needs full control.',
paramDescriptions: {
- placement: 'position relative to trigger.',
- alignment: 'alignment along placement axis.',
+ placement: 'position relative to trigger. logical: start/end follow the popover\'s inherited direction (RTL mirrors).',
+ alignment: 'alignment along placement axis. logical: start/end follow the popover\'s inherited direction (RTL mirrors).',
delay: 'show delay in ms.',
hideDelay: 'hide delay after mouse/focus leave in ms.',
focusTrigger: 'when focus opens hover card; auto = naturally focusable elements only.',
diff --git a/packages/core/src/HoverCard/useHoverCard.tsx b/packages/core/src/HoverCard/useHoverCard.tsx
index faac7c6096..423487f5c1 100644
--- a/packages/core/src/HoverCard/useHoverCard.tsx
+++ b/packages/core/src/HoverCard/useHoverCard.tsx
@@ -181,10 +181,14 @@ export interface HoverCardReturn {
/**
* Render function for hover card content.
* Returns anchor-positioned popover element.
+ *
+ * `positioning` is excluded: the hover card always derives its position
+ * from placement/alignment, so accepting the custom opt-out here would be
+ * a silent no-op.
*/
renderHoverCard: (
children: ReactNode,
- props?: ContextRenderProps,
+ props?: Omit<ContextRenderProps, 'positioning'>,
) => ReactNode;
/**
@@ -450,7 +454,10 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
// Render function that wraps layer.render with hover card behavior
const renderHoverCard = useCallback(
- (children: ReactNode, props?: ContextRenderProps): ReactNode => {
+ (
+ children: ReactNode,
+ props?: Omit<ContextRenderProps, 'positioning'>,
+ ): ReactNode => {
const renderPlacement = props?.placement ?? placement;
const renderProps = {
placement: renderPlacement,
diff --git a/packages/core/src/Layer/useLayer.doc.mjs b/packages/core/src/Layer/useLayer.doc.mjs
index 0e3104a1eb..173aa2954a 100644
--- a/packages/core/src/Layer/useLayer.doc.mjs
+++ b/packages/core/src/Layer/useLayer.doc.mjs
@@ -78,7 +78,7 @@ export const docs = {
name: 'render',
type: '(children: ReactNode, props: ContextRenderProps | FixedRenderProps) => ReactNode',
description:
- 'Render function for the popover element. Pass placement/alignment in context mode or x/y in fixed mode. In context mode, pass `as: "span"` to render an inline-safe layer (e.g. inside a paragraph). The layer renders inline in the React tree; the Popover API promotes it to the top layer when shown, so it escapes ancestor clipping and stacking without a portal.',
+ 'Render function for the popover element. Pass placement/alignment in context mode or x/y in fixed mode. Placement/alignment are logical: they map to the self-* position-area keyword family, which resolves against the popover\'s own inherited direction, so RTL contexts mirror automatically in pure CSS. Pass `positioning: "custom"` in context mode to author position styles yourself via `style` (e.g. explicit anchor() insets or an anchor-size() cover): the hook keeps the popover behavior and position-anchor wiring but derives no position styles — including the automatic RTL mirroring, which becomes your responsibility. In context mode, pass `as: "span"` to render an inline-safe layer (e.g. inside a paragraph). The layer renders inline in the React tree; the Popover API promotes it to the top layer when shown, so it escapes ancestor clipping and stacking without a portal.',
},
],
usage: {
@@ -130,7 +130,7 @@ export const docsDense = {
hide: 'hide layer.',
isOpen: 'whether layer is open.',
id: 'unique ARIA id.',
- render: 'renders popover element; pass placement/alignment or x/y. Context mode accepts `as: "span"` for inline-safe layers. Renders inline; the Popover API top layer escapes clipping/stacking without a portal.',
+ render: 'renders popover element; pass placement/alignment or x/y. Placement/alignment logical: mapped to self-* position-area keywords resolved against the popover\'s inherited direction (RTL mirrors in pure CSS). `positioning: "custom"` (context mode) = author position styles yourself via `style`; keeps popover behavior + position-anchor wiring, derives nothing (incl. RTL mirroring — yours). Context mode accepts `as: "span"` for inline-safe layers. Renders inline; the Popover API top layer escapes clipping/stacking without a portal.',
},
usage: {
description:
diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsx
index 7e140e56aa..d808e87499 100644
--- a/packages/core/src/Layer/useLayer.test.tsx
+++ b/packages/core/src/Layer/useLayer.test.tsx
@@ -3,15 +3,21 @@
/**
* @file useLayer.test.tsx
* @input Uses vitest, @testing-library/react, useLayer hook
- * @output Unit tests for useLayer show/hide behavior and feature-detection guards
+ * @output Tests for useLayer show/hide feature-detection guards and context-mode positioning
* @position Testing; validates useLayer.tsx implementation
*
- * SYNC: When useLayer.tsx changes, update tests to match new behavior
+ * SYNC: When useLayer.tsx changes, update tests accordingly
*/
import {describe, it, expect, vi, afterEach} from 'vitest';
import {render, act} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import {useLayer} from './useLayer';
+import type {
+ LayerPlacement,
+ LayerAlignment,
+ ContextRenderProps,
+} from './useLayer';
/**
* Minimal harness that exposes the imperative show/hide callbacks and renders
@@ -109,3 +115,216 @@ describe('useLayer', () => {
});
});
});
+
+/**
+ * Harness that owns the trigger element.
+ */
+function Harness({
+ placement,
+ alignment,
+ triggerStyle,
+ triggerDir,
+}: {
+ placement: LayerPlacement;
+ alignment: LayerAlignment;
+ triggerStyle?: React.CSSProperties;
+ triggerDir?: string;
+}) {
+ const layer = useLayer({mode: 'context'});
+ return (
+ <>
+ <button
+ type="button"
+ ref={layer.ref}
+ dir={triggerDir}
+ style={triggerStyle}
+ onClick={layer.isOpen ? layer.hide : layer.show}>
+ trigger
+ </button>
+ {layer.render(<span>content</span>, {placement, alignment})}
+ </>
+ );
+}
+
+async function openAndGetStyle(ui: React.ReactElement): Promise<string> {
+ const user = userEvent.setup();
+ const {container, getByRole} = render(ui);
+ await user.click(getByRole('button', {name: 'trigger'}));
+ const popover = container.querySelector('[popover]');
+ return popover?.getAttribute('style') ?? '';
+}
+
+describe('useLayer context positioning', () => {
+ // The mapping uses the self-* logical keyword family, so the emitted
+ // string is direction-independent by construction: the browser resolves
+ // the inline axis against the popover's own inherited direction, and RTL
+ // mirrors with no JS. jsdom has no layout engine, so these tests can only
+ // assert the emitted string — the actual RTL geometry is covered by the
+ // RTL Storybook story (and was verified against the full 12-cell matrix
+ // in a real browser).
+ describe('self-* position-area mapping', () => {
+ it.each([
+ // [placement, alignment, expected position-area]
+ ['above', 'start', 'self-block-start span-self-inline-end'],
+ ['above', 'center', 'self-block-start'],
+ ['above', 'end', 'self-block-start span-self-inline-start'],
+ ['below', 'start', 'self-block-end span-self-inline-end'],
+ ['below', 'center', 'self-block-end'],
+ ['below', 'end', 'self-block-end span-self-inline-start'],
+ ['start', 'start', 'self-inline-start span-self-block-end'],
+ ['start', 'center', 'self-inline-start'],
+ ['start', 'end', 'self-inline-start span-self-block-start'],
+ ['end', 'start', 'self-inline-end span-self-block-end'],
+ ['end', 'center', 'self-inline-end'],
+ ['end', 'end', 'self-inline-end span-self-block-start'],
+ ] as const)(
+ 'placement=%s alignment=%s emits position-area %s',
+ async (placement, alignment, expectedArea) => {
+ const style = await openAndGetStyle(
+ <Harness placement={placement} alignment={alignment} />,
+ );
+ expect(style).toMatch(
+ new RegExp(`position-area: ${expectedArea}(;|$)`),
+ );
+ expect(style).not.toContain('justify-self');
+ },
+ );
+
+ it('emits the same string regardless of trigger direction', async () => {
+ const user = userEvent.setup();
+ const first = render(<Harness placement="below" alignment="start" />);
+ await user.click(first.getByRole('button', {name: 'trigger'}));
+ const ltr =
+ first.container.querySelector('[popover]')?.getAttribute('style') ?? '';
+ first.unmount();
+
+ const second = render(
+ <Harness
+ placement="below"
+ alignment="start"
+ triggerDir="rtl"
+ triggerStyle={{direction: 'rtl'}}
+ />,
+ );
+ await user.click(second.getByRole('button', {name: 'trigger'}));
+ const rtl =
+ second.container.querySelector('[popover]')?.getAttribute('style') ??
+ '';
+ // The unique position-anchor id differs per render; the placement
+ // mapping must not.
+ const positionArea = (s: string) => s.match(/position-area:[^;]*/)?.[0];
+ expect(positionArea(rtl)).toBeDefined();
+ expect(positionArea(rtl)).toBe(positionArea(ltr));
+ });
+
+ it('keeps position-try fallbacks intact', async () => {
+ const style = await openAndGetStyle(
+ <Harness placement="below" alignment="start" />,
+ );
+ expect(style).toContain(
+ 'position-try-fallbacks: flip-block, flip-inline, flip-block flip-inline',
+ );
+ });
+ });
+
+ describe("positioning='custom' (consumer-authored position styles)", () => {
+ // Consumers like Carousel and Tokenizer keep useLayer's popover behavior
+ // and anchor wiring but position the layer themselves. The opt-out must
+ // suppress every placement-derived style — position-area and the try
+ // fallbacks — so those consumers never need to know which properties
+ // the hook would have emitted.
+ function CustomHarness({
+ triggerStyle,
+ renderProps,
+ }: {
+ triggerStyle?: React.CSSProperties;
+ renderProps: ContextRenderProps;
+ }) {
+ const layer = useLayer({mode: 'context'});
+ return (
+ <>
+ <button
+ type="button"
+ ref={layer.ref}
+ style={triggerStyle}
+ onClick={layer.isOpen ? layer.hide : layer.show}>
+ trigger
+ </button>
+ {layer.render(<span>content</span>, renderProps)}
+ </>
+ );
+ }
+
+ it('keeps the anchor wiring but derives no placement styles', async () => {
+ const style = await openAndGetStyle(
+ <CustomHarness
+ renderProps={{
+ positioning: 'custom',
+ style: {positionArea: 'center'},
+ }}
+ />,
+ );
+ expect(style).toContain('position-anchor');
+ // The consumer-authored area is the only one present…
+ expect(style).toContain('position-area: center');
+ // …and no placement-derived styles leak through.
+ expect(style).not.toContain('position-try-fallbacks');
+ });
+
+ it('ignores placement and alignment when positioning is custom', async () => {
+ // placement/alignment are documented as ignored under custom. Derived
+ // output would be position-area "self-block-end span-self-inline-end";
+ // none of it may appear.
+ const style = await openAndGetStyle(
+ <CustomHarness
+ renderProps={{
+ positioning: 'custom',
+ placement: 'below',
+ alignment: 'start',
+ style: {positionArea: 'center'},
+ }}
+ />,
+ );
+ expect(style).toContain('position-anchor');
+ expect(style).toContain('position-area: center');
+ expect(style).not.toContain('self-block');
+ expect(style).not.toContain('position-try-fallbacks');
+ });
+
+ it('emits only the anchor wiring when custom positioning passes no style at all', async () => {
+ // The strongest suppression probe: with no consumer style in the merge
+ // (Tokenizer's insets-only shape reduces to this in jsdom), nothing can
+ // clobber a leaked derived value — any position-area or try-fallbacks
+ // in the output is a genuine leak.
+ const style = await openAndGetStyle(
+ <CustomHarness renderProps={{positioning: 'custom'}} />,
+ );
+ expect(style).toContain('position-anchor');
+ expect(style).not.toContain('position-area');
+ expect(style).not.toContain('position-try-fallbacks');
+ });
+ });
+
+ it('fixed mode emits no anchor-positioning styles', async () => {
+ function FixedHarness() {
+ const layer = useLayer({mode: 'fixed'});
+ return (
+ <>
+ <button type="button" onClick={layer.show}>
+ opener
+ </button>
+ {layer.render(<span>content</span>, {x: 10, y: 20})}
+ </>
+ );
+ }
+
+ const user = userEvent.setup();
+ const {container, getByRole} = render(<FixedHarness />);
+ await user.click(getByRole('button', {name: 'opener'}));
+
+ const style =
+ container.querySelector('[popover]')?.getAttribute('style') ?? '';
+ expect(style).not.toContain('position-area');
+ expect(style).not.toContain('position-anchor');
+ });
+});
diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx
index 557d6e6a67..3c74390dba 100644
--- a/packages/core/src/Layer/useLayer.tsx
+++ b/packages/core/src/Layer/useLayer.tsx
@@ -9,7 +9,8 @@
* @position Core layer utility; used by useHoverCard, useTooltip, etc.
*
* SYNC: When modified, update:
- * - /packages/core/src/Layer/Layer.doc.mjs
+ * - /packages/core/src/Layer/useLayer.doc.mjs
+ * - /packages/core/src/Layer/useLayer.test.tsx
* - /packages/core/src/Layer/index.ts
*/
@@ -52,7 +53,9 @@ const styles = stylex.create({
});
/**
- * Position placement relative to anchor
+ * Position placement relative to anchor.
+ * Logical: start/end resolve against the popover's own inherited direction
+ * via CSS (RTL contexts mirror automatically, no JS involved).
*/
export type LayerPlacement = 'above' | 'below' | 'start' | 'end';
@@ -65,7 +68,31 @@ export type LayerAlignment = 'start' | 'center' | 'end';
* Render props for context mode (anchor positioning)
*/
export interface ContextRenderProps {
+ /**
+ * Who authors the layer's position styles.
+ *
+ * `'anchor'` (default): the hook derives CSS anchor-positioning styles —
+ * `position-area` and `position-try-fallbacks` — from the logical
+ * `placement`/`alignment`.
+ *
+ * `'custom'`: the consumer authors its own position styles via `style`
+ * (e.g. explicit `anchor()` insets or an `anchor-size()` cover). The hook
+ * keeps the popover behavior and the `position-anchor` wiring but emits no
+ * placement-derived styles, so direction handling becomes the consumer's
+ * responsibility. `placement`/`alignment` are ignored.
+ *
+ * @default 'anchor'
+ */
+ positioning?: 'anchor' | 'custom';
+ /**
+ * Logical placement relative to the anchor. Ignored when `positioning`
+ * is `'custom'`.
+ */
placement?: LayerPlacement;
+ /**
+ * Alignment along the placement axis. Ignored when `positioning`
+ * is `'custom'`.
+ */
alignment?: LayerAlignment;
/**
* ARIA role applied to the popover container (e.g. `'tooltip'`). Lets
@@ -252,40 +279,45 @@ export interface FixedLayerReturn {
}
/**
- * Map placement and alignment to CSS position-area value.
+ * Map logical placement/alignment to a CSS position-area value.
+ *
+ * Uses the self-* logical keyword family: the inline axis resolves against
+ * the popover's own inherited direction (the layer renders inside the
+ * trigger's subtree, so it inherits `direction` and mirrors in RTL with no
+ * JS). The block axis is direction-neutral but must come from the same
+ * keyword family — mixing physical `top` with `self-inline-*` produces an
+ * invalid position-area (computes to `none`, which pins the popover to the
+ * viewport corner because styles.base zeroes the UA margins).
+ *
+ * Note the plain logical family (`inline-start`, no `self-`) is NOT a
+ * substitute: it resolves against the containing block — the page root for
+ * a top-layer popover — so it ignores `direction` set on a subtree, which
+ * is exactly #3389's repro.
*/
function getPositionArea(
placement: LayerPlacement = 'above',
alignment: LayerAlignment = 'center',
): string {
- const placementMap: Record<LayerPlacement, string> = {
- above: 'top',
- below: 'bottom',
- start: 'left',
- end: 'right',
- };
-
- const cssPlacement = placementMap[placement];
-
- // For above/below, alignment is horizontal
if (placement === 'above' || placement === 'below') {
+ const block = placement === 'above' ? 'self-block-start' : 'self-block-end';
if (alignment === 'start') {
- return `${cssPlacement} span-right`;
+ return `${block} span-self-inline-end`;
}
if (alignment === 'end') {
- return `${cssPlacement} span-left`;
+ return `${block} span-self-inline-start`;
}
- return cssPlacement; // center
+ return block; // center
}
- // For start/end, alignment is vertical
+ const inline =
+ placement === 'start' ? 'self-inline-start' : 'self-inline-end';
if (alignment === 'start') {
- return `${cssPlacement} span-bottom`;
+ return `${inline} span-self-block-end`;
}
if (alignment === 'end') {
- return `${cssPlacement} span-top`;
+ return `${inline} span-self-block-start`;
}
- return `${cssPlacement} center`;
+ return inline; // center
}
/**
@@ -321,18 +353,18 @@ export function useLayer(
const isOpenRef = useRef(false);
const show = useCallback(() => {
- const el = popoverRef.current;
- if (el && !isOpenRef.current) {
+ const popover = popoverRef.current;
+ if (popover && !isOpenRef.current) {
// Finding infra-4: the Popover API is unsupported on Safari <17 and
// Firefox <125. On those browsers `showPopover` does not exist, so
// calling it unconditionally throws a TypeError and the layer never
// opens. Guard behind a feature check; when the API is missing, fall
// back to plain visibility (the [popover] attribute is inert there, so
// the element sits in normal flow) so the layer still becomes visible.
- if (typeof el.showPopover === 'function') {
- el.showPopover();
+ if (typeof popover.showPopover === 'function') {
+ popover.showPopover();
} else {
- el.style.display = 'block';
+ popover.style.display = 'block';
}
isOpenRef.current = true;
setIsOpen(true);
@@ -461,6 +493,7 @@ export function useLayer(
const {
placement = 'above',
alignment = 'center',
+ positioning = 'anchor',
role,
xstyle,
className: extraClassName,
@@ -471,11 +504,17 @@ export function useLayer(
} = props || {};
// CSS anchor positioning (dynamic, not in StyleX)
- const anchorStyle: React.CSSProperties = {
- positionAnchor: anchorId,
- positionArea: getPositionArea(placement, alignment),
- positionTryFallbacks: 'flip-block, flip-inline, flip-block flip-inline',
- };
+ const anchorStyle: React.CSSProperties =
+ positioning === 'custom'
+ ? // Consumer authors its own position styles via `style` — keep
+ // only the anchor wiring, derive nothing from placement.
+ {positionAnchor: anchorId}
+ : {
+ positionAnchor: anchorId,
+ positionArea: getPositionArea(placement, alignment),
+ positionTryFallbacks:
+ 'flip-block, flip-inline, flip-block flip-inline',
+ };
const stylexResult = stylex.props(styles.base, xstyle);
const combinedClassName = extraClassName
diff --git a/packages/core/src/Popover/Popover.doc.mjs b/packages/core/src/Popover/Popover.doc.mjs
index 10f3a3bd55..0579c20bc4 100644
--- a/packages/core/src/Popover/Popover.doc.mjs
+++ b/packages/core/src/Popover/Popover.doc.mjs
@@ -36,13 +36,13 @@ export const docs = {
{
name: 'placement',
type: "'above' | 'below' | 'start' | 'end'",
- description: 'Position placement relative to the trigger.',
+ description: 'Position placement relative to the trigger. Logical: start/end resolve against the popover\'s own inherited direction, so RTL contexts mirror automatically in pure CSS.',
default: "'below'",
},
{
name: 'alignment',
type: "'start' | 'center' | 'end'",
- description: 'Alignment along the placement axis.',
+ description: 'Alignment along the placement axis. Logical: start/end follow the popover\'s own inherited direction (RTL mirrors).',
default: "'start'",
},
{
@@ -177,13 +177,13 @@ export const docsZh = {
{
name: 'placement',
type: "'above' | 'below' | 'start' | 'end'",
- description: '相对于触发器的位置放置方式。',
+ description: '相对于触发器的位置放置方式。逻辑值:start/end 根据弹出层自身继承的方向解析,RTL 环境通过纯 CSS 自动镜像。',
default: "'below'",
},
{
name: 'alignment',
type: "'start' | 'center' | 'end'",
- description: '沿放置轴的对齐方式。',
+ description: '沿放置轴的对齐方式。逻辑值:start/end 跟随弹出层自身继承的方向(RTL 镜像)。',
default: "'start'",
},
{
@@ -305,8 +305,8 @@ export const docsDense = {
children: 'Trigger element. Must contain <button> or [role="button"] element.',
anchorRef: 'External ref for popover anchor in sibling mode.',
content: 'Content displayed inside popover.',
- placement: 'Position relative to trigger.',
- alignment: 'Alignment along placement axis.',
+ placement: 'Position relative to trigger. Logical: start/end resolve against the popover\'s inherited direction (RTL mirrors).',
+ alignment: 'Alignment along placement axis. Logical: start/end follow the popover\'s inherited direction (RTL mirrors).',
isOpen: 'Whether popover shown in controlled mode.',
onOpenChange: 'Callback fired when popover visibility changes.',
isEnabled: 'When false, trigger interactions ignored.',
diff --git a/packages/core/src/Popover/usePopover.doc.mjs b/packages/core/src/Popover/usePopover.doc.mjs
index 0368ca1964..90b74a964e 100644
--- a/packages/core/src/Popover/usePopover.doc.mjs
+++ b/packages/core/src/Popover/usePopover.doc.mjs
@@ -29,7 +29,7 @@ export const docs = {
{name: 'toggle', type: '() => void', description: 'Toggle the popover open or closed.'},
{name: 'isOpen', type: 'boolean', description: 'Whether the popover is currently open.'},
{name: 'id', type: 'string', description: 'Unique ID for aria-describedby or aria-controls.'},
- {name: 'render', type: '(children: ReactNode, props?: ContextRenderProps) => ReactNode', description: 'Render function for anchor-positioned popover content. Pass placement and alignment here.'},
+ {name: 'render', type: '(children: ReactNode, props?: ContextRenderProps) => ReactNode', description: 'Render function for anchor-positioned popover content. Pass placement and alignment here. Logical: start/end resolve against the popover\'s own inherited direction (RTL mirrors in pure CSS).'},
{name: 'triggerProps', type: '{aria-haspopup: "dialog" | "true"; aria-expanded: boolean; aria-controls: string}', description: 'ARIA attributes to spread onto the trigger element. aria-haspopup reflects the popover role.'},
],
usage: {
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index debb1cf14b..dbb81c8877 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -186,7 +186,33 @@ describe('Selector', () => {
.getByRole('listbox', {hidden: true})
.closest('[popover]');
expect(popover?.getAttribute('style')).toContain(
- 'position-area: top span-right',
+ 'position-area: self-block-start span-self-inline-end',
+ );
+ });
+
+ it('emits the direction-independent logical mapping under an RTL ancestor (#3389)', async () => {
+ // The self-* position-area keywords resolve against the popover's own
+ // inherited direction in the browser, so RTL emits the same string as
+ // LTR and the mirroring is pure CSS — jsdom can only assert the string.
+ const user = userEvent.setup();
+ render(
+ <div style={{direction: 'rtl'}}>
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Banana"
+ onChange={() => {}}
+ />
+ </div>,
+ );
+
+ await user.click(screen.getByRole('combobox'));
+
+ const popover = screen
+ .getByRole('listbox', {hidden: true})
+ .closest('[popover]');
+ expect(popover?.getAttribute('style')).toContain(
+ 'position-area: self-block-end span-self-inline-end',
);
});
diff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsx
index a8c03ed01a..0f9a0cda58 100644
--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx
+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx
@@ -479,6 +479,60 @@ describe('Tokenizer', () => {
expect(screen.getByText('Charlie')).toBeInTheDocument();
});
+ it('unfocusedLayer: RTL emits no justify-self into the inset-positioned popover', () => {
+ // The popover positions itself with explicit anchor() insets
+ // (positioning: 'custom'), so none of useLayer's placement-derived
+ // styles may reach it — an RTL justify-self with insets and no
+ // position-area would re-align the box inside the inset-modified
+ // containing block instead of hugging the anchor.
+ const original = window.getComputedStyle;
+ let root: HTMLElement | null = null;
+ const spy = vi
+ .spyOn(window, 'getComputedStyle')
+ .mockImplementation((el, pseudo) => {
+ const style = original(el, pseudo);
+ if (root && el instanceof Element && root.contains(el)) {
+ Object.defineProperty(style, 'direction', {
+ value: 'rtl',
+ configurable: true,
+ });
+ }
+ return style;
+ });
+
+ try {
+ const {container} = render(
+ <div style={{direction: 'rtl'}}>
+ <Tokenizer
+ label="Members"
+ searchSource={userSource}
+ value={[users[0], users[1], users[2]]}
+ onChange={() => {}}
+ tokenOverflowBehavior="unfocusedLayer"
+ data-testid="tokenizer"
+ />
+ </div>,
+ );
+ root = container.firstElementChild as HTMLElement;
+
+ fireEvent.focusIn(screen.getByTestId('tokenizer'));
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalled();
+
+ const popover = container.querySelector('[popover]');
+ const style = popover?.getAttribute('style') ?? '';
+ // jsdom drops anchor() values for known properties (top/left), so
+ // anchor the positive check on position-anchor instead. The negative
+ // checks are meaningful: jsdom serializes both justify-self and
+ // position-area when emitted (the DropdownMenu RTL test relies on it).
+ expect(style).toContain('position-anchor');
+ expect(style).not.toContain('justify-self');
+ expect(style).not.toContain('position-area');
+ expect(style).not.toContain('position-try-fallbacks');
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
it('unfocusedLayer: collapses on blur', () => {
const {container} = render(
<Tokenizer
diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsx
index bcc0358202..632b5e2089 100644
--- a/packages/core/src/Tokenizer/Tokenizer.tsx
+++ b/packages/core/src/Tokenizer/Tokenizer.tsx
@@ -684,9 +684,11 @@ export function Tokenizer<T extends SearchableItem>({
);
});
+ // Self-authored position styles (positioning: 'custom' below): explicit
+ // anchor() insets pin the expanded layer over the field itself.
+ // `left` is physical, so this popover does not yet mirror in RTL —
+ // known follow-up from #3389.
const popoverOverrideStyle: React.CSSProperties = {
- positionArea: undefined,
- positionTryFallbacks: undefined,
top: 'anchor(top)',
left: 'anchor(start)',
};
@@ -846,8 +848,7 @@ export function Tokenizer<T extends SearchableItem>({
{wrapperContent}
</div>,
{
- placement: 'below',
- alignment: 'start',
+ positioning: 'custom',
xstyle: styles.layerPopover,
style: popoverOverrideStyle,
},
diff --git a/packages/core/src/Tooltip/Tooltip.doc.mjs b/packages/core/src/Tooltip/Tooltip.doc.mjs
index 2035a68159..4c977658e4 100644
--- a/packages/core/src/Tooltip/Tooltip.doc.mjs
+++ b/packages/core/src/Tooltip/Tooltip.doc.mjs
@@ -39,13 +39,13 @@ export const docs = {
{
name: 'placement',
type: "'above' | 'below' | 'start' | 'end'",
- description: 'Position relative to the anchor element.',
+ description: "Position relative to the anchor element. Logical: start/end resolve against the popover\'s own inherited direction (RTL mirrors in pure CSS).",
default: "'above'",
},
{
name: 'alignment',
type: "'start' | 'center' | 'end'",
- description: 'Alignment along the placement axis.',
+ description: "Alignment along the placement axis. Logical: start/end resolve against the popover\'s own inherited direction (RTL mirrors in pure CSS).",
default: "'center'",
},
{
@@ -138,13 +138,13 @@ export const docsZh = {
{
name: 'placement',
type: "'above' | 'below' | 'start' | 'end'",
- description: '相对于锚点元素的位置。',
+ description: '相对于锚点元素的位置。逻辑值:start/end 根据弹出层自身继承的方向解析(RTL 镜像)。',
default: "'above'",
},
{
name: 'alignment',
type: "'start' | 'center' | 'end'",
- description: '沿放置轴的对齐方式。',
+ description: '沿放置轴的对齐方式。逻辑值:start/end 根据弹出层自身继承的方向解析(RTL 镜像)。',
default: "'center'",
},
{
@@ -230,8 +230,8 @@ export const docsDense = {
children: 'Trigger element(s) that activate tooltip.',
anchorRef: 'External anchor ref for sibling mode.',
content: 'Tooltip content, typically short text.',
- placement: 'Position relative to anchor.',
- alignment: 'Alignment along placement axis.',
+ placement: 'Position relative to anchor. Logical: start/end follow the popover\'s inherited direction (RTL mirrors).',
+ alignment: 'Alignment along placement axis. Logical: start/end follow the popover\'s inherited direction (RTL mirrors).',
delay: 'Show delay in ms.',
hideDelay: 'Hide delay in ms.',
focusTrigger: 'Controls when focus events trigger tooltip.',
diff --git a/packages/core/src/Tooltip/useTooltip.doc.mjs b/packages/core/src/Tooltip/useTooltip.doc.mjs
index 61f503381b..1150c1707a 100644
--- a/packages/core/src/Tooltip/useTooltip.doc.mjs
+++ b/packages/core/src/Tooltip/useTooltip.doc.mjs
@@ -7,8 +7,8 @@ export const docs = {
group: 'Tooltip',
keywords: ['tooltip', 'hint', 'label', 'hover', 'info', 'title', 'floating'],
params: [
- {name: 'placement', type: "'above' | 'below' | 'start' | 'end'", description: 'Position relative to the trigger.', default: "'above'"},
- {name: 'alignment', type: "'start' | 'center' | 'end'", description: 'Alignment along the placement axis.', default: "'center'"},
+ {name: 'placement', type: "'above' | 'below' | 'start' | 'end'", description: "Position relative to the trigger. Logical: start/end resolve against the popover\'s own inherited direction (RTL mirrors in pure CSS).", default: "'above'"},
+ {name: 'alignment', type: "'start' | 'center' | 'end'", description: "Alignment along the placement axis. Logical: start/end resolve against the popover\'s own inherited direction (RTL mirrors in pure CSS).", default: "'center'"},
{name: 'delay', type: 'number', description: 'Delay before showing on hover, in milliseconds.', default: '200'},
{name: 'hideDelay', type: 'number', description: 'Delay before hiding after mouse or focus leaves, in milliseconds.', default: '0'},
{name: 'focusTrigger', type: "'auto' | 'always' | 'never'", description: 'When focus should open the tooltip. auto only attaches focus listeners to naturally focusable elements.', default: "'auto'"},
@@ -24,7 +24,7 @@ export const docs = {
{name: 'interactionRef', type: 'RefCallback<HTMLElement>', description: 'Ref for the hover/focus interaction element.'},
{name: 'anchorId', type: 'string', description: 'CSS anchor name for advanced positioning cases.'},
{name: 'describedBy', type: 'string', description: 'ID to compose into aria-describedby on the trigger.'},
- {name: 'renderTooltip', type: '(children: ReactNode, props?: ContextRenderProps) => ReactNode', description: 'Render function for the anchor-positioned tooltip content.'},
+ {name: 'renderTooltip', type: "(children: ReactNode, props?: Omit<ContextRenderProps, 'positioning'>) => ReactNode", description: 'Render function for the anchor-positioned tooltip content. The positioning opt-out is excluded: the tooltip always derives its position from placement/alignment.'},
],
usage: {
description: 'Headless hook for hover/focus-triggered tooltips. Builds on useLayer with hover intent, keyboard focus handling, and accessible aria-describedby linking. Use for custom trigger elements that need tooltip behavior without the wrapper component.',
@@ -44,8 +44,8 @@ export const docs = {
export const docsDense = {
description: 'Headless hover/focus tooltip hook. Builds on useLayer w/ hover intent, keyboard focus handling, aria-describedby. Use for custom triggers without wrapper component.',
paramDescriptions: {
- placement: 'position relative to trigger.',
- alignment: 'alignment along placement axis.',
+ placement: 'position relative to trigger. logical: start/end follow the popover\'s inherited direction (RTL mirrors).',
+ alignment: 'alignment along placement axis. logical: start/end follow the popover\'s inherited direction (RTL mirrors).',
delay: 'show delay in ms.',
hideDelay: 'hide delay after mouse/focus leave in ms.',
focusTrigger: 'when focus opens tooltip; auto = naturally focusable elements only.',
diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsx
index bd74d332e8..68d0d2ac5a 100644
--- a/packages/core/src/Tooltip/useTooltip.tsx
+++ b/packages/core/src/Tooltip/useTooltip.tsx
@@ -190,8 +190,15 @@ export interface TooltipReturn {
/**
* Render function for tooltip content.
* Returns anchor-positioned popover element.
+ *
+ * `positioning` is excluded: the tooltip always derives its position from
+ * placement/alignment, so accepting the custom opt-out here would be a
+ * silent no-op.
*/
- renderTooltip: (children: ReactNode, props?: ContextRenderProps) => ReactNode;
+ renderTooltip: (
+ children: ReactNode,
+ props?: Omit<ContextRenderProps, 'positioning'>,
+ ) => ReactNode;
}
/**
@@ -463,7 +470,10 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
// Render function that wraps layer.render with tooltip styling
const renderTooltip = useCallback(
- (children: ReactNode, props?: ContextRenderProps): ReactNode => {
+ (
+ children: ReactNode,
+ props?: Omit<ContextRenderProps, 'positioning'>,
+ ): ReactNode => {
const renderPlacement = props?.placement ?? placement;
const renderProps = {
placement: renderPlacement,
diff --git a/packages/core/src/TopNav/TopNav.test.tsx b/packages/core/src/TopNav/TopNav.test.tsx
index 3406a8c8df..48c6a805fb 100644
--- a/packages/core/src/TopNav/TopNav.test.tsx
+++ b/packages/core/src/TopNav/TopNav.test.tsx
@@ -46,9 +46,7 @@ describe('TopNav', () => {
});
it('renders heading slot content', () => {
- render(
- <TopNav heading={<span data-testid="title-content">Logo</span>} />,
- );
+ render(<TopNav heading={<span data-testid="title-content">Logo</span>} />);
expect(screen.getByTestId('title-content')).toBeInTheDocument();
});
@@ -243,7 +241,9 @@ describe('TopNavHeading', () => {
});
it('names a logo-only link via logoLabel', () => {
- render(<TopNavHeading logo={logo} headingHref="/home" logoLabel="Home" />);
+ render(
+ <TopNavHeading logo={logo} headingHref="/home" logoLabel="Home" />,
+ );
expect(screen.getByRole('link', {name: 'Home'})).toHaveAttribute(
'href',
'/home',
@@ -295,9 +295,7 @@ describe('TopNavItem', () => {
});
it('renders children instead of label when provided', () => {
- render(
- <TopNavItem label="Accessible name">Custom content</TopNavItem>,
- );
+ render(<TopNavItem label="Accessible name">Custom content</TopNavItem>);
expect(screen.getByText('Custom content')).toBeInTheDocument();
});
diff --git a/packages/core/src/hooks/useTreeFocus.test.tsx b/packages/core/src/hooks/useTreeFocus.test.tsx
index cc697f84b6..1376988774 100644
--- a/packages/core/src/hooks/useTreeFocus.test.tsx
+++ b/packages/core/src/hooks/useTreeFocus.test.tsx
@@ -44,9 +44,7 @@ function Tree({
const nodes = isOpen && expanded.length > 0 ? expanded : collapsed;
const {treeRef, handleKeyDown} = useTreeFocus<HTMLUListElement>({
onToggleExpand: () => setIsOpen(o => !o),
- onActivate: onActivate
- ? (_item, id) => onActivate(id)
- : undefined,
+ onActivate: onActivate ? (_item, id) => onActivate(id) : undefined,
});
return (
<ul ref={treeRef} role="tree" onKeyDown={handleKeyDown}>