Files
RuneStone/src/lib/layout/FileTree.svelte
T
Knotty Wyvern 0fdc991b2e Give way in narrow windows and use one icon for each action
Phase 5-6.

- Side panes give way when the window becomes narrow: the outline
  below 1100 pixels, the side pane below 800 pixels. They come back
  when the window grows. A pane that the user opens in a narrow window
  stays open, and the saved layout keeps the wide-window choice.
- One function has one icon. The SDK icon set gets duplicate, template,
  and tab. The reveal action has one label for each platform (Show in
  Explorer, Show in Finder, Show in file manager).
- The file menu follows one order: open, clipboard, organize, show and
  copy path, history, then Delete and Delete permanently in the error
  color after a separator. The tree copies paths through a Copy path
  submenu, as the tab menu does.
- The tree uses the shared chevron. Search hits come in groups by file,
  with counts and marked matches. Bookmarks show the name, the folder,
  and a remove button.
- All boolean settings use one switch design (src/lib/ui/switch.css).
  Browser settings apply at once, and the Save button is gone. The
  Settings window opens with the focus on its search.
- Targets of at least 24 pixels: the tab close button, outline rows,
  switches, and the settings search.
- Catalog rows in French, Japanese, and Simplified Chinese.
- Docs: UI-052, ui-design.md, and the user guide.

Tests: the new layout/panesAndSettings. Tests that closed or opened
panes by hand around narrow windows now rely on the new behavior, or
wait for the panes to give way before they reopen one. Tests that read
the old menu labels or the browser Save button use the new ones.
2026-10-28 21:31:36 -07:00

1077 lines
45 KiB
Svelte

