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
141 changed files with 3915 additions and 503 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. Git, Background, Terminal, PDF Viewer, and Project Management are native features with an off switch in Settings → Features (`src/lib/features/`). They do not use the plugin API.
Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_CSV_Viewer`. Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_CSV_Viewer`.
The [development guide](docs/development.md#architecture) maps the source folders. The [development guide](docs/development.md#architecture) maps the source folders.
The public repository is `https://github.com/KnottyWyvern-GH/RuneStone`. Its releases page holds the installers, the browser engine ZIPs, and the SDK packages.
## Skills ## 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.
+14 -14
View File
@@ -4,29 +4,25 @@ RuneStone is a desktop workspace for Markdown notes, code, and project work that
## Install and start ## Install and start
Download the installer for your computer. On Windows 10 or 11 (x64):
| Platform | Installer | Status | 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.
| Windows 10 or 11, x64 | [RuneStone_0.1.49_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.49/RuneStone_0.1.49_x64-setup.exe) | Primary platform | 3. Open RuneStone from the Start menu.
| 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.44_amd64.deb](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_amd64.deb) | Experimental: built on Ubuntu 26.04.1, needs GLIBC 2.39 or newer |
- **Windows:** Open the installer and complete setup. Then open RuneStone from the Start menu. The built-in browser needs a separate engine download of about 160 MB. A browser tab offers it on first use.
- **macOS:** Open the disk image and drag RuneStone into Applications. Then open RuneStone from Applications.
- **Linux:** Run `sudo apt install ./RuneStone_0.1.44_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.
For checksums, updates, and reinstalls, see [Installation and updates](docs/installation.md). For checksums, updates, and reinstalls, see [Installation and updates](docs/installation.md).
macOS and Linux have no 1.0.0 package. Build RuneStone from source on these systems. See [Build Linux packages](docs/builds.md#build-linux-packages) or [macOS packages](docs/builds.md#macos-packages).
## What you can do ## What you can do
- Write Markdown with live formatting, editable tables, table formulas, images, and Mermaid diagrams. - Write Markdown with live formatting, editable tables, table formulas, images, and Mermaid diagrams.
- Switch between the Write, Source, Read, and Split views. - Switch between the Write, Source, Read, and Split views.
- Find files, search a workspace, and resolve changes that other tools make to your files. - Find files, search a workspace, and resolve changes that other tools make to your files.
- Open web pages in browser tabs beside your documents. - Open web pages in browser tabs beside your documents.
- Add optional plugins, such as Terminal, Git, Project Management, PDF Viewer, and CSV Viewer. - Use Git source control, a terminal, a PDF viewer, Project Management boards, and a background slideshow. Each one has an off switch in **Settings → Features**.
- Add optional plugins from plugin ZIP files.
## Find help ## Find help
@@ -47,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. - Read the [interface design reference](docs/ui-design.md) before you change the interface.
- See [product boundaries](docs/development.md#product-boundaries) for exclusions and architecture constraints. - See [product boundaries](docs/development.md#product-boundaries) for exclusions and architecture constraints.
## License
RuneStone uses the [Apache License 2.0](LICENSE). See also [NOTICE](NOTICE) and the [third-party notices](THIRD_PARTY_NOTICES.md).
## Maintainer ## Maintainer
[kwyvern-gh](https://github.com/kwyvern-gh) [KnottyWyvern-GH](https://github.com/KnottyWyvern-GH)
+1 -2
View File
@@ -1,7 +1,6 @@
# Third-party notices # 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 RuneStone app includes the third-party packages below. The browser engine has its own notices in [browser-runtime/THIRD_PARTY_NOTICES.md](browser-runtime/THIRD_PARTY_NOTICES.md).
The license texts follow the table. The browser engine has its own notices in [browser-runtime/THIRD_PARTY_NOTICES.md](browser-runtime/THIRD_PARTY_NOTICES.md).
| Package | Version | License | Source | Used by | | Package | Version | License | Source | Used by |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "runestone-browser", "name": "runestone-browser",
"version": "0.1.8", "version": "0.1.11",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "runestone-browser", "name": "runestone-browser",
"version": "0.1.8", "version": "0.1.11",
"dependencies": { "dependencies": {
"@ghostery/adblocker": "2.18.2", "@ghostery/adblocker": "2.18.2",
"ipaddr.js": "2.3.0" "ipaddr.js": "2.3.0"
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "runestone-browser", "name": "runestone-browser",
"version": "0.1.8", "version": "0.1.11",
"private": true, "private": true,
"description": "Isolated browser runtime included with RuneStone", "description": "Isolated browser runtime included with RuneStone",
"type": "module", "type": "module",
+20
View File
@@ -5,7 +5,27 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import electron from 'electron'; import electron from 'electron';
const directory = await mkdtemp(path.join(os.tmpdir(), 'runestone-plugin-browser-')); 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) => { 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') { if (req.url === '/picture.png') {
res.writeHead(200, { 'Content-Type': 'image/png' }); res.writeHead(200, { 'Content-Type': 'image/png' });
return res.end(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII=', 'base64')); 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); pageFocusStates.set(wc, enabled);
if (enabled) wc.focus(); 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) { function emulateViewport(item) {
if (!item.viewport) return; if (!item.viewport) return;
const { width, height } = item.viewport, scale = item.scale; const { width, height } = item.viewport, scale = item.scale;
@@ -141,7 +166,9 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
changed(); 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('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-title-updated', (_event, title) => { item.title = title.slice(0, 200); changed(); });
wc.on('page-favicon-updated', (_event, urls) => { wc.on('page-favicon-updated', (_event, urls) => {
@@ -248,7 +275,13 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
switch (args.action) { switch (args.action) {
case 'copyLink': if (context.linkURL) clipboard.writeText(context.linkURL); break; case 'copyLink': if (context.linkURL) clipboard.writeText(context.linkURL); break;
case 'copyImageAddress': if (context.srcURL) clipboard.writeText(context.srcURL); 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 'openExternal': if (context.linkURL) await openExternal(context.linkURL); break;
case 'saveImage': case 'saveLink': { case 'saveImage': case 'saveLink': {
const url = args.action === 'saveImage' ? context.srcURL : context.linkURL; const url = args.action === 'saveImage' ? context.srcURL : context.linkURL;
@@ -259,6 +292,22 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
} }
return null; 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': { case 'input': {
const current = tab(args.tabId), wc = current.view.webContents; const current = tab(args.tabId), wc = current.view.webContents;
const input = args.input; 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 assert.rejects(engine.command('contextAction', { tabId: first, token: 'expired', action: 'saveImage' }), /no longer available/);
await wc.executeJavaScript('document.querySelector("#save-image").remove();true;'); 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'); 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'); await until(async () => await wc.executeJavaScript("getComputedStyle(document.querySelector('.advertisement')).display") === 'none');
assert.equal(await wc.executeJavaScript('typeof window.adExecuted'), 'undefined'); assert.equal(await wc.executeJavaScript('typeof window.adExecuted'), 'undefined');
passed.push('network and cosmetic ad blocking remain active'); 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.on('window-all-closed', () => {});
app.whenReady().then(async () => { app.whenReady().then(async () => {
let framePending = false; 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; if (value.event === 'frame') framePending = true;
process.send?.({ event: value }, () => { if (value.event === 'frame') framePending = false; }); 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/`. 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. The script prints `Installer available: <path>` when it completes.
After a successful build, the version fields keep the new version. After a successful build, the version fields keep the new version.
Example, from the 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 ### What the script does
@@ -229,7 +229,7 @@ Procedure, in the RuneStone repository root. The commands use the Tauri CLI from
If the build fails, restore the previous version fields. If the build fails, restore the previous version fields.
Example, from 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. `pnpm build:installer` does not build Linux packages. It stops on operating systems other than Windows.
Linux packages do not include the browser engine, and no Linux engine is published yet. The browser tab says that no engine is available for the platform. Linux packages do not include the browser engine, and no Linux engine is published yet. The browser tab says that no engine is available for the platform.
-1
View File
@@ -1 +0,0 @@
313f15e68c3b3a6eec9fb223548c9843e6e87af5566885088ddbf7434742e100 RuneStone_0.1.44_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. Plugins keep full application access. This API does not add a permission sandbox.
The API does not include context sources, remote model servers, or credential storage. The API does not include context sources, remote model servers, or credential storage.
For tests, see `tests/unit/plugins/completion.spec.ts`. For 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`.
+69 -1
View File
@@ -830,6 +830,7 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
- Shared implementation: `tokens.css` (`--rs-menu-bg`, `--rs-menu-active-bg`, `--rs-menu-backdrop`, and the `--rs-image-menu-*` tokens), `menu.css`, `appearance.ts` and `backgrounds.ts` (the image switch), and `actionMenu.ts` (popover submenus). - Shared implementation: `tokens.css` (`--rs-menu-bg`, `--rs-menu-active-bg`, `--rs-menu-backdrop`, and the `--rs-image-menu-*` tokens), `menu.css`, `appearance.ts` and `backgrounds.ts` (the image switch), and `actionMenu.ts` (popover submenus).
- Evidence: `tests/smoke/menus/consistency.smoke.mjs` checks an opaque menu without an image, and 92% with a blur over an image. Screenshots are in `output/phase-5a/5a-3/` in the main checkout. - Evidence: `tests/smoke/menus/consistency.smoke.mjs` checks an opaque menu without an image, and 92% with a blur over an image. Screenshots are in `output/phase-5a/5a-3/` in the main checkout.
- Replaces: [UI-013](#ui-013--translucent-menu-surfaces). - Replaces: [UI-013](#ui-013--translucent-menu-surfaces).
- Replaced by: [UI-061](#ui-061--translucent-menus-and-hover-fills-over-images) replaces the image rule. Menus without an image stay opaque.
- Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open. - Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open.
### UI-044 — Core palettes and the lightest page ### UI-044 — Core palettes and the lightest page
@@ -954,7 +955,7 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
- Scope: The main header, the side pane, the left ribbon, the tab bars, the Settings and Browser window title bars, and the window builders of the host. - Scope: The main header, the side pane, the left ribbon, the tab bars, the Settings and Browser window title bars, and the window builders of the host.
- Shared implementation: `WorkbenchHeader.svelte`, `LeftPane.svelte`, `PluginRibbon.svelte`, `TabBar.svelte`, `WindowControls.svelte`, `src-tauri/src/window_frame.rs`, `src-tauri/tauri.macos.conf.json`, and the `--rs-titlebar-inset-start` token. - Shared implementation: `WorkbenchHeader.svelte`, `LeftPane.svelte`, `PluginRibbon.svelte`, `TabBar.svelte`, `WindowControls.svelte`, `src-tauri/src/window_frame.rs`, `src-tauri/tauri.macos.conf.json`, and the `--rs-titlebar-inset-start` token.
- Evidence: `tests/smoke/layout/titleBar.smoke.mjs` and the Rust command list test. - Evidence: `tests/smoke/layout/titleBar.smoke.mjs` and the Rust command list test.
- Replaces / replaced by: The left pane footer, and the ribbon rule "The ribbon has no width when it has no entries." - 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. - Limits: Browser checks use desktop service mocks. Snap Layouts, the native drag area, and the macOS title bar need native acceptance. The macOS code path was not compiled here. On Windows 10, Win+Z does nothing.
### UI-051 — Check marks, focus rings, and control states ### UI-051 — Check marks, focus rings, and control states
@@ -1106,3 +1107,70 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
- Evidence: `tests/smoke/features/pm*.smoke.mjs` and `tests/unit/features/pm/`, with screenshots in both themes in `output/smoke/features/`. `pmLanguage.smoke.mjs` shows a board in French. - Evidence: `tests/smoke/features/pm*.smoke.mjs` and `tests/unit/features/pm/`, with screenshots in both themes in `output/smoke/features/`. `pmLanguage.smoke.mjs` shows a board in French.
- Replaces / replaced by: The Project Management plugin, its settings view, the boards service, and `api.backgrounds`. The rules of [UI-033](#ui-033--list-capacity-and-a-frozen-all-tasks-overview) through [UI-038](#ui-038--fixed-workspace-default-board) stay. - Replaces / replaced by: The Project Management plugin, its settings view, the boards service, and `api.backgrounds`. The rules of [UI-033](#ui-033--list-capacity-and-a-frozen-all-tasks-overview) through [UI-038](#ui-038--fixed-workspace-default-board) stay.
- Limits: **More actions**, the card actions, and the list actions stay popup panels of the feature. The old package stays installed until the user removes it. - Limits: **More actions**, the card actions, and the list actions stay popup panels of the feature. The old package stays installed until the user removes it.
### UI-061 — Translucent menus and hover fills over images
- Type: Rule change
- Date: 2026-10-30
- Status: Implemented for user review
- Decision source: Card 05b9bfa1 reports that menus, the workspace button, and row highlights lost their transparency over a background image.
- Previous rule: [UI-043](#ui-043--opaque-menus). With a background image, menus were at least 92% opaque, and a hovered menu row was 92% `--rs-bg-active`. Hovered rows in the work area and the workspace button used the opaque `--rs-bg-active`.
- New rule: Without a background image, nothing changes. Menus, hover fills, and the workspace button are opaque. With an image, menus use the surface transparency of Appearance (82% at the default amount of 18%) and keep the blur. 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 `--rs-text-strong`.
- Reason: A nearly opaque `--rs-bg-active` hides the image. A translucent `--rs-bg-active` disappears over mid-tone image areas, because its color is close to the tinted pane there. The veil keeps the image as visible as the pane around it. It adds about the same brightness step as the opaque hover over light, mid-tone, and dark image areas. The blur keeps menu labels clear of document text.
- Scope: Host menus, plugin menus, submenus, the workspace picker, the workspace button, and the hover fills of the side panes, the tab bar, the view modes, icon buttons, Source control, the Git graph and diff tabs, the PDF toolbar, Find, the editor controls, and the bookmarks bar. Dialogs and Settings keep opaque fills.
- Palette change: Silver Serpent `text-dim` is `#c2c6cc` (was `#b3b8be`). It keeps 4.5:1 on a hovered row over a white image.
- Shared implementation: `tokens.css` (`--rs-hover-bg`, `--rs-image-hover-bg`, `--rs-image-menu-bg`, and `--rs-image-menu-active-bg`) and `backgrounds.ts` (the image switch).
- 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 ### 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`. 2. In the repository folder, run `pnpm install --frozen-lockfile`.
3. Prepare the browser runtime. See [Built-in browser runtime](#built-in-browser-runtime). 3. Prepare the browser runtime. See [Built-in browser runtime](#built-in-browser-runtime).
4. Run `pnpm tauri dev`. 4. Run `pnpm tauri dev`.
@@ -232,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. - `pdfjs-dist` is a host dependency. `src/lib/features/pdf/engine.ts` loads the minified build. The worker, the character maps, the standard fonts, and the image decoders are Vite assets of the app, so PDF.js makes no network request. `build.assetsInlineLimit` in `vite.config.js` keeps these files out of the code.
- Project Management has one editor view, `planning`, with `launch: true`. The view pattern `board-<hex of the board ID>` gives each board its own tab. Its ribbon button in `PluginRibbon.svelte` calls the launch, which opens the default board of the workspace or All tasks. It has no command. - Project Management has one editor view, `planning`, with `launch: true`. The view pattern `board-<hex of the board ID>` gives each board its own tab. Its ribbon button in `PluginRibbon.svelte` calls the launch, which opens the default board of the workspace or All tasks. It has no command.
- Project Management reads and writes only `.runestone/pm/`. `storage/legacy.ts` finds data in the old format of visible notes. The interface then offers the migration, with backups in `.runestone/pm/backups/`. It migrates only after the user chooses it. - Project Management reads and writes only `.runestone/pm/`. `storage/legacy.ts` finds data in the old format of visible notes. The interface then offers the migration, with backups in `.runestone/pm/backups/`. It migrates only after the user chooses it.
- Project Management deletes no files. A description draft is `.runestone/pm/drafts/<hex of the card ID>.json`. The data of its unsaved images is in `<hex of the card ID>.images.json` in the same folder. Thus a text change does not write the images again.
Only a save of the description or the card writes `.runestone/pm/images/<image ID>.json`. **Save** and **Cancel** of the description replace the draft and its image record with empty records. As a result, a discarded draft leaves no image file.
- `pm/storage/` and `pm/model/` stay pure TypeScript without host modules, so the `runestone-project-management` skill can bundle them. They mark their user-visible text with `message()` from `storage/message.ts` and keep it in English. The interface translates that text with `localize()` in `pm/ui/text.ts`. - `pm/storage/` and `pm/model/` stay pure TypeScript without host modules, so the `runestone-project-management` skill can bundle them. They mark their user-visible text with `message()` from `storage/message.ts` and keep it in English. The interface translates that text with `localize()` in `pm/ui/text.ts`.
- The `projectManagement` section holds the priority levels (`pmSettings.ts`). The default board is `defaultBoardId` in `.runestone/pm/workspace.json`, so each workspace has its own. Appearance → Background reads the board list from the same file through `pmBoards.ts`, without the feature code. - The `projectManagement` section holds the priority levels (`pmSettings.ts`). The default board is `defaultBoardId` in `.runestone/pm/workspace.json`, so each workspace has its own. Appearance → Background reads the board list from the same file through `pmBoards.ts`, without the feature code.
- The first start makes the `projectManagement` section from the kept settings of the Project Management plugin. When `localStorage` has no view states, it also copies the view states of the plugin. - The first start makes the `projectManagement` section from the kept settings of the Project Management plugin. When `localStorage` has no view states, it also copies the view states of the plugin.
+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. | | 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. | | 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. 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 - **Copy path** and **Show in Explorer**, for workspace images
**Remove image**, or the Delete key, removes the image link from the note. It does not delete the file. Undo restores the link. **Remove image**, or the Delete key, removes the image link from the note. It does not delete the file. Undo restores the link.
Zoom works in Write, Read, and 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 ## 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. RuneStone renders Mermaid diagrams locally. If a diagram is not valid, RuneStone shows an error message and the diagram source.
Read shows frontmatter in a collapsed **Properties** section. Read shows frontmatter in a collapsed **Properties** section.
@@ -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 | SUM, AVERAGE, MIN, MAX, COUNT, ABS, and ROUND |
Functions that take a range ignore text and blank cells. Arithmetic uses zero for a blank cell. Functions that take a range ignore text and blank cells. Arithmetic uses zero for a blank cell.
Results update in Write, Read, and 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. The **Formulas** control below each table explains the syntax. The active cell shows its address.
A formula that is not valid, a missing cell, or a circular reference shows an error label. A formula that is not valid, a missing cell, or a circular reference shows an error label.
+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. The card details have the title, the labels, and the description in Markdown.
A change to the description stays a draft until you select **Save**. **Cancel** restores the saved text. When you close the card with a draft, the card shows an unsaved marker. A change to the description stays a draft until you select **Save**. **Cancel** restores the saved text. When you close the card with a draft, the card shows an unsaved marker.
An image that you paste or drop into a draft stays with the draft. **Save** adds the image to the card. **Cancel** removes it.
Board and list changes save at once. Other fields save when you close the card details. Board and list changes save at once. Other fields save when you close the card details.
### Card details ### Card details
@@ -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. 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. 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. **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). To show the Background slideshow on the boards, see [Choose where the background shows](themes.md#choose-where-the-background-shows).
+1 -1
View File
@@ -22,7 +22,7 @@ Each named theme has its own fonts and syntax colors. Fonts come from your compu
## Adjust transparency ## Adjust transparency
**Transparent surfaces** tints work areas with a [background](#show-a-background) and compatible plugin surfaces. **Transparent surfaces** tints work areas with a [background](#show-a-background) and compatible plugin surfaces.
Menus stay opaque. With a background image, menus are at least 92% opaque and blur the image. Without a background image, menus are opaque. With an image, menus use the same transparency as other surfaces and blur the image.
Set **Transparency amount** from 0% to 100%. The default is 18%. Set **Transparency amount** from 0% to 100%. The default is 18%.
Turn off **Transparent surfaces** for opaque surfaces. Text and icons stay opaque in both cases. Turn off **Transparent surfaces** for opaque surfaces. Text and icons stay opaque in both cases.
+32 -34
View File
@@ -2,23 +2,32 @@
[RuneStone](../README.md) · [User guide](user-guide.md) [RuneStone](../README.md) · [User guide](user-guide.md)
This guide installs, updates, or reinstalls RuneStone from a 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 | | Platform | Release file | Notes |
| --- | --- | --- | | --- | --- | --- |
| Windows 10 or 11, x64 | [RuneStone_0.1.49_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.49/RuneStone_0.1.49_x64-setup.exe) | Installs for the current Windows account | | 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 | [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. | | macOS, Apple silicon | None | Build the app from source. See [macOS packages](builds.md#macos-packages). Intel Macs are not supported. |
| Linux, amd64 | [RuneStone_0.1.44_amd64.deb](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_amd64.deb) | Experimental. Built on Ubuntu 26.04.1. Needs GLIBC 2.39 or newer. | | 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, 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). The built-in browser needs a separate engine download. See [Use the built-in browser](user-guide.md#use-the-built-in-browser).
## Install on Windows ## Install on Windows
1. Save `RuneStone_0.1.49_x64-setup.exe` to Downloads. 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 the file. 2. Open PowerShell in Downloads.
3. Complete setup. Keep the default destination unless you need another location. 3. Check the download:
4. Open RuneStone from the Start menu.
```powershell
$expected = (Get-Content .\windows-SHA256SUMS).Split(' ')[0]
(Get-FileHash .\RuneStone_1.0.0_x64-setup.exe).Hash -eq $expected
```
If the result is not `True`, delete the file and download it again.
4. Open the setup file.
5. Complete setup. Keep the default destination unless you need another location.
6. Open RuneStone from the Start menu.
## Update or reinstall on Windows ## Update or reinstall on Windows
@@ -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 ## Install on macOS
1. Save `RuneStone_0.1.44_aarch64.dmg` to Downloads. Build the app on an Apple silicon Mac first. See [macOS packages](builds.md#macos-packages).
2. Open the disk image.
3. Drag RuneStone into Applications.
4. Eject the disk image.
5. Open RuneStone from Applications.
The app has an ad hoc signature and is not notarized by Apple. 1. Copy `RuneStone.app` from `src-tauri/target/release/bundle/macos/` into Applications.
If macOS blocks the first launch, open **System Settings → Privacy & Security** and choose **Open Anyway**. 2. Open RuneStone from Applications.
## Update or reinstall on macOS ## Update or reinstall on macOS
1. Save your documents and quit RuneStone. 1. Save your documents and quit RuneStone.
2. Open the disk image for the same or a newer version. 2. Build the same or a newer version.
3. Drag RuneStone into Applications and confirm the replacement. 3. Copy the new `RuneStone.app` into Applications and confirm the replacement.
4. Eject the disk image. 4. Open RuneStone from Applications.
5. Open RuneStone from Applications.
## Install on Linux ## Install on Linux
1. Save `RuneStone_0.1.44_amd64.deb` and [linux-SHA256SUMS](https://git.knottywyvern.com/kwyvern/RuneStone/raw/branch/master/docs/checksums/0.1.44/linux-SHA256SUMS) to Downloads. Build the Debian package first. See [Build Linux packages](builds.md#build-linux-packages).
2. Open Terminal in Downloads.
3. Check the download: 1. Open Terminal in the folder that contains the package.
2. Install the package. Use the file name of your build:
```bash ```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. 3. Open RuneStone from your applications menu, or run `runestone` in Terminal.
4. Install the package:
```bash
sudo apt install ./RuneStone_0.1.44_amd64.deb
```
5. Open RuneStone from your applications menu, or run `runestone` in Terminal.
APT installs the system libraries that the package declares. Run RuneStone as your ordinary desktop user. APT installs the system libraries that the package declares. Run RuneStone as your ordinary desktop user.
@@ -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. 2. Open Terminal in the folder that contains the new package.
3. Install the newer package with the same `sudo apt install ./<file>.deb` command. 3. Install the newer package with the same `sudo apt install ./<file>.deb` command.
To reinstall the same version, run `sudo apt install --reinstall ./RuneStone_0.1.44_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. Install it in each plugin project from the URL of its package file on the RuneStone releases page.
```sh ```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. - Always give the full URL. The SDK is not on the npm registry, and another account owns the `@runestone` scope there.
@@ -146,7 +146,7 @@ For the RuneStone source setup, see [Run from source](development.md#run-from-so
### Example: CSV Viewer ### Example: CSV Viewer
Source: [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 | | Item | Value |
| --- | --- | | --- | --- |
+1 -8
View File
@@ -2,7 +2,7 @@
[RuneStone](../README.md) · [User guide](user-guide.md) [RuneStone](../README.md) · [User guide](user-guide.md)
This guide explains how to install, enable, update, and remove optional plugins 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). 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. Use HTTPS for a remote server. HTTP sends the token and the package without encryption.
RuneStone uses the token for this request only and does not save it. RuneStone uses the token for this request only and does not save it.
## Plugin guides
| Plugin | Guide |
| --- | --- |
| Local Autocomplete | [Local Autocomplete trial guide](https://git.knottywyvern.com/kwyvern/RuneStone_LocalModel/src/branch/main/docs/trial-guide.md) |
| CSV Viewer | [CSV Viewer README](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer/src/branch/main/README.md) |
## Plugin help ## Plugin help
| Problem | Action | | Problem | Action |
+2 -2
View File
@@ -88,7 +88,7 @@ The installer, engine, and SDK scripts stop if the release file exists. The plug
## Publish an installer ## Publish an installer
Publish RuneStone installers on the [RuneStone releases page](https://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). 1. Build the installer and complete the [installer checks](builds.md#installer-checks).
2. Create a release with the tag `v<version>` on the commit that sets the version. 2. Create a release with the tag `v<version>` on the commit that sets the version.
@@ -181,7 +181,7 @@ Plugin authors install the SDK from the URL of that file. See [Install the SDK](
1. Commit the SDK changes in RuneStone. Run `pnpm check` and `pnpm test`. 1. Commit the SDK changes in RuneStone. Run `pnpm check` and `pnpm test`.
2. Run `pnpm release:sdk --release-url <folder URL> --version <version> --dry-run`. Read the plan. 2. Run `pnpm release:sdk --release-url <folder URL> --version <version> --dry-run`. Read the plan.
The folder URL is the download folder of the release, for example `https://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`. 3. Run the same command without `--dry-run`.
4. On the RuneStone releases page, create a release with the tag `plugin-sdk-v<version>` on the `source` commit in `sdk.json`. 4. On the RuneStone releases page, create a release with the tag `plugin-sdk-v<version>` on the `source` commit in `sdk.json`.
5. Attach only the `.tgz` file. Leave the release description empty. 5. Attach only the `.tgz` file. Leave the release description empty.
+8 -6
View File
@@ -52,7 +52,8 @@ Do not copy feature-specific colors into a shared control.
| `--rs-menu-font-size` | 13px | Menu text | | `--rs-menu-font-size` | 13px | Menu text |
| `--rs-menu-icon-size` / `--rs-menu-icon-gap` | 14px / 8px | Menu icon and its gap to the label | | `--rs-menu-icon-size` / `--rs-menu-icon-gap` | 14px / 8px | Menu icon and its gap to the label |
| `--rs-menu-border` | `transparent` | Borderless panel. `--rs-menu-shadow` supplies the edge. | | `--rs-menu-border` | `transparent` | Borderless panel. `--rs-menu-shadow` supplies the edge. |
| `--rs-menu-bg`, `--rs-menu-active-bg` | `--rs-bg-elevated`, `--rs-bg-active` | Opaque menu surface and hover or focus fill. With a background image: at least 92% opaque. | | `--rs-menu-bg`, `--rs-menu-active-bg` | `--rs-bg-elevated`, `--rs-bg-active` | Opaque menu surface and hover or focus fill. With a background image: the surface tint and the `--rs-hover-bg` veil. |
| `--rs-hover-bg` | `--rs-bg-active` | Hover fill of rows and controls in the work area, and the fill of the workspace button. With a background image: a 6% veil of `--rs-text-strong`. |
| `--rs-menu-backdrop` | `none` | With a background image: `blur(18px) saturate(1.2)` | | `--rs-menu-backdrop` | `none` | With a background image: `blur(18px) saturate(1.2)` |
| `--rs-surface-opacity` | 82% | Shared surface tint. Appearance settings adjust it. | | `--rs-surface-opacity` | 82% | Shared surface tint. Appearance settings adjust it. |
@@ -100,7 +101,7 @@ Use one menu design for context menus, action menus, and their submenus in the h
- Use the `--rs-menu-*` tokens and `--rs-control-radius`. One menu family shares font, row height, padding, icon size, label alignment, separators, and shadow. - Use the `--rs-menu-*` tokens and `--rs-control-radius`. One menu family shares font, row height, padding, icon size, label alignment, separators, and shadow.
- A menu can grow wider when its content needs more space. All other measurements stay shared. - A menu can grow wider when its content needs more space. All other measurements stay shared.
- Keep the padding inset around every row, so hover and focus fills do not touch the panel edge. - Keep the padding inset around every row, so hover and focus fills do not touch the panel edge.
- The panel is borderless, with a shadow. Its surface is opaque through `--rs-menu-bg` and `--rs-menu-active-bg`. Only with a background image, it is at least 92% opaque and blurs the image. Host menus, plugin menus, submenus, and the workspace picker all use this surface. - The panel is borderless, with a shadow. Its surface is opaque through `--rs-menu-bg` and `--rs-menu-active-bg`. Only with a background image, it uses the surface tint (82% by default) and blurs the image, and a hovered row gets the veil of `--rs-hover-bg`. Host menus, plugin menus, submenus, and the workspace picker all use this surface.
- Submenus show as popovers in the top layer, so the blur of the parent menu cannot clip them. - Submenus show as popovers in the top layer, so the blur of the parent menu cannot clip them.
- Plugins call `api.ui.showActionMenu` for the host menu, when the host API exists. The host handles dismissal, focus return, and plugin cleanup. - Plugins call `api.ui.showActionMenu` for the host menu, when the host API exists. The host handles dismissal, focus return, and plugin cleanup.
@@ -142,14 +143,14 @@ Use one menu design for context menus, action menus, and their submenus in the h
- Native editing menus keep recognized editing, spelling, and emoji commands. The host removes system sharing, writing direction, dictation, and unnamed tools before shared display or native fallback. - Native editing menus keep recognized editing, spelling, and emoji commands. The host removes system sharing, writing direction, dictation, and unnamed tools before shared display or native fallback.
- New note creates a blank note. Its submenu contains templates and Manage templates. - New note creates a blank note. Its submenu contains templates and Manage templates.
Decisions: [UI-002](design-decisions.md#ui-002--share-the-requested-dropdown-design), [UI-003](design-decisions.md#ui-003--quiet-menu-choices), [UI-006](design-decisions.md#ui-006--borderless-shared-menus), [UI-007](design-decisions.md#ui-007--repeated-menu-drift), [UI-008](design-decisions.md#ui-008--keep-native-editing-menus-focused), [UI-026](design-decisions.md#ui-026--compact-shared-menu-rows), [UI-027](design-decisions.md#ui-027--direct-spelling-corrections), [UI-043](design-decisions.md#ui-043--opaque-menus). Decisions: [UI-002](design-decisions.md#ui-002--share-the-requested-dropdown-design), [UI-003](design-decisions.md#ui-003--quiet-menu-choices), [UI-006](design-decisions.md#ui-006--borderless-shared-menus), [UI-007](design-decisions.md#ui-007--repeated-menu-drift), [UI-008](design-decisions.md#ui-008--keep-native-editing-menus-focused), [UI-026](design-decisions.md#ui-026--compact-shared-menu-rows), [UI-027](design-decisions.md#ui-027--direct-spelling-corrections), [UI-043](design-decisions.md#ui-043--opaque-menus), [UI-061](design-decisions.md#ui-061--translucent-menus-and-hover-fills-over-images).
## Window and navigation ## Window and navigation
- The main header holds navigation, document tabs, Save, the outline toggle, and window controls. The other tools are in the left ribbon, so the tabs keep their room. A detached tab window has no ribbon, so its header keeps those tools. - The main header holds navigation, document tabs, Save, the outline toggle, and window controls. The other tools are in the left ribbon, so the tabs keep their room. A detached tab window has no ribbon, so its header keeps those tools.
- A bar at the bottom of the side pane holds the workspace switcher, Help, and Settings, as in Obsidian. The switcher names the workspace and opens the workspace list above it. - A bar at the bottom of the side pane holds the workspace switcher, Help, and Settings, as in Obsidian. The switcher names the workspace and opens the workspace list above it.
- The left ribbon is always present. It holds the tools, then a line, then the plugin view shortcuts. The tools are New browser tab, Terminal, Project Management, Plug-in views, and Commands. A tool of an off feature does not show. Its menus open at its right. While the side pane is closed, the workspace switcher, Help, and Settings move to the bottom of the ribbon, so they stay reachable. - The left ribbon is always present. It holds the tools, then a line, then the plugin view shortcuts. The tools are New browser tab, Terminal, Project Management, Plug-in views, and Commands. A tool of an off feature does not show. Its menus open at its right. While the side pane is closed, the workspace switcher, Help, and Settings move to the bottom of the ribbon, so they stay reachable.
- Tabs keep a minimum width of 120 pixels and scroll. Fades show tabs out of view, and ⌄ lists all tabs. A drag area 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. - Windows and Linux title bars use square caption buttons, 46 pixels wide and full height. Rest the pointer on maximize for Snap Layouts on Windows 11. macOS keeps its native traffic lights, and title bars leave `--rs-titlebar-inset-start` free for them.
- Files, Search, Bookmarks, Source control (while Git is on), and the sidebar views of installed plugins share the top navigation group. The active navigation button shows which view fills the left pane. - Files, Search, Bookmarks, Source control (while Git is on), and the sidebar views of installed plugins share the top navigation group. The active navigation button shows which view fills the left pane.
- Plugin editor views can use the left ribbon. - Plugin editor views can use the left ribbon.
@@ -221,15 +222,16 @@ Decisions: [UI-009](design-decisions.md#ui-009--character-theme-appearances), [U
- The app image fills the work area below the titlebar, including new tabs and document views. It stays fixed while content scrolls. - The app image fills the work area below the titlebar, including new tabs and document views. It stays fixed while content scrolls.
- Sidebars use `--rs-image-sidebar-bg` (82% tint). Editor surfaces use `--rs-image-editor-bg` (90% tint). Without an image, both are opaque. - Sidebars use `--rs-image-sidebar-bg` (82% tint). Editor surfaces use `--rs-image-editor-bg` (90% tint). Without an image, both are opaque.
- Write, Source, Read, and 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`. - 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. - 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.
- Headers and dialogs keep their own surfaces. - Headers and dialogs keep their own surfaces.
- The app work area and Project Management keep separate images and settings in every theme. The one image of Background can be up to 50 MiB. Its bytes stay in IndexedDB, and the appearance settings keep a small reference. - The app work area and Project Management keep separate images and settings in every theme. The one image of Background can be up to 50 MiB. Its bytes stay in IndexedDB, and the appearance settings keep a small reference.
- The folder and the one image each have a size, nine alignment positions, and an overlay from -100% (lighter) to 100% (darker), set with a slider or a typed value. - The folder and the one image each have a size, nine alignment positions, and an overlay from -100% (lighter) to 100% (darker), set with a slider or a typed value.
- Without a background frame, every surface and menu is opaque. With Background off, no image shows. - Without a background frame, every surface and menu is opaque. With Background off, no image shows.
Decisions: [UI-010](design-decisions.md#ui-010--background-surface-visibility), [UI-011](design-decisions.md#ui-011--backgrounds-across-the-work-area), [UI-016](design-decisions.md#ui-016--translucent-code-blocks). Decisions: [UI-010](design-decisions.md#ui-010--background-surface-visibility), [UI-011](design-decisions.md#ui-011--backgrounds-across-the-work-area), [UI-016](design-decisions.md#ui-016--translucent-code-blocks), [UI-061](design-decisions.md#ui-061--translucent-menus-and-hover-fills-over-images).
### Project Management surfaces ### Project Management surfaces
+33 -8
View File
@@ -75,14 +75,14 @@ On macOS and Linux, you can still open, edit, rename, and delete existing files
## Edit documents ## Edit documents
Each document pane has one view control with three choices, and a **Split** button: Each document pane has one view control with three choices, and a **Read beside** button:
| Choice | Shows | | Choice | Shows |
| --- | --- | | --- | --- |
| **Write** | Formatted Markdown. The active line shows its Markdown source. | | **Write** | Formatted Markdown. The active line shows its Markdown source. |
| **Source** | The plain source with line numbers and syntax colors | | **Source** | The plain source with line numbers and syntax colors |
| **Read** | The rendered document, without editing. Markdown files only. | | **Read** | The rendered document, without editing. Markdown files only. |
| **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**. Press Ctrl+E to switch between Write and Source. Press Ctrl+Shift+E to switch between Read and the editor. The tab menu has the same choices under **View**.
The control shows icons only. Hover over an icon, or focus it with the keyboard, to see its name and shortcut. The arrow keys move the choice. The control shows icons only. Hover over an icon, or focus it with the keyboard, to see its name and shortcut. The arrow keys move the choice.
@@ -103,9 +103,9 @@ Read follows CommonMark: a single line break inside a paragraph is a space. To s
- Ctrl+click a link in Write or Source. In Read, a normal click follows the link. - Ctrl+click a link in Write or Source. In Read, a normal click follows the link.
- A workspace file link opens in a new tab and keeps the current document open. - A workspace file link opens in a new tab and keeps the current document open.
- A heading link, such as `guide.md#save-your-work` or `#save-your-work`, 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. - 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. 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 | | 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. | | 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. |
| Zoom | Select **Zoom in** or **Zoom out**, from 25% to 400%. **Fit width** fits the page to the tab again. | | Go to a page | Select **Previous page** or **Next page**. Or type a number in the page field and press Enter. |
| Rotate | Select **Rotate clockwise**. Each click turns the page by 90 degrees. | | 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. | | Copy text | Select text on the page with the pointer, then press Ctrl+C. |
| Show changes from another program | Select **Reload PDF**. The tab stays on the same page. | | Show changes from another program | Select **Reload PDF**. The tab stays on the same page. |
| Open a protected PDF | Type the password, then select **Unlock**. RuneStone does not save the password. | | Open a protected PDF | Type the password, then select **Unlock**. RuneStone does not save the password. |
- A PDF file must be in the workspace and at most 64 MiB. - A PDF file must be in the workspace and at most 64 MiB.
- The tab shows 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. - Scanned pages show as images, so you cannot select their text.
- If a PDF does not open, the tab shows the error. Select **Reload PDF**, or try another copy of the file. - If a PDF does not open, the tab shows the error. Select **Reload PDF**, or try another copy of the file.
@@ -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. When you start RuneStone again, it opens the document tabs of the workspace. It keeps their order, pins, and active tab.
This includes PDF tabs and plugin tabs that show a file. RuneStone reads the contents again from disk. Missing files do not stop the other tabs from opening. This includes PDF tabs and plugin tabs that show a file. RuneStone reads the contents again from disk. Missing files do not stop the other tabs from opening.
### Show tabs side by side
Use panes to see two tabs at the same time. For example, browse the web or read a PDF file in one pane, and write a note in the other pane.
1. Right-click a tab that is not visible, or a file in the file tree.
2. Select **Open to the right**.
The tab opens in a new pane to the right of the active pane. A pane shows a document, a PDF file, or a plugin tab, for example a browser tab. A tab shows in one pane at a time.
You can also drag a tab from the tab bar to a pane. A drop on the middle of the pane shows the tab in that pane. A drop on the 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 ## Save your work
Auto-save is on by default. It saves changed files every 5 seconds, also in background tabs. RuneStone does not write unchanged files. Auto-save is on by default. It saves changed files every 5 seconds, also in background tabs. RuneStone does not write unchanged files.
@@ -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. 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**. 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. 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. **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. 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", "name": "runestone",
"version": "0.1.51", "version": "1.0.0a",
"description": "Desktop editor for a local workspace", "description": "Desktop editor for a local workspace",
"type": "module", "type": "module",
"scripts": { "scripts": {
@@ -25,7 +25,7 @@
"sdk:build": "node scripts/buildSdk.mjs", "sdk:build": "node scripts/buildSdk.mjs",
"release:sdk": "node scripts/releaseSdk.mjs" "release:sdk": "node scripts/releaseSdk.mjs"
}, },
"license": "MIT", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@codemirror/autocomplete": "^6.20.3", "@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1", "@codemirror/commands": "^6.11.1",
+9 -9
View File
@@ -1,6 +1,6 @@
# RuneStone Plugin SDK # RuneStone Plugin SDK
`@runestone/plugin-sdk` gives TypeScript types and small helpers for [RuneStone](https://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. RuneStone is a desktop workspace for Markdown notes, code, and project work. Plugins add views, commands, and document editors to it.
The SDK contains: The SDK contains:
@@ -17,7 +17,7 @@ The SDK does not run plugins and does not call RuneStone. RuneStone gives the `a
Install the SDK from the URL of its package file on the RuneStone releases page. Install the SDK from the URL of its package file on the RuneStone releases page.
```sh ```sh
pnpm add -D "https://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`: The result in `package.json`:
@@ -25,7 +25,7 @@ The result in `package.json`:
```json ```json
{ {
"devDependencies": { "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. 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. A type-only import, such as `import type { PluginApi }`, adds no code to the bundle.
@@ -128,12 +128,12 @@ A new SDK release can add types for new RuneStone features. Use the feature chec
## Documentation and help ## Documentation and help
- [Plugin development reference](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugin-development.md): the package format, the API, and the build procedure - [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://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/completion.md) - [Completion API](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/completion.md)
- [Install and manage plugins](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugins.md) - [Install and manage plugins](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/plugins.md)
- [Release policy](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/releases.md#sdk-releases) - [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. 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"/>', 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-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-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"/>', 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"/>', 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"/>', '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]] [[package]]
name = "runestone" name = "runestone"
version = "0.1.51" version = "1.0.0+1"
dependencies = [ dependencies = [
"base64 0.23.1", "base64 0.23.1",
"dunce", "dunce",
+3 -2
View File
@@ -1,8 +1,9 @@
[package] [package]
name = "runestone" name = "runestone"
version = "0.1.51" version = "1.0.0+1"
description = "Writing workspace plus script editor" description = "Writing workspace plus script editor"
authors = ["Knotty Wyvern"] authors = ["Knotty Wyvern"]
license = "Apache-2.0"
edition = "2021" edition = "2021"
[lib] [lib]
@@ -46,4 +47,4 @@ opt-level = 3
strip = true strip = true
[package.metadata.runestone] [package.metadata.runestone]
version = "0.1.51" version = "1.0.0a"
+4 -4
View File
@@ -1,11 +1,11 @@
{ {
"version": "0.1.8", "version": "0.1.11",
"protocol": 1, "protocol": 1,
"platforms": { "platforms": {
"windows-x86_64": { "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", "url": "https://github.com/KnottyWyvern-GH/RuneStone/releases/download/browser-engine-v0.1.11/RuneStone-Browser_0.1.11_win32-x64.zip",
"bytes": 163632595, "bytes": 163623801,
"sha256": "d704003bf5fe047b100a3cf0ab84f3321fd272510cf287a229e50d1653d0856b" "sha256": "1e0153b134cebe882b36f74e1f3c2a4ed37acb2caca10548034a8b5d88738d26"
} }
} }
} }
+2
View File
@@ -71,6 +71,8 @@ fn main() {
"workspace_delete", "workspace_delete",
"workspace_read_data_url", "workspace_read_data_url",
"workspace_write_bytes", "workspace_write_bytes",
"workspace_save_image_url",
"workspace_download_image",
"workspace_copy", "workspace_copy",
"workspace_abs_path", "workspace_abs_path",
"workspace_reveal", "workspace_reveal",
+2
View File
@@ -69,6 +69,8 @@
"allow-workspace-delete", "allow-workspace-delete",
"allow-workspace-read-data-url", "allow-workspace-read-data-url",
"allow-workspace-write-bytes", "allow-workspace-write-bytes",
"allow-workspace-save-image-url",
"allow-workspace-download-image",
"allow-workspace-copy", "allow-workspace-copy",
"allow-workspace-abs-path", "allow-workspace-abs-path",
"allow-workspace-reveal", "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", "insertText",
"edit", "edit",
"contextAction", "contextAction",
"copiedImage",
"linkAt",
"frameAck", "frameAck",
"createProfile", "createProfile",
"renameProfile", "renameProfile",
@@ -480,7 +482,7 @@ impl BrowserState {
let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id })); let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id }));
return Ok(worker.routing.lock()?.snapshot(result, owner)); 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.")?; let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
match worker.routing.lock()?.owners.get(id) { match worker.routing.lock()?.owners.get(id) {
Some(window) if window == owner => {}, Some(window) if window == owner => {},
+2
View File
@@ -107,6 +107,8 @@ pub fn run() {
workspace::workspace_delete, workspace::workspace_delete,
workspace::workspace_read_data_url, workspace::workspace_read_data_url,
workspace::workspace_write_bytes, workspace::workspace_write_bytes,
workspace::workspace_save_image_url,
workspace::workspace_download_image,
workspace::workspace_copy, workspace::workspace_copy,
workspace::workspace_abs_path, workspace::workspace_abs_path,
workspace::workspace_reveal, 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 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. //! 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`). //! Plugin settings stay in the app data folder (see `plugins.rs`).
use std::io; use std::io;
@@ -178,6 +179,19 @@ impl Store {
Ok(Change { section: section.into(), revision: next, value }) 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. /// 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> { pub fn migrate(&mut self, sections: Map<String, Value>) -> Result<Snapshot> {
for name in sections.keys() { check_section(name)?; } for name in sections.keys() { check_section(name)?; }
@@ -229,9 +243,9 @@ pub async fn settings_read(app: AppHandle) -> Result<Snapshot> {
#[tauri::command] #[tauri::command]
pub async fn settings_write(app: AppHandle, section: String, value: Value) -> Result<Change> { 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. // 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) Ok(change)
} }
@@ -292,6 +306,35 @@ mod tests {
fs::remove_dir_all(dir).unwrap(); 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] #[test]
fn writes_reject_unknown_sections_and_values_above_the_limit() { fn writes_reject_unknown_sections_and_values_above_the_limit() {
let (dir, path) = fixture("limits"); 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)? let bytes = fsutil::read_to_limit(file, MAX_IMAGE_BYTES as u64)?
.ok_or_else(|| Error::new("image is too large"))?; .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,{}", "data:{mime};base64,{}",
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes) base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes)
)) )
} }
fn copy_destination(path: &Path, number: u32) -> PathBuf { 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) 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -1598,6 +1704,50 @@ mod tests {
fs::remove_dir_all(root).unwrap(); 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] #[test]
fn permanent_delete_removes_files_and_folders_but_never_the_root() { fn permanent_delete_removes_files_and_folders_but_never_the_root() {
let root = workspace_fixture("delete"); let root = workspace_fixture("delete");
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "RuneStone", "productName": "RuneStone",
"version": "0.1.51", "version": "1.0.0+1",
"identifier": "com.runestone.app", "identifier": "com.runestone.app",
"build": { "build": {
"beforeDevCommand": "pnpm dev", "beforeDevCommand": "pnpm dev",
+1 -1
View File
@@ -24,7 +24,7 @@
{/each} {/each}
</div> </div>
<style> <style>
.bookmarks{color:var(--rs-text);font-family:var(--rs-font-ui)}.row{display:flex;align-items:center;padding:0 5px;border-radius:var(--rs-control-radius)}.row:hover{background:var(--rs-bg-active)} .bookmarks{color:var(--rs-text);font-family:var(--rs-font-ui)}.row{display:flex;align-items:center;padding:0 5px;border-radius:var(--rs-control-radius)}.row:hover{background:var(--rs-hover-bg)}
.link{display:flex;align-items:center;gap:8px;flex:1;min-width:0;padding:7px 5px;border:0;border-radius:var(--rs-control-radius);color:inherit;background:transparent;text-align:left;cursor:pointer} .link{display:flex;align-items:center;gap:8px;flex:1;min-width:0;padding:7px 5px;border:0;border-radius:var(--rs-control-radius);color:inherit;background:transparent;text-align:left;cursor:pointer}
span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.link:focus-visible{outline:2px solid var(--rs-focus)}p{padding:8px;font-size:12px}.error{color:var(--rs-error)}.note{margin:0;color:var(--rs-text-dim)} span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.link:focus-visible{outline:2px solid var(--rs-focus)}p{padding:8px;font-size:12px}.error{color:var(--rs-error)}.note{margin:0;color:var(--rs-text-dim)}
</style> </style>
+40 -7
View File
@@ -11,6 +11,7 @@
import { TabSession, type TabStatus } from './tabSession'; import { TabSession, type TabStatus } from './tabSession';
import { engine } from './engine'; import { engine } from './engine';
import { AutoScroll } from './autoScroll'; 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 { 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…') }); let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: $t('Opening browser…') });
const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); }); 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 scrollAnchor = $state<{ x: number; y: number } | null>(null);
let scrollFrame = 0, moveFrame = 0, movePending = false; let scrollFrame = 0, moveFrame = 0, movePending = false;
let pendingMove: Record<string, unknown> | undefined; 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 result = $derived(current?.find?.text === findText ? current.find : null);
const documentKey = $derived(`${tabId}:${current?.url}:${!!current?.loading}`); const documentKey = $derived(`${tabId}:${current?.url}:${!!current?.loading}`);
$effect(() => { $effect(() => {
@@ -116,8 +117,9 @@
{ label: $t('Copy link address'), icon: 'copy', run: action('copyLink') }, { label: $t('Copy link address'), icon: 'copy', run: action('copyLink') },
{ label: $t('Save link as…'), icon: 'save', run: action('saveLink') }, { separator: true }); { label: $t('Save link as…'), icon: 'save', run: action('saveLink') }, { separator: true });
if (context.hasImageContents) items.push( 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('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 }); { label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
if (context.isEditable) items.push( if (context.isEditable) items.push(
{ label: $t('Undo'), icon: 'undo', shortcut: keys('Mod+Z'), disabled: !context.editFlags.canUndo, run: edit('undo') }, { 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; }); if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; });
await connection.send(command, args); 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') { async function openTab(profileId = current?.profileId || $browserState?.profiles[0]?.id || 'user') {
if (opening) return; if (opening) return;
opening = true; opening = true;
@@ -194,23 +213,37 @@
if (mounted && pendingMove) moveFrame = requestAnimationFrame(flushMove); 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) { function pointer(event: MouseEvent | WheelEvent, type: string) {
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') textInput.focus({ preventScroll: true }); event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') textInput.focus({ preventScroll: true });
const rect = surface.getBoundingClientRect(); const rect = surface.getBoundingClientRect();
const point = { x: event.clientX - rect.left, y: event.clientY - rect.top }; 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 === 'mouseUp' && event.button === suppressedRelease) { suppressedRelease = -1; return; }
if (type === 'mouseDown' && autoScroll.anchor) { suppressedRelease = event.button; stopScroll(); return; } if (type === 'mouseDown' && autoScroll.anchor) { suppressedRelease = event.button; stopScroll(); return; }
if (type === 'mouseDown' && event.button === 1 && ready) { if (type === 'mouseDown' && event.button === 1 && ready) {
pendingMove = undefined; cancelAnimationFrame(moveFrame); moveFrame = 0; 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 (autoScroll.anchor) {
if (type === 'mouseMove') autoScroll.move(point); if (type === 'mouseMove') autoScroll.move(point);
if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); } if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); }
if (type === 'mouseWheel') stopScroll(); else return; 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, ...pagePoint(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))),
button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event), 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) } : {}) }; ...('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; } 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 = ''; } }} oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
onblur={stopScroll}></textarea> 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 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>
</div> </div>
<style> <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)} 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)} .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} .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} 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)} .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} .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 id = `tab-${crypto.randomUUID()}`;
const saved: SavedView = { view: id, profileId, url, runtimeId: '' }; const saved: SavedView = { view: id, profileId, url, runtimeId: '' };
const run = (command: string, args?: Record<string, unknown>) => { void saved.control?.action(command, args); }; const run = (command: string, args?: Record<string, unknown>) => { void saved.control?.action(command, args); };
// A new tab with the home page of the profile opens in a pane beside this tab.
const split = (direction: 'right' | 'down') => { const split = (direction: 'right' | 'down') => {
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId); const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
void open(current?.profileId || saved.profileId, 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, api.registerView({ id, title: 'Browser', placement: 'editor', icon: 'globe', pinned, launcher: false,
tabDragData: ({ pinned }) => { tabDragData: ({ pinned }) => {
@@ -65,8 +66,8 @@ export async function activate(api: PluginApi) {
return [ return [
{ separator: true }, { separator: true },
{ label: tr("Move to new window"), icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) }, { label: tr("Move to new window"), icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
{ label: tr("Split right"), icon: 'split-right', disabled: !ready, run: () => split('right') }, { label: tr("New tab to the 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 below"), icon: 'split-down', disabled: !ready, run: () => split('down') },
{ separator: true }, { separator: true },
{ label: tr("Find…"), icon: 'search', shortcut: keys('Mod+F'), disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } }, { label: tr("Find…"), icon: 'search', shortcut: keys('Mod+F'), disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
{ label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') }, { label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') },
+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; if (this.closed || this.value.phase !== 'ready') return;
const tabId = this.value.tabId; const tabId = this.value.tabId;
try { 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: '' }); if (tabId === this.value.tabId && this.value.phase === 'ready' && !['input', 'resize', 'visible'].includes(command) && this.value.message) this.update({ message: '' });
return reply;
} catch (error) { } catch (error) {
// Replies from the previous connection cannot replace the current error. // Replies from the previous connection cannot replace the current error.
if (this.closed || tabId !== this.value.tabId || this.value.phase !== 'ready') return; 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 type { Chrome, OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api"; import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
import { linkCandidates } from "$lib/workspace/markdownLinks"; import { linkCandidates } from "$lib/workspace/markdownLinks";
import { documentHeadings } from "$lib/workspace/headingLinks";
import { editImageSource, imageSource } from "./imageSource"; import { editImageSource, imageSource } from "./imageSource";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml"; import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { 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 { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink"; import { workspaceFileLink } from "./workspaceFileLink";
import { savedEditor, saveEditor } from "./editorStates"; import { savedEditor, saveEditor } from "./editorStates";
@@ -48,7 +50,7 @@
onChange: (value: string, id: string) => void; onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>; onRenameTitle?: (id: string, title: string) => Promise<void>;
onOpenLink?: (kind: "md" | "wiki", target: string) => 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; focusLine?: number | null;
/** The line and the column of the cursor, from 1. */ /** The line and the column of the cursor, from 1. */
onSelectionLine?: (line: number, column: number) => void; onSelectionLine?: (line: number, column: number) => void;
@@ -99,7 +101,12 @@
let decoded = source; let decoded = source;
try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ } try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ }
for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) { for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) {
try { 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); loading.set(source, task);
@@ -126,10 +133,12 @@
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null; 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 range = position === null ? view.state.selection.main : { from: position, to: position };
const id = Symbol(), path = buffer.relPath; const id = Symbol(), path = buffer.relPath;
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) }); view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
@@ -137,7 +146,7 @@
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : []; const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
for (const file of files) { for (const file of files) {
if (editor !== view) return; if (editor !== view) return;
const snippet = await onInsertImage?.(file); const snippet = await onInsertImage?.(file, source);
if (snippet) snippets.push(snippet); if (snippet) snippets.push(snippet);
} }
if (editor !== view || !snippets.length) return; if (editor !== view || !snippets.length) return;
@@ -432,8 +441,11 @@
const view = editor; const view = editor;
if (!view || line == null) return; if (!view || line == null) return;
untrack(() => { untrack(() => {
const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from; const number = Math.min(view.state.doc.lines, Math.max(1, line));
const effects = [EditorView.scrollIntoView(anchor, { y: "center" })]; 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 })); }); foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
view.dispatch({ selection: { anchor }, effects }); view.dispatch({ selection: { anchor }, effects });
view.focus(); view.focus();
+1 -1
View File
@@ -3,7 +3,7 @@
.reading .rs-heading-toggle { inset-inline-start: -24px; } .reading .rs-heading-toggle { inset-inline-start: -24px; }
.live-writer .rs-heading-toggle { top: .7em; } .live-writer .rs-heading-toggle { top: .7em; }
.rs-heading-toggle { position: absolute; inset-inline-start: -30px; top: 0; width: 28px; height: 28px; padding: 6px; border: 0; border-radius: var(--rs-control-radius); color: var(--rs-text-dim); background: transparent; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; vertical-align: middle; } .rs-heading-toggle { position: absolute; inset-inline-start: -30px; top: 0; width: 28px; height: 28px; padding: 6px; border: 0; border-radius: var(--rs-control-radius); color: var(--rs-text-dim); background: transparent; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; vertical-align: middle; }
.rs-heading-toggle:hover, .rs-heading-toggle:focus-visible { color: var(--rs-text); background: var(--rs-bg-active); } .rs-heading-toggle:hover, .rs-heading-toggle:focus-visible { color: var(--rs-text); background: var(--rs-hover-bg); }
.rs-heading-toggle:focus-visible { outline: 1px solid var(--rs-focus); outline-offset: 1px; } .rs-heading-toggle:focus-visible { outline: 1px solid var(--rs-focus); outline-offset: 1px; }
.rs-heading-toggle svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } .rs-heading-toggle svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.rs-heading-toggle[aria-expanded="true"] svg { transform: rotate(90deg); } .rs-heading-toggle[aria-expanded="true"] svg { transform: rotate(90deg); }
+1 -1
View File
@@ -10,7 +10,7 @@
.md-image-actions { position: absolute; top: 8px; right: 8px; display: flex; gap: 2px; padding: 3px; border-radius: 6px; background: var(--rs-bg-elevated); box-shadow: 0 2px 8px #0005; opacity: 0; transition: opacity 100ms; } .md-image-actions { position: absolute; top: 8px; right: 8px; display: flex; gap: 2px; padding: 3px; border-radius: 6px; background: var(--rs-bg-elevated); box-shadow: 0 2px 8px #0005; opacity: 0; transition: opacity 100ms; }
.md-image-frame:hover .md-image-actions, .md-image-frame:focus-within .md-image-actions { opacity: 1; } .md-image-frame:hover .md-image-actions, .md-image-frame:focus-within .md-image-actions { opacity: 1; }
.image-action { position: relative; display: inline-grid; place-items: center; flex: 0 0 34px; width: 34px; height: 34px; padding: 6px; color: var(--rs-text); border: 0; border-radius: 4px; background: transparent; cursor: pointer; } .image-action { position: relative; display: inline-grid; place-items: center; flex: 0 0 34px; width: 34px; height: 34px; padding: 6px; color: var(--rs-text); border: 0; border-radius: 4px; background: transparent; cursor: pointer; }
.image-action:hover, .image-action:focus-visible { background: var(--rs-bg-active); color: var(--rs-text-strong); } .image-action:hover, .image-action:focus-visible { background: var(--rs-hover-bg); color: var(--rs-text-strong); }
.image-action:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; } .image-action:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; }
.image-action:disabled { color: var(--rs-text-dim); cursor: default; } .image-action:disabled { color: var(--rs-text-dim); cursor: default; }
.image-lightbox { position: fixed; inset: 0; width: 100vw; height: 100vh; max-width: none; max-height: none; margin: 0; padding: 0; border: 0; background: var(--rs-image-viewer-bg); color: var(--rs-text); } .image-lightbox { position: fixed; inset: 0; width: 100vw; height: 100vh; max-width: none; max-height: none; margin: 0; padding: 0; border: 0; background: var(--rs-image-viewer-bg); color: var(--rs-text); }
+9
View File
@@ -5,6 +5,7 @@ import { attachTooltip } from "../ui/tooltip";
const tooltipCleanups = new WeakMap<HTMLElement, () => void>(); const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
import type { ActionMenuItem } from "../ui/actionMenu"; import type { ActionMenuItem } from "../ui/actionMenu";
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu"; import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
import { imageSize, rememberImageSize } from "../workspace/imageSizes";
export type ImageActions = { export type ImageActions = {
edit?: () => void; edit?: () => void;
@@ -56,6 +57,8 @@ function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
viewport.className = "image-lightbox-viewport"; viewport.className = "image-lightbox-viewport";
const image = original.cloneNode() as HTMLImageElement; const image = original.cloneNode() as HTMLImageElement;
image.removeAttribute("loading"); image.removeAttribute("loading");
image.removeAttribute("width");
image.removeAttribute("height");
image.draggable = false; image.draggable = false;
let scale = 0; let scale = 0;
const status = document.createElement("span"); const status = document.createElement("span");
@@ -91,6 +94,12 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
const cleanup: (() => void)[] = []; const cleanup: (() => void)[] = [];
for (const image of root.querySelectorAll<HTMLImageElement>("img[data-md-src]")) { for (const image of root.querySelectorAll<HTMLImageElement>("img[data-md-src]")) {
if (image.closest(".md-image-frame")) continue; if (image.closest(".md-image-frame")) continue;
// A remote image gives its size when it loads. The next view of this image keeps its space from the start.
const remember = () => rememberImageSize(image.src, image.naturalWidth, image.naturalHeight);
image.addEventListener("load", remember);
cleanup.push(() => image.removeEventListener("load", remember));
const known = !image.getAttribute("width") && imageSize(image.src);
if (known) { image.width = known.width; image.height = known.height; }
const frame = document.createElement("span"); const frame = document.createElement("span");
frame.className = "md-image-frame"; frame.className = "md-image-frame";
frame.contentEditable = "false"; frame.contentEditable = "false";
+2
View File
@@ -5,6 +5,7 @@ import { imageControls, type ImageActions } from "./imageControls";
import { editImageSource } from "./imageSource"; import { editImageSource } from "./imageSource";
import { requestText } from "../workspace/dialogs.svelte"; import { requestText } from "../workspace/dialogs.svelte";
import { isRemoteImage } from "../workspace/media"; import { isRemoteImage } from "../workspace/media";
import { estimatedImageHeight } from "../workspace/imageSizes";
import { actionIcon } from "../ui/actionIcons"; import { actionIcon } from "../ui/actionIcons";
export type ImageContext = { export type ImageContext = {
@@ -18,6 +19,7 @@ const cleanups = new WeakMap<HTMLElement, () => void>();
export class ImagePreview extends WidgetType { export class ImagePreview extends WidgetType {
constructor(readonly html: string, readonly source: string, readonly context: ImageContext, readonly editing = false, readonly block = true) { super(); } constructor(readonly html: string, readonly source: string, readonly context: ImageContext, readonly editing = false, readonly block = true) { super(); }
eq(other: ImagePreview) { return this.html === other.html && this.source === other.source && this.editing === other.editing && this.block === other.block; } eq(other: ImagePreview) { return this.html === other.html && this.source === other.source && this.editing === other.editing && this.block === other.block; }
get estimatedHeight() { return estimatedImageHeight(this.html); }
toDOM(view: EditorView) { toDOM(view: EditorView) {
const dom = document.createElement(this.block ? "div" : "span"); const dom = document.createElement(this.block ? "div" : "span");
dom.className = `reading writer-preview ${this.block ? "writer-image" : "writer-image-inline"}`; dom.className = `reading writer-preview ${this.block ? "writer-image" : "writer-image-inline"}`;
+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. */ /** The tooltip of a link in Write. A click with Ctrl, or Cmd on macOS, opens the link. */
const linkTooltip = () => tr("{modifier}+click to open link", { modifier: isMac() ? "⌘" : "Ctrl" }); const linkTooltip = () => tr("{modifier}+click to open link", { modifier: isMac() ? "⌘" : "Ctrl" });
import { EditorSelection, StateEffect, StateField, type EditorState, type Range } from "@codemirror/state"; import { EditorSelection, StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view"; import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language"; import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
import { renderMarkdownSections } from "../workspace/noteHtml"; import { renderMarkdownSections } from "../workspace/noteHtml";
import { renderDiagrams } from "../workspace/diagrams"; import { renderDiagrams } from "../workspace/diagrams";
@@ -22,9 +22,34 @@ import { listLabels } from "./markdownLists";
import { activeTableFormulas } from "../formulas/index.ts"; import { activeTableFormulas } from "../formulas/index.ts";
const previewFormulas = new WeakMap<HTMLElement, unknown>(); const previewFormulas = new WeakMap<HTMLElement, unknown>();
const previewHtml = new WeakMap<HTMLElement, string>();
export const refreshImages = StateEffect.define<void>(); export const refreshImages = StateEffect.define<void>();
const imageCleanups = new WeakMap<HTMLElement, () => void>(); const imageCleanups = new WeakMap<HTMLElement, () => void>();
/**
* CodeMirror reads the line height of the document from the first short line that holds only plain text.
* A different height makes it estimate all heights again, and the view then jumps to other text.
* A mark span keeps a line with a different height out of that reading.
*/
const otherLineHeight = Decoration.mark({ class: "writer-line-text" });
// A resize observer records the height of a preview without a CodeMirror measure request.
// A request from toDOM restarts the layout loop of CodeMirror, and a loop that restarts too often does not restore the scroll position.
const previewHeights = new WeakMap<Element, { value: number }>();
let previewSizes: ResizeObserver | undefined;
function watchPreviewHeight(dom: HTMLElement, height: { value: number }) {
previewSizes ??= new ResizeObserver(entries => {
for (const { target } of entries) {
const holder = previewHeights.get(target);
if (holder && target.isConnected) holder.value = (target as HTMLElement).offsetHeight;
}
});
const known = previewHeights.get(dom);
if (known && known !== height) height.value = known.value;
previewHeights.set(dom, height);
previewSizes.observe(dom);
}
const linkTooltips = ViewPlugin.define(view => { const linkTooltips = ViewPlugin.define(view => {
const attached = new Map<HTMLElement, () => void>(); const attached = new Map<HTMLElement, () => void>();
const refresh = () => { const refresh = () => {
@@ -119,23 +144,35 @@ class ListLabel extends WidgetType {
ignoreEvent() { return false; } ignoreEvent() { return false; }
} }
/**
* The heights of previews, by their HTML, from a layout outside the editor. CodeMirror draws only the lines near the view.
* Without a height, a large table counts as one line until its first draw. The document then grows by thousands of pixels
* at one time, the scrollbar moves, and the layout loop of CodeMirror can stop before it restores the scroll position.
*/
const measuredHeights = new Map<string, { width: number; height: number }>();
const maxMeasuredHeights = 1000;
class Preview extends WidgetType { class Preview extends WidgetType {
readonly formulas = activeTableFormulas(); readonly formulas = activeTableFormulas();
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) { super(); } readonly estimate: number;
get estimatedHeight() { return this.height.value; } constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) {
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; } super();
measure(dom: HTMLElement, view: EditorView) { this.estimate = measuredHeights.get(html)?.height ?? -1;
view.requestMeasure({ key: this.height, read: () => dom.offsetHeight, write: height => { this.height.value = height; } });
} }
updateDOM(dom: HTMLElement, view: EditorView) { get estimatedHeight() { return this.height.value >= 0 ? this.height.value : this.estimate; }
if (previewFormulas.get(dom) !== this.formulas || tableEditors.get(dom)?.source !== this.source) return false; // A new estimate must reach the height map of CodeMirror. updateDOM keeps the drawn table.
this.measure(dom, view); 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; 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) { toDOM(view: EditorView) {
const dom = document.createElement("div"); const dom = document.createElement("div");
previewFormulas.set(dom, this.formulas); previewFormulas.set(dom, this.formulas);
previewHtml.set(dom, this.html);
dom.className = "reading writer-preview"; dom.className = "reading writer-preview";
dom.innerHTML = this.html; dom.innerHTML = this.html;
// Widgets handle their own events, so CodeMirror's link handler cannot run. // Widgets handle their own events, so CodeMirror's link handler cannot run.
@@ -153,7 +190,7 @@ class Preview extends WidgetType {
}, { capture: true }); }, { capture: true });
tableControls(dom, view, this.source, this.actions); tableControls(dom, view, this.source, this.actions);
imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); })); imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); }));
this.measure(dom, view); watchPreviewHeight(dom, this.height);
dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove()); dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove());
dom.addEventListener("mousedown", event => { dom.addEventListener("mousedown", event => {
if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return; if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return;
@@ -174,6 +211,45 @@ class Preview extends WidgetType {
ignoreEvent() { return true; } ignoreEvent() { return true; }
} }
function textColumnWidth(view: EditorView) {
const style = getComputedStyle(view.contentDOM);
return view.contentDOM.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
}
/** Measure previews in one layout pass, in a hidden copy of the text column. A copy has the table frame and footer, but not the table controls. */
function measurePreviews(view: EditorView, widgets: Preview[], width: number) {
const host = document.createElement("div");
host.className = view.contentDOM.className;
host.setAttribute("aria-hidden", "true");
host.style.cssText = "position:absolute;inset:0 0 auto 0;height:0;min-height:0;padding-block:0;overflow:hidden;visibility:hidden;pointer-events:none";
const footer = document.createElement("div");
footer.className = "table-footer";
const tools = activeTableFormulas()?.createFormulaTools(() => {}, () => {});
if (tools) footer.append(tools.formulaTools);
const copies = widgets.map(widget => {
const copy = document.createElement("div");
copy.className = "reading writer-preview";
copy.innerHTML = widget.html;
const scroll = copy.querySelector(".md-table-scroll");
if (scroll && parseMarkdownTable(widget.source)) {
const frame = document.createElement("div");
frame.className = "writer-table";
scroll.before(frame);
frame.append(scroll);
frame.after(footer.cloneNode(true));
}
host.append(copy);
return copy;
});
view.scrollDOM.append(host);
if (measuredHeights.size + widgets.length > maxMeasuredHeights) measuredHeights.clear();
copies.forEach((copy, index) => {
measuredHeights.set(widgets[index].html, { width, height: copy.offsetHeight });
widgets[index].height.value = -1;
});
host.remove();
}
export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) { export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) {
const selecting = StateEffect.define<boolean>(); const selecting = StateEffect.define<boolean>();
const mouseSelecting = StateField.define({ const mouseSelecting = StateField.define({
@@ -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); const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to);
for (let number = 1; number <= state.doc.lines; number++) { for (let number = 1; number <= state.doc.lines; number++) {
const line = state.doc.line(number); const line = state.doc.line(number);
if (!line.text.trim() && !hidden(line.from, line.to)) 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 replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({ atomic: true }).range(from, to)); };
const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); }; const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); };
@@ -274,6 +353,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
for (let number = first.number; number <= last.number; number++) { for (let number = first.number; number <= last.number; number++) {
const line = state.doc.line(number); const line = state.doc.line(number);
ranges.push(Decoration.line({ class: editingCode ? "writer-code-source" : `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from)); ranges.push(Decoration.line({ class: editingCode ? "writer-code-source" : `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from));
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
} }
return false; return false;
} }
@@ -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() === "-"; const pendingList = node.name === "SetextHeading2" && state.doc.lineAt(node.to).text.trim() === "-";
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name) && !pendingList) { if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name) && !pendingList) {
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from)); ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
} }
if (node.name === "InlineCode") codeRanges.push({ from: node.from, to: node.to }); if (node.name === "InlineCode") codeRanges.push({ from: node.from, to: node.to });
if (node.name === "TaskMarker") { if (node.name === "TaskMarker") {
@@ -366,6 +447,36 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
filter: (_from, _to, decoration) => decoration.spec.atomic === true, filter: (_from, _to, decoration) => decoration.spec.atomic === true,
}))], }))],
}); });
// Give each preview that is not drawn a height, after the document opens, changes, or gets another width.
const previewMeasuring = ViewPlugin.fromClass(class {
frame = 0;
width = -1;
constructor(readonly view: EditorView) { this.schedule(); }
update(update: ViewUpdate) {
if (update.geometryChanged || update.startState.field(decorations) !== update.state.field(decorations)) this.schedule();
}
schedule() {
this.frame ||= requestAnimationFrame(() => { this.frame = 0; this.measure(); });
}
measure() {
const { view } = this, width = textColumnWidth(view);
// The editor has no width while another view or tab covers it.
if (width < 50) return;
const resized = Math.abs(width - this.width) > 1;
this.width = width;
const { from: drawnFrom, to: drawnTo } = view.viewport;
const widgets: Preview[] = [];
view.state.field(decorations).between(0, view.state.doc.length, (from, to, decoration) => {
const widget = decoration.spec.widget;
if (!(widget instanceof Preview) || (from < drawnTo && to > drawnFrom)) return;
if ((resized || widget.height.value < 0) && measuredHeights.get(widget.html)?.width !== width) widgets.push(widget);
});
if (!widgets.length) return;
measurePreviews(view, widgets, width);
view.dispatch({ effects: refreshImages.of() });
}
destroy() { cancelAnimationFrame(this.frame); }
});
const mousePreview = ViewPlugin.define(view => { const mousePreview = ViewPlugin.define(view => {
const finish = () => { const finish = () => {
if (!view.state.field(mouseSelecting)) return; if (!view.state.field(mouseSelecting)) return;
@@ -400,6 +511,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
window.removeEventListener("blur", finish); 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))]; EditorView.focusChangeEffect.of((_state, focusing) => focusBody.of(focusing))];
} }
+17 -1
View File
@@ -1,10 +1,18 @@
import { SearchQuery } from "@codemirror/search"; import { SearchQuery } from "@codemirror/search";
import { documentMatches, type FindTarget } from "./findTarget"; import { documentMatches, type FindTarget } from "./findTarget";
/** Keys that do not change the text of the find field. These keys keep the selected match. */
const keepsMatch = /^(?:Enter|Escape|Tab|Shift|Control|Alt|Meta|CapsLock|ContextMenu|F\d+)$/;
/** Search the visible reading text without changing its Markdown or rendered nodes. */ /** Search the visible reading text without changing its Markdown or rendered nodes. */
export function readingSearch(root: HTMLElement, close: () => void, options: { includeButtons?: boolean; focusOnClose?: () => void } = {}): FindTarget { export function readingSearch(root: HTMLElement, close: () => void, options: { includeButtons?: boolean; focusOnClose?: () => void } = {}): FindTarget {
let query = new SearchQuery({ search: "" }); let query = new SearchQuery({ search: "" });
let current = -1; let current = -1;
// The window selection also holds the caret of a focused find field. There it reads as collapsed and outside the text.
function matchSelected() {
const selection = window.getSelection();
return !!selection && !selection.isCollapsed && root.contains(selection.anchorNode);
}
function ranges() { function ranges() {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
const nodes: { node: Text; from: number; to: number }[] = []; const nodes: { node: Text; from: number; to: number }[] = [];
@@ -40,7 +48,15 @@ export function readingSearch(root: HTMLElement, close: () => void, options: { i
} }
return { return {
get query() { return query; }, readOnly: true, canSelectAll: false, get query() { return query; }, readOnly: true, canSelectAll: false,
setQuery(value) { if (query.eq(value)) return; query = value; current = -1; 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() {}, next, selectAll() {}, replace() {},
close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); }, close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); },
}; };
+1 -1
View File
@@ -35,7 +35,7 @@
.table-drag-handle[hidden], .table-drop-indicator[hidden] { display: none; } .table-drag-handle[hidden], .table-drop-indicator[hidden] { display: none; }
.table-drag-handle .action-icon { width: 18px; height: 18px; pointer-events: none; } .table-drag-handle .action-icon { width: 18px; height: 18px; pointer-events: none; }
.table-drag-column .action-icon { transform: rotate(90deg); } .table-drag-column .action-icon { transform: rotate(90deg); }
.table-drag-handle:hover, .table-drag-handle:focus-visible:not([data-pointer-focus]) { opacity: 1; color: var(--rs-text); background: var(--rs-bg-active); outline: 2px solid var(--rs-accent); outline-offset: -2px; z-index: 2; } .table-drag-handle:hover, .table-drag-handle:focus-visible:not([data-pointer-focus]) { opacity: 1; color: var(--rs-text); background: var(--rs-hover-bg); outline: 2px solid var(--rs-accent); outline-offset: -2px; z-index: 2; }
.writer-table.is-table-dragging, .writer-table.is-table-dragging * { cursor: grabbing !important; user-select: none; } .writer-table.is-table-dragging, .writer-table.is-table-dragging * { cursor: grabbing !important; user-select: none; }
.writer-table.is-table-dragging .table-drag-handle::after { display: none; } .writer-table.is-table-dragging .table-drag-handle::after { display: none; }
.table-drop-indicator { position: absolute; z-index: 3; border-radius: 2px; background: var(--rs-accent); pointer-events: none; } .table-drop-indicator { position: absolute; z-index: 3; border-radius: 2px; background: var(--rs-accent); pointer-events: none; }
+7
View File
@@ -451,6 +451,13 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
event.preventDefault(); activate(cell); event.preventDefault(); activate(cell);
const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY }); const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY });
if (hit) { editor?.commands.setTextSelection(hit.pos); editor?.view.focus(); } if (hit) { editor?.commands.setTextSelection(hit.pos); editor?.view.focus(); }
} else if (event.detail === 1 && editor && !editor.view.composing && editor.view.dom.contains(event.target)) {
// ProseMirror reads a native click on the next selectionchange. Its
// delayed focus check can run first and restore the old selection, so
// the click is lost under load. Set the clicked position here. The
// browser then places the same caret, and a drag starts from it.
const hit = editor.view.posAtCoords({ left: event.clientX, top: event.clientY });
if (hit) editor.commands.setTextSelection(hit.pos);
} }
}); });
refreshFormulas(); refreshFormulas();
+1 -1
View File
@@ -32,7 +32,7 @@
.header { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; } .header { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
strong { flex: 1; min-width: 0; overflow-wrap: anywhere; } strong { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.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 { 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:not(:disabled) { background: var(--rs-bg-active); } .text-button:hover:not(:disabled) { background: var(--rs-hover-bg); }
.text-button:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; } .text-button:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
.text-button:disabled { color: var(--rs-text-dim); } .text-button:disabled { color: var(--rs-text-dim); }
.error { margin: 0; color: var(--rs-error); } .error { margin: 0; color: var(--rs-error); }
+2 -2
View File
@@ -216,7 +216,7 @@
ol { flex: 1; min-width: 0; margin: 0; padding: 0; list-style: none; } ol { flex: 1; min-width: 0; margin: 0; padding: 0; list-style: none; }
li { height: 30px; min-width: 0; } li { height: 30px; min-width: 0; }
ol button { display: grid; grid-template-columns: minmax(0, 1fr) 95px 78px 54px; align-items: center; gap: 8px; width: 100%; height: 30px; padding: 0 6px; border: var(--rs-item-selection-width) solid transparent; border-radius: var(--rs-item-selection-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; } ol button { display: grid; grid-template-columns: minmax(0, 1fr) 95px 78px 54px; align-items: center; gap: 8px; width: 100%; height: 30px; padding: 0 6px; border: var(--rs-item-selection-width) solid transparent; border-radius: var(--rs-item-selection-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
ol button:hover { background: var(--rs-bg-active); } ol button:hover { background: var(--rs-hover-bg); }
ol button[aria-selected="true"], .file[aria-pressed="true"] { background: var(--rs-item-selection-bg); border-color: var(--rs-item-selection-border); } ol button[aria-selected="true"], .file[aria-pressed="true"] { background: var(--rs-item-selection-bg); border-color: var(--rs-item-selection-border); }
ol button:focus-visible, .file:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; } ol button:focus-visible, .file:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
.description { display: flex; align-items: center; gap: 5px; min-width: 0; } .description { display: flex; align-items: center; gap: 5px; min-width: 0; }
@@ -233,7 +233,7 @@
.message { white-space: pre-wrap; overflow-wrap: anywhere; } .message { white-space: pre-wrap; overflow-wrap: anywhere; }
.files { display: flex; flex-direction: column; flex-shrink: 0; max-height: 180px; overflow: auto; } .files { display: flex; flex-direction: column; flex-shrink: 0; max-height: 180px; overflow: auto; }
.file { display: flex; flex-shrink: 0; align-items: center; gap: 6px; min-width: 0; min-height: 28px; padding: 3px 6px; border: var(--rs-item-selection-width) solid transparent; border-radius: var(--rs-item-selection-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; } .file { display: flex; flex-shrink: 0; align-items: center; gap: 6px; min-width: 0; min-height: 28px; padding: 3px 6px; border: var(--rs-item-selection-width) solid transparent; border-radius: var(--rs-item-selection-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
.file:hover { background: var(--rs-bg-active); } .file:hover { background: var(--rs-hover-bg); }
.file span:first-child { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .file span:first-child { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.details :global(.diff) { min-height: 140px; } .details :global(.diff) { min-height: 140px; }
@container (max-width: 950px) { ol button { grid-template-columns: minmax(0, 1fr) 54px; } .author, .date { display: none; } } @container (max-width: 950px) { ol button { grid-template-columns: minmax(0, 1fr) 54px; } .author, .date { display: none; } }
+3 -3
View File
@@ -179,20 +179,20 @@
textarea { box-sizing: border-box; width: 100%; min-height: 60px; resize: vertical; padding: 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; } textarea { box-sizing: border-box; width: 100%; min-height: 60px; resize: vertical; padding: 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
textarea:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; } textarea:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; }
.primary { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 28px; padding: 3px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; font-weight: 600; } .primary { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 28px; padding: 3px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; font-weight: 600; }
.primary:hover:not(:disabled) { background: var(--rs-bg-active); } .primary:hover:not(:disabled) { background: var(--rs-hover-bg); }
.primary:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; } .primary:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
.primary:disabled { color: var(--rs-text-dim); } .primary:disabled { color: var(--rs-text-dim); }
small { color: var(--rs-text-dim); line-height: 1.5; } small { color: var(--rs-text-dim); line-height: 1.5; }
.changes { min-width: 0; border-top: 1px solid var(--rs-border); } .changes { min-width: 0; border-top: 1px solid var(--rs-border); }
summary { padding: 8px 4px; border-radius: var(--rs-control-radius); cursor: pointer; font-weight: 600; } summary { padding: 8px 4px; border-radius: var(--rs-control-radius); cursor: pointer; font-weight: 600; }
summary:hover { background: var(--rs-bg-active); } summary:hover { background: var(--rs-hover-bg); }
summary:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; } summary:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
.group { margin-bottom: 6px; } .group { margin-bottom: 6px; }
.group-header { display: flex; align-items: center; gap: 6px; padding-bottom: 4px; } .group-header { display: flex; align-items: center; gap: 6px; padding-bottom: 4px; }
h3 { flex: 1; margin: 0; padding-left: 4px; font: inherit; font-weight: 600; } h3 { flex: 1; margin: 0; padding-left: 4px; font: inherit; font-weight: 600; }
.row { display: flex; align-items: center; gap: 3px; min-width: 0; } .row { display: flex; align-items: center; gap: 3px; min-width: 0; }
.file { display: flex; flex: 1; align-items: center; gap: 6px; min-width: 0; min-height: 28px; padding: 4px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; } .file { display: flex; flex: 1; align-items: center; gap: 6px; min-width: 0; min-height: 28px; padding: 4px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
.file:hover:not(:disabled) { background: var(--rs-bg-active); } .file:hover:not(:disabled) { background: var(--rs-hover-bg); }
.file:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; } .file:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
.file:disabled { color: var(--rs-text-dim); } .file:disabled { color: var(--rs-text-dim); }
.file span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .file span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+179 -68
View File
@@ -1,28 +1,32 @@
<script lang="ts"> <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. // 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 { message, t } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte"; import IconButton from "$lib/ui/IconButton.svelte";
import type { PluginDocumentContext } from "$lib/plugins/sdk"; import type { PluginDocumentContext } from "$lib/plugins/sdk";
import { openPdf, TextLayer, type OpenPdf, type PDFDocumentProxy, type RenderTask } from "./engine"; import { openPdf, TextLayer, type OpenPdf, type PDFDocumentProxy, type RenderTask } from "./engine";
import { MAX_ZOOM, MIN_ZOOM, 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(); let { file, readBytes }: { file: PluginDocumentContext; readBytes: (path: string) => Promise<Uint8Array> } = $props();
type Status = { key: string; values?: Record<string, string | number>; alert?: boolean }; type Status = { key: string; values?: Record<string, string | number>; alert?: boolean };
/** One page that has a drawing, or waits for one. `key` names the zoom, the rotation, and the pixel ratio. */
type Drawing = { key: string; done: boolean; cancel(): void };
let page = $state(1); let page = $state(1);
let count = $state(0); let count = $state(0);
let zoom = $state(1); let zoom = $state(1);
let rotation = $state(0); let rotation = $state(0);
let fit = $state(true); let fit = $state(true);
let sizes = $state.raw<PageSize[]>([]);
let status = $state<Status>({ key: message("Loading PDF…") }); let status = $state<Status>({ key: message("Loading PDF…") });
let asking = $state<"needed" | "incorrect" | null>(null); let asking = $state<"needed" | "incorrect" | null>(null);
let reloading = $state(false); let reloading = $state(false);
let failed = $state(false); let failed = $state(false);
let scroller: HTMLDivElement; let scroller: HTMLDivElement;
let sheet: HTMLDivElement; let sheets: HTMLDivElement[] = $state([]);
let pageInput: HTMLInputElement; let pageInput: HTMLInputElement;
let passwordInput: HTMLInputElement | undefined = $state(); let passwordInput: HTMLInputElement | undefined = $state();
@@ -30,14 +34,20 @@
let pdf: PDFDocumentProxy | undefined; let pdf: PDFDocumentProxy | undefined;
let opened: OpenPdf | undefined; let opened: OpenPdf | undefined;
let answer: ((password: string) => void) | undefined; let answer: ((password: string) => void) | undefined;
let render: RenderTask | undefined; let generation = 0;
let text: TextLayer | undefined; const drawings = new Map<number, Drawing>();
let revision = 0;
let queue: Promise<void> = Promise.resolve(); let queue: Promise<void> = Promise.resolve();
let loading: Promise<void> = Promise.resolve(); let loading: Promise<void> = Promise.resolve();
let closing: Promise<void> | undefined; let closing: Promise<void> | undefined;
// The place in the document: a page and the part of its height above the top of the visible area.
let anchor = { index: 0, part: 0 };
// The scroll position that the viewer set. A scroll event at this position keeps the page number.
let settled = -1;
let frame = 0;
const ready = $derived(count > 0); const ready = $derived(count > 0);
const boxes = $derived(pageBoxes(sizes, zoom, rotation));
const zoomText = $derived(ready ? `${Math.round(zoom * 100)}%` : "—");
function fail(reason: unknown) { function fail(reason: unknown) {
if (disposed) return; if (disposed) return;
@@ -45,53 +55,137 @@
status = { key: message("Cannot display this PDF. {reason}"), values: { reason: reason instanceof Error ? reason.message : String(reason) }, alert: true }; status = { key: message("Cannot display this PDF. {reason}"), values: { reason: reason instanceof Error ? reason.message : String(reason) }, alert: true };
} }
/** Draw the current page again. A newer request cancels the older one. */ const drawingKey = () => `${zoom}:${rotation}:${window.devicePixelRatio}`;
function schedule() {
const request = ++revision; /** The status line names the current page when its drawing is complete. */
render?.cancel(); text?.cancel(); function report() {
if (pdf && !disposed) status = { key: message("Loading page {page}…"), values: { page } }; 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 () => { queue = queue.then(async () => {
if (disposed || request !== revision || !pdf || scroller.clientWidth === 0) return; if (cancelled || disposed || !source) return;
const pdfPage = await pdf.getPage(page); const pdfPage = await source.getPage(number);
if (disposed || request !== revision) return; const sheet = sheets[number - 1];
const angle = (pdfPage.rotate + rotation) % 360; if (cancelled || disposed || !sheet) return;
if (fit) zoom = zoomLevel((scroller.clientWidth - 32) / pdfPage.getViewport({ scale: 1, rotation: angle }).width); const viewport = pdfPage.getViewport({ scale: zoom, rotation: (pdfPage.rotate + rotation) % 360 });
const viewport = pdfPage.getViewport({ scale: zoom, rotation: angle });
const scale = outputScale(viewport.width, viewport.height, window.devicePixelRatio); const scale = outputScale(viewport.width, viewport.height, window.devicePixelRatio);
const canvas = document.createElement("canvas"); const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.floor(viewport.width * scale)); canvas.width = Math.max(1, Math.floor(viewport.width * scale));
canvas.height = Math.max(1, Math.floor(viewport.height * scale)); canvas.height = Math.max(1, Math.floor(viewport.height * scale));
canvas.style.width = `${viewport.width}px`;
canvas.style.height = `${viewport.height}px`;
canvas.setAttribute("role", "img"); canvas.setAttribute("role", "img");
// The measurement tool and the smoke tests find the page by this English name. Keep "PDF page N". // The measurement tool and the smoke tests find the page by this English name. Keep "PDF page N".
canvas.setAttribute("aria-label", $t("PDF page {page}", { page })); canvas.setAttribute("aria-label", $t("PDF page {page}", { page: number }));
const layer = document.createElement("div"); const layer = document.createElement("div");
layer.className = "textLayer"; layer.className = "textLayer";
sheet.style.width = `${viewport.width}px`; layer.style.setProperty("--total-scale-factor", String(viewport.scale));
sheet.style.height = `${viewport.height}px`;
sheet.style.setProperty("--total-scale-factor", String(zoom));
sheet.replaceChildren(canvas, layer);
render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] }); render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] });
await render.promise; await render.promise;
if (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 }); text = new TextLayer({ textContentSource: pdfPage.streamTextContent(), container: layer, viewport });
await text.render(); await text.render();
if (disposed || request !== revision) return; if (cancelled || disposed) return;
status = { key: message("Page {page} of {count}"), values: { page, count } }; drawing.done = true;
pdfPage.cleanup(); 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) { function go(value: number) {
if (!pdf) return; if (!pdf) return;
page = pageNumber(value, pdf.numPages); page = pageNumber(value, pdf.numPages);
pageInput.value = String(page); pageInput.value = String(page);
scroller.scrollTop = 0; // The first page shows with the margin above it. Each other page shows with half of the gap above it.
schedule(); 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() { async function load() {
failed = false; failed = false;
@@ -105,20 +199,27 @@
status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") }; status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") };
queueMicrotask(() => passwordInput?.focus()); queueMicrotask(() => passwordInput?.focus());
}); });
pdf = await opened.promise; const source = await opened.promise;
if (disposed) return; if (disposed) return;
page = pageNumber(page, pdf.numPages); const current = ++generation;
count = pdf.numPages; const { width, height } = (await source.getPage(1)).getViewport({ scale: 1 });
schedule(); 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() { async function release() {
revision++; generation++;
render?.cancel(); text?.cancel(); for (const drawing of drawings.values()) drawing.cancel();
drawings.clear();
await queue; await queue;
const current = opened; const current = opened;
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0; opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0; sizes = [];
sheet?.replaceChildren();
await current?.close(); await current?.close();
} }
@@ -145,12 +246,11 @@
next(value); next(value);
} }
function pageKey(event: KeyboardEvent) { /** Ctrl and the wheel change the zoom. The wheel alone scrolls the pages. */
if (event.ctrlKey || event.metaKey || event.altKey || !ready) return; function wheel(event: WheelEvent) {
if (event.key === "PageDown" || event.key === "PageUp") { if (!(event.ctrlKey || event.metaKey) || !ready || event.deltaY === 0) return;
event.preventDefault(); event.preventDefault();
go(page + (event.key === "PageDown" ? 1 : -1)); 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. */ /** Stop the drawing, release the document, and stop its worker. The host calls it before it removes the tab. */
@@ -163,21 +263,23 @@
onMount(() => { onMount(() => {
loading = load().catch(fail); 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 width = 0;
let timer: ReturnType<typeof setTimeout> | undefined; let timer: ReturnType<typeof setTimeout> | undefined;
const resized = () => { applyFit(); restore(); };
const observer = new ResizeObserver(() => { const observer = new ResizeObserver(() => {
const next = scroller.clientWidth; const next = scroller.clientWidth;
if (next === 0 || next === width) return; if (next === width) return;
const first = width === 0; const shown = width === 0;
width = next; width = next;
clearTimeout(timer); clearTimeout(timer);
if (!fit) return; if (next === 0) return;
if (first) schedule(); if (shown) resized();
else timer = setTimeout(schedule, RESIZE_SETTLE_MS); else timer = setTimeout(resized, RESIZE_SETTLE_MS);
}); });
observer.observe(scroller); 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> </script>
@@ -191,10 +293,12 @@
<IconButton icon="down" label={$t("Next page")} disabled={!ready || page >= count} onclick={() => go(page + 1)} /> <IconButton icon="down" label={$t("Next page")} disabled={!ready || page >= count} onclick={() => go(page + 1)} />
<span class="separator" aria-hidden="true"></span> <span class="separator" aria-hidden="true"></span>
<IconButton icon="zoom-out" label={$t("Zoom out")} disabled={!ready || zoom <= MIN_ZOOM} onclick={() => setZoom(zoom / ZOOM_STEP)} /> <IconButton icon="zoom-out" label={$t("Zoom out")} disabled={!ready || zoom <= MIN_ZOOM} onclick={() => setZoom(zoom / ZOOM_STEP)} />
<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="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="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); schedule(); }} /> <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()} /> <IconButton icon="refresh" label={$t("Reload PDF")} disabled={reloading || (!ready && !failed)} onclick={() => void reload()} />
</div> </div>
<p class="status" class:alert={status.alert} role={status.alert ? "alert" : "status"} aria-live={status.alert ? "assertive" : "polite"}>{$t(status.key, status.values)}</p> <p class="status" class:alert={status.alert} role={status.alert ? "alert" : "status"} aria-live={status.alert ? "assertive" : "polite"}>{$t(status.key, status.values)}</p>
@@ -204,32 +308,39 @@
<button class="text-button" type="submit">{$t("Unlock")}</button> <button class="text-button" type="submit">{$t("Unlock")}</button>
</form> </form>
{/if} {/if}
<!-- The page area takes focus for Page Up and Page Down. --> <!-- 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, a11y_no_noninteractive_element_interactions --> <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<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={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF pages")} data-tab-focus onscroll={scrolled}>
<div bind:this={sheet} class="sheet"></div> <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> </div>
</section> </section>
<style> <style>
.pdf-viewer { display: flex; flex-direction: column; height: 100%; min-height: 240px; min-width: 0; color: var(--rs-text); font-size: 13px; } .pdf-viewer { display: flex; flex-direction: column; height: 100%; min-height: 240px; min-width: 0; color: var(--rs-text); font-size: 13px; }
.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 { 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; } .count { margin: 0 4px; color: var(--rs-text-dim); white-space: nowrap; }
.separator { width: 1px; height: 18px; margin: 0 4px; background: var(--rs-border); } .separator { width: 1px; height: 18px; margin: 0 4px; background: var(--rs-border); }
.zoom { min-width: 44px; color: var(--rs-text-dim); text-align: center; white-space: nowrap; } .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; font-size: 12px; color: var(--rs-text-dim); overflow-wrap: anywhere; } .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); } .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; } .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 { 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); } .text-button:hover { background: var(--rs-bg-active); }
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; } /* 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; } .scroll:focus-visible { outline-offset: -2px; }
.pages { display: flex; flex-direction: column; align-items: center; gap: 12px; width: max-content; min-width: 100%; }
/* A PDF page is paper: white in both themes. */ /* A PDF page is paper: white in both themes. */
.sheet { position: relative; margin: 0 auto; background: white; box-shadow: 0 2px 10px #0003; } .sheet { position: relative; flex: none; background: white; box-shadow: 0 2px 10px #0003; }
.sheet :global(canvas) { display: block; } .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. */ /* The text layer geometry follows the viewer styles of PDF.js 6 (Apache-2.0). See THIRD_PARTY_NOTICES.md. */
.sheet :global(.textLayer) { position: absolute; inset: 0; overflow: clip; text-align: initial; line-height: 1; letter-spacing: normal; word-spacing: normal; text-size-adjust: none; forced-color-adjust: none; transform-origin: 0 0; --min-font-size: 1; --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size)); --min-font-size-inv: calc(1 / var(--min-font-size)); } .sheet :global(.textLayer) { position: absolute; inset: 0; overflow: clip; text-align: initial; line-height: 1; letter-spacing: normal; word-spacing: normal; text-size-adjust: none; forced-color-adjust: none; transform-origin: 0 0; --min-font-size: 1; --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size)); --min-font-size-inv: calc(1 / var(--min-font-size)); }
.sheet :global(.textLayer :is(span, br)) { position: absolute; color: transparent; white-space: pre; cursor: text; transform-origin: 0 0; user-select: text; } .sheet :global(.textLayer :is(span, br)) { position: absolute; color: transparent; white-space: pre; cursor: text; transform-origin: 0 0; user-select: text; }
+57
View File
@@ -29,3 +29,60 @@ export function nextRotation(rotation: number): number {
export function outputScale(width: number, height: number, deviceScale: number): number { export function outputScale(width: number, height: number, deviceScale: number): number {
return Math.min(deviceScale || 1, 2, 8192 / width, 8192 / height, Math.sqrt(16_000_000 / (width * height))); return Math.min(deviceScale || 1, 2, 8192 / width, 8192 / height, Math.sqrt(16_000_000 / (width * height)));
} }
/** The space around the pages and between two pages, in CSS pixels. `PdfViewer.svelte` uses the same values in its styles. */
export const PAGE_MARGIN = 16;
export const PAGE_GAP = 12;
/** The size of a page at zoom 1, with the rotation of the file. */
export interface PageSize { width: number; height: number }
/** The place of a page in the column of pages, in whole CSS pixels. */
export interface PageBox { top: number; width: number; height: number }
/** The zoom factor for typed text such as "150" or "150 %". Text that is not a number gives null. */
export function zoomFromText(text: string): number | null {
const value = Number(text.replace("%", "").replace(",", ".").trim());
return text.trim() && Number.isFinite(value) && value > 0 ? zoomLevel(value / 100) : null;
}
/** The zoom that fits the widest page in `available` pixels. */
export function fitZoom(sizes: readonly PageSize[], rotation: number, available: number): number {
const turned = rotation % 180 !== 0;
const widest = Math.max(0, ...sizes.map(size => turned ? size.height : size.width));
return zoomLevel(widest > 0 ? available / widest : 1);
}
/** One box for each page, from the top of the column to the bottom. */
export function pageBoxes(sizes: readonly PageSize[], zoom: number, rotation: number): PageBox[] {
const turned = rotation % 180 !== 0;
let top = PAGE_MARGIN;
return sizes.map(size => {
const width = Math.max(1, Math.floor((turned ? size.height : size.width) * zoom));
const height = Math.max(1, Math.floor((turned ? size.width : size.height) * zoom));
const box = { top, width, height };
top += height + PAGE_GAP;
return box;
});
}
/** The numbers of the pages that touch the range from `from` to `to`. */
export function pagesInRange(boxes: readonly PageBox[], from: number, to: number): number[] {
const pages: number[] = [];
for (let index = 0; index < boxes.length; index++) {
if (boxes[index].top >= to) break;
if (boxes[index].top + boxes[index].height > from) pages.push(index + 1);
}
return pages;
}
/** The number of the page that shows the most in the range from `from` to `to`. The first such page wins. */
export function mostVisiblePage(boxes: readonly PageBox[], from: number, to: number): number {
let page = 1, most = 0;
for (let index = 0; index < boxes.length; index++) {
const { top, height } = boxes[index];
if (top >= to) break;
const shown = Math.min(top + height, to) - Math.max(top, from);
if (shown > most) { most = shown; page = index + 1; }
}
return page;
}
@@ -1,34 +1,77 @@
import type { Workspace } from "../model/model.ts"; import type { Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts"; import { readOptional, saveDocument } from "./persistence.ts";
import { message } from "./message.ts"; import { message } from "./message.ts";
import { imagePath, parseImage } from "./images.ts";
/** 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 { export class DescriptionDraft {
private source: string | null = null; private source: string | null = null;
private imageSource: string | null = null;
private images: ReadonlyMap<string, string> = new Map();
private queue: Promise<unknown> = Promise.resolve(); private queue: Promise<unknown> = Promise.resolve();
readonly path: string; readonly path: string;
readonly imagesPath: string;
private workspace: Workspace; private workspace: Workspace;
constructor(workspace: Workspace, id: string) { constructor(workspace: Workspace, id: string) {
this.workspace = workspace; this.workspace = workspace;
const key = Array.from(new TextEncoder().encode(id), byte => byte.toString(16).padStart(2, "0")).join(""); const key = Array.from(new TextEncoder().encode(id), byte => byte.toString(16).padStart(2, "0")).join("");
this.path = `.runestone/pm/drafts/${key}.json`; this.path = `.runestone/pm/drafts/${key}.json`;
this.imagesPath = `.runestone/pm/drafts/${key}.images.json`;
} }
async load(): Promise<string | null> { async load(): Promise<string | null> {
this.source = await readOptional(this.workspace, this.path); this.source = await readOptional(this.workspace, this.path);
if (this.source === null) return null; if (this.source === null) return null;
const value = JSON.parse(this.source); const value = JSON.parse(this.source);
if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string")) if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string"))
throw new Error(message("The description draft is invalid. Preserve it before recovery.")); throw invalidDraft();
return value.body; 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 write = this.queue.then(async () => {
const next = body === null ? new Map<string, string>() : images;
// Keep the old and the new image data until the text is saved, so that each saved reference has its data.
await this.saveImages(new Map([...this.images, ...next]));
const source = JSON.stringify({ schema: 1, body }) + "\n"; const source = JSON.stringify({ schema: 1, body }) + "\n";
if (source === this.source || (body === null && this.source === null)) return; if (source !== this.source && !(body === null && this.source === null)) {
await saveDocument(this.workspace, this.path, source, this.source); await saveDocument(this.workspace, this.path, source, this.source);
this.source = source; this.source = source;
}
await this.saveImages(next);
}); });
this.queue = write.catch(() => {}); this.queue = write.catch(() => {});
return write; return write;
} }
private async saveImages(images: ReadonlyMap<string, string>) {
if (sameImages(images, this.images) || (!images.size && this.imageSource === null)) return;
const sorted = [...images].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
const source = JSON.stringify({ schema: 1, images: Object.fromEntries(sorted) }) + "\n";
await saveDocument(this.workspace, this.imagesPath, source, this.imageSource);
this.imageSource = source;
this.images = new Map(images);
}
} }
+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.")); throw new Error(message("The saved image is invalid or exceeds 50 MiB."));
return value.data; return value.data;
} }
/** Write the pending images that `body`, `attachments`, or `ids` refer to. Returns the IDs of the written images. */
export async function saveImages( export async function saveImages(
workspace: Workspace, workspace: Workspace,
body: string, body: string,
pending: Map<string, string>, pending: ReadonlyMap<string, string>,
attachments: TaskFields["attachments"] = [], 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); const data = pending.get(id);
if (!data) continue; if (!data) continue;
const source = JSON.stringify({ schema: 1, data }) + "\n"; const source = JSON.stringify({ schema: 1, data }) + "\n";
@@ -66,5 +69,7 @@ export async function saveImages(
// Retrying a failed card save reuses its complete image files. // Retrying a failed card save reuses its complete image files.
const previous = await workspace.readOptional?.(path); const previous = await workspace.readOptional?.(path);
if (previous !== source) await saveDocument(workspace, path, source, null); if (previous !== source) await saveDocument(workspace, path, source, null);
saved.push(id);
} }
return saved;
} }
+63 -14
View File
@@ -11,6 +11,30 @@ import {
parseImage, parseImage,
saveImages, saveImages,
} from "../storage/images.ts"; } 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. */ /** The image data stays outside the card Markdown and loads only in the open editor. */
export function createCardImages( 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; if (disposed || loading || description.disabled || !files.length) return;
loading = true; loading = true;
updateControls(); updateControls();
@@ -237,18 +262,20 @@ export function createCardImages(
end = description.selectionEnd; end = description.selectionEnd;
try { try {
const staged: { id: string; name: string; data: string }[] = []; const staged: { id: string; name: string; data: string }[] = [];
let refused = false;
for (const file of files) { 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.")); 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.")); throw new Error(message("Use an image between 1 byte and 50 MiB."));
const bytes = new Uint8Array(await file.arrayBuffer()); const data = original?.data ?? await fileDataUrl(file);
let binary = ""; const name = original ? `${(file.name || "image").replace(/\.\w+$/, "")}.${original.type.slice(6)}` : file.name;
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)}`;
// Decode the image before the reference goes in, so that an invalid clipboard file keeps the draft. // Decode the image before the reference goes in, so that an invalid clipboard file keeps the draft.
const image = new Image(); const image = new Image();
image.src = data; image.src = data;
@@ -257,7 +284,7 @@ export function createCardImages(
}); });
staged.push({ staged.push({
id: crypto.randomUUID(), id: crypto.randomUUID(),
name: (file.name || tr("Pasted image")).slice(0, 255), name: (name || tr("Pasted image")).slice(0, 255),
data, data,
}); });
} }
@@ -269,6 +296,7 @@ export function createCardImages(
description.setRangeText(`\n${markdown}\n`, start, end, "end"); description.setRangeText(`\n${markdown}\n`, start, end, "end");
} }
description.dispatchEvent(new Event("input", { bubbles: true })); 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) { } catch (reason) {
if (!disposed) if (!disposed)
(attachOnly ? attachmentError : error).textContent = errorText(reason); (attachOnly ? attachmentError : error).textContent = errorText(reason);
@@ -288,7 +316,9 @@ export function createCardImages(
if (!files.length) return; if (!files.length) return;
event.preventDefault(); event.preventDefault();
event.stopPropagation(); 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) => { const dragOver = (event: DragEvent) => {
if (event.dataTransfer?.types.includes("Files")) { if (event.dataTransfer?.types.includes("Files")) {
@@ -339,7 +369,26 @@ export function createCardImages(
saving = value; saving = value;
updateControls(); 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() { dispose() {
disposed = true; disposed = true;
clearTimeout(idleTimer); clearTimeout(idleTimer);
@@ -347,7 +396,7 @@ export function createCardImages(
viewerObserver = undefined; viewerObserver = undefined;
viewer?.remove(); viewer = undefined; viewer?.remove(); viewer = undefined;
revision++; revision++;
pending.clear(); // Keep the pending image data. A draft save that is in progress after a close still needs it.
loaded.clear(); loaded.clear();
description.removeEventListener("paste", paste); description.removeEventListener("paste", paste);
description.removeEventListener("input", render); description.removeEventListener("input", render);
+4 -3
View File
@@ -67,7 +67,7 @@
cursor: default; cursor: default;
} }
.rs-pm button:not(.rs-picker-row):not([role^="menuitem"]):focus-visible, .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 select:focus-visible,
.rs-pm textarea:focus-visible { .rs-pm textarea:focus-visible {
outline: 1px solid var(--pm-accent); outline: 1px solid var(--pm-accent);
@@ -196,7 +196,8 @@
.pm-search-row input { .pm-search-row input {
width: min(340px, 100%); 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 select,
.rs-pm textarea { .rs-pm textarea {
background: var(--pm-field-surface); background: var(--pm-field-surface);
@@ -205,7 +206,7 @@
padding: 6px 8px; padding: 6px 8px;
min-height: 30px; 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; min-height: 0;
width: 16px; width: 16px;
height: 16px; height: 16px;
+17 -7
View File
@@ -1051,7 +1051,11 @@ export function mountPM(
description, description,
(name, action) => button(tr(name), action, name === "Actual size" ? "expand" : "image"), (name, action) => button(tr(name), action, name === "Actual size" ? "expand" : "image"),
(name, action) => iconButton(name, "close", action), (name, action) => iconButton(name, "close", action),
(loading) => { 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, task?.attachments,
); );
const formattingIcons: Record<string, keyof typeof icons> = { const formattingIcons: Record<string, keyof typeof icons> = {
@@ -1064,9 +1068,10 @@ export function mountPM(
let descriptionSaving = false; let descriptionSaving = false;
let draftTimer: ReturnType<typeof setTimeout> | undefined; let draftTimer: ReturnType<typeof setTimeout> | undefined;
let draftEdited = false; let draftEdited = false;
const draftReady = draft?.load().then(body => { const draftReady = draft && Promise.all([draft.load(), draft.loadImages()]).then(([body, draftImages]) => {
if (body !== null && !draftEdited && dialog.isConnected) { if (body !== null && !draftEdited && dialog.isConnected) {
descriptionEditor.restoreDraft(body); descriptionEditor.restoreDraft(body);
images.restore(draftImages);
updateDescriptionBadge(task!.id, body !== task!.body); updateDescriptionBadge(task!.id, body !== task!.body);
} }
}); });
@@ -1074,8 +1079,13 @@ export function mountPM(
clearTimeout(draftTimer); clearTimeout(draftTimer);
await draftReady; await draftReady;
if (!draft || !task) return; if (!draft || !task) return;
await images.save(description.value); const body = description.value;
await draft.save(description.value === task.body ? null : 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); }; const reportDraftError = (reason: unknown) => { error.textContent = errorText(reason); };
void draftReady?.catch(reportDraftError); void draftReady?.catch(reportDraftError);
@@ -1113,8 +1123,7 @@ export function mountPM(
description.addEventListener("input", () => { description.addEventListener("input", () => {
draftEdited = true; draftEdited = true;
if (task) updateDescriptionBadge(task.id, description.value !== task.body); if (task) updateDescriptionBadge(task.id, description.value !== task.body);
clearTimeout(draftTimer); scheduleDraft();
if (draft && !images.isLoading()) draftTimer = setTimeout(() => { void flushDraft().catch(reportDraftError); }, 300);
}); });
const useSharedChoices = sharedChoice; const useSharedChoices = sharedChoice;
const updateChoice = sharedChoices.update; const updateChoice = sharedChoices.update;
@@ -1549,7 +1558,8 @@ export function mountPM(
const ok = await perform( const ok = await perform(
async () => { async () => {
await flushDraft(); 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)); const existingIds = new Set(store.tasks.map(candidate => candidate.id));
await (task && boardSelect.value && (boardSelect.value !== originalBoardId || (!store.board.reference && listChanged)) await (task && boardSelect.value && (boardSelect.value !== originalBoardId || (!store.board.reference && listChanged))
? store.saveToBoard(task, boardSelect.value, listSelect.value || null, { ...fields, body }) ? store.saveToBoard(task, boardSelect.value, listSelect.value || null, { ...fields, body })
+26 -12
View File
@@ -1020,10 +1020,10 @@ export const messageRows: [string, string, string, string][] = [
"阅读" "阅读"
], ],
[ [
"Split", "Read beside",
"Diviser", "Lire à côté",
"分割", "横に閲覧",
"分栏" "并排阅读"
], ],
[ [
"Editor", "Editor",
@@ -1464,10 +1464,10 @@ export const messageRows: [string, string, string, string][] = [
"版本 {version}" "版本 {version}"
], ],
[ [
"RuneStone is under development. Maintained by kwyvern-gh.", "RuneStone is under development. Maintained by KnottyWyvern-GH.",
"RuneStone est en développement. Maintenu par kwyvern-gh.", "RuneStone est en développement. Maintenu par KnottyWyvern-GH.",
"RuneStoneは開発中です。管理者:kwyvern-gh。", "RuneStoneは開発中です。管理者:KnottyWyvern-GH。",
"RuneStone 正在开发中。由 kwyvern-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.", "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", "Open link in default browser",
"Ouvrir le lien dans le navigateur par défaut", "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. File moves stopped.", "L’espace de travail a changé. Les déplacements de fichiers sont arrêtés.", "ワークスペースが変更されました。ファイルの移動を停止しました。", "工作区已更改。文件移动已停止。"],
["The workspace changed. Paste stopped.", "L’espace de travail a changé. Le collage est arrêté.", "ワークスペースが変更されました。貼り付けを停止しました。", "工作区已更改。粘贴已停止。"], ["The workspace changed. Paste stopped.", "L’espace de travail a changé. Le collage est arrêté.", "ワークスペースが変更されました。貼り付けを停止しました。", "工作区已更改。粘贴已停止。"],
["Move to new window", "Déplacer vers une nouvelle fenêtre", "新しいウィンドウに移動", "移到新窗口"], ["Move to new window", "Déplacer vers une nouvelle fenêtre", "新しいウィンドウに移動", "移到新窗口"],
["Split right", "Scinder à droite", "右に分割", "向右拆分"], ["New tab to the right", "Nouvel onglet à droite", "右に新しいタブ", "在右侧新建标签页"],
["Split down", "Scinder vers le bas", "下に分割", "向下拆分"], ["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…", "検索…", "查找…"], ["Find…", "Rechercher…", "検索…", "查找…"],
["Open in default browser", "Ouvrir dans le navigateur par défaut", "既定のブラウザーで開く", "在默认浏览器中打开"], ["Open in default browser", "Ouvrir dans le navigateur par défaut", "既定のブラウザーで開く", "在默认浏览器中打开"],
["Invalid browser tab transfer.", "Transfert d’onglet de navigateur non valide.", "ブラウザータブの移動が無効です。", "浏览器标签页转移无效。"], ["Invalid browser tab transfer.", "Transfert d’onglet de navigateur non valide.", "ブラウザータブの移動が無効です。", "浏览器标签页转移无效。"],
@@ -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 笔记上方显示文件名。"], ["Show the file name above each Markdown note in Write and Read.", "Afficher le nom du fichier au-dessus de chaque note Markdown dans Écrire et Lire.", "「書く」と「閲覧」で、各 Markdown ノートの上にファイル名を表示します。", "在“写作”和“阅读”中,在每篇 Markdown 笔记上方显示文件名。"],
["Source", "Source", "ソース", "源码"], ["Source", "Source", "ソース", "源码"],
["View", "Affichage", "表示", "视图"], ["View", "Affichage", "表示", "视图"],
["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 Write and Source", "Alterner entre Écrire et Source", "「書く」と「ソース」を切り替え", "在写作和源码之间切换"],
["Switch between Read and the editor", "Alterner entre Lire et l’éditeur", "「閲覧」とエディターを切り替え", "在阅读和编辑器之间切换"], ["Switch between Read and the editor", "Alterner entre Lire et l’éditeur", "「閲覧」とエディターを切り替え", "在阅读和编辑器之间切换"],
["Unsaved", "Non enregistré", "未保存", "未保存"], ["Unsaved", "Non enregistré", "未保存", "未保存"],
@@ -3674,7 +3685,8 @@ export const messageRows: [string, string, string, string][] = [
["Loading page {page}…", "Chargement de la page {page}…", "{page} ページを読み込み中…", "正在加载第 {page} 页…"], ["Loading page {page}…", "Chargement de la page {page}…", "{page} ページを読み込み中…", "正在加载第 {page} 页…"],
["Page {page} of {count}", "Page {page} sur {count}", "{page} / {count} ページ", "第 {page} 页,共 {count} 页"], ["Page {page} of {count}", "Page {page} sur {count}", "{page} / {count} ページ", "第 {page} 页,共 {count} 页"],
["PDF page {page}", "Page PDF {page}", "PDF の {page} ページ", "PDF 第 {page} 页"], ["PDF page {page}", "Page PDF {page}", "PDF の {page} ページ", "PDF 第 {page} 页"],
["PDF 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 密码"], ["PDF password", "Mot de passe du PDF", "PDF のパスワード", "PDF 密码"],
["Unlock", "Déverrouiller", "ロック解除", "解锁"], ["Unlock", "Déverrouiller", "ロック解除", "解锁"],
["This PDF needs a password.", "Ce PDF nécessite un mot de passe.", "この PDF にはパスワードが必要です。", "此 PDF 需要密码。"], ["This PDF needs a password.", "Ce PDF nécessite un mot de passe.", "この PDF にはパスワードが必要です。", "此 PDF 需要密码。"],
@@ -4065,6 +4077,8 @@ export const messageRows: [string, string, string, string][] = [
["Unlink {name}", "Délier {name}", "{name} のリンクを解除", "取消关联 {name}"], ["Unlink {name}", "Délier {name}", "{name} のリンクを解除", "取消关联 {name}"],
["Unsaved changes", "Modifications non enregistrées", "未保存の変更", "未保存的更改"], ["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 图片。"], ["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 之间的图片。"], ["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}"], ["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 会从所有卡片中移除每个已删除的标签。"], ["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 会从所有卡片中移除每个已删除的标签。"],
+4 -3
View File
@@ -11,9 +11,10 @@
error?: string | null; error?: string | null;
onOpen: (entry: Backlink) => void; onOpen: (entry: Backlink) => void;
onRebuild?: () => void; onRebuild?: () => void;
/** The owner keeps this value, so the choice survives when the section closes with its tab. */
expanded?: boolean;
}; };
let { entries, busy = false, error = null, onOpen, onRebuild }: Props = $props(); let { entries, busy = false, error = null, onOpen, onRebuild, expanded = $bindable(true) }: Props = $props();
let expanded = $state(true);
const contentId = $props.id(); const contentId = $props.id();
function collapseTooltip(node: HTMLElement) { function collapseTooltip(node: HTMLElement) {
return { destroy: attachTooltip(node, () => $t(expanded ? "Collapse backlinks" : "Expand backlinks")) }; return { destroy: attachTooltip(node, () => $t(expanded ? "Collapse backlinks" : "Expand backlinks")) };
@@ -71,7 +72,7 @@
.source-title > span:first-of-type { min-width: 0; overflow-wrap: anywhere; } .source-title > span:first-of-type { min-width: 0; overflow-wrap: anywhere; }
.line { margin-left: auto; color: var(--rs-text-dim); font-variant-numeric: tabular-nums; } .line { margin-left: auto; color: var(--rs-text-dim); font-variant-numeric: tabular-nums; }
.excerpt { display: -webkit-box; line-clamp: 2; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; margin-top: 3px; font-size: 12px; overflow-wrap: anywhere; } .excerpt { display: -webkit-box; line-clamp: 2; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; margin-top: 3px; font-size: 12px; overflow-wrap: anywhere; }
.toggle:hover, .source:hover { background: var(--rs-bg-active); } .toggle:hover, .source:hover { background: var(--rs-hover-bg); }
.toggle:focus-visible, .source:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; } .toggle:focus-visible, .source:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
.placeholder, .error { margin: 8px 12px; font-size: 12px; overflow-wrap: anywhere; } .placeholder, .error { margin: 8px 12px; font-size: 12px; overflow-wrap: anywhere; }
.placeholder { color: var(--rs-text-dim); } .placeholder { color: var(--rs-text-dim); }
+1 -1
View File
@@ -94,7 +94,7 @@
} }
li > button:hover { li > button:hover {
background: var(--rs-bg-active); background: var(--rs-hover-bg);
color: var(--rs-text-strong); color: var(--rs-text-strong);
} }
+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>
+188 -48
View File
@@ -1,26 +1,35 @@
<script lang="ts"> <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 type { ComponentProps } from "svelte";
import { t } from "$lib/i18n"; import { t } from "$lib/i18n";
import PluginEditor from "$lib/plugins/PluginEditor.svelte"; import PluginEditor from "$lib/plugins/PluginEditor.svelte";
import { pluginEditors, pluginView, selectPluginEditor } from "$lib/plugins/external"; import { pluginEditors, pluginView, selectPluginEditor, type OpenPluginView } from "$lib/plugins/external";
import type { Documents } from "$lib/workspace/documents.svelte"; import type { Documents } from "$lib/workspace/documents.svelte";
import type { OpenBuffer } from "$lib/workspace/types"; import type { OpenBuffer } from "$lib/workspace/types";
import EditorPane from "./EditorPane.svelte"; import EditorPane from "./EditorPane.svelte";
import Icon from "$lib/ui/Icon.svelte"; import Icon from "$lib/ui/Icon.svelte";
import 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 type { ViewMode } from "./ViewModes.svelte";
import TabBar from "./TabBar.svelte";
type EditorProps = ComponentProps<typeof EditorPane>; type EditorProps = ComponentProps<typeof EditorPane>;
type DocumentView = { id: string; reading: boolean; split: boolean; buffer: OpenBuffer | null; bounds: { width: number } }; type DocumentView = { id: string; reading: boolean; split: boolean; buffer: OpenBuffer | null; pluginKey: string | null };
type Bounds = { left: number; top: number; width: number; height: number }; /** The pane under a dragged tab, and the place of the drop on it. */
type DropTarget = { pane: string; zone: PaneDrop };
type Props = { type Props = {
editorPluginVisible: boolean; /** The focused plugin view covers the whole area. */
split: boolean; pluginCover: boolean;
pluginBounds: Record<string, Bounds | undefined>; /** The drop hint of a dragged tab. */
tabBar: ComponentProps<typeof TabBar>; drop: DropTarget | null;
onResize: (path: SplitPath, ratio: number) => void;
pluginPaneComponents: Record<string, PluginEditor | undefined>; pluginPaneComponents: Record<string, PluginEditor | undefined>;
documentViews: DocumentView[]; documentViews: DocumentView[];
layout: SplitLayout;
activePane: string; activePane: string;
paneComponents: Record<string, EditorPane | undefined>; paneComponents: Record<string, EditorPane | undefined>;
documents: Documents | null; documents: Documents | null;
@@ -37,7 +46,7 @@
onQuickOpen: () => void; onQuickOpen: () => void;
onOpenBrowser?: () => void; onOpenBrowser?: () => void;
onChange: EditorProps["onChange"]; 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"]; onRenameTitle: EditorProps["onRenameTitle"];
tableActions: (pane: DocumentView) => EditorProps["tableActions"]; tableActions: (pane: DocumentView) => EditorProps["tableActions"];
linkActions: (pane: DocumentView) => EditorProps["linkActions"]; linkActions: (pane: DocumentView) => EditorProps["linkActions"];
@@ -46,37 +55,113 @@
onCursor: (pane: DocumentView, line: number, column: number) => void; onCursor: (pane: DocumentView, line: number, column: number) => void;
onOpenLink: (pane: DocumentView, kind: "md" | "wiki", target: string) => void; onOpenLink: (pane: DocumentView, kind: "md" | "wiki", target: string) => void;
}; };
let { 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, documents, tabs, hasWorkspace, browserOpening, focusLine, onFocusPane, onCloseSplit, onSaveCopy, onOpenWorkspace, onNewFile, onNewNote,
onQuickOpen, onOpenBrowser, onChange, onInsertImage, onRenameTitle, tableActions, linkActions, onView, onSplitView, onCursor, onOpenLink }: Props = $props(); onQuickOpen, onOpenBrowser, onChange, onInsertImage, onRenameTitle, tableActions, linkActions, onView, onSplitView, onCursor, onOpenLink }: Props = $props();
// A narrow area shows the panes one above the other, in the same order.
let width = $state(0);
const stacked = $derived(width > 0 && width <= 640);
const bounds = $derived(paneBounds(stacked ? stackLayout(layout) : layout));
const hosts = $derived(new Map(documentViews.flatMap(pane => pane.pluginKey ? [[pane.pluginKey, pane.id] as const] : [])));
const several = $derived(documentViews.length > 1);
function focusPlugin(view: OpenPluginView, host: string | undefined) {
if (host) onFocusPane(host);
else if ($pluginView?.key !== view.key) selectPluginEditor(view);
}
let area: HTMLElement;
const full = { left: 0, top: 0, width: 100, height: 100 };
const dividers = $derived(pluginCover || !several ? [] : splitDividers(stacked ? stackLayout(layout) : layout));
/** The place of the divider: the line between the two sides of its split, in percent of the area. */
function dividerStyle(divider: SplitDivider) {
const { bounds: box, ratio } = divider;
return divider.direction === "right"
? `left:${box.left + box.width * ratio}%;top:${box.top}%;height:${box.height}%`
: `top:${box.top + box.height * ratio}%;left:${box.left}%;width:${box.width}%`;
}
function ratioAt(divider: SplitDivider, x: number, y: number) {
const rect = area.getBoundingClientRect(), box = divider.bounds;
return divider.direction === "right"
? (x - rect.left - rect.width * box.left / 100) / (rect.width * box.width / 100)
: (y - rect.top - rect.height * box.top / 100) / (rect.height * box.height / 100);
}
let resizing = $state<"right" | "down" | null>(null);
function startResize(event: PointerEvent, divider: SplitDivider) {
if (event.button !== 0) return;
event.preventDefault();
const handle = event.currentTarget as HTMLElement;
handle.setPointerCapture(event.pointerId);
handle.focus({ preventScroll: true });
resizing = divider.direction;
const move = (next: PointerEvent) => onResize(divider.path, ratioAt(divider, next.clientX, next.clientY));
const end = () => {
resizing = null;
handle.removeEventListener("pointermove", move);
handle.removeEventListener("pointerup", end);
handle.removeEventListener("pointercancel", end);
};
handle.addEventListener("pointermove", move);
handle.addEventListener("pointerup", end);
handle.addEventListener("pointercancel", end);
}
function resizeKey(event: KeyboardEvent, divider: SplitDivider) {
const steps: Record<string, number> = divider.direction === "right" ? { ArrowLeft: -0.05, ArrowRight: 0.05 } : { ArrowUp: -0.05, ArrowDown: 0.05 };
if (event.key in steps) onResize(divider.path, divider.ratio + steps[event.key]);
else if (event.key === "Home") onResize(divider.path, 0.1);
else if (event.key === "End") onResize(divider.path, 0.9);
else if (event.key === "Enter") onResize(divider.path, 0.5);
else return;
event.preventDefault();
}
function tooltip(node: HTMLElement, text: string) {
let label = text;
const dispose = attachTooltip(node, () => label);
return { update(value: string) { label = value; }, destroy: dispose };
}
/**
* The drop target under a point: a pane, and the place on it. The 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> </script>
<main class="center"> <main class="center" class:resizing={!!resizing} class:resizing-down={resizing === "down"} bind:this={area} bind:clientWidth={width}>
<div class="plugin-panes" class:inactive={!editorPluginVisible}> <div class="editor-host" class:plugin-covered={pluginCover}>
{#each $pluginEditors as pane (pane.key)} <div class="document-panes" class:split={several}>
{@const bounds = pluginBounds[pane.key]}
<!-- svelte-ignore a11y_no_static_element_interactions (Focus selects the pane that owns the input.) -->
<div class="plugin-pane" class:inactive={!bounds} class:split class:focused={$pluginView?.key === pane.key}
style:left={`${bounds?.left ?? 0}%`} style:top={`${bounds?.top ?? 0}%`}
style:width={`${bounds?.width ?? 100}%`} style:height={`${bounds?.height ?? 100}%`}
onfocusin={() => { if ($pluginView?.key !== pane.key) selectPluginEditor(pane); }}
onpointerdown={() => { if ($pluginView?.key !== pane.key) selectPluginEditor(pane); }}>
{#if split && bounds}
<TabBar {...tabBar} tabs={tabBar.tabs.filter(tab => tab.id === pane.key)} />
{/if}
<PluginEditor bind:this={pluginPaneComponents[pane.key]} view={pane} />
</div>
{/each}
</div>
<div class="editor-host" class:plugin-covered={editorPluginVisible}>
<div class="document-panes" class:split={documentViews.length > 1}>
{#each documentViews as pane (pane.id)} {#each documentViews as pane (pane.id)}
{@const box = bounds[pane.id]}
<!-- svelte-ignore a11y_no_static_element_interactions (Focus identifies the document for shared commands.) --> <!-- svelte-ignore a11y_no_static_element_interactions (Focus identifies the document for shared commands.) -->
<div class="document-pane" class:focused={activePane === pane.id} <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 ?? ""} 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)} onpointerdowncapture={() => onFocusPane(pane.id)}
onfocusin={() => onFocusPane(pane.id)}> onfocusin={() => onFocusPane(pane.id)}>
<!-- A pane with a plugin view stays empty. The plugin layer shows the view over it. -->
{#if !pane.pluginKey}
{#if pane.buffer?.diskError} {#if pane.buffer?.diskError}
<div class="conflict" role="alert"><Icon icon="alert" /><span>{pane.buffer.diskError}</span><button class="primary" onclick={() => void documents?.refresh()}>{$t("Retry")}</button><button onclick={() => onSaveCopy(pane.buffer)}>{$t("Save a copy")}</button></div> <div class="conflict" role="alert"><Icon icon="alert" /><span>{pane.buffer.diskError}</span><button class="primary" onclick={() => void documents?.refresh()}>{$t("Retry")}</button><button onclick={() => onSaveCopy(pane.buffer)}>{$t("Save a copy")}</button></div>
{:else if pane.buffer?.diskContents != null} {:else if pane.buffer?.diskContents != null}
@@ -94,7 +179,7 @@
bind:this={paneComponents[pane.id]} bind:this={paneComponents[pane.id]}
{tabs} {tabs}
active={activePane === pane.id} active={activePane === pane.id}
onCloseSplit={documentViews.length > 1 ? () => onCloseSplit(pane.id) : undefined} onCloseSplit={several ? () => onCloseSplit(pane.id) : undefined}
{hasWorkspace} {hasWorkspace}
{onOpenWorkspace} {onOpenWorkspace}
{onNewFile} {onNewFile}
@@ -108,7 +193,7 @@
split={pane.split} split={pane.split}
focusLine={activePane === pane.id ? focusLine : null} focusLine={activePane === pane.id ? focusLine : null}
{onChange} {onChange}
onInsertImage={file => onInsertImage(file, pane.buffer)} onInsertImage={(file, source) => onInsertImage(file, pane.buffer, source)}
{onRenameTitle} {onRenameTitle}
tableActions={tableActions(pane)} tableActions={tableActions(pane)}
linkActions={linkActions(pane)} linkActions={linkActions(pane)}
@@ -117,10 +202,50 @@
onCursor={(line, column) => onCursor(pane, line, column)} onCursor={(line, column) => onCursor(pane, line, column)}
onOpenLink={(kind, target) => onOpenLink(pane, kind, target)} onOpenLink={(kind, target) => onOpenLink(pane, kind, target)}
/> />
{/if}
</div> </div>
{/each} {/each}
</div> </div>
</div> </div>
<div class="plugin-panes">
{#each $pluginEditors as view (view.key)}
{@const host = pluginCover ? undefined : hosts.get(view.key)}
{@const box = pluginCover ? ($pluginView?.key === view.key ? full : undefined) : host ? bounds[host] : undefined}
<!-- svelte-ignore a11y_no_static_element_interactions (Focus selects the pane that owns the input.) -->
<div class="plugin-pane" class:inactive={!box} class:embedded={!!host}
class:focused={host ? activePane === host : $pluginView?.key === view.key}
class:edge-left={!!host && (box?.left ?? 0) > 0} class:edge-top={!!host && (box?.top ?? 0) > 0}
data-plugin-pane={view.key}
style:left={`${box?.left ?? 0}%`} style:top={`${box?.top ?? 0}%`}
style:width={`${box?.width ?? 100}%`} style:height={`${box?.height ?? 100}%`}
onfocusin={() => focusPlugin(view, host)}
onpointerdowncapture={() => focusPlugin(view, host)}>
{#if host && several}
<div class="pane-bar">
<span class="pane-title" title={view.title}>{view.title}</span>
<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> </main>
<style> <style>
@@ -140,7 +265,7 @@
.conflict > :global(svg) { width: 18px; height: 18px; flex-shrink: 0; color: var(--rs-warn); } .conflict > :global(svg) { width: 18px; height: 18px; flex-shrink: 0; color: var(--rs-warn); }
.conflict span { flex: 1 1 220px; min-width: 0; } .conflict span { flex: 1 1 220px; min-width: 0; }
.conflict button { min-height: 28px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); padding: 4px 10px; } .conflict button { min-height: 28px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); padding: 4px 10px; }
.conflict button:hover { background: var(--rs-bg-active); } .conflict button:hover { background: var(--rs-hover-bg); }
.conflict button.primary { border-color: var(--rs-accent); background: var(--rs-accent); color: var(--rs-on-accent); } .conflict button.primary { border-color: var(--rs-accent); background: var(--rs-accent); color: var(--rs-on-accent); }
.conflict button.danger { border-color: var(--rs-error); color: var(--rs-error); } .conflict button.danger { border-color: var(--rs-error); color: var(--rs-error); }
.disk-review { padding: 8px 12px; max-height: 35vh; overflow: auto; flex: 0 0 auto; } .disk-review { padding: 8px 12px; max-height: 35vh; overflow: auto; flex: 0 0 auto; }
@@ -155,19 +280,34 @@
container-type: inline-size; container-type: inline-size;
} }
.document-panes { flex: 1; min-height: 0; display: flex; overflow: hidden; } /* Each pane has its place in the split layout. A pane beside or below another pane has a border on that edge. */
.document-pane { flex: var(--pane-weight) 1 0; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; } .document-panes { position: relative; flex: 1; min-height: 0; overflow: hidden; }
.document-pane + .document-pane { border-left: 1px solid var(--rs-border); } .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); } .document-panes.split .document-pane.focused :global(.chrome-bar) { background: var(--rs-bg-active); }
@container (max-width: 640px) {
.document-panes.split { flex-direction: column; overflow-y: auto; }
.document-panes.split .document-pane { flex: 1 0 320px; }
.document-pane + .document-pane { border-left: 0; border-top: 1px solid var(--rs-border); }
}
.editor-host.plugin-covered { display: none; } .editor-host.plugin-covered { display: none; }
.plugin-panes { position: relative; flex: 1; min-height: 0; min-width: 0; overflow: hidden; } /* The plugin layer covers the area, but only its visible panes take the pointer. */
.plugin-pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; box-sizing: border-box; } .plugin-panes { position: absolute; inset: 0; overflow: hidden; pointer-events: none; }
.plugin-pane.split { border: 1px solid var(--rs-border); } .plugin-pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; box-sizing: border-box; pointer-events: auto; }
.plugin-pane.split.focused { border-color: var(--rs-accent); } .plugin-pane.embedded { background: var(--rs-bg); }
.plugin-panes.inactive, .plugin-pane.inactive { display: none; } .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> </style>
+7 -5
View File
@@ -9,7 +9,7 @@
import type { FindTarget } from "$lib/editor/findTarget"; import type { FindTarget } from "$lib/editor/findTarget";
import DocumentEditor from "$lib/editor/DocumentEditor.svelte"; import DocumentEditor from "$lib/editor/DocumentEditor.svelte";
import { tick } from "svelte"; import { tick } from "svelte";
import IconButton from "$lib/ui/IconButton.svelte"; import CloseSplitButton from "./CloseSplitButton.svelte";
import ImageViewer from "./ImageViewer.svelte"; import ImageViewer from "./ImageViewer.svelte";
import MarkdownView from "./MarkdownView.svelte"; import MarkdownView from "./MarkdownView.svelte";
import ViewModes, { type ViewMode } from "./ViewModes.svelte"; import ViewModes, { type ViewMode } from "./ViewModes.svelte";
@@ -29,7 +29,7 @@
focusLine: number | null; focusLine: number | null;
onChange: (value: string, id: string) => void; onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<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; onView?: (view: ViewMode) => void;
onSplit?: (split: boolean) => void; onSplit?: (split: boolean) => void;
onCursor?: (line: number, column: number) => void; onCursor?: (line: number, column: number) => void;
@@ -147,12 +147,14 @@
const splitView = $derived(split && canPreview && !reading); const splitView = $derived(split && canPreview && !reading);
const view: ViewMode = $derived(readOnly ? "read" : chrome === "Source" ? "source" : "write"); const view: ViewMode = $derived(readOnly ? "read" : chrome === "Source" ? "source" : "write");
// The tab already names the file, so the breadcrumb shows only its folder. // The tab already names the file, so the breadcrumb shows only its folder.
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> </script>
{#if !buffer || buffer.kind === "empty"} {#if !buffer || buffer.kind === "empty"}
<div class="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"> <div class="welcome-actions">
{#if hasWorkspace} {#if hasWorkspace}
<div class="welcome-row"> <div class="welcome-row">
@@ -178,7 +180,7 @@
</span> </span>
{/if} {/if}
<div class="actions" bind:this={modeControls}> <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} {#if !isImage}<ViewModes {view} split={splitView} readable={canPreview} onView={next => onView?.(next)} onSplit={next => onSplit?.(next)} />{/if}
</div> </div>
</div> </div>
+4
View File
@@ -43,6 +43,8 @@
workspaceRoot: string; workspaceRoot: string;
activePath: string | null; activePath: string | null;
onOpenFile: (entry: TreeEntry, newTab?: boolean) => void; onOpenFile: (entry: TreeEntry, newTab?: boolean) => void;
/** Open the file in a new pane to the right of the active pane. */
onOpenRight?: (entry: TreeEntry) => void;
session: WorkspaceSession; session: WorkspaceSession;
onStatus?: (message: string) => void; onStatus?: (message: string) => void;
onCreated?: (entry: TreeEntry) => void; onCreated?: (entry: TreeEntry) => void;
@@ -56,6 +58,7 @@
workspaceRoot, workspaceRoot,
activePath, activePath,
onOpenFile, onOpenFile,
onOpenRight,
session, session,
onStatus, onStatus,
onCreated, onCreated,
@@ -878,6 +881,7 @@
...(!multiple && entry.kind === "folder" ? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }] : []), ...(!multiple && entry.kind === "folder" ? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }] : []),
...(!multiple && entry.kind === "file" ? [ ...(!multiple && entry.kind === "file" ? [
{ kind: "action" as const, label: $t("Open in new tab"), icon: "tab" as const, run: () => onOpenFile(entry, true) }, { kind: "action" as const, label: $t("Open in new tab"), icon: "tab" as const, run: () => onOpenFile(entry, true) },
...(onOpenRight ? [{ kind: "action" as const, label: $t("Open to the right"), icon: "split-right" as const, run: () => onOpenRight(entry) }] : []),
{ kind: "action" as const, label: $t("Open in default app"), icon: "external" as const, run: () => { void workspaceOpenDefault(entry.rel_path).catch(reason => error = String(reason)); } }, { kind: "action" as const, label: $t("Open in default app"), icon: "external" as const, run: () => { void workspaceOpenDefault(entry.rel_path).catch(reason => error = String(reason)); } },
] : []), ] : []),
terminalItem(parent), terminalItem(parent),
+4 -2
View File
@@ -29,13 +29,14 @@
onHelp: () => void; onHelp: () => void;
onSettings: () => void; onSettings: () => void;
onOpenFile: (entry: TreeEntry, line?: number, target?: "current" | "new") => void; onOpenFile: (entry: TreeEntry, line?: number, target?: "current" | "new") => void;
onOpenRight?: (entry: TreeEntry) => void;
onCreated: (entry: TreeEntry) => void; onCreated: (entry: TreeEntry) => void;
onSaveTemplate: (entry: TreeEntry) => void; onSaveTemplate: (entry: TreeEntry) => void;
onManageTemplates: () => void; onManageTemplates: () => void;
onStatus: (message: string) => void; onStatus: (message: string) => void;
}; };
let { workspace, session, leftView, keysActive, showInternal, activePath, searchRequest, fileTree = $bindable(), workspaceAnchor = $bindable(), let { workspace, session, leftView, keysActive, showInternal, activePath, searchRequest, fileTree = $bindable(), workspaceAnchor = $bindable(),
onOpenFile, 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) { function tooltip(node: HTMLElement, text: string) {
let current = text; let current = text;
@@ -63,6 +64,7 @@
{onManageTemplates} {onManageTemplates}
{activePath} {activePath}
onOpenFile={(entry, newTab) => onOpenFile(entry, undefined, newTab ? "new" : "current")} onOpenFile={(entry, newTab) => onOpenFile(entry, undefined, newTab ? "new" : "current")}
{onOpenRight}
{session} {session}
{keysActive} {keysActive}
{onCreated} {onCreated}
@@ -166,7 +168,7 @@
padding: 0 10px; padding: 0 10px;
border: 1px solid transparent; border: 1px solid transparent;
border-radius: var(--rs-control-radius); border-radius: var(--rs-control-radius);
background: var(--rs-bg-active); background: var(--rs-hover-bg);
color: var(--rs-text-strong); color: var(--rs-text-strong);
font: 600 13px var(--rs-font-ui); font: 600 13px var(--rs-font-ui);
text-align: left; text-align: left;
+6 -2
View File
@@ -4,6 +4,7 @@
import { tick, type Snippet } from "svelte"; import { tick, type Snippet } from "svelte";
import { workspaceReadDataUrl } from "$lib/workspace/api"; import { workspaceReadDataUrl } from "$lib/workspace/api";
import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml"; import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml";
import { loadImageSize } from "$lib/workspace/imageSizes";
import { renderDiagrams } from "$lib/workspace/diagrams"; import { renderDiagrams } from "$lib/workspace/diagrams";
import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media"; import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media";
import { imageControls } from "$lib/editor/imageControls"; import { imageControls } from "$lib/editor/imageControls";
@@ -55,7 +56,9 @@
const base = normalized.split("/").pop() ?? path; const base = normalized.split("/").pop() ?? path;
for (const candidate of new Set([primary, normalized, base])) { for (const candidate of new Set([primary, normalized, base])) {
try { try {
urls.set(source, await workspaceReadDataUrl(candidate)); const url = await workspaceReadDataUrl(candidate);
await loadImageSize(url);
urls.set(source, url);
return; return;
} catch { /* Try the workspace-relative attachment next. */ } } catch { /* Try the workspace-relative attachment next. */ }
} }
@@ -102,7 +105,8 @@
[...el.querySelectorAll<HTMLElement>("h1, h2, h3, h4, h5, h6")].filter(heading => !heading.classList.contains("document-title"))[index]; [...el.querySelectorAll<HTMLElement>("h1, h2, h3, h4, h5, h6")].filter(heading => !heading.classList.contains("document-title"))[index];
if (!target) return; if (!target) return;
currentHeadings?.reveal(target); currentHeadings?.reveal(target);
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 }); el.focus({ preventScroll: true });
}); });
return renderDiagrams(el, () => cancelled); return renderDiagrams(el, () => cancelled);
+1 -1
View File
@@ -134,7 +134,7 @@
} }
li button:hover { li button:hover {
background: var(--rs-bg-active); background: var(--rs-hover-bg);
color: var(--rs-text-strong); color: var(--rs-text-strong);
} }
</style> </style>
+3 -2
View File
@@ -13,8 +13,9 @@
backlinks: Backlink[]; backlinks: Backlink[];
session: WorkspaceSession; session: WorkspaceSession;
onOpenBacklink: (entry: Backlink) => void; onOpenBacklink: (entry: Backlink) => void;
backlinksOpen?: boolean;
}; };
let { outlineItems, onJump, showBacklinks, backlinks, session, onOpenBacklink }: Props = $props(); let { outlineItems, onJump, showBacklinks, backlinks, session, onOpenBacklink, backlinksOpen = $bindable(true) }: Props = $props();
</script> </script>
<aside class="right"> <aside class="right">
@@ -22,7 +23,7 @@
<OutlinePane items={outlineItems} {onJump} /> <OutlinePane items={outlineItems} {onJump} />
</div> </div>
{#if showBacklinks} {#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} {/if}
</aside> </aside>
+1 -1
View File
@@ -175,7 +175,7 @@
} }
button:hover { button:hover {
background: var(--rs-bg-active); background: var(--rs-hover-bg);
} }
.line { .line {
+1 -1
View File
@@ -253,7 +253,7 @@
{/each} {/each}
</details> </details>
</div> </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} {/if}
</div> </div>
</div> </div>
+44 -5
View File
@@ -27,9 +27,14 @@
tabDragData?: (tab: WorkbenchTab) => string | undefined; tabDragData?: (tab: WorkbenchTab) => string | undefined;
onDropTab?: (data: string, index: number) => void; onDropTab?: (data: string, index: number) => void;
onDetach?: (tab: WorkbenchTab) => void; onDetach?: (tab: WorkbenchTab) => void;
/** A tab drag outside the tab bar. The result tells whether the point can take the tab, for example a document pane. */
onDragAt?: (relPath: string, x: number, y: number) => boolean;
/** A tab drop outside the tab bar. The result tells whether the drop used the tab. */
onDropAt?: (relPath: string, x: number, y: number) => boolean;
onDragEnd?: () => void;
}; };
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab, onDetach }: 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"; const transferType = "application/x-runestone-tab";
let bar: HTMLDivElement; let bar: HTMLDivElement;
let dragged = $state<string | null>(null); let dragged = $state<string | null>(null);
@@ -61,6 +66,34 @@
suppressClick = true; suppressClick = true;
event.dataTransfer.effectAllowed = "move"; event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData(transferType, data); event.dataTransfer.setData(transferType, data);
watchAreaDrop(tab.relPath);
}
// A tab that leaves the tab bar can go to a pane of the document area. The listeners run first, in the capture
// phase, so that an editor under the pointer does not take the drop.
let stopAreaDrop = () => {};
function watchAreaDrop(path: string) {
stopAreaDrop();
if (!onDragAt || !onDropAt) return;
const inBar = (event: DragEvent) => event.target instanceof Node && bar.contains(event.target);
const over = (event: DragEvent) => {
if (inBar(event) || !onDragAt?.(path, event.clientX, event.clientY)) return;
event.preventDefault(); event.stopPropagation();
if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
};
const drop = (event: DragEvent) => {
if (inBar(event) || !onDropAt?.(path, event.clientX, event.clientY)) return;
event.preventDefault(); event.stopPropagation();
finishTabTransfer();
};
window.addEventListener("dragover", over, true);
window.addEventListener("drop", drop, true);
stopAreaDrop = () => {
window.removeEventListener("dragover", over, true);
window.removeEventListener("drop", drop, true);
stopAreaDrop = () => {};
onDragEnd?.();
};
} }
function transferIndex(x: number) { function transferIndex(x: number) {
@@ -85,6 +118,7 @@
} }
function finishTabTransfer() { function finishTabTransfer() {
stopAreaDrop();
dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false; dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false;
cancelAnimationFrame(transferFrame); transferFrame = 0; cancelAnimationFrame(transferFrame); transferFrame = 0;
} }
@@ -289,6 +323,7 @@
frame = requestAnimationFrame(scroll); frame = requestAnimationFrame(scroll);
}; };
const clean = () => { const clean = () => {
if (started) onDragEnd?.();
if (pointerTarget.hasPointerCapture(pointerId)) pointerTarget.releasePointerCapture(pointerId); if (pointerTarget.hasPointerCapture(pointerId)) pointerTarget.releasePointerCapture(pointerId);
cancelAnimationFrame(frame); cancelAnimationFrame(frame);
dragged = dropBefore = dropAfter = null; dragged = dropBefore = dropAfter = null;
@@ -306,15 +341,19 @@
e.preventDefault(); e.preventDefault();
if (!started) { started = true; suppressClick = true; dragged = path; frame = requestAnimationFrame(scroll); } if (!started) { started = true; suppressClick = true; dragged = path; frame = requestAnimationFrame(scroll); }
update(); update();
if (destination === null) onDragAt?.(path, x, y);
else onDragEnd?.();
}; };
const onUp = (e: PointerEvent) => { const onUp = (e: PointerEvent) => {
if (e.pointerId !== pointerId) return; if (e.pointerId !== pointerId) return;
x = e.clientX; y = e.clientY; x = e.clientX; y = e.clientY;
if (started) update(); if (started) update();
const target = destination; const target = destination;
const wasStarted = started;
clean(); clean();
if (started && target !== null) void move(path, target); if (wasStarted && target !== null) void move(path, target);
else if (started && (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight)) { 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); const tab = tabs.find(tab => tab.relPath === path);
if (tab) onDetach?.(tab); if (tab) onDetach?.(tab);
} }
@@ -446,7 +485,7 @@
} }
.tab:focus-within { box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border); } .tab:focus-within { box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border); }
.tab:not(.active):hover { background: var(--rs-bg-active); } .tab:not(.active):hover { background: var(--rs-hover-bg); }
.tab.dragging { opacity: 0.5; } .tab.dragging { opacity: 0.5; }
.tabs:has(.dragging) .tab > button:first-child { cursor: grabbing; } .tabs:has(.dragging) .tab > button:first-child { cursor: grabbing; }
.tab.drop-before::before, .tab.drop-after::after { .tab.drop-before::before, .tab.drop-after::after {
@@ -521,6 +560,6 @@
background: transparent; background: transparent;
color: var(--rs-text-dim); color: var(--rs-text-dim);
} }
.all-tabs:hover { background: var(--rs-bg-active); border-color: var(--rs-border); color: var(--rs-text-strong); } .all-tabs:hover { background: var(--rs-hover-bg); border-color: var(--rs-border); color: var(--rs-text-strong); }
.all-tabs svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; transform: rotate(90deg); } .all-tabs svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; transform: rotate(90deg); }
</style> </style>
+2 -2
View File
@@ -229,7 +229,7 @@
} }
.row:hover { .row:hover {
background: var(--rs-bg-active); background: var(--rs-hover-bg);
} }
.row.active { .row.active {
@@ -305,7 +305,7 @@
.row.drop-inside { .row.drop-inside {
outline: 1px solid var(--rs-accent); outline: 1px solid var(--rs-accent);
background: var(--rs-bg-active); background: var(--rs-hover-bg);
} }
.twist { .twist {
+5 -5
View File
@@ -1,10 +1,10 @@
<script lang="ts" module> <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"; export type ViewMode = "write" | "source" | "read";
</script> </script>
<script lang="ts"> <script lang="ts">
// The view control of a document pane: Write, Source, and Read in one radio group, then the 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. // All choices stay visible. Narrow panes show only the icons.
import { t } from "$lib/i18n"; import { t } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte"; import Icon from "$lib/ui/Icon.svelte";
@@ -16,7 +16,7 @@
type Props = { type Props = {
view: ViewMode; view: ViewMode;
split: boolean; split: boolean;
/** Markdown files have Read and 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; readable: boolean;
onView: (view: ViewMode) => void; onView: (view: ViewMode) => void;
onSplit: (split: boolean) => void; onSplit: (split: boolean) => void;
@@ -60,7 +60,7 @@
{/each} {/each}
</div> </div>
{#if readable} {#if readable}
<button type="button" class="split" aria-pressed={split} aria-label={$t("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" /> <Icon icon="split" />
</button> </button>
{/if} {/if}
@@ -92,7 +92,7 @@
button :global(svg) { width: 16px; height: 16px; flex-shrink: 0; } button :global(svg) { width: 16px; height: 16px; flex-shrink: 0; }
/* Hover gets only a fill. The current choice also gets the selection fill and an accent bar. */ /* Hover gets only a fill. The current choice also gets the selection fill and an accent bar. */
button:hover { background: var(--rs-bg-active); color: var(--rs-text-strong); } button:hover { background: var(--rs-hover-bg); color: var(--rs-text-strong); }
button[aria-checked="true"], button[aria-pressed="true"] { button[aria-checked="true"], button[aria-pressed="true"] {
background: var(--rs-item-selection-bg); background: var(--rs-item-selection-bg);
color: var(--rs-text-strong); color: var(--rs-text-strong);
+205 -31
View File
@@ -6,13 +6,14 @@
import type PluginEditor from "$lib/plugins/PluginEditor.svelte"; import type PluginEditor from "$lib/plugins/PluginEditor.svelte";
import { featureOfOwner } from "$lib/features/catalog"; import { featureOfOwner } from "$lib/features/catalog";
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup, pluginTools, installedPlugins, runPluginCommand } from "$lib/plugins/external"; import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup, pluginTools, installedPlugins, runPluginCommand } from "$lib/plugins/external";
import { containsPane, paneBounds } 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 { pluginSidebar, closePluginSidebar, pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginFileOpen, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
import { onMount, onDestroy, tick, untrack } from "svelte"; import { onMount, onDestroy, tick, untrack } from "svelte";
import type { MenuLink } from "$lib/editor/linkMenu"; import type { MenuLink } from "$lib/editor/linkMenu";
import { WorkspaceSession } from "$lib/workspace/session.svelte"; import { WorkspaceSession } from "$lib/workspace/session.svelte";
import { retainEditorStates } from "$lib/editor/editorStates"; import { retainEditorStates } from "$lib/editor/editorStates";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView } 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 type { ViewMode } from "./ViewModes.svelte";
import { selectedEditorText } from "$lib/editor/selection"; import { selectedEditorText } from "$lib/editor/selection";
import { pluginHost } from "$lib/plugins/registry"; import { pluginHost } from "$lib/plugins/registry";
@@ -65,10 +66,12 @@
workspaceReveal, workspaceReveal,
workspaceWrite, workspaceWrite,
workspaceWriteBytes, workspaceWriteBytes,
workspaceSaveImageUrl,
} from "$lib/workspace/api"; } from "$lib/workspace/api";
import { detectChrome } from "$lib/workspace/chrome"; import { detectChrome } from "$lib/workspace/chrome";
import { planRename, planMarkdownTitleRename, planDocumentTitleRename, renameSelection } from "$lib/workspace/renamePath"; 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 { headingLinkLine, linkFragment } from "$lib/workspace/headingLinks";
import type { Chrome, OpenBuffer, TreeEntry, WorkspaceInfo } from "$lib/workspace/types"; import type { Chrome, OpenBuffer, TreeEntry, WorkspaceInfo } from "$lib/workspace/types";
@@ -147,6 +150,7 @@
let searchRequest = $state<{ text: string; id: number } | null>(null); let searchRequest = $state<{ text: string; id: number } | null>(null);
let leftOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.leftOpen); let leftOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.leftOpen);
let rightOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.rightOpen); let rightOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.rightOpen);
let backlinksOpen = $state(DEFAULT_WORKBENCH_LAYOUT.backlinksOpen);
$effect(() => { if ($pluginSidebar && !transferredWindow) leftOpen = true; }); $effect(() => { if ($pluginSidebar && !transferredWindow) leftOpen = true; });
let terminalOpen = $state(false); let terminalOpen = $state(false);
let documentPanes = $state(initialDocumentPanes()); let documentPanes = $state(initialDocumentPanes());
@@ -226,7 +230,9 @@
}, () => { }, () => {
if (documents !== next) return; if (documents !== next) return;
const selected = next.active; 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; if (selected) view = selected.chromeOverride ?? selected.chrome;
}); });
return next; return next;
@@ -235,8 +241,8 @@
onDestroy(() => retainEditorStates([])); onDestroy(() => retainEditorStates([]));
const documentViews = $derived.by(() => { const documentViews = $derived.by(() => {
const bounds = paneBounds(documentPanes.layout); const bounds = paneBounds(documentPanes.layout);
return documentPanes.panes.map(pane => ({ ...pane, buffer: tabs.find(tab => tab.id === pane.documentId) ?? null, bounds: bounds[pane.id] })) return documentPanes.panes.map(pane => ({ ...pane, buffer: tabs.find(tab => tab.id === pane.documentId) ?? null }))
.sort((a, b) => a.bounds.left - b.bounds.left); .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) { function setReading(next: boolean, paneId = documentPanes.active) {
documentPanes = readDocumentPane(documentPanes, paneId, next); documentPanes = readDocumentPane(documentPanes, paneId, next);
@@ -246,6 +252,13 @@
if (!pane) return; if (!pane) return;
const tab = tabs.find(tab => tab.id === pane.documentId); const tab = tabs.find(tab => tab.id === pane.documentId);
documentPanes = selectPane(documentPanes, paneId); documentPanes = selectPane(documentPanes, paneId);
if (pane.pluginKey) {
const key = pane.pluginKey;
const view = $pluginEditors.find(view => view.key === key);
if (view && !($pluginEditorActive && $pluginView?.key === key)) selectPluginEditor(view);
if (focusEditor) void tick().then(() => { if (documentPanes.active === paneId) pluginPaneComponents[key]?.focus(); });
return;
}
pluginEditorActive.set(false); pluginEditorActive.set(false);
if (tab && documents?.active?.id !== tab.id) { focusLine = null; documents?.select(tab.relPath); } if (tab && documents?.active?.id !== tab.id) { focusLine = null; documents?.select(tab.relPath); }
if (focusEditor) void tick().then(() => { if (focusEditor) void tick().then(() => {
@@ -254,27 +267,163 @@
document.querySelector<HTMLElement>(`[data-document-pane="${paneId}"]`)?.scrollIntoView({ block: "nearest", inline: "nearest" }); document.querySelector<HTMLElement>(`[data-document-pane="${paneId}"]`)?.scrollIntoView({ block: "nearest", inline: "nearest" });
}); });
} }
function closeSplit(paneId: string) { /** 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. */
documentPanes = closeDocumentPane(documentPanes, paneId); function changePanes(next: DocumentPanes) {
focusDocumentPane(documentPanes.active, true); 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) { async function openToRight(file: TreeEntry, sourcePane: string) {
const current = documents; const current = documents;
const covered = sourcePane === documentPanes.active ? coverKey : null;
const source = documentPanes.panes.find(pane => pane.id === sourcePane); const source = documentPanes.panes.find(pane => pane.id === sourcePane);
if (!current || switching || !source) return; if (!current || switching || !source) return;
const unchanged = () => {
const now = documentPanes.panes.find(pane => pane.id === sourcePane);
return documents === current && !switching && documentPanes.active === sourcePane && coverKey === covered
&& now?.documentId === source.documentId && now?.pluginKey === source.pluginKey;
};
const open = current.buffers.find(tab => tab.relPath === file.rel_path);
if (!(open && open.contents !== open.saved)) {
// The placement effect opens the plugin view in a new pane beside the source pane.
rightOf = { pane: sourcePane, cover: covered };
try {
const opened = await openPluginDocument(file.rel_path, unchanged);
await tick();
if (opened) return;
} finally { rightOf = null; }
}
await current.open(file, "background"); await current.open(file, "background");
if (documents !== current || switching || documentPanes.active !== sourcePane if (!unchanged()) return;
|| documentPanes.panes.find(pane => pane.id === sourcePane)?.documentId !== source.documentId) return;
const target = current.buffers.find(tab => tab.relPath === file.rel_path); const target = current.buffers.find(tab => tab.relPath === file.rel_path);
if (!target) return; if (!target) return;
keepCoverInPane();
documentPanes = splitDocumentPane(documentPanes, sourcePane, target.id, crypto.randomUUID()); documentPanes = splitDocumentPane(documentPanes, sourcePane, target.id, crypto.randomUUID());
focusDocumentPane(documentPanes.active, true); focusDocumentPane(documentPanes.active, true);
} }
function tabContent(tab: EditorTab): PaneContent {
return "plugin" in tab ? { pluginKey: tab.plugin.key } : { documentId: tab.buffer.id };
}
/** A visible tab is the plugin view over the area, or the content of a pane. */
function tabVisible(tab: EditorTab) {
if (coverKey) return "plugin" in tab && tab.plugin.key === coverKey;
return !!paneOf(documentPanes, tabContent(tab));
}
/** Show a tab in a new pane to the right of the active pane. The active pane keeps its content. */
function openTabToRight(tab: EditorTab) {
if (switching || tabVisible(tab)) return;
keepCoverInPane();
documentPanes = splitWithContent(documentPanes, documentPanes.active, tabContent(tab), crypto.randomUUID());
focusDocumentPane(documentPanes.active, true);
}
// A tab that the user drags from the tab bar to the document area: the pane and the place of the drop.
let documentArea: DocumentArea | undefined = $state();
let tabDrop = $state<{ pane: string; zone: PaneDrop } | null>(null);
function tabDropTarget(path: string, x: number, y: number) {
const tab = workingTabs.find(tab => tab.relPath === path);
const target = tab && !switching ? documentArea?.dropAt(x, y) ?? null : null;
if (!tab || !target) return null;
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 focusLine = $state<number | null>(null);
let dragging = $state<"left" | "right" | "bottom" | null>(null); let dragging = $state<"left" | "right" | "bottom" | null>(null);
let centerStack: HTMLElement | undefined = $state(); let centerStack: HTMLElement | undefined = $state();
// A focused plugin view is the active tab. It covers the area only when no pane shows it.
const editorPluginVisible = $derived($pluginView?.placement === "editor" && $pluginEditorActive); const editorPluginVisible = $derived($pluginView?.placement === "editor" && $pluginEditorActive);
const coverKey = $derived(editorPluginVisible && $pluginView && !paneOf(documentPanes, { pluginKey: $pluginView.key }) ? $pluginView.key : null);
type EditorTab = WorkbenchTab & ({ buffer: OpenBuffer } | { plugin: OpenPluginView }); type EditorTab = WorkbenchTab & ({ buffer: OpenBuffer } | { plugin: OpenPluginView });
let tabOrder = $state<string[]>([]); let tabOrder = $state<string[]>([]);
const availableTabs = $derived<EditorTab[]>([ const availableTabs = $derived<EditorTab[]>([
@@ -361,9 +510,7 @@
} catch (reason) { error = String(reason); } } catch (reason) { error = String(reason); }
} }
const activeTabPath = $derived(editorPluginVisible && $pluginView ? `plugin:${$pluginView.key}` : activePath); const activeTabPath = $derived(editorPluginVisible && $pluginView ? `plugin:${$pluginView.key}` : activePath);
const activeSplit = $derived($pluginSplits.find(tree => $pluginView && containsPane(tree, $pluginView.key))); // The working tabs of the header.
const pluginBounds = $derived(activeSplit ? paneBounds(activeSplit) : $pluginView ? paneBounds($pluginView.key) : {});
// The working tabs, for the header and for the tab bar of each plugin pane in a split.
const tabBarProps = $derived({ tabs: workingTabs, activePath: activeTabPath, onSelect: selectWorkingTab, onClose: closeTab, const tabBarProps = $derived({ tabs: workingTabs, activePath: activeTabPath, onSelect: selectWorkingTab, onClose: closeTab,
onCloseTabs: (path: string, scope: TabCloseScope) => void closeTabs(path, scope), onPin: pinWorkingTab, fileActions: workingTabFileActions, onCloseTabs: (path: string, scope: TabCloseScope) => void closeTabs(path, scope), onPin: pinWorkingTab, fileActions: workingTabFileActions,
tabActions: workingTabActions, onMove: moveWorkingTab, tabDragData: workingTabDragData, onDropTab: (data: string, index: number) => void receiveTab(data, index) }); tabActions: workingTabActions, onMove: moveWorkingTab, tabDragData: workingTabDragData, onDropTab: (data: string, index: number) => void receiveTab(data, index) });
@@ -409,7 +556,7 @@
documents?.setChrome(next); 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) { function setDocumentView(paneId: string, next: ViewMode) {
focusDocumentPane(paneId); focusDocumentPane(paneId);
if (next === "read") { setReading(true, paneId); return; } if (next === "read") { setReading(true, paneId); return; }
@@ -554,6 +701,8 @@
pluginEditorActive.set(false); pluginEditorActive.set(false);
focusLine = null; focusLine = null;
documents?.select(relPath); documents?.select(relPath);
const selected = documents?.active?.id;
if (selected) documentPanes = showInActivePane(documentPanes, { documentId: selected });
focusDocumentPane(documentPanes.active, true); focusDocumentPane(documentPanes.active, true);
status = documents?.active?.kind === "empty" ? $t("New tab") : ""; status = documents?.active?.kind === "empty" ? $t("New tab") : "";
} }
@@ -582,9 +731,14 @@
} }
function workingTabActions(item: WorkbenchTab): ActionMenuItem[] { function workingTabActions(item: WorkbenchTab): ActionMenuItem[] {
const tab = workingTabs.find(tab => tab.id === item.id); const tab = workingTabs.find(tab => tab.id === item.id);
const actions = tab && "plugin" in tab ? pluginTabActions(tab.plugin) : []; if (!tab) return [];
if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return actions; const actions = "plugin" in tab ? pluginTabActions(tab.plugin) : [];
return tab ? [{ label: $t("Open in new window"), icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : []; 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) { async function detachTab(item: WorkbenchTab, keepSource = false) {
const tab = workingTabs.find(tab => tab.id === item.id); const tab = workingTabs.find(tab => tab.id === item.id);
@@ -719,7 +873,7 @@
{ label: $t("Source"), icon: "code", radio: true, checked: viewMode === "source", run: () => setDocumentView(documentPanes.active, "source") }, { label: $t("Source"), icon: "code", radio: true, checked: viewMode === "source", run: () => setDocumentView(documentPanes.active, "source") },
{ label: $t("Read"), icon: "book", radio: true, checked: viewMode === "read", run: () => setDocumentView(documentPanes.active, "read") }, { label: $t("Read"), icon: "book", radio: true, checked: viewMode === "read", run: () => setDocumentView(documentPanes.active, "read") },
{ separator: true }, { separator: true },
{ label: $t("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)) { if (!note || note.kind !== "text" || !isMarkdownPath(note.relPath)) {
return null; return null;
} }
const noteRel = note.relPath; const noteRel = note.relPath;
const current = documents; const current = documents;
try { try {
const rel = attachmentRel(file.name); let rel = attachmentRel(file.name);
const dataUrl = await readFileDataUrl(file); 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]; const base64 = dataUrl.split(",")[1];
if (!base64) { 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; return null;
} }
if (documents !== current || switching) return null; if (documents !== current || switching) return null;
await workspaceWriteBytes(rel, base64); 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) return null; if (documents !== current) return null;
session.changed([rel]); session.changed([rel]);
return `![](${"../".repeat(noteRel.split("/").length - 1)}${rel})`; return `![](${"../".repeat(noteRel.split("/").length - 1)}${rel})`;
@@ -928,7 +1096,10 @@
if (!workingTabs.length) return false; if (!workingTabs.length) return false;
const index = workingTabs.findIndex(tab => tab.relPath === activeTabPath); const index = workingTabs.findIndex(tab => tab.relPath === activeTabPath);
const next = (index + (command === "previous-tab" ? -1 : 1) + workingTabs.length) % workingTabs.length; const next = (index + (command === "previous-tab" ? -1 : 1) + workingTabs.length) % workingTabs.length;
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; return true;
} }
case "command-palette": palette = true; return true; case "command-palette": palette = true; return true;
@@ -1161,7 +1332,7 @@
try { try {
// The layout stays in localStorage on purpose: per-machine view state that is harmless to lose. // The layout stays in localStorage on purpose: per-machine view state that is harmless to lose.
const layout = parseWorkbenchLayout(localStorage.getItem(WORKBENCH_LAYOUT_KEY)); const layout = parseWorkbenchLayout(localStorage.getItem(WORKBENCH_LAYOUT_KEY));
({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout); ({ leftOpen, rightOpen, leftWidth, rightWidth, leftView, backlinksOpen } = layout);
if (transferredWindow) { leftOpen = false; rightOpen = false; } if (transferredWindow) { leftOpen = false; rightOpen = false; }
layoutReady = true; layoutReady = true;
} catch { error = $t("Could not read your layout. Default layout applies for this window."); } } catch { error = $t("Could not read your layout. Default layout applies for this window."); }
@@ -1194,7 +1365,7 @@
$effect(() => { $effect(() => {
if (!layoutReady || transferredWindow) return; if (!layoutReady || transferredWindow) return;
const saved = { leftOpen: narrow.left ? wide.left : leftOpen, rightOpen: narrow.right ? wide.right : rightOpen }; const saved = { leftOpen: narrow.left ? wide.left : leftOpen, rightOpen: narrow.right ? wide.right : rightOpen };
try { saveWorkbenchLayout(localStorage, { ...saved, leftWidth, rightWidth, leftView }); } try { saveWorkbenchLayout(localStorage, { ...saved, leftWidth, rightWidth, leftView, backlinksOpen }); }
catch { error = $t("Could not save your layout. Layout changes apply for this window only."); } catch { error = $t("Could not save your layout. Layout changes apply for this window only."); }
}); });
@@ -1301,7 +1472,7 @@
{leftView} {leftView}
{sidebarNavigation} {sidebarNavigation}
onSelectLeft={selectLeft} 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} onNewTab={newTab}
canOpenBrowser={!!browserContribution?.newTab} canOpenBrowser={!!browserContribution?.newTab}
{browserOpening} {browserOpening}
@@ -1331,6 +1502,7 @@
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath} activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
{searchRequest} {searchRequest}
onOpenFile={(entry, line, target) => void openFile(entry, line, target)} onOpenFile={(entry, line, target) => void openFile(entry, line, target)}
onOpenRight={(entry) => void openToRight(entry, documentPanes.active)}
onCreated={(entry) => { void openCreatedFile(entry); }} onCreated={(entry) => { void openCreatedFile(entry); }}
onSaveTemplate={(entry) => { void saveTemplate(entry); }} onSaveTemplate={(entry) => { void saveTemplate(entry); }}
onManageTemplates={() => templateManager = true} onManageTemplates={() => templateManager = true}
@@ -1357,13 +1529,14 @@
<div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}> <div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}>
<DocumentArea <DocumentArea
bind:this={documentArea}
bind:pluginPaneComponents bind:pluginPaneComponents
bind:paneComponents bind:paneComponents
{editorPluginVisible} pluginCover={coverKey !== null}
split={!!activeSplit} drop={tabDrop}
{pluginBounds} onResize={(path, ratio) => { documentPanes = resizeDocumentPanes(documentPanes, path, ratio); }}
tabBar={tabBarProps}
{documentViews} {documentViews}
layout={documentPanes.layout}
activePane={documentPanes.active} activePane={documentPanes.active}
{documents} {documents}
{tabs} {tabs}
@@ -1379,7 +1552,7 @@
onQuickOpen={() => quickOpen = true} onQuickOpen={() => quickOpen = true}
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined} onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
{onChange} {onChange}
onInsertImage={(file, tab) => insertImage(file, tab)} onInsertImage={(file, tab, source) => insertImage(file, tab, source)}
onRenameTitle={renameNoteTitle} onRenameTitle={renameNoteTitle}
tableActions={(pane) => ({ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) })} tableActions={(pane) => ({ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) })}
linkActions={(pane) => ({ linkActions={(pane) => ({
@@ -1448,6 +1621,7 @@
}} }}
showBacklinks={buffer?.kind === "text" && isMarkdownPath(buffer.relPath) && !editorPluginVisible} showBacklinks={buffer?.kind === "text" && isMarkdownPath(buffer.relPath) && !editorPluginVisible}
{backlinks} {backlinks}
bind:backlinksOpen
{session} {session}
onOpenBacklink={(entry) => void openBacklink(entry)} onOpenBacklink={(entry) => void openBacklink(entry)}
/> />
+4 -4
View File
@@ -115,12 +115,12 @@
:global(.shell.left-open) .header-left { width: calc(var(--ribbon-width) + var(--left) + 1px); } :global(.shell.left-open) .header-left { width: calc(var(--ribbon-width) + var(--left) + 1px); }
.header-left :global(.icon-btn), .header-right :global(.icon-btn) { flex-shrink: 0; } .header-left :global(.icon-btn), .header-right :global(.icon-btn) { flex-shrink: 0; }
.header-right { justify-content: flex-end; } .header-right { justify-content: flex-end; }
/* A drag area keeps the window movable when the tabs fill the header: 120 pixels, and at least 48 in a narrow header. */ /* 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: 0 1 120px; min-width: 48px; align-self: stretch; } .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) { .header-center :global(.tabs) {
flex: 0 1000 auto; flex: 0 1 auto;
align-self: stretch; align-self: stretch;
min-width: 120px; min-width: 120px;
min-height: 28px; min-height: 28px;
+15
View File
@@ -23,9 +23,24 @@
const folderName = (path: string) => path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path; const folderName = (path: string) => path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path;
const removeTooltip = (node: HTMLElement) => ({ destroy: attachTooltip(node, () => tr("Remove from recent workspaces")) }); 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.")); 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() { export async function show() {
if (busy || creating) return; if (busy || creating) return;
if (pressedOpen) { pressedOpen = false; return; }
if (menu.matches(":popover-open")) { menu.hidePopover(); return; } if (menu.matches(":popover-open")) { menu.hidePopover(); return; }
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
error = ""; loading = true; error = ""; loading = true;
+1 -1
View File
@@ -43,7 +43,7 @@
<style> <style>
.access-button { display: flex; align-items: center; gap: 6px; white-space: nowrap; min-height: 32px; padding: 5px 8px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); } .access-button { display: flex; align-items: center; gap: 6px; white-space: nowrap; min-height: 32px; padding: 5px 8px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); }
.access-button:hover, .access-button[aria-expanded="true"] { background: var(--rs-bg-active); } .access-button:hover, .access-button[aria-expanded="true"] { background: var(--rs-hover-bg); }
.access-button:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; } .access-button:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
.access-button.compact { position: relative; width: 28px; height: 28px; min-height: 28px; padding: 5px; } .access-button.compact { position: relative; width: 28px; height: 28px; min-height: 28px; padding: 5px; }
.access-button.ribbon { justify-content: center; width: 32px; height: 32px; min-height: 32px; padding: 0; } .access-button.ribbon { justify-content: center; width: 32px; height: 32px; min-height: 32px; padding: 0; }
+5
View File
@@ -28,6 +28,11 @@
findPanel?.focus(); findPanel?.focus();
} }
/** Give the keyboard to the tab: to the element that the view marks with `data-tab-focus`, or to the view. */
export function focus() {
(host?.querySelector<HTMLElement>("[data-tab-focus]") ?? host)?.focus({ preventScroll: true });
}
function searchKey(event: KeyboardEvent) { function searchKey(event: KeyboardEvent) {
if (event.target instanceof Element && event.target.closest('dialog, [role="dialog"], [role="menu"]')) return; if (event.target instanceof Element && event.target.closest('dialog, [role="dialog"], [role="menu"]')) return;
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "f") { if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "f") {
+2 -1
View File
@@ -1,7 +1,7 @@
import type { BackgroundFrame } from './backgroundContracts.ts'; import type { BackgroundFrame } from './backgroundContracts.ts';
const positions = ['center', 'top left', 'top', 'top right', 'left', 'right', 'bottom left', 'bottom', 'bottom right']; const positions = ['center', 'top left', 'top', 'top right', 'left', 'right', 'bottom left', 'bottom', 'bottom right'];
const properties = ['--rs-background-overlay', '--rs-background-image', '--rs-background-position', '--rs-background-size', '--rs-background-layer-sizes', '--rs-background-layer-positions', '--rs-background-previous-layer-sizes', '--rs-background-previous-layer-positions', '--rs-background-previous-image', '--rs-background-previous-position', '--rs-background-previous-size', '--rs-background-transition-image', '--rs-workarea-sidebar-bg', '--rs-workarea-editor-bg', '--rs-workarea-surface-opacity', '--rs-workarea-plugin-bg', '--rs-menu-bg', '--rs-menu-active-bg', '--rs-menu-backdrop'] as const; const properties = ['--rs-background-overlay', '--rs-background-image', '--rs-background-position', '--rs-background-size', '--rs-background-layer-sizes', '--rs-background-layer-positions', '--rs-background-previous-layer-sizes', '--rs-background-previous-layer-positions', '--rs-background-previous-image', '--rs-background-previous-position', '--rs-background-previous-size', '--rs-background-transition-image', '--rs-workarea-sidebar-bg', '--rs-workarea-editor-bg', '--rs-workarea-surface-opacity', '--rs-workarea-plugin-bg', '--rs-menu-bg', '--rs-menu-active-bg', '--rs-menu-backdrop', '--rs-hover-bg'] as const;
function validImage(frame: BackgroundFrame) { function validImage(frame: BackgroundFrame) {
return frame && typeof frame.url === 'string' && /^blob:[^\s"'\\()]+$/.test(frame.url) return frame && typeof frame.url === 'string' && /^blob:[^\s"'\\()]+$/.test(frame.url)
@@ -122,6 +122,7 @@ export class BackgroundHub {
put('--rs-menu-bg', 'var(--rs-image-menu-bg)'); put('--rs-menu-bg', 'var(--rs-image-menu-bg)');
put('--rs-menu-active-bg', 'var(--rs-image-menu-active-bg)'); put('--rs-menu-active-bg', 'var(--rs-image-menu-active-bg)');
put('--rs-menu-backdrop', 'var(--rs-image-menu-backdrop)'); put('--rs-menu-backdrop', 'var(--rs-image-menu-backdrop)');
put('--rs-hover-bg', 'var(--rs-image-hover-bg)');
put('--rs-background-transition-image', previous ? currentImage : 'none'); put('--rs-background-transition-image', previous ? currentImage : 'none');
put('--rs-background-previous-image', previous ? previous.image : 'none'); put('--rs-background-previous-image', previous ? previous.image : 'none');
put('--rs-background-previous-position', frame.previous?.position ?? frame.position); put('--rs-background-previous-position', frame.previous?.position ?? frame.position);
+17
View File
@@ -56,6 +56,23 @@ function encode(section: SettingsSection, value: unknown): string {
return section === 'language' && typeof value === 'string' ? value : JSON.stringify(value); 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) { function notify(section: SettingsSection) {
for (const callback of [...subscribers.get(section) ?? []]) { for (const callback of [...subscribers.get(section) ?? []]) {
try { callback(); } catch (reason) { console.error(`A ${section} settings subscriber failed.`, reason); } 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 { syncTableFormulas } from '$lib/formulas';
import { syncFileTitle } from '$lib/editor/fileTitle'; import { syncFileTitle } from '$lib/editor/fileTitle';
import { onMount } from 'svelte'; 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'; import { applyAppearance, readAppearance } from './appearance';
onMount(() => { onMount(() => {
const stopLocale = syncLocale(); const stopLocale = syncLocale();
@@ -14,7 +14,8 @@
const stored = readSection('appearance'); const stored = readSection('appearance');
const appearance = readAppearance(); const appearance = readAppearance();
// Save the normalized value, for example a new ID for a renamed theme. // 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. */ }); writeSection('appearance', appearance).catch(() => { /* The normalized value applies until the next save. */ });
} }
applyAppearance(appearance); applyAppearance(appearance);
+1 -1
View File
@@ -11,7 +11,7 @@ export const silverSerpent = {
variants: { variants: {
dark: { dark: {
bg: '#141619', 'bg-elevated': '#1c1e21', 'bg-active': '#2b3034', border: '#3b4046', bg: '#141619', 'bg-elevated': '#1c1e21', 'bg-active': '#2b3034', border: '#3b4046',
text: '#e5e8ec', 'text-dim': '#b3b8be', 'text-strong': '#fcf9ea', text: '#e5e8ec', 'text-dim': '#c2c6cc', 'text-strong': '#fcf9ea',
accent: '#bfd4e7', 'accent-2': '#31d78c', selection: '#0c6944', 'item-selection-bg': '#0c6944a6', accent: '#bfd4e7', 'accent-2': '#31d78c', selection: '#0c6944', 'item-selection-bg': '#0c6944a6',
error: '#ff645f', 'warn-hot': '#fd923e', warn: '#fec84b', ok: '#5cdc78', special: '#fb9989', error: '#ff645f', 'warn-hot': '#fd923e', warn: '#fec84b', ok: '#5cdc78', special: '#fb9989',
'syntax-keyword': '#31d78c', 'syntax-string': '#f0de99', 'syntax-number': '#fda293', 'syntax-comment': '#b2b7bd', 'syntax-keyword': '#31d78c', 'syntax-string': '#f0de99', 'syntax-number': '#fda293', 'syntax-comment': '#b2b7bd',
+7 -3
View File
@@ -37,13 +37,17 @@
--rs-menu-icon-gap: 8px; --rs-menu-icon-gap: 8px;
--rs-menu-font-size: 13px; --rs-menu-font-size: 13px;
--rs-menu-border: transparent; --rs-menu-border: transparent;
/* Menus are opaque. With a background image, they stay at least 92% opaque and blur the image (UI-043). */ /* Menus are opaque (UI-043). With a background image, they use the surface transparency and blur the image (UI-061). */
--rs-menu-bg: var(--rs-bg-elevated); --rs-menu-bg: var(--rs-bg-elevated);
--rs-menu-active-bg: var(--rs-bg-active); --rs-menu-active-bg: var(--rs-bg-active);
--rs-menu-backdrop: none; --rs-menu-backdrop: none;
--rs-image-menu-bg: color-mix(in srgb, var(--rs-bg-elevated) max(92%, var(--rs-surface-opacity)), transparent); --rs-image-menu-bg: color-mix(in srgb, var(--rs-bg-elevated) var(--rs-surface-opacity), transparent);
--rs-image-menu-active-bg: color-mix(in srgb, var(--rs-bg-active) max(92%, var(--rs-surface-opacity)), transparent); --rs-image-menu-active-bg: var(--rs-image-hover-bg);
--rs-image-menu-backdrop: blur(18px) saturate(1.2); --rs-image-menu-backdrop: blur(18px) saturate(1.2);
/* The fill of hovered rows and filled controls in the work area. With a background image, a thin veil of the text color
keeps the image visible and the hover visible over light and dark image areas (UI-061). */
--rs-hover-bg: var(--rs-bg-active);
--rs-image-hover-bg: color-mix(in srgb, var(--rs-text-strong) 6%, transparent);
--rs-menu-shadow: 0 8px 30px #0006; --rs-menu-shadow: 0 8px 30px #0006;
--rs-item-selection-radius: var(--rs-control-radius); --rs-item-selection-radius: var(--rs-control-radius);
--rs-item-selection-bg: color-mix(in srgb, var(--rs-accent) 12%, transparent); --rs-item-selection-bg: color-mix(in srgb, var(--rs-accent) 12%, transparent);
+4
View File
@@ -34,6 +34,8 @@
<path d="m6 9 6 6 6-6" /> <path d="m6 9 6 6 6-6" />
{:else if icon === "chevrons-up-down"} {:else if icon === "chevrons-up-down"}
<path d="m7 15 5 5 5-5M7 9l5-5 5 5" /> <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"} {:else if icon === "maximize"}
<path d="M8 3H3v5M16 3h5v5M21 16v5h-5M8 21H3v-5" /> <path d="M8 3H3v5M16 3h5v5M21 16v5h-5M8 21H3v-5" />
{:else if icon === "minimize"} {:else if icon === "minimize"}
@@ -154,6 +156,8 @@
<path d="M3 4v16M21 4v16M7 12h10M10 9l-3 3 3 3M14 9l3 3-3 3" /> <path d="M3 4v16M21 4v16M7 12h10M10 9l-3 3 3 3M14 9l3 3-3 3" />
{:else if icon === "rotate"} {:else if icon === "rotate"}
<path d="M20 7v5h-5" /><path d="M20 12a8 8 0 1 0-2 6" /> <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} {/if}
</svg> </svg>
<style> <style>
+4 -2
View File
@@ -23,6 +23,7 @@
| "more" | "more"
| "chevron-down" | "chevron-down"
| "chevrons-up-down" | "chevrons-up-down"
| "scroll"
| "up" | "up"
| "down" | "down"
| "maximize" | "maximize"
@@ -61,7 +62,8 @@
| "zoom-in" | "zoom-in"
| "zoom-out" | "zoom-out"
| "fit-width" | "fit-width"
| "rotate"; | "rotate"
| "split-close";
type Props = { type Props = {
icon: IconName; icon: IconName;
@@ -145,7 +147,7 @@
/* Hover gets a neutral fill. An active toggle also gets the accent color and an accent bar. A disabled button is dim. */ /* Hover gets a neutral fill. An active toggle also gets the accent color and an accent bar. A disabled button is dim. */
.icon-btn:not(:disabled):hover { .icon-btn:not(:disabled):hover {
background: var(--rs-bg-active); background: var(--rs-hover-bg);
border-color: var(--rs-border); border-color: var(--rs-border);
color: var(--rs-text-strong); color: var(--rs-text-strong);
} }
+1 -1
View File
@@ -49,7 +49,7 @@
font: inherit; font: inherit;
white-space: nowrap; white-space: nowrap;
} }
.rs-find-button:hover:not(:disabled) { background: var(--rs-bg-active); color: var(--rs-accent); } .rs-find-button:hover:not(:disabled) { background: var(--rs-hover-bg); color: var(--rs-accent); }
.rs-find-options { gap: 4px 14px; color: var(--rs-text-dim); font-size: 12px; } .rs-find-options { gap: 4px 14px; color: var(--rs-text-dim); font-size: 12px; }
.rs-find-options label { display: inline-flex; align-items: center; gap: 5px; min-height: 24px; cursor: pointer; } .rs-find-options label { display: inline-flex; align-items: center; gap: 5px; min-height: 24px; cursor: pointer; }
.rs-find-options input { margin: 0; accent-color: var(--rs-accent); } .rs-find-options input { margin: 0; accent-color: var(--rs-accent); }
+10
View File
@@ -83,6 +83,16 @@ export function workspaceWriteBytes(rel: string, base64: string): Promise<void>
return invoke("workspace_write_bytes", { rel, base64 }); 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 = { export type CopyResult = {
name: string; name: string;
rel_path: 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;
}
+113 -22
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 }; export type DocumentPanes = { layout: SplitLayout; panes: DocumentPane[]; active: string };
/** The content of a pane: a document ID or the key of a plugin editor view. */
export type PaneContent = { documentId: string } | { pluginKey: string };
function emptyPane(id: string): DocumentPane {
return { id, documentId: null, pluginKey: null, reading: false, split: false };
}
function filled(id: string, content: PaneContent): DocumentPane {
return "documentId" in content ? { ...emptyPane(id), documentId: content.documentId } : { ...emptyPane(id), pluginKey: content.pluginKey };
}
export function initialDocumentPanes(): DocumentPanes { export function initialDocumentPanes(): DocumentPanes {
return { layout: "document-main", panes: [{ 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 { export function selectPane(state: DocumentPanes, id: string): DocumentPanes {
return state.active === id || !state.panes.some(pane => pane.id === id) ? state : { ...state, active: id }; return state.active === id || !state.panes.some(pane => pane.id === id) ? state : { ...state, active: id };
} }
/** Tabs own documents. Panes keep only a reference and local viewing state. */ /** The pane that shows the content, if a pane shows it. */
export function syncDocumentPanes(state: DocumentPanes, live: readonly string[], selected: string | null): DocumentPanes { export function paneOf(state: DocumentPanes, content: PaneContent): DocumentPane | undefined {
const ids = new Set(live); return state.panes.find(pane => "documentId" in content ? pane.documentId === content.documentId : pane.pluginKey === content.pluginKey);
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);
} }
/** Remove the panes that became empty. The last pane always stays. */
function collapse(state: DocumentPanes, panes: DocumentPane[], active: string): DocumentPanes {
let layout = state.layout; let layout = state.layout;
for (const pane of panes) { 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); const next = removePane(layout, pane.id);
if (next !== null) { layout = next; panes = panes.filter(item => item.id !== pane.id); } if (next !== null) { layout = next; panes = panes.filter(item => item.id !== pane.id); }
} }
@@ -34,14 +44,49 @@ export function syncDocumentPanes(state: DocumentPanes, live: readonly string[],
return { layout, panes, active }; 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 (existing) return selectPane(state, existing.id);
if (!state.panes.some(pane => pane.id === source) || state.panes.some(pane => pane.id === paneId)) return state; if (!state.panes.some(pane => pane.id === source) || state.panes.some(pane => pane.id === paneId)) return state;
return { const layout = splitPane(state.layout, source, paneId, direction === "left" ? "right" : direction, direction === "left");
layout: splitPane(state.layout, source, paneId, "right"), return { layout, panes: [...state.panes, filled(paneId, content)], active: paneId };
panes: [...state.panes, { id: paneId, documentId, reading: false, split: false }], active: paneId, }
};
export function splitDocumentPane(state: DocumentPanes, source: string, documentId: string, paneId: string): DocumentPanes {
return splitWithContent(state, source, { documentId }, paneId);
} }
export function closeDocumentPane(state: DocumentPanes, id: string): DocumentPanes { export function closeDocumentPane(state: DocumentPanes, id: string): DocumentPanes {
@@ -50,15 +95,61 @@ export function closeDocumentPane(state: DocumentPanes, id: string): DocumentPan
if (layout === null) return state; if (layout === null) return state;
const bounds = paneBounds(state.layout); const bounds = paneBounds(state.layout);
const panes = state.panes.filter(pane => pane.id !== id); const panes = state.panes.filter(pane => pane.id !== id);
const 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 }; 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 { export function readDocumentPane(state: DocumentPanes, id: string, reading: boolean): DocumentPanes {
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, reading, split: reading ? false : pane.split } : pane) }; return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, reading, split: reading ? false : pane.split } : pane) };
} }
/** Show or hide the Read view beside the editor. 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 { export function splitDocumentView(state: DocumentPanes, id: string, split: boolean): DocumentPanes {
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, split, reading: split ? false : pane.reading } : pane) }; return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, split, reading: split ? false : pane.reading } : pane) };
} }
+44
View File
@@ -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}`; 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[] { export function imageFiles(data: DataTransfer | null): File[] {
return [...(data?.files ?? [])].filter(file => isImagePath(file.name)); return [...(data?.files ?? [])].filter(file => isImagePath(file.name));
} }

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