An open source design system that's fully customizable and agent ready
TypeScript
test(SegmentedControl): hold the slide from its start (#10338)
Christopher Chedeau6cc14bef90fa
diff --git a/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts b/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.tsindex 4924772ca8..58b0bb043d 100644--- a/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts+++ b/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts@@ -25,14 +25,19 @@ import {// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned.import {PNG} from 'pngjs';import {+ advanceFrozenPage,animationStoryboard,+ armHold,blockMainThread,busyWindowProof,castStoryboard,compareCurve,countBetween,+ freezePageOn,freezeTimers,+ holdAnimations,installLongTaskLog,+ installPageFreeze,installTimerGate,MARKER_RGB,openStory,@@ -40,6 +45,7 @@ import {releaseAnimations,springStep,startScreencast,+ thawPage,thawTimers,timeline,touchDriver,@@ -273,37 +279,6 @@ async function waitForLens(}}-/**- * Pauses the running animations of both radiogroup pseudo-elements, the lens- * and its shadow, into the harness's held set. Then `releaseAnimations` moves- * exactly them. A pseudo-element has no inline style, so the animator holds- * each value with a finished, filling animation. Every running animation- * overrides those, so they are left alone.- */-async function holdLens(- control: Control,-): Promise<{easing: string; durationMs: number; pseudo: string}[]> {- return control.group.evaluate(group => {- const held = group.getAnimations({subtree: true}).filter(a => {- const effect = a.effect as KeyframeEffect | null;- return (- effect?.target === group &&- effect.pseudoElement != null &&- a.playState !== 'finished'- );- });- for (const animation of held) {- animation.pause();- }- (window as unknown as {__harnessHeld: Animation[]}).__harnessHeld = held;- return held.map(a => ({- easing: String((a.effect as KeyframeEffect).getTiming().easing),- durationMs: Number(a.effect?.getComputedTiming().duration ?? 0),- pseudo: String((a.effect as KeyframeEffect).pseudoElement),- }));- });-}-/*** The lens's presented geometry at each held time. `x` is its translate, the* center's offset from its layout box's center. `center` is in the track's@@ -511,10 +486,9 @@ test('the surface lands exactly where the segment paints it', async ({// Gate timers: the hand-back runs from the slide's completion timer, which// must wait while the landed frame is photographed.await installTimerGate(page);- const watch = await watchAnimations(control.group);+ await freezeTimersAtLensBirth(page);await control.tapSegment('list');- await waitForLens(control, {watch});- await freezeTimers(page);+ await timersFrozenAtLensBirth(page);// The slide runs its course on the compositor. With the timers held, the// hand-back waits. So this is the slide's last frame: the lens carries the// surface, and the segment's own is hidden.@@ -587,12 +561,12 @@ test('the titles switch at once with the selection: no second copy of a title isconst elements = await control.group.evaluate(group => group.querySelectorAll('*').length,);- const watch = await watchAnimations(control.group);+ await holdLensAnimationsAtBirth(page);await control.tapSegment('table');- await waitForLens(control, {watch});- // Mid-slide, as many elements as at rest, and nothing animates Table's- // title's weight or color: it already shows its selected rendering. (Its- // opacity comes back from the press's dim.)+ await heldLensSlide(control);+ // Once the slide starts, as many elements as at rest, and nothing animates+ // Table's title's weight or color: it already shows its selected rendering.+ // (Its opacity comes back from the press's dim.)expect(await control.group.evaluate(group => group.querySelectorAll('*').length),).toBe(elements);@@ -608,15 +582,15 @@ test('the titles switch at once with the selection: no second copy of a title is.filter(key => key === 'color' || key === 'fontWeight'),),).toEqual([]);+ await releaseAnimations(page, {finish: true});});test('a second tap mid-flight retargets from what is on screen, keeping its velocity', async ({page,}) => {+ await installPageFreeze(page);const control = await openControl(page);- const watch = await watchAnimations(control.group);- await control.tapSegment('table');- await waitForLens(control, {minProgressMs: 60, watch});+ await installTimerGate(page);const describe = async () =>control.group.evaluate(async group => {const animations = group.getAnimations({subtree: true}).filter(a => {@@ -645,10 +619,16 @@ test('a second tap mid-flight retargets from what is on screen, keeping its velo})),}))[0];});+ // Frozen in the first tap's own task, the slide starts held at its start.+ // The scene then moves 60 ms into it, and the second tap lands there.+ await freezePageOn(page, 'touchend');+ await control.tapSegment('table');+ await advanceFrozenPage(page, 60);const first = await describe();await control.tapSegment('list');await expect(control.segment('list')).toHaveAttribute('aria-checked', 'true');const second = await describe();+ await thawPage(page);expect(second.startTime).toBeGreaterThan(first.startTime);// The first curve, read where the second one starts.const at = (@@ -1038,6 +1018,77 @@ async function holdLensAnimationsAtBirth(page: Page): Promise<void> {});}+/**+ * Waits until the tap's slide is held from its first frame+ * (`holdLensAnimationsAtBirth`), then puts `animate` back.+ */+async function heldLensSlide(control: Control): Promise<void> {+ await control.group.evaluate(async group => {+ const w = window as unknown as {+ __harnessHeld: Animation[];+ __restoreAnimate: () => void;+ __harnessTimerGate?: {timeout?: typeof setTimeout};+ };+ const later = w.__harnessTimerGate?.timeout ?? setTimeout;+ const isSlide = (animation: Animation) => {+ const effect = animation.effect as KeyframeEffect;+ return (+ effect.target === group &&+ effect.pseudoElement === '::before' &&+ Number(effect.getComputedTiming().duration) > 1+ );+ };+ const deadline = performance.now() + 5000;+ while (!w.__harnessHeld.some(isSlide)) {+ if (performance.now() > deadline) {+ throw new Error('no lens slide was held');+ }+ await new Promise(resolve => later(resolve, 4));+ }+ w.__restoreAnimate();+ });+}++/**+ * Freezes the page's timers in the task that starts the lens's slide. A+ * timer that the slide's end schedules then waits, however late the test+ * looks. The slide itself runs on. Needs `installTimerGate` first.+ */+async function freezeTimersAtLensBirth(page: Page): Promise<void> {+ await page.evaluate(() => {+ const original = Element.prototype.animate;+ const w = window as unknown as {+ __harnessTimerGate: {freeze(): void};+ __lensBorn?: boolean;+ };+ w.__lensBorn = false;+ Element.prototype.animate = function (+ this: Element,+ ...args: Parameters<Element['animate']>+ ): Animation {+ const animation = original.apply(this, args);+ const [, options] = args;+ if (+ this.getAttribute('role') === 'radiogroup' &&+ typeof options === 'object' &&+ options?.pseudoElement != null &&+ Number(options.duration) > 1+ ) {+ Element.prototype.animate = original;+ w.__harnessTimerGate.freeze();+ w.__lensBorn = true;+ }+ return animation;+ };+ });+}++async function timersFrozenAtLensBirth(page: Page): Promise<void> {+ await page.waitForFunction(+ () => (window as unknown as {__lensBorn?: boolean}).__lensBorn === true,+ );+}+/*** The easings of the slides that `holdLensAnimationsAtBirth` held on this* control's lens (its radiogroup's ::before). `Element.animate` is put back@@ -1161,10 +1212,9 @@ test('the slide plays UISegmentedControl’s measured spring, an internal motion}});const from = boxOf(await control.boxes(), 'grid');- const watch = await watchAnimations(control.group);+ await holdLensAnimationsAtBirth(page);await control.tapSegment('table');- await waitForLens(control, {watch});- await holdLens(control);+ await heldLensSlide(control);const samples = await sampleLens(control.group, timeline(400));await releaseAnimations(page);// Where Table is once its title has its new weight: where the lens aims.@@ -1196,10 +1246,9 @@ test('RTL: the surface slides toward the tapped segment', async ({page}) => {{direction: 'rtl'},);const grid = boxOf(await control.boxes(), 'grid');- const watch = await watchAnimations(control.group);+ await holdLensAnimationsAtBirth(page);await control.tapSegment('table');- await waitForLens(control, {watch});- await holdLens(control);+ await heldLensSlide(control);const [start, end] = await sampleLens(control.group, [0, 2000]);// Where Table is once its title has its new weight.const table = boxOf(await control.boxes(), 'table');@@ -1441,6 +1490,7 @@ test('storyboard: tap to slide, and a second tap mid-flight',{tag: '@storyboard'},async ({page}, testInfo) => {+ await installPageFreeze(page);const control = await openControl(page);await installTimerGate(page);const measure = async () => {@@ -1457,15 +1507,25 @@ test(});return sample;};- const watch = await watchAnimations(control.group);+ // A segment's own release fade starts before the slide: with a count of+ // 2, it cannot trigger the hold alone.+ const hold = await armHold(page, control.group, {+ judges: {+ target: control.group,+ property: 'translate',+ pseudoElement: '::before',+ },+ count: 2,+ newOnly: true,+ });await control.tapSegment('table');- await waitForLens(control, {watch});+ const held = await hold.held();await freezeTimers(page);const {storyboard: slideBoard} = await animationStoryboard(page, {+ held,name: 'segmented-tap-slide',times: timeline(700),clip: control.group,- scope: control.group,measure,columns: 8,cellScale: 1,@@ -1481,17 +1541,22 @@ test(expect(Math.max(...xs)).toBeGreaterThan(centerOf(table));expect(Math.max(...xs) - centerOf(table)).toBeLessThan(2);- // A second tap 80 ms into a slide back to the first segment.+ // A second tap 80 ms into a slide back to the first segment. Frozen in+ // the first tap's own task, the slide starts held. The scene moves 80 ms+ // on. The second tap's retarget then starts held too, and the hold takes+ // it from there.+ await freezePageOn(page, 'touchend');await control.tapSegment('grid');- await waitForLens(control, {minProgressMs: 80});+ await advanceFrozenPage(page, 80);await control.tapSegment('list');- await waitForLens(control);+ const retargetHeld = await holdAnimations(page, control.group);+ await thawPage(page);await freezeTimers(page);const {storyboard: retargetBoard} = await animationStoryboard(page, {+ held: retargetHeld,name: 'segmented-retarget',times: timeline(700),clip: control.group,- scope: control.group,measure,columns: 8,cellScale: 1,