Skip to content

Commit 73803ee

Browse files
committed
fix(core): Switch's track colour keeps fading in while the main thread is busy
On the iOS 26.2 simulator, a tap followed by a 700 ms main-thread block moved the thumb through the block but froze the track's on colour until the block ended: Safari ran the on layer's opacity fade on the main thread. The on layer is now composited from the start under a coarse pointer (`will-change: opacity`), and once the touch presentation attaches, its opacity belongs to the animator alone (its class keeps the mount value). The Chromium busy-main-thread proof now also tracks the track colour through the block; Chromium composites the fade either way, so the iOS simulator clip is the before/after evidence.
1 parent f8f3be1 commit 73803ee

3 files changed

Lines changed: 140 additions & 1 deletion

File tree

‎packages/core/src/Switch/Switch.tsx‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
useId,
2121
useMemo,
2222
useOptimistic,
23+
useState,
2324
useTransition,
2425
useEffect,
2526
useRef,
@@ -393,6 +394,9 @@ const styles = stylex.create({
393394
inset: 0,
394395
borderRadius: 'inherit',
395396
pointerEvents: 'none',
397+
// Its own compositing layer from the start, so its colour fade runs off
398+
// the main thread (iOS Safari otherwise animates it on the main thread).
399+
willChange: {default: null, [TOUCH]: 'opacity'},
396400
backgroundColor: {
397401
default: colorVars['--color-accent'],
398402
'@media (forced-colors: active)': 'Highlight',
@@ -720,6 +724,10 @@ export function Switch({
720724
const thumbRef = useRef<HTMLDivElement>(null);
721725
const glassRef = useRef<HTMLSpanElement>(null);
722726
const onLayerRef = useRef<HTMLSpanElement>(null);
727+
// Once mounted, the touch presentation's animator owns the on layer's
728+
// opacity; its class keeps the value it mounted with, so a toggle never
729+
// changes the faded property's base under a running fade.
730+
const [isOnAtMount] = useState(isOn);
723731
const touchParts = useMemo<SwitchTouchParts>(
724732
() => ({
725733
surface: surfaceRef,
@@ -813,7 +821,7 @@ export function Switch({
813821
ref={onLayerRef}
814822
{...stylex.props(
815823
styles.trackOnLayer,
816-
!isOn && styles.trackOnLayerOff,
824+
!isOnAtMount && styles.trackOnLayerOff,
817825
)}
818826
/>
819827
<span

‎packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts‎

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import {
5050
waitForRest,
5151
withStorybook,
5252
writeEvidence,
53+
type CastFrame,
5354
type TouchDriver,
5455
} from '@astryxdesign/interaction-harness';
5556
import {SWITCH_CLAIMS_HELD_TOUCH} from '../switchTouchClaim';
@@ -764,6 +765,68 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2)', () => {
764765
expect(held.at(-1)!.box!.x - held[0].box!.x).toBeGreaterThanOrEqual(8);
765766
});
766767

768+
test('P10 · the track colour keeps fading in while the main thread is blocked', async ({
769+
page,
770+
browserName,
771+
}, testInfo) => {
772+
test.skip(
773+
browserName !== 'chromium',
774+
'screencast frame evidence is Chromium-only in Playwright (WebKit: the iOS simulator rig)',
775+
);
776+
const {driver, input, onLayer, center} = await openSwitch(page);
777+
// Hide the thumb (its animations still run) so the whole track shows
778+
// its colour.
779+
await page.addStyleTag({
780+
content:
781+
'#storybook-root .astryx-switch > span:not(:first-child) { visibility: hidden }',
782+
});
783+
const box = await page
784+
.locator('#storybook-root .astryx-switch')
785+
.first()
786+
.boundingBox();
787+
if (box == null) {
788+
throw new Error('no track');
789+
}
790+
const cast = await startScreencast(page);
791+
await driver.play(tap(center, {holdMs: 50}));
792+
await expect(input).toBeChecked();
793+
await waitForAnimation(onLayer, {minProgressMs: 16});
794+
const block = await blockMainThread(page, 700);
795+
await page.waitForTimeout(150);
796+
const castFrames = await cast.stop();
797+
const luma = await sampleLuma(page, castFrames, {
798+
x: box.x + 4,
799+
y: box.y + 4,
800+
width: box.width - 8,
801+
height: box.height - 8,
802+
});
803+
await writeEvidence(
804+
'busy-main-thread/switch-track-colour',
805+
{
806+
[`${testInfo.project.name}.json`]: JSON.stringify(
807+
{
808+
block,
809+
frames: luma.map(f => ({
810+
t: +(f.t - block.from).toFixed(1),
811+
luma: +f.luma.toFixed(1),
812+
})),
813+
},
814+
null,
815+
1,
816+
),
817+
},
818+
testInfo,
819+
);
820+
const off = luma[0].luma;
821+
const on = luma.at(-1)!.luma;
822+
const held = luma.filter(
823+
f => f.t >= block.from + 20 && f.t <= block.to - 20,
824+
);
825+
expect(held.length).toBeGreaterThan(20);
826+
// Most of the fade happened while the main thread was held.
827+
expect(held[0].luma - held.at(-1)!.luma).toBeGreaterThan(0.5 * (off - on));
828+
});
829+
767830
test('P10 · the toggle does no Layout or Paint per frame', async ({
768831
page,
769832
browserName,
@@ -852,6 +915,67 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2)', () => {
852915
);
853916
});
854917

918+
/**
919+
* The mean luma of a box (CSS px) in each screencast frame, decoded in a
920+
* scratch page like the harness's marker tracking.
921+
*/
922+
async function sampleLuma(
923+
page: Page,
924+
frames: ReadonlyArray<CastFrame>,
925+
region: {x: number; y: number; width: number; height: number},
926+
): Promise<{t: number; luma: number}[]> {
927+
const scratch = await page.context().newPage();
928+
try {
929+
const out: {t: number; luma: number}[] = [];
930+
for (let i = 0; i < frames.length; i += 12) {
931+
const batch = frames.slice(i, i + 12);
932+
const values = await scratch.evaluate(
933+
async ({items, box}) => {
934+
const result: number[] = [];
935+
for (const item of items) {
936+
const blob = await (
937+
await fetch(`data:image/${item.format};base64,${item.data}`)
938+
).blob();
939+
const bitmap = await createImageBitmap(blob);
940+
const scale = bitmap.width / item.viewportWidth;
941+
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
942+
const context = canvas.getContext('2d');
943+
if (context == null) {
944+
throw new Error('no 2d context');
945+
}
946+
context.drawImage(bitmap, 0, 0);
947+
const {data} = context.getImageData(
948+
Math.round(box.x * scale),
949+
Math.round(box.y * scale),
950+
Math.max(1, Math.round(box.width * scale)),
951+
Math.max(1, Math.round(box.height * scale)),
952+
);
953+
let sum = 0;
954+
for (let o = 0; o < data.length; o += 4) {
955+
sum +=
956+
0.2126 * data[o] + 0.7152 * data[o + 1] + 0.0722 * data[o + 2];
957+
}
958+
result.push(sum / (data.length / 4));
959+
}
960+
return result;
961+
},
962+
{
963+
items: batch.map(f => ({
964+
data: f.data,
965+
format: f.format,
966+
viewportWidth: f.viewportWidth,
967+
})),
968+
box: region,
969+
},
970+
);
971+
values.forEach((luma, k) => out.push({t: batch[k].t, luma}));
972+
}
973+
return out;
974+
} finally {
975+
await scratch.close();
976+
}
977+
}
978+
855979
/** The track with room for the lifted lens around it. */
856980
async function clipAround(track: Locator) {
857981
const box = await track.boundingBox();

‎packages/core/src/Switch/useSwitchTouch.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,10 @@
4848
* (the lift spring until the settle may start, then the settle spring from
4949
* that state), so the settle starts on time on the compositor even if the
5050
* main thread is busy.
51+
* - The track's on layer is composited from the start (`will-change` under a
52+
* coarse pointer, Switch.tsx) and, once attached, its opacity is the
53+
* animator's alone: iOS Safari otherwise ran its fade on the main thread,
54+
* so a busy main thread froze the track colour while the thumb moved.
5155
* - Reduce Motion changes nothing here: UISwitch keeps its lift and springs
5256
* (it drops only the lens's squash and stretch, which this does not draw).
5357
*
@@ -267,6 +271,9 @@ export class SwitchTouchController {
267271
this.on = createAnimator(elements.on, {
268272
initial: {opacity: this.isOn ? 1 : 0},
269273
});
274+
// The on layer's class holds the value it mounted with; from here its
275+
// opacity is the animator's.
276+
this.on.set({opacity: this.isOn ? 1 : 0});
270277

271278
const host = getGestureHost(elements.surface.ownerDocument);
272279
this.detachers = SWITCH_CLAIMS_HELD_TOUCH

0 commit comments

Comments
 (0)