Skip to content

Commit 56fd98b

Browse files
StiensWoutGrok 4.7juliusmarminge
authored
perf(web): batch first-send composer updates (#36166)
Co-authored-by: Grok 4.7 <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent 2dd6cdd commit 56fd98b

3 files changed

Lines changed: 174 additions & 42 deletions

File tree

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2+
3+
import { runMobileComposerTransition } from "./draftHeroTransition";
4+
5+
type StartViewTransition = (update: () => void | Promise<void>) => {
6+
finished: Promise<void>;
7+
};
8+
9+
function stubEnvironment(input: {
10+
mobile: boolean;
11+
reducedMotion?: boolean;
12+
startViewTransition?: StartViewTransition;
13+
}) {
14+
const styles = new Map<string, string>();
15+
const root = {
16+
style: {
17+
setProperty: (name: string, value: string) => styles.set(name, value),
18+
removeProperty: (name: string) => styles.delete(name),
19+
getPropertyValue: (name: string) => styles.get(name) ?? "",
20+
},
21+
dataset: {} as Record<string, string>,
22+
};
23+
vi.stubGlobal("window", {
24+
matchMedia: (query: string) => ({
25+
matches: query.includes("max-width") ? input.mobile : (input.reducedMotion ?? false),
26+
}),
27+
});
28+
vi.stubGlobal("document", {
29+
documentElement: root,
30+
...(input.startViewTransition ? { startViewTransition: input.startViewTransition } : {}),
31+
});
32+
return root;
33+
}
34+
35+
/** A view transition that runs its update after the old snapshot, like the browser does. */
36+
function deferredViewTransition(): StartViewTransition {
37+
return (update) => ({
38+
finished: Promise.resolve().then(update),
39+
});
40+
}
41+
42+
describe("runMobileComposerTransition", () => {
43+
afterEach(() => {
44+
vi.unstubAllGlobals();
45+
});
46+
47+
it.each([
48+
{ name: "desktop viewport", mobile: false, active: true },
49+
{ name: "reduced motion", mobile: true, reducedMotion: true, active: true },
50+
{ name: "panel motion off", mobile: true, active: false },
51+
{ name: "no view transition support", mobile: true, active: true, unsupported: true },
52+
])("applies the update before returning on $name", ({ unsupported, active, ...env }) => {
53+
const startViewTransition = vi.fn(deferredViewTransition());
54+
stubEnvironment({ ...env, ...(unsupported ? {} : { startViewTransition }) });
55+
const update = vi.fn();
56+
57+
const docking = runMobileComposerTransition(update, { active, durationMs: 200 });
58+
59+
expect(docking).toBeUndefined();
60+
expect(update).toHaveBeenCalledTimes(1);
61+
expect(startViewTransition).not.toHaveBeenCalled();
62+
});
63+
64+
it("applies the update once inside a mobile view transition and resolves after it", async () => {
65+
let finish!: () => void;
66+
const finished = new Promise<void>((resolve) => {
67+
finish = resolve;
68+
});
69+
const startViewTransition = vi.fn((update: () => void) => {
70+
void Promise.resolve().then(update);
71+
return { finished };
72+
});
73+
const root = stubEnvironment({ mobile: true, startViewTransition });
74+
const update = vi.fn();
75+
76+
const docking = runMobileComposerTransition(update, { active: true, durationMs: 200 });
77+
78+
expect(update).not.toHaveBeenCalled();
79+
expect(root.dataset.mobileComposerRouteTransition).toBe("true");
80+
expect(root.style.getPropertyValue("--mobile-composer-transition-duration")).toBe("200ms");
81+
await docking;
82+
expect(update).toHaveBeenCalledTimes(1);
83+
expect(root.dataset.mobileComposerRouteTransition).toBe("true");
84+
finish();
85+
await finished;
86+
expect(root.dataset.mobileComposerRouteTransition).toBeUndefined();
87+
expect(root.style.getPropertyValue("--mobile-composer-transition-duration")).toBe("");
88+
expect(update).toHaveBeenCalledTimes(1);
89+
});
90+
91+
it.each([
92+
{
93+
name: "the transition cannot start",
94+
startViewTransition: (): ReturnType<StartViewTransition> => {
95+
throw new Error("InvalidStateError");
96+
},
97+
update: vi.fn(),
98+
},
99+
{
100+
name: "the update throws",
101+
startViewTransition: deferredViewTransition(),
102+
update: vi.fn(() => {
103+
throw new Error("render failed");
104+
}),
105+
},
106+
{
107+
name: "an inline update throws",
108+
mobile: false,
109+
startViewTransition: deferredViewTransition(),
110+
update: vi.fn(() => {
111+
throw new Error("render failed");
112+
}),
113+
},
114+
])(
115+
"still releases the caller once when $name",
116+
async ({ mobile = true, startViewTransition, update }) => {
117+
stubEnvironment({ mobile, startViewTransition });
118+
119+
await runMobileComposerTransition(update, { active: true, durationMs: 200 });
120+
121+
expect(update).toHaveBeenCalledTimes(1);
122+
},
123+
);
124+
});

‎apps/web/src/components/chat/draftHeroTransition.ts‎

Lines changed: 45 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { flushSync } from "react-dom";
2+
13
export const DRAFT_HERO_TRANSITION_ANIMATION_ID = "t3-draft-hero-transition";
24
export const DRAFT_HERO_TRANSITION_EASING = "cubic-bezier(0.4, 0, 0.2, 1)";
35
export const MOBILE_COMPOSER_VIEW_TRANSITION_NAME = "t3-mobile-composer";
@@ -35,59 +37,73 @@ export async function waitForDraftHeroTransition(): Promise<void> {
3537
]);
3638
}
3739

