diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index 0ee6b9a0c7cc1..eb38737350bf3 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -333,7 +333,7 @@ describe("composer context undo lifetime", () => { }); } - it("restores a deleted chip and its file bytes on same-draft undo, then releases them on unmount", async () => { + it("restores a deleted chip and its file bytes on same-draft undo", async () => { await using composer = await mountComposer(); await composer.deleteDraft(); expect(composer.draft()).toEqual({ value: "", files: [] }); @@ -345,14 +345,10 @@ describe("composer context undo lifetime", () => { expect(serializeEditorDoc(composer.editor().state.doc).value).toBe(composer.initialValue); expect(composer.draft()).toEqual({ value: composer.initialValue, files: [file] }); expect(composer.draft().files[0]?.file).toBe(file.file); - - await composer.deleteDraft(); - await composer.unmount(); - expect(retained.files.size).toBe(0); }); it.each(["", "Draft B"])( - "releases deleted payloads and prevents undo into the previous draft when switching to %j", + "drops deleted payloads and prevents undo into the previous draft when switching to %j", async (destinationValue) => { await using composer = await mountComposer(destinationValue); await composer.deleteDraft(); @@ -361,7 +357,8 @@ describe("composer context undo lifetime", () => { expect(retained.files.get(fileContextReference(file).contextId)?.file).toBe(file.file); await composer.show("b"); - expect(retained.files.size).toBe(0); + expect(composer.retained()).not.toBe(retained); + expect(composer.retained().files.size).toBe(0); await composer.undo(); expect(serializeEditorDoc(composer.editor().state.doc).value).toBe(destinationValue); expect(composer.draft()).toEqual({ value: destinationValue, files: [] }); diff --git a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx index 1b2f572dfbd20..1471c4dcd6800 100644 --- a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx +++ b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx @@ -7,7 +7,7 @@ import type { } from "@t3tools/contracts"; import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { CircleAlertIcon, PaperclipIcon, PlayIcon, XIcon } from "lucide-react"; -import { type ComponentProps, useLayoutEffect, useRef } from "react"; +import { type ComponentProps, useRef } from "react"; import { type ComposerFileAttachment, @@ -79,22 +79,16 @@ function SnapShotAttachmentFrame({ readonly arrival?: boolean | undefined; readonly animateArrival?: boolean | undefined; }) { - const frameRef = useRef(null); - - useLayoutEffect(() => { - const frame = frameRef.current; - if (!frame || (!animationId && !arrival)) return; - frame.scrollIntoView({ block: "nearest", inline: "nearest" }); - if (!animationId) return; - - return scheduleSnapShotAnimationDestination(animationId, () => - setSnapShotAnimationDestination(animationId, frame, animationSource), - ); - }, [animationId, animationSource, arrival]); - return (
{ + if (!frame || (!animationId && !arrival)) return; + frame.scrollIntoView({ block: "nearest", inline: "nearest" }); + if (!animationId) return; + return scheduleSnapShotAnimationDestination(animationId, () => + setSnapShotAnimationDestination(animationId, frame, animationSource), + ); + }} className={cn( animateArrival && !animationId && diff --git a/apps/web/src/components/chat/ComposerBannerStack.tsx b/apps/web/src/components/chat/ComposerBannerStack.tsx index 530415424a5c0..0d5a7e6e3ab34 100644 --- a/apps/web/src/components/chat/ComposerBannerStack.tsx +++ b/apps/web/src/components/chat/ComposerBannerStack.tsx @@ -1,5 +1,6 @@ import { InfoIcon } from "lucide-react"; -import { useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from "react"; +import { useId, useRef, useState, type ReactNode } from "react"; +import { flushSync } from "react-dom"; import { cn } from "~/lib/utils"; import { Button } from "../ui/button"; @@ -51,39 +52,25 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose const noticesRef = useRef(null); const peekRef = useRef(null); const expandedItemsRef = useRef(null); - const pendingFocusRef = useRef<"peek" | "notice" | null>(null); const expandedItemsId = useId(); const [requestedExitingItemId, setExitingItemId] = useState(null); - const dismissTimeoutRef = useRef | null>(null); const exitingItemId = requestedExitingItemId !== null && items.some((item) => item.id === requestedExitingItemId) ? requestedExitingItemId : null; - useEffect(() => { - return () => { - if (dismissTimeoutRef.current) { - clearTimeout(dismissTimeoutRef.current); - } - }; - }, []); - if (items.length < 2 && stackExpanded) { setStackExpanded(false); } - useLayoutEffect(() => { - if (stackExpanded && pendingFocusRef.current === "notice") { - pendingFocusRef.current = null; - const firstControl = expandedItemsRef.current?.querySelector( - 'button:not(:disabled), a[href], input:not(:disabled), [tabindex="0"]', - ); - (firstControl ?? expandedItemsRef.current)?.focus({ preventScroll: true }); - } else if (!stackExpanded && pendingFocusRef.current === "peek") { - pendingFocusRef.current = null; - peekRef.current?.focus({ preventScroll: true }); - } - }, [stackExpanded]); + const expandAndFocusNotice = () => { + flushSync(() => setStackExpanded(true)); + const container = expandedItemsRef.current; + const firstControl = container?.querySelector( + 'button:not(:disabled), a[href], input:not(:disabled), [tabindex="0"]', + ); + (firstControl ?? container)?.focus({ preventScroll: true }); + }; const orderedItems = items.toSorted((a, b) => bannerPriority(a) - bannerPriority(b)); const frontItem = orderedItems[0]; @@ -106,13 +93,9 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose return; } setExitingItemId(item.id); - if (dismissTimeoutRef.current) { - clearTimeout(dismissTimeoutRef.current); - } - dismissTimeoutRef.current = setTimeout(() => { - dismissTimeoutRef.current = null; - item.onDismiss?.(); - }, DISMISS_TRANSITION_MS); + // A timer, not transitionend: the dismissal must commit even when the stack unmounts + // (thread switch) or a collapsed composer hides it mid-exit, and transitionend never fires then. + setTimeout(() => item.onDismiss?.(), DISMISS_TRANSITION_MS); }; return ( @@ -126,7 +109,8 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose onPointerEnter={(event) => { if (event.pointerType === "touch") return; if (document.activeElement === peekRef.current) { - pendingFocusRef.current = "notice"; + expandAndFocusNotice(); + return; } setStackExpanded(true); }} @@ -145,8 +129,8 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose if (event.key !== "Escape" || !stackExpanded) return; event.preventDefault(); event.stopPropagation(); - pendingFocusRef.current = "peek"; - setStackExpanded(false); + flushSync(() => setStackExpanded(false)); + peekRef.current?.focus({ preventScroll: true }); }} > {showCollapsedStackCap && firstStackedItem ? ( @@ -160,8 +144,7 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose tabIndex={stackExpanded ? -1 : 0} onClick={(event) => { event.currentTarget.focus({ preventScroll: true }); - pendingFocusRef.current = "notice"; - setStackExpanded(true); + expandAndFocusNotice(); }} className={cn(stackExpanded && "pointer-events-none invisible opacity-0")} /> @@ -257,12 +240,10 @@ function NoticeText({ readonly className: string; readonly detailsLabel: string; }) { - const textRef = useRef(null); const detailsRef = useRef(null); const [showDetails, setShowDetails] = useState(false); - useLayoutEffect(() => { - const text = textRef.current; + const observeOverflow = (text: HTMLSpanElement | null) => { if (!text) return; const measure = () => { // Ignore the space taken by the details button itself so it cannot @@ -284,11 +265,11 @@ function NoticeText({ stopObserving(); mutations.disconnect(); }; - }, []); + }; return ( - + {children} {showDetails ? ( diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx index 4d556d48be701..24da284dc9837 100644 --- a/apps/web/src/components/chat/ComposerCommandMenu.tsx +++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx @@ -21,7 +21,7 @@ import { UserRoundIcon, type LucideIcon, } from "lucide-react"; -import { memo, useLayoutEffect, useRef } from "react"; +import { memo } from "react"; import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic"; import { cn } from "~/lib/utils"; @@ -90,16 +90,6 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: { onHighlightedItemChange: (itemId: string | null) => void; onSelect: (item: ComposerCommandItem) => void; }) { - const listRef = useRef(null); - - useLayoutEffect(() => { - if (!props.activeItemId || !listRef.current) return; - const el = listRef.current.querySelector( - `[data-composer-item-id="${CSS.escape(props.activeItemId)}"]`, - ); - el?.scrollIntoView({ block: "nearest" }); - }, [props.activeItemId]); - return ( @@ -159,6 +148,10 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: { ); }); +function scrollActiveRowIntoView(row: HTMLElement | null) { + row?.scrollIntoView({ block: "nearest" }); +} + const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: { optionId: string; item: ComposerCommandItem; @@ -181,6 +174,7 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: { aria-selected={props.isActive} value={props.item.id} data-composer-item-id={props.item.id} + ref={props.isActive ? scrollActiveRowIntoView : undefined} active={props.isActive} onMouseMove={() => { if (!props.isActive) props.onHighlight(props.item.id); diff --git a/apps/web/src/components/chat/ComposerImageThumbnail.tsx b/apps/web/src/components/chat/ComposerImageThumbnail.tsx index 31fff763a6772..e9de2aa93b302 100644 --- a/apps/web/src/components/chat/ComposerImageThumbnail.tsx +++ b/apps/web/src/components/chat/ComposerImageThumbnail.tsx @@ -1,11 +1,24 @@ -import { memo, useEffect, useState, type ReactNode } from "react"; +import { memo, Suspense, use, type ReactNode } from "react"; import { createComposerImageThumbnail, readComposerImageThumbnail, } from "../../lib/imageCompression"; -export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({ +export const ComposerImageThumbnail = memo(function ComposerImageThumbnail(props: { + file: File; + alt: string; + className: string; + fallback: ReactNode; +}) { + return ( + + + + ); +}); + +function ThumbnailImage({ file, alt, className, @@ -16,16 +29,8 @@ export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({ className: string; fallback: ReactNode; }) { - const [preview, setPreview] = useState<{ file: File; src: string | null } | null>(null); - useEffect(() => { - let active = true; - void createComposerImageThumbnail(file).then((src) => { - if (active) setPreview({ file, src }); - }); - return () => { - active = false; - }; - }, [file]); - const src = preview?.file === file ? preview.src : (readComposerImageThumbnail(file) ?? null); + // A settled thumbnail paints synchronously instead of suspending for a tick. + const settled = readComposerImageThumbnail(file); + const src = settled === undefined ? use(createComposerImageThumbnail(file)) : settled; return src ? {alt} : fallback; -}); +} diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx index 99f80d8e50813..b0b096eeceb92 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx @@ -1,6 +1,6 @@ import { type RuntimeRequestId, type ScopedThreadRef } from "@t3tools/contracts"; -import { memo, useEffect, useEffectEvent, useRef, useState } from "react"; -import { useStableCallback } from "~/hooks/useStableCallback"; +import { memo, type Ref, useEffect, useRef, useState } from "react"; +import { commandScopeRef } from "~/shortcuts/dispatcher"; import { type PendingUserInput } from "../../session-logic"; import { derivePendingUserInputProgress, @@ -23,6 +23,8 @@ interface PendingUserInputPanelProps { onToggleOption: (questionId: string, optionValue: string) => void; onAdvance: () => void; onDismiss: (requestId: RuntimeRequestId) => void; + /** Attached to each question card; the card remounts per request. */ + ref?: Ref; } export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({ @@ -36,6 +38,7 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn onToggleOption, onAdvance, onDismiss, + ref, }: PendingUserInputPanelProps) { if (pendingUserInputs.length === 0) return null; const activePrompt = pendingUserInputs[0]; @@ -54,6 +57,7 @@ export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserIn onToggleOption={onToggleOption} onAdvance={onAdvance} onDismiss={onDismiss} + ref={ref} /> ); }); @@ -69,6 +73,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( onToggleOption, onAdvance, onDismiss, + ref, }: { prompt: PendingUserInput; cwd: string | undefined; @@ -80,12 +85,12 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( onToggleOption: (questionId: string, optionValue: string) => void; onAdvance: () => void; onDismiss: (requestId: RuntimeRequestId) => void; + ref: Ref | undefined; }) { // Message-mode requests remain answerable after their provider turn ends. const canRespond = prompt.responseCapability !== "not_resumable"; const responseDisabled = disabled || isResponding || !canRespond; const autoAdvanceTimerRef = useRef(null); - const advance = useStableCallback(onAdvance); const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{ questionId: string; optionValue: string; @@ -101,6 +106,18 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( !customAnswerActive && progress.selectedOptionValues.includes(option.value ?? option.label), ); const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id; + // A pick only advances its own question while it may still be answered, so moving to another + // question (Previous, Next, a resolved request), losing permission, or unmounting cancels it. + useEffect(() => { + const clearAutoAdvance = () => { + if (autoAdvanceTimerRef.current !== null) { + window.clearTimeout(autoAdvanceTimerRef.current); + autoAdvanceTimerRef.current = null; + } + }; + if (disabled || activeQuestion?.id === undefined) clearAutoAdvance(); + return clearAutoAdvance; + }, [activeQuestion?.id, disabled]); if ( optimisticSingleSelect && @@ -113,17 +130,6 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( setOptimisticSingleSelect(null); } - useEffect(() => { - const clearAutoAdvance = () => { - if (autoAdvanceTimerRef.current !== null) { - window.clearTimeout(autoAdvanceTimerRef.current); - autoAdvanceTimerRef.current = null; - } - }; - if (disabled || activeQuestion?.id === undefined) clearAutoAdvance(); - return clearAutoAdvance; - }, [activeQuestion?.id, disabled]); - const handleOptionSelection = (questionId: string, optionValue: string) => { if (disabled || isResponding) return; if (activeQuestion?.multiSelect) { @@ -132,50 +138,46 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( } setOptimisticSingleSelect({ questionId, optionValue }); onToggleOption(questionId, optionValue); - if (autoAdvanceTimerRef.current !== null) { - window.clearTimeout(autoAdvanceTimerRef.current); - } + if (autoAdvanceTimerRef.current !== null) window.clearTimeout(autoAdvanceTimerRef.current); autoAdvanceTimerRef.current = window.setTimeout(() => { autoAdvanceTimerRef.current = null; - advance(); + onAdvance(); }, 200); }; - const selectOptionFromShortcut = useEffectEvent(handleOptionSelection); - - useEffect(() => { - if (!activeQuestion || responseDisabled || isCollapsed) return; - const handler = (event: globalThis.KeyboardEvent) => { - if (event.metaKey || event.ctrlKey || event.altKey) return; - const target = event.target; - if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) { - return; - } - if ( - target instanceof HTMLElement && - target.closest('[contenteditable]:not([contenteditable="false"])') - ) { - return; - } - const digit = Number.parseInt(event.key, 10); - if (Number.isNaN(digit) || digit < 1 || digit > 9) return; - const optionIndex = digit - 1; - if (optionIndex >= activeQuestion.options.length) return; - const option = activeQuestion.options[optionIndex]; - if (!option) return; - event.preventDefault(); - selectOptionFromShortcut(activeQuestion.id, option.value ?? option.label); - }; - document.addEventListener("keydown", handler); - return () => document.removeEventListener("keydown", handler); - }, [activeQuestion, isCollapsed, responseDisabled]); - if (!activeQuestion) { return null; } + const optionShortcutScope = (node: HTMLDivElement | null) => + commandScopeRef( + {}, + { + onKeyDown: (event) => { + if (event.metaKey || event.ctrlKey || event.altKey) return false; + const target = event.target; + if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) { + return false; + } + if ( + target instanceof HTMLElement && + target.closest('[contenteditable]:not([contenteditable="false"])') + ) { + return false; + } + const digit = Number.parseInt(event.key, 10); + if (Number.isNaN(digit) || digit < 1 || digit > 9) return false; + const option = activeQuestion.options[digit - 1]; + if (!option) return false; + event.preventDefault(); + handleOptionSelection(activeQuestion.id, option.value ?? option.label); + }, + }, + )(node); + return ( { setCollapsedQuestionId(open ? null : activeQuestion.id); @@ -230,7 +232,10 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( - + void; }) { const { entries, stashShortcutLabel, composerFormRef, onRestore, onDelete, onClose } = props; - const drawerRef = useRef(null); const [highlightedId, setHighlightedId] = useState(entries[0]?.id ?? null); const highlightedEntry = entries.find((entry) => entry.id === highlightedId) ?? entries[0]; - useEffect(() => { + const attachDrawer = (drawer: HTMLDivElement | null) => { + if (!drawer) return; const closeOnOutsidePointer = (event: PointerEvent) => { - const drawer = drawerRef.current; if ( - (drawer && event.composedPath().includes(drawer)) || + event.composedPath().includes(drawer) || (event.target instanceof Element && event.target.closest('[data-prompt-stash-badge="true"]')) ) { @@ -55,18 +54,14 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: { } onClose(); }; - document.addEventListener("pointerdown", closeOnOutsidePointer, true); - return () => document.removeEventListener("pointerdown", closeOnOutsidePointer, true); - }, [onClose]); - useEffect(() => { const handler = (event: KeyboardEvent) => { const target = event.target; if ( !(target instanceof Node) || (target !== document.body && !(target instanceof Element && target.closest('[data-prompt-stash-badge="true"]')) && - !drawerRef.current?.contains(target) && + !drawer.contains(target) && !composerFormRef.current?.querySelector('textarea, [role="textbox"]')?.contains(target)) ) { return; @@ -87,9 +82,9 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: { const nextIndex = (normalizedIndex + offset + entries.length) % entries.length; setHighlightedId(entries[nextIndex]?.id ?? null); const nextButton = - drawerRef.current?.querySelectorAll("[data-stash-restore]")[nextIndex]; + drawer.querySelectorAll("[data-stash-restore]")[nextIndex]; nextButton?.scrollIntoView({ block: "nearest" }); - if (drawerRef.current?.contains(document.activeElement)) { + if (drawer.contains(document.activeElement)) { nextButton?.focus({ preventScroll: true }); } return; @@ -112,12 +107,16 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: { onDelete(highlightedEntry); } }; + document.addEventListener("pointerdown", closeOnOutsidePointer, true); window.addEventListener("keydown", handler, true); - return () => window.removeEventListener("keydown", handler, true); - }, [composerFormRef, entries, highlightedEntry, onClose, onDelete, onRestore]); + return () => { + document.removeEventListener("pointerdown", closeOnOutsidePointer, true); + window.removeEventListener("keydown", handler, true); + }; + }; return ( - + } aria-label="Close stash" diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsx index b2041df5500df..46fed2ddc002e 100644 --- a/apps/web/src/components/chat/DraftHeroHeadline.tsx +++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx @@ -5,7 +5,7 @@ import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/envir import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { FolderPlusIcon } from "lucide-react"; import { useAtomValue } from "@effect/atom-react"; -import { useEffect, useRef, useState } from "react"; +import { useRef, useState } from "react"; import { openCommandPalette } from "~/commandPaletteBus"; import { shortcutLabelForCommand } from "~/keybindings"; @@ -159,21 +159,23 @@ export function DraftHeroHeadline({ ); const selectedPickerItem = pickerItems.find((item) => item.value === activeProjectKey) ?? null; - // Picker changes invalidate pending no-project home continuations. - const latestTargetRef = useRef({ draftId, activeProjectKey, scratchTargetEnvironmentId }); - useEffect(() => { - latestTargetRef.current = { draftId, activeProjectKey, scratchTargetEnvironmentId }; - }, [activeProjectKey, scratchTargetEnvironmentId, draftId]); + // The picker can change the draft's target while the no-project home is + // still being opened; a stale continuation must not retarget it again. Picking + // a project clears the pending request, and the draft session is compared + // against the store when the scratch project arrives. + const pendingScratchRef = useRef(null); + const draftTargetKey = () => { + const session = draftId ? useComposerDraftStore.getState().getDraftSession(draftId) : null; + return session + ? `${session.environmentId}:${session.projectId}:${session.logicalProjectKey}` + : null; + }; // Retargeting an empty draft would overwrite the project's draft and strand browser tabs. const selectProject = (project: (typeof projects)[number], logicalProjectKey: string) => { if (!draftId) { return; } - latestTargetRef.current = { - draftId, - activeProjectKey: logicalProjectKey, - scratchTargetEnvironmentId: project.environmentId, - }; + pendingScratchRef.current = null; const currentDraft = getComposerDraft(draftId); if (!composerDraftHasUserContent(currentDraft)) { void openProjectDraft(scopeProjectRef(project.environmentId, project.id)); @@ -204,17 +206,14 @@ export function DraftHeroHeadline({ if (scratchTargetEnvironmentId === null || isScratchDraft) { return false; } - const requested = { draftId, activeProjectKey, scratchTargetEnvironmentId }; + const request = Symbol("scratch"); + pendingScratchRef.current = request; + const requestedTarget = draftTargetKey(); const project = await openScratchProject(scratchTargetEnvironmentId); - const latest = latestTargetRef.current; - if ( - !project || - latest.draftId !== requested.draftId || - latest.activeProjectKey !== requested.activeProjectKey || - latest.scratchTargetEnvironmentId !== requested.scratchTargetEnvironmentId - ) { + if (!project || pendingScratchRef.current !== request || draftTargetKey() !== requestedTarget) { return false; } + pendingScratchRef.current = null; selectProject(project, deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings)); return true; }; diff --git a/apps/web/src/components/chat/DraftHeroProjectHeading.tsx b/apps/web/src/components/chat/DraftHeroProjectHeading.tsx index a0c5754e71b21..8f2b305184123 100644 --- a/apps/web/src/components/chat/DraftHeroProjectHeading.tsx +++ b/apps/web/src/components/chat/DraftHeroProjectHeading.tsx @@ -1,4 +1,4 @@ -import { useLayoutEffect, useRef, useState, type ReactNode } from "react"; +import { useRef, useState, type ReactNode } from "react"; import { observeResize } from "~/lib/observeResize"; @@ -9,12 +9,11 @@ export function DraftHeroProjectHeading({ children: ReactNode; projectName: string; }) { - const containerRef = useRef(null); const inlineRef = useRef(null); const [fitsInline, setFitsInline] = useState(false); - useLayoutEffect(() => { - const container = containerRef.current; + // Child refs attach before this one, so the inline measure span is already set. + const observeFit = (container: HTMLDivElement | null) => { const inline = inlineRef.current; if (!container || !inline) return; @@ -26,10 +25,10 @@ export function DraftHeroProjectHeading({ ); update(); return observeResize([container, inline], update); - }, []); + }; return ( -
+