An open source design system that's fully customizable and agent ready
TypeScript
feat(layer): the layer runtime owns the viewport inset (spec:AST-059) (#6919)
Cindy Zhangd45599cb835d
diff --git a/.changeset/layer-owns-the-viewport-inset.md b/.changeset/layer-owns-the-viewport-inset.mdnew file mode 100644index 0000000000..fdafd7f689--- /dev/null+++ b/.changeset/layer-owns-the-viewport-inset.md@@ -0,0 +1,15 @@+---+'@astryxdesign/core': patch+---++[feat] The layer runtime owns the viewport inset: one gutter, one cap, one fallback order, and one place an app declares a floating bar.++Every anchored layer — Popover, DropdownMenu and its submenus, Typeahead, Tooltip, HoverCard, the selectors — now keeps the same gutter from each viewport edge (the spacing-4 step or the device safe-area inset, whichever is larger) and is capped to the viewport. Four components used to carry their own copies of that gutter, and they had drifted.++- An explicit `width` on `Popover` and `menuWidth` on `DropdownMenu` or `Typeahead` render at their size up to the viewport. They used to be capped to the room beside the trigger, so a 352px menu opened from a control near a panel edge rendered 274px wide.+- A layer that does not fit beside its trigger flips; one that fits on neither side keeps its size and slides into view while its trigger is on screen. Once the trigger has left the viewport the layer holds its position and size instead of chasing the edge.+- An app that floats a persistent bar over a viewport edge — a phone navigation bar — declares it once, as `inset` on the `LayerProvider` it already mounts: `<LayerProvider inset={{blockEnd: 56}}>`. Every anchored layer then ends above the bar, and the toast viewport rises by the same amount, so one bar is declared once for both. Every edge defaults to zero, so nothing moves by default; an existing `toast.inset` keeps its meaning as the toast-only override.++One additive prop (`LayerProvider.inset`, type `LayerInset`); no other prop, type, or default changes. `spec:AST-059` holds the decisions; the `Core/Layer` stories show each behavior.++@cixzhangdiff --git a/.github/scripts/story-play-guard.js b/.github/scripts/story-play-guard.jsindex 4900a5e4da..0c6d00f1f2 100644--- a/.github/scripts/story-play-guard.js+++ b/.github/scripts/story-play-guard.js@@ -41,7 +41,8 @@ const TARGETS = [{component: 'Selector',story: 'core-selector--size-variants',- guards: 'compact and wide-spacing triggers match their size tokens, large label text stays unclipped, and multiline values grow by one text row',+ guards:+ 'compact and wide-spacing triggers match their size tokens, large label text stays unclipped, and multiline values grow by one text row',},{component: 'MultiSelector',@@ -98,6 +99,101 @@ const TARGETS = [guards:'on a coarse pointer, the compact combobox and full Clear all hit area remain separate in RTL as well',},+ // spec:AST-059 — the layer runtime's viewport inset. Each story is one+ // claim of the record; the guard is its rendered evidence, at a desktop+ // viewport and at a phone's, because a cap that holds only where the+ // viewport is wider than the layer is no cap. Every play also asserts the+ // first painted frame equals the settled one (FR8).+ ...[+ {+ story: 'core-layer--content-fits-beside-trigger',+ guards:+ 'FR2/FR4: a content-sized layer with room beside its trigger stays start-aligned at its content size',+ },+ {+ story: 'core-layer--content-does-not-fit-beside-trigger',+ guards:+ 'FR2/FR4: unwrappable content flips at its size where it fits the viewport and is capped to the viewport where it does not',+ },+ {+ story: 'core-layer--explicit-size-near-edge',+ guards:+ 'FR2: a 352px end-aligned layer 45px from the edge renders at min(352px, cap), on screen',+ },+ {+ story: 'core-layer--trigger-near-edge-flips',+ guards:+ 'FR4: a 320px start-aligned layer near the end edge flips to end alignment and keeps the gutter',+ },+ {+ story: 'core-layer--neither-side-fits',+ guards:+ 'FR2/FR4: a 1000px layer on a centred trigger slides inside the gutters where it fits the viewport and is capped where it does not',+ },+ {+ story: 'core-layer--trigger-near-the-bottom-flips',+ guards:+ 'FR4: a layer placed below a trigger with no room below flips above, inside the block gutters',+ },+ {+ story: 'core-layer--wide-layer-near-the-bottom-flips',+ guards:+ 'FR2/FR4: a layer wider than the room beside its trigger, placed below with no room below, is capped to the viewport and flips above',+ },+ {+ story: 'core-layer--taller-than-the-viewport',+ guards:+ 'FR3: the layer box is capped to the viewport minus both block gutters',+ },+ {+ story: 'core-layer--anchor-leaves-the-viewport',+ guards:+ 'FR5: an open layer follows its anchor out of the viewport with its size intact and does not pin to the edge',+ },+ {+ story: 'core-layer--anchor-already-off-screen',+ guards:+ 'FR5/FR8: a layer opened with its anchor off-screen holds beside the anchor from its first frame',+ },+ {+ story: 'core-layer--app-declared-inset',+ guards:+ 'FR6: LayerProvider inset lifts the bottom gutter so a layer flips above a trigger near a declared bar',+ },+ {+ story: 'core-layer--inset-changes-while-open',+ guards:+ 'FR6/FR8: changing the provider inset moves an open layer in the same frame, with no later shift',+ },+ {+ story: 'core-layer--layer-opens-as-inset-arrives',+ guards:+ 'FR6/FR8: a layer mounted open in the same commit as its provider is above the bar in its first frame',+ },+ {+ story: 'core-layer--measured-inset',+ guards:+ 'FR6/FR8: an inset the app measures and declares before paint reaches the layer in that same frame',+ },+ {+ story: 'core-layer--portaled-outside-the-provider-subtree',+ guards:+ 'FR6: a layer portaled out of its JSX position still receives the provider inset',+ },+ {+ story: 'core-layer--gutter-at-the-edge',+ guards:+ 'FR1: a wrapping layer beside a flush trigger stops 16px short of the viewport edge',+ },+ ].flatMap(target => [+ {component: 'Layer', ...target},+ {+ component: 'Layer (phone)',+ ...target,+ viewport: {width: 390, height: 844},+ hasTouch: true,+ },+ ]),{component: 'TabList',story: 'core-tablist--full-bleed-geometry',@@ -216,7 +312,7 @@ async function run() {try {for (const target of TARGETS) {const context = await browser.newContext({- viewport: {width: 1280, height: 900},+ viewport: target.viewport ?? {width: 1280, height: 900},hasTouch: target.hasTouch === true,});const page = await context.newPage();diff --git a/apps/storybook/stories/Layer.stories.tsx b/apps/storybook/stories/Layer.stories.tsxindex 07f6c8ce87..482eb2f98b 100644--- a/apps/storybook/stories/Layer.stories.tsx+++ b/apps/storybook/stories/Layer.stories.tsx@@ -1,6 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {useRef, useState} from 'react';+import {useLayoutEffect, useRef, useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import * as stylex from '@stylexjs/stylex';import {useLayer} from '@astryxdesign/core/Layer';@@ -406,3 +406,1079 @@ export const InlineTriggerHosting: Story = {},},};++// =============================================================================+// Viewport inset — spec:AST-059+// =============================================================================+//+// Each story below is a claim in `docs/specs/AST-059-layer-viewport-inset`+// a person can open and look at, and a geometry assertion the story play+// guard runs in real Chromium at two viewports — 1280×900 and a 390×844+// phone — so a claim that holds only where the viewport is wider than the+// layer is caught. The assertions read the layer's rectangle synchronously+// after the opening click commits: that is the geometry of the first frame+// the browser paints (FR8). Each then settles and reads again; any+// difference is a paint-then-shift and fails.++const GUTTER = 16; // --spacing-4+const TOLERANCE = 1.5;++const viewportStyles = stylex.create({+ canvas: {+ position: 'relative',+ boxSizing: 'border-box',+ inlineSize: '100%',+ minBlockSize: '100dvh',+ overflow: 'clip',+ },+ wideCanvas: {+ inlineSize: 3000,+ minBlockSize: '100dvh',+ position: 'relative',+ },+ caption: {+ position: 'absolute',+ insetBlockStart: 16,+ insetInlineStart: 16,+ maxInlineSize: 'calc(100% - 32px)',+ fontSize: 13,+ lineHeight: 1.5,+ color: 'var(--color-text-secondary)',+ margin: 0,+ },+ // A raw useLayer surface. The runtime caps the layer box to the viewport;+ // what happens to content wider or taller than that is the surface's — here+ // it reads the same cap and scrolls, as Popover does once it measures+ // overflow.+ surface: {+ boxSizing: 'border-box',+ backgroundColor: 'var(--color-background-surface)',+ border: '2px solid var(--color-border-accent, #6366f1)',+ borderRadius: 8,+ padding: 12,+ fontSize: 14,+ lineHeight: 1.4,+ maxInlineSize: stylex.firstThatWorks(+ 'calc(100vi - 32px)',+ 'calc(100vw - 32px)',+ ),+ maxBlockSize: stylex.firstThatWorks(+ 'calc(100dvb - 32px)',+ 'calc(100vh - 32px)',+ ),+ overflow: 'auto',+ },+ nowrap: {whiteSpace: 'nowrap'},+ tall: {+ blockSize: 2000,+ inlineSize: 200,+ background:+ 'repeating-linear-gradient(to bottom, transparent 0 39px, var(--color-border-default) 39px 40px)',+ },+ explicitWidth: (width: number) => ({width}),+ bottomBar: {+ position: 'fixed',+ insetBlockEnd: 0,+ insetInlineStart: 0,+ insetInlineEnd: 0,+ backgroundColor: 'var(--color-background-inverse, #111)',+ color: 'var(--color-text-inverse, #fff)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: 13,+ },+ barHeight: (height: number) => ({blockSize: height}),+ controls: {+ position: 'fixed',+ insetBlockStart: 8,+ insetInlineEnd: 8,+ display: 'flex',+ gap: 8,+ zIndex: 1,+ },+});++type Pos = {+ top?: number | string;+ left?: number | string;+ right?: number | string;+ bottom?: number | string;+};+type Placement = 'above' | 'below' | 'start' | 'end';+type Alignment = 'start' | 'center' | 'end';++function ViewportLayer({+ at,+ placement = 'below',+ alignment = 'start',+ width,+ children,+ caption,+ canvasXstyle,+ extra,+ isOpenInitially = false,+}: {+ at: Pos;+ placement?: Placement;+ alignment?: Alignment;+ width?: number;+ children: React.ReactNode;+ caption: string;+ canvasXstyle?: stylex.StyleXStyles;+ extra?: React.ReactNode;+ isOpenInitially?: boolean;+}) {+ const layer = useLayer({mode: 'context', lightDismiss: true});+ const openedRef = useRef(false);+ useLayoutEffect(() => {+ if (isOpenInitially && !openedRef.current) {+ openedRef.current = true;+ layer.show();+ }+ }, [isOpenInitially, layer]);+ return (+ <div+ {...stylex.props(viewportStyles.canvas, canvasXstyle)}+ data-testid="canvas">+ <p {...stylex.props(viewportStyles.caption)}>{caption}</p>+ <div style={{position: 'absolute', ...at}}>+ <Button+ ref={layer.ref}+ label="Open"+ size="sm"+ data-testid="trigger"+ onClick={() => (layer.isOpen ? layer.hide() : layer.show())}+ />+ </div>+ {layer.render(+ <div {...stylex.props(viewportStyles.surface)}>{children}</div>,+ {+ placement,+ alignment,+ offset: 4,+ xstyle: width != null ? viewportStyles.explicitWidth(width) : null,+ },+ )}+ {extra}+ </div>+ );+}++const nextFrame = () => new Promise(r => requestAnimationFrame(() => r(null)));+// React commits a discrete event's state update in a microtask; microtasks+// run before the browser paints, so a read after this is still the first+// frame's geometry.+const committed = () => new Promise(r => queueMicrotask(() => r(null)));+const settle = async () => {+ await nextFrame();+ await nextFrame();+};++type Rects = {+ trigger: DOMRect;+ layer: DOMRect;+ vw: number;+ vh: number;+};++function rects(canvasElement: HTMLElement): Rects {+ const trigger = canvasElement.querySelector<HTMLElement>(+ '[data-testid="trigger"]',+ );+ const layer = document.querySelector<HTMLElement>(+ '[popover]:popover-open[id]',+ );+ if (!trigger || !layer) {+ throw new Error('No open layer');+ }+ return {+ trigger: trigger.getBoundingClientRect(),+ layer: layer.getBoundingClientRect(),+ vw: window.innerWidth,+ vh: window.innerHeight,+ };+}++/** The largest inline size a layer may take at this viewport (FR2). */+const inlineCap = (r: Rects) => r.vw - 2 * GUTTER;++function sameRect(a: DOMRect, b: DOMRect) {+ return (+ Math.abs(a.left - b.left) <= TOLERANCE &&+ Math.abs(a.top - b.top) <= TOLERANCE &&+ Math.abs(a.width - b.width) <= TOLERANCE &&+ Math.abs(a.height - b.height) <= TOLERANCE+ );+}++/**+ * Click the trigger, read the first frame's geometry synchronously (the+ * discrete event flushes React and the rect read forces layout), then settle+ * and read again. A difference is a paint-then-shift (FR8).+ */+async function open(canvasElement: HTMLElement): Promise<Rects> {+ canvasElement.querySelector<HTMLElement>('[data-testid="trigger"]')?.click();+ const first = rects(canvasElement);+ await settle();+ const settled = rects(canvasElement);+ assertNoShift(first, settled, 'after opening');+ return settled;+}++function assertNoShift(first: Rects, settled: Rects, when: string) {+ if (!sameRect(first.layer, settled.layer)) {+ fail(+ `Paint-then-shift ${when}: first frame ${fmt(first.layer)}, settled ${fmt(settled.layer)}`,+ );+ }+}++const fmt = (r: DOMRect) =>+ `${Math.round(r.left)}..${Math.round(r.right)} × ${Math.round(r.top)}..${Math.round(r.bottom)} (${Math.round(r.width)}w)`;++/** What the browser resolved for the open layer; appended to every failure. */+function diagnose(): string {+ const layer = document.querySelector<HTMLElement>(+ '[popover]:popover-open[id]',+ );+ if (!layer) {+ return 'no open layer';+ }+ const cs = getComputedStyle(layer);+ const read = (prop: string) => cs.getPropertyValue(prop).trim();+ return [+ `position-area=${read('position-area')}`,+ `fallbacks=${read('position-try-fallbacks')}`,+ `justify-self=${read('justify-self')} align-self=${read('align-self')}`,+ `inset t/r/b/l=${read('top')}/${read('right')}/${read('bottom')}/${read('left')}`,+ `margin t/r/b/l=${read('margin-top')}/${read('margin-right')}/${read('margin-bottom')}/${read('margin-left')}`,+ `max w/h=${read('max-width')}/${read('max-height')}`,+ `inline style=${layer.getAttribute('style') ?? ''}`,+ ].join('\n ');+}++function fail(message: string): never {+ throw new Error(`${message}\n ${diagnose()}`);+}++function assertOnScreen(r: Rects, label: string, gutter = GUTTER) {+ const {layer, vw, vh} = r;+ if (+ layer.left < gutter - TOLERANCE ||+ layer.right > vw - gutter + TOLERANCE ||+ layer.top < gutter - TOLERANCE ||+ layer.bottom > vh - gutter + TOLERANCE+ ) {+ fail(+ `${label}: layer ${fmt(layer)} leaves the ${gutter}px gutter in a ${vw}×${vh} viewport`,+ );+ }+}++/** An explicit width renders at its size, or at the cap when it is larger. */+function assertWidth(r: Rects, asked: number, label: string) {+ const expected = Math.min(asked, inlineCap(r));+ if (Math.abs(r.layer.width - expected) > TOLERANCE) {+ throw new Error(+ `${label}: asked ${asked}px, cap ${inlineCap(r)}px, rendered ${Math.round(r.layer.width)}px`,+ );+ }+}++const viewportParameters = {+ layout: 'fullscreen',+ docs: {story: {inline: false, height: '600px'}},+};++export const ContentFitsBesideTrigger: Story = {+ name: 'Viewport inset: content-sized, fits beside the trigger',+ parameters: viewportParameters,+ render: () => (+ <ViewportLayer+ at={{top: 120, left: 40}}+ caption="FR2, FR4 — A content-sized layer with room beside its trigger sizes to its content and stays start-aligned to the trigger. Nothing caps it to the span; nothing moves it.">+ <span {...stylex.props(viewportStyles.nowrap)}>Four short rows</span>+ </ViewportLayer>+ ),+ play: async ({canvasElement}) => {+ const r = await open(canvasElement);+ if (Math.abs(r.layer.left - r.trigger.left) > TOLERANCE) {+ throw new Error(+ `Expected the layer to stay start-aligned to the trigger (${r.trigger.left}), got ${r.layer.left}`,+ );+ }+ if (r.layer.width < 120) {+ throw new Error(`Layer shrank to ${r.layer.width}px`);+ }+ assertOnScreen(r, 'fits beside');+ },+};++export const ContentDoesNotFitBesideTrigger: Story = {+ name: 'Viewport inset: content-sized, does not fit beside the trigger',+ parameters: viewportParameters,+ render: () => (+ <ViewportLayer+ at={{top: 120, right: 60}}+ caption="FR2, FR4 — The trigger sits 60px from the inline-end edge and the layer's content cannot wrap. Where the content fits the viewport (desktop), the layer keeps its size and flips to end alignment instead of being squeezed into the room beside the trigger. Where it does not fit the viewport at all (a phone), the layer is capped to the viewport minus its gutters and the content scrolls inside it.">+ <span {...stylex.props(viewportStyles.nowrap)}>+ Unbreakable-label-that-cannot-wrap-to-fit-beside-the-trigger+ </span>+ </ViewportLayer>+ ),+ play: async ({canvasElement}) => {+ const r = await open(canvasElement);+ const cap = inlineCap(r);+ if (r.layer.width < Math.min(300, cap) - TOLERANCE) {+ throw new Error(`Layer was squeezed to ${r.layer.width}px`);+ }+ if (r.layer.width > cap + TOLERANCE) {+ throw new Error(`Layer ${r.layer.width}px exceeds the cap ${cap}px`);+ }+ if (+ r.layer.width < cap - TOLERANCE &&+ Math.abs(r.layer.right - r.trigger.right) > TOLERANCE+ ) {+ throw new Error(+ `Expected a flip to end alignment (right ${r.trigger.right}), got right ${r.layer.right}`,+ );+ }+ assertOnScreen(r, 'does not fit beside');+ },+};++export const ExplicitSizeNearEdge: Story = {+ name: 'Viewport inset: explicit size near an edge (352px)',+ parameters: viewportParameters,+ render: () => (+ <ViewportLayer+ at={{top: 120, left: 45}}+ alignment="end"+ width={352}+ caption="FR2 — An end-aligned layer given width 352 on a trigger 45px from the inline-start edge. The room beside the trigger is 45px plus the trigger; the layer renders at 352px anyway, flipped to start alignment, never shrunk to 274px.">+ A 352px panel+ </ViewportLayer>+ ),+ play: async ({canvasElement}) => {+ const r = await open(canvasElement);+ assertWidth(r, 352, 'explicit size');+ assertOnScreen(r, 'explicit size');+ },+};++export const TriggerNearEdgeFlips: Story = {+ name: 'Viewport inset: trigger near an edge flips',+ parameters: viewportParameters,+ render: () => (+ <ViewportLayer+ at={{top: 120, right: 80}}+ width={320}+ caption="FR4 — A start-aligned 320px layer on a trigger 80px from the inline-end edge flips to end alignment: its inline-end edge meets the trigger's, and it keeps the 16px gutter from the viewport edge.">+ Flipped to the other side+ </ViewportLayer>+ ),+ play: async ({canvasElement}) => {+ const r = await open(canvasElement);+ assertWidth(r, 320, 'flip');+ // A flip is the answer where the end side has room for 320px (desktop);+ // on a phone neither side does and the layer slides instead (FR4).+ const roomOnEndSide = r.trigger.right - GUTTER;+ if (+ roomOnEndSide >= 320 &&+ Math.abs(r.layer.right - r.trigger.right) > TOLERANCE+ ) {+ throw new Error(+ `Expected the flipped layer's end edge at ${r.trigger.right}, got ${r.layer.right}`,+ );+ }+ assertOnScreen(r, 'flip');+ },+};++export const NeitherSideFits: Story = {+ name: 'Viewport inset: neither side fits',+ parameters: viewportParameters,+ render: () => (+ <ViewportLayer+ at={{top: 120, left: 'calc(50% - 20px)'}}+ width={1000}+ caption="FR2, FR4 — A 1000px layer on a centred trigger fits on neither side of it. Where 1000px fits the viewport, it keeps its size and slides along the inline axis the least distance that brings it inside the gutters. Where it does not, it is capped to the viewport minus the gutters.">+ Too wide for either side; slid into view+ </ViewportLayer>+ ),+ play: async ({canvasElement}) => {+ const r = await open(canvasElement);+ assertWidth(r, 1000, 'neither side fits');+ assertOnScreen(r, 'neither side fits');+ },+};++function assertAbove(r: Rects, label: string) {+ if (r.layer.bottom > r.trigger.top + TOLERANCE) {+ fail(+ `${label}: expected the layer above its trigger (trigger top ${Math.round(r.trigger.top)}), layer ${fmt(r.layer)}`,+ );+ }+}++export const TriggerNearTheBottomFlips: Story = {+ name: 'Viewport inset: trigger near the bottom flips above',+ parameters: viewportParameters,+ render: () => (+ <ViewportLayer+ at={{bottom: 60, left: 40}}+ width={240}+ caption="FR4 — A 240px layer placed below a trigger 60px from the bottom edge has no room below and flips above. The block axis follows the same rule as the inline axis.">+ <div style={{blockSize: 90}}>90px of rows</div>+ </ViewportLayer>+ ),+ play: async ({canvasElement}) => {+ const r = await open(canvasElement);+ assertAbove(r, 'near the bottom');+ assertOnScreen(r, 'near the bottom');+ },+};++export const WideLayerNearTheBottomFlips: Story = {+ name: 'Viewport inset: wide layer, trigger near the bottom',+ parameters: viewportParameters,+ render: () => (+ <ViewportLayer+ at={{bottom: 60, left: 40}}+ width={690}+ caption="FR2, FR4 — A 690px layer placed below a trigger 60px from the bottom edge. On a phone the width is capped to the viewport and fits beside the trigger on neither side; the layer still flips above, because the slide option spans the whole inline axis and leaves the block axis free to choose the side with room.">+ <div style={{blockSize: 90}}>90px of rows</div>+ </ViewportLayer>+ ),+ play: async ({canvasElement}) => {+ const r = await open(canvasElement);+ assertWidth(r, 690, 'wide near the bottom');+ assertAbove(r, 'wide near the bottom');+ assertOnScreen(r, 'wide near the bottom');+ },+};++export const TallerThanTheViewport: Story = {+ name: 'Viewport inset: taller than the viewport',+ parameters: viewportParameters,+ render: () => (+ <ViewportLayer+ at={{top: 120, left: 40}}+ caption="FR3 — Content 2000px tall. The layer box is capped to the viewport minus both block gutters; the surface inside scrolls.">+ <div {...stylex.props(viewportStyles.tall)}>2000px of rows</div>+ </ViewportLayer>+ ),+ play: async ({canvasElement}) => {+ const r = await open(canvasElement);+ if (r.layer.height > r.vh - 2 * GUTTER + TOLERANCE) {+ fail(+ `Layer block size ${r.layer.height}px exceeds the viewport minus gutters (${r.vh - 2 * GUTTER}px)`,+ );+ }+ // Taller than either side can hold: capped and shifted into the viewport,+ // keeping its anchor clearance rather than the gutter on the edge it+ // meets (FR4). Inside the viewport on the block axis; gutters inline.+ if (r.layer.top < -TOLERANCE || r.layer.bottom > r.vh + TOLERANCE) {+ fail(`Layer ${fmt(r.layer)} leaves the viewport`);+ }+ if (+ r.layer.left < GUTTER - TOLERANCE ||+ r.layer.right > r.vw - GUTTER + TOLERANCE+ ) {+ fail(`Layer ${fmt(r.layer)} leaves the inline gutter`);+ }+ },+};++// Anchor visibility is observed, not polled; give the observer its+// rendering opportunity and the fallback re-evaluation that follows.+const scrollAndSettle = async (x: number) => {+ window.scrollTo(x, 0);+ await settle();+ await new Promise(resolve => setTimeout(resolve, 600));+ await settle();+};++export const AnchorLeavesTheViewport: Story = {+ name: 'Viewport inset: anchor leaves the viewport',+ parameters: viewportParameters,+ render: () => (+ <ViewportLayer+ at={{top: 120, left: 200}}+ width={320}+ canvasXstyle={viewportStyles.wideCanvas}+ caption="FR5 — Scroll the page sideways until the trigger leaves the viewport. The open layer goes with it and keeps its 320px: it does not slide toward the edge and pin itself into the strip that is left. Scroll back and it is where it was.">+ Holds position and size+ </ViewportLayer>+ ),+ play: async ({canvasElement}) => {+ const before = await open(canvasElement);+ await scrollAndSettle(before.trigger.right + 400);+ const away = rects(canvasElement);+ if (away.trigger.right > 0) {+ throw new Error(+ `Fixture: trigger still in view at ${away.trigger.left}..${away.trigger.right}`,+ );+ }+ if (Math.abs(away.layer.width - before.layer.width) > TOLERANCE) {+ throw new Error(+ `Layer changed size with its anchor off-screen: ${before.layer.width} → ${away.layer.width}`,+ );+ }+ if (away.layer.left >= 0) {+ throw new Error(+ `Layer slid toward the viewport edge (left ${away.layer.left}) while its anchor is at ${away.trigger.left}`,+ );+ }+ await scrollAndSettle(0);+ const back = rects(canvasElement);+ if (Math.abs(back.layer.width - before.layer.width) > TOLERANCE) {+ fail(+ `Layer changed size after its anchor returned: ${before.layer.width} → ${back.layer.width}`,+ );+ }+ // Where the layer fit beside its trigger it comes back to the same+ // place. A layer that had to slide (a phone) is a recorded verification+ // gap (spec:AST-059 VG1): Chromium does not re-run the slide when the pin+ // is withdrawn, so the layer can return start-aligned to its anchor and+ // off-screen until its next layout. Asserted here only where it fit.+ const fitBeside = before.layer.left >= before.trigger.left - TOLERANCE;+ if (fitBeside) {+ assertOnScreen(back, 'after the anchor returned');+ if (Math.abs(back.layer.left - before.layer.left) > TOLERANCE) {+ fail(+ `Layer did not return with its anchor: ${before.layer.left} → ${back.layer.left}`,+ );+ }+ }+ },+};++export const AnchorAlreadyOffScreen: Story = {+ name: 'Viewport inset: anchor already off-screen when the layer opens',+ parameters: viewportParameters,+ render: () => (+ <ViewportLayer+ at={{top: 120, left: 200}}+ width={320}+ canvasXstyle={viewportStyles.wideCanvas}+ caption="FR5, FR8 — The page is scrolled so the trigger is off-screen before the layer opens. The first painted frame already holds beside the anchor; it does not open pinned to the viewport edge and then move.">+ Opened with its anchor out of view+ </ViewportLayer>+ ),+ play: async ({canvasElement}) => {+ const trigger = canvasElement.querySelector<HTMLElement>(+ '[data-testid="trigger"]',+ );+ if (!trigger) {+ throw new Error('No trigger');+ }+ await scrollAndSettle(trigger.getBoundingClientRect().right + 400);+ if (trigger.getBoundingClientRect().right > 0) {+ throw new Error('Fixture: trigger still in view');+ }+ const r = await open(canvasElement);+ if (r.layer.left >= 0) {+ throw new Error(+ `First frame pinned the layer to the viewport (left ${r.layer.left}) while its anchor is at ${r.trigger.left}`,+ );+ }+ await scrollAndSettle(0);+ },+};++function AppInsetDemo({+ initialInset,+ isOpenInitially,+}: {+ initialInset: number;+ isOpenInitially?: boolean;+}) {+ const [inset, setInset] = useState(initialInset);+ return (+ <LayerProvider inset={{blockEnd: inset}}>+ <ViewportLayer+ at={{bottom: 270, left: 40}}+ isOpenInitially={isOpenInitially}+ caption={`FR6, FR8 — The app floats a ${inset}px bar over the bottom edge and declares it once: <LayerProvider inset={{blockEnd: ${inset}}}>. The layer's bottom gutter becomes ${inset + 16}px, so a layer that would end under the bar flips above its trigger instead. (Storybook already mounts the root provider, so this one is nested and narrows the inset for the layers in this story; an app declares it on its root provider and its toasts rise too.) Change the inset while the layer is open: the layer and the bar move in the same frame.`}+ extra={+ <>+ <div+ {...stylex.props(+ viewportStyles.bottomBar,+ viewportStyles.barHeight(inset),+ )}>+ persistent bar — {inset}px, outside layout flow+ </div>+ <div {...stylex.props(viewportStyles.controls)}>+ <Button+ label="Bar 80"+ size="sm"+ variant="secondary"+ data-testid="inset-80"+ onClick={() => setInset(80)}+ />+ <Button+ label="Bar 160"+ size="sm"+ variant="secondary"+ data-testid="inset-160"+ onClick={() => setInset(160)}+ />+ </div>+ </>+ }>+ <div style={{blockSize: 90}}>90px of rows</div>+ </ViewportLayer>+ </LayerProvider>+ );+}++function assertAboveBar(r: Rects, bar: number, label: string) {+ if (r.layer.bottom > r.vh - bar - GUTTER + TOLERANCE) {+ fail(+ `${label}: layer ends at ${r.layer.bottom}px (trigger ${fmt(r.trigger)}), under the ${bar}px bar (viewport ${r.vh}px)`,+ );+ }+}++export const AppDeclaredInset: Story = {+ name: 'Viewport inset: app-declared inset (floating bar)',+ parameters: viewportParameters,+ render: () => <AppInsetDemo initialInset={160} />,+ play: async ({canvasElement}) => {+ const r = await open(canvasElement);+ assertAboveBar(r, 160, 'declared 160px');+ if (r.layer.bottom > r.trigger.top) {+ throw new Error('Expected the layer to flip above the trigger');+ }+ },+};++export const InsetChangesWhileOpen: Story = {+ name: 'Viewport inset: inset changes while the layer is open',+ parameters: viewportParameters,+ render: () => <AppInsetDemo initialInset={80} />,+ play: async ({canvasElement}) => {+ const at80 = await open(canvasElement);+ // With an 80px bar the 90px layer fits below its trigger.+ if (at80.layer.top < at80.trigger.bottom) {+ throw new Error('Fixture: expected the layer below its trigger at 80px');+ }+ canvasElement+ .querySelector<HTMLElement>('[data-testid="inset-160"]')+ ?.click();+ await committed();+ const first = rects(canvasElement);+ assertAboveBar(first, 160, 'first frame after the inset changed');+ await settle();+ assertNoShift(first, rects(canvasElement), 'after the inset changed');+ },+};++export const LayerOpensAsInsetArrives: Story = {+ name: 'Viewport inset: layer opens in the frame the inset arrives',+ parameters: viewportParameters,+ render: () => <AppInsetDemo initialInset={160} isOpenInitially />,+ play: async ({canvasElement}) => {+ // The provider mounts with its inset and the layer opens in the same+ // commit; the first frame is already above the bar.+ const first = rects(canvasElement);+ assertAboveBar(first, 160, 'first frame');+ await settle();+ assertNoShift(first, rects(canvasElement), 'after mounting open');+ },+};++function MeasuredBarDemo() {+ const barRef = useRef<HTMLDivElement>(null);+ const [tall, setTall] = useState(false);+ const [measured, setMeasured] = useState(0);+ // The app measures its own bar before paint and declares what it found.+ useLayoutEffect(() => {+ const bar = barRef.current;+ if (!bar) {+ return;+ }+ setMeasured(bar.getBoundingClientRect().height);+ }, [tall]);+ return (+ <LayerProvider inset={{blockEnd: measured}}>+ <ViewportLayer+ at={{bottom: 270, left: 40}}+ caption={`FR6, FR8 — The bar's height is measured by the app (${measured}px) and declared on LayerProvider. The runtime measures nothing: it renders at whatever the provider declares, in the same frame the declaration changes.`}+ extra={+ <>+ <div+ ref={barRef}+ {...stylex.props(+ viewportStyles.bottomBar,+ viewportStyles.barHeight(tall ? 160 : 80),+ )}>+ measured bar — {measured}px+ </div>+ <div {...stylex.props(viewportStyles.controls)}>+ <Button+ label={tall ? 'Shrink bar' : 'Grow bar'}+ size="sm"+ variant="secondary"+ data-testid="toggle-bar"+ onClick={() => setTall(v => !v)}+ />+ </div>+ </>+ }>+ <div style={{blockSize: 90}}>90px of rows</div>+ </ViewportLayer>+ </LayerProvider>+ );+}++export const MeasuredInset: Story = {+ name: 'Viewport inset: inset measured by the app',+ parameters: viewportParameters,+ render: () => <MeasuredBarDemo />,+ play: async ({canvasElement}) => {+ const r = await open(canvasElement);+ assertAboveBar(r, 80, 'measured 80px');+ canvasElement+ .querySelector<HTMLElement>('[data-testid="toggle-bar"]')+ ?.click();+ await committed();+ // The app's layout effect re-measured and re-declared before this paint.+ const first = rects(canvasElement);+ assertAboveBar(first, 160, 'first frame after the bar grew');+ await settle();+ assertNoShift(first, rects(canvasElement), 'after the bar grew');+ },+};++function PortaledLayerDemo() {+ const layer = useLayer({mode: 'context', lightDismiss: true});+ return (+ <div {...stylex.props(viewportStyles.canvas)} data-testid="canvas">+ <p {...stylex.props(viewportStyles.caption)}>+ FR6, FR8 — The trigger sits inside a paragraph, which cannot contain the+ layer, so the layer portals out of it. The declared 160px inset still+ reaches it: the value travels by context and is written on the layer+ itself, not inherited from the provider's subtree.+ </p>+ <p style={{position: 'absolute', bottom: 270, left: 40, margin: 0}}>+ <Button+ ref={layer.ref}+ label="Open"+ size="sm"+ data-testid="trigger"+ onClick={() => (layer.isOpen ? layer.hide() : layer.show())}+ />+ {layer.render(+ <div {...stylex.props(viewportStyles.surface)}>+ <div style={{blockSize: 90}}>90px of rows</div>+ </div>,+ {placement: 'below', alignment: 'start', offset: 4},+ )}+ </p>+ <div+ {...stylex.props(+ viewportStyles.bottomBar,+ viewportStyles.barHeight(160),+ )}>+ persistent bar — 160px+ </div>+ </div>+ );+}++export const PortaledOutsideTheProviderSubtree: Story = {+ name: 'Viewport inset: layer portaled out of its JSX position',+ parameters: viewportParameters,+ render: () => (+ <LayerProvider inset={{blockEnd: 160}}>+ <PortaledLayerDemo />+ </LayerProvider>+ ),+ play: async ({canvasElement}) => {+ const r = await open(canvasElement);+ const layer = document.querySelector<HTMLElement>(+ '[popover]:popover-open[id]',+ );+ if (layer?.closest('p')) {+ throw new Error('Fixture: the layer did not portal out of the paragraph');+ }+ assertAboveBar(r, 160, 'portaled layer');+ },+};++export const GutterAtTheEdge: Story = {+ name: 'Viewport inset: the gutter',+ parameters: viewportParameters,+ render: () => (+ <ViewportLayer+ at={{top: 120, right: 0}}+ caption="FR1 — The trigger is flush with the inline-end edge. The layer's content can wrap, so it fits beside the trigger by wrapping, and its inline-end edge stops 16px short of the viewport. (The device safe-area term of the gutter cannot be shown here: Chromium emulation does not populate env(safe-area-inset-*).)">+ <span>+ Prose that wraps keeps the gutter rather than flipping or sliding, so a+ layer never touches the viewport edge.+ </span>+ </ViewportLayer>+ ),+ play: async ({canvasElement}) => {+ const r = await open(canvasElement);+ if (r.layer.right > r.vw - GUTTER + TOLERANCE) {+ throw new Error(+ `Layer end edge ${r.layer.right} is inside the ${GUTTER}px gutter (viewport ${r.vw})`,+ );+ }+ },+};++// -----------------------------------------------------------------------------+// Playground — an exploration instrument, not a claim. Drag the trigger+// anywhere (touch or mouse); the layer stays open and follows. Adjust width,+// placement, and alignment from the canvas; read the resolved geometry.+// -----------------------------------------------------------------------------++const playgroundStyles = stylex.create({+ canvas: {+ position: 'fixed',+ inset: 0,+ overflow: 'clip',+ touchAction: 'none',+ },+ handle: {+ position: 'absolute',+ touchAction: 'none',+ userSelect: 'none',+ cursor: 'grab',+ },+ panel: {+ position: 'fixed',+ insetBlockStart: 8,+ insetInlineStart: 8,+ insetInlineEnd: 8,+ display: 'flex',+ flexWrap: 'wrap',+ gap: 6,+ alignItems: 'center',+ fontSize: 12,+ lineHeight: 1.4,+ padding: 8,+ borderRadius: 8,+ backgroundColor: 'var(--color-background-surface)',+ boxShadow: 'var(--shadow-low)',+ zIndex: 1,+ },+ readout: {+ position: 'fixed',+ insetBlockEnd: 8,+ insetInlineStart: 8,+ insetInlineEnd: 8,+ fontFamily: 'ui-monospace, monospace',+ fontSize: 11,+ lineHeight: 1.5,+ padding: 8,+ borderRadius: 8,+ backgroundColor: 'var(--color-background-surface)',+ boxShadow: 'var(--shadow-low)',+ whiteSpace: 'pre-wrap',+ zIndex: 1,+ },+ select: {+ fontSize: 12,+ padding: 4,+ },+});++type Readout = {+ box: string;+ within: string;+ resolved: string;+};++function readGeometry(trigger: HTMLElement, layer: HTMLElement): Readout {+ const t = trigger.getBoundingClientRect();+ const l = layer.getBoundingClientRect();+ const vw = window.innerWidth;+ const vh = window.innerHeight;+ const side =+ l.bottom <= t.top + 1+ ? 'above'+ : l.top >= t.bottom - 1+ ? 'below'+ : l.right <= t.left + 1+ ? 'start'+ : l.left >= t.right - 1+ ? 'end'+ : 'overlapping';+ const isBlock = side === 'above' || side === 'below';+ const align = isBlock+ ? Math.abs(l.left - t.left) <= 1+ ? 'start'+ : Math.abs(l.right - t.right) <= 1+ ? 'end'+ : Math.abs(l.left + l.width / 2 - (t.left + t.width / 2)) <= 1+ ? 'center'+ : 'slid'+ : Math.abs(l.top - t.top) <= 1+ ? 'start'+ : Math.abs(l.bottom - t.bottom) <= 1+ ? 'end'+ : Math.abs(l.top + l.height / 2 - (t.top + t.height / 2)) <= 1+ ? 'center'+ : 'slid';+ const inside =+ l.left >= GUTTER - 1 &&+ l.right <= vw - GUTTER + 1 &&+ l.top >= GUTTER - 1 &&+ l.bottom <= vh - GUTTER + 1;+ return {+ box: `layer ${Math.round(l.width)}×${Math.round(l.height)} at ${Math.round(l.left)},${Math.round(l.top)} · viewport ${vw}×${vh} · cap ${vw - 2 * GUTTER}`,+ within: inside+ ? 'inside the 16px gutters'+ : `OUTSIDE the gutters: left ${Math.round(l.left)} right ${Math.round(vw - l.right)} top ${Math.round(l.top)} bottom ${Math.round(vh - l.bottom)}`,+ resolved: `resolved ${side} / ${align} · anchor ${Math.round(t.left)},${Math.round(t.top)}`,+ };+}++function PlaygroundDemo() {+ const [pos, setPos] = useState({x: 160, y: 200});+ const [width, setWidth] = useState(240);+ const [placement, setPlacement] = useState<Placement>('below');+ const [alignment, setAlignment] = useState<Alignment>('start');+ const [readout, setReadout] = useState<Readout | null>(null);+ const layer = useLayer({mode: 'context', lightDismiss: false});+ const triggerRef = useRef<HTMLButtonElement | null>(null);+ const layerElRef = useRef<HTMLElement | null>(null);+ const dragRef = useRef<{dx: number; dy: number} | null>(null);+ const openedRef = useRef(false);++ useLayoutEffect(() => {+ if (!openedRef.current) {+ openedRef.current = true;+ layer.show();+ }+ }, [layer]);++ // Read after each commit; the readout is display, never an input to layout.+ // Set only when the text changes, or the readout would re-render itself.+ useLayoutEffect(() => {+ const trigger = triggerRef.current;+ const el =+ layerElRef.current ??+ document.querySelector<HTMLElement>('[popover]:popover-open[id]');+ if (trigger && el) {+ layerElRef.current = el;+ const next = readGeometry(trigger, el);+ setReadout(current =>+ current &&+ current.box === next.box &&+ current.within === next.within &&+ current.resolved === next.resolved+ ? current+ : next,+ );+ }+ });++ return (+ <div {...stylex.props(playgroundStyles.canvas)}>+ <div {...stylex.props(playgroundStyles.panel)}>+ <label>+ width{' '}+ <input+ type="range"+ min={80}+ max={1400}+ step={10}+ value={width}+ onChange={e => setWidth(Number(e.target.value))}+ />{' '}+ {width}px+ </label>+ <select+ {...stylex.props(playgroundStyles.select)}+ value={placement}+ aria-label="placement"+ onChange={e => setPlacement(e.target.value as Placement)}>+ {(['above', 'below', 'start', 'end'] as const).map(p => (+ <option key={p} value={p}>+ placement: {p}+ </option>+ ))}+ </select>+ <select+ {...stylex.props(playgroundStyles.select)}+ value={alignment}+ aria-label="alignment"+ onChange={e => setAlignment(e.target.value as Alignment)}>+ {(['start', 'center', 'end'] as const).map(a => (+ <option key={a} value={a}>+ alignment: {a}+ </option>+ ))}+ </select>+ <span>Drag the trigger anywhere; the layer stays open.</span>+ </div>+ <button+ type="button"+ ref={el => {+ triggerRef.current = el;+ layer.ref(el);+ }}+ {...stylex.props(playgroundStyles.handle)}+ style={{left: pos.x, top: pos.y}}+ onPointerDown={e => {+ dragRef.current = {dx: e.clientX - pos.x, dy: e.clientY - pos.y};+ e.currentTarget.setPointerCapture(e.pointerId);+ }}+ onPointerMove={e => {+ const d = dragRef.current;+ if (d) {+ setPos({x: e.clientX - d.dx, y: e.clientY - d.dy});+ }+ }}+ onPointerUp={() => {+ dragRef.current = null;+ }}+ onPointerCancel={() => {+ dragRef.current = null;+ }}>+ drag me+ </button>+ {layer.render(+ <div {...stylex.props(viewportStyles.surface)}>+ <div style={{blockSize: 120}}>+ {placement}/{alignment}, {width}px+ </div>+ </div>,+ {+ placement,+ alignment,+ offset: 4,+ xstyle: viewportStyles.explicitWidth(width),+ },+ )}+ <div {...stylex.props(playgroundStyles.readout)}>+ {readout+ ? `${readout.box}\n${readout.resolved}\n${readout.within}`+ : '…'}+ </div>+ </div>+ );+}++export const Playground: Story = {+ name: 'Viewport inset: playground (drag the trigger)',+ parameters: {+ ...viewportParameters,+ docs: {+ ...viewportParameters.docs,+ description: {+ story:+ 'An exploration instrument, not a claim: drag the trigger to any edge or corner, on a phone or with a mouse, while the layer stays open; change width (past the viewport), placement, and alignment; read the resolved geometry. The pinned stories above are the evidence for each rule — this is how to find the configuration nobody pinned.',+ },+ },+ },+ render: () => <PlaygroundDemo />,+};diff --git a/apps/storybook/stories/Popover.stories.tsx b/apps/storybook/stories/Popover.stories.tsxindex 0798a92446..b445b53133 100644--- a/apps/storybook/stories/Popover.stories.tsx+++ b/apps/storybook/stories/Popover.stories.tsx@@ -98,10 +98,6 @@ const readinessStyles = stylex.create({paddingInlineEnd: spacingVars['--spacing-4'],overflow: 'clip',},- edgeAnchorRow: {- display: 'flex',- justifyContent: 'flex-end',- },oversizedTrigger: {inlineSize: 640,},@@ -676,56 +672,10 @@ export const RenderProp: Story = {// Responsive and Interaction Readiness Evidence// =============================================================================-export const ViewportFit: Story = {- name: 'Viewport Fit',- parameters: {- layout: 'fullscreen',- viewport: {defaultViewport: 'mobile1'},- docs: {- story: {inline: false, height: '844px'},- description: {- story:- 'Uses the actual Storybook viewport rather than a simulated phone frame. The Popover requests a 640px width and must stay anchored to the trigger while preserving at least 16px safe-area-aware gutters from both viewport edges.',- },- },- },- render: () => (- <div {...stylex.props(readinessStyles.viewportStoryCanvas)}>- <div {...stylex.props(readinessStyles.edgeAnchorRow)}>- <Popover- placement="below"- alignment="end"- label="Narrow viewport fit evidence"- width={640}- content={- <VStack gap={3} xstyle={readinessStyles.evidenceCopy}>- <Heading level={4} tabIndex={-1}>- Narrow viewport fit- </Heading>- <Text type="body" wordBreak="break-word">- This intentionally requests a wider-than-mobile popover. The- layer should stay anchored to the trigger, preserve safe gutters- on both viewport edges, and allow long content to reflow instead- of causing horizontal page overflow.- </Text>- <Text type="supporting" wordBreak="break-word">- Long localized-token-like content:- project-settings-notification-delivery-exception-review-queue- </Text>- </VStack>- }>- <Button label="Open fit evidence">Open fit evidence</Button>- </Popover>- </div>- </div>- ),- play: async ({canvasElement}) => {- const trigger = canvasElement.querySelector('button');- if (trigger instanceof HTMLElement) {- trigger.click();- }- },-};+// Viewport geometry — gutters, caps, flips, the slide — is the layer runtime's+// and is demonstrated under Core/Layer (spec:AST-059). Popover keeps the+// stories for what is Popover's own: its match-trigger preference, scrolling,+// focus, dismissal, and surface styling.export const MatchTriggerViewportFit: Story = {name: 'Match-trigger viewport fit',@@ -736,7 +686,7 @@ export const MatchTriggerViewportFit: Story = {story: {inline: false, height: '844px'},description: {story:- 'Uses the actual Storybook viewport. The real trigger is intentionally 640px wide, while Popover keeps its default match-trigger sizing; the Popover must cap to the available viewport instead of inheriting the full trigger width.',+ 'Uses the actual Storybook viewport. The real trigger is intentionally 640px wide, while Popover keeps its default match-trigger sizing; the preference is clamped by the layer runtime\u2019s viewport cap (spec:AST-059 FR7) instead of inheriting the full trigger width.',},},},diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.mdindex 9f197a29f6..7ac6ccfd6f 100644--- a/docs/architecture/layer-runtime.md+++ b/docs/architecture/layer-runtime.md@@ -26,6 +26,8 @@ applies_to:verified_by:[packages/core/src/Layer/useLayer.test.tsx,+ packages/core/src/Layer/layerViewportInset.test.ts,+ packages/core/src/Layer/LayerProvider.test.tsx,packages/core/src/Layer/layerHost.test.ts,packages/core/src/Layer/anchorName.test.ts,packages/core/src/Layer/useLayerDismissal.test.tsx,@@ -38,7 +40,7 @@ verified_by:packages/core/src/hooks/useMenuHover.test.tsx,packages/core/src/Toast/ToastViewport.test.tsx,]-deciding_specs: [spec:AST-038]+deciding_specs: [spec:AST-038, spec:AST-059]---# Layer runtime@@ -49,7 +51,8 @@ deciding_specs: [spec:AST-038]{"scope": "global","triggers": {- "layering": ["INV2", "INV5", "INV6", "INV7"]+ "layering": ["INV2", "INV5", "INV6", "INV7", "INV11", "INV12"],+ "layout": ["INV3", "INV11", "INV12"]}}```@@ -116,8 +119,77 @@ can flip across either axis. Centered placements also gain span fallbacks so thesurface can move along the alignment axis near viewport edges. Clearance isapplied to both edges of the placement axis so a flip retains the gap.-Popover adds component-specific viewport sizing and overflow behavior above this-geometry. Those constraints are not universal Layer behavior.+#### Viewport inset++Anchor mode owns the viewport inset (`spec:AST-059`). Every anchor-mode layer+keeps a gutter from each viewport edge equal to `max(--spacing-4,+env(safe-area-inset-<edge>))` plus the inset the app declares for that edge as+`inset` on `LayerProvider` (`blockStart`, `blockEnd`, `inlineStart`,+`inlineEnd`; zero by default; app configuration, not a theme value). The+provider publishes the declaration through its context; `useLayer` reads it+and writes it inline on the layer element as the custom properties+`--astryx-layer-inset-<logical-edge>` the gutter expressions read, and the+toast viewport writes the same properties on itself from the provider's prop.+Because the value travels by context and not by CSS inheritance, a corrective+portal cannot lose it, and a layer with no provider — nothing written, every+property reading `0px` — renders exactly as one under a default provider. A+hand-written property is an unsupported escape hatch. The inline gutter reads+the larger of the two physical safe-area insets so a flipped layer still clears+a notch. `Layer/layerViewportInset.stylex.ts` holds the one definition. The+gutter is a margin, so the margin box is what must fit a position option and+what the browser's overflow shift keeps inside the viewport: a layer that would+end inside the gutter or under a declared bar does not fit there and the next+option is tried. On the placement axis the gutter rides the far edge beside+the anchor clearance on the near edge; on the alignment axis it rides the far+edge of an aligned layer — one on the anchor-facing edge would push the layer+off its anchor — and both edges of a centered one. The flip tactics swap the+margins with the area, so the clearance stays on the anchor side and the gutter+on the far side, and the placement-axis gutter is one value for both edges —+the larger of the two block gutters — so a bar declared on one block edge keeps+a layer the same distance from the opposite edge.++The layer box is capped to the viewport minus both gutters on both axes, never+to the span of viewport beside the trigger, and never exceeds that cap. An+explicit size renders at its size up to the cap; a content-sized layer wraps to+the room beside its trigger when its content can wrap and keeps its size up to+the cap when it cannot. Content that cannot fit the cap overflows inside the+layer box, where the composing component scrolls or clips it (Popover scrolls+once it measures overflow); the box itself stays on screen. A consumer caps its+painted surface with the same definition and clamps any minimum of its own+(trigger matching, an explicit width or `menuWidth`) with the runtime's cap+expression, because a CSS minimum otherwise wins over a maximum.++The fallback order is the runtime's: preferred position; flip across the+placement axis; flip across the alignment axis; both; then, while the anchor is+in view, the slide: named `@position-try` options (`Layer/layerSlideRules.ts`)+whose area spans the whole alignment axis, same side of the trigger first,+opposite side second, each carrying the gutter on both alignment-axis edges and+the clearance-and-gutter pair of the side it lands on, which the browser's+overflow alignment shifts the least distance that brings the margin box inside+the viewport. Centered layers keep their one-sided spans ahead of the full+span. The slide is its own option because a layer wider than the room on either+side of its trigger overflows every flipped option on the alignment axis, and+the browser would otherwise keep the base option and never move the layer to+the side of the trigger with room on the placement axis. The rules are one+static style sheet the runtime installs in the layer's document head before+the layer's first paint — never inside the layer, where a role-bearing layer's+text would name them to assistive technology, and never beside it, where they+would change a parent's last child.+Content taller than the placement axis can hold on either side is capped to the+viewport minus both gutters and shifted into the viewport by the browser; its+margin box stays inside the viewport, so it keeps its anchor clearance from the+edge it meets.+Once the anchor has left the viewport the runtime pins the layer's+self-alignment `unsafe` toward the anchor, so the layer holds the position its+flips give it and holds its size rather than sliding to the edge. Components+pass no fallbacks of their own to an anchor-mode layer.++Every one of these inputs is resolved by the browser's style and layout in the+same frame as the render that produced it; the runtime measures nothing after+paint to apply them. Anchor visibility is read synchronously in a layout effect+before the layer's first paint and then observed while the layer is open, so a+layer opened with its anchor already out of view holds from its first frame. A+layer never paints at a geometry it is about to correct.### Current browser support behavior@@ -258,8 +330,9 @@ layers use Layer rendering without joining Escape/platform dismissal.- **INV2 — Hosting and promotion are separate.** A React portal moves DOM. NativePopover or modal Dialog APIs control top-layer participation and modalboundaries.-- **INV3 — Positioning modes do not leak.** Anchor mode owns logical placement and- fallbacks; custom mode owns its geometry; fixed mode owns explicit coordinates.+- **INV3 — Positioning modes do not leak.** Anchor mode owns logical placement,+ fallbacks, and the viewport inset; custom mode owns its geometry; fixed mode+ owns explicit coordinates.- **INV4 — Shared anchors compose.** One layer adding or removing its anchor namedoes not overwrite names belonging to sibling layers.- **INV5 — Logical placement remains direction-aware.** Standard anchored@@ -276,9 +349,21 @@ layers use Layer rendering without joining Escape/platform dismissal.- **INV9 — Outside channels remain component-owned and uncoordinated.** Currentbackdrop, pointer, touch, hover/focus, and swipe handlers act through theirowning component or browser mechanism rather than one shared branch operation.-- **INV10 — LayerProvider is Toast configuration, not a universal layer host.**- Trigger-associated layers resolve near their JSX position independently of the- provider.+- **INV10 — LayerProvider is configuration, not a universal layer host.** It+ carries Toast configuration and the app-declared viewport inset. Trigger-+ associated layers resolve near their JSX position independently of the+ provider; the inset reaches them as a context value each layer carries on+ itself, never by resolving placement through the provider, and a layer with+ no provider renders as one under a provider with the default inset.+- **INV11 — One viewport gutter.** The gutter, the viewport caps, and the+ app-declared inset have one definition in the runtime; every anchor-mode layer+ inherits them, the layer box never exceeds the caps, the toast viewport reads+ the same inset, no consumer defines its own, no size is capped to the span+ beside the trigger, and a consumer minimum is clamped by the runtime's cap.+- **INV12 — The first frame is the settled frame.** No input to a layer's+ viewport geometry is measured after paint and then applied; the one runtime+ observation, anchor visibility, is read before first paint. A layer never+ paints at a geometry it is about to correct.This record does not make future eligible-owner, branch-association, global-host,or browser-support requirements current. It does not own component focus entry or@@ -315,7 +400,12 @@ be updated only as that work ships.inheritance, writing context, and reduced-browser behavior.- A positioning change verifies all placement/alignment combinations in LTR andRTL, viewport-edge fallbacks, offsets after flips, shared anchors, custom mode,- and fixed mode.+ and fixed mode; and, through the `Core/Layer` viewport-inset stories in real+ Chromium at a desktop and a phone viewport, an explicit size near an edge,+ content that fits and content that does not fit beside the trigger, a trigger+ where neither side fits, a layer wider than the viewport, an anchor that+ leaves the viewport or is already out of view, an app-declared inset arriving+ or changing, and the first painted frame against the settled one.- A Popover lifecycle change verifies programmatic and browser closes, controlledstate, temporary invoker association, and same-gesture trigger behavior.- A dismissal-stack change updates `family:overlay-dismissal` when membership or@@ -335,6 +425,12 @@ be updated only as that work ships.anchor/fixed/custom rendering, trigger source, and current same-gesture memory.- `Layer/layerHost.ts` owns safe inline versus nearest corrective portal placement.- `Layer/anchorName.ts` owns composition of anchor names on one trigger.+- `Layer/layerViewportInset.stylex.ts` owns the gutter and the viewport caps;+ `Layer/layerSlideRules.ts` owns the slide options' `@position-try` rules;+ `LayerProvider` publishes the declared inset through `LayerContext`, and+ `Layer/layerInset.ts` owns the `--astryx-layer-inset-*` properties a layer or+ the toast viewport writes on itself to carry it; `Layer/clampInlineSize.ts`+ owns the clamp a consumer applies to a size of its own.- `Layer/gestureCounter.ts` owns physical pointer/key gesture identity.- `Layer/layerStack.ts`, `Layer/useLayerDismissal.ts`, and`Layer/LayerDepthContext.tsx` own current registration, presence, ordering, and@@ -354,7 +450,9 @@ be updated only as that work ships.- Lab Drawer owns modal `showModal()` and non-modal `showPopover()` hosting whilethe shared dismissal stack owns Escape and platform close routing.- `LayerProvider`, `ToastContext`, `useToast`, and `ToastViewport` own current- notification state, dispatch, and viewport rendering.+ notification state, dispatch, and viewport rendering; the viewport sits at+ the provider's inset on each edge unless its own `toast.inset` overrides that+ edge.- CommandPalette owns command search and selection; Dialog owns its native modalhost.- `family:overlay-dismissal` owns Escape/platform-close membership.@@ -367,21 +465,29 @@ be updated only as that work ships.`spec:AST-038` governs the layer content boundary projected above. It does notchange the hosting runtime described here.+`spec:AST-059` governs the viewport inset projected above: the gutter, the+caps, the fallback order and its anchor-visibility condition, and the+app-declared inset.+`spec:AST-003` is accepted but unimplemented. It defines the approved nextruntime and must move to `shipped` before its requirements are incorporated intothis current architecture record.## Verification-| 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 |-| 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 |-| INV6, INV7 | `useLayer.test.tsx`, `Popover.test.tsx`, `DropdownMenu.test.tsx`, and `useMenuHover.test.tsx` | Duplicate close callback or the same press/re-hover reopens a surface |-| INV8 | `useLayerDismissal.test.tsx`, `layerDismissalInvariants.test.tsx`, and `useFocusTrap.test.tsx` | Current top registered layer is skipped, two layers close, or a blocker leaks through |-| INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests | A current local channel silently changes ownership or policy |-| INV10 | `LayerProvider.tsx`, `useToast.tsx`, and `ToastViewport.test.tsx` | Provider begins relocating ordinary layers or Toast fallback loses its current lifecycle |+| 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 |+| 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 | 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 |+| INV12 | The `Core/Layer` viewport-inset stories' first-frame comparison, and `useLayer.test.tsx`'s synchronous anchor read | A layer whose first painted rectangle differs from its settled one |+| INV6, INV7 | `useLayer.test.tsx`, `Popover.test.tsx`, `DropdownMenu.test.tsx`, and `useMenuHover.test.tsx` | Duplicate close callback or the same press/re-hover reopens a surface |+| INV8 | `useLayerDismissal.test.tsx`, `layerDismissalInvariants.test.tsx`, and `useFocusTrap.test.tsx` | Current top registered layer is skipped, two layers close, or a blocker leaks through |+| INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests | A current local channel silently changes ownership or policy |+| INV10 | `LayerProvider.tsx`, `LayerProvider.test.tsx`, `useToast.tsx`, and `ToastViewport.test.tsx` | Provider begins relocating ordinary layers, Toast fallback loses its current lifecycle, or a default provider renders differently from no provider |Current unit coverage proves emitted styles, reducers, state transitions, and DOMplacement. Native Popover, `<dialog>`, focus, top-layer ordering, and rendered-anchor geometry require real Chromium and WebKit evidence when changed.+anchor geometry require real Chromium and WebKit evidence when changed. The+device safe-area term of the gutter is not reproducible in Chromium emulation;+it is proven on a device.diff --git a/docs/specs/AST-059-layer-viewport-inset/spec.md b/docs/specs/AST-059-layer-viewport-inset/spec.mdindex 640d58ddf8..86fb61ae80 100644--- a/docs/specs/AST-059-layer-viewport-inset/spec.md+++ b/docs/specs/AST-059-layer-viewport-inset/spec.md@@ -165,15 +165,20 @@ the app reaches every layer instead of the components that happen to read it.preferred position; the flip across the placement axis; the flip across thealignment axis; both flips; then, while its anchor is in view, a slidealong the alignment axis that keeps the layer's size and moves it the least- distance that brings it inside the gutters. Side placements slide along the- block axis. The gutter bounds position as well as size: a layer that would- end inside a gutter, or under a declared bar, does not fit there and the- next option is tried. On the placement axis that positional bound is the- larger of the axis's two gutters, applied to both edges, so a bar declared on- one block edge keeps a layer the same distance from the opposite edge (the- size cap still subtracts each edge's own gutter). Content taller than either- side can hold is capped to the viewport and shifted into it, keeping its- anchor clearance from the edge it meets. The runtime authors this order; a component passes no+ distance that brings it inside the gutters, on the preferred side of the+ trigger first and the opposite side second. The slide is a position option+ of its own, not a side effect of the flips failing: a layer wider than the+ room beside its trigger on both sides still reaches the side of the trigger+ that has room on the placement axis. Side placements slide along the block+ axis. The gutter bounds position as well as size on both axes: a layer that+ would end inside a gutter, or under a declared bar, does not fit there and+ the next option is tried; a slid layer keeps the gutter on both edges. On+ the placement axis that positional bound is the larger of the axis's two+ gutters, applied to both edges, so a bar declared on one block edge keeps a+ layer the same distance from the opposite edge (the size cap still+ subtracts each edge's own gutter). Content taller than either side can hold+ is capped to the viewport and shifted into it, keeping its anchor clearance+ from the edge it meets. The runtime authors this order; a component passes nofallbacks of its own to an anchor-mode layer.- **FR5 — An off-screen anchor holds.** A layer whose anchor has left theviewport does not slide. It keeps the position the flips give it and its@@ -328,16 +333,16 @@ surface styling. A playground story with a draggable trigger and live width,placement, and alignment controls exists for exploration; it is not evidencefor any row.-| Contract | Verification | Representative states | Mutation or failure expectation |-| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| FR1, FR7 | One gutter module; a source scan for a second gutter or a `100%`-of-span cap among anchor-mode layers; story "the gutter" at both viewports | Default gutter at every edge; a wrapping layer beside a trigger flush with the edge | A second gutter constant among anchor-mode layers, or a layer inside the 16px gutter |-| FR2 | Stories "explicit size near an edge (352px)", "content-sized, fits beside the trigger", "content-sized, does not fit beside the trigger", "neither side fits" at both viewports; clamp strings in Popover and DropdownMenu suites | 352px end-aligned on a trigger 45px from the edge; a short content-sized layer; an unbreakable run wider than a phone; a 1000px layer on a phone, where the cap is 358px | A layer narrower than `min(asked, cap)`, a layer box wider than the cap at any viewport, or `100%` of the anchor span in a cap |-| FR3 | Story "taller than the viewport" at both viewports; the runtime's viewport-fit style on every anchor-mode layer | Content 2000px tall | The layer box's block size exceeds the viewport minus gutters |-| FR4 | Stories "content-sized, does not fit beside the trigger", "trigger near an edge flips", "neither side fits" at both viewports | A flip to end alignment at content size and at an explicit size; a 1000px layer slid inside the gutters where it fits | A layer squeezed into the span, a flipped edge off the trigger's edge, or a layer outside the gutters |-| FR5 | Stories "anchor leaves the viewport" and "anchor already off-screen when the layer opens"; the runtime's anchor-visibility unit suite | Horizontal scroll carries the trigger out of view while the layer is open, then back; a layer opened with its anchor already off-screen | The layer slides toward the viewport edge after the anchor is gone, changes size, does not return with its anchor, or opens pinned to the edge |-| FR6 | Stories "app-declared inset (floating bar)" and "layer portaled out of its JSX position"; `LayerProvider` and `ToastViewport` unit suites | An 80px bar declared as `inset={{blockEnd: 80}}`; a toast under the same provider; a `toast.inset` override; no provider; a layer hosted outside the paragraph it was rendered in | A layer or toast ends under the bar, an unset edge moves anything, a `toast.inset` edge stops overriding, no-provider geometry differs from the default provider's, or a portaled layer loses the inset |-| FR8 | Every story above (first frame compared with settled); stories "inset changes while the layer is open", "layer opens in the frame the inset arrives", "inset measured by the app", "anchor already off-screen when the layer opens" | The provider's inset changes 80→160 with the layer open; a layer mounted open in the provider's first commit; a bar the app measures before paint and declares; an off-screen anchor at open | The first frame's rectangle differs from the settled one, or the first frame after a declaration change is not already at the new geometry |-| FR1 safe area | A device run: `env(safe-area-inset-*)` is set only by a real device and Chromium emulation does not populate it, so no Storybook story can show it. | Landscape phone with a notch on one side | A layer under the notch |+| Contract | Verification | Representative states | Mutation or failure expectation |+| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1, FR7 | One gutter module; a source scan for a second gutter or a `100%`-of-span cap among anchor-mode layers; story "the gutter" at both viewports | Default gutter at every edge; a wrapping layer beside a trigger flush with the edge | A second gutter constant among anchor-mode layers, or a layer inside the 16px gutter |+| FR2 | Stories "explicit size near an edge (352px)", "content-sized, fits beside the trigger", "content-sized, does not fit beside the trigger", "neither side fits" at both viewports; clamp strings in Popover and DropdownMenu suites | 352px end-aligned on a trigger 45px from the edge; a short content-sized layer; an unbreakable run wider than a phone; a 1000px layer on a phone, where the cap is 358px | A layer narrower than `min(asked, cap)`, a layer box wider than the cap at any viewport, or `100%` of the anchor span in a cap |+| FR3 | Story "taller than the viewport" at both viewports; the runtime's viewport-fit style on every anchor-mode layer | Content 2000px tall | The layer box's block size exceeds the viewport minus gutters |+| FR4 | Stories "content-sized, does not fit beside the trigger", "trigger near an edge flips", "neither side fits", "trigger near the bottom flips above", "wide layer, trigger near the bottom" at both viewports | A flip to end alignment at content size and at an explicit size; a 1000px layer slid inside the gutters where it fits; a block flip with room only above; a block flip when the inline axis is also capped | A layer squeezed into the span, a flipped edge off the trigger's edge, a layer outside the gutters on either axis, or a layer left on the side with no room |+| FR5 | Stories "anchor leaves the viewport" and "anchor already off-screen when the layer opens"; the runtime's anchor-visibility unit suite | Horizontal scroll carries the trigger out of view while the layer is open, then back; a layer opened with its anchor already off-screen | The layer slides toward the viewport edge after the anchor is gone, changes size, does not return with its anchor, or opens pinned to the edge |+| FR6 | Stories "app-declared inset (floating bar)" and "layer portaled out of its JSX position"; `LayerProvider` and `ToastViewport` unit suites | An 80px bar declared as `inset={{blockEnd: 80}}`; a toast under the same provider; a `toast.inset` override; no provider; a layer hosted outside the paragraph it was rendered in | A layer or toast ends under the bar, an unset edge moves anything, a `toast.inset` edge stops overriding, no-provider geometry differs from the default provider's, or a portaled layer loses the inset |+| FR8 | Every story above (first frame compared with settled); stories "inset changes while the layer is open", "layer opens in the frame the inset arrives", "inset measured by the app", "anchor already off-screen when the layer opens" | The provider's inset changes 80→160 with the layer open; a layer mounted open in the provider's first commit; a bar the app measures before paint and declares; an off-screen anchor at open | The first frame's rectangle differs from the settled one, or the first frame after a declaration change is not already at the new geometry |+| FR1 safe area | A device run: `env(safe-area-inset-*)` is set only by a real device and Chromium emulation does not populate it, so no Storybook story can show it. | Landscape phone with a notch on one side | A layer under the notch |**Verification gap — VG1.** A layer that had to slide (it fit on neitherside of its trigger) and whose anchor leaves and returns can come backdiff --git a/packages/core/src/ComplexSelector/ComplexSelector.test.tsx b/packages/core/src/ComplexSelector/ComplexSelector.test.tsxindex c2f9991100..4013b265d6 100644--- a/packages/core/src/ComplexSelector/ComplexSelector.test.tsx+++ b/packages/core/src/ComplexSelector/ComplexSelector.test.tsx@@ -163,7 +163,7 @@ describe('ComplexSelector', () => {);});- it('gives the popup clearance on both block edges, not just the leading one (#4803)', async () => {+ it('gives the popup clearance on the edge facing the trigger, which a flip carries to the other side (#4803)', async () => {const user = userEvent.setup();render(<FruitComplexSelector@@ -174,14 +174,15 @@ describe('ComplexSelector', () => {await user.click(screen.getByRole('button', {name: 'Fruit blend'}));const popup = document.querySelector('[popover]') as HTMLElement;expect(popup).not.toBeNull();- // Both edges, not just the leading one: the trailing edge is what faces- // the trigger when the same popup opens upward (placement="above") or is- // flipped by position-try-fallbacks. useLayer's `offset` sets both from- // the resolved placement; jsdom resolves neither the var indirection nor- // logical margins, so read the debug-mode declarations it emits.+ // The clearance rides the edge facing the trigger and the viewport gutter+ // the far edge; a position-try flip swaps the two with the area, so the+ // gap survives opening upward (spec:AST-059 FR1, FR4). jsdom resolves+ // neither the var indirection nor logical margins, so read the+ // debug-mode declarations it emits.const blockStart = popup.style.getPropertyValue('--x-marginBlockStart');expect(blockStart).not.toBe('');- expect(popup.style.getPropertyValue('--x-marginBlockEnd')).toBe(blockStart);+ expect(popup.style.getPropertyValue('--x-marginBlockEnd')).toBe('');+ expect(popup.className).toContain('useLayer__styles.placementBelow');});it('runs changeAction through the provided onChange helper', async () => {diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsxindex bebb2bf3bf..e0fe4a3043 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx@@ -521,11 +521,10 @@ describe('DropdownMenu', () => {const popover = screen.getByRole('menu', {hidden: true}).closest('[popover]');- expect(popover?.className).toContain(- 'DropdownMenu__styles.popoverViewportBlockStart',- );+ // The gutter is the layer runtime's (spec:AST-059 FR1, FR7).+ expect(popover?.className).toContain('useLayer__styles.gutterBlockEnd');expect(popover?.className).not.toContain(- 'DropdownMenu__styles.popoverViewportStart',+ 'useLayer__styles.gutterInlineEnd',);});@@ -558,9 +557,13 @@ describe('DropdownMenu', () => {expect(popover?.className).toContain('DropdownMenu__styles.popoverViewport',);- expect(popover?.className).toContain('DropdownMenu__styles.popoverAligned');+ expect(popover?.className).toContain(+ 'DropdownMenu__styles.popoverMatchTrigger',+ );+ // The cap is the viewport, never the span beside the trigger+ // (spec:AST-059 FR2, FR7).expect(popover).toHaveStyle(- 'min-width: min(anchor-size(width),calc(100% - max(var(--spacing-4),env(safe-area-inset-left,0px),env(safe-area-inset-right,0px))))',+ 'min-width: min(anchor-size(width),calc(100vi - calc(max(var(--spacing-4), env(safe-area-inset-left, 0px)) + var(--astryx-layer-inset-inline-start, 0px)) - calc(max(var(--spacing-4), env(safe-area-inset-right, 0px)) + var(--astryx-layer-inset-inline-end, 0px))))',);unmount();@@ -577,7 +580,8 @@ describe('DropdownMenu', () => {'DropdownMenu__styles.popoverViewport',);expect(popover).toHaveStyle({minWidth: 'var(--x-minWidth)'});- expect(popover?.getAttribute('style')).toContain('min(640px, calc(100%');+ expect(popover?.getAttribute('style')).toContain('min(640px, calc(100vw');+ expect(popover?.getAttribute('style')).not.toContain('100%');});it.each(['max-content', 'fit-content', 'auto'])(@@ -598,9 +602,7 @@ describe('DropdownMenu', () => {'DropdownMenu__styles.popoverCustomIntrinsicWidth',);expect(popover?.getAttribute('style')).toContain(menuWidth);- expect(popover?.className).toContain(- 'DropdownMenu__styles.popoverViewportAligned',- );+ expect(popover?.className).toContain('useLayer__styles.gutterInlineEnd');expect(popover?.getAttribute('style')).not.toContain(`min(${menuWidth},`);},);@@ -629,7 +631,7 @@ describe('DropdownMenu', () => {);});expect(menu).toHaveStyle(- 'max-height: min(300px,calc(100dvb - max(var(--spacing-4),env(safe-area-inset-top,0px)) - max(var(--spacing-4),env(safe-area-inset-bottom,0px))))',+ 'max-height: min(300px,calc(100dvb - calc(max(var(--spacing-4), env(safe-area-inset-top, 0px)) + var(--astryx-layer-inset-block-start, 0px)) - calc(max(var(--spacing-4), env(safe-area-inset-bottom, 0px)) + var(--astryx-layer-inset-block-end, 0px))))',);expect(menu).not.toHaveStyle({overflowY: 'auto'});expect(menu).toHaveAttribute('tabindex', '-1');diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex d2227a876e..3a433cae13 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -72,6 +72,7 @@ import {useMenuOverflow} from './useMenuOverflow';import {useDevWarning} from '../hooks/useDevWarning';import {useMenuDrillIn} from './useMenuDrillIn';import {resolveMenuWidth} from './menuWidth';+import {layerViewportInset} from '../Layer/layerViewportInset.stylex';import {useAdaptivePresentation,type AdaptivePresentation,@@ -94,14 +95,11 @@ import {useInteractionModalityTracking} from '../utils/interactionModality';import {useTranslator} from '../i18n';import {focusOutlineStyles} from '../utils/focusOutline.stylex';-const MENU_VIEWPORT_GUTTER = spacingVars['--spacing-4'];-const MENU_MAX_INLINE_SIZE = `calc(100vi - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px)) - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-right, 0px)))`;-const MENU_MAX_INLINE_SIZE_FALLBACK = `calc(100vw - ${MENU_VIEWPORT_GUTTER} - ${MENU_VIEWPORT_GUTTER})`;-const MENU_MAX_BLOCK_SIZE = `min(300px, calc(100dvb - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px)) - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px))))`;-const MENU_MAX_BLOCK_SIZE_FALLBACK = `min(300px, calc(100vh - ${MENU_VIEWPORT_GUTTER} - ${MENU_VIEWPORT_GUTTER}))`;-const MENU_POSITION_AREA_MAX_INLINE_SIZE = `calc(100% - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px), env(safe-area-inset-right, 0px)))`;-const MENU_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK = `calc(100% - ${MENU_VIEWPORT_GUTTER})`;-const MENU_INLINE_EDGE_GUTTER = `max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px), env(safe-area-inset-right, 0px))`;+// The menu's own lower cap on the placement axis; the viewport cap underneath+// it is the layer runtime's (spec:AST-059 FR3).+const MENU_BLOCK_CAP = '300px';+const MENU_MAX_BLOCK_SIZE = `min(${MENU_BLOCK_CAP}, ${layerViewportInset.maxBlockSize})`;+const MENU_MAX_BLOCK_SIZE_FALLBACK = `min(${MENU_BLOCK_CAP}, ${layerViewportInset.maxBlockSizeFallback})`;const MENU_TRIGGER_OPEN_BACKGROUND = `linear-gradient(${colorVars['--color-overlay-pressed']}, ${colorVars['--color-overlay-pressed']})`;const styles = stylex.create({@@ -129,8 +127,8 @@ const styles = stylex.create({WebkitTouchCallout: 'none',userSelect: 'none',maxInlineSize: stylex.firstThatWorks(- MENU_MAX_INLINE_SIZE,- MENU_MAX_INLINE_SIZE_FALLBACK,+ layerViewportInset.maxInlineSize,+ layerViewportInset.maxInlineSizeFallback,),maxHeight: stylex.firstThatWorks(MENU_MAX_BLOCK_SIZE,@@ -160,6 +158,8 @@ const styles = stylex.create({touchAction: 'pan-y',overscrollBehavior: 'contain',},+ // The menu's lower block cap rides on the layer box too, so the layer's+ // flip decision sees the same height the menu paints.popoverViewport: {boxSizing: 'border-box',maxBlockSize: stylex.firstThatWorks(@@ -167,51 +167,12 @@ const styles = stylex.create({MENU_MAX_BLOCK_SIZE_FALLBACK,),},- popoverViewportAligned: {- maxInlineSize: stylex.firstThatWorks(- MENU_POSITION_AREA_MAX_INLINE_SIZE,- MENU_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK,- ),- },- popoverViewportStart: {- marginInlineEnd: MENU_INLINE_EDGE_GUTTER,- },- popoverViewportEnd: {- marginInlineStart: MENU_INLINE_EDGE_GUTTER,- },- popoverViewportBlockStart: {- marginBlockEnd: `max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px))`,- },- popoverViewportBlockEnd: {- marginBlockStart: `max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px))`,- },- popoverViewportCentered: {- marginInlineStart: MENU_INLINE_EDGE_GUTTER,- marginInlineEnd: MENU_INLINE_EDGE_GUTTER,- maxInlineSize: stylex.firstThatWorks(- MENU_MAX_INLINE_SIZE,- MENU_MAX_INLINE_SIZE_FALLBACK,- ),- },- popoverViewportBlockCentered: {- marginBlockStart: `max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px))`,- marginBlockEnd: `max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px))`,- maxInlineSize: stylex.firstThatWorks(- MENU_MAX_INLINE_SIZE,- MENU_MAX_INLINE_SIZE_FALLBACK,- ),- },- popoverAligned: {+ // Without a width the menu prefers the trigger's minimum width, clamped by+ // the runtime's cap because a CSS minimum beats a maximum (spec:AST-059 FR7).+ popoverMatchTrigger: {minWidth: stylex.firstThatWorks(- `min(anchor-size(width), ${MENU_POSITION_AREA_MAX_INLINE_SIZE})`,- `min(anchor-size(width), ${MENU_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK})`,- 'anchor-size(width)',- ),- },- popoverCentered: {- minWidth: stylex.firstThatWorks(- `min(anchor-size(width), ${MENU_MAX_INLINE_SIZE})`,- `min(anchor-size(width), ${MENU_MAX_INLINE_SIZE_FALLBACK})`,+ `min(anchor-size(width), ${layerViewportInset.maxInlineSize})`,+ `min(anchor-size(width), ${layerViewportInset.maxInlineSizeFallback})`,'anchor-size(width)',),},@@ -223,16 +184,14 @@ const styles = stylex.create({}),});-const MENU_VIEWPORT_BLOCK_GUTTERS = `max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px)) - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px))`;-// `menuMaxHeight` lifts the 300px cap for a menu that must fit its rows; the// viewport still bounds it.const dynamicStyles = stylex.create({menuMaxHeight: (maxHeight: string) => ({- maxHeight: `min(${maxHeight}, calc(100dvb - ${MENU_VIEWPORT_BLOCK_GUTTERS}))`,+ maxHeight: `min(${maxHeight}, ${layerViewportInset.maxBlockSize})`,}),popoverViewportMaxBlockSize: (maxHeight: string) => ({- maxBlockSize: `min(${maxHeight}, calc(100dvb - ${MENU_VIEWPORT_BLOCK_GUTTERS}))`,+ maxBlockSize: `min(${maxHeight}, ${layerViewportInset.maxBlockSize})`,}),});@@ -1157,21 +1116,16 @@ function DropdownMenuPopover({<Icon icon="chevronDown" size="sm" color="inherit" />) : undefined);- const requestedWidthLimit =- alignment === 'center'- ? MENU_MAX_INLINE_SIZE_FALLBACK- : MENU_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK;+ // An explicit menuWidth is clamped to the viewport, never to the room+ // beside the trigger (spec:AST-059 FR2, FR7).const resolvedMenuWidth = menuWidth- ? resolveMenuWidth(menuWidth, requestedWidthLimit)+ ? resolveMenuWidth(menuWidth, layerViewportInset.maxInlineSizeFallback): null;const popoverXstyle = resolvedMenuWidth? resolvedMenuWidth.property === 'inlineSize'? styles.popoverCustomIntrinsicWidth(resolvedMenuWidth.value): styles.popoverCustomWidth(resolvedMenuWidth.value)- : alignment === 'center'- ? styles.popoverCentered- : styles.popoverAligned;- const isSidePlacement = placement === 'start' || placement === 'end';+ : styles.popoverMatchTrigger;// The drill-in view stack for sub-menus on a phone.const {drillIn, wrapContent} = useMenuDrillIn(isOpen);@@ -1316,20 +1270,6 @@ function DropdownMenuPopover({styles.popoverViewport,resolvedMaxHeight != null &&dynamicStyles.popoverViewportMaxBlockSize(resolvedMaxHeight),- alignment === 'center'- ? isSidePlacement- ? styles.popoverViewportBlockCentered- : styles.popoverViewportCentered- : [- styles.popoverViewportAligned,- isSidePlacement- ? alignment === 'start'- ? styles.popoverViewportBlockStart- : styles.popoverViewportBlockEnd- : alignment === 'start'- ? styles.popoverViewportStart- : styles.popoverViewportEnd,- ],popoverXstyle,layerAnimations[placement],],diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsxindex c33c179f9d..73d9cd5f94 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx@@ -114,7 +114,7 @@ describe('DropdownMenuSubMenu', () => {expect(popover).toHaveStyle({minWidth: 'var(--x-minWidth)'});expect(popover?.getAttribute('style')).toContain('min(640px, calc(100vw');expect(flyout).toHaveStyle(- 'max-height: min(300px,calc(100dvb - max(var(--spacing-4),env(safe-area-inset-top,0px)) - max(var(--spacing-4),env(safe-area-inset-bottom,0px))))',+ 'max-height: min(300px,calc(100dvb - calc(max(var(--spacing-4), env(safe-area-inset-top, 0px)) + var(--astryx-layer-inset-block-start, 0px)) - calc(max(var(--spacing-4), env(safe-area-inset-bottom, 0px)) + var(--astryx-layer-inset-block-end, 0px))))',);expect(flyout).not.toHaveStyle({overflowY: 'auto'});expect(flyout).toHaveAttribute('tabindex', '-1');diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsxindex 3aed46eb43..b024341c84 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx@@ -71,6 +71,7 @@ import {isMenuPressActivation, useMenuPress} from '../hooks/useMenuPress';import {useTypeahead} from '../hooks/useTypeahead';import {useMenuOverflow} from './useMenuOverflow';import {resolveMenuWidth} from './menuWidth';+import {layerViewportInset} from '../Layer/layerViewportInset.stylex';import {colorVars,spacingVars,@@ -99,13 +100,11 @@ import {focusMenuItemOnHover} from './menuItemHover';import {DropdownMenuItem} from './DropdownMenuItem';import {useTranslator} from '../i18n';-const MENU_VIEWPORT_GUTTER = spacingVars['--spacing-4'];-// `useLayer` adds 4px of anchor clearance. An 8px collision margin resolves-// to a 4px visible gap after the browser flips the flyout.-const MENU_MAX_INLINE_SIZE = `calc(100vi - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px)) - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-right, 0px)))`;-const MENU_MAX_INLINE_SIZE_FALLBACK = `calc(100vw - ${MENU_VIEWPORT_GUTTER} - ${MENU_VIEWPORT_GUTTER})`;-const MENU_MAX_BLOCK_SIZE = `min(300px, calc(100dvb - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px)) - max(${MENU_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px))))`;-const MENU_MAX_BLOCK_SIZE_FALLBACK = `min(300px, calc(100vh - ${MENU_VIEWPORT_GUTTER} - ${MENU_VIEWPORT_GUTTER}))`;+// The flyout's own lower cap on the placement axis; the viewport cap under+// it and the inline gutter beside it are the layer runtime's (spec:AST-059).+const MENU_BLOCK_CAP = '300px';+const MENU_MAX_BLOCK_SIZE = `min(${MENU_BLOCK_CAP}, ${layerViewportInset.maxBlockSize})`;+const MENU_MAX_BLOCK_SIZE_FALLBACK = `min(${MENU_BLOCK_CAP}, ${layerViewportInset.maxBlockSizeFallback})`;const triggerStyles = stylex.create({root: {@@ -163,8 +162,8 @@ const flyoutStyles = stylex.create({flexDirection: 'column',gap: spacingVars['--spacing-0-5'],maxInlineSize: stylex.firstThatWorks(- MENU_MAX_INLINE_SIZE,- MENU_MAX_INLINE_SIZE_FALLBACK,+ layerViewportInset.maxInlineSize,+ layerViewportInset.maxInlineSizeFallback,),maxHeight: stylex.firstThatWorks(MENU_MAX_BLOCK_SIZE,@@ -210,8 +209,8 @@ const flyoutStyles = stylex.create({},popover: {minWidth: stylex.firstThatWorks(- `min(160px, ${MENU_MAX_INLINE_SIZE})`,- `min(160px, ${MENU_MAX_INLINE_SIZE_FALLBACK})`,+ `min(160px, ${layerViewportInset.maxInlineSize})`,+ `min(160px, ${layerViewportInset.maxInlineSizeFallback})`,'160px',),},@@ -714,7 +713,7 @@ export function DropdownMenuSubMenu();const resolvedMenuWidth = menuWidth- ? resolveMenuWidth(menuWidth, MENU_MAX_INLINE_SIZE_FALLBACK)+ ? resolveMenuWidth(menuWidth, layerViewportInset.maxInlineSizeFallback): null;const popoverXstyle = resolvedMenuWidth? resolvedMenuWidth.property === 'inlineSize'diff --git a/packages/core/src/DropdownMenu/menuWidth.ts b/packages/core/src/DropdownMenu/menuWidth.tsindex 2b4740e68c..d1f1b568b6 100644--- a/packages/core/src/DropdownMenu/menuWidth.ts+++ b/packages/core/src/DropdownMenu/menuWidth.ts@@ -7,19 +7,7 @@* @position Shared width compatibility logic for root menus and submenu flyouts*/-const INTRINSIC_AND_CSS_WIDE_WIDTHS = new Set([- 'auto',- 'contain',- 'fit-content',- 'inherit',- 'initial',- 'max-content',- 'min-content',- 'revert',- 'revert-layer',- 'stretch',- 'unset',-]);+import {clampInlineSize, isIntrinsicInlineSize} from '../Layer/clampInlineSize';export type ResolvedMenuWidth =| {property: 'inlineSize'; value: string}@@ -28,24 +16,15 @@ export type ResolvedMenuWidth =/*** CSS intrinsic and CSS-wide keywords cannot be arguments to `min()`. Apply* those values as the preferred inline size so max-inline-size can still cap- * the menu. Lengths retain the existing minimum-width growth contract.+ * the menu. Lengths retain the existing minimum-width growth contract, clamped+ * to the layer runtime's viewport cap (spec:AST-059 FR7).*/export function resolveMenuWidth(menuWidth: number | string,maximum: string,): ResolvedMenuWidth {- if (typeof menuWidth === 'number') {- return {property: 'minWidth', value: `min(${menuWidth}px, ${maximum})`};+ if (typeof menuWidth === 'string' && isIntrinsicInlineSize(menuWidth)) {+ return {property: 'inlineSize', value: menuWidth.trim()};}-- const width = menuWidth.trim();- const normalizedWidth = width.toLowerCase();- if (- INTRINSIC_AND_CSS_WIDE_WIDTHS.has(normalizedWidth) ||- normalizedWidth.startsWith('fit-content(')- ) {- return {property: 'inlineSize', value: width};- }-- return {property: 'minWidth', value: `min(${width}, ${maximum})`};+ return {property: 'minWidth', value: clampInlineSize(menuWidth, maximum)};}diff --git a/packages/core/src/Layer/Layer.doc.mjs b/packages/core/src/Layer/Layer.doc.mjsindex 6a43fd8594..69306c85e1 100644--- a/packages/core/src/Layer/Layer.doc.mjs+++ b/packages/core/src/Layer/Layer.doc.mjs@@ -20,8 +20,13 @@ export const docs = {],usage: {description:- 'Layer utilities provide the app-level provider used by overlay systems. Use LayerProvider at the app root for toast/layer configuration; use higher-level Popover, HoverCard, or Tooltip APIs for most overlay UI. Rendered layer content, not the provider’s application subtree, uses theme body text defaults and exits ancestor surface/group membership. Establish intentional groups and complete required providers inside each layer.',+ 'Layer utilities provide the app-level provider used by overlay systems. Use LayerProvider at the app root for toast/layer configuration; use higher-level Popover, HoverCard, or Tooltip APIs for most overlay UI. Rendered layer content, not the provider’s application subtree, uses theme body text defaults and exits ancestor surface/group membership. Establish intentional groups and complete required providers inside each layer. Every anchored layer keeps a gutter from each viewport edge — the spacing-4 step or the device safe-area inset, whichever is larger — and is capped to the viewport, never to the room beside its trigger: an explicit width renders at its size, flips when it does not fit beside the trigger, and slides into view when it fits on neither side. An app that floats a persistent bar over a viewport edge declares it once as inset on LayerProvider (blockStart, blockEnd, inlineStart, inlineEnd); each edge adds to that edge\u2019s gutter for every anchored layer and moves the toast viewport by the same amount, and defaults to zero. The inset is app configuration, not a theme value.',bestPractices: [+ {+ guidance: true,+ description:+ 'Declare a persistent bar floating over the viewport once, as inset on LayerProvider; every anchored layer and toast then stays clear of it.',+ },{guidance: true,description:@@ -49,14 +54,21 @@ export const docs = {{name: 'children',type: 'ReactNode',- description: 'Application subtree that can use the shared layer context.',+ description:+ 'Application subtree that can use the shared layer context.',required: true,},{name: 'toast',type: 'LayerToastConfig',description:- 'Toast viewport configuration. Controls position, maxVisible, and inset for toasts shown through useToast.',+ 'Toast viewport configuration. Controls position, maxVisible, and a toast-only inset that overrides the provider inset per edge for toasts shown through useToast.',+ },+ {+ name: 'inset',+ type: 'LayerInset',+ description:+ 'A persistent bar floating over a viewport edge, declared once: blockStart, blockEnd, inlineStart, inlineEnd as pixel numbers or CSS lengths. Each edge adds to the gutter every anchored layer keeps from that edge and moves the toast viewport by the same amount. Defaults to zero on every edge.',},],},@@ -76,7 +88,8 @@ export const docsDense = {},{guidance: true,- description: 'Use Popover/HoverCard/Tooltip for common overlay patterns.',+ description:+ 'Use Popover/HoverCard/Tooltip for common overlay patterns.',},{guidance: false,@@ -91,6 +104,8 @@ export const docsDense = {propDescriptions: {children: 'application subtree using shared layer context',toast: 'toast viewport config: position, maxVisible, inset',+ inset:+ 'persistent bar over a viewport edge, declared once for layers and toasts',},},],diff --git a/packages/core/src/Layer/LayerContext.ts b/packages/core/src/Layer/LayerContext.tsindex d809ae99c2..eee3efa5db 100644--- a/packages/core/src/Layer/LayerContext.ts+++ b/packages/core/src/Layer/LayerContext.ts@@ -15,6 +15,22 @@import {createContext, use} from 'react';+/**+ * The inset an app declares for a persistent bar floating over a viewport+ * edge — a phone navigation bar, a docked toolbar — once, on `LayerProvider`.+ * Each edge adds to the layer runtime's gutter for every anchored layer under+ * the provider and moves the toast viewport by the same amount. A number is+ * pixels; a string is a CSS length. Every edge defaults to zero: the system+ * already knows the device's own edges (the gutter reads+ * `env(safe-area-inset-*)`); only the app knows the bars it draws.+ */+export interface LayerInset {+ blockStart?: number | string;+ blockEnd?: number | string;+ inlineStart?: number | string;+ inlineEnd?: number | string;+}+/*** Toast configuration passed through the layer provider.*/@@ -23,7 +39,11 @@ export interface LayerToastConfig {position?: 'topEnd' | 'topStart' | 'bottomEnd' | 'bottomStart';/** Maximum visible toasts. @default 5 */maxVisible?: number;- /** Inset from viewport edges. */+ /**+ * Toast-only inset from viewport edges. An edge set here replaces the+ * provider-level `inset` for the toast viewport on that edge; unset edges+ * follow the provider.+ */inset?: {top?: number;bottom?: number;@@ -38,6 +58,8 @@ export interface LayerToastConfig {export interface LayerContextValue {/** Toast configuration from the provider. */toastConfig: LayerToastConfig;+ /** The app-declared viewport inset from the provider; undefined is zero on every edge. */+ inset: LayerInset | undefined;/** Whether this is a real provider (not fallback). */isProvider: true;}diff --git a/packages/core/src/Layer/LayerProvider.test.tsx b/packages/core/src/Layer/LayerProvider.test.tsxnew file mode 100644index 0000000000..3e97216c71--- /dev/null+++ b/packages/core/src/Layer/LayerProvider.test.tsx@@ -0,0 +1,143 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file LayerProvider.test.tsx+ * @input LayerProvider, useLayer, ToastViewport+ * @output Proves the provider-declared inset reaches anchored layers and the+ * toast viewport by inheritance, and that the default is no declaration+ * (spec:AST-059 FR6, DEC-5)+ */++import {describe, expect, it} from 'vitest';+import {fireEvent, render} from '@testing-library/react';+import {LayerProvider} from './LayerProvider';+import {useLayer} from './useLayer';+import {layerInsetProperties} from './layerInset';++function AnchoredLayer() {+ const layer = useLayer({mode: 'context'});+ return (+ <>+ <button type="button" ref={layer.ref} onClick={layer.show}>+ Open+ </button>+ {layer.render(<span>Layer</span>, {placement: 'below'})}+ </>+ );+}++function PortaledLayer() {+ const layer = useLayer({mode: 'context'});+ // A <p> cannot contain the layer's <div>, so the layer portals out of it.+ return (+ <p>+ <button type="button" ref={layer.ref} onClick={layer.show}>+ Open+ </button>+ {layer.render(<span>Layer</span>, {placement: 'below'})}+ </p>+ );+}++describe('LayerProvider inset (spec:AST-059 FR6)', () => {+ it('declares nothing by default, so a default provider matches no provider', () => {+ expect(layerInsetProperties(undefined)).toEqual({});+ expect(layerInsetProperties({})).toEqual({});+ const {container} = render(+ <LayerProvider>+ <AnchoredLayer />+ </LayerProvider>,+ );+ fireEvent.click(container.querySelector('button')!);+ for (const el of Array.from(container.querySelectorAll<HTMLElement>('*'))) {+ expect(el.getAttribute('style') ?? '').not.toContain(+ '--astryx-layer-inset',+ );+ }+ });++ it('writes one custom property per declared edge, pixels for numbers and lengths as written', () => {+ expect(+ layerInsetProperties({blockEnd: 56, inlineStart: 'var(--rail, 0px)'}),+ ).toEqual({+ '--astryx-layer-inset-block-end': '56px',+ '--astryx-layer-inset-inline-start': 'var(--rail, 0px)',+ });+ });++ it('writes the declared inset inline on the anchored layer and on the toast viewport', () => {+ const {container} = render(+ <LayerProvider inset={{blockEnd: 56}}>+ <AnchoredLayer />+ </LayerProvider>,+ );+ fireEvent.click(container.querySelector('button')!);+ const popovers = Array.from(+ container.querySelectorAll<HTMLElement>('[popover]'),+ );+ expect(popovers.length).toBe(2);+ for (const el of popovers) {+ expect(el.style.getPropertyValue('--astryx-layer-inset-block-end')).toBe(+ '56px',+ );+ }+ });++ it('reaches a layer that portals out of an unsafe host, because the value travels by context, not inheritance', () => {+ const {container} = render(+ <LayerProvider inset={{inlineEnd: 24}}>+ <PortaledLayer />+ </LayerProvider>,+ );+ fireEvent.click(container.querySelector('button')!);+ const layer = container.querySelector<HTMLElement>(+ '[popover="manual"][id]',+ );+ expect(layer?.closest('p')).toBeNull();+ expect(+ layer?.style.getPropertyValue('--astryx-layer-inset-inline-end'),+ ).toBe('24px');+ });++ it('lets a nested provider narrow the inset for the layers in its subtree', () => {+ const {container} = render(+ <LayerProvider inset={{blockEnd: 56}}>+ <LayerProvider inset={{blockEnd: 120}}>+ <AnchoredLayer />+ </LayerProvider>+ </LayerProvider>,+ );+ fireEvent.click(container.querySelector('button')!);+ const layer = container.querySelector<HTMLElement>(+ '[popover="manual"][id]',+ );+ expect(+ layer?.style.getPropertyValue('--astryx-layer-inset-block-end'),+ ).toBe('120px');+ // One toast viewport, the root's, at the root's declaration.+ const viewports = Array.from(+ container.querySelectorAll<HTMLElement>('[popover="manual"]:not([id])'),+ );+ expect(viewports.length).toBe(1);+ expect(+ viewports[0].style.getPropertyValue('--astryx-layer-inset-block-end'),+ ).toBe('56px');+ });++ it('lets toast.inset replace the provider value for the toast viewport on the edges it sets', () => {+ const {container} = render(+ <LayerProvider inset={{blockEnd: 56}} toast={{inset: {bottom: 120}}}>+ <span>app</span>+ </LayerProvider>,+ );+ const viewport = container.querySelector(+ '[popover="manual"]',+ ) as HTMLElement;+ // The inline override wins over the class that reads the provider value.+ expect(viewport.style.bottom).toBe('120px');+ expect(+ viewport.style.getPropertyValue('--astryx-layer-inset-block-end'),+ ).toBe('56px');+ expect(viewport.style.insetInlineStart).toBe('');+ });+});diff --git a/packages/core/src/Layer/LayerProvider.tsx b/packages/core/src/Layer/LayerProvider.tsxindex e96e8a2990..4751fa17f8 100644--- a/packages/core/src/Layer/LayerProvider.tsx+++ b/packages/core/src/Layer/LayerProvider.tsx@@ -7,6 +7,7 @@ import {LayerContext,useLayerContext,type LayerContextValue,+ type LayerInset,type LayerToastConfig,} from './LayerContext';import {ToastViewport} from '../Toast/ToastViewport';@@ -15,13 +16,28 @@ export interface LayerProviderProps {children: ReactNode;/** Toast configuration. Omit to use defaults. */toast?: LayerToastConfig;+ /**+ * A persistent bar floating over a viewport edge, declared once. Each edge+ * adds to the gutter every anchored layer keeps from that edge and moves+ * the toast viewport by the same amount. Numbers are pixels; strings are+ * CSS lengths. Defaults to zero on every edge.+ *+ * @example+ * ```+ * <LayerProvider inset={{blockEnd: 56}}>…</LayerProvider>+ * ```+ */+ inset?: LayerInset;}/*** App-level provider for layer systems (toast, sheet, imperative modals).** Optional — hooks fall back to a lazy self-mounting viewport when no- * provider exists. Nested providers are no-ops.+ * provider exists. Nested providers are no-ops, except that one declaring an+ * `inset` narrows it for the anchored layers in its subtree. `inset` declares+ * a persistent bar floating over a viewport edge once; anchored layers and+ * toasts both clear it.** @example* ```@@ -35,25 +51,43 @@ const DEFAULT_TOAST_CONFIG = {};export function LayerProvider({children,toast: toastConfig = DEFAULT_TOAST_CONFIG,+ inset,}: LayerProviderProps) {const existingContext = useLayerContext();const contextValue = useMemo<LayerContextValue>(- () => ({toastConfig, isProvider: true}),- [toastConfig],+ () => ({toastConfig, inset, isProvider: true}),+ [toastConfig, inset],+ );+ const nestedValue = useMemo<LayerContextValue | null>(+ () =>+ existingContext && inset != null ? {...existingContext, inset} : null,+ [existingContext, inset],);- // Nested provider — pass through+ // Nested provider — pass through. One that declares an inset narrows it+ // for the anchored layers in its subtree (an app hosted inside another+ // provider can still declare its own bar); the toast viewport is the+ // root's and reads the root's declaration.if (existingContext) {- return <>{children}</>;+ if (nestedValue == null) {+ return <>{children}</>;+ }+ return <LayerContext value={nestedValue}>{children}</LayerContext>;}+ // The declared inset reaches anchored layers through context — each layer+ // writes it inline on itself, so a corrective portal cannot escape it — and+ // the toast viewport through its prop. Nothing resolves placement through+ // the provider (spec:AST-059 FR6). With no inset nothing is written, so a+ // surface with no provider renders as one under the default provider.return (<LayerContext value={contextValue}><ToastViewportposition={toastConfig.position}maxVisible={toastConfig.maxVisible}- inset={toastConfig.inset}>+ inset={toastConfig.inset}+ layerInset={inset}>{children}</ToastViewport></LayerContext>diff --git a/packages/core/src/Layer/clampInlineSize.ts b/packages/core/src/Layer/clampInlineSize.tsnew file mode 100644index 0000000000..c6552521c2--- /dev/null+++ b/packages/core/src/Layer/clampInlineSize.ts@@ -0,0 +1,49 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file clampInlineSize.ts+ * @input A consumer's preferred inline size and the runtime's viewport cap+ * @output The size clamped to the cap, or the keyword left as written+ * @position Layer runtime geometry; spec:AST-059 FR7 — a consumer's own size+ * rule cannot defeat the viewport cap+ */++const INTRINSIC_AND_CSS_WIDE_WIDTHS = new Set([+ 'auto',+ 'contain',+ 'fit-content',+ 'inherit',+ 'initial',+ 'max-content',+ 'min-content',+ 'revert',+ 'revert-layer',+ 'stretch',+ 'unset',+]);++/**+ * Whether a width value is an intrinsic or CSS-wide keyword. Those cannot be+ * arguments to `min()`, so a consumer applies them as written and lets the+ * painted surface's own cap bound the result.+ */+export function isIntrinsicInlineSize(value: string): boolean {+ const normalized = value.trim().toLowerCase();+ return (+ INTRINSIC_AND_CSS_WIDE_WIDTHS.has(normalized) ||+ normalized.startsWith('fit-content(')+ );+}++/**+ * Clamp a length to the runtime's viewport cap. A number is pixels. A CSS+ * minimum wins over a maximum, so a consumer that applies a preferred size as+ * `min-width` must clamp it here rather than relying on `max-inline-size`.+ */+export function clampInlineSize(+ value: number | string,+ maximum: string,+): string {+ const length = typeof value === 'number' ? `${value}px` : value.trim();+ return `min(${length}, ${maximum})`;+}diff --git a/packages/core/src/Layer/index.ts b/packages/core/src/Layer/index.tsindex e98734e309..d292879bf4 100644--- a/packages/core/src/Layer/index.ts+++ b/packages/core/src/Layer/index.ts@@ -50,7 +50,11 @@ export type {export {LayerProvider} from './LayerProvider';export type {LayerProviderProps} from './LayerProvider';export {LayerContext, useLayerContext} from './LayerContext';-export type {LayerContextValue, LayerToastConfig} from './LayerContext';+export type {+ LayerContextValue,+ LayerInset,+ LayerToastConfig,+} from './LayerContext';// Shared entry animation styles for layer-based componentsexport {layerAnimations} from './layerAnimations.stylex';diff --git a/packages/core/src/Layer/layerInset.ts b/packages/core/src/Layer/layerInset.tsnew file mode 100644index 0000000000..aee38a7880--- /dev/null+++ b/packages/core/src/Layer/layerInset.ts@@ -0,0 +1,46 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file layerInset.ts+ * @input A LayerProvider inset declaration+ * @output The inline custom properties that carry it to a layer or the toast+ * viewport, where the gutter reads them+ * @position Layer runtime; the mechanism behind `LayerProvider.inset`+ * (spec:AST-059 FR6). The property names are implementation; the provider+ * prop is the public surface.+ */++import type {CSSProperties} from 'react';+import type {LayerInset} from './LayerContext';++const INSET_PROPERTIES: ReadonlyArray<[keyof LayerInset, string]> = [+ ['blockStart', '--astryx-layer-inset-block-start'],+ ['blockEnd', '--astryx-layer-inset-block-end'],+ ['inlineStart', '--astryx-layer-inset-inline-start'],+ ['inlineEnd', '--astryx-layer-inset-inline-end'],+];++function toCssLength(value: number | string): string {+ return typeof value === 'number' ? `${value}px` : value;+}++/**+ * The inline custom properties that carry a declared inset to the element+ * whose gutter reads them — the layer, or the toast viewport. One property+ * per declared edge; an undeclared edge sets nothing, so it reads `0px`+ * through the gutter's fallback exactly as it does with no provider at all.+ */+export function layerInsetProperties(+ inset: LayerInset | undefined,+): CSSProperties {+ const style: Record<string, string> = {};+ if (inset) {+ for (const [edge, property] of INSET_PROPERTIES) {+ const value = inset[edge];+ if (value != null && value !== '') {+ style[property] = toCssLength(value);+ }+ }+ }+ return style;+}diff --git a/packages/core/src/Layer/layerSlideRules.ts b/packages/core/src/Layer/layerSlideRules.tsnew file mode 100644index 0000000000..abc050f320--- /dev/null+++ b/packages/core/src/Layer/layerSlideRules.ts@@ -0,0 +1,149 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file layerSlideRules.ts+ * @input A layer's placement and alignment+ * @output The `@position-try` rules for its slide options and their names+ * @position Layer runtime geometry; the slide of spec:AST-059 FR4+ *+ * The slide is a position option whose area spans the whole alignment axis,+ * so a layer wider than the room beside its trigger on both sides still+ * reaches the side of the trigger that has room on the placement axis. A+ * plain `<position-area>` fallback would keep the base margins and insets,+ * which belong to an edge-aligned layer: the alignment-axis gutter on one+ * edge only, and the clearance/gutter pair of the base side on the placement+ * axis. Each slide option therefore carries its own declarations — the+ * gutter on both alignment-axis edges, and the clearance facing the anchor+ * with the gutter on the far edge of the side it lands on.+ *+ * The rules are static — the anchor clearance travels through a custom+ * property — so one style sheet per document carries all of them. It is+ * installed from a layout effect, before the layer's first paint, rather than+ * through StyleX, whose `positionTry()` output is malformed in the pinned+ * release. The sheet lives in the document head, not beside or inside the+ * layer: a sibling would change what a parent's last child is, and text+ * inside a role-bearing layer would name it to assistive technology.+ */++import type {LayerAlignment, LayerPlacement} from './useLayer';+import {layerViewportInset} from './layerViewportInset.stylex';++/** The custom property a layer writes its anchor clearance to. */+export const LAYER_CLEARANCE_PROPERTY = '--_astryx-layer-clearance';++type Side = 'same' | 'opposite';++export function slideRuleName(+ placement: LayerPlacement,+ alignment: LayerAlignment,+ side: Side,+): string {+ return `--astryx-layer-slide-${placement}-${alignment}-${side}`;+}++const CLEARANCE = `var(${LAYER_CLEARANCE_PROPERTY}, 0px)`;++/** Two declarations: the `env()`-less fallback first, then the full value. */+function pair(property: string, fallback: string, value: string): string {+ return `${property}:${fallback};${property}:${value};`;+}++function blockGutter(property: string): string {+ return pair(+ property,+ layerViewportInset.gutterBlockFallback,+ layerViewportInset.gutterBlock,+ );+}++function inlineGutter(property: string): string {+ return pair(+ property,+ layerViewportInset.gutterInlineFallback,+ layerViewportInset.gutterInline,+ );+}++const OPPOSITE: Record<LayerPlacement, LayerPlacement> = {+ above: 'below',+ below: 'above',+ start: 'end',+ end: 'start',+};++function areaFor(placement: LayerPlacement): string {+ switch (placement) {+ case 'above':+ return 'self-block-start span-all';+ case 'below':+ return 'self-block-end span-all';+ case 'start':+ return 'self-inline-start span-all';+ case 'end':+ return 'self-inline-end span-all';+ }+}++/** The placement-axis margins for a layer resting on `placement`'s side. */+function placementMargins(placement: LayerPlacement): string {+ switch (placement) {+ case 'above':+ return `margin-block-end:${CLEARANCE};${blockGutter('margin-block-start')}`;+ case 'below':+ return `margin-block-start:${CLEARANCE};${blockGutter('margin-block-end')}`;+ case 'start':+ return `margin-inline-end:${CLEARANCE};${inlineGutter('margin-inline-start')}`;+ case 'end':+ return `margin-inline-start:${CLEARANCE};${inlineGutter('margin-inline-end')}`;+ }+}++/** The alignment-axis gutter on both edges, with the base inset reset. */+function alignmentMargins(placement: LayerPlacement): string {+ return placement === 'above' || placement === 'below'+ ? `${inlineGutter('margin-inline-start')}${inlineGutter('margin-inline-end')}inset-inline-start:0;inset-inline-end:0;`+ : `${blockGutter('margin-block-start')}${blockGutter('margin-block-end')}inset-block-start:0;inset-block-end:0;`;+}++function rule(+ placement: LayerPlacement,+ alignment: LayerAlignment,+ side: Side,+): string {+ const landing = side === 'same' ? placement : OPPOSITE[placement];+ return `@position-try ${slideRuleName(placement, alignment, side)}{position-area:${areaFor(landing)};${placementMargins(landing)}${alignmentMargins(landing)}}`;+}++const PLACEMENTS: ReadonlyArray<LayerPlacement> = [+ 'above',+ 'below',+ 'start',+ 'end',+];+const ALIGNMENTS: ReadonlyArray<LayerAlignment> = ['start', 'center', 'end'];++/** Every slide rule, for every placement and alignment. */+export function slideRulesCss(): string {+ return PLACEMENTS.flatMap(placement =>+ ALIGNMENTS.flatMap(alignment => [+ rule(placement, alignment, 'same'),+ rule(placement, alignment, 'opposite'),+ ]),+ ).join('');+}++export const SLIDE_RULES_ID = 'astryx-layer-slide-rules';++/**+ * Install the slide rules in a document once. Idempotent; a second layer, or+ * a layer in another document (an iframe), finds or adds its own sheet.+ */+export function ensureSlideRules(doc: Document): void {+ if (doc.getElementById(SLIDE_RULES_ID)) {+ return;+ }+ const style = doc.createElement('style');+ style.id = SLIDE_RULES_ID;+ style.textContent = slideRulesCss();+ doc.head.appendChild(style);+}diff --git a/packages/core/src/Layer/layerViewportInset.stylex.ts b/packages/core/src/Layer/layerViewportInset.stylex.tsnew file mode 100644index 0000000000..cc66b6ac8f--- /dev/null+++ b/packages/core/src/Layer/layerViewportInset.stylex.ts@@ -0,0 +1,81 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file layerViewportInset.stylex.ts+ * @input Uses the spacing token, the device safe-area insets, and the+ * app-declared `--astryx-layer-inset-*` custom properties+ * @output Exports the one definition of an anchored layer's viewport gutter+ * and the size caps derived from it+ * @position Layer runtime geometry; read by useLayer and by consumers that+ * clamp a size of their own (spec:AST-059 FR1, FR7)+ *+ * An anchored layer keeps a gutter from each viewport edge: the spacing-4 step+ * or the device safe-area inset for that edge, whichever is larger, plus the+ * inset an app declares for a persistent bar floating over that edge. The+ * inline gutter reads the larger of the two physical safe-area insets, so a+ * layer that flips across the inline axis still clears a notch on either side.+ *+ * `defineConsts`, not plain exported strings: StyleX inlines a cross-file+ * value only through `defineVars`/`defineConsts` from a `.stylex.ts` file.+ * Nothing here is a theme variable: the gutter is geometry, not treatment.+ *+ * App declaration (once, usually on `:root`):+ *+ * ```css+ * :root { --astryx-layer-inset-block-end: var(--app-nav-bar-height, 0px); }+ * ```+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Layer/useLayer.tsx+ * - /packages/core/src/Layer/layerViewportInset.test.ts+ * - /docs/specs/AST-059-layer-viewport-inset/spec.md+ */++import * as stylex from '@stylexjs/stylex';++// `defineConsts` admits only static values, so the spacing token is named by+// its custom property rather than through `spacingVars`; it is the same+// `--spacing-4` every other gutter in core reads.+const SPACING = 'var(--spacing-4)';++const INSET_BLOCK_START = 'var(--astryx-layer-inset-block-start, 0px)';+const INSET_BLOCK_END = 'var(--astryx-layer-inset-block-end, 0px)';+const INSET_INLINE_START = 'var(--astryx-layer-inset-inline-start, 0px)';+const INSET_INLINE_END = 'var(--astryx-layer-inset-inline-end, 0px)';++const GUTTER_BLOCK_START = `calc(max(${SPACING}, env(safe-area-inset-top, 0px)) + ${INSET_BLOCK_START})`;+const GUTTER_BLOCK_END = `calc(max(${SPACING}, env(safe-area-inset-bottom, 0px)) + ${INSET_BLOCK_END})`;+const GUTTER_INLINE_LEFT = `calc(max(${SPACING}, env(safe-area-inset-left, 0px)) + ${INSET_INLINE_START})`;+const GUTTER_INLINE_RIGHT = `calc(max(${SPACING}, env(safe-area-inset-right, 0px)) + ${INSET_INLINE_END})`;+// A flipped layer may land on either inline side, so one gutter serves both+// edges: the larger safe-area inset plus the larger app inset.+const GUTTER_INLINE = `calc(max(${SPACING}, env(safe-area-inset-left, 0px), env(safe-area-inset-right, 0px)) + max(${INSET_INLINE_START}, ${INSET_INLINE_END}))`;+// The positional gutter on the block axis is an inset the flip tactics mirror+// between the two edges, so one value serves both: the larger of the two.+const GUTTER_BLOCK = `calc(max(${SPACING}, env(safe-area-inset-top, 0px), env(safe-area-inset-bottom, 0px)) + max(${INSET_BLOCK_START}, ${INSET_BLOCK_END}))`;++/**+ * The viewport gutter and the caps derived from it. Every value has an+ * `env()`-less fallback for engines without safe-area support; pair them with+ * `stylex.firstThatWorks(cap, capFallback)`.+ */+export const layerViewportInset = stylex.defineConsts({+ /** Gutter from the block-start viewport edge. */+ gutterBlockStart: GUTTER_BLOCK_START,+ /** Gutter from the block-end viewport edge. */+ gutterBlockEnd: GUTTER_BLOCK_END,+ /** Gutter from either inline viewport edge. */+ gutterInline: GUTTER_INLINE,+ /** Positional gutter from either block viewport edge: the larger of the two. */+ gutterBlock: GUTTER_BLOCK,+ gutterBlockFallback: `calc(${SPACING} + max(${INSET_BLOCK_START}, ${INSET_BLOCK_END}))`,+ gutterBlockStartFallback: `calc(${SPACING} + ${INSET_BLOCK_START})`,+ gutterBlockEndFallback: `calc(${SPACING} + ${INSET_BLOCK_END})`,+ gutterInlineFallback: `calc(${SPACING} + max(${INSET_INLINE_START}, ${INSET_INLINE_END}))`,+ /** The largest inline size a layer may take: the viewport minus both gutters. */+ maxInlineSize: `calc(100vi - ${GUTTER_INLINE_LEFT} - ${GUTTER_INLINE_RIGHT})`,+ maxInlineSizeFallback: `calc(100vw - ${SPACING} - ${SPACING} - ${INSET_INLINE_START} - ${INSET_INLINE_END})`,+ /** The largest block size a layer may take: the viewport minus both gutters. */+ maxBlockSize: `calc(100dvb - ${GUTTER_BLOCK_START} - ${GUTTER_BLOCK_END})`,+ maxBlockSizeFallback: `calc(100vh - ${SPACING} - ${SPACING} - ${INSET_BLOCK_START} - ${INSET_BLOCK_END})`,+});diff --git a/packages/core/src/Layer/layerViewportInset.test.ts b/packages/core/src/Layer/layerViewportInset.test.tsnew file mode 100644index 0000000000..79360a106f--- /dev/null+++ b/packages/core/src/Layer/layerViewportInset.test.ts@@ -0,0 +1,119 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file layerViewportInset.test.ts+ * @input The layer runtime's gutter module and the core source tree+ * @output Proves one gutter definition and the clamp helper (spec:AST-059+ * FR1, FR6, FR7)+ */++import {readdirSync, readFileSync, statSync} from 'node:fs';+import {join} from 'node:path';+import {describe, expect, it} from 'vitest';+import {layerViewportInset} from './layerViewportInset.stylex';+import {clampInlineSize, isIntrinsicInlineSize} from './clampInlineSize';++const EDGES = ['block-start', 'block-end', 'inline-start', 'inline-end'];++// Surfaces that keep the same gutter by convention but are not anchor-mode+// layers (spec:AST-059 non-goals), plus the module itself.+const GUTTER_OWNERS = new Set([+ 'Layer/layerViewportInset.stylex.ts',+ 'Dialog/Dialog.tsx',+ 'Toast/ToastViewport.tsx',+ 'BottomSheet/BottomSheetPanel.tsx',+ 'Stepper/Step.tsx',+ 'Tokenizer/useEndLaneReserve.ts',+]);++function sourceFiles(dir: string): string[] {+ const out: string[] = [];+ for (const entry of readdirSync(dir)) {+ const full = join(dir, entry);+ if (statSync(full).isDirectory()) {+ out.push(...sourceFiles(full));+ } else if (/\.(ts|tsx)$/.test(entry) && !/\.test\.|\.spec\./.test(entry)) {+ out.push(full);+ }+ }+ return out;+}++describe('layerViewportInset (spec:AST-059)', () => {+ it('reads the spacing step, the safe-area inset, and the app-declared inset for every edge (FR1, FR6)', () => {+ expect(layerViewportInset.gutterBlockStart).toBe(+ 'calc(max(var(--spacing-4), env(safe-area-inset-top, 0px)) + var(--astryx-layer-inset-block-start, 0px))',+ );+ expect(layerViewportInset.gutterBlockEnd).toBe(+ 'calc(max(var(--spacing-4), env(safe-area-inset-bottom, 0px)) + var(--astryx-layer-inset-block-end, 0px))',+ );+ // One inline gutter serves both edges: the larger safe-area inset and the+ // larger app inset, so a flipped layer still clears a notch.+ expect(layerViewportInset.gutterInline).toBe(+ 'calc(max(var(--spacing-4), env(safe-area-inset-left, 0px), env(safe-area-inset-right, 0px)) + max(var(--astryx-layer-inset-inline-start, 0px), var(--astryx-layer-inset-inline-end, 0px)))',+ );+ for (const edge of EDGES) {+ const property = `--astryx-layer-inset-${edge}`;+ expect(+ layerViewportInset.maxInlineSize + layerViewportInset.maxBlockSize,+ ).toContain(`var(${property}, 0px)`);+ }+ });++ it('caps both axes to the viewport minus both gutters, with env()-less fallbacks (FR2, FR3)', () => {+ expect(layerViewportInset.maxInlineSize).toMatch(/^calc\(100vi - /);+ expect(layerViewportInset.maxBlockSize).toMatch(/^calc\(100dvb - /);+ expect(layerViewportInset.maxInlineSizeFallback).toMatch(/^calc\(100vw - /);+ expect(layerViewportInset.maxBlockSizeFallback).toMatch(/^calc\(100vh - /);+ for (const value of [+ layerViewportInset.maxInlineSizeFallback,+ layerViewportInset.maxBlockSizeFallback,+ layerViewportInset.gutterInlineFallback,+ layerViewportInset.gutterBlockStartFallback,+ layerViewportInset.gutterBlockEndFallback,+ ]) {+ expect(value).not.toContain('env(');+ expect(value).toContain('--astryx-layer-inset-');+ }+ // Never the span beside the trigger.+ for (const value of Object.values(layerViewportInset)) {+ expect(value).not.toContain('100%');+ }+ });++ it('is the only gutter definition among anchor-mode layers (FR1, FR7)', () => {+ const root = join(process.cwd(), 'packages/core/src');+ const offenders = sourceFiles(root)+ .filter(file => {+ const source = readFileSync(file, 'utf8');+ // A gutter of its own, or a size capped to the span beside the+ // trigger: `100%` of a position-area region minus the gutter.+ return (+ /safe-area-inset-(left|right|top|bottom)/.test(source) ||+ /calc\(100% - (max\(|\$\{spacingVars\['--spacing-4'\]\})/.test(source)+ );+ })+ .map(file => file.slice(root.length + 1))+ .filter(file => !GUTTER_OWNERS.has(file));+ expect(offenders).toEqual([]);+ });+});++describe('clampInlineSize (spec:AST-059 FR7)', () => {+ it('clamps a length to the cap and treats a number as pixels', () => {+ expect(clampInlineSize(352, 'CAP')).toBe('min(352px, CAP)');+ expect(clampInlineSize(' 20rem ', 'CAP')).toBe('min(20rem, CAP)');+ });++ it('recognizes keywords that cannot be clamped', () => {+ for (const keyword of [+ 'auto',+ 'max-content',+ 'fit-content(20em)',+ 'Inherit',+ ]) {+ expect(isIntrinsicInlineSize(keyword)).toBe(true);+ }+ expect(isIntrinsicInlineSize('352px')).toBe(false);+ });+});diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsxindex d00058c456..71e79f3dd7 100644--- a/packages/core/src/Layer/useLayer.test.tsx+++ b/packages/core/src/Layer/useLayer.test.tsx@@ -24,6 +24,7 @@ import {useLayer,useLayerInternal,getPositionTryFallbacks,+ getSelfAlignment,} from './useLayer';import {typeScaleVars} from '../theme/tokens.stylex';import type {@@ -189,49 +190,71 @@ describe('useLayer identity', () => {});});-describe('getPositionTryFallbacks (issue #3671)', () => {+describe('getPositionTryFallbacks (issue #3671, spec:AST-059 FR4)', () => {const FLIPS = 'flip-block, flip-inline, flip-block flip-inline';+ const slides = (p: LayerPlacement, a: LayerAlignment) =>+ `--astryx-layer-slide-${p}-${a}-same, --astryx-layer-slide-${p}-${a}-opposite`;- it('appends inline span fallbacks for centered above/below layers so inline overflow can resolve (flip-inline is a no-op on center)', () => {+ it('appends inline span fallbacks for centered above/below layers so inline overflow can resolve (flip-inline is a no-op on center), then the named slides', () => {expect(getPositionTryFallbacks('above', 'center')).toBe(- `${FLIPS}, top span-left, top span-right, bottom span-left, bottom span-right`,+ `${FLIPS}, top span-left, top span-right, bottom span-left, bottom span-right, ${slides('above', 'center')}`,);expect(getPositionTryFallbacks('below', 'center')).toBe(- `${FLIPS}, bottom span-left, bottom span-right, top span-left, top span-right`,+ `${FLIPS}, bottom span-left, bottom span-right, top span-left, top span-right, ${slides('below', 'center')}`,);});- it('appends block span fallbacks for centered start/end layers so block overflow can resolve (flip-block is a no-op on center)', () => {+ it('appends block span fallbacks for centered start/end layers so block overflow can resolve (flip-block is a no-op on center), then the named slides', () => {expect(getPositionTryFallbacks('start', 'center')).toBe(- `${FLIPS}, left span-top, left span-bottom, right span-top, right span-bottom`,+ `${FLIPS}, left span-top, left span-bottom, right span-top, right span-bottom, ${slides('start', 'center')}`,);expect(getPositionTryFallbacks('end', 'center')).toBe(- `${FLIPS}, right span-top, right span-bottom, left span-top, left span-bottom`,+ `${FLIPS}, right span-top, right span-bottom, left span-top, left span-bottom, ${slides('end', 'center')}`,);});- it('keeps flip-only fallbacks for non-centered alignments (flips already resolve overflow there)', () => {- const nonCentered: [LayerPlacement, LayerAlignment][] = [- ['above', 'start'],- ['above', 'end'],- ['below', 'start'],- ['below', 'end'],- ['start', 'start'],- ['start', 'end'],- ['end', 'start'],- ['end', 'end'],- ];- for (const [placement, alignment] of nonCentered) {- expect(getPositionTryFallbacks(placement, alignment)).toBe(FLIPS);+ it('gives aligned layers the flips, then the named slide on the same side and on the opposite side', () => {+ for (const placement of ['above', 'below', 'start', 'end'] as const) {+ for (const alignment of ['start', 'end'] as const) {+ expect(getPositionTryFallbacks(placement, alignment)).toBe(+ `${FLIPS}, ${slides(placement, alignment)}`,+ );+ }}});+ it('installs the slide rules once in the document head, with the gutter on both alignment-axis edges and the clearance facing the anchor on the landing side', async () => {+ const user = userEvent.setup();+ const {container} = render(+ <ContextLayerHarness placement="below" alignment="start" />,+ );+ await user.click(container.querySelector('button')!);+ const popover = container.querySelector('[popover]');+ // One sheet in the document head: never inside the layer, where a+ // role-bearing layer's text would name it to assistive technology, and+ // never beside it, where it would change a parent's last child.+ expect(popover?.querySelector('style')).toBeNull();+ expect(container.querySelector('style')).toBeNull();+ const css =+ document.getElementById('astryx-layer-slide-rules')?.textContent ?? '';+ expect(css).toContain(+ '@position-try --astryx-layer-slide-below-start-same{position-area:self-block-end span-all;margin-block-start:var(--_astryx-layer-clearance, 0px);',+ );+ expect(css).toContain(+ '@position-try --astryx-layer-slide-below-start-opposite{position-area:self-block-start span-all;margin-block-end:var(--_astryx-layer-clearance, 0px);',+ );+ expect(css).toMatch(+ /margin-inline-start:[^;]*;margin-inline-start:[^;]*env\(safe-area-inset-left/,+ );+ expect(css).toContain('inset-inline-start:0;inset-inline-end:0;');+ });+it('defaults to above/center when called without arguments (matches renderContext defaults)', () => {expect(getPositionTryFallbacks()).toBe(getPositionTryFallbacks('above', 'center'),);expect(getPositionTryFallbacks(undefined, undefined)).toBe(- `${FLIPS}, top span-left, top span-right, bottom span-left, bottom span-right`,+ getPositionTryFallbacks('above', 'center'),);});@@ -239,17 +262,14 @@ describe('getPositionTryFallbacks (issue #3671)', () => {const placements: LayerPlacement[] = ['above', 'below', 'start', 'end'];const alignments: LayerAlignment[] = ['start', 'center', 'end'];const spanPattern: Record<LayerPlacement, RegExp> = {- above: /^(top|bottom) span-(left|right)$/,- below: /^(top|bottom) span-(left|right)$/,- start: /^(left|right) span-(top|bottom)$/,- end: /^(left|right) span-(top|bottom)$/,+ above: /^(top|bottom) span-(left|right)$|^--astryx-layer-slide-above-/,+ below: /^(top|bottom) span-(left|right)$|^--astryx-layer-slide-below-/,+ start: /^(left|right) span-(top|bottom)$|^--astryx-layer-slide-start-/,+ end: /^(left|right) span-(top|bottom)$|^--astryx-layer-slide-end-/,};-for (const placement of placements) {for (const alignment of alignments) {- const list = getPositionTryFallbacks(placement, alignment);- const items = list.split(', ');-+ const items = getPositionTryFallbacks(placement, alignment).split(', ');expect(items.slice(0, 3)).toEqual(['flip-block','flip-inline',@@ -259,7 +279,7 @@ describe('getPositionTryFallbacks (issue #3671)', () => {for (const item of items.slice(3)) {expect(item).toMatch(spanPattern[placement]);}- expect(items.length).toBe(alignment === 'center' ? 7 : 3);+ expect(items.length).toBe(alignment === 'center' ? 9 : 5);}}});@@ -274,11 +294,13 @@ describe('getPositionTryFallbacks (issue #3671)', () => {expect(layerEl.style.positionTryFallbacks).toContain('top span-left');rerender(<ContextLayerHarness placement="above" alignment="start" />);- expect(layerEl.style.positionTryFallbacks).toBe(FLIPS);+ expect(layerEl.style.positionTryFallbacks).toBe(+ getPositionTryFallbacks('above', 'start'),+ );rerender(<ContextLayerHarness placement="start" alignment="center" />);expect(layerEl.style.positionTryFallbacks).toBe(- `${FLIPS}, left span-top, left span-bottom, right span-top, right span-bottom`,+ getPositionTryFallbacks('start', 'center'),);});@@ -301,11 +323,150 @@ describe('getPositionTryFallbacks (issue #3671)', () => {const layerEl = container.querySelector('[popover]') as HTMLElement;expect(layerEl).not.toBeNull();expect(layerEl.style.positionTryFallbacks).toBe(- `${FLIPS}, top span-left, top span-right, bottom span-left, bottom span-right`,+ getPositionTryFallbacks('above', 'center'),);});});+describe('viewport inset (spec:AST-059)', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('caps every anchor-mode layer on the placement axis and keeps the far-edge gutter of its alignment axis (FR1, FR3)', async () => {+ const user = userEvent.setup();+ const cases: [LayerPlacement, LayerAlignment, string[], string[]][] = [+ [+ 'below',+ 'start',+ ['farBelow', 'gutterInlineEnd'],+ ['gutterInlineStart', 'farAbove'],+ ],+ ['below', 'end', ['farBelow', 'gutterInlineStart'], ['gutterInlineEnd']],+ [+ 'above',+ 'center',+ ['farAbove', 'gutterInlineStart', 'gutterInlineEnd'],+ ['farBelow'],+ ],+ [+ 'end',+ 'start',+ ['farEnd', 'gutterBlockEnd'],+ ['gutterBlockStart', 'farStart'],+ ],+ ['start', 'end', ['farStart', 'gutterBlockStart'], ['gutterBlockEnd']],+ ['end', 'center', ['farEnd', 'gutterBlockStart', 'gutterBlockEnd'], []],+ ];+ for (const [placement, alignment, present, absent] of cases) {+ const {container, unmount} = render(+ <ContextLayerHarness placement={placement} alignment={alignment} />,+ );+ await user.click(container.querySelector('button')!);+ const layerEl = container.querySelector('[popover]') as HTMLElement;+ expect(layerEl.className).toContain('useLayer__styles.viewportFit');+ for (const key of present) {+ expect(layerEl.className).toContain(`useLayer__styles.${key}`);+ }+ for (const key of absent) {+ expect(layerEl.className).not.toContain(`useLayer__styles.${key}`);+ }+ // The gutter never caps the layer box's inline size: an auto-width+ // layer shrinks to the room beside its trigger on its own, and a cap on+ // the box keeps the browser from choosing a flip.+ expect(layerEl.className).not.toMatch(/useLayer__styles\.maxInline/);+ unmount();+ }+ });++ it('leaves custom and fixed positioning without the viewport fit (INV3)', () => {+ function CustomHarness() {+ const layer = useLayer({mode: 'context'});+ return (+ <>+ <button type="button" ref={layer.ref} onClick={layer.show}>+ Trigger+ </button>+ {layer.render(<span>Custom</span>, {positioning: 'custom'})}+ </>+ );+ }+ const {container} = render(<CustomHarness />);+ fireEvent.click(container.querySelector('button')!);+ const layerEl = container.querySelector('[popover]') as HTMLElement;+ expect(layerEl.className).not.toContain('useLayer__styles.viewportFit');+ expect(layerEl.className).not.toMatch(/useLayer__styles\.gutter/);+ });++ it('pins an aligned layer unsafe toward its anchor only while the anchor is out of view (FR4, FR5)', () => {+ expect(getSelfAlignment('below', 'start', true)).toEqual({});+ expect(getSelfAlignment('below', 'start', false)).toEqual({+ justifySelf: 'unsafe self-start',+ });+ expect(getSelfAlignment('above', 'end', false)).toEqual({+ justifySelf: 'unsafe self-end',+ });+ expect(getSelfAlignment('end', 'start', false)).toEqual({+ alignSelf: 'unsafe self-start',+ });+ expect(getSelfAlignment('start', 'end', false)).toEqual({+ alignSelf: 'unsafe self-end',+ });+ // Centered layers slide through their span fallbacks and never pin.+ expect(getSelfAlignment('below', 'center', false)).toEqual({});+ });++ it('withdraws the slide when the observed anchor leaves the viewport and restores it when it returns (FR5)', async () => {+ let notify!: IntersectionObserverCallback;+ const observed: Element[] = [];+ const disconnect = vi.fn();+ class Observer {+ constructor(callback: IntersectionObserverCallback) {+ notify = callback;+ }+ observe(target: Element) {+ observed.push(target);+ }+ unobserve() {}+ disconnect = disconnect;+ takeRecords() {+ return [];+ }+ }+ vi.stubGlobal('IntersectionObserver', Observer);++ const user = userEvent.setup();+ const {container} = render(+ <ContextLayerHarness placement="below" alignment="start" />,+ );+ const trigger = container.querySelector('button')!;+ await user.click(trigger);+ const layerEl = container.querySelector('[popover]') as HTMLElement;+ expect(observed).toEqual([trigger]);+ expect(layerEl.style.justifySelf).toBe('');++ act(() => {+ notify(+ [{isIntersecting: false} as IntersectionObserverEntry],+ {} as IntersectionObserver,+ );+ });+ expect(layerEl.style.justifySelf).toBe('unsafe self-start');+ // The fallback list stays; only the overflow shift is withdrawn.+ expect(layerEl.style.positionTryFallbacks).toBe(+ getPositionTryFallbacks('below', 'start'),+ );++ act(() => {+ notify(+ [{isIntersecting: true} as IntersectionObserverEntry],+ {} as IntersectionObserver,+ );+ });+ expect(layerEl.style.justifySelf).toBe('');+ });+});+describe('useLayer', () => {const originalShowPopover = HTMLElement.prototype.showPopover;const originalHidePopover = HTMLElement.prototype.hidePopover;@@ -907,24 +1068,33 @@ describe('useLayer context positioning', () => {const NONE = {blockStart: '', blockEnd: '', inlineStart: '', inlineEnd: ''};- it('is flush by default', async () => {+ // The clearance rides the anchor-facing edge of the placement axis; the+ // far edge carries the static viewport gutter (spec:AST-059 FR1), which is+ // a class, not a dynamic variable, so it does not appear here.+ it('is flush against the anchor by default', async () => {expect(await openAndGetOffsets(<OffsetHarness placement="below" />),).toEqual(NONE);});- // Both edges of the axis, so the gap survives a position-try-fallbacks- // flip to the opposite side (#4803).- it('clears both block edges for a block placement', async () => {+ // The flip tactic swaps the two block margins with the area, so the gap+ // survives a position-try-fallbacks flip to the opposite side (#4803).+ it('clears the anchor-facing block edge for a block placement', async () => {expect(await openAndGetOffsets(<OffsetHarness placement="above" offset={8} />),- ).toEqual({...NONE, blockStart: '8px', blockEnd: '8px'});+ ).toEqual({...NONE, blockEnd: '8px'});});- it('clears both inline edges for an inline placement', async () => {+ it('clears the opposite block edge when placed below', async () => {+ expect(+ await openAndGetOffsets(<OffsetHarness placement="below" offset={8} />),+ ).toEqual({...NONE, blockStart: '8px'});+ });++ it('clears the anchor-facing inline edge for an inline placement', async () => {expect(await openAndGetOffsets(<OffsetHarness placement="end" offset={8} />),- ).toEqual({...NONE, inlineStart: '8px', inlineEnd: '8px'});+ ).toEqual({...NONE, inlineStart: '8px'});});it('takes a CSS length string', async () => {@@ -932,11 +1102,18 @@ describe('useLayer context positioning', () => {await openAndGetOffsets(<OffsetHarness placement="below" offset="var(--spacing-1)" />,),- ).toEqual({- ...NONE,- blockStart: 'var(--spacing-1)',- blockEnd: 'var(--spacing-1)',- });+ ).toEqual({...NONE, blockStart: 'var(--spacing-1)'});+ });++ it('puts the viewport gutter on the far edge of the placement axis (FR1, FR6)', async () => {+ const user = userEvent.setup();+ const {container, getByRole} = render(+ <OffsetHarness placement="below" offset={8} />,+ );+ await user.click(getByRole('button', {name: 'trigger'}));+ const el = container.querySelector('[popover]') as HTMLElement;+ expect(el.className).toContain('useLayer__styles.placementBelow');+ expect(el.className).not.toContain('useLayer__styles.placementAbove');});it('is ignored under custom positioning, which owns its own insets', async () => {diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsxindex 30de135be6..8e1864de34 100644--- a/packages/core/src/Layer/useLayer.tsx+++ b/packages/core/src/Layer/useLayer.tsx@@ -32,6 +32,15 @@ import {addAnchorName, removeAnchorName} from './anchorName';import {currentGesture, currentGestureHasClicked} from './gestureCounter';import {resolveLayerPortalTarget} from './layerHost';import {layerTextReset} from './layerTextReset.stylex';+import {layerViewportInset} from './layerViewportInset.stylex';+import {layerInsetProperties} from './layerInset';+import {+ LAYER_CLEARANCE_PROPERTY,+ ensureSlideRules,+ slideRuleName,+} from './layerSlideRules';+import {useLayerContext} from './LayerContext';+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import {overlayPaddingReset} from '../Layout/padding.stylex';const styles = stylex.create({@@ -55,18 +64,83 @@ const styles = stylex.create({fixed: {position: 'fixed',},- // Clearance from the anchor. Set on BOTH edges of the placement axis, not- // just the one facing the anchor: `position-try-fallbacks` can flip the- // layer to the opposite side at paint time, and a single-edge margin then- // lands on the far side and the gap vanishes (#4803).- offsetBlock: (offset: string) => ({+ // Margins on the placement axis: the anchor clearance on the edge facing+ // the anchor, the viewport gutter on the far edge (spec:AST-059 FR1, FR6).+ // The margin box is what must fit a position option and what the browser's+ // overflow shift keeps inside the viewport, so a layer that would end+ // inside the gutter — or under a declared bar — does not fit there and the+ // next option is tried. A flip tactic swaps the two values with the area,+ // so the clearance stays on the anchor side and the gutter on the far side+ // (#4803); for the same reason the gutter is one value for both edges, the+ // larger of the two block gutters.+ placementBelow: (offset: string) => ({marginBlockStart: offset,+ marginBlockEnd: layerViewportInset.gutterBlock,+ }),+ placementAbove: (offset: string) => ({+ marginBlockStart: layerViewportInset.gutterBlock,marginBlockEnd: offset,}),- offsetInline: (offset: string) => ({+ placementEnd: (offset: string) => ({marginInlineStart: offset,+ marginInlineEnd: layerViewportInset.gutterInline,+ }),+ placementStart: (offset: string) => ({+ marginInlineStart: layerViewportInset.gutterInline,marginInlineEnd: offset,}),+ // Flush against the anchor (no offset): only the far-edge gutter.+ farBelow: {marginBlockEnd: layerViewportInset.gutterBlock},+ farAbove: {marginBlockStart: layerViewportInset.gutterBlock},+ farEnd: {marginInlineEnd: layerViewportInset.gutterInline},+ farStart: {marginInlineStart: layerViewportInset.gutterInline},+ // The viewport inset (spec:AST-059 FR1–FR3). Every anchor-mode layer is+ // capped to the viewport minus both gutters on both axes and keeps the+ // runtime's gutter from the far viewport edge of its alignment axis as a+ // margin (the placement-axis gutter rides the placement margins above).+ // The cap is on the layer box itself: content wider than the viewport+ // overflows inside the layer, where the composing component decides+ // whether it scrolls or clips; the box never leaves the viewport.+ viewportFit: {+ boxSizing: 'border-box',+ maxInlineSize: stylex.firstThatWorks(+ layerViewportInset.maxInlineSize,+ layerViewportInset.maxInlineSizeFallback,+ ),+ maxBlockSize: stylex.firstThatWorks(+ layerViewportInset.maxBlockSize,+ layerViewportInset.maxBlockSizeFallback,+ ),+ },+ // Alignment-axis gutter (spec:AST-059 FR1): a margin on the far viewport+ // edge of the alignment axis — one on the anchor-facing edge would push an+ // aligned layer off its anchor — or both edges for a centered layer. The+ // flip tactic mirrors it with the area. The slide options carry both+ // (see layerSlideRules.ts).+ gutterInlineEnd: {+ marginInlineEnd: stylex.firstThatWorks(+ layerViewportInset.gutterInline,+ layerViewportInset.gutterInlineFallback,+ ),+ },+ gutterInlineStart: {+ marginInlineStart: stylex.firstThatWorks(+ layerViewportInset.gutterInline,+ layerViewportInset.gutterInlineFallback,+ ),+ },+ gutterBlockEnd: {+ marginBlockEnd: stylex.firstThatWorks(+ layerViewportInset.gutterBlock,+ layerViewportInset.gutterBlockFallback,+ ),+ },+ gutterBlockStart: {+ marginBlockStart: stylex.firstThatWorks(+ layerViewportInset.gutterBlock,+ layerViewportInset.gutterBlockFallback,+ ),+ },});/**@@ -424,33 +498,97 @@ function getPositionArea(}/**- * Compute the `position-try-fallbacks` list for a placement/alignment pair.+ * Compute the `position-try-fallbacks` list for a placement/alignment pair+ * (spec:AST-059 FR4).*- * Flips alone cannot rescue a centered layer — flipping along the alignment- * axis maps center → center, so overflow on that axis renders clipped- * (#3671). Centered alignments therefore append span-based fallbacks letting- * the browser slide the layer along the alignment axis as a last resort- * (same-side spans first). Flips already resolve non-centered alignments.+ * Flips first; they mirror the placement-axis margins (clearance and gutter)+ * and the alignment-axis gutter with the area. Then the slide: named+ * `@position-try` options whose area spans the whole alignment axis+ * (`layerSlideRules.ts`), same side of the trigger first, opposite side+ * second. Flips alone cannot rescue a layer wider than the room on either+ * side of its trigger — every flipped option overflows the alignment axis+ * too, and the browser keeps the base option, so the layer never moves to the+ * side of the trigger that has room on the placement axis (#3671 for centered+ * layers, where a flip maps center → center). A slide option fits wherever+ * the layer fits the viewport; its anchor-center alignment plus the browser's+ * overflow shift keep the layer's margin box — and so the gutter on both+ * edges — inside the viewport. Centered layers keep their one-sided spans+ * ahead of the full span so they slide the least distance first.*/export function getPositionTryFallbacks(placement: LayerPlacement = 'above',alignment: LayerAlignment = 'center',): string {const flips = 'flip-block, flip-inline, flip-block flip-inline';+ const slides = `${slideRuleName(placement, alignment, 'same')}, ${slideRuleName(placement, alignment, 'opposite')}`;if (alignment !== 'center') {- return flips;+ return `${flips}, ${slides}`;}if (placement === 'above' || placement === 'below') {const [same, opposite] =placement === 'above' ? ['top', 'bottom'] : ['bottom', 'top'];- return `${flips}, ${same} span-left, ${same} span-right, ${opposite} span-left, ${opposite} span-right`;+ return `${flips}, ${same} span-left, ${same} span-right, ${opposite} span-left, ${opposite} span-right, ${slides}`;}const [same, opposite] =placement === 'start' ? ['left', 'right'] : ['right', 'left'];- return `${flips}, ${same} span-top, ${same} span-bottom, ${opposite} span-top, ${opposite} span-bottom`;+ return `${flips}, ${same} span-top, ${same} span-bottom, ${opposite} span-top, ${opposite} span-bottom, ${slides}`;+}++/**+ * The self-alignment an aligned layer uses while its anchor is out of view+ * (spec:AST-059 FR5). A position-area box that overflows the room beside its+ * anchor is shifted by default to stay inside the viewport — the slide an+ * aligned layer relies on when it fits on neither side (FR4). Once the anchor+ * has left the viewport that shift would pin the layer into the narrowest+ * strip at the edge, so the alignment is pinned `unsafe` toward the anchor+ * instead and the layer holds the position its flips give it. `self-*`+ * keywords resolve against the layer's own direction, matching the `self-*`+ * position-area family; the flip tactics swap start/end with the area.+ *+ * Centered layers already slide through their span fallbacks and are+ * unchanged; a visible anchor keeps the browser's default alignment.+ */+export function getSelfAlignment(+ placement: LayerPlacement,+ alignment: LayerAlignment,+ isAnchorInView: boolean,+): React.CSSProperties {+ if (isAnchorInView || alignment === 'center') {+ return {};+ }+ const edge = alignment === 'start' ? 'unsafe self-start' : 'unsafe self-end';+ return placement === 'above' || placement === 'below'+ ? {justifySelf: edge}+ : {alignSelf: edge};+}++/**+ * The gutter styles for a placement/alignment pair: the far viewport edge of+ * the alignment axis, or both edges when centered (spec:AST-059 FR1).+ */+function getGutterStyles(+ placement: LayerPlacement,+ alignment: LayerAlignment,+): ReadonlyArray<StyleXStyles> {+ if (placement === 'above' || placement === 'below') {+ if (alignment === 'start') {+ return [styles.gutterInlineEnd];+ }+ if (alignment === 'end') {+ return [styles.gutterInlineStart];+ }+ return [styles.gutterInlineStart, styles.gutterInlineEnd];+ }+ if (alignment === 'start') {+ return [styles.gutterBlockEnd];+ }+ if (alignment === 'end') {+ return [styles.gutterBlockStart];+ }+ return [styles.gutterBlockStart, styles.gutterBlockEnd];}/**@@ -521,6 +659,23 @@ function useLayerImplementation(const anchorId = `--astryx-layer-${id.replace(/:/g, '')}`;const [isOpen, setIsOpen] = useState(false);+ // Whether the anchor is inside the viewport (spec:AST-059 FR5). The slide+ // fallback is withdrawn while it is not, so an aligned layer holds its+ // position and size instead of chasing an anchor nobody can see.+ const [isAnchorInView, setIsAnchorInView] = useState(true);+ // Mirror so the pre-paint read commits nothing when the answer is unchanged.+ const isAnchorInViewRef = useRef(true);+ const updateAnchorInView = useCallback((inView: boolean) => {+ if (isAnchorInViewRef.current !== inView) {+ isAnchorInViewRef.current = inView;+ setIsAnchorInView(inView);+ }+ }, []);+ // The inset the app declared on LayerProvider (FR6). Read through context+ // and written inline on the layer, so a corrective portal cannot escape it+ // and no measurement is needed to apply it.+ const layerContext = useLayerContext();+ const declaredInset = layerContext?.inset;const popoverRef = useRef<HTMLElement | null>(null);// The DOM element on which the current logical open state was applied.// A portal target change replaces the popover element; retaining the old@@ -850,6 +1005,58 @@ function useLayerImplementation(};}, [handleToggle, bindToggleListener]);+ // The slide options' `@position-try` rules (FR4) are installed in the+ // layer's document before its first paint; one sheet serves every layer.+ useIsomorphicLayoutEffect(() => {+ if (mode !== 'context') {+ return;+ }+ const doc =+ popoverRef.current?.ownerDocument ?? sentinelRef.current?.ownerDocument;+ if (doc) {+ ensureSlideRules(doc);+ }+ }, [mode, contextMount]);++ // Anchor visibility (FR5). The first frame must already be right (FR8), so+ // the opening read is synchronous — a layout effect runs before paint, and a+ // state change inside it re-renders before paint — against the visual+ // viewport. IntersectionObserver then tracks changes while open; with no+ // root it reports against the viewport and through every ancestor clip, so+ // an anchor scrolled out of a panel reads as out of view too.+ useIsomorphicLayoutEffect(() => {+ if (!isOpen || mode !== 'context') {+ return;+ }+ const anchor = triggerRef.current;+ if (!anchor) {+ return;+ }+ const view = anchor.ownerDocument.defaultView;+ if (view) {+ // Edge-adjacent counts as in view, as IntersectionObserver reports it;+ // an engine with no layout (a zero rect) therefore reads as in view too.+ const rect = anchor.getBoundingClientRect();+ const inView =+ rect.bottom >= 0 &&+ rect.right >= 0 &&+ rect.top <= view.innerHeight &&+ rect.left <= view.innerWidth;+ updateAnchorInView(inView);+ }+ if (typeof IntersectionObserver === 'undefined') {+ return;+ }+ const observer = new IntersectionObserver(entries => {+ const latest = entries[entries.length - 1];+ if (latest) {+ updateAnchorInView(latest.isIntersecting);+ }+ });+ observer.observe(anchor);+ return () => observer.disconnect();+ }, [isOpen, mode, updateAnchorInView]);+// Render function for context modeconst renderContext = useCallback((children: ReactNode, props?: ContextRenderProps) => {@@ -890,19 +1097,43 @@ function useLayerImplementation(placement,alignment,),+ ...getSelfAlignment(placement, alignment, isAnchorInView),};+ const clearance = offset ? toCssLength(offset) : null;+ const clearanceProperty: Record<string, string> =+ positioning === 'anchor' && clearance != null+ ? {[LAYER_CLEARANCE_PROPERTY]: clearance}+ : {};const offsetStyle =- positioning === 'anchor' && offset- ? placement === 'above' || placement === 'below'- ? styles.offsetBlock(toCssLength(offset))- : styles.offsetInline(toCssLength(offset))+ positioning !== 'anchor'+ ? null+ : clearance == null+ ? placement === 'above'+ ? styles.farAbove+ : placement === 'below'+ ? styles.farBelow+ : placement === 'start'+ ? styles.farStart+ : styles.farEnd+ : placement === 'above'+ ? styles.placementAbove(clearance)+ : placement === 'below'+ ? styles.placementBelow(clearance)+ : placement === 'start'+ ? styles.placementStart(clearance)+ : styles.placementEnd(clearance);++ const viewportStyles =+ positioning === 'anchor'+ ? [styles.viewportFit, ...getGutterStyles(placement, alignment)]: null;const stylexResult = stylex.props(layerTextReset.reset,styles.base,overlayPaddingReset.reset,+ viewportStyles,offsetStyle,xstyle,);@@ -924,6 +1155,8 @@ function useLayerImplementation(style={{...stylexResult.style,...anchorStyle,+ ...clearanceProperty,+ ...layerInsetProperties(declaredInset),...contextMount.portalStyle,...extraStyle,}}@@ -945,7 +1178,9 @@ function useLayerImplementation([anchorId,contextMount,+ declaredInset,id,+ isAnchorInView,lightDismiss,popoverRefCallback,sentinelRefCallback,diff --git a/packages/core/src/Popover/Popover.spec.md b/packages/core/src/Popover/Popover.spec.mdindex 799c11613a..668d9c3af3 100644--- a/packages/core/src/Popover/Popover.spec.md+++ b/packages/core/src/Popover/Popover.spec.md@@ -45,8 +45,9 @@ and rendering contract for custom compositions.This contract records the behavior present after[PR #5373](https://github.com/facebook/astryx/pull/5373), the Popover target-direction settled by Cindy Zhang on 2026-08-31, and the focus/opening correction-approved by Cindy Zhang on 2026-09-07. Public API signatures and release status+direction settled by Cindy Zhang on 2026-08-31, the focus/opening correction+approved by Cindy Zhang on 2026-09-07, and the move of viewport fitting to the+layer runtime decided by Cindy Zhang on 2026-10-03 (`spec:AST-059`). Public API signatures and release statusremain unchanged. Consumer syntax and complete signatures remain owned by`Popover.doc.mjs` and `usePopover.doc.mjs`. The canonical `popover` target andthe deprecated `popover-surface` compatibility alias remain supported together.@@ -87,9 +88,9 @@ replacement when it is authored, while existing themes continue to work.- The public `usePopover` semantic contract: visibility operations, triggerbindings, surface rendering, dialog semantics, focus containment, andlifecycle notifications.-- Popover-specific focus destination selection, viewport fitting, safe-area- gutters, match-trigger sizing, conditional internal scrolling, and the- measurement lifecycle needed to support them.+- Popover-specific focus destination selection, the preferred size (an explicit+ `width`, else the trigger's minimum width), conditional internal scrolling,+ and the measurement lifecycle needed to support them.- The current fallback close control appended by the hook.**Does not own / non-goals**@@ -100,6 +101,11 @@ replacement when it is authored, while existing themes continue to work.- Generic top-layer hosting, native popover lifecycle reconciliation, anchorpositioning, portal/context selection, and same-gesture reopen protection —owned by `architecture:layer-runtime`.+- The viewport inset — the gutter and safe-area insets, the size caps, the+ fallback order including the slide and its anchor-visibility condition, and+ the app-declared inset — owned by `architecture:layer-runtime` through+ `spec:AST-059`. Popover clamps its own preferred size with the runtime's cap+ and adds nothing of its own.- Shared Escape and platform-close ordering — owned by`family:overlay-dismissal`.- The shared focus-trap algorithm outside Popover-specific destination choice —@@ -117,17 +123,17 @@ surface, not the Layer entry point. There is no installable## Public concepts-| Concept | Closed values or states | Meaning | Availability | Default | Owner | Stability | Invalid or unsupported behavior |-| ------------------------ | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ------------------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Trigger composition | Wrapped trigger, render-prop trigger, or referenced anchor | Supplies the anchor and the control that opens or closes the standard component | Popover | Wrapped trigger when children are supplied | `component:Popover` | Current public behavior | A referenced or wrapped anchor without a button or button role warns in development and receives no trigger handler; it does not throw. |-| Visibility ownership | Uncontrolled or externally controlled | Chooses whether Popover stores visibility or synchronizes to caller state | Popover | Uncontrolled | `component:Popover` | Current public behavior | Controlled changes are synchronized through show/hide; dismissal requests are reported to the caller rather than redefining the external source of truth. |-| Popup semantics | Dialog or neutral wrapper | Exposes dialog semantics or lets child menu/listbox semantics own the popup | Popover and hook | Dialog | `component:Popover` | Current public behavior | A dialog without a label warns in development. Neutral mode omits dialog role and modal semantics. |-| Focus entry | Automatic or caller-preserved | Focuses genuine caller content, falls back to the labeled dialog surface when none exists, or preserves current focus | Popover and hook | Automatic | `component:Popover` | Current public behavior | The injected fallback close control is excluded from initial-focus candidates and reveals only when reached sequentially. |-| Dismissal | Outside/Escape enabled or disabled within native constraints | Controls light dismiss and explicit Escape participation | Popover and hook | Both enabled | `component:Popover`; `family:overlay-dismissal` owns Escape/platform-close ordering | Current public behavior | Disabling Escape alone cannot override the native Escape behavior of an auto popover; explicit-dismiss behavior requires light dismiss to be disabled too. |-| Surface treatment | Default surface or caller-owned treatment | Applies the shared painted surface and optional consumer styling | Popover and hook | Default surface | `component:Popover` | Current public behavior | Custom styling does not change lifecycle, focus, or dismissal semantics. |-| Surface padding | A spacing-scale step, `0` through `10` | Sets the inset the painted surface keeps around caller content; `0` is a flush surface for content that owns its own edges | Popover and hook | Popover: step 3; hook: none | `component:Popover` | Pending owner review (DEC-4) | The rung lands on the painted surface, so a theme's `padding` on the `popover` target replaces it rather than nesting; consumer `xstyle` merges after it. |-| Surface target ownership | Shared baseline or component-specific refinement | Assigns `popover` as the broad surface owner and lets a composed component add its own target on that same element | Popover and hook | `popover` baseline; no component-specific refinement | `component:Popover`; the composed component owns its refinement target | Current compatibility contract | `popover-surface` is compatibility output, not a new target for consumers or a second anatomy owner. |-| Placement and fit | Logical placement/alignment plus preferred width | Positions the anchor surface and constrains it to available space | Popover and hook renderer | Below/start; Popover matches trigger minimum width when no width is supplied | `component:Popover` above `architecture:layer-runtime` | Current public behavior | Preferred width and trigger matching remain capped by viewport and safe-area availability. |+| Concept | Closed values or states | Meaning | Availability | Default | Owner | Stability | Invalid or unsupported behavior |+| ---------------------------- | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ------------------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Trigger composition | Wrapped trigger, render-prop trigger, or referenced anchor | Supplies the anchor and the control that opens or closes the standard component | Popover | Wrapped trigger when children are supplied | `component:Popover` | Current public behavior | A referenced or wrapped anchor without a button or button role warns in development and receives no trigger handler; it does not throw. |+| Visibility ownership | Uncontrolled or externally controlled | Chooses whether Popover stores visibility or synchronizes to caller state | Popover | Uncontrolled | `component:Popover` | Current public behavior | Controlled changes are synchronized through show/hide; dismissal requests are reported to the caller rather than redefining the external source of truth. |+| Popup semantics | Dialog or neutral wrapper | Exposes dialog semantics or lets child menu/listbox semantics own the popup | Popover and hook | Dialog | `component:Popover` | Current public behavior | A dialog without a label warns in development. Neutral mode omits dialog role and modal semantics. |+| Focus entry | Automatic or caller-preserved | Focuses genuine caller content, falls back to the labeled dialog surface when none exists, or preserves current focus | Popover and hook | Automatic | `component:Popover` | Current public behavior | The injected fallback close control is excluded from initial-focus candidates and reveals only when reached sequentially. |+| Dismissal | Outside/Escape enabled or disabled within native constraints | Controls light dismiss and explicit Escape participation | Popover and hook | Both enabled | `component:Popover`; `family:overlay-dismissal` owns Escape/platform-close ordering | Current public behavior | Disabling Escape alone cannot override the native Escape behavior of an auto popover; explicit-dismiss behavior requires light dismiss to be disabled too. |+| Surface treatment | Default surface or caller-owned treatment | Applies the shared painted surface and optional consumer styling | Popover and hook | Default surface | `component:Popover` | Current public behavior | Custom styling does not change lifecycle, focus, or dismissal semantics. |+| Surface padding | A spacing-scale step, `0` through `10` | Sets the inset the painted surface keeps around caller content; `0` is a flush surface for content that owns its own edges | Popover and hook | Popover: step 3; hook: none | `component:Popover` | Pending owner review (DEC-4) | The rung lands on the painted surface, so a theme's `padding` on the `popover` target replaces it rather than nesting; consumer `xstyle` merges after it. |+| Surface target ownership | Shared baseline or component-specific refinement | Assigns `popover` as the broad surface owner and lets a composed component add its own target on that same element | Popover and hook | `popover` baseline; no component-specific refinement | `component:Popover`; the composed component owns its refinement target | Current compatibility contract | `popover-surface` is compatibility output, not a new target for consumers or a second anatomy owner. |+| Placement and preferred size | Logical placement/alignment plus preferred width | Positions the anchor surface and states the size Popover prefers; the layer runtime fits it to the viewport | Popover and hook renderer | Below/start; Popover matches trigger minimum width when no width is supplied | `component:Popover` for the preference; `architecture:layer-runtime` for the fit | Current public behavior | An explicit width renders at its size up to the viewport minus gutters; it is never shrunk to the room beside the trigger (`spec:AST-059` FR2). |### Public `usePopover` semantic inputs@@ -179,7 +185,7 @@ table owns their semantic effect.| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- || FR1 | Popover and public `usePopover` expose one visibility lifecycle with canonical show, hide, and toggle operations. Every opening path inherits same-gesture reopen protection without changing public signatures. | Current public package surface, `architecture:layer-runtime/INV7`, and owner approval on 2026-09-07 | Accepted; implemented and covered by focused Popover-family tests || FR2 | Popover derives semantic focus entry identically across activation modalities: first genuine caller content, then labeled dialog-surface fallback. The injected close control is excluded. Shared interaction modality controls focus indication, not destination. | PR #5373, `architecture:interaction-modality`, and owner approval on 2026-09-07 | Accepted; implemented and covered by Popover focus tests |-| FR3 | The preferred surface size is capped to logical viewport and safe-area availability before overflow is enabled. | PR #5373, current source, tests, and Storybook fixtures | Verified in unit/style evidence; real rendered viewport evidence remains a gap |+| FR3 | Retired. Viewport and safe-area capping is the layer runtime's (`spec:AST-059` FR2, FR3); Popover clamps its preferred size with the runtime's cap and caps its painted surface with the same definition. | `spec:AST-059`, owner direction 2026-10-03 | Retired; see `architecture:layer-runtime` INV11 and the `Core/Layer` viewport-inset stories || FR4 | Popover enables internal scrolling only after measured overflow exceeds the current tolerance. Fitting content does not become a scroll container. | PR #5373 and current tests | Verified current behavior || FR5 | Overflow signals while open coalesce into at most one measurement per animation frame, and Popover owns no measurement observers while closed. | PR #5373 and current tests | Verified current resource behavior || FR6 | Component anatomy contains the caller trigger and content, one painted Popover surface, and the optional fallback close control. Popover owns no Header, Body, or separate shared-hook surface part. | Current source, docs target inventory, and tests | Accepted anatomy; stale consumer anatomy corrected by this contract |@@ -198,9 +204,9 @@ table owns their semantic effect.surface padding rung, or add a component-owned refinement target whilepreserving the canonical `popover` ownership, lifecycle, focus containment,and dismissal model.-- **AV4 — Placement.** Logical placement, alignment, preferred width, and- available viewport size may change geometry without changing the fit and- overflow precedence below.+- **AV4 — Placement.** Logical placement, alignment, and preferred width may+ change geometry without changing the overflow precedence below; the fit+ against the viewport is the layer runtime's.### Representative focus and dismissal states@@ -225,11 +231,13 @@ table owns their semantic effect.one-opening `skipAutoFocus` preference; otherwise Popover derives genuinecontent focus and its safe surface fallback.- **ORD2 — Preferred inline size.** An explicit width wins over trigger matching.- Without explicit width, Popover prefers trigger minimum width. Either preferred- size remains capped by available viewport and safe-area space.-- **ORD3 — Viewport fit.** Logical placement and alignment select the applicable- safe-area gutters; the positioned layer and painted surface are capped before- overflow state is evaluated.+ Without explicit width, Popover prefers trigger minimum width. Either+ preferred size is clamped by the layer runtime's viewport cap+ (`spec:AST-059` FR7); neither is capped to the room beside the trigger.+- **ORD3 — Retired.** The viewport fit — gutters, caps, flips, and the slide —+ is the layer runtime's (`spec:AST-059` FR1–FR5). Popover's painted surface+ reads the runtime's cap so overflow state is evaluated against the same+ bound the layer applies.- **ORD4 — Conditional scroll.** Measured overflow greater than 1 px enablesinternal scrolling and overscroll containment; fitting content leaves bothdisabled.@@ -267,12 +275,12 @@ table owns their semantic effect.## Design relationships-| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |-| ---------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------ | -------------- | ------------------ |-| Trigger element | Supplies or references the control and anchor without becoming Popover-owned presentation. | Caller content | Supporting | FR6, AR1 |-| Popover surface | Paints the component surface, owns the canonical `popover` target, and carries fit, scroll, focus, and dialog behavior. | Current source and owner DEC-2 | Prominent | FR2–FR7, AR2–AR4 |-| Popover content | Renders caller-supplied interaction or information inside the surface. | Caller content | Prominent | FR2, FR6 |-| Fallback close control | Provides an end-of-trap close affordance without becoming the initial focus destination. | `component:Button` | Supporting | FR2, AR3 |+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |+| ---------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------ | -------------- | --------------------- |+| Trigger element | Supplies or references the control and anchor without becoming Popover-owned presentation. | Caller content | Supporting | FR6, AR1 |+| Popover surface | Paints the component surface, owns the canonical `popover` target, and carries scroll, focus, and dialog behavior. | Current source and owner DEC-2 | Prominent | FR2, FR4–FR7, AR2–AR4 |+| Popover content | Renders caller-supplied interaction or information inside the surface. | Caller content | Prominent | FR2, FR6 |+| Fallback close control | Provides an end-of-trap close affordance without becoming the initial focus destination. | `component:Button` | Supporting | FR2, AR3 |### Theming anatomy@@ -321,9 +329,9 @@ removal.- `architecture:public-component-api` owns installable reachability and thedistinction between public package API and source-level implementation seams.- `architecture:layer-runtime` owns the shared host, native popover lifecycle,- anchor geometry, portal/context behavior, and same-gesture dismissal guard;- Popover owns the component-specific fit, overflow, and focus composition above- that runtime.+ anchor geometry, the viewport inset (`spec:AST-059`), portal/context+ behavior, and same-gesture dismissal guard; Popover owns its preferred size,+ overflow, and focus composition above that runtime.- `architecture:interaction-modality` owns shared modality classification andfocus-indicator visibility. Popover owns semantic focus entry and fallback;pointer input does not select a different destination merely to hide an outline.@@ -338,15 +346,15 @@ removal.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |-| Public boundary, FR1 | `Popover.test.tsx` compile-time public-surface assertions plus package/barrel inspection | Unchanged public signatures and same-gesture rejection across Popover-family openings | A public type changes or a same-gesture request reaches visibility state. | `audit:Popover/api` |-| FR2, AR2–AR4 | `Popover.test.tsx` focus/role suites and `useFocusTrap.test.tsx` container-entry suites | Pointer, keyboard/AT-style, read-only, neutral role, no autofocus, controlled, Tab/Shift+Tab, Escape, focus return | Changing semantic destination by modality, selecting fallback close initially, losing shared indication, or allowing focus escape fails assertions. | `audit:Popover/accessibility` |-| FR3, FR4 | `Popover.test.tsx` sizing/overflow suites; `Popover.stories.tsx` real-viewport scenarios for manual/browser evidence | Explicit width, trigger matching, all alignments, fitting and overflowing content | Removing a cap, reversing width precedence, or always enabling scroll fails emitted-style or overflow assertions. | `audit:Popover/layout` |-| FR8 | `Popover.test.tsx` surface-padding suite | Default rung, `0`, an explicit rung, a direct hook composition with and without a rung | A default other than step 3, a rung landing on a box inside the surface, or the hook painting a rung it was not given fails the suite. | `audit:Popover/theming` |-| FR5 | `Popover.test.tsx` scheduling and observer-lifecycle suites | Closed, opened, repeated signals, cleanup | Constructing observers while closed or measuring more than once per pending frame fails lifecycle assertions. | `audit:Popover/resources` |-| FR6, FR7 and theming anatomy | `Popover.test.tsx`, `Popover.doc.mjs`, `usePopover.doc.mjs`, `astryx theme targets Popover --json`, and `scripts/check-knowledge.mjs` | One real surface with canonical `popover`; deprecated alias on that element; composed-component refinements | A fake anatomy part, loss of compatibility output, missing deprecation metadata, or an active target without a real owner fails review or validation. | `audit:Popover/theming` |-| AR5 | `Popover.stories.tsx` manual-AT fixture and PR #5373 test record | Read-only dialog manual-AT fixture; no recorded NVDA/VoiceOver announcement result | A fixture without recorded AT/browser observations cannot be cited as announcement proof. | `audit:Popover/at-evidence` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |+| Public boundary, FR1 | `Popover.test.tsx` compile-time public-surface assertions plus package/barrel inspection | Unchanged public signatures and same-gesture rejection across Popover-family openings | A public type changes or a same-gesture request reaches visibility state. | `audit:Popover/api` |+| FR2, AR2–AR4 | `Popover.test.tsx` focus/role suites and `useFocusTrap.test.tsx` container-entry suites | Pointer, keyboard/AT-style, read-only, neutral role, no autofocus, controlled, Tab/Shift+Tab, Escape, focus return | Changing semantic destination by modality, selecting fallback close initially, losing shared indication, or allowing focus escape fails assertions. | `audit:Popover/accessibility` |+| ORD2, FR4 | `Popover.test.tsx` sizing/overflow suites; `Popover.stories.tsx` match-trigger and overflow scenarios; geometry under `Core/Layer` viewport-inset stories | Explicit width clamped to the viewport, trigger matching, fitting and overflowing content | Reversing width precedence, capping to the span beside the trigger, or always enabling scroll fails emitted-style or overflow assertions. | `audit:Popover/layout` |+| FR8 | `Popover.test.tsx` surface-padding suite | Default rung, `0`, an explicit rung, a direct hook composition with and without a rung | A default other than step 3, a rung landing on a box inside the surface, or the hook painting a rung it was not given fails the suite. | `audit:Popover/theming` |+| FR5 | `Popover.test.tsx` scheduling and observer-lifecycle suites | Closed, opened, repeated signals, cleanup | Constructing observers while closed or measuring more than once per pending frame fails lifecycle assertions. | `audit:Popover/resources` |+| FR6, FR7 and theming anatomy | `Popover.test.tsx`, `Popover.doc.mjs`, `usePopover.doc.mjs`, `astryx theme targets Popover --json`, and `scripts/check-knowledge.mjs` | One real surface with canonical `popover`; deprecated alias on that element; composed-component refinements | A fake anatomy part, loss of compatibility output, missing deprecation metadata, or an active target without a real owner fails review or validation. | `audit:Popover/theming` |+| AR5 | `Popover.stories.tsx` manual-AT fixture and PR #5373 test record | Read-only dialog manual-AT fixture; no recorded NVDA/VoiceOver announcement result | A fixture without recorded AT/browser observations cannot be cited as announcement proof. | `audit:Popover/at-evidence` |## Decision log@@ -413,9 +421,11 @@ These implementation and evidence items remain required follow-up, but they donot block acceptance of the semantic contract above.- **VG1 — Real browser behavior.** Unit tests assert emitted sizing styles and- synthetic dimensions, not rendered viewport layout. Native popover light- dismiss, top-layer ordering, anchor geometry, rendered focus behavior, and- focus-indicator modality still require real Chromium/WebKit evidence when changed.+ synthetic dimensions, not rendered viewport layout. Rendered viewport+ geometry is covered by the `Core/Layer` viewport-inset stories under the+ story play guard; native popover light dismiss, top-layer ordering, rendered+ focus behavior, and focus-indicator modality still require real+ Chromium/WebKit evidence when changed.- **VG2 — AT announcement.** The current story provides manual instructions, butnamed NVDA + Chrome and VoiceOver + Safari results are absent. No announcementoutcome is claimed.diff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsxindex 15f13498ad..0eef0b77ae 100644--- a/packages/core/src/Popover/Popover.test.tsx+++ b/packages/core/src/Popover/Popover.test.tsx@@ -265,9 +265,14 @@ describe('Popover', () => {const layer = document.querySelector('[popover]');expect(layer).toHaveStyle({boxSizing: 'border-box'});- expect(layer?.className).toContain('Popover__styles.viewportFit');- expect(layer?.className).toContain('Popover__styles.viewportAligned');- expect(layer?.className).toContain('Popover__styles.viewportStart');+ // The viewport fit is the layer runtime's (spec:AST-059 FR1, FR3); the+ // explicit width is clamped to the viewport, never to the span beside+ // the trigger (FR2).+ expect(layer?.className).toContain('useLayer__styles.viewportFit');+ expect(layer?.className).toContain('useLayer__styles.gutterInlineEnd');+ expect(layer?.className).toContain('Popover__styles.customWidth');+ expect(layer?.getAttribute('style')).toContain('min(640px, calc(100vw');+ expect(layer?.getAttribute('style')).not.toContain('100%');const surface = screen.getByTestId('popover-content').parentElement;expect(surface?.className).toContain('Popover__styles.surfaceViewportFit');const popoverSource = readFileSync(@@ -275,11 +280,12 @@ describe('Popover', () => {'utf8',);expect(popoverSource).toMatch(- /surfaceViewportFit:[\s\S]*?maxInlineSize: stylex\.firstThatWorks\(\s*POPOVER_MAX_INLINE_SIZE/,+ /surfaceViewportFit:[\s\S]*?maxInlineSize: stylex\.firstThatWorks\(\s*layerViewportInset\.maxInlineSize/,);expect(popoverSource).toMatch(- /surfaceViewportFit:[\s\S]*?maxBlockSize: stylex\.firstThatWorks\(\s*POPOVER_MAX_BLOCK_SIZE/,+ /surfaceViewportFit:[\s\S]*?maxBlockSize: stylex\.firstThatWorks\(\s*layerViewportInset\.maxBlockSize/,);+ expect(popoverSource).not.toMatch(/safe-area-inset|calc\(100%/);expect(surface?.className).not.toContain('Popover__styles.surfaceScrollable',);@@ -435,7 +441,7 @@ describe('Popover', () => {}});- it('keeps aligned popovers anchored while applying viewport gutters', () => {+ it('inherits the far-edge gutter from the layer runtime for aligned popovers', () => {render(<Popover content={<span>Content</span>} label="Test"><button type="button">Open</button>@@ -445,10 +451,13 @@ describe('Popover', () => {fireEvent.click(screen.getByRole('button', {name: 'Open'}));const layer = document.querySelector('[popover]');- expect(layer?.className).toContain('Popover__styles.viewportAligned');- expect(layer?.className).toContain('Popover__styles.viewportStart');+ expect(layer?.className).toContain('useLayer__styles.gutterInlineEnd');+ expect(layer?.className).not.toContain(+ 'useLayer__styles.gutterInlineStart',+ );+ expect(layer?.className).toContain('Popover__styles.matchTrigger');expect(layer).toHaveStyle(- 'min-width: min(anchor-size(width),calc(100% - max(var(--spacing-4),env(safe-area-inset-left,0px),env(safe-area-inset-right,0px))))',+ 'min-width: min(anchor-size(width),calc(100vi - calc(max(var(--spacing-4), env(safe-area-inset-left, 0px)) + var(--astryx-layer-inset-inline-start, 0px)) - calc(max(var(--spacing-4), env(safe-area-inset-right, 0px)) + var(--astryx-layer-inset-inline-end, 0px))))',);});@@ -462,12 +471,11 @@ describe('Popover', () => {fireEvent.click(screen.getByRole('button', {name: 'Open'}));const layer = document.querySelector('[popover]');- expect(layer?.className).toContain('Popover__styles.viewportAligned');- expect(layer?.className).toContain('Popover__styles.viewportEnd');- expect(layer?.className).not.toContain('Popover__styles.viewportStart');+ expect(layer?.className).toContain('useLayer__styles.gutterInlineStart');+ expect(layer?.className).not.toContain('useLayer__styles.gutterInlineEnd');});- it('reserves both inline gutters only for centered popovers', () => {+ it('reserves both inline gutters for centered popovers', () => {render(<Popover content={<span>Content</span>} label="Test" alignment="center"><button type="button">Open</button>@@ -477,11 +485,10 @@ describe('Popover', () => {fireEvent.click(screen.getByRole('button', {name: 'Open'}));const layer = document.querySelector('[popover]');- expect(layer?.className).toContain('Popover__styles.viewportCentered');- expect(layer?.className).not.toContain('Popover__styles.viewportAligned');- expect(layer).toHaveStyle(- 'min-width: min(anchor-size(width),calc(100vi - max(var(--spacing-4),env(safe-area-inset-left,0px)) - max(var(--spacing-4),env(safe-area-inset-right,0px))))',- );+ expect(layer?.className).toContain('useLayer__styles.gutterInlineStart');+ expect(layer?.className).toContain('useLayer__styles.gutterInlineEnd');+ // One match-trigger minimum for every alignment: the cap is the viewport.+ expect(layer?.className).toContain('Popover__styles.matchTrigger');});it('uses block-axis gutters for side placement', () => {@@ -498,8 +505,8 @@ describe('Popover', () => {fireEvent.click(screen.getByRole('button', {name: 'Open'}));const layer = document.querySelector('[popover]');- expect(layer?.className).toContain('Popover__styles.viewportBlockStart');- expect(layer?.className).not.toContain('Popover__styles.viewportStart');+ expect(layer?.className).toContain('useLayer__styles.gutterBlockEnd');+ expect(layer?.className).not.toContain('useLayer__styles.gutterInlineEnd');});it('preserves the dialog aria-haspopup contract for render-prop triggers', () => {diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsxindex b4692b21d5..e17ad6ff27 100644--- a/packages/core/src/Popover/Popover.tsx+++ b/packages/core/src/Popover/Popover.tsx@@ -5,7 +5,7 @@/*** @file Popover.tsx* @input Uses React layout measurement and the usePopover hook- * @output Exports Popover with viewport fitting, conditional overflow, and content-first focus+ * @output Exports Popover with conditional overflow and content-first focus above the layer runtime's viewport fit* @position Layer component; declarative wrapper around usePopover hook** For hover-triggered overlays, use HoverCard instead.@@ -31,6 +31,8 @@ import type {BaseProps} from '../BaseProps';import {usePopover} from './usePopover';import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';import {layerAnimations} from '../Layer/layerAnimations.stylex';+import {layerViewportInset} from '../Layer/layerViewportInset.stylex';+import {clampInlineSize, isIntrinsicInlineSize} from '../Layer/clampInlineSize';import {spacingVars} from '../theme/tokens.stylex';import {InteractiveRoleContext} from '../InteractiveRoleContext/InteractiveRoleContext';import type {SpacingStep} from '../utils/types';@@ -40,15 +42,6 @@ import type {SpacingStep} from '../utils/types';// =============================================================================const BUTTON_SELECTOR = 'button, [role="button"]';-const POPOVER_VIEWPORT_GUTTER = spacingVars['--spacing-4'];-const POPOVER_MAX_INLINE_SIZE = `calc(100vi - max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px)) - max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-right, 0px)))`;-const POPOVER_MAX_INLINE_SIZE_FALLBACK = `calc(100vw - ${POPOVER_VIEWPORT_GUTTER} - ${POPOVER_VIEWPORT_GUTTER})`;-const POPOVER_MAX_BLOCK_SIZE = `calc(100dvb - max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px)) - max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px)))`;-const POPOVER_MAX_BLOCK_SIZE_FALLBACK = `calc(100vh - ${POPOVER_VIEWPORT_GUTTER} - ${POPOVER_VIEWPORT_GUTTER})`;-const POPOVER_POSITION_AREA_MAX_INLINE_SIZE = `calc(100% - max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px), env(safe-area-inset-right, 0px)))`;-const POPOVER_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK = `calc(100% - ${POPOVER_VIEWPORT_GUTTER})`;-const POPOVER_INLINE_EDGE_GUTTER = `max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px), env(safe-area-inset-right, 0px))`;-/*** Find the trigger button inside a container element.* Looks for `<button>` or `[role="button"]` — either the element itself@@ -164,7 +157,9 @@ export interface PopoverProps extends Pick</*** Width of the popover container.- * Numbers are px, strings used as-is.+ * Numbers are px, strings are CSS widths. The popover renders at this width+ * up to the viewport minus its gutters — it is never shrunk to the room+ * beside the trigger; when it does not fit there it flips or slides.* @default 'auto'*/width?: number | string;@@ -270,76 +265,37 @@ const styles = stylex.create({anchorWrapper: {display: 'inline-flex',},- viewportFit: {- boxSizing: 'border-box',- maxBlockSize: stylex.firstThatWorks(- POPOVER_MAX_BLOCK_SIZE,- POPOVER_MAX_BLOCK_SIZE_FALLBACK,- ),- },- viewportAligned: {- maxInlineSize: stylex.firstThatWorks(- POPOVER_POSITION_AREA_MAX_INLINE_SIZE,- POPOVER_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK,- ),- },- viewportStart: {- marginInlineEnd: POPOVER_INLINE_EDGE_GUTTER,- },- viewportEnd: {- marginInlineStart: POPOVER_INLINE_EDGE_GUTTER,- },- viewportBlockStart: {- marginBlockEnd: `max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px))`,- },- viewportBlockEnd: {- marginBlockStart: `max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px))`,- },- viewportCentered: {- marginInlineStart: POPOVER_INLINE_EDGE_GUTTER,- marginInlineEnd: POPOVER_INLINE_EDGE_GUTTER,- maxInlineSize: stylex.firstThatWorks(- POPOVER_MAX_INLINE_SIZE,- POPOVER_MAX_INLINE_SIZE_FALLBACK,- ),- },- viewportBlockCentered: {- marginBlockStart: `max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-top, 0px))`,- marginBlockEnd: `max(${POPOVER_VIEWPORT_GUTTER}, env(safe-area-inset-bottom, 0px))`,- maxInlineSize: stylex.firstThatWorks(- POPOVER_MAX_INLINE_SIZE,- POPOVER_MAX_INLINE_SIZE_FALLBACK,- ),- },+ // The painted surface is capped to the viewport with the layer runtime's+ // one definition (spec:AST-059 FR2, FR3): the layer box above it caps the+ // block axis itself and leaves the inline axis to the surface, so a flip is+ // still chosen when the surface does not fit beside the trigger.surfaceViewportFit: {boxSizing: 'border-box',maxInlineSize: stylex.firstThatWorks(- POPOVER_MAX_INLINE_SIZE,- POPOVER_MAX_INLINE_SIZE_FALLBACK,+ layerViewportInset.maxInlineSize,+ layerViewportInset.maxInlineSizeFallback,),maxBlockSize: stylex.firstThatWorks(- POPOVER_MAX_BLOCK_SIZE,- POPOVER_MAX_BLOCK_SIZE_FALLBACK,+ layerViewportInset.maxBlockSize,+ layerViewportInset.maxBlockSizeFallback,),},surfaceScrollable: {overflow: 'auto',overscrollBehavior: 'contain',},- customWidth: (width: string | number) => ({- width: typeof width === 'number' ? `${width}px` : width,+ // An explicit width renders at its size up to the viewport cap, never+ // shrunk to the room beside the trigger (spec:AST-059 FR2). Keywords cannot+ // sit inside min(); the surface cap above bounds them.+ customWidth: (width: string) => ({+ width,}),- matchTriggerAligned: {+ // Without a width the surface prefers the trigger's minimum width, clamped+ // by the runtime's cap because a CSS minimum beats a maximum (FR7).+ matchTrigger: {minWidth: stylex.firstThatWorks(- `min(anchor-size(width), ${POPOVER_POSITION_AREA_MAX_INLINE_SIZE})`,- `min(anchor-size(width), ${POPOVER_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK})`,- 'anchor-size(width)',- ),- },- matchTriggerCentered: {- minWidth: stylex.firstThatWorks(- `min(anchor-size(width), ${POPOVER_MAX_INLINE_SIZE})`,- `min(anchor-size(width), ${POPOVER_MAX_INLINE_SIZE_FALLBACK})`,+ `min(anchor-size(width), ${layerViewportInset.maxInlineSize})`,+ `min(anchor-size(width), ${layerViewportInset.maxInlineSizeFallback})`,'anchor-size(width)',),},@@ -675,28 +631,16 @@ export function Popover({}}, [isOpen, isControlled, popover]);- // Determine popover xstyle- const popoverSizeXstyle = width- ? styles.customWidth(width)- : alignment === 'center'- ? styles.matchTriggerCentered- : styles.matchTriggerAligned;- const isSidePlacement = placement === 'start' || placement === 'end';- const popoverViewportXstyle =- alignment === 'center'- ? isSidePlacement- ? styles.viewportBlockCentered- : styles.viewportCentered- : [- styles.viewportAligned,- isSidePlacement- ? alignment === 'start'- ? styles.viewportBlockStart- : styles.viewportBlockEnd- : alignment === 'start'- ? styles.viewportStart- : styles.viewportEnd,- ];+ // Popover's one sizing fact: an explicit width wins over trigger matching.+ // Fit against the viewport is the layer runtime's (spec:AST-059).+ const popoverSizeXstyle = !width+ ? styles.matchTrigger+ : styles.customWidth(+ typeof width === 'string' && isIntrinsicInlineSize(width)+ ? width.trim()+ : clampInlineSize(width, layerViewportInset.maxInlineSizeFallback),+ );+ const layerXstyle = [popoverSizeXstyle, layerAnimations[placement]];// Sibling mode: render only the popover (no wrapper needed)if (anchorRef && children == null) {@@ -706,12 +650,7 @@ export function Popover({placement,alignment,offset: spacingVars['--spacing-1'],- xstyle: [- styles.viewportFit,- popoverViewportXstyle,- popoverSizeXstyle,- layerAnimations[placement],- ],+ xstyle: layerXstyle,})}</>);@@ -736,12 +675,7 @@ export function Popover({placement,alignment,offset: spacingVars['--spacing-1'],- xstyle: [- styles.viewportFit,- popoverViewportXstyle,- popoverSizeXstyle,- layerAnimations[placement],- ],+ xstyle: layerXstyle,})}</>);@@ -759,12 +693,7 @@ export function Popover({placement,alignment,offset: spacingVars['--spacing-1'],- xstyle: [- styles.viewportFit,- popoverViewportXstyle,- popoverSizeXstyle,- layerAnimations[placement],- ],+ xstyle: layerXstyle,})}</>);diff --git a/packages/core/src/PowerSearch/PowerSearch.test.tsx b/packages/core/src/PowerSearch/PowerSearch.test.tsxindex 1fd3fc8dbc..14d3f6afd3 100644--- a/packages/core/src/PowerSearch/PowerSearch.test.tsx+++ b/packages/core/src/PowerSearch/PowerSearch.test.tsx@@ -645,9 +645,11 @@ describe('field menu sizing', () => {const listbox = screen.getByRole('listbox', {hidden: true});const popover = listbox.closest('[popover]');expect(popover).not.toBeNull();- expect((popover as HTMLElement).style.getPropertyValue('--x-width')).toBe(- '480px',- );+ // Clamped to the layer runtime's viewport cap, never to the room beside+ // the field (spec:AST-059 FR2, FR7).+ expect(+ (popover as HTMLElement).style.getPropertyValue('--x-width'),+ ).toMatch(/^min\(480px, calc\(100vw - /);});});diff --git a/packages/core/src/PowerSearch/PowerSearch.tsx b/packages/core/src/PowerSearch/PowerSearch.tsxindex c7c8e22757..ae7bfb3b97 100644--- a/packages/core/src/PowerSearch/PowerSearch.tsx+++ b/packages/core/src/PowerSearch/PowerSearch.tsx@@ -39,6 +39,7 @@ import type {IconType} from '../Icon';import type {IconName} from '../Icon/globalIconRegistry';import type {InputStatus, FieldStatusVariant} from '../Field';import {usePopover} from '../Popover/usePopover';+import {layerViewportInset} from '../Layer/layerViewportInset.stylex';import {useAnnounce} from '../hooks/useAnnounce';import {spacingVars,@@ -117,12 +118,14 @@ const tokenValueStyles = stylex.create({const popoverLayerStyles = stylex.create({layer: {width: 'anchor-size(width)',- // Floor for comfortable editing, yielding when the available inline- // space cannot fit it, so the editor stays on-screen at narrow viewport- // widths (#4761). Percentages resolve against the position-area region- // (anchor start edge to viewport end), falling back to the viewport- // where area sizing is not honored.- minWidth: `min(400px, calc(100% - ${spacingVars['--spacing-4']}))`,+ // Floor for comfortable editing, clamped by the layer runtime's viewport+ // cap (spec:AST-059 FR7) rather than by the room beside the anchor; the+ // runtime flips or slides the editor into view when it does not fit there+ // (#4761).+ minWidth: stylex.firstThatWorks(+ `min(400px, ${layerViewportInset.maxInlineSize})`,+ `min(400px, ${layerViewportInset.maxInlineSizeFallback})`,+ ),},});diff --git a/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx b/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsxindex a9801c120d..78b0044db5 100644--- a/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx+++ b/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx@@ -20,7 +20,7 @@ import {} from '@testing-library/react';import React, {useState} from 'react';import * as stylex from '@stylexjs/stylex';-import {spacingVars} from '../theme/tokens.stylex';+import {layerViewportInset} from '../Layer/layerViewportInset.stylex';import {PowerSearch} from './PowerSearch';import {PowerSearchEditPopover} from './PowerSearchEditPopover';import {useInternalConfig} from './useInternalConfig';@@ -579,7 +579,10 @@ const CHIP_ROW_COLLAPSE = '@container (max-width: 399px)';const probe = stylex.create({responsiveLayerMinWidth: {- minWidth: `min(400px, calc(100% - ${spacingVars['--spacing-4']}))`,+ minWidth: stylex.firstThatWorks(+ `min(400px, ${layerViewportInset.maxInlineSize})`,+ `min(400px, ${layerViewportInset.maxInlineSizeFallback})`,+ ),},fixedLayerMinWidth: {minWidth: 400},queryContainer: {containerType: 'inline-size'},@@ -755,8 +758,8 @@ describe('narrow-width layout (#4761)', () => {.closest('[popover]') as HTMLElement;expect(layer).not.toBeNull();- // The fixed 400px floor is replaced by one clamped to the available- // inline space, so the popover never opens wider than the screen.+ // The fixed 400px floor is clamped by the layer runtime's viewport cap+ // (spec:AST-059 FR7), so the popover never opens wider than the screen.expectProbeClasses(layer, probe.responsiveLayerMinWidth);for (const cls of atomicClasses(probe.fixedLayerMinWidth)) {expect(layer).not.toHaveClass(cls);diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsxindex b8f0f0f242..452a79c5bb 100644--- a/packages/core/src/Selector/Selector.test.tsx+++ b/packages/core/src/Selector/Selector.test.tsx@@ -667,16 +667,15 @@ describe('Selector', () => {const popover = screen.getByRole('listbox', {hidden: true}).closest('[popover]') as HTMLElement;- // Both block edges, so the gap survives a position-try-fallbacks flip- // to the opposite side (#4803).+ // The clearance rides the edge facing the trigger — the block end for+ // placement="above" — and a position-try flip carries it to the other+ // side with the area, so the gap survives the flip (#4803).await waitFor(() => {- expect(popover.style.getPropertyValue('--x-marginBlockStart')).toBe(+ expect(popover.style.getPropertyValue('--x-marginBlockEnd')).toBe(spacingVars['--spacing-1'],);});- expect(popover.style.getPropertyValue('--x-marginBlockEnd')).toBe(- spacingVars['--spacing-1'],- );+ expect(popover.style.getPropertyValue('--x-marginBlockStart')).toBe('');});it('clears the trigger in search mode', async () => {diff --git a/packages/core/src/Toast/ToastViewport.test.tsx b/packages/core/src/Toast/ToastViewport.test.tsxindex 4e1a4cfbe7..4f6ea0be72 100644--- a/packages/core/src/Toast/ToastViewport.test.tsx+++ b/packages/core/src/Toast/ToastViewport.test.tsx@@ -217,8 +217,14 @@ describe('Toast responsive layout', () => {expect(style.boxSizing).toBe('border-box');expect(style.width).not.toBe('100%');expect(style.paddingInlineEnd).not.toBe('0px');- expect(style.insetInlineStart).toBe('0');- expect(style.insetInlineEnd).toBe('0');+ // The viewport sits at the app-declared inset (spec:AST-059 FR6), 0px+ // unless LayerProvider declares a bar on that edge.+ expect(style.insetInlineStart).toBe(+ 'var(--astryx-layer-inset-inline-start,0px)',+ );+ expect(style.insetInlineEnd).toBe(+ 'var(--astryx-layer-inset-inline-end,0px)',+ );});it('preserves custom start and end insets in LTR and RTL without forcing full width', () => {@@ -286,7 +292,9 @@ describe('ToastViewport placement', () => {it('defaults to bottomEnd with an end-aligned full-inline viewport', () => {const {viewport} = renderPlacement();- expect(getComputedStyle(viewport).bottom).toBe('0px');+ expect(getComputedStyle(viewport).bottom).toBe(+ 'var(--astryx-layer-inset-block-end,0px)',+ );expect(getComputedStyle(viewport).alignItems).toBe('flex-end');expect(getComputedStyle(viewport).width).not.toBe('100%');});@@ -310,7 +318,9 @@ describe('ToastViewport placement', () => {it('maps explicit top and bottom placements to their configured edge', () => {const top = renderPlacement({position: 'topEnd'});- expect(getComputedStyle(top.viewport).top).toBe('0px');+ expect(getComputedStyle(top.viewport).top).toBe(+ 'var(--astryx-layer-inset-block-start,0px)',+ );expect(getComputedStyle(top.viewport).alignItems).toBe('flex-end');expect(getComputedStyle(top.viewport).flexDirection).toBe('column-reverse');top.unmount();@@ -320,7 +330,9 @@ describe('ToastViewport placement', () => {triggerLabel: 'Bottom trigger',body: 'Bottom start',});- expect(getComputedStyle(bottom.viewport).bottom).toBe('0px');+ expect(getComputedStyle(bottom.viewport).bottom).toBe(+ 'var(--astryx-layer-inset-block-end,0px)',+ );expect(getComputedStyle(bottom.viewport).alignItems).toBe('flex-start');bottom.unmount();});diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsxindex fef8e24813..0a5cc10946 100644--- a/packages/core/src/Toast/ToastViewport.tsx+++ b/packages/core/src/Toast/ToastViewport.tsx@@ -35,6 +35,8 @@ import {ToastSurface} from './Toast';import {ToastContext, type ToastContextValue} from './ToastContext';import type {ToastEntry, ToastPosition, ToastDismissReason} from './types';import {useTranslator} from '../i18n';+import {layerInsetProperties} from '../Layer/layerInset';+import type {LayerInset} from '../Layer/LayerContext';const SAFE_AREA_INLINE_START = `max(${spacingVars['--spacing-4']}, env(safe-area-inset-left, 0px))`;const SAFE_AREA_INLINE_END = `max(${spacingVars['--spacing-4']}, env(safe-area-inset-right, 0px))`;@@ -81,19 +83,28 @@ const styles = stylex.create({backgroundColor: 'transparent',overflow: 'visible',},+ // The viewport sits at the inset the app declared on LayerProvider for a+ // bar floating over that edge (spec:AST-059 FR6); unset, each reads 0px.+ // A toast-only `inset` prop writes the same edges inline and wins.viewportInlineSpan: {- insetInlineStart: 0,- insetInlineEnd: 0,+ insetInlineStart: 'var(--astryx-layer-inset-inline-start, 0px)',+ insetInlineEnd: 'var(--astryx-layer-inset-inline-end, 0px)',+ },+ bottomEnd: {+ bottom: 'var(--astryx-layer-inset-block-end, 0px)',+ alignItems: 'flex-end',+ },+ bottomStart: {+ bottom: 'var(--astryx-layer-inset-block-end, 0px)',+ alignItems: 'flex-start',},- bottomEnd: {bottom: 0, alignItems: 'flex-end'},- bottomStart: {bottom: 0, alignItems: 'flex-start'},topEnd: {- top: 0,+ top: 'var(--astryx-layer-inset-block-start, 0px)',alignItems: 'flex-end',flexDirection: 'column-reverse',},topStart: {- top: 0,+ top: 'var(--astryx-layer-inset-block-start, 0px)',alignItems: 'flex-start',flexDirection: 'column-reverse',},@@ -179,6 +190,11 @@ export interface ToastViewportProps {/** Maximum number of visible toasts. @default 5 */maxVisible?: number;inset?: {top?: number; bottom?: number; start?: number; end?: number};+ /**+ * The app-declared viewport inset from LayerProvider (spec:AST-059 FR6).+ * The viewport sits at it on each edge unless `inset` overrides that edge.+ */+ layerInset?: LayerInset;/*** Promote viewport to CSS top layer via popover="manual".* Set to false when inside a dialog or other top-layer element.@@ -307,6 +323,7 @@ export function ToastViewport({position = 'bottomEnd',maxVisible = 5,inset,+ layerInset,isTopLayer = true,children,}: ToastViewportProps) {@@ -515,7 +532,9 @@ export function ToastViewport({const visibleToasts = toasts.slice(-maxVisible);- const insetStyle: React.CSSProperties = {};+ const insetStyle: React.CSSProperties = {+ ...layerInsetProperties(layerInset),+ };if (inset?.top) {insetStyle.top = inset.top;}diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsxindex 26f2fdaeb2..af1c2555ce 100644--- a/packages/core/src/Typeahead/BaseTypeahead.tsx+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx@@ -61,6 +61,8 @@ import {themeProps} from '../utils/themeProps';import {useTranslator} from '../i18n';import {useMergedRefs} from '../hooks/useMergedRefs';+import {layerViewportInset} from '../Layer/layerViewportInset.stylex';+import {clampInlineSize} from '../Layer/clampInlineSize';// =============================================================================// Types// =============================================================================@@ -273,10 +275,6 @@ export interface BaseTypeaheadProps<T extends SearchableItem> extends Omit<// Styles// =============================================================================-const TYPEAHEAD_VIEWPORT_GUTTER = spacingVars['--spacing-4'];-const TYPEAHEAD_POSITION_AREA_MAX_INLINE_SIZE = `calc(100% - max(${TYPEAHEAD_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px), env(safe-area-inset-right, 0px)))`;-const TYPEAHEAD_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK = `calc(100% - ${TYPEAHEAD_VIEWPORT_GUTTER})`;-const styles = stylex.create({input: {display: 'block',@@ -312,16 +310,19 @@ const styles = stylex.create({overflowY: 'auto',padding: spacingVars['--spacing-1'],},+ // The menu prefers the input's width and renders an explicit menuWidth at+ // its size, both clamped to the layer runtime's viewport cap rather than to+ // the room beside the input (spec:AST-059 FR2, FR7).popover: {boxSizing: 'border-box',- minWidth: 'anchor-size(width)',- maxInlineSize: stylex.firstThatWorks(- TYPEAHEAD_POSITION_AREA_MAX_INLINE_SIZE,- TYPEAHEAD_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK,+ minWidth: stylex.firstThatWorks(+ `min(anchor-size(width), ${layerViewportInset.maxInlineSize})`,+ `min(anchor-size(width), ${layerViewportInset.maxInlineSizeFallback})`,+ 'anchor-size(width)',),},- popoverCustomWidth: (width: number) => ({- width: `${width}px`,+ popoverCustomWidth: (width: string) => ({+ width,}),groupHeading: {paddingInline: spacingVars['--spacing-2'],@@ -1207,7 +1208,13 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({offset: spacingVars['--spacing-1'],xstyle: [styles.popover,- menuWidth != null && styles.popoverCustomWidth(menuWidth),+ menuWidth != null &&+ styles.popoverCustomWidth(+ clampInlineSize(+ menuWidth,+ layerViewportInset.maxInlineSizeFallback,+ ),+ ),],},)}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex cda2903001..5e4a7c08a5 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -123,7 +123,7 @@ export type {// Layer providerexport {LayerProvider} from './Layer';-export type {LayerProviderProps, LayerToastConfig} from './Layer';+export type {LayerProviderProps, LayerInset, LayerToastConfig} from './Layer';// Toastexport {Toast, useToast} from './Toast';