Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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: [] });
Expand All @@ -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();
Expand All @@ -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: [] });
Expand Down
24 changes: 9 additions & 15 deletions apps/web/src/components/chat/ComposerAttachmentStrip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -79,22 +79,16 @@ function SnapShotAttachmentFrame({
readonly arrival?: boolean | undefined;
readonly animateArrival?: boolean | undefined;
}) {
const frameRef = useRef<HTMLDivElement>(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 (
<div
ref={frameRef}
ref={(frame) => {
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 &&
Expand Down
61 changes: 21 additions & 40 deletions apps/web/src/components/chat/ComposerBannerStack.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -51,39 +52,25 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
const noticesRef = useRef<HTMLDivElement>(null);
const peekRef = useRef<HTMLButtonElement>(null);
const expandedItemsRef = useRef<HTMLDivElement>(null);
const pendingFocusRef = useRef<"peek" | "notice" | null>(null);
const expandedItemsId = useId();
const [requestedExitingItemId, setExitingItemId] = useState<string | null>(null);
const dismissTimeoutRef = useRef<ReturnType<typeof setTimeout> | 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<HTMLElement>(
'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<HTMLElement>(
'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];
Expand All @@ -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 (
Expand All @@ -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);
}}
Expand All @@ -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 ? (
Expand All @@ -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")}
/>
Expand Down Expand Up @@ -257,12 +240,10 @@ function NoticeText({
readonly className: string;
readonly detailsLabel: string;
}) {
const textRef = useRef<HTMLSpanElement>(null);
const detailsRef = useRef<HTMLButtonElement>(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
Expand All @@ -284,11 +265,11 @@ function NoticeText({
stopObserving();
mutations.disconnect();
};
}, []);
};

return (
<span className="contents">
<span ref={textRef} className={className}>
<span ref={observeOverflow} className={className}>
{children}
</span>
{showDetails ? (
Expand Down
18 changes: 6 additions & 12 deletions apps/web/src/components/chat/ComposerCommandMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -90,16 +90,6 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
onHighlightedItemChange: (itemId: string | null) => void;
onSelect: (item: ComposerCommandItem) => void;
}) {
const listRef = useRef<HTMLDivElement>(null);

useLayoutEffect(() => {
if (!props.activeItemId || !listRef.current) return;
const el = listRef.current.querySelector<HTMLElement>(
`[data-composer-item-id="${CSS.escape(props.activeItemId)}"]`,
);
el?.scrollIntoView({ block: "nearest" });
}, [props.activeItemId]);

return (
<Command
autoHighlight={false}
Expand All @@ -111,7 +101,6 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
}}
>
<ComposerBanner.Surface
ref={listRef}
className="flex min-h-0 w-full flex-col overflow-hidden pb-(--chat-composer-attachment-overlap) **:data-[slot=command-item]:rounded-lg **:data-[slot=scroll-area-scrollbar]:data-[orientation=vertical]:my-4"
data-composer-command-drawer="true"
>
Expand Down Expand Up @@ -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;
Expand All @@ -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);
Expand Down
33 changes: 19 additions & 14 deletions apps/web/src/components/chat/ComposerImageThumbnail.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<Suspense fallback={props.fallback}>
<ThumbnailImage {...props} />
</Suspense>
);
});

function ThumbnailImage({
file,
alt,
className,
Expand All @@ -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 ? <img src={src} alt={alt} className={className} /> : fallback;
});
}
Loading
Loading