<script lang="ts">
import { t } from "$lib/i18n";
import { onMount, tick, untrack } from "svelte";
import { createNote, noteTemplates, TEMPLATE_FOLDER, type NoteTemplate } from "$lib/workspace/templates";
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,
workspaceReveal,
workspaceOpenDefault,
workspaceOpenTerminal,
} from "$lib/workspace/api";
import type { Marks } from "$lib/workspace/marks";
import { moveMarks, replayMoveMarks } from "$lib/workspace/treeMoveHistory";
import type { WorkspaceSession } from "$lib/workspace/session.svelte";
import { actionEntries, selectionRoots, setSelectedMarks, runTreeActions } from "$lib/workspace/treeActions";
import {
dropPlaceAt,
joinRel,
parentRel,
planDrop,
uniqueName,
type DropPlace,
type DropTarget,
} from "$lib/workspace/treeDrop";
import { planRename } from "$lib/workspace/renamePath";
import { isImagePath } from "$lib/workspace/media";
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 { revealLabel } from "$lib/ui/menuItems";
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;
session: WorkspaceSession;
onStatus?: (message: string) => void;
onCreated?: (entry: TreeEntry) => void;
keysActive?: boolean;
showInternal?: boolean;
onSaveTemplate?: (entry: TreeEntry) => void;
onManageTemplates?: () => void;
};
let {
workspaceRoot,
activePath,
onOpenFile,
session,
onStatus,
onCreated,
keysActive = true,
showInternal = false,
onSaveTemplate,
onManageTemplates,
}: 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);
// The session store is the only writer of the marks.
const marks = $derived(session.marks.current);
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 skipClick = false;
let imageLanding = $state(false);
let cancelDrag: (() => void) | undefined;
let treeElement: HTMLDivElement;
let clipboard = $state<{ root: string; paths: string[]; cut: boolean } | null>(null);
type MoveBatch = { action?: "rename"; moves: { from: string; to: string }[]; before: Marks; after: Marks };
let undoMoves = $state<MoveBatch[]>([]);
let redoMoves = $state<MoveBatch[]>([]);
let moving = $state(false);
let templates = $state<NoteTemplate[]>([]);
$effect(() => {
void workspaceRoot;
let cancelled = false;
void noteTemplates().then(value => { if (!cancelled) templates = value; });
return () => { cancelled = true; };
});
onMount(() => {
const read = () => { void noteTemplates().then(value => templates = value); };
read(); window.addEventListener("runestone-templates-changed", read);
return () => window.removeEventListener("runestone-templates-changed", read);
});
$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, showInternal);
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;
undoMoves = []; redoMoves = []; clipboard = null;
expanded = new Set([""]);
selection = { paths: new Set(), anchor: null };
childrenMap = {};
void load("");
});
// Reload the loaded folders that a change touches. Expanded folders keep their state after a rename.
$effect(() => session.subscribe(change => {
const parents = new Set<string>();
if (change.type === "changed") change.paths.forEach(path => parents.add(parentRel(path)));
else if (change.type === "deleted") { forgetFolder(change.path); parents.add(parentRel(change.path)); }
else if (change.type === "renamed") { renameTreePaths(change.from, change.to); parents.add(parentRel(change.from)); parents.add(parentRel(change.to)); }
else if (change.type === "internal" && change.paths.some(path => path.startsWith(TEMPLATE_FOLDER))) void noteTemplates().then(value => templates = value);
for (const parent of parents) if (parent in untrack(() => childrenMap)) void load(parent);
}));
$effect(() => {
void showInternal;
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 };
}
// The tree has one Tab stop: the last focused row, else the selection, the open file, or the first row.
let focusRel = $state<string | null>(null);
const tabStop = $derived([focusRel, selection.anchor, activePath].find(path => path && visiblePaths.includes(path)) ?? visiblePaths[0] ?? null);
let typed = "", typedAt = 0;
async function focusRow(rel: string) {
focusRel = rel;
await tick();
const row = [...treeElement.querySelectorAll<HTMLElement>("[data-tree-rel]")].find(node => node.dataset.treeRel === rel);
row?.focus({ preventScroll: true });
row?.scrollIntoView({ block: "nearest" });
}
// The keys of the tree pattern: arrows move, Right opens or enters a folder, Left closes it or goes to its parent,
// Home and End go to the ends, and typed letters find a row. Shift with an arrow extends the selection.
function treeKey(event: KeyboardEvent) {
const row = event.target instanceof HTMLElement && event.target.matches("[data-tree-rel]") ? event.target : null;
if (!row || event.ctrlKey || event.metaKey || event.altKey) return;
const rel = row.dataset.treeRel!;
const entry = findEntry(rel);
const index = visiblePaths.indexOf(rel);
if (!entry || index < 0) return;
let next: string | undefined;
if (event.key === "ArrowDown") next = visiblePaths[index + 1];
else if (event.key === "ArrowUp") next = visiblePaths[index - 1];
else if (event.key === "Home") next = visiblePaths[0];
else if (event.key === "End") next = visiblePaths.at(-1);
else if (event.key === "ArrowRight") {
if (entry.kind !== "folder") return;
event.preventDefault();
if (!expanded.has(rel)) toggleFolder(entry);
else if (childrenMap[rel]?.length) next = childrenMap[rel][0].rel_path;
} else if (event.key === "ArrowLeft") {
event.preventDefault();
if (entry.kind === "folder" && expanded.has(rel)) toggleFolder(entry);
else if (rel.includes("/")) next = parentRel(rel);
} else if (event.key.length === 1 && event.key !== " ") {
const now = Date.now();
typed = (now - typedAt < 700 ? typed : "") + event.key.toLowerCase();
typedAt = now;
const order = [...visiblePaths.slice(index + (typed.length === 1 ? 1 : 0)), ...visiblePaths.slice(0, index + (typed.length === 1 ? 1 : 0))];
next = order.find(path => (path.split("/").pop() ?? path).toLowerCase().startsWith(typed));
if (!next) return;
} else return;
event.preventDefault();
if (!next) return;
selection = event.shiftKey && event.key.startsWith("Arrow") ? selectTreePath(selection, next, visiblePaths, { shiftKey: true }) : { paths: new Set([next]), anchor: next };
void focusRow(next);
}
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, done: 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?.(done);
}
async function persistMarks(change: (current: Marks) => Marks) {
try {
await session.marks.update(change);
} 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;
renameDraft = entry.name;
}
function cancelRename() {
renameRel = null;
renameDraft = "";
}
async function commitRename() {
const from = renameRel;
if (!from || moving) {
return;
}
const plan = planRename(from, renameDraft);
cancelRename();
if (plan.action === "noop") {
return;
}
if (plan.action === "error") {
error = plan.message;
return;
}
const operationRoot = workspaceRoot;
const before = session.marks.snapshot();
moving = true;
try {
if (!await session.rename(from, plan.to) || workspaceRoot !== operationRoot) return;
undoMoves = [...undoMoves, { action: "rename", moves: [{ from, to: plan.to }], before, after: session.marks.snapshot() }];
redoMoves = [];
renameTreePaths(from, plan.to);
await load(parentRel(from));
selectOnly(plan.to);
await focusTreePath(plan.to);
onStatus?.($t("Renamed to {path}", { path: plan.to }));
} catch (err) {
error = err instanceof Error ? err.message : String(err);
} finally { moving = false; }
}
function onWindowKey(event: KeyboardEvent) {
if (!keysActive) {
return;
}
if (event.target instanceof Element && treeElement?.contains(event.target)
&& !event.target.closest('input, textarea, [contenteditable="true"]')
&& (event.ctrlKey || event.metaKey) && !event.altKey) {
const key = event.key.toLowerCase();
if (key === "z" || key === "y") {
event.preventDefault(); event.stopPropagation();
void replayMoves(key === "y" || event.shiftKey);
return;
}
const entries = selectionRoots([...selection.paths].map(findEntry).filter((entry): entry is TreeEntry => !!entry));
if ((key === "c" || key === "x") && entries.length) {
event.preventDefault(); clipboard = { root: workspaceRoot, paths: entries.map(entry => entry.rel_path), cut: key === "x" }; return;
}
if (key === "v") {
event.preventDefault();
const selected = entries[0];
void pasteEntries(selected?.kind === "folder" ? selected.rel_path : selected ? parentRel(selected.rel_path) : "");
return;
}
}
// Delete moves the selection to the trash. Shift+Delete deletes it permanently.
// macOS keyboards: Cmd+Backspace and Cmd+Option+Backspace, as in Finder.
const deleteKey = event.key === "Delete" && !event.ctrlKey && !event.metaKey && !event.altKey;
const macDeleteKey = event.key === "Backspace" && event.metaKey && !event.ctrlKey && !event.shiftKey;
if ((deleteKey || macDeleteKey) && event.target instanceof Element && treeElement?.contains(event.target)
&& !event.target.closest('input, textarea, [contenteditable="true"]')) {
const entries = [...selection.paths].map(findEntry).filter((entry): entry is TreeEntry => !!entry);
if (!entries.length) return;
event.preventDefault(); event.stopPropagation();
void deleteEntries(entries, deleteKey ? event.shiftKey : event.altKey);
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" | "file") {
const operationRoot = workspaceRoot;
let name: string;
if (kind === "note" || kind === "folder") {
name = kind === "folder" ? "untitled" : "untitled.md";
if (kind === "folder") {
await load(parent);
if (workspaceRoot !== operationRoot || error) return;
}
} else {
const typed = await requestText($t("File name, including any extension"), "Untitled");
if (!typed) {
return;
}
const plan = planRename("", typed);
if (plan.action === "error") {
error = plan.message;
return;
}
name = typed.trim();
}
if (workspaceRoot !== operationRoot) return;
const finalName = kind === "file" ? name : uniqueName(kind === "folder" ? namesIn(parent).map(value => value.toLowerCase()) : namesIn(parent), name);
const rel = joinRel(parent, finalName);
try {
await workspaceCreate(rel, kind === "folder" ? "folder" : "file");
if (workspaceRoot !== operationRoot) return;
await persistMarks(current => ({ ...current, order: { ...current.order, [parent]: [...(current.order[parent] ?? []), finalName] } }));
if (kind === "folder" || (!childrenMap[parent] && parent !== "")) {
const next = new Set(expanded);
next.add(parent);
expanded = next;
}
await load(parent);
if (workspaceRoot !== operationRoot) return;
onStatus?.($t("Created {path}", { path: rel }));
if (kind === "folder") {
startRename({ name: finalName, rel_path: rel, kind: "folder" });
} else {
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}/`)));
}
function renameTreePaths(from: string, to: string) {
const rename = (path: string) => path === from || path.startsWith(`${from}/`) ? to + path.slice(from.length) : path;
expanded = new Set([...expanded].map(rename));
childrenMap = Object.fromEntries(Object.entries(childrenMap).map(([parent, entries]) => [rename(parent), entries.map(entry => {
const rel_path = rename(entry.rel_path);
return rel_path === entry.rel_path ? entry : { ...entry, rel_path, name: rel_path.split("/").pop()! };
})]));
selection = { paths: new Set([...selection.paths].map(rename)), anchor: selection.anchor === null ? null : rename(selection.anchor) };
}
async function handleDrop(target: TreeEntry, entries: TreeEntry[], place: DropPlace) {
if (moving) return;
const operationRoot = workspaceRoot;
const before = session.marks.snapshot();
const moves: MoveBatch["moves"] = [];
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, showInternal)) };
} catch (err) {
error = err instanceof Error ? err.message : String(err);
return;
}
const paths = new Map(entries.map(entry => [entry.rel_path, entry.rel_path]));
moving = true;
const result = await runTreeActions(place === "after" ? [...entries].reverse() : entries, async entry => {
if (workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped."));
const plan = planDrop(entry.rel_path, target, place, namesIn);
if (plan.action === "noop") return;
if (plan.action === "reorder") {
await persistMarks(current => ({ ...current, order: { ...current.order, [plan.parent]: plan.names } }));
await load(plan.parent);
return;
}
forgetFolder(plan.from);
const moved = await session.rename(plan.from, plan.to, current => {
const next = moveMarks(current, plan.from, plan.to);
return { ...next, order: { ...next.order, [plan.fromParent]: plan.orderFrom, [plan.toParent]: plan.orderTo } };
});
if (!moved || workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped."));
moves.push({ from: plan.from, to: plan.to });
paths.set(plan.from, plan.to);
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?.($t("Moved {count} of {total} items", { count: result.completed.length, total: entries.length }));
if (moves.length || JSON.stringify(before.order) !== JSON.stringify(marks.order)) {
undoMoves = [...undoMoves, { moves, before, after: session.marks.snapshot() }];
redoMoves = [];
}
moving = false;
await focusTreePath(paths.values().next().value);
}
export async function revealPath(path: string) {
const operationRoot = workspaceRoot;
const folders = path.split("/").slice(0, -1);
await load("");
let parent = "";
for (const folder of folders) {
if (workspaceRoot !== operationRoot) return;
parent = parent ? `${parent}/${folder}` : folder;
expanded = new Set([...expanded, parent]);
await load(parent);
}
if (workspaceRoot !== operationRoot) return;
selectOnly(path);
await focusTreePath(path);
const target = [...treeElement.querySelectorAll<HTMLElement>("[data-tree-rel]")].find(node => node.dataset.treeRel === path);
target?.scrollIntoView({ block: "nearest" });
}
async function focusTreePath(path?: string) {
await tick();
const target = [...treeElement.querySelectorAll<HTMLElement>("[data-tree-rel]")].find(node => node.dataset.treeRel === path);
(target ?? treeElement).focus({ preventScroll: true });
}
async function replayMoves(redo = false) {
if (moving) return;
const stack = redo ? redoMoves : undoMoves;
const batch = stack.at(-1);
if (!batch) return;
const operationRoot = workspaceRoot;
moving = true;
const applied: { from: string; to: string }[] = [];
try {
for (const move of redo ? batch.moves : [...batch.moves].reverse()) {
if (workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped."));
const from = redo ? move.from : move.to, to = redo ? move.to : move.from;
// The batch restores the marks after all moves, so each move leaves them alone.
if (!await session.rename(from, to, null) || workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped."));
applied.push({ from, to });
}
if (workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped."));
await persistMarks(current => replayMoveMarks(current, batch.before, batch.after, batch.moves, redo));
if (redo) { redoMoves = redoMoves.slice(0, -1); undoMoves = [...undoMoves, batch]; }
else { undoMoves = undoMoves.slice(0, -1); redoMoves = [...redoMoves, batch]; }
for (const move of applied) renameTreePaths(move.from, move.to);
const folders = new Set([...Object.keys(childrenMap), ...applied.flatMap(move => [parentRel(move.from), parentRel(move.to)])]);
for (const folder of folders) await load(folder);
selection = { paths: new Set(applied.map(move => move.to)), anchor: applied.at(-1)?.to ?? null };
await focusTreePath(applied.at(-1)?.to);
onStatus?.(redo ? "File change restored." : "File change undone.");
} catch (reason) {
const rollbackErrors: string[] = [];
for (const move of applied.reverse()) {
if (workspaceRoot !== operationRoot) { rollbackErrors.push("The original workspace is unavailable."); break; }
try { await session.rename(move.to, move.from, null); }
catch (failure) { rollbackErrors.push(String(failure)); }
}
if (rollbackErrors.length) { undoMoves = []; redoMoves = []; }
error = [String(reason), ...rollbackErrors].join("\n");
} finally { moving = false; }
}
async function pasteEntries(parent: string) {
if (!clipboard || clipboard.root !== workspaceRoot || moving) return;
const source = clipboard;
const operationRoot = workspaceRoot;
const before = session.marks.snapshot();
const moves: MoveBatch["moves"] = [];
moving = true;
const result = await runTreeActions(source.paths.map(rel_path => ({ rel_path, name: rel_path.split("/").pop()!, kind: "file" as const })), async entry => {
if (workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. Paste stopped."));
if (source.cut) {
const to = joinRel(parent, entry.name);
if (to === entry.rel_path) return;
if (!await session.rename(entry.rel_path, to) || workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. Paste stopped."));
moves.push({ from: entry.rel_path, to });
} else await workspaceCopy(entry.rel_path, parent, operationRoot);
});
if (moves.length) { undoMoves = [...undoMoves, { moves, before, after: session.marks.snapshot() }]; redoMoves = []; }
if (source.cut) clipboard = result.failures.length ? { ...source, paths: source.paths.filter(path => !moves.some(move => move.from === path)) } : null;
for (const folder of new Set([parent, ...source.paths.map(parentRel)])) await load(folder);
error = result.failures.length ? result.failures.join("\n") : null;
moving = false;
}
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?.($t("Copied {count} of {total} items", { count: result.completed.length, total: roots.length }));
}
// Delete moves items to the system trash. One file needs no confirmation, because the
// trash can restore it. A folder or several items need one. A permanent delete
// (Shift+Delete, or "Delete permanently" in the menu) always asks first.
function deleteQuestion(entries: TreeEntry[], roots: TreeEntry[], permanent: boolean): string | null {
if (entries.length === 1) {
const name = entries[0].name;
if (entries[0].kind === "folder") return $t(permanent ? "Permanently delete {name} and everything inside it?" : "Move {name} and everything inside it to the trash?", { name });
return permanent ? $t("Permanently delete {name}?", { name }) : null;
}
const folders = entries.some(entry => entry.kind === "folder");
const question = permanent
? $t(folders ? "Permanently delete {count} selected items and all contents of selected folders?" : "Permanently delete {count} selected items?", { count: entries.length })
: $t(folders ? "Move {count} selected items and all contents of selected folders to the trash?" : "Move {count} selected items to the trash?", { count: entries.length });
return question + "\n\n" + roots.map(entry => entry.rel_path).join("\n");
}
async function deleteEntries(entries: TreeEntry[], permanent = false) {
if (!entries.length) return;
const roots = selectionRoots(entries);
const question = deleteQuestion(entries, roots, permanent);
try {
if (question && !await confirm(question, { title: $t(permanent ? "Delete from disk" : "Move to trash"), kind: "warning" })) return;
const result = await runTreeActions(roots, async entry => {
await workspaceDelete(entry.rel_path, permanent);
forgetFolder(entry.rel_path);
session.deleted(entry.rel_path);
});
for (const parent of new Set(roots.map(entry => parentRel(entry.rel_path)))) await load(parent);
// The trash can be unavailable, for example on a network drive. A permanent delete stays an explicit choice.
const hint = !permanent && result.failures.length ? [$t("To delete permanently instead, select the items and press Shift+Delete.")] : [];
error = result.failures.length ? [...result.failures, ...hint].join("\n") : null;
onStatus?.(permanent
? $t("Deleted {count} of {total} items", { count: result.completed.length, total: roots.length })
: $t("Moved {count} of {total} items to the trash. Restore them from the system trash.", { count: result.completed.length, total: roots.length }));
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
}
async function createTreeNote(parent: string, template?: NoteTemplate) {
try {
const path = await createNote(parent, template);
session.changed([path]);
await load(parent);
onCreated?.({ name: path.split("/").pop()!, rel_path: path, kind: "file" });
} catch (reason) { error = String(reason); }
}
function paneMenuItems(parent: string): MenuItem[] {
const fromTemplate = (template?: NoteTemplate) => createTreeNote(parent, template);
// New note comes first, because notes are the most common new item.
return [
...(templates.length || onManageTemplates ? [{ kind: "group" as const, label: $t("New note"), icon: "file-plus" as const, run: () => { void fromTemplate(); }, items: [
{ kind: "action" as const, label: $t("Blank note"), icon: "file-plus" as const, run: () => { void fromTemplate(); } },
...templates.map(template => ({ kind: "action" as const, label: template.name, icon: "file-plus" as const, run: () => { void fromTemplate(template); } })),
...(onManageTemplates ? [{ kind: "sep" as const }, { kind: "action" as const, label: $t("Manage templates…"), icon: "template" as const, run: onManageTemplates }] : []),
] }] : [{ kind: "action" as const, label: $t("New note"), icon: "file-plus" as const, run: () => { void fromTemplate(); } }]),
{
kind: "action",
label: $t("New file…"),
icon: "file-plus",
run: () => { void createIn(parent, "file"); },
},
{ kind: "action", label: $t("New folder"), icon: "folder-plus", run: () => { void createIn(parent, "folder"); } },
...$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 = $t("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); }
})(); },
})),
];
}
// The file menu has one order: open, clipboard, organize, show and copy path, history, then Delete in the error color.
function terminalItem(parent: string): MenuItem {
return { kind: "action", label: $t("Open in terminal"), icon: "terminal", run: () => { void workspaceOpenTerminal(parent).catch(reason => error = String(reason)); } };
}
function pasteItem(parent: string): MenuItem {
return { kind: "action", label: $t("Paste"), icon: "paste", disabled: !clipboard || clipboard.root !== workspaceRoot || moving, run: () => { void pasteEntries(parent); } };
}
function moveHistoryItems(): MenuItem[] {
return [
{ kind: "action", label: undoMoves.at(-1)?.action === "rename" ? $t("Undo rename") : $t("Undo file move"), icon: "undo", disabled: !undoMoves.length || moving, run: () => { void replayMoves(); } },
{ kind: "action", label: redoMoves.at(-1)?.action === "rename" ? $t("Redo rename") : $t("Redo file move"), icon: "redo", disabled: !redoMoves.length || moving, run: () => { void replayMoves(true); } },
];
}
function revealItem(entries: TreeEntry[] | null): MenuItem {
return {
kind: "action",
label: $t(revealLabel()),
icon: "folder",
run: () => {
void (async () => {
if (!entries) { await workspaceReveal("").catch((err) => { error = err instanceof Error ? err.message : String(err); }); return; }
const result = await runTreeActions(entries, item => workspaceReveal(item.rel_path));
error = result.failures.length ? result.failures.join("\n") : null;
})();
},
};
}
function menuItems(entry: TreeEntry | null): MenuItem[] {
if (!entry) {
return [
...paneMenuItems(""),
{ kind: "sep" },
terminalItem(""),
{ kind: "sep" },
pasteItem(""),
{ kind: "sep" },
revealItem(null),
{ kind: "sep" },
...moveHistoryItems(),
];
}
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 parent = entry.kind === "folder" ? entry.rel_path : parentRel(entry.rel_path);
const copySystemPaths = async () => {
try {
const paths = await Promise.all(entries.map(item => workspaceAbsPath(item.rel_path)));
await copyText(paths.join("\n"), multiple ? $t("Copied system paths") : $t("Copied system path"));
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
};
return [
...(!multiple && entry.kind === "folder" ? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }] : []),
...(!multiple && entry.kind === "file" ? [
{ kind: "action" as const, label: $t("Open in new tab"), icon: "tab" as const, run: () => onOpenFile(entry, true) },
{ kind: "action" as const, label: $t("Open in default app"), icon: "external" as const, run: () => { void workspaceOpenDefault(entry.rel_path).catch(reason => error = String(reason)); } },
] : []),
terminalItem(parent),
{ kind: "sep" },
{ kind: "action", label: $t("Cut"), icon: "cut", run: () => { clipboard = { root: workspaceRoot, paths: selectionRoots(entries).map(item => item.rel_path), cut: true }; } },
{ kind: "action", label: $t("Copy"), icon: "copy", run: () => { clipboard = { root: workspaceRoot, paths: selectionRoots(entries).map(item => item.rel_path), cut: false }; } },
pasteItem(parent),
{ kind: "action", label: multiple ? $t("Make copies ({count})", { count: entries.length }) : $t("Make a copy"), icon: "duplicate", run: () => { void copyEntries(entries); } },
{ kind: "sep" },
{ kind: "action", label: $t("Rename"), icon: "rename", disabled: multiple, run: () => { startRename(entry); } },
{
kind: "action",
label: bookmarked ? (multiple ? $t("Remove bookmarks") : $t("Remove bookmark")) : $t("Bookmark"),
icon: "bookmark",
run: () => { void persistMarks(current => ({ ...current, bookmarks: setSelectedMarks(current.bookmarks, entries, !bookmarked) })); },
},
{
kind: "action",
label: pinned ? $t("Unpin") : $t("Pin"),
icon: "pin",
run: () => { void persistMarks(current => ({ ...current, pins: setSelectedMarks(current.pins, entries, !pinned) })); },
},
...(!multiple && entry.kind === "file" && /\.md$/i.test(entry.name) && onSaveTemplate ? [
{ kind: "action" as const, label: $t("Save as template"), icon: "template" as const, run: () => onSaveTemplate?.(entry) },
] : []),
{ kind: "sep" },
revealItem(entries),
{ kind: "group", label: $t("Copy path"), icon: "copy", items: [
{ kind: "action", label: $t("Workspace path"), icon: "copy", run: () => { void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? $t("Copied workspace paths") : $t("Copied workspace path")); } },
{ kind: "action", label: $t("System path"), icon: "copy", run: () => { void copySystemPaths(); } },
] },
{ kind: "sep" },
...moveHistoryItems(),
{ kind: "sep" },
{ kind: "action", label: multiple ? $t("Delete ({count})", { count: entries.length }) : $t("Delete"), icon: "trash", danger: true, run: () => { void deleteEntries(entries); } },
{ kind: "action", label: multiple ? $t("Delete permanently ({count})", { count: entries.length }) : $t("Delete permanently"), icon: "trash", danger: true, run: () => { void deleteEntries(entries, true); } },
];
}
</script>
<svelte:window onkeydown={onWindowKey} />
<div class="wrap">
<div class="ribbon tree-tools">
<IconButton icon="file-plus" label={$t("New note")} onclick={() => void createTreeNote("")} />
<IconButton icon="folder-plus" label={$t("New folder")} onclick={() => void createIn("", "folder")} />
<IconButton
icon="sort"
label={sortMode === "custom" ? $t("Sort: custom") : sortMode === "name" ? $t("Sort: name") : $t("Sort: name Z-A")}
onclick={cycleSort}
/>
<IconButton
icon={allCollapsed ? "unfold" : "fold"}
label={allCollapsed ? $t("Expand all") : $t("Collapse all")}
onclick={() => {
if (allCollapsed) {
void expandAll();
} else {
collapseAll();
}
}}
/>
</div>
<div
bind:this={treeElement}
class="tree"
tabindex="-1"
role="navigation"
aria-label={$t("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">{$t("Loading…")}</p>
{/if}
{#if childrenMap[""]}
<!-- svelte-ignore a11y_no_noninteractive_element_interactions (The tree handles the keys of its rows.) -->
<ul role="tree" aria-label={$t("Workspace files")} aria-multiselectable="true" onkeydown={treeKey}>
{#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}
{tabStop}
onFocusRow={(rel) => (focusRel = rel)}
/>
{/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 ? $t("{count} items", { count: dragEntries.length }) : dragRel.split("/").pop()}</span>
{#if imageLanding}
<span class="hint">{isImagePath(dragRel ?? "") ? $t("Insert image") : $t("Insert link")}</span>
{:else if landing && dropTarget}
<span class="hint">{$t(dropTarget.place === "inside" ? "Into {name}" : dropTarget.place === "before" ? "Before {name}" : "After {name}", { name: landing.name })}</span>
{/if}
</div>
{/if}
{#if menu}
<ContextMenu
label={$t("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>