Tele-v / src /components /Modals.tsx
oga3oga's picture
try-mistral-workspace-edit
b246ace verified
Raw History Blame Contribute Delete
25.3 kB
import { useEffect, useState, useRef } from "react";
import type { FileEntry } from "../types";
import { api } from "../api";
import { fmt } from "../utils";
import { extractStorageCredentials, exportCredentialsToFile, importCredentialsFromFile, mergeCredentialsIntoSettings } from "../utils/credentials";
interface MergeItem { uid: string; file: FileEntry; }
// ─── MergeModal ──────────────────────────────────────────────────────────────
export function MergeModal({ files, onClose, onMergeStarted }: {
files: FileEntry[];
onClose: () => void;
onMergeStarted: () => void;
}) {
const [items, setItems] = useState<MergeItem[]>(() =>
files.map((f) => ({ uid: `$${f.id}_$${Math.random().toString(16).slice(2)}`, file: f }))
);
const [outName, setOutName] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const dragUid = useRef<string | null>(null);
const dragOverUid = useRef<string | null>(null);
useEffect(() => {
const firstFile = files[0];
if (!firstFile) {
setOutName("merged_output.mkv");
return;
}
const name = firstFile.name;
const lastDotIndex = name.lastIndexOf(".");
if (lastDotIndex > 0) {
const baseName = name.slice(0, lastDotIndex);
const ext = name.slice(lastDotIndex);
setOutName(`$${baseName}_merged$${ext}`);
} else {
setOutName(`${name}_merged.mkv`);
}
}, [files]);
const moveUp = (idx: number) => {
if (idx === 0) return;
const next = [...items]; [next[idx - 1], next[idx]] = [next[idx], next[idx - 1]]; setItems(next);
};
const moveDown = (idx: number) => {
if (idx === items.length - 1) return;
const next = [...items]; [next[idx], next[idx + 1]] = [next[idx + 1], next[idx]]; setItems(next);
};
const handleDragStart = (uid: string) => { dragUid.current = uid; };
const handleDragOver = (e: React.DragEvent, uid: string) => { e.preventDefault(); dragOverUid.current = uid; };
const handleDrop = () => {
if (!dragUid.current || !dragOverUid.current || dragUid.current === dragOverUid.current) return;
const from = items.findIndex((i) => i.uid === dragUid.current);
const to = items.findIndex((i) => i.uid === dragOverUid.current);
if (from === -1 || to === -1) return;
const next = [...items];
const [moved] = next.splice(from, 1);
next.splice(to, 0, moved);
setItems(next);
dragUid.current = null; dragOverUid.current = null;
};
const removeItem = (uid: string) => setItems((prev) => prev.filter((i) => i.uid !== uid));
const handleMerge = async () => {
if (items.length < 2) { setError("Need at least 2 files to merge"); return; }
if (!outName.trim()) { setError("Output filename is required"); return; }
setError(null); setBusy(true);
try {
const r = await fetch("/api/merge", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fileIds: items.map((i) => i.file.id), outputFilename: outName.trim() }),
});
const data = await r.json();
if (data.error) { setError(data.error); setBusy(false); return; }
onMergeStarted();
onClose();
} catch { setError("Failed to start merge"); setBusy(false); }
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}>
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] flex flex-col" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 flex-shrink-0">
<div className="flex items-center gap-2">
<span className="text-lg">πŸ”—</span>
<h2 className="text-sm font-bold text-slate-800">Merge Files</h2>
<span className="rounded-full bg-violet-100 px-2 py-0.5 text-xs font-semibold text-violet-700">{items.length} files</span>
</div>
<button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors">
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
</svg>
</button>
</div>
<div className="flex-1 overflow-y-auto p-5 space-y-3">
<div className="text-[11px] text-slate-400 bg-slate-50 rounded-lg px-3 py-2">
Drag rows or use ↑↓ to set order. Files joined topβ†’bottom via stream copy (lossless, instant).
</div>
<div className="rounded-xl border border-slate-200 bg-white overflow-hidden divide-y divide-slate-100">
{items.map((item, idx) => (
<div key={item.uid} draggable onDragStart={() => handleDragStart(item.uid)}
onDragOver={(e) => handleDragOver(e, item.uid)} onDrop={handleDrop}
className="flex items-center gap-3 px-4 py-3 hover:bg-slate-50 cursor-grab active:cursor-grabbing transition-colors">
<svg className="h-4 w-4 flex-shrink-0 text-slate-300" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 9h16.5m-16.5 6.75h16.5" />
</svg>
<span className="flex h-6 w-6 items-center justify-center rounded-full bg-violet-100 text-[11px] font-bold text-violet-700 flex-shrink-0">{idx + 1}</span>
<div className="flex-1 min-w-0">
<p className="truncate text-sm font-medium text-slate-800" title={item.file.name}>{item.file.name}</p>
<p className="text-[10px] text-slate-400">{fmt(item.file.sizeBytes)} Β· {item.file.folder}</p>
</div>
<div className="flex items-center gap-1 flex-shrink-0">
<button onClick={() => moveUp(idx)} disabled={idx === 0}
className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed">
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="m4.5 15.75 7.5-7.5 7.5 7.5" />
</svg>
</button>
<button onClick={() => moveDown(idx)} disabled={idx === items.length - 1}
className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed">
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
</svg>
</button>
{items.length > 2 && (
<button onClick={() => removeItem(item.uid)}
className="rounded p-1 text-red-400 hover:bg-red-50 hover:text-red-600">
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
</div>
))}
</div>
<div className="space-y-1">
<label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Output Filename</label>
<input type="text" value={outName} onChange={(e) => setOutName(e.target.value)}
className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" />
</div>
{error && <p className="text-xs text-red-500">{error}</p>}
<div className="text-xs text-slate-400 bg-slate-50 rounded-lg px-3 py-2">
πŸ’‘ Output saved to same folder as the first selected file. Stream copy = instant, lossless.
</div>
</div>
<div className="px-5 pb-5 flex-shrink-0">
<button onClick={handleMerge} disabled={busy || items.length < 2 || !outName.trim()}
className="w-full rounded-xl bg-violet-600 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-violet-700 disabled:opacity-50">
{busy ? "Starting Merge…" : `πŸ”— Merge ${items.length} Files`}
</button>
</div>
</div>
</div>
);
}
// ─── MoveModal ───────────────────────────────────────────────────────────────
export function MoveModal({ files, folders, onClose, onMoved }: {
files: FileEntry[];
folders: string[];
onClose: () => void;
onMoved: () => void;
}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const itemCount = files.length;
const handleMove = async (targetFolder: string) => {
if (files.every((f) => (f.folder || "/") === targetFolder)) { onClose(); return; }
setBusy(true); setError(null);
try {
const ids = files.map((f) => f.id);
const data = await api.batchMove(ids, targetFolder);
if (data.error) { setError(data.error); setBusy(false); return; }
onMoved();
onClose();
} catch { setError("Failed to move file(s)"); setBusy(false); }
};
const allFolders = Array.from(new Set(["/", ...folders])).sort((a, b) => {
if (a === "/") return -1; if (b === "/") return 1; return a.localeCompare(b);
});
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}>
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-sm" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
<div className="flex items-center gap-2 min-w-0">
<span className="text-lg flex-shrink-0">↗️</span>
<div className="min-w-0">
<h2 className="text-sm font-bold text-slate-800">Move {itemCount === 1 ? "File" : `${itemCount} Files`}</h2>
<p className="text-[10px] text-slate-400 truncate">
{itemCount === 1 ? files[0].name : `${itemCount} selected files`}
</p>
</div>
</div>
<button onClick={onClose} className="flex-shrink-0 rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600">
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
</svg>
</button>
</div>
<div className="p-4 space-y-2">
<p className="text-xs text-slate-500 mb-3">Select destination folder:</p>
{error && <p className="text-xs text-red-500 mb-2">{error}</p>}
<div className="rounded-xl border border-slate-200 overflow-hidden divide-y divide-slate-100 max-h-64 overflow-y-auto">
{allFolders.map((folder) => {
const isCurrent = files.every((f) => (f.folder || "/") === folder);
return (
<button key={folder} onClick={() => !busy && handleMove(folder)} disabled={busy || isCurrent}
className={`w-full flex items-center gap-3 px-4 py-3 text-left transition-colors ${
isCurrent ? "bg-violet-50 cursor-not-allowed" : "hover:bg-slate-50"
}`}>
<svg className={`h-4 w-4 flex-shrink-0 ${isCurrent ? "text-violet-500" : "text-amber-500"}`} fill="currentColor" viewBox="0 0 24 24">
<path d="M19.5 21a3 3 0 0 0 3-3v-4.5a3 3 0 0 0-3-3h-15a3 3 0 0 0-3 3V18a3 3 0 0 0 3 3h15ZM1.5 10.146V6a3 3 0 0 1 3-3h5.379a2.25 2.25 0 0 1 1.59.659l2.122 2.121c.14.141.331.22.53.22H19.5a3 3 0 0 1 3 3v1.146A4.483 4.483 0 0 0 19.5 12h-15a4.483 4.483 0 0 0-3 1.146V10.146Z" />
</svg>
<span className={`text-sm font-medium flex-1 truncate ${isCurrent ? "text-violet-700" : "text-slate-700"}`}>
{folder === "/" ? "/ (root)" : folder}
</span>
{isCurrent && (
<span className="text-[10px] text-violet-500 font-semibold flex-shrink-0">current</span>
)}
</button>
);
})}
</div>
{busy && <p className="text-xs text-slate-400 text-center">Moving…</p>}
</div>
</div>
</div>
);
}
// ─── CreateFolderModal ───────────────────────────────────────────────────────
export function CreateFolderModal({ onClose, onCreated }: { onClose: () => void; onCreated: (name: string) => void }) {
const [name, setName] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleCreate = async () => {
const trimmed = name.trim();
if (!trimmed) { setError("Folder name is required"); return; }
setBusy(true); setError(null);
try {
const data = await api.createFolder(trimmed);
if (data.error) { setError(data.error); setBusy(false); return; }
onCreated(data.folder ?? `/${trimmed}`);
onClose();
} catch { setError("Failed to create folder"); setBusy(false); }
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}>
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-xs" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
<div className="flex items-center gap-2">
<span className="text-lg">πŸ“</span>
<h2 className="text-sm font-bold text-slate-800">New Folder</h2>
</div>
<button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600">
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
</svg>
</button>
</div>
<div className="p-5 space-y-4">
<input autoFocus type="text" placeholder="Folder name…" value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleCreate(); if (e.key === "Escape") onClose(); }}
className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" />
{error && <p className="text-xs text-red-500">{error}</p>}
<button onClick={handleCreate} disabled={busy || !name.trim()}
className="w-full rounded-xl bg-violet-600 py-2.5 text-sm font-semibold text-white hover:bg-violet-700 disabled:opacity-50 transition-colors">
{busy ? "Creating…" : "Create Folder"}
</button>
</div>
</div>
</div>
);
}
// ─── PreviewModal ────────────────────────────────────────────────────────────
export function PreviewModal({ title, url, onClose }: { title: string; url: string; onClose: () => void }) {
return (
<div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/70 backdrop-blur-sm p-4" onClick={onClose}>
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between px-5 py-3 border-b border-slate-100">
<h2 className="text-sm font-bold text-slate-800 truncate pr-2">{title}</h2>
<button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600">
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
</svg>
</button>
</div>
<div className="p-2">
<img src={url} alt={title} className="w-full rounded-xl max-h-[80vh] object-contain" />
</div>
</div>
</div>
);
}
// ─── CredentialsModal ──────────────────────────────────────────────────────────
export function CredentialsModal({ settings, onClose, onSettingsUpdated }: {
settings: any;
onClose: () => void;
onSettingsUpdated: (newSettings: any) => void;
}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const [importFile, setImportFile] = useState<File | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const handleExport = () => {
try {
const credentials = extractStorageCredentials(settings);
exportCredentialsToFile(credentials, 'storage_credentials.json');
setSuccess('Credentials exported successfully!');
setTimeout(() => setSuccess(null), 3000);
} catch (err) {
setError('Failed to export credentials');
console.error('Export error:', err);
}
};
const handleImportFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
setImportFile(file);
setError(null);
setSuccess(null);
}
};
const handleImport = async () => {
if (!importFile) return;
setBusy(true);
setError(null);
setSuccess(null);
try {
const importedCredentials = await importCredentialsFromFile(importFile);
const mergedSettings = mergeCredentialsIntoSettings(settings, importedCredentials);
// Save the merged settings
const response = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(mergedSettings)
});
if (!response.ok) {
throw new Error('Failed to save settings');
}
setSuccess('Credentials imported successfully!');
onSettingsUpdated(mergedSettings);
setTimeout(() => {
setSuccess(null);
onClose();
}, 2000);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to import credentials');
console.error('Import error:', err);
} finally {
setBusy(false);
setImportFile(null);
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}
};
const handleCancelImport = () => {
setImportFile(null);
setError(null);
setSuccess(null);
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};
const credentials = extractStorageCredentials(settings);
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}>
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-md" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
<div className="flex items-center gap-2">
<span className="text-lg">πŸ”‘</span>
<h2 className="text-sm font-bold text-slate-800">Storage Credentials Manager</h2>
</div>
<button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600">
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
</svg>
</button>
</div>
<div className="p-5 space-y-4">
<div className="space-y-2">
<h3 className="text-sm font-semibold text-slate-700">Export Credentials</h3>
<p className="text-xs text-slate-500">Download your storage credentials to import into another instance.</p>
<button
onClick={handleExport}
disabled={busy}
className="w-full rounded-xl bg-green-600 py-2.5 text-sm font-semibold text-white hover:bg-green-700 disabled:opacity-50 transition-colors"
>
πŸ“₯ Export Credentials
</button>
</div>
<div className="space-y-2">
<h3 className="text-sm font-semibold text-slate-700">Import Credentials</h3>
<p className="text-xs text-slate-500">Upload a credentials file to import storage settings.</p>
{!importFile ? (
<label className="block">
<input
type="file"
ref={fileInputRef}
onChange={handleImportFileChange}
accept=".json"
className="hidden"
disabled={busy}
/>
<div className="w-full rounded-xl border-2 border-dashed border-slate-300 py-3 text-center cursor-pointer hover:border-slate-400 transition-colors">
<span className="text-sm font-medium text-slate-600">πŸ“ Choose Credentials File</span>
</div>
</label>
) : (
<div className="space-y-2">
<div className="flex items-center gap-2 p-2 bg-slate-50 rounded-lg">
<span className="text-xs font-medium text-slate-700 truncate flex-1">πŸ“„ {importFile.name}</span>
<button
onClick={handleCancelImport}
disabled={busy}
className="text-slate-400 hover:text-slate-600 disabled:opacity-50"
>
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
</svg>
</button>
</div>
<button
onClick={handleImport}
disabled={busy}
className="w-full rounded-xl bg-blue-600 py-2.5 text-sm font-semibold text-white hover:bg-blue-700 disabled:opacity-50 transition-colors"
>
{busy ? 'Importing…' : 'πŸ“€ Import Credentials'}
</button>
</div>
)}
</div>
{error && (
<div className="p-3 bg-red-50 rounded-lg">
<p className="text-xs text-red-600 font-medium">❌ {error}</p>
</div>
)}
{success && (
<div className="p-3 bg-green-50 rounded-lg">
<p className="text-xs text-green-600 font-medium">βœ… {success}</p>
</div>
)}
<div className="pt-4 border-t border-slate-100">
<h4 className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">Credentials Summary</h4>
<div className="space-y-2 text-xs">
<div className="flex justify-between">
<span className="text-slate-500">B2 Connections:</span>
<span className="font-medium">{credentials.b2SavedConnections?.length || 0}</span>
</div>
<div className="flex justify-between">
<span className="text-slate-500">Remote URLs:</span>
<span className="font-medium">{credentials.remoteUrlHistory?.length || 0}</span>
</div>
<div className="flex justify-between">
<span className="text-slate-500">Per-remote creds:</span>
<span className="font-medium">{credentials.remoteCredentials ? Object.keys(credentials.remoteCredentials).length : 0}</span>
</div>
<div className="flex justify-between">
<span className="text-slate-500">Current Remote:</span>
<span className="font-medium truncate max-w-[150px]">{credentials.remoteUrl || 'None'}</span>
</div>
<div className="flex justify-between">
<span className="text-slate-500">Legacy HF Token:</span>
<span className="font-medium">{credentials.remoteHfToken ? 'βœ“ Set' : 'Not set'}</span>
</div>
</div>
</div>
</div>
</div>
</div>
);
}