Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { splitFilePathPosition } from "@t3tools/shared/fileLinks";
3import { isMacPlatform, isWindowsPlatform } from "./lib/utils";
4import { useAtomValue } from "@effect/atom-react";
5import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts";
6import { msg } from "gt-react";
7import type { DragEvent } from "react";
8
9import { hostEnvironmentIdAtom } from "./state/primaryEnvironment";
10import { useEnvironmentScope } from "./state/session";
11import { toastManager } from "./components/ui/toast";
12import { m } from "./i18n/messages";
13
14export function useNativeFileDrag(
15 environmentId: EnvironmentId | null | undefined,
16 resolvePath: () => string | Promise<string>,
17) {
18 const hostEnvironmentId = useAtomValue(hostEnvironmentIdAtom);
19 const canOperate = useEnvironmentScope(environmentId ?? null, AuthOrchestrationOperateScope);
20 const enabled =
21 typeof window.desktopBridge?.startFileDrag === "function" &&
22 (isMacPlatform(navigator.platform) || isWindowsPlatform(navigator.platform)) &&
23 environmentId != null &&
24 environmentId === hostEnvironmentId &&
25 canOperate;
26 return {
27 draggable: enabled || undefined,
28 onDragStart: (event: DragEvent<HTMLElement>) => {
29 if (!enabled) return;
30 // Electron replaces the HTML drag with a native file drag.
31 event.preventDefault();
32 event.stopPropagation();
33 let released = false;
34 window.addEventListener("pointerup", () => (released = true), { once: true });
35 void (async () => {
36 const { path } = splitFilePathPosition(await resolvePath());
37 if (released) return;
38 const started = await window.desktopBridge?.startFileDrag({ environmentId, path });
39 if (!started) throw new Error(m(msg("The file is unavailable on this computer.")));
40 })().catch((error: unknown) => {
41 if (released) return;
42 toastManager.add({
43 type: "error",
44 title: m(msg("Unable to drag file")),
45 description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")),
46 });
47 });
48 },
49 };
50}