From 6a033d02065d13bc1f2d46a54ec916d57059c2c3 Mon Sep 17 00:00:00 2001 From: Renfei Zhou Date: Sun, 22 Nov 2026 00:21:52 +0000 Subject: [PATCH] feat(web): open a dragged file or link in the right-panel pane it is dropped on Dragging a Files row or a chat link (file, pull request, issue, thread, board, Dashboard or web link) onto a right-panel pane opens it there. A drop on a tab strip opens it at that slot, and the outer thirds of a single pane split the panel with the link on that side, as a tab drag does. Each source keeps its own open; the panel places the surface that open activates. The composer @mention drop, also in a side chat inside the panel, and tab dragging are unchanged. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + apps/web/src/browser/openFileInPreview.ts | 3 + apps/web/src/components/ChatMarkdown.tsx | 46 ++- apps/web/src/components/RightPanelTabs.tsx | 1 + apps/web/src/components/ThreadContextChip.tsx | 6 +- .../src/components/chat/MarkdownFileLink.tsx | 22 +- .../components/chat/MarkdownThreadLink.tsx | 34 +- .../src/components/files/FileBrowserPanel.tsx | 16 +- .../files/fileTreeDragMention.test.ts | 12 +- .../components/files/fileTreeDragMention.ts | 10 +- apps/web/src/fork/dashboard/dashboardLink.tsx | 19 +- .../rightPanelSplit/PanelLinkDropScope.tsx | 187 +++++++++ .../rightPanelSplit/RightPanelDragScope.tsx | 2 +- .../RightPanelSplitView.browser.test.tsx | 301 +++++++++++++- .../rightPanelSplit/RightPanelSplitView.tsx | 69 ++-- .../fork/rightPanelSplit/chatAnchorLink.ts | 107 +++++ .../fork/rightPanelSplit/dropTarget.logic.ts | 72 +++- .../rightPanelSplit/linkDrop.logic.test.ts | 377 ++++++++++++++++++ .../fork/rightPanelSplit/linkDrop.logic.ts | 192 +++++++++ .../fork/rightPanelSplit/linkSources.test.ts | 180 +++++++++ .../src/fork/rightPanelSplit/linkSources.ts | 139 +++++++ .../fork/rightPanelSplit/panelLinkDrag.css | 16 + .../src/fork/rightPanelSplit/panelLinkDrag.ts | 143 +++++++ apps/web/src/fork/whiteboard/boardChannel.ts | 7 + apps/web/src/lib/openIssueLink.ts | 24 +- apps/web/src/lib/sideChatPane.ts | 2 +- apps/web/src/rightPanelStore.ts | 28 +- 27 files changed, 1918 insertions(+), 98 deletions(-) create mode 100644 apps/web/src/fork/rightPanelSplit/PanelLinkDropScope.tsx create mode 100644 apps/web/src/fork/rightPanelSplit/chatAnchorLink.ts create mode 100644 apps/web/src/fork/rightPanelSplit/linkDrop.logic.test.ts create mode 100644 apps/web/src/fork/rightPanelSplit/linkDrop.logic.ts create mode 100644 apps/web/src/fork/rightPanelSplit/linkSources.test.ts create mode 100644 apps/web/src/fork/rightPanelSplit/linkSources.ts create mode 100644 apps/web/src/fork/rightPanelSplit/panelLinkDrag.css create mode 100644 apps/web/src/fork/rightPanelSplit/panelLinkDrag.ts diff --git a/README.md b/README.md index d30eeeb0e6f8..05d9229a71f7 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ This is a fork of T3 Code that integrates a few additional features, including: - "Enable Dashboard", beside Display mode in the same menu, gives the thread a Dashboard in either mode: a Dashboard tab in the right panel (+ → Dashboard) with six status slots that the agent writes with its `dashboard_set` tool and reads with `dashboard_get`. Each slot shows how long ago it changed, and new text stays highlighted until you click the slot. Select text in a slot to quote it with Cite, as you would in a message. Agents can link to the Dashboard in their messages, and a click on the link opens it. - Settings → Threads → New threads → Display mode picks the mode for threads you start from the message box in the web or desktop app. Threads that agents, scheduled tasks, side chats or the mobile app start open in Normal mode, and existing threads keep their mode. - **Split the right panel in two:** drag a right-panel tab onto the left or right part of the panel's content and drop it to get two panes side by side, each with its own tabs, as with Windows Snap. Drag tabs between the panes, drag the line between them to resize (double-click resets it), and close or move away a pane's last tab to go back to one pane. The tab menu has Split right, Split left, Move to the other pane and Unsplit. New tabs open in the pane you last used. A narrow window shows all tabs in one strip and keeps the split for when there is room. A press anywhere on a tab now switches to it at once. +- **Drag links into the right panel:** drag a file from the Files tree, or a link from a chat message, onto a right-panel pane to open it there. Supported chat links are file, pull request, issue, thread, `board://`, Dashboard, and web links. Drop the item on a tab strip to open it at that spot. Drop the item on the left or right third of a single pane to split the panel on that side when there is room. If the item is already open in the other pane, the drop moves its tab to where you dropped it. A dropped file keeps a standalone Files tab open beside it. A plain click on a file still replaces the Files tab. A full pull request or issue URL opens as a pull request or issue tab when a click opens that kind of tab. Other web links, and pull request or issue links that do not, drag whenever the preview browser is available. Dropping one opens it in the preview browser, even when a plain click opens it in your system browser. Without a preview browser, those links do not drag to the panel. Folder rows in the Files tree, short references like `#42`, commit links, and web image and video URLs do not drag to the panel. A chat file link drags whenever a click opens it in the panel. A dropped file link opens what its click opens, in the pane you chose. It can open a workspace folder or a workspace image or video file. Dragging a Files row to a message box still adds an `@mention`. In the desktop app on Mac and Windows, file links in chat still drag out as files instead of dropping on the panel. - Copy buttons on pages in the preview browser now put the copied text into your own clipboard. - **Two preview browser modes:** Settings → Browser → Preview browser picks the browser the server runs for preview tabs. **T3 native** (fast) is the default. It runs chrome-headless-shell, Chrome's small build that runs without a window. **Chrome** (slow) runs full Chrome, for pages that don't work in T3 native. On platforms where T3 has no Chrome for Testing build (Google's Chrome build for test automation), both choices run T3 native. Switching closes the open preview tabs. - **Compact when idle for Claude threads:** a choice in Settings → Providers → Advanced → Compact idle threads. Besides compacting before the prompt cache expires, it compacts a large idle Claude thread (default 400K tokens or more) a set time (default 15 minutes) after the last message or answer from a user or a bot, so the compaction runs while no one waits for a reply. The token counts and the wait are set right under the choice. diff --git a/apps/web/src/browser/openFileInPreview.ts b/apps/web/src/browser/openFileInPreview.ts index e93edfeac91c..571338c027b9 100644 --- a/apps/web/src/browser/openFileInPreview.ts +++ b/apps/web/src/browser/openFileInPreview.ts @@ -64,6 +64,8 @@ export async function openUrlInPreview(input: { readonly openPreview: OpenPreviewMutation; readonly profileId?: PreviewOpenInput["profileId"]; readonly background?: boolean; + /** Runs right after the panel opens the tab, in the same task as that write. */ + readonly onOpened?: () => void; }): Promise> { // Read before any await: a side chat pane that unmounts meanwhile drops its host mapping. const threadRef = rightPanelHostRef(input.threadRef); @@ -108,6 +110,7 @@ export async function openUrlInPreview(input: { } applyPreviewServerSnapshot(threadRef, snapshot); useRightPanelStore.getState().openBrowser(threadRef, snapshot.tabId); + input.onOpened?.(); }); } diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index c4074b1ac357..9931a29eaad9 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -103,6 +103,9 @@ import type { } from "react-markdown"; import { createIncrementalMarkdownPlugin } from "../markdown-incremental"; import { postWhiteboardHover, remarkWhiteboardLinks } from "../fork/whiteboard/markdown-whiteboard"; +import { chatAnchorPanelLinks } from "../fork/rightPanelSplit/chatAnchorLink"; +import { openedSync } from "../fork/rightPanelSplit/linkSources"; +import { type OpenedSurface, startPanelLinkDrag } from "../fork/rightPanelSplit/panelLinkDrag"; import { showBoardRef } from "../fork/whiteboard/boardChannel"; import { remarkEndLinksAtCjkPunctuation } from "../fork/cjkLinkEnd"; import { DashboardLinkChip, parseDashboardHref } from "../fork/dashboard/dashboardLink"; @@ -177,7 +180,7 @@ import { appAtomRegistry } from "../rpc/atomRegistry"; import { hostEnvironmentIdAtom } from "../state/primaryEnvironment"; import { cn } from "../lib/utils"; import { resolveRemoteOpenState, useRemoteOpenResolution } from "../remoteOpen"; -import { rightPanelHostRef, useRightPanelStore } from "../rightPanelStore"; +import { type OpenFileOptions, rightPanelHostRef, useRightPanelStore } from "../rightPanelStore"; import { useOpenIssueLink } from "../lib/openIssueLink"; import { issueTrackerEnvironment } from "../state/issueTrackers"; import { useEnvironmentQuery } from "../state/query"; @@ -794,7 +797,7 @@ function useChatMarkdownState({ if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return; await pullRequestLinking.changeLink(threadRef, href, linked); }; - const openExternalLinkInPreview = (url: string) => { + const openExternalLinkInPreview = (url: string, onOpened?: () => void) => { if (!threadRef || !canOperatePreview) { return Promise.resolve( AsyncResult.failure( @@ -806,7 +809,8 @@ function useChatMarkdownState({ ), ); } - return openUrlInPreview({ threadRef, url, openPreview }).then((result) => { + const opened = onOpened ? { onOpened } : {}; + return openUrlInPreview({ threadRef, url, openPreview, ...opened }).then((result) => { if (result._tag === "Success") recordVisitForThread(threadRef, url); else if (!isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); @@ -823,6 +827,14 @@ function useChatMarkdownState({ return result; }); }; + const anchorPanelLink = chatAnchorPanelLinks({ + threadRef, + canOperatePreview, + issueTrackers, + openChangeRequestLink, + openIssueLink, + openExternalLinkInPreview, + }); const openMarkdownFileInPreview = (path: string) => { const preparedConnection = threadRef ? readPreparedConnection(threadRef.environmentId) : null; if (!threadRef || !canOperatePreview || preparedConnection === null) { @@ -918,30 +930,35 @@ function useChatMarkdownState({ } return findAgentDirectoryMatch(workspaceRelativePath, agentRoots, searchRoot); }; - const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => { - if (!threadRef) return; + const openFileInPanel = ( + fileLinkMeta: MarkdownFileLinkMeta, + panelPath: string, + ...options: [OpenFileOptions?] + ): OpenedSurface | Promise => { + if (!threadRef) return null; const openAt = (path: string) => - useRightPanelStore.getState().openFile(threadRef, path, fileLinkMeta.line); + openedSync(rightPanelHostRef(threadRef), () => + useRightPanelStore.getState().openFile(threadRef, path, fileLinkMeta.line, ...options), + ); if ( fileLinkMeta.workspaceLookupPath === null || !cwd || workspaceLinkLookupQuery(panelPath, cwd) === null ) { - openAt(panelPath); - return; + return openAt(panelPath); } // Anything the user opens in this panel meanwhile, such as a file from the picker, wins. const panelRef = rightPanelHostRef(threadRef); const panelKey = scopedThreadKey(panelRef); const userActionRevision = useRightPanelStore.getState().markUserAction(panelRef); - void (async () => { + return (async () => { const match = await findWorkspaceFileMatch(fileLinkMeta); if ( scopedThreadKey(rightPanelHostRef(threadRef)) !== panelKey || useRightPanelStore.getState().getUserActionRevision(panelRef) !== userActionRevision ) - return; - openAt(match ?? panelPath); + return null; + return openAt(match ?? panelPath); })(); }; const fileLinkChip = ( @@ -1019,7 +1036,7 @@ function useChatMarkdownState({ resolveCopyPaths={async () => markdownFileCopyPaths(fileLinkMeta, await resolveHostPath(), cwd) } - onOpenInPanel={(path) => openFileInPanel(fileLinkMeta, path)} + onOpenInPanel={(path, _line, ...options) => openFileInPanel(fileLinkMeta, path, ...options)} onOpenMedia={ threadRef && canPreviewMedia ? () => openMarkdownMedia(mediaPath, fileLinkMeta.filePath) @@ -1072,6 +1089,7 @@ function useChatMarkdownState({ openIssueLink, openDeferredMarkdownLink, openExternalLinkInPreview, + anchorPanelLink, openMarkdownMedia, projects, issueProjects, @@ -1246,6 +1264,7 @@ const CHAT_MARKDOWN_COMPONENTS = { openDeferredMarkdownLink, linkTargetPreference, openExternalLinkInPreview, + anchorPanelLink, projects, issueProjects, issueTrackers, @@ -1359,6 +1378,9 @@ const CHAT_MARKDOWN_COMPONENTS = { onMouseLeave={() => { if (isWhiteboardLink) postWhiteboardHover(null); }} + onDragStart={(event) => + startPanelLinkDrag(event, anchorPanelLink(href, pullRequestAutolink)) + } onClick={(event) => { onClick?.(event); if (isWhiteboardLink && href) { diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 48f8da169d4c..45db35ed3494 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -1141,6 +1141,7 @@ function RightPanelTab( return (
{ preventTabMiddleButtonDefault(event); press.onMouseDown(event); diff --git a/apps/web/src/components/ThreadContextChip.tsx b/apps/web/src/components/ThreadContextChip.tsx index cc099fc791a8..3f9e5968b1a2 100644 --- a/apps/web/src/components/ThreadContextChip.tsx +++ b/apps/web/src/components/ThreadContextChip.tsx @@ -3,6 +3,7 @@ import type { ThreadContextRecord, ProjectId } from "@t3tools/contracts"; import { Link, useNavigate } from "@tanstack/react-router"; import { MessagesSquareIcon } from "lucide-react"; import { useGT } from "gt-react"; +import type { DragEventHandler } from "react"; import { resolveThreadOpenRoute } from "~/lib/sideChatPane"; import { buildThreadRouteParams } from "~/threadRoutes"; @@ -18,6 +19,8 @@ export function ThreadContextChip(props: { projectId?: ProjectId | null; copyMarkdown?: string; unreadable?: boolean; + /** Makes the chip draggable; without it the router link does not drag. */ + onDragStart?: DragEventHandler | undefined; }) { const gt = useGT(); const { environmentId, threadId } = props.record; @@ -58,7 +61,8 @@ export function ThreadContextChip(props: { ), }); }} - draggable={false} + draggable={props.onDragStart !== undefined} + onDragStart={props.onDragStart} /> } aria-label={gt("Thread, {title}", { title })} diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsx index a70c75265e39..b4e514e1fea2 100644 --- a/apps/web/src/components/chat/MarkdownFileLink.tsx +++ b/apps/web/src/components/chat/MarkdownFileLink.tsx @@ -17,9 +17,12 @@ import { leavesFileChipClickToBrowser, runHostFileLinkMenuItem, } from "../../fork/hostFileLinks"; +import { fileChipPanelLink } from "../../fork/rightPanelSplit/linkSources"; +import { type OpenedSurface, startPanelLinkDrag } from "../../fork/rightPanelSplit/panelLinkDrag"; import { readLocalApi } from "../../localApi"; import { cn } from "../../lib/utils"; import { shouldOpenMarkdownFileLinkInEditor } from "../../markdown-links"; +import type { OpenFileOptions } from "../../rightPanelStore"; import type { markdownFileCopyPaths } from "../../markdownFileHostPath"; import { documentChipKindForFileName } from "../../pierre-icons"; import { ContextChip } from "../ContextChip"; @@ -49,7 +52,12 @@ interface MarkdownFileLinkProps { theme: "light" | "dark"; threadRef?: ScopedThreadRef | undefined; onOpen?: (() => Promise>) | undefined; - onOpenInPanel: (panelPath: string, line: number | undefined) => void; + /** The surface it opened in the panel, or null. */ + onOpenInPanel: ( + panelPath: string, + line: number | undefined, + options?: OpenFileOptions, + ) => OpenedSurface | Promise; resolveDragPath: () => Promise; resolveCopyPaths: () => Promise>; openInEditorMenuLabel: string; @@ -127,7 +135,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ const handleOpenInFilePreview = () => { if (threadRef && panelPath) { - onOpenInPanel(panelPath, line); + void onOpenInPanel(panelPath, line); return; } if (onOpenMedia) { @@ -348,6 +356,16 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ hasPrimaryAction ? ( { + if (nativeDrag.draggable) nativeDrag.onDragStart(event); + else + startPanelLinkDrag( + event, + fileChipPanelLink(threadRef, panelPath, (path, options) => + onOpenInPanel(path, line, options), + ), + ); + }} kind={chipKind} dir="ltr" render={} diff --git a/apps/web/src/components/chat/MarkdownThreadLink.tsx b/apps/web/src/components/chat/MarkdownThreadLink.tsx index 320951a9e312..8209a36c9a48 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.tsx @@ -11,6 +11,8 @@ import { import { unknownThreadLinkLabel } from "@t3tools/shared/threadLinksCopy"; import { resolveLinkedThreadOpen } from "@t3tools/client-runtime/linked-thread"; +import { threadChipPanelLink } from "../../fork/rightPanelSplit/linkSources"; +import { startPanelOnlyDrag } from "../../fork/rightPanelSplit/panelLinkDrag"; import { configuredHostedAppUrl } from "../../hostedPairing"; import { useThreadRefs, useThreadShell } from "../../state/entities"; import { useConnectedEnvironmentIds, useEnvironmentIdentities } from "../../state/environments"; @@ -87,6 +89,12 @@ export function MarkdownThreadLink(props: { if (linked && linkedLabel !== undefined) { const knownTitle = props.label ?? written?.title ?? null; const title = knownTitle ?? gt("Thread on {label}", { label: linkedLabel }); + const linkedTarget = { + viaEnvironmentId: props.environmentId, + ...writtenRef, + label: linkedLabel, + title: knownTitle, + }; return ( + startPanelOnlyDrag( + event, + threadChipPanelLink({ + threadRef: props.threadRef, + target: { kind: "linked", target: linkedTarget }, + }), + ) + } {...trigger( (intent) => openLinkedThreadRead({ panelRef, - target: { - viaEnvironmentId: props.environmentId, - ...writtenRef, - label: linkedLabel, - title: knownTitle, - }, + target: linkedTarget, intent, navigate, }), @@ -138,6 +151,15 @@ export function MarkdownThreadLink(props: { record={{ ...ref, title }} projectId={resolved?.metadata.projectId ?? null} copyMarkdown={formatHostedThreadLink(ref, title, configuredHostedAppUrl())} + onDragStart={ + props.threadRef + ? (event) => + startPanelOnlyDrag( + event, + threadChipPanelLink({ threadRef: props.threadRef, target: { kind: "local", ref } }), + ) + : undefined + } /> ); } diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 1fee7db23872..404861f11510 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -25,6 +25,8 @@ import { useStableCallback } from "~/hooks/useStableCallback"; import { useTheme } from "~/hooks/useTheme"; import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh"; import { useFileContextMenu, type FileContextMenuAction } from "~/fileContextMenu"; +import { fileRowPanelLink } from "~/fork/rightPanelSplit/linkSources"; +import { startPanelLinkDrag, usePanelLinkOwner } from "~/fork/rightPanelSplit/panelLinkDrag"; import { readLocalApi } from "~/localApi"; import { T3_PIERRE_ICONS } from "~/pierre-icons"; import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme"; @@ -169,6 +171,7 @@ export default function FileBrowserPanel({ const messages = useMessages(); const { resolvedTheme } = useTheme(); const composerRef = useComposerHandleContext(); + const panelLinkOwner = usePanelLinkOwner(); const fileContextMenu = useFileContextMenu(environmentId); const { entries: directoryEntries, @@ -550,7 +553,18 @@ export default function FileBrowserPanel({ contextMenuPointerRef.current = { x: event.clientX, y: event.clientY, at: event.timeStamp }; }} // Capture dragstart before the tree selects the row so selection sees the drag flag. - onDragStartCapture={(event) => dragMention.handleDragStart(event.nativeEvent)} + onDragStartCapture={(event) => { + const treePath = dragMention.handleDragStart(event.nativeEvent); + startPanelLinkDrag( + event, + fileRowPanelLink({ + owner: panelLinkOwner, + treePath, + isFile: (path) => entryKindsRef.current.get(path) === "file", + panelPath, + }), + ); + }} onDragEnd={() => dragMention.handleDragEnd((path) => model.getItem(path)?.deselect())} onWheel={stopFollowingReveal} onPointerDown={stopFollowingReveal} diff --git a/apps/web/src/components/files/fileTreeDragMention.test.ts b/apps/web/src/components/files/fileTreeDragMention.test.ts index 2c459a4c3d9a..008c7c20c464 100644 --- a/apps/web/src/components/files/fileTreeDragMention.test.ts +++ b/apps/web/src/components/files/fileTreeDragMention.test.ts @@ -20,10 +20,11 @@ describe("createFileTreeDragMentionController", () => { it("tags a row drag with the mention payload and flags the drag", () => { const controller = createFileTreeDragMentionController({}); const transfer = makeTransfer(); - controller.handleDragStart({ + const row = controller.handleDragStart({ dataTransfer: transfer, composedPath: () => [{}, rowNode("docs/index.md"), {}], }); + expect(row).toBe("docs/index.md"); expect(transfer.getData(COMPOSER_MENTION_DRAG_TYPE)).toBe("[index.md](docs/index.md)"); expect(controller.isDragInProgress()).toBe(true); }); @@ -31,21 +32,24 @@ describe("createFileTreeDragMentionController", () => { it("does not tag drags of selected text from the panel chrome", () => { const controller = createFileTreeDragMentionController({}); const transfer = makeTransfer("selected text"); - controller.handleDragStart({ dataTransfer: transfer, composedPath: () => [{}] }); + expect( + controller.handleDragStart({ dataTransfer: transfer, composedPath: () => [{}] }), + ).toBeNull(); expect(transfer.data.has(COMPOSER_MENTION_DRAG_TYPE)).toBe(false); expect(controller.isDragInProgress()).toBe(false); }); - it("drags the whole selection when the dragged row is part of it", () => { + it("drags the whole selection when the dragged row is part of it, and names the row", () => { const deselected: Array = []; const controller = createFileTreeDragMentionController({}); const deselect = (path: string) => void deselected.push(path); controller.handleSelectionChange(["docs/index.md", "docs/api.md", "src/app.ts"]); const transfer = makeTransfer(); - controller.handleDragStart({ + const row = controller.handleDragStart({ dataTransfer: transfer, composedPath: () => [rowNode("docs/api.md")], }); + expect(row).toBe("docs/api.md"); expect(transfer.getData(COMPOSER_MENTION_DRAG_TYPE)).toBe( "[index.md](docs/index.md) [api.md](docs/api.md) [app.ts](src/app.ts)", ); diff --git a/apps/web/src/components/files/fileTreeDragMention.ts b/apps/web/src/components/files/fileTreeDragMention.ts index 2db7794ad61b..04879af03180 100644 --- a/apps/web/src/components/files/fileTreeDragMention.ts +++ b/apps/web/src/components/files/fileTreeDragMention.ts @@ -20,7 +20,8 @@ export interface FileTreeDragMentionHost { export interface FileTreeDragMentionController { isDragInProgress(): boolean; handleSelectionChange(selectedPaths: ReadonlyArray): void; - handleDragStart(event: FileTreeDragStartEvent): void; + /** Returns the tree path of the row under the pointer, or null when the drag is not a row's. */ + handleDragStart(event: FileTreeDragStartEvent): string | null; handleDragEnd(deselect: (treePath: string) => void): void; } @@ -44,7 +45,7 @@ export function createFileTreeDragMentionController( }, handleDragStart(event) { if (event.dataTransfer === null) { - return; + return null; } // Require a tree-row origin; text/plain fallback would misclassify selected panel text as a mention. let itemPath: string | null = null; @@ -55,7 +56,7 @@ export function createFileTreeDragMentionController( } } if (itemPath === null) { - return; + return null; } const dragged = selection.includes(itemPath) ? selection : [itemPath]; const mentions = dragged @@ -67,10 +68,11 @@ export function createFileTreeDragMentionController( }) .filter((mention): mention is string => mention !== null); if (mentions.length === 0) { - return; + return null; } draggedPaths = dragged; event.dataTransfer.setData(COMPOSER_MENTION_DRAG_TYPE, mentions.join(" ")); + return itemPath; }, handleDragEnd(deselect) { if (draggedPaths.length === 0) { diff --git a/apps/web/src/fork/dashboard/dashboardLink.tsx b/apps/web/src/fork/dashboard/dashboardLink.tsx index 0a481c8ea879..2c17f39d8f7b 100644 --- a/apps/web/src/fork/dashboard/dashboardLink.tsx +++ b/apps/web/src/fork/dashboard/dashboardLink.tsx @@ -11,6 +11,8 @@ import { selectActiveRightPanel, useRightPanelStore, } from "../../rightPanelStore"; +import { openedSync } from "../rightPanelSplit/linkSources"; +import { type PanelLink, startPanelOnlyDrag } from "../rightPanelSplit/panelLinkDrag"; import { FORK_SURFACES, threadHasModeSurface } from "./dashboardSurface"; /** "open" for the Dashboard link, "inert" for any other `t3-dashboard:` link, null otherwise. */ @@ -25,9 +27,13 @@ export function dashboardLinkLabel(node: unknown, href: string): string { return written === "" || written === href ? "Dashboard" : written; } +function isHostedThread(threadRef: ScopedThreadRef): boolean { + return scopedThreadKey(rightPanelHostRef(threadRef)) !== scopedThreadKey(threadRef); +} + function openThreadDashboard(threadRef: ScopedThreadRef) { // A hosted thread's actions open in its host's panel, which shows the host's Dashboard. - if (scopedThreadKey(rightPanelHostRef(threadRef)) !== scopedThreadKey(threadRef)) { + if (isHostedThread(threadRef)) { toastManager.add({ type: "info", title: "Open this thread on its own to see its Dashboard" }); return; } @@ -42,6 +48,15 @@ function openThreadDashboard(threadRef: ScopedThreadRef) { if (alreadyShown) requestWorkspaceFocus({ area: "panel" }); } +/** What a drop of the chip on a right-panel pane opens, when the click would open the Dashboard. */ +function dashboardPanelLink(threadRef: ScopedThreadRef): PanelLink | null { + if (isHostedThread(threadRef) || !threadHasModeSurface(threadRef, "dashboard")) return null; + return { + panelRef: threadRef, + open: () => openedSync(threadRef, () => openThreadDashboard(threadRef)), + }; +} + /** A chat link to the thread's Dashboard: a chip that opens it, or plain text when it cannot. */ export function DashboardLinkChip(props: { readonly threadRef: ScopedThreadRef | undefined; @@ -58,6 +73,8 @@ export function DashboardLinkChip(props: { aria-label={label === "Dashboard" ? "Open the Dashboard" : `${label}. Open the Dashboard`} data-markdown-copy={`[${label.replace(/[\\[\]*_`<>&]/g, "\\$&")}](${DASHBOARD_LINK_HREF})`} onClick={() => openThreadDashboard(threadRef)} + draggable + onDragStart={(event) => startPanelOnlyDrag(event, dashboardPanelLink(threadRef))} > {label} diff --git a/apps/web/src/fork/rightPanelSplit/PanelLinkDropScope.tsx b/apps/web/src/fork/rightPanelSplit/PanelLinkDropScope.tsx new file mode 100644 index 000000000000..85730051aa84 --- /dev/null +++ b/apps/web/src/fork/rightPanelSplit/PanelLinkDropScope.tsx @@ -0,0 +1,187 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { + type DragEvent as ReactDragEvent, + type ReactNode, + useEffect, + useRef, + useState, +} from "react"; +import { createPortal } from "react-dom"; + +import { useStableCallback } from "~/hooks/useStableCallback"; +import { selectThreadRightPanelState, useRightPanelStore } from "~/rightPanelStore"; + +import { type Rect, samePlan } from "./dropTarget.logic"; +import { + dropEffectFor, + type LinkDropPlan, + type LinkPlacement, + type PaneGeometry, + placementChange, + planLinkDrop, +} from "./linkDrop.logic"; +import { + claimPanelLinkDrop, + type OpenedSurface, + type PanelLink, + PanelLinkOwnerContext, + useOwnedPanelLinkDrag, +} from "./panelLinkDrag"; +import { DropGhostView } from "./RightPanelDragScope"; +import type { PaneSide, SplitChange } from "./splitLayout.logic"; + +function clipped(rect: Rect, to: Rect): Rect | null { + const left = Math.max(rect.left, to.left); + const right = Math.min(rect.right, to.right); + return right <= left ? null : { left, right, top: rect.top, bottom: rect.bottom }; +} + +function measurePanes(scope: HTMLElement): PaneGeometry[] { + return [...scope.querySelectorAll("[data-right-panel-pane]")].flatMap((pane) => { + const strip = pane.querySelector("[data-right-panel-tabbar]"); + const content = pane.querySelector("[data-right-panel-surface-content]"); + const list = pane.querySelector("[data-right-panel-tab-list]"); + if (strip === null || content === null || list === null) return []; + const viewport = list.getBoundingClientRect(); + const tabs = [...list.querySelectorAll("[data-right-panel-tab-id]")].flatMap( + (tab) => { + const rect = clipped(tab.getBoundingClientRect(), viewport); + return rect === null ? [] : [{ id: tab.dataset.rightPanelTabId!, rect }]; + }, + ); + return [ + { + side: (pane.dataset.rightPanelPane as PaneSide | undefined) ?? "left", + strip: strip.getBoundingClientRect(), + content: content.getBoundingClientRect(), + tabs, + }, + ]; + }); +} + +/** A text field takes a dropped link as text. */ +function inTextField(target: EventTarget | null): boolean { + return ( + target instanceof HTMLElement && + (target.isContentEditable || target.closest("input, textarea") !== null) + ); +} + +/** + * The HTML drop target of one ChatView panel, for links dragged from chat or the Files tree. + * Wrap the panes in it, inside the split row; it adds no box of its own. + */ +export function PanelLinkDropScope(props: { + readonly threadRef: ScopedThreadRef; + readonly splitAllowed: boolean; + readonly splitRendered: boolean; + readonly splitGrowth: number; + /** The split view's change, which also widens the panel on a new split. */ + readonly applyChange: (change: SplitChange) => void; + readonly children: ReactNode; +}) { + const { threadRef, splitAllowed, splitRendered, splitGrowth } = props; + const owned = useOwnedPanelLinkDrag(threadRef); + const cancelPending = useRef<(() => void) | null>(null); + const applyChange = useStableCallback(props.applyChange); + const [plan, setPlan] = useState(null); + const shown = useRef(null); + const entered = useRef(null); + const readThread = () => + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, threadRef); + + const show = (next: LinkDropPlan | null) => { + if (samePlan(shown.current, next)) return; + shown.current = next; + setPlan(next); + }; + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- an open still loading must not move a tab after the panel is gone + useEffect(() => () => cancelPending.current?.(), []); + + const place = (link: PanelLink, placement: LinkPlacement) => { + cancelPending.current?.(); + const before = readThread(); + const settle = (opened: OpenedSurface) => { + if (opened === null) return; + const after = readThread(); + if (!after.surfaces.some((surface) => surface.id === opened)) return; + const change = placementChange(before, after, opened, placement); + if (change !== null) applyChange(change); + }; + const result = link.open(); + if (!(result instanceof Promise)) { + settle(result); + return; + } + // Anything the user does before a slow open lands wins over the drop's placement. + const cancel = () => { + document.removeEventListener("pointerdown", cancel, true); + document.removeEventListener("keydown", cancel, true); + if (cancelPending.current === cancel) cancelPending.current = null; + }; + document.addEventListener("pointerdown", cancel, true); + document.addEventListener("keydown", cancel, true); + cancelPending.current = cancel; + void result.then( + (opened) => { + if (cancelPending.current !== cancel) return; + cancel(); + settle(opened); + }, + () => cancel(), + ); + }; + + /** Accepts the drag here and gives its plan, unless a child or a text field takes it. */ + const accept = (event: ReactDragEvent): LinkDropPlan | null => { + // A child claims a drag by stopping it, as the composer does; the Files tree only prevents + // default for its own rows and then drops them as a no-op, so `defaultPrevented` is no claim. + if (!owned || inTextField(event.target)) return null; + const effect = dropEffectFor(event.dataTransfer.effectAllowed); + if (effect === null) return null; + const next = planLinkDrop({ + arrangement: readThread(), + splitRendered, + splitAllowed, + splitGrowth, + panes: measurePanes(event.currentTarget), + pointer: { x: event.clientX, y: event.clientY }, + }); + if (next === null) return null; + event.preventDefault(); + event.dataTransfer.dropEffect = effect; + return next; + }; + + return ( + +
{ + entered.current = event.target; + show(accept(event)); + }} + onDragOver={(event) => show(accept(event))} + onDragLeave={(event) => { + // An enter this scope did not see went outside it, or to a child that claimed the drag. + if (event.relatedTarget !== entered.current) show(null); + }} + onDrop={(event) => { + const accepted = shown.current; + show(null); + if (accepted === null) return; + // An anchor's URL would otherwise navigate the page. + event.preventDefault(); + event.stopPropagation(); + const link = claimPanelLinkDrop(threadRef, event.dataTransfer); + if (link !== null) place(link, accepted.placement); + }} + > + {props.children} +
+ {owned && plan ? createPortal(, document.body) : null} +
+ ); +} diff --git a/apps/web/src/fork/rightPanelSplit/RightPanelDragScope.tsx b/apps/web/src/fork/rightPanelSplit/RightPanelDragScope.tsx index e428f99cf63b..8d4b0e6d2cf1 100644 --- a/apps/web/src/fork/rightPanelSplit/RightPanelDragScope.tsx +++ b/apps/web/src/fork/rightPanelSplit/RightPanelDragScope.tsx @@ -174,7 +174,7 @@ export function RightPanelDragScope(props: { ); } -function DropGhostView({ ghost }: { ghost: DropGhost }) { +export function DropGhostView({ ghost }: { ghost: DropGhost }) { if (ghost.kind === "marker") { return (
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref); -function StubSurface(props: { surface: RightPanelSurface; onRender: (id: string) => void }) { +/** Claims `@mention` drags in the capture phase and stops them, as the chat composer does. */ +function StubComposer(props: { onMention: (text: string) => void }) { + const handlers = makeComposerMentionDragHandlers({ + insertMentionAtEnd: (text) => { + props.onMention(text); + return true; + }, + insertPullRequestAtEnd: () => false, + setDragActive: () => {}, + onInsertRejected: () => {}, + }); + return ( +
+ ); +} + +function StubSurface(props: { + surface: RightPanelSurface; + onRender: (id: string) => void; + onMention: (text: string) => void; +}) { props.onRender(props.surface.id); + if (props.surface.id === "file:page.html") { + return