diff --git a/docs/design-decisions.md b/docs/design-decisions.md index 5d3a5fe..8254ff6 100644 --- a/docs/design-decisions.md +++ b/docs/design-decisions.md @@ -423,6 +423,16 @@ Correction: prose links and editor controls use the shared tooltip helper. The t 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. +Card a18e86d1 exposed native tab titles outside the shared tooltip helper. +Tab labels and close buttons now use attachTooltip. +The exact tab receives hover, focus, Escape, and theme checks in october15Appearance.smoke.mjs. + +Card 44460b1d exposed native and local tooltips in Git after UI-019. +Cause: Git controls used title attributes and a separate tooltip style. +Correction: Git uses a delegated tooltip helper with the shared .rs-tooltip presentation and theme tokens. +Prevention: Check each reported changed-file, commit, and commit-file control with hover, focus, Escape, both themes, and narrow windows. +Evidence: RuneStone_Git/.audit/git-tooltip-evidence.json and git-tooltip-*.png. Native desktop acceptance remains open. + ### UI-020 — Per-image slideshow layout - Type: Rule change @@ -560,3 +570,174 @@ Replaced by: [UI-024](#ui-024--assertive-functional-color-by-default) strengthen - Evidence: scripts/appearanceLanguage.smoke.mjs, scripts/customThemes.spec.ts, and the affected cards retain checks and screenshots. - Follow-up evidence: Cards 5a56a250-b46a-4319-8f25-5f6ac4362a32, 682ad51f-66a1-477d-b02e-c1acb1c14d4e, and 97fe6f6b-5780-436e-abd8-a8135efbbe87 cover the full range, themed slider, and missing font stacks. `scripts/hostAppearance.smoke.mjs` checks the exact controls and exports. - Limits: Browser checks use desktop mocks. Native display and user acceptance remain open. + +### UI-029 — Text selection transparency + +- Type: Rule change +- Date: 2026-10-15 +- Status: Implemented for user review +- Source: Card cf9f6f56-d7c3-4ed9-9c15-61456c1009b2 requests transparency in selected text. +- Previous rule: The shared selection color could be opaque. +- New rule: Cap selection opacity at 65%. Preserve the theme hue and any lower custom opacity. +- Reason: Keep the background visible beneath selected text. +- Scope: Writer, Reading, IDE, and compatible plugin fields. +- Implementation: appearance.ts sets --rs-selection after the theme palette. Theme exports retain their source colors. +- Evidence: october15Appearance.smoke.mjs checks the exact tab, selected text, slider, background, and installation checkbox. Screenshots stay in output/october15-appearance. +- Limits: Native desktop appearance and user acceptance remain open. + +Card d3b52384 exposed opaque Terminal selection after UI-029. +Cause: The xterm DOM renderer blends selection colors into opaque backgrounds, including selected glyph backgrounds. +Correction: Terminal applies the shared selection color through --rs-terminal-selection. Its adapter caps alpha at 65% and preserves lower alpha values. +The overlay retains the source hue. Selected glyph backgrounds stay transparent, and text stays opaque. +Evidence: RuneStone_Terminal/.audit/terminal-selection-evidence.json records source colors, alpha, composites, and contrast. +Screenshots cover both themes at 620 and 1440 pixels. Measured text contrast is 8.94:1 in dark and 11.80:1 in light. +Native shell, background image, and desktop acceptance remain open. + +### UI-030 — Settings installation checkbox theme drift + +- Type: Recurring problem +- Date: 2026-10-15 +- Status: Implemented for user review +- Source: Card 55911872 reports repeated Settings theme drift. Related theme-control corrections appear in UI-028. +- Cause: The installation checkbox omitted accent-color and used the browser default. +- Correction: PluginManager now reads --rs-accent. This correction adds no fixed palette colors. +- Prevention: Check the exact installation control in the reported theme and another appearance. +- Evidence: october15Appearance.smoke.mjs and output/october15-appearance retain the checks and screenshots. +- Limits: Native desktop appearance and user acceptance remain open. +### UI-031 — Shared Find controls in plugin views + +- Type: Rule change +- Date: 2026-10-15 +- Status: Implemented for user review +- Decision source: Cards 59c3a70a and 4621dd41. +- Previous rule: Document modes shared FindPanel. Plugin views without a Find handler exposed the native browser search. +- New rule: Plugin editor views use FindPanel to search their visible text when the plugin supplies no Find handler. +- Reason: Keep Ctrl+F consistent across the central work area. +- Scope: Plugin editor views. A plugin Find handler retains control of its own search engine. +- Shared implementation: PluginEditor.svelte, Workbench.svelte, readingSearch.ts, FindPanel.svelte, and find.css. +- Evidence: pluginFind.smoke.mjs covers two plugin views, card buttons, hidden content, keyboard navigation, focus return, both themes, and narrow windows. +- Evidence files: output/todo-oct15/plugin-find/. +- Limits: Rendered text search excludes input values and content inside embedded documents. Native desktop acceptance remains open. + +### UI-032 — Checklist marker keyboard entry + +- Type: Recurring problem +- Date: 2026-10-15 +- Status: Implemented for user review +- Source: Card 56229174 returned after the 0.1.37 review. +- Cause: The checkbox replacement starts at the list bullet. The edit interval started later, at the opening bracket. +- Test gap: The earlier smoke placed the caret inside the marker through the editor API. It missed real keyboard entry. +- Correction: The edit interval includes the replacement start. Task text retains its rendered checkbox. +- Shared implementation: liveMarkdown.ts. Existing checkbox styles and theme tokens remain. +- Prevention: Use ArrowLeft and Home from task text. Edit the raw marker, return to text, and toggle the checkbox. +- Evidence: editorClipboardChecklist.smoke.mjs passes in both themes at 1440 and 600 pixels. +- Evidence files: output/editor-clipboard-checklist/. +- Limits: Browser tests use desktop service mocks. Native desktop acceptance remains open. +### UI-033 — List capacity and a frozen All Tasks overview + +- Type: Rule change +- Date: 2026-10-15 +- Status: Implemented for user review +- Decision source: Cards ae44dc20 and 8561a6a0. +- Previous rule: Lists showed counts without capacity. All Tasks grouped cards by status and allowed direct movement. +- New rule: Lists can set an optional maximum. All Tasks shows each board list and prevents direct movement between lists. +- Reason: Show list capacity and prevent accidental moves between similarly named cards and lists from different boards. +- Scope: Project Management Kanban lists and the All Tasks overview. +- Shared implementation: BoardList.maxCards, BoardStore.setLimit, listMenu, allTaskColumns, shared menu tokens, and --rs-error. +- Behavior: Capacity warns at or above the maximum. It permits extra cards, as the supplied references show. +- Behavior: All Tasks retains empty and custom lists with board names. Card details and named boards retain move controls. +- Evidence: List limit, All Tasks, board drag, and package browser checks. Screenshots are in RuneStone_Project_Management/output/card-work/. +- Release separation: 0.2.43 contains list limits. 0.2.43b adds the complete freeze. The earlier 0.2.43a is superseded. +- Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open. + +### UI-034 — Find scope and shared list names + +- Type: Rule change +- Date: 2026-10-16 +- Status: Implemented for user review +- Decision source: Cards 04b333b0 and 505c6a28. +- Previous rule: UI-031 added fallback Find to generic plugin views. UI-033 kept separate columns for matching list names. +- New rule: Document editors expose fallback Find. Generic plugin views and Kanban documents do not expose fallback Find. +- New rule: Matching list names share one All Tasks column. Name matching ignores case and outer spaces. +- Reason: Keep document search relevant and avoid repeated columns across boards. +- Scope: Host plugin Find controls and the Project Management All Tasks overview. +- Shared implementation: PluginEditor.svelte, FindPanel.svelte, readingSearch.ts, and PM all-tasks.ts. +- Behavior: Plugins with a Find handler retain their search behavior. Distinct lists and empty lists remain visible. +- Behavior: Cards appear once per matching column. The overview keeps movement controls disabled. +- Behavior: Merged columns omit board-specific capacity limits. Named boards retain their limits and movement controls. +- Evidence: Host pluginFind smoke, PM All Tasks browser checks, 129 PM unit tests, and shared menu checks pass. +- Evidence files: Host .audit/host-privacy-find and PM output/card-work/all-tasks-{light,dark}-{1100,390}.png. +- Local overrides: No color or shared menu presentation overrides changed. Shared focus and control tokens remain. +- Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open. + +### UI-035 — Board dividers in All Tasks + +- Type: Rule change +- Date: 2026-10-16 +- Status: Implemented for user review +- Decision source: Card 0e80098e-f6a4-4552-a503-601be8b0310c and its divider mockup. +- Previous rule: Matching lists shared a column without board labels. +- New rule: Each populated column groups cards under board names with a divider below each heading. +- Behavior: Shared cards appear once per column. Their heading names all boards represented by that placement. +- Behavior: Cards without a matching active board use No active board. Empty groups stay hidden. +- Reason: Show board membership without repeated columns or card copies. +- Scope: Project Management All Tasks Kanban columns. +- Shared implementation: allTaskGroups, pm-board-group-heading, --pm-text, and --pm-line. +- Local overrides: No palette changes or menu overrides. Heading text stays opaque. +- Evidence: Type checks, unit tests, and All Tasks browser checks cover shared memberships, detail moves, and frozen cards. +- Evidence files: RuneStone_Project_Management/output/card-work/all-tasks-{light,dark}-{1100,390}.png. +- Design check: Headings replace repeated card badges. Existing controls and the work area retain their layout. +- Limits: Browser tests use desktop service mocks. Native desktop acceptance remains open. + +### UI-036 — Compact list collapse and assigned creation + +- Type: Rule change +- Date: 2026-10-16 +- Status: Implemented for user review +- Decision source: Cards fe74c884-3511-4c11-9f6a-8a7e584d940e and f73144cc-6567-4ed3-8b79-14a3ac038016. +- Previous rule: Collapse hid cards without reducing column width. All Tasks lacked creation controls for most board lists. +- New rule: Collapsed lists use narrow strips with vertical names, counts, and an accessible expand control. +- New rule: All Tasks creation requires an active board and resolves list names to that board's list IDs. +- Reason: Recover horizontal space and create assigned cards without leaving the overview. +- Scope: Project Management Kanban columns and the shared card editor. +- Shared implementation: BoardStore.collapse, PMViewState.collapsedLists, openEditor, createSharedChoices, and TaskStore.create. +- Shared tokens: Existing --pm-panel, --pm-line, --pm-text, --pm-radius, and host focus tokens. +- Local overrides: Column layout changes only. No new palette values or menu presentation overrides. +- Design check: The vertical strip preserves list identity and count. Existing Board and List controls handle assignment without a second form. +- Evidence: Unit tests cover assigned creation and stale destinations. Browser tests cover collapse, focus, board switching, required assignment, cancellation, and saved cards. +- Evidence files: RuneStone_Project_Management/output/card-work/collapsed-*, create-all-*, create-board-menu-*, and create-list-menu-* screenshots. +- Limits: Browser tests use mocked workspace services. Native desktop acceptance remains open. +### UI-037 — Saved metadata and explicit description drafts + +- Type: Rule change +- Date: 2026-10-17 +- Status: Implemented for user review +- Decision source: Cards 220b0d31, 58575469, f44bdd09, and 4ade34d0. The user chose drafts until Save in this chat. +- New rule: Existing card descriptions remain drafts until the user chooses Save. Cancel restores the saved description. +- Behavior: Closing card details preserves the draft separately. Reopening shows an unsaved marker. Edit opens the draft. +- Behavior: Board and list choices save immediately. Other card metadata uses the same save path on outside click and Close. +- Reason: Keep description edits safe while making the commit action clear. Prevent a close action from discarding metadata. +- Scope: Project Management card details and local draft storage. +- Shared implementation: openEditor, descriptionEditor, and the description draft store. +- Shared tokens: Existing control, focus, panel, and text tokens. No palette changes. +- Evidence: TypeScript and 134 unit tests pass. All 236 browser checks pass across the full run and the focused fixture rerun. +- Evidence files: RuneStone_Project_Management/.audit/october-{description,timestamp}-{theme}-{width}.png. +- Limits: Native desktop acceptance remains open. + +### UI-038 — Fixed workspace default board + +- Type: Rule change +- Date: 2026-10-17 +- Status: Implemented for user review +- Decision source: Cards 2596f9c9 and 8cffc80a, including the agreed default-board scope. +- New rule: The Project Management launcher opens a fixed workspace default: All tasks or a selected board. +- Behavior: Restored tabs and explicit board links retain their targets. An unavailable default returns to All tasks. +- Behavior: A workspace without boards shows a visible New board action. +- Reason: Give first-time users a clear start and let each workspace retain its chosen entry point. +- Scope: Project Management settings, initial empty state, and host view launch handling. +- Shared implementation: PluginView.launch, ExternalSession.launch, and the existing Project Management board registration. +- Shared tokens: Existing action, control, focus, and menu tokens. No palette changes. +- Evidence: Host session tests and browser checks pass for launch, explicit opening, and restored tabs. Plugin checks pass, including all 236 browser checks across full and focused runs. +- Evidence files: RuneStone_Project_Management/.audit/october-{default,onboarding}-{theme}-{width}.png. The packaged plugin also passes its host state check. +- Local overrides: The new onboarding control uses the existing standard button for readable text in both themes. +- Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open. diff --git a/docs/menu-surfaces.json b/docs/menu-surfaces.json index cb9a61f..3b53520 100644 --- a/docs/menu-surfaces.json +++ b/docs/menu-surfaces.json @@ -236,12 +236,12 @@ "RuneStone_Project_Management/src/ui.ts": { "counts": { "action": 4, - "nativeChoice": 14, + "nativeChoice": 13, "picker": 1, "localPopup": 1 }, "design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained", - "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" + "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts; tests/list-limits.spec.ts; tests/all-tasks.spec.ts; tests/card-board-details.spec.ts" }, "RuneStone_Terminal/src/TerminalDock.svelte": { "counts": { @@ -321,6 +321,13 @@ }, "design": "Shared action menu for interface language; settings retain ordinary controls", "check": "scripts/appearanceLanguage.smoke.mjs; scripts/menuConsistency.smoke.mjs" + }, + "RuneStone_Project_Management/src/workspace-default.ts": { + "counts": { + "nativeChoice": 1 + }, + "design": "Uses the host menu. Keeps a native selector for older hosts.", + "check": "RuneStone_Project_Management/tests/october-cards.spec.ts with PM_HOST_URL; both themes, narrow layout, keyboard focus" } } } diff --git a/docs/plugins.md b/docs/plugins.md index 79c9d81..b8e47be 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -28,7 +28,7 @@ The local source folder is `../RuneStone_Terminal/` when both repositories share No plugin starts automatically in a fresh installation. The application build does not include these packages. Package builds include their JavaScript dependencies and terminal styles. -Build them again after source changes, then uninstall the old version and install the new ZIP. +Build them again after source changes, then select the new ZIP through Install plugin ZIP. The old bundled switches no longer apply. Existing terminal appearance settings remain available after installation. Formula source stays in Markdown files when the plugin is absent, disabled, or removed. Native pseudo-terminal services remain in the desktop host. The Terminal package supplies the interface, shortcuts, and session controls. @@ -55,7 +55,11 @@ External plugins run with RuneStone's application access. Enable only code you t Package metadata and hashes do not verify a publisher's identity. This version has no permission sandbox or marketplace. Scanning and installation do not execute code, install dependencies, or run installation scripts. -Plugins cannot overwrite an existing ID. Uninstall the previous package before installing another version. +A package with an installed ID updates that plugin after review. Choose Apply packages to replace its files. +The review shows the current and new versions. Updates keep plugin settings and the previous enabled state. +RuneStone stops the plugin in every window and waits for cleanup before replacement. Cleanup failure blocks replacement. +An interrupted update restores the old package unless the new catalog entry committed. +Automatic repository scans remain future work. 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. @@ -116,7 +120,8 @@ Staging directories never participate in plugin discovery. Each reviewed candidate belongs to one window and expires after 30 minutes. Rust checks the source and staged content hashes before publishing a complete directory. -A duplicate destination blocks publication. A crash cannot enable a partial installation. +An untracked destination blocks publication. Reviewed updates pin the installed package hash and retain a recovery journal. +A crash cannot enable a partial installation. Removal plans belong to one window and expire after five minutes. The backend accepts a single-use removal token when the user confirms deletion. @@ -344,9 +349,6 @@ export function activate(api) { | --- | --- | | `api.id` | The installed plugin ID | | `api.signal` | An abort signal triggered before shutdown | -| `api.i18n.locale` | Current interface language: `en`, `fr`, `ja`, or `zh-CN`. Optional API | -| `api.i18n.t(message, values?, catalogs?)` | Translate an explicit interface message with optional plugin catalogs and named placeholders | -| `api.i18n.subscribe(listener)` | Receive the current language immediately and subsequent changes. Returns cleanup and stops when the plugin is disabled | | `contribute(key, value)` | Register a typed terminal or table formula contribution | | `registerCommand({ id, title, run })` | Add a command to Commands in the toolbar | | `registerCommand({ category: "open", ... })` | Add a launch action to Open tab or view | @@ -393,12 +395,9 @@ Settings loads enabled plugins so their configuration pages remain available in The host calls `mount(container, context)` with `context.surface` set to `"settings"` or `"view"`. Older hosts can omit the context argument. -The optional language API shares the language selected in General settings across plugin views and windows. -Plugins supply their own catalogs for plugin-specific text. A missing message falls back to the shared host catalog, then its English source. -For example, `api.i18n?.t('Hide column', {}, { fr: { 'Hide column': 'Masquer la colonne' } }) ?? 'Hide column'`. -Use a subscription to refresh interface labels after a language change. Dispose a view's subscription when that view closes. -Translate explicit interface text only. Keep document text, filenames, board names, IDs, and keyboard identifiers unchanged. -Existing packages retain their current language until their source adopts this API and supplies catalogs. +The language setting applies to RuneStone's interface. The host does not translate plugin interfaces or supply a plugin translation API. +Plugin authors can manage translations within their own packages. + Local Autocomplete keeps temporary reference text in its editor view because that text belongs to one window. Open Commands → Configure Local Autocomplete in that window to use reference text. @@ -554,3 +553,11 @@ Each window keeps its own sequence. The plugin settings API shares folder and pl 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. + +### View launch defaults + +Views can supply an optional `launch()` handler for entry through the plugin launcher or navigation button. +The handler can select a default view with `api.openView(id)`. +Explicit `api.openView` calls and restored tabs bypass the launch handler and retain their targets. +Views without a handler open as before. Older hosts ignore this optional field. +Project Management uses this handler for its fixed workspace default board. diff --git a/docs/ui-design.md b/docs/ui-design.md index ebf9c9f..5bfbc51 100644 --- a/docs/ui-design.md +++ b/docs/ui-design.md @@ -286,6 +286,10 @@ Tooltips use the shared tooltip tokens for padding, font size, surface, text, an 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. +Text selection retains the theme hue with at most 65% opacity. This lets users see the background through selected text. +Explicit lower opacity values remain unchanged. Text stays opaque. Theme exports retain the source palette colors. +See [UI-029](design-decisions.md#ui-029--text-selection-transparency). + See [UI-019](design-decisions.md#ui-019--one-tooltip-surface). ## Browser and slideshow images @@ -307,3 +311,63 @@ See [UI-018](design-decisions.md#ui-018--named-palettes-and-local-fonts) for the 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). +## Find controls + +Writer, source, Reading, and plugin editor views share FindPanel and find.css. +Plugin document editors without a Find handler search their visible rendered text through readingSearch.ts. +Generic plugin views and Kanban documents do not expose fallback Find. Find and Replace inputs disable saved-info suggestions. +Keep replacement controls hidden for rendered text. Preserve plugin Find handlers for views with their own search engine. +Ctrl+F opens Find. Enter and Shift+Enter select matches. Escape closes Find and returns focus. +See [UI-031](design-decisions.md#ui-031--shared-find-controls-in-plugin-views) for the plugin scope and limits. +## Project Management lists + +A list can set an optional maximum through its shared action menu. Show the active count and maximum together. +Use an opaque warning icon and tooltip when the count reaches or exceeds the maximum. Extra cards remain permitted. +Count all active cards in the list, including cards outside the current search results. + +All Tasks merges lists with matching names into one column. Name matching ignores case and outer spaces. +Cards appear once per matching column. Distinct lists and empty lists remain visible. +Merged columns omit board-specific capacity limits. Named board lists retain their own limits. +Keep this overview frozen against card drag and quick movement actions. Card details and named boards retain their move controls. +See [UI-033](design-decisions.md#ui-033--list-capacity-and-a-frozen-all-tasks-overview) for the reason and separate hotfix. + +See [UI-034](design-decisions.md#ui-034--find-scope-and-shared-list-names) for the current Find and All Tasks rules. + +All Tasks groups cards within each column under board names with dividers. +Shared cards appear once per column, under a heading that names each matching board. +Cards without an active board use No active board. Empty groups stay hidden. +See [UI-035](design-decisions.md#ui-035--board-dividers-in-all-tasks) for the scope and review evidence. + + +### Collapse and creation + +Lists collapse into narrow strips with vertical names and card counts in named boards and All Tasks. +The expand control keeps its accessible name, tooltip, keyboard focus, and expanded state. +Named boards save collapse state with their lists. All Tasks saves its own collapse state with the view. +Collapsing All Tasks columns does not change board lists or card placements. + +All Tasks can create cards through each column or the New card action. +Each new card requires an active board. The destination list uses that board's own list ID. +A matching list name selects the destination list when available. Otherwise, the board's default list applies. +The shared card editor and host choice menus supply the Board and List controls. +Card movement remains disabled in the overview. +See [UI-036](design-decisions.md#ui-036--compact-list-collapse-and-assigned-creation) for the decision. + +### Card drafts and metadata + +Existing card descriptions remain drafts until Save. Cancel restores the saved description. +Closing card details preserves the draft separately. Reopening shows an unsaved marker. Edit opens the draft. +Board and list choices save immediately. Close and outside click use the same save path for other metadata. +Keep readable space below long descriptions and use the labels Save and Cancel. +See [UI-037](design-decisions.md#ui-037--saved-metadata-and-explicit-description-drafts) for the reason and checks. + +### Default board and card creation time + +Each workspace can choose a fixed default: All tasks or one board. +The launcher uses that default. Restored tabs and explicit links retain their targets. +An unavailable default returns to All tasks. A workspace without boards shows a visible New board action. +See [UI-038](design-decisions.md#ui-038--fixed-workspace-default-board) for the scope and host contract. + +New cards record their original creation time. Card details show that date and time. +Existing cards show Unknown unless a reliable original creation time exists. +Moves and later edits do not change the creation time. Keep timestamps out of board cards. diff --git a/output/tab-site-icon-dark.png b/output/tab-site-icon-dark.png index e18778d..3d8cf47 100644 Binary files a/output/tab-site-icon-dark.png and b/output/tab-site-icon-dark.png differ diff --git a/output/tab-site-icon-light.png b/output/tab-site-icon-light.png index e8b5f51..3d8cf47 100644 Binary files a/output/tab-site-icon-light.png and b/output/tab-site-icon-light.png differ diff --git a/package.json b/package.json index 8010d53..4cc0df8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "runestone", - "version": "0.1.36", + "version": "0.1.41", "description": "Desktop editor for a local workspace", "type": "module", "scripts": { diff --git a/scripts/customThemes.spec.ts b/scripts/customThemes.spec.ts index ec5d7f8..5b3c309 100644 --- a/scripts/customThemes.spec.ts +++ b/scripts/customThemes.spec.ts @@ -65,13 +65,13 @@ test('Full transparency range produces valid surface opacity values', () => { } } }); -test('Opaque mode removes surface transparency and retains the amount for re-enabling', () => { +test('Opaque mode retains background ownership and the amount for re-enabling', () => { const values = new Map(); const root = { dataset: {} as Record, style: { setProperty: (key: string, value: string) => values.set(key, value) } } as unknown as HTMLElement; applyTransparency({ enabled: false, amount: 32 }, root); assert.equal(values.get('--rs-surface-opacity'), '100%'); assert.equal(values.get('--rs-editor-surface-opacity'), '100%'); - assert.equal(values.get('--rs-transparent-plugin-bg'), 'var(--rs-bg)'); + assert.equal(values.get('--rs-transparent-plugin-bg'), 'transparent'); assert.equal(root.dataset.transparency, 'off'); applyTransparency({ enabled: true, amount: 18 }, root); assert.equal(values.get('--rs-surface-opacity'), '82%'); diff --git a/scripts/documentFind.spec.ts b/scripts/documentFind.spec.ts new file mode 100644 index 0000000..ed7f3bb --- /dev/null +++ b/scripts/documentFind.spec.ts @@ -0,0 +1,23 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { SearchQuery } from "@codemirror/search"; +import { documentMatches, replacementText } from "../src/lib/editor/findTarget.ts"; + +test("document search uses Writer word matching and normalized CRLF positions", () => { + const query = new SearchQuery({ search: "Alpha", wholeWord: true, caseSensitive: true }); + const { state, matches } = documentMatches("Alpha alphabet\r\nalpha Alpha", query); + assert.deepEqual(matches.map(({ from, to }) => ({ from, to })), [{ from: 0, to: 5 }, { from: 21, to: 26 }]); + assert.equal(state.doc.lineAt(matches[1].from).number, 2); + assert.equal(state.doc.lineAt(matches[1].from).from, 15); +}); + +test("replacement keeps regex context, capture groups, dollars, and line breaks", () => { + const query = new SearchQuery({ search: "(?<=G)(amma)", regexp: true, replace: "$1-$12-$&-$$\\n" }); + assert.equal(replacementText("Gamma", 1, query), "amma-amma2-amma-$\n"); + assert.equal(replacementText("Alpha", 0, new SearchQuery({ search: "Alpha", replace: "$1\\t" })), "$1\t"); +}); + +test("empty and invalid queries do not produce matches", () => { + assert.deepEqual(documentMatches("Alpha", new SearchQuery({ search: "" })).matches, []); + assert.deepEqual(documentMatches("Alpha", new SearchQuery({ search: "[", regexp: true })).matches, []); +}); diff --git a/scripts/documents.spec.ts b/scripts/documents.spec.ts index 2ecb8fc..b3ba4b1 100644 --- a/scripts/documents.spec.ts +++ b/scripts/documents.spec.ts @@ -24,6 +24,25 @@ function setup() { return { docs, disk, io }; } +test("imported tabs retain unsaved text and preserve pinned empty tabs", async () => { + const { docs } = setup(); + docs.newTab(); + const empty = docs.active!; + docs.togglePin(empty.relPath); + const source = setup().docs; + await source.open(entry("note.md")); + source.edit(source.active!.id, "unsaved source text"); + source.togglePin("note.md"); + assert.equal(docs.importTab(source.active!), true); + assert.equal(docs.active!.contents, "unsaved source text"); + assert.equal(docs.active!.saved, "original"); + assert.equal(docs.active!.pinned, true); + assert.notEqual(docs.active!.id, source.active!.id); + assert.ok(docs.buffers.some(tab => tab.id === empty.id)); + assert.equal(docs.importTab({ ...source.active!, contents: "different" }), false); + assert.equal(docs.active!.contents, "unsaved source text"); +}); + test("background loading for a split preserves the selected document and its unsaved edits", async () => { const { docs } = setup(); await docs.open(entry("note.md")); diff --git a/scripts/editorClipboardChecklist.smoke.mjs b/scripts/editorClipboardChecklist.smoke.mjs new file mode 100644 index 0000000..8e80639 --- /dev/null +++ b/scripts/editorClipboardChecklist.smoke.mjs @@ -0,0 +1,149 @@ +// 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-clipboard-checklist', { 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.evaluate(async () => { + const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js'); + window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content')); + }); + const source = '# Clipboard and tasks\n\n- [ ] CCNA lab\n- [x] CCNA course\n\nPaste here.\n'; + const reset = async () => page.evaluate(source => { + window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: source.indexOf('CCNA lab') } }); + window.__CM__.focus(); + }, source); + const count = () => page.locator('.writer-checkbox').count(); + const clipboard = '
TickerName
ADBE.USAdobe
ADSK.USAutodesk
'; + for (const mode of ['dark', 'light']) { + await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode); + for (const width of [1440, 600]) { + if (width === 600) { + await page.getByRole('button', { name: 'Files', exact: true }).click(); + await page.getByRole('button', { name: 'Hide outline', exact: true }).click(); + } + await page.setViewportSize({ width, height: width === 600 ? 760 : 1000 }); + await reset(); + assert.equal(await count(), 2, 'Caret at task text keeps both checkboxes'); + await page.screenshot({ path: `output/editor-clipboard-checklist/${mode}-${width}-task-text.png` }); + await page.keyboard.press('ArrowLeft'); + assert.equal(await count(), 1, 'ArrowLeft from text reveals the marker'); + await page.screenshot({ path: `output/editor-clipboard-checklist/${mode}-${width}-task-marker.png` }); + await page.keyboard.press('Home'); + assert.equal(await count(), 1, 'Home keeps the marker editable'); + await page.keyboard.press('ArrowRight'); + await page.keyboard.press('ArrowRight'); + await page.keyboard.press('ArrowRight'); + await page.keyboard.press('Delete'); + await page.keyboard.type('x'); + assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /- \[x\] CCNA lab/); + await page.keyboard.press('Home'); + for (let i = 0; i < 6; i++) await page.keyboard.press('ArrowRight'); + assert.equal(await count(), 2, 'Leaving the marker restores the checkbox'); + await page.keyboard.type('New '); + assert.equal(await count(), 2, 'Typing task text keeps the checkbox'); + await page.locator('.writer-checkbox').first().click(); + assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /- \[ \] New CCNA lab/); + await page.evaluate(() => { + const view = window.__CM__; + view.dispatch({ selection: { anchor: view.state.sliceDoc().indexOf('Paste here.') } }); view.focus(); + }); + await page.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate((node, html) => { + const data = new DataTransfer(); data.setData('text/html', html); data.setData('text/plain', 'Ticker\tName\nADBE.US\tAdobe\nADSK.US\tAutodesk'); + node.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true })); + }, clipboard); + await page.locator('.live-writer table').waitFor(); + const pasted = await page.evaluate(() => window.__CM__.state.sliceDoc()); + assert.doesNotMatch(pasted, /Fragment|/); + assert.match(pasted, /\| Ticker \| Name \|/); + assert.equal(await page.locator('.live-writer table tr').count(), 3); + await page.screenshot({ path: `output/editor-clipboard-checklist/${mode}-${width}-table-paste.png` }); + if (width === 600) { + 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(); + } + } + } + assert.deepEqual(errors, []); + console.log('PASS: keyboard marker entry, task text, checkbox toggle, Windows HTML clipboard fragments, both themes and narrow layouts.'); +} catch (error) { + await page.screenshot({ path: 'output/editor-clipboard-checklist/failure.png' }); + throw error; +} finally { await browser.close(); } diff --git a/scripts/editorTemplateHyphen.smoke.mjs b/scripts/editorTemplateHyphen.smoke.mjs new file mode 100644 index 0000000..4404424 --- /dev/null +++ b/scripts/editorTemplateHyphen.smoke.mjs @@ -0,0 +1,155 @@ +// 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) || (!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-template-hyphen', { recursive: true }); + await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420'); + await page.getByText('smoke-workspace', { exact: true }).waitFor(); + // Save the empty task lines from the reported template, then create through + // the normal note action so the filename receives the initial focus. + await page.evaluate(async () => { + const { saveNoteTemplate } = await import('/src/lib/workspace/templates.ts'); + await saveNoteTemplate('To Do', '- [ ] \n'.repeat(10)); + }); + await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click(); + await page.getByRole('button', { name: 'New note', exact: true }).last().click(); + await page.getByRole('menuitem', { name: 'To Do', exact: true }).click(); + const title = page.getByRole('textbox', { name: 'Note filename', exact: true }); + await title.waitFor(); + await page.waitForFunction(() => document.activeElement?.getAttribute('aria-label') === 'Note filename'); + await page.evaluate(async () => { + const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js'); + window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content')); + }); + const count = () => page.locator('.writer-checkbox').count(); + const expectCount = async expected => { + await page.waitForFunction(expected => document.querySelectorAll('.writer-checkbox').length === expected, expected); + assert.equal(await count(), expected); + }; + const setSource = source => page.evaluate(source => { + window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: source.length } }); + window.__CM__.focus(); + }, source); + const plain = 'Some generic mobs or factions,\n-'; + for (const mode of ['dark', 'light']) { + await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode); + for (const width of [1440, 600]) { + await page.setViewportSize({ width, height: width === 600 ? 760 : 1000 }); + if (width === 600) { + await page.getByRole('button', { name: 'Files', exact: true }).click(); + await page.getByRole('button', { name: 'Hide outline', exact: true }).click(); + } + if (!(await title.isVisible())) await page.getByRole('button', { name: 'Rename note', exact: true }).click(); + await title.focus(); + await expectCount(10); + await page.screenshot({ path: `output/editor-template-hyphen/${mode}-${width}-template-title.png` }); + await page.keyboard.press('Escape'); + await page.evaluate(() => { + const view = window.__CM__; + view.dispatch({ selection: { anchor: 0 } }); view.focus(); + }); + await expectCount(9); + await page.keyboard.press('End'); + await page.keyboard.type('First task'); + await expectCount(10); + await page.locator('.writer-checkbox').first().click(); + assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /^- \[x\] First task/); + await page.screenshot({ path: `output/editor-template-hyphen/${mode}-${width}-template-edit.png` }); + + await setSource(plain); + assert.equal(await page.locator('.writer-h2').count(), 0, 'A lone hyphen must not enlarge preceding prose'); + await page.screenshot({ path: `output/editor-template-hyphen/${mode}-${width}-single-hyphen.png` }); + await page.keyboard.type(' Item'); + assert.equal(await page.locator('.writer-h2').count(), 0, 'The hyphen continues into a list'); + assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), plain + ' Item'); + await setSource(plain + '-'); + assert.equal(await page.locator('.writer-h2').count(), 1, 'Two hyphens retain Setext heading support'); + await setSource('A normal heading\n===\n'); + assert.equal(await page.locator('.writer-h1').count(), 1); + // Restore the template for the next theme and size without an active body caret. + await setSource('- [ ] \n'.repeat(10)); + await page.getByRole('button', { name: 'Rename note', exact: true }).click(); + if (width === 600) { + 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(); + } + } + } + assert.deepEqual(errors, []); + console.log('PASS: template creation, filename focus, keyboard task entry, checkbox toggle, lone hyphen, list continuation, and Setext headings in both themes and narrow layouts.'); +} catch (error) { + await page.screenshot({ path: 'output/editor-template-hyphen/failure.png' }); + throw error; +} finally { await browser.close(); } diff --git a/scripts/externalPlugins.spec.ts b/scripts/externalPlugins.spec.ts index 07c2071..b8f4364 100644 --- a/scripts/externalPlugins.spec.ts +++ b/scripts/externalPlugins.spec.ts @@ -2,7 +2,6 @@ import test from "node:test"; import assert from "node:assert/strict"; import { ExternalSession } from "../src/lib/plugins/externalSession.ts"; import type { PluginApi } from "../src/lib/plugins/sdk.ts"; -import { locale } from "../src/lib/i18n/index.ts"; function fixture() { let writes = 0; const session = new ExternalSession("org.test.demo", { @@ -13,25 +12,6 @@ function fixture() { return { session, writes: () => writes }; } -test("plugin language changes stop before cleanup and reject later access", async () => { - const { session } = fixture(); - const changes: string[] = []; - let api!: PluginApi; - try { - await session.start({ activate(value) { - api = value; - api.i18n!.subscribe(language => changes.push(language)); - api.onDispose(() => { locale.set('ja'); }); - } }); - locale.set('fr'); - assert.equal(api.i18n!.t('Settings'), 'Paramètres'); - await session.stop(); - assert.deepEqual(changes, ['en', 'fr']); - assert.throws(() => api.i18n!.t('Settings'), /disabled/); - assert.throws(() => api.i18n!.locale, /disabled/); - } finally { await session.stop(); locale.set('en'); } -}); - test("native Markdown discovery remains optional and is revoked on disable", async () => { let api!: PluginApi; let scans = 0; @@ -133,3 +113,26 @@ test("batch workspace reads remain optional and stop when the plugin is disabled await old.start({ activate(value) { assert.equal(value.workspace.readMany, undefined); } }); await old.stop(); }); + +test("view launch selects a default while explicit opens preserve their target", async () => { + const opened: string[] = []; + let api!: PluginApi; + const session = new ExternalSession("org.test.launch", { + workspace: { list: async () => [], read: async () => "", write: async () => {} }, + settings: { read: async () => null, write: async () => {} }, + assets: { read: async () => new Uint8Array() }, + }, () => {}, id => { opened.push(id); }); + await session.start({ activate(value) { + api = value; + api.registerView({ id: "all", title: "All", launch: async () => { api.openView("board"); }, mount() {} }); + api.registerView({ id: "board", title: "Board", mount() {} }); + assert.throws(() => api.registerView({ id: "invalid", title: "Invalid", launch: true as never, mount() {} }), /launch handler/); + } }); + await session.launch("all"); + api.openView("all"); + await session.launch("board"); + assert.deepEqual(opened, ["board", "all", "board"]); + await assert.rejects(session.launch("missing"), /Unknown plugin view/); + await session.stop(); + await assert.rejects(session.launch("all"), /disabled/); +}); diff --git a/scripts/htmlClipboard.spec.ts b/scripts/htmlClipboard.spec.ts new file mode 100644 index 0000000..39964d2 --- /dev/null +++ b/scripts/htmlClipboard.spec.ts @@ -0,0 +1,17 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { htmlToMarkdown } from "../src/lib/workspace/htmlToMarkdown.ts"; + +test("Windows HTML clipboard fragment comments do not become table content", () => { + const html = '
TickerName
ADBE.USAdobe
ADSK.USAutodesk
'; + assert.equal(htmlToMarkdown(html), '| Ticker | Name |\n| --- | --- |\n| ADBE.US | Adobe |\n| ADSK.US | Autodesk |'); +}); + +test("comments inside cells preserve adjacent text and formatting", () => { + const html = '
Notes
First part
Second
'; + assert.equal(htmlToMarkdown(html), '| Notes |\n| --- |\n| First part
**Second** |'); +}); + +test("escaped comment text remains user content", () => { + assert.equal(htmlToMarkdown('

