An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): under a finger, NavigationStack's bar takes the iOS 26 look (#8396)
Christopher Chedeau0081c1165c57
diff --git a/.changeset/core-internal-entries-lab-scroll-edge.md b/.changeset/core-internal-entries-lab-scroll-edge.mdnew file mode 100644index 0000000000..654409667a--- /dev/null+++ b/.changeset/core-internal-entries-lab-scroll-edge.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: Core's internal touch entry also names, for Lab's NavigationStack, the gesture host and the coarse-pointer check. Its scroll edge effect reads the internal finger-scroll hook and its end call. Apps import nothing new.++@vjeuxdiff --git a/apps/storybook/stories/NavigationStack.stories.tsx b/apps/storybook/stories/NavigationStack.stories.tsxindex 370ea1230c..14ad11773c 100644--- a/apps/storybook/stories/NavigationStack.stories.tsx+++ b/apps/storybook/stories/NavigationStack.stories.tsx@@ -308,3 +308,81 @@ export const LargeTitle: Story = {name: 'Large title',render: () => <LargeTitleStack />,};++// =============================================================================+// Scrolling — content passing under the bar+// =============================================================================++const MESSAGES = Array.from({length: 40}, (_, index) => `Message ${index + 1}`);++function MessageRows() {+ const nav = useNavigationStack<string>();+ return (+ <List>+ {MESSAGES.map(message => (+ <ListItem+ key={message}+ label={message}+ description="Tap to open; scroll the list under the bar."+ endContent={+ <Icon+ icon="chevronRight"+ color="secondary"+ xstyle={rtlStyles.mirror}+ />+ }+ onClick={() => nav.push(message)}+ />+ ))}+ </List>+ );+}++function MessageBody({title}: {title: string}) {+ return (+ <List>+ {Array.from({length: 30}, (_, index) => (+ <ListItem+ key={index}+ label={`${title}, line ${index + 1}`}+ description="Long content scrolls under the bar."+ />+ ))}+ </List>+ );+}++function ScrollingStack() {+ const [path, setPath] = useState<string[]>([]);+ return (+ <div style={{height: '100vh'}}>+ <NavigationStack+ label="Mail"+ root={+ <NavigationScreen title="Inbox">+ <MessageRows />+ </NavigationScreen>+ }+ path={path}+ onPathChange={setPath}+ getKey={entry => entry}+ renderScreen={entry => (+ <NavigationScreen title={entry}>+ <MessageBody title={entry} />+ </NavigationScreen>+ )}+ data-testid="navigation-stack"+ />+ </div>+ );+}++/**+ * Screens long enough to scroll under the bar. On a touch screen the bar+ * paints no background. Once a screen's content has moved 10px under it, a+ * veil of the body colour fades in, as iOS 26's scroll edge effect does.+ * Each screen keeps its own veil through a push, a pop or a back swipe.+ */+export const Scrolling: Story = {+ render: () => <ScrollingStack />,+};diff --git a/packages/core/src/internal/touch.test.ts b/packages/core/src/internal/touch.test.tsindex 29b43412da..c440bf8cb9 100644--- a/packages/core/src/internal/touch.test.ts+++ b/packages/core/src/internal/touch.test.ts@@ -137,6 +137,23 @@ describe('internal/touch', () => {expect(entry.navigation).toBeDefined();});+ it("re-exports by name what NavigationStack's bars and scroll edge effect read", async () => {+ const entry: Record<string, unknown> = await import('./touch');+ const host = await import('../gestures/GestureHost');+ const pointer = await import('../utils/coarsePointer');+ const fingerScroll = await import('../gestures/useFingerScroll');+ expect(entry.getGestureHost).toBe(host.getGestureHost);+ expect(entry.isCoarsePointer).toBe(pointer.isCoarsePointer);+ expect(entry.useFingerScroll).toBe(fingerScroll.useFingerScroll);+ for (const name of [+ 'getGestureHost',+ 'isCoarsePointer',+ 'useFingerScroll',+ ]) {+ expect(typeof entry[name], name).toBe('function');+ }+ });+it('attaches no window or document listeners when it loads', async () => {vi.resetModules();const onWindow = vi.spyOn(window, 'addEventListener');diff --git a/packages/core/src/internal/touch.ts b/packages/core/src/internal/touch.tsindex b7a33df704..f4e8d2f3da 100644--- a/packages/core/src/internal/touch.ts+++ b/packages/core/src/internal/touch.ts@@ -100,3 +100,10 @@ export {useInteractionModalityTracking} from '../utils/interactionModality';// scroll is a finger's, and act when that scroll ends.export {useFingerScroll} from '../gestures/useFingerScroll';export type {UseFingerScrollOptions} from '../gestures/useFingerScroll';++// Lab's NavigationStack scroll edge effect reads the finger-scroll hook+// above, and drops the veil's compositing layer when a finger's scroll ends.+// It reads the gesture host for a finger's landing. The stack's bars read the+// coarse-pointer check.+export {getGestureHost} from '../gestures/GestureHost';+export {isCoarsePointer} from '../utils/coarsePointer';diff --git a/packages/lab/src/NavigationStack/NavigationStack.doc.mjs b/packages/lab/src/NavigationStack/NavigationStack.doc.mjsindex 834b13855b..7a6b65445f 100644--- a/packages/lab/src/NavigationStack/NavigationStack.doc.mjs+++ b/packages/lab/src/NavigationStack/NavigationStack.doc.mjs@@ -25,7 +25,7 @@ export const docs = {name: 'NavigationStack',displayName: 'Navigation Stack',description:- "The navigator. You own the path: pass the entries pushed on the root screen and update them in onPathChange. The stack renders the root screen and one screen per entry, the top one last, keeps covered screens and their scroll positions alive, and makes them inert. The bar shows the top screen's title, its end content and a round Back button with a chevron, named by the screen it returns to. A push moves focus to the new screen's title; a pop returns it to the control that pushed the screen.",+ "The navigator. You own the path: pass the entries pushed on the root screen and update them in onPathChange. The stack renders the root screen and one screen per entry, the top one last, keeps covered screens and their scroll positions alive, and makes them inert. The bar shows the top screen's title, its end content and a round Back button with a chevron, named by the screen it returns to. A push moves focus to the new screen's title; a pop returns it to the control that pushed the screen. Under a finger the bar paints no background and no hairline, as iOS 26's does. Once a screen's content has moved 10px under the bar, a veil of the body colour fades in at the top of that screen. Each screen keeps its own veil through a push, a pop or a back swipe. With a mouse the bar keeps its surface and hairline.",props: [{name: 'root',diff --git a/packages/lab/src/NavigationStack/NavigationStack.test.tsx b/packages/lab/src/NavigationStack/NavigationStack.test.tsxindex 62782c7feb..11bc223e5c 100644--- a/packages/lab/src/NavigationStack/NavigationStack.test.tsx+++ b/packages/lab/src/NavigationStack/NavigationStack.test.tsx@@ -219,6 +219,23 @@ describe('NavigationStack', () => {);});+ it('puts the scroll edge sentinel right after the large title', () => {+ render(<LargeHarness />);+ const scroller = screenCard('Settings')?.firstElementChild;+ const content = scroller?.firstElementChild;+ const [title, sentinel] = Array.from(content?.children ?? []);+ expect(title).toBe(+ screen.getByRole('heading', {level: 1, name: 'Settings'}),+ );+ // It ends where the large title ends, so the veil comes on as the+ // bar's title takes over. The scroller holds no other sentinel.+ expect(sentinel).toHaveAttribute('data-navigation-scroll-edge-sentinel');+ expect(sentinel).toHaveAttribute('aria-hidden', 'true');+ expect(+ scroller?.querySelectorAll('[data-navigation-scroll-edge-sentinel]'),+ ).toHaveLength(1);+ });+it('moves focus to the pushed screen’s large title', async () => {render(<LargeHarness />);const general = screen.getByRole('button', {name: 'General'});@@ -234,6 +251,24 @@ describe('NavigationStack', () => {});});+ it('marks the top of an inline screen’s content with the scroll edge sentinel, under its veil', () => {+ render(<Harness />);+ const card = screenCard('Settings');+ const [sentinel, content] = Array.from(+ card?.firstElementChild?.children ?? [],+ );+ // The sentinel sits just above the content, at its static position in+ // the scroller. The screen's first element stays the content's first.+ expect(sentinel).toHaveAttribute('data-navigation-scroll-edge-sentinel');+ expect(+ content?.querySelector('[data-navigation-scroll-edge-sentinel]'),+ ).toBeNull();+ // The veil is the card's own child, over the scroller, hidden from+ // assistive technology.+ const veil = card?.querySelector(':scope > [data-navigation-scroll-edge]');+ expect(veil).toHaveAttribute('aria-hidden', 'true');+ });+it('shows a screen’s end content in its bar, out of reach once a screen covers it', async () => {render(<Harness rootEndContent={<button type="button">Edit</button>} />);const edit = screen.getByRole('button', {name: 'Edit'});diff --git a/packages/lab/src/NavigationStack/NavigationStack.tsx b/packages/lab/src/NavigationStack/NavigationStack.tsxindex 53668a6def..9d25d78ad7 100644--- a/packages/lab/src/NavigationStack/NavigationStack.tsx+++ b/packages/lab/src/NavigationStack/NavigationStack.tsx@@ -7,7 +7,8 @@* @input React and StyleX. Core's compositor animator and UIKit tables come* from Core's internal touch entry and navigationMotion.ts. The math is in* navigationTransition.ts, and the back swipes in NavigationStackTouch.ts.- * Each screen scrolls through Core's useScrollableArea.+ * Each screen scrolls through Core's useScrollableArea, under Lab's scroll+ * edge effect (internal/useScrollEdgeEffect.ts).* @output Exports NavigationStack, a push/pop navigator with UIKit's* transitions and back gestures. NavigationScreen is one screen: its bar* title, back title, end content and content. useNavigationStack pushes,@@ -36,12 +37,14 @@ import {import * as stylex from '@stylexjs/stylex';import {focusForLastInput,+ isCoarsePointer,isFocusLost,isRtlElement,resolveMotion,solveSpring,toSpring,useInteractionModalityTracking,+ useTouchPresentation,type MotionEngine,type SpringDescription,} from '@astryxdesign/core/internal/touch';@@ -64,8 +67,9 @@ import {programmaticVelocity,} from './navigationTransition';import {useBackSwipes, type BackSwipeStack} from './NavigationStackTouch';-import {navigation, springs} from './navigationMotion';+import {bars, navigation, springs} from './navigationMotion';import {useMotionEngine} from '../internal/useMotionEngine';+import {useScrollEdgeEffect} from '../internal/useScrollEdgeEffect';// =============================================================================// Types@@ -169,39 +173,65 @@ const styles = stylex.create({height: BAR_HEIGHT,zIndex: 1,},- // The bar's own background and hairline, under every screen's bar layer- // (each paints its own opaque background over it).+ // The bar's own background and hairline, under every screen's bar layer,+ // which paints its own background over it. iOS 26.2's bar paints neither:+ // under a finger the content shows through until the screen's scroll edge+ // effect veils it. The literal coarse-pointer key is the resolver's touch+ // constant. A mouse keeps both.barBackground: {position: 'absolute',inset: 0,zIndex: -2,- backgroundColor: colorVars['--color-background-surface'],- borderBottomWidth: 1,+ backgroundColor: {+ default: colorVars['--color-background-surface'],+ '@media (pointer: coarse)': 'transparent',+ },+ borderBottomWidth: {+ default: 1,+ '@media (pointer: coarse)': 0,+ },borderBottomStyle: 'solid',borderBottomColor: colorVars['--color-border'],},// Each screen's bar moves with its screen, as UIKit's per-screen bar copy- // does. It has an opaque background of its own (barLayerBackground), so- // the incoming one covers the outgoing title.+ // does. Under a mouse it has an opaque background of its own+ // (barLayerBackground), so the incoming one covers the outgoing title.+ // Under a finger the bars are clear, so barClip cuts the covered bar at the+ // top card's leading edge.barLayer: {+ position: 'absolute',+ inset: 0,+ // Below the back button: WebKit does not promote the static siblings a+ // moving layer crosses, so the moving one goes underneath.+ zIndex: -1,+ },+ // The box that cuts the bar, moved by the stack. The row inside it moves+ // back by as much, so only the cut moves.+ barClip: {+ position: 'absolute',+ inset: 0,+ overflow: 'hidden',+ },+ barRow: {position: 'absolute',inset: 0,display: 'grid',gridTemplateColumns: '1fr auto 1fr',alignItems: 'center',paddingInline: spacingVars['--spacing-4'],- // Below the back button: WebKit does not promote the static siblings a- // moving layer crosses, so the moving one goes underneath.- zIndex: -1,},- // A layer's opaque background, above the bar's hairline.+ // A layer's background, above the bar's hairline. It is clear under a+ // finger, as the bar's own background.barLayerBackground: {position: 'absolute',insetInline: 0,top: 0,bottom: 1,zIndex: -1,- backgroundColor: colorVars['--color-background-surface'],+ backgroundColor: {+ default: colorVars['--color-background-surface'],+ '@media (pointer: coarse)': 'transparent',+ },},// The one back button: it stays put while the bars move under it.backControl: {@@ -303,6 +333,23 @@ const styles = stylex.create({cardHidden: {contentVisibility: 'hidden',},+ // The scroll edge sentinel stays at its static position, just above the+ // content. The scroller is its containing block, so it scrolls with the+ // content with no positioned wrapper. On an inline screen it sits outside+ // the content, so the screen's first element keeps :first-child.+ edgeSentinelStatic: {+ insetBlockStart: 'auto',+ insetInlineStart: 'auto',+ },+ // On a large-title screen the sentinel follows the large title in the+ // content and ends where the title ends. So the veil comes on as the bar's+ // title takes over. iOS's veil leaves out an expanded large title. The+ // margin is the sentinel's 10px height.+ edgeSentinelAfterLargeTitle: {+ insetBlockStart: 'auto',+ insetInlineStart: 'auto',+ marginBlockStart: -10,+ },dim: {position: 'absolute',inset: 0,@@ -339,6 +386,14 @@ interface ScreenLayers {dim: MotionEngine;bar: MotionEngine;barDim: MotionEngine;+ /**+ * The bar's clip box and the row inside it, moved apart: the row moves by+ * the opposite of the box. Under a finger the box's edge cuts a covered+ * bar at the top card's leading edge, and the row holds still. Identity+ * everywhere else.+ */+ barClip: MotionEngine;+ barClipContent: MotionEngine;titleElement: HTMLElement | null;/** The large title above the content, for `titleDisplayMode="large"`. */largeTitleElement: HTMLElement | null;@@ -413,6 +468,23 @@ function CardLayer({);const card = useMotionEngine();const dim = useMotionEngine();+ const scrollerRef = useRef<HTMLDivElement | null>(null);+ // iOS 26: each screen's scroll view carries its own edge effect, so a push+ // or a pop carries each screen's veil with its card. It switches on once+ // the content has moved 10px under the bar, which overlays the scroller.+ // The veil is half strength at the bar's bottom. A hidden screen, two or+ // more levels down, has no layout to measure, so it runs no effect. Once+ // revealed it measures and switches at once.+ const edge = useScrollEdgeEffect({+ enabled: !isHidden,+ root: scrollerRef,+ rootInset: BAR_HEIGHT,+ edge: `${BAR_HEIGHT}px`,+ sentinelXstyle: isLarge+ ? styles.edgeSentinelAfterLargeTitle+ : styles.edgeSentinelStatic,+ springs: bars.scrollEdgeEffect,+ });// A forward Tab into the scroller moves on to its first plain link or// button.const {getViewportProps, getContentProps} = useScrollableArea({@@ -442,23 +514,34 @@ function CardLayer({{...stylex.props(styles.card, isHidden && styles.cardHidden)}><div{...getViewportProps<HTMLDivElement>({+ ref: scrollerRef,xstyle: [focusOutlineStyles.focusVisible, styles.scroller],})}>+ {isLarge ? null : (+ <div {...edge.sentinelProps} data-navigation-scroll-edge-sentinel />+ )}<div {...getContentProps<HTMLDivElement>({})}>{isLarge ? (- <h1- ref={largeTitleCallback}- tabIndex={-1}- {...stylex.props(- focusOutlineStyles.focusVisible,- styles.largeTitle,- )}>- {props.title}- </h1>+ <>+ <h1+ ref={largeTitleCallback}+ tabIndex={-1}+ {...stylex.props(+ focusOutlineStyles.focusVisible,+ styles.largeTitle,+ )}>+ {props.title}+ </h1>+ <div+ {...edge.sentinelProps}+ data-navigation-scroll-edge-sentinel+ />+ </>) : null}{props.children}</div></div>+ <div {...edge.layerProps} data-navigation-scroll-edge /><divref={dim.ref}aria-hidden@@ -484,6 +567,8 @@ function BarLayer({}) {const bar = useMotionEngine();const barDim = useMotionEngine();+ const clip = useMotionEngine();+ const clipContent = useMotionEngine();// The bar's animators register with it as it attaches. Stable, as the// card's: a new callback would detach and reattach the animator.const barRef = useCallback(@@ -492,9 +577,18 @@ function BarLayer({const entry = registry.get(model.key) ?? {};entry.bar = bar.animator;entry.barDim = barDim.animator;+ entry.barClip = clip.animator;+ entry.barClipContent = clipContent.animator;registry.set(model.key, entry);},- [bar, registry, model.key, barDim.animator],+ [+ bar,+ registry,+ model.key,+ barDim.animator,+ clip.animator,+ clipContent.animator,+ ],);const titleText = useMotionEngine();const wasShownRef = useRef<boolean | null>(null);@@ -535,25 +629,34 @@ function BarLayer({data-navigation-bar={model.key}inert={isCovered || undefined}{...stylex.props(styles.barLayer, isCovered && styles.barLayerCovered)}>- <div aria-hidden {...stylex.props(styles.barLayerBackground)} />- <div {...stylex.props(styles.barStart)} />- <h2- ref={titleRefs}- tabIndex={-1}- aria-hidden={isLargeTitleShown || undefined}- {...stylex.props(styles.barTitle, focusOutlineStyles.focusVisible)}>- {props.title}- </h2>- <div {...stylex.props(styles.barEnd)}>{props.endContent}</div>- <div- ref={barDim.ref}- aria-hidden- {...stylex.props(- styles.dim,- styles.barDim,- dynamicStyles.dimColor(navigation.dimmingAlpha),- )}- />+ <div ref={clip.ref} {...stylex.props(styles.barClip)}>+ <div ref={clipContent.ref} {...stylex.props(styles.barRow)}>+ <div+ aria-hidden+ data-navigation-bar-background+ {...stylex.props(styles.barLayerBackground)}+ />+ <div {...stylex.props(styles.barStart)} />+ <h2+ ref={titleRefs}+ tabIndex={-1}+ aria-hidden={isLargeTitleShown || undefined}+ {...stylex.props(styles.barTitle, focusOutlineStyles.focusVisible)}>+ {props.title}+ </h2>+ <div {...stylex.props(styles.barEnd)}>{props.endContent}</div>+ <div+ ref={barDim.ref}+ aria-hidden+ data-navigation-bar-dim+ {...stylex.props(+ styles.dim,+ styles.barDim,+ dynamicStyles.dimColor(navigation.dimmingAlpha),+ )}+ />+ </div>+ </div></div>);}@@ -691,6 +794,13 @@ function writingDirection(element: HTMLElement | null): 'ltr' | 'rtl' {* chevron fades out at once and the platter leaves with the screen. A back* swipe leaves it alone until the pop finishes.*+ * Under a finger the bars paint no background and no hairline, as iOS 26's+ * do. Each screen carries a scroll edge effect: a veil of the body colour+ * that comes in once the content has moved 10px under the bar. The veil+ * fades for a finger's scroll and rides the screen's card through a push, a+ * pop or a back swipe. The bar a card covers is cut at that card's leading+ * edge. A mouse keeps the bar's surface and hairline.+ ** In a browser tab the screen's leading edge is the browser's own back* swipe, which iOS Safari keeps. So the stack's edge swipe runs only in a* home-screen web app (`navigator.standalone`). The content swipe ignores@@ -871,6 +981,85 @@ export function NavigationStack<T>({[registry],);+ // Under a finger the bars are iOS 26's: clear, so a covered bar would show+ // through the card above it. UIKit's covering view cuts the title under it+ // at its leading edge. Here the covered bar's clip box follows the top+ // card's leading edge, and the row inside it holds still. At rest the box+ // is shut. While the cards travel it moves on their spring, or with the+ // finger. The stack reads the touch presentation as each move starts, as+ // the swipes do. A mouse keeps opaque bars and the boxes at identity.+ const clearBarsRef = useRef(false);+ const readClearBars = useCallback(() => {+ clearBarsRef.current = isCoarsePointer(+ containerRef.current?.ownerDocument.defaultView,+ );+ return clearBarsRef.current;+ }, []);+ /**+ * Where the covered bar's box goes so its edge meets the top card's+ * leading edge (the top card at `topX`, the covered bar at `underBarX`).+ */+ const clipXFor = useCallback((topX: number, underBarX: number) => {+ const width = cardsRef.current?.clientWidth ?? 0;+ const sign = writingDirection(containerRef.current) === 'rtl' ? -1 : 1;+ return topX - underBarX - sign * width;+ }, []);+ const setClip = useCallback(+ (key: string | null, x: number) => {+ const layers = layersOf(key);+ layers?.barClip?.set({x});+ layers?.barClipContent?.set({x: -x});+ },+ [layersOf],+ );++ const shownBarsRef = useRef<ReadonlySet<string>>(new Set());+ // A bar that mounts covered parks at the parallax, as `settle` parks a+ // covered screen. A pop that reveals a screen two levels down brings one.+ // Under a finger it is cut away at the top card's leading edge; under a+ // mouse it is whole, under the opaque top bar. A bar that was already shown+ // keeps its place, and the transition moves it. This drives the bars'+ // compositor animators, the system it syncs.+ useLayoutEffect(() => {+ const before = shownBarsRef.current;+ shownBarsRef.current = new Set(+ underKey == null ? [topKey] : [topKey, underKey],+ );+ if (underKey == null || before.has(underKey)) {+ return;+ }+ const values = layersAt(+ 0,+ cardsRef.current?.clientWidth ?? 0,+ writingDirection(containerRef.current),+ );+ layersOf(underKey)?.bar?.set({x: values.underX});+ setClip(underKey, readClearBars() ? clipXFor(0, values.underX) : 0);+ }, [topKey, underKey, layersOf, readClearBars, setClip, clipXFor]);++ const {isTouch} = useTouchPresentation();+ const touchSeenRef = useRef(isTouch);+ // The touch presentation can change while a screen is covered (a tablet+ // losing its mouse). The bars' backgrounds follow it at once, so the+ // covered bar's cut follows it too. A running move reads it again as it+ // settles. This drives the bars' compositor animators, the system it syncs.+ useLayoutEffect(() => {+ if (touchSeenRef.current === isTouch) {+ return;+ }+ touchSeenRef.current = isTouch;+ const running = runningRef.current;+ if (underKey == null || (running != null && !running.done)) {+ return;+ }+ const values = layersAt(+ 0,+ cardsRef.current?.clientWidth ?? 0,+ writingDirection(containerRef.current),+ );+ setClip(underKey, readClearBars() ? clipXFor(0, values.underX) : 0);+ }, [isTouch, underKey, readClearBars, setClip, clipXFor]);+/*** Writes the layers for progress p (a finger's frame, or a transition's* first one; no animation). The top bar moves with its card. Under a@@ -893,12 +1082,20 @@ export function NavigationStack<T>({topLayers?.card?.set({x: values.topX});topLayers?.bar?.set({x: values.topX});underLayers?.card?.set({x: values.underX});- underLayers?.bar?.set({x: underBar === 'ride' ? values.underX : 0});+ const underBarX = underBar === 'ride' ? values.underX : 0;+ underLayers?.bar?.set({x: underBarX});underLayers?.dim?.set({opacity: values.dim});underLayers?.barDim?.set({opacity: values.dim});+ // Under a finger the covered bar is cut where the top card's leading+ // edge is; under a mouse both bars are whole.+ setClip(top, 0);+ setClip(+ under,+ clearBarsRef.current ? clipXFor(values.topX, underBarX) : 0,+ );progressRef.current = p;},- [layersOf],+ [layersOf, setClip, clipXFor],);/**@@ -975,6 +1172,57 @@ export function NavigationStack<T>({),);}+ if (clearBarsRef.current) {+ // Under a finger the covered bar's box rides the top card's leading+ // edge on the same spring, from the same start and velocity. The+ // difference of the two bars' curves is the same curve. There is no+ // clamp: an overshoot past rest stays cut. Reduced Motion's+ // cross-fade has no travel: the titles swap at once, as UIKit's do.+ const underBarTo =+ underBar === 'ride'+ ? values.underX+ : (underLayers?.bar?.get('x') ?? 0);+ const clipTo = clipXFor(values.topX, underBarTo);+ setClip(top, 0);+ if (+ (topLayers?.card?.reducedMotion({touchRelease: release}) ?? 'off') !==+ 'off'+ ) {+ setClip(under, clipTo);+ if (to === 1) {+ // A pop: the leaving bar goes at once too.+ setClip(top, direction === 'rtl' ? width : -width);+ }+ } else if (underLayers?.barClip && underLayers.barClipContent) {+ const clipVelocity =+ velocity == null+ ? undefined+ : velocity.topX - (underBar === 'ride' ? velocity.underX : 0);+ handles.push(+ underLayers.barClip.animate(+ {x: clipTo},+ {+ spring,+ velocity: clipVelocity == null ? undefined : {x: clipVelocity},+ },+ {at, touchRelease: release},+ ),+ underLayers.barClipContent.animate(+ {x: -clipTo},+ {+ spring,+ velocity: clipVelocity == null ? undefined : {x: -clipVelocity},+ },+ {at, touchRelease: release},+ ),+ );+ }+ } else {+ // Under a mouse both bars are whole, also after a pointer that was+ // coarse left a cut.+ setClip(top, 0);+ setClip(under, 0);+ }for (const dim of [underLayers?.dim, underLayers?.barDim]) {if (dim == null) {continue;@@ -1001,7 +1249,7 @@ export function NavigationStack<T>({results => results.every(Boolean),);},- [layersOf],+ [layersOf, setClip, clipXFor],);/**@@ -1064,15 +1312,21 @@ export function NavigationStack<T>({layers?.dim?.set({opacity: 0});layers?.bar?.set({x: 0});layers?.barDim?.set({opacity: 0});+ // A screen on top shows its whole bar, under any pointer.+ setClip(key, 0);} else {// Covered: parked at the parallax, under the top screen and its bar.layers?.card?.set({x: values.underX, opacity: 1});layers?.dim?.set({opacity: 1});layers?.bar?.set({x: values.underX});layers?.barDim?.set({opacity: 1});+ // Under a finger cut away at the top card's leading edge (the top+ // card at rest); under a mouse whole, parked under the opaque bar.+ // Read again here: the pointer may have changed during the move.+ setClip(key, readClearBars() ? clipXFor(0, values.underX) : 0);}},- [layersOf],+ [layersOf, readClearBars, setClip, clipXFor],);const focusAfter = useCallback(@@ -1127,6 +1381,7 @@ export function NavigationStack<T>({useLayoutEffect(() => {const {view, fadeBack} = transitionInputsRef.current;const transition = view.transition;+ readClearBars();if (transition.kind === 'none') {// Settle every screen where it rests.view.models.forEach((model, index) => {@@ -1229,6 +1484,7 @@ export function NavigationStack<T>({animateProgress,focusAfter,layersOf,+ readClearBars,setProgress,settle,backControl.animator,@@ -1336,7 +1592,8 @@ export function NavigationStack<T>({},grab: (top, under) => {// Grab whatever is moving: the top card's presentation value is the- // progress to continue from.+ // progress to continue from. A finger's move starts here.+ readClearBars();const width = cardsRef.current?.clientWidth ?? 0;const x = layersOf(top)?.card?.get('x') ?? 0;const direction = writingDirection(containerRef.current);@@ -1346,6 +1603,8 @@ export function NavigationStack<T>({layers?.dim?.stop();layers?.bar?.stop();layers?.barDim?.stop();+ layers?.barClip?.stop();+ layers?.barClipContent?.stop();}runningRef.current = null;return progressFromScreen(x, width, direction);diff --git a/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts b/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.tsindex 728ff79304..fa390dc9ba 100644--- a/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts+++ b/packages/lab/src/NavigationStack/__tests__/NavigationStack.interaction.browser.spec.ts@@ -29,7 +29,10 @@ import {countBetween,drag,flick,+ freezePageWhen,holdAnimations,+ installPageFreeze,+ installTimerGate,markElement,openStory,releaseAnimations,@@ -37,6 +40,7 @@ import {sampleRects,startBusyControl,startScreencast,+ thawPage,touchDriver,touchStoryboard,traceRendering,@@ -298,6 +302,127 @@ const crit = (response: number, ms: number) => {return 1 - (1 + u) * Math.exp(-u);};+/** One scene time of a push: where the incoming card and the cut stand. */+interface CutSample {+ /** The incoming card's leading edge, px. */+ cardEdge: number;+ /** How far the covered bar's cut is from that edge, px. */+ gap: number;+}++/** The scene times `cutAcrossPush` reads, ms after the push starts. */+const CUT_TIMES = [16, 50, 90, 130, 180, 240, 300, 380];++/**+ * Runs `push`, then reads the incoming card's leading edge and the covered+ * bar's cut from their rendered boxes at each of `CUT_TIMES`. The scene+ * freezes while the push runs, so nothing moves or retires. Each read moves+ * every animation of the push to one scene time first. Mid-flight, WebKit can+ * report one moving layer a frame late; at a held time it cannot. A freeze+ * that lands late on a busy machine still reads the whole flight. The page+ * needs `installPageFreeze` before it loads and `installTimerGate` after.+ */+async function cutAcrossPush(+ page: Page,+ push: () => Promise<void>,+ {+ covered,+ incoming,+ direction,+ }: {covered: string; incoming: string; direction: 'ltr' | 'rtl'},+): Promise<CutSample[]> {+ // Armed before the push, so the scene freezes while it runs.+ const frozen = freezePageWhen(+ page,+ key =>+ document+ .querySelector(`[data-navigation-screen="${key}"]`)+ ?.getAnimations()+ .some(animation => animation.playState === 'running') === true,+ incoming,+ );+ await push();+ await frozen;+ try {+ return await page.evaluate(+ ([coveredKey, incomingKey, dir, times]) => {+ const stack = document.querySelector(+ '[data-testid="navigation-stack"]',+ );+ const cardElement = document.querySelector(+ `[data-navigation-screen="${incomingKey}"]`,+ );+ const cutElement = document.querySelector(+ `[data-navigation-bar="${coveredKey}"]`,+ )?.firstElementChild;+ if (stack == null || cardElement == null || cutElement == null) {+ return [];+ }+ const runs = document.getAnimations().filter(animation => {+ const target =+ animation.effect instanceof KeyframeEffect+ ? animation.effect.target+ : null;+ return (+ target != null &&+ stack.contains(target) &&+ animation.startTime != null+ );+ });+ // Read once: a held run's start follows its current time.+ const starts = runs.map(animation => Number(animation.startTime));+ const heldAt = runs.map(animation => animation.currentTime);+ // Scene times count from the incoming card's own start, whatever+ // else in the stack animates (a row's press feedback).+ const cardRun = runs.findIndex(+ animation =>+ animation.effect instanceof KeyframeEffect &&+ animation.effect.target === cardElement,+ );+ if (cardRun < 0) {+ return [];+ }+ const origin = starts[cardRun];+ const samples = times.map(t => {+ runs.forEach((animation, index) => {+ animation.currentTime = Math.max(0, origin + t - starts[index]);+ });+ const cardBox = cardElement.getBoundingClientRect();+ const cutBox = cutElement.getBoundingClientRect();+ // The cut's trailing edge meets the card's leading edge.+ const cardEdge = dir === 'rtl' ? cardBox.right : cardBox.left;+ const cutEdge = dir === 'rtl' ? cutBox.left : cutBox.right;+ return {cardEdge, gap: Math.abs(cutEdge - cardEdge)};+ });+ // Back where the freeze held them, so the thaw plays on from there.+ runs.forEach((animation, index) => {+ animation.currentTime = heldAt[index];+ });+ return samples;+ },+ [covered, incoming, direction, CUT_TIMES] as const,+ );+ } finally {+ await thawPage(page);+ }+}++/**+ * The samples span the flight, and at every one the cut stays on the card's+ * leading edge.+ */+function expectCutOnCardEdge(samples: CutSample[], width: number) {+ const trace = JSON.stringify(samples);+ expect(samples.length, trace).toBeGreaterThanOrEqual(5);+ const travel = Math.abs(+ samples[0].cardEdge - samples[samples.length - 1].cardEdge,+ );+ expect(travel, trace).toBeGreaterThan(width * 0.5);+ for (const sample of samples) {+ expect(sample.gap, trace).toBeLessThan(2);+ }+}+const rowCenter = async (page: Page, name: string) => {const box = await page.getByRole('button', {name}).first().boundingBox();if (box == null) {@@ -880,7 +1005,85 @@ test('a push keeps advancing every frame while the main thread is blocked', asynexpect(proof.verdict.failures, proof.summary).toEqual([]);});-test('the incoming bar covers the old title while the main thread is blocked', async ({+// With a mouse the bars are opaque: the incoming one covers the old title.+// Under a finger iOS 26's bars are clear (NavigationStackScrollEdge's proofs)+// and the incoming screen cuts the old title instead (the next test).+test('with a mouse, the incoming bar covers the old title while the main thread is blocked', async ({+ browser,+ browserName,+}) => {+ test.skip(+ browserName !== 'chromium',+ 'screencast frame evidence is Chromium-only in Playwright (WebKit: the iOS simulator rig)',+ );+ const {context, page} = await newFinePage(browser);+ try {+ await openStack(page, 'settings', {pointer: 'mouse'});+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ // A marker at the trailing end of the root's title: the pushed screen's+ // opaque bar slides over it on the compositor.+ await page.locator('[data-navigation-bar="root"] h2').evaluate(title => {+ const element = title as HTMLElement;+ element.style.position = 'relative';+ const chip = document.createElement('div');+ chip.setAttribute('aria-hidden', 'true');+ chip.style.cssText =+ 'position:absolute;top:4px;right:0;width:10px;height:10px;background:rgb(255,0,255);pointer-events:none;';+ element.append(chip);+ });+ const cast = await startScreencast(page);+ const row = await rowCenter(page, 'General');+ await page.mouse.click(row.x, row.y);+ await waitForAnimation(card(page, 'screen-General'), {minProgressMs: 16});+ const block = await blockMainThread(page, 900);+ await page.waitForTimeout(150);+ const frames = await cast.stop();+ const tracked = await trackMarker(page, frames);+ const trace = JSON.stringify(+ tracked.map(f => [Math.round(f.t - block.from), f.box?.x ?? null]),+ );+ const during = tracked.filter(f => f.t > block.from && f.t < block.to - 20);+ // Seen while blocked, then covered before the block ends.+ expect(+ during.some(f => f.box != null),+ trace,+ ).toBe(true);+ expect(during.at(-1)?.box ?? null, trace).toBeNull();+ } finally {+ await context.close();+ }+});++/**+ * How much of bar `key` its clip box shows inside the stack. It is a+ * fraction of the stack's width, rounded to 0.01: 0 cut away, 1 whole.+ */+async function readCut(page: Page, key: string) {+ return page.evaluate(k => {+ const stack = document+ .querySelector('[data-testid="navigation-stack"]')+ ?.getBoundingClientRect();+ const box = document+ .querySelector(`[data-navigation-bar="${k}"]`)+ ?.firstElementChild?.getBoundingClientRect();+ if (stack == null || box == null) {+ return {shown: -1};+ }+ const shown =+ Math.max(+ 0,+ Math.min(box.right, stack.right) - Math.max(box.left, stack.left),+ ) / stack.width;+ return {shown: Math.round(shown * 100) / 100};+ }, key);+}++// Under a finger iOS 26's bars are clear, and the bar a card covers is cut+// at that card's leading edge. So the incoming screen still hides the title+// it slides over, even while the main thread is blocked.+test('under a finger, the incoming screen cuts the old title while the main thread is blocked', async ({page,browserName,}) => {@@ -889,8 +1092,9 @@ test('the incoming bar covers the old title while the main thread is blocked', a'screencast frame evidence is Chromium-only in Playwright (WebKit: the iOS simulator)',);const {driver} = await openStack(page, 'settings');- // A marker at the trailing end of the root's title: the pushed screen's- // opaque bar slides over it on the compositor.+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(true);await page.locator('[data-navigation-bar="root"] h2').evaluate(title => {const element = title as HTMLElement;element.style.position = 'relative';@@ -916,7 +1120,7 @@ test('the incoming bar covers the old title while the main thread is blocked', atracked.map(f => [Math.round(f.t - block.from), f.box?.x ?? null]),);const during = tracked.filter(f => f.t > block.from && f.t < block.to - 20);- // Seen while blocked, then covered before the block ends.+ // Seen while blocked, then cut before the block ends.expect(during.some(f => f.box != null),trace,@@ -924,6 +1128,145 @@ test('the incoming bar covers the old title while the main thread is blocked', aexpect(during.at(-1)?.box ?? null, trace).toBeNull();});+test('under a finger the cut rides the incoming card’s leading edge', async ({+ page,+}) => {+ // The page clock a freeze needs, installed before the story loads.+ await installPageFreeze(page);+ const {driver, width} = await openStack(page, 'settings');+ await installTimerGate(page);+ const row = await rowCenter(page, 'General');+ // Through the push the root's bar shows only left of the incoming card:+ // the cut and the card's edge move on one spring.+ const samples = await cutAcrossPush(page, () => driver.tap(row), {+ covered: 'root',+ incoming: 'screen-General',+ direction: 'ltr',+ });+ expectCutOnCardEdge(samples, width);+ await waitForRest(card(page, 'screen-General'));+ expect(await readCut(page, 'root')).toEqual({shown: 0});+ expect(await readCut(page, 'screen-General')).toEqual({shown: 1});+});++test('under a finger in a right-to-left stack, the cut mirrors', async ({+ page,+}) => {+ await installPageFreeze(page);+ const {driver, width} = await openStack(page, 'settings');+ await installTimerGate(page);+ await page+ .getByTestId('navigation-stack')+ .evaluate(element => element.setAttribute('dir', 'rtl'));+ const row = await rowCenter(page, 'General');+ // The incoming card enters from the left: the root's bar shows only right+ // of the card's leading edge.+ const samples = await cutAcrossPush(page, () => driver.tap(row), {+ covered: 'root',+ incoming: 'screen-General',+ direction: 'rtl',+ });+ expectCutOnCardEdge(samples, width);+ await waitForRest(card(page, 'screen-General'));+ expect(await readCut(page, 'root')).toEqual({shown: 0});+ expect(await readCut(page, 'screen-General')).toEqual({shown: 1});+});++test('a pointer that turns fine after a push leaves the revealed bar whole', async ({+ page,+}) => {+ // A tablet that picks up a trackpad. The push runs under a finger, which+ // cuts the root's bar away. Then the pointer is fine and Back pops at once.+ const {driver} = await openStack(page, 'settings');+ await driver.tap(await rowCenter(page, 'General'));+ await waitForRest(card(page, 'screen-General'));+ expect(await readCut(page, 'root')).toEqual({shown: 0});+ await page.evaluate(() => {+ const matchMedia = window.matchMedia.bind(window);+ window.matchMedia = (query: string) =>+ query.replace(/\s/g, '') === '(pointer:coarse)'+ ? matchMedia('(max-width: 0px)')+ : matchMedia(query);+ });+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ await page.locator('[data-navigation-back]').click();+ await expect(card(page, 'screen-General')).toHaveCount(0);+ await waitForRest(card(page, 'root'));+ expect(await readCut(page, 'root')).toEqual({shown: 1});+});++test('a pointer that turns coarse while a screen is covered cuts the covered bar away', async ({+ browser,+ browserName,+}) => {+ test.skip(+ browserName !== 'chromium',+ 'Only Chromium turns the primary pointer coarse mid-test (touch emulation).',+ );+ // A tablet that loses its mouse. The push runs under a mouse, so the root's+ // bar stays whole under the opaque top bar. Then the pointer turns coarse:+ // the bars clear, and the covered bar is cut away at once.+ const {context, page} = await newFinePage(browser);+ try {+ await openStack(page, 'settings', {pointer: 'mouse'});+ const row = await rowCenter(page, 'General');+ await page.mouse.click(row.x, row.y);+ await waitForRest(card(page, 'screen-General'));+ // The root's bar is there and laid out, and whole at the parallax.+ const title = page.locator('[data-navigation-bar="root"] h2');+ expect((await title.boundingBox())?.width ?? 0).toBeGreaterThan(0);+ expect((await readCut(page, 'root')).shown).toBeGreaterThan(0.5);+ const cdp = await context.newCDPSession(page);+ await cdp.send('Emulation.setTouchEmulationEnabled', {+ enabled: true,+ maxTouchPoints: 1,+ });+ await expect+ .poll(() => page.evaluate(() => matchMedia('(pointer: coarse)').matches))+ .toBe(true);+ await expect.poll(() => readCut(page, 'root')).toEqual({shown: 0});+ expect(await readCut(page, 'screen-General')).toEqual({shown: 1});+ } finally {+ await context.close();+ }+});++test('under a finger, a pop that reveals a screen two levels down leaves its bar cut away', async ({+ page,+}) => {+ // The story opens two screens deep, so the root's bar mounts under General+ // only once the pop is over.+ await openStack(page, 'pushed');+ await page.locator('[data-navigation-back]').click();+ await expect(card(page, 'screen-About')).toHaveCount(0);+ await waitForRest(card(page, 'screen-General'));+ // The root's bar is there and laid out, so its cut is a real reading.+ await expect(page.locator('[data-navigation-bar="root"]')).toHaveCount(1);+ const box = await page+ .locator('[data-navigation-bar="root"] h2')+ .boundingBox();+ expect(box?.width ?? 0).toBeGreaterThan(0);+ expect(await readCut(page, 'root')).toEqual({shown: 0});+ expect(await readCut(page, 'screen-General')).toEqual({shown: 1});+});++test('under a finger, Back reveals the covered bar whole', async ({page}) => {+ const {driver} = await openStack(page, 'settings');+ await driver.tap(await rowCenter(page, 'General'));+ await waitForRest(card(page, 'screen-General'));+ expect(await readCut(page, 'root')).toEqual({shown: 0});+ const back = await page.locator('[data-navigation-back]').boundingBox();+ if (back == null) {+ throw new Error('no back button');+ }+ await driver.tap({x: back.x + back.width / 2, y: back.y + back.height / 2});+ await expect(card(page, 'screen-General')).toHaveCount(0);+ await waitForRest(card(page, 'root'));+ expect(await readCut(page, 'root')).toEqual({shown: 1});+});+test('under a mouse a drag across the content pops, as a finger’s does', async ({browser,}) => {@@ -1040,25 +1383,53 @@ test.describe('the bars ride with their screens, as UIKit’s', () => {}});- test('each bar is opaque and stacks over the one it covers', async ({+ test('with a mouse, each bar is opaque and stacks over the one it covers', async ({+ browser,+ }) => {+ const {context, page} = await newFinePage(browser);+ try {+ await openStack(page, 'settings', {pointer: 'mouse'});+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ const row = await rowCenter(page, 'General');+ await page.mouse.click(row.x, row.y);+ await waitForRest(card(page, 'screen-General'));+ const bars = await page.evaluate(() =>+ [...document.querySelectorAll('[data-navigation-bar]')].map(bar => ({+ key: bar.getAttribute('data-navigation-bar'),+ // Each layer paints its opaque background on its own element.+ background: getComputedStyle(+ bar.querySelector('[data-navigation-bar-background]') ?? bar,+ ).backgroundColor,+ })),+ );+ expect(bars.map(bar => bar.key)).toEqual(['root', 'screen-General']);+ for (const bar of bars) {+ // An rgb() colour has no alpha; rgba(…, 0) would let the title show.+ expect(bar.background, JSON.stringify(bar)).toMatch(/^rgb\(/);+ }+ } finally {+ await context.close();+ }+ });++ test('under a finger each bar is clear, and the covered one cut away at rest', async ({page,}) => {const {driver} = await openStack(page, 'settings');await driver.tap(await rowCenter(page, 'General'));await waitForRest(card(page, 'screen-General'));const bars = await page.evaluate(() =>- [...document.querySelectorAll('[data-navigation-bar]')].map(bar => ({- key: bar.getAttribute('data-navigation-bar'),- // Each layer paints its opaque background on its first child.- background: getComputedStyle(bar.firstElementChild ?? bar)- .backgroundColor,- })),+ [...document.querySelectorAll('[data-navigation-bar-background]')].map(+ background => getComputedStyle(background).backgroundColor,+ ),);- expect(bars.map(bar => bar.key)).toEqual(['root', 'screen-General']);- for (const bar of bars) {- // An rgb() colour has no alpha; rgba(…, 0) would let the title show.- expect(bar.background, JSON.stringify(bar)).toMatch(/^rgb\(/);- }+ expect(bars).toEqual(['rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 0)']);+ // iOS 26 cuts the covered screen's bar at the top card's leading edge.+ // At rest nothing of it shows, and the top bar is whole.+ expect(await readCut(page, 'root')).toEqual({shown: 0});+ expect(await readCut(page, 'screen-General')).toEqual({shown: 1});});test('the covered bar’s dimming ends above the bar’s hairline', async ({@@ -1067,13 +1438,16 @@ test.describe('the bars ride with their screens, as UIKit’s', () => {const {driver} = await openStack(page, 'settings');await driver.tap(await rowCenter(page, 'General'));await waitForRest(card(page, 'screen-General'));- // Each layer's dimming is its last child; the hairline is the bar's- // bottom pixel, which the layers' backgrounds leave uncovered.+ // The hairline is the bar's bottom pixel, which the layers' backgrounds+ // leave uncovered. Each layer's dimming sits in its cut row.const layers = await page.evaluate(() =>[...document.querySelectorAll('[data-navigation-bar]')].map(bar => ({key: bar.getAttribute('data-navigation-bar'),bottom: bar.getBoundingClientRect().bottom,- dimBottom: bar.lastElementChild?.getBoundingClientRect().bottom ?? NaN,+ dimBottom:+ bar+ .querySelector('[data-navigation-bar-dim]')+ ?.getBoundingClientRect().bottom ?? NaN,})),);expect(layers.map(layer => layer.key)).toEqual(['root', 'screen-General']);@@ -1314,6 +1688,12 @@ test.describe('edge cases', () => {first?.cards['screen-About'] ?? 0,JSON.stringify(first),).toBeGreaterThan(width * 0.5);+ // Under a finger both end at rest. The screen below is cut away, so the+ // root's bar is no longer rendered, and the top bar is whole.+ await waitForRest(card(page, 'screen-About'));+ expect(await page.locator('[data-navigation-bar="root"]').count()).toBe(0);+ expect(await readCut(page, 'screen-General')).toEqual({shown: 0});+ expect(await readCut(page, 'screen-About')).toEqual({shown: 1});});test('a sideways drag on a strip that can still scroll scrolls it instead of popping', async ({diff --git a/packages/lab/src/NavigationStack/__tests__/NavigationStackScrollEdge.interaction.browser.spec.ts b/packages/lab/src/NavigationStack/__tests__/NavigationStackScrollEdge.interaction.browser.spec.tsnew file mode 100644index 0000000000..2e09aac425--- /dev/null+++ b/packages/lab/src/NavigationStack/__tests__/NavigationStackScrollEdge.interaction.browser.spec.ts@@ -0,0 +1,331 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file NavigationStackScrollEdge.interaction.browser.spec.ts+ * @input The built "Scrolling" NavigationStack story on the touch phone+ * profile, programmatic and real-touch scrolls, and the interaction harness+ * @output Proofs of the bar's iOS 26 look under a finger. The bar paints no+ * background or hairline, and each screen's veil switches at 10px. A push+ * and a pop keep each screen's veil, and a finger's scroll fades it. A+ * screen a pop reveals shows the veil for its own scroll. On a large-title+ * screen the veil comes on as the bar's title takes over. The veil is+ * hidden from assistive technology. A mouse keeps the bar's surface and+ * runs no veil.+ * @position Interaction proof for NavigationStack.tsx and Lab's+ * internal/useScrollEdgeEffect.ts, run by `pnpm test:interaction`. The+ * phone profile's coarse pointer is the touch case in both engines.+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ animationStoryboard,+ drag,+ frames,+ openStory,+ releaseAnimations,+ touchDriver,+ waitForAnimation,+ waitForRest,+ withStorybook,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++const STORY = 'lab-navigationstack--scrolling';++const card = (page: Page, screen: string) =>+ page.locator(`[data-navigation-screen="${screen}"]`);+const veil = (page: Page, screen: string) =>+ card(page, screen).locator(':scope > [data-navigation-scroll-edge]');+const scroller = (page: Page, screen: string) =>+ card(page, screen).locator(':scope > :first-child');++async function presentedOpacity(layer: Locator): Promise<number> {+ return layer.evaluate(element => Number(getComputedStyle(element).opacity));+}++/** Scrolls a screen, lets the observer report, waits for the fade to end. */+async function settleAt(page: Page, screen: string, top: number) {+ await scroller(page, screen).evaluate((element, y) => {+ element.scrollTop = y;+ }, top);+ await frames(page, 3);+ await waitForRest(veil(page, screen));+ return presentedOpacity(veil(page, screen));+}++/**+ * Scrolls a screen while a finger rests on its content, and lifts the finger+ * two frames later, after the observer has reported. The gesture host reads+ * the scroll as the finger's, so the veil fades.+ */+async function fingerScrollTo(page: Page, screen: string, top: number) {+ await scroller(page, screen).evaluate((element, y) => {+ const target = element.lastElementChild ?? element;+ const touch = {identifier: 7, clientX: 100, clientY: 400, target};+ const fire = (type: string, touches: (typeof touch)[]) => {+ const event = new Event(type, {bubbles: true, cancelable: true});+ Object.defineProperty(event, 'changedTouches', {value: [touch]});+ Object.defineProperty(event, 'touches', {value: touches});+ target.dispatchEvent(event);+ };+ fire('touchstart', [touch]);+ element.scrollTop = y;+ requestAnimationFrame(() =>+ requestAnimationFrame(() => fire('touchend', [])),+ );+ }, top);+}++async function openStack(page: Page, story = STORY) {+ await openStory(page, storybook(), story);+ await expect(page.getByTestId('navigation-stack')).toBeVisible();+ await expect(veil(page, 'root')).toBeAttached();+}++test('the bar paints no background and no hairline under a finger', async ({+ page,+}) => {+ await openStack(page);+ const background = await page+ .getByTestId('navigation-stack')+ .evaluate(stack => {+ const bar = stack.firstElementChild as HTMLElement;+ const style = getComputedStyle(bar.firstElementChild as HTMLElement);+ return {+ color: style.backgroundColor,+ border: style.borderBottomWidth,+ };+ });+ expect(background).toEqual({color: 'rgba(0, 0, 0, 0)', border: '0px'});+});++test('a scroll the program drives switches a screen’s veil at once: off through 10px, on beyond, both ways', async ({+ page,+}) => {+ await openStack(page);+ const steps: [number, number][] = [+ [0, 0],+ [5, 0],+ [10, 0],+ [11, 1],+ [200, 1],+ [10, 0],+ [0, 0],+ ];+ const seen: {top: number; opacity: number}[] = [];+ for (const [top, expected] of steps) {+ const opacity = await settleAt(page, 'root', top);+ seen.push({top, opacity});+ expect(opacity, `${top}px under the bar`).toBe(expected);+ // At once: the WebKit workaround (no fade on the program's scroll).+ expect(+ await veil(page, 'root').evaluate(+ element => element.getAnimations().length,+ ),+ ).toBe(0);+ }+ test+ .info()+ .annotations.push({type: 'switch', description: JSON.stringify(seen)});+});++test('a push brings the new screen’s own veil; a pop returns to the scrolled screen’s', async ({+ page,+}) => {+ await openStack(page);+ expect(await settleAt(page, 'root', 300)).toBe(1);+ await page.getByRole('button', {name: /Message 9\b/}).click();+ await expect(card(page, 'screen-Message 9')).toHaveAttribute(+ 'data-navigation-top',+ 'true',+ );+ await waitForRest(card(page, 'screen-Message 9'));+ await waitForRest(veil(page, 'screen-Message 9'));+ // The new screen sits at its top: its own veil is off. The covered screen+ // keeps its own, on.+ expect(await presentedOpacity(veil(page, 'screen-Message 9'))).toBe(0);+ expect(await presentedOpacity(veil(page, 'root'))).toBe(1);+ await page.getByRole('button', {name: 'Inbox'}).click();+ await expect(card(page, 'root')).toHaveAttribute(+ 'data-navigation-top',+ 'true',+ );+ await waitForRest(card(page, 'root'));+ expect(await presentedOpacity(veil(page, 'root'))).toBe(1);+});++test('a screen a pop reveals shows the veil for its own scroll: off at its top', async ({+ page,+}) => {+ // The story opens two screens deep, so the root mounts hidden.+ await openStack(page, 'lab-navigationstack--pushed');+ const back = page.locator('[data-navigation-back]');+ await back.click();+ await expect(card(page, 'screen-About')).toHaveCount(0);+ await waitForRest(card(page, 'screen-General'));+ await back.click();+ await expect(card(page, 'root')).toHaveAttribute(+ 'data-navigation-top',+ 'true',+ );+ await waitForRest(card(page, 'root'));+ await waitForRest(veil(page, 'root'));+ // The veil is there and laid out, so an opacity of 0 is a real reading.+ const box = await veil(page, 'root').boundingBox();+ expect(box?.width ?? 0).toBeGreaterThan(0);+ expect(box?.height ?? 0).toBeGreaterThan(0);+ expect(+ await scroller(page, 'root').evaluate(element => element.scrollTop),+ ).toBe(0);+ expect(await presentedOpacity(veil(page, 'root'))).toBe(0);+});++test('on a large-title screen the veil comes on as the bar’s title takes over', async ({+ page,+}) => {+ await openStack(page, 'lab-navigationstack--large-title');+ const geometry = await card(page, 'root').evaluate(element => {+ const title = element.querySelector('h1');+ const sentinel = element.querySelector(+ '[data-navigation-scroll-edge-sentinel]',+ );+ const bar = document.querySelector('[data-navigation-bar="root"]');+ if (title == null || sentinel == null || bar == null) {+ return null;+ }+ const titleBox = title.getBoundingClientRect();+ const sentinelBox = sentinel.getBoundingClientRect();+ return {+ titleHeight: Math.round(titleBox.height),+ titleBottom: Math.round(titleBox.bottom),+ sentinelBottom: Math.round(sentinelBox.bottom),+ sentinelHeight: Math.round(sentinelBox.height),+ // How far the root scrolls before the large title's bottom meets the+ // bar's, where the bar's title takes over.+ collapseAt: Math.round(+ titleBox.bottom - bar.getBoundingClientRect().bottom,+ ),+ };+ });+ if (geometry == null) {+ throw new Error('no large title, scroll edge sentinel or bar');+ }+ const {collapseAt, ...ends} = geometry;+ expect(ends.titleHeight).toBeGreaterThan(20);+ expect(ends.sentinelHeight).toBe(10);+ expect(ends.sentinelBottom).toBe(ends.titleBottom);+ expect(collapseAt).toBeGreaterThan(10);+ const barTitle = page.locator('[data-navigation-bar="root"] h2');+ // Short of it the large title shows: the bar's title is hidden, no veil.+ expect(await settleAt(page, 'root', collapseAt - 4)).toBe(0);+ await waitForRest(barTitle);+ expect(await presentedOpacity(barTitle)).toBe(0);+ // Past it the bar's title shows, over the veil.+ expect(await settleAt(page, 'root', collapseAt + 4)).toBe(1);+ await waitForRest(barTitle);+ expect(await presentedOpacity(barTitle)).toBe(1);+});++test('a finger scrolling the screen fades the veil in', async ({+ page,+ browserName,+}) => {+ test.skip(+ browserName !== 'chromium',+ 'native scrolling from injected touches is Chromium-only (harness README)',+ );+ await openStack(page);+ const driver = await touchDriver(page);+ await driver.play(+ drag({x: 200, y: 560}, {x: 200, y: 460}, {durationMs: 300, restMs: 450}),+ );+ await waitForRest(veil(page, 'root'));+ const top = await scroller(page, 'root').evaluate(+ element => element.scrollTop,+ );+ expect(top).toBeGreaterThan(10);+ expect(await presentedOpacity(veil(page, 'root'))).toBe(1);+});++test('the veil and its sentinel are hidden from assistive technology', async ({+ page,+}) => {+ await openStack(page);+ const hidden = await card(page, 'root').evaluate(element => {+ const layer = element.querySelector('[data-navigation-scroll-edge]');+ const sentinel = element.querySelector(+ '[data-navigation-scroll-edge-sentinel]',+ );+ return {+ layer: layer?.getAttribute('aria-hidden'),+ sentinel: sentinel?.getAttribute('aria-hidden'),+ pointer: layer == null ? null : getComputedStyle(layer).pointerEvents,+ };+ });+ expect(hidden).toEqual({layer: 'true', sentinel: 'true', pointer: 'none'});+});++test.describe('with a mouse', () => {+ test.use({hasTouch: false, isMobile: false});++ test('the bar keeps its surface and hairline and runs no veil', async ({+ page,+ }) => {+ await openStack(page);+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ const background = await page+ .getByTestId('navigation-stack')+ .evaluate(stack => {+ const bar = stack.firstElementChild as HTMLElement;+ const style = getComputedStyle(bar.firstElementChild as HTMLElement);+ return {color: style.backgroundColor, border: style.borderBottomWidth};+ });+ expect(background.color).not.toBe('rgba(0, 0, 0, 0)');+ expect(background.border).toBe('1px');+ await scroller(page, 'root').evaluate(element => {+ element.scrollTop = 200;+ });+ await frames(page, 5);+ expect(+ await veil(page, 'root').evaluate(element => ({+ display: getComputedStyle(element).display,+ running: element.getAnimations().length,+ })),+ ).toEqual({display: 'none', running: 0});+ });+});++test(+ 'storyboard: a screen’s veil fading in',+ {tag: '@storyboard'},+ async ({page}, testInfo) => {+ await openStack(page);+ const layer = veil(page, 'root');+ const viewport = page.viewportSize() ?? {width: 402, height: 714};+ const clip = {x: 0, y: 0, width: viewport.width, height: 120};+ await fingerScrollTo(page, 'root', 120);+ await waitForAnimation(layer);+ const {storyboard} = await animationStoryboard(page, {+ name: 'navigation-stack-scroll-edge-appear',+ clip,+ scope: layer,+ measure: async () => ({opacity: await presentedOpacity(layer)}),+ columns: 6,+ cellScale: 0.5,+ });+ await releaseAnimations(page, {finish: true});+ await storyboard.write(testInfo);+ const ins = storyboard.frames.map(f => f.data.opacity as number);+ expect(ins[0]).toBeLessThan(0.05);+ expect(ins.every((o, i) => i === 0 || o >= ins[i - 1] - 0.002)).toBe(true);+ expect(ins.at(-1)).toBeGreaterThan(0.99);+ },+);diff --git a/packages/lab/src/NavigationStack/navigationMotion.ts b/packages/lab/src/NavigationStack/navigationMotion.tsindex 725bc9e4ee..fdc981d130 100644--- a/packages/lab/src/NavigationStack/navigationMotion.ts+++ b/packages/lab/src/NavigationStack/navigationMotion.ts@@ -5,7 +5,8 @@* @input Core's UIKit navigation table and its four navigation springs, from* Core's internal touch entry* @output `navigation` and `springs`: Core's navigation values with the ones- * only NavigationStack reads, each with its measurement+ * only NavigationStack reads, each with its measurement. `bars`: iOS 26's+ * scroll edge effect under the bar.* @position NavigationStack's motion table. Core's tables keep the values* Core's own components read.*/@@ -103,3 +104,86 @@ export const springs = {*/navigationBackButton: {response: 0.4, dampingRatio: 1},} as const;++/**+ * iOS 26.2's bars paint no background. The scroll view's edge effect+ * separates a bar from the content under it: a veil of one colour, with+ * nothing blurred. Its colour is a theme value; this table holds its shape+ * and its timing. Lengths are in pt (CSS px).+ */+export const bars = {+ scrollEdgeEffect: {+ /**+ * The veil is off while the content sits at most this far past its rest+ * offset, and on beyond it. It is a switch, not a ramp, with no+ * hysteresis. Overscroll keeps it off.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, content offset stepped from +7.5 to +12.5 pt past+ * rest in 0.25 pt steps, ScrollEdgeEffectView model and presentation+ * opacity read after each step and 500 ms later, Oct 23 2026+ */+ switchPt: 10,+ /**+ * The veil fading in as the content passes the switch: critically+ * damped, response 0.2 s.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, `-[CALayer addAnimation:forKey:]` hooked on the effect+ * view while crossing the switch (opacity, mass 1, stiffness 986.96,+ * damping 62.83, duration 0.294), and its presentation opacity sampled+ * every frame through a 100 pt/s HID drag, Oct 23 2026+ */+ appear: {mass: 1, stiffness: 986.96, damping: 62.83},+ /**+ * The veil fading out as the content comes back over the switch:+ * critically damped, response 0.35 s.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, `-[CALayer addAnimation:forKey:]` hooked on the effect+ * view while crossing the switch back (opacity, mass 1, stiffness+ * 322.27, damping 35.90, duration 0.514), and its presentation opacity+ * sampled every frame through the drag back to rest, Oct 23 2026+ */+ disappear: {mass: 1, stiffness: 322.27, damping: 35.9},+ /**+ * How far the soft edge reaches below the bar's bottom edge.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, ScrollEdgeEffectView frame (0, 0, 402, 170.8) under a+ * standard navigation bar at y 62, height 54, Oct 23 2026+ */+ softExtentPt: 54.8,+ veil: {+ /**+ * UIKit's highest veil alpha, in light and dark mode alike. iOS adapts+ * the veil to the content's luminance. The web veil takes the bar's+ * theme colour and plays 0.95, so a bar's title keeps 4.5:1 over+ * bright content.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, screenshots of solid black, #808080 and white+ * content under the effect read per pt row (y 0–180, light and dark,+ * with and without a title), and the LuminanceAdjustment layer's+ * opacity (0.85 in both modes), Oct 23 2026+ */+ maxAlpha: 0.85,+ /**+ * Under a titled bar, the veil's edge is half-transparent this far+ * above the bottom of the bar's content. An expanded large title sits+ * outside the veil.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, PocketMask's ShadowLayer frame in window coordinates+ * with an inline title and with a collapsed large title (bottom edge+ * at y 106), with no bar content and with an expanded large title+ * (y 51), Oct 23 2026+ */+ edgeAboveContentBottomPt: 10,+ /**+ * How soft the edge is under a titled bar. The veil's alpha is+ * `maxAlpha × (1 − Φ((y − edge) / softnessPt))`, with Φ the standard+ * normal CDF. Nothing behind the veil is blurred.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, the ShadowLayer's shadowRadius (18 with a title, 24+ * without), per-pt-row profiles, 1 pt stripe contrast per row,+ * Oct 23 2026+ */+ softnessPt: 18,+ },+ },+} as const;diff --git a/packages/lab/src/internal/__tests__/coarsePointer.ts b/packages/lab/src/internal/__tests__/coarsePointer.tsnew file mode 100644index 0000000000..e873ccf27a--- /dev/null+++ b/packages/lab/src/internal/__tests__/coarsePointer.ts@@ -0,0 +1,35 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file coarsePointer.ts+ * @input jsdom's window and Core's touch query (its internal touch entry)+ * @output coarsePrimaryPointer(): a phone's primary pointer, until restored+ * @position Test helper of packages/lab/src/internal. jsdom has no+ * matchMedia, and Core's gesture host listens only under a coarse pointer.+ */++import {TOUCH_QUERY} from '@astryxdesign/core/internal/touch';++/** The primary pointer is coarse until the returned restore runs. */+export function coarsePrimaryPointer(): () => void {+ const hadOwn = Object.prototype.hasOwnProperty.call(window, 'matchMedia');+ const original = window.matchMedia;+ window.matchMedia = (query: string) =>+ ({+ matches: query.trim() === TOUCH_QUERY,+ media: query,+ onchange: null,+ addEventListener: () => {},+ removeEventListener: () => {},+ addListener: () => {},+ removeListener: () => {},+ dispatchEvent: () => false,+ }) as unknown as MediaQueryList;+ return () => {+ if (hadOwn) {+ window.matchMedia = original;+ } else {+ delete (window as {matchMedia?: unknown}).matchMedia;+ }+ };+}diff --git a/packages/lab/src/internal/useScrollEdgeEffect.test.tsx b/packages/lab/src/internal/useScrollEdgeEffect.test.tsxnew file mode 100644index 0000000000..59326c1e2c--- /dev/null+++ b/packages/lab/src/internal/useScrollEdgeEffect.test.tsx@@ -0,0 +1,757 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useScrollEdgeEffect.test.tsx+ * @input vitest (jsdom), React Testing Library, a recording+ * IntersectionObserver, a recording animator and Core's gesture host+ * @output The effect's decisions: what it observes, against which root, and+ * the props it hands out. A finger's scroll fades and the program's+ * switches. The layer's promotion and the veil's literals follow the bars+ * table.+ * @position Unit tests of packages/lab/src/internal/useScrollEdgeEffect.ts.+ * NavigationStackScrollEdge.interaction.browser.spec.ts proves the fade.+ */++import {readFileSync} from 'node:fs';+import {join} from 'node:path';+import * as stylex from '@stylexjs/stylex';+import type {StyleXStyles} from '@stylexjs/stylex';+import {act, cleanup, render, screen} from '@testing-library/react';+import {useRef} from 'react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {getGestureHost} from '@astryxdesign/core/internal/touch';+import type * as TouchEntry from '@astryxdesign/core/internal/touch';+import type * as CoreUtils from '@astryxdesign/core/utils';+import {bars} from '../NavigationStack/navigationMotion';+import {coarsePrimaryPointer} from './__tests__/coarsePointer';+import {useScrollEdgeEffect} from './useScrollEdgeEffect';++const testStyles = stylex.create({+ staticSentinel: {+ insetBlockStart: 'auto',+ insetInlineStart: 'auto',+ },+});++const animator = {+ set: vi.fn(),+ animate: vi.fn(),+ /** The layer, where a test attaches it (the mocked ref attaches nothing). */+ element: null as HTMLElement | null,+};++vi.mock('./useMotionEngine', () => ({+ useMotionEngine: () => ({ref: () => {}, animator}),+}));++/**+ * Core's shared resize observer, as the hook subscribes to it. Like Core's,+ * it calls back once as it subscribes.+ */+const resize = {callbacks: [] as Array<() => void>, stops: 0};+vi.mock('@astryxdesign/core/utils', async importOriginal => ({+ ...(await importOriginal<typeof CoreUtils>()),+ observeResize: (_element: Element, callback: () => void) => {+ resize.callbacks.push(callback);+ callback();+ return () => {+ resize.stops += 1;+ };+ },+}));++/** The touch presentation the hook sees: a finger unless a test says otherwise. */+const pointer = {isTouch: true};+/**+ * Core's finger-scroll hook: what the hook asks it to watch, and whether the+ * scroll now moving is a finger's.+ */+const host = {+ isFinger: true,+ watched: [] as unknown[],+ /** The hook's latest end call, as the real one keeps it. */+ onEnd: null as (() => void) | null,+};+/** useFingerScroll's reader is stable across renders, as the real one. */+const readFingerScroll = () => host.isFinger;+/** The finger-scroll hook saying that the finger's scroll has ended. */+function endFingerScroll() {+ host.isFinger = false;+ act(() => {+ host.onEnd?.();+ });+}+vi.mock('@astryxdesign/core/internal/touch', async importOriginal => ({+ ...(await importOriginal<typeof TouchEntry>()),+ useTouchPresentation: () => ({+ isTouch: pointer.isTouch,+ isCompact: true,+ isCompactTouch: pointer.isTouch,+ }),+ useFingerScroll: (scroller: unknown, options?: {onEnd?: () => void}) => {+ host.watched.push(scroller);+ host.onEnd = options?.onEnd ?? null;+ return readFingerScroll;+ },+}));++/** The node the hook last asked useFingerScroll to watch, if any. */+function watchedNode(): Document | Element | null {+ const last = host.watched.at(-1) as+ Document | {current: Element | null} | undefined;+ return last instanceof Document ? last : (last?.current ?? null);+}++class RecordingObserver {+ static instances: RecordingObserver[] = [];+ readonly observed: Element[] = [];+ disconnected = false;+ constructor(+ readonly callback: IntersectionObserverCallback,+ readonly options: IntersectionObserverInit = {},+ ) {+ RecordingObserver.instances.push(this);+ }+ observe(target: Element) {+ this.observed.push(target);+ }+ readonly unobserved: Element[] = [];+ unobserve(target: Element) {+ this.unobserved.push(target);+ }+ disconnect() {+ this.disconnected = true;+ }+ takeRecords(): IntersectionObserverEntry[] {+ return [];+ }+ /**+ * Reports the sentinel intersecting its root (true) or gone (false), with+ * the root rectangle's top when given (the engine's, margin applied) and+ * its height.+ */+ report(isIntersecting: boolean, rootTop?: number, rootHeight = 400) {+ act(() => {+ this.callback(+ [+ {+ isIntersecting,+ rootBounds:+ rootTop == null+ ? null+ : ({top: rootTop, height: rootHeight} as DOMRectReadOnly),+ } as IntersectionObserverEntry,+ ],+ this as unknown as IntersectionObserver,+ );+ });+ }+}++/** A touch event on `target` from finger 1 (down for touchstart). */+function touch(type: 'touchstart' | 'touchend', target: Element) {+ const event = new Event(type, {bubbles: true, cancelable: true});+ const finger = {identifier: 1, clientX: 10, clientY: 10, target};+ Object.defineProperty(event, 'changedTouches', {value: [finger]});+ Object.defineProperty(event, 'touches', {+ value: type === 'touchstart' ? [finger] : [],+ });+ act(() => {+ target.dispatchEvent(event);+ });+}++/**+ * Takes `onscrollend` off the window, as in a browser that sends no+ * `scrollend`; returns the restore.+ */+function withoutScrollEnd(): () => void {+ const own = Object.getOwnPropertyDescriptor(window, 'onscrollend');+ const proto = Object.getPrototypeOf(window) as object;+ const inherited = Object.getOwnPropertyDescriptor(proto, 'onscrollend');+ Reflect.deleteProperty(window, 'onscrollend');+ Reflect.deleteProperty(proto, 'onscrollend');+ expect('onscrollend' in window).toBe(false);+ return () => {+ if (inherited != null) {+ Object.defineProperty(proto, 'onscrollend', inherited);+ }+ if (own != null) {+ Object.defineProperty(window, 'onscrollend', own);+ }+ };+}++beforeEach(() => {+ animator.element = null;+ pointer.isTouch = true;+ host.isFinger = true;+ host.watched = [];+ RecordingObserver.instances = [];+ host.onEnd = null;+ resize.callbacks = [];+ resize.stops = 0;+ animator.set.mockClear();+ animator.animate.mockClear();+ vi.stubGlobal('IntersectionObserver', RecordingObserver);+});++afterEach(() => {+ vi.unstubAllGlobals();+});++let renders = 0;++function Bar({+ enabled,+ inContainer = false,+ sentinelKey = 'a',+ rootInset,+ color,+ sentinelXstyle,+}: {+ enabled: boolean;+ inContainer?: boolean;+ sentinelKey?: string;+ rootInset?: number;+ color?: string;+ sentinelXstyle?: StyleXStyles;+}) {+ renders += 1;+ const containerRef = useRef<HTMLDivElement>(null);+ const {layerProps, sentinelProps} = useScrollEdgeEffect({+ enabled,+ root: inContainer ? containerRef : undefined,+ rootInset,+ edge: '44px',+ color,+ sentinelXstyle,+ springs: bars.scrollEdgeEffect,+ });+ return (+ <div ref={containerRef} data-testid="container">+ <div {...layerProps} data-testid="layer" />+ <div key={sentinelKey} {...sentinelProps} data-testid="sentinel" />+ </div>+ );+}++/** Gives the test's scroller a layout: jsdom gives every element height 0. */+function withLayout(container: HTMLElement, top = 16) {+ Object.defineProperty(container, 'clientHeight', {+ configurable: true,+ value: 500,+ });+ vi.spyOn(container, 'getBoundingClientRect').mockReturnValue({+ top,+ } as DOMRect);+}++const observer = () => {+ const instance = RecordingObserver.instances.at(-1);+ if (instance == null) {+ throw new Error('no observer');+ }+ return instance;+};++describe('useScrollEdgeEffect', () => {+ it('observes the sentinel against its own document, at threshold 0', () => {+ const {getByTestId} = render(<Bar enabled />);+ expect(observer().observed).toEqual([getByTestId('sentinel')]);+ expect(observer().options.root).toBe(document);+ expect(observer().options.threshold).toBe(0);+ });++ it('observes against the scroll container when given one', () => {+ const {getByTestId} = render(<Bar enabled inContainer />);+ expect(observer().options.root).toBe(getByTestId('container'));+ });++ it('takes the inset of a bar that overlays its scroller off the root', () => {+ render(<Bar enabled inContainer rootInset={44} />);+ expect(observer().options.rootMargin).toBe('-44px 0px 0px 0px');+ });++ it('observes the page with no margin', () => {+ render(<Bar enabled />);+ expect(observer().options.rootMargin).toBe('0px 0px 0px 0px');+ });++ it('measures the root on the first report and, where the engine starts it at the content box, observes again from the padding edge', () => {+ // WebKit (iOS 26.2 Safari) starts a scroll container's root rectangle at+ // its content box. Here that is below a 44px top padding: the first+ // report's root top is the padding edge + 44 (padding) + 44 (the inset).+ const {getByTestId} = render(<Bar enabled inContainer rootInset={44} />);+ withLayout(getByTestId('container'));+ const first = observer();+ first.report(true, 16 + 44 + 44);+ // Not acted on: measured from the content box.+ expect(animator.set).not.toHaveBeenCalled();+ expect(first.disconnected).toBe(true);+ const second = observer();+ expect(second).not.toBe(first);+ expect(second.options.rootMargin).toBe('0px 0px 0px 0px');+ expect(second.observed).toEqual([getByTestId('sentinel')]);+ // Its first report puts the effect in place at once.+ second.report(true, 16 + 44);+ expect(animator.set).toHaveBeenLastCalledWith(+ {opacity: 0},+ {promote: false},+ );+ expect(RecordingObserver.instances).toHaveLength(2);+ });++ it('keeps the first observer where the engine starts the root at the padding edge', () => {+ // Chromium: the root rectangle is the padding box.+ const {getByTestId} = render(<Bar enabled inContainer rootInset={44} />);+ withLayout(getByTestId('container'));+ observer().report(false, 16 + 44);+ expect(RecordingObserver.instances).toHaveLength(1);+ expect(animator.set).toHaveBeenLastCalledWith(+ {opacity: 1},+ {promote: false},+ );+ });++ it('measures nothing while the scroller has no layout, and observes again once it has one', () => {+ // A stack in a hidden panel: the scroller and its root rectangle have no+ // size, so the first report holds nothing to measure.+ const {getByTestId} = render(<Bar enabled inContainer rootInset={44} />);+ const first = observer();+ first.report(false, 0, 0);+ expect(animator.set).not.toHaveBeenCalled();+ // The call as it subscribes finds no size: it neither stops the wait nor+ // observes again.+ expect(first.disconnected).toBe(false);+ expect(resize.callbacks).toHaveLength(1);+ expect(resize.stops).toBe(0);+ // A resize that leaves it without layout changes nothing.+ act(() => resize.callbacks[0]());+ expect(RecordingObserver.instances).toHaveLength(1);+ // Shown: a new observer from the padding edge reports at once, and the+ // veil is off at rest.+ withLayout(getByTestId('container'));+ act(() => resize.callbacks[0]());+ expect(resize.stops).toBe(1);+ expect(first.disconnected).toBe(true);+ const second = observer();+ expect(second).not.toBe(first);+ expect(second.options.rootMargin).toBe('-44px 0px 0px 0px');+ second.report(true, 16 + 44);+ expect(RecordingObserver.instances).toHaveLength(2);+ expect(animator.set).toHaveBeenLastCalledWith(+ {opacity: 0},+ {promote: false},+ );+ });++ it('measures a laid-out scroller whose root rectangle has no height, with no wait', () => {+ // WebKit's content-box root for a scroller no taller than its 44px top+ // padding: the rectangle has no height, but its top is a real reading.+ const {getByTestId} = render(<Bar enabled inContainer rootInset={44} />);+ withLayout(getByTestId('container'));+ const first = observer();+ first.report(true, 16 + 44 + 44, 0);+ expect(resize.callbacks).toHaveLength(0);+ expect(first.disconnected).toBe(true);+ expect(observer().options.rootMargin).toBe('0px 0px 0px 0px');+ });++ it('hands out decorative layer and sentinel props, sized by edge', () => {+ const {getByTestId} = render(<Bar enabled color="rgb(1, 2, 3)" />);+ const layer = getByTestId('layer');+ expect(layer.getAttribute('aria-hidden')).toBe('true');+ expect(getByTestId('sentinel').getAttribute('aria-hidden')).toBe('true');+ // The veil's colour and height are runtime values, StyleX custom+ // properties on the element. The height is the soft extent past the+ // bar's bottom, and the bar's bottom under Reduce Transparency.+ const style = layer.getAttribute('style') ?? '';+ expect(style).toContain('rgb(1, 2, 3)');+ expect(style).toContain('calc(44px + 54.8px)');+ expect(style).toContain('44px');+ });++ it("adds the caller's sentinel styles, e.g. its static position", () => {+ const plain = render(<Bar enabled />)+ .getByTestId('sentinel')+ .getAttribute('class');+ cleanup();+ const placed = render(+ <Bar enabled sentinelXstyle={testStyles.staticSentinel} />,+ )+ .getByTestId('sentinel')+ .getAttribute('class');+ expect(placed).not.toBe(plain);+ for (const name of (+ stylex.props(testStyles.staticSentinel).className ?? ''+ ).split(' ')) {+ expect(placed?.split(' ')).toContain(name);+ }+ });++ it('defaults the veil to the body colour', () => {+ const {getByTestId} = render(<Bar enabled />);+ expect(getByTestId('layer').getAttribute('style')).toContain(+ 'var(--color-background-body)',+ );+ });++ it('puts the first report in place without a fade', () => {+ render(<Bar enabled />);+ observer().report(true);+ expect(animator.set).toHaveBeenLastCalledWith(+ {opacity: 0},+ {promote: false},+ );+ expect(animator.animate).not.toHaveBeenCalled();+ });++ it('shows the effect at once when the page loads scrolled', () => {+ render(<Bar enabled />);+ observer().report(false);+ expect(animator.set).toHaveBeenLastCalledWith(+ {opacity: 1},+ {promote: false},+ );+ expect(animator.animate).not.toHaveBeenCalled();+ });++ it('fades in on the appear spring and out on the disappear spring under a finger', () => {+ render(<Bar enabled />);+ observer().report(true);+ observer().report(false);+ expect(animator.animate).toHaveBeenLastCalledWith(+ {opacity: 1},+ {spring: bars.scrollEdgeEffect.appear},+ );+ // Back before the fade ended: the animator turns it around.+ observer().report(true);+ expect(animator.animate).toHaveBeenLastCalledWith(+ {opacity: 0},+ {spring: bars.scrollEdgeEffect.disappear},+ );+ expect(animator.animate).toHaveBeenCalledTimes(2);+ });++ it('ignores a report that changes nothing', () => {+ render(<Bar enabled />);+ observer().report(true);+ observer().report(false);+ observer().report(false);+ expect(animator.animate).toHaveBeenCalledTimes(1);+ });++ // On iOS 26.2, a fade that starts as the program's scroll crosses the+ // switch blanks the sticky bar's items.+ it('switches at once, without a fade, for a scroll the program drives', () => {+ host.isFinger = false;+ render(<Bar enabled />);+ observer().report(true);+ observer().report(false);+ expect(animator.set).toHaveBeenLastCalledWith(+ {opacity: 1},+ {promote: false},+ );+ observer().report(true);+ expect(animator.set).toHaveBeenLastCalledWith(+ {opacity: 0},+ {promote: false},+ );+ expect(animator.animate).not.toHaveBeenCalled();+ });++ it('fades for a finger and switches for the program within one page', () => {+ render(<Bar enabled />);+ observer().report(true);+ // A finger scrolls the content under the bar…+ observer().report(false);+ expect(animator.animate).toHaveBeenCalledTimes(1);+ // …and a status-bar tap brings it back.+ host.isFinger = false;+ observer().report(true);+ expect(animator.set).toHaveBeenLastCalledWith(+ {opacity: 0},+ {promote: false},+ );+ expect(animator.animate).toHaveBeenCalledTimes(1);+ });++ it('watches the page’s finger scrolls, or the scroll container’s', () => {+ const {unmount} = render(<Bar enabled />);+ expect(watchedNode()).toBe(document);+ unmount();+ render(<Bar enabled inContainer />);+ expect(watchedNode()).toBe(screen.getByTestId('container'));+ });++ // The sentinel lives in a ref, not React state.+ it('attaches the sentinel without re-rendering the host', () => {+ renders = 0;+ render(<Bar enabled />);+ expect(renders).toBe(1);+ expect(observer().observed).toEqual([screen.getByTestId('sentinel')]);+ });++ // The layer is composited only while a finger works the scroller. The+ // program's switch writes no compositing layer.+ it('a scroll the program drives switches the layer without promotion', () => {+ host.isFinger = false;+ render(<Bar enabled />);+ observer().report(true);+ observer().report(false);+ expect(animator.set).toHaveBeenLastCalledWith(+ {opacity: 1},+ {promote: false},+ );+ expect(animator.animate).not.toHaveBeenCalled();+ });++ // The gesture host listens only where the primary pointer is coarse, and+ // jsdom has no matchMedia.+ describe('under a coarse primary pointer', () => {+ let restorePointer: () => void = () => {};+ beforeEach(() => {+ restorePointer = coarsePrimaryPointer();+ });+ afterEach(() => {+ restorePointer();+ });++ it('in a scroll container, a finger’s landing composites the layer until it lifts', () => {+ host.isFinger = false;+ const {getByTestId} = render(<Bar enabled inContainer />);+ const layer = getByTestId('layer');+ animator.element = layer;+ const promotion = () =>+ layer.style.getPropertyValue('--_scroll-edge-will-change');+ expect(promotion()).toBe('');+ touch('touchstart', getByTestId('sentinel'));+ expect(promotion()).toBe('opacity');+ touch('touchend', getByTestId('sentinel'));+ expect(promotion()).toBe('');+ });++ it('keeps the layer composited through the finger’s momentum, until its scroll ends', () => {+ const {getByTestId} = render(<Bar enabled inContainer />);+ const layer = getByTestId('layer');+ animator.element = layer;+ const promotion = () =>+ layer.style.getPropertyValue('--_scroll-edge-will-change');+ touch('touchstart', getByTestId('sentinel'));+ // Lifted while its scroll still moves (useFingerScroll still reads it).+ touch('touchend', getByTestId('sentinel'));+ expect(promotion()).toBe('opacity');+ endFingerScroll();+ expect(promotion()).toBe('');+ });++ // Where the browser sends no `scrollend`, the finger-scroll hook times+ // the end itself. The effect keeps no timer: only the hook's end call+ // drops the layer.+ it('drops the layer only when the finger-scroll hook says the scroll ended, with no timer of its own', () => {+ vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout']});+ const restoreScrollEnd = withoutScrollEnd();+ try {+ const {getByTestId} = render(<Bar enabled inContainer />);+ const container = getByTestId('container');+ const layer = getByTestId('layer');+ animator.element = layer;+ const promotion = () =>+ layer.style.getPropertyValue('--_scroll-edge-will-change');+ touch('touchstart', getByTestId('sentinel'));+ container.dispatchEvent(new Event('scroll'));+ // Lifted mid-fling: its momentum still scrolls.+ touch('touchend', getByTestId('sentinel'));+ act(() => {+ vi.advanceTimersByTime(1000);+ });+ expect(promotion()).toBe('opacity');+ expect(vi.getTimerCount()).toBe(0);+ endFingerScroll();+ expect(promotion()).toBe('');+ } finally {+ restoreScrollEnd();+ vi.useRealTimers();+ }+ });++ it('adds no scroll listener of its own however many screens run it', () => {+ // The gesture host's own listeners start with its first retain. Take+ // it first, so that only the hook's are counted.+ const releaseHost = getGestureHost(document).retain();+ const onDocument = vi.spyOn(document, 'addEventListener');+ const onWindow = vi.spyOn(window, 'addEventListener');+ const scrollTypes = (spy: typeof onWindow) =>+ spy.mock.calls+ .map(([type]) => type)+ .filter(type => type === 'scroll' || type === 'scrollend');+ const three = () => (+ <>+ <Bar enabled inContainer sentinelKey="a" />+ <Bar enabled inContainer sentinelKey="b" />+ <Bar enabled inContainer sentinelKey="c" />+ </>+ );+ try {+ render(three());+ expect(scrollTypes(onDocument)).toEqual([]);+ expect(scrollTypes(onWindow)).toEqual([]);+ cleanup();+ onWindow.mockClear();+ // Where the browser sends no `scrollend`, nothing changes here: the+ // finger-scroll hook times the end.+ const restoreScrollEnd = withoutScrollEnd();+ try {+ render(three());+ expect(scrollTypes(onDocument)).toEqual([]);+ expect(scrollTypes(onWindow)).toEqual([]);+ } finally {+ restoreScrollEnd();+ }+ } finally {+ onDocument.mockRestore();+ onWindow.mockRestore();+ releaseHost();+ }+ });+ });++ it('with a mouse a finger never composites the layer', () => {+ pointer.isTouch = false;+ const restorePointer = coarsePrimaryPointer();+ try {+ const {getByTestId} = render(<Bar enabled inContainer />);+ const layer = getByTestId('layer');+ animator.element = layer;+ touch('touchstart', getByTestId('sentinel'));+ expect(layer.style.getPropertyValue('--_scroll-edge-will-change')).toBe(+ '',+ );+ touch('touchend', getByTestId('sentinel'));+ } finally {+ restorePointer();+ }+ });++ it('moves the observer to a replacement sentinel node', () => {+ const {rerender} = render(<Bar enabled />);+ const first = screen.getByTestId('sentinel');+ const instance = observer();+ rerender(<Bar enabled sentinelKey="b" />);+ const second = screen.getByTestId('sentinel');+ expect(second).not.toBe(first);+ expect(instance.unobserved).toContain(first);+ expect(instance.observed.at(-1)).toBe(second);+ expect(RecordingObserver.instances.at(-1)).toBe(instance);+ });++ it('observes nothing with a mouse', () => {+ pointer.isTouch = false;+ expect(window.matchMedia('(pointer: coarse)').matches).toBe(false);+ render(<Bar enabled />);+ expect(RecordingObserver.instances).toHaveLength(0);+ // Nothing is watched: a mouse costs no touch work.+ expect(watchedNode()).toBeNull();+ expect(animator.animate).not.toHaveBeenCalled();+ });++ it('observes nothing while disabled', () => {+ render(<Bar enabled={false} />);+ expect(RecordingObserver.instances).toHaveLength(0);+ });++ it('stops observing and turns transparent when disabled', () => {+ const {rerender} = render(<Bar enabled />);+ const first = observer();+ first.report(false);+ rerender(<Bar enabled={false} />);+ expect(first.disconnected).toBe(true);+ expect(watchedNode()).toBeNull();+ expect(animator.set).toHaveBeenLastCalledWith(+ {opacity: 0},+ {promote: false},+ );+ });++ it('does nothing where IntersectionObserver is missing', () => {+ vi.stubGlobal('IntersectionObserver', undefined);+ expect(() => render(<Bar enabled />)).not.toThrow();+ expect(animator.set).not.toHaveBeenCalled();+ });+});++describe('the veil follows the constants table', () => {+ const source = readFileSync(+ join(__dirname, 'useScrollEdgeEffect.ts'),+ 'utf8',+ );++ /** The literal block of `styles.<name>` in useScrollEdgeEffect.ts. */+ function styleBlock(name: string): string {+ const start = source.indexOf(`\n ${name}: {`);+ expect(start, `styles.${name} not found`).toBeGreaterThan(-1);+ const end = source.indexOf('\n },', start);+ return source.slice(start, end);+ }++ // The veil's edge is the bar's bottom. The soft extent reaches+ // `softExtentPt` past it, so the edge is that far above the layer's bottom.+ const edgeAboveBottom = bars.scrollEdgeEffect.softExtentPt;+ // UIKit's edge sits `veil.edgeAboveContentBottomPt` higher; the stops are+ // sampled around it.+ const {edgeAboveContentBottomPt} = bars.scrollEdgeEffect.veil;++ it('the layer reaches softExtentPt past the bar; Reduce Transparency ends it at the bar', () => {+ expect(source).toContain(+ 'dynamicStyles.geometry(`calc(${edge} + ' ++ edgeAboveBottom ++ 'px)`, edge, color)',+ );+ });++ it('the layer’s will-change follows the hook’s promotion property', () => {+ expect(styleBlock('layer')).toContain(+ "willChange: 'var(--_scroll-edge-will-change, auto)',",+ );+ });++ it('the sentinel is switchPt tall', () => {+ expect(styleBlock('sentinel')).toContain(+ `height: ${bars.scrollEdgeEffect.switchPt},`,+ );+ });++ // Denser than UIKit's 0.85: 0.95, with the edge at the bar's bottom. A+ // bar's title keeps 4.5:1 over the brightest scrolled content (WCAG 1.4.3).+ it('the veil is 0.95 × (1 − Φ((y − edge) / softness)), sampled every 6px over ±3σ', () => {+ const maxAlpha = 0.95;+ const {softnessPt} = bars.scrollEdgeEffect.veil;+ expect(maxAlpha).toBeGreaterThan(bars.scrollEdgeEffect.veil.maxAlpha);+ const uikitEdge = edgeAboveBottom + edgeAboveContentBottomPt;+ const stops: string[] = [];+ for (let d = -3 * softnessPt; d <= 3 * softnessPt; d += 6) {+ const alpha =+ maxAlpha * (1 - normalCdf((d - edgeAboveContentBottomPt) / softnessPt));+ const offset = Math.round((uikitEdge - d) * 10) / 10;+ stops.push(`rgb(0 0 0 / ${alpha.toFixed(3)}) calc(100% - ${offset}px)`);+ }+ expect(styleBlock('layer')).toContain(+ `'linear-gradient(to bottom, ${stops.join(', ')})'`,+ );+ });+});++/** Standard normal CDF, by Simpson integration of the density (oracle). */+function normalCdf(z: number): number {+ const n = 2000;+ const h = Math.abs(z) / n;+ let sum = 0;+ for (let i = 0; i <= n; i++) {+ const t = i * h;+ const weight = i === 0 || i === n ? 1 : i % 2 === 1 ? 4 : 2;+ sum += weight * Math.exp((-t * t) / 2);+ }+ const half = (sum * h) / 3 / Math.sqrt(2 * Math.PI);+ return z >= 0 ? 0.5 + half : 0.5 - half;+}diff --git a/packages/lab/src/internal/useScrollEdgeEffect.ts b/packages/lab/src/internal/useScrollEdgeEffect.tsnew file mode 100644index 0000000000..4692d952a2--- /dev/null+++ b/packages/lab/src/internal/useScrollEdgeEffect.ts@@ -0,0 +1,357 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useScrollEdgeEffect.ts+ * @input React, StyleX, IntersectionObserver, Lab's motion engine, and+ * Core's gesture host, finger-scroll hook (with its end call), resize+ * observer, touch presentation and colour tokens+ * @output useScrollEdgeEffect: props for a bar's scroll edge veil and for the+ * sentinel that switches it, fading on the caller's springs+ * @position Lab's iOS 26 bar look under a finger, for NavigationStack. Lab's+ * entry point does not export it. With a mouse it observes nothing.+ *+ * SYNC: When modified, update useScrollEdgeEffect.test.tsx and NavigationStack.+ */++import * as stylex from '@stylexjs/stylex';+import type {StyleXStyles} from '@stylexjs/stylex';+import {useCallback, useEffect, useRef, type RefObject} from 'react';+import {+ getGestureHost,+ useFingerScroll,+ useTouchPresentation,+ type SpringDescription,+} from '@astryxdesign/core/internal/touch';+import {colorVars} from '@astryxdesign/core/theme/tokens.stylex';+import {observeResize} from '@astryxdesign/core/utils';+import {useMotionEngine} from './useMotionEngine';++/** No scroller: nothing is watched (a mouse, or the effect is off). */+const NO_SCROLLER: RefObject<Element | null> = {current: null};++/**+ * The private custom property the layer's `will-change` reads: `opacity`+ * while a finger works the scroller, unset otherwise. Only this hook sets it,+ * inline; it is not theme data.+ */+export const SCROLL_EDGE_LAYER_PROMOTION = '--_scroll-edge-will-change';++const styles = stylex.create({+ // The veil: one colour, never a blur. Its mask is+ // 0.95 × (1 − Φ((y − edge) / 18px)), half strength at `edge`, sampled every+ // 6px over ±3σ; useScrollEdgeEffect.test.tsx recomputes it. It is denser+ // than UIKit's 0.85, so a bar's title keeps 4.5:1 over bright content.+ layer: {+ display: {+ default: 'none',+ '@media (pointer: coarse)': 'block',+ },+ position: 'absolute',+ insetInline: 0,+ insetBlockStart: 0,+ pointerEvents: 'none',+ opacity: 0,+ // Composited only while a finger works the scroller. On iOS 26.2, a+ // composited layer under a sticky bar blanks the bar's items when the+ // program scrolls back to the top.+ willChange: 'var(--_scroll-edge-will-change, auto)',+ maskImage: {+ default:+ 'linear-gradient(to bottom, rgb(0 0 0 / 0.950) calc(100% - 118.8px), rgb(0 0 0 / 0.949) calc(100% - 112.8px), rgb(0 0 0 / 0.948) calc(100% - 106.8px), rgb(0 0 0 / 0.945) calc(100% - 100.8px), rgb(0 0 0 / 0.938) calc(100% - 94.8px), rgb(0 0 0 / 0.922) calc(100% - 88.8px), rgb(0 0 0 / 0.893) calc(100% - 82.8px), rgb(0 0 0 / 0.845) calc(100% - 76.8px), rgb(0 0 0 / 0.772) calc(100% - 70.8px), rgb(0 0 0 / 0.675) calc(100% - 64.8px), rgb(0 0 0 / 0.559) calc(100% - 58.8px), rgb(0 0 0 / 0.433) calc(100% - 52.8px), rgb(0 0 0 / 0.312) calc(100% - 46.8px), rgb(0 0 0 / 0.207) calc(100% - 40.8px), rgb(0 0 0 / 0.127) calc(100% - 34.8px), rgb(0 0 0 / 0.071) calc(100% - 28.8px), rgb(0 0 0 / 0.036) calc(100% - 22.8px), rgb(0 0 0 / 0.017) calc(100% - 16.8px), rgb(0 0 0 / 0.007) calc(100% - 10.8px))',+ // Reduce Transparency: an opaque band with a hard edge, as UIKit's.+ '@media (prefers-reduced-transparency: reduce)': 'none',+ },+ },+ // `bars.scrollEdgeEffect.switchPt` (10px) tall, at the top of the content.+ sentinel: {+ position: 'absolute',+ insetBlockStart: 0,+ insetInlineStart: 0,+ width: 1,+ height: 10,+ pointerEvents: 'none',+ visibility: 'hidden',+ },+});++const dynamicStyles = stylex.create({+ // The layer ends 54.8px below the veil's edge (the soft extent). Reduce+ // Transparency ends the opaque band at the edge, the bar's bottom.+ geometry: (height: string, reducedHeight: string, color: string) => ({+ height: {+ default: height,+ '@media (prefers-reduced-transparency: reduce)': reducedHeight,+ },+ backgroundColor: color,+ }),+});++export interface UseScrollEdgeEffectOptions {+ /**+ * Whether the effect runs. When false, and always with a mouse, the veil+ * stays transparent and nothing is observed.+ * @default true+ */+ readonly enabled?: boolean;+ /**+ * The scroll container whose content passes under the bar. Omit for a+ * page that scrolls (the viewport).+ */+ readonly root?: RefObject<Element | null>;+ /**+ * How far, in px, a bar overlays the top of `root` from its padding edge.+ * Under a 44px bar it is `44`: the content counts as under the bar once it+ * passes the bar's bottom edge.+ * @default 0+ */+ readonly rootInset?: number;+ /**+ * The bar's bottom edge, where the veil is half strength, from the top of+ * the layer's containing block. A CSS length without `calc()`: `100%`+ * inside the bar, `44px` under a 44px bar that overlays the screen.+ */+ readonly edge: string;+ /**+ * The veil's colour: the colour behind the bar's content.+ * @default the body background+ */+ readonly color?: string;+ /** Extra styles for the layer, e.g. its stacking order. */+ readonly layerXstyle?: StyleXStyles;+ /**+ * Extra styles for the sentinel. Insets of `auto` leave it at its static+ * position, the top of the content, with no positioned wrapper.+ */+ readonly sentinelXstyle?: StyleXStyles;+ /** The fades' springs: a bar's are `bars.scrollEdgeEffect`'s. */+ readonly springs: {+ readonly appear: SpringDescription;+ readonly disappear: SpringDescription;+ };+}++/** Props to spread on an element, ref included. */+interface ElementProps {+ readonly ref: (element: HTMLElement | null) => void;+ readonly 'aria-hidden': true;+ readonly className?: string;+ readonly style?: Readonly<Record<string, string | number>>;+}++export interface UseScrollEdgeEffectResult {+ /**+ * The veil: spread on an empty element at the top of the bar's containing+ * block, above the content and below the bar's items.+ */+ readonly layerProps: ElementProps;+ /**+ * The sentinel: spread on an empty element at the top of the scrolled+ * content. With static insets, the scroll container must be its containing+ * block, so that it scrolls with the content.+ */+ readonly sentinelProps: ElementProps;+}++/**+ * The iOS 26 scroll edge effect of a bar, under a finger. A veil fades in once+ * the content has moved more than 10px under the bar, and out when it comes+ * back. It is a switch with a timed fade, not a ramp that follows the scroll.+ *+ * @example+ * ```+ * const edge = useScrollEdgeEffect({+ * root: scrollerRef,+ * rootInset: 44,+ * edge: '44px',+ * springs: bars.scrollEdgeEffect,+ * });+ * <div {...edge.layerProps} />+ * <div ref={scrollerRef}><div><div {...edge.sentinelProps} /></div>…</div>+ * ```+ */+export function useScrollEdgeEffect({+ enabled = true,+ root,+ rootInset = 0,+ edge,+ color = colorVars['--color-background-body'],+ layerXstyle,+ sentinelXstyle,+ springs,+}: UseScrollEdgeEffectOptions): UseScrollEdgeEffectResult {+ const {isTouch} = useTouchPresentation();+ const isOn = enabled && isTouch;+ const {ref: layerRef, animator} = useMotionEngine({+ initial: {opacity: 0},+ });+ // The running effect's promotion check. The finger-scroll hook calls it+ // when a finger's scroll ends; the effect sets it and clears it.+ const updatePromotionRef = useRef<(() => void) | null>(null);+ // Watched only while the effect runs, so a mouse costs nothing. A page's+ // scroll is the document's; a container scrolls itself.+ const isFingerScroll = useFingerScroll(+ !isOn+ ? NO_SCROLLER+ : (root ?? (typeof document === 'undefined' ? NO_SCROLLER : document)),+ {onEnd: () => updatePromotionRef.current?.()},+ );+ // The callback ref owns the sentinel, never React state. It moves the+ // running observer to a replacement node.+ const sentinelElementRef = useRef<HTMLElement | null>(null);+ const observerRef = useRef<IntersectionObserver | null>(null);+ const sentinelRef = useCallback((element: HTMLElement | null) => {+ const observer = observerRef.current;+ if (observer != null && sentinelElementRef.current != null) {+ observer.unobserve(sentinelElementRef.current);+ }+ sentinelElementRef.current = element;+ if (observer != null && element != null) {+ observer.observe(element);+ }+ }, []);++ // Synchronizes with an IntersectionObserver on the sentinel and with the+ // gesture host's fingers, which decide the layer's promotion. While the+ // scroller has no layout, it also waits on Core's shared resize observer.+ useEffect(() => {+ if (!isOn || typeof IntersectionObserver === 'undefined') {+ return;+ }+ const sentinel = sentinelElementRef.current;+ const doc = sentinel?.ownerDocument ?? document;+ const container = root?.current ?? null;+ let isShown: boolean | null = null;+ // Engines disagree on a scroll container's root rectangle: Chromium+ // takes its padding box, WebKit its content box. The first report+ // measures the difference; a page has no padding edge.+ let rootOffset: number | null = container == null ? 0 : null;+ let observer: IntersectionObserver;+ let stopWaiting: (() => void) | null = null;+ const report = (entries: IntersectionObserverEntry[]) => {+ const entry = entries[entries.length - 1];+ if (entry == null) {+ return;+ }+ if (rootOffset == null && container != null) {+ const bounds = entry.rootBounds;+ // A scroller with no layout (a stack in a hidden panel) gives nothing+ // to measure. Wait until it has a size, then observe again: a new+ // observer reports at once. The resize observer calls back once as+ // it subscribes; the scroller has no size yet, so that call returns.+ if (container.clientHeight <= 0) {+ stopWaiting ??= observeResize(container, () => {+ if (container.clientHeight <= 0) {+ return;+ }+ stopWaiting?.();+ stopWaiting = null;+ observer.disconnect();+ observe();+ });+ return;+ }+ const paddingEdge =+ container.getBoundingClientRect().top + container.clientTop;+ const offset =+ bounds == null ? 0 : Math.round(bounds.top - rootInset - paddingEdge);+ rootOffset = offset;+ if (offset !== 0) {+ // WebKit measured this report from the content box: observe+ // again from the padding edge.+ observer.disconnect();+ observe();+ return;+ }+ }+ // The sentinel's bottom passes the root's top when the content has+ // moved more than 10px under the bar. A box that only touches it+ // still intersects: 10px is off, 10.25px is on, as measured.+ const next = !entry.isIntersecting;+ if (next === isShown) {+ return;+ }+ if (isShown != null && isFingerScroll()) {+ // Under Reduce Motion the animator plays its own opacity+ // cross-fade on a coarse pointer.+ animator.animate(+ {opacity: next ? 1 : 0},+ {spring: next ? springs.appear : springs.disappear},+ );+ } else {+ // The first report, or the program's scroll: at once, with no+ // compositing layer (the WebKit blank on the layer style above).+ animator.set({opacity: next ? 1 : 0}, {promote: false});+ }+ isShown = next;+ };+ const observe = () => {+ observer = new IntersectionObserver(report, {+ // The sentinel's own document: inside a frame, the implicit root is+ // the top-level viewport.+ root: container ?? doc,+ rootMargin: `${(rootOffset ?? 0) - rootInset}px 0px 0px 0px`,+ threshold: 0,+ });+ observerRef.current = observer;+ const current = sentinelElementRef.current;+ if (current != null) {+ observer.observe(current);+ }+ };+ observe();+ // The layer is promoted from a finger's landing until its scroll ends,+ // momentum included. A fade that starts mid-drag then finds its layer.+ // Drop this once iOS no longer blanks a sticky bar when the program+ // scrolls over a composited layer.+ const scroller: Node = container ?? doc;+ const host = getGestureHost(doc);+ const releaseHost = host.retain();+ let isPromoted = false;+ const updatePromotion = () => {+ const layer = animator.element;+ const next = host.isFingerDownIn(scroller) || isFingerScroll();+ if (layer == null || next === isPromoted) {+ return;+ }+ isPromoted = next;+ if (next) {+ layer.style.setProperty(SCROLL_EDGE_LAYER_PROMOTION, 'opacity');+ } else {+ layer.style.removeProperty(SCROLL_EDGE_LAYER_PROMOTION);+ }+ };+ const unsubscribeFingers = host.onFingersChange(updatePromotion);+ // The finger-scroll hook says when the finger's scroll has ended, its+ // momentum included, so the layer drops with no listener or timer here.+ updatePromotionRef.current = updatePromotion;+ return () => {+ observerRef.current = null;+ observer.disconnect();+ unsubscribeFingers();+ updatePromotionRef.current = null;+ stopWaiting?.();+ releaseHost();+ animator.element?.style.removeProperty(SCROLL_EDGE_LAYER_PROMOTION);+ animator.set({opacity: 0}, {promote: false});+ };+ }, [isOn, root, rootInset, animator, isFingerScroll, springs]);++ return {+ layerProps: {+ ref: layerRef,+ 'aria-hidden': true,+ ...stylex.props(+ styles.layer,+ dynamicStyles.geometry(`calc(${edge} + 54.8px)`, edge, color),+ layerXstyle,+ ),+ },+ sentinelProps: {+ ref: sentinelRef,+ 'aria-hidden': true,+ ...stylex.props(styles.sentinel, sentinelXstyle),+ },+ };+}