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