Initial RuneStone project

This commit is contained in:
Knotty Wyvern
2026-09-26 01:25:42 -07:00
commit bdc15e952d
190 changed files with 25986 additions and 0 deletions
+90
View File
@@ -0,0 +1,90 @@
<script lang="ts">
import { loadMarks } from "$lib/workspace/marks";
import type { TreeEntry } from "$lib/workspace/types";
type Props = {
refreshToken: number;
onOpen: (entry: TreeEntry) => void;
};
let { refreshToken, onOpen }: Props = $props();
let bookmarks = $state<string[]>([]);
$effect(() => {
void refreshToken;
void loadMarks().then((marks) => {
bookmarks = marks.bookmarks;
});
});
</script>
<div class="pane">
<div class="pane-label">Bookmarks</div>
{#if bookmarks.length === 0}
<p class="placeholder">Right-click a file and choose Bookmark.</p>
{:else}
<ul>
{#each bookmarks as rel (rel)}
<li>
<button
type="button"
onclick={() =>
onOpen({
name: rel.split("/").pop() ?? rel,
rel_path: rel,
kind: "file",
})}
>
{rel}
</button>
</li>
{/each}
</ul>
{/if}
</div>
<style>
.pane {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
}
.pane-label {
padding: 6px 10px;
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--rs-text-dim);
border-bottom: 1px solid var(--rs-border);
text-align: center;
}
.placeholder {
margin: 12px;
color: var(--rs-text-dim);
}
ul {
list-style: none;
margin: 0;
padding: 6px 0;
overflow: auto;
}
button {
width: 100%;
border-radius: var(--rs-control-radius);
border: 0;
background: transparent;
color: var(--rs-text);
text-align: left;
padding: 6px 10px;
}
button:hover {
background: var(--rs-bg-active);
color: var(--rs-text-strong);
}
</style>
+167
View File
@@ -0,0 +1,167 @@
<script lang="ts">
import type { MenuAction, MenuItem } from "./menuTypes";
type Props = {
x: number;
y: number;
items: MenuItem[];
onClose: () => void;
};
let { x, y, items, onClose }: Props = $props();
let root: HTMLElement | undefined = $state();
let left = $state(0);
let top = $state(0);
$effect(() => {
left = x;
top = y;
void items;
queueMicrotask(() => {
if (!root) {
return;
}
const rect = root.getBoundingClientRect();
left = Math.min(x, window.innerWidth - rect.width - 8);
top = Math.min(y, window.innerHeight - rect.height - 8);
});
});
function onWindowDown(event: MouseEvent) {
if (root && !root.contains(event.target as Node)) {
onClose();
}
}
function onKey(event: KeyboardEvent) {
if (event.key === "Escape") {
onClose();
}
}
function runAction(item: MenuAction) {
if (item.disabled) {
return;
}
item.run();
onClose();
}
</script>
<svelte:window onmousedown={onWindowDown} onkeydown={onKey} />
<div
bind:this={root}
class="menu"
style:left="{left}px"
style:top="{top}px"
role="menu"
>
{#each items as item, i (i)}
{#if item.kind === "sep"}
<div class="sep"></div>
{:else if item.kind === "group"}
<div class="group">
<div class="group-label" role="none">{item.label}</div>
<div class="flyout" role="menu">
{#each item.items as sub, j (`${i}-${j}`)}
{#if sub.kind === "sep"}
<div class="sep"></div>
{:else if sub.kind === "action"}
<button
type="button"
role="menuitem"
disabled={sub.disabled}
onclick={() => runAction(sub)}
>
{sub.label}
</button>
{/if}
{/each}
</div>
</div>
{:else}
<button
type="button"
role="menuitem"
disabled={item.disabled}
onclick={() => runAction(item)}
>
{item.label}
</button>
{/if}
{/each}
</div>
<style>
.menu,
.flyout {
min-width: 200px;
padding: 4px 0;
background: var(--rs-bg-elevated);
border: 1px solid var(--rs-border);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
}
.menu {
position: fixed;
z-index: 40;
}
.group {
position: relative;
}
.group-label {
padding: 6px 12px;
color: var(--rs-text);
cursor: default;
}
.group-label::after {
content: "▸";
float: right;
color: var(--rs-text-dim);
}
.flyout {
display: none;
position: absolute;
left: 100%;
top: 0;
z-index: 41;
}
.group:hover > .flyout,
.group:focus-within > .flyout {
display: block;
}
button {
display: block;
width: 100%;
border: 0;
background: transparent;
color: var(--rs-text-strong);
text-align: left;
padding: 6px 12px;
}
button:hover,
button:focus-visible {
background: var(--rs-bg-active);
outline: none;
}
button:disabled {
color: var(--rs-text-dim);
opacity: 0.55;
}
.sep {
height: 1px;
margin: 4px 0;
background: var(--rs-border);
}
</style>
+228
View File
@@ -0,0 +1,228 @@
<script lang="ts">
import EditorHost from "$lib/editor/EditorHost.svelte";
import LiveWriter from "$lib/editor/LiveWriter.svelte";
import { onDestroy, tick } from "svelte";
import { retainEditorSessions } from "$lib/editor/sessions";
import ImageViewer from "./ImageViewer.svelte";
import MarkdownView from "./MarkdownView.svelte";
import ModeSwitcher from "$lib/ui/ModeSwitcher.svelte";
import Icon from "$lib/ui/Icon.svelte";
import { isMarkdownPath } from "$lib/workspace/media";
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import type { TableContextActions } from "$lib/editor/tableCellActions";
type Props = {
buffer: OpenBuffer | null;
tabs: OpenBuffer[];
chrome: Chrome;
reading: boolean;
focusLine: number | null;
onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>;
onInsertImage?: (file: File) => Promise<string | null>;
onToggleReading?: () => void;
onToggleChrome?: () => void;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onOpenWorkspace: () => void;
onNewFile: () => void;
onQuickOpen: () => void;
hasWorkspace: boolean;
tableActions?: TableContextActions;
};
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onQuickOpen, hasWorkspace, tableActions }: Props = $props();
let previewMode = $state<"split" | "preview">("split");
let modeControls = $state<HTMLDivElement>();
const shouldFocusOnMount = () => !modeControls?.contains(document.activeElement);
const previewScroll = new Map<string, { top: number; left: number }>();
$effect(() => {
const ids = tabs.map(tab => tab.id);
retainEditorSessions(ids);
for (const id of previewScroll.keys()) if (!ids.includes(id)) previewScroll.delete(id);
});
onDestroy(() => retainEditorSessions([]));
function rememberPreviewScroll(node: HTMLDivElement, id: string) {
const saved = previewScroll.get(id);
let cancelled = false;
let restoring = true;
let frame = 0;
const save = () => {
if (!restoring) previewScroll.set(id, { top: node.scrollTop, left: node.scrollLeft });
};
node.addEventListener("scroll", save);
// Markdown renders in an effect; wait for its DOM before restoring offsets.
void tick().then(() => {
if (cancelled) return;
frame = requestAnimationFrame(() => {
node.scrollTop = saved?.top ?? 0;
node.scrollLeft = saved?.left ?? 0;
restoring = false;
});
});
return { destroy() {
cancelled = true;
cancelAnimationFrame(frame);
node.removeEventListener("scroll", save);
} };
}
const isIde = $derived(chrome === "Ide");
const isImage = $derived(buffer?.kind === "image");
const canPreview = $derived(buffer !== null && buffer.kind === "text" && isMarkdownPath(buffer.relPath));
const documentMode = $derived(!reading ? "edit" : previewMode === "preview" ? "read" : "split");
function setDocumentMode(mode: string) {
if (mode !== "edit") previewMode = mode === "read" ? "preview" : "split";
if (reading !== (mode !== "edit")) onToggleReading?.();
}
</script>
{#if !buffer || buffer.kind === "empty"}
<div class="empty">
<h1>{buffer?.kind === "empty" ? "New tab" : "One project. Notes, code, terminal."}</h1>
<p>{hasWorkspace ? "Open a file to get started, or create a note or script." : "Open a folder to work with your own files."}</p>
<div class="welcome-actions">
<button onclick={onOpenWorkspace}><Icon icon="folder-open" /> Open folder <kbd>Ctrl O</kbd></button>
{#if hasWorkspace}
<button onclick={onNewFile}><Icon icon="file-plus" /> New file <kbd>Ctrl N</kbd></button>
<button onclick={onQuickOpen}><Icon icon="search" /> Find a file <kbd>Ctrl P</kbd></button>
{/if}
</div>
<p class="hint">Save · Ctrl S &nbsp; Terminal · Ctrl ` &nbsp; Find in file · Ctrl F</p>
</div>
{:else}
<div class="editor">
<div class="chrome-bar">
<span class="breadcrumb" title={buffer.relPath}>{buffer.relPath}</span>
<div class="actions" bind:this={modeControls}>
{#if canPreview}
<ModeSwitcher
label="Document view"
value={documentMode}
options={[
{ value: "edit", label: "Edit", icon: "pen" },
{ value: "read", label: "Read", icon: "book-open" },
{ value: "split", label: "Split", icon: "split" },
]}
onchange={setDocumentMode}
/>
{/if}
<ModeSwitcher
label="Editor layout"
value={chrome}
options={[
{ value: "Ide", label: "IDE", icon: "code" },
{ value: "Writing", label: "Writer", icon: "text" },
]}
shortcut=" (Ctrl E)"
onchange={(mode) => { if (mode !== chrome) onToggleChrome?.(); }}
/>
</div>
</div>
<div class="body" class:split={reading && canPreview && previewMode === "split"}>
{#if isImage && buffer.imageUrl}
<ImageViewer src={buffer.imageUrl} name={buffer.name} />
{:else}
<div class="editor-wrap" class:hidden={reading && canPreview && previewMode === "preview"}>
{#key buffer.id}
{#if !isIde && canPreview && !reading}
<LiveWriter {buffer} {onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {focusLine} {tableActions} {shouldFocusOnMount} />
{:else}
<EditorHost {buffer} {chrome} {onChange} {onInsertImage} {focusLine} {tableActions} {shouldFocusOnMount} />
{/if}
{/key}
</div>
{#if reading && canPreview}
{#key buffer.id}
<div class="md-page" use:rememberPreviewScroll={buffer.id}>
<MarkdownView noteRel={buffer.relPath} contents={buffer.contents} {onOpenLink} />
</div>
{/key}
{/if}
{/if}
</div>
</div>
{/if}
<style>
.breadcrumb { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-right: auto; }
.welcome-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 12px; }
.welcome-actions button { display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); padding: 10px 14px; }
kbd { margin-left: 12px; color: var(--rs-text-dim); font-size: 11px; }
h1 { color: var(--rs-text-strong); font-size: 24px; font-weight: 500; }
.hint { margin-top: 32px; font-size: 12px; }
.hidden { display: none; }
.split .md-page { border-left: 1px solid var(--rs-border); }
.editor { container-type: inline-size; }
.empty,
.editor {
height: 100%;
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
flex: 1;
}
.empty {
align-items: center;
justify-content: center;
color: var(--rs-text-dim);
padding: 24px;
text-align: center;
}
.chrome-bar {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
height: 42px;
padding: 0 10px;
background: var(--rs-bg-elevated);
border-bottom: 1px solid var(--rs-border);
color: var(--rs-text-dim);
flex: 0 0 auto;
}
.actions {
display: flex;
align-items: center;
gap: 8px;
flex: 0 0 auto;
}
.body {
flex: 1;
display: flex;
min-height: 0;
min-width: 0;
}
.body > :global(*) {
flex: 1;
min-width: 0;
}
.md-page {
flex: 1;
min-height: 0;
overflow: auto;
padding: clamp(24px, 4vw, 56px) clamp(22px, 4vw, 64px) 96px;
scrollbar-gutter: stable;
}
.editor-wrap {
flex: 1;
min-width: 0;
min-height: 0;
position: relative;
}
@container (max-width: 680px) {
.body.split { flex-direction: column; }
.md-page { padding: 28px 24px 64px; }
.split .md-page { border-left: 0; border-top: 1px solid var(--rs-border); }
}
</style>
+748
View File
@@ -0,0 +1,748 @@
<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, togglePath, type Marks } from "$lib/workspace/marks";
import {
dropHint,
dropPlaceAt,
joinRel,
parentRel,
planDrop,
uniqueName,
type DropPlace,
type DropTarget,
} from "$lib/workspace/treeDrop";
import { planRename } 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";
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 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;
$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) };
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;
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 || rel === dragRel) {
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;
cancelDrag?.();
const onMove = (moveEvent: PointerEvent) => {
if (!started) {
if (Math.hypot(moveEvent.clientX - startX, moveEvent.clientY - startY) <= 8) {
return;
}
started = true;
selectOnly(entry.rel_path);
dragRel = entry.rel_path;
}
dragPoint = { x: moveEvent.clientX, y: moveEvent.clientY };
imageLanding = entry.kind === "file" && 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; 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 && entry.kind === "file" && 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);
}
}
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;
renameDraft = entry.name;
}
function cancelRename() {
renameRel = null;
renameDraft = "";
}
async function commitRename() {
const from = renameRel;
if (!from) {
return;
}
const plan = 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);
}
}
async function handleDrop(target: TreeEntry, draggedRel: string, place: DropPlace) {
const plan = planDrop(draggedRel, target, place, namesIn);
if (plan.action === "noop") {
return;
}
try {
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);
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);
}
selectOnly(plan.to);
onEntryRenamed?.(plan.from, plan.to);
onStatus?.(`Moved to ${plan.to}`);
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
}
function paneMenuItems(parent: string): MenuItem[] {
return [
{
kind: "action",
label: "Create folder",
run: () => {
void createIn(parent, "folder");
},
},
{
kind: "action",
label: "Create new note",
run: () => {
void createIn(parent, "note");
},
},
];
}
function menuItems(entry: TreeEntry | null): MenuItem[] {
if (!entry) {
return paneMenuItems("");
}
const pinned = pins.has(entry.rel_path);
const bookmarked = bookmarks.has(entry.rel_path);
const createItems =
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);
}
})();
},
},
{
kind: "action",
label: bookmarked ? "Remove bookmark" : "Bookmark",
run: () => {
void persistMarks({
...marks,
bookmarks: togglePath(marks.bookmarks, entry.rel_path),
});
},
},
{ kind: "sep" },
{
kind: "action",
label: "Copy workspace path",
run: () => {
void copyText(entry.rel_path, "workspace path");
},
},
{
kind: "action",
label: "Copy system path",
run: () => {
void (async () => {
try {
const abs = await workspaceAbsPath(entry.rel_path);
await copyText(abs, "system path");
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
})();
},
},
{
kind: "action",
label: "Show in Explorer",
run: () => {
void (async () => {
try {
await workspaceReveal(entry.rel_path);
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
})();
},
},
{ kind: "sep" },
{
kind: "action",
label: pinned ? "Unpin" : "Pin",
run: () => {
void persistMarks({
...marks,
pins: togglePath(marks.pins, entry.rel_path),
});
},
},
{
kind: "action",
label: "Rename",
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);
}
})();
},
},
];
}
</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) => {
menu = { x, y, entry: target };
selectOnly(target.rel_path);
}}
{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>{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
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);
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>
+32
View File
@@ -0,0 +1,32 @@
<script lang="ts">
type Props = {
src: string;
name: string;
};
let { src, name }: Props = $props();
</script>
<div class="viewer">
<img {src} alt={name} />
</div>
<style>
.viewer {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
overflow: auto;
padding: 16px;
background: var(--rs-bg);
}
img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
border: 1px solid var(--rs-border);
background: var(--rs-bg-elevated);
}
</style>
+161
View File
@@ -0,0 +1,161 @@
<script lang="ts">
import { tick, type Snippet } from "svelte";
import { workspaceReadDataUrl } from "$lib/workspace/api";
import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml";
import { renderDiagrams } from "$lib/workspace/diagrams";
import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media";
import { imageControls } from "$lib/editor/imageControls";
type Props = {
noteRel: string;
contents: string;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onEditBlock?: (start: number, end: number) => void;
editing?: { start: number; end: number } | null;
blockEditor?: Snippet;
};
let { noteRel, contents, onOpenLink, onEditBlock, editing = null, blockEditor }: Props = $props();
let html = $state("");
let sections = $state<MarkdownSection[]>([]);
let root: HTMLDivElement | undefined = $state();
async function loadUrls(noteRel: string, contents: string): Promise<Map<string, string>> {
const urls = new Map<string, string>();
await Promise.all(markdownImages(contents).map(async source => {
if (isRemoteImage(source)) {
urls.set(source, source.trim());
return;
}
let path = source;
try { path = decodeURIComponent(source); } catch { /* Keep literal malformed escapes. */ }
const primary = resolveImageRel(noteRel, path);
const normalized = path.replaceAll("\\", "/").replace(/^\/+/, "");
const base = normalized.split("/").pop() ?? path;
for (const candidate of new Set([primary, normalized, base])) {
try {
urls.set(source, await workspaceReadDataUrl(candidate));
return;
} catch { /* Try the workspace-relative attachment next. */ }
}
urls.set(source, "");
}));
return urls;
}
$effect(() => {
const path = noteRel;
const text = contents;
let cancelled = false;
html = renderMarkdownHtml(text, new Map());
sections = renderMarkdownSections(text, new Map());
void loadUrls(path, text).then(urls => {
if (!cancelled) {
html = renderMarkdownHtml(text, urls);
sections = renderMarkdownSections(text, urls);
}
});
return () => { cancelled = true; };
});
$effect(() => {
void html;
void sections;
void editing;
const el = root;
let cancelled = false;
let releaseImages: (() => void) | undefined;
if (el) void tick().then(() => {
if (cancelled) return;
releaseImages = imageControls(el);
return renderDiagrams(el, () => cancelled);
});
return () => { cancelled = true; releaseImages?.(); };
});
async function copyFence(button: HTMLButtonElement, body: string) {
try {
await navigator.clipboard.writeText(body);
} catch {
const ta = document.createElement("textarea");
ta.value = body;
ta.setAttribute("readonly", "");
ta.style.position = "fixed";
ta.style.left = "-9999px";
document.body.appendChild(ta);
ta.select();
try {
document.execCommand("copy");
} finally {
ta.remove();
}
}
button.dataset.copied = "true";
button.setAttribute("aria-label", "Copied");
button.title = "Copied";
window.setTimeout(() => {
if (button.isConnected) {
delete button.dataset.copied;
button.setAttribute("aria-label", "Copy code");
button.title = "Copy code";
}
}, 1200);
}
</script>
<!-- Events are delegated from generated native links and buttons, which support keyboard activation. -->
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
<div
class="reading"
bind:this={root}
onkeydown={(event) => {
if (event.target instanceof HTMLElement && event.target.classList.contains("md-edit-block") && (event.key === "Enter" || event.key === " ")) {
event.preventDefault();
onEditBlock?.(Number(event.target.dataset.start), Number(event.target.dataset.end));
}
}}
onclick={(event) => {
const copy = event.target instanceof Element ? event.target.closest("button.rs-fence-copy") : null;
if (copy instanceof HTMLButtonElement) {
event.preventDefault();
const pre = copy.closest("pre.md-code") ?? copy.closest("pre");
const body = pre?.querySelector("code")?.textContent ?? "";
void copyFence(copy, body);
return;
}
const node = event.target instanceof Element ? event.target.closest("a") : null;
if (!node) {
const target = event.target instanceof Element ? event.target : null;
if (target?.closest("textarea, button, summary")) return;
const block = target?.closest<HTMLElement>(".md-edit-block");
if (block) onEditBlock?.(Number(block.dataset.start), Number(block.dataset.end));
return;
}
const href = node.getAttribute("href") ?? "";
const kind = node.getAttribute("data-kind");
if (kind === "wiki") {
event.preventDefault();
onOpenLink?.("wiki", href);
return;
}
if (kind === "md") {
event.preventDefault();
onOpenLink?.("md", href);
}
}}
>
<h1 class="document-title">{markdownTitle(noteRel)}</h1>
{#if onEditBlock}
{#each sections.filter(section => !editing || section.start < editing.start) as section (section.start)}
<div class="md-edit-block" role="button" tabindex="0" aria-label="Edit document block" data-start={section.start} data-end={section.end}>{@html section.html}</div>
{/each}
{#if editing && blockEditor}
{@render blockEditor()}
{#each sections.filter(section => section.start >= editing.end && section.end > editing.end) as section (section.start)}
<div class="md-edit-block" role="button" tabindex="0" aria-label="Edit document block" data-start={section.start} data-end={section.end}>{@html section.html}</div>
{/each}
{/if}
{:else}
{@html html}
{/if}
</div>
+74
View File
@@ -0,0 +1,74 @@
<script lang="ts">
import type { OutlineItem } from "$lib/workspace/outline";
type Props = {
items: OutlineItem[];
onJump: (line: number) => void;
};
let { items, onJump }: Props = $props();
</script>
<div class="outline">
<div class="pane-label">Outline</div>
{#if items.length === 0}
<p class="placeholder">No headings or symbols in this file.</p>
{:else}
<ul>
{#each items 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>
<style>
.outline {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
}
.pane-label {
padding: 6px 10px;
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--rs-text-dim);
border-bottom: 1px solid var(--rs-border);
text-align: center;
}
.placeholder {
margin: 12px;
color: var(--rs-text-dim);
}
ul {
list-style: none;
margin: 0;
padding: 6px 0;
overflow: auto;
}
button {
width: 100%;
border-radius: var(--rs-control-radius);
border: 0;
background: transparent;
color: var(--rs-text);
text-align: left;
padding: 3px 8px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
button:hover {
background: var(--rs-bg-active);
color: var(--rs-text-strong);
}
</style>
+60
View File
@@ -0,0 +1,60 @@
<script lang="ts">
import { workspaceList } from "$lib/workspace/api";
import type { TreeEntry } from "$lib/workspace/types";
import { onMount } from "svelte";
let { onOpen, onClose }: { onOpen: (entry: TreeEntry) => void; onClose: () => void } = $props();
let query = $state("");
let files = $state<TreeEntry[]>([]);
let selected = $state(0);
let loading = $state(true);
let error = $state("");
let dialog: HTMLDialogElement;
let input: HTMLInputElement;
const matches = $derived(files.filter(file => query.toLowerCase().split(/\s+/).every(part => file.rel_path.toLowerCase().includes(part))).slice(0, 80));
function pick(entry?: TreeEntry) { if (entry) { onOpen(entry); onClose(); } }
onMount(() => {
dialog.showModal(); input.focus();
let cancelled = false;
void (async () => {
const queue = [""];
try {
while (queue.length && !cancelled) {
const entries = await workspaceList(queue.shift()!);
if (cancelled) return;
files = [...files, ...entries.filter(e => e.kind === "file")];
queue.push(...entries.filter(e => e.kind === "folder").map(e => e.rel_path));
}
} catch (err) { if (!cancelled) error = String(err); }
finally { if (!cancelled) loading = false; }
})();
return () => { cancelled = true; };
});
</script>
<dialog bind:this={dialog} oncancel={onClose}>
<input bind:this={input} bind:value={query} oninput={() => selected = 0} aria-label="Find a file" placeholder="Find a note or code file…" onkeydown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1)));
dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" });
}
if (event.key === "Enter") { event.preventDefault(); pick(matches[selected]); }
}} />
<div class="results">
{#each matches as entry, index (entry.rel_path)}
<button data-index={index} class:selected={selected === index} onclick={() => pick(entry)}><strong>{entry.name}</strong><span>{entry.rel_path}</span></button>
{/each}
{#if !matches.length}<p>{loading ? "Finding files…" : "No matching files."}</p>{/if}
</div>
<footer>{error || `${files.length} files${loading ? " · indexing…" : ""}`} <span>↑ ↓ select · Enter open · Esc close</span></footer>
</dialog>
<style>
dialog { margin-top: 12vh; padding: 0; width: min(640px, 85vw); background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); }
dialog::backdrop { background: #0008; }
input { width: 100%; padding: 16px; border: 0; background: var(--rs-bg); color: var(--rs-text-strong); }
.results { max-height: 50vh; overflow: auto; padding: 6px; }
button { width: 100%; display: flex; flex-direction: column; align-items: flex-start; gap: 3px; padding: 8px 10px; border: 0; background: transparent; text-align: left; }
button.selected, button:hover { background: var(--rs-bg-active); }
button span, footer { color: var(--rs-text-dim); font-size: 12px; }
footer { padding: 10px 14px; display: flex; justify-content: space-between; border-top: 1px solid var(--rs-border); }
</style>
+147
View File
@@ -0,0 +1,147 @@
<script lang="ts">
import IconButton from "$lib/ui/IconButton.svelte";
import { workspaceSearch, type SearchHit } from "$lib/workspace/api";
import type { TreeEntry } from "$lib/workspace/types";
type Props = {
onOpen: (entry: TreeEntry, line: number) => void;
searchRequest?: { text: string; id: number } | null;
};
let { onOpen, searchRequest }: Props = $props();
let query = $state("");
let hits = $state<SearchHit[]>([]);
let error = $state<string | null>(null);
let generation = 0;
$effect(() => { if (searchRequest) { query = searchRequest.text; void run(searchRequest.text); } });
async function run(value = query) {
const version = ++generation;
const q = value.trim();
if (!q) {
hits = [];
return;
}
try {
const results = await workspaceSearch(q);
if (version !== generation) return;
hits = results;
error = null;
} catch (err) {
if (version !== generation) return;
error = err instanceof Error ? err.message : String(err);
}
}
</script>
<div class="pane">
<div class="pane-label">Search</div>
<form
class="bar"
onsubmit={(event) => {
event.preventDefault();
void run();
}}
>
<input bind:value={query} placeholder="Search files and notes" />
<IconButton icon="search" label="Search workspace" type="submit" />
</form>
{#if error}
<p class="error">{error}</p>
{/if}
<ul>
{#each hits as hit (hit.rel_path + hit.line + hit.text)}
<li>
<button
type="button"
onclick={() =>
onOpen(
{
name: hit.rel_path.split("/").pop() ?? hit.rel_path,
rel_path: hit.rel_path,
kind: "file",
},
hit.line,
)}
>
<span class="path">{hit.rel_path}:{hit.line}</span>
<span class="text">{hit.text}</span>
</button>
</li>
{/each}
</ul>
</div>
<style>
.pane {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
}
.pane-label {
padding: 6px 10px;
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--rs-text-dim);
border-bottom: 1px solid var(--rs-border);
text-align: center;
}
.bar {
display: flex;
gap: 6px;
padding: 8px;
}
input {
flex: 1;
min-width: 0;
border-radius: 5px;
border: 1px solid var(--rs-border);
background: var(--rs-bg);
padding: 4px 8px;
}
ul {
list-style: none;
margin: 0;
padding: 0 0 12px;
overflow: auto;
}
button {
width: 100%;
border-radius: var(--rs-control-radius);
border: 0;
background: transparent;
text-align: left;
padding: 6px 10px;
}
button:hover {
background: var(--rs-bg-active);
}
.path {
display: block;
color: var(--rs-accent);
font-size: 12px;
}
.text {
display: block;
color: var(--rs-text-dim);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.error {
margin: 8px 10px;
color: var(--rs-error);
}
</style>
+114
View File
@@ -0,0 +1,114 @@
<script lang="ts">
import type { OpenBuffer } from "$lib/workspace/types";
type Props = {
tabs: OpenBuffer[];
activePath: string | null;
onSelect: (relPath: string) => void;
onClose: (relPath: string) => void;
};
let { tabs, activePath, onSelect, onClose }: Props = $props();
function onMiddleDown(event: MouseEvent) {
if (event.button === 1) {
event.preventDefault();
}
}
function onMiddleUp(event: MouseEvent, relPath: string) {
if (event.button === 1) {
event.preventDefault();
event.stopPropagation();
onClose(relPath);
}
}
</script>
<div class="tabs" role="tablist" aria-label="Open files">
{#each tabs as tab (tab.relPath)}
<div class="tab" class:active={tab.relPath === activePath}>
<button
type="button"
role="tab"
aria-selected={tab.relPath === activePath}
title={tab.kind === "empty" ? tab.name : tab.relPath}
onclick={() => onSelect(tab.relPath)}
onmousedown={onMiddleDown}
onmouseup={(event) => onMiddleUp(event, tab.relPath)}
>
{tab.name}{tab.contents !== tab.saved ? " •" : ""}
</button>
<button
class="close"
type="button"
aria-label="Close {tab.name}"
title="Close {tab.name}"
onclick={() => onClose(tab.relPath)}
onmousedown={onMiddleDown}
onmouseup={(event) => onMiddleUp(event, tab.relPath)}
>
×
</button>
</div>
{/each}
</div>
<style>
.tabs {
display: flex;
min-height: 32px;
overflow-x: auto;
background: var(--rs-bg-elevated);
border-bottom: 1px solid var(--rs-border);
}
.tab {
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-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);
}
.tab > button:first-child {
flex: 1;
min-width: 0;
border: 0;
background: transparent;
color: var(--rs-text-dim);
text-align: left;
padding: 0 8px 0 12px;
height: 32px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tab.active > button:first-child {
color: var(--rs-text-strong);
}
.close {
border: 0;
border-radius: var(--rs-control-radius);
background: transparent;
color: var(--rs-text-dim);
width: 22px;
height: 22px;
margin-right: 4px;
flex: 0 0 22px;
}
.close:hover {
color: var(--rs-text-strong);
background: var(--rs-bg);
}
</style>
+260
View File
@@ -0,0 +1,260 @@
<script lang="ts">
import { onMount, tick } from "svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
import { ptyProfiles, ptyNewWindow, ptyDictation, workspaceRead } from "$lib/workspace/api";
import { directoryCommand, fileCommand, parseTasks, readSettings, remember, type ShellProfile, type TerminalControl, type TerminalSettings as Settings } from "$lib/terminal/model";
import TerminalPicker from "$lib/terminal/TerminalPicker.svelte";
import TerminalSettings from "$lib/terminal/TerminalSettings.svelte";
import TerminalPane from "./TerminalPane.svelte";
type Session = { id: string; group: string; title: string; state: string; profile: ShellProfile; directory: string; weight: number; command?: string };
type Picker = { title: string; items: { label: string; detail?: string; value: string }[]; onPick: (value: string) => void; empty?: string };
let { cwd, visible, maximized = false, standalone = false, onClose, onMaximize = () => {}, activeFile = false, onRunFile, getSelection = () => "", onConfigureTasks }: {
cwd: string; visible: boolean; maximized?: boolean; standalone?: boolean; onClose: () => void; onMaximize?: () => void;
activeFile?: boolean; onRunFile?: () => Promise<string | null>; getSelection?: () => string; onConfigureTasks?: () => Promise<void>;
} = $props();
let sessions = $state<Session[]>([]);
let profiles = $state<ShellProfile[]>([]);
let settings = $state(readSettings());
let activeId = $state("");
let loading = $state(true);
let error = $state("");
let railWidth = $state(205);
let picker = $state<Picker | null>(null);
let showSettings = $state(false);
let recentCommands = $state<string[]>([]);
let recentDirectories = $state<string[]>([]);
let menu: HTMLElement | undefined;
let menuAnchor: HTMLElement | undefined;
let profileAnchor: HTMLDivElement;
let moreAnchor: HTMLDivElement;
let panes: HTMLDivElement;
let sequence = 0;
let stopResize: (() => void) | undefined;
let ready: Promise<void> = Promise.resolve();
const controls = new Map<string, TerminalControl>();
const active = $derived(sessions.find(session => session.id === activeId));
const group = $derived(sessions.filter(session => session.group === active?.group));
const totalWeight = $derived(group.reduce((sum, session) => sum + session.weight, 0));
function report(reason: unknown) { error = String(reason); }
function persist(next: Settings) {
settings = { ...next };
try { localStorage.setItem("runestone.terminal", JSON.stringify(settings)); } catch (reason) { report(reason); }
}
function defaultProfile() { return profiles.find(profile => profile.id === settings.defaultProfile) || profiles.find(profile => profile.kind !== "node") || profiles[0]; }
export function addSession(profile = defaultProfile(), split = false, command?: string, title?: string) {
if (!profile) return;
const id = crypto.randomUUID();
const next = { id, group: split && active ? active.group : id, title: title || `${profile.title} ${++sequence}`, state: "Starting", profile,
directory: split && active ? active.directory : cwd, weight: 1, command };
if (split) for (const member of group) member.weight = 1;
sessions = [...sessions, next]; activeId = id;
recentDirectories = remember(recentDirectories, next.directory);
}
function killSession(id: string) {
const previous = sessions.findIndex(session => session.id === id);
const sibling = sessions.find(session => session.group === sessions[previous]?.group && session.id !== id);
sessions = sessions.filter(session => session.id !== id);
if (activeId === id) activeId = sibling?.id || sessions[Math.max(0, previous - 1)]?.id || "";
void tick().then(() => controls.get(activeId)?.focus());
}
function select(id: string) { activeId = id; }
function closeMenu(focus = false) { menu?.remove(); menu = undefined; if (focus) menuAnchor?.querySelector<HTMLButtonElement>("button")?.focus(); }
function showMenu(anchor: HTMLElement, items: ActionMenuItem[], name: string) {
const same = menu && menuAnchor === anchor; closeMenu(); if (same) return;
menuAnchor = anchor;
const wrap = (entries: ActionMenuItem[]): ActionMenuItem[] => entries.map(item => "separator" in item ? item : { ...item,
children: item.children ? wrap(item.children) : undefined,
run: item.run ? () => { closeMenu(); item.run?.(); } : undefined });
const bounds = anchor.getBoundingClientRect();
menu = actionMenu(bounds.right - 430, bounds.bottom + 4, wrap(items), () => closeMenu(true), name);
}
function profileMenu() {
showMenu(profileAnchor, [
{ label: "New Terminal", icon: "plus", shortcut: "Ctrl+Shift+`", run: () => addSession() },
{ label: "New Terminal Window", icon: "external", shortcut: "Ctrl+Shift+Alt+`", run: () => void ptyNewWindow().catch(report) },
{ label: "Split Terminal", icon: "column", shortcut: "Ctrl+Shift+5", disabled: !active, run: () => addSession(active?.profile, true) },
{ separator: true },
...profiles.map(profile => ({ label: profile.title, icon: "code" as const, title: profile.kind === "node" ? "Node.js REPL with a local inspector. Attach using an external debugger." : undefined, run: () => addSession(profile) })),
{ label: "Split Terminal with Profile", icon: "column", disabled: !active, children: profiles.map(profile => ({ label: profile.title, icon: "code", run: () => addSession(profile, true) })) },
{ separator: true },
{ label: "Configure Terminal Settings", icon: "format", run: () => showSettings = true },
{ label: "Select Default Profile", icon: "select", run: () => picker = { title: "Select default terminal profile", items: profiles.filter(profile => profile.kind !== "node").map(profile => ({ label: profile.title, value: profile.id, detail: profile.id === settings.defaultProfile ? "Default" : undefined })), onPick: value => persist({ ...settings, defaultProfile: value }) } },
{ separator: true },
{ label: "Run Task…", icon: "task", run: () => void runTask() },
{ label: "Configure Tasks…", icon: "code", disabled: !onConfigureTasks, run: () => void onConfigureTasks?.().catch(report) },
], "Terminal profiles");
}
async function runFile() {
const target = active;
if (!target || !onRunFile) return;
try { const path = await onRunFile(); if (path) controls.get(target.id)?.send(fileCommand(path, target.profile.kind)); } catch (reason) { report(reason); }
}
function runSelection() {
const text = getSelection();
if (!text) { error = "Select text in the editor first."; return; }
controls.get(activeId)?.send(text);
}
function historyPicker(kind: "commands" | "directories") {
const target = active;
if (!target) return;
picker = { title: kind === "commands" ? "Run recent command" : "Go to recent directory",
items: (kind === "commands" ? recentCommands : recentDirectories).map(value => ({ label: value, value })),
empty: kind === "commands" ? "No commands yet. Shell commands appear after the next prompt." : "No directories yet.",
onPick: value => { try { controls.get(target.id)?.send(kind === "commands" ? value : directoryCommand(value, target.profile.kind)); } catch (reason) { report(reason); } } };
}
async function runTask() {
try {
const tasks = parseTasks(await workspaceRead(".runestone/tasks.json"));
picker = { title: "Run task", items: tasks.map((task, index) => ({ label: task.label, detail: task.command, value: String(index) })), empty: "No tasks configured. Choose Configure Tasks… to add one.", onPick: index => {
const task = tasks[Number(index)];
const profile = task.profile ? profiles.find(profile => profile.id === task.profile) : defaultProfile();
if (!profile) { error = `Task profile is unavailable: ${task.profile}`; return; }
addSession(profile, false, task.command, task.label);
} };
} catch (reason) { error = `Cannot load .runestone/tasks.json. Use Configure Tasks… to create or edit it. ${String(reason)}`; }
}
function moreMenu() {
showMenu(moreAnchor, [
{ label: "Scroll to Previous Command", icon: "up", shortcut: "Ctrl+UpArrow", disabled: !active, run: () => controls.get(activeId)?.scrollCommand(-1) },
{ label: "Scroll to Next Command", icon: "down", shortcut: "Ctrl+DownArrow", disabled: !active, run: () => controls.get(activeId)?.scrollCommand(1) },
{ label: "Clear Terminal", icon: "clear", disabled: !active, run: () => controls.get(activeId)?.clear() },
{ label: "Run Active File", icon: "code", disabled: !active || !activeFile, run: () => void runFile() },
{ label: "Run Selected Text", icon: "select", disabled: !active || !activeFile, run: runSelection },
{ label: "Start Dictation", icon: "comment", disabled: !active, title: "Start Windows voice typing in the focused terminal", run: () => { controls.get(activeId)?.focus(); void ptyDictation().catch(report); } },
{ separator: true },
{ label: "Go to Recent Directory…", icon: "external", shortcut: "Ctrl+G", disabled: !active, run: () => historyPicker("directories") },
{ label: "Run Recent Command…", icon: "task", shortcut: "Ctrl+Alt+R", disabled: !active, run: () => historyPicker("commands") },
], "Terminal actions");
}
export async function command(action: "new" | "split" | "window" | "previous" | "next" | "commands" | "directories") {
await ready;
if (action === "new") addSession();
else if (action === "split") addSession(active?.profile || defaultProfile(), !!active);
else if (action === "window") void ptyNewWindow().catch(report);
else if (action === "previous" || action === "next") controls.get(activeId)?.scrollCommand(action === "previous" ? -1 : 1);
else historyPicker(action);
}
function beginResize(event: PointerEvent, update: (x: number) => void) {
if (event.button !== 0) return;
event.preventDefault(); stopResize?.();
const move = (event: PointerEvent) => update(event.clientX);
stopResize = () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", stop); window.removeEventListener("pointercancel", stop); stopResize = undefined; };
const stop = () => stopResize?.();
window.addEventListener("pointermove", move); window.addEventListener("pointerup", stop); window.addEventListener("pointercancel", stop);
}
function resizeRail(event: PointerEvent) { const x = event.clientX, width = railWidth; beginResize(event, next => railWidth = Math.min(340, Math.max(140, width + x - next))); }
function resizeSplit(event: PointerEvent, session: Session) {
const index = group.indexOf(session), previous = group[index - 1];
if (!previous) return;
const x = event.clientX, before = previous.weight, after = session.weight, width = panes.clientWidth, total = totalWeight;
beginResize(event, next => { const change = (next - x) / width * total; previous.weight = Math.min(before + after - .15, Math.max(.15, before + change)); session.weight = before + after - previous.weight; });
}
function paneLeft(session: Session) { return group.slice(0, group.indexOf(session)).reduce((sum, item) => sum + item.weight, 0) / totalWeight * 100; }
onMount(() => {
let disposed = false;
ready = ptyProfiles().then(found => {
if (disposed) return;
profiles = found;
if (!profiles.some(profile => profile.id === settings.defaultProfile)) settings.defaultProfile = defaultProfile()?.id || "";
if (profiles.length) addSession(); else error = "No supported shells were found on PATH.";
}).catch(report).finally(() => loading = false);
const outside = (event: PointerEvent) => { if (menu && !menu.contains(event.target as Node) && !menuAnchor?.contains(event.target as Node)) closeMenu(); };
const resize = () => closeMenu();
window.addEventListener("pointerdown", outside); window.addEventListener("resize", resize);
return () => { disposed = true; closeMenu(); stopResize?.(); window.removeEventListener("pointerdown", outside); window.removeEventListener("resize", resize); };
});
$effect(() => { if (!visible) { closeMenu(); picker = null; showSettings = false; } });
</script>
<div class="dock" style:--rail="{railWidth}px">
<header class="ribbon">
<span class="label" title={cwd}>Terminal</span><span class="directory" title={active?.directory || cwd}>{active?.directory || cwd}</span>
<div class="actions">
{#if sessions.length === 1}<span class="single-session" title={`${active?.title} · ${active?.state}`}>{active?.profile.title}</span>{/if}
<IconButton icon="plus" label="New terminal" disabled={loading || !profiles.length} onclick={() => addSession()} />
<div bind:this={profileAnchor}><IconButton icon="chevron-down" label="Terminal profiles and tasks" disabled={loading} onclick={profileMenu} /></div>
<IconButton icon="split" label="Split terminal (Ctrl+Shift+5)" disabled={!active} onclick={() => addSession(active?.profile, true)} />
<div bind:this={moreAnchor}><IconButton icon="more" label="More terminal actions" onclick={moreMenu} /></div>
<IconButton icon="trash" label="Kill terminal" disabled={!active} onclick={() => killSession(activeId)} />
{#if !standalone}<IconButton icon={maximized ? "restore" : "maximize"} label={maximized ? "Restore panel" : "Maximize panel"} onclick={onMaximize} />{/if}
<IconButton icon="close" label={standalone ? "Close terminal window" : "Hide terminal (sessions keep running)"} onclick={onClose} />
</div>
</header>
{#if error}<div class="error" role="alert"><span>{error}</span><button aria-label="Dismiss terminal error" onclick={() => error = ""}>×</button></div>{/if}
<div class="body">
<div class="panes" bind:this={panes}>
{#each sessions as session (session.id)}
<div class="pane" class:shown={session.group === active?.group} class:focused={session.id === activeId}
style:left="{session.group === active?.group ? paneLeft(session) : 0}%" style:width="{session.group === active?.group ? session.weight / totalWeight * 100 : 100}%">
{#if group.length > 1 && session.group === active?.group}<div class="pane-label">{session.title}</div>{/if}
<TerminalPane id={session.id} {cwd} directory={session.directory} profile={session.profile} {settings}
active={visible && session.group === active?.group} focused={session.id === activeId} onFocus={() => activeId = session.id}
onState={state => { session.state = state; if (state === "Running" && session.command) { controls.get(session.id)?.send(session.command); session.command = undefined; } }}
onControl={control => { if (control) controls.set(session.id, control); else controls.delete(session.id); }}
onCommand={command => recentCommands = remember(recentCommands, command)}
onDirectory={directory => { session.directory = directory; recentDirectories = remember(recentDirectories, directory); }} />
{#if session.group === active?.group && group.indexOf(session) > 0}
<div class="split-gutter" role="separator" aria-label="Resize split terminals" aria-orientation="vertical" onpointerdown={event => resizeSplit(event, session)}></div>
{/if}
</div>
{/each}
{#if !sessions.length}<div class="empty"><p>{loading ? "Detecting terminal profiles…" : "No terminal sessions."}</p><button disabled={loading || !profiles.length} onclick={() => addSession()}>Start a terminal</button></div>{/if}
</div>
{#if sessions.length > 1}
<div class="gutter" role="separator" aria-orientation="vertical" aria-label="Resize terminal list" onpointerdown={resizeRail}></div>
<nav class="rail" aria-label="Terminal list">
{#each sessions as session (session.id)}
<div class="item" data-session={session.id} class:active={session.id === activeId} class:grouped={sessions.filter(item => item.group === session.group).length > 1}>
<button class="pick" aria-pressed={session.id === activeId} title={`${session.title} · ${session.state} · ${session.directory}`} onclick={() => select(session.id)}
onkeydown={event => {
if (event.key === "Delete") { event.preventDefault(); killSession(session.id); }
if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); const next = sessions[(sessions.indexOf(session) + (event.key === "ArrowDown" ? 1 : sessions.length - 1)) % sessions.length]; activeId = next.id; (event.currentTarget.closest("nav")?.querySelector(`[data-session="${next.id}"] .pick`) as HTMLButtonElement)?.focus(); }
}}><span class="shell-icon" aria-hidden="true">›_</span><span class="session-name">{session.title}<small>{session.state}</small></span></button>
<div class="row-actions">
<IconButton icon="split" label={`Split ${session.title}`} onclick={() => { activeId = session.id; addSession(session.profile, true); }} />
<IconButton icon="trash" label={`Kill ${session.title} (Del)`} onclick={() => killSession(session.id)} />
</div>
</div>
{/each}
</nav>
{/if}
</div>
</div>
{#if picker}<TerminalPicker {...picker} onClose={() => picker = null} />{/if}
{#if showSettings}<TerminalSettings {settings} {profiles} onSave={persist} onClose={() => showSettings = false} />{/if}
<style>
.dock { display: flex; flex-direction: column; height: 100%; min-height: 0; }
.ribbon { display: flex; align-items: center; gap: 10px; flex: 0 0 36px; padding: 0 8px; background: var(--rs-bg-elevated); }
.label { font-size: 13px; color: var(--rs-text-strong); }
.directory { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--rs-text-dim); font-size: 12px; }
.actions, .row-actions { display: flex; align-items: center; flex-shrink: 0; }
.single-session { max-width: 130px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; color: var(--rs-text-dim); margin-right: 6px; }
.body { display: flex; flex: 1; min-height: 0; }
.panes { flex: 1; position: relative; min-width: 0; min-height: 0; }
.pane { display: flex; flex-direction: column; position: absolute; top: 0; bottom: 0; visibility: hidden; min-width: 0; overflow: hidden; }
.pane.shown { visibility: visible; }
.pane :global(.term) { flex: 1; min-height: 0; height: auto; }
.pane-label { flex: 0 0 23px; padding: 3px 10px; font-size: 11px; color: var(--rs-text-dim); border-top: 1px solid transparent; }
.focused .pane-label { color: var(--rs-text-strong); border-top-color: var(--rs-accent); }
.split-gutter { position: absolute; top: 0; bottom: 0; left: 0; width: 4px; cursor: col-resize; background: var(--rs-border); }
.gutter { flex: 0 0 4px; cursor: col-resize; }
.gutter:hover, .split-gutter:hover { background: var(--rs-accent); }
.rail { flex: 0 0 var(--rail); width: var(--rail); overflow: auto; padding: 4px; border-left: 1px solid var(--rs-border); }
.item { display: flex; align-items: center; min-width: 0; border-left: 2px solid transparent; }
.item.grouped { border-left-color: var(--rs-border); }
.item.active { background: var(--rs-bg-active); border-left-color: var(--rs-accent); }
.pick { display: flex; align-items: center; gap: 7px; flex: 1; min-width: 0; border: 0; background: transparent; text-align: left; padding: 5px; }
.shell-icon { color: var(--rs-text-dim); }
.session-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
small { display: block; font-size: 10px; color: var(--rs-text-dim); }
.row-actions { visibility: hidden; }
.item:hover .row-actions, .item:focus-within .row-actions, .item.active .row-actions { visibility: visible; }
.error { padding: 7px 12px; display: flex; align-items: center; gap: 8px; color: var(--rs-error); font-size: 12px; border-bottom: 1px solid var(--rs-border); }
.error span { flex: 1; }
.error button, .empty button { background: var(--rs-bg-active); border: 1px solid var(--rs-border); padding: 4px 8px; }
.empty { padding: 20px; color: var(--rs-text-dim); }
@media (max-width: 700px) { .rail { flex-basis: 150px; width: 150px; } .row-actions { display: none; } .directory, .single-session { display: none; } .label { flex: 1; } }
</style>
+218
View File
@@ -0,0 +1,218 @@
<script lang="ts">
import { listen } from "@tauri-apps/api/event";
import { FitAddon } from "@xterm/addon-fit";
import { Terminal } from "@xterm/xterm";
import { onMount } from "svelte";
import { ptyClose, ptyOpen, ptyResize, ptyWrite } from "$lib/workspace/api";
import { terminalShortcut, type ShellProfile, type TerminalControl, type TerminalSettings } from "$lib/terminal/model";
import "@xterm/xterm/css/xterm.css";
type Props = {
id: string;
cwd: string;
active: boolean;
focused: boolean;
profile: ShellProfile;
directory: string;
settings: TerminalSettings;
onFocus: () => void;
onControl: (control: TerminalControl | null) => void;
onCommand: (command: string) => void;
onDirectory: (directory: string) => void;
onState: (state: string) => void;
};
let { id, cwd, active, focused, profile, directory, settings, onFocus, onControl, onCommand, onDirectory, onState }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let focusTerminal: (() => void) | undefined = $state();
let instance = $state.raw<Terminal>();
let resizeTerminal: (() => void) | undefined;
$effect(() => { if (active && focused && !document.activeElement?.closest(".rail")) focusTerminal?.(); });
$effect(() => {
if (instance) {
instance.options.fontSize = settings.fontSize;
instance.options.scrollback = settings.scrollback;
instance.options.cursorBlink = settings.cursorBlink;
requestAnimationFrame(() => resizeTerminal?.());
}
});
onMount(() => {
if (!host) {
return;
}
const term = new Terminal({
scrollback: settings.scrollback,
fontFamily: "Cascadia Code, Cascadia Mono, Consolas, monospace",
fontSize: settings.fontSize,
cursorBlink: settings.cursorBlink,
allowProposedApi: true,
theme: {
background: "#141414",
foreground: "#e6e6e6",
cursor: "#82aaff",
selectionBackground: "#264f78",
black: "#3b4252",
red: "#bf616a",
green: "#a3be8c",
yellow: "#ebcb8b",
blue: "#81a1c1",
magenta: "#b48ead",
cyan: "#88c0d0",
white: "#e5e9f0",
},
});
const fit = new FitAddon();
term.loadAddon(fit);
term.open(host);
instance = term;
term.attachCustomKeyEventHandler(event => !terminalShortcut(event));
let disposed = false;
let opened = false;
let exited = false;
const pendingInput: string[] = [];
let writes = Promise.resolve();
const unlisteners: (() => void)[] = [];
const fail = (err: unknown) => {
if (!disposed) term.writeln(`\r\n${String(err)}`);
};
const resize = () => {
if (disposed || !host?.clientWidth || !host?.clientHeight) return;
fit.fit();
if (opened && !exited) void ptyResize(id, term.cols, term.rows).catch(fail);
};
resizeTerminal = resize;
focusTerminal = () => { resize(); term.focus(); };
const send = (data: string) => {
if (exited || disposed) return;
if (!opened) { pendingInput.push(data); return; }
writes = writes.then(() => ptyWrite(id, data)).catch(fail);
};
const onData = term.onData(send);
let markers: import("@xterm/xterm").IMarker[] = [];
let prompt: { marker: import("@xterm/xterm").IMarker; column: number } | undefined;
const promptParser = term.parser.registerOscHandler(133, data => {
if (data === "A") {
const marker = term.registerMarker(0);
if (marker) markers = [...markers.filter(item => !item.isDisposed), marker].slice(-1000);
}
if (data === "B") {
prompt?.marker.dispose();
const marker = term.registerMarker(0);
prompt = marker ? { marker, column: term.buffer.active.cursorX } : undefined;
}
return true;
});
const integration = term.parser.registerOscHandler(633, data => {
const separator = data.indexOf(";");
const type = data.slice(0, separator), value = data.slice(separator + 1);
try {
if (type === "Cwd") onDirectory(value);
if (type === "RSCwd" || type === "RSCommand") {
const decoded = new TextDecoder().decode(Uint8Array.from(atob(value), char => char.charCodeAt(0)));
if (type === "RSCwd") onDirectory(decoded); else onCommand(decoded);
}
} catch { /* Ignore malformed shell integration output. */ }
return true;
});
const keys = term.onKey(({ domEvent }) => {
if (profile.kind !== "cmd" || domEvent.key !== "Enter" || !prompt || prompt.marker.isDisposed) return;
const buffer = term.buffer.active;
let command = "";
for (let line = prompt.marker.line; line <= buffer.baseY + buffer.cursorY; line++) {
command += buffer.getLine(line)?.translateToString(true, line === prompt.marker.line ? prompt.column : 0) || "";
}
if (command.trim()) onCommand(command);
prompt.marker.dispose(); prompt = undefined;
});
onControl({
focus: () => { resize(); term.focus(); },
clear: () => { markers.forEach(marker => marker.dispose()); markers = []; term.clear(); term.focus(); },
scrollCommand: direction => {
const lines = markers.filter(marker => !marker.isDisposed).map(marker => marker.line);
const current = term.buffer.active.viewportY;
const target = direction < 0 ? lines.reverse().find(line => line < current) : lines.find(line => line > current);
if (target !== undefined) term.scrollToLine(target); else if (direction > 0) term.scrollToBottom();
},
send: (text, execute = true) => {
if (exited) return;
term.paste(text.replace(/\r?\n/g, "\r"));
if (execute) send("\r");
term.focus();
},
});
const start = async () => {
try {
// Subscribe before spawning: shells and agents can print immediately.
const offData = await listen<{ id: string; data: number[] }>("pty-data", (event) => {
if (!disposed && event.payload.id === id) term.write(new Uint8Array(event.payload.data));
});
unlisteners.push(offData);
if (disposed) return;
const offExit = await listen<{ id: string; code: number | null }>("pty-exit", (event) => {
if (!disposed && event.payload.id === id) {
exited = true;
onState(`Exited${event.payload.code === null ? "" : ` (${event.payload.code})`}`);
term.writeln(`\r\n[Process exited${event.payload.code === null ? "" : ` with code ${event.payload.code}`} ]`);
}
});
unlisteners.push(offExit);
if (disposed) return;
resize();
await ptyOpen(id, term.cols, term.rows, cwd, profile.id, directory);
opened = true;
if (disposed) { await ptyClose(id); return; }
// Includes xterm's replies to startup cursor-position queries.
for (const data of pendingInput.splice(0)) {
writes = writes.then(() => ptyWrite(id, data)).catch(fail);
}
if (!exited) onState("Running");
resize();
if (active && focused) term.focus();
} catch (err) {
fail(err);
if (!disposed) onState("Failed");
} finally {
if (disposed) unlisteners.splice(0).forEach((off) => off());
}
};
void start();
const observer = new ResizeObserver(resize);
observer.observe(host);
return () => {
disposed = true;
focusTerminal = undefined;
instance = undefined;
resizeTerminal = undefined;
onControl(null);
observer.disconnect();
onData.dispose();
promptParser.dispose(); integration.dispose(); keys.dispose();
unlisteners.splice(0).forEach((off) => off());
if (opened) void ptyClose(id).catch(() => {});
term.dispose();
};
});
</script>
<div class="term" data-cwd={directory} bind:this={host} onfocusin={onFocus}></div>
<style>
.term {
height: 100%;
min-height: 0;
padding: 4px;
background: #141414;
}
.term :global(.xterm),
.term :global(.xterm-viewport) {
height: 100%;
}
.term :global(.xterm-viewport) {
/* Whole terminal rows can leave a gap above the bottom edge. */
background-color: transparent;
}
</style>
+29
View File
@@ -0,0 +1,29 @@
<script lang="ts">
import { dialogs, finishText } from "$lib/workspace/dialogs.svelte";
let element: HTMLDialogElement | undefined = $state();
let input: HTMLInputElement | undefined = $state();
$effect(() => {
if (dialogs.text && element && input) {
element.showModal(); input.focus(); input.select();
}
});
</script>
{#if dialogs.text}
<dialog bind:this={element} oncancel={(event) => { event.preventDefault(); finishText(null); }}>
<form onsubmit={(event) => { event.preventDefault(); finishText(dialogs.text?.value.trim() || null); }}>
<label for="text-request">{dialogs.text.title}</label>
<input id="text-request" bind:this={input} bind:value={dialogs.text.value} autocomplete="off" />
<div><button type="button" onclick={() => finishText(null)}>Cancel</button><button type="submit" disabled={!dialogs.text.value.trim()}>Continue</button></div>
</form>
</dialog>
{/if}
<style>
dialog { width: min(480px, 90vw); padding: 22px; background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); }
dialog::backdrop { background: #0008; }
form { display: flex; flex-direction: column; gap: 16px; }
input { width: 100%; background: var(--rs-bg); color: var(--rs-text-strong); border: 1px solid var(--rs-border); padding: 9px; }
form div { display: flex; justify-content: flex-end; gap: 8px; }
button { padding: 6px 12px; background: var(--rs-bg-active); border: 1px solid var(--rs-border); }
</style>
+345
View File
@@ -0,0 +1,345 @@
<script lang="ts">
import type { TreeEntry } from "$lib/workspace/types";
import type { DropTarget } from "$lib/workspace/treeDrop";
import type { SelectionModifiers, TreeSelectionEdges } from "$lib/workspace/treeSelection";
import { treeFileParts } from "$lib/workspace/chrome";
import TreeNode from "./TreeNode.svelte";
type Props = {
entry: TreeEntry;
childrenMap: Record<string, TreeEntry[]>;
expanded: Set<string>;
activePath: string | null;
selectedPaths: Set<string>;
selectionEdges: ReadonlyMap<string, TreeSelectionEdges>;
renameRel: string | null;
renameDraft: string;
onRenameDraft: (value: string) => void;
onRenameCommit: () => void;
onRenameCancel: () => void;
pins: Set<string>;
bookmarks: Set<string>;
onRowClick: (entry: TreeEntry, modifiers?: SelectionModifiers, newTab?: boolean) => void;
onContextMenu: (entry: TreeEntry, x: number, y: number) => void;
dropTarget: DropTarget | null;
dragRel: string | null;
onDragPointerDown: (entry: TreeEntry, event: PointerEvent) => void;
};
let {
entry,
childrenMap,
expanded,
activePath,
selectedPaths,
selectionEdges,
renameRel,
renameDraft,
onRenameDraft,
onRenameCommit,
onRenameCancel,
pins,
bookmarks,
onRowClick,
onContextMenu,
dropTarget,
dragRel,
onDragPointerDown,
}: Props = $props();
let isOpen = $derived(expanded.has(entry.rel_path));
let isActive = $derived(activePath === entry.rel_path);
let isSelected = $derived(selectedPaths.has(entry.rel_path));
let edges = $derived(selectionEdges.get(entry.rel_path));
let isRenaming = $derived(renameRel === entry.rel_path);
let isDragging = $derived(dragRel === entry.rel_path);
let dropOn = $derived(dropTarget?.rel === entry.rel_path ? dropTarget.place : null);
let nested = $derived(childrenMap[entry.rel_path] ?? []);
let parts = $derived(entry.kind === "file" ? treeFileParts(entry.name) : { label: entry.name, ext: "" });
let ext = $derived(parts.ext);
let label = $derived(parts.label);
function focusSelect(node: HTMLInputElement) {
node.focus();
node.select();
}
function edgeWidth(steps: number | null | undefined) {
if (steps == null) return "100%";
return steps === 0 ? "0px" : `calc(${steps} * var(--tree-indent) + var(--rs-item-selection-width))`;
}
</script>
<li role="none" style:--tree-indent="12px">
<div
class="row"
class:active={isActive}
class:selected={isSelected}
style:--selection-top-width={edgeWidth(edges?.top)}
style:--selection-bottom-width={edgeWidth(edges?.bottom)}
style:--selection-top-left-radius={edges?.top === 0 ? "0px" : "var(--rs-item-selection-radius)"}
style:--selection-top-right-radius={edges?.top == null ? "var(--rs-item-selection-radius)" : "0px"}
style:--selection-bottom-left-radius={edges?.bottom === 0 ? "0px" : "var(--rs-item-selection-radius)"}
style:--selection-bottom-right-radius={edges?.bottom == null ? "var(--rs-item-selection-radius)" : "0px"}
class:folder={entry.kind === "folder"}
class:dragging={isDragging}
class:drop-before={dropOn === "before"}
class:drop-after={dropOn === "after"}
class:drop-inside={dropOn === "inside"}
data-tree-rel={entry.rel_path}
data-tree-kind={entry.kind}
role="treeitem"
tabindex="0"
aria-selected={isSelected}
aria-expanded={entry.kind === "folder" ? isOpen : undefined}
aria-level={entry.rel_path.split("/").length}
onpointerdown={(event) => {
if (event.button === 1) event.preventDefault();
onDragPointerDown(entry, event);
}}
onclick={(event) => onRowClick(entry, event)}
onauxclick={(event) => {
if (event.button !== 1) return;
event.preventDefault();
if (!isRenaming && entry.kind === "file") onRowClick(entry, {}, true);
}}
onkeydown={(event) => {
if (isRenaming) {
return;
}
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
onRowClick(entry, event);
}
}}
oncontextmenu={(event) => {
event.preventDefault();
event.stopPropagation();
onContextMenu(entry, event.clientX, event.clientY);
}}
>
{#if isSelected}
<span class="selection-outline" class:full-top={edges?.top == null} class:full-bottom={edges?.bottom == null} aria-hidden="true">
{#if edges?.top != null && edges.top > 0}<span class="selection-step top"></span>{/if}
{#if edges?.bottom != null && edges.bottom > 0}<span class="selection-step bottom"></span>{/if}
</span>
{/if}
<span class="twist" class:open={isOpen} class:folder={entry.kind === "folder"}></span>
{#if isRenaming}
<input
class="rename"
value={renameDraft}
use:focusSelect
onclick={(event) => event.stopPropagation()}
onpointerdown={(event) => event.stopPropagation()}
oninput={(event) => onRenameDraft(event.currentTarget.value)}
onkeydown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
onRenameCommit();
}
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
onRenameCancel();
}
}}
onblur={() => onRenameCommit()}
/>
{:else}
<span class="name">{label}</span>
{/if}
{#if ext}
<span class="mark ext">{ext}</span>
{/if}
</div>
{#if entry.kind === "folder" && isOpen}
<ul role="group">
{#each nested as child (child.rel_path)}
<TreeNode
entry={child}
{childrenMap}
{expanded}
{activePath}
{selectedPaths}
{selectionEdges}
{renameRel}
{renameDraft}
{onRenameDraft}
{onRenameCommit}
{onRenameCancel}
{pins}
{bookmarks}
{onRowClick}
{onContextMenu}
{dropTarget}
{dragRel}
{onDragPointerDown}
/>
{/each}
</ul>
{/if}
</li>
<style>
li {
list-style: none;
}
ul {
list-style: none;
margin: 0;
padding: 0 0 0 var(--tree-indent);
}
.row {
position: relative;
display: flex;
align-items: center;
gap: 4px;
width: 100%;
border: 0;
border-radius: var(--rs-control-radius);
background: transparent;
color: var(--rs-text);
text-align: left;
padding: 3px 8px;
cursor: grab;
user-select: none;
}
.row:hover {
background: var(--rs-bg-active);
}
.row.active {
background: var(--rs-bg-active);
color: var(--rs-text-strong);
}
.row.selected {
background-color: var(--rs-item-selection-bg);
border-radius: var(--selection-top-left-radius) var(--selection-top-right-radius)
var(--selection-bottom-right-radius) var(--selection-bottom-left-radius);
color: var(--rs-text-strong);
outline: none;
}
.selection-outline {
position: absolute;
inset: 0;
pointer-events: none;
border: var(--rs-item-selection-width) solid var(--rs-item-selection-border);
border-top: 0;
border-bottom: 0;
border-radius: inherit;
}
.selection-outline.full-top { border-top: var(--rs-item-selection-width) solid var(--rs-item-selection-border); }
.selection-outline.full-bottom { border-bottom: var(--rs-item-selection-width) solid var(--rs-item-selection-border); }
/* Round exposed indentation steps without drawing across shared row edges. */
.selection-step {
position: absolute;
left: calc(-1 * var(--rs-item-selection-width));
height: var(--rs-item-selection-radius);
border-left: var(--rs-item-selection-width) solid var(--rs-item-selection-border);
}
.selection-step.top {
top: 0;
width: var(--selection-top-width);
border-top: var(--rs-item-selection-width) solid var(--rs-item-selection-border);
border-top-left-radius: var(--rs-item-selection-radius);
}
.selection-step.bottom {
bottom: 0;
width: var(--selection-bottom-width);
border-bottom: var(--rs-item-selection-width) solid var(--rs-item-selection-border);
border-bottom-left-radius: var(--rs-item-selection-radius);
}
.row.dragging {
opacity: 0.4;
}
.row.drop-before::before,
.row.drop-after::after {
content: "";
position: absolute;
left: 16px;
right: 8px;
height: 2px;
background: var(--rs-accent);
}
.row.drop-before::before {
top: 0;
}
.row.drop-after::after {
bottom: 0;
}
.row.drop-inside {
outline: 1px solid var(--rs-accent);
background: var(--rs-bg-active);
}
.twist {
width: 14px;
height: 14px;
flex: 0 0 14px;
color: var(--rs-text-strong);
display: inline-flex;
align-items: center;
justify-content: center;
}
.twist.folder::before {
content: "";
width: 0;
height: 0;
border-style: solid;
border-width: 5px 0 5px 8px;
border-color: transparent transparent transparent currentColor;
transform: rotate(0deg);
}
.twist.folder.open::before {
transform: rotate(90deg);
}
.name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.rename {
flex: 1;
min-width: 0;
height: 20px;
padding: 0 4px;
border: 1px solid var(--rs-accent);
background: var(--rs-bg);
color: var(--rs-text-strong);
}
.folder .name {
color: var(--rs-text-strong);
}
.mark {
margin-left: auto;
font-size: 10px;
letter-spacing: 0.06em;
padding: 1px 5px;
text-transform: uppercase;
color: var(--rs-accent);
background: var(--rs-bg-active);
flex: 0 0 auto;
}
</style>
File diff suppressed because it is too large Load Diff
+158
View File
@@ -0,0 +1,158 @@
<script lang="ts">
import { tick } from "svelte";
import Icon from "$lib/ui/Icon.svelte";
import { pickWorkspaceFolder, workspaceRecent } from "$lib/workspace/api";
let { currentRoot, anchor, onOpen }: {
currentRoot?: string; anchor?: HTMLElement;
onOpen: (path: string, name?: string) => Promise<boolean>;
} = $props();
let menu: HTMLDivElement;
let dialog: HTMLDialogElement | undefined = $state();
let input: HTMLInputElement | undefined = $state();
let recent = $state<string[]>([]);
let loading = $state(false);
let busy = $state(false);
let error = $state("");
let creating = $state(false);
let name = $state("");
let parent = $state("");
let returnFocus: HTMLElement | null = null;
const folderName = (path: string) => path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path;
const destination = $derived(parent ? `${parent.replace(/[\\/]+$/, "")}${parent.includes("\\") ? "\\" : "/"}${name.trim()}` : "Choose where to create your workspace.");
export async function show() {
if (busy || creating) return;
if (menu.matches(":popover-open")) { menu.hidePopover(); return; }
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
error = ""; loading = true;
menu.showPopover();
position();
menu.querySelector<HTMLButtonElement>("button")?.focus();
try { recent = await workspaceRecent(); }
catch (err) { error = `Could not load recent workspaces: ${String(err)}`; }
finally { loading = false; }
await tick();
if (menu.matches(":popover-open")) { position(); menu.querySelector<HTMLButtonElement>("button")?.focus(); }
}
function position() {
const rect = anchor?.getBoundingClientRect();
menu.style.left = `${Math.max(8, Math.min(rect?.left ?? (innerWidth - menu.offsetWidth) / 2, innerWidth - menu.offsetWidth - 8))}px`;
menu.style.top = `${Math.max(8, (rect?.top ?? (innerHeight + menu.offsetHeight) / 2) - menu.offsetHeight - 8)}px`;
}
function close() { menu.hidePopover(); returnFocus?.focus(); }
async function open(path: string) {
if (busy) return;
if (path === currentRoot) { close(); return; }
busy = true; error = "";
try { if (await onOpen(path)) close(); }
catch (err) { error = `Could not open workspace: ${String(err)}`; }
finally { busy = false; }
}
async function browse() {
if (busy) return;
busy = true; error = "";
try {
const path = await pickWorkspaceFolder();
if (path && await onOpen(path)) close();
} catch (err) { error = String(err); }
finally { busy = false; }
}
async function newWorkspace() {
menu.hidePopover(); error = ""; name = ""; parent = ""; creating = true;
await tick(); dialog?.showModal(); input?.focus();
}
function cancel() { if (!busy) { creating = false; returnFocus?.focus(); } }
async function chooseLocation() {
busy = true; error = "";
try { const path = await pickWorkspaceFolder("Choose a location for the new workspace"); if (path) parent = path; }
catch (err) { error = String(err); }
finally { busy = false; }
}
async function create() {
if (busy || !name.trim() || !parent) return;
busy = true; error = "";
try { if (await onOpen(parent, name.trim())) { creating = false; returnFocus?.focus(); } }
catch (err) { error = String(err); }
finally { busy = false; }
}
function navigate(event: KeyboardEvent) {
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
event.preventDefault();
const buttons = [...menu.querySelectorAll<HTMLButtonElement>("button:not(:disabled)")];
const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
const next = event.key === "Home" ? 0 : event.key === "End" ? buttons.length - 1 : (index + (event.key === "ArrowDown" ? 1 : -1) + buttons.length) % buttons.length;
buttons[next]?.focus();
}
</script>
<svelte:window onresize={() => { if (menu?.matches(":popover-open")) position(); }} />
<div bind:this={menu} popover="auto" class="workspace-menu" role="dialog" aria-label="Workspaces" tabindex="-1" onkeydown={navigate}>
<h2>Recent workspaces</h2>
<div class="recent" aria-busy={loading || busy}>
{#if loading}<p>Loading workspaces…</p>
{:else if !recent.length}<p>No recent workspaces yet.</p>{/if}
{#each recent as path}
<button class="workspace-row" class:current={path === currentRoot} aria-current={path === currentRoot ? "true" : undefined} disabled={busy} onclick={() => open(path)}>
<Icon icon="folder-open" />
<span class="details"><span>{folderName(path)}</span><small>{path}</small></span>
{#if path === currentRoot}<span class="current-label">Current</span>{/if}
</button>
{/each}
</div>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<footer>
<button disabled={busy} onclick={newWorkspace}><Icon icon="folder-plus" /> New workspace…</button>
<button disabled={busy} onclick={browse}><Icon icon="folder-open" /> Open another folder…</button>
</footer>
</div>
{#if creating}
<dialog bind:this={dialog} aria-labelledby="new-workspace-title" oncancel={(event) => { event.preventDefault(); cancel(); }}>
<form onsubmit={(event) => { event.preventDefault(); void create(); }}>
<h2 id="new-workspace-title"><Icon icon="folder-plus" /> New workspace</h2>
<p>Create a folder for your notes and files, then open it in a new window.</p>
<label for="workspace-name">Workspace name</label>
<input id="workspace-name" bind:this={input} bind:value={name} oninput={() => error = ""} placeholder="My workspace" autocomplete="off" required disabled={busy} />
<div class="location-label"><label for="workspace-location">Location</label><button type="button" disabled={busy} onclick={chooseLocation}><Icon icon="folder-open" /> Browse…</button></div>
<input id="workspace-location" value={parent} readonly placeholder="Choose a parent folder" />
<small class="destination">{parent ? "Will create: " : ""}{destination}</small>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<div class="actions"><button type="button" disabled={busy} onclick={cancel}>Cancel</button><button class="primary" type="submit" disabled={busy || !name.trim() || !parent}>{busy ? "Please wait…" : "Create workspace"}</button></div>
</form>
</dialog>
{/if}
<style>
.workspace-menu, dialog { background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); box-shadow: 0 12px 36px #0006; }
.workspace-menu { position: fixed; inset: auto; margin: 0; padding: 6px; width: min(380px, calc(100vw - 16px)); max-height: calc(100vh - 16px); overflow: auto; }
h2 { font-size: 14px; font-weight: 600; margin: 0; padding: 9px 10px; display: flex; align-items: center; gap: 8px; }
p { font-size: 13px; color: var(--rs-text-dim); margin: 8px 10px; }
.recent { max-height: min(360px, 45vh); overflow: auto; padding: 2px; }
button { display: flex; align-items: center; gap: 10px; background: transparent; border: 1px solid transparent; border-radius: var(--rs-control-radius); padding: 9px 10px; color: var(--rs-text); text-align: left; }
button:hover { background: var(--rs-bg-active); }
button:focus-visible, input:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
button:disabled { opacity: .5; }
.workspace-row, footer button { width: 100%; }
.workspace-row.current { background: var(--rs-item-selection-bg); box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border); border-radius: var(--rs-item-selection-radius); }
.details { min-width: 0; display: flex; flex: 1; flex-direction: column; gap: 3px; }
small { font-size: 11px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
.current-label { font-size: 11px; color: var(--rs-accent); }
footer { border-top: 1px solid var(--rs-border); margin-top: 6px; padding-top: 6px; }
dialog { width: min(480px, calc(100vw - 32px)); padding: 22px; }
dialog::backdrop { background: #0008; }
form { display: flex; flex-direction: column; gap: 12px; }
form h2, form p { padding: 0; margin: 0; }
form label { font-size: 13px; }
input { width: 100%; background: var(--rs-bg); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 10px; }
.location-label, .actions { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
form button { border-color: var(--rs-border); background: var(--rs-bg-active); }
.actions { justify-content: flex-end; margin-top: 8px; }
.primary { border-color: var(--rs-accent); }
.error { color: var(--rs-error); overflow-wrap: anywhere; }
</style>
+16
View File
@@ -0,0 +1,16 @@
export type MenuAction = {
kind: "action";
label: string;
run: () => void;
disabled?: boolean;
};
export type MenuSep = { kind: "sep" };
export type MenuGroup = {
kind: "group";
label: string;
items: MenuItem[];
};
export type MenuItem = MenuAction | MenuSep | MenuGroup;