Files
RuneStone/src/lib/layout/EditorPane.svelte
T
Knotty Wyvern 61976191d0 Show different tabs side by side in split view
Each tab menu has "Open to the right". It shows the tab in a new pane to
the right of the active pane. A pane shows a document or a plugin tab,
for example a browser tab.

- A plugin view stays in the plugin layer above the panes, so a move
  between panes does not mount it again.
- A browser tab that covers the area moves to the left pane when a tab
  opens beside it. The last pane gives its plugin tab the whole area.
- The "Split" toggle of a document is now "Read beside".

Card 565874b2.
2026-11-10 06:40:44 -07:00

300 lines
13 KiB
Svelte

<script lang="ts">
import { t } from "$lib/i18n";
import { commandShortcut } from "./workbenchKeys";
import { featureSwitches } from "$lib/features/state";
import { gitApi } from "$lib/git/service";
import type { GitLineInfo } from "$lib/git/contracts";
import FindPanel from "$lib/editor/FindPanel.svelte";
import { readingSearch } from "$lib/editor/readingSearch";
import type { FindTarget } from "$lib/editor/findTarget";
import DocumentEditor from "$lib/editor/DocumentEditor.svelte";
import { tick } from "svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import ImageViewer from "./ImageViewer.svelte";
import MarkdownView from "./MarkdownView.svelte";
import ViewModes, { type ViewMode } from "./ViewModes.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";
import type { DocumentLinkActions } from "$lib/editor/linkMenu";
type Props = {
buffer: OpenBuffer | null;
tabs: OpenBuffer[];
chrome: Chrome;
reading: boolean;
split: boolean;
focusLine: number | null;
onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>;
onInsertImage?: (file: File, source?: string) => Promise<string | null>;
onView?: (view: ViewMode) => void;
onSplit?: (split: boolean) => void;
onCursor?: (line: number, column: number) => void;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onOpenWorkspace: () => void;
onNewFile: () => void;
onNewNote?: (event: MouseEvent) => void;
onQuickOpen: () => void;
onOpenBrowser?: () => void;
browserOpening?: boolean;
hasWorkspace: boolean;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
active?: boolean;
onCloseSplit?: () => void;
};
let { buffer, tabs, chrome, reading, split, focusLine, onChange, onRenameTitle, onInsertImage, onView, onSplit, onCursor, onOpenLink, onOpenWorkspace, onNewFile, onNewNote, onQuickOpen, onOpenBrowser, browserOpening = false, hasWorkspace, tableActions, linkActions, active = true, onCloseSplit }: Props = $props();
let selectedLine = $state(1);
let lineInfo = $state<GitLineInfo | null>(null);
// The blame line needs no feature code: it calls the host Git service while the Git feature is on.
const git = $derived($featureSwitches.git ? gitApi : null);
$effect(() => { void buffer?.id; selectedLine = 1; });
$effect(() => {
void buffer?.id;
const path = buffer?.relPath, line = selectedLine, provider = git;
const dirty = buffer?.contents !== buffer?.saved;
const available = buffer?.kind === "text" && !readOnly;
lineInfo = null;
if (!path || !provider || !available || dirty) return;
let cancelled = false;
const timer = setTimeout(() => {
void provider.blame(path, line).then(info => { if (!cancelled) lineInfo = info; }).catch(() => {});
}, 250);
return () => { cancelled = true; clearTimeout(timer); };
});
function lineDate(value: string, detailed = false) {
const date = new Date(/^\d+$/.test(value) ? Number(value) * 1000 : value);
return Number.isNaN(date.getTime()) ? value : detailed ? date.toLocaleString() : date.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
}
let modeControls = $state<HTMLDivElement>();
let titleFocusId = $state<string | null>(null);
let element: HTMLDivElement | undefined = $state();
let documentEditor: DocumentEditor | undefined = $state();
let readingFind = $state.raw<FindTarget>();
let readingFindPanel = $state<FindPanel>();
$effect(() => { void buffer?.id; void reading; void split; readingFind = undefined; });
async function documentSearch(event: KeyboardEvent) {
if (event.target instanceof Element && event.target.closest('[role="menu"], dialog, [role="dialog"]')) return;
const key = event.key.toLowerCase();
const open = (event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && (key === "f" || key === "h");
const advance = key === "f3" && !event.ctrlKey && !event.metaKey && !event.altKey;
if ((!open && !advance) || buffer?.kind !== "text") return;
event.preventDefault(); event.stopPropagation();
const inReading = readOnly || splitView && event.target instanceof Element && (!!event.target.closest(".md-page") || !!readingFind && !!event.target.closest(".rs-find-bar"));
if (inReading) {
const root = element?.querySelector<HTMLElement>(".md-page > .reading");
if (!root) return;
documentEditor?.closeFind();
readingFind ??= readingSearch(root, () => { readingFind = undefined; });
await tick();
if (advance) readingFind.next(event.shiftKey);
else readingFindPanel?.focus();
} else {
readingFind = undefined;
if (advance) documentEditor?.nextMatch(event.shiftKey);
else documentEditor?.openFind(key === "h");
}
}
const shouldFocusOnMount = () => active && !modeControls?.contains(document.activeElement);
export function focusEditor() {
if (readOnly) element?.querySelector<HTMLElement>(".md-page > .reading")?.focus({ preventScroll: true });
else documentEditor?.focus();
}
export function focusTitle(id: string) {
titleFocusId = id;
}
$effect(() => {
if (titleFocusId !== buffer?.id) titleFocusId = null;
});
const previewScroll = new Map<string, { top: number; left: number }>();
$effect(() => {
const ids = tabs.map(tab => tab.id);
for (const id of previewScroll.keys()) if (!ids.includes(id)) previewScroll.delete(id);
});
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 isImage = $derived(buffer?.kind === "image");
const canPreview = $derived(buffer !== null && buffer.kind === "text" && isMarkdownPath(buffer.relPath));
const readOnly = $derived(reading && canPreview);
const splitView = $derived(split && canPreview && !reading);
const view: ViewMode = $derived(readOnly ? "read" : chrome === "Source" ? "source" : "write");
// The tab already names the file, so the breadcrumb shows only its folder.
// Beside other panes, the breadcrumb also names the file, because the tab bar names only the file of the active pane.
const folder = $derived(!buffer ? "" : onCloseSplit ? buffer.relPath.split("/").join(" / ")
: buffer.relPath.includes("/") ? buffer.relPath.slice(0, buffer.relPath.lastIndexOf("/")).split("/").join(" / ") : "");
</script>
{#if !buffer || buffer.kind === "empty"}
<div class="empty">
{#if onCloseSplit}<IconButton icon="close" label={$t("Close split")} onclick={onCloseSplit} />{/if}
<div class="welcome-actions">
{#if hasWorkspace}
<div class="welcome-row">
<button onclick={onNewFile}><Icon icon="file-plus" /> {$t("New file")} <kbd>{commandShortcut("new-file")}</kbd></button>
{#if onNewNote}<button onclick={onNewNote}><Icon icon="pen" /> {$t("New note")}</button>{/if}
<button onclick={onQuickOpen}><Icon icon="search" /> {$t("Find file")} <kbd>{commandShortcut("quick-open")}</kbd></button>
</div>
{/if}
<div class="welcome-row">
<button onclick={onOpenWorkspace}><Icon icon="folder-open" /> {$t("Open folder")} <kbd>{commandShortcut("open-workspace")}</kbd></button>
{#if onOpenBrowser}<button onclick={onOpenBrowser} disabled={browserOpening}><Icon icon="globe" /> {browserOpening ? $t("Opening browser…") : $t("Open browser")}</button>{/if}
</div>
</div>
</div>
{:else}
<!-- svelte-ignore a11y_no_static_element_interactions (Capture document shortcuts before nested editor handlers.) -->
<div class="editor" class:pane-active={active} bind:this={element} onkeydowncapture={documentSearch}>
<div class="chrome-bar">
<span class="breadcrumb" title={buffer.relPath}>{folder}</span>
{#if lineInfo}
<span class="line-history" title={`Line ${selectedLine} · ${lineInfo.author} · ${lineDate(lineInfo.date, true)}\n${lineInfo.summary} (${lineInfo.commit.slice(0, 8)})`}>
<Icon icon="git" /><span>Ln {selectedLine} · {lineDate(lineInfo.date)}</span>
</span>
{/if}
<div class="actions" bind:this={modeControls}>
{#if onCloseSplit}<IconButton icon="close" label={$t("Close split")} onclick={onCloseSplit} />{/if}
{#if !isImage}<ViewModes {view} split={splitView} readable={canPreview} onView={next => onView?.(next)} onSplit={next => onSplit?.(next)} />{/if}
</div>
</div>
{#if readingFind}<FindPanel bind:this={readingFindPanel} target={readingFind} />{/if}
<div class="body" class:split={splitView}>
{#if isImage && buffer.imageUrl}
<ImageViewer src={buffer.imageUrl} name={buffer.name} />
{:else}
<div class="editor-wrap" class:hidden={readOnly}>
{#key buffer.id}
<DocumentEditor bind:this={documentEditor} {buffer} mode={chrome === "Writing" && canPreview && !readOnly ? "write" : "source"} {chrome}
{onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {linkActions} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line, column) => { selectedLine = line; onCursor?.(line, column); }}
focusTitle={titleFocusId === buffer.id} onTitleFocused={() => { titleFocusId = null; }} />
{/key}
</div>
{#if readOnly || splitView}
{#key buffer.id}
<div class="md-page" use:rememberPreviewScroll={buffer.id}>
<MarkdownView noteRel={buffer.relPath} contents={buffer.contents} {focusLine} {onOpenLink} {linkActions} onSearch={tableActions?.onSearch} />
</div>
{/key}
{/if}
{/if}
</div>
</div>
{/if}
<style>
.line-history { display: inline-flex; align-items: center; gap: 5px; min-width: 0; max-width: 40%; color: var(--rs-text-dim); font-size: 11px; white-space: nowrap; }
.line-history span { overflow: hidden; text-overflow: ellipsis; }
.line-history :global(svg) { width: 14px; height: 14px; flex-shrink: 0; }
.breadcrumb { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-right: auto; }
.welcome-actions { display: flex; flex-direction: column; gap: 12px; max-width: 100%; }
.welcome-row { display: flex; flex-wrap: wrap; justify-content: center; gap: 12px; max-width: 100%; }
.welcome-actions button { flex-wrap: wrap; justify-content: center; max-width: 100%; }
.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-image-control-bg); padding: 10px 14px; }
.welcome-actions button:hover { background: var(--rs-image-control-hover-bg); }
kbd { margin-left: 12px; color: var(--rs-text-dim); font-size: 11px; }
.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 {
overflow: auto;
box-sizing: border-box;
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;
min-height: 34px;
flex-shrink: 0;
padding: 0 10px;
background: var(--rs-bg);
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 {
background: var(--rs-workarea-editor-bg);
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>