<!--Example-->

'), ''); +}); diff --git a/scripts/october15Appearance.smoke.mjs b/scripts/october15Appearance.smoke.mjs new file mode 100644 index 0000000..27c93a9 --- /dev/null +++ b/scripts/october15Appearance.smoke.mjs @@ -0,0 +1,166 @@ +// 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:window|is_maximized') return false; + if (command === 'plugins_snapshot') return { root: 'C:/theme-test-plugins', plugins: [] }; + 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/october15-appearance', { 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(); + for (const mode of ['dark', 'light']) { + await page.evaluate(async mode => { + const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); + saveAppearance({ theme: 'default', mode, transparency: { enabled: true, amount: 0 }, newTabBackground: { image: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=' } }); + }, mode); + const tab = page.getByRole('tab', { name: /welcome\.md/ }); + assert.equal(await tab.getAttribute('title'), null); + await page.mouse.move(600, 600); + await tab.hover(); + await page.locator('.rs-tooltip:popover-open').waitFor(); + assert.match(await page.locator('.rs-tooltip:popover-open').innerText(), /welcome\.md/); + await page.screenshot({ path: `output/october15-appearance/${mode}-tab-tooltip.png` }); + await page.keyboard.press('Escape'); + assert.equal(await page.locator('.rs-tooltip:popover-open').count(), 0); + await tab.focus(); + await page.locator('.rs-tooltip:popover-open').waitFor(); + await page.keyboard.press('Escape'); + const writer = page.getByRole('textbox', { name: 'Writing editor', exact: true }); + await writer.click(); await page.keyboard.press('Control+a'); + const colors = await writer.evaluate(node => { + const root = getComputedStyle(document.documentElement); + return { selection: root.getPropertyValue('--rs-selection'), bg: getComputedStyle(node, '::selection').backgroundColor, + text: getComputedStyle(node).color, image: root.getPropertyValue('--rs-new-tab-image'), pluginBg: root.getPropertyValue('--rs-workarea-plugin-bg') }; + }); + assert.match(colors.selection.trim(), /^#[0-9a-f]{6}a6$/i); + assert.match(colors.bg, /0\.65/); + assert.notEqual(colors.image.trim(), 'none'); + assert.equal(colors.pluginBg.trim(), 'transparent'); + console.log(mode, colors); + await page.screenshot({ path: `output/october15-appearance/${mode}-selection.png` }); + await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click(); + await page.locator('.empty').waitFor(); + await page.screenshot({ path: `output/october15-appearance/${mode}-zero-background.png` }); + await page.getByRole('tab', { name: /welcome\.md/ }).click(); + } + await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true'); + await page.getByRole('button', { name: 'Appearance', exact: true }).click(); + for (const mode of ['dark', 'light']) { + await page.evaluate(async mode => { + (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }); + window.dispatchEvent(new Event('focus')); + }, mode); + const slider = page.locator('#surface-transparency'); + for (const width of [1100, 390]) { + await page.setViewportSize({ width, height: 800 }); + await slider.fill('0'); const zero = await slider.boundingBox(); + for (const amount of ['1', '9', '11', '18', '99', '100']) { + await slider.fill(amount); const current = await slider.boundingBox(); + assert.equal(current.x, zero.x); assert.equal(current.width, zero.width); + } + await page.screenshot({ path: `output/october15-appearance/${mode}-${width}-slider.png` }); + } + } + await page.evaluate(() => { + const invoke = window.__TAURI_INTERNALS__.invoke; + window.__TAURI_INTERNALS__.invoke = (command, args) => command === 'plugins_choose' + ? Promise.resolve([{ token: 'theme-test', source: 'C:/Downloads/example.zip', error: null, + manifest: { id: 'example', name: 'Theme example', version: '0.1.0', description: 'Theme control test', author: 'RuneStone', entry: 'main.js' } }]) + : invoke(command, args); + }); + await page.getByRole('button', { name: 'Plug-ins', exact: true }).click(); + for (const [theme, mode] of [['harvest-moon', 'dark'], ['default', 'light']]) { + await page.evaluate(async ({ theme, mode }) => { + (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme, mode }); window.dispatchEvent(new Event('focus')); + }, { theme, mode }); + await page.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click(); + const checkbox = page.getByRole('checkbox', { name: 'Theme example', exact: true }); + await checkbox.waitFor(); + assert.equal(await checkbox.evaluate(node => getComputedStyle(node).accentColor), await page.evaluate(() => { + const probe = document.createElement('span'); probe.style.color = 'var(--rs-accent)'; document.body.append(probe); + const color = getComputedStyle(probe).color; probe.remove(); return color; + })); + await checkbox.focus(); + await page.screenshot({ path: `output/october15-appearance/${theme}-${mode}-install-checkbox.png` }); + await page.getByRole('button', { name: 'Cancel', exact: true }).click(); + } + assert.deepEqual(errors, []); + console.log('PASS: exact tab tooltips, translucent text selection, retained zero-transparency background, stable slider, themed installation checkbox.'); +} catch (error) { + await page.screenshot({ path: 'output/october15-appearance/failure.png' }); + throw error; +} finally { await browser.close(); } diff --git a/scripts/october15Editor.smoke.mjs b/scripts/october15Editor.smoke.mjs new file mode 100644 index 0000000..df7e32c --- /dev/null +++ b/scripts/october15Editor.smoke.mjs @@ -0,0 +1,159 @@ +// 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/october15-editor', { 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.evaluate(async () => { + const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js'); + window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content')); + }); + const source = '# Example\n\n| Name | Notes |\n| --- | --- |\n| Alpha | First
Second |\n| Beta | Last |\n\nAfter.\n\n- [ ] A task\n'; + const reset = async () => { + await page.evaluate(source => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: 0 } }), source); + await page.locator('.live-writer table').waitFor(); + }; + const cell = (r, c) => page.locator('.live-writer table tr').nth(r).locator('th,td').nth(c); + for (const mode of ['dark', 'light']) { + await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode); + await reset(); + await cell(1, 1).click(); + await page.keyboard.press('Enter'); + await page.waitForFunction(() => document.activeElement?.closest('td')?.cellIndex === 1 && document.activeElement.closest('tr').rowIndex === 2); + await page.keyboard.press('Enter'); + await page.waitForFunction(() => document.activeElement?.closest('td')?.cellIndex === 1 && document.activeElement.closest('tr').rowIndex === 3); + assert.equal(await page.locator('.live-writer table tr').count(), 4); + await page.keyboard.type('New'); + await page.keyboard.press('Shift+Enter'); + await page.keyboard.type('Line'); + assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /New
Line/); + await page.screenshot({ path: `output/october15-editor/${mode}-table-enter.png` }); + await reset(); + await cell(0, 0).click(); + await page.keyboard.press('Shift+F10'); + await page.getByRole('menuitem', { name: 'Select cell', exact: true }).click(); + await page.keyboard.press('Shift+ArrowRight'); + await page.keyboard.press('Shift+ArrowDown'); + const copied = await page.locator('.writer-table').evaluate(node => { + const data = new DataTransfer(); + node.dispatchEvent(new ClipboardEvent('copy', { clipboardData: data, bubbles: true, cancelable: true })); + return { html: data.getData('text/html'), text: data.getData('text/plain') }; + }); + assert.match(copied.html, //); + assert.match(copied.text, /Name\tNotes/); + await page.evaluate(() => { + const view = window.__CM__; + const anchor = view.state.sliceDoc().indexOf('After.'); + view.dispatch({ selection: { anchor } }); view.focus(); + }); + await page.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate((node, copied) => { + const data = new DataTransfer(); data.setData('text/html', copied.html); data.setData('text/plain', copied.text); + node.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true })); + }, copied); + assert.equal(await page.locator('.live-writer table').count(), 2); + assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /First
Second/); + await page.screenshot({ path: `output/october15-editor/${mode}-table-paste.png` }); + await reset(); + await page.evaluate(() => { + const view = window.__CM__; + view.dispatch({ selection: { anchor: view.state.sliceDoc().indexOf('A task') + 3 } }); view.focus(); + }); + assert.equal(await page.locator('.writer-checkbox').count(), 1); + await page.screenshot({ path: `output/october15-editor/${mode}-checklist-text.png` }); + await page.evaluate(() => { + const view = window.__CM__; + view.dispatch({ selection: { anchor: view.state.sliceDoc().indexOf('[ ]') + 1 } }); view.focus(); + }); + assert.equal(await page.locator('.writer-checkbox').count(), 0); + await page.screenshot({ path: `output/october15-editor/${mode}-checklist-source.png` }); + await page.getByRole('button', { name: 'Rename note', exact: true }).click(); + await page.getByRole('textbox', { name: 'Note filename', exact: true }).press('Tab'); + await page.waitForFunction(() => document.activeElement?.classList.contains('cm-content')); + await page.screenshot({ path: `output/october15-editor/${mode}-title-tab.png` }); + await page.setViewportSize({ width: 600, height: 760 }); + await reset(); + await page.screenshot({ path: `output/october15-editor/${mode}-narrow.png` }); + await page.setViewportSize({ width: 1440, height: 1000 }); + } + assert.deepEqual(errors, []); + console.log('PASS: Enter advances and creates rows in the same column, Shift+Enter, table clipboard with line breaks, task marker editing, title Tab, both themes and narrow layouts.'); +} catch (error) { + await page.screenshot({ path: 'output/october15-editor/failure.png' }); + throw error; +} finally { await browser.close(); } diff --git a/scripts/pluginAccess.smoke.mjs b/scripts/pluginAccess.smoke.mjs index a9e172f..7eadacd 100644 --- a/scripts/pluginAccess.smoke.mjs +++ b/scripts/pluginAccess.smoke.mjs @@ -35,7 +35,9 @@ await context.addInitScript(() => { }}); }`, "org.example.tasks": `export function activate(api) { - api.registerView({ id: 'tasks', title: 'All tasks', icon: 'list', navigation: true, placement: 'editor', mount(container) { container.textContent = 'Task content'; } }); + api.registerView({ id: 'tasks', title: 'All tasks', icon: 'list', navigation: true, placement: 'editor', launch() { api.openView('default-board'); }, mount(container) { container.textContent = 'Task content'; } }); + api.registerView({ id: 'default-board', title: 'Default board', launcher: false, placement: 'editor', mount(container) { container.textContent = 'Default board content'; } }); + window.taskTestApi = api; api.registerView({ id: 'dialog', title: 'Task summary', mount(container) { container.textContent = 'Task summary content'; } }); }`, }; @@ -72,6 +74,17 @@ try { assert.equal(await main.getByRole('button', { name: 'Open tab or view', exact: true }).count(), 0); assert.equal(await main.getByRole('button', { name: 'Commands', exact: true }).count(), 1); await main.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'All tasks', exact: true }).click(); + await main.getByText('Default board content', { exact: true }).waitFor(); + await main.evaluate(() => window.taskTestApi.openView('tasks')); + await main.getByText('Task content', { exact: true }).waitFor(); + await main.evaluate(async () => { + const { closePluginEditor, pluginTabState, pluginView, restorePluginTab } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); + let view; + const off = pluginView.subscribe(value => { view = value; }); off(); + const transfer = pluginTabState(view); + closePluginEditor(view.key); + if (!await restorePluginTab(transfer)) throw Error('Tab restore failed'); + }); await main.getByText('Task content', { exact: true }).waitFor(); await main.evaluate(async () => { const { runPluginCommand } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); diff --git a/scripts/pluginFind.smoke.mjs b/scripts/pluginFind.smoke.mjs new file mode 100644 index 0000000..e47acca --- /dev/null +++ b/scripts/pluginFind.smoke.mjs @@ -0,0 +1,176 @@ +// Run against the host development server with PLAYWRIGHT_MODULE set when needed. +import { createRequire } from 'node:module'; +import assert from 'node:assert/strict'; +import { mkdir, readFile } 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 = []; +page.on('pageerror', error => errors.push(error.message)); +const output = '.audit/host-privacy-find'; +await mkdir(output, { recursive: true }); +const pm = { + manifest: JSON.parse(await readFile(new URL('../../RuneStone_Project_Management/dist/plugin/plugin.json', import.meta.url), 'utf8')), + code: await readFile(new URL('../../RuneStone_Project_Management/dist/plugin/main.js', import.meta.url), 'utf8'), +}; +await page.addInitScript(({ pm }) => { + window.isTauri = true; + const files = new Map([['untitled.md', '# Existing note\n'], ['sample.finddoc', 'Alpha alpha alphabet']]); + files.set('Board.md', '---\nrunestone_pm:\n schema: 1\n kind: board\n id: host-find-board\n lists:\n - {id: todo, name: To do, status: todo, collapsed: false}\n - {id: doing, name: In progress, status: doing, collapsed: false}\n - {id: done, name: Done, status: done, collapsed: false}\n defaults: {todo: todo, doing: doing, done: done}\n---\n'); + const callbacks = new Map(), listeners = new Map(); + let sequence = 0; + const manifest = { schemaVersion: 1, id: 'test.find', name: 'Find test', author: 'Test', description: 'Search checks', version: '1.0.0', apiVersion: 1, entry: 'main.js', access: 'full-app' }; + const code = `export function activate(api) { + api.registerDocumentType({ id: 'document', title: 'Test document', extensions: ['finddoc'], identify: path => ({ id: path }), mount(root) { + root.innerHTML = '

Test document

Alpha alpha alphabet

'; + }}); + for (const name of ['Board', 'Changes']) api.registerView({ id: name.toLowerCase(), title: name, placement: 'editor', navigation: true, icon: 'list', mount(root) { + root.innerHTML = '

' + name + '

Alpha alpha alphabet

'; + }}); + api.registerView({ id: 'native', title: 'Custom find', placement: 'editor', navigation: true, find() { window.customFindCalls = (window.customFindCalls || 0) + 1; }, mount(root) { root.innerHTML = '

Native content

'; } }); + }`; + 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 = {}) => { + if (command === 'plugin:event|listen') { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; } + if (command === 'plugin:event|unlisten') return; + if (command === 'workspace_last_path') return 'C:/find-test'; + if (command === 'workspace_open') return { root: 'C:/find-test', name: 'find-test', watch_mode: 'native' }; + if (command === 'workspace_list') return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: 'file' })); + if (command === 'workspace_read') { if (!files.has(args.rel) && args.missingOk) return null; if (!files.has(args.rel)) throw Error('Missing file'); return files.get(args.rel); } + if (command === 'workspace_list_markdown') return [...files.keys()].filter(path => !path.startsWith('.') && path.endsWith('.md')); + if (command === 'workspace_read_many') return args.paths.map(path => ({ path, source: files.get(path) })); + if (command === 'workspace_create') { if (files.has(args.rel)) throw Error('File exists'); files.set(args.rel, ''); return; } + if (command === 'workspace_write') { files.set(args.rel, args.contents); return; } + if (command === 'plugins_snapshot') return { root: 'C:/test/plugins', plugins: [manifest, pm.manifest].map(item => ({ manifest: item, hash: item.id, enabled: true, path: 'C:/test/plugins/' + item.id, error: null, removal: false })) }; + if (command === 'plugins_load') return args.id === pm.manifest.id ? pm.code : code; + if (command === 'plugins_data') return 'null'; + if (command === 'browser_connect') return 'test'; + return null; + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} }; + window.__FILES__ = files; +}, { pm }); +try { + await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420'); + await page.locator('.ws').getByText('find-test', { exact: true }).waitFor(); + await page.getByRole('button', { name: 'Plug-in views', exact: true }).waitFor(); + const note = page.locator('.tree-tools').getByRole('button', { name: 'New note', exact: true }); + assert.equal(await page.locator('.tree-tools').getByRole('button', { name: 'New file', exact: true }).count(), 0); + await note.click(); + await page.waitForFunction(() => window.__FILES__.has('untitled 2.md')); + await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor(); + await page.getByRole('textbox', { name: 'Writing editor', exact: true }).click(); + await page.keyboard.press('Control+f'); + for (const label of ['Find in document', 'Replace with']) { + assert.equal(await page.getByRole('textbox', { name: label, exact: true }).getAttribute('autocomplete'), 'off'); + } + await page.keyboard.press('Escape'); + await page.screenshot({ path: `${output}/new-note-dark.png` }); + assert.equal(await page.getByRole('dialog').count(), 0, 'The note opens without a filename dialog'); + await note.click(); + await page.waitForFunction(() => window.__FILES__.has('untitled 3.md')); + 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 page.getByRole('tab', { name: 'untitled 3.md', exact: true }).click(); + await page.getByRole('textbox', { name: 'Writing editor', exact: true }).click(); + await page.keyboard.press('Control+f'); + const writerFind = page.getByRole('textbox', { name: 'Find in document', exact: true }); + await writerFind.fill('fift'); + assert.equal(await writerFind.getAttribute('autocomplete'), 'off'); + assert.equal(await page.getByRole('textbox', { name: 'Replace with', exact: true }).getAttribute('autocomplete'), 'off'); + await page.screenshot({ path: `${output}/find-privacy-${theme}.png` }); + await page.setViewportSize({ width: 650, height: 800 }); + await page.screenshot({ path: `${output}/find-privacy-${theme}-narrow.png` }); + await page.keyboard.press('Escape'); + await page.setViewportSize({ width: 1440, height: 1000 }); + await page.mouse.move(900, 400); + await note.hover(); + await page.getByRole('tooltip').filter({ hasText: /^New note$/ }).waitFor(); + await page.screenshot({ path: `${output}/new-note-tooltip-${theme}.png` }); + for (const name of ['Board', 'Changes']) { + await page.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name, exact: true }).click(); + const pane = page.getByRole('tabpanel', { name, exact: true }); + await pane.getByRole('button', { name: 'Details', exact: true }).focus(); + await page.keyboard.press('Control+f'); + assert.equal(await pane.locator('.rs-find-bar').count(), 0, 'Non-document plugin views do not show document Find'); + await page.screenshot({ path: `${output}/${name}-${theme}.png` }); + await page.setViewportSize({ width: 650, height: 800 }); + await page.keyboard.press('Control+f'); + assert.equal(await pane.locator('.rs-find-bar').count(), 0); + await page.screenshot({ path: `${output}/${name}-${theme}-narrow.png` }); + await page.setViewportSize({ width: 1440, height: 1000 }); + } + for (const surface of ['all-tasks', 'board-document']) { + if (surface === 'all-tasks') { + await page.getByRole('button', { name: 'Plug-in views', exact: true }).click(); + await page.getByRole('menuitem', { name: /^Project Management/ }).click(); + } else await page.getByRole('tree', { name: 'Workspace files' }).getByText('Board', { exact: true }).dblclick(); + const pane = page.locator('.plugin-editor-pane:visible'); + await pane.locator('.pm-board').waitFor(); + await pane.focus(); + await page.keyboard.press('Control+f'); + assert.equal(await pane.locator('.rs-find-bar').count(), 0, 'Actual PM views do not show host Find'); + await page.screenshot({ path: `${output}/pm-${surface}-${theme}.png` }); + await page.setViewportSize({ width: 650, height: 800 }); + await page.keyboard.press('Control+f'); + assert.equal(await pane.locator('.rs-find-bar').count(), 0); + await page.screenshot({ path: `${output}/pm-${surface}-${theme}-narrow.png` }); + await page.setViewportSize({ width: 1440, height: 1000 }); + } + await page.getByRole('tree', { name: 'Workspace files' }).getByText('sample', { exact: true }).dblclick(); + for (const name of ['sample']) { + const pane = page.getByRole('tabpanel', { name, exact: true }); + const returnButton = pane.getByRole('button', { name: 'Details', exact: true }); + await returnButton.focus(); + await page.keyboard.press('Control+f'); + const find = pane.getByRole('textbox', { name: 'Find in document', exact: true }); + assert.equal(await find.getAttribute('autocomplete'), 'off'); + await find.fill('Alpha'); + assert.equal(await page.locator('.rs-find-bar:visible').count(), 1); + assert.equal(await pane.getByRole('textbox', { name: 'Replace with' }).count(), 0); + await page.keyboard.press('Enter'); + assert.equal(await page.evaluate(() => getSelection().toString()), 'Alpha'); + await page.keyboard.press('F3'); + assert.equal(await page.evaluate(() => getSelection().toString()), 'alpha'); + await pane.getByText('Whole word', { exact: true }).click(); + await find.focus(); + const matches = []; + for (let i = 0; i < 4; i++) { + await page.keyboard.press('Enter'); + matches.push(await page.evaluate(() => ({ text: getSelection().toString(), button: !!getSelection().anchorNode?.parentElement?.closest('button') }))); + } + assert.equal(matches.filter(match => match.button).length, 1, 'Rendered card buttons participate in search'); + assert.ok(matches.every(match => /^alpha$/i.test(match.text))); + await page.screenshot({ path: `${output}/${name}-${theme}.png` }); + await page.setViewportSize({ width: 650, height: 800 }); + await page.screenshot({ path: `${output}/${name}-${theme}-narrow.png` }); + const bar = await pane.locator('.rs-find-bar').boundingBox(), bounds = await pane.boundingBox(); + assert.ok(bar.x >= bounds.x && bar.x + bar.width <= bounds.x + bounds.width + 1); + await page.getByRole('button', { name: 'Files', exact: true }).click(); + await page.getByRole('button', { name: 'Hide outline', exact: true }).click(); + await page.screenshot({ path: `${output}/${name}-${theme}-narrow-focused.png` }); + await find.focus(); + await page.keyboard.press('Escape'); + assert.equal(await returnButton.evaluate(node => node === 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('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'Custom find', exact: true }).click(); + await page.getByRole('tabpanel', { name: 'Custom find' }).focus(); + await page.keyboard.press('Control+f'); + assert.equal(await page.evaluate(() => window.customFindCalls), 1, 'Plugin find handlers retain ownership'); + assert.equal(await page.locator('.rs-find-bar:visible').count(), 0); + assert.deepEqual(errors, []); + console.log('PASS: Find privacy attributes, actual PM All Tasks and board scope, plugin document Find, custom handlers, focus, both themes, and narrow layouts'); +} catch (error) { + await page.screenshot({ path: `${output}/failure.png` }); + throw error; +} finally { await browser.close(); } diff --git a/scripts/pluginInstall.smoke.mjs b/scripts/pluginInstall.smoke.mjs index cc9d8c1..47c1f7c 100644 --- a/scripts/pluginInstall.smoke.mjs +++ b/scripts/pluginInstall.smoke.mjs @@ -57,7 +57,8 @@ await page.context().addInitScript(({ manifest, pluginCode }) => { } if (command === "plugins_cancel") { removalPrepared = false; return; } if (command === "plugins_install") { - installed = [{ manifest, hash: 'reviewed-hash', enabled: args.enabled, installedAt: Date.parse('2026-10-05T18:24:36Z'), path, error: null, removal: false }]; + const previous = installed[0]; + installed = [{ manifest, hash: 'reviewed-hash', enabled: previous ? previous.enabled : args.enabled, installedAt: Date.parse('2026-10-05T18:24:36Z'), path, error: null, removal: false }]; emit('plugins-changed', null); return [{ name: manifest.name, error: null }]; } if (command === "plugins_set_enabled") { @@ -167,14 +168,31 @@ try { assert.match(await settingsDialog.locator('time').innerText(), /Oct 5, 2026.*11:24:36 AM PDT/); await settingsPage.screenshot({ path: '.audit/plugin-manager-installed.png' }); await settingsPage.keyboard.press('Escape'); - await page.evaluate(async pluginId => { - const { runPluginCommand } = await import('/src/lib/plugins/external.ts'); - await runPluginCommand(pluginId, 'show-overview'); - }, manifest.id); + await page.getByRole('button', { name: 'Commands', exact: true }).click(); + await page.getByRole('menuitem', { name: /Show workspace overview/ }).click(); const view = page.getByRole('dialog', { name: 'Workspace overview', exact: true }); await view.getByText(/files and folders in this workspace/).waitFor(); await view.getByRole('button', { name: 'Close plugin view', exact: true }).click(); await settings(); + await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click(); + await review.getByText(/Update .* → .*Settings and enabled state stay the same/).waitFor(); + assert.equal(await review.getByRole('button', { name: 'Install and enable', exact: true }).count(), 0); + for (const mode of ['dark', 'light']) { + await settingsPage.evaluate(async mode => { + const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); + saveAppearance({ theme: 'default', mode }); + }, mode); + for (const width of [1440, 590]) { + await settingsPage.setViewportSize({ width, height: width === 590 ? 820 : 1000 }); + await settingsPage.screenshot({ path: `.audit/plugin-update-review-${mode}-${width}.png` }); + assert.equal(await review.evaluate(element => element.scrollWidth > element.clientWidth), false); + } + } + await review.getByRole('button', { name: 'Apply packages', exact: true }).click(); + assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked()); + assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true); + assert.equal(await count('plugins_remove'), 0); + await settingsPage.setViewportSize({ width: 1440, height: 1000 }); await uninstall(); const confirmation = settingsPage.getByRole('dialog', { name: 'Uninstall Workspace overview?', exact: true }); assert(await confirmation.getByRole('button', { name: 'Cancel', exact: true }).evaluate(el => el === document.activeElement)); @@ -213,4 +231,8 @@ try { assert.equal(await count('plugins_from_git'), 3); assert.deepEqual(errors, []); console.log('External plugin smoke passed: ZIP and Git-link review, download errors, token clearing, disabled installation, code loading, cancellation, focus, cleanup, and uninstall.'); +} catch (error) { + console.log('Main page:', await page.locator('body').innerText()); + console.log('Page errors:', errors); + throw error; } finally { await browser.close(); } diff --git a/scripts/pluginTranslation.spec.ts b/scripts/pluginTranslation.spec.ts deleted file mode 100644 index 50b167e..0000000 --- a/scripts/pluginTranslation.spec.ts +++ /dev/null @@ -1,35 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { locale } from '../src/lib/i18n/index.ts'; -import { pluginTranslation } from '../src/lib/plugins/translation.ts'; - -test('Plugin messages use the host language, explicit catalogs, and safe fallbacks', () => { - const api = pluginTranslation(() => {}, () => {}); - try { - locale.set('fr'); - assert.equal(api.locale, 'fr'); - assert.equal(api.t('Settings'), 'Paramètres'); - assert.equal(api.t('Column {name}', { name: 'User data' }, { fr: { 'Column {name}': 'Colonne {name}' } }), 'Colonne User data'); - assert.equal(api.t('Unknown {name}', { name: 'text' }), 'Unknown text'); - assert.equal(api.t('constructor'), 'constructor'); - assert.equal(api.t('Settings', {}, { fr: Object.create({ Settings: 'Inherited' }) }), 'Paramètres'); - } finally { locale.set('en'); } -}); - -test('Plugin language subscriptions stop at disposal and reject access after disable', () => { - const cleanup: (() => void)[] = [], languages: string[] = []; - let stopped = false; - const api = pluginTranslation(() => { if (stopped) throw new Error('Disabled'); }, off => cleanup.push(off)); - try { - api.subscribe(language => languages.push(language)); - locale.set('ja'); - assert.deepEqual(languages, ['en', 'ja']); - stopped = true; - for (const off of cleanup) off(); - locale.set('zh-CN'); - assert.deepEqual(languages, ['en', 'ja']); - assert.throws(() => api.locale, /Disabled/); - assert.throws(() => api.t('Settings'), /Disabled/); - assert.throws(() => api.subscribe(() => {}), /Disabled/); - } finally { locale.set('en'); } -}); diff --git a/scripts/tabOrder.smoke.mjs b/scripts/tabOrder.smoke.mjs index 84b994b..7448bb5 100644 --- a/scripts/tabOrder.smoke.mjs +++ b/scripts/tabOrder.smoke.mjs @@ -114,6 +114,9 @@ try { const bar = document.querySelector('[aria-label="Working tabs"]'); return bar.scrollLeft >= bar.scrollWidth - bar.clientWidth - 2; }); + // Native drag needs a fresh pointer event after the strip scrolls beneath it. + await page.mouse.move(bounds.x + bounds.width - 4, source.y + source.height / 2); + await page.mouse.move(bounds.x + bounds.width - 3, source.y + source.height / 2); await page.mouse.up(); await settle(); assert.equal((await order()).at(-1), "note-15.md"); diff --git a/scripts/tabTransfer.smoke.mjs b/scripts/tabTransfer.smoke.mjs new file mode 100644 index 0000000..9e66145 --- /dev/null +++ b/scripts/tabTransfer.smoke.mjs @@ -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 context = await browser.newContext({ viewport: { width: 1440, height: 900 } }); +await context.addInitScript(() => { + window.isTauri = true; + localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false })); + const root = location.search.includes("other") ? "C:\\other" : "C:\\transfer"; + let sequence = 0; + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, + transformCallback: () => ++sequence, unregisterCallback: () => {}, + invoke: async (command, args = {}) => { + if (command === "plugin:event|listen") return ++sequence; + if (command === "plugin:event|unlisten" || command.startsWith("plugin:window|")) return; + if (command === "workspace_last_path") return root; + if (command === "workspace_open") return { root, name: "transfer", watch_mode: "native" }; + if (command === "workspace_read") return "# " + args.rel + "\n\nOriginal text.\n"; + if (command === "workspace_list") return args.rel ? [] : ["a.md", "b.md"].map(name => ({ name, rel_path: name, kind: "file" })); + if (command === "workspace_search") return []; + if (command === "plugins_snapshot") return { root, plugins: [] }; + throw new Error(`Unhandled IPC: ${command}`); + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; +}); +const url = process.env.SMOKE_URL || "http://127.0.0.1:1420"; +const source = await context.newPage(), target = await context.newPage(), other = await context.newPage(); +for (const page of [source, target, other]) page.setDefaultTimeout(10000); +const errors = []; +for (const page of [source, target, other]) page.on("pageerror", error => errors.push(error.message)); +const tab = (page, name) => page.locator('[role="tab"]').filter({ hasText: name }); +async function open(page, name) { + await page.bringToFront(); + await page.getByRole("tablist", { name: "Working tabs" }).waitFor(); + await page.getByRole("tab").first().waitFor(); + await page.keyboard.press("Control+p"); + await page.getByRole("textbox", { name: "Find a file" }).fill(name); + await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click(); + await tab(page, name).waitFor(); +} +async function start(page, name) { + return tab(page, name).evaluate(node => { + const transfer = new DataTransfer(); + node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer })); + return transfer.getData("application/x-runestone-tab"); + }); +} +async function drop(page, data) { + await page.getByRole("tablist", { name: "Working tabs" }).evaluate((node, data) => { + const transfer = new DataTransfer(); + transfer.setData("application/x-runestone-tab", data); + node.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer })); + node.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer })); + }, data); +} +async function captureTransfer(page, data) { + await mkdir("output/tab-transfer", { recursive: true }); + for (const theme of ["light", "dark"]) { + await page.evaluate(async mode => { + const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); + await applyAppearance({ theme: 'default', mode }); + }, theme); + await page.getByRole("tablist", { name: "Working tabs" }).evaluate((node, data) => { + const transfer = new DataTransfer(); + transfer.setData("application/x-runestone-tab", data); + node.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer })); + }, data); + await page.screenshot({ path: `output/tab-transfer/${theme}-receiving.png` }); + } +} +try { + await Promise.all([source.goto(url), target.goto(url), other.goto(url + "/?other")]); + await open(source, "a.md"); + await open(target, "b.md"); + await tab(source, "a.md").click({ button: "right" }); + await source.getByRole("menuitem", { name: "Pin", exact: true }).click(); + await source.locator(".cm-content").fill("Unsaved transfer text"); + let data = await start(source, "a.md"); + assert.ok(JSON.parse(data).tabTransfer); + await drop(other, data); + await other.getByText("Move tabs only between windows of the same workspace.").waitFor(); + assert.equal(await tab(source, "a.md").count(), 1); + await captureTransfer(target, data); + await drop(target, data); + console.log("Dropped into matching workspace"); + await tab(target, "a.md").waitFor(); + await tab(source, "a.md").waitFor({ state: "detached" }); + console.log("Source acknowledged transfer"); + assert.match(await target.locator(".cm-content").innerText(), /Unsaved transfer text/); + const changedTarget = await context.newPage(); + changedTarget.on("pageerror", error => errors.push(error.message)); + await changedTarget.goto(url); + await changedTarget.getByRole("tab").first().waitFor(); + await open(source, "a.md"); + data = await start(source, "a.md"); + await source.locator(".cm-content").fill("Changed during transfer"); + await drop(changedTarget, data); + await tab(changedTarget, "a.md").waitFor(); + assert.equal(await tab(source, "a.md").count(), 1); + assert.match(await source.locator(".cm-content").innerText(), /Changed during transfer/); + assert.ok(await tab(target, "a.md").getAttribute("aria-describedby")); + assert.deepEqual(await target.getByRole("tablist", { name: "Working tabs" }).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)), ["a.md", "b.md"]); + await open(source, "a.md"); + data = await start(source, "a.md"); + await drop(target, data); + await target.getByText("This tab is already open in this window. The source tab remains open.").waitFor(); + assert.equal(await tab(source, "a.md").count(), 1); + assert.match(await target.locator(".cm-content").innerText(), /Unsaved transfer text/); + await mkdir("output/tab-transfer", { recursive: true }); + for (const theme of ["light", "dark"]) { + await target.evaluate(async mode => { + const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); + await applyAppearance({ theme: 'default', mode }); + }, theme); + await target.screenshot({ path: `output/tab-transfer/${theme}.png` }); + } + await target.setViewportSize({ width: 700, height: 700 }); + await target.screenshot({ path: "output/tab-transfer/narrow.png" }); + assert.deepEqual(errors, []); + console.log("PASS: same-workspace transfer, unsaved text, pinned state, insertion order, other-workspace rejection, duplicate protection, and source edits during transfer"); +} catch (reason) { + console.log(await other.locator("body").innerText()); + console.log(await target.locator("body").innerText()); + throw reason; +} finally { await browser.close(); } diff --git a/scripts/tableNavigation.smoke.mjs b/scripts/tableNavigation.smoke.mjs index 3af2b4a..d5094c8 100644 --- a/scripts/tableNavigation.smoke.mjs +++ b/scripts/tableNavigation.smoke.mjs @@ -357,7 +357,7 @@ try { }, tallSource); await quickOpen('line-breaks.md'); await table.waitFor(); - for (const [r, c, key] of [[1, 0, 'Shift+Enter'], [20, 0, 'Shift+Enter'], [21, 0, 'Enter'], [20, 0, 'Shift+Enter'], [20, 1, 'Shift+Enter'], [0, 0, 'Shift+Enter']]) { + for (const [r, c, key] of [[1, 0, 'Shift+Enter'], [20, 0, 'Shift+Enter'], [21, 0, 'Shift+Enter'], [20, 0, 'Shift+Enter'], [20, 1, 'Shift+Enter'], [0, 0, 'Shift+Enter']]) { await at(r, c); const before = await page.locator('.live-writer .cm-scroller').evaluate(el => el.scrollTop); await page.keyboard.press(key); diff --git a/scripts/tableSelection.spec.ts b/scripts/tableSelection.spec.ts index e3e5c4f..64c4af2 100644 --- a/scripts/tableSelection.spec.ts +++ b/scripts/tableSelection.spec.ts @@ -1,12 +1,24 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { alignTableCells, clipboardCells, copyTableCells, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells } from "../src/lib/editor/tableSelection.ts"; +import { alignTableCells, clipboardCells, copyTableCells, copyTableMarkdown, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells } from "../src/lib/editor/tableSelection.ts"; +import { htmlToMarkdown } from "../src/lib/workspace/htmlToMarkdown.ts"; import { parseMarkdownTable } from "../src/lib/editor/markdownTable.ts"; import { renderMarkdownHtml, plainInlineMarkdown } from "../src/lib/workspace/noteHtml.ts"; import { tableCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts"; const source = "| A | B | C |\r\n| --- | :---: | ---: |\r\n| one | two | three |\r\n| four | five | six |\r\n\r\nTail"; const range = { anchor: { row: 2, column: 1 }, head: { row: 1, column: 0 } }; +test("selected cells retain table structure and line breaks through HTML clipboard", () => { + const source = "| Name | Notes |\n| --- | --- |\n| **Alpha** | First
Second |"; + const range = { anchor: { row: 0, column: 0 }, head: { row: 1, column: 1 } }; + const copied = copyTableMarkdown(source, range); + const pasted = htmlToMarkdown(renderMarkdownHtml(copied, new Map())); + const table = parseMarkdownTable(pasted)!; + assert.equal(table.columns, 2); + assert.equal(table.rows.length, 3); + assert.equal(table.rows[2].cells[0].text, "**Alpha**"); + assert.equal(table.rows[2].cells[1].text, "First
Second"); +}); test("reversed rectangular selections only change selected cells and preserve CRLF", () => { const changed = formatTableCells(source, range, "bold"); assert.equal(changed, source.replace("one", "**one**").replace("two", "**two**").replace("four", "**four**").replace("five", "**five**")); diff --git a/scripts/unifiedFind.smoke.mjs b/scripts/unifiedFind.smoke.mjs new file mode 100644 index 0000000..5be4ff0 --- /dev/null +++ b/scripts/unifiedFind.smoke.mjs @@ -0,0 +1,200 @@ +// 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 = []; +const output = ".audit/todo-2026-10-14/unified-find"; +await mkdir(output, { 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 === "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 }; +}); + +const sample = "# Alpha\n\nAlpha alpha alphabet\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n| Beta | Two |\n\nLast Alpha paragraph.\n"; +const find = page.getByRole("textbox", { name: "Find in document", exact: true }); +const replace = page.getByRole("textbox", { name: "Replace with", exact: true }); +async function mode(group, value) { + await page.getByRole("group", { name: group, exact: true }).hover(); + await page.getByRole("button", { name: value, exact: true }).click(); +} +async function onePanel() { + assert.equal(await page.locator('.rs-find-bar:visible').count(), 1); + assert.equal(await page.locator('.find-widget.visible').count(), 0, 'No Monaco floating find widget'); + const bar = await page.locator('.rs-find-bar:visible').boundingBox(); + const pane = await page.locator('.editor.pane-active').boundingBox(); + assert.ok(Math.abs(bar.width - pane.width) < 3, 'Find spans the document pane'); +} +async function sourceEditor() { + await page.waitForFunction(() => !!document.querySelector('.monaco-editor')); + return page.evaluate(async () => { + const { monaco } = await import('/src/lib/editor/monacoEnv.ts'); + window.__MONACO__ = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected && view.getDomNode().getBoundingClientRect().width > 0); + window.__MONACO__.focus(); + }); +} +try { + 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(); + for (const theme of ['dark', 'light']) { + await page.evaluate(async theme => { + const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); + saveAppearance({ theme: 'default', mode: theme }); + }, theme); + await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor(); + await page.evaluate(async sample => { + const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js'); + window.__CM__ = EditorView.findFromDOM(document.querySelector('.live-writer > .cm-editor .cm-content')); + window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: sample }, selection: { anchor: 0 } }); + window.__CM__.focus(); + }, sample); + await page.keyboard.press('Control+f'); + await find.fill('Alpha'); + await onePanel(); + await page.screenshot({ path: `${output}/writer-${theme}.png` }); + await page.keyboard.press('Escape'); + await page.locator('.live-writer td').first().dblclick(); + await page.locator('.writer-cell-editor').waitFor(); + await page.keyboard.press('Control+f'); + await onePanel(); + assert.equal(await find.evaluate(node => node === document.activeElement), true, 'Table focus opens the document find'); + assert.equal(await page.locator('.writer-cell-editor .rs-find-bar').count(), 0); + await find.fill('Last Alpha'); + await page.keyboard.press('Enter'); + assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc(window.__CM__.state.selection.main.from, window.__CM__.state.selection.main.to)), /Last Alpha/); + await page.screenshot({ path: `${output}/table-focus-${theme}.png` }); + await page.keyboard.press('Escape'); + await mode('Editor layout', 'IDE'); + await sourceEditor(); + await page.evaluate(() => { window.__MONACO__.getModel().setValue('Alpha alpha alphabet\r\nAlpha second\r\nAlpha third'); window.__MONACO__.setPosition({ lineNumber: 1, column: 1 }); }); + await page.keyboard.press('Control+f'); + await find.fill('Alpha'); + await onePanel(); + await page.keyboard.press('Enter'); + const first = await page.evaluate(() => window.__MONACO__.getSelection().toString()); + await page.keyboard.press('Enter'); + assert.notEqual(await page.evaluate(() => window.__MONACO__.getSelection().toString()), first); + await page.keyboard.press('Shift+Enter'); + assert.equal(await page.evaluate(() => window.__MONACO__.getSelection().toString()), first); + await page.getByRole('checkbox', { name: 'Match case' }).check(); + await page.getByRole('checkbox', { name: 'Whole word' }).check(); + await replace.fill('Gamma'); + await page.getByRole('button', { name: 'Replace all', exact: true }).click(); + assert.equal(await page.evaluate(() => window.__MONACO__.getValue().replace(/\r\n/g, '\n')), 'Gamma alpha alphabet\nGamma second\nGamma third'); + await page.getByRole('checkbox', { name: 'Regex' }).check(); + await find.fill('['); + assert.equal(await find.getAttribute('aria-invalid'), 'true'); + assert.equal(await page.getByRole('button', { name: 'Replace all', exact: true }).isDisabled(), true); + await find.fill('(?<=G)(amma)'); + await page.getByRole('checkbox', { name: 'Whole word' }).uncheck(); + await replace.fill('$1!'); + await page.getByRole('button', { name: 'Replace all', exact: true }).click(); + assert.match(await page.evaluate(() => window.__MONACO__.getValue()), /^Gamma! alpha/); + await page.getByRole('checkbox', { name: 'Regex' }).uncheck(); + await find.fill('Gamma'); + await page.getByRole('button', { name: 'Select all', exact: true }).click(); + assert.equal(await page.evaluate(() => window.__MONACO__.getSelections().length), 3); + await page.screenshot({ path: `${output}/source-${theme}.png` }); + await find.focus(); await page.keyboard.press('Escape'); + assert.equal(await find.count(), 0); + assert.equal(await page.evaluate(() => window.__MONACO__.hasTextFocus()), true); + await page.keyboard.press('Control+h'); + assert.equal(await replace.evaluate(node => node === document.activeElement), true); + await find.fill('Gamma'); + await page.keyboard.press('Enter'); + await page.keyboard.press('F3'); + await page.screenshot({ path: `${output}/source-replace-${theme}.png` }); + await page.setViewportSize({ width: 800, height: 700 }); + await onePanel(); + assert.equal(await page.locator('.rs-find-bar').evaluate(node => node.scrollWidth <= node.clientWidth), true); + await page.screenshot({ path: `${output}/source-narrow-${theme}.png` }); + await page.setViewportSize({ width: 1440, height: 1000 }); + await find.focus(); await page.keyboard.press('Escape'); + await page.evaluate(sample => window.__MONACO__.getModel().setValue(sample), sample); + await mode('Document view', 'Read'); + await page.locator('.reading').focus(); + await page.keyboard.press('Control+f'); + await find.fill('Alpha'); await page.keyboard.press('Enter'); + await onePanel(); + assert.equal(await replace.count(), 0, 'Reading search does not offer replacement'); + assert.equal(await page.evaluate(() => window.getSelection().toString()), 'Alpha'); + const anchor = await page.evaluate(() => window.getSelection().anchorNode.parentElement.outerHTML); + await page.keyboard.press('Enter'); + assert.notEqual(await page.evaluate(() => window.getSelection().anchorNode.parentElement.outerHTML), anchor); + await page.screenshot({ path: `${output}/reading-${theme}.png` }); + await page.keyboard.press('Escape'); + assert.equal(await page.locator('.reading').evaluate(node => node === document.activeElement), true); + await mode('Document view', 'Edit'); + await mode('Editor layout', 'Writer'); + } + assert.deepEqual(errors, []); + console.log('PASS: one full-width document Find in Writer, nested table focus, IDE/source, and Reading, with replacement, regex, CRLF, focus return, both themes, and narrow controls.'); +} catch (error) { + console.error('Browser errors:', errors); + await page.screenshot({ path: `${output}/failure.png` }); + throw error; +} finally { await browser.close(); } diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index d0815e2..8aeaf46 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -3130,7 +3130,7 @@ dependencies = [ [[package]] name = "runestone" -version = "0.1.36" +version = "0.1.41" dependencies = [ "base64 0.23.1", "dunce", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 337d007..b9fdccd 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "runestone" -version = "0.1.36" +version = "0.1.41" description = "Writing workspace plus script editor" authors = ["you"] edition = "2021" @@ -44,4 +44,4 @@ panic = "abort" strip = true [package.metadata.runestone] -version = "0.1.36" +version = "0.1.41" diff --git a/src-tauri/src/plugins.rs b/src-tauri/src/plugins.rs index 5047112..85853c2 100644 --- a/src-tauri/src/plugins.rs +++ b/src-tauri/src/plugins.rs @@ -85,6 +85,14 @@ struct Candidate { hash: String, manifest: Manifest, created: Instant, + previous: Option, +} +#[derive(Serialize, Deserialize)] +struct UpdateJournal { + previous: Installed, + next_hash: String, + backup: String, + staged: String, } #[derive(Clone, Serialize)] pub struct RemovalPlan { @@ -456,6 +464,7 @@ impl Service { cleanup_errors: BTreeMap::new(), removing: BTreeMap::new(), }; + service.recover_updates()?; let mut recovered = false; for (id, record) in &mut service.catalog.plugins { if let Some(token) = &record.removal { @@ -474,6 +483,48 @@ impl Service { } Ok(service) } + fn recover_updates(&mut self) -> Result<()> { + let staging = self.directory("plugin-staging")?; + for entry in fs::read_dir(&staging).map_err(fail)? { + let entry = entry.map_err(fail)?; + let name = entry.file_name().to_string_lossy().into_owned(); + if !name.starts_with("update-") || !name.ends_with(".json") { continue; } + let journal: UpdateJournal = serde_json::from_slice(&bounded(&entry.path(), 128 * 1024)?).map_err(fail)?; + let id = journal.previous.manifest.id.clone(); + if !valid_id(&id) { return Err("Invalid plugin update journal.".into()); } + Uuid::parse_str(&journal.backup).map_err(fail)?; + Uuid::parse_str(&journal.staged).map_err(fail)?; + let target = self.directory("plugins")?.join(&id); + let backup = staging.join(&journal.backup); + let staged = staging.join(&journal.staged); + let committed = self.catalog.plugins.get(&id).is_some_and(|record| record.hash == journal.next_hash) + && package(&target).is_ok_and(|current| current.hash == journal.next_hash); + if backup.exists() { + safe_child(&staging, &backup)?; + if package(&backup)?.hash != journal.previous.hash { return Err("The plugin update backup changed.".into()); } + if committed { erase(&staging, &backup)?; } + else { + if target.exists() { + safe_child(&self.directory("plugins")?, &target)?; + if package(&target)?.hash != journal.next_hash || staged.exists() { + return Err("Plugin update recovery requires inspection of the staging directory.".into()); + } + fs::rename(&target, &staged).map_err(fail)?; + } + fs::rename(&backup, &target).map_err(fail)?; + } + } + if !committed { + if package(&target)?.hash != journal.previous.hash { return Err("The previous plugin package changed.".into()); } + let mut previous = journal.previous; + previous.enabled = false; + self.catalog.plugins.insert(id.clone(), previous); + self.persist()?; + } + erase(&staging, &entry.path())?; + } + Ok(()) + } fn directory(&self, name: &str) -> Result { let path = self.root.join(name); safe_child(&self.root, &path)?; @@ -594,13 +645,14 @@ impl Service { let display = source.to_string_lossy().into_owned(); let result = (|| { let current = package(&source)?; - if self.catalog.plugins.contains_key(¤t.manifest.id) - || self - .directory("plugins")? - .join(¤t.manifest.id) - .exists() - { - return Err("This plugin ID is already installed. Uninstall it before installing another version.".into()); + let previous = self.catalog.plugins.get(¤t.manifest.id).cloned(); + if let Some(record) = &previous { + let row = self.row(¤t.manifest.id)?; + if row.error.is_some() || record.removal.is_some() || self.removing.contains_key(¤t.manifest.id) { + return Err("Finish plugin cleanup before updating it.".into()); + } + } else if self.directory("plugins")?.join(¤t.manifest.id).exists() { + return Err("Refresh the plugin list before installing this package.".into()); } let staging = self.directory("plugin-staging")?.join(&token); fs::create_dir(&staging).map_err(fail)?; @@ -630,6 +682,7 @@ impl Service { hash: current.hash, manifest: manifest.clone(), created: Instant::now(), + previous, }, ); Ok(manifest) @@ -682,6 +735,9 @@ impl Service { return Err("The package review expired. Select it again.".into()); } let id = candidate.manifest.id.clone(); + if candidate.previous.is_some() { + return self.update(owner, token); + } if self.catalog.plugins.contains_key(&id) { return Err("This plugin ID is already installed.".into()); } @@ -731,6 +787,82 @@ impl Service { } Ok(candidate.manifest.name) } + fn begin_update(&mut self, owner: &str, token: &str) -> Result> { + let candidate = self.candidates.get(token).ok_or("Select the package again.")?; + if candidate.owner != owner || candidate.created.elapsed() > Duration::from_secs(1800) { + return Err("The package review expired. Select it again.".into()); + } + let Some(previous) = &candidate.previous else { return Ok(None); }; + let id = candidate.manifest.id.clone(); + let current = self.catalog.plugins.get(&id).ok_or("The installed plugin changed. Select the package again.")?; + if current.hash != previous.hash || current.enabled != previous.enabled || current.removal.is_some() + || self.removing.contains_key(&id) || self.cleanup_errors.contains_key(&id) + || package(&self.directory("plugins")?.join(&id))?.hash != previous.hash { + return Err("The installed plugin changed. Refresh and select the package again.".into()); + } + self.catalog.plugins.get_mut(&id).unwrap().enabled = false; + if let Err(error) = self.persist() { + self.catalog.plugins.get_mut(&id).unwrap().enabled = previous.enabled; + return Err(error); + } + self.removing.insert(id.clone(), previous.hash.clone()); + Ok(Some(id)) + } + fn update(&mut self, owner: &str, token: &str) -> Result { + let candidate = self.candidates.get(token).ok_or("Select the package again.")?; + if candidate.owner != owner || candidate.created.elapsed() > Duration::from_secs(1800) { + return Err("The package review expired. Select it again.".into()); + } + let previous = candidate.previous.clone().ok_or("The plugin update is unavailable.")?; + let id = candidate.manifest.id.clone(); + if self.removing.get(&id) != Some(&previous.hash) { + return Err("Start the plugin update again.".into()); + } + if self.leases.get(&id).is_some_and(|windows| !windows.is_empty()) || self.cleanup_errors.contains_key(&id) { + return Err("Plugin cleanup did not finish. Close other RuneStone windows and retry the update.".into()); + } + if candidate.source.as_ref().map(|source| package(source)).transpose()?.is_some_and(|source| source.hash != candidate.hash) + || package(&candidate.directory)?.hash != candidate.hash { + return Err("The package changed after review. Select it again.".into()); + } + let parent = self.directory("plugins")?; + let target = parent.join(&id); + safe_child(&parent, &target)?; + if package(&target)?.hash != previous.hash { + return Err("Plugin files changed during shutdown. Select the package again.".into()); + } + let staging = self.directory("plugin-staging")?; + safe_child(&staging, &candidate.directory)?; + let backup = staging.join(uid()); + let journal_path = staging.join(format!("update-{}.json", uid())); + let journal = UpdateJournal { previous: previous.clone(), next_hash: candidate.hash.clone(), + backup: backup.file_name().unwrap().to_string_lossy().into_owned(), + staged: candidate.directory.file_name().unwrap().to_string_lossy().into_owned() }; + fs::write(&journal_path, serde_json::to_vec(&journal).map_err(fail)?).map_err(fail)?; + fs::rename(&target, &backup).map_err(fail)?; + if let Err(error) = fs::rename(&candidate.directory, &target) { + fs::rename(&backup, &target).map_err(fail)?; + let _ = erase(&staging, &journal_path); + return Err(fail(error)); + } + self.catalog.plugins.insert(id.clone(), Installed { + manifest: candidate.manifest.clone(), hash: candidate.hash.clone(), enabled: previous.enabled, + installed_at: Some(SystemTime::now().duration_since(UNIX_EPOCH).map_err(fail)?.as_millis() as u64), + removal: None, removal_files: BTreeMap::new(), + }); + if let Err(error) = self.persist() { + fs::rename(&target, &candidate.directory).map_err(fail)?; + fs::rename(&backup, &target).map_err(fail)?; + self.catalog.plugins.insert(id, previous); + let _ = erase(&staging, &journal_path); + return Err(error); + } + let name = self.candidates.remove(token).unwrap().manifest.name; + // The backup contains only the exact package approved before shutdown. + if package(&backup).is_ok_and(|old| old.hash == previous.hash) { let _ = erase(&staging, &backup); } + let _ = erase(&staging, &journal_path); + Ok(name) + } fn prepare(&mut self, owner: &str, id: &str) -> Result { if self.removing.contains_key(id) { return Err("This plugin is already being removed.".into()); @@ -1004,24 +1136,42 @@ pub async fn plugins_install( tokens: Vec, enabled: bool, ) -> Result> { - let result = state.with(&app, |service| { - Ok(tokens - .iter() - .map(|token| { - let name = service - .candidates - .get(token) - .map(|c| c.manifest.name.clone()) - .unwrap_or_else(|| "Plugin".into()); - InstallResult { - name, - error: service.install(window.label(), token, enabled).err(), + let mut result = Vec::new(); + for token in tokens { + let name = state.with(&app, |service| Ok(service.candidates.get(&token) + .map(|candidate| candidate.manifest.name.clone()).unwrap_or_else(|| "Plugin".into())))?; + let updating = state.with(&app, |service| service.begin_update(window.label(), &token)); + let error = match updating { + Err(error) => Some(error), + Ok(id) => { + if let Some(id) = &id { + changed(&app); + let start = Instant::now(); + while state.with(&app, |service| Ok(service.leases.get(id).is_some_and(|windows| !windows.is_empty())))? + && start.elapsed() < Duration::from_secs(10) { + tauri::async_runtime::spawn_blocking(|| std::thread::sleep(Duration::from_millis(50))).await.map_err(fail)?; + } } - }) - .collect()) - }); + let installed = state.with(&app, |service| { + let installed = service.install(window.label(), &token, enabled); + if let Some(id) = &id { + service.removing.remove(id); + if installed.is_err() { + if let Some(previous) = service.candidates.get(&token).and_then(|candidate| candidate.previous.clone()) { + if let Some(record) = service.catalog.plugins.get_mut(id) { record.enabled = previous.enabled; } + service.persist()?; + } + } + } + installed + }); + installed.err() + } + }; + result.push(InstallResult { name, error }); + } changed(&app); - result + Ok(result) } #[tauri::command] pub async fn plugins_set_enabled( @@ -1427,6 +1577,80 @@ mod tests { f.install(true); assert!(f.service.row(&id).unwrap().installed_at.unwrap() >= installed_at); } + + #[test] + fn reviewed_update_keeps_settings_and_enabled_state_and_replaces_files() { + for enabled in [false, true] { + let mut f = Fixture::new(); + let id = f.install(enabled); + let settings = f.service.directory("plugin-data").unwrap().join(format!("{id}.json")); + fs::write(&settings, r#"{"keep":true}"#).unwrap(); + let manifest = fs::read_to_string(f.source.join("plugin.json")).unwrap().replace("1.0.0", "1.0.1"); + fs::write(f.source.join("plugin.json"), manifest).unwrap(); + fs::write(f.source.join("main.js"), "export function activate() { /* update */ }").unwrap(); + let candidate = f.service.inspect("main", f.source.clone()); + assert!(candidate.error.is_none(), "{:?}", candidate.error); + assert!(f.service.begin_update("other", &candidate.token).is_err()); + assert_eq!(f.service.begin_update("main", &candidate.token).unwrap(), Some(id.clone())); + assert!(!f.service.row(&id).unwrap().enabled); + f.service.install("main", &candidate.token, !enabled).unwrap(); + f.service.removing.remove(&id); + let row = f.service.row(&id).unwrap(); + assert_eq!(row.manifest.version, "1.0.1"); + assert_eq!(row.enabled, enabled); + assert!(row.error.is_none()); + assert_eq!(fs::read_to_string(&settings).unwrap(), r#"{"keep":true}"#); + assert_eq!(Service::open(f.root.join("app")).unwrap().row(&id).unwrap().manifest.version, "1.0.1"); + } + } + + #[test] + fn update_waits_for_cleanup_and_rejects_changed_packages() { + let mut f = Fixture::new(); + let id = f.install(true); + let candidate = f.service.inspect("main", f.source.clone()); + f.service.leases.entry(id.clone()).or_default().insert("main".into()); + f.service.begin_update("main", &candidate.token).unwrap(); + assert!(f.service.install("main", &candidate.token, true).unwrap_err().contains("cleanup")); + f.service.leases.clear(); + fs::write(f.source.join("main.js"), "changed after review").unwrap(); + assert!(f.service.install("main", &candidate.token, true).unwrap_err().contains("changed after review")); + assert_eq!(f.service.row(&id).unwrap().manifest.version, "1.0.0"); + assert_eq!(fs::read_to_string(f.service.directory("plugins").unwrap().join(&id).join("main.js")).unwrap(), "export function activate() {}"); + } + + #[test] + fn interrupted_update_restores_previous_package_until_commit() { + for phase in 0..4 { + let mut f = Fixture::new(); + let id = f.install(true); + let previous = f.service.catalog.plugins[&id].clone(); + let manifest = fs::read_to_string(f.source.join("plugin.json")).unwrap().replace("1.0.0", "1.0.1"); + fs::write(f.source.join("plugin.json"), manifest).unwrap(); + let row = f.service.inspect("main", f.source.clone()); + f.service.begin_update("main", &row.token).unwrap(); + let candidate = &f.service.candidates[&row.token]; + let journal = UpdateJournal { previous, next_hash: candidate.hash.clone(), backup: uid(), staged: row.token.clone() }; + let staging = f.service.directory("plugin-staging").unwrap(); + fs::write(staging.join(format!("update-{}.json", uid())), serde_json::to_vec(&journal).unwrap()).unwrap(); + let target = f.service.directory("plugins").unwrap().join(&id); + if phase >= 1 { fs::rename(&target, staging.join(&journal.backup)).unwrap(); } + if phase >= 2 { fs::rename(&candidate.directory, &target).unwrap(); } + if phase == 3 { + let record = f.service.catalog.plugins.get_mut(&id).unwrap(); + record.manifest = candidate.manifest.clone(); + record.hash = candidate.hash.clone(); + record.enabled = true; + f.service.persist().unwrap(); + } + let recovered = Service::open(f.root.join("app")).unwrap(); + let row = recovered.row(&id).unwrap(); + assert!(row.error.is_none()); + assert_eq!(row.manifest.version, if phase == 3 { "1.0.1" } else { "1.0.0" }); + assert_eq!(row.enabled, phase == 3); + assert!(!staging.join(&journal.backup).exists()); + } + } #[test] fn legacy_and_discovered_plugins_keep_unknown_install_times() { let mut f = Fixture::new(); @@ -1522,7 +1746,7 @@ mod tests { f.service.install("main", &row.token, false).unwrap(); assert!(!f.service.row("org.test.demo").unwrap().enabled); assert_eq!(package(&f.source).unwrap().hash, original.hash); - assert!(f.service.inspect("main", f.source.clone()).error.is_some()); + assert!(f.service.inspect("main", f.source.clone()).error.is_none()); } #[test] fn feature_packages_use_the_standard_install_and_remove_lifecycle() { diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index ec7621e..54bf0c6 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "RuneStone", - "version": "0.1.36", + "version": "0.1.41", "identifier": "com.runestone.app", "build": { "beforeDevCommand": "pnpm dev", diff --git a/src/lib/editor/EditorHost.svelte b/src/lib/editor/EditorHost.svelte index 44ca688..82e06ac 100644 --- a/src/lib/editor/EditorHost.svelte +++ b/src/lib/editor/EditorHost.svelte @@ -1,6 +1,9 @@ +
+{#if findOpen && search}{/if}
+
{#if loadError}{/if}