Compare commits
108
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d849c3c1b5 | ||
|
|
c68a1afb6d | ||
|
|
956ead818b | ||
|
|
e66f089176 | ||
|
|
e6deecc092 | ||
|
|
833f793244 | ||
|
|
53b9cea7f0 | ||
|
|
ab868bbe8e | ||
|
|
115c32fa92 | ||
|
|
8c43f598fb | ||
|
|
4e5c3cb165 | ||
|
|
d3218b2501 | ||
|
|
58f77b2e9f | ||
|
|
f019d5d8d4 | ||
|
|
135e6d6d92 | ||
|
|
a950edfb13 | ||
|
|
54ccea199e | ||
|
|
2928bc220b | ||
|
|
0bf7d47496 | ||
|
|
516671a235 | ||
|
|
4f8d91e70b | ||
|
|
0cc83b7b93 | ||
|
|
5958c9c252 | ||
|
|
d10615d903 | ||
|
|
aebe700366 | ||
|
|
c06d48f250 | ||
|
|
6004e126f7 | ||
|
|
48b8249ba6 | ||
|
|
5dc53e4a5e | ||
|
|
8bc11c801f | ||
|
|
c271e2bae1 | ||
|
|
eeddd880e1 | ||
|
|
0fdc991b2e | ||
|
|
b7a9784f55 | ||
|
|
c8cf56b224 | ||
|
|
9cf82503d0 | ||
|
|
ebacdb8164 | ||
|
|
b2348d0fe8 | ||
|
|
5483881bc2 | ||
|
|
d160568249 | ||
|
|
35f39e93f3 | ||
|
|
a34c1a5dce | ||
|
|
445d0200b2 | ||
|
|
5bd616d7fd | ||
|
|
af68d92969 | ||
|
|
1c19da25ba | ||
|
|
e9c59f28de | ||
|
|
3e6bc5f088 | ||
|
|
f32f60b540 | ||
|
|
6cd9195370 | ||
|
|
724402729e | ||
|
|
80f5d908e0 | ||
|
|
36a06a9c6b | ||
|
|
4d09da30d9 | ||
|
|
d62ee5d0b7 | ||
|
|
c1ad9fa60c | ||
|
|
bb0b8f88b6 | ||
|
|
9591c251e9 | ||
|
|
374d4db933 | ||
|
|
e83bf46268 | ||
|
|
a6d6e96d6d | ||
|
|
eb2adf6a11 | ||
|
|
5e1533c371 | ||
|
|
72671e5d01 | ||
|
|
777cab2cc1 | ||
|
|
5d5ba9e1f7 | ||
|
|
a0eef01ed0 | ||
|
|
2448c68abf | ||
|
|
70510a114f | ||
|
|
7914942698 | ||
|
|
e217eb31d2 | ||
|
|
bd46f3a189 | ||
|
|
69f90df571 | ||
|
|
c66ea1ce83 | ||
|
|
e433bed28e | ||
|
|
90d1940c73 | ||
|
|
2d2a146e34 | ||
|
|
4240d7dad1 | ||
|
|
d7a87795f5 | ||
|
|
44a0ef7ba7 | ||
|
|
3fa514f19a | ||
|
|
46e3daae6c | ||
|
|
562ef87d24 | ||
|
|
f741389418 | ||
|
|
b742d274f1 | ||
|
|
0dd43335fe | ||
|
|
4e14be33bd | ||
|
|
ae388885bb | ||
|
|
3daf5270a7 | ||
|
|
622c2dffaa | ||
|
|
146dbf0305 | ||
|
|
7c497ba569 | ||
|
|
7e7660d9bb | ||
|
|
da28f6eaf6 | ||
|
|
42dd0fa711 | ||
|
|
68e86ab6eb | ||
|
|
b066359b66 | ||
|
|
30cbfeedd6 | ||
|
|
edef2520af | ||
|
|
f6eaa52949 | ||
|
|
909894b9c8 | ||
|
|
a8b1defb9d | ||
|
|
dd9fc64676 | ||
|
|
5d0a4a24f9 | ||
|
|
6b7af0d527 | ||
|
|
0268c5c9f0 | ||
|
|
43106ed9c7 | ||
|
|
bdc15e952d |
@@ -1,2 +0,0 @@
|
||||
# Tauri writes these files with LF line endings on each build.
|
||||
src-tauri/permissions/autogenerated/*.toml text eol=lf
|
||||
@@ -0,0 +1,3 @@
|
||||
# Agent instructions
|
||||
|
||||
The instructions for AI agents in this repository are in [CLAUDE.md](CLAUDE.md). Read and obey that file.
|
||||
@@ -5,7 +5,6 @@ A Tauri 2 host in Rust (`src-tauri/`) serves a Svelte 5 and TypeScript interface
|
||||
Git, Background, Terminal, PDF Viewer, and Project Management are native features with an off switch in Settings → Features (`src/lib/features/`). They do not use the plugin API.
|
||||
Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_CSV_Viewer`.
|
||||
The [development guide](docs/development.md#architecture) maps the source folders.
|
||||
The public repository is `https://github.com/kwyvern-gh/RuneStone`. Its releases page holds the installers, the browser engine ZIPs, and the SDK packages.
|
||||
|
||||
## Skills
|
||||
|
||||
@@ -120,5 +119,5 @@ Rules from the owner:
|
||||
|
||||
## Subagents
|
||||
|
||||
Use only Haiku 5.5 (`model: "haiku"`) or Opus 5.5 (`model: "opus"`, effort `high` to `xhigh`). Never use Sonnet or Fable.
|
||||
Use only Haiku 5.5 (`model: "haiku"`) or Opus 5.5 (`model: "opus"`, effort `medium` to `xhigh`). Never use Sonnet or Fable.
|
||||
The `runestone-project-management` skill maps task types to models and lists what each brief must contain.
|
||||
|
||||
@@ -1,202 +0,0 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,4 +0,0 @@
|
||||
RuneStone
|
||||
Copyright 2026 Knotty Wyvern
|
||||
|
||||
This product includes third-party software. See THIRD_PARTY_NOTICES.md for its licenses.
|
||||
@@ -4,25 +4,29 @@ RuneStone is a desktop workspace for Markdown notes, code, and project work that
|
||||
|
||||
## Install and start
|
||||
|
||||
On Windows 10 or 11 (x64):
|
||||
Download the installer for your computer.
|
||||
|
||||
1. Download [RuneStone_1.0.0_x64-setup.exe](https://github.com/kwyvern-gh/RuneStone/releases/download/v1.0.0/RuneStone_1.0.0_x64-setup.exe).
|
||||
2. Open the installer and complete setup.
|
||||
3. Open RuneStone from the Start menu.
|
||||
| Platform | Installer | Status |
|
||||
| --- | --- | --- |
|
||||
| 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 |
|
||||
| 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 |
|
||||
|
||||
The built-in browser needs a separate engine download of about 160 MB. A browser tab offers it on first use.
|
||||
- **Windows:** Open the installer and complete setup. Then open RuneStone from the Start menu.
|
||||
- **macOS:** Open the disk image and drag RuneStone into Applications. Then open RuneStone from Applications.
|
||||
- **Linux:** Run `sudo apt install ./RuneStone_0.1.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).
|
||||
|
||||
macOS and Linux have no 1.0.0 package. Build RuneStone from source on these systems. See [Build Linux packages](docs/builds.md#build-linux-packages) or [macOS packages](docs/builds.md#macos-packages).
|
||||
|
||||
## What you can do
|
||||
|
||||
- Write Markdown with live formatting, editable tables, table formulas, images, and Mermaid diagrams.
|
||||
- Switch between the Write, Source, Read, and Split views.
|
||||
- Find files, search a workspace, and resolve changes that other tools make to your files.
|
||||
- Open web pages in browser tabs beside your documents.
|
||||
- Use Git source control, a terminal, a PDF viewer, Project Management boards, and a background slideshow. Each one has an off switch in **Settings → Features**.
|
||||
- Add optional plugins from plugin ZIP files.
|
||||
- Add optional plugins, such as Terminal, Git, Project Management, PDF Viewer, and CSV Viewer.
|
||||
|
||||
## Find help
|
||||
|
||||
@@ -43,10 +47,6 @@ When you report a problem to the maintainer, include the app version, operating
|
||||
- Read the [interface design reference](docs/ui-design.md) before you change the interface.
|
||||
- See [product boundaries](docs/development.md#product-boundaries) for exclusions and architecture constraints.
|
||||
|
||||
## License
|
||||
|
||||
RuneStone uses the [Apache License 2.0](LICENSE). See also [NOTICE](NOTICE) and the [third-party notices](THIRD_PARTY_NOTICES.md).
|
||||
|
||||
## Maintainer
|
||||
|
||||
[kwyvern-gh](https://github.com/kwyvern-gh)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# Third-party notices
|
||||
|
||||
The RuneStone app includes the third-party packages below. The browser engine has its own notices in [browser-runtime/THIRD_PARTY_NOTICES.md](browser-runtime/THIRD_PARTY_NOTICES.md).
|
||||
The RuneStone app includes the third-party packages below. Each row gives the package, its version, its license, and its source.
|
||||
The license texts follow the table. The browser engine has its own notices in [browser-runtime/THIRD_PARTY_NOTICES.md](browser-runtime/THIRD_PARTY_NOTICES.md).
|
||||
|
||||
| Package | Version | License | Source | Used by |
|
||||
| --- | --- | --- | --- | --- |
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "runestone-browser",
|
||||
"version": "0.1.11",
|
||||
"version": "0.1.8",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "runestone-browser",
|
||||
"version": "0.1.11",
|
||||
"version": "0.1.8",
|
||||
"dependencies": {
|
||||
"@ghostery/adblocker": "2.18.2",
|
||||
"ipaddr.js": "2.3.0"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "runestone-browser",
|
||||
"version": "0.1.11",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"description": "Isolated browser runtime included with RuneStone",
|
||||
"type": "module",
|
||||
|
||||
@@ -5,27 +5,7 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import electron from 'electron';
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), 'runestone-plugin-browser-'));
|
||||
// A two-frame GIF that the server gives only one time, as some image hosts do.
|
||||
const onceGif = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAACAkQBACH5BAAKAAAALAAAAAABAAEAAAICTAEAOw==', 'base64');
|
||||
let onceGifServed = false;
|
||||
// The same GIF with 7 MB of comment blocks, so that Copy image needs more than one part.
|
||||
const comment = Buffer.concat([Buffer.from([255]), Buffer.alloc(255, 0x61)]);
|
||||
const largeGif = Buffer.concat([onceGif.subarray(0, 32), Buffer.from([0x21, 0xfe]), ...Array(28_000).fill(comment), Buffer.from([0]), onceGif.subarray(32)]);
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.url === '/direct.gif') {
|
||||
res.writeHead(200, { 'Content-Type': 'image/gif' });
|
||||
return res.end(largeGif);
|
||||
}
|
||||
if (req.url === '/large.gif') {
|
||||
res.writeHead(200, { 'Content-Type': 'image/gif' });
|
||||
return res.end(largeGif);
|
||||
}
|
||||
if (req.url === '/once.gif') {
|
||||
if (onceGifServed) { res.writeHead(200, { 'Content-Type': 'text/html' }); return res.end('Invalid request'); }
|
||||
onceGifServed = true;
|
||||
res.writeHead(200, { 'Content-Type': 'image/gif' });
|
||||
return res.end(onceGif);
|
||||
}
|
||||
if (req.url === '/picture.png') {
|
||||
res.writeHead(200, { 'Content-Type': 'image/png' });
|
||||
return res.end(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII=', 'base64'));
|
||||
|
||||
@@ -31,31 +31,6 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
|
||||
pageFocusStates.set(wc, enabled);
|
||||
if (enabled) wc.focus();
|
||||
}
|
||||
// The last image that Copy image took from a page. RuneStone gets it in parts when the user pastes.
|
||||
let copied = null;
|
||||
const COPIED_PART = 3_000_000;
|
||||
// The page holds the encoded image. Its bytes keep all frames of a GIF, and the website gets no second request.
|
||||
async function loadedImage(wc, url) {
|
||||
if (!wc.debugger.isAttached()) { wc.debugger.attach('1.3'); pageFocusStates.delete(wc); }
|
||||
await wc.debugger.sendCommand('Page.enable');
|
||||
try {
|
||||
const href = value => { try { return new URL(value).href; } catch { return ''; } };
|
||||
const nodes = [(await wc.debugger.sendCommand('Page.getResourceTree')).frameTree];
|
||||
for (const node of nodes) {
|
||||
// An image that opens as the page itself is the main resource of its frame.
|
||||
const page = href(node.frame.url) === url && /^image\//.test(node.frame.mimeType) ? node.frame : undefined;
|
||||
const resource = page ?? node.resources?.find(item => item.type === 'Image' && href(item.url) === url);
|
||||
if (resource) {
|
||||
const { content, base64Encoded } = await wc.debugger.sendCommand('Page.getResourceContent', { frameId: node.frame.id, url: resource.url });
|
||||
const data = Buffer.from(content, base64Encoded ? 'base64' : 'utf8');
|
||||
const valid = /^image\/(?:gif|png|jpeg|webp|avif|bmp)$/.test(resource.mimeType) && data.length > 0 && data.length <= 20_000_000;
|
||||
return valid ? { mime: resource.mimeType, data } : null;
|
||||
}
|
||||
nodes.push(...(node.childFrames ?? []));
|
||||
}
|
||||
return null;
|
||||
} finally { await wc.debugger.sendCommand('Page.disable').catch(() => {}); }
|
||||
}
|
||||
function emulateViewport(item) {
|
||||
if (!item.viewport) return;
|
||||
const { width, height } = item.viewport, scale = item.scale;
|
||||
@@ -166,9 +141,7 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
|
||||
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', (_event, url) => { store.visit(profileId, url, item.title); changed(); });
|
||||
wc.on('did-navigate-in-page', (_event, _url, main) => { if (main) { item.epoch++; agent.revokeAll(); } changed(); });
|
||||
wc.on('page-title-updated', (_event, title) => { item.title = title.slice(0, 200); changed(); });
|
||||
wc.on('page-favicon-updated', (_event, urls) => {
|
||||
@@ -275,13 +248,7 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
|
||||
switch (args.action) {
|
||||
case 'copyLink': if (context.linkURL) clipboard.writeText(context.linkURL); break;
|
||||
case 'copyImageAddress': if (context.srcURL) clipboard.writeText(context.srcURL); break;
|
||||
case 'copyImage': {
|
||||
if (!context.hasImageContents) 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 'copyImage': if (context.hasImageContents) wc.copyImageAt(Math.round(context.x * current.scale), Math.round(context.y * current.scale)); break;
|
||||
case 'openExternal': if (context.linkURL) await openExternal(context.linkURL); break;
|
||||
case 'saveImage': case 'saveLink': {
|
||||
const url = args.action === 'saveImage' ? context.srcURL : context.linkURL;
|
||||
@@ -292,22 +259,6 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 'linkAt': {
|
||||
// A middle-click on a link opens it in a new tab. The isolated world keeps page scripts from changing the answer.
|
||||
if (![args.x, args.y].every(value => Number.isInteger(value) && value >= 0 && value <= 5120)) throw new Error('Invalid pointer position.');
|
||||
const href = await tab(args.tabId).view.webContents.executeJavaScriptInIsolatedWorld(902, [{
|
||||
code: `document.elementFromPoint(${args.x}, ${args.y})?.closest('a[href], area[href]')?.href ?? ''`,
|
||||
}]).catch(() => '');
|
||||
try { return { url: href ? webUrl(href, { blank: false }) : null }; } catch { return { url: null }; }
|
||||
}
|
||||
case 'copiedImage': {
|
||||
// A part stays below the line limit of the host connection.
|
||||
if (!copied || copied.token !== args.token || copied.tabId !== args.tabId || !Number.isSafeInteger(args.offset) || args.offset < 0 || args.offset >= copied.data.length) {
|
||||
throw new Error('The copied image is no longer available.');
|
||||
}
|
||||
const end = Math.min(copied.data.length, args.offset + COPIED_PART);
|
||||
return { data: copied.data.subarray(args.offset, end).toString('base64'), next: end < copied.data.length ? end : null };
|
||||
}
|
||||
case 'input': {
|
||||
const current = tab(args.tabId), wc = current.view.webContents;
|
||||
const input = args.input;
|
||||
|
||||
@@ -124,64 +124,6 @@ app.whenReady().then(async () => {
|
||||
await assert.rejects(engine.command('contextAction', { tabId: first, token: 'expired', action: 'saveImage' }), /no longer available/);
|
||||
await wc.executeJavaScript('document.querySelector("#save-image").remove();true;');
|
||||
passed.push('Unicode text, native image context menus, saved image bytes and stale menu protection work');
|
||||
// Copy image keeps the bytes that the page loaded. The test server gives this GIF only one time.
|
||||
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<img id="copy-image" src="${process.env.RS_TEST_URL}once.gif" style="position:absolute;left:400px;top:40px;width:80px;height:80px">');true;`);
|
||||
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete'));
|
||||
const menus = events.length;
|
||||
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 440, y: 80, button: 'right' } });
|
||||
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 440, y: 80, button: 'right' } });
|
||||
await until(() => events.slice(menus).some(event => event.event === 'context-menu' && event.hasImageContents));
|
||||
const imageMenu = events.findLast(event => event.event === 'context-menu');
|
||||
const { copied } = await engine.command('contextAction', { tabId: first, token: imageMenu.token, action: 'copyImage' });
|
||||
assert.deepEqual([copied.url, copied.mime, copied.size], [`${process.env.RS_TEST_URL}once.gif`, 'image/gif', 85]);
|
||||
const part = await engine.command('copiedImage', { tabId: first, token: copied.token, offset: 0 });
|
||||
const bytes = Buffer.from(part.data, 'base64');
|
||||
assert.equal(bytes.subarray(0, 6).toString(), 'GIF89a');
|
||||
assert.equal(bytes.length, 85);
|
||||
assert.equal(part.next, null);
|
||||
await assert.rejects(engine.command('copiedImage', { tabId: first, token: copied.token, offset: 85 }), /no longer available/);
|
||||
await assert.rejects(engine.command('copiedImage', { tabId: 'other', token: copied.token, offset: 0 }), /no longer available/);
|
||||
// A large image comes in parts that stay below the line limit of the host.
|
||||
await wc.executeJavaScript(`document.querySelector("#copy-image").src = "${process.env.RS_TEST_URL}large.gif";true;`);
|
||||
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete && document.querySelector("#copy-image").naturalWidth === 1'));
|
||||
const largeMenus = events.length;
|
||||
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 440, y: 80, button: 'right' } });
|
||||
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 440, y: 80, button: 'right' } });
|
||||
await until(() => events.slice(largeMenus).some(event => event.event === 'context-menu' && event.hasImageContents));
|
||||
const large = (await engine.command('contextAction', { tabId: first, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
|
||||
const parts = [];
|
||||
for (let offset = 0; offset !== null;) {
|
||||
const next = await engine.command('copiedImage', { tabId: first, token: large.token, offset });
|
||||
assert.ok(next.data.length <= 4_000_000);
|
||||
parts.push(Buffer.from(next.data, 'base64')); offset = next.next;
|
||||
}
|
||||
const whole = Buffer.concat(parts);
|
||||
assert.ok(parts.length >= 3);
|
||||
assert.equal(whole.length, large.size);
|
||||
assert.equal(whole.subarray(0, 6).toString(), 'GIF89a');
|
||||
assert.equal(whole.at(-1), 0x3b);
|
||||
await wc.executeJavaScript('document.querySelector("#copy-image").remove();true;');
|
||||
// A middle-click asks for the link under the pointer. Only web links count.
|
||||
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<a id="middle-link" href="${process.env.RS_TEST_URL}linked" style="position:absolute;left:600px;top:40px;width:120px;height:30px;display:block">Linked</a><a id="script-link" href="javascript:void(0)" style="position:absolute;left:600px;top:100px;width:120px;height:30px;display:block">Script</a>');true;`);
|
||||
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 650, y: 50 }), { url: `${process.env.RS_TEST_URL}linked` });
|
||||
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 650, y: 110 }), { url: null });
|
||||
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 900, y: 600 }), { url: null });
|
||||
await assert.rejects(engine.command('linkAt', { tabId: first, x: -1, y: 50 }), /Invalid pointer position/);
|
||||
await wc.executeJavaScript('document.querySelector("#middle-link").remove(); document.querySelector("#script-link").remove();true;');
|
||||
// An image that opens as the page itself is the main resource of the tab.
|
||||
const direct = (await engine.command('newTab', { url: `${process.env.RS_TEST_URL}direct.gif` })).tabId;
|
||||
const directContents = engine.tabs.get(direct).view.webContents;
|
||||
await until(async () => await directContents.executeJavaScript('document.images[0]?.complete === true').catch(() => false));
|
||||
const box = await directContents.executeJavaScript('(({ x, y, width, height }) => ({ x: Math.floor(x + width / 2), y: Math.floor(y + height / 2) }))(document.images[0].getBoundingClientRect())');
|
||||
const directMenus = events.length;
|
||||
await engine.command('input', { tabId: direct, input: { type: 'mouseDown', ...box, button: 'right' } });
|
||||
await engine.command('input', { tabId: direct, input: { type: 'mouseUp', ...box, button: 'right' } });
|
||||
await until(() => events.slice(directMenus).some(event => event.event === 'context-menu' && event.tabId === direct && event.hasImageContents));
|
||||
const directCopy = (await engine.command('contextAction', { tabId: direct, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
|
||||
assert.deepEqual([directCopy.mime, directCopy.size], ['image/gif', large.size]);
|
||||
await engine.command('closeTab', { tabId: direct });
|
||||
passed.push('Copy image keeps the loaded GIF bytes without a second request, also for an image that opens as the page');
|
||||
passed.push('A middle-click finds the web link under the pointer');
|
||||
await until(async () => await wc.executeJavaScript("getComputedStyle(document.querySelector('.advertisement')).display") === 'none');
|
||||
assert.equal(await wc.executeJavaScript('typeof window.adExecuted'), 'undefined');
|
||||
passed.push('network and cosmetic ad blocking remain active');
|
||||
|
||||
@@ -6,8 +6,7 @@ app.setPath('userData', process.env.RS_INTERACTION_ROOT);
|
||||
app.on('window-all-closed', () => {});
|
||||
app.whenReady().then(async () => {
|
||||
let framePending = false;
|
||||
// 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 => {
|
||||
const engine = await createEngine({ directory: process.env.RS_INTERACTION_ROOT, canEmitFrame: () => !framePending, emit: value => {
|
||||
if (value.event === 'frame') framePending = true;
|
||||
process.send?.({ event: value }, () => { if (value.event === 'frame') framePending = false; });
|
||||
} });
|
||||
|
||||
+2
-2
@@ -37,7 +37,7 @@ Output:
|
||||
The script prints `Installer available: <path>` when it completes.
|
||||
After a successful build, the version fields keep the new version.
|
||||
|
||||
Example, from the 1.0.0 download link in the README: version `1.0.0` gives `releases/1.0.0/RuneStone_1.0.0_x64-setup.exe`.
|
||||
Example, from the 0.1.44 download link in the README: version `0.1.44` gives `releases/0.1.44/RuneStone_0.1.44_x64-setup.exe`.
|
||||
|
||||
### What the script does
|
||||
|
||||
@@ -229,7 +229,7 @@ Procedure, in the RuneStone repository root. The commands use the Tauri CLI from
|
||||
|
||||
If the build fails, restore the previous version fields.
|
||||
|
||||
Example, from `productName` and `version` in `src-tauri/tauri.conf.json`: the x86_64 Debian build of version `1.0.0` is `RuneStone_1.0.0_amd64.deb`.
|
||||
Example, from the 0.1.44 download link in the README: the x86_64 Debian build of version `0.1.44` is `RuneStone_0.1.44_amd64.deb`.
|
||||
|
||||
`pnpm build:installer` does not build Linux packages. It stops on operating systems other than Windows.
|
||||
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.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
313f15e68c3b3a6eec9fb223548c9843e6e87af5566885088ddbf7434742e100 RuneStone_0.1.44_amd64.deb
|
||||
@@ -1 +0,0 @@
|
||||
66d20b7321e1cdfb001e606d2cff2e174589e70eaf736edb6fbbf655e5591876 RuneStone_1.0.0_x64-setup.exe
|
||||
+1
-1
@@ -114,4 +114,4 @@ Abort stops the display at once. A blocked network read can continue until the r
|
||||
Plugins keep full application access. This API does not add a permission sandbox.
|
||||
The API does not include context sources, remote model servers, or credential storage.
|
||||
|
||||
For tests, see `tests/unit/plugins/completion.spec.ts`.
|
||||
For 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).
|
||||
|
||||
@@ -830,7 +830,6 @@ 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).
|
||||
- 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).
|
||||
- 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.
|
||||
|
||||
### UI-044 — Core palettes and the lightest page
|
||||
@@ -955,7 +954,7 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
|
||||
- Scope: The main header, the side pane, the left ribbon, the tab bars, the Settings and Browser window title bars, and the window builders of the host.
|
||||
- Shared implementation: `WorkbenchHeader.svelte`, `LeftPane.svelte`, `PluginRibbon.svelte`, `TabBar.svelte`, `WindowControls.svelte`, `src-tauri/src/window_frame.rs`, `src-tauri/tauri.macos.conf.json`, and the `--rs-titlebar-inset-start` token.
|
||||
- Evidence: `tests/smoke/layout/titleBar.smoke.mjs` and the Rust command list test.
|
||||
- Replaces / replaced by: The left pane footer, and the ribbon rule "The ribbon has no width when it has no entries." [UI-062](#ui-062--tabs-use-the-free-header-space) replaces the drag area rule.
|
||||
- Replaces / replaced by: The left pane footer, and the ribbon rule "The ribbon has no width when it has no entries."
|
||||
- Limits: Browser checks use desktop service mocks. Snap Layouts, the native drag area, and the macOS title bar need native acceptance. The macOS code path was not compiled here. On Windows 10, Win+Z does nothing.
|
||||
|
||||
### UI-051 — Check marks, focus rings, and control states
|
||||
@@ -1107,68 +1106,3 @@ 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.
|
||||
- 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.
|
||||
|
||||
### 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 right or bottom part of a pane opens a new pane there. A hint shows the place of the drop.
|
||||
- Reason: "Split" named two different things. Users compare a note with a different note, with a web page, or with a PDF file. Equal pane sizes did not fit a web page or a PDF page beside a note.
|
||||
- Scope: Document panes, plugin editor tabs, the tab menu, the tab bar, the file tree menu, and the view control.
|
||||
- Shared implementation: `src/lib/workspace/documentPanes.ts`, `src/lib/workspace/splitLayout.ts` (`stackLayout`, `splitSibling`, `splitDividers`, `setSplitRatio`), `src/lib/layout/DocumentArea.svelte`, `src/lib/layout/TabBar.svelte` (`onDragAt`, `onDropAt`), and `src/lib/layout/Workbench.svelte`. A plugin view stays in the plugin layer above the panes, so a move between panes does not mount it again.
|
||||
- Exceptions: In the menu of a browser tab, **New tab to the right** and **New tab below** open a new browser tab with the home page in a pane beside the tab. These items replace **Split right** and **Split down**, which opened a copy of the page in a split of plugin views only. The separate browser window keeps its own plugin split.
|
||||
- Narrow layout: An area of 640 pixels or less shows the panes one above the other, in the same order and with the same ratios. The area does not scroll. Each pane keeps its own scroll bar. A tab drop opens a new pane only below.
|
||||
- Evidence: `tests/smoke/layout/mixedSplits.smoke.mjs`, `tests/smoke/layout/pdfBesideNote.smoke.mjs`, `tests/smoke/layout/splits.smoke.mjs`, and `tests/unit/layout/documentPanes.spec.ts`.
|
||||
- Replaces / replaced by: The document-only panes of [UI-021](#ui-021--workspace-links-in-document-panes), and the name **Split** of [UI-049](#ui-049--one-view-control-and-one-file-name).
|
||||
- Limits: A tab from a different window opens in the tab bar, not in a pane. Browser checks use desktop service mocks. Native desktop acceptance remains open.
|
||||
|
||||
+1
-3
@@ -16,7 +16,7 @@ This guide is for developers who change RuneStone's source code. To use the app,
|
||||
|
||||
### First run
|
||||
|
||||
1. Clone the repository: `https://github.com/kwyvern-gh/RuneStone.git`.
|
||||
1. Clone the repository: `https://git.knottywyvern.com/kwyvern/RuneStone`.
|
||||
2. In the repository folder, run `pnpm install --frozen-lockfile`.
|
||||
3. Prepare the browser runtime. See [Built-in browser runtime](#built-in-browser-runtime).
|
||||
4. Run `pnpm tauri dev`.
|
||||
@@ -232,8 +232,6 @@ Git, Background, Terminal, PDF Viewer, and Project Management are native feature
|
||||
- `pdfjs-dist` is a host dependency. `src/lib/features/pdf/engine.ts` loads the minified build. The worker, the character maps, the standard fonts, and the image decoders are Vite assets of the app, so PDF.js makes no network request. `build.assetsInlineLimit` in `vite.config.js` keeps these files out of the code.
|
||||
- Project Management has one editor view, `planning`, with `launch: true`. The view pattern `board-<hex of the board ID>` gives each board its own tab. Its ribbon button in `PluginRibbon.svelte` calls the launch, which opens the default board of the workspace or All tasks. It has no command.
|
||||
- Project Management reads and writes only `.runestone/pm/`. `storage/legacy.ts` finds data in the old format of visible notes. The interface then offers the migration, with backups in `.runestone/pm/backups/`. It migrates only after the user chooses it.
|
||||
- Project Management deletes no files. A description draft is `.runestone/pm/drafts/<hex of the card ID>.json`. The data of its unsaved images is in `<hex of the card ID>.images.json` in the same folder. Thus a text change does not write the images again.
|
||||
Only a save of the description or the card writes `.runestone/pm/images/<image ID>.json`. **Save** and **Cancel** of the description replace the draft and its image record with empty records. As a result, a discarded draft leaves no image file.
|
||||
- `pm/storage/` and `pm/model/` stay pure TypeScript without host modules, so the `runestone-project-management` skill can bundle them. They mark their user-visible text with `message()` from `storage/message.ts` and keep it in English. The interface translates that text with `localize()` in `pm/ui/text.ts`.
|
||||
- The `projectManagement` section holds the priority levels (`pmSettings.ts`). The default board is `defaultBoardId` in `.runestone/pm/workspace.json`, so each workspace has its own. Appearance → Background reads the board list from the same file through `pmBoards.ts`, without the feature code.
|
||||
- The first start makes the `projectManagement` section from the kept settings of the Project Management plugin. When `localStorage` has no view states, it also copies the view states of the plugin.
|
||||
|
||||
@@ -10,8 +10,6 @@ This guide explains how to insert and edit images, read diagrams, edit Markdown
|
||||
| --- | --- |
|
||||
| Drag an image from the navigator into a Markdown editor | RuneStone inserts a relative link to the existing file. Press Escape to cancel the drag. |
|
||||
| Drop an image from your system file manager, or paste an image | RuneStone copies the image into the workspace `attachments/` folder with a unique name, then inserts a link. |
|
||||
| Paste an image that you copied with **Copy image** in the RuneStone browser | RuneStone saves the original file that the page loaded. A GIF keeps its animation, also from a website that refuses downloads. |
|
||||
| Paste a GIF, WebP, or AVIF image that you copied in another web browser | That browser copies only the first frame. RuneStone downloads the original file from the image address, so the animation stays. If the website refuses the download, RuneStone saves the first frame and shows a message. |
|
||||
|
||||
Undo removes the inserted link. It keeps the image file.
|
||||
|
||||
@@ -24,11 +22,11 @@ Select an image, then right-click it or press Shift+F10 for these actions:
|
||||
- **Copy path** and **Show in Explorer**, for workspace images
|
||||
|
||||
**Remove image**, or the Delete key, removes the image link from the note. It does not delete the file. Undo restores the link.
|
||||
Zoom works in Write, Read, and Read beside. It can fit the image or magnify it. Press Escape to close it.
|
||||
Zoom works in Write, Read, and Split. It can fit the image or magnify it. Press Escape to close it.
|
||||
|
||||
## Read diagrams and document properties
|
||||
|
||||
Write, Read, and Read beside show wiki links, note callouts, and Mermaid diagrams.
|
||||
Write, Read, and Split show wiki links, note callouts, and Mermaid diagrams.
|
||||
RuneStone renders Mermaid diagrams locally. If a diagram is not valid, RuneStone shows an error message and the diagram source.
|
||||
Read shows frontmatter in a collapsed **Properties** section.
|
||||
|
||||
@@ -97,7 +95,7 @@ Start a cell with `=` to make a formula. Columns use letters A, B, … AA. Row 1
|
||||
| Functions | SUM, AVERAGE, MIN, MAX, COUNT, ABS, and ROUND |
|
||||
|
||||
Functions that take a range ignore text and blank cells. Arithmetic uses zero for a blank cell.
|
||||
Results update in Write, Read, and Read beside. Select a result to edit its formula. Enter saves the formula, and Tab moves to the next cell.
|
||||
Results update in Write, Read, and Split. Select a result to edit its formula. Enter saves the formula, and Tab moves to the next cell.
|
||||
The **Formulas** control below each table explains the syntax. The active cell shows its address.
|
||||
A formula that is not valid, a missing cell, or a circular reference shows an error label.
|
||||
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ Git is part of RuneStone and is on by default. It needs the `git` program on the
|
||||
3. Select a file to open its diff in an editor tab. **Open file** in that tab opens the file in the editor.
|
||||
4. Select the plus button beside a file to stage it, or the minus button to unstage it. The button beside a group stages or unstages all files in that group.
|
||||
|
||||
Source control shows the current branch and the **Changes** section with two groups. **Staged changes** go into the next commit. **Unstaged changes** holds the files that still need review or staging.
|
||||
Source control shows the current branch and two groups. **Staged changes** go into the next commit. **Changes** holds the files that still need review or staging.
|
||||
A file shows in both groups when only part of its content is staged. Unstage keeps the content of the working file.
|
||||
|
||||
Source control reads the repository again after each change in the workspace, also in the `.git` folder, and when the window gets focus. **Refresh source control** reads it at once.
|
||||
|
||||
@@ -52,7 +52,6 @@ A card can be on more than one board, with a different list on each board.
|
||||
|
||||
The card details have the title, the labels, and the description in Markdown.
|
||||
A change to the description stays a draft until you select **Save**. **Cancel** restores the saved text. When you close the card with a draft, the card shows an unsaved marker.
|
||||
An image that you paste or drop into a draft stays with the draft. **Save** adds the image to the card. **Cancel** removes it.
|
||||
Board and list changes save at once. Other fields save when you close the card details.
|
||||
|
||||
### Card details
|
||||
@@ -117,12 +116,6 @@ To add an image to a card, paste it or drop it into the description, or select *
|
||||
Use a PNG, JPEG, GIF, or WebP image of at most 50 MiB.
|
||||
To show an image on the board, add **Card cover** and choose one of the images of the card.
|
||||
|
||||
A web browser copies only the first frame of an image. When you paste a GIF or WebP image from a browser, RuneStone downloads the original file.
|
||||
Then the animation stays.
|
||||
|
||||
Some websites refuse that download. Then the card gets the first frame, and RuneStone shows a message.
|
||||
To keep the animation, use **Copy image** in the RuneStone browser. That copy keeps the original file that the page loaded.
|
||||
|
||||
**More actions** → **Customize background** sets an image behind the open board, or behind All tasks.
|
||||
To show the Background slideshow on the boards, see [Choose where the background shows](themes.md#choose-where-the-background-shows).
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ Each named theme has its own fonts and syntax colors. Fonts come from your compu
|
||||
## Adjust transparency
|
||||
|
||||
**Transparent surfaces** tints work areas with a [background](#show-a-background) and compatible plugin surfaces.
|
||||
Without a background image, menus are opaque. With an image, menus use the same transparency as other surfaces and blur the image.
|
||||
Menus stay opaque. With a background image, menus are at least 92% opaque and blur the image.
|
||||
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.
|
||||
|
||||
|
||||
+34
-32
@@ -2,32 +2,23 @@
|
||||
|
||||
[RuneStone](../README.md) · [User guide](user-guide.md)
|
||||
|
||||
This guide installs, updates, or reinstalls RuneStone from a release file or from a package that you build.
|
||||
This guide installs, updates, or reinstalls RuneStone from a supplied release file.
|
||||
|
||||
| Platform | Release file | Notes |
|
||||
| --- | --- | --- |
|
||||
| Windows 10 or 11, x64 | [RuneStone_1.0.0_x64-setup.exe](https://github.com/kwyvern-gh/RuneStone/releases/download/v1.0.0/RuneStone_1.0.0_x64-setup.exe) | Installs for the current Windows account |
|
||||
| macOS, Apple silicon | None | Build the app from source. See [macOS packages](builds.md#macos-packages). Intel Macs are not supported. |
|
||||
| Linux, amd64 | None | Build a Debian package from source. See [Build Linux packages](builds.md#build-linux-packages). |
|
||||
| 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 |
|
||||
| macOS, Apple silicon | [RuneStone_0.1.44_aarch64.dmg](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_aarch64.dmg) | Experimental. Intel Macs are not supported. |
|
||||
| Linux, amd64 | [RuneStone_0.1.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. |
|
||||
|
||||
On Windows, you do not need Node.js, Rust, or a source checkout.
|
||||
The built-in browser needs a separate engine download. See [Use the built-in browser](user-guide.md#use-the-built-in-browser).
|
||||
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).
|
||||
|
||||
## Install on Windows
|
||||
|
||||
1. Save `RuneStone_1.0.0_x64-setup.exe` and [windows-SHA256SUMS](https://github.com/kwyvern-gh/RuneStone/raw/master/docs/checksums/1.0.0/windows-SHA256SUMS) to Downloads.
|
||||
2. Open PowerShell in Downloads.
|
||||
3. Check the download:
|
||||
|
||||
```powershell
|
||||
$expected = (Get-Content .\windows-SHA256SUMS).Split(' ')[0]
|
||||
(Get-FileHash .\RuneStone_1.0.0_x64-setup.exe).Hash -eq $expected
|
||||
```
|
||||
|
||||
If the result is not `True`, delete the file and download it again.
|
||||
4. Open the setup file.
|
||||
5. Complete setup. Keep the default destination unless you need another location.
|
||||
6. Open RuneStone from the Start menu.
|
||||
1. Save `RuneStone_0.1.49_x64-setup.exe` to Downloads.
|
||||
2. Open the file.
|
||||
3. Complete setup. Keep the default destination unless you need another location.
|
||||
4. Open RuneStone from the Start menu.
|
||||
|
||||
## Update or reinstall on Windows
|
||||
|
||||
@@ -42,30 +33,41 @@ After an update from 0.1.48 or earlier, a browser tab asks you to download the b
|
||||
|
||||
## Install on macOS
|
||||
|
||||
Build the app on an Apple silicon Mac first. See [macOS packages](builds.md#macos-packages).
|
||||
1. Save `RuneStone_0.1.44_aarch64.dmg` to Downloads.
|
||||
2. Open the disk image.
|
||||
3. Drag RuneStone into Applications.
|
||||
4. Eject the disk image.
|
||||
5. Open RuneStone from Applications.
|
||||
|
||||
1. Copy `RuneStone.app` from `src-tauri/target/release/bundle/macos/` into Applications.
|
||||
2. Open RuneStone from Applications.
|
||||
The app has an ad hoc signature and is not notarized by Apple.
|
||||
If macOS blocks the first launch, open **System Settings → Privacy & Security** and choose **Open Anyway**.
|
||||
|
||||
## Update or reinstall on macOS
|
||||
|
||||
1. Save your documents and quit RuneStone.
|
||||
2. Build the same or a newer version.
|
||||
3. Copy the new `RuneStone.app` into Applications and confirm the replacement.
|
||||
4. Open RuneStone from Applications.
|
||||
2. Open the disk image for the same or a newer version.
|
||||
3. Drag RuneStone into Applications and confirm the replacement.
|
||||
4. Eject the disk image.
|
||||
5. Open RuneStone from Applications.
|
||||
|
||||
## Install on Linux
|
||||
|
||||
Build the Debian package first. See [Build Linux packages](builds.md#build-linux-packages).
|
||||
|
||||
1. Open Terminal in the folder that contains the package.
|
||||
2. Install the package. Use the file name of your build:
|
||||
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.
|
||||
2. Open Terminal in Downloads.
|
||||
3. Check the download:
|
||||
|
||||
```bash
|
||||
sudo apt install ./RuneStone_1.0.0_amd64.deb
|
||||
sha256sum --check linux-SHA256SUMS
|
||||
```
|
||||
|
||||
3. Open RuneStone from your applications menu, or run `runestone` in Terminal.
|
||||
If the result is not `OK`, delete the file and download it again.
|
||||
4. Install the package:
|
||||
|
||||
```bash
|
||||
sudo apt install ./RuneStone_0.1.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.
|
||||
|
||||
@@ -75,4 +77,4 @@ APT installs the system libraries that the package declares. Run RuneStone as yo
|
||||
2. Open Terminal in the folder that contains the new package.
|
||||
3. Install the newer package with the same `sudo apt install ./<file>.deb` command.
|
||||
|
||||
To reinstall the same version, run `sudo apt install --reinstall ./<file>.deb`.
|
||||
To reinstall the same version, run `sudo apt install --reinstall ./RuneStone_0.1.44_amd64.deb`.
|
||||
|
||||
@@ -20,7 +20,7 @@ The plugin SDK `@runestone/plugin-sdk` gives the API types, the feature checks,
|
||||
Install it in each plugin project from the URL of its package file on the RuneStone releases page.
|
||||
|
||||
```sh
|
||||
pnpm add -D "https://github.com/kwyvern-gh/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
||||
pnpm add -D "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
||||
```
|
||||
|
||||
- Always give the full URL. The SDK is not on the npm registry, and another account owns the `@runestone` scope there.
|
||||
@@ -146,7 +146,7 @@ For the RuneStone source setup, see [Run from source](development.md#run-from-so
|
||||
|
||||
### Example: CSV Viewer
|
||||
|
||||
Source: the CSV Viewer repository, a private repository: its `package.json`, `plugin.json`, `scripts/build.mjs`, and `README.md`.
|
||||
Source: [CSV Viewer repository](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer), its `package.json`, `plugin.json`, `scripts/build.mjs`, and `README.md`.
|
||||
|
||||
| Item | Value |
|
||||
| --- | --- |
|
||||
|
||||
+8
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
[RuneStone](../README.md) · [User guide](user-guide.md)
|
||||
|
||||
This guide explains how to install, enable, update, and remove optional plugins.
|
||||
This guide explains how to install, enable, update, and remove optional plugins such as CSV Viewer and Local Autocomplete.
|
||||
|
||||
Manage all plugins in **Settings → Plug-ins**. The built-in browser, table formulas, Git, Background, Terminal, PDF Viewer, and Project Management are not plugins. To turn Git, Background, Terminal, PDF Viewer, or Project Management off, see [Turn features on or off](user-guide.md#turn-features-on-or-off).
|
||||
|
||||
@@ -71,6 +71,13 @@ To install a prerelease, enter its tag. The release must have exactly one plugin
|
||||
Use HTTPS for a remote server. HTTP sends the token and the package without encryption.
|
||||
RuneStone uses the token for this request only and does not save it.
|
||||
|
||||
## Plugin guides
|
||||
|
||||
| Plugin | Guide |
|
||||
| --- | --- |
|
||||
| Local Autocomplete | [Local Autocomplete trial guide](https://git.knottywyvern.com/kwyvern/RuneStone_LocalModel/src/branch/main/docs/trial-guide.md) |
|
||||
| CSV Viewer | [CSV Viewer README](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer/src/branch/main/README.md) |
|
||||
|
||||
## Plugin help
|
||||
|
||||
| Problem | Action |
|
||||
|
||||
+2
-2
@@ -88,7 +88,7 @@ The installer, engine, and SDK scripts stop if the release file exists. The plug
|
||||
|
||||
## Publish an installer
|
||||
|
||||
Publish RuneStone installers on the [RuneStone releases page](https://github.com/kwyvern-gh/RuneStone/releases). Browser engine ZIPs and SDK packages use the same page.
|
||||
Publish RuneStone installers on the [RuneStone releases page](https://git.knottywyvern.com/kwyvern/RuneStone/releases). Browser engine ZIPs and SDK packages use the same page.
|
||||
|
||||
1. Build the installer and complete the [installer checks](builds.md#installer-checks).
|
||||
2. Create a release with the tag `v<version>` on the commit that sets the version.
|
||||
@@ -181,7 +181,7 @@ Plugin authors install the SDK from the URL of that file. See [Install the SDK](
|
||||
|
||||
1. Commit the SDK changes in RuneStone. Run `pnpm check` and `pnpm test`.
|
||||
2. Run `pnpm release:sdk --release-url <folder URL> --version <version> --dry-run`. Read the plan.
|
||||
The folder URL is the download folder of the release, for example `https://github.com/kwyvern-gh/RuneStone/releases/download/plugin-sdk-v0.1.2`.
|
||||
The folder URL is the download folder of the release, for example `https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2`.
|
||||
3. Run the same command without `--dry-run`.
|
||||
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.
|
||||
|
||||
+6
-8
@@ -52,8 +52,7 @@ Do not copy feature-specific colors into a shared control.
|
||||
| `--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-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: 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-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-backdrop` | `none` | With a background image: `blur(18px) saturate(1.2)` |
|
||||
| `--rs-surface-opacity` | 82% | Shared surface tint. Appearance settings adjust it. |
|
||||
|
||||
@@ -101,7 +100,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.
|
||||
- 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.
|
||||
- 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.
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
@@ -143,14 +142,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.
|
||||
- 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), [UI-061](design-decisions.md#ui-061--translucent-menus-and-hover-fills-over-images).
|
||||
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).
|
||||
|
||||
## 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.
|
||||
- A bar at the bottom of the side pane holds the workspace switcher, Help, and Settings, as in Obsidian. The switcher names the workspace and opens the workspace list above it.
|
||||
- The left ribbon is always present. It holds the tools, then a line, then the plugin view shortcuts. The tools are New browser tab, Terminal, Project Management, Plug-in views, and Commands. A tool of an off feature does not show. Its menus open at its right. While the side pane is closed, the workspace switcher, Help, and Settings move to the bottom of the ribbon, so they stay reachable.
|
||||
- Tabs keep a minimum width of 120 pixels and scroll. Fades show tabs out of view, and ⌄ lists all tabs. A drag area after the tabs fills the free space of the header. The tabs use all space up to a drag area of 48 pixels before they scroll ([UI-062](design-decisions.md#ui-062--tabs-use-the-free-header-space)).
|
||||
- Tabs keep a minimum width of 120 pixels and scroll. Fades show tabs out of view, and ⌄ lists all tabs. A drag area of 120 pixels sits after the tabs. In a narrow header, the tabs shrink first, and the drag area keeps at least 48 pixels.
|
||||
- Windows and Linux title bars use square caption buttons, 46 pixels wide and full height. Rest the pointer on maximize for Snap Layouts on Windows 11. macOS keeps its native traffic lights, and title bars leave `--rs-titlebar-inset-start` free for them.
|
||||
- Files, Search, Bookmarks, Source control (while Git is on), and the sidebar views of installed plugins share the top navigation group. The active navigation button shows which view fills the left pane.
|
||||
- Plugin editor views can use the left ribbon.
|
||||
@@ -222,16 +221,15 @@ Decisions: [UI-009](design-decisions.md#ui-009--character-theme-appearances), [U
|
||||
|
||||
- The app image fills the work area below the titlebar, including new tabs and document views. It stays fixed while content scrolls.
|
||||
- Sidebars use `--rs-image-sidebar-bg` (82% tint). Editor surfaces use `--rs-image-editor-bg` (90% tint). Without an image, both are opaque.
|
||||
- Write, Source, Read, and Read beside share the editor surface. CodeMirror layers stay transparent above it.
|
||||
- Write, Source, Read, and Split share the editor surface. CodeMirror layers stay transparent above it.
|
||||
- Code blocks in Write and Read use `--rs-code-block-bg`.
|
||||
- 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.
|
||||
- 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 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.
|
||||
|
||||
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).
|
||||
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).
|
||||
|
||||
### Project Management surfaces
|
||||
|
||||
|
||||
+8
-32
@@ -75,14 +75,14 @@ On macOS and Linux, you can still open, edit, rename, and delete existing files
|
||||
|
||||
## Edit documents
|
||||
|
||||
Each document pane has one view control with three choices, and a **Read beside** button:
|
||||
Each document pane has one view control with three choices, and a **Split** button:
|
||||
|
||||
| Choice | Shows |
|
||||
| --- | --- |
|
||||
| **Write** | Formatted Markdown. The active line shows its Markdown source. |
|
||||
| **Source** | The plain source with line numbers and syntax colors |
|
||||
| **Read** | The rendered document, without editing. Markdown files only. |
|
||||
| **Read beside** | Read beside Write or Source. Narrow panes stack the two views. Select **Read beside** again to close it. Markdown files only. |
|
||||
| **Split** | Read beside Write or Source. Narrow panes stack the two views. Select **Split** again to close it. Markdown files only. |
|
||||
|
||||
Press Ctrl+E to switch between Write and Source. Press Ctrl+Shift+E to switch between Read and the editor. The tab menu has the same choices under **View**.
|
||||
The control shows icons only. Hover over an icon, or focus it with the keyboard, to see its name and shortcut. The arrow keys move the choice.
|
||||
@@ -103,9 +103,9 @@ Read follows CommonMark: a single line break inside a paragraph is a space. To s
|
||||
|
||||
- Ctrl+click a link in Write or Source. In Read, a normal click follows the link.
|
||||
- A workspace file link opens in a new tab and keeps the current document open.
|
||||
- A heading link, such as `guide.md#save-your-work` or `#save-your-work`, puts that heading at the top of the view. A heading near the end of a short document stays lower.
|
||||
- A heading link, such as `guide.md#save-your-work` or `#save-your-work`, scrolls to that heading.
|
||||
- A wiki link, such as `[[Meeting notes]]`, finds the note by name anywhere in the workspace. If two notes have the same name, use a relative or workspace path.
|
||||
- The **Backlinks** section below the outline lists notes that link to the current note. Select an entry to open it. Select the **Backlinks** title to collapse or expand the section. RuneStone keeps that choice for all notes and after a restart.
|
||||
- The **Backlinks** section below the outline lists notes that link to the current note. Select an entry to open it.
|
||||
|
||||
If backlinks look out of date, select **Rebuild note index**. Your Markdown files do not depend on this index.
|
||||
|
||||
@@ -136,17 +136,15 @@ Select a PDF file in the file tree. It opens in its own tab. The file tree marks
|
||||
|
||||
| Action | How |
|
||||
| --- | --- |
|
||||
| Scroll through the pages | Use the wheel or the scroll bar. With the page area focused, use Page Up, Page Down, Home, End, and the arrow keys. |
|
||||
| Go to a page | Select **Previous page** or **Next page**. Or type a number in the page field and press Enter. |
|
||||
| Zoom | Select **Zoom in** or **Zoom out**. Or type a percent in the zoom field and press Enter. Or hold Ctrl and turn the wheel. The zoom is from 25% to 400%. **Fit width** fits the pages to the tab again. |
|
||||
| Rotate | Select **Rotate clockwise**. Each click turns the pages by 90 degrees. |
|
||||
| Change the page | Select **Previous page** or **Next page**. Or type a number in the page field and press Enter. With the page area focused, press Page Up or Page Down. |
|
||||
| Zoom | Select **Zoom in** or **Zoom out**, from 25% to 400%. **Fit width** fits the page to the tab again. |
|
||||
| Rotate | Select **Rotate clockwise**. Each click turns the page by 90 degrees. |
|
||||
| Copy text | Select text on the page with the pointer, then press Ctrl+C. |
|
||||
| Show changes from another program | Select **Reload PDF**. The tab stays on the same page. |
|
||||
| Open a protected PDF | Type the password, then select **Unlock**. RuneStone does not save the password. |
|
||||
|
||||
- A PDF file must be in the workspace and at most 64 MiB.
|
||||
- The tab shows 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.
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
@@ -184,24 +182,6 @@ If the move fails, the source tab stays open.
|
||||
When you start RuneStone again, it opens the document tabs of the workspace. It keeps their order, pins, and active tab.
|
||||
This includes PDF tabs and plugin tabs that show a file. RuneStone reads the contents again from disk. Missing files do not stop the other tabs from opening.
|
||||
|
||||
### Show tabs side by side
|
||||
|
||||
Use panes to see two tabs at the same time. For example, browse the web or read a PDF file in one pane, and write a note in the other pane.
|
||||
|
||||
1. Right-click a tab that is not visible, or a file in the file tree.
|
||||
2. Select **Open to the right**.
|
||||
|
||||
The tab opens in a new pane to the right of the active pane. A pane shows a document, a PDF file, or a plugin tab, for example a browser tab. A tab shows in one pane at a time.
|
||||
|
||||
You can also drag a tab from the tab bar to a pane. A drop on the middle of the pane shows the tab in that pane. A drop on the right or bottom part opens a new pane there. A hint shows the place before you release the tab.
|
||||
|
||||
- Click a pane to make its tab the active tab. A tab that you select, or a file that you open, replaces the content of the active pane. The replaced tab stays open.
|
||||
- Drag the divider between two panes to change their sizes. Double-click the divider to give the panes equal sizes. With the keyboard, focus the divider and use the arrow keys.
|
||||
- A pane beside other panes names its file in the bar above the document. Select **Close split** in that bar to close the pane. The tab stays open.
|
||||
- A browser tab or a PDF tab that fills the area moves to the left pane when a tab opens to the right. When one pane is left, its tab fills the area again.
|
||||
- In the menu of a browser tab, **New tab to the right** and **New tab below** open a new browser tab with the home page in a pane beside it.
|
||||
- The link menu also has **Open to the right**. In a narrow window, the panes show one above the other.
|
||||
|
||||
## Save your work
|
||||
|
||||
Auto-save is on by default. It saves changed files every 5 seconds, also in background tabs. RuneStone does not write unchanged files.
|
||||
@@ -282,10 +262,6 @@ If a download fails, the tab shows the cause. Select **Retry** to start the down
|
||||
Until the engine is installed, web links in your documents open in your system browser.
|
||||
After a RuneStone update that needs a new engine, a browser tab offers **Update the engine**.
|
||||
|
||||
In a page, middle-click a link to open it in a new tab. Middle-click other content to scroll, then move the pointer in the direction to scroll.
|
||||
Right-click an image for **Open image in new tab**, **Save image as…**, **Copy image**, and **Copy image address**.
|
||||
**Copy image** keeps the original file. A GIF that you paste into a document or a card keeps its animation.
|
||||
|
||||
Use **Settings → Browser** to set the homepage and search engine, manage profiles, block ads, and clear cookies, cache, or history.
|
||||
**Settings → Browser → Browser engine** shows the installed version. **Remove engine** frees the disk space. Your profiles, bookmarks, and history stay.
|
||||
Each profile keeps its own cookies and bookmarks. Web bookmarks show in the Bookmarks pane.
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "runestone",
|
||||
"version": "1.0.1c",
|
||||
"version": "0.1.51",
|
||||
"description": "Desktop editor for a local workspace",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -25,7 +25,7 @@
|
||||
"sdk:build": "node scripts/buildSdk.mjs",
|
||||
"release:sdk": "node scripts/releaseSdk.mjs"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.20.3",
|
||||
"@codemirror/commands": "^6.11.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# RuneStone Plugin SDK
|
||||
|
||||
`@runestone/plugin-sdk` gives TypeScript types and small helpers for [RuneStone](https://github.com/kwyvern-gh/RuneStone) plugins.
|
||||
`@runestone/plugin-sdk` gives TypeScript types and small helpers for [RuneStone](https://git.knottywyvern.com/kwyvern/RuneStone) plugins.
|
||||
RuneStone is a desktop workspace for Markdown notes, code, and project work. Plugins add views, commands, and document editors to it.
|
||||
|
||||
The SDK contains:
|
||||
@@ -17,7 +17,7 @@ The SDK does not run plugins and does not call RuneStone. RuneStone gives the `a
|
||||
Install the SDK from the URL of its package file on the RuneStone releases page.
|
||||
|
||||
```sh
|
||||
pnpm add -D "https://github.com/kwyvern-gh/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
||||
pnpm add -D "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
||||
```
|
||||
|
||||
The result in `package.json`:
|
||||
@@ -25,7 +25,7 @@ The result in `package.json`:
|
||||
```json
|
||||
{
|
||||
"devDependencies": {
|
||||
"@runestone/plugin-sdk": "https://github.com/kwyvern-gh/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
||||
"@runestone/plugin-sdk": "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -60,7 +60,7 @@ export function activate(api: PluginApi) {
|
||||
```
|
||||
|
||||
Compile the module with a bundler, so the entry file contains the SDK helpers that it uses. RuneStone loads the entry from a Blob URL, so imports from `node_modules` do not resolve at run time.
|
||||
Then make the plugin ZIP. See [Build and package a plugin](https://github.com/kwyvern-gh/RuneStone/blob/master/docs/plugin-development.md#build-and-package-a-plugin).
|
||||
Then make the plugin ZIP. See [Build and package a plugin](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugin-development.md#build-and-package-a-plugin).
|
||||
|
||||
A type-only import, such as `import type { PluginApi }`, adds no code to the bundle.
|
||||
|
||||
@@ -128,12 +128,12 @@ A new SDK release can add types for new RuneStone features. Use the feature chec
|
||||
|
||||
## Documentation and help
|
||||
|
||||
- [Plugin development reference](https://github.com/kwyvern-gh/RuneStone/blob/master/docs/plugin-development.md): the package format, the API, and the build procedure
|
||||
- [Completion API](https://github.com/kwyvern-gh/RuneStone/blob/master/docs/completion.md)
|
||||
- [Install and manage plugins](https://github.com/kwyvern-gh/RuneStone/blob/master/docs/plugins.md)
|
||||
- [Release policy](https://github.com/kwyvern-gh/RuneStone/blob/master/docs/releases.md#sdk-releases)
|
||||
- [Plugin development reference](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugin-development.md): the package format, the API, and the build procedure
|
||||
- [Completion API](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/completion.md)
|
||||
- [Install and manage plugins](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugins.md)
|
||||
- [Release policy](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/releases.md#sdk-releases)
|
||||
|
||||
The SDK source is in the `packages/plugin-sdk` folder of the [RuneStone repository](https://github.com/kwyvern-gh/RuneStone). Report problems there.
|
||||
The SDK source is in the `packages/plugin-sdk` folder of the [RuneStone repository](https://git.knottywyvern.com/kwyvern/RuneStone). Report problems there.
|
||||
|
||||
Knotty Wyvern maintains RuneStone and the SDK.
|
||||
|
||||
|
||||
Generated
+1
-1
@@ -3130,7 +3130,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "runestone"
|
||||
version = "1.0.1+3"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"dunce",
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
[package]
|
||||
name = "runestone"
|
||||
version = "1.0.1+3"
|
||||
version = "0.1.51"
|
||||
description = "Writing workspace plus script editor"
|
||||
authors = ["Knotty Wyvern"]
|
||||
license = "Apache-2.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
@@ -47,4 +46,4 @@ opt-level = 3
|
||||
strip = true
|
||||
|
||||
[package.metadata.runestone]
|
||||
version = "1.0.1c"
|
||||
version = "0.1.51"
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"version": "0.1.11",
|
||||
"version": "0.1.8",
|
||||
"protocol": 1,
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"url": "https://github.com/kwyvern-gh/RuneStone/releases/download/browser-engine-v0.1.11/RuneStone-Browser_0.1.11_win32-x64.zip",
|
||||
"bytes": 163623801,
|
||||
"sha256": "1e0153b134cebe882b36f74e1f3c2a4ed37acb2caca10548034a8b5d88738d26"
|
||||
"url": "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/browser-engine-v0.1.8/RuneStone-Browser_0.1.8_win32-x64.zip",
|
||||
"bytes": 163632595,
|
||||
"sha256": "d704003bf5fe047b100a3cf0ab84f3321fd272510cf287a229e50d1653d0856b"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,8 +71,6 @@ fn main() {
|
||||
"workspace_delete",
|
||||
"workspace_read_data_url",
|
||||
"workspace_write_bytes",
|
||||
"workspace_save_image_url",
|
||||
"workspace_download_image",
|
||||
"workspace_copy",
|
||||
"workspace_abs_path",
|
||||
"workspace_reveal",
|
||||
|
||||
@@ -69,8 +69,6 @@
|
||||
"allow-workspace-delete",
|
||||
"allow-workspace-read-data-url",
|
||||
"allow-workspace-write-bytes",
|
||||
"allow-workspace-save-image-url",
|
||||
"allow-workspace-download-image",
|
||||
"allow-workspace-copy",
|
||||
"allow-workspace-abs-path",
|
||||
"allow-workspace-reveal",
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
# 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"]
|
||||
@@ -1,11 +0,0 @@
|
||||
# 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"]
|
||||
@@ -34,8 +34,6 @@ const COMMANDS: &[&str] = &[
|
||||
"insertText",
|
||||
"edit",
|
||||
"contextAction",
|
||||
"copiedImage",
|
||||
"linkAt",
|
||||
"frameAck",
|
||||
"createProfile",
|
||||
"renameProfile",
|
||||
@@ -482,7 +480,7 @@ impl BrowserState {
|
||||
let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id }));
|
||||
return Ok(worker.routing.lock()?.snapshot(result, owner));
|
||||
}
|
||||
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "copiedImage", "linkAt", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
|
||||
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
|
||||
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
|
||||
match worker.routing.lock()?.owners.get(id) {
|
||||
Some(window) if window == owner => {},
|
||||
|
||||
@@ -107,8 +107,6 @@ pub fn run() {
|
||||
workspace::workspace_delete,
|
||||
workspace::workspace_read_data_url,
|
||||
workspace::workspace_write_bytes,
|
||||
workspace::workspace_save_image_url,
|
||||
workspace::workspace_download_image,
|
||||
workspace::workspace_copy,
|
||||
workspace::workspace_abs_path,
|
||||
workspace::workspace_reveal,
|
||||
|
||||
+2
-152
@@ -967,14 +967,10 @@ fn read_data_url(root: &Path, rel: &str) -> Result<String> {
|
||||
}
|
||||
let bytes = fsutil::read_to_limit(file, MAX_IMAGE_BYTES as u64)?
|
||||
.ok_or_else(|| Error::new("image is too large"))?;
|
||||
Ok(data_url(mime, &bytes))
|
||||
}
|
||||
|
||||
fn data_url(mime: &str, bytes: &[u8]) -> String {
|
||||
format!(
|
||||
Ok(format!(
|
||||
"data:{mime};base64,{}",
|
||||
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes)
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
fn copy_destination(path: &Path, number: u32) -> PathBuf {
|
||||
@@ -1248,108 +1244,6 @@ fn write_image(root: &Path, rel: &str, base64: &str) -> Result<()> {
|
||||
fsutil::write_bytes(&path, &bytes)
|
||||
}
|
||||
|
||||
/// Save the original of an image that a web page copied. The clipboard has only a still copy,
|
||||
/// so an animated GIF needs its source file. `rel` has no extension. The format of the
|
||||
/// downloaded file sets it. Returns the path of the new file.
|
||||
#[tauri::command]
|
||||
pub async fn workspace_save_image_url(
|
||||
window: tauri::Window,
|
||||
state: State<'_, WorkspaceState>,
|
||||
url: String,
|
||||
rel: String,
|
||||
) -> Result<String> {
|
||||
let root = current_root(&state, window.label())?;
|
||||
blocking(move || {
|
||||
let bytes = download_image(&url)?;
|
||||
save_image(&root, &rel, &bytes)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Download a web image and return it as a data URL. Project Management keeps card images
|
||||
/// as data URLs, so this gives a card the original of a copied image.
|
||||
#[tauri::command]
|
||||
pub async fn workspace_download_image(url: String) -> Result<String> {
|
||||
blocking(move || image_data_url(&download_image(&url)?)).await
|
||||
}
|
||||
|
||||
fn image_data_url(bytes: &[u8]) -> Result<String> {
|
||||
let extension = image_extension(bytes).ok_or_else(|| Error::new("file is not an image"))?;
|
||||
let mime = mime_from_path(Path::new(&format!("image.{extension}")))
|
||||
.ok_or_else(|| Error::new("file is not an image"))?;
|
||||
Ok(data_url(mime, bytes))
|
||||
}
|
||||
|
||||
fn download_image(url: &str) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
let web = |url: &reqwest::Url| matches!(url.scheme(), "http" | "https");
|
||||
let url = reqwest::Url::parse(url).map_err(|_| Error::new("invalid image address"))?;
|
||||
if !web(&url) {
|
||||
return Err(Error::new("image address is not http or https"));
|
||||
}
|
||||
let client = reqwest::blocking::Client::builder()
|
||||
.user_agent(concat!("RuneStone/", env!("CARGO_PKG_VERSION")))
|
||||
.connect_timeout(Duration::from_secs(10))
|
||||
.timeout(Duration::from_secs(30))
|
||||
.redirect(reqwest::redirect::Policy::custom(move |attempt| {
|
||||
if attempt.previous().len() >= 5 || !web(attempt.url()) {
|
||||
attempt.stop()
|
||||
} else {
|
||||
attempt.follow()
|
||||
}
|
||||
}))
|
||||
.build()
|
||||
.map_err(Error::from_display)?;
|
||||
let response = client.get(url).send().map_err(Error::from_display)?;
|
||||
if !response.status().is_success() {
|
||||
return Err(Error::new(format!("image server answered {}", response.status())));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
response.take(MAX_IMAGE_BYTES as u64 + 1).read_to_end(&mut bytes)?;
|
||||
if bytes.len() > MAX_IMAGE_BYTES {
|
||||
return Err(Error::new("image is too large"));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn save_image(root: &Path, rel: &str, bytes: &[u8]) -> Result<String> {
|
||||
let extension = image_extension(bytes).ok_or_else(|| Error::new("file is not an image"))?;
|
||||
let rel = format!("{rel}.{extension}");
|
||||
let path = resolve_for_write(root, &rel)?;
|
||||
check_new_components(root, &rel)?;
|
||||
if path.exists() {
|
||||
return Err(Error::new("a file with that name already exists"));
|
||||
}
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fsutil::write_bytes(&path, bytes)?;
|
||||
Ok(rel)
|
||||
}
|
||||
|
||||
/// The extension of a raster image format from its first bytes. A web server can send a
|
||||
/// wrong type, and an SVG file can contain scripts, so the type header and SVG do not count.
|
||||
fn image_extension(bytes: &[u8]) -> Option<&'static str> {
|
||||
let at = |start: usize, value: &[u8]| bytes.get(start..start + value.len()) == Some(value);
|
||||
if at(0, b"GIF87a") || at(0, b"GIF89a") {
|
||||
Some("gif")
|
||||
} else if at(0, b"\x89PNG\r\n\x1a\n") {
|
||||
Some("png")
|
||||
} else if at(0, b"\xff\xd8\xff") {
|
||||
Some("jpg")
|
||||
} else if at(0, b"RIFF") && at(8, b"WEBP") {
|
||||
Some("webp")
|
||||
} else if at(4, b"ftypavif") || at(4, b"ftypavis") {
|
||||
Some("avif")
|
||||
} else if at(0, b"BM") {
|
||||
Some("bmp")
|
||||
} else if at(0, b"\0\0\x01\0") {
|
||||
Some("ico")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1704,50 +1598,6 @@ mod tests {
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_formats_come_from_the_file_contents() {
|
||||
assert_eq!(image_extension(b"GIF89a\x01\0"), Some("gif"));
|
||||
assert_eq!(image_extension(b"GIF87a"), Some("gif"));
|
||||
assert_eq!(image_extension(b"\x89PNG\r\n\x1a\n\0"), Some("png"));
|
||||
assert_eq!(image_extension(b"\xff\xd8\xff\xe0"), Some("jpg"));
|
||||
assert_eq!(image_extension(b"RIFF\0\0\0\0WEBPVP8 "), Some("webp"));
|
||||
assert_eq!(image_extension(b"\0\0\0\x1cftypavif"), Some("avif"));
|
||||
assert_eq!(image_extension(b"BM\0\0"), Some("bmp"));
|
||||
assert_eq!(image_extension(b"\0\0\x01\0\x01\0"), Some("ico"));
|
||||
assert_eq!(image_extension(b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"), None);
|
||||
assert_eq!(image_extension(b"<!doctype html>"), None);
|
||||
assert_eq!(image_extension(b"RIFF"), None);
|
||||
assert_eq!(image_extension(b""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_images_keep_their_original_format() {
|
||||
let root = workspace_fixture("image-url");
|
||||
let gif = b"GIF89a\x01\0\x01\0\0\0\0;".to_vec();
|
||||
let (base, server) = crate::plugin_sources::tests::server(vec![
|
||||
("302 Found\r\nLocation: /cat.gif".into(), Vec::new()),
|
||||
("200 OK\r\nContent-Type: image/png".into(), gif.clone()),
|
||||
("200 OK\r\nContent-Type: image/gif".into(), b"<!doctype html>".to_vec()),
|
||||
("404 Not Found".into(), Vec::new()),
|
||||
]);
|
||||
let bytes = download_image(&format!("{base}/image")).unwrap();
|
||||
assert_eq!(save_image(&root, "attachments/pasted", &bytes).unwrap(), "attachments/pasted.gif");
|
||||
assert_eq!(fs::read(root.join("attachments/pasted.gif")).unwrap(), gif);
|
||||
assert_eq!(image_data_url(&bytes).unwrap(), "data:image/gif;base64,R0lGODlhAQABAAAAADs=");
|
||||
let page = download_image(&format!("{base}/page")).unwrap();
|
||||
assert_eq!(save_image(&root, "attachments/page", &page).unwrap_err().to_string(), "file is not an image");
|
||||
assert_eq!(image_data_url(&page).unwrap_err().to_string(), "file is not an image");
|
||||
assert_eq!(image_data_url(b"\xff\xd8\xff\xe0").unwrap(), "data:image/jpeg;base64,/9j/4A==");
|
||||
assert!(download_image(&format!("{base}/missing")).unwrap_err().to_string().contains("404"));
|
||||
let requests = server.join().unwrap();
|
||||
assert!(requests[1].starts_with("GET /cat.gif "));
|
||||
assert!(download_image("file:///C:/cat.gif").is_err());
|
||||
assert!(save_image(&root, "attachments/pasted", &gif).is_err(), "an existing file stays");
|
||||
assert!(save_image(&root, "../outside", &gif).is_err());
|
||||
assert_eq!(names(&root.join("attachments")), ["pasted.gif"]);
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permanent_delete_removes_files_and_folders_but_never_the_root() {
|
||||
let root = workspace_fixture("delete");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "RuneStone",
|
||||
"version": "1.0.1+3",
|
||||
"version": "0.1.51",
|
||||
"identifier": "com.runestone.app",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
{/each}
|
||||
</div>
|
||||
<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-hover-bg)}
|
||||
.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)}
|
||||
.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)}
|
||||
</style>
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
import { TabSession, type TabStatus } from './tabSession';
|
||||
import { engine } from './engine';
|
||||
import { AutoScroll } from './autoScroll';
|
||||
import { keepCopiedImage } from '$lib/workspace/copiedImage';
|
||||
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string, url?: string) => Promise<void> } = $props();
|
||||
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: $t('Opening browser…') });
|
||||
const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); });
|
||||
@@ -44,7 +43,7 @@
|
||||
let scrollAnchor = $state<{ x: number; y: number } | null>(null);
|
||||
let scrollFrame = 0, moveFrame = 0, movePending = false;
|
||||
let pendingMove: Record<string, unknown> | undefined;
|
||||
let suppressedRelease = -1, middlePressed = false;
|
||||
let suppressedRelease = -1;
|
||||
const result = $derived(current?.find?.text === findText ? current.find : null);
|
||||
const documentKey = $derived(`${tabId}:${current?.url}:${!!current?.loading}`);
|
||||
$effect(() => {
|
||||
@@ -117,9 +116,8 @@
|
||||
{ label: $t('Copy link address'), icon: 'copy', run: action('copyLink') },
|
||||
{ label: $t('Save link as…'), icon: 'save', run: action('saveLink') }, { separator: true });
|
||||
if (context.hasImageContents) items.push(
|
||||
{ label: $t('Open image in new tab'), icon: 'file-plus', disabled: !context.srcURL, run: () => void newTab(current?.profileId || 'user', context.srcURL) },
|
||||
{ label: $t('Save image as…'), icon: 'save', disabled: !context.srcURL, run: action('saveImage') },
|
||||
{ label: $t('Copy image'), icon: 'copy', run: () => copyImage(context) },
|
||||
{ label: $t('Copy image'), icon: 'copy', run: action('copyImage') },
|
||||
{ label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
|
||||
if (context.isEditable) items.push(
|
||||
{ label: $t('Undo'), icon: 'undo', shortcut: keys('Mod+Z'), disabled: !context.editFlags.canUndo, run: edit('undo') },
|
||||
@@ -144,23 +142,6 @@
|
||||
if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; });
|
||||
await connection.send(command, args);
|
||||
}
|
||||
// A paste of a copied image uses the bytes that the page loaded. The engine gives them in parts.
|
||||
// A paste can come before the reply, so the copy is known at once by its address.
|
||||
function copyImage(context: PageMenu) {
|
||||
const owner = tabId;
|
||||
const data = (async () => {
|
||||
const reply = await connection.send('contextAction', { token: context.token, action: 'copyImage' }) as { copied?: { token: string; mime: string } } | null | undefined;
|
||||
const copied = reply?.copied;
|
||||
if (!copied) return undefined;
|
||||
let data = '';
|
||||
for (let offset: number | null = 0; offset !== null;) {
|
||||
const part: { data: string; next: number | null } = await request('copiedImage', { tabId: owner, token: copied.token, offset });
|
||||
data += part.data; offset = part.next;
|
||||
}
|
||||
return `data:${copied.mime};base64,${data}`;
|
||||
})().catch(() => undefined);
|
||||
if (context.srcURL) keepCopiedImage(context.srcURL, data);
|
||||
}
|
||||
async function openTab(profileId = current?.profileId || $browserState?.profiles[0]?.id || 'user') {
|
||||
if (opening) return;
|
||||
opening = true;
|
||||
@@ -213,37 +194,23 @@
|
||||
if (mounted && pendingMove) moveFrame = requestAnimationFrame(flushMove);
|
||||
});
|
||||
}
|
||||
// The frame has the CSS size of the page viewport. A surface point less the frame offset is the same page point.
|
||||
function pagePoint(point: { x: number; y: number }) {
|
||||
return { x: Math.max(0, Math.min(width - 1, Math.round(point.x - imageBox.x))), y: Math.max(0, Math.min(height - 1, Math.round(point.y - imageBox.y))) };
|
||||
}
|
||||
// A middle-click starts scrolling at once. On a link, it stops the scroll and opens the link in a new tab.
|
||||
async function openLinkAt(input: { x: number; y: number }) {
|
||||
const owner = tabId;
|
||||
const found = await request<{ url: string | null }>('linkAt', { tabId: owner, ...input }).catch(() => null);
|
||||
if (!found?.url || owner !== tabId || !autoScroll.anchor) return;
|
||||
stopScroll();
|
||||
if (middlePressed) suppressedRelease = 1;
|
||||
void newTab(current?.profileId || 'user', found.url);
|
||||
}
|
||||
function pointer(event: MouseEvent | WheelEvent, type: string) {
|
||||
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') textInput.focus({ preventScroll: true });
|
||||
const rect = surface.getBoundingClientRect();
|
||||
const point = { x: event.clientX - rect.left, y: event.clientY - rect.top };
|
||||
if (event.button === 1) middlePressed = type === 'mouseDown';
|
||||
if (type === 'mouseUp' && event.button === suppressedRelease) { suppressedRelease = -1; return; }
|
||||
if (type === 'mouseDown' && autoScroll.anchor) { suppressedRelease = event.button; stopScroll(); return; }
|
||||
if (type === 'mouseDown' && event.button === 1 && ready) {
|
||||
pendingMove = undefined; cancelAnimationFrame(moveFrame); moveFrame = 0;
|
||||
autoScroll.start(point); scrollAnchor = point; scrollFrame = requestAnimationFrame(scrollStep);
|
||||
void openLinkAt(pagePoint(point)); return;
|
||||
autoScroll.start(point); scrollAnchor = point; scrollFrame = requestAnimationFrame(scrollStep); return;
|
||||
}
|
||||
if (autoScroll.anchor) {
|
||||
if (type === 'mouseMove') autoScroll.move(point);
|
||||
if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); }
|
||||
if (type === 'mouseWheel') stopScroll(); else return;
|
||||
}
|
||||
const input = { type, ...pagePoint(point),
|
||||
// The frame has the CSS size of the page viewport. A surface point less the frame offset is the same page point.
|
||||
const input = { type, x: Math.max(0, Math.min(width - 1, Math.round(point.x - imageBox.x))), y: Math.max(0, Math.min(height - 1, Math.round(point.y - imageBox.y))),
|
||||
button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event),
|
||||
...('deltaY' in event ? { deltaY: -event.deltaY * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? height : 1), deltaX: -event.deltaX * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? width : 1) } : {}) };
|
||||
if (type === 'mouseWheel') { wheels.push(input as Parameters<WheelQueue['push']>[0]); return; }
|
||||
@@ -319,7 +286,7 @@
|
||||
oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
|
||||
onblur={stopScroll}></textarea>
|
||||
{#if image && ready && !blank}<img src={image} class:exact={imageBox.exact} style:width={`${imageBox.width}px`} style:height={`${imageBox.height}px`} style:transform={`translate(${imageBox.x}px, ${imageBox.y}px)`} alt={$t("Web page rendered by the browser")} draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
|
||||
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true"><Icon icon="scroll" /></span>{/if}
|
||||
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
|
||||
</div>
|
||||
</div>
|
||||
<style>
|
||||
@@ -331,7 +298,7 @@
|
||||
input{flex:1}.profile-choice{max-width:160px;display:flex;align-items:center;gap:var(--rs-menu-icon-gap);cursor:pointer}input:focus-visible,.profile-choice:focus-visible{outline:2px solid var(--rs-focus)}
|
||||
.surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)}
|
||||
.browser.blank,.blank .surface{background:transparent}
|
||||
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width: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}
|
||||
.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}
|
||||
img{display:block;pointer-events:none;user-select:none;will-change:transform}img.exact{image-rendering:pixelated}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px}
|
||||
.error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)}
|
||||
.reconnect{padding:6px 12px;margin:4px 0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);cursor:pointer}
|
||||
|
||||
@@ -47,10 +47,9 @@ export async function activate(api: PluginApi) {
|
||||
const id = `tab-${crypto.randomUUID()}`;
|
||||
const saved: SavedView = { view: id, profileId, url, runtimeId: '' };
|
||||
const run = (command: string, args?: Record<string, unknown>) => { void saved.control?.action(command, args); };
|
||||
// A new tab with the home page of the profile opens in a pane beside this tab.
|
||||
const split = (direction: 'right' | 'down') => {
|
||||
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
|
||||
void open(current?.profileId || saved.profileId, undefined, { split: direction, relativeTo: id });
|
||||
void open(current?.profileId || saved.profileId, current?.url || saved.url || 'about:blank', { split: direction, relativeTo: id });
|
||||
};
|
||||
api.registerView({ id, title: 'Browser', placement: 'editor', icon: 'globe', pinned, launcher: false,
|
||||
tabDragData: ({ pinned }) => {
|
||||
@@ -66,8 +65,8 @@ export async function activate(api: PluginApi) {
|
||||
return [
|
||||
{ separator: true },
|
||||
{ label: tr("Move to new window"), icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
|
||||
{ label: tr("New tab to the right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
|
||||
{ label: tr("New tab below"), icon: 'split-down', disabled: !ready, run: () => split('down') },
|
||||
{ label: tr("Split right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
|
||||
{ label: tr("Split down"), icon: 'split-down', disabled: !ready, run: () => split('down') },
|
||||
{ separator: true },
|
||||
{ label: tr("Find…"), icon: 'search', shortcut: keys('Mod+F'), disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
|
||||
{ label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') },
|
||||
|
||||
@@ -75,14 +75,12 @@ export class TabSession {
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Returns the reply of the engine, or undefined when the request did not complete. */
|
||||
async send(command: string, args: Record<string, unknown> = {}): Promise<unknown> {
|
||||
async send(command: string, args: Record<string, unknown> = {}) {
|
||||
if (this.closed || this.value.phase !== 'ready') return;
|
||||
const tabId = this.value.tabId;
|
||||
try {
|
||||
const reply = await this.transport(command, { ...args, tabId });
|
||||
await this.transport(command, { ...args, tabId });
|
||||
if (tabId === this.value.tabId && this.value.phase === 'ready' && !['input', 'resize', 'visible'].includes(command) && this.value.message) this.update({ message: '' });
|
||||
return reply;
|
||||
} catch (error) {
|
||||
// Replies from the previous connection cannot replace the current error.
|
||||
if (this.closed || tabId !== this.value.tabId || this.value.phase !== 'ready') return;
|
||||
|
||||
@@ -13,11 +13,9 @@
|
||||
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
|
||||
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
|
||||
import { linkCandidates } from "$lib/workspace/markdownLinks";
|
||||
import { documentHeadings } from "$lib/workspace/headingLinks";
|
||||
import { editImageSource, imageSource } from "./imageSource";
|
||||
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
|
||||
import { loadImageSize } from "$lib/workspace/imageSizes";
|
||||
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle, pastedImageSource } from "$lib/workspace/media";
|
||||
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle } from "$lib/workspace/media";
|
||||
import { registerImageDropTarget } from "./workspaceImageDrop";
|
||||
import { workspaceFileLink } from "./workspaceFileLink";
|
||||
import { savedEditor, saveEditor } from "./editorStates";
|
||||
@@ -50,7 +48,7 @@
|
||||
onChange: (value: string, id: string) => void;
|
||||
onRenameTitle?: (id: string, title: string) => Promise<void>;
|
||||
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
|
||||
onInsertImage?: (file: File, source?: string) => Promise<string | null>;
|
||||
onInsertImage?: (file: File) => Promise<string | null>;
|
||||
focusLine?: number | null;
|
||||
/** The line and the column of the cursor, from 1. */
|
||||
onSelectionLine?: (line: number, column: number) => void;
|
||||
@@ -101,12 +99,7 @@
|
||||
let decoded = source;
|
||||
try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ }
|
||||
for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) {
|
||||
try {
|
||||
const url = await workspaceReadDataUrl(candidate);
|
||||
await loadImageSize(url);
|
||||
urls.set(source, url);
|
||||
return;
|
||||
} catch { /* Try attachment location. */ }
|
||||
try { urls.set(source, await workspaceReadDataUrl(candidate)); return; } catch { /* Try attachment location. */ }
|
||||
}
|
||||
})();
|
||||
loading.set(source, task);
|
||||
@@ -133,12 +126,10 @@
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null;
|
||||
// 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);
|
||||
await importImages(view, files, position);
|
||||
}
|
||||
|
||||
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string, source?: string) {
|
||||
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string) {
|
||||
const range = position === null ? view.state.selection.main : { from: position, to: position };
|
||||
const id = Symbol(), path = buffer.relPath;
|
||||
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
|
||||
@@ -146,7 +137,7 @@
|
||||
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
|
||||
for (const file of files) {
|
||||
if (editor !== view) return;
|
||||
const snippet = await onInsertImage?.(file, source);
|
||||
const snippet = await onInsertImage?.(file);
|
||||
if (snippet) snippets.push(snippet);
|
||||
}
|
||||
if (editor !== view || !snippets.length) return;
|
||||
@@ -441,11 +432,8 @@
|
||||
const view = editor;
|
||||
if (!view || line == null) return;
|
||||
untrack(() => {
|
||||
const number = Math.min(view.state.doc.lines, Math.max(1, line));
|
||||
const anchor = view.state.doc.line(number).from;
|
||||
// A heading starts the text to read, so it goes to the top, as in Read. Other lines, such as a search match, stay in the center.
|
||||
const heading = markdownDocument && documentHeadings(view.state.doc.toString()).some(entry => entry.line === number);
|
||||
const effects = [EditorView.scrollIntoView(anchor, heading ? { y: "start", yMargin: 24 } : { y: "center" })];
|
||||
const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from;
|
||||
const effects = [EditorView.scrollIntoView(anchor, { y: "center" })];
|
||||
foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
|
||||
view.dispatch({ selection: { anchor }, effects });
|
||||
view.focus();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
.reading .rs-heading-toggle { inset-inline-start: -24px; }
|
||||
.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:hover, .rs-heading-toggle:focus-visible { color: var(--rs-text); background: var(--rs-hover-bg); }
|
||||
.rs-heading-toggle:hover, .rs-heading-toggle:focus-visible { color: var(--rs-text); background: var(--rs-bg-active); }
|
||||
.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[aria-expanded="true"] svg { transform: rotate(90deg); }
|
||||
|
||||
@@ -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-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:hover, .image-action:focus-visible { background: var(--rs-hover-bg); color: var(--rs-text-strong); }
|
||||
.image-action:hover, .image-action:focus-visible { background: var(--rs-bg-active); color: var(--rs-text-strong); }
|
||||
.image-action:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; }
|
||||
.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); }
|
||||
|
||||
@@ -5,7 +5,6 @@ import { attachTooltip } from "../ui/tooltip";
|
||||
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
|
||||
import type { ActionMenuItem } from "../ui/actionMenu";
|
||||
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
|
||||
import { imageSize, rememberImageSize } from "../workspace/imageSizes";
|
||||
|
||||
export type ImageActions = {
|
||||
edit?: () => void;
|
||||
@@ -57,8 +56,6 @@ function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
|
||||
viewport.className = "image-lightbox-viewport";
|
||||
const image = original.cloneNode() as HTMLImageElement;
|
||||
image.removeAttribute("loading");
|
||||
image.removeAttribute("width");
|
||||
image.removeAttribute("height");
|
||||
image.draggable = false;
|
||||
let scale = 0;
|
||||
const status = document.createElement("span");
|
||||
@@ -94,12 +91,6 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
|
||||
const cleanup: (() => void)[] = [];
|
||||
for (const image of root.querySelectorAll<HTMLImageElement>("img[data-md-src]")) {
|
||||
if (image.closest(".md-image-frame")) continue;
|
||||
// A remote image gives its size when it loads. The next view of this image keeps its space from the start.
|
||||
const remember = () => rememberImageSize(image.src, image.naturalWidth, image.naturalHeight);
|
||||
image.addEventListener("load", remember);
|
||||
cleanup.push(() => image.removeEventListener("load", remember));
|
||||
const known = !image.getAttribute("width") && imageSize(image.src);
|
||||
if (known) { image.width = known.width; image.height = known.height; }
|
||||
const frame = document.createElement("span");
|
||||
frame.className = "md-image-frame";
|
||||
frame.contentEditable = "false";
|
||||
|
||||
@@ -5,7 +5,6 @@ import { imageControls, type ImageActions } from "./imageControls";
|
||||
import { editImageSource } from "./imageSource";
|
||||
import { requestText } from "../workspace/dialogs.svelte";
|
||||
import { isRemoteImage } from "../workspace/media";
|
||||
import { estimatedImageHeight } from "../workspace/imageSizes";
|
||||
import { actionIcon } from "../ui/actionIcons";
|
||||
|
||||
export type ImageContext = {
|
||||
@@ -19,7 +18,6 @@ const cleanups = new WeakMap<HTMLElement, () => void>();
|
||||
export class ImagePreview extends WidgetType {
|
||||
constructor(readonly html: string, readonly source: string, readonly context: ImageContext, readonly editing = false, readonly block = true) { super(); }
|
||||
eq(other: ImagePreview) { return this.html === other.html && this.source === other.source && this.editing === other.editing && this.block === other.block; }
|
||||
get estimatedHeight() { return estimatedImageHeight(this.html); }
|
||||
toDOM(view: EditorView) {
|
||||
const dom = document.createElement(this.block ? "div" : "span");
|
||||
dom.className = `reading writer-preview ${this.block ? "writer-image" : "writer-image-inline"}`;
|
||||
|
||||
+13
-124
@@ -4,7 +4,7 @@ import { isMac } from "../ui/shortcuts";
|
||||
/** The tooltip of a link in Write. A click with Ctrl, or Cmd on macOS, opens the link. */
|
||||
const linkTooltip = () => tr("{modifier}+click to open link", { modifier: isMac() ? "⌘" : "Ctrl" });
|
||||
import { EditorSelection, StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
|
||||
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
|
||||
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
|
||||
import { renderMarkdownSections } from "../workspace/noteHtml";
|
||||
import { renderDiagrams } from "../workspace/diagrams";
|
||||
@@ -22,34 +22,9 @@ import { listLabels } from "./markdownLists";
|
||||
import { activeTableFormulas } from "../formulas/index.ts";
|
||||
|
||||
const previewFormulas = new WeakMap<HTMLElement, unknown>();
|
||||
const previewHtml = new WeakMap<HTMLElement, string>();
|
||||
export const refreshImages = StateEffect.define<void>();
|
||||
const imageCleanups = new WeakMap<HTMLElement, () => void>();
|
||||
|
||||
/**
|
||||
* CodeMirror reads the line height of the document from the first short line that holds only plain text.
|
||||
* A different height makes it estimate all heights again, and the view then jumps to other text.
|
||||
* A mark span keeps a line with a different height out of that reading.
|
||||
*/
|
||||
const otherLineHeight = Decoration.mark({ class: "writer-line-text" });
|
||||
|
||||
// A resize observer records the height of a preview without a CodeMirror measure request.
|
||||
// A request from toDOM restarts the layout loop of CodeMirror, and a loop that restarts too often does not restore the scroll position.
|
||||
const previewHeights = new WeakMap<Element, { value: number }>();
|
||||
let previewSizes: ResizeObserver | undefined;
|
||||
function watchPreviewHeight(dom: HTMLElement, height: { value: number }) {
|
||||
previewSizes ??= new ResizeObserver(entries => {
|
||||
for (const { target } of entries) {
|
||||
const holder = previewHeights.get(target);
|
||||
if (holder && target.isConnected) holder.value = (target as HTMLElement).offsetHeight;
|
||||
}
|
||||
});
|
||||
const known = previewHeights.get(dom);
|
||||
if (known && known !== height) height.value = known.value;
|
||||
previewHeights.set(dom, height);
|
||||
previewSizes.observe(dom);
|
||||
}
|
||||
|
||||
const linkTooltips = ViewPlugin.define(view => {
|
||||
const attached = new Map<HTMLElement, () => void>();
|
||||
const refresh = () => {
|
||||
@@ -144,35 +119,23 @@ class ListLabel extends WidgetType {
|
||||
ignoreEvent() { return false; }
|
||||
}
|
||||
|
||||
/**
|
||||
* The heights of previews, by their HTML, from a layout outside the editor. CodeMirror draws only the lines near the view.
|
||||
* Without a height, a large table counts as one line until its first draw. The document then grows by thousands of pixels
|
||||
* at one time, the scrollbar moves, and the layout loop of CodeMirror can stop before it restores the scroll position.
|
||||
*/
|
||||
const measuredHeights = new Map<string, { width: number; height: number }>();
|
||||
const maxMeasuredHeights = 1000;
|
||||
|
||||
class Preview extends WidgetType {
|
||||
readonly formulas = activeTableFormulas();
|
||||
readonly estimate: number;
|
||||
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) {
|
||||
super();
|
||||
this.estimate = measuredHeights.get(html)?.height ?? -1;
|
||||
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) { super(); }
|
||||
get estimatedHeight() { return this.height.value; }
|
||||
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; }
|
||||
measure(dom: HTMLElement, view: EditorView) {
|
||||
view.requestMeasure({ key: this.height, read: () => dom.offsetHeight, write: height => { this.height.value = height; } });
|
||||
}
|
||||
get estimatedHeight() { return this.height.value >= 0 ? this.height.value : this.estimate; }
|
||||
// A new estimate must reach the height map of CodeMirror. updateDOM keeps the drawn table.
|
||||
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible && other.estimate === this.estimate; }
|
||||
updateDOM(dom: HTMLElement) {
|
||||
const table = tableEditors.get(dom);
|
||||
if (previewFormulas.get(dom) !== this.formulas || (table ? table.source !== this.source : previewHtml.get(dom) !== this.html)) return false;
|
||||
watchPreviewHeight(dom, this.height);
|
||||
updateDOM(dom: HTMLElement, view: EditorView) {
|
||||
if (previewFormulas.get(dom) !== this.formulas || tableEditors.get(dom)?.source !== this.source) return false;
|
||||
this.measure(dom, view);
|
||||
return true;
|
||||
}
|
||||
destroy(dom: HTMLElement) { previewSizes?.unobserve(dom); tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
|
||||
destroy(dom: HTMLElement) { tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
|
||||
toDOM(view: EditorView) {
|
||||
const dom = document.createElement("div");
|
||||
previewFormulas.set(dom, this.formulas);
|
||||
previewHtml.set(dom, this.html);
|
||||
dom.className = "reading writer-preview";
|
||||
dom.innerHTML = this.html;
|
||||
// Widgets handle their own events, so CodeMirror's link handler cannot run.
|
||||
@@ -190,7 +153,7 @@ class Preview extends WidgetType {
|
||||
}, { capture: true });
|
||||
tableControls(dom, view, this.source, this.actions);
|
||||
imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); }));
|
||||
watchPreviewHeight(dom, this.height);
|
||||
this.measure(dom, view);
|
||||
dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove());
|
||||
dom.addEventListener("mousedown", event => {
|
||||
if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return;
|
||||
@@ -211,45 +174,6 @@ class Preview extends WidgetType {
|
||||
ignoreEvent() { return true; }
|
||||
}
|
||||
|
||||
function textColumnWidth(view: EditorView) {
|
||||
const style = getComputedStyle(view.contentDOM);
|
||||
return view.contentDOM.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
|
||||
}
|
||||
|
||||
/** Measure previews in one layout pass, in a hidden copy of the text column. A copy has the table frame and footer, but not the table controls. */
|
||||
function measurePreviews(view: EditorView, widgets: Preview[], width: number) {
|
||||
const host = document.createElement("div");
|
||||
host.className = view.contentDOM.className;
|
||||
host.setAttribute("aria-hidden", "true");
|
||||
host.style.cssText = "position:absolute;inset:0 0 auto 0;height:0;min-height:0;padding-block:0;overflow:hidden;visibility:hidden;pointer-events:none";
|
||||
const footer = document.createElement("div");
|
||||
footer.className = "table-footer";
|
||||
const tools = activeTableFormulas()?.createFormulaTools(() => {}, () => {});
|
||||
if (tools) footer.append(tools.formulaTools);
|
||||
const copies = widgets.map(widget => {
|
||||
const copy = document.createElement("div");
|
||||
copy.className = "reading writer-preview";
|
||||
copy.innerHTML = widget.html;
|
||||
const scroll = copy.querySelector(".md-table-scroll");
|
||||
if (scroll && parseMarkdownTable(widget.source)) {
|
||||
const frame = document.createElement("div");
|
||||
frame.className = "writer-table";
|
||||
scroll.before(frame);
|
||||
frame.append(scroll);
|
||||
frame.after(footer.cloneNode(true));
|
||||
}
|
||||
host.append(copy);
|
||||
return copy;
|
||||
});
|
||||
view.scrollDOM.append(host);
|
||||
if (measuredHeights.size + widgets.length > maxMeasuredHeights) measuredHeights.clear();
|
||||
copies.forEach((copy, index) => {
|
||||
measuredHeights.set(widgets[index].html, { width, height: copy.offsetHeight });
|
||||
widgets[index].height.value = -1;
|
||||
});
|
||||
host.remove();
|
||||
}
|
||||
|
||||
export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) {
|
||||
const selecting = StateEffect.define<boolean>();
|
||||
const mouseSelecting = StateField.define({
|
||||
@@ -332,10 +256,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to);
|
||||
for (let number = 1; number <= state.doc.lines; number++) {
|
||||
const line = state.doc.line(number);
|
||||
if (!line.text.trim() && !hidden(line.from, line.to)) {
|
||||
ranges.push(Decoration.line({ class: "writer-blank" }).range(line.from));
|
||||
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
|
||||
}
|
||||
if (!line.text.trim() && !hidden(line.from, line.to)) ranges.push(Decoration.line({ class: "writer-blank" }).range(line.from));
|
||||
}
|
||||
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)); };
|
||||
@@ -353,7 +274,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
for (let number = first.number; number <= last.number; number++) {
|
||||
const line = state.doc.line(number);
|
||||
ranges.push(Decoration.line({ class: editingCode ? "writer-code-source" : `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from));
|
||||
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -363,7 +283,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
const pendingList = node.name === "SetextHeading2" && state.doc.lineAt(node.to).text.trim() === "-";
|
||||
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name) && !pendingList) {
|
||||
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
|
||||
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
|
||||
}
|
||||
if (node.name === "InlineCode") codeRanges.push({ from: node.from, to: node.to });
|
||||
if (node.name === "TaskMarker") {
|
||||
@@ -447,36 +366,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
filter: (_from, _to, decoration) => decoration.spec.atomic === true,
|
||||
}))],
|
||||
});
|
||||
// Give each preview that is not drawn a height, after the document opens, changes, or gets another width.
|
||||
const previewMeasuring = ViewPlugin.fromClass(class {
|
||||
frame = 0;
|
||||
width = -1;
|
||||
constructor(readonly view: EditorView) { this.schedule(); }
|
||||
update(update: ViewUpdate) {
|
||||
if (update.geometryChanged || update.startState.field(decorations) !== update.state.field(decorations)) this.schedule();
|
||||
}
|
||||
schedule() {
|
||||
this.frame ||= requestAnimationFrame(() => { this.frame = 0; this.measure(); });
|
||||
}
|
||||
measure() {
|
||||
const { view } = this, width = textColumnWidth(view);
|
||||
// The editor has no width while another view or tab covers it.
|
||||
if (width < 50) return;
|
||||
const resized = Math.abs(width - this.width) > 1;
|
||||
this.width = width;
|
||||
const { from: drawnFrom, to: drawnTo } = view.viewport;
|
||||
const widgets: Preview[] = [];
|
||||
view.state.field(decorations).between(0, view.state.doc.length, (from, to, decoration) => {
|
||||
const widget = decoration.spec.widget;
|
||||
if (!(widget instanceof Preview) || (from < drawnTo && to > drawnFrom)) return;
|
||||
if ((resized || widget.height.value < 0) && measuredHeights.get(widget.html)?.width !== width) widgets.push(widget);
|
||||
});
|
||||
if (!widgets.length) return;
|
||||
measurePreviews(view, widgets, width);
|
||||
view.dispatch({ effects: refreshImages.of() });
|
||||
}
|
||||
destroy() { cancelAnimationFrame(this.frame); }
|
||||
});
|
||||
const mousePreview = ViewPlugin.define(view => {
|
||||
const finish = () => {
|
||||
if (!view.state.field(mouseSelecting)) return;
|
||||
@@ -511,6 +400,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
window.removeEventListener("blur", finish);
|
||||
} };
|
||||
});
|
||||
return [imageSource, linkTooltips, bodyFocused, mouseSelecting, decorations, previewMeasuring, mousePreview, syncBodyFocus,
|
||||
return [imageSource, linkTooltips, bodyFocused, mouseSelecting, decorations, mousePreview, syncBodyFocus,
|
||||
EditorView.focusChangeEffect.of((_state, focusing) => focusBody.of(focusing))];
|
||||
}
|
||||
|
||||
@@ -1,18 +1,10 @@
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
import { documentMatches, type FindTarget } from "./findTarget";
|
||||
|
||||
/** Keys that do not change the text of the find field. These keys keep the selected match. */
|
||||
const keepsMatch = /^(?:Enter|Escape|Tab|Shift|Control|Alt|Meta|CapsLock|ContextMenu|F\d+)$/;
|
||||
|
||||
/** Search the visible reading text without changing its Markdown or rendered nodes. */
|
||||
export function readingSearch(root: HTMLElement, close: () => void, options: { includeButtons?: boolean; focusOnClose?: () => void } = {}): FindTarget {
|
||||
let query = new SearchQuery({ search: "" });
|
||||
let current = -1;
|
||||
// The window selection also holds the caret of a focused find field. There it reads as collapsed and outside the text.
|
||||
function matchSelected() {
|
||||
const selection = window.getSelection();
|
||||
return !!selection && !selection.isCollapsed && root.contains(selection.anchorNode);
|
||||
}
|
||||
function ranges() {
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
||||
const nodes: { node: Text; from: number; to: number }[] = [];
|
||||
@@ -48,15 +40,7 @@ export function readingSearch(root: HTMLElement, close: () => void, options: { i
|
||||
}
|
||||
return {
|
||||
get query() { return query; }, readOnly: true, canSelectAll: false,
|
||||
setQuery(value) { if (query.eq(value)) return; query = value; current = -1; 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;
|
||||
},
|
||||
setQuery(value) { if (query.eq(value)) return; query = value; current = -1; window.getSelection()?.removeAllRanges(); },
|
||||
next, selectAll() {}, replace() {},
|
||||
close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); },
|
||||
};
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
.table-drag-handle[hidden], .table-drop-indicator[hidden] { display: none; }
|
||||
.table-drag-handle .action-icon { width: 18px; height: 18px; pointer-events: none; }
|
||||
.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-hover-bg); 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-bg-active); 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 .table-drag-handle::after { display: none; }
|
||||
.table-drop-indicator { position: absolute; z-index: 3; border-radius: 2px; background: var(--rs-accent); pointer-events: none; }
|
||||
|
||||
@@ -451,13 +451,6 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
event.preventDefault(); activate(cell);
|
||||
const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY });
|
||||
if (hit) { editor?.commands.setTextSelection(hit.pos); editor?.view.focus(); }
|
||||
} else if (event.detail === 1 && editor && !editor.view.composing && editor.view.dom.contains(event.target)) {
|
||||
// ProseMirror reads a native click on the next selectionchange. Its
|
||||
// delayed focus check can run first and restore the old selection, so
|
||||
// the click is lost under load. Set the clicked position here. The
|
||||
// browser then places the same caret, and a drag starts from it.
|
||||
const hit = editor.view.posAtCoords({ left: event.clientX, top: event.clientY });
|
||||
if (hit) editor.commands.setTextSelection(hit.pos);
|
||||
}
|
||||
});
|
||||
refreshFormulas();
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
.header { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
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:hover:not(:disabled) { background: var(--rs-hover-bg); }
|
||||
.text-button:hover:not(:disabled) { background: var(--rs-bg-active); }
|
||||
.text-button:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.text-button:disabled { color: var(--rs-text-dim); }
|
||||
.error { margin: 0; color: var(--rs-error); }
|
||||
|
||||
@@ -216,7 +216,7 @@
|
||||
ol { flex: 1; min-width: 0; margin: 0; padding: 0; list-style: none; }
|
||||
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:hover { background: var(--rs-hover-bg); }
|
||||
ol button:hover { background: var(--rs-bg-active); }
|
||||
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; }
|
||||
.description { display: flex; align-items: center; gap: 5px; min-width: 0; }
|
||||
@@ -233,7 +233,7 @@
|
||||
.message { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.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:hover { background: var(--rs-hover-bg); }
|
||||
.file:hover { background: var(--rs-bg-active); }
|
||||
.file span:first-child { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.details :global(.diff) { min-height: 140px; }
|
||||
@container (max-width: 950px) { ol button { grid-template-columns: minmax(0, 1fr) 54px; } .author, .date { display: none; } }
|
||||
|
||||
@@ -149,7 +149,7 @@
|
||||
{#if group.changes.length}
|
||||
<section class="group">
|
||||
<div class="group-header">
|
||||
<h3>{group.staged ? $t("Staged changes ({count})", { count: group.changes.length }) : $t("Unstaged changes ({count})", { count: group.changes.length })}</h3>
|
||||
<h3>{group.staged ? $t("Staged changes ({count})", { count: group.changes.length }) : $t("Changes ({count})", { count: group.changes.length })}</h3>
|
||||
<IconButton icon={group.staged ? "minus" : "plus"} label={group.staged ? $t("Unstage all") : $t("Stage all")} disabled={busy} onclick={() => stage(group.changes, group.staged)} />
|
||||
</div>
|
||||
{#each group.changes as change (change.path)}
|
||||
@@ -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: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:hover:not(:disabled) { background: var(--rs-hover-bg); }
|
||||
.primary:hover:not(:disabled) { background: var(--rs-bg-active); }
|
||||
.primary:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.primary:disabled { color: var(--rs-text-dim); }
|
||||
small { color: var(--rs-text-dim); line-height: 1.5; }
|
||||
.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:hover { background: var(--rs-hover-bg); }
|
||||
summary:hover { background: var(--rs-bg-active); }
|
||||
summary:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
|
||||
.group { margin-bottom: 6px; }
|
||||
.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; }
|
||||
.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:hover:not(:disabled) { background: var(--rs-hover-bg); }
|
||||
.file:hover:not(:disabled) { background: var(--rs-bg-active); }
|
||||
.file:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
|
||||
.file:disabled { color: var(--rs-text-dim); }
|
||||
.file span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
@@ -1,32 +1,28 @@
|
||||
<script lang="ts">
|
||||
// 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.
|
||||
// One PDF tab: the toolbar, the status line, the password form, and one page with its text layer.
|
||||
// The document and its worker live as long as the tab. `close` releases both.
|
||||
import { flushSync, onMount } from "svelte";
|
||||
import { onMount } from "svelte";
|
||||
import { message, t } from "$lib/i18n";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import type { PluginDocumentContext } from "$lib/plugins/sdk";
|
||||
import { openPdf, TextLayer, type OpenPdf, type PDFDocumentProxy, type RenderTask } from "./engine";
|
||||
import { MAX_ZOOM, MIN_ZOOM, PAGE_GAP, PAGE_MARGIN, RESIZE_SETTLE_MS, ZOOM_STEP, fitZoom, mostVisiblePage, nextRotation, outputScale, pageBoxes, pageNumber, pagesInRange, zoomFromText, zoomLevel, type PageSize } from "./model";
|
||||
import { MAX_ZOOM, MIN_ZOOM, RESIZE_SETTLE_MS, ZOOM_STEP, nextRotation, outputScale, pageNumber, zoomLevel } from "./model";
|
||||
|
||||
let { file, readBytes }: { file: PluginDocumentContext; readBytes: (path: string) => Promise<Uint8Array> } = $props();
|
||||
|
||||
type Status = { key: string; values?: Record<string, string | number>; alert?: boolean };
|
||||
/** One page that has a drawing, or waits for one. `key` names the zoom, the rotation, and the pixel ratio. */
|
||||
type Drawing = { key: string; done: boolean; cancel(): void };
|
||||
|
||||
let page = $state(1);
|
||||
let count = $state(0);
|
||||
let zoom = $state(1);
|
||||
let rotation = $state(0);
|
||||
let fit = $state(true);
|
||||
let sizes = $state.raw<PageSize[]>([]);
|
||||
let status = $state<Status>({ key: message("Loading PDF…") });
|
||||
let asking = $state<"needed" | "incorrect" | null>(null);
|
||||
let reloading = $state(false);
|
||||
let failed = $state(false);
|
||||
let scroller: HTMLDivElement;
|
||||
let sheets: HTMLDivElement[] = $state([]);
|
||||
let sheet: HTMLDivElement;
|
||||
let pageInput: HTMLInputElement;
|
||||
let passwordInput: HTMLInputElement | undefined = $state();
|
||||
|
||||
@@ -34,20 +30,14 @@
|
||||
let pdf: PDFDocumentProxy | undefined;
|
||||
let opened: OpenPdf | undefined;
|
||||
let answer: ((password: string) => void) | undefined;
|
||||
let generation = 0;
|
||||
const drawings = new Map<number, Drawing>();
|
||||
let render: RenderTask | undefined;
|
||||
let text: TextLayer | undefined;
|
||||
let revision = 0;
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
let loading: Promise<void> = Promise.resolve();
|
||||
let closing: Promise<void> | undefined;
|
||||
// The place in the document: a page and the part of its height above the top of the visible area.
|
||||
let anchor = { index: 0, part: 0 };
|
||||
// The scroll position that the viewer set. A scroll event at this position keeps the page number.
|
||||
let settled = -1;
|
||||
let frame = 0;
|
||||
|
||||
const ready = $derived(count > 0);
|
||||
const boxes = $derived(pageBoxes(sizes, zoom, rotation));
|
||||
const zoomText = $derived(ready ? `${Math.round(zoom * 100)}%` : "—");
|
||||
|
||||
function fail(reason: unknown) {
|
||||
if (disposed) return;
|
||||
@@ -55,137 +45,53 @@
|
||||
status = { key: message("Cannot display this PDF. {reason}"), values: { reason: reason instanceof Error ? reason.message : String(reason) }, alert: true };
|
||||
}
|
||||
|
||||
const drawingKey = () => `${zoom}:${rotation}:${window.devicePixelRatio}`;
|
||||
|
||||
/** The status line names the current page when its drawing is complete. */
|
||||
function report() {
|
||||
if (disposed || failed || !pdf) return;
|
||||
const drawing = drawings.get(page);
|
||||
status = drawing?.done && drawing.key === drawingKey()
|
||||
? { key: message("Page {page} of {count}"), values: { page, count } }
|
||||
: { key: message("Loading page {page}…"), values: { page } };
|
||||
}
|
||||
|
||||
/** Draw one page. The jobs run one at a time. A cancelled job ends at its next step. */
|
||||
function draw(number: number, key: string) {
|
||||
let cancelled = false;
|
||||
let render: RenderTask | undefined;
|
||||
let text: TextLayer | undefined;
|
||||
const drawing: Drawing = { key, done: false, cancel() { cancelled = true; render?.cancel(); text?.cancel(); } };
|
||||
drawings.set(number, drawing);
|
||||
const source = pdf;
|
||||
/** Draw the current page again. A newer request cancels the older one. */
|
||||
function schedule() {
|
||||
const request = ++revision;
|
||||
render?.cancel(); text?.cancel();
|
||||
if (pdf && !disposed) status = { key: message("Loading page {page}…"), values: { page } };
|
||||
queue = queue.then(async () => {
|
||||
if (cancelled || disposed || !source) return;
|
||||
const pdfPage = await source.getPage(number);
|
||||
const sheet = sheets[number - 1];
|
||||
if (cancelled || disposed || !sheet) return;
|
||||
const viewport = pdfPage.getViewport({ scale: zoom, rotation: (pdfPage.rotate + rotation) % 360 });
|
||||
if (disposed || request !== revision || !pdf || scroller.clientWidth === 0) return;
|
||||
const pdfPage = await pdf.getPage(page);
|
||||
if (disposed || request !== revision) return;
|
||||
const angle = (pdfPage.rotate + rotation) % 360;
|
||||
if (fit) zoom = zoomLevel((scroller.clientWidth - 32) / pdfPage.getViewport({ scale: 1, rotation: angle }).width);
|
||||
const viewport = pdfPage.getViewport({ scale: zoom, rotation: angle });
|
||||
const scale = outputScale(viewport.width, viewport.height, window.devicePixelRatio);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.max(1, Math.floor(viewport.width * scale));
|
||||
canvas.height = Math.max(1, Math.floor(viewport.height * scale));
|
||||
canvas.style.width = `${viewport.width}px`;
|
||||
canvas.style.height = `${viewport.height}px`;
|
||||
canvas.setAttribute("role", "img");
|
||||
// The measurement tool and the smoke tests find the page by this English name. Keep "PDF page N".
|
||||
canvas.setAttribute("aria-label", $t("PDF page {page}", { page: number }));
|
||||
canvas.setAttribute("aria-label", $t("PDF page {page}", { page }));
|
||||
const layer = document.createElement("div");
|
||||
layer.className = "textLayer";
|
||||
layer.style.setProperty("--total-scale-factor", String(viewport.scale));
|
||||
sheet.style.width = `${viewport.width}px`;
|
||||
sheet.style.height = `${viewport.height}px`;
|
||||
sheet.style.setProperty("--total-scale-factor", String(zoom));
|
||||
sheet.replaceChildren(canvas, layer);
|
||||
render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] });
|
||||
await render.promise;
|
||||
if (cancelled || disposed) return;
|
||||
// The old drawing of the page stays until the new one is complete.
|
||||
sheet.replaceChildren(canvas, layer);
|
||||
if (disposed || request !== revision) return;
|
||||
text = new TextLayer({ textContentSource: pdfPage.streamTextContent(), container: layer, viewport });
|
||||
await text.render();
|
||||
if (cancelled || disposed) return;
|
||||
drawing.done = true;
|
||||
if (disposed || request !== revision) return;
|
||||
status = { key: message("Page {page} of {count}"), values: { page, count } };
|
||||
pdfPage.cleanup();
|
||||
report();
|
||||
}).catch(reason => { if (!cancelled && !disposed) fail(reason); });
|
||||
}).catch(reason => { if (!disposed && request === revision) fail(reason); });
|
||||
}
|
||||
|
||||
/** Draw the pages near the visible area, the current page first. Empty the pages that are far from it. */
|
||||
function refresh() {
|
||||
if (!pdf || disposed || scroller.clientWidth === 0) return;
|
||||
const key = drawingKey();
|
||||
const height = scroller.clientHeight;
|
||||
const wanted = pagesInRange(boxes, scroller.scrollTop - height, scroller.scrollTop + 2 * height);
|
||||
for (const [number, drawing] of drawings) {
|
||||
const keep = wanted.includes(number);
|
||||
if (keep && drawing.key === key) continue;
|
||||
drawing.cancel();
|
||||
drawings.delete(number);
|
||||
if (!keep) sheets[number - 1]?.replaceChildren();
|
||||
}
|
||||
for (const number of wanted.sort((a, b) => Math.abs(a - page) - Math.abs(b - page))) if (!drawings.has(number)) draw(number, key);
|
||||
report();
|
||||
}
|
||||
|
||||
/** Put the remembered place at the top of the visible area again, after the page boxes changed. */
|
||||
function restore() {
|
||||
flushSync();
|
||||
const box = boxes[anchor.index];
|
||||
if (!box || scroller.clientWidth === 0) return;
|
||||
scroller.scrollTop = Math.max(0, box.top + anchor.part * box.height);
|
||||
settled = scroller.scrollTop;
|
||||
refresh();
|
||||
}
|
||||
|
||||
function remember() {
|
||||
const box = boxes[page - 1];
|
||||
anchor = { index: page - 1, part: box ? (scroller.scrollTop - box.top) / box.height : 0 };
|
||||
}
|
||||
|
||||
function scrolled() {
|
||||
if (frame) return;
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = 0;
|
||||
if (disposed || !ready || scroller.clientWidth === 0) return;
|
||||
if (scroller.scrollTop !== settled) {
|
||||
settled = -1;
|
||||
page = mostVisiblePage(boxes, scroller.scrollTop, scroller.scrollTop + scroller.clientHeight);
|
||||
remember();
|
||||
}
|
||||
refresh();
|
||||
});
|
||||
}
|
||||
|
||||
/** Show the top of a page. */
|
||||
function go(value: number) {
|
||||
if (!pdf) return;
|
||||
page = pageNumber(value, pdf.numPages);
|
||||
pageInput.value = String(page);
|
||||
// The first page shows with the margin above it. Each other page shows with half of the gap above it.
|
||||
anchor = { index: page - 1, part: -(page === 1 ? PAGE_MARGIN : PAGE_GAP / 2) / (boxes[page - 1]?.height ?? 1) };
|
||||
restore();
|
||||
scroller.scrollTop = 0;
|
||||
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();
|
||||
}
|
||||
function setZoom(value: number) { fit = false; zoom = zoomLevel(value); schedule(); }
|
||||
|
||||
async function load() {
|
||||
failed = false;
|
||||
@@ -199,27 +105,20 @@
|
||||
status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") };
|
||||
queueMicrotask(() => passwordInput?.focus());
|
||||
});
|
||||
const source = await opened.promise;
|
||||
pdf = await opened.promise;
|
||||
if (disposed) return;
|
||||
const current = ++generation;
|
||||
const { width, height } = (await source.getPage(1)).getViewport({ scale: 1 });
|
||||
if (disposed) return;
|
||||
pdf = source;
|
||||
sizes = Array.from({ length: source.numPages }, () => ({ width, height }));
|
||||
count = source.numPages;
|
||||
applyFit();
|
||||
go(page);
|
||||
report();
|
||||
void measure(source, current).catch(reason => { if (current === generation) fail(reason); });
|
||||
page = pageNumber(page, pdf.numPages);
|
||||
count = pdf.numPages;
|
||||
schedule();
|
||||
}
|
||||
|
||||
async function release() {
|
||||
generation++;
|
||||
for (const drawing of drawings.values()) drawing.cancel();
|
||||
drawings.clear();
|
||||
revision++;
|
||||
render?.cancel(); text?.cancel();
|
||||
await queue;
|
||||
const current = opened;
|
||||
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0; sizes = [];
|
||||
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0;
|
||||
sheet?.replaceChildren();
|
||||
await current?.close();
|
||||
}
|
||||
|
||||
@@ -246,11 +145,12 @@
|
||||
next(value);
|
||||
}
|
||||
|
||||
/** Ctrl and the wheel change the zoom. The wheel alone scrolls the pages. */
|
||||
function wheel(event: WheelEvent) {
|
||||
if (!(event.ctrlKey || event.metaKey) || !ready || event.deltaY === 0) return;
|
||||
function pageKey(event: KeyboardEvent) {
|
||||
if (event.ctrlKey || event.metaKey || event.altKey || !ready) return;
|
||||
if (event.key === "PageDown" || event.key === "PageUp") {
|
||||
event.preventDefault();
|
||||
setZoom(event.deltaY < 0 ? zoom * 1.1 : zoom / 1.1);
|
||||
go(page + (event.key === "PageDown" ? 1 : -1));
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop the drawing, release the document, and stop its worker. The host calls it before it removes the tab. */
|
||||
@@ -263,23 +163,21 @@
|
||||
|
||||
onMount(() => {
|
||||
loading = load().catch(fail);
|
||||
// Fit-width pages follow the width of the tab. A tab that shows again draws at once. Later sizes wait until the size settles.
|
||||
// A fit-width page follows the width of the tab. The first size draws at once. Later sizes wait until the size settles.
|
||||
let width = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const resized = () => { applyFit(); restore(); };
|
||||
const observer = new ResizeObserver(() => {
|
||||
const next = scroller.clientWidth;
|
||||
if (next === width) return;
|
||||
const shown = width === 0;
|
||||
if (next === 0 || next === width) return;
|
||||
const first = width === 0;
|
||||
width = next;
|
||||
clearTimeout(timer);
|
||||
if (next === 0) return;
|
||||
if (shown) resized();
|
||||
else timer = setTimeout(resized, RESIZE_SETTLE_MS);
|
||||
if (!fit) return;
|
||||
if (first) schedule();
|
||||
else timer = setTimeout(schedule, RESIZE_SETTLE_MS);
|
||||
});
|
||||
observer.observe(scroller);
|
||||
scroller.addEventListener("wheel", wheel, { passive: false });
|
||||
return () => { observer.disconnect(); clearTimeout(timer); cancelAnimationFrame(frame); scroller.removeEventListener("wheel", wheel); void close(); };
|
||||
return () => { observer.disconnect(); clearTimeout(timer); void close(); };
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -293,12 +191,10 @@
|
||||
<IconButton icon="down" label={$t("Next page")} disabled={!ready || page >= count} onclick={() => go(page + 1)} />
|
||||
<span class="separator" aria-hidden="true"></span>
|
||||
<IconButton icon="zoom-out" label={$t("Zoom out")} disabled={!ready || zoom <= MIN_ZOOM} onclick={() => setZoom(zoom / ZOOM_STEP)} />
|
||||
<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); }} />
|
||||
<span class="zoom">{ready ? `${Math.round(zoom * 100)}%` : "—"}</span>
|
||||
<IconButton icon="zoom-in" label={$t("Zoom in")} disabled={!ready || zoom >= MAX_ZOOM} onclick={() => setZoom(zoom * ZOOM_STEP)} />
|
||||
<IconButton icon="fit-width" label={$t("Fit width")} active={fit && ready} disabled={!ready} onclick={() => { fit = true; applyFit(); restore(); }} />
|
||||
<IconButton icon="rotate" label={$t("Rotate clockwise")} disabled={!ready} onclick={() => { rotation = nextRotation(rotation); applyFit(); restore(); }} />
|
||||
<IconButton icon="fit-width" label={$t("Fit width")} active={fit && ready} disabled={!ready} onclick={() => { fit = true; schedule(); }} />
|
||||
<IconButton icon="rotate" label={$t("Rotate clockwise")} disabled={!ready} onclick={() => { rotation = nextRotation(rotation); schedule(); }} />
|
||||
<IconButton icon="refresh" label={$t("Reload PDF")} disabled={reloading || (!ready && !failed)} onclick={() => void reload()} />
|
||||
</div>
|
||||
<p class="status" class:alert={status.alert} role={status.alert ? "alert" : "status"} aria-live={status.alert ? "assertive" : "polite"}>{$t(status.key, status.values)}</p>
|
||||
@@ -308,39 +204,32 @@
|
||||
<button class="text-button" type="submit">{$t("Unlock")}</button>
|
||||
</form>
|
||||
{/if}
|
||||
<!-- The page area takes focus, so the keyboard scrolls the pages. The host gives it focus after a tab change by keyboard. -->
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
|
||||
<div bind:this={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF pages")} data-tab-focus onscroll={scrolled}>
|
||||
<div class="pages">
|
||||
{#each boxes as box, index (index)}
|
||||
<div bind:this={sheets[index]} class="sheet" data-page={index + 1} style:width={`${box.width}px`} style:height={`${box.height}px`}></div>
|
||||
{/each}
|
||||
</div>
|
||||
<!-- The page area takes focus for Page Up and Page Down. -->
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
|
||||
<div bind:this={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF page. Use Page Up and Page Down to change pages.")} onkeydown={pageKey}>
|
||||
<div bind:this={sheet} class="sheet"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.pdf-viewer { display: flex; flex-direction: column; height: 100%; min-height: 240px; min-width: 0; color: var(--rs-text); font-size: 13px; }
|
||||
/* 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); }
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 8px; border-bottom: 1px solid var(--rs-border); }
|
||||
.page { box-sizing: border-box; width: 64px; height: 28px; margin-left: 4px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: right; }
|
||||
.page:disabled, .zoom:disabled { color: var(--rs-text-dim); }
|
||||
.page:disabled { color: var(--rs-text-dim); }
|
||||
.count { margin: 0 4px; color: var(--rs-text-dim); white-space: nowrap; }
|
||||
.separator { width: 1px; height: 18px; margin: 0 4px; background: var(--rs-border); }
|
||||
.zoom { box-sizing: border-box; width: 60px; height: 28px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: center; }
|
||||
.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; }
|
||||
.zoom { min-width: 44px; color: var(--rs-text-dim); text-align: center; white-space: nowrap; }
|
||||
.status { margin: 0; padding: 4px 12px; font-size: 12px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
|
||||
.status.alert { color: var(--rs-error); }
|
||||
.password { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); }
|
||||
.password { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; }
|
||||
.password input { box-sizing: border-box; height: 28px; margin-left: 4px; padding: 2px 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; }
|
||||
.text-button:hover { background: var(--rs-bg-active); }
|
||||
/* 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 { flex: 1; min-height: 0; overflow: auto; padding: 16px; }
|
||||
.scroll:focus-visible { outline-offset: -2px; }
|
||||
.pages { display: flex; flex-direction: column; align-items: center; gap: 12px; width: max-content; min-width: 100%; }
|
||||
/* A PDF page is paper: white in both themes. */
|
||||
.sheet { position: relative; flex: none; background: white; box-shadow: 0 2px 10px #0003; }
|
||||
.sheet :global(canvas) { display: block; width: 100%; height: 100%; }
|
||||
.sheet { position: relative; margin: 0 auto; background: white; box-shadow: 0 2px 10px #0003; }
|
||||
.sheet :global(canvas) { display: block; }
|
||||
/* The text layer geometry follows the viewer styles of PDF.js 6 (Apache-2.0). See THIRD_PARTY_NOTICES.md. */
|
||||
.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; }
|
||||
|
||||
@@ -29,60 +29,3 @@ export function nextRotation(rotation: number): number {
|
||||
export function outputScale(width: number, height: number, deviceScale: number): number {
|
||||
return Math.min(deviceScale || 1, 2, 8192 / width, 8192 / height, Math.sqrt(16_000_000 / (width * height)));
|
||||
}
|
||||
|
||||
/** The space around the pages and between two pages, in CSS pixels. `PdfViewer.svelte` uses the same values in its styles. */
|
||||
export const PAGE_MARGIN = 16;
|
||||
export const PAGE_GAP = 12;
|
||||
|
||||
/** The size of a page at zoom 1, with the rotation of the file. */
|
||||
export interface PageSize { width: number; height: number }
|
||||
/** The place of a page in the column of pages, in whole CSS pixels. */
|
||||
export interface PageBox { top: number; width: number; height: number }
|
||||
|
||||
/** The zoom factor for typed text such as "150" or "150 %". Text that is not a number gives null. */
|
||||
export function zoomFromText(text: string): number | null {
|
||||
const value = Number(text.replace("%", "").replace(",", ".").trim());
|
||||
return text.trim() && Number.isFinite(value) && value > 0 ? zoomLevel(value / 100) : null;
|
||||
}
|
||||
|
||||
/** The zoom that fits the widest page in `available` pixels. */
|
||||
export function fitZoom(sizes: readonly PageSize[], rotation: number, available: number): number {
|
||||
const turned = rotation % 180 !== 0;
|
||||
const widest = Math.max(0, ...sizes.map(size => turned ? size.height : size.width));
|
||||
return zoomLevel(widest > 0 ? available / widest : 1);
|
||||
}
|
||||
|
||||
/** One box for each page, from the top of the column to the bottom. */
|
||||
export function pageBoxes(sizes: readonly PageSize[], zoom: number, rotation: number): PageBox[] {
|
||||
const turned = rotation % 180 !== 0;
|
||||
let top = PAGE_MARGIN;
|
||||
return sizes.map(size => {
|
||||
const width = Math.max(1, Math.floor((turned ? size.height : size.width) * zoom));
|
||||
const height = Math.max(1, Math.floor((turned ? size.width : size.height) * zoom));
|
||||
const box = { top, width, height };
|
||||
top += height + PAGE_GAP;
|
||||
return box;
|
||||
});
|
||||
}
|
||||
|
||||
/** The numbers of the pages that touch the range from `from` to `to`. */
|
||||
export function pagesInRange(boxes: readonly PageBox[], from: number, to: number): number[] {
|
||||
const pages: number[] = [];
|
||||
for (let index = 0; index < boxes.length; index++) {
|
||||
if (boxes[index].top >= to) break;
|
||||
if (boxes[index].top + boxes[index].height > from) pages.push(index + 1);
|
||||
}
|
||||
return pages;
|
||||
}
|
||||
|
||||
/** The number of the page that shows the most in the range from `from` to `to`. The first such page wins. */
|
||||
export function mostVisiblePage(boxes: readonly PageBox[], from: number, to: number): number {
|
||||
let page = 1, most = 0;
|
||||
for (let index = 0; index < boxes.length; index++) {
|
||||
const { top, height } = boxes[index];
|
||||
if (top >= to) break;
|
||||
const shown = Math.min(top + height, to) - Math.max(top, from);
|
||||
if (shown > most) { most = shown; page = index + 1; }
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
@@ -1,77 +1,34 @@
|
||||
import type { Workspace } from "../model/model.ts";
|
||||
import { readOptional, saveDocument } from "./persistence.ts";
|
||||
import { message } from "./message.ts";
|
||||
import { imagePath, parseImage } from "./images.ts";
|
||||
|
||||
const invalidDraft = () => new Error(message("The description draft is invalid. Preserve it before recovery."));
|
||||
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.
|
||||
*/
|
||||
/** A draft is separate from the saved card and uses compare-and-write protection. */
|
||||
export class DescriptionDraft {
|
||||
private source: string | null = null;
|
||||
private imageSource: string | null = null;
|
||||
private images: ReadonlyMap<string, string> = new Map();
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
readonly path: string;
|
||||
readonly imagesPath: string;
|
||||
private workspace: Workspace;
|
||||
constructor(workspace: Workspace, id: string) {
|
||||
this.workspace = workspace;
|
||||
const key = Array.from(new TextEncoder().encode(id), byte => byte.toString(16).padStart(2, "0")).join("");
|
||||
this.path = `.runestone/pm/drafts/${key}.json`;
|
||||
this.imagesPath = `.runestone/pm/drafts/${key}.images.json`;
|
||||
}
|
||||
async load(): Promise<string | null> {
|
||||
this.source = await readOptional(this.workspace, this.path);
|
||||
if (this.source === null) return null;
|
||||
const value = JSON.parse(this.source);
|
||||
if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string"))
|
||||
throw invalidDraft();
|
||||
throw new Error(message("The description draft is invalid. Preserve it before recovery."));
|
||||
return value.body;
|
||||
}
|
||||
/** The image data of the draft, by image ID. A draft of an earlier version has no image record. Call this before `save`. */
|
||||
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> {
|
||||
save(body: string | null): Promise<void> {
|
||||
const write = this.queue.then(async () => {
|
||||
const next = body === null ? new Map<string, string>() : images;
|
||||
// Keep the old and the new image data until the text is saved, so that each saved reference has its data.
|
||||
await this.saveImages(new Map([...this.images, ...next]));
|
||||
const source = JSON.stringify({ schema: 1, body }) + "\n";
|
||||
if (source !== this.source && !(body === null && this.source === null)) {
|
||||
if (source === this.source || (body === null && this.source === null)) return;
|
||||
await saveDocument(this.workspace, this.path, source, this.source);
|
||||
this.source = source;
|
||||
}
|
||||
await this.saveImages(next);
|
||||
});
|
||||
this.queue = write.catch(() => {});
|
||||
return write;
|
||||
}
|
||||
private async saveImages(images: ReadonlyMap<string, string>) {
|
||||
if (sameImages(images, this.images) || (!images.size && this.imageSource === null)) return;
|
||||
const sorted = [...images].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
||||
const source = JSON.stringify({ schema: 1, images: Object.fromEntries(sorted) }) + "\n";
|
||||
await saveDocument(this.workspace, this.imagesPath, source, this.imageSource);
|
||||
this.imageSource = source;
|
||||
this.images = new Map(images);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,16 +51,13 @@ export function parseImage(source: string): string {
|
||||
throw new Error(message("The saved image is invalid or exceeds 50 MiB."));
|
||||
return value.data;
|
||||
}
|
||||
/** Write the pending images that `body`, `attachments`, or `ids` refer to. Returns the IDs of the written images. */
|
||||
export async function saveImages(
|
||||
workspace: Workspace,
|
||||
body: string,
|
||||
pending: ReadonlyMap<string, string>,
|
||||
pending: Map<string, string>,
|
||||
attachments: TaskFields["attachments"] = [],
|
||||
ids: string[] = [],
|
||||
) {
|
||||
const saved: string[] = [];
|
||||
for (const id of new Set([...[...imageReferences(body), ...attachments].map((image) => image.id), ...ids])) {
|
||||
for (const id of new Set([...imageReferences(body), ...attachments].map((image) => image.id))) {
|
||||
const data = pending.get(id);
|
||||
if (!data) continue;
|
||||
const source = JSON.stringify({ schema: 1, data }) + "\n";
|
||||
@@ -69,7 +66,5 @@ export async function saveImages(
|
||||
// Retrying a failed card save reuses its complete image files.
|
||||
const previous = await workspace.readOptional?.(path);
|
||||
if (previous !== source) await saveDocument(workspace, path, source, null);
|
||||
saved.push(id);
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
|
||||
@@ -11,30 +11,6 @@ import {
|
||||
parseImage,
|
||||
saveImages,
|
||||
} from "../storage/images.ts";
|
||||
import { workspaceDownloadImage } from "../../../workspace/api.ts";
|
||||
import { copiedImage } from "../../../workspace/copiedImage.ts";
|
||||
import { mayAnimate, pastedImageSource } from "../../../workspace/media.ts";
|
||||
|
||||
async function fileDataUrl(file: File) {
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
let binary = "";
|
||||
for (let offset = 0; offset < bytes.length; offset += 8192)
|
||||
binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
|
||||
return `data:${file.type};base64,${btoa(binary)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The original of a copied web image. The RuneStone browser keeps the bytes of the image that it copied.
|
||||
* For a copy from another browser, download the original of a format with frames.
|
||||
* Undefined keeps the still copy. "refused" means that the website did not give the original.
|
||||
*/
|
||||
async function webImage(source: string): Promise<{ data: string; type: string } | "refused" | undefined> {
|
||||
const data = await copiedImage(source) ?? (mayAnimate(source) ? await workspaceDownloadImage(source).catch(() => "") : undefined);
|
||||
if (data === undefined) return undefined;
|
||||
if (!data) return "refused";
|
||||
const type = /^data:([^;]+);/.exec(data)?.[1] ?? "";
|
||||
return imageTypes.includes(type) ? { data, type } : undefined;
|
||||
}
|
||||
|
||||
/** The image data stays outside the card Markdown and loads only in the open editor. */
|
||||
export function createCardImages(
|
||||
@@ -250,8 +226,7 @@ export function createCardImages(
|
||||
}
|
||||
}
|
||||
}
|
||||
/** `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) {
|
||||
async function addFiles(files: File[], attachOnly = false) {
|
||||
if (disposed || loading || description.disabled || !files.length) return;
|
||||
loading = true;
|
||||
updateControls();
|
||||
@@ -262,20 +237,18 @@ export function createCardImages(
|
||||
end = description.selectionEnd;
|
||||
try {
|
||||
const staged: { id: string; name: string; data: string }[] = [];
|
||||
let refused = false;
|
||||
for (const file of files) {
|
||||
// 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))
|
||||
if (!imageTypes.includes(file.type))
|
||||
throw new Error(message("Use a PNG, JPEG, GIF, or WebP image."));
|
||||
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)
|
||||
if (!file.size || file.size > maxImageBytes)
|
||||
throw new Error(message("Use an image between 1 byte and 50 MiB."));
|
||||
const data = original?.data ?? await fileDataUrl(file);
|
||||
const name = original ? `${(file.name || "image").replace(/\.\w+$/, "")}.${original.type.slice(6)}` : file.name;
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
let binary = "";
|
||||
for (let offset = 0; offset < bytes.length; offset += 8192)
|
||||
binary += String.fromCharCode(
|
||||
...bytes.subarray(offset, offset + 8192),
|
||||
);
|
||||
const data = `data:${file.type};base64,${btoa(binary)}`;
|
||||
// Decode the image before the reference goes in, so that an invalid clipboard file keeps the draft.
|
||||
const image = new Image();
|
||||
image.src = data;
|
||||
@@ -284,7 +257,7 @@ export function createCardImages(
|
||||
});
|
||||
staged.push({
|
||||
id: crypto.randomUUID(),
|
||||
name: (name || tr("Pasted image")).slice(0, 255),
|
||||
name: (file.name || tr("Pasted image")).slice(0, 255),
|
||||
data,
|
||||
});
|
||||
}
|
||||
@@ -296,7 +269,6 @@ export function createCardImages(
|
||||
description.setRangeText(`\n${markdown}\n`, start, end, "end");
|
||||
}
|
||||
description.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
if (refused) error.textContent = tr("The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file.");
|
||||
} catch (reason) {
|
||||
if (!disposed)
|
||||
(attachOnly ? attachmentError : error).textContent = errorText(reason);
|
||||
@@ -316,9 +288,7 @@ export function createCardImages(
|
||||
if (!files.length) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
// 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);
|
||||
void addFiles(files);
|
||||
};
|
||||
const dragOver = (event: DragEvent) => {
|
||||
if (event.dataTransfer?.types.includes("Files")) {
|
||||
@@ -369,26 +339,7 @@ export function createCardImages(
|
||||
saving = value;
|
||||
updateControls();
|
||||
},
|
||||
/** 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();
|
||||
},
|
||||
save: (body: string) => saveImages(workspace, body, pending, attachments),
|
||||
dispose() {
|
||||
disposed = true;
|
||||
clearTimeout(idleTimer);
|
||||
@@ -396,7 +347,7 @@ export function createCardImages(
|
||||
viewerObserver = undefined;
|
||||
viewer?.remove(); viewer = undefined;
|
||||
revision++;
|
||||
// Keep the pending image data. A draft save that is in progress after a close still needs it.
|
||||
pending.clear();
|
||||
loaded.clear();
|
||||
description.removeEventListener("paste", paste);
|
||||
description.removeEventListener("input", render);
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
cursor: default;
|
||||
}
|
||||
.rs-pm button:not(.rs-picker-row):not([role^="menuitem"]):focus-visible,
|
||||
.rs-pm input:not(:where(.rs-find-bar input)):focus-visible,
|
||||
.rs-pm input:not(.rs-find-bar input):focus-visible,
|
||||
.rs-pm select:focus-visible,
|
||||
.rs-pm textarea:focus-visible {
|
||||
outline: 1px solid var(--pm-accent);
|
||||
@@ -196,8 +196,7 @@
|
||||
.pm-search-row input {
|
||||
width: min(340px, 100%);
|
||||
}
|
||||
/* 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 input:not(.rs-find-bar input),
|
||||
.rs-pm select,
|
||||
.rs-pm textarea {
|
||||
background: var(--pm-field-surface);
|
||||
@@ -206,7 +205,7 @@
|
||||
padding: 6px 8px;
|
||||
min-height: 30px;
|
||||
}
|
||||
.rs-pm input[type="checkbox"]:not(:where(.rs-find-bar input)) {
|
||||
.rs-pm input[type="checkbox"]:not(.rs-find-bar input) {
|
||||
min-height: 0;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
|
||||
@@ -1051,11 +1051,7 @@ export function mountPM(
|
||||
description,
|
||||
(name, action) => button(tr(name), action, name === "Actual size" ? "expand" : "image"),
|
||||
(name, action) => iconButton(name, "close", action),
|
||||
(loading) => {
|
||||
save.disabled = loading || busy || !title.value.trim(); descriptionEditor.updateLoading();
|
||||
// The input event of a pasted image comes while the image loads. Save the draft after the load.
|
||||
if (!loading) scheduleDraft();
|
||||
},
|
||||
(loading) => { save.disabled = loading || busy || !title.value.trim(); descriptionEditor.updateLoading(); },
|
||||
task?.attachments,
|
||||
);
|
||||
const formattingIcons: Record<string, keyof typeof icons> = {
|
||||
@@ -1068,10 +1064,9 @@ export function mountPM(
|
||||
let descriptionSaving = false;
|
||||
let draftTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let draftEdited = false;
|
||||
const draftReady = draft && Promise.all([draft.load(), draft.loadImages()]).then(([body, draftImages]) => {
|
||||
const draftReady = draft?.load().then(body => {
|
||||
if (body !== null && !draftEdited && dialog.isConnected) {
|
||||
descriptionEditor.restoreDraft(body);
|
||||
images.restore(draftImages);
|
||||
updateDescriptionBadge(task!.id, body !== task!.body);
|
||||
}
|
||||
});
|
||||
@@ -1079,13 +1074,8 @@ export function mountPM(
|
||||
clearTimeout(draftTimer);
|
||||
await draftReady;
|
||||
if (!draft || !task) return;
|
||||
const body = description.value;
|
||||
// The draft keeps the data of its unsaved images. The image files come only with a save of the description or the card.
|
||||
await draft.save(body === task.body ? null : body, images.draftImages(body));
|
||||
};
|
||||
const scheduleDraft = () => {
|
||||
clearTimeout(draftTimer);
|
||||
if (draft && !images.isLoading()) draftTimer = setTimeout(() => { void flushDraft().catch(reportDraftError); }, 300);
|
||||
await images.save(description.value);
|
||||
await draft.save(description.value === task.body ? null : description.value);
|
||||
};
|
||||
const reportDraftError = (reason: unknown) => { error.textContent = errorText(reason); };
|
||||
void draftReady?.catch(reportDraftError);
|
||||
@@ -1123,7 +1113,8 @@ export function mountPM(
|
||||
description.addEventListener("input", () => {
|
||||
draftEdited = true;
|
||||
if (task) updateDescriptionBadge(task.id, description.value !== task.body);
|
||||
scheduleDraft();
|
||||
clearTimeout(draftTimer);
|
||||
if (draft && !images.isLoading()) draftTimer = setTimeout(() => { void flushDraft().catch(reportDraftError); }, 300);
|
||||
});
|
||||
const useSharedChoices = sharedChoice;
|
||||
const updateChoice = sharedChoices.update;
|
||||
@@ -1558,8 +1549,7 @@ export function mountPM(
|
||||
const ok = await perform(
|
||||
async () => {
|
||||
await flushDraft();
|
||||
// The cover can be an image that only the description draft has.
|
||||
await images.save(body, cover.value ? [cover.value] : []);
|
||||
await images.save(body);
|
||||
const existingIds = new Set(store.tasks.map(candidate => candidate.id));
|
||||
await (task && boardSelect.value && (boardSelect.value !== originalBoardId || (!store.board.reference && listChanged))
|
||||
? store.saveToBoard(task, boardSelect.value, listSelect.value || null, { ...fields, body })
|
||||
|
||||
@@ -1020,10 +1020,10 @@ export const messageRows: [string, string, string, string][] = [
|
||||
"阅读"
|
||||
],
|
||||
[
|
||||
"Read beside",
|
||||
"Lire à côté",
|
||||
"横に閲覧",
|
||||
"并排阅读"
|
||||
"Split",
|
||||
"Diviser",
|
||||
"分割",
|
||||
"分栏"
|
||||
],
|
||||
[
|
||||
"Editor",
|
||||
@@ -1679,12 +1679,6 @@ export const messageRows: [string, string, string, string][] = [
|
||||
"新しいタブでリンクを開く",
|
||||
"在新标签页中打开链接"
|
||||
],
|
||||
[
|
||||
"Open image in new tab",
|
||||
"Ouvrir l’image dans un nouvel onglet",
|
||||
"新しいタブで画像を開く",
|
||||
"在新标签页中打开图片"
|
||||
],
|
||||
[
|
||||
"Open link in default browser",
|
||||
"Ouvrir le lien dans le navigateur par défaut",
|
||||
@@ -3300,12 +3294,8 @@ export const messageRows: [string, string, string, string][] = [
|
||||
["The workspace changed. File moves stopped.", "L’espace de travail a changé. Les déplacements de fichiers sont arrêtés.", "ワークスペースが変更されました。ファイルの移動を停止しました。", "工作区已更改。文件移动已停止。"],
|
||||
["The workspace changed. Paste stopped.", "L’espace de travail a changé. Le collage est arrêté.", "ワークスペースが変更されました。貼り付けを停止しました。", "工作区已更改。粘贴已停止。"],
|
||||
["Move to new window", "Déplacer vers une nouvelle fenêtre", "新しいウィンドウに移動", "移到新窗口"],
|
||||
["New tab to the right", "Nouvel onglet à droite", "右に新しいタブ", "在右侧新建标签页"],
|
||||
["New tab below", "Nouvel onglet en dessous", "下に新しいタブ", "在下方新建标签页"],
|
||||
["Resize panes", "Redimensionner les volets", "ペインのサイズを変更", "调整窗格大小"],
|
||||
["Drag to resize the panes. Double-click to give them equal sizes.", "Faites glisser pour redimensionner les volets. Double-cliquez pour leur donner la même taille.", "ドラッグしてペインのサイズを変更します。ダブルクリックすると同じサイズになります。", "拖动以调整窗格大小。双击使窗格大小相同。"],
|
||||
["Show here", "Afficher ici", "ここに表示", "在此显示"],
|
||||
["Open below", "Ouvrir en dessous", "下に開く", "在下方打开"],
|
||||
["Split right", "Scinder à droite", "右に分割", "向右拆分"],
|
||||
["Split down", "Scinder vers le bas", "下に分割", "向下拆分"],
|
||||
["Find…", "Rechercher…", "検索…", "查找…"],
|
||||
["Open in default browser", "Ouvrir dans le navigateur par défaut", "既定のブラウザーで開く", "在默认浏览器中打开"],
|
||||
["Invalid browser tab transfer.", "Transfert d’onglet de navigateur non valide.", "ブラウザータブの移動が無効です。", "浏览器标签页转移无效。"],
|
||||
@@ -3380,7 +3370,7 @@ export const messageRows: [string, string, string, string][] = [
|
||||
["Show the file name above each Markdown note in Write and Read.", "Afficher le nom du fichier au-dessus de chaque note Markdown dans Écrire et Lire.", "「書く」と「閲覧」で、各 Markdown ノートの上にファイル名を表示します。", "在“写作”和“阅读”中,在每篇 Markdown 笔记上方显示文件名。"],
|
||||
["Source", "Source", "ソース", "源码"],
|
||||
["View", "Affichage", "表示", "视图"],
|
||||
["Read beside: show the Read view beside the editor", "Lire à côté : afficher Lire à côté de l’éditeur", "横に閲覧: エディターの横に閲覧を表示", "并排阅读:在编辑器旁显示阅读"],
|
||||
["Split: Read beside the editor", "Diviser : Lire à côté de l’éditeur", "分割: エディターの横に閲覧を表示", "分栏:在编辑器旁显示阅读"],
|
||||
["Switch between Write and Source", "Alterner entre Écrire et Source", "「書く」と「ソース」を切り替え", "在写作和源码之间切换"],
|
||||
["Switch between Read and the editor", "Alterner entre Lire et l’éditeur", "「閲覧」とエディターを切り替え", "在阅读和编辑器之间切换"],
|
||||
["Unsaved", "Non enregistré", "未保存", "未保存"],
|
||||
@@ -3458,7 +3448,6 @@ export const messageRows: [string, string, string, string][] = [
|
||||
["Commit created.", "Commit créé.", "コミットを作成しました。", "已创建提交。"],
|
||||
["Changes ({count})", "Modifications ({count})", "変更 ({count})", "更改 ({count})"],
|
||||
["Staged changes ({count})", "Modifications indexées ({count})", "ステージ済みの変更 ({count})", "已暂存的更改 ({count})"],
|
||||
["Unstaged changes ({count})", "Modifications non indexées ({count})", "未ステージの変更 ({count})", "未暂存的更改 ({count})"],
|
||||
["Stage all", "Tout indexer", "すべてステージ", "全部暂存"],
|
||||
["Unstage all", "Tout désindexer", "すべてステージ解除", "全部取消暂存"],
|
||||
["Stage {path}", "Indexer {path}", "{path} をステージ", "暂存 {path}"],
|
||||
@@ -3684,8 +3673,7 @@ export const messageRows: [string, string, string, string][] = [
|
||||
["Loading page {page}…", "Chargement de la page {page}…", "{page} ページを読み込み中…", "正在加载第 {page} 页…"],
|
||||
["Page {page} of {count}", "Page {page} sur {count}", "{page} / {count} ページ", "第 {page} 页,共 {count} 页"],
|
||||
["PDF page {page}", "Page PDF {page}", "PDF の {page} ページ", "PDF 第 {page} 页"],
|
||||
["PDF pages", "Pages du PDF", "PDF のページ", "PDF 页面"],
|
||||
["Zoom percent", "Pourcentage de zoom", "ズームの倍率", "缩放百分比"],
|
||||
["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 password", "Mot de passe du PDF", "PDF のパスワード", "PDF 密码"],
|
||||
["Unlock", "Déverrouiller", "ロック解除", "解锁"],
|
||||
["This PDF needs a password.", "Ce PDF nécessite un mot de passe.", "この PDF にはパスワードが必要です。", "此 PDF 需要密码。"],
|
||||
@@ -4076,8 +4064,6 @@ export const messageRows: [string, string, string, string][] = [
|
||||
["Unlink {name}", "Délier {name}", "{name} のリンクを解除", "取消关联 {name}"],
|
||||
["Unsaved changes", "Modifications non enregistrées", "未保存の変更", "未保存的更改"],
|
||||
["Use a PNG, JPEG, GIF, or WebP image.", "Utilisez une image PNG, JPEG, GIF ou WebP.", "PNG、JPEG、GIF、WebP のいずれかの画像を使用してください。", "请使用 PNG、JPEG、GIF 或 WebP 图片。"],
|
||||
["The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file.", "Le site web a refusé l’image d’origine. RuneStone n’en a donc ajouté que la première trame. Pour conserver l’animation, copiez l’image dans le navigateur de RuneStone. Vous pouvez aussi enregistrer l’image, puis ajouter le fichier enregistré.", "Web サイトが元の画像を拒否したため、RuneStone は最初のフレームだけを追加しました。アニメーションを保つには、RuneStone のブラウザーで画像をコピーしてください。画像を保存して、保存したファイルを追加することもできます。", "网站拒绝提供原始图片,因此 RuneStone 只添加了第一帧。要保留动画,请在 RuneStone 浏览器中复制图片。也可以保存图片,然后添加保存的文件。"],
|
||||
["The image file is empty. A browser can give an empty file when the website refuses a download. To add the image, copy it in the RuneStone browser. You can also save the image and add the saved file.", "Le fichier image est vide. Un navigateur peut fournir un fichier vide quand le site web refuse un téléchargement. Pour ajouter l’image, copiez-la dans le navigateur de RuneStone. Vous pouvez aussi enregistrer l’image, puis ajouter le fichier enregistré.", "画像ファイルが空です。Web サイトがダウンロードを拒否すると、ブラウザーが空のファイルを渡すことがあります。画像を追加するには、RuneStone のブラウザーでコピーしてください。画像を保存して、保存したファイルを追加することもできます。", "图片文件为空。网站拒绝下载时,浏览器可能会提供空文件。要添加图片,请在 RuneStone 浏览器中复制它。也可以保存图片,然后添加保存的文件。"],
|
||||
["Use an image between 1 byte and 50 MiB.", "Utilisez une image entre 1 octet et 50 Mio.", "1 バイトから 50 MiB までの画像を使用してください。", "请使用 1 字节到 50 MiB 之间的图片。"],
|
||||
["View image {name}", "Afficher l’image {name}", "画像 {name} を表示", "查看图片 {name}"],
|
||||
["When you save, RuneStone removes each deleted label from all cards.", "Lors de l’enregistrement, RuneStone retire chaque étiquette supprimée de toutes les cartes.", "保存すると、RuneStone は削除したラベルをすべてのカードから外します。", "保存时,RuneStone 会从所有卡片中移除每个已删除的标签。"],
|
||||
|
||||
@@ -11,10 +11,9 @@
|
||||
error?: string | null;
|
||||
onOpen: (entry: Backlink) => void;
|
||||
onRebuild?: () => void;
|
||||
/** The owner keeps this value, so the choice survives when the section closes with its tab. */
|
||||
expanded?: boolean;
|
||||
};
|
||||
let { entries, busy = false, error = null, onOpen, onRebuild, expanded = $bindable(true) }: Props = $props();
|
||||
let { entries, busy = false, error = null, onOpen, onRebuild }: Props = $props();
|
||||
let expanded = $state(true);
|
||||
const contentId = $props.id();
|
||||
function collapseTooltip(node: HTMLElement) {
|
||||
return { destroy: attachTooltip(node, () => $t(expanded ? "Collapse backlinks" : "Expand backlinks")) };
|
||||
@@ -72,7 +71,7 @@
|
||||
.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; }
|
||||
.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-hover-bg); }
|
||||
.toggle:hover, .source:hover { background: var(--rs-bg-active); }
|
||||
.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 { color: var(--rs-text-dim); }
|
||||
|
||||
@@ -94,7 +94,7 @@
|
||||
}
|
||||
|
||||
li > button:hover {
|
||||
background: var(--rs-hover-bg);
|
||||
background: var(--rs-bg-active);
|
||||
color: var(--rs-text-strong);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,35 +1,26 @@
|
||||
<script lang="ts">
|
||||
// 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.
|
||||
// The document area: plugin editor panes over the document panes, with the save conflict banner of each document.
|
||||
import type { ComponentProps } from "svelte";
|
||||
import { t } from "$lib/i18n";
|
||||
import PluginEditor from "$lib/plugins/PluginEditor.svelte";
|
||||
import { pluginEditors, pluginView, selectPluginEditor, type OpenPluginView } from "$lib/plugins/external";
|
||||
import { pluginEditors, pluginView, selectPluginEditor } from "$lib/plugins/external";
|
||||
import type { Documents } from "$lib/workspace/documents.svelte";
|
||||
import type { OpenBuffer } from "$lib/workspace/types";
|
||||
import EditorPane from "./EditorPane.svelte";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import { paneBounds, splitDividers, stackLayout, type SplitDivider, type SplitLayout, type SplitPath } from "$lib/workspace/splitLayout";
|
||||
import type { PaneDrop } from "$lib/workspace/documentPanes";
|
||||
import { attachTooltip } from "$lib/ui/tooltip";
|
||||
import type { ViewMode } from "./ViewModes.svelte";
|
||||
import TabBar from "./TabBar.svelte";
|
||||
|
||||
type EditorProps = ComponentProps<typeof EditorPane>;
|
||||
type DocumentView = { id: string; reading: boolean; split: boolean; buffer: OpenBuffer | null; pluginKey: string | null };
|
||||
/** The pane under a dragged tab, and the place of the drop on it. */
|
||||
type DropTarget = { pane: string; zone: PaneDrop };
|
||||
type DocumentView = { id: string; reading: boolean; split: boolean; buffer: OpenBuffer | null; bounds: { width: number } };
|
||||
type Bounds = { left: number; top: number; width: number; height: number };
|
||||
type Props = {
|
||||
/** The focused plugin view covers the whole area. */
|
||||
pluginCover: boolean;
|
||||
/** The drop hint of a dragged tab. */
|
||||
drop: DropTarget | null;
|
||||
onResize: (path: SplitPath, ratio: number) => void;
|
||||
editorPluginVisible: boolean;
|
||||
split: boolean;
|
||||
pluginBounds: Record<string, Bounds | undefined>;
|
||||
tabBar: ComponentProps<typeof TabBar>;
|
||||
pluginPaneComponents: Record<string, PluginEditor | undefined>;
|
||||
documentViews: DocumentView[];
|
||||
layout: SplitLayout;
|
||||
activePane: string;
|
||||
paneComponents: Record<string, EditorPane | undefined>;
|
||||
documents: Documents | null;
|
||||
@@ -46,7 +37,7 @@
|
||||
onQuickOpen: () => void;
|
||||
onOpenBrowser?: () => void;
|
||||
onChange: EditorProps["onChange"];
|
||||
onInsertImage: (file: File, buffer: OpenBuffer | null, source?: string) => Promise<string | null>;
|
||||
onInsertImage: (file: File, buffer: OpenBuffer | null) => Promise<string | null>;
|
||||
onRenameTitle: EditorProps["onRenameTitle"];
|
||||
tableActions: (pane: DocumentView) => EditorProps["tableActions"];
|
||||
linkActions: (pane: DocumentView) => EditorProps["linkActions"];
|
||||
@@ -55,112 +46,37 @@
|
||||
onCursor: (pane: DocumentView, line: number, column: number) => void;
|
||||
onOpenLink: (pane: DocumentView, kind: "md" | "wiki", target: string) => void;
|
||||
};
|
||||
let { pluginCover, drop, onResize, pluginPaneComponents = $bindable(), documentViews, layout, activePane, paneComponents = $bindable(),
|
||||
let { editorPluginVisible, split, pluginBounds, tabBar, pluginPaneComponents = $bindable(), documentViews, activePane, paneComponents = $bindable(),
|
||||
documents, tabs, hasWorkspace, browserOpening, focusLine, onFocusPane, onCloseSplit, onSaveCopy, onOpenWorkspace, onNewFile, onNewNote,
|
||||
onQuickOpen, onOpenBrowser, onChange, onInsertImage, onRenameTitle, tableActions, linkActions, onView, onSplitView, onCursor, onOpenLink }: Props = $props();
|
||||
|
||||
// A narrow area shows the panes one above the other, in the same order.
|
||||
let width = $state(0);
|
||||
const stacked = $derived(width > 0 && width <= 640);
|
||||
const bounds = $derived(paneBounds(stacked ? stackLayout(layout) : layout));
|
||||
const hosts = $derived(new Map(documentViews.flatMap(pane => pane.pluginKey ? [[pane.pluginKey, pane.id] as const] : [])));
|
||||
const several = $derived(documentViews.length > 1);
|
||||
function focusPlugin(view: OpenPluginView, host: string | undefined) {
|
||||
if (host) onFocusPane(host);
|
||||
else if ($pluginView?.key !== view.key) selectPluginEditor(view);
|
||||
}
|
||||
|
||||
let area: HTMLElement;
|
||||
const full = { left: 0, top: 0, width: 100, height: 100 };
|
||||
const dividers = $derived(pluginCover || !several ? [] : splitDividers(stacked ? stackLayout(layout) : layout));
|
||||
/** The place of the divider: the line between the two sides of its split, in percent of the area. */
|
||||
function dividerStyle(divider: SplitDivider) {
|
||||
const { bounds: box, ratio } = divider;
|
||||
return divider.direction === "right"
|
||||
? `left:${box.left + box.width * ratio}%;top:${box.top}%;height:${box.height}%`
|
||||
: `top:${box.top + box.height * ratio}%;left:${box.left}%;width:${box.width}%`;
|
||||
}
|
||||
function ratioAt(divider: SplitDivider, x: number, y: number) {
|
||||
const rect = area.getBoundingClientRect(), box = divider.bounds;
|
||||
return divider.direction === "right"
|
||||
? (x - rect.left - rect.width * box.left / 100) / (rect.width * box.width / 100)
|
||||
: (y - rect.top - rect.height * box.top / 100) / (rect.height * box.height / 100);
|
||||
}
|
||||
let resizing = $state<"right" | "down" | null>(null);
|
||||
function startResize(event: PointerEvent, divider: SplitDivider) {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
const handle = event.currentTarget as HTMLElement;
|
||||
handle.setPointerCapture(event.pointerId);
|
||||
handle.focus({ preventScroll: true });
|
||||
resizing = divider.direction;
|
||||
const move = (next: PointerEvent) => onResize(divider.path, ratioAt(divider, next.clientX, next.clientY));
|
||||
const end = () => {
|
||||
resizing = null;
|
||||
handle.removeEventListener("pointermove", move);
|
||||
handle.removeEventListener("pointerup", end);
|
||||
handle.removeEventListener("pointercancel", end);
|
||||
};
|
||||
handle.addEventListener("pointermove", move);
|
||||
handle.addEventListener("pointerup", end);
|
||||
handle.addEventListener("pointercancel", end);
|
||||
}
|
||||
function resizeKey(event: KeyboardEvent, divider: SplitDivider) {
|
||||
const steps: Record<string, number> = divider.direction === "right" ? { ArrowLeft: -0.05, ArrowRight: 0.05 } : { ArrowUp: -0.05, ArrowDown: 0.05 };
|
||||
if (event.key in steps) onResize(divider.path, divider.ratio + steps[event.key]);
|
||||
else if (event.key === "Home") onResize(divider.path, 0.1);
|
||||
else if (event.key === "End") onResize(divider.path, 0.9);
|
||||
else if (event.key === "Enter") onResize(divider.path, 0.5);
|
||||
else return;
|
||||
event.preventDefault();
|
||||
}
|
||||
function tooltip(node: HTMLElement, text: string) {
|
||||
let label = text;
|
||||
const dispose = attachTooltip(node, () => label);
|
||||
return { update(value: string) { label = value; }, destroy: dispose };
|
||||
}
|
||||
|
||||
/**
|
||||
* The drop target under a point: a pane, and the place on it. The right and bottom sides open a new pane.
|
||||
* While a plugin view covers the area, the area is one pane. A narrow area opens new panes only below.
|
||||
*/
|
||||
export function dropAt(x: number, y: number): DropTarget | null {
|
||||
const rect = area?.getBoundingClientRect();
|
||||
if (!rect || !rect.width || !rect.height || x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) return null;
|
||||
const px = (x - rect.left) / rect.width * 100, py = (y - rect.top) / rect.height * 100;
|
||||
const pane = pluginCover ? activePane : documentViews.find(view => {
|
||||
const box = bounds[view.id];
|
||||
return box && px >= box.left && px <= box.left + box.width && py >= box.top && py <= box.top + box.height;
|
||||
})?.id;
|
||||
const box = pane ? (pluginCover ? full : bounds[pane]) : undefined;
|
||||
if (!pane || !box) return null;
|
||||
const rx = (px - box.left) / box.width, ry = (py - box.top) / box.height;
|
||||
return { pane, zone: rx > 0.7 && !stacked ? "right" : ry > 0.7 ? "down" : "center" };
|
||||
}
|
||||
const dropBox = $derived.by(() => {
|
||||
if (!drop) return null;
|
||||
const box = pluginCover ? full : bounds[drop.pane];
|
||||
if (!box) return null;
|
||||
if (drop.zone === "right") return { ...box, left: box.left + box.width / 2, width: box.width / 2 };
|
||||
if (drop.zone === "down") return { ...box, top: box.top + box.height / 2, height: box.height / 2 };
|
||||
return box;
|
||||
});
|
||||
</script>
|
||||
|
||||
<main class="center" class:resizing={!!resizing} class:resizing-down={resizing === "down"} bind:this={area} bind:clientWidth={width}>
|
||||
<div class="editor-host" class:plugin-covered={pluginCover}>
|
||||
<div class="document-panes" class:split={several}>
|
||||
<main class="center">
|
||||
<div class="plugin-panes" class:inactive={!editorPluginVisible}>
|
||||
{#each $pluginEditors as pane (pane.key)}
|
||||
{@const bounds = pluginBounds[pane.key]}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions (Focus selects the pane that owns the input.) -->
|
||||
<div class="plugin-pane" class:inactive={!bounds} class:split class:focused={$pluginView?.key === pane.key}
|
||||
style:left={`${bounds?.left ?? 0}%`} style:top={`${bounds?.top ?? 0}%`}
|
||||
style:width={`${bounds?.width ?? 100}%`} style:height={`${bounds?.height ?? 100}%`}
|
||||
onfocusin={() => { if ($pluginView?.key !== pane.key) selectPluginEditor(pane); }}
|
||||
onpointerdown={() => { if ($pluginView?.key !== pane.key) selectPluginEditor(pane); }}>
|
||||
{#if split && bounds}
|
||||
<TabBar {...tabBar} tabs={tabBar.tabs.filter(tab => tab.id === pane.key)} />
|
||||
{/if}
|
||||
<PluginEditor bind:this={pluginPaneComponents[pane.key]} view={pane} />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="editor-host" class:plugin-covered={editorPluginVisible}>
|
||||
<div class="document-panes" class:split={documentViews.length > 1}>
|
||||
{#each documentViews as pane (pane.id)}
|
||||
{@const box = bounds[pane.id]}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions (Focus identifies the document for shared commands.) -->
|
||||
<div class="document-pane" class:focused={activePane === pane.id} class:edge-left={(box?.left ?? 0) > 0} class:edge-top={(box?.top ?? 0) > 0}
|
||||
<div class="document-pane" class:focused={activePane === pane.id}
|
||||
data-document-pane={pane.id} data-document-path={pane.buffer?.relPath ?? ""}
|
||||
style:left={`${box?.left ?? 0}%`} style:top={`${box?.top ?? 0}%`}
|
||||
style:width={`${box?.width ?? 100}%`} style:height={`${box?.height ?? 100}%`}
|
||||
style:--pane-weight={pane.bounds.width}
|
||||
onpointerdowncapture={() => onFocusPane(pane.id)}
|
||||
onfocusin={() => onFocusPane(pane.id)}>
|
||||
<!-- A pane with a plugin view stays empty. The plugin layer shows the view over it. -->
|
||||
{#if !pane.pluginKey}
|
||||
{#if pane.buffer?.diskError}
|
||||
<div class="conflict" role="alert"><Icon icon="alert" /><span>{pane.buffer.diskError}</span><button class="primary" onclick={() => void documents?.refresh()}>{$t("Retry")}</button><button onclick={() => onSaveCopy(pane.buffer)}>{$t("Save a copy")}</button></div>
|
||||
{:else if pane.buffer?.diskContents != null}
|
||||
@@ -178,7 +94,7 @@
|
||||
bind:this={paneComponents[pane.id]}
|
||||
{tabs}
|
||||
active={activePane === pane.id}
|
||||
onCloseSplit={several ? () => onCloseSplit(pane.id) : undefined}
|
||||
onCloseSplit={documentViews.length > 1 ? () => onCloseSplit(pane.id) : undefined}
|
||||
{hasWorkspace}
|
||||
{onOpenWorkspace}
|
||||
{onNewFile}
|
||||
@@ -192,7 +108,7 @@
|
||||
split={pane.split}
|
||||
focusLine={activePane === pane.id ? focusLine : null}
|
||||
{onChange}
|
||||
onInsertImage={(file, source) => onInsertImage(file, pane.buffer, source)}
|
||||
onInsertImage={file => onInsertImage(file, pane.buffer)}
|
||||
{onRenameTitle}
|
||||
tableActions={tableActions(pane)}
|
||||
linkActions={linkActions(pane)}
|
||||
@@ -201,50 +117,10 @@
|
||||
onCursor={(line, column) => onCursor(pane, line, column)}
|
||||
onOpenLink={(kind, target) => onOpenLink(pane, kind, target)}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
<div class="plugin-panes">
|
||||
{#each $pluginEditors as view (view.key)}
|
||||
{@const host = pluginCover ? undefined : hosts.get(view.key)}
|
||||
{@const box = pluginCover ? ($pluginView?.key === view.key ? full : undefined) : host ? bounds[host] : undefined}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions (Focus selects the pane that owns the input.) -->
|
||||
<div class="plugin-pane" class:inactive={!box} class:embedded={!!host}
|
||||
class:focused={host ? activePane === host : $pluginView?.key === view.key}
|
||||
class:edge-left={!!host && (box?.left ?? 0) > 0} class:edge-top={!!host && (box?.top ?? 0) > 0}
|
||||
data-plugin-pane={view.key}
|
||||
style:left={`${box?.left ?? 0}%`} style:top={`${box?.top ?? 0}%`}
|
||||
style:width={`${box?.width ?? 100}%`} style:height={`${box?.height ?? 100}%`}
|
||||
onfocusin={() => focusPlugin(view, host)}
|
||||
onpointerdowncapture={() => focusPlugin(view, host)}>
|
||||
{#if host && several}
|
||||
<div class="pane-bar">
|
||||
<span class="pane-title" title={view.title}>{view.title}</span>
|
||||
<IconButton icon="close" label={$t("Close split")} onclick={() => onCloseSplit(host)} />
|
||||
</div>
|
||||
{/if}
|
||||
<PluginEditor bind:this={pluginPaneComponents[view.key]} {view} />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{#each dividers as divider (divider.path.join("/"))}
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (A focusable separator is the splitter pattern.) -->
|
||||
<div class="divider" class:vertical={divider.direction === "right"} style={dividerStyle(divider)}
|
||||
role="separator" tabindex="0" aria-label={$t("Resize panes")}
|
||||
aria-orientation={divider.direction === "right" ? "vertical" : "horizontal"}
|
||||
aria-valuemin={10} aria-valuemax={90} aria-valuenow={Math.round(divider.ratio * 100)}
|
||||
use:tooltip={$t("Drag to resize the panes. Double-click to give them equal sizes.")}
|
||||
onpointerdown={event => startResize(event, divider)}
|
||||
ondblclick={() => onResize(divider.path, 0.5)}
|
||||
onkeydown={event => resizeKey(event, divider)}></div>
|
||||
{/each}
|
||||
{#if dropBox && drop}
|
||||
<div class="drop-hint" data-drop-zone={drop.zone} style:left={`${dropBox.left}%`} style:top={`${dropBox.top}%`} style:width={`${dropBox.width}%`} style:height={`${dropBox.height}%`}>
|
||||
<span>{drop.zone === "center" ? $t("Show here") : drop.zone === "right" ? $t("Open to the right") : $t("Open below")}</span>
|
||||
</div>
|
||||
{/if}
|
||||
</main>
|
||||
|
||||
<style>
|
||||
@@ -264,7 +140,7 @@
|
||||
.conflict > :global(svg) { width: 18px; height: 18px; flex-shrink: 0; color: var(--rs-warn); }
|
||||
.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:hover { background: var(--rs-hover-bg); }
|
||||
.conflict button:hover { background: var(--rs-bg-active); }
|
||||
.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); }
|
||||
.disk-review { padding: 8px 12px; max-height: 35vh; overflow: auto; flex: 0 0 auto; }
|
||||
@@ -279,34 +155,19 @@
|
||||
container-type: inline-size;
|
||||
}
|
||||
|
||||
/* Each pane has its place in the split layout. A pane beside or below another pane has a border on that edge. */
|
||||
.document-panes { position: relative; flex: 1; min-height: 0; overflow: hidden; }
|
||||
.document-pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; overflow: hidden; box-sizing: border-box; }
|
||||
.edge-left { border-left: 1px solid var(--rs-border); }
|
||||
.edge-top { border-top: 1px solid var(--rs-border); }
|
||||
.document-panes { flex: 1; min-height: 0; display: flex; overflow: hidden; }
|
||||
.document-pane { flex: var(--pane-weight) 1 0; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
|
||||
.document-pane + .document-pane { border-left: 1px solid var(--rs-border); }
|
||||
.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; }
|
||||
/* The plugin layer covers the area, but only its visible panes take the pointer. */
|
||||
.plugin-panes { position: absolute; inset: 0; overflow: hidden; pointer-events: none; }
|
||||
.plugin-pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; box-sizing: border-box; pointer-events: auto; }
|
||||
.plugin-pane.embedded { background: var(--rs-bg); }
|
||||
.plugin-pane.inactive { display: none; }
|
||||
/* The bar of a plugin view in a pane matches the chrome bar of a document pane. */
|
||||
.pane-bar { 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; }
|
||||
.plugin-panes { position: relative; flex: 1; min-height: 0; min-width: 0; overflow: hidden; }
|
||||
.plugin-pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; box-sizing: border-box; }
|
||||
.plugin-pane.split { border: 1px solid var(--rs-border); }
|
||||
.plugin-pane.split.focused { border-color: var(--rs-accent); }
|
||||
.plugin-panes.inactive, .plugin-pane.inactive { display: none; }
|
||||
</style>
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
focusLine: number | null;
|
||||
onChange: (value: string, id: string) => void;
|
||||
onRenameTitle?: (id: string, title: string) => Promise<void>;
|
||||
onInsertImage?: (file: File, source?: string) => Promise<string | null>;
|
||||
onInsertImage?: (file: File) => Promise<string | null>;
|
||||
onView?: (view: ViewMode) => void;
|
||||
onSplit?: (split: boolean) => void;
|
||||
onCursor?: (line: number, column: number) => void;
|
||||
@@ -147,9 +147,7 @@
|
||||
const splitView = $derived(split && canPreview && !reading);
|
||||
const view: ViewMode = $derived(readOnly ? "read" : chrome === "Source" ? "source" : "write");
|
||||
// The tab already names the file, so the breadcrumb shows only its folder.
|
||||
// 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(" / ") : "");
|
||||
const folder = $derived(buffer?.relPath.includes("/") ? buffer.relPath.slice(0, buffer.relPath.lastIndexOf("/")).split("/").join(" / ") : "");
|
||||
</script>
|
||||
|
||||
{#if !buffer || buffer.kind === "empty"}
|
||||
|
||||
@@ -43,8 +43,6 @@
|
||||
workspaceRoot: string;
|
||||
activePath: string | null;
|
||||
onOpenFile: (entry: TreeEntry, newTab?: boolean) => void;
|
||||
/** Open the file in a new pane to the right of the active pane. */
|
||||
onOpenRight?: (entry: TreeEntry) => void;
|
||||
session: WorkspaceSession;
|
||||
onStatus?: (message: string) => void;
|
||||
onCreated?: (entry: TreeEntry) => void;
|
||||
@@ -58,7 +56,6 @@
|
||||
workspaceRoot,
|
||||
activePath,
|
||||
onOpenFile,
|
||||
onOpenRight,
|
||||
session,
|
||||
onStatus,
|
||||
onCreated,
|
||||
@@ -881,7 +878,6 @@
|
||||
...(!multiple && entry.kind === "folder" ? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }] : []),
|
||||
...(!multiple && entry.kind === "file" ? [
|
||||
{ kind: "action" as const, label: $t("Open in new tab"), icon: "tab" as const, run: () => onOpenFile(entry, true) },
|
||||
...(onOpenRight ? [{ kind: "action" as const, label: $t("Open to the right"), icon: "split-right" as const, run: () => onOpenRight(entry) }] : []),
|
||||
{ kind: "action" as const, label: $t("Open in default app"), icon: "external" as const, run: () => { void workspaceOpenDefault(entry.rel_path).catch(reason => error = String(reason)); } },
|
||||
] : []),
|
||||
terminalItem(parent),
|
||||
|
||||
@@ -29,14 +29,13 @@
|
||||
onHelp: () => void;
|
||||
onSettings: () => void;
|
||||
onOpenFile: (entry: TreeEntry, line?: number, target?: "current" | "new") => void;
|
||||
onOpenRight?: (entry: TreeEntry) => void;
|
||||
onCreated: (entry: TreeEntry) => void;
|
||||
onSaveTemplate: (entry: TreeEntry) => void;
|
||||
onManageTemplates: () => void;
|
||||
onStatus: (message: string) => void;
|
||||
};
|
||||
let { workspace, session, leftView, keysActive, showInternal, activePath, searchRequest, fileTree = $bindable(), workspaceAnchor = $bindable(),
|
||||
onOpenFile, onOpenRight, onCreated, onSaveTemplate, onManageTemplates, onStatus, onChooseWorkspace, onHelp, onSettings }: Props = $props();
|
||||
onOpenFile, onCreated, onSaveTemplate, onManageTemplates, onStatus, onChooseWorkspace, onHelp, onSettings }: Props = $props();
|
||||
|
||||
function tooltip(node: HTMLElement, text: string) {
|
||||
let current = text;
|
||||
@@ -64,7 +63,6 @@
|
||||
{onManageTemplates}
|
||||
{activePath}
|
||||
onOpenFile={(entry, newTab) => onOpenFile(entry, undefined, newTab ? "new" : "current")}
|
||||
{onOpenRight}
|
||||
{session}
|
||||
{keysActive}
|
||||
{onCreated}
|
||||
@@ -168,7 +166,7 @@
|
||||
padding: 0 10px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--rs-control-radius);
|
||||
background: var(--rs-hover-bg);
|
||||
background: var(--rs-bg-active);
|
||||
color: var(--rs-text-strong);
|
||||
font: 600 13px var(--rs-font-ui);
|
||||
text-align: left;
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
import { tick, type Snippet } from "svelte";
|
||||
import { workspaceReadDataUrl } from "$lib/workspace/api";
|
||||
import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml";
|
||||
import { loadImageSize } from "$lib/workspace/imageSizes";
|
||||
import { renderDiagrams } from "$lib/workspace/diagrams";
|
||||
import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media";
|
||||
import { imageControls } from "$lib/editor/imageControls";
|
||||
@@ -56,9 +55,7 @@
|
||||
const base = normalized.split("/").pop() ?? path;
|
||||
for (const candidate of new Set([primary, normalized, base])) {
|
||||
try {
|
||||
const url = await workspaceReadDataUrl(candidate);
|
||||
await loadImageSize(url);
|
||||
urls.set(source, url);
|
||||
urls.set(source, await workspaceReadDataUrl(candidate));
|
||||
return;
|
||||
} catch { /* Try the workspace-relative attachment next. */ }
|
||||
}
|
||||
@@ -105,8 +102,7 @@
|
||||
[...el.querySelectorAll<HTMLElement>("h1, h2, h3, h4, h5, h6")].filter(heading => !heading.classList.contains("document-title"))[index];
|
||||
if (!target) return;
|
||||
currentHeadings?.reveal(target);
|
||||
// The heading starts the text to read, so it goes to the top. Its scroll margin keeps a gap above it (reading.css).
|
||||
target.scrollIntoView({ block: "start" });
|
||||
target.scrollIntoView({ block: "center" });
|
||||
el.focus({ preventScroll: true });
|
||||
});
|
||||
return renderDiagrams(el, () => cancelled);
|
||||
|
||||
@@ -134,7 +134,7 @@
|
||||
}
|
||||
|
||||
li button:hover {
|
||||
background: var(--rs-hover-bg);
|
||||
background: var(--rs-bg-active);
|
||||
color: var(--rs-text-strong);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -13,9 +13,8 @@
|
||||
backlinks: Backlink[];
|
||||
session: WorkspaceSession;
|
||||
onOpenBacklink: (entry: Backlink) => void;
|
||||
backlinksOpen?: boolean;
|
||||
};
|
||||
let { outlineItems, onJump, showBacklinks, backlinks, session, onOpenBacklink, backlinksOpen = $bindable(true) }: Props = $props();
|
||||
let { outlineItems, onJump, showBacklinks, backlinks, session, onOpenBacklink }: Props = $props();
|
||||
</script>
|
||||
|
||||
<aside class="right">
|
||||
@@ -23,7 +22,7 @@
|
||||
<OutlinePane items={outlineItems} {onJump} />
|
||||
</div>
|
||||
{#if showBacklinks}
|
||||
<Backlinks bind:expanded={backlinksOpen} entries={backlinks} busy={session.indexBusy} error={session.indexError} onOpen={onOpenBacklink} onRebuild={() => void session.rebuildIndex()} />
|
||||
<Backlinks entries={backlinks} busy={session.indexBusy} error={session.indexError} onOpen={onOpenBacklink} onRebuild={() => void session.rebuildIndex()} />
|
||||
{/if}
|
||||
</aside>
|
||||
|
||||
|
||||
@@ -175,7 +175,7 @@
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: var(--rs-hover-bg);
|
||||
background: var(--rs-bg-active);
|
||||
}
|
||||
|
||||
.line {
|
||||
|
||||
@@ -27,14 +27,9 @@
|
||||
tabDragData?: (tab: WorkbenchTab) => string | undefined;
|
||||
onDropTab?: (data: string, index: number) => void;
|
||||
onDetach?: (tab: WorkbenchTab) => void;
|
||||
/** A tab drag outside the tab bar. The result tells whether the point can take the tab, for example a document pane. */
|
||||
onDragAt?: (relPath: string, x: number, y: number) => boolean;
|
||||
/** A tab drop outside the tab bar. The result tells whether the drop used the tab. */
|
||||
onDropAt?: (relPath: string, x: number, y: number) => boolean;
|
||||
onDragEnd?: () => void;
|
||||
};
|
||||
|
||||
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab, onDetach, onDragAt, onDropAt, onDragEnd }: Props = $props();
|
||||
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab, onDetach }: Props = $props();
|
||||
const transferType = "application/x-runestone-tab";
|
||||
let bar: HTMLDivElement;
|
||||
let dragged = $state<string | null>(null);
|
||||
@@ -66,34 +61,6 @@
|
||||
suppressClick = true;
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
event.dataTransfer.setData(transferType, data);
|
||||
watchAreaDrop(tab.relPath);
|
||||
}
|
||||
|
||||
// A tab that leaves the tab bar can go to a pane of the document area. The listeners run first, in the capture
|
||||
// phase, so that an editor under the pointer does not take the drop.
|
||||
let stopAreaDrop = () => {};
|
||||
function watchAreaDrop(path: string) {
|
||||
stopAreaDrop();
|
||||
if (!onDragAt || !onDropAt) return;
|
||||
const inBar = (event: DragEvent) => event.target instanceof Node && bar.contains(event.target);
|
||||
const over = (event: DragEvent) => {
|
||||
if (inBar(event) || !onDragAt?.(path, event.clientX, event.clientY)) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
|
||||
};
|
||||
const drop = (event: DragEvent) => {
|
||||
if (inBar(event) || !onDropAt?.(path, event.clientX, event.clientY)) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
finishTabTransfer();
|
||||
};
|
||||
window.addEventListener("dragover", over, true);
|
||||
window.addEventListener("drop", drop, true);
|
||||
stopAreaDrop = () => {
|
||||
window.removeEventListener("dragover", over, true);
|
||||
window.removeEventListener("drop", drop, true);
|
||||
stopAreaDrop = () => {};
|
||||
onDragEnd?.();
|
||||
};
|
||||
}
|
||||
|
||||
function transferIndex(x: number) {
|
||||
@@ -118,7 +85,6 @@
|
||||
}
|
||||
|
||||
function finishTabTransfer() {
|
||||
stopAreaDrop();
|
||||
dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false;
|
||||
cancelAnimationFrame(transferFrame); transferFrame = 0;
|
||||
}
|
||||
@@ -323,7 +289,6 @@
|
||||
frame = requestAnimationFrame(scroll);
|
||||
};
|
||||
const clean = () => {
|
||||
if (started) onDragEnd?.();
|
||||
if (pointerTarget.hasPointerCapture(pointerId)) pointerTarget.releasePointerCapture(pointerId);
|
||||
cancelAnimationFrame(frame);
|
||||
dragged = dropBefore = dropAfter = null;
|
||||
@@ -341,19 +306,15 @@
|
||||
e.preventDefault();
|
||||
if (!started) { started = true; suppressClick = true; dragged = path; frame = requestAnimationFrame(scroll); }
|
||||
update();
|
||||
if (destination === null) onDragAt?.(path, x, y);
|
||||
else onDragEnd?.();
|
||||
};
|
||||
const onUp = (e: PointerEvent) => {
|
||||
if (e.pointerId !== pointerId) return;
|
||||
x = e.clientX; y = e.clientY;
|
||||
if (started) update();
|
||||
const target = destination;
|
||||
const wasStarted = started;
|
||||
clean();
|
||||
if (wasStarted && target !== null) void move(path, target);
|
||||
else if (wasStarted && onDropAt?.(path, x, y)) return;
|
||||
else if (wasStarted && (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight)) {
|
||||
if (started && target !== null) void move(path, target);
|
||||
else if (started && (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight)) {
|
||||
const tab = tabs.find(tab => tab.relPath === path);
|
||||
if (tab) onDetach?.(tab);
|
||||
}
|
||||
@@ -485,7 +446,7 @@
|
||||
}
|
||||
|
||||
.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-hover-bg); }
|
||||
.tab:not(.active):hover { background: var(--rs-bg-active); }
|
||||
.tab.dragging { opacity: 0.5; }
|
||||
.tabs:has(.dragging) .tab > button:first-child { cursor: grabbing; }
|
||||
.tab.drop-before::before, .tab.drop-after::after {
|
||||
@@ -560,6 +521,6 @@
|
||||
background: transparent;
|
||||
color: var(--rs-text-dim);
|
||||
}
|
||||
.all-tabs:hover { background: var(--rs-hover-bg); border-color: var(--rs-border); color: var(--rs-text-strong); }
|
||||
.all-tabs:hover { background: var(--rs-bg-active); 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); }
|
||||
</style>
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
}
|
||||
|
||||
.row:hover {
|
||||
background: var(--rs-hover-bg);
|
||||
background: var(--rs-bg-active);
|
||||
}
|
||||
|
||||
.row.active {
|
||||
@@ -305,7 +305,7 @@
|
||||
|
||||
.row.drop-inside {
|
||||
outline: 1px solid var(--rs-accent);
|
||||
background: var(--rs-hover-bg);
|
||||
background: var(--rs-bg-active);
|
||||
}
|
||||
|
||||
.twist {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
<script lang="ts" module>
|
||||
/** The view of a document pane. Read beside is a separate toggle beside Write or Source. */
|
||||
/** The view of a document pane. Split is a separate toggle beside Write or Source. */
|
||||
export type ViewMode = "write" | "source" | "read";
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
// The view control of a document pane: Write, Source, and Read in one radio group, then the Read beside toggle.
|
||||
// The view control of a document pane: Write, Source, and Read in one radio group, then the Split toggle.
|
||||
// All choices stay visible. Narrow panes show only the icons.
|
||||
import { t } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
@@ -16,7 +16,7 @@
|
||||
type Props = {
|
||||
view: ViewMode;
|
||||
split: boolean;
|
||||
/** Markdown files have Read and Read beside. Other text files have only Write and Source. */
|
||||
/** Markdown files have Read and Split. Other text files have only Write and Source. */
|
||||
readable: boolean;
|
||||
onView: (view: ViewMode) => void;
|
||||
onSplit: (split: boolean) => void;
|
||||
@@ -60,7 +60,7 @@
|
||||
{/each}
|
||||
</div>
|
||||
{#if readable}
|
||||
<button type="button" class="split" aria-pressed={split} aria-label={$t("Read beside")} use:tooltip={$t("Read beside: show the Read view beside the editor")} onclick={() => onSplit(!split)}>
|
||||
<button type="button" class="split" aria-pressed={split} aria-label={$t("Split")} use:tooltip={$t("Split: Read beside the editor")} onclick={() => onSplit(!split)}>
|
||||
<Icon icon="split" />
|
||||
</button>
|
||||
{/if}
|
||||
@@ -92,7 +92,7 @@
|
||||
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. */
|
||||
button:hover { background: var(--rs-hover-bg); color: var(--rs-text-strong); }
|
||||
button:hover { background: var(--rs-bg-active); color: var(--rs-text-strong); }
|
||||
button[aria-checked="true"], button[aria-pressed="true"] {
|
||||
background: var(--rs-item-selection-bg);
|
||||
color: var(--rs-text-strong);
|
||||
|
||||
+30
-185
@@ -6,14 +6,13 @@
|
||||
import type PluginEditor from "$lib/plugins/PluginEditor.svelte";
|
||||
import { featureOfOwner } from "$lib/features/catalog";
|
||||
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup, pluginTools, installedPlugins, runPluginCommand } from "$lib/plugins/external";
|
||||
import { containsPane, paneBounds, splitSibling } from "$lib/workspace/splitLayout";
|
||||
import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
|
||||
import { pluginSidebar, closePluginSidebar, pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginFileOpen, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
|
||||
import { onMount, onDestroy, tick, untrack } from "svelte";
|
||||
import type { MenuLink } from "$lib/editor/linkMenu";
|
||||
import { WorkspaceSession } from "$lib/workspace/session.svelte";
|
||||
import { retainEditorStates } from "$lib/editor/editorStates";
|
||||
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView,
|
||||
paneOf, showInActivePane, splitWithContent, releaseSolePlugin, dropInPane, resizeDocumentPanes, type PaneContent, type PaneDrop, type DocumentPanes } from "$lib/workspace/documentPanes";
|
||||
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView } from "$lib/workspace/documentPanes";
|
||||
import type { ViewMode } from "./ViewModes.svelte";
|
||||
import { selectedEditorText } from "$lib/editor/selection";
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
@@ -66,12 +65,10 @@
|
||||
workspaceReveal,
|
||||
workspaceWrite,
|
||||
workspaceWriteBytes,
|
||||
workspaceSaveImageUrl,
|
||||
} from "$lib/workspace/api";
|
||||
import { detectChrome } from "$lib/workspace/chrome";
|
||||
import { planRename, planMarkdownTitleRename, planDocumentTitleRename, renameSelection } from "$lib/workspace/renamePath";
|
||||
import { attachmentRel, dataUrlExtension, isImagePath, isMarkdownPath, mayAnimate } from "$lib/workspace/media";
|
||||
import { copiedImage } from "$lib/workspace/copiedImage";
|
||||
import { attachmentRel, isImagePath, isMarkdownPath } from "$lib/workspace/media";
|
||||
import { headingLinkLine, linkFragment } from "$lib/workspace/headingLinks";
|
||||
import type { Chrome, OpenBuffer, TreeEntry, WorkspaceInfo } from "$lib/workspace/types";
|
||||
|
||||
@@ -150,7 +147,6 @@
|
||||
let searchRequest = $state<{ text: string; id: number } | null>(null);
|
||||
let leftOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.leftOpen);
|
||||
let rightOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.rightOpen);
|
||||
let backlinksOpen = $state(DEFAULT_WORKBENCH_LAYOUT.backlinksOpen);
|
||||
$effect(() => { if ($pluginSidebar && !transferredWindow) leftOpen = true; });
|
||||
let terminalOpen = $state(false);
|
||||
let documentPanes = $state(initialDocumentPanes());
|
||||
@@ -230,9 +226,7 @@
|
||||
}, () => {
|
||||
if (documents !== next) return;
|
||||
const selected = next.active;
|
||||
// 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);
|
||||
documentPanes = syncDocumentPanes(documentPanes, next.buffers.map(tab => tab.id), selected?.id ?? null);
|
||||
if (selected) view = selected.chromeOverride ?? selected.chrome;
|
||||
});
|
||||
return next;
|
||||
@@ -241,8 +235,8 @@
|
||||
onDestroy(() => retainEditorStates([]));
|
||||
const documentViews = $derived.by(() => {
|
||||
const bounds = paneBounds(documentPanes.layout);
|
||||
return documentPanes.panes.map(pane => ({ ...pane, buffer: tabs.find(tab => tab.id === pane.documentId) ?? null }))
|
||||
.sort((a, b) => bounds[a.id].left - bounds[b.id].left || bounds[a.id].top - bounds[b.id].top);
|
||||
return documentPanes.panes.map(pane => ({ ...pane, buffer: tabs.find(tab => tab.id === pane.documentId) ?? null, bounds: bounds[pane.id] }))
|
||||
.sort((a, b) => a.bounds.left - b.bounds.left);
|
||||
});
|
||||
function setReading(next: boolean, paneId = documentPanes.active) {
|
||||
documentPanes = readDocumentPane(documentPanes, paneId, next);
|
||||
@@ -252,13 +246,6 @@
|
||||
if (!pane) return;
|
||||
const tab = tabs.find(tab => tab.id === pane.documentId);
|
||||
documentPanes = selectPane(documentPanes, paneId);
|
||||
if (pane.pluginKey) {
|
||||
const key = pane.pluginKey;
|
||||
const view = $pluginEditors.find(view => view.key === key);
|
||||
if (view && !($pluginEditorActive && $pluginView?.key === key)) selectPluginEditor(view);
|
||||
if (focusEditor) void tick().then(() => { if (documentPanes.active === paneId) pluginPaneComponents[key]?.focus(); });
|
||||
return;
|
||||
}
|
||||
pluginEditorActive.set(false);
|
||||
if (tab && documents?.active?.id !== tab.id) { focusLine = null; documents?.select(tab.relPath); }
|
||||
if (focusEditor) void tick().then(() => {
|
||||
@@ -267,147 +254,27 @@
|
||||
document.querySelector<HTMLElement>(`[data-document-pane="${paneId}"]`)?.scrollIntoView({ block: "nearest", inline: "nearest" });
|
||||
});
|
||||
}
|
||||
/** Use a new pane state and focus its active pane. The last pane does not keep a plugin view. The view covers the area again. */
|
||||
function changePanes(next: DocumentPanes) {
|
||||
const released = releaseSolePlugin(next);
|
||||
documentPanes = released.state;
|
||||
const view = $pluginEditors.find(view => view.key === released.pluginKey);
|
||||
if (view) {
|
||||
selectPluginEditor(view);
|
||||
void tick().then(() => pluginPaneComponents[view.key]?.focus());
|
||||
} else focusDocumentPane(documentPanes.active, true);
|
||||
}
|
||||
function closeSplit(paneId: string) {
|
||||
changePanes(closeDocumentPane(documentPanes, paneId));
|
||||
documentPanes = closeDocumentPane(documentPanes, paneId);
|
||||
focusDocumentPane(documentPanes.active, true);
|
||||
}
|
||||
/** The plugin view that covers the document area moves into the active pane, so that a new pane can open beside it. */
|
||||
function keepCoverInPane() {
|
||||
if (coverKey) documentPanes = showInActivePane(documentPanes, { pluginKey: coverKey });
|
||||
}
|
||||
/** A plugin document that opens to the right, for example a PDF file: the source pane, and the plugin view that covers the area. */
|
||||
let rightOf: { pane: string; cover: string | null } | null = null;
|
||||
async function openToRight(file: TreeEntry, sourcePane: string) {
|
||||
const current = documents;
|
||||
const covered = sourcePane === documentPanes.active ? coverKey : null;
|
||||
const source = documentPanes.panes.find(pane => pane.id === sourcePane);
|
||||
if (!current || switching || !source) return;
|
||||
const unchanged = () => {
|
||||
const now = documentPanes.panes.find(pane => pane.id === sourcePane);
|
||||
return documents === current && !switching && documentPanes.active === sourcePane && coverKey === covered
|
||||
&& now?.documentId === source.documentId && now?.pluginKey === source.pluginKey;
|
||||
};
|
||||
const open = current.buffers.find(tab => tab.relPath === file.rel_path);
|
||||
if (!(open && open.contents !== open.saved)) {
|
||||
// The placement effect opens the plugin view in a new pane beside the source pane.
|
||||
rightOf = { pane: sourcePane, cover: covered };
|
||||
try {
|
||||
const opened = await openPluginDocument(file.rel_path, unchanged);
|
||||
await tick();
|
||||
if (opened) return;
|
||||
} finally { rightOf = null; }
|
||||
}
|
||||
await current.open(file, "background");
|
||||
if (!unchanged()) return;
|
||||
if (documents !== current || switching || documentPanes.active !== sourcePane
|
||||
|| documentPanes.panes.find(pane => pane.id === sourcePane)?.documentId !== source.documentId) return;
|
||||
const target = current.buffers.find(tab => tab.relPath === file.rel_path);
|
||||
if (!target) return;
|
||||
keepCoverInPane();
|
||||
documentPanes = splitDocumentPane(documentPanes, sourcePane, target.id, crypto.randomUUID());
|
||||
focusDocumentPane(documentPanes.active, true);
|
||||
}
|
||||
function tabContent(tab: EditorTab): PaneContent {
|
||||
return "plugin" in tab ? { pluginKey: tab.plugin.key } : { documentId: tab.buffer.id };
|
||||
}
|
||||
/** A visible tab is the plugin view over the area, or the content of a pane. */
|
||||
function tabVisible(tab: EditorTab) {
|
||||
if (coverKey) return "plugin" in tab && tab.plugin.key === coverKey;
|
||||
return !!paneOf(documentPanes, tabContent(tab));
|
||||
}
|
||||
/** Show a tab in a new pane to the right of the active pane. The active pane keeps its content. */
|
||||
function openTabToRight(tab: EditorTab) {
|
||||
if (switching || tabVisible(tab)) return;
|
||||
keepCoverInPane();
|
||||
documentPanes = splitWithContent(documentPanes, documentPanes.active, tabContent(tab), crypto.randomUUID());
|
||||
focusDocumentPane(documentPanes.active, true);
|
||||
}
|
||||
// A tab that the user drags from the tab bar to the document area: the pane and the place of the drop.
|
||||
let documentArea: DocumentArea | undefined = $state();
|
||||
let tabDrop = $state<{ pane: string; zone: PaneDrop } | null>(null);
|
||||
function tabDropTarget(path: string, x: number, y: number) {
|
||||
const tab = workingTabs.find(tab => tab.relPath === path);
|
||||
const target = tab && !switching ? documentArea?.dropAt(x, y) ?? null : null;
|
||||
if (!tab || !target) return null;
|
||||
// A drop on the pane that shows the tab changes nothing.
|
||||
if (coverKey ? "plugin" in tab && tab.plugin.key === coverKey : paneOf(documentPanes, tabContent(tab))?.id === target.pane) return null;
|
||||
return { tab, target };
|
||||
}
|
||||
function tabDragAt(path: string, x: number, y: number) {
|
||||
tabDrop = tabDropTarget(path, x, y)?.target ?? null;
|
||||
return tabDrop !== null;
|
||||
}
|
||||
function tabDropAt(path: string, x: number, y: number) {
|
||||
const found = tabDropTarget(path, x, y);
|
||||
tabDrop = null;
|
||||
if (!found) return false;
|
||||
const { tab, target } = found;
|
||||
if (coverKey) {
|
||||
if (target.zone === "center") { selectWorkingTab(tab.relPath); return true; }
|
||||
keepCoverInPane();
|
||||
}
|
||||
changePanes(dropInPane(documentPanes, tabContent(tab), target.pane, target.zone, crypto.randomUUID()));
|
||||
return true;
|
||||
}
|
||||
// Each focused plugin view that is not in a pane gets a pane when the area has several panes.
|
||||
// A new view that a plugin opens beside its own view, for example a browser tab, opens beside the pane of that view.
|
||||
// When the own view covers the area, it moves into the pane first.
|
||||
const placedPlugins = new Set<string>();
|
||||
$effect(() => {
|
||||
const view = $pluginEditorActive && $pluginView?.placement === "editor" ? $pluginView : null;
|
||||
const splits = $pluginSplits;
|
||||
if (!view) return;
|
||||
untrack(() => {
|
||||
const fresh = !placedPlugins.has(view.key);
|
||||
placedPlugins.add(view.key);
|
||||
const shown = paneOf(documentPanes, { pluginKey: view.key });
|
||||
if (shown) { documentPanes = selectPane(documentPanes, shown.id); return; }
|
||||
const right = rightOf;
|
||||
if (right && documentPanes.panes.some(pane => pane.id === right.pane)) {
|
||||
rightOf = null;
|
||||
if (right.cover && right.cover !== view.key && !paneOf(documentPanes, { pluginKey: right.cover }))
|
||||
documentPanes = showInActivePane(selectPane(documentPanes, right.pane), { pluginKey: right.cover });
|
||||
documentPanes = splitWithContent(documentPanes, right.pane, { pluginKey: view.key }, crypto.randomUUID());
|
||||
return;
|
||||
}
|
||||
const group = fresh ? splits.find(tree => containsPane(tree, view.key)) : undefined;
|
||||
const beside = group ? splitSibling(group, view.key) : null;
|
||||
if (documentPanes.panes.length < 2 && !beside) return;
|
||||
if (beside && documentPanes.panes.length < 2 && !paneOf(documentPanes, { pluginKey: beside.sibling }))
|
||||
documentPanes = showInActivePane(documentPanes, { pluginKey: beside.sibling });
|
||||
const source = beside ? paneOf(documentPanes, { pluginKey: beside.sibling }) : undefined;
|
||||
documentPanes = source && beside
|
||||
? splitWithContent(documentPanes, source.id, { pluginKey: view.key }, crypto.randomUUID(), beside.direction)
|
||||
: showInActivePane(documentPanes, { pluginKey: view.key });
|
||||
});
|
||||
});
|
||||
// The selected document is visible while no plugin view has the focus.
|
||||
$effect(() => {
|
||||
const selected = $pluginEditorActive && $pluginView?.placement === "editor" ? null : buffer?.id ?? null;
|
||||
if (selected) untrack(() => { documentPanes = showInActivePane(documentPanes, { documentId: selected }); });
|
||||
});
|
||||
// A closed plugin view leaves its pane. The last pane does not keep a plugin view.
|
||||
$effect(() => {
|
||||
const keys = $pluginEditors.map(view => view.key);
|
||||
untrack(() => {
|
||||
for (const key of placedPlugins) if (!keys.includes(key)) placedPlugins.delete(key);
|
||||
documentPanes = releaseSolePlugin(syncDocumentPanes(documentPanes, tabs.map(tab => tab.id), null, keys)).state;
|
||||
});
|
||||
});
|
||||
let focusLine = $state<number | null>(null);
|
||||
let dragging = $state<"left" | "right" | "bottom" | null>(null);
|
||||
let centerStack: HTMLElement | undefined = $state();
|
||||
|
||||
// A focused plugin view is the active tab. It covers the area only when no pane shows it.
|
||||
const editorPluginVisible = $derived($pluginView?.placement === "editor" && $pluginEditorActive);
|
||||
const coverKey = $derived(editorPluginVisible && $pluginView && !paneOf(documentPanes, { pluginKey: $pluginView.key }) ? $pluginView.key : null);
|
||||
type EditorTab = WorkbenchTab & ({ buffer: OpenBuffer } | { plugin: OpenPluginView });
|
||||
let tabOrder = $state<string[]>([]);
|
||||
const availableTabs = $derived<EditorTab[]>([
|
||||
@@ -494,7 +361,9 @@
|
||||
} catch (reason) { error = String(reason); }
|
||||
}
|
||||
const activeTabPath = $derived(editorPluginVisible && $pluginView ? `plugin:${$pluginView.key}` : activePath);
|
||||
// The working tabs of the header.
|
||||
const activeSplit = $derived($pluginSplits.find(tree => $pluginView && containsPane(tree, $pluginView.key)));
|
||||
const pluginBounds = $derived(activeSplit ? paneBounds(activeSplit) : $pluginView ? paneBounds($pluginView.key) : {});
|
||||
// The working tabs, for the header and for the tab bar of each plugin pane in a split.
|
||||
const tabBarProps = $derived({ tabs: workingTabs, activePath: activeTabPath, onSelect: selectWorkingTab, onClose: closeTab,
|
||||
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) });
|
||||
@@ -540,7 +409,7 @@
|
||||
documents?.setChrome(next);
|
||||
}
|
||||
|
||||
/** Show Write, Source, or Read in a pane. Write and Source keep Read beside. */
|
||||
/** Show Write, Source, or Read in a pane. Write and Source keep a Split view. */
|
||||
function setDocumentView(paneId: string, next: ViewMode) {
|
||||
focusDocumentPane(paneId);
|
||||
if (next === "read") { setReading(true, paneId); return; }
|
||||
@@ -685,8 +554,6 @@
|
||||
pluginEditorActive.set(false);
|
||||
focusLine = null;
|
||||
documents?.select(relPath);
|
||||
const selected = documents?.active?.id;
|
||||
if (selected) documentPanes = showInActivePane(documentPanes, { documentId: selected });
|
||||
focusDocumentPane(documentPanes.active, true);
|
||||
status = documents?.active?.kind === "empty" ? $t("New tab") : "";
|
||||
}
|
||||
@@ -715,11 +582,9 @@
|
||||
}
|
||||
function workingTabActions(item: WorkbenchTab): ActionMenuItem[] {
|
||||
const tab = workingTabs.find(tab => tab.id === item.id);
|
||||
if (!tab) return [];
|
||||
const actions = "plugin" in tab ? pluginTabActions(tab.plugin) : [];
|
||||
const right: ActionMenuItem = { label: $t("Open to the right"), icon: "split-right", disabled: tabVisible(tab), run: () => openTabToRight(tab) };
|
||||
if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return [right, ...actions];
|
||||
return [right, { label: $t("Open in new window"), icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions];
|
||||
const actions = tab && "plugin" in tab ? pluginTabActions(tab.plugin) : [];
|
||||
if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return actions;
|
||||
return tab ? [{ label: $t("Open in new window"), icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : [];
|
||||
}
|
||||
async function detachTab(item: WorkbenchTab, keepSource = false) {
|
||||
const tab = workingTabs.find(tab => tab.id === item.id);
|
||||
@@ -854,7 +719,7 @@
|
||||
{ label: $t("Source"), icon: "code", radio: true, checked: viewMode === "source", run: () => setDocumentView(documentPanes.active, "source") },
|
||||
{ label: $t("Read"), icon: "book", radio: true, checked: viewMode === "read", run: () => setDocumentView(documentPanes.active, "read") },
|
||||
{ separator: true },
|
||||
{ label: $t("Read beside"), icon: "split-right", checked: activeDocumentPane?.split === true && !reading, run: () => setSplitView(documentPanes.active, !(activeDocumentPane?.split && !reading)) },
|
||||
{ label: $t("Split"), icon: "split-right", checked: activeDocumentPane?.split === true && !reading, run: () => setSplitView(documentPanes.active, !(activeDocumentPane?.split && !reading)) },
|
||||
] },
|
||||
);
|
||||
}
|
||||
@@ -910,35 +775,21 @@
|
||||
});
|
||||
}
|
||||
|
||||
/** `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> {
|
||||
async function insertImage(file: File, note = buffer): Promise<string | null> {
|
||||
if (!note || note.kind !== "text" || !isMarkdownPath(note.relPath)) {
|
||||
return null;
|
||||
}
|
||||
const noteRel = note.relPath;
|
||||
const current = documents;
|
||||
try {
|
||||
let rel = attachmentRel(file.name);
|
||||
const stem = rel.replace(/\.[^./]+$/, "");
|
||||
// The RuneStone browser keeps the bytes of the image that it copied. For a copy from another browser, download the original of a format with frames.
|
||||
const copied = source ? await copiedImage(source) : undefined;
|
||||
const copiedExtension = copied ? dataUrlExtension(copied) : undefined;
|
||||
const download = !copiedExtension && !!source && mayAnimate(source);
|
||||
// The host sets the extension from the downloaded file. A failed download keeps the still copy.
|
||||
const downloaded = download && source ? await workspaceSaveImageUrl(source, stem).catch(() => null) : null;
|
||||
if (downloaded) rel = downloaded;
|
||||
else {
|
||||
if (copiedExtension) rel = `${stem}.${copiedExtension}`;
|
||||
const dataUrl = copied && copiedExtension ? copied : await readFileDataUrl(file);
|
||||
const rel = attachmentRel(file.name);
|
||||
const dataUrl = await readFileDataUrl(file);
|
||||
const base64 = dataUrl.split(",")[1];
|
||||
if (!base64) {
|
||||
error = $t("The image file is empty. A browser can give an empty file when the website refuses a download. To add the image, copy it in the RuneStone browser. You can also save the image and add the saved file.");
|
||||
return null;
|
||||
}
|
||||
if (documents !== current || switching) return null;
|
||||
await workspaceWriteBytes(rel, base64);
|
||||
if (download) error = $t("The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file.");
|
||||
}
|
||||
if (documents !== current) return null;
|
||||
session.changed([rel]);
|
||||
return `.length - 1)}${rel})`;
|
||||
@@ -1077,10 +928,7 @@
|
||||
if (!workingTabs.length) return false;
|
||||
const index = workingTabs.findIndex(tab => tab.relPath === activeTabPath);
|
||||
const next = (index + (command === "previous-tab" ? -1 : 1) + workingTabs.length) % workingTabs.length;
|
||||
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(); });
|
||||
selectWorkingTab(workingTabs[next].relPath);
|
||||
return true;
|
||||
}
|
||||
case "command-palette": palette = true; return true;
|
||||
@@ -1313,7 +1161,7 @@
|
||||
try {
|
||||
// The layout stays in localStorage on purpose: per-machine view state that is harmless to lose.
|
||||
const layout = parseWorkbenchLayout(localStorage.getItem(WORKBENCH_LAYOUT_KEY));
|
||||
({ leftOpen, rightOpen, leftWidth, rightWidth, leftView, backlinksOpen } = layout);
|
||||
({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout);
|
||||
if (transferredWindow) { leftOpen = false; rightOpen = false; }
|
||||
layoutReady = true;
|
||||
} catch { error = $t("Could not read your layout. Default layout applies for this window."); }
|
||||
@@ -1346,7 +1194,7 @@
|
||||
$effect(() => {
|
||||
if (!layoutReady || transferredWindow) return;
|
||||
const saved = { leftOpen: narrow.left ? wide.left : leftOpen, rightOpen: narrow.right ? wide.right : rightOpen };
|
||||
try { saveWorkbenchLayout(localStorage, { ...saved, leftWidth, rightWidth, leftView, backlinksOpen }); }
|
||||
try { saveWorkbenchLayout(localStorage, { ...saved, leftWidth, rightWidth, leftView }); }
|
||||
catch { error = $t("Could not save your layout. Layout changes apply for this window only."); }
|
||||
});
|
||||
|
||||
@@ -1453,7 +1301,7 @@
|
||||
{leftView}
|
||||
{sidebarNavigation}
|
||||
onSelectLeft={selectLeft}
|
||||
tabBar={{ ...tabBarProps, onDetach: (tab) => { void detachTab(tab); }, onDragAt: tabDragAt, onDropAt: tabDropAt, onDragEnd: () => { tabDrop = null; } }}
|
||||
tabBar={{ ...tabBarProps, onDetach: (tab) => { void detachTab(tab); } }}
|
||||
onNewTab={newTab}
|
||||
canOpenBrowser={!!browserContribution?.newTab}
|
||||
{browserOpening}
|
||||
@@ -1483,7 +1331,6 @@
|
||||
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
|
||||
{searchRequest}
|
||||
onOpenFile={(entry, line, target) => void openFile(entry, line, target)}
|
||||
onOpenRight={(entry) => void openToRight(entry, documentPanes.active)}
|
||||
onCreated={(entry) => { void openCreatedFile(entry); }}
|
||||
onSaveTemplate={(entry) => { void saveTemplate(entry); }}
|
||||
onManageTemplates={() => templateManager = true}
|
||||
@@ -1510,14 +1357,13 @@
|
||||
|
||||
<div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}>
|
||||
<DocumentArea
|
||||
bind:this={documentArea}
|
||||
bind:pluginPaneComponents
|
||||
bind:paneComponents
|
||||
pluginCover={coverKey !== null}
|
||||
drop={tabDrop}
|
||||
onResize={(path, ratio) => { documentPanes = resizeDocumentPanes(documentPanes, path, ratio); }}
|
||||
{editorPluginVisible}
|
||||
split={!!activeSplit}
|
||||
{pluginBounds}
|
||||
tabBar={tabBarProps}
|
||||
{documentViews}
|
||||
layout={documentPanes.layout}
|
||||
activePane={documentPanes.active}
|
||||
{documents}
|
||||
{tabs}
|
||||
@@ -1533,7 +1379,7 @@
|
||||
onQuickOpen={() => quickOpen = true}
|
||||
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
|
||||
{onChange}
|
||||
onInsertImage={(file, tab, source) => insertImage(file, tab, source)}
|
||||
onInsertImage={(file, tab) => insertImage(file, tab)}
|
||||
onRenameTitle={renameNoteTitle}
|
||||
tableActions={(pane) => ({ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) })}
|
||||
linkActions={(pane) => ({
|
||||
@@ -1602,7 +1448,6 @@
|
||||
}}
|
||||
showBacklinks={buffer?.kind === "text" && isMarkdownPath(buffer.relPath) && !editorPluginVisible}
|
||||
{backlinks}
|
||||
bind:backlinksOpen
|
||||
{session}
|
||||
onOpenBacklink={(entry) => void openBacklink(entry)}
|
||||
/>
|
||||
|
||||
@@ -115,12 +115,12 @@
|
||||
:global(.shell.left-open) .header-left { width: calc(var(--ribbon-width) + var(--left) + 1px); }
|
||||
.header-left :global(.icon-btn), .header-right :global(.icon-btn) { flex-shrink: 0; }
|
||||
.header-right { justify-content: flex-end; }
|
||||
/* The drag area fills the free space after the tabs. It keeps 48 pixels, so the window stays movable when the tabs fill the header. */
|
||||
.window-drag-space { flex: 1 0 48px; align-self: stretch; }
|
||||
/* A drag area keeps the window movable when the tabs fill the header: 120 pixels, and at least 48 in a narrow header. */
|
||||
.window-drag-space { flex: 0 1 120px; min-width: 48px; align-self: stretch; }
|
||||
|
||||
/* The tab strip uses all space up to the drag area, then scrolls. It keeps room for one readable tab. */
|
||||
/* The tab strip keeps room for one readable tab. It shrinks first, so the drag area shrinks only after it. */
|
||||
.header-center :global(.tabs) {
|
||||
flex: 0 1 auto;
|
||||
flex: 0 1000 auto;
|
||||
align-self: stretch;
|
||||
min-width: 120px;
|
||||
min-height: 28px;
|
||||
|
||||
@@ -23,24 +23,9 @@
|
||||
const folderName = (path: string) => path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path;
|
||||
const removeTooltip = (node: HTMLElement) => ({ destroy: attachTooltip(node, () => tr("Remove from recent workspaces")) });
|
||||
const destination = $derived(parent ? `${parent.replace(/[\\/]+$/, "")}${parent.includes("\\") ? "\\" : "/"}${name.trim()}` : $t("Choose where to create your workspace."));
|
||||
// A press on the anchor closes the open menu before the click. Then the click must not open it again.
|
||||
let pressedOpen = false;
|
||||
|
||||
$effect(() => {
|
||||
const target = anchor;
|
||||
if (!target) return;
|
||||
const press = () => {
|
||||
pressedOpen = menu.matches(":popover-open");
|
||||
// The click comes in the same task as the release. A drag away from the anchor gives no click.
|
||||
if (pressedOpen) window.addEventListener("pointerup", () => setTimeout(() => { pressedOpen = false; }), { once: true });
|
||||
};
|
||||
target.addEventListener("pointerdown", press);
|
||||
return () => target.removeEventListener("pointerdown", press);
|
||||
});
|
||||
|
||||
export async function show() {
|
||||
if (busy || creating) return;
|
||||
if (pressedOpen) { pressedOpen = false; return; }
|
||||
if (menu.matches(":popover-open")) { menu.hidePopover(); return; }
|
||||
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
error = ""; loading = true;
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
|
||||
<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:hover, .access-button[aria-expanded="true"] { background: var(--rs-hover-bg); }
|
||||
.access-button:hover, .access-button[aria-expanded="true"] { background: var(--rs-bg-active); }
|
||||
.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.ribbon { justify-content: center; width: 32px; height: 32px; min-height: 32px; padding: 0; }
|
||||
|
||||
@@ -28,11 +28,6 @@
|
||||
findPanel?.focus();
|
||||
}
|
||||
|
||||
/** Give the keyboard to the tab: to the element that the view marks with `data-tab-focus`, or to the view. */
|
||||
export function focus() {
|
||||
(host?.querySelector<HTMLElement>("[data-tab-focus]") ?? host)?.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
function searchKey(event: KeyboardEvent) {
|
||||
if (event.target instanceof Element && event.target.closest('dialog, [role="dialog"], [role="menu"]')) return;
|
||||
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "f") {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { BackgroundFrame } from './backgroundContracts.ts';
|
||||
|
||||
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', '--rs-hover-bg'] 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'] as const;
|
||||
|
||||
function validImage(frame: BackgroundFrame) {
|
||||
return frame && typeof frame.url === 'string' && /^blob:[^\s"'\\()]+$/.test(frame.url)
|
||||
@@ -122,7 +122,6 @@ export class BackgroundHub {
|
||||
put('--rs-menu-bg', 'var(--rs-image-menu-bg)');
|
||||
put('--rs-menu-active-bg', 'var(--rs-image-menu-active-bg)');
|
||||
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-previous-image', previous ? previous.image : 'none');
|
||||
put('--rs-background-previous-position', frame.previous?.position ?? frame.position);
|
||||
|
||||
@@ -11,7 +11,7 @@ export const silverSerpent = {
|
||||
variants: {
|
||||
dark: {
|
||||
bg: '#141619', 'bg-elevated': '#1c1e21', 'bg-active': '#2b3034', border: '#3b4046',
|
||||
text: '#e5e8ec', 'text-dim': '#c2c6cc', 'text-strong': '#fcf9ea',
|
||||
text: '#e5e8ec', 'text-dim': '#b3b8be', 'text-strong': '#fcf9ea',
|
||||
accent: '#bfd4e7', 'accent-2': '#31d78c', selection: '#0c6944', 'item-selection-bg': '#0c6944a6',
|
||||
error: '#ff645f', 'warn-hot': '#fd923e', warn: '#fec84b', ok: '#5cdc78', special: '#fb9989',
|
||||
'syntax-keyword': '#31d78c', 'syntax-string': '#f0de99', 'syntax-number': '#fda293', 'syntax-comment': '#b2b7bd',
|
||||
|
||||
@@ -37,17 +37,13 @@
|
||||
--rs-menu-icon-gap: 8px;
|
||||
--rs-menu-font-size: 13px;
|
||||
--rs-menu-border: transparent;
|
||||
/* Menus are opaque (UI-043). With a background image, they use the surface transparency and blur the image (UI-061). */
|
||||
/* Menus are opaque. With a background image, they stay at least 92% opaque and blur the image (UI-043). */
|
||||
--rs-menu-bg: var(--rs-bg-elevated);
|
||||
--rs-menu-active-bg: var(--rs-bg-active);
|
||||
--rs-menu-backdrop: none;
|
||||
--rs-image-menu-bg: color-mix(in srgb, var(--rs-bg-elevated) var(--rs-surface-opacity), transparent);
|
||||
--rs-image-menu-active-bg: var(--rs-image-hover-bg);
|
||||
--rs-image-menu-bg: color-mix(in srgb, var(--rs-bg-elevated) max(92%, 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-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-item-selection-radius: var(--rs-control-radius);
|
||||
--rs-item-selection-bg: color-mix(in srgb, var(--rs-accent) 12%, transparent);
|
||||
|
||||
@@ -34,8 +34,6 @@
|
||||
<path d="m6 9 6 6 6-6" />
|
||||
{:else if icon === "chevrons-up-down"}
|
||||
<path d="m7 15 5 5 5-5M7 9l5-5 5 5" />
|
||||
{:else if icon === "scroll"}
|
||||
<path d="M12 3v5m-3-2 3-3 3 3M12 21v-5m-3 2 3 3 3-3M3 12h5m-2-3-3 3 3 3M21 12h-5m2-3 3 3-3 3" /><circle cx="12" cy="12" r="1" />
|
||||
{:else if icon === "maximize"}
|
||||
<path d="M8 3H3v5M16 3h5v5M21 16v5h-5M8 21H3v-5" />
|
||||
{:else if icon === "minimize"}
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
| "more"
|
||||
| "chevron-down"
|
||||
| "chevrons-up-down"
|
||||
| "scroll"
|
||||
| "up"
|
||||
| "down"
|
||||
| "maximize"
|
||||
@@ -146,7 +145,7 @@
|
||||
|
||||
/* 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 {
|
||||
background: var(--rs-hover-bg);
|
||||
background: var(--rs-bg-active);
|
||||
border-color: var(--rs-border);
|
||||
color: var(--rs-text-strong);
|
||||
}
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@
|
||||
font: inherit;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.rs-find-button:hover:not(:disabled) { background: var(--rs-hover-bg); color: var(--rs-accent); }
|
||||
.rs-find-button:hover:not(:disabled) { background: var(--rs-bg-active); color: var(--rs-accent); }
|
||||
.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 input { margin: 0; accent-color: var(--rs-accent); }
|
||||
|
||||
@@ -83,16 +83,6 @@ export function workspaceWriteBytes(rel: string, base64: string): Promise<void>
|
||||
return invoke("workspace_write_bytes", { rel, base64 });
|
||||
}
|
||||
|
||||
/** Download a web image to `rel` plus the extension of its format. Returns the path of the new file. */
|
||||
export function workspaceSaveImageUrl(url: string, rel: string): Promise<string> {
|
||||
return invoke("workspace_save_image_url", { url, rel });
|
||||
}
|
||||
|
||||
/** Download a web image. Returns it as a data URL. */
|
||||
export function workspaceDownloadImage(url: string): Promise<string> {
|
||||
return invoke("workspace_download_image", { url });
|
||||
}
|
||||
|
||||
export type CopyResult = {
|
||||
name: string;
|
||||
rel_path: string;
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
@@ -1,40 +1,30 @@
|
||||
import { paneBounds, removePane, setSplitRatio, splitPane, type SplitLayout, type SplitPath } from "./splitLayout.ts";
|
||||
import { paneBounds, removePane, splitPane, type SplitLayout } from "./splitLayout.ts";
|
||||
|
||||
/**
|
||||
* 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 };
|
||||
/** `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 };
|
||||
export type DocumentPanes = { layout: SplitLayout; panes: DocumentPane[]; active: string };
|
||||
/** The content of a pane: a document ID or the key of a plugin editor view. */
|
||||
export type PaneContent = { documentId: string } | { pluginKey: string };
|
||||
|
||||
function emptyPane(id: string): DocumentPane {
|
||||
return { id, documentId: null, pluginKey: null, reading: false, split: false };
|
||||
}
|
||||
|
||||
function filled(id: string, content: PaneContent): DocumentPane {
|
||||
return "documentId" in content ? { ...emptyPane(id), documentId: content.documentId } : { ...emptyPane(id), pluginKey: content.pluginKey };
|
||||
}
|
||||
|
||||
export function initialDocumentPanes(): DocumentPanes {
|
||||
return { layout: "document-main", panes: [emptyPane("document-main")], active: "document-main" };
|
||||
return { layout: "document-main", panes: [{ id: "document-main", documentId: null, reading: false, split: false }], active: "document-main" };
|
||||
}
|
||||
|
||||
export function selectPane(state: DocumentPanes, id: string): DocumentPanes {
|
||||
return state.active === id || !state.panes.some(pane => pane.id === id) ? state : { ...state, active: id };
|
||||
}
|
||||
|
||||
/** The pane that shows the content, if a pane shows it. */
|
||||
export function paneOf(state: DocumentPanes, content: PaneContent): DocumentPane | undefined {
|
||||
return state.panes.find(pane => "documentId" in content ? pane.documentId === content.documentId : pane.pluginKey === content.pluginKey);
|
||||
/** Tabs own documents. Panes keep only a reference and local viewing state. */
|
||||
export function syncDocumentPanes(state: DocumentPanes, live: readonly string[], selected: string | null): DocumentPanes {
|
||||
const ids = new Set(live);
|
||||
let panes = state.panes.map(pane => pane.documentId && !ids.has(pane.documentId) ? { ...pane, documentId: null, reading: false, split: false } : pane);
|
||||
let active = state.active;
|
||||
if (selected && ids.has(selected)) {
|
||||
const existing = panes.find(pane => pane.documentId === selected);
|
||||
if (existing) active = existing.id;
|
||||
else panes = panes.map(pane => pane.id === active ? { ...pane, documentId: selected } : pane);
|
||||
}
|
||||
|
||||
/** Remove the panes that became empty. The last pane always stays. */
|
||||
function collapse(state: DocumentPanes, panes: DocumentPane[], active: string): DocumentPanes {
|
||||
let layout = state.layout;
|
||||
for (const pane of panes) {
|
||||
if (pane.documentId === null && pane.pluginKey === null && panes.length > 1) {
|
||||
if (pane.documentId === null && panes.length > 1) {
|
||||
const next = removePane(layout, pane.id);
|
||||
if (next !== null) { layout = next; panes = panes.filter(item => item.id !== pane.id); }
|
||||
}
|
||||
@@ -44,45 +34,14 @@ function collapse(state: DocumentPanes, panes: DocumentPane[], active: string):
|
||||
return { layout, panes, active };
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) };
|
||||
}
|
||||
|
||||
/** Show the content in a new pane beside `source`. When a pane already shows it, that pane becomes active. */
|
||||
export function splitWithContent(state: DocumentPanes, source: string, content: PaneContent, paneId: string, direction: "right" | "down" = "right"): DocumentPanes {
|
||||
const existing = paneOf(state, content);
|
||||
export function splitDocumentPane(state: DocumentPanes, source: string, documentId: string, paneId: string): DocumentPanes {
|
||||
const existing = state.panes.find(pane => pane.documentId === documentId);
|
||||
if (existing) return selectPane(state, existing.id);
|
||||
if (!state.panes.some(pane => pane.id === source) || state.panes.some(pane => pane.id === paneId)) return state;
|
||||
return { layout: splitPane(state.layout, source, paneId, direction), panes: [...state.panes, filled(paneId, content)], active: paneId };
|
||||
}
|
||||
|
||||
export function splitDocumentPane(state: DocumentPanes, source: string, documentId: string, paneId: string): DocumentPanes {
|
||||
return splitWithContent(state, source, { documentId }, paneId);
|
||||
return {
|
||||
layout: splitPane(state.layout, source, paneId, "right"),
|
||||
panes: [...state.panes, { id: paneId, documentId, reading: false, split: false }], active: paneId,
|
||||
};
|
||||
}
|
||||
|
||||
export function closeDocumentPane(state: DocumentPanes, id: string): DocumentPanes {
|
||||
@@ -91,49 +50,15 @@ export function closeDocumentPane(state: DocumentPanes, id: string): DocumentPan
|
||||
if (layout === null) return state;
|
||||
const bounds = paneBounds(state.layout);
|
||||
const panes = state.panes.filter(pane => pane.id !== id);
|
||||
const distance = (pane: DocumentPane) => Math.abs(bounds[pane.id].left - bounds[id].left) + Math.abs(bounds[pane.id].top - bounds[id].top);
|
||||
const neighbor = [...panes].sort((a, b) => distance(a) - distance(b))[0];
|
||||
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];
|
||||
return { layout, panes, active: state.active === id ? neighbor.id : state.active };
|
||||
}
|
||||
|
||||
/**
|
||||
* One pane shows a plugin view only beside other panes. When the last pane shows a plugin view,
|
||||
* the pane becomes empty and the result names the view, so that the caller can show it over the whole area.
|
||||
*/
|
||||
export function releaseSolePlugin(state: DocumentPanes): { state: DocumentPanes; pluginKey: string | null } {
|
||||
const [pane] = state.panes;
|
||||
if (state.panes.length !== 1 || pane.pluginKey === null) return { state, pluginKey: null };
|
||||
return { state: { ...state, panes: [{ ...pane, pluginKey: null }] }, pluginKey: pane.pluginKey };
|
||||
}
|
||||
|
||||
/** The place of a tab drop on a pane: the pane itself, or a new pane on its right or bottom side. */
|
||||
export type PaneDrop = "center" | "right" | "down";
|
||||
|
||||
/**
|
||||
* Show the content in the `target` pane (`center`), or in a new pane beside it.
|
||||
* The content leaves the pane that showed it before, so that it shows in one pane only.
|
||||
* The content that the drop replaces stays open as a tab.
|
||||
*/
|
||||
export function dropInPane(state: DocumentPanes, content: PaneContent, target: string, zone: PaneDrop, paneId: string): DocumentPanes {
|
||||
if (!state.panes.some(pane => pane.id === target)) return state;
|
||||
const current = paneOf(state, content);
|
||||
if (current?.id === target) return selectPane(state, target);
|
||||
const cleared = state.panes.map(pane => pane.id === current?.id ? emptyPane(pane.id) : pane);
|
||||
if (zone === "center") return collapse(state, cleared.map(pane => pane.id === target ? filled(target, content) : pane), target);
|
||||
return splitWithContent(collapse(state, cleared, target), target, content, paneId, zone);
|
||||
}
|
||||
|
||||
/** Give a new ratio to a split between panes. */
|
||||
export function resizeDocumentPanes(state: DocumentPanes, path: SplitPath, ratio: number): DocumentPanes {
|
||||
const layout = setSplitRatio(state.layout, path, ratio);
|
||||
return layout === state.layout ? state : { ...state, layout };
|
||||
}
|
||||
|
||||
export function readDocumentPane(state: DocumentPanes, id: string, reading: boolean): DocumentPanes {
|
||||
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, reading, split: reading ? false : pane.split } : pane) };
|
||||
}
|
||||
|
||||
/** Show or hide the Read view beside the editor. Read beside ends the Read-only view. */
|
||||
/** Show or hide the Read view beside the editor. Split ends the Read-only view. */
|
||||
export function splitDocumentView(state: DocumentPanes, id: string, split: boolean): DocumentPanes {
|
||||
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, split, reading: split ? false : pane.reading } : pane) };
|
||||
}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
/**
|
||||
* The natural sizes of the images that the app has loaded. The views use them to keep the space of an image before it
|
||||
* loads. Without this space the text moves when an image loads, and each new height starts a layout pass of the editor.
|
||||
*/
|
||||
const sizes = new Map<string, { width: number; height: number }>();
|
||||
|
||||
// A data URL can hold megabytes. The key keeps the map from holding the image data.
|
||||
function key(url: string) {
|
||||
if (url.length <= 256) return url;
|
||||
const middle = url.length >> 1;
|
||||
return `${url.length}:${url.slice(middle, middle + 64)}`;
|
||||
}
|
||||
|
||||
export function imageSize(url: string) {
|
||||
return sizes.get(key(url));
|
||||
}
|
||||
|
||||
export function rememberImageSize(url: string, width: number, height: number) {
|
||||
if (width > 0 && height > 0) sizes.set(key(url), { width, height });
|
||||
}
|
||||
|
||||
/** Read the size of an image that the app holds as data. A remote image gives its size when it loads in a view. */
|
||||
export function loadImageSize(url: string): Promise<void> {
|
||||
if (!url.startsWith("data:image/") || imageSize(url)) return Promise.resolve();
|
||||
return new Promise(resolve => {
|
||||
const image = new Image();
|
||||
image.onload = () => { rememberImageSize(url, image.naturalWidth, image.naturalHeight); resolve(); };
|
||||
image.onerror = () => resolve();
|
||||
image.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
/** The width of the text column at its largest. It gives an estimate before the editor can measure an image. */
|
||||
const columnWidth = 740;
|
||||
/** The margins of an image frame, from `.md-image-frame`. */
|
||||
const frameMargins = 45;
|
||||
|
||||
/** The estimated height of an image in Write, from the size attributes of its HTML. A negative value means that the size is not known. */
|
||||
export function estimatedImageHeight(html: string) {
|
||||
const match = /\bwidth="(\d+)" height="(\d+)"/.exec(html);
|
||||
if (!match) return -1;
|
||||
const width = Number(match[1]), height = Number(match[2]);
|
||||
return Math.round(height * Math.min(1, columnWidth / width)) + frameMargins;
|
||||
}
|
||||
@@ -96,39 +96,6 @@ export function attachmentRel(fileName: string): string {
|
||||
return `attachments/${stamp}-${crypto.randomUUID()}-${safe}`;
|
||||
}
|
||||
|
||||
const ENTITIES: Record<string, string> = { amp: "&", quot: '"', apos: "'", "#39": "'", lt: "<", gt: ">" };
|
||||
|
||||
/**
|
||||
* The web address of a copied image. A browser puts only the first frame on the clipboard,
|
||||
* with HTML that names the original file.
|
||||
*/
|
||||
export function pastedImageSource(html: string): string | undefined {
|
||||
const images = [...html.matchAll(/<img\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi)];
|
||||
if (images.length !== 1) return undefined;
|
||||
const [, double, single, bare] = images[0];
|
||||
const source = (double ?? single ?? bare).trim().replace(/&(amp|quot|apos|#39|lt|gt);/g, (_, name: string) => ENTITIES[name]);
|
||||
try {
|
||||
const url = new URL(source);
|
||||
return /^https?:$/.test(url.protocol) ? url.href : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** A GIF, WebP, or AVIF address. These formats can have more frames, so the original is worth a download. */
|
||||
export function mayAnimate(source: string): boolean {
|
||||
return /\.(?:gif|webp|avif)$/i.test(new URL(source).pathname);
|
||||
}
|
||||
|
||||
const EXTENSIONS: Record<string, string> = {
|
||||
"image/gif": "gif", "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/avif": "avif", "image/bmp": "bmp",
|
||||
};
|
||||
|
||||
/** The file extension of an image data URL, or undefined for another type. */
|
||||
export function dataUrlExtension(data: string): string | undefined {
|
||||
return EXTENSIONS[/^data:([^;,]+)[;,]/.exec(data)?.[1] ?? ""];
|
||||
}
|
||||
|
||||
export function imageFiles(data: DataTransfer | null): File[] {
|
||||
return [...(data?.files ?? [])].filter(file => isImagePath(file.name));
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import { inlineMathEnd } from "./inlineMath.ts";
|
||||
import { activeTableFormulas } from "../formulas/index.ts";
|
||||
import { hasTableDelimiter } from "../editor/markdownTable.ts";
|
||||
import { footnotes, renderFootnotes, type FootnoteEnvironment } from "../editor/footnotes.ts";
|
||||
import { imageSize } from "./imageSizes.ts";
|
||||
|
||||
const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false });
|
||||
markdown.use(footnotes);
|
||||
@@ -163,8 +162,7 @@ markdown.renderer.rules.image = (tokens, index, _options, env, renderer) => {
|
||||
const alt = renderer.renderInlineAsText(token.children || [], markdown.options, env);
|
||||
// Only app-resolved image data or HTTP(S) URLs become image sources.
|
||||
if (!/^(?:https?:\/\/|data:image\/)/i.test(resolved)) return `<span class="missing-image" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}" alt="${escapeHtml(alt)}">Image unavailable: ${escapeHtml(alt || original)}</span>`;
|
||||
const size = imageSize(resolved);
|
||||
return `<img src="${escapeHtml(resolved)}" alt="${escapeHtml(alt)}" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}"${size ? ` width="${size.width}" height="${size.height}"` : ""} loading="lazy">`;
|
||||
return `<img src="${escapeHtml(resolved)}" alt="${escapeHtml(alt)}" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}" loading="lazy">`;
|
||||
};
|
||||
markdown.renderer.rules.table_open = () => '<div class="md-table-scroll"><table>\n';
|
||||
markdown.renderer.rules.table_close = () => '</table></div>\n';
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
/** A split gives `ratio` of its size to `first`. A split without a ratio divides its size in two equal parts. */
|
||||
export type SplitLayout = string | { direction: "right" | "down"; first: SplitLayout; second: SplitLayout; ratio?: number };
|
||||
export type SplitLayout = string | { direction: "right" | "down"; first: SplitLayout; second: SplitLayout };
|
||||
export type PaneBounds = { left: number; top: number; width: number; height: number };
|
||||
/** The path from the root to a split: the side of each split on the way. */
|
||||
export type SplitPath = readonly ("first" | "second")[];
|
||||
/** A divider between the two sides of a split. `bounds` is the area of the split, in percent of the root. */
|
||||
export type SplitDivider = { path: SplitPath; direction: "right" | "down"; ratio: number; bounds: PaneBounds };
|
||||
const ratioOf = (tree: Exclude<SplitLayout, string>) => tree.ratio ?? 0.5;
|
||||
|
||||
export function containsPane(tree: SplitLayout, key: string): boolean {
|
||||
return typeof tree === "string" ? tree === key : containsPane(tree.first, key) || containsPane(tree.second, key);
|
||||
@@ -24,47 +18,8 @@ export function removePane(tree: SplitLayout, key: string): SplitLayout | null {
|
||||
|
||||
export function paneBounds(tree: SplitLayout, bounds: PaneBounds = { left: 0, top: 0, width: 100, height: 100 }): Record<string, PaneBounds> {
|
||||
if (typeof tree === "string") return { [tree]: bounds };
|
||||
const [a, b] = sides(tree, bounds);
|
||||
const a = { ...bounds }, b = { ...bounds };
|
||||
if (tree.direction === "right") { a.width /= 2; b.width /= 2; b.left += a.width; }
|
||||
else { a.height /= 2; b.height /= 2; b.top += a.height; }
|
||||
return { ...paneBounds(tree.first, a), ...paneBounds(tree.second, b) };
|
||||
}
|
||||
|
||||
function sides(tree: Exclude<SplitLayout, string>, bounds: PaneBounds): [PaneBounds, PaneBounds] {
|
||||
const a = { ...bounds }, b = { ...bounds }, ratio = ratioOf(tree);
|
||||
if (tree.direction === "right") { a.width = bounds.width * ratio; b.width = bounds.width - a.width; b.left += a.width; }
|
||||
else { a.height = bounds.height * ratio; b.height = bounds.height - a.height; b.top += a.height; }
|
||||
return [a, b];
|
||||
}
|
||||
|
||||
/** Each split of the tree, with its place, for the dividers that change its ratio. */
|
||||
export function splitDividers(tree: SplitLayout, bounds: PaneBounds = { left: 0, top: 0, width: 100, height: 100 }, path: SplitPath = []): SplitDivider[] {
|
||||
if (typeof tree === "string") return [];
|
||||
const [a, b] = sides(tree, bounds);
|
||||
return [{ path, direction: tree.direction, ratio: ratioOf(tree), bounds },
|
||||
...splitDividers(tree.first, a, [...path, "first"]), ...splitDividers(tree.second, b, [...path, "second"])];
|
||||
}
|
||||
|
||||
/** Give a new ratio to the split at `path`. The ratio stays between 0.1 and 0.9. */
|
||||
export function setSplitRatio(tree: SplitLayout, path: SplitPath, ratio: number): SplitLayout {
|
||||
if (typeof tree === "string" || !Number.isFinite(ratio)) return tree;
|
||||
if (!path.length) {
|
||||
const next = Math.round(Math.max(0.1, Math.min(0.9, ratio)) * 1000) / 1000;
|
||||
return next === ratioOf(tree) ? tree : { ...tree, ratio: next };
|
||||
}
|
||||
const [side, ...rest] = path;
|
||||
const child = setSplitRatio(tree[side], rest, ratio);
|
||||
return child === tree[side] ? tree : { ...tree, [side]: child };
|
||||
}
|
||||
|
||||
/** The same panes in the same order, one above the other. A narrow area uses it. */
|
||||
export function stackLayout(tree: SplitLayout): SplitLayout {
|
||||
return typeof tree === "string" ? tree : { ...tree, direction: "down", first: stackLayout(tree.first), second: stackLayout(tree.second) };
|
||||
}
|
||||
|
||||
/** The direction of the split that put `key` beside a different pane, and the first pane on the other side. */
|
||||
export function splitSibling(tree: SplitLayout, key: string): { direction: "right" | "down"; sibling: string } | null {
|
||||
if (typeof tree === "string") return null;
|
||||
const first = (node: SplitLayout): string => typeof node === "string" ? node : first(node.first);
|
||||
if (tree.second === key) return { direction: tree.direction, sibling: first(tree.first) };
|
||||
if (tree.first === key) return { direction: tree.direction, sibling: first(tree.second) };
|
||||
return splitSibling(tree.first, key) ?? splitSibling(tree.second, key);
|
||||
}
|
||||
|
||||
@@ -6,8 +6,6 @@ export interface WorkbenchLayout {
|
||||
leftWidth: number;
|
||||
rightWidth: number;
|
||||
leftView: "files" | "search" | "bookmarks";
|
||||
/** The Backlinks section below the outline is expanded. */
|
||||
backlinksOpen: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_WORKBENCH_LAYOUT: Readonly<WorkbenchLayout> = {
|
||||
@@ -16,7 +14,6 @@ export const DEFAULT_WORKBENCH_LAYOUT: Readonly<WorkbenchLayout> = {
|
||||
leftWidth: 260,
|
||||
rightWidth: 240,
|
||||
leftView: "files",
|
||||
backlinksOpen: true,
|
||||
};
|
||||
|
||||
function width(value: unknown, fallback: number): number {
|
||||
@@ -32,7 +29,6 @@ export function parseWorkbenchLayout(raw: string | null): WorkbenchLayout {
|
||||
leftWidth: width(value?.leftWidth, DEFAULT_WORKBENCH_LAYOUT.leftWidth),
|
||||
rightWidth: width(value?.rightWidth, DEFAULT_WORKBENCH_LAYOUT.rightWidth),
|
||||
leftView: ["files", "search", "bookmarks"].includes(value?.leftView) ? value.leftView : DEFAULT_WORKBENCH_LAYOUT.leftView,
|
||||
backlinksOpen: typeof value?.backlinksOpen === "boolean" ? value.backlinksOpen : DEFAULT_WORKBENCH_LAYOUT.backlinksOpen,
|
||||
};
|
||||
} catch { return { ...DEFAULT_WORKBENCH_LAYOUT }; }
|
||||
}
|
||||
|
||||
@@ -80,11 +80,11 @@ export function settle(page) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Choose "Write", "Source", or "Read" in the view control of a document pane, or toggle "Read beside" (src/lib/layout/ViewModes.svelte).
|
||||
* Choose "Write", "Source", or "Read" in the view control of a document pane, or toggle "Split" (src/lib/layout/ViewModes.svelte).
|
||||
* `scope` is the page, or a pane locator when the window shows more than one document pane.
|
||||
*/
|
||||
export async function chooseView(scope, name) {
|
||||
if (name === "Read beside") return scope.locator(".chrome-bar").getByRole("button", { name: "Read beside", exact: true }).click();
|
||||
if (name === "Split") return scope.locator(".chrome-bar").getByRole("button", { name: "Split", exact: true }).click();
|
||||
return scope.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name, exact: true }).click();
|
||||
}
|
||||
|
||||
|
||||
@@ -88,11 +88,6 @@ function pmCommands(test) {
|
||||
else workspace.folders.add(rel);
|
||||
return null;
|
||||
}),
|
||||
// The download of a copied web image: a 1 by 1 GIF. An address with "offline" fails.
|
||||
workspace_download_image: ({ url }) => {
|
||||
if (url.includes("offline")) throw new Error("Cannot reach the image server");
|
||||
return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
|
||||
},
|
||||
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
|
||||
spelling_menu_install: () => null,
|
||||
"plugin:window|is_maximized": () => false,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user