Improve workspace navigation, search, and tab actions
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { MenuAction, MenuItem } from "./menuTypes";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
|
||||
type Props = {
|
||||
x: number;
|
||||
@@ -75,6 +76,7 @@
|
||||
disabled={sub.disabled}
|
||||
onclick={() => runAction(sub)}
|
||||
>
|
||||
{#if sub.icon}<Icon icon={sub.icon} />{/if}
|
||||
{sub.label}
|
||||
</button>
|
||||
{/if}
|
||||
@@ -88,6 +90,7 @@
|
||||
disabled={item.disabled}
|
||||
onclick={() => runAction(item)}
|
||||
>
|
||||
{#if item.icon}<Icon icon={item.icon} />{/if}
|
||||
{item.label}
|
||||
</button>
|
||||
{/if}
|
||||
@@ -101,6 +104,7 @@
|
||||
padding: 4px 0;
|
||||
background: var(--rs-bg-elevated);
|
||||
border: 1px solid var(--rs-border);
|
||||
border-radius: var(--rs-control-radius);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
@@ -139,13 +143,16 @@
|
||||
}
|
||||
|
||||
button {
|
||||
display: block;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--rs-text-strong);
|
||||
text-align: left;
|
||||
padding: 6px 12px;
|
||||
border-radius: var(--rs-control-radius);
|
||||
}
|
||||
|
||||
button:hover,
|
||||
|
||||
@@ -76,6 +76,10 @@
|
||||
if (mode !== "edit") previewMode = mode === "read" ? "preview" : "split";
|
||||
if (reading !== (mode !== "edit")) onToggleReading?.();
|
||||
}
|
||||
|
||||
export function toggleReadingView() {
|
||||
setDocumentMode(reading ? "edit" : "read");
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if !buffer || buffer.kind === "empty"}
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
workspaceRename,
|
||||
workspaceReveal,
|
||||
} from "$lib/workspace/api";
|
||||
import { loadMarks, saveMarks, togglePath, type Marks } from "$lib/workspace/marks";
|
||||
import { loadMarks, saveMarks, type Marks } from "$lib/workspace/marks";
|
||||
import { actionEntries, selectionRoots, setSelectedMarks, runTreeActions } from "$lib/workspace/treeActions";
|
||||
import {
|
||||
dropHint,
|
||||
dropPlaceAt,
|
||||
@@ -63,6 +64,7 @@
|
||||
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 });
|
||||
@@ -212,7 +214,7 @@
|
||||
return null;
|
||||
}
|
||||
const rel = hit.dataset.treeRel;
|
||||
if (!rel || rel === dragRel) {
|
||||
if (!rel || dragEntries.some(entry => rel === entry.rel_path || rel.startsWith(`${entry.rel_path}/`))) {
|
||||
return null;
|
||||
}
|
||||
const kind = hit.dataset.treeKind === "folder" ? "folder" : "file";
|
||||
@@ -228,6 +230,7 @@
|
||||
const startX = event.clientX;
|
||||
const startY = event.clientY;
|
||||
let started = false;
|
||||
let singleFile = false;
|
||||
cancelDrag?.();
|
||||
const onMove = (moveEvent: PointerEvent) => {
|
||||
if (!started) {
|
||||
@@ -235,11 +238,13 @@
|
||||
return;
|
||||
}
|
||||
started = true;
|
||||
selectOnly(entry.rel_path);
|
||||
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 = entry.kind === "file" && highlightImageDrop(entry.rel_path, dragPoint);
|
||||
imageLanding = singleFile && highlightImageDrop(entry.rel_path, dragPoint);
|
||||
dropTarget = readDropAt(moveEvent.clientX, moveEvent.clientY);
|
||||
};
|
||||
const clean = () => {
|
||||
@@ -248,7 +253,7 @@
|
||||
window.removeEventListener("pointercancel", clean);
|
||||
window.removeEventListener("keydown", onKey, true);
|
||||
highlightImageDrop();
|
||||
dragRel = null; dropTarget = null; dragPoint = null; imageLanding = false;
|
||||
dragRel = null; dragEntries = []; dropTarget = null; dragPoint = null; imageLanding = false;
|
||||
cancelDrag = undefined;
|
||||
};
|
||||
const onKey = (key: KeyboardEvent) => { if (key.key === "Escape") { key.preventDefault(); clean(); } };
|
||||
@@ -257,12 +262,12 @@
|
||||
skipClick = true;
|
||||
setTimeout(() => { skipClick = false; }, 0);
|
||||
}
|
||||
if (started && entry.kind === "file" && dropWorkspaceImage(entry.rel_path, { x: up.clientX, y: up.clientY })) { clean(); return; }
|
||||
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, dragRel, dropTarget.place);
|
||||
void handleDrop(target, [...dragEntries], dropTarget.place);
|
||||
}
|
||||
}
|
||||
clean();
|
||||
@@ -436,21 +441,35 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDrop(target: TreeEntry, draggedRel: string, place: DropPlace) {
|
||||
const plan = planDrop(draggedRel, target, place, namesIn);
|
||||
if (plan.action === "noop") {
|
||||
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;
|
||||
}
|
||||
try {
|
||||
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);
|
||||
onStatus?.(`Moved ${draggedRel}`);
|
||||
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;
|
||||
@@ -459,9 +478,36 @@
|
||||
if (plan.toParent !== plan.fromParent) {
|
||||
await load(plan.toParent);
|
||||
}
|
||||
selectOnly(plan.to);
|
||||
onEntryRenamed?.(plan.from, plan.to);
|
||||
onStatus?.(`Moved to ${plan.to}`);
|
||||
});
|
||||
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);
|
||||
}
|
||||
@@ -472,6 +518,7 @@
|
||||
{
|
||||
kind: "action",
|
||||
label: "Create folder",
|
||||
icon: "folder-plus",
|
||||
run: () => {
|
||||
void createIn(parent, "folder");
|
||||
},
|
||||
@@ -479,6 +526,7 @@
|
||||
{
|
||||
kind: "action",
|
||||
label: "Create new note",
|
||||
icon: "file-plus",
|
||||
run: () => {
|
||||
void createIn(parent, "note");
|
||||
},
|
||||
@@ -490,55 +538,51 @@
|
||||
if (!entry) {
|
||||
return paneMenuItems("");
|
||||
}
|
||||
const pinned = pins.has(entry.rel_path);
|
||||
const bookmarked = bookmarks.has(entry.rel_path);
|
||||
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 =
|
||||
entry.kind === "folder"
|
||||
!multiple && entry.kind === "folder"
|
||||
? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }]
|
||||
: [];
|
||||
return [
|
||||
...createItems,
|
||||
{
|
||||
kind: "action",
|
||||
label: "Make a copy",
|
||||
run: () => {
|
||||
void (async () => {
|
||||
try {
|
||||
const copy = await workspaceCopy(entry.rel_path);
|
||||
await load(parentRel(entry.rel_path));
|
||||
onStatus?.(`Copied to ${copy.rel_path}`);
|
||||
} catch (err) {
|
||||
error = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
})();
|
||||
},
|
||||
label: multiple ? `Make copies (${entries.length})` : "Make a copy",
|
||||
icon: "files",
|
||||
run: () => { void copyEntries(entries); },
|
||||
},
|
||||
{
|
||||
kind: "action",
|
||||
label: bookmarked ? "Remove bookmark" : "Bookmark",
|
||||
label: bookmarked ? (multiple ? "Remove bookmarks" : "Remove bookmark") : "Bookmark",
|
||||
icon: "bookmark",
|
||||
run: () => {
|
||||
void persistMarks({
|
||||
...marks,
|
||||
bookmarks: togglePath(marks.bookmarks, entry.rel_path),
|
||||
bookmarks: setSelectedMarks(marks.bookmarks, entries, !bookmarked),
|
||||
});
|
||||
},
|
||||
},
|
||||
{ kind: "sep" },
|
||||
{
|
||||
kind: "action",
|
||||
label: "Copy workspace path",
|
||||
label: multiple ? "Copy workspace paths" : "Copy workspace path",
|
||||
icon: "files",
|
||||
run: () => {
|
||||
void copyText(entry.rel_path, "workspace path");
|
||||
void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? "workspace paths" : "workspace path");
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: "action",
|
||||
label: "Copy system path",
|
||||
label: multiple ? "Copy system paths" : "Copy system path",
|
||||
icon: "files",
|
||||
run: () => {
|
||||
void (async () => {
|
||||
try {
|
||||
const abs = await workspaceAbsPath(entry.rel_path);
|
||||
await copyText(abs, "system path");
|
||||
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);
|
||||
}
|
||||
@@ -548,13 +592,11 @@
|
||||
{
|
||||
kind: "action",
|
||||
label: "Show in Explorer",
|
||||
icon: "folder-open",
|
||||
run: () => {
|
||||
void (async () => {
|
||||
try {
|
||||
await workspaceReveal(entry.rel_path);
|
||||
} catch (err) {
|
||||
error = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
const result = await runTreeActions(entries, item => workspaceReveal(item.rel_path));
|
||||
error = result.failures.length ? result.failures.join("\n") : null;
|
||||
})();
|
||||
},
|
||||
},
|
||||
@@ -565,33 +607,24 @@
|
||||
run: () => {
|
||||
void persistMarks({
|
||||
...marks,
|
||||
pins: togglePath(marks.pins, entry.rel_path),
|
||||
pins: setSelectedMarks(marks.pins, entries, !pinned),
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: "action",
|
||||
label: "Rename",
|
||||
icon: "pen",
|
||||
disabled: multiple,
|
||||
run: () => {
|
||||
startRename(entry);
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: "action",
|
||||
label: "Delete",
|
||||
run: () => {
|
||||
void (async () => {
|
||||
try {
|
||||
if (!await confirm(`Permanently delete ${entry.name}${entry.kind === "folder" ? " and everything inside it" : ""}?`, { title: "Delete from disk", kind: "warning" })) return;
|
||||
await workspaceDelete(entry.rel_path);
|
||||
await load(parentRel(entry.rel_path));
|
||||
onEntryGone?.(entry.rel_path);
|
||||
onStatus?.(`Deleted ${entry.rel_path}`);
|
||||
} catch (err) {
|
||||
error = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
})();
|
||||
},
|
||||
label: multiple ? `Delete (${entries.length})` : "Delete",
|
||||
icon: "trash",
|
||||
run: () => { void deleteEntries(entries); },
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -647,8 +680,8 @@
|
||||
{bookmarks}
|
||||
{onRowClick}
|
||||
onContextMenu={(target, x, y) => {
|
||||
if (!selection.paths.has(target.rel_path)) selectOnly(target.rel_path);
|
||||
menu = { x, y, entry: target };
|
||||
selectOnly(target.rel_path);
|
||||
}}
|
||||
{dropTarget}
|
||||
{dragRel}
|
||||
@@ -670,7 +703,7 @@
|
||||
{#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>{dragRel.split("/").pop()}</span>
|
||||
<span>{dragEntries.length > 1 ? `${dragEntries.length} items` : dragRel.split("/").pop()}</span>
|
||||
{#if imageLanding}
|
||||
<span class="hint">Insert image</span>
|
||||
{:else if landing && dropTarget}
|
||||
@@ -715,6 +748,7 @@
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { tick } from "svelte";
|
||||
import type { OutlineItem } from "$lib/workspace/outline";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import "$lib/ui/find.css";
|
||||
|
||||
type Props = {
|
||||
items: OutlineItem[];
|
||||
@@ -7,22 +11,73 @@
|
||||
};
|
||||
|
||||
let { items, onJump }: Props = $props();
|
||||
let searchOpen = $state(false);
|
||||
let query = $state("");
|
||||
let pane: HTMLElement;
|
||||
let searchInput = $state<HTMLInputElement>();
|
||||
const visibleItems = $derived(items.filter(item => item.text.toLocaleLowerCase().includes(query.toLocaleLowerCase())));
|
||||
|
||||
async function openSearch() {
|
||||
searchOpen = true;
|
||||
await tick();
|
||||
searchInput?.focus();
|
||||
searchInput?.select();
|
||||
}
|
||||
|
||||
function closeSearch() {
|
||||
searchOpen = false;
|
||||
query = "";
|
||||
pane.focus();
|
||||
}
|
||||
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "f") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void openSearch();
|
||||
} else if (event.key === "Escape" && searchOpen) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
closeSearch();
|
||||
} else if (event.key === "Enter" && event.target === searchInput && visibleItems[0]) {
|
||||
event.preventDefault();
|
||||
onJump(visibleItems[0].line);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="outline">
|
||||
<div class="pane-label">Outline</div>
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (The outline accepts focus for pane-local search shortcuts.) -->
|
||||
<section class="outline" aria-label="Outline" tabindex="0" bind:this={pane} onkeydown={keydown}>
|
||||
<div class="pane-label">
|
||||
<span>Outline</span>
|
||||
<IconButton icon="search" label="Find in outline (Ctrl+F)" active={searchOpen} onclick={() => void openSearch()} />
|
||||
</div>
|
||||
{#if searchOpen}
|
||||
<div class="rs-find-bar outline-search">
|
||||
<div class="rs-find-row">
|
||||
<div class="rs-find-field">
|
||||
<Icon icon="search" />
|
||||
<input bind:this={searchInput} bind:value={query} aria-label="Find in outline" placeholder="Find in outline" />
|
||||
</div>
|
||||
<IconButton icon="close" label="Close outline find (Escape)" onclick={closeSearch} />
|
||||
</div>
|
||||
<span class="match-count" role="status">{visibleItems.length} of {items.length} headings or symbols</span>
|
||||
</div>
|
||||
{/if}
|
||||
{#if items.length === 0}
|
||||
<p class="placeholder">No headings or symbols in this file.</p>
|
||||
{:else if visibleItems.length === 0}
|
||||
<p class="placeholder">No matching headings or symbols.</p>
|
||||
{:else}
|
||||
<ul>
|
||||
{#each items as item (item.line + item.text)}
|
||||
{#each visibleItems as item (item.line + item.text)}
|
||||
<li style:padding-left="{8 + (item.level - 1) * 12}px">
|
||||
<button type="button" onclick={() => onJump(item.line)}>{item.text}</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.outline {
|
||||
@@ -33,7 +88,10 @@
|
||||
}
|
||||
|
||||
.pane-label {
|
||||
padding: 6px 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 2px 8px 2px 10px;
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
@@ -42,6 +100,11 @@
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.outline-search { border-bottom: 1px solid var(--rs-border); }
|
||||
.outline-search :global(.rs-find-row) { flex-wrap: nowrap; }
|
||||
.outline-search :global(.rs-find-field) { flex-basis: 0; }
|
||||
.match-count { color: var(--rs-text-dim); font-size: 11px; }
|
||||
|
||||
.placeholder {
|
||||
margin: 12px;
|
||||
color: var(--rs-text-dim);
|
||||
@@ -54,7 +117,7 @@
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
button {
|
||||
li button {
|
||||
width: 100%;
|
||||
border-radius: var(--rs-control-radius);
|
||||
border: 0;
|
||||
@@ -67,7 +130,7 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
li button:hover {
|
||||
background: var(--rs-bg-active);
|
||||
color: var(--rs-text-strong);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy, tick } from "svelte";
|
||||
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
|
||||
import { actionIcons } from "$lib/ui/actionIcons";
|
||||
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
|
||||
import type { OpenBuffer } from "$lib/workspace/types";
|
||||
|
||||
type Props = {
|
||||
@@ -6,9 +10,175 @@
|
||||
activePath: string | null;
|
||||
onSelect: (relPath: string) => void;
|
||||
onClose: (relPath: string) => void;
|
||||
onMove: (relPath: string, index: number) => void;
|
||||
onCloseTabs: (relPath: string, scope: TabCloseScope) => void;
|
||||
onPin: (relPath: string) => void;
|
||||
fileActions: (tab: OpenBuffer) => ActionMenuItem[];
|
||||
};
|
||||
|
||||
let { tabs, activePath, onSelect, onClose }: Props = $props();
|
||||
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions }: Props = $props();
|
||||
let bar: HTMLDivElement;
|
||||
let dragged = $state<string | null>(null);
|
||||
let dropBefore = $state<string | null>(null);
|
||||
let dropAfter = $state<string | null>(null);
|
||||
let announcement = $state("");
|
||||
let cancelDrag = () => {};
|
||||
let suppressClick = false;
|
||||
let menu: HTMLElement | undefined;
|
||||
let menuAnchor: HTMLButtonElement | undefined;
|
||||
let menuPath = $state<string | null>(null);
|
||||
|
||||
$effect(() => {
|
||||
if (menuPath && !tabs.some(tab => tab.relPath === menuPath)) closeMenu();
|
||||
});
|
||||
|
||||
function tabButton(path: string) {
|
||||
return [...bar.querySelectorAll<HTMLButtonElement>('[role="tab"]')].find(button => button.dataset.path === path);
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
const path = activePath;
|
||||
if (path) void tick().then(() => tabButton(path)?.scrollIntoView({ block: "nearest", inline: "nearest" }));
|
||||
});
|
||||
|
||||
async function move(path: string, index: number) {
|
||||
onMove(path, index);
|
||||
await tick();
|
||||
tabButton(path)?.focus();
|
||||
const position = tabs.findIndex(tab => tab.relPath === path);
|
||||
if (position >= 0) announcement = `${tabs[position].name}, position ${position + 1} of ${tabs.length}`;
|
||||
}
|
||||
|
||||
function closeMenu(restoreFocus = false) {
|
||||
menu?.remove();
|
||||
menu = undefined;
|
||||
menuPath = null;
|
||||
if (restoreFocus) menuAnchor?.focus();
|
||||
}
|
||||
|
||||
function showMenu(button: HTMLButtonElement, path: string, x: number, y: number) {
|
||||
cancelDrag();
|
||||
closeMenu();
|
||||
menuAnchor = button;
|
||||
const index = tabs.findIndex(tab => tab.relPath === path);
|
||||
if (index < 0) return;
|
||||
menuPath = path;
|
||||
const run = (action: () => void) => () => { closeMenu(true); action(); };
|
||||
const closing = (label: string, scope: TabCloseScope): ActionMenuItem => ({
|
||||
label, icon: "close", disabled: !tabsToClose(tabs, path, scope).length,
|
||||
run: run(() => onCloseTabs(path, scope)),
|
||||
});
|
||||
const wrapActions = (items: ActionMenuItem[]): ActionMenuItem[] => items.map(item => {
|
||||
if ("separator" in item) return item;
|
||||
return { ...item, run: item.run ? run(item.run) : undefined,
|
||||
children: item.children ? wrapActions(item.children) : undefined };
|
||||
});
|
||||
menu = actionMenu(x, y, [
|
||||
closing("Close", "one"),
|
||||
closing("Close others", "others"),
|
||||
closing("Close tabs after", "after"),
|
||||
closing("Close all", "all"),
|
||||
{ separator: true },
|
||||
{ label: tabs[index].pinned ? "Unpin" : "Pin", icon: "pin", run: run(() => onPin(path)) },
|
||||
...(path === activePath ? wrapActions(fileActions(tabs[index])) : []),
|
||||
{ separator: true },
|
||||
{ label: "Move tab", icon: "swap", children: [
|
||||
{ label: "Move tab left", icon: "move-left", disabled: index <= 0,
|
||||
run: run(() => { void move(path, index - 1); }) },
|
||||
{ label: "Move tab right", icon: "move-right", disabled: index === tabs.length - 1,
|
||||
run: run(() => { void move(path, index + 1); }) },
|
||||
] },
|
||||
], () => closeMenu(true), "Tab actions");
|
||||
menu.classList.add("tab-menu");
|
||||
}
|
||||
|
||||
function onKey(event: KeyboardEvent, path: string) {
|
||||
if (event.key === "Enter" || event.key === " ") suppressClick = false;
|
||||
const index = tabs.findIndex(tab => tab.relPath === path);
|
||||
if (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const button = event.currentTarget as HTMLButtonElement, bounds = button.getBoundingClientRect();
|
||||
showMenu(button, path, bounds.left, bounds.bottom);
|
||||
} else if (["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key) && !event.ctrlKey && !event.metaKey) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const next = event.key === "Home" ? 0 : event.key === "End" ? tabs.length - 1
|
||||
: Math.max(0, Math.min(tabs.length - 1, index + (event.key === "ArrowLeft" ? -1 : 1)));
|
||||
if (event.altKey && event.shiftKey) void move(path, next);
|
||||
else if (!event.altKey && !event.shiftKey) {
|
||||
onSelect(tabs[next].relPath);
|
||||
tabButton(tabs[next].relPath)?.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function startDrag(event: PointerEvent, path: string) {
|
||||
if (event.button !== 0 || !event.isPrimary) return;
|
||||
cancelDrag();
|
||||
closeMenu();
|
||||
suppressClick = false;
|
||||
const startX = event.clientX, startY = event.clientY, pointerId = event.pointerId;
|
||||
let x = startX, y = startY, started = false, destination: number | null = null, frame = 0;
|
||||
const update = () => {
|
||||
dropBefore = dropAfter = null;
|
||||
destination = null;
|
||||
const bounds = bar.getBoundingClientRect();
|
||||
if (y < bounds.top || y > bounds.bottom) return;
|
||||
const others = [...bar.querySelectorAll<HTMLElement>(".tab")].filter(row => row.dataset.path !== path);
|
||||
const before = others.findIndex(row => { const rect = row.getBoundingClientRect(); return x < rect.left + rect.width / 2; });
|
||||
destination = before < 0 ? others.length : before;
|
||||
if (destination === tabs.findIndex(tab => tab.relPath === path)) return;
|
||||
if (before >= 0) dropBefore = others[before].dataset.path!;
|
||||
else dropAfter = others.at(-1)?.dataset.path ?? null;
|
||||
};
|
||||
const scroll = () => {
|
||||
if (!started) return;
|
||||
const bounds = bar.getBoundingClientRect();
|
||||
if (y >= bounds.top && y <= bounds.bottom) {
|
||||
const speed = x < bounds.left + 28 ? -10 : x > bounds.right - 28 ? 10 : 0;
|
||||
if (speed) { bar.scrollLeft += speed; update(); }
|
||||
}
|
||||
frame = requestAnimationFrame(scroll);
|
||||
};
|
||||
const clean = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
dragged = dropBefore = dropAfter = null;
|
||||
window.removeEventListener("pointermove", onMovePointer);
|
||||
window.removeEventListener("pointerup", onUp);
|
||||
window.removeEventListener("pointercancel", clean);
|
||||
window.removeEventListener("blur", clean);
|
||||
window.removeEventListener("keydown", onEscape, true);
|
||||
cancelDrag = () => {};
|
||||
};
|
||||
const onMovePointer = (e: PointerEvent) => {
|
||||
if (e.pointerId !== pointerId) return;
|
||||
x = e.clientX; y = e.clientY;
|
||||
if (!started && Math.hypot(x - startX, y - startY) < 5) return;
|
||||
e.preventDefault();
|
||||
if (!started) { started = true; suppressClick = true; dragged = path; frame = requestAnimationFrame(scroll); }
|
||||
update();
|
||||
};
|
||||
const onUp = (e: PointerEvent) => {
|
||||
if (e.pointerId !== pointerId) return;
|
||||
x = e.clientX; y = e.clientY;
|
||||
if (started) update();
|
||||
const target = destination;
|
||||
clean();
|
||||
if (started && target !== null) void move(path, target);
|
||||
};
|
||||
const onEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); clean(); }
|
||||
};
|
||||
cancelDrag = clean;
|
||||
window.addEventListener("pointermove", onMovePointer, { passive: false });
|
||||
window.addEventListener("pointerup", onUp);
|
||||
window.addEventListener("pointercancel", clean);
|
||||
window.addEventListener("blur", clean);
|
||||
window.addEventListener("keydown", onEscape, true);
|
||||
}
|
||||
|
||||
onDestroy(() => { cancelDrag(); closeMenu(); });
|
||||
|
||||
function onMiddleDown(event: MouseEvent) {
|
||||
if (event.button === 1) {
|
||||
@@ -25,20 +195,33 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="tabs" role="tablist" aria-label="Open files">
|
||||
<svelte:window onpointerdown={(event) => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }} onresize={() => closeMenu()} />
|
||||
|
||||
<div bind:this={bar} class="tabs" role="tablist" aria-label="Open files">
|
||||
{#each tabs as tab (tab.relPath)}
|
||||
<div class="tab" class:active={tab.relPath === activePath}>
|
||||
<div class="tab" data-path={tab.relPath} class:active={tab.relPath === activePath} class:dragging={dragged === tab.relPath}
|
||||
class:drop-before={dropBefore === tab.relPath} class:drop-after={dropAfter === tab.relPath}>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
data-path={tab.relPath}
|
||||
tabindex={tab.relPath === activePath ? 0 : -1}
|
||||
aria-selected={tab.relPath === activePath}
|
||||
title={tab.kind === "empty" ? tab.name : tab.relPath}
|
||||
onclick={() => onSelect(tab.relPath)}
|
||||
aria-describedby={tab.pinned ? `tab-pin-${tab.id}` : undefined}
|
||||
aria-keyshortcuts="Alt+Shift+ArrowLeft Alt+Shift+ArrowRight"
|
||||
title={`${tab.kind === "empty" ? tab.name : tab.relPath}\nDrag to reorder. Right-click for tab actions.`}
|
||||
onclick={() => { if (suppressClick) { suppressClick = false; return; } onSelect(tab.relPath); }}
|
||||
onpointerdown={(event) => startDrag(event, tab.relPath)}
|
||||
ondragstart={(event) => event.preventDefault()}
|
||||
onkeydown={(event) => onKey(event, tab.relPath)}
|
||||
oncontextmenu={(event) => { event.preventDefault(); event.stopPropagation(); showMenu(event.currentTarget, tab.relPath, event.clientX, event.clientY); }}
|
||||
onmousedown={onMiddleDown}
|
||||
onmouseup={(event) => onMiddleUp(event, tab.relPath)}
|
||||
>
|
||||
{#if tab.pinned}<svg class="pin" viewBox="0 0 24 24" aria-hidden="true">{@html actionIcons.pin}</svg>{/if}
|
||||
{tab.name}{tab.contents !== tab.saved ? " •" : ""}
|
||||
</button>
|
||||
{#if tab.pinned}<span class="sr-only" id={`tab-pin-${tab.id}`}>Pinned tab</span>{/if}
|
||||
<button
|
||||
class="close"
|
||||
type="button"
|
||||
@@ -53,6 +236,7 @@
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<span class="sr-only" role="status">{announcement}</span>
|
||||
|
||||
<style>
|
||||
.tabs {
|
||||
@@ -64,21 +248,43 @@
|
||||
}
|
||||
|
||||
.tab {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
max-width: 220px;
|
||||
flex-shrink: 0;
|
||||
border-radius: var(--rs-item-selection-radius) var(--rs-item-selection-radius) 0 0;
|
||||
border-radius: var(--rs-item-selection-radius);
|
||||
border-right: 1px solid var(--rs-border);
|
||||
background: var(--rs-bg);
|
||||
}
|
||||
|
||||
.tab.active {
|
||||
background: var(--rs-bg-active);
|
||||
box-shadow: inset 0 2px var(--rs-accent);
|
||||
background: var(--rs-item-selection-bg);
|
||||
box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border);
|
||||
}
|
||||
|
||||
.tab:hover { background: var(--rs-bg-active); }
|
||||
.tab.dragging { opacity: 0.5; }
|
||||
.tabs:has(.dragging) .tab > button:first-child { cursor: grabbing; }
|
||||
.tab.drop-before::before, .tab.drop-after::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
bottom: 3px;
|
||||
width: 3px;
|
||||
border-radius: var(--rs-control-radius);
|
||||
background: var(--rs-accent);
|
||||
pointer-events: none;
|
||||
}
|
||||
.tab.drop-before::before { left: 0; }
|
||||
.tab.drop-after::after { right: 0; }
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
|
||||
|
||||
.tab > button:first-child {
|
||||
border-radius: var(--rs-control-radius);
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
cursor: grab;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
@@ -96,6 +302,11 @@
|
||||
color: var(--rs-text-strong);
|
||||
}
|
||||
|
||||
.pin { width: 14px; height: 14px; margin-right: 6px; vertical-align: -2px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
|
||||
:global(.tab-menu) { width: 244px; border-radius: var(--rs-control-radius); }
|
||||
:global(.tab-menu button) { border-radius: var(--rs-control-radius); min-height: 30px; }
|
||||
:global(.tab-menu .table-cell-submenu) { border-radius: var(--rs-control-radius); }
|
||||
|
||||
.close {
|
||||
border: 0;
|
||||
border-radius: var(--rs-control-radius);
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
import { confirm } from "@tauri-apps/plugin-dialog";
|
||||
import { openUrl } from "@tauri-apps/plugin-opener";
|
||||
import { Documents } from "$lib/workspace/documents";
|
||||
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
|
||||
import type { ActionMenuItem } from "$lib/ui/actionMenu";
|
||||
import { requestText } from "$lib/workspace/dialogs.svelte";
|
||||
import TextDialog from "./TextDialog.svelte";
|
||||
import QuickOpen from "./QuickOpen.svelte";
|
||||
@@ -32,6 +34,7 @@
|
||||
workspaceRead,
|
||||
workspaceReadDataUrl,
|
||||
workspaceRename,
|
||||
workspaceReveal,
|
||||
workspaceWrite,
|
||||
workspaceWriteBytes,
|
||||
} from "$lib/workspace/api";
|
||||
@@ -68,6 +71,8 @@
|
||||
let saving = $state(false);
|
||||
let switching = false;
|
||||
let documents: Documents | null = null;
|
||||
let editorPane: EditorPane | undefined = $state();
|
||||
let closingTabs = false;
|
||||
const hasDirty = $derived(tabs.some(tab => tab.contents !== tab.saved));
|
||||
|
||||
function createDocuments() {
|
||||
@@ -194,10 +199,58 @@
|
||||
}
|
||||
|
||||
async function closeTab(relPath: string) {
|
||||
const tab = tabs.find(item => item.relPath === relPath);
|
||||
if (!tab) return;
|
||||
if (tab.contents !== tab.saved && !await confirm(`Discard unsaved edits in ${tab.name}?`, { title: "Close document", kind: "warning" })) return;
|
||||
documents?.close(relPath);
|
||||
await closeTabs(relPath, "one");
|
||||
}
|
||||
|
||||
async function closeTabs(path: string, scope: TabCloseScope) {
|
||||
const current = documents;
|
||||
if (!current || closingTabs || switching) return;
|
||||
closingTabs = true;
|
||||
try {
|
||||
const targets = tabsToClose(current.buffers, path, scope);
|
||||
for (const target of targets) {
|
||||
if (documents !== current || switching) break;
|
||||
const tab = current.buffers.find(item => item.id === target.id);
|
||||
if (!tab || (scope !== "one" && tab.pinned)) continue;
|
||||
const contents = tab.contents;
|
||||
if (contents !== tab.saved && !await confirm(`Discard unsaved edits in ${tab.name}?`, { title: "Close document", kind: "warning" })) break;
|
||||
if (documents !== current || switching || tab.contents !== contents) break;
|
||||
if (scope !== "one" && tab.pinned) continue;
|
||||
current.close(tab.relPath);
|
||||
}
|
||||
} catch (err) { error = String(err); }
|
||||
finally { closingTabs = false; }
|
||||
}
|
||||
|
||||
async function copyTabPath(path: string, system: boolean) {
|
||||
try {
|
||||
const text = system ? await workspaceAbsPath(path) : path;
|
||||
await navigator.clipboard.writeText(text);
|
||||
status = system ? "Copied system path" : "Copied workspace path";
|
||||
} catch (err) { error = String(err); }
|
||||
}
|
||||
|
||||
function tabFileActions(tab: OpenBuffer): ActionMenuItem[] {
|
||||
if (tab.kind === "empty") return [];
|
||||
const items: ActionMenuItem[] = [];
|
||||
if (tab.kind === "text" && isMarkdownPath(tab.relPath)) {
|
||||
items.push(
|
||||
{ label: reading ? "Editing view" : "Reading view", icon: "book", run: () => editorPane?.toggleReadingView() },
|
||||
{ label: isIde ? "Writing mode" : "Source mode", icon: "code", run: toggleChrome },
|
||||
);
|
||||
}
|
||||
items.push({ separator: true },
|
||||
{ label: "Rename…", icon: "rename", run: () => { void renameActive(); } },
|
||||
);
|
||||
if (tab.kind === "text") items.push({ label: "Save a copy…", icon: "copy", run: () => { void saveCopy(); } });
|
||||
items.push({ separator: true },
|
||||
{ label: "Copy path", icon: "copy", children: [
|
||||
{ label: "Workspace path", icon: "copy", run: () => { void copyTabPath(tab.relPath, false); } },
|
||||
{ label: "System path", icon: "copy", run: () => { void copyTabPath(tab.relPath, true); } },
|
||||
] },
|
||||
{ label: "Show in system explorer", icon: "folder", run: () => { void workspaceReveal(tab.relPath).catch(err => { error = String(err); }); } },
|
||||
);
|
||||
return items;
|
||||
}
|
||||
|
||||
async function openFile(entry: TreeEntry, line?: number, target: "current" | "new" = "new") {
|
||||
@@ -427,12 +480,13 @@
|
||||
if (!activePath || buffer?.kind === "empty") {
|
||||
return;
|
||||
}
|
||||
const current = activePath.split("/").pop() ?? activePath;
|
||||
const typed = await requestText("Rename to", current);
|
||||
if (typed == null) {
|
||||
const current = documents;
|
||||
const from = activePath;
|
||||
const typed = await requestText("Rename to", from.split("/").pop() ?? from);
|
||||
if (typed == null || documents !== current || switching) {
|
||||
return;
|
||||
}
|
||||
const plan = planRename(activePath, typed);
|
||||
const plan = planRename(from, typed);
|
||||
if (plan.action === "error") {
|
||||
error = plan.message;
|
||||
return;
|
||||
@@ -441,8 +495,9 @@
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await workspaceRename(activePath, plan.to);
|
||||
applyPathRename(activePath, plan.to);
|
||||
await workspaceRename(from, plan.to);
|
||||
current?.rename(from, plan.to);
|
||||
if (documents !== current) return;
|
||||
refreshToken += 1;
|
||||
status = `Renamed to ${plan.to}`;
|
||||
error = null;
|
||||
@@ -569,7 +624,9 @@
|
||||
</div>
|
||||
<div class="header-center" data-tauri-drag-region>
|
||||
{#if tabs.length > 0}
|
||||
<TabBar {tabs} {activePath} onSelect={selectTab} onClose={closeTab} />
|
||||
<TabBar {tabs} {activePath} onSelect={selectTab} onClose={closeTab}
|
||||
onCloseTabs={(path, scope) => void closeTabs(path, scope)} onPin={(path) => documents?.togglePin(path)}
|
||||
fileActions={tabFileActions} onMove={(path, index) => documents?.move(path, index)} />
|
||||
{/if}
|
||||
<IconButton icon="plus" label="New tab (Ctrl T)" onclick={newTab} />
|
||||
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
|
||||
@@ -650,6 +707,7 @@
|
||||
<details class="disk-review"><summary>View disk version</summary><pre>{buffer.diskContents}</pre></details>
|
||||
{/if}
|
||||
<EditorPane
|
||||
bind:this={editorPane}
|
||||
{tabs}
|
||||
hasWorkspace={!!workspace}
|
||||
onOpenWorkspace={() => void chooseWorkspace()}
|
||||
@@ -811,7 +869,7 @@
|
||||
}
|
||||
|
||||
.header-center :global(.tab.active) {
|
||||
background: var(--rs-bg-active);
|
||||
background: var(--rs-item-selection-bg);
|
||||
}
|
||||
|
||||
.ws {
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import type { IconName } from "$lib/ui/IconButton.svelte";
|
||||
|
||||
export type MenuAction = {
|
||||
kind: "action";
|
||||
label: string;
|
||||
run: () => void;
|
||||
disabled?: boolean;
|
||||
icon?: IconName;
|
||||
};
|
||||
|
||||
export type MenuSep = { kind: "sep" };
|
||||
|
||||
Reference in New Issue
Block a user