38-
export async function runMobileComposerTransition(
39-
update: () => void | Promise<void>,
40+
// Only a mobile view transition flushes `update` (its new snapshot must show it) and returns a
41+
// promise; otherwise it runs inline so its state batches with the caller's. Errors never block.
42+
export function runMobileComposerTransition(
43+
update: () => void,
4044
options: { active: boolean; durationMs: number },
41-
): Promise<void> {
45+
): Promise<void> | undefined {
4246
if (typeof document === "undefined" || typeof window === "undefined") {
43-
await update();
47+
runInlineUpdate(update);
4448
return;
4549
}
4650

4751
const transitionDocument = document as ComposerViewTransitionDocument;
4852
const mobileViewport = window.matchMedia?.("(max-width: 639px)").matches ?? false;
4953
const prefersReducedMotion =
5054
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
51-
if (
52-
!options.active ||
53-
!mobileViewport ||
54-
prefersReducedMotion ||
55-
!transitionDocument.startViewTransition
56-
) {
57-
await update();
55+
const startViewTransition = transitionDocument.startViewTransition?.bind(transitionDocument);
56+
if (!options.active || !mobileViewport || prefersReducedMotion || !startViewTransition) {
57+
runInlineUpdate(update);
5858
return;
5959
}
6060

61-
let updateStarted = false;
62-
const runUpdate = async () => {
63-
if (updateStarted) return;
64-
updateStarted = true;
65-
await update();
66-
};
61+
return new Promise<void>((resolveUpdated) => {
62+
let updateStarted = false;
63+
const runUpdate = () => {
64+
if (updateStarted) return;
65+
updateStarted = true;
66+
try {
67+
flushSync(update);
68+
} finally {
69+
resolveUpdated();
70+
}
71+
};
72+
void runViewTransition(startViewTransition, runUpdate, options.durationMs);
73+
});
74+
}
75+
76+
function runInlineUpdate(update: () => void) {
77+
try {
78+
update();
79+
} catch {}
80+
}
81+
82+
async function runViewTransition(
83+
startViewTransition: (update: () => void) => ComposerViewTransition,
84+
runUpdate: () => void,
85+
durationMs: number,
86+
) {
87+
const root = document.documentElement;
6788
let transitionFinished: Promise<void> | null = null;
68-
transitionDocument.documentElement.style.setProperty(
69-
MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY,
70-
`${String(options.durationMs)}ms`,
71-
);
72-
transitionDocument.documentElement.dataset.mobileComposerRouteTransition = "true";
89+
root.style.setProperty(MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY, `${String(durationMs)}ms`);
90+
root.dataset.mobileComposerRouteTransition = "true";
7391
try {
74-
const transition = transitionDocument.startViewTransition(runUpdate);
92+
const transition = startViewTransition(runUpdate);
7593
transitionFinished = transition.finished.catch(() => undefined);
7694
activeMobileComposerTransition = transitionFinished;
7795
try {
7896
await transition.finished;
7997
} catch {
80-
await runUpdate();
98+
runInlineUpdate(runUpdate);
8199
}
82100
} catch {
83-
await runUpdate();
101+
runInlineUpdate(runUpdate);
84102
} finally {
85103
if (activeMobileComposerTransition === transitionFinished) {
86104
activeMobileComposerTransition = null;
87105
}
88-
delete transitionDocument.documentElement.dataset.mobileComposerRouteTransition;
89-
transitionDocument.documentElement.style.removeProperty(
90-
MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY,
91-
);
106+
delete root.dataset.mobileComposerRouteTransition;
107+
root.style.removeProperty(MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY);
92108
}
93109
}

‎apps/web/src/components/chat/useComposerSend.ts‎

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@ import {
4545
} from "@t3tools/client-runtime/environment";
4646
import { createModelSelection } from "@t3tools/shared/model";
4747
import { type SetStateAction, useLayoutEffect, useRef } from "react";
48-
import { flushSync } from "react-dom";
4948
import { useNavigate } from "@tanstack/react-router";
5049
import {
5150
isAtomCommandInterrupted,
@@ -905,25 +904,18 @@ export function useComposerSend(input: ComposerSendInput) {
905904
shouldDockDraftHeroForSubmission({ isDraftHeroState, activeThreadKey, submissionIntent }) &&
906905
activeThreadKey
907906
) {
908-
let resolveDockStarted: (() => void) | undefined;
909-
const dockStarted = new Promise<void>((resolve) => {
910-
resolveDockStarted = resolve;
911-
});
912-
const dockTransition = runMobileComposerTransition(
907+
const docking = runMobileComposerTransition(
913908
() => {
914-
flushSync(() => {
915-
captureDraftHeroComposerRect();
916-
setDockedDraftHeroThreadKey(activeThreadKey);
917-
});
918-
resolveDockStarted?.();
909+
captureDraftHeroComposerRect();
910+
setDockedDraftHeroThreadKey(activeThreadKey);
919911
},
920912
{
921913
active: panelAnimationsActive,
922914
durationMs: panelAnimationDurationMs,
923915
},
924916
);
925-
void dockTransition.catch(() => resolveDockStarted?.());
926-
await dockStarted;
917+
// Awaiting only a real transition keeps an inline dock in the same render as the send.
918+
if (docking) await docking;
927919
}
928920

929921
const attachmentCapabilitiesBeforeDispatch = readLiveAttachmentCapabilities();

0 commit comments

Comments
 (0)