Compare commits

..
125 Commits
Author SHA1 Message Date
Knotty Wyvern 3c099e7f49 Link the 0.1.53 Windows installer
The Linux package stays at 0.1.51, and macOS stays at 0.1.44. The README also drops the owner's removed sentence about developer tools.
2026-10-31 19:51:20 -07:00
Knotty Wyvern 5c4d759c1b Pin browser engine 0.1.11
Engine 0.1.11 finds the link under a middle-click. It replaces engine 0.1.10 in the pin.
2026-10-31 19:42:17 -07:00
Knotty Wyvern 2ca7752c9d Open links and images in new browser tabs
- A middle-click on a link opens the link in a new tab. Scrolling
  starts at once, as before. The new engine command linkAt reads the
  link under the pointer in an isolated world. When it finds a web
  link, the tab stops the scroll and opens the link.
- The image menu of a page starts with Open image in new tab.

A new tab opens in front, like Open link in new tab. The engine smoke
test checks linkAt, and the interaction test checks both actions with
the real engine. Cards 333909d1 and f7ee842d.
2026-10-31 19:41:27 -07:00
Knotty Wyvern 68c302a271 Pin browser engine 0.1.10
Engine 0.1.10 keeps the display scale when a page replaces itself during its load. It replaces engine 0.1.9 in the pin.
2026-10-31 19:08:13 -07:00
Knotty Wyvern 19ef8f2e15 Keep the display scale when a page replaces itself during its load
The engine applied device emulation at did-finish-load. Each new
document gets a renderer widget without emulation. Google replaces its
first document with ?zx=... before that document finishes. Thus the
first document kept a scale of 1, and the page grew by the display
scale when the second document finished.

The engine now also applies emulation when a main-frame document
commits. In the real app at 125%, Google keeps the same size before and
after its second document. Card 40a8db13.
2026-10-31 19:06:45 -07:00
Knotty Wyvern 28661f28bc Draw the browser scroll marker with the scroll icon
Middle-click scrolling in the built-in browser showed the text arrow
"↕" at 20 px in a 24 px circle. The look of that glyph depends on the
font, and the circle cut it. It also showed only two directions, but
the scroll moves in four.

The marker now uses the four-way scroll icon of Project Management,
which the shared Icon component also gets. The marker has the size of
the Project Management marker: a 26 px circle with a 20 px icon. The
interaction smoke test checks the icon and keeps screenshots in both
themes. Card ac49c9ec.
2026-10-31 19:06:45 -07:00
Knotty Wyvern 33495d2bf7 Set the version to 0.1.53 2026-10-31 18:31:37 -07:00
Knotty Wyvern e4be352a2b Pin browser engine 0.1.9
Engine 0.1.9 keeps the original bytes for Copy image. The pin names its ZIP on the RuneStone releases page.
2026-10-31 18:24:37 -07:00
Knotty Wyvern 6e1b24e40f Keep the frames of pasted GIF, WebP, and AVIF images
A browser puts only the first frame of an image on the clipboard, with
HTML that names the image address.

- Documents and cards download the original of a GIF, WebP, or AVIF
  address. The host commands workspace_save_image_url and
  workspace_download_image read the format from the file contents and
  refuse other data. A failed download keeps the first frame and shows
  a message.
- Copy image in the RuneStone browser keeps the bytes that the page
  loaded. The engine reads them through the DevTools Protocol, so the
  website gets no second request. The new copiedImage command gives
  them in parts below the line limit of the host. A paste uses them
  first.
- An empty dropped image file shows a message. Firefox gives such a
  file when the website refuses its download.

Copy image needs a new browser engine build. Card 0d5c18f7.
2026-10-31 17:33:08 -07:00
Knotty Wyvern 31ce7e73ce Close the workspace menu on a second click of its button
The menu is an automatic popover. A press on the button closed the open
menu, and the click that followed opened it again. The picker now
records an open menu when the press starts on the button. The click
then leaves the menu closed.

The workspace smoke test clicks the button two times. Card 53db89fc.
2026-10-31 17:33:07 -07:00
Knotty Wyvern 8e2df5544a Show the label colors in Manage labels again
The default field rule of Project Management excluded the find bar with
:not(.rs-find-bar input). That exclusion raised the specificity of the
rule above the rule of each control. Thus the color swatches, the card
title field, the switches, and the date field got the default field
background.

:where() inside :not() keeps the exclusion and adds no specificity.
A new smoke test checks the 16 swatch colors and the card title field in
both themes. Card 0efb6b6e.
2026-10-31 17:33:07 -07:00
Knotty Wyvern bc15f70a34 Link the 0.1.52 Windows installer
The Linux package stays at 0.1.51, because 0.1.52 has no Linux build.
2026-10-30 16:41:23 -07:00
Knotty Wyvern 648a5672e7 Set the version to 0.1.52 2026-10-30 16:12:19 -07:00
Knotty Wyvern 9fc1490988 Make menus and hover fills translucent over a background image
With a background image, menus use the surface transparency of Appearance
(82% by default) instead of at least 92%, and they keep the blur.
Hovered rows and controls in the work area, hovered menu rows, and the
workspace button use the new --rs-hover-bg token. With an image, it is a
6% veil of the strong text color. The image stays visible, and the hover
shows over light and dark image areas. Without an image, nothing changes.

Silver Serpent dim text is now #c2c6cc. It keeps 4.5:1 contrast on a
hovered row over a white image.

UI-061 replaces the image rule of UI-043. Card 05b9bfa1.
2026-10-30 13:38:47 -07:00
Knotty Wyvern b2993e81a3 Link the 0.1.51 Windows and Linux packages
The README names the native features and their off switch in Settings > Features.
The installation guide links the 0.1.51 checksum file for Linux.
2026-10-30 00:51:20 -07:00
Knotty Wyvern 7c2d526e13 Remove AGENTS.md and raise the lowest Opus subagent effort to high
AGENTS.md only pointed to CLAUDE.md. No tracked file outside docs/archive links to it.
2026-10-30 00:48:21 -07:00
Knotty Wyvern 424a817c90 Give the unstaged group of Source control its own title
The Changes section and its unstaged group both showed "Changes (2)".
The group title is now "Unstaged changes (2)". The section title keeps the total count.
2026-10-30 00:21:43 -07:00
Knotty Wyvern d849c3c1b5 Name a plugin that stays in two usage examples 2026-10-29 22:22:23 -07:00
Knotty Wyvern c68a1afb6d Set the version to 0.1.51 2026-10-29 22:22:01 -07:00
Knotty Wyvern 956ead818b Translate Project Management and add its tests and guide
- Every interface string of Project Management goes through the catalog: 539 new rows with fr, ja, and zh-CN.
- Storage and model messages use a local message() marker and stay free of host imports. The interface translates them.
- A board renders again when the language changes. Dates use the interface language.
- Fix: the ribbon button waits for the feature switches at startup, and the settings code loads no feature module.
- Add six smoke tests: board state, cards, menus, drag and drop, views, and language.
- Add docs/guides/project-management.md and UI-060. Update the user, plugin, SDK, host, development, and interface docs and CLAUDE.md.
- Name the fake board view of tree/renameUndo "Board fixture", because the native Project Management button is now in the ribbon.
2026-10-29 21:53:09 -07:00
Knotty Wyvern e66f089176 Make Project Management a native feature
- Move the storage and model of the plugin into src/lib/features/pm/ as pure TypeScript, so the skill can still bundle them.
- Move the DOM interface onto the host menus, the shared tooltip, and the host icons.
- A ribbon button opens Project Management. Board tabs keep the owner runestone.pm and the board-<hex> view IDs through view patterns.
- Read only .runestone/pm/. Offer the plugin migration, with backups, for legacy notes.
- A save, move, or delete reads only that card again. Watcher paths reach the feature.
- Add Settings → Project Management and the projectManagement section. View states move to localStorage.
- Background reads the boards from workspace.json. Remove api.backgrounds and the boards service.
- Add yaml 2.9.1. Use the host markdown-it.
- Move 18 plugin test files to tests/unit/features/pm/ and add native tests.
2026-10-29 20:54:29 -07:00
Knotty Wyvern e6deecc092 Make PDF Viewer a native feature
- Move the PDF Viewer plugin into src/lib/features/pdf/ with pdfjs-dist 6.4.299 (minified builds).
- A static pdf document type marks PDF files and opens them as tabs. The first PDF tab loads the module.
- The worker, the character maps, the fonts, and the decoders come from the app. One worker for each tab.
- The toolbar uses IconButton and the shared tooltip, with the new zoom-in, zoom-out, fit-width, and rotate icons.
- Add THIRD_PARTY_NOTICES.md for PDF.js and xterm.
- Update the tests, the menu inventory, the docs, and UI-059.
2026-10-29 19:41:17 -07:00
Knotty Wyvern 833f793244 Make Terminal a native feature
- Move the Terminal plugin into src/lib/features/terminal/ on the host Svelte runtime, with xterm 6.0.0 and addon-fit 0.11.0.
- Buttons, shortcuts, Help rows, and the close guard follow the Terminal switch. The first use loads the module.
- Add Settings → Terminal and the terminal settings section. The first start copies the old runestone.terminal key.
- The 16 ANSI colors come from the --rs-ansi-* tokens.
- Off asks first when a shell runs in any window (pty_running).
- Rust: no pty-data or pty-exit events, an owner check for write, resize, and close, output joined up to 64 KiB or 8 ms, and the sessions of a reloaded page close.
- Remove api.pty, the terminal contribution, TerminalSlot, and the plugin loader of the smoke harness.
- Check only the tested switches in the Background smoke test.
- Update the tests, the menu inventory, the docs, and UI-058.
2026-10-29 19:02:58 -07:00
Knotty Wyvern 53b9cea7f0 Fix the folder path of the Background measurement
realpath from node:fs/promises has no native form. Use realpathSync.native from node:fs.
2026-10-29 17:43:18 -07:00
Knotty Wyvern ab868bbe8e Make Background a native feature
- Background replaces the Background Slideshow plugin and the background image of Appearance. It shows a folder as a slideshow, or one image.
- It is on by default. Its module loads at launch only when a folder or an image is chosen.
- Rust keeps the one folder in background-folder.json. The interface never sends a path. Eight background_* commands replace the six deprecated backgrounds_* commands.
- The first start moves the slideshow folder and settings, and keeps the saved image as the image source.
- One blur worker with a cache, fewer folder reads, and a decode before each fade. The hub writes only the changed properties.
- Remove the deprecated folder methods of api.backgrounds. set, get, and subscribe stay for the Project Management plugin.
- Show the view buttons in the workbench test without text, after UI-056.
- Update the tests, the measurement tool, the docs, and UI-057.
2026-10-29 17:25:17 -07:00
Knotty Wyvern 115c32fa92 Show the view control with icons only
- Write, Source, Read, and Split show icons only, at every width.
- Each control keeps its accessible name and a tooltip with its shortcut.
- UI-056 records the rule. It replaces the names of UI-049.
2026-10-29 16:28:25 -07:00
Knotty Wyvern 8c43f598fb Set the version to 0.1.50 2026-10-29 16:20:11 -07:00
Knotty Wyvern 4e5c3cb165 Add the memory and response measurement of native features
- scripts/measureFeatures.mjs starts a test build with remote debugging, runs each scenario 3 times, and writes the medians to output/phase-7/<stage>/.
- It records the private bytes and the working set of the process tree, the JS heap, the start time, the first-need time, and long tasks.
- It refuses the installed RuneStone and its identifier, and it stops only the process tree that it started.
- Plugin mode installs the plugin ZIPs through a local Gitea-format server. Native mode uses the features settings section.
2026-10-29 15:52:19 -07:00
Knotty Wyvern d3218b2501 Make Git a native feature with an off switch
- Add the native feature runtime in src/lib/features/: the catalog, the switches, the first-start migration, the loader, and the feature sessions.
- Add Settings → Features and the features settings section.
- Add features_legacy. It reads the old plugin packages and changes nothing.
- Move Git from the plugin into src/lib/features/git/, on host internals.
- Remove api.git, the git contribution key, and the SDK Git types.
- Add pnpm check:features. It fails when a feature module loads at start.
- Update the tests, the menu inventory, the docs, and UI-055.
2026-10-29 15:51:21 -07:00
Knotty Wyvern 58f77b2e9f Link the 0.1.49 installer on the RuneStone releases page
The rebuilt 0.1.49 downloads the browser engine from the RuneStone releases page.
2026-10-29 13:22:04 -07:00
Knotty Wyvern f019d5d8d4 Move the engine download to the RuneStone releases page
The pin keeps the size and the SHA-256 of engine 0.1.8. Only the URL changes.
2026-10-29 13:08:32 -07:00
Knotty Wyvern 135e6d6d92 Set the SDK version to 0.1.2 2026-10-29 13:05:31 -07:00
Knotty Wyvern a950edfb13 Release the plugin SDK as a package file
pnpm release:sdk now packs runestone-plugin-sdk-<version>.tgz and sdk.json
into releases/plugin-sdk/<version>/. Plugins install the SDK from the URL
of that file on the RuneStone releases page. The script no longer uses a
clone of a separate SDK repository.

Installers, browser engine ZIPs, and SDK packages now share the RuneStone
releases page.
2026-10-29 13:05:10 -07:00
Knotty Wyvern 54ccea199e Link the 0.1.49 Windows installer
The Windows download now points to release v0.1.49 in RuneStone_Releases. The docs also say that the browser engine is a separate download.
2026-10-29 11:55:23 -07:00
Knotty Wyvern 2928bc220b Set the version to 0.1.49 2026-10-29 02:58:51 -07:00
Knotty Wyvern 0bf7d47496 Pin browser engine 0.1.8
The engine ZIP is the release browser-engine-v0.1.8 of the public
RuneStone_Releases repository: 163632595 bytes, SHA-256
d704003bf5fe047b100a3cf0ab84f3321fd272510cf287a229e50d1653d0856b.
2026-10-29 02:49:02 -07:00
Knotty Wyvern 516671a235 Ignore local access tokens 2026-10-29 02:47:09 -07:00
Knotty Wyvern 4f8d91e70b Set the SDK version to 0.1.1
SDK 0.1.1 is tagged v0.1.1 in the public SDK repository. It adds the
action icons duplicate, template, and tab, and the optional URL of the
browser contribution's newTab.
2026-10-29 02:42:17 -07:00
Knotty Wyvern 0cc83b7b93 Point the SDK install lines at v0.1.1 2026-10-29 02:40:40 -07:00
Knotty Wyvern 5958c9c252 Describe the engine release without a fixed host
The engine ZIP waits for a public release location. The steps no longer
name the current Git server, its proxy, or its upload limit. They also
say how to move a published engine: upload the same ZIP and change only
the URL in the pin.
2026-10-29 02:21:04 -07:00
Knotty Wyvern d10615d903 Refuse a browser engine pin with another protocol
The pin names the protocol of its engine. An engine of another protocol
would fail at its first start, so the host now refuses its pin before the
download. This also uses the protocol field, which the build reported as
unread.
2026-10-29 01:40:35 -07:00
Knotty Wyvern aebe700366 Ship the browser engine as its own release file
The installer no longer bundles the engine, and the installer script
stops when the bundle names it or when the setup file is over 30 MB.
pnpm build:browser-engine packages the engine, writes a deterministic
ZIP and its record to releases/browser-engine/<version>/, and pins the
ZIP in the host. The installer hooks remove the engine folder that 0.1.48
leaves behind, and uninstall removes the downloaded engine.
2026-10-29 01:25:53 -07:00
Knotty Wyvern c06d48f250 Show the engine setup until the browser engine is installed
A browser tab shows the download size, Download the engine, Install from
file, and Open in default browser until the engine can start. It shows
progress, Cancel, the cause of a failure, and Retry, and then opens the
page. Settings -> Browser shows the engine state and Remove engine. Web
links open in the system browser until the engine is installed. Open
link in app browser always opens a browser tab.
2026-10-29 01:18:21 -07:00
Knotty Wyvern 6004e126f7 Download, verify, and install the browser engine
Each host build pins one engine version in src-tauri/browser-engine.json.
The new engine manager downloads that ZIP over HTTPS, makes sure that its
size and SHA-256 match the pin, extracts it safely to the local app data
folder, and marks the installation last. It can also install a local
ZIP, cancel, report progress, and remove the engine. The host refuses an
engine that sends another protocol with its ready event.
2026-10-29 00:57:51 -07:00
Knotty Wyvern 48b8249ba6 Remove the special cases for the old Browser package
A browser request now needs the session token of its window. Disabling
an old runestone.browser package no longer stops the engine. One list of
built-in modules starts the browser and the theme editor, and the plugin
menus skip their tools. The access rules no longer treat the browser ID
in a special way.
2026-10-29 00:48:37 -07:00
Knotty Wyvern 5dc53e4a5e Keep the browser profiles in Local AppData
The browser data moves from the roaming app data folder to the local
app data folder before the engine starts. A failed rename falls back
to a copy. The old folder stays when the copy fails or when the new
folder exists.
2026-10-29 00:38:08 -07:00
Knotty Wyvern 8bc11c801f Set the version to 0.1.48
0.1.48 is the test installer for Phase 5a and Phase 5: the theme
rework, the command palette, the view control, the title bar and
ribbon, keyboard and focus, the layout and Settings fixes, and the
plain fixes. It is for the owner's tests and is not published.
2026-10-28 23:57:19 -07:00
Knotty Wyvern c271e2bae1 Put the global actions in a bottom bar and the tools in the ribbon
Decision 3 correction and the owner's ribbon direction of 2026-10-28.

- One bar at the bottom of the side pane holds the workspace switcher,
  Help, and Settings, as in Obsidian. The switcher opens the workspace
  list above it. The header has no workspace button.
- While the side pane is closed, the workspace switcher, Help, and
  Settings move to the bottom of the left ribbon, so they stay
  reachable.
- New browser tab, Terminal, Plug-in views, and Commands moved from the
  header to the top of the left ribbon, so the tabs have more room.
  Their menus open at the right of the ribbon. The header keeps Save,
  the outline toggle, and the window controls. A detached tab window
  has no ribbon and keeps these tools in its header.
- Docs: decision 3 and the ribbon tools in UI-050, ui-design.md, and
  the user guide.

Tests: layout/titleBar checks the bottom bar, the ribbon fallback, and
the header buttons. workspace/openAndCreate uses the ribbon switcher in
a narrow window. tree/renameUndo reads the tools in the ribbon.
2026-10-28 23:57:19 -07:00
Knotty Wyvern eeddd880e1 Ask Save or Don't save, and show useful status facts
Phase 5-7.

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

Tests: the new layout/plainFixes, the keepLineBreaks cases in the
settings unit tests, and the new install button name.
2026-10-28 22:06:13 -07:00
Knotty Wyvern 0fdc991b2e Give way in narrow windows and use one icon for each action
Phase 5-6.

- Side panes give way when the window becomes narrow: the outline
  below 1100 pixels, the side pane below 800 pixels. They come back
  when the window grows. A pane that the user opens in a narrow window
  stays open, and the saved layout keeps the wide-window choice.
- One function has one icon. The SDK icon set gets duplicate, template,
  and tab. The reveal action has one label for each platform (Show in
  Explorer, Show in Finder, Show in file manager).
- The file menu follows one order: open, clipboard, organize, show and
  copy path, history, then Delete and Delete permanently in the error
  color after a separator. The tree copies paths through a Copy path
  submenu, as the tab menu does.
- The tree uses the shared chevron. Search hits come in groups by file,
  with counts and marked matches. Bookmarks show the name, the folder,
  and a remove button.
- All boolean settings use one switch design (src/lib/ui/switch.css).
  Browser settings apply at once, and the Save button is gone. The
  Settings window opens with the focus on its search.
- Targets of at least 24 pixels: the tab close button, outline rows,
  switches, and the settings search.
- Catalog rows in French, Japanese, and Simplified Chinese.
- Docs: UI-052, ui-design.md, and the user guide.

Tests: the new layout/panesAndSettings. Tests that closed or opened
panes by hand around narrow windows now rely on the new behavior, or
wait for the panes to give way before they reopen one. Tests that read
the old menu labels or the browser Save button use the new ones.
2026-10-28 21:31:36 -07:00
Knotty Wyvern b7a9784f55 Show the current choice, keyboard focus, and states apart
Phase 5-5.

- The current radio row shows a check mark in the icon column and no
  fill (UI-051, replaces the radio rule of UI-003). The list of all
  tabs names pinned tabs in text.
- Keyboard focus adds a 2-pixel ring inside menu rows. The global
  focus ring is 2 pixels with a 1-pixel offset.
- Active toggles get the accent color, the selection fill, and a
  2-pixel accent bar. Hover gets only a neutral fill. Enabled icon
  buttons use --rs-text.
- Disabled controls use --rs-text-dim at full opacity, not opacity.
- The file tree has one Tab stop. Up and Down move, Shift extends the
  selection, Right opens or enters a folder, Left closes it or goes to
  its parent, Home and End go to the ends, and typed letters find a
  row.
- The three workbench splitters take focus. The arrow keys move them
  by 16 pixels, and Home and End go to their limits.
- Help names Esc, then Tab, to leave the text.
- 5 new catalog rows in French, Japanese, and Simplified Chinese.
- Docs: UI-051, ui-design.md, and the user guide.

Tests: the new layout/keyboardFocus. backgroundImages now expects the
check mark on the current radio row.
2026-10-28 20:44:35 -07:00
Knotty Wyvern c8cf56b224 Keep global actions visible and follow each platform's title bar
Phase 5-4.

- The workspace button sits at the left end of the header. It shows
  the workspace name and opens the workspace list below it.
- The left ribbon is always present: plugin views at the top, Help and
  Settings at the bottom. The left pane footer is gone.
- Tabs keep 120 pixels and scroll. Fades show tabs out of view, and a
  list button names all tabs, with pinned and unsaved marks. The
  active tab now scrolls into view with its close button.
- A drag area of 120 pixels follows the tabs. In a narrow header, the
  tabs shrink first, and the drag area keeps at least 48 pixels.
- Caption buttons are square, 46 pixels wide, and full height. When the
  pointer rests on maximize, the new window_snap_layouts command opens
  Snap Layouts with Win+Z for the focused window.
- macOS keeps its native traffic lights: tauri.macos.conf.json and the
  runtime window builders use an overlay title bar. Title bars leave
  --rs-titlebar-inset-start free for the traffic lights.
- 3 new catalog rows and 1 removed row, in French, Japanese, and
  Simplified Chinese.
- Docs: UI-050, the user guide, and ui-design.md.

Tests: the new layout/titleBar. Tests that used the left pane footer,
the rounded caption buttons, the 600-pixel theme editor pane, or a
ribbon of no width now follow the new layout.
2026-10-28 20:21:20 -07:00
Knotty Wyvern 9cf82503d0 Show one view control and name the file once
Phase 5-3.

- One radio group shows Write, Source, and Read at all times, with an
  icon and a name. Narrow panes show only the icons. The arrow keys
  move the choice, and the group has one Tab stop. The current choice
  gets the selection fill and an accent bar. Hover gets only a fill.
- A Split toggle shows Read beside Write or Source. Each document pane
  keeps a split flag beside its reading flag. Read ends Split.
- Ctrl+Shift+E switches between Read and the editor. Ctrl+E still
  switches between Write and Source.
- "IDE" becomes "Source" in the Chrome type, the tab menu (a View
  submenu), the status bar, the catalog, the tests, and the docs.
- Settings, General, File name title hides the title in Write and
  Read. It is on by default.
- The breadcrumb shows only the folder of the file. The status bar
  shows the view, not the path.
- ModeSwitcher.svelte and its hover test are gone. The new test
  layout/viewModes covers the control.
- The command palette from 5-2 gets its row in docs/menu-surfaces.json.
- The user guide Format table is whole again. The 5-2 edit had put
  the Paragraph and Insert rows under the shortcut table.
- 8 new catalog rows and 10 removed rows, in French, Japanese, and
  Simplified Chinese.
- Docs: UI-049, the user guide, ui-design.md, document-tools.md,
  development.md, and the README feature list.

Tests: the new layout/viewModes, new cases in documentPanes.spec.ts
and settings.spec.ts, and the chooseView harness helper. 21 smoke
tests use the new control. Tests that read the full path from the
breadcrumb now read its tooltip.
2026-10-28 19:45:08 -07:00
Knotty Wyvern ebacdb8164 Add the command palette, Write formatting keys, and platform labels
Phase 5-2.

- Ctrl+Shift+P opens the command palette: every workbench command with
  its shortcut, then the plugin commands (UI-048).
- In Write, Ctrl+B, Ctrl+I, Ctrl+Shift+X, and Ctrl+Shift+H format the
  selection, and Ctrl+K inserts a Markdown link. The Format menu shows
  these shortcuts.
- Ctrl+\ toggles the side pane. It matches the physical key on every
  keyboard layout. Ctrl+B now belongs to Write.
- Help lists every shortcut in groups, open by default. The list comes
  from the command table.
- src/lib/ui/shortcuts.ts writes shortcut labels for the platform:
  Ctrl+Shift+P on Windows and Linux, and the macOS symbols on a Mac.
  The catalog uses placeholders, so no translation contains "Ctrl".
- 19 new catalog rows, and 10 rows converted to placeholders, in
  French, Japanese, and Simplified Chinese.
- Docs: UI-048, the user guide keyboard tables, and a label rule in
  ui-design.md.

New tests: layout/commands, tests/unit/ui/shortcuts.spec.ts, and new
cases in workbenchKeys.spec.ts. Tests that read the old labels or
pressed Ctrl+B for the side pane now use the new names and Ctrl+\.

The smoke harness raises the resource timing buffer to 5000 entries.
The new modules pushed the CodeMirror language module past the
default 250 entries, so editor/markdownPaste could not find its URL.
2026-10-28 19:10:25 -07:00
Knotty Wyvern b2348d0fe8 Split the workbench markup into region components
Phase 5-1.

Workbench.svelte keeps the state and the commands. Six components now
draw its regions, each with its own styles:

- WorkbenchHeader: the side pane buttons, the working tabs, the
  actions, and the window controls.
- PluginRibbon: the ribbon of plugin views.
- LeftPane: the plugin sidebar, files, search, bookmarks, and the
  workspace footer.
- DocumentArea: the plugin editor panes, the document panes, and the
  save conflict banners.
- RightPane: the outline and the backlinks.
- StatusBar: the status line.

Each component keeps the root element of its region, so the shell grid
places them as before. Workbench.svelte has about 450 fewer lines.
There is no visible change.

pnpm check passes. pnpm test: 451 of 451 pass. Full smoke suite: 95
passed, 2 known. plugins/access failed one time and passed on retry
and 3 of 3 times alone.
2026-10-28 18:40:50 -07:00
Knotty Wyvern 5483881bc2 Add the theme editor tab and theme preview cards
Phase 5a-5.

- Settings → Appearance shows a preview card for each theme. The cards
  are one radio group. The arrow keys move and select, and the current
  card has the selection outline and a check mark (UI-047).
- Edit theme opens the theme editor as a workbench tab in the window
  that opened Settings. The window shows each change at once.
- The editor shows all 51 color roles in seven groups. Each role has a
  color picker, a hex field, its lowest readability result, and a reset
  button. A failure shows a warning icon and its ratio, or "Too close".
- Save writes a short schema 3 theme with the built-in theme as its
  base. A built-in theme does not change. Discard returns to the saved
  colors, and Duplicate saves a copy.
- The editor is a built-in package, like the browser, so it uses the
  editor tab code of plugins.
- 23 new catalog rows with French, Japanese, and Simplified Chinese.
- The smoke harness sends emit to every page and emit_to to the pages
  with the target window label.
- Docs: UI-047, ui-design.md, and "Edit a theme" in guides/themes.md.

New tests: appearance/themeEditor and tests/unit/theme/themeEditor.spec.ts.
Six smoke tests use the cards instead of the theme menu.
2026-10-28 18:13:57 -07:00
Knotty Wyvern d160568249 Check text and code on the selection fill
Source draws search matches and selection matches with the item
selection fill, behind code. No rule checked that surface. In four core
palettes, code colors were 3.8:1 to 4.3:1 on it, and dim text in a
selected row was 4.0:1 in two light palettes.

- The text rule also checks the item selection fill over bg-elevated.
  The syntax rule also checks the fill over bg (UI-046).
- The derived fill is the accent at 12%, not 20%. RuneStone, Claude,
  and custom themes without their own fill use it. Sakura and the
  character themes set their own fill and pass.
- Matches keep their underline, and selected rows keep their outline.

pnpm check passes. pnpm test: 446 of 446 pass. Full smoke suite: 92
passed, 2 known. Three tests failed one time while Vite compiled the
changed modules, and passed on retry and 3 of 3 times alone.
2026-10-28 17:36:43 -07:00
Knotty Wyvern 35f39e93f3 Redesign the character palettes from the reference cards
Phase 5a-4. The owner chose candidate B of each palette.

- Harvest Moon uses copper from Holo's tail as the accent, cream from
  the tail tip, and red-brown surfaces.
- Crimson Pilot uses plugsuit red as the accent, orange hair, blue eyes,
  and the yellow dress. Borders are a low-chroma wine. Error is a light
  rose red, so it differs from the accent.
- Silver Serpent uses silver from the grey eyes as the accent, Slytherin
  emerald as the second accent, and charcoal surfaces.
- All eight built-in palettes pass every readability rule. The
  known-failure list in contrast.spec.ts is gone.
- characterPalettes.spec.ts measures text selection as the app draws
  it, at most 65% opaque over the page (UI-029).
- Docs: UI-045, and the character references in ui-color.md.

pnpm check passes. pnpm test: 446 of 446 pass. Full smoke suite: 95
passed, 2 known.
2026-10-28 17:25:51 -07:00
Knotty Wyvern a34c1a5dce Keep an open context menu when its items change
The file pane menu took its items from live state: the template list,
the selection, and the clipboard. A template reload while the menu was
open rebuilt the menu and closed its open submenu. The
workspace/manageTemplates smoke test failed in about half of its runs
because of this race.

ContextMenu.svelte now reads the items once when the menu opens. It
builds the menu again only when its position or label changes.

manageTemplates has a new check: a template reload keeps the open
submenu. The check fails without the fix. With the fix, the test passed
6 of 6 runs. The tree, plugins, menus, and workspace smoke groups pass
(23 of 23), and pnpm check passes.
2026-10-28 16:53:03 -07:00
Knotty Wyvern 445d0200b2 Make menus opaque and redesign the core palettes
Phase 5a-3. The owner chose candidate B of each palette.

- Menus are opaque (UI-043, replaces UI-013). With a background image,
  menus are at least 92% opaque and blur the image. Submenus show as
  manual popovers in the top layer, so the blur cannot clip them.
- In a light palette, the page is the lightest surface, and the side
  panes have a slight tint (UI-044).
- RuneStone uses neutral surfaces and the rune cyan of the app icon.
  Claude Dark uses the layout of the Claude app. Claude Light uses a
  white page with brand Light panes and a darker orange for text.
  Sakura uses Petal Veil for active rows.
- All five core palettes pass every readability rule. A text role keeps
  the hue of its source and changes only its lightness.
- The accent-text rule also checks accent-2, because inline code in
  Read uses it as text.
- The root token defaults match RuneStone Dark.

pnpm check passes. pnpm test: 447 pass, 5 todo, 0 fail. Full smoke
suite: 92 passed, 2 known. editor/markdownPaste and tables/formulas
failed one time and passed on retry. workspace/manageTemplates fails
about half of its runs, also on the previous commit: the tree menu
rebuilds when the template list reloads, and the open submenu closes.
2026-10-28 16:47:55 -07:00
Knotty Wyvern 5bd616d7fd Give themes named color roles, theme data files, and file format 3
Phase 5a-1 and 5a-2.

- roles.ts names 51 color roles. One derivation rule fills the roles
  that a theme does not give, for all themes. tokens.css keeps only the
  root defaults, without theme blocks.
- Each built-in theme is one data file in src/lib/theme/themes/. No code
  outside the theme data names a theme ID. characterThemes.ts is gone.
- New roles: link, focus, on-accent, highlight, scrim, the syntax roles,
  and 16 terminal (ANSI) roles. Stray colors in components use the roles.
- contrast.ts checks each theme against the readability rules of
  docs/ui-color.md. The tests mark the known palette failures as todo,
  and a second test fails when a known failure starts to pass.
- Theme files use schema 3 with a mode and an optional built-in base.
  A short file gets the missing colors and fonts from the base. Schema 1
  and 2 files still import. Old syntax names convert on import.
- Docs: ui-color.md, plugin-development.md (theme tokens), ui-design.md,
  guides/themes.md, and UI-041 and UI-042 in design-decisions.md.

The applied colors stay the same for every built-in theme, except three
small changes: the conflict line uses the warn color, the Write
highlight uses the highlight role, and two dialog backdrops use the
scrim role.

pnpm check passes. pnpm test: 447 pass, 31 todo, 0 fail. Full smoke
suite: 93 passed, 2 known. appearance/palettes read the old syntax
names and passed 3 of 3 times after the fix. workspace/manageTemplates
failed one time and passed on retry.
2026-10-28 15:50:45 -07:00
Knotty Wyvern af68d92969 Show browser frames at one frame pixel for each screen pixel
The built-in browser looked blurry at Windows display scaling above 100%.
The engine rendered sharp frames, but the host stretched each frame to the
surface. The stretch resampled every pixel and blended text and images.

- The engine crops the extra frame edge and sends the frame scale.
- The view shows each frame at its CSS size, at a device pixel edge, on its
  own compositor layer, with nearest-pixel sampling.
- Pointer input subtracts the frame offset.
- The view sends a new scale when the display scale changes.
- A new smoke test, browser/scale, measures stripe contrast at 100%, 125%,
  150%, and 200%, and after a scale change. It also tests click positions.

Measured contrast at 150%: 92 of 255 before, 255 after.

(cherry picked from commit e98a65de536111b5365d1c6f863a897a8e38e505)
2026-10-28 12:32:41 -07:00
Knotty Wyvern 1c19da25ba Set the version to 0.1.47
0.1.47 is the test installer for Phase 4: the CodeMirror source view, list nesting, shared menus, the workspace session, reactive documents, and the translation catalog audit. It is for the owner's tests and is not published.
2026-10-28 12:26:11 -07:00
Knotty Wyvern e9c59f28de Send the remaining interface text through the catalog and audit it
Phase 4f.

- scripts/i18nAudit.mjs runs in pnpm check. It fails for a key that the
  catalog does not have, a catalog key that the code does not use, and
  a row without all four languages.
- message() marks a key that a variable carries to the translation call
  later: table formats, formula errors, and browser status messages.
- 53 new rows with French, Japanese, and Simplified Chinese text for the
  status and error messages of the workbench, the tree, Settings, theme
  import, images, the built-in browser, and code blocks. The backlinks
  toggle now translates too.
- 13 unused rows are gone.
- Errors of the plugin API stay in English. docs/development.md has the
  rule in "Interface text".

pnpm check, pnpm test (350 of 350), and the full smoke suite pass,
except two tests that failed one time under load and passed on retry
and 3 of 3 times alone.
2026-10-28 12:00:24 -07:00
Knotty Wyvern 3e6bc5f088 Move global CSS beside its code and make Documents reactive
Phase 4e.

- app.css holds only imports. Its rules moved into files beside their
  code, in the original cascade order. Dead rules of the deleted TipTap
  Writer are gone.
- workbenchKeys.ts is one table of the workbench shortcuts. Workbench
  runs the commands.
- session.linkTargets is the one link resolution for the link menu and
  for link opening.
- Documents is a rune module (documents.svelte.ts). Workbench reads the
  tabs and the active path from it, without a copy of all buffers on
  each change. The editor mount effect now copies the buffer inside
  untrack, so an edit does not remount the editor.
- Unit tests can import .svelte.ts modules through a Node module hook
  that compiles them with the Svelte compiler.

pnpm check, pnpm test (350 of 350), and the full smoke suite pass,
except tables/linkCaret, which failed one time under load and passed
on retry and 3 of 3 times alone.
2026-10-28 11:50:33 -07:00
Knotty Wyvern f32f60b540 Add a workspace session for marks, renames, the index, and events
Phase 4d. session.svelte.ts holds the workspace state of each window:
the marks, the note index, renames, and typed change events. It
replaces refreshToken.

- One rename path: session.rename serves the tree, the note title, the
  rename command, the link menu, plugins, and the template manager.
  Open documents, plugin views, the index, and the marks follow it.
  A title rename, the rename command, and a plugin rename now also
  move pins and bookmarks.
- marksStore.svelte.ts is the only writer of .runestone/marks.json.
  Changes run in order from the latest marks. A change from another
  window reloads the marks.
- The note index updates only the paths that change, does not rescan
  on window focus, reads in batches of 64, and keeps links, not text.
- Plugins also hear about .runestone/ changes from other windows.
- The outline uses the heading parser of heading links and Read, so
  lines in code blocks are no longer headings.
- New note is above New file in the tree menu (card a6032af5).
- New workspace/session smoke test and new unit tests for the index
  and the outline.

pnpm check, pnpm test (347 of 347), and the full smoke suite pass,
except workspace/manageTemplates, which failed one time under load and
passed on retry and 4 of 4 times alone.
2026-10-28 11:28:54 -07:00
Knotty Wyvern 6cd9195370 Use one menu lifecycle and shared menu rows in the editors
Phase 4c. The Markdown, code, Read, and image menus open through
showActionMenu. It closes a menu on an outside press, an outside scroll,
a resize, and window blur. A host surface now gives its own focus
return, so four copies of the listener code are gone.

- menuItems.ts builds Undo, Redo, the clipboard rows, and the search
  row. The Markdown, code, Read, table cell, and table range menus use
  it. The Markdown and table menus now show the shortcuts for Cut,
  Copy, Paste, and Select all, as the other menus did.
- writerSearch.ts is now editorSearch.ts, because it serves Write and
  Source.
- Plugins still get only close() from api.ui.showActionMenu. The SDK
  menu types do not change.
- The table range menu and the native spelling menu keep their own
  lifecycle, because their open state drives table editing and the
  native spelling protocol.
- docs/ui-design.md names the shared rows and the search modules. The
  menu inventory has the new count for markdownMenu.ts.

pnpm check, pnpm test (341 of 341), and the full smoke suite pass, except
tables/formulas, which failed one time under load and passed on retry.
2026-10-28 11:09:09 -07:00
Knotty Wyvern 724402729e Replace Monaco with one CodeMirror editor and nest list items with Tab
Phase 4b. DocumentEditor.svelte replaces LiveWriter.svelte and the Monaco
EditorHost.svelte. Each open document has one CodeMirror state. Write and
Source are two compartment configurations of it, so they share the undo
history. editorStates.ts keeps the state while the tab stays open. The
Monaco model, the diff bridge, its timers, and sessions.ts are gone.

- Source: syntax colors from the theme tokens, lazy language packages,
  line numbers, folding, and the current line in IDE, wrapped lines in
  Writing, several carets, and bracket matching and closing.
- Lists (card 088e778b): Tab nests a list item and Shift+Tab moves it
  up, in Write and Source. Both renumber the list. The source keeps
  "1.". Write and Read show numbers, letters, then Roman numerals.
- Indent (card 696c30ce): a fixed 4 spaces in Write and Source.
- The code menu uses CodeMirror commands. The command palette item and
  the Monaco styles, search, theme, and workers are removed.
- @codemirror/legacy-modes is pinned to 6.5.4. Version 6.5.5 uses
  parser types that do not match @codemirror/language 6.12.
- 26 smoke tests use CodeMirror instead of Monaco. New tests:
  editor/listNesting and the markdownLists unit tests.
- Docs: development, UI design, plugin host, user guide, and UI-040.

pnpm check, pnpm test (341 of 341), and pnpm build pass. The full smoke
suite passes, except one template test that passed on retry.
2026-10-28 10:48:44 -07:00
Knotty Wyvern 80f5d908e0 Fix the table cell arrow race and remove the TipTap Writer
Phase 4a. The ProseMirror focus handler starts a 20 ms timer that writes
the ProseMirror selection back to the DOM. Under load, the timer ran
after a native arrow move and before ProseMirror read the
selectionchange event, so one move was lost. The cell editor now moves
the DOM selection with Selection.modify and reads the result in the
same key event. This covers plain and Shift arrows and word moves.
Other shortcuts stay with the browser.

- Workbench.svelte no longer filters access events. Rust already drops
  them.
- Delete the unused TipTap Writer: WriterHost.svelte, writerMenu.ts,
  writerMarks.ts, headingMarks.ts, and their two unit tests.
- Remove the 8 TipTap packages that only the Writer used, and its entry
  in docs/menu-surfaces.json.

With a 4x CPU slowdown, 11 of 60 runs failed before the fix and 0 of
120 after it. pnpm check, pnpm test, and the smoke suite pass.
2026-10-28 09:39:08 -07:00
Knotty Wyvern 36a06a9c6b Set the version to 0.1.46
0.1.46 is the test installer for Phase 3: Table Formulas built in, the
plugin runtime changes, the content security policy, and the SDK APIs.
It is for the owner's tests and is not published.
2026-10-28 03:31:39 -07:00
Knotty Wyvern 4d09da30d9 Support the migrated plugins in the host tests
- The pty_open mocks in layout/workbench and plugins/lifecycle send
  output through the channel that api.pty passes. Without a channel they
  keep the old events, so released Terminal versions still pass.
- plugins/gitToolbar resolves the Git plugin's "@runestone/plugin-sdk"
  imports to this repository's SDK build. The smoke runner builds the
  SDK when it is missing.
- The menu audit no longer compares the Terminal plugin's copies of the
  host menu files. The plugin now uses host menus through the SDK.

Checked with the released plugins and with the migrated Terminal, Git,
and Project Management branches.
2026-10-28 03:11:07 -07:00
Knotty Wyvern d62ee5d0b7 Set the plugin SDK version to 0.1.0
Release 0.1.0 is committed and tagged v0.1.0 in the local clone of the
public repository kwyvern/RuneStone_Plugin_SDK. It is not pushed yet.
2026-10-28 02:41:24 -07:00
Knotty Wyvern c1ad9fa60c Add the plugin SDK commands and rule to CLAUDE.md 2026-10-28 02:34:29 -07:00
Knotty Wyvern bb0b8f88b6 Add the versioned plugin SDK package and its release script
The new package packages/plugin-sdk (@runestone/plugin-sdk) is the one source of the public plugin types.
It contains PluginApi and its members, the manifest type, API_VERSION, and feature checks
(hasFeature, requireFeature, requireFeatures, missingFeatures). It also contains the action icons and
the tooltip helper as DOM functions, because RuneStone has no API for them. Menus stay host-drawn through
api.ui.showActionMenu, so the SDK contains only the menu types. The SDK uses the Apache License 2.0.

The host imports the SDK with relative paths in src/lib/plugins/sdk.ts, src/lib/ui/actionIcons.ts, and
src/lib/ui/tooltip.ts. The completion, Git, background, and contribution contract files export the SDK types.
The menu files keep their types, because the Terminal plugin keeps copies of them. A unit test makes sure
that those types and the SDK types are the same. The menu inventory now scans the SDK source.

pnpm sdk:build compiles the SDK to dist/. pnpm release:sdk --version <v> builds it, then commits and tags
v<v> in a local clone of the public repository. It never pushes, and it prints the push commands.
It stops before a change in these conditions:
- The clone is missing, has changes, or is not on a branch.
- The tag exists, or the version is not greater than the current version.
- The package has no LICENSE file, or the SDK source has changes that are not committed.
A failed attempt restores the version and the clone.

pnpm check type checks the SDK and the example plugin. The example plugin now has JSDoc types from the SDK.
pnpm test covers the feature checks, the host and SDK parity, and the release script with temporary
Git repositories. The plugin development, release, development, and completion guides describe the SDK.
2026-10-28 02:33:16 -07:00
Knotty Wyvern 9591c251e9 List the folder grant, terminal, and plugin service modules in the host reference 2026-10-28 02:14:19 -07:00
Knotty Wyvern 374d4db933 Give the terminal and folder grant services to each plugin session
Bind the native terminal service and the folder grant service of the
plugin to its ExternalSession. Without this change, api.pty and
api.files are absent.
2026-10-28 02:01:50 -07:00
Knotty Wyvern e83bf46268 Cache plugin package hashes, add a content security policy, and limit browser windows
Plugin runtime cost:
- Remove the timed plugin scan. Windows scan at start, on focus, on Refresh, and on plugins-changed.
- Keep one package check for each plugin folder. Read and hash the files again only when the
  entry names, sizes, or modification times change. Enable and load always read all files.
  An asset read checks the SHA-256 hash of its file.
- A changed package still stops and needs a new enable decision. Add tests for the cache,
  for changes that keep the metadata, and for the enable decision.
- Replace the 50 ms wait loops of update and removal with a condition variable. The limit
  stays at 10 seconds. Command names, arguments, and results do not change.

Content security policy:
- Set app.security.csp in tauri.conf.json. Keep Tauri from adding nonces to style-src.
- Add CSP mode to the smoke tests (pnpm smoke --csp). The dev server sends the same policy
  with each HTML page, and the harness fails a test on a policy violation.
- Decode data URLs without fetch in the background frame test.

Capabilities:
- Give browser windows their own capability. They load no installed plugin.
  Add a unit test and a browser window smoke test for the command set.

Document the scans, the hash cache, the policy, and the window capabilities.
2026-10-28 02:01:50 -07:00
Knotty Wyvern a6d6e96d6d Give plugins SDK APIs for terminals, granted folders, and plugin services
Plugins can now do through the SDK what they did with direct native calls.
The SDK checks plugin shutdown, so these APIs can move to an isolated
plugin context later.

- api.pty opens shell sessions. pty_open accepts an optional channel.
  A channel session sends its output as raw bytes to its own webview
  and sends no pty-data or pty-exit events. Without a channel, the
  events stay, so the released Terminal plugin keeps working. The host
  closes the open sessions of a plugin when the plugin stops.
- api.files gives folder grants. The user selects the folder, the
  host keeps the grants of each plugin in its retained data, and the
  plugin uses an opaque grant ID. The host rejects names with folder
  parts, links, and files over the size limit. Sidecar JSON files
  replace the per-image settings commands.
- api.services lets one plugin offer data to another plugin in the
  same window. The host copies arguments and results.
- The folder methods of api.backgrounds are deprecated. They stay for
  released Background Slideshow versions.
- The plugin reference lists the native calls of each plugin and the
  SDK member that replaces each call.
2026-10-28 01:46:55 -07:00
Knotty Wyvern eb2adf6a11 Find the Terminal plugin the same way as the runner, and wait for formula results
pluginMocks.mjs now finds the compiled Terminal plugin through
RUNESTONE_PLUGIN_REPOS, like the "@requires plugin:terminal" check.
Before, it used a path relative to the file, which fails in a worktree.

tables/formulas waits for the cycle results after Ctrl+Enter. Under
load, the check ran before the table rendered again.
2026-10-28 01:18:57 -07:00
Knotty Wyvern 5e1533c371 Make Table Formulas a built-in feature
The formula engine, the rendered results, and the formula help now
come from src/lib/formulas/. The editor and the renderer call this
module directly. The tableFormulas contribution type is removed.

- Add the tableFormulas general setting (default on) and a switch in
  Settings > General. When it is off, formulas show as source text.
- Do not load an installed runestone.table-formulas package. Settings
  > Plug-ins marks it as included with RuneStone and tells the user
  that it can be removed. The user's files stay in place.
- Translate the formula help and the error descriptions into French,
  Japanese, and Simplified Chinese.
- Port the plugin unit tests. Test the setting and use a test-only
  contribution for the generic plugin lifecycle tests.
- Smoke tests load only Terminal. The formula and lifecycle tests use
  the built-in feature and its setting.
- Remove scripts/buildPlugins.mjs, the build:plugins script, and the
  plugin-packages requirement of the smoke runner.
- Remove RuneStone_Table_Formulas from the menu audit scope. It had no
  menu surfaces.
- Update the README, the user guides, and the developer references.
2026-10-28 01:05:43 -07:00
Knotty Wyvern 72671e5d01 Set the version to 0.1.45
0.1.45 is the first installer built with the Phase 2 host changes and the
stock NSIS template with RuneStone hooks. It is a test build for the
owner and is not published.
2026-10-28 00:30:27 -07:00
Knotty Wyvern 777cab2cc1 Include the 0.1.44a link selection fix
A mouse drag across rendered links keeps the layout stable until the
mouse button is released. The selection then includes the hidden link
syntax at its ends. This fix shipped in the 0.1.44a installer, but it
was not committed. editor/linkSelection is its smoke test on the harness.
2026-10-28 00:19:00 -07:00
Knotty Wyvern 5d5ba9e1f7 Keep preferences in one settings file and move tab transfer to the host
Keep the user preferences in settings.json in the app config folder.
WebView storage can be lost, and the host cannot read it. The file has
a schema number, a revision number, and one value for each section:
general, appearance, customThemes, customThemesLegacy, and language.
- settings_read gives all sections, the revision, and a one-time
  notice.
- settings_write replaces one section, writes the file atomically, and
  sends settings-changed to all windows. The limit is 8 MiB.
- settings_migrate writes the first file only when no file exists.
- The host moves a damaged file to settings.corrupt-<seconds>.json,
  starts from the defaults, and reports this one time.

Each window loads the sections before its first render. One store in
src/lib/settings/store.ts replaces the storage listeners. When no file
exists, the window normalizes the old localStorage values and migrates
them. The old keys stay in place for one release. The window layout
and the open tabs stay in localStorage on purpose. The browser preview
keeps all preferences in localStorage.

Keep tab transfer offers in host memory, not in localStorage, because
an offer can hold unsaved text. A window takes an offer once. The host
checks the workspace root and a 120 second expiry. When the receiver
accepts the tab, the host sends tab-transfer-accepted to the source
window only. A refused offer stays open, and the source tab stays open.
A new window and a drop on the tab ribbon use one check.

The smoke harness serves the new commands from one shared state for
each browser context. Tests read saved values from the mock settings
file. Rust, unit, and smoke tests cover the changes.
2026-10-27 23:56:00 -07:00
Knotty Wyvern a0eef01ed0 Move workspace file work off the main thread and delete to the trash
Run the blocking workspace commands on the blocking thread pool.
Tauri runs a synchronous command on the main thread, so a long search
or copy froze every window. Command names, arguments, and results do
not change.

Send each workspace-event only to the windows that have its root open.
The frontend listens with its window label as the target. Do not send
access events, because the frontend ignores them. Drop watchers after
the state lock is released, because a macOS watcher waits for its
thread when it stops.

Fix these defects. Each fix has a Rust test:
- A rename that changes only the letter case works on case-insensitive
  volumes.
- New files publish with a move that never replaces a file: MoveFileExW
  on Windows, renameat2 or renamex_np on Linux and macOS, then a hard
  link, then create_new. exFAT, FAT32, and many network mounts now work.
  The Windows save recovery uses the same move.
- On macOS and Linux, existing names with a colon stay usable. New names
  reject the characters that Windows does not allow, on every platform.
- workspace_read_data_url checks the size before it reads the file.
- workspace_write_bytes uses the atomic writer. Its only caller writes
  new names, so it gets no conflict check.
- Delete and rename act on a link itself, not on its target.

Delete now moves items to the system trash. One file moves without a
confirmation. A folder or several items need one. Shift+Delete and
"Delete permanently" keep the permanent delete with its confirmation.
Windows drives without a Recycle Bin give an error instead of a silent
permanent delete. The smoke test for tree actions now checks this
behavior. The user guide describes it and the new-name rule.
2026-10-27 23:15:14 -07:00
Knotty Wyvern 2448c68abf Move blocking host work off the main thread and fix Git SSH settings
Window close no longer waits on the main thread. The handler revokes
browser sessions and plugin leases with short locks. A cleanup thread
stops terminals, closes browser tabs, and erases plugin review folders.
The browser cleanup sends closeTab without a wait for the reply, and
stops the engine outside the engine lock.

Terminal, plugin, background, and browser commands do their file,
process, and plugin-lock work on blocking workers. Terminal events go
to the window that opened the session. Command names, arguments,
results, and events do not change.

The Git service keeps GIT_SSH, GIT_SSH_COMMAND, GIT_SSH_VARIANT, and a
configured core.sshCommand. It adds its SSH defaults only when the user
has none. It still removes other inherited GIT_* variables.

After the first check, Git status starts 2 processes and an unstaged
diff starts 1. The service finds Git once, checks Git once per run,
caches the repository check per root until the Git metadata changes,
waits on its pipes instead of a 15 ms poll, and locks each root
separately.

Lease errors name the plugin. A profile copy rejects junctions.
2026-10-27 23:08:59 -07:00
Knotty Wyvern 70510a114f Give the front end its version through the build environment
vite.config.js reads RUNESTONE_VERSION and falls back to package.json.
The installer build sets RUNESTONE_VERSION and writes all four version
files only after the installer exists. Before, it wrote package.json
before the build and restored it after a failure.

The installation guide and CLAUDE.md now say that setup replaces the
installed app in place. The installer no longer shows a maintenance page.
2026-10-27 22:59:22 -07:00
Knotty Wyvern 7914942698 Use the stock Tauri NSIS template with RuneStone installer hooks
Remove the 996-line fork of the Tauri 2.11.4 template and the custom
comparator. src-tauri/windows/hooks.nsh now adds the RuneStone behavior
through bundle.windows.nsis.installerHooks:

- RuneStoneGuiInit (MUI_CUSTOMFUNCTION_GUIINIT) runs before the first
  page in interactive and passive setup. It stops a downgrade with exit
  code 2. It makes the stock maintenance page skip itself, so that setup
  never starts the uninstaller for an upgrade or a reinstall.
- The hidden section RuneStoneVersionCheck runs before the Tauri sections
  in all modes. Silent setup shows no pages, so it needs this check.
- NSIS_HOOK_POSTINSTALL writes the release version to DisplayVersion and
  RuneStoneReleaseVersion, and the Windows version to
  RuneStoneWindowsVersion. Installed apps now show 0.1.23a, not 0.1.23+1.

Setup compares the four-number Windows encoding with ${VersionCompare}.
An unknown installed version stops setup.

buildInstaller.mjs gives the toolchain version to Tauri through a
--config override. It writes tauri.conf.json, Cargo.toml, and Cargo.lock
only after the installer is complete. package.json changes during the
build because the Settings dialog imports its version. A failed build
restores it. Add --dry-run, which prints the plan and changes no file.

The tests compile NSIS programs with the real makensis. They simulate the
installed version in a test-only HKCU key and check /S, /P, /UPDATE, and
interactive setup. A drift check reads the template from the installed
Tauri CLI. The first real installer needs the installer checks in
docs/builds.md.
2026-10-27 22:54:00 -07:00
Knotty Wyvern e217eb31d2 Start the smoke test server on the port in SMOKE_URL
Two checkouts can then run their smoke tests at the same time.
2026-10-27 22:42:39 -07:00
Knotty Wyvern bd46f3a189 Add a shared error type and shared file helpers to the Rust host
Replace the three error styles with one Error type and one Result alias in
error.rs. The error crosses IPC as the same plain string as before. The
message text does not change.

Move the shared file mechanics to fsutil.rs. These are the reserved-name
check, the link and junction check, the limited reads, and the atomic
writes. Each module keeps its own path rules, limits, and messages. The
plugin settings writer now flushes its file to disk before the rename.

Remove the current_root_path and list_entries wrappers and an unused mime
value. Use named windows-sys constants for the process, file, drive, and
error codes.

Add a test that compares the command lists in lib.rs, build.rs, and the
capability files. The settings capability must be a subset of the full list.

In Cargo.toml, set the author, keep only the rlib crate type, and remove
the unused thiserror dependency. Remove panic = "abort" from the release
profile. A panic on a worker thread then stops only that thread. It does
not stop the editor with unsaved buffers.
2026-10-27 22:41:11 -07:00
Knotty Wyvern 69f90df571 Move the smoke tests onto the shared harness
Each smoke test now uses tests/smoke/_harness/ for Playwright, the Tauri
IPC mock, the in-memory workspace, and output folders, instead of its
own copy. The tests keep their interactions and assertions. Mock
handlers that the app never calls are gone.

- Split the four mixed regression scripts into 18 feature tests.
- Update tests that broke when the app changed on purpose. Each update
  cites the app source that shows the new behavior.
- Mark two real app defects with @known-issue: the settings window
  controls are 1px shorter than the main window controls, and plugin
  tabs cannot be reordered by dragging without a workspace.
- Merge three palette unit tests into one table-driven test.
- The native tests load Playwright through the harness and read
  NATIVE_CDP_URL, with their old variable names as fallbacks.
- A failed smoke test saves a screenshot and prints the console errors.
- The runner runs failed tests once more, alone, and reports a test
  that then passes as flaky.

Result: 89 passed, 1 flaky, 2 known issues, 0 failed. Before, 45 of 78
passed.
2026-10-27 20:58:55 -07:00
Knotty Wyvern c66ea1ce83 Add a smoke test runner, a shared harness, and safer build scripts
- pnpm smoke runs tests/smoke/ in parallel. It starts Vite when nothing
  serves SMOKE_URL, finds an installed Chrome when Playwright has no
  Chromium, and skips a test with a reason when a requirement that the
  test declares with "// @requires" is missing. Logs go to
  output/smoke/logs/.
- tests/smoke/_harness/ holds the Playwright launch, page error
  collection, the Tauri IPC mock with an in-memory workspace, and output
  folders. tabs/order uses it as the first converted test.
- Pin Playwright 1.63.0, the version that browser-runtime uses.
- RUNESTONE_PLUGIN_REPOS names the folder of the sibling plugin
  checkouts for buildPlugins, the menu audit, and the smoke tests.
- buildInstaller restores the version fields after Ctrl+C, keeps the
  backups of each attempt, stops when the browser runtime is not staged,
  and writes the file name instead of absolute paths to host.json.
- buildPlugins clears the staged Table Formulas package before copying.
- plugins/choiceMenus used the wrong Local Autocomplete folder name.
2026-10-27 19:55:49 -07:00
Knotty Wyvern e433bed28e Move the tests from scripts/ to tests/ by feature
Unit tests go to tests/unit/<area>/, browser smoke tests to
tests/smoke/<area>/, and tests against a running desktop app to
tests/native/. Files named after dates, work passes, or Kanban cards get
feature names, for example editorOctober12 -> editor/footnotes.

scripts/ keeps the build, release, and package tools. Plugin repositories
import scripts/packagePlugin.mjs, and the Terminal smoke test imports
scripts/pluginMocks.mjs, which now re-exports the harness copy.

The unit tests get their own type check (tests/tsconfig.json) with Node
types. pnpm check runs it after the app check. Add @types/node and fix
the three test mocks that it reported.
2026-10-27 19:47:39 -07:00
Knotty Wyvern 90d1940c73 Make the checks pass on a fresh clone
- build.rs creates the empty browser-engine folder that tauri-build
  requires, so cargo test runs before the browser runtime is staged.
- The Table Formulas tests skip with a reason when the package is not
  built. Before, the missing module failed two whole test files.
- The installer test accepts CRLF checkouts and skips with a reason
  when the NSIS compiler is missing.
- hostTodo.spec.mjs never ran because of its extension. Its two valid
  background tests move to appearance.spec.ts with current defaults.
  The third test repeated an existing export test.
- Remove tsconfig.plugins.json. It checked the plugins/ folder, which
  moved to separate repositories in 0.1.7.
2026-10-27 19:41:08 -07:00
Knotty Wyvern 2d2a146e34 Remove tracked build output and unused template files
Move the icon drafts from output/ to design/icon-drafts/, so output/
holds only generated files. Remove the test screenshots, a duplicate of
static/runestone.svg, and the unused Svelte, Tauri, and Vite logos.
Remove .gitignore lines that /output/ already covers.
2026-10-27 19:38:39 -07:00
Knotty Wyvern 4240d7dad1 Rewrite the documentation and the agent instructions
Move the agent instructions from AGENTS.md to CLAUDE.md. AGENTS.md now
points to CLAUDE.md. The UI rules move to docs/ui-design.md. The version
and release policy moves to the new docs/releases.md.

Rewrite the README, the user guides, and the developer references.
Check each claim against the code. Remove old version history and
repeated warnings. Link to Gitea at git.knottywyvern.com instead of the
LAN address. Move the October 13 menu audit to the archive.
2026-10-27 19:35:43 -07:00
Knotty Wyvern d7a87795f5 Fix 0.1.44 downloads and keep releases limited to installers 2026-10-21 22:06:09 -07:00
Knotty Wyvern 44a0ef7ba7 Record Linux 0.1.44 installer and validation 2026-10-22 00:20:48 -04:00
Knotty Wyvern 3fa514f19a Publish macOS 0.1.44 installer and validation record 2026-10-21 21:13:20 -07:00
Knotty Wyvern 46e3daae6c Link the Windows 0.1.44 release from the README 2026-10-21 21:06:29 -07:00
Knotty Wyvern 562ef87d24 Add workspace links, restore tabs, and update project guides 2026-10-21 21:05:48 -07:00
Knotty Wyvern f741389418 Close secondary workspace windows after the last tab 2026-10-21 15:06:55 -07:00
Knotty Wyvern b742d274f1 Merge PR #5: Windows installation guide 2026-10-21 14:53:55 -07:00
Knotty Wyvern 0dd43335fe Merge PR #4: Linux installation guide 2026-10-21 14:53:46 -07:00
Knotty Wyvern 4e14be33bd Merge PR #2: macOS installation guide 2026-10-21 14:53:28 -07:00
Knotty Wyvern ae388885bb Merge PR #3: cross-platform installer release 2026-10-21 14:53:28 -07:00
Knotty Wyvern 3daf5270a7 Document Windows installer setup and updates 2026-10-21 14:28:29 -07:00
Knotty Wyvern 622c2dffaa Document macOS DMG installation for Apple silicon 2026-10-21 14:25:35 -07:00
Knotty Wyvern 146dbf0305 Merge remote-tracking branch 'origin/codex/release-0.1.42' into codex/release-0.1.42 2026-10-21 14:24:56 -07:00
Knotty Wyvern 7c497ba569 Prepare 0.1.42 macOS Apple silicon release 2026-10-21 14:24:47 -07:00
Knotty Wyvern 7e7660d9bb Document Linux Debian installer setup 2026-10-21 17:24:37 -04:00
Knotty Wyvern da28f6eaf6 Record completed Linux 0.1.42 installer release 2026-10-21 17:24:37 -04:00
Knotty Wyvern 42dd0fa711 Improve editor, plugin updates, and window transfers for 0.1.41 2026-10-21 10:42:44 -07:00
Knotty Wyvern 68e86ab6eb Add interface languages and improve themes and workspace controls for 0.1.36 2026-10-15 10:55:59 -07:00
kwyvern b066359b66 Merge pull request 'Prepare Linux builds and validate native desktop runtime' (#1) from linux-readiness into master
Reviewed-on: #1
2026-10-14 18:14:24 -07:00
kwyvern 30cbfeedd6 Prepare Linux builds and validate native desktop runtime 2026-10-14 18:06:22 -07:00
Knotty Wyvern edef2520af Update editor, themes, menus, backgrounds, and release tooling 2026-10-14 16:19:51 -07:00
Knotty Wyvern f6eaa52949 Update the browser, editor, settings, and installer 2026-10-12 14:46:21 -07:00
Knotty Wyvern 909894b9c8 Update editor, workspace, Git services, appearance, and project guides 2026-10-11 09:41:16 -07:00
Knotty Wyvern a8b1defb9d Add completion, browser integration, and workspace improvements 2026-10-07 11:25:17 -07:00
Knotty Wyvern dd9fc64676 Keep the RuneStone 0.1.7 installer local 2026-10-06 09:32:08 -07:00
Knotty Wyvern 5d0a4a24f9 Release RuneStone 0.1.7 with plugin documents and shared menus 2026-10-06 09:29:09 -07:00
Knotty Wyvern 6b7af0d527 Release RuneStone 0.1.4 with installable plugins and settings 2026-10-04 15:05:51 -07:00
Knotty Wyvern 0268c5c9f0 Release RuneStone 0.1.3 and expand plugin plans 2026-10-03 04:23:45 -07:00
Knotty Wyvern 43106ed9c7 Improve workspace navigation, search, and tab actions 2026-09-29 07:48:24 -07:00
Knotty Wyvern bdc15e952d Initial RuneStone project 2026-09-26 01:25:42 -07:00
82 changed files with 381 additions and 2621 deletions
-2
View File
@@ -1,2 +0,0 @@
# Tauri writes these files with LF line endings on each build.
src-tauri/permissions/autogenerated/*.toml text eol=lf
-1
View File
@@ -5,7 +5,6 @@ A Tauri 2 host in Rust (`src-tauri/`) serves a Svelte 5 and TypeScript interface
Git, Background, Terminal, PDF Viewer, and Project Management are native features with an off switch in Settings → Features (`src/lib/features/`). They do not use the plugin API. Git, Background, Terminal, PDF Viewer, and Project Management are native features with an off switch in Settings → Features (`src/lib/features/`). They do not use the plugin API.
Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_CSV_Viewer`. Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_CSV_Viewer`.
The [development guide](docs/development.md#architecture) maps the source folders. The [development guide](docs/development.md#architecture) maps the source folders.
The public repository is `https://github.com/kwyvern-gh/RuneStone`. Its releases page holds the installers, the browser engine ZIPs, and the SDK packages.
## Skills ## Skills
-202
View File
@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-4
View File
@@ -1,4 +0,0 @@
RuneStone
Copyright 2026 Knotty Wyvern
This product includes third-party software. See THIRD_PARTY_NOTICES.md for its licenses.
+12 -12
View File
@@ -4,17 +4,21 @@ RuneStone is a desktop workspace for Markdown notes, code, and project work that
## Install and start ## Install and start
On Windows 10 or 11 (x64): Download the installer for your computer.
1. Download [RuneStone_1.0.0_x64-setup.exe](https://github.com/kwyvern-gh/RuneStone/releases/download/v1.0.0/RuneStone_1.0.0_x64-setup.exe). | Platform | Installer | Status |
2. Open the installer and complete setup. | --- | --- | --- |
3. Open RuneStone from the Start menu. | Windows 10 or 11, x64 | [RuneStone_0.1.53_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.53/RuneStone_0.1.53_x64-setup.exe) | Primary platform |
| macOS, Apple silicon | [RuneStone_0.1.44_aarch64.dmg](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_aarch64.dmg) | Experimental: ad hoc signed, not notarized |
| Linux, amd64 | [RuneStone_0.1.51_amd64.deb](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.51/RuneStone_0.1.51_amd64.deb) | Experimental: built on Ubuntu 26.04.1, needs GLIBC 2.39 or newer |
The built-in browser needs a separate engine download of about 160 MB. A browser tab offers it on first use. - **Windows:** Open the installer and complete setup. Then open RuneStone from the Start menu.
- **macOS:** Open the disk image and drag RuneStone into Applications. Then open RuneStone from Applications.
- **Linux:** Run `sudo apt install ./RuneStone_0.1.51_amd64.deb` in the download folder. Then open RuneStone from your applications menu.
On Windows, the built-in browser needs a separate engine download of about 160 MB. A browser tab offers it on first use.
For checksums, updates, and reinstalls, see [Installation and updates](docs/installation.md). For checksums, updates, and reinstalls, see [Installation and updates](docs/installation.md).
macOS and Linux have no 1.0.0 package. Build RuneStone from source on these systems. See [Build Linux packages](docs/builds.md#build-linux-packages) or [macOS packages](docs/builds.md#macos-packages).
## What you can do ## What you can do
- Write Markdown with live formatting, editable tables, table formulas, images, and Mermaid diagrams. - Write Markdown with live formatting, editable tables, table formulas, images, and Mermaid diagrams.
@@ -22,7 +26,7 @@ macOS and Linux have no 1.0.0 package. Build RuneStone from source on these syst
- Find files, search a workspace, and resolve changes that other tools make to your files. - Find files, search a workspace, and resolve changes that other tools make to your files.
- Open web pages in browser tabs beside your documents. - Open web pages in browser tabs beside your documents.
- Use Git source control, a terminal, a PDF viewer, Project Management boards, and a background slideshow. Each one has an off switch in **Settings → Features**. - Use Git source control, a terminal, a PDF viewer, Project Management boards, and a background slideshow. Each one has an off switch in **Settings → Features**.
- Add optional plugins from plugin ZIP files. - Add optional plugins, such as CSV Viewer.
## Find help ## Find help
@@ -43,10 +47,6 @@ When you report a problem to the maintainer, include the app version, operating
- Read the [interface design reference](docs/ui-design.md) before you change the interface. - Read the [interface design reference](docs/ui-design.md) before you change the interface.
- See [product boundaries](docs/development.md#product-boundaries) for exclusions and architecture constraints. - See [product boundaries](docs/development.md#product-boundaries) for exclusions and architecture constraints.
## License
RuneStone uses the [Apache License 2.0](LICENSE). See also [NOTICE](NOTICE) and the [third-party notices](THIRD_PARTY_NOTICES.md).
## Maintainer ## Maintainer
[kwyvern-gh](https://github.com/kwyvern-gh) [kwyvern-gh](https://github.com/kwyvern-gh)
+2 -1
View File
@@ -1,6 +1,7 @@
# Third-party notices # Third-party notices
The RuneStone app includes the third-party packages below. The browser engine has its own notices in [browser-runtime/THIRD_PARTY_NOTICES.md](browser-runtime/THIRD_PARTY_NOTICES.md). The RuneStone app includes the third-party packages below. Each row gives the package, its version, its license, and its source.
The license texts follow the table. The browser engine has its own notices in [browser-runtime/THIRD_PARTY_NOTICES.md](browser-runtime/THIRD_PARTY_NOTICES.md).
| Package | Version | License | Source | Used by | | Package | Version | License | Source | Used by |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
+2 -2
View File
@@ -37,7 +37,7 @@ Output:
The script prints `Installer available: <path>` when it completes. The script prints `Installer available: <path>` when it completes.
After a successful build, the version fields keep the new version. After a successful build, the version fields keep the new version.
Example, from the 1.0.0 download link in the README: version `1.0.0` gives `releases/1.0.0/RuneStone_1.0.0_x64-setup.exe`. Example, from the 0.1.44 download link in the README: version `0.1.44` gives `releases/0.1.44/RuneStone_0.1.44_x64-setup.exe`.
### What the script does ### What the script does
@@ -229,7 +229,7 @@ Procedure, in the RuneStone repository root. The commands use the Tauri CLI from
If the build fails, restore the previous version fields. If the build fails, restore the previous version fields.
Example, from `productName` and `version` in `src-tauri/tauri.conf.json`: the x86_64 Debian build of version `1.0.0` is `RuneStone_1.0.0_amd64.deb`. Example, from the 0.1.44 download link in the README: the x86_64 Debian build of version `0.1.44` is `RuneStone_0.1.44_amd64.deb`.
`pnpm build:installer` does not build Linux packages. It stops on operating systems other than Windows. `pnpm build:installer` does not build Linux packages. It stops on operating systems other than Windows.
Linux packages do not include the browser engine, and no Linux engine is published yet. The browser tab says that no engine is available for the platform. Linux packages do not include the browser engine, and no Linux engine is published yet. The browser tab says that no engine is available for the platform.
+1
View File
@@ -0,0 +1 @@
313f15e68c3b3a6eec9fb223548c9843e6e87af5566885088ddbf7434742e100 RuneStone_0.1.44_amd64.deb
+1
View File
@@ -0,0 +1 @@
80ee6a5274c15333ac793d76b3b82164199e30344e6826218f593a7e842374f7 RuneStone_0.1.51_amd64.deb
-1
View File
@@ -1 +0,0 @@
66d20b7321e1cdfb001e606d2cff2e174589e70eaf736edb6fbbf655e5591876 RuneStone_1.0.0_x64-setup.exe
+1 -1
View File
@@ -114,4 +114,4 @@ Abort stops the display at once. A blocked network read can continue until the r
Plugins keep full application access. This API does not add a permission sandbox. Plugins keep full application access. This API does not add a permission sandbox.
The API does not include context sources, remote model servers, or credential storage. The API does not include context sources, remote model servers, or credential storage.
For tests, see `tests/unit/plugins/completion.spec.ts`. For tests, see `tests/unit/plugins/completion.spec.ts`. For a provider plugin, see the [Local Autocomplete trial guide](https://git.knottywyvern.com/kwyvern/RuneStone_LocalModel/src/branch/main/docs/trial-guide.md).
+1 -50
View File
@@ -955,7 +955,7 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
- Scope: The main header, the side pane, the left ribbon, the tab bars, the Settings and Browser window title bars, and the window builders of the host. - Scope: The main header, the side pane, the left ribbon, the tab bars, the Settings and Browser window title bars, and the window builders of the host.
- Shared implementation: `WorkbenchHeader.svelte`, `LeftPane.svelte`, `PluginRibbon.svelte`, `TabBar.svelte`, `WindowControls.svelte`, `src-tauri/src/window_frame.rs`, `src-tauri/tauri.macos.conf.json`, and the `--rs-titlebar-inset-start` token. - Shared implementation: `WorkbenchHeader.svelte`, `LeftPane.svelte`, `PluginRibbon.svelte`, `TabBar.svelte`, `WindowControls.svelte`, `src-tauri/src/window_frame.rs`, `src-tauri/tauri.macos.conf.json`, and the `--rs-titlebar-inset-start` token.
- Evidence: `tests/smoke/layout/titleBar.smoke.mjs` and the Rust command list test. - Evidence: `tests/smoke/layout/titleBar.smoke.mjs` and the Rust command list test.
- Replaces / replaced by: The left pane footer, and the ribbon rule "The ribbon has no width when it has no entries." [UI-062](#ui-062--tabs-use-the-free-header-space) replaces the drag area rule. - Replaces / replaced by: The left pane footer, and the ribbon rule "The ribbon has no width when it has no entries."
- Limits: Browser checks use desktop service mocks. Snap Layouts, the native drag area, and the macOS title bar need native acceptance. The macOS code path was not compiled here. On Windows 10, Win+Z does nothing. - Limits: Browser checks use desktop service mocks. Snap Layouts, the native drag area, and the macOS title bar need native acceptance. The macOS code path was not compiled here. On Windows 10, Win+Z does nothing.
### UI-051 — Check marks, focus rings, and control states ### UI-051 — Check marks, focus rings, and control states
@@ -1123,52 +1123,3 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
- Evidence: `tests/smoke/menus/consistency.smoke.mjs` and `tests/smoke/features/background.smoke.mjs` check the 82% menu, the blur, and the 6% veil with an image, and opaque fills without one. `tests/unit/theme/characterPalettes.spec.ts` checks the Silver Serpent row colors on a hovered row over a white image. - Evidence: `tests/smoke/menus/consistency.smoke.mjs` and `tests/smoke/features/background.smoke.mjs` check the 82% menu, the blur, and the 6% veil with an image, and opaque fills without one. `tests/unit/theme/characterPalettes.spec.ts` checks the Silver Serpent row colors on a hovered row over a white image.
- Replaces: The image rule of [UI-043](#ui-043--opaque-menus). Menus without an image stay opaque. - Replaces: The image rule of [UI-043](#ui-043--opaque-menus). Menus without an image stay opaque.
- Limits: Over the brightest image areas, dim text on a hovered row has about 15% less contrast than on the pane around it. Browser checks use desktop service mocks. Native desktop acceptance remains open. - Limits: Over the brightest image areas, dim text on a hovered row has about 15% less contrast than on the pane around it. Browser checks use desktop service mocks. Native desktop acceptance remains open.
### UI-062 — Tabs use the free header space
- Type: Rule change
- Date: 2026-11-02
- Status: Implemented for user review
- Decision source: Card 7f1d29d6 ("wasted free space") reports empty header space beside tabs that scroll.
- Previous rule: [UI-050](#ui-050--global-actions-tabs-and-platform-title-bars). A drag area of 120 pixels sat after the tabs. The tabs shrank and scrolled first, so the 120 pixels stayed empty while tabs were out of view.
- New rule: The drag area fills the free space after the + button. When the tabs need more room, they use all space up to a drag area of 48 pixels. Then they scroll. Tabs keep their minimum width of 120 pixels. [Interface design](ui-design.md) holds the rule.
- Reason: Space that shows a tab is more useful than empty space. 48 pixels keep the window movable when the side pane is closed. While the side pane is open, the empty part of the header above it is also a drag area.
- Scope: The header of the main window and of detached tab windows. The header of the browser window keeps its drag area of at least 120 pixels.
- Shared implementation: `src/lib/layout/WorkbenchHeader.svelte`.
- Exceptions: None.
- Evidence: `tests/smoke/layout/titleBar.smoke.mjs` checks a drag area that fills the header with one tab, and a drag area of 48 pixels at the end of the header when 11 tabs scroll.
- Replaces / replaced by: The drag area rule of [UI-050](#ui-050--global-actions-tabs-and-platform-title-bars).
- Limits: Browser checks use desktop service mocks. The native window drag on the smaller area needs native acceptance.
### UI-063 — PDF pages in one column
- Type: Rule change
- Date: 2026-11-09
- Status: Implemented for user review
- Decision source: Cards 9b7b246e, 59ff5dc1, 2e425cbc, 7bd092d2, 2142ca04, and c0900ae8 report a PDF toolbar that a background image hides, no custom zoom, no scroll between pages, lost focus after Ctrl+Tab, and Page Up and Page Down that change pages.
- Previous rule: [UI-059](#ui-059--the-pdf-toolbar-on-shared-controls). The tab showed one page at a time. Page Up and Page Down changed the page. The zoom percent was text. The tab had no surface of its own, so a background image showed through the toolbar and the status line.
- New rule: The tab shows all pages in one column that scrolls. The wheel, the scroll bar, Page Up, Page Down, Home, End, and the arrow keys scroll. The page field shows the page that fills most of the tab. **Previous page**, **Next page**, and the page field show the top of a page. The zoom percent is a field: a typed percent and Enter set the zoom from 25% to 400%. Ctrl and the wheel also change the zoom. The toolbar, the status line, and the password form are opaque (`--rs-bg-elevated`) with and without a background image. The page area uses the editor surface (`--rs-workarea-editor-bg`). Ctrl+Tab and Ctrl+Shift+Tab give keyboard focus to the new plugin tab.
- Reason: A reader scrolls through a document. A page change on Page Down hides the rest of a page that is higher than the tab. A toolbar must stay readable over each image, as headers do.
- Scope: The PDF tab. The focus rule applies to each plugin tab: the host focuses the element that the view marks with `data-tab-focus`, or the view.
- Shared implementation: `src/lib/features/pdf/PdfViewer.svelte`, `src/lib/features/pdf/model.ts`, `src/lib/plugins/PluginEditor.svelte` (`focus`), and the tab commands in `src/lib/layout/Workbench.svelte`.
- Exceptions: A click on a tab or an arrow key in the tab bar keeps the focus in the tab bar.
- Evidence: `tests/smoke/features/pdf.smoke.mjs` and `tests/unit/features/pdf.spec.ts`.
- Replaces / replaced by: The one-page rule and the zoom text of [UI-059](#ui-059--the-pdf-toolbar-on-shared-controls).
- Limits: Only the pages near the visible area have a drawing. Until the viewer reads the size of a page, the page has the size of the first page. Browser checks use desktop service mocks. Native desktop acceptance remains open.
### UI-064 — Split view shows different tabs
- Type: Rule change
- Date: 2026-11-10
- Status: Implemented for user review
- Decision source: Card 565874b2 reports that split view shows only the same document side by side. The user expects different documents side by side, also with a web browser.
- Previous rule: [UI-021](#ui-021--workspace-links-in-document-panes). Only a file tree item or a workspace link opened a document to the right. Document panes held only documents. A plugin tab, for example a browser tab, covered the whole document area. The **Split** toggle showed Read beside the editor of the same document.
- New rule: Each tab menu has **Open to the right**. It shows the tab in a new pane to the right of the active pane. A pane shows a document or a plugin tab. A tab shows in one pane at most, so the item is unavailable for a visible tab. A tab that the user selects, or a file that the user opens, replaces the content of the active pane. The replaced tab stays open. A plugin tab that covers the area moves to the active pane when a tab opens beside it. When one pane is left, its plugin tab covers the area again. A plugin pane has a bar with its title and **Close split**. A document pane beside other panes shows the full path in its bar. The **Split** toggle is now **Read beside**. The file tree menu also has **Open to the right**, also for PDF files and boards. A divider between two panes changes their sizes, with the pointer or the keyboard. A double-click gives the panes equal sizes. A tab that the user drags from the tab bar to a pane replaces the content of that pane. A drop on the right or bottom part of a pane opens a new pane there. A hint shows the place of the drop.
- Reason: "Split" named two different things. Users compare a note with a different note, with a web page, or with a PDF file. Equal pane sizes did not fit a web page or a PDF page beside a note.
- Scope: Document panes, plugin editor tabs, the tab menu, the tab bar, the file tree menu, and the view control.
- Shared implementation: `src/lib/workspace/documentPanes.ts`, `src/lib/workspace/splitLayout.ts` (`stackLayout`, `splitSibling`, `splitDividers`, `setSplitRatio`), `src/lib/layout/DocumentArea.svelte`, `src/lib/layout/TabBar.svelte` (`onDragAt`, `onDropAt`), and `src/lib/layout/Workbench.svelte`. A plugin view stays in the plugin layer above the panes, so a move between panes does not mount it again.
- Exceptions: In the menu of a browser tab, **New tab to the right** and **New tab below** open a new browser tab with the home page in a pane beside the tab. These items replace **Split right** and **Split down**, which opened a copy of the page in a split of plugin views only. The separate browser window keeps its own plugin split.
- Narrow layout: An area of 640 pixels or less shows the panes one above the other, in the same order and with the same ratios. The area does not scroll. Each pane keeps its own scroll bar. A tab drop opens a new pane only below.
- Evidence: `tests/smoke/layout/mixedSplits.smoke.mjs`, `tests/smoke/layout/pdfBesideNote.smoke.mjs`, `tests/smoke/layout/splits.smoke.mjs`, and `tests/unit/layout/documentPanes.spec.ts`.
- Replaces / replaced by: The document-only panes of [UI-021](#ui-021--workspace-links-in-document-panes), and the name **Split** of [UI-049](#ui-049--one-view-control-and-one-file-name).
- Limits: A tab from a different window opens in the tab bar, not in a pane. Browser checks use desktop service mocks. Native desktop acceptance remains open.
+1 -3
View File
@@ -16,7 +16,7 @@ This guide is for developers who change RuneStone's source code. To use the app,
### First run ### First run
1. Clone the repository: `https://github.com/kwyvern-gh/RuneStone.git`. 1. Clone the repository: `https://git.knottywyvern.com/kwyvern/RuneStone`.
2. In the repository folder, run `pnpm install --frozen-lockfile`. 2. In the repository folder, run `pnpm install --frozen-lockfile`.
3. Prepare the browser runtime. See [Built-in browser runtime](#built-in-browser-runtime). 3. Prepare the browser runtime. See [Built-in browser runtime](#built-in-browser-runtime).
4. Run `pnpm tauri dev`. 4. Run `pnpm tauri dev`.
@@ -232,8 +232,6 @@ Git, Background, Terminal, PDF Viewer, and Project Management are native feature
- `pdfjs-dist` is a host dependency. `src/lib/features/pdf/engine.ts` loads the minified build. The worker, the character maps, the standard fonts, and the image decoders are Vite assets of the app, so PDF.js makes no network request. `build.assetsInlineLimit` in `vite.config.js` keeps these files out of the code. - `pdfjs-dist` is a host dependency. `src/lib/features/pdf/engine.ts` loads the minified build. The worker, the character maps, the standard fonts, and the image decoders are Vite assets of the app, so PDF.js makes no network request. `build.assetsInlineLimit` in `vite.config.js` keeps these files out of the code.
- Project Management has one editor view, `planning`, with `launch: true`. The view pattern `board-<hex of the board ID>` gives each board its own tab. Its ribbon button in `PluginRibbon.svelte` calls the launch, which opens the default board of the workspace or All tasks. It has no command. - Project Management has one editor view, `planning`, with `launch: true`. The view pattern `board-<hex of the board ID>` gives each board its own tab. Its ribbon button in `PluginRibbon.svelte` calls the launch, which opens the default board of the workspace or All tasks. It has no command.
- Project Management reads and writes only `.runestone/pm/`. `storage/legacy.ts` finds data in the old format of visible notes. The interface then offers the migration, with backups in `.runestone/pm/backups/`. It migrates only after the user chooses it. - Project Management reads and writes only `.runestone/pm/`. `storage/legacy.ts` finds data in the old format of visible notes. The interface then offers the migration, with backups in `.runestone/pm/backups/`. It migrates only after the user chooses it.
- Project Management deletes no files. A description draft is `.runestone/pm/drafts/<hex of the card ID>.json`. The data of its unsaved images is in `<hex of the card ID>.images.json` in the same folder. Thus a text change does not write the images again.
Only a save of the description or the card writes `.runestone/pm/images/<image ID>.json`. **Save** and **Cancel** of the description replace the draft and its image record with empty records. As a result, a discarded draft leaves no image file.
- `pm/storage/` and `pm/model/` stay pure TypeScript without host modules, so the `runestone-project-management` skill can bundle them. They mark their user-visible text with `message()` from `storage/message.ts` and keep it in English. The interface translates that text with `localize()` in `pm/ui/text.ts`. - `pm/storage/` and `pm/model/` stay pure TypeScript without host modules, so the `runestone-project-management` skill can bundle them. They mark their user-visible text with `message()` from `storage/message.ts` and keep it in English. The interface translates that text with `localize()` in `pm/ui/text.ts`.
- The `projectManagement` section holds the priority levels (`pmSettings.ts`). The default board is `defaultBoardId` in `.runestone/pm/workspace.json`, so each workspace has its own. Appearance → Background reads the board list from the same file through `pmBoards.ts`, without the feature code. - The `projectManagement` section holds the priority levels (`pmSettings.ts`). The default board is `defaultBoardId` in `.runestone/pm/workspace.json`, so each workspace has its own. Appearance → Background reads the board list from the same file through `pmBoards.ts`, without the feature code.
- The first start makes the `projectManagement` section from the kept settings of the Project Management plugin. When `localStorage` has no view states, it also copies the view states of the plugin. - The first start makes the `projectManagement` section from the kept settings of the Project Management plugin. When `localStorage` has no view states, it also copies the view states of the plugin.
+3 -3
View File
@@ -24,11 +24,11 @@ Select an image, then right-click it or press Shift+F10 for these actions:
- **Copy path** and **Show in Explorer**, for workspace images - **Copy path** and **Show in Explorer**, for workspace images
**Remove image**, or the Delete key, removes the image link from the note. It does not delete the file. Undo restores the link. **Remove image**, or the Delete key, removes the image link from the note. It does not delete the file. Undo restores the link.
Zoom works in Write, Read, and Read beside. It can fit the image or magnify it. Press Escape to close it. Zoom works in Write, Read, and Split. It can fit the image or magnify it. Press Escape to close it.
## Read diagrams and document properties ## Read diagrams and document properties
Write, Read, and Read beside show wiki links, note callouts, and Mermaid diagrams. Write, Read, and Split show wiki links, note callouts, and Mermaid diagrams.
RuneStone renders Mermaid diagrams locally. If a diagram is not valid, RuneStone shows an error message and the diagram source. RuneStone renders Mermaid diagrams locally. If a diagram is not valid, RuneStone shows an error message and the diagram source.
Read shows frontmatter in a collapsed **Properties** section. Read shows frontmatter in a collapsed **Properties** section.
@@ -97,7 +97,7 @@ Start a cell with `=` to make a formula. Columns use letters A, B, … AA. Row 1
| Functions | SUM, AVERAGE, MIN, MAX, COUNT, ABS, and ROUND | | Functions | SUM, AVERAGE, MIN, MAX, COUNT, ABS, and ROUND |
Functions that take a range ignore text and blank cells. Arithmetic uses zero for a blank cell. Functions that take a range ignore text and blank cells. Arithmetic uses zero for a blank cell.
Results update in Write, Read, and Read beside. Select a result to edit its formula. Enter saves the formula, and Tab moves to the next cell. Results update in Write, Read, and Split. Select a result to edit its formula. Enter saves the formula, and Tab moves to the next cell.
The **Formulas** control below each table explains the syntax. The active cell shows its address. The **Formulas** control below each table explains the syntax. The active cell shows its address.
A formula that is not valid, a missing cell, or a circular reference shows an error label. A formula that is not valid, a missing cell, or a circular reference shows an error label.
-1
View File
@@ -52,7 +52,6 @@ A card can be on more than one board, with a different list on each board.
The card details have the title, the labels, and the description in Markdown. The card details have the title, the labels, and the description in Markdown.
A change to the description stays a draft until you select **Save**. **Cancel** restores the saved text. When you close the card with a draft, the card shows an unsaved marker. A change to the description stays a draft until you select **Save**. **Cancel** restores the saved text. When you close the card with a draft, the card shows an unsaved marker.
An image that you paste or drop into a draft stays with the draft. **Save** adds the image to the card. **Cancel** removes it.
Board and list changes save at once. Other fields save when you close the card details. Board and list changes save at once. Other fields save when you close the card details.
### Card details ### Card details
+34 -32
View File
@@ -2,32 +2,23 @@
[RuneStone](../README.md) · [User guide](user-guide.md) [RuneStone](../README.md) · [User guide](user-guide.md)
This guide installs, updates, or reinstalls RuneStone from a release file or from a package that you build. This guide installs, updates, or reinstalls RuneStone from a supplied release file.
| Platform | Release file | Notes | | Platform | Release file | Notes |
| --- | --- | --- | | --- | --- | --- |
| Windows 10 or 11, x64 | [RuneStone_1.0.0_x64-setup.exe](https://github.com/kwyvern-gh/RuneStone/releases/download/v1.0.0/RuneStone_1.0.0_x64-setup.exe) | Installs for the current Windows account | | Windows 10 or 11, x64 | [RuneStone_0.1.53_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.53/RuneStone_0.1.53_x64-setup.exe) | Installs for the current Windows account |
| macOS, Apple silicon | None | Build the app from source. See [macOS packages](builds.md#macos-packages). Intel Macs are not supported. | | macOS, Apple silicon | [RuneStone_0.1.44_aarch64.dmg](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_aarch64.dmg) | Experimental. Intel Macs are not supported. |
| Linux, amd64 | None | Build a Debian package from source. See [Build Linux packages](builds.md#build-linux-packages). | | Linux, amd64 | [RuneStone_0.1.51_amd64.deb](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.51/RuneStone_0.1.51_amd64.deb) | Experimental. Built on Ubuntu 26.04.1. Needs GLIBC 2.39 or newer. |
On Windows, you do not need Node.js, Rust, or a source checkout. You do not need Node.js, Rust, or a source checkout.
The built-in browser needs a separate engine download. See [Use the built-in browser](user-guide.md#use-the-built-in-browser). On Windows, the built-in browser needs a separate engine download. See [Use the built-in browser](user-guide.md#use-the-built-in-browser).
## Install on Windows ## Install on Windows
1. Save `RuneStone_1.0.0_x64-setup.exe` and [windows-SHA256SUMS](https://github.com/kwyvern-gh/RuneStone/raw/master/docs/checksums/1.0.0/windows-SHA256SUMS) to Downloads. 1. Save `RuneStone_0.1.53_x64-setup.exe` to Downloads.
2. Open PowerShell in Downloads. 2. Open the file.
3. Check the download: 3. Complete setup. Keep the default destination unless you need another location.
4. Open RuneStone from the Start menu.
```powershell
$expected = (Get-Content .\windows-SHA256SUMS).Split(' ')[0]
(Get-FileHash .\RuneStone_1.0.0_x64-setup.exe).Hash -eq $expected
```
If the result is not `True`, delete the file and download it again.
4. Open the setup file.
5. Complete setup. Keep the default destination unless you need another location.
6. Open RuneStone from the Start menu.
## Update or reinstall on Windows ## Update or reinstall on Windows
@@ -42,30 +33,41 @@ After an update from 0.1.48 or earlier, a browser tab asks you to download the b
## Install on macOS ## Install on macOS
Build the app on an Apple silicon Mac first. See [macOS packages](builds.md#macos-packages). 1. Save `RuneStone_0.1.44_aarch64.dmg` to Downloads.
2. Open the disk image.
3. Drag RuneStone into Applications.
4. Eject the disk image.
5. Open RuneStone from Applications.
1. Copy `RuneStone.app` from `src-tauri/target/release/bundle/macos/` into Applications. The app has an ad hoc signature and is not notarized by Apple.
2. Open RuneStone from Applications. If macOS blocks the first launch, open **System Settings → Privacy & Security** and choose **Open Anyway**.
## Update or reinstall on macOS ## Update or reinstall on macOS
1. Save your documents and quit RuneStone. 1. Save your documents and quit RuneStone.
2. Build the same or a newer version. 2. Open the disk image for the same or a newer version.
3. Copy the new `RuneStone.app` into Applications and confirm the replacement. 3. Drag RuneStone into Applications and confirm the replacement.
4. Open RuneStone from Applications. 4. Eject the disk image.
5. Open RuneStone from Applications.
## Install on Linux ## Install on Linux
Build the Debian package first. See [Build Linux packages](builds.md#build-linux-packages). 1. Save `RuneStone_0.1.51_amd64.deb` and [linux-SHA256SUMS](https://git.knottywyvern.com/kwyvern/RuneStone/raw/branch/master/docs/checksums/0.1.51/linux-SHA256SUMS) to Downloads.
2. Open Terminal in Downloads.
1. Open Terminal in the folder that contains the package. 3. Check the download:
2. Install the package. Use the file name of your build:
```bash ```bash
sudo apt install ./RuneStone_1.0.0_amd64.deb sha256sum --check linux-SHA256SUMS
``` ```
3. Open RuneStone from your applications menu, or run `runestone` in Terminal. If the result is not `OK`, delete the file and download it again.
4. Install the package:
```bash
sudo apt install ./RuneStone_0.1.51_amd64.deb
```
5. Open RuneStone from your applications menu, or run `runestone` in Terminal.
APT installs the system libraries that the package declares. Run RuneStone as your ordinary desktop user. APT installs the system libraries that the package declares. Run RuneStone as your ordinary desktop user.
@@ -75,4 +77,4 @@ APT installs the system libraries that the package declares. Run RuneStone as yo
2. Open Terminal in the folder that contains the new package. 2. Open Terminal in the folder that contains the new package.
3. Install the newer package with the same `sudo apt install ./<file>.deb` command. 3. Install the newer package with the same `sudo apt install ./<file>.deb` command.
To reinstall the same version, run `sudo apt install --reinstall ./<file>.deb`. To reinstall the same version, run `sudo apt install --reinstall ./RuneStone_0.1.51_amd64.deb`.
+2 -2
View File
@@ -20,7 +20,7 @@ The plugin SDK `@runestone/plugin-sdk` gives the API types, the feature checks,
Install it in each plugin project from the URL of its package file on the RuneStone releases page. Install it in each plugin project from the URL of its package file on the RuneStone releases page.
```sh ```sh
pnpm add -D "https://github.com/kwyvern-gh/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz" pnpm add -D "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
``` ```
- Always give the full URL. The SDK is not on the npm registry, and another account owns the `@runestone` scope there. - Always give the full URL. The SDK is not on the npm registry, and another account owns the `@runestone` scope there.
@@ -146,7 +146,7 @@ For the RuneStone source setup, see [Run from source](development.md#run-from-so
### Example: CSV Viewer ### Example: CSV Viewer
Source: the CSV Viewer repository, a private repository: its `package.json`, `plugin.json`, `scripts/build.mjs`, and `README.md`. Source: [CSV Viewer repository](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer), its `package.json`, `plugin.json`, `scripts/build.mjs`, and `README.md`.
| Item | Value | | Item | Value |
| --- | --- | | --- | --- |
+8 -1
View File
@@ -2,7 +2,7 @@
[RuneStone](../README.md) · [User guide](user-guide.md) [RuneStone](../README.md) · [User guide](user-guide.md)
This guide explains how to install, enable, update, and remove optional plugins. This guide explains how to install, enable, update, and remove optional plugins such as CSV Viewer and Local Autocomplete.
Manage all plugins in **Settings → Plug-ins**. The built-in browser, table formulas, Git, Background, Terminal, PDF Viewer, and Project Management are not plugins. To turn Git, Background, Terminal, PDF Viewer, or Project Management off, see [Turn features on or off](user-guide.md#turn-features-on-or-off). Manage all plugins in **Settings → Plug-ins**. The built-in browser, table formulas, Git, Background, Terminal, PDF Viewer, and Project Management are not plugins. To turn Git, Background, Terminal, PDF Viewer, or Project Management off, see [Turn features on or off](user-guide.md#turn-features-on-or-off).
@@ -71,6 +71,13 @@ To install a prerelease, enter its tag. The release must have exactly one plugin
Use HTTPS for a remote server. HTTP sends the token and the package without encryption. Use HTTPS for a remote server. HTTP sends the token and the package without encryption.
RuneStone uses the token for this request only and does not save it. RuneStone uses the token for this request only and does not save it.
## Plugin guides
| Plugin | Guide |
| --- | --- |
| Local Autocomplete | [Local Autocomplete trial guide](https://git.knottywyvern.com/kwyvern/RuneStone_LocalModel/src/branch/main/docs/trial-guide.md) |
| CSV Viewer | [CSV Viewer README](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer/src/branch/main/README.md) |
## Plugin help ## Plugin help
| Problem | Action | | Problem | Action |
+2 -2
View File
@@ -88,7 +88,7 @@ The installer, engine, and SDK scripts stop if the release file exists. The plug
## Publish an installer ## Publish an installer
Publish RuneStone installers on the [RuneStone releases page](https://github.com/kwyvern-gh/RuneStone/releases). Browser engine ZIPs and SDK packages use the same page. Publish RuneStone installers on the [RuneStone releases page](https://git.knottywyvern.com/kwyvern/RuneStone/releases). Browser engine ZIPs and SDK packages use the same page.
1. Build the installer and complete the [installer checks](builds.md#installer-checks). 1. Build the installer and complete the [installer checks](builds.md#installer-checks).
2. Create a release with the tag `v<version>` on the commit that sets the version. 2. Create a release with the tag `v<version>` on the commit that sets the version.
@@ -181,7 +181,7 @@ Plugin authors install the SDK from the URL of that file. See [Install the SDK](
1. Commit the SDK changes in RuneStone. Run `pnpm check` and `pnpm test`. 1. Commit the SDK changes in RuneStone. Run `pnpm check` and `pnpm test`.
2. Run `pnpm release:sdk --release-url <folder URL> --version <version> --dry-run`. Read the plan. 2. Run `pnpm release:sdk --release-url <folder URL> --version <version> --dry-run`. Read the plan.
The folder URL is the download folder of the release, for example `https://github.com/kwyvern-gh/RuneStone/releases/download/plugin-sdk-v0.1.2`. The folder URL is the download folder of the release, for example `https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2`.
3. Run the same command without `--dry-run`. 3. Run the same command without `--dry-run`.
4. On the RuneStone releases page, create a release with the tag `plugin-sdk-v<version>` on the `source` commit in `sdk.json`. 4. On the RuneStone releases page, create a release with the tag `plugin-sdk-v<version>` on the `source` commit in `sdk.json`.
5. Attach only the `.tgz` file. Leave the release description empty. 5. Attach only the `.tgz` file. Leave the release description empty.
+2 -2
View File
@@ -150,7 +150,7 @@ Decisions: [UI-002](design-decisions.md#ui-002--share-the-requested-dropdown-des
- The main header holds navigation, document tabs, Save, the outline toggle, and window controls. The other tools are in the left ribbon, so the tabs keep their room. A detached tab window has no ribbon, so its header keeps those tools. - The main header holds navigation, document tabs, Save, the outline toggle, and window controls. The other tools are in the left ribbon, so the tabs keep their room. A detached tab window has no ribbon, so its header keeps those tools.
- A bar at the bottom of the side pane holds the workspace switcher, Help, and Settings, as in Obsidian. The switcher names the workspace and opens the workspace list above it. - A bar at the bottom of the side pane holds the workspace switcher, Help, and Settings, as in Obsidian. The switcher names the workspace and opens the workspace list above it.
- The left ribbon is always present. It holds the tools, then a line, then the plugin view shortcuts. The tools are New browser tab, Terminal, Project Management, Plug-in views, and Commands. A tool of an off feature does not show. Its menus open at its right. While the side pane is closed, the workspace switcher, Help, and Settings move to the bottom of the ribbon, so they stay reachable. - The left ribbon is always present. It holds the tools, then a line, then the plugin view shortcuts. The tools are New browser tab, Terminal, Project Management, Plug-in views, and Commands. A tool of an off feature does not show. Its menus open at its right. While the side pane is closed, the workspace switcher, Help, and Settings move to the bottom of the ribbon, so they stay reachable.
- Tabs keep a minimum width of 120 pixels and scroll. Fades show tabs out of view, and ⌄ lists all tabs. A drag area after the tabs fills the free space of the header. The tabs use all space up to a drag area of 48 pixels before they scroll ([UI-062](design-decisions.md#ui-062--tabs-use-the-free-header-space)). - Tabs keep a minimum width of 120 pixels and scroll. Fades show tabs out of view, and ⌄ lists all tabs. A drag area of 120 pixels sits after the tabs. In a narrow header, the tabs shrink first, and the drag area keeps at least 48 pixels.
- Windows and Linux title bars use square caption buttons, 46 pixels wide and full height. Rest the pointer on maximize for Snap Layouts on Windows 11. macOS keeps its native traffic lights, and title bars leave `--rs-titlebar-inset-start` free for them. - Windows and Linux title bars use square caption buttons, 46 pixels wide and full height. Rest the pointer on maximize for Snap Layouts on Windows 11. macOS keeps its native traffic lights, and title bars leave `--rs-titlebar-inset-start` free for them.
- Files, Search, Bookmarks, Source control (while Git is on), and the sidebar views of installed plugins share the top navigation group. The active navigation button shows which view fills the left pane. - Files, Search, Bookmarks, Source control (while Git is on), and the sidebar views of installed plugins share the top navigation group. The active navigation button shows which view fills the left pane.
- Plugin editor views can use the left ribbon. - Plugin editor views can use the left ribbon.
@@ -222,7 +222,7 @@ Decisions: [UI-009](design-decisions.md#ui-009--character-theme-appearances), [U
- The app image fills the work area below the titlebar, including new tabs and document views. It stays fixed while content scrolls. - The app image fills the work area below the titlebar, including new tabs and document views. It stays fixed while content scrolls.
- Sidebars use `--rs-image-sidebar-bg` (82% tint). Editor surfaces use `--rs-image-editor-bg` (90% tint). Without an image, both are opaque. - Sidebars use `--rs-image-sidebar-bg` (82% tint). Editor surfaces use `--rs-image-editor-bg` (90% tint). Without an image, both are opaque.
- Write, Source, Read, and Read beside share the editor surface. CodeMirror layers stay transparent above it. - Write, Source, Read, and Split share the editor surface. CodeMirror layers stay transparent above it.
- Code blocks in Write and Read use `--rs-code-block-bg`. - Code blocks in Write and Read use `--rs-code-block-bg`.
- Hovered rows and controls in the work area, hovered menu rows, and the workspace button use `--rs-hover-bg`. With an image, it is a 6% veil of the strong text color. The image stays visible, and the hover shows over light and dark image areas. Dialogs and Settings keep opaque fills. - Hovered rows and controls in the work area, hovered menu rows, and the workspace button use `--rs-hover-bg`. With an image, it is a 6% veil of the strong text color. The image stays visible, and the hover shows over light and dark image areas. Dialogs and Settings keep opaque fills.
- New-tab buttons use `--rs-image-control-bg` and `--rs-image-control-hover-bg`. Their tint keeps labels readable while the image stays visible. The new-tab screen shows only its action buttons, with icons, labels, and shortcuts. - New-tab buttons use `--rs-image-control-bg` and `--rs-image-control-hover-bg`. Their tint keeps labels readable while the image stays visible. The new-tab screen shows only its action buttons, with icons, labels, and shortcuts.
+8 -28
View File
@@ -75,14 +75,14 @@ On macOS and Linux, you can still open, edit, rename, and delete existing files
## Edit documents ## Edit documents
Each document pane has one view control with three choices, and a **Read beside** button: Each document pane has one view control with three choices, and a **Split** button:
| Choice | Shows | | Choice | Shows |
| --- | --- | | --- | --- |
| **Write** | Formatted Markdown. The active line shows its Markdown source. | | **Write** | Formatted Markdown. The active line shows its Markdown source. |
| **Source** | The plain source with line numbers and syntax colors | | **Source** | The plain source with line numbers and syntax colors |
| **Read** | The rendered document, without editing. Markdown files only. | | **Read** | The rendered document, without editing. Markdown files only. |
| **Read beside** | Read beside Write or Source. Narrow panes stack the two views. Select **Read beside** again to close it. Markdown files only. | | **Split** | Read beside Write or Source. Narrow panes stack the two views. Select **Split** again to close it. Markdown files only. |
Press Ctrl+E to switch between Write and Source. Press Ctrl+Shift+E to switch between Read and the editor. The tab menu has the same choices under **View**. Press Ctrl+E to switch between Write and Source. Press Ctrl+Shift+E to switch between Read and the editor. The tab menu has the same choices under **View**.
The control shows icons only. Hover over an icon, or focus it with the keyboard, to see its name and shortcut. The arrow keys move the choice. The control shows icons only. Hover over an icon, or focus it with the keyboard, to see its name and shortcut. The arrow keys move the choice.
@@ -103,9 +103,9 @@ Read follows CommonMark: a single line break inside a paragraph is a space. To s
- Ctrl+click a link in Write or Source. In Read, a normal click follows the link. - Ctrl+click a link in Write or Source. In Read, a normal click follows the link.
- A workspace file link opens in a new tab and keeps the current document open. - A workspace file link opens in a new tab and keeps the current document open.
- A heading link, such as `guide.md#save-your-work` or `#save-your-work`, puts that heading at the top of the view. A heading near the end of a short document stays lower. - A heading link, such as `guide.md#save-your-work` or `#save-your-work`, scrolls to that heading.
- A wiki link, such as `[[Meeting notes]]`, finds the note by name anywhere in the workspace. If two notes have the same name, use a relative or workspace path. - A wiki link, such as `[[Meeting notes]]`, finds the note by name anywhere in the workspace. If two notes have the same name, use a relative or workspace path.
- The **Backlinks** section below the outline lists notes that link to the current note. Select an entry to open it. Select the **Backlinks** title to collapse or expand the section. RuneStone keeps that choice for all notes and after a restart. - The **Backlinks** section below the outline lists notes that link to the current note. Select an entry to open it.
If backlinks look out of date, select **Rebuild note index**. Your Markdown files do not depend on this index. If backlinks look out of date, select **Rebuild note index**. Your Markdown files do not depend on this index.
@@ -136,17 +136,15 @@ Select a PDF file in the file tree. It opens in its own tab. The file tree marks
| Action | How | | Action | How |
| --- | --- | | --- | --- |
| Scroll through the pages | Use the wheel or the scroll bar. With the page area focused, use Page Up, Page Down, Home, End, and the arrow keys. | | Change the page | Select **Previous page** or **Next page**. Or type a number in the page field and press Enter. With the page area focused, press Page Up or Page Down. |
| Go to a page | Select **Previous page** or **Next page**. Or type a number in the page field and press Enter. | | Zoom | Select **Zoom in** or **Zoom out**, from 25% to 400%. **Fit width** fits the page to the tab again. |
| Zoom | Select **Zoom in** or **Zoom out**. Or type a percent in the zoom field and press Enter. Or hold Ctrl and turn the wheel. The zoom is from 25% to 400%. **Fit width** fits the pages to the tab again. | | Rotate | Select **Rotate clockwise**. Each click turns the page by 90 degrees. |
| Rotate | Select **Rotate clockwise**. Each click turns the pages by 90 degrees. |
| Copy text | Select text on the page with the pointer, then press Ctrl+C. | | Copy text | Select text on the page with the pointer, then press Ctrl+C. |
| Show changes from another program | Select **Reload PDF**. The tab stays on the same page. | | Show changes from another program | Select **Reload PDF**. The tab stays on the same page. |
| Open a protected PDF | Type the password, then select **Unlock**. RuneStone does not save the password. | | Open a protected PDF | Type the password, then select **Unlock**. RuneStone does not save the password. |
- A PDF file must be in the workspace and at most 64 MiB. - A PDF file must be in the workspace and at most 64 MiB.
- The tab shows all pages in one column. The page field shows the page that fills most of the tab. After Ctrl+Tab, the keyboard scrolls the new PDF tab at once. - The tab shows one page at a time. It does not edit PDF files, fill forms, open links, run scripts in a PDF, or print.
- The tab does not edit PDF files, fill forms, open links, run scripts in a PDF, or print.
- Scanned pages show as images, so you cannot select their text. - Scanned pages show as images, so you cannot select their text.
- If a PDF does not open, the tab shows the error. Select **Reload PDF**, or try another copy of the file. - If a PDF does not open, the tab shows the error. Select **Reload PDF**, or try another copy of the file.
@@ -184,24 +182,6 @@ If the move fails, the source tab stays open.
When you start RuneStone again, it opens the document tabs of the workspace. It keeps their order, pins, and active tab. When you start RuneStone again, it opens the document tabs of the workspace. It keeps their order, pins, and active tab.
This includes PDF tabs and plugin tabs that show a file. RuneStone reads the contents again from disk. Missing files do not stop the other tabs from opening. This includes PDF tabs and plugin tabs that show a file. RuneStone reads the contents again from disk. Missing files do not stop the other tabs from opening.
### Show tabs side by side
Use panes to see two tabs at the same time. For example, browse the web or read a PDF file in one pane, and write a note in the other pane.
1. Right-click a tab that is not visible, or a file in the file tree.
2. Select **Open to the right**.
The tab opens in a new pane to the right of the active pane. A pane shows a document, a PDF file, or a plugin tab, for example a browser tab. A tab shows in one pane at a time.
You can also drag a tab from the tab bar to a pane. A drop on the middle of the pane shows the tab in that pane. A drop on the right or bottom part opens a new pane there. A hint shows the place before you release the tab.
- Click a pane to make its tab the active tab. A tab that you select, or a file that you open, replaces the content of the active pane. The replaced tab stays open.
- Drag the divider between two panes to change their sizes. Double-click the divider to give the panes equal sizes. With the keyboard, focus the divider and use the arrow keys.
- A pane beside other panes names its file in the bar above the document. Select **Close split** in that bar to close the pane. The tab stays open.
- A browser tab or a PDF tab that fills the area moves to the left pane when a tab opens to the right. When one pane is left, its tab fills the area again.
- In the menu of a browser tab, **New tab to the right** and **New tab below** open a new browser tab with the home page in a pane beside it.
- The link menu also has **Open to the right**. In a narrow window, the panes show one above the other.
## Save your work ## Save your work
Auto-save is on by default. It saves changed files every 5 seconds, also in background tabs. RuneStone does not write unchanged files. Auto-save is on by default. It saves changed files every 5 seconds, also in background tabs. RuneStone does not write unchanged files.
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "runestone", "name": "runestone",
"version": "1.0.1c", "version": "0.1.53",
"description": "Desktop editor for a local workspace", "description": "Desktop editor for a local workspace",
"type": "module", "type": "module",
"scripts": { "scripts": {
@@ -25,7 +25,7 @@
"sdk:build": "node scripts/buildSdk.mjs", "sdk:build": "node scripts/buildSdk.mjs",
"release:sdk": "node scripts/releaseSdk.mjs" "release:sdk": "node scripts/releaseSdk.mjs"
}, },
"license": "Apache-2.0", "license": "MIT",
"dependencies": { "dependencies": {
"@codemirror/autocomplete": "^6.20.3", "@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1", "@codemirror/commands": "^6.11.1",
+9 -9
View File
@@ -1,6 +1,6 @@
# RuneStone Plugin SDK # RuneStone Plugin SDK
`@runestone/plugin-sdk` gives TypeScript types and small helpers for [RuneStone](https://github.com/kwyvern-gh/RuneStone) plugins. `@runestone/plugin-sdk` gives TypeScript types and small helpers for [RuneStone](https://git.knottywyvern.com/kwyvern/RuneStone) plugins.
RuneStone is a desktop workspace for Markdown notes, code, and project work. Plugins add views, commands, and document editors to it. RuneStone is a desktop workspace for Markdown notes, code, and project work. Plugins add views, commands, and document editors to it.
The SDK contains: The SDK contains:
@@ -17,7 +17,7 @@ The SDK does not run plugins and does not call RuneStone. RuneStone gives the `a
Install the SDK from the URL of its package file on the RuneStone releases page. Install the SDK from the URL of its package file on the RuneStone releases page.
```sh ```sh
pnpm add -D "https://github.com/kwyvern-gh/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz" pnpm add -D "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
``` ```
The result in `package.json`: The result in `package.json`:
@@ -25,7 +25,7 @@ The result in `package.json`:
```json ```json
{ {
"devDependencies": { "devDependencies": {
"@runestone/plugin-sdk": "https://github.com/kwyvern-gh/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz" "@runestone/plugin-sdk": "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
} }
} }
``` ```
@@ -60,7 +60,7 @@ export function activate(api: PluginApi) {
``` ```
Compile the module with a bundler, so the entry file contains the SDK helpers that it uses. RuneStone loads the entry from a Blob URL, so imports from `node_modules` do not resolve at run time. Compile the module with a bundler, so the entry file contains the SDK helpers that it uses. RuneStone loads the entry from a Blob URL, so imports from `node_modules` do not resolve at run time.
Then make the plugin ZIP. See [Build and package a plugin](https://github.com/kwyvern-gh/RuneStone/blob/master/docs/plugin-development.md#build-and-package-a-plugin). Then make the plugin ZIP. See [Build and package a plugin](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugin-development.md#build-and-package-a-plugin).
A type-only import, such as `import type { PluginApi }`, adds no code to the bundle. A type-only import, such as `import type { PluginApi }`, adds no code to the bundle.
@@ -128,12 +128,12 @@ A new SDK release can add types for new RuneStone features. Use the feature chec
## Documentation and help ## Documentation and help
- [Plugin development reference](https://github.com/kwyvern-gh/RuneStone/blob/master/docs/plugin-development.md): the package format, the API, and the build procedure - [Plugin development reference](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugin-development.md): the package format, the API, and the build procedure
- [Completion API](https://github.com/kwyvern-gh/RuneStone/blob/master/docs/completion.md) - [Completion API](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/completion.md)
- [Install and manage plugins](https://github.com/kwyvern-gh/RuneStone/blob/master/docs/plugins.md) - [Install and manage plugins](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugins.md)
- [Release policy](https://github.com/kwyvern-gh/RuneStone/blob/master/docs/releases.md#sdk-releases) - [Release policy](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/releases.md#sdk-releases)
The SDK source is in the `packages/plugin-sdk` folder of the [RuneStone repository](https://github.com/kwyvern-gh/RuneStone). Report problems there. The SDK source is in the `packages/plugin-sdk` folder of the [RuneStone repository](https://git.knottywyvern.com/kwyvern/RuneStone). Report problems there.
Knotty Wyvern maintains RuneStone and the SDK. Knotty Wyvern maintains RuneStone and the SDK.
+1 -1
View File
@@ -3130,7 +3130,7 @@ dependencies = [
[[package]] [[package]]
name = "runestone" name = "runestone"
version = "1.0.1+3" version = "0.1.53"
dependencies = [ dependencies = [
"base64 0.23.1", "base64 0.23.1",
"dunce", "dunce",
+2 -3
View File
@@ -1,9 +1,8 @@
[package] [package]
name = "runestone" name = "runestone"
version = "1.0.1+3" version = "0.1.53"
description = "Writing workspace plus script editor" description = "Writing workspace plus script editor"
authors = ["Knotty Wyvern"] authors = ["Knotty Wyvern"]
license = "Apache-2.0"
edition = "2021" edition = "2021"
[lib] [lib]
@@ -47,4 +46,4 @@ opt-level = 3
strip = true strip = true
[package.metadata.runestone] [package.metadata.runestone]
version = "1.0.1c" version = "0.1.53"
+1 -1
View File
@@ -3,7 +3,7 @@
"protocol": 1, "protocol": 1,
"platforms": { "platforms": {
"windows-x86_64": { "windows-x86_64": {
"url": "https://github.com/kwyvern-gh/RuneStone/releases/download/browser-engine-v0.1.11/RuneStone-Browser_0.1.11_win32-x64.zip", "url": "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/browser-engine-v0.1.11/RuneStone-Browser_0.1.11_win32-x64.zip",
"bytes": 163623801, "bytes": 163623801,
"sha256": "1e0153b134cebe882b36f74e1f3c2a4ed37acb2caca10548034a8b5d88738d26" "sha256": "1e0153b134cebe882b36f74e1f3c2a4ed37acb2caca10548034a8b5d88738d26"
} }
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "RuneStone", "productName": "RuneStone",
"version": "1.0.1+3", "version": "0.1.53",
"identifier": "com.runestone.app", "identifier": "com.runestone.app",
"build": { "build": {
"beforeDevCommand": "pnpm dev", "beforeDevCommand": "pnpm dev",
+3 -4
View File
@@ -47,10 +47,9 @@ export async function activate(api: PluginApi) {
const id = `tab-${crypto.randomUUID()}`; const id = `tab-${crypto.randomUUID()}`;
const saved: SavedView = { view: id, profileId, url, runtimeId: '' }; const saved: SavedView = { view: id, profileId, url, runtimeId: '' };
const run = (command: string, args?: Record<string, unknown>) => { void saved.control?.action(command, args); }; const run = (command: string, args?: Record<string, unknown>) => { void saved.control?.action(command, args); };
// A new tab with the home page of the profile opens in a pane beside this tab.
const split = (direction: 'right' | 'down') => { const split = (direction: 'right' | 'down') => {
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId); const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
void open(current?.profileId || saved.profileId, undefined, { split: direction, relativeTo: id }); void open(current?.profileId || saved.profileId, current?.url || saved.url || 'about:blank', { split: direction, relativeTo: id });
}; };
api.registerView({ id, title: 'Browser', placement: 'editor', icon: 'globe', pinned, launcher: false, api.registerView({ id, title: 'Browser', placement: 'editor', icon: 'globe', pinned, launcher: false,
tabDragData: ({ pinned }) => { tabDragData: ({ pinned }) => {
@@ -66,8 +65,8 @@ export async function activate(api: PluginApi) {
return [ return [
{ separator: true }, { separator: true },
{ label: tr("Move to new window"), icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) }, { label: tr("Move to new window"), icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
{ label: tr("New tab to the right"), icon: 'split-right', disabled: !ready, run: () => split('right') }, { label: tr("Split right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
{ label: tr("New tab below"), icon: 'split-down', disabled: !ready, run: () => split('down') }, { label: tr("Split down"), icon: 'split-down', disabled: !ready, run: () => split('down') },
{ separator: true }, { separator: true },
{ label: tr("Find…"), icon: 'search', shortcut: keys('Mod+F'), disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } }, { label: tr("Find…"), icon: 'search', shortcut: keys('Mod+F'), disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
{ label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') }, { label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') },
+3 -13
View File
@@ -13,10 +13,8 @@
import type { Chrome, OpenBuffer } from "$lib/workspace/types"; import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api"; import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
import { linkCandidates } from "$lib/workspace/markdownLinks"; import { linkCandidates } from "$lib/workspace/markdownLinks";
import { documentHeadings } from "$lib/workspace/headingLinks";
import { editImageSource, imageSource } from "./imageSource"; import { editImageSource, imageSource } from "./imageSource";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml"; import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { loadImageSize } from "$lib/workspace/imageSizes";
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle, pastedImageSource } from "$lib/workspace/media"; import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle, pastedImageSource } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop"; import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink"; import { workspaceFileLink } from "./workspaceFileLink";
@@ -101,12 +99,7 @@
let decoded = source; let decoded = source;
try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ } try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ }
for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) { for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) {
try { try { urls.set(source, await workspaceReadDataUrl(candidate)); return; } catch { /* Try attachment location. */ }
const url = await workspaceReadDataUrl(candidate);
await loadImageSize(url);
urls.set(source, url);
return;
} catch { /* Try attachment location. */ }
} }
})(); })();
loading.set(source, task); loading.set(source, task);
@@ -441,11 +434,8 @@
const view = editor; const view = editor;
if (!view || line == null) return; if (!view || line == null) return;
untrack(() => { untrack(() => {
const number = Math.min(view.state.doc.lines, Math.max(1, line)); const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from;
const anchor = view.state.doc.line(number).from; const effects = [EditorView.scrollIntoView(anchor, { y: "center" })];
// A heading starts the text to read, so it goes to the top, as in Read. Other lines, such as a search match, stay in the center.
const heading = markdownDocument && documentHeadings(view.state.doc.toString()).some(entry => entry.line === number);
const effects = [EditorView.scrollIntoView(anchor, heading ? { y: "start", yMargin: 24 } : { y: "center" })];
foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); }); foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
view.dispatch({ selection: { anchor }, effects }); view.dispatch({ selection: { anchor }, effects });
view.focus(); view.focus();
-9
View File
@@ -5,7 +5,6 @@ import { attachTooltip } from "../ui/tooltip";
const tooltipCleanups = new WeakMap<HTMLElement, () => void>(); const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
import type { ActionMenuItem } from "../ui/actionMenu"; import type { ActionMenuItem } from "../ui/actionMenu";
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu"; import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
import { imageSize, rememberImageSize } from "../workspace/imageSizes";
export type ImageActions = { export type ImageActions = {
edit?: () => void; edit?: () => void;
@@ -57,8 +56,6 @@ function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
viewport.className = "image-lightbox-viewport"; viewport.className = "image-lightbox-viewport";
const image = original.cloneNode() as HTMLImageElement; const image = original.cloneNode() as HTMLImageElement;
image.removeAttribute("loading"); image.removeAttribute("loading");
image.removeAttribute("width");
image.removeAttribute("height");
image.draggable = false; image.draggable = false;
let scale = 0; let scale = 0;
const status = document.createElement("span"); const status = document.createElement("span");
@@ -94,12 +91,6 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
const cleanup: (() => void)[] = []; const cleanup: (() => void)[] = [];
for (const image of root.querySelectorAll<HTMLImageElement>("img[data-md-src]")) { for (const image of root.querySelectorAll<HTMLImageElement>("img[data-md-src]")) {
if (image.closest(".md-image-frame")) continue; if (image.closest(".md-image-frame")) continue;
// A remote image gives its size when it loads. The next view of this image keeps its space from the start.
const remember = () => rememberImageSize(image.src, image.naturalWidth, image.naturalHeight);
image.addEventListener("load", remember);
cleanup.push(() => image.removeEventListener("load", remember));
const known = !image.getAttribute("width") && imageSize(image.src);
if (known) { image.width = known.width; image.height = known.height; }
const frame = document.createElement("span"); const frame = document.createElement("span");
frame.className = "md-image-frame"; frame.className = "md-image-frame";
frame.contentEditable = "false"; frame.contentEditable = "false";
-2
View File
@@ -5,7 +5,6 @@ import { imageControls, type ImageActions } from "./imageControls";
import { editImageSource } from "./imageSource"; import { editImageSource } from "./imageSource";
import { requestText } from "../workspace/dialogs.svelte"; import { requestText } from "../workspace/dialogs.svelte";
import { isRemoteImage } from "../workspace/media"; import { isRemoteImage } from "../workspace/media";
import { estimatedImageHeight } from "../workspace/imageSizes";
import { actionIcon } from "../ui/actionIcons"; import { actionIcon } from "../ui/actionIcons";
export type ImageContext = { export type ImageContext = {
@@ -19,7 +18,6 @@ const cleanups = new WeakMap<HTMLElement, () => void>();
export class ImagePreview extends WidgetType { export class ImagePreview extends WidgetType {
constructor(readonly html: string, readonly source: string, readonly context: ImageContext, readonly editing = false, readonly block = true) { super(); } constructor(readonly html: string, readonly source: string, readonly context: ImageContext, readonly editing = false, readonly block = true) { super(); }
eq(other: ImagePreview) { return this.html === other.html && this.source === other.source && this.editing === other.editing && this.block === other.block; } eq(other: ImagePreview) { return this.html === other.html && this.source === other.source && this.editing === other.editing && this.block === other.block; }
get estimatedHeight() { return estimatedImageHeight(this.html); }
toDOM(view: EditorView) { toDOM(view: EditorView) {
const dom = document.createElement(this.block ? "div" : "span"); const dom = document.createElement(this.block ? "div" : "span");
dom.className = `reading writer-preview ${this.block ? "writer-image" : "writer-image-inline"}`; dom.className = `reading writer-preview ${this.block ? "writer-image" : "writer-image-inline"}`;
+13 -124
View File
@@ -4,7 +4,7 @@ import { isMac } from "../ui/shortcuts";
/** The tooltip of a link in Write. A click with Ctrl, or Cmd on macOS, opens the link. */ /** The tooltip of a link in Write. A click with Ctrl, or Cmd on macOS, opens the link. */
const linkTooltip = () => tr("{modifier}+click to open link", { modifier: isMac() ? "⌘" : "Ctrl" }); const linkTooltip = () => tr("{modifier}+click to open link", { modifier: isMac() ? "⌘" : "Ctrl" });
import { EditorSelection, StateEffect, StateField, type EditorState, type Range } from "@codemirror/state"; import { EditorSelection, StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from "@codemirror/view"; import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language"; import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
import { renderMarkdownSections } from "../workspace/noteHtml"; import { renderMarkdownSections } from "../workspace/noteHtml";
import { renderDiagrams } from "../workspace/diagrams"; import { renderDiagrams } from "../workspace/diagrams";
@@ -22,34 +22,9 @@ import { listLabels } from "./markdownLists";
import { activeTableFormulas } from "../formulas/index.ts"; import { activeTableFormulas } from "../formulas/index.ts";
const previewFormulas = new WeakMap<HTMLElement, unknown>(); const previewFormulas = new WeakMap<HTMLElement, unknown>();
const previewHtml = new WeakMap<HTMLElement, string>();
export const refreshImages = StateEffect.define<void>(); export const refreshImages = StateEffect.define<void>();
const imageCleanups = new WeakMap<HTMLElement, () => void>(); const imageCleanups = new WeakMap<HTMLElement, () => void>();
/**
* CodeMirror reads the line height of the document from the first short line that holds only plain text.
* A different height makes it estimate all heights again, and the view then jumps to other text.
* A mark span keeps a line with a different height out of that reading.
*/
const otherLineHeight = Decoration.mark({ class: "writer-line-text" });
// A resize observer records the height of a preview without a CodeMirror measure request.
// A request from toDOM restarts the layout loop of CodeMirror, and a loop that restarts too often does not restore the scroll position.
const previewHeights = new WeakMap<Element, { value: number }>();
let previewSizes: ResizeObserver | undefined;
function watchPreviewHeight(dom: HTMLElement, height: { value: number }) {
previewSizes ??= new ResizeObserver(entries => {
for (const { target } of entries) {
const holder = previewHeights.get(target);
if (holder && target.isConnected) holder.value = (target as HTMLElement).offsetHeight;
}
});
const known = previewHeights.get(dom);
if (known && known !== height) height.value = known.value;
previewHeights.set(dom, height);
previewSizes.observe(dom);
}
const linkTooltips = ViewPlugin.define(view => { const linkTooltips = ViewPlugin.define(view => {
const attached = new Map<HTMLElement, () => void>(); const attached = new Map<HTMLElement, () => void>();
const refresh = () => { const refresh = () => {
@@ -144,35 +119,23 @@ class ListLabel extends WidgetType {
ignoreEvent() { return false; } ignoreEvent() { return false; }
} }
/**
* The heights of previews, by their HTML, from a layout outside the editor. CodeMirror draws only the lines near the view.
* Without a height, a large table counts as one line until its first draw. The document then grows by thousands of pixels
* at one time, the scrollbar moves, and the layout loop of CodeMirror can stop before it restores the scroll position.
*/
const measuredHeights = new Map<string, { width: number; height: number }>();
const maxMeasuredHeights = 1000;
class Preview extends WidgetType { class Preview extends WidgetType {
readonly formulas = activeTableFormulas(); readonly formulas = activeTableFormulas();
readonly estimate: number; constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) { super(); }
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) { get estimatedHeight() { return this.height.value; }
super(); eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; }
this.estimate = measuredHeights.get(html)?.height ?? -1; measure(dom: HTMLElement, view: EditorView) {
view.requestMeasure({ key: this.height, read: () => dom.offsetHeight, write: height => { this.height.value = height; } });
} }
get estimatedHeight() { return this.height.value >= 0 ? this.height.value : this.estimate; } updateDOM(dom: HTMLElement, view: EditorView) {
// A new estimate must reach the height map of CodeMirror. updateDOM keeps the drawn table. if (previewFormulas.get(dom) !== this.formulas || tableEditors.get(dom)?.source !== this.source) return false;
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible && other.estimate === this.estimate; } this.measure(dom, view);
updateDOM(dom: HTMLElement) {
const table = tableEditors.get(dom);
if (previewFormulas.get(dom) !== this.formulas || (table ? table.source !== this.source : previewHtml.get(dom) !== this.html)) return false;
watchPreviewHeight(dom, this.height);
return true; return true;
} }
destroy(dom: HTMLElement) { previewSizes?.unobserve(dom); tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); } destroy(dom: HTMLElement) { tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
toDOM(view: EditorView) { toDOM(view: EditorView) {
const dom = document.createElement("div"); const dom = document.createElement("div");
previewFormulas.set(dom, this.formulas); previewFormulas.set(dom, this.formulas);
previewHtml.set(dom, this.html);
dom.className = "reading writer-preview"; dom.className = "reading writer-preview";
dom.innerHTML = this.html; dom.innerHTML = this.html;
// Widgets handle their own events, so CodeMirror's link handler cannot run. // Widgets handle their own events, so CodeMirror's link handler cannot run.
@@ -190,7 +153,7 @@ class Preview extends WidgetType {
}, { capture: true }); }, { capture: true });
tableControls(dom, view, this.source, this.actions); tableControls(dom, view, this.source, this.actions);
imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); })); imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); }));
watchPreviewHeight(dom, this.height); this.measure(dom, view);
dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove()); dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove());
dom.addEventListener("mousedown", event => { dom.addEventListener("mousedown", event => {
if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return; if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return;
@@ -211,45 +174,6 @@ class Preview extends WidgetType {
ignoreEvent() { return true; } ignoreEvent() { return true; }
} }
function textColumnWidth(view: EditorView) {
const style = getComputedStyle(view.contentDOM);
return view.contentDOM.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
}
/** Measure previews in one layout pass, in a hidden copy of the text column. A copy has the table frame and footer, but not the table controls. */
function measurePreviews(view: EditorView, widgets: Preview[], width: number) {
const host = document.createElement("div");
host.className = view.contentDOM.className;
host.setAttribute("aria-hidden", "true");
host.style.cssText = "position:absolute;inset:0 0 auto 0;height:0;min-height:0;padding-block:0;overflow:hidden;visibility:hidden;pointer-events:none";
const footer = document.createElement("div");
footer.className = "table-footer";
const tools = activeTableFormulas()?.createFormulaTools(() => {}, () => {});
if (tools) footer.append(tools.formulaTools);
const copies = widgets.map(widget => {
const copy = document.createElement("div");
copy.className = "reading writer-preview";
copy.innerHTML = widget.html;
const scroll = copy.querySelector(".md-table-scroll");
if (scroll && parseMarkdownTable(widget.source)) {
const frame = document.createElement("div");
frame.className = "writer-table";
scroll.before(frame);
frame.append(scroll);
frame.after(footer.cloneNode(true));
}
host.append(copy);
return copy;
});
view.scrollDOM.append(host);
if (measuredHeights.size + widgets.length > maxMeasuredHeights) measuredHeights.clear();
copies.forEach((copy, index) => {
measuredHeights.set(widgets[index].html, { width, height: copy.offsetHeight });
widgets[index].height.value = -1;
});
host.remove();
}
export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) { export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) {
const selecting = StateEffect.define<boolean>(); const selecting = StateEffect.define<boolean>();
const mouseSelecting = StateField.define({ const mouseSelecting = StateField.define({
@@ -332,10 +256,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to); const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to);
for (let number = 1; number <= state.doc.lines; number++) { for (let number = 1; number <= state.doc.lines; number++) {
const line = state.doc.line(number); const line = state.doc.line(number);
if (!line.text.trim() && !hidden(line.from, line.to)) { if (!line.text.trim() && !hidden(line.from, line.to)) ranges.push(Decoration.line({ class: "writer-blank" }).range(line.from));
ranges.push(Decoration.line({ class: "writer-blank" }).range(line.from));
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
}
} }
const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({ atomic: true }).range(from, to)); }; const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({ atomic: true }).range(from, to)); };
const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); }; const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); };
@@ -353,7 +274,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
for (let number = first.number; number <= last.number; number++) { for (let number = first.number; number <= last.number; number++) {
const line = state.doc.line(number); const line = state.doc.line(number);
ranges.push(Decoration.line({ class: editingCode ? "writer-code-source" : `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from)); ranges.push(Decoration.line({ class: editingCode ? "writer-code-source" : `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from));
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
} }
return false; return false;
} }
@@ -363,7 +283,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
const pendingList = node.name === "SetextHeading2" && state.doc.lineAt(node.to).text.trim() === "-"; const pendingList = node.name === "SetextHeading2" && state.doc.lineAt(node.to).text.trim() === "-";
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name) && !pendingList) { 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)); ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
} }
if (node.name === "InlineCode") codeRanges.push({ from: node.from, to: node.to }); if (node.name === "InlineCode") codeRanges.push({ from: node.from, to: node.to });
if (node.name === "TaskMarker") { if (node.name === "TaskMarker") {
@@ -447,36 +366,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
filter: (_from, _to, decoration) => decoration.spec.atomic === true, filter: (_from, _to, decoration) => decoration.spec.atomic === true,
}))], }))],
}); });
// Give each preview that is not drawn a height, after the document opens, changes, or gets another width.
const previewMeasuring = ViewPlugin.fromClass(class {
frame = 0;
width = -1;
constructor(readonly view: EditorView) { this.schedule(); }
update(update: ViewUpdate) {
if (update.geometryChanged || update.startState.field(decorations) !== update.state.field(decorations)) this.schedule();
}
schedule() {
this.frame ||= requestAnimationFrame(() => { this.frame = 0; this.measure(); });
}
measure() {
const { view } = this, width = textColumnWidth(view);
// The editor has no width while another view or tab covers it.
if (width < 50) return;
const resized = Math.abs(width - this.width) > 1;
this.width = width;
const { from: drawnFrom, to: drawnTo } = view.viewport;
const widgets: Preview[] = [];
view.state.field(decorations).between(0, view.state.doc.length, (from, to, decoration) => {
const widget = decoration.spec.widget;
if (!(widget instanceof Preview) || (from < drawnTo && to > drawnFrom)) return;
if ((resized || widget.height.value < 0) && measuredHeights.get(widget.html)?.width !== width) widgets.push(widget);
});
if (!widgets.length) return;
measurePreviews(view, widgets, width);
view.dispatch({ effects: refreshImages.of() });
}
destroy() { cancelAnimationFrame(this.frame); }
});
const mousePreview = ViewPlugin.define(view => { const mousePreview = ViewPlugin.define(view => {
const finish = () => { const finish = () => {
if (!view.state.field(mouseSelecting)) return; if (!view.state.field(mouseSelecting)) return;
@@ -511,6 +400,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
window.removeEventListener("blur", finish); window.removeEventListener("blur", finish);
} }; } };
}); });
return [imageSource, linkTooltips, bodyFocused, mouseSelecting, decorations, previewMeasuring, mousePreview, syncBodyFocus, return [imageSource, linkTooltips, bodyFocused, mouseSelecting, decorations, mousePreview, syncBodyFocus,
EditorView.focusChangeEffect.of((_state, focusing) => focusBody.of(focusing))]; EditorView.focusChangeEffect.of((_state, focusing) => focusBody.of(focusing))];
} }
+1 -17
View File
@@ -1,18 +1,10 @@
import { SearchQuery } from "@codemirror/search"; import { SearchQuery } from "@codemirror/search";
import { documentMatches, type FindTarget } from "./findTarget"; import { documentMatches, type FindTarget } from "./findTarget";
/** Keys that do not change the text of the find field. These keys keep the selected match. */
const keepsMatch = /^(?:Enter|Escape|Tab|Shift|Control|Alt|Meta|CapsLock|ContextMenu|F\d+)$/;
/** Search the visible reading text without changing its Markdown or rendered nodes. */ /** 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 { export function readingSearch(root: HTMLElement, close: () => void, options: { includeButtons?: boolean; focusOnClose?: () => void } = {}): FindTarget {
let query = new SearchQuery({ search: "" }); let query = new SearchQuery({ search: "" });
let current = -1; let current = -1;
// The window selection also holds the caret of a focused find field. There it reads as collapsed and outside the text.
function matchSelected() {
const selection = window.getSelection();
return !!selection && !selection.isCollapsed && root.contains(selection.anchorNode);
}
function ranges() { function ranges() {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
const nodes: { node: Text; from: number; to: number }[] = []; const nodes: { node: Text; from: number; to: number }[] = [];
@@ -48,15 +40,7 @@ export function readingSearch(root: HTMLElement, close: () => void, options: { i
} }
return { return {
get query() { return query; }, readOnly: true, canSelectAll: false, get query() { return query; }, readOnly: true, canSelectAll: false,
setQuery(value) { if (query.eq(value)) return; query = value; current = -1; if (matchSelected()) window.getSelection()?.removeAllRanges(); }, setQuery(value) { if (query.eq(value)) return; query = value; current = -1; window.getSelection()?.removeAllRanges(); },
// A selected match takes the caret from the find field, and the browser then drops typed keys. Put the caret back first.
// The field cannot report its old caret at this time, so the caret goes to the end of the text.
keydown(event) {
const field = event.target;
const copy = (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c";
if (field instanceof HTMLInputElement && field.type === "text" && !copy && !keepsMatch.test(event.key) && matchSelected()) field.setSelectionRange(field.value.length, field.value.length);
return false;
},
next, selectAll() {}, replace() {}, next, selectAll() {}, replace() {},
close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); }, close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); },
}; };
-7
View File
@@ -451,13 +451,6 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
event.preventDefault(); activate(cell); event.preventDefault(); activate(cell);
const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY }); const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY });
if (hit) { editor?.commands.setTextSelection(hit.pos); editor?.view.focus(); } if (hit) { editor?.commands.setTextSelection(hit.pos); editor?.view.focus(); }
} else if (event.detail === 1 && editor && !editor.view.composing && editor.view.dom.contains(event.target)) {
// ProseMirror reads a native click on the next selectionchange. Its
// delayed focus check can run first and restore the old selection, so
// the click is lost under load. Set the clicked position here. The
// browser then places the same caret, and a drag starts from it.
const hit = editor.view.posAtCoords({ left: event.clientX, top: event.clientY });
if (hit) editor.commands.setTextSelection(hit.pos);
} }
}); });
refreshFormulas(); refreshFormulas();
+69 -180
View File
@@ -1,32 +1,28 @@
<script lang="ts"> <script lang="ts">
// One PDF tab: the toolbar, the status line, the password form, and all pages in one column that scrolls. // One PDF tab: the toolbar, the status line, the password form, and one page with its text layer.
// Only the pages near the visible area have a canvas and a text layer. The other pages are empty sheets.
// The document and its worker live as long as the tab. `close` releases both. // The document and its worker live as long as the tab. `close` releases both.
import { flushSync, onMount } from "svelte"; import { onMount } from "svelte";
import { message, t } from "$lib/i18n"; import { message, t } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte"; import IconButton from "$lib/ui/IconButton.svelte";
import type { PluginDocumentContext } from "$lib/plugins/sdk"; import type { PluginDocumentContext } from "$lib/plugins/sdk";
import { openPdf, TextLayer, type OpenPdf, type PDFDocumentProxy, type RenderTask } from "./engine"; import { openPdf, TextLayer, type OpenPdf, type PDFDocumentProxy, type RenderTask } from "./engine";
import { MAX_ZOOM, MIN_ZOOM, PAGE_GAP, PAGE_MARGIN, RESIZE_SETTLE_MS, ZOOM_STEP, fitZoom, mostVisiblePage, nextRotation, outputScale, pageBoxes, pageNumber, pagesInRange, zoomFromText, zoomLevel, type PageSize } from "./model"; import { MAX_ZOOM, MIN_ZOOM, RESIZE_SETTLE_MS, ZOOM_STEP, nextRotation, outputScale, pageNumber, zoomLevel } from "./model";
let { file, readBytes }: { file: PluginDocumentContext; readBytes: (path: string) => Promise<Uint8Array> } = $props(); let { file, readBytes }: { file: PluginDocumentContext; readBytes: (path: string) => Promise<Uint8Array> } = $props();
type Status = { key: string; values?: Record<string, string | number>; alert?: boolean }; type Status = { key: string; values?: Record<string, string | number>; alert?: boolean };
/** One page that has a drawing, or waits for one. `key` names the zoom, the rotation, and the pixel ratio. */
type Drawing = { key: string; done: boolean; cancel(): void };
let page = $state(1); let page = $state(1);
let count = $state(0); let count = $state(0);
let zoom = $state(1); let zoom = $state(1);
let rotation = $state(0); let rotation = $state(0);
let fit = $state(true); let fit = $state(true);
let sizes = $state.raw<PageSize[]>([]);
let status = $state<Status>({ key: message("Loading PDF…") }); let status = $state<Status>({ key: message("Loading PDF…") });
let asking = $state<"needed" | "incorrect" | null>(null); let asking = $state<"needed" | "incorrect" | null>(null);
let reloading = $state(false); let reloading = $state(false);
let failed = $state(false); let failed = $state(false);
let scroller: HTMLDivElement; let scroller: HTMLDivElement;
let sheets: HTMLDivElement[] = $state([]); let sheet: HTMLDivElement;
let pageInput: HTMLInputElement; let pageInput: HTMLInputElement;
let passwordInput: HTMLInputElement | undefined = $state(); let passwordInput: HTMLInputElement | undefined = $state();
@@ -34,20 +30,14 @@
let pdf: PDFDocumentProxy | undefined; let pdf: PDFDocumentProxy | undefined;
let opened: OpenPdf | undefined; let opened: OpenPdf | undefined;
let answer: ((password: string) => void) | undefined; let answer: ((password: string) => void) | undefined;
let generation = 0; let render: RenderTask | undefined;
const drawings = new Map<number, Drawing>(); let text: TextLayer | undefined;
let revision = 0;
let queue: Promise<void> = Promise.resolve(); let queue: Promise<void> = Promise.resolve();
let loading: Promise<void> = Promise.resolve(); let loading: Promise<void> = Promise.resolve();
let closing: Promise<void> | undefined; let closing: Promise<void> | undefined;
// The place in the document: a page and the part of its height above the top of the visible area.
let anchor = { index: 0, part: 0 };
// The scroll position that the viewer set. A scroll event at this position keeps the page number.
let settled = -1;
let frame = 0;
const ready = $derived(count > 0); const ready = $derived(count > 0);
const boxes = $derived(pageBoxes(sizes, zoom, rotation));
const zoomText = $derived(ready ? `${Math.round(zoom * 100)}%` : "—");
function fail(reason: unknown) { function fail(reason: unknown) {
if (disposed) return; if (disposed) return;
@@ -55,137 +45,53 @@
status = { key: message("Cannot display this PDF. {reason}"), values: { reason: reason instanceof Error ? reason.message : String(reason) }, alert: true }; status = { key: message("Cannot display this PDF. {reason}"), values: { reason: reason instanceof Error ? reason.message : String(reason) }, alert: true };
} }
const drawingKey = () => `${zoom}:${rotation}:${window.devicePixelRatio}`; /** Draw the current page again. A newer request cancels the older one. */
function schedule() {
/** The status line names the current page when its drawing is complete. */ const request = ++revision;
function report() { render?.cancel(); text?.cancel();
if (disposed || failed || !pdf) return; if (pdf && !disposed) status = { key: message("Loading page {page}…"), values: { page } };
const drawing = drawings.get(page);
status = drawing?.done && drawing.key === drawingKey()
? { key: message("Page {page} of {count}"), values: { page, count } }
: { key: message("Loading page {page}…"), values: { page } };
}
/** Draw one page. The jobs run one at a time. A cancelled job ends at its next step. */
function draw(number: number, key: string) {
let cancelled = false;
let render: RenderTask | undefined;
let text: TextLayer | undefined;
const drawing: Drawing = { key, done: false, cancel() { cancelled = true; render?.cancel(); text?.cancel(); } };
drawings.set(number, drawing);
const source = pdf;
queue = queue.then(async () => { queue = queue.then(async () => {
if (cancelled || disposed || !source) return; if (disposed || request !== revision || !pdf || scroller.clientWidth === 0) return;
const pdfPage = await source.getPage(number); const pdfPage = await pdf.getPage(page);
const sheet = sheets[number - 1]; if (disposed || request !== revision) return;
if (cancelled || disposed || !sheet) return; const angle = (pdfPage.rotate + rotation) % 360;
const viewport = pdfPage.getViewport({ scale: zoom, rotation: (pdfPage.rotate + rotation) % 360 }); if (fit) zoom = zoomLevel((scroller.clientWidth - 32) / pdfPage.getViewport({ scale: 1, rotation: angle }).width);
const viewport = pdfPage.getViewport({ scale: zoom, rotation: angle });
const scale = outputScale(viewport.width, viewport.height, window.devicePixelRatio); const scale = outputScale(viewport.width, viewport.height, window.devicePixelRatio);
const canvas = document.createElement("canvas"); const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.floor(viewport.width * scale)); canvas.width = Math.max(1, Math.floor(viewport.width * scale));
canvas.height = Math.max(1, Math.floor(viewport.height * scale)); canvas.height = Math.max(1, Math.floor(viewport.height * scale));
canvas.style.width = `${viewport.width}px`;
canvas.style.height = `${viewport.height}px`;
canvas.setAttribute("role", "img"); canvas.setAttribute("role", "img");
// The measurement tool and the smoke tests find the page by this English name. Keep "PDF page N". // The measurement tool and the smoke tests find the page by this English name. Keep "PDF page N".
canvas.setAttribute("aria-label", $t("PDF page {page}", { page: number })); canvas.setAttribute("aria-label", $t("PDF page {page}", { page }));
const layer = document.createElement("div"); const layer = document.createElement("div");
layer.className = "textLayer"; layer.className = "textLayer";
layer.style.setProperty("--total-scale-factor", String(viewport.scale)); sheet.style.width = `${viewport.width}px`;
sheet.style.height = `${viewport.height}px`;
sheet.style.setProperty("--total-scale-factor", String(zoom));
sheet.replaceChildren(canvas, layer);
render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] }); render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] });
await render.promise; await render.promise;
if (cancelled || disposed) return; if (disposed || request !== revision) return;
// The old drawing of the page stays until the new one is complete.
sheet.replaceChildren(canvas, layer);
text = new TextLayer({ textContentSource: pdfPage.streamTextContent(), container: layer, viewport }); text = new TextLayer({ textContentSource: pdfPage.streamTextContent(), container: layer, viewport });
await text.render(); await text.render();
if (cancelled || disposed) return; if (disposed || request !== revision) return;
drawing.done = true; status = { key: message("Page {page} of {count}"), values: { page, count } };
pdfPage.cleanup(); pdfPage.cleanup();
report(); }).catch(reason => { if (!disposed && request === revision) fail(reason); });
}).catch(reason => { if (!cancelled && !disposed) fail(reason); });
} }
/** Draw the pages near the visible area, the current page first. Empty the pages that are far from it. */
function refresh() {
if (!pdf || disposed || scroller.clientWidth === 0) return;
const key = drawingKey();
const height = scroller.clientHeight;
const wanted = pagesInRange(boxes, scroller.scrollTop - height, scroller.scrollTop + 2 * height);
for (const [number, drawing] of drawings) {
const keep = wanted.includes(number);
if (keep && drawing.key === key) continue;
drawing.cancel();
drawings.delete(number);
if (!keep) sheets[number - 1]?.replaceChildren();
}
for (const number of wanted.sort((a, b) => Math.abs(a - page) - Math.abs(b - page))) if (!drawings.has(number)) draw(number, key);
report();
}
/** Put the remembered place at the top of the visible area again, after the page boxes changed. */
function restore() {
flushSync();
const box = boxes[anchor.index];
if (!box || scroller.clientWidth === 0) return;
scroller.scrollTop = Math.max(0, box.top + anchor.part * box.height);
settled = scroller.scrollTop;
refresh();
}
function remember() {
const box = boxes[page - 1];
anchor = { index: page - 1, part: box ? (scroller.scrollTop - box.top) / box.height : 0 };
}
function scrolled() {
if (frame) return;
frame = requestAnimationFrame(() => {
frame = 0;
if (disposed || !ready || scroller.clientWidth === 0) return;
if (scroller.scrollTop !== settled) {
settled = -1;
page = mostVisiblePage(boxes, scroller.scrollTop, scroller.scrollTop + scroller.clientHeight);
remember();
}
refresh();
});
}
/** Show the top of a page. */
function go(value: number) { function go(value: number) {
if (!pdf) return; if (!pdf) return;
page = pageNumber(value, pdf.numPages); page = pageNumber(value, pdf.numPages);
pageInput.value = String(page); pageInput.value = String(page);
// The first page shows with the margin above it. Each other page shows with half of the gap above it. scroller.scrollTop = 0;
anchor = { index: page - 1, part: -(page === 1 ? PAGE_MARGIN : PAGE_GAP / 2) / (boxes[page - 1]?.height ?? 1) }; schedule();
restore();
} }
function applyFit() { function setZoom(value: number) { fit = false; zoom = zoomLevel(value); schedule(); }
if (fit && scroller.clientWidth > 0 && sizes.length) zoom = fitZoom(sizes, rotation, scroller.clientWidth - 2 * PAGE_MARGIN);
}
function setZoom(value: number) { fit = false; zoom = zoomLevel(value); restore(); }
function typedZoom(input: HTMLInputElement) {
const value = zoomFromText(input.value);
if (value !== null && Math.round(value * 100) !== Math.round(zoom * 100)) setZoom(value);
input.value = zoomText;
}
/** Read the size of each page after the first. Until then, a page has the size of the first page. */
async function measure(source: PDFDocumentProxy, current: number) {
const next = [...sizes];
let changed = false;
for (let number = 2; number <= source.numPages; number++) {
const { width, height } = (await source.getPage(number)).getViewport({ scale: 1 });
if (disposed || current !== generation) return;
if (width !== next[number - 1].width || height !== next[number - 1].height) { next[number - 1] = { width, height }; changed = true; }
}
if (!changed) return;
sizes = next;
applyFit();
restore();
}
async function load() { async function load() {
failed = false; failed = false;
@@ -199,27 +105,20 @@
status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") }; status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") };
queueMicrotask(() => passwordInput?.focus()); queueMicrotask(() => passwordInput?.focus());
}); });
const source = await opened.promise; pdf = await opened.promise;
if (disposed) return; if (disposed) return;
const current = ++generation; page = pageNumber(page, pdf.numPages);
const { width, height } = (await source.getPage(1)).getViewport({ scale: 1 }); count = pdf.numPages;
if (disposed) return; schedule();
pdf = source;
sizes = Array.from({ length: source.numPages }, () => ({ width, height }));
count = source.numPages;
applyFit();
go(page);
report();
void measure(source, current).catch(reason => { if (current === generation) fail(reason); });
} }
async function release() { async function release() {
generation++; revision++;
for (const drawing of drawings.values()) drawing.cancel(); render?.cancel(); text?.cancel();
drawings.clear();
await queue; await queue;
const current = opened; const current = opened;
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0; sizes = []; opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0;
sheet?.replaceChildren();
await current?.close(); await current?.close();
} }
@@ -246,11 +145,12 @@
next(value); next(value);
} }
/** Ctrl and the wheel change the zoom. The wheel alone scrolls the pages. */ function pageKey(event: KeyboardEvent) {
function wheel(event: WheelEvent) { if (event.ctrlKey || event.metaKey || event.altKey || !ready) return;
if (!(event.ctrlKey || event.metaKey) || !ready || event.deltaY === 0) return; if (event.key === "PageDown" || event.key === "PageUp") {
event.preventDefault(); event.preventDefault();
setZoom(event.deltaY < 0 ? zoom * 1.1 : zoom / 1.1); go(page + (event.key === "PageDown" ? 1 : -1));
}
} }
/** Stop the drawing, release the document, and stop its worker. The host calls it before it removes the tab. */ /** Stop the drawing, release the document, and stop its worker. The host calls it before it removes the tab. */
@@ -263,23 +163,21 @@
onMount(() => { onMount(() => {
loading = load().catch(fail); loading = load().catch(fail);
// Fit-width pages follow the width of the tab. A tab that shows again draws at once. Later sizes wait until the size settles. // A fit-width page follows the width of the tab. The first size draws at once. Later sizes wait until the size settles.
let width = 0; let width = 0;
let timer: ReturnType<typeof setTimeout> | undefined; let timer: ReturnType<typeof setTimeout> | undefined;
const resized = () => { applyFit(); restore(); };
const observer = new ResizeObserver(() => { const observer = new ResizeObserver(() => {
const next = scroller.clientWidth; const next = scroller.clientWidth;
if (next === width) return; if (next === 0 || next === width) return;
const shown = width === 0; const first = width === 0;
width = next; width = next;
clearTimeout(timer); clearTimeout(timer);
if (next === 0) return; if (!fit) return;
if (shown) resized(); if (first) schedule();
else timer = setTimeout(resized, RESIZE_SETTLE_MS); else timer = setTimeout(schedule, RESIZE_SETTLE_MS);
}); });
observer.observe(scroller); observer.observe(scroller);
scroller.addEventListener("wheel", wheel, { passive: false }); return () => { observer.disconnect(); clearTimeout(timer); void close(); };
return () => { observer.disconnect(); clearTimeout(timer); cancelAnimationFrame(frame); scroller.removeEventListener("wheel", wheel); void close(); };
}); });
</script> </script>
@@ -293,12 +191,10 @@
<IconButton icon="down" label={$t("Next page")} disabled={!ready || page >= count} onclick={() => go(page + 1)} /> <IconButton icon="down" label={$t("Next page")} disabled={!ready || page >= count} onclick={() => go(page + 1)} />
<span class="separator" aria-hidden="true"></span> <span class="separator" aria-hidden="true"></span>
<IconButton icon="zoom-out" label={$t("Zoom out")} disabled={!ready || zoom <= MIN_ZOOM} onclick={() => setZoom(zoom / ZOOM_STEP)} /> <IconButton icon="zoom-out" label={$t("Zoom out")} disabled={!ready || zoom <= MIN_ZOOM} onclick={() => setZoom(zoom / ZOOM_STEP)} />
<input class="zoom" type="text" inputmode="decimal" value={zoomText} disabled={!ready} aria-label={$t("Zoom percent")} <span class="zoom">{ready ? `${Math.round(zoom * 100)}%` : "—"}</span>
onfocus={event => event.currentTarget.select()} onchange={event => typedZoom(event.currentTarget)}
onkeydown={event => { if (event.key === "Enter") typedZoom(event.currentTarget); }} />
<IconButton icon="zoom-in" label={$t("Zoom in")} disabled={!ready || zoom >= MAX_ZOOM} onclick={() => setZoom(zoom * ZOOM_STEP)} /> <IconButton icon="zoom-in" label={$t("Zoom in")} disabled={!ready || zoom >= MAX_ZOOM} onclick={() => setZoom(zoom * ZOOM_STEP)} />
<IconButton icon="fit-width" label={$t("Fit width")} active={fit && ready} disabled={!ready} onclick={() => { fit = true; applyFit(); restore(); }} /> <IconButton icon="fit-width" label={$t("Fit width")} active={fit && ready} disabled={!ready} onclick={() => { fit = true; schedule(); }} />
<IconButton icon="rotate" label={$t("Rotate clockwise")} disabled={!ready} onclick={() => { rotation = nextRotation(rotation); applyFit(); restore(); }} /> <IconButton icon="rotate" label={$t("Rotate clockwise")} disabled={!ready} onclick={() => { rotation = nextRotation(rotation); schedule(); }} />
<IconButton icon="refresh" label={$t("Reload PDF")} disabled={reloading || (!ready && !failed)} onclick={() => void reload()} /> <IconButton icon="refresh" label={$t("Reload PDF")} disabled={reloading || (!ready && !failed)} onclick={() => void reload()} />
</div> </div>
<p class="status" class:alert={status.alert} role={status.alert ? "alert" : "status"} aria-live={status.alert ? "assertive" : "polite"}>{$t(status.key, status.values)}</p> <p class="status" class:alert={status.alert} role={status.alert ? "alert" : "status"} aria-live={status.alert ? "assertive" : "polite"}>{$t(status.key, status.values)}</p>
@@ -308,39 +204,32 @@
<button class="text-button" type="submit">{$t("Unlock")}</button> <button class="text-button" type="submit">{$t("Unlock")}</button>
</form> </form>
{/if} {/if}
<!-- The page area takes focus, so the keyboard scrolls the pages. The host gives it focus after a tab change by keyboard. --> <!-- The page area takes focus for Page Up and Page Down. -->
<!-- svelte-ignore a11y_no_noninteractive_tabindex --> <!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
<div bind:this={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF pages")} data-tab-focus onscroll={scrolled}> <div bind:this={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF page. Use Page Up and Page Down to change pages.")} onkeydown={pageKey}>
<div class="pages"> <div bind:this={sheet} class="sheet"></div>
{#each boxes as box, index (index)}
<div bind:this={sheets[index]} class="sheet" data-page={index + 1} style:width={`${box.width}px`} style:height={`${box.height}px`}></div>
{/each}
</div>
</div> </div>
</section> </section>
<style> <style>
.pdf-viewer { display: flex; flex-direction: column; height: 100%; min-height: 240px; min-width: 0; color: var(--rs-text); font-size: 13px; } .pdf-viewer { display: flex; flex-direction: column; height: 100%; min-height: 240px; min-width: 0; color: var(--rs-text); font-size: 13px; }
/* The toolbar, the status line, and the password form are opaque, so a background image never hides them. */ .toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 8px; border-bottom: 1px solid var(--rs-border); }
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 8px; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); }
.page { box-sizing: border-box; width: 64px; height: 28px; margin-left: 4px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: right; } .page { box-sizing: border-box; width: 64px; height: 28px; margin-left: 4px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: right; }
.page:disabled, .zoom:disabled { color: var(--rs-text-dim); } .page:disabled { color: var(--rs-text-dim); }
.count { margin: 0 4px; color: var(--rs-text-dim); white-space: nowrap; } .count { margin: 0 4px; color: var(--rs-text-dim); white-space: nowrap; }
.separator { width: 1px; height: 18px; margin: 0 4px; background: var(--rs-border); } .separator { width: 1px; height: 18px; margin: 0 4px; background: var(--rs-border); }
.zoom { box-sizing: border-box; width: 60px; height: 28px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: center; } .zoom { min-width: 44px; color: var(--rs-text-dim); text-align: center; white-space: nowrap; }
.status { margin: 0; padding: 4px 12px; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); font-size: 12px; color: var(--rs-text-dim); overflow-wrap: anywhere; } .status { margin: 0; padding: 4px 12px; font-size: 12px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
.status.alert { color: var(--rs-error); } .status.alert { color: var(--rs-error); }
.password { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); } .password { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; }
.password input { box-sizing: border-box; height: 28px; margin-left: 4px; padding: 2px 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; } .password input { box-sizing: border-box; height: 28px; margin-left: 4px; padding: 2px 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; } .text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; }
.text-button:hover { background: var(--rs-bg-active); } .text-button:hover { background: var(--rs-hover-bg); }
/* The padding and the gap match PAGE_MARGIN and PAGE_GAP in model.ts. */ .scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; }
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; background: var(--rs-workarea-editor-bg); }
.scroll:focus-visible { outline-offset: -2px; } .scroll:focus-visible { outline-offset: -2px; }
.pages { display: flex; flex-direction: column; align-items: center; gap: 12px; width: max-content; min-width: 100%; }
/* A PDF page is paper: white in both themes. */ /* A PDF page is paper: white in both themes. */
.sheet { position: relative; flex: none; background: white; box-shadow: 0 2px 10px #0003; } .sheet { position: relative; margin: 0 auto; background: white; box-shadow: 0 2px 10px #0003; }
.sheet :global(canvas) { display: block; width: 100%; height: 100%; } .sheet :global(canvas) { display: block; }
/* The text layer geometry follows the viewer styles of PDF.js 6 (Apache-2.0). See THIRD_PARTY_NOTICES.md. */ /* The text layer geometry follows the viewer styles of PDF.js 6 (Apache-2.0). See THIRD_PARTY_NOTICES.md. */
.sheet :global(.textLayer) { position: absolute; inset: 0; overflow: clip; text-align: initial; line-height: 1; letter-spacing: normal; word-spacing: normal; text-size-adjust: none; forced-color-adjust: none; transform-origin: 0 0; --min-font-size: 1; --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size)); --min-font-size-inv: calc(1 / var(--min-font-size)); } .sheet :global(.textLayer) { position: absolute; inset: 0; overflow: clip; text-align: initial; line-height: 1; letter-spacing: normal; word-spacing: normal; text-size-adjust: none; forced-color-adjust: none; transform-origin: 0 0; --min-font-size: 1; --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size)); --min-font-size-inv: calc(1 / var(--min-font-size)); }
.sheet :global(.textLayer :is(span, br)) { position: absolute; color: transparent; white-space: pre; cursor: text; transform-origin: 0 0; user-select: text; } .sheet :global(.textLayer :is(span, br)) { position: absolute; color: transparent; white-space: pre; cursor: text; transform-origin: 0 0; user-select: text; }
-57
View File
@@ -29,60 +29,3 @@ export function nextRotation(rotation: number): number {
export function outputScale(width: number, height: number, deviceScale: number): number { export function outputScale(width: number, height: number, deviceScale: number): number {
return Math.min(deviceScale || 1, 2, 8192 / width, 8192 / height, Math.sqrt(16_000_000 / (width * height))); return Math.min(deviceScale || 1, 2, 8192 / width, 8192 / height, Math.sqrt(16_000_000 / (width * height)));
} }
/** The space around the pages and between two pages, in CSS pixels. `PdfViewer.svelte` uses the same values in its styles. */
export const PAGE_MARGIN = 16;
export const PAGE_GAP = 12;
/** The size of a page at zoom 1, with the rotation of the file. */
export interface PageSize { width: number; height: number }
/** The place of a page in the column of pages, in whole CSS pixels. */
export interface PageBox { top: number; width: number; height: number }
/** The zoom factor for typed text such as "150" or "150 %". Text that is not a number gives null. */
export function zoomFromText(text: string): number | null {
const value = Number(text.replace("%", "").replace(",", ".").trim());
return text.trim() && Number.isFinite(value) && value > 0 ? zoomLevel(value / 100) : null;
}
/** The zoom that fits the widest page in `available` pixels. */
export function fitZoom(sizes: readonly PageSize[], rotation: number, available: number): number {
const turned = rotation % 180 !== 0;
const widest = Math.max(0, ...sizes.map(size => turned ? size.height : size.width));
return zoomLevel(widest > 0 ? available / widest : 1);
}
/** One box for each page, from the top of the column to the bottom. */
export function pageBoxes(sizes: readonly PageSize[], zoom: number, rotation: number): PageBox[] {
const turned = rotation % 180 !== 0;
let top = PAGE_MARGIN;
return sizes.map(size => {
const width = Math.max(1, Math.floor((turned ? size.height : size.width) * zoom));
const height = Math.max(1, Math.floor((turned ? size.width : size.height) * zoom));
const box = { top, width, height };
top += height + PAGE_GAP;
return box;
});
}
/** The numbers of the pages that touch the range from `from` to `to`. */
export function pagesInRange(boxes: readonly PageBox[], from: number, to: number): number[] {
const pages: number[] = [];
for (let index = 0; index < boxes.length; index++) {
if (boxes[index].top >= to) break;
if (boxes[index].top + boxes[index].height > from) pages.push(index + 1);
}
return pages;
}
/** The number of the page that shows the most in the range from `from` to `to`. The first such page wins. */
export function mostVisiblePage(boxes: readonly PageBox[], from: number, to: number): number {
let page = 1, most = 0;
for (let index = 0; index < boxes.length; index++) {
const { top, height } = boxes[index];
if (top >= to) break;
const shown = Math.min(top + height, to) - Math.max(top, from);
if (shown > most) { most = shown; page = index + 1; }
}
return page;
}
@@ -1,77 +1,34 @@
import type { Workspace } from "../model/model.ts"; import type { Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts"; import { readOptional, saveDocument } from "./persistence.ts";
import { message } from "./message.ts"; import { message } from "./message.ts";
import { imagePath, parseImage } from "./images.ts";
const invalidDraft = () => new Error(message("The description draft is invalid. Preserve it before recovery.")); /** A draft is separate from the saved card and uses compare-and-write protection. */
const sameImages = (a: ReadonlyMap<string, string>, b: ReadonlyMap<string, string>) =>
a.size === b.size && [...a].every(([id, data]) => b.get(id) === data);
/**
* A draft is separate from the saved card and uses compare-and-write protection.
* A second file keeps the data of the images that only the draft uses. Thus a text change does not write the images again.
* The image folder gets an image only from a save of the description or the card. A discarded draft keeps an empty image record, so no image file stays behind.
*/
export class DescriptionDraft { export class DescriptionDraft {
private source: string | null = null; private source: string | null = null;
private imageSource: string | null = null;
private images: ReadonlyMap<string, string> = new Map();
private queue: Promise<unknown> = Promise.resolve(); private queue: Promise<unknown> = Promise.resolve();
readonly path: string; readonly path: string;
readonly imagesPath: string;
private workspace: Workspace; private workspace: Workspace;
constructor(workspace: Workspace, id: string) { constructor(workspace: Workspace, id: string) {
this.workspace = workspace; this.workspace = workspace;
const key = Array.from(new TextEncoder().encode(id), byte => byte.toString(16).padStart(2, "0")).join(""); const key = Array.from(new TextEncoder().encode(id), byte => byte.toString(16).padStart(2, "0")).join("");
this.path = `.runestone/pm/drafts/${key}.json`; this.path = `.runestone/pm/drafts/${key}.json`;
this.imagesPath = `.runestone/pm/drafts/${key}.images.json`;
} }
async load(): Promise<string | null> { async load(): Promise<string | null> {
this.source = await readOptional(this.workspace, this.path); this.source = await readOptional(this.workspace, this.path);
if (this.source === null) return null; if (this.source === null) return null;
const value = JSON.parse(this.source); const value = JSON.parse(this.source);
if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string")) if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string"))
throw invalidDraft(); throw new Error(message("The description draft is invalid. Preserve it before recovery."));
return value.body; return value.body;
} }
/** The image data of the draft, by image ID. A draft of an earlier version has no image record. Call this before `save`. */ save(body: string | null): Promise<void> {
async loadImages(): Promise<Map<string, string>> {
this.images = new Map();
this.imageSource = await readOptional(this.workspace, this.imagesPath);
if (this.imageSource === null) return new Map();
const value = JSON.parse(this.imageSource);
if (value?.schema !== 1 || typeof value.images !== "object" || value.images === null || Array.isArray(value.images))
throw invalidDraft();
const images = new Map<string, string>();
for (const [id, data] of Object.entries(value.images)) {
try { imagePath(id); images.set(id, parseImage(JSON.stringify({ schema: 1, data }))); }
catch { throw invalidDraft(); }
}
this.images = images;
return new Map(images);
}
/** Save the text of the draft and the data of the images that only the draft uses. A `null` body discards the draft and its images. */
save(body: string | null, images: ReadonlyMap<string, string> = new Map()): Promise<void> {
const write = this.queue.then(async () => { const write = this.queue.then(async () => {
const next = body === null ? new Map<string, string>() : images;
// Keep the old and the new image data until the text is saved, so that each saved reference has its data.
await this.saveImages(new Map([...this.images, ...next]));
const source = JSON.stringify({ schema: 1, body }) + "\n"; const source = JSON.stringify({ schema: 1, body }) + "\n";
if (source !== this.source && !(body === null && this.source === null)) { if (source === this.source || (body === null && this.source === null)) return;
await saveDocument(this.workspace, this.path, source, this.source); await saveDocument(this.workspace, this.path, source, this.source);
this.source = source; this.source = source;
}
await this.saveImages(next);
}); });
this.queue = write.catch(() => {}); this.queue = write.catch(() => {});
return write; return write;
} }
private async saveImages(images: ReadonlyMap<string, string>) {
if (sameImages(images, this.images) || (!images.size && this.imageSource === null)) return;
const sorted = [...images].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
const source = JSON.stringify({ schema: 1, images: Object.fromEntries(sorted) }) + "\n";
await saveDocument(this.workspace, this.imagesPath, source, this.imageSource);
this.imageSource = source;
this.images = new Map(images);
}
} }
+2 -7
View File
@@ -51,16 +51,13 @@ export function parseImage(source: string): string {
throw new Error(message("The saved image is invalid or exceeds 50 MiB.")); throw new Error(message("The saved image is invalid or exceeds 50 MiB."));
return value.data; return value.data;
} }
/** Write the pending images that `body`, `attachments`, or `ids` refer to. Returns the IDs of the written images. */
export async function saveImages( export async function saveImages(
workspace: Workspace, workspace: Workspace,
body: string, body: string,
pending: ReadonlyMap<string, string>, pending: Map<string, string>,
attachments: TaskFields["attachments"] = [], attachments: TaskFields["attachments"] = [],
ids: string[] = [],
) { ) {
const saved: string[] = []; for (const id of new Set([...imageReferences(body), ...attachments].map((image) => image.id))) {
for (const id of new Set([...[...imageReferences(body), ...attachments].map((image) => image.id), ...ids])) {
const data = pending.get(id); const data = pending.get(id);
if (!data) continue; if (!data) continue;
const source = JSON.stringify({ schema: 1, data }) + "\n"; const source = JSON.stringify({ schema: 1, data }) + "\n";
@@ -69,7 +66,5 @@ export async function saveImages(
// Retrying a failed card save reuses its complete image files. // Retrying a failed card save reuses its complete image files.
const previous = await workspace.readOptional?.(path); const previous = await workspace.readOptional?.(path);
if (previous !== source) await saveDocument(workspace, path, source, null); if (previous !== source) await saveDocument(workspace, path, source, null);
saved.push(id);
} }
return saved;
} }
+2 -21
View File
@@ -369,26 +369,7 @@ export function createCardImages(
saving = value; saving = value;
updateControls(); updateControls();
}, },
/** Write the images of `body`, of the attachments, and of `ids`, for example the card cover. */ save: (body: string) => saveImages(workspace, body, pending, attachments),
async save(body: string, ids: string[] = []) {
for (const id of await saveImages(workspace, body, pending, attachments, ids)) {
// The image file now holds the data, so the description draft does not keep it.
const data = pending.get(id);
if (!data) continue;
loaded.set(id, Promise.resolve(data));
pending.delete(id);
}
},
/** The data of the unsaved images that `body` refers to. The description draft keeps it. */
draftImages: (body: string) => new Map(imageReferences(body).flatMap(ref => {
const data = pending.get(ref.id);
return data ? [[ref.id, data] as const] : [];
})),
/** Add the image data of a restored description draft, and show the images of the restored text. */
restore(images: ReadonlyMap<string, string>) {
for (const [id, data] of images) if (!pending.has(id)) pending.set(id, data);
void render();
},
dispose() { dispose() {
disposed = true; disposed = true;
clearTimeout(idleTimer); clearTimeout(idleTimer);
@@ -396,7 +377,7 @@ export function createCardImages(
viewerObserver = undefined; viewerObserver = undefined;
viewer?.remove(); viewer = undefined; viewer?.remove(); viewer = undefined;
revision++; revision++;
// Keep the pending image data. A draft save that is in progress after a close still needs it. pending.clear();
loaded.clear(); loaded.clear();
description.removeEventListener("paste", paste); description.removeEventListener("paste", paste);
description.removeEventListener("input", render); description.removeEventListener("input", render);
+7 -17
View File
@@ -1051,11 +1051,7 @@ export function mountPM(
description, description,
(name, action) => button(tr(name), action, name === "Actual size" ? "expand" : "image"), (name, action) => button(tr(name), action, name === "Actual size" ? "expand" : "image"),
(name, action) => iconButton(name, "close", action), (name, action) => iconButton(name, "close", action),
(loading) => { (loading) => { save.disabled = loading || busy || !title.value.trim(); descriptionEditor.updateLoading(); },
save.disabled = loading || busy || !title.value.trim(); descriptionEditor.updateLoading();
// The input event of a pasted image comes while the image loads. Save the draft after the load.
if (!loading) scheduleDraft();
},
task?.attachments, task?.attachments,
); );
const formattingIcons: Record<string, keyof typeof icons> = { const formattingIcons: Record<string, keyof typeof icons> = {
@@ -1068,10 +1064,9 @@ export function mountPM(
let descriptionSaving = false; let descriptionSaving = false;
let draftTimer: ReturnType<typeof setTimeout> | undefined; let draftTimer: ReturnType<typeof setTimeout> | undefined;
let draftEdited = false; let draftEdited = false;
const draftReady = draft && Promise.all([draft.load(), draft.loadImages()]).then(([body, draftImages]) => { const draftReady = draft?.load().then(body => {
if (body !== null && !draftEdited && dialog.isConnected) { if (body !== null && !draftEdited && dialog.isConnected) {
descriptionEditor.restoreDraft(body); descriptionEditor.restoreDraft(body);
images.restore(draftImages);
updateDescriptionBadge(task!.id, body !== task!.body); updateDescriptionBadge(task!.id, body !== task!.body);
} }
}); });
@@ -1079,13 +1074,8 @@ export function mountPM(
clearTimeout(draftTimer); clearTimeout(draftTimer);
await draftReady; await draftReady;
if (!draft || !task) return; if (!draft || !task) return;
const body = description.value; await images.save(description.value);
// The draft keeps the data of its unsaved images. The image files come only with a save of the description or the card. await draft.save(description.value === task.body ? null : description.value);
await draft.save(body === task.body ? null : body, images.draftImages(body));
};
const scheduleDraft = () => {
clearTimeout(draftTimer);
if (draft && !images.isLoading()) draftTimer = setTimeout(() => { void flushDraft().catch(reportDraftError); }, 300);
}; };
const reportDraftError = (reason: unknown) => { error.textContent = errorText(reason); }; const reportDraftError = (reason: unknown) => { error.textContent = errorText(reason); };
void draftReady?.catch(reportDraftError); void draftReady?.catch(reportDraftError);
@@ -1123,7 +1113,8 @@ export function mountPM(
description.addEventListener("input", () => { description.addEventListener("input", () => {
draftEdited = true; draftEdited = true;
if (task) updateDescriptionBadge(task.id, description.value !== task.body); if (task) updateDescriptionBadge(task.id, description.value !== task.body);
scheduleDraft(); clearTimeout(draftTimer);
if (draft && !images.isLoading()) draftTimer = setTimeout(() => { void flushDraft().catch(reportDraftError); }, 300);
}); });
const useSharedChoices = sharedChoice; const useSharedChoices = sharedChoice;
const updateChoice = sharedChoices.update; const updateChoice = sharedChoices.update;
@@ -1558,8 +1549,7 @@ export function mountPM(
const ok = await perform( const ok = await perform(
async () => { async () => {
await flushDraft(); await flushDraft();
// The cover can be an image that only the description draft has. await images.save(body);
await images.save(body, cover.value ? [cover.value] : []);
const existingIds = new Set(store.tasks.map(candidate => candidate.id)); const existingIds = new Set(store.tasks.map(candidate => candidate.id));
await (task && boardSelect.value && (boardSelect.value !== originalBoardId || (!store.board.reference && listChanged)) await (task && boardSelect.value && (boardSelect.value !== originalBoardId || (!store.board.reference && listChanged))
? store.saveToBoard(task, boardSelect.value, listSelect.value || null, { ...fields, body }) ? store.saveToBoard(task, boardSelect.value, listSelect.value || null, { ...fields, body })
+8 -13
View File
@@ -1020,10 +1020,10 @@ export const messageRows: [string, string, string, string][] = [
"阅读" "阅读"
], ],
[ [
"Read beside", "Split",
"Lire à côté", "Diviser",
"横に閲覧", "分割",
"并排阅读" "分栏"
], ],
[ [
"Editor", "Editor",
@@ -3300,12 +3300,8 @@ export const messageRows: [string, string, string, string][] = [
["The workspace changed. File moves stopped.", "L’espace de travail a changé. Les déplacements de fichiers sont arrêtés.", "ワークスペースが変更されました。ファイルの移動を停止しました。", "工作区已更改。文件移动已停止。"], ["The workspace changed. File moves stopped.", "L’espace de travail a changé. Les déplacements de fichiers sont arrêtés.", "ワークスペースが変更されました。ファイルの移動を停止しました。", "工作区已更改。文件移动已停止。"],
["The workspace changed. Paste stopped.", "L’espace de travail a changé. Le collage est arrêté.", "ワークスペースが変更されました。貼り付けを停止しました。", "工作区已更改。粘贴已停止。"], ["The workspace changed. Paste stopped.", "L’espace de travail a changé. Le collage est arrêté.", "ワークスペースが変更されました。貼り付けを停止しました。", "工作区已更改。粘贴已停止。"],
["Move to new window", "Déplacer vers une nouvelle fenêtre", "新しいウィンドウに移動", "移到新窗口"], ["Move to new window", "Déplacer vers une nouvelle fenêtre", "新しいウィンドウに移動", "移到新窗口"],
["New tab to the right", "Nouvel onglet à droite", "右に新しいタブ", "在右侧新建标签页"], ["Split right", "Scinder à droite", "右に分割", "向右拆分"],
["New tab below", "Nouvel onglet en dessous", "下に新しいタブ", "在下方新建标签页"], ["Split down", "Scinder vers le bas", "下に分割", "向下拆分"],
["Resize panes", "Redimensionner les volets", "ペインのサイズを変更", "调整窗格大小"],
["Drag to resize the panes. Double-click to give them equal sizes.", "Faites glisser pour redimensionner les volets. Double-cliquez pour leur donner la même taille.", "ドラッグしてペインのサイズを変更します。ダブルクリックすると同じサイズになります。", "拖动以调整窗格大小。双击使窗格大小相同。"],
["Show here", "Afficher ici", "ここに表示", "在此显示"],
["Open below", "Ouvrir en dessous", "下に開く", "在下方打开"],
["Find…", "Rechercher…", "検索…", "查找…"], ["Find…", "Rechercher…", "検索…", "查找…"],
["Open in default browser", "Ouvrir dans le navigateur par défaut", "既定のブラウザーで開く", "在默认浏览器中打开"], ["Open in default browser", "Ouvrir dans le navigateur par défaut", "既定のブラウザーで開く", "在默认浏览器中打开"],
["Invalid browser tab transfer.", "Transfert d’onglet de navigateur non valide.", "ブラウザータブの移動が無効です。", "浏览器标签页转移无效。"], ["Invalid browser tab transfer.", "Transfert d’onglet de navigateur non valide.", "ブラウザータブの移動が無効です。", "浏览器标签页转移无效。"],
@@ -3380,7 +3376,7 @@ export const messageRows: [string, string, string, string][] = [
["Show the file name above each Markdown note in Write and Read.", "Afficher le nom du fichier au-dessus de chaque note Markdown dans Écrire et Lire.", "「書く」と「閲覧」で、各 Markdown ノートの上にファイル名を表示します。", "在“写作”和“阅读”中,在每篇 Markdown 笔记上方显示文件名。"], ["Show the file name above each Markdown note in Write and Read.", "Afficher le nom du fichier au-dessus de chaque note Markdown dans Écrire et Lire.", "「書く」と「閲覧」で、各 Markdown ノートの上にファイル名を表示します。", "在“写作”和“阅读”中,在每篇 Markdown 笔记上方显示文件名。"],
["Source", "Source", "ソース", "源码"], ["Source", "Source", "ソース", "源码"],
["View", "Affichage", "表示", "视图"], ["View", "Affichage", "表示", "视图"],
["Read beside: show the Read view beside the editor", "Lire à côté : afficher Lire à côté de l’éditeur", "横に閲覧: エディターの横に閲覧を表示", "并排阅读:在编辑器旁显示阅读"], ["Split: Read beside the editor", "Diviser : Lire à côté de l’éditeur", "分割: エディターの横に閲覧を表示", "分栏:在编辑器旁显示阅读"],
["Switch between Write and Source", "Alterner entre Écrire et Source", "「書く」と「ソース」を切り替え", "在写作和源码之间切换"], ["Switch between Write and Source", "Alterner entre Écrire et Source", "「書く」と「ソース」を切り替え", "在写作和源码之间切换"],
["Switch between Read and the editor", "Alterner entre Lire et l’éditeur", "「閲覧」とエディターを切り替え", "在阅读和编辑器之间切换"], ["Switch between Read and the editor", "Alterner entre Lire et l’éditeur", "「閲覧」とエディターを切り替え", "在阅读和编辑器之间切换"],
["Unsaved", "Non enregistré", "未保存", "未保存"], ["Unsaved", "Non enregistré", "未保存", "未保存"],
@@ -3684,8 +3680,7 @@ export const messageRows: [string, string, string, string][] = [
["Loading page {page}…", "Chargement de la page {page}…", "{page} ページを読み込み中…", "正在加载第 {page} 页…"], ["Loading page {page}…", "Chargement de la page {page}…", "{page} ページを読み込み中…", "正在加载第 {page} 页…"],
["Page {page} of {count}", "Page {page} sur {count}", "{page} / {count} ページ", "第 {page} 页,共 {count} 页"], ["Page {page} of {count}", "Page {page} sur {count}", "{page} / {count} ページ", "第 {page} 页,共 {count} 页"],
["PDF page {page}", "Page PDF {page}", "PDF の {page} ページ", "PDF 第 {page} 页"], ["PDF page {page}", "Page PDF {page}", "PDF の {page} ページ", "PDF 第 {page} 页"],
["PDF pages", "Pages du PDF", "PDF のページ", "PDF 页面"], ["PDF page. Use Page Up and Page Down to change pages.", "Page PDF. Utilisez Page préc. et Page suiv. pour changer de page.", "PDF のページ。Page Up と Page Down でページを切り替えます。", "PDF 页面。使用 Page Up 和 Page Down 翻页。"],
["Zoom percent", "Pourcentage de zoom", "ズームの倍率", "缩放百分比"],
["PDF password", "Mot de passe du PDF", "PDF のパスワード", "PDF 密码"], ["PDF password", "Mot de passe du PDF", "PDF のパスワード", "PDF 密码"],
["Unlock", "Déverrouiller", "ロック解除", "解锁"], ["Unlock", "Déverrouiller", "ロック解除", "解锁"],
["This PDF needs a password.", "Ce PDF nécessite un mot de passe.", "この PDF にはパスワードが必要です。", "此 PDF 需要密码。"], ["This PDF needs a password.", "Ce PDF nécessite un mot de passe.", "この PDF にはパスワードが必要です。", "此 PDF 需要密码。"],
+2 -3
View File
@@ -11,10 +11,9 @@
error?: string | null; error?: string | null;
onOpen: (entry: Backlink) => void; onOpen: (entry: Backlink) => void;
onRebuild?: () => void; onRebuild?: () => void;
/** The owner keeps this value, so the choice survives when the section closes with its tab. */
expanded?: boolean;
}; };
let { entries, busy = false, error = null, onOpen, onRebuild, expanded = $bindable(true) }: Props = $props(); let { entries, busy = false, error = null, onOpen, onRebuild }: Props = $props();
let expanded = $state(true);
const contentId = $props.id(); const contentId = $props.id();
function collapseTooltip(node: HTMLElement) { function collapseTooltip(node: HTMLElement) {
return { destroy: attachTooltip(node, () => $t(expanded ? "Collapse backlinks" : "Expand backlinks")) }; return { destroy: attachTooltip(node, () => $t(expanded ? "Collapse backlinks" : "Expand backlinks")) };
+45 -184
View File
@@ -1,35 +1,26 @@
<script lang="ts"> <script lang="ts">
// The document area: the panes of documents and plugin editor views, with the save conflict banner of each document. // The document area: plugin editor panes over the document panes, with the save conflict banner of each document.
// A plugin view stays in the plugin layer above the document panes, so that a move between panes does not mount it again.
// Without a pane, the layer shows the focused plugin view over the whole area. In a pane, the view covers its pane.
// A divider between two panes changes the ratio of their split. A tab that the user drags over the area shows a drop hint.
import type { ComponentProps } from "svelte"; import type { ComponentProps } from "svelte";
import { t } from "$lib/i18n"; import { t } from "$lib/i18n";
import PluginEditor from "$lib/plugins/PluginEditor.svelte"; import PluginEditor from "$lib/plugins/PluginEditor.svelte";
import { pluginEditors, pluginView, selectPluginEditor, type OpenPluginView } from "$lib/plugins/external"; import { pluginEditors, pluginView, selectPluginEditor } from "$lib/plugins/external";
import type { Documents } from "$lib/workspace/documents.svelte"; import type { Documents } from "$lib/workspace/documents.svelte";
import type { OpenBuffer } from "$lib/workspace/types"; import type { OpenBuffer } from "$lib/workspace/types";
import EditorPane from "./EditorPane.svelte"; import EditorPane from "./EditorPane.svelte";
import Icon from "$lib/ui/Icon.svelte"; import Icon from "$lib/ui/Icon.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import { paneBounds, splitDividers, stackLayout, type SplitDivider, type SplitLayout, type SplitPath } from "$lib/workspace/splitLayout";
import type { PaneDrop } from "$lib/workspace/documentPanes";
import { attachTooltip } from "$lib/ui/tooltip";
import type { ViewMode } from "./ViewModes.svelte"; import type { ViewMode } from "./ViewModes.svelte";
import TabBar from "./TabBar.svelte";
type EditorProps = ComponentProps<typeof EditorPane>; type EditorProps = ComponentProps<typeof EditorPane>;
type DocumentView = { id: string; reading: boolean; split: boolean; buffer: OpenBuffer | null; pluginKey: string | null }; type DocumentView = { id: string; reading: boolean; split: boolean; buffer: OpenBuffer | null; bounds: { width: number } };
/** The pane under a dragged tab, and the place of the drop on it. */ type Bounds = { left: number; top: number; width: number; height: number };
type DropTarget = { pane: string; zone: PaneDrop };
type Props = { type Props = {
/** The focused plugin view covers the whole area. */ editorPluginVisible: boolean;
pluginCover: boolean; split: boolean;
/** The drop hint of a dragged tab. */ pluginBounds: Record<string, Bounds | undefined>;
drop: DropTarget | null; tabBar: ComponentProps<typeof TabBar>;
onResize: (path: SplitPath, ratio: number) => void;
pluginPaneComponents: Record<string, PluginEditor | undefined>; pluginPaneComponents: Record<string, PluginEditor | undefined>;
documentViews: DocumentView[]; documentViews: DocumentView[];
layout: SplitLayout;
activePane: string; activePane: string;
paneComponents: Record<string, EditorPane | undefined>; paneComponents: Record<string, EditorPane | undefined>;
documents: Documents | null; documents: Documents | null;
@@ -55,112 +46,37 @@
onCursor: (pane: DocumentView, line: number, column: number) => void; onCursor: (pane: DocumentView, line: number, column: number) => void;
onOpenLink: (pane: DocumentView, kind: "md" | "wiki", target: string) => void; onOpenLink: (pane: DocumentView, kind: "md" | "wiki", target: string) => void;
}; };
let { pluginCover, drop, onResize, pluginPaneComponents = $bindable(), documentViews, layout, activePane, paneComponents = $bindable(), let { editorPluginVisible, split, pluginBounds, tabBar, pluginPaneComponents = $bindable(), documentViews, activePane, paneComponents = $bindable(),
documents, tabs, hasWorkspace, browserOpening, focusLine, onFocusPane, onCloseSplit, onSaveCopy, onOpenWorkspace, onNewFile, onNewNote, documents, tabs, hasWorkspace, browserOpening, focusLine, onFocusPane, onCloseSplit, onSaveCopy, onOpenWorkspace, onNewFile, onNewNote,
onQuickOpen, onOpenBrowser, onChange, onInsertImage, onRenameTitle, tableActions, linkActions, onView, onSplitView, onCursor, onOpenLink }: Props = $props(); onQuickOpen, onOpenBrowser, onChange, onInsertImage, onRenameTitle, tableActions, linkActions, onView, onSplitView, onCursor, onOpenLink }: Props = $props();
// A narrow area shows the panes one above the other, in the same order.
let width = $state(0);
const stacked = $derived(width > 0 && width <= 640);
const bounds = $derived(paneBounds(stacked ? stackLayout(layout) : layout));
const hosts = $derived(new Map(documentViews.flatMap(pane => pane.pluginKey ? [[pane.pluginKey, pane.id] as const] : [])));
const several = $derived(documentViews.length > 1);
function focusPlugin(view: OpenPluginView, host: string | undefined) {
if (host) onFocusPane(host);
else if ($pluginView?.key !== view.key) selectPluginEditor(view);
}
let area: HTMLElement;
const full = { left: 0, top: 0, width: 100, height: 100 };
const dividers = $derived(pluginCover || !several ? [] : splitDividers(stacked ? stackLayout(layout) : layout));
/** The place of the divider: the line between the two sides of its split, in percent of the area. */
function dividerStyle(divider: SplitDivider) {
const { bounds: box, ratio } = divider;
return divider.direction === "right"
? `left:${box.left + box.width * ratio}%;top:${box.top}%;height:${box.height}%`
: `top:${box.top + box.height * ratio}%;left:${box.left}%;width:${box.width}%`;
}
function ratioAt(divider: SplitDivider, x: number, y: number) {
const rect = area.getBoundingClientRect(), box = divider.bounds;
return divider.direction === "right"
? (x - rect.left - rect.width * box.left / 100) / (rect.width * box.width / 100)
: (y - rect.top - rect.height * box.top / 100) / (rect.height * box.height / 100);
}
let resizing = $state<"right" | "down" | null>(null);
function startResize(event: PointerEvent, divider: SplitDivider) {
if (event.button !== 0) return;
event.preventDefault();
const handle = event.currentTarget as HTMLElement;
handle.setPointerCapture(event.pointerId);
handle.focus({ preventScroll: true });
resizing = divider.direction;
const move = (next: PointerEvent) => onResize(divider.path, ratioAt(divider, next.clientX, next.clientY));
const end = () => {
resizing = null;
handle.removeEventListener("pointermove", move);
handle.removeEventListener("pointerup", end);
handle.removeEventListener("pointercancel", end);
};
handle.addEventListener("pointermove", move);
handle.addEventListener("pointerup", end);
handle.addEventListener("pointercancel", end);
}
function resizeKey(event: KeyboardEvent, divider: SplitDivider) {
const steps: Record<string, number> = divider.direction === "right" ? { ArrowLeft: -0.05, ArrowRight: 0.05 } : { ArrowUp: -0.05, ArrowDown: 0.05 };
if (event.key in steps) onResize(divider.path, divider.ratio + steps[event.key]);
else if (event.key === "Home") onResize(divider.path, 0.1);
else if (event.key === "End") onResize(divider.path, 0.9);
else if (event.key === "Enter") onResize(divider.path, 0.5);
else return;
event.preventDefault();
}
function tooltip(node: HTMLElement, text: string) {
let label = text;
const dispose = attachTooltip(node, () => label);
return { update(value: string) { label = value; }, destroy: dispose };
}
/**
* The drop target under a point: a pane, and the place on it. The right and bottom sides open a new pane.
* While a plugin view covers the area, the area is one pane. A narrow area opens new panes only below.
*/
export function dropAt(x: number, y: number): DropTarget | null {
const rect = area?.getBoundingClientRect();
if (!rect || !rect.width || !rect.height || x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) return null;
const px = (x - rect.left) / rect.width * 100, py = (y - rect.top) / rect.height * 100;
const pane = pluginCover ? activePane : documentViews.find(view => {
const box = bounds[view.id];
return box && px >= box.left && px <= box.left + box.width && py >= box.top && py <= box.top + box.height;
})?.id;
const box = pane ? (pluginCover ? full : bounds[pane]) : undefined;
if (!pane || !box) return null;
const rx = (px - box.left) / box.width, ry = (py - box.top) / box.height;
return { pane, zone: rx > 0.7 && !stacked ? "right" : ry > 0.7 ? "down" : "center" };
}
const dropBox = $derived.by(() => {
if (!drop) return null;
const box = pluginCover ? full : bounds[drop.pane];
if (!box) return null;
if (drop.zone === "right") return { ...box, left: box.left + box.width / 2, width: box.width / 2 };
if (drop.zone === "down") return { ...box, top: box.top + box.height / 2, height: box.height / 2 };
return box;
});
</script> </script>
<main class="center" class:resizing={!!resizing} class:resizing-down={resizing === "down"} bind:this={area} bind:clientWidth={width}> <main class="center">
<div class="editor-host" class:plugin-covered={pluginCover}> <div class="plugin-panes" class:inactive={!editorPluginVisible}>
<div class="document-panes" class:split={several}> {#each $pluginEditors as pane (pane.key)}
{@const bounds = pluginBounds[pane.key]}
<!-- svelte-ignore a11y_no_static_element_interactions (Focus selects the pane that owns the input.) -->
<div class="plugin-pane" class:inactive={!bounds} class:split class:focused={$pluginView?.key === pane.key}
style:left={`${bounds?.left ?? 0}%`} style:top={`${bounds?.top ?? 0}%`}
style:width={`${bounds?.width ?? 100}%`} style:height={`${bounds?.height ?? 100}%`}
onfocusin={() => { if ($pluginView?.key !== pane.key) selectPluginEditor(pane); }}
onpointerdown={() => { if ($pluginView?.key !== pane.key) selectPluginEditor(pane); }}>
{#if split && bounds}
<TabBar {...tabBar} tabs={tabBar.tabs.filter(tab => tab.id === pane.key)} />
{/if}
<PluginEditor bind:this={pluginPaneComponents[pane.key]} view={pane} />
</div>
{/each}
</div>
<div class="editor-host" class:plugin-covered={editorPluginVisible}>
<div class="document-panes" class:split={documentViews.length > 1}>
{#each documentViews as pane (pane.id)} {#each documentViews as pane (pane.id)}
{@const box = bounds[pane.id]}
<!-- svelte-ignore a11y_no_static_element_interactions (Focus identifies the document for shared commands.) --> <!-- svelte-ignore a11y_no_static_element_interactions (Focus identifies the document for shared commands.) -->
<div class="document-pane" class:focused={activePane === pane.id} class:edge-left={(box?.left ?? 0) > 0} class:edge-top={(box?.top ?? 0) > 0} <div class="document-pane" class:focused={activePane === pane.id}
data-document-pane={pane.id} data-document-path={pane.buffer?.relPath ?? ""} data-document-pane={pane.id} data-document-path={pane.buffer?.relPath ?? ""}
style:left={`${box?.left ?? 0}%`} style:top={`${box?.top ?? 0}%`} style:--pane-weight={pane.bounds.width}
style:width={`${box?.width ?? 100}%`} style:height={`${box?.height ?? 100}%`}
onpointerdowncapture={() => onFocusPane(pane.id)} onpointerdowncapture={() => onFocusPane(pane.id)}
onfocusin={() => onFocusPane(pane.id)}> onfocusin={() => onFocusPane(pane.id)}>
<!-- A pane with a plugin view stays empty. The plugin layer shows the view over it. -->
{#if !pane.pluginKey}
{#if pane.buffer?.diskError} {#if pane.buffer?.diskError}
<div class="conflict" role="alert"><Icon icon="alert" /><span>{pane.buffer.diskError}</span><button class="primary" onclick={() => void documents?.refresh()}>{$t("Retry")}</button><button onclick={() => onSaveCopy(pane.buffer)}>{$t("Save a copy")}</button></div> <div class="conflict" role="alert"><Icon icon="alert" /><span>{pane.buffer.diskError}</span><button class="primary" onclick={() => void documents?.refresh()}>{$t("Retry")}</button><button onclick={() => onSaveCopy(pane.buffer)}>{$t("Save a copy")}</button></div>
{:else if pane.buffer?.diskContents != null} {:else if pane.buffer?.diskContents != null}
@@ -178,7 +94,7 @@
bind:this={paneComponents[pane.id]} bind:this={paneComponents[pane.id]}
{tabs} {tabs}
active={activePane === pane.id} active={activePane === pane.id}
onCloseSplit={several ? () => onCloseSplit(pane.id) : undefined} onCloseSplit={documentViews.length > 1 ? () => onCloseSplit(pane.id) : undefined}
{hasWorkspace} {hasWorkspace}
{onOpenWorkspace} {onOpenWorkspace}
{onNewFile} {onNewFile}
@@ -201,50 +117,10 @@
onCursor={(line, column) => onCursor(pane, line, column)} onCursor={(line, column) => onCursor(pane, line, column)}
onOpenLink={(kind, target) => onOpenLink(pane, kind, target)} onOpenLink={(kind, target) => onOpenLink(pane, kind, target)}
/> />
{/if}
</div> </div>
{/each} {/each}
</div> </div>
</div> </div>
<div class="plugin-panes">
{#each $pluginEditors as view (view.key)}
{@const host = pluginCover ? undefined : hosts.get(view.key)}
{@const box = pluginCover ? ($pluginView?.key === view.key ? full : undefined) : host ? bounds[host] : undefined}
<!-- svelte-ignore a11y_no_static_element_interactions (Focus selects the pane that owns the input.) -->
<div class="plugin-pane" class:inactive={!box} class:embedded={!!host}
class:focused={host ? activePane === host : $pluginView?.key === view.key}
class:edge-left={!!host && (box?.left ?? 0) > 0} class:edge-top={!!host && (box?.top ?? 0) > 0}
data-plugin-pane={view.key}
style:left={`${box?.left ?? 0}%`} style:top={`${box?.top ?? 0}%`}
style:width={`${box?.width ?? 100}%`} style:height={`${box?.height ?? 100}%`}
onfocusin={() => focusPlugin(view, host)}
onpointerdowncapture={() => focusPlugin(view, host)}>
{#if host && several}
<div class="pane-bar">
<span class="pane-title" title={view.title}>{view.title}</span>
<IconButton icon="close" label={$t("Close split")} onclick={() => onCloseSplit(host)} />
</div>
{/if}
<PluginEditor bind:this={pluginPaneComponents[view.key]} {view} />
</div>
{/each}
</div>
{#each dividers as divider (divider.path.join("/"))}
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (A focusable separator is the splitter pattern.) -->
<div class="divider" class:vertical={divider.direction === "right"} style={dividerStyle(divider)}
role="separator" tabindex="0" aria-label={$t("Resize panes")}
aria-orientation={divider.direction === "right" ? "vertical" : "horizontal"}
aria-valuemin={10} aria-valuemax={90} aria-valuenow={Math.round(divider.ratio * 100)}
use:tooltip={$t("Drag to resize the panes. Double-click to give them equal sizes.")}
onpointerdown={event => startResize(event, divider)}
ondblclick={() => onResize(divider.path, 0.5)}
onkeydown={event => resizeKey(event, divider)}></div>
{/each}
{#if dropBox && drop}
<div class="drop-hint" data-drop-zone={drop.zone} style:left={`${dropBox.left}%`} style:top={`${dropBox.top}%`} style:width={`${dropBox.width}%`} style:height={`${dropBox.height}%`}>
<span>{drop.zone === "center" ? $t("Show here") : drop.zone === "right" ? $t("Open to the right") : $t("Open below")}</span>
</div>
{/if}
</main> </main>
<style> <style>
@@ -279,34 +155,19 @@
container-type: inline-size; container-type: inline-size;
} }
/* Each pane has its place in the split layout. A pane beside or below another pane has a border on that edge. */ .document-panes { flex: 1; min-height: 0; display: flex; overflow: hidden; }
.document-panes { position: relative; flex: 1; min-height: 0; overflow: hidden; } .document-pane { flex: var(--pane-weight) 1 0; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
.document-pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; overflow: hidden; box-sizing: border-box; } .document-pane + .document-pane { border-left: 1px solid var(--rs-border); }
.edge-left { border-left: 1px solid var(--rs-border); }
.edge-top { border-top: 1px solid var(--rs-border); }
.document-panes.split .document-pane.focused :global(.chrome-bar) { background: var(--rs-bg-active); } .document-panes.split .document-pane.focused :global(.chrome-bar) { background: var(--rs-bg-active); }
@container (max-width: 640px) {
.document-panes.split { flex-direction: column; overflow-y: auto; }
.document-panes.split .document-pane { flex: 1 0 320px; }
.document-pane + .document-pane { border-left: 0; border-top: 1px solid var(--rs-border); }
}
.editor-host.plugin-covered { display: none; } .editor-host.plugin-covered { display: none; }
/* The plugin layer covers the area, but only its visible panes take the pointer. */ .plugin-panes { position: relative; flex: 1; min-height: 0; min-width: 0; overflow: hidden; }
.plugin-panes { position: absolute; inset: 0; overflow: hidden; pointer-events: none; } .plugin-pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; box-sizing: border-box; }
.plugin-pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; box-sizing: border-box; pointer-events: auto; } .plugin-pane.split { border: 1px solid var(--rs-border); }
.plugin-pane.embedded { background: var(--rs-bg); } .plugin-pane.split.focused { border-color: var(--rs-accent); }
.plugin-pane.inactive { display: none; } .plugin-panes.inactive, .plugin-pane.inactive { display: none; }
/* The bar of a plugin view in a pane matches the chrome bar of a document pane. */
.pane-bar { display: flex; align-items: center; gap: 8px; min-height: 34px; flex: 0 0 auto; padding: 0 10px; background: var(--rs-bg); border-bottom: 1px solid var(--rs-border); color: var(--rs-text-dim); }
.plugin-pane.focused .pane-bar { background: var(--rs-bg-active); }
.pane-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* A divider is a wide, invisible target over the border between two panes. It shows the accent color on hover and focus. */
.divider { position: absolute; z-index: 3; height: 8px; margin-top: -4px; cursor: row-resize; touch-action: none; }
.divider.vertical { width: 8px; margin-top: 0; margin-left: -4px; cursor: col-resize; }
.divider::after { content: ""; position: absolute; inset: 3px 0; border-radius: 1px; }
.divider.vertical::after { inset: 0 3px; }
.divider:hover::after, .divider:focus-visible::after, .center.resizing .divider:focus::after { background: var(--rs-accent); }
.divider:focus-visible { outline: none; }
.center.resizing { cursor: col-resize; user-select: none; }
.center.resizing-down { cursor: row-resize; }
.center.resizing .document-panes, .center.resizing .plugin-pane { pointer-events: none; }
/* The drop hint shows where a dragged tab goes. */
.drop-hint { position: absolute; z-index: 4; box-sizing: border-box; display: flex; align-items: center; justify-content: center; pointer-events: none;
border: 2px solid var(--rs-accent); border-radius: var(--rs-control-radius); background: color-mix(in srgb, var(--rs-accent) 16%, transparent); }
.drop-hint span { padding: 4px 10px; border-radius: var(--rs-control-radius); background: var(--rs-accent); color: var(--rs-on-accent); font-weight: 600; }
</style> </style>
+1 -3
View File
@@ -147,9 +147,7 @@
const splitView = $derived(split && canPreview && !reading); const splitView = $derived(split && canPreview && !reading);
const view: ViewMode = $derived(readOnly ? "read" : chrome === "Source" ? "source" : "write"); const view: ViewMode = $derived(readOnly ? "read" : chrome === "Source" ? "source" : "write");
// The tab already names the file, so the breadcrumb shows only its folder. // The tab already names the file, so the breadcrumb shows only its folder.
// Beside other panes, the breadcrumb also names the file, because the tab bar names only the file of the active pane. const folder = $derived(buffer?.relPath.includes("/") ? buffer.relPath.slice(0, buffer.relPath.lastIndexOf("/")).split("/").join(" / ") : "");
const folder = $derived(!buffer ? "" : onCloseSplit ? buffer.relPath.split("/").join(" / ")
: buffer.relPath.includes("/") ? buffer.relPath.slice(0, buffer.relPath.lastIndexOf("/")).split("/").join(" / ") : "");
</script> </script>
{#if !buffer || buffer.kind === "empty"} {#if !buffer || buffer.kind === "empty"}
-4
View File
@@ -43,8 +43,6 @@
workspaceRoot: string; workspaceRoot: string;
activePath: string | null; activePath: string | null;
onOpenFile: (entry: TreeEntry, newTab?: boolean) => void; onOpenFile: (entry: TreeEntry, newTab?: boolean) => void;
/** Open the file in a new pane to the right of the active pane. */
onOpenRight?: (entry: TreeEntry) => void;
session: WorkspaceSession; session: WorkspaceSession;
onStatus?: (message: string) => void; onStatus?: (message: string) => void;
onCreated?: (entry: TreeEntry) => void; onCreated?: (entry: TreeEntry) => void;
@@ -58,7 +56,6 @@
workspaceRoot, workspaceRoot,
activePath, activePath,
onOpenFile, onOpenFile,
onOpenRight,
session, session,
onStatus, onStatus,
onCreated, onCreated,
@@ -881,7 +878,6 @@
...(!multiple && entry.kind === "folder" ? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }] : []), ...(!multiple && entry.kind === "folder" ? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }] : []),
...(!multiple && entry.kind === "file" ? [ ...(!multiple && entry.kind === "file" ? [
{ kind: "action" as const, label: $t("Open in new tab"), icon: "tab" as const, run: () => onOpenFile(entry, true) }, { kind: "action" as const, label: $t("Open in new tab"), icon: "tab" as const, run: () => onOpenFile(entry, true) },
...(onOpenRight ? [{ kind: "action" as const, label: $t("Open to the right"), icon: "split-right" as const, run: () => onOpenRight(entry) }] : []),
{ kind: "action" as const, label: $t("Open in default app"), icon: "external" as const, run: () => { void workspaceOpenDefault(entry.rel_path).catch(reason => error = String(reason)); } }, { kind: "action" as const, label: $t("Open in default app"), icon: "external" as const, run: () => { void workspaceOpenDefault(entry.rel_path).catch(reason => error = String(reason)); } },
] : []), ] : []),
terminalItem(parent), terminalItem(parent),
+1 -3
View File
@@ -29,14 +29,13 @@
onHelp: () => void; onHelp: () => void;
onSettings: () => void; onSettings: () => void;
onOpenFile: (entry: TreeEntry, line?: number, target?: "current" | "new") => void; onOpenFile: (entry: TreeEntry, line?: number, target?: "current" | "new") => void;
onOpenRight?: (entry: TreeEntry) => void;
onCreated: (entry: TreeEntry) => void; onCreated: (entry: TreeEntry) => void;
onSaveTemplate: (entry: TreeEntry) => void; onSaveTemplate: (entry: TreeEntry) => void;
onManageTemplates: () => void; onManageTemplates: () => void;
onStatus: (message: string) => void; onStatus: (message: string) => void;
}; };
let { workspace, session, leftView, keysActive, showInternal, activePath, searchRequest, fileTree = $bindable(), workspaceAnchor = $bindable(), let { workspace, session, leftView, keysActive, showInternal, activePath, searchRequest, fileTree = $bindable(), workspaceAnchor = $bindable(),
onOpenFile, onOpenRight, onCreated, onSaveTemplate, onManageTemplates, onStatus, onChooseWorkspace, onHelp, onSettings }: Props = $props(); onOpenFile, onCreated, onSaveTemplate, onManageTemplates, onStatus, onChooseWorkspace, onHelp, onSettings }: Props = $props();
function tooltip(node: HTMLElement, text: string) { function tooltip(node: HTMLElement, text: string) {
let current = text; let current = text;
@@ -64,7 +63,6 @@
{onManageTemplates} {onManageTemplates}
{activePath} {activePath}
onOpenFile={(entry, newTab) => onOpenFile(entry, undefined, newTab ? "new" : "current")} onOpenFile={(entry, newTab) => onOpenFile(entry, undefined, newTab ? "new" : "current")}
{onOpenRight}
{session} {session}
{keysActive} {keysActive}
{onCreated} {onCreated}
+2 -6
View File
@@ -4,7 +4,6 @@
import { tick, type Snippet } from "svelte"; import { tick, type Snippet } from "svelte";
import { workspaceReadDataUrl } from "$lib/workspace/api"; import { workspaceReadDataUrl } from "$lib/workspace/api";
import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml"; import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml";
import { loadImageSize } from "$lib/workspace/imageSizes";
import { renderDiagrams } from "$lib/workspace/diagrams"; import { renderDiagrams } from "$lib/workspace/diagrams";
import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media"; import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media";
import { imageControls } from "$lib/editor/imageControls"; import { imageControls } from "$lib/editor/imageControls";
@@ -56,9 +55,7 @@
const base = normalized.split("/").pop() ?? path; const base = normalized.split("/").pop() ?? path;
for (const candidate of new Set([primary, normalized, base])) { for (const candidate of new Set([primary, normalized, base])) {
try { try {
const url = await workspaceReadDataUrl(candidate); urls.set(source, await workspaceReadDataUrl(candidate));
await loadImageSize(url);
urls.set(source, url);
return; return;
} catch { /* Try the workspace-relative attachment next. */ } } catch { /* Try the workspace-relative attachment next. */ }
} }
@@ -105,8 +102,7 @@
[...el.querySelectorAll<HTMLElement>("h1, h2, h3, h4, h5, h6")].filter(heading => !heading.classList.contains("document-title"))[index]; [...el.querySelectorAll<HTMLElement>("h1, h2, h3, h4, h5, h6")].filter(heading => !heading.classList.contains("document-title"))[index];
if (!target) return; if (!target) return;
currentHeadings?.reveal(target); currentHeadings?.reveal(target);
// The heading starts the text to read, so it goes to the top. Its scroll margin keeps a gap above it (reading.css). target.scrollIntoView({ block: "center" });
target.scrollIntoView({ block: "start" });
el.focus({ preventScroll: true }); el.focus({ preventScroll: true });
}); });
return renderDiagrams(el, () => cancelled); return renderDiagrams(el, () => cancelled);
+2 -3
View File
@@ -13,9 +13,8 @@
backlinks: Backlink[]; backlinks: Backlink[];
session: WorkspaceSession; session: WorkspaceSession;
onOpenBacklink: (entry: Backlink) => void; onOpenBacklink: (entry: Backlink) => void;
backlinksOpen?: boolean;
}; };
let { outlineItems, onJump, showBacklinks, backlinks, session, onOpenBacklink, backlinksOpen = $bindable(true) }: Props = $props(); let { outlineItems, onJump, showBacklinks, backlinks, session, onOpenBacklink }: Props = $props();
</script> </script>
<aside class="right"> <aside class="right">
@@ -23,7 +22,7 @@
<OutlinePane items={outlineItems} {onJump} /> <OutlinePane items={outlineItems} {onJump} />
</div> </div>
{#if showBacklinks} {#if showBacklinks}
<Backlinks bind:expanded={backlinksOpen} entries={backlinks} busy={session.indexBusy} error={session.indexError} onOpen={onOpenBacklink} onRebuild={() => void session.rebuildIndex()} /> <Backlinks entries={backlinks} busy={session.indexBusy} error={session.indexError} onOpen={onOpenBacklink} onRebuild={() => void session.rebuildIndex()} />
{/if} {/if}
</aside> </aside>
+3 -42
View File
@@ -27,14 +27,9 @@
tabDragData?: (tab: WorkbenchTab) => string | undefined; tabDragData?: (tab: WorkbenchTab) => string | undefined;
onDropTab?: (data: string, index: number) => void; onDropTab?: (data: string, index: number) => void;
onDetach?: (tab: WorkbenchTab) => void; onDetach?: (tab: WorkbenchTab) => void;
/** A tab drag outside the tab bar. The result tells whether the point can take the tab, for example a document pane. */
onDragAt?: (relPath: string, x: number, y: number) => boolean;
/** A tab drop outside the tab bar. The result tells whether the drop used the tab. */
onDropAt?: (relPath: string, x: number, y: number) => boolean;
onDragEnd?: () => void;
}; };
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab, onDetach, onDragAt, onDropAt, onDragEnd }: Props = $props(); let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab, onDetach }: Props = $props();
const transferType = "application/x-runestone-tab"; const transferType = "application/x-runestone-tab";
let bar: HTMLDivElement; let bar: HTMLDivElement;
let dragged = $state<string | null>(null); let dragged = $state<string | null>(null);
@@ -66,34 +61,6 @@
suppressClick = true; suppressClick = true;
event.dataTransfer.effectAllowed = "move"; event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData(transferType, data); event.dataTransfer.setData(transferType, data);
watchAreaDrop(tab.relPath);
}
// A tab that leaves the tab bar can go to a pane of the document area. The listeners run first, in the capture
// phase, so that an editor under the pointer does not take the drop.
let stopAreaDrop = () => {};
function watchAreaDrop(path: string) {
stopAreaDrop();
if (!onDragAt || !onDropAt) return;
const inBar = (event: DragEvent) => event.target instanceof Node && bar.contains(event.target);
const over = (event: DragEvent) => {
if (inBar(event) || !onDragAt?.(path, event.clientX, event.clientY)) return;
event.preventDefault(); event.stopPropagation();
if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
};
const drop = (event: DragEvent) => {
if (inBar(event) || !onDropAt?.(path, event.clientX, event.clientY)) return;
event.preventDefault(); event.stopPropagation();
finishTabTransfer();
};
window.addEventListener("dragover", over, true);
window.addEventListener("drop", drop, true);
stopAreaDrop = () => {
window.removeEventListener("dragover", over, true);
window.removeEventListener("drop", drop, true);
stopAreaDrop = () => {};
onDragEnd?.();
};
} }
function transferIndex(x: number) { function transferIndex(x: number) {
@@ -118,7 +85,6 @@
} }
function finishTabTransfer() { function finishTabTransfer() {
stopAreaDrop();
dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false; dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false;
cancelAnimationFrame(transferFrame); transferFrame = 0; cancelAnimationFrame(transferFrame); transferFrame = 0;
} }
@@ -323,7 +289,6 @@
frame = requestAnimationFrame(scroll); frame = requestAnimationFrame(scroll);
}; };
const clean = () => { const clean = () => {
if (started) onDragEnd?.();
if (pointerTarget.hasPointerCapture(pointerId)) pointerTarget.releasePointerCapture(pointerId); if (pointerTarget.hasPointerCapture(pointerId)) pointerTarget.releasePointerCapture(pointerId);
cancelAnimationFrame(frame); cancelAnimationFrame(frame);
dragged = dropBefore = dropAfter = null; dragged = dropBefore = dropAfter = null;
@@ -341,19 +306,15 @@
e.preventDefault(); e.preventDefault();
if (!started) { started = true; suppressClick = true; dragged = path; frame = requestAnimationFrame(scroll); } if (!started) { started = true; suppressClick = true; dragged = path; frame = requestAnimationFrame(scroll); }
update(); update();
if (destination === null) onDragAt?.(path, x, y);
else onDragEnd?.();
}; };
const onUp = (e: PointerEvent) => { const onUp = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return; if (e.pointerId !== pointerId) return;
x = e.clientX; y = e.clientY; x = e.clientX; y = e.clientY;
if (started) update(); if (started) update();
const target = destination; const target = destination;
const wasStarted = started;
clean(); clean();
if (wasStarted && target !== null) void move(path, target); if (started && target !== null) void move(path, target);
else if (wasStarted && onDropAt?.(path, x, y)) return; else if (started && (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight)) {
else if (wasStarted && (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight)) {
const tab = tabs.find(tab => tab.relPath === path); const tab = tabs.find(tab => tab.relPath === path);
if (tab) onDetach?.(tab); if (tab) onDetach?.(tab);
} }
+4 -4
View File
@@ -1,10 +1,10 @@
<script lang="ts" module> <script lang="ts" module>
/** The view of a document pane. Read beside is a separate toggle beside Write or Source. */ /** The view of a document pane. Split is a separate toggle beside Write or Source. */
export type ViewMode = "write" | "source" | "read"; export type ViewMode = "write" | "source" | "read";
</script> </script>
<script lang="ts"> <script lang="ts">
// The view control of a document pane: Write, Source, and Read in one radio group, then the Read beside toggle. // The view control of a document pane: Write, Source, and Read in one radio group, then the Split toggle.
// All choices stay visible. Narrow panes show only the icons. // All choices stay visible. Narrow panes show only the icons.
import { t } from "$lib/i18n"; import { t } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte"; import Icon from "$lib/ui/Icon.svelte";
@@ -16,7 +16,7 @@
type Props = { type Props = {
view: ViewMode; view: ViewMode;
split: boolean; split: boolean;
/** Markdown files have Read and Read beside. Other text files have only Write and Source. */ /** Markdown files have Read and Split. Other text files have only Write and Source. */
readable: boolean; readable: boolean;
onView: (view: ViewMode) => void; onView: (view: ViewMode) => void;
onSplit: (split: boolean) => void; onSplit: (split: boolean) => void;
@@ -60,7 +60,7 @@
{/each} {/each}
</div> </div>
{#if readable} {#if readable}
<button type="button" class="split" aria-pressed={split} aria-label={$t("Read beside")} use:tooltip={$t("Read beside: show the Read view beside the editor")} onclick={() => onSplit(!split)}> <button type="button" class="split" aria-pressed={split} aria-label={$t("Split")} use:tooltip={$t("Split: Read beside the editor")} onclick={() => onSplit(!split)}>
<Icon icon="split" /> <Icon icon="split" />
</button> </button>
{/if} {/if}
+25 -164
View File
@@ -6,14 +6,13 @@
import type PluginEditor from "$lib/plugins/PluginEditor.svelte"; import type PluginEditor from "$lib/plugins/PluginEditor.svelte";
import { featureOfOwner } from "$lib/features/catalog"; import { featureOfOwner } from "$lib/features/catalog";
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup, pluginTools, installedPlugins, runPluginCommand } from "$lib/plugins/external"; import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup, pluginTools, installedPlugins, runPluginCommand } from "$lib/plugins/external";
import { containsPane, paneBounds, splitSibling } from "$lib/workspace/splitLayout"; 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 { 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"; import { onMount, onDestroy, tick, untrack } from "svelte";
import type { MenuLink } from "$lib/editor/linkMenu"; import type { MenuLink } from "$lib/editor/linkMenu";
import { WorkspaceSession } from "$lib/workspace/session.svelte"; import { WorkspaceSession } from "$lib/workspace/session.svelte";
import { retainEditorStates } from "$lib/editor/editorStates"; import { retainEditorStates } from "$lib/editor/editorStates";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView, import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView } from "$lib/workspace/documentPanes";
paneOf, showInActivePane, splitWithContent, releaseSolePlugin, dropInPane, resizeDocumentPanes, type PaneContent, type PaneDrop, type DocumentPanes } from "$lib/workspace/documentPanes";
import type { ViewMode } from "./ViewModes.svelte"; import type { ViewMode } from "./ViewModes.svelte";
import { selectedEditorText } from "$lib/editor/selection"; import { selectedEditorText } from "$lib/editor/selection";
import { pluginHost } from "$lib/plugins/registry"; import { pluginHost } from "$lib/plugins/registry";
@@ -150,7 +149,6 @@
let searchRequest = $state<{ text: string; id: number } | null>(null); let searchRequest = $state<{ text: string; id: number } | null>(null);
let leftOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.leftOpen); let leftOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.leftOpen);
let rightOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.rightOpen); let rightOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.rightOpen);
let backlinksOpen = $state(DEFAULT_WORKBENCH_LAYOUT.backlinksOpen);
$effect(() => { if ($pluginSidebar && !transferredWindow) leftOpen = true; }); $effect(() => { if ($pluginSidebar && !transferredWindow) leftOpen = true; });
let terminalOpen = $state(false); let terminalOpen = $state(false);
let documentPanes = $state(initialDocumentPanes()); let documentPanes = $state(initialDocumentPanes());
@@ -230,9 +228,7 @@
}, () => { }, () => {
if (documents !== next) return; if (documents !== next) return;
const selected = next.active; const selected = next.active;
// While a plugin view has the focus, a document change does not replace the content of a pane. documentPanes = syncDocumentPanes(documentPanes, next.buffers.map(tab => tab.id), selected?.id ?? null);
const pluginFocused = $pluginEditorActive && $pluginView?.placement === "editor";
documentPanes = syncDocumentPanes(documentPanes, next.buffers.map(tab => tab.id), pluginFocused ? null : selected?.id ?? null);
if (selected) view = selected.chromeOverride ?? selected.chrome; if (selected) view = selected.chromeOverride ?? selected.chrome;
}); });
return next; return next;
@@ -241,8 +237,8 @@
onDestroy(() => retainEditorStates([])); onDestroy(() => retainEditorStates([]));
const documentViews = $derived.by(() => { const documentViews = $derived.by(() => {
const bounds = paneBounds(documentPanes.layout); const bounds = paneBounds(documentPanes.layout);
return documentPanes.panes.map(pane => ({ ...pane, buffer: tabs.find(tab => tab.id === pane.documentId) ?? null })) return documentPanes.panes.map(pane => ({ ...pane, buffer: tabs.find(tab => tab.id === pane.documentId) ?? null, bounds: bounds[pane.id] }))
.sort((a, b) => bounds[a.id].left - bounds[b.id].left || bounds[a.id].top - bounds[b.id].top); .sort((a, b) => a.bounds.left - b.bounds.left);
}); });
function setReading(next: boolean, paneId = documentPanes.active) { function setReading(next: boolean, paneId = documentPanes.active) {
documentPanes = readDocumentPane(documentPanes, paneId, next); documentPanes = readDocumentPane(documentPanes, paneId, next);
@@ -252,13 +248,6 @@
if (!pane) return; if (!pane) return;
const tab = tabs.find(tab => tab.id === pane.documentId); const tab = tabs.find(tab => tab.id === pane.documentId);
documentPanes = selectPane(documentPanes, paneId); documentPanes = selectPane(documentPanes, paneId);
if (pane.pluginKey) {
const key = pane.pluginKey;
const view = $pluginEditors.find(view => view.key === key);
if (view && !($pluginEditorActive && $pluginView?.key === key)) selectPluginEditor(view);
if (focusEditor) void tick().then(() => { if (documentPanes.active === paneId) pluginPaneComponents[key]?.focus(); });
return;
}
pluginEditorActive.set(false); pluginEditorActive.set(false);
if (tab && documents?.active?.id !== tab.id) { focusLine = null; documents?.select(tab.relPath); } if (tab && documents?.active?.id !== tab.id) { focusLine = null; documents?.select(tab.relPath); }
if (focusEditor) void tick().then(() => { if (focusEditor) void tick().then(() => {
@@ -267,147 +256,27 @@
document.querySelector<HTMLElement>(`[data-document-pane="${paneId}"]`)?.scrollIntoView({ block: "nearest", inline: "nearest" }); document.querySelector<HTMLElement>(`[data-document-pane="${paneId}"]`)?.scrollIntoView({ block: "nearest", inline: "nearest" });
}); });
} }
/** Use a new pane state and focus its active pane. The last pane does not keep a plugin view. The view covers the area again. */
function changePanes(next: DocumentPanes) {
const released = releaseSolePlugin(next);
documentPanes = released.state;
const view = $pluginEditors.find(view => view.key === released.pluginKey);
if (view) {
selectPluginEditor(view);
void tick().then(() => pluginPaneComponents[view.key]?.focus());
} else focusDocumentPane(documentPanes.active, true);
}
function closeSplit(paneId: string) { function closeSplit(paneId: string) {
changePanes(closeDocumentPane(documentPanes, paneId)); documentPanes = closeDocumentPane(documentPanes, paneId);
focusDocumentPane(documentPanes.active, true);
} }
/** The plugin view that covers the document area moves into the active pane, so that a new pane can open beside it. */
function keepCoverInPane() {
if (coverKey) documentPanes = showInActivePane(documentPanes, { pluginKey: coverKey });
}
/** A plugin document that opens to the right, for example a PDF file: the source pane, and the plugin view that covers the area. */
let rightOf: { pane: string; cover: string | null } | null = null;
async function openToRight(file: TreeEntry, sourcePane: string) { async function openToRight(file: TreeEntry, sourcePane: string) {
const current = documents; const current = documents;
const covered = sourcePane === documentPanes.active ? coverKey : null;
const source = documentPanes.panes.find(pane => pane.id === sourcePane); const source = documentPanes.panes.find(pane => pane.id === sourcePane);
if (!current || switching || !source) return; if (!current || switching || !source) return;
const unchanged = () => {
const now = documentPanes.panes.find(pane => pane.id === sourcePane);
return documents === current && !switching && documentPanes.active === sourcePane && coverKey === covered
&& now?.documentId === source.documentId && now?.pluginKey === source.pluginKey;
};
const open = current.buffers.find(tab => tab.relPath === file.rel_path);
if (!(open && open.contents !== open.saved)) {
// The placement effect opens the plugin view in a new pane beside the source pane.
rightOf = { pane: sourcePane, cover: covered };
try {
const opened = await openPluginDocument(file.rel_path, unchanged);
await tick();
if (opened) return;
} finally { rightOf = null; }
}
await current.open(file, "background"); await current.open(file, "background");
if (!unchanged()) return; if (documents !== current || switching || documentPanes.active !== sourcePane
|| documentPanes.panes.find(pane => pane.id === sourcePane)?.documentId !== source.documentId) return;
const target = current.buffers.find(tab => tab.relPath === file.rel_path); const target = current.buffers.find(tab => tab.relPath === file.rel_path);
if (!target) return; if (!target) return;
keepCoverInPane();
documentPanes = splitDocumentPane(documentPanes, sourcePane, target.id, crypto.randomUUID()); documentPanes = splitDocumentPane(documentPanes, sourcePane, target.id, crypto.randomUUID());
focusDocumentPane(documentPanes.active, true); focusDocumentPane(documentPanes.active, true);
} }
function tabContent(tab: EditorTab): PaneContent {
return "plugin" in tab ? { pluginKey: tab.plugin.key } : { documentId: tab.buffer.id };
}
/** A visible tab is the plugin view over the area, or the content of a pane. */
function tabVisible(tab: EditorTab) {
if (coverKey) return "plugin" in tab && tab.plugin.key === coverKey;
return !!paneOf(documentPanes, tabContent(tab));
}
/** Show a tab in a new pane to the right of the active pane. The active pane keeps its content. */
function openTabToRight(tab: EditorTab) {
if (switching || tabVisible(tab)) return;
keepCoverInPane();
documentPanes = splitWithContent(documentPanes, documentPanes.active, tabContent(tab), crypto.randomUUID());
focusDocumentPane(documentPanes.active, true);
}
// A tab that the user drags from the tab bar to the document area: the pane and the place of the drop.
let documentArea: DocumentArea | undefined = $state();
let tabDrop = $state<{ pane: string; zone: PaneDrop } | null>(null);
function tabDropTarget(path: string, x: number, y: number) {
const tab = workingTabs.find(tab => tab.relPath === path);
const target = tab && !switching ? documentArea?.dropAt(x, y) ?? null : null;
if (!tab || !target) return null;
// A drop on the pane that shows the tab changes nothing.
if (coverKey ? "plugin" in tab && tab.plugin.key === coverKey : paneOf(documentPanes, tabContent(tab))?.id === target.pane) return null;
return { tab, target };
}
function tabDragAt(path: string, x: number, y: number) {
tabDrop = tabDropTarget(path, x, y)?.target ?? null;
return tabDrop !== null;
}
function tabDropAt(path: string, x: number, y: number) {
const found = tabDropTarget(path, x, y);
tabDrop = null;
if (!found) return false;
const { tab, target } = found;
if (coverKey) {
if (target.zone === "center") { selectWorkingTab(tab.relPath); return true; }
keepCoverInPane();
}
changePanes(dropInPane(documentPanes, tabContent(tab), target.pane, target.zone, crypto.randomUUID()));
return true;
}
// Each focused plugin view that is not in a pane gets a pane when the area has several panes.
// A new view that a plugin opens beside its own view, for example a browser tab, opens beside the pane of that view.
// When the own view covers the area, it moves into the pane first.
const placedPlugins = new Set<string>();
$effect(() => {
const view = $pluginEditorActive && $pluginView?.placement === "editor" ? $pluginView : null;
const splits = $pluginSplits;
if (!view) return;
untrack(() => {
const fresh = !placedPlugins.has(view.key);
placedPlugins.add(view.key);
const shown = paneOf(documentPanes, { pluginKey: view.key });
if (shown) { documentPanes = selectPane(documentPanes, shown.id); return; }
const right = rightOf;
if (right && documentPanes.panes.some(pane => pane.id === right.pane)) {
rightOf = null;
if (right.cover && right.cover !== view.key && !paneOf(documentPanes, { pluginKey: right.cover }))
documentPanes = showInActivePane(selectPane(documentPanes, right.pane), { pluginKey: right.cover });
documentPanes = splitWithContent(documentPanes, right.pane, { pluginKey: view.key }, crypto.randomUUID());
return;
}
const group = fresh ? splits.find(tree => containsPane(tree, view.key)) : undefined;
const beside = group ? splitSibling(group, view.key) : null;
if (documentPanes.panes.length < 2 && !beside) return;
if (beside && documentPanes.panes.length < 2 && !paneOf(documentPanes, { pluginKey: beside.sibling }))
documentPanes = showInActivePane(documentPanes, { pluginKey: beside.sibling });
const source = beside ? paneOf(documentPanes, { pluginKey: beside.sibling }) : undefined;
documentPanes = source && beside
? splitWithContent(documentPanes, source.id, { pluginKey: view.key }, crypto.randomUUID(), beside.direction)
: showInActivePane(documentPanes, { pluginKey: view.key });
});
});
// The selected document is visible while no plugin view has the focus.
$effect(() => {
const selected = $pluginEditorActive && $pluginView?.placement === "editor" ? null : buffer?.id ?? null;
if (selected) untrack(() => { documentPanes = showInActivePane(documentPanes, { documentId: selected }); });
});
// A closed plugin view leaves its pane. The last pane does not keep a plugin view.
$effect(() => {
const keys = $pluginEditors.map(view => view.key);
untrack(() => {
for (const key of placedPlugins) if (!keys.includes(key)) placedPlugins.delete(key);
documentPanes = releaseSolePlugin(syncDocumentPanes(documentPanes, tabs.map(tab => tab.id), null, keys)).state;
});
});
let focusLine = $state<number | null>(null); let focusLine = $state<number | null>(null);
let dragging = $state<"left" | "right" | "bottom" | null>(null); let dragging = $state<"left" | "right" | "bottom" | null>(null);
let centerStack: HTMLElement | undefined = $state(); let centerStack: HTMLElement | undefined = $state();
// A focused plugin view is the active tab. It covers the area only when no pane shows it.
const editorPluginVisible = $derived($pluginView?.placement === "editor" && $pluginEditorActive); const editorPluginVisible = $derived($pluginView?.placement === "editor" && $pluginEditorActive);
const coverKey = $derived(editorPluginVisible && $pluginView && !paneOf(documentPanes, { pluginKey: $pluginView.key }) ? $pluginView.key : null);
type EditorTab = WorkbenchTab & ({ buffer: OpenBuffer } | { plugin: OpenPluginView }); type EditorTab = WorkbenchTab & ({ buffer: OpenBuffer } | { plugin: OpenPluginView });
let tabOrder = $state<string[]>([]); let tabOrder = $state<string[]>([]);
const availableTabs = $derived<EditorTab[]>([ const availableTabs = $derived<EditorTab[]>([
@@ -494,7 +363,9 @@
} catch (reason) { error = String(reason); } } catch (reason) { error = String(reason); }
} }
const activeTabPath = $derived(editorPluginVisible && $pluginView ? `plugin:${$pluginView.key}` : activePath); const activeTabPath = $derived(editorPluginVisible && $pluginView ? `plugin:${$pluginView.key}` : activePath);
// The working tabs of the header. const activeSplit = $derived($pluginSplits.find(tree => $pluginView && containsPane(tree, $pluginView.key)));
const pluginBounds = $derived(activeSplit ? paneBounds(activeSplit) : $pluginView ? paneBounds($pluginView.key) : {});
// The working tabs, for the header and for the tab bar of each plugin pane in a split.
const tabBarProps = $derived({ tabs: workingTabs, activePath: activeTabPath, onSelect: selectWorkingTab, onClose: closeTab, const tabBarProps = $derived({ tabs: workingTabs, activePath: activeTabPath, onSelect: selectWorkingTab, onClose: closeTab,
onCloseTabs: (path: string, scope: TabCloseScope) => void closeTabs(path, scope), onPin: pinWorkingTab, fileActions: workingTabFileActions, onCloseTabs: (path: string, scope: TabCloseScope) => void closeTabs(path, scope), onPin: pinWorkingTab, fileActions: workingTabFileActions,
tabActions: workingTabActions, onMove: moveWorkingTab, tabDragData: workingTabDragData, onDropTab: (data: string, index: number) => void receiveTab(data, index) }); tabActions: workingTabActions, onMove: moveWorkingTab, tabDragData: workingTabDragData, onDropTab: (data: string, index: number) => void receiveTab(data, index) });
@@ -540,7 +411,7 @@
documents?.setChrome(next); documents?.setChrome(next);
} }
/** Show Write, Source, or Read in a pane. Write and Source keep Read beside. */ /** Show Write, Source, or Read in a pane. Write and Source keep a Split view. */
function setDocumentView(paneId: string, next: ViewMode) { function setDocumentView(paneId: string, next: ViewMode) {
focusDocumentPane(paneId); focusDocumentPane(paneId);
if (next === "read") { setReading(true, paneId); return; } if (next === "read") { setReading(true, paneId); return; }
@@ -685,8 +556,6 @@
pluginEditorActive.set(false); pluginEditorActive.set(false);
focusLine = null; focusLine = null;
documents?.select(relPath); documents?.select(relPath);
const selected = documents?.active?.id;
if (selected) documentPanes = showInActivePane(documentPanes, { documentId: selected });
focusDocumentPane(documentPanes.active, true); focusDocumentPane(documentPanes.active, true);
status = documents?.active?.kind === "empty" ? $t("New tab") : ""; status = documents?.active?.kind === "empty" ? $t("New tab") : "";
} }
@@ -715,11 +584,9 @@
} }
function workingTabActions(item: WorkbenchTab): ActionMenuItem[] { function workingTabActions(item: WorkbenchTab): ActionMenuItem[] {
const tab = workingTabs.find(tab => tab.id === item.id); const tab = workingTabs.find(tab => tab.id === item.id);
if (!tab) return []; const actions = tab && "plugin" in tab ? pluginTabActions(tab.plugin) : [];
const actions = "plugin" in tab ? pluginTabActions(tab.plugin) : []; if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return actions;
const right: ActionMenuItem = { label: $t("Open to the right"), icon: "split-right", disabled: tabVisible(tab), run: () => openTabToRight(tab) }; return tab ? [{ label: $t("Open in new window"), icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : [];
if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return [right, ...actions];
return [right, { label: $t("Open in new window"), icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions];
} }
async function detachTab(item: WorkbenchTab, keepSource = false) { async function detachTab(item: WorkbenchTab, keepSource = false) {
const tab = workingTabs.find(tab => tab.id === item.id); const tab = workingTabs.find(tab => tab.id === item.id);
@@ -854,7 +721,7 @@
{ label: $t("Source"), icon: "code", radio: true, checked: viewMode === "source", run: () => setDocumentView(documentPanes.active, "source") }, { label: $t("Source"), icon: "code", radio: true, checked: viewMode === "source", run: () => setDocumentView(documentPanes.active, "source") },
{ label: $t("Read"), icon: "book", radio: true, checked: viewMode === "read", run: () => setDocumentView(documentPanes.active, "read") }, { label: $t("Read"), icon: "book", radio: true, checked: viewMode === "read", run: () => setDocumentView(documentPanes.active, "read") },
{ separator: true }, { separator: true },
{ label: $t("Read beside"), icon: "split-right", checked: activeDocumentPane?.split === true && !reading, run: () => setSplitView(documentPanes.active, !(activeDocumentPane?.split && !reading)) }, { label: $t("Split"), icon: "split-right", checked: activeDocumentPane?.split === true && !reading, run: () => setSplitView(documentPanes.active, !(activeDocumentPane?.split && !reading)) },
] }, ] },
); );
} }
@@ -1077,10 +944,7 @@
if (!workingTabs.length) return false; if (!workingTabs.length) return false;
const index = workingTabs.findIndex(tab => tab.relPath === activeTabPath); const index = workingTabs.findIndex(tab => tab.relPath === activeTabPath);
const next = (index + (command === "previous-tab" ? -1 : 1) + workingTabs.length) % workingTabs.length; const next = (index + (command === "previous-tab" ? -1 : 1) + workingTabs.length) % workingTabs.length;
const target = workingTabs[next]; selectWorkingTab(workingTabs[next].relPath);
selectWorkingTab(target.relPath);
// A document tab takes focus in `selectTab`. A plugin tab takes it here, so the keyboard works in the new tab.
if ("plugin" in target) void tick().then(() => { if ($pluginView?.key === target.plugin.key) pluginPaneComponents[target.plugin.key]?.focus(); });
return true; return true;
} }
case "command-palette": palette = true; return true; case "command-palette": palette = true; return true;
@@ -1313,7 +1177,7 @@
try { try {
// The layout stays in localStorage on purpose: per-machine view state that is harmless to lose. // The layout stays in localStorage on purpose: per-machine view state that is harmless to lose.
const layout = parseWorkbenchLayout(localStorage.getItem(WORKBENCH_LAYOUT_KEY)); const layout = parseWorkbenchLayout(localStorage.getItem(WORKBENCH_LAYOUT_KEY));
({ leftOpen, rightOpen, leftWidth, rightWidth, leftView, backlinksOpen } = layout); ({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout);
if (transferredWindow) { leftOpen = false; rightOpen = false; } if (transferredWindow) { leftOpen = false; rightOpen = false; }
layoutReady = true; layoutReady = true;
} catch { error = $t("Could not read your layout. Default layout applies for this window."); } } catch { error = $t("Could not read your layout. Default layout applies for this window."); }
@@ -1346,7 +1210,7 @@
$effect(() => { $effect(() => {
if (!layoutReady || transferredWindow) return; if (!layoutReady || transferredWindow) return;
const saved = { leftOpen: narrow.left ? wide.left : leftOpen, rightOpen: narrow.right ? wide.right : rightOpen }; const saved = { leftOpen: narrow.left ? wide.left : leftOpen, rightOpen: narrow.right ? wide.right : rightOpen };
try { saveWorkbenchLayout(localStorage, { ...saved, leftWidth, rightWidth, leftView, backlinksOpen }); } try { saveWorkbenchLayout(localStorage, { ...saved, leftWidth, rightWidth, leftView }); }
catch { error = $t("Could not save your layout. Layout changes apply for this window only."); } catch { error = $t("Could not save your layout. Layout changes apply for this window only."); }
}); });
@@ -1453,7 +1317,7 @@
{leftView} {leftView}
{sidebarNavigation} {sidebarNavigation}
onSelectLeft={selectLeft} onSelectLeft={selectLeft}
tabBar={{ ...tabBarProps, onDetach: (tab) => { void detachTab(tab); }, onDragAt: tabDragAt, onDropAt: tabDropAt, onDragEnd: () => { tabDrop = null; } }} tabBar={{ ...tabBarProps, onDetach: (tab) => { void detachTab(tab); } }}
onNewTab={newTab} onNewTab={newTab}
canOpenBrowser={!!browserContribution?.newTab} canOpenBrowser={!!browserContribution?.newTab}
{browserOpening} {browserOpening}
@@ -1483,7 +1347,6 @@
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath} activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
{searchRequest} {searchRequest}
onOpenFile={(entry, line, target) => void openFile(entry, line, target)} onOpenFile={(entry, line, target) => void openFile(entry, line, target)}
onOpenRight={(entry) => void openToRight(entry, documentPanes.active)}
onCreated={(entry) => { void openCreatedFile(entry); }} onCreated={(entry) => { void openCreatedFile(entry); }}
onSaveTemplate={(entry) => { void saveTemplate(entry); }} onSaveTemplate={(entry) => { void saveTemplate(entry); }}
onManageTemplates={() => templateManager = true} onManageTemplates={() => templateManager = true}
@@ -1510,14 +1373,13 @@
<div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}> <div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}>
<DocumentArea <DocumentArea
bind:this={documentArea}
bind:pluginPaneComponents bind:pluginPaneComponents
bind:paneComponents bind:paneComponents
pluginCover={coverKey !== null} {editorPluginVisible}
drop={tabDrop} split={!!activeSplit}
onResize={(path, ratio) => { documentPanes = resizeDocumentPanes(documentPanes, path, ratio); }} {pluginBounds}
tabBar={tabBarProps}
{documentViews} {documentViews}
layout={documentPanes.layout}
activePane={documentPanes.active} activePane={documentPanes.active}
{documents} {documents}
{tabs} {tabs}
@@ -1602,7 +1464,6 @@
}} }}
showBacklinks={buffer?.kind === "text" && isMarkdownPath(buffer.relPath) && !editorPluginVisible} showBacklinks={buffer?.kind === "text" && isMarkdownPath(buffer.relPath) && !editorPluginVisible}
{backlinks} {backlinks}
bind:backlinksOpen
{session} {session}
onOpenBacklink={(entry) => void openBacklink(entry)} onOpenBacklink={(entry) => void openBacklink(entry)}
/> />
+4 -4
View File
@@ -115,12 +115,12 @@
:global(.shell.left-open) .header-left { width: calc(var(--ribbon-width) + var(--left) + 1px); } :global(.shell.left-open) .header-left { width: calc(var(--ribbon-width) + var(--left) + 1px); }
.header-left :global(.icon-btn), .header-right :global(.icon-btn) { flex-shrink: 0; } .header-left :global(.icon-btn), .header-right :global(.icon-btn) { flex-shrink: 0; }
.header-right { justify-content: flex-end; } .header-right { justify-content: flex-end; }
/* The drag area fills the free space after the tabs. It keeps 48 pixels, so the window stays movable when the tabs fill the header. */ /* A drag area keeps the window movable when the tabs fill the header: 120 pixels, and at least 48 in a narrow header. */
.window-drag-space { flex: 1 0 48px; align-self: stretch; } .window-drag-space { flex: 0 1 120px; min-width: 48px; align-self: stretch; }
/* The tab strip uses all space up to the drag area, then scrolls. It keeps room for one readable tab. */ /* The tab strip keeps room for one readable tab. It shrinks first, so the drag area shrinks only after it. */
.header-center :global(.tabs) { .header-center :global(.tabs) {
flex: 0 1 auto; flex: 0 1000 auto;
align-self: stretch; align-self: stretch;
min-width: 120px; min-width: 120px;
min-height: 28px; min-height: 28px;
-5
View File
@@ -28,11 +28,6 @@
findPanel?.focus(); findPanel?.focus();
} }
/** Give the keyboard to the tab: to the element that the view marks with `data-tab-focus`, or to the view. */
export function focus() {
(host?.querySelector<HTMLElement>("[data-tab-focus]") ?? host)?.focus({ preventScroll: true });
}
function searchKey(event: KeyboardEvent) { function searchKey(event: KeyboardEvent) {
if (event.target instanceof Element && event.target.closest('dialog, [role="dialog"], [role="menu"]')) 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") { if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "f") {
+23 -98
View File
@@ -1,40 +1,30 @@
import { paneBounds, removePane, setSplitRatio, splitPane, type SplitLayout, type SplitPath } from "./splitLayout.ts"; import { paneBounds, removePane, splitPane, type SplitLayout } from "./splitLayout.ts";
/** /** `reading` shows only the Read view. `split` shows the Read view beside the editor. A pane never has both. */
* A pane shows one document or one plugin editor view, for example a browser tab. A pane never shows both. export type DocumentPane = { id: string; documentId: string | null; reading: boolean; split: boolean };
* `reading` shows only the Read view. `split` shows the Read view beside the editor. A pane never has both.
*/
export type DocumentPane = { id: string; documentId: string | null; pluginKey: string | null; reading: boolean; split: boolean };
export type DocumentPanes = { layout: SplitLayout; panes: DocumentPane[]; active: string }; export type DocumentPanes = { layout: SplitLayout; panes: DocumentPane[]; active: string };
/** The content of a pane: a document ID or the key of a plugin editor view. */
export type PaneContent = { documentId: string } | { pluginKey: string };
function emptyPane(id: string): DocumentPane {
return { id, documentId: null, pluginKey: null, reading: false, split: false };
}
function filled(id: string, content: PaneContent): DocumentPane {
return "documentId" in content ? { ...emptyPane(id), documentId: content.documentId } : { ...emptyPane(id), pluginKey: content.pluginKey };
}
export function initialDocumentPanes(): DocumentPanes { export function initialDocumentPanes(): DocumentPanes {
return { layout: "document-main", panes: [emptyPane("document-main")], active: "document-main" }; return { layout: "document-main", panes: [{ id: "document-main", documentId: null, reading: false, split: false }], active: "document-main" };
} }
export function selectPane(state: DocumentPanes, id: string): DocumentPanes { export function selectPane(state: DocumentPanes, id: string): DocumentPanes {
return state.active === id || !state.panes.some(pane => pane.id === id) ? state : { ...state, active: id }; return state.active === id || !state.panes.some(pane => pane.id === id) ? state : { ...state, active: id };
} }
/** The pane that shows the content, if a pane shows it. */ /** Tabs own documents. Panes keep only a reference and local viewing state. */
export function paneOf(state: DocumentPanes, content: PaneContent): DocumentPane | undefined { export function syncDocumentPanes(state: DocumentPanes, live: readonly string[], selected: string | null): DocumentPanes {
return state.panes.find(pane => "documentId" in content ? pane.documentId === content.documentId : pane.pluginKey === content.pluginKey); const ids = new Set(live);
} let panes = state.panes.map(pane => pane.documentId && !ids.has(pane.documentId) ? { ...pane, documentId: null, reading: false, split: false } : pane);
let active = state.active;
/** Remove the panes that became empty. The last pane always stays. */ if (selected && ids.has(selected)) {
function collapse(state: DocumentPanes, panes: DocumentPane[], active: string): DocumentPanes { const existing = panes.find(pane => pane.documentId === selected);
if (existing) active = existing.id;
else panes = panes.map(pane => pane.id === active ? { ...pane, documentId: selected } : pane);
}
let layout = state.layout; let layout = state.layout;
for (const pane of panes) { for (const pane of panes) {
if (pane.documentId === null && pane.pluginKey === null && panes.length > 1) { if (pane.documentId === null && panes.length > 1) {
const next = removePane(layout, pane.id); const next = removePane(layout, pane.id);
if (next !== null) { layout = next; panes = panes.filter(item => item.id !== pane.id); } if (next !== null) { layout = next; panes = panes.filter(item => item.id !== pane.id); }
} }
@@ -44,45 +34,14 @@ function collapse(state: DocumentPanes, panes: DocumentPane[], active: string):
return { layout, panes, active }; return { layout, panes, active };
} }
/** export function splitDocumentPane(state: DocumentPanes, source: string, documentId: string, paneId: string): DocumentPanes {
* Tabs own documents. Panes keep only a reference and local viewing state. const existing = state.panes.find(pane => pane.documentId === documentId);
* A selected document that no pane shows replaces the content of the active pane.
* Give `livePlugins` to also clear the panes of closed plugin views.
*/
export function syncDocumentPanes(state: DocumentPanes, live: readonly string[], selected: string | null, livePlugins?: readonly string[]): DocumentPanes {
const ids = new Set(live);
const plugins = livePlugins ? new Set(livePlugins) : null;
let panes = state.panes.map(pane => {
if (pane.documentId && !ids.has(pane.documentId)) return { ...pane, documentId: null, reading: false, split: false };
if (plugins && pane.pluginKey && !plugins.has(pane.pluginKey)) return { ...pane, pluginKey: null };
return pane;
});
let active = state.active;
if (selected && ids.has(selected)) {
const existing = panes.find(pane => pane.documentId === selected);
if (existing) active = existing.id;
else panes = panes.map(pane => pane.id === active ? { ...pane, documentId: selected, pluginKey: null } : pane);
}
return collapse(state, panes, active);
}
/** Show the content in the active pane. When a pane already shows it, that pane becomes active. */
export function showInActivePane(state: DocumentPanes, content: PaneContent): DocumentPanes {
const existing = paneOf(state, content);
if (existing) return selectPane(state, existing.id);
return { ...state, panes: state.panes.map(pane => pane.id === state.active ? filled(pane.id, content) : pane) };
}
/** Show the content in a new pane beside `source`. When a pane already shows it, that pane becomes active. */
export function splitWithContent(state: DocumentPanes, source: string, content: PaneContent, paneId: string, direction: "right" | "down" = "right"): DocumentPanes {
const existing = paneOf(state, content);
if (existing) return selectPane(state, existing.id); if (existing) return selectPane(state, existing.id);
if (!state.panes.some(pane => pane.id === source) || state.panes.some(pane => pane.id === paneId)) return state; if (!state.panes.some(pane => pane.id === source) || state.panes.some(pane => pane.id === paneId)) return state;
return { layout: splitPane(state.layout, source, paneId, direction), panes: [...state.panes, filled(paneId, content)], active: paneId }; return {
} layout: splitPane(state.layout, source, paneId, "right"),
panes: [...state.panes, { id: paneId, documentId, reading: false, split: false }], active: paneId,
export function splitDocumentPane(state: DocumentPanes, source: string, documentId: string, paneId: string): DocumentPanes { };
return splitWithContent(state, source, { documentId }, paneId);
} }
export function closeDocumentPane(state: DocumentPanes, id: string): DocumentPanes { export function closeDocumentPane(state: DocumentPanes, id: string): DocumentPanes {
@@ -91,49 +50,15 @@ export function closeDocumentPane(state: DocumentPanes, id: string): DocumentPan
if (layout === null) return state; if (layout === null) return state;
const bounds = paneBounds(state.layout); const bounds = paneBounds(state.layout);
const panes = state.panes.filter(pane => pane.id !== id); const panes = state.panes.filter(pane => pane.id !== id);
const distance = (pane: DocumentPane) => Math.abs(bounds[pane.id].left - bounds[id].left) + Math.abs(bounds[pane.id].top - bounds[id].top); const neighbor = [...panes].sort((a, b) => Math.abs(bounds[a.id].left - bounds[id].left) - Math.abs(bounds[b.id].left - bounds[id].left))[0];
const neighbor = [...panes].sort((a, b) => distance(a) - distance(b))[0];
return { layout, panes, active: state.active === id ? neighbor.id : state.active }; return { layout, panes, active: state.active === id ? neighbor.id : state.active };
} }
/**
* One pane shows a plugin view only beside other panes. When the last pane shows a plugin view,
* the pane becomes empty and the result names the view, so that the caller can show it over the whole area.
*/
export function releaseSolePlugin(state: DocumentPanes): { state: DocumentPanes; pluginKey: string | null } {
const [pane] = state.panes;
if (state.panes.length !== 1 || pane.pluginKey === null) return { state, pluginKey: null };
return { state: { ...state, panes: [{ ...pane, pluginKey: null }] }, pluginKey: pane.pluginKey };
}
/** The place of a tab drop on a pane: the pane itself, or a new pane on its right or bottom side. */
export type PaneDrop = "center" | "right" | "down";
/**
* Show the content in the `target` pane (`center`), or in a new pane beside it.
* The content leaves the pane that showed it before, so that it shows in one pane only.
* The content that the drop replaces stays open as a tab.
*/
export function dropInPane(state: DocumentPanes, content: PaneContent, target: string, zone: PaneDrop, paneId: string): DocumentPanes {
if (!state.panes.some(pane => pane.id === target)) return state;
const current = paneOf(state, content);
if (current?.id === target) return selectPane(state, target);
const cleared = state.panes.map(pane => pane.id === current?.id ? emptyPane(pane.id) : pane);
if (zone === "center") return collapse(state, cleared.map(pane => pane.id === target ? filled(target, content) : pane), target);
return splitWithContent(collapse(state, cleared, target), target, content, paneId, zone);
}
/** Give a new ratio to a split between panes. */
export function resizeDocumentPanes(state: DocumentPanes, path: SplitPath, ratio: number): DocumentPanes {
const layout = setSplitRatio(state.layout, path, ratio);
return layout === state.layout ? state : { ...state, layout };
}
export function readDocumentPane(state: DocumentPanes, id: string, reading: boolean): DocumentPanes { export function readDocumentPane(state: DocumentPanes, id: string, reading: boolean): DocumentPanes {
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, reading, split: reading ? false : pane.split } : pane) }; return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, reading, split: reading ? false : pane.split } : pane) };
} }
/** Show or hide the Read view beside the editor. Read beside ends the Read-only view. */ /** Show or hide the Read view beside the editor. Split ends the Read-only view. */
export function splitDocumentView(state: DocumentPanes, id: string, split: boolean): DocumentPanes { export function splitDocumentView(state: DocumentPanes, id: string, split: boolean): DocumentPanes {
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, split, reading: split ? false : pane.reading } : pane) }; return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, split, reading: split ? false : pane.reading } : pane) };
} }
-44
View File
@@ -1,44 +0,0 @@
/**
* The natural sizes of the images that the app has loaded. The views use them to keep the space of an image before it
* loads. Without this space the text moves when an image loads, and each new height starts a layout pass of the editor.
*/
const sizes = new Map<string, { width: number; height: number }>();
// A data URL can hold megabytes. The key keeps the map from holding the image data.
function key(url: string) {
if (url.length <= 256) return url;
const middle = url.length >> 1;
return `${url.length}:${url.slice(middle, middle + 64)}`;
}
export function imageSize(url: string) {
return sizes.get(key(url));
}
export function rememberImageSize(url: string, width: number, height: number) {
if (width > 0 && height > 0) sizes.set(key(url), { width, height });
}
/** Read the size of an image that the app holds as data. A remote image gives its size when it loads in a view. */
export function loadImageSize(url: string): Promise<void> {
if (!url.startsWith("data:image/") || imageSize(url)) return Promise.resolve();
return new Promise(resolve => {
const image = new Image();
image.onload = () => { rememberImageSize(url, image.naturalWidth, image.naturalHeight); resolve(); };
image.onerror = () => resolve();
image.src = url;
});
}
/** The width of the text column at its largest. It gives an estimate before the editor can measure an image. */
const columnWidth = 740;
/** The margins of an image frame, from `.md-image-frame`. */
const frameMargins = 45;
/** The estimated height of an image in Write, from the size attributes of its HTML. A negative value means that the size is not known. */
export function estimatedImageHeight(html: string) {
const match = /\bwidth="(\d+)" height="(\d+)"/.exec(html);
if (!match) return -1;
const width = Number(match[1]), height = Number(match[2]);
return Math.round(height * Math.min(1, columnWidth / width)) + frameMargins;
}
+1 -3
View File
@@ -5,7 +5,6 @@ import { inlineMathEnd } from "./inlineMath.ts";
import { activeTableFormulas } from "../formulas/index.ts"; import { activeTableFormulas } from "../formulas/index.ts";
import { hasTableDelimiter } from "../editor/markdownTable.ts"; import { hasTableDelimiter } from "../editor/markdownTable.ts";
import { footnotes, renderFootnotes, type FootnoteEnvironment } from "../editor/footnotes.ts"; import { footnotes, renderFootnotes, type FootnoteEnvironment } from "../editor/footnotes.ts";
import { imageSize } from "./imageSizes.ts";
const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false }); const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false });
markdown.use(footnotes); markdown.use(footnotes);
@@ -163,8 +162,7 @@ markdown.renderer.rules.image = (tokens, index, _options, env, renderer) => {
const alt = renderer.renderInlineAsText(token.children || [], markdown.options, env); const alt = renderer.renderInlineAsText(token.children || [], markdown.options, env);
// Only app-resolved image data or HTTP(S) URLs become image sources. // Only app-resolved image data or HTTP(S) URLs become image sources.
if (!/^(?:https?:\/\/|data:image\/)/i.test(resolved)) return `<span class="missing-image" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}" alt="${escapeHtml(alt)}">Image unavailable: ${escapeHtml(alt || original)}</span>`; if (!/^(?:https?:\/\/|data:image\/)/i.test(resolved)) return `<span class="missing-image" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}" alt="${escapeHtml(alt)}">Image unavailable: ${escapeHtml(alt || original)}</span>`;
const size = imageSize(resolved); return `<img src="${escapeHtml(resolved)}" alt="${escapeHtml(alt)}" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}" loading="lazy">`;
return `<img src="${escapeHtml(resolved)}" alt="${escapeHtml(alt)}" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}"${size ? ` width="${size.width}" height="${size.height}"` : ""} loading="lazy">`;
}; };
markdown.renderer.rules.table_open = () => '<div class="md-table-scroll"><table>\n'; markdown.renderer.rules.table_open = () => '<div class="md-table-scroll"><table>\n';
markdown.renderer.rules.table_close = () => '</table></div>\n'; markdown.renderer.rules.table_close = () => '</table></div>\n';
+4 -49
View File
@@ -1,11 +1,5 @@
/** A split gives `ratio` of its size to `first`. A split without a ratio divides its size in two equal parts. */ export type SplitLayout = string | { direction: "right" | "down"; first: SplitLayout; second: SplitLayout };
export type SplitLayout = string | { direction: "right" | "down"; first: SplitLayout; second: SplitLayout; ratio?: number };
export type PaneBounds = { left: number; top: number; width: number; height: number }; export type PaneBounds = { left: number; top: number; width: number; height: number };
/** The path from the root to a split: the side of each split on the way. */
export type SplitPath = readonly ("first" | "second")[];
/** A divider between the two sides of a split. `bounds` is the area of the split, in percent of the root. */
export type SplitDivider = { path: SplitPath; direction: "right" | "down"; ratio: number; bounds: PaneBounds };
const ratioOf = (tree: Exclude<SplitLayout, string>) => tree.ratio ?? 0.5;
export function containsPane(tree: SplitLayout, key: string): boolean { export function containsPane(tree: SplitLayout, key: string): boolean {
return typeof tree === "string" ? tree === key : containsPane(tree.first, key) || containsPane(tree.second, key); return typeof tree === "string" ? tree === key : containsPane(tree.first, key) || containsPane(tree.second, key);
@@ -24,47 +18,8 @@ export function removePane(tree: SplitLayout, key: string): SplitLayout | null {
export function paneBounds(tree: SplitLayout, bounds: PaneBounds = { left: 0, top: 0, width: 100, height: 100 }): Record<string, PaneBounds> { export function paneBounds(tree: SplitLayout, bounds: PaneBounds = { left: 0, top: 0, width: 100, height: 100 }): Record<string, PaneBounds> {
if (typeof tree === "string") return { [tree]: bounds }; if (typeof tree === "string") return { [tree]: bounds };
const [a, b] = sides(tree, bounds); const a = { ...bounds }, b = { ...bounds };
if (tree.direction === "right") { a.width /= 2; b.width /= 2; b.left += a.width; }
else { a.height /= 2; b.height /= 2; b.top += a.height; }
return { ...paneBounds(tree.first, a), ...paneBounds(tree.second, b) }; return { ...paneBounds(tree.first, a), ...paneBounds(tree.second, b) };
} }
function sides(tree: Exclude<SplitLayout, string>, bounds: PaneBounds): [PaneBounds, PaneBounds] {
const a = { ...bounds }, b = { ...bounds }, ratio = ratioOf(tree);
if (tree.direction === "right") { a.width = bounds.width * ratio; b.width = bounds.width - a.width; b.left += a.width; }
else { a.height = bounds.height * ratio; b.height = bounds.height - a.height; b.top += a.height; }
return [a, b];
}
/** Each split of the tree, with its place, for the dividers that change its ratio. */
export function splitDividers(tree: SplitLayout, bounds: PaneBounds = { left: 0, top: 0, width: 100, height: 100 }, path: SplitPath = []): SplitDivider[] {
if (typeof tree === "string") return [];
const [a, b] = sides(tree, bounds);
return [{ path, direction: tree.direction, ratio: ratioOf(tree), bounds },
...splitDividers(tree.first, a, [...path, "first"]), ...splitDividers(tree.second, b, [...path, "second"])];
}
/** Give a new ratio to the split at `path`. The ratio stays between 0.1 and 0.9. */
export function setSplitRatio(tree: SplitLayout, path: SplitPath, ratio: number): SplitLayout {
if (typeof tree === "string" || !Number.isFinite(ratio)) return tree;
if (!path.length) {
const next = Math.round(Math.max(0.1, Math.min(0.9, ratio)) * 1000) / 1000;
return next === ratioOf(tree) ? tree : { ...tree, ratio: next };
}
const [side, ...rest] = path;
const child = setSplitRatio(tree[side], rest, ratio);
return child === tree[side] ? tree : { ...tree, [side]: child };
}
/** The same panes in the same order, one above the other. A narrow area uses it. */
export function stackLayout(tree: SplitLayout): SplitLayout {
return typeof tree === "string" ? tree : { ...tree, direction: "down", first: stackLayout(tree.first), second: stackLayout(tree.second) };
}
/** The direction of the split that put `key` beside a different pane, and the first pane on the other side. */
export function splitSibling(tree: SplitLayout, key: string): { direction: "right" | "down"; sibling: string } | null {
if (typeof tree === "string") return null;
const first = (node: SplitLayout): string => typeof node === "string" ? node : first(node.first);
if (tree.second === key) return { direction: tree.direction, sibling: first(tree.first) };
if (tree.first === key) return { direction: tree.direction, sibling: first(tree.second) };
return splitSibling(tree.first, key) ?? splitSibling(tree.second, key);
}
-4
View File
@@ -6,8 +6,6 @@ export interface WorkbenchLayout {
leftWidth: number; leftWidth: number;
rightWidth: number; rightWidth: number;
leftView: "files" | "search" | "bookmarks"; leftView: "files" | "search" | "bookmarks";
/** The Backlinks section below the outline is expanded. */
backlinksOpen: boolean;
} }
export const DEFAULT_WORKBENCH_LAYOUT: Readonly<WorkbenchLayout> = { export const DEFAULT_WORKBENCH_LAYOUT: Readonly<WorkbenchLayout> = {
@@ -16,7 +14,6 @@ export const DEFAULT_WORKBENCH_LAYOUT: Readonly<WorkbenchLayout> = {
leftWidth: 260, leftWidth: 260,
rightWidth: 240, rightWidth: 240,
leftView: "files", leftView: "files",
backlinksOpen: true,
}; };
function width(value: unknown, fallback: number): number { function width(value: unknown, fallback: number): number {
@@ -32,7 +29,6 @@ export function parseWorkbenchLayout(raw: string | null): WorkbenchLayout {
leftWidth: width(value?.leftWidth, DEFAULT_WORKBENCH_LAYOUT.leftWidth), leftWidth: width(value?.leftWidth, DEFAULT_WORKBENCH_LAYOUT.leftWidth),
rightWidth: width(value?.rightWidth, DEFAULT_WORKBENCH_LAYOUT.rightWidth), rightWidth: width(value?.rightWidth, DEFAULT_WORKBENCH_LAYOUT.rightWidth),
leftView: ["files", "search", "bookmarks"].includes(value?.leftView) ? value.leftView : DEFAULT_WORKBENCH_LAYOUT.leftView, leftView: ["files", "search", "bookmarks"].includes(value?.leftView) ? value.leftView : DEFAULT_WORKBENCH_LAYOUT.leftView,
backlinksOpen: typeof value?.backlinksOpen === "boolean" ? value.backlinksOpen : DEFAULT_WORKBENCH_LAYOUT.backlinksOpen,
}; };
} catch { return { ...DEFAULT_WORKBENCH_LAYOUT }; } } catch { return { ...DEFAULT_WORKBENCH_LAYOUT }; }
} }
+2 -2
View File
@@ -80,11 +80,11 @@ export function settle(page) {
} }
/** /**
* Choose "Write", "Source", or "Read" in the view control of a document pane, or toggle "Read beside" (src/lib/layout/ViewModes.svelte). * Choose "Write", "Source", or "Read" in the view control of a document pane, or toggle "Split" (src/lib/layout/ViewModes.svelte).
* `scope` is the page, or a pane locator when the window shows more than one document pane. * `scope` is the page, or a pane locator when the window shows more than one document pane.
*/ */
export async function chooseView(scope, name) { export async function chooseView(scope, name) {
if (name === "Read beside") return scope.locator(".chrome-bar").getByRole("button", { name: "Read beside", exact: true }).click(); if (name === "Split") return scope.locator(".chrome-bar").getByRole("button", { name: "Split", exact: true }).click();
return scope.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name, exact: true }).click(); return scope.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name, exact: true }).click();
} }
@@ -103,11 +103,11 @@ await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
assert.deepEqual(await background.boundingBox(), beforeScroll); assert.deepEqual(await background.boundingBox(), beforeScroll);
await page.screenshot({ path: `${output}/${theme}-reader.png` }); await page.screenshot({ path: `${output}/${theme}-reader.png` });
// Split shows the Write editor beside Read. // Split shows the Write editor beside Read.
await chooseView(page, 'Read beside'); await chooseView(page, 'Split');
await page.locator('.live-writer .cm-content').waitFor(); await page.locator('.live-writer .cm-content').waitFor();
assert.equal(await style(page.locator('.live-writer .cm-editor').first(), 'backgroundColor'), 'rgba(0, 0, 0, 0)'); assert.equal(await style(page.locator('.live-writer .cm-editor').first(), 'backgroundColor'), 'rgba(0, 0, 0, 0)');
await page.screenshot({ path: `${output}/${theme}-split.png` }); await page.screenshot({ path: `${output}/${theme}-split.png` });
await chooseView(page, 'Read beside'); await chooseView(page, 'Split');
await chooseView(page, 'Source'); await chooseView(page, 'Source');
await page.locator('.source-editor .cm-content').waitFor(); await page.locator('.source-editor .cm-content').waitFor();
await page.screenshot({ path: `${output}/${theme}-ide.png` }); await page.screenshot({ path: `${output}/${theme}-ide.png` });
@@ -1,145 +0,0 @@
// Scrolling in Write and Read through a large document with large tables, images, code blocks, and short lines keeps the text in place.
import assert from "node:assert/strict";
import { chooseView, mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
const words = "lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua".split(" ");
const text = (seed, count) => Array.from({ length: count }, (_, i) => words[(seed * 7 + i * 3) % words.length]).join(" ");
/** A short first heading holds the caret when the document opens. Short code lines and fences have another line height than prose. */
function largeDocument() {
const parts = ["# Large\n"];
for (let section = 0; section < 10; section++) {
parts.push(`## Section ${section}\n`, `Short line ${section}\n`, " \n");
for (let p = 0; p < 5; p++) parts.push(`P${section}.${p} ${text(section + p, 30 + (p * 37) % 90)}\n`);
const rows = Array.from({ length: 25 + (section * 17) % 50 }, (_, r) => `| T${section}R${r} | ${text(r, 2)} | ${text(section + r, 6 + (r * 11) % 50)} |`);
parts.push(["| Row | Name | Description |", "| --- | --- | --- |", ...rows].join("\n") + "\n");
if (section % 2 === 0) parts.push(`![Picture ${section}](img${section}.svg)\n`);
if (section % 3 === 0) parts.push("```python\nx = 1\ny = 2\n```\n");
parts.push(`- item ${section} one\n- item ${section} two\n`);
}
return parts.join("\n");
}
await runSmoke("editor/scrollStability", async ({ page }) => {
await mockTauri(page, {
state: { source: largeDocument() },
commands: test => {
const svg = (width, height) => btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><rect width="100%" height="100%" fill="#336"/></svg>`);
const files = { "notes/large.md": test.state.source };
for (let section = 0; section < 10; section += 2) files[`notes/img${section}.svg`] = svg(1400, 700 + section * 60);
const workspace = test.workspace({ root: "C:/smoke-workspace", files });
return {
...workspace,
workspace_read_data_url: ({ rel }) => {
if (!workspace.files.has(rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + workspace.files.get(rel);
},
};
},
});
await page.setViewportSize({ width: 1440, height: 1000 });
/** Wheel over the view. After each tick lands, the text must be where the tick put it. Returns the ticks where the text moved by itself, and the document heights. */
async function wheel(selector, delta, ticks) {
const box = await page.locator(selector).boundingBox();
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.evaluate(selector => {
const scroller = document.querySelector(selector);
const unique = /^s*(Td+Rd+|Pd+.d+|Short line d+|item d+ (?:one|two)|Section d+)/;
const keyOf = element => unique.exec(element.textContent || "")?.[1] ?? "";
const items = () => [...scroller.querySelectorAll(".cm-line, tr, .reading p, .reading h2, .reading li")];
const frame = () => new Promise(resolve => requestAnimationFrame(resolve));
const atEdge = () => scroller.scrollTop <= 0 || scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 2;
let tracked = null;
window.__scroll = {
jumps: [], heights: [],
before(delta) {
const area = scroller.getBoundingClientRect(), margin = Math.abs(delta) + 60;
const element = items().find(item => { const rect = item.getBoundingClientRect(); return rect.height > 0 && rect.top >= area.top + margin && rect.top <= area.bottom - margin && keyOf(item); });
tracked = element ? { element, key: keyOf(element), top: element.getBoundingClientRect().top, delta, scrollTop: scroller.scrollTop } : null;
},
// A tick can land some frames later on a busy computer. Wait for it, then for the layout passes of the editor.
async after() {
for (let waited = 0; tracked && scroller.scrollTop === tracked.scrollTop && waited < 60; waited++) await frame();
for (let settled = 0; settled < 3; settled++) await frame();
this.heights.push(scroller.scrollHeight);
if (atEdge()) return true;
if (!tracked) return false;
const element = tracked.element.isConnected ? tracked.element : items().find(item => keyOf(item) === tracked.key);
if (!element) this.jumps.push(`${tracked.key} left the view`);
else {
const moved = Math.round(element.getBoundingClientRect().top - (tracked.top - tracked.delta));
if (Math.abs(moved) > 4) this.jumps.push(`${tracked.key} moved ${moved}`);
}
return false;
},
};
}, selector);
for (let tick = 0; tick < ticks; tick++) {
await page.evaluate(delta => window.__scroll.before(delta), delta);
await page.mouse.wheel(0, delta);
if (await page.evaluate(() => window.__scroll.after()) && tick > 0) break;
}
return page.evaluate(() => ({ jumps: window.__scroll.jumps, heights: window.__scroll.heights }));
}
const jump = (selector, fraction) => page.evaluate(({ selector, fraction }) => { const scroller = document.querySelector(selector); scroller.scrollTop = scroller.scrollHeight * fraction; }, { selector, fraction });
await page.goto(smokeUrl);
await page.getByText(/smoke-workspace/).first().waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("large.md");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "large.md" }).first().click();
await page.locator(".cm-content").waitFor();
await page.waitForTimeout(400);
// Text that was not on screen yet: the heights are estimates until the first draw.
await jump(".cm-scroller", .6);
await page.waitForTimeout(300);
const first = await wheel(".cm-scroller", -200, 120);
assert.deepEqual(first.jumps, [], "Wheel up through new tables and images");
const spread = heights => Math.max(...heights) - Math.min(...heights);
// Line heights are estimates, but tables and images have their heights before the first draw.
assert.ok(spread(first.heights) < Math.max(...first.heights) * .05, `The document keeps about its height at the first draw: ${Math.min(...first.heights)} to ${Math.max(...first.heights)}`);
// Text that was drawn before: images and tables come back with their heights.
await jump(".cm-scroller", 0);
await page.waitForTimeout(200);
const down = await wheel(".cm-scroller", 400, 130);
assert.deepEqual(down.jumps, [], "Wheel down to the end");
const up = await wheel(".cm-scroller", -400, 130);
assert.deepEqual(up.jumps, [], "Wheel up to the start");
assert.ok(spread(up.heights) < 200, `The document keeps its height on the way back: ${Math.min(...up.heights)} to ${Math.max(...up.heights)}`);
// A short heading with the caret and a code block with the caret have another line height too.
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".cm-content"));
const heading = view.state.doc.toString().indexOf("## Section 3");
view.dispatch({ selection: { anchor: heading + 3 }, scrollIntoView: true });
});
await page.waitForTimeout(300);
const caret = await wheel(".cm-scroller", 300, 25);
assert.deepEqual(caret.jumps, [], "Wheel down with the caret in a short heading");
assert.ok(spread(caret.heights) < 200, `The document keeps its height with the caret in a short heading: ${Math.min(...caret.heights)} to ${Math.max(...caret.heights)}`);
// Images in Write keep their space before they load.
const image = page.locator(".cm-content img[data-md-src]").first();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".cm-content"));
view.scrollDOM.scrollTop = view.lineBlockAt(view.state.doc.toString().indexOf("![Picture 0]")).top;
});
await image.waitFor();
assert.equal(await image.getAttribute("width"), "1400");
assert.equal(await image.getAttribute("height"), "700");
// Read shows the same document without virtual lines.
await chooseView(page, "Read");
await page.locator(".md-page > .reading").waitFor();
await page.waitForTimeout(300);
await jump(".md-page", .6);
await page.waitForTimeout(300);
const reading = await wheel(".md-page", -300, 60);
assert.deepEqual(reading.jumps, [], "Wheel up in Read");
assert.equal(await page.locator(".md-page img[data-md-src]").first().getAttribute("height"), "700", "Images in Read keep their space before they load");
}, { timeout: 30000 });
+8 -96
View File
@@ -1,6 +1,5 @@
// The native PDF Viewer: the file tree marks PDF files without the module, the first PDF tab loads it, and each tab // The native PDF Viewer: the file tree marks PDF files without the module, the first PDF tab loads it, and each tab
// renders its pages in one column with selectable text, page controls, zoom, a typed zoom, rotation, scrolling by wheel and // renders a page with selectable text, page controls, zoom, rotation, Page Up and Page Down, and Reload.
// keyboard, and Reload. It also checks the opaque toolbar and the focus after Ctrl+Tab.
// It also checks two tabs, one worker for each open tab, a protected PDF, a damaged file, Off and On, no network request, // It also checks two tabs, one worker for each open tab, a protected PDF, a damaged file, Off and On, no network request,
// no text read of a PDF, the owner ID of a tab transfer, a saved tab after a reload, both themes, and a narrow toolbar. // no text read of a PDF, the owner ID of a tab transfer, a saved tab after a reload, both themes, and a narrow toolbar.
// It replaces tests/browser.mjs of the PDF Viewer plugin. // It replaces tests/browser.mjs of the PDF Viewer plugin.
@@ -79,13 +78,8 @@ await runSmoke("features/pdf", async ({ page }) => {
await rendered("Page 1 of 2"); await rendered("Page 1 of 2");
assert.equal(await loaded(), true, "The first PDF tab loads the module"); assert.equal(await loaded(), true, "The first PDF tab loads the module");
await active.getByRole("img", { name: "PDF page 1", exact: true }).waitFor(); await active.getByRole("img", { name: "PDF page 1", exact: true }).waitFor();
const sheet = number => active.locator(`.sheet[data-page="${number}"]`); assert.match(await active.locator(".textLayer").innerText(), /Page one text selection/);
const scroll = active.locator(".scroll"); assert.ok(await active.locator("canvas").evaluate(canvas => {
const scrollTop = () => scroll.evaluate(node => node.scrollTop);
await sheet(1).locator(".textLayer span").first().waitFor();
assert.match(await sheet(1).locator(".textLayer").innerText(), /Page one text selection/);
assert.equal(await active.locator(".sheet").count(), 2, "Each page has a sheet in the column");
assert.ok(await sheet(1).locator("canvas").evaluate(canvas => {
const data = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data; const data = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data;
let colored = 0; let colored = 0;
for (let index = 0; index < data.length; index += 4) if (data[index] < 200 && data[index + 2] > 100) colored++; for (let index = 0; index < data.length; index += 4) if (data[index] < 200 && data[index + 2] > 100) colored++;
@@ -95,10 +89,6 @@ await runSmoke("features/pdf", async ({ page }) => {
assert.equal(await button("Fit width").getAttribute("aria-pressed"), "true"); assert.equal(await button("Fit width").getAttribute("aria-pressed"), "true");
assert.equal(await button("Previous page").isDisabled(), true); assert.equal(await button("Previous page").isDisabled(), true);
assert.equal(await workers(), 1); assert.equal(await workers(), 1);
// The toolbar and the status line are opaque, so a background image does not show through them.
for (const selector of [".toolbar", ".status"]) {
assert.match(await active.locator(selector).evaluate(node => getComputedStyle(node).backgroundColor), /^rgb\(/, `${selector} has an opaque fill`);
}
// Both themes. The page stays white paper. // Both themes. The page stays white paper.
for (const theme of ["dark", "light"]) { for (const theme of ["dark", "light"]) {
@@ -129,8 +119,7 @@ await runSmoke("features/pdf", async ({ page }) => {
await rendered("Page 2 of 2"); await rendered("Page 2 of 2");
await active.getByRole("img", { name: "PDF page 2", exact: true }).waitFor(); await active.getByRole("img", { name: "PDF page 2", exact: true }).waitFor();
assert.equal(await button("Next page").isDisabled(), true); assert.equal(await button("Next page").isDisabled(), true);
const zoomField = active.getByRole("textbox", { name: "Zoom percent", exact: true }); const zoomText = () => active.locator(".zoom").innerText();
const zoomText = () => zoomField.inputValue();
const before = await zoomText(); const before = await zoomText();
await button("Zoom in").click(); await button("Zoom in").click();
await rendered("Page 2 of 2"); await rendered("Page 2 of 2");
@@ -138,70 +127,13 @@ await runSmoke("features/pdf", async ({ page }) => {
assert.equal(await button("Fit width").getAttribute("aria-pressed"), "false"); assert.equal(await button("Fit width").getAttribute("aria-pressed"), "false");
await button("Rotate clockwise").click(); await button("Rotate clockwise").click();
await rendered("Page 2 of 2"); await rendered("Page 2 of 2");
assert.ok(await sheet(2).locator("canvas").evaluate(canvas => canvas.width > canvas.height), "A rotated page is wider than high"); assert.ok(await active.locator("canvas").evaluate(canvas => canvas.width > canvas.height), "A rotated page is wider than high");
for (let turn = 0; turn < 3; turn++) await button("Rotate clockwise").click(); await active.locator(".scroll").focus();
// A typed zoom.
await zoomField.fill("137");
await zoomField.press("Enter");
assert.equal(await zoomText(), "137%");
await zoomField.fill("text");
await zoomField.press("Enter");
assert.equal(await zoomText(), "137%", "Text that is not a number keeps the zoom");
await zoomField.fill("9000");
await zoomField.press("Enter");
assert.equal(await zoomText(), "400%", "A typed zoom stays in the limits");
const unfitted = button("Fit width").and(page.locator('[aria-pressed="false"]'));
await unfitted.waitFor();
const fitted = button("Fit width").and(page.locator('[aria-pressed="true"]'));
const input = active.getByRole("spinbutton", { name: "Page number", exact: true });
await input.fill("1");
await input.press("Enter");
await rendered("Page 1 of 2");
// Page Down and Page Up scroll. At 400%, a page is higher than the tab. They do not jump to the next page, and they do not draw a page again at the ends.
assert.equal(await scrollTop(), 0);
await scroll.focus();
const keepCanvas = number => sheet(number).locator("canvas").evaluate(canvas => { window.__PDF_CANVAS__ = canvas; });
const sameCanvas = number => sheet(number).locator("canvas").evaluate(canvas => window.__PDF_CANVAS__ === canvas);
await keepCanvas(1);
await page.keyboard.press("PageUp"); await page.keyboard.press("PageUp");
await page.waitForTimeout(300);
assert.equal(await scrollTop(), 0);
assert.equal(await sameCanvas(1), true, "Page Up at the start does not draw the page again");
await rendered("Page 1 of 2"); await rendered("Page 1 of 2");
await page.keyboard.press("PageDown"); await page.keyboard.press("PageDown");
await page.waitForFunction(() => document.activeElement.scrollTop > 0);
await page.waitForTimeout(400);
assert.ok(await scrollTop() < await sheet(2).evaluate(node => node.offsetTop - node.previousElementSibling.offsetTop), "Page Down scrolls less than one page");
await rendered("Page 1 of 2");
assert.equal(await input.inputValue(), "1");
await page.keyboard.press("End");
await rendered("Page 2 of 2");
assert.equal(await input.inputValue(), "2", "The page field follows the scroll position");
await page.waitForTimeout(400);
const end = await scrollTop();
await keepCanvas(2);
await page.keyboard.press("PageDown");
await page.waitForTimeout(300);
assert.equal(await scrollTop(), end);
assert.equal(await sameCanvas(2), true, "Page Down at the end does not draw the page again");
await rendered("Page 2 of 2");
// The wheel shows the other pages.
await page.keyboard.press("Home");
await rendered("Page 1 of 2");
await scroll.hover();
await page.mouse.wheel(0, 5000);
await rendered("Page 2 of 2");
await active.getByRole("img", { name: "PDF page 2", exact: true }).waitFor();
// Ctrl and the wheel change the zoom.
await button("Fit width").click();
await fitted.waitFor();
await scroll.hover();
await page.keyboard.down("Control");
await page.mouse.wheel(0, -100);
await page.keyboard.up("Control");
await unfitted.waitFor();
await button("Fit width").click();
await rendered("Page 2 of 2"); await rendered("Page 2 of 2");
const input = active.getByRole("spinbutton", { name: "Page number", exact: true });
await input.fill("1"); await input.fill("1");
await input.press("Enter"); await input.press("Enter");
await rendered("Page 1 of 2"); await rendered("Page 1 of 2");
@@ -216,24 +148,6 @@ await runSmoke("features/pdf", async ({ page }) => {
assert.equal(await workers(), 2); assert.equal(await workers(), 2);
await row("Other.PDF").click(); await row("Other.PDF").click();
assert.equal(await tab("Other").count(), 1, "A second open selects the same tab"); assert.equal(await tab("Other").count(), 1, "A second open selects the same tab");
// The tabs are New tab, Sample, and Other. Ctrl+Tab and Ctrl+Shift+Tab give the keyboard to the page area of the PDF tab.
const focused = () => page.waitForFunction(() => document.activeElement?.matches(".pdf-viewer .scroll") && document.activeElement.offsetParent !== null);
await page.keyboard.press("Control+Shift+Tab");
await focused();
assert.equal(await tab("Sample").getAttribute("aria-selected"), "true");
await input.fill("1");
await input.press("Enter");
await rendered("Page 1 of 2");
await page.keyboard.press("Control+Tab");
await focused();
await page.keyboard.press("Control+Shift+Tab");
await focused();
assert.equal(await tab("Sample").getAttribute("aria-selected"), "true");
await page.keyboard.press("PageDown");
await page.waitForFunction(() => document.activeElement.scrollTop > 0);
await page.keyboard.press("Control+Tab");
await rendered("Page 1 of 2");
assert.equal(await tab("Other").getAttribute("aria-selected"), "true");
await page.getByRole("button", { name: "Close Other", exact: true }).click(); await page.getByRole("button", { name: "Close Other", exact: true }).click();
await tab("Other").waitFor({ state: "detached" }); await tab("Other").waitFor({ state: "detached" });
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 1); await page.waitForFunction(() => window.__PDF_WORKERS__.size === 1);
@@ -268,8 +182,6 @@ await runSmoke("features/pdf", async ({ page }) => {
// Reload keeps the page and replaces the worker. // Reload keeps the page and replaces the worker.
await tab("Sample").click(); await tab("Sample").click();
await input.fill("2");
await input.press("Enter");
await rendered("Page 2 of 2"); await rendered("Page 2 of 2");
await button("Reload PDF").click(); await button("Reload PDF").click();
await rendered("Page 2 of 2"); await rendered("Page 2 of 2");
@@ -313,5 +225,5 @@ await runSmoke("features/pdf", async ({ page }) => {
assert.equal(await tab("Sample").count(), 1); assert.equal(await tab("Sample").count(), 1);
assert.deepEqual(requests, [], "No network request leaves the app"); assert.deepEqual(requests, [], "No network request leaves the app");
console.log("PASS: PDF Viewer loads at first need, renders text and pages, scrolls, zooms, rotates, reloads, unlocks, reports a damaged file, keeps one worker per tab, restores its tab, and Off removes it"); console.log("PASS: PDF Viewer loads at first need, renders text and pages, zooms, rotates, reloads, unlocks, reports a damaged file, keeps one worker per tab, restores its tab, and Off removes it");
}, { timeout: 60000, viewport: { width: 1440, height: 1000 } }); }, { timeout: 60000, viewport: { width: 1440, height: 1000 } });
@@ -1,90 +0,0 @@
// Project Management description drafts with images: an image pasted in an unsaved description survives a close,
// a reopen, and a reload of the card. Save writes the image file. Cancel removes the image data and writes no image file.
import assert from "node:assert/strict";
import { runSmoke } from "../_harness/index.mjs";
import { cardPath, draftPath, fileText, loadWorkspace, openBoard, pane, waitForFile } from "../_harness/pmFixture.mjs";
const imageFile = id => `.runestone/pm/images/${id}.json`;
const draftImagesPath = id => draftPath(id).replace(/\.json$/, ".images.json");
const json = async (page, path) => JSON.parse(await fileText(page, path) ?? "null");
await runSmoke("features/pmDraftImages", async ({ page }) => {
await loadWorkspace(page);
await openBoard(page, "Roadmap");
const editor = page.locator("dialog.pm-card-editor[open]");
const description = editor.locator('textarea[aria-label="Details (Markdown)"]');
const descriptionAction = name => editor.locator(".pm-description-actions").getByRole("button", { name, exact: true });
const openCard = async title => {
await pane(page).locator(".pm-card-title", { hasText: new RegExp(`^${title}$`) }).click();
await editor.waitFor();
await editor.getByRole("button", { name: "Edit", exact: true }).click();
};
const closeCard = async () => {
await editor.getByRole("button", { name: "Close card", exact: true }).click();
await editor.waitFor({ state: "detached" });
};
// Paste a 1 by 1 PNG into the description. Returns the image ID of the new reference.
const pasteImage = async name => {
await description.evaluate((element, name) => {
const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="), c => c.charCodeAt(0));
const data = new DataTransfer();
data.items.add(new File([png], name, { type: "image/png" }));
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
}, name);
const reference = new RegExp(`!\\[${name.replace(".", "\\.")}\\]\\(pm-image:([0-9a-f-]{36})\\)`);
await page.waitForFunction(source => new RegExp(source).test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value), reference.source);
return reference.exec(await description.inputValue())[1];
};
// Wait until the gallery thumbnail of `name` shows the decoded image.
const imageLoads = async name => {
await page.waitForFunction(alt => {
const image = document.querySelector(`dialog.pm-card-editor[open] .pm-card-images img[alt="${alt}"]`);
return !!image?.complete && image.naturalWidth > 0;
}, name);
assert.equal(await editor.locator(".pm-card-images .pm-error").allInnerTexts().then(texts => texts.join("")), "");
};
// A pasted image stays with the draft when the card closes. The image folder gets no file yet.
await openCard("Card A");
const first = await pasteImage("dot.png");
await imageLoads("dot.png");
await closeCard();
await waitForFile(page, draftPath("card-a"), new RegExp(`pm-image:${first}`));
assert.match((await json(page, draftImagesPath("card-a"))).images[first], /^data:image\/png;base64,iVBOR/);
assert.equal(await fileText(page, imageFile(first)), undefined, "Only a save writes the image file");
assert.match(await fileText(page, cardPath("card-a")), /\nBody of Card A\.\n$/, "Close keeps the saved description");
// The reopened card restores the draft and shows its image. Save writes the image file and ends the draft.
await openCard("Card A");
await imageLoads("dot.png");
assert.match(await description.inputValue(), new RegExp(`pm-image:${first}`));
await descriptionAction("Save").click();
await waitForFile(page, cardPath("card-a"), new RegExp(`!\\[dot\\.png\\]\\(pm-image:${first}\\)`));
assert.match(await fileText(page, imageFile(first)), /"data":"data:image\/png;base64,iVBOR/);
assert.equal((await json(page, draftPath("card-a"))).body, null);
assert.deepEqual((await json(page, draftImagesPath("card-a"))).images, {});
await closeCard();
await openCard("Card A");
await imageLoads("dot.png");
await closeCard();
// The draft saves after the paste, without another edit, so the image survives a reload of the app.
await openCard("Card B");
const second = await pasteImage("second.png");
await waitForFile(page, draftImagesPath("card-b"), new RegExp(second));
await waitForFile(page, draftPath("card-b"), new RegExp(`pm-image:${second}`));
await page.reload();
await page.locator('[data-tree-rel="note.md"]').waitFor();
await openBoard(page, "Roadmap");
await openCard("Card B");
await imageLoads("second.png");
// Cancel removes the draft and its image data. The image folder gets no file.
await descriptionAction("Cancel").click();
await page.waitForFunction(rel => /"body":null/.test(window.__TEST__.files.get(rel) ?? ""), draftPath("card-b"));
assert.deepEqual((await json(page, draftImagesPath("card-b"))).images, {});
assert.equal(await fileText(page, imageFile(second)), undefined);
assert.doesNotMatch(await fileText(page, cardPath("card-b")), /pm-image:/);
await closeCard();
console.log("PASS: a draft image survives a close, a reopen, and a reload. Save writes its file. Cancel leaves no image data.");
});
+3 -5
View File
@@ -33,9 +33,9 @@ await runSmoke("find/documentFind", async ({ page }) => {
async function onePanel() { async function onePanel() {
assert.equal(await page.locator('.rs-find-bar:visible').count(), 1); assert.equal(await page.locator('.rs-find-bar:visible').count(), 1);
assert.equal(await page.locator('.cm-search').count(), 0, 'No default CodeMirror search panel'); assert.equal(await page.locator('.cm-search').count(), 0, 'No default CodeMirror search panel');
// Read both widths in one task. Two separate reads can cross a layout change. const bar = await page.locator('.rs-find-bar:visible').boundingBox();
const [bar, pane] = await page.locator('.rs-find-bar:visible').evaluate(node => [node, node.closest('.editor.pane-active')].map(element => element.getBoundingClientRect().width)); const pane = await page.locator('.editor.pane-active').boundingBox();
assert.ok(Math.abs(bar - pane) < 3, 'Find spans the document pane'); assert.ok(Math.abs(bar.width - pane.width) < 3, 'Find spans the document pane');
} }
async function sourceEditor() { async function sourceEditor() {
await page.waitForFunction(() => !!document.querySelector('.source-editor .cm-content')); await page.waitForFunction(() => !!document.querySelector('.source-editor .cm-content'));
@@ -120,8 +120,6 @@ await runSmoke("find/documentFind", async ({ page }) => {
await page.keyboard.press('F3'); await page.keyboard.press('F3');
await page.screenshot({ path: `${output}/source-replace-${theme}.png` }); await page.screenshot({ path: `${output}/source-replace-${theme}.png` });
await page.setViewportSize({ width: 800, height: 700 }); await page.setViewportSize({ width: 800, height: 700 });
// The outline closes in the resize event, one frame after the viewport changes. The pane width changes again at that point.
await page.locator('.shell.right-open').waitFor({ state: 'detached' });
await onePanel(); await onePanel();
assert.equal(await page.locator('.rs-find-bar').evaluate(node => node.scrollWidth <= node.clientWidth), true); 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.screenshot({ path: `${output}/source-narrow-${theme}.png` });
-81
View File
@@ -1,81 +0,0 @@
// Find takes typed text key by key in Write, Source, Read, and both sides of Split, also after Enter finds a match.
import assert from "node:assert/strict";
import { chooseView, mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("find/typing", async ({ page }) => {
const sample = "# Alpha\n\nAlpha alpha alphabet\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n| Beta | Two |\n\nLast Alpha paragraph.\n";
await mockTauri(page, {
state: { sample },
commands: test => {
const workspace = test.workspace({ root: "C:\\smoke-workspace", files: { "notes/welcome.md": test.state.sample } });
return { ...workspace, workspace_search: () => [], "plugin:dialog|message": () => "Cancel" };
},
});
const find = page.getByRole("textbox", { name: "Find in document", exact: true });
const type = text => page.keyboard.type(text, { delay: 15 });
const focused = () => find.evaluate(node => node === document.activeElement);
const reading = { typed: "Alpha alp", removed: "Alpha aha" };
/**
* Open Find, then type, delete, and type again without another click in the field.
* After Enter, CodeMirror selects the text of the field in Write and Source, so the next key replaces it.
* In Read, the caret stays at the end of the text, so the next key adds to it.
*/
async function typing(label, open, afterEnter = { typed: "p", removed: "ha" }) {
await open();
await page.keyboard.press("Control+f");
await find.waitFor();
assert.equal(await focused(), true, `${label}: Find has focus`);
await type("Alpha");
assert.equal(await find.inputValue(), "Alpha", `${label}: each key reaches the field`);
await page.keyboard.press("Backspace");
await type("a al");
assert.equal(await find.inputValue(), "Alpha al", `${label}: Backspace and more keys reach the field`);
assert.equal(await focused(), true, `${label}: Find keeps focus`);
await page.keyboard.press("Enter");
assert.equal(await focused(), true, `${label}: Enter keeps focus in Find`);
await type("p");
assert.equal(await find.inputValue(), afterEnter.typed, `${label}: keys after Enter reach the field`);
await page.keyboard.press("Enter");
await page.keyboard.press("Backspace");
await page.keyboard.press("Backspace");
await type("ha");
assert.equal(await find.inputValue(), afterEnter.removed, `${label}: Backspace after Enter acts on the field`);
await page.keyboard.press("Escape");
await find.waitFor({ state: "detached" });
}
await page.goto(smokeUrl);
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.locator(".cm-content").waitFor();
await typing("Write", async () => { await page.locator(".cm-content").click(); });
await typing("Source", async () => {
await chooseView(page, "Source");
await page.locator(".source-editor .cm-content").click();
});
await typing("Read", async () => {
await chooseView(page, "Read");
await page.locator(".md-page > .reading").focus();
}, reading);
await chooseView(page, "Source");
await chooseView(page, "Read beside");
await typing("Split, the text side", async () => { await page.locator(".source-editor .cm-content").click(); });
await typing("Split, the reading side", async () => { await page.locator(".md-page > .reading").click({ position: { x: 40, y: 10 } }); }, reading);
// A match stays selected until the search text changes, and the next search finds a match again.
await page.locator(".md-page > .reading").click({ position: { x: 40, y: 10 } });
await page.keyboard.press("Control+f");
await type("Alpha");
await page.keyboard.press("Enter");
assert.equal(await page.evaluate(() => window.getSelection().toString()), "Alpha", "Enter selects the match");
await type(" a");
assert.equal(await find.inputValue(), "Alpha a", "A key after Enter adds to the text");
assert.equal(await page.evaluate(() => window.getSelection().toString()), "", "A new key removes the selected match");
await page.keyboard.press("Enter");
assert.equal(await page.evaluate(() => window.getSelection().toString()), "Alpha a", "Enter selects the match of the longer text");
await page.keyboard.press("Escape");
});
-202
View File
@@ -1,202 +0,0 @@
// Split view with different tabs: two documents side by side, a browser tab beside a document, a browser tab that covers
// the area and then moves into a pane, the close control of a plugin pane, and the Read beside toggle, in both themes.
// Also the divider that resizes two panes, a tab that the user drags into a pane, and the new browser tab beside a browser tab.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/mixedSplits", async ({ page }) => {
const output = await outputDir("layout/mixedSplits");
await page.addInitScript(() => localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false })));
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\mixed-split-workspace",
files: { "a.md": "# Alpha\n\nAlpha text.\n", "b.md": "# Bravo\n\nBravo text.\n" },
});
const snapshot = { profiles: [{ id: "user", name: "User" }], tabs: [], bookmarks: [], settings: { search: "duckduckgo", adblock: true, linkDestination: "internal", personalRules: "", homepage: "", filterLists: [] } };
let next = 0;
return {
...workspace,
browser_connect: () => "window-session",
browser_request: ({ command, args }) => {
if (command === "newTab") { globalThis.newTabUrls = [...(globalThis.newTabUrls || []), args.url ?? null]; const tabId = "native-" + (++next); snapshot.tabs.push({ id: tabId, profileId: "user", url: "about:blank", title: "Browser", loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
if (command === "closeTab") snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.tabId);
return structuredClone(snapshot);
},
};
},
});
const pane = rel => page.locator(`[data-document-path="${rel}"]`);
const browserPane = page.locator(".plugin-pane:not(.inactive)").filter({ has: page.locator('[data-browser-state="ready"]') });
const tab = name => page.getByRole("tab", { name: new RegExp(name) });
async function openToRight(name) {
await tab(name).click({ button: "right" });
await page.getByRole("menuitem", { name: "Open to the right", exact: true }).click();
}
async function box(locator) { const value = await locator.boundingBox(); assert.ok(value, "The pane is visible"); return value; }
// A native tab drag: dragstart on the tab button, dragover at a place of the target, then the drop and dragend.
async function dragOver(source, target, where) {
const point = await target.evaluate((node, where) => {
const r = node.getBoundingClientRect();
return where === "down" ? { x: r.left + r.width / 2, y: r.bottom - 12 } : where === "right" ? { x: r.right - 12, y: r.top + r.height / 2 } : { x: r.left + r.width / 2, y: r.top + r.height / 2 };
}, where);
return source.evaluate((node, point) => {
const transfer = new DataTransfer();
node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, cancelable: true, dataTransfer: transfer }));
const over = new DragEvent("dragover", { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y, dataTransfer: transfer });
document.elementFromPoint(point.x, point.y).dispatchEvent(over);
globalThis.tabDrag = { node, transfer, point };
return over.defaultPrevented;
}, point);
}
async function drop() {
return page.evaluate(() => {
const { node, transfer, point } = globalThis.tabDrag;
const event = new DragEvent("drop", { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y, dataTransfer: transfer });
document.elementFromPoint(point.x, point.y).dispatchEvent(event);
node.dispatchEvent(new DragEvent("dragend", { bubbles: true, clientX: point.x, clientY: point.y, dataTransfer: transfer }));
return event.defaultPrevented;
});
}
async function setMode(mode) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, mode);
}
async function newBrowserTab() {
await page.evaluate(async () => { const { pluginHost } = await import("/src/lib/plugins/registry.ts"); await pluginHost.get("browser").newTab(); });
await page.locator('[data-browser-state="ready"]').last().waitFor();
}
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click(); await pane("a.md").locator(".cm-content").waitFor();
// A click in the file tree replaces the current tab, so the second file opens from a new tab.
await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
await page.locator('[data-tree-rel="b.md"]').click(); await pane("b.md").locator(".cm-content").waitFor();
assert.equal(await page.getByRole("tab").count(), 2);
await page.waitForFunction(async () => { const { pluginHost } = await import("/src/lib/plugins/registry.ts"); return !!pluginHost.get("browser"); });
// Two different documents side by side.
await openToRight("a.md");
await pane("a.md").locator(".cm-content").waitFor();
assert.equal(await page.locator(".document-pane").count(), 2);
const left = await box(pane("b.md")), right = await box(pane("a.md"));
assert.ok(right.x >= left.x + left.width - 1 && Math.abs(left.y - right.y) < 2, "The documents show side by side");
assert.equal(await pane("a.md").locator(".breadcrumb").innerText(), "a.md", "A pane beside another pane names its file");
await tab("a.md").click({ button: "right" });
assert.equal(await page.getByRole("menuitem", { name: "Open to the right", exact: true }).isDisabled(), true, "A visible tab cannot open again");
await page.keyboard.press("Escape");
// A new browser tab opens in the focused pane. The document that it replaces stays open as a tab.
await newBrowserTab();
assert.equal(await pane("a.md").count(), 0);
assert.equal(await tab("a.md").count(), 1);
const documentBox = await box(pane("b.md")), webBox = await box(browserPane);
assert.ok(webBox.x >= documentBox.x + documentBox.width - 1, "The browser shows beside the document");
assert.ok(Math.abs(webBox.width - documentBox.width) < 4, "The panes share the area");
for (const theme of ["light", "dark"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, theme);
await page.screenshot({ path: path.join(output, `document-and-browser-${theme}.png`) });
}
// A click in the document pane makes its tab active. The browser stays visible.
await pane("b.md").locator(".cm-content").click();
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent?.includes("b.md"));
assert.equal(await browserPane.count(), 1);
// The document opens beside the browser, and the close control of the browser pane leaves the tab open.
await openToRight("a.md");
await pane("a.md").locator(".cm-content").waitFor();
assert.equal(await page.locator(".document-pane").count(), 3);
await browserPane.getByRole("button", { name: "Close split", exact: true }).click();
assert.equal(await page.locator(".document-pane").count(), 2);
assert.equal(await page.getByRole("tab", { name: /Browser/ }).count(), 1);
await pane("a.md").getByRole("button", { name: "Close split", exact: true }).click();
assert.equal(await page.locator(".document-pane").count(), 1);
// A browser tab that covers the whole area moves into the left pane when a document opens to the right.
await page.getByRole("tab", { name: /Browser/ }).click();
await browserPane.waitFor();
assert.ok((await box(browserPane)).width > (await box(page.locator(".center"))).width - 4, "The browser covers the area");
await openToRight("a.md");
await pane("a.md").locator(".cm-content").waitFor();
const coverLeft = await box(browserPane), coverRight = await box(pane("a.md"));
assert.ok(coverRight.x >= coverLeft.x + coverLeft.width - 1, "The browser keeps the left pane");
await pane("a.md").getByRole("button", { name: "Close split", exact: true }).click();
await browserPane.waitFor();
assert.ok((await box(browserPane)).width > (await box(page.locator(".center"))).width - 4, "The last pane gives the browser the whole area");
// Read beside is the toggle for the Read view beside the editor.
await tab("b.md").click();
await pane("b.md").locator(".cm-content").waitFor();
await pane("b.md").getByRole("button", { name: "Read beside", exact: true }).click();
await pane("b.md").locator(".md-page").waitFor();
await pane("b.md").getByRole("button", { name: "Read beside", exact: true }).click();
// The divider between two panes changes their sizes, with the pointer and with the keyboard.
await openToRight("a.md");
await pane("a.md").locator(".cm-content").waitFor();
const divider = page.getByRole("separator", { name: "Resize panes" });
assert.equal(await divider.count(), 1);
const area = await box(page.locator(".center"));
const handle = await box(divider);
await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
await page.mouse.down();
await page.mouse.move(handle.x + handle.width / 2 - area.width * 0.2, handle.y + handle.height / 2, { steps: 4 });
await page.mouse.up();
const narrow = await box(pane("b.md")), wide = await box(pane("a.md"));
assert.ok(Math.abs(narrow.width - area.width * 0.3) < 4, `The left pane has 30% of the area: ${narrow.width} of ${area.width}`);
assert.ok(Math.abs(wide.x - (narrow.x + narrow.width)) < 2, "The right pane starts at the divider");
assert.equal(await divider.getAttribute("aria-valuenow"), "30");
await divider.focus(); await page.keyboard.press("ArrowRight");
assert.equal(await divider.getAttribute("aria-valuenow"), "35");
for (const mode of ["light", "dark"]) {
await setMode(mode);
await divider.hover();
await page.screenshot({ path: path.join(output, `divider-${mode}.png`) });
}
await divider.dblclick();
assert.equal(await divider.getAttribute("aria-valuenow"), "50");
// A new browser tab replaces the document in the focused pane. A document tab dragged to the bottom of the browser pane
// opens below it.
await newBrowserTab();
assert.equal(await pane("a.md").count(), 0);
assert.equal(await dragOver(tab("a.md"), browserPane, "down"), true, "The browser pane takes the tab");
await page.locator('.drop-hint[data-drop-zone="down"]').waitFor();
for (const mode of ["light", "dark"]) {
await setMode(mode);
await page.screenshot({ path: path.join(output, `tab-drop-${mode}.png`) });
}
assert.equal(await drop(), true);
await pane("a.md").locator(".cm-content").waitFor();
assert.equal(await page.locator(".drop-hint").count(), 0);
const web = await box(browserPane), below = await box(pane("a.md"));
assert.ok(below.y >= web.y + web.height - 1 && Math.abs(below.x - web.x) < 2, "The document shows below the browser");
assert.equal(await page.getByRole("separator", { name: "Resize panes" }).count(), 2);
// The browser tab dragged to the document pane replaces it there, and leaves its old pane. The first browser tab is not visible.
assert.equal(await dragOver(tab("Browser").last(), pane("b.md"), "center"), true);
assert.equal(await drop(), true);
await page.waitForFunction(() => document.querySelectorAll(".document-pane").length === 2);
assert.equal(await pane("b.md").count(), 0);
assert.equal(await tab("b.md").count(), 1, "The replaced document stays open as a tab");
const moved = await box(browserPane), rest = await box(pane("a.md"));
assert.ok(rest.x >= moved.x + moved.width - 1, "The browser shows left of the document");
// A drop on the pane that shows the tab changes nothing.
assert.equal(await dragOver(tab("Browser").last(), browserPane, "center"), false);
await drop();
// "New tab to the right" of a browser tab that covers the area opens a new browser tab beside it, not a copy of the page.
await pane("a.md").getByRole("button", { name: "Close split", exact: true }).click();
await browserPane.waitFor();
assert.ok((await box(browserPane)).width > area.width - 4, "The browser covers the area");
const before = await page.evaluate(() => globalThis.newTabUrls.length);
await tab("Browser").last().click({ button: "right" });
await page.getByRole("menuitem", { name: "New tab to the right", exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll(".plugin-pane.embedded:not(.inactive)").length === 2);
assert.deepEqual(await page.evaluate(start => globalThis.newTabUrls.slice(start), before), [null], "The new tab opens the home page");
const [first, second] = await page.locator(".plugin-pane.embedded:not(.inactive)").evaluateAll(nodes => nodes.map(node => { const r = node.getBoundingClientRect(); return { x: r.x, width: r.width }; }).sort((a, b) => a.x - b.x));
assert.ok(second.x >= first.x + first.width - 1 && first.width > area.width * 0.4, "The browser tabs show side by side");
await page.screenshot({ path: path.join(output, "browser-beside-browser.png") });
console.log(JSON.stringify({ passed: ["two documents side by side", "browser beside a document", "replaced document stays a tab", "focus by click", "plugin pane close control", "covering browser moves into a pane", "last pane releases the browser", "Read beside toggle", "divider by pointer, keyboard, and double-click", "tab drop below a pane", "tab drop replaces a pane", "new browser tab beside a browser tab", "light/dark screenshots"], nativeDesktop: "not tested" }, null, 2));
}, { timeout: 30000 });
+6 -29
View File
@@ -1,16 +1,15 @@
// Sidebar layout persistence: the hidden outline, resized sidebars, the navigation view, and collapsed backlinks survive layout changes, tab changes, reloads, and reopened windows. // Sidebar layout persistence: the hidden outline, resized sidebars, and the navigation view survive layout changes, reloads, and reopened windows.
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs"; import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/outline", async ({ browser }) => { await runSmoke("layout/outline", async ({ browser }) => {
const output = await outputDir("layout/outline");
// Pages share one context, so a reopened window keeps the saved layout. // Pages share one context, so a reopened window keeps the saved layout.
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } }); const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
// Unknown commands return null, as the original mock did. // Unknown commands return null, as the original mock did.
await mockTauri(context, { await mockTauri(context, {
strict: false, strict: false,
commands: test => ({ commands: test => ({
...test.workspace({ root: "D:\\LayoutTest", files: { "note.md": "# Layout test\n\nA note.\n", "data.txt": "Plain text.\n" } }), ...test.workspace({ root: "D:\\LayoutTest", files: { "note.md": "# Layout test\n\nA note.\n" } }),
plugins_snapshot: () => ({ root: "D:\\LayoutTest\\plugins", plugins: [] }), plugins_snapshot: () => ({ root: "D:\\LayoutTest\\plugins", plugins: [] }),
}), }),
}); });
@@ -33,15 +32,11 @@ await runSmoke("layout/outline", async ({ browser }) => {
async function widths() { async function widths() {
return page.locator(".shell").evaluate(element => [element.style.getPropertyValue("--left"), element.style.getPropertyValue("--right")]); return page.locator(".shell").evaluate(element => [element.style.getPropertyValue("--left"), element.style.getPropertyValue("--right")]);
} }
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).click();
await page.locator(`[role="tab"][data-path="${name}"][aria-selected="true"]`).waitFor();
}
await reopen(); await reopen();
await page.getByText("LayoutTest", { exact: true }).waitFor(); await page.getByText("LayoutTest", { exact: true }).waitFor();
await quickOpen("note.md"); await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("note.md");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.md" }).click();
await page.locator(".cm-content").waitFor(); await page.locator(".cm-content").waitFor();
await page.getByRole("button", { name: "Hide outline", exact: true }).click(); await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await page.keyboard.press("Control+e"); await page.keyboard.press("Control+e");
@@ -80,24 +75,6 @@ await runSmoke("layout/outline", async ({ browser }) => {
await page.getByRole("button", { name: "Show outline", exact: true }).click(); await page.getByRole("button", { name: "Show outline", exact: true }).click();
assert.deepEqual(await widths(), resized); assert.deepEqual(await widths(), resized);
console.log("PASS: collapsed sidebars retain their sizes and navigation view"); console.log("PASS: collapsed sidebars retain their sizes and navigation view");
// Card e81770bc: collapsed backlinks stay collapsed while a tab without backlinks is active, and after a window reopen.
const backlinks = () => page.getByRole("button", { name: /^Backlinks \d+$/ });
await quickOpen("note.md");
await backlinks().click();
assert.equal(await backlinks().getAttribute("aria-expanded"), "false");
await quickOpen("data.txt");
await backlinks().waitFor({ state: "detached" });
await quickOpen("note.md");
assert.equal(await backlinks().getAttribute("aria-expanded"), "false");
await page.screenshot({ path: `${output}/backlinks-collapsed-after-tab-change.png` });
await reopen();
await quickOpen("note.md");
assert.equal(await backlinks().getAttribute("aria-expanded"), "false");
await backlinks().click();
assert.equal(await backlinks().getAttribute("aria-expanded"), "true");
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("runestone.workbenchLayout")).backlinksOpen), true);
console.log("PASS: collapsed backlinks survive a tab change and a window reopen");
errors.push(...page.errors); errors.push(...page.errors);
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
@@ -51,7 +51,7 @@ await runSmoke("layout/panesAndSettings", async ({ browser }) => {
const menu = page.getByRole("menu", { name: "File actions", exact: true }); const menu = page.getByRole("menu", { name: "File actions", exact: true });
await menu.waitFor(); await menu.waitFor();
const labels = await menu.locator(":scope > button, :scope > hr").evaluateAll(nodes => nodes.map(node => node.tagName === "HR" ? "|" : node.querySelector(".action-label").textContent)); const labels = await menu.locator(":scope > button, :scope > hr").evaluateAll(nodes => nodes.map(node => node.tagName === "HR" ? "|" : node.querySelector(".action-label").textContent));
assert.deepEqual(labels, ["Open in new tab", "Open to the right", "Open in default app", "Open in terminal", "|", "Cut", "Copy", "Paste", "Make a copy", "|", assert.deepEqual(labels, ["Open in new tab", "Open in default app", "Open in terminal", "|", "Cut", "Copy", "Paste", "Make a copy", "|",
"Rename", "Remove bookmark", "Pin", "Save as template", "|", "Show in Explorer", "Copy path", "|", "Undo file move", "Redo file move", "|", "Delete", "Delete permanently"]); "Rename", "Remove bookmark", "Pin", "Save as template", "|", "Show in Explorer", "Copy path", "|", "Undo file move", "Redo file move", "|", "Delete", "Delete permanently"]);
const error = await page.evaluate(() => { const probe = document.createElement("span"); probe.style.color = "var(--rs-error)"; document.body.append(probe); const color = getComputedStyle(probe).color; probe.remove(); return color; }); const error = await page.evaluate(() => { const probe = document.createElement("span"); probe.style.color = "var(--rs-error)"; document.body.append(probe); const color = getComputedStyle(probe).color; probe.remove(); return color; });
assert.equal(await menu.getByRole("menuitem", { name: "Delete", exact: true }).evaluate(node => getComputedStyle(node).color), error); assert.equal(await menu.getByRole("menuitem", { name: "Delete", exact: true }).evaluate(node => getComputedStyle(node).color), error);
@@ -1,84 +0,0 @@
// A PDF file beside a note: "Open to the right" in the file tree opens the PDF in a new pane beside the note.
// The user writes in the note and turns the pages of the PDF, and both panes stay visible. A drag of the divider resizes
// both panes. A PDF that covers the area moves into the left pane when a note opens to its right. Both themes.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { samplePdf } from "../../fixtures/pdf/fixtures.mjs";
await runSmoke("layout/pdfBesideNote", async ({ page }) => {
const output = await outputDir("layout/pdfBesideNote");
await page.addInitScript(() => localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false })));
await mockTauri(page, {
state: { sample: [...samplePdf()] },
commands: test => ({
...test.workspace({ root: "C:\\pdf-beside-note", files: { "Sample.pdf": "", "note.md": "# Note\n\nReading notes.\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
workspace_read_bytes: () => new Uint8Array(test.state.sample).buffer,
}),
});
const row = name => page.locator(`[data-tree-rel="${name}"]`);
const note = page.locator('[data-document-path="note.md"]');
const pdf = page.locator(".plugin-pane:not(.inactive)").filter({ has: page.locator(".pdf-viewer") });
const status = pdf.locator(".pdf-viewer .status");
async function box(locator) { const value = await locator.boundingBox(); assert.ok(value, "The pane is visible"); return value; }
async function besideEachOther(left, right, message) {
const a = await box(left), b = await box(right);
assert.ok(b.x >= a.x + a.width - 1 && Math.abs(a.y - b.y) < 2, message);
return [a, b];
}
await page.goto(smokeUrl);
await row("note.md").click();
await note.locator(".cm-content").waitFor();
// The file tree opens the PDF in a new pane to the right of the note.
await row("Sample.pdf").click({ button: "right" });
await page.getByRole("menuitem", { name: "Open to the right", exact: true }).click();
await status.filter({ hasText: /^Page 1 of 2$/ }).waitFor();
assert.equal(await page.locator(".document-pane").count(), 2);
await besideEachOther(note, pdf, "The PDF shows to the right of the note");
// Write in the note. The PDF stays visible.
await note.locator(".cm-content").click();
await page.keyboard.press("Control+End");
await page.keyboard.type("Typed beside the PDF.");
assert.match(await note.locator(".cm-content").innerText(), /Typed beside the PDF\./);
assert.equal(await pdf.count(), 1);
// Turn a page of the PDF. The note stays visible and keeps the text.
await pdf.getByRole("button", { name: "Next page", exact: true }).click();
await status.filter({ hasText: /^Page 2 of 2$/ }).waitFor();
assert.match(await note.locator(".cm-content").innerText(), /Typed beside the PDF\./);
// Back to the note: the keyboard goes to the note.
await note.locator(".cm-content").click();
await page.keyboard.type(" More.");
assert.match(await note.locator(".cm-content").innerText(), /Typed beside the PDF\. More\./);
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent?.includes("note.md"));
// The divider gives the PDF more space.
const divider = page.getByRole("separator", { name: "Resize panes" });
const handle = await box(divider), area = await box(page.locator(".center"));
await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
await page.mouse.down();
await page.mouse.move(handle.x + handle.width / 2 - area.width * 0.15, handle.y + handle.height / 2, { steps: 4 });
await page.mouse.up();
const [left, right] = await besideEachOther(note, pdf, "The panes stay side by side after a resize");
assert.ok(right.width > left.width + area.width * 0.2, "The PDF pane is wider than the note pane");
for (const mode of ["light", "dark"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, mode);
await page.screenshot({ path: path.join(output, `pdf-beside-note-${mode}.png`) });
}
// A PDF that covers the area moves into the left pane when a note opens to its right.
await pdf.getByRole("button", { name: "Close split", exact: true }).click();
await page.getByRole("tab", { name: /Sample/ }).click();
await status.waitFor();
assert.ok((await box(pdf)).width > area.width - 4, "The PDF covers the area");
await row("note.md").click({ button: "right" });
await page.getByRole("menuitem", { name: "Open to the right", exact: true }).click();
await note.locator(".cm-content").waitFor();
await besideEachOther(pdf, note, "The PDF keeps the left pane");
console.log(JSON.stringify({ passed: ["file tree opens a PDF to the right", "typing in the note beside the PDF", "page turn in the PDF beside the note", "divider resize", "covering PDF moves into a pane", "light/dark screenshots"], nativeDesktop: "not tested" }, null, 2));
}, { timeout: 30000 });
+5 -11
View File
@@ -67,14 +67,8 @@ await runSmoke("layout/titleBar", async ({ browser }) => {
await page.keyboard.press("Control+\\"); await page.keyboard.press("Control+\\");
await page.locator("aside.left").waitFor(); await page.locator("aside.left").waitFor();
// With few tabs, the drag area fills the free space after the + button.
const drag = page.locator(".window-drag-space");
await open(names[0]);
const center = await box(page.locator(".header-center")), free = await box(drag);
assert.ok(free.width > 400 && Math.abs(free.right - center.right) <= 1, JSON.stringify({ center, free }));
// Tabs keep a readable width and scroll. Fades show hidden tabs, and the list names every tab. // Tabs keep a readable width and scroll. Fades show hidden tabs, and the list names every tab.
for (const name of names.slice(1)) await open(name); for (const name of names) await open(name);
const widths = await page.locator("header .tab").evaluateAll(tabs => tabs.map(tab => tab.getBoundingClientRect().width)); const widths = await page.locator("header .tab").evaluateAll(tabs => tabs.map(tab => tab.getBoundingClientRect().width));
assert.ok(widths.every(width => width >= 120), JSON.stringify(widths)); assert.ok(widths.every(width => width >= 120), JSON.stringify(widths));
const strip = page.locator("header .tabs"); const strip = page.locator("header .tabs");
@@ -99,9 +93,9 @@ await runSmoke("layout/titleBar", async ({ browser }) => {
await list.waitFor({ state: "detached" }); await list.waitFor({ state: "detached" });
assert.equal(await strip.evaluate(node => node.classList.contains("fade-end")), true); assert.equal(await strip.evaluate(node => node.classList.contains("fade-end")), true);
// When the tabs scroll, they use all space up to a drag area of 48 pixels. Caption buttons are square and fill the title bar height. // A fixed drag area follows the tabs. Caption buttons are square and fill the title bar height.
assert.equal(Math.round((await box(drag)).width), 48); const drag = page.locator(".window-drag-space");
assert.ok(Math.abs((await box(drag)).right - (await box(page.locator(".header-center"))).right) <= 1); assert.equal(Math.round((await box(drag)).width), 120);
assert.equal(await drag.getAttribute("data-tauri-drag-region"), ""); assert.equal(await drag.getAttribute("data-tauri-drag-region"), "");
const captions = await page.locator(".window-controls .icon-btn").evaluateAll(buttons => buttons.map(button => ({ width: button.getBoundingClientRect().width, height: button.getBoundingClientRect().height, radius: getComputedStyle(button).borderRadius }))); const captions = await page.locator(".window-controls .icon-btn").evaluateAll(buttons => buttons.map(button => ({ width: button.getBoundingClientRect().width, height: button.getBoundingClientRect().height, radius: getComputedStyle(button).borderRadius })));
const height = (await box(page.locator("header.header"))).height; const height = (await box(page.locator("header.header"))).height;
@@ -140,5 +134,5 @@ await runSmoke("layout/titleBar", async ({ browser }) => {
assert.match(await mac.getByRole("button", { name: "Settings (⌘,)", exact: true }).getAttribute("aria-label"), /⌘/); assert.match(await mac.getByRole("button", { name: "Settings (⌘,)", exact: true }).getAttribute("aria-label"), /⌘/);
await mac.locator("header.header").screenshot({ path: `${output}/header-mac.png` }); await mac.locator("header.header").screenshot({ path: `${output}/header-mac.png` });
assert.deepEqual([...page.errors, ...mac.errors], []); assert.deepEqual([...page.errors, ...mac.errors], []);
console.log("PASS: bottom bar of the side pane, ribbon fallback, readable tabs with fades and a list, tabs that fill the header up to the drag area, square caption buttons, Snap Layouts request, macOS layout, both themes, narrow window."); console.log("PASS: bottom bar of the side pane, ribbon fallback, readable tabs with fades and a list, fixed drag area, square caption buttons, Snap Layouts request, macOS layout, both themes, narrow window.");
}); });
+6 -6
View File
@@ -21,7 +21,7 @@ await runSmoke("layout/viewModes", async ({ browser }) => {
const page = await openPage(context), settings = await openPage(context); const page = await openPage(context), settings = await openPage(context);
const group = page.getByRole("radiogroup", { name: "View", exact: true }); const group = page.getByRole("radiogroup", { name: "View", exact: true });
const radio = name => group.getByRole("radio", { name, exact: true }); const radio = name => group.getByRole("radio", { name, exact: true });
const split = page.locator(".chrome-bar").getByRole("button", { name: "Read beside", exact: true }); const split = page.locator(".chrome-bar").getByRole("button", { name: "Split", exact: true });
const checked = () => group.getByRole("radio", { checked: true }).getAttribute("aria-label"); const checked = () => group.getByRole("radio", { checked: true }).getAttribute("aria-label");
const status = () => page.locator(".status").innerText(); const status = () => page.locator(".status").innerText();
async function open(name) { async function open(name) {
@@ -86,7 +86,7 @@ await runSmoke("layout/viewModes", async ({ browser }) => {
await page.locator(".live-writer").waitFor(); await page.locator(".live-writer").waitFor();
// Split shows Read beside the current editor. Write and Source keep it. Read ends it. // Split shows Read beside the current editor. Write and Source keep it. Read ends it.
await chooseView(page, "Read beside"); await chooseView(page, "Split");
assert.equal(await split.getAttribute("aria-pressed"), "true"); assert.equal(await split.getAttribute("aria-pressed"), "true");
await page.locator(".body.split .live-writer").waitFor(); await page.locator(".body.split .live-writer").waitFor();
await page.locator(".body.split .md-page").waitFor(); await page.locator(".body.split .md-page").waitFor();
@@ -97,10 +97,10 @@ await runSmoke("layout/viewModes", async ({ browser }) => {
assert.equal(await split.getAttribute("aria-pressed"), "false"); assert.equal(await split.getAttribute("aria-pressed"), "false");
assert.equal(await page.locator(".body.split").count(), 0); assert.equal(await page.locator(".body.split").count(), 0);
assert.equal(await page.locator(".editor-wrap").isVisible(), false); assert.equal(await page.locator(".editor-wrap").isVisible(), false);
await chooseView(page, "Read beside"); await chooseView(page, "Split");
await page.locator(".body.split .source-editor").waitFor(); await page.locator(".body.split .source-editor").waitFor();
assert.equal(await checked(), "Source"); assert.equal(await checked(), "Source");
await chooseView(page, "Read beside"); await chooseView(page, "Split");
await chooseView(page, "Write"); await chooseView(page, "Write");
// The file title shows by default. The General setting hides it in Write and Read. // The file title shows by default. The General setting hides it in Write and Read.
@@ -123,9 +123,9 @@ await runSmoke("layout/viewModes", async ({ browser }) => {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); window.dispatchEvent(new Event("focus")); }, theme); await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); window.dispatchEvent(new Event("focus")); }, theme);
await page.waitForFunction(mode => document.documentElement.dataset.theme === mode, theme); await page.waitForFunction(mode => document.documentElement.dataset.theme === mode, theme);
await page.locator(".chrome-bar").screenshot({ path: `${output}/bar-${theme}.png` }); await page.locator(".chrome-bar").screenshot({ path: `${output}/bar-${theme}.png` });
await chooseView(page, "Read beside"); await chooseView(page, "Split");
await page.locator(".chrome-bar").screenshot({ path: `${output}/bar-split-${theme}.png` }); await page.locator(".chrome-bar").screenshot({ path: `${output}/bar-split-${theme}.png` });
await chooseView(page, "Read beside"); await chooseView(page, "Split");
} }
// The controls show icons only, at every width (UI-056). The names stay for assistive technology and tooltips. // The controls show icons only, at every width (UI-056). The names stay for assistive technology and tooltips.
+3 -3
View File
@@ -72,7 +72,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
await page.keyboard.press("Control+s"); await page.keyboard.press("Control+s");
await page.waitForFunction(expected => window.__TEST__.files.get("notes/welcome.md") === expected, original + "Added in source."); await page.waitForFunction(expected => window.__TEST__.files.get("notes/welcome.md") === expected, original + "Added in source.");
await chooseView(page, "Read beside"); await chooseView(page, "Split");
await page.locator(".md-page h1").first().waitFor(); await page.locator(".md-page h1").first().waitFor();
assert.ok(await page.locator(".source-editor").isVisible()); assert.ok(await page.locator(".source-editor").isVisible());
await page.evaluate(() => { await page.evaluate(() => {
@@ -153,7 +153,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
await page.locator(".md-page").evaluate(element => { element.scrollTop = 0; }); await page.locator(".md-page").evaluate(element => { element.scrollTop = 0; });
await page.screenshot({ path: path.join(output, "reader-narrow.png") }); await page.screenshot({ path: path.join(output, "reader-narrow.png") });
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1)); assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
await chooseView(page, "Read beside"); await chooseView(page, "Split");
await page.waitForFunction(() => { await page.waitForFunction(() => {
const host = document.querySelector(".source-editor"); const host = document.querySelector(".source-editor");
const rendered = host?.querySelector(".cm-editor"); const rendered = host?.querySelector(".cm-editor");
@@ -168,7 +168,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
await page.screenshot({ path: path.join(output, "reader-split-wide.png") }); await page.screenshot({ path: path.join(output, "reader-split-wide.png") });
// A second press ends the Split view. // A second press ends the Split view.
await chooseView(page, "Read beside"); await chooseView(page, "Split");
await page.locator(".md-page").waitFor({ state: "detached" }); await page.locator(".md-page").waitFor({ state: "detached" });
// The editor stores one line break character. The saved file keeps its own line breaks. // The editor stores one line break character. The saved file keeps its own line breaks.
assert.equal(await contents(), showcase.replace(/\r\n/g, "\n")); assert.equal(await contents(), showcase.replace(/\r\n/g, "\n"));
+3 -20
View File
@@ -26,7 +26,7 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
const url = new URL(smokeUrl).href; const url = new URL(smokeUrl).href;
const filler = Array.from({ length: 50 }, (_, i) => `Paragraph ${i}. Some text before the destination.\n`).join('\n'); const filler = Array.from({ length: 50 }, (_, i) => `Paragraph ${i}. Some text before the destination.\n`).join('\n');
const source = '# Install and start\n\nChoose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).\n\n[Other document](other.md#caf%C3%A9-setup-1)\n\n[Missing section](#no-such-section)\n\n' + filler + '\n## Windows installer\n\nWindows instructions.\n\n' + filler + '\n## macOS installer (Apple Silicon)\n\nMac instructions.\n\n' + filler + '\n## Linux (Intel/AMD 64-bit)\n\nLinux instructions.\n'; const source = '# Install and start\n\nChoose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).\n\n[Other document](other.md#caf%C3%A9-setup-1)\n\n[Missing section](#no-such-section)\n\n' + filler + '\n## Windows installer\n\nWindows instructions.\n\n' + filler + '\n## macOS installer (Apple Silicon)\n\nMac instructions.\n\n' + filler + '\n## Linux (Intel/AMD 64-bit)\n\nLinux instructions.\n';
const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n\n' + filler; const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n';
async function writerJump(label, line) { async function writerJump(label, line) {
const link = page.locator('.cm-content .writer-link').filter({ hasText: label }).first(); const link = page.locator('.cm-content .writer-link').filter({ hasText: label }).first();
await link.click({ modifiers: ['Control'] }); await link.click({ modifiers: ['Control'] });
@@ -57,16 +57,6 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
return !heading.hidden && rect.top >= box.top && rect.bottom <= box.bottom; return !heading.hidden && rect.top >= box.top && rect.bottom <= box.bottom;
}, text); }, text);
} }
// A heading link puts the heading at the top of the view, below a gap of about 24 pixels.
// The last heading of a short document cannot reach the top, so the checks use headings with text below them.
async function headingAtTop(selector, text, scroller) {
await page.waitForFunction(({ selector, text, scroller }) => [...document.querySelectorAll(selector)].some(node => {
const offset = node.textContent.includes(text) ? node.getBoundingClientRect().top - node.closest(scroller).getBoundingClientRect().top : -1;
return offset >= 0 && offset <= 60;
}), { selector, text, scroller });
}
const writerHeadingAtTop = text => headingAtTop('.cm-line.writer-heading', text, '.cm-scroller');
const readerHeadingAtTop = text => headingAtTop('.reading h2', text, '.md-page');
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) { for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height:1000 }); await page.setViewportSize({ width, height:1000 });
await page.goto(url); await page.goto(url);
@@ -82,12 +72,10 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
await page.getByRole('button', { name:'Hide outline', exact:true }).click(); await page.getByRole('button', { name:'Hide outline', exact:true }).click();
} }
await writerJump('Windows setup', await jumpLine('## Windows installer')); await writerJump('Windows setup', await jumpLine('## Windows installer'));
await writerHeadingAtTop('Windows installer');
await top(); await top();
await writerJump('Windows setup', await jumpLine('## Windows installer')); await writerJump('Windows setup', await jumpLine('## Windows installer'));
await top(); await top();
await writerJump('macOS setup', await jumpLine('## macOS installer')); await writerJump('macOS setup', await jumpLine('## macOS installer'));
await writerHeadingAtTop('macOS installer (Apple Silicon)');
await top(); await top();
await writerJump('Linux setup', await jumpLine('## Linux')); await writerJump('Linux setup', await jumpLine('## Linux'));
await page.screenshot({ path:`${output}/writer-${theme}-${width}.png` }); await page.screenshot({ path:`${output}/writer-${theme}-${width}.png` });
@@ -103,26 +91,21 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
const view = node ? EditorView.findFromDOM(node) : null; const view = node ? EditorView.findFromDOM(node) : null;
return view && view.state.doc.lineAt(view.state.selection.main.head).text === '## Café setup' && view.state.selection.main.head > 100; return view && view.state.doc.lineAt(view.state.selection.main.head).text === '## Café setup' && view.state.selection.main.head > 100;
}); });
// The card case: a link to a heading in another file.
await writerHeadingAtTop('Café setup');
await page.screenshot({ path:`${output}/other-file-${theme}-${width}.png` });
assert.equal(await page.getByRole('tab', { name:'a.md', exact:true }).count(), 1); assert.equal(await page.getByRole('tab', { name:'a.md', exact:true }).count(), 1);
await page.getByRole('tab', { name:'a.md', exact:true }).click(); await page.getByRole('tab', { name:'a.md', exact:true }).click();
await top(); await top();
await chooseView(page, 'Read'); await chooseView(page, 'Read');
await readerJump('Windows setup', 'Windows installer'); await readerJump('Windows setup', 'Windows installer');
await readerHeadingAtTop('Windows installer');
await page.screenshot({ path:`${output}/reading-${theme}-${width}.png` }); await page.screenshot({ path:`${output}/reading-${theme}-${width}.png` });
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; }); await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('macOS setup', 'macOS installer (Apple Silicon)'); await readerJump('macOS setup', 'macOS installer (Apple Silicon)');
await readerHeadingAtTop('macOS installer (Apple Silicon)');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; }); await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)'); await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
await chooseView(page, 'Read beside'); await chooseView(page, 'Split');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; }); await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Windows setup', 'Windows installer'); await readerJump('Windows setup', 'Windows installer');
await page.screenshot({ path:`${output}/split-${theme}-${width}.png` }); await page.screenshot({ path:`${output}/split-${theme}-${width}.png` });
await chooseView(page, 'Read beside'); await chooseView(page, 'Split');
await chooseView(page, 'Source'); await chooseView(page, 'Source');
await page.locator('.source-editor .cm-content').waitFor(); await page.locator('.source-editor .cm-content').waitFor();
await chooseView(page, 'Read'); await chooseView(page, 'Read');
+2 -2
View File
@@ -129,7 +129,7 @@ await runSmoke("tables/formulas", async ({ page }) => {
await page.keyboard.press('Control+e'); await page.keyboard.press('Control+e');
assert.equal(await result(3, 1).innerText(), '12'); assert.equal(await result(3, 1).innerText(), '12');
assert.equal(await result(3, 3).innerText(), '58'); assert.equal(await result(3, 3).innerText(), '58');
for (const mode of ['Read', 'Read beside']) { for (const mode of ['Read', 'Split']) {
await chooseView(page, mode); await chooseView(page, mode);
const preview = page.locator('.md-page table').first(); const preview = page.locator('.md-page table').first();
await preview.waitFor(); await preview.waitFor();
@@ -146,7 +146,7 @@ await runSmoke("tables/formulas", async ({ page }) => {
assert.match(await total.innerText(), /=SUM\(D2:D3\)/); assert.match(await total.innerText(), /=SUM\(D2:D3\)/);
assert.match(await total.innerText(), /=SUM\(B2:B3\)/); assert.match(await total.innerText(), /=SUM\(B2:B3\)/);
await shot('formulas-off-split'); await shot('formulas-off-split');
await chooseView(page, 'Read beside'); await chooseView(page, 'Split');
await table.waitFor(); await table.waitFor();
assert.equal(await table.locator('.md-table-formula').count(), 0); assert.equal(await table.locator('.md-table-formula').count(), 0);
assert.match(await cell(3, 3).innerText(), /=SUM\(D2:D3\)/); assert.match(await cell(3, 3).innerText(), /=SUM\(D2:D3\)/);
@@ -1,62 +0,0 @@
// A click on a link in a table cell that took focus a moment earlier. The ProseMirror focus check runs before selectionchange, and the link source still opens at the clicked character.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tables/linkClickAfterFocus", async ({ page }) => {
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: "C:\\tab-menu-workspace",
files: { "a.md": "| Name | Value |\n| --- | --- |\n| One | Text |\n| Two | Before [Guide](docs/guide.md) after |\n" },
}),
spelling_menu_install: () => null,
}),
});
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.writer-table').waitFor();
await page.getByRole('cell', { name:'B2 · Row 2, column 2', exact:true }).click();
await page.locator('.writer-cell-editor').waitFor();
// Force the order that load causes: the click moves the native selection, the focus check runs, and only then selectionchange reaches ProseMirror.
// The focus check is the 20 ms timer in the focus handler of prosemirror-view. Its source is the only timer source that reads currentSelection.
await page.evaluate(() => {
const setTimeout = window.setTimeout, checks = [];
const hold = event => event.stopImmediatePropagation();
window.setTimeout = (run, delay, ...rest) => {
if (delay !== 20 || !String(run).includes('currentSelection')) return setTimeout(run, delay, ...rest);
checks.push(run);
return 0;
};
document.addEventListener('selectionchange', hold, true);
window.__runFocusCheck = () => {
window.setTimeout = setTimeout;
for (const check of checks) check();
document.removeEventListener('selectionchange', hold, true);
return checks.length;
};
});
await page.keyboard.press('Enter');
const linkCell = page.getByRole('cell', { name:'B3 · Row 3, column 2', exact:true });
await linkCell.locator('.writer-cell-editor').waitFor();
// Let the other timers of the new editor run. A flush after the click reads the native selection and hides the race.
await page.waitForTimeout(100);
const point = await linkCell.locator('a').evaluate(link => {
const range = document.createRange();
range.setStart(link.firstChild, 1); range.collapse(true);
const rect = range.getBoundingClientRect();
return { x: rect.x, y: rect.y + rect.height / 2 };
});
await page.mouse.click(point.x, point.y);
assert.ok(await page.evaluate(() => window.__runFocusCheck()) > 0, 'The focus check ran after the click');
await page.locator('.is-source-editing .writer-cell-editor').waitFor();
assert.equal(await linkCell.locator('.writer-link-target').innerText(), 'docs/guide.md', 'The click opens the link source');
const caretPrefix = await page.evaluate(() => {
const selection = getSelection(), range = document.createRange();
range.selectNodeContents(document.querySelector('.is-source-editing .writer-cell-editor'));
range.setEnd(selection.anchorNode, selection.anchorOffset);
return range.toString();
});
assert.equal(caretPrefix, 'Before [G', 'The caret stays at the clicked label character');
});
+3 -3
View File
@@ -59,7 +59,7 @@ await runSmoke("tabs/menus", async ({ page }) => {
const view = async name => { const view = async name => {
await show("d.md"); await show("d.md");
await item("View").click(); await item("View").click();
await page.getByRole(name === "Read beside" ? "menuitemcheckbox" : "menuitemradio", { name, exact: true }).click(); await page.getByRole(name === "Split" ? "menuitemcheckbox" : "menuitemradio", { name, exact: true }).click();
}; };
await show("d.md"); await show("d.md");
await item("View").click(); await item("View").click();
@@ -68,11 +68,11 @@ await runSmoke("tabs/menus", async ({ page }) => {
await page.keyboard.press("Escape"); await page.keyboard.press("Escape");
await view("Read"); await view("Read");
await page.locator(".md-page").waitFor(); await page.locator(".md-page").waitFor();
await view("Read beside"); await view("Split");
await page.locator(".body.split .md-page").waitFor(); await page.locator(".body.split .md-page").waitFor();
await view("Source"); await view("Source");
await page.locator(".body.split .source-editor .cm-content").waitFor(); await page.locator(".body.split .source-editor .cm-content").waitFor();
await view("Read beside"); await view("Split");
await page.locator(".md-page").waitFor({ state: "detached" }); await page.locator(".md-page").waitFor({ state: "detached" });
await view("Write"); await view("Write");
await page.locator(".live-writer .cm-editor").waitFor(); await page.locator(".live-writer .cm-editor").waitFor();
+2 -2
View File
@@ -65,9 +65,9 @@ await runSmoke("tabs/scroll", async ({ page }) => {
await roundTrip('.cm-scroller', 'Writing'); await roundTrip('.cm-scroller', 'Writing');
await chooseView(page, 'Read'); await chooseView(page, 'Read');
await roundTrip('.md-page', 'Reading'); await roundTrip('.md-page', 'Reading');
await chooseView(page, 'Read beside'); await chooseView(page, 'Split');
await roundTrip('.md-page', 'Split preview'); await roundTrip('.md-page', 'Split preview');
await chooseView(page, 'Read beside'); await chooseView(page, 'Split');
await chooseView(page, 'Source'); await chooseView(page, 'Source');
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click(); await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
await chooseView(page, 'Source'); await chooseView(page, 'Source');
-32
View File
@@ -1,32 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { estimatedImageHeight, imageSize, rememberImageSize } from "../../../src/lib/workspace/imageSizes.ts";
import { renderMarkdownHtml } from "../../../src/lib/workspace/noteHtml.ts";
test("a rendered image has size attributes only when its size is known", () => {
const unknown = "data:image/png;base64,AAAA";
const known = "data:image/png;base64,BBBB";
rememberImageSize(known, 1400, 700);
const urls = new Map([["a.png", unknown], ["b.png", known]]);
assert.doesNotMatch(renderMarkdownHtml("![a](a.png)", urls), /width=/);
assert.match(renderMarkdownHtml("![b](b.png)", urls), /width="1400" height="700"/);
});
test("a large data URL keeps its size without the image data as the key", () => {
const url = `data:image/png;base64,${"A".repeat(5000)}${"B".repeat(100)}${"C".repeat(5000)}`;
const other = `data:image/png;base64,${"A".repeat(5000)}${"D".repeat(100)}${"C".repeat(5000)}`;
rememberImageSize(url, 10, 20);
assert.deepEqual(imageSize(url), { width: 10, height: 20 });
assert.equal(imageSize(other), undefined);
});
test("an image without a real size stays unknown", () => {
rememberImageSize("data:image/svg+xml;base64,AAAA", 0, 0);
assert.equal(imageSize("data:image/svg+xml;base64,AAAA"), undefined);
});
test("the estimate scales a wide image to the text column and keeps a small image", () => {
assert.equal(estimatedImageHeight('<img src="x" alt="">'), -1);
assert.equal(estimatedImageHeight('<img width="1480" height="740">'), 370 + 45);
assert.equal(estimatedImageHeight('<img width="100" height="50">'), 50 + 45);
});
+1 -33
View File
@@ -4,7 +4,7 @@ import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts"; import { featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
import { identifyPdf } from "../../../src/lib/features/pdfDocument.ts"; import { identifyPdf } from "../../../src/lib/features/pdfDocument.ts";
import { PAGE_GAP, PAGE_MARGIN, fitZoom, mostVisiblePage, nextRotation, outputScale, pageBoxes, pageNumber, pagesInRange, zoomFromText, zoomLevel } from "../../../src/lib/features/pdf/model.ts"; import { nextRotation, outputScale, pageNumber, zoomLevel } from "../../../src/lib/features/pdf/model.ts";
import { FeatureSession } from "../../../src/lib/features/session.ts"; import { FeatureSession } from "../../../src/lib/features/session.ts";
import type { FeatureContext, FeatureInstance } from "../../../src/lib/features/types.ts"; import type { FeatureContext, FeatureInstance } from "../../../src/lib/features/types.ts";
import type { PluginDocumentContext } from "../../../src/lib/plugins/sdk.ts"; import type { PluginDocumentContext } from "../../../src/lib/plugins/sdk.ts";
@@ -26,38 +26,6 @@ test("page and zoom inputs stay within supported bounds", () => {
assert.deepEqual([0, 90, 180, 270].map(nextRotation), [90, 180, 270, 0]); assert.deepEqual([0, 90, 180, 270].map(nextRotation), [90, 180, 270, 0]);
}); });
test("a typed zoom is a percent within the limits", () => {
assert.equal(zoomFromText("137"), 1.37);
assert.equal(zoomFromText(" 150 % "), 1.5);
assert.equal(zoomFromText("112,5"), 1.125);
assert.equal(zoomFromText("9000"), 4);
assert.equal(zoomFromText("1"), .25);
for (const text of ["", " ", "text", "-50", "0", "1e999"]) assert.equal(zoomFromText(text), null);
});
test("the pages are one column, and the scroll position gives the current page", () => {
const sizes = [{ width: 600, height: 800 }, { width: 800, height: 600 }, { width: 600, height: 800 }];
const boxes = pageBoxes(sizes, .5, 0);
assert.deepEqual(boxes, [
{ top: PAGE_MARGIN, width: 300, height: 400 },
{ top: PAGE_MARGIN + 400 + PAGE_GAP, width: 400, height: 300 },
{ top: PAGE_MARGIN + 700 + 2 * PAGE_GAP, width: 300, height: 400 },
]);
assert.deepEqual(pageBoxes(sizes, 1, 90).map(box => [box.width, box.height]), [[800, 600], [600, 800], [800, 600]]);
assert.equal(fitZoom(sizes, 0, 400), .5);
assert.equal(fitZoom(sizes, 90, 400), .5);
assert.equal(fitZoom([{ width: 600, height: 900 }], 90, 450), .5);
assert.equal(fitZoom([], 0, 400), 1);
assert.deepEqual(pagesInRange(boxes, 0, 100), [1]);
assert.deepEqual(pagesInRange(boxes, 400, 800), [1, 2, 3]);
assert.deepEqual(pagesInRange(boxes, 5000, 6000), []);
assert.equal(mostVisiblePage(boxes, 0, 300), 1);
assert.equal(mostVisiblePage(boxes, 300, 600), 2);
assert.equal(mostVisiblePage(boxes, 900, 1200), 3);
assert.equal(mostVisiblePage(boxes, 0, 2000), 1, "The first page wins when several pages show in full");
assert.equal(mostVisiblePage([], 0, 100), 1);
});
test("large PDF pages respect canvas dimension and memory limits", () => { test("large PDF pages respect canvas dimension and memory limits", () => {
for (const [width, height] of [[612, 792], [20000, 500], [20000, 20000]]) { for (const [width, height] of [[612, 792], [20000, 500], [20000, 20000]]) {
const scale = outputScale(width, height, 3); const scale = outputScale(width, height, 3);
@@ -1,108 +0,0 @@
// The image data of description drafts: an image in an unsaved description survives a close, and a discard leaves no image data.
import test from "node:test";
import assert from "node:assert/strict";
import { DescriptionDraft } from "../../../../src/lib/features/pm/storage/description-draft.ts";
import { imageMarkdown, imagePath, saveImages } from "../../../../src/lib/features/pm/storage/images.ts";
import { privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
import { memoryWorkspace } from "./_memory.ts";
const one = "12345678-1234-1234-1234-123456789abc";
const two = "87654321-1234-1234-1234-123456789abc";
const data = "data:image/png;base64,aGVsbG8=";
const other = "data:image/gif;base64,R0lGOD==";
/** A workspace that records the path of each write and creation, in order. */
function recorded() {
const workspace = memoryWorkspace({ [privateRulesPath]: "*\n" });
const writes: string[] = [];
const { write, create } = workspace;
workspace.write = async (path, contents, expected) => { await write(path, contents, expected); writes.push(path); };
workspace.create = async (path, contents) => { await create!(path, contents); writes.push(path); };
return { workspace, writes };
}
test("a draft from an earlier version, without an image record, still loads", async () => {
const { workspace } = recorded();
const draft = new DescriptionDraft(workspace, "task");
workspace.files.set(draft.path, JSON.stringify({ schema: 1, body: `Old ${imageMarkdown("a.png", one)}` }) + "\n");
const reopened = new DescriptionDraft(workspace, "task");
assert.equal(await reopened.load(), `Old ${imageMarkdown("a.png", one)}`);
assert.deepEqual(await reopened.loadImages(), new Map());
await reopened.save("Newer text");
assert.equal(workspace.files.has(reopened.imagesPath), false, "A draft without images makes no image record");
});
test("the draft keeps the data of its unsaved images, and the image folder stays empty", async () => {
const { workspace, writes } = recorded();
const draft = new DescriptionDraft(workspace, "task");
await draft.loadImages();
const body = `Text\n${imageMarkdown("a.png", one)}`;
await draft.save(body, new Map([[one, data]]));
assert.deepEqual(writes, [draft.imagesPath, draft.path], "The image data comes before the reference");
assert.equal([...workspace.files.keys()].some(path => path.startsWith(".runestone/pm/images/")), false);
// A text change does not write the image data again.
await draft.save(`${body}\nMore`, new Map([[one, data]]));
assert.deepEqual(writes, [draft.imagesPath, draft.path, draft.path]);
const reopened = new DescriptionDraft(workspace, "task");
assert.equal(await reopened.load(), `${body}\nMore`);
assert.deepEqual(await reopened.loadImages(), new Map([[one, data]]));
// A later save writes the image file from the restored data.
assert.deepEqual(await saveImages(workspace, body, await reopened.loadImages()), [one]);
assert.match(workspace.files.get(imagePath(one))!, /data:image\/png;base64,aGVsbG8=/);
});
test("a removed image keeps its data until the text without the reference is saved", async () => {
const { workspace, writes } = recorded();
const draft = new DescriptionDraft(workspace, "task");
await draft.loadImages();
await draft.save(`${imageMarkdown("a.png", one)}\n${imageMarkdown("b.gif", two)}`, new Map([[one, data], [two, other]]));
writes.length = 0;
await draft.save(imageMarkdown("a.png", one), new Map([[one, data]]));
assert.deepEqual(writes, [draft.path, draft.imagesPath]);
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[one, data]]));
// An image that replaces another one: the record holds both images while the text changes.
writes.length = 0;
await draft.save(imageMarkdown("b.gif", two), new Map([[two, other]]));
assert.deepEqual(writes, [draft.imagesPath, draft.path, draft.imagesPath]);
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[two, other]]));
});
test("a discarded draft keeps no image data and writes no image file", async () => {
const { workspace, writes } = recorded();
const draft = new DescriptionDraft(workspace, "task");
await draft.loadImages();
await draft.save(imageMarkdown("a.png", one), new Map([[one, data]]));
writes.length = 0;
await draft.save(null, new Map([[one, data]]));
assert.deepEqual(writes, [draft.path, draft.imagesPath], "The text goes first, so that no saved reference loses its data");
assert.equal(await new DescriptionDraft(workspace, "task").load(), null);
assert.equal(workspace.files.get(draft.imagesPath), JSON.stringify({ schema: 1, images: {} }) + "\n");
assert.equal([...workspace.files.keys()].some(path => path.startsWith(".runestone/pm/images/")), false);
});
test("an invalid image record stops the draft, and a stale writer cannot overwrite the images", async () => {
const { workspace } = recorded();
const draft = new DescriptionDraft(workspace, "task");
for (const images of [null, [], { "../secret": data }, { [one]: "data:image/svg+xml;base64,PHN2Zz4=" }]) {
workspace.files.set(draft.imagesPath, JSON.stringify({ schema: 1, images }));
await assert.rejects(draft.loadImages(), /description draft is invalid/);
}
workspace.files.delete(draft.imagesPath);
const first = new DescriptionDraft(workspace, "task"), second = new DescriptionDraft(workspace, "task");
await first.loadImages();
await second.loadImages();
await first.save(imageMarkdown("a.png", one), new Map([[one, data]]));
await assert.rejects(second.save(imageMarkdown("b.gif", two), new Map([[two, other]])), /exists/);
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[one, data]]));
});
test("an image save includes extra IDs, for example a card cover, and returns the saved IDs", async () => {
const workspace = memoryWorkspace({ [privateRulesPath]: "*\n" });
const pending = new Map([[one, data], [two, other]]);
assert.deepEqual(await saveImages(workspace, "", pending, [], [two]), [two]);
assert.equal(workspace.files.has(imagePath(one)), false);
assert.equal(workspace.files.has(imagePath(two)), true);
});
+2 -85
View File
@@ -1,7 +1,7 @@
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView, splitWithContent, showInActivePane, paneOf, releaseSolePlugin, dropInPane, resizeDocumentPanes } from "../../../src/lib/workspace/documentPanes.ts"; import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView } from "../../../src/lib/workspace/documentPanes.ts";
import { paneBounds, splitDividers, splitSibling, stackLayout, setSplitRatio } from "../../../src/lib/workspace/splitLayout.ts"; import { paneBounds } from "../../../src/lib/workspace/splitLayout.ts";
import { registerSelection, selectedEditorText } from "../../../src/lib/editor/selection.ts"; import { registerSelection, selectedEditorText } from "../../../src/lib/editor/selection.ts";
test("opening a link to the right keeps its source and focuses an existing pane for duplicate targets", () => { test("opening a link to the right keeps its source and focuses an existing pane for duplicate targets", () => {
@@ -71,86 +71,3 @@ test("selection readers remain available in both panes and disposal cannot clear
assert.equal(selectedEditorText("b"), ""); assert.equal(selectedEditorText("b"), "");
replacement(); replacement();
}); });
test("a pane shows a document or a plugin view, and each tab has at most one pane", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b"], "a");
const primary = state.active;
state = splitWithContent(state, primary, { pluginKey: "browser" }, "web");
assert.deepEqual(state.panes.map(pane => [pane.documentId, pane.pluginKey]), [["a", null], [null, "browser"]]);
assert.equal(state.active, "web");
assert.equal(splitWithContent(state, primary, { pluginKey: "browser" }, "again"), selectPane(state, "web"));
// A document change does not remove the plugin pane.
assert.equal(syncDocumentPanes(state, ["a", "b"], null), state);
// A selected document replaces the view of the active pane. The view stays open as a tab.
const replaced = syncDocumentPanes(state, ["a", "b"], "b");
assert.deepEqual(replaced.panes.map(pane => [pane.documentId, pane.pluginKey]), [["a", null], ["b", null]]);
// A plugin view replaces the document of the active pane, and a shown document selects its pane.
state = showInActivePane(selectPane(replaced, primary), { pluginKey: "board" });
assert.deepEqual(state.panes.map(pane => [pane.documentId, pane.pluginKey]), [[null, "board"], ["b", null]]);
assert.equal(showInActivePane(state, { documentId: "b" }).active, "web");
assert.equal(paneOf(state, { pluginKey: "board" })?.id, primary);
});
test("a closed plugin view leaves its pane, and the last pane gives its plugin view back to the whole area", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a"], "a");
state = splitWithContent(state, state.active, { pluginKey: "browser" }, "web", "down");
assert.deepEqual(paneBounds(state.layout).web, { left: 0, top: 50, width: 100, height: 50 });
assert.deepEqual(paneBounds(stackLayout({ direction: "right", first: "x", second: "y" })).y, { left: 0, top: 50, width: 100, height: 50 });
const closed = syncDocumentPanes(state, ["a"], null, []);
assert.deepEqual(closed.panes.map(pane => pane.id), ["document-main"]);
const remaining = closeDocumentPane(state, "document-main");
assert.equal(remaining.active, "web");
const released = releaseSolePlugin(remaining);
assert.equal(released.pluginKey, "browser");
assert.deepEqual([released.state.panes[0].documentId, released.state.panes[0].pluginKey], [null, null]);
assert.equal(releaseSolePlugin(closed).state, closed);
});
test("the split sibling names the pane that a plugin view opened beside", () => {
const tree = { direction: "right" as const, first: "a", second: { direction: "down" as const, first: "b", second: "c" } };
assert.deepEqual(splitSibling(tree, "c"), { direction: "down", sibling: "b" });
assert.deepEqual(splitSibling(tree, "a"), { direction: "right", sibling: "b" });
assert.equal(splitSibling("a", "a"), null);
});
test("a divider changes the ratio of its split, within limits, and the narrow layout keeps the ratio", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b", "c"], "a");
state = splitDocumentPane(state, state.active, "b", "right");
state = splitWithContent(state, "right", { documentId: "c" }, "low", "down");
const dividers = splitDividers(state.layout);
assert.deepEqual(dividers.map(divider => [divider.path.join("/"), divider.direction, divider.ratio]), [["", "right", 0.5], ["second", "down", 0.5]]);
state = resizeDocumentPanes(state, [], 0.3);
state = resizeDocumentPanes(state, ["second"], 0.75);
const bounds = paneBounds(state.layout);
assert.equal(bounds["document-main"].width, 30);
assert.deepEqual(bounds.right, { left: 30, top: 0, width: 70, height: 75 });
assert.equal(bounds.low.top, 75);
assert.equal(paneBounds(stackLayout(state.layout))["document-main"].height, 30);
assert.equal(paneBounds(resizeDocumentPanes(state, [], 0.02).layout)["document-main"].width, 10, "A pane keeps a tenth of the split at least");
assert.equal(setSplitRatio("only", [], 0.4), "only");
assert.equal(resizeDocumentPanes(state, ["second", "first"], 0.4), state, "A path to a pane changes nothing");
});
test("a tab drop replaces the content of a pane or opens a pane beside it, and the content leaves its old pane", () => {
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b", "c"], "a");
const main = state.active;
state = splitWithContent(state, main, { pluginKey: "web" }, "right");
// A document dropped in the browser pane replaces the browser there. The browser stays open as a tab.
let next = dropInPane(state, { documentId: "b" }, "right", "center", "new");
assert.deepEqual(next.panes.map(pane => [pane.documentId, pane.pluginKey]), [["a", null], ["b", null]]);
assert.equal(next.active, "right");
// A drop on the bottom side of a pane opens a new pane there.
next = dropInPane(state, { documentId: "c" }, main, "down", "new");
assert.deepEqual(paneBounds(next.layout).new, { left: 0, top: 50, width: 50, height: 50 });
assert.equal(next.active, "new");
// A visible tab moves: its old pane closes.
next = dropInPane(state, { pluginKey: "web" }, main, "down", "new");
assert.deepEqual(next.panes.map(pane => [pane.id, pane.pluginKey]), [[main, null], ["new", "web"]]);
assert.deepEqual(paneBounds(next.layout).new, { left: 0, top: 50, width: 100, height: 50 });
next = dropInPane(state, { pluginKey: "web" }, main, "center", "new");
assert.deepEqual(next.panes.map(pane => pane.pluginKey), ["web"]);
// A drop on the pane that shows the content only makes it active.
assert.equal(dropInPane(state, { pluginKey: "web" }, "right", "down", "new").panes.length, 2);
assert.equal(dropInPane(state, { documentId: "a" }, "missing", "center", "new"), state);
});
+4 -6
View File
@@ -10,20 +10,18 @@ test("missing and damaged layouts use defaults", () => {
test("invalid layout fields do not discard valid collapsed states", () => { test("invalid layout fields do not discard valid collapsed states", () => {
for (const leftWidth of [0, -1, 159, 481, "260", null]) { for (const leftWidth of [0, -1, 159, 481, "260", null]) {
assert.deepEqual(parseWorkbenchLayout(JSON.stringify({ leftOpen: false, rightOpen: false, leftWidth, rightWidth: 320, leftView: "unknown", backlinksOpen: "false" })), { assert.deepEqual(parseWorkbenchLayout(JSON.stringify({ leftOpen: false, rightOpen: false, leftWidth, rightWidth: 320, leftView: "unknown" })), {
...DEFAULT_WORKBENCH_LAYOUT, leftOpen: false, rightOpen: false, rightWidth: 320, ...DEFAULT_WORKBENCH_LAYOUT, leftOpen: false, rightOpen: false, rightWidth: 320,
}); });
} }
assert.deepEqual(parseWorkbenchLayout('{"leftOpen":"false","rightOpen":0}'), DEFAULT_WORKBENCH_LAYOUT); assert.deepEqual(parseWorkbenchLayout('{"leftOpen":"false","rightOpen":0}'), DEFAULT_WORKBENCH_LAYOUT);
// A layout from an older version has no backlinks field. The section starts expanded.
assert.equal(parseWorkbenchLayout('{"leftOpen":false}').backlinksOpen, true);
}); });
test("layout survives storage round trips with hidden panels, all navigation views, and collapsed backlinks", () => { test("layout survives storage round trips with hidden panels and all navigation views", () => {
const store = new Map<string, string>(); const store = new Map<string, string>();
for (const leftView of ["files", "search", "bookmarks"] as const) { for (const leftView of ["files", "search", "bookmarks"] as const) {
for (const [leftWidth, backlinksOpen] of [[160, false], [321.5, true], [480, false]] as const) { for (const leftWidth of [160, 321.5, 480]) {
const layout = { leftOpen: false, rightOpen: false, leftWidth, rightWidth: 400, leftView, backlinksOpen }; const layout = { leftOpen: false, rightOpen: false, leftWidth, rightWidth: 400, leftView };
saveWorkbenchLayout({ setItem: (key, value) => { store.set(key, value); } }, layout); saveWorkbenchLayout({ setItem: (key, value) => { store.set(key, value); } }, layout);
assert.deepEqual(parseWorkbenchLayout(store.get(WORKBENCH_LAYOUT_KEY)!), layout); assert.deepEqual(parseWorkbenchLayout(store.get(WORKBENCH_LAYOUT_KEY)!), layout);
} }