Files
warren/frontend/utils/files.ts
2025-09-05 01:22:40 +02:00

99 lines
2.5 KiB
TypeScript

import { copyFile, moveFiles } from '~/lib/api/warrens';
import type { DirectoryEntry } from '~/shared/types';
export function joinPaths(path: string, ...other: string[]): string {
for (const p of other) {
if (!path.endsWith('/')) {
path += '/';
}
path += trim(p, '/');
}
return path;
}
export function getParentPath(path: string): string {
const sliceEnd = Math.max(1, path.lastIndexOf('/'));
return path.slice(0, sliceEnd);
}
export function onDirectoryEntryDrop(
entry: DirectoryEntry,
isParent: boolean = false
): (e: DragEvent) => void {
return async (e: DragEvent) => {
const warrenStore = useWarrenStore();
if (
e.dataTransfer == null ||
warrenStore.current == null ||
warrenStore.current.dir == null
) {
return;
}
if (entry.fileType !== 'directory') {
return;
}
const fileName = e.dataTransfer.getData('application/warren');
if (entry.name === fileName) {
return;
}
const draggedEntry = warrenStore.current.dir.entries.find(
(e) => e.name === fileName
);
if (draggedEntry == null) {
return;
}
const targetPaths = getTargetsFromSelection(
draggedEntry,
warrenStore.selection
).map((currentEntry) =>
joinPaths(warrenStore.current!.path, currentEntry.name)
);
let targetPath: string;
if (isParent) {
targetPath = getParentPath(warrenStore.current.path);
} else {
targetPath = joinPaths(warrenStore.current.path, entry.name);
}
await moveFiles(warrenStore.current.warrenId, targetPaths, targetPath);
};
}
export async function pasteFile(
current: { warrenId: string; path: string; name: string },
target: { warrenId: string; path: string; name: string }
): Promise<boolean> {
if (current.warrenId !== target.warrenId) {
throw new Error('Cross-warren copies are not supported yet');
}
const { success } = await copyFile(
current.warrenId,
joinPaths(current.path, current.name),
joinPaths(target.path, target.name)
);
return success;
}
export function downloadFile(fileName: string, href: string) {
const anchor = document.createElement('a');
anchor.href = href;
anchor.download = fileName;
anchor.rel = 'noopener';
anchor.target = '_blank';
anchor.click();
}