Compare commits

..
3 Commits
Author SHA1 Message Date
Knotty Wyvern 1878bcfcf4 Set the version to 1.0.0a 2026-11-25 07:32:37 -07:00
Knotty Wyvern 1f3179facc Stop the settings write loop between windows
Two or more windows saved the appearance section to each other without end. The host stores object keys in alphabetical order. ThemeSync compared the stored value and the normalized value as JSON text, so a different key order started a new save in each window. Each save replaced settings.json, about 150 times each second. On a SATA SSD without a DRAM cache, these writes stalled all disk access for 6 to 8 seconds, about every 40 seconds.

- ThemeSync compares the two values with sameSettingsValue, which ignores the key order.
- The host skips a write when the section already holds the value, and sends no settings-changed event. This also stops a similar loop in another section.
- New tests: key order in sameSettingsValue, an appearance from the host that needs no new save, and an unchanged host write.
2026-11-25 07:32:37 -07:00
Knotty Wyvern b52eeb14a1 RuneStone 1.0.0 2026-11-16 04:21:21 -07:00
121 changed files with 3826 additions and 460 deletions
+2
View File
@@ -0,0 +1,2 @@
# Tauri writes these files with LF line endings on each build.
src-tauri/permissions/autogenerated/*.toml text eol=lf
+1
View File
@@ -5,6 +5,7 @@ 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.
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 public repository is `https://github.com/KnottyWyvern-GH/RuneStone`. Its releases page holds the installers, the browser engine ZIPs, and the SDK packages.
## Skills
+202
View File
@@ -0,0 +1,202 @@
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
@@ -0,0 +1,4 @@
RuneStone
Copyright 2026 Knotty Wyvern
This product includes third-party software. See THIRD_PARTY_NOTICES.md for its licenses.
+13 -14
View File
@@ -4,22 +4,17 @@ RuneStone is a desktop workspace for Markdown notes, code, and project work that
## Install and start
Download the installer for your computer.
On Windows 10 or 11 (x64):
| Platform | Installer | Status |
| --- | --- | --- |
| Windows 10 or 11, x64 | [RuneStone_0.1.51_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.51/RuneStone_0.1.51_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 |
1. Download [RuneStone_1.0.0_x64-setup.exe](https://github.com/KnottyWyvern-GH/RuneStone/releases/download/v1.0.0/RuneStone_1.0.0_x64-setup.exe).
2. Open the installer and complete setup.
3. Open RuneStone from the Start menu.
- **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.
You do not need developer tools.
On Windows, the built-in browser needs a separate engine download of about 160 MB. A browser tab offers it on first use.
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).
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
- Write Markdown with live formatting, editable tables, table formulas, images, and Mermaid diagrams.
@@ -27,7 +22,7 @@ For checksums, updates, and reinstalls, see [Installation and updates](docs/inst
- Find files, search a workspace, and resolve changes that other tools make to your files.
- 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**.
- Add optional plugins, such as CSV Viewer.
- Add optional plugins from plugin ZIP files.
## Find help
@@ -48,6 +43,10 @@ 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.
- 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
[kwyvern-gh](https://github.com/kwyvern-gh)
[KnottyWyvern-GH](https://github.com/KnottyWyvern-GH)
+1 -2
View File
@@ -1,7 +1,6 @@
# Third-party notices
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).
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).
| Package | Version | License | Source | Used by |
| --- | --- | --- | --- | --- |
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "runestone-browser",
"version": "0.1.8",
"version": "0.1.11",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "runestone-browser",
"version": "0.1.8",
"version": "0.1.11",
"dependencies": {
"@ghostery/adblocker": "2.18.2",
"ipaddr.js": "2.3.0"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "runestone-browser",
"version": "0.1.8",
"version": "0.1.11",
"private": true,
"description": "Isolated browser runtime included with RuneStone",
"type": "module",
+20
View File
@@ -5,7 +5,27 @@ import os from 'node:os';
import path from 'node:path';
import electron from 'electron';
const directory = await mkdtemp(path.join(os.tmpdir(), 'runestone-plugin-browser-'));
// A two-frame GIF that the server gives only one time, as some image hosts do.
const onceGif = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAACAkQBACH5BAAKAAAALAAAAAABAAEAAAICTAEAOw==', 'base64');
let onceGifServed = false;
// The same GIF with 7 MB of comment blocks, so that Copy image needs more than one part.
const comment = Buffer.concat([Buffer.from([255]), Buffer.alloc(255, 0x61)]);
const largeGif = Buffer.concat([onceGif.subarray(0, 32), Buffer.from([0x21, 0xfe]), ...Array(28_000).fill(comment), Buffer.from([0]), onceGif.subarray(32)]);
const server = http.createServer((req, res) => {
if (req.url === '/direct.gif') {
res.writeHead(200, { 'Content-Type': 'image/gif' });
return res.end(largeGif);
}
if (req.url === '/large.gif') {
res.writeHead(200, { 'Content-Type': 'image/gif' });
return res.end(largeGif);
}
if (req.url === '/once.gif') {
if (onceGifServed) { res.writeHead(200, { 'Content-Type': 'text/html' }); return res.end('Invalid request'); }
onceGifServed = true;
res.writeHead(200, { 'Content-Type': 'image/gif' });
return res.end(onceGif);
}
if (req.url === '/picture.png') {
res.writeHead(200, { 'Content-Type': 'image/png' });
return res.end(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII=', 'base64'));
+51 -2
View File
@@ -31,6 +31,31 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
pageFocusStates.set(wc, enabled);
if (enabled) wc.focus();
}
// The last image that Copy image took from a page. RuneStone gets it in parts when the user pastes.
let copied = null;
const COPIED_PART = 3_000_000;
// The page holds the encoded image. Its bytes keep all frames of a GIF, and the website gets no second request.
async function loadedImage(wc, url) {
if (!wc.debugger.isAttached()) { wc.debugger.attach('1.3'); pageFocusStates.delete(wc); }
await wc.debugger.sendCommand('Page.enable');
try {
const href = value => { try { return new URL(value).href; } catch { return ''; } };
const nodes = [(await wc.debugger.sendCommand('Page.getResourceTree')).frameTree];
for (const node of nodes) {
// An image that opens as the page itself is the main resource of its frame.
const page = href(node.frame.url) === url && /^image\//.test(node.frame.mimeType) ? node.frame : undefined;
const resource = page ?? node.resources?.find(item => item.type === 'Image' && href(item.url) === url);
if (resource) {
const { content, base64Encoded } = await wc.debugger.sendCommand('Page.getResourceContent', { frameId: node.frame.id, url: resource.url });
const data = Buffer.from(content, base64Encoded ? 'base64' : 'utf8');
const valid = /^image\/(?:gif|png|jpeg|webp|avif|bmp)$/.test(resource.mimeType) && data.length > 0 && data.length <= 20_000_000;
return valid ? { mime: resource.mimeType, data } : null;
}
nodes.push(...(node.childFrames ?? []));
}
return null;
} finally { await wc.debugger.sendCommand('Page.disable').catch(() => {}); }
}
function emulateViewport(item) {
if (!item.viewport) return;
const { width, height } = item.viewport, scale = item.scale;
@@ -141,7 +166,9 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
changed();
}
});
wc.on('did-navigate', (_event, url) => { store.visit(profileId, url, item.title); changed(); });
// Each new document gets a renderer widget without device emulation. A page that replaces itself before it finishes
// loading, as Google does, otherwise keeps a scale of 1 and grows when the next document finishes.
wc.on('did-navigate', (_event, url) => { emulateViewport(item); store.visit(profileId, url, item.title); changed(); });
wc.on('did-navigate-in-page', (_event, _url, main) => { if (main) { item.epoch++; agent.revokeAll(); } changed(); });
wc.on('page-title-updated', (_event, title) => { item.title = title.slice(0, 200); changed(); });
wc.on('page-favicon-updated', (_event, urls) => {
@@ -248,7 +275,13 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
switch (args.action) {
case 'copyLink': if (context.linkURL) clipboard.writeText(context.linkURL); break;
case 'copyImageAddress': if (context.srcURL) clipboard.writeText(context.srcURL); break;
case 'copyImage': if (context.hasImageContents) wc.copyImageAt(Math.round(context.x * current.scale), Math.round(context.y * current.scale)); break;
case 'copyImage': {
if (!context.hasImageContents) break;
wc.copyImageAt(Math.round(context.x * current.scale), Math.round(context.y * current.scale));
const image = context.srcURL ? await loadedImage(wc, context.srcURL).catch(() => null) : null;
copied = image && { token: randomUUID(), tabId: current.id, url: context.srcURL, ...image };
return copied && { copied: { token: copied.token, url: copied.url, mime: copied.mime, size: copied.data.length } };
}
case 'openExternal': if (context.linkURL) await openExternal(context.linkURL); break;
case 'saveImage': case 'saveLink': {
const url = args.action === 'saveImage' ? context.srcURL : context.linkURL;
@@ -259,6 +292,22 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
}
return null;
}
case 'linkAt': {
// A middle-click on a link opens it in a new tab. The isolated world keeps page scripts from changing the answer.
if (![args.x, args.y].every(value => Number.isInteger(value) && value >= 0 && value <= 5120)) throw new Error('Invalid pointer position.');
const href = await tab(args.tabId).view.webContents.executeJavaScriptInIsolatedWorld(902, [{
code: `document.elementFromPoint(${args.x}, ${args.y})?.closest('a[href], area[href]')?.href ?? ''`,
}]).catch(() => '');
try { return { url: href ? webUrl(href, { blank: false }) : null }; } catch { return { url: null }; }
}
case 'copiedImage': {
// A part stays below the line limit of the host connection.
if (!copied || copied.token !== args.token || copied.tabId !== args.tabId || !Number.isSafeInteger(args.offset) || args.offset < 0 || args.offset >= copied.data.length) {
throw new Error('The copied image is no longer available.');
}
const end = Math.min(copied.data.length, args.offset + COPIED_PART);
return { data: copied.data.subarray(args.offset, end).toString('base64'), next: end < copied.data.length ? end : null };
}
case 'input': {
const current = tab(args.tabId), wc = current.view.webContents;
const input = args.input;
+58
View File
@@ -124,6 +124,64 @@ app.whenReady().then(async () => {
await assert.rejects(engine.command('contextAction', { tabId: first, token: 'expired', action: 'saveImage' }), /no longer available/);
await wc.executeJavaScript('document.querySelector("#save-image").remove();true;');
passed.push('Unicode text, native image context menus, saved image bytes and stale menu protection work');
// Copy image keeps the bytes that the page loaded. The test server gives this GIF only one time.
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<img id="copy-image" src="${process.env.RS_TEST_URL}once.gif" style="position:absolute;left:400px;top:40px;width:80px;height:80px">');true;`);
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete'));
const menus = events.length;
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 440, y: 80, button: 'right' } });
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 440, y: 80, button: 'right' } });
await until(() => events.slice(menus).some(event => event.event === 'context-menu' && event.hasImageContents));
const imageMenu = events.findLast(event => event.event === 'context-menu');
const { copied } = await engine.command('contextAction', { tabId: first, token: imageMenu.token, action: 'copyImage' });
assert.deepEqual([copied.url, copied.mime, copied.size], [`${process.env.RS_TEST_URL}once.gif`, 'image/gif', 85]);
const part = await engine.command('copiedImage', { tabId: first, token: copied.token, offset: 0 });
const bytes = Buffer.from(part.data, 'base64');
assert.equal(bytes.subarray(0, 6).toString(), 'GIF89a');
assert.equal(bytes.length, 85);
assert.equal(part.next, null);
await assert.rejects(engine.command('copiedImage', { tabId: first, token: copied.token, offset: 85 }), /no longer available/);
await assert.rejects(engine.command('copiedImage', { tabId: 'other', token: copied.token, offset: 0 }), /no longer available/);
// A large image comes in parts that stay below the line limit of the host.
await wc.executeJavaScript(`document.querySelector("#copy-image").src = "${process.env.RS_TEST_URL}large.gif";true;`);
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete && document.querySelector("#copy-image").naturalWidth === 1'));
const largeMenus = events.length;
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 440, y: 80, button: 'right' } });
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 440, y: 80, button: 'right' } });
await until(() => events.slice(largeMenus).some(event => event.event === 'context-menu' && event.hasImageContents));
const large = (await engine.command('contextAction', { tabId: first, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
const parts = [];
for (let offset = 0; offset !== null;) {
const next = await engine.command('copiedImage', { tabId: first, token: large.token, offset });
assert.ok(next.data.length <= 4_000_000);
parts.push(Buffer.from(next.data, 'base64')); offset = next.next;
}
const whole = Buffer.concat(parts);
assert.ok(parts.length >= 3);
assert.equal(whole.length, large.size);
assert.equal(whole.subarray(0, 6).toString(), 'GIF89a');
assert.equal(whole.at(-1), 0x3b);
await wc.executeJavaScript('document.querySelector("#copy-image").remove();true;');
// A middle-click asks for the link under the pointer. Only web links count.
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<a id="middle-link" href="${process.env.RS_TEST_URL}linked" style="position:absolute;left:600px;top:40px;width:120px;height:30px;display:block">Linked</a><a id="script-link" href="javascript:void(0)" style="position:absolute;left:600px;top:100px;width:120px;height:30px;display:block">Script</a>');true;`);
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 650, y: 50 }), { url: `${process.env.RS_TEST_URL}linked` });
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 650, y: 110 }), { url: null });
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 900, y: 600 }), { url: null });
await assert.rejects(engine.command('linkAt', { tabId: first, x: -1, y: 50 }), /Invalid pointer position/);
await wc.executeJavaScript('document.querySelector("#middle-link").remove(); document.querySelector("#script-link").remove();true;');
// An image that opens as the page itself is the main resource of the tab.
const direct = (await engine.command('newTab', { url: `${process.env.RS_TEST_URL}direct.gif` })).tabId;
const directContents = engine.tabs.get(direct).view.webContents;
await until(async () => await directContents.executeJavaScript('document.images[0]?.complete === true').catch(() => false));
const box = await directContents.executeJavaScript('(({ x, y, width, height }) => ({ x: Math.floor(x + width / 2), y: Math.floor(y + height / 2) }))(document.images[0].getBoundingClientRect())');
const directMenus = events.length;
await engine.command('input', { tabId: direct, input: { type: 'mouseDown', ...box, button: 'right' } });
await engine.command('input', { tabId: direct, input: { type: 'mouseUp', ...box, button: 'right' } });
await until(() => events.slice(directMenus).some(event => event.event === 'context-menu' && event.tabId === direct && event.hasImageContents));
const directCopy = (await engine.command('contextAction', { tabId: direct, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
assert.deepEqual([directCopy.mime, directCopy.size], ['image/gif', large.size]);
await engine.command('closeTab', { tabId: direct });
passed.push('Copy image keeps the loaded GIF bytes without a second request, also for an image that opens as the page');
passed.push('A middle-click finds the web link under the pointer');
await until(async () => await wc.executeJavaScript("getComputedStyle(document.querySelector('.advertisement')).display") === 'none');
assert.equal(await wc.executeJavaScript('typeof window.adExecuted'), 'undefined');
passed.push('network and cosmetic ad blocking remain active');
+2 -1
View File
@@ -6,7 +6,8 @@ app.setPath('userData', process.env.RS_INTERACTION_ROOT);
app.on('window-all-closed', () => {});
app.whenReady().then(async () => {
let framePending = false;
const engine = await createEngine({ directory: process.env.RS_INTERACTION_ROOT, canEmitFrame: () => !framePending, emit: value => {
// The fixture server of the smoke test is on 127.0.0.1. The engine blocks local addresses for other hosts.
const engine = await createEngine({ directory: process.env.RS_INTERACTION_ROOT, allowedTestHosts: new Set(['127.0.0.1']), canEmitFrame: () => !framePending, emit: value => {
if (value.event === 'frame') framePending = true;
process.send?.({ event: value }, () => { if (value.event === 'frame') framePending = false; });
} });
+1 -1
View File
@@ -20,4 +20,4 @@ Build procedure: frozen pnpm install; Browser npm ci, checks, tests, engine test
Artifact: `releases/0.1.44/RuneStone_0.1.44_aarch64.dmg`. Logs and packaging scripts remain under `output/macos-installer-0.1.44/`.
Published alongside the existing Windows installer in the [Gitea 0.1.44 release](https://git.knottywyvern.com/kwyvern/RuneStone/releases/tag/v0.1.44), with `macos-release-notes.md` as a separate attachment. The existing release tag was retained.
Published alongside the existing Windows installer in the Gitea 0.1.44 release, with `macos-release-notes.md` as a separate attachment. The existing release tag was retained.
+2 -2
View File
@@ -37,7 +37,7 @@ Output:
The script prints `Installer available: <path>` when it completes.
After a successful build, the version fields keep the new version.
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`.
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`.
### 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.
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`.
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`.
`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.
-1
View File
@@ -1 +0,0 @@
313f15e68c3b3a6eec9fb223548c9843e6e87af5566885088ddbf7434742e100 RuneStone_0.1.44_amd64.deb
-1
View File
@@ -1 +0,0 @@
80ee6a5274c15333ac793d76b3b82164199e30344e6826218f593a7e842374f7 RuneStone_0.1.51_amd64.deb
+1
View File
@@ -0,0 +1 @@
72b17356fdb42a58051a84961e36fdd893ff26e210e7f855b8a96cde69ce946e 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.
The API does not include context sources, remote model servers, or credential storage.
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).
For tests, see `tests/unit/plugins/completion.spec.ts`.
+52 -1
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.
- 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.
- Replaces / replaced by: The left pane footer, and the ribbon rule "The ribbon has no width when it has no entries."
- 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.
- 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
@@ -1123,3 +1123,54 @@ 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.
- 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.
### 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 left, right, or bottom part of a pane opens a new pane there (left: card 156758f1). A hint shows the place of the drop. The tab that a pane shows can also go to the left, right, or bottom part of its own pane (card e0dc8473). The tab moves to the new pane. The old pane then shows the nearest tab that no pane shows: first the tabs after it, then the tabs before it. Below a plugin tab that covers the area, the old pane shows its document. Without such a tab, the drag shows no hint.
- 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/visibleTabDrag.smoke.mjs` (real mouse input), `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.
Update 2026-11-16: The user did not find a way to close a split without closing the tab. The **Close split** button showed only a close icon, so it looked like the close button of a tab. Now the button shows a split icon and its name (`src/lib/layout/CloseSplitButton.svelte`). In a pane of 420 pixels or less, it shows only the icon, and a tooltip gives the name. The tab menu also has **Close split** for a tab in a pane beside other panes. The tab stays open. Evidence: `tests/smoke/layout/visibleTabDrag.smoke.mjs`.
+3 -1
View File
@@ -16,7 +16,7 @@ This guide is for developers who change RuneStone's source code. To use the app,
### First run
1. Clone the repository: `https://git.knottywyvern.com/kwyvern/RuneStone`.
1. Clone the repository: `https://github.com/KnottyWyvern-GH/RuneStone.git`.
2. In the repository folder, run `pnpm install --frozen-lockfile`.
3. Prepare the browser runtime. See [Built-in browser runtime](#built-in-browser-runtime).
4. Run `pnpm tauri dev`.
@@ -232,6 +232,8 @@ 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.
- 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 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`.
- 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.
+5 -3
View File
@@ -10,6 +10,8 @@ This guide explains how to insert and edit images, read diagrams, edit Markdown
| --- | --- |
| Drag an image from the navigator into a Markdown editor | RuneStone inserts a relative link to the existing file. Press Escape to cancel the drag. |
| Drop an image from your system file manager, or paste an image | RuneStone copies the image into the workspace `attachments/` folder with a unique name, then inserts a link. |
| Paste an image that you copied with **Copy image** in the RuneStone browser | RuneStone saves the original file that the page loaded. A GIF keeps its animation, also from a website that refuses downloads. |
| Paste a GIF, WebP, or AVIF image that you copied in another web browser | That browser copies only the first frame. RuneStone downloads the original file from the image address, so the animation stays. If the website refuses the download, RuneStone saves the first frame and shows a message. |
Undo removes the inserted link. It keeps the image file.
@@ -22,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
**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 Split. It can fit the image or magnify it. Press Escape to close it.
Zoom works in Write, Read, and Read beside. It can fit the image or magnify it. Press Escape to close it.
## Read diagrams and document properties
Write, Read, and Split show wiki links, note callouts, and Mermaid diagrams.
Write, Read, and Read beside show wiki links, note callouts, and Mermaid diagrams.
RuneStone renders Mermaid diagrams locally. If a diagram is not valid, RuneStone shows an error message and the diagram source.
Read shows frontmatter in a collapsed **Properties** section.
@@ -95,7 +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 that take a range ignore text and blank cells. Arithmetic uses zero for a blank 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.
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.
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.
+7
View File
@@ -52,6 +52,7 @@ 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.
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.
### Card details
@@ -116,6 +117,12 @@ To add an image to a card, paste it or drop it into the description, or select *
Use a PNG, JPEG, GIF, or WebP image of at most 50 MiB.
To show an image on the board, add **Card cover** and choose one of the images of the card.
A web browser copies only the first frame of an image. When you paste a GIF or WebP image from a browser, RuneStone downloads the original file.
Then the animation stays.
Some websites refuse that download. Then the card gets the first frame, and RuneStone shows a message.
To keep the animation, use **Copy image** in the RuneStone browser. That copy keeps the original file that the page loaded.
**More actions** → **Customize background** sets an image behind the open board, or behind All tasks.
To show the Background slideshow on the boards, see [Choose where the background shows](themes.md#choose-where-the-background-shows).
+32 -34
View File
@@ -2,23 +2,32 @@
[RuneStone](../README.md) · [User guide](user-guide.md)
This guide installs, updates, or reinstalls RuneStone from a supplied release file.
This guide installs, updates, or reinstalls RuneStone from a release file or from a package that you build.
| Platform | Release file | Notes |
| --- | --- | --- |
| Windows 10 or 11, x64 | [RuneStone_0.1.51_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.51/RuneStone_0.1.51_x64-setup.exe) | Installs for the current Windows account |
| 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 | [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. |
| Windows 10 or 11, x64 | [RuneStone_1.0.0_x64-setup.exe](https://github.com/KnottyWyvern-GH/RuneStone/releases/download/v1.0.0/RuneStone_1.0.0_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. |
| Linux, amd64 | None | Build a Debian package from source. See [Build Linux packages](builds.md#build-linux-packages). |
You do not need Node.js, Rust, or a source checkout.
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).
On Windows, 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).
## Install on Windows
1. Save `RuneStone_0.1.51_x64-setup.exe` to Downloads.
2. Open the file.
3. Complete setup. Keep the default destination unless you need another location.
4. Open RuneStone from the Start menu.
1. Save `RuneStone_1.0.0_x64-setup.exe` and [windows-SHA256SUMS](https://github.com/KnottyWyvern-GH/RuneStone/raw/master/docs/checksums/1.0.0/windows-SHA256SUMS) to Downloads.
2. Open PowerShell in Downloads.
3. Check the download:
```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
@@ -33,41 +42,30 @@ After an update from 0.1.48 or earlier, a browser tab asks you to download the b
## Install on macOS
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.
Build the app on an Apple silicon Mac first. See [macOS packages](builds.md#macos-packages).
The app has an ad hoc signature and is not notarized by Apple.
If macOS blocks the first launch, open **System Settings → Privacy & Security** and choose **Open Anyway**.
1. Copy `RuneStone.app` from `src-tauri/target/release/bundle/macos/` into Applications.
2. Open RuneStone from Applications.
## Update or reinstall on macOS
1. Save your documents and quit RuneStone.
2. Open the disk image for the same or a newer version.
3. Drag RuneStone into Applications and confirm the replacement.
4. Eject the disk image.
5. Open RuneStone from Applications.
2. Build the same or a newer version.
3. Copy the new `RuneStone.app` into Applications and confirm the replacement.
4. Open RuneStone from Applications.
## Install on Linux
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.
3. Check the download:
Build the Debian package first. See [Build Linux packages](builds.md#build-linux-packages).
1. Open Terminal in the folder that contains the package.
2. Install the package. Use the file name of your build:
```bash
sha256sum --check linux-SHA256SUMS
sudo apt install ./RuneStone_1.0.0_amd64.deb
```
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.
3. 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.
@@ -77,4 +75,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.
3. Install the newer package with the same `sudo apt install ./<file>.deb` command.
To reinstall the same version, run `sudo apt install --reinstall ./RuneStone_0.1.51_amd64.deb`.
To reinstall the same version, run `sudo apt install --reinstall ./<file>.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.
```sh
pnpm add -D "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
pnpm add -D "https://github.com/KnottyWyvern-GH/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.
@@ -146,7 +146,7 @@ For the RuneStone source setup, see [Run from source](development.md#run-from-so
### Example: CSV Viewer
Source: [CSV Viewer repository](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer), its `package.json`, `plugin.json`, `scripts/build.mjs`, and `README.md`.
Source: the CSV Viewer repository, a private repository: its `package.json`, `plugin.json`, `scripts/build.mjs`, and `README.md`.
| Item | Value |
| --- | --- |
+1 -8
View File
@@ -2,7 +2,7 @@
[RuneStone](../README.md) · [User guide](user-guide.md)
This guide explains how to install, enable, update, and remove optional plugins such as CSV Viewer and Local Autocomplete.
This guide explains how to install, enable, update, and remove optional plugins.
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,13 +71,6 @@ 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.
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
| 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 RuneStone installers on the [RuneStone releases page](https://git.knottywyvern.com/kwyvern/RuneStone/releases). Browser engine ZIPs and SDK packages use the same page.
Publish RuneStone installers on the [RuneStone releases page](https://github.com/KnottyWyvern-GH/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).
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`.
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://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2`.
The folder URL is the download folder of the release, for example `https://github.com/KnottyWyvern-GH/RuneStone/releases/download/plugin-sdk-v0.1.2`.
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`.
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.
- 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.
- 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.
- 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)).
- 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.
- 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.
- 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 Split share the editor surface. CodeMirror layers stay transparent above it.
- Write, Source, Read, and Read beside share the editor surface. CodeMirror layers stay transparent above it.
- 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.
- 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.
+33 -8
View File
@@ -75,14 +75,14 @@ On macOS and Linux, you can still open, edit, rename, and delete existing files
## Edit documents
Each document pane has one view control with three choices, and a **Split** button:
Each document pane has one view control with three choices, and a **Read beside** button:
| Choice | Shows |
| --- | --- |
| **Write** | Formatted Markdown. The active line shows its Markdown source. |
| **Source** | The plain source with line numbers and syntax colors |
| **Read** | The rendered document, without editing. Markdown files only. |
| **Split** | Read beside Write or Source. Narrow panes stack the two views. Select **Split** again to close it. Markdown files only. |
| **Read beside** | Read beside Write or Source. Narrow panes stack the two views. Select **Read beside** 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**.
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.
- A workspace file link opens in a new tab and keeps the current document open.
- A heading link, such as `guide.md#save-your-work` or `#save-your-work`, scrolls to that heading.
- A 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 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.
- 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.
If backlinks look out of date, select **Rebuild note index**. Your Markdown files do not depend on this index.
@@ -136,15 +136,17 @@ Select a PDF file in the file tree. It opens in its own tab. The file tree marks
| Action | How |
| --- | --- |
| 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. |
| Zoom | Select **Zoom in** or **Zoom out**, from 25% to 400%. **Fit width** fits the page to the tab again. |
| Rotate | Select **Rotate clockwise**. Each click turns the page by 90 degrees. |
| 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. |
| 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**. 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 pages by 90 degrees. |
| 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. |
| 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.
- 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 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 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.
- If a PDF does not open, the tab shows the error. Select **Reload PDF**, or try another copy of the file.
@@ -182,6 +184,25 @@ 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.
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 left, right, or bottom part opens a new pane there. A hint shows the place before you release the tab.
You can also drag the tab that a pane shows to the left, right, or bottom part of that pane. The tab moves to the new pane, and the old pane shows the next tab that is not visible. This needs a second tab that is not visible.
- 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. To close the pane, select **Close split** in that bar. You can also right-click its tab and select **Close split**. 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
Auto-save is on by default. It saves changed files every 5 seconds, also in background tabs. RuneStone does not write unchanged files.
@@ -262,6 +283,10 @@ If a download fails, the tab shows the cause. Select **Retry** to start the down
Until the engine is installed, web links in your documents open in your system browser.
After a RuneStone update that needs a new engine, a browser tab offers **Update the engine**.
In a page, middle-click a link to open it in a new tab. Middle-click other content to scroll, then move the pointer in the direction to scroll.
Right-click an image for **Open image in new tab**, **Save image as…**, **Copy image**, and **Copy image address**.
**Copy image** keeps the original file. A GIF that you paste into a document or a card keeps its animation.
Use **Settings → Browser** to set the homepage and search engine, manage profiles, block ads, and clear cookies, cache, or history.
**Settings → Browser → Browser engine** shows the installed version. **Remove engine** frees the disk space. Your profiles, bookmarks, and history stay.
Each profile keeps its own cookies and bookmarks. Web bookmarks show in the Bookmarks pane.
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "runestone",
"version": "0.1.52",
"version": "1.0.0a",
"description": "Desktop editor for a local workspace",
"type": "module",
"scripts": {
@@ -25,7 +25,7 @@
"sdk:build": "node scripts/buildSdk.mjs",
"release:sdk": "node scripts/releaseSdk.mjs"
},
"license": "MIT",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
+9 -9
View File
@@ -1,6 +1,6 @@
# RuneStone Plugin SDK
`@runestone/plugin-sdk` gives TypeScript types and small helpers for [RuneStone](https://git.knottywyvern.com/kwyvern/RuneStone) plugins.
`@runestone/plugin-sdk` gives TypeScript types and small helpers for [RuneStone](https://github.com/KnottyWyvern-GH/RuneStone) plugins.
RuneStone is a desktop workspace for Markdown notes, code, and project work. Plugins add views, commands, and document editors to it.
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.
```sh
pnpm add -D "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
pnpm add -D "https://github.com/KnottyWyvern-GH/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
```
The result in `package.json`:
@@ -25,7 +25,7 @@ The result in `package.json`:
```json
{
"devDependencies": {
"@runestone/plugin-sdk": "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
"@runestone/plugin-sdk": "https://github.com/KnottyWyvern-GH/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.
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).
Then make the plugin ZIP. See [Build and package a plugin](https://github.com/KnottyWyvern-GH/RuneStone/blob/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.
@@ -128,12 +128,12 @@ A new SDK release can add types for new RuneStone features. Use the feature chec
## Documentation and help
- [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://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/completion.md)
- [Install and manage plugins](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugins.md)
- [Release policy](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/releases.md#sdk-releases)
- [Plugin development reference](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/plugin-development.md): the package format, the API, and the build procedure
- [Completion API](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/completion.md)
- [Install and manage plugins](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/plugins.md)
- [Release policy](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/releases.md#sdk-releases)
The SDK source is in the `packages/plugin-sdk` folder of the [RuneStone repository](https://git.knottywyvern.com/kwyvern/RuneStone). Report problems there.
The SDK source is in the `packages/plugin-sdk` folder of the [RuneStone repository](https://github.com/KnottyWyvern-GH/RuneStone). Report problems there.
Knotty Wyvern maintains RuneStone and the SDK.
+1
View File
@@ -22,6 +22,7 @@ export const actionIcons = {
puzzle: '<path d="M9 3H4v6a3 3 0 1 1 0 6v5h6a3 3 0 1 1 6 0h4v-6a3 3 0 1 0 0-6V3h-5a3 3 0 1 1-6 0Z"/>',
'split-right': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M12 4v16m3-11 3 3-3 3"/>',
'split-down': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 12h18m-12 3 3 3 3-3"/>',
'split-close': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="m7 9 3 3-3 3m10-6-3 3 3 3"/>',
kanban: '<rect x="3" y="4" width="5" height="16" rx="1"/><rect x="10" y="4" width="5" height="11" rx="1"/><rect x="17" y="4" width="4" height="7" rx="1"/>',
bookmark: '<path d="M6 4h12v16l-6-3-6 3z"/>',
'file-plus': '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M12 18v-6M9 15h6"/>',
+1 -1
View File
@@ -3130,7 +3130,7 @@ dependencies = [
[[package]]
name = "runestone"
version = "0.1.52"
version = "1.0.0+1"
dependencies = [
"base64 0.23.1",
"dunce",
+3 -2
View File
@@ -1,8 +1,9 @@
[package]
name = "runestone"
version = "0.1.52"
version = "1.0.0+1"
description = "Writing workspace plus script editor"
authors = ["Knotty Wyvern"]
license = "Apache-2.0"
edition = "2021"
[lib]
@@ -46,4 +47,4 @@ opt-level = 3
strip = true
[package.metadata.runestone]
version = "0.1.52"
version = "1.0.0a"
+4 -4
View File
@@ -1,11 +1,11 @@
{
"version": "0.1.8",
"version": "0.1.11",
"protocol": 1,
"platforms": {
"windows-x86_64": {
"url": "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/browser-engine-v0.1.8/RuneStone-Browser_0.1.8_win32-x64.zip",
"bytes": 163632595,
"sha256": "d704003bf5fe047b100a3cf0ab84f3321fd272510cf287a229e50d1653d0856b"
"url": "https://github.com/KnottyWyvern-GH/RuneStone/releases/download/browser-engine-v0.1.11/RuneStone-Browser_0.1.11_win32-x64.zip",
"bytes": 163623801,
"sha256": "1e0153b134cebe882b36f74e1f3c2a4ed37acb2caca10548034a8b5d88738d26"
}
}
}
+2
View File
@@ -71,6 +71,8 @@ fn main() {
"workspace_delete",
"workspace_read_data_url",
"workspace_write_bytes",
"workspace_save_image_url",
"workspace_download_image",
"workspace_copy",
"workspace_abs_path",
"workspace_reveal",
+2
View File
@@ -69,6 +69,8 @@
"allow-workspace-delete",
"allow-workspace-read-data-url",
"allow-workspace-write-bytes",
"allow-workspace-save-image-url",
"allow-workspace-download-image",
"allow-workspace-copy",
"allow-workspace-abs-path",
"allow-workspace-reveal",
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-download-image"
description = "Enables the workspace_download_image command without any pre-configured scope."
commands.allow = ["workspace_download_image"]
[[permission]]
identifier = "deny-workspace-download-image"
description = "Denies the workspace_download_image command without any pre-configured scope."
commands.deny = ["workspace_download_image"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-save-image-url"
description = "Enables the workspace_save_image_url command without any pre-configured scope."
commands.allow = ["workspace_save_image_url"]
[[permission]]
identifier = "deny-workspace-save-image-url"
description = "Denies the workspace_save_image_url command without any pre-configured scope."
commands.deny = ["workspace_save_image_url"]
+3 -1
View File
@@ -34,6 +34,8 @@ const COMMANDS: &[&str] = &[
"insertText",
"edit",
"contextAction",
"copiedImage",
"linkAt",
"frameAck",
"createProfile",
"renameProfile",
@@ -480,7 +482,7 @@ impl BrowserState {
let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id }));
return Ok(worker.routing.lock()?.snapshot(result, owner));
}
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "copiedImage", "linkAt", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
match worker.routing.lock()?.owners.get(id) {
Some(window) if window == owner => {},
+2
View File
@@ -107,6 +107,8 @@ pub fn run() {
workspace::workspace_delete,
workspace::workspace_read_data_url,
workspace::workspace_write_bytes,
workspace::workspace_save_image_url,
workspace::workspace_download_image,
workspace::workspace_copy,
workspace::workspace_abs_path,
workspace::workspace_reveal,
+46 -3
View File
@@ -2,7 +2,8 @@
//!
//! The file holds a `schema` number, a `revision` number, and one value for each section.
//! The host does not interpret the section values. The frontend normalizes them.
//! Every write replaces the complete file atomically and sends `settings-changed` to all windows.
//! A write that changes a section replaces the complete file atomically and sends `settings-changed` to all windows.
//! A write of the value that a section already holds changes nothing and sends no event.
//! Plugin settings stay in the app data folder (see `plugins.rs`).
use std::io;
@@ -178,6 +179,19 @@ impl Store {
Ok(Change { section: section.into(), revision: next, value })
}
/// Like `write`, but when the file already holds `value` in this section, the file stays as it is.
/// The change then has the current revision, and `false` tells the caller to send no event.
/// The compare ignores the key order of objects. Without this check, windows that save the same value
/// can start each other again without end, and each write replaces the file.
pub fn write_if_changed(&mut self, section: &str, value: Value) -> Result<(Change, bool)> {
check_section(section)?;
let loaded = self.load()?;
if loaded.exists && *loaded.document.get(section).unwrap_or(&Value::Null) == value {
return Ok((Change { section: section.into(), revision: revision(&loaded.document), value }, false));
}
Ok((self.write(section, value)?, true))
}
/// Write the first file from the migrated values. When a file exists, keep it and return it unchanged.
pub fn migrate(&mut self, sections: Map<String, Value>) -> Result<Snapshot> {
for name in sections.keys() { check_section(name)?; }
@@ -229,9 +243,9 @@ pub async fn settings_read(app: AppHandle) -> Result<Snapshot> {
#[tauri::command]
pub async fn settings_write(app: AppHandle, section: String, value: Value) -> Result<Change> {
let change = with_store(&app, move |store| store.write(&section, value)).await?;
let (change, saved) = with_store(&app, move |store| store.write_if_changed(&section, value)).await?;
// Every window shows the same preferences, so the change goes to all of them.
let _ = app.emit(CHANGED_EVENT, &change);
if saved { let _ = app.emit(CHANGED_EVENT, &change); }
Ok(change)
}
@@ -292,6 +306,35 @@ mod tests {
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_write_of_the_stored_value_keeps_the_file_and_the_revision() {
let (dir, path) = fixture("unchanged");
let mut store = Store::new(path.clone());
// A missing file gets created, also for a value that matches the empty default.
let (created, saved) = store.write_if_changed("language", Value::Null).unwrap();
assert!(saved);
assert_eq!(created.revision, 1);
let (first, saved) = store.write_if_changed("appearance", json!({ "theme": "harvest-moon", "mode": "dark", "transparency": { "enabled": true, "amount": 18 } })).unwrap();
assert!(saved);
assert_eq!(first.revision, 2);
let before = fs::read(&path).unwrap();
// The same value in a different key order changes nothing.
let (again, saved) = store.write_if_changed("appearance", json!({ "transparency": { "amount": 18, "enabled": true }, "mode": "dark", "theme": "harvest-moon" })).unwrap();
assert!(!saved, "No save and no event");
assert_eq!(again.revision, 2);
assert_eq!(fs::read(&path).unwrap(), before, "The file stays as it is");
// A missing section and `null` are the same.
assert!(!store.write_if_changed("terminal", Value::Null).unwrap().1);
// A different value saves as usual.
let (changed, saved) = store.write_if_changed("appearance", json!({ "theme": "harvest-moon", "mode": "light" })).unwrap();
assert!(saved);
assert_eq!(changed.revision, 3);
assert_eq!(on_disk(&path)["appearance"], json!({ "mode": "light", "theme": "harvest-moon" }));
assert!(store.write_if_changed("plugins", json!({})).is_err(), "Unknown sections stay refused");
assert_eq!(files(&dir), vec![FILE_NAME.to_owned()], "No temporary files remain");
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn writes_reject_unknown_sections_and_values_above_the_limit() {
let (dir, path) = fixture("limits");
+152 -2
View File
@@ -967,10 +967,14 @@ fn read_data_url(root: &Path, rel: &str) -> Result<String> {
}
let bytes = fsutil::read_to_limit(file, MAX_IMAGE_BYTES as u64)?
.ok_or_else(|| Error::new("image is too large"))?;
Ok(format!(
Ok(data_url(mime, &bytes))
}
fn data_url(mime: &str, bytes: &[u8]) -> String {
format!(
"data:{mime};base64,{}",
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes)
))
)
}
fn copy_destination(path: &Path, number: u32) -> PathBuf {
@@ -1244,6 +1248,108 @@ fn write_image(root: &Path, rel: &str, base64: &str) -> Result<()> {
fsutil::write_bytes(&path, &bytes)
}
/// Save the original of an image that a web page copied. The clipboard has only a still copy,
/// so an animated GIF needs its source file. `rel` has no extension. The format of the
/// downloaded file sets it. Returns the path of the new file.
#[tauri::command]
pub async fn workspace_save_image_url(
window: tauri::Window,
state: State<'_, WorkspaceState>,
url: String,
rel: String,
) -> Result<String> {
let root = current_root(&state, window.label())?;
blocking(move || {
let bytes = download_image(&url)?;
save_image(&root, &rel, &bytes)
})
.await
}
/// Download a web image and return it as a data URL. Project Management keeps card images
/// as data URLs, so this gives a card the original of a copied image.
#[tauri::command]
pub async fn workspace_download_image(url: String) -> Result<String> {
blocking(move || image_data_url(&download_image(&url)?)).await
}
fn image_data_url(bytes: &[u8]) -> Result<String> {
let extension = image_extension(bytes).ok_or_else(|| Error::new("file is not an image"))?;
let mime = mime_from_path(Path::new(&format!("image.{extension}")))
.ok_or_else(|| Error::new("file is not an image"))?;
Ok(data_url(mime, bytes))
}
fn download_image(url: &str) -> Result<Vec<u8>> {
use std::io::Read;
let web = |url: &reqwest::Url| matches!(url.scheme(), "http" | "https");
let url = reqwest::Url::parse(url).map_err(|_| Error::new("invalid image address"))?;
if !web(&url) {
return Err(Error::new("image address is not http or https"));
}
let client = reqwest::blocking::Client::builder()
.user_agent(concat!("RuneStone/", env!("CARGO_PKG_VERSION")))
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(30))
.redirect(reqwest::redirect::Policy::custom(move |attempt| {
if attempt.previous().len() >= 5 || !web(attempt.url()) {
attempt.stop()
} else {
attempt.follow()
}
}))
.build()
.map_err(Error::from_display)?;
let response = client.get(url).send().map_err(Error::from_display)?;
if !response.status().is_success() {
return Err(Error::new(format!("image server answered {}", response.status())));
}
let mut bytes = Vec::new();
response.take(MAX_IMAGE_BYTES as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > MAX_IMAGE_BYTES {
return Err(Error::new("image is too large"));
}
Ok(bytes)
}
fn save_image(root: &Path, rel: &str, bytes: &[u8]) -> Result<String> {
let extension = image_extension(bytes).ok_or_else(|| Error::new("file is not an image"))?;
let rel = format!("{rel}.{extension}");
let path = resolve_for_write(root, &rel)?;
check_new_components(root, &rel)?;
if path.exists() {
return Err(Error::new("a file with that name already exists"));
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fsutil::write_bytes(&path, bytes)?;
Ok(rel)
}
/// The extension of a raster image format from its first bytes. A web server can send a
/// wrong type, and an SVG file can contain scripts, so the type header and SVG do not count.
fn image_extension(bytes: &[u8]) -> Option<&'static str> {
let at = |start: usize, value: &[u8]| bytes.get(start..start + value.len()) == Some(value);
if at(0, b"GIF87a") || at(0, b"GIF89a") {
Some("gif")
} else if at(0, b"\x89PNG\r\n\x1a\n") {
Some("png")
} else if at(0, b"\xff\xd8\xff") {
Some("jpg")
} else if at(0, b"RIFF") && at(8, b"WEBP") {
Some("webp")
} else if at(4, b"ftypavif") || at(4, b"ftypavis") {
Some("avif")
} else if at(0, b"BM") {
Some("bmp")
} else if at(0, b"\0\0\x01\0") {
Some("ico")
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1598,6 +1704,50 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn image_formats_come_from_the_file_contents() {
assert_eq!(image_extension(b"GIF89a\x01\0"), Some("gif"));
assert_eq!(image_extension(b"GIF87a"), Some("gif"));
assert_eq!(image_extension(b"\x89PNG\r\n\x1a\n\0"), Some("png"));
assert_eq!(image_extension(b"\xff\xd8\xff\xe0"), Some("jpg"));
assert_eq!(image_extension(b"RIFF\0\0\0\0WEBPVP8 "), Some("webp"));
assert_eq!(image_extension(b"\0\0\0\x1cftypavif"), Some("avif"));
assert_eq!(image_extension(b"BM\0\0"), Some("bmp"));
assert_eq!(image_extension(b"\0\0\x01\0\x01\0"), Some("ico"));
assert_eq!(image_extension(b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"), None);
assert_eq!(image_extension(b"<!doctype html>"), None);
assert_eq!(image_extension(b"RIFF"), None);
assert_eq!(image_extension(b""), None);
}
#[test]
fn web_images_keep_their_original_format() {
let root = workspace_fixture("image-url");
let gif = b"GIF89a\x01\0\x01\0\0\0\0;".to_vec();
let (base, server) = crate::plugin_sources::tests::server(vec![
("302 Found\r\nLocation: /cat.gif".into(), Vec::new()),
("200 OK\r\nContent-Type: image/png".into(), gif.clone()),
("200 OK\r\nContent-Type: image/gif".into(), b"<!doctype html>".to_vec()),
("404 Not Found".into(), Vec::new()),
]);
let bytes = download_image(&format!("{base}/image")).unwrap();
assert_eq!(save_image(&root, "attachments/pasted", &bytes).unwrap(), "attachments/pasted.gif");
assert_eq!(fs::read(root.join("attachments/pasted.gif")).unwrap(), gif);
assert_eq!(image_data_url(&bytes).unwrap(), "data:image/gif;base64,R0lGODlhAQABAAAAADs=");
let page = download_image(&format!("{base}/page")).unwrap();
assert_eq!(save_image(&root, "attachments/page", &page).unwrap_err().to_string(), "file is not an image");
assert_eq!(image_data_url(&page).unwrap_err().to_string(), "file is not an image");
assert_eq!(image_data_url(b"\xff\xd8\xff\xe0").unwrap(), "data:image/jpeg;base64,/9j/4A==");
assert!(download_image(&format!("{base}/missing")).unwrap_err().to_string().contains("404"));
let requests = server.join().unwrap();
assert!(requests[1].starts_with("GET /cat.gif "));
assert!(download_image("file:///C:/cat.gif").is_err());
assert!(save_image(&root, "attachments/pasted", &gif).is_err(), "an existing file stays");
assert!(save_image(&root, "../outside", &gif).is_err());
assert_eq!(names(&root.join("attachments")), ["pasted.gif"]);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn permanent_delete_removes_files_and_folders_but_never_the_root() {
let root = workspace_fixture("delete");
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "RuneStone",
"version": "0.1.52",
"version": "1.0.0+1",
"identifier": "com.runestone.app",
"build": {
"beforeDevCommand": "pnpm dev",
+40 -7
View File
@@ -11,6 +11,7 @@
import { TabSession, type TabStatus } from './tabSession';
import { engine } from './engine';
import { AutoScroll } from './autoScroll';
import { keepCopiedImage } from '$lib/workspace/copiedImage';
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string, url?: string) => Promise<void> } = $props();
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: $t('Opening browser…') });
const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); });
@@ -43,7 +44,7 @@
let scrollAnchor = $state<{ x: number; y: number } | null>(null);
let scrollFrame = 0, moveFrame = 0, movePending = false;
let pendingMove: Record<string, unknown> | undefined;
let suppressedRelease = -1;
let suppressedRelease = -1, middlePressed = false;
const result = $derived(current?.find?.text === findText ? current.find : null);
const documentKey = $derived(`${tabId}:${current?.url}:${!!current?.loading}`);
$effect(() => {
@@ -116,8 +117,9 @@
{ label: $t('Copy link address'), icon: 'copy', run: action('copyLink') },
{ label: $t('Save link as…'), icon: 'save', run: action('saveLink') }, { separator: true });
if (context.hasImageContents) items.push(
{ label: $t('Open image in new tab'), icon: 'file-plus', disabled: !context.srcURL, run: () => void newTab(current?.profileId || 'user', context.srcURL) },
{ label: $t('Save image as…'), icon: 'save', disabled: !context.srcURL, run: action('saveImage') },
{ label: $t('Copy image'), icon: 'copy', run: action('copyImage') },
{ label: $t('Copy image'), icon: 'copy', run: () => copyImage(context) },
{ label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
if (context.isEditable) items.push(
{ label: $t('Undo'), icon: 'undo', shortcut: keys('Mod+Z'), disabled: !context.editFlags.canUndo, run: edit('undo') },
@@ -142,6 +144,23 @@
if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; });
await connection.send(command, args);
}
// A paste of a copied image uses the bytes that the page loaded. The engine gives them in parts.
// A paste can come before the reply, so the copy is known at once by its address.
function copyImage(context: PageMenu) {
const owner = tabId;
const data = (async () => {
const reply = await connection.send('contextAction', { token: context.token, action: 'copyImage' }) as { copied?: { token: string; mime: string } } | null | undefined;
const copied = reply?.copied;
if (!copied) return undefined;
let data = '';
for (let offset: number | null = 0; offset !== null;) {
const part: { data: string; next: number | null } = await request('copiedImage', { tabId: owner, token: copied.token, offset });
data += part.data; offset = part.next;
}
return `data:${copied.mime};base64,${data}`;
})().catch(() => undefined);
if (context.srcURL) keepCopiedImage(context.srcURL, data);
}
async function openTab(profileId = current?.profileId || $browserState?.profiles[0]?.id || 'user') {
if (opening) return;
opening = true;
@@ -194,23 +213,37 @@
if (mounted && pendingMove) moveFrame = requestAnimationFrame(flushMove);
});
}
// The frame has the CSS size of the page viewport. A surface point less the frame offset is the same page point.
function pagePoint(point: { x: number; y: number }) {
return { x: Math.max(0, Math.min(width - 1, Math.round(point.x - imageBox.x))), y: Math.max(0, Math.min(height - 1, Math.round(point.y - imageBox.y))) };
}
// A middle-click starts scrolling at once. On a link, it stops the scroll and opens the link in a new tab.
async function openLinkAt(input: { x: number; y: number }) {
const owner = tabId;
const found = await request<{ url: string | null }>('linkAt', { tabId: owner, ...input }).catch(() => null);
if (!found?.url || owner !== tabId || !autoScroll.anchor) return;
stopScroll();
if (middlePressed) suppressedRelease = 1;
void newTab(current?.profileId || 'user', found.url);
}
function pointer(event: MouseEvent | WheelEvent, type: string) {
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') textInput.focus({ preventScroll: true });
const rect = surface.getBoundingClientRect();
const point = { x: event.clientX - rect.left, y: event.clientY - rect.top };
if (event.button === 1) middlePressed = type === 'mouseDown';
if (type === 'mouseUp' && event.button === suppressedRelease) { suppressedRelease = -1; return; }
if (type === 'mouseDown' && autoScroll.anchor) { suppressedRelease = event.button; stopScroll(); return; }
if (type === 'mouseDown' && event.button === 1 && ready) {
pendingMove = undefined; cancelAnimationFrame(moveFrame); moveFrame = 0;
autoScroll.start(point); scrollAnchor = point; scrollFrame = requestAnimationFrame(scrollStep); return;
autoScroll.start(point); scrollAnchor = point; scrollFrame = requestAnimationFrame(scrollStep);
void openLinkAt(pagePoint(point)); return;
}
if (autoScroll.anchor) {
if (type === 'mouseMove') autoScroll.move(point);
if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); }
if (type === 'mouseWheel') stopScroll(); else return;
}
// The frame has the CSS size of the page viewport. A surface point less the frame offset is the same page point.
const input = { type, x: Math.max(0, Math.min(width - 1, Math.round(point.x - imageBox.x))), y: Math.max(0, Math.min(height - 1, Math.round(point.y - imageBox.y))),
const input = { type, ...pagePoint(point),
button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event),
...('deltaY' in event ? { deltaY: -event.deltaY * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? height : 1), deltaX: -event.deltaX * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? width : 1) } : {}) };
if (type === 'mouseWheel') { wheels.push(input as Parameters<WheelQueue['push']>[0]); return; }
@@ -286,7 +319,7 @@
oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
onblur={stopScroll}></textarea>
{#if image && ready && !blank}<img src={image} class:exact={imageBox.exact} style:width={`${imageBox.width}px`} style:height={`${imageBox.height}px`} style:transform={`translate(${imageBox.x}px, ${imageBox.y}px)`} alt={$t("Web page rendered by the browser")} draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true"><Icon icon="scroll" /></span>{/if}
</div>
</div>
<style>
@@ -298,7 +331,7 @@
input{flex:1}.profile-choice{max-width:160px;display:flex;align-items:center;gap:var(--rs-menu-icon-gap);cursor:pointer}input:focus-visible,.profile-choice:focus-visible{outline:2px solid var(--rs-focus)}
.surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)}
.browser.blank,.blank .surface{background:transparent}
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);font-size:20px;pointer-events:none;box-shadow:0 1px 4px #0006}
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:26px;height:26px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);pointer-events:none;box-shadow:0 1px 4px #0006}.scroll-anchor :global(svg){width:20px;height:20px;flex-basis:20px}
img{display:block;pointer-events:none;user-select:none;will-change:transform}img.exact{image-rendering:pixelated}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px}
.error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)}
.reconnect{padding:6px 12px;margin:4px 0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);cursor:pointer}
+4 -3
View File
@@ -47,9 +47,10 @@ export async function activate(api: PluginApi) {
const id = `tab-${crypto.randomUUID()}`;
const saved: SavedView = { view: id, profileId, url, runtimeId: '' };
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 current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
void open(current?.profileId || saved.profileId, current?.url || saved.url || 'about:blank', { split: direction, relativeTo: id });
void open(current?.profileId || saved.profileId, undefined, { split: direction, relativeTo: id });
};
api.registerView({ id, title: 'Browser', placement: 'editor', icon: 'globe', pinned, launcher: false,
tabDragData: ({ pinned }) => {
@@ -65,8 +66,8 @@ export async function activate(api: PluginApi) {
return [
{ separator: true },
{ label: tr("Move to new window"), icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
{ label: tr("Split right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
{ label: tr("Split down"), icon: 'split-down', disabled: !ready, run: () => split('down') },
{ label: tr("New tab to the right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
{ label: tr("New tab below"), icon: 'split-down', disabled: !ready, run: () => split('down') },
{ separator: true },
{ 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') },
+4 -2
View File
@@ -75,12 +75,14 @@ export class TabSession {
}
}
}
async send(command: string, args: Record<string, unknown> = {}) {
/** Returns the reply of the engine, or undefined when the request did not complete. */
async send(command: string, args: Record<string, unknown> = {}): Promise<unknown> {
if (this.closed || this.value.phase !== 'ready') return;
const tabId = this.value.tabId;
try {
await this.transport(command, { ...args, tabId });
const reply = await this.transport(command, { ...args, tabId });
if (tabId === this.value.tabId && this.value.phase === 'ready' && !['input', 'resize', 'visible'].includes(command) && this.value.message) this.update({ message: '' });
return reply;
} catch (error) {
// Replies from the previous connection cannot replace the current error.
if (this.closed || tabId !== this.value.tabId || this.value.phase !== 'ready') return;
+20 -8
View File
@@ -13,9 +13,11 @@
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
import { linkCandidates } from "$lib/workspace/markdownLinks";
import { documentHeadings } from "$lib/workspace/headingLinks";
import { editImageSource, imageSource } from "./imageSource";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle } from "$lib/workspace/media";
import { loadImageSize } from "$lib/workspace/imageSizes";
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle, pastedImageSource } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { savedEditor, saveEditor } from "./editorStates";
@@ -48,7 +50,7 @@
onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
onInsertImage?: (file: File, source?: string) => Promise<string | null>;
focusLine?: number | null;
/** The line and the column of the cursor, from 1. */
onSelectionLine?: (line: number, column: number) => void;
@@ -99,7 +101,12 @@
let decoded = source;
try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ }
for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) {
try { urls.set(source, await workspaceReadDataUrl(candidate)); return; } catch { /* Try attachment location. */ }
try {
const url = await workspaceReadDataUrl(candidate);
await loadImageSize(url);
urls.set(source, url);
return;
} catch { /* Try attachment location. */ }
}
})();
loading.set(source, task);
@@ -126,10 +133,12 @@
event.preventDefault();
event.stopPropagation();
const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null;
await importImages(view, files, position);
// Read the HTML now. The clipboard data is empty after the paste event.
const source = event instanceof ClipboardEvent && files.length === 1 ? pastedImageSource(data?.getData("text/html") ?? "") : undefined;
await importImages(view, files, position, undefined, source);
}
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string) {
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string, source?: string) {
const range = position === null ? view.state.selection.main : { from: position, to: position };
const id = Symbol(), path = buffer.relPath;
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
@@ -137,7 +146,7 @@
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
for (const file of files) {
if (editor !== view) return;
const snippet = await onInsertImage?.(file);
const snippet = await onInsertImage?.(file, source);
if (snippet) snippets.push(snippet);
}
if (editor !== view || !snippets.length) return;
@@ -432,8 +441,11 @@
const view = editor;
if (!view || line == null) return;
untrack(() => {
const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from;
const effects = [EditorView.scrollIntoView(anchor, { y: "center" })];
const number = Math.min(view.state.doc.lines, Math.max(1, line));
const anchor = view.state.doc.line(number).from;
// 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 })); });
view.dispatch({ selection: { anchor }, effects });
view.focus();
+9
View File
@@ -5,6 +5,7 @@ import { attachTooltip } from "../ui/tooltip";
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
import type { ActionMenuItem } from "../ui/actionMenu";
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
import { imageSize, rememberImageSize } from "../workspace/imageSizes";
export type ImageActions = {
edit?: () => void;
@@ -56,6 +57,8 @@ function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
viewport.className = "image-lightbox-viewport";
const image = original.cloneNode() as HTMLImageElement;
image.removeAttribute("loading");
image.removeAttribute("width");
image.removeAttribute("height");
image.draggable = false;
let scale = 0;
const status = document.createElement("span");
@@ -91,6 +94,12 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
const cleanup: (() => void)[] = [];
for (const image of root.querySelectorAll<HTMLImageElement>("img[data-md-src]")) {
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");
frame.className = "md-image-frame";
frame.contentEditable = "false";
+2
View File
@@ -5,6 +5,7 @@ import { imageControls, type ImageActions } from "./imageControls";
import { editImageSource } from "./imageSource";
import { requestText } from "../workspace/dialogs.svelte";
import { isRemoteImage } from "../workspace/media";
import { estimatedImageHeight } from "../workspace/imageSizes";
import { actionIcon } from "../ui/actionIcons";
export type ImageContext = {
@@ -18,6 +19,7 @@ const cleanups = new WeakMap<HTMLElement, () => void>();
export class ImagePreview extends WidgetType {
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; }
get estimatedHeight() { return estimatedImageHeight(this.html); }
toDOM(view: EditorView) {
const dom = document.createElement(this.block ? "div" : "span");
dom.className = `reading writer-preview ${this.block ? "writer-image" : "writer-image-inline"}`;
+124 -13
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. */
const linkTooltip = () => tr("{modifier}+click to open link", { modifier: isMac() ? "⌘" : "Ctrl" });
import { EditorSelection, StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
import { renderMarkdownSections } from "../workspace/noteHtml";
import { renderDiagrams } from "../workspace/diagrams";
@@ -22,9 +22,34 @@ import { listLabels } from "./markdownLists";
import { activeTableFormulas } from "../formulas/index.ts";
const previewFormulas = new WeakMap<HTMLElement, unknown>();
const previewHtml = new WeakMap<HTMLElement, string>();
export const refreshImages = StateEffect.define<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 attached = new Map<HTMLElement, () => void>();
const refresh = () => {
@@ -119,23 +144,35 @@ class ListLabel extends WidgetType {
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 {
readonly formulas = activeTableFormulas();
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) { super(); }
get estimatedHeight() { return this.height.value; }
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; }
measure(dom: HTMLElement, view: EditorView) {
view.requestMeasure({ key: this.height, read: () => dom.offsetHeight, write: height => { this.height.value = height; } });
readonly estimate: number;
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) {
super();
this.estimate = measuredHeights.get(html)?.height ?? -1;
}
updateDOM(dom: HTMLElement, view: EditorView) {
if (previewFormulas.get(dom) !== this.formulas || tableEditors.get(dom)?.source !== this.source) return false;
this.measure(dom, view);
get estimatedHeight() { return this.height.value >= 0 ? this.height.value : this.estimate; }
// A new estimate must reach the height map of CodeMirror. updateDOM keeps the drawn table.
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible && other.estimate === this.estimate; }
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;
}
destroy(dom: HTMLElement) { tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
destroy(dom: HTMLElement) { previewSizes?.unobserve(dom); tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
toDOM(view: EditorView) {
const dom = document.createElement("div");
previewFormulas.set(dom, this.formulas);
previewHtml.set(dom, this.html);
dom.className = "reading writer-preview";
dom.innerHTML = this.html;
// Widgets handle their own events, so CodeMirror's link handler cannot run.
@@ -153,7 +190,7 @@ class Preview extends WidgetType {
}, { capture: true });
tableControls(dom, view, this.source, this.actions);
imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); }));
this.measure(dom, view);
watchPreviewHeight(dom, this.height);
dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove());
dom.addEventListener("mousedown", event => {
if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return;
@@ -174,6 +211,45 @@ class Preview extends WidgetType {
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 = {}) {
const selecting = StateEffect.define<boolean>();
const mouseSelecting = StateField.define({
@@ -256,7 +332,10 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to);
for (let number = 1; number <= state.doc.lines; number++) {
const line = state.doc.line(number);
if (!line.text.trim() && !hidden(line.from, line.to)) ranges.push(Decoration.line({ class: "writer-blank" }).range(line.from));
if (!line.text.trim() && !hidden(line.from, line.to)) {
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 mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); };
@@ -274,6 +353,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
for (let number = first.number; number <= last.number; 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));
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
}
return false;
}
@@ -283,6 +363,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
const pendingList = node.name === "SetextHeading2" && state.doc.lineAt(node.to).text.trim() === "-";
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name) && !pendingList) {
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
if (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 === "TaskMarker") {
@@ -366,6 +447,36 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
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 finish = () => {
if (!view.state.field(mouseSelecting)) return;
@@ -400,6 +511,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
window.removeEventListener("blur", finish);
} };
});
return [imageSource, linkTooltips, bodyFocused, mouseSelecting, decorations, mousePreview, syncBodyFocus,
return [imageSource, linkTooltips, bodyFocused, mouseSelecting, decorations, previewMeasuring, mousePreview, syncBodyFocus,
EditorView.focusChangeEffect.of((_state, focusing) => focusBody.of(focusing))];
}
+17 -1
View File
@@ -1,10 +1,18 @@
import { SearchQuery } from "@codemirror/search";
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. */
export function readingSearch(root: HTMLElement, close: () => void, options: { includeButtons?: boolean; focusOnClose?: () => void } = {}): FindTarget {
let query = new SearchQuery({ search: "" });
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() {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
const nodes: { node: Text; from: number; to: number }[] = [];
@@ -40,7 +48,15 @@ export function readingSearch(root: HTMLElement, close: () => void, options: { i
}
return {
get query() { return query; }, readOnly: true, canSelectAll: false,
setQuery(value) { if (query.eq(value)) return; query = value; current = -1; window.getSelection()?.removeAllRanges(); },
setQuery(value) { if (query.eq(value)) return; query = value; current = -1; if (matchSelected()) 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() {},
close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); },
};
+7
View File
@@ -451,6 +451,13 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
event.preventDefault(); activate(cell);
const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY });
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();
+181 -70
View File
@@ -1,28 +1,32 @@
<script lang="ts">
// One PDF tab: the toolbar, the status line, the password form, and one page with its text layer.
// One PDF tab: the toolbar, the status line, the password form, and all pages in one column that scrolls.
// 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.
import { onMount } from "svelte";
import { flushSync, onMount } from "svelte";
import { message, t } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte";
import type { PluginDocumentContext } from "$lib/plugins/sdk";
import { openPdf, TextLayer, type OpenPdf, type PDFDocumentProxy, type RenderTask } from "./engine";
import { MAX_ZOOM, MIN_ZOOM, RESIZE_SETTLE_MS, ZOOM_STEP, nextRotation, outputScale, pageNumber, zoomLevel } from "./model";
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";
let { file, readBytes }: { file: PluginDocumentContext; readBytes: (path: string) => Promise<Uint8Array> } = $props();
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 count = $state(0);
let zoom = $state(1);
let rotation = $state(0);
let fit = $state(true);
let sizes = $state.raw<PageSize[]>([]);
let status = $state<Status>({ key: message("Loading PDF…") });
let asking = $state<"needed" | "incorrect" | null>(null);
let reloading = $state(false);
let failed = $state(false);
let scroller: HTMLDivElement;
let sheet: HTMLDivElement;
let sheets: HTMLDivElement[] = $state([]);
let pageInput: HTMLInputElement;
let passwordInput: HTMLInputElement | undefined = $state();
@@ -30,14 +34,20 @@
let pdf: PDFDocumentProxy | undefined;
let opened: OpenPdf | undefined;
let answer: ((password: string) => void) | undefined;
let render: RenderTask | undefined;
let text: TextLayer | undefined;
let revision = 0;
let generation = 0;
const drawings = new Map<number, Drawing>();
let queue: Promise<void> = Promise.resolve();
let loading: Promise<void> = Promise.resolve();
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 boxes = $derived(pageBoxes(sizes, zoom, rotation));
const zoomText = $derived(ready ? `${Math.round(zoom * 100)}%` : "—");
function fail(reason: unknown) {
if (disposed) return;
@@ -45,53 +55,137 @@
status = { key: message("Cannot display this PDF. {reason}"), values: { reason: reason instanceof Error ? reason.message : String(reason) }, alert: true };
}
/** Draw the current page again. A newer request cancels the older one. */
function schedule() {
const request = ++revision;
render?.cancel(); text?.cancel();
if (pdf && !disposed) status = { key: message("Loading page {page}…"), values: { page } };
const drawingKey = () => `${zoom}:${rotation}:${window.devicePixelRatio}`;
/** The status line names the current page when its drawing is complete. */
function report() {
if (disposed || failed || !pdf) return;
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 () => {
if (disposed || request !== revision || !pdf || scroller.clientWidth === 0) return;
const pdfPage = await pdf.getPage(page);
if (disposed || request !== revision) return;
const angle = (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 });
if (cancelled || disposed || !source) return;
const pdfPage = await source.getPage(number);
const sheet = sheets[number - 1];
if (cancelled || disposed || !sheet) return;
const viewport = pdfPage.getViewport({ scale: zoom, rotation: (pdfPage.rotate + rotation) % 360 });
const scale = outputScale(viewport.width, viewport.height, window.devicePixelRatio);
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.floor(viewport.width * 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");
// 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 }));
canvas.setAttribute("aria-label", $t("PDF page {page}", { page: number }));
const layer = document.createElement("div");
layer.className = "textLayer";
sheet.style.width = `${viewport.width}px`;
sheet.style.height = `${viewport.height}px`;
sheet.style.setProperty("--total-scale-factor", String(zoom));
sheet.replaceChildren(canvas, layer);
layer.style.setProperty("--total-scale-factor", String(viewport.scale));
render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] });
await render.promise;
if (disposed || request !== revision) return;
if (cancelled || disposed) 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 });
await text.render();
if (disposed || request !== revision) return;
status = { key: message("Page {page} of {count}"), values: { page, count } };
if (cancelled || disposed) return;
drawing.done = true;
pdfPage.cleanup();
}).catch(reason => { if (!disposed && request === revision) fail(reason); });
report();
}).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) {
if (!pdf) return;
page = pageNumber(value, pdf.numPages);
pageInput.value = String(page);
scroller.scrollTop = 0;
schedule();
// The first page shows with the margin above it. Each other page shows with half of the gap above it.
anchor = { index: page - 1, part: -(page === 1 ? PAGE_MARGIN : PAGE_GAP / 2) / (boxes[page - 1]?.height ?? 1) };
restore();
}
function setZoom(value: number) { fit = false; zoom = zoomLevel(value); schedule(); }
function applyFit() {
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() {
failed = false;
@@ -105,20 +199,27 @@
status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") };
queueMicrotask(() => passwordInput?.focus());
});
pdf = await opened.promise;
const source = await opened.promise;
if (disposed) return;
page = pageNumber(page, pdf.numPages);
count = pdf.numPages;
schedule();
const current = ++generation;
const { width, height } = (await source.getPage(1)).getViewport({ scale: 1 });
if (disposed) return;
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() {
revision++;
render?.cancel(); text?.cancel();
generation++;
for (const drawing of drawings.values()) drawing.cancel();
drawings.clear();
await queue;
const current = opened;
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0;
sheet?.replaceChildren();
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0; sizes = [];
await current?.close();
}
@@ -145,12 +246,11 @@
next(value);
}
function pageKey(event: KeyboardEvent) {
if (event.ctrlKey || event.metaKey || event.altKey || !ready) return;
if (event.key === "PageDown" || event.key === "PageUp") {
event.preventDefault();
go(page + (event.key === "PageDown" ? 1 : -1));
}
/** Ctrl and the wheel change the zoom. The wheel alone scrolls the pages. */
function wheel(event: WheelEvent) {
if (!(event.ctrlKey || event.metaKey) || !ready || event.deltaY === 0) return;
event.preventDefault();
setZoom(event.deltaY < 0 ? zoom * 1.1 : zoom / 1.1);
}
/** Stop the drawing, release the document, and stop its worker. The host calls it before it removes the tab. */
@@ -163,21 +263,23 @@
onMount(() => {
loading = load().catch(fail);
// A fit-width page follows the width of the tab. The first size draws at once. Later sizes wait until the size settles.
// Fit-width pages follow the width of the tab. A tab that shows again draws at once. Later sizes wait until the size settles.
let width = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
const resized = () => { applyFit(); restore(); };
const observer = new ResizeObserver(() => {
const next = scroller.clientWidth;
if (next === 0 || next === width) return;
const first = width === 0;
if (next === width) return;
const shown = width === 0;
width = next;
clearTimeout(timer);
if (!fit) return;
if (first) schedule();
else timer = setTimeout(schedule, RESIZE_SETTLE_MS);
if (next === 0) return;
if (shown) resized();
else timer = setTimeout(resized, RESIZE_SETTLE_MS);
});
observer.observe(scroller);
return () => { observer.disconnect(); clearTimeout(timer); void close(); };
scroller.addEventListener("wheel", wheel, { passive: false });
return () => { observer.disconnect(); clearTimeout(timer); cancelAnimationFrame(frame); scroller.removeEventListener("wheel", wheel); void close(); };
});
</script>
@@ -191,10 +293,12 @@
<IconButton icon="down" label={$t("Next page")} disabled={!ready || page >= count} onclick={() => go(page + 1)} />
<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)} />
<span class="zoom">{ready ? `${Math.round(zoom * 100)}%` : "—"}</span>
<input class="zoom" type="text" inputmode="decimal" value={zoomText} disabled={!ready} aria-label={$t("Zoom percent")}
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="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); schedule(); }} />
<IconButton icon="fit-width" label={$t("Fit width")} active={fit && ready} disabled={!ready} onclick={() => { fit = true; applyFit(); restore(); }} />
<IconButton icon="rotate" label={$t("Rotate clockwise")} disabled={!ready} onclick={() => { rotation = nextRotation(rotation); applyFit(); restore(); }} />
<IconButton icon="refresh" label={$t("Reload PDF")} disabled={reloading || (!ready && !failed)} onclick={() => void reload()} />
</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>
@@ -204,32 +308,39 @@
<button class="text-button" type="submit">{$t("Unlock")}</button>
</form>
{/if}
<!-- The page area takes focus for Page Up and Page Down. -->
<!-- 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 page. Use Page Up and Page Down to change pages.")} onkeydown={pageKey}>
<div bind:this={sheet} class="sheet"></div>
<!-- The page area takes focus, so the keyboard scrolls the pages. The host gives it focus after a tab change by keyboard. -->
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div bind:this={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF pages")} data-tab-focus onscroll={scrolled}>
<div class="pages">
{#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>
</section>
<style>
.pdf-viewer { display: flex; flex-direction: column; height: 100%; min-height: 240px; min-width: 0; color: var(--rs-text); font-size: 13px; }
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 8px; border-bottom: 1px solid var(--rs-border); }
/* 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); 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:disabled { color: var(--rs-text-dim); }
.page:disabled, .zoom:disabled { color: var(--rs-text-dim); }
.count { margin: 0 4px; color: var(--rs-text-dim); white-space: nowrap; }
.separator { width: 1px; height: 18px; margin: 0 4px; background: var(--rs-border); }
.zoom { min-width: 44px; color: var(--rs-text-dim); text-align: center; white-space: nowrap; }
.status { margin: 0; padding: 4px 12px; font-size: 12px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
.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; }
.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.alert { color: var(--rs-error); }
.password { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; }
.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 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-elevated); color: var(--rs-text); font: inherit; }
.text-button:hover { background: var(--rs-hover-bg); }
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; }
.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:hover { background: var(--rs-bg-active); }
/* The padding and the gap match PAGE_MARGIN and PAGE_GAP in model.ts. */
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; background: var(--rs-workarea-editor-bg); }
.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. */
.sheet { position: relative; margin: 0 auto; background: white; box-shadow: 0 2px 10px #0003; }
.sheet :global(canvas) { display: block; }
.sheet { position: relative; flex: none; background: white; box-shadow: 0 2px 10px #0003; }
.sheet :global(canvas) { display: block; width: 100%; height: 100%; }
/* 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 :is(span, br)) { position: absolute; color: transparent; white-space: pre; cursor: text; transform-origin: 0 0; user-select: text; }
+57
View File
@@ -29,3 +29,60 @@ export function nextRotation(rotation: 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)));
}
/** 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,34 +1,77 @@
import type { Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts";
import { message } from "./message.ts";
import { imagePath, parseImage } from "./images.ts";
/** A draft is separate from the saved card and uses compare-and-write protection. */
const invalidDraft = () => new Error(message("The description draft is invalid. Preserve it before recovery."));
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 {
private source: string | null = null;
private imageSource: string | null = null;
private images: ReadonlyMap<string, string> = new Map();
private queue: Promise<unknown> = Promise.resolve();
readonly path: string;
readonly imagesPath: string;
private workspace: Workspace;
constructor(workspace: Workspace, id: string) {
this.workspace = workspace;
const key = Array.from(new TextEncoder().encode(id), byte => byte.toString(16).padStart(2, "0")).join("");
this.path = `.runestone/pm/drafts/${key}.json`;
this.imagesPath = `.runestone/pm/drafts/${key}.images.json`;
}
async load(): Promise<string | null> {
this.source = await readOptional(this.workspace, this.path);
if (this.source === null) return null;
const value = JSON.parse(this.source);
if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string"))
throw new Error(message("The description draft is invalid. Preserve it before recovery."));
throw invalidDraft();
return value.body;
}
save(body: string | null): Promise<void> {
/** The image data of the draft, by image ID. A draft of an earlier version has no image record. Call this before `save`. */
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 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";
if (source === this.source || (body === null && this.source === null)) return;
await saveDocument(this.workspace, this.path, source, this.source);
this.source = source;
if (source !== this.source && !(body === null && this.source === null)) {
await saveDocument(this.workspace, this.path, source, this.source);
this.source = source;
}
await this.saveImages(next);
});
this.queue = write.catch(() => {});
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);
}
}
+7 -2
View File
@@ -51,13 +51,16 @@ export function parseImage(source: string): string {
throw new Error(message("The saved image is invalid or exceeds 50 MiB."));
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(
workspace: Workspace,
body: string,
pending: Map<string, string>,
pending: ReadonlyMap<string, string>,
attachments: TaskFields["attachments"] = [],
ids: string[] = [],
) {
for (const id of new Set([...imageReferences(body), ...attachments].map((image) => image.id))) {
const saved: string[] = [];
for (const id of new Set([...[...imageReferences(body), ...attachments].map((image) => image.id), ...ids])) {
const data = pending.get(id);
if (!data) continue;
const source = JSON.stringify({ schema: 1, data }) + "\n";
@@ -66,5 +69,7 @@ export async function saveImages(
// Retrying a failed card save reuses its complete image files.
const previous = await workspace.readOptional?.(path);
if (previous !== source) await saveDocument(workspace, path, source, null);
saved.push(id);
}
return saved;
}
+63 -14
View File
@@ -11,6 +11,30 @@ import {
parseImage,
saveImages,
} from "../storage/images.ts";
import { workspaceDownloadImage } from "../../../workspace/api.ts";
import { copiedImage } from "../../../workspace/copiedImage.ts";
import { mayAnimate, pastedImageSource } from "../../../workspace/media.ts";
async function fileDataUrl(file: File) {
const bytes = new Uint8Array(await file.arrayBuffer());
let binary = "";
for (let offset = 0; offset < bytes.length; offset += 8192)
binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
return `data:${file.type};base64,${btoa(binary)}`;
}
/**
* The original of a copied web image. The RuneStone browser keeps the bytes of the image that it copied.
* For a copy from another browser, download the original of a format with frames.
* Undefined keeps the still copy. "refused" means that the website did not give the original.
*/
async function webImage(source: string): Promise<{ data: string; type: string } | "refused" | undefined> {
const data = await copiedImage(source) ?? (mayAnimate(source) ? await workspaceDownloadImage(source).catch(() => "") : undefined);
if (data === undefined) return undefined;
if (!data) return "refused";
const type = /^data:([^;]+);/.exec(data)?.[1] ?? "";
return imageTypes.includes(type) ? { data, type } : undefined;
}
/** The image data stays outside the card Markdown and loads only in the open editor. */
export function createCardImages(
@@ -226,7 +250,8 @@ export function createCardImages(
}
}
}
async function addFiles(files: File[], attachOnly = false) {
/** `source` is the web address of the original of a copied image. `files` holds its still copy. */
async function addFiles(files: File[], attachOnly = false, source?: string) {
if (disposed || loading || description.disabled || !files.length) return;
loading = true;
updateControls();
@@ -237,18 +262,20 @@ export function createCardImages(
end = description.selectionEnd;
try {
const staged: { id: string; name: string; data: string }[] = [];
let refused = false;
for (const file of files) {
if (!imageTypes.includes(file.type))
// A browser copies only the first frame of a web image. The original keeps all of its frames.
const web = source ? await webImage(source) : undefined;
refused ||= web === "refused";
const original = typeof web === "object" ? web : undefined;
if (!original && !imageTypes.includes(file.type))
throw new Error(message("Use a PNG, JPEG, GIF, or WebP image."));
if (!file.size || file.size > maxImageBytes)
if (!original && !file.size)
throw new Error(message("The image file is empty. A browser can give an empty file when the website refuses a download. To add the image, copy it in the RuneStone browser. You can also save the image and add the saved file."));
if (!original && file.size > maxImageBytes)
throw new Error(message("Use an image between 1 byte and 50 MiB."));
const bytes = new Uint8Array(await file.arrayBuffer());
let binary = "";
for (let offset = 0; offset < bytes.length; offset += 8192)
binary += String.fromCharCode(
...bytes.subarray(offset, offset + 8192),
);
const data = `data:${file.type};base64,${btoa(binary)}`;
const data = original?.data ?? await fileDataUrl(file);
const name = original ? `${(file.name || "image").replace(/\.\w+$/, "")}.${original.type.slice(6)}` : file.name;
// Decode the image before the reference goes in, so that an invalid clipboard file keeps the draft.
const image = new Image();
image.src = data;
@@ -257,7 +284,7 @@ export function createCardImages(
});
staged.push({
id: crypto.randomUUID(),
name: (file.name || tr("Pasted image")).slice(0, 255),
name: (name || tr("Pasted image")).slice(0, 255),
data,
});
}
@@ -269,6 +296,7 @@ export function createCardImages(
description.setRangeText(`\n${markdown}\n`, start, end, "end");
}
description.dispatchEvent(new Event("input", { bubbles: true }));
if (refused) error.textContent = tr("The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file.");
} catch (reason) {
if (!disposed)
(attachOnly ? attachmentError : error).textContent = errorText(reason);
@@ -288,7 +316,9 @@ export function createCardImages(
if (!files.length) return;
event.preventDefault();
event.stopPropagation();
void addFiles(files);
// Read the HTML now. The clipboard data is empty after the paste event.
const source = files.length === 1 ? pastedImageSource(event.clipboardData?.getData("text/html") ?? "") : undefined;
void addFiles(files, false, source);
};
const dragOver = (event: DragEvent) => {
if (event.dataTransfer?.types.includes("Files")) {
@@ -339,7 +369,26 @@ export function createCardImages(
saving = value;
updateControls();
},
save: (body: string) => saveImages(workspace, body, pending, attachments),
/** Write the images of `body`, of the attachments, and of `ids`, for example the card cover. */
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() {
disposed = true;
clearTimeout(idleTimer);
@@ -347,7 +396,7 @@ export function createCardImages(
viewerObserver = undefined;
viewer?.remove(); viewer = undefined;
revision++;
pending.clear();
// Keep the pending image data. A draft save that is in progress after a close still needs it.
loaded.clear();
description.removeEventListener("paste", paste);
description.removeEventListener("input", render);
+4 -3
View File
@@ -67,7 +67,7 @@
cursor: default;
}
.rs-pm button:not(.rs-picker-row):not([role^="menuitem"]):focus-visible,
.rs-pm input:not(.rs-find-bar input):focus-visible,
.rs-pm input:not(:where(.rs-find-bar input)):focus-visible,
.rs-pm select:focus-visible,
.rs-pm textarea:focus-visible {
outline: 1px solid var(--pm-accent);
@@ -196,7 +196,8 @@
.pm-search-row input {
width: min(340px, 100%);
}
.rs-pm input:not(.rs-find-bar input),
/* The find bar exclusion adds no specificity, so the rules of each control can replace these defaults. */
.rs-pm input:not(:where(.rs-find-bar input)),
.rs-pm select,
.rs-pm textarea {
background: var(--pm-field-surface);
@@ -205,7 +206,7 @@
padding: 6px 8px;
min-height: 30px;
}
.rs-pm input[type="checkbox"]:not(.rs-find-bar input) {
.rs-pm input[type="checkbox"]:not(:where(.rs-find-bar input)) {
min-height: 0;
width: 16px;
height: 16px;
+17 -7
View File
@@ -1051,7 +1051,11 @@ export function mountPM(
description,
(name, action) => button(tr(name), action, name === "Actual size" ? "expand" : "image"),
(name, action) => iconButton(name, "close", action),
(loading) => { save.disabled = loading || busy || !title.value.trim(); descriptionEditor.updateLoading(); },
(loading) => {
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,
);
const formattingIcons: Record<string, keyof typeof icons> = {
@@ -1064,9 +1068,10 @@ export function mountPM(
let descriptionSaving = false;
let draftTimer: ReturnType<typeof setTimeout> | undefined;
let draftEdited = false;
const draftReady = draft?.load().then(body => {
const draftReady = draft && Promise.all([draft.load(), draft.loadImages()]).then(([body, draftImages]) => {
if (body !== null && !draftEdited && dialog.isConnected) {
descriptionEditor.restoreDraft(body);
images.restore(draftImages);
updateDescriptionBadge(task!.id, body !== task!.body);
}
});
@@ -1074,8 +1079,13 @@ export function mountPM(
clearTimeout(draftTimer);
await draftReady;
if (!draft || !task) return;
await images.save(description.value);
await draft.save(description.value === task.body ? null : description.value);
const body = 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(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); };
void draftReady?.catch(reportDraftError);
@@ -1113,8 +1123,7 @@ export function mountPM(
description.addEventListener("input", () => {
draftEdited = true;
if (task) updateDescriptionBadge(task.id, description.value !== task.body);
clearTimeout(draftTimer);
if (draft && !images.isLoading()) draftTimer = setTimeout(() => { void flushDraft().catch(reportDraftError); }, 300);
scheduleDraft();
});
const useSharedChoices = sharedChoice;
const updateChoice = sharedChoices.update;
@@ -1549,7 +1558,8 @@ export function mountPM(
const ok = await perform(
async () => {
await flushDraft();
await images.save(body);
// The cover can be an image that only the description draft has.
await images.save(body, cover.value ? [cover.value] : []);
const existingIds = new Set(store.tasks.map(candidate => candidate.id));
await (task && boardSelect.value && (boardSelect.value !== originalBoardId || (!store.board.reference && listChanged))
? store.saveToBoard(task, boardSelect.value, listSelect.value || null, { ...fields, body })
+26 -12
View File
@@ -1020,10 +1020,10 @@ export const messageRows: [string, string, string, string][] = [
"阅读"
],
[
"Split",
"Diviser",
"分割",
"分栏"
"Read beside",
"Lire à côté",
"横に閲覧",
"并排阅读"
],
[
"Editor",
@@ -1464,10 +1464,10 @@ export const messageRows: [string, string, string, string][] = [
"版本 {version}"
],
[
"RuneStone is under development. Maintained by kwyvern-gh.",
"RuneStone est en développement. Maintenu par kwyvern-gh.",
"RuneStoneは開発中です。管理者:kwyvern-gh。",
"RuneStone 正在开发中。由 kwyvern-gh 维护。"
"RuneStone is under development. Maintained by KnottyWyvern-GH.",
"RuneStone est en développement. Maintenu par KnottyWyvern-GH.",
"RuneStoneは開発中です。管理者:KnottyWyvern-GH。",
"RuneStone 正在开发中。由 KnottyWyvern-GH 维护。"
],
[
"Use the folder button to open a workspace or create one. Your notes and scripts stay as ordinary files on disk.",
@@ -1679,6 +1679,12 @@ export const messageRows: [string, string, string, string][] = [
"新しいタブでリンクを開く",
"在新标签页中打开链接"
],
[
"Open image in new tab",
"Ouvrir l’image dans un nouvel onglet",
"新しいタブで画像を開く",
"在新标签页中打开图片"
],
[
"Open link in default browser",
"Ouvrir le lien dans le navigateur par défaut",
@@ -3294,8 +3300,13 @@ 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. Paste stopped.", "L’espace de travail a changé. Le collage est arrêté.", "ワークスペースが変更されました。貼り付けを停止しました。", "工作区已更改。粘贴已停止。"],
["Move to new window", "Déplacer vers une nouvelle fenêtre", "新しいウィンドウに移動", "移到新窗口"],
["Split right", "Scinder à droite", "右に分割", "向右拆分"],
["Split down", "Scinder vers le bas", "下に分割", "向下拆分"],
["New tab to the right", "Nouvel onglet à droite", "右に新しいタブ", "在右侧新建标签页"],
["New tab below", "Nouvel onglet en dessous", "下に新しいタブ", "在下方新建标签页"],
["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", "下に開く", "在下方打开"],
["Open to the left", "Ouvrir à gauche", "左側で開く", "在左侧打开"],
["Find…", "Rechercher…", "検索…", "查找…"],
["Open in default browser", "Ouvrir dans le navigateur par défaut", "既定のブラウザーで開く", "在默认浏览器中打开"],
["Invalid browser tab transfer.", "Transfert d’onglet de navigateur non valide.", "ブラウザータブの移動が無効です。", "浏览器标签页转移无效。"],
@@ -3370,7 +3381,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 笔记上方显示文件名。"],
["Source", "Source", "ソース", "源码"],
["View", "Affichage", "表示", "视图"],
["Split: Read beside the editor", "Diviser : Lire à côté de l’éditeur", "分割: エディターの横に閲覧を表示", "分栏:在编辑器旁显示阅读"],
["Read beside: show the Read view beside the editor", "Lire à côté : afficher Lire à côté de l’éditeur", "横に閲覧: エディターの横に閲覧を表示", "并排阅读:在编辑器旁显示阅读"],
["Switch between Write and Source", "Alterner entre Écrire et Source", "「書く」と「ソース」を切り替え", "在写作和源码之间切换"],
["Switch between Read and the editor", "Alterner entre Lire et l’éditeur", "「閲覧」とエディターを切り替え", "在阅读和编辑器之间切换"],
["Unsaved", "Non enregistré", "未保存", "未保存"],
@@ -3674,7 +3685,8 @@ export const messageRows: [string, string, string, string][] = [
["Loading page {page}…", "Chargement de la page {page}…", "{page} ページを読み込み中…", "正在加载第 {page} 页…"],
["Page {page} of {count}", "Page {page} sur {count}", "{page} / {count} ページ", "第 {page} 页,共 {count} 页"],
["PDF page {page}", "Page PDF {page}", "PDF の {page} ページ", "PDF 第 {page} 页"],
["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 翻页。"],
["PDF pages", "Pages du PDF", "PDF のページ", "PDF 页面"],
["Zoom percent", "Pourcentage de zoom", "ズームの倍率", "缩放百分比"],
["PDF password", "Mot de passe du PDF", "PDF のパスワード", "PDF 密码"],
["Unlock", "Déverrouiller", "ロック解除", "解锁"],
["This PDF needs a password.", "Ce PDF nécessite un mot de passe.", "この PDF にはパスワードが必要です。", "此 PDF 需要密码。"],
@@ -4065,6 +4077,8 @@ export const messageRows: [string, string, string, string][] = [
["Unlink {name}", "Délier {name}", "{name} のリンクを解除", "取消关联 {name}"],
["Unsaved changes", "Modifications non enregistrées", "未保存の変更", "未保存的更改"],
["Use a PNG, JPEG, GIF, or WebP image.", "Utilisez une image PNG, JPEG, GIF ou WebP.", "PNG、JPEG、GIF、WebP のいずれかの画像を使用してください。", "请使用 PNG、JPEG、GIF 或 WebP 图片。"],
["The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file.", "Le site web a refusé l’image d’origine. RuneStone n’en a donc ajouté que la première trame. Pour conserver l’animation, copiez l’image dans le navigateur de RuneStone. Vous pouvez aussi enregistrer l’image, puis ajouter le fichier enregistré.", "Web サイトが元の画像を拒否したため、RuneStone は最初のフレームだけを追加しました。アニメーションを保つには、RuneStone のブラウザーで画像をコピーしてください。画像を保存して、保存したファイルを追加することもできます。", "网站拒绝提供原始图片,因此 RuneStone 只添加了第一帧。要保留动画,请在 RuneStone 浏览器中复制图片。也可以保存图片,然后添加保存的文件。"],
["The image file is empty. A browser can give an empty file when the website refuses a download. To add the image, copy it in the RuneStone browser. You can also save the image and add the saved file.", "Le fichier image est vide. Un navigateur peut fournir un fichier vide quand le site web refuse un téléchargement. Pour ajouter l’image, copiez-la dans le navigateur de RuneStone. Vous pouvez aussi enregistrer l’image, puis ajouter le fichier enregistré.", "画像ファイルが空です。Web サイトがダウンロードを拒否すると、ブラウザーが空のファイルを渡すことがあります。画像を追加するには、RuneStone のブラウザーでコピーしてください。画像を保存して、保存したファイルを追加することもできます。", "图片文件为空。网站拒绝下载时,浏览器可能会提供空文件。要添加图片,请在 RuneStone 浏览器中复制它。也可以保存图片,然后添加保存的文件。"],
["Use an image between 1 byte and 50 MiB.", "Utilisez une image entre 1 octet et 50 Mio.", "1 バイトから 50 MiB までの画像を使用してください。", "请使用 1 字节到 50 MiB 之间的图片。"],
["View image {name}", "Afficher l’image {name}", "画像 {name} を表示", "查看图片 {name}"],
["When you save, RuneStone removes each deleted label from all cards.", "Lors de l’enregistrement, RuneStone retire chaque étiquette supprimée de toutes les cartes.", "保存すると、RuneStone は削除したラベルをすべてのカードから外します。", "保存时,RuneStone 会从所有卡片中移除每个已删除的标签。"],
+3 -2
View File
@@ -11,9 +11,10 @@
error?: string | null;
onOpen: (entry: Backlink) => 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 }: Props = $props();
let expanded = $state(true);
let { entries, busy = false, error = null, onOpen, onRebuild, expanded = $bindable(true) }: Props = $props();
const contentId = $props.id();
function collapseTooltip(node: HTMLElement) {
return { destroy: attachTooltip(node, () => $t(expanded ? "Collapse backlinks" : "Expand backlinks")) };
+46
View File
@@ -0,0 +1,46 @@
<script lang="ts">
import Icon from "$lib/ui/Icon.svelte";
import { attachTooltip } from "$lib/ui/tooltip";
import { t } from "$lib/i18n";
// A pane beside other panes closes with this button. Its tab stays open in the tab bar.
// The button shows its name, because a bare close icon looks like the close button of a tab.
// A narrow pane shows only the icon. Then the tooltip gives the name.
let { onclick }: { onclick: () => void } = $props();
let text: HTMLSpanElement;
function tooltip(node: HTMLElement) {
const dispose = attachTooltip(node, () => text && getComputedStyle(text).display === "none" ? $t("Close split") : "");
return { destroy: dispose };
}
</script>
<button type="button" class="close-split" aria-label={$t("Close split")} {onclick} use:tooltip><Icon icon="split-close" /><span bind:this={text}>{$t("Close split")}</span></button>
<style>
.close-split {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
justify-content: center;
gap: 6px;
min-width: 32px;
height: 32px;
padding: 0 10px 0 8px;
box-sizing: border-box;
border: 1px solid var(--rs-border);
border-radius: var(--rs-control-radius);
background: transparent;
color: var(--rs-text-dim);
font: inherit;
font-size: 12px;
white-space: nowrap;
}
.close-split :global(svg) { width: 16px; height: 16px; flex-shrink: 0; }
.close-split:hover { background: var(--rs-hover-bg); color: var(--rs-text-strong); }
/* The pane bar and the editor bar are size containers. A narrow pane keeps room for its path and its view controls. */
@container (max-width: 420px) {
.close-split { padding: 0; }
.close-split span { display: none; }
}
</style>
+187 -47
View File
@@ -1,26 +1,35 @@
<script lang="ts">
// The document area: plugin editor panes over the document panes, with the save conflict banner of each document.
// The document area: the panes of documents and plugin editor views, 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 { t } from "$lib/i18n";
import PluginEditor from "$lib/plugins/PluginEditor.svelte";
import { pluginEditors, pluginView, selectPluginEditor } from "$lib/plugins/external";
import { pluginEditors, pluginView, selectPluginEditor, type OpenPluginView } from "$lib/plugins/external";
import type { Documents } from "$lib/workspace/documents.svelte";
import type { OpenBuffer } from "$lib/workspace/types";
import EditorPane from "./EditorPane.svelte";
import Icon from "$lib/ui/Icon.svelte";
import CloseSplitButton from "./CloseSplitButton.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 TabBar from "./TabBar.svelte";
type EditorProps = ComponentProps<typeof EditorPane>;
type DocumentView = { id: string; reading: boolean; split: boolean; buffer: OpenBuffer | null; bounds: { width: number } };
type Bounds = { left: number; top: number; width: number; height: number };
type DocumentView = { id: string; reading: boolean; split: boolean; buffer: OpenBuffer | null; pluginKey: string | null };
/** The pane under a dragged tab, and the place of the drop on it. */
type DropTarget = { pane: string; zone: PaneDrop };
type Props = {
editorPluginVisible: boolean;
split: boolean;
pluginBounds: Record<string, Bounds | undefined>;
tabBar: ComponentProps<typeof TabBar>;
/** The focused plugin view covers the whole area. */
pluginCover: boolean;
/** The drop hint of a dragged tab. */
drop: DropTarget | null;
onResize: (path: SplitPath, ratio: number) => void;
pluginPaneComponents: Record<string, PluginEditor | undefined>;
documentViews: DocumentView[];
layout: SplitLayout;
activePane: string;
paneComponents: Record<string, EditorPane | undefined>;
documents: Documents | null;
@@ -37,7 +46,7 @@
onQuickOpen: () => void;
onOpenBrowser?: () => void;
onChange: EditorProps["onChange"];
onInsertImage: (file: File, buffer: OpenBuffer | null) => Promise<string | null>;
onInsertImage: (file: File, buffer: OpenBuffer | null, source?: string) => Promise<string | null>;
onRenameTitle: EditorProps["onRenameTitle"];
tableActions: (pane: DocumentView) => EditorProps["tableActions"];
linkActions: (pane: DocumentView) => EditorProps["linkActions"];
@@ -46,37 +55,113 @@
onCursor: (pane: DocumentView, line: number, column: number) => void;
onOpenLink: (pane: DocumentView, kind: "md" | "wiki", target: string) => void;
};
let { editorPluginVisible, split, pluginBounds, tabBar, pluginPaneComponents = $bindable(), documentViews, activePane, paneComponents = $bindable(),
let { pluginCover, drop, onResize, pluginPaneComponents = $bindable(), documentViews, layout, activePane, paneComponents = $bindable(),
documents, tabs, hasWorkspace, browserOpening, focusLine, onFocusPane, onCloseSplit, onSaveCopy, onOpenWorkspace, onNewFile, onNewNote,
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 left, 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" : rx < 0.3 && !stacked ? "left" : 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 === "left") return { ...box, width: box.width / 2 };
if (drop.zone === "down") return { ...box, top: box.top + box.height / 2, height: box.height / 2 };
return box;
});
</script>
<main class="center">
<div class="plugin-panes" class:inactive={!editorPluginVisible}>
{#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}>
<main class="center" class:resizing={!!resizing} class:resizing-down={resizing === "down"} bind:this={area} bind:clientWidth={width}>
<div class="editor-host" class:plugin-covered={pluginCover}>
<div class="document-panes" class:split={several}>
{#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.) -->
<div class="document-pane" class:focused={activePane === pane.id}
<div class="document-pane" class:focused={activePane === pane.id} class:edge-left={(box?.left ?? 0) > 0} class:edge-top={(box?.top ?? 0) > 0}
data-document-pane={pane.id} data-document-path={pane.buffer?.relPath ?? ""}
style:--pane-weight={pane.bounds.width}
style:left={`${box?.left ?? 0}%`} style:top={`${box?.top ?? 0}%`}
style:width={`${box?.width ?? 100}%`} style:height={`${box?.height ?? 100}%`}
onpointerdowncapture={() => 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}
<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}
@@ -94,7 +179,7 @@
bind:this={paneComponents[pane.id]}
{tabs}
active={activePane === pane.id}
onCloseSplit={documentViews.length > 1 ? () => onCloseSplit(pane.id) : undefined}
onCloseSplit={several ? () => onCloseSplit(pane.id) : undefined}
{hasWorkspace}
{onOpenWorkspace}
{onNewFile}
@@ -108,7 +193,7 @@
split={pane.split}
focusLine={activePane === pane.id ? focusLine : null}
{onChange}
onInsertImage={file => onInsertImage(file, pane.buffer)}
onInsertImage={(file, source) => onInsertImage(file, pane.buffer, source)}
{onRenameTitle}
tableActions={tableActions(pane)}
linkActions={linkActions(pane)}
@@ -117,10 +202,50 @@
onCursor={(line, column) => onCursor(pane, line, column)}
onOpenLink={(kind, target) => onOpenLink(pane, kind, target)}
/>
{/if}
</div>
{/each}
</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>
<CloseSplitButton 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") : drop.zone === "left" ? $t("Open to the left") : $t("Open below")}</span>
</div>
{/if}
</main>
<style>
@@ -155,19 +280,34 @@
container-type: inline-size;
}
.document-panes { flex: 1; min-height: 0; display: flex; overflow: hidden; }
.document-pane { flex: var(--pane-weight) 1 0; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
.document-pane + .document-pane { border-left: 1px solid var(--rs-border); }
/* Each pane has its place in the split layout. A pane beside or below another pane has a border on that edge. */
.document-panes { position: relative; flex: 1; min-height: 0; overflow: hidden; }
.document-pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; overflow: hidden; box-sizing: border-box; }
.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); }
@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; }
.plugin-panes { position: relative; flex: 1; min-height: 0; min-width: 0; overflow: hidden; }
.plugin-pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; box-sizing: border-box; }
.plugin-pane.split { border: 1px solid var(--rs-border); }
.plugin-pane.split.focused { border-color: var(--rs-accent); }
.plugin-panes.inactive, .plugin-pane.inactive { display: none; }
/* The plugin layer covers the area, but only its visible panes take the pointer. */
.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; pointer-events: auto; }
.plugin-pane.embedded { background: var(--rs-bg); }
.plugin-pane.inactive { display: none; }
/* The bar of a plugin view in a pane matches the chrome bar of a document pane. */
.pane-bar { container-type: inline-size; 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>
+7 -5
View File
@@ -9,7 +9,7 @@
import type { FindTarget } from "$lib/editor/findTarget";
import DocumentEditor from "$lib/editor/DocumentEditor.svelte";
import { tick } from "svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import CloseSplitButton from "./CloseSplitButton.svelte";
import ImageViewer from "./ImageViewer.svelte";
import MarkdownView from "./MarkdownView.svelte";
import ViewModes, { type ViewMode } from "./ViewModes.svelte";
@@ -29,7 +29,7 @@
focusLine: number | null;
onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>;
onInsertImage?: (file: File) => Promise<string | null>;
onInsertImage?: (file: File, source?: string) => Promise<string | null>;
onView?: (view: ViewMode) => void;
onSplit?: (split: boolean) => void;
onCursor?: (line: number, column: number) => void;
@@ -147,12 +147,14 @@
const splitView = $derived(split && canPreview && !reading);
const view: ViewMode = $derived(readOnly ? "read" : chrome === "Source" ? "source" : "write");
// The tab already names the file, so the breadcrumb shows only its folder.
const folder = $derived(buffer?.relPath.includes("/") ? buffer.relPath.slice(0, buffer.relPath.lastIndexOf("/")).split("/").join(" / ") : "");
// 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 ? "" : onCloseSplit ? buffer.relPath.split("/").join(" / ")
: buffer.relPath.includes("/") ? buffer.relPath.slice(0, buffer.relPath.lastIndexOf("/")).split("/").join(" / ") : "");
</script>
{#if !buffer || buffer.kind === "empty"}
<div class="empty">
{#if onCloseSplit}<IconButton icon="close" label={$t("Close split")} onclick={onCloseSplit} />{/if}
{#if onCloseSplit}<CloseSplitButton onclick={onCloseSplit} />{/if}
<div class="welcome-actions">
{#if hasWorkspace}
<div class="welcome-row">
@@ -178,7 +180,7 @@
</span>
{/if}
<div class="actions" bind:this={modeControls}>
{#if onCloseSplit}<IconButton icon="close" label={$t("Close split")} onclick={onCloseSplit} />{/if}
{#if onCloseSplit}<CloseSplitButton onclick={onCloseSplit} />{/if}
{#if !isImage}<ViewModes {view} split={splitView} readable={canPreview} onView={next => onView?.(next)} onSplit={next => onSplit?.(next)} />{/if}
</div>
</div>
+4
View File
@@ -43,6 +43,8 @@
workspaceRoot: string;
activePath: string | null;
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;
onStatus?: (message: string) => void;
onCreated?: (entry: TreeEntry) => void;
@@ -56,6 +58,7 @@
workspaceRoot,
activePath,
onOpenFile,
onOpenRight,
session,
onStatus,
onCreated,
@@ -878,6 +881,7 @@
...(!multiple && entry.kind === "folder" ? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }] : []),
...(!multiple && entry.kind === "file" ? [
{ 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)); } },
] : []),
terminalItem(parent),
+3 -1
View File
@@ -29,13 +29,14 @@
onHelp: () => void;
onSettings: () => void;
onOpenFile: (entry: TreeEntry, line?: number, target?: "current" | "new") => void;
onOpenRight?: (entry: TreeEntry) => void;
onCreated: (entry: TreeEntry) => void;
onSaveTemplate: (entry: TreeEntry) => void;
onManageTemplates: () => void;
onStatus: (message: string) => void;
};
let { workspace, session, leftView, keysActive, showInternal, activePath, searchRequest, fileTree = $bindable(), workspaceAnchor = $bindable(),
onOpenFile, onCreated, onSaveTemplate, onManageTemplates, onStatus, onChooseWorkspace, onHelp, onSettings }: Props = $props();
onOpenFile, onOpenRight, onCreated, onSaveTemplate, onManageTemplates, onStatus, onChooseWorkspace, onHelp, onSettings }: Props = $props();
function tooltip(node: HTMLElement, text: string) {
let current = text;
@@ -63,6 +64,7 @@
{onManageTemplates}
{activePath}
onOpenFile={(entry, newTab) => onOpenFile(entry, undefined, newTab ? "new" : "current")}
{onOpenRight}
{session}
{keysActive}
{onCreated}
+6 -2
View File
@@ -4,6 +4,7 @@
import { tick, type Snippet } from "svelte";
import { workspaceReadDataUrl } from "$lib/workspace/api";
import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml";
import { loadImageSize } from "$lib/workspace/imageSizes";
import { renderDiagrams } from "$lib/workspace/diagrams";
import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media";
import { imageControls } from "$lib/editor/imageControls";
@@ -55,7 +56,9 @@
const base = normalized.split("/").pop() ?? path;
for (const candidate of new Set([primary, normalized, base])) {
try {
urls.set(source, await workspaceReadDataUrl(candidate));
const url = await workspaceReadDataUrl(candidate);
await loadImageSize(url);
urls.set(source, url);
return;
} catch { /* Try the workspace-relative attachment next. */ }
}
@@ -102,7 +105,8 @@
[...el.querySelectorAll<HTMLElement>("h1, h2, h3, h4, h5, h6")].filter(heading => !heading.classList.contains("document-title"))[index];
if (!target) return;
currentHeadings?.reveal(target);
target.scrollIntoView({ block: "center" });
// 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: "start" });
el.focus({ preventScroll: true });
});
return renderDiagrams(el, () => cancelled);
+3 -2
View File
@@ -13,8 +13,9 @@
backlinks: Backlink[];
session: WorkspaceSession;
onOpenBacklink: (entry: Backlink) => void;
backlinksOpen?: boolean;
};
let { outlineItems, onJump, showBacklinks, backlinks, session, onOpenBacklink }: Props = $props();
let { outlineItems, onJump, showBacklinks, backlinks, session, onOpenBacklink, backlinksOpen = $bindable(true) }: Props = $props();
</script>
<aside class="right">
@@ -22,7 +23,7 @@
<OutlinePane items={outlineItems} {onJump} />
</div>
{#if showBacklinks}
<Backlinks entries={backlinks} busy={session.indexBusy} error={session.indexError} onOpen={onOpenBacklink} onRebuild={() => void session.rebuildIndex()} />
<Backlinks bind:expanded={backlinksOpen} entries={backlinks} busy={session.indexBusy} error={session.indexError} onOpen={onOpenBacklink} onRebuild={() => void session.rebuildIndex()} />
{/if}
</aside>
+1 -1
View File
@@ -253,7 +253,7 @@
{/each}
</details>
</div>
<p class="about-note">{$t("RuneStone is under development. Maintained by kwyvern-gh.")}</p>
<p class="about-note">{$t("RuneStone is under development. Maintained by KnottyWyvern-GH.")}</p>
{/if}
</div>
</div>
+42 -3
View File
@@ -27,9 +27,14 @@
tabDragData?: (tab: WorkbenchTab) => string | undefined;
onDropTab?: (data: string, index: number) => 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 }: Props = $props();
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab, onDetach, onDragAt, onDropAt, onDragEnd }: Props = $props();
const transferType = "application/x-runestone-tab";
let bar: HTMLDivElement;
let dragged = $state<string | null>(null);
@@ -61,6 +66,34 @@
suppressClick = true;
event.dataTransfer.effectAllowed = "move";
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) {
@@ -85,6 +118,7 @@
}
function finishTabTransfer() {
stopAreaDrop();
dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false;
cancelAnimationFrame(transferFrame); transferFrame = 0;
}
@@ -289,6 +323,7 @@
frame = requestAnimationFrame(scroll);
};
const clean = () => {
if (started) onDragEnd?.();
if (pointerTarget.hasPointerCapture(pointerId)) pointerTarget.releasePointerCapture(pointerId);
cancelAnimationFrame(frame);
dragged = dropBefore = dropAfter = null;
@@ -306,15 +341,19 @@
e.preventDefault();
if (!started) { started = true; suppressClick = true; dragged = path; frame = requestAnimationFrame(scroll); }
update();
if (destination === null) onDragAt?.(path, x, y);
else onDragEnd?.();
};
const onUp = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return;
x = e.clientX; y = e.clientY;
if (started) update();
const target = destination;
const wasStarted = started;
clean();
if (started && target !== null) void move(path, target);
else if (started && (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight)) {
if (wasStarted && target !== null) void move(path, target);
else if (wasStarted && onDropAt?.(path, x, y)) return;
else if (wasStarted && (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight)) {
const tab = tabs.find(tab => tab.relPath === path);
if (tab) onDetach?.(tab);
}
+4 -4
View File
@@ -1,10 +1,10 @@
<script lang="ts" module>
/** The view of a document pane. Split is a separate toggle beside Write or Source. */
/** The view of a document pane. Read beside is a separate toggle beside Write or Source. */
export type ViewMode = "write" | "source" | "read";
</script>
<script lang="ts">
// The view control of a document pane: Write, Source, and Read in one radio group, then the Split toggle.
// The view control of a document pane: Write, Source, and Read in one radio group, then the Read beside toggle.
// All choices stay visible. Narrow panes show only the icons.
import { t } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte";
@@ -16,7 +16,7 @@
type Props = {
view: ViewMode;
split: boolean;
/** Markdown files have Read and Split. Other text files have only Write and Source. */
/** Markdown files have Read and Read beside. Other text files have only Write and Source. */
readable: boolean;
onView: (view: ViewMode) => void;
onSplit: (split: boolean) => void;
@@ -60,7 +60,7 @@
{/each}
</div>
{#if readable}
<button type="button" class="split" aria-pressed={split} aria-label={$t("Split")} use:tooltip={$t("Split: Read beside the editor")} onclick={() => onSplit(!split)}>
<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)}>
<Icon icon="split" />
</button>
{/if}
+210 -36
View File
@@ -6,13 +6,14 @@
import type PluginEditor from "$lib/plugins/PluginEditor.svelte";
import { featureOfOwner } from "$lib/features/catalog";
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup, pluginTools, installedPlugins, runPluginCommand } from "$lib/plugins/external";
import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
import { containsPane, paneBounds, splitSibling } from "$lib/workspace/splitLayout";
import { pluginSidebar, closePluginSidebar, pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginFileOpen, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
import { onMount, onDestroy, tick, untrack } from "svelte";
import type { MenuLink } from "$lib/editor/linkMenu";
import { WorkspaceSession } from "$lib/workspace/session.svelte";
import { retainEditorStates } from "$lib/editor/editorStates";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView } from "$lib/workspace/documentPanes";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView,
paneOf, showInActivePane, splitWithContent, releaseSolePlugin, dropInPane, moveToNewPane, resizeDocumentPanes, type PaneContent, type PaneDrop, type DocumentPanes } from "$lib/workspace/documentPanes";
import type { ViewMode } from "./ViewModes.svelte";
import { selectedEditorText } from "$lib/editor/selection";
import { pluginHost } from "$lib/plugins/registry";
@@ -65,10 +66,12 @@
workspaceReveal,
workspaceWrite,
workspaceWriteBytes,
workspaceSaveImageUrl,
} from "$lib/workspace/api";
import { detectChrome } from "$lib/workspace/chrome";
import { planRename, planMarkdownTitleRename, planDocumentTitleRename, renameSelection } from "$lib/workspace/renamePath";
import { attachmentRel, isImagePath, isMarkdownPath } from "$lib/workspace/media";
import { attachmentRel, dataUrlExtension, isImagePath, isMarkdownPath, mayAnimate } from "$lib/workspace/media";
import { copiedImage } from "$lib/workspace/copiedImage";
import { headingLinkLine, linkFragment } from "$lib/workspace/headingLinks";
import type { Chrome, OpenBuffer, TreeEntry, WorkspaceInfo } from "$lib/workspace/types";
@@ -147,6 +150,7 @@
let searchRequest = $state<{ text: string; id: number } | null>(null);
let leftOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.leftOpen);
let rightOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.rightOpen);
let backlinksOpen = $state(DEFAULT_WORKBENCH_LAYOUT.backlinksOpen);
$effect(() => { if ($pluginSidebar && !transferredWindow) leftOpen = true; });
let terminalOpen = $state(false);
let documentPanes = $state(initialDocumentPanes());
@@ -226,7 +230,9 @@
}, () => {
if (documents !== next) return;
const selected = next.active;
documentPanes = syncDocumentPanes(documentPanes, next.buffers.map(tab => tab.id), selected?.id ?? null);
// While a plugin view has the focus, a document change does not replace the content of a pane.
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;
});
return next;
@@ -235,8 +241,8 @@
onDestroy(() => retainEditorStates([]));
const documentViews = $derived.by(() => {
const bounds = paneBounds(documentPanes.layout);
return documentPanes.panes.map(pane => ({ ...pane, buffer: tabs.find(tab => tab.id === pane.documentId) ?? null, bounds: bounds[pane.id] }))
.sort((a, b) => a.bounds.left - b.bounds.left);
return documentPanes.panes.map(pane => ({ ...pane, buffer: tabs.find(tab => tab.id === pane.documentId) ?? null }))
.sort((a, b) => bounds[a.id].left - bounds[b.id].left || bounds[a.id].top - bounds[b.id].top);
});
function setReading(next: boolean, paneId = documentPanes.active) {
documentPanes = readDocumentPane(documentPanes, paneId, next);
@@ -246,6 +252,13 @@
if (!pane) return;
const tab = tabs.find(tab => tab.id === pane.documentId);
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);
if (tab && documents?.active?.id !== tab.id) { focusLine = null; documents?.select(tab.relPath); }
if (focusEditor) void tick().then(() => {
@@ -254,27 +267,163 @@
document.querySelector<HTMLElement>(`[data-document-pane="${paneId}"]`)?.scrollIntoView({ block: "nearest", inline: "nearest" });
});
}
function closeSplit(paneId: string) {
documentPanes = closeDocumentPane(documentPanes, paneId);
focusDocumentPane(documentPanes.active, true);
/** 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) {
changePanes(closeDocumentPane(documentPanes, paneId));
}
/** 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) {
const current = documents;
const covered = sourcePane === documentPanes.active ? coverKey : null;
const source = documentPanes.panes.find(pane => pane.id === sourcePane);
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");
if (documents !== current || switching || documentPanes.active !== sourcePane
|| documentPanes.panes.find(pane => pane.id === sourcePane)?.documentId !== source.documentId) return;
if (!unchanged()) return;
const target = current.buffers.find(tab => tab.relPath === file.rel_path);
if (!target) return;
keepCoverInPane();
documentPanes = splitDocumentPane(documentPanes, sourcePane, target.id, crypto.randomUUID());
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;
const own = coverKey ? "plugin" in tab && tab.plugin.key === coverKey : paneOf(documentPanes, tabContent(tab))?.id === target.pane;
if (!own) return { tab, target, stay: null };
// The tab that the pane shows can move to a new pane beside it. Then the pane shows a different tab:
// the document below a plugin view that covers the area, or the next tab that no pane shows.
if (target.zone === "center") return null;
const below = coverKey ? documentPanes.panes.find(pane => pane.id === target.pane)?.documentId : null;
const next = below ? undefined : tabAfter(tab);
const stay: PaneContent | null = below ? { documentId: below } : next ? tabContent(next) : null;
return stay ? { tab, target, stay } : null;
}
/** The nearest tab that no pane shows: first the tabs after `tab`, then the tabs before it. A closed tab uses the same order. */
function tabAfter(tab: EditorTab) {
const index = workingTabs.indexOf(tab);
const free = (item: EditorTab) => item !== tab && !paneOf(documentPanes, tabContent(item));
return workingTabs.slice(index + 1).find(free) ?? workingTabs.slice(0, Math.max(index, 0)).reverse().find(free);
}
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, stay } = found;
if (stay) {
if (target.zone !== "center") changePanes(moveToNewPane(documentPanes, target.pane, stay, tabContent(tab), target.zone, crypto.randomUUID()));
return true;
}
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 dragging = $state<"left" | "right" | "bottom" | null>(null);
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 coverKey = $derived(editorPluginVisible && $pluginView && !paneOf(documentPanes, { pluginKey: $pluginView.key }) ? $pluginView.key : null);
type EditorTab = WorkbenchTab & ({ buffer: OpenBuffer } | { plugin: OpenPluginView });
let tabOrder = $state<string[]>([]);
const availableTabs = $derived<EditorTab[]>([
@@ -361,9 +510,7 @@
} catch (reason) { error = String(reason); }
}
const activeTabPath = $derived(editorPluginVisible && $pluginView ? `plugin:${$pluginView.key}` : activePath);
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.
// The working tabs of the header.
const tabBarProps = $derived({ tabs: workingTabs, activePath: activeTabPath, onSelect: selectWorkingTab, onClose: closeTab,
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) });
@@ -409,7 +556,7 @@
documents?.setChrome(next);
}
/** Show Write, Source, or Read in a pane. Write and Source keep a Split view. */
/** Show Write, Source, or Read in a pane. Write and Source keep Read beside. */
function setDocumentView(paneId: string, next: ViewMode) {
focusDocumentPane(paneId);
if (next === "read") { setReading(true, paneId); return; }
@@ -554,6 +701,8 @@
pluginEditorActive.set(false);
focusLine = null;
documents?.select(relPath);
const selected = documents?.active?.id;
if (selected) documentPanes = showInActivePane(documentPanes, { documentId: selected });
focusDocumentPane(documentPanes.active, true);
status = documents?.active?.kind === "empty" ? $t("New tab") : "";
}
@@ -582,9 +731,14 @@
}
function workingTabActions(item: WorkbenchTab): ActionMenuItem[] {
const tab = workingTabs.find(tab => tab.id === item.id);
const actions = tab && "plugin" in tab ? pluginTabActions(tab.plugin) : [];
if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return actions;
return tab ? [{ label: $t("Open in new window"), icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : [];
if (!tab) return [];
const actions = "plugin" in tab ? pluginTabActions(tab.plugin) : [];
const right: ActionMenuItem = { label: $t("Open to the right"), icon: "split-right", disabled: tabVisible(tab), run: () => openTabToRight(tab) };
// A tab in a pane beside other panes can leave the split. The tab stays open.
const pane = !coverKey && documentPanes.panes.length > 1 ? paneOf(documentPanes, tabContent(tab)) : undefined;
const close: ActionMenuItem[] = pane ? [{ label: $t("Close split"), icon: "split-close", run: () => closeSplit(pane.id) }] : [];
if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return [right, ...close, ...actions];
return [right, ...close, { label: $t("Open in new window"), icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions];
}
async function detachTab(item: WorkbenchTab, keepSource = false) {
const tab = workingTabs.find(tab => tab.id === item.id);
@@ -719,7 +873,7 @@
{ label: $t("Source"), icon: "code", radio: true, checked: viewMode === "source", run: () => setDocumentView(documentPanes.active, "source") },
{ label: $t("Read"), icon: "book", radio: true, checked: viewMode === "read", run: () => setDocumentView(documentPanes.active, "read") },
{ separator: true },
{ label: $t("Split"), icon: "split-right", checked: activeDocumentPane?.split === true && !reading, run: () => setSplitView(documentPanes.active, !(activeDocumentPane?.split && !reading)) },
{ label: $t("Read beside"), icon: "split-right", checked: activeDocumentPane?.split === true && !reading, run: () => setSplitView(documentPanes.active, !(activeDocumentPane?.split && !reading)) },
] },
);
}
@@ -775,21 +929,35 @@
});
}
async function insertImage(file: File, note = buffer): Promise<string | null> {
/** `source` is the web address of the original of a copied image. `file` is its still copy. */
async function insertImage(file: File, note = buffer, source?: string): Promise<string | null> {
if (!note || note.kind !== "text" || !isMarkdownPath(note.relPath)) {
return null;
}
const noteRel = note.relPath;
const current = documents;
try {
const rel = attachmentRel(file.name);
const dataUrl = await readFileDataUrl(file);
const base64 = dataUrl.split(",")[1];
if (!base64) {
return null;
let rel = attachmentRel(file.name);
const stem = rel.replace(/\.[^./]+$/, "");
// The RuneStone browser keeps the bytes of the image that it copied. For a copy from another browser, download the original of a format with frames.
const copied = source ? await copiedImage(source) : undefined;
const copiedExtension = copied ? dataUrlExtension(copied) : undefined;
const download = !copiedExtension && !!source && mayAnimate(source);
// The host sets the extension from the downloaded file. A failed download keeps the still copy.
const downloaded = download && source ? await workspaceSaveImageUrl(source, stem).catch(() => null) : null;
if (downloaded) rel = downloaded;
else {
if (copiedExtension) rel = `${stem}.${copiedExtension}`;
const dataUrl = copied && copiedExtension ? copied : await readFileDataUrl(file);
const base64 = dataUrl.split(",")[1];
if (!base64) {
error = $t("The image file is empty. A browser can give an empty file when the website refuses a download. To add the image, copy it in the RuneStone browser. You can also save the image and add the saved file.");
return null;
}
if (documents !== current || switching) return null;
await workspaceWriteBytes(rel, base64);
if (download) error = $t("The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file.");
}
if (documents !== current || switching) return null;
await workspaceWriteBytes(rel, base64);
if (documents !== current) return null;
session.changed([rel]);
return `![](${"../".repeat(noteRel.split("/").length - 1)}${rel})`;
@@ -928,7 +1096,10 @@
if (!workingTabs.length) return false;
const index = workingTabs.findIndex(tab => tab.relPath === activeTabPath);
const next = (index + (command === "previous-tab" ? -1 : 1) + workingTabs.length) % workingTabs.length;
selectWorkingTab(workingTabs[next].relPath);
const target = workingTabs[next];
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;
}
case "command-palette": palette = true; return true;
@@ -1161,7 +1332,7 @@
try {
// The layout stays in localStorage on purpose: per-machine view state that is harmless to lose.
const layout = parseWorkbenchLayout(localStorage.getItem(WORKBENCH_LAYOUT_KEY));
({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout);
({ leftOpen, rightOpen, leftWidth, rightWidth, leftView, backlinksOpen } = layout);
if (transferredWindow) { leftOpen = false; rightOpen = false; }
layoutReady = true;
} catch { error = $t("Could not read your layout. Default layout applies for this window."); }
@@ -1194,7 +1365,7 @@
$effect(() => {
if (!layoutReady || transferredWindow) return;
const saved = { leftOpen: narrow.left ? wide.left : leftOpen, rightOpen: narrow.right ? wide.right : rightOpen };
try { saveWorkbenchLayout(localStorage, { ...saved, leftWidth, rightWidth, leftView }); }
try { saveWorkbenchLayout(localStorage, { ...saved, leftWidth, rightWidth, leftView, backlinksOpen }); }
catch { error = $t("Could not save your layout. Layout changes apply for this window only."); }
});
@@ -1301,7 +1472,7 @@
{leftView}
{sidebarNavigation}
onSelectLeft={selectLeft}
tabBar={{ ...tabBarProps, onDetach: (tab) => { void detachTab(tab); } }}
tabBar={{ ...tabBarProps, onDetach: (tab) => { void detachTab(tab); }, onDragAt: tabDragAt, onDropAt: tabDropAt, onDragEnd: () => { tabDrop = null; } }}
onNewTab={newTab}
canOpenBrowser={!!browserContribution?.newTab}
{browserOpening}
@@ -1331,6 +1502,7 @@
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
{searchRequest}
onOpenFile={(entry, line, target) => void openFile(entry, line, target)}
onOpenRight={(entry) => void openToRight(entry, documentPanes.active)}
onCreated={(entry) => { void openCreatedFile(entry); }}
onSaveTemplate={(entry) => { void saveTemplate(entry); }}
onManageTemplates={() => templateManager = true}
@@ -1357,13 +1529,14 @@
<div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}>
<DocumentArea
bind:this={documentArea}
bind:pluginPaneComponents
bind:paneComponents
{editorPluginVisible}
split={!!activeSplit}
{pluginBounds}
tabBar={tabBarProps}
pluginCover={coverKey !== null}
drop={tabDrop}
onResize={(path, ratio) => { documentPanes = resizeDocumentPanes(documentPanes, path, ratio); }}
{documentViews}
layout={documentPanes.layout}
activePane={documentPanes.active}
{documents}
{tabs}
@@ -1379,7 +1552,7 @@
onQuickOpen={() => quickOpen = true}
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
{onChange}
onInsertImage={(file, tab) => insertImage(file, tab)}
onInsertImage={(file, tab, source) => insertImage(file, tab, source)}
onRenameTitle={renameNoteTitle}
tableActions={(pane) => ({ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) })}
linkActions={(pane) => ({
@@ -1448,6 +1621,7 @@
}}
showBacklinks={buffer?.kind === "text" && isMarkdownPath(buffer.relPath) && !editorPluginVisible}
{backlinks}
bind:backlinksOpen
{session}
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); }
.header-left :global(.icon-btn), .header-right :global(.icon-btn) { flex-shrink: 0; }
.header-right { justify-content: flex-end; }
/* 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: 0 1 120px; min-width: 48px; align-self: stretch; }
/* 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. */
.window-drag-space { flex: 1 0 48px; align-self: stretch; }
/* The tab strip keeps room for one readable tab. It shrinks first, so the drag area shrinks only after it. */
/* The tab strip uses all space up to the drag area, then scrolls. It keeps room for one readable tab. */
.header-center :global(.tabs) {
flex: 0 1000 auto;
flex: 0 1 auto;
align-self: stretch;
min-width: 120px;
min-height: 28px;
+15
View File
@@ -23,9 +23,24 @@
const folderName = (path: string) => path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path;
const removeTooltip = (node: HTMLElement) => ({ destroy: attachTooltip(node, () => tr("Remove from recent workspaces")) });
const destination = $derived(parent ? `${parent.replace(/[\\/]+$/, "")}${parent.includes("\\") ? "\\" : "/"}${name.trim()}` : $t("Choose where to create your workspace."));
// A press on the anchor closes the open menu before the click. Then the click must not open it again.
let pressedOpen = false;
$effect(() => {
const target = anchor;
if (!target) return;
const press = () => {
pressedOpen = menu.matches(":popover-open");
// The click comes in the same task as the release. A drag away from the anchor gives no click.
if (pressedOpen) window.addEventListener("pointerup", () => setTimeout(() => { pressedOpen = false; }), { once: true });
};
target.addEventListener("pointerdown", press);
return () => target.removeEventListener("pointerdown", press);
});
export async function show() {
if (busy || creating) return;
if (pressedOpen) { pressedOpen = false; return; }
if (menu.matches(":popover-open")) { menu.hidePopover(); return; }
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
error = ""; loading = true;
+5
View File
@@ -28,6 +28,11 @@
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) {
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") {
+17
View File
@@ -56,6 +56,23 @@ function encode(section: SettingsSection, value: unknown): string {
return section === 'language' && typeof value === 'string' ? value : JSON.stringify(value);
}
// The same value with the object keys in alphabetical order, at every depth.
function sortKeys(value: unknown): unknown {
if (Array.isArray(value)) return value.map(sortKeys);
if (!value || typeof value !== 'object') return value;
const source = value as Record<string, unknown>;
return Object.fromEntries(Object.keys(source).sort().map(key => [key, sortKeys(source[key])]));
}
/**
* True when two section values hold the same data. The key order of objects does not matter.
* The desktop host stores the keys in alphabetical order, so a value that comes back from the host
* can have a different key order than the value that a window saved.
*/
export function sameSettingsValue(a: unknown, b: unknown): boolean {
return JSON.stringify(sortKeys(a)) === JSON.stringify(sortKeys(b));
}
function notify(section: SettingsSection) {
for (const callback of [...subscribers.get(section) ?? []]) {
try { callback(); } catch (reason) { console.error(`A ${section} settings subscriber failed.`, reason); }
+3 -2
View File
@@ -3,7 +3,7 @@
import { syncTableFormulas } from '$lib/formulas';
import { syncFileTitle } from '$lib/editor/fileTitle';
import { onMount } from 'svelte';
import { onSettingsChange, readSection, writeSection } from '$lib/settings/store';
import { onSettingsChange, readSection, sameSettingsValue, writeSection } from '$lib/settings/store';
import { applyAppearance, readAppearance } from './appearance';
onMount(() => {
const stopLocale = syncLocale();
@@ -14,7 +14,8 @@
const stored = readSection('appearance');
const appearance = readAppearance();
// Save the normalized value, for example a new ID for a renamed theme.
if (stored !== undefined && JSON.stringify(stored) !== JSON.stringify(appearance)) {
// Ignore the key order: the host sorts the keys, so a text compare saves again in each window without end.
if (stored !== undefined && !sameSettingsValue(stored, appearance)) {
writeSection('appearance', appearance).catch(() => { /* The normalized value applies until the next save. */ });
}
applyAppearance(appearance);
+4
View File
@@ -34,6 +34,8 @@
<path d="m6 9 6 6 6-6" />
{:else if icon === "chevrons-up-down"}
<path d="m7 15 5 5 5-5M7 9l5-5 5 5" />
{:else if icon === "scroll"}
<path d="M12 3v5m-3-2 3-3 3 3M12 21v-5m-3 2 3 3 3-3M3 12h5m-2-3-3 3 3 3M21 12h-5m2-3 3 3-3 3" /><circle cx="12" cy="12" r="1" />
{:else if icon === "maximize"}
<path d="M8 3H3v5M16 3h5v5M21 16v5h-5M8 21H3v-5" />
{:else if icon === "minimize"}
@@ -154,6 +156,8 @@
<path d="M3 4v16M21 4v16M7 12h10M10 9l-3 3 3 3M14 9l3 3-3 3" />
{:else if icon === "rotate"}
<path d="M20 7v5h-5" /><path d="M20 12a8 8 0 1 0-2 6" />
{:else if icon === "split-close"}
{@html actionIcons["split-close"]}
{/if}
</svg>
<style>
+3 -1
View File
@@ -23,6 +23,7 @@
| "more"
| "chevron-down"
| "chevrons-up-down"
| "scroll"
| "up"
| "down"
| "maximize"
@@ -61,7 +62,8 @@
| "zoom-in"
| "zoom-out"
| "fit-width"
| "rotate";
| "rotate"
| "split-close";
type Props = {
icon: IconName;
+10
View File
@@ -83,6 +83,16 @@ export function workspaceWriteBytes(rel: string, base64: string): Promise<void>
return invoke("workspace_write_bytes", { rel, base64 });
}
/** Download a web image to `rel` plus the extension of its format. Returns the path of the new file. */
export function workspaceSaveImageUrl(url: string, rel: string): Promise<string> {
return invoke("workspace_save_image_url", { url, rel });
}
/** Download a web image. Returns it as a data URL. */
export function workspaceDownloadImage(url: string): Promise<string> {
return invoke("workspace_download_image", { url });
}
export type CopyResult = {
name: string;
rel_path: string;
+16
View File
@@ -0,0 +1,16 @@
/**
* The original of the last image that Copy image took in the RuneStone browser.
* The browser takes the bytes that the page loaded, so a pasted GIF keeps its frames.
* This also works when the website refuses a second download of the image.
*/
let last: { url: string; data: Promise<string | undefined> } | undefined;
/** Keep the original of a copied image. `data` gives its data URL. */
export function keepCopiedImage(url: string, data: Promise<string | undefined>) {
last = { url, data: data.catch(() => undefined) };
}
/** The data URL of the original of `url`, when the RuneStone browser copied that image last. */
export async function copiedImage(url: string): Promise<string | undefined> {
return last?.url === url ? last.data : undefined;
}
+114 -23
View File
@@ -1,30 +1,40 @@
import { paneBounds, removePane, splitPane, type SplitLayout } from "./splitLayout.ts";
import { paneBounds, removePane, setSplitRatio, splitPane, type SplitLayout, type SplitPath } from "./splitLayout.ts";
/** `reading` shows only the Read view. `split` shows the Read view beside the editor. A pane never has both. */
export type DocumentPane = { id: string; documentId: string | null; reading: boolean; split: boolean };
/**
* A pane shows one document or one plugin editor view, for example a browser tab. A pane never shows both.
* `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 };
/** 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 {
return { layout: "document-main", panes: [{ id: "document-main", documentId: null, reading: false, split: false }], active: "document-main" };
return { layout: "document-main", panes: [emptyPane("document-main")], active: "document-main" };
}
export function selectPane(state: DocumentPanes, id: string): DocumentPanes {
return state.active === id || !state.panes.some(pane => pane.id === id) ? state : { ...state, active: id };
}
/** Tabs own documents. Panes keep only a reference and local viewing state. */
export function syncDocumentPanes(state: DocumentPanes, live: readonly string[], selected: string | null): DocumentPanes {
const ids = new Set(live);
let panes = state.panes.map(pane => pane.documentId && !ids.has(pane.documentId) ? { ...pane, documentId: null, reading: false, split: false } : 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 } : pane);
}
/** The pane that shows the content, if a pane shows it. */
export function paneOf(state: DocumentPanes, content: PaneContent): DocumentPane | undefined {
return state.panes.find(pane => "documentId" in content ? pane.documentId === content.documentId : pane.pluginKey === content.pluginKey);
}
/** Remove the panes that became empty. The last pane always stays. */
function collapse(state: DocumentPanes, panes: DocumentPane[], active: string): DocumentPanes {
let layout = state.layout;
for (const pane of panes) {
if (pane.documentId === null && panes.length > 1) {
if (pane.documentId === null && pane.pluginKey === null && panes.length > 1) {
const next = removePane(layout, pane.id);
if (next !== null) { layout = next; panes = panes.filter(item => item.id !== pane.id); }
}
@@ -34,14 +44,49 @@ export function syncDocumentPanes(state: DocumentPanes, live: readonly string[],
return { layout, panes, active };
}
export function splitDocumentPane(state: DocumentPanes, source: string, documentId: string, paneId: string): DocumentPanes {
const existing = state.panes.find(pane => pane.documentId === documentId);
/**
* Tabs own documents. Panes keep only a reference and local viewing state.
* 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) };
}
/** The side of a pane where a new pane opens. */
export type PaneSide = "right" | "down" | "left";
/** 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: PaneSide = "right"): DocumentPanes {
const existing = paneOf(state, content);
if (existing) return selectPane(state, existing.id);
if (!state.panes.some(pane => pane.id === source) || state.panes.some(pane => pane.id === paneId)) return state;
return {
layout: splitPane(state.layout, source, paneId, "right"),
panes: [...state.panes, { id: paneId, documentId, reading: false, split: false }], active: paneId,
};
const layout = splitPane(state.layout, source, paneId, direction === "left" ? "right" : direction, direction === "left");
return { layout, panes: [...state.panes, filled(paneId, content)], 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 {
@@ -50,15 +95,61 @@ export function closeDocumentPane(state: DocumentPanes, id: string): DocumentPan
if (layout === null) return state;
const bounds = paneBounds(state.layout);
const panes = state.panes.filter(pane => pane.id !== id);
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 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) => distance(a) - distance(b))[0];
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 left, right, or bottom side. */
export type PaneDrop = "center" | PaneSide;
/**
* 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);
}
/**
* Move the content of the `source` pane to a new pane beside it. The `source` pane then shows `stay`.
* `stay` is content that no other pane shows. `content` is the content of `source`, or content that no pane shows,
* for example a plugin view that covers the area.
*/
export function moveToNewPane(state: DocumentPanes, source: string, stay: PaneContent, content: PaneContent, zone: PaneSide, paneId: string): DocumentPanes {
const holder = paneOf(state, stay), shown = paneOf(state, content);
if (!state.panes.some(pane => pane.id === source) || (holder && holder.id !== source) || (shown && shown.id !== source) || (holder && shown)) return state;
const panes = holder ? state.panes : state.panes.map(pane => pane.id === source ? filled(source, stay) : pane);
return splitWithContent({ ...state, panes }, source, 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 {
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, reading, split: reading ? false : pane.split } : pane) };
}
/** Show or hide the Read view beside the editor. Split ends the Read-only view. */
/** Show or hide the Read view beside the editor. Read beside ends the Read-only view. */
export function splitDocumentView(state: DocumentPanes, id: string, split: boolean): DocumentPanes {
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, split, reading: split ? false : pane.reading } : pane) };
}
+44
View File
@@ -0,0 +1,44 @@
/**
* 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;
}
+33
View File
@@ -96,6 +96,39 @@ export function attachmentRel(fileName: string): string {
return `attachments/${stamp}-${crypto.randomUUID()}-${safe}`;
}
const ENTITIES: Record<string, string> = { amp: "&", quot: '"', apos: "'", "#39": "'", lt: "<", gt: ">" };
/**
* The web address of a copied image. A browser puts only the first frame on the clipboard,
* with HTML that names the original file.
*/
export function pastedImageSource(html: string): string | undefined {
const images = [...html.matchAll(/<img\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi)];
if (images.length !== 1) return undefined;
const [, double, single, bare] = images[0];
const source = (double ?? single ?? bare).trim().replace(/&(amp|quot|apos|#39|lt|gt);/g, (_, name: string) => ENTITIES[name]);
try {
const url = new URL(source);
return /^https?:$/.test(url.protocol) ? url.href : undefined;
} catch {
return undefined;
}
}
/** A GIF, WebP, or AVIF address. These formats can have more frames, so the original is worth a download. */
export function mayAnimate(source: string): boolean {
return /\.(?:gif|webp|avif)$/i.test(new URL(source).pathname);
}
const EXTENSIONS: Record<string, string> = {
"image/gif": "gif", "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/avif": "avif", "image/bmp": "bmp",
};
/** The file extension of an image data URL, or undefined for another type. */
export function dataUrlExtension(data: string): string | undefined {
return EXTENSIONS[/^data:([^;,]+)[;,]/.exec(data)?.[1] ?? ""];
}
export function imageFiles(data: DataTransfer | null): File[] {
return [...(data?.files ?? [])].filter(file => isImagePath(file.name));
}
+3 -1
View File
@@ -5,6 +5,7 @@ import { inlineMathEnd } from "./inlineMath.ts";
import { activeTableFormulas } from "../formulas/index.ts";
import { hasTableDelimiter } from "../editor/markdownTable.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 });
markdown.use(footnotes);
@@ -162,7 +163,8 @@ markdown.renderer.rules.image = (tokens, index, _options, env, renderer) => {
const alt = renderer.renderInlineAsText(token.children || [], markdown.options, env);
// 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>`;
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">`;
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"}"${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_close = () => '</table></div>\n';
+53 -7
View File
@@ -1,13 +1,20 @@
export type SplitLayout = string | { direction: "right" | "down"; first: SplitLayout; second: SplitLayout };
/** 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; ratio?: 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 {
return typeof tree === "string" ? tree === key : containsPane(tree.first, key) || containsPane(tree.second, key);
}
export function splitPane(tree: SplitLayout, key: string, next: string, direction: "right" | "down"): SplitLayout {
if (typeof tree === "string") return tree === key ? { direction, first: tree, second: next } : tree;
return { ...tree, first: splitPane(tree.first, key, next, direction), second: splitPane(tree.second, key, next, direction) };
/** Split the `key` pane. The `next` pane goes after it, or before it when `before` is true. */
export function splitPane(tree: SplitLayout, key: string, next: string, direction: "right" | "down", before = false): SplitLayout {
if (typeof tree === "string") return tree === key ? (before ? { direction, first: next, second: tree } : { direction, first: tree, second: next }) : tree;
return { ...tree, first: splitPane(tree.first, key, next, direction, before), second: splitPane(tree.second, key, next, direction, before) };
}
export function removePane(tree: SplitLayout, key: string): SplitLayout | null {
@@ -18,8 +25,47 @@ 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> {
if (typeof tree === "string") return { [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; }
const [a, b] = sides(tree, bounds);
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,6 +6,8 @@ export interface WorkbenchLayout {
leftWidth: number;
rightWidth: number;
leftView: "files" | "search" | "bookmarks";
/** The Backlinks section below the outline is expanded. */
backlinksOpen: boolean;
}
export const DEFAULT_WORKBENCH_LAYOUT: Readonly<WorkbenchLayout> = {
@@ -14,6 +16,7 @@ export const DEFAULT_WORKBENCH_LAYOUT: Readonly<WorkbenchLayout> = {
leftWidth: 260,
rightWidth: 240,
leftView: "files",
backlinksOpen: true,
};
function width(value: unknown, fallback: number): number {
@@ -29,6 +32,7 @@ export function parseWorkbenchLayout(raw: string | null): WorkbenchLayout {
leftWidth: width(value?.leftWidth, DEFAULT_WORKBENCH_LAYOUT.leftWidth),
rightWidth: width(value?.rightWidth, DEFAULT_WORKBENCH_LAYOUT.rightWidth),
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 }; }
}
+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 "Split" (src/lib/layout/ViewModes.svelte).
* Choose "Write", "Source", or "Read" in the view control of a document pane, or toggle "Read beside" (src/lib/layout/ViewModes.svelte).
* `scope` is the page, or a pane locator when the window shows more than one document pane.
*/
export async function chooseView(scope, name) {
if (name === "Split") return scope.locator(".chrome-bar").getByRole("button", { name: "Split", exact: true }).click();
if (name === "Read beside") return scope.locator(".chrome-bar").getByRole("button", { name: "Read beside", exact: true }).click();
return scope.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name, exact: true }).click();
}
+5
View File
@@ -88,6 +88,11 @@ function pmCommands(test) {
else workspace.folders.add(rel);
return null;
}),
// The download of a copied web image: a 1 by 1 GIF. An address with "offline" fails.
workspace_download_image: ({ url }) => {
if (url.includes("offline")) throw new Error("Cannot reach the image server");
return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
},
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false,
@@ -103,11 +103,11 @@ await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
assert.deepEqual(await background.boundingBox(), beforeScroll);
await page.screenshot({ path: `${output}/${theme}-reader.png` });
// Split shows the Write editor beside Read.
await chooseView(page, 'Split');
await chooseView(page, 'Read beside');
await page.locator('.live-writer .cm-content').waitFor();
assert.equal(await style(page.locator('.live-writer .cm-editor').first(), 'backgroundColor'), 'rgba(0, 0, 0, 0)');
await page.screenshot({ path: `${output}/${theme}-split.png` });
await chooseView(page, 'Split');
await chooseView(page, 'Read beside');
await chooseView(page, 'Source');
await page.locator('.source-editor .cm-content').waitFor();
await page.screenshot({ path: `${output}/${theme}-ide.png` });
+46 -1
View File
@@ -52,9 +52,19 @@ async function startEngine() {
return engine;
}
// A two-frame GIF that the fixture gives only one time, as some image hosts do.
const onceGif = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAACAkQBACH5BAAKAAAALAAAAAABAAEAAAICTAEAOw==', 'base64');
/** Serve an empty page. A tab on about:blank shows the host background instead of frames (docs/ui-design.md:218). */
async function startFixture() {
const server = createServer((_request, response) => { response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>'); });
let gifServed = false;
const server = createServer((request, response) => {
if (request.url === '/once.gif') {
response.writeHead(200, { 'content-type': gifServed ? 'text/html' : 'image/gif' });
response.end(gifServed ? 'Invalid request' : onceGif); gifServed = true; return;
}
response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
}
@@ -120,6 +130,33 @@ await runSmoke('browser/interaction', async ({ browser }) => {
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v');
await expectRemote('document.querySelector("#typing").value', 'https://example.com/');
// Copy image keeps the GIF bytes that the page loaded, also when the website refuses a second request.
const gifUrl = `${fixture.url}once.gif`;
await evaluate(`document.body.innerHTML='<img id="gif" src="${gifUrl}" style="position:absolute;left:40px;top:300px;width:80px;height:80px">';true;`);
await expectRemote('document.querySelector("#gif").complete && document.querySelector("#gif").naturalWidth', 1);
await page.mouse.click(initialBox.x + 80, initialBox.y + 340, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy image', exact: true }).click();
const copied = await page.evaluate(async url => (await import('/src/lib/workspace/copiedImage.ts')).copiedImage(url), gifUrl);
assert.equal(copied, `data:image/gif;base64,${onceGif.toString('base64')}`);
assert.equal(commands.filter(call => call.command === 'copiedImage').length, 1);
// A new browser tab opens in front. Close it, so that the next steps use the first tab again.
async function expectTab(url) {
for (let attempt = 0; attempt < 100 && !(await rpc('state')).tabs.some(tab => tab.url === url); attempt++) await page.waitForTimeout(50);
assert.ok((await rpc('state')).tabs.some(tab => tab.url === url), `A new browser tab opens ${url}`);
await page.keyboard.press('Control+w');
for (let attempt = 0; attempt < 100 && (await rpc('state')).tabs.length > 1; attempt++) await page.waitForTimeout(50);
assert.equal((await rpc('state')).tabs.length, 1);
await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor();
}
await page.mouse.click(initialBox.x + 80, initialBox.y + 340, { button: 'right' });
await page.getByRole('menuitem', { name: 'Open image in new tab', exact: true }).click();
await expectTab(gifUrl);
// A middle-click on a link opens the link in a new tab instead of scrolling.
const linked = `${fixture.url}linked`;
await evaluate(`document.body.innerHTML='<a href="${linked}" style="position:absolute;left:40px;top:300px;display:block;width:200px;height:40px">Linked page</a>';true;`);
await page.mouse.click(initialBox.x + 100, initialBox.y + 320, { button: 'middle' });
await expectTab(linked);
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'A middle-click on a link does not keep scrolling');
await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`);
await page.locator('.surface img').waitFor();
await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });
@@ -143,6 +180,14 @@ await runSmoke('browser/interaction', async ({ browser }) => {
const box = await surface.boundingBox();
const x = box.x + 220, y = box.y + 180;
await page.mouse.click(x, y, { button: 'middle' });
// The marker draws the four-way scroll icon, not a text glyph that depends on the font.
const marker = page.locator('.scroll-anchor');
assert.equal(await marker.locator('svg path').count(), 1);
assert.equal(await marker.evaluate(node => node.textContent.trim()), '');
for (const theme of ['light', 'dark']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).applyAppearance({ theme: 'default', mode }), theme);
await page.screenshot({ path: path.join(output, `scroll-marker-${theme}.png`), clip: { x: x - 30, y: y - 30, width: 60, height: 60 } });
}
await page.mouse.move(x + 90, y + 120);
await page.waitForTimeout(1500);
const scrolled = await evaluate('({x:scrollX,y:scrollY})');
+52 -1
View File
@@ -28,6 +28,13 @@ await runSmoke("editor/images", async ({ page }) => {
if (test.failWrite) throw new Error("Image write failed");
workspace.files.set(args.rel, args.base64);
},
// The download of a copied web image. The host adds the extension of the downloaded format.
workspace_save_image_url: args => {
if (args.url.includes("offline")) throw new Error("Cannot reach the image server");
const rel = args.rel + ".gif";
workspace.files.set(rel, btoa('<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>'));
return rel;
},
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);
@@ -196,5 +203,49 @@ await runSmoke("editor/images", async ({ page }) => {
await page.waitForFunction(() => document.querySelector(".md-image-frame img"));
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/second.md").includes("pasted.svg"));
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode and undo passed.");
// A browser copies the still first frame of a GIF. RuneStone saves the original file from the address in the HTML.
async function pasteWebImage(src) {
await page.locator(".cm-content").evaluate((element, src) => {
const data = new DataTransfer();
data.items.add(new File(["png"], "image.png", { type: "image/png" }));
data.setData("text/html", `<html><body>\r\n<!--StartFragment--><img src="${src}"/><!--EndFragment-->\r\n</body>\r\n</html>`);
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
}, src);
}
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
const writes = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_write_bytes").length);
const writesBefore = await writes();
await pasteWebImage("https://media.example.com/cat.gif?size=large&amp;v=2");
await page.waitForFunction(() => /attachments\/[\w-]+-image\.gif\)/.test(window.__CM__.state.doc.toString()));
const download = await page.evaluate(() => window.__TEST__.calls.find(call => call.command === "workspace_save_image_url").args);
assert.equal(download.url, "https://media.example.com/cat.gif?size=large&v=2");
assert.match(download.rel, /^attachments\/[\w-]+-image$/);
assert.equal(await writes(), writesBefore);
// When the download fails, the still copy stays.
await pasteWebImage("https://offline.example.com/cat.gif");
await page.waitForFunction(() => /attachments\/[\w-]+-image\.png\)/.test(window.__CM__.state.doc.toString()));
assert.equal(await writes(), writesBefore + 1);
await page.getByText("The website refused the original image, so RuneStone added only its first frame.", { exact: false }).waitFor();
// The RuneStone browser keeps the bytes of the image that it copied. The website gets no second request.
await page.evaluate(async () => (await import("/src/lib/workspace/copiedImage.ts")).keepCopiedImage("https://offline.example.com/copied.gif",
Promise.resolve("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")));
const downloads = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_save_image_url").length);
const downloadsBefore = await downloads();
await pasteWebImage("https://offline.example.com/copied.gif");
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/-image\.gif\)/g) || []).length === 2);
assert.equal(await downloads(), downloadsBefore);
assert.match(await page.evaluate(() => window.__TEST__.calls.findLast(call => call.command === "workspace_write_bytes").args.rel), /-image\.gif$/);
// An empty file from a browser drag gives a message, not a broken image.
await page.locator(".cm-content").evaluate(element => {
const data = new DataTransfer();
data.items.add(new File([], "viprsr188.gif", { type: "image/gif" }));
const rect = element.getBoundingClientRect();
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 }));
});
await page.getByText("The image file is empty.", { exact: false }).waitFor();
assert.ok(!(await page.evaluate(() => window.__CM__.state.doc.toString())).includes("viprsr188"));
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode, undo, web GIF pastes, copied originals, and empty files passed.");
});
@@ -0,0 +1,145 @@
// 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 });
+96 -8
View File
@@ -1,5 +1,6 @@
// The native PDF Viewer: the file tree marks PDF files without the module, the first PDF tab loads it, and each tab
// renders a page with selectable text, page controls, zoom, rotation, Page Up and Page Down, and Reload.
// renders its pages in one column with selectable text, page controls, zoom, a typed zoom, rotation, scrolling by wheel and
// 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,
// 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.
@@ -78,8 +79,13 @@ await runSmoke("features/pdf", async ({ page }) => {
await rendered("Page 1 of 2");
assert.equal(await loaded(), true, "The first PDF tab loads the module");
await active.getByRole("img", { name: "PDF page 1", exact: true }).waitFor();
assert.match(await active.locator(".textLayer").innerText(), /Page one text selection/);
assert.ok(await active.locator("canvas").evaluate(canvas => {
const sheet = number => active.locator(`.sheet[data-page="${number}"]`);
const scroll = active.locator(".scroll");
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;
let colored = 0;
for (let index = 0; index < data.length; index += 4) if (data[index] < 200 && data[index + 2] > 100) colored++;
@@ -89,6 +95,10 @@ await runSmoke("features/pdf", async ({ page }) => {
assert.equal(await button("Fit width").getAttribute("aria-pressed"), "true");
assert.equal(await button("Previous page").isDisabled(), true);
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.
for (const theme of ["dark", "light"]) {
@@ -119,7 +129,8 @@ await runSmoke("features/pdf", async ({ page }) => {
await rendered("Page 2 of 2");
await active.getByRole("img", { name: "PDF page 2", exact: true }).waitFor();
assert.equal(await button("Next page").isDisabled(), true);
const zoomText = () => active.locator(".zoom").innerText();
const zoomField = active.getByRole("textbox", { name: "Zoom percent", exact: true });
const zoomText = () => zoomField.inputValue();
const before = await zoomText();
await button("Zoom in").click();
await rendered("Page 2 of 2");
@@ -127,13 +138,70 @@ await runSmoke("features/pdf", async ({ page }) => {
assert.equal(await button("Fit width").getAttribute("aria-pressed"), "false");
await button("Rotate clockwise").click();
await rendered("Page 2 of 2");
assert.ok(await active.locator("canvas").evaluate(canvas => canvas.width > canvas.height), "A rotated page is wider than high");
await active.locator(".scroll").focus();
assert.ok(await sheet(2).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();
// 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.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 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");
const input = active.getByRole("spinbutton", { name: "Page number", exact: true });
await input.fill("1");
await input.press("Enter");
await rendered("Page 1 of 2");
@@ -148,6 +216,24 @@ await runSmoke("features/pdf", async ({ page }) => {
assert.equal(await workers(), 2);
await row("Other.PDF").click();
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 tab("Other").waitFor({ state: "detached" });
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 1);
@@ -182,6 +268,8 @@ await runSmoke("features/pdf", async ({ page }) => {
// Reload keeps the page and replaces the worker.
await tab("Sample").click();
await input.fill("2");
await input.press("Enter");
await rendered("Page 2 of 2");
await button("Reload PDF").click();
await rendered("Page 2 of 2");
@@ -225,5 +313,5 @@ await runSmoke("features/pdf", async ({ page }) => {
assert.equal(await tab("Sample").count(), 1);
assert.deepEqual(requests, [], "No network request leaves the app");
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");
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");
}, { timeout: 60000, viewport: { width: 1440, height: 1000 } });
@@ -0,0 +1,90 @@
// 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.");
});
+66
View File
@@ -0,0 +1,66 @@
// Project Management card images: a GIF copied in a web browser keeps its original file. A failed download keeps the still copy.
import assert from "node:assert/strict";
import { runSmoke } from "../_harness/index.mjs";
import { cardPath, fileText, loadWorkspace, openBoard, pane, waitForFile } from "../_harness/pmFixture.mjs";
const imageFile = id => `.runestone/pm/images/${id}.json`;
await runSmoke("features/pmImages", async ({ page }) => {
await loadWorkspace(page);
await openBoard(page, "Roadmap");
await pane(page).locator(".pm-card-title", { hasText: /^Card A$/ }).click();
const editor = page.locator("dialog.pm-card-editor[open]");
await editor.waitFor();
await editor.getByRole("button", { name: "Edit", exact: true }).click();
const description = editor.locator('textarea[aria-label="Details (Markdown)"]');
await description.fill("");
// A browser puts a still PNG on the clipboard, with HTML that names the original GIF.
async function pasteWebImage(src) {
await description.evaluate((element, src) => {
const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="), c => c.charCodeAt(0));
const data = new DataTransfer();
data.items.add(new File([png], "image.png", { type: "image/png" }));
data.setData("text/html", `<html><body><!--StartFragment--><img src="${src}"/><!--EndFragment--></body></html>`);
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
}, src);
}
const reference = name => new RegExp(`!\\[${name.replace(".", "\\.")}\\]\\(pm-image:([0-9a-f-]{36})\\)`);
await pasteWebImage("https://media.example.com/cat.gif");
await page.waitForFunction(() => /!\[image\.gif\]\(pm-image:/.test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value));
const download = await page.evaluate(() => window.__TEST__.calls.find(call => call.command === "workspace_download_image").args);
assert.equal(download.url, "https://media.example.com/cat.gif");
// When the download fails, the card gets the still PNG.
await pasteWebImage("https://offline.example.com/cat.gif");
await page.waitForFunction(() => /!\[image\.png\]\(pm-image:/.test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value));
await editor.getByText("The website refused the original image, so RuneStone added only its first frame.", { exact: false }).waitFor();
// The RuneStone browser keeps the bytes of the image that it copied. The website gets no second request.
await page.evaluate(async () => (await import("/src/lib/workspace/copiedImage.ts")).keepCopiedImage("https://offline.example.com/copied.gif",
Promise.resolve("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")));
const downloads = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_download_image").length);
const downloadsBefore = await downloads();
await pasteWebImage("https://offline.example.com/copied.gif");
await page.waitForFunction(() => (document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value.match(/!\[image\.gif\]/g) || []).length === 2);
assert.equal(await downloads(), downloadsBefore);
assert.equal(await editor.getByText("The website refused the original image", { exact: false }).count(), 0, "A kept original clears the message");
// An empty file from a browser drag gives a message, not the size limit.
await description.evaluate(element => {
const data = new DataTransfer();
data.items.add(new File([], "viprsr188.gif", { type: "image/gif" }));
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data }));
});
await editor.getByText("The image file is empty.", { exact: false }).waitFor();
assert.equal(await editor.getByText("Use an image between 1 byte and 50 MiB.").count(), 0);
await editor.locator(".pm-description-actions").getByRole("button", { name: "Save", exact: true }).click();
await waitForFile(page, cardPath("card-a"), /pm-image:.*\n?[\s\S]*pm-image:/);
const body = await fileText(page, cardPath("card-a"));
const gif = reference("image.gif").exec(body)[1], png = reference("image.png").exec(body)[1];
assert.match(await fileText(page, imageFile(gif)), /"data":"data:image\/gif;base64,R0lGOD/);
assert.match(await fileText(page, imageFile(png)), /"data":"data:image\/png;base64,iVBOR/);
console.log("PASS: a pasted web GIF keeps its original file, a copied original needs no download, and failures explain the cause");
});
@@ -0,0 +1,38 @@
// Project Management label colors: each color choice of Manage labels shows its color, and the card title keeps its own field style, in both themes.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke } from "../_harness/index.mjs";
import { loadWorkspace, openBoard, pane, setTheme } from "../_harness/pmFixture.mjs";
const rgb = hex => `rgb(${hex.slice(1).match(/../g).map(value => parseInt(value, 16)).join(", ")})`;
await runSmoke("features/pmLabelColors", async ({ page }) => {
const output = await outputDir("features/pmLabelColors");
await loadWorkspace(page);
await openBoard(page, "Roadmap");
await pane(page).locator(".pm-card-title", { hasText: /^Card A$/ }).click();
const editor = page.locator("dialog.pm-card-editor[open]");
await editor.waitFor();
// The card title is a transparent field. The default field rule of Project Management does not replace its background.
const title = editor.getByRole("textbox", { name: "Title", exact: true });
assert.equal(await title.evaluate(input => getComputedStyle(input).backgroundColor), "rgba(0, 0, 0, 0)");
await editor.getByRole("group", { name: "Card details", exact: true }).getByRole("button", { name: "Labels", exact: true }).click();
await page.getByRole("dialog", { name: "Choose labels", exact: true }).getByRole("button", { name: "Manage labels", exact: true }).click();
const manager = page.getByRole("dialog", { name: "Manage labels", exact: true });
await manager.waitFor();
const bug = manager.getByRole("group", { name: "Label Bug", exact: true });
const swatches = await bug.locator("input.pm-color-swatch").evaluateAll(inputs =>
inputs.map(input => ({ name: input.getAttribute("aria-label"), color: input.style.getPropertyValue("--pm-swatch-color"), shown: getComputedStyle(input).backgroundColor })));
assert.equal(swatches.length, 16);
for (const swatch of swatches) assert.equal(swatch.shown, rgb(swatch.color), `${swatch.name} shows its color`);
await bug.getByRole("radio", { name: "Blue", exact: true }).check();
await manager.locator(".pm-label-badge", { hasText: /^Bug$/ }).waitFor();
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await bug.screenshot({ path: path.join(output, `label-colors-${theme}.png`) });
}
console.log("PASS: label color choices and the card title field");
});
+5 -3
View File
@@ -33,9 +33,9 @@ await runSmoke("find/documentFind", async ({ page }) => {
async function onePanel() {
assert.equal(await page.locator('.rs-find-bar:visible').count(), 1);
assert.equal(await page.locator('.cm-search').count(), 0, 'No default CodeMirror search panel');
const bar = await page.locator('.rs-find-bar:visible').boundingBox();
const pane = await page.locator('.editor.pane-active').boundingBox();
assert.ok(Math.abs(bar.width - pane.width) < 3, 'Find spans the document pane');
// Read both widths in one task. Two separate reads can cross a layout change.
const [bar, pane] = await page.locator('.rs-find-bar:visible').evaluate(node => [node, node.closest('.editor.pane-active')].map(element => element.getBoundingClientRect().width));
assert.ok(Math.abs(bar - pane) < 3, 'Find spans the document pane');
}
async function sourceEditor() {
await page.waitForFunction(() => !!document.querySelector('.source-editor .cm-content'));
@@ -120,6 +120,8 @@ await runSmoke("find/documentFind", async ({ page }) => {
await page.keyboard.press('F3');
await page.screenshot({ path: `${output}/source-replace-${theme}.png` });
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();
assert.equal(await page.locator('.rs-find-bar').evaluate(node => node.scrollWidth <= node.clientWidth), true);
await page.screenshot({ path: `${output}/source-narrow-${theme}.png` });
+81
View File
@@ -0,0 +1,81 @@
// 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
@@ -0,0 +1,202 @@
// 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 });

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