Improve editor, plugin updates, and window transfers for 0.1.41
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+19
-12
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 4.9 KiB After Width: | Height: | Size: 5.2 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 5.0 KiB After Width: | Height: | Size: 5.2 KiB |
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "runestone",
|
||||
"version": "0.1.36",
|
||||
"version": "0.1.41",
|
||||
"description": "Desktop editor for a local workspace",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -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<string, string>();
|
||||
const root = { dataset: {} as Record<string, string>, 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%');
|
||||
|
||||
@@ -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, []);
|
||||
});
|
||||
@@ -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"));
|
||||
|
||||
@@ -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 = '<html><body><!--StartFragment--><table><thead><tr><th>Ticker</th><th>Name</th></tr></thead><tbody><tr><td>ADBE.US</td><td>Adobe</td></tr><tr><td>ADSK.US</td><td>Autodesk</td></tr></tbody></table><!--EndFragment--></body></html>';
|
||||
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(); }
|
||||
@@ -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(); }
|
||||
@@ -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/);
|
||||
});
|
||||
|
||||
@@ -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 = '<html><body><!--StartFragment--><table><tr><th>Ticker</th><th>Name</th></tr><tr><td>ADBE.US</td><td>Adobe</td></tr><tr><td>ADSK.US</td><td>Autodesk</td></tr></table><!--EndFragment--></body></html>';
|
||||
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 = '<table><tr><th>Notes</th></tr><tr><td>First<!-- multi-line\n <b>comment</b> --> part<br><strong>Second</strong></td></tr></table>';
|
||||
assert.equal(htmlToMarkdown(html), '| Notes |\n| --- |\n| First part<br>**Second** |');
|
||||
});
|
||||
|
||||
test("escaped comment text remains user content", () => {
|
||||
assert.equal(htmlToMarkdown('<p><!--Example--></p>'), '<!--Example-->');
|
||||
});
|
||||
@@ -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(); }
|
||||
@@ -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<br>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<br>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, /<table>/);
|
||||
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<br>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(); }
|
||||
@@ -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);
|
||||
|
||||
@@ -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 = '<section><h2>Test document</h2><p>Alpha alpha alphabet</p><button>Alpha card</button><p hidden>Hidden Alpha</p><button class="focus-return">Details</button></section>';
|
||||
}});
|
||||
for (const name of ['Board', 'Changes']) api.registerView({ id: name.toLowerCase(), title: name, placement: 'editor', navigation: true, icon: 'list', mount(root) {
|
||||
root.innerHTML = '<section><h2>' + name + '</h2><p>Alpha alpha alphabet</p><button>Alpha card</button><p hidden>Hidden Alpha</p><button class="focus-return">Details</button></section>';
|
||||
}});
|
||||
api.registerView({ id: 'native', title: 'Custom find', placement: 'editor', navigation: true, find() { window.customFindCalls = (window.customFindCalls || 0) + 1; }, mount(root) { root.innerHTML = '<p>Native content</p>'; } });
|
||||
}`;
|
||||
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(); }
|
||||
@@ -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(); }
|
||||
|
||||
@@ -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: '<b>User data</b>' }, { fr: { 'Column {name}': 'Colonne {name}' } }), 'Colonne <b>User data</b>');
|
||||
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'); }
|
||||
});
|
||||
@@ -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");
|
||||
|
||||
@@ -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(); }
|
||||
@@ -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);
|
||||
|
||||
@@ -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<br>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<br>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**"));
|
||||
|
||||
@@ -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(); }
|
||||
Generated
+1
-1
@@ -3130,7 +3130,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "runestone"
|
||||
version = "0.1.36"
|
||||
version = "0.1.41"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"dunce",
|
||||
|
||||
@@ -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"
|
||||
|
||||
+249
-25
@@ -85,6 +85,14 @@ struct Candidate {
|
||||
hash: String,
|
||||
manifest: Manifest,
|
||||
created: Instant,
|
||||
previous: Option<Installed>,
|
||||
}
|
||||
#[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<PathBuf> {
|
||||
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<Option<String>> {
|
||||
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<String> {
|
||||
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<RemovalPlan> {
|
||||
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<String>,
|
||||
enabled: bool,
|
||||
) -> Result<Vec<InstallResult>> {
|
||||
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(),
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
});
|
||||
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);
|
||||
result
|
||||
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)?;
|
||||
}
|
||||
}
|
||||
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);
|
||||
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() {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<script lang="ts">
|
||||
import FindPanel from "./FindPanel.svelte";
|
||||
import { monacoSearch } from "./monacoSearch";
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
import { t } from "$lib/i18n";
|
||||
import { untrack } from "svelte";
|
||||
import { tick, untrack } from "svelte";
|
||||
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
|
||||
import { isMarkdownPath, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
|
||||
import { registerImageDropTarget } from "./workspaceImageDrop";
|
||||
@@ -34,6 +37,24 @@
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let editor: import("monaco-editor").editor.IStandaloneCodeEditor | undefined;
|
||||
export function focus() { editor?.focus(); }
|
||||
let search = $state.raw<ReturnType<typeof monacoSearch>>();
|
||||
let findOpen = $state(false);
|
||||
let findPanel = $state<FindPanel>();
|
||||
export async function openFind(replace = false) {
|
||||
if (!search || !editor) return;
|
||||
const selection = editor.getSelection();
|
||||
const text = selection && editor.getModel()?.getValueInRange(selection);
|
||||
if (text && !text.includes("\n") && !text.includes("\r")) {
|
||||
search.target.setQuery(new SearchQuery({ ...search.target.query, search: text }));
|
||||
findPanel?.sync(search.target.query);
|
||||
}
|
||||
findOpen = true;
|
||||
search.refresh();
|
||||
await tick();
|
||||
findPanel?.focus(replace);
|
||||
}
|
||||
export function closeFind() { if (findOpen) search?.target.close(); }
|
||||
export function nextMatch(backward = false) { if (findOpen) search?.target.next(backward); else void openFind(); }
|
||||
let ready = $state(0);
|
||||
let applying = false;
|
||||
let loadError = $state<string | null>(null);
|
||||
@@ -125,6 +146,12 @@
|
||||
...monacoChrome(mode),
|
||||
});
|
||||
editor = view;
|
||||
search = monacoSearch(monaco, view, () => { findOpen = false; });
|
||||
for (const [id, label, replace] of [["actions.find", "Find", false], ["editor.action.startFindReplaceAction", "Replace", true]] as const) {
|
||||
listeners.push(view.addAction({ id, label, keybindings: [monaco.KeyMod.CtrlCmd | (replace ? monaco.KeyCode.KeyH : monaco.KeyCode.KeyF)], run: () => openFind(replace) }));
|
||||
}
|
||||
listeners.push(view.addAction({ id: "editor.action.nextMatchFindAction", label: "Next match", keybindings: [monaco.KeyCode.F3], run: () => nextMatch() }));
|
||||
listeners.push(view.addAction({ id: "editor.action.previousMatchFindAction", label: "Previous match", keybindings: [monaco.KeyMod.Shift | monaco.KeyCode.F3], run: () => nextMatch(true) }));
|
||||
const linkPath = `/${encodeURIComponent(untrack(() => buffer.id))}/`;
|
||||
if (markdown) listeners.push(monaco.languages.registerLinkProvider("markdown", {
|
||||
provideLinks(candidate) {
|
||||
@@ -230,6 +257,9 @@
|
||||
menu?.destroy();
|
||||
releaseDrop?.();
|
||||
listeners.forEach(listener => listener.dispose());
|
||||
search?.dispose();
|
||||
search = undefined;
|
||||
findOpen = false;
|
||||
view?.dispose();
|
||||
if (session) releaseEditorSession(session);
|
||||
editor = undefined;
|
||||
@@ -273,6 +303,8 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="source-editor">
|
||||
{#if findOpen && search}<FindPanel bind:this={findPanel} target={search.target} />{/if}
|
||||
<div
|
||||
class="monaco-host"
|
||||
role="application"
|
||||
@@ -291,14 +323,14 @@
|
||||
void takeImages(event, event.clipboardData);
|
||||
}}
|
||||
></div>
|
||||
</div>
|
||||
{#if loadError}<p class="editor-notice" role="alert">{loadError}<button onclick={() => { loadError = null; }}>{$t("Dismiss")}</button></p>{/if}
|
||||
|
||||
<style>
|
||||
.monaco-host {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.source-editor { position: absolute; inset: 0; display: flex; flex-direction: column; min-width: 0; }
|
||||
.source-editor :global(.rs-find-bar) { flex-shrink: 0; border-bottom: 1px solid var(--rs-border); }
|
||||
.monaco-host { position: relative; flex: 1; min-height: 0; overflow: hidden; }
|
||||
.monaco-host :global(.rs-source-search-match) { background: var(--rs-item-selection-bg); outline: 1px solid var(--rs-accent); }
|
||||
|
||||
.monaco-host :global(.monaco-editor),
|
||||
.monaco-host :global(.overflow-guard) {
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { untrack } from "svelte";
|
||||
import { runScopeHandlers, type EditorView } from "@codemirror/view";
|
||||
import { SearchQuery, closeSearchPanel, findNext, findPrevious, getSearchQuery, replaceAll, replaceNext, selectMatches, setSearchQuery } from "@codemirror/search";
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
import type { FindTarget } from "./findTarget";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import "$lib/ui/find.css";
|
||||
|
||||
let { view }: { view: EditorView } = $props();
|
||||
const initialQuery = untrack(() => getSearchQuery(view.state));
|
||||
let { target }: { target: FindTarget } = $props();
|
||||
const initialQuery = untrack(() => target.query);
|
||||
let searchInput: HTMLInputElement;
|
||||
let replaceInput = $state<HTMLInputElement>();
|
||||
export function focus(replace = false) { (replace ? replaceInput : searchInput)?.select(); }
|
||||
let query = $state.raw(initialQuery);
|
||||
let searchText = $state(initialQuery.search);
|
||||
let replacement = $state(initialQuery.replace);
|
||||
@@ -28,18 +31,23 @@
|
||||
|
||||
function commit() {
|
||||
query = new SearchQuery({ search: searchText, replace: replacement, caseSensitive, regexp, wholeWord });
|
||||
view.dispatch({ effects: setSearchQuery.of(query) });
|
||||
target.setQuery(query);
|
||||
}
|
||||
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if (runScopeHandlers(view, event, "search-panel")) {
|
||||
if (target.keydown?.(event)) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
} else if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
target.close();
|
||||
} else if (event.key === "Enter" && event.target instanceof HTMLInputElement && event.target.type === "text") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
commit();
|
||||
if (event.target.name === "replace") replaceNext(view);
|
||||
else (event.shiftKey ? findPrevious : findNext)(view);
|
||||
if (event.target.name === "replace") target.replace();
|
||||
else target.next(event.shiftKey);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -49,14 +57,14 @@
|
||||
<div class="rs-find-row">
|
||||
<div class="rs-find-field">
|
||||
<Icon icon="search" />
|
||||
<input type="text" name="search" {...{ "main-field": "true" }} aria-label={$t("Find in document")} placeholder={$t("Find in document")}
|
||||
<input bind:this={searchInput} type="text" name="search" autocomplete="off" {...{ "main-field": "true" }} aria-label={$t("Find in document")} placeholder={$t("Find in document")}
|
||||
aria-invalid={searchText !== "" && !query.valid} bind:value={() => searchText, value => { searchText = value; commit(); }} />
|
||||
</div>
|
||||
<div class="rs-find-actions">
|
||||
<IconButton icon="up" label={$t("Previous match (Shift+Enter)")} onclick={() => findPrevious(view)} disabled={!query.valid} />
|
||||
<IconButton icon="down" label={$t("Next match (Enter)")} onclick={() => findNext(view)} disabled={!query.valid} />
|
||||
<button class="rs-find-button" type="button" onclick={() => selectMatches(view)} disabled={!query.valid}>{$t("Select all")}</button>
|
||||
<IconButton icon="close" label={$t("Close find (Escape)")} onclick={() => closeSearchPanel(view)} />
|
||||
<IconButton icon="up" label={$t("Previous match (Shift+Enter)")} onclick={() => target.next(true)} disabled={!query.valid} />
|
||||
<IconButton icon="down" label={$t("Next match (Enter)")} onclick={() => target.next()} disabled={!query.valid} />
|
||||
{#if target.canSelectAll !== false}<button class="rs-find-button" type="button" onclick={() => target.selectAll()} disabled={!query.valid}>{$t("Select all")}</button>{/if}
|
||||
<IconButton icon="close" label={$t("Close find (Escape)")} onclick={() => target.close()} />
|
||||
</div>
|
||||
</div>
|
||||
<div class="rs-find-options">
|
||||
@@ -65,14 +73,14 @@
|
||||
<label><input type="checkbox" bind:checked={() => regexp, value => { regexp = value; commit(); }} />{$t("Regex")}</label>
|
||||
{#if searchText && !query.valid}<span class="rs-find-error" role="status">{$t("Invalid expression")}</span>{/if}
|
||||
</div>
|
||||
{#if !view.state.readOnly}
|
||||
{#if !target.readOnly}
|
||||
<div class="rs-find-row">
|
||||
<div class="rs-find-field">
|
||||
<input type="text" name="replace" aria-label={$t("Replace with")} placeholder={$t("Replace with")} bind:value={() => replacement, value => { replacement = value; commit(); }} />
|
||||
<input bind:this={replaceInput} type="text" name="replace" autocomplete="off" aria-label={$t("Replace with")} placeholder={$t("Replace with")} bind:value={() => replacement, value => { replacement = value; commit(); }} />
|
||||
</div>
|
||||
<div class="rs-find-actions">
|
||||
<button class="rs-find-button" type="button" onclick={() => replaceNext(view)} disabled={!query.valid}>{$t("Replace")}</button>
|
||||
<button class="rs-find-button" type="button" onclick={() => replaceAll(view)} disabled={!query.valid}>{$t("Replace all")}</button>
|
||||
<button class="rs-find-button" type="button" onclick={() => target.replace()} disabled={!query.valid}>{$t("Replace")}</button>
|
||||
<button class="rs-find-button" type="button" onclick={() => target.replace(true)} disabled={!query.valid}>{$t("Replace all")}</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
import { writerHistory, historyKeymap } from "./writerHistory";
|
||||
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
||||
import { noteFormats } from "./noteFormats";
|
||||
import { searchKeymap } from "@codemirror/search";
|
||||
import { closeSearchPanel, findNext, findPrevious, openSearchPanel, searchKeymap } from "@codemirror/search";
|
||||
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
|
||||
import { writerSearch } from "./writerSearch";
|
||||
import type { OpenBuffer } from "$lib/workspace/types";
|
||||
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
|
||||
@@ -52,6 +53,13 @@
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let editor = $state.raw<EditorView>();
|
||||
export function focus() { editor?.focus(); }
|
||||
export function openFind(replace = false) {
|
||||
if (!editor) return;
|
||||
openSearchPanel(editor);
|
||||
editor.dom.querySelector<HTMLInputElement>(replace ? 'input[name="replace"]' : 'input[name="search"]')?.select();
|
||||
}
|
||||
export function closeFind() { if (editor) closeSearchPanel(editor); }
|
||||
export function nextMatch(backward = false) { if (editor) (backward ? findPrevious : findNext)(editor); }
|
||||
let error = $state("");
|
||||
let model: import("monaco-editor").editor.ITextModel | undefined;
|
||||
let ModelSelection: typeof import("monaco-editor").Selection;
|
||||
@@ -272,6 +280,17 @@
|
||||
return true;
|
||||
},
|
||||
paste(event, view) {
|
||||
const html = event.clipboardData?.getData("text/html") || "";
|
||||
if (/<table[\s>]/i.test(html)) {
|
||||
const markdown = htmlToMarkdown(html).replace(/\r\n?/g, "\n").trim();
|
||||
if (markdown) {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const { from, to } = view.state.selection.main;
|
||||
const insert = imageInsertion(view.state.doc.toString(), from, to, [markdown]);
|
||||
view.dispatch({ changes: { from, to, insert }, selection: { anchor: from + insert.length }, userEvent: "input.paste", annotations: isolateHistory.of("full") });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (!onInsertImage || !imageFiles(event.clipboardData).length) return false;
|
||||
void insertImages(event, view); return true;
|
||||
},
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
|
||||
/** Commands for the shared document search controls. */
|
||||
export interface FindTarget {
|
||||
query: SearchQuery;
|
||||
readOnly: boolean;
|
||||
canSelectAll?: boolean;
|
||||
setQuery(query: SearchQuery): void;
|
||||
next(backward?: boolean): void;
|
||||
selectAll(): void;
|
||||
replace(all?: boolean): void;
|
||||
close(): void;
|
||||
keydown?(event: KeyboardEvent): boolean;
|
||||
}
|
||||
|
||||
export function documentMatches(source: string, query: SearchQuery) {
|
||||
const state = EditorState.create({ doc: source });
|
||||
const matches: { from: number; to: number }[] = [];
|
||||
if (query.valid) {
|
||||
const cursor = query.getCursor(state);
|
||||
for (let match = cursor.next(); !match.done; match = cursor.next()) matches.push(match.value);
|
||||
}
|
||||
return { state, matches };
|
||||
}
|
||||
|
||||
export function replacementText(source: string, from: number, query: SearchQuery) {
|
||||
const replacement = query.literal ? query.replace : query.replace.replace(/\\([nrt\\])/g, (_, char: string) => ({ n: "\n", r: "\r", t: "\t", "\\": "\\" })[char]!);
|
||||
if (!query.regexp) return replacement;
|
||||
const expression = new RegExp(query.search, "gmu" + (query.caseSensitive ? "" : "i"));
|
||||
expression.lastIndex = from;
|
||||
const match = expression.exec(source);
|
||||
return replacement.replace(/\$([$&]|\d+)/g, (token, index: string) => {
|
||||
if (index === "$") return "$";
|
||||
if (index === "&") return match?.[0] ?? "";
|
||||
for (let length = index.length; length > 0; length--) {
|
||||
const number = Number(index.slice(0, length));
|
||||
if (match && number > 0 && number < match.length) return (match[number] ?? "") + index.slice(length);
|
||||
}
|
||||
return token;
|
||||
});
|
||||
}
|
||||
@@ -145,6 +145,24 @@ class Preview extends WidgetType {
|
||||
}
|
||||
|
||||
export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) {
|
||||
const focusBody = StateEffect.define<boolean>();
|
||||
const bodyFocused = StateField.define({
|
||||
create: () => false,
|
||||
update(value, transaction) {
|
||||
for (const effect of transaction.effects) if (effect.is(focusBody)) value = effect.value;
|
||||
return value;
|
||||
},
|
||||
});
|
||||
const syncBodyFocus = ViewPlugin.define(view => {
|
||||
// A restored editor can already own focus before its focus observer starts.
|
||||
const sync = () => queueMicrotask(() => {
|
||||
if (view.dom.isConnected && view.state.field(bodyFocused, false) !== undefined && view.state.field(bodyFocused) !== view.hasFocus) {
|
||||
view.dispatch({ effects: focusBody.of(view.hasFocus) });
|
||||
}
|
||||
});
|
||||
sync();
|
||||
return { update: sync };
|
||||
});
|
||||
function build(state: EditorState, previous?: DecorationSet): DecorationSet {
|
||||
const ranges: Range<Decoration>[] = [];
|
||||
const active = state.selection.ranges.map(range => ({ from: state.doc.lineAt(range.from).from, to: state.doc.lineAt(range.to).to }));
|
||||
@@ -221,17 +239,32 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
return false;
|
||||
}
|
||||
const line = state.doc.lineAt(node.from);
|
||||
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name)) {
|
||||
// A list starts with one hyphen. Do not enlarge the preceding paragraph
|
||||
// while the user enters that marker. Keep the Markdown source unchanged.
|
||||
const pendingList = node.name === "SetextHeading2" && state.doc.lineAt(node.to).text.trim() === "-";
|
||||
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name) && !pendingList) {
|
||||
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
|
||||
}
|
||||
if (node.name === "InlineCode") codeRanges.push({ from: node.from, to: node.to });
|
||||
if (node.name === "TaskMarker") {
|
||||
const match = /^(\s*)([-+*]\s+)\[([ xX])\]\s?/.exec(line.text);
|
||||
if (!match) return;
|
||||
const markerFrom = line.from + match[1].length;
|
||||
// ArrowLeft and Home reach the replacement's start, before the list bullet.
|
||||
// Keep the trailing space outside the edit range so task text stays rendered.
|
||||
const editingMarker = state.field(bodyFocused) && state.selection.ranges.some(range => range.from <= node.to && range.to >= markerFrom);
|
||||
if (editingMarker) return;
|
||||
ranges.push(Decoration.replace({ widget: new Checkbox(match[3].toLowerCase() === "x"), atomic: true }).range(markerFrom, line.from + match[0].length));
|
||||
if (match[3].toLowerCase() === "x") mark(line.from + match[0].length, line.to, "writer-completed");
|
||||
return;
|
||||
}
|
||||
if (selected(node.from, node.to)) return;
|
||||
if (node.name === "HorizontalRule") {
|
||||
ranges.push(Decoration.line({ class: "writer-divider-line" }).range(line.from));
|
||||
ranges.push(Decoration.replace({ widget: new Divider(), atomic: true }).range(node.from, node.to));
|
||||
return false;
|
||||
}
|
||||
if (node.name === "HeaderMark") replace(node.from, Math.min(line.to, node.to + 1));
|
||||
if (node.name === "HeaderMark" && !(source.slice(node.from, node.to) === "-" && node.node.parent?.name === "SetextHeading2")) replace(node.from, Math.min(line.to, node.to + 1));
|
||||
if (node.name === "StrongEmphasis") mark(node.from, node.to, "writer-strong");
|
||||
if (node.name === "Emphasis") mark(node.from, node.to, "writer-emphasis");
|
||||
if (node.name === "Strikethrough") mark(node.from, node.to, "writer-strike");
|
||||
@@ -252,12 +285,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", "data-editor-tooltip": "Ctrl+click to open link" } }).range(node.from + 1, node.from + 1 + match[1].length));
|
||||
return false;
|
||||
}
|
||||
if (node.name === "TaskMarker") {
|
||||
const match = /^(\s*)([-+*]\s+)\[([ xX])\]\s?/.exec(line.text);
|
||||
if (!match) return;
|
||||
ranges.push(Decoration.replace({ widget: new Checkbox(match[3].toLowerCase() === "x"), atomic: true }).range(line.from + match[1].length, line.from + match[0].length));
|
||||
if (match[3].toLowerCase() === "x") mark(line.from + match[0].length, line.to, "writer-completed");
|
||||
}
|
||||
} });
|
||||
for (const match of source.matchAll(/\[\^([^\]\s]+)\](:)?/g)) {
|
||||
const from = match.index, to = from + match[0].length;
|
||||
@@ -281,12 +308,12 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
}
|
||||
return Decoration.set(ranges, true);
|
||||
}
|
||||
return [imageSource, linkTooltips, StateField.define<DecorationSet>({
|
||||
return [imageSource, linkTooltips, bodyFocused, syncBodyFocus, EditorView.focusChangeEffect.of((_state, focusing) => focusBody.of(focusing)), StateField.define<DecorationSet>({
|
||||
create: build,
|
||||
update(value, transaction) {
|
||||
return transaction.docChanged || transaction.selection
|
||||
|| syntaxTree(transaction.startState) !== syntaxTree(transaction.state)
|
||||
|| transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource) || effect.is(foldEffect) || effect.is(unfoldEffect))
|
||||
|| transaction.effects.some(effect => effect.is(focusBody) || effect.is(refreshImages) || effect.is(editImageSource) || effect.is(foldEffect) || effect.is(unfoldEffect))
|
||||
? build(transaction.state, value.map(transaction.changes)) : value;
|
||||
},
|
||||
provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field).update({
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import type * as Monaco from "monaco-editor";
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
import { documentMatches, replacementText, type FindTarget } from "./findTarget";
|
||||
|
||||
export function monacoSearch(monaco: typeof Monaco, view: Monaco.editor.IStandaloneCodeEditor, close: () => void) {
|
||||
const decorations = view.createDecorationsCollection();
|
||||
let active = false;
|
||||
let query = new SearchQuery({ search: "" });
|
||||
function snapshot() {
|
||||
const model = view.getModel()!;
|
||||
const { state, matches } = documentMatches(model.getValue(), query);
|
||||
function range(match: { from: number; to: number }) {
|
||||
const from = state.doc.lineAt(match.from), to = state.doc.lineAt(match.to);
|
||||
return new monaco.Range(from.number, match.from - from.from + 1, to.number, match.to - to.from + 1);
|
||||
}
|
||||
return { model, state, matches, range };
|
||||
}
|
||||
function refresh() {
|
||||
active = true;
|
||||
const { matches, range } = snapshot();
|
||||
decorations.set(matches.map(match => ({ range: range(match), options: { inlineClassName: "rs-source-search-match" } })));
|
||||
}
|
||||
function next(backward = false) {
|
||||
const { matches, range } = snapshot();
|
||||
if (!matches.length) return;
|
||||
const selection = view.getSelection();
|
||||
const ranges = matches.map(range);
|
||||
const current = ranges.findIndex(match => selection?.equalsRange(match));
|
||||
let index: number;
|
||||
if (current >= 0) index = (current + (backward ? -1 : 1) + ranges.length) % ranges.length;
|
||||
else if (backward) {
|
||||
index = ranges.findLastIndex(match => !selection || monaco.Position.compare(match.getEndPosition(), selection.getStartPosition()) <= 0);
|
||||
if (index < 0) index = ranges.length - 1;
|
||||
} else {
|
||||
index = ranges.findIndex(match => !selection || monaco.Position.compare(match.getStartPosition(), selection.getEndPosition()) >= 0);
|
||||
if (index < 0) index = 0;
|
||||
}
|
||||
view.setSelection(ranges[index]);
|
||||
view.revealRangeInCenterIfOutsideViewport(ranges[index]);
|
||||
}
|
||||
const target: FindTarget = {
|
||||
get query() { return query; }, readOnly: false,
|
||||
setQuery(value) { query = value; refresh(); },
|
||||
next,
|
||||
selectAll() {
|
||||
const { matches, range } = snapshot();
|
||||
if (!matches.length) return;
|
||||
view.setSelections(matches.map(match => { const value = range(match); return new monaco.Selection(value.startLineNumber, value.startColumn, value.endLineNumber, value.endColumn); }));
|
||||
view.focus();
|
||||
},
|
||||
replace(all = false) {
|
||||
const { state, matches, range } = snapshot();
|
||||
const selection = view.getSelection();
|
||||
const selected = all ? matches : matches.filter(match => selection?.equalsRange(range(match))).slice(0, 1);
|
||||
if (!selected.length) { if (!all) next(); return; }
|
||||
const edits = selected.map(match => ({ range: range(match), text: replacementText(state.doc.toString(), match.from, query) }));
|
||||
const last = selected[selected.length - 1];
|
||||
const inserted = edits[edits.length - 1].text;
|
||||
const end = state.update({ changes: selected.map((match, index) => ({ ...match, insert: edits[index].text })) }).state;
|
||||
const offset = all ? 0 : last.from + inserted.length;
|
||||
const line = end.doc.lineAt(Math.min(offset, end.doc.length));
|
||||
view.pushUndoStop();
|
||||
view.executeEdits("document-find", edits, [new monaco.Selection(line.number, offset - line.from + 1, line.number, offset - line.from + 1)]);
|
||||
view.pushUndoStop();
|
||||
if (!all) next();
|
||||
},
|
||||
close() { active = false; decorations.clear(); close(); view.focus(); },
|
||||
};
|
||||
const changed = view.onDidChangeModelContent(() => { if (active) refresh(); });
|
||||
return { target, refresh, dispose() { changed.dispose(); decorations.clear(); } };
|
||||
}
|
||||
@@ -81,6 +81,7 @@ class NoteTitle extends WidgetType {
|
||||
event.stopPropagation();
|
||||
if (event.isComposing) return;
|
||||
if (event.key === "Enter") { event.preventDefault(); void commit(true); }
|
||||
if (event.key === "Tab" && !event.shiftKey) { event.preventDefault(); void commit(true); }
|
||||
if (event.key === "Escape" && !pending) { event.preventDefault(); finish(); button.focus(); }
|
||||
};
|
||||
return block;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
import { documentMatches, type FindTarget } from "./findTarget";
|
||||
|
||||
/** Search the visible reading text without changing its Markdown or rendered nodes. */
|
||||
export function readingSearch(root: HTMLElement, close: () => void, options: { includeButtons?: boolean; focusOnClose?: () => void } = {}): FindTarget {
|
||||
let query = new SearchQuery({ search: "" });
|
||||
let current = -1;
|
||||
function ranges() {
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
||||
const nodes: { node: Text; from: number; to: number }[] = [];
|
||||
let source = "", block: Element | null = null;
|
||||
while (walker.nextNode()) {
|
||||
const node = walker.currentNode as Text, parent = node.parentElement;
|
||||
if (!parent || parent.closest(options.includeButtons ? "[hidden], [aria-hidden=true], script, style" : "button, [hidden], script, style") || !parent.getClientRects().length) continue;
|
||||
const nextBlock = parent.closest("p, h1, h2, h3, h4, h5, h6, li, td, th, pre, button, div, section");
|
||||
if (nodes.length && nextBlock !== block) source += "\n";
|
||||
block = nextBlock;
|
||||
nodes.push({ node, from: source.length, to: source.length + node.length });
|
||||
source += node.data;
|
||||
}
|
||||
return documentMatches(source, query).matches.flatMap(match => {
|
||||
const start = nodes.find(node => node.to > match.from || node.from === match.from);
|
||||
const end = nodes.find(node => node.to >= match.to);
|
||||
if (!start || !end) return [];
|
||||
const range = document.createRange();
|
||||
range.setStart(start.node, Math.max(0, match.from - start.from));
|
||||
range.setEnd(end.node, Math.max(0, match.to - end.from));
|
||||
return [range];
|
||||
});
|
||||
}
|
||||
function next(backward = false) {
|
||||
const matches = ranges();
|
||||
if (!matches.length) { current = -1; return; }
|
||||
current = current < 0 ? (backward ? matches.length - 1 : 0) : (current + (backward ? -1 : 1) + matches.length) % matches.length;
|
||||
const range = matches[current];
|
||||
const selection = window.getSelection();
|
||||
selection?.removeAllRanges();
|
||||
selection?.addRange(range);
|
||||
range.startContainer.parentElement?.scrollIntoView({ block: "center" });
|
||||
}
|
||||
return {
|
||||
get query() { return query; }, readOnly: true, canSelectAll: false,
|
||||
setQuery(value) { if (query.eq(value)) return; query = value; current = -1; window.getSelection()?.removeAllRanges(); },
|
||||
next, selectAll() {}, replace() {},
|
||||
close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); },
|
||||
};
|
||||
}
|
||||
@@ -277,9 +277,13 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
if (event.key === "Escape") { event.preventDefault(); leave(true); return true; }
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
if (sourceEditing || /^=(?!=)/.test((editor?.getText() || "").trim())) { finish(); wrapper.focus(); }
|
||||
if (event.shiftKey) editor?.commands.setHardBreak();
|
||||
else if (event.ctrlKey || event.metaKey) leave(true);
|
||||
else editor?.commands.setHardBreak();
|
||||
else {
|
||||
const next = table!.rows[row + 1]?.cells[column];
|
||||
if (next) { activate(next); editor?.commands.setTextSelection(1); editor?.view.focus(); }
|
||||
else add("row", true, column);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (event.key === "Tab") {
|
||||
@@ -360,7 +364,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
view.requestMeasure();
|
||||
}
|
||||
|
||||
function add(kind: "row" | "column", focusNew = false) {
|
||||
function add(kind: "row" | "column", focusNew = false, column = 0) {
|
||||
const from = view.posAtDOM(root);
|
||||
finish();
|
||||
const current = controller.source;
|
||||
@@ -369,7 +373,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
requestAnimationFrame(() => {
|
||||
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
|
||||
if (!updated) return;
|
||||
if (focusNew) updated.querySelector<HTMLTableCellElement>("tbody tr:last-child td")?.focus();
|
||||
if (focusNew) updated.querySelector<HTMLTableRowElement>("tbody tr:last-child")?.cells[column]?.focus();
|
||||
if (kind === "column") {
|
||||
const viewport = updated.querySelector<HTMLElement>(".md-table-scroll")!;
|
||||
viewport.scrollLeft = viewport.scrollWidth;
|
||||
|
||||
@@ -60,6 +60,16 @@ export function copyTableCells(source: string, range: CellRange): string {
|
||||
return Array.from({ length: bottom - top + 1 }, (_, r) => Array.from({ length: right - left + 1 }, (_, c) => quote(table.rows[sourceRow(top + r)]?.cells[left + c]?.text || "")).join("\t")).join("\n");
|
||||
}
|
||||
|
||||
export function copyTableMarkdown(source: string, range: CellRange): string {
|
||||
const table = parseMarkdownTable(source);
|
||||
if (!table) return "";
|
||||
const { top, bottom, left, right } = bounds(range);
|
||||
const rows = Array.from({ length: bottom - top + 1 }, (_, r) =>
|
||||
`| ${Array.from({ length: right - left + 1 }, (_, c) => table.rows[sourceRow(top + r)]?.cells[left + c]?.text || "").join(" | ")} |`);
|
||||
rows.splice(1, 0, `| ${Array.from({ length: right - left + 1 }, () => "---").join(" | ")} |`);
|
||||
return rows.join("\n");
|
||||
}
|
||||
|
||||
// Parse quoted spreadsheet TSV, including embedded tabs/newlines, or a Markdown table.
|
||||
export function clipboardCells(text: string): string[][] {
|
||||
const table = parseMarkdownTable(text);
|
||||
|
||||
@@ -7,7 +7,8 @@ import { useSpellingMenu } from "./spellingMenu";
|
||||
import { changeTableStructure, sortTableColumn, type TableAxis, type TableOperation } from "./tableStructure";
|
||||
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
|
||||
import { cellFormats, tableTextItems, type TableContextActions } from "./tableCellActions";
|
||||
import { alignTableCells, bounds, copyTableCells, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells, type CellFormat, type CellPoint, type CellRange } from "./tableSelection";
|
||||
import { alignTableCells, bounds, copyTableCells, copyTableMarkdown, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells, type CellFormat, type CellPoint, type CellRange } from "./tableSelection";
|
||||
import { renderMarkdownHtml } from "../workspace/noteHtml";
|
||||
|
||||
const selections = new WeakMap<Element, (range: CellRange) => void>();
|
||||
|
||||
@@ -76,7 +77,12 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
const text = await navigator.clipboard.readText();
|
||||
if (root.isConnected && source() === before && range === selected) apply((value, target) => pasteTableCells(value, target, text));
|
||||
} else {
|
||||
await navigator.clipboard.writeText(copyTableCells(before, selected));
|
||||
if (navigator.clipboard.write && typeof ClipboardItem !== "undefined") {
|
||||
await navigator.clipboard.write([new ClipboardItem({
|
||||
"text/plain": new Blob([copyTableCells(before, selected)], { type: "text/plain" }),
|
||||
"text/html": new Blob([renderMarkdownHtml(copyTableMarkdown(before, selected), new Map())], { type: "text/html" }),
|
||||
})]);
|
||||
} else await navigator.clipboard.writeText(copyTableMarkdown(before, selected));
|
||||
if (action === "cut" && root.isConnected && source() === before && range === selected) clearCells();
|
||||
}
|
||||
} catch {
|
||||
@@ -233,7 +239,11 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
if (action === "paste" && !event.clipboardData.types.includes("text/plain")) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (action === "paste") apply((text, selected) => pasteTableCells(text, selected, event.clipboardData!.getData("text/plain")));
|
||||
else { event.clipboardData.setData("text/plain", copyTableCells(source(), range)); if (action === "cut") clearCells(); }
|
||||
else {
|
||||
event.clipboardData.setData("text/plain", copyTableCells(source(), range));
|
||||
event.clipboardData.setData("text/html", renderMarkdownHtml(copyTableMarkdown(source(), range), new Map()));
|
||||
if (action === "cut") clearCells();
|
||||
}
|
||||
}, { ...options, capture: true });
|
||||
// Spreadsheet data pasted while editing one cell becomes a grid operation.
|
||||
wrapper.addEventListener("paste", event => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { flushSync, mount, unmount } from "svelte";
|
||||
import { getSearchQuery, search, type SearchQuery } from "@codemirror/search";
|
||||
import { runScopeHandlers } from "@codemirror/view";
|
||||
import { closeSearchPanel, findNext, findPrevious, getSearchQuery, replaceAll, replaceNext, search, selectMatches, setSearchQuery, type SearchQuery } from "@codemirror/search";
|
||||
import FindPanel from "./FindPanel.svelte";
|
||||
|
||||
export const writerSearch = search({
|
||||
@@ -12,7 +13,15 @@ export const writerSearch = search({
|
||||
dom,
|
||||
top: true,
|
||||
mount() {
|
||||
panel = mount(FindPanel, { target: dom, props: { view } });
|
||||
panel = mount(FindPanel, { target: dom, props: { target: {
|
||||
query: getSearchQuery(view.state), readOnly: view.state.readOnly,
|
||||
setQuery(query) { view.dispatch({ effects: setSearchQuery.of(query) }); },
|
||||
next(backward) { (backward ? findPrevious : findNext)(view); },
|
||||
selectAll() { selectMatches(view); },
|
||||
replace(all) { (all ? replaceAll : replaceNext)(view); },
|
||||
close() { closeSearchPanel(view); view.focus(); },
|
||||
keydown(event) { return runScopeHandlers(view, event, "search-panel"); },
|
||||
} } });
|
||||
flushSync();
|
||||
dom.querySelector<HTMLInputElement>("[main-field]")?.select();
|
||||
},
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
export type Locale = 'en' | 'fr' | 'ja' | 'zh-CN';
|
||||
export const messageRows: [string, string, string, string][] = [
|
||||
["{name}: package applied.", "{name} : paquet appliqué.", "{name}: パッケージを適用しました。", "{name}:已应用软件包。"],
|
||||
["To update a plugin, select its new ZIP or release link. Its settings and enabled state stay the same.", "Pour mettre à jour un plug-in, sélectionnez son nouveau ZIP ou lien de version. Ses paramètres et son état restent identiques.", "プラグインを更新するには、新しいZIPまたはリリースリンクを選択してください。設定と有効状態は保持されます。", "要更新插件,请选择新的 ZIP 或发行链接。设置和启用状态保持不变。"],
|
||||
["Update {current} → {next}. Settings and enabled state stay the same.", "Mise à jour {current} → {next}. Les paramètres et l’état restent identiques.", "{current} → {next} に更新します。設定と有効状態は保持されます。", "更新 {current} → {next}。设置和启用状态保持不变。"],
|
||||
["Apply packages", "Appliquer les paquets", "パッケージを適用", "应用软件包"],
|
||||
[
|
||||
"Settings",
|
||||
"Paramètres",
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
import { t } from "$lib/i18n";
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import type { GitLineInfo } from "$lib/git/contracts";
|
||||
import FindPanel from "$lib/editor/FindPanel.svelte";
|
||||
import { readingSearch } from "$lib/editor/readingSearch";
|
||||
import type { FindTarget } from "$lib/editor/findTarget";
|
||||
import EditorHost from "$lib/editor/EditorHost.svelte";
|
||||
import LiveWriter from "$lib/editor/LiveWriter.svelte";
|
||||
import { tick } from "svelte";
|
||||
@@ -69,6 +72,32 @@
|
||||
let element: HTMLDivElement | undefined = $state();
|
||||
let writerEditor: LiveWriter | undefined = $state();
|
||||
let sourceEditor: EditorHost | undefined = $state();
|
||||
let readingFind = $state.raw<FindTarget>();
|
||||
let readingFindPanel = $state<FindPanel>();
|
||||
$effect(() => { void buffer?.id; void reading; void previewMode; readingFind = undefined; });
|
||||
async function documentSearch(event: KeyboardEvent) {
|
||||
if (event.target instanceof Element && event.target.closest('[role="menu"], dialog, [role="dialog"]')) return;
|
||||
const key = event.key.toLowerCase();
|
||||
const open = (event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && (key === "f" || key === "h");
|
||||
const advance = key === "f3" && !event.ctrlKey && !event.metaKey && !event.altKey;
|
||||
if ((!open && !advance) || buffer?.kind !== "text") return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const inReading = reading && (previewMode === "preview" || event.target instanceof Element && (!!event.target.closest(".md-page") || !!readingFind && !!event.target.closest(".rs-find-bar")));
|
||||
if (inReading) {
|
||||
const root = element?.querySelector<HTMLElement>(".reading");
|
||||
if (!root) return;
|
||||
sourceEditor?.closeFind();
|
||||
writerEditor?.closeFind();
|
||||
readingFind ??= readingSearch(root, () => { readingFind = undefined; });
|
||||
await tick();
|
||||
if (advance) readingFind.next(event.shiftKey);
|
||||
else readingFindPanel?.focus();
|
||||
} else {
|
||||
readingFind = undefined;
|
||||
if (writerEditor) { if (advance) writerEditor.nextMatch(event.shiftKey); else writerEditor.openFind(key === "h"); }
|
||||
else if (sourceEditor) { if (advance) sourceEditor.nextMatch(event.shiftKey); else await sourceEditor.openFind(key === "h"); }
|
||||
}
|
||||
}
|
||||
const shouldFocusOnMount = () => active && !modeControls?.contains(document.activeElement);
|
||||
export function focusEditor() {
|
||||
if (reading) element?.querySelector<HTMLElement>(".reading")?.focus({ preventScroll: true });
|
||||
@@ -145,7 +174,8 @@
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="editor" class:pane-active={active} bind:this={element}>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions (Capture document shortcuts before nested editor handlers.) -->
|
||||
<div class="editor" class:pane-active={active} bind:this={element} onkeydowncapture={documentSearch}>
|
||||
<div class="chrome-bar">
|
||||
<span class="breadcrumb" title={buffer.relPath}>{buffer.relPath}</span>
|
||||
{#if lineInfo}
|
||||
@@ -179,6 +209,7 @@
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{#if readingFind}<FindPanel bind:this={readingFindPanel} target={readingFind} />{/if}
|
||||
<div class="body" class:split={reading && canPreview && previewMode === "split"}>
|
||||
{#if isImage && buffer.imageUrl}
|
||||
<ImageViewer src={buffer.imageUrl} name={buffer.name} />
|
||||
|
||||
@@ -702,14 +702,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
function paneMenuItems(parent: string): MenuItem[] {
|
||||
const fromTemplate = async (template?: NoteTemplate) => {
|
||||
async function createTreeNote(parent: string, template?: NoteTemplate) {
|
||||
try {
|
||||
const path = await createNote(parent, template);
|
||||
await load(parent);
|
||||
onCreated?.({ name: path.split("/").pop()!, rel_path: path, kind: "file" });
|
||||
} catch (reason) { error = String(reason); }
|
||||
};
|
||||
}
|
||||
|
||||
function paneMenuItems(parent: string): MenuItem[] {
|
||||
const fromTemplate = (template?: NoteTemplate) => createTreeNote(parent, template);
|
||||
return [
|
||||
{
|
||||
kind: "action",
|
||||
@@ -881,7 +883,7 @@
|
||||
|
||||
<div class="wrap">
|
||||
<div class="ribbon tree-tools">
|
||||
<IconButton icon="file-plus" label={$t("New file")} onclick={() => void createIn("", "file")} />
|
||||
<IconButton icon="file-plus" label={$t("New note")} onclick={() => void createTreeNote("")} />
|
||||
<IconButton icon="folder-plus" label={$t("New folder")} onclick={() => void createIn("", "folder")} />
|
||||
<IconButton
|
||||
icon="sort"
|
||||
|
||||
@@ -4,6 +4,13 @@
|
||||
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
|
||||
import { actionIcons } from "$lib/ui/actionIcons";
|
||||
import TabIcon from "$lib/ui/TabIcon.svelte";
|
||||
import { attachTooltip } from "$lib/ui/tooltip";
|
||||
|
||||
function tabTooltip(node: HTMLElement, label: string) {
|
||||
let text = label;
|
||||
const dispose = attachTooltip(node, () => text);
|
||||
return { update(value: string) { text = value; }, destroy: dispose };
|
||||
}
|
||||
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
|
||||
import type { WorkbenchTab } from "$lib/workspace/workbenchTabs";
|
||||
|
||||
@@ -35,6 +42,16 @@
|
||||
let menuAnchor: HTMLButtonElement | undefined;
|
||||
let menuPath = $state<string | null>(null);
|
||||
let receiving = $state(false);
|
||||
let transferFrame = 0;
|
||||
let transferX = 0;
|
||||
|
||||
function scrollTransfer() {
|
||||
if (!receiving) { transferFrame = 0; return; }
|
||||
const bounds = bar.getBoundingClientRect();
|
||||
const speed = transferX < bounds.left + 28 ? -10 : transferX > bounds.right - 28 ? 10 : 0;
|
||||
if (speed) { bar.scrollLeft += speed; transferIndex(transferX); }
|
||||
transferFrame = requestAnimationFrame(scrollTransfer);
|
||||
}
|
||||
|
||||
function startTabTransfer(event: DragEvent, tab: WorkbenchTab) {
|
||||
const data = tabDragData(tab);
|
||||
@@ -59,13 +76,18 @@
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = "move";
|
||||
receiving = true;
|
||||
transferX = event.clientX;
|
||||
if (!transferFrame) transferFrame = requestAnimationFrame(scrollTransfer);
|
||||
const bounds = bar.getBoundingClientRect();
|
||||
if (event.clientX < bounds.left + 28) bar.scrollLeft -= 10;
|
||||
else if (event.clientX > bounds.right - 28) bar.scrollLeft += 10;
|
||||
transferIndex(event.clientX);
|
||||
}
|
||||
|
||||
function finishTabTransfer() { dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false; }
|
||||
function finishTabTransfer() {
|
||||
dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false;
|
||||
cancelAnimationFrame(transferFrame); transferFrame = 0;
|
||||
}
|
||||
|
||||
function dropTab(event: DragEvent) {
|
||||
const data = event.dataTransfer?.getData(transferType);
|
||||
@@ -237,7 +259,7 @@
|
||||
window.addEventListener("keydown", onEscape, true);
|
||||
}
|
||||
|
||||
onDestroy(() => { cancelDrag(); closeMenu(); });
|
||||
onDestroy(() => { cancelDrag(); finishTabTransfer(); closeMenu(); });
|
||||
|
||||
function onMiddleDown(event: MouseEvent) {
|
||||
if (event.button === 1) {
|
||||
@@ -271,7 +293,7 @@
|
||||
aria-controls={tab.panelId}
|
||||
aria-describedby={tab.pinned ? `tab-pin-${tab.id}` : undefined}
|
||||
aria-keyshortcuts="Alt+Shift+ArrowLeft Alt+Shift+ArrowRight"
|
||||
title={`${tab.title}\n${tab.draggable ? $t("Drag to reorder or move to another RuneStone window.") : $t("Drag to reorder.")} ${$t("Right-click for tab actions.")}`}
|
||||
use:tabTooltip={`${tab.title}\n${tab.draggable ? $t("Drag to reorder or move to another RuneStone window.") : $t("Drag to reorder.")} ${$t("Right-click for tab actions.")}`}
|
||||
onclick={() => { if (suppressClick) { suppressClick = false; return; } onSelect(tab.relPath); }}
|
||||
onpointerdown={(event) => { if (!tab.draggable) startDrag(event, tab.relPath); else suppressClick = false; }}
|
||||
draggable={!!tab.draggable}
|
||||
@@ -295,7 +317,7 @@
|
||||
class="close"
|
||||
type="button"
|
||||
aria-label={$t("Close {name}", { name: tab.name })}
|
||||
title={$t("Close {name}", { name: tab.name })}
|
||||
use:tabTooltip={$t("Close {name}", { name: tab.name })}
|
||||
onclick={() => onClose(tab.relPath)}
|
||||
onmousedown={onMiddleDown}
|
||||
onmouseup={(event) => onMiddleUp(event, tab.relPath)}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import PluginTools from "$lib/plugins/PluginTools.svelte";
|
||||
import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte";
|
||||
import PluginEditor from "$lib/plugins/PluginEditor.svelte";
|
||||
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, findPluginEditor } from "$lib/plugins/external";
|
||||
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab } from "$lib/plugins/external";
|
||||
import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
|
||||
import { pluginSidebar, closePluginSidebar, pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginFileOpen, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
|
||||
import { onMount, onDestroy, tick, untrack } from "svelte";
|
||||
@@ -146,6 +146,7 @@
|
||||
let workbenchReady = $state(false);
|
||||
let documents: Documents | null = null;
|
||||
let paneComponents = $state<Record<string, EditorPane | undefined>>({});
|
||||
let pluginPaneComponents = $state<Record<string, PluginEditor | undefined>>({});
|
||||
function activeEditor() { return paneComponents[documentPanes.active]; }
|
||||
let fileTree: FileTree | undefined = $state();
|
||||
let closingTabs = false;
|
||||
@@ -216,7 +217,7 @@
|
||||
...tabs.map(tab => ({
|
||||
id: tab.tabId ?? tab.id, relPath: tab.relPath, name: tab.name,
|
||||
title: tab.kind === "empty" ? tab.name : tab.relPath,
|
||||
dirty: tab.contents !== tab.saved, pinned: !!tab.pinned, buffer: tab,
|
||||
dirty: tab.contents !== tab.saved, pinned: !!tab.pinned, draggable: desktop, buffer: tab,
|
||||
})),
|
||||
...$pluginEditors.map(plugin => ({
|
||||
id: plugin.key, relPath: `plugin:${plugin.key}`, name: plugin.title,
|
||||
@@ -236,10 +237,35 @@
|
||||
});
|
||||
function workingTabDragData(tab: WorkbenchTab) {
|
||||
const view = $pluginEditors.find(view => view.key === tab.id);
|
||||
return view ? pluginTabDragData(view) : undefined;
|
||||
if (view) return pluginTabDragData(view);
|
||||
const item = workingTabs.find(item => item.id === tab.id);
|
||||
if (!item || !workspace || !desktop) return;
|
||||
try { return JSON.stringify({ tabTransfer: prepareTabTransfer(item).token }); }
|
||||
catch (reason) { error = String(reason); return; }
|
||||
}
|
||||
async function receiveTab(data: string, index: number) {
|
||||
try {
|
||||
const payload = JSON.parse(data);
|
||||
if (typeof payload?.tabTransfer === "string") {
|
||||
if (!/^[0-9a-f-]{36}$/i.test(payload.tabTransfer)) throw new Error("Invalid tab transfer.");
|
||||
const key = `runestone.tab-transfer.${payload.tabTransfer}`;
|
||||
const raw = localStorage.getItem(key);
|
||||
if (!raw) throw new Error("This tab transfer expired. Drag the tab again.");
|
||||
const transfer = JSON.parse(raw);
|
||||
if (!workspace || switching || !documents || transfer.root !== workspace.root) throw new Error("Move tabs only between windows of the same workspace.");
|
||||
if (!Number.isFinite(transfer.created) || transfer.created < Date.now() - 120000
|
||||
|| !transfer.buffer || typeof transfer.buffer.relPath !== "string" || typeof transfer.buffer.contents !== "string"
|
||||
|| typeof transfer.buffer.saved !== "string") throw new Error("Invalid tab transfer.");
|
||||
if (!documents.importTab(transfer.buffer)) throw new Error("This tab is already open in this window. The source tab remains open.");
|
||||
selectTab(transfer.buffer.relPath);
|
||||
setReading(transfer.reading === true);
|
||||
await tick();
|
||||
moveWorkingTab(transfer.buffer.relPath, index);
|
||||
localStorage.setItem(key + ".accepted", "true");
|
||||
localStorage.removeItem(key);
|
||||
error = null;
|
||||
return;
|
||||
}
|
||||
await dropPluginTab(data);
|
||||
if ($pluginView?.placement === "editor") moveWorkingTab(`plugin:${$pluginView.key}`, index);
|
||||
error = null;
|
||||
@@ -350,7 +376,9 @@
|
||||
const transfer = JSON.parse(raw);
|
||||
if (transfer.root === workspace.root && transfer.created > Date.now() - 120000
|
||||
&& (transfer.buffer || transfer.plugin)) {
|
||||
if (transfer.buffer && typeof transfer.buffer.relPath === "string" && typeof transfer.buffer.contents === "string") documents.importTab(transfer.buffer);
|
||||
if (transfer.buffer && typeof transfer.buffer.relPath === "string" && typeof transfer.buffer.contents === "string") {
|
||||
if (!documents.importTab(transfer.buffer)) throw new Error("This tab is already open in this window.");
|
||||
}
|
||||
else if (transfer.plugin) {
|
||||
const deadline = Date.now() + 15000;
|
||||
while (!await restorePluginTab(transfer.plugin)) {
|
||||
@@ -413,6 +441,13 @@
|
||||
const action = pluginTabActions(tab.plugin).find(action => "label" in action && /(?:move|open).*new window/i.test(action.label));
|
||||
if (action && "run" in action && !action.disabled) { action.run?.(); return; }
|
||||
}
|
||||
let transfer: ReturnType<typeof prepareTabTransfer> | undefined;
|
||||
try {
|
||||
transfer = prepareTabTransfer(tab, keepSource, true);
|
||||
await workspaceOpenWindow(workspace.root, transfer.token);
|
||||
} catch (reason) { transfer?.finish(); error = String(reason); }
|
||||
}
|
||||
function prepareTabTransfer(tab: EditorTab, keepSource = false, reportTimeout = false) {
|
||||
const current = documents;
|
||||
const bufferSnapshot = (buffer?: OpenBuffer) => JSON.stringify(buffer ? { ...buffer, diskError: buffer.diskError ?? null } : undefined);
|
||||
const snapshot = "buffer" in tab ? bufferSnapshot(tab.buffer) : JSON.stringify(pluginTabState(tab.plugin));
|
||||
@@ -432,11 +467,11 @@
|
||||
finish();
|
||||
};
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify({ root: workspace.root, created: Date.now(), ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading }));
|
||||
localStorage.setItem(key, JSON.stringify({ root: workspace!.root, created: Date.now(), ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading }));
|
||||
window.addEventListener("storage", accepted);
|
||||
timer = setTimeout(() => { finish(); error = "The new window did not accept the tab. The source tab remains open."; }, 30000);
|
||||
await workspaceOpenWindow(workspace.root, token);
|
||||
} catch (reason) { finish(); error = String(reason); }
|
||||
timer = setTimeout(() => { finish(); if (reportTimeout) error = "The new window did not accept the tab. The source tab remains open."; }, 30000);
|
||||
return { token, finish };
|
||||
} catch (reason) { finish(); throw reason; }
|
||||
}
|
||||
function pinWorkingTab(path: string) {
|
||||
const tab = workingTabs.find(tab => tab.relPath === path);
|
||||
@@ -726,7 +761,9 @@
|
||||
if (event.defaultPrevented) return;
|
||||
if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return;
|
||||
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "f" && editorPluginVisible && $pluginView) {
|
||||
if (findPluginEditor($pluginView)) { event.preventDefault(); return; }
|
||||
event.preventDefault();
|
||||
void pluginPaneComponents[$pluginView.key]?.openFind();
|
||||
return;
|
||||
}
|
||||
const action = pluginHost.get("terminal")?.shortcut(event);
|
||||
const terminalTarget = event.target instanceof Element && !!event.target.closest(".dock");
|
||||
@@ -1218,7 +1255,7 @@
|
||||
onCloseTabs={(path, scope) => void closeTabs(path, scope)} fileActions={workingTabFileActions} tabActions={workingTabActions}
|
||||
tabDragData={workingTabDragData} onDropTab={(data, index) => void receiveTab(data, index)} />
|
||||
{/if}
|
||||
<PluginEditor view={pane} />
|
||||
<PluginEditor bind:this={pluginPaneComponents[pane.key]} view={pane} />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
@@ -1,14 +1,44 @@
|
||||
<script lang="ts">
|
||||
import { untrack } from "svelte";
|
||||
import { mountPluginView, type OpenPluginView } from "./external";
|
||||
import { tick, untrack } from "svelte";
|
||||
import { findPluginEditor, mountPluginView, type OpenPluginView } from "./external";
|
||||
import FindPanel from "$lib/editor/FindPanel.svelte";
|
||||
import { readingSearch } from "$lib/editor/readingSearch";
|
||||
import type { FindTarget } from "$lib/editor/findTarget";
|
||||
let { view }: { view: OpenPluginView } = $props();
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let error = $state("");
|
||||
let findTarget = $state.raw<FindTarget>();
|
||||
let findPanel = $state<FindPanel>();
|
||||
let returnFocus: HTMLElement | null = null;
|
||||
|
||||
export async function openFind() {
|
||||
if (findPluginEditor(view)) return;
|
||||
if (!view.document || view.icon === "kanban" || !host) return;
|
||||
if (!findTarget) {
|
||||
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
findTarget = readingSearch(host, () => { findTarget = undefined; }, {
|
||||
includeButtons: true,
|
||||
focusOnClose: () => (returnFocus?.isConnected ? returnFocus : host)?.focus({ preventScroll: true }),
|
||||
});
|
||||
}
|
||||
await tick();
|
||||
findPanel?.focus();
|
||||
}
|
||||
|
||||
function searchKey(event: KeyboardEvent) {
|
||||
if (event.target instanceof Element && event.target.closest('dialog, [role="dialog"], [role="menu"]')) return;
|
||||
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "f") {
|
||||
event.preventDefault(); event.stopPropagation(); void openFind();
|
||||
} else if (findTarget && event.key === "F3" && !event.ctrlKey && !event.metaKey && !event.altKey) {
|
||||
event.preventDefault(); event.stopPropagation(); findTarget.next(event.shiftKey);
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
const element = host;
|
||||
if (!element) return;
|
||||
error = "";
|
||||
findTarget = undefined;
|
||||
let cancelled = false;
|
||||
let cleanup: (() => void | Promise<void>) | undefined;
|
||||
void untrack(() => mountPluginView(view.owner, view.id, element, view.document)).then(dispose => {
|
||||
@@ -23,10 +53,11 @@
|
||||
</script>
|
||||
|
||||
<div id={`plugin-editor-${view.key}`} class="plugin-editor-pane"
|
||||
role="tabpanel" aria-label={view.title} tabindex="-1">
|
||||
role="tabpanel" aria-label={view.title} tabindex="-1" onkeydowncapture={searchKey}>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
{#if findTarget}<FindPanel bind:this={findPanel} target={findTarget} />{/if}
|
||||
{#key `${view.owner}:${view.id}:${view.document?.path ?? ""}`}
|
||||
<div class="plugin-editor-content" bind:this={host}></div>
|
||||
<div class="plugin-editor-content" tabindex="-1" bind:this={host}></div>
|
||||
{/key}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
let cancelButton: HTMLButtonElement | undefined = $state();
|
||||
let previous: HTMLElement | null = null;
|
||||
const external = $derived($installedPlugins.plugins);
|
||||
const hasUpdates = $derived(candidates.some(candidate => external.some(plugin => plugin.manifest.id === candidate.manifest?.id)));
|
||||
$effect(() => {
|
||||
if (modal && (plan || candidates.length || gitForm)) {
|
||||
if (!modal.open) { previous = document.activeElement instanceof HTMLElement ? document.activeElement : null; modal.showModal(); }
|
||||
@@ -55,7 +56,7 @@
|
||||
async function install(enabled: boolean) {
|
||||
await run(async () => {
|
||||
const result = await invoke<{ name: string; error: string | null }[]>("plugins_install", { tokens: selected, enabled });
|
||||
message = result.filter(item => !item.error).map(item => $t(enabled ? "{name} installed and enabled." : "{name} installed.", { name: item.name })).join(" ");
|
||||
message = result.filter(item => !item.error).map(item => $t("{name}: package applied.", { name: item.name })).join(" ");
|
||||
error = result.filter(item => item.error).map(item => `${item.name}: ${item.error}`).join("\n");
|
||||
await invoke("plugins_cancel", { tokens: candidates.map(item => item.token) });
|
||||
candidates = []; selected = []; await refreshPlugins(); previous?.focus();
|
||||
@@ -103,6 +104,7 @@
|
||||
|
||||
<h2>{$t("Plug-ins")}</h2>
|
||||
<p>{$t("Install a plugin ZIP file or get a release from a Git repository link.")}</p>
|
||||
<p>{$t("To update a plugin, select its new ZIP or release link. Its settings and enabled state stay the same.")}</p>
|
||||
<div class="toolbar">
|
||||
<button disabled={!desktop || busy} onclick={() => choose()}><Icon icon="file-plus" />{$t("Install plugin ZIP")}</button>
|
||||
<button disabled={!desktop || busy} onclick={() => { error = ""; gitForm = true; }}><Icon icon="link" />{$t("Install from Git link")}</button>
|
||||
@@ -180,12 +182,15 @@
|
||||
<div class="candidate">
|
||||
<label><input type="checkbox" bind:group={selected} value={candidate.token} disabled={busy || !!candidate.error} />{candidate.manifest?.name ?? $t("Invalid package")}</label>
|
||||
{#if candidate.manifest}<p>{candidate.manifest.author} · {candidate.manifest.version}</p><p>{candidate.manifest.description}</p><p class="path">{$t("Destination: {path}", { path: `${$installedPlugins.root}\\${candidate.manifest.id}` })}</p>{/if}
|
||||
{#each external.filter(plugin => plugin.manifest.id === candidate.manifest?.id) as installed}
|
||||
<p>{$t("Update {current} → {next}. Settings and enabled state stay the same.", { current: installed.manifest.version, next: candidate.manifest!.version })}</p>
|
||||
{/each}
|
||||
<p class="path">{$t("Source: {path}", { path: candidate.source })}</p>
|
||||
{#if candidate.error}<p class="error">{candidate.error}</p>{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<footer><button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button><button disabled={busy || !selected.length} onclick={() => install(false)}>{$t("Install")}</button><button disabled={busy || !selected.length} onclick={() => install(true)}>{$t("Install and enable")}</button></footer>
|
||||
<footer><button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button><button disabled={busy || !selected.length} onclick={() => install(false)}>{$t(hasUpdates ? "Apply packages" : "Install")}</button>{#if !hasUpdates}<button disabled={busy || !selected.length} onclick={() => install(true)}>{$t("Install and enable")}</button>{/if}</footer>
|
||||
{/if}
|
||||
</dialog>
|
||||
{/if}
|
||||
@@ -221,6 +226,7 @@
|
||||
footer { justify-content: flex-end; margin-top: var(--rs-settings-section-gap); }
|
||||
.candidate { padding: var(--rs-settings-row-padding) 0; border-bottom: 1px solid var(--rs-border); }
|
||||
.candidate label { display: flex; gap: 8px; }
|
||||
input[type=checkbox] { accent-color: var(--rs-accent); }
|
||||
.field { display: flex; flex-direction: column; gap: 6px; margin: 10px 0; }
|
||||
.field input { min-width: 0; min-height: var(--rs-settings-control-height); padding: 4px 8px; color: var(--rs-text); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
@media (max-width: 420px) {
|
||||
|
||||
@@ -343,7 +343,9 @@ export async function setPluginEnabled(id: string, enabled: boolean, hash?: stri
|
||||
export async function runPluginCommand(owner: string, id: string) {
|
||||
try { await sessions.get(owner)?.session.run(id); } catch (error) { report(owner, error); throw error; }
|
||||
}
|
||||
export function openPluginView(owner: string, id: string) { show(owner, id); }
|
||||
export function openPluginView(owner: string, id: string) {
|
||||
void sessions.get(owner)?.session.launch(id).catch(error => report(owner, error));
|
||||
}
|
||||
export async function mountPluginView(owner: string, id: string, element: HTMLElement, document?: PluginDocumentContext, surface: "settings" | "view" = "view"): Promise<Dispose> {
|
||||
const session = sessions.get(owner)?.session;
|
||||
if (!session) throw new Error("The plugin is disabled.");
|
||||
|
||||
@@ -4,7 +4,6 @@ import { registerCompletionInput } from "../completion/input.ts";
|
||||
import { showActionMenu } from "../ui/managedActionMenu.ts";
|
||||
import { backgroundHub } from "./backgrounds.ts";
|
||||
import type { BackgroundFiles } from "./backgroundContracts.ts";
|
||||
import { pluginTranslation } from "./translation.ts";
|
||||
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
|
||||
|
||||
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
|
||||
@@ -55,7 +54,6 @@ export class ExternalSession {
|
||||
};
|
||||
const api: PluginApi = {
|
||||
id: this.id, signal: this.controller.signal,
|
||||
i18n: pluginTranslation(() => this.check(), off => { this.contributions.push(off); }),
|
||||
...(this.services.backgrounds ? { backgrounds: {
|
||||
version: 1 as const,
|
||||
chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()),
|
||||
@@ -101,7 +99,7 @@ export class ExternalSession {
|
||||
},
|
||||
contribute: (key, value) => { this.check(); this.contributions.push(this.registry.register(this.id, key, value)); },
|
||||
registerCommand: item => { if (item.category !== undefined && !["open", "action"].includes(item.category)) throw new Error("Unknown plugin command category."); if (typeof item.run !== "function") throw new Error("A command needs a run function."); register(this.commands, item); },
|
||||
registerView: item => { if ([item.settings, item.launcher, item.navigation, item.toolbar].some(value => value !== undefined && typeof value !== "boolean")) throw new Error("Plugin view access options must be boolean."); if (item.placement !== undefined && !["dialog", "editor", "sidebar"].includes(item.placement)) throw new Error("Unknown plugin view placement."); if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); },
|
||||
registerView: item => { if ([item.settings, item.launcher, item.navigation, item.toolbar].some(value => value !== undefined && typeof value !== "boolean")) throw new Error("Plugin view access options must be boolean."); if (item.placement !== undefined && !["dialog", "editor", "sidebar"].includes(item.placement)) throw new Error("Unknown plugin view placement."); if (item.launch !== undefined && typeof item.launch !== "function") throw new Error("A view launch handler must be a function."); if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); },
|
||||
registerTabDrop: receive => { this.check(); if (typeof receive !== "function" || this.receiveTab) throw new Error("Invalid or duplicate tab receiver."); this.receiveTab = receive; },
|
||||
updateViewTitle: (id, title) => {
|
||||
this.check(); const view = this.views.get(id);
|
||||
@@ -171,6 +169,13 @@ export class ExternalSession {
|
||||
await deadline(this.activation);
|
||||
}
|
||||
async run(id: string) { this.check(); const command = this.commands.get(id); if (!command) throw new Error("Unknown plugin command."); await command.run(); }
|
||||
async launch(id: string) {
|
||||
this.check();
|
||||
const view = this.views.get(id);
|
||||
if (!view) throw new Error("Unknown plugin view.");
|
||||
if (view.launch) await view.launch();
|
||||
else this.show(id);
|
||||
}
|
||||
private backgroundRequest<T>(request: () => Promise<T>): Promise<T> {
|
||||
this.check();
|
||||
return request().then(value => { this.check(); return value; });
|
||||
|
||||
@@ -6,7 +6,7 @@ export type { BackgroundFrame, BackgroundApi } from "./backgroundContracts.ts";
|
||||
/** Package API v1. Compiled plugins export activate(api). */
|
||||
export type Dispose = () => void | Promise<void>;
|
||||
export interface PluginCommand { id: string; title: string; icon?: ActionIcon | PluginView["icon"]; category?: "open" | "action"; run: () => void | Promise<void> }
|
||||
export interface PluginView { id: string; title: string; settings?: boolean; launcher?: boolean; placement?: "dialog" | "editor" | "sidebar"; navigation?: boolean; toolbar?: boolean; pinned?: boolean; icon?: "list" | "kanban" | "puzzle" | "globe" | "git"; iconImage?: string | null; tabActions?: (context: { pinned: boolean }) => ActionMenuItem[]; tabDragData?: (context: { pinned: boolean }) => string | undefined; find?: () => void; saveTabState?: () => unknown; restoreTabState?: (state: unknown) => void | Promise<void>; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise<void | Dispose> }
|
||||
export interface PluginView { id: string; title: string; settings?: boolean; launcher?: boolean; launch?: () => void | Promise<void>; placement?: "dialog" | "editor" | "sidebar"; navigation?: boolean; toolbar?: boolean; pinned?: boolean; icon?: "list" | "kanban" | "puzzle" | "globe" | "git"; iconImage?: string | null; tabActions?: (context: { pinned: boolean }) => ActionMenuItem[]; tabDragData?: (context: { pinned: boolean }) => string | undefined; find?: () => void; saveTabState?: () => unknown; restoreTabState?: (state: unknown) => void | Promise<void>; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise<void | Dispose> }
|
||||
export interface PluginViewOpenOptions { split: "right" | "down"; relativeTo: string }
|
||||
export interface PluginDocumentContext { id: string; path: string }
|
||||
export interface PluginDocumentType {
|
||||
@@ -20,7 +20,6 @@ export interface PluginDocumentType {
|
||||
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
|
||||
}
|
||||
export interface PluginApi {
|
||||
i18n?: import("./translation.ts").PluginTranslation;
|
||||
backgrounds?: import("./backgroundContracts.ts").BackgroundApi;
|
||||
ui?: { showActionMenu(options: import("../ui/managedActionMenu.ts").MenuOptions): { close(): void } };
|
||||
git?: import("../git/contracts.ts").GitApi;
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import { get } from 'svelte/store';
|
||||
import { locale, translate, type Locale } from '../i18n/index.ts';
|
||||
|
||||
export type PluginCatalogs = Partial<Record<Locale, Record<string, string>>>;
|
||||
export interface PluginTranslation {
|
||||
readonly locale: Locale;
|
||||
t(message: string, values?: Record<string, string | number>, catalogs?: PluginCatalogs): string;
|
||||
subscribe(listener: (language: Locale) => void): () => void;
|
||||
}
|
||||
|
||||
/** Translates only explicit interface messages. Document content stays with the plugin. */
|
||||
export function pluginTranslation(check: () => void, track: (cleanup: () => void) => void): PluginTranslation {
|
||||
return {
|
||||
get locale() { check(); return get(locale); },
|
||||
t(message, values = {}, catalogs = {}) {
|
||||
check();
|
||||
const language = get(locale);
|
||||
const catalog = Object.hasOwn(catalogs, language) ? catalogs[language] : undefined;
|
||||
if (!catalog || !Object.hasOwn(catalog, message)) return translate(language, message, values);
|
||||
return catalog[message].replace(/\{(\w+)\}/g, (match, key: string) => Object.hasOwn(values, key) ? String(values[key]) : match);
|
||||
},
|
||||
subscribe(listener) {
|
||||
check();
|
||||
if (typeof listener !== 'function') throw new Error('A language listener must be a function.');
|
||||
const off = locale.subscribe(listener);
|
||||
track(off);
|
||||
return off;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -176,6 +176,7 @@
|
||||
.preview-function{color:var(--rs-syntax-function,var(--rs-accent-2))}
|
||||
.preview-number{color:var(--rs-syntax-number,var(--rs-special))}
|
||||
.overlay-controls{display:flex;align-items:center;flex-wrap:wrap;gap:var(--rs-settings-gap);max-width:100%}
|
||||
.overlay-controls output{width:4ch;flex:0 0 4ch;text-align:right;font-variant-numeric:tabular-nums}
|
||||
.overlay-controls input[type=range]{width:160px;max-width:100%;min-width:0}
|
||||
input[type=checkbox]{accent-color:var(--rs-accent)}
|
||||
.overlay-controls input[type=range]{appearance:none;background:transparent;height:var(--rs-settings-control-height);margin:0;cursor:pointer}
|
||||
|
||||
@@ -107,7 +107,7 @@ export function applyTransparency(value: Appearance['transparency'], root: HTMLE
|
||||
root.style.setProperty('--rs-surface-opacity', `${100 - amount}%`);
|
||||
root.style.setProperty('--rs-editor-surface-opacity', `${100 - amount * 10 / 18}%`);
|
||||
root.style.setProperty('--rs-hover-surface-opacity', `${100 - amount * 8 / 18}%`);
|
||||
root.style.setProperty('--rs-transparent-plugin-bg', amount ? 'transparent' : 'var(--rs-bg)');
|
||||
root.style.setProperty('--rs-transparent-plugin-bg', 'transparent');
|
||||
}
|
||||
const backgroundUrls = new WeakMap<HTMLElement, { image: string; url: string }>();
|
||||
const backgroundRequests = new WeakMap<HTMLElement, string | undefined>();
|
||||
@@ -194,6 +194,13 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
|
||||
for (const [key, color] of Object.entries(characterSyntax(theme))) root.style.setProperty(`--rs-${key}`, color);
|
||||
root.style.setProperty('--rs-danger', 'var(--rs-error)');
|
||||
if (custom) for (const [key, color] of Object.entries(custom.colors)) root.style.setProperty(`--rs-${key}`, color);
|
||||
// Keep the theme hue while exposing the background beneath selected text.
|
||||
const selection = root.style.getPropertyValue('--rs-selection').trim().slice(1);
|
||||
const fullSelection = selection.length <= 4 ? [...selection].map(part => part + part).join('') : selection;
|
||||
if (/^[0-9a-f]{6}([0-9a-f]{2})?$/i.test(fullSelection)) {
|
||||
const alpha = Math.min(166, fullSelection.length === 8 ? parseInt(fullSelection.slice(6), 16) : 255);
|
||||
root.style.setProperty('--rs-selection', `#${fullSelection.slice(0, 6)}${alpha.toString(16).padStart(2, '0')}`);
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent('runestone-theme-changed'));
|
||||
}
|
||||
export function saveAppearance(value: Appearance) {
|
||||
|
||||
@@ -48,7 +48,7 @@ export class Documents {
|
||||
|
||||
importTab(buffer: OpenBuffer) {
|
||||
if (this.disposed || this.buffers.some(tab => tab.relPath === buffer.relPath)) return false;
|
||||
this.buffers = this.buffers.filter(tab => tab.kind !== "empty");
|
||||
this.buffers = this.buffers.filter(tab => tab.kind !== "empty" || tab.pinned || tab.contents !== tab.saved);
|
||||
this.buffers.push({ ...buffer, id: crypto.randomUUID(), tabId: undefined });
|
||||
this.select(buffer.relPath);
|
||||
return true;
|
||||
|
||||
@@ -18,7 +18,8 @@ function parseAttrs(raw: string): Record<string, string> {
|
||||
}
|
||||
|
||||
export function htmlToMarkdown(html: string): string {
|
||||
const tokens = html.match(/<\/?[a-zA-Z][^>]*>|[^<]+/g) ?? [];
|
||||
// Windows HTML clipboard fragments include comments around the copied content.
|
||||
const tokens = html.replace(/<!--[\s\S]*?(?:-->|$)/g, "").match(/<\/?[a-zA-Z][^>]*>|[^<]+/g) ?? [];
|
||||
const out: string[] = [];
|
||||
const list: string[] = [];
|
||||
let inPre = false;
|
||||
@@ -39,7 +40,7 @@ export function htmlToMarkdown(html: string): string {
|
||||
const spanKind: string[] = [];
|
||||
|
||||
function flushInline(): string {
|
||||
const text = unescapeHtml(inline.replace(/\s+/g, " ").trim());
|
||||
const text = unescapeHtml(inline.replace(/\s+/g, " ").replace(/\s*<br>\s*/g, "<br>").trim());
|
||||
inline = "";
|
||||
return text;
|
||||
}
|
||||
@@ -185,7 +186,7 @@ export function htmlToMarkdown(html: string): string {
|
||||
const tag = (space === -1 ? body : body.slice(0, space)).toLowerCase();
|
||||
const attrs = space === -1 ? {} : parseAttrs(body.slice(space + 1));
|
||||
if (tag === "br") {
|
||||
inline += "\n";
|
||||
inline += inCell ? "<br>" : "\n";
|
||||
continue;
|
||||
}
|
||||
if (tag === "img") {
|
||||
|
||||
Reference in New Issue
Block a user