An open source design system that's fully customizable and agent ready
TypeScript
fix(Slider): the value tooltip stays on its thumb through a drag (#10228)
Christopher Chedeau1bc28f34990a
diff --git a/.changeset/slider-tooltip-follows-thumb.md b/.changeset/slider-tooltip-follows-thumb.mdnew file mode 100644index 0000000000..095f9393cf--- /dev/null+++ b/.changeset/slider-tooltip-follows-thumb.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `Slider`'s value tooltip stays on its thumb in every frame of a drag and of the coast after a finger lifts. It trailed the thumb by up to 14 px, because it was anchored to a box that moved only when the owner rendered the new value. The tooltip now moves with the thumb by the same translate, and its anchor box keeps its place until the drag ends.++@vjeuxdiff --git a/packages/core/src/Slider/Slider.tsx b/packages/core/src/Slider/Slider.tsxindex a145b05474..c7b5123c17 100644--- a/packages/core/src/Slider/Slider.tsx+++ b/packages/core/src/Slider/Slider.tsx@@ -5,7 +5,7 @@/*** @file Slider.tsx* @input Uses React, useId, useRef, useCallback, useEffect, Field, useTooltip, VisuallyHidden, the touch presentation resolver and useSliderTouch (UISlider's touch tracking)- * @output Exports Slider and its props. Unfilled marks share the track token. Modifier-only key presses do not restore the thumb focus ring. A drag belongs to the pointer that started it. The thumbs and the filled range travel by `translate` in container units, so moving them never lays out. Padding on the control moves no part. The value tooltip anchors to a box that layout places at the value. A drag on a thumb is a pan for every pointer, tracked as UISlider does. Under a coarse primary pointer, each thumb's `::before` is its touch target. A finger's tap on the track sets the value on its lift. A mouse press on the track keeps the pointer handlers. Two coincident range thumbs separate toward the press or the first movement+ * @output Exports Slider and its props. Unfilled marks share the track token. Modifier-only key presses do not restore the thumb focus ring. A drag belongs to the pointer that started it. The thumbs and the filled range travel by `translate` in container units, so moving them never lays out. Padding on the control moves no part. The value tooltip anchors to a box that layout places at the value. During a drag and its coast, the box keeps its place and the tooltip moves with the thumb by translate. A drag on a thumb is a pan for every pointer, tracked as UISlider does. Under a coarse primary pointer, each thumb's `::before` is its touch target. A finger's tap on the track sets the value on its lift. A mouse press on the track keeps the pointer handlers. Two coincident range thumbs separate toward the press or the first movement* @position Core implementation; consumed by index.ts, tested by Slider.test.tsx** SYNC: When modified, update these files to stay in sync:@@ -23,13 +23,13 @@ import {useRef,useState,useCallback,- type CSSProperties,type FocusEvent,type KeyboardEvent,type PointerEvent,type ReactElement,type ReactNode,type Ref,+ type RefObject,} from 'react';import {flushSync} from 'react-dom';import * as stylex from '@stylexjs/stylex';@@ -210,6 +210,12 @@ type ThumbStyle = React.CSSProperties &Partial<Record<(typeof HIT_INSET)[keyof typeof HIT_INSET], string>>;type FillStyle = React.CSSProperties &Record<typeof FILL_START | typeof FILL_END, number>;+type AnchorStyle = React.CSSProperties & Record<typeof THUMB_PROGRESS, number>;+/** A thumb's value-tooltip anchor and the id of the tooltip it places. */+interface ValueAnchor {+ readonly element: HTMLElement;+ readonly tooltipId: string;+}// =============================================================================// Styles@@ -256,13 +262,23 @@ const styles = stylex.create({// Where layout places a thumb at its value: the value tooltip's position// anchor. CSS anchor positioning reads the anchor's layout box, which the// thumb's `translate` does not move in every engine. So the tooltip anchors- // here while hover and focus stay on the thumb.+ // here while hover and focus stay on the thumb. During a drag the anchor+ // keeps the place the drag held, and the tooltip moves with the thumb by+ // translate.valueAnchor: {position: 'absolute',width: THUMB_SIZE,height: THUMB_SIZE,pointerEvents: 'none',},+ valueAnchorHorizontal: {+ top: `calc(50% - ${THUMB_SIZE / 2}px)`,+ insetInlineStart: `calc(var(${THUMB_PROGRESS}) * (100cqi - ${THUMB_SIZE}px))`,+ },+ valueAnchorVertical: {+ insetInlineStart: `calc(50% - ${THUMB_SIZE / 2}px)`,+ bottom: `calc(var(${THUMB_PROGRESS}) * (100cqb - ${THUMB_SIZE}px))`,+ },trackContainerHorizontal: {height: THUMB_SIZE,// The whole track is the tap target (a click anywhere on it moves the@@ -635,14 +651,21 @@ function SliderValueTooltip({content,placement,isOpen,- anchorStyle,+ isHorizontal,+ progress,+ index,+ anchors,thumbRef,children,}: {content: ReactNode;placement: 'above' | 'start';isOpen: boolean | undefined;- anchorStyle: CSSProperties;+ isHorizontal: boolean;+ /** The thumb's place along the travel, from 0 to 1. */+ progress: number;+ index: number;+ anchors: RefObject<Map<number, ValueAnchor>>;thumbRef: Ref<HTMLDivElement> | undefined;children: (trigger: {ref: Ref<HTMLDivElement>;@@ -659,12 +682,36 @@ function SliderValueTooltip({thumbRef,tooltip.interactionRef,);+ const {describedBy} = tooltip;+ const recordAnchor = useCallback(+ (element: HTMLSpanElement | null) => {+ if (element == null) {+ anchors.current.delete(index);+ } else {+ anchors.current.set(index, {element, tooltipId: describedBy});+ }+ },+ [anchors, index, describedBy],+ );+ const anchorRef = useMergedRefs<HTMLSpanElement>(+ tooltip.positionRef,+ recordAnchor,+ );+ const anchorStyle: AnchorStyle = {[THUMB_PROGRESS]: progress};return (<><spanaria-hidden="true"- ref={tooltip.positionRef}- {...mergeProps(stylex.props(styles.valueAnchor), {style: anchorStyle})}+ ref={anchorRef}+ {...mergeProps(+ stylex.props(+ styles.valueAnchor,+ isHorizontal+ ? styles.valueAnchorHorizontal+ : styles.valueAnchorVertical,+ ),+ {style: anchorStyle},+ )}/>{children({ref: triggerRef, describedBy: tooltip.describedBy})}{tooltip.renderTooltip(content)}@@ -767,6 +814,11 @@ export function Slider({ref, ...props}: SliderProps) {const trackRef = useRef<HTMLDivElement>(null);const fillMoverRef = useRef<HTMLDivElement>(null);const fillRef = useRef<HTMLDivElement>(null);+ const valueAnchorsRef = useRef(new Map<number, ValueAnchor>());+ /** The places an interaction holds value-tooltip anchors at, by thumb. */+ const [heldAnchors, setHeldAnchors] = useState<ReadonlyMap<number, number>>(+ () => new Map(),+ );const draggingThumbRef = useRef<number | null>(null);const [draggingThumb, setDraggingThumb] = useState<number | null>(null);@@ -1269,6 +1321,35 @@ export function Slider({ref, ...props}: SliderProps) {});},reportEnd: () => fireChangeEnd(),+ // A held anchor renders at its held place, so a render during the drag+ // writes nothing on it. In Chromium, any style change on an element in+ // anchor positioning lays it out.+ holdAnchor: index => {+ const anchor = valueAnchorsRef.current.get(index)?.element;+ const progress = parseFloat(+ anchor?.style.getPropertyValue(THUMB_PROGRESS) ?? '',+ );+ if (anchor == null || !Number.isFinite(progress)) {+ return null;+ }+ setHeldAnchors(held => new Map(held).set(index, progress));+ return progress;+ },+ // From the controller's hand-back, after the owner rendered the last+ // value. The anchors take their final place in this render, before the+ // next frame.+ releaseAnchors: indices => {+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the anchors must reach their final place in the task that ends the tooltips' translates+ flushSync(() => {+ setHeldAnchors(held => {+ const next = new Map(held);+ for (const index of indices) {+ next.delete(index);+ }+ return next;+ });+ });+ },// A tap on the track, from useSliderTouch. It takes a mark's value on a// mark, else the point along the travel. It moves the thumb a track// press moves.@@ -1292,13 +1373,20 @@ export function Slider({ref, ...props}: SliderProps) {if (control == null) {return null;}+ const thumbs = Array.from(+ control.querySelectorAll<HTMLElement>('[role="slider"]'),+ );return {control,- thumbs: Array.from(- control.querySelectorAll<HTMLElement>('[role="slider"]'),- ),+ thumbs,fillMover: fillMoverRef.current,fill: fillRef.current,+ tooltips: thumbs.map((_, index) => {+ const anchor = valueAnchorsRef.current.get(index);+ return anchor == null+ ? null+ : control.ownerDocument.getElementById(anchor.tooltipId);+ }),};},});@@ -1539,7 +1627,6 @@ export function Slider({ref, ...props}: SliderProps) {);if (useValueTooltip) {- const anchorAt = `calc(${insetPosition(percent)} - ${THUMB_SIZE / 2}px)`;return (<SliderValueTooltipkey={thumbIndex}@@ -1550,17 +1637,10 @@ export function Slider({ref, ...props}: SliderProps) {isOpen={draggingThumb === null ? undefined : draggingThumb === thumbIndex}- anchorStyle={- isHorizontal- ? {- insetInlineStart: anchorAt,- top: `calc(50% - ${THUMB_SIZE / 2}px)`,- }- : {- bottom: anchorAt,- insetInlineStart: `calc(50% - ${THUMB_SIZE / 2}px)`,- }- }+ isHorizontal={isHorizontal}+ progress={heldAnchors.get(thumbIndex) ?? percent / 100}+ index={thumbIndex}+ anchors={valueAnchorsRef}thumbRef={!isRange ? ref : undefined}>{thumbElement}</SliderValueTooltip>diff --git a/packages/core/src/Slider/__tests__/SliderValueTooltip.interaction.browser.spec.ts b/packages/core/src/Slider/__tests__/SliderValueTooltip.interaction.browser.spec.tsnew file mode 100644index 0000000000..0420e2622d--- /dev/null+++ b/packages/core/src/Slider/__tests__/SliderValueTooltip.interaction.browser.spec.ts@@ -0,0 +1,435 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SliderValueTooltip.interaction.browser.spec.ts+ * @input The built Slider "Default" and "Vertical orientation" stories,+ * Playwright's mouse, real touch input and the interaction harness+ * @output Proofs that the value tooltip stays on its thumb in every frame of+ * a mouse drag, of a finger's drag and of its coast. Each runs left to+ * right, right to left and vertical. They read where the page places the+ * two and where the screen draws them. Its anchor box stays put until the+ * end, so no layout moves it per frame.+ * @position Browser layer of Slider's value tooltip. The touch model's own+ * proofs are in SliderTouch.interaction.browser.spec.ts.+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {+ castStep,+ CONTROL_RGB,+ flick,+ frames,+ MARKER_RGB,+ openStory,+ startScreencast,+ touchDriver,+ trackMarker,+ waitForRest,+ withStorybook,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++/** The largest gap the page may place between the two, CSS px. */+const PLACED_GAP = 0.5;++/** Each direction of travel, and the screen direction that raises the value. */+const LAYOUTS = [+ {+ name: 'left to right',+ story: 'core-slider--default',+ rtl: false,+ axis: 'x',+ toward: {x: 1, y: 0},+ },+ {+ name: 'right to left',+ story: 'core-slider--default',+ rtl: true,+ axis: 'x',+ toward: {x: -1, y: 0},+ },+ {+ name: 'vertical',+ story: 'core-slider--vertical-orientation',+ rtl: false,+ axis: 'y',+ toward: {x: 0, y: -1},+ },+] as const;++type Layout = (typeof LAYOUTS)[number];++async function openLayout(page: Page, layout: Layout): Promise<void> {+ if (layout.rtl) {+ await page.goto(+ `${storybook()}/iframe.html?id=${layout.story}&viewMode=story&globals=direction:rtl`,+ );+ await page.getByRole('slider').first().waitFor();+ await frames(page, 2);+ } else {+ await openStory(page, storybook(), layout.story);+ }+}++interface Gaps {+ /** Frames the page drew while the tooltip was open. */+ readonly frames: number;+ /** Each frame's gap, CSS px, in drawing order. */+ readonly gaps: number[];+ /** Frames with a running translate animation on the thumb: the coast. */+ readonly coastFrames: number;+}++/**+ * Starts recording, once per frame, how far the open tooltip's center has+ * moved from the thumb's center since rest, along the travel. Each element+ * is read where the page draws it: its anchor or its own box, at rest, plus+ * its live computed translate. A compositor animation's client rect is+ * stale in some engines, but its computed translate is current in all.+ */+async function recordGaps(+ page: Page,+ axis: 'x' | 'y',+): Promise<() => Promise<Gaps>> {+ await page.evaluate(along => {+ const thumb = document.querySelector<HTMLElement>('[role="slider"]');+ const tooltip = document.querySelector<HTMLElement>(':popover-open');+ if (thumb == null || tooltip == null) {+ throw new Error('recordGaps: open the value tooltip first');+ }+ const anchorName =+ getComputedStyle(tooltip).getPropertyValue('position-anchor');+ const anchor = [...document.querySelectorAll<HTMLElement>('*')].find(+ element =>+ getComputedStyle(element).getPropertyValue('anchor-name') ===+ anchorName,+ );+ if (anchor == null) {+ throw new Error(`recordGaps: no element is named ${anchorName}`);+ }+ const centerX = (element: Element) => {+ const box = element.getBoundingClientRect();+ return along === 'x'+ ? box.left + box.width / 2+ : box.top + box.height / 2;+ };+ const translateX = (element: Element) => {+ const translate = getComputedStyle(element).translate;+ const [x = '0', y = '0'] =+ translate === 'none' ? [] : translate.split(' ');+ return parseFloat(along === 'x' ? x : y);+ };+ // At rest no animation runs, so every client rect is current.+ const thumbBox = centerX(thumb) - translateX(thumb);+ const fromAnchor = centerX(tooltip) - centerX(anchor);+ const thumbAt = () => thumbBox + translateX(thumb);+ const tooltipAt = () => centerX(anchor) + fromAnchor + translateX(tooltip);+ const restGap = tooltipAt() - thumbAt();+ const state = {on: true, gaps: [] as number[], coastFrames: 0};+ (window as unknown as {__tooltipGaps: typeof state}).__tooltipGaps = state;+ const read = () => {+ if (!state.on) {+ return;+ }+ if (tooltip.matches(':popover-open')) {+ state.gaps.push(tooltipAt() - thumbAt() - restGap);+ if (+ thumb+ .getAnimations()+ .some(animation =>+ (animation.effect as KeyframeEffect | null)+ ?.getKeyframes()+ .some(keyframe => 'translate' in keyframe),+ )+ ) {+ state.coastFrames += 1;+ }+ }+ requestAnimationFrame(read);+ };+ requestAnimationFrame(read);+ }, axis);+ return async () =>+ page.evaluate(() => {+ const state = (+ window as unknown as {+ __tooltipGaps: {on: boolean; gaps: number[]; coastFrames: number};+ }+ ).__tooltipGaps;+ state.on = false;+ return {+ frames: state.gaps.length,+ gaps: state.gaps,+ coastFrames: state.coastFrames,+ };+ });+}++/** The frames whose gap passes `limit`, as "frame: gap" for a message. */+function overLimit(gaps: ReadonlyArray<number>, limit: number): string[] {+ return gaps.flatMap((gap, index) =>+ Math.abs(gap) > limit ? [`${index}: ${gap.toFixed(2)} px`] : [],+ );+}++test.describe('with a mouse', () => {+ test.use({+ isMobile: false,+ hasTouch: false,+ deviceScaleFactor: 1,+ viewport: {width: 800, height: 600},+ });++ for (const layout of LAYOUTS) {+ test(`the value tooltip stays on its thumb in every frame of a mouse drag, ${layout.name}`, async ({+ page,+ }) => {+ await openLayout(page, layout);+ const thumb = page.getByRole('slider').first();+ const box = await thumb.boundingBox();+ if (box == null) {+ throw new Error('the thumb has no box');+ }+ const at = {x: box.x + box.width / 2, y: box.y + box.height / 2};+ // Hovering the thumb opens its tooltip, and the drag keeps it open.+ await page.mouse.move(at.x, at.y);+ await expect(page.getByRole('tooltip')).toBeVisible();+ await frames(page, 20);+ const stop = await recordGaps(page, layout.axis);+ await page.mouse.down();+ for (let step = 1; step <= 30; step++) {+ await page.mouse.move(+ at.x + step * 4 * layout.toward.x,+ at.y + step * 4 * layout.toward.y,+ );+ await frames(page, 1);+ }+ await page.mouse.up();+ await frames(page, 10);+ const {frames: drawn, gaps} = await stop();+ expect(drawn).toBeGreaterThan(30);+ expect(Number(await thumb.getAttribute('aria-valuenow'))).toBeGreaterThan(+ 50,+ );+ expect(overLimit(gaps, PLACED_GAP), `${drawn} frames`).toEqual([]);+ });+ }+ test('after a drag, a key that takes the value back to where the drag began brings the tooltip back with its thumb', async ({+ page,+ }) => {+ await openStory(page, storybook(), 'core-slider--default');+ const thumb = page.getByRole('slider').first();+ await thumb.focus();+ await page.keyboard.press('Home');+ await expect(thumb).toHaveAttribute('aria-valuenow', '0');+ await expect(page.getByRole('tooltip')).toBeVisible();+ await frames(page, 20);+ const box = await thumb.boundingBox();+ if (box == null) {+ throw new Error('the thumb has no box');+ }+ const at = {x: box.x + box.width / 2, y: box.y + box.height / 2};+ const stop = await recordGaps(page, 'x');+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ for (let step = 1; step <= 30; step++) {+ await page.mouse.move(at.x + step * 4, at.y);+ await frames(page, 1);+ }+ await page.mouse.up();+ await frames(page, 10);+ expect(Number(await thumb.getAttribute('aria-valuenow'))).toBeGreaterThan(+ 0,+ );+ // The value the drag began at: the first render after the drag gives it+ // again.+ await page.keyboard.press('Home');+ await expect(thumb).toHaveAttribute('aria-valuenow', '0');+ await frames(page, 10);+ const {frames: drawn, gaps} = await stop();+ expect(overLimit(gaps, PLACED_GAP), `${drawn} frames`).toEqual([]);+ });+});++test.describe('with a finger', () => {+ for (const layout of LAYOUTS) {+ test(`the value tooltip stays on its thumb in every frame of a drag and its coast, ${layout.name}`, async ({+ page,+ }) => {+ await openLayout(page, layout);+ const driver = await touchDriver(page);+ const thumb = page.getByRole('slider').first();+ await expect(thumb).toBeVisible();+ // A focused thumb shows its tooltip through the drag and the coast.+ await thumb.focus();+ await expect(page.getByRole('tooltip')).toBeVisible();+ await frames(page, 20);+ const box = await thumb.boundingBox();+ if (box == null) {+ throw new Error('the thumb has no box');+ }+ const at = {x: box.x + box.width / 2, y: box.y + box.height / 2};+ const stop = await recordGaps(page, layout.axis);+ await driver.play(+ flick(at, {+ velocity: {x: 300 * layout.toward.x, y: 300 * layout.toward.y},+ durationMs: 200,+ }),+ );+ await waitForRest(thumb);+ await frames(page, 10);+ const {frames: drawn, gaps, coastFrames} = await stop();+ expect(Number(await thumb.getAttribute('aria-valuenow'))).toBeGreaterThan(+ 50,+ );+ // With the script's timestamps the release velocity is the script's, so+ // the coast always runs. Injected touches carry their real dispatch+ // times, and a scheduling gap before the lift reads as a resting finger+ // (README: engine limits).+ if (driver.scriptedTimestamps) {+ expect(coastFrames).toBeGreaterThan(5);+ }+ expect(overLimit(gaps, PLACED_GAP), `${drawn} frames`).toEqual([]);+ });+ }++ test('the value tooltip’s anchor box stays put through a drag and its coast, and moves once at the end', async ({+ page,+ }) => {+ await openStory(page, storybook(), 'core-slider--default');+ const driver = await touchDriver(page);+ const thumb = page.getByRole('slider').first();+ await expect(thumb).toBeVisible();+ await thumb.focus();+ await expect(page.getByRole('tooltip')).toBeVisible();+ await frames(page, 20);+ const box = await thumb.boundingBox();+ if (box == null) {+ throw new Error('the thumb has no box');+ }+ const at = {x: box.x + box.width / 2, y: box.y + box.height / 2};+ // Every write to the anchor box, whether the thumb still moved by+ // translate then, and the box's place in every frame.+ await page.evaluate(() => {+ const thumbElement =+ document.querySelector<HTMLElement>('[role="slider"]');+ const tooltip = document.querySelector<HTMLElement>(':popover-open');+ const name = tooltip+ ? getComputedStyle(tooltip).getPropertyValue('position-anchor')+ : '';+ const anchor = [...document.querySelectorAll<HTMLElement>('*')].find(+ element =>+ getComputedStyle(element).getPropertyValue('anchor-name') === name,+ );+ if (anchor == null || thumbElement == null) {+ throw new Error(`no element is named ${name}`);+ }+ const moving = () =>+ thumbElement.style.translate !== '' ||+ thumbElement+ .getAnimations()+ .some(animation =>+ (animation.effect as KeyframeEffect | null)+ ?.getKeyframes()+ .some(keyframe => 'translate' in keyframe),+ );+ const state = {+ on: true,+ writes: [] as boolean[],+ places: [] as number[],+ };+ (window as unknown as {__anchor: typeof state}).__anchor = state;+ new MutationObserver(records => {+ for (const _ of records) {+ state.writes.push(moving());+ }+ }).observe(anchor, {attributes: true});+ const read = () => {+ if (!state.on) {+ return;+ }+ state.places.push(anchor.getBoundingClientRect().left);+ requestAnimationFrame(read);+ };+ requestAnimationFrame(read);+ });+ await driver.play(flick(at, {velocity: {x: 300, y: 0}, durationMs: 300}));+ await waitForRest(thumb);+ await frames(page, 10);+ const {writes, moves} = await page.evaluate(() => {+ const state = (+ window as unknown as {+ __anchor: {on: boolean; writes: boolean[]; places: number[]};+ }+ ).__anchor;+ state.on = false;+ return {+ writes: state.writes,+ moves: state.places.filter(+ (place, index) => index > 0 && place !== state.places[index - 1],+ ).length,+ };+ });+ expect(await thumb.getAttribute('aria-valuenow')).not.toBe('50');+ // One write, once the thumb stopped moving by translate, and one move.+ expect(writes).toEqual([false]);+ expect(moves).toBe(1);+ });++ test('the screen draws the value tooltip on its thumb in every frame of a drag and its coast', async ({+ page,+ }) => {+ await openStory(page, storybook(), 'core-slider--default');+ const driver = await touchDriver(page);+ const thumb = page.getByRole('slider').first();+ await expect(thumb).toBeVisible();+ await thumb.focus();+ const tooltip = page.getByRole('tooltip');+ await expect(tooltip).toBeVisible();+ // A chip at each one's center: the thumb's lift scales it about its+ // center, and the tooltip widens about its center as its text changes.+ for (const [element, rgb] of [+ [thumb, MARKER_RGB],+ [tooltip, CONTROL_RGB],+ ] as const) {+ await element.evaluate((node, color) => {+ const chip = document.createElement('div');+ chip.style.cssText = `position:absolute;left:calc(50% - 3px);top:calc(50% - 3px);width:6px;height:6px;background:rgb(${color.join(',')});z-index:2147483647;pointer-events:none;`;+ node.append(chip);+ }, rgb);+ }+ await frames(page, 20);+ const box = await thumb.boundingBox();+ if (box == null) {+ throw new Error('the thumb has no box');+ }+ const at = {x: box.x + box.width / 2, y: box.y + box.height / 2};+ const cast = await startScreencast(page);+ await frames(page, 4);+ await driver.play(flick(at, {velocity: {x: 300, y: 0}, durationMs: 300}));+ await waitForRest(thumb);+ await frames(page, 6);+ const shot = await cast.stop();+ const thumbs = await trackMarker(page, shot);+ const tooltips = await trackMarker(page, shot, {rgb: CONTROL_RGB});+ const pairs = thumbs.flatMap((frame, index) => {+ const other = tooltips[index]?.box;+ return frame.box != null && other != null+ ? [frame.box.x + frame.box.width / 2 - (other.x + other.width / 2)]+ : [];+ });+ expect(pairs.length).toBeGreaterThan(30);+ // One step of the cast's position grid: 1 px in Chromium's PNG cast,+ // 2 px in WebKit's JPEG cast.+ const step = castStep(thumbs, 'x');+ const rest = pairs[0];+ expect(+ overLimit(+ pairs.map(gap => gap - rest),+ step,+ ),+ `${pairs.length} frames`,+ ).toEqual([]);+ });+});diff --git a/packages/core/src/Slider/sliderTouchController.ts b/packages/core/src/Slider/sliderTouchController.tsindex 916ae87e31..5a3e9ac224 100644--- a/packages/core/src/Slider/sliderTouchController.ts+++ b/packages/core/src/Slider/sliderTouchController.ts@@ -2,8 +2,9 @@/*** @file sliderTouchController.ts- * @input The slider's control (and its size), thumbs, fill parts and value- * model; the gesture recognizers, the animator and the UIKit slider table+ * @input The slider's control (and its size), thumbs, fill parts, value+ * tooltips and value model; the gesture recognizers, the animator and the+ * UIKit slider table* @output Exports `SliderTouchController`, `sliderCoastCurve` and the* `SliderTouchModel` and `SliderTouchParts` types* @position Internal to Slider: useSliderTouch attaches it while enabled.@@ -60,6 +61,8 @@ export interface SliderTouchParts {/** The fill's mover (a range's start) and the fill itself. */readonly fillMover: HTMLElement | null;readonly fill: HTMLElement | null;+ /** Each thumb's value tooltip while it is mounted, else null. */+ readonly tooltips: ReadonlyArray<HTMLElement | null>;}/** What the controller needs from Slider. Read fresh on every use. */@@ -97,6 +100,18 @@ export interface SliderTouchModel {commit(index: number, value: number | null): void;/** `onChangeEnd`, with the values the owner rendered. */reportEnd(): void;+ /**+ * Holds thumb `index`'s value-tooltip anchor where the owner last rendered+ * it, and returns that place as progress along the travel (0 to 1). Null+ * when the thumb has no value tooltip. While held, the owner's renders do+ * not move the anchor, so the tooltip can move with the thumb by translate.+ */+ holdAnchor(index: number): number | null;+ /**+ * The anchors of thumbs `indices` follow the owner's rendered values+ * again. The owner renders them now, so they move in this task.+ */+ releaseAnchors(indices: ReadonlyArray<number>): void;/*** The value a press at client point (`x`, `y`) on the track means: a* mark's value on a mark, else the point along the travel.@@ -173,6 +188,8 @@ interface Interaction {* thumb by its first movement and may pass to the other thumb.*/readonly beganCoincident: boolean;+ /** Each held tooltip anchor's place, as progress, by thumb. */+ readonly anchors: Map<number, number | null>;}/**@@ -241,6 +258,8 @@ export class SliderTouchController {private readonly getParts: () => SliderTouchParts | null;private readonly interactions = new Map<number, Interaction>();private readonly animators = new Map<HTMLElement, Animator>();+ /** The thumbs whose tooltip anchor an interaction holds. */+ private readonly heldAnchors = new Set<number>();/** The owner unmounted the slider: a cancel reports nothing then. */private disposed = false;/** Thumbs whose current touch is a mouse: Slider's own handlers take it. */@@ -422,6 +441,7 @@ export class SliderTouchController {for (const interaction of ended) {this.model.commit(interaction.index, null);}+ this.releaseHeldAnchors();if (ended.some(interaction => interaction.changed)) {this.model.reportEnd();}@@ -454,9 +474,35 @@ export class SliderTouchController {animator.set({opacity: 1});element.style.removeProperty('opacity');}+ // A value tooltip mounts anew each time it opens.+ if (!element.isConnected) {+ animator.dispose();+ this.animators.delete(element);+ }}}+ /**+ * Releases the tooltip anchors that no live interaction holds. It runs in+ * the task of the hand-back that ends their tooltips' translates. So+ * anchor positioning takes over at the place each translate held.+ */+ private releaseHeldAnchors(): void {+ const live = [...this.interactions.values()].filter(+ interaction => interaction.coast != null || !interaction.released,+ );+ const released = [...this.heldAnchors].filter(+ index => !live.some(interaction => interaction.anchors.has(index)),+ );+ if (released.length === 0) {+ return;+ }+ for (const index of released) {+ this.heldAnchors.delete(index);+ }+ this.model.releaseAnchors(released);+ }+// -- events ----------------------------------------------------------------private handleControlEvent(@@ -619,6 +665,7 @@ export class SliderTouchController {isMouse,coasts,beganCoincident: this.model.isRange && values[0] === values[1],+ anchors: new Map(),});this.model.press(owner);}@@ -821,6 +868,7 @@ export class SliderTouchController {isMouse: false,coasts: false,beganCoincident: false,+ anchors: new Map(),};this.interactions.set(index, interaction);// A tap's value change happens in place. So under Reduce Motion it@@ -1038,6 +1086,15 @@ export class SliderTouchController {}};add(parts.thumbs[index], p => p, 1);+ const tooltip = parts.tooltips[index];+ if (tooltip != null) {+ const anchored = this.anchorFor(interaction);+ if (anchored != null) {+ // The tooltip's anchor stays where it was held. The tooltip moves+ // with the thumb by translate.+ add(tooltip, p => p - anchored * travel, 1);+ }+ }if (isRange) {if (index === 0) {add(parts.fillMover, p => inset + p, 1);@@ -1109,6 +1166,7 @@ export class SliderTouchController {// reads what the owner rendered.this.model.commit(interaction.index, finalValue);this.handBack();+ this.releaseHeldAnchors();if (report) {this.model.reportEnd();}@@ -1192,6 +1250,22 @@ export class SliderTouchController {return animator;}+ /**+ * Where the interaction's thumb's tooltip anchor is held, as progress.+ * The first call for a thumb holds it, where the owner last rendered it.+ */+ private anchorFor(interaction: Interaction): number | null {+ const {anchors, index} = interaction;+ if (!anchors.has(index)) {+ const held = this.model.holdAnchor(index);+ anchors.set(index, held);+ if (held != null) {+ this.heldAnchors.add(index);+ }+ }+ return anchors.get(index) ?? null;+ }+private partsOf(interaction: Interaction): Set<HTMLElement> {const parts = this.getParts();const set = new Set<HTMLElement>();@@ -1199,7 +1273,10 @@ export class SliderTouchController {return set;}const thumb = parts.thumbs[interaction.index];- for (const element of [thumb, parts.fillMover, parts.fill]) {+ const tooltip = interaction.anchors.has(interaction.index)+ ? parts.tooltips[interaction.index]+ : null;+ for (const element of [thumb, parts.fillMover, parts.fill, tooltip]) {if (element != null) {set.add(element);}