Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useNativeFileDrag.ts

47 lines1.9 KB

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