Polish draft hero landing and mobile composer transition

- Add project selection guidance and disabled composer states
- Animate hero-to-docked composer handoff on mobile
- Cover mobile transition behavior with tests

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-07-18 00:16:15 +02:00
1 parent a07c32d2f4
commit 9274d0fb27
7 files changed
+485 -156

No files matched your search

+170 -96
View File
@@ -53,6 +53,7 @@ import {
useRef,
useState,
} from "react";
import { flushSync } from "react-dom";
import { useNavigate } from "@tanstack/react-router";
import { useShallow } from "zustand/react/shallow";
import {
@@ -217,6 +218,9 @@ import {
DRAFT_HERO_TRANSITION_ANIMATION_ID,
DRAFT_HERO_TRANSITION_DURATION_MS,
DRAFT_HERO_TRANSITION_EASING,
MOBILE_COMPOSER_CHROME_VIEW_TRANSITION_NAME,
MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,
runMobileComposerTransition,
} from "./chat/draftHeroTransition";
import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
@@ -263,44 +267,49 @@ const EMPTY_PROVIDERS: ServerProvider[] = [];
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
function useDraftHeroLayoutTransition(isDraftHeroState: boolean) {
const composerRef = useRef<HTMLDivElement | null>(null);
const lowerChromeRef = useRef<HTMLDivElement | null>(null);
const transitionGroupRef = useRef<HTMLDivElement | null>(null);
const composerAnchorRef = useRef<HTMLDivElement | null>(null);
const previousStateRef = useRef(isDraftHeroState);
const previousRectsRef = useRef<Array<DOMRect | null>>([null, null]);
const animationsRef = useRef<Animation[]>([]);
const attachComposerRef = (element: HTMLDivElement | null) => {
composerRef.current = element;
const previousComposerRectRef = useRef<DOMRect | null>(null);
const animationRef = useRef<Animation | null>(null);
const attachTransitionGroupRef = (element: HTMLDivElement | null) => {
transitionGroupRef.current = element;
};
const attachLowerChromeRef = (element: HTMLDivElement | null) => {
lowerChromeRef.current = element;
const attachComposerAnchorRef = (element: HTMLDivElement | null) => {
composerAnchorRef.current = element;
};
const captureComposerRect = () => {
previousComposerRectRef.current = composerAnchorRef.current?.getBoundingClientRect() ?? null;
};
useLayoutEffect(() => {
const elements = [composerRef.current, lowerChromeRef.current] as const;
const nextRects = elements.map((element) => element?.getBoundingClientRect() ?? null);
const transitionGroup = transitionGroupRef.current;
const nextComposerRect = composerAnchorRef.current?.getBoundingClientRect() ?? null;
const stateChanged = previousStateRef.current !== isDraftHeroState;
const prefersReducedMotion =
typeof window !== "undefined" &&
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
const mobileComposerTransitionActive =
typeof document !== "undefined" &&
document.documentElement.dataset.mobileComposerRouteTransition === "true";
animationsRef.current.forEach((animation) => animation.cancel());
animationsRef.current = [];
animationRef.current?.cancel();
animationRef.current = null;
if (stateChanged && !prefersReducedMotion) {
elements.forEach((element, index) => {
const previousRect = previousRectsRef.current[index];
const nextRect = nextRects[index];
if (!element || !previousRect || !nextRect || typeof element.animate !== "function") {
return;
}
const translateX = previousRect.left - nextRect.left;
const translateY = previousRect.top - nextRect.top;
if (Math.abs(translateX) < 0.5 && Math.abs(translateY) < 0.5) {
return;
}
const animation = element.animate(
const previousComposerRect = previousComposerRectRef.current;
if (
stateChanged &&
!prefersReducedMotion &&
!mobileComposerTransitionActive &&
transitionGroup &&
previousComposerRect &&
nextComposerRect &&
typeof transitionGroup.animate === "function"
) {
const translateX = previousComposerRect.left - nextComposerRect.left;
const translateY = previousComposerRect.top - nextComposerRect.top;
if (Math.abs(translateX) >= 0.5 || Math.abs(translateY) >= 0.5) {
const animation = transitionGroup.animate(
[
{ transform: `translate3d(${translateX}px, ${translateY}px, 0)` },
{ transform: "translate3d(0, 0, 0)" },
@@ -311,15 +320,23 @@ function useDraftHeroLayoutTransition(isDraftHeroState: boolean) {
},
);
animation.id = DRAFT_HERO_TRANSITION_ANIMATION_ID;
animationsRef.current.push(animation);
});
animationRef.current = animation;
void animation.finished
.catch(() => undefined)
.then(() => {
if (animationRef.current !== animation) {
return;
}
animationRef.current = null;
});
}
}
previousStateRef.current = isDraftHeroState;
previousRectsRef.current = nextRects;
previousComposerRectRef.current = nextComposerRect;
}, [isDraftHeroState]);
return [attachComposerRef, attachLowerChromeRef] as const;
return [attachTransitionGroupRef, attachComposerAnchorRef, captureComposerRect] as const;
}
const PreviewPanel = lazy(() =>
import("./preview/PreviewPanel").then((module) => ({ default: module.PreviewPanel })),
@@ -404,6 +421,7 @@ type ChatViewProps =
threadId: ThreadId;
onDiffPanelOpen?: () => void;
reserveTitleBarControlInset?: boolean;
forceExpandedMobileComposer?: boolean;
routeKind: "server";
draftId?: never;
}
@@ -412,6 +430,7 @@ type ChatViewProps =
threadId: ThreadId;
onDiffPanelOpen?: () => void;
reserveTitleBarControlInset?: boolean;
forceExpandedMobileComposer?: boolean;
routeKind: "draft";
draftId: DraftId;
};
@@ -1051,6 +1070,7 @@ function ChatViewContent(props: ChatViewProps) {
routeKind,
onDiffPanelOpen,
reserveTitleBarControlInset = true,
forceExpandedMobileComposer = false,
} = props;
const draftId = routeKind === "draft" ? props.draftId : null;
const routeThreadRef = useMemo(
@@ -2128,9 +2148,16 @@ function ChatViewContent(props: ChatViewProps) {
deriveTimelineEntries(timelineMessages, activeThread?.proposedPlans ?? [], workLogEntries),
[activeThread?.proposedPlans, timelineMessages, workLogEntries],
);
const isDraftHeroState = isLocalDraftThread && timelineEntries.length === 0 && !isWorking;
const [attachDraftHeroComposerRef, attachDraftHeroLowerChromeRef] =
useDraftHeroLayoutTransition(isDraftHeroState);
const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState<string | null>(null);
const draftHeroDockRequested =
activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey;
const isDraftHeroState =
isLocalDraftThread && timelineEntries.length === 0 && !isWorking && !draftHeroDockRequested;
const [
attachDraftHeroTransitionGroupRef,
attachDraftHeroComposerAnchorRef,
captureDraftHeroComposerRect,
] = useDraftHeroLayoutTransition(isDraftHeroState);
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const turnDiffSummaryByAssistantMessageId = useMemo(() => {
@@ -4031,7 +4058,16 @@ function ChatViewContent(props: ChatViewProps) {
}
return;
}
if (!activeProject) return;
if (!activeProject) {
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Choose a project first",
description: "This draft no longer points to an available project.",
}),
);
return;
}
const threadIdForSend = activeThread.id;
const isFirstMessage = !isServerThread || activeThread.messages.length === 0;
const baseBranchForWorktree =
@@ -4048,6 +4084,21 @@ function ChatViewContent(props: ChatViewProps) {
return;
}
if (isDraftHeroState && activeThreadKey) {
let resolveDockStarted: (() => void) | undefined;
const dockStarted = new Promise<void>((resolve) => {
resolveDockStarted = resolve;
});
const dockTransition = runMobileComposerTransition(() => {
flushSync(() => {
captureDraftHeroComposerRect();
setDockedDraftHeroThreadKey(activeThreadKey);
});
resolveDockStarted?.();
});
void dockTransition.catch(() => resolveDockStarted?.());
await dockStarted;
}
sendInFlightRef.current = true;
beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) });
@@ -4302,6 +4353,9 @@ function ChatViewContent(props: ChatViewProps) {
}
sendInFlightRef.current = false;
if (!turnStartSucceeded) {
setDockedDraftHeroThreadKey((currentThreadKey) =>
currentThreadKey === activeThreadKey ? null : currentThreadKey,
);
resetLocalDispatch();
}
};
@@ -5198,24 +5252,11 @@ function ChatViewContent(props: ChatViewProps) {
data-chat-composer-overlay="true"
className={
isDraftHeroState
? "pointer-events-none absolute inset-0 z-20 flex flex-col pt-1.5 sm:pt-2"
? "pointer-events-none absolute inset-0 z-20 flex items-center"
: "pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2"
}
>
{/* Equal flexible spacers keep the hero group vertically stable:
whatever mounts below (branch toolbar, banners) grows into the
bottom spacer instead of re-centering the headline. */}
{isDraftHeroState ? (
<div key="draft-hero-top-spacer" className="min-h-0 flex-1 basis-0" />
) : null}
{isDraftHeroState ? (
<div key="draft-hero-headline" className="chat-composer-horizontal-inset pb-8">
<DraftHeroHeadline
activeProjectRef={activeProjectRef}
activeProjectTitle={activeProject?.title ?? null}
/>
</div>
) : (
{!isDraftHeroState ? (
<div
key="docked-composer-blur"
aria-hidden="true"
@@ -5225,15 +5266,38 @@ function ChatViewContent(props: ChatViewProps) {
<div className="chat-composer-shared-blur absolute -inset-8" />
</div>
</div>
)}
) : null}
<div
key="chat-composer"
ref={attachDraftHeroComposerRef}
className="chat-composer-horizontal-inset"
ref={attachDraftHeroTransitionGroupRef}
className="chat-composer-horizontal-inset w-full"
>
<div className="pointer-events-auto relative z-10 isolate">
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
<div className="relative z-10">
{isDraftHeroState ? (
<div className="absolute inset-x-0 bottom-full z-0">
<div
className="pb-8"
style={
forceExpandedMobileComposer
? {
viewTransitionName: MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,
}
: undefined
}
>
<DraftHeroHeadline
activeProjectRef={activeProjectRef}
activeProjectTitle={activeProject?.title ?? null}
/>
</div>
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
</div>
) : (
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
)}
<div
ref={attachDraftHeroComposerAnchorRef}
className="relative z-10 mx-auto w-full max-w-3xl"
>
<ChatComposer
composerRef={composerRef}
composerDraftTarget={composerDraftTarget}
@@ -5246,6 +5310,8 @@ function ChatViewContent(props: ChatViewProps) {
activeThread={activeThread}
isServerThread={isServerThread}
isLocalDraftThread={isLocalDraftThread}
forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}
projectSelectionRequired={isLocalDraftThread && activeProject === null}
phase={phase}
isConnecting={isConnecting}
isSendBusy={isSendBusy}
@@ -5306,49 +5372,57 @@ function ChatViewContent(props: ChatViewProps) {
onExpandImage={onExpandTimelineImage}
/>
</div>
</div>
</div>
<div
key="composer-lower-chrome"
ref={attachDraftHeroLowerChromeRef}
className={cn("flex min-h-0 flex-col", isDraftHeroState ? "flex-1 basis-0" : null)}
>
<div
className={cn(
"chat-composer-horizontal-inset chat-composer-lower-chrome relative z-10",
isGitRepo
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
)}
>
{isGitRepo && (
<div className="pointer-events-auto">
<BranchToolbar
environmentId={activeThread.environmentId}
threadId={activeThread.id}
{...(routeKind === "draft" && draftId ? { draftId } : {})}
onEnvModeChange={onEnvModeChange}
startFromOrigin={startFromOrigin}
onStartFromOriginChange={onStartFromOriginChange}
{...(canOverrideServerThreadEnvMode
? { effectiveEnvModeOverride: envMode }
: {})}
{...(canOverrideServerThreadEnvMode
<div
className={cn(
"min-h-0",
isDraftHeroState ? "absolute inset-x-0 top-full" : null,
)}
>
<div
className={cn(
"chat-composer-lower-chrome relative z-10",
isGitRepo
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
)}
style={
forceExpandedMobileComposer
? {
activeThreadBranchOverride: activeThreadBranch,
onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
viewTransitionName: MOBILE_COMPOSER_CHROME_VIEW_TRANSITION_NAME,
}
: {})}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
{...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {})}
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
availableEnvironments={logicalProjectEnvironments}
/>
: undefined
}
>
{isGitRepo && (
<div className="pointer-events-auto">
<BranchToolbar
environmentId={activeThread.environmentId}
threadId={activeThread.id}
{...(routeKind === "draft" && draftId ? { draftId } : {})}
onEnvModeChange={onEnvModeChange}
startFromOrigin={startFromOrigin}
onStartFromOriginChange={onStartFromOriginChange}
{...(canOverrideServerThreadEnvMode
? { effectiveEnvModeOverride: envMode }
: {})}
{...(canOverrideServerThreadEnvMode
? {
activeThreadBranchOverride: activeThreadBranch,
onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
}
: {})}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
{...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {})}
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
availableEnvironments={logicalProjectEnvironments}
/>
</div>
)}
</div>
)}
</div>
</div>
</div>
</div>
+38 -14
View File
@@ -77,6 +77,7 @@ import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
import { searchSlashCommandItems } from "./composerSlashCommandSearch";
import { MOBILE_COMPOSER_VIEW_TRANSITION_NAME } from "./draftHeroTransition";
import {
getComposerPromptInjectionState,
getComposerProviderState,
@@ -441,6 +442,8 @@ export interface ChatComposerProps {
activeThread: Thread | undefined;
isServerThread: boolean;
isLocalDraftThread: boolean;
forceExpandedOnMobile: boolean;
projectSelectionRequired: boolean;
// Session phase
phase: SessionPhase;
@@ -552,6 +555,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
activeThread,
isServerThread: _isServerThread,
isLocalDraftThread: _isLocalDraftThread,
forceExpandedOnMobile,
projectSelectionRequired,
phase,
isConnecting,
isSendBusy,
@@ -882,7 +887,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);
const [isComposerFocused, setIsComposerFocused] = useState(false);
const isMobileViewport = useMediaQuery("max-sm");
const isComposerCollapsedMobile = isMobileViewport && !isComposerFocused;
const isComposerCollapsedMobile =
isMobileViewport && !forceExpandedOnMobile && !isComposerFocused;
// ------------------------------------------------------------------
// Refs
@@ -1135,7 +1141,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
[activePendingIsResponding, activePendingProgress, activePendingResolvedAnswers],
);
const collapsedComposerPrimaryActionDisabled =
phase === "running" || isSendBusy || isConnecting || !composerSendState.hasSendableContent;
phase === "running" ||
isSendBusy ||
isConnecting ||
projectSelectionRequired ||
!composerSendState.hasSendableContent;
const collapsedComposerPrimaryActionLabel = "Send message";
const showMobilePendingAnswerActions =
isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null;
@@ -1924,6 +1934,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isConnecting ||
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
) {
return false;
@@ -2024,6 +2035,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isConnecting,
isComposerApprovalState,
pendingUserInputs.length,
projectSelectionRequired,
environmentUnavailable,
activePendingProgress,
applyPromptReplacement,
@@ -2046,6 +2058,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
onSubmit={submitComposer}
className="mx-auto w-full min-w-0 max-w-3xl"
data-chat-composer-form="true"
style={
isMobileViewport ? { viewTransitionName: MOBILE_COMPOSER_VIEW_TRANSITION_NAME } : undefined
}
>
<div
className={cn(
@@ -2061,9 +2076,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
ref={composerSurfaceRef}
data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}
className={cn(
"chat-composer-glass rounded-[20px] border transition-colors duration-200 has-focus-visible:border-ring/45",
"chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-ring/45",
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
environmentUnavailable ? "opacity-75" : null,
environmentUnavailable || projectSelectionRequired ? "opacity-75" : null,
composerProviderState.composerSurfaceClassName,
)}
onFocusCapture={(event) => {
@@ -2175,7 +2190,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
promptHasText={false}
isSendBusy={isSendBusy}
isConnecting={isConnecting}
isEnvironmentUnavailable={environmentUnavailable !== null}
isEnvironmentUnavailable={
environmentUnavailable !== null || projectSelectionRequired
}
isPreparingWorktree={false}
hasSendableContent={false}
preserveComposerFocusOnPointerDown
@@ -2409,17 +2426,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? "Type your own answer, or leave this blank to use the selected option"
: showPlanFollowUpPrompt && activeProposedPlan
? "Add feedback to refine the plan, or leave this blank to implement it"
: environmentUnavailable
? `${environmentUnavailable.label}: ${connectionStatusText(
environmentUnavailable.connection,
)}`
: phase === "disconnected"
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, $use skills, or / for commands"
: projectSelectionRequired
? "Choose a project above to start a thread"
: environmentUnavailable
? `${environmentUnavailable.label}: ${connectionStatusText(
environmentUnavailable.connection,
)}`
: phase === "disconnected"
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, $use skills, or / for commands"
}
disabled={
isConnecting ||
isComposerApprovalState ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
}
/>
@@ -2436,7 +2456,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
promptHasText={false}
isSendBusy={isSendBusy}
isConnecting={isConnecting}
isEnvironmentUnavailable={environmentUnavailable !== null}
isEnvironmentUnavailable={
environmentUnavailable !== null || projectSelectionRequired
}
isPreparingWorktree={false}
hasSendableContent={false}
preserveComposerFocusOnPointerDown
@@ -2547,7 +2569,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
promptHasText={prompt.trim().length > 0}
isSendBusy={isSendBusy}
isConnecting={isConnecting}
isEnvironmentUnavailable={environmentUnavailable !== null}
isEnvironmentUnavailable={
environmentUnavailable !== null || projectSelectionRequired
}
isPreparingWorktree={isPreparingWorktree}
hasSendableContent={composerSendState.hasSendableContent}
preserveComposerFocusOnPointerDown={isMobileViewport}
@@ -1,12 +1,21 @@
import type { ScopedProjectRef } from "@t3tools/contracts";
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
import { ChevronDownIcon } from "lucide-react";
import { FolderPlusIcon } from "lucide-react";
import { useMemo } from "react";
import { useOpenAddProjectCommandPalette } from "~/commandPaletteContext";
import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
import { useProjects, useThreadShells } from "~/state/entities";
import { sortProjectsForSidebar } from "../Sidebar.logic";
import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../ui/menu";
import {
Menu,
MenuItem,
MenuPopup,
MenuRadioGroup,
MenuRadioItem,
MenuSeparator,
MenuTrigger,
} from "../ui/menu";
interface DraftHeroHeadlineProps {
readonly activeProjectRef: ScopedProjectRef | null;
@@ -20,6 +29,7 @@ export function DraftHeroHeadline({
const projects = useProjects();
const threads = useThreadShells();
const handleNewThread = useNewThreadHandler();
const openAddProject = useOpenAddProjectCommandPalette();
const orderedProjects = useMemo(
() => sortProjectsForSidebar(projects, threads, "updated_at"),
@@ -39,50 +49,60 @@ export function DraftHeroHeadline({
[orderedProjects],
);
const activeProjectKey = activeProjectRef === null ? "" : scopedProjectKey(activeProjectRef);
const hasResolvedProject = activeProjectTitle !== null;
const canChooseProject = orderedProjects.length > 0;
const shouldShowProjectMenu = canChooseProject;
const projectSelector = shouldShowProjectMenu ? (
<Menu>
<MenuTrigger
aria-label={hasResolvedProject ? "Change project" : "Choose a project"}
className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-foreground underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
>
{activeProjectTitle ?? "Choose a project"}
</MenuTrigger>
<MenuPopup align="center" className="max-h-80 w-64 overflow-y-auto">
<MenuRadioGroup
value={activeProjectKey}
onValueChange={(value) => {
const project = projectByKey.get(value as string);
if (!project || value === activeProjectKey) {
return;
}
void handleNewThread(scopeProjectRef(project.environmentId, project.id), {
replace: true,
});
}}
>
{orderedProjects.map((project) => {
const key = scopedProjectKey(scopeProjectRef(project.environmentId, project.id));
return (
<MenuRadioItem key={key} value={key} closeOnClick>
<span className="min-w-0 truncate">{project.title}</span>
</MenuRadioItem>
);
})}
</MenuRadioGroup>
<MenuSeparator />
<MenuItem onClick={openAddProject}>
<FolderPlusIcon />
New project
</MenuItem>
</MenuPopup>
</Menu>
) : (
<span className="text-muted-foreground/60">{activeProjectTitle ?? "Add a project"}</span>
);
const projectLabel = activeProjectTitle ?? "this project";
return (
<h1 className="mx-auto w-full max-w-3xl text-center font-semibold text-2xl text-foreground sm:text-3xl">
What should we do in{" "}
{orderedProjects.length > 1 ? (
<Menu>
<MenuTrigger className="pointer-events-auto inline-flex cursor-pointer items-baseline gap-1.5 rounded-md text-muted-foreground/60 transition-colors hover:text-foreground/80 focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring">
{projectLabel}
<span
aria-hidden="true"
className="mr-1.5 flex size-4 shrink-0 items-center justify-center self-center rounded-full bg-muted-foreground/12 sm:size-5"
>
<ChevronDownIcon className="size-2.5 sm:size-3" />
</span>
</MenuTrigger>
<MenuPopup align="center" className="max-h-80 w-64 overflow-y-auto">
<MenuRadioGroup
value={activeProjectKey}
onValueChange={(value) => {
const project = projectByKey.get(value as string);
if (!project || value === activeProjectKey) {
return;
}
void handleNewThread(scopeProjectRef(project.environmentId, project.id), {
replace: true,
});
}}
>
{orderedProjects.map((project) => {
const key = scopedProjectKey(scopeProjectRef(project.environmentId, project.id));
return (
<MenuRadioItem key={key} value={key} closeOnClick>
<span className="min-w-0 truncate">{project.title}</span>
</MenuRadioItem>
);
})}
</MenuRadioGroup>
</MenuPopup>
</Menu>
<h1 className="mx-auto w-full max-w-5xl text-center font-normal text-3xl text-foreground tracking-tight sm:text-5xl">
{hasResolvedProject ? (
<>What should we build in {projectSelector}?</>
) : canChooseProject ? (
<>{projectSelector} to start</>
) : (
<span className="text-muted-foreground/60">{projectLabel}</span>
<>Add a project to start</>
)}
?
</h1>
);
}
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import {
DRAFT_HERO_TRANSITION_ANIMATION_ID,
runMobileComposerTransition,
waitForDraftHeroTransition,
} from "./draftHeroTransition";
@@ -47,3 +48,76 @@ describe("waitForDraftHeroTransition", () => {
await expect(waitForDraftHeroTransition()).resolves.toBeUndefined();
});
});
describe("runMobileComposerTransition", () => {
it("keeps the route handoff waiting while the mobile composer morph is active", async () => {
let finishTransition: (() => void) | undefined;
const transitionFinished = new Promise<void>((resolve) => {
finishTransition = resolve;
});
const dataset: Record<string, string> = {};
vi.stubGlobal("document", {
documentElement: { dataset },
getAnimations: () => [],
startViewTransition: (update: () => void | Promise<void>) => {
void update();
return { finished: transitionFinished };
},
});
vi.stubGlobal("window", {
matchMedia: (query: string) => ({ matches: query === "(max-width: 639px)" }),
});
const transition = runMobileComposerTransition(() => undefined);
await Promise.resolve();
let handoffComplete = false;
const handoff = waitForDraftHeroTransition().then(() => {
handoffComplete = true;
});
await Promise.resolve();
expect(handoffComplete).toBe(false);
finishTransition?.();
await Promise.all([transition, handoff]);
expect(handoffComplete).toBe(true);
});
it("uses a scoped view transition on mobile", async () => {
const dataset: Record<string, string> = {};
const startViewTransition = vi.fn((update: () => void | Promise<void>) => ({
finished: Promise.resolve(update()).then(() => undefined),
}));
vi.stubGlobal("document", {
documentElement: { dataset },
startViewTransition,
});
vi.stubGlobal("window", {
matchMedia: (query: string) => ({ matches: query === "(max-width: 639px)" }),
});
const update = vi.fn();
await runMobileComposerTransition(update);
expect(startViewTransition).toHaveBeenCalledOnce();
expect(update).toHaveBeenCalledOnce();
expect(dataset).not.toHaveProperty("mobileComposerRouteTransition");
});
it("updates without a view transition when reduced motion is preferred", async () => {
const startViewTransition = vi.fn();
vi.stubGlobal("document", {
documentElement: { dataset: {} },
startViewTransition,
});
vi.stubGlobal("window", {
matchMedia: () => ({ matches: true }),
});
const update = vi.fn();
await runMobileComposerTransition(update);
expect(startViewTransition).not.toHaveBeenCalled();
expect(update).toHaveBeenCalledOnce();
});
});
@@ -1,9 +1,24 @@
export const DRAFT_HERO_TRANSITION_ANIMATION_ID = "t3-draft-hero-transition";
export const DRAFT_HERO_TRANSITION_DURATION_MS = 180;
export const DRAFT_HERO_TRANSITION_EASING = "cubic-bezier(0.2, 0, 0, 1)";
export const DRAFT_HERO_TRANSITION_EASING = "cubic-bezier(0.16, 1, 0.3, 1)";
export const MOBILE_COMPOSER_VIEW_TRANSITION_NAME = "t3-mobile-composer";
export const MOBILE_COMPOSER_CHROME_VIEW_TRANSITION_NAME = "t3-mobile-composer-chrome";
export const MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME = "t3-mobile-draft-headline";
type ComposerViewTransition = {
readonly finished: Promise<void>;
};
let activeMobileComposerTransition: Promise<void> | null = null;
type ComposerViewTransitionDocument = Document & {
startViewTransition?: (update: () => void | Promise<void>) => ComposerViewTransition;
};
export async function waitForDraftHeroTransition(): Promise<void> {
const mobileComposerTransition = activeMobileComposerTransition;
if (typeof document === "undefined" || typeof document.getAnimations !== "function") {
await mobileComposerTransition;
return;
}
@@ -11,13 +26,58 @@ export async function waitForDraftHeroTransition(): Promise<void> {
.getAnimations()
.filter((animation) => animation.id === DRAFT_HERO_TRANSITION_ANIMATION_ID);
await Promise.all(
activeTransitions.map(async (animation) => {
await Promise.all([
mobileComposerTransition,
...activeTransitions.map(async (animation) => {
try {
await animation.finished;
} catch {
// A cancelled transition is already safe to hand off.
}
}),
);
]);
}
export async function runMobileComposerTransition(
update: () => void | Promise<void>,
): Promise<void> {
if (typeof document === "undefined" || typeof window === "undefined") {
await update();
return;
}
const transitionDocument = document as ComposerViewTransitionDocument;
const mobileViewport = window.matchMedia?.("(max-width: 639px)").matches ?? false;
const prefersReducedMotion =
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
if (!mobileViewport || prefersReducedMotion || !transitionDocument.startViewTransition) {
await update();
return;
}
let updateStarted = false;
const runUpdate = async () => {
if (updateStarted) return;
updateStarted = true;
await update();
};
let transitionFinished: Promise<void> | null = null;
transitionDocument.documentElement.dataset.mobileComposerRouteTransition = "true";
try {
const transition = transitionDocument.startViewTransition(runUpdate);
transitionFinished = transition.finished.catch(() => undefined);
activeMobileComposerTransition = transitionFinished;
try {
await transition.finished;
} catch {
await runUpdate();
}
} catch {
await runUpdate();
} finally {
if (activeMobileComposerTransition === transitionFinished) {
activeMobileComposerTransition = null;
}
delete transitionDocument.documentElement.dataset.mobileComposerRouteTransition;
}
}
+75
View File
@@ -4,6 +4,81 @@
/* Window Controls Overlay: active when Electron exposes native titlebar control geometry. */
@custom-variant wco (&:is(.wco, .wco *));
/* On mobile, morph the expanded hero composer into the compact docked
composer while it moves; the rest of the app remains visually stationary. */
html[data-mobile-composer-route-transition="true"]::view-transition-old(root),
html[data-mobile-composer-route-transition="true"]::view-transition-new(root) {
animation: none;
}
html[data-mobile-composer-route-transition="true"]::view-transition-group(t3-mobile-composer),
html[data-mobile-composer-route-transition="true"]::view-transition-group(t3-mobile-composer-chrome) {
animation-duration: 180ms;
animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}
html[data-mobile-composer-route-transition="true"]::view-transition-image-pair(t3-mobile-composer),
html[data-mobile-composer-route-transition="true"]::view-transition-image-pair(t3-mobile-composer-chrome) {
isolation: isolate;
}
html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobile-composer),
html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobile-composer-chrome) {
animation: t3-mobile-composer-old 180ms linear both;
mix-blend-mode: normal;
}
html[data-mobile-composer-route-transition="true"]::view-transition-new(t3-mobile-composer),
html[data-mobile-composer-route-transition="true"]::view-transition-new(t3-mobile-composer-chrome) {
animation: t3-mobile-composer-new 180ms linear both;
mix-blend-mode: normal;
}
/* The expanded and compact composers have different internal layouts. Keep
one snapshot visible at a time so their controls cannot ghost over each
other while the shared geometry continues moving and resizing. */
@keyframes t3-mobile-composer-old {
0%,
54.99% {
opacity: 1;
}
55%,
100% {
opacity: 0;
}
}
@keyframes t3-mobile-composer-new {
0%,
54.99% {
opacity: 0;
}
55%,
100% {
opacity: 1;
}
}
html[data-mobile-composer-route-transition="true"]::view-transition-group(t3-mobile-draft-headline) {
animation-duration: 130ms;
}
html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobile-draft-headline) {
animation: t3-mobile-draft-headline-exit 130ms cubic-bezier(0.4, 0, 1, 1) both;
mix-blend-mode: normal;
}
@keyframes t3-mobile-draft-headline-exit {
from {
opacity: 1;
transform: translateY(0);
}
to {
opacity: 0;
transform: translateY(-6px);
}
}
:root {
--app-scrollbar-width: 6px;
--workspace-topbar-height: 52px;
@@ -73,6 +73,7 @@ function DraftChatThreadRouteView() {
environmentId={canonicalThreadRef.environmentId}
threadId={canonicalThreadRef.threadId}
routeKind="server"
forceExpandedMobileComposer
/>
</SidebarInset>
);
@@ -89,6 +90,7 @@ function DraftChatThreadRouteView() {
environmentId={draftSession.environmentId}
threadId={draftSession.threadId}
routeKind="draft"
forceExpandedMobileComposer
/>
</SidebarInset>
);