Update editor, themes, menus, backgrounds, and release tooling

This commit is contained in:
Knotty Wyvern
2026-10-14 16:19:51 -07:00
parent f6eaa52949
commit edef2520af
113 changed files with 5722 additions and 386 deletions
+1
View File
@@ -25,3 +25,4 @@ output/browser-test.conf.json
/.runestone/
/output/
/releases/
+37 -1
View File
@@ -169,7 +169,7 @@ Read priority from the separate `runestone_pm.priority` detail field, never from
## UI work: keep attention on the work
Use the principles in [Interface design](docs/ui-design.md#design-principles) for all interface work.
Use quiet active states. Reserve strong borders and accents for controls that need attention.
Keep active states clear and the structure focused. Use strong colors for theme identity, status, and actions that need attention.
Show board and view names once where possible. Keep switching and renaming as separate actions.
Use familiar icons and visual previews. Keep labels when they prevent ambiguity.
Keep accessible names, keyboard focus, and tooltips on icon controls.
@@ -192,3 +192,39 @@ Use the [design decision log](docs/design-decisions.md) for rule changes, recurr
- Before moving UI work to Review, include the evidence required by the guide.
Identify the shared component or token, check local overrides, and record any gaps in checks.
Check design principles as well as styling. Keep unresolved work In progress and reserve Done for the user's acceptance.
## Release directory
Keep all completed release files in `releases/` at this project root.
RuneStone installers use `releases/<version>/`. Each plugin keeps its ZIPs directly in its own `releases/` folder.
Keep release notes, checksums, and build metadata with the release they describe.
Never copy plugin ZIPs into the host project or another plugin project.
Use `dist/`, `build/`, `output/`, and toolchain folders only for compilation, staging, logs, or checks.
Move completed installers from the toolchain bundle folder into `releases/` after packaging.
Do not leave a second installer copy in the bundle folder.
Do not overwrite a release with different contents. Remove duplicates only after their SHA-256 hashes match.
Keep distinct versions and files with different contents. Report filename conflicts before changing them.
Keep `releases/` outside Git. Report the full artifact path after each completed build.
This rule applies to the main app, all existing plugins, and all new plugins.
## UI work: assertive color and complete menu coverage
Use the global `ui-functional-color` skill for UI work. Read [Functional color requirements](docs/ui-color.md) before choosing or reviewing UI colors.
Start with vivid candidates for accents, priority, status, selection outlines, syntax, and important data.
Prefer the stronger candidate when readability, meaning, and distinction remain sound. Treat full saturation and full HSV value as normal options.
Do not soften colors solely for quiet, refined, professional, premium, minimal, or cohesive styling.
Require a concrete reason and before/after evidence for a softer choice.
Keep informative text and symbols opaque. Use shared tokens and check the actual composite surface.
The guide applies to human developers and agents. Existing muted values do not establish an approved soft design requirement.
Searchable pickers can contain search, descriptions, and forms. Their panels and result rows use the shared menu presentation.
Use `rs-picker`, `rs-picker-row`, `rs-picker-icon`, and `rs-picker-hint` from `src/lib/ui/menu.css`.
Keep their different layout and semantics. Do not use the richer layout allowance to override panel color, row padding, font, or focus states.
Use the shared action menu for native select replacements whenever the host API exists.
Native selects remain only as documented fallbacks for older plugin hosts. Embedded website controls retain the website design.
Run `node scripts/menuSurfaceAudit.mjs` before menu work moves to Review.
The inventory covers menu renderers, callers, native selects, and searchable pickers across the host and sibling plugins.
An added or changed menu entry point requires inventory review. Source coverage does not prove runtime compliance.
Run the listed browser checks for affected surfaces and retain screenshots of the exact reported control.
A neighboring selector does not satisfy a card. Check every control shown in its screenshots.
+1 -12
View File
@@ -1,14 +1,3 @@
---
runestone_pm:
schema: 1
id: 66c0769c-c13e-417d-826e-4ae112dc6f55
kind: task
status: todo
tags: []
sessions: []
archived: true
placements: {}
---
# RuneStone
A desktop workspace for notes, code, and project work stored in ordinary local files.
@@ -49,7 +38,7 @@ Keep workspace folders outside the application folder.
| --- | --- |
| Edit documents, manage tabs, or resolve a save conflict | [User guide](docs/user-guide.md) |
| Change colors or install a theme | [Appearance guide](docs/guides/themes.md) |
| Install or remove an optional plugin | [Plugin installation](docs/plugins.md#install-a-plugin) |
| Install or remove an optional plugin | [Plugin installation](<docs/plugins.md#install-a-plugin>) |
| Fix setup or launch problems | [Installation help](docs/installation.md#setup-help) |
| Understand future work | [Roadmap](docs/roadmap.md) |
@@ -0,0 +1,92 @@
import { nativeRequest } from './native-support.mjs';
import { chromium } from 'playwright';
import { spawn, execFileSync } from 'node:child_process';
import { mkdir } from 'node:fs/promises';
import { resolve, basename, dirname } from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
const host = resolve(process.env.RUNESTONE_ROOT || '..');
const portServer = net.createServer();
await new Promise(resolve => portServer.listen(0, '127.0.0.1', resolve));
const port = portServer.address().port;
await new Promise(resolve => portServer.close(resolve));
const native = spawn(resolve(host, 'src-tauri/target/debug/runestone.exe'), [], { windowsHide: true, stdio: 'ignore',
env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}` } });
let browser, page;
try {
for (let attempt = 0; attempt < 60; attempt++) {
try { browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`); break; }
catch { await new Promise(resolve => setTimeout(resolve, 500)); }
}
if (!browser) throw Error('The isolated host did not start.');
page = browser.contexts()[0].pages()[0];
await page.waitForFunction(() => !!window.__TAURI_INTERNALS__?.invoke);
const invoke = (command, args = {}) => nativeRequest(page, command, args);
const snapshot = await invoke('plugins_snapshot');
assert.equal(basename(snapshot.root), 'plugins');
assert.equal(basename(dirname(snapshot.root)), 'com.runestone.browser-test', 'The test must use its isolated profile.');
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await page.locator('[data-browser-state="ready"]').waitFor();
const address = page.getByRole('textbox', { name: 'Address or search', exact: true });
const fixture = '<html><body><input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><textarea id="other" style="position:absolute;left:40px;top:140px;width:300px;height:80px"></textarea><div id="rich" contenteditable="true" style="position:absolute;left:40px;top:280px;width:300px;height:80px;border:1px solid">Rich text</div></body></html>';
await address.fill(`https://httpbin.org/base64/${Buffer.from(fixture).toString('base64')}`);
await address.press('Enter');
await page.waitForTimeout(2500);
await mkdir(resolve(host, '.audit/browser-fields-native'), { recursive: true });
await page.screenshot({ path: resolve(host, '.audit/browser-fields-native/before-input.png') });
const surface = page.getByRole('application', { name: 'Web page', exact: true });
const box = await surface.boundingBox();
await page.mouse.click(box.x + 100, box.y + 60);
const expectCaret = () => page.waitForFunction(() => {
const image = document.querySelector('.surface img');
if (!image?.complete || !image.naturalWidth) return false;
const ratio = image.naturalWidth / document.querySelector('.surface').clientWidth;
const canvas = document.createElement('canvas'); canvas.width = 12; canvas.height = 28;
const context = canvas.getContext('2d');
context.drawImage(image, 42 * ratio, 46 * ratio, 12 * ratio, 28 * ratio, 0, 0, 12, 28);
const pixels = context.getImageData(0, 0, 12, 28).data;
let dark = 0;
for (let offset = 0; offset < pixels.length; offset += 4) if (pixels[offset] < 100 && pixels[offset + 1] < 100 && pixels[offset + 2] < 100) dark++;
return dark >= 8;
}, null, { timeout: 5000, polling: 50 });
await expectCaret();
await page.screenshot({ path: resolve(host, '.audit/browser-fields-native/visible-caret.png') });
const clipboard = () => execFileSync('powershell.exe', ['-NoProfile', '-Command', 'Get-Clipboard -Raw'], { encoding: 'utf8', windowsHide: true }).trim();
for (const [name, y, value] of [['input', 60, 'RuneStone input'], ['textarea', 170, 'RuneStone textarea'], ['contenteditable', 310, 'RuneStone rich text']]) {
await page.mouse.click(box.x + 100, box.y + y);
const focused = await page.evaluate(() => document.activeElement?.getAttribute('aria-label'));
assert.equal(focused, 'Web page text input', 'The native host keeps its input bridge focused.');
await page.keyboard.press('Control+a');
await page.keyboard.type(value);
await page.waitForTimeout(800);
await page.keyboard.press('Control+a');
await page.keyboard.press('Control+c');
await page.waitForTimeout(300);
await page.screenshot({ path: resolve(host, `.audit/browser-fields-native/${name}.png`) });
assert.equal(clipboard(), value, `The native ${name} accepts text and selection.`);
console.log(`PASS: native ${name} accepts focus, typing and selection`);
}
for (const mode of ['dark', 'light']) {
await page.evaluate(mode => {
localStorage.setItem('runestone.appearance', JSON.stringify({ theme: 'default', mode }));
window.dispatchEvent(new StorageEvent('storage', { key: 'runestone.appearance' }));
}, mode);
await page.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
await page.setViewportSize({ width: 880, height: 650 });
await page.waitForTimeout(500);
const narrowBox = await surface.boundingBox();
await page.mouse.click(narrowBox.x + 60, narrowBox.y + 60);
await page.keyboard.press('Control+a');
await page.keyboard.press('Backspace');
await expectCaret();
await page.screenshot();
await page.waitForTimeout(100);
await page.screenshot({ path: resolve(host, `.audit/browser-fields-native/caret-${mode}-880.png`) });
}
console.log('PASS: native caret pixels in dark and light appearances at 880px');
} finally {
if (page) await nativeRequest(page, 'browser_stop').catch(() => {});
await browser?.close(); native.kill();
}
+33 -6
View File
@@ -18,6 +18,27 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
const runtimeId = randomUUID();
let revision = 0;
const tab = id => { const found = tabs.get(id); if (!found) throw new Error('Unknown browser tab.'); return found; };
const pageFocusStates = new WeakMap();
async function focusPage(wc, enabled) {
// Hidden offscreen windows cannot gain native focus. Chromium still needs it to paint the caret.
if (!wc.debugger.isAttached()) {
if (!enabled) return;
wc.debugger.attach('1.3');
pageFocusStates.delete(wc);
}
if (pageFocusStates.get(wc) === enabled) return;
await wc.debugger.sendCommand('Emulation.setFocusEmulationEnabled', { enabled });
pageFocusStates.set(wc, enabled);
if (enabled) wc.focus();
}
function emulateViewport(item) {
if (!item.viewport) return;
const { width, height } = item.viewport, scale = item.scale;
item.view.setContentSize(Math.round(width * scale), Math.round(height * scale));
item.view.webContents.enableDeviceEmulation({ screenPosition: 'desktop', screenSize: { width, height },
deviceScaleFactor: scale, viewPosition: { x: 0, y: 0 }, viewSize: { width, height }, scale });
item.view.webContents.invalidate();
}
const agent = new AgentController(tab);
const snapshot = () => ({
runtimeId, revision: ++revision,
@@ -134,6 +155,7 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
});
wc.on('destroyed', () => { item.iconRequest?.abort(); clearTimeout(item.settle); clearTimeout(item.retryFrame); });
wc.on('did-stop-loading', () => { changed(); void cosmetics(item); });
wc.on('did-finish-load', () => emulateViewport(item));
wc.on('did-fail-load', (_event, code, _description, _url, main) => { if (main && code !== -3) emit({ event: 'error', tabId: item.id, message: `Page load failed (${code}).` }); });
wc.on('paint', (_event, _dirty, image) => {
item.latestImage = image;
@@ -196,15 +218,20 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
const scale = Number(args.scale ?? 1);
if (!Number.isFinite(scale) || scale < 1 || scale > 3) throw new Error('Invalid browser scale.');
current.scale = scale;
current.view.setContentSize(Math.round(args.width * scale), Math.round(args.height * scale));
current.view.webContents.enableDeviceEmulation({ screenPosition: 'desktop', screenSize: { width: args.width, height: args.height },
deviceScaleFactor: scale, viewPosition: { x: 0, y: 0 }, viewSize: { width: args.width, height: args.height }, scale });
current.viewport = { width: args.width, height: args.height };
emulateViewport(current);
current.delivery.clear(); current.view.webContents.invalidate(); return null;
}
case 'visible': { const item = tab(args.tabId), wc = item.view.webContents; item.delivery.clear(); if (args.visible === true) { wc.startPainting(); wc.invalidate(); } else { wc.stopPainting(); clearTimeout(item.settle); clearTimeout(item.retryFrame); } return null; }
case 'visible': { const item = tab(args.tabId), wc = item.view.webContents; item.delivery.clear(); if (args.visible === true) { wc.startPainting(); wc.invalidate(); } else { await focusPage(wc, false); wc.stopPainting(); clearTimeout(item.settle); clearTimeout(item.retryFrame); } return null; }
case 'focus': {
if (typeof args.focused !== 'boolean') throw new Error('Invalid browser focus.');
await focusPage(tab(args.tabId).view.webContents, args.focused); return null;
}
case 'insertText': {
if (typeof args.text !== 'string' || args.text.length > 100000) throw new Error('Invalid browser text.');
await tab(args.tabId).view.webContents.insertText(args.text); return null;
const wc = tab(args.tabId).view.webContents;
await focusPage(wc, true);
await wc.insertText(args.text); return null;
}
case 'edit': {
const wc = tab(args.tabId).view.webContents;
@@ -244,7 +271,7 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
event = { type: input.type, keyCode: input.keyCode, modifiers };
}
// Pointer motion and wheel events must not repeatedly activate the native window.
if (input.type === 'mouseDown' || input.type === 'keyDown' || input.type === 'char') wc.focus();
if (input.type === 'mouseDown' || input.type === 'keyDown' || input.type === 'char') await focusPage(wc, true);
wc.sendInputEvent(event); return null;
}
case 'createProfile': store.createProfile(args.name); break;
+14
View File
@@ -90,6 +90,20 @@ app.whenReady().then(async () => {
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 50, y: 35, button: 'left' } });
await engine.command('input', { tabId: first, input: { type: 'char', keyCode: 'x' } });
await until(async () => await wc.executeJavaScript("document.querySelector('input').value") === 'x');
assert.equal(await wc.executeJavaScript('document.hasFocus()'), true);
await engine.command('focus', { tabId: first, focused: false });
assert.equal(await wc.executeJavaScript('document.hasFocus()'), false);
await engine.command('focus', { tabId: first, focused: true });
assert.equal(await wc.executeJavaScript('document.hasFocus()'), true);
wc.debugger.detach();
await engine.command('focus', { tabId: first, focused: true });
assert.equal(await wc.executeJavaScript('document.hasFocus()'), true);
await engine.command('visible', { tabId: first, visible: false });
assert.equal(await wc.executeJavaScript('document.hasFocus()'), false);
await engine.command('visible', { tabId: first, visible: true });
await engine.command('focus', { tabId: first, focused: true });
await assert.rejects(engine.command('focus', { tabId: first, focused: 'true' }), /Invalid browser focus/);
passed.push('offscreen focus supports the caret, blur, hidden tabs, and debugger reattachment');
passed.push('offscreen frames and forwarded pointer and keyboard input work');
await engine.command('insertText', { tabId: first, text: '日本語 🙂' });
await until(async () => (await wc.executeJavaScript("document.querySelector('input').value")).endsWith('日本語 🙂'));
+3 -1
View File
@@ -21,11 +21,13 @@ The first build needs internet access to download the packaging tools and the We
Find the installer in:
```text
src-tauri/target/release/bundle/nsis/RuneStone_<version>_x64-setup.exe
releases/<version>/RuneStone_<version>_x64-setup.exe
```
Distribute this setup file. Users do not need the repository, a local server, or build tools.
Build output stays outside version control.
The build moves the completed installer into `releases/<version>/` with its `host.json` metadata.
The toolchain bundle folder does not retain a second installer copy.
## Installer settings
+338 -2
View File
@@ -177,16 +177,41 @@ Entry status describes the record. It does not move a Kanban card to Done or rep
- Type: Recurring problem
- Date: 2026-10-12
- Status: Resolved
- Status: Implemented for user review
- Existing rule: Shared action menus in the interface guide.
- Scope: Browser settings and Project Management card, priority, background, and list-status controls.
- Scope: Browser settings and Project Management card, priority, background, and list-status controls. Scope also includes BG Slideshow settings menus.
- Occurrences: Cards 41461dfe and 1d823866 follow earlier menu corrections in UI-002 and UI-003. Card b8cc5ef1 repeats the issue in background and list-status choices.
- Occurrence: Card f6baf300 repeats the menu problem in a modal Settings dialog.
- Cause: Browser settings used native selects. PM card and priority controls used local popup renderers. Background and list-status choices missed the shared-choice conversion.
- Modal cause: BG Slideshow passed no dialog parent to the shared menu. The menu opened outside the modal and could not receive input.
- Correction: Use the shared menu API for these controls. Match the host background labels and retain the numeric overlay field.
- Modal correction: Pass the nearest dialog as the menu parent.
- Prevention: Check each background choice and the list-status choice with the real host menu API, in both themes and narrow layouts.
- Modal prevention: Run the settings harness with showModal to catch blocked pointer and keyboard input.
- Check: The current host and PM check reports record the results.
- Evidence: output/round4-pm-report.json, output/round4-editor-menu-report.json, and output/round4-overlay-report.json.
- Modal evidence: RuneStone_BG_Slideshow/tests/artifacts/settings and the card review notes.
- Resolution: The combined checks passed on 2026-10-12. Reopen this entry if the problem returns.
- Editor occurrence: Cards e7edc2ca and e6dfcb06 report different menus over words, blank space, and IDE content.
- Editor cause: Writer opened its spelling-only menu over words. Code files retained the default Monaco menu.
- Editor correction: Combine spelling suggestions with Markdown actions. Route code actions through the shared menu.
- Editor prevention: Compare word, blank-space, Markdown IDE, and code IDE menus in both themes with keyboard dismissal.
- Editor evidence: `.audit/editor-surfaces` and the shared menu smoke report accompany the card review.
- Relationship occurrence: Card 2f5052e8-965d-4f12-8010-befdd87fa2e9 repeats the menu problem in linked-card Relationship choices.
- Relationship cause: createRelations did not receive the existing shared-choice adapter.
- Relationship correction: Pass useSharedChoices to createRelations and apply it to the Relationship selector.
- Relationship prevention: Test the card relationship selector with the real host menu API, both themes, narrow windows, and keyboard focus.
- Relationship evidence: RuneStone_ProjectManagement/tests/relations-menu.spec.ts and .audit/linked-card-relationship screenshots.
- Reopened on 2026-10-13: cards 2f5052e8 and 048353f7.
The linked-card card returned to To Do because the earlier fix changed Relationship but left Card to link as a native select.
The move-to-board card exposed the same missing adapter in the destination form.
The earlier checks covered the relationship selector only. Rich-picker exemptions also allowed independent visual styles.
The correction applies the adapter to all short PM choices and shares presentation with searchable pickers.
Browser, Terminal, Local Autocomplete, and Slideshow choices form part of the same source audit.
Keyboard focus now scrolls only the menu panel. It cannot dismiss a menu by scrolling its parent dialog.
### UI-008 — Keep native editing menus focused
@@ -204,3 +229,314 @@ Entry status describes the record. It does not move a Kanban card to Done or rep
- Evidence: Native payloads and two full smoke runs in output/todo-menus.
- Replaces: None.
### UI-009 — Character theme appearances
- Type: Rule change
- Date: 2026-10-12
- Status: Implemented for user review
- Decision source: Card 7421c542 requests stronger character colors, syntax colors, and one suitable appearance per character.
- Previous rule: Character themes offered separate light and dark appearances with mostly surface colors.
- New rule: Each character uses one appearance with distinct text, accent, and syntax colors. Asuka also offers a school uniform palette.
- Reason: Reflect the character through hair, eyes, clothing, and readable code colors.
- Scope: Character palettes, the theme picker, preview, export, import, and IDE syntax colors.
- Shared implementation: characterThemes.ts, appearance.ts, syntax tokens, and Monaco theme rules.
- Exceptions: None.
- Evidence: Character theme smoke checks passed all five palettes. Contrast checks passed for text and syntax. Screenshots remain in .audit/character-themes.
- Limits: Native desktop checks remain untested.
- Replaces: None.
- Replaced by: UI-012 changes the palette selection. Fixed appearances and syntax rules remain.
### UI-010 — Background surface visibility
- Type: Rule change
- Date: 2026-10-12
- Status: Implemented for user review
- Decision source: Card f0250163 requests transparent new-tab buttons, board lists, and cards.
- Previous rule: New-tab buttons used opaque surfaces. Board lists used a nearly opaque surface, and cards used opaque surfaces.
- New rule: New-tab controls use shared image control tokens. Board lists and unselected cards use modest transparency when an image is active.
- Reason: Keep the image visible while labels and selections remain clear.
- Scope: New-tab buttons and Project Management lists and cards with images.
- Shared implementation: --rs-image-control-bg, --rs-image-control-hover-bg, EditorPane.svelte, and existing PM background styles.
- Exceptions: Selected cards retain the shared selection treatment.
- Evidence: Background browser checks passed both themes and narrow layouts. Screenshots remain in .audit/background-frames and RuneStone_ProjectManagement/.audit/pm-background-*.
- Limits: Native desktop interaction remains untested.
- Replaces: None.
- Replaced by: UI-011 extends the app image across the work area. Control and card rules remain.
- Replaced by: UI-014 changes Project Management surfaces and host image inheritance.
### UI-011 — Backgrounds across the work area
- Type: Rule change
- Date: 2026-10-12
- Status: Implemented for user review
- Decision source: Cards 0fbf1d44, 17cd5ff2, and 3c610e21.
- Previous rule: The app image appeared only behind the new-tab screen. Sidebars and editors used opaque surfaces.
- New rule: One background spans the work area below the titlebar. Sidebars use an 82% tint. Editors use a 90% tint.
- Reason: Show a continuous image while text and controls remain readable.
- Scope: New tabs, sidebars, Writer, Reading, split views, and IDE.
- Shared implementation: Workbench background layer and --rs-image-sidebar-bg, --rs-image-editor-bg, and --rs-workarea-* tokens.
- Splash controls: Keep buttons, icons, labels, and shortcuts. Remove headings, descriptions, and hint text. Button tint matches Project Management lists.
- Exceptions: Headers, menus, dialogs, and embedded plugin views retain their own surfaces.
- Evidence: Background and appearance browser reports and screenshots accompany the card review.
- Limits: Native desktop appearance and distraction levels require user review.
- Replaces: The new-tab-only scope of UI-010. Its control and card rules remain.
- Replaced by: UI-013 adds menu transparency. UI-014 lets Project Management share the host background.
### UI-012 — Retain three stronger character themes
- Type: Rule change
- Date: 2026-10-12
- Status: Implemented for user review
- Decision source: Card 541c87e6.
- Previous rule: Five character palettes included Renamon and Asuka School Uniform.
- New rule: Retain Holo, Asuka, and Malfoid with stronger identity colors. Remove Renamon and Asuka School Uniform.
- Reason: Reduce unused choices and replace soft colors with recognizable clothing, hair, and eye colors.
- Scope: Theme registry, appearance selection, syntax colors, saved settings, and export.
- Shared implementation: characterThemes.ts, appearance.ts, the shared theme picker, and Monaco theme rules.
- Migration: Removed themes return to RuneStone while their saved mode and background remain.
- Evidence: Palette contrast checks and character browser checks. Screenshots remain in .audit/character-themes.
- Limits: Native desktop appearance requires user review.
- Replaces: The palette selection rule in UI-009. Its fixed appearance and syntax rules remain.
### UI-013 — Translucent menu surfaces
- Type: Rule change
- Date: 2026-10-12
- Status: Implemented for user review
- Decision source: Card e3c5261f requests transparency across menus.
- Previous rule: Menus used opaque elevated surfaces.
- New rule: Shared menus use an 82% theme tint, including hover and active rows.
- Reason: Keep background images visible while menu labels remain readable.
- Scope: Host action menus, submenus, plugin menus through the host API, and the workspace picker.
- Shared implementation: `menu.css`, `--rs-menu-bg`, and `--rs-menu-active-bg`.
- Exceptions: Native system menus retain platform presentation. Rich dialogs retain their own surfaces.
- Evidence: Menu smoke checks pass both themes, keyboard navigation, disabled rows, focus return, submenus, and viewport edges.
- Screenshots: `.audit/menu-file-light.png`, `.audit/menu-file-dark.png`, and `.audit/menu-edge.png`.
- Limits: Native desktop appearance requires user review.
- Replaces: The opaque menu exception in UI-011.
### UI-014 — Readable Project Management surfaces
- Type: Rule change
- Date: 2026-10-12
- Status: Implemented for user review
- Decision source: Cards ed544871, c290007f, 312ee71d, 399f6818, and 6e1b418d.
- Previous rule: Project Management retained an opaque root. Cards and fields used different tints. Gantt and calendar lacked a shared readable panel.
- New rule: Project Management shows one host image unless a board supplies its own image. Related surfaces share an 82% tint.
- Reason: Show the image once and keep tasks, dates, details, and search text readable.
- Scope: Project Management backgrounds, lists, cards, details, fields, Gantt, and calendar.
- Shared implementation: Host work-area tokens and Project Management surface tokens.
- Exceptions: Selected cards retain the shared selection treatment.
- Evidence: Unit, clipping, keyboard, background, and surface browser checks accompany the card review.
- Limits: Native desktop appearance requires user review.
- Replaces: The Project Management surface scope of UI-010 and the opaque plugin exception in UI-011.
- Background recurrence: Card ed544871 returned to To Do on 2026-10-13 with left and right sidebar examples.
- Background cause: Slideshow published the same frame to the app and boards. Each renderer scaled that image to a different area.
- Background correction: Compare app and board frames, including appearance and transitions. Matching frames use only the host layer.
- Background prevention: Publish matching frames to app and boards in the host integration test. Check both sidebars and narrow layouts.
- Background evidence: `.audit/host-pm-matching-slideshow-*.png` in the Project Management checkout and transient frame tests.
### UI-015 — Slower slideshow fades
- Type: Rule change
- Date: 2026-10-12
- Status: Implemented for user review
- Decision source: Card 9ae11a7a reports that fades are too fast.
- Previous rule: Images faded for 800 milliseconds.
- New rule: Images fade for two seconds. Reduced motion removes the animation.
- Reason: Give the image change a slower visual pace.
- Scope: App and Project Management slideshow frames.
- Shared implementation: Background Slideshow `transitionMs`, host BackgroundHub, and Project Management frame rendering.
- Exceptions: Manual Next and image intervals below two seconds can interrupt a fade.
- Evidence: All 11 slideshow unit tests, TypeScript checks, and the settings browser check pass.
- Limits: Native desktop appearance requires user review.
- Replaces: The 800-millisecond fade rule in the interface guide.
### UI-016 — Translucent code blocks
- Type: Rule change
- Date: 2026-10-13
- Status: Implemented for user review
- Decision source: Card ea3ab6df requests transparent code blocks.
- Previous rule: Fenced code blocks used opaque elevated surfaces.
- New rule: Writer and Reading code blocks share an 82% elevated tint.
- Reason: Keep the image visible through code blocks while code text remains readable.
- Scope: Fenced code blocks in Writer and Reading, including split layouts.
- Shared implementation: `--rs-code-block-bg` in the theme tokens.
- Evidence: Editor browser screenshots and checks accompany the card review.
- Limits: Native desktop appearance requires user review.
### UI-017 — Quiet card detail controls
- Type: Rule change
- Date: 2026-10-13
- Status: Implemented for user review
- Decision source: Card 165db7bc requests transparent buttons and plain label removal.
- Previous rule: Card detail buttons and the footer used separate tinted surfaces.
- New rule: Buttons have transparent resting backgrounds. The footer stays in the content flow with no extra tint.
- Reason: Remove the large label removal button and the dark bar without obscuring the form.
- Scope: Project Management card details. Shared menu rows retain their existing presentation.
- Shared implementation: Existing Project Management hover, focus, surface, and radius tokens.
- Evidence: `.audit/pm-details-fixed-*.png`, focused keyboard checks, and the Project Management browser suite.
- Limits: Native desktop appearance requires user review.
### UI-018 — Named palettes and local fonts
- Type: Rule change
- Date: 2026-10-13
- Status: Implemented for user review
- Decision source: Cards f7b0eaae, c46f6614, 7c3abb8e, d86825df, and 26f515c6.
- Previous rule: The palettes used character names and the common interface font.
- New rule: Harvest Moon, Crimson Pilot, and Silver Serpent use distinct palettes and local font stacks. Saved choices migrate to the new names.
- Reason: Give each palette a clear identity with readable surfaces, text, and syntax colors.
- Scope: Theme settings, previews, exports, saved choices, and editor colors.
- Shared implementation: Appearance normalization, palette definitions, and font tokens.
- Evidence: Nine theme checks and the theme browser smoke pass. Screenshots are in .audit/character-themes.
- Limits: Native desktop appearance requires user review.
- Replaces: The names and typography in UI-009 and UI-012.
### UI-019 — One tooltip surface
- Type: Rule change
- Date: 2026-10-13
- Status: Implemented for user review
- Decision source: Cards 18c41c19 and 218d43f3.
- Previous rule: Table cells used native titles. Plugin and toolbar hints used separate styles.
- New rule: Tooltip tokens set the surface, padding, text, font size, shadow, and shared control radius. Controls show one hint.
- Reason: Keep hints readable and remove duplicate labels.
- Scope: Table cell hints, toolbar controls, view switches, and Project Management hints.
- Shared implementation: --rs-tooltip-* tokens, attachTooltip, IconButton, ModeSwitcher, and pm-tooltip.
- Evidence: Browser checks cover light and dark themes, keyboard focus, Escape, narrow windows, and viewport edges.
- Evidence files: Host .audit/todo-ui and Project Management .audit/tooltip-*.png.
- Limits: Native desktop appearance requires user review.
Cards 07e0c4e4 and 0f9fc3b9 exposed remaining tooltip drift after UI-019.
Cause: native titles and local CSS bypassed attachTooltip. Earlier tests did not cover these control paths.
Correction: prose links and editor controls use the shared tooltip helper. The table keeps a concise cell hint.
Prevention: check the exact screenshot target with pointer and keyboard focus, both themes, Escape, and viewport edges.
Evidence: editorLinkEditing.smoke.mjs and the editor screenshot attachments. Native desktop acceptance remains open.
### UI-020 — Per-image slideshow layout
- Type: Rule change
- Date: 2026-10-13
- Status: Implemented for user review
- Decision source: Card 9c5ae261 and the user's approval of the draft on October 13.
- Previous rule: One global layout applied to every slideshow image.
- New rule: Per-image fit, position, and overlay settings override the global layout. Portrait images use a full foreground over blurred fill by default.
- Reason: Show portrait images without cropping their content or leaving empty bands.
- Scope: Slideshow settings, app backgrounds, and Project Management backgrounds.
- Shared implementation: The image sidecar API, optional blurredUrl frames, and separate foreground and cover layers.
- Evidence: Host frame and sidecar checks cover layout, cleanup, size limits, and external changes. Plugin checks accompany the card review.
- Limits: Native desktop appearance requires user review.
### UI-021 — Workspace links in document panes
- Type: Rule change
- Date: 2026-10-13
- Status: Implemented for user review
- Decision source: Card 68ccce34 requests workspace link actions, including Open to the right.
- Previous rule: Documents used one editor pane. Split layouts supported plugin views.
- New rule: Workspace links can open another document beside the current pane. Each document has one visible pane. Duplicate targets focus their existing pane.
- Reason: Keep the source note visible while users read or edit its linked note.
- Scope: Document panes, focus, save routing, selection, model lifetime, and close controls.
- Shared implementation: splitLayout geometry, documentPanes state, document sessions, and IconButton.
- Narrow layout: Document panes stack vertically and keep their content scrollable.
- Close behavior: Closing a split removes its pane and preserves the document tab and unsaved text.
- Evidence: Document unit checks and the split browser smoke accompany the card review.
- Limits: Native desktop acceptance requires user review. Pane layouts remain local to the open window.
### UI-022 — Functional color without an artificial ceiling
Type: Rule change
Date: 2026-10-13
Status: Superseded
Decision source: The user's request for functional color and current character references, plus cards 093e372f and 4bb33e4f.
Previous rule: Quiet surfaces and accents reserved for attention, without a clear boundary between layout restraint and color strength.
New rule: Quiet structure places no ceiling on saturation or HSV value. Color strength follows function and the current references.
Reason: Repeated muted palettes reduced identity and priority visibility.
Scope: Host and plugin themes, status indicators, syntax colors, and review evidence.
Shared implementation: Character palette roles, selection tokens, priority variables, and shared menu presentation.
Evidence: Exact Holo color measurements, contrast checks, and screenshots accompany the card review. Native desktop acceptance remains open.
Replaces: The interpretation that quiet structure requires globally muted colors.
Replaced by: [UI-024](#ui-024--assertive-functional-color-by-default) strengthens the default and required evidence.
### UI-023 — Separate theme font roles
- Type: Rule change
- Date: 2026-10-13
- Status: Implemented for user review
- Decision source: The user's request to review all three theme fonts.
- Previous rule: Each named theme used one family for controls, prose, and headings.
- New rule: Compact controls and longer prose can use separate families. Each role keeps a fallback stack.
- Reason: Small serif controls were harder to scan. Bahnschrift prose gave long passages the same condensed appearance as tool labels.
- Scope: Harvest Moon, Crimson Pilot, and Silver Serpent.
- Shared implementation: --rs-font-ui, --rs-font-prose, and --rs-font-heading in tokens.css.
- Evidence: themeTypography.smoke.mjs checks actual rendered fonts, selected text, narrow menus, and long settings navigation.
- Limits: Native WebView rendering and subjective reading comfort require user acceptance.
- Replaces: The single-family rule in UI-018. Its saved theme names remain.
### UI-024 — Assertive functional color by default
- Type: Rule change
- Date: 2026-10-13
- Status: Accepted
- Decision source: The user's explicit request for stronger color requirements for future agents and human developers, including a global skill.
- Previous rule: UI-022 permitted full saturation and value but did not require a stronger candidate or evidence for softer choices.
- New rule: Start with assertive functional colors. Prefer stronger candidates when readability and meaning remain sound. Require concrete evidence for softer choices.
- Reason: Permission alone leaves the default unclear. Earlier soft palettes required repeated corrections.
- Scope: RuneStone and all plugins. The user's global skill applies the same preference to other UI work within its stated scope.
- Shared implementation: [Functional color requirements](ui-color.md), theme tokens, project agent instructions, and the global ui-functional-color skill.
- Exceptions: Explicit user direction and approved project exceptions retain their scope. Readability remains required.
- Evidence: The [October 13 review](menu-audit.md), cards 093e372f and 4bb33e4f, and the user's direction in this chat.
- Limits: This policy cannot guarantee future adherence. Reviews still need measured values and rendered screenshots.
- Replaces: [UI-022](#ui-022--functional-color-without-an-artificial-ceiling) for the strength of the default and required evidence.
- Release impact: Documentation and instructions only. No version or artifact change.
### UI-025 — Table links hide their source after repeated fixes
- Type: Recurring problem
- Date: 2026-10-13
- Status: Resolved
- Existing rule: Inline editing keeps attention on the document under the interface design principles.
- Scope: Writer links inside Markdown table cells.
- Occurrences: Cards 8ee17b99-3a69-49c0-8aa1-e3d67e8f966f, 08f4f317-6273-4279-8136-4afe6f665b1d, and e9105823-69b2-440b-8931-5782256c8ce8.
- Cause: A normal click placed the caret in rendered text but did not reveal the link source. Earlier tests checked caret position and invoked Edit link before checking the URL.
- Correction: Reveal inline Markdown when the caret enters a link. Preserve the caret position within its label.
- Prevention: Check ordinary clicks and keyboard entry before invoking any menu. Check the visible URL, label edits, target edits, undo, and save.
- Check: The ordinary-click and keyboard regression passed in both themes at wide and narrow widths. Source checks and 245 unit tests passed.
- Evidence: The current card includes the actual and expected screenshots. New screenshots accompany its review.
- Resolution: Source checks passed on 2026-10-13. Native WebView acceptance remains open. Reopen this entry if the problem returns.
### UI-026 — Compact shared menu rows
- Type: Rule change
- Date: 2026-10-14
- Status: Implemented for user review
- Decision source: Card e16480da-be7d-426c-969e-8af0cd894e54 requests more actions within the same vertical space.
- Previous rule: Menus used 30-pixel rows and 4-pixel vertical padding.
- New rule: Menus use 24-pixel rows and 2-pixel vertical padding. Text, icons, panel padding, and horizontal padding retain their shared dimensions.
- Reason: Compact rows reduce menu height while preserving readable labels and keyboard access.
- Scope: Host and plugin action menus, submenus, and shared picker rows.
- Shared implementation: --rs-menu-row-height and --rs-menu-row-padding in tokens.css, consumed by menu.css and plugin controls.
- Evidence: The file menu measures 456 pixels after the change and 558 pixels with the previous tokens, in both themes.
- Checks: menuConsistency.smoke.mjs compares host menus, keyboard access, disabled actions, modal menus, and viewport bounds.
- Limits: Browser checks use desktop mocks. Native display scaling and user acceptance remain open.
### UI-027 — Direct spelling corrections
- Type: Rule change
- Date: 2026-10-14
- Status: Implemented for user review
- Decision source: Card 658fc42d-6d6d-4d90-8d32-0e350ebfbc9f and its Obsidian screenshot.
- Previous rule: The Markdown menu placed spelling corrections inside a final Spelling submenu.
- New rule: Put corrections and Add to dictionary first in the main editing menu.
- Reason: Users can see and choose a correction immediately after a right click.
- Scope: The shared Markdown menu in Writer and the Markdown source editor.
- Shared implementation: markdownMenu.ts with the shared actionMenu renderer.
- Checks: editorSurfaces.smoke.mjs checks direct corrections, keyboard activation, replacement, undo, and narrow menus in both themes.
- Limits: Browser checks mock Windows spelling results. Native dictionary behavior remains a user acceptance check.
+87
View File
@@ -0,0 +1,87 @@
# Menu and color review — October 13, 2026
The seven boards contained eight To Do cards: five in RuneStone and three in Project Management. No selected card was blocked.
Reference cards remain in Backlog. They supply evidence and do not count as implementation tasks.
## Menu coverage
The source audit covers RuneStone, Project Management, Terminal, Background Slideshow, Local Autocomplete, Git, PDF Viewer, and Table Formulas.
The [inventory](menu-surfaces.json) records 38 source files, their design route, and their check.
Project Management has 21 distinct menu, choice, and picker routes in its detailed local inventory.
PDF Viewer and Table Formulas contain no independent menu renderer. Git's commit list is a persistent listbox.
| Surface | Result |
| --- | --- |
| Linked cards | Both Relationship and Card to link use the shared menu. Search updates the card choices. |
| Move card to board | Destination board and list use shared menus inside the dialog. |
| Other PM choices | Cover, bulk moves, board, list, status, and backgrounds use the shared adapter. |
| Search results | Labels, tags, details, notes, workspace files, Terminal choices, and slideshow images use shared picker presentation. |
| Browser | Profile and web-data choices use the shared menu. |
| Local Autocomplete | Server type uses the host menu when the API is available. |
| Terminal | Menu snapshots match the host. The default profile uses a radio menu. |
| Keyboard navigation | Menu focus scrolls only its panel. A short modal no longer dismisses the menu during arrow navigation. |
The earlier linked-card check tested only Relationship. Its neighboring Card to link control remained native.
The richer-layout allowance also let independent picker styles persist. The guide now requires shared presentation within those layouts.
Run `pnpm check:menus` for the source audit. It rejects new or changed entry-point counts and stale Terminal snapshots.
This check detects known source patterns. It does not prove every runtime state, native menu, or future rendering method is compliant.
Browser tests must still open the exact control from each reported screenshot.
## Functional color
No inspected rule requires a saturation or HSV value ceiling. The local guide used quiet and restrained language without separating structure from color strength.
That ambiguity could influence choices. It does not establish the cause of every earlier model output.
The guide now permits 100% saturation and value where they serve recognition or meaning.
Holo's prior mean saturation across palette roles was 30.24%. Asuka was 53.05%, and Malfoid was 16.24%.
Some existing colors already reached 100% value. The problem was not a universal numeric cap.
Holo now uses copper, chestnut, cream, amber, and red from the current fan-art references.
Its amber accent has 82% saturation and 100% value. Its minimum tested syntax contrast is 4.61:1.
The further theme pass below covers Asuka and Malfoid. Priority symbols use full saturation and value, opaque strokes, and readable theme text.
## Theme refinements and font roles
Asuka now assigns more syntax roles to red, orange, yellow, and blue. One green role reflects the suit detail.
The old selected keyword contrast was 3.95:1. All tested solid-state text and syntax pairs now reach at least 4.71:1.
Malfoid now uses emerald for identity and selection, with separate silver, blonde, cream, and skin-tone roles.
Emerald accent saturation increased from 29% to 76%. Tested text and syntax pairs reach at least 4.61:1, including the measured image surfaces.
All three named themes use their selection token for tree and table fills as well as text selection.
| Theme | Controls | Prose | Headings |
| --- | --- | --- | --- |
| Harvest Moon / Holo | Candara | Constantia | Constantia |
| Crimson Pilot / Asuka | Bahnschrift | Segoe UI | Bahnschrift |
| Silver Serpent / Malfoid | Corbel | Palatino Linotype | Palatino Linotype |
The font roles separate compact controls from longer reading. Character identity remains in the selected families and headings.
Chrome's font inspection confirms the actual families on this machine. The check does not rely on CSS names alone.
The shared code font remains Cascadia Mono on this machine. Each role retains a fallback stack for other systems.
Checks use 13-pixel controls, 15-pixel prose, 24-pixel headings, selected text, 360-pixel settings, and a long plugin list.
Image contrast depends on the composited surface. Asuka's red accent reaches 3.22:1 on an 82% elevated tint over pure white.
Ordinary menu text passes there. Actual syntax surfaces use a 90% editor tint and pass the separate code checks.
This limit remains visible in the evidence. The palette does not claim universal contrast over every user image or overlay.
## Evidence and limits
Host checks pass with zero errors or warnings and 243 unit tests. Project Management passes 119 unit tests and 14 host-menu browser tests.
Terminal passes seven unit tests and browser checks. Slideshow passes 14 unit tests and both settings browser suites.
Local Autocomplete passes 11 unit tests and its modal-menu browser check.
Browser checks cover themes, narrow layouts, focus, keyboard use, and the reported controls. Screenshots remain in each project's `.audit` folder.
Operating-system menus, embedded website controls, older-host fallbacks, and upstream Monaco widgets retain their respective implementations.
Native desktop interaction and screen-reader output remain acceptance checks. Browser results use mocked desktop APIs.
Source versions remain unchanged. This review produced no installer or plugin ZIP.
## Build artifacts: 2026-10-13
RuneStone 0.1.32 contains the reviewed host changes. Its installer is in RuneStone/releases/0.1.32/.
Project Management 0.2.35 contains the reviewed plugin menu and priority changes. Its ZIP is in RuneStone_ProjectManagement/releases/.
The coordinated build also includes Terminal 0.1.7, Background Slideshow 0.0.7, and Local Autocomplete 0.1.4 in their respective release folders.
Checksums, release notes, and build metadata accompany each artifact.
The host passed 243 unit tests and 93 native tests, with three native tests ignored.
PM passed 119 unit tests and 161 browser tests, with 16 browser tests skipped.
Archive integrity and manifest versions pass for all four ZIPs.
These artifacts are ready for user acceptance. All eight cards remain in Review.
+316
View File
@@ -0,0 +1,316 @@
{
"date": "2026-10-14",
"scope": [
"RuneStone",
"RuneStone_ProjectManagement",
"RuneStone_Terminal",
"RuneStone_BG_Slideshow",
"RuneStone_LocalAutocomplete",
"RuneStone_Git",
"RuneStone_PDFViewer",
"RuneStone_TableFormulas",
"RuneStone_CSVViewer"
],
"limits": [
"Source patterns detect known menu construction routes. Browser evidence remains a separate check.",
"Native operating-system menus and embedded website controls keep platform presentation.",
"Older plugin hosts without ui.showActionMenu retain documented fallbacks."
],
"surfaces": {
"RuneStone/src/lib/browser/Browser.svelte": {
"counts": {
"action": 2
},
"design": "Shared action menu",
"check": "scripts/builtinBrowser.smoke.mjs; scripts/browserWebData.smoke.mjs"
},
"RuneStone/src/lib/browser/Settings.svelte": {
"counts": {
"action": 1,
"localPopup": 2
},
"design": "Shared action menu",
"check": "scripts/builtinBrowser.smoke.mjs; scripts/browserWebData.smoke.mjs"
},
"RuneStone/src/lib/browser/WebData.svelte": {
"counts": {
"action": 1
},
"design": "Shared action menu",
"check": "scripts/builtinBrowser.smoke.mjs; scripts/browserWebData.smoke.mjs"
},
"RuneStone/src/lib/editor/codeMenu.ts": {
"counts": {
"action": 1
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs; scripts/editorLinkEditing.smoke.mjs; scripts/editorSurfaces.smoke.mjs"
},
"RuneStone/src/lib/editor/imageControls.ts": {
"counts": {
"action": 1
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs; scripts/editorLinkEditing.smoke.mjs; scripts/editorSurfaces.smoke.mjs"
},
"RuneStone/src/lib/editor/markdownMenu.ts": {
"counts": {
"action": 2
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs; scripts/editorLinkEditing.smoke.mjs; scripts/editorSurfaces.smoke.mjs"
},
"RuneStone/src/lib/editor/readingMenu.ts": {
"counts": {
"action": 1
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs; scripts/editorLinkEditing.smoke.mjs; scripts/editorSurfaces.smoke.mjs"
},
"RuneStone/src/lib/editor/spellingMenu.ts": {
"counts": {
"action": 1
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs; scripts/editorLinkEditing.smoke.mjs; scripts/editorSurfaces.smoke.mjs"
},
"RuneStone/src/lib/editor/tableSelectionControls.ts": {
"counts": {
"action": 1
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs; scripts/editorLinkEditing.smoke.mjs; scripts/editorSurfaces.smoke.mjs"
},
"RuneStone/src/lib/editor/WriterHost.svelte": {
"counts": {
"svelteMenu": 1
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs; scripts/editorLinkEditing.smoke.mjs; scripts/editorSurfaces.smoke.mjs"
},
"RuneStone/src/lib/layout/ContextMenu.svelte": {
"counts": {
"action": 1
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs"
},
"RuneStone/src/lib/layout/FileTree.svelte": {
"counts": {
"svelteMenu": 1
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs"
},
"RuneStone/src/lib/layout/QuickOpen.svelte": {
"counts": {
"picker": 1,
"localPopup": 3
},
"design": "Shared searchable picker used by quick file open and document link picker",
"check": "scripts/workspaces.smoke.mjs; scripts/editorLinkMenus.smoke.mjs"
},
"RuneStone/src/lib/layout/TabBar.svelte": {
"counts": {
"action": 1
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs"
},
"RuneStone/src/lib/layout/Workbench.svelte": {
"counts": {
"action": 1
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs"
},
"RuneStone/src/lib/layout/WorkspacePicker.svelte": {
"counts": {
"picker": 1,
"localPopup": 7
},
"design": "Shared rich picker; paths retain a detail row",
"check": "scripts/workspaces.smoke.mjs"
},
"RuneStone/src/lib/plugins/externalSession.ts": {
"counts": {
"action": 1
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs"
},
"RuneStone/src/lib/plugins/PluginAccessMenu.svelte": {
"counts": {
"svelteMenu": 1
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs"
},
"RuneStone/src/lib/plugins/sdk.ts": {
"counts": {
"action": 1
},
"design": "API type declaration, no renderer",
"check": "pnpm check"
},
"RuneStone/src/lib/theme/AppearanceSettings.svelte": {
"counts": {
"action": 2,
"localPopup": 3
},
"design": "Shared action menu",
"check": "scripts/characterThemes.smoke.mjs"
},
"RuneStone/src/lib/ui/actionMenu.ts": {
"counts": {
"action": 1,
"localPopup": 2
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs"
},
"RuneStone/src/lib/ui/managedActionMenu.ts": {
"counts": {
"action": 2
},
"design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs"
},
"RuneStone_ProjectManagement/src/choices-ui.ts": {
"counts": {
"action": 1
},
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
"check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
},
"RuneStone_ProjectManagement/src/details-ui.ts": {
"counts": {
"picker": 1,
"localPopup": 4
},
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
"check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
},
"RuneStone_ProjectManagement/src/labels-ui.ts": {
"counts": {
"picker": 1,
"localPopup": 3
},
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
"check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
},
"RuneStone_ProjectManagement/src/preferences.ts": {
"counts": {
"action": 1,
"nativeChoice": 1
},
"design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained",
"check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
},
"RuneStone_ProjectManagement/src/priority-ui.ts": {
"counts": {
"action": 1,
"picker": 1,
"localPopup": 3
},
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
"check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
},
"RuneStone_ProjectManagement/src/relations-ui.ts": {
"counts": {
"nativeChoice": 1,
"picker": 1,
"localPopup": 5
},
"design": "Shared relationship choice and direct searchable picker rows; older-host choice fallback retained",
"check": "RuneStone_ProjectManagement/tests/relations-menu.spec.ts; tests/menu-audit.spec.ts; tests/related-cards.spec.ts"
},
"RuneStone_ProjectManagement/src/tags.ts": {
"counts": {
"picker": 2,
"localPopup": 2
},
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
"check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
},
"RuneStone_ProjectManagement/src/ui.ts": {
"counts": {
"action": 4,
"nativeChoice": 14,
"picker": 1,
"localPopup": 1
},
"design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained",
"check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
},
"RuneStone_Terminal/src/TerminalDock.svelte": {
"counts": {
"action": 1
},
"design": "Synchronized shared action menu snapshot",
"check": "RuneStone_Terminal/scripts/terminal.smoke.mjs"
},
"RuneStone_Terminal/src/TerminalPicker.svelte": {
"counts": {
"picker": 2,
"localPopup": 3
},
"design": "Shared searchable picker",
"check": "RuneStone_Terminal/scripts/terminal.smoke.mjs"
},
"RuneStone_Terminal/src/TerminalSettings.svelte": {
"counts": {
"action": 1,
"localPopup": 1
},
"design": "Synchronized shared action menu snapshot",
"check": "RuneStone_Terminal/scripts/terminal.smoke.mjs"
},
"RuneStone_BG_Slideshow/src/contracts.ts": {
"counts": {
"action": 1
},
"design": "API type declaration, no renderer",
"check": "pnpm check"
},
"RuneStone_BG_Slideshow/src/image-settings-ui.ts": {
"counts": {
"action": 1,
"nativeChoice": 1,
"picker": 2,
"localPopup": 3
},
"design": "Host action menus and shared searchable image picker; native image select only on older hosts",
"check": "RuneStone_BG_Slideshow/tests/settings.smoke.mjs"
},
"RuneStone_BG_Slideshow/src/settings.ts": {
"counts": {
"action": 1
},
"design": "Host action menus and shared searchable image picker; native image select only on older hosts",
"check": "RuneStone_BG_Slideshow/tests/settings.smoke.mjs"
},
"RuneStone_LocalAutocomplete/src/main.mjs": {
"counts": {
"action": 1,
"nativeChoice": 1
},
"design": "Host radio menu; native server select only on older hosts",
"check": "scripts/pluginChoiceMenus.smoke.mjs"
},
"RuneStone_Git/src/view.js": {
"counts": {
"picker": 1
},
"design": "Commit history listbox, not a popup menu",
"check": "Source inspection: persistent history list retains its own layout"
},
"RuneStone_CSVViewer/src/index.js": {
"counts": {
"action": 1
},
"design": "Host action menus for columns, sorting, filter types, and operators",
"check": "RuneStone_CSVViewer/tests/browser.mjs; tests/host.mjs"
}
}
}
+46 -4
View File
@@ -12,7 +12,7 @@ Terminal and Table formulas use the same installed package system as all other p
1. Clone `RuneStone_TableFormulas` beside RuneStone and run `pnpm install --frozen-lockfile` in that checkout.
2. Run `pnpm build:plugins` from the RuneStone repository root for Table formulas.
3. In Settings → Plug-ins, choose Install plugin ZIP.
4. Select the ZIP files in `plugin-packages/`, then choose Install and enable.
4. Select the ZIP files in `../RuneStone_TableFormulas/releases/`, then choose Install and enable.
The build creates `runestone.table-formulas-0.1.0.zip`.
Table formulas is a development package in its [own repository](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_TableFormulas).
@@ -61,7 +61,7 @@ Each package succeeds or fails independently. The result identifies any failures
A changed source requires a new review. Cancelling the review removes its temporary copies.
Try the example with `pnpm package:plugin fixtures/plugins/workspace-overview`.
Install the resulting ZIP from `plugin-packages/`, then choose Install and enable.
Install the resulting ZIP from `releases/`, then choose Install and enable.
Use Open tab or view beside New tab to open Workspace overview.
Use Commands in the toolbar to run Show workspace overview.
@@ -216,7 +216,9 @@ Keep JavaScript readable where practical. Avoid minification and obfuscation tha
3. Install the resulting ZIP in RuneStone and test its features, disable action, and uninstall action.
4. Share that same ZIP as the release file.
Use Node.js 24 or later for the packaging command. The default output folder is `plugin-packages/`.
Use Node.js 24 or later for the packaging command. The default output folder is `releases/` in the project that contains the compiled folder.
Keep plugin release ZIPs in that plugin project, including when the host calls the build.
Explicit output folders are for temporary checks or staging. Move completed releases into the owning project's `releases/` folder.
It checks the manifest, paths, entry module, and size limits before it writes `<id>-<version>.zip`.
It includes every file in the input folder. Keep dependencies, credentials, and unrelated build files outside that folder.
The output folder must be outside the input folder.
@@ -447,7 +449,7 @@ The plugin must stop its mounted controls and native sessions in `onDispose` bef
| `src/lib/plugins/TerminalSlot.svelte` | The host element for terminal controls |
| `../RuneStone_Terminal/src/` | Terminal plugin source in its own repository |
| `../RuneStone_TableFormulas/` | Table formulas source, unit tests, and package build |
| `scripts/buildPlugins.mjs` | Table formulas compilation and ZIP release in `plugin-packages/` |
| `scripts/buildPlugins.mjs` | Table formulas compilation and ZIP release in `../RuneStone_TableFormulas/releases/` |
| `scripts/packagePlugin.mjs` | Shared checks and ZIP creation for plugin authors |
Run `pnpm build:plugins`, `pnpm check`, `pnpm test`, `pnpm build`, and `cargo test --manifest-path src-tauri/Cargo.toml --lib --offline`.
@@ -497,3 +499,43 @@ The Git graph uses graphical commit nodes and parent links. It shows forks, merg
The host returns structured history from `git.graph()`: `{ commits: [{ id, parents, refs, summary, author, date }] }`.
The graph keeps the latest 100 commits. Dashed links mark parents outside that history.
The updated Git package requires the matching host build. An older host shows an update message instead of a graph.
## Temporary background API
RuneStone 0.1.25 adds optional `api.backgrounds` with `version: 1`.
Background Slideshow uses it for local image folders and temporary backgrounds.
Project Management 0.2.29 uses it for board backgrounds.
| Method | Contract |
| --- | --- |
| `chooseFolder()` | Open the native folder picker. Return an absolute path or null on cancellation. |
| `defaultFolder()` | Optional. Create and return Pictures/RuneStone Backgrounds for new settings. |
| `list(folder)` | List PNG, JPEG, GIF, and WebP filenames directly inside the folder. |
| `read(folder, name)` | Read one raster image as bytes, with a 50 MiB limit. |
| `set(target, frame)` | Apply a temporary frame. Pass null to remove this plugin's frame. |
| `get(target)` | Read the active frame or null. |
| `subscribe(listener)` | Receive the changed target. Return a cleanup function. |
Targets are `app`, `pm-all`, and `pm-board:<board UUID>`.
A frame contains `url`, `overlay`, `position`, and `size`.
It can also contain `previous` with those four fields and `transitionMs` from 0 to 5000.
Renderers fade between these frames unless reduced motion is active. Keep both blob URLs valid until replacement or cleanup.
Use a blob URL. The publishing plugin owns the URL and must release it after replacement or cleanup.
Overlay ranges from -1 to 1. Negative values lighten the image, and positive values darken it.
Position and size use the same choices as custom image settings.
Frames belong to the plugin activation in the current window. They do not change saved background settings.
The last published frame wins. Removing it reveals an earlier active frame or the saved background.
Project Management checks a temporary board frame first, then `pm-all`, then the saved board image.
Disable removes the plugin's frames and subscriptions before cleanup.
File access requires an active plugin lease. Pending reads fail after access is revoked.
Image reads reject path traversal, linked files, unsupported formats, and oversized files.
Each window keeps its own sequence. The plugin settings API shares folder and playback settings across windows.
### Per-image background settings
Slideshow stores per-image fit, position, and overlay in .runestone-backgrounds.json beside the images. The sidecar uses schema 1 and an images object. Settings saves compare the previous file text to preserve external changes. The sidecar has a 1 MiB limit.
Portrait images show the full image over a blurred cover layer by default. Each target scales the foreground and blurred layer separately. The image editor shows a preview and lets users save or reset an override. Global settings remain the fallback for other images.
The optional background API adds readImageSettings and writeImageSettings. Temporary frames can supply blurredUrl. The plugin owns all frame URLs and releases them after replacement or shutdown.
+85
View File
@@ -0,0 +1,85 @@
# Functional color requirements
[Interface design](ui-design.md#functional-color-and-complete-menu-checks) · [Decision UI-024](design-decisions.md#ui-024--assertive-functional-color-by-default)
RuneStone uses assertive color to help users recognize information, distinguish states, and identify themes.
This policy applies to human developers and agents across the host and all plugins.
Start with vivid functional colors. Choose softer colors only when a concrete requirement or measured problem supports that choice.
## What aggressive color selection means
Actively evaluate strong colors for accents, priority marks, status indicators, selection outlines, links, syntax, and important data.
Include high-saturation and high-value candidates. Treat 100% saturation and 100% HSV value as ordinary options when they serve the role.
Prefer the stronger candidate when readability, meaning, and distinction remain sound.
Do not automatically turn red into dusty coral, emerald into sage, gold into beige, or clear data colors into similar pastels.
Words such as quiet, refined, professional, premium, minimal, and cohesive do not set color limits.
Keep the layout focused through spacing, hierarchy, restrained repetition, and the amount of color on screen.
Use vivid colors where users must recognize identity, state, or meaning.
Set surfaces and dividers for their support role. There is no requirement to saturate every background, neutral, or text color.
A palette average is not a design target, and one bright token cannot excuse a mostly indistinct palette.
## Requirements by role
| Role | Requirement |
| --- | --- |
| Theme identity | Preserve characteristic hues and their strength from current references. |
| Priority and status | Use clear, assertive colors with opaque symbols. Pair color with shape or text. |
| Links and actions | Keep actionable text distinct and readable against its actual surface. |
| Selection and focus | Show a clear state change and boundary. Preserve readable content inside the selected area. |
| Syntax and data | Give different meanings distinct roles. Avoid several nearly identical muted colors. |
| Backgrounds and dividers | Support content and visible boundaries. Choose their strength by function rather than a palette-wide muting rule. |
| Disabled states | Distinguish unavailable actions while keeping labels readable. Do not apply their opacity to enabled content. |
Use shared theme tokens. Correct an inappropriate token at its source instead of adding local saturation or opacity overrides.
Do not fade an entire badge, row, or container when only its background needs transparency.
Keep meaningful foreground symbols and text opaque.
## References and known failures
Read the current reference cards and respect the user's stated source priority.
For Holo, prefer the current fan art. Exclude removed images from later palette decisions.
Separate characteristic colors from scenery, lighting, alternate clothing, and unrelated details.
The first trading screenshot and Bloomberg example demonstrate clear information and state distinctions. They do not prescribe a terminal-like appearance for RuneStone.
The October 13 review found specific problems:
- Holo used marshy green and pink roles that did not match the requested identity. Warm copper, chestnut, amber, and red replaced them.
- Asuka repeated green and similar cyan roles. Red, orange, yellow, and blue now carry clearer meanings.
- Malfoid used a sage accent and near-gray syntax. The emerald accent changed from about 29% saturation to 76%.
- Priority marks were too dark to draw attention. Their symbols now use full saturation and value with readable text.
These values record that correction. They are not universal quotas or fixed limits for future themes.
See the [menu and color review](menu-audit.md) for implementation evidence and image-surface limits.
## Readability and visual checks
Check contrast against the actual rendered background, including alpha, layered surfaces, images, overlays, and selected states.
HSV value is not perceived brightness or a contrast ratio. Full value does not guarantee readable text.
When contrast fails, compare foreground, background, local surface, and role changes before reducing color strength.
Preserve readable text and state recognition. Follow the project's accessibility thresholds and existing contrast checks.
Passing contrast alone does not prove useful color distinctions, theme identity, or effective priority emphasis.
Inspect screenshots at normal display scale. Check relevant light and dark appearances, narrow layouts, focus, hover, selection, and disabled states.
Check actual content, code, menus, and priority marks where the changed tokens appear.
Record unavailable checks and failures. Browser mocks do not replace native desktop acceptance.
## Evidence required for review
For each changed role, record:
| Field | Required evidence |
| --- | --- |
| Purpose | Meaning, theme reference, or recognition task |
| Implementation | Shared token and affected controls |
| Color | Old and new hex values, HSV saturation and value, and opacity |
| Readability | Foreground/background pairs, actual composite surface, and contrast results |
| Visual result | Normal-scale screenshots of affected states and layouts |
| Softer choice | Concrete requirement or measured problem, plus the stronger candidate considered |
A generic claim that muted colors look elegant or comfortable is insufficient.
Correct unexplained muting or record the unresolved issue before moving the work to Review.
Use the project's exception process for deliberate departures from this policy. A documented exception does not itself authorize the departure.
User acceptance still determines Done.
Agents also use the global `ui-functional-color` skill. This document supplies the project rules for contributors without that skill.
+112 -11
View File
@@ -1,13 +1,13 @@
# Interface design
[Back to development](development.md)
[Back to development](development.md) · [Functional color requirements](ui-color.md)
RuneStone uses compact controls, clear icons, and shared theme values.
This reference describes the interface and its shared dimensions. Agent instructions remain in [AGENTS.md](../AGENTS.md).
## Design principles
Keep attention on the user's work. Use quiet backgrounds for the active view and reserve strong accents for alerts or actions that need attention.
Keep attention on the user's work. Use quiet structure for the active view. Preserve clear colors for identity, meaning, and attention.
Show only what the current task needs. Let users collapse optional sections and hide panes when they need more space.
Tabs can join visually with their content area. A selected view does not need a bright border or a repeated heading.
@@ -61,29 +61,37 @@ Feature code does not override menu rows. Menu width can expand when content nee
| --- | --- | --- |
| `--rs-menu-width` | 248px | Standard menu width |
| `--rs-menu-padding` | 5px | Inset around rows |
| `--rs-menu-row-height` | 30px | Minimum row height |
| `--rs-menu-row-padding` | 4px 10px | Vertical and horizontal row padding |
| `--rs-menu-row-height` | 24px | Minimum row height |
| `--rs-menu-row-padding` | 2px 10px | Vertical and horizontal row padding |
| `--rs-menu-font-size` | 13px | Shared text size |
| `--rs-menu-border` | `transparent` | Borderless panel |
| `--rs-menu-icon-size` | 14px | Action icon size |
| `--rs-menu-icon-gap` | 8px | Space between icon and label |
See [UI-026](design-decisions.md#ui-026--compact-shared-menu-rows) for compact shared rows.
Spelling corrections appear first in the main editing menu. Add to dictionary follows them, before ordinary editing actions.
See [UI-027](design-decisions.md#ui-027--direct-spelling-corrections) for direct corrections.
Menus with only text choices omit the icon column. Mixed action menus reserve the icon column for every row.
Shortcut text and submenu arrows occupy trailing columns.
Enabled rows share hover and keyboard focus colors. Disabled rows stay readable and cannot run.
Menus support arrow keys, Home, End, Enter, Space, and Escape.
Right opens a submenu. Left returns to its parent. Keyboard dismissal restores focus.
Menus stay inside the viewport and scroll when their contents exceed its height.
Menus use 30-pixel rows, 13-pixel text, and a borderless panel with a shadow.
Keep hover and keyboard focus fills quiet, with an inset from the panel edge.
Menus use 24-pixel rows, 13-pixel text, and a borderless panel with a shadow.
Menus use an 82% surface tint through `--rs-menu-bg` and `--rs-menu-active-bg`.
The shared action menu applies this tint to host and plugin menus, including submenus.
The workspace picker shares the menu surface. Labels and icons remain opaque.
See [UI-013](design-decisions.md#ui-013--translucent-menu-surfaces).
Use the shared hover and keyboard focus fills, with an inset from the panel edge.
Theme, appearance, board, and list menus share these values. See [decision UI-002](design-decisions.md#ui-002--share-the-requested-dropdown-design).
See [UI-006](design-decisions.md#ui-006--borderless-shared-menus) for the borderless panel rule.
Radio choices show the current option with a quiet fill and no checkmark.
Radio choices show the current option with the shared fill and no checkmark.
The current enabled radio choice receives focus when its menu opens. See [UI-003](design-decisions.md#ui-003--quiet-menu-choices).
A menu row can have a default action and a submenu.
Clicking the label, Enter, or Space runs the default action. Hover, the submenu arrow, or Right opens the submenu.
New note creates a blank note. Its submenu contains templates and Manage templates.
Searchable pickers and form dialogs can use richer layouts. Native select controls retain platform behavior.
Searchable pickers and form dialogs can use richer layouts. Their menu surfaces still use the shared presentation below.
Native editing menus retain recognized editing, spelling, and emoji commands.
They omit system sharing, writing direction, dictation, and unsupported unnamed tools.
The host filters the native collection before shared display or native fallback. See [UI-008](design-decisions.md#ui-008--keep-native-editing-menus-focused).
@@ -93,7 +101,7 @@ The host filters the native collection before shared display or native fallback.
Settings navigation pairs icons with labels. Each settings page uses readable text and ordinary controls.
Related plugin metadata and actions occupy compact rows. Controls wrap at narrow widths, and the content area scrolls.
Long navigation lists must leave room for the selected page.
New tabs and Project Management keep separate background images and settings in every theme. Images can be up to 50 MiB.
The app work area and Project Management keep separate background images and settings in every theme. Images can be up to 50 MiB.
Image bytes stay in IndexedDB. Settings retain a small image reference.
Both support image size, nine alignment positions, and an overlay that lightens or darkens the image.
Set the overlay with the slider or type a percentage from -100 to 100.
@@ -122,6 +130,8 @@ Tables use shared cell padding and line height. Entering a cell does not change
A plain paragraph after a table remains a paragraph when the separator line is removed.
Table rows need an unescaped pipe. Writer and Reading use the same row boundary rule.
Table links reveal their Markdown source when the caret enters the link. Keep the caret at the chosen label character. Edit link selects the complete target inside the cell. Check ordinary clicks and keyboard entry before menu actions. See [UI-025](design-decisions.md#ui-025--table-links-hide-their-source-after-repeated-fixes) for the repeated failure and its regression checks.
## Checks for interface changes
Check light and dark themes, keyboard use, focus indicators, narrow windows, and viewport edges.
@@ -133,7 +143,7 @@ The menu check covers file, folder, pane, tab, editor, table, and submenu exampl
Use `SMOKE_URL` to select the server URL. Use `PLAYWRIGHT_MODULE` and `CHROME_PATH` when the environment needs explicit paths.
Browser tests with desktop mocks do not replace native installer and window acceptance checks.
## Keep controls quiet
## Keep controls focused
Keep empty forms hidden until the user chooses an add action. Keep section names, counts, and expand controls visible.
Remember that a collapsed section still contains work. Do not remove its data or hide errors that need attention.
@@ -147,13 +157,75 @@ Board switching, renaming, and adding work remain separate controls. Put plug-in
Use the shared action menu for short option lists, including board and theme choices. Mark the current option with a radio state.
Use a searchable picker for long lists. Native selectors remain an older-host fallback for plugins.
Menu rows use the same inset, hover fill, focus fill, and corner radius. A menu choice and a file selection serve different purposes.
File selections retain the shared selection fill and outer outline. Hover uses the quiet active background across both surfaces.
File selections retain the shared selection fill and outer outline. Hover uses the shared active background across both surfaces.
Do not copy feature-specific colors into a shared control.
The Claude palette follows the [Anthropic brand guide](https://github.com/anthropics/skills/blob/main/skills/brand-guidelines/SKILL.md).
Keep its warm light and dark surfaces, orange accent, Lora body font, and Poppins headings with their documented fallbacks.
Shared dimensions and interaction rules apply to every palette.
Named palettes use one fixed appearance.
Harvest Moon, Crimson Pilot, and Silver Serpent each use one dark appearance. Their palettes use multiple surface, text, accent, and syntax colors. Saved choices retain their colors and backgrounds after the names change. Harvest Moon uses Candara controls and Constantia prose and headings. Crimson Pilot uses Bahnschrift controls and headings with Segoe UI prose. Silver Serpent uses Corbel controls and Palatino Linotype prose and headings. Each local font stack has fallback fonts. Code keeps the shared monospace stack. See [UI-023](design-decisions.md#ui-023--separate-theme-font-roles).
Removed palettes return to the default appearance.
Saved selections for removed themes return to RuneStone and retain their mode and background settings.
The theme preview includes code colors. See [UI-009](design-decisions.md#ui-009--character-theme-appearances) for this rule change.
New-tab controls use `--rs-image-control-bg` and `--rs-image-control-hover-bg`.
Their backgrounds retain enough color for readable labels while the image remains visible.
The new-tab screen shows only its action buttons, with icons, labels, and shortcuts.
Buttons use the same 82% tint as Project Management lists.
One app image spans the work area below the titlebar, including new tabs and document views.
Sidebars use `--rs-image-sidebar-bg` at 82%. Editor surfaces use `--rs-image-editor-bg` at 90%.
Without an image, both use their ordinary opaque surfaces.
Writer, Reading, split, and IDE share the tinted editor surface. Monaco layers remain transparent above it.
Code blocks in Writer and Reading use `--rs-code-block-bg`, an 82% tint of the elevated surface.
See [UI-016](design-decisions.md#ui-016--translucent-code-blocks) for this rule.
The IDE command palette uses the shared selection fill, outline, and corner radius.
Headers and dialogs retain their own surfaces. Menus and Project Management use the image rules below.
The image remains fixed while content scrolls. Saved appearance and slideshow settings keep their existing controls.
See [UI-011](design-decisions.md#ui-011--backgrounds-across-the-work-area) for the work-area rule.
See [UI-012](design-decisions.md#ui-012--retain-three-stronger-character-themes) for the theme changes.
Project Management without its own image shows the single host background through a transparent root.
A saved or temporary board image retains its own background area.
The host exposes `--rs-workarea-plugin-bg` and `--rs-workarea-surface-opacity` for saved images and slideshow frames.
Lists, cards, card details, and search fields share an 82% tint when an image is active.
Gantt and calendar views use one tinted panel. Date cells and headings keep the image visible.
Selected cards retain the shared selection treatment. Nested surfaces keep their own tint to preserve readable controls.
See [UI-014](design-decisions.md#ui-014--readable-project-management-surfaces).
See [UI-010](design-decisions.md#ui-010--background-surface-visibility) for the surface rule.
Slideshow frames override saved board images while active. A temporary board frame takes priority over the all-board frame.
Identical app and Project Management slideshow frames use the host image once across both sidebars and the board.
Distinct board frames retain their own background area.
Card detail buttons have transparent resting backgrounds. Hover, pressed, and keyboard focus states remain visible.
See [UI-017](design-decisions.md#ui-017--quiet-card-detail-controls) for the detail controls.
Removal restores the saved image.
Image changes fade for two seconds. Reduced motion removes the animation.
Short image intervals and manual Next can interrupt a fade.
See [UI-015](design-decisions.md#ui-015--slower-slideshow-fades).
## Functional color and complete menu checks
Use [Functional color requirements](ui-color.md) for all color choices and reviews in the host and plugins.
Start with vivid candidates for accents, priorities, status, selection outlines, syntax, and important data.
Prefer stronger colors when readability, meaning, and distinction remain sound. Full saturation and full HSV value are normal options.
Require concrete evidence for softer choices. Quiet layout does not authorize weak color or broad opacity reductions.
The guide defines role requirements, current references, rendered checks, and the evidence needed for Review.
See [UI-024](design-decisions.md#ui-024--assertive-functional-color-by-default) for the stronger default.
Searchable pickers can contain search, descriptions, and forms. Their panels and result rows use the shared menu presentation.
Use `rs-picker`, `rs-picker-row`, `rs-picker-icon`, and `rs-picker-hint` from `src/lib/ui/menu.css`.
Keep their different layout and semantics. Do not use the richer layout allowance to override panel color, row padding, font, or focus states.
Use the shared action menu for native select replacements whenever the host API exists.
Native selects remain only as documented fallbacks for older plugin hosts. Embedded website controls retain the website design.
Run `node scripts/menuSurfaceAudit.mjs` before menu work moves to Review.
See the [menu and color review](menu-audit.md) and [source inventory](menu-surfaces.json) for scope and known limits.
The inventory covers menu renderers, callers, native selects, and searchable pickers across the host and sibling plugins.
An added or changed menu entry point requires inventory review. Source coverage does not prove runtime compliance.
Run the listed browser checks for affected surfaces and retain screenshots of the exact reported control.
A neighboring selector does not satisfy a card. Check every control shown in its screenshots.
## Prevent repeated UI drift
Before a new control, find its shared component and an existing example. Extend that component when the same change helps other callers.
@@ -199,3 +271,32 @@ Run the shared menu check after menu changes and relevant feature checks after b
Keep native desktop checks separate from browser tests with mocked desktop services.
Automated checks support visual and interaction review. They do not decide whether the interface keeps attention on the user's work.
Move implementation-ready work to Review after the relevant checks pass. Keep unresolved work In progress and reserve Done for the user's acceptance.
## Tooltips and text selection
Tooltips use the shared tooltip tokens for padding, font size, surface, text, and shadow. Controls keep one tooltip and no duplicate native title. Table cell hints use the same surface as toolbar hints. Hover and keyboard focus show the hint. Escape dismisses it. The hint stays within the viewport.
Text selection uses --rs-selection and --rs-selection-text in Writer, Reading, IDE, and Project Management fields. A CodeMirror selection layer must override its generated default styles.
See [UI-019](design-decisions.md#ui-019--one-tooltip-surface).
## Browser and slideshow images
New browser tabs with about:blank show the host background. Loaded pages retain their own rendering, including intentionally empty pages.
Slideshow stores per-image fit, position, and overlay in .runestone-backgrounds.json beside the images. The sidecar uses schema 1 and an images object. Settings saves compare the previous file text to preserve external changes. The sidecar has a 1 MiB limit.
Portrait images show the full image over a blurred cover layer by default. Each target scales the foreground and blurred layer separately. The image editor shows a preview and lets users save or reset an override. Global settings remain the fallback for other images.
The optional background API adds readImageSettings and writeImageSettings. Temporary frames can supply blurredUrl. The plugin owns all frame URLs and releases them after replacement or shutdown.
See [UI-020](design-decisions.md#ui-020--per-image-slideshow-layout).
See [UI-018](design-decisions.md#ui-018--named-palettes-and-local-fonts) for the palette names and font choices.
## Document panes
Workspace links can open another document to the right. Duplicate targets focus their existing pane. Closing a split preserves its tab and unsaved text. The focused pane controls Save, outline, and Terminal selection. Narrow work areas stack the panes vertically. Pane layouts stay local to the open window.
See [UI-021](design-decisions.md#ui-021--workspace-links-in-document-panes).
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "runestone",
"version": "0.1.23a",
"version": "0.1.34",
"description": "Desktop editor for a local workspace",
"type": "module",
"scripts": {
@@ -11,6 +11,7 @@
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && svelte-check --tsconfig ./tsconfig.plugins.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"check:menus": "node scripts/menuSurfaceAudit.mjs",
"tauri": "tauri",
"test": "node --experimental-strip-types --test scripts/*.spec.ts",
"build:plugins": "node scripts/buildPlugins.mjs",
+15 -16
View File
@@ -81,11 +81,11 @@ try {
return expected ? JSON.stringify(colors) === JSON.stringify(expected) : Object.values(colors).every(Boolean) && new Set(Object.values(colors)).size === 3;
}, expected);
}
const themeName = theme => ({ default: 'RuneStone', claude: 'Claude', sakura: 'Sakura' })[theme];
const themeName = (theme, mode) => theme === 'sakura' ? 'Sakura' : `${({ default: 'RuneStone', claude: 'Claude' })[theme]} ${mode === 'light' ? 'Light' : 'Dark'}`;
const picker = (page, name) => page.locator('.picker').filter({ has: page.locator('svg') }).and(page.getByRole('button', { name, exact: true }));
async function choose(page, name, value) {
await picker(page, name).click();
await page.getByRole('menuitemradio', { name: name === 'Color theme' ? themeName(value) : value === 'light' ? 'Light' : 'Dark', exact: true }).click();
async function choose(page, theme, mode) {
await picker(page, 'Color theme').click();
await page.getByRole('menuitemradio', { name: themeName(theme, mode), exact: true }).click();
}
async function openAppearance(page) {
await page.goto(`${origin}/?settingsWindow=true`);
@@ -100,17 +100,18 @@ try {
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).colorScheme), mode);
}
assert.equal((await picker(secondSettings, "Color theme").textContent()).trim(), themeName(theme));
assert.equal((await picker(secondSettings, "Appearance").textContent()).trim(), mode === "light" ? "Light" : "Dark");
assert.equal((await picker(secondSettings, "Color theme").textContent()).trim(), themeName(theme, mode));
await main.waitForFunction(() => {
const root = document.documentElement;
const probe = document.createElement("i");
probe.style.backgroundColor = getComputedStyle(root).getPropertyValue("--rs-bg");
probe.style.backgroundColor = getComputedStyle(root).getPropertyValue("--rs-workarea-editor-bg");
document.body.append(probe);
const expected = getComputedStyle(probe).backgroundColor;
probe.remove();
const surfaces = [...document.querySelectorAll(".monaco-editor .monaco-editor-background")];
return surfaces.length > 0 && surfaces.every(element => getComputedStyle(element).backgroundColor === expected);
const workarea = document.querySelector('.editor > .body');
return surfaces.length > 0 && surfaces.every(element => getComputedStyle(element).backgroundColor === 'rgba(0, 0, 0, 0)')
&& workarea && getComputedStyle(workarea).backgroundColor === expected;
});
return settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim());
}
@@ -120,8 +121,7 @@ try {
for (const theme of ["default", "claude", "sakura"]) {
for (const mode of theme === "sakura" ? ["light"] : ["light", "dark"]) {
const before = await editorIds();
await choose(settings, 'Color theme', theme);
if (theme !== "sakura") await choose(settings, 'Appearance', mode);
await choose(settings, theme, mode);
backgrounds.add(await expectAppearance(theme, mode));
assert.deepEqual(await editorIds(), before, "Existing Monaco editors keep their identity when a theme changes");
await openCode(nextCode++);
@@ -154,10 +154,10 @@ try {
}
assert.equal(backgrounds.size, 5, "All supported combinations have distinct backgrounds");
await picker(settings, 'Color theme').click();
assert.deepEqual(await settings.getByRole('menuitemradio').allTextContents(), ['RuneStone', 'Claude', 'Sakura']);
assert.deepEqual(await settings.getByRole('menuitemradio').allTextContents(), ['RuneStone Light', 'RuneStone Dark', 'Claude Light', 'Claude Dark', 'Sakura', 'Harvest Moon', 'Crimson Pilot', 'Silver Serpent']);
await settings.keyboard.press('Escape');
assert.equal(await picker(settings, 'Appearance').isDisabled(), true);
assert.equal(await picker(secondSettings, 'Appearance').isDisabled(), true);
assert.equal(await picker(settings, 'Appearance').count(), 0);
assert.equal(await picker(secondSettings, 'Appearance').count(), 0);
const sakura = await settings.evaluate(() => {
const css = getComputedStyle(document.documentElement);
return Object.fromEntries(['bg', 'border', 'selection', 'bg-active', 'syntax-parameter', 'syntax-keyword', 'syntax-local', 'syntax-static', 'syntax-instance', 'syntax-global'].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
@@ -177,14 +177,13 @@ try {
}
for (const [theme, mode] of [['default', 'dark'], ['claude', 'light'], ['claude', 'dark'], ['sakura', 'light']]) {
await settings.setViewportSize({ width: 1100, height: 780 });
await choose(settings, 'Color theme', theme);
if (theme !== 'sakura') await choose(settings, 'Appearance', mode);
await choose(settings, theme, mode);
await expectAppearance(theme, mode);
await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), 'Narrow settings do not overflow the viewport');
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Appearance controls do not overflow the content area');
for (const name of ['Color theme', 'Appearance']) {
for (const name of ['Color theme']) {
const control = picker(settings, name);
await control.scrollIntoViewIfNeeded();
const bounds = await control.boundingBox();
+60 -3
View File
@@ -1,14 +1,71 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { parseAppearance, normalizeAppearance, THEMES } from '../src/lib/theme/appearance.ts';
import { parseCustomTheme } from '../src/lib/theme/customThemes.ts';
import { CHARACTER_THEMES, SYNTAX_ROLES } from '../src/lib/theme/characterThemes.ts';
import { parseAppearance, normalizeAppearance, exportAppearanceTheme, BUILTIN_THEMES, THEMES, themeModes } from '../src/lib/theme/appearance.ts';
test('Removed palettes preserve the saved mode with the default palette', () => {
for (const theme of ['gpt', 'terminal', 'unknown']) {
for (const theme of ['gpt', 'terminal', 'unknown', 'renamon', 'asuka-school']) {
for (const mode of ['light', 'dark'] as const) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme: 'default', mode });
}
}
assert.deepEqual(THEMES, ['default', 'claude', 'sakura']);
assert.deepEqual(THEMES, ['default', 'claude', 'sakura', 'harvest-moon', 'crimson-pilot', 'silver-serpent']);
assert.deepEqual(BUILTIN_THEMES.map(theme => theme.id), THEMES);
});
test('Renamed palettes preserve saved choices and backgrounds', () => {
const newTabBackground = { imageId: '01234567-89ab-cdef-0123-456789abcdef', position: 'top left', size: 'auto', overlay: -0.4 };
for (const [previous, theme] of [['holo', 'harvest-moon'], ['asuka', 'crimson-pilot'], ['malfoid', 'silver-serpent']]) {
for (const mode of ['light', 'dark']) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme: previous, mode, newTabBackground })), { theme, mode: 'dark', newTabBackground });
}
}
for (const theme of ['constructor', '__proto__', 'toString']) {
assert.deepEqual(normalizeAppearance({ theme, mode: 'light' }), { theme: 'default', mode: 'light' });
}
});
test('Removed character themes retain the saved background', () => {
const newTabBackground = { imageId: '01234567-89ab-cdef-0123-456789abcdef', position: 'top left', size: 'auto', overlay: -0.4 };
for (const theme of ['renamon', 'asuka-school']) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode: 'light', newTabBackground })), { theme: 'default', mode: 'light', newTabBackground });
}
});
function luminance(color: string) {
const rgb = color.slice(1).match(/../g)!.map(value => parseInt(value, 16) / 255)
.map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4);
return rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722;
}
function contrast(foreground: string, background: string) {
const values = [luminance(foreground), luminance(background)].sort((a, b) => b - a);
return (values[0] + 0.05) / (values[1] + 0.05);
}
test('Character palettes restore one appearance and export readable surfaces and syntax', () => {
for (const theme of Object.keys(CHARACTER_THEMES) as (keyof typeof CHARACTER_THEMES)[]) {
const exported = exportAppearanceTheme(theme);
for (const mode of ['light', 'dark'] as const) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme, mode: CHARACTER_THEMES[theme].mode });
const colors = exported[mode];
for (const foreground of ['text', 'text-dim', 'text-strong', 'accent'] as const) {
for (const background of ['bg', 'bg-elevated', 'bg-active', 'selection'] as const) {
if (foreground === 'accent' && background === 'selection') continue;
assert(contrast(colors[foreground]!, colors[background]!) >= 4.5, `${theme} ${mode}: ${foreground} on ${background}`);
}
}
}
assert.deepEqual(themeModes(theme), [CHARACTER_THEMES[theme].mode]);
assert.deepEqual(exported.light, exported.dark);
assert.deepEqual(parseCustomTheme(exported), exported);
for (const role of SYNTAX_ROLES) {
for (const background of ['bg', 'bg-active'] as const) {
assert(contrast(exported.light[`syntax-${role}`]!, exported.light[background]!) >= 4.5, `${theme}: ${role} on ${background}`);
}
}
assert(new Set(SYNTAX_ROLES.map(role => exported.light[`syntax-${role}`])).size >= 7);
assert.notDeepEqual(exported.dark, exportAppearanceTheme('default').dark);
}
});
test('Sakura cannot restore or save a dark appearance', () => {
assert.deepEqual(parseAppearance('{"theme":"sakura","mode":"dark"}'), { theme: 'sakura', mode: 'light' });
+44
View File
@@ -0,0 +1,44 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { characterTheme, SYNTAX_ROLES } from '../src/lib/theme/characterThemes.ts';
const rgb = (color: string) => color.slice(1).match(/../g)!.map(value => parseInt(value, 16));
const mix = (foreground: string, background: string, opacity: number) => '#' + rgb(foreground)
.map((value, index) => Math.round(value * opacity + rgb(background)[index] * (1 - opacity)).toString(16).padStart(2, '0')).join('');
function luminance(color: string) {
return rgb(color).map(value => value / 255)
.map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4)
.reduce((sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index], 0);
}
function contrast(foreground: string, background: string) {
const [high, low] = [luminance(foreground), luminance(background)].sort((a, b) => b - a);
return (high + 0.05) / (low + 0.05);
}
test('Crimson Pilot text and syntax remain readable in active and selected states', () => {
const palette = characterTheme('crimson-pilot')!;
const [background, elevated, active, , dim, text, strong, accent, selection] = palette.surfaces;
const foregrounds = { dim, text, strong, accent, secondary: palette.secondary,
...Object.fromEntries(SYNTAX_ROLES.map((role, index) => [`syntax-${role}`, palette.syntax[index]])) };
for (const [role, foreground] of Object.entries(foregrounds)) {
for (const surface of [background, elevated, active, selection]) {
assert(contrast(foreground, surface) >= 4.5, `${role} on ${surface} needs 4.5:1 contrast`);
}
}
});
test('Crimson Pilot text remains readable on image-tinted editor and panel surfaces', () => {
const palette = characterTheme('crimson-pilot')!;
const [background, elevated, , , dim, text, strong] = palette.surfaces;
const editor = mix(background, '#ffffff', 0.9);
const codeBlock = mix(elevated, editor, 0.82);
const panel = mix(elevated, '#ffffff', 0.82);
for (const foreground of palette.syntax) {
for (const surface of [editor, codeBlock]) {
assert(contrast(foreground, surface) >= 4.5, `${foreground} on ${surface} needs 4.5:1 contrast`);
}
}
for (const foreground of [dim, text, strong]) {
assert(contrast(foreground, panel) >= 4.5, `${foreground} on image panel ${panel} needs 4.5:1 contrast`);
}
});
+142
View File
@@ -0,0 +1,142 @@
import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const output = '.audit/background-frames';
const report = [];
await mkdir(output, { recursive: true });
try {
for (const theme of ['light', 'dark']) {
const page = await browser.newPage({ viewport: { width: 1280, height: 820 } });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = 'C:/background-test';
const files = new Map([
['welcome.md', '# Working notes\n\nKeep the image quiet behind readable text.\n\n## Next steps\n\n- Write a note\n- Review the code\n\n' + 'A paragraph with **bold text** and a [link](https://example.com).\n\n'.repeat(24)],
['hello.ts', '// A focused code view\nexport function greet(name: string) {\n const message = `Hello ${name}`;\n return message;\n}\n'],
]);
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } }, transformCallback: () => 1, unregisterCallback() {},
invoke: async (command, args = {}) => {
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'background-test', watch_mode: 'native' };
if (command === 'workspace_list') return [...files.keys()].map(name => ({ name, rel_path: name, kind: 'file' }));
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('missing'); return files.get(args.rel); }
if (command === 'workspace_search') return [];
if (command === 'plugins_snapshot') return { root, plugins: [] };
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
});
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('.welcome-actions button').first().waitFor();
await page.getByText('background-test', { exact: true }).waitFor();
await page.evaluate(async theme => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
const { backgroundHub } = await import('/src/lib/plugins/backgrounds.ts');
const make = (first, second) => {
const canvas = document.createElement('canvas'); canvas.width = 1200; canvas.height = 800;
const ctx = canvas.getContext('2d'); const gradient = ctx.createLinearGradient(0, 0, 1200, 800);
gradient.addColorStop(0, first); gradient.addColorStop(1, second); ctx.fillStyle = gradient; ctx.fillRect(0, 0, 1200, 800);
ctx.strokeStyle = '#ffffff88'; ctx.lineWidth = 12;
for (let x = 0; x < 1400; x += 200) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x - 300, 800); ctx.stroke(); }
return canvas.toDataURL();
};
const saved = make('#bd486c', '#438f67');
saveAppearance({ theme: 'default', mode: theme, newTabBackground: { image: saved, overlay: 0.15, position: 'center', size: 'cover' } });
const urls = await Promise.all([make('#bd486c', '#438f67'), make('#286f9b', '#725ea2')].map(async url => URL.createObjectURL(await (await fetch(url)).blob())));
window.backgroundTest = { hub: backgroundHub, owner: Symbol(), urls, saved, theme };
}, theme);
const background = page.locator('.workarea-background');
assert.equal(await background.count(), 1);
assert.equal(await page.locator('.empty h1, .empty > p').count(), 0);
assert.equal(await page.locator('.empty').evaluate(node => getComputedStyle(node).backgroundImage), 'none');
const bounds = await background.boundingBox();
assert.equal(bounds.x, 0); assert.equal(bounds.y, 36); assert.equal(bounds.width, 1280); assert.equal(bounds.height, 762);
assert.match(await background.evaluate(node => getComputedStyle(node).backgroundImage), /blob:/);
assert.match(await page.locator('.left').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
assert.match(await page.locator('.right').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
assert.match(await page.locator('.welcome-actions button').first().evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
assert.doesNotMatch(await page.locator('header.header').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
await page.locator('.welcome-actions button').first().focus();
await page.keyboard.press('Tab');
assert(await page.locator('.welcome-actions').evaluate(node => node.contains(document.activeElement)));
await page.screenshot({ path: `${output}/${theme}-splash.png` });
await page.evaluate(() => {
const { hub, owner, urls } = window.backgroundTest;
hub.set(owner, 'app', { url: urls[0], blurredUrl: urls[1], overlay: 0.15, position: 'top', size: 'contain' });
});
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundSize), '100% 100%, contain, cover');
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundPosition), '50% 50%, 50% 0%, 50% 50%');
await page.screenshot({ path: `${output}/${theme}-portrait-layers.png` });
await page.setViewportSize({ width: 390, height: 700 });
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundSize), '100% 100%, contain, cover');
await page.screenshot({ path: `${output}/${theme}-portrait-layers-narrow.png` });
await page.setViewportSize({ width: 1280, height: 820 });
await page.evaluate(() => {
const { hub, owner, urls } = window.backgroundTest;
hub.set(owner, 'app', { url: urls[1], overlay: 0.2, position: 'center', size: 'cover', previous: { url: urls[0], overlay: 0.15, position: 'center', size: 'cover' }, transitionMs: 2000 });
});
await page.waitForTimeout(180);
const opacity = await background.evaluate(node => Number(getComputedStyle(node, '::after').opacity));
assert(opacity > 0 && opacity < 1, `Fade has an intermediate opacity: ${opacity}`);
await page.waitForTimeout(900);
assert.ok(await background.evaluate(node => Number(getComputedStyle(node, '::after').opacity) < 1), 'The fade remains active after one second');
await page.waitForTimeout(1100);
assert.equal(await background.evaluate(node => getComputedStyle(node, '::after').opacity), '1');
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome');
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
assert.match(await page.locator('.editor > .body').evaluate(node => getComputedStyle(node).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 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('.monaco-editor').waitFor();
assert.equal(await page.locator('.monaco-editor-background').first().evaluate(node => getComputedStyle(node).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 page.locator('.monaco-editor').waitFor();
await page.screenshot({ path: `${output}/${theme}-ide.png` });
await page.setViewportSize({ width: 680, height: 720 });
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
await page.screenshot({ path: `${output}/${theme}-ide-narrow.png` });
await page.keyboard.press('Control+t');
await page.locator('.welcome-actions').waitFor();
await page.setViewportSize({ width: 480, height: 640 });
assert(await page.locator('.empty').evaluate(node => node.scrollWidth <= node.clientWidth));
await page.screenshot({ path: `${output}/${theme}-splash-narrow.png` });
await page.emulateMedia({ reducedMotion: 'reduce' });
await page.evaluate(() => { const { hub, owner, urls } = window.backgroundTest; hub.set(owner, 'app', { url: urls[0], overlay: 0.2, position: 'center', size: 'cover', previous: { url: urls[1], overlay: 0.2, position: 'center', size: 'cover' }, transitionMs: 2000 }); });
assert.equal(await background.evaluate(node => node.getAnimations().length), 0);
await page.evaluate(() => { const { hub, owner, urls } = window.backgroundTest; hub.removeOwner(owner); urls.forEach(URL.revokeObjectURL); });
assert.equal(await page.evaluate(() => document.body.style.getPropertyValue('--rs-background-previous-image')), '');
assert.match(await background.evaluate(node => getComputedStyle(node).backgroundImage), /blob:/);
await page.evaluate(async () => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode: window.backgroundTest.theme }); });
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundImage), 'none');
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome');
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
await page.locator('.editor > .body').waitFor();
assert.equal(await page.locator('.editor > .body').evaluate(node => getComputedStyle(node).backgroundColor), await page.locator('.shell').evaluate(node => getComputedStyle(node).backgroundColor));
await page.screenshot({ path: output + '/' + theme + '-removed.png' });
assert.deepEqual(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' });
await page.close();
console.log(`PASS: ${theme} workarea backgrounds, editors, keyboard, narrow layout, fade, and restoration`);
}
await writeFile(`${output}/report.json`, JSON.stringify(report, null, 2));
} finally { await browser.close(); }
+155
View File
@@ -0,0 +1,155 @@
import test from 'node:test';
import { readFileSync } from 'node:fs';
import assert from 'node:assert/strict';
import { BackgroundHub, backgroundHub } from '../src/lib/plugins/backgrounds.ts';
import { ExternalSession } from '../src/lib/plugins/externalSession.ts';
import type { BackgroundFrame, PluginApi } from '../src/lib/plugins/sdk.ts';
const frame: BackgroundFrame = { url: 'blob:http://localhost/example', overlay: 0.3, position: 'center', size: 'cover' };
test('frames retain ownership, reveal earlier owners, and cannot mutate hub state', () => {
const hub = new BackgroundHub(() => undefined);
const first = Symbol(), second = Symbol();
const events: string[] = [];
hub.subscribe(target => events.push(target));
hub.set(first, 'pm-all', frame);
const received = hub.get('pm-all')!;
received.url = 'blob:changed';
assert.equal(hub.get('pm-all')!.url, frame.url);
hub.set(second, 'pm-all', { ...frame, overlay: -0.4 });
hub.set(first, 'app', frame);
assert.equal(hub.get('pm-all')!.overlay, -0.4);
hub.removeOwner(second);
assert.equal(hub.get('pm-all')!.overlay, 0.3);
hub.removeOwner(first);
assert.equal(hub.get('pm-all'), null);
assert.equal(hub.get('app'), null);
assert.deepEqual(events, ['pm-all', 'pm-all', 'app', 'pm-all', 'pm-all', 'app']);
});
test('app override uses body properties and removes them without changing current root appearance', () => {
const root = new Map([['--rs-background-image', 'saved image']]);
const properties = new Map<string, string>();
const style = {
getPropertyValue: (key: string) => properties.get(key) ?? '',
getPropertyPriority: () => '',
setProperty: (key: string, value: string) => properties.set(key, value),
removeProperty: (key: string) => { properties.delete(key); },
};
const hub = new BackgroundHub(() => ({ style }) as unknown as HTMLElement);
const owner = Symbol();
hub.set(owner, 'app', frame);
assert.match(properties.get('--rs-background-image')!, /blob:http/);
assert.equal(properties.get('--rs-workarea-surface-opacity'), '82%');
assert.equal(properties.get('--rs-workarea-plugin-bg'), 'transparent');
root.set('--rs-background-image', 'new saved image');
hub.set(owner, 'app', { ...frame, overlay: -0.5, size: 'contain' });
assert.match(properties.get('--rs-background-image')!, /255,255,255,0.5/);
hub.removeOwner(owner);
assert.equal(properties.size, 0);
assert.equal(root.get('--rs-background-image'), 'new saved image');
});
test('invalid frames and targets do not enter the hub', () => {
const hub = new BackgroundHub(() => undefined), owner = Symbol();
for (const target of ['pm-board:../../x', 'unknown', 'pm-board:']) assert.throws(() => hub.set(owner, target, frame), /target/);
for (const invalid of [{ ...frame, url: 'https://example.com/image.png' }, { ...frame, blurredUrl: 'https://example.com/image.png' }, { ...frame, blurredUrl: 'blob:bad")' }, { ...frame, overlay: NaN }, { ...frame, overlay: 2 }, { ...frame, url: 'blob:bad")' }]) {
assert.throws(() => hub.set(owner, 'app', invalid), /frame/);
}
hub.set(owner, 'pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1', frame);
hub.removeOwner(owner);
});
test('portrait frames retain a contained foreground and cover underlay through transitions and cleanup', () => {
const properties = new Map<string, string>();
const style = { getPropertyValue: (key: string) => properties.get(key) ?? '', getPropertyPriority: () => '',
setProperty: (key: string, value: string) => properties.set(key, value), removeProperty: (key: string) => properties.delete(key) };
const hub = new BackgroundHub(() => ({ style }) as unknown as HTMLElement), owner = Symbol();
hub.set(owner, 'app', { ...frame, size: 'contain', blurredUrl: 'blob:blurred', previous: frame, transitionMs: 2000 });
assert.equal(properties.get('--rs-background-layer-sizes'), '100% 100%, contain, cover');
assert.equal(properties.get('--rs-background-layer-positions'), 'center, center, center');
assert.equal(properties.get('--rs-background-previous-layer-sizes'), '100% 100%, cover');
assert.match(properties.get('--rs-background-image')!, /blob:blurred/);
const received = hub.get('app')!;
received.blurredUrl = 'blob:changed';
assert.equal(hub.get('app')!.blurredUrl, 'blob:blurred');
hub.removeOwner(owner);
assert.equal(properties.size, 0);
});
test('fade frames validate previous images and keep nested data private', () => {
const hub = new BackgroundHub(() => undefined), owner = Symbol();
const fading = { ...frame, previous: { ...frame, url: 'blob:previous' }, transitionMs: 800 };
hub.set(owner, 'pm-all', fading);
fading.previous.url = 'blob:mutated';
const received = hub.get('pm-all')!;
assert.equal(received.previous!.url, 'blob:previous');
received.previous!.url = 'blob:changed';
assert.equal(hub.get('pm-all')!.previous!.url, 'blob:previous');
for (const invalid of [
{ ...frame, previous: { ...frame, url: 'https://example.com/image.png' } },
{ ...frame, transitionMs: NaN }, { ...frame, transitionMs: -1 }, { ...frame, transitionMs: 5001 },
]) assert.throws(() => hub.set(owner, 'pm-all', invalid), /frame/);
});
test('subscriber errors do not prevent frame cleanup or remaining notifications', () => {
const hub = new BackgroundHub(() => undefined), owner = Symbol();
let events = 0;
hub.subscribe(() => { throw new Error('Subscriber failure'); });
hub.subscribe(() => { events++; });
hub.set(owner, 'pm-all', frame);
hub.removeOwner(owner);
assert.equal(events, 2);
assert.equal(hub.get('pm-all'), null);
});
test('disable removes frames and subscriptions before cleanup and rejects pending file results', async () => {
let api!: PluginApi;
let finishRead!: (value: Uint8Array) => void;
let finishList!: (value: { name: string }[]) => void;
let finishPicker!: (value: string | null) => void;
const session = new ExternalSession('org.test.backgrounds', {
workspace: { list: async () => [], read: async () => '', write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
backgrounds: {
chooseFolder: () => new Promise(resolve => { finishPicker = resolve; }),
list: () => new Promise(resolve => { finishList = resolve; }),
read: () => new Promise(resolve => { finishRead = resolve; }),
},
}, () => {}, () => {});
let notifications = 0;
await session.start({ activate(value) {
api = value;
api.backgrounds!.subscribe(() => { notifications++; });
api.backgrounds!.set('app', frame);
api.backgrounds!.set('pm-all', frame);
api.onDispose(() => {
assert.equal(backgroundHub.get('app'), null);
assert.equal(backgroundHub.get('pm-all'), null);
assert.throws(() => api.backgrounds!.get('app'), /disabled/);
});
} });
const pending = [api.backgrounds!.read('folder', 'file.png'), api.backgrounds!.list('folder'), api.backgrounds!.chooseFolder()];
const rejected = pending.map(request => assert.rejects(request, /disabled/));
await session.stop();
finishRead(new Uint8Array([1])); finishList([{ name: 'file.png' }]); finishPicker('folder');
await Promise.all(rejected);
assert.equal(notifications, 2);
assert.throws(() => api.backgrounds!.set('app', frame), /disabled/);
assert.throws(() => api.backgrounds!.read('folder', 'file.png'), /disabled/);
assert.throws(() => api.backgrounds!.subscribe(() => {}), /disabled/);
assert.equal(backgroundHub.get('app'), null);
});
test('background commands are allowed in main and settings windows', () => {
const build = readFileSync(new URL('../src-tauri/build.rs', import.meta.url), 'utf8');
for (const scope of ['default', 'settings']) {
const capability = JSON.parse(readFileSync(new URL(`../src-tauri/capabilities/${scope}.json`, import.meta.url), 'utf8'));
for (const command of ['backgrounds_choose_folder', 'backgrounds_default_folder', 'backgrounds_list', 'backgrounds_read', 'backgrounds_read_image_settings', 'backgrounds_write_image_settings']) {
assert(build.includes(`"${command}"`), `${command} needs a generated desktop permission`);
assert(capability.permissions.includes(`allow-${command.replaceAll('_', '-')}`), `${scope} must allow ${command}`);
}
}
});
+153
View File
@@ -0,0 +1,153 @@
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
const runtime = path.resolve('browser-runtime');
const require = createRequire(path.join(runtime, 'package.json'));
const { chromium } = require('playwright');
const electron = require('electron');
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
let sequence = 0, page, pendingFrame, painting = false;
const pending = new Map();
const commands = [];
const rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
async function paint() {
if (painting || !page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await page.evaluate(value => window.browserEmit?.('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
const ready = new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && page) void page.evaluate(value => window.browserEmit?.('browser-state', value), message.event).catch(() => {});
});
});
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
const errors = [];
try {
await ready;
page = await browser.newPage({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: Number(process.env.BROWSER_TEST_SCALE || 1) });
page.on('pageerror', error => errors.push(error.message));
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
await page.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map(), listeners = new Map(); let next = 0;
window.browserEmit = (event, payload) => { for (const [id, entry] of listeners) if (entry.event === event) callbacks.get(entry.handler)?.({ event, id, payload }); };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') { const id = ++next; listeners.set(id, args); return id; }
if (command === 'plugin:event|unlisten') { listeners.delete(args.eventId); return; }
if (command === 'browser_connect') return 'test-session';
if (command === 'browser_stop' || command === 'plugins_release') return;
if (command === 'browser_request') return window.browserRpc(args.command, args.args);
if (command === 'workspace_last_path') return null;
if (command === 'workspace_recent') return [];
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
if (command.startsWith('plugin:window|')) return false;
throw Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => listeners.delete(id) };
});
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1451');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
await page.locator('[data-browser-state="ready"]').waitFor();
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
const evaluate = code => rpc('testEvaluate', { tabId, code });
async function expectRemote(code, expected) {
for (let attempt = 0; attempt < 100; attempt++) {
if (await evaluate(code) === expected) return;
await page.waitForTimeout(50);
}
assert.equal(await evaluate(code), expected);
}
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><textarea id="other" style="position:absolute;left:40px;top:140px;width:300px;height:80px"></textarea><div id="rich" contenteditable="true" style="position:absolute;left:40px;top:280px;width:300px;height:80px;border:1px solid">Rich text</div>'; true;`);
await page.locator('.surface img').waitFor();
await page.waitForTimeout(300);
const box = await surface.boundingBox();
await page.mouse.click(box.x + 100, box.y + 60);
await page.waitForTimeout(150);
assert.deepEqual(await evaluate('({active:document.activeElement.id,focused:document.hasFocus()})'), { active: 'typing', focused: true });
await mkdir('.audit/browser-fields', { recursive: true });
await page.waitForFunction(() => {
const image = document.querySelector('.surface img');
if (!image?.complete || !image.naturalWidth) return false;
const surface = document.querySelector('.surface');
const ratio = image.naturalWidth / surface.clientWidth;
const canvas = document.createElement('canvas'); canvas.width = 12; canvas.height = 28;
const context = canvas.getContext('2d');
context.drawImage(image, 42 * ratio, 46 * ratio, 12 * ratio, 28 * ratio, 0, 0, 12, 28);
const pixels = context.getImageData(0, 0, 12, 28).data;
let dark = 0;
for (let offset = 0; offset < pixels.length; offset += 4) if (pixels[offset] < 100 && pixels[offset + 1] < 100 && pixels[offset + 2] < 100) dark++;
return dark >= 8;
}, null, { timeout: 5000, polling: 50 });
await page.screenshot({ path: `.audit/browser-fields/caret-${process.env.BROWSER_TEST_SCALE || 1}x.png` });
await page.getByRole('textbox', { name: 'Address or search' }).focus();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.hasFocus()'), false, 'The toolbar removes focus from the page');
await page.mouse.click(box.x + 100, box.y + 60);
await page.waitForTimeout(100);
assert.equal(await evaluate('document.hasFocus()'), true, 'A page click restores focus');
await page.keyboard.type('Hello World!');
await expectRemote('document.querySelector("#typing").value', 'Hello World!');
await page.mouse.move(box.x + 50, box.y + 60);
await page.mouse.down();
await page.mouse.move(box.x + 100, box.y + 60, { steps: 8 });
await page.mouse.up();
await page.waitForTimeout(200);
assert(await evaluate('document.querySelector("#typing").selectionEnd > document.querySelector("#typing").selectionStart'), 'Dragging selects text in the embedded field');
await page.mouse.click(box.x + 100, box.y + 170);
await page.keyboard.type('Second field');
await expectRemote('document.querySelector("#other").value', 'Second field');
await page.mouse.click(box.x + 100, box.y + 310);
await page.keyboard.press('Control+a');
await page.keyboard.type('Edited rich text');
await expectRemote('document.querySelector("#rich").textContent', 'Edited rich text');
await evaluate(`document.body.insertAdjacentHTML('beforeend', '<iframe id="frame" style="position:absolute;left:40px;top:390px;width:300px;height:100px" srcdoc="<input id=framed style=width:200px;height:40px>"></iframe>'); true;`);
await page.waitForTimeout(200);
await page.mouse.click(box.x + 100, box.y + 415);
await page.keyboard.type('Frame input');
await expectRemote('document.querySelector("#frame").contentDocument.querySelector("#framed").value', 'Frame input');
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), true);
await page.getByRole('textbox', { name: 'Address or search' }).focus();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), false);
await rpc('navigate', { tabId, input: 'about:blank' });
await page.waitForTimeout(100);
await evaluate(`document.body.innerHTML='<input id="after-navigation" style="position:absolute;left:40px;top:40px;width:300px;height:40px">'; true;`);
await page.waitForTimeout(400);
await page.mouse.click(box.x + 100, box.y + 60);
await page.keyboard.type('After navigation');
await page.waitForTimeout(500);
assert.equal(await evaluate('devicePixelRatio'), Number(process.env.BROWSER_TEST_SCALE || 1), 'Navigation preserves the host pixel ratio');
await expectRemote('document.querySelector("#after-navigation").value', 'After navigation');
assert.equal(await evaluate('document.hasFocus()'), true);
assert.deepEqual(errors, []);
console.log('PASS: visible caret, page focus, toolbar blur, input, textarea, contenteditable, iframe and navigation');
} finally {
await browser.close();
await rpc('shutdown').catch(() => {}); child.kill();
}
+5 -4
View File
@@ -74,7 +74,8 @@ async function selectProfile(id) {
await profile.click();
await page.getByRole('menuitemradio', { name: id === 'work' ? 'Work' : 'Personal', exact: true }).click();
}
const kind = section.getByRole('combobox', { name: 'Web data type', exact: true });
const kind = section.getByRole('button', { name: 'Web data type', exact: true });
async function selectKind(value) { await kind.click(); await page.getByRole('menuitemradio', { name: value === 'cookies' ? 'Cookies' : 'History', exact: true }).click(); }
const filter = section.getByRole('searchbox', { name: 'Filter web data', exact: true });
const refresh = section.getByRole('button', { name: 'Refresh', exact: true });
const personalCookie = () => section.getByRole('button', { name: 'Remove cookie session from personal.example at /account', exact: true });
@@ -109,7 +110,7 @@ try {
await settle();
await section.getByText('No matching cookies.', { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.webDataTest.data.work.cookies.length), 1, 'Removing a cookie preserves another profile with the same ID');
await kind.selectOption('history');
await selectKind('history');
await filter.fill('GUIDE');
await section.getByRole('button', { name: 'Remove history entry Personal guide', exact: true }).click();
await settle();
@@ -122,7 +123,7 @@ try {
await settle();
assert.equal(await filter.inputValue(), '', 'Profile changes clear the prior filter');
await section.getByText('Work guide', { exact: true }).waitFor();
await kind.selectOption('cookies');
await selectKind('cookies');
await workCookie().waitFor();
// A delayed successful response from the previous profile must not replace the current rows.
@@ -188,7 +189,7 @@ try {
}, theme);
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), theme === 'light' ? '#f3f3f3' : '#141414');
for (const dataType of ['cookies', 'history']) {
await kind.selectOption(dataType);
await selectKind(dataType);
await section.scrollIntoViewIfNeeded();
await page.screenshot({ path: `.audit/cards-2026-10-08-next/browser-web-data-${dataType}-${theme}.png` });
const overflow = await section.evaluate(node => {
+4 -3
View File
@@ -26,7 +26,7 @@ if (process.platform !== 'win32') throw Error('Build the Windows installer on Wi
const artifactDir = path.join(root, 'src-tauri/target/release/bundle/nsis');
const artifact = path.join(artifactDir, `RuneStone_${next.version}_x64-setup.exe`);
const internalArtifact = path.join(artifactDir, `RuneStone_${next.toolchain}_x64-setup.exe`);
const releaseDir = path.join(root, 'output/releases', next.version);
const releaseDir = path.join(root, 'releases', next.version);
const releaseArtifact = path.join(releaseDir, path.basename(artifact));
const metadataPath = path.join(releaseDir, 'host.json');
for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) if (await exists(file)) throw Error('The release file already exists: ' + file);
@@ -75,15 +75,16 @@ try {
await fs.copyFile(artifact, releaseArtifact, 1);
const bytes = await fs.readFile(releaseArtifact);
const metadata = { version: next.version, toolchainVersion: next.toolchain, windowsVersion: next.windows,
source: artifact, path: releaseArtifact, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
source: releaseArtifact, path: releaseArtifact, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
await fs.unlink(artifact);
complete = true;
console.log('Installer available: ' + releaseArtifact);
} finally {
if (!complete) {
for (let i = 0; i < files.length; i++) await fs.writeFile(files[i], before[i]);
for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) {
if (await exists(file)) await fs.rename(file, file + '.failed-' + Date.now());
if (await exists(file)) await fs.rename(file, path.join(staging, path.basename(file) + '.failed-' + Date.now()));
}
}
}
+1 -1
View File
@@ -16,4 +16,4 @@ execFileSync(process.execPath, [formulasBuild], { cwd: formulasRoot, stdio: "inh
const formulasOutput = resolve(root, "plugin-packages/table-formulas");
await mkdir(formulasOutput, { recursive: true });
await cp(resolve(formulasRoot, "dist/plugin"), formulasOutput, { recursive: true });
console.log(await packagePlugin(formulasOutput, resolve(root, "plugin-packages")));
console.log(await packagePlugin(formulasOutput, resolve(formulasRoot, "releases")));
+6 -3
View File
@@ -64,7 +64,9 @@ try {
await page.getByRole('textbox', { name: 'Address or search' }).fill('https://example.com');
await page.getByRole('textbox', { name: 'Address or search' }).press('Enter');
await page.waitForFunction(() => window.builtinCheck.commands.includes('navigate'));
assert.equal(await page.getByRole('combobox', { name: 'Browser profile' }).inputValue(), 'user');
await page.getByRole('button', { name: 'Browser profile' }).click();
assert.equal(await page.getByRole('menuitemradio', { checked: true }).count(), 1);
await page.keyboard.press('Escape');
await page.evaluate(async () => { window.builtinCheck.legacy = true; const { refreshPlugins } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); await refreshPlugins(); });
assert.equal(await page.evaluate(() => window.builtinCheck.loads.includes('runestone.browser')), false);
await page.evaluate(async () => { window.builtinCheck.removed = true; const { refreshPlugins } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); await refreshPlugins(); });
@@ -87,7 +89,7 @@ try {
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:5174') + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await page.getByRole('button', { name: 'Save browser settings' }).waitFor({ state: 'visible' });
assert.equal(await page.getByRole('combobox', { name: 'Profile', exact: true }).inputValue(), 'user');
assert.match(await page.getByRole('button', { name: 'Profile', exact: true }).innerText(), /Existing user/);
await page.setViewportSize({ width: 360, height: 800 });
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
@@ -97,10 +99,11 @@ try {
assert.deepEqual(errors, []);
console.log('Built-in browser, legacy package independence, same-tab replacement and plugin sidebar checks passed.');
} catch (error) {
console.error(error);
console.error(await page.evaluate(async () => {
const m = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
const read = store => { let value; store.subscribe(x => value = x)(); return value; };
return { state: window.builtinCheck, text: document.body.innerText, errors: read(m.externalErrors), views: read(m.pluginEditors), tools: read(m.pluginTools) };
}), errors);
}).catch(reason => ({ diagnosticError: String(reason) })), errors);
throw error;
} finally { await browser.close(); }
+231
View File
@@ -0,0 +1,231 @@
import assert from 'node:assert/strict';
import { mkdir } from 'node:fs/promises';
import { createRequire } from 'node:module';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const output = '.audit/character-themes';
const errors = [];
await mkdir(output, { recursive: true });
try {
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === 'plugins_snapshot') return { root: 'C:/theme-smoke-plugins', plugins: [] };
if (command === 'workspace_last_path') return 'C:\\theme-smoke';
if (command === 'workspace_open') return { root: 'C:\\theme-smoke', name: 'theme-smoke', watch_mode: 'native' };
if (command === 'workspace_list') return [{ name: 'Theme.md', rel_path: 'Theme.md', kind: 'file' }, { name: 'Theme.py', rel_path: 'Theme.py', kind: 'file' }];
if (command === 'workspace_read' && args.rel === 'Theme.py') return '# Character colors\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n';
if (command === 'workspace_read') return '# Theme sample\n\nA calm surface with readable text.\n\n[Link](https://example.com)\n';
if (command === 'workspace_search') return [];
if (command === 'theme_export') { window.exportedTheme = JSON.parse(args.contents); return 'C:\\theme-smoke\\my-theme.json'; }
if (command === 'plugin:event|listen') return args.handler;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage();
const settings = await context.newPage();
const ide = await context.newPage();
const fontSession = await context.newCDPSession(settings);
await fontSession.send('DOM.enable');
await fontSession.send('CSS.enable');
for (const page of [main, settings, ide]) page.on('pageerror', error => errors.push(error.message));
await main.goto(origin);
await main.getByText('theme-smoke', { exact: true }).waitFor();
await main.keyboard.press('Control+p');
await main.getByRole('textbox', { name: 'Find a file' }).fill('Theme.md');
await main.getByRole('textbox', { name: 'Find a file' }).press('Enter');
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await ide.goto(origin);
await ide.getByText('theme-smoke', { exact: true }).waitFor();
await ide.keyboard.press('Control+p');
await ide.getByRole('textbox', { name: 'Find a file' }).fill('Theme.py');
await ide.getByRole('textbox', { name: 'Find a file' }).press('Enter');
await ide.locator('.monaco-editor textarea').waitFor();
const editorIds = () => ide.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
return monaco.editor.getEditors().filter(editor => editor.getDomNode()?.isConnected).map(editor => editor.getId());
});
const initialEditors = await editorIds();
const openSettings = async () => {
await settings.goto(`${origin}/?settingsWindow=true`);
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await settings.getByRole('img', { name: 'Color theme preview' }).waitFor();
};
const picker = name => settings.locator('.picker').and(settings.getByRole('button', { name, exact: true }));
const choose = async (name, value) => {
await picker(name).click();
await settings.getByRole('menuitemradio', { name: value, exact: true }).click();
};
await openSettings();
await picker('Color theme').click();
assert.equal(await settings.getByRole('menuitemradio', { name: 'Renamon', exact: true }).count(), 0);
assert.equal(await settings.getByRole('menuitemradio', { name: 'Asuka School Uniform', exact: true }).count(), 0);
for (const label of ['Holo', 'Asuka Langley Soryu', 'Malfoid']) {
assert.equal(await settings.getByRole('menuitemradio', { name: label, exact: true }).count(), 0);
}
await settings.keyboard.press('Escape');
const cases = [
['harvest-moon', 'Harvest Moon', 'dark', { ui: 'Candara', prose: 'Constantia', heading: 'Constantia' }],
['crimson-pilot', 'Crimson Pilot', 'dark', { ui: 'Bahnschrift', prose: 'Segoe UI', heading: 'Bahnschrift' }],
['silver-serpent', 'Silver Serpent', 'dark', { ui: 'Corbel', prose: 'Palatino Linotype', heading: 'Palatino Linotype' }],
];
for (const [theme, label, mode, expectedFonts] of cases) {
await settings.setViewportSize({ width: 1100, height: 780 });
const variant = label;
await choose('Color theme', variant);
for (const page of [main, settings, ide]) {
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
}
const colors = await settings.evaluate(async theme => {
const { exportAppearanceTheme } = await import('/src/lib/theme/appearance.ts');
return exportAppearanceTheme(theme);
}, theme);
const actual = await settings.evaluate(keys => {
const css = getComputedStyle(document.documentElement);
return Object.fromEntries(keys.map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
}, Object.keys(colors[mode]));
assert.deepEqual(actual, colors[mode]);
const fonts = await settings.evaluate(() => {
const css = getComputedStyle(document.documentElement);
return { ui: css.getPropertyValue('--rs-font-ui'), prose: getComputedStyle(document.querySelector('.preview-prose')).fontFamily,
heading: getComputedStyle(document.querySelector('.preview-document strong')).fontFamily,
code: getComputedStyle(document.querySelector('.preview-code')).fontFamily };
});
for (const key of ['ui', 'prose', 'heading']) assert(fonts[key].includes(expectedFonts[key]), `${theme}: ${key} uses its font`);
assert(fonts.code.includes('Cascadia Mono'), 'Code retains the shared monospace font');
const { root } = await fontSession.send('DOM.getDocument');
const { nodeId } = await fontSession.send('DOM.querySelector', { nodeId: root.nodeId, selector: '.preview-prose' });
const rendered = await fontSession.send('CSS.getPlatformFontsForNode', { nodeId });
assert(rendered.fonts.some(item => item.glyphCount > 0), 'The font renders visible glyphs');
console.log(`${theme} rendered fonts: ${rendered.fonts.map(item => item.familyName).join(', ')}`);
await settings.getByRole('button', { name: 'Export theme template' }).click();
assert.deepEqual(await settings.evaluate(() => window.exportedTheme), colors);
await ide.waitForFunction(expected => {
const spans = [...document.querySelectorAll('.view-line span')].filter(node => !node.children.length);
return Object.entries(expected).every(([text, color]) => {
const node = spans.find(node => node.textContent.replaceAll('\u00a0', ' ').includes(text));
const probe = document.createElement('i');
probe.style.color = color; document.body.append(probe);
const target = getComputedStyle(probe).color; probe.remove();
return node && getComputedStyle(node).color === target;
});
}, { return: colors[mode]['syntax-keyword'], RuneStone: colors[mode]['syntax-string'], 42: colors[mode]['syntax-number'], print: colors[mode]['syntax-keyword'], '# Character colors': colors[mode]['syntax-comment'] });
assert.deepEqual(await editorIds(), initialEditors, 'Theme changes preserve the editor');
if (theme === 'harvest-moon') {
const normalized = await settings.evaluate(async () => {
const { normalizeAppearance } = await import('/src/lib/theme/appearance.ts');
return normalizeAppearance({ theme: 'harvest-moon', mode: 'light' });
});
assert.equal(normalized.mode, 'dark', 'Harvest Moon keeps its fixed dark appearance');
await main.locator('[data-tree-rel="Theme.md"]').click();
const selectedRow = await main.locator('[data-tree-rel="Theme.md"]').evaluate(node => {
const css = getComputedStyle(node);
return { selected: node.getAttribute('aria-selected'), fill: css.backgroundColor,
selection: getComputedStyle(document.documentElement).getPropertyValue('--rs-item-selection-bg').trim() };
});
assert.equal(selectedRow.selected, 'true');
assert.equal(selectedRow.selection, colors[mode].selection, 'File selection uses the same warm selection color');
assert.equal(selectedRow.fill, 'rgb(72, 39, 20)', 'The selected file paints the warm fill');
await main.screenshot({ path: `${output}/${theme}-${mode}-file-selection.png` });
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate(node => {
node.focus();
const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);
let text;
while ((text = walker.nextNode()) && !text.textContent.includes('A calm surface')) {}
const range = document.createRange(); range.selectNodeContents(text);
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
});
assert.equal(await main.evaluate(() => window.getSelection().toString()), 'A calm surface with readable text.');
await main.screenshot({ path: `${output}/${theme}-${mode}-writer-selection.png` });
await ide.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
editor.setSelection(new monaco.Selection(1, 1, 3, 21)); editor.focus();
});
await ide.locator('.selected-text').first().waitFor();
assert.equal(await ide.locator('.selected-text').first().evaluate(node => getComputedStyle(node).backgroundColor),
'rgb(72, 39, 20)', 'IDE selection uses the same warm fill');
await ide.screenshot({ path: `${output}/${theme}-${mode}-ide-selection.png` });
await ide.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected).setPosition({ lineNumber: 1, column: 1 });
});
}
await ide.screenshot({ path: `${output}/${theme}-${mode}-ide.png` });
await settings.screenshot({ path: `${output}/${theme}-${mode}-settings.png` });
await main.screenshot({ path: `${output}/${theme}-${mode}-document.png` });
await settings.reload();
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
assert.equal((await picker('Color theme').textContent()).trim(), variant);
await settings.setViewportSize({ width: 360, height: 480 });
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Narrow settings fit the content area');
await picker('Color theme').scrollIntoViewIfNeeded();
await picker('Color theme').focus();
await settings.keyboard.press('Enter');
const current = settings.getByRole('menuitemradio', { name: variant, exact: true });
await current.waitFor();
assert.equal(await current.getAttribute('aria-checked'), 'true');
assert(await current.evaluate(node => document.activeElement === node), 'The menu focuses the current theme');
const bounds = await settings.getByRole('menu', { name: 'Color theme', exact: true }).boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.y >= 0 && bounds.y + bounds.height <= 480, 'The menu stays within the viewport');
await settings.screenshot({ path: `${output}/${theme}-${mode}-360-menu.png` });
await settings.keyboard.press('ArrowDown');
await settings.keyboard.press('ArrowUp');
assert(await current.evaluate(node => document.activeElement === node));
await settings.keyboard.press('Escape');
assert(await picker('Color theme').evaluate(node => document.activeElement === node), 'Dismissal returns focus');
await settings.screenshot({ path: `${output}/${theme}-${mode}-360-focus.png` });
await settings.evaluate(async () => {
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
pluginTools.set(Array.from({ length: 16 }, (_, index) => ({ owner: 'org.example.theme-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
});
const navigation = settings.locator('dialog aside');
const bodyBounds = await settings.locator('dialog .body').boundingBox();
assert((await navigation.boundingBox()).height <= bodyBounds.height * 0.4 + 1, 'Long plugin navigation leaves room for settings');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth));
await settings.getByRole('button', { name: 'Plugin settings 16', exact: true }).scrollIntoViewIfNeeded();
await settings.screenshot({ path: `${output}/${theme}-${mode}-360-long-navigation.png` });
await settings.evaluate(async () => { const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); pluginTools.set([]); });
console.log(`PASS: ${theme} ${mode}, colors, fonts, IDE syntax, export, saved state, window sync, narrow menu, 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 => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode: 'dark' })), previous);
await openSettings();
assert.equal((await picker('Color theme').textContent()).trim(), label);
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), theme);
await choose('Color theme', label);
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).theme), theme);
}
for (const [removed, mode] of [['renamon', 'light'], ['asuka-school', 'dark']]) {
await settings.evaluate(({ theme, mode }) => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode })), { theme: removed, mode });
await settings.setViewportSize({ width: 1100, height: 780 });
await openSettings();
for (const page of [main, settings, ide]) {
await page.waitForFunction(mode => document.documentElement.dataset.palette === 'default' && document.documentElement.dataset.theme === mode, mode);
}
assert.equal((await picker('Color theme').textContent()).trim(), `RuneStone ${mode === 'light' ? 'Light' : 'Dark'}`);
assert((await settings.evaluate(() => getComputedStyle(document.body).fontFamily)).includes('Segoe UI'), 'The default font returns after a palette change');
await settings.screenshot({ path: `${output}/${removed}-fallback-${mode}-settings.png` });
await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.locator('dialog .content').evaluate(node => node.scrollWidth <= node.clientWidth));
await settings.screenshot({ path: `${output}/default-${mode}-360-settings.png` });
console.log(`PASS: ${removed} saved appearance restores RuneStone ${mode}`);
}
assert.deepEqual(errors, []);
console.log('Character theme smoke passed.');
} catch (error) {
console.error('Page errors:', errors);
for (const context of browser.contexts()) {
for (const [index, page] of context.pages().entries()) await page.screenshot({ path: `${output}/failure-${index}.png` }).catch(() => {});
}
throw error;
} finally { await browser.close(); }
+57
View File
@@ -0,0 +1,57 @@
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 { paneBounds } from "../src/lib/workspace/splitLayout.ts";
import { registerSelection, selectedEditorText } from "../src/lib/editor/selection.ts";
test("opening a link to the right keeps its source and focuses an existing pane for duplicate targets", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b", "c"], "a");
const primary = state.active;
state = readDocumentPane(state, primary, true);
state = splitDocumentPane(state, primary, "b", "right");
assert.deepEqual(state.panes.map(pane => pane.documentId), ["a", "b"]);
assert.equal(state.active, "right");
assert.deepEqual(paneBounds(state.layout).right, { left: 50, top: 0, width: 50, height: 100 });
state = splitDocumentPane(state, "right", "a", "unused");
assert.equal(state.active, primary);
assert.equal(state.panes.length, 2);
assert.equal(state.panes[0].reading, true);
state = splitDocumentPane(state, "right", "c", "third");
assert.equal(paneBounds(state.layout).third.left, 75);
});
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");
state = closeDocumentPane(state, "right");
assert.equal(state.panes[0].documentId, "a");
assert.equal(state.layout, state.active);
state = syncDocumentPanes(state, ["a", "b"], "b");
assert.equal(state.panes[0].documentId, "b");
});
test("tab replacement stays in its focused pane, and closing another tab collapses only its empty pane", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b"], "a");
state = splitDocumentPane(state, state.active, "b", "right");
state = syncDocumentPanes(state, ["a", "c"], "c");
assert.deepEqual(state.panes.map(pane => pane.documentId), ["a", "c"]);
assert.equal(state.active, "right");
const unchanged = syncDocumentPanes(state, ["a", "c"], "c");
assert.equal(unchanged, state);
state = syncDocumentPanes(state, ["c"], "c");
assert.equal(state.panes.length, 1);
assert.equal(state.layout, "right");
assert.equal(selectPane(state, "missing"), state);
});
test("selection readers remain available in both panes and disposal cannot clear a replacement reader", () => {
const first = registerSelection("a", () => "first selection");
const second = registerSelection("b", () => "second selection");
assert.equal(selectedEditorText("a"), "first selection");
assert.equal(selectedEditorText("b"), "second selection");
const replacement = registerSelection("a", () => "new selection");
first(); second();
assert.equal(selectedEditorText("a"), "new selection");
assert.equal(selectedEditorText("b"), "");
replacement();
});
+160
View File
@@ -0,0 +1,160 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
page.on("console", message => { if (message.text().includes("binding_property_non_reactive")) errors.push(message.text()); });
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n\n\`\`\`js\nconst answer = 42;\n\`\`\`\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`]));
files.set("a.md", "# Links\n\nSelected reading text.\n\n[Web label](https://example.com/path)\n\n[[b.md|Workspace note]]\n");
files.set("a.md", "# Alpha\n\nOrigin paragraph.\n\n[[notes/b.md|Right note]]\n");
files.set("notes/b.md", "# Bravo\n\nSecond paragraph.\n\n[Relative](c.md)\n\n[[/a.md|Original note]]\n");
files.set("notes/c.md", "# Charlie\n\nThird paragraph.\n");
files.set("sample.txt", "const answer = 42;\n");
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null, opened: null, app: null, windows: [] };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
window.tabMenuTest.files = files;
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.tabMenuTest.change = (path, text) => { files.set(path, text); callbacks.get(listeners.get("workspace-event"))?.({ event: "workspace-event", id: 1, payload: { root, kind: "modify", paths: [path] } }); };
window.tabMenuTest.writes = [];
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: ["Corrected"], misspelled: args.word === "Original" };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_list") return [...(!args.rel ? [{ name: "notes", rel_path: "notes", kind: "folder" }] : []), ...[...files.keys()].filter(path => path.split("/").slice(0, -1).join("/") === (args.rel || "")).map(path => ({ name: path.split("/").at(-1), rel_path: path, kind: "file" }))];
if (command === "workspace_search") { window.tabMenuTest.searched = args.query; return []; }
if (command === "plugin:opener|open_url") { window.tabMenuTest.opened = args.url; return; }
if (command === "workspace_open_default") { window.tabMenuTest.app = args.rel; return; }
if (command === "workspace_open_window") { window.tabMenuTest.windows.push(args); return; }
if (command === "workspace_write") { if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("conflict"); files.set(args.rel, args.contents); window.tabMenuTest.writes.push(args.rel); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const output = '.audit/document-splits';
await mkdir(output, {recursive:true});
const pane = path => page.locator(`[data-document-path="${path}"]`);
const item = name => page.getByRole('menuitem',{name,exact:true});
async function openRight(path,label) {
const current = pane(path);
await current.locator('.cm-content').getByText(path === 'a.md' ? 'Origin paragraph.' : 'Second paragraph.',{exact:true}).click();
await current.locator('.cm-content').getByText(label,{exact:true}).click({button:'right'});
await item('Open to the right').click();
}
async function append(path, text) {
const target=pane(path).locator('.cm-content');
await target.click(); await page.keyboard.press('Control+End'); await page.keyboard.type(text);
}
async function text(path) { return pane(path).locator('.cm-content').evaluate(async node=> { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); return EditorView.findFromDOM(node).state.doc.toString(); }); }
async function focus(path) { await pane(path).locator('.cm-content').click(); }
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('[data-tree-rel="a.md"]').click(); await pane('a.md').locator('.cm-content').waitFor();
await append('a.md','\nLeft unsaved.');
await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
assert.equal(await page.locator('.document-pane').count(),2);
assert.match(await text('a.md'),/Left unsaved/);
await append('notes/b.md','\nRight saved.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.writes.includes('notes/b.md'));
assert.equal(await page.evaluate(()=>window.tabMenuTest.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.tabMenuTest.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('.monaco-editor').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(async()=>{const {monaco}=await import('/src/lib/editor/monacoEnv.ts');return monaco.editor.getEditors().some(editor=>editor.getModel()?.uri.path.endsWith('/b.md') && editor.hasTextFocus());}); await page.keyboard.press('Control+End'); await page.keyboard.type('\nIDE edit.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.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();
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();
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}});
});
const selections=await page.evaluate(async()=> { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); const resource=performance.getEntriesByType('resource').find(entry=>new URL(entry.name).pathname==='/src/lib/editor/selection.ts'); const {selectedEditorText}=await import(resource.name); return monaco.editor.getModels().map(model=>selectedEditorText(model.uri.path.split('/')[1])).filter(Boolean).sort(); });
assert.deepEqual(selections,['Origin','Second'],'Each pane retains its own selection');
await openRight('a.md','Right note'); assert.equal(await page.locator('.document-pane').count(),2);
await page.waitForFunction(()=>document.activeElement?.closest('[data-document-path]')?.dataset.documentPath==='notes/b.md');
await openRight('notes/b.md','Original note'); assert.equal(await page.locator('.document-pane').count(),2);
await page.waitForFunction(()=>document.activeElement?.closest('[data-document-path]')?.dataset.documentPath==='a.md');
await append('notes/b.md','\nRight still unsaved.');
for(const theme of ['light','dark']) {
await page.evaluate(async mode=> { const {saveAppearance}=await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default',mode}); },theme);
await page.screenshot({path:`${output}/two-editors-${theme}.png`});
}
await pane('notes/b.md').getByRole('button',{name:'Close split',exact:true}).click();
assert.equal(await page.locator('.document-pane').count(),1); assert.equal(await pane('a.md').count(),1);
assert.match(await text('a.md'),/Left unsaved/);
assert.equal(await page.evaluate(async()=> { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); return monaco.editor.getModels().length; }),2,'Closing a split preserves both tab models');
await page.getByRole('tab',{name:/b.md/}).click(); await pane('notes/b.md').locator('.cm-content').waitFor();
assert.match(await text('notes/b.md'),/Right still unsaved/,'The closed split retains its unsaved buffer');
await page.getByRole('tab',{name:/a.md/}).click(); await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
await openRight('notes/b.md','Relative'); await pane('notes/c.md').locator('.cm-content').waitFor();
assert.equal(await page.locator('.document-pane').count(),3);
assert.match(await text('notes/c.md'),/Charlie/,'Relative links use the pane document folder');
await pane('notes/c.md').getByRole('button',{name:'Close split',exact:true}).click();
assert.equal(await page.locator('.document-pane').count(),2);
await page.evaluate(()=>window.tabMenuTest.change('notes/b.md','# Bravo disk\n\nExternal update.\n'));
await pane('notes/b.md').getByRole('alert').waitFor();
assert.equal(await pane('a.md').getByRole('alert').count(),0);
assert.match(await text('notes/b.md'),/Right still unsaved/,'A disk conflict preserves the right pane edits');
await focus('a.md');
await pane('notes/b.md').getByRole('button',{name:'Use disk version',exact:true}).click();
await page.waitForFunction(()=>document.querySelector('[data-document-path="notes/b.md"] .cm-content')?.textContent.includes('External update.'));
assert.match(await text('a.md'),/Left unsaved/,'Resolving the other pane cannot replace the primary buffer');
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:560,height:740});
for(const theme of ['light','dark']) {
await page.evaluate(async mode=> { const {saveAppearance}=await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default',mode}); },theme);
const first=await pane('a.md').boundingBox(), second=await pane('notes/b.md').boundingBox();
assert.ok(first.width>500 && second.width>500 && second.y>=first.y+first.height-1,'Narrow panes stack with readable widths');
await page.screenshot({path:`${output}/stacked-${theme}.png`});
}
await append('notes/b.md','\nNarrow edit.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.files.get('notes/b.md').includes('Narrow edit.'));
await pane('notes/b.md').getByRole('button',{name:'Close split',exact:true}).click();
await append('a.md','\nAfter closing split.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.files.get('a.md').includes('After closing split.'));
await page.setViewportSize({width:1440,height:1000});
await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
await append('notes/b.md','\nClose guard.');
await page.keyboard.press('Control+w');
await page.waitForFunction(()=>window.tabMenuTest.prompts.length>0);
assert.equal(await pane('notes/b.md').count(),1,'Cancel keeps the dirty split open');
await page.keyboard.press('Control+s'); await page.waitForFunction(()=>window.tabMenuTest.files.get('notes/b.md').includes('Close guard.'));
await page.keyboard.press('Control+w'); await pane('notes/b.md').waitFor({state:'detached'});
await focus('a.md'); await append('a.md','\nOther tab closed.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.tabMenuTest.files.get('a.md').includes('Other tab closed.'));
assert.equal(await page.evaluate(async()=>{const {monaco}=await import('/src/lib/editor/monacoEnv.ts');return monaco.editor.getModels().some(model=>model.uri.path.endsWith('/b.md'));}),false,'Closing the tab releases only its model');
assert.deepEqual(errors,[]);
console.log(JSON.stringify({passed:['independent Writer/IDE/Reading modes','dirty close cancellation and model release','independent edits and saves','per-pane selections','focus existing duplicate target','closing split retains unsaved tabs and models','nested relative link origin','per-pane conflict resolution','narrow layout and save','light/dark screenshots'],nativeDesktop:'not tested'},null,2));
} catch(error) { await page.screenshot({path:`${output}/failure.png`}); console.log(await page.locator('.status,.rs-menu').allTextContents()); throw error; } finally { await browser.close(); }
+15
View File
@@ -24,6 +24,21 @@ function setup() {
return { docs, disk, io };
}
test("background loading for a split preserves the selected document and its unsaved edits", async () => {
const { docs } = setup();
await docs.open(entry("note.md"));
const first = docs.active!;
docs.edit(first.id, "unsaved text");
await docs.open(entry("script.py"), "background");
assert.equal(docs.active, first);
assert.equal(first.contents, "unsaved text");
assert.equal(docs.buffers.length, 2);
await assert.rejects(docs.open(entry("missing.md"), "background"));
assert.equal(docs.active, first);
docs.select("script.py");
assert.equal(docs.active?.relPath, "script.py");
});
test("tab moves preserve selection, dirty buffers, and in-flight saves", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
+129
View File
@@ -0,0 +1,129 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal [guide](docs/guide.md) text.\n\n| Name | Value |\n| --- | --- |\n| [Roadmap](docs/roadmap.md) | [[guide\\|Guide]] |\n| [One](same.md) + [Two](same.md) | Empty |\n`]));
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.writer-table').waitFor();
for(const theme of ['dark','light']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}), theme);
const prose = page.locator('.writer-link').filter({hasText:'guide'}).first();
await prose.hover();
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.equal(await prose.getAttribute('title'),null);
await page.screenshot({path:'.audit/editor-link-tooltip-'+theme+'.png'});
await page.keyboard.press('Escape');
await prose.click();
assert.equal(await page.locator('.writer-link-source').count(),1);
const colored = await page.locator('.writer-link-source').evaluate(el => ({color:getComputedStyle(el).color, parent:getComputedStyle(el.parentElement).color}));
assert.notEqual(colored.color,colored.parent);
await page.screenshot({path:'.audit/editor-link-source-'+theme+'.png'});
const cell=page.locator('.writer-table td').first();
await cell.locator('a').click({position:{x:22,y:8}});
assert.ok(await page.evaluate(()=>getSelection().anchorOffset > 0));
await cell.click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.getByRole('dialog').count(),0);
assert.equal(await page.evaluate(()=>getSelection().toString()),theme === 'dark' ? 'docs/roadmap.md' : 'docs/new-roadmap.md');
await page.screenshot({path:'.audit/editor-table-source-'+theme+'.png'});
await page.keyboard.type('docs/new-roadmap.md');
await page.keyboard.press('Enter');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/new-roadmap.md');
if(theme === 'dark') {
await page.locator('.cm-line').filter({hasText:'Original'}).click();
await page.keyboard.press('Control+z');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/roadmap.md');
await page.keyboard.press('Control+Shift+z');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/new-roadmap.md');
}
await cell.locator('a').click({position:{x:22,y:8}});
const selection=await page.evaluate(()=>{const s=getSelection();return {offset:s.anchorOffset,length:s.anchorNode.textContent.length};});
assert.ok(selection.offset>0 && selection.offset<selection.length,JSON.stringify(selection));
await page.keyboard.type('X');
assert.ok((await cell.innerText()).includes('X'));
await page.keyboard.press('Escape');
const wiki=page.locator('.writer-table td').nth(1);
await wiki.click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.evaluate(()=>getSelection().toString()),theme==='dark'?'guide':'new-guide');
await page.keyboard.type('new-guide');
await page.keyboard.press('Enter');
assert.equal(await wiki.locator('a').getAttribute('href'),'new-guide');
}
const multi=page.locator('.writer-table td').nth(2);
await multi.locator('a').nth(1).click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.evaluate(()=>getSelection().toString()),'same.md');
await page.keyboard.type('second.md');
await page.keyboard.press('Enter');
assert.equal(await multi.locator('a').first().getAttribute('href'),'same.md');
assert.equal(await multi.locator('a').nth(1).getAttribute('href'),'second.md');
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.getByRole('button',{name:'Files',exact:true}).click();
await page.setViewportSize({width:620,height:700});
await page.waitForTimeout(250);
await page.locator('.table-add-row').scrollIntoViewIfNeeded();
await page.waitForTimeout(100);
await page.locator('.table-add-row').focus();
await page.locator('.rs-tooltip:popover-open').waitFor();
const rect=await page.locator('.rs-tooltip:popover-open').boundingBox();
assert.ok(rect.x>=0 && rect.x+rect.width<=620);
await page.screenshot({path:'.audit/editor-tooltip-narrow-focus.png'});
await page.keyboard.press('Escape');
assert.equal(await page.locator('.rs-tooltip:popover-open').count(),0);
assert.equal(await page.locator('.table-edit-help:visible').count(),0);
for (const mode of ['light','dark']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}),mode);
await page.locator('.writer-table td').nth(1).hover();
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.match(await page.locator('.rs-tooltip:popover-open').innerText(),/Row 2, column 2/);
await page.screenshot({path:'.audit/editor-cell-tooltip-narrow-'+mode+'.png'});
await page.keyboard.press('Escape');
await page.mouse.move(5,90);
}
assert.deepEqual(errors,[]);
console.log('Editor link and tooltip checks passed');
} finally { await browser.close(); }
+209
View File
@@ -0,0 +1,209 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n\n\`\`\`js\nconst answer = 42;\n\`\`\`\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`]));
files.set("a.md", "# Links\n\nSelected reading text.\n\n[Web label](https://example.com/path)\n\n[[b.md|Workspace note]]\n\n| Link | Note |\n| --- | --- |\n| [Cell web](https://example.com/cell) | [[b.md\\|Cell note]] |\n");
files.set("sample.txt", "const answer = 42;\n");
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null, opened: null, app: null, windows: [] };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
window.tabMenuTest.files = files;
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: ["Corrected"], misspelled: args.word === "Original" };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_list") return [...(!args.rel ? [{ name: "notes", rel_path: "notes", kind: "folder" }] : []), ...[...files.keys()].filter(path => path.split("/").slice(0, -1).join("/") === (args.rel || "")).map(path => ({ name: path.split("/").at(-1), rel_path: path, kind: "file" }))];
if (command === "workspace_search") { window.tabMenuTest.searched = args.query; return []; }
if (command === "plugin:opener|open_url") { window.tabMenuTest.opened = args.url; return; }
if (command === "workspace_open_default") { window.tabMenuTest.app = args.rel; return; }
if (command === "workspace_open_window") { window.tabMenuTest.windows.push(args); return; }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const menu = name => page.getByRole('menu', { name, exact: true });
const item = name => page.getByRole('menuitem', { name, exact: true });
const output = '.audit/editor-link-menus';
await mkdir(output, { recursive: true });
const dismiss = async () => { await page.keyboard.press('Escape'); await page.locator('.rs-menu').waitFor({ state: 'detached' }); };
const report = [];
async function writerMenu(target='Web label') {
await page.locator('.cm-content').getByText('Selected reading text.', { exact: true }).click();
await page.locator('.cm-content').getByText(target, { exact: true }).click({ button: 'right' });
await menu('Markdown text actions').waitFor();
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.evaluate(async () => {
const { pluginHost } = await import('/src/lib/plugins/registry.ts');
pluginHost.register('link-smoke', 'browser', { open: async target => { window.tabMenuTest.browser = target; return true; }, mountSettings: () => () => {}, mountBookmarks: () => () => {} });
});
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default', mode}); }, theme);
await writerMenu();
for (const label of ['Open link in app browser', 'Open link in default browser', 'Copy URL', 'Edit link']) assert.equal(await item(label).count(), 1);
await page.screenshot({ path: `${output}/writer-link-${theme}.png` });
await item('Copy URL').click();
await page.waitForFunction(() => window.tabMenuTest.clipboard === 'https://example.com/path');
await writerMenu(); await item('Open link in default browser').click();
await page.waitForFunction(() => window.tabMenuTest.opened === 'https://example.com/path');
await writerMenu(); await item('Open link in app browser').click();
await page.waitForFunction(() => window.tabMenuTest.browser === 'https://example.com/path');
await writerMenu(); await item('Edit link').click();
assert.equal(await page.evaluate(async () => { const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js'); const v = EditorView.findFromDOM(document.querySelector('.cm-content')); return v.state.sliceDoc(v.state.selection.main.from, v.state.selection.main.to); }), 'https://example.com/path');
await page.screenshot({ path: `${output}/edit-url-${theme}.png` });
await page.keyboard.type('https://changed.example');
await page.keyboard.press('Control+z');
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
await writerMenu('Workspace note');
for (const label of ['Open in new tab', 'Open in new window', 'Copy path', 'Bookmark', 'Show in system explorer', 'Reveal file in navigation', 'Edit link']) assert.equal(await item(label).count(), 1);
for (const label of ['Rename…', 'Move file to…', 'Open in default app']) assert.equal(await item(label).count(), 0);
await page.screenshot({ path: `${output}/workspace-link-${theme}.png` });
await dismiss();
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:560,height:620});
await writerMenu('Workspace note'); await page.keyboard.press('End');
assert.match(await page.evaluate(() => document.activeElement.textContent), /Select all/);
await page.screenshot({path:`${output}/workspace-narrow-${theme}.png`});
await dismiss(); 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 writerMenu('Workspace note');
await item('Copy path').focus(); await page.keyboard.press('ArrowRight'); await item('Workspace path').click();
await page.waitForFunction(() => window.tabMenuTest.clipboard === 'b.md');
await writerMenu('Workspace note'); await item('Show in system explorer').click(); await page.waitForFunction(() => window.tabMenuTest.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();
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');
await menu('Reading actions').waitFor();
await page.keyboard.press('End'); assert.match(await page.evaluate(() => document.activeElement.textContent), /^Search for/);
await page.screenshot({ path: `${output}/reading-selection-${theme}.png` });
await page.keyboard.press('Home'); await page.keyboard.press('Enter');
await page.waitForFunction(() => window.tabMenuTest.clipboard === 'Selected reading text.');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', {name:/^Search for/}).click();
await page.waitForFunction(() => window.tabMenuTest.searched === 'Selected reading text.');
await page.evaluate(() => getSelection().removeAllRanges());
await reading.getByRole('link',{name:'Web label'}).click({button:'right'});
await item('Copy URL').click(); await page.waitForFunction(() => window.tabMenuTest.clipboard === 'https://example.com/path');
await page.getByRole('button', { name: 'Search', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
await page.setViewportSize({ width: 560, height: 620 });
await reading.getByRole('link',{name:'Web label'}).click({button:'right'});
const rect=await menu('Reading actions').boundingBox(); assert.ok(rect.x>=0 && rect.x+rect.width<=560 && rect.y+rect.height<=620);
await page.screenshot({ path: `${output}/reading-narrow-${theme}.png` });
await dismiss();
assert.equal(await reading.evaluate(node => node.contains(document.activeElement)), true);
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 page.locator('.monaco-editor').waitFor();
await page.evaluate(async () => { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); const editor=monaco.editor.getEditors()[0]; const model=editor.getModel(); const pos=model.getPositionAt(model.getValue().indexOf('Web label')+2); editor.setPosition(pos); editor.focus(); });
await page.keyboard.press('Shift+F10'); await item('Edit link').click();
assert.equal(await page.evaluate(async () => { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); const editor=monaco.editor.getEditors()[0]; return editor.getModel().getValueInRange(editor.getSelection()); }), '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 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'});
await item('Edit link').waitFor();
await page.screenshot({path:`${output}/table-link-${theme}.png`});
await item('Copy URL').click();
await page.waitForFunction(() => window.tabMenuTest.clipboard === 'https://example.com/cell');
await cellLink.click({button:'right'}); await item('Edit link').click();
const sourceCell = page.locator('.writer-table .is-source-editing .writer-cell-editor');
await sourceCell.waitFor();
assert.equal(await page.getByLabel('Edit link target').count(), 0);
assert.equal(await page.evaluate(() => getSelection().toString()), 'https://example.com/cell');
assert.equal(await sourceCell.locator('.writer-link-target').innerText(), 'https://example.com/cell');
await page.screenshot({path:`${output}/table-edit-${theme}.png`});
await page.keyboard.type('https://changed.example/cell'); await page.keyboard.press('Enter');
await page.waitForFunction(() => document.querySelector('.writer-table a')?.getAttribute('href') === 'https://changed.example/cell');
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.writer-table a')?.getAttribute('href') === 'https://example.com/cell');
const cellNote = page.locator('.writer-table a').filter({hasText:'Cell note'});
await cellNote.click({button:'right'}); await item('Edit link').click();
assert.equal(await page.evaluate(() => getSelection().toString()), 'b.md');
await page.keyboard.type('c.md'); await page.keyboard.press('Enter');
await page.waitForFunction(() => [...document.querySelectorAll('.writer-table a')].some(node => node.textContent === 'Cell note' && node.getAttribute('href') === 'c.md'));
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => [...document.querySelectorAll('.writer-table a')].some(node => node.textContent === 'Cell note' && node.getAttribute('href') === 'b.md'));
await cellLink.click({button:'right'}); await item('Edit link').click();
await page.keyboard.type('https://escape.example'); await page.keyboard.press('Escape');
assert.equal(await sourceCell.count(), 0);
assert.equal(await cellLink.getAttribute('href'), 'https://escape.example');
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.writer-table a')?.getAttribute('href') === 'https://example.com/cell');
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:560,height:620});
await cellLink.click(); await page.keyboard.press('Shift+F10'); await item('Edit link').waitFor();
await page.screenshot({path:`${output}/table-narrow-${theme}.png`});
await dismiss();
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'});
}
await writerMenu('Workspace note'); await item('Open in new window').click();
await page.waitForFunction(() => window.tabMenuTest.windows.length === 1);
await page.evaluate(() => { const {transfer}=window.tabMenuTest.windows[0]; dispatchEvent(new StorageEvent('storage',{key:`runestone.tab-transfer.${transfer}.accepted`,newValue:'true'})); });
assert.equal(await page.getByRole('tab',{name:/b.md/}).count(),1,'Opening a linked document in a new window keeps the source tab');
await page.locator('[data-tree-rel="a.md"]').click();
await writerMenu('Workspace note'); await item('Bookmark').click();
await page.waitForFunction(() => JSON.parse(window.tabMenuTest.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.tabMenuTest.clipboard.endsWith('\\b.md'));
await page.getByRole('group', { name: 'Document view', exact: true }).hover(); await page.getByRole('button', { name:'Read', exact:true }).click();
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.tabMenuTest.app === 'b.md');
await readerWorkspaceMenu(); await item('Rename…').click();
await page.getByLabel('New file name').fill('renamed.md'); await page.getByRole('button',{name:'Continue',exact:true}).click();
await page.waitForFunction(() => window.tabMenuTest.files.has('renamed.md') && !window.tabMenuTest.files.has('b.md'));
assert.equal(await page.evaluate(() => JSON.parse(window.tabMenuTest.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 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 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.tabMenuTest.files.has('notes/moved.md') && !window.tabMenuTest.files.has('renamed.md'));
assert.equal(await page.evaluate(() => JSON.parse(window.tabMenuTest.files.get('.runestone/marks.json')).bookmarks.includes('notes/moved.md')),true);
assert.deepEqual(errors,[]); console.log(JSON.stringify(report,null,2));
} catch(error) { await page.screenshot({path:`${output}/failure.png`}); console.log(await page.locator('.rs-menu').allTextContents()); throw error; } finally { await browser.close(); }
+10
View File
@@ -21,3 +21,13 @@ test("bare and angle links omit prose punctuation and preserve balanced parenthe
const source = 'Go to https://example.com/a_(b). Next (<https://example.org>). Mail <mailto:[email protected]>.';
assert.deepEqual(documentLinks(source).map(link => link.target), ["https://example.com/a_(b)", "https://example.org", "mailto:[email protected]"]);
});
test("edit link selects only its destination, preserving labels, titles, brackets, and spacing", () => {
const source = '[Local](<notes/two words.md> "Title") and [Web](https://example.com/a_\\(b\\)) and [[ Another note#Heading |Alias]] and <https://example.org>.';
const links = documentLinks(source);
assert.deepEqual(links.map(link => source.slice(link.targetFrom, link.targetTo)), ["notes/two words.md", "https://example.com/a_\\(b\\)", "Another note#Heading", "https://example.org"]);
});
test("wiki image embeds do not expose document actions", () => {
assert.deepEqual(documentLinks('![[image.png]] [[note|label]]').map(link => link.target), ["note"]);
});
+181
View File
@@ -0,0 +1,181 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n\n\`\`\`js\nconst answer = 42;\n\`\`\`\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`]));
files.set("sample.txt", "const answer = 42;\n");
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: ["Corrected"], misspelled: args.word === "Original" };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") throw new Error("Keep unsaved edits for the close test");
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const menu = name => page.getByRole('menu', { name, exact: true });
const item = name => page.getByRole('menuitem', { name, exact: true });
const output = '.audit/editor-surfaces';
await mkdir(output, { recursive: true });
const report = [];
const dismiss = async () => { await page.keyboard.press('Escape'); await page.locator('.rs-menu').waitFor({ state: 'detached' }); };
const styles = panel => panel.evaluate(node => {
const row = node.querySelector(':scope > button');
const a = getComputedStyle(node), b = getComputedStyle(row);
return [a.backgroundColor, a.borderRadius, a.padding, b.minHeight, b.padding, b.font];
});
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
for (const theme of ['dark', 'light']) {
await page.setViewportSize({ width: 1440, height: 1000 });
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
const canvas = document.createElement('canvas');
canvas.width = 800; canvas.height = 600;
const c = canvas.getContext('2d');
const g = c.createLinearGradient(0, 0, 800, 600);
g.addColorStop(0, '#628ba8'); g.addColorStop(1, '#b47796');
c.fillStyle = g; c.fillRect(0, 0, 800, 600);
saveAppearance({ theme: 'default', mode, newTabBackground: { image: canvas.toDataURL(), overlay: .15, position: 'center', size: 'cover' } });
}, theme);
await page.locator('[data-tree-rel="a.md"]').click({ button: 'right' });
const reference = await styles(menu('File actions'));
await dismiss();
const text = page.getByText('Original text.', { exact: true });
await text.click({ button: 'right', position: { x: 20, y: 8 } });
const writer = menu('Markdown text actions');
assert.deepEqual(await styles(writer), reference);
for (const name of ['Add link', 'Add external link', 'Format', 'Paragraph', 'Insert', 'Paste', 'Select all']) assert.equal(await item(name).count(), 1);
await item('Corrected').waitFor();
assert.equal(await item('Spelling').count(), 0, 'Corrections appear directly in the main menu');
assert.equal(await writer.locator(':scope > button').first().textContent(), 'Corrected');
await page.screenshot({ path: `${output}/writer-menu-${theme}.png` });
await item('Corrected').focus(); await page.keyboard.press('Enter');
await page.getByText('Corrected text.', { exact: true }).waitFor();
await page.keyboard.press('Control+z');
await text.waitFor();
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
await page.setViewportSize({ width: 560, height: 620 });
await text.click({ button: 'right', position: { x: 20, y: 8 } });
await item('Corrected').waitFor();
await page.keyboard.press('Home');
assert.equal(await item('Corrected').evaluate(node => node === document.activeElement), true);
const spellingBounds = await writer.boundingBox();
assert.ok(spellingBounds.x >= 8 && spellingBounds.x + spellingBounds.width <= 552);
await page.screenshot({ path: `${output}/spelling-narrow-${theme}.png` });
await page.keyboard.press('Enter');
await page.getByText('Corrected text.', { exact: true }).waitFor();
await page.keyboard.press('Control+z');
await text.waitFor();
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').click({ button: 'right', position: { x: 600, y: 150 } });
assert.deepEqual(await styles(writer), reference, 'Blank space uses the same actions');
await item('Format').focus(); await page.keyboard.press('ArrowRight');
await item('Bold').click();
await page.locator('.cm-content').click({ button: 'right', position: { x: 600, y: 150 } });
await page.getByRole('menuitem', { name: 'Undo Ctrl+Z', exact: true }).click();
assert.equal(await page.locator('.cm-content').textContent().then(s => s.includes('**')), false, 'Undo reverses the menu edit');
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();
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 page.locator('.monaco-editor').waitFor();
await page.locator('.monaco-host').click({ button: 'right', position: { x: 500, y: 400 } });
assert.deepEqual(await styles(writer), reference, 'Markdown IDE retains the same menu');
await dismiss();
await page.locator('[data-tree-rel="sample.txt"]').click();
await page.locator('.monaco-host').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.equal(await page.locator('.monaco-menu').count(), 0);
await page.screenshot({ path: `${output}/ide-menu-${theme}.png` });
await page.getByRole('menuitem', { name: 'Command palette F1', exact: true }).click();
const palette = page.locator('.quick-input-widget');
await palette.waitFor({ state: 'visible' });
const paletteMetrics = () => palette.evaluate(node => {
const row = node.querySelector('.monaco-list-row.focused');
const field = node.querySelector('.monaco-inputbox');
const a = getComputedStyle(row), b = getComputedStyle(field);
const probe = document.createElement('div');
probe.style.background = 'var(--rs-item-selection-bg)'; probe.style.color = 'var(--rs-item-selection-border)';
node.append(probe); const expected = getComputedStyle(probe);
const result = { fill: a.backgroundColor, expectedFill: expected.backgroundColor, outline: a.outlineColor, expectedOutline: expected.color, radius: a.borderRadius, inputRadius: b.borderRadius, inputOutline: b.outlineColor, inputOutlineWidth: b.outlineWidth };
probe.remove(); return result;
});
let p = await paletteMetrics();
assert.equal(p.fill, p.expectedFill);
assert.equal(p.outline, p.expectedOutline);
assert.equal(p.radius, '5px'); assert.equal(p.inputRadius, '5px');
assert.equal(p.inputOutline, p.expectedOutline); assert.equal(p.inputOutlineWidth, '2px');
await page.keyboard.press('ArrowDown');
p = await paletteMetrics(); assert.equal(p.fill, p.expectedFill);
await page.screenshot({ path: `${output}/palette-${theme}.png` });
await page.keyboard.press('Escape');
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
await page.setViewportSize({ width: 560, height: 620 });
await page.locator('.monaco-host').click({ button: 'right', position: { x: 100, y: 300 } });
await code.waitFor();
const bounds = await code.boundingBox();
assert.ok(bounds.x >= 0 && bounds.x + bounds.width <= 560);
await page.keyboard.press('End');
assert.equal(await page.getByRole('menuitem', { name: 'Command palette F1', exact: true }).evaluate(n => n === document.activeElement), true);
await page.screenshot({ path: `${output}/ide-narrow-${theme}.png` });
await page.keyboard.press('Enter');
await palette.waitFor({ state: 'visible' });
await page.screenshot({ path: `${output}/palette-narrow-${theme}.png` });
await page.keyboard.press('Escape');
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('[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', 'palette selection/focus', 'narrow keyboard menu/palette'], nativeDesktop: 'not tested' });
}
assert.deepEqual(errors, []);
console.log(JSON.stringify(report, null, 2));
} catch (error) { await page.screenshot({path: `${output}/failure.png`}); console.log(await page.locator(".rs-menu").allTextContents()); throw error; } finally { await browser.close(); }
+40
View File
@@ -0,0 +1,40 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { CHARACTER_THEMES, SYNTAX_ROLES } from '../src/lib/theme/characterThemes.ts';
const rgb = (hex: string) => hex.match(/[0-9a-f]{2}/gi)!.map(channel => parseInt(channel, 16));
const luminance = (hex: string) => rgb(hex).map(channel => channel / 255)
.map(channel => channel <= .04045 ? channel / 12.92 : ((channel + .055) / 1.055) ** 2.4)
.reduce((sum, channel, index) => sum + channel * [.2126, .7152, .0722][index], 0);
const contrast = (a: string, b: string) => (Math.max(luminance(a), luminance(b)) + .05) / (Math.min(luminance(a), luminance(b)) + .05);
const mix = (a: string, b: string, ratio: number) => '#' + rgb(a)
.map((channel, index) => Math.round(channel * ratio + rgb(b)[index] * (1 - ratio)).toString(16).padStart(2, '0')).join('');
test('Silver Serpent text and syntax remain readable on opaque and image surfaces', () => {
const { surfaces, syntax, secondary } = CHARACTER_THEMES['silver-serpent'];
const [bg, elevated, active, , dim, text, strong, accent, selection] = surfaces;
const panelOnWhite = mix(elevated, '#ffffff', .82);
const editorOnWhite = mix(bg, '#ffffff', .9);
const backgrounds = {
bg, elevated, active, selection,
panelOnWhite,
editorOnWhite,
menuHoverOnWhite: mix(active, panelOnWhite, .82),
controlHoverOnWhite: mix(active, '#ffffff', .92),
codeBlockOnWhite: mix(elevated, editorOnWhite, .82),
};
const foregrounds = { dim, text, strong, accent, secondary,
...Object.fromEntries(SYNTAX_ROLES.map((role, index) => [`syntax-${role}`, syntax[index]])) };
for (const [backgroundName, background] of Object.entries(backgrounds)) {
for (const [foregroundName, foreground] of Object.entries(foregrounds)) {
assert(contrast(foreground, background) >= 4.5, `${foregroundName} on ${backgroundName}`);
}
}
});
test('Silver Serpent selection has a readable perimeter and a separate fill', () => {
const [bg, elevated, , , , , , accent, selection] = CHARACTER_THEMES['silver-serpent'].surfaces;
assert(contrast(accent, selection) >= 3, 'selection perimeter');
assert(contrast(selection, bg) >= 1.5, 'selection against the editor');
assert(contrast(selection, elevated) >= 1.5, 'selection against a panel');
});
+70 -2
View File
@@ -25,6 +25,7 @@ await page.addInitScript(() => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
@@ -70,13 +71,36 @@ try {
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
const canvas = document.createElement('canvas');
canvas.width = 800; canvas.height = 600;
const context = canvas.getContext('2d');
const gradient = context.createLinearGradient(0, 0, 800, 600);
gradient.addColorStop(0, '#628ba8'); gradient.addColorStop(1, '#b47796');
context.fillStyle = gradient; context.fillRect(0, 0, 800, 600);
saveAppearance({ theme: 'default', mode, newTabBackground: { image: canvas.toDataURL(), overlay: 0.15, position: 'center', size: 'cover' } });
}, theme);
await row.focus();
await row.click({ button: "right" });
const file = menu("File actions");
await file.waitFor();
const reference = await metrics(file);
assert.equal(reference.row[1], "24px", "Menus use compact shared rows");
assert.equal(reference.row[0], "2px 10px");
const compactHeight = await file.evaluate(node => node.getBoundingClientRect().height);
await page.evaluate(() => {
document.documentElement.style.setProperty('--rs-menu-row-height', '30px');
document.documentElement.style.setProperty('--rs-menu-row-padding', '4px 10px');
});
const previousHeight = await file.evaluate(node => node.getBoundingClientRect().height);
await page.screenshot({ path: '.audit/todo-2026-10-14/menu-spacing-before-' + theme + '.png' });
await page.evaluate(() => {
document.documentElement.style.removeProperty('--rs-menu-row-height');
document.documentElement.style.removeProperty('--rs-menu-row-padding');
});
assert.ok(compactHeight < previousHeight * .85, 'The same actions use at least 15% less vertical space');
console.log(JSON.stringify({ theme, compactHeight, previousHeight }));
await page.screenshot({ path: '.audit/todo-2026-10-14/menu-spacing-after-' + theme + '.png' });
assert.ok(reference.panel[2].includes('/ 0.82') || /rgba\(.+, 0\.82\)/.test(reference.panel[2]), "Shared menus retain an 82% surface tint");
assert.ok(reference.inset >= 5, "Rows need an inset from the panel border");
assert.equal(await item("Pin").locator("svg.action-icon").count(), 1);
const offsets = await file.locator(":scope > button").evaluateAll(nodes => nodes.map(node => Math.round(node.querySelector(".action-label").getBoundingClientRect().left - node.getBoundingClientRect().left)));
@@ -131,6 +155,20 @@ try {
return { x: bounds.left + bounds.width / 2, y: bounds.top + bounds.height / 2 };
});
await page.mouse.click(wordPoint.x, wordPoint.y, { button: "right" });
await editor.waitFor();
assert.deepEqual(await metrics(editor), reference, "Word and blank-space menus share styles");
assert.equal(await item("Format").count(), 1, "Words retain the Markdown actions");
await dismiss();
await page.evaluate(() => {
const input = document.createElement("input");
input.id = "native-spelling-test";
input.spellcheck = true;
input.value = "Original";
Object.assign(input.style, { position: "fixed", left: "500px", top: "100px" });
document.body.append(input);
input.focus();
input.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
});
await page.evaluate(() => window.spellingTest.emit({ request: "spelling-1", items: [
{ id: 71, name: "suggestion", label: "Original", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
{ id: 72, name: "addToDictionary", label: "Add to dictionary", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
@@ -152,7 +190,7 @@ try {
await page.keyboard.press("Enter");
await spelling.waitFor({ state: "detached" });
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "spelling-1", command: 71 });
assert.equal(await page.locator(".cm-content").evaluate(node => node === document.activeElement), true);
assert.equal(await page.locator("#native-spelling-test").evaluate(node => node === document.activeElement), true);
async function emitSpelling(request) {
await page.evaluate(request => window.spellingTest.emit({ request, items: [
{ id: 81, name: "suggestion", label: "Replacement", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
@@ -170,6 +208,7 @@ try {
await emitSpelling("new");
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "old", command: null });
await dismiss();
await page.locator("#native-spelling-test").evaluate(node => node.remove());
await page.evaluate(() => {
const input = document.createElement("input");
input.spellcheck = false;
@@ -216,6 +255,35 @@ try {
assert.equal(await item("Action 29").evaluate(node => node === document.activeElement), true);
await page.screenshot({ path: ".audit/menu-edge.png" });
await dismiss();
await page.evaluate(async () => {
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
const dialog = document.createElement("dialog");
dialog.id = "menu-modal-test";
dialog.style.cssText = "height:220px;width:320px;overflow:auto";
const content = document.createElement("div");
content.style.height = "600px";
dialog.append(content);
document.body.append(dialog);
dialog.showModal();
dialog.scrollTop = 160;
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
window.menuModalScroll = dialog.scrollTop;
const root = actionMenu(180, 280, Array.from({ length: 30 }, (_, index) => ({ label: `Modal action ${index}`, icon: "copy" })), () => root.remove(), "Modal scrolling test", dialog);
const dismissOnAncestorScroll = event => { if (!root.contains(event.target)) root.remove(); };
dialog.addEventListener("scroll", dismissOnAncestorScroll, true);
});
await page.keyboard.press("End");
const modalMenu = menu("Modal scrolling test");
await modalMenu.waitFor();
assert.equal(await item("Modal action 29").evaluate(node => node === document.activeElement), true);
assert.equal(await page.locator("#menu-modal-test").evaluate(dialog => dialog.scrollTop), await page.evaluate(() => window.menuModalScroll), "Keyboard traversal scrolls only the menu panel");
const modalBounds = await modalMenu.boundingBox(), lastBounds = await item("Modal action 29").boundingBox();
assert.ok(lastBounds.y >= modalBounds.y && lastBounds.y + lastBounds.height <= modalBounds.y + modalBounds.height + 1, "End keeps the last row visible inside a short modal");
await page.screenshot({ path: ".audit/menu-modal-end.png" });
await page.keyboard.press("Home");
assert.equal(await item("Modal action 0").evaluate(node => node === document.activeElement), true);
await dismiss();
await page.locator("#menu-modal-test").evaluate(dialog => { dialog.close(); dialog.remove(); });
assert.deepEqual(errors, []);
console.log("PASS: menu styles, dark/light themes, icons, disabled rows, focus return, submenus, scrolling, and viewport edges");
} finally { await browser.close(); }
+59
View File
@@ -0,0 +1,59 @@
import { readdir, readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = fileURLToPath(new URL('../', import.meta.url));
export const projects = ['RuneStone', 'RuneStone_ProjectManagement', 'RuneStone_Terminal', 'RuneStone_BG_Slideshow', 'RuneStone_LocalAutocomplete', 'RuneStone_Git', 'RuneStone_PDFViewer', 'RuneStone_TableFormulas', 'RuneStone_CSVViewer'];
const patterns = {
action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
svelteMenu: /<ContextMenu\b/g,
nativeChoice: /<select\b|(?:createElement|el)\(\s*['"]select['"]/g,
picker: /rs-picker(?:[\s"']|$)|role=['"]listbox['"]|setAttribute\(\s*['"]role['"],\s*['"]listbox['"]/g,
localPopup: /(?:class|className)\s*=\s*['"][^'"\n]*(?:menu|picker|popup)|\.popover\s*=/g,
};
async function files(dir) {
const entries = await readdir(dir, { withFileTypes: true });
const results = await Promise.all(entries.filter(entry => !entry.isSymbolicLink()).map(entry => entry.isDirectory()
? files(path.join(dir, entry.name)) : /\.(svelte|[cm]?[jt]s)$/.test(entry.name) ? [path.join(dir, entry.name)] : []));
return results.flat();
}
export async function discover() {
const surfaces = {}, missing = [];
for (const project of projects) {
const base = project === 'RuneStone' ? root : path.resolve(root, '..', project);
let sources;
try { sources = await files(path.join(base, 'src')); } catch (error) { if (error.code === 'ENOENT') { missing.push(project); continue; } throw error; }
for (const file of sources) {
const source = await readFile(file, 'utf8');
const counts = Object.fromEntries(Object.entries(patterns).map(([name, pattern]) => [name, [...source.matchAll(pattern)].length]).filter(([, count]) => count));
if (Object.keys(counts).length) surfaces[`${project}/${path.relative(base, file).replaceAll('\\', '/')}`] = counts;
}
}
return { surfaces, missing };
}
export async function checkInventory() {
const { surfaces, missing } = await discover();
const inventory = JSON.parse(await readFile(path.join(root, 'docs/menu-surfaces.json'), 'utf8'));
const failures = missing.map(project => `Missing checkout: ${project}`);
for (const [file, counts] of Object.entries(surfaces)) {
const entry = inventory.surfaces[file];
if (!entry) failures.push(`Unreviewed surface: ${file}`);
else if (JSON.stringify(counts) !== JSON.stringify(entry.counts)) failures.push(`Changed entry points: ${file}`);
else if (!entry.design || !entry.check) failures.push(`Missing design or check: ${file}`);
}
for (const file of Object.keys(inventory.surfaces)) if (!(file in surfaces)) failures.push(`Stale inventory: ${file}`);
for (const name of ['actionMenu.ts', 'managedActionMenu.ts', 'IconButton.svelte']) {
try {
const host = await readFile(path.join(root, 'src/lib/ui', name), 'utf8');
const terminal = await readFile(path.resolve(root, '../RuneStone_Terminal/vendor/runestone/ui', name), 'utf8');
if (host.replaceAll('\r\n', '\n') !== terminal.replaceAll('\r\n', '\n')) failures.push(`Terminal shared snapshot differs: ${name}`);
} catch (error) { failures.push(`Cannot check Terminal snapshot ${name}: ${error.code}`); }
}
if (failures.length) { console.error(failures.join('\n')); return false; }
console.log(`PASS: ${Object.keys(surfaces).length} source files across ${projects.length} projects match the reviewed menu inventory. Runtime checks remain separate.`);
return true;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
if (process.argv.includes('--discover')) console.log(JSON.stringify(await discover(), null, 2));
else if (!await checkInventory()) process.exitCode = 1;
}
+22 -5
View File
@@ -1,6 +1,6 @@
import { lstat, readdir, readFile, mkdir, writeFile, realpath, rename, unlink } from "node:fs/promises";
import { lstat, readdir, readFile, mkdir, writeFile, realpath, link, unlink } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { resolve, relative, isAbsolute, join } from "node:path";
import { resolve, relative, isAbsolute, join, dirname } from "node:path";
import { pathToFileURL } from "node:url";
import { crc32, deflateRawSync } from "node:zlib";
@@ -50,9 +50,21 @@ function zip(files) {
return Buffer.concat([...local, ...central, end]);
}
export async function packagePlugin(source, destination = "plugin-packages") {
export async function packagePlugin(source, destination) {
const input = resolve(source);
const output = resolve(destination);
let project = input;
if (!destination) {
while (true) {
try { await readFile(join(project, "package.json")); break; }
catch (error) {
if (error.code !== "ENOENT") throw error;
const parent = dirname(project);
requireValue(parent !== project, "Pass an output folder when the compiled folder has no project root.");
project = parent;
}
}
}
const output = resolve(destination ?? join(project, "releases"));
const inputMeta = await lstat(input);
requireValue(inputMeta.isDirectory() && !inputMeta.isSymbolicLink(), "Select a compiled plugin folder.");
const files = [], names = new Set();
@@ -102,7 +114,12 @@ export async function packagePlugin(source, destination = "plugin-packages") {
const temporary = `${target}.${randomUUID()}.tmp`;
try {
await writeFile(temporary, archive, { flag: "wx" });
await rename(temporary, target);
try {
await link(temporary, target);
} catch (error) {
if (error.code !== "EEXIST") throw error;
requireValue((await readFile(target)).equals(archive), "The release file already contains different contents: " + target);
}
} finally {
await unlink(temporary).catch(error => { if (error.code !== "ENOENT") throw error; });
}
+52
View File
@@ -0,0 +1,52 @@
import assert from 'node:assert/strict';
import { readFile, mkdir } from 'node:fs/promises';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage();
const url = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await mkdir('.audit/menu-audit', { recursive: true });
await page.route('**/__choice-audit__', route => route.fulfill({ contentType: 'text/html', body: '<link rel="stylesheet" href="/src/lib/theme/tokens.css"><link rel="stylesheet" href="/src/lib/ui/menu.css"><style>dialog{inset:0;margin:0;max-width:none;max-height:none;width:100%;height:100%;box-sizing:border-box;background:var(--rs-bg);color:var(--rs-text);padding:0;border:0}</style><dialog><main></main></dialog>' }));
await page.route('**/__autocomplete__/*.mjs', async route => {
const name = new URL(route.request().url()).pathname.split('/').pop();
assert.ok(['main.mjs', 'engine.mjs'].includes(name));
await route.fulfill({ contentType: 'application/javascript', body: await readFile(new URL(`../../RuneStone_LocalAutocomplete/src/${name}`, import.meta.url), 'utf8') });
});
try {
for (const theme of ['light', 'dark']) for (const width of [1100, 390]) {
await page.setViewportSize({ width, height: 850 });
await page.goto(url + '/__choice-audit__');
await page.evaluate(async theme => {
document.documentElement.dataset.theme = theme;
const { showActionMenu } = await import('/src/lib/ui/managedActionMenu.ts');
const { activate } = await import('/__autocomplete__/main.mjs');
let view;
window.choiceAudit = { saved: null };
await activate({ ui: { showActionMenu }, completion: { version: 1, transport() {}, invalidate() {}, registerProvider() { return () => {}; }, registerInput() { return { dispose() {}, request() {} }; } },
settings: { read: async () => ({}), write: async value => { window.choiceAudit.saved = value; } },
onDispose() {}, registerCommand() {}, registerView(value) { view = value; } });
document.querySelector('dialog').showModal();
window.choiceAudit.dispose = view.mount(document.querySelector('main'), { surface: 'settings' });
}, theme);
const trigger = page.getByRole('button', { name: 'Server type', exact: true });
await trigger.click();
const menu = page.getByRole('menu', { name: 'Server type', exact: true });
assert.equal(await menu.evaluate(node => !!node.closest('dialog[open]')), true);
await page.keyboard.press('End');
assert.equal(await page.getByRole('menuitemradio', { name: 'Ollama', exact: true }).evaluate(node => node === document.activeElement), true);
await page.screenshot({ path: `.audit/menu-audit/autocomplete-${theme}-${width}.png` });
await page.keyboard.press('Enter');
assert.match(await trigger.innerText(), /Ollama/);
await page.getByRole('button', { name: 'Save settings', exact: true }).click();
await page.waitForFunction(() => window.choiceAudit.saved?.adapter === 'ollama');
await trigger.click(); await page.keyboard.press('Escape');
assert.equal(await trigger.evaluate(node => node === document.activeElement), true);
await trigger.click(); await page.evaluate(() => window.choiceAudit.dispose());
assert.equal(await page.locator('.rs-menu').count(), 0);
}
assert.deepEqual(errors, []);
console.log('PASS: Local Autocomplete shared choices, modal input, saved adapter, focus return, and cleanup in both themes at 1100/390px.');
} finally { await browser.close(); }
+6 -1
View File
@@ -39,11 +39,16 @@ test("plugin packaging rejects invalid release inputs before writing an archive"
await writeFile(join(source, "invalid file.txt"), "test");
await assert.rejects(packagePlugin(source, output), /Invalid package path/);
await rm(join(source, "invalid file.txt"));
const path = await packagePlugin(source, output);
await writeFile(join(root, "package.json"), JSON.stringify({ name: "test-plugin" }));
const path = await packagePlugin(source);
assert.equal(path, join(await realpath(output), "org.test.demo-1.0.0.zip"));
const first = await readFile(path);
await packagePlugin(source, output);
assert.deepEqual(await readFile(path), first);
await writeFile(join(source, "main.js"), "export function activate() { return 1; }");
await assert.rejects(packagePlugin(source), /different contents/);
assert.deepEqual(await readFile(path), first);
await writeFile(join(source, "main.js"), "export function activate() {}");
for (const version of ["0.2.28a", "0.2.28b", "0.2.28aa"]) {
await save({ version });
const hotfix = await packagePlugin(source, output);
+121
View File
@@ -0,0 +1,121 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "spelling_menu_install") return;
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
try {
await mkdir("output/editor-october12", { recursive: true });
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "welcome.md" }).first().click();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await page.locator('.md-properties').waitFor();
await page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
});
const original = await page.evaluate(() => window.__CM__.state.sliceDoc());
assert.equal(await page.evaluate(() => window.__CM__.state.selection.main.head), original.indexOf('\n\n') + 1);
await page.locator('.md-properties summary').click();
assert.equal(await page.locator('.md-properties').getAttribute('open'), '');
assert.match(await page.locator('.md-properties pre').textContent(), /title: Welcome/);
for (const mode of ['light', 'dark']) {
await page.evaluate(async mode => {
const { applyAppearance } = await import('/src/lib/theme/appearance.ts');
applyAppearance({ theme: 'default', mode });
}, mode);
await page.setViewportSize({ width: 760, height: 900 });
await page.screenshot({ path: `output/editor-october12/properties-${mode}-narrow.png` });
}
await page.evaluate(() => { window.__CM__.dispatch({ selection: { anchor: 11 } }); window.__CM__.focus(); });
assert.equal(await page.locator('.md-properties').count(), 0);
await page.keyboard.type('New ');
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /title: New Welcome/);
await page.keyboard.press('Control+z');
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), original);
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 page.locator('.reading .md-properties').waitFor();
await page.getByRole('group', { name: 'Document view' }).hover();
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
assert.equal(await page.locator('.writer-preview .md-properties').count(), 0);
assert.equal(errors.length, 0, errors.join('\n'));
console.log('Properties first-open, editing, undo, saved selection, and both themes passed.');
} finally {
await browser.close();
}
+12 -2
View File
@@ -104,6 +104,13 @@ try {
await table.waitFor();
assert.equal(await result(1, 3).innerText(), '9.5');
assert.equal(await result(3, 3).innerText(), '17.5');
await cell(1, 3).hover();
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.equal(await cell(1, 3).getAttribute('title'), null);
assert.match(await page.locator('.rs-tooltip:popover-open').innerText(), /D2.*AVERAGE/);
await page.screenshot({ path: '.audit/table-cell-hint.png' });
await page.keyboard.press('Escape');
assert.equal(await page.locator('.rs-tooltip:popover-open').count(), 0);
await cell(1, 3).click();
assert.equal(await page.locator('.table-formula-status').innerText(), 'D2 = 9.5');
await edit.fill('=AVERAGE(B2+C2)');
@@ -153,14 +160,17 @@ try {
async function checkFooter() {
const geometry = await page.evaluate(() => {
const rect = selector => document.querySelector(selector).getBoundingClientRect().toJSON();
return { table: rect('.live-writer .md-table-scroll'), footer: rect('.table-footer'), tools: rect('.table-formula-tools'), help: rect('.table-edit-help'), summary: rect('.table-formula-help summary'), status: rect('.table-formula-status') };
return { table: rect('.live-writer .md-table-scroll'), footer: rect('.table-footer'), tools: rect('.table-formula-tools'), help: rect('.table-edit-help'), helpHidden: document.querySelector('.table-edit-help').hidden, summary: rect('.table-formula-help summary'), status: rect('.table-formula-status') };
});
assert.ok(Math.abs(geometry.table.x - geometry.footer.x) < 2);
assert.ok(Math.abs(geometry.help.x - geometry.tools.x) < 2);
assert.ok(Math.abs(geometry.footer.x - geometry.tools.x) < 2);
if (!geometry.helpHidden) assert.ok(Math.abs(geometry.help.x - geometry.tools.x) < 2);
assert.ok(geometry.footer.y >= geometry.table.bottom);
assert.ok(geometry.footer.y - geometry.table.bottom <= 28, 'Only the add-row control sits between table and footer');
if (!geometry.helpHidden) {
assert.ok(geometry.tools.y >= geometry.help.bottom, 'Help must not overlap the controls');
assert.ok(geometry.help.right <= geometry.footer.right + 1);
}
if (geometry.status.x > geometry.summary.right) assert.ok(Math.abs((geometry.status.y + geometry.status.height / 2) - (geometry.summary.y + geometry.summary.height / 2)) < 2);
}
await cell(3, 1).click();
+157
View File
@@ -0,0 +1,157 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
localStorage.clear();
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map([["a.md", '# Links\n\nOutside table.\n\n| Name | Value |\n| --- | --- |\n| One | Text |\n| Two | Text |\n| Three | Text |\n| Four | Text |\n| Five | [Roadmp](docs/roadmap.md) |\n| Keyboard | Before [Guide](docs/guide.md) after |\n| Wiki | [[guide\\|Guide]] |\n| Repeated | **Prefix** [One](same.md) + [Sec**ond**](same.md "Title") |\n']]);
window.tabMenuTest = { files, prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const output = '.audit/table-link-caret';
await mkdir(output, { recursive: true });
const sourceCell = () => page.locator('.is-source-editing .writer-cell-editor');
async function clickTextAt(locator, offset, button = 'left') {
const point = await locator.evaluate((element, offset) => {
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
let node;
while ((node = walker.nextNode())) {
if (offset > node.textContent.length) { offset -= node.textContent.length; continue; }
const range = document.createRange();
range.setStart(node, offset); range.collapse(true);
const rect = range.getBoundingClientRect();
return { x: rect.x, y: rect.y + rect.height / 2 };
}
throw new Error('No text position');
}, offset);
await page.mouse.click(point.x, point.y, { button });
}
const selected = () => page.evaluate(() => getSelection().toString());
const caretPrefix = () => page.evaluate(() => {
const selection = getSelection(), range = document.createRange();
range.selectNodeContents(document.querySelector('.is-source-editing .writer-cell-editor'));
range.setEnd(selection.anchorNode, selection.anchorOffset);
return range.toString();
});
const documentText = () => page.locator('.cm-content').evaluate(async node => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
return EditorView.findFromDOM(node).state.doc.toString();
});
try {
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height: 1000 });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.writer-table').waitFor();
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme:'default', mode }), theme);
if (width < 1000) {
await page.getByRole('button', { name:'Files', exact:true }).click();
await page.getByRole('button', { name:'Hide outline', exact:true }).click();
}
const cell = page.getByRole('cell', { name:'Row 6, column 2', exact:true });
await clickTextAt(cell.locator('a'), 5);
await sourceCell().waitFor();
assert.equal(await cell.locator('.writer-link-target').innerText(), 'docs/roadmap.md', 'Ordinary click reveals the URL');
assert.equal(await caretPrefix(), '[Roadm', 'The caret stays at the clicked label character');
await page.keyboard.type('a');
assert.equal(await sourceCell().innerText(), '[Roadmap](docs/roadmap.md)');
await page.screenshot({ path:`${output}/click-label-${theme}-${width}.png` });
await page.keyboard.press('Escape');
assert.equal(await cell.locator('a').innerText(), 'Roadmap');
await clickTextAt(cell.locator('a'), 3);
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', { name:'Edit link', exact:true }).click();
assert.equal(await selected(), 'docs/roadmap.md');
assert.equal(await page.getByRole('dialog').count(), 0);
await page.screenshot({ path:`${output}/edit-target-${theme}-${width}.png` });
await page.keyboard.type('docs/changed.md');
await page.keyboard.press('Enter');
assert.equal(await cell.locator('a').getAttribute('href'), 'docs/changed.md');
await page.locator('.cm-line').filter({ hasText:'Outside table.' }).click();
await page.keyboard.press('Control+z');
assert.equal(await cell.locator('a').getAttribute('href'), 'docs/roadmap.md');
await page.keyboard.press('Control+y');
assert.equal(await cell.locator('a').getAttribute('href'), 'docs/changed.md');
await page.keyboard.press('Control+s');
assert.match(await page.evaluate(() => window.tabMenuTest.files.get('a.md')), /\[Roadmap\]\(docs\/changed.md\)/);
const keyboard = page.getByRole('cell', { name:'Row 7, column 2', exact:true });
await clickTextAt(keyboard, 7);
assert.equal(await sourceCell().count(), 0, 'Plain cell text remains rendered');
await page.keyboard.press('ArrowRight');
await sourceCell().waitFor();
assert.equal(await keyboard.locator('.writer-link-target').innerText(), 'docs/guide.md');
assert.equal(await caretPrefix(), 'Before [G');
await page.screenshot({ path:`${output}/keyboard-${theme}-${width}.png` });
await page.keyboard.press('Escape');
const wiki = page.getByRole('cell', { name:'Row 8, column 2', exact:true });
await clickTextAt(wiki.locator('a'), 3);
await sourceCell().waitFor();
assert.equal(await caretPrefix(), '[[guide\\|Gui');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', { name:'Edit link', exact:true }).click();
assert.equal(await selected(), 'guide');
await page.keyboard.type('new-guide');
await page.keyboard.press('Enter');
assert.equal(await wiki.locator('a').getAttribute('href'), 'new-guide');
const repeated = page.getByRole('cell', { name:'Row 9, column 2', exact:true });
await clickTextAt(repeated.locator('a').nth(1), 4);
await sourceCell().waitFor();
assert.equal(await caretPrefix(), '**Prefix** [One](same.md) + [Sec**o');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', { name:'Edit link', exact:true }).click();
assert.equal(await selected(), 'same.md');
await page.keyboard.type('second.md');
await page.keyboard.press('Enter');
assert.equal(await repeated.locator('a').first().getAttribute('href'), 'same.md');
assert.equal(await repeated.locator('a').nth(1).getAttribute('href'), 'second.md');
assert.match(await documentText(), /\[Sec\*\*ond\*\*\]\(second.md "Title"\)/);
assert.deepEqual(await page.evaluate(() => window.tabMenuTest.prompts), []);
}
assert.deepEqual(errors, []);
console.log('PASS: ordinary link click reveals Markdown, exact spelling caret, keyboard entry, inline Edit link, URL selection, wiki aliases, repeated targets, formatted labels, title preservation, save, undo/redo, both themes, and narrow windows. Native WebView acceptance remains open.');
} catch (error) {
console.error(error);
await page.screenshot({ path:`${output}/failure.png` });
console.log(await page.locator('.writer-cell-editor').allTextContents());
console.log({errors, active:await page.evaluate(() => document.activeElement?.outerHTML.slice(0,300))});
throw error;
} finally { await browser.close(); }
+30
View File
@@ -0,0 +1,30 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { documentLinks } from "../src/lib/editor/documentLinks.ts";
import { tableLinkLabelPosition } from "../src/lib/editor/tableLinkSource.ts";
test("table link reveal retains the clicked character through Markdown label marks", () => {
for (const [source, offset, prefix] of [
["[Roadmap](docs/roadmap.md)", 5, "[Roadm"],
['**Prefix** [One](same.md) + [Sec**ond**](same.md "Title")', 4, '**Prefix** [One](same.md) + [Sec**o'],
["[A \\*star](note.md)", 3, "[A \\*"],
["[Use `code`](note.md)", 5, "[Use `c"],
["<https://example.org>", 8, "<https://"],
] as const) {
const link = documentLinks(source).at(-1)!;
assert.equal(source.slice(0, tableLinkLabelPosition(source, link, offset)), prefix);
}
});
test("table wiki links retain literal label text, aliases, spaces, and escaped pipes", () => {
for (const [source, offset, prefix] of [
["[[guide\\|Guide]]", 3, "[[guide\\|Gui"],
["[[guide\\|**Alias**]]", 2, "[[guide\\|**"],
["[[ Guide ]]", 3, "[[ G"],
["[[Guide\\|]]", 2, "[[Gu"],
["[[guide\\|A\\|B]]", 2, "[[guide\\|A\\|"],
] as const) {
const link = documentLinks(source)[0];
assert.equal(source.slice(0, tableLinkLabelPosition(source, link, offset)), prefix);
}
});
+40
View File
@@ -0,0 +1,40 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { characterTheme, characterSyntax, SYNTAX_ROLES } from '../src/lib/theme/characterThemes.ts';
const rgb = (color: string) => color.slice(1).match(/../g)!.map(value => parseInt(value, 16) / 255);
function luminance(color: string) {
return rgb(color).map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4)
.reduce((sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index], 0);
}
function contrast(foreground: string, background: string) {
const values = [luminance(foreground), luminance(background)].sort((a, b) => b - a);
return (values[0] + 0.05) / (values[1] + 0.05);
}
test('Harvest Moon text and syntax stay readable on editor, panel, and selected surfaces', () => {
const palette = characterTheme('harvest-moon')!;
const [background, elevated, active, , dim, text, strong, accent, selection] = palette.surfaces;
for (const foreground of [dim, text, strong, accent, palette.secondary]) {
for (const surface of [background, elevated, active, selection]) {
assert(contrast(foreground, surface) >= 4.5, `${foreground} on ${surface} needs 4.5:1 contrast`);
}
}
for (const [index, foreground] of palette.syntax.entries()) {
for (const surface of [background, elevated, selection]) {
assert(contrast(foreground, surface) >= 4.5, `${SYNTAX_ROLES[index]} on ${surface} needs 4.5:1 contrast`);
}
}
});
test('Harvest Moon uses the warm character colors for all palette roles', () => {
const palette = characterTheme('harvest-moon')!;
for (const color of [...palette.surfaces, palette.secondary, ...palette.syntax]) {
assert.match(color, /^#[0-9a-f]{6}$/i);
const [red, green, blue] = rgb(color);
assert(red >= green && green >= blue, `${color} must follow the copper, amber, red, or cream palette`);
}
assert.equal(palette.mode, 'dark');
assert.equal(Object.keys(characterSyntax('harvest-moon')).length, SYNTAX_ROLES.length);
assert.deepEqual(characterSyntax('unknown'), {});
});
+145
View File
@@ -0,0 +1,145 @@
import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const output = '.audit/theme-typography';
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const errors = [];
const report = [];
await mkdir(output, { recursive: true });
try {
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === 'plugins_snapshot') return { root: 'C:/font-smoke-plugins', plugins: [] };
if (command === 'workspace_last_path') return 'C:\\font-smoke';
if (command === 'workspace_open') return { root: 'C:\\font-smoke', name: 'font-smoke', watch_mode: 'native' };
if (command === 'workspace_list') return [{ name: 'Typography.md', rel_path: 'Typography.md', kind: 'file' }];
if (command === 'workspace_read') return '# A place for your ideas\n\nRead the next chapter, collect clear notes, and keep your work close. Small letters, open spaces, and steady lines help each sentence stay readable.\n\n## Details worth keeping\n\nThe quick brown fox jumps over the lazy dog. Il1 O0 rn m, 0123456789.\n\n`const name = "RuneStone";`\n';
if (command === 'workspace_search') return [];
if (command === 'plugin:event|listen') return args.handler;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage();
const settings = await context.newPage();
for (const page of [main, settings]) page.on('pageerror', error => errors.push(error.message));
await main.goto(origin);
await main.getByText('font-smoke', { exact: true }).waitFor();
await main.keyboard.press('Control+p');
await main.getByRole('textbox', { name: 'Find a file' }).fill('Typography.md');
await main.getByRole('textbox', { name: 'Find a file' }).press('Enter');
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await settings.goto(`${origin}/?settingsWindow=true`);
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
const sessions = new Map();
async function rendered(page, selector) {
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
let session = sessions.get(page);
if (!session) {
session = await context.newCDPSession(page);
await session.send('DOM.enable'); await session.send('CSS.enable'); sessions.set(page, session);
}
const { root } = await session.send('DOM.getDocument');
const { nodeId } = await session.send('DOM.querySelector', { nodeId: root.nodeId, selector });
assert(nodeId, selector);
const { fonts } = await session.send('CSS.getPlatformFontsForNode', { nodeId });
const style = await page.locator(selector).first().evaluate(node => {
const css = getComputedStyle(node);
return { family: css.fontFamily, size: css.fontSize, weight: css.fontWeight, lineHeight: css.lineHeight };
});
return { ...style, rendered: fonts.filter(font => font.glyphCount).map(({ familyName, postScriptName, glyphCount, isCustomFont }) => ({ familyName, postScriptName, glyphCount, isCustomFont })) };
}
const cases = [
['harvest-moon', 'Harvest Moon', 'Constantia', 'Candara', 'Constantia', 'Constantia'],
['crimson-pilot', 'Crimson Pilot', 'Bahnschrift', 'Bahnschrift', 'Segoe UI', 'Bahnschrift'],
['silver-serpent', 'Silver Serpent', 'Palatino Linotype', 'Corbel', 'Palatino Linotype', 'Palatino Linotype'],
];
for (const [theme, label, oldFont, ui, prose, heading] of cases) {
await settings.setViewportSize({ width: 1100, height: 780 });
const picker = settings.locator('.picker').and(settings.getByRole('button', { name: 'Color theme', exact: true }));
await picker.click();
await settings.getByRole('menuitemradio', { name: label, exact: true }).click();
await main.waitForFunction(theme => document.documentElement.dataset.palette === theme, theme);
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).press('Control+Home');
await main.evaluate(() => { getSelection().removeAllRanges(); document.activeElement?.blur(); });
for (const page of [main, settings]) {
await page.evaluate(font => {
for (const role of ['ui', 'prose', 'heading']) document.documentElement.style.setProperty(`--rs-font-${role}`, `"${font}"`);
}, oldFont);
await page.screenshot({ path: `${output}/${theme}-before-${page === main ? 'document' : 'settings'}.png` });
await page.evaluate(() => {
for (const role of ['ui', 'prose', 'heading']) document.documentElement.style.removeProperty(`--rs-font-${role}`);
});
}
const roles = {
ui: await rendered(settings, '.picker[aria-label="Color theme"]'),
prose: await rendered(main, '.cm-line:not(.writer-heading):not(.writer-blank)'),
heading: await rendered(main, '.writer-h1'),
mono: await rendered(settings, '.preview-code'),
};
for (const [role, family] of Object.entries({ ui, prose, heading })) {
assert(roles[role].family.includes(family), `${theme}: ${role} CSS family`);
assert(roles[role].rendered.some(font => font.familyName === family), `${theme}: ${role} actually renders ${family}: ${JSON.stringify(roles[role])}`);
}
assert.equal(roles.ui.size, '13px');
assert.equal(roles.prose.size, '15px');
assert(roles.mono.family.includes('Cascadia Mono'));
assert(roles.mono.rendered.some(font => font.familyName === 'Cascadia Mono'));
await settings.screenshot({ path: `${output}/${theme}-after-settings.png` });
await main.screenshot({ path: `${output}/${theme}-after-document.png` });
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate(node => {
node.focus();
const paragraph = [...node.querySelectorAll('.cm-line')].find(line => line.textContent.includes('Read the next chapter'));
const range = document.createRange(); range.selectNodeContents(paragraph);
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
});
assert((await main.evaluate(() => getSelection().toString())).includes('Read the next chapter'));
await main.screenshot({ path: `${output}/${theme}-selected-prose.png` });
await settings.setViewportSize({ width: 360, height: 480 });
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), `${theme}: narrow overflow`);
await picker.scrollIntoViewIfNeeded(); await picker.focus(); await settings.keyboard.press('Enter');
const current = settings.getByRole('menuitemradio', { name: label, exact: true });
await current.waitFor();
assert(await current.evaluate(node => node === document.activeElement));
await settings.screenshot({ path: `${output}/${theme}-narrow-menu.png` });
await settings.keyboard.press('Escape');
assert(await picker.evaluate(node => node === document.activeElement));
await settings.evaluate(async () => {
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
pluginTools.set(Array.from({ length: 16 }, (_, index) => ({ owner: 'org.example.font-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
});
const bodyBounds = await settings.locator('dialog .body').boundingBox();
assert((await settings.locator('dialog aside').boundingBox()).height <= bodyBounds.height * .4 + 1);
await settings.getByRole('button', { name: 'Plugin settings 16', exact: true }).scrollIntoViewIfNeeded();
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth));
await settings.screenshot({ path: `${output}/${theme}-narrow-long-plugins.png` });
await settings.evaluate(async () => {
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); pluginTools.set([]);
});
const fallback = {};
for (const [role, page, selector] of [['ui', settings, '.picker[aria-label="Color theme"]'], ['prose', main, '.cm-line:not(.writer-heading):not(.writer-blank)'], ['heading', main, '.writer-h1']]) {
await page.evaluate(role => {
const css = getComputedStyle(document.documentElement);
const stack = css.getPropertyValue(`--rs-font-${role}`);
document.documentElement.style.setProperty(`--rs-font-${role}`, stack.slice(stack.indexOf(',') + 1));
}, role);
fallback[role] = await rendered(page, selector);
assert(fallback[role].rendered.length > 0);
await page.evaluate(role => document.documentElement.style.removeProperty(`--rs-font-${role}`), role);
}
report.push({ theme, oldFont, roles, fallback });
console.log(`PASS ${theme}: real UI and prose sizes, rendered fonts, shared monospace, selection, narrow settings, keyboard focus, long plugin navigation`);
}
assert.deepEqual(errors, []);
await writeFile(`${output}/rendered-fonts.json`, JSON.stringify(report, null, 2));
} finally { await browser.close(); }
+137
View File
@@ -0,0 +1,137 @@
import { createRequire } from 'node:module';
import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1280, height: 850 } });
const page = await context.newPage();
page.setDefaultTimeout(10000);
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await context.addInitScript(() => {
window.isTauri = true;
const root = 'C:\\navigation-check';
const folders = new Set(['Untitled', 'Parent', 'Empty']);
const files = new Map([['note.md', '# Note'], ['Parent/existing.md', '# Existing']]);
const state = { folders, files, calls: [] };
window.__NAVIGATION_CHECK__ = state;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
state.calls.push({ command, args });
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'workspace_last_path') return state.noWorkspace ? null : root;
if (command === 'workspace_open') return { root, name: 'navigation-check', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
if (command === 'workspace_write') { files.set(args.rel, args.contents); return; }
if (command === 'workspace_list') {
const prefix = args.rel ? args.rel + '/' : '';
return [...[...folders].filter(path => path.startsWith(prefix) && !path.slice(prefix.length).includes('/')).map(path => ({ name: path.slice(prefix.length), rel_path: path, kind: 'folder' })),
...[...files.keys()].filter(path => path.startsWith(prefix) && !path.slice(prefix.length).includes('/') && !path.startsWith('.runestone/')).map(path => ({ name: path.slice(prefix.length), rel_path: path, kind: 'file' }))];
}
if (command === 'workspace_create') { if (folders.has(args.rel) || files.has(args.rel)) throw new Error('Destination exists'); if (args.kind === 'folder') folders.add(args.rel); else files.set(args.rel, ''); return; }
if (command === 'workspace_rename') {
if (folders.has(args.to) || files.has(args.to)) throw new Error('Destination exists');
if (folders.delete(args.from)) folders.add(args.to);
else { files.set(args.to, files.get(args.from)); files.delete(args.from); }
return;
}
if (command === 'plugin:event|listen') return ++sequence;
if (command === 'plugin:window|is_maximized') return false;
if (command === 'workspace_recent' || command === 'workspace_search') return [];
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const output = '.audit/todo-navigation';
await mkdir(output, { recursive: true });
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const input = () => page.locator('.tree input');
const folderAction = () => page.getByRole('menuitem', { name: 'New folder', exact: true });
async function checkRename(name) {
await input().waitFor();
await page.waitForFunction(() => document.activeElement?.matches('.tree input'));
const state = await input().evaluate(node => ({ name: node.value, start: node.selectionStart, end: node.selectionEnd }));
assert.deepEqual(state, { name, start: 0, end: name.length });
assert.equal(await page.getByRole('dialog').count(), 0, 'New folder uses inline rename');
}
async function setMode(mode) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5194');
await row('Untitled').waitFor();
const welcome = page.locator('.welcome-actions');
await welcome.waitFor();
await welcome.getByRole('button', { name: 'Open browser', exact: true }).waitFor();
assert.deepEqual(await welcome.locator('button').allTextContents().then(values => values.map(value => value.replace(/Ctrl [NOP]/g, '').trim())), ['New file', 'New note', 'Find file', 'Open folder', 'Open browser']);
const firstRow = welcome.locator('.welcome-row').first();
assert.equal(await firstRow.locator('button').count(), 3);
const tops = await firstRow.locator('button').evaluateAll(nodes => nodes.map(node => node.getBoundingClientRect().top));
assert.ok(tops.every(top => top === tops[0]), 'Wide layout has three actions in the first row');
await welcome.getByRole('button', { name: /^New file/ }).focus();
for (const name of ['New note', 'Find file', 'Open folder', 'Open browser']) {
await page.keyboard.press('Tab');
assert.ok((await page.evaluate(() => document.activeElement.textContent)).includes(name), `Tab reaches ${name} in order`);
}
for (const mode of ['dark', 'light']) {
await setMode(mode);
await welcome.getByRole('button', { name: /^New file/ }).focus();
await page.screenshot({ path: `${output}/splash-${mode}.png` });
await page.setViewportSize({ width: 850, height: 650 });
await page.screenshot({ path: `${output}/splash-${mode}-narrow.png` });
assert.ok(await welcome.locator('button').evaluateAll(nodes => nodes.every(node => { const rect = node.getBoundingClientRect(); return rect.left >= 0 && rect.right <= innerWidth; })), 'Narrow splash controls fit');
await page.setViewportSize({ width: 1280, height: 850 });
}
await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 80, y: 320 } });
await folderAction().focus();
await page.keyboard.press('Enter');
await checkRename('untitled 2');
await input().fill('Created folder');
await input().press('Enter');
await row('Created folder').waitFor();
await row('Parent').click();
await row('Parent').click();
assert.equal(await row('Parent').getAttribute('aria-expanded'), 'false');
await row('Parent').click({ button: 'right' });
await folderAction().click();
await checkRename('untitled');
assert.equal(await row('Parent').getAttribute('aria-expanded'), 'true', 'Cached collapsed parent opens for rename');
await input().press('Escape');
await row('Parent/untitled').waitFor();
for (const mode of ['dark', 'light']) {
await setMode(mode);
await row('Parent').click({ button: 'right' });
await folderAction().click();
const expected = mode === 'dark' ? 'untitled 2' : 'untitled 3';
await checkRename(expected);
await page.screenshot({ path: `${output}/new-folder-${mode}.png` });
await page.setViewportSize({ width: 850, height: 650 });
await page.screenshot({ path: `${output}/new-folder-${mode}-narrow.png` });
await input().press('Escape');
await page.setViewportSize({ width: 1280, height: 850 });
}
await row('Empty').click({ button: 'right' });
await folderAction().click();
await checkRename('untitled');
await input().fill('First folder');
await input().press('Enter');
await row('Empty/First folder').waitFor();
assert.equal(await page.evaluate(() => window.__NAVIGATION_CHECK__.folders.has('Empty/First folder')), true);
const emptyPage = await context.newPage();
await emptyPage.addInitScript(() => { window.__NAVIGATION_CHECK__.noWorkspace = true; });
await emptyPage.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5194');
await emptyPage.locator('.welcome-actions').waitFor();
await emptyPage.locator('.welcome-actions').getByRole('button', { name: 'Open browser', exact: true }).waitFor();
assert.deepEqual(await emptyPage.locator('.welcome-actions button').allTextContents().then(values => values.map(value => value.replace(/Ctrl O/g, '').trim())), ['Open folder', 'Open browser']);
await emptyPage.screenshot({ path: `${output}/splash-no-workspace.png` });
await emptyPage.close();
assert.deepEqual(errors, []);
await writeFile(`${output}/checks.json`, JSON.stringify({ passed: true, checks: ['Case-insensitive root name collision', 'Selected inline name and no dialog', 'Enter saves rename', 'Escape retains created folder', 'Collapsed cached parent opens', 'Empty parent', 'Repeated unique names', 'Splash order and three-column maximum', 'Keyboard tab order', 'No workspace actions', 'Dark/light wide/narrow screenshots'], errors }, null, 2));
console.log(`Navigation checks passed. Evidence: ${output}`);
} finally { await browser.close(); }
+115
View File
@@ -0,0 +1,115 @@
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { mkdir } from 'node:fs/promises';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || '../browser-runtime/node_modules/playwright');
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROME_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe' });
const output = '.audit/todo-ui';
await mkdir(output, { recursive: true });
try {
for (const theme of ['light', 'dark']) {
const page = await browser.newPage({ viewport: { width: 1100, height: 780 } });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } }, transformCallback: () => 1, unregisterCallback() {},
invoke: async (command, args = {}) => {
if (command === 'workspace_last_path') return 'C:/todo-ui';
if (command === 'workspace_open') return { root: 'C:/todo-ui', name: 'todo-ui', watch_mode: 'native' };
if (command === 'workspace_list') return [{ name: 'sample.md', rel_path: 'sample.md', kind: 'file' }];
if (command === 'workspace_read') return '# Selection sample\n\nThe same text color applies to each editor.\n';
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'workspace_search') return [];
if (command === 'browser_request') {
if (args.command === 'frameAck') window.blankAcks = (window.blankAcks || 0) + 1;
return window.browserSnapshot;
}
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
});
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('todo-ui', { exact: true }).waitFor();
await page.evaluate(async theme => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode: theme });
const { attachTooltip } = await import('/src/lib/ui/tooltip.ts');
const cell = document.createElement('button');
cell.id = 'tooltip-test'; cell.textContent = 'Formula cell';
Object.assign(cell.style, { position: 'fixed', left: '20px', top: '100px', zIndex: '2000' });
document.body.append(cell);
window.disposeTip = attachTooltip(cell, () => 'B6 · Click to edit · Type = for a formula');
}, theme);
const target = page.locator('#tooltip-test');
await target.hover();
const tooltip = page.locator('.rs-tooltip:popover-open');
await tooltip.waitFor();
assert.equal(await target.getAttribute('title'), null);
assert.equal(await tooltip.evaluate(node => getComputedStyle(node).borderRadius), '5px');
await page.screenshot({ path: `${output}/${theme}-tooltip.png` });
await page.keyboard.press('Escape');
assert.equal(await page.locator('.rs-tooltip:popover-open').count(), 0);
await target.focus();
await tooltip.waitFor();
await page.setViewportSize({ width: 390, height: 620 });
await page.locator('header').first().hover();
await target.hover();
await tooltip.waitFor();
const bounds = await tooltip.boundingBox();
assert(bounds.x >= 8 && bounds.x + bounds.width <= 382);
await page.screenshot({ path: `${output}/${theme}-narrow-tooltip.png` });
await page.evaluate(() => { window.disposeTip(); document.getElementById('tooltip-test').remove(); });
await page.setViewportSize({ width: 1100, height: 780 });
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('sample.md');
await page.getByRole('textbox', { name: 'Find a file' }).press('Enter');
const writer = page.getByRole('textbox', { name: 'Writing editor', exact: true });
await writer.waitFor(); await writer.click(); await page.keyboard.press('Control+a');
const colors = await writer.evaluate(node => {
const probe = document.createElement('span'); probe.style.backgroundColor = 'var(--rs-selection)'; node.append(probe);
const expected = getComputedStyle(probe).backgroundColor; probe.remove();
return { expected, native: getComputedStyle(node, '::selection').backgroundColor,
layer: getComputedStyle(document.querySelector('.cm-selectionBackground')).backgroundColor };
});
assert.equal(colors.native, colors.expected); assert.equal(colors.layer, colors.expected);
await page.screenshot({ path: `${output}/${theme}-writer-selection.png` });
await page.getByRole('group', { name: 'Document view', exact: true }).hover();
await page.getByRole('button', { name: 'Read', exact: true }).click();
const reader = page.locator('.reading');
await reader.waitFor();
assert.equal(await reader.evaluate(node => getComputedStyle(node, '::selection').backgroundColor), colors.expected);
await page.evaluate(async () => {
const { mount } = await import('/node_modules/svelte/src/index-client.js');
const { default: Browser } = await import('/src/lib/browser/Browser.svelte');
const client = await import('/src/lib/browser/client.ts');
const container = document.createElement('div'); container.id = 'browser-test';
Object.assign(container.style, { position: 'fixed', inset: '50px 10px 20px', zIndex: '2000', background: 'linear-gradient(120deg,#945975,#395c72)' });
document.body.append(container);
window.browserSnapshot = { profiles: [{ id: 'user', name: 'User' }], tabs: [{ id: 'blank', profileId: 'user', url: 'about:blank', title: '', loading: false }], bookmarks: [], settings: {} };
client.state.set(window.browserSnapshot);
mount(Browser, { target: container, props: { initial: { tabId: 'blank' }, onSessionChange() {}, async newTab() {} } });
window.browserClient = client;
});
const surface = page.locator('#browser-test .surface');
await page.locator('#browser-test [data-browser-state="ready"]').waitFor();
await page.evaluate(() => window.browserClient.frames.get('blank')({ tabId: 'blank', frameId: 1, width: 10, height: 10, mime: 'image/png', data: 'AA==' }));
assert.equal(await surface.evaluate(node => getComputedStyle(node).backgroundColor), 'rgba(0, 0, 0, 0)');
assert.equal(await surface.locator('img').count(), 0);
assert.equal(await page.evaluate(() => window.blankAcks), 1);
await page.screenshot({ path: `${output}/${theme}-blank-browser.png` });
await page.evaluate(() => {
window.browserSnapshot.tabs[0].url = 'https://example.com/minimal';
window.browserClient.state.set({ ...window.browserSnapshot });
const canvas = document.createElement('canvas'); canvas.width = 10; canvas.height = 10;
const ctx = canvas.getContext('2d'); ctx.fillStyle = 'white'; ctx.fillRect(0, 0, 10, 10);
window.browserClient.frames.get('blank')({ tabId: 'blank', frameId: 2, width: 10, height: 10, mime: 'image/png', data: canvas.toDataURL().split(',')[1] });
});
await surface.locator('img').waitFor();
assert.notEqual(await surface.evaluate(node => getComputedStyle(node).backgroundColor), 'rgba(0, 0, 0, 0)');
assert.deepEqual(errors, []);
await page.close();
}
console.log('To do UI smoke passed: tooltips, selection, blank browser, light/dark/narrow.');
} finally { await browser.close(); }
-3
View File
@@ -62,8 +62,6 @@ try {
window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco;
window.__MONACO__.editor.getEditors().find(e => e.getDomNode()?.isConnected).setValue("My pending edit");
});
await page.getByRole("button", { name: "Terminal", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_open"));
const trigger = page.getByRole("button", { name: "Open folder", exact: true });
const menu = page.getByRole("dialog", { name: "Workspaces", exact: true });
await trigger.click();
@@ -104,7 +102,6 @@ try {
assert.deepEqual(await page.evaluate(() => window.__TEST__.windows), ["D:\\Writing\\Notes", "D:\\Other", "D:\\Projects\\Fresh notes"]);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length), opened);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "plugin:dialog|message").length), 0);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length), 0);
assert.equal(await page.evaluate(() => window.__MONACO__.editor.getEditors().find(e => e.getDomNode()?.isConnected)?.getValue()), "My pending edit");
assert(await page.getByRole("tab", { name: /note\.txt/ }).isVisible());
await trigger.click();
+1 -1
View File
@@ -3130,7 +3130,7 @@ dependencies = [
[[package]]
name = "runestone"
version = "0.1.23+1"
version = "0.1.34"
dependencies = [
"base64 0.23.1",
"dunce",
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "runestone"
version = "0.1.23+1"
version = "0.1.34"
description = "Writing workspace plus script editor"
authors = ["you"]
edition = "2021"
@@ -44,4 +44,4 @@ panic = "abort"
strip = true
[package.metadata.runestone]
version = "0.1.23a"
version = "0.1.34"
+6
View File
@@ -3,6 +3,12 @@ fn main() {
tauri_build::Attributes::new().app_manifest(
tauri_build::AppManifest::new().commands(&[
"theme_export",
"backgrounds_choose_folder",
"backgrounds_default_folder",
"backgrounds_list",
"backgrounds_read",
"backgrounds_read_image_settings",
"backgrounds_write_image_settings",
"spelling_suggestions",
"spelling_menu_install",
"spelling_menu_select",
+13 -2
View File
@@ -2,7 +2,12 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main", "workspace-*", "terminal-*", "browser-*"],
"windows": [
"main",
"workspace-*",
"terminal-*",
"browser-*"
],
"permissions": [
"allow-spelling-menu-install",
"allow-spelling-suggestions",
@@ -76,6 +81,12 @@
"allow-pty-profiles",
"allow-pty-new-window",
"allow-pty-dictation",
"opener:allow-reveal-item-in-dir"
"opener:allow-reveal-item-in-dir",
"allow-backgrounds-choose-folder",
"allow-backgrounds-default-folder",
"allow-backgrounds-list",
"allow-backgrounds-read",
"allow-backgrounds-read-image-settings",
"allow-backgrounds-write-image-settings"
]
}
+11 -2
View File
@@ -2,7 +2,10 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "settings",
"description": "Settings windows and their plugin settings",
"windows": ["settings-main", "settings-workspace-*"],
"windows": [
"settings-main",
"settings-workspace-*"
],
"permissions": [
"allow-theme-export",
"core:default",
@@ -29,6 +32,12 @@
"allow-browser-connect",
"allow-browser-stop",
"allow-completion-request",
"allow-completion-cancel"
"allow-completion-cancel",
"allow-backgrounds-choose-folder",
"allow-backgrounds-default-folder",
"allow-backgrounds-list",
"allow-backgrounds-read",
"allow-backgrounds-read-image-settings",
"allow-backgrounds-write-image-settings"
]
}
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-choose-folder"
description = "Enables the backgrounds_choose_folder command without any pre-configured scope."
commands.allow = ["backgrounds_choose_folder"]
[[permission]]
identifier = "deny-backgrounds-choose-folder"
description = "Denies the backgrounds_choose_folder command without any pre-configured scope."
commands.deny = ["backgrounds_choose_folder"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-default-folder"
description = "Enables the backgrounds_default_folder command without any pre-configured scope."
commands.allow = ["backgrounds_default_folder"]
[[permission]]
identifier = "deny-backgrounds-default-folder"
description = "Denies the backgrounds_default_folder command without any pre-configured scope."
commands.deny = ["backgrounds_default_folder"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-list"
description = "Enables the backgrounds_list command without any pre-configured scope."
commands.allow = ["backgrounds_list"]
[[permission]]
identifier = "deny-backgrounds-list"
description = "Denies the backgrounds_list command without any pre-configured scope."
commands.deny = ["backgrounds_list"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-read"
description = "Enables the backgrounds_read command without any pre-configured scope."
commands.allow = ["backgrounds_read"]
[[permission]]
identifier = "deny-backgrounds-read"
description = "Denies the backgrounds_read command without any pre-configured scope."
commands.deny = ["backgrounds_read"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-read-image-settings"
description = "Enables the backgrounds_read_image_settings command without any pre-configured scope."
commands.allow = ["backgrounds_read_image_settings"]
[[permission]]
identifier = "deny-backgrounds-read-image-settings"
description = "Denies the backgrounds_read_image_settings command without any pre-configured scope."
commands.deny = ["backgrounds_read_image_settings"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-write-image-settings"
description = "Enables the backgrounds_write_image_settings command without any pre-configured scope."
commands.allow = ["backgrounds_write_image_settings"]
[[permission]]
identifier = "deny-backgrounds-write-image-settings"
description = "Denies the backgrounds_write_image_settings command without any pre-configured scope."
commands.deny = ["backgrounds_write_image_settings"]
+425
View File
@@ -0,0 +1,425 @@
use crate::plugins::PluginState;
use base64::Engine;
use serde::Serialize;
use std::fs::{self, File, Metadata};
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use tauri::{AppHandle, Manager, Window};
use tauri_plugin_dialog::DialogExt;
const IMAGE_LIMIT: u64 = 50 * 1024 * 1024;
const SETTINGS_LIMIT: u64 = 1024 * 1024;
const SETTINGS_FILE: &str = ".runestone-backgrounds.json";
type Result<T> = std::result::Result<T, String>;
#[derive(Debug, Serialize)]
pub struct BackgroundFile {
name: String,
}
fn fail(error: impl std::fmt::Display) -> String {
error.to_string()
}
fn require_plugin(app: &AppHandle, window: &Window, id: &str) -> Result<()> {
app.state::<PluginState>()
.require_lease(app, window.label(), id)
.map_err(|_| "The plugin is not enabled in this window.".into())
}
fn folder_root(folder: &Path) -> Result<PathBuf> {
if !folder.is_absolute()
|| folder
.components()
.any(|part| matches!(part, Component::ParentDir))
{
return Err("Supply an absolute background folder path without parent segments.".into());
}
let root = dunce::canonicalize(folder).map_err(fail)?;
if !root.is_dir() {
return Err("The background folder does not exist.".into());
}
Ok(root)
}
fn is_link(metadata: &Metadata) -> bool {
if metadata.file_type().is_symlink() {
return true;
}
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
return metadata.file_attributes() & 0x400 != 0;
}
#[cfg(not(windows))]
false
}
fn supported(name: &str) -> bool {
Path::new(name)
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
matches!(
extension.to_ascii_lowercase().as_str(),
"png" | "jpg" | "jpeg" | "gif" | "webp"
)
})
}
fn image_path(root: &Path, name: &str) -> Result<PathBuf> {
if name.is_empty()
|| name.contains(['/', '\\', ':'])
|| name.ends_with(['.', ' '])
|| !supported(name)
|| Path::new(name).components().count() != 1
|| !matches!(
Path::new(name).components().next(),
Some(Component::Normal(_))
)
{
return Err("Supply one PNG, JPEG, GIF, or WebP filename.".into());
}
let path = root.join(name);
let metadata = fs::symlink_metadata(&path).map_err(fail)?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Background images must be ordinary files, not links.".into());
}
let resolved = dunce::canonicalize(&path).map_err(fail)?;
if resolved.parent() != Some(root) {
return Err("The background image is outside its folder.".into());
}
Ok(path)
}
fn list_images(folder: &Path) -> Result<Vec<BackgroundFile>> {
let root = folder_root(folder)?;
let mut images = Vec::new();
for entry in fs::read_dir(&root).map_err(fail)? {
let entry = entry.map_err(fail)?;
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
if supported(&name) && image_path(&root, &name).is_ok() {
images.push(BackgroundFile { name });
}
}
images.sort_by(|a, b| a.name.cmp(&b.name));
Ok(images)
}
fn raster_signature(bytes: &[u8]) -> bool {
bytes.starts_with(b"\x89PNG\r\n\x1a\n")
|| bytes.starts_with(b"\xff\xd8\xff")
|| bytes.starts_with(b"GIF87a")
|| bytes.starts_with(b"GIF89a")
|| (bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP")
}
fn read_image(folder: &Path, name: &str) -> Result<Vec<u8>> {
let root = folder_root(folder)?;
let path = image_path(&root, name)?;
let mut options = File::options();
options.read(true);
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
// Open the entry itself so a replaced link cannot redirect the read.
options.custom_flags(0x00200000);
}
let file = options.open(&path).map_err(fail)?;
let metadata = file.metadata().map_err(fail)?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Background images must be ordinary files, not links.".into());
}
if metadata.len() > IMAGE_LIMIT {
return Err("The background image exceeds 50 MiB.".into());
}
image_path(&root, name)?;
let mut bytes = Vec::new();
file.take(IMAGE_LIMIT + 1)
.read_to_end(&mut bytes)
.map_err(fail)?;
if bytes.len() as u64 > IMAGE_LIMIT {
return Err("The background image exceeds 50 MiB.".into());
}
if !raster_signature(&bytes) {
return Err("The file is not a supported raster image.".into());
}
Ok(bytes)
}
#[tauri::command]
pub async fn backgrounds_default_folder(
app: AppHandle,
window: Window,
id: String,
) -> Result<String> {
require_plugin(&app, &window, &id)?;
let pictures = app.path().picture_dir().map_err(fail)?;
let folder = pictures.join("RuneStone Backgrounds");
fs::create_dir_all(&folder).map_err(fail)?;
require_plugin(&app, &window, &id)?;
folder_root(&folder).map(|root| root.to_string_lossy().into_owned())
}
#[tauri::command]
pub async fn backgrounds_choose_folder(
app: AppHandle,
window: Window,
id: String,
) -> Result<Option<String>> {
require_plugin(&app, &window, &id)?;
let picker_app = app.clone();
let picker_window = window.clone();
let selected = tauri::async_runtime::spawn_blocking(move || {
picker_app
.dialog()
.file()
.set_parent(&picker_window)
.set_title("Choose background image folder")
.blocking_pick_folder()
})
.await
.map_err(fail)?;
require_plugin(&app, &window, &id)?;
selected
.map(|source| {
let path = source.into_path().map_err(fail)?;
folder_root(&path).map(|root| root.to_string_lossy().into_owned())
})
.transpose()
}
#[tauri::command]
pub async fn backgrounds_list(
app: AppHandle,
window: Window,
id: String,
folder: String,
) -> Result<Vec<BackgroundFile>> {
require_plugin(&app, &window, &id)?;
let result = tauri::async_runtime::spawn_blocking(move || list_images(Path::new(&folder)))
.await
.map_err(fail)??;
require_plugin(&app, &window, &id)?;
Ok(result)
}
#[tauri::command]
pub async fn backgrounds_read(
app: AppHandle,
window: Window,
id: String,
folder: String,
name: String,
) -> Result<String> {
require_plugin(&app, &window, &id)?;
let result =
tauri::async_runtime::spawn_blocking(move || read_image(Path::new(&folder), &name))
.await
.map_err(fail)??;
require_plugin(&app, &window, &id)?;
Ok(base64::engine::general_purpose::STANDARD.encode(result))
}
fn read_image_settings(folder: &Path) -> Result<Option<String>> {
let root = folder_root(folder)?;
let path = root.join(SETTINGS_FILE);
let metadata = match fs::symlink_metadata(&path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(fail(error)),
};
if !metadata.is_file() || is_link(&metadata) || metadata.len() > SETTINGS_LIMIT {
return Err("Image settings must be an ordinary file within 1 MiB.".into());
}
let mut options = File::options();
options.read(true);
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
options.custom_flags(0x00200000);
}
let file = options.open(&path).map_err(fail)?;
let metadata = file.metadata().map_err(fail)?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Image settings must be an ordinary file, not a link.".into());
}
let mut bytes = Vec::new();
file.take(SETTINGS_LIMIT + 1).read_to_end(&mut bytes).map_err(fail)?;
if bytes.len() as u64 > SETTINGS_LIMIT {
return Err("Image settings exceed 1 MiB.".into());
}
String::from_utf8(bytes).map(Some).map_err(fail)
}
fn write_image_settings(folder: &Path, contents: &str, expected: Option<&str>) -> Result<()> {
static WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
let _lock = WRITE_LOCK.lock().map_err(fail)?;
if contents.len() as u64 > SETTINGS_LIMIT {
return Err("Image settings exceed 1 MiB.".into());
}
let value: serde_json::Value = serde_json::from_str(contents).map_err(fail)?;
if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1)
|| !value.get("images").is_some_and(serde_json::Value::is_object)
{
return Err("Use image settings with schema 1 and an images object.".into());
}
let root = folder_root(folder)?;
if read_image_settings(&root)?.as_deref() != expected {
return Err("Image settings changed. Reload them before saving.".into());
}
let path = root.join(SETTINGS_FILE);
if expected.is_some() {
crate::workspace::write_text(&path, contents, expected).map_err(fail)
} else {
// Publish a complete new file without replacing a file created by another process.
let temp = root.join(format!(".runestone-backgrounds-{}.tmp", uuid::Uuid::new_v4()));
let result = (|| -> Result<()> {
use std::io::Write;
let mut file = File::options().write(true).create_new(true).open(&temp).map_err(fail)?;
file.write_all(contents.as_bytes()).map_err(fail)?;
file.sync_all().map_err(fail)?;
drop(file);
fs::hard_link(&temp, &path).map_err(fail)
})();
let _ = fs::remove_file(temp);
result
}
}
#[tauri::command]
pub async fn backgrounds_read_image_settings(app: AppHandle, window: Window, id: String, folder: String) -> Result<Option<String>> {
require_plugin(&app, &window, &id)?;
let result = tauri::async_runtime::spawn_blocking(move || read_image_settings(Path::new(&folder))).await.map_err(fail)??;
require_plugin(&app, &window, &id)?;
Ok(result)
}
#[tauri::command]
pub async fn backgrounds_write_image_settings(app: AppHandle, window: Window, id: String, folder: String, contents: String, expected: Option<String>) -> Result<()> {
require_plugin(&app, &window, &id)?;
// Check the lease again immediately before the write on the blocking worker.
tauri::async_runtime::spawn_blocking(move || {
require_plugin(&app, &window, &id)?;
write_image_settings(Path::new(&folder), &contents, expected.as_deref())
}).await.map_err(fail)?
}
#[cfg(test)]
mod tests {
use super::*;
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
let root = std::env::temp_dir()
.join(format!("runestone-backgrounds-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
Self(root)
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn image_settings_preserve_external_changes_and_validate_file_limits() {
let fixture = Fixture::new();
let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#;
let next = r#"{"schema":1,"images":{}}"#;
assert_eq!(read_image_settings(&fixture.0).unwrap(), None);
write_image_settings(&fixture.0, first, None).unwrap();
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
assert!(write_image_settings(&fixture.0, next, None).is_err());
assert!(write_image_settings(&fixture.0, next, Some("stale")).is_err());
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
write_image_settings(&fixture.0, next, Some(first)).unwrap();
assert!(write_image_settings(&fixture.0, r#"{"schema":2,"images":{}}"#, Some(next)).is_err());
assert!(write_image_settings(&fixture.0, &"x".repeat(SETTINGS_LIMIT as usize + 1), Some(next)).is_err());
File::create(fixture.0.join(SETTINGS_FILE)).unwrap().set_len(SETTINGS_LIMIT + 1).unwrap();
assert!(read_image_settings(&fixture.0).is_err());
}
#[test]
fn listing_is_nonrecursive_and_filters_extensions() {
let fixture = Fixture::new();
fs::write(fixture.0.join("a.PNG"), b"\x89PNG\r\n\x1a\n").unwrap();
fs::write(fixture.0.join("b.jpg"), b"\xff\xd8\xff").unwrap();
fs::write(fixture.0.join("text.svg"), b"<svg />").unwrap();
fs::create_dir(fixture.0.join("nested.gif")).unwrap();
fs::write(fixture.0.join("nested.gif/hidden.png"), b"png").unwrap();
let names: Vec<_> = list_images(&fixture.0)
.unwrap()
.into_iter()
.map(|image| image.name)
.collect();
assert_eq!(names, vec!["a.PNG", "b.jpg"]);
assert_eq!(
read_image(&fixture.0, "a.PNG").unwrap(),
b"\x89PNG\r\n\x1a\n"
);
}
#[test]
fn reads_reject_traversal_invalid_images_and_oversized_files() {
let fixture = Fixture::new();
for name in [
"../escape.png",
"nested/image.png",
"nested\\image.png",
"C:\\image.png",
"image.png:stream",
"image.svg",
] {
assert!(read_image(&fixture.0, name).is_err(), "{name}");
}
assert!(list_images(Path::new("relative")).is_err());
fs::write(fixture.0.join("invalid.png"), b"<svg />").unwrap();
assert!(read_image(&fixture.0, "invalid.png")
.unwrap_err()
.contains("raster"));
let file = File::create(fixture.0.join("large.png")).unwrap();
file.set_len(IMAGE_LIMIT + 1).unwrap();
assert!(read_image(&fixture.0, "large.png")
.unwrap_err()
.contains("50 MiB"));
}
#[test]
fn raster_types_are_recognized() {
for bytes in [
b"\x89PNG\r\n\x1a\n".as_slice(),
b"\xff\xd8\xff",
b"GIF87a",
b"GIF89a",
b"RIFF0000WEBP",
] {
assert!(raster_signature(bytes));
}
assert!(!raster_signature(b"RIFF0000WAVE"));
}
#[test]
fn links_cannot_escape_the_folder() {
let fixture = Fixture::new();
let outside = Fixture::new();
let original = outside.0.join("outside.png");
fs::write(&original, b"\x89PNG\r\n\x1a\n").unwrap();
let link = fixture.0.join("link.png");
#[cfg(unix)]
std::os::unix::fs::symlink(&original, &link).unwrap();
#[cfg(windows)]
if let Err(error) = std::os::windows::fs::symlink_file(&original, &link) {
if error.raw_os_error() == Some(1314) {
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
return;
}
panic!("{error}");
}
assert!(list_images(&fixture.0).unwrap().is_empty());
assert!(read_image(&fixture.0, "link.png").is_err());
}
}
+2 -1
View File
@@ -29,6 +29,7 @@ const COMMANDS: &[&str] = &[
"adoptTab",
"resize",
"visible",
"focus",
"input",
"insertText",
"edit",
@@ -414,7 +415,7 @@ impl BrowserState {
let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id }));
return Ok(worker.routing.lock().map_err(fail)?.snapshot(result, owner));
}
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "input", "insertText", "edit", "contextAction", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
match worker.routing.lock().map_err(fail)?.owners.get(id) {
Some(window) if window == owner => {},
+7
View File
@@ -8,6 +8,7 @@ mod completion;
mod settings;
mod spelling;
mod theme;
mod backgrounds;
use pty::PtyState;
use tauri::Manager;
@@ -25,6 +26,12 @@ pub fn run() {
.manage(completion::CompletionState::default())
.manage(settings::SettingsState::default())
.invoke_handler(tauri::generate_handler![
backgrounds::backgrounds_choose_folder,
backgrounds::backgrounds_default_folder,
backgrounds::backgrounds_list,
backgrounds::backgrounds_read,
backgrounds::backgrounds_read_image_settings,
backgrounds::backgrounds_write_image_settings,
theme::theme_export,
spelling::spelling_menu_install,
spelling::spelling_suggestions,
+1 -1
View File
@@ -613,7 +613,7 @@ pub fn workspace_write(
write_text(&path, &contents, expected.as_deref())
}
fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> WsResult<()> {
pub(crate) fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> WsResult<()> {
if let Some(expected) = expected {
let current = fs::read_to_string(path).map_err(|_| {
err("Save blocked: file was removed or cannot be read. Your edits are still open.")
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "RuneStone",
"version": "0.1.23+1",
"version": "0.1.34",
"identifier": "com.runestone.app",
"build": {
"beforeDevCommand": "pnpm dev",
+40 -5
View File
@@ -48,6 +48,23 @@ button:disabled {
::selection {
background: var(--rs-selection);
color: var(--rs-selection-text);
}
.rs-tooltip {
position: fixed;
inset: auto;
margin: 0;
max-width: min(280px, calc(100vw - 16px));
padding: var(--rs-tooltip-padding);
border: 1px solid var(--rs-border);
border-radius: var(--rs-control-radius);
background: var(--rs-tooltip-bg);
color: var(--rs-tooltip-text);
box-shadow: var(--rs-tooltip-shadow);
font: var(--rs-tooltip-font-size)/1.5 var(--rs-font-ui);
white-space: pre-line;
pointer-events: none;
}
::-webkit-scrollbar {
@@ -124,8 +141,6 @@ button:disabled {
.note-title-button .action-icon { opacity: .45; }
.note-title-button:hover .action-icon, .note-title-button:focus-visible .action-icon { opacity: 1; color: var(--rs-accent); }
.note-title-button:focus-visible { outline: 1px solid var(--rs-accent); outline-offset: 4px; border-radius: 3px; }
.note-title-help { display: none; position: absolute; top: 100%; left: 0; z-index: 5; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: 4px; background: var(--rs-bg-elevated); color: var(--rs-text); font: 12px/1.5 var(--rs-font-ui); white-space: nowrap; }
.note-title-button:hover .note-title-help, .note-title-button:focus-visible .note-title-help { display: block; }
.note-title-input { box-sizing: border-box; width: 100%; min-width: 0; padding: 0; border: 0; border-radius: 2px; outline: 1px solid var(--rs-accent); outline-offset: 4px; background: transparent; color: inherit; font: inherit; }
.note-title-input[aria-invalid] { outline-color: var(--rs-danger, #e57878); }
.note-title-error { margin: -.8em 0 1em; color: var(--rs-danger, #e57878); font: 13px/1.5 var(--rs-font-ui); }
@@ -184,7 +199,7 @@ button:disabled {
}
.reading pre {
position: relative;
background: var(--rs-bg-elevated);
background: var(--rs-code-block-bg);
border: 1px solid var(--rs-border);
border-radius: 8px;
padding: 18px 20px;
@@ -194,6 +209,28 @@ button:disabled {
tab-size: 4;
}
.reading pre.md-code { padding-top: 44px; }
/* Monaco's command picker uses the host selection and control dimensions. */
.quick-input-widget .quick-input-list .monaco-list-row {
border-radius: var(--rs-item-selection-radius);
}
.quick-input-widget .quick-input-list .monaco-list-row:is(:hover, .focused, .selected) {
background: var(--rs-item-selection-bg) !important;
color: var(--rs-text) !important;
}
.quick-input-widget .quick-input-list .monaco-list-row.focused {
outline: var(--rs-item-selection-width) solid var(--rs-item-selection-border) !important;
outline-offset: calc(-1 * var(--rs-item-selection-width));
}
.quick-input-widget .monaco-inputbox {
border-radius: var(--rs-control-radius) !important;
border-color: var(--rs-border) !important;
}
.quick-input-widget .monaco-inputbox:is(.synthetic-focus, :focus-within) {
outline: var(--rs-item-selection-width) solid var(--rs-item-selection-border) !important;
outline-offset: calc(-1 * var(--rs-item-selection-width));
}
.quick-input-widget .monaco-inputbox input:focus { outline: none !important; }
.reading pre code {
background: transparent;
padding: 0;
@@ -272,7 +309,6 @@ button:disabled {
.image-action:hover, .image-action:focus-visible { background: var(--rs-bg-active); color: var(--rs-text-strong); }
.image-action:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: 1px; }
.image-action:disabled { opacity: .4; cursor: default; }
.image-action:hover::after, .image-action:focus-visible::after { content: attr(data-tooltip); position: absolute; top: calc(100% + 5px); right: 0; width: max-content; z-index: 5; padding: 4px 8px; background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: 4px; font: 12px/1.5 var(--rs-font-ui); pointer-events: none; }
.image-lightbox { position: fixed; inset: 0; width: 100vw; height: 100vh; max-width: none; max-height: none; margin: 0; padding: 0; border: 0; background: #090a0de8; color: var(--rs-text); }
.image-lightbox[open] { display: flex; flex-direction: column; }
.image-lightbox::backdrop { background: #0009; }
@@ -371,7 +407,6 @@ button:disabled {
.table-drag-handle .action-icon { width: 18px; height: 18px; pointer-events: none; }
.table-drag-column .action-icon { transform: rotate(90deg); }
.table-drag-handle:hover, .table-drag-handle:focus-visible:not([data-pointer-focus]) { opacity: 1; color: var(--rs-text); background: var(--rs-bg-active); outline: 2px solid var(--rs-accent); outline-offset: -2px; z-index: 2; }
.table-drag-handle:focus-visible:not([data-pointer-focus])::after { content: attr(data-tooltip); position: absolute; top: 100%; left: var(--table-tooltip-left, 0); z-index: 10; box-sizing: border-box; width: max-content; max-width: var(--table-tooltip-width, 260px); padding: 5px 8px; border: 1px solid var(--rs-border); border-radius: 4px; background: var(--rs-bg-elevated); color: var(--rs-text); font: 12px/1.4 var(--rs-font-ui); pointer-events: none; }
.writer-table.is-table-dragging, .writer-table.is-table-dragging * { cursor: grabbing !important; user-select: none; }
.writer-table.is-table-dragging .table-drag-handle::after { display: none; }
.table-drop-indicator { position: absolute; z-index: 3; border-radius: 2px; background: var(--rs-accent); pointer-events: none; }
+25 -10
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { onMount, untrack, tick } from 'svelte';
import IconButton from '$lib/ui/IconButton.svelte';
import Icon from '$lib/ui/Icon.svelte';
import { state as browserState, pageErrors, request, frames, pageEvents, type PageMenu, type BrowserFrame } from './client';
import type { ActionMenuItem } from '$lib/ui/actionMenu';
import { showActionMenu } from '$lib/ui/managedActionMenu';
@@ -13,14 +14,24 @@
const tabId = $derived(status.tabId);
const ready = $derived(status.phase === 'ready');
const current = $derived($browserState?.tabs.find(tab => tab.id === tabId));
const blank = $derived(!current?.url || current.url === 'about:blank');
let address = $state(''); let editing = $state(false);
let image = $state(''); let surface: HTMLDivElement; let addressField: HTMLInputElement;
let width = 1000, height = 700, textInput: HTMLTextAreaElement, composing = false;
let inputQueue = Promise.resolve();
const orderedInput = (command: string, args: Record<string, unknown>) => inputQueue = inputQueue.then(() => send(command, args));
function pageFocus(focused: boolean) { void orderedInput('focus', { focused }); }
const wheels = new WheelQueue(input => send('input', { input }));
let displayedFrame: BrowserFrame | undefined;
let closeMenu: (() => void) | undefined;
function chooseProfile(event: MouseEvent) {
closeMenu?.();
const anchor = event.currentTarget as HTMLButtonElement;
const rect = anchor.getBoundingClientRect();
closeMenu = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: 'Browser profile',
items: ($browserState?.profiles || []).map(profile => ({ label: profile.name, radio: true,
checked: profile.id === current?.profileId, run: () => void openTab(profile.id) })) }).close;
}
let opening = $state(false), openingError = $state(''), mounted = $state(false);
let findOpen = $state(false), findText = $state('');
let findField: HTMLInputElement | undefined = $state();
@@ -60,7 +71,9 @@
frames.set(id, frame => {
if (displayedFrame) acknowledgeFrame();
if (frame.width > 0 && frame.height > 0 && ['image/png', 'image/jpeg'].includes(frame.mime)) {
displayedFrame = frame; image = `data:${frame.mime};base64,${frame.data}`;
displayedFrame = frame;
if (blank) { image = ''; acknowledgeFrame(); }
else image = `data:${frame.mime};base64,${frame.data}`;
}
});
pageEvents.set(id, event => {
@@ -199,18 +212,18 @@
if (type === 'keyDown' && [...event.key].length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) void orderedInput('insertText', { text: event.key });
}
</script>
<svelte:window onblur={stopScroll} />
<svelte:document onvisibilitychange={() => { if (document.hidden) stopScroll(); }} />
<div class="browser" data-browser-tab={tabId} data-browser-state={status.phase}>
<svelte:window onblur={() => { stopScroll(); pageFocus(false); }} onfocus={() => { if (surface?.contains(document.activeElement)) pageFocus(true); }} />
<svelte:document onvisibilitychange={() => { if (document.hidden) { stopScroll(); pageFocus(false); } else if (surface?.contains(document.activeElement)) pageFocus(true); }} />
<div class="browser" class:blank data-browser-tab={tabId} data-browser-state={status.phase}>
<form class="toolbar" onsubmit={event => { event.preventDefault(); editing = false; void send('navigate', { input: address }); surface.focus(); }}>
<IconButton icon="arrow-left" label="Back" disabled={!ready || !current?.canBack} onclick={() => void send('back')} />
<IconButton icon="arrow-right" label="Forward" disabled={!ready || !current?.canForward} onclick={() => void send('forward')} />
<IconButton icon={current?.loading ? 'stop' : 'refresh'} label={current?.loading ? 'Stop loading' : 'Reload'} disabled={!ready} onclick={() => void send(current?.loading ? 'stop' : 'reload')} />
<input bind:this={addressField} bind:value={address} disabled={!ready} onfocus={() => editing = true} onblur={() => editing = false} aria-label="Address or search" placeholder="Search or enter an address" spellcheck="false" autocomplete="off">
<IconButton icon="bookmark" label="Bookmark this page" disabled={!ready || !current?.url.startsWith('http')} onclick={() => void send('bookmark')} />
<select aria-label="Browser profile" value={current?.profileId} disabled={opening} onchange={event => void openTab(event.currentTarget.value)}>
{#each $browserState?.profiles || [] as profile}<option value={profile.id}>{profile.name}</option>{/each}
</select>
<button type="button" class="profile-choice" aria-label="Browser profile" aria-haspopup="menu" disabled={opening} onclick={chooseProfile}>
{$browserState?.profiles.find(profile => profile.id === current?.profileId)?.name ?? 'Profile'}<Icon icon="chevron-down" />
</button>
</form>
{#if findOpen}
<!-- svelte-ignore a11y_no_noninteractive_element_interactions (Find controls share the Escape shortcut.) -->
@@ -240,13 +253,14 @@
<div class="surface" class:autoscroll={!!scrollAnchor} bind:this={surface} role="application" aria-label="Web page" tabindex="0"
onmousedown={event => pointer(event, 'mouseDown')} onmouseup={event => pointer(event, 'mouseUp')}
onmousemove={event => pointer(event, 'mouseMove')} onwheel={event => pointer(event, 'mouseWheel')}
onfocusin={() => pageFocus(true)} onfocusout={event => { if (!surface.contains(event.relatedTarget as Node | null)) pageFocus(false); }}
onkeydown={event => key(event, 'keyDown')} onkeyup={event => key(event, 'keyUp')} onblur={stopScroll} onmouseleave={stopScroll} onauxclick={event => event.preventDefault()} oncontextmenu={event => event.preventDefault()}>
<textarea class="text-input" bind:this={textInput} aria-label="Web page text input" autocomplete="off" spellcheck="false"
oncompositionstart={() => composing = true}
oncompositionend={event => { composing = false; if (event.data) void orderedInput('insertText', { text: event.data }); textInput.value = ''; }}
oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
onblur={stopScroll}></textarea>
{#if image && ready}<img src={image} alt="Web page rendered by the browser" draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
{#if image && ready && !blank}<img src={image} alt="Web page rendered by the browser" draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
</div>
</div>
@@ -255,9 +269,10 @@
.browser{display:flex;flex-direction:column;width:100%;height:100%;min-height:200px;background:var(--rs-bg);color:var(--rs-text);font-family:var(--rs-font-ui)}
.toolbar,.findbar{display:flex;align-items:center;gap:4px;padding:5px 8px;border-bottom:1px solid var(--rs-border);background:var(--rs-bg-elevated)}
.toolbar{flex-wrap:wrap}.toolbar input{flex:1 1 120px}.findbar input{max-width:320px}.find-count{font-size:12px;white-space:nowrap;color:var(--rs-text-dim);min-width:66px}
input,select{min-width:0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;padding:5px 8px}
input{flex:1}select{max-width:160px}input:focus-visible,select:focus-visible{outline:2px solid var(--rs-accent)}
input,.profile-choice{min-width:0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;padding:5px 8px}
input{flex:1}.profile-choice{max-width:160px;display:flex;align-items:center;gap:var(--rs-menu-icon-gap);cursor:pointer}input:focus-visible,.profile-choice:focus-visible{outline:2px solid var(--rs-accent)}
.surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)}
.browser.blank,.blank .surface{background:transparent}
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);font-size:20px;pointer-events:none;box-shadow:0 1px 4px #0006}
img{display:block;width:100%;height:100%;pointer-events:none;user-select:none}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px}
.error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)}
+15 -3
View File
@@ -1,5 +1,7 @@
<script lang="ts">
import { onDestroy } from 'svelte';
import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import { request } from './client';
let { profileId }: { profileId: string } = $props();
type Cookie = { id: string; name: string; domain: string; path: string };
@@ -7,6 +9,16 @@
type Data = { profileId: string; cookies: Cookie[]; history: Visit[] };
let data = $state<Data | null>(null), error = $state(''), busy = $state(false), query = $state('');
let kind = $state<'cookies' | 'history'>('cookies');
let closePicker = () => {};
onDestroy(() => closePicker());
function chooseKind(event: MouseEvent) {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement, rect = anchor.getBoundingClientRect();
closePicker = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: 'Web data type',
parent: anchor.closest('dialog') ?? undefined,
items: (['cookies', 'history'] as const).map(value => ({ label: value === 'cookies' ? 'Cookies' : 'History',
radio: true, checked: kind === value, run: () => kind = value })) }).close;
}
let generation = 0;
const cookies = $derived((data?.cookies || []).filter(item => `${item.domain} ${item.name} ${item.path}`.toLowerCase().includes(query.toLowerCase())));
const history = $derived((data?.history || []).filter(item => `${item.title} ${item.url}`.toLowerCase().includes(query.toLowerCase())));
@@ -26,7 +38,7 @@
</script>
<section aria-label="Individual web data">
<div class="toolbar">
<label>Show<select aria-label="Web data type" bind:value={kind}><option value="cookies">Cookies</option><option value="history">History</option></select></label>
<div class="choice"><span>Show</span><button type="button" aria-label="Web data type" aria-haspopup="menu" onclick={chooseKind}>{kind === 'cookies' ? 'Cookies' : 'History'}<Icon icon="chevron-down" /></button></div>
<label class="search">Filter<input type="search" aria-label="Filter web data" bind:value={query} placeholder="Search this profile"></label>
<button disabled={busy} onclick={() => void refresh()}><Icon icon="refresh" />Refresh</button>
</div>
@@ -45,9 +57,9 @@
</section>
<style>
section{margin-top:var(--rs-settings-section-gap)}.toolbar{display:flex;align-items:end;gap:var(--rs-settings-gap);flex-wrap:wrap}
label{display:flex;flex-direction:column;gap:4px}.search{flex:1;min-width:150px}input,select,button{min-height:var(--rs-settings-control-height);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);font:inherit;padding:4px 8px}
label,.choice{display:flex;flex-direction:column;gap:4px}.search{flex:1;min-width:150px}input,button{min-height:var(--rs-settings-control-height);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);font:inherit;padding:4px 8px}
button{display:inline-flex;align-items:center;justify-content:center;gap:6px;flex:none;cursor:pointer}button:hover{background:var(--rs-bg-active)}button:disabled{opacity:.6;cursor:wait}
button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px}
button:focus-visible,input:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px}
p,small{font-size:var(--rs-settings-description-size);color:var(--rs-text-dim);line-height:1.5}.entries{max-height:320px;overflow:auto;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);padding:0 var(--rs-settings-row-padding)}
.entry{display:flex;gap:var(--rs-settings-gap);align-items:center;padding:var(--rs-settings-row-padding) 0}.entry+.entry{border-top:1px solid var(--rs-border)}.entry>div{flex:1;min-width:0;overflow-wrap:anywhere}small{display:block}strong{font-weight:500}[role=alert]{color:var(--rs-error)}
@media(max-width:450px){.entry{flex-wrap:wrap}.entry>div{flex-basis:100%}}
+31 -9
View File
@@ -4,12 +4,14 @@
import { isMarkdownPath, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { editorSession } from "./sessions";
import { editorSession, releaseEditorSession } from "./sessions";
import { registerSelection } from "./selection";
import { monacoChrome } from "./monacoChrome";
import { codeFont } from "./codeFont";
import { connectMonacoCompletion } from "$lib/completion/monaco";
import { markdownMenu } from "./markdownMenu";
import type { DocumentLinkActions } from "./linkMenu";
import { codeMenu } from "./codeMenu";
import type { TableContextActions } from "./tableCellActions";
import { documentLinks, documentLinkAt } from "./documentLinks";
@@ -22,13 +24,15 @@
focusLine?: number | null;
onSelectionLine?: (line: number) => void;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
shouldFocusOnMount?: () => boolean;
};
let { buffer, chrome, onChange, onInsertImage, onOpenLink, focusLine = null, onSelectionLine, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props();
let { buffer, chrome, onChange, onInsertImage, onOpenLink, focusLine = null, onSelectionLine, tableActions = {}, linkActions = {}, shouldFocusOnMount = () => true }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor: import("monaco-editor").editor.IStandaloneCodeEditor | undefined;
export function focus() { editor?.focus(); }
let ready = $state(0);
let applying = false;
let loadError = $state<string | null>(null);
@@ -116,7 +120,7 @@
renderWhitespace: "selection",
bracketPairColorization: { enabled: true },
overviewRulerLanes: 0,
contextmenu: !markdown,
contextmenu: false,
...monacoChrome(mode),
});
editor = view;
@@ -167,13 +171,31 @@
});
view.pushUndoStop();
},
select(from, to) {
const start = model.getPositionAt(from), end = model.getPositionAt(to);
view.setSelection(new monaco.Selection(start.lineNumber, start.column, end.lineNumber, end.column));
view.revealPositionInCenterIfOutsideViewport(end);
},
selectAll() { view.setSelection(model.getFullModelRange()); view.focus(); },
focus() { view.focus(); },
}, untrack(() => tableActions), message => { loadError = message; });
listeners.push(view.onContextMenu(event => {
event.event.preventDefault(); event.event.stopPropagation();
menu?.open(event.event.posx, event.event.posy);
}));
undo() { view.trigger("markdown-menu", "undo", null); },
redo() { view.trigger("markdown-menu", "redo", null); },
canUndo() { return model.canUndo(); },
canRedo() { return model.canRedo(); },
}, untrack(() => tableActions), message => { loadError = message; }, () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }));
} else {
menu = codeMenu(view, message => { loadError = message; });
}
const openContextMenu = (event: MouseEvent) => {
event.preventDefault(); event.stopImmediatePropagation();
const position = view.getTargetAtClientPoint(event.clientX, event.clientY)?.position;
const selection = view.getSelection();
if (position && (!selection || selection.isEmpty() || !selection.containsPosition(position))) view.setPosition(position);
view.focus();
menu?.open(event.clientX, event.clientY, undefined, position ? model.getOffsetAt(position) : undefined);
};
el.addEventListener("contextmenu", openContextMenu, true);
listeners.push({ dispose: () => el.removeEventListener("contextmenu", openContextMenu, true) });
listeners.push(view.onKeyDown(event => {
if (event.browserEvent.key !== "ContextMenu" && !(event.shiftKey && event.browserEvent.key === "F10")) return;
event.preventDefault(); event.stopPropagation();
@@ -183,7 +205,6 @@
}));
listeners.push(view.onDidChangeCursorSelection(() => menu?.close(false)));
listeners.push(model.onDidChangeContent(() => menu?.close(false)));
}
const documentId = untrack(() => buffer.id);
releaseCompletion = connectMonacoCompletion(monaco, view, documentId, markdown);
releaseSelection = registerSelection(documentId, () => view.getSelections()?.map(range => model.getValueInRange(range)).join("\n") || "");
@@ -209,6 +230,7 @@
releaseDrop?.();
listeners.forEach(listener => listener.dispose());
view?.dispose();
if (session) releaseEditorSession(session);
editor = undefined;
};
});
+28 -16
View File
@@ -1,7 +1,6 @@
<script lang="ts">
import { pluginHost } from "$lib/plugins/registry";
import { useSpellingMenu } from "./spellingMenu";
import { spellingWord } from "./spellingWord";
import { isSpellingTarget } from "./spellingMenu";
import { untrack } from "svelte";
import { Compartment, EditorState, EditorSelection, Transaction } from "@codemirror/state";
import { EditorView, drawSelection, keymap } from "@codemirror/view";
@@ -15,11 +14,11 @@
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
import { linkCandidates } from "$lib/workspace/markdownLinks";
import { editImageSource, imageSource } from "./imageSource";
import { markdownImages } from "$lib/workspace/noteHtml";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { editorSession } from "./sessions";
import { editorSession, releaseEditorSession } from "./sessions";
import { registerSelection } from "./selection";
import { liveMarkdown, refreshImages } from "./liveMarkdown";
import { imageDrops, trackImageDrop, clearImageDrop } from "./imageDrop";
@@ -27,6 +26,7 @@
import { markdownTitle } from "$lib/workspace/media";
import type { TableContextActions } from "./tableCellActions";
import { markdownMenu } from "./markdownMenu";
import type { DocumentLinkActions } from "./linkMenu";
import { tableNavigation } from "./tableNavigation";
import { completionExtension } from "$lib/completion/codemirror";
import { documentLinkAt } from "./documentLinks";
@@ -42,13 +42,15 @@
focusLine?: number | null;
onSelectionLine?: (line: number) => void;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
shouldFocusOnMount?: () => boolean;
focusTitle?: boolean;
onTitleFocused?: () => void;
};
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, onSelectionLine, tableActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, onSelectionLine, tableActions = {}, linkActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor = $state.raw<EditorView>();
export function focus() { editor?.focus(); }
let error = $state("");
let model: import("monaco-editor").editor.ITextModel | undefined;
let ModelSelection: typeof import("monaco-editor").Selection;
@@ -195,7 +197,7 @@
if (!view.state.field(imageSource)) return false;
view.dispatch({ effects: editImageSource.of(null) }); return true;
} }, indentWithTab, ...searchKeymap, ...historyKeymap, ...defaultKeymap]), EditorView.lineWrapping,
liveMarkdown(urls, untrack(() => tableActions), {
liveMarkdown(urls, { ...untrack(() => tableActions), linkActions: () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }) }, {
open: image => onOpenLink?.(image.dataset.mdKind === "wiki" ? "wiki" : "md", image.dataset.mdSrc || ""),
reveal: async image => {
for (const path of linkCandidates(current.relPath, image.dataset.mdSrc || "", "md")) {
@@ -242,12 +244,11 @@
EditorView.domEventHandlers({
contextmenu(event, view) {
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
if (event.target instanceof HTMLElement && spellingWord(event.target.closest<HTMLElement>('[contenteditable="true"]') ?? event.target, event.clientX, event.clientY) && useSpellingMenu(event, view.state.selection.main.empty)) { menu?.close(false); return false; }
event.preventDefault();
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
const position = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
const selection = view.state.selection.main;
if (position !== null && (selection.empty || position < selection.from || position > selection.to)) view.dispatch({ selection: { anchor: position } });
menu?.open(event.clientX, event.clientY);
menu?.open(event.clientX, event.clientY, selection.empty && isSpellingTarget(event.target) ? position ?? undefined : undefined, position ?? undefined);
return true;
},
keydown(event, view) {
@@ -255,7 +256,7 @@
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
event.preventDefault();
const coords = view.coordsAtPos(view.state.selection.main.head);
if (coords) menu?.open(coords.left, coords.bottom);
if (coords) menu?.open(coords.left, coords.bottom, view.state.selection.main.empty ? view.state.selection.main.head : undefined);
return true;
},
mousedown(event, view) {
@@ -275,7 +276,12 @@
},
}),
];
freshState = source => EditorState.create({ doc: source, extensions });
// Start in the body so the initial caret does not reveal properties source.
// Saved selections and explicit line navigation still restore their positions.
freshState = source => {
const doc = EditorState.create({ doc: source }).doc;
return EditorState.create({ doc, selection: { anchor: documentBodyStart(doc.toString()) }, extensions });
};
const saved = session.writer;
const state = saved?.source === lastValue
? EditorState.fromJSON(saved.state, { extensions })
@@ -314,9 +320,14 @@
return { source: doc.toString(), selection: selection.main, valid: () => editor === view && view.state.doc === doc && view.state.selection.eq(selection) };
},
apply(edit) { view.dispatch({ changes: { from: edit.from, to: edit.to, insert: edit.insert }, selection: { anchor: edit.anchor, head: edit.head }, userEvent: "input.markdown", annotations: isolateHistory.of("full") }); },
select(from, to) { view.dispatch({ selection: { anchor: from, head: to }, scrollIntoView: true }); },
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
focus() { view.focus(); },
}, untrack(() => tableActions), message => { error = message; });
undo() { clearTimeout(historyTimer); model?.pushStackElement(); void model?.undo(); },
redo() { clearTimeout(historyTimer); void model?.redo(); },
canUndo() { return model?.canUndo() ?? false; },
canRedo() { return model?.canRedo() ?? false; },
}, untrack(() => tableActions), message => { error = message; }, () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }));
if (!focusTitle && shouldFocusOnMount()) view.focus();
}).catch(reason => { if (!cancelled) error = String(reason); });
return () => {
@@ -330,6 +341,7 @@
releaseScroll?.();
if (session && editor && scroll) session.writer = { source: modelSource(editor.state), state: editor.state.toJSON(), scroll };
editor?.destroy();
if (session) releaseEditorSession(session);
releaseSelection?.();
editor = undefined;
};
@@ -404,22 +416,22 @@
.live-writer :global(.writer-heading:hover)::before { display: none; }
.live-writer :global(.cm-panels) { background: var(--rs-bg-elevated); color: var(--rs-text); }
.live-writer :global(.cm-cursor) { border-left-color: var(--rs-text-strong); }
.live-writer :global(.cm-selectionBackground), .live-writer :global(.cm-focused .cm-selectionBackground) { background: var(--rs-bg-active); }
.live-writer :global(.cm-editor .cm-selectionLayer .cm-selectionBackground), .live-writer :global(.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground) { background: var(--rs-selection); }
.live-writer :global(.writer-blank) { font-size: .75em; }
.live-writer :global(.writer-strong) { font-weight: 600; color: var(--rs-text-strong); }
.live-writer :global(.writer-emphasis) { font-style: italic; }
.live-writer :global(.writer-strike), .live-writer :global(.writer-completed) { text-decoration: line-through; color: var(--rs-text-dim); }
.live-writer :global(.writer-link) { color: var(--rs-accent); text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-link-source) { color: var(--rs-accent); }
.live-writer :global(.writer-link-target) { text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-inline-code), .live-writer :global(.writer-code-source) { font-family: var(--rs-font-mono); font-size: .9em; }
.live-writer :global(.writer-inline-code) { background: var(--rs-bg-elevated); border-radius: 3px; }
.live-writer :global(.writer-code-line) { padding: 0 20px; border-inline: 1px solid var(--rs-border); background: var(--rs-bg-elevated); font: 13px/1.65 var(--rs-font-mono); tab-size: 4; }
.live-writer :global(.writer-code-line) { padding: 0 20px; border-inline: 1px solid var(--rs-border); background: var(--rs-code-block-bg); font: 13px/1.65 var(--rs-font-mono); tab-size: 4; }
.live-writer :global(.writer-code-first) { padding-top: 10px; border-top: 1px solid var(--rs-border); border-radius: var(--rs-control-radius) var(--rs-control-radius) 0 0; padding-right: 44px; }
.live-writer :global(.writer-code-last) { padding-bottom: 10px; border-bottom: 1px solid var(--rs-border); border-radius: 0 0 var(--rs-control-radius) var(--rs-control-radius); }
.live-writer :global(.writer-code-fence) { color: var(--rs-text-dim); }
.live-writer :global(.writer-code-copy) { top: 4px; border-radius: var(--rs-control-radius); }
.live-writer :global(.writer-code-copy:focus-visible) { outline: 1px solid var(--rs-accent); outline-offset: -2px; }
.live-writer :global(.writer-code-tooltip) { display: none; position: absolute; z-index: 2; top: 100%; right: 0; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: 12px/1.5 var(--rs-font-ui); white-space: nowrap; pointer-events: none; }
.live-writer :global(.writer-code-copy:focus-visible .writer-code-tooltip) { display: block; }
.live-writer :global(.writer-highlight) { background: #e7c56a38; color: var(--rs-text-strong); }
.live-writer :global(.writer-math) { font-family: var(--rs-font-mono); font-style: italic; }
.live-writer :global(.writer-comment) { color: var(--rs-text-dim); background: var(--rs-bg-active); }
+59
View File
@@ -0,0 +1,59 @@
import type { editor } from "monaco-editor";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
/** Keep Monaco editing commands in the host's shared action menu. */
export function codeMenu(view: editor.IStandaloneCodeEditor, report: (message: string) => void) {
let root: HTMLElement | undefined;
function close(focus = true) {
root?.remove(); root = undefined;
if (focus) view.focus();
}
const outside = (event: MouseEvent) => { if (root && !root.contains(event.target as Node)) close(false); };
const scroll = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); };
const resize = () => close(false);
document.addEventListener("mousedown", outside, true);
document.addEventListener("scroll", scroll, true);
window.addEventListener("resize", resize);
function open(x: number, y: number) {
close(false);
const model = view.getModel(), selection = view.getSelection();
if (!model || !selection) return;
const version = model.getVersionId();
const valid = () => view.getModel() === model && !model.isDisposed() && model.getVersionId() === version && !!view.getSelection()?.equalsRange(selection);
const selected = model.getValueInRange(selection);
const replace = (text: string) => {
if (!valid()) return;
view.pushUndoStop();
view.executeEdits("code-menu", [{ range: selection, text }]);
view.pushUndoStop(); view.focus();
};
const clipboard = async (kind: "cut" | "copy" | "paste") => {
close();
try {
if (kind === "paste") replace(await navigator.clipboard.readText());
else { await navigator.clipboard.writeText(selected); if (kind === "cut") replace(""); }
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
};
const run = (id: string) => { close(); void view.getAction(id)?.run(); };
const items: ActionMenuItem[] = [
{ label: "Undo", icon: "undo", shortcut: "Ctrl+Z", disabled: !model.canUndo(), run: () => { close(); view.trigger("code-menu", "undo", null); } },
{ label: "Redo", icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !model.canRedo(), run: () => { close(); view.trigger("code-menu", "redo", null); } },
{ separator: true },
{ label: "Change all occurrences", icon: "select", shortcut: "Ctrl+F2", disabled: !view.getAction("editor.action.changeAll")?.isSupported(), run: () => run("editor.action.changeAll") },
{ separator: true },
{ label: "Cut", icon: "cut", shortcut: "Ctrl+X", disabled: !selected, run: () => void clipboard("cut") },
{ label: "Copy", icon: "copy", shortcut: "Ctrl+C", disabled: !selected, run: () => void clipboard("copy") },
{ label: "Paste", icon: "paste", shortcut: "Ctrl+V", run: () => void clipboard("paste") },
{ label: "Select all", icon: "select", shortcut: "Ctrl+A", run: () => { close(); view.setSelection(model.getFullModelRange()); } },
{ separator: true },
{ label: "Command palette", icon: "terminal", shortcut: "F1", run: () => run("editor.action.quickCommand") },
];
root = actionMenu(x, y, items, close, "Code text actions");
}
return { open, close, destroy() {
close(false);
document.removeEventListener("mousedown", outside, true);
document.removeEventListener("scroll", scroll, true);
window.removeEventListener("resize", resize);
} };
}
+8 -4
View File
@@ -1,6 +1,6 @@
import { markdownLanguage } from "@codemirror/lang-markdown";
export type DocumentLink = { from: number; to: number; kind: "md" | "wiki"; target: string };
export type DocumentLink = { from: number; to: number; targetFrom: number; targetTo: number; kind: "md" | "wiki"; target: string };
/** Source ranges survive the change from formatted text to editable Markdown. */
export function documentLinks(source: string): DocumentLink[] {
@@ -15,13 +15,17 @@ export function documentLinks(source: string): DocumentLink[] {
const url = node.node.getChild("URL");
if (!url) return;
const target = source.slice(url.from, url.to).replace(/^<|>$/g, "").replace(/\\([\\()])/g, "$1");
links.push({ from: node.from, to: node.to, kind: "md", target });
const angled = source[url.from] === "<";
links.push({ from: node.from, to: node.to, targetFrom: url.from + Number(angled), targetTo: url.to - Number(angled), kind: "md", target });
return false;
} });
const occupied = (from: number, to: number) => [...literal, ...links].some(range => from < range.to && to > range.from);
for (const match of source.matchAll(/\[\[([^\]\n]+)\]\]/g)) {
if (occupied(match.index, match.index + match[0].length)) continue;
links.push({ from: match.index, to: match.index + match[0].length, kind: "wiki", target: match[1].split("|")[0].trim() });
if (source[match.index - 1] === "!") continue;
const raw = match[1].split(/\\?\|/)[0], target = raw.trim();
const targetFrom = match.index + 2 + raw.length - raw.trimStart().length;
links.push({ from: match.index, to: match.index + match[0].length, targetFrom, targetTo: targetFrom + target.length, kind: "wiki", target });
}
for (const match of source.matchAll(/(?:https?:\/\/|mailto:)[^\s<>]+/g)) {
if (occupied(match.index, match.index + match[0].length)) continue;
@@ -29,7 +33,7 @@ export function documentLinks(source: string): DocumentLink[] {
const open = (match[0].match(/\(/g) || []).length, close = (match[0].match(/\)/g) || []).length;
return suffix.slice(0, Math.max(0, suffix.length - Math.max(0, close - open)));
});
links.push({ from: match.index, to: match.index + target.length, kind: "md", target });
links.push({ from: match.index, to: match.index + target.length, targetFrom: match.index, targetTo: match.index + target.length, kind: "md", target });
}
return links.sort((a, b) => a.from - b.from);
}
-2
View File
@@ -7,8 +7,6 @@
.rs-heading-toggle:focus-visible { outline: 1px solid var(--rs-accent); outline-offset: 1px; }
.rs-heading-toggle svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.rs-heading-toggle[aria-expanded="true"] svg { transform: rotate(90deg); }
.rs-heading-tooltip { display: none; position: absolute; z-index: 5; top: 100%; inset-inline-start: 0; max-width: 240px; width: max-content; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: 12px/1.5 var(--rs-font-ui); white-space: normal; pointer-events: none; }
.rs-heading-toggle:hover .rs-heading-tooltip, .rs-heading-toggle:focus-visible .rs-heading-tooltip { display: block; }
.rs-heading-collapsed::after { content: " …"; color: var(--rs-text-dim); font-weight: normal; }
.live-writer .cm-foldPlaceholder { border: none; background: transparent; color: var(--rs-text-dim); cursor: pointer; padding: 0 .3em; }
.reading [hidden] { display: none !important; }
+7 -8
View File
@@ -2,6 +2,8 @@ import { StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, keymap } from "@codemirror/view";
import { codeFolding, foldEffect, foldKeymap, foldedRanges, foldService, syntaxTree, unfoldEffect } from "@codemirror/language";
import { actionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip";
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
export type HeadingRange = { start: number; from: number; to: number; level: number; label: string };
@@ -29,12 +31,9 @@ export function headingButton(label: string, collapsed: boolean): HTMLButtonElem
button.setAttribute("aria-expanded", String(!collapsed));
const title = `${collapsed ? "Expand" : "Collapse"} ${label || "heading"}`;
button.setAttribute("aria-label", title);
button.title = title;
tooltipCleanups.set(button, attachTooltip(button, () => button.getAttribute("aria-label") || ""));
const icon = actionIcon("chevron");
const tooltip = document.createElement("span");
tooltip.className = "rs-heading-tooltip";
tooltip.textContent = title;
button.append(icon, tooltip);
button.append(icon);
return button;
}
@@ -55,6 +54,7 @@ class HeadingToggle extends WidgetType {
};
return button;
}
destroy(dom: HTMLElement) { tooltipCleanups.get(dom)?.(); }
ignoreEvent() { return true; }
}
@@ -103,8 +103,7 @@ export function readerHeadingFolding(root: HTMLElement, collapsed: Set<string>)
const label = `${collapsed.has(item.key) ? "Expand" : "Collapse"} ${item.label}`;
button.setAttribute("aria-expanded", String(!collapsed.has(item.key)));
button.setAttribute("aria-label", label);
button.title = label;
button.querySelector(".rs-heading-tooltip")!.textContent = label;
item.heading.classList.toggle("rs-heading-collapsed", collapsed.has(item.key));
}
if (!collapsed.has(item.key)) return;
@@ -137,7 +136,7 @@ export function readerHeadingFolding(root: HTMLElement, collapsed: Set<string>)
},
destroy() {
elements.forEach(element => { element.hidden = false; });
headings.forEach(item => { item.heading.querySelector(".rs-heading-toggle")?.remove(); item.heading.classList.remove("rs-foldable-heading", "rs-heading-collapsed"); });
headings.forEach(item => { const button = item.heading.querySelector<HTMLElement>(".rs-heading-toggle"); if (button) tooltipCleanups.get(button)?.(); button?.remove(); item.heading.classList.remove("rs-foldable-heading", "rs-heading-collapsed"); });
},
};
}
+5 -2
View File
@@ -1,4 +1,6 @@
import { actionIcon, type ActionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip";
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
export type ImageActions = {
@@ -32,7 +34,7 @@ function button(label: string, icon: ActionIcon, action: () => void) {
control.type = "button";
control.className = "image-action";
control.setAttribute("aria-label", label);
control.dataset.tooltip = label;
tooltipCleanups.set(control, attachTooltip(control, () => label));
control.append(actionIcon(icon));
control.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); action(); });
return control;
@@ -73,7 +75,7 @@ function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
dialog.append(header, viewport);
dialog.addEventListener("click", event => { if (event.target === dialog || event.target === viewport) dialog.close(); });
// Escape and focus trapping are provided by the native modal dialog.
dialog.addEventListener("close", () => { dialog.remove(); if (trigger.isConnected) trigger.focus(); }, { once: true });
dialog.addEventListener("close", () => { [zoomOut, zoomIn, fit, close].forEach(button => tooltipCleanups.get(button)?.()); dialog.remove(); if (trigger.isConnected) trigger.focus(); }, { once: true });
image.addEventListener("load", () => resize(scale));
document.body.append(dialog);
dialog.showModal();
@@ -103,6 +105,7 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
toolbar.append(zoom);
if (actions.edit) toolbar.append(button(actions.editing ? "Hide image source" : "Edit image source", "code", actions.editing && actions.done ? actions.done : actions.edit));
frame.append(toolbar);
cleanup.push(() => toolbar.querySelectorAll<HTMLButtonElement>("button").forEach(button => tooltipCleanups.get(button)?.()));
let menu: HTMLElement | undefined;
let openingMenu = false;
function closeMenu(focus = true) { menu?.remove(); menu = undefined; if (focus && frame.isConnected) frame.focus({ preventScroll: true }); }
+1 -1
View File
@@ -64,7 +64,7 @@ export class ImagePreview extends WidgetType {
const edit = document.createElement("button");
edit.type = "button"; edit.className = "image-action";
const label = this.editing ? "Hide image source" : "Edit image source";
edit.setAttribute("aria-label", label); edit.dataset.tooltip = label;
edit.setAttribute("aria-label", label); edit.dataset.editorTooltip = label;
edit.append(actionIcon("code"));
edit.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); (this.editing ? actions.done : actions.edit)?.(); });
dom.append(edit);
+30
View File
@@ -0,0 +1,30 @@
import type { ActionMenuItem } from "../ui/actionMenu";
export type MenuLink = { kind: "md" | "wiki"; target: string };
export type DocumentLinkActions = {
open?: (link: MenuLink) => void | Promise<void>;
browser?: (target: string) => void | Promise<void>;
defaultBrowser?: (target: string) => void | Promise<void>;
workspaceItems?: (link: MenuLink) => ActionMenuItem[];
};
export function linkMenuItems(link: MenuLink, actions: DocumentLinkActions, close: () => void, report: (message: string) => void, edit?: () => void): ActionMenuItem[] {
const run = (action: () => void | Promise<void>) => () => {
close();
void Promise.resolve().then(action).catch(error => report(error instanceof Error ? error.message : String(error)));
};
const external = /^(https?:\/\/|mailto:)/i.test(link.target);
const items: ActionMenuItem[] = external ? [
...(actions.browser && /^https?:\/\//i.test(link.target) ? [{ label: "Open link in app browser", icon: "globe" as const, run: run(() => actions.browser!(link.target)) }] : []),
...(actions.defaultBrowser ? [{ label: "Open link in default browser", icon: "external" as const, run: run(() => actions.defaultBrowser!(link.target)) }] : []),
] : [];
if (!items.length && actions.open) items.push({ label: external ? "Open link" : "Open in new tab", icon: external ? "external" : "file-plus", run: run(() => actions.open!(link)) });
if (!external && actions.workspaceItems) {
const wrap = (item: ActionMenuItem): ActionMenuItem => "separator" in item ? item : { ...item, run: item.run ? run(item.run) : undefined, children: item.children?.map(wrap) };
const workspaceItems = actions.workspaceItems(link).filter(item => !edit || "separator" in item || !["Rename…", "Move file to…", "Open in default app"].includes(item.label));
items.push(...workspaceItems.map(wrap));
}
items.push({ label: external ? "Copy URL" : "Copy link target", icon: "link", run: run(() => navigator.clipboard.writeText(link.target)) });
if (edit) items.push({ label: "Edit link", icon: "rename", run: () => { close(); edit(); } });
return items;
}
+29 -14
View File
@@ -1,5 +1,5 @@
import { StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
import { renderMarkdownSections } from "../workspace/noteHtml";
import { renderDiagrams } from "../workspace/diagrams";
@@ -10,6 +10,8 @@ import { imageControls } from "./imageControls";
import { ImagePreview, type ImageContext } from "./imagePreview";
import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
import { actionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip";
import { documentLinks } from "./documentLinks";
import { pluginHost } from "../plugins/registry.ts";
@@ -17,6 +19,20 @@ const previewFormulas = new WeakMap<HTMLElement, unknown>();
export const refreshImages = StateEffect.define<void>();
const imageCleanups = new WeakMap<HTMLElement, () => void>();
const linkTooltips = ViewPlugin.define(view => {
const attached = new Map<HTMLElement, () => void>();
const refresh = () => {
for (const [node, dispose] of attached) if (!view.dom.contains(node)) { dispose(); attached.delete(node); }
for (const node of view.dom.querySelectorAll<HTMLElement>("[data-editor-tooltip]")) {
if (!attached.has(node)) attached.set(node, attachTooltip(node, () => node.dataset.editorTooltip || ""));
}
};
const observer = new MutationObserver(refresh);
observer.observe(view.dom, { childList: true, subtree: true });
refresh();
return { destroy() { observer.disconnect(); attached.forEach(dispose => dispose()); } };
});
class CodeCopy extends WidgetType {
constructor(readonly code: string) { super(); }
eq(other: CodeCopy) { return this.code === other.code; }
@@ -25,24 +41,18 @@ class CodeCopy extends WidgetType {
button.type = "button";
button.className = "rs-fence-copy writer-code-copy";
button.setAttribute("aria-label", "Copy code");
button.title = "Copy code";
const help = document.createElement("span");
help.className = "writer-code-tooltip";
help.setAttribute("role", "tooltip");
help.textContent = "Copy code";
button.append(actionIcon("copy"), help);
button.dataset.editorTooltip = "Copy code";
button.append(actionIcon("copy"));
button.onmousedown = event => event.preventDefault();
button.onclick = async event => {
event.preventDefault(); event.stopPropagation();
try {
await navigator.clipboard.writeText(this.code);
button.dataset.copied = "true";
button.title = "Copied";
help.textContent = "Copied";
button.dataset.editorTooltip = "Copied";
button.setAttribute("aria-label", "Code copied");
} catch {
button.title = "Could not copy code";
help.textContent = "Could not copy code";
button.dataset.editorTooltip = "Could not copy code";
button.setAttribute("aria-label", "Could not copy code");
}
};
@@ -238,7 +248,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
if (!match) return;
replace(node.from, node.from + 1);
replace(node.from + 1 + match[1].length, node.to);
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", title: "Ctrl+click to open link" } }).range(node.from + 1, node.from + 1 + match[1].length));
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", "data-editor-tooltip": "Ctrl+click to open link" } }).range(node.from + 1, node.from + 1 + match[1].length));
return false;
}
if (node.name === "TaskMarker") {
@@ -261,11 +271,16 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
const labelStart = from + 2 + (separator < 0 ? 0 : separator + 1);
replace(from, labelStart);
replace(to - 2, to);
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-kind": "wiki", "data-href": match[1].split("|")[0] } }).range(labelStart, to - 2));
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-kind": "wiki", "data-href": match[1].split("|")[0], "data-editor-tooltip": "Ctrl+click to open link" } }).range(labelStart, to - 2));
}
for (const link of documentLinks(source)) {
if (!selected(link.from, link.to) || hidden(link.from, link.to)) continue;
mark(link.from, link.to, "writer-link-source");
mark(link.targetFrom, link.targetTo, "writer-link-target");
}
return Decoration.set(ranges, true);
}
return [imageSource, StateField.define<DecorationSet>({
return [imageSource, linkTooltips, StateField.define<DecorationSet>({
create: build,
update(value, transaction) {
return transaction.docChanged || transaction.selection
+39 -2
View File
@@ -1,6 +1,10 @@
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { invoke, isTauri } from "@tauri-apps/api/core";
import { wordAt } from "./spellingWord";
import { pickLinkDocument } from "./documentPicker";
import { externalLinkText, workspaceLinkText } from "./linkCommands";
import { documentLinkAt } from "./documentLinks";
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
import { htmlToMarkdown } from "../workspace/htmlToMarkdown";
import { cellFormats, type TableContextActions } from "./tableCellActions";
import { formatText, insertBlock, paragraphText, replacement, type MarkdownEdit, type TextSelection, type ParagraphStyle, type InsertBlock } from "./markdownCommands";
@@ -10,11 +14,16 @@ export type MarkdownMenuEditor = {
apply: (edit: MarkdownEdit) => void;
selectAll: () => void;
focus: () => void;
select: (from: number, to: number) => void;
undo?: () => void;
redo?: () => void;
canUndo?: () => boolean;
canRedo?: () => boolean;
};
// A shared controller keeps menus, async selection guards, and clipboard behavior
// identical in the writing editor and the source editor.
export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextActions, report: (message: string) => void) {
export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextActions, report: (message: string) => void, linkActions: () => DocumentLinkActions = () => ({})) {
let root: HTMLElement | undefined, destroyed = false;
const pending = new AbortController();
function close(focus = true) {
@@ -28,10 +37,11 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
document.addEventListener("scroll", scroll, true);
window.addEventListener("resize", resize);
function open(x: number, y: number) {
function open(x: number, y: number, spellingOffset?: number, linkOffset?: number) {
close(false);
const snapshot = editor.snapshot(), { source, selection } = snapshot;
const text = source.slice(selection.from, selection.to);
const selectedLink = documentLinkAt(source, linkOffset ?? selection.from);
const valid = () => !destroyed && snapshot.valid();
function apply(edit: MarkdownEdit) {
if (!valid()) return;
@@ -74,6 +84,15 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
const paragraph = (label: string, style: ParagraphStyle, icon: "bullet" | "number" | "task" | "heading" | "paragraph" | "quote"): ActionMenuItem => ({ label, icon, run: () => apply(paragraphText(source, selection, style)) });
const insert = (label: string, kind: InsertBlock, icon: "footnote" | "table" | "quote" | "rule" | "code" | "math"): ActionMenuItem => ({ label, icon, run: () => apply(insertBlock(source, selection, kind)) });
const items: ActionMenuItem[] = [
...(selectedLink ? [...linkMenuItems(selectedLink, linkActions(), () => close(false), report, () => {
if (!valid()) return;
editor.select(selectedLink.targetFrom, selectedLink.targetTo); editor.focus();
}), { separator: true as const }] : []),
...(editor.undo ? [
{ label: "Undo", icon: "undo" as const, shortcut: "Ctrl+Z", disabled: !editor.canUndo?.(), run: () => { close(); editor.undo?.(); } },
{ label: "Redo", icon: "redo" as const, shortcut: "Ctrl+Shift+Z", disabled: !editor.canRedo?.(), run: () => { close(); editor.redo?.(); } },
{ separator: true as const },
] : []),
{ label: "Add link", icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) },
{ separator: true },
@@ -104,6 +123,24 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
{ label: "Select all", icon: "select", run: () => { close(); editor.selectAll(); } },
];
root = actionMenu(x, y, items, close, "Markdown text actions");
const opened = root;
const word = spellingOffset === undefined ? null : wordAt(source, spellingOffset);
if (word && isTauri()) {
const languages = [...new Set([document.documentElement.lang, ...navigator.languages].filter(Boolean))];
void invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages }).then(result => {
if (!result.misspelled || root !== opened || !valid()) return;
const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => apply(replacement(word, value)) }));
if (!suggestions.length) suggestions.push({ label: "No spelling suggestions", disabled: true });
suggestions.push({ label: "Add to dictionary", icon: "book", run: () => {
close();
void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(() => report("Could not add the word to the dictionary."));
} });
const focusedLabel = opened.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined;
opened.remove();
root = actionMenu(x, y, [...suggestions, { separator: true }, ...items], close, "Markdown text actions");
if (focusedLabel) [...root.querySelectorAll<HTMLButtonElement>(":scope > button")].find(button => button.querySelector(".action-label")?.textContent === focusedLabel)?.focus();
}).catch(() => { /* Editing actions remain available without spelling suggestions. */ });
}
}
return { open, close, destroy() {
destroyed = true; pending.abort(); close(false);
+27 -12
View File
@@ -12,28 +12,43 @@ export let currentTheme = 'runestone-default-dark';
function updateTheme() {
const style = getComputedStyle(document.documentElement);
const color = (name: string) => style.getPropertyValue(`--rs-${name}`).trim();
const sakura = document.documentElement.dataset.palette === 'sakura';
const syntaxColor = (role: string) => {
const value = document.documentElement.style.getPropertyValue(`--rs-syntax-${role}`).trim();
const match = /^#([0-9a-f]{3,8})$/i.exec(value);
if (!match) return undefined;
const hex = match[1];
return hex.length === 3 || hex.length === 4 ? `#${hex.slice(0, 3).split('').map(part => part + part).join('')}`
: hex.length === 6 || hex.length === 8 ? `#${hex.slice(0, 6)}` : undefined;
};
const syntaxRules = [
['keyword', 'keyword'], ['variable.parameter', 'parameter'], ['variable', 'local'],
['variable.predefined', 'global'], ['variable.property', 'instance'], ['variable.static', 'static'],
['identifier', 'local'], ['string', 'string'], ['number', 'number'], ['comment', 'comment'],
['type', 'type'], ['type.identifier', 'type'], ['entity.name.type', 'type'],
['function', 'function'], ['predefined', 'function'], ['delimiter', 'global'],
].flatMap(([token, role]) => {
const foreground = syntaxColor(role);
return foreground ? [{ token, foreground: foreground.slice(1) }] : [];
});
// Monaco permits only letters, digits, and hyphens in registered theme names.
const palette = (document.documentElement.dataset.palette || 'default').replace(/[^a-z0-9-]/gi, '-');
currentTheme = `runestone-${palette}-${document.documentElement.dataset.theme || 'dark'}`;
monaco.editor.defineTheme(currentTheme, {
base: document.documentElement.dataset.theme === 'light' ? 'vs' : 'vs-dark',
inherit: true,
rules: sakura ? [
{ token: 'keyword', foreground: color('syntax-keyword').replace('#', '') },
{ token: 'variable.parameter', foreground: color('syntax-parameter').replace('#', '') },
{ token: 'variable', foreground: color('syntax-local').replace('#', '') },
{ token: 'variable.predefined', foreground: color('syntax-global').replace('#', '') },
{ token: 'variable.property', foreground: color('syntax-instance').replace('#', '') },
{ token: 'variable.static', foreground: color('syntax-static').replace('#', '') },
] : [],
rules: syntaxRules,
colors: {
'editor.background': color('bg'), 'editor.foreground': color('text'),
...Object.fromEntries(['keyword', 'number', 'type', 'string', 'function', 'parameter'].flatMap((role, index) => {
const foreground = syntaxColor(role);
return foreground ? [[`editorBracketHighlight.foreground${index + 1}`, foreground]] : [];
})),
'editor.background': '#00000000', 'editor.foreground': color('text'),
'editor.lineHighlightBackground': color('bg-active'), 'editor.selectionBackground': color('selection'),
'editor.inactiveSelectionBackground': color('selection'), 'editor.selectionForeground': color('selection-text'),
'editorCursor.foreground': color('accent'), 'editorLineNumber.foreground': color('text-dim'),
'editorLineNumber.activeForeground': color('text'), 'editorGutter.background': color('bg'),
'editorLineNumber.activeForeground': color('text'), 'editorGutter.background': '#00000000',
'editorWidget.background': color('bg-elevated'), 'editorWidget.border': color('border'),
'minimap.background': color('bg-elevated'), 'editorIndentGuide.background1': color('border'),
'minimap.background': '#00000000', 'editorIndentGuide.background1': color('border'),
'editorIndentGuide.activeBackground1': color('text-dim'),
},
});
+1 -5
View File
@@ -21,11 +21,7 @@ class NoteTitle extends WidgetType {
button.className = "note-title-button";
button.setAttribute("aria-label", "Rename note");
button.append(document.createTextNode(this.title), actionIcon("rename"));
const help = document.createElement("span");
help.className = "note-title-help";
help.textContent = "Rename note";
help.setAttribute("role", "tooltip");
button.append(help);
button.dataset.editorTooltip = "Rename note";
heading.replaceChildren(button);
const input = document.createElement("input");
+58
View File
@@ -0,0 +1,58 @@
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
/** Preserve the DOM range while the shared menu owns keyboard focus. */
export function readingMenu(host: HTMLElement, actions: DocumentLinkActions, search: ((text: string) => void) | undefined, report: (message: string) => void) {
let root: HTMLElement | undefined;
let previousFocus: HTMLElement | null = null;
let range: Range | undefined;
function close(restore = true) {
if (!root) return;
root.remove(); root = undefined;
if (restore) {
(previousFocus?.isConnected ? previousFocus : host).focus({ preventScroll: true });
if (range?.startContainer.isConnected && range.endContainer.isConnected) {
const selection = window.getSelection(); selection?.removeAllRanges(); selection?.addRange(range);
}
}
}
function open(event: MouseEvent | KeyboardEvent) {
if (event.defaultPrevented || event.target instanceof Element && event.target.closest("input, textarea, [contenteditable=true], .rs-image-frame")) return;
const keyboard = event instanceof KeyboardEvent;
if (keyboard && event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
const selection = window.getSelection();
const selected = selection?.rangeCount ? selection.getRangeAt(0) : undefined;
range = selected && host.contains(selected.startContainer) && host.contains(selected.endContainer) ? selected.cloneRange() : undefined;
const text = range?.toString() ?? "";
const target = event.target instanceof Element ? event.target : null;
const anchor = target?.closest("a") ?? (keyboard && selection?.anchorNode ? (selection.anchorNode.parentElement?.closest("a") ?? null) : null);
if (!text && !anchor) return;
event.preventDefault(); event.stopPropagation(); close(false);
previousFocus = document.activeElement instanceof HTMLElement && host.contains(document.activeElement) ? document.activeElement : host;
const items: ActionMenuItem[] = [];
if (text) items.push(
{ label: "Copy", icon: "copy", shortcut: "Ctrl+C", run: () => { close(); void navigator.clipboard.writeText(text).catch(() => report("Clipboard unavailable. Use Ctrl+C to copy.")); } },
{ label: `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”`, icon: "search", disabled: !search, run: () => { close(false); search?.(text); } },
);
if (anchor) {
if (items.length) items.push({ separator: true });
if (anchor.hasAttribute("data-footnote-link")) items.push({ label: "Open link", icon: "link", run: () => { close(false); (anchor as HTMLElement).click(); } });
else items.push(...linkMenuItems({ kind: anchor.getAttribute("data-kind") === "wiki" ? "wiki" : "md", target: anchor.getAttribute("href") ?? "" }, actions, () => close(false), report));
}
const rect = keyboard ? (range?.getBoundingClientRect() ?? anchor?.getBoundingClientRect() ?? host.getBoundingClientRect()) : null;
root = actionMenu(rect?.left ?? (event as MouseEvent).clientX, rect?.bottom ?? (event as MouseEvent).clientY, items, close, "Reading actions");
}
const outside = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); };
const resize = () => close(false);
host.addEventListener("contextmenu", open);
host.addEventListener("keydown", open);
document.addEventListener("mousedown", outside, true);
document.addEventListener("scroll", outside, true);
window.addEventListener("resize", resize);
return () => {
close(false);
host.removeEventListener("contextmenu", open); host.removeEventListener("keydown", open);
document.removeEventListener("mousedown", outside, true); document.removeEventListener("scroll", outside, true);
window.removeEventListener("resize", resize);
};
}
+4 -5
View File
@@ -1,10 +1,9 @@
// Readers retain editor selection when toolbar buttons take focus.
let current: { id: string; read: () => string } | undefined;
const readers = new Map<string, () => string>();
export function registerSelection(id: string, read: () => string): () => void {
const owner = { id, read };
current = owner;
return () => { if (current === owner) current = undefined; };
readers.set(id, read);
return () => { if (readers.get(id) === read) readers.delete(id); };
}
export function selectedEditorText(id?: string): string {
return current && current.id === id ? current.read() : "";
return id ? readers.get(id)?.() ?? "" : "";
}
+14 -2
View File
@@ -3,17 +3,20 @@ import type { OpenBuffer } from "../workspace/types";
import { languageFor } from "./languageFor";
type Session = {
users: number;
model: Monaco.editor.ITextModel;
view: Monaco.editor.ICodeEditorViewState | null;
writerSelections: Map<number, import("@codemirror/state").EditorSelection>;
writer?: { source: string; state: ReturnType<import("@codemirror/state").EditorState["toJSON"]>; scroll: ReturnType<import("@codemirror/view").EditorView["scrollSnapshot"]> };
};
const sessions = new Map<string, Session>();
let retained = new Set<string>();
export function editorSession(monaco: typeof Monaco, buffer: OpenBuffer): Session {
let session = sessions.get(buffer.id);
if (!session) {
session = {
users: 0,
model: monaco.editor.createModel(buffer.contents, languageFor(buffer.relPath), monaco.Uri.parse(`inmemory://runestone/${buffer.id}/${buffer.name}`)),
view: null,
writerSelections: new Map(),
@@ -21,12 +24,21 @@ export function editorSession(monaco: typeof Monaco, buffer: OpenBuffer): Sessio
sessions.set(buffer.id, session);
}
monaco.editor.setModelLanguage(session.model, languageFor(buffer.relPath));
session.users++;
return session;
}
export function retainEditorSessions(ids: string[]) {
const retained = new Set(ids);
retained = new Set(ids);
for (const [id, session] of sessions) {
if (!retained.has(id)) { session.model.dispose(); sessions.delete(id); }
if (!retained.has(id) && session.users === 0) { session.model.dispose(); sessions.delete(id); }
}
}
export function releaseEditorSession(session: Session) {
session.users = Math.max(0, session.users - 1);
if (session.users) return;
for (const [id, entry] of sessions) {
if (entry === session && !retained.has(id)) { session.model.dispose(); sessions.delete(id); break; }
}
}
+28 -4
View File
@@ -1,9 +1,12 @@
import type { Editor, JSONContent } from "@tiptap/core";
import { getMarkRange, type Editor, type JSONContent } from "@tiptap/core";
import { requestText } from "../workspace/dialogs.svelte";
import { extractedCellMarkdown } from "./tableCellMarkdown";
import type { ActionMenuItem } from "../ui/actionMenu";
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
import { documentLinkAt } from "./documentLinks";
export type TableContextActions = {
linkActions?: () => DocumentLinkActions;
onSearch?: (text: string) => void;
onExtract?: (markdown: string, label: string, valid: () => boolean) => Promise<string | null>;
};
@@ -13,8 +16,9 @@ export const cellFormats = [
["Code", "code"], ["Math", "math"], ["Comment", "comment"], ["Clear formatting", "clear"],
] as const;
export function tableTextItems(editor: Editor, actions: TableContextActions, close: () => void, transaction: (run: () => void) => void, pending: (value: boolean) => void, report: (message: string) => void): ActionMenuItem[] {
export function tableTextItems(editor: Editor, actions: TableContextActions, close: () => void, transaction: (run: () => void) => void, pending: (value: boolean) => void, report: (message: string) => void, editSource: (range: { from: number; to: number }) => void): ActionMenuItem[] {
const selection = editor.state.selection, doc = editor.state.doc;
const sourceEditing = editor.view.dom.parentElement?.classList.contains("is-source-editing");
const text = doc.textBetween(selection.from, selection.to, "\n");
const valid = () => !editor.isDestroyed && editor.state.doc === doc && editor.state.selection.eq(selection);
function run(command: () => void) { if (!valid()) return; close(); transaction(() => { editor.view.focus(); command(); }); }
@@ -41,6 +45,21 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
});
});
}
const at = doc.resolve(selection.from);
const mark = [...at.marks(), ...(at.nodeAfter?.marks || [])].find(mark => mark.type.name === "link");
const linkRange = mark && getMarkRange(doc.resolve(selection.from), mark.type, mark.attrs);
const sourceLink = sourceEditing ? documentLinkAt(doc.textContent, selection.from - 1)
|| documentLinkAt(doc.textContent, selection.from - 2) : undefined;
const selectedLink = sourceLink || (mark && linkRange ? { kind: mark.attrs["data-kind"] === "wiki" ? "wiki" as const : "md" as const, target: String(mark.attrs.href) } : undefined);
function editLink() {
if (!selectedLink) return;
if (!valid()) return;
close();
if (sourceLink) {
editor.commands.setTextSelection({ from: sourceLink.targetFrom + 1, to: sourceLink.targetTo + 1 });
editor.view.focus();
} else if (linkRange) editSource(linkRange);
}
async function clipboard(action: "cut" | "copy" | "paste" | "plain") {
await request(async () => {
try {
@@ -49,7 +68,7 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
if (action === "cut") run(() => { editor.commands.deleteSelection(); });
} else {
let html = "", value = "";
if (action === "paste" && navigator.clipboard.read) {
if (!sourceEditing && action === "paste" && navigator.clipboard.read) {
try {
const data = await navigator.clipboard.read();
const rich = data.find(item => item.types.includes("text/html"));
@@ -72,7 +91,8 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
});
}
return [
const items: ActionMenuItem[] = [
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
{ label: "Add link", icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) },
{ separator: true },
@@ -95,4 +115,8 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
{ label: "Paste as plain text", icon: "paste-text", run: () => void clipboard("plain") },
{ label: "Select all", icon: "select", run: () => { close(); editor.commands.selectAll(); editor.view.focus(); } },
];
return sourceEditing ? [
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
...items.slice(items.findIndex(item => "label" in item && item.label === "Cut")),
] : items;
}
+93 -10
View File
@@ -1,4 +1,6 @@
import { Editor, Mark } from "@tiptap/core";
import { Editor, Extension, Mark, getMarkRange } from "@tiptap/core";
import { Plugin } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
import Highlight from "@tiptap/extension-highlight";
import StarterKit from "@tiptap/starter-kit";
import Link from "@tiptap/extension-link";
@@ -13,6 +15,10 @@ import { tableDragControls } from "./tableDragControls";
import type { TableContextActions } from "./tableCellActions";
import { actionIcon } from "../ui/actionIcons";
import { pluginHost } from "../plugins/registry.ts";
import { attachTooltip } from "../ui/tooltip";
import { documentLinks } from "./documentLinks";
import { tableLinkLabelPosition } from "./tableLinkSource";
import { renderMarkdownHtml } from "../workspace/noteHtml";
const cellFormats = ["math", "comment"].map(name => Mark.create({
name,
@@ -46,10 +52,13 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
wrapper.append(scroll);
let editor: Editor | undefined;
let active: HTMLTableCellElement | undefined;
let sourceEditing = false;
let sourceImages = new Map<string, string>();
let firstEdit = true;
let selectionControls: ReturnType<typeof tableSelectionControls> | undefined;
let dragControls: ReturnType<typeof tableDragControls> | undefined;
const controller = { source: initialSource, enter, destroy: () => { dragControls?.destroy(); selectionControls?.destroy(); editor?.destroy(); editor = undefined; } };
const tooltipCleanup: (() => void)[] = [];
const controller = { source: initialSource, enter, destroy: () => { tooltipCleanup.forEach(dispose => dispose()); dragControls?.destroy(); selectionControls?.destroy(); editor?.destroy(); editor = undefined; } };
tableEditors.set(root, controller);
function enter(forward: boolean, x?: number) {
@@ -83,7 +92,8 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
for (const row of table!.rows) for (const cell of row.cells) {
const result = results[row.rowIndex]?.[cell.cellIndex];
const address = formulas.cellAddress(row.rowIndex, cell.cellIndex);
cell.title = `${address} · ${result?.formula || "Click to edit · Type = for a formula"}`;
cell.dataset.cellHint = `${address}${result?.formula ? ` · ${result.formula}` : ""}`;
cell.removeAttribute("title");
if (result && cell !== active) cell.innerHTML = formulas.tableFormulaHtml(result);
if (cell === active) {
formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : " · Type = to calculate"}`;
@@ -115,10 +125,16 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
function finish() {
if (!editor || !active) return;
const cell = active;
const html = editor.getHTML();
let html = editor.getHTML();
if (sourceEditing) {
const rendered = document.createElement("div");
rendered.innerHTML = renderMarkdownHtml(controller.source, sourceImages);
html = rendered.querySelector("table")?.rows[(cell.parentElement as HTMLTableRowElement).rowIndex]?.cells[cell.cellIndex]?.innerHTML ?? html;
}
sourceEditing = false;
editor.destroy(); editor = undefined; active = undefined;
cell.innerHTML = html;
cell.classList.remove("is-editing");
cell.classList.remove("is-editing", "is-source-editing");
refreshFormulas();
formulaStatus.textContent = "Type = in a cell to calculate";
formulaHint.hidden = true;
@@ -165,6 +181,22 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
editor = new Editor({
element: cell,
extensions: [
Extension.create({
name: "cellLinkSource",
addProseMirrorPlugins: () => [new Plugin({ props: { decorations(state) {
if (!sourceEditing) return null;
const decorations: Decoration[] = [];
state.doc.descendants((node, position) => {
if (!node.isTextblock) return;
for (const link of documentLinks(node.textBetween(0, node.content.size, "\n", "\n"))) {
decorations.push(Decoration.inline(position + link.from + 1, position + link.to + 1, { class: "writer-link-source", "data-href": link.target, "data-kind": link.kind }));
if (link.targetTo > link.targetFrom) decorations.push(Decoration.inline(position + link.targetFrom + 1, position + link.targetTo + 1, { class: "writer-link-target" }));
}
return false;
});
return DecorationSet.create(state.doc, decorations);
} } })],
}),
StarterKit.configure({ blockquote: false, bulletList: false, orderedList: false, listItem: false, listKeymap: false, codeBlock: false, heading: false, horizontalRule: false, link: false, underline: false, undoRedo: false, trailingNode: false, gapcursor: false, dropcursor: false }),
CellLink.configure({ openOnClick: false, autolink: false }),
CellImage.configure({ inline: true, allowBase64: true }),
@@ -177,6 +209,9 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
attributes: { class: "writer-cell-editor", role: "textbox", "aria-label": cell.getAttribute("aria-label")!, "aria-multiline": "true", spellcheck: "true" },
handleKeyDown(_editorView, event) {
if (event.isComposing) return false;
if (sourceEditing && (event.ctrlKey || event.metaKey) && ["b", "i"].includes(event.key.toLowerCase())) {
event.preventDefault(); event.stopPropagation(); return true;
}
if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
// The nested editor owns cursor movement, including word movement
// and selections. Never let an arrow reach the prose editor.
@@ -237,10 +272,11 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
});
return true;
}
if (event.key === "Escape" && sourceEditing) { event.preventDefault(); finish(); wrapper.focus(); return true; }
if (event.key === "Escape") { event.preventDefault(); leave(true); return true; }
if (event.key === "Enter") {
event.preventDefault();
if (/^=(?!=)/.test((editor?.getText() || "").trim())) { finish(); wrapper.focus(); }
if (sourceEditing || /^=(?!=)/.test((editor?.getText() || "").trim())) { finish(); wrapper.focus(); }
else if (event.ctrlKey || event.metaKey) leave(true);
else editor?.commands.setHardBreak();
return true;
@@ -258,7 +294,13 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
},
},
onUpdate({ editor: current }) {
const text = tableCellMarkdown(current.getJSON());
const text = sourceEditing
? current.getText({ blockSeparator: "<br>" }).replace(/\r?\n/g, "<br>").replace(/\|/g, (_pipe, offset, value) => {
let slashes = 0;
for (let before = offset - 1; before >= 0 && value[before] === "\\"; before--) slashes++;
return slashes % 2 ? "|" : "\\|";
})
: tableCellMarkdown(current.getJSON());
const source = controller.source;
// Track the full edited range, including typed spaces. Re-parsing the
// trimmed cell on each key would gradually turn those spaces into padding.
@@ -269,6 +311,18 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
if (contentFrom !== undefined) contentTo = contentFrom + text.length;
change(insert);
},
onSelectionUpdate({ editor: current }) {
// Read the final mouse/keyboard selection after activation sets its
// temporary caret. Menus and range selections keep their own focus.
requestAnimationFrame(() => {
if (current !== editor || current.isDestroyed || sourceEditing || !current.isFocused || current.view.composing) return;
const { selection } = current.state;
if (!selection.empty) return;
const mark = selection.$from.marks().find(mark => mark.type.name === "link");
const range = mark && getMarkRange(selection.$from, mark.type, mark.attrs);
if (range) editSource(range, selection.from - range.from);
});
},
onBlur() {
// A toolbar click, another cell, or the prose editor can now take focus.
queueMicrotask(() => { if (active === cell && !cell.contains(document.activeElement) && !selectionControls?.keepEditing()) finish(); });
@@ -279,6 +333,32 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
view.requestMeasure();
}
function editSource(range: { from: number; to: number }, labelOffset?: number) {
if (!editor || !active) return;
const row = (active.parentElement as HTMLTableRowElement).rowIndex;
const cell = parseMarkdownTable(controller.source)?.rows[row === 0 ? 0 : row + 1]?.cells[active.cellIndex];
if (!cell) return;
const preceding = new Set<number>();
editor.state.doc.descendants((node, position) => {
const mark = node.marks.find(mark => mark.type.name === "link");
if (mark && position < range.from) {
const found = getMarkRange(editor!.state.doc.resolve(position), mark.type, mark.attrs);
if (found && found.from < range.from) preceding.add(found.from);
}
});
const link = documentLinks(cell.text)[preceding.size];
if (!link) return;
sourceImages = new Map([...root.querySelectorAll<HTMLImageElement>("img[data-md-src]")].map(image => [image.dataset.mdSrc!, image.src]));
sourceEditing = true;
active.classList.add("is-source-editing");
editor.commands.setContent({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: cell.text }] }] }, { emitUpdate: false });
editor.commands.setTextSelection(labelOffset === undefined
? { from: link.targetFrom + 1, to: link.targetTo + 1 }
: tableLinkLabelPosition(cell.text, link, labelOffset) + 1);
editor.view.focus();
view.requestMeasure();
}
function add(kind: "row" | "column", focusNew = false) {
const from = view.posAtDOM(root);
finish();
@@ -299,7 +379,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
const help = document.createElement("div");
help.className = "table-edit-help";
help.textContent = "Drag grips: move rows/columns · Drag cells: select · Right-click: actions · Arrows: move through cells · Tab: next cell · Esc: exit table";
help.hidden = true;
const footer = document.createElement("div");
footer.className = "table-footer";
const tools = formulas?.createFormulaTools(finish, () => view.requestMeasure());
@@ -313,7 +393,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
const label = kind === "column" ? "Add column to the right" : "Add row below";
button.type = "button";
button.className = `table-add table-add-${kind}`;
button.title = label;
tooltipCleanup.push(attachTooltip(button, () => label));
button.setAttribute("aria-label", label);
const plus = document.createElement("span");
plus.append(actionIcon("plus"));
@@ -332,7 +412,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
cell.setAttribute("aria-label", `${formulas ? formulas.cellAddress(row.rowIndex, cell.cellIndex) + " · " : ""}Row ${row.rowIndex + 1}, column ${cell.cellIndex + 1}`);
cell.addEventListener("focus", () => activate(cell));
}
selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate }, actions);
selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate, editSource }, actions);
dragControls = tableDragControls(root, wrapper, table, scroll, view, () => controller.source, selectionControls.select, change);
table.addEventListener("mousedown", event => {
if (event.button !== 0) return;
@@ -347,4 +427,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
}
});
refreshFormulas();
for (const row of table.rows) for (const cell of row.cells) {
tooltipCleanup.push(attachTooltip(cell, () => cell.dataset.cellHint || cell.getAttribute("aria-label") || ""));
}
}
+4 -3
View File
@@ -2,12 +2,14 @@ import type { EditorView } from "@codemirror/view";
import { actionIcon } from "../ui/actionIcons";
import { moveTableAxis, type TableAxis } from "./tableStructure";
import type { CellRange } from "./tableSelection";
import { attachTooltip } from "../ui/tooltip";
const controls = new WeakMap<HTMLTableElement, (axis: TableAxis, index: number, keyboard: boolean) => void>();
export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, scroll: HTMLElement, view: EditorView, source: () => string, select: (range: CellRange) => void, change: (text: string, structural: boolean) => void) {
const lifecycle = new AbortController(), options = { signal: lifecycle.signal };
const handles: { axis: TableAxis; index: number; button: HTMLButtonElement }[] = [];
const tooltipCleanup: (() => void)[] = [];
const layer = document.createElement("div");
layer.className = "table-drag-layer";
wrapper.append(layer);
@@ -172,8 +174,7 @@ export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table
const label = `Move ${axis} ${index + 1}`;
const tooltip = `${label} · Drag to reorder · ${axis === "row" ? "↑/↓" : "←/→"} to move`;
button.setAttribute("aria-label", label);
button.title = tooltip;
button.dataset.tooltip = tooltip;
tooltipCleanup.push(attachTooltip(button, () => drag ? "" : tooltip));
button.append(actionIcon("grip"));
layer.append(button);
handles.push({ axis, index, button });
@@ -222,5 +223,5 @@ export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table
const observer = new ResizeObserver(scheduleLayout);
observer.observe(table); observer.observe(scroll);
scheduleLayout();
return { destroy() { cancel(); cancelAnimationFrame(layoutFrame); lifecycle.abort(); observer.disconnect(); controls.delete(table); } };
return { destroy() { cancel(); tooltipCleanup.forEach(dispose => dispose()); cancelAnimationFrame(layoutFrame); lifecycle.abort(); observer.disconnect(); controls.delete(table); } };
}
+45
View File
@@ -0,0 +1,45 @@
import { markdownLanguage } from "@codemirror/lang-markdown";
import type { DocumentLink } from "./documentLinks";
/** Keep the caret on the clicked label character when Markdown becomes visible. */
export function tableLinkLabelPosition(source: string, link: DocumentLink, offset: number): number {
let from = link.targetFrom, to = link.targetTo;
if (link.kind === "wiki") {
const separator = source.indexOf("|", link.from + 2);
from = link.from + 2; to = link.to - 2;
if (separator >= 0 && separator < to) {
if (separator + 1 < to) from = separator + 1;
else to = separator - Number(source[separator - 1] === "\\");
}
} else if (source[link.from] === "[") {
from = link.from + 1;
markdownLanguage.parser.parse(source).iterate({ enter(node) {
if (node.name === "LinkMark" && node.from > from && node.from < link.targetFrom && source[node.from] === "]") to = node.from;
} });
}
const label = source.slice(from, to);
const hidden = new Set<number>();
const entities = new Map<number, { to: number; length: number }>();
if (link.kind === "wiki") {
// Wiki labels are literal text. Table parsing removes escaped pipe marks.
for (let i = 0; i < label.length - 1; i++) if (label[i] === "\\" && label[i + 1] === "|") hidden.add(i);
} else markdownLanguage.parser.parse(label).iterate({ enter(node) {
if (["EmphasisMark", "StrikethroughMark", "CodeMark"].includes(node.name)) {
for (let i = node.from; i < node.to; i++) hidden.add(i);
} else if (node.name === "Escape") hidden.add(node.from);
else if (node.name === "Entity") {
const text = document.createElement("textarea");
text.innerHTML = label.slice(node.from, node.to);
entities.set(node.from, { to: node.to, length: text.value.length });
}
} });
let visible = 0;
for (let i = 0; i < label.length; i++) {
if (hidden.has(i)) continue;
if (visible >= offset) return from + i;
const entity = entities.get(i);
if (entity) { visible += entity.length; i = entity.to - 1; }
else visible++;
}
return to;
}
+4 -4
View File
@@ -10,7 +10,7 @@ import { alignTableCells, bounds, copyTableCells, deleteTableCells, formatTableC
const selections = new WeakMap<Element, (range: CellRange) => void>();
export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, view: EditorView, source: () => string, finish: () => void, change: (text: string, structural: boolean) => void, rich: { get: () => Editor | undefined; activate: (cell: HTMLTableCellElement) => void }, actions: TableContextActions) {
export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, view: EditorView, source: () => string, finish: () => void, change: (text: string, structural: boolean) => void, rich: { get: () => Editor | undefined; activate: (cell: HTMLTableCellElement) => void; editSource: (range: { from: number; to: number }) => void }, actions: TableContextActions) {
const lifecycle = new AbortController(), options = { signal: lifecycle.signal };
let range: CellRange | undefined, down: CellPoint | undefined, dragging = false;
let menu: HTMLElement | undefined;
@@ -80,7 +80,7 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
}
} catch {
const status = root.querySelector<HTMLElement>(".table-edit-help");
if (status) { status.setAttribute("role", "status"); status.textContent = `Clipboard unavailable here. Use ${navigator.platform.includes("Mac") ? "⌘" : "Ctrl"}+${action === "paste" ? "V" : action === "cut" ? "X" : "C"}.`; }
if (status) { status.hidden = false; status.setAttribute("role", "status"); status.textContent = `Clipboard unavailable here. Use ${navigator.platform.includes("Mac") ? "⌘" : "Ctrl"}+${action === "paste" ? "V" : action === "cut" ? "X" : "C"}.`; }
}
}
function showMenu(x: number, y: number, at = range?.head, textEditor?: Editor) {
@@ -109,11 +109,11 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
].map(item => ({ ...item, title: "Alignment applies to the selected Markdown columns" } as ActionMenuItem));
const report = (message: string) => {
const status = root.querySelector<HTMLElement>(".table-edit-help");
if (status) { status.setAttribute("role", "status"); status.textContent = message; status.style.visibility = "visible"; }
if (status) { status.hidden = false; status.setAttribute("role", "status"); status.textContent = message; status.style.visibility = "visible"; }
};
const items: ActionMenuItem[] = textEditor ? tableTextItems(textEditor, actions, closeMenu, run => {
view.dispatch({ annotations: isolateHistory.of("before") }); run(); view.dispatch({ annotations: isolateHistory.of("after") });
}, value => { pending = value; }, report) : [
}, value => { pending = value; }, report, rich.editSource) : [
...(["cut", "copy", "paste"] as const).map(action => ({ label: action[0].toUpperCase() + action.slice(1), icon: action, run: () => void clipboard(action) })),
sep,
{ label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, run: () => format(kind) })) },
+36 -26
View File
@@ -3,8 +3,8 @@
import type { GitLineInfo } from "$lib/git/contracts";
import EditorHost from "$lib/editor/EditorHost.svelte";
import LiveWriter from "$lib/editor/LiveWriter.svelte";
import { onDestroy, tick } from "svelte";
import { retainEditorSessions } from "$lib/editor/sessions";
import { tick } from "svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import ImageViewer from "./ImageViewer.svelte";
import MarkdownView from "./MarkdownView.svelte";
import ModeSwitcher from "$lib/ui/ModeSwitcher.svelte";
@@ -13,6 +13,8 @@
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import type { TableContextActions } from "$lib/editor/tableCellActions";
import type { DocumentLinkActions } from "$lib/editor/linkMenu";
type Props = {
buffer: OpenBuffer | null;
tabs: OpenBuffer[];
@@ -33,9 +35,12 @@
browserOpening?: boolean;
hasWorkspace: boolean;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
active?: boolean;
onCloseSplit?: () => void;
};
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onNewNote, onQuickOpen, onOpenBrowser, browserOpening = false, hasWorkspace, tableActions }: Props = $props();
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 selectedLine = $state(1);
let lineInfo = $state<GitLineInfo | null>(null);
const git = $derived.by(() => { void $pluginHost; return pluginHost.get("git"); });
@@ -60,7 +65,15 @@
let previewMode = $state<"split" | "preview">("split");
let modeControls = $state<HTMLDivElement>();
let titleFocusId = $state<string | null>(null);
const shouldFocusOnMount = () => !modeControls?.contains(document.activeElement);
let element: HTMLDivElement | undefined = $state();
let writerEditor: LiveWriter | undefined = $state();
let sourceEditor: EditorHost | undefined = $state();
const shouldFocusOnMount = () => active && !modeControls?.contains(document.activeElement);
export function focusEditor() {
if (reading) element?.querySelector<HTMLElement>(".reading")?.focus({ preventScroll: true });
else if (writerEditor) writerEditor.focus();
else sourceEditor?.focus();
}
export function focusTitle(id: string) {
titleFocusId = id;
}
@@ -70,10 +83,8 @@
const previewScroll = new Map<string, { top: number; left: number }>();
$effect(() => {
const ids = tabs.map(tab => tab.id);
retainEditorSessions(ids);
for (const id of previewScroll.keys()) if (!ids.includes(id)) previewScroll.delete(id);
});
onDestroy(() => retainEditorSessions([]));
function rememberPreviewScroll(node: HTMLDivElement, id: string) {
const saved = previewScroll.get(id);
@@ -117,21 +128,23 @@
{#if !buffer || buffer.kind === "empty"}
<div class="empty">
<h1>{buffer?.kind === "empty" ? "New tab" : "One project. Notes, code, terminal."}</h1>
<p>{hasWorkspace ? "Open a file to get started, or create a note or script." : "Open a folder to work with your own files."}</p>
{#if onCloseSplit}<IconButton icon="close" label="Close split" onclick={onCloseSplit} />{/if}
<div class="welcome-actions">
{#if onOpenBrowser}<button onclick={onOpenBrowser} disabled={browserOpening}><Icon icon="globe" /> {browserOpening ? "Opening browser…" : "Open browser"}</button>{/if}
<button onclick={onOpenWorkspace}><Icon icon="folder-open" /> Open folder <kbd>Ctrl O</kbd></button>
{#if hasWorkspace}
<div class="welcome-row">
<button onclick={onNewFile}><Icon icon="file-plus" /> New file <kbd>Ctrl N</kbd></button>
{#if onNewNote}<button onclick={onNewNote}><Icon icon="pen" /> New note</button>{/if}
<button onclick={onQuickOpen}><Icon icon="search" /> Find a file <kbd>Ctrl P</kbd></button>
<button onclick={onQuickOpen}><Icon icon="search" /> Find file <kbd>Ctrl P</kbd></button>
</div>
{/if}
<div class="welcome-row">
<button onclick={onOpenWorkspace}><Icon icon="folder-open" /> Open folder <kbd>Ctrl O</kbd></button>
{#if onOpenBrowser}<button onclick={onOpenBrowser} disabled={browserOpening}><Icon icon="globe" /> {browserOpening ? "Opening browser…" : "Open browser"}</button>{/if}
</div>
</div>
<p class="hint">Save · Ctrl S &nbsp; Terminal · Ctrl ` &nbsp; Find in file · Ctrl F</p>
</div>
{:else}
<div class="editor">
<div class="editor" class:pane-active={active} bind:this={element}>
<div class="chrome-bar">
<span class="breadcrumb" title={buffer.relPath}>{buffer.relPath}</span>
{#if lineInfo}
@@ -140,6 +153,7 @@
</span>
{/if}
<div class="actions" bind:this={modeControls}>
{#if onCloseSplit}<IconButton icon="close" label="Close split" onclick={onCloseSplit} />{/if}
{#if canPreview}
<ModeSwitcher
label="Document view"
@@ -171,17 +185,17 @@
<div class="editor-wrap" class:hidden={reading && canPreview && previewMode === "preview"}>
{#key buffer.id}
{#if !isIde && canPreview && !reading}
<LiveWriter {buffer} {onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line) => selectedLine = line}
<LiveWriter bind:this={writerEditor} {buffer} {onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {linkActions} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line) => selectedLine = line}
focusTitle={titleFocusId === buffer.id} onTitleFocused={() => { titleFocusId = null; }} />
{:else}
<EditorHost {buffer} {chrome} {onChange} {onInsertImage} {onOpenLink} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line) => selectedLine = line} />
<EditorHost bind:this={sourceEditor} {buffer} {chrome} {onChange} {onInsertImage} {onOpenLink} {linkActions} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line) => selectedLine = line} />
{/if}
{/key}
</div>
{#if reading && canPreview}
{#key buffer.id}
<div class="md-page" use:rememberPreviewScroll={buffer.id}>
<MarkdownView noteRel={buffer.relPath} contents={buffer.contents} {onOpenLink} />
<MarkdownView noteRel={buffer.relPath} contents={buffer.contents} {onOpenLink} {linkActions} onSearch={tableActions?.onSearch} />
</div>
{/key}
{/if}
@@ -195,11 +209,12 @@
.line-history span { overflow: hidden; text-overflow: ellipsis; }
.line-history :global(svg) { width: 14px; height: 14px; flex-shrink: 0; }
.breadcrumb { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-right: auto; }
.welcome-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 12px; }
.welcome-actions button { display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); padding: 10px 14px; }
.welcome-actions { display: flex; flex-direction: column; gap: 12px; max-width: 100%; }
.welcome-row { display: flex; flex-wrap: wrap; justify-content: center; gap: 12px; max-width: 100%; }
.welcome-actions button { flex-wrap: wrap; justify-content: center; max-width: 100%; }
.welcome-actions button { display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-image-control-bg); padding: 10px 14px; }
.welcome-actions button:hover { background: var(--rs-image-control-hover-bg); }
kbd { margin-left: 12px; color: var(--rs-text-dim); font-size: 11px; }
h1 { color: var(--rs-text-strong); font-size: 24px; font-weight: 500; }
.hint { margin-top: 32px; font-size: 12px; }
.hidden { display: none; }
.split .md-page { border-left: 1px solid var(--rs-border); }
.editor { container-type: inline-size; }
@@ -214,11 +229,6 @@
}
.empty {
background-color: var(--rs-new-tab-bg, var(--rs-bg));
background-image: var(--rs-background-image, var(--rs-new-tab-image, none));
background-size: 100% 100%, var(--rs-background-size, cover);
background-position: center, var(--rs-background-position, center);
background-repeat: no-repeat;
overflow: auto;
box-sizing: border-box;
align-items: center;
@@ -227,7 +237,6 @@
padding: 24px;
text-align: center;
}
.empty h1,.empty>p{background:color-mix(in srgb,var(--rs-bg) 92%,transparent);padding:8px 14px;border-radius:var(--rs-control-radius)}
.chrome-bar {
display: flex;
@@ -251,6 +260,7 @@
}
.body {
background: var(--rs-workarea-editor-bg);
flex: 1;
display: flex;
min-height: 0;
+34 -6
View File
@@ -469,11 +469,16 @@
}
async function createIn(parent: string, kind: "folder" | "note" | "file") {
const operationRoot = workspaceRoot;
let name: string;
if (kind === "note") {
name = "untitled.md";
if (kind === "note" || kind === "folder") {
name = kind === "folder" ? "untitled" : "untitled.md";
if (kind === "folder") {
await load(parent);
if (workspaceRoot !== operationRoot || error) return;
}
} else {
const typed = await requestText(kind === "folder" ? "Folder name" : "File name, including any extension", kind === "folder" ? "folder" : "Untitled");
const typed = await requestText("File name, including any extension", "Untitled");
if (!typed) {
return;
}
@@ -484,21 +489,26 @@
}
name = typed.trim();
}
const finalName = kind === "file" ? name : uniqueName(namesIn(parent), name);
if (workspaceRoot !== operationRoot) return;
const finalName = kind === "file" ? name : uniqueName(kind === "folder" ? namesIn(parent).map(value => value.toLowerCase()) : namesIn(parent), name);
const rel = joinRel(parent, finalName);
try {
await workspaceCreate(rel, kind === "folder" ? "folder" : "file");
if (workspaceRoot !== operationRoot) return;
const order = { ...marks.order };
order[parent] = [...(order[parent] ?? []), finalName];
await persistMarks({ ...marks, order });
if (!childrenMap[parent] && parent !== "") {
if (kind === "folder" || (!childrenMap[parent] && parent !== "")) {
const next = new Set(expanded);
next.add(parent);
expanded = next;
}
await load(parent);
if (workspaceRoot !== operationRoot) return;
onStatus?.(`Created ${rel}`);
if (kind !== "folder") {
if (kind === "folder") {
startRename({ name: finalName, rel_path: rel, kind: "folder" });
} else {
onCreated?.({ name: finalName, rel_path: rel, kind: "file" });
}
} catch (err) {
@@ -575,6 +585,24 @@
await focusTreePath(paths.values().next().value);
}
export async function revealPath(path: string) {
const operationRoot = workspaceRoot;
const folders = path.split("/").slice(0, -1);
await load("");
let parent = "";
for (const folder of folders) {
if (workspaceRoot !== operationRoot) return;
parent = parent ? `${parent}/${folder}` : folder;
expanded = new Set([...expanded, parent]);
await load(parent);
}
if (workspaceRoot !== operationRoot) return;
selectOnly(path);
await focusTreePath(path);
const target = [...treeElement.querySelectorAll<HTMLElement>("[data-tree-rel]")].find(node => node.dataset.treeRel === path);
target?.scrollIntoView({ block: "nearest" });
}
async function focusTreePath(path?: string) {
await tick();
const target = [...treeElement.querySelectorAll<HTMLElement>("[data-tree-rel]")].find(node => node.dataset.treeRel === path);
+14 -1
View File
@@ -9,23 +9,34 @@
import { readerHeadingFolding } from "$lib/editor/headingFolding";
import "$lib/editor/headingFolding.css";
import { readingMenu } from "$lib/editor/readingMenu";
import type { DocumentLinkActions } from "$lib/editor/linkMenu";
type Props = {
noteRel: string;
contents: string;
linkActions?: DocumentLinkActions;
onSearch?: (text: string) => void;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onEditBlock?: (start: number, end: number) => void;
editing?: { start: number; end: number } | null;
blockEditor?: Snippet;
};
let { noteRel, contents, onOpenLink, onEditBlock, editing = null, blockEditor }: Props = $props();
let { noteRel, contents, onOpenLink, linkActions = {}, onSearch, onEditBlock, editing = null, blockEditor }: Props = $props();
let html = $state("");
let menuError = $state("");
let sections = $state<MarkdownSection[]>([]);
let root: HTMLDivElement | undefined = $state();
const collapsedHeadings = new Set<string>();
let foldingNote = "";
let headingControls: ReturnType<typeof readerHeadingFolding> | undefined;
$effect(() => {
if (!root) return;
return readingMenu(root, { ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }, onSearch, message => { menuError = message; });
});
async function loadUrls(noteRel: string, contents: string): Promise<Map<string, string>> {
const urls = new Map<string, string>();
await Promise.all(markdownImages(contents).map(async source => {
@@ -117,6 +128,7 @@
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
<div
class="reading"
tabindex="-1"
bind:this={root}
onkeydown={(event) => {
if (event.target instanceof HTMLElement && event.target.classList.contains("md-edit-block") && (event.key === "Enter" || event.key === " ")) {
@@ -165,6 +177,7 @@
}
}}
>
{#if menuError}<p role="alert">{menuError}</p>{/if}
<h1 class="document-title">{markdownTitle(noteRel)}</h1>
{#if onEditBlock}
{#each sections.filter(section => !editing || section.start < editing.start) as section (section.start)}
+10 -9
View File
@@ -10,9 +10,11 @@
let error = $state("");
let dialog: HTMLDialogElement;
let input: HTMLInputElement;
let picked = false;
const matches = $derived(files.filter(file => query.toLowerCase().split(/\s+/).every(part => file.rel_path.toLowerCase().includes(part))).slice(0, 80));
function pick(entry?: TreeEntry) { if (entry) { onOpen(entry); onClose(); } }
function pick(entry?: TreeEntry) { if (entry) { picked = true; onOpen(entry); onClose(); } }
onMount(() => {
const origin = document.activeElement instanceof HTMLElement ? document.activeElement : null;
dialog.showModal(); input.focus();
let cancelled = false;
void (async () => {
@@ -27,11 +29,11 @@
} catch (err) { if (!cancelled) error = String(err); }
finally { if (!cancelled) loading = false; }
})();
return () => { cancelled = true; };
return () => { cancelled = true; if (!picked && origin?.isConnected) origin.focus({ preventScroll: true }); };
});
</script>
<dialog bind:this={dialog} aria-label={purpose} onpointerdown={(event) => {
<dialog class="rs-picker" bind:this={dialog} aria-label={purpose} onpointerdown={(event) => {
const bounds = dialog.getBoundingClientRect();
if (event.target === dialog && (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom)) onClose();
}} oncancel={onClose}>
@@ -44,7 +46,7 @@
}} />
<div class="results">
{#each matches as entry, index (entry.rel_path)}
<button data-index={index} class:selected={selected === index} onclick={() => pick(entry)}><strong>{entry.name}</strong><span>{entry.rel_path}</span></button>
<button class="rs-picker-row" data-index={index} aria-current={selected === index ? 'true' : undefined} onclick={() => pick(entry)}><span class="file-detail"><strong>{entry.name}</strong><span class="rs-picker-hint">{entry.rel_path}</span></span></button>
{/each}
{#if !matches.length}<p>{loading ? "Finding files…" : "No matching files."}</p>{/if}
</div>
@@ -52,12 +54,11 @@
</dialog>
<style>
dialog { margin-top: 12vh; padding: 0; width: min(640px, 85vw); background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); }
dialog { margin-top: 12vh; width: min(640px, 85vw); }
dialog::backdrop { background: #0008; }
input { width: 100%; padding: 16px; border: 0; background: var(--rs-bg); color: var(--rs-text-strong); }
.results { max-height: 50vh; overflow: auto; padding: 6px; }
button { width: 100%; display: flex; flex-direction: column; align-items: flex-start; gap: 3px; padding: 8px 10px; border: 0; background: transparent; text-align: left; }
button.selected, button:hover { background: var(--rs-bg-active); }
button span, footer { color: var(--rs-text-dim); font-size: 12px; }
.results { max-height: 50vh; overflow: auto; }
.file-detail { min-width: 0; overflow-wrap: anywhere; }
footer { color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); }
footer { padding: 10px 14px; display: flex; justify-content: space-between; border-top: 1px solid var(--rs-border); }
</style>
+1 -1
View File
@@ -24,7 +24,7 @@
const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = [
{ id: "about", label: "Help and about", icon: "help", keywords: "help about version shortcuts keyboard guide" },
{ id: "general", label: "General", icon: "settings", keywords: "auto-save autosave save interval seconds files" },
{ id: "appearance", label: "Appearance", icon: "sun", keywords: "theme colors light dark GPT Claude Terminal Sakura" },
{ id: "appearance", label: "Appearance", icon: "sun", keywords: "theme colors light dark Claude Sakura Harvest Moon Crimson Pilot Silver Serpent" },
{ id: "plugins", label: "Plug-ins", icon: "puzzle", keywords: "plugins extensions community" },
];
let section = $state<Section>(untrack(() => help ? "about" : "general"));
+225 -43
View File
@@ -6,7 +6,12 @@
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, findPluginEditor } from "$lib/plugins/external";
import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
import { pluginSidebar, closePluginSidebar, pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginFileOpen, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
import { onMount, tick, untrack } from "svelte";
import { onMount, onDestroy, tick, untrack } from "svelte";
import type { MenuLink } from "$lib/editor/linkMenu";
import { loadMarks, saveMarks } from "$lib/workspace/marks";
import { moveMarks } from "$lib/workspace/treeMoveHistory";
import { retainEditorSessions } from "$lib/editor/sessions";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane } from "$lib/workspace/documentPanes";
import { selectedEditorText } from "$lib/editor/selection";
import { pluginHost } from "$lib/plugins/registry";
import type { Contributions } from "$lib/plugins/contracts";
@@ -41,6 +46,8 @@
import {
onWorkspaceEvent,
workspaceNew,
workspaceList,
workspaceOpenDefault,
workspaceCreate,
workspaceAbsPath,
workspaceLastPath,
@@ -93,7 +100,8 @@
let rightOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.rightOpen);
$effect(() => { if ($pluginSidebar && !transferredWindow) leftOpen = true; });
let terminalOpen = $state(false);
let reading = $state(false);
let documentPanes = $state(initialDocumentPanes());
const reading = $derived(documentPanes.panes.find(pane => pane.id === documentPanes.active)?.reading ?? false);
let quickOpen = $state(false);
let templateManager = $state(false);
let terminalStarted = $state(false);
@@ -136,11 +144,14 @@
let switching = false;
let workbenchReady = $state(false);
let documents: Documents | null = null;
let editorPane: EditorPane | undefined = $state();
let paneComponents = $state<Record<string, EditorPane | undefined>>({});
function activeEditor() { return paneComponents[documentPanes.active]; }
let fileTree: FileTree | undefined = $state();
let closingTabs = false;
const hasDirty = $derived(tabs.some(tab => tab.contents !== tab.saved));
function createDocuments() {
documentPanes = initialDocumentPanes();
const next = new Documents({
read: workspaceRead, write: workspaceWrite, image: workspaceReadDataUrl,
kind: path => isImagePath(path) ? "image" : "text", chrome: detectChrome,
@@ -149,10 +160,50 @@
tabs = next.buffers.map(tab => ({ ...tab }));
activePath = next.activePath;
const selected = next.active;
documentPanes = syncDocumentPanes(documentPanes, next.buffers.map(tab => tab.id), selected?.id ?? null);
if (selected) view = selected.chromeOverride ?? selected.chrome;
});
return next;
}
$effect(() => retainEditorSessions(tabs.map(tab => tab.id)));
onDestroy(() => retainEditorSessions([]));
const documentViews = $derived.by(() => {
const bounds = paneBounds(documentPanes.layout);
return documentPanes.panes.map(pane => ({ ...pane, buffer: tabs.find(tab => tab.id === pane.documentId) ?? null, bounds: bounds[pane.id] }))
.sort((a, b) => a.bounds.left - b.bounds.left);
});
function setReading(next: boolean, paneId = documentPanes.active) {
documentPanes = readDocumentPane(documentPanes, paneId, next);
}
function focusDocumentPane(paneId: string, focusEditor = false) {
const pane = documentPanes.panes.find(pane => pane.id === paneId);
if (!pane) return;
const tab = tabs.find(tab => tab.id === pane.documentId);
documentPanes = selectPane(documentPanes, paneId);
pluginEditorActive.set(false);
if (tab && documents?.active?.id !== tab.id) { focusLine = null; documents?.select(tab.relPath); }
if (focusEditor) void tick().then(() => {
if (documentPanes.active !== paneId) return;
paneComponents[paneId]?.focusEditor();
document.querySelector<HTMLElement>(`[data-document-pane="${paneId}"]`)?.scrollIntoView({ block: "nearest", inline: "nearest" });
});
}
function closeSplit(paneId: string) {
documentPanes = closeDocumentPane(documentPanes, paneId);
focusDocumentPane(documentPanes.active, true);
}
async function openToRight(file: TreeEntry, sourcePane: string) {
const current = documents;
const source = documentPanes.panes.find(pane => pane.id === sourcePane);
if (!current || switching || !source) return;
await current.open(file, "background");
if (documents !== current || switching || documentPanes.active !== sourcePane
|| documentPanes.panes.find(pane => pane.id === sourcePane)?.documentId !== source.documentId) return;
const target = current.buffers.find(tab => tab.relPath === file.rel_path);
if (!target) return;
documentPanes = splitDocumentPane(documentPanes, sourcePane, target.id, crypto.randomUUID());
focusDocumentPane(documentPanes.active, true);
}
let focusLine = $state<number | null>(null);
let dragging = $state<"left" | "right" | "bottom" | null>(null);
let centerStack: HTMLElement | undefined = $state();
@@ -212,7 +263,7 @@
function toggleChrome() {
const next = view === "Writing" ? "Ide" : "Writing";
reading = false;
setReading(false);
applyChrome(next);
documents?.setChrome(next);
}
@@ -306,7 +357,7 @@
await new Promise(resolve => setTimeout(resolve, 100));
}
} else throw new Error("Invalid tab transfer.");
reading = transfer.reading === true;
setReading(transfer.reading === true);
localStorage.setItem(key + ".accepted", "true");
localStorage.removeItem(key);
}
@@ -322,6 +373,7 @@
pluginEditorActive.set(false);
focusLine = null;
documents?.select(relPath);
focusDocumentPane(documentPanes.active, true);
status = documents?.active?.kind === "empty" ? "New tab" : relPath;
}
@@ -353,7 +405,7 @@
if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return actions;
return tab ? [{ label: "Open in new window", icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : [];
}
async function detachTab(item: WorkbenchTab) {
async function detachTab(item: WorkbenchTab, keepSource = false) {
const tab = workingTabs.find(tab => tab.id === item.id);
if (!tab || !workspace || !desktop) return;
if ("plugin" in tab) {
@@ -373,9 +425,9 @@
};
const accepted = (event: StorageEvent) => {
if (event.key !== key + ".accepted" || event.newValue !== "true") return;
if ("buffer" in tab) {
if (!keepSource && "buffer" in tab) {
if (documents === current && bufferSnapshot(current?.buffers.find(buffer => buffer.id === tab.buffer.id)) === snapshot) current?.close(tab.relPath);
} else if (JSON.stringify(pluginTabState(tab.plugin)) === snapshot) closePluginEditor(tab.plugin.key);
} else if (!keepSource && "plugin" in tab && JSON.stringify(pluginTabState(tab.plugin)) === snapshot) closePluginEditor(tab.plugin.key);
finish();
};
try {
@@ -449,7 +501,7 @@
if (tab.kind === "text" && isMarkdownPath(tab.relPath)) {
items.push(
{ label: "Save as template", icon: "copy", run: () => { void saveTemplate({ name: tab.name, rel_path: tab.relPath, kind: "file" }); } },
{ label: reading ? "Editing view" : "Reading view", icon: "book", run: () => editorPane?.toggleReadingView() },
{ label: reading ? "Editing view" : "Reading view", icon: "book", run: () => activeEditor()?.toggleReadingView() },
{ label: isIde ? "Writing mode" : "Source mode", icon: "code", run: toggleChrome },
);
}
@@ -482,7 +534,7 @@
error = null;
focusLine = null;
if (line) {
reading = false;
setReading(false);
queueMicrotask(() => { focusLine = line; });
}
} catch (err) { if (documents === current) error = String(err); }
@@ -492,8 +544,8 @@
const current = documents;
await openFile(entry);
if (documents !== current || current?.active?.relPath !== entry.rel_path || !isMarkdownPath(entry.rel_path)) return;
reading = false;
editorPane?.focusTitle(current.active.id);
setReading(false);
activeEditor()?.focusTitle(current.active.id);
}
function readFileDataUrl(file: File): Promise<string> {
@@ -505,11 +557,11 @@
});
}
async function insertImage(file: File): Promise<string | null> {
if (!buffer || buffer.kind !== "text" || !isMarkdownPath(buffer.relPath)) {
async function insertImage(file: File, note = buffer): Promise<string | null> {
if (!note || note.kind !== "text" || !isMarkdownPath(note.relPath)) {
return null;
}
const noteRel = buffer.relPath;
const noteRel = note.relPath;
const current = documents;
try {
const rel = attachmentRel(file.name);
@@ -538,8 +590,8 @@
searchRequest = { text, id: (searchRequest?.id || 0) + 1 };
}
async function extractSelection(markdown: string, label: string, valid: () => boolean): Promise<string | null> {
const current = documents, note = buffer;
async function extractSelection(markdown: string, label: string, valid: () => boolean, note = buffer): Promise<string | null> {
const current = documents;
if (!workspace || !current || !note) return null;
const folder = note.relPath.slice(0, note.relPath.lastIndexOf("/") + 1);
const suggested = label.replace(/[<>:"/\\|?*\r\n]/g, " ").trim().slice(0, 60) || "Extracted selection";
@@ -587,8 +639,7 @@
} finally { saving = false; }
}
async function saveCopy() {
const tab = buffer;
async function saveCopy(tab = buffer) {
if (!tab || tab.kind !== "text") return;
const name = await requestText("Save a copy as (workspace relative path)", tab.relPath.replace(/(\.[^./]+)?$/, " copy$1"));
if (!name) return;
@@ -789,7 +840,72 @@
}
}
async function openLink(kind: "md" | "wiki", target: string) {
function workspaceLinkItems(link: MenuLink, origin = activePath ?? "", sourcePane = documentPanes.active): ActionMenuItem[] {
const current = documents, currentWorkspace = workspace;
const valid = () => documents === current && workspace === currentWorkspace && !!currentWorkspace;
const entry = async () => {
for (const path of linkCandidates(origin, link.target, link.kind)) {
if (!valid()) throw new Error("The workspace changed. Open the link menu again.");
const parent = path.split("/").slice(0, -1).join("/");
let files: TreeEntry[];
try { files = await workspaceList(parent); } catch { continue; }
const found = files.find(file => file.rel_path === path && file.kind === "file");
if (found) return found;
}
throw new Error(`Could not find ${link.target} in the workspace.`);
};
const run = (action: (file: TreeEntry) => void | Promise<void>) => () => {
void entry().then(file => { if (valid()) return action(file); }).catch(reason => { error = String(reason); });
};
async function rename(file: TreeEntry, move = false) {
const typed = await requestText(move ? "Move file to (workspace path, including filename)" : "New file name", move ? file.rel_path : file.name);
if (!typed || !valid()) return;
let to = typed.trim().replaceAll("\\", "/");
if (move) {
if (!to || to.startsWith("/") || to.split("/").some(part => !part || part === "." || part === "..") || /[<>:"|?*\u0000-\u001f]/.test(to)) throw new Error("Enter a relative workspace path without reserved characters.");
} else {
const plan = planRename(file.rel_path, to);
if (plan.action === "noop") return;
if (plan.action === "error") throw new Error(plan.message);
to = plan.to;
}
if (to === file.rel_path) return;
const marks = await loadMarks();
if (!valid()) return;
await workspaceRename(file.rel_path, to, currentWorkspace!.root);
if (!valid()) return;
applyPathRename(file.rel_path, to);
await saveMarks(moveMarks(marks, file.rel_path, to));
refreshToken++;
status = `Moved to ${to}`;
}
return [
{ label: "Open to the right", icon: "split-right", run: run(file => openToRight(file, sourcePane)) },
{ label: "Open in new window", icon: "external", disabled: !desktop, run: run(async file => {
await openFile(file, undefined, "new");
if (!valid()) return;
const tab = workingTabs.find(tab => tab.relPath === file.rel_path);
if (tab) await detachTab(tab, true);
}) },
{ label: "Copy path", icon: "copy", children: [
{ label: "Workspace path", icon: "copy", run: run(file => copyTabPath(file.rel_path, false)) },
{ label: "System path", icon: "copy", run: run(file => copyTabPath(file.rel_path, true)) },
] },
{ label: "Rename…", icon: "rename", run: run(file => rename(file)) },
{ label: "Move file to…", icon: "folder", run: run(file => rename(file, true)) },
{ label: "Bookmark", icon: "bookmark", run: run(async file => {
const marks = await loadMarks();
if (!valid()) return;
if (!marks.bookmarks.includes(file.rel_path)) await saveMarks({ ...marks, bookmarks: [...marks.bookmarks, file.rel_path] });
refreshToken++; status = `Bookmarked ${file.name}`;
}) },
{ label: "Open in default app", icon: "external", run: run(file => workspaceOpenDefault(file.rel_path)) },
{ label: "Show in system explorer", icon: "folder", run: run(file => workspaceReveal(file.rel_path)) },
{ label: "Reveal file in navigation", icon: "folder", run: run(async file => { closePluginSidebar(); leftView = "files"; leftOpen = true; await tick(); await fileTree?.revealPath(file.rel_path); }) },
];
}
async function openLink(kind: "md" | "wiki", target: string, origin = activePath ?? "", paneId = documentPanes.active) {
if (/^(https?:\/\/|mailto:)/i.test(target)) {
try {
if (/^https?:\/\//i.test(target) && await pluginHost.get("browser")?.open(target)) return;
@@ -797,7 +913,8 @@
} catch (err) { error = String(err); }
return;
}
const rels = linkCandidates(activePath ?? "", target, kind);
const rels = linkCandidates(origin, target, kind);
focusDocumentPane(paneId);
for (const rel of rels) {
try {
await documents?.open({ name: rel.split("/").pop() ?? rel, rel_path: rel, kind: "file" });
@@ -952,6 +1069,7 @@
onpointerup={() => (dragging = null)}
onpointerleave={() => (dragging = null)}
>
<div class="workarea-background" aria-hidden="true"></div>
<header class="header" data-tauri-drag-region>
<div class="header-left" data-tauri-drag-region>
{#if !transferredWindow}
@@ -1034,6 +1152,7 @@
<div class="left-stack">
<div class="left-layer" class:shown={leftView === "files"}>
<FileTree
bind:this={fileTree}
workspaceRoot={workspace.root}
showInternal={settings.showInternalFolder}
onSaveTemplate={(entry) => { void saveTemplate(entry); }}
@@ -1103,20 +1222,30 @@
{/each}
</div>
<div class="editor-host" class:plugin-covered={editorPluginVisible}>
{#if buffer?.diskError}
<div class="conflict" role="alert"><span>{buffer.diskError}</span><button onclick={() => void saveCopy()}>Save a copy</button><button onclick={() => void documents?.refresh()}>Retry</button></div>
{:else if buffer?.diskContents != null}
<div class="document-panes" class:split={documentViews.length > 1}>
{#each documentViews as pane (pane.id)}
<!-- svelte-ignore a11y_no_static_element_interactions (Focus identifies the document for shared commands.) -->
<div class="document-pane" class:focused={documentPanes.active === pane.id}
data-document-pane={pane.id} data-document-path={pane.buffer?.relPath ?? ""}
style:--pane-weight={pane.bounds.width}
onpointerdowncapture={() => focusDocumentPane(pane.id)}
onfocusin={() => focusDocumentPane(pane.id)}>
{#if pane.buffer?.diskError}
<div class="conflict" role="alert"><span>{pane.buffer.diskError}</span><button onclick={() => void saveCopy(pane.buffer)}>Save a copy</button><button onclick={() => void documents?.refresh()}>Retry</button></div>
{:else if pane.buffer?.diskContents != null}
<div class="conflict" role="alert">
<span>This file changed on disk. Your edits are preserved. Review both versions before saving.</span>
<button onclick={() => { if (buffer) documents?.resolve(buffer.id, true); }}>Use disk version</button>
<button onclick={() => { if (buffer) documents?.resolve(buffer.id, false); }}>Keep my edits</button>
<button onclick={() => void saveCopy()}>Save a copy</button>
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, true); }}>Use disk version</button>
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, false); }}>Keep my edits</button>
<button onclick={() => void saveCopy(pane.buffer)}>Save a copy</button>
</div>
<details class="disk-review"><summary>View disk version</summary><pre>{buffer.diskContents}</pre></details>
<details class="disk-review"><summary>View disk version</summary><pre>{pane.buffer.diskContents}</pre></details>
{/if}
<EditorPane
bind:this={editorPane}
bind:this={paneComponents[pane.id]}
{tabs}
active={documentPanes.active === pane.id}
onCloseSplit={documentViews.length > 1 ? () => closeSplit(pane.id) : undefined}
hasWorkspace={!!workspace}
onOpenWorkspace={() => void chooseWorkspace()}
onNewFile={() => void newFile()}
@@ -1124,19 +1253,27 @@
onQuickOpen={() => quickOpen = true}
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
{browserOpening}
{buffer}
chrome={view}
{reading}
{focusLine}
buffer={pane.buffer}
chrome={pane.buffer?.chromeOverride ?? pane.buffer?.chrome ?? "Writing"}
reading={pane.reading}
focusLine={documentPanes.active === pane.id ? focusLine : null}
{onChange}
onInsertImage={insertImage}
onInsertImage={file => insertImage(file, pane.buffer)}
onRenameTitle={renameNoteTitle}
tableActions={{ onSearch: searchSelection, onExtract: extractSelection }}
onToggleReading={() => (reading = !reading)}
onToggleChrome={toggleChrome}
onOpenLink={(kind, target) => void openLink(kind, target)}
tableActions={{ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) }}
linkActions={{
browser: browserContribution ? async target => { if (!await browserContribution?.open(target)) throw new Error("Could not open the app browser."); } : undefined,
defaultBrowser: target => openUrl(target),
workspaceItems: link => workspaceLinkItems(link, pane.buffer?.relPath ?? "", pane.id),
}}
onToggleReading={() => setReading(!pane.reading, pane.id)}
onToggleChrome={() => { focusDocumentPane(pane.id); toggleChrome(); }}
onOpenLink={(kind, target) => void openLink(kind, target, pane.buffer?.relPath ?? "", pane.id)}
/>
</div>
{/each}
</div>
</div>
</main>
{#if terminalContribution && terminalStarted}
<div
@@ -1170,7 +1307,7 @@
items={outlineItems}
onJump={(line) => {
pluginEditorActive.set(false);
reading = false;
setReading(false);
focusLine = null;
queueMicrotask(() => {
focusLine = line;
@@ -1199,6 +1336,8 @@
.disk-review { padding: 8px 12px; max-height: 35vh; overflow: auto; flex: 0 0 auto; }
.disk-review pre { white-space: pre-wrap; user-select: text; }
.shell {
position: relative;
isolation: isolate;
height: 100vh;
display: grid;
--ribbon-width: 0px;
@@ -1207,6 +1346,39 @@
background: var(--rs-bg);
}
.workarea-background {
position: absolute;
inset: var(--rs-titlebar-height) 0 22px;
z-index: -1;
pointer-events: none;
background-color: var(--rs-new-tab-bg, var(--rs-bg));
background-image: var(--rs-background-image, var(--rs-new-tab-image, none));
background-size: var(--rs-background-layer-sizes, 100% 100%, var(--rs-background-size, cover));
background-position: var(--rs-background-layer-positions, center, var(--rs-background-position, center));
background-repeat: no-repeat;
}
.workarea-background::before,
.workarea-background::after {
content: '';
position: absolute;
inset: 0;
pointer-events: none;
background-repeat: no-repeat;
}
.workarea-background::before {
background-image: var(--rs-background-previous-image, none);
background-size: var(--rs-background-previous-layer-sizes, 100% 100%, var(--rs-background-previous-size, cover));
background-position: var(--rs-background-previous-layer-positions, center, var(--rs-background-previous-position, center));
}
.workarea-background::after {
background-image: var(--rs-background-transition-image, none);
background-size: var(--rs-background-layer-sizes, 100% 100%, var(--rs-background-size, cover));
background-position: var(--rs-background-layer-positions, center, var(--rs-background-position, center));
}
.shell.left-open {
grid-template-columns: var(--ribbon-width) var(--left) 1px minmax(0, 1fr);
}
@@ -1232,7 +1404,7 @@
min-height: 0;
padding: 6px 5px;
overflow-y: auto;
background: var(--rs-bg-elevated);
background: var(--rs-workarea-sidebar-bg);
border-right: 1px solid var(--rs-border);
}
@@ -1315,7 +1487,7 @@
min-width: 0;
min-height: 0;
overflow: hidden;
background: var(--rs-bg);
background: transparent;
}
.center-stack {
@@ -1337,6 +1509,16 @@
position: relative;
}
.editor-host { container-type: inline-size; }
.document-panes { flex: 1; min-height: 0; display: flex; overflow: hidden; }
.document-pane { flex: var(--pane-weight) 1 0; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
.document-pane + .document-pane { border-left: 1px solid var(--rs-border); }
.document-panes.split .document-pane.focused :global(.chrome-bar) { background: var(--rs-bg-active); }
@container (max-width: 640px) {
.document-panes.split { flex-direction: column; overflow-y: auto; }
.document-panes.split .document-pane { flex: 1 0 320px; }
.document-pane + .document-pane { border-left: 0; border-top: 1px solid var(--rs-border); }
}
.editor-host.plugin-covered { display: none; }
.center { position: relative; }
.plugin-panes { position: relative; flex: 1; min-height: 0; min-width: 0; overflow: hidden; }
@@ -1347,7 +1529,7 @@
.left,
.right {
background: var(--rs-bg-elevated);
background: var(--rs-workarea-sidebar-bg);
}
.left {
@@ -1487,7 +1669,7 @@
display: flex;
flex-direction: column;
min-height: 0;
background: var(--rs-bg-elevated);
background: transparent;
}
.bottom > :global(*) {
+13 -13
View File
@@ -82,6 +82,7 @@
finally { busy = false; }
}
function navigate(event: KeyboardEvent) {
if (event.key === "Escape") { event.preventDefault(); close(); return; }
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
event.preventDefault();
const buttons = [...menu.querySelectorAll<HTMLButtonElement>("button:not(:disabled)")];
@@ -92,14 +93,14 @@
</script>
<svelte:window onresize={() => { if (menu?.matches(":popover-open")) position(); }} />
<div bind:this={menu} popover="auto" class="workspace-menu" role="dialog" aria-label="Workspaces" tabindex="-1" onkeydown={navigate}>
<div bind:this={menu} popover="auto" class="workspace-menu rs-picker" role="dialog" aria-label="Workspaces" tabindex="-1" onkeydown={navigate}>
<h2>Recent workspaces</h2>
<div class="recent" aria-busy={loading || busy}>
{#if loading}<p>Loading workspaces…</p>
{:else if !recent.length}<p>No recent workspaces yet.</p>{/if}
{#each recent as path}
<button class="workspace-row" class:current={path === currentRoot} aria-current={path === currentRoot ? "true" : undefined} disabled={busy} onclick={() => open(path)}>
<Icon icon="folder-open" />
<button class="workspace-row rs-picker-row" aria-current={path === currentRoot ? "true" : undefined} disabled={busy} onclick={() => open(path)}>
<span class="rs-picker-icon"><Icon icon="folder-open" /></span>
<span class="details"><span>{folderName(path)}</span><small>{path}</small></span>
{#if path === currentRoot}<span class="current-label">Current</span>{/if}
</button>
@@ -107,8 +108,8 @@
</div>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<footer>
<button disabled={busy} onclick={newWorkspace}><Icon icon="folder-plus" /> New workspace…</button>
<button disabled={busy} onclick={browse}><Icon icon="folder-open" /> Open another folder…</button>
<button class="rs-picker-row" disabled={busy} onclick={newWorkspace}><span class="rs-picker-icon"><Icon icon="folder-plus" /></span> New workspace…</button>
<button class="rs-picker-row" disabled={busy} onclick={browse}><span class="rs-picker-icon"><Icon icon="folder-open" /></span> Open another folder…</button>
</footer>
</div>
@@ -129,17 +130,16 @@
{/if}
<style>
.workspace-menu, dialog { background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); box-shadow: 0 12px 36px #0006; }
.workspace-menu { position: fixed; inset: auto; margin: 0; padding: 6px; width: min(380px, calc(100vw - 16px)); max-height: calc(100vh - 16px); overflow: auto; }
dialog { background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); box-shadow: 0 12px 36px #0006; }
.workspace-menu { position: fixed; inset: auto; margin: 0; width: min(380px, calc(100vw - 16px)); }
h2 { font-size: 14px; font-weight: 600; margin: 0; padding: 9px 10px; display: flex; align-items: center; gap: 8px; }
p { font-size: 13px; color: var(--rs-text-dim); margin: 8px 10px; }
.recent { max-height: min(360px, 45vh); overflow: auto; padding: 2px; }
button { display: flex; align-items: center; gap: 10px; background: transparent; border: 1px solid transparent; border-radius: var(--rs-control-radius); padding: 9px 10px; color: var(--rs-text); text-align: left; }
button:hover { background: var(--rs-bg-active); }
button:focus-visible, input:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
button:disabled { opacity: .5; }
.recent { max-height: min(360px, 45vh); overflow: auto; }
form button { display: flex; align-items: center; gap: 10px; background: transparent; border: 1px solid transparent; border-radius: var(--rs-control-radius); padding: 9px 10px; color: var(--rs-text); text-align: left; }
form button:hover { background: var(--rs-bg-active); }
form button:focus-visible, input:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
form button:disabled { opacity: .5; }
.workspace-row, footer button { width: 100%; }
.workspace-row.current { background: var(--rs-item-selection-bg); box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border); border-radius: var(--rs-item-selection-radius); }
.details { min-width: 0; display: flex; flex: 1; flex-direction: column; gap: 3px; }
small { font-size: 11px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
.current-label { font-size: 11px; color: var(--rs-accent); }
+24
View File
@@ -0,0 +1,24 @@
export interface BackgroundFrame {
url: string;
blurredUrl?: string;
overlay: number;
position: 'center' | 'top left' | 'top' | 'top right' | 'left' | 'right' | 'bottom left' | 'bottom' | 'bottom right';
size: 'cover' | 'contain' | 'auto';
previous?: Omit<BackgroundFrame, 'previous' | 'transitionMs'>;
transitionMs?: number;
}
export interface BackgroundApi {
readonly version: 1;
chooseFolder(): Promise<string | null>;
defaultFolder?(): Promise<string>;
list(folder: string): Promise<{ name: string }[]>;
read(folder: string, name: string): Promise<Uint8Array>;
readImageSettings?(folder: string): Promise<string | null>;
writeImageSettings?(folder: string, contents: string, expected: string | null): Promise<void>;
set(target: string, frame: BackgroundFrame | null): void;
get(target: string): BackgroundFrame | null;
subscribe(listener: (target: string) => void): () => void;
}
export type BackgroundFiles = Pick<BackgroundApi, 'chooseFolder' | 'defaultFolder' | 'list' | 'read' | 'readImageSettings' | 'writeImageSettings'>;
+125
View File
@@ -0,0 +1,125 @@
import type { BackgroundFrame } from './backgroundContracts.ts';
const positions = ['center', 'top left', 'top', 'top right', 'left', 'right', 'bottom left', 'bottom', 'bottom right'];
const properties = ['--rs-background-overlay', '--rs-background-image', '--rs-background-position', '--rs-background-size', '--rs-background-layer-sizes', '--rs-background-layer-positions', '--rs-background-previous-layer-sizes', '--rs-background-previous-layer-positions', '--rs-background-previous-image', '--rs-background-previous-position', '--rs-background-previous-size', '--rs-background-transition-image', '--rs-workarea-sidebar-bg', '--rs-workarea-editor-bg', '--rs-workarea-surface-opacity', '--rs-workarea-plugin-bg'] as const;
function validImage(frame: BackgroundFrame) {
return frame && typeof frame.url === 'string' && /^blob:[^\s"'\\()]+$/.test(frame.url)
&& Number.isFinite(frame.overlay) && frame.overlay >= -1 && frame.overlay <= 1
&& (frame.blurredUrl === undefined || (typeof frame.blurredUrl === 'string' && /^blob:[^\s"'\\()]+$/.test(frame.blurredUrl)))
&& positions.includes(frame.position) && ['cover', 'contain', 'auto'].includes(frame.size);
}
function image(frame: BackgroundFrame) {
const shade = frame.overlay < 0 ? '255,255,255' : '0,0,0';
const overlay = `linear-gradient(rgba(${shade},${Math.abs(frame.overlay)}),rgba(${shade},${Math.abs(frame.overlay)}))`;
return { overlay, image: `${overlay}, url("${frame.url}")${frame.blurredUrl ? `, url("${frame.blurredUrl}")` : ''}`,
sizes: `100% 100%, ${frame.size}${frame.blurredUrl ? ', cover' : ''}`,
positions: `center, ${frame.position}${frame.blurredUrl ? ', center' : ''}` };
}
function copy(frame: BackgroundFrame): BackgroundFrame {
return { ...frame, ...(frame.previous ? { previous: { ...frame.previous } } : {}) };
}
function checkTarget(target: string) {
if (target !== 'app' && target !== 'pm-all' && !/^pm-board:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(target)) {
throw new Error('Invalid background target.');
}
}
/** Each window retains temporary frames without changing saved appearance settings. */
export class BackgroundHub {
private frames = new Map<string, Map<symbol, BackgroundFrame>>();
private listeners = new Set<(target: string) => void>();
private restore?: () => void;
private body: () => HTMLElement | undefined;
constructor(body: () => HTMLElement | undefined = () => typeof document === 'undefined' ? undefined : document.body) {
this.body = body;
}
get(target: string): BackgroundFrame | null {
checkTarget(target);
const frame = [...(this.frames.get(target)?.values() ?? [])].at(-1);
return frame ? copy(frame) : null;
}
set(owner: symbol, target: string, frame: BackgroundFrame | null) {
checkTarget(target);
if (frame !== null && (!validImage(frame)
|| (frame.previous !== undefined && (!validImage(frame.previous) || 'previous' in frame.previous || 'transitionMs' in frame.previous))
|| (frame.transitionMs !== undefined && (!Number.isFinite(frame.transitionMs) || frame.transitionMs < 0 || frame.transitionMs > 5000)))) {
throw new Error('Invalid background frame. Use a blob URL and an overlay from -1 to 1.');
}
const owners = this.frames.get(target) ?? new Map<symbol, BackgroundFrame>();
const removed = owners.delete(owner);
if (frame) owners.set(owner, copy(frame));
if (owners.size) this.frames.set(target, owners);
else this.frames.delete(target);
if (frame || removed) this.changed(target);
}
removeOwner(owner: symbol) {
for (const [target, owners] of this.frames) {
if (!owners.delete(owner)) continue;
if (!owners.size) this.frames.delete(target);
this.changed(target);
}
}
subscribe(listener: (target: string) => void): () => void {
this.listeners.add(listener);
return () => { this.listeners.delete(listener); };
}
private changed(target: string) {
if (target === 'app') this.applyApp();
for (const listener of [...this.listeners]) {
try { listener(target); } catch { /* A subscriber must not prevent cleanup or other subscribers. */ }
}
}
private applyApp() {
const frame = this.get('app');
if (!frame) { this.restore?.(); this.restore = undefined; return; }
const body = this.body();
if (!body) return;
if (!this.restore) {
const previous = properties.map(key => [key, body.style.getPropertyValue(key), body.style.getPropertyPriority(key)]);
this.restore = () => {
for (const [key, value, priority] of previous) {
if (value) body.style.setProperty(key, value, priority);
else body.style.removeProperty(key);
}
};
}
const { overlay, image: currentImage, sizes, positions: layerPositions } = image(frame);
body.style.setProperty('--rs-background-overlay', overlay);
body.style.setProperty('--rs-background-image', currentImage);
body.style.setProperty('--rs-background-position', frame.position);
body.style.setProperty('--rs-background-size', frame.size);
body.style.setProperty('--rs-background-layer-sizes', sizes);
body.style.setProperty('--rs-background-layer-positions', layerPositions);
body.style.setProperty('--rs-background-previous-layer-sizes', frame.previous ? image(frame.previous).sizes : sizes);
body.style.setProperty('--rs-background-previous-layer-positions', frame.previous ? image(frame.previous).positions : layerPositions);
body.style.setProperty('--rs-workarea-sidebar-bg', 'var(--rs-image-sidebar-bg)');
body.style.setProperty('--rs-workarea-editor-bg', 'var(--rs-image-editor-bg)');
body.style.setProperty('--rs-workarea-surface-opacity', '82%');
body.style.setProperty('--rs-workarea-plugin-bg', 'transparent');
body.style.setProperty('--rs-background-transition-image', frame.previous ? currentImage : 'none');
body.style.setProperty('--rs-background-previous-image', frame.previous ? image(frame.previous).image : 'none');
body.style.setProperty('--rs-background-previous-position', frame.previous?.position ?? frame.position);
body.style.setProperty('--rs-background-previous-size', frame.previous?.size ?? frame.size);
if (typeof document !== 'undefined') {
for (const element of body.querySelectorAll('.workarea-background')) {
for (const animation of element.getAnimations()) animation.cancel();
if (frame.previous && frame.transitionMs && !window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
element.animate([{ opacity: 0 }, { opacity: 1 }], { duration: frame.transitionMs, easing: 'ease-in-out', pseudoElement: '::after' });
}
}
}
}
}
export const backgroundHub = new BackgroundHub();
+8
View File
@@ -242,6 +242,14 @@ async function activate(row: InstalledPlugin, builtin?: PluginModule) {
const session = new ExternalSession(id, {
completionTransport,
git: gitApi,
backgrounds: {
chooseFolder: () => invoke<string | null>('backgrounds_choose_folder', { id }),
defaultFolder: () => invoke<string>('backgrounds_default_folder', { id }),
list: folder => invoke<{ name: string }[]>('backgrounds_list', { id, folder }),
read: async (folder, name) => Uint8Array.from(atob(await invoke<string>('backgrounds_read', { id, folder, name })), character => character.charCodeAt(0)),
readImageSettings: folder => invoke<string | null>('backgrounds_read_image_settings', { id, folder }),
writeImageSettings: (folder, contents, expected) => invoke<void>('backgrounds_write_image_settings', { id, folder, contents, expected }),
},
openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); },
workspace: {
list: path => workspaceList(path ?? ""), read: workspaceRead,
+31 -2
View File
@@ -2,6 +2,8 @@ import { pluginHost, type ContributionRegistry } from "./registry.ts";
import { completionHub } from "../completion/hub.ts";
import { registerCompletionInput } from "../completion/input.ts";
import { showActionMenu } from "../ui/managedActionMenu.ts";
import { backgroundHub } from "./backgrounds.ts";
import type { BackgroundFiles } from "./backgroundContracts.ts";
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
@@ -23,8 +25,10 @@ export class ExternalSession {
private mounted = new Set<Dispose>();
private contributions: Dispose[] = [];
private registry: ContributionRegistry;
private backgroundOwner = Symbol('plugin backgrounds');
private backgroundSubscriptions = new Set<() => void>();
readonly id: string;
private services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] };
private services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] };
private changed: () => void;
private show: PluginApi["openView"];
private close?: PluginApi["closeView"];
@@ -33,7 +37,7 @@ export class ExternalSession {
private receiveTab?: (data: string) => void | Promise<void>;
private openDocument: (path: string) => Promise<void>;
private renameDocument?: PluginApi["renameDocument"];
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] }, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"], replace?: PluginApi["replaceView"], replaceDocument?: PluginApi["replaceDocumentWithView"]) {
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] }, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"], replace?: PluginApi["replaceView"], replaceDocument?: PluginApi["replaceDocumentWithView"]) {
this.openDocument = openDocument;
this.renameDocument = renameDocument;
this.close = close;
@@ -50,6 +54,25 @@ export class ExternalSession {
};
const api: PluginApi = {
id: this.id, signal: this.controller.signal,
...(this.services.backgrounds ? { backgrounds: {
version: 1 as const,
chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()),
...(this.services.backgrounds.defaultFolder ? { defaultFolder: () => this.backgroundRequest(() => this.services.backgrounds!.defaultFolder!()) } : {}),
list: (folder: string) => this.backgroundRequest(() => this.services.backgrounds!.list(folder)),
read: (folder: string, name: string) => this.backgroundRequest(() => this.services.backgrounds!.read(folder, name)),
...(this.services.backgrounds.readImageSettings ? { readImageSettings: (folder: string) => this.backgroundRequest(() => this.services.backgrounds!.readImageSettings!(folder)) } : {}),
...(this.services.backgrounds.writeImageSettings ? { writeImageSettings: (folder: string, contents: string, expected: string | null) => this.backgroundRequest(() => this.services.backgrounds!.writeImageSettings!(folder, contents, expected)) } : {}),
set: (target: string, frame: import('./backgroundContracts.ts').BackgroundFrame | null) => { this.check(); backgroundHub.set(this.backgroundOwner, target, frame); },
get: (target: string) => { this.check(); return backgroundHub.get(target); },
subscribe: (listener: (target: string) => void) => {
this.check();
if (typeof listener !== 'function') throw new Error('A background listener must be a function.');
const off = backgroundHub.subscribe(target => { if (!this.stopped) listener(target); });
const cleanup = () => { off(); this.backgroundSubscriptions.delete(cleanup); };
this.backgroundSubscriptions.add(cleanup);
return cleanup;
},
} } : {}),
ui: { showActionMenu: options => { this.check(); return showActionMenu(options, this.controller.signal); } },
...(this.services.git ? { git: {
status: () => { this.check(); return this.services.git!.status(); },
@@ -145,6 +168,10 @@ export class ExternalSession {
await deadline(this.activation);
}
async run(id: string) { this.check(); const command = this.commands.get(id); if (!command) throw new Error("Unknown plugin command."); await command.run(); }
private backgroundRequest<T>(request: () => Promise<T>): Promise<T> {
this.check();
return request().then(value => { this.check(); return value; });
}
async dropTab(data: string) {
this.check();
if (!this.receiveTab) throw new Error("This plugin cannot receive tabs.");
@@ -170,6 +197,8 @@ export class ExternalSession {
stop(): Promise<void> {
if (this.stopping) return this.stopping;
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.documentTypes.clear(); this.receiveTab = undefined; this.changed();
for (const off of this.backgroundSubscriptions) off();
backgroundHub.removeOwner(this.backgroundOwner);
for (const remove of this.contributions.splice(0)) remove();
this.stopping = (async () => {
const errors: unknown[] = [];
+2
View File
@@ -1,6 +1,7 @@
import type { Contributions } from "./contracts.ts";
import type { CompletionApi } from "../completion/contracts.ts";
import type { ActionMenuItem } from "../ui/actionMenu.ts";
export type { BackgroundFrame, BackgroundApi } from "./backgroundContracts.ts";
/** Package API v1. Compiled plugins export activate(api). */
export type Dispose = () => void | Promise<void>;
export interface PluginCommand { id: string; title: string; icon?: PluginView["icon"]; category?: "open" | "action"; run: () => void | Promise<void> }
@@ -18,6 +19,7 @@ export interface PluginDocumentType {
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
}
export interface PluginApi {
backgrounds?: import("./backgroundContracts.ts").BackgroundApi;
ui?: { showActionMenu(options: import("../ui/managedActionMenu.ts").MenuOptions): { close(): void } };
git?: import("../git/contracts.ts").GitApi;
completion?: CompletionApi;
+29 -10
View File
@@ -6,7 +6,7 @@
import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import { saveBackgroundImage, removeBackgroundImage } from './backgroundImages';
import { APPEARANCE_KEY, DEFAULT_APPEARANCE, BACKGROUND_POSITIONS, BACKGROUND_SIZES, parseAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
import { APPEARANCE_KEY, DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, BACKGROUND_POSITIONS, BACKGROUND_SIZES, parseAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
let appearance = $state<Appearance>({ ...DEFAULT_APPEARANCE });
let error = $state('');
let status = $state('');
@@ -16,16 +16,18 @@
let installed = $state<CustomTheme[]>([]);
let themeInput: HTMLInputElement;
let closePicker = () => {};
const themes = $derived([{ id: 'default', name: 'RuneStone' }, { id: 'claude', name: 'Claude' }, { id: 'sakura', name: 'Sakura' }, ...installed.map(theme => ({ id: `custom:${theme.id}`, name: theme.name }))]);
const themes = $derived([...BUILTIN_THEMES, ...installed.map(theme => ({ id: `custom:${theme.id}` as ThemeName, name: theme.name }))].flatMap(theme =>
themeModes(theme.id).map(mode => ({
theme: theme.id, mode, name: themeModes(theme.id).length === 1 ? theme.name : `${theme.name} ${mode === 'light' ? 'Light' : 'Dark'}`,
}))));
onDestroy(() => closePicker());
function picker(event: MouseEvent, mode = false) {
function picker(event: MouseEvent) {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
const choices = mode ? [{ id: 'light', name: 'Light' }, { id: 'dark', name: 'Dark' }] : themes;
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: mode ? 'Appearance' : 'Color theme', parent: anchor.closest('dialog') ?? undefined,
items: choices.map(choice => ({ label: choice.name, radio: true, checked: choice.id === (mode ? appearance.mode : appearance.theme),
run: () => change(mode ? { ...appearance, mode: choice.id as 'light' | 'dark' } : { ...appearance, theme: choice.id as ThemeName }) })) }).close;
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: 'Color theme', parent: anchor.closest('dialog') ?? undefined,
items: themes.map(choice => ({ label: choice.name, radio: true, checked: choice.theme === appearance.theme && choice.mode === appearance.mode,
run: () => change({ ...appearance, theme: choice.theme, mode: choice.mode }) })) }).close;
}
const positionLabels = ['Center', 'Top left', 'Top center', 'Top right', 'Center left', 'Center right', 'Bottom left', 'Bottom center', 'Bottom right'];
const sizeLabels = ['Fill', 'Fit', 'Actual size'];
@@ -105,10 +107,13 @@
}
</script>
<h2>Appearance</h2>
<p>Choose a color theme and a light or dark appearance.</p>
<p>Choose a color theme variant.</p>
<div class="card">
<div class="setting-row"><span>Color theme</span><button class="picker" aria-label="Color theme" aria-haspopup="menu" onclick={event => picker(event)}>{themes.find(theme => theme.id === appearance.theme)?.name ?? 'RuneStone'}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>Appearance</span><button class="picker" aria-label="Appearance" aria-haspopup="menu" disabled={appearance.theme === 'sakura'} onclick={event => picker(event, true)}>{appearance.mode === 'light' ? 'Light' : 'Dark'}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>Color theme</span><button class="picker" aria-label="Color theme" aria-haspopup="menu" onclick={event => picker(event)}>{themes.find(theme => theme.theme === appearance.theme && theme.mode === appearance.mode)?.name ?? 'RuneStone Dark'}<Icon icon="chevron-down" /></button></div>
</div>
<div class="theme-preview" role="img" aria-label="Color theme preview">
<div class="preview-sidebar" aria-hidden="true"><span></span><span></span><span></span></div>
<div class="preview-document" aria-hidden="true"><strong>RuneStone</strong><span class="preview-prose">A place for your ideas.</span><span class="preview-selection">Selected text</span><span class="preview-link">Link</span><code class="preview-code"><span class="preview-keyword">const</span> name = <span class="preview-string">"RuneStone"</span>;<br /><span class="preview-function">show</span>(name, <span class="preview-number">42</span>);</code></div>
</div>
<div class="theme-actions">
<input bind:this={themeInput} type="file" accept=".json,application/json" aria-label="Theme JSON file" hidden onchange={event => { void importTheme(event.currentTarget.files?.[0]); }} />
@@ -149,6 +154,20 @@
.picker{display:flex;align-items:center;gap:8px;min-height:var(--rs-settings-control-height);max-width:100%;padding:4px 8px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
.picker :global(svg){width:14px;height:14px;flex-shrink:0}
.picker:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}
.theme-preview{display:flex;gap:var(--rs-settings-gap);margin-top:var(--rs-settings-gap);padding:var(--rs-settings-row-padding);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);min-height:100px}
.preview-sidebar{display:flex;flex-direction:column;gap:var(--rs-settings-gap);width:22%;padding:var(--rs-settings-row-padding);background:var(--rs-bg-elevated);border-radius:var(--rs-control-radius)}
.preview-sidebar span{height:6px;background:var(--rs-text-dim);opacity:.5;border-radius:var(--rs-control-radius)}
.preview-sidebar span:first-child{height:20px;background:var(--rs-bg-active);opacity:1}
.preview-document{display:flex;align-items:flex-start;flex-direction:column;gap:var(--rs-settings-gap);flex:1;min-width:0;padding:4px}
.preview-document strong{color:var(--rs-text-strong);font-family:var(--rs-font-heading)}
.preview-prose{font-family:var(--rs-font-prose);color:var(--rs-text)}
.preview-selection{background:var(--rs-selection);color:var(--rs-text);padding:2px 4px;border-radius:var(--rs-item-selection-radius)}
.preview-link{color:var(--rs-accent);font-size:var(--rs-settings-description-size)}
.preview-code{font-family:var(--rs-font-mono);font-size:var(--rs-settings-description-size);line-height:1.6;overflow-wrap:anywhere;white-space:normal}
.preview-keyword{color:var(--rs-syntax-keyword)}
.preview-string{color:var(--rs-syntax-string,var(--rs-ok))}
.preview-function{color:var(--rs-syntax-function,var(--rs-accent-2))}
.preview-number{color:var(--rs-syntax-number,var(--rs-special))}
.overlay-controls{display:flex;align-items:center;flex-wrap:wrap;gap:var(--rs-settings-gap);max-width:100%}
.overlay-controls input[type=range]{width:160px;max-width:100%;min-width:0}
.overlay-value{padding:0;gap:4px;flex-wrap:nowrap}

Some files were not shown because too many files have changed in this diff Show More