Ask Save or Don't save, and show useful status facts

Phase 5-7.

- A changed tab asks Save, Don't save, or Cancel through the native
  dialog, instead of OK and Cancel to discard.
- The conflict banner uses --rs-warn with a warning icon. Keep my
  edits is the primary choice and comes first. Use disk version comes
  last, in the error color. The banner wraps in a narrow pane.
- The status bar shows the save state, the line and column, the word
  count, the line endings, and the view. It shows the watch mode only
  when it polls a network folder.
- The outline and the document facts follow the active tab. A tab
  without a document has no outline and no document facts.
- Tables: only formula cells have a hover hint, so no hint covers the
  next cell. The table adds no gap above its control area. The add
  controls show while a cell has focus.
- The plugin review marks Install and enable as the primary action. The
  other choice is Install, keep disabled.
- Read follows CommonMark soft breaks. Settings, General, Keep line
  breaks shows each source line break. The table preview and cell
  editors of Write keep their line breaks, because their editing
  depends on them.
- Catalog rows in French, Japanese, and Simplified Chinese.
- Docs: UI-053, the user guide, and plugins.md.

Tests: the new layout/plainFixes, the keepLineBreaks cases in the
settings unit tests, and the new install button name.
This commit is contained in:
Knotty Wyvern
2026-10-28 22:06:13 -07:00
parent 0fdc991b2e
commit eeddd880e1
24 changed files with 294 additions and 70 deletions
+15
View File
@@ -980,3 +980,18 @@ Native shell, background image, and desktop acceptance remain open.
- Evidence: `tests/smoke/layout/panesAndSettings.smoke.mjs`.
- Replaces / replaced by: The fixed side panes of narrow windows, and the Save button of the browser settings.
- Limits: At startup, the saved layout applies as it is, also in a narrow window. Panes give way only when the window becomes narrower. Browser checks use desktop service mocks. The SDK release that publishes the new icon names is a separate step.
### UI-053 — Close prompts, conflicts, the status bar, tables, and line breaks
- Type: Rule change
- Date: 2026-10-28
- Status: Implemented for user review
- Decision source: Owner decisions 11 and 14 of 2026-10-27 (interface review issues 10, 16, 17, 18, 23, and 24), stage 5-7.
- Previous rule: A changed tab closed after "Discard unsaved edits? OK/Cancel", with no Save. The conflict banner had no status color or icon, and Use disk version came first in the same style as the other choices. The status bar showed the path, "native watch", and the mode. A tab without a document kept the outline of the last note. Every table cell showed its address in a tooltip over the next cell, tables had about 70 pixels above them, and their add controls showed only on hover. The plugin review had three equal buttons. Read showed each source line break.
- New rule: A changed tab asks Save, Don't save, or Cancel. The conflict banner uses `--rs-warn` with a warning icon. Keep my edits is the primary choice and comes first, and Use disk version comes last in the error color. The status bar shows the save state, the line and column, the word count, the line endings, and the view, and it shows the watch mode only when it polls. The outline and the document facts follow the active tab. Only formula cells have a hover hint, the table adds no gap above its control area, and the add and drag controls show while a cell has focus. Install and enable is the primary plugin action, and the other choice is Install, keep disabled. Read follows CommonMark soft breaks, and **Keep line breaks** in Settings → General shows each source line break.
- Reason: The safe choice must be the easy choice. The status bar must show useful facts. A hint must not hide text.
- Scope: Tab closing, the conflict banner, the status bar, the outline, Write tables, the plugin install review, and Read.
- Shared implementation: `closeTabs` in `Workbench.svelte`, `DocumentArea.svelte`, `StatusBar.svelte`, `tableControls.ts`, `PluginManager.svelte`, `reading.css`, and `fileTitle.ts` (the document settings).
- Evidence: `tests/smoke/layout/plainFixes.smoke.mjs` and `tests/unit/layout/settings.spec.ts`.
- Replaces / replaced by: The OK and Cancel close prompt, and `white-space: pre-line` for every Read paragraph.
- Limits: The word count splits on spaces and counts each Han, Hiragana, and Katakana character as one word. The close prompt uses the native dialog, which browser checks mock. The table control area keeps its 26-pixel padding, because the drag handles need it. The drag handles still show only on hover: showing every row and column handle on focus was too busy. The line break setting applies to Read. The table preview and cell editors of Write keep each line break, because their editing depends on it.
+2 -2
View File
@@ -16,7 +16,7 @@ Get the release ZIP of the plugin, such as `runestone.terminal-<version>.zip`. D
2. Choose **Install plugin ZIP**.
3. Select one or more ZIP files. You can select up to 100 at a time.
4. Review the name, author, version, source, and destination of each plugin.
5. Choose **Install and enable**, or choose **Install** to install the plugin disabled.
5. Choose **Install and enable**, or choose **Install, keep disabled**.
RuneStone copies each plugin into its application data folder and keeps your ZIP unchanged.
The review and installation do not run plugin code.
@@ -65,7 +65,7 @@ RuneStone downloads only the attached ZIP. It does not clone or build the reposi
3. In **Release tag**, enter a tag. Leave it empty to get the latest stable release.
4. For a private repository, enter a Gitea **Access token** with read access to the repository.
5. Choose **Review release**.
6. Review the package. Choose **Install**, **Install and enable**, or, for an installed plugin, **Apply packages**.
6. Review the package. Choose **Install and enable**, **Install, keep disabled**, or, for an installed plugin, **Apply packages**.
To install a prerelease, enter its tag. The release must have exactly one plugin ZIP attached. Source archives and branch links do not work.
Use HTTPS for a remote server. HTTP sends the token and the package without encryption.
+6 -4
View File
@@ -82,7 +82,7 @@ Each document pane has one view control with three choices, and a **Split** butt
Press Ctrl+E to switch between Write and Source. Press Ctrl+Shift+E to switch between Read and the editor. The tab menu has the same choices under **View**.
In a narrow pane, the control shows only icons. Hover over an icon, or focus it with the keyboard, to see its name. The arrow keys move the choice.
The status bar shows the current view. The bar above the document shows the folder of the file, and the tab shows the file name.
The status bar shows the save state, the line and column of the cursor, the word count, the line endings (LF or CRLF), and the current view. For a folder on a network drive, it also shows **Polling for changes**. A tab without a document, such as the theme editor, has no outline and no document facts. The bar above the document shows the folder of the file, and the tab shows the file name.
Write keeps your Markdown source, frontmatter, and Windows line endings. Read shows frontmatter in a collapsed **Properties** section.
Select a checkbox to complete a task. Copy code blocks without their Markdown fences with the **Copy code** button.
In a list item, press Tab to make a nested item. Press Shift+Tab to move it one level up. RuneStone renumbers the list.
@@ -93,6 +93,8 @@ To rename a note, select its title in Write and type a new name. Press Enter or
The file keeps its folder, extension, contents, and edit history.
To hide the title in Write and Read, turn off **Settings → General → File name title**. Then use F2 or **Rename…** in the tab menu.
Read follows CommonMark: a single line break inside a paragraph is a space. To show each line break of the source in Read, turn on **Settings → General → Keep line breaks**.
### Links and backlinks
- Ctrl+click a link in Write or Source. In Read, a normal click follows the link.
@@ -164,7 +166,7 @@ Press Ctrl+S to save the active file immediately.
To change auto-save, open **Settings → General**. Set an interval from 1 to 300 seconds, or turn auto-save off.
**Restore defaults** sets auto-save on with a 5-second interval.
If you close a tab or window with unsaved edits, RuneStone asks before it discards them or ends terminal sessions.
If you close a tab with unsaved edits, RuneStone asks whether to save them: **Save**, **Don't save**, or **Cancel**. If you close a window with unsaved edits or running terminal sessions, RuneStone asks before it closes.
Unsaved text and terminal sessions do not survive a restart or a crash.
## Resolve file conflicts
@@ -178,9 +180,9 @@ Then choose one action:
| Action | Result |
| --- | --- |
| **Use disk version** | Replaces your edits with the file on disk. |
| **Keep my edits** | Keeps your edits. The next save replaces the file on disk. |
| **Save a copy** | Saves your edits to a new file. |
| **Use disk version** | Replaces your edits with the file on disk. The button is last, in the error color. |
If the file is deleted, the tab keeps your text. Use **Save a copy**, or **Retry** after the file is back.
@@ -194,7 +196,7 @@ Settings apply at once to all workspaces on this computer and update all open wi
| Category | Settings |
| --- | --- |
| General | Display language, **File name title**, **Table formulas**, **Show .runestone folder**, and auto-save |
| General | Display language, **File name title**, **Keep line breaks**, **Table formulas**, **Show .runestone folder**, and auto-save |
| Appearance | Color theme, transparency, background image, and custom themes. See [Appearance and custom themes](guides/themes.md). |
| Plug-ins | Install, enable, update, and remove plugins. See [Install and manage plugins](plugins.md). |
| Browser | Homepage, search engine, profiles, ad blocking, and web data |
+13 -4
View File
@@ -50,7 +50,8 @@
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
focusLine?: number | null;
onSelectionLine?: (line: number) => void;
/** The line and the column of the cursor, from 1. */
onSelectionLine?: (line: number, column: number) => void;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
shouldFocusOnMount?: () => boolean;
@@ -189,6 +190,11 @@
return untrack(() => $fileTitleVisible) ? noteTitle(markdownTitle(path), onRenameTitle ? renameTitle : undefined) : [];
}
function reportCursor(state: EditorState) {
const head = state.selection.main.head, line = state.doc.lineAt(head);
onSelectionLine?.(line.number, head - line.from + 1);
}
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 }] : [];
@@ -221,7 +227,7 @@
EditorView.updateListener.of(update => {
if (update.docChanged || update.selectionSet) {
menu?.close(false);
onSelectionLine?.(update.state.doc.lineAt(update.state.selection.main.head).number);
reportCursor(update.state);
}
if (!update.docChanged) return;
scroll = scroll?.map(update.changes);
@@ -314,7 +320,7 @@
// Restore through CodeMirror's layout pass, once its viewport is measured.
const view = new EditorView({ state, parent: el, scrollTo: restore?.scroll });
editor = view;
onSelectionLine?.(view.state.doc.lineAt(view.state.selection.main.head).number);
reportCursor(view.state);
scroll = restore?.scroll ?? view.scrollSnapshot();
// Svelte may detach the old tab before effect cleanup runs, at which point
// DOM scroll offsets read as zero. Capture while the view is still mounted.
@@ -502,12 +508,15 @@
.live-writer :global(.writer-preview) { display: flow-root; max-width: none; margin: 0; white-space: normal; }
.live-writer :global(.writer-preview > :last-child) { margin-bottom: 0; }
.live-writer :global(.writer-preview img) { max-width: 100%; }
.live-writer :global(.writer-table) { position: relative; width: fit-content; max-width: 100%; margin: 1.4em 0 0; padding: 26px; }
/* The padding holds the drag and add controls. The table adds no extra gap above it. */
.live-writer :global(.writer-table) { position: relative; width: fit-content; max-width: 100%; margin: 0; padding: 26px; }
.live-writer :global(.writer-table .md-table-scroll) { margin: 0; border-radius: 0; }
.live-writer :global(.writer-table td), .live-writer :global(.writer-table th) { cursor: text; }
.live-writer :global(.writer-cell-editor) { outline: none; min-height: 1lh; white-space: pre-wrap; overflow-wrap: break-word; }
.live-writer :global(.writer-table p) { margin: 0; }
.live-writer :global(.table-add) { position: absolute; display: block; padding: 0; opacity: 0; border: 1px solid var(--rs-border); background: var(--rs-bg-elevated); color: var(--rs-text-dim); cursor: pointer; transition: opacity 100ms; }
/* The add controls show, in dim color, while a cell of the table has focus. */
.live-writer :global(.writer-table:focus-within .table-add) { opacity: 1; }
.live-writer :global(.table-add:hover), .live-writer :global(.table-add:focus-visible) { opacity: 1; color: var(--rs-accent); border-color: var(--rs-accent-deep); outline: none; }
.live-writer :global(.table-add-column) { right: 0; top: 26px; bottom: 26px; width: 26px; border-radius: 0 4px 4px 0; }
.live-writer :global(.table-add-row) { left: 26px; right: 26px; bottom: 0; height: 26px; border-radius: 0 0 4px 4px; }
+8 -4
View File
@@ -1,4 +1,5 @@
// The `showFileTitle` general setting shows the file name as a title above a Markdown note in Write and Read.
// The document settings of the general section. `showFileTitle` shows the file name as a title above a Markdown note
// in Write and Read. `keepLineBreaks` keeps each line break of the source in Read.
import { writable } from "svelte/store";
import { onSettingsChange } from "../settings/store.ts";
import { DEFAULT_SETTINGS, readSettings } from "../workspace/settings.ts";
@@ -7,11 +8,14 @@ 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. */
/** Apply the saved settings 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); }
let settings = DEFAULT_SETTINGS;
try { settings = readSettings(); } catch { /* The defaults apply. */ }
visible.set(settings.showFileTitle);
// The `keepLineBreaks` setting: Read shows each source line break (src/lib/layout/reading.css).
document.documentElement.toggleAttribute("data-keep-line-breaks", settings.keepLineBreaks);
};
read();
return onSettingsChange("general", read);
+4 -2
View File
@@ -92,7 +92,9 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
for (const row of table!.rows) for (const cell of row.cells) {
const result = results[row.rowIndex]?.[cell.cellIndex];
const address = formulas.cellAddress(row.rowIndex, cell.cellIndex);
cell.dataset.cellHint = `${address}${result?.formula ? ` · ${result.formula}` : ""}`;
// Only a formula cell has a hover hint. The footer shows the address of each cell, so no hint covers the next cell.
if (result?.formula) cell.dataset.cellHint = `${address} · ${result.formula}`;
else delete cell.dataset.cellHint;
cell.removeAttribute("title");
if (result && cell !== active) cell.innerHTML = formulas.tableFormulaHtml(result);
if (cell === active) {
@@ -453,6 +455,6 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
});
refreshFormulas();
for (const row of table.rows) for (const cell of row.cells) {
tooltipCleanup.push(attachTooltip(cell, () => cell.dataset.cellHint || cell.getAttribute("aria-label") || ""));
tooltipCleanup.push(attachTooltip(cell, () => cell.dataset.cellHint || ""));
}
}
+11 -12
View File
@@ -2177,12 +2177,6 @@ export const messageRows: [string, string, string, string][] = [
"プラグインのインストールを確認",
"检查插件安装"
],
[
"Install",
"Installer",
"インストール",
"安装"
],
[
"Install and enable",
"Installer et activer",
@@ -2921,12 +2915,6 @@ export const messageRows: [string, string, string, string][] = [
" · 離すとキャンセル",
" · 松开以取消"
],
[
"Discard unsaved edits in {name}?",
"Abandonner les modifications non enregistrées de {name} ?",
"{name}の未保存の変更を破棄しますか?",
"放弃 {name} 中未保存的编辑?"
],
[
"Extracted selection to {path}",
"Sélection extraite vers {path}",
@@ -3424,6 +3412,17 @@ export const messageRows: [string, string, string, string][] = [
["Remove bookmark: {name}", "Retirer le signet : {name}", "ブックマークを削除: {name}", "移除书签:{name}"],
["Show in Finder", "Afficher dans le Finder", "Finder で表示", "在访达中显示"],
["Show in file manager", "Afficher dans le gestionnaire de fichiers", "ファイルマネージャーで表示", "在文件管理器中显示"],
["This folder is on a network drive. RuneStone checks it for changes at intervals.", "Ce dossier se trouve sur un lecteur réseau. RuneStone y recherche les modifications à intervalles réguliers.", "このフォルダーはネットワークドライブ上にあります。RuneStone は一定の間隔で変更を確認します。", "此文件夹位于网络驱动器上。RuneStone 会定期检查其中的更改。"],
["Polling for changes", "Recherche périodique des modifications", "変更を定期確認中", "正在定期检查更改"],
["Saved", "Enregistré", "保存済み", "已保存"],
["Ln {line}, Col {column}", "Ligne {line}, col. {column}", "{line} 行、{column} 列", "第 {line} 行,第 {column} 列"],
["1 word", "1 mot", "1 語", "1 个词"],
["{count} words", "{count} mots", "{count} 語", "{count} 个词"],
["Don't save", "Ne pas enregistrer", "保存しない", "不保存"],
["Save the changes to {name}?", "Enregistrer les modifications de {name} ?", "{name} の変更を保存しますか?", "是否保存对 {name} 的更改?"],
["Install, keep disabled", "Installer, laisser désactivé", "インストールして無効のままにする", "安装,保持停用"],
["Keep line breaks", "Conserver les sauts de ligne", "改行を保持", "保留换行"],
["Show each line break of the source in Read. When this is off, Read joins the lines of a paragraph, as CommonMark does.", "Afficher chaque saut de ligne de la source en lecture. Désactivé, la lecture joint les lignes d’un paragraphe, comme CommonMark.", "閲覧でソースの各改行を表示します。オフにすると、CommonMark と同様に段落内の行を連結します。", "在阅读中显示源文本的每个换行。关闭后,阅读会像 CommonMark 一样合并段落中的各行。"],
];
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
+17 -7
View File
@@ -7,6 +7,7 @@
import type { Documents } from "$lib/workspace/documents.svelte";
import type { OpenBuffer } from "$lib/workspace/types";
import EditorPane from "./EditorPane.svelte";
import Icon from "$lib/ui/Icon.svelte";
import type { ViewMode } from "./ViewModes.svelte";
import TabBar from "./TabBar.svelte";
@@ -42,11 +43,12 @@
linkActions: (pane: DocumentView) => EditorProps["linkActions"];
onView: (pane: DocumentView, view: ViewMode) => void;
onSplitView: (pane: DocumentView, split: boolean) => void;
onCursor: (pane: DocumentView, line: number, column: number) => 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, onView, onSplitView, onOpenLink }: Props = $props();
onQuickOpen, onOpenBrowser, onChange, onInsertImage, onRenameTitle, tableActions, linkActions, onView, onSplitView, onCursor, onOpenLink }: Props = $props();
</script>
<main class="center">
@@ -76,13 +78,15 @@
onpointerdowncapture={() => onFocusPane(pane.id)}
onfocusin={() => onFocusPane(pane.id)}>
{#if pane.buffer?.diskError}
<div class="conflict" role="alert"><span>{pane.buffer.diskError}</span><button onclick={() => onSaveCopy(pane.buffer)}>{$t("Save a copy")}</button><button onclick={() => void documents?.refresh()}>{$t("Retry")}</button></div>
<div class="conflict" role="alert"><Icon icon="alert" /><span>{pane.buffer.diskError}</span><button class="primary" onclick={() => void documents?.refresh()}>{$t("Retry")}</button><button onclick={() => onSaveCopy(pane.buffer)}>{$t("Save a copy")}</button></div>
{:else if pane.buffer?.diskContents != null}
<div class="conflict" role="alert">
<!-- The safe choice comes first. The choice that discards your edits comes last, in the error color. -->
<Icon icon="alert" />
<span>{$t("This file changed on disk. Your edits are preserved. Review both versions before saving.")}</span>
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, true); }}>{$t("Use disk version")}</button>
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, false); }}>{$t("Keep my edits")}</button>
<button class="primary" onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, false); }}>{$t("Keep my edits")}</button>
<button onclick={() => onSaveCopy(pane.buffer)}>{$t("Save a copy")}</button>
<button class="danger" onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, true); }}>{$t("Use disk version")}</button>
</div>
<details class="disk-review"><summary>{$t("View disk version")}</summary><pre>{pane.buffer.diskContents}</pre></details>
{/if}
@@ -110,6 +114,7 @@
linkActions={linkActions(pane)}
onView={view => onView(pane, view)}
onSplit={next => onSplitView(pane, next)}
onCursor={(line, column) => onCursor(pane, line, column)}
onOpenLink={(kind, target) => onOpenLink(pane, kind, target)}
/>
</div>
@@ -130,9 +135,14 @@
background: transparent;
}
.conflict { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding: 10px; background: var(--rs-bg-active); border-bottom: 1px solid var(--rs-warn); }
.conflict span { flex: 1 1 300px; }
.conflict button { border: 1px solid var(--rs-border); background: var(--rs-bg); padding: 4px 8px; }
/* The conflict banner uses the warning status color and icon. Its text and buttons wrap in a narrow pane. */
.conflict { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding: 10px; background: color-mix(in srgb, var(--rs-warn) 14%, var(--rs-bg)); border-bottom: 2px solid var(--rs-warn); color: var(--rs-text-strong); }
.conflict > :global(svg) { width: 18px; height: 18px; flex-shrink: 0; color: var(--rs-warn); }
.conflict span { flex: 1 1 220px; min-width: 0; }
.conflict button { min-height: 28px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); padding: 4px 10px; }
.conflict button:hover { background: var(--rs-bg-active); }
.conflict button.primary { border-color: var(--rs-accent); background: var(--rs-accent); color: var(--rs-on-accent); }
.conflict button.danger { border-color: var(--rs-error); color: var(--rs-error); }
.disk-review { padding: 8px 12px; max-height: 35vh; overflow: auto; flex: 0 0 auto; }
.disk-review pre { white-space: pre-wrap; user-select: text; }
+3 -2
View File
@@ -31,6 +31,7 @@
onInsertImage?: (file: File) => 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;
@@ -45,7 +46,7 @@
onCloseSplit?: () => void;
};
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 { 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);
const git = $derived.by(() => { void $pluginHost; return pluginHost.get("git"); });
@@ -187,7 +188,7 @@
<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) => selectedLine = line}
{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>
+4
View File
@@ -147,6 +147,10 @@
<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="rs-switch" type="checkbox" role="switch" aria-describedby="file-title-description" checked={settings.showFileTitle} onchange={event => apply({ ...settings, showFileTitle: event.currentTarget.checked })} />
</div>
<div class="setting-row">
<div><label for="keep-line-breaks">{$t("Keep line breaks")}</label><p id="line-breaks-description">{$t("Show each line break of the source in Read. When this is off, Read joins the lines of a paragraph, as CommonMark does.")}</p></div>
<input id="keep-line-breaks" class="rs-switch" type="checkbox" role="switch" aria-describedby="line-breaks-description" checked={settings.keepLineBreaks} onchange={event => apply({ ...settings, keepLineBreaks: event.currentTarget.checked })} />
</div>
</div>
<h3>{$t("Tables")}</h3>
<div class="card">
+19 -11
View File
@@ -1,16 +1,22 @@
<script lang="ts">
// The status bar at the bottom of the workbench.
// The status bar at the bottom of the workbench: the last message, then the facts of the active document.
import { t } from "$lib/i18n";
import type { ViewMode } from "./ViewModes.svelte";
// `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();
type Facts = { saved: boolean; line: number; column: number; words: number; endings: "LF" | "CRLF" };
// `view` and `facts` belong to the active text document. They are null for other tabs.
// `polling` is true when the workspace is on a network drive, where RuneStone polls for changes.
let { message, polling, view, facts }: { message: string; polling: boolean; view: ViewMode | null; facts: Facts | null } = $props();
</script>
<footer class="status">
<span>{message}</span>
{#if watchMode}
<span>{watchMode} watch</span>
<span class="message">{message}</span>
{#if polling}<span title={$t("This folder is on a network drive. RuneStone checks it for changes at intervals.")}>{$t("Polling for changes")}</span>{/if}
{#if facts}
<span class:unsaved={!facts.saved}>{facts.saved ? $t("Saved") : $t("Unsaved")}</span>
<span>{$t("Ln {line}, Col {column}", { line: facts.line, column: facts.column })}</span>
<span>{facts.words === 1 ? $t("1 word") : $t("{count} words", { count: facts.words })}</span>
<span>{facts.endings}</span>
{/if}
{#if view}<span>{view === "read" ? $t("Read") : view === "source" ? $t("Source") : $t("Write")}</span>{/if}
</footer>
@@ -19,22 +25,24 @@
.status {
grid-column: 1 / -1;
display: flex;
justify-content: space-between;
gap: 12px;
gap: 16px;
padding: 0 10px;
background: var(--rs-bg-elevated);
border-top: 1px solid var(--rs-border);
color: var(--rs-text-dim);
font-size: 12px;
white-space: nowrap;
overflow: hidden;
}
/* The message takes the free space, so the other items stay at the right. */
.status :first-child {
/* The message takes the free space, so the facts stay at the right. */
.message {
flex: 1;
min-width: 0;
color: var(--rs-text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.unsaved { color: var(--rs-text-strong); }
</style>
+32 -4
View File
@@ -16,7 +16,7 @@
import type { Contributions } from "$lib/plugins/contracts";
import { invoke, isTauri } from "@tauri-apps/api/core";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { confirm } from "@tauri-apps/plugin-dialog";
import { confirm, message as dialogMessage } from "@tauri-apps/plugin-dialog";
import { openUrl } from "@tauri-apps/plugin-opener";
import { Documents } from "$lib/workspace/documents.svelte";
import { documentSessionKey, parseDocumentSession, restoreDocumentSession, type DocumentSession } from "$lib/workspace/documentSession";
@@ -369,9 +369,27 @@
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");
// The outline and the status bar follow the active tab. A plugin or browser tab has no document facts.
const documentActive = $derived(!editorPluginVisible && buffer?.kind === "text");
const outlineItems = $derived(
buffer && buffer.kind === "text" ? buildOutline(buffer.relPath, buffer.contents) : [],
documentActive && buffer ? buildOutline(buffer.relPath, buffer.contents) : [],
);
let cursor = $state({ line: 1, column: 1 });
$effect(() => { void buffer?.id; cursor = { line: 1, column: 1 }; });
const documentFacts = $derived(documentActive && buffer ? {
saved: buffer.contents === buffer.saved,
line: cursor.line,
column: cursor.column,
words: countWords(buffer.contents),
endings: buffer.saved.includes("\r\n") ? "CRLF" as const : "LF" as const,
} : null);
/** Words separated by space, and each Han, Hiragana, or Katakana character as one word. */
function countWords(text: string) {
const ideographs = text.match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/gu)?.length ?? 0;
const rest = text.replace(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/gu, " ").trim();
return ideographs + (rest ? rest.split(/\s+/).length : 0);
}
function applyChrome(next: Chrome) {
view = next;
@@ -650,8 +668,17 @@
if ("buffer" in target) {
if (!tab) continue;
const contents = tab.contents;
if (contents !== tab.saved && !await confirm($t("Discard unsaved edits in {name}?", { name: tab.name }), { title: $t("Close document"), kind: "warning" })) break;
if (contents !== tab.saved) {
// The platform choices for a changed document: Save, Don't save, or Cancel.
const labels = { yes: $t("Save"), no: $t("Don't save"), cancel: $t("Cancel") };
const choice = await dialogMessage($t("Save the changes to {name}?", { name: tab.name }), { title: $t("Close document"), kind: "warning", buttons: labels });
if (choice !== labels.yes && choice !== "Yes" && choice !== labels.no && choice !== "No") break;
if (documents !== current || switching || tab.contents !== contents) break;
if (choice === labels.yes || choice === "Yes") {
try { await current!.save(tab.id); } catch (reason) { error = String(reason); break; }
}
}
if (documents !== current || switching) break;
if (scope !== "one" && tab.pinned) continue;
}
const index = workingTabs.findIndex(item => item.id === target.id);
@@ -1353,6 +1380,7 @@
})}
onView={(pane, next) => setDocumentView(pane.id, next)}
onSplitView={(pane, next) => setSplitView(pane.id, next)}
onCursor={(pane, line, column) => { if (pane.id === documentPanes.active) cursor = { line, column }; }}
onOpenLink={(pane, kind, target) => void openLink(kind, target, pane.buffer?.relPath ?? "", pane.id)}
/>
{#if terminalContribution && terminalStarted}
@@ -1414,7 +1442,7 @@
/>
{/if}
<StatusBar message={error ?? status} watchMode={workspace?.watch_mode ?? null} view={buffer?.kind === "text" ? viewMode : null} />
<StatusBar message={error ?? status} polling={workspace?.watch_mode === "poll"} view={documentActive ? viewMode : null} facts={documentFacts} />
</div>
<style>
+4
View File
@@ -36,6 +36,10 @@
.document-title, .reading .document-title { margin: 0 0 .85em; color: var(--rs-text-strong); font: var(--rs-heading-weight) 1.8em/1.3 var(--rs-font-heading); overflow-wrap: anywhere; }
.reading > :first-child { margin-top: 0; }
.reading p { margin: 0 0 .75em; white-space: pre-line; }
/* Read follows CommonMark soft breaks by default. The Keep line breaks setting shows each source line break.
The table preview and cell editors of Write keep their line breaks: their editing depends on them. */
.reading:not(.writer-preview) p { white-space: normal; }
:root[data-keep-line-breaks] .reading:not(.writer-preview) p { white-space: pre-line; }
.reading strong { font-weight: 600; color: var(--rs-text-strong); }
.reading a { color: var(--rs-link); text-decoration-thickness: 1px; text-underline-offset: 3px; }
.reading a:hover { color: var(--rs-accent-2); }
+3 -1
View File
@@ -191,7 +191,7 @@
</div>
{/each}
{#if error}<p class="error" role="alert">{error}</p>{/if}
<footer><button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button><button disabled={busy || !selected.length} onclick={() => install(false)}>{$t(hasUpdates ? "Apply packages" : "Install")}</button>{#if !hasUpdates}<button disabled={busy || !selected.length} onclick={() => install(true)}>{$t("Install and enable")}</button>{/if}</footer>
<footer><button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button><button class:primary={hasUpdates} disabled={busy || !selected.length} onclick={() => install(false)}>{hasUpdates ? $t("Apply packages") : $t("Install, keep disabled")}</button>{#if !hasUpdates}<button class="primary" disabled={busy || !selected.length} onclick={() => install(true)}>{$t("Install and enable")}</button>{/if}</footer>
{/if}
</dialog>
{/if}
@@ -225,6 +225,8 @@
dialog { width: min(650px, 90vw); max-height: 85vh; padding: 16px; color: var(--rs-text); background: var(--rs-bg); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
dialog::backdrop { background: var(--rs-scrim); }
footer { justify-content: flex-end; margin-top: var(--rs-settings-section-gap); }
/* The likely action is the primary button. */
footer .primary:not(:disabled) { border-color: var(--rs-accent); background: var(--rs-accent); color: var(--rs-on-accent); }
.candidate { padding: var(--rs-settings-row-padding) 0; border-bottom: 1px solid var(--rs-border); }
.candidate label { display: flex; gap: 8px; }
input[type=checkbox] { accent-color: var(--rs-accent); }
+5 -1
View File
@@ -14,6 +14,8 @@ export interface AppSettings {
tableFormulas: boolean;
/** Show the file name as a title above a Markdown note in Write and Read. */
showFileTitle: boolean;
/** Show each line break of the Markdown source in Read. Off follows CommonMark: a line break inside a paragraph is a space. */
keepLineBreaks: boolean;
}
export const DEFAULT_SETTINGS: Readonly<AppSettings> = {
@@ -22,6 +24,7 @@ export const DEFAULT_SETTINGS: Readonly<AppSettings> = {
showInternalFolder: false,
tableFormulas: true,
showFileTitle: true,
keepLineBreaks: false,
};
export function validAutosaveSeconds(value: unknown): value is number {
@@ -37,6 +40,7 @@ export function normalizeSettings(input: unknown): AppSettings {
showInternalFolder: value?.showInternalFolder === true,
tableFormulas: typeof value?.tableFormulas === "boolean" ? value.tableFormulas : DEFAULT_SETTINGS.tableFormulas,
showFileTitle: typeof value?.showFileTitle === "boolean" ? value.showFileTitle : DEFAULT_SETTINGS.showFileTitle,
keepLineBreaks: value?.keepLineBreaks === true,
};
}
@@ -54,5 +58,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, showFileTitle: settings.showFileTitle !== false });
return writeSection("general", { autosaveEnabled: settings.autosaveEnabled, autosaveSeconds: settings.autosaveSeconds, showInternalFolder: settings.showInternalFolder === true, tableFormulas: settings.tableFormulas !== false, showFileTitle: settings.showFileTitle !== false, keepLineBreaks: settings.keepLineBreaks === true });
}
+125
View File
@@ -0,0 +1,125 @@
// Plain fixes: Save, Don't save, and Cancel when a changed tab closes, the conflict banner, the status bar facts,
// panes that follow the active tab, table hints and controls, and the line break setting.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/plainFixes", async ({ page }) => {
const output = await outputDir("layout/plainFixes");
await mockTauri(page, {
state: { answer: "Cancel" },
commands: test => {
const workspace = test.workspace({
root: "C:\\plain",
files: {
"a.md": "# Alpha\n\nFirst line\nsecond line of the same paragraph.\n",
"b.md": "# Beta\r\n\r\nWindows text.\r\n",
"c.md": "# Gamma\n\nThird note.\n",
"table.md": "| Name | Value |\n| --- | --- |\n| One | 1 |\n| Two | =B2*2 |\n",
},
});
Object.assign(test, { files: workspace.files });
return {
...workspace,
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
"plugin:window|is_maximized": () => false,
"plugin:dialog|message": args => { (test.state.prompts ??= []).push(args); return test.state.answer; },
};
},
});
await page.setViewportSize({ width: 1280, height: 800 });
await page.goto(smokeUrl);
await page.getByText("plain", { exact: true }).waitFor();
await page.evaluate(() => window.__TEST__.writeSettings("general", { autosaveEnabled: false, autosaveSeconds: 5 }));
const open = async name => {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("tab", { name, exact: true, selected: true }).waitFor();
};
const status = () => page.locator(".status").innerText();
const type = async text => { await page.locator(".cm-content").click(); await page.keyboard.press("Control+End"); await page.keyboard.type(text); };
const answer = value => page.evaluate(value => { window.__TEST__.state.answer = value; }, value);
const file = name => page.evaluate(name => window.__TEST__.files.get(name), name);
// The status bar shows the save state, the cursor, the words, the line endings, and the view. Native watching has no label.
await open("a.md");
await page.locator(".cm-content").click();
await page.keyboard.press("Control+Home");
await page.waitForFunction(() => /Ln 1, Col 1/.test(document.querySelector(".status").textContent));
assert.match(await status(), /Saved/);
assert.match(await status(), /10 words/);
assert.match(await status(), /LF/);
assert.doesNotMatch(await status(), /watch/i);
await open("b.md");
await page.waitForFunction(() => /CRLF/.test(document.querySelector(".status").textContent));
await page.locator(".status").screenshot({ path: `${output}/status.png` });
// Closing a changed tab asks Save, Don't save, or Cancel.
await type(" Edited");
await page.waitForFunction(() => /Unsaved/.test(document.querySelector(".status").textContent));
const prompts = () => page.evaluate(() => window.__TEST__.state.prompts ?? []);
await page.keyboard.press("Control+w");
await page.waitForFunction(() => (window.__TEST__.state.prompts ?? []).length === 1);
assert.deepEqual((await prompts())[0].buttons, { YesNoCancelCustom: ["Save", "Don't save", "Cancel"] });
assert.equal(await page.getByRole("tab", { name: /^b\.md/ }).count(), 1, "Cancel keeps the tab");
await answer("Save");
await page.keyboard.press("Control+w");
await page.getByRole("tab", { name: /^b\.md/ }).waitFor({ state: "detached" });
assert.match(await file("b.md"), /Edited/);
await open("c.md");
await type(" Dropped");
await answer("Don't save");
await page.keyboard.press("Control+w");
await page.getByRole("tab", { name: /^c\.md/ }).waitFor({ state: "detached" });
assert.doesNotMatch(await file("c.md"), /Dropped/);
// The conflict banner: the warning icon, the safe choice first, and the choice that discards edits last.
await open("a.md");
await type(" Mine");
await page.evaluate(() => {
window.__TEST__.files.set("a.md", "# Alpha\n\nChanged on disk.\n");
window.__TEST__.emit("workspace-event", { root: "C:\\plain", kind: "modify", paths: ["a.md"] });
});
const banner = page.locator(".conflict");
await banner.waitFor();
assert.equal(await banner.locator("svg").count(), 1);
assert.deepEqual(await banner.getByRole("button").allInnerTexts(), ["Keep my edits", "Save a copy", "Use disk version"]);
const color = token => page.evaluate(token => { const probe = document.createElement("span"); probe.style.color = `var(${token})`; document.body.append(probe); const value = getComputedStyle(probe).color; probe.remove(); return value; }, token);
assert.equal(await banner.getByRole("button", { name: "Use disk version" }).evaluate(node => getComputedStyle(node).color), await color("--rs-error"));
assert.equal(await banner.evaluate(node => getComputedStyle(node).borderBottomColor), await color("--rs-warn"));
await page.setViewportSize({ width: 880, height: 800 });
assert.ok(await banner.evaluate(node => node.scrollWidth <= node.clientWidth + 1), "The banner wraps in a narrow pane");
await page.screenshot({ path: `${output}/conflict-narrow.png` });
await page.setViewportSize({ width: 1280, height: 800 });
await banner.getByRole("button", { name: "Keep my edits" }).click();
await banner.waitFor({ state: "detached" });
// Read follows CommonMark soft breaks by default. The setting keeps each source line break.
await page.keyboard.press("Control+s");
await chooseView(page, "Read");
const paragraph = page.locator(".md-page .reading p").first();
assert.equal(await paragraph.evaluate(node => getComputedStyle(node).whiteSpace), "normal");
await page.evaluate(() => window.__TEST__.writeSettings("general", { ...window.__TEST__.settings("general"), keepLineBreaks: true }));
await page.waitForFunction(() => getComputedStyle(document.querySelector(".md-page .reading p")).whiteSpace === "pre-line");
await page.evaluate(() => window.__TEST__.writeSettings("general", { ...window.__TEST__.settings("general"), keepLineBreaks: false }));
await chooseView(page, "Write");
// A plain table cell has no hover hint, because the footer shows its address. The controls show while a cell has focus.
await open("table.md");
const table = page.locator(".live-writer .writer-table");
await table.waitFor();
await table.locator("td").first().hover();
await page.waitForTimeout(500);
assert.equal(await page.locator(".rs-tooltip:popover-open").count(), 0);
await table.locator("td").first().click();
await page.waitForFunction(() => getComputedStyle(document.querySelector(".writer-table .table-add")).opacity === "1");
await page.keyboard.press("Escape");
// The outline and the status bar follow the active tab: a tab without a document has no outline and no document facts.
await page.evaluate(() => window.__TEST__.emit("runestone-theme-editor-open", null));
await page.getByRole("tab", { name: "Theme editor", exact: true, selected: true }).waitFor();
await page.waitForFunction(() => !/Ln \d/.test(document.querySelector(".status").textContent));
assert.equal(await page.locator("aside.right li").count(), 0);
assert.deepEqual(page.errors, []);
console.log("PASS: status bar facts, Save, Don't save, and Cancel on close, conflict banner order and colors, line break setting, table hints and controls, panes that follow the active tab.");
});
+4 -1
View File
@@ -358,7 +358,8 @@ await runSmoke("layout/workbench", async ({ page }) => {
assert.equal(await tableHeading.innerText(), '# Table layout');
await table.locator('tbody tr').first().locator('td').first().click();
await page.waitForFunction(() => document.querySelector('.live-writer .writer-heading')?.textContent === 'Table layout');
await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '0'));
// The add controls show while a cell of the table has focus (src/lib/editor/DocumentEditor.svelte).
await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '1'));
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('tables.md')), tableSource);
assert.equal(await table.locator('th').count(), 5);
@@ -374,6 +375,8 @@ await runSmoke("layout/workbench", async ({ page }) => {
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
const addColumn = page.getByRole('button', { name: 'Add column to the right', exact: true });
const addRow = page.getByRole('button', { name: 'Add row below', exact: true });
// The add controls show on hover, and also while a cell of the table has focus. This part checks hover alone.
await page.evaluate(() => document.activeElement?.blur());
await addColumn.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1');
assert.equal(await addRow.evaluate(el => getComputedStyle(el).opacity), '0');
+3 -3
View File
@@ -88,9 +88,9 @@ await runSmoke("links/linkEditing", async ({ page }) => {
for (const mode of ['light','dark']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}),mode);
await page.locator('.writer-table td').nth(1).hover();
await page.locator('.rs-tooltip:popover-open').waitFor();
// Table formulas are on by default, so the cell tooltip shows the cell address.
assert.equal(await page.locator('.rs-tooltip:popover-open').innerText(),'B2');
// Only a formula cell has a hover hint. The footer shows the address of the cell with focus (src/lib/editor/tableControls.ts).
await page.waitForTimeout(500);
assert.ok((await page.locator('.rs-tooltip:popover-open').allInnerTexts()).every(text => !/^[A-Z]+\d+/.test(text)));
await page.screenshot({path:path.join(output, 'editor-cell-tooltip-narrow-'+mode+'.png')});
await page.keyboard.press('Escape');
await page.mouse.move(5,90);
+2 -1
View File
@@ -84,7 +84,8 @@ await runSmoke("links/workspaceLinks", async ({ page }) => {
});
await backlink('moved/wiki.md').waitFor();
assert.equal(await backlink('wiki.md').count(),0);
await page.evaluate(()=>{window.__TEST__.answer='Ok';});
// A changed tab asks Save, Don't save, or Cancel (src/lib/layout/Workbench.svelte).
await page.evaluate(()=>{window.__TEST__.answer="Don't save";});
await page.getByRole('tab',{name:/^source\.md(?: •)?$/}).click();
await page.keyboard.press('Control+w');
await page.getByRole('tab',{name:/^source\.md(?: •)?$/}).waitFor({state:'detached'});
+1 -1
View File
@@ -175,7 +175,7 @@ await runSmoke("plugins/install", async ({ browser }) => {
await shot("plugin-git-narrow.png");
assert.equal(await gitDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
await gitDialog.getByRole("button", { name: "Review release", exact: true }).click();
await review.getByRole("button", { name: "Install", exact: true }).click();
await review.getByRole("button", { name: "Install, keep disabled", exact: true }).click();
await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).waitFor();
assert.equal(await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).isChecked(), false);
assert.equal(await count("plugins_from_git"), 3);
+2 -1
View File
@@ -105,7 +105,8 @@ await runSmoke("tabs/menus", async ({ page }) => {
await item("Close all").click();
await page.waitForFunction(() => window.__TEST__.prompts.length === 1);
assert.deepEqual(await order(), ["b.md", "c.md"]);
await page.evaluate(() => { window.__TEST__.answer = "Ok"; });
// A changed tab asks Save, Don't save, or Cancel (src/lib/layout/Workbench.svelte).
await page.evaluate(() => { window.__TEST__.answer = "Don't save"; });
await show("c.md •");
await item("Close all").click();
await tab("c.md •").waitFor({ state: "detached" });
+7 -5
View File
@@ -7,9 +7,9 @@ test("missing or damaged preferences keep safe defaults", () => {
assert.deepEqual(parseSettings(raw), DEFAULT_SETTINGS);
}
for (const autosaveSeconds of [0, -1, 301, 1.5, "10", null]) {
assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds, showInternalFolder: false })), { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true, showFileTitle: true });
assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds, showInternalFolder: false })), { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true, showFileTitle: true, keepLineBreaks: false });
}
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10, showInternalFolder: false, tableFormulas: true, showFileTitle: true });
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10, showInternalFolder: false, tableFormulas: true, showFileTitle: true, keepLineBreaks: false });
});
function withStorage(storage: Pick<Storage, "getItem" | "setItem">, body: () => void) {
@@ -22,7 +22,7 @@ test("preferences persist and load at both interval limits", () => {
const store = new Map<string, string>();
withStorage({ getItem: (key: string) => store.get(key) ?? null, setItem: (key: string, value: string) => { store.set(key, value); } }, () => {
for (const autosaveSeconds of [1, 23, 300]) {
const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false, tableFormulas: autosaveSeconds !== 23, showFileTitle: autosaveSeconds !== 300 };
const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false, tableFormulas: autosaveSeconds !== 23, showFileTitle: autosaveSeconds !== 300, keepLineBreaks: autosaveSeconds === 1 };
void saveSettings(settings);
assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings);
assert.deepEqual(readSettings(), settings);
@@ -34,7 +34,7 @@ test("invalid changes never reach storage and storage failures reach the caller"
let writes = 0;
withStorage({ getItem: () => null, setItem: () => { writes++; } }, () => {
for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) {
assert.throws(() => saveSettings({ autosaveEnabled: true, autosaveSeconds, showInternalFolder: false, tableFormulas: true, showFileTitle: true }));
assert.throws(() => saveSettings({ autosaveEnabled: true, autosaveSeconds, showInternalFolder: false, tableFormulas: true, showFileTitle: true, keepLineBreaks: false }));
}
});
assert.equal(writes, 0);
@@ -45,9 +45,11 @@ test("invalid changes never reach storage and storage failures reach the caller"
test("stored values of any type normalize to safe settings", () => {
for (const value of [undefined, null, 42, "text", [], { autosaveSeconds: 0 }]) assert.deepEqual(normalizeSettings(value), DEFAULT_SETTINGS);
assert.deepEqual(normalizeSettings({ autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true }), { autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true, tableFormulas: true, showFileTitle: true });
assert.deepEqual(normalizeSettings({ autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true }), { autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true, tableFormulas: true, showFileTitle: true, keepLineBreaks: false });
assert.equal(normalizeSettings({ tableFormulas: false }).tableFormulas, false);
for (const tableFormulas of [null, 0, "false", {}]) assert.equal(normalizeSettings({ tableFormulas }).tableFormulas, true);
assert.equal(normalizeSettings({ showFileTitle: false }).showFileTitle, false);
for (const showFileTitle of [null, 0, "false", {}]) assert.equal(normalizeSettings({ showFileTitle }).showFileTitle, true);
assert.equal(normalizeSettings({ keepLineBreaks: true }).keepLineBreaks, true);
for (const keepLineBreaks of [null, 1, "true", {}]) assert.equal(normalizeSettings({ keepLineBreaks }).keepLineBreaks, false);
});
+2 -2
View File
@@ -16,7 +16,7 @@ test('Migration reads the four old keys and the theme backup, and normalizes eac
'runestone.language': 'fr',
}));
assert.deepEqual(sections, {
general: { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true, showFileTitle: true },
general: { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true, showFileTitle: true, keepLineBreaks: false },
language: 'fr',
customThemes: [{ ...custom, schema: 3, mode: 'dark' }],
customThemesLegacy: [{ schema: 1, id: 'kept' }],
@@ -50,7 +50,7 @@ test('Damaged old values become defaults and unknown languages become English',
'runestone.language': 'de',
}));
assert.deepEqual(sections, {
general: { autosaveEnabled: true, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true, showFileTitle: true },
general: { autosaveEnabled: true, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true, showFileTitle: true, keepLineBreaks: false },
language: 'en',
appearance: { theme: 'default', mode: 'dark' },
});
+1 -1
View File
@@ -64,7 +64,7 @@ test('The first start migrates the old localStorage values, and later reads come
assert.deepEqual(calls.filter(call => !call.command.startsWith('plugin:')).map(call => call.command), ['settings_read', 'settings_migrate']);
assert.equal(calls[0].command, 'plugin:event|listen', 'The listener starts before the read');
assert.equal(store.readSection('language'), 'ja');
assert.deepEqual(store.readSection('general'), { autosaveEnabled: true, autosaveSeconds: 12, showInternalFolder: false, tableFormulas: true, showFileTitle: true });
assert.deepEqual(store.readSection('general'), { autosaveEnabled: true, autosaveSeconds: 12, showInternalFolder: false, tableFormulas: true, showFileTitle: true, keepLineBreaks: false });
assert.equal(legacy.get('runestone.language'), 'ja', 'The old value stays in place');
assert.equal(store.takeSettingsNotice(), 'Notice once');
assert.equal(store.takeSettingsNotice(), null);