Show one view control and name the file once

Phase 5-3.

- One radio group shows Write, Source, and Read at all times, with an
  icon and a name. Narrow panes show only the icons. The arrow keys
  move the choice, and the group has one Tab stop. The current choice
  gets the selection fill and an accent bar. Hover gets only a fill.
- A Split toggle shows Read beside Write or Source. Each document pane
  keeps a split flag beside its reading flag. Read ends Split.
- Ctrl+Shift+E switches between Read and the editor. Ctrl+E still
  switches between Write and Source.
- "IDE" becomes "Source" in the Chrome type, the tab menu (a View
  submenu), the status bar, the catalog, the tests, and the docs.
- Settings, General, File name title hides the title in Write and
  Read. It is on by default.
- The breadcrumb shows only the folder of the file. The status bar
  shows the view, not the path.
- ModeSwitcher.svelte and its hover test are gone. The new test
  layout/viewModes covers the control.
- The command palette from 5-2 gets its row in docs/menu-surfaces.json.
- The user guide Format table is whole again. The 5-2 edit had put
  the Paragraph and Insert rows under the shortcut table.
- 8 new catalog rows and 10 removed rows, in French, Japanese, and
  Simplified Chinese.
- Docs: UI-049, the user guide, ui-design.md, document-tools.md,
  development.md, and the README feature list.

