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
+1 -1
View File
@@ -22,7 +22,7 @@ For checksums, updates, and reinstalls, see [Installation and updates](docs/inst
## What you can do
- Write Markdown with live formatting, editable tables, table formulas, images, and Mermaid diagrams.
- Switch between Writer, IDE source editing, Read, and Split views.
- Switch between the Write, Source, Read, and Split views.
- Find files, search a workspace, and resolve changes that other tools make to your files.
- Open web pages in browser tabs beside your documents.
- Add optional plugins, such as Terminal, Git, Project Management, PDF Viewer, and CSV Viewer.
+16
View File
@@ -918,3 +918,19 @@ Native shell, background image, and desktop acceptance remain open.
- Evidence: `tests/smoke/layout/commands.smoke.mjs`, `tests/unit/ui/shortcuts.spec.ts`, and `tests/unit/layout/workbenchKeys.spec.ts`.
- Replaces / replaced by: The Ctrl+B sidebar shortcut in the user guide.
- Limits: The macOS labels are tested as unit cases, not on a Mac. Browser checks use desktop service mocks.
### UI-049 — One view control and one file name
- Type: Rule change
- Date: 2026-10-28
- Status: Implemented for user review
- Decision source: Owner decisions 4 and 5 of 2026-10-27 (interface review issues 5 and 7), stage 5-3.
- Previous rule: Two icon-only switchers, "Document view" (Edit, Read, Split) and "Editor layout" (Writer, IDE), showed only the current choice until hover. Hover widened them, so the target moved. The same views had other names in the tab menu ("Reading view", "Source mode") and in the status bar ("IDE"). The file name showed in the tab, in the breadcrumb as a full path, as a title, and in the status bar.
- New rule: 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 separate **Split** toggle shows Read beside Write or Source. Write and Source keep Split, and Read ends it. Ctrl+E switches between Write and Source, and Ctrl+Shift+E switches between Read and the editor. The tab menu, the status bar, the docs, and the code use the same names. "IDE" is not a view name.
- File name: The file name title stays on by default. **Settings → General → File name title** hides it in Write and Read. The breadcrumb shows only the folder, with the full path in its tooltip. The status bar shows the view, not the path.
- Reason: A choice that a user cannot see does not help, and a target must not move under the pointer. "IDE" promised language services that Source does not have. The tab already names the file.
- Scope: Document panes, the tab menu, the status bar, Settings → General, and the docs.
- Shared implementation: `ViewModes.svelte`, `documentPanes.ts` (`split` beside `reading`), `fileTitle.ts`, and the `Source` value of the `Chrome` type.
- Evidence: `tests/smoke/layout/viewModes.smoke.mjs`, `tests/unit/layout/documentPanes.spec.ts`, and `tests/unit/layout/settings.spec.ts`.
- Replaces / replaced by: `ModeSwitcher.svelte` and its hover test.
- Limits: Split now shows Write beside Read when Write is the editor. Choose Source for the former source and preview layout. Browser checks use desktop service mocks.
+1 -1
View File
@@ -80,7 +80,7 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command
| Folder | Responsibility |
| --- | --- |
| `layout/` | The app shell: `Workbench.svelte` holds the state and the commands, and `WorkbenchHeader`, `PluginRibbon`, `LeftPane`, `DocumentArea`, `RightPane`, and `StatusBar` draw its regions. Also the file tree, tabs, panes, Settings, and dialogs |
| `layout/` | The app shell: `Workbench.svelte` holds the state and the commands, and `WorkbenchHeader`, `PluginRibbon`, `LeftPane`, `DocumentArea`, `RightPane`, and `StatusBar` draw its regions. `ViewModes` is the Write, Source, and Read control of each document pane. Also the file tree, tabs, panes, Settings, and dialogs |
| `editor/` | The document editor (`DocumentEditor.svelte`) with its Write and Source configurations, Markdown lists, tables, links, images, and editor menus |
| `formulas/` | Table formulas: the parser and evaluator (`engine.ts`), the rendered results, the formula help, and the `tableFormulas` setting (`index.ts`) |
| `workspace/` | Tauri wrappers, document buffers, the workspace session (`session.svelte.ts`: marks, renames, change events, and the note index), paths, templates, and tab transfer (`tabTransfer.ts`) |
+4 -4
View File
@@ -13,7 +13,7 @@ This guide explains how to insert and edit images, read diagrams, edit Markdown
Undo removes the inserted link. It keeps the image file.
In Writer, the image shows and its Markdown stays hidden. To edit the Markdown, choose **Edit image source**. To hide it again, choose the same button, press Escape, or move the cursor away.
In Write, the image shows and its Markdown stays hidden. To edit the Markdown, choose **Edit image source**. To hide it again, choose the same button, press Escape, or move the cursor away.
Select an image, then right-click it or press Shift+F10 for these actions:
@@ -22,11 +22,11 @@ Select an image, then right-click it or press Shift+F10 for these actions:
- **Copy path** and **Show in Explorer**, for workspace images
**Remove image**, or the Delete key, removes the image link from the note. It does not delete the file. Undo restores the link.
Zoom works in Writer, Read, and Split. It can fit the image or magnify it. Press Escape to close it.
Zoom works in Write, Read, and Split. It can fit the image or magnify it. Press Escape to close it.
## Read diagrams and document properties
Writer, Read, and Split show wiki links, note callouts, and Mermaid diagrams.
Write, Read, and Split show wiki links, note callouts, and Mermaid diagrams.
RuneStone renders Mermaid diagrams locally. If a diagram is not valid, RuneStone shows an error message and the diagram source.
Read shows frontmatter in a collapsed **Properties** section.
@@ -95,7 +95,7 @@ Start a cell with `=` to make a formula. Columns use letters A, B, … AA. Row 1
| Functions | SUM, AVERAGE, MIN, MAX, COUNT, ABS, and ROUND |
Functions that take a range ignore text and blank cells. Arithmetic uses zero for a blank cell.
Results update in Writer, Read, and Split. Select a result to edit its formula. Enter saves the formula, and Tab moves to the next cell.
Results update in Write, Read, and Split. Select a result to edit its formula. Enter saves the formula, and Tab moves to the next cell.
The **Formulas** control below each table explains the syntax. The active cell shows its address.
A formula that is not valid, a missing cell, or a circular reference shows an error label.
+8
View File
@@ -94,6 +94,14 @@
"design": "Shared action menu",
"check": "tests/smoke/menus/consistency.smoke.mjs"
},
"RuneStone/src/lib/layout/CommandPalette.svelte": {
"counts": {
"picker": 1,
"localPopup": 3
},
"design": "Shared searchable picker (rs-picker) for the command palette",
"check": "tests/smoke/layout/commands.smoke.mjs"
},
"RuneStone/src/lib/layout/QuickOpen.svelte": {
"counts": {
"picker": 1,
+6 -6
View File
@@ -167,10 +167,10 @@ Decisions: [UI-028](design-decisions.md#ui-028--adjustable-surface-transparency-
## Typography and tables
- The interface uses `--rs-font-ui`. Prose uses `--rs-font-prose`. Headings use `--rs-font-heading`.
- The IDE and Terminal share `--rs-font-mono` and `--rs-code-font-weight` (default 300). The monospace stack starts with Cascadia Mono, then Cascadia Code, JetBrains Mono, Fira Code, and Consolas. Terminal font size is a separate setting.
- Source and Terminal share `--rs-font-mono` and `--rs-code-font-weight` (default 300). The monospace stack starts with Cascadia Mono, then Cascadia Code, JetBrains Mono, Fira Code, and Consolas. Terminal font size is a separate setting.
- Document headings use space between sections, not separator lines. Heading fold controls use the shared chevron and take keyboard focus.
- Tables use shared cell padding and line height. Entering a cell does not change its row height.
- A table row needs an unescaped pipe. Writer and Reading use the same row rule. A paragraph after a table stays a paragraph when the separator line is removed.
- A table row needs an unescaped pipe. Write and Read use the same row rule. A paragraph after a table stays a paragraph when the separator line is removed.
- A table link shows its Markdown source when the caret enters it. The caret stays at the chosen label character. Edit link selects the full target inside the cell. Test ordinary clicks and keyboard entry before menu actions ([UI-025](design-decisions.md#ui-025--table-links-hide-their-source-after-repeated-fixes)).
Decisions: [UI-005](design-decisions.md#ui-005--heading-spacing).
@@ -200,8 +200,8 @@ Decisions: [UI-009](design-decisions.md#ui-009--character-theme-appearances), [U
- The app image fills the work area below the titlebar, including new tabs and document views. It stays fixed while content scrolls.
- Sidebars use `--rs-image-sidebar-bg` (82% tint). Editor surfaces use `--rs-image-editor-bg` (90% tint). Without an image, both are opaque.
- Writer, Reading, split, and IDE views share the editor surface. CodeMirror layers stay transparent above it.
- Code blocks in Writer and Reading use `--rs-code-block-bg`.
- Write, Source, Read, and Split share the editor surface. CodeMirror layers stay transparent above it.
- Code blocks in Write and Read use `--rs-code-block-bg`.
- New-tab buttons use `--rs-image-control-bg` and `--rs-image-control-hover-bg`. Their tint keeps labels readable while the image stays visible. The new-tab screen shows only its action buttons, with icons, labels, and shortcuts.
- Headers and dialogs keep their own surfaces.
- The app work area and Project Management keep separate images and settings in every theme. An image can be up to 50 MiB. Image bytes stay in IndexedDB, and settings keep a small reference.
@@ -233,7 +233,7 @@ Decisions: [UI-015](design-decisions.md#ui-015--slower-slideshow-fades), [UI-020
- Use one tooltip per control, with no duplicate native `title`. Tooltips use the `--rs-tooltip-*` tokens for padding, font size, surface, text, and shadow. Table cell hints use the same surface.
- Hover and keyboard focus show a tooltip. Escape dismisses it. It stays inside the viewport.
- Text selection uses `--rs-selection` and `--rs-selection-text` in Writer, Reading, the IDE, and Project Management fields. A CodeMirror selection layer must override its generated default styles.
- Text selection uses `--rs-selection` and `--rs-selection-text` in Write, Source, Read, and Project Management fields. A CodeMirror selection layer must override its generated default styles.
- Text selection keeps the theme hue at 65% opacity or less, so the background shows through. A lower explicit opacity stays unchanged. Text stays opaque. Theme exports keep the source colors.
Decisions: [UI-019](design-decisions.md#ui-019--one-tooltip-surface), [UI-029](design-decisions.md#ui-029--text-selection-transparency).
@@ -243,7 +243,7 @@ Decisions: [UI-019](design-decisions.md#ui-019--one-tooltip-surface), [UI-029](d
- A workspace link can open another document in a pane to the right. A duplicate target focuses its existing pane.
- Closing a split keeps its tab and unsaved text. The focused pane controls Save, the outline, and the Terminal selection.
- Narrow work areas stack the panes vertically. Pane layouts stay local to the window.
- Writer, source, Reading, and plugin editor views share `FindPanel.svelte` and `find.css`.
- Write, Source, Read, and plugin editor views share `FindPanel.svelte` and `find.css`.
- A plugin document editor without a Find handler searches its visible rendered text through `readingSearch.ts`. Rendered-text Find has no replace controls. Plugin Find handlers stay in use for views with their own search engine.
- Generic plugin views and Kanban documents have no fallback Find.
- Ctrl+F opens Find. Enter and Shift+Enter move between matches. Escape closes Find and returns focus. Find and Replace fields turn off saved-input suggestions.
+22 -16
View File
@@ -70,26 +70,31 @@ On macOS and Linux, you can still open, edit, rename, and delete existing files
## Edit documents
Each document pane has two controls:
Each document pane has one view control with three choices, and a **Split** button:
| Control | Choices |
| Choice | Shows |
| --- | --- |
| Editor layout (Ctrl+E) | **Writer** shows formatted Markdown and reveals the source of the active line. **IDE** shows the plain source with syntax colors. |
| Document view | **Edit**, **Read**, or **Split**. Split shows the editor and the reading view together. It stacks them in narrow panes. |
| **Write** | Formatted Markdown. The active line shows its Markdown source. |
| **Source** | The plain source with line numbers and syntax colors |
| **Read** | The rendered document, without editing. Markdown files only. |
| **Split** | Read beside Write or Source. Narrow panes stack the two views. Select **Split** again to close it. Markdown files only. |
Hover over a control, or focus it with the keyboard, to see its name.
Writer keeps your Markdown source, frontmatter, and Windows line endings. Read shows frontmatter in a collapsed **Properties** section.
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.
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.
Nested ordered lists show letters, then Roman numerals. The Markdown source keeps the numbers, for example `1.`.
Tab in other text indents by 4 spaces.
To rename a note, select its title in Writer and type a new name. Press Enter or leave the field to save the name. Press Escape to cancel.
To rename a note, select its title in Write and type a new name. Press Enter or leave the field to save the name. Press Escape to cancel.
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.
### Links and backlinks
- Ctrl+click a link in Writer or IDE. In Read, a normal click follows the link.
- Ctrl+click a link in Write or Source. In Read, a normal click follows the link.
- A workspace file link opens in a new tab and keeps the current document open.
- A heading link, such as `guide.md#save-your-work` or `#save-your-work`, scrolls to that heading.
- A wiki link, such as `[[Meeting notes]]`, finds the note by name anywhere in the workspace. If two notes have the same name, use a relative or workspace path.
@@ -104,16 +109,16 @@ Right-click Markdown text, or press Shift+F10, to open the context menu. Use the
| Menu | Actions |
| --- | --- |
| Format | Bold, italic, strikethrough, highlight, code, math, comment, and clear formatting |
| Paragraph | Bulleted and numbered lists, tasks, headings 1–6, body text, and quotes |
| Insert | Footnotes, tables, callouts, horizontal rules, code blocks, and math blocks |
In Writer, these shortcuts format the selected text:
In Write, these shortcuts format the selected text:
| Format | Shortcut |
| --- | --- |
| Bold / Italic | Ctrl+B / Ctrl+I |
| Strikethrough / Highlight | Ctrl+Shift+X / Ctrl+Shift+H |
| Link (`[text]()`, with the cursor in the address) | Ctrl+K |
| Paragraph | Bulleted and numbered lists, tasks, headings 1–6, body text, and quotes |
| Insert | Footnotes, tables, callouts, horizontal rules, code blocks, and math blocks |
The menu also has link, search, extraction, and clipboard actions. RuneStone has no formatting toolbar.
Right-click a misspelled word to see spelling suggestions from the operating system.
@@ -187,7 +192,7 @@ Settings apply to all workspaces on this computer and update all open windows.
| Category | Settings |
| --- | --- |
| General | Display language, **Table formulas**, **Show .runestone folder**, and auto-save |
| General | Display language, **File name title**, **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 |
@@ -221,10 +226,11 @@ This table lists the Windows and Linux keys. On macOS, Cmd replaces Ctrl, and Ru
| Move the focused tab | Alt+Shift+Left / Alt+Shift+Right |
| Save | Ctrl+S |
| Find in document / Search workspace | Ctrl+F / Ctrl+Shift+F |
| Switch Writer and IDE | Ctrl+E |
| Switch Write and Source | Ctrl+E |
| Switch Read and the editor | Ctrl+Shift+E |
| Nest a list item / Move it up | Tab / Shift+Tab |
| Bold / Italic / Link (Writer) | Ctrl+B / Ctrl+I / Ctrl+K |
| Strikethrough / Highlight (Writer) | Ctrl+Shift+X / Ctrl+Shift+H |
| Bold / Italic / Link (Write) | Ctrl+B / Ctrl+I / Ctrl+K |
| Strikethrough / Highlight (Write) | Ctrl+Shift+X / Ctrl+Shift+H |
| Show or hide the sidebar | Ctrl+\ |
| Rename | F2 |
| Delete to the trash / Delete permanently | Delete / Shift+Delete |
@@ -236,7 +242,7 @@ The [Terminal guide](guides/terminal.md) lists the terminal shortcuts.
## Limits
- Math shows as formatted source text. RuneStone does not typeset formulas.
- The IDE editor colors syntax, but has no language services such as error checks or go to definition.
- Source colors syntax, but has no language services such as error checks or go to definition.
- RuneStone does not support Obsidian Bases.
- Plugins have full access to RuneStone and your files. See [Install and manage plugins](plugins.md).
+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";
+9
View File
@@ -79,6 +79,15 @@ export function settle(page) {
return page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
/**
* Choose "Write", "Source", or "Read" in the view control of a document pane, or toggle "Split" (src/lib/layout/ViewModes.svelte).
* `scope` is the page, or a pane locator when the window shows more than one document pane.
*/
export async function chooseView(scope, name) {
if (name === "Split") return scope.locator(".chrome-bar").getByRole("button", { name: "Split", exact: true }).click();
return scope.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name, exact: true }).click();
}
/**
* Mock the Tauri IPC layer before the app loads. The mock handles the event plugin.
*
@@ -1,7 +1,7 @@
// Workarea backgrounds in both themes: splash, writer, reader, split, IDE, narrow layouts, fades, reduced motion, and removal.
// Workarea backgrounds in both themes: splash, writer, reader, split, Source, narrow layouts, fades, reduced motion, and removal.
import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
import { chooseView, mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
const viewport = { width: 1280, height: 820 };
@@ -94,20 +94,19 @@ await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
assert.match(await style(page.locator('.editor > .body'), 'backgroundColor'), /(?:0\.9|90%)/);
await page.screenshot({ path: `${output}/${theme}-writer.png` });
await page.getByRole('group', { name: 'Document view', exact: true }).hover();
await page.getByRole('button', { name: 'Read', exact: true }).click();
await chooseView(page, 'Read');
await page.locator('.md-page').waitFor();
const beforeScroll = await background.boundingBox();
await page.locator('.md-page').evaluate(node => { node.scrollTop = 600; });
assert.deepEqual(await background.boundingBox(), beforeScroll);
await page.screenshot({ path: `${output}/${theme}-reader.png` });
await page.getByRole('button', { name: 'Split', exact: true }).click();
await page.locator('.source-editor .cm-content').waitFor();
assert.equal(await style(page.locator('.source-editor .cm-editor').first(), 'backgroundColor'), 'rgba(0, 0, 0, 0)');
// Split shows the Write editor beside Read.
await chooseView(page, 'Split');
await page.locator('.live-writer .cm-content').waitFor();
assert.equal(await style(page.locator('.live-writer .cm-editor').first(), 'backgroundColor'), 'rgba(0, 0, 0, 0)');
await page.screenshot({ path: `${output}/${theme}-split.png` });
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('group', { name: 'Editor layout', exact: true }).hover();
await page.getByRole('button', { name: 'IDE', exact: true }).click();
await chooseView(page, 'Split');
await chooseView(page, 'Source');
await page.locator('.source-editor .cm-content').waitFor();
await page.screenshot({ path: `${output}/${theme}-ide.png` });
await page.setViewportSize({ width: 680, height: 720 });
@@ -133,7 +132,7 @@ await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
assert.equal(await style(page.locator('.editor > .body'), 'backgroundColor'), await style(page.locator('.shell'), 'backgroundColor'));
await page.screenshot({ path: `${output}/${theme}-removed.png` });
assert.deepEqual(page.errors, []);
report.push({ theme, passed: ['saved image', 'continuous workarea', 'sidebar transparency', 'button-only splash', 'keyboard focus', 'writer', 'reader scrolling', 'split', 'IDE transparency', 'narrow layout', 'fade', 'reduced motion', 'slideshow removal', 'saved image removal'], screenshots: `${output}/${theme}-*.png`, nativeDesktop: 'not tested' });
report.push({ theme, passed: ['saved image', 'continuous workarea', 'sidebar transparency', 'button-only splash', 'keyboard focus', 'writer', 'reader scrolling', 'split', 'Source transparency', 'narrow layout', 'fade', 'reduced motion', 'slideshow removal', 'saved image removal'], screenshots: `${output}/${theme}-*.png`, nativeDesktop: 'not tested' });
await page.close();
console.log(`PASS: ${theme} workarea backgrounds, editors, keyboard, narrow layout, fade, and restoration`);
}
@@ -1,4 +1,4 @@
// Character themes: colors, fonts, IDE syntax, export, window sync, narrow theme cards, selection fills, and legacy or removed theme IDs.
// Character themes: colors, fonts, Source syntax, export, window sync, narrow theme cards, selection fills, and legacy or removed theme IDs.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
@@ -148,7 +148,7 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => {
});
await ide.locator('.source-editor .cm-selectionBackground').first().waitFor();
assert.equal(await ide.locator('.source-editor .cm-selectionBackground').first().evaluate(node => getComputedStyle(node).backgroundColor),
warmFill, 'IDE selection uses the same warm fill');
warmFill, 'Source selection uses the same warm fill');
await ide.screenshot({ path: path.join(output, `${theme}-${mode}-ide-selection.png`) });
await ide.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
@@ -185,7 +185,7 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => {
await settings.getByRole('button', { name: 'Plugin settings 16', exact: true }).scrollIntoViewIfNeeded();
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-360-long-navigation.png`) });
await setPluginTools(0);
console.log(`PASS: ${theme} ${mode}, colors, fonts, IDE syntax, export, saved state, window sync, narrow theme cards, keyboard and focus`);
console.log(`PASS: ${theme} ${mode}, colors, fonts, Source syntax, export, saved state, window sync, narrow theme cards, keyboard and focus`);
}
for (const [previous, theme, label] of [['holo', 'harvest-moon', 'Harvest Moon'], ['asuka', 'crimson-pilot', 'Crimson Pilot'], ['malfoid', 'silver-serpent', 'Silver Serpent']]) {
await settings.evaluate(theme => window.__TEST__.writeSettings('appearance', { theme, mode: 'dark' }), previous);
+6 -6
View File
@@ -16,8 +16,8 @@ await runSmoke("appearance/density", async ({ page }) => {
}),
});
const row = page.locator('[data-tree-rel="note.md"]');
const documentView = () => page.getByRole("group", { name: "Document view" }).locator("button.current");
const editorLayout = () => page.getByRole("group", { name: "Editor layout" }).locator("button.current");
// The checked choice of the view control. Arrow keys, Home, and End move the choice (src/lib/layout/ViewModes.svelte).
const view = () => page.getByRole("radiogroup", { name: "View" }).getByRole("radio", { checked: true });
const setTheme = theme => page.evaluate(theme => { document.documentElement.dataset.theme = theme; }, theme);
await page.goto(smokeUrl);
@@ -65,21 +65,21 @@ await runSmoke("appearance/density", async ({ page }) => {
assert.equal(tab.shadow, "none");
await line.hover();
await page.screenshot({ path: path.join(output, `writer-${theme}.png`) });
await documentView().press("ArrowRight");
await view().press("End");
await page.locator(".md-page .reading").waitFor();
const paragraph = page.locator(".md-page p").filter({ hasText: "A second paragraph." });
await paragraph.hover();
assert.equal(await paragraph.evaluate(el => getComputedStyle(el, "::before").width), "3px");
assert.ok((await page.locator(".md-page table").boundingBox()).width < 400);
await page.screenshot({ path: path.join(output, `read-${theme}.png`) });
await documentView().press("Home");
await view().press("Home");
}
await editorLayout().press("Home");
await view().press("ArrowRight");
await page.locator(".source-editor .cm-content").waitFor();
await page.locator(".line-history").waitFor();
await page.evaluate(() => window.removeGit());
await page.locator(".line-history").waitFor({ state: "hidden" });
await editorLayout().press("End");
await view().press("Home");
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await page.setViewportSize({ width: 760, height: 640 });
for (const theme of ["dark", "light"]) {
+1 -1
View File
@@ -29,7 +29,7 @@ await runSmoke("appearance/palettes", async ({ browser }) => {
await main.getByRole("dialog").getByRole("button").filter({ hasText: `theme-${index}.py` }).first().waitFor();
await main.getByRole("textbox", { name: "Find a file" }).press("Enter");
await main.locator(".source-editor .cm-content").waitFor();
await main.waitForFunction(file => document.querySelector(".editor .breadcrumb")?.textContent.endsWith(file)
await main.waitForFunction(file => document.querySelector(".editor .breadcrumb")?.title.endsWith(file)
&& document.querySelector(".source-editor .cm-content")?.dataset.language === "python", `theme-${index}.py`);
await main.locator(".source-editor .cm-line").filter({ hasText: `Theme sample ${index}` }).waitFor();
}
+4 -5
View File
@@ -1,6 +1,6 @@
// Writer text menu on empty and whitespace lines: submenus, disabled actions, links, the file picker, keyboard focus, both themes, a narrow window, and the IDE.
// Writer text menu on empty and whitespace lines: submenus, disabled actions, links, the file picker, keyboard focus, both themes, a narrow window, and the Source.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/emptyMenu", async ({ page }) => {
await mockTauri(page, {
@@ -95,8 +95,7 @@ await runSmoke("editor/emptyMenu", async ({ page }) => {
await page.setViewportSize({width:1440,height:1000});
await page.getByRole('button',{name:'Show outline',exact:true}).click();
}
await page.getByRole('group',{name:'Editor layout'}).hover();
await page.getByRole('button',{name:'IDE',exact:true}).click();
await chooseView(page, 'Source');
await page.locator('.source-editor .cm-content').waitFor();
await page.locator('.source-editor .cm-content').focus();
await page.keyboard.press('Shift+F10');
@@ -112,5 +111,5 @@ await runSmoke("editor/emptyMenu", async ({ page }) => {
await page.keyboard.press('Enter');
await page.getByRole('dialog').waitFor({state:'detached'});
await page.screenshot({path:`${output}/ide-links.png`});
console.log('PASS: empty and whitespace Writer menus, full submenus, disabled actions, links, picker, selection, keyboard focus, two themes, narrow viewport and IDE.');
console.log('PASS: empty and whitespace Writer menus, full submenus, disabled actions, links, picker, selection, keyboard focus, two themes, narrow viewport and Source.');
});
+3 -5
View File
@@ -1,6 +1,6 @@
// Footnotes and heading folds: the footnote menu, Reader numbering and backlinks, nested folding, keyboard toggles, and source preservation.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/footnotes", async ({ page }) => {
await mockTauri(page, {
@@ -95,8 +95,7 @@ await runSmoke("editor/footnotes", async ({ page }) => {
const borders = await page.locator(".writer-heading").evaluateAll(headings => headings.map(heading => getComputedStyle(heading).borderBottomWidth));
assert.ok(borders.every(border => border === "0px"));
assert.ok(await page.locator(".writer-heading").first().evaluate(heading => parseFloat(getComputedStyle(heading).paddingTop) > 8));
await page.getByRole("group", { name: "Document view" }).hover();
await page.getByRole("button", { name: "Read", exact: true }).click();
await chooseView(page, "Read");
await page.locator(".md-footnotes").waitFor();
assert.equal(await page.locator(".md-footnote-ref").count(), 2);
assert.equal(await page.locator(".md-footnotes li").count(), 1);
@@ -117,8 +116,7 @@ await runSmoke("editor/footnotes", async ({ page }) => {
assert.equal(await page.locator(".md-footnotes").isVisible(), true);
await page.locator(".md-footnote-back").first().click();
assert.equal(await page.evaluate(() => document.activeElement?.id), "rs-fnref-1-1");
await page.getByRole("group", { name: "Document view" }).hover();
await page.getByRole("button", { name: "Edit", exact: true }).click();
await chooseView(page, "Write");
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
await editor();
}
+2 -4
View File
@@ -1,6 +1,6 @@
// Images dragged from the file tree: hidden source, selection, image menu actions, cancel, and source mode.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/imageNavigation", async ({ page }) => {
await mockTauri(page, {
@@ -143,9 +143,7 @@ await runSmoke("editor/imageNavigation", async ({ page }) => {
await page.keyboard.press("Escape");
assert.equal(await page.locator(".cm-line").filter({ hasText: "![Reference]" }).count(), 0);
// The same navigator drag works in the source editor.
// The layout switcher names its buttons by mode (src/lib/layout/EditorPane.svelte:200-208, src/lib/ui/ModeSwitcher.svelte:96).
await page.getByRole("group", { name: "Editor layout", exact: true }).hover();
await page.getByRole("button", { name: "IDE", exact: true }).click();
await chooseView(page, "Source");
await page.locator(".source-editor .cm-content").waitFor();
await dragFromTree(".source-editor .cm-content");
await page.keyboard.press("Control+s");
+4 -4
View File
@@ -138,15 +138,15 @@ await runSmoke("editor/images", async ({ page }) => {
}, "../attachments/typed.svg");
await page.locator('img[alt="Wiki image"]').waitFor();
await save();
await page.getByRole("group", { name: "Document view" }).getByRole("button", { name: "Edit", exact: true }).focus();
await page.keyboard.press("ArrowRight");
await page.getByRole("radiogroup", { name: "View" }).getByRole("radio", { name: "Write", exact: true }).focus();
await page.keyboard.press("End");
await page.locator(".md-page .md-image-frame").first().hover();
await page.locator(".md-page").getByRole("button", { name: "Zoom in", exact: true }).first().click();
await page.getByRole("dialog", { name: "Image zoom" }).waitFor();
await page.keyboard.press("Escape");
// Source mode uses the same drop flow; the batch is one undo step.
await page.getByRole("group", { name: "Document view" }).getByRole("button", { name: "Read", exact: true }).focus();
// Source uses the same drop flow. The batch is one undo step.
await page.getByRole("radiogroup", { name: "View" }).getByRole("radio", { name: "Read", exact: true }).focus();
await page.keyboard.press("Home");
await page.keyboard.press("Control+e");
await page.locator(".source-editor .cm-content").waitFor();
+4 -6
View File
@@ -1,6 +1,6 @@
// Writer interactions: code selection and copy, caret and scroll restore, Ctrl+click links, shared heading typography, and spelling targets.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/interactions", async ({ page }) => {
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
@@ -93,7 +93,7 @@ await runSmoke("editor/interactions", async ({ page }) => {
}, linkPoint);
await page.keyboard.down("Control"); await page.mouse.click(point.x, point.y); await page.keyboard.up("Control");
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent.includes("other.md"));
console.log("PASS: Writer and IDE Ctrl+click open workspace links while retaining the source tab");
console.log("PASS: Writer and Source Ctrl+click open workspace links while retaining the source tab");
await page.getByRole("tab", { name: "note.md", exact: true }).click();
await page.keyboard.press("Control+e");
@@ -106,13 +106,11 @@ await runSmoke("editor/interactions", async ({ page }) => {
}, theme);
const writing = await page.locator(".writer-h1").first().evaluate(node => { const style = getComputedStyle(node); return { size: style.fontSize, line: style.lineHeight, family: style.fontFamily, weight: style.fontWeight }; });
await page.screenshot({ path: `${output}/editor-typography-${theme}.png` });
await page.getByRole("group", { name: "Document view", exact: true }).hover();
await page.getByRole("button", { name: "Read", exact: true }).click();
await chooseView(page, "Read");
const reading = await page.locator(".reading h1:not(.document-title)").first().evaluate(node => { const style = getComputedStyle(node); return { size: style.fontSize, line: style.lineHeight, family: style.fontFamily, weight: style.fontWeight }; });
assert.deepEqual(writing, reading);
await page.screenshot({ path: `${output}/reader-typography-${theme}.png` });
await page.getByRole("group", { name: "Document view", exact: true }).hover();
await page.getByRole("button", { name: "Edit", exact: true }).click();
await chooseView(page, "Write");
await top();
}
await page.setViewportSize({ width: 640, height: 750 });
+4 -6
View File
@@ -1,6 +1,6 @@
// List nesting: Tab and Shift+Tab in Write, nested labels in Write and Read, one undo history in Write and Source, and the 4-space indent in Source.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/listNesting", async ({ page }) => {
await mockTauri(page, {
@@ -68,21 +68,19 @@ await runSmoke("editor/listNesting", async ({ page }) => {
await page.keyboard.press("Tab");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n2. A\n", "The first item stays in place");
await page.getByRole("group", { name: "Document view" }).hover();
await page.getByRole("button", { name: "Read", exact: true }).click();
await chooseView(page, "Read");
await page.locator(".md-page ol ol").waitFor();
assert.equal(await page.locator(".md-page ol ol").evaluate(list => getComputedStyle(list).listStyleType), "lower-alpha");
assert.equal(await page.locator(".md-page > .reading > ol, .md-page ol").first().evaluate(list => getComputedStyle(list).listStyleType), "decimal");
await page.locator(".md-page").screenshot({ path: `${output}/reader.png` });
await page.getByRole("group", { name: "Document view" }).hover();
await page.getByRole("button", { name: "Edit", exact: true }).click();
await chooseView(page, "Write");
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
// Write and Source share the undo history of the document.
await caretAt("2. A");
await page.keyboard.type(" more");
await page.keyboard.press("Control+e");
await page.locator('.source-editor[data-chrome="Ide"] .cm-gutters').waitFor();
await page.locator('.source-editor[data-chrome="Source"] .cm-gutters').waitFor();
assert.equal(await page.locator(".source-editor .cm-content").getAttribute("data-language"), "markdown");
await page.locator(".source-editor .cm-content").focus();
await page.keyboard.press("Control+z");
+4 -2
View File
@@ -31,7 +31,8 @@ await runSmoke("editor/markdownMenu", async ({ page }) => {
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", { selected: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Source mode", exact: true }).click();
await page.getByRole("menuitem", { name: "View", exact: true }).click();
await page.getByRole("menuitemradio", { name: "Source", exact: true }).click();
await page.locator(".source-editor .cm-content").waitFor();
}
async function waitForText(text) {
@@ -56,7 +57,8 @@ await runSmoke("editor/markdownMenu", async ({ page }) => {
await waitForText("**First** paragraph.\n\nSecond paragraph.\n");
await page.keyboard.press("Control+z"); await waitForText(source);
await page.getByRole("tab", { selected: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Writing mode", exact: true }).click();
await page.getByRole("menuitem", { name: "View", exact: true }).click();
await page.getByRole("menuitemradio", { name: "Write", exact: true }).click();
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.click(); await page.keyboard.press("Control+Home");
await page.keyboard.press("Control+Shift+ArrowRight");
@@ -1,19 +0,0 @@
// The document mode switcher expands within 500 ms when the pointer hovers it.
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/modeSwitcherHover", async ({ page }) => {
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\mode-switcher", files: { "a.md": "# Alpha\n\nTemplate body.\n" } }),
plugins_snapshot: () => ({ plugins: [], issues: [] }),
spelling_menu_install: () => null,
}),
});
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator(".cm-content").waitFor();
await page.locator(".mode-switcher").first().hover();
await page.waitForFunction(() => document.querySelector(".mode-switcher")?.classList.contains("expanded"), null, { timeout: 500 });
await page.mouse.move(500, 400);
console.log("PASS: the mode switcher expands on hover");
}, { timeout: 15000 });
+2 -2
View File
@@ -1,4 +1,4 @@
// Repeated copy and paste of formatted Markdown stays exact across saves, tab switches, IDE switches, and line endings.
// Repeated copy and paste of formatted Markdown stays exact across saves, tab switches, Source switches, and line endings.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
@@ -94,5 +94,5 @@ await runSmoke("editor/pasteRepeat", async ({ page }) => {
});
assert.equal(synchronized, true, 'Writer and saved source agree');
}
console.log('PASS: formatted Markdown copied across notes stays exact through 12 paste/delete cycles, saves, tab reopen, IDE reopen, and LF/CRLF/CR clipboard replacement');
console.log('PASS: formatted Markdown copied across notes stays exact through 12 paste/delete cycles, saves, tab reopen, Source reopen, and LF/CRLF/CR clipboard replacement');
});
+3 -5
View File
@@ -1,6 +1,6 @@
// Front matter properties: first open, editing, undo, the saved selection, and both themes.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/properties", async ({ page }) => {
await mockTauri(page, {
@@ -47,11 +47,9 @@ await runSmoke("editor/properties", async ({ page }) => {
await page.evaluate(() => window.__CM__.dispatch({ selection: { anchor: window.__CM__.state.doc.length } }));
await page.locator('.md-properties').waitFor();
await page.evaluate(() => { window.__CM__.dispatch({ selection: { anchor: 11 } }); window.__CM__.focus(); });
await page.getByRole('group', { name: 'Document view' }).hover();
await page.getByRole('button', { name: 'Read', exact: true }).click();
await chooseView(page, 'Read');
await page.locator('.reading .md-properties').waitFor();
await page.getByRole('group', { name: 'Document view' }).hover();
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await chooseView(page, 'Write');
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
assert.equal(await page.locator('.writer-preview .md-properties').count(), 0);
console.log('Properties first-open, editing, undo, saved selection, and both themes passed.');
+2 -3
View File
@@ -1,7 +1,7 @@
// Text selection uses --rs-selection in Writer (native and CodeMirror layers) and in Read view, in both themes.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "editor/selectionColor";
await runSmoke(name, async ({ browser }) => {
@@ -36,8 +36,7 @@ await runSmoke(name, async ({ browser }) => {
assert.equal(colors.native, colors.expected);
assert.equal(colors.layer, colors.expected);
await page.screenshot({ path: path.join(output, `${theme}-writer-selection.png`) });
await page.getByRole("group", { name: "Document view", exact: true }).hover();
await page.getByRole("button", { name: "Read", exact: true }).click();
await chooseView(page, "Read");
const reader = page.locator(".reading");
await reader.waitFor();
assert.equal(await reader.evaluate(node => getComputedStyle(node, "::selection").backgroundColor), colors.expected);
+8 -12
View File
@@ -1,6 +1,6 @@
// Editor menu surfaces: Writer, spelling, IDE, and code menus share the file menu styles; and the code tint match in both themes.
// Editor menu surfaces: Writer, spelling, Source, and code menus share the file menu styles; and the code tint match in both themes.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/surfaces", async ({ page }) => {
await mockTauri(page, {
@@ -85,22 +85,19 @@ await runSmoke("editor/surfaces", async ({ page }) => {
const tint = await page.locator('.writer-code-line').first().evaluate(node => getComputedStyle(node).backgroundColor);
assert.ok(tint.includes('/ 0.82') || /rgba\(.+, 0\.82\)/.test(tint), `Writer code tint: ${tint}`);
await page.screenshot({ path: `${output}/writer-code-${theme}.png` });
await page.getByRole('group', { name: 'Document view', exact: true }).hover();
await page.getByRole('button', { name: 'Read', exact: true }).click();
await chooseView(page, 'Read');
const readingTint = await page.locator('pre.md-code').evaluate(node => getComputedStyle(node).backgroundColor);
assert.equal(readingTint, tint, 'Reader and Writer use the same code tint');
await page.screenshot({ path: `${output}/reader-code-${theme}.png` });
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('group', { name: 'Editor layout', exact: true }).hover();
await page.getByRole('button', { name: 'IDE', exact: true }).click();
await chooseView(page, 'Source');
await page.locator('.source-editor .cm-content').waitFor();
await page.locator('.source-editor').click({ button: 'right', position: { x: 500, y: 400 } });
assert.deepEqual(await styles(writer), reference, 'Markdown IDE retains the same menu');
assert.deepEqual(await styles(writer), reference, 'Markdown Source retains the same menu');
await dismiss();
await page.locator('[data-tree-rel="sample.txt"]').click();
await page.locator('.source-editor').click({ button: 'right', position: { x: 500, y: 400 } });
const code = menu('Code text actions');
assert.deepEqual(await styles(code), reference, 'Code IDE uses the host menu');
assert.deepEqual(await styles(code), reference, 'Code Source uses the host menu');
// The host menu is the only menu. The editor adds no menu of its own.
assert.equal(await page.getByRole('menu').count(), 1);
assert.equal(await code.getByRole('menuitem', { name: 'Command palette F1', exact: true }).count(), 0);
@@ -128,9 +125,8 @@ await runSmoke("editor/surfaces", async ({ page }) => {
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Show outline', exact: true }).click();
await page.locator('[data-tree-rel="a.md"]').click();
await page.getByRole('group', { name: 'Editor layout', exact: true }).hover();
await page.getByRole('button', { name: 'Writer', exact: true }).click();
report.push({ theme, passed: ['word and blank menu parity', 'spelling correction and undo', 'Writer/IDE parity', 'undo menu action', 'code menu host styles', 'transparent code in Writer/Reader', 'narrow keyboard menu'], nativeDesktop: 'not tested' });
await chooseView(page, 'Write');
report.push({ theme, passed: ['word and blank menu parity', 'spelling correction and undo', 'Writer/Source parity', 'undo menu action', 'code menu host styles', 'transparent code in Writer/Reader', 'narrow keyboard menu'], nativeDesktop: 'not tested' });
}
console.log(JSON.stringify(report, null, 2));
}, { timeout: 15000 });
+3 -3
View File
@@ -1,4 +1,4 @@
// Undo history survives tab switches, window focus, IDE edits, and table cell edits.
// Undo history survives tab switches, window focus, Source edits, and table cell edits.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
@@ -77,7 +77,7 @@ await runSmoke("editor/undoHistory", async ({ page }) => {
window.__IDE__ = view;
});
await page.keyboard.type(' second edit');
assert.equal(await page.evaluate(() => window.__IDE__.dom.isConnected), true, 'Typing keeps the same IDE editor mounted');
assert.equal(await page.evaluate(() => window.__IDE__.dom.isConnected), true, 'Typing keeps the same Source editor mounted');
assert.equal(await page.evaluate(() => window.__IDE__.state.doc.toString()), original + ' first edit second edit');
await page.keyboard.press('Control+e');
await expectWriter(original + ' first edit second edit');
@@ -91,7 +91,7 @@ await runSmoke("editor/undoHistory", async ({ page }) => {
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit second edit');
console.log('PASS: Writer undo includes edits from IDE mode');
console.log('PASS: Writer undo includes edits from Source mode');
const tableSource = '# Table\n\n| A | B |\n| --- | --- |\n| One | Two |\n\nTail.\n';
await page.evaluate(source => {
window.__TEST__.files.set('table.md', source);
+6 -11
View File
@@ -1,6 +1,6 @@
// One full-width document Find in Writer, table cells, IDE source, and Reading: replacement, regex, CRLF, focus return, both themes, and narrow controls.
// One full-width document Find in Writer, table cells, Source source, and Reading: replacement, regex, CRLF, focus return, both themes, and narrow controls.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("find/documentFind", async ({ page }) => {
const output = await outputDir("find/documentFind");
@@ -30,10 +30,6 @@ await runSmoke("find/documentFind", async ({ page }) => {
const sample = "# Alpha\n\nAlpha alpha alphabet\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n| Beta | Two |\n\nLast Alpha paragraph.\n";
const find = page.getByRole("textbox", { name: "Find in document", exact: true });
const replace = page.getByRole("textbox", { name: "Replace with", exact: true });
async function mode(group, value) {
await page.getByRole("group", { name: group, exact: true }).hover();
await page.getByRole("button", { name: value, exact: true }).click();
}
async function onePanel() {
assert.equal(await page.locator('.rs-find-bar:visible').count(), 1);
assert.equal(await page.locator('.cm-search').count(), 0, 'No default CodeMirror search panel');
@@ -82,7 +78,7 @@ await runSmoke("find/documentFind", async ({ page }) => {
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc(window.__CM__.state.selection.main.from, window.__CM__.state.selection.main.to)), /Last Alpha/);
await page.screenshot({ path: `${output}/table-focus-${theme}.png` });
await page.keyboard.press('Escape');
await mode('Editor layout', 'IDE');
await chooseView(page, 'Source');
await sourceEditor();
await page.evaluate(() => { const view = window.__SOURCE__; view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: 'Alpha alpha alphabet\r\nAlpha second\r\nAlpha third' }, selection: { anchor: 0 } }); });
await page.keyboard.press('Control+f');
@@ -130,7 +126,7 @@ await runSmoke("find/documentFind", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
await find.focus(); await page.keyboard.press('Escape');
await page.evaluate(sample => { const view = window.__SOURCE__; view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: sample } }); }, sample);
await mode('Document view', 'Read');
await chooseView(page, 'Read');
await page.locator('.reading').focus();
await page.keyboard.press('Control+f');
await find.fill('Alpha'); await page.keyboard.press('Enter');
@@ -143,8 +139,7 @@ await runSmoke("find/documentFind", async ({ page }) => {
await page.screenshot({ path: `${output}/reading-${theme}.png` });
await page.keyboard.press('Escape');
assert.equal(await page.locator('.reading').evaluate(node => node === document.activeElement), true);
await mode('Document view', 'Edit');
await mode('Editor layout', 'Writer');
await chooseView(page, 'Write');
}
console.log('PASS: one full-width document Find in Writer, nested table focus, IDE/source, and Reading, with replacement, regex, CRLF, focus return, both themes, and narrow controls.');
console.log('PASS: one full-width document Find in Writer, nested table focus, Source/source, and Reading, with replacement, regex, CRLF, focus return, both themes, and narrow controls.');
});
+1 -1
View File
@@ -45,7 +45,7 @@ await runSmoke("layout/outline", async ({ browser }) => {
await page.keyboard.press("Control+e");
await page.locator(".cm-content").waitFor();
assert.equal(await page.locator(".right").count(), 0);
console.log("PASS: hidden outline stays hidden across Writer and IDE changes");
console.log("PASS: hidden outline stays hidden across Writer and Source changes");
await page.reload();
await page.getByRole("button", { name: "Show outline", exact: true }).waitFor();
assert.equal(await page.locator(".right").count(), 0);
+9 -13
View File
@@ -1,6 +1,6 @@
// Document splits: independent modes, edits, saves, selections, and conflicts per pane; nested relative links; narrow stacking; and the close guard.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/splits", async ({ page }) => {
const output = await outputDir("layout/splits");
@@ -66,22 +66,18 @@ await runSmoke("layout/splits", async ({ page }) => {
await page.waitForFunction(()=>window.__TEST__.writes.includes('notes/b.md'));
assert.equal(await page.evaluate(()=>window.__TEST__.writes.includes('a.md')),false,'Save uses the focused right pane');
await focus('a.md'); await page.keyboard.press('Control+s'); await page.waitForFunction(()=>window.__TEST__.writes.includes('a.md'));
await pane('notes/b.md').getByRole('group',{name:'Editor layout',exact:true}).hover();
await pane('notes/b.md').getByRole('button',{name:'IDE',exact:true}).click(); await pane('notes/b.md').locator('.source-editor .cm-content').waitFor();
await chooseView(pane('notes/b.md'), 'Source'); await pane('notes/b.md').locator('.source-editor .cm-content').waitFor();
assert.equal(await pane('a.md').locator('.cm-content').count(),1,'Changing the right mode keeps the left editor');
await openRight('a.md','Right note');
assert.equal(await page.locator('.document-pane').count(),2);
await page.waitForFunction(()=>!!document.activeElement?.matches('[data-document-path="notes/b.md"] .source-editor .cm-content')); await page.keyboard.press('Control+End'); await page.keyboard.type('\nIDE edit.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.__TEST__.files.get('notes/b.md').includes('IDE edit.'));
await pane('notes/b.md').getByRole('group',{name:'Editor layout',exact:true}).hover();
await pane('notes/b.md').getByRole('button',{name:'Writer',exact:true}).click(); await pane('notes/b.md').locator('.cm-content').waitFor();
assert.match(await text('notes/b.md'),/IDE edit/);
await pane('notes/b.md').getByRole('group',{name:'Document view',exact:true}).hover();
await pane('notes/b.md').getByRole('button',{name:'Read',exact:true}).click(); await pane('notes/b.md').locator('.reading').waitFor();
await page.waitForFunction(()=>!!document.activeElement?.matches('[data-document-path="notes/b.md"] .source-editor .cm-content')); await page.keyboard.press('Control+End'); await page.keyboard.type('\nSource edit.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.__TEST__.files.get('notes/b.md').includes('Source edit.'));
await chooseView(pane('notes/b.md'), 'Write'); await pane('notes/b.md').locator('.cm-content').waitFor();
assert.match(await text('notes/b.md'),/Source edit/);
await chooseView(pane('notes/b.md'), 'Read'); await pane('notes/b.md').locator('.reading').waitFor();
assert.equal(await pane('a.md').locator('.reading').count(),0,'Reading mode belongs to its pane');
await focus('a.md'); assert.equal(await pane('notes/b.md').locator('.reading').count(),1);
await pane('notes/b.md').getByRole('group',{name:'Document view',exact:true}).hover();
await pane('notes/b.md').getByRole('button',{name:'Edit',exact:true}).click(); await pane('notes/b.md').locator('.cm-content').waitFor();
await chooseView(pane('notes/b.md'), 'Write'); await pane('notes/b.md').locator('.cm-content').waitFor();
for(const path of ['a.md','notes/b.md']) await pane(path).locator('.cm-content').evaluate(async node=> {
const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const v=EditorView.findFromDOM(node); const source=v.state.doc.toString(); const from=source.indexOf(source.includes('Alpha') ? 'Origin' : 'Second'); v.dispatch({selection:{anchor:from,head:from+6}});
});
@@ -146,5 +142,5 @@ await runSmoke("layout/splits", async ({ page }) => {
assert.match(reopened,/Close guard\./);
await focus('notes/b.md'); await page.keyboard.press('Control+z');
assert.equal(await text('notes/b.md'),reopened,'Closing the tab releases only its editor state');
console.log(JSON.stringify({passed:['independent Writer/IDE/Reading modes','dirty close cancellation and editor state release','independent edits and saves','per-pane selections','focus existing duplicate target','closing split retains unsaved tabs','nested relative link origin','per-pane conflict resolution','narrow layout and save','light/dark screenshots'],nativeDesktop:'not tested'},null,2));
console.log(JSON.stringify({passed:['independent Writer/Source/Reading modes','dirty close cancellation and editor state release','independent edits and saves','per-pane selections','focus existing duplicate target','closing split retains unsaved tabs','nested relative link origin','per-pane conflict resolution','narrow layout and save','light/dark screenshots'],nativeDesktop:'not tested'},null,2));
}, { timeout: 15000 });
+147
View File
@@ -0,0 +1,147 @@
// The view control: Write, Source, and Read always visible, the Split toggle, keys, the status bar, the breadcrumb, the file title setting, narrow panes, and both themes.
import assert from "node:assert/strict";
import { chooseView, mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/viewModes", async ({ browser }) => {
const output = await outputDir("layout/viewModes");
const context = await browser.newContext({ viewport: { width: 1200, height: 760 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({
root: "C:\\view-modes",
files: {
"notes/field-notes.md": "# Project field notes\n\nFirst paragraph with **bold** text.\n",
"top.md": "# Top\n\nRoot note.\n",
"src/hello.py": "print('hello')\n",
},
}),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
}),
});
const page = await openPage(context), settings = await openPage(context);
const group = page.getByRole("radiogroup", { name: "View", exact: true });
const radio = name => group.getByRole("radio", { name, exact: true });
const split = page.locator(".chrome-bar").getByRole("button", { name: "Split", exact: true });
const checked = () => group.getByRole("radio", { checked: true }).getAttribute("aria-label");
const status = () => page.locator(".status").innerText();
async function open(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();
}
await page.goto(smokeUrl);
await page.getByText("view-modes", { exact: true }).waitFor();
await open("field-notes.md");
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
// All choices stay visible, and the pointer does not move them.
assert.deepEqual(await group.getByRole("radio").evaluateAll(nodes => nodes.map(node => node.getAttribute("aria-label"))), ["Write", "Source", "Read"]);
assert.equal(await checked(), "Write");
assert.equal(await split.getAttribute("aria-pressed"), "false");
const boxes = () => group.getByRole("radio").evaluateAll(nodes => nodes.map(node => JSON.stringify(node.getBoundingClientRect())));
const before = await boxes();
await radio("Source").hover();
assert.deepEqual(await boxes(), before);
// Hover gets a fill. Only the current choice gets the accent bar.
const look = name => radio(name).evaluate(node => ({ fill: getComputedStyle(node).backgroundColor, bar: getComputedStyle(node).boxShadow }));
const [hovered, current] = [await look("Source"), await look("Write")];
assert.notEqual(hovered.fill, "rgba(0, 0, 0, 0)");
assert.equal(hovered.bar, "none");
assert.match(current.bar, /inset/);
assert.notEqual(hovered.fill, current.fill);
// The tab names the file, so the breadcrumb shows only its folder and the status bar shows only the view.
assert.equal(await page.locator(".breadcrumb").innerText(), "notes");
assert.equal(await page.locator(".breadcrumb").getAttribute("title"), "notes/field-notes.md");
assert.doesNotMatch(await status(), /field-notes/);
assert.match(await status(), /Write$/);
// The group has one Tab stop. Arrow keys, Home, and End move the choice.
assert.deepEqual(await group.getByRole("radio").evaluateAll(nodes => nodes.map(node => node.tabIndex)), [0, -1, -1]);
await radio("Write").focus();
await page.keyboard.press("ArrowRight");
await page.locator(".source-editor .cm-gutters").waitFor();
assert.equal(await checked(), "Source");
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Source");
assert.match(await status(), /Source$/);
await page.keyboard.press("End");
await page.locator(".md-page .reading").waitFor();
assert.equal(await checked(), "Read");
assert.match(await status(), /Read$/);
await page.keyboard.press("Home");
await page.locator(".live-writer").waitFor();
assert.equal(await checked(), "Write");
// Ctrl+Shift+E switches between Read and the editor. Ctrl+E switches between Write and Source.
await page.locator(".cm-content").click();
await page.keyboard.press("Control+Shift+E");
await page.locator(".md-page .reading").waitFor();
await page.keyboard.press("Control+Shift+E");
await page.locator(".live-writer").waitFor();
await page.keyboard.press("Control+e");
await page.locator(".source-editor").waitFor();
await page.keyboard.press("Control+e");
await page.locator(".live-writer").waitFor();
// Split shows Read beside the current editor. Write and Source keep it. Read ends it.
await chooseView(page, "Split");
assert.equal(await split.getAttribute("aria-pressed"), "true");
await page.locator(".body.split .live-writer").waitFor();
await page.locator(".body.split .md-page").waitFor();
await chooseView(page, "Source");
await page.locator(".body.split .source-editor").waitFor();
assert.equal(await split.getAttribute("aria-pressed"), "true");
await chooseView(page, "Read");
assert.equal(await split.getAttribute("aria-pressed"), "false");
assert.equal(await page.locator(".body.split").count(), 0);
assert.equal(await page.locator(".editor-wrap").isVisible(), false);
await chooseView(page, "Split");
await page.locator(".body.split .source-editor").waitFor();
assert.equal(await checked(), "Source");
await chooseView(page, "Split");
await chooseView(page, "Write");
// The file title shows by default. The General setting hides it in Write and Read.
assert.equal(await page.locator(".live-writer .document-title").count(), 1);
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("button", { name: "General", exact: true }).click();
const titleSwitch = settings.getByRole("switch", { name: "File name title", exact: true });
assert.equal(await titleSwitch.isChecked(), true);
await titleSwitch.uncheck();
await page.waitForFunction(() => !document.querySelector(".live-writer .document-title"));
await chooseView(page, "Read");
await page.locator(".md-page .reading").waitFor();
assert.equal(await page.locator(".md-page .document-title").count(), 0);
await titleSwitch.check();
await page.locator(".md-page .document-title").waitFor();
await chooseView(page, "Write");
await page.locator(".live-writer .document-title").waitFor();
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); window.dispatchEvent(new Event("focus")); }, theme);
await page.waitForFunction(mode => document.documentElement.dataset.theme === mode, theme);
await page.locator(".chrome-bar").screenshot({ path: `${output}/bar-${theme}.png` });
await chooseView(page, "Split");
await page.locator(".chrome-bar").screenshot({ path: `${output}/bar-split-${theme}.png` });
await chooseView(page, "Split");
}
// Narrow panes show only the icons. The names stay for assistive technology and tooltips.
await page.setViewportSize({ width: 700, height: 600 });
await page.waitForFunction(() => getComputedStyle(document.querySelector(".view-modes .label")).display === "none");
assert.equal(await radio("Read").getAttribute("aria-label"), "Read");
assert.ok(await page.locator(".chrome-bar").evaluate(node => node.scrollWidth <= node.clientWidth + 1));
await page.locator(".chrome-bar").screenshot({ path: `${output}/bar-narrow.png` });
await page.setViewportSize({ width: 1200, height: 760 });
// Other text files have Write and Source only. A file at the workspace root has no folder in the breadcrumb.
await open("hello.py");
assert.deepEqual(await group.getByRole("radio").evaluateAll(nodes => nodes.map(node => node.getAttribute("aria-label"))), ["Write", "Source"]);
assert.equal(await split.count(), 0);
await open("top.md");
assert.equal(await page.locator(".breadcrumb").innerText(), "");
assert.deepEqual([...page.errors, ...settings.errors], []);
console.log("PASS: visible view choices, hover and current states, radio keys, Ctrl+E and Ctrl+Shift+E, Split, status bar, breadcrumb, file title setting, narrow panes, both themes.");
});
+23 -32
View File
@@ -3,7 +3,7 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { mockTauri, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
await runSmoke("layout/workbench", async ({ page }) => {
@@ -49,16 +49,11 @@ await runSmoke("layout/workbench", async ({ page }) => {
});
await mockFeaturePlugins(page);
// Choose a mode from a compact mode switcher, such as "Editor layout" or "Document view".
async function mode(group, value) {
await page.getByRole("group", { name: group, exact: true }).hover();
await page.getByRole("button", { name: value, exact: true }).click();
}
async function quickOpen(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 mode("Editor layout", "IDE");
await chooseView(page, "Source");
await page.locator(".source-editor .cm-content").waitFor();
}
async function contents() {
@@ -94,7 +89,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
await page.keyboard.press("Control+s");
await page.waitForFunction(expected => window.__TEST__.files.get("notes/welcome.md") === expected, original + "Added in source.");
await mode("Document view", "Split");
await chooseView(page, "Split");
await page.locator(".md-page h1").first().waitFor();
assert.ok(await page.locator(".source-editor").isVisible());
await page.evaluate(() => {
@@ -142,19 +137,17 @@ await runSmoke("layout/workbench", async ({ page }) => {
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["reader-showcase.md"] });
}, showcase);
await quickOpen("reader-showcase.md");
// The Read mode is a compact switcher button; its tooltip is a decorative child (src/lib/ui/ModeSwitcher.svelte:108).
const documentView = page.getByRole("group", { name: "Document view", exact: true });
const read = documentView.locator('button[aria-label="Read"]');
const readTip = read.locator(".tooltip");
assert.equal(await read.innerText(), "");
// Each view choice shows an icon and its name. The tooltip adds the shortcut (src/lib/layout/ViewModes.svelte).
const read = page.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name: "Read", exact: true });
const readTip = page.getByRole("tooltip").filter({ hasText: "Read (Ctrl+Shift+E)" });
assert.equal(await read.innerText(), "Read");
assert.equal(await read.locator("svg").count(), 1);
await documentView.hover();
await read.hover();
await readTip.waitFor({ state: "visible" });
const tip = await readTip.boundingBox();
assert.ok(tip.x >= 0 && tip.x + tip.width <= 1440);
await read.click();
assert.equal(await read.getAttribute("aria-pressed"), "true");
assert.equal(await read.getAttribute("aria-checked"), "true");
await page.locator(".reading h1:not(.document-title)").waitFor();
assert.equal(await page.locator(".source-editor").isVisible(), false);
assert.equal(await page.locator(".reading h1:not(.document-title)").innerText(), "Project field notes");
@@ -176,7 +169,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
await page.locator(".md-page").evaluate(element => { element.scrollTop = 0; });
await page.screenshot({ path: path.join(output, "reader-narrow.png") });
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
await mode("Document view", "Split");
await chooseView(page, "Split");
await page.waitForFunction(() => {
const host = document.querySelector(".source-editor");
const rendered = host?.querySelector(".cm-editor");
@@ -190,11 +183,12 @@ await runSmoke("layout/workbench", async ({ page }) => {
await page.waitForFunction(() => getComputedStyle(document.querySelector(".body.split")).flexDirection === "row");
await page.screenshot({ path: path.join(output, "reader-split-wide.png") });
await mode("Document view", "Edit");
// A second press ends the Split view.
await chooseView(page, "Split");
await page.locator(".md-page").waitFor({ state: "detached" });
// The editor stores one line break character. The saved file keeps its own line breaks.
assert.equal(await contents(), showcase.replace(/\r\n/g, "\n"));
assert.equal(await page.evaluate(() => window.__TEST__.files.get("reader-showcase.md")), showcase);
await documentView.hover();
await read.focus();
await readTip.waitFor({ state: "visible" });
await page.keyboard.press("Escape");
@@ -208,7 +202,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["writing.md"] });
}, writingSource);
await quickOpen("writing.md");
await mode("Editor layout", "Writer");
await chooseView(page, "Write");
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.waitFor();
assert.equal(await page.locator('.live-writer [contenteditable="true"]').count(), 1);
@@ -229,14 +223,14 @@ await runSmoke("layout/workbench", async ({ page }) => {
await page.keyboard.press("Control+y");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource);
await mode("Editor layout", "IDE");
await chooseView(page, "Source");
await waitForText(editedSource);
await focusEditor();
await page.keyboard.press("Control+z");
await waitForText(writingSource);
await mode("Editor layout", "Writer");
await chooseView(page, "Write");
await writer.waitFor();
// Write keeps the caret of the IDE undo, so the paragraph can show its source.
// Write keeps the caret of the Source undo, so the paragraph can show its source.
await page.locator(".live-writer .cm-line").filter({ hasText: /A (\*\*)?formatted(\*\*)? paragraph\./ }).click();
await page.keyboard.press("End");
await page.keyboard.press("Enter");
@@ -301,7 +295,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["crlf.md"] });
});
await quickOpen("crlf.md");
await mode("Editor layout", "Writer");
await chooseView(page, "Write");
await page.locator(".live-writer .cm-line").filter({ hasText: "A paragraph." }).click();
await page.keyboard.press("Home");
await page.keyboard.type("Changed ");
@@ -354,7 +348,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
}, tableSource);
await page.setViewportSize({ width: 1440, height: 1000 });
await quickOpen("tables.md");
await mode("Editor layout", "Writer");
await chooseView(page, "Write");
const table = page.locator('.live-writer table');
await table.waitFor();
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'tables');
@@ -447,7 +441,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
await page.keyboard.press('Escape');
await page.setViewportSize({ width: 1000, height: 900 });
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
await mode('Document view', 'Read');
await chooseView(page, 'Read');
assert.equal(await page.locator('.md-page .document-title').innerText(), 'tables');
assert.equal(await page.locator('.md-page table br').count(), 5);
assert.ok(await page.locator('.md-page').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
@@ -465,8 +459,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
} });
}, selectionTable);
await quickOpen('selection-table.md');
await mode('Document view', 'Edit');
await mode('Editor layout', 'Writer');
await chooseView(page, 'Write');
const selectedTable = page.locator('.live-writer table');
const selectedCell = (r, c) => selectedTable.locator('tr').nth(r).locator('th, td').nth(c);
const fromCell = await selectedCell(1, 0).boundingBox(), toCell = await selectedCell(2, 1).boundingBox();
@@ -557,8 +550,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-actions.md'] });
}, actionsSource);
await quickOpen('table-actions.md');
await mode('Document view', 'Edit');
await mode('Editor layout', 'Writer');
await chooseView(page, 'Write');
const actionTable = page.locator('.live-writer table');
const actionCell = (r, c) => actionTable.locator('tr').nth(r).locator('th, td').nth(c);
async function actionItem(label, group, r = 1, c = 0) {
@@ -694,8 +686,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['rich-table.md'] });
}, richTable);
await quickOpen('rich-table.md');
await mode('Document view', 'Edit');
await mode('Editor layout', 'Writer');
await chooseView(page, 'Write');
const richCell = page.locator('.live-writer tbody tr').first().locator('td').last();
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'rich-table');
await richCell.click();
@@ -743,7 +734,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-hit-testing.md'] });
}, hitTestSource);
await quickOpen('table-hit-testing.md');
await mode('Editor layout', 'Writer');
await chooseView(page, 'Write');
async function clickRenderedLine(locator, expected) {
await locator.scrollIntoViewIfNeeded();
const rect = await locator.boundingBox();
+3 -3
View File
@@ -1,4 +1,4 @@
// File tree drags into Writer and the IDE: documents become escaped links, images embed, and undo restores the source.
// File tree drags into Writer and the Source: documents become escaped links, images embed, and undo restores the source.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
@@ -73,9 +73,9 @@ await runSmoke("links/fileDragLinks", async ({ page }) => {
assert.equal(await page.evaluate(() => window.dragSource.hasFocus), true);
await page.keyboard.press("Control+z");
await page.waitForFunction(expected => window.dragSource.state.doc.toString() === expected, originalIde, { timeout: 3000 });
assert.equal(await ideSource(), originalIde, "IDE undo restores the exact source");
assert.equal(await ideSource(), originalIde, "Source undo restores the exact source");
await drag("images/diagram (#1).svg", ".source-editor .cm-content");
assert.ok((await ideSource()).includes("![](../images/diagram%20%28%231%29.svg)"));
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(call => ["workspace_rename", "workspace_write_bytes"].includes(call.command)).length), 0);
console.log("PASS: IDE drags insert escaped document links and image embeds, undo restores the source, and no file moves");
console.log("PASS: Source drags insert escaped document links and image embeds, undo restores the source, and no file moves");
}, { timeout: 15000 });
+9 -11
View File
@@ -1,6 +1,6 @@
// Link context menus in the Writer, Reading, IDE, and table cells: browser and workspace actions, Edit link with undo, keyboard use, narrow windows, bookmarks, rename, and move.
// Link context menus in the Writer, Reading, Source, and table cells: browser and workspace actions, Edit link with undo, keyboard use, narrow windows, bookmarks, rename, and move.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("links/linkMenus", async ({ page }) => {
const output = await outputDir("links/linkMenus");
@@ -79,7 +79,7 @@ await runSmoke("links/linkMenus", async ({ page }) => {
await writerMenu('Workspace note'); await item('Show in system explorer').click(); await page.waitForFunction(() => window.__TEST__.revealed === 'b.md');
await writerMenu('Workspace note'); await item('Reveal file in navigation').click();
await page.waitForFunction(() => document.activeElement?.getAttribute('data-tree-rel') === 'b.md');
await page.getByRole('group', { name: 'Document view', exact: true }).hover(); await page.getByRole('button', { name:'Read', exact:true }).click();
await chooseView(page, 'Read');
const reading = page.locator('.reading');
await reading.getByText('Selected reading text.',{exact:true}).evaluate(node => { const range = document.createRange(); range.selectNodeContents(node); const s = getSelection(); s.removeAllRanges(); s.addRange(range); node.closest('.reading').focus(); });
await page.keyboard.press('Shift+F10');
@@ -105,15 +105,13 @@ await runSmoke("links/linkMenus", async ({ page }) => {
await page.setViewportSize({width:1440,height:1000});
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Show outline', exact: true }).click();
await page.getByRole('group', { name: 'Document view', exact: true }).hover();
await page.getByRole('button',{name:'Edit',exact:true}).click();
await page.getByRole('group', { name:'Editor layout',exact:true }).hover(); await page.getByRole('button',{name:'IDE',exact:true}).click();
await chooseView(page, 'Source');
await page.locator('.source-editor .cm-content').waitFor();
await page.evaluate(async () => { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const view=EditorView.findFromDOM(document.querySelector('.source-editor .cm-content')); view.dispatch({selection:{anchor:view.state.doc.toString().indexOf('Web label')+2}}); view.focus(); });
await page.keyboard.press('Shift+F10'); await item('Edit link').click();
assert.equal(await page.evaluate(async () => { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const {state}=EditorView.findFromDOM(document.querySelector('.source-editor .cm-content')); return state.sliceDoc(state.selection.main.from,state.selection.main.to); }), 'https://example.com/path');
await page.screenshot({ path: `${output}/ide-edit-url-${theme}.png` });
await page.getByRole('group', { name:'Editor layout',exact:true }).hover(); await page.getByRole('button',{name:'Writer',exact:true}).click();
await chooseView(page, 'Write');
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
const cellLink = page.locator('.writer-table a').filter({hasText:'Cell web'});
await cellLink.click({button:'right'});
@@ -156,7 +154,7 @@ await runSmoke("links/linkMenus", async ({ page }) => {
await page.setViewportSize({width:1440,height:1000});
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Show outline',exact:true}).click();
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
report.push({theme,passed:['Writer and IDE edit URL selection','browser destinations','workspace file actions','Reader copy/search/link actions','inline table web/wiki link edits and undo','table source Escape and keyboard menu','keyboard focus return','narrow viewport'],nativeDesktop:'not tested'});
report.push({theme,passed:['Writer and Source edit URL selection','browser destinations','workspace file actions','Reader copy/search/link actions','inline table web/wiki link edits and undo','table source Escape and keyboard menu','keyboard focus return','narrow viewport'],nativeDesktop:'not tested'});
}
await writerMenu('Workspace note'); await item('Open in new window').click();
await page.waitForFunction(() => window.__TEST__.windows.length === 1);
@@ -167,7 +165,7 @@ await runSmoke("links/linkMenus", async ({ page }) => {
await page.waitForFunction(() => JSON.parse(window.__TEST__.files.get('.runestone/marks.json') || '{}').bookmarks?.includes('b.md'));
await writerMenu('Workspace note'); await item('Copy path').focus(); await page.keyboard.press('ArrowRight'); await item('System path').click();
await page.waitForFunction(() => window.__TEST__.clipboard.endsWith('\\b.md'));
await page.getByRole('group', { name: 'Document view', exact: true }).hover(); await page.getByRole('button', { name:'Read', exact:true }).click();
await chooseView(page, 'Read');
const readerWorkspaceMenu = async () => { await page.locator('.reading').getByRole('link',{name:'Workspace note'}).click({button:'right'}); };
await readerWorkspaceMenu(); await item('Open in default app').click();
await page.waitForFunction(() => window.__TEST__.app === 'b.md');
@@ -175,9 +173,9 @@ await runSmoke("links/linkMenus", async ({ page }) => {
await page.getByLabel('New file name').fill('renamed.md'); await page.getByRole('button',{name:'Continue',exact:true}).click();
await page.waitForFunction(() => window.__TEST__.files.has('renamed.md') && !window.__TEST__.files.has('b.md'));
assert.equal(await page.evaluate(() => JSON.parse(window.__TEST__.files.get('.runestone/marks.json')).bookmarks.includes('renamed.md')),true);
await page.getByRole('group', { name: 'Document view', exact: true }).hover(); await page.getByRole('button', { name:'Edit', exact:true }).click();
await chooseView(page, 'Write');
await page.locator('.cm-content').evaluate(async node => { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const view=EditorView.findFromDOM(node); const from=view.state.doc.toString().indexOf('b.md'); view.dispatch({changes:{from,to:from+4,insert:'renamed.md'}}); });
await page.getByRole('group', { name: 'Document view', exact: true }).hover(); await page.getByRole('button', { name:'Read', exact:true }).click();
await chooseView(page, 'Read');
await readerWorkspaceMenu(); await item('Move file to…').click();
await page.getByLabel('Move file to (workspace path, including filename)').fill('notes/moved.md'); await page.getByRole('button',{name:'Continue',exact:true}).click();
await page.waitForFunction(() => window.__TEST__.files.has('notes/moved.md') && !window.__TEST__.files.has('renamed.md'));
+9 -14
View File
@@ -1,6 +1,6 @@
// Section links: heading anchors in the Writer, Reading, Split, and IDE views, an encoded duplicate heading in another file, a missing section, and folded headings, in both themes.
// Section links: heading anchors in the Writer, Reading, Split, and Source views, an encoded duplicate heading in another file, a missing section, and folded headings, in both themes.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("links/sectionLinks", async ({ page }) => {
const output = await outputDir("links/sectionLinks");
@@ -27,11 +27,6 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
const filler = Array.from({ length: 50 }, (_, i) => `Paragraph ${i}. Some text before the destination.\n`).join('\n');
const source = '# Install and start\n\nChoose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).\n\n[Other document](other.md#caf%C3%A9-setup-1)\n\n[Missing section](#no-such-section)\n\n' + filler + '\n## Windows installer\n\nWindows instructions.\n\n' + filler + '\n## macOS installer (Apple Silicon)\n\nMac instructions.\n\n' + filler + '\n## Linux (Intel/AMD 64-bit)\n\nLinux instructions.\n';
const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n';
async function choose(group, value) {
const control = page.getByRole('group', { name: group, exact: true });
await control.hover();
await control.locator(`[data-value="${value}"]`).click();
}
async function writerJump(label, line) {
const link = page.locator('.cm-content .writer-link').filter({ hasText: label }).first();
await link.click({ modifiers: ['Control'] });
@@ -99,24 +94,24 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
assert.equal(await page.getByRole('tab', { name:'a.md', exact:true }).count(), 1);
await page.getByRole('tab', { name:'a.md', exact:true }).click();
await top();
await choose('Document view', 'read');
await chooseView(page, 'Read');
await readerJump('Windows setup', 'Windows installer');
await page.screenshot({ path:`${output}/reading-${theme}-${width}.png` });
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('macOS setup', 'macOS installer (Apple Silicon)');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
await choose('Document view', 'split');
await chooseView(page, 'Split');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Windows setup', 'Windows installer');
await page.screenshot({ path:`${output}/split-${theme}-${width}.png` });
await choose('Document view', 'edit');
await choose('Editor layout', 'Ide');
await chooseView(page, 'Split');
await chooseView(page, 'Source');
await page.locator('.source-editor .cm-content').waitFor();
await choose('Document view', 'read');
await chooseView(page, 'Read');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
await choose('Document view', 'edit');
await chooseView(page, 'Source');
await page.waitForFunction(() => {
const node = document.querySelector('.source-editor .cm-content');
return node?.textContent.includes('Linux');
@@ -135,7 +130,7 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
await writerJump('Jump to nested', folded.slice(0, folded.indexOf('## Nested')).split('\n').length);
await top();
await writerJump('Wiki section', folded.slice(0, folded.indexOf('## Nested')).split('\n').length);
await choose('Document view', 'read');
await chooseView(page, 'Read');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await page.getByRole('button', { name:'Collapse Parent', exact:true }).last().click();
await readerJump('Jump to nested', 'Nested');
+4 -4
View File
@@ -47,7 +47,7 @@ await runSmoke("links/workspaceLinks", async ({ page }) => {
assert.equal(await page.getByRole('tab',{name:'source.md',exact:true}).count(),1);
await page.screenshot({path:path.join(output, 'workspace-links-dark.png')});
await backlink('projects/source.md').click();
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.textContent==='projects/source.md');
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.title==='projects/source.md');
const writer=page.getByRole('textbox',{name:'Writing editor',exact:true});
await writer.focus(); await page.keyboard.press('Control+Home'); await page.keyboard.press('Control+a'); await page.keyboard.type('# Source\n\nNo links now.');
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
@@ -60,7 +60,7 @@ await runSmoke("links/workspaceLinks", async ({ page }) => {
await page.waitForTimeout(350);
await openNote('other.md');
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.textContent==='archive/deep/Target.md');
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.title==='archive/deep/Target.md');
await page.evaluate(()=>{
window.__TEST__.files.set('wiki.md','# Wiki\n\n[[Target]]\n');
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'create',paths:['wiki.md']});
@@ -68,14 +68,14 @@ await runSmoke("links/workspaceLinks", async ({ page }) => {
await openNote('wiki.md');
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.locator('.status').filter({hasText:'More than one note matches Target'}).waitFor();
assert.equal(await page.locator('.breadcrumb').textContent(),'wiki.md');
assert.equal(await page.locator('.breadcrumb').getAttribute('title'),'wiki.md');
await page.evaluate(()=>{
window.__TEST__.files.delete('duplicates/Target.md');
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'remove',paths:['duplicates/Target.md']});
});
await page.waitForTimeout(350);
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.textContent==='archive/deep/Target.md');
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.title==='archive/deep/Target.md');
await backlink('wiki.md').waitFor();
await page.evaluate(()=>{
const {files,emit,root}=window.__TEST__;
+1 -1
View File
@@ -98,7 +98,7 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
await switchFor('Table formulas').check();
await closeSettings();
await page.waitForFunction(() => document.querySelector('.md-table-formula')?.textContent === '8');
await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { pressed: true }).press('ArrowRight');
await page.getByRole('radiogroup', { name: 'View', exact: true }).getByRole('radio', { checked: true }).press('End');
const preview = page.locator('.md-page table').first();
await preview.locator('.md-table-formula').waitFor();
await settings('General');
+4 -4
View File
@@ -1,7 +1,7 @@
// Table drag handles: hover and focus grips, previews, row and column moves, undo, cancellation, keyboard moves, and auto-scroll.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const source = '# Drag tables\n\n| Name | Value | Notes |\n| :--- | ---: | :---: |\n| Alpha | 10 | **Bold**<br>second line |\n| Beta | 20 | Two |\n| Gamma | 30 | Three |\n| Delta | 40 | Four |\n\nAfter.\n';
const long = '# Long table\n\n| Item | Value |\n| --- | --- |\n' + Array.from({ length: 30 }, (_, i) => `| Item ${i + 1} | ${i + 1} |`).join('\n') + '\n\nAfter.\n';
@@ -20,7 +20,7 @@ await runSmoke("tables/drag", async ({ page }) => {
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("group", { name: "Editor layout" }).locator("button.current").press("Home");
await chooseView(page, "Source");
await page.locator(".source-editor .cm-content").waitFor();
}
const table = page.locator('.live-writer table');
@@ -46,7 +46,7 @@ await runSmoke("tables/drag", async ({ page }) => {
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await quickOpen('drag.md');
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("End");
await chooseView(page, "Write");
await table.waitFor();
assert.equal(await page.locator('.table-drag-row[data-index="0"]').count(), 0);
await page.mouse.move(5, 5);
@@ -136,7 +136,7 @@ await runSmoke("tables/drag", async ({ page }) => {
// Long tables scroll the document while the pointer stays at its lower edge.
await page.setViewportSize({ width: 1440, height: 700 });
await quickOpen('long.md');
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("End");
await chooseView(page, "Write");
await table.waitFor();
await grip('row', 1);
const scroller = await page.locator('.live-writer .cm-scroller').boundingBox();
+3 -3
View File
@@ -2,7 +2,7 @@
// and the general setting that turns formulas off and on.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const source = '# Table formulas\n\n| Name | Appearance | Charisma | Combined |\n| --- | ---: | ---: | ---: |\n| First | 9 | 10 | =AVERAGE(B2:C2) |\n| Second | 7 | 9 | =SUM(B3+C3)/2 |\n| Total | | | =SUM(D2:D3) |\n\nAfter.\n';
@@ -130,7 +130,7 @@ await runSmoke("tables/formulas", async ({ page }) => {
assert.equal(await result(3, 1).innerText(), '12');
assert.equal(await result(3, 3).innerText(), '58');
for (const mode of ['Read', 'Split']) {
await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { pressed: true }).press('ArrowRight');
await chooseView(page, mode);
const preview = page.locator('.md-page table').first();
await preview.waitFor();
// Enter in the last row added an empty row below Total (src/lib/editor/tableControls.ts:285).
@@ -146,7 +146,7 @@ await runSmoke("tables/formulas", async ({ page }) => {
assert.match(await total.innerText(), /=SUM\(D2:D3\)/);
assert.match(await total.innerText(), /=SUM\(B2:B3\)/);
await shot('formulas-off-split');
await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { name: 'Edit', exact: true }).click();
await chooseView(page, 'Split');
await table.waitFor();
assert.equal(await table.locator('.md-table-formula').count(), 0);
assert.match(await cell(3, 3).innerText(), /=SUM\(D2:D3\)/);
+21 -12
View File
@@ -37,7 +37,7 @@ await runSmoke("tabs/menus", async ({ page }) => {
await show("b.md");
assert.equal(await tab("d.md").getAttribute("aria-selected"), "true");
assert.equal(await item("Rename…").count(), 0);
assert.equal(await item("Reading view").count(), 0);
assert.equal(await item("View").count(), 0);
assert.doesNotMatch(await menu().innerText(), /Alt|Shift|Ctrl/);
await page.screenshot({ path: path.join(output, "inactive.png") });
await item("Pin").click();
@@ -55,18 +55,27 @@ await runSmoke("tabs/menus", async ({ page }) => {
assert.equal(await item("Move tab left").evaluate(node => node === document.activeElement), true);
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("Escape");
// The View submenu has the same choices as the view control of the pane.
const view = async name => {
await show("d.md");
await item("View").click();
await page.getByRole(name === "Split" ? "menuitemcheckbox" : "menuitemradio", { name, exact: true }).click();
};
await show("d.md");
await item("Reading view").click();
await item("View").click();
assert.equal(await page.getByRole("menuitemradio", { name: "Write", exact: true }).getAttribute("aria-checked"), "true");
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
await view("Read");
await page.locator(".md-page").waitFor();
await show("d.md");
await item("Editing view").click();
await page.locator(".cm-editor").waitFor();
await show("d.md");
await item("Source mode").click();
await page.locator(".source-editor .cm-content").waitFor();
await show("d.md");
await item("Writing mode").click();
await page.locator(".cm-editor").waitFor();
await view("Split");
await page.locator(".body.split .md-page").waitFor();
await view("Source");
await page.locator(".body.split .source-editor .cm-content").waitFor();
await view("Split");
await page.locator(".md-page").waitFor({ state: "detached" });
await view("Write");
await page.locator(".live-writer .cm-editor").waitFor();
await show("d.md");
await item("Copy path").click();
await item("Workspace path").click();
@@ -115,6 +124,6 @@ await runSmoke("tabs/menus", async ({ page }) => {
await added.click({ button: "right" });
await menu().waitFor();
assert.equal(await item("Rename…").count(), 0);
assert.equal(await item("Reading view").count(), 0);
assert.equal(await item("View").count(), 0);
await page.keyboard.press("Escape");
}, { timeout: 15000 });
+9 -16
View File
@@ -1,6 +1,6 @@
// Each tab keeps its own scroll position in the Writing, Reading, Split, and IDE layouts.
// Each tab keeps its own scroll position in the Writing, Reading, Split, and Source layouts.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, settle as settleFrames, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, runSmoke, settle as settleFrames, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tabs/scroll", async ({ page }) => {
await mockTauri(page, {
@@ -57,27 +57,20 @@ await runSmoke("tabs/scroll", async ({ page }) => {
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
}
// The view and layout switchers show only the current mode until hovered (src/lib/ui/ModeSwitcher.svelte:92, :153).
async function mode(group, name) {
const switcher = page.getByRole('group', { name: group, exact: true });
await switcher.hover();
await switcher.getByRole('button', { name, exact: true }).click();
}
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await open('scroll-b.md');
await open('scroll-a.md');
await mode('Editor layout', 'Writer');
await chooseView(page, 'Write');
await roundTrip('.cm-scroller', 'Writing');
await mode('Document view', 'Read');
await chooseView(page, 'Read');
await roundTrip('.md-page', 'Reading');
await mode('Document view', 'Split');
await chooseView(page, 'Split');
await roundTrip('.md-page', 'Split preview');
await mode('Document view', 'Edit');
await mode('Editor layout', 'IDE');
await chooseView(page, 'Split');
await chooseView(page, 'Source');
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
await mode('Editor layout', 'IDE');
await chooseView(page, 'Source');
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
await roundTrip('.source-editor .cm-scroller', 'IDE');
await roundTrip('.source-editor .cm-scroller', 'Source');
});
+1 -1
View File
@@ -47,7 +47,7 @@ await runSmoke("tree/renameTitle", async ({ page }) => {
await title.waitFor();
}
async function editTitle(value) { await title.click(); await input.fill(value); }
const renamed = name => page.waitForFunction(expected => document.querySelector(".breadcrumb")?.textContent === expected, name);
const renamed = name => page.waitForFunction(expected => document.querySelector(".breadcrumb")?.title === expected, name);
try {
await page.goto(smokeUrl);
+1 -1
View File
@@ -39,7 +39,7 @@ await runSmoke("workspace/session", async ({ page }) => {
await title.click();
await page.getByRole("textbox", { name: "Note filename", exact: true }).fill("renamed");
await page.keyboard.press("Enter");
await page.waitForFunction(() => document.querySelector(".breadcrumb")?.textContent === "notes/renamed.md");
await page.waitForFunction(() => document.querySelector(".breadcrumb")?.title === "notes/renamed.md");
await page.waitForFunction(() => window.__TEST__.files.get(".runestone/marks.json").includes("notes/renamed.md"));
assert.deepEqual(await marks(), { pins: ["notes/renamed.md"], bookmarks: ["notes/renamed.md"], order: {} }, "A title rename moves the pin and the bookmark");
await tree.getByText("renamed", { exact: true }).waitFor();
+17 -1
View File
@@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane } from "../../../src/lib/workspace/documentPanes.ts";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView } from "../../../src/lib/workspace/documentPanes.ts";
import { paneBounds } from "../../../src/lib/workspace/splitLayout.ts";
import { registerSelection, selectedEditorText } from "../../../src/lib/editor/selection.ts";
@@ -20,6 +20,22 @@ test("opening a link to the right keeps its source and focuses an existing pane
assert.equal(paneBounds(state.layout).third.left, 75);
});
test("Read and Split exclude each other, and a closed document resets both", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b"], "a");
const pane = state.active;
state = splitDocumentView(state, pane, true);
assert.deepEqual([state.panes[0].reading, state.panes[0].split], [false, true]);
state = readDocumentPane(state, pane, true);
assert.deepEqual([state.panes[0].reading, state.panes[0].split], [true, false]);
state = splitDocumentView(state, pane, true);
assert.deepEqual([state.panes[0].reading, state.panes[0].split], [false, true]);
// Write and Source keep the Split view.
state = readDocumentPane(state, pane, false);
assert.equal(state.panes[0].split, true);
state = syncDocumentPanes(state, ["b"], "b");
assert.deepEqual([state.panes[0].documentId, state.panes[0].reading, state.panes[0].split], ["b", false, false]);
});
test("closing a split preserves the remaining pane and a later tab selection can restore its hidden document", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b"], "a");
state = splitDocumentPane(state, state.active, "b", "right");
+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 });
assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds, showInternalFolder: false })), { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true, showFileTitle: true });
}
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10, showInternalFolder: false, tableFormulas: true });
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10, showInternalFolder: false, tableFormulas: true, showFileTitle: true });
});
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 };
const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false, tableFormulas: autosaveSeconds !== 23, showFileTitle: autosaveSeconds !== 300 };
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 }));
assert.throws(() => saveSettings({ autosaveEnabled: true, autosaveSeconds, showInternalFolder: false, tableFormulas: true, showFileTitle: true }));
}
});
assert.equal(writes, 0);
@@ -45,7 +45,9 @@ 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 });
assert.deepEqual(normalizeSettings({ autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true }), { autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true, tableFormulas: true, showFileTitle: true });
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);
});
+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 },
general: { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true, showFileTitle: true },
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 },
general: { autosaveEnabled: true, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true, showFileTitle: true },
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 });
assert.deepEqual(store.readSection('general'), { autosaveEnabled: true, autosaveSeconds: 12, showInternalFolder: false, tableFormulas: true, showFileTitle: true });
assert.equal(legacy.get('runestone.language'), 'ja', 'The old value stays in place');
assert.equal(store.takeSettingsNotice(), 'Notice once');
assert.equal(store.takeSettingsNotice(), null);
+4 -4
View File
@@ -8,9 +8,9 @@ test("markdown files open in writing chrome", () => {
});
test("scripts open in ide chrome", () => {
assert.equal(detectChrome("src/hello.py"), "Ide");
assert.equal(detectChrome("tools/setup.sh"), "Ide");
assert.equal(detectChrome("Makefile"), "Ide");
assert.equal(detectChrome("src/hello.py"), "Source");
assert.equal(detectChrome("tools/setup.sh"), "Source");
assert.equal(detectChrome("Makefile"), "Source");
});
test("writing chrome wraps and hides the code gutters", () => {
@@ -18,7 +18,7 @@ test("writing chrome wraps and hides the code gutters", () => {
});
test("ide chrome shows the code gutters and does not wrap", () => {
assert.deepEqual(chromeLayout("Ide"), { wrap: false, gutters: true, activeLine: true });
assert.deepEqual(chromeLayout("Source"), { wrap: false, gutters: true, activeLine: true });
});
test("extensionOf reads the last suffix", () => {
+2 -2
View File
@@ -63,7 +63,7 @@ test("tab moves preserve selection, dirty buffers, and in-flight saves", async (
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "my edits");
docs.setChrome("Ide");
docs.setChrome("Source");
await docs.open(entry("script.py"));
docs.newTab();
const blank = docs.active!;
@@ -78,7 +78,7 @@ test("tab moves preserve selection, dirty buffers, and in-flight saves", async (
assert.equal(docs.buffers[2], note);
assert.equal(note.contents, "my edits");
assert.equal(note.saved, "original");
assert.equal(note.chromeOverride, "Ide");
assert.equal(note.chromeOverride, "Source");
docs.move(blank.relPath, 0);
assert.equal(docs.active, blank);
gate.resolve();