Skip to content
Open
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
76 changes: 56 additions & 20 deletions apps/web/src/components/chat/ChatComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ import {
shouldSubmitComposerOnEnter,
} from "../../composer-logic";
import { deriveComposerSendState, readFileAsDataUrl } from "../ChatView.logic";
import {
dataTransferHasComposerMention,
makeComposerMentionDragHandlers,
} from "./composerMentionDrag";
import {
type ComposerImageAttachment,
type DraftId,
Expand Down Expand Up @@ -1878,6 +1882,53 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
addComposerImages(files);
focusComposer();
};

const insertComposerTextAtEnd = (
text: string,
options?: { ensureLeadingBoundary?: boolean },
): boolean => {
if (
text.length === 0 ||
isConnecting ||
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
) {
return false;
}
const prompt = promptRef.current;
const needsLeadingSpace =
(options?.ensureLeadingBoundary ?? false) && prompt.length > 0 && !/\s$/.test(prompt);
return applyPromptReplacement(
prompt.length,
prompt.length,
needsLeadingSpace ? ` ${text}` : text,
);
};
Comment thread
cursor[bot] marked this conversation as resolved.

// File-tree drags land as mentions. Handled in the capture phase so the
// editor never sees the drop; the load-bearing rules (native stop, "move"
// effect, no eager focus) live in makeComposerMentionDragHandlers.
const composerMentionDragHandlers = makeComposerMentionDragHandlers({
insertMentionAtEnd: (text) => insertComposerTextAtEnd(text, { ensureLeadingBoundary: true }),
setDragActive: setIsDragOverComposer,
onInsertRejected: () => {
toastManager.add({
type: "error",
title: "Unable to add to chat",
description: "The composer is busy; try again once it is ready.",
});
},
});

const onComposerMentionDragLeaveCapture = (event: React.DragEvent<HTMLDivElement>) => {
if (!dataTransferHasComposerMention(event.dataTransfer.types)) return;
event.stopPropagation();
const nextTarget = event.relatedTarget;
if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;
setIsDragOverComposer(false);
};
const handleInterruptPrimaryAction = useCallback(() => {
void onInterrupt();
}, [onInterrupt]);
Expand Down Expand Up @@ -1941,26 +1992,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
focusAt: (cursor: number) => {
composerEditorRef.current?.focusAt(cursor);
},
insertTextAtEnd: (text: string, options?: { ensureLeadingBoundary?: boolean }) => {
if (
text.length === 0 ||
isConnecting ||
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
) {
return false;
}
const prompt = promptRef.current;
const needsLeadingSpace =
(options?.ensureLeadingBoundary ?? false) && prompt.length > 0 && !/\s$/.test(prompt);
return applyPromptReplacement(
prompt.length,
prompt.length,
needsLeadingSpace ? ` ${text}` : text,
);
},
insertTextAtEnd: insertComposerTextAtEnd,
openModelPicker: () => {
setIsComposerModelPickerOpen(true);
},
Expand Down Expand Up @@ -2087,6 +2119,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
onDragOver={onComposerDragOver}
onDragLeave={onComposerDragLeave}
onDrop={onComposerDrop}
onDragEnterCapture={composerMentionDragHandlers.onDragEnter}
onDragOverCapture={composerMentionDragHandlers.onDragOver}
onDragLeaveCapture={onComposerMentionDragLeaveCapture}
onDropCapture={composerMentionDragHandlers.onDrop}
>
<div
ref={composerSurfaceRef}
Expand Down
123 changes: 123 additions & 0 deletions apps/web/src/components/chat/composerMentionDrag.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { describe, expect, it } from "@effect/vitest";

import {
COMPOSER_MENTION_DRAG_TYPE,
type ComposerMentionDropHost,
composerMentionFromTreePath,
dataTransferHasComposerMention,
makeComposerMentionDragHandlers,
} from "./composerMentionDrag.ts";

const makeDragEvent = (options?: { mention?: string; types?: ReadonlyArray<string> }) => {
const mention = options?.mention ?? "[index.md](docs/index.md)";
const calls: Array<string> = [];
const event = {
dataTransfer: {
types: options?.types ?? [COMPOSER_MENTION_DRAG_TYPE, "text/plain"],
getData: (format: string) => (format === COMPOSER_MENTION_DRAG_TYPE ? mention : ""),
dropEffect: "none",
},
nativeEvent: {
stopPropagation: () => void calls.push("nativeStopPropagation"),
},
preventDefault: () => void calls.push("preventDefault"),
stopPropagation: () => void calls.push("stopPropagation"),
};
return { event, calls };
};

const makeHost = (insertResult = true) => {
const log: Array<string> = [];
const host: ComposerMentionDropHost = {
insertMentionAtEnd: (text) => {
log.push(`insert:${text}`);
return insertResult;
},
setDragActive: (active) => void log.push(`active:${active}`),
onInsertRejected: () => void log.push("rejected"),
};
return { host, log };
};

describe("composerMentionFromTreePath", () => {
it("serializes a file path into a mention", () => {
expect(composerMentionFromTreePath("docs/index.md")).toBe("[index.md](docs/index.md)");
});

it("strips the trailing slash directory rows carry", () => {
expect(composerMentionFromTreePath("docs/architecture/")).toBe(
"[architecture](docs/architecture)",
);
});

it("rejects drags that carry no path", () => {
expect(composerMentionFromTreePath("")).toBeNull();
expect(composerMentionFromTreePath("/")).toBeNull();
});
});