Tests: the new layout/viewModes, new cases in documentPanes.spec.ts
and settings.spec.ts, and the chooseView harness helper. 21 smoke
tests use the new control. Tests that read the full path from the
breadcrumb now read its tooltip.
This commit is contained in:
Knotty Wyvern
2026-10-28 19:45:08 -07:00
parent ebacdb8164
commit 9cf82503d0
64 changed files with 675 additions and 590 deletions
+14 -5
View File
@@ -23,6 +23,7 @@
import { liveMarkdown, refreshImages } from "./liveMarkdown";
import { imageDrops, trackImageDrop, clearImageDrop } from "./imageDrop";
import { noteTitle } from "./noteTitle";
import { fileTitleVisible } from "./fileTitle";
import type { TableContextActions } from "./tableCellActions";
import { markdownMenu } from "./markdownMenu";
import { codeMenu } from "./codeMenu";
@@ -178,11 +179,16 @@
},
report: message => { error = message; },
}),
title.of(noteTitle(markdownTitle(current.relPath), onRenameTitle ? renameTitle : undefined)),
title.of(fileTitle(current.relPath)),
EditorView.contentAttributes.of({ role: "textbox", "aria-label": $t("Writing editor"), "aria-multiline": "true", spellcheck: "true" }),
];
}
// The file name title, or nothing when the setting hides it.
function fileTitle(path: string): Extension {
return untrack(() => $fileTitleVisible) ? noteTitle(markdownTitle(path), onRenameTitle ? renameTitle : undefined) : [];
}
function modeExtensions(next: NonNullable<typeof shown>): Extension {
// Tab in a Markdown list item makes a nested item in Write and in Source.
const lists: KeyBinding[] = next.markdown ? [{ key: "Tab", run: indentListItem, shift: outdentListItem }] : [];
@@ -382,16 +388,19 @@
});
$effect(() => {
const name = markdownTitle(buffer.relPath);
const path = buffer.relPath;
void $fileTitleVisible;
const view = editor;
if (view && shown?.mode === "write") view.dispatch({ effects: title.reconfigure(noteTitle(name, onRenameTitle ? renameTitle : undefined)) });
if (view && shown?.mode === "write") view.dispatch({ effects: title.reconfigure(fileTitle(path)) });
});
$effect(() => {
if (!focusTitle || !editor || shown?.mode !== "write") return;
const button = editor.dom.querySelector<HTMLButtonElement>(".note-title-button");
if (!button) return;
button.click();
// Without the title, a new note starts with the cursor in the text.
if (button) button.click();
else if (!$fileTitleVisible) editor.focus();
else return;
onTitleFocused?.();
});
+18
View File
@@ -0,0 +1,18 @@
// The `showFileTitle` general setting shows the file name as a title above a Markdown note in Write and Read.
import { writable } from "svelte/store";
import { onSettingsChange } from "../settings/store.ts";
import { DEFAULT_SETTINGS, readSettings } from "../workspace/settings.ts";
const visible = writable(DEFAULT_SETTINGS.showFileTitle);
/** A store with the current state of the setting. */
export const fileTitleVisible = { subscribe: visible.subscribe };
/** Apply the saved setting now and after each change in any window. Returns a function that stops it. */
export function syncFileTitle() {
const read = () => {
try { visible.set(readSettings().showFileTitle); }
catch { visible.set(DEFAULT_SETTINGS.showFileTitle); }
};
read();
return onSettingsChange("general", read);
}
+9 -56
View File
@@ -1043,18 +1043,6 @@ export const messageRows: [string, string, string, string][] = [
"ブラウザーを開く",
"打开浏览器"
],
[
"Document view",
"Vue du document",
"ドキュメント表示",
"文档视图"
],
[
"Edit",
"Modifier",
"編集",
"编辑"
],
[
"Read",
"Lire",
@@ -1067,24 +1055,6 @@ export const messageRows: [string, string, string, string][] = [
"分割",
"分栏"
],
[
"Editor layout",
"Disposition de l’éditeur",
"エディターのレイアウト",
"编辑器布局"
],
[
"IDE",
"IDE",
"IDE",
"IDE"
],
[
"Writer",
"Rédaction",
"ライター",
"写作"
],
[
"Editor",
"Éditeur",
@@ -1115,30 +1085,6 @@ export const messageRows: [string, string, string, string][] = [
"テンプレートとして保存",
"保存为模板"
],
[
"Editing view",
"Vue de modification",
"編集表示",
"编辑视图"
],
[
"Reading view",
"Vue de lecture",
"閲覧表示",
"阅读视图"
],
[
"Writing mode",
"Mode rédaction",
"文章モード",
"写作模式"
],
[
"Source mode",
"Mode source",
"ソースモード",
"源码模式"
],
[
"Rename…",
"Renommer…",
@@ -3500,7 +3446,6 @@ export const messageRows: [string, string, string, string][] = [
["{count} commands", "{count} commandes", "{count} 個のコマンド", "{count} 个命令"],
["run", "exécuter", "実行", "运行"],
["Show all commands", "Afficher toutes les commandes", "すべてのコマンドを表示", "显示所有命令"],
["Switch between writing and source editing", "Alterner entre rédaction et code source", "文章編集とソース編集を切り替え", "在写作和源码编辑之间切换"],
["Show or hide the terminal", "Afficher ou masquer le terminal", "ターミナルを表示または非表示", "显示或隐藏终端"],
["Close the tab", "Fermer l’onglet", "タブを閉じる", "关闭标签页"],
["Show or hide the side pane", "Afficher ou masquer le panneau latéral", "サイドパネルを表示または非表示", "显示或隐藏侧边栏"],
@@ -3510,7 +3455,15 @@ export const messageRows: [string, string, string, string][] = [
["Write", "Écrire", "書く", "写作"],
["Find in the document", "Rechercher dans le document", "ドキュメント内を検索", "在文档中查找"],
["Move to the Recycle Bin", "Placer dans la Corbeille", "ごみ箱に移動", "移到回收站"],
["Open the context menu", "Ouvrir le menu contextuel", "コンテキストメニューを開く", "打开上下文菜单"]
["Open the context menu", "Ouvrir le menu contextuel", "コンテキストメニューを開く", "打开上下文菜单"],
["Documents", "Documents", "ドキュメント", "文档"],
["File name title", "Titre du nom de fichier", "ファイル名のタイトル", "文件名标题"],
["Show the file name above each Markdown note in Write and Read.", "Afficher le nom du fichier au-dessus de chaque note Markdown dans Écrire et Lire.", "「書く」と「閲覧」で、各 Markdown ノートの上にファイル名を表示します。", "在“写作”和“阅读”中,在每篇 Markdown 笔记上方显示文件名。"],
["Source", "Source", "ソース", "源码"],
["View", "Affichage", "表示", "视图"],
["Split: Read beside the editor", "Diviser : Lire à côté de l’éditeur", "分割: エディターの横に閲覧を表示", "分栏:在编辑器旁显示阅读"],
["Switch between Write and Source", "Alterner entre Écrire et Source", "「書く」と「ソース」を切り替え", "在写作和源码之间切换"],
["Switch between Read and the editor", "Alterner entre Lire et l’éditeur", "「閲覧」とエディターを切り替え", "在阅读和编辑器之间切换"],
];
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
+8 -6
View File
@@ -7,10 +7,11 @@
import type { Documents } from "$lib/workspace/documents.svelte";
import type { OpenBuffer } from "$lib/workspace/types";
import EditorPane from "./EditorPane.svelte";
import type { ViewMode } from "./ViewModes.svelte";
import TabBar from "./TabBar.svelte";
type EditorProps = ComponentProps<typeof EditorPane>;
type DocumentView = { id: string; reading: boolean; buffer: OpenBuffer | null; bounds: { width: number } };
type DocumentView = { id: string; reading: boolean; split: boolean; buffer: OpenBuffer | null; bounds: { width: number } };
type Bounds = { left: number; top: number; width: number; height: number };
type Props = {
editorPluginVisible: boolean;
@@ -39,13 +40,13 @@
onRenameTitle: EditorProps["onRenameTitle"];
tableActions: (pane: DocumentView) => EditorProps["tableActions"];
linkActions: (pane: DocumentView) => EditorProps["linkActions"];
onToggleReading: (pane: DocumentView) => void;
onToggleChrome: (pane: DocumentView) => void;
onView: (pane: DocumentView, view: ViewMode) => void;
onSplitView: (pane: DocumentView, split: boolean) => void;
onOpenLink: (pane: DocumentView, kind: "md" | "wiki", target: string) => void;
};
let { editorPluginVisible, split, pluginBounds, tabBar, pluginPaneComponents = $bindable(), documentViews, activePane, paneComponents = $bindable(),
documents, tabs, hasWorkspace, browserOpening, focusLine, onFocusPane, onCloseSplit, onSaveCopy, onOpenWorkspace, onNewFile, onNewNote,
onQuickOpen, onOpenBrowser, onChange, onInsertImage, onRenameTitle, tableActions, linkActions, onToggleReading, onToggleChrome, onOpenLink }: Props = $props();
onQuickOpen, onOpenBrowser, onChange, onInsertImage, onRenameTitle, tableActions, linkActions, onView, onSplitView, onOpenLink }: Props = $props();
</script>
<main class="center">
@@ -100,14 +101,15 @@
buffer={pane.buffer}
chrome={pane.buffer?.chromeOverride ?? pane.buffer?.chrome ?? "Writing"}
reading={pane.reading}
split={pane.split}
focusLine={activePane === pane.id ? focusLine : null}
{onChange}
onInsertImage={file => onInsertImage(file, pane.buffer)}
{onRenameTitle}
tableActions={tableActions(pane)}
linkActions={linkActions(pane)}
onToggleReading={() => onToggleReading(pane)}
onToggleChrome={() => onToggleChrome(pane)}
onView={view => onView(pane, view)}
onSplit={next => onSplitView(pane, next)}
onOpenLink={(kind, target) => onOpenLink(pane, kind, target)}
/>
</div>
+21 -48
View File
@@ -11,7 +11,7 @@
import IconButton from "$lib/ui/IconButton.svelte";
import ImageViewer from "./ImageViewer.svelte";
import MarkdownView from "./MarkdownView.svelte";
import ModeSwitcher from "$lib/ui/ModeSwitcher.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";
@@ -24,12 +24,13 @@
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) => Promise<string | null>;
onToggleReading?: () => void;
onToggleChrome?: () => void;
onView?: (view: ViewMode) => void;
onSplit?: (split: boolean) => void;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onOpenWorkspace: () => void;
onNewFile: () => void;
@@ -44,7 +45,7 @@
onCloseSplit?: () => void;
};
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onNewNote, onQuickOpen, onOpenBrowser, browserOpening = false, hasWorkspace, tableActions, linkActions, active = true, onCloseSplit }: Props = $props();
let { buffer, tabs, chrome, reading, split, focusLine, onChange, onRenameTitle, onInsertImage, onView, onSplit, 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);
const git = $derived.by(() => { void $pluginHost; return pluginHost.get("git"); });
@@ -53,7 +54,7 @@
void buffer?.id;
const path = buffer?.relPath, line = selectedLine, provider = git;
const dirty = buffer?.contents !== buffer?.saved;
const available = buffer?.kind === "text" && !reading;
const available = buffer?.kind === "text" && !readOnly;
lineInfo = null;
if (!path || !provider || !available || dirty) return;
let cancelled = false;
@@ -66,14 +67,13 @@
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 previewMode = $state<"split" | "preview">("split");
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 previewMode; readingFind = undefined; });
$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();
@@ -81,9 +81,9 @@
const advance = key === "f3" && !event.ctrlKey && !event.metaKey && !event.altKey;
if ((!open && !advance) || buffer?.kind !== "text") return;
event.preventDefault(); event.stopPropagation();
const inReading = reading && (previewMode === "preview" || event.target instanceof Element && (!!event.target.closest(".md-page") || !!readingFind && !!event.target.closest(".rs-find-bar")));
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>(".reading");
const root = element?.querySelector<HTMLElement>(".md-page > .reading");
if (!root) return;
documentEditor?.closeFind();
readingFind ??= readingSearch(root, () => { readingFind = undefined; });
@@ -98,7 +98,7 @@
}
const shouldFocusOnMount = () => active && !modeControls?.contains(document.activeElement);
export function focusEditor() {
if (reading) element?.querySelector<HTMLElement>(".reading")?.focus({ preventScroll: true });
if (readOnly) element?.querySelector<HTMLElement>(".md-page > .reading")?.focus({ preventScroll: true });
else documentEditor?.focus();
}
export function focusTitle(id: string) {
@@ -138,19 +138,13 @@
} };
}
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?.();
}
export function toggleReadingView() {
setDocumentMode(reading ? "edit" : "read");
}
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.
const folder = $derived(buffer?.relPath.includes("/") ? buffer.relPath.slice(0, buffer.relPath.lastIndexOf("/")).split("/").join(" / ") : "");
</script>
{#if !buffer || buffer.kind === "empty"}
@@ -174,7 +168,7 @@
<!-- 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}>{buffer.relPath}</span>
<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>
@@ -182,43 +176,22 @@
{/if}
<div class="actions" bind:this={modeControls}>
{#if onCloseSplit}<IconButton icon="close" label={$t("Close split")} onclick={onCloseSplit} />{/if}
{#if canPreview}
<ModeSwitcher
label={$t("Document view")}
value={documentMode}
options={[
{ value: "edit", label: $t("Edit"), icon: "pen" },
{ value: "read", label: $t("Read"), icon: "book-open" },
{ value: "split", label: $t("Split"), icon: "split" },
]}
onchange={setDocumentMode}
/>
{/if}
<ModeSwitcher
label={$t("Editor layout")}
value={chrome}
options={[
{ value: "Ide", label: $t("IDE"), icon: "code" },
{ value: "Writing", label: $t("Writer"), icon: "text" },
]}
shortcut={` (${commandShortcut("toggle-layout")})`}
onchange={(mode) => { if (mode !== chrome) onToggleChrome?.(); }}
/>
{#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={reading && canPreview && previewMode === "split"}>
<div class="body" class:split={splitView}>
{#if isImage && buffer.imageUrl}
<ImageViewer src={buffer.imageUrl} name={buffer.name} />
{:else}
<div class="editor-wrap" class:hidden={reading && canPreview && previewMode === "preview"}>
<div class="editor-wrap" class:hidden={readOnly}>
{#key buffer.id}
<DocumentEditor bind:this={documentEditor} {buffer} mode={!isIde && canPreview && !reading ? "write" : "source"} {chrome}
<DocumentEditor bind:this={documentEditor} {buffer} mode={chrome === "Writing" && canPreview && !readOnly ? "write" : "source"} {chrome}
{onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {linkActions} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line) => selectedLine = line}
focusTitle={titleFocusId === buffer.id} onTitleFocused={() => { titleFocusId = null; }} />
{/key}
</div>
{#if reading && canPreview}
{#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} />
+2 -1
View File
@@ -8,6 +8,7 @@
import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media";
import { imageControls } from "$lib/editor/imageControls";
import { readerHeadingFolding } from "$lib/editor/headingFolding";
import { fileTitleVisible } from "$lib/editor/fileTitle";
import { documentHeadings } from "$lib/workspace/headingLinks";
import "$lib/editor/headingFolding.css";
@@ -193,7 +194,7 @@
}}
>
{#if menuError}<p role="alert">{menuError}</p>{/if}
<h1 class="document-title">{markdownTitle(noteRel)}</h1>
{#if $fileTitleVisible}<h1 class="document-title">{markdownTitle(noteRel)}</h1>{/if}
{#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={$t("Edit document block")} data-start={section.start} data-end={section.end}>{@html section.html}</div>
+7
View File
@@ -138,6 +138,13 @@
<p class="intro">{$t("Choose how RuneStone saves your work.")}</p>
<h3>{$t('Language')}</h3>
<div class="card"><div class="setting-row language-row"><div><label for="language-picker">{$t('Display language')}</label><p>{$t('Choose the language for RuneStone controls.')}</p></div><button id="language-picker" class="text-button language-picker" aria-haspopup="menu" onclick={languagePicker}><Icon icon="globe" />{LANGUAGES.find(item => item.id === $locale)?.name}<Icon icon="chevron-down" /></button></div></div>
<h3>{$t("Documents")}</h3>
<div class="card">
<div class="setting-row">
<div><label for="show-file-title">{$t("File name title")}</label><p id="file-title-description">{$t("Show the file name above each Markdown note in Write and Read.")}</p></div>
<input id="show-file-title" class="switch" type="checkbox" role="switch" aria-describedby="file-title-description" checked={settings.showFileTitle} onchange={event => apply({ ...settings, showFileTitle: event.currentTarget.checked })} />
</div>
</div>
<h3>{$t("Tables")}</h3>
<div class="card">
<div class="setting-row">
+7 -2
View File
@@ -1,8 +1,10 @@
<script lang="ts">
// The status bar at the bottom of the workbench.
import { t } from "$lib/i18n";
import type { ViewMode } from "./ViewModes.svelte";
let { message, watchMode, source }: { message: string; watchMode: string | null; source: boolean } = $props();
// `view` is the view of the active text document, or null for other tabs.
let { message, watchMode, view }: { message: string; watchMode: string | null; view: ViewMode | null } = $props();
</script>
<footer class="status">
@@ -10,7 +12,7 @@
{#if watchMode}
<span>{watchMode} watch</span>
{/if}
<span>{source ? $t("IDE") : $t("Writer")}</span>
{#if view}<span>{view === "read" ? $t("Read") : view === "source" ? $t("Source") : $t("Write")}</span>{/if}
</footer>
<style>
@@ -26,7 +28,10 @@
font-size: 12px;
}
/* The message takes the free space, so the other items stay at the right. */
.status :first-child {
flex: 1;
min-width: 0;
color: var(--rs-text);
overflow: hidden;
text-overflow: ellipsis;
+110
View File
@@ -0,0 +1,110 @@
<script lang="ts" module>
/** The view of a document pane. Split is a separate toggle beside Write or Source. */
export type ViewMode = "write" | "source" | "read";
</script>
<script lang="ts">
// The view control of a document pane: Write, Source, and Read in one radio group, then the Split toggle.
// All choices stay visible. Narrow panes show only the icons.
import { t } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte";
import type { IconName } from "$lib/ui/IconButton.svelte";
import { attachTooltip } from "$lib/ui/tooltip";
import { commandShortcut } from "./workbenchKeys";
type Option = { value: ViewMode; label: string; icon: IconName; shortcut: string };
type Props = {
view: ViewMode;
split: boolean;
/** Markdown files have Read and Split. Other text files have only Write and Source. */
readable: boolean;
onView: (view: ViewMode) => void;
onSplit: (split: boolean) => void;
};
let { view, split, readable, onView, onSplit }: Props = $props();
let group: HTMLDivElement;
const options: Option[] = $derived([
{ value: "write", label: $t("Write"), icon: "pen", shortcut: commandShortcut("toggle-layout") },
{ value: "source", label: $t("Source"), icon: "code", shortcut: commandShortcut("toggle-layout") },
...(readable ? [{ value: "read" as const, label: $t("Read"), icon: "book-open" as const, shortcut: commandShortcut("toggle-reading") }] : []),
]);
function tooltip(node: HTMLElement, text: string) {
let current = text;
const dispose = attachTooltip(node, () => current);
return { update(value: string) { current = value; }, destroy: dispose };
}
// Arrow keys move the choice, as in each radio group. The group has one Tab stop.
function keydown(event: KeyboardEvent, index: number) {
const last = options.length - 1;
const next = event.key === "ArrowRight" || event.key === "ArrowDown" ? (index + 1) % options.length
: event.key === "ArrowLeft" || event.key === "ArrowUp" ? (index + last) % options.length
: event.key === "Home" ? 0 : event.key === "End" ? last : -1;
if (next < 0) return;
event.preventDefault();
onView(options[next].value);
group.querySelectorAll<HTMLButtonElement>("[role=radio]")[next]?.focus();
}
</script>
<div class="view-modes" role="radiogroup" aria-label={$t("View")} bind:this={group}>
{#each options as option, index (option.value)}
<button type="button" role="radio" aria-checked={option.value === view} aria-label={option.label}
tabindex={option.value === view ? 0 : -1}
use:tooltip={`${option.label} (${option.shortcut})`}
onclick={() => onView(option.value)} onkeydown={event => keydown(event, index)}>
<Icon icon={option.icon} /><span class="label" aria-hidden="true">{option.label}</span>
</button>
{/each}
</div>
{#if readable}
<button type="button" class="split" aria-pressed={split} aria-label={$t("Split")} use:tooltip={$t("Split: Read beside the editor")} onclick={() => onSplit(!split)}>
<Icon icon="split" /><span class="label" aria-hidden="true">{$t("Split")}</span>
</button>
{/if}
<style>
.view-modes {
display: inline-flex;
flex: 0 0 auto;
gap: 2px;
padding: 2px;
border: 1px solid var(--rs-border);
border-radius: var(--rs-control-radius);
}
button {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
gap: 6px;
height: 26px;
min-width: 28px;
padding: 0 8px;
border: 0;
border-radius: var(--rs-control-radius);
background: transparent;
color: var(--rs-text-dim);
font: 12px var(--rs-font-ui);
white-space: nowrap;
}
button :global(svg) { width: 16px; height: 16px; flex-shrink: 0; }
/* Hover gets only a fill. The current choice also gets the selection fill and an accent bar. */
button:hover { background: var(--rs-bg-active); color: var(--rs-text-strong); }
button[aria-checked="true"], button[aria-pressed="true"] {
background: var(--rs-item-selection-bg);
color: var(--rs-text-strong);
box-shadow: inset 0 -2px 0 var(--rs-accent);
}
.split { height: 32px; border: 1px solid var(--rs-border); }
@container (max-width: 560px) {
.label { display: none; }
button { padding: 0 6px; }
}
</style>
+37 -12
View File
@@ -9,7 +9,8 @@
import type { MenuLink } from "$lib/editor/linkMenu";
import { WorkspaceSession } from "$lib/workspace/session.svelte";
import { retainEditorStates } from "$lib/editor/editorStates";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane } from "$lib/workspace/documentPanes";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView } from "$lib/workspace/documentPanes";
import type { ViewMode } from "./ViewModes.svelte";
import { selectedEditorText } from "$lib/editor/selection";
import { pluginHost } from "$lib/plugins/registry";
import type { Contributions } from "$lib/plugins/contracts";
@@ -146,7 +147,8 @@
$effect(() => { if ($pluginSidebar && !transferredWindow) leftOpen = true; });
let terminalOpen = $state(false);
let documentPanes = $state(initialDocumentPanes());
const reading = $derived(documentPanes.panes.find(pane => pane.id === documentPanes.active)?.reading ?? false);
const activeDocumentPane = $derived(documentPanes.panes.find(pane => pane.id === documentPanes.active));
const reading = $derived(activeDocumentPane?.reading ?? false);
let quickOpen = $state(false);
let palette = $state(false);
/** The commands of the palette: the app commands that apply here, then the plugin commands. */
@@ -362,7 +364,10 @@
if (order.length !== tabOrder.length || order.some((id, index) => id !== tabOrder[index])) tabOrder = order;
});
const dirty = $derived(buffer !== null && buffer.contents !== buffer.saved);
const isIde = $derived(view === "Ide");
const isSource = $derived(view === "Source");
const readable = $derived(buffer?.kind === "text" && isMarkdownPath(buffer.relPath));
// The status bar names the view of the active pane. Split shows the editor view.
const viewMode: ViewMode = $derived(reading && readable ? "read" : isSource ? "source" : "write");
const outlineItems = $derived(
buffer && buffer.kind === "text" ? buildOutline(buffer.relPath, buffer.contents) : [],
);
@@ -372,12 +377,26 @@
}
function toggleChrome() {
const next = view === "Writing" ? "Ide" : "Writing";
const next = view === "Writing" ? "Source" : "Writing";
setReading(false);
applyChrome(next);
documents?.setChrome(next);
}
/** Show Write, Source, or Read in a pane. Write and Source keep a Split view. */
function setDocumentView(paneId: string, next: ViewMode) {
focusDocumentPane(paneId);
if (next === "read") { setReading(true, paneId); return; }
setReading(false, paneId);
const chrome = next === "source" ? "Source" : "Writing";
if (chrome !== view) { applyChrome(chrome); documents?.setChrome(chrome); }
}
function setSplitView(paneId: string, split: boolean) {
focusDocumentPane(paneId);
documentPanes = splitDocumentView(documentPanes, paneId, split);
}
function toggleTerminal() {
if (!terminalEnabled) return;
terminalOpen = !terminalOpen;
@@ -510,7 +529,7 @@
focusLine = null;
documents?.select(relPath);
focusDocumentPane(documentPanes.active, true);
status = documents?.active?.kind === "empty" ? $t("New tab") : relPath;
status = documents?.active?.kind === "empty" ? $t("New tab") : "";
}
function selectWorkingTab(path: string) {
@@ -660,8 +679,13 @@
if (tab.kind === "text" && isMarkdownPath(tab.relPath)) {
items.push(
{ label: $t("Save as template"), icon: "copy", run: () => { void saveTemplate({ name: tab.name, rel_path: tab.relPath, kind: "file" }); } },
{ label: reading ? $t("Editing view") : $t("Reading view"), icon: "book", run: () => activeEditor()?.toggleReadingView() },
{ label: isIde ? $t("Writing mode") : $t("Source mode"), icon: "code", run: toggleChrome },
{ label: $t("View"), icon: "book", children: [
{ label: $t("Write"), icon: "paragraph", radio: true, checked: viewMode === "write", run: () => setDocumentView(documentPanes.active, "write") },
{ label: $t("Source"), icon: "code", radio: true, checked: viewMode === "source", run: () => setDocumentView(documentPanes.active, "source") },
{ label: $t("Read"), icon: "book", radio: true, checked: viewMode === "read", run: () => setDocumentView(documentPanes.active, "read") },
{ separator: true },
{ label: $t("Split"), icon: "split-right", checked: activeDocumentPane?.split === true && !reading, run: () => setSplitView(documentPanes.active, !(activeDocumentPane?.split && !reading)) },
] },
);
}
items.push({ separator: true },
@@ -684,12 +708,12 @@
try {
const open = current.buffers.find(tab => tab.relPath === entry.rel_path);
if (!line && !(open && open.contents !== open.saved) && await openPluginDocument(entry.rel_path, () => documents === current && !switching)) {
status = entry.rel_path; error = null; return;
status = ""; error = null; return;
}
await current.open(entry, target);
if (documents !== current) return;
pluginEditorActive.set(false);
status = entry.rel_path;
status = "";
error = null;
focusLine = null;
if (line) {
@@ -882,6 +906,7 @@
case "open-workspace": void chooseWorkspace(); return true;
case "new-file": void newFile(); return true;
case "toggle-layout": if (!editorPluginVisible) toggleChrome(); return true;
case "toggle-reading": if (!editorPluginVisible && readable) setReading(!reading); return true;
case "toggle-terminal": if (!terminalEnabled) return false; toggleTerminal(); return true;
case "close-tab":
if (editorPluginVisible) { if (activeTabPath) void closeTab(activeTabPath); }
@@ -1281,8 +1306,8 @@
defaultBrowser: target => openUrl(target),
workspaceItems: link => workspaceLinkItems(link, pane.buffer?.relPath ?? "", pane.id),
})}
onToggleReading={(pane) => setReading(!pane.reading, pane.id)}
onToggleChrome={(pane) => { focusDocumentPane(pane.id); toggleChrome(); }}
onView={(pane, next) => setDocumentView(pane.id, next)}
onSplitView={(pane, next) => setSplitView(pane.id, next)}
onOpenLink={(pane, kind, target) => void openLink(kind, target, pane.buffer?.relPath ?? "", pane.id)}
/>
{#if terminalContribution && terminalStarted}
@@ -1329,7 +1354,7 @@
/>
{/if}
<StatusBar message={error ?? status} watchMode={workspace?.watch_mode ?? null} source={isIde} />
<StatusBar message={error ?? status} watchMode={workspace?.watch_mode ?? null} view={buffer?.kind === "text" ? viewMode : null} />
</div>
<style>
+4 -2
View File
@@ -3,7 +3,7 @@ import { keys, shortcutLabel } from "../ui/shortcuts.ts";
/** The commands of the workbench shortcuts. Workbench.svelte runs them. */
export type WorkbenchCommand =
| "command-palette" | "quick-open" | "new-tab" | "search-workspace" | "save" | "open-workspace" | "new-file" | "toggle-layout"
| "command-palette" | "quick-open" | "new-tab" | "search-workspace" | "save" | "open-workspace" | "new-file" | "toggle-layout" | "toggle-reading"
| "toggle-terminal" | "close-tab" | "toggle-sidebar" | "rename" | "next-tab" | "previous-tab" | "settings" | "help";
/**
@@ -32,6 +32,7 @@ export const workbenchKeys: WorkbenchKey[] = [
{ key: "s", mod: true, command: "save" },
{ key: "o", mod: true, command: "open-workspace" },
{ key: "n", mod: true, command: "new-file" },
{ key: "e", mod: true, shift: true, command: "toggle-reading" },
{ key: "e", mod: true, command: "toggle-layout" },
{ key: "`", mod: true, command: "toggle-terminal" },
{ key: "w", mod: true, command: "close-tab" },
@@ -57,7 +58,8 @@ export const COMMAND_LABELS: Record<WorkbenchCommand, string> = {
save: message("Save the active file"),
"open-workspace": message("Open a workspace"),
"new-file": message("New file"),
"toggle-layout": message("Switch between writing and source editing"),
"toggle-layout": message("Switch between Write and Source"),
"toggle-reading": message("Switch between Read and the editor"),
"toggle-terminal": message("Show or hide the terminal"),
"close-tab": message("Close the tab"),
"toggle-sidebar": message("Show or hide the side pane"),
+3 -1
View File
@@ -1,12 +1,14 @@
<script lang="ts">
import { syncLocale } from '$lib/i18n';
import { syncTableFormulas } from '$lib/formulas';
import { syncFileTitle } from '$lib/editor/fileTitle';
import { onMount } from 'svelte';
import { onSettingsChange, readSection, writeSection } from '$lib/settings/store';
import { applyAppearance, readAppearance } from './appearance';
onMount(() => {
const stopLocale = syncLocale();
const stopFormulas = syncTableFormulas();
const stopFileTitle = syncFileTitle();
const read = () => {
try {
const stored = readSection('appearance');
@@ -21,6 +23,6 @@
};
read();
const stops = [onSettingsChange('appearance', read), onSettingsChange('customThemes', read)];
return () => { stopLocale(); stopFormulas(); stops.forEach(stop => stop()); };
return () => { stopLocale(); stopFormulas(); stopFileTitle(); stops.forEach(stop => stop()); };
});
</script>
-179
View File
@@ -1,179 +0,0 @@
<script lang="ts">
import { tick } from "svelte";
import Icon from "./Icon.svelte";
import type { IconName } from "./IconButton.svelte";
type Option = { value: string; label: string; icon: IconName };
let { label, options, value, onchange, shortcut = "" }: {
label: string;
options: Option[];
value: string;
onchange: (value: string) => void;
shortcut?: string;
} = $props();
let expanded = $state(false);
let tooltipDismissed = $state(false);
let hovered = false;
let keyboardFocus = false;
let group: HTMLDivElement;
const selected = $derived(Math.max(0, options.findIndex(option => option.value === value)));
function scheduleExpansion() {
if (hovered || keyboardFocus) expanded = true;
}
function collapse() {
expanded = false;
}
function leave() {
hovered = false;
if (!keyboardFocus) collapse();
}
async function choose(index: number) {
scheduleExpansion();
const hadFocus = group.contains(document.activeElement);
onchange(options[index].value);
await tick();
// A compact click changes which button is visible; carry focus with it.
if (hadFocus) group.querySelector<HTMLButtonElement>(`[data-value="${options[index].value}"]`)?.focus({ preventScroll: true });
}
function keydown(event: KeyboardEvent) {
keyboardFocus = true;
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
tooltipDismissed = true;
collapse();
group.querySelector<HTMLButtonElement>(`[data-value="${value}"]`)?.focus();
} else if (["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) {
event.preventDefault();
expanded = true;
const index = event.key === "Home" ? 0 : event.key === "End" ? options.length - 1
: (selected + (event.key === "ArrowRight" ? 1 : -1) + options.length) % options.length;
void choose(index);
}
}
</script>
<div
bind:this={group}
class="mode-switcher"
class:expanded
class:tooltip-dismissed={tooltipDismissed}
role="group"
aria-label={label}
style:--count={expanded ? options.length : 1}
style:--selected={expanded ? selected : 0}
onmouseenter={() => { hovered = true; scheduleExpansion(); }}
onmouseleave={leave}
onfocusin={(event) => {
if ((event.target as HTMLElement).matches(":focus-visible") && !group.contains(event.relatedTarget as Node)) {
keyboardFocus = true;
scheduleExpansion();
}
}}
onfocusout={(event) => {
if (!group.contains(event.relatedTarget as Node)) {
keyboardFocus = false;
if (!hovered) collapse();
}
}}
>
<span class="selection" aria-hidden="true"></span>
{#each options as option, index (option.value)}
<button
type="button"
class:current={option.value === value}
class:concealed={!expanded && option.value !== value}
style:--index={expanded ? index : 0}
data-value={option.value}
aria-label={option.label}
aria-pressed={option.value === value}
tabindex={expanded || option.value === value ? 0 : -1}
onmouseenter={() => { tooltipDismissed = false; }}
onfocus={() => { tooltipDismissed = false; }}
onpointerdown={() => { keyboardFocus = false; }}
onpointerup={scheduleExpansion}
onpointercancel={scheduleExpansion}
onkeydown={keydown}
onkeyup={(event) => { if (event.key === "Enter" || event.key === " ") scheduleExpansion(); }}
onclick={() => void choose(expanded ? index : (selected + 1) % options.length)}
>
<Icon icon={option.icon} />
<span class="tooltip" role="tooltip" aria-hidden="true">{option.label}{shortcut}</span>
</button>
{/each}
</div>
<style>
.mode-switcher {
--segment: 32px;
position: relative;
flex: 0 0 auto;
width: calc(var(--segment) * var(--count) + 6px);
height: 34px;
border: 1px solid transparent;
border-radius: var(--rs-control-radius);
}
.selection {
position: absolute;
inset: 2px auto 2px 2px;
width: var(--segment);
border-radius: var(--rs-control-radius);
background: var(--rs-bg-active);
transform: translateX(calc(var(--selected) * var(--segment)));
transition: transform 180ms ease;
pointer-events: none;
}
button {
position: absolute;
top: 2px;
left: 2px;
width: var(--segment);
height: 28px;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
border: 0;
border-radius: var(--rs-control-radius);
background: transparent;
color: var(--rs-text-dim);
font-size: 12px;
transform: translateX(calc(var(--index) * var(--segment)));
transition: opacity 120ms ease;
}
button.current { color: var(--rs-text-strong); }
button:hover { color: var(--rs-text-strong); }
button.concealed { visibility: hidden; opacity: 0; pointer-events: none; }
button:hover, button:focus-visible { z-index: 1; }
.tooltip {
position: absolute;
top: calc(100% + 9px);
right: 0;
padding: var(--rs-tooltip-padding);
border: 1px solid var(--rs-border);
border-radius: var(--rs-control-radius);
background: var(--rs-tooltip-bg);
box-shadow: var(--rs-tooltip-shadow);
color: var(--rs-tooltip-text);
font: var(--rs-tooltip-font-size)/1.5 var(--rs-font-ui);
white-space: nowrap;
pointer-events: none;
visibility: hidden;
opacity: 0;
}
.mode-switcher:not(.tooltip-dismissed) button:not(.concealed):is(:hover, :focus-visible) .tooltip {
visibility: visible;
opacity: 1;
transition: opacity 120ms ease 200ms, visibility 0s linear 200ms;
}
@media (prefers-reduced-motion: reduce) {
.mode-switcher, .selection, button { transition: none; }
}
</style>
+4 -4
View File
@@ -23,11 +23,11 @@ export function detectChrome(relPath: string): Chrome {
if (WRITING_EXT.has(extensionOf(relPath))) {
return "Writing";
}
return "Ide";
return "Source";
}
/** Writing wraps lines and hides the code gutters. IDE shows line numbers, folding, and the current line. */
/** Writing wraps lines and hides the code gutters. Source shows line numbers, folding, and the current line. */
export function chromeLayout(chrome: Chrome) {
const ide = chrome === "Ide";
return { wrap: !ide, gutters: ide, activeLine: ide };
const source = chrome === "Source";
return { wrap: !source, gutters: source, activeLine: source };
}
+11 -5
View File
@@ -1,10 +1,11 @@
import { paneBounds, removePane, splitPane, type SplitLayout } from "./splitLayout.ts";
export type DocumentPane = { id: string; documentId: string | null; reading: boolean };
/** `reading` shows only the Read view. `split` shows the Read view beside the editor. A pane never has both. */
export type DocumentPane = { id: string; documentId: string | null; reading: boolean; split: boolean };
export type DocumentPanes = { layout: SplitLayout; panes: DocumentPane[]; active: string };
export function initialDocumentPanes(): DocumentPanes {
return { layout: "document-main", panes: [{ id: "document-main", documentId: null, reading: false }], active: "document-main" };
return { layout: "document-main", panes: [{ id: "document-main", documentId: null, reading: false, split: false }], active: "document-main" };
}
export function selectPane(state: DocumentPanes, id: string): DocumentPanes {
@@ -14,7 +15,7 @@ export function selectPane(state: DocumentPanes, id: string): DocumentPanes {
/** Tabs own documents. Panes keep only a reference and local viewing state. */
export function syncDocumentPanes(state: DocumentPanes, live: readonly string[], selected: string | null): DocumentPanes {
const ids = new Set(live);
let panes = state.panes.map(pane => pane.documentId && !ids.has(pane.documentId) ? { ...pane, documentId: null, reading: false } : pane);
let panes = state.panes.map(pane => pane.documentId && !ids.has(pane.documentId) ? { ...pane, documentId: null, reading: false, split: false } : pane);
let active = state.active;
if (selected && ids.has(selected)) {
const existing = panes.find(pane => pane.documentId === selected);
@@ -39,7 +40,7 @@ export function splitDocumentPane(state: DocumentPanes, source: string, document
if (!state.panes.some(pane => pane.id === source) || state.panes.some(pane => pane.id === paneId)) return state;
return {
layout: splitPane(state.layout, source, paneId, "right"),
panes: [...state.panes, { id: paneId, documentId, reading: false }], active: paneId,
panes: [...state.panes, { id: paneId, documentId, reading: false, split: false }], active: paneId,
};
}
@@ -54,5 +55,10 @@ export function closeDocumentPane(state: DocumentPanes, id: string): DocumentPan
}
export function readDocumentPane(state: DocumentPanes, id: string, reading: boolean): DocumentPanes {
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, reading } : pane) };
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, reading, split: reading ? false : pane.split } : pane) };
}
/** Show or hide the Read view beside the editor. Split ends the Read-only view. */
export function splitDocumentView(state: DocumentPanes, id: string, split: boolean): DocumentPanes {
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, split, reading: split ? false : pane.reading } : pane) };
}
+5 -1
View File
@@ -12,6 +12,8 @@ export interface AppSettings {
showInternalFolder: boolean;
/** Calculate table cells that start with `=`. When off, formulas show as source text. */
tableFormulas: boolean;
/** Show the file name as a title above a Markdown note in Write and Read. */
showFileTitle: boolean;
}
export const DEFAULT_SETTINGS: Readonly<AppSettings> = {
@@ -19,6 +21,7 @@ export const DEFAULT_SETTINGS: Readonly<AppSettings> = {
autosaveSeconds: 5,
showInternalFolder: false,
tableFormulas: true,
showFileTitle: true,
};
export function validAutosaveSeconds(value: unknown): value is number {
@@ -33,6 +36,7 @@ export function normalizeSettings(input: unknown): AppSettings {
autosaveSeconds: validAutosaveSeconds(value?.autosaveSeconds) ? value.autosaveSeconds : DEFAULT_SETTINGS.autosaveSeconds,
showInternalFolder: value?.showInternalFolder === true,
tableFormulas: typeof value?.tableFormulas === "boolean" ? value.tableFormulas : DEFAULT_SETTINGS.tableFormulas,
showFileTitle: typeof value?.showFileTitle === "boolean" ? value.showFileTitle : DEFAULT_SETTINGS.showFileTitle,
};
}
@@ -50,5 +54,5 @@ export function saveSettings(settings: AppSettings): Promise<void> {
if (!validAutosaveSeconds(settings.autosaveSeconds) || typeof settings.autosaveEnabled !== "boolean") {
throw new Error(tr("Choose a whole number from 1 to 300 seconds."));
}
return writeSection("general", { autosaveEnabled: settings.autosaveEnabled, autosaveSeconds: settings.autosaveSeconds, showInternalFolder: settings.showInternalFolder === true, tableFormulas: settings.tableFormulas !== false });
return writeSection("general", { autosaveEnabled: settings.autosaveEnabled, autosaveSeconds: settings.autosaveSeconds, showInternalFolder: settings.showInternalFolder === true, tableFormulas: settings.tableFormulas !== false, showFileTitle: settings.showFileTitle !== false });
}
+1 -1
View File
@@ -1,4 +1,4 @@
export type Chrome = "Writing" | "Ide";
export type Chrome = "Writing" | "Source";
export type TreeKind = "file" | "folder";