821 lines
26 KiB
Svelte
821 lines
26 KiB
Svelte
<script lang="ts">
|
|
import { untrack } from "svelte";
|
|
import { confirm } from "@tauri-apps/plugin-dialog";
|
|
import { requestText } from "$lib/workspace/dialogs.svelte";
|
|
import type { TreeEntry } from "$lib/workspace/types";
|
|
import {
|
|
workspaceAbsPath,
|
|
workspaceCopy,
|
|
workspaceCreate,
|
|
workspaceDelete,
|
|
workspaceList,
|
|
workspaceRename,
|
|
workspaceReveal,
|
|
} from "$lib/workspace/api";
|
|
import { loadMarks, saveMarks, type Marks } from "$lib/workspace/marks";
|
|
import { actionEntries, selectionRoots, setSelectedMarks, runTreeActions } from "$lib/workspace/treeActions";
|
|
import {
|
|
dropHint,
|
|
dropPlaceAt,
|
|
joinRel,
|
|
parentRel,
|
|
planDrop,
|
|
uniqueName,
|
|
type DropPlace,
|
|
type DropTarget,
|
|
} from "$lib/workspace/treeDrop";
|
|
import { planRename, planDocumentTitleRename } from "$lib/workspace/renamePath";
|
|
import { selectTreePath, treeSelectionEdges, visibleTreePaths, type SelectionModifiers, type TreeSelection } from "$lib/workspace/treeSelection";
|
|
import ContextMenu from "./ContextMenu.svelte";
|
|
import type { MenuItem } from "./menuTypes";
|
|
import TreeNode from "./TreeNode.svelte";
|
|
import IconButton from "$lib/ui/IconButton.svelte";
|
|
import { dropWorkspaceImage, highlightImageDrop } from "$lib/editor/workspaceImageDrop";
|
|
import { pluginDocuments, pluginDocumentTypes, inspectPluginDocuments, createPluginDocument } from "$lib/plugins/external";
|
|
|
|
type Props = {
|
|
workspaceRoot: string;
|
|
activePath: string | null;
|
|
onOpenFile: (entry: TreeEntry, newTab?: boolean) => void;
|
|
refreshToken: number;
|
|
onStatus?: (message: string) => void;
|
|
onEntryGone?: (rel: string) => void;
|
|
onEntryRenamed?: (from: string, to: string) => void;
|
|
onCreated?: (entry: TreeEntry) => void;
|
|
keysActive?: boolean;
|
|
};
|
|
|
|
let {
|
|
workspaceRoot,
|
|
activePath,
|
|
onOpenFile,
|
|
refreshToken,
|
|
onStatus,
|
|
onEntryGone,
|
|
onEntryRenamed,
|
|
onCreated,
|
|
keysActive = true,
|
|
}: Props = $props();
|
|
|
|
let expanded = $state<Set<string>>(new Set([""]));
|
|
let childrenMap = $state<Record<string, TreeEntry[]>>({});
|
|
let loading = $state(false);
|
|
let error = $state<string | null>(null);
|
|
let marks = $state<Marks>({ pins: [], bookmarks: [], order: {} });
|
|
let menu = $state<{ x: number; y: number; entry: TreeEntry | null } | null>(null);
|
|
let sortMode = $state<"custom" | "name" | "name-desc">("custom");
|
|
let dragRel = $state<string | null>(null);
|
|
let dragEntries = $state<TreeEntry[]>([]);
|
|
let dropTarget = $state<DropTarget | null>(null);
|
|
let dragPoint = $state<{ x: number; y: number } | null>(null);
|
|
let selection = $state<TreeSelection>({ paths: new Set(), anchor: null });
|
|
const visiblePaths = $derived(visibleTreePaths(childrenMap, expanded));
|
|
const selectionEdges = $derived(treeSelectionEdges(visiblePaths, selection.paths));
|
|
let renameRel = $state<string | null>(null);
|
|
let renameDraft = $state("");
|
|
let renameDocument = false;
|
|
let skipClick = false;
|
|
let imageLanding = $state(false);
|
|
let cancelDrag: (() => void) | undefined;
|
|
$effect(() => () => cancelDrag?.());
|
|
|
|
const pins = $derived(new Set(marks.pins));
|
|
const bookmarks = $derived(new Set(marks.bookmarks));
|
|
|
|
function sortEntries(parent: string, entries: TreeEntry[]): TreeEntry[] {
|
|
const pinSet = new Set(marks.pins);
|
|
const custom = marks.order[parent] ?? [];
|
|
return [...entries].sort((a, b) => {
|
|
const ap = pinSet.has(a.rel_path) ? 0 : 1;
|
|
const bp = pinSet.has(b.rel_path) ? 0 : 1;
|
|
if (ap !== bp) {
|
|
return ap - bp;
|
|
}
|
|
if (sortMode === "custom") {
|
|
const ai = custom.indexOf(a.name);
|
|
const bi = custom.indexOf(b.name);
|
|
if (ai !== -1 || bi !== -1) {
|
|
if (ai === -1) {
|
|
return 1;
|
|
}
|
|
if (bi === -1) {
|
|
return -1;
|
|
}
|
|
if (ai !== bi) {
|
|
return ai - bi;
|
|
}
|
|
}
|
|
}
|
|
if (a.kind !== b.kind) {
|
|
return a.kind === "folder" ? -1 : 1;
|
|
}
|
|
const byName = a.name.localeCompare(b.name, undefined, { sensitivity: "base" });
|
|
return sortMode === "name-desc" ? -byName : byName;
|
|
});
|
|
}
|
|
|
|
async function load(rel: string) {
|
|
loading = true;
|
|
try {
|
|
const entries = await workspaceList(rel);
|
|
childrenMap = { ...childrenMap, [rel]: sortEntries(rel, entries) };
|
|
void inspectPluginDocuments(entries);
|
|
error = null;
|
|
} catch (err) {
|
|
error = err instanceof Error ? err.message : String(err);
|
|
} finally {
|
|
loading = false;
|
|
}
|
|
}
|
|
|
|
$effect(() => {
|
|
void workspaceRoot;
|
|
expanded = new Set([""]);
|
|
selection = { paths: new Set(), anchor: null };
|
|
childrenMap = {};
|
|
marks = { pins: [], bookmarks: [], order: {} };
|
|
void loadMarks().then((next) => {
|
|
marks = next;
|
|
});
|
|
void load("");
|
|
});
|
|
|
|
$effect(() => {
|
|
void refreshToken;
|
|
void $pluginDocumentTypes;
|
|
const keys = untrack(() => Object.keys(childrenMap));
|
|
for (const key of keys) {
|
|
void load(key);
|
|
}
|
|
});
|
|
|
|
$effect(() => {
|
|
void marks;
|
|
const current = untrack(() => childrenMap);
|
|
const next: Record<string, TreeEntry[]> = {};
|
|
for (const [key, list] of Object.entries(current)) {
|
|
next[key] = sortEntries(key, list);
|
|
}
|
|
childrenMap = next;
|
|
});
|
|
|
|
function toggleFolder(entry: TreeEntry) {
|
|
const next = new Set(expanded);
|
|
if (next.has(entry.rel_path)) {
|
|
next.delete(entry.rel_path);
|
|
} else {
|
|
next.add(entry.rel_path);
|
|
if (!childrenMap[entry.rel_path]) {
|
|
void load(entry.rel_path);
|
|
}
|
|
}
|
|
expanded = next;
|
|
}
|
|
|
|
// Drop selections that are no longer visible after collapsing, deleting or refreshing.
|
|
$effect(() => {
|
|
const visible = new Set(visiblePaths);
|
|
const current = untrack(() => selection);
|
|
const paths = new Set([...current.paths].filter((path) => visible.has(path)));
|
|
const anchor = current.anchor && visible.has(current.anchor) ? current.anchor : null;
|
|
if (paths.size !== current.paths.size || anchor !== current.anchor) selection = { paths, anchor };
|
|
});
|
|
|
|
function selectOnly(rel: string) {
|
|
selection = { paths: new Set([rel]), anchor: rel };
|
|
}
|
|
|
|
function onRowClick(entry: TreeEntry, modifiers: SelectionModifiers = {}, newTab = false) {
|
|
if (skipClick) {
|
|
skipClick = false;
|
|
return;
|
|
}
|
|
selection = selectTreePath(selection, entry.rel_path, visiblePaths, modifiers);
|
|
if (renameRel && renameRel !== entry.rel_path) {
|
|
void commitRename();
|
|
}
|
|
if (modifiers.ctrlKey || modifiers.metaKey || modifiers.shiftKey) return;
|
|
if (entry.kind === "folder") {
|
|
toggleFolder(entry);
|
|
return;
|
|
}
|
|
onOpenFile(entry, newTab);
|
|
}
|
|
|
|
function findEntry(rel: string): TreeEntry | null {
|
|
for (const list of Object.values(childrenMap)) {
|
|
const found = list.find((item) => item.rel_path === rel);
|
|
if (found) {
|
|
return found;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function readDropAt(clientX: number, clientY: number): DropTarget | null {
|
|
const hit = document.elementFromPoint(clientX, clientY)?.closest("[data-tree-rel]");
|
|
if (!(hit instanceof HTMLElement)) {
|
|
return null;
|
|
}
|
|
const rel = hit.dataset.treeRel;
|
|
if (!rel || dragEntries.some(entry => rel === entry.rel_path || rel.startsWith(`${entry.rel_path}/`))) {
|
|
return null;
|
|
}
|
|
const kind = hit.dataset.treeKind === "folder" ? "folder" : "file";
|
|
const rect = hit.getBoundingClientRect();
|
|
const yRatio = rect.height ? (clientY - rect.top) / rect.height : 0.5;
|
|
return { rel, place: dropPlaceAt(kind, yRatio) };
|
|
}
|
|
|
|
function onDragPointerDown(entry: TreeEntry, event: PointerEvent) {
|
|
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || renameRel === entry.rel_path) {
|
|
return;
|
|
}
|
|
const startX = event.clientX;
|
|
const startY = event.clientY;
|
|
let started = false;
|
|
let singleFile = false;
|
|
cancelDrag?.();
|
|
const onMove = (moveEvent: PointerEvent) => {
|
|
if (!started) {
|
|
if (Math.hypot(moveEvent.clientX - startX, moveEvent.clientY - startY) <= 8) {
|
|
return;
|
|
}
|
|
started = true;
|
|
if (!selection.paths.has(entry.rel_path)) selectOnly(entry.rel_path);
|
|
dragEntries = selectionRoots(actionEntries(entry, selection.paths, visiblePaths, findEntry));
|
|
singleFile = selection.paths.size === 1 && entry.kind === "file";
|
|
dragRel = entry.rel_path;
|
|
}
|
|
dragPoint = { x: moveEvent.clientX, y: moveEvent.clientY };
|
|
imageLanding = singleFile && highlightImageDrop(entry.rel_path, dragPoint);
|
|
dropTarget = readDropAt(moveEvent.clientX, moveEvent.clientY);
|
|
};
|
|
const clean = () => {
|
|
window.removeEventListener("pointermove", onMove);
|
|
window.removeEventListener("pointerup", onUp);
|
|
window.removeEventListener("pointercancel", clean);
|
|
window.removeEventListener("keydown", onKey, true);
|
|
highlightImageDrop();
|
|
dragRel = null; dragEntries = []; dropTarget = null; dragPoint = null; imageLanding = false;
|
|
cancelDrag = undefined;
|
|
};
|
|
const onKey = (key: KeyboardEvent) => { if (key.key === "Escape") { key.preventDefault(); clean(); } };
|
|
const onUp = (up: PointerEvent) => {
|
|
if (started) {
|
|
skipClick = true;
|
|
setTimeout(() => { skipClick = false; }, 0);
|
|
}
|
|
if (started && singleFile && dropWorkspaceImage(entry.rel_path, { x: up.clientX, y: up.clientY })) { clean(); return; }
|
|
if (started && dragRel && dropTarget) {
|
|
const target = findEntry(dropTarget.rel);
|
|
if (target) {
|
|
skipClick = true;
|
|
void handleDrop(target, [...dragEntries], dropTarget.place);
|
|
}
|
|
}
|
|
clean();
|
|
};
|
|
cancelDrag = clean;
|
|
window.addEventListener("pointermove", onMove);
|
|
window.addEventListener("pointerup", onUp);
|
|
window.addEventListener("pointercancel", clean);
|
|
window.addEventListener("keydown", onKey, true);
|
|
}
|
|
|
|
function cycleSort() {
|
|
sortMode = sortMode === "custom" ? "name" : sortMode === "name" ? "name-desc" : "custom";
|
|
const current = untrack(() => childrenMap);
|
|
const next: Record<string, TreeEntry[]> = {};
|
|
for (const [key, list] of Object.entries(current)) {
|
|
next[key] = sortEntries(key, list);
|
|
}
|
|
childrenMap = next;
|
|
}
|
|
|
|
const folderPaths = $derived(
|
|
Object.values(childrenMap)
|
|
.flat()
|
|
.filter((item) => item.kind === "folder")
|
|
.map((item) => item.rel_path),
|
|
);
|
|
const allCollapsed = $derived(folderPaths.every((path) => !expanded.has(path)));
|
|
|
|
function collapseAll() {
|
|
expanded = new Set([""]);
|
|
}
|
|
|
|
async function expandAll() {
|
|
const folders = new Set<string>([""]);
|
|
const walk = async (parent: string) => {
|
|
if (!childrenMap[parent]) {
|
|
await load(parent);
|
|
}
|
|
for (const child of childrenMap[parent] ?? []) {
|
|
if (child.kind === "folder") {
|
|
folders.add(child.rel_path);
|
|
await walk(child.rel_path);
|
|
}
|
|
}
|
|
};
|
|
await walk("");
|
|
expanded = folders;
|
|
}
|
|
|
|
async function copyText(text: string, label: string) {
|
|
try {
|
|
await navigator.clipboard.writeText(text);
|
|
} catch {
|
|
const area = document.createElement("textarea");
|
|
area.value = text;
|
|
document.body.appendChild(area);
|
|
area.select();
|
|
document.execCommand("copy");
|
|
area.remove();
|
|
}
|
|
onStatus?.(`Copied ${label}`);
|
|
}
|
|
|
|
async function persistMarks(next: Marks) {
|
|
marks = next;
|
|
try {
|
|
await saveMarks(next);
|
|
} catch (err) {
|
|
error = err instanceof Error ? err.message : String(err);
|
|
}
|
|
}
|
|
|
|
function namesIn(parent: string): string[] {
|
|
return (childrenMap[parent] ?? []).map((item) => item.name);
|
|
}
|
|
|
|
function startRename(entry: TreeEntry) {
|
|
selectOnly(entry.rel_path);
|
|
renameRel = entry.rel_path;
|
|
renameDocument = entry.kind === "file" && (!!$pluginDocuments[entry.rel_path] || /\.(md|markdown|mdown)$/i.test(entry.name));
|
|
renameDraft = renameDocument ? entry.name.replace(/\.[^.]+$/, "") : entry.name;
|
|
}
|
|
|
|
function cancelRename() {
|
|
renameRel = null;
|
|
renameDraft = "";
|
|
}
|
|
|
|
async function commitRename() {
|
|
const from = renameRel;
|
|
if (!from) {
|
|
return;
|
|
}
|
|
const plan = renameDocument ? planDocumentTitleRename(from, renameDraft) : planRename(from, renameDraft);
|
|
cancelRename();
|
|
if (plan.action === "noop") {
|
|
return;
|
|
}
|
|
if (plan.action === "error") {
|
|
error = plan.message;
|
|
return;
|
|
}
|
|
try {
|
|
await workspaceRename(from, plan.to);
|
|
await load(parentRel(from));
|
|
selectOnly(plan.to);
|
|
onEntryRenamed?.(from, plan.to);
|
|
onStatus?.(`Renamed to ${plan.to}`);
|
|
} catch (err) {
|
|
error = err instanceof Error ? err.message : String(err);
|
|
}
|
|
}
|
|
|
|
function onWindowKey(event: KeyboardEvent) {
|
|
if (!keysActive) {
|
|
return;
|
|
}
|
|
if (event.key !== "F2" || event.ctrlKey || event.metaKey || event.altKey) {
|
|
return;
|
|
}
|
|
if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
|
|
return;
|
|
}
|
|
if (selection.paths.size > 1) return;
|
|
const rel = selection.paths.values().next().value ?? activePath;
|
|
if (!rel) {
|
|
return;
|
|
}
|
|
const entry = findEntry(rel);
|
|
if (!entry) {
|
|
return;
|
|
}
|
|
event.preventDefault();
|
|
startRename(entry);
|
|
}
|
|
|
|
async function createIn(parent: string, kind: "folder" | "note") {
|
|
let name: string;
|
|
if (kind === "note") {
|
|
name = "untitled.md";
|
|
} else {
|
|
const typed = await requestText("Folder name", "folder");
|
|
if (!typed) {
|
|
return;
|
|
}
|
|
if (typed.includes("/") || typed.includes("\\")) {
|
|
error = "Name cannot contain a path separator";
|
|
return;
|
|
}
|
|
name = typed;
|
|
}
|
|
const finalName = uniqueName(namesIn(parent), name);
|
|
const rel = joinRel(parent, finalName);
|
|
try {
|
|
await workspaceCreate(rel, kind === "folder" ? "folder" : "file");
|
|
const order = { ...marks.order };
|
|
order[parent] = [...(order[parent] ?? []), finalName];
|
|
await persistMarks({ ...marks, order });
|
|
if (!childrenMap[parent] && parent !== "") {
|
|
const next = new Set(expanded);
|
|
next.add(parent);
|
|
expanded = next;
|
|
}
|
|
await load(parent);
|
|
onStatus?.(`Created ${rel}`);
|
|
if (kind === "note") {
|
|
onCreated?.({ name: finalName, rel_path: rel, kind: "file" });
|
|
}
|
|
} catch (err) {
|
|
error = err instanceof Error ? err.message : String(err);
|
|
}
|
|
}
|
|
|
|
function forgetFolder(rel: string) {
|
|
childrenMap = Object.fromEntries(Object.entries(childrenMap).filter(([path]) => path !== rel && !path.startsWith(`${rel}/`)));
|
|
expanded = new Set([...expanded].filter(path => path !== rel && !path.startsWith(`${rel}/`)));
|
|
}
|
|
|
|
async function handleDrop(target: TreeEntry, entries: TreeEntry[], place: DropPlace) {
|
|
const destination = place === "inside" ? target.rel_path : parentRel(target.rel_path);
|
|
// Load collapsed folders before checking for name conflicts.
|
|
try {
|
|
childrenMap = { ...childrenMap, [destination]: sortEntries(destination, await workspaceList(destination)) };
|
|
} catch (err) {
|
|
error = err instanceof Error ? err.message : String(err);
|
|
return;
|
|
}
|
|
const paths = new Map(entries.map(entry => [entry.rel_path, entry.rel_path]));
|
|
const result = await runTreeActions(place === "after" ? [...entries].reverse() : entries, async entry => {
|
|
const plan = planDrop(entry.rel_path, target, place, namesIn);
|
|
if (plan.action === "noop") return;
|
|
if (plan.action === "reorder") {
|
|
const order = { ...marks.order };
|
|
order[plan.parent] = plan.names;
|
|
await persistMarks({ ...marks, order });
|
|
await load(plan.parent);
|
|
return;
|
|
}
|
|
await workspaceRename(plan.from, plan.to);
|
|
paths.set(plan.from, plan.to);
|
|
forgetFolder(plan.from);
|
|
onEntryRenamed?.(plan.from, plan.to);
|
|
const order = { ...marks.order };
|
|
order[plan.fromParent] = plan.orderFrom;
|
|
order[plan.toParent] = plan.orderTo;
|
|
await persistMarks({ ...marks, order });
|
|
await load(plan.fromParent);
|
|
if (plan.toParent !== plan.fromParent) {
|
|
await load(plan.toParent);
|
|
}
|
|
});
|
|
if (place === "inside") expanded = new Set([...expanded, destination]);
|
|
selection = { paths: new Set(paths.values()), anchor: paths.values().next().value ?? null };
|
|
error = result.failures.length ? result.failures.join("\n") : null;
|
|
onStatus?.(`Moved ${result.completed.length} of ${entries.length} items`);
|
|
}
|
|
|
|
async function copyEntries(entries: TreeEntry[]) {
|
|
const roots = selectionRoots(entries);
|
|
const result = await runTreeActions(roots, entry => workspaceCopy(entry.rel_path));
|
|
for (const parent of new Set(roots.map(entry => parentRel(entry.rel_path)))) await load(parent);
|
|
error = result.failures.length ? result.failures.join("\n") : null;
|
|
onStatus?.(`Copied ${result.completed.length} of ${roots.length} items`);
|
|
}
|
|
|
|
async function deleteEntries(entries: TreeEntry[]) {
|
|
const roots = selectionRoots(entries);
|
|
const message = entries.length === 1
|
|
? `Permanently delete ${entries[0].name}${entries[0].kind === "folder" ? " and everything inside it" : ""}?`
|
|
: `Permanently delete ${entries.length} selected items${entries.some(entry => entry.kind === "folder") ? " and all contents of selected folders" : ""}?\n\n${roots.map(entry => entry.rel_path).join("\n")}`;
|
|
try {
|
|
if (!await confirm(message, { title: "Delete from disk", kind: "warning" })) return;
|
|
const result = await runTreeActions(roots, async entry => {
|
|
await workspaceDelete(entry.rel_path);
|
|
forgetFolder(entry.rel_path);
|
|
onEntryGone?.(entry.rel_path);
|
|
});
|
|
for (const parent of new Set(roots.map(entry => parentRel(entry.rel_path)))) await load(parent);
|
|
error = result.failures.length ? result.failures.join("\n") : null;
|
|
onStatus?.(`Deleted ${result.completed.length} of ${roots.length} items`);
|
|
} catch (err) {
|
|
error = err instanceof Error ? err.message : String(err);
|
|
}
|
|
}
|
|
|
|
function paneMenuItems(parent: string): MenuItem[] {
|
|
return [
|
|
{
|
|
kind: "action",
|
|
label: "Create folder",
|
|
icon: "folder-plus",
|
|
run: () => {
|
|
void createIn(parent, "folder");
|
|
},
|
|
},
|
|
{
|
|
kind: "action",
|
|
label: "Create new note",
|
|
icon: "file-plus",
|
|
run: () => {
|
|
void createIn(parent, "note");
|
|
},
|
|
},
|
|
...$pluginDocumentTypes.filter(item => item.type.create).map(({ owner, type }): MenuItem => ({
|
|
kind: "action", label: type.create!.label, icon: type.icon === "kanban" ? "kanban" : "file-plus",
|
|
run: () => { void (async () => {
|
|
const create = type.create!;
|
|
const typed = await requestText(create.label, create.defaultName);
|
|
if (typed === null) return;
|
|
const name = typed.trim().replace(new RegExp(`\\.${create.extension}$`, "i"), "");
|
|
if (!name || name.length > 100 || /[<>:"/\\|?*\x00-\x1f]/.test(name) || /[. ]$/.test(name) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name)) { error = "Enter a valid document name."; return; }
|
|
const fileName = `${name}.${create.extension}`;
|
|
const path = joinRel(parent, fileName);
|
|
try {
|
|
await createPluginDocument(owner, type.id, path);
|
|
expanded = new Set([...expanded, parent]);
|
|
await load(parent);
|
|
onOpenFile({ name: fileName, rel_path: path, kind: "file" }, true);
|
|
} catch (reason) { error = String(reason); }
|
|
})(); },
|
|
})),
|
|
];
|
|
}
|
|
|
|
function menuItems(entry: TreeEntry | null): MenuItem[] {
|
|
if (!entry) {
|
|
return [
|
|
...paneMenuItems(""),
|
|
{ kind: "sep" },
|
|
{
|
|
kind: "action",
|
|
label: "Show in Explorer",
|
|
icon: "folder",
|
|
run: () => {
|
|
void workspaceReveal("").catch((err) => {
|
|
error = err instanceof Error ? err.message : String(err);
|
|
});
|
|
},
|
|
},
|
|
];
|
|
}
|
|
const entries = actionEntries(entry, selection.paths, visiblePaths, findEntry);
|
|
const multiple = entries.length > 1;
|
|
const pinned = entries.every(item => pins.has(item.rel_path));
|
|
const bookmarked = entries.every(item => bookmarks.has(item.rel_path));
|
|
const createItems =
|
|
!multiple && entry.kind === "folder"
|
|
? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }]
|
|
: [];
|
|
return [
|
|
...createItems,
|
|
{
|
|
kind: "action",
|
|
label: multiple ? `Make copies (${entries.length})` : "Make a copy",
|
|
icon: "copy",
|
|
run: () => { void copyEntries(entries); },
|
|
},
|
|
{
|
|
kind: "action",
|
|
label: bookmarked ? (multiple ? "Remove bookmarks" : "Remove bookmark") : "Bookmark",
|
|
icon: "bookmark",
|
|
run: () => {
|
|
void persistMarks({
|
|
...marks,
|
|
bookmarks: setSelectedMarks(marks.bookmarks, entries, !bookmarked),
|
|
});
|
|
},
|
|
},
|
|
{ kind: "sep" },
|
|
{
|
|
kind: "action",
|
|
label: multiple ? "Copy workspace paths" : "Copy workspace path",
|
|
icon: "copy",
|
|
run: () => {
|
|
void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? "workspace paths" : "workspace path");
|
|
},
|
|
},
|
|
{
|
|
kind: "action",
|
|
label: multiple ? "Copy system paths" : "Copy system path",
|
|
icon: "copy",
|
|
run: () => {
|
|
void (async () => {
|
|
try {
|
|
const paths = await Promise.all(entries.map(item => workspaceAbsPath(item.rel_path)));
|
|
await copyText(paths.join("\n"), multiple ? "system paths" : "system path");
|
|
} catch (err) {
|
|
error = err instanceof Error ? err.message : String(err);
|
|
}
|
|
})();
|
|
},
|
|
},
|
|
{
|
|
kind: "action",
|
|
label: "Show in Explorer",
|
|
icon: "folder",
|
|
run: () => {
|
|
void (async () => {
|
|
const result = await runTreeActions(entries, item => workspaceReveal(item.rel_path));
|
|
error = result.failures.length ? result.failures.join("\n") : null;
|
|
})();
|
|
},
|
|
},
|
|
{ kind: "sep" },
|
|
{
|
|
kind: "action",
|
|
label: pinned ? "Unpin" : "Pin",
|
|
icon: "pin",
|
|
run: () => {
|
|
void persistMarks({
|
|
...marks,
|
|
pins: setSelectedMarks(marks.pins, entries, !pinned),
|
|
});
|
|
},
|
|
},
|
|
{
|
|
kind: "action",
|
|
label: "Rename",
|
|
icon: "rename",
|
|
disabled: multiple,
|
|
run: () => {
|
|
startRename(entry);
|
|
},
|
|
},
|
|
{
|
|
kind: "action",
|
|
label: multiple ? `Delete (${entries.length})` : "Delete",
|
|
icon: "trash",
|
|
run: () => { void deleteEntries(entries); },
|
|
},
|
|
];
|
|
}
|
|
</script>
|
|
|
|
<svelte:window onkeydown={onWindowKey} />
|
|
|
|
<div class="wrap">
|
|
<div class="ribbon tree-tools">
|
|
<IconButton icon="file-plus" label="New file" onclick={() => void createIn("", "note")} />
|
|
<IconButton icon="folder-plus" label="New folder" onclick={() => void createIn("", "folder")} />
|
|
<IconButton
|
|
icon="sort"
|
|
label={sortMode === "custom" ? "Sort: custom" : sortMode === "name" ? "Sort: name" : "Sort: name Z-A"}
|
|
onclick={cycleSort}
|
|
/>
|
|
<IconButton
|
|
icon={allCollapsed ? "unfold" : "fold"}
|
|
label={allCollapsed ? "Expand all" : "Collapse all"}
|
|
onclick={() => {
|
|
if (allCollapsed) {
|
|
void expandAll();
|
|
} else {
|
|
collapseAll();
|
|
}
|
|
}}
|
|
/>
|
|
</div>
|
|
<div
|
|
class="tree"
|
|
role="navigation"
|
|
aria-label="Workspace files"
|
|
oncontextmenu={(event) => {
|
|
event.preventDefault();
|
|
menu = { x: event.clientX, y: event.clientY, entry: null };
|
|
}}
|
|
>
|
|
{#if error}
|
|
<p class="error">{error}</p>
|
|
{/if}
|
|
{#if loading && !childrenMap[""]}
|
|
<p class="muted">Loading…</p>
|
|
{/if}
|
|
{#if childrenMap[""]}
|
|
<ul role="tree" aria-label="Workspace files" aria-multiselectable="true">
|
|
{#each childrenMap[""] as entry (entry.rel_path)}
|
|
<TreeNode
|
|
{entry}
|
|
{childrenMap}
|
|
{expanded}
|
|
{activePath}
|
|
{pins}
|
|
{bookmarks}
|
|
{onRowClick}
|
|
onContextMenu={(target, x, y) => {
|
|
if (!selection.paths.has(target.rel_path)) selectOnly(target.rel_path);
|
|
menu = { x, y, entry: target };
|
|
}}
|
|
{dropTarget}
|
|
{dragRel}
|
|
selectedPaths={selection.paths}
|
|
{selectionEdges}
|
|
{renameRel}
|
|
{renameDraft}
|
|
onRenameDraft={(value) => (renameDraft = value)}
|
|
onRenameCommit={() => void commitRename()}
|
|
onRenameCancel={cancelRename}
|
|
{onDragPointerDown}
|
|
/>
|
|
{/each}
|
|
</ul>
|
|
{/if}
|
|
</div>
|
|
</div>
|
|
|
|
{#if dragRel && dragPoint}
|
|
{@const landing = dropTarget ? findEntry(dropTarget.rel) : null}
|
|
<div class="drag-ghost" style:left="{dragPoint.x + 12}px" style:top="{dragPoint.y + 12}px">
|
|
<span>{dragEntries.length > 1 ? `${dragEntries.length} items` : dragRel.split("/").pop()}</span>
|
|
{#if imageLanding}
|
|
<span class="hint">Insert image</span>
|
|
{:else if landing && dropTarget}
|
|
<span class="hint">{dropHint(landing.name, dropTarget.place)}</span>
|
|
{/if}
|
|
</div>
|
|
{/if}
|
|
|
|
{#if menu}
|
|
<ContextMenu
|
|
label="File actions"
|
|
x={menu.x}
|
|
y={menu.y}
|
|
items={menuItems(menu.entry)}
|
|
onClose={() => (menu = null)}
|
|
/>
|
|
{/if}
|
|
|
|
<style>
|
|
.wrap {
|
|
height: 100%;
|
|
display: flex;
|
|
flex-direction: column;
|
|
min-height: 0;
|
|
}
|
|
|
|
.ribbon.tree-tools {
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
gap: 2px;
|
|
padding: 4px 6px;
|
|
border-bottom: 1px solid var(--rs-border);
|
|
}
|
|
|
|
.drag-ghost {
|
|
position: fixed;
|
|
z-index: 40;
|
|
pointer-events: none;
|
|
display: flex;
|
|
flex-direction: column;
|
|
gap: 2px;
|
|
padding: 4px 8px;
|
|
background: var(--rs-bg-elevated);
|
|
border: 1px solid var(--rs-accent);
|
|
border-radius: var(--rs-control-radius);
|
|
color: var(--rs-text-strong);
|
|
font-size: 12px;
|
|
}
|
|
|
|
.drag-ghost .hint {
|
|
color: var(--rs-accent);
|
|
}
|
|
|
|
.tree {
|
|
flex: 1;
|
|
overflow: auto;
|
|
padding: 6px 0 12px;
|
|
min-height: 0;
|
|
}
|
|
|
|
ul {
|
|
list-style: none;
|
|
margin: 0;
|
|
padding: 0 0 0 4px;
|
|
}
|
|
|
|
.muted,
|
|
.error {
|
|
margin: 8px 12px;
|
|
color: var(--rs-text-dim);
|
|
}
|
|
|
|
.error {
|
|
color: var(--rs-error);
|
|
}
|
|
</style>
|