Initial commit: RomM Companion desktop v0.1.0
CI / frontend (push) Successful in 56s
CI / rust-check (push) Successful in 3m25s

This commit is contained in:
Seth Wade committed 2026-11-30 22:27:44 -05:00
commit 238a23c528
41 files changed
+17214

No files matched your search

+247
View File
@@ -0,0 +1,247 @@
import React from "react";
import {
AlertTriangle,
CheckCircle2,
CloudDownload,
CloudUpload,
Eye,
FolderSync,
HardDrive,
Loader2,
RefreshCw,
Trash2,
} from "lucide-react";
import type { AppStateSnapshot, DiscoveredSaveItem, SyncRunSummary } from "../lib/types";
interface Props {
appState: AppStateSnapshot;
discoveredSaves: DiscoveredSaveItem[];
syncing: boolean;
lastSummary: SyncRunSummary | null;
onSyncNow: () => void;
onResolveConflict: (id: string, resolution: "keep_local" | "keep_server") => void;
onClearLogs: () => void;
onAutoDetect: () => void;
}
export const Dashboard: React.FC<Props> = ({
appState,
discoveredSaves,
syncing,
lastSummary,
onSyncNow,
onResolveConflict,
onClearLogs,
onAutoDetect,
}) => {
const matchedCount = discoveredSaves.filter((s) => s.matchedRomId !== null).length;
const enabledEmulators = appState.emulators.filter((e) => e.enabled).length;
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-bold tracking-tight">Dashboard</h2>
<p className="text-sm text-slate-400">
Connected to <span className="text-slate-200">{appState.serverUrl}</span> as{" "}
<span className="text-indigo-400 font-medium">{appState.username}</span>
</p>
</div>
<div className="flex items-center gap-2.5">
{appState.emulators.length === 0 && (
<button
onClick={onAutoDetect}
className="px-4 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-sm font-medium transition cursor-pointer"
>
Auto-Detect Emulators
</button>
)}
<button
onClick={onSyncNow}
disabled={syncing}
className="px-4 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-sm font-medium flex items-center gap-2 shadow-lg shadow-indigo-950/50 transition cursor-pointer disabled:opacity-50"
>
{syncing ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<RefreshCw className="w-4 h-4" />
)}
{syncing ? "Syncing..." : "Sync Saves & States"}
</button>
</div>
</div>
{/* Stat Cards */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<div className="p-4 rounded-xl bg-slate-900/80 border border-slate-800">
<div className="flex items-center justify-between text-slate-400 text-xs font-medium mb-2">
<span>ACTIVE EMULATORS</span>
<HardDrive className="w-4 h-4 text-indigo-400" />
</div>
<div className="text-2xl font-bold">{enabledEmulators}</div>
<div className="text-xs text-slate-500 mt-1">
{appState.emulators.length} configured rules
</div>
</div>
<div className="p-4 rounded-xl bg-slate-900/80 border border-slate-800">
<div className="flex items-center justify-between text-slate-400 text-xs font-medium mb-2">
<span>MATCHED SAVES / STATES</span>
<FolderSync className="w-4 h-4 text-emerald-400" />
</div>
<div className="text-2xl font-bold">
{matchedCount}{" "}
<span className="text-sm font-normal text-slate-500">/ {discoveredSaves.length}</span>
</div>
<div className="text-xs text-slate-500 mt-1">
{appState.cachedRomCount} ROMs indexed from RomM
</div>
</div>
<div className="p-4 rounded-xl bg-slate-900/80 border border-slate-800">
<div className="flex items-center justify-between text-slate-400 text-xs font-medium mb-2">
<span>FILE WATCHER</span>
<Eye
className={`w-4 h-4 ${appState.watcherActive ? "text-emerald-400" : "text-slate-500"}`}
/>
</div>
<div className="text-2xl font-bold">
{appState.watcherActive ? "Active" : "Paused"}
</div>
<div className="text-xs text-slate-500 mt-1">
Watching {appState.watchedPaths.length} folder(s)
</div>
</div>
<div className="p-4 rounded-xl bg-slate-900/80 border border-slate-800">
<div className="flex items-center justify-between text-slate-400 text-xs font-medium mb-2">
<span>CONFLICTS</span>
<AlertTriangle
className={`w-4 h-4 ${appState.conflicts.length > 0 ? "text-amber-400" : "text-slate-500"}`}
/>
</div>
<div className="text-2xl font-bold">{appState.conflicts.length}</div>
<div className="text-xs text-slate-500 mt-1">
{appState.conflicts.length === 0 ? "All saves clean" : "Needs your decision"}
</div>
</div>
</div>
{/* Last Sync Summary Banner */}
{lastSummary && (
<div className="p-4 rounded-xl bg-indigo-950/40 border border-indigo-500/30 flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2.5 text-sm">
<CheckCircle2 className="w-5 h-5 text-emerald-400 shrink-0" />
<span>
Last sync completed: <strong>{lastSummary.uploadedSaves}</strong> saves uploaded,{" "}
<strong>{lastSummary.downloadedSaves}</strong> downloaded,{" "}
<strong>{lastSummary.uploadedStates}</strong> states synced,{" "}
<strong>{lastSummary.upToDate}</strong> already up to date.
</span>
</div>
{lastSummary.errors.length > 0 && (
<span className="text-xs text-rose-300">
{lastSummary.errors.length} error(s) — check log below
</span>
)}
</div>
)}
{/* Pending Conflicts */}
{appState.conflicts.length > 0 && (
<div className="space-y-3">
<h3 className="text-sm font-semibold uppercase tracking-wider text-amber-400 flex items-center gap-2">
<AlertTriangle className="w-4 h-4" /> Save Conflicts Requiring Resolution
</h3>
<div className="space-y-2.5">
{appState.conflicts.map((c) => (
<div
key={c.id}
className="p-4 rounded-xl bg-amber-950/25 border border-amber-500/40 flex flex-wrap items-center justify-between gap-4"
>
<div className="space-y-1">
<div className="font-semibold text-sm">
{c.romName}{" "}
<span className="text-xs font-normal text-slate-400">
({c.fileName} • slot: {c.slot})
</span>
</div>
<div className="text-xs text-slate-400">{c.reason}</div>
<div className="text-xs text-slate-500">
Local: {new Date(c.localUpdatedAt).toLocaleString()} | Server:{" "}
{c.serverUpdatedAt ? new Date(c.serverUpdatedAt).toLocaleString() : "Unknown"}
</div>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => onResolveConflict(c.id, "keep_local")}
className="px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-xs font-medium flex items-center gap-1.5 cursor-pointer"
>
<CloudUpload className="w-3.5 h-3.5" /> Keep Local (Upload)
</button>
<button
onClick={() => onResolveConflict(c.id, "keep_server")}
className="px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-xs font-medium flex items-center gap-1.5 cursor-pointer"
>
<CloudDownload className="w-3.5 h-3.5" /> Keep Server (Backup Local)
</button>
</div>
</div>
))}
</div>
</div>
)}
{/* Activity Log */}
<div className="rounded-xl bg-slate-900/80 border border-slate-800 overflow-hidden">
<div className="px-4 py-3 border-b border-slate-800 flex items-center justify-between">
<h3 className="text-sm font-semibold">Recent Sync Activity</h3>
{appState.logs.length > 0 && (
<button
onClick={onClearLogs}
className="text-xs text-slate-400 hover:text-slate-200 flex items-center gap-1 cursor-pointer"
>
<Trash2 className="w-3.5 h-3.5" /> Clear
</button>
)}
</div>
<div className="divide-y divide-slate-800/70 max-h-80 overflow-y-auto">
{appState.logs.length === 0 ? (
<div className="p-6 text-center text-sm text-slate-500">
No sync activity yet. Configure an emulator and click <strong>Sync Saves & States</strong>.
</div>
) : (
appState.logs.slice(0, 50).map((log) => (
<div key={log.id} className="px-4 py-2.5 flex items-start justify-between gap-3 text-xs">
<div className="flex items-start gap-2.5">
<span
className={`mt-1 w-2 h-2 rounded-full shrink-0 ${
log.level === "success"
? "bg-emerald-400"
: log.level === "warning"
? "bg-amber-400"
: log.level === "error"
? "bg-rose-400"
: "bg-sky-400"
}`}
/>
<div>
<div className="text-slate-200">{log.message}</div>
{log.filePath && (
<div className="text-[11px] text-slate-500 font-mono truncate max-w-xl">
{log.filePath}
</div>
)}
</div>
</div>
<span className="text-slate-500 shrink-0">
{new Date(log.timestamp).toLocaleTimeString()}
</span>
</div>
))
)}
</div>
</div>
</div>
);
};
+487
View File
@@ -0,0 +1,487 @@
import React, { useEffect, useState } from "react";
import {
CheckCircle2,
FolderOpen,
Plus,
Sparkles,
Trash2,
X,
} from "lucide-react";
import { api } from "../lib/tauri";
import type { EmulatorPresetInfo, EmulatorRule, SaveStructure } from "../lib/types";
interface Props {
emulators: EmulatorRule[];
onRefreshState: () => Promise<void>;
}
export const EmulatorsView: React.FC<Props> = ({ emulators, onRefreshState }) => {
const [presets, setPresets] = useState<EmulatorPresetInfo[]>([]);
const [editing, setEditing] = useState<EmulatorRule | null>(null);
const [extInput, setExtInput] = useState("");
const [stateExtInput, setStateExtInput] = useState("");
const [slugInput, setSlugInput] = useState("");
useEffect(() => {
api.getEmulatorPresets().then(setPresets).catch(console.error);
}, []);
const openEditor = (rule: EmulatorRule) => {
setEditing({ ...rule });
setExtInput(rule.saveExtensions.join(", "));
setStateExtInput(rule.stateExtensions.join(", "));
setSlugInput(rule.platformSlugs.join(", "));
};
const handleAddPreset = async (p: EmulatorPresetInfo) => {
const rule: EmulatorRule = {
id: p.id,
name: p.name,
platformSlugs: p.platformSlugs,
saveDir: p.detectedSaveDir || p.defaultSaveDir,
stateDir: p.detectedStateDir || p.defaultStateDir,
romDir: null,
saveExtensions: p.saveExtensions,
stateExtensions: p.stateExtensions,
structure: p.structure,
folderDepth: p.folderDepth || 1,
enabled: true,
isCustom: false,
syncStates: Boolean(p.detectedStateDir || p.defaultStateDir),
defaultSlot: "default",
};
openEditor(rule);
};
const handleNewCustom = () => {
openEditor({
id: `custom-${Date.now()}`,
name: "Custom Emulator",
platformSlugs: [],
saveDir: "",
stateDir: null,
romDir: null,
saveExtensions: ["sav", "srm"],
stateExtensions: ["state"],
structure: "file_per_game",
folderDepth: 1,
enabled: true,
isCustom: true,
syncStates: false,
defaultSlot: "default",
});
};
const handleSaveRule = async (e: React.FormEvent) => {
e.preventDefault();
if (!editing) return;
const cleaned: EmulatorRule = {
...editing,
saveExtensions: extInput
.split(",")
.map((s) => s.trim().replace(/^\./, ""))
.filter(Boolean),
stateExtensions: stateExtInput
.split(",")
.map((s) => s.trim().replace(/^\./, ""))
.filter(Boolean),
platformSlugs: slugInput
.split(",")
.map((s) => s.trim().toLowerCase())
.filter(Boolean),
};
await api.upsertEmulatorRule(cleaned);
setEditing(null);
await onRefreshState();
};
const handleToggleEnabled = async (rule: EmulatorRule) => {
await api.upsertEmulatorRule({ ...rule, enabled: !rule.enabled });
await onRefreshState();
};
const handleDelete = async (id: string) => {
await api.deleteEmulatorRule(id);
await onRefreshState();
};
const handleAutoDetectAll = async () => {
await api.autoPopulateDetectedEmulators();
await onRefreshState();
};
const configuredIds = new Set(emulators.map((e) => e.id));
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-bold tracking-tight">Emulators & Save Rules</h2>
<p className="text-sm text-slate-400">
Auto-detect standalone console & handheld emulators or define custom save folders.
</p>
</div>
<div className="flex items-center gap-2">
<button
onClick={handleAutoDetectAll}
className="px-3.5 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-sm font-medium flex items-center gap-2 cursor-pointer"
>
<Sparkles className="w-4 h-4 text-indigo-400" /> Auto-Add Detected
</button>
<button
onClick={handleNewCustom}
className="px-3.5 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-sm font-medium flex items-center gap-2 cursor-pointer"
>
<Plus className="w-4 h-4" /> Custom Rule
</button>
</div>
</div>
{/* Configured Rules */}
<div className="space-y-3">
<h3 className="text-xs font-semibold uppercase tracking-wider text-slate-400">
Configured Rules ({emulators.length})
</h3>
{emulators.length === 0 ? (
<div className="p-6 rounded-xl bg-slate-900/60 border border-dashed border-slate-800 text-center text-sm text-slate-400">
No emulators configured yet. Click <strong>Auto-Add Detected</strong> or pick a preset
below.
</div>
) : (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{emulators.map((rule) => (
<div
key={rule.id}
className="p-4 rounded-xl bg-slate-900/90 border border-slate-800 flex flex-col justify-between gap-3"
>
<div className="flex items-start justify-between gap-3">
<div>
<div className="flex items-center gap-2">
<span className="font-semibold text-sm">{rule.name}</span>
<span className="text-[11px] px-2 py-0.5 rounded-full bg-slate-800 text-slate-300">
{rule.structure.replace(/_/g, " ")}
</span>
</div>
<div className="text-xs text-slate-400 font-mono mt-1 break-all">
Saves: {rule.saveDir || "(not set)"}
</div>
{rule.romDir && (
<div className="text-xs text-emerald-400/90 font-mono break-all">
ROMs: {rule.romDir}
</div>
)}
{rule.syncStates && rule.stateDir && (
<div className="text-xs text-slate-500 font-mono break-all">
States: {rule.stateDir}
</div>
)}
</div>
<label className="inline-flex items-center cursor-pointer">
<input
type="checkbox"
checked={rule.enabled}
onChange={() => handleToggleEnabled(rule)}
className="sr-only peer"
/>
<div className="w-9 h-5 bg-slate-700 rounded-full peer peer-checked:bg-indigo-600 relative after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-4" />
</label>
</div>
<div className="flex items-center justify-between pt-2 border-t border-slate-800/80">
<div className="flex flex-wrap gap-1">
{rule.platformSlugs.map((slug) => (
<span
key={slug}
className="text-[10px] uppercase px-1.5 py-0.5 rounded bg-indigo-950/70 text-indigo-300 border border-indigo-500/20"
>
{slug}
</span>
))}
</div>
<div className="flex items-center gap-2">
<button
onClick={() => openEditor(rule)}
className="text-xs text-indigo-400 hover:text-indigo-300 font-medium cursor-pointer"
>
Edit
</button>
<button
onClick={() => handleDelete(rule.id)}
className="text-xs text-slate-500 hover:text-rose-400 cursor-pointer"
title="Remove rule"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
</div>
</div>
))}
</div>
)}
</div>
{/* Presets Catalog */}
<div className="space-y-3">
<h3 className="text-xs font-semibold uppercase tracking-wider text-slate-400">
Built-In Emulator Presets
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{presets.map((p) => {
const added = configuredIds.has(p.id);
return (
<div
key={p.id}
className="p-4 rounded-xl bg-slate-900/60 border border-slate-800/90 flex flex-col justify-between gap-3"
>
<div>
<div className="flex items-center justify-between gap-2">
<span className="font-medium text-sm">{p.name}</span>
{p.detected ? (
<span className="inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-emerald-950/70 text-emerald-300 border border-emerald-500/30">
<CheckCircle2 className="w-3 h-3" /> Detected
</span>
) : (
<span className="text-[11px] px-2 py-0.5 rounded-full bg-slate-800 text-slate-400">
Not found
</span>
)}
</div>
<p className="text-xs text-slate-400 mt-1.5 leading-relaxed">{p.notes}</p>
</div>
<div className="flex items-center justify-between">
<span className="text-[11px] text-slate-500 capitalize">{p.category}</span>
<button
onClick={() => handleAddPreset(p)}
className={`px-3 py-1 rounded-lg text-xs font-medium cursor-pointer transition ${
added
? "bg-slate-800 text-slate-300 hover:bg-slate-700"
: "bg-indigo-600/20 text-indigo-300 border border-indigo-500/30 hover:bg-indigo-600/30"
}`}
>
{added ? "Reconfigure" : "+ Add Preset"}
</button>
</div>
</div>
);
})}
</div>
</div>
{/* Edit Modal */}
{editing && (
<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4">
<form
onSubmit={handleSaveRule}
className="w-full max-w-lg bg-slate-900 border border-slate-800 rounded-2xl p-6 space-y-4 shadow-2xl max-h-[90vh] overflow-y-auto"
>
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">Configure Emulator Rule</h3>
<button
type="button"
onClick={() => setEditing(null)}
className="text-slate-400 hover:text-white cursor-pointer"
>
<X className="w-5 h-5" />
</button>
</div>
<div className="space-y-3">
<div>
<label className="block text-xs text-slate-400 mb-1">Display Name</label>
<input
required
value={editing.name}
onChange={(e) => setEditing({ ...editing, name: e.target.value })}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">Save Directory</label>
<div className="flex gap-2">
<input
required
value={editing.saveDir}
onChange={(e) => setEditing({ ...editing, saveDir: e.target.value })}
className="flex-1 px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
<button
type="button"
onClick={async () => {
const dir = await api.pickFolder("Select Save Directory");
if (dir) setEditing({ ...editing, saveDir: dir });
}}
className="px-3 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs flex items-center gap-1 cursor-pointer"
>
<FolderOpen className="w-3.5 h-3.5" /> Browse
</button>
</div>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">
ROMs Directory (games for this platform download here automatically)
</label>
<div className="flex gap-2">
<input
value={editing.romDir || ""}
onChange={(e) => setEditing({ ...editing, romDir: e.target.value || null })}
placeholder="Optional — e.g. ~/ROMs/GameCube"
className="flex-1 px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
<button
type="button"
onClick={async () => {
const dir = await api.pickFolder("Select ROMs Directory for This Emulator");
if (dir) setEditing({ ...editing, romDir: dir });
}}
className="px-3 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs flex items-center gap-1 cursor-pointer"
>
<FolderOpen className="w-3.5 h-3.5" /> Browse
</button>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-xs text-slate-400 mb-1">Save Layout</label>
<select
value={editing.structure}
onChange={(e) =>
setEditing({ ...editing, structure: e.target.value as SaveStructure })
}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
>
<option value="file_per_game">File per game (.sav, .mcd)</option>
<option value="folder_per_game">Folder per game (zipped)</option>
<option value="memory_card">Memory card (.ps2, .raw)</option>
</select>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">Default RomM Slot</label>
<input
value={editing.defaultSlot}
onChange={(e) => setEditing({ ...editing, defaultSlot: e.target.value })}
placeholder="default"
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
</div>
{editing.structure === "folder_per_game" && (
<div>
<label className="block text-xs text-slate-400 mb-1">
Nested Folder Depth (1 = direct subfolders, 2 = Cemu high/low, 5 = 3DS title tree)
</label>
<input
type="number"
min={1}
max={6}
value={editing.folderDepth || 1}
onChange={(e) =>
setEditing({
...editing,
folderDepth: Math.max(1, Math.min(6, Number(e.target.value) || 1)),
})
}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
)}
<div>
<label className="block text-xs text-slate-400 mb-1">
RomM Platform Slugs (comma-separated, e.g. ps2, ngc, wii, switch)
</label>
<input
value={slugInput}
onChange={(e) => setSlugInput(e.target.value)}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">
Save Extensions (comma-separated, empty = all files/folders)
</label>
<input
value={extInput}
onChange={(e) => setExtInput(e.target.value)}
placeholder="sav, srm, gci, mcd"
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
</div>
<div className="pt-2 border-t border-slate-800 space-y-2.5">
<label className="flex items-center gap-2 text-sm cursor-pointer">
<input
type="checkbox"
checked={editing.syncStates}
onChange={(e) => setEditing({ ...editing, syncStates: e.target.checked })}
className="rounded border-slate-700"
/>
Also sync Save States (/api/states)
</label>
{editing.syncStates && (
<>
<div>
<label className="block text-xs text-slate-400 mb-1">
Save States Directory
</label>
<div className="flex gap-2">
<input
value={editing.stateDir || ""}
onChange={(e) =>
setEditing({ ...editing, stateDir: e.target.value || null })
}
className="flex-1 px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
<button
type="button"
onClick={async () => {
const dir = await api.pickFolder("Select Save States Directory");
if (dir) setEditing({ ...editing, stateDir: dir });
}}
className="px-3 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs flex items-center gap-1 cursor-pointer"
>
<FolderOpen className="w-3.5 h-3.5" /> Browse
</button>
</div>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">
State Extensions (comma-separated)
</label>
<input
value={stateExtInput}
onChange={(e) => setStateExtInput(e.target.value)}
placeholder="p2s, ppst, s01, ss0, sav"
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
</div>
</>
)}
</div>
</div>
<div className="flex justify-end gap-2 pt-2">
<button
type="button"
onClick={() => setEditing(null)}
className="px-4 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-sm cursor-pointer"
>
Cancel
</button>
<button
type="submit"
className="px-4 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-sm font-medium cursor-pointer"
>
Save Rule
</button>
</div>
</form>
</div>
)}
</div>
);
};
+574
View File
@@ -0,0 +1,574 @@
import React, { useCallback, useEffect, useState } from "react";
import { listen } from "@tauri-apps/api/event";
import {
Archive,
CheckCircle2,
Download,
Folder,
FolderOpen,
HardDrive,
Link2,
Loader2,
RefreshCw,
Search,
Usb,
X,
} from "lucide-react";
import { api } from "../lib/tauri";
import {
formatBytes,
type DetectedNextUiVolume,
type NextUiCardInspection,
type NextUiSdSaveItem,
type PlatformSchema,
type SimpleRomSchema,
type SyncRunSummary,
} from "../lib/types";
interface Props {
onRefreshState: () => Promise<void>;
}
export const HandheldView: React.FC<Props> = ({ onRefreshState }) => {
const [volumes, setVolumes] = useState<DetectedNextUiVolume[]>([]);
const [selectedRoot, setSelectedRoot] = useState<string>("");
const [inspection, setInspection] = useState<NextUiCardInspection | null>(null);
const [syncStates, setSyncStates] = useState(true);
const [syncing, setSyncing] = useState(false);
const [lastSummary, setLastSummary] = useState<SyncRunSummary | null>(null);
const [toast, setToast] = useState<string | null>(null);
const [subTab, setSubTab] = useState<"saves" | "roms">("saves");
// Manual save linking
const [linkingItem, setLinkingItem] = useState<NextUiSdSaveItem | null>(null);
const [linkSearch, setLinkSearch] = useState("");
const [linkResults, setLinkResults] = useState<SimpleRomSchema[]>([]);
// Send ROMs to SD card
const [platforms, setPlatforms] = useState<PlatformSchema[]>([]);
const [selectedPlatform, setSelectedPlatform] = useState<number | null>(null);
const [romSearch, setRomSearch] = useState("");
const [roms, setRoms] = useState<SimpleRomSchema[]>([]);
const [loadingRoms, setLoadingRoms] = useState(false);
const [downloadingId, setDownloadingId] = useState<number | null>(null);
const [downloadPct, setDownloadPct] = useState(0);
const scanVolumes = useCallback(async () => {
const vols = await api.detectNextUiVolumes();
setVolumes(vols);
if (vols.length > 0 && !selectedRoot) {
setSelectedRoot(vols[0].path);
}
}, [selectedRoot]);
const inspectCard = useCallback(async (root: string) => {
if (!root) {
setInspection(null);
return;
}
const info = await api.inspectNextUiCard(root);
setInspection(info);
}, []);
useEffect(() => {
scanVolumes();
api.fetchPlatforms().then(setPlatforms).catch(() => {});
const unlistenPromise = listen<{ romId: number; downloaded: number; total: number | null }>(
"rom:download-progress",
(event) => {
const { romId, downloaded, total } = event.payload;
setDownloadingId(romId);
if (total && total > 0) {
setDownloadPct(Math.round((downloaded / total) * 100));
}
}
);
return () => {
unlistenPromise.then((u) => u());
};
}, [scanVolumes]);
useEffect(() => {
if (selectedRoot) {
inspectCard(selectedRoot);
}
}, [selectedRoot, inspectCard]);
const loadRoms = useCallback(async () => {
setLoadingRoms(true);
try {
const page = await api.fetchRoms({
platformId: selectedPlatform,
searchTerm: romSearch || null,
limit: 80,
offset: 0,
});
setRoms(page.items);
} catch (e) {
setToast(String(e));
} finally {
setLoadingRoms(false);
}
}, [selectedPlatform, romSearch]);
useEffect(() => {
if (subTab === "roms") {
loadRoms();
}
}, [subTab, selectedPlatform, loadRoms]);
const handleBrowseSd = async () => {
const picked = await api.pickFolder("Select Mounted NextUI SD Card Root");
if (picked) {
setSelectedRoot(picked);
}
};
const handleSyncCard = async () => {
if (!selectedRoot) return;
setSyncing(true);
setToast(null);
try {
const summary = await api.syncNextUiCard(selectedRoot, syncStates);
setLastSummary(summary);
await inspectCard(selectedRoot);
await onRefreshState();
} catch (e) {
setToast(`Sync failed: ${e}`);
} finally {
setSyncing(false);
}
};
const handleSendRom = async (rom: SimpleRomSchema) => {
if (!selectedRoot) return;
setDownloadingId(rom.id);
setDownloadPct(0);
setToast(null);
try {
const dest = await api.downloadRomToNextUi({
sdRoot: selectedRoot,
romId: rom.id,
fileName: rom.fs_name,
platformSlug: rom.platform_slug,
platformDisplayName: rom.platform_display_name,
});
setToast(`Sent to SD card: ${dest}`);
await inspectCard(selectedRoot);
} catch (e) {
setToast(`Transfer failed: ${e}`);
} finally {
setDownloadingId(null);
setDownloadPct(0);
}
};
const openLinker = async (item: NextUiSdSaveItem) => {
setLinkingItem(item);
setLinkSearch("");
const page = await api.fetchRoms({ limit: 30, offset: 0 });
setLinkResults(page.items);
};
const handleLink = async (rom: SimpleRomSchema) => {
if (!linkingItem) return;
await api.linkSaveToRom({
localPath: linkingItem.localPath,
romId: rom.id,
romName: rom.name || rom.fs_name_no_ext,
emulatorId: `nextui-${linkingItem.systemTag.toLowerCase()}`,
slot: linkingItem.slot || "default",
isState: linkingItem.isState,
});
setLinkingItem(null);
if (selectedRoot) await inspectCard(selectedRoot);
};
const matchedCount = inspection
? inspection.saves.filter((s) => s.matchedRomId !== null).length
: 0;
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-bold tracking-tight flex items-center gap-2.5">
<Usb className="w-6 h-6 text-indigo-400" />
NextUI Handheld (USB / SD Card)
</h2>
<p className="text-sm text-slate-400">
Sync saves, states, and ROMs with your TrimUI Smart Pro S / Brick over USB Storage or
an SD card reader — no handheld Wi-Fi needed.
</p>
</div>
<div className="flex items-center gap-2">
<button
onClick={scanVolumes}
className="px-3.5 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-xs font-medium flex items-center gap-1.5 cursor-pointer"
>
<RefreshCw className="w-3.5 h-3.5" /> Rescan Drives
</button>
<button
onClick={handleBrowseSd}
className="px-3.5 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-xs font-medium flex items-center gap-1.5 cursor-pointer"
>
<FolderOpen className="w-3.5 h-3.5" /> Select SD Folder
</button>
</div>
</div>
{/* Detected Drives Strip */}
{volumes.length > 0 && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{volumes.map((v) => {
const active = selectedRoot === v.path;
return (
<button
key={v.path}
onClick={() => setSelectedRoot(v.path)}
className={`text-left p-4 rounded-xl border transition cursor-pointer ${
active
? "bg-indigo-950/40 border-indigo-500/60"
: "bg-slate-900/80 border-slate-800 hover:border-slate-700"
}`}
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 font-semibold text-sm">
<HardDrive className="w-4 h-4 text-emerald-400" />
{v.label}
</div>
<span className="text-[11px] px-2 py-0.5 rounded-full bg-indigo-950 text-indigo-300 border border-indigo-500/30">
{v.detectedPlatform}
</span>
</div>
<div className="text-xs text-slate-400 mt-1">{v.deviceLabel}</div>
<div className="text-[11px] font-mono text-slate-500 mt-1 truncate">{v.path}</div>
</button>
);
})}
</div>
)}
{!inspection ? (
<div className="p-8 rounded-2xl bg-slate-900/70 border border-dashed border-slate-800 text-center space-y-3">
<Usb className="w-8 h-8 text-slate-500 mx-auto" />
<div className="text-sm font-medium text-slate-300">No NextUI SD card selected</div>
<p className="text-xs text-slate-500 max-w-md mx-auto">
Plug your TrimUI Smart Pro S into your computer in <strong>USB Storage</strong> mode (or
insert its microSD card), then click <strong>Rescan Drives</strong> or{" "}
<strong>Select SD Folder</strong>.
</p>
</div>
) : (
<>
{/* Active SD Card Summary & Sync Action */}
<div className="p-5 rounded-2xl bg-slate-900/90 border border-slate-800 flex flex-wrap items-center justify-between gap-4">
<div className="space-y-1.5">
<div className="flex items-center gap-2">
<span className="font-semibold text-base">{inspection.deviceName}</span>
<span className="text-[11px] uppercase px-2 py-0.5 rounded-full bg-emerald-950 text-emerald-300 border border-emerald-500/30">
{inspection.detectedPlatform}
</span>
</div>
<div className="text-xs text-slate-400 font-mono">{inspection.sdRoot}</div>
<div className="flex flex-wrap gap-1.5 pt-1">
{inspection.systemTags.map((tag) => (
<span
key={tag}
className="text-[10px] px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 font-mono"
>
{tag}
</span>
))}
</div>
</div>
<div className="flex flex-col items-end gap-2">
<button
onClick={handleSyncCard}
disabled={syncing}
className="px-4 py-2.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-sm font-medium flex items-center gap-2 shadow-lg shadow-indigo-950/50 transition cursor-pointer disabled:opacity-50"
>
{syncing ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<RefreshCw className="w-4 h-4" />
)}
{syncing ? "Syncing SD Card..." : "Sync SD Card with RomM"}
</button>
<label className="flex items-center gap-1.5 text-xs text-slate-400 cursor-pointer">
<input
type="checkbox"
checked={syncStates}
onChange={(e) => setSyncStates(e.target.checked)}
/>
Also sync Save States (/api/states)
</label>
</div>
</div>
{lastSummary && (
<div className="p-3.5 rounded-xl bg-indigo-950/40 border border-indigo-500/30 text-sm flex items-center gap-2.5">
<CheckCircle2 className="w-4 h-4 text-emerald-400 shrink-0" />
<span>
SD Card Sync Complete: <strong>{lastSummary.uploadedSaves}</strong> saves uploaded,{" "}
<strong>{lastSummary.downloadedSaves}</strong> downloaded to SD card,{" "}
<strong>{lastSummary.uploadedStates}</strong> states synced,{" "}
<strong>{lastSummary.upToDate}</strong> up to date
{lastSummary.conflicts.length > 0 &&
` • ${lastSummary.conflicts.length} conflict(s) (see Dashboard)`}
</span>
</div>
)}
{toast && (
<div className="p-3 rounded-lg bg-slate-900 border border-indigo-500/40 text-xs text-indigo-200">
{toast}
</div>
)}
{/* Sub-tabs */}
<div className="flex gap-1 p-1 bg-slate-900 border border-slate-800 rounded-xl w-fit">
<button
onClick={() => setSubTab("saves")}
className={`px-3.5 py-1.5 rounded-lg text-xs font-medium cursor-pointer ${
subTab === "saves" ? "bg-indigo-600 text-white" : "text-slate-400 hover:text-white"
}`}
>
SD Saves & States ({matchedCount}/{inspection.saves.length} matched)
</button>
<button
onClick={() => setSubTab("roms")}
className={`px-3.5 py-1.5 rounded-lg text-xs font-medium cursor-pointer ${
subTab === "roms" ? "bg-indigo-600 text-white" : "text-slate-400 hover:text-white"
}`}
>
Send ROMs to SD Card
</button>
</div>
{subTab === "saves" ? (
<div className="rounded-xl bg-slate-900/80 border border-slate-800 divide-y divide-slate-800/80">
{inspection.saves.length === 0 ? (
<div className="p-8 text-center text-sm text-slate-500">
No saves found under <code>/Saves/&lt;TAG&gt;/</code> on this SD card yet.
</div>
) : (
inspection.saves.map((item) => (
<div
key={item.localPath}
className="px-4 py-3 flex flex-wrap items-center justify-between gap-4"
>
<div className="min-w-0 space-y-0.5">
<div className="flex items-center gap-2">
{item.isDirectory ? (
<Folder className="w-4 h-4 text-amber-400 shrink-0" />
) : (
<Archive className="w-4 h-4 text-indigo-400 shrink-0" />
)}
<span className="font-medium text-sm truncate">{item.fileName}</span>
<span className="text-[10px] uppercase px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 font-mono">
{item.systemTag}
</span>
<span
className={`text-[10px] uppercase px-1.5 py-0.5 rounded ${
item.isState
? "bg-purple-950 text-purple-300"
: "bg-indigo-950 text-indigo-300"
}`}
>
{item.isState ? "State" : "Save"}
</span>
</div>
<div className="text-xs text-slate-500 font-mono truncate max-w-xl">
{formatBytes(item.sizeBytes)} • {item.localPath}
</div>
</div>
<div className="flex items-center gap-2.5 shrink-0">
{item.matchedRomId ? (
<div className="text-right">
<div className="text-xs font-medium text-emerald-400 flex items-center gap-1 justify-end">
<CheckCircle2 className="w-3.5 h-3.5" />
{item.matchedRomName}
</div>
<div className="text-[11px] text-slate-500">
{item.matchedPlatform} • {item.matchSource}
</div>
</div>
) : (
<span className="text-xs text-amber-400">Unmatched</span>
)}
<button
onClick={() => openLinker(item)}
className="px-2.5 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs font-medium flex items-center gap-1 cursor-pointer"
>
<Link2 className="w-3.5 h-3.5" /> {item.matchedRomId ? "Relink" : "Link"}
</button>
</div>
</div>
))
)}
</div>
) : (
<div className="space-y-3">
<div className="flex flex-wrap gap-2">
<select
value={selectedPlatform ?? ""}
onChange={(e) =>
setSelectedPlatform(e.target.value ? Number(e.target.value) : null)
}
className="px-3 py-2 rounded-lg bg-slate-900 border border-slate-800 text-sm"
>
<option value="">All Platforms ({platforms.length})</option>
{platforms.map((p) => (
<option key={p.id} value={p.id}>
{p.display_name} ({p.rom_count})
</option>
))}
</select>
<form
onSubmit={(e) => {
e.preventDefault();
loadRoms();
}}
className="flex-1 flex gap-2 min-w-[200px]"
>
<div className="relative flex-1">
<Search className="w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
<input
value={romSearch}
onChange={(e) => setRomSearch(e.target.value)}
placeholder="Search RomM games to copy to your TrimUI..."
className="w-full pl-9 pr-3 py-2 bg-slate-900 border border-slate-800 rounded-lg text-sm"
/>
</div>
<button
type="submit"
className="px-4 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-sm font-medium cursor-pointer"
>
Search
</button>
</form>
</div>
<div className="rounded-xl bg-slate-900/80 border border-slate-800 divide-y divide-slate-800/80">
{loadingRoms ? (
<div className="p-8 flex items-center justify-center gap-2 text-sm text-slate-400">
<Loader2 className="w-4 h-4 animate-spin" /> Loading ROMs...
</div>
) : roms.length === 0 ? (
<div className="p-8 text-center text-sm text-slate-500">No ROMs found.</div>
) : (
roms.map((rom) => {
const isDl = downloadingId === rom.id;
return (
<div
key={rom.id}
className="px-4 py-3 flex items-center justify-between gap-4"
>
<div className="min-w-0">
<div className="font-medium text-sm truncate">
{rom.name || rom.fs_name_no_ext}
</div>
<div className="text-xs text-slate-400 flex items-center gap-2 mt-0.5">
<span className="px-1.5 py-0.5 rounded bg-indigo-950/70 text-indigo-300 text-[11px]">
{rom.platform_display_name}
</span>
<span className="font-mono text-slate-500 truncate max-w-md">
{rom.fs_name}
</span>
<span>{formatBytes(rom.fs_size_bytes)}</span>
</div>
</div>
<button
onClick={() => handleSendRom(rom)}
disabled={downloadingId !== null}
className="px-3 py-1.5 rounded-lg bg-indigo-600/20 hover:bg-indigo-600 text-indigo-200 hover:text-white border border-indigo-500/30 text-xs font-medium flex items-center gap-1.5 shrink-0 transition cursor-pointer disabled:opacity-50"
>
{isDl ? (
<>
<Loader2 className="w-3.5 h-3.5 animate-spin" /> {downloadPct}%
</>
) : (
<>
<Download className="w-3.5 h-3.5" /> Send to SD
</>
)}
</button>
</div>
);
})
)}
</div>
</div>
)}
</>
)}
{/* Manual Link Modal */}
{linkingItem && (
<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4">
<div className="w-full max-w-lg bg-slate-900 border border-slate-800 rounded-2xl p-6 space-y-4 shadow-2xl">
<div className="flex items-center justify-between">
<div>
<h3 className="text-base font-semibold">Link SD Save to RomM Game</h3>
<p className="text-xs text-slate-400 font-mono truncate max-w-md">
{linkingItem.fileName}
</p>
</div>
<button
onClick={() => setLinkingItem(null)}
className="text-slate-400 hover:text-white cursor-pointer"
>
<X className="w-5 h-5" />
</button>
</div>
<form
onSubmit={async (e) => {
e.preventDefault();
const page = await api.fetchRoms({ searchTerm: linkSearch, limit: 30, offset: 0 });
setLinkResults(page.items);
}}
className="flex gap-2"
>
<input
value={linkSearch}
onChange={(e) => setLinkSearch(e.target.value)}
placeholder="Search RomM games..."
className="flex-1 px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
<button
type="submit"
className="px-3.5 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-xs font-medium cursor-pointer"
>
Search
</button>
</form>
<div className="max-h-64 overflow-y-auto divide-y divide-slate-800 border border-slate-800 rounded-xl">
{linkResults.map((rom) => (
<button
key={rom.id}
onClick={() => handleLink(rom)}
className="w-full text-left px-3.5 py-2.5 hover:bg-slate-800/70 flex items-center justify-between gap-2 cursor-pointer"
>
<div className="min-w-0">
<div className="text-sm font-medium truncate">
{rom.name || rom.fs_name_no_ext}
</div>
<div className="text-xs text-slate-500 truncate">{rom.fs_name}</div>
</div>
<span className="text-[11px] px-2 py-0.5 rounded bg-indigo-950 text-indigo-300 shrink-0">
{rom.platform_display_name}
</span>
</button>
))}
</div>
</div>
</div>
)}
</div>
);
};
+680
View File
@@ -0,0 +1,680 @@
import React, { useEffect, useState } from "react";
import { listen } from "@tauri-apps/api/event";
import {
Archive,
CheckCircle2,
CloudDownload,
CloudUpload,
Download,
FolderSearch,
Hash,
Loader2,
Search,
X,
} from "lucide-react";
import { api } from "../lib/tauri";
import {
formatBytes,
type DiscoveredSaveItem,
type EmulatorRule,
type LocalRomScanResult,
type PlatformSchema,
type RemoteSavesAndStates,
type SimpleRomSchema,
} from "../lib/types";
interface Props {
defaultDownloadDir: string | null;
emulators: EmulatorRule[];
discoveredSaves: DiscoveredSaveItem[];
onRefreshAll: () => Promise<void>;
}
function findEmulatorForRom(
emulators: EmulatorRule[],
rom: SimpleRomSchema
): EmulatorRule | undefined {
const matches = (e: EmulatorRule) =>
e.platformSlugs.some(
(s) =>
s.toLowerCase() === rom.platform_slug.toLowerCase() ||
s.toLowerCase() === rom.platform_fs_slug.toLowerCase()
);
return emulators.find((e) => e.enabled && matches(e)) || emulators.find(matches);
}
export const LibraryView: React.FC<Props> = ({
defaultDownloadDir,
emulators,
discoveredSaves,
onRefreshAll,
}) => {
const [tab, setTab] = useState<"romm" | "scanner">("romm");
const [platforms, setPlatforms] = useState<PlatformSchema[]>([]);
const [selectedPlatform, setSelectedPlatform] = useState<number | null>(null);
const [search, setSearch] = useState("");
const [roms, setRoms] = useState<SimpleRomSchema[]>([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [downloadingId, setDownloadingId] = useState<number | null>(null);
const [downloadPct, setDownloadPct] = useState<number>(0);
const [toast, setToast] = useState<string | null>(null);
// Per-game Saves & States modal
const [activeRom, setActiveRom] = useState<SimpleRomSchema | null>(null);
const [remoteAssets, setRemoteAssets] = useState<RemoteSavesAndStates | null>(null);
const [loadingAssets, setLoadingAssets] = useState(false);
const [busyAction, setBusyAction] = useState<string | null>(null);
// Local ROM folder scanner state
const [scanFolder, setScanFolder] = useState("");
const [useHashLookup, setUseHashLookup] = useState(true);
const [scanning, setScanning] = useState(false);
const [scanResults, setScanResults] = useState<LocalRomScanResult[]>([]);
useEffect(() => {
api.fetchPlatforms().then(setPlatforms).catch(console.error);
const unlistenPromise = listen<{ romId: number; downloaded: number; total: number | null }>(
"rom:download-progress",
(event) => {
const { romId, downloaded, total } = event.payload;
setDownloadingId(romId);
if (total && total > 0) {
setDownloadPct(Math.round((downloaded / total) * 100));
}
}
);
return () => {
unlistenPromise.then((u) => u());
};
}, []);
const loadRoms = async () => {
setLoading(true);
try {
const page = await api.fetchRoms({
platformId: selectedPlatform,
searchTerm: search || null,
limit: 80,
offset: 0,
});
setRoms(page.items);
setTotal(page.total);
} catch (e) {
setToast(String(e));
} finally {
setLoading(false);
}
};
useEffect(() => {
loadRoms();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedPlatform]);
const handleDownloadRom = async (rom: SimpleRomSchema) => {
const inheritedEmu = findEmulatorForRom(emulators, rom);
let dest: string | null = inheritedEmu?.romDir || defaultDownloadDir;
if (!dest) {
dest = await api.pickFolder(`Choose Download Folder for ${rom.name || rom.fs_name}`);
}
if (!dest) return;
setDownloadingId(rom.id);
setDownloadPct(0);
setToast(null);
try {
const savedPath = await api.downloadRomToFolder({
romId: rom.id,
fileName: rom.fs_name,
destFolder: dest,
platformSlug: rom.platform_slug,
platformFsSlug: rom.platform_fs_slug,
});
setToast(`Downloaded to ${savedPath}`);
} catch (e) {
setToast(`Download failed: ${e}`);
} finally {
setDownloadingId(null);
setDownloadPct(0);
}
};
const openGameSaves = async (rom: SimpleRomSchema) => {
setActiveRom(rom);
setRemoteAssets(null);
setLoadingAssets(true);
try {
const data = await api.fetchRemoteSavesAndStates(rom.id);
setRemoteAssets(data);
} catch (e) {
setToast(`Failed to load saves for ${rom.name || rom.fs_name}: ${e}`);
} finally {
setLoadingAssets(false);
}
};
const handlePullSave = async (
rom: SimpleRomSchema,
saveId: number,
fileName: string,
emulatorHint: string | null
) => {
const inheritedEmu = findEmulatorForRom(emulators, rom);
let destOverride: string | null = null;
if (!inheritedEmu || !inheritedEmu.saveDir) {
destOverride = await api.pickFolder(`Select Save Folder for ${rom.platform_display_name}`);
if (!destOverride) return;
}
setBusyAction(`save-${saveId}`);
setToast(null);
try {
const placed = await api.downloadSingleSave({
saveId,
romId: rom.id,
fileName,
platformSlug: rom.platform_slug,
platformFsSlug: rom.platform_fs_slug,
emulatorHint,
destOverride,
});
setToast(`Downloaded save to ${placed}`);
await onRefreshAll();
} catch (e) {
setToast(`Save download failed: ${e}`);
} finally {
setBusyAction(null);
}
};
const handlePullState = async (
rom: SimpleRomSchema,
stateId: number,
fileName: string,
emulatorHint: string | null
) => {
const inheritedEmu = findEmulatorForRom(emulators, rom);
let destOverride: string | null = null;
if (!inheritedEmu || (!inheritedEmu.stateDir && !inheritedEmu.saveDir)) {
destOverride = await api.pickFolder(
`Select Save States Folder for ${rom.platform_display_name}`
);
if (!destOverride) return;
}
setBusyAction(`state-${stateId}`);
setToast(null);
try {
const placed = await api.downloadSingleState({
stateId,
romId: rom.id,
fileName,
platformSlug: rom.platform_slug,
platformFsSlug: rom.platform_fs_slug,
emulatorHint,
destOverride,
});
setToast(`Downloaded state to ${placed}`);
await onRefreshAll();
} catch (e) {
setToast(`State download failed: ${e}`);
} finally {
setBusyAction(null);
}
};
const handlePushLocal = async (item: DiscoveredSaveItem, rom: SimpleRomSchema) => {
setBusyAction(`push-${item.localPath}`);
setToast(null);
try {
await api.uploadSingleSave({
localPath: item.localPath,
fileName: item.fileName,
romId: rom.id,
emulatorId: item.emulatorId,
slot: item.slot || "default",
isDirectory: item.isDirectory,
isState: item.isState,
});
setToast(`Uploaded '${item.fileName}' to RomM!`);
const refreshed = await api.fetchRemoteSavesAndStates(rom.id);
setRemoteAssets(refreshed);
await onRefreshAll();
} catch (e) {
setToast(`Upload failed: ${e}`);
} finally {
setBusyAction(null);
}
};
const handleScanLocal = async () => {
let folder = scanFolder;
if (!folder) {
const picked = await api.pickFolder("Select Local ROMs Folder");
if (!picked) return;
folder = picked;
setScanFolder(picked);
}
setScanning(true);
setToast(null);
try {
const res = await api.scanLocalRomFolder(folder, useHashLookup);
setScanResults(res);
} catch (e) {
setToast(String(e));
} finally {
setScanning(false);
}
};
const activeInheritedEmu = activeRom ? findEmulatorForRom(emulators, activeRom) : undefined;
const activeLocalItems = activeRom
? discoveredSaves.filter((s) => s.matchedRomId === activeRom.id)
: [];
return (
<div className="space-y-5">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-bold tracking-tight">ROM Library & Hash Matcher</h2>
<p className="text-sm text-slate-400">
ROMs and individual saves automatically inherit the configured emulator paths for their
system.
</p>
</div>
<div className="flex gap-1 p-1 bg-slate-900 border border-slate-800 rounded-xl">
<button
onClick={() => setTab("romm")}
className={`px-3.5 py-1.5 rounded-lg text-xs font-medium cursor-pointer ${
tab === "romm" ? "bg-indigo-600 text-white" : "text-slate-400 hover:text-white"
}`}
>
RomM Library ({total})
</button>
<button
onClick={() => setTab("scanner")}
className={`px-3.5 py-1.5 rounded-lg text-xs font-medium cursor-pointer ${
tab === "scanner" ? "bg-indigo-600 text-white" : "text-slate-400 hover:text-white"
}`}
>
Local ROM Scanner
</button>
</div>
</div>
{toast && (
<div className="p-3 rounded-lg bg-slate-900 border border-indigo-500/40 text-xs text-indigo-200 break-all">
{toast}
</div>
)}
{tab === "romm" ? (
<>
<div className="flex flex-wrap gap-2.5">
<select
value={selectedPlatform ?? ""}
onChange={(e) =>
setSelectedPlatform(e.target.value ? Number(e.target.value) : null)
}
className="px-3 py-2 rounded-lg bg-slate-900 border border-slate-800 text-sm"
>
<option value="">All Platforms ({platforms.length})</option>
{platforms.map((p) => (
<option key={p.id} value={p.id}>
{p.display_name} ({p.rom_count})
</option>
))}
</select>
<form
onSubmit={(e) => {
e.preventDefault();
loadRoms();
}}
className="flex-1 flex gap-2 min-w-[220px]"
>
<div className="relative flex-1">
<Search className="w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
<input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search ROMs by title or filename..."
className="w-full pl-9 pr-3 py-2 bg-slate-900 border border-slate-800 rounded-lg text-sm focus:outline-none focus:border-indigo-500"
/>
</div>
<button
type="submit"
className="px-4 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-sm font-medium cursor-pointer"
>
Search
</button>
</form>
</div>
<div className="rounded-xl bg-slate-900/80 border border-slate-800 overflow-hidden">
{loading ? (
<div className="p-10 flex items-center justify-center gap-2 text-slate-400 text-sm">
<Loader2 className="w-4 h-4 animate-spin" /> Loading ROMs from RomM...
</div>
) : roms.length === 0 ? (
<div className="p-10 text-center text-sm text-slate-500">No ROMs found.</div>
) : (
<div className="divide-y divide-slate-800/80">
{roms.map((rom) => {
const isDl = downloadingId === rom.id;
const inherited = findEmulatorForRom(emulators, rom);
return (
<div
key={rom.id}
className="px-4 py-3 flex items-center justify-between gap-4 hover:bg-slate-800/30 transition"
>
<div className="min-w-0">
<div className="font-medium text-sm truncate">
{rom.name || rom.fs_name_no_ext}
</div>
<div className="text-xs text-slate-400 flex flex-wrap items-center gap-2 mt-0.5">
<span className="px-1.5 py-0.5 rounded bg-indigo-950/70 text-indigo-300 text-[11px]">
{rom.platform_display_name}
</span>
{inherited && (
<span
className="px-1.5 py-0.5 rounded bg-emerald-950/70 text-emerald-300 text-[11px]"
title={
inherited.romDir
? `ROMs → ${inherited.romDir}\nSaves → ${inherited.saveDir}`
: `Saves → ${inherited.saveDir}`
}
>
→ {inherited.name}
</span>
)}
<span className="font-mono text-slate-500 truncate max-w-md">
{rom.fs_name}
</span>
<span>{formatBytes(rom.fs_size_bytes)}</span>
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
<button
onClick={() => openGameSaves(rom)}
className="px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-xs font-medium flex items-center gap-1.5 cursor-pointer transition"
title="Inspect, download, or upload individual saves & states for this game"
>
<Archive className="w-3.5 h-3.5 text-indigo-400" /> Saves
</button>
<button
onClick={() => handleDownloadRom(rom)}
disabled={downloadingId !== null}
className="px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-indigo-600 text-xs font-medium flex items-center gap-1.5 transition cursor-pointer disabled:opacity-50"
title={
inherited?.romDir
? `Download directly into ${inherited.romDir}`
: "Download ROM"
}
>
{isDl ? (
<>
<Loader2 className="w-3.5 h-3.5 animate-spin" /> {downloadPct}%
</>
) : (
<>
<Download className="w-3.5 h-3.5" /> Download
</>
)}
</button>
</div>
</div>
);
})}
</div>
)}
</div>
</>
) : (
<div className="space-y-4">
<div className="p-4 rounded-xl bg-slate-900/80 border border-slate-800 space-y-3">
<div className="flex flex-wrap gap-2">
<input
value={scanFolder}
onChange={(e) => setScanFolder(e.target.value)}
placeholder="Choose a local ROM directory to scan..."
className="flex-1 px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
<button
onClick={async () => {
const dir = await api.pickFolder("Select Local ROMs Folder");
if (dir) setScanFolder(dir);
}}
className="px-3 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs font-medium cursor-pointer"
>
Browse
</button>
<button
onClick={handleScanLocal}
disabled={scanning}
className="px-4 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-xs font-medium flex items-center gap-1.5 cursor-pointer disabled:opacity-50"
>
{scanning ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<FolderSearch className="w-3.5 h-3.5" />
)}
Scan & Match
</button>
</div>
<label className="flex items-center gap-2 text-xs text-slate-300 cursor-pointer">
<input
type="checkbox"
checked={useHashLookup}
onChange={(e) => setUseHashLookup(e.target.checked)}
/>
<Hash className="w-3.5 h-3.5 text-indigo-400" />
Compute CRC32 / MD5 / SHA1 hashes and query RomM <code>/api/roms/by-hash</code> (up
to 512 MB per file; larger ISOs match by filename)
</label>
</div>
{scanResults.length > 0 && (
<div className="rounded-xl bg-slate-900/80 border border-slate-800 divide-y divide-slate-800/80">
{scanResults.map((item) => (
<div
key={item.localPath}
className="px-4 py-3 flex items-center justify-between gap-4"
>
<div className="min-w-0">
<div className="text-sm font-medium truncate">{item.fileName}</div>
<div className="text-xs text-slate-500 flex flex-wrap gap-2 mt-0.5 font-mono">
<span>{formatBytes(item.sizeBytes)}</span>
{item.crc32 && <span>CRC32: {item.crc32}</span>}
</div>
</div>
<div className="text-right shrink-0">
{item.matchedRomId ? (
<div className="flex items-center gap-1.5 text-xs text-emerald-400">
<CheckCircle2 className="w-3.5 h-3.5" />
<span>{item.matchedRomName}</span>
<span className="px-1.5 py-0.5 rounded bg-emerald-950 text-emerald-300 text-[10px] uppercase">
{item.matchSource}
</span>
</div>
) : (
<span className="text-xs text-slate-500">Unmatched</span>
)}
</div>
</div>
))}
</div>
)}
</div>
)}
{/* Per-Game Individual Saves & States Modal */}
{activeRom && (
<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4">
<div className="w-full max-w-2xl bg-slate-900 border border-slate-800 rounded-2xl p-6 space-y-5 shadow-2xl max-h-[85vh] overflow-y-auto">
<div className="flex items-start justify-between gap-3">
<div>
<h3 className="text-lg font-semibold">
{activeRom.name || activeRom.fs_name_no_ext}
</h3>
<p className="text-xs text-slate-400 mt-0.5">
{activeRom.platform_display_name} •{" "}
{activeInheritedEmu ? (
<span className="text-emerald-400">
Inherited Emulator: {activeInheritedEmu.name} ({activeInheritedEmu.saveDir})
</span>
) : (
<span className="text-amber-400">
No emulator configured for {activeRom.platform_slug} (will prompt for folder)
</span>
)}
</p>
</div>
<button
onClick={() => setActiveRom(null)}
className="text-slate-400 hover:text-white cursor-pointer"
>
<X className="w-5 h-5" />
</button>
</div>
{loadingAssets ? (
<div className="py-8 flex items-center justify-center gap-2 text-sm text-slate-400">
<Loader2 className="w-4 h-4 animate-spin" /> Loading saves & states from RomM...
</div>
) : (
<div className="space-y-5">
{/* Server Saves */}
<div className="space-y-2">
<h4 className="text-xs font-semibold uppercase tracking-wider text-slate-400">
RomM Server Saves ({remoteAssets?.saves.length ?? 0})
</h4>
{!remoteAssets || remoteAssets.saves.length === 0 ? (
<div className="p-3 rounded-xl bg-slate-950/60 border border-slate-800 text-xs text-slate-500">
No saves stored on RomM for this game yet.
</div>
) : (
<div className="rounded-xl bg-slate-950/60 border border-slate-800 divide-y divide-slate-800/80">
{remoteAssets.saves.map((s) => (
<div
key={s.id}
className="px-3.5 py-2.5 flex items-center justify-between gap-3"
>
<div className="min-w-0">
<div className="text-sm font-medium truncate">{s.file_name}</div>
<div className="text-[11px] text-slate-500">
Slot: {s.slot || "manual"} • {formatBytes(s.file_size_bytes)} •{" "}
{new Date(s.updated_at).toLocaleString()}
</div>
</div>
<button
onClick={() =>
handlePullSave(activeRom, s.id, s.file_name, s.emulator)
}
disabled={busyAction !== null}
className="px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-xs font-medium flex items-center gap-1.5 shrink-0 cursor-pointer disabled:opacity-50"
>
{busyAction === `save-${s.id}` ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<CloudDownload className="w-3.5 h-3.5" />
)}
Pull to Emulator
</button>
</div>
))}
</div>
)}
</div>
{/* Server States */}
<div className="space-y-2">
<h4 className="text-xs font-semibold uppercase tracking-wider text-slate-400">
RomM Server Save States ({remoteAssets?.states.length ?? 0})
</h4>
{!remoteAssets || remoteAssets.states.length === 0 ? (
<div className="p-3 rounded-xl bg-slate-950/60 border border-slate-800 text-xs text-slate-500">
No save states stored on RomM for this game yet.
</div>
) : (
<div className="rounded-xl bg-slate-950/60 border border-slate-800 divide-y divide-slate-800/80">
{remoteAssets.states.map((st) => (
<div
key={st.id}
className="px-3.5 py-2.5 flex items-center justify-between gap-3"
>
<div className="min-w-0">
<div className="text-sm font-medium truncate">{st.file_name}</div>
<div className="text-[11px] text-slate-500">
{formatBytes(st.file_size_bytes)} •{" "}
{new Date(st.updated_at).toLocaleString()}
</div>
</div>
<button
onClick={() =>
handlePullState(activeRom, st.id, st.file_name, st.emulator)
}
disabled={busyAction !== null}
className="px-3 py-1.5 rounded-lg bg-purple-600 hover:bg-purple-500 text-xs font-medium flex items-center gap-1.5 shrink-0 cursor-pointer disabled:opacity-50"
>
{busyAction === `state-${st.id}` ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<CloudDownload className="w-3.5 h-3.5" />
)}
Pull State
</button>
</div>
))}
</div>
)}
</div>
{/* Local Saves & States for this ROM */}
<div className="space-y-2">
<h4 className="text-xs font-semibold uppercase tracking-wider text-slate-400">
Local Saves & States ({activeLocalItems.length})
</h4>
{activeLocalItems.length === 0 ? (
<div className="p-3 rounded-xl bg-slate-950/60 border border-slate-800 text-xs text-slate-500">
No local saves matched to this game yet.
</div>
) : (
<div className="rounded-xl bg-slate-950/60 border border-slate-800 divide-y divide-slate-800/80">
{activeLocalItems.map((item) => (
<div
key={item.localPath}
className="px-3.5 py-2.5 flex items-center justify-between gap-3"
>
<div className="min-w-0">
<div className="text-sm font-medium truncate">{item.fileName}</div>
<div className="text-[11px] text-slate-500 font-mono truncate">
{item.isState ? "State" : `Save • ${item.slot}`} •{" "}
{formatBytes(item.sizeBytes)} • {item.localPath}
</div>
</div>
<button
onClick={() => handlePushLocal(item, activeRom)}
disabled={busyAction !== null}
className="px-3 py-1.5 rounded-lg bg-emerald-600/20 hover:bg-emerald-600 text-emerald-200 hover:text-white border border-emerald-500/30 text-xs font-medium flex items-center gap-1.5 shrink-0 cursor-pointer disabled:opacity-50 transition"
>
{busyAction === `push-${item.localPath}` ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<CloudUpload className="w-3.5 h-3.5" />
)}
Push to RomM
</button>
</div>
))}
</div>
)}
</div>
</div>
)}
</div>
</div>
)}
</div>
);
};
+350
View File
@@ -0,0 +1,350 @@
import React, { useEffect, useRef, useState } from "react";
import {
CheckCircle2,
ExternalLink,
Gamepad2,
KeyRound,
Loader2,
Lock,
Server,
Smartphone,
} from "lucide-react";
import { api } from "../lib/tauri";
import type { DeviceAuthInitResponse } from "../lib/types";
interface Props {
initialServerUrl: string;
initialDeviceName: string;
onConnected: () => Promise<void>;
}
type AuthTab = "device" | "token" | "password";
export const OnboardingConnect: React.FC<Props> = ({
initialServerUrl,
initialDeviceName,
onConnected,
}) => {
const [serverUrl, setServerUrl] = useState(initialServerUrl || "https://");
const [deviceName, setDeviceName] = useState(initialDeviceName);
const [tab, setTab] = useState<AuthTab>("device");
const [pairCode, setPairCode] = useState("");
const [rawToken, setRawToken] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [deviceAuth, setDeviceAuth] = useState<DeviceAuthInitResponse | null>(null);
const [loading, setLoading] = useState(false);
const [serverOk, setServerOk] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const pollRef = useRef<number | null>(null);
useEffect(() => {
return () => {
if (pollRef.current) window.clearInterval(pollRef.current);
};
}, []);
const handleTestServer = async () => {
setError(null);
setServerOk(null);
setLoading(true);
try {
await api.testServer(serverUrl);
setServerOk("Connected to RomM server!");
} catch (e) {
setError(String(e));
} finally {
setLoading(false);
}
};
const handleStartDeviceAuth = async () => {
setError(null);
setLoading(true);
try {
const init = await api.startDeviceAuth(serverUrl, deviceName);
setDeviceAuth(init);
const base = serverUrl.trim().replace(/\/+$/, "");
const verifyUrl = init.verification_path_complete.startsWith("http")
? init.verification_path_complete
: `${base}${init.verification_path_complete}`;
await api.openExternalUrl(verifyUrl).catch(() => {});
if (pollRef.current) window.clearInterval(pollRef.current);
const intervalMs = Math.max((init.interval || 5) * 1000, 2500);
pollRef.current = window.setInterval(async () => {
try {
const user = await api.pollDeviceAuth(serverUrl, init.device_code);
if (user) {
if (pollRef.current) window.clearInterval(pollRef.current);
setDeviceAuth(null);
await onConnected();
}
} catch (err) {
if (pollRef.current) window.clearInterval(pollRef.current);
setDeviceAuth(null);
setError(String(err));
}
}, intervalMs);
} catch (e) {
setError(String(e));
} finally {
setLoading(false);
}
};
const handleTokenOrPair = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setLoading(true);
try {
if (pairCode.trim()) {
await api.exchangePairCode(serverUrl, pairCode.trim());
} else if (rawToken.trim()) {
await api.connectWithToken(serverUrl, rawToken.trim());
} else {
throw new Error("Enter either a pair code or an API token.");
}
await onConnected();
} catch (err) {
setError(String(err));
} finally {
setLoading(false);
}
};
const handlePasswordLogin = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setLoading(true);
try {
await api.loginWithPassword(serverUrl, username, password);
await onConnected();
} catch (err) {
setError(String(err));
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center p-6 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-indigo-950/60 via-slate-950 to-slate-950">
<div className="w-full max-w-xl bg-slate-900/90 border border-slate-800 rounded-2xl shadow-2xl p-8 backdrop-blur">
<div className="flex items-center gap-3 mb-6">
<div className="w-11 h-11 rounded-xl bg-indigo-600/20 border border-indigo-500/40 flex items-center justify-center text-indigo-400">
<Gamepad2 className="w-6 h-6" />
</div>
<div>
<h1 className="text-xl font-bold tracking-tight">RomM Companion</h1>
<p className="text-sm text-slate-400">
Sync saves, states & ROMs for standalone emulators with RomM 5.1.0
</p>
</div>
</div>
{/* Server URL & Device Name */}
<div className="space-y-4 mb-6">
<div>
<label className="block text-xs font-medium uppercase tracking-wider text-slate-400 mb-1.5">
RomM Server URL
</label>
<div className="flex gap-2">
<div className="relative flex-1">
<Server className="w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
<input
type="url"
value={serverUrl}
onChange={(e) => setServerUrl(e.target.value)}
placeholder="https://rom.example.com"
className="w-full pl-9 pr-3 py-2.5 bg-slate-950 border border-slate-800 rounded-lg text-sm focus:outline-none focus:border-indigo-500"
/>
</div>
<button
type="button"
onClick={handleTestServer}
disabled={loading}
className="px-3.5 py-2.5 text-sm font-medium rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 transition cursor-pointer"
>
Test
</button>
</div>
{serverOk && (
<p className="mt-1.5 text-xs text-emerald-400 flex items-center gap-1.5">
<CheckCircle2 className="w-3.5 h-3.5" /> {serverOk}
</p>
)}
</div>
<div>
<label className="block text-xs font-medium uppercase tracking-wider text-slate-400 mb-1.5">
This Device Name
</label>
<input
type="text"
value={deviceName}
onChange={(e) => setDeviceName(e.target.value)}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm focus:outline-none focus:border-indigo-500"
/>
</div>
</div>
{/* Auth Method Tabs */}
<div className="grid grid-cols-3 gap-1 p-1 bg-slate-950 rounded-xl border border-slate-800 mb-5">
{(
[
{ id: "device", label: "Device Pairing", icon: Smartphone },
{ id: "token", label: "Pair Code / Token", icon: KeyRound },
{ id: "password", label: "Username", icon: Lock },
] as const
).map((t) => {
const Icon = t.icon;
const active = tab === t.id;
return (
<button
key={t.id}
type="button"
onClick={() => {
setTab(t.id);
setError(null);
}}
className={`flex items-center justify-center gap-1.5 py-2 px-2 rounded-lg text-xs font-medium transition cursor-pointer ${
active
? "bg-indigo-600 text-white shadow"
: "text-slate-400 hover:text-slate-200"
}`}
>
<Icon className="w-3.5 h-3.5" />
{t.label}
</button>
);
})}
</div>
{tab === "device" && (
<div className="space-y-4">
{!deviceAuth ? (
<>
<p className="text-sm text-slate-400">
Start passwordless device pairing via RomM 5.1.0. Your browser will open so you
can approve this machine in one click.
</p>
<button
type="button"
onClick={handleStartDeviceAuth}
disabled={loading}
className="w-full py-2.5 px-4 rounded-lg bg-indigo-600 hover:bg-indigo-500 font-medium text-sm flex items-center justify-center gap-2 transition cursor-pointer disabled:opacity-50"
>
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <ExternalLink className="w-4 h-4" />}
Pair This Device with RomM
</button>
</>
) : (
<div className="p-4 rounded-xl bg-indigo-950/40 border border-indigo-500/40 text-center space-y-3">
<p className="text-xs uppercase tracking-wider text-indigo-300 font-medium">
Approve this code in your RomM browser tab
</p>
<div className="text-3xl font-mono font-bold tracking-widest text-white">
{deviceAuth.user_code}
</div>
<div className="flex items-center justify-center gap-2 text-xs text-slate-400">
<Loader2 className="w-3.5 h-3.5 animate-spin text-indigo-400" />
Waiting for approval...
</div>
<button
type="button"
onClick={() => {
const base = serverUrl.trim().replace(/\/+$/, "");
const url = deviceAuth.verification_path_complete.startsWith("http")
? deviceAuth.verification_path_complete
: `${base}${deviceAuth.verification_path_complete}`;
api.openExternalUrl(url);
}}
className="text-xs text-indigo-400 hover:underline cursor-pointer"
>
Re-open approval page in browser
</button>
</div>
)}
</div>
)}
{tab === "token" && (
<form onSubmit={handleTokenOrPair} className="space-y-3">
<div>
<label className="block text-xs text-slate-400 mb-1">
One-Time Pair Code (from RomM Client Tokens)
</label>
<input
type="text"
value={pairCode}
onChange={(e) => setPairCode(e.target.value)}
placeholder="e.g. ABCD-1234"
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm font-mono focus:outline-none focus:border-indigo-500"
/>
</div>
<div className="text-center text-xs text-slate-500">— or —</div>
<div>
<label className="block text-xs text-slate-400 mb-1">Raw Client API Token</label>
<input
type="password"
value={rawToken}
onChange={(e) => setRawToken(e.target.value)}
placeholder="Paste bearer token..."
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm font-mono focus:outline-none focus:border-indigo-500"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full py-2.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 font-medium text-sm flex items-center justify-center gap-2 transition cursor-pointer disabled:opacity-50"
>
{loading && <Loader2 className="w-4 h-4 animate-spin" />}
Connect
</button>
</form>
)}
{tab === "password" && (
<form onSubmit={handlePasswordLogin} className="space-y-3">
<div>
<label className="block text-xs text-slate-400 mb-1">Username</label>
<input
type="text"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm focus:outline-none focus:border-indigo-500"
/>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">Password</label>
<input
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm focus:outline-none focus:border-indigo-500"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full py-2.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 font-medium text-sm flex items-center justify-center gap-2 transition cursor-pointer disabled:opacity-50"
>
{loading && <Loader2 className="w-4 h-4 animate-spin" />}
Sign In
</button>
</form>
)}
{error && (
<div className="mt-4 p-3 rounded-lg bg-rose-950/60 border border-rose-500/40 text-xs text-rose-200 break-words">
{error}
</div>
)}
</div>
</div>
);
};
+382
View File
@@ -0,0 +1,382 @@
import React, { useEffect, useState } from "react";
import {
Archive,
CheckCircle2,
CloudUpload,
Folder,
History,
Link2,
Loader2,
RefreshCw,
Search,
Unlink,
X,
} from "lucide-react";
import { api } from "../lib/tauri";
import {
formatBytes,
type BackupEntry,
type DiscoveredSaveItem,
type SimpleRomSchema,
} from "../lib/types";
interface Props {
discoveredSaves: DiscoveredSaveItem[];
onRefreshSaves: () => Promise<void>;
}
export const SavesStatesView: React.FC<Props> = ({ discoveredSaves, onRefreshSaves }) => {
const [subTab, setSubTab] = useState<"local" | "backups">("local");
const [filter, setFilter] = useState<"all" | "matched" | "unmatched" | "states">("all");
const [linkingItem, setLinkingItem] = useState<DiscoveredSaveItem | null>(null);
const [romSearch, setRomSearch] = useState("");
const [romResults, setRomResults] = useState<SimpleRomSchema[]>([]);
const [slotInput, setSlotInput] = useState("default");
const [backups, setBackups] = useState<BackupEntry[]>([]);
const [toast, setToast] = useState<string | null>(null);
const [uploadingPath, setUploadingPath] = useState<string | null>(null);
const handleUploadSingle = async (item: DiscoveredSaveItem) => {
if (!item.matchedRomId) return;
setUploadingPath(item.localPath);
setToast(null);
try {
await api.uploadSingleSave({
localPath: item.localPath,
fileName: item.fileName,
romId: item.matchedRomId,
emulatorId: item.emulatorId,
slot: item.slot || "default",
isDirectory: item.isDirectory,
isState: item.isState,
});
setToast(`Uploaded '${item.fileName}' to RomM!`);
await onRefreshSaves();
} catch (e) {
setToast(`Upload failed: ${e}`);
} finally {
setUploadingPath(null);
}
};
useEffect(() => {
if (subTab === "backups") {
api.listBackups().then(setBackups).catch(console.error);
}
}, [subTab]);
const filtered = discoveredSaves.filter((s) => {
if (filter === "matched") return s.matchedRomId !== null;
if (filter === "unmatched") return s.matchedRomId === null;
if (filter === "states") return s.isState;
return true;
});
const openLinker = async (item: DiscoveredSaveItem) => {
setLinkingItem(item);
setSlotInput(item.slot || "default");
setRomSearch("");
const page = await api.fetchRoms({ limit: 30, offset: 0 });
setRomResults(page.items);
};
const searchRomsForLink = async (e: React.FormEvent) => {
e.preventDefault();
const page = await api.fetchRoms({ searchTerm: romSearch, limit: 30, offset: 0 });
setRomResults(page.items);
};
const handleLink = async (rom: SimpleRomSchema) => {
if (!linkingItem) return;
await api.linkSaveToRom({
localPath: linkingItem.localPath,
romId: rom.id,
romName: rom.name || rom.fs_name_no_ext,
emulatorId: linkingItem.emulatorId,
slot: slotInput || "default",
isState: linkingItem.isState,
});
setLinkingItem(null);
await onRefreshSaves();
};
const handleUnlink = async (localPath: string) => {
await api.unlinkSave(localPath);
await onRefreshSaves();
};
const handleRestoreBackup = async (b: BackupEntry) => {
const destFolder = await api.pickFolder("Select Target Folder to Restore Backup Into");
if (!destFolder) return;
const isZip = b.fileName.endsWith(".zip");
const targetPath = `${destFolder}/${b.fileName.replace(/^\d{8}T\d{6}Z_/, "").replace(/\.zip$/, "")}`;
try {
await api.restoreBackup(b.backupPath, targetPath, isZip);
setToast(`Restored backup to ${targetPath}`);
} catch (e) {
setToast(`Restore failed: ${e}`);
}
};
return (
<div className="space-y-5">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-bold tracking-tight">Saves, States & Backups</h2>
<p className="text-sm text-slate-400">
Inspect matched save files & save states, manually link Title ID folders, or restore
automatic backups.
</p>
</div>
<div className="flex items-center gap-2">
<div className="flex gap-1 p-1 bg-slate-900 border border-slate-800 rounded-xl">
<button
onClick={() => setSubTab("local")}
className={`px-3 py-1.5 rounded-lg text-xs font-medium cursor-pointer ${
subTab === "local" ? "bg-indigo-600 text-white" : "text-slate-400 hover:text-white"
}`}
>
Local Saves ({discoveredSaves.length})
</button>
<button
onClick={() => setSubTab("backups")}
className={`px-3 py-1.5 rounded-lg text-xs font-medium flex items-center gap-1 cursor-pointer ${
subTab === "backups"
? "bg-indigo-600 text-white"
: "text-slate-400 hover:text-white"
}`}
>
<History className="w-3.5 h-3.5" /> Backups
</button>
</div>
<button
onClick={onRefreshSaves}
className="p-2 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 cursor-pointer"
title="Rescan local save folders"
>
<RefreshCw className="w-4 h-4" />
</button>
</div>
</div>
{toast && (
<div className="p-3 rounded-lg bg-slate-900 border border-indigo-500/40 text-xs text-indigo-200">
{toast}
</div>
)}
{subTab === "local" ? (
<>
<div className="flex flex-wrap gap-2">
{(["all", "matched", "unmatched", "states"] as const).map((f) => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-3 py-1.5 rounded-lg text-xs font-medium capitalize cursor-pointer border ${
filter === f
? "bg-indigo-600/20 border-indigo-500/50 text-indigo-300"
: "bg-slate-900 border-slate-800 text-slate-400 hover:text-slate-200"
}`}
>
{f}
</button>
))}
</div>
<div className="rounded-xl bg-slate-900/80 border border-slate-800 divide-y divide-slate-800/80">
{filtered.length === 0 ? (
<div className="p-8 text-center text-sm text-slate-500">
No saves discovered matching this filter. Make sure at least one emulator rule is
enabled in <strong>Emulators</strong>.
</div>
) : (
filtered.map((item) => (
<div
key={item.localPath}
className="px-4 py-3 flex flex-wrap items-center justify-between gap-4"
>
<div className="min-w-0 space-y-1">
<div className="flex items-center gap-2">
{item.isDirectory ? (
<Folder className="w-4 h-4 text-amber-400 shrink-0" />
) : (
<Archive className="w-4 h-4 text-indigo-400 shrink-0" />
)}
<span className="font-medium text-sm truncate">{item.fileName}</span>
<span
className={`text-[10px] uppercase px-1.5 py-0.5 rounded font-medium ${
item.isState
? "bg-purple-950 text-purple-300"
: "bg-slate-800 text-slate-300"
}`}
>
{item.isState ? "State" : `Save • ${item.slot}`}
</span>
</div>
<div className="text-xs text-slate-500 font-mono truncate max-w-2xl">
{item.emulatorName} • {formatBytes(item.sizeBytes)} • {item.localPath}
</div>
</div>
<div className="flex items-center gap-2.5 shrink-0">
{item.matchedRomId ? (
<div className="text-right">
<div className="text-xs font-medium text-emerald-400 flex items-center gap-1 justify-end">
<CheckCircle2 className="w-3.5 h-3.5" />
{item.matchedRomName}
</div>
<div className="text-[11px] text-slate-500">
{item.matchedPlatform} • {item.matchSource} (
{Math.round(item.matchConfidence * 100)}%)
</div>
</div>
) : (
<span className="text-xs text-amber-400">Unmatched</span>
)}
{item.matchedRomId && (
<button
onClick={() => handleUploadSingle(item)}
disabled={uploadingPath !== null}
className="px-2.5 py-1.5 rounded-lg bg-indigo-600/20 hover:bg-indigo-600 text-indigo-200 hover:text-white border border-indigo-500/30 text-xs font-medium flex items-center gap-1 cursor-pointer disabled:opacity-50 transition"
title="Push this save directly to RomM"
>
{uploadingPath === item.localPath ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<CloudUpload className="w-3.5 h-3.5" />
)}
Push
</button>
)}
<button
onClick={() => openLinker(item)}
className="px-2.5 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs font-medium flex items-center gap-1 cursor-pointer"
>
<Link2 className="w-3.5 h-3.5" /> {item.matchedRomId ? "Relink" : "Link ROM"}
</button>
{item.matchSource === "manual" && (
<button
onClick={() => handleUnlink(item.localPath)}
className="p-1.5 rounded-lg bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-300 cursor-pointer"
title="Remove manual link"
>
<Unlink className="w-3.5 h-3.5" />
</button>
)}
</div>
</div>
))
)}
</div>
</>
) : (
<div className="rounded-xl bg-slate-900/80 border border-slate-800 divide-y divide-slate-800/80">
{backups.length === 0 ? (
<div className="p-8 text-center text-sm text-slate-500">
No local backups yet. Backups are automatically created before any server save
overwrites a local file.
</div>
) : (
backups.map((b) => (
<div
key={b.backupPath}
className="px-4 py-3 flex items-center justify-between gap-4"
>
<div>
<div className="text-sm font-medium">{b.fileName}</div>
<div className="text-xs text-slate-500">
ROM #{b.romId} • {formatBytes(b.sizeBytes)} •{" "}
{new Date(b.createdAt).toLocaleString()}
</div>
</div>
<button
onClick={() => handleRestoreBackup(b)}
className="px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-indigo-600 text-xs font-medium cursor-pointer transition"
>
Restore to Folder
</button>
</div>
))
)}
</div>
)}
{/* Manual Link Modal */}
{linkingItem && (
<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4">
<div className="w-full max-w-lg bg-slate-900 border border-slate-800 rounded-2xl p-6 space-y-4 shadow-2xl">
<div className="flex items-center justify-between">
<div>
<h3 className="text-base font-semibold">Link Save to RomM Game</h3>
<p className="text-xs text-slate-400 font-mono truncate max-w-md">
{linkingItem.fileName}
</p>
</div>
<button
onClick={() => setLinkingItem(null)}
className="text-slate-400 hover:text-white cursor-pointer"
>
<X className="w-5 h-5" />
</button>
</div>
{!linkingItem.isState && (
<div>
<label className="block text-xs text-slate-400 mb-1">
RomM Save Slot Name (kept consistent across syncs)
</label>
<input
value={slotInput}
onChange={(e) => setSlotInput(e.target.value)}
className="w-full px-3 py-1.5 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
)}
<form onSubmit={searchRomsForLink} className="flex gap-2">
<div className="relative flex-1">
<Search className="w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
<input
value={romSearch}
onChange={(e) => setRomSearch(e.target.value)}
placeholder="Search RomM games..."
className="w-full pl-9 pr-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
<button
type="submit"
className="px-3.5 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-xs font-medium cursor-pointer"
>
Search
</button>
</form>
<div className="max-h-64 overflow-y-auto divide-y divide-slate-800 border border-slate-800 rounded-xl">
{romResults.map((rom) => (
<button
key={rom.id}
onClick={() => handleLink(rom)}
className="w-full text-left px-3.5 py-2.5 hover:bg-slate-800/70 flex items-center justify-between gap-2 cursor-pointer"
>
<div className="min-w-0">
<div className="text-sm font-medium truncate">
{rom.name || rom.fs_name_no_ext}
</div>
<div className="text-xs text-slate-500 truncate">{rom.fs_name}</div>
</div>
<span className="text-[11px] px-2 py-0.5 rounded bg-indigo-950 text-indigo-300 shrink-0">
{rom.platform_display_name}
</span>
</button>
))}
</div>
</div>
</div>
)}
</div>
);
};
+171
View File
@@ -0,0 +1,171 @@
import React, { useState } from "react";
import { FolderOpen, LogOut, Save } from "lucide-react";
import { api } from "../lib/tauri";
import type { AppStateSnapshot, WatcherSettings } from "../lib/types";
interface Props {
appState: AppStateSnapshot;
onRefreshState: () => Promise<void>;
onDisconnect: () => Promise<void>;
}
export const SettingsView: React.FC<Props> = ({
appState,
onRefreshState,
onDisconnect,
}) => {
const [settings, setSettings] = useState<WatcherSettings>(appState.settings);
const [deviceName, setDeviceName] = useState(appState.deviceName);
const [savedMsg, setSavedMsg] = useState(false);
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
await api.saveSettings(settings, deviceName);
await onRefreshState();
setSavedMsg(true);
setTimeout(() => setSavedMsg(false), 2500);
};
return (
<div className="space-y-6 max-w-2xl">
<div>
<h2 className="text-2xl font-bold tracking-tight">Settings</h2>
<p className="text-sm text-slate-400">
Configure background watching, backup retention, tray behavior, and device identity.
</p>
</div>
<form
onSubmit={handleSave}
className="p-6 rounded-2xl bg-slate-900/80 border border-slate-800 space-y-5"
>
<div>
<label className="block text-xs font-medium uppercase tracking-wider text-slate-400 mb-1.5">
Device Name
</label>
<input
value={deviceName}
onChange={(e) => setDeviceName(e.target.value)}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
<p className="text-xs text-slate-500 mt-1">
RomM Device ID: <span className="font-mono">{appState.deviceId || "Not registered"}</span>
</p>
</div>
<div className="space-y-3 pt-2 border-t border-slate-800">
<label className="flex items-center justify-between text-sm cursor-pointer">
<span>Enable Background File Watcher</span>
<input
type="checkbox"
checked={settings.enabled}
onChange={(e) => setSettings({ ...settings, enabled: e.target.checked })}
/>
</label>
<label className="flex items-center justify-between text-sm cursor-pointer">
<span>Auto-Sync Immediately When Save Files Change</span>
<input
type="checkbox"
checked={settings.autoSyncOnChange}
onChange={(e) => setSettings({ ...settings, autoSyncOnChange: e.target.checked })}
/>
</label>
<label className="flex items-center justify-between text-sm cursor-pointer">
<span>Minimize to System Tray on Window Close</span>
<input
type="checkbox"
checked={settings.minimizeToTray}
onChange={(e) => setSettings({ ...settings, minimizeToTray: e.target.checked })}
/>
</label>
</div>
<div className="grid grid-cols-2 gap-4 pt-2 border-t border-slate-800">
<div>
<label className="block text-xs text-slate-400 mb-1">
Watcher Debounce (seconds)
</label>
<input
type="number"
min={1}
max={60}
value={settings.debounceSeconds}
onChange={(e) =>
setSettings({ ...settings, debounceSeconds: Number(e.target.value) || 5 })
}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
<div>
<label className="block text-xs text-slate-400 mb-1">
Max Local Backups per ROM
</label>
<input
type="number"
min={1}
max={100}
value={settings.maxBackupsPerSave}
onChange={(e) =>
setSettings({ ...settings, maxBackupsPerSave: Number(e.target.value) || 10 })
}
className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-sm"
/>
</div>
</div>
<div className="pt-2 border-t border-slate-800">
<label className="block text-xs text-slate-400 mb-1">
Default ROM Download Folder (optional)
</label>
<div className="flex gap-2">
<input
value={settings.defaultRomDownloadDir || ""}
onChange={(e) =>
setSettings({ ...settings, defaultRomDownloadDir: e.target.value || null })
}
placeholder="Ask every time"
className="flex-1 px-3 py-2 bg-slate-950 border border-slate-800 rounded-lg text-xs font-mono"
/>
<button
type="button"
onClick={async () => {
const dir = await api.pickFolder("Select Default ROM Download Folder");
if (dir) setSettings({ ...settings, defaultRomDownloadDir: dir });
}}
className="px-3 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs flex items-center gap-1 cursor-pointer"
>
<FolderOpen className="w-3.5 h-3.5" /> Browse
</button>
</div>
</div>
<div className="flex items-center justify-between pt-3">
<button
type="submit"
className="px-4 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-sm font-medium flex items-center gap-2 cursor-pointer"
>
<Save className="w-4 h-4" /> Save Settings
</button>
{savedMsg && <span className="text-xs text-emerald-400">Saved!</span>}
</div>
</form>
<div className="p-5 rounded-2xl bg-rose-950/20 border border-rose-500/30 flex items-center justify-between">
<div>
<div className="text-sm font-semibold text-rose-200">Disconnect from RomM</div>
<div className="text-xs text-slate-400">
Clears the saved auth token from this machine. Local emulator rules are kept.
</div>
</div>
<button
onClick={onDisconnect}
className="px-3.5 py-2 rounded-lg bg-rose-600 hover:bg-rose-500 text-xs font-medium flex items-center gap-1.5 cursor-pointer"
>
<LogOut className="w-3.5 h-3.5" /> Disconnect
</button>
</div>
</div>
);
};