describe("dataTransferHasComposerMention", () => {
it("detects the mention payload among drag types", () => {
expect(dataTransferHasComposerMention([COMPOSER_MENTION_DRAG_TYPE, "text/plain"])).toBe(true);
expect(dataTransferHasComposerMention(["Files"])).toBe(false);
expect(dataTransferHasComposerMention([])).toBe(false);
});
});

describe("makeComposerMentionDragHandlers", () => {
it("leaves drags without the mention payload alone", () => {
const { host, log } = makeHost();
const handlers = makeComposerMentionDragHandlers(host);
const { event, calls } = makeDragEvent({ types: ["Files"] });
handlers.onDragEnter(event);
handlers.onDragOver(event);
handlers.onDrop(event);
expect(calls).toEqual([]);
expect(log).toEqual([]);
});

it("stops the native event too, not just the synthetic one", () => {
// React's stopPropagation only halts synthetic dispatch; without the
// native stop, the editor's own DOM listeners process the drop and sync
// their stale state back over the inserted mention.
const { host } = makeHost();
const handlers = makeComposerMentionDragHandlers(host);
const { event, calls } = makeDragEvent();
handlers.onDrop(event);
expect(calls).toContain("preventDefault");
expect(calls).toContain("stopPropagation");
expect(calls).toContain("nativeStopPropagation");
});

it('answers dragover with the "move" effect the tree allows', () => {
// Naming an effect outside the source's effectAllowed makes the browser
// cancel the drop without ever firing it.
const { host } = makeHost();
const handlers = makeComposerMentionDragHandlers(host);
const { event } = makeDragEvent();
handlers.onDragOver(event);
expect(event.dataTransfer.dropEffect).toBe("move");
});

it("inserts the mention with its trailing space and clears the highlight", () => {
const { host, log } = makeHost();
const handlers = makeComposerMentionDragHandlers(host);
handlers.onDragEnter(makeDragEvent().event);
handlers.onDrop(makeDragEvent().event);
expect(log).toEqual(["active:true", "active:false", "insert:[index.md](docs/index.md) "]);
});

it("reports a rejected insert instead of failing silently", () => {
const { host, log } = makeHost(false);
const handlers = makeComposerMentionDragHandlers(host);
handlers.onDrop(makeDragEvent().event);
expect(log).toContain("rejected");
});

it("ignores a drop whose payload is empty", () => {
const { host, log } = makeHost();
const handlers = makeComposerMentionDragHandlers(host);
handlers.onDrop(makeDragEvent({ mention: "" }).event);
expect(log).toEqual(["active:false"]);
});
});
98 changes: 98 additions & 0 deletions apps/web/src/components/chat/composerMentionDrag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";

/**
* Drag payload type carrying a serialized composer mention. Set on drags that
* start in the workspace file tree so the composer can tell them apart from
* OS file drags and plain text selections.
*/
export const COMPOSER_MENTION_DRAG_TYPE = "application/x-t3code-composer-mention";

export function composerMentionFromTreePath(treePath: string): string | null {
const relativePath = treePath.replace(/\/+$/, "");
if (relativePath.length === 0) {
return null;
}
return serializeComposerFileLink(relativePath);
}

export function dataTransferHasComposerMention(types: ReadonlyArray<string>): boolean {
return types.includes(COMPOSER_MENTION_DRAG_TYPE);
}

export interface ComposerMentionDragTransfer {
readonly types: ReadonlyArray<string>;
getData(format: string): string;
dropEffect: string;
}

export interface ComposerMentionDragEvent {
readonly dataTransfer: ComposerMentionDragTransfer;
readonly nativeEvent: { stopPropagation(): void };
preventDefault(): void;
stopPropagation(): void;
}

/**
* What a mention drop is allowed to do to the composer. Deliberately narrow:
* there is no way to focus the editor from here. Focusing it synchronously
* during the drop makes the not-yet-reconciled editor sync its stale empty
* state back over the inserted mention; the insert path already focuses on
* the next frame, after the editor has caught up.
*/
export interface ComposerMentionDropHost {
insertMentionAtEnd(text: string): boolean;
setDragActive(active: boolean): void;
onInsertRejected(): void;
}

export interface ComposerMentionDragHandlers {
onDragEnter(event: ComposerMentionDragEvent): void;
onDragOver(event: ComposerMentionDragEvent): void;
onDrop(event: ComposerMentionDragEvent): void;
}

export function makeComposerMentionDragHandlers(
host: ComposerMentionDropHost,
): ComposerMentionDragHandlers {
// Claim the event for the composer: React's stopPropagation only halts the
// synthetic dispatch, so the native event must be stopped too or the
// editor's own DOM listeners still process the drag.
const claim = (event: ComposerMentionDragEvent): boolean => {
if (!dataTransferHasComposerMention(event.dataTransfer.types)) {
return false;
}
event.preventDefault();
event.stopPropagation();
event.nativeEvent.stopPropagation();
return true;
};
return {
onDragEnter(event) {
if (claim(event)) {
host.setDragActive(true);
}
},
onDragOver(event) {
if (!claim(event)) {
return;
}
// The tree constrains its drags to effectAllowed "move"; naming any
// other effect makes the browser cancel the drop without firing it.
event.dataTransfer.dropEffect = "move";
host.setDragActive(true);
},
onDrop(event) {
if (!claim(event)) {
return;
}
host.setDragActive(false);
const mention = event.dataTransfer.getData(COMPOSER_MENTION_DRAG_TYPE);
if (mention.length === 0) {
return;
}
if (!host.insertMentionAtEnd(`${mention} `)) {
host.onInsertRejected();
}
},
};
}
Loading
Loading