Open History to see the last commit
1import {
2 COMPOSER_MENTION_DRAG_TYPE,
3 composerMentionFromTreePath,
4} from "~/components/chat/composerMentionDrag";
5
6interface FileTreeDragTransfer {
7 setData(format: string, data: string): void;
8}
9
10export interface FileTreeDragStartEvent {
11 readonly dataTransfer: FileTreeDragTransfer | null;
12 composedPath(): ReadonlyArray<unknown>;
13}
14
15export interface FileTreeDragMentionHost {
16 /** The path a dragged row mentions; defaults to the tree path itself. */
17 mentionPath?(treePath: string): string;
18}
19
20export interface FileTreeDragMentionController {
21 isDragInProgress(): boolean;
22 handleSelectionChange(selectedPaths: ReadonlyArray<string>): void;
23 handleDragStart(event: FileTreeDragStartEvent): void;
24 handleDragEnd(deselect: (treePath: string) => void): void;
25}
26
27const itemPathOf = (node: unknown): string | null => {
28 if (typeof node !== "object" || node === null) {
29 return null;
30 }
31 const element = node as { getAttribute?: (name: string) => string | null };
32 return typeof element.getAttribute === "function" ? element.getAttribute("data-item-path") : null;
33};
34
35export function createFileTreeDragMentionController(
36 host: FileTreeDragMentionHost,
37): FileTreeDragMentionController {
38 let selection: ReadonlyArray<string> = [];
39 let draggedPaths: ReadonlyArray<string> = [];
40 return {
41 isDragInProgress: () => draggedPaths.length > 0,
42 handleSelectionChange(selectedPaths) {
43 selection = selectedPaths;
44 },
45 handleDragStart(event) {
46 if (event.dataTransfer === null) {
47 return;
48 }
49 // Only drags that originate on a tree row are mentions; a text/plain
50 // fallback would also tag drags of selected text from the panel chrome.
51 let itemPath: string | null = null;
52 for (const node of event.composedPath()) {
53 itemPath = itemPathOf(node);
54 if (itemPath !== null) {
55 break;
56 }
57 }
58 if (itemPath === null) {
59 return;
60 }
61 const dragged = selection.includes(itemPath) ? selection : [itemPath];
62 const mentions = dragged
63 .map((path) => {
64 const treePath = path.replace(/\/+$/, "");
65 return composerMentionFromTreePath(
66 treePath && host.mentionPath ? host.mentionPath(treePath) : path,
67 );
68 })
69 .filter((mention): mention is string => mention !== null);
70 if (mentions.length === 0) {
71 return;
72 }
73 draggedPaths = dragged;
74 event.dataTransfer.setData(COMPOSER_MENTION_DRAG_TYPE, mentions.join(" "));
75 },
76 handleDragEnd(deselect) {
77 if (draggedPaths.length === 0) {
78 return;
79 }
80 for (const path of draggedPaths) {
81 deselect(path);
82 }
83 draggedPaths = [];
84 },
85 };
86}