Compare commits
125
Commits
master
..
3c099e7f49
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c099e7f49 | ||
|
|
5c4d759c1b | ||
|
|
2ca7752c9d | ||
|
|
68c302a271 | ||
|
|
19ef8f2e15 | ||
|
|
28661f28bc | ||
|
|
33495d2bf7 | ||
|
|
e4be352a2b | ||
|
|
6e1b24e40f | ||
|
|
31ce7e73ce | ||
|
|
8e2df5544a | ||
|
|
bc15f70a34 | ||
|
|
648a5672e7 | ||
|
|
9fc1490988 | ||
|
|
b2993e81a3 | ||
|
|
7c2d526e13 | ||
|
|
424a817c90 | ||
|
|
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
|
||||
@@ -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/KnottyWyvern-GH/RuneStone`. Its releases page holds the installers, the browser engine ZIPs, and the SDK packages.
|
||||
|
||||
## Skills
|
||||
|
||||
|
||||
@@ -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,17 +4,21 @@ 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/KnottyWyvern-GH/RuneStone/releases/download/v1.0.0/RuneStone_1.0.0_x64-setup.exe).
|
||||
2. Open the installer and complete setup.
|
||||
3. Open RuneStone from the Start menu.
|
||||
| Platform | Installer | Status |
|
||||
| --- | --- | --- |
|
||||
| Windows 10 or 11, x64 | [RuneStone_0.1.53_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.53/RuneStone_0.1.53_x64-setup.exe) | Primary platform |
|
||||
| macOS, Apple silicon | [RuneStone_0.1.44_aarch64.dmg](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_aarch64.dmg) | Experimental: ad hoc signed, not notarized |
|
||||
| Linux, amd64 | [RuneStone_0.1.51_amd64.deb](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.51/RuneStone_0.1.51_amd64.deb) | Experimental: built on Ubuntu 26.04.1, needs GLIBC 2.39 or newer |
|
||||
|
||||
The built-in browser needs a separate engine download of about 160 MB. A browser tab offers it on first use.
|
||||
- **Windows:** Open the installer and complete setup. Then open RuneStone from the Start menu.
|
||||
- **macOS:** Open the disk image and drag RuneStone into Applications. Then open RuneStone from Applications.
|
||||
- **Linux:** Run `sudo apt install ./RuneStone_0.1.51_amd64.deb` in the download folder. Then open RuneStone from your applications menu.
|
||||
|
||||
On Windows, the built-in browser needs a separate engine download of about 160 MB. A browser tab offers it on first use.
|
||||
For checksums, updates, and reinstalls, see [Installation and updates](docs/installation.md).
|
||||
|
||||
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.
|
||||
@@ -22,7 +26,7 @@ macOS and Linux have no 1.0.0 package. Build RuneStone from source on these syst
|
||||
- Find files, search a workspace, and resolve changes that other tools make to your files.
|
||||
- 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 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
|
||||
|
||||
[KnottyWyvern-GH](https://github.com/KnottyWyvern-GH)
|
||||
[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 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
|
||||
@@ -20,4 +20,4 @@ Build procedure: frozen pnpm install; Browser npm ci, checks, tests, engine test
|
||||
|
||||
Artifact: `releases/0.1.44/RuneStone_0.1.44_aarch64.dmg`. Logs and packaging scripts remain under `output/macos-installer-0.1.44/`.
|
||||
|
||||
Published alongside the existing Windows installer in the Gitea 0.1.44 release, with `macos-release-notes.md` as a separate attachment. The existing release tag was retained.
|
||||
Published alongside the existing Windows installer in the [Gitea 0.1.44 release](https://git.knottywyvern.com/kwyvern/RuneStone/releases/tag/v0.1.44), with `macos-release-notes.md` as a separate attachment. The existing release tag was retained.
|
||||
|
||||
+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
|
||||
@@ -0,0 +1 @@
|
||||
80ee6a5274c15333ac793d76b3b82164199e30344e6826218f593a7e842374f7 RuneStone_0.1.51_amd64.deb
|
||||
@@ -1 +0,0 @@
|
||||
72b17356fdb42a58051a84961e36fdd893ff26e210e7f855b8a96cde69ce946e 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).
|
||||
|
||||
@@ -955,7 +955,7 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
|
||||
- Scope: The main header, the side pane, the left ribbon, the tab bars, the Settings and Browser window title bars, and the window builders of the host.
|
||||
- Shared implementation: `WorkbenchHeader.svelte`, `LeftPane.svelte`, `PluginRibbon.svelte`, `TabBar.svelte`, `WindowControls.svelte`, `src-tauri/src/window_frame.rs`, `src-tauri/tauri.macos.conf.json`, and the `--rs-titlebar-inset-start` token.
|
||||
- Evidence: `tests/smoke/layout/titleBar.smoke.mjs` and the Rust command list test.
|
||||
- Replaces / replaced by: The left pane footer, and the ribbon rule "The ribbon has no width when it has no entries." [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
|
||||
@@ -1123,54 +1123,3 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
|
||||
- Evidence: `tests/smoke/menus/consistency.smoke.mjs` and `tests/smoke/features/background.smoke.mjs` check the 82% menu, the blur, and the 6% veil with an image, and opaque fills without one. `tests/unit/theme/characterPalettes.spec.ts` checks the Silver Serpent row colors on a hovered row over a white image.
|
||||
- Replaces: The image rule of [UI-043](#ui-043--opaque-menus). Menus without an image stay opaque.
|
||||
- Limits: Over the brightest image areas, dim text on a hovered row has about 15% less contrast than on the pane around it. Browser checks use desktop service mocks. Native desktop acceptance remains open.
|
||||
|
||||
### UI-062 — Tabs use the free header space
|
||||
|
||||
- Type: Rule change
|
||||
- Date: 2026-11-02
|
||||
- Status: Implemented for user review
|
||||
- Decision source: Card 7f1d29d6 ("wasted free space") reports empty header space beside tabs that scroll.
|
||||
- Previous rule: [UI-050](#ui-050--global-actions-tabs-and-platform-title-bars). A drag area of 120 pixels sat after the tabs. The tabs shrank and scrolled first, so the 120 pixels stayed empty while tabs were out of view.
|
||||
- New rule: The drag area fills the free space after the + button. When the tabs need more room, they use all space up to a drag area of 48 pixels. Then they scroll. Tabs keep their minimum width of 120 pixels. [Interface design](ui-design.md) holds the rule.
|
||||
- Reason: Space that shows a tab is more useful than empty space. 48 pixels keep the window movable when the side pane is closed. While the side pane is open, the empty part of the header above it is also a drag area.
|
||||
- Scope: The header of the main window and of detached tab windows. The header of the browser window keeps its drag area of at least 120 pixels.
|
||||
- Shared implementation: `src/lib/layout/WorkbenchHeader.svelte`.
|
||||
- Exceptions: None.
|
||||
- Evidence: `tests/smoke/layout/titleBar.smoke.mjs` checks a drag area that fills the header with one tab, and a drag area of 48 pixels at the end of the header when 11 tabs scroll.
|
||||
- Replaces / replaced by: The drag area rule of [UI-050](#ui-050--global-actions-tabs-and-platform-title-bars).
|
||||
- Limits: Browser checks use desktop service mocks. The native window drag on the smaller area needs native acceptance.
|
||||
|
||||
### UI-063 — PDF pages in one column
|
||||
|
||||
- Type: Rule change
|
||||
- Date: 2026-11-09
|
||||
- Status: Implemented for user review
|
||||
- Decision source: Cards 9b7b246e, 59ff5dc1, 2e425cbc, 7bd092d2, 2142ca04, and c0900ae8 report a PDF toolbar that a background image hides, no custom zoom, no scroll between pages, lost focus after Ctrl+Tab, and Page Up and Page Down that change pages.
|
||||
- Previous rule: [UI-059](#ui-059--the-pdf-toolbar-on-shared-controls). The tab showed one page at a time. Page Up and Page Down changed the page. The zoom percent was text. The tab had no surface of its own, so a background image showed through the toolbar and the status line.
|
||||
- New rule: The tab shows all pages in one column that scrolls. The wheel, the scroll bar, Page Up, Page Down, Home, End, and the arrow keys scroll. The page field shows the page that fills most of the tab. **Previous page**, **Next page**, and the page field show the top of a page. The zoom percent is a field: a typed percent and Enter set the zoom from 25% to 400%. Ctrl and the wheel also change the zoom. The toolbar, the status line, and the password form are opaque (`--rs-bg-elevated`) with and without a background image. The page area uses the editor surface (`--rs-workarea-editor-bg`). Ctrl+Tab and Ctrl+Shift+Tab give keyboard focus to the new plugin tab.
|
||||
- Reason: A reader scrolls through a document. A page change on Page Down hides the rest of a page that is higher than the tab. A toolbar must stay readable over each image, as headers do.
|
||||
- Scope: The PDF tab. The focus rule applies to each plugin tab: the host focuses the element that the view marks with `data-tab-focus`, or the view.
|
||||
- Shared implementation: `src/lib/features/pdf/PdfViewer.svelte`, `src/lib/features/pdf/model.ts`, `src/lib/plugins/PluginEditor.svelte` (`focus`), and the tab commands in `src/lib/layout/Workbench.svelte`.
|
||||
- Exceptions: A click on a tab or an arrow key in the tab bar keeps the focus in the tab bar.
|
||||
- Evidence: `tests/smoke/features/pdf.smoke.mjs` and `tests/unit/features/pdf.spec.ts`.
|
||||
- Replaces / replaced by: The one-page rule and the zoom text of [UI-059](#ui-059--the-pdf-toolbar-on-shared-controls).
|
||||
- Limits: Only the pages near the visible area have a drawing. Until the viewer reads the size of a page, the page has the size of the first page. Browser checks use desktop service mocks. Native desktop acceptance remains open.
|
||||
|
||||
### UI-064 — Split view shows different tabs
|
||||
|
||||
- Type: Rule change
|
||||
- Date: 2026-11-10
|
||||
- Status: Implemented for user review
|
||||
- Decision source: Card 565874b2 reports that split view shows only the same document side by side. The user expects different documents side by side, also with a web browser.
|
||||
- Previous rule: [UI-021](#ui-021--workspace-links-in-document-panes). Only a file tree item or a workspace link opened a document to the right. Document panes held only documents. A plugin tab, for example a browser tab, covered the whole document area. The **Split** toggle showed Read beside the editor of the same document.
|
||||
- New rule: Each tab menu has **Open to the right**. It shows the tab in a new pane to the right of the active pane. A pane shows a document or a plugin tab. A tab shows in one pane at most, so the item is unavailable for a visible tab. A tab that the user selects, or a file that the user opens, replaces the content of the active pane. The replaced tab stays open. A plugin tab that covers the area moves to the active pane when a tab opens beside it. When one pane is left, its plugin tab covers the area again. A plugin pane has a bar with its title and **Close split**. A document pane beside other panes shows the full path in its bar. The **Split** toggle is now **Read beside**. The file tree menu also has **Open to the right**, also for PDF files and boards. A divider between two panes changes their sizes, with the pointer or the keyboard. A double-click gives the panes equal sizes. A tab that the user drags from the tab bar to a pane replaces the content of that pane. A drop on the left, right, or bottom part of a pane opens a new pane there (left: card 156758f1). A hint shows the place of the drop. The tab that a pane shows can also go to the left, right, or bottom part of its own pane (card e0dc8473). The tab moves to the new pane. The old pane then shows the nearest tab that no pane shows: first the tabs after it, then the tabs before it. Below a plugin tab that covers the area, the old pane shows its document. Without such a tab, the drag shows no hint.
|
||||
- Reason: "Split" named two different things. Users compare a note with a different note, with a web page, or with a PDF file. Equal pane sizes did not fit a web page or a PDF page beside a note.
|
||||
- Scope: Document panes, plugin editor tabs, the tab menu, the tab bar, the file tree menu, and the view control.
|
||||
- Shared implementation: `src/lib/workspace/documentPanes.ts`, `src/lib/workspace/splitLayout.ts` (`stackLayout`, `splitSibling`, `splitDividers`, `setSplitRatio`), `src/lib/layout/DocumentArea.svelte`, `src/lib/layout/TabBar.svelte` (`onDragAt`, `onDropAt`), and `src/lib/layout/Workbench.svelte`. A plugin view stays in the plugin layer above the panes, so a move between panes does not mount it again.
|
||||
- Exceptions: In the menu of a browser tab, **New tab to the right** and **New tab below** open a new browser tab with the home page in a pane beside the tab. These items replace **Split right** and **Split down**, which opened a copy of the page in a split of plugin views only. The separate browser window keeps its own plugin split.
|
||||
- Narrow layout: An area of 640 pixels or less shows the panes one above the other, in the same order and with the same ratios. The area does not scroll. Each pane keeps its own scroll bar. A tab drop opens a new pane only below.
|
||||
- Evidence: `tests/smoke/layout/mixedSplits.smoke.mjs`, `tests/smoke/layout/visibleTabDrag.smoke.mjs` (real mouse input), `tests/smoke/layout/pdfBesideNote.smoke.mjs`, `tests/smoke/layout/splits.smoke.mjs`, and `tests/unit/layout/documentPanes.spec.ts`.
|
||||
- Replaces / replaced by: The document-only panes of [UI-021](#ui-021--workspace-links-in-document-panes), and the name **Split** of [UI-049](#ui-049--one-view-control-and-one-file-name).
|
||||
- Limits: A tab from a different window opens in the tab bar, not in a pane. Browser checks use desktop service mocks. Native desktop acceptance remains open.
|
||||
|
||||
Update 2026-11-16: The user did not find a way to close a split without closing the tab. The **Close split** button showed only a close icon, so it looked like the close button of a tab. Now the button shows a split icon and its name (`src/lib/layout/CloseSplitButton.svelte`). In a pane of 420 pixels or less, it shows only the icon, and a tooltip gives the name. The tab menu also has **Close split** for a tab in a pane beside other panes. The tab stays open. Evidence: `tests/smoke/layout/visibleTabDrag.smoke.mjs`.
|
||||
|
||||
+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/KnottyWyvern-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.
|
||||
|
||||
@@ -24,11 +24,11 @@ Select an image, then right-click it or press Shift+F10 for these actions:
|
||||
- **Copy path** and **Show in Explorer**, for workspace images
|
||||
|
||||
**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 +97,7 @@ Start a cell with `=` to make a formula. Columns use letters A, B, … AA. Row 1
|
||||
| Functions | SUM, AVERAGE, MIN, MAX, COUNT, ABS, and ROUND |
|
||||
|
||||
Functions that take a range ignore text and blank cells. Arithmetic uses zero for a blank cell.
|
||||
Results update in Write, Read, and 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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
+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/KnottyWyvern-GH/RuneStone/releases/download/v1.0.0/RuneStone_1.0.0_x64-setup.exe) | Installs for the current Windows account |
|
||||
| macOS, Apple silicon | None | Build the app from source. See [macOS packages](builds.md#macos-packages). Intel Macs are not supported. |
|
||||
| Linux, amd64 | None | Build a Debian package from source. See [Build Linux packages](builds.md#build-linux-packages). |
|
||||
| Windows 10 or 11, x64 | [RuneStone_0.1.53_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.53/RuneStone_0.1.53_x64-setup.exe) | Installs for the current Windows account |
|
||||
| macOS, Apple silicon | [RuneStone_0.1.44_aarch64.dmg](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_aarch64.dmg) | Experimental. Intel Macs are not supported. |
|
||||
| Linux, amd64 | [RuneStone_0.1.51_amd64.deb](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.51/RuneStone_0.1.51_amd64.deb) | Experimental. Built on Ubuntu 26.04.1. Needs GLIBC 2.39 or newer. |
|
||||
|
||||
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/KnottyWyvern-GH/RuneStone/raw/master/docs/checksums/1.0.0/windows-SHA256SUMS) to Downloads.
|
||||
2. Open PowerShell in Downloads.
|
||||
3. Check the download:
|
||||
|
||||
```powershell
|
||||
$expected = (Get-Content .\windows-SHA256SUMS).Split(' ')[0]
|
||||
(Get-FileHash .\RuneStone_1.0.0_x64-setup.exe).Hash -eq $expected
|
||||
```
|
||||
|
||||
If the result is not `True`, delete the file and download it again.
|
||||
4. Open the setup file.
|
||||
5. Complete setup. Keep the default destination unless you need another location.
|
||||
6. Open RuneStone from the Start menu.
|
||||
1. Save `RuneStone_0.1.53_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.51_amd64.deb` and [linux-SHA256SUMS](https://git.knottywyvern.com/kwyvern/RuneStone/raw/branch/master/docs/checksums/0.1.51/linux-SHA256SUMS) to Downloads.
|
||||
2. Open Terminal in Downloads.
|
||||
3. Check the download:
|
||||
|
||||
```bash
|
||||
sudo apt install ./RuneStone_1.0.0_amd64.deb
|
||||
sha256sum --check linux-SHA256SUMS
|
||||
```
|
||||
|
||||
3. Open RuneStone from your applications menu, or run `runestone` in Terminal.
|
||||
If the result is not `OK`, delete the file and download it again.
|
||||
4. Install the package:
|
||||
|
||||
```bash
|
||||
sudo apt install ./RuneStone_0.1.51_amd64.deb
|
||||
```
|
||||
|
||||
5. Open RuneStone from your applications menu, or run `runestone` in Terminal.
|
||||
|
||||
APT installs the system libraries that the package declares. Run RuneStone as your ordinary desktop user.
|
||||
|
||||
@@ -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.51_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/KnottyWyvern-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/KnottyWyvern-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/KnottyWyvern-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.
|
||||
|
||||
+2
-2
@@ -150,7 +150,7 @@ Decisions: [UI-002](design-decisions.md#ui-002--share-the-requested-dropdown-des
|
||||
- The main header holds navigation, document tabs, Save, the outline toggle, and window controls. The other tools are in the left ribbon, so the tabs keep their room. A detached tab window has no ribbon, so its header keeps those tools.
|
||||
- A bar at the bottom of the side pane holds the workspace switcher, Help, and Settings, as in Obsidian. The switcher names the workspace and opens the workspace list above it.
|
||||
- The left ribbon is always present. It holds the tools, then a line, then the plugin view shortcuts. The tools are New browser tab, Terminal, Project Management, Plug-in views, and Commands. A tool of an off feature does not show. Its menus open at its right. While the side pane is closed, the workspace switcher, Help, and Settings move to the bottom of the ribbon, so they stay reachable.
|
||||
- Tabs keep a minimum width of 120 pixels and scroll. Fades show tabs out of view, and ⌄ lists all tabs. A drag area 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,7 +222,7 @@ Decisions: [UI-009](design-decisions.md#ui-009--character-theme-appearances), [U
|
||||
|
||||
- The app image fills the work area below the titlebar, including new tabs and document views. It stays fixed while content scrolls.
|
||||
- Sidebars use `--rs-image-sidebar-bg` (82% tint). Editor surfaces use `--rs-image-editor-bg` (90% tint). Without an image, both are opaque.
|
||||
- Write, Source, Read, and 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.
|
||||
|
||||
+8
-29
@@ -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,25 +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 left, right, or bottom part opens a new pane there. A hint shows the place before you release the tab.
|
||||
You can also drag the tab that a pane shows to the left, right, or bottom part of that pane. The tab moves to the new pane, and the old pane shows the next tab that is not visible. This needs a second tab that is not visible.
|
||||
|
||||
- Click a pane to make its tab the active tab. A tab that you select, or a file that you open, replaces the content of the active pane. The replaced tab stays open.
|
||||
- Drag the divider between two panes to change their sizes. Double-click the divider to give the panes equal sizes. With the keyboard, focus the divider and use the arrow keys.
|
||||
- A pane beside other panes names its file in the bar above the document. To close the pane, select **Close split** in that bar. You can also right-click its tab and select **Close split**. The tab stays open.
|
||||
- A browser tab or a PDF tab that fills the area moves to the left pane when a tab opens to the right. When one pane is left, its tab fills the area again.
|
||||
- In the menu of a browser tab, **New tab to the right** and **New tab below** open a new browser tab with the home page in a pane beside it.
|
||||
- The link menu also has **Open to the right**. In a narrow window, the panes show one above the other.
|
||||
|
||||
## Save your work
|
||||
|
||||
Auto-save is on by default. It saves changed files every 5 seconds, also in background tabs. RuneStone does not write unchanged files.
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "runestone",
|
||||
"version": "1.0.0a",
|
||||
"version": "0.1.53",
|
||||
"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/KnottyWyvern-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/KnottyWyvern-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/KnottyWyvern-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/KnottyWyvern-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/KnottyWyvern-GH/RuneStone/blob/master/docs/plugin-development.md): the package format, the API, and the build procedure
|
||||
- [Completion API](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/completion.md)
|
||||
- [Install and manage plugins](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/plugins.md)
|
||||
- [Release policy](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/releases.md#sdk-releases)
|
||||
- [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/KnottyWyvern-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.
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ export const actionIcons = {
|
||||
puzzle: '<path d="M9 3H4v6a3 3 0 1 1 0 6v5h6a3 3 0 1 1 6 0h4v-6a3 3 0 1 0 0-6V3h-5a3 3 0 1 1-6 0Z"/>',
|
||||
'split-right': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M12 4v16m3-11 3 3-3 3"/>',
|
||||
'split-down': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 12h18m-12 3 3 3 3-3"/>',
|
||||
'split-close': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="m7 9 3 3-3 3m10-6-3 3 3 3"/>',
|
||||
kanban: '<rect x="3" y="4" width="5" height="16" rx="1"/><rect x="10" y="4" width="5" height="11" rx="1"/><rect x="17" y="4" width="4" height="7" rx="1"/>',
|
||||
bookmark: '<path d="M6 4h12v16l-6-3-6 3z"/>',
|
||||
'file-plus': '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M12 18v-6M9 15h6"/>',
|
||||
|
||||
Generated
+1
-1
@@ -3130,7 +3130,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "runestone"
|
||||
version = "1.0.0+1"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"dunce",
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
[package]
|
||||
name = "runestone"
|
||||
version = "1.0.0+1"
|
||||
version = "0.1.53"
|
||||
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.0a"
|
||||
version = "0.1.53"
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"protocol": 1,
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"url": "https://github.com/KnottyWyvern-GH/RuneStone/releases/download/browser-engine-v0.1.11/RuneStone-Browser_0.1.11_win32-x64.zip",
|
||||
"url": "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/browser-engine-v0.1.11/RuneStone-Browser_0.1.11_win32-x64.zip",
|
||||
"bytes": 163623801,
|
||||
"sha256": "1e0153b134cebe882b36f74e1f3c2a4ed37acb2caca10548034a8b5d88738d26"
|
||||
}
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
//!
|
||||
//! The file holds a `schema` number, a `revision` number, and one value for each section.
|
||||
//! The host does not interpret the section values. The frontend normalizes them.
|
||||
//! A write that changes a section replaces the complete file atomically and sends `settings-changed` to all windows.
|
||||
//! A write of the value that a section already holds changes nothing and sends no event.
|
||||
//! Every write replaces the complete file atomically and sends `settings-changed` to all windows.
|
||||
//! Plugin settings stay in the app data folder (see `plugins.rs`).
|
||||
|
||||
use std::io;
|
||||
@@ -179,19 +178,6 @@ impl Store {
|
||||
Ok(Change { section: section.into(), revision: next, value })
|
||||
}
|
||||
|
||||
/// Like `write`, but when the file already holds `value` in this section, the file stays as it is.
|
||||
/// The change then has the current revision, and `false` tells the caller to send no event.
|
||||
/// The compare ignores the key order of objects. Without this check, windows that save the same value
|
||||
/// can start each other again without end, and each write replaces the file.
|
||||
pub fn write_if_changed(&mut self, section: &str, value: Value) -> Result<(Change, bool)> {
|
||||
check_section(section)?;
|
||||
let loaded = self.load()?;
|
||||
if loaded.exists && *loaded.document.get(section).unwrap_or(&Value::Null) == value {
|
||||
return Ok((Change { section: section.into(), revision: revision(&loaded.document), value }, false));
|
||||
}
|
||||
Ok((self.write(section, value)?, true))
|
||||
}
|
||||
|
||||
/// Write the first file from the migrated values. When a file exists, keep it and return it unchanged.
|
||||
pub fn migrate(&mut self, sections: Map<String, Value>) -> Result<Snapshot> {
|
||||
for name in sections.keys() { check_section(name)?; }
|
||||
@@ -243,9 +229,9 @@ pub async fn settings_read(app: AppHandle) -> Result<Snapshot> {
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn settings_write(app: AppHandle, section: String, value: Value) -> Result<Change> {
|
||||
let (change, saved) = with_store(&app, move |store| store.write_if_changed(§ion, value)).await?;
|
||||
let change = with_store(&app, move |store| store.write(§ion, value)).await?;
|
||||
// Every window shows the same preferences, so the change goes to all of them.
|
||||
if saved { let _ = app.emit(CHANGED_EVENT, &change); }
|
||||
let _ = app.emit(CHANGED_EVENT, &change);
|
||||
Ok(change)
|
||||
}
|
||||
|
||||
@@ -306,35 +292,6 @@ mod tests {
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_of_the_stored_value_keeps_the_file_and_the_revision() {
|
||||
let (dir, path) = fixture("unchanged");
|
||||
let mut store = Store::new(path.clone());
|
||||
// A missing file gets created, also for a value that matches the empty default.
|
||||
let (created, saved) = store.write_if_changed("language", Value::Null).unwrap();
|
||||
assert!(saved);
|
||||
assert_eq!(created.revision, 1);
|
||||
let (first, saved) = store.write_if_changed("appearance", json!({ "theme": "harvest-moon", "mode": "dark", "transparency": { "enabled": true, "amount": 18 } })).unwrap();
|
||||
assert!(saved);
|
||||
assert_eq!(first.revision, 2);
|
||||
let before = fs::read(&path).unwrap();
|
||||
// The same value in a different key order changes nothing.
|
||||
let (again, saved) = store.write_if_changed("appearance", json!({ "transparency": { "amount": 18, "enabled": true }, "mode": "dark", "theme": "harvest-moon" })).unwrap();
|
||||
assert!(!saved, "No save and no event");
|
||||
assert_eq!(again.revision, 2);
|
||||
assert_eq!(fs::read(&path).unwrap(), before, "The file stays as it is");
|
||||
// A missing section and `null` are the same.
|
||||
assert!(!store.write_if_changed("terminal", Value::Null).unwrap().1);
|
||||
// A different value saves as usual.
|
||||
let (changed, saved) = store.write_if_changed("appearance", json!({ "theme": "harvest-moon", "mode": "light" })).unwrap();
|
||||
assert!(saved);
|
||||
assert_eq!(changed.revision, 3);
|
||||
assert_eq!(on_disk(&path)["appearance"], json!({ "mode": "light", "theme": "harvest-moon" }));
|
||||
assert!(store.write_if_changed("plugins", json!({})).is_err(), "Unknown sections stay refused");
|
||||
assert_eq!(files(&dir), vec![FILE_NAME.to_owned()], "No temporary files remain");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_reject_unknown_sections_and_values_above_the_limit() {
|
||||
let (dir, path) = fixture("limits");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "RuneStone",
|
||||
"version": "1.0.0+1",
|
||||
"version": "0.1.53",
|
||||
"identifier": "com.runestone.app",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
@@ -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') },
|
||||
|
||||
@@ -13,10 +13,8 @@
|
||||
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 { registerImageDropTarget } from "./workspaceImageDrop";
|
||||
import { workspaceFileLink } from "./workspaceFileLink";
|
||||
@@ -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);
|
||||
@@ -441,11 +434,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();
|
||||
|
||||
@@ -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 }); },
|
||||
};
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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: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); }
|
||||
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; }
|
||||
.text-button:hover { background: var(--rs-hover-bg); }
|
||||
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; }
|
||||
.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;
|
||||
}
|
||||
|
||||
@@ -369,26 +369,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 +377,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);
|
||||
|
||||
@@ -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 })
|
||||
|
||||
+12
-18
@@ -1020,10 +1020,10 @@ export const messageRows: [string, string, string, string][] = [
|
||||
"阅读"
|
||||
],
|
||||
[
|
||||
"Read beside",
|
||||
"Lire à côté",
|
||||
"横に閲覧",
|
||||
"并排阅读"
|
||||
"Split",
|
||||
"Diviser",
|
||||
"分割",
|
||||
"分栏"
|
||||
],
|
||||
[
|
||||
"Editor",
|
||||
@@ -1464,10 +1464,10 @@ export const messageRows: [string, string, string, string][] = [
|
||||
"版本 {version}"
|
||||
],
|
||||
[
|
||||
"RuneStone is under development. Maintained by KnottyWyvern-GH.",
|
||||
"RuneStone est en développement. Maintenu par KnottyWyvern-GH.",
|
||||
"RuneStoneは開発中です。管理者:KnottyWyvern-GH。",
|
||||
"RuneStone 正在开发中。由 KnottyWyvern-GH 维护。"
|
||||
"RuneStone is under development. Maintained by kwyvern-gh.",
|
||||
"RuneStone est en développement. Maintenu par kwyvern-gh.",
|
||||
"RuneStoneは開発中です。管理者:kwyvern-gh。",
|
||||
"RuneStone 正在开发中。由 kwyvern-gh 维护。"
|
||||
],
|
||||
[
|
||||
"Use the folder button to open a workspace or create one. Your notes and scripts stay as ordinary files on disk.",
|
||||
@@ -3300,13 +3300,8 @@ export const messageRows: [string, string, string, string][] = [
|
||||
["The workspace changed. File moves stopped.", "L’espace de travail a changé. Les déplacements de fichiers sont arrêtés.", "ワークスペースが変更されました。ファイルの移動を停止しました。", "工作区已更改。文件移动已停止。"],
|
||||
["The workspace changed. 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", "下に開く", "在下方打开"],
|
||||
["Open to the left", "Ouvrir à gauche", "左側で開く", "在左侧打开"],
|
||||
["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.", "ブラウザータブの移動が無効です。", "浏览器标签页转移无效。"],
|
||||
@@ -3381,7 +3376,7 @@ export const messageRows: [string, string, string, string][] = [
|
||||
["Show the file name above each Markdown note in Write and Read.", "Afficher le nom du fichier au-dessus de chaque note Markdown dans Écrire et Lire.", "「書く」と「閲覧」で、各 Markdown ノートの上にファイル名を表示します。", "在“写作”和“阅读”中,在每篇 Markdown 笔记上方显示文件名。"],
|
||||
["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é", "未保存", "未保存"],
|
||||
@@ -3685,8 +3680,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 需要密码。"],
|
||||
|
||||
@@ -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")) };
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
<script lang="ts">
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { attachTooltip } from "$lib/ui/tooltip";
|
||||
import { t } from "$lib/i18n";
|
||||
|
||||
// A pane beside other panes closes with this button. Its tab stays open in the tab bar.
|
||||
// The button shows its name, because a bare close icon looks like the close button of a tab.
|
||||
// A narrow pane shows only the icon. Then the tooltip gives the name.
|
||||
let { onclick }: { onclick: () => void } = $props();
|
||||
let text: HTMLSpanElement;
|
||||
|
||||
function tooltip(node: HTMLElement) {
|
||||
const dispose = attachTooltip(node, () => text && getComputedStyle(text).display === "none" ? $t("Close split") : "");
|
||||
return { destroy: dispose };
|
||||
}
|
||||
</script>
|
||||
|
||||
<button type="button" class="close-split" aria-label={$t("Close split")} {onclick} use:tooltip><Icon icon="split-close" /><span bind:this={text}>{$t("Close split")}</span></button>
|
||||
|
||||
<style>
|
||||
.close-split {
|
||||
display: inline-flex;
|
||||
flex: 0 0 auto;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
min-width: 32px;
|
||||
height: 32px;
|
||||
padding: 0 10px 0 8px;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid var(--rs-border);
|
||||
border-radius: var(--rs-control-radius);
|
||||
background: transparent;
|
||||
color: var(--rs-text-dim);
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.close-split :global(svg) { width: 16px; height: 16px; flex-shrink: 0; }
|
||||
.close-split:hover { background: var(--rs-hover-bg); color: var(--rs-text-strong); }
|
||||
/* The pane bar and the editor bar are size containers. A narrow pane keeps room for its path and its view controls. */
|
||||
@container (max-width: 420px) {
|
||||
.close-split { padding: 0; }
|
||||
.close-split span { display: none; }
|
||||
}
|
||||
</style>
|
||||
@@ -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 CloseSplitButton from "./CloseSplitButton.svelte";
|
||||
import { paneBounds, splitDividers, stackLayout, type SplitDivider, type SplitLayout, type SplitPath } from "$lib/workspace/splitLayout";
|
||||
import type { PaneDrop } from "$lib/workspace/documentPanes";
|
||||
import { attachTooltip } from "$lib/ui/tooltip";
|
||||
import type { ViewMode } from "./ViewModes.svelte";
|
||||
import TabBar from "./TabBar.svelte";
|
||||
|
||||
type EditorProps = ComponentProps<typeof EditorPane>;
|
||||
type DocumentView = { id: string; reading: boolean; split: boolean; buffer: OpenBuffer | null; 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;
|
||||
@@ -55,113 +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 left, right, and bottom sides open a new pane.
|
||||
* While a plugin view covers the area, the area is one pane. A narrow area opens new panes only below.
|
||||
*/
|
||||
export function dropAt(x: number, y: number): DropTarget | null {
|
||||
const rect = area?.getBoundingClientRect();
|
||||
if (!rect || !rect.width || !rect.height || x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) return null;
|
||||
const px = (x - rect.left) / rect.width * 100, py = (y - rect.top) / rect.height * 100;
|
||||
const pane = pluginCover ? activePane : documentViews.find(view => {
|
||||
const box = bounds[view.id];
|
||||
return box && px >= box.left && px <= box.left + box.width && py >= box.top && py <= box.top + box.height;
|
||||
})?.id;
|
||||
const box = pane ? (pluginCover ? full : bounds[pane]) : undefined;
|
||||
if (!pane || !box) return null;
|
||||
const rx = (px - box.left) / box.width, ry = (py - box.top) / box.height;
|
||||
return { pane, zone: rx > 0.7 && !stacked ? "right" : rx < 0.3 && !stacked ? "left" : ry > 0.7 ? "down" : "center" };
|
||||
}
|
||||
const dropBox = $derived.by(() => {
|
||||
if (!drop) return null;
|
||||
const box = pluginCover ? full : bounds[drop.pane];
|
||||
if (!box) return null;
|
||||
if (drop.zone === "right") return { ...box, left: box.left + box.width / 2, width: box.width / 2 };
|
||||
if (drop.zone === "left") return { ...box, width: box.width / 2 };
|
||||
if (drop.zone === "down") return { ...box, top: box.top + box.height / 2, height: box.height / 2 };
|
||||
return box;
|
||||
});
|
||||
</script>
|
||||
|
||||
<main class="center" 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}
|
||||
@@ -179,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}
|
||||
@@ -202,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>
|
||||
<CloseSplitButton onclick={() => onCloseSplit(host)} />
|
||||
</div>
|
||||
{/if}
|
||||
<PluginEditor bind:this={pluginPaneComponents[view.key]} {view} />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{#each dividers as divider (divider.path.join("/"))}
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (A focusable separator is the splitter pattern.) -->
|
||||
<div class="divider" class:vertical={divider.direction === "right"} style={dividerStyle(divider)}
|
||||
role="separator" tabindex="0" aria-label={$t("Resize panes")}
|
||||
aria-orientation={divider.direction === "right" ? "vertical" : "horizontal"}
|
||||
aria-valuemin={10} aria-valuemax={90} aria-valuenow={Math.round(divider.ratio * 100)}
|
||||
use:tooltip={$t("Drag to resize the panes. Double-click to give them equal sizes.")}
|
||||
onpointerdown={event => startResize(event, divider)}
|
||||
ondblclick={() => onResize(divider.path, 0.5)}
|
||||
onkeydown={event => resizeKey(event, divider)}></div>
|
||||
{/each}
|
||||
{#if dropBox && drop}
|
||||
<div class="drop-hint" data-drop-zone={drop.zone} style:left={`${dropBox.left}%`} style:top={`${dropBox.top}%`} style:width={`${dropBox.width}%`} style:height={`${dropBox.height}%`}>
|
||||
<span>{drop.zone === "center" ? $t("Show here") : drop.zone === "right" ? $t("Open to the right") : drop.zone === "left" ? $t("Open to the left") : $t("Open below")}</span>
|
||||
</div>
|
||||
{/if}
|
||||
</main>
|
||||
|
||||
<style>
|
||||
@@ -280,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 { container-type: inline-size; display: flex; align-items: center; gap: 8px; min-height: 34px; flex: 0 0 auto; padding: 0 10px; background: var(--rs-bg); border-bottom: 1px solid var(--rs-border); color: var(--rs-text-dim); }
|
||||
.plugin-pane.focused .pane-bar { background: var(--rs-bg-active); }
|
||||
.pane-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
/* A divider is a wide, invisible target over the border between two panes. It shows the accent color on hover and focus. */
|
||||
.divider { position: absolute; z-index: 3; height: 8px; margin-top: -4px; cursor: row-resize; touch-action: none; }
|
||||
.divider.vertical { width: 8px; margin-top: 0; margin-left: -4px; cursor: col-resize; }
|
||||
.divider::after { content: ""; position: absolute; inset: 3px 0; border-radius: 1px; }
|
||||
.divider.vertical::after { inset: 0 3px; }
|
||||
.divider:hover::after, .divider:focus-visible::after, .center.resizing .divider:focus::after { background: var(--rs-accent); }
|
||||
.divider:focus-visible { outline: none; }
|
||||
.center.resizing { cursor: col-resize; user-select: none; }
|
||||
.center.resizing-down { cursor: row-resize; }
|
||||
.center.resizing .document-panes, .center.resizing .plugin-pane { pointer-events: none; }
|
||||
/* The drop hint shows where a dragged tab goes. */
|
||||
.drop-hint { position: absolute; z-index: 4; box-sizing: border-box; display: flex; align-items: center; justify-content: center; pointer-events: none;
|
||||
border: 2px solid var(--rs-accent); border-radius: var(--rs-control-radius); background: color-mix(in srgb, var(--rs-accent) 16%, transparent); }
|
||||
.drop-hint span { padding: 4px 10px; border-radius: var(--rs-control-radius); background: var(--rs-accent); color: var(--rs-on-accent); font-weight: 600; }
|
||||
.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>
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
import type { FindTarget } from "$lib/editor/findTarget";
|
||||
import DocumentEditor from "$lib/editor/DocumentEditor.svelte";
|
||||
import { tick } from "svelte";
|
||||
import CloseSplitButton from "./CloseSplitButton.svelte";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import ImageViewer from "./ImageViewer.svelte";
|
||||
import MarkdownView from "./MarkdownView.svelte";
|
||||
import ViewModes, { type ViewMode } from "./ViewModes.svelte";
|
||||
@@ -147,14 +147,12 @@
|
||||
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"}
|
||||
<div class="empty">
|
||||
{#if onCloseSplit}<CloseSplitButton onclick={onCloseSplit} />{/if}
|
||||
{#if onCloseSplit}<IconButton icon="close" label={$t("Close split")} onclick={onCloseSplit} />{/if}
|
||||
<div class="welcome-actions">
|
||||
{#if hasWorkspace}
|
||||
<div class="welcome-row">
|
||||
@@ -180,7 +178,7 @@
|
||||
</span>
|
||||
{/if}
|
||||
<div class="actions" bind:this={modeControls}>
|
||||
{#if onCloseSplit}<CloseSplitButton onclick={onCloseSplit} />{/if}
|
||||
{#if onCloseSplit}<IconButton icon="close" label={$t("Close split")} onclick={onCloseSplit} />{/if}
|
||||
{#if !isImage}<ViewModes {view} split={splitView} readable={canPreview} onView={next => onView?.(next)} onSplit={next => onSplit?.(next)} />{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -253,7 +253,7 @@
|
||||
{/each}
|
||||
</details>
|
||||
</div>
|
||||
<p class="about-note">{$t("RuneStone is under development. Maintained by KnottyWyvern-GH.")}</p>
|
||||
<p class="about-note">{$t("RuneStone is under development. Maintained by kwyvern-gh.")}</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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}
|
||||
|
||||
+25
-183
@@ -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, moveToNewPane, 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";
|
||||
@@ -150,7 +149,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 +228,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 +237,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 +248,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,163 +256,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;
|
||||
const own = coverKey ? "plugin" in tab && tab.plugin.key === coverKey : paneOf(documentPanes, tabContent(tab))?.id === target.pane;
|
||||
if (!own) return { tab, target, stay: null };
|
||||
// The tab that the pane shows can move to a new pane beside it. Then the pane shows a different tab:
|
||||
// the document below a plugin view that covers the area, or the next tab that no pane shows.
|
||||
if (target.zone === "center") return null;
|
||||
const below = coverKey ? documentPanes.panes.find(pane => pane.id === target.pane)?.documentId : null;
|
||||
const next = below ? undefined : tabAfter(tab);
|
||||
const stay: PaneContent | null = below ? { documentId: below } : next ? tabContent(next) : null;
|
||||
return stay ? { tab, target, stay } : null;
|
||||
}
|
||||
/** The nearest tab that no pane shows: first the tabs after `tab`, then the tabs before it. A closed tab uses the same order. */
|
||||
function tabAfter(tab: EditorTab) {
|
||||
const index = workingTabs.indexOf(tab);
|
||||
const free = (item: EditorTab) => item !== tab && !paneOf(documentPanes, tabContent(item));
|
||||
return workingTabs.slice(index + 1).find(free) ?? workingTabs.slice(0, Math.max(index, 0)).reverse().find(free);
|
||||
}
|
||||
function tabDragAt(path: string, x: number, y: number) {
|
||||
tabDrop = tabDropTarget(path, x, y)?.target ?? null;
|
||||
return tabDrop !== null;
|
||||
}
|
||||
function tabDropAt(path: string, x: number, y: number) {
|
||||
const found = tabDropTarget(path, x, y);
|
||||
tabDrop = null;
|
||||
if (!found) return false;
|
||||
const { tab, target, stay } = found;
|
||||
if (stay) {
|
||||
if (target.zone !== "center") changePanes(moveToNewPane(documentPanes, target.pane, stay, tabContent(tab), target.zone, crypto.randomUUID()));
|
||||
return true;
|
||||
}
|
||||
if (coverKey) {
|
||||
if (target.zone === "center") { selectWorkingTab(tab.relPath); return true; }
|
||||
keepCoverInPane();
|
||||
}
|
||||
changePanes(dropInPane(documentPanes, tabContent(tab), target.pane, target.zone, crypto.randomUUID()));
|
||||
return true;
|
||||
}
|
||||
// Each focused plugin view that is not in a pane gets a pane when the area has several panes.
|
||||
// A new view that a plugin opens beside its own view, for example a browser tab, opens beside the pane of that view.
|
||||
// When the own view covers the area, it moves into the pane first.
|
||||
const placedPlugins = new Set<string>();
|
||||
$effect(() => {
|
||||
const view = $pluginEditorActive && $pluginView?.placement === "editor" ? $pluginView : null;
|
||||
const splits = $pluginSplits;
|
||||
if (!view) return;
|
||||
untrack(() => {
|
||||
const fresh = !placedPlugins.has(view.key);
|
||||
placedPlugins.add(view.key);
|
||||
const shown = paneOf(documentPanes, { pluginKey: view.key });
|
||||
if (shown) { documentPanes = selectPane(documentPanes, shown.id); return; }
|
||||
const right = rightOf;
|
||||
if (right && documentPanes.panes.some(pane => pane.id === right.pane)) {
|
||||
rightOf = null;
|
||||
if (right.cover && right.cover !== view.key && !paneOf(documentPanes, { pluginKey: right.cover }))
|
||||
documentPanes = showInActivePane(selectPane(documentPanes, right.pane), { pluginKey: right.cover });
|
||||
documentPanes = splitWithContent(documentPanes, right.pane, { pluginKey: view.key }, crypto.randomUUID());
|
||||
return;
|
||||
}
|
||||
const group = fresh ? splits.find(tree => containsPane(tree, view.key)) : undefined;
|
||||
const beside = group ? splitSibling(group, view.key) : null;
|
||||
if (documentPanes.panes.length < 2 && !beside) return;
|
||||
if (beside && documentPanes.panes.length < 2 && !paneOf(documentPanes, { pluginKey: beside.sibling }))
|
||||
documentPanes = showInActivePane(documentPanes, { pluginKey: beside.sibling });
|
||||
const source = beside ? paneOf(documentPanes, { pluginKey: beside.sibling }) : undefined;
|
||||
documentPanes = source && beside
|
||||
? splitWithContent(documentPanes, source.id, { pluginKey: view.key }, crypto.randomUUID(), beside.direction)
|
||||
: showInActivePane(documentPanes, { pluginKey: view.key });
|
||||
});
|
||||
});
|
||||
// The selected document is visible while no plugin view has the focus.
|
||||
$effect(() => {
|
||||
const selected = $pluginEditorActive && $pluginView?.placement === "editor" ? null : buffer?.id ?? null;
|
||||
if (selected) untrack(() => { documentPanes = showInActivePane(documentPanes, { documentId: selected }); });
|
||||
});
|
||||
// A closed plugin view leaves its pane. The last pane does not keep a plugin view.
|
||||
$effect(() => {
|
||||
const keys = $pluginEditors.map(view => view.key);
|
||||
untrack(() => {
|
||||
for (const key of placedPlugins) if (!keys.includes(key)) placedPlugins.delete(key);
|
||||
documentPanes = releaseSolePlugin(syncDocumentPanes(documentPanes, tabs.map(tab => tab.id), null, keys)).state;
|
||||
});
|
||||
});
|
||||
let focusLine = $state<number | null>(null);
|
||||
let dragging = $state<"left" | "right" | "bottom" | null>(null);
|
||||
let centerStack: HTMLElement | undefined = $state();
|
||||
|
||||
// A focused plugin view is the active tab. It covers the area only when no pane shows it.
|
||||
const editorPluginVisible = $derived($pluginView?.placement === "editor" && $pluginEditorActive);
|
||||
const coverKey = $derived(editorPluginVisible && $pluginView && !paneOf(documentPanes, { pluginKey: $pluginView.key }) ? $pluginView.key : null);
|
||||
type EditorTab = WorkbenchTab & ({ buffer: OpenBuffer } | { plugin: OpenPluginView });
|
||||
let tabOrder = $state<string[]>([]);
|
||||
const availableTabs = $derived<EditorTab[]>([
|
||||
@@ -510,7 +363,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) });
|
||||
@@ -556,7 +411,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; }
|
||||
@@ -701,8 +556,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") : "";
|
||||
}
|
||||
@@ -731,14 +584,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) };
|
||||
// A tab in a pane beside other panes can leave the split. The tab stays open.
|
||||
const pane = !coverKey && documentPanes.panes.length > 1 ? paneOf(documentPanes, tabContent(tab)) : undefined;
|
||||
const close: ActionMenuItem[] = pane ? [{ label: $t("Close split"), icon: "split-close", run: () => closeSplit(pane.id) }] : [];
|
||||
if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return [right, ...close, ...actions];
|
||||
return [right, ...close, { label: $t("Open in new window"), icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions];
|
||||
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);
|
||||
@@ -873,7 +721,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)) },
|
||||
] },
|
||||
);
|
||||
}
|
||||
@@ -1096,10 +944,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;
|
||||
@@ -1332,7 +1177,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."); }
|
||||
@@ -1365,7 +1210,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."); }
|
||||
});
|
||||
|
||||
@@ -1472,7 +1317,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}
|
||||
@@ -1502,7 +1347,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}
|
||||
@@ -1529,14 +1373,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}
|
||||
@@ -1621,7 +1464,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;
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -56,23 +56,6 @@ function encode(section: SettingsSection, value: unknown): string {
|
||||
return section === 'language' && typeof value === 'string' ? value : JSON.stringify(value);
|
||||
}
|
||||
|
||||
// The same value with the object keys in alphabetical order, at every depth.
|
||||
function sortKeys(value: unknown): unknown {
|
||||
if (Array.isArray(value)) return value.map(sortKeys);
|
||||
if (!value || typeof value !== 'object') return value;
|
||||
const source = value as Record<string, unknown>;
|
||||
return Object.fromEntries(Object.keys(source).sort().map(key => [key, sortKeys(source[key])]));
|
||||
}
|
||||
|
||||
/**
|
||||
* True when two section values hold the same data. The key order of objects does not matter.
|
||||
* The desktop host stores the keys in alphabetical order, so a value that comes back from the host
|
||||
* can have a different key order than the value that a window saved.
|
||||
*/
|
||||
export function sameSettingsValue(a: unknown, b: unknown): boolean {
|
||||
return JSON.stringify(sortKeys(a)) === JSON.stringify(sortKeys(b));
|
||||
}
|
||||
|
||||
function notify(section: SettingsSection) {
|
||||
for (const callback of [...subscribers.get(section) ?? []]) {
|
||||
try { callback(); } catch (reason) { console.error(`A ${section} settings subscriber failed.`, reason); }
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { syncTableFormulas } from '$lib/formulas';
|
||||
import { syncFileTitle } from '$lib/editor/fileTitle';
|
||||
import { onMount } from 'svelte';
|
||||
import { onSettingsChange, readSection, sameSettingsValue, writeSection } from '$lib/settings/store';
|
||||
import { onSettingsChange, readSection, writeSection } from '$lib/settings/store';
|
||||
import { applyAppearance, readAppearance } from './appearance';
|
||||
onMount(() => {
|
||||
const stopLocale = syncLocale();
|
||||
@@ -14,8 +14,7 @@
|
||||
const stored = readSection('appearance');
|
||||
const appearance = readAppearance();
|
||||
// Save the normalized value, for example a new ID for a renamed theme.
|
||||
// Ignore the key order: the host sorts the keys, so a text compare saves again in each window without end.
|
||||
if (stored !== undefined && !sameSettingsValue(stored, appearance)) {
|
||||
if (stored !== undefined && JSON.stringify(stored) !== JSON.stringify(appearance)) {
|
||||
writeSection('appearance', appearance).catch(() => { /* The normalized value applies until the next save. */ });
|
||||
}
|
||||
applyAppearance(appearance);
|
||||
|
||||
@@ -156,8 +156,6 @@
|
||||
<path d="M3 4v16M21 4v16M7 12h10M10 9l-3 3 3 3M14 9l3 3-3 3" />
|
||||
{:else if icon === "rotate"}
|
||||
<path d="M20 7v5h-5" /><path d="M20 12a8 8 0 1 0-2 6" />
|
||||
{:else if icon === "split-close"}
|
||||
{@html actionIcons["split-close"]}
|
||||
{/if}
|
||||
</svg>
|
||||
<style>
|
||||
|
||||
@@ -62,8 +62,7 @@
|
||||
| "zoom-in"
|
||||
| "zoom-out"
|
||||
| "fit-width"
|
||||
| "rotate"
|
||||
| "split-close";
|
||||
| "rotate";
|
||||
|
||||
type Props = {
|
||||
icon: IconName;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/** Remove the panes that became empty. The last pane always stays. */
|
||||
function collapse(state: DocumentPanes, panes: DocumentPane[], active: string): DocumentPanes {
|
||||
/** 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);
|
||||
}
|
||||
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,49 +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) };
|
||||
}
|
||||
|
||||
/** The side of a pane where a new pane opens. */
|
||||
export type PaneSide = "right" | "down" | "left";
|
||||
|
||||
/** Show the content in a new pane beside `source`. When a pane already shows it, that pane becomes active. */
|
||||
export function splitWithContent(state: DocumentPanes, source: string, content: PaneContent, paneId: string, direction: PaneSide = "right"): DocumentPanes {
|
||||
const existing = paneOf(state, content);
|
||||
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;
|
||||
const layout = splitPane(state.layout, source, paneId, direction === "left" ? "right" : direction, direction === "left");
|
||||
return { layout, panes: [...state.panes, filled(paneId, content)], active: paneId };
|
||||
}
|
||||
|
||||
export function splitDocumentPane(state: DocumentPanes, source: string, documentId: string, paneId: string): DocumentPanes {
|
||||
return splitWithContent(state, source, { documentId }, paneId);
|
||||
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 {
|
||||
@@ -95,61 +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 left, right, or bottom side. */
|
||||
export type PaneDrop = "center" | PaneSide;
|
||||
|
||||
/**
|
||||
* Show the content in the `target` pane (`center`), or in a new pane beside it.
|
||||
* The content leaves the pane that showed it before, so that it shows in one pane only.
|
||||
* The content that the drop replaces stays open as a tab.
|
||||
*/
|
||||
export function dropInPane(state: DocumentPanes, content: PaneContent, target: string, zone: PaneDrop, paneId: string): DocumentPanes {
|
||||
if (!state.panes.some(pane => pane.id === target)) return state;
|
||||
const current = paneOf(state, content);
|
||||
if (current?.id === target) return selectPane(state, target);
|
||||
const cleared = state.panes.map(pane => pane.id === current?.id ? emptyPane(pane.id) : pane);
|
||||
if (zone === "center") return collapse(state, cleared.map(pane => pane.id === target ? filled(target, content) : pane), target);
|
||||
return splitWithContent(collapse(state, cleared, target), target, content, paneId, zone);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the content of the `source` pane to a new pane beside it. The `source` pane then shows `stay`.
|
||||
* `stay` is content that no other pane shows. `content` is the content of `source`, or content that no pane shows,
|
||||
* for example a plugin view that covers the area.
|
||||
*/
|
||||
export function moveToNewPane(state: DocumentPanes, source: string, stay: PaneContent, content: PaneContent, zone: PaneSide, paneId: string): DocumentPanes {
|
||||
const holder = paneOf(state, stay), shown = paneOf(state, content);
|
||||
if (!state.panes.some(pane => pane.id === source) || (holder && holder.id !== source) || (shown && shown.id !== source) || (holder && shown)) return state;
|
||||
const panes = holder ? state.panes : state.panes.map(pane => pane.id === source ? filled(source, stay) : pane);
|
||||
return splitWithContent({ ...state, panes }, source, content, paneId, zone);
|
||||
}
|
||||
|
||||
/** Give a new ratio to a split between panes. */
|
||||
export function resizeDocumentPanes(state: DocumentPanes, path: SplitPath, ratio: number): DocumentPanes {
|
||||
const layout = setSplitRatio(state.layout, path, ratio);
|
||||
return layout === state.layout ? state : { ...state, layout };
|
||||
}
|
||||
|
||||
export function readDocumentPane(state: DocumentPanes, id: string, reading: boolean): DocumentPanes {
|
||||
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, reading, split: reading ? false : pane.split } : pane) };
|
||||
}
|
||||
|
||||
/** Show or hide the Read view beside the editor. 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;
|
||||
}
|
||||
@@ -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,20 +1,13 @@
|
||||
/** 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);
|
||||
}
|
||||
|
||||
/** Split the `key` pane. The `next` pane goes after it, or before it when `before` is true. */
|
||||
export function splitPane(tree: SplitLayout, key: string, next: string, direction: "right" | "down", before = false): SplitLayout {
|
||||
if (typeof tree === "string") return tree === key ? (before ? { direction, first: next, second: tree } : { direction, first: tree, second: next }) : tree;
|
||||
return { ...tree, first: splitPane(tree.first, key, next, direction, before), second: splitPane(tree.second, key, next, direction, before) };
|
||||
export function splitPane(tree: SplitLayout, key: string, next: string, direction: "right" | "down"): SplitLayout {
|
||||
if (typeof tree === "string") return tree === key ? { direction, first: tree, second: next } : tree;
|
||||
return { ...tree, first: splitPane(tree.first, key, next, direction), second: splitPane(tree.second, key, next, direction) };
|
||||
}
|
||||
|
||||
export function removePane(tree: SplitLayout, key: string): SplitLayout | null {
|
||||
@@ -25,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -103,11 +103,11 @@ await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
|
||||
assert.deepEqual(await background.boundingBox(), beforeScroll);
|
||||
await page.screenshot({ path: `${output}/${theme}-reader.png` });
|
||||
// Split shows the Write editor beside Read.
|
||||
await chooseView(page, 'Read beside');
|
||||
await chooseView(page, 'Split');
|
||||
await page.locator('.live-writer .cm-content').waitFor();
|
||||
assert.equal(await style(page.locator('.live-writer .cm-editor').first(), 'backgroundColor'), 'rgba(0, 0, 0, 0)');
|
||||
await page.screenshot({ path: `${output}/${theme}-split.png` });
|
||||
await chooseView(page, 'Read beside');
|
||||
await chooseView(page, 'Split');
|
||||
await chooseView(page, 'Source');
|
||||
await page.locator('.source-editor .cm-content').waitFor();
|
||||
await page.screenshot({ path: `${output}/${theme}-ide.png` });
|
||||
|
||||
@@ -1,145 +0,0 @@
|
||||
// Scrolling in Write and Read through a large document with large tables, images, code blocks, and short lines keeps the text in place.
|
||||
import assert from "node:assert/strict";
|
||||
import { chooseView, mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||
|
||||
const words = "lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua".split(" ");
|
||||
const text = (seed, count) => Array.from({ length: count }, (_, i) => words[(seed * 7 + i * 3) % words.length]).join(" ");
|
||||
|
||||
/** A short first heading holds the caret when the document opens. Short code lines and fences have another line height than prose. */
|
||||
function largeDocument() {
|
||||
const parts = ["# Large\n"];
|
||||
for (let section = 0; section < 10; section++) {
|
||||
parts.push(`## Section ${section}\n`, `Short line ${section}\n`, " \n");
|
||||
for (let p = 0; p < 5; p++) parts.push(`P${section}.${p} ${text(section + p, 30 + (p * 37) % 90)}\n`);
|
||||
const rows = Array.from({ length: 25 + (section * 17) % 50 }, (_, r) => `| T${section}R${r} | ${text(r, 2)} | ${text(section + r, 6 + (r * 11) % 50)} |`);
|
||||
parts.push(["| Row | Name | Description |", "| --- | --- | --- |", ...rows].join("\n") + "\n");
|
||||
if (section % 2 === 0) parts.push(`\n`);
|
||||
if (section % 3 === 0) parts.push("```python\nx = 1\ny = 2\n```\n");
|
||||
parts.push(`- item ${section} one\n- item ${section} two\n`);
|
||||
}
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
await runSmoke("editor/scrollStability", async ({ page }) => {
|
||||
await mockTauri(page, {
|
||||
state: { source: largeDocument() },
|
||||
commands: test => {
|
||||
const svg = (width, height) => btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><rect width="100%" height="100%" fill="#336"/></svg>`);
|
||||
const files = { "notes/large.md": test.state.source };
|
||||
for (let section = 0; section < 10; section += 2) files[`notes/img${section}.svg`] = svg(1400, 700 + section * 60);
|
||||
const workspace = test.workspace({ root: "C:/smoke-workspace", files });
|
||||
return {
|
||||
...workspace,
|
||||
workspace_read_data_url: ({ rel }) => {
|
||||
if (!workspace.files.has(rel)) throw new Error("missing image");
|
||||
return "data:image/svg+xml;base64," + workspace.files.get(rel);
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
|
||||
/** Wheel over the view. After each tick lands, the text must be where the tick put it. Returns the ticks where the text moved by itself, and the document heights. */
|
||||
async function wheel(selector, delta, ticks) {
|
||||
const box = await page.locator(selector).boundingBox();
|
||||
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
|
||||
await page.evaluate(selector => {
|
||||
const scroller = document.querySelector(selector);
|
||||
const unique = /^s*(Td+Rd+|Pd+.d+|Short line d+|item d+ (?:one|two)|Section d+)/;
|
||||
const keyOf = element => unique.exec(element.textContent || "")?.[1] ?? "";
|
||||
const items = () => [...scroller.querySelectorAll(".cm-line, tr, .reading p, .reading h2, .reading li")];
|
||||
const frame = () => new Promise(resolve => requestAnimationFrame(resolve));
|
||||
const atEdge = () => scroller.scrollTop <= 0 || scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 2;
|
||||
let tracked = null;
|
||||
window.__scroll = {
|
||||
jumps: [], heights: [],
|
||||
before(delta) {
|
||||
const area = scroller.getBoundingClientRect(), margin = Math.abs(delta) + 60;
|
||||
const element = items().find(item => { const rect = item.getBoundingClientRect(); return rect.height > 0 && rect.top >= area.top + margin && rect.top <= area.bottom - margin && keyOf(item); });
|
||||
tracked = element ? { element, key: keyOf(element), top: element.getBoundingClientRect().top, delta, scrollTop: scroller.scrollTop } : null;
|
||||
},
|
||||
// A tick can land some frames later on a busy computer. Wait for it, then for the layout passes of the editor.
|
||||
async after() {
|
||||
for (let waited = 0; tracked && scroller.scrollTop === tracked.scrollTop && waited < 60; waited++) await frame();
|
||||
for (let settled = 0; settled < 3; settled++) await frame();
|
||||
this.heights.push(scroller.scrollHeight);
|
||||
if (atEdge()) return true;
|
||||
if (!tracked) return false;
|
||||
const element = tracked.element.isConnected ? tracked.element : items().find(item => keyOf(item) === tracked.key);
|
||||
if (!element) this.jumps.push(`${tracked.key} left the view`);
|
||||
else {
|
||||
const moved = Math.round(element.getBoundingClientRect().top - (tracked.top - tracked.delta));
|
||||
if (Math.abs(moved) > 4) this.jumps.push(`${tracked.key} moved ${moved}`);
|
||||
}
|
||||
return false;
|
||||
},
|
||||
};
|
||||
}, selector);
|
||||
for (let tick = 0; tick < ticks; tick++) {
|
||||
await page.evaluate(delta => window.__scroll.before(delta), delta);
|
||||
await page.mouse.wheel(0, delta);
|
||||
if (await page.evaluate(() => window.__scroll.after()) && tick > 0) break;
|
||||
}
|
||||
return page.evaluate(() => ({ jumps: window.__scroll.jumps, heights: window.__scroll.heights }));
|
||||
}
|
||||
const jump = (selector, fraction) => page.evaluate(({ selector, fraction }) => { const scroller = document.querySelector(selector); scroller.scrollTop = scroller.scrollHeight * fraction; }, { selector, fraction });
|
||||
|
||||
await page.goto(smokeUrl);
|
||||
await page.getByText(/smoke-workspace/).first().waitFor();
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill("large.md");
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: "large.md" }).first().click();
|
||||
await page.locator(".cm-content").waitFor();
|
||||
await page.waitForTimeout(400);
|
||||
|
||||
// Text that was not on screen yet: the heights are estimates until the first draw.
|
||||
await jump(".cm-scroller", .6);
|
||||
await page.waitForTimeout(300);
|
||||
const first = await wheel(".cm-scroller", -200, 120);
|
||||
assert.deepEqual(first.jumps, [], "Wheel up through new tables and images");
|
||||
const spread = heights => Math.max(...heights) - Math.min(...heights);
|
||||
// Line heights are estimates, but tables and images have their heights before the first draw.
|
||||
assert.ok(spread(first.heights) < Math.max(...first.heights) * .05, `The document keeps about its height at the first draw: ${Math.min(...first.heights)} to ${Math.max(...first.heights)}`);
|
||||
|
||||
// Text that was drawn before: images and tables come back with their heights.
|
||||
await jump(".cm-scroller", 0);
|
||||
await page.waitForTimeout(200);
|
||||
const down = await wheel(".cm-scroller", 400, 130);
|
||||
assert.deepEqual(down.jumps, [], "Wheel down to the end");
|
||||
const up = await wheel(".cm-scroller", -400, 130);
|
||||
assert.deepEqual(up.jumps, [], "Wheel up to the start");
|
||||
assert.ok(spread(up.heights) < 200, `The document keeps its height on the way back: ${Math.min(...up.heights)} to ${Math.max(...up.heights)}`);
|
||||
|
||||
// A short heading with the caret and a code block with the caret have another line height too.
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
const view = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
const heading = view.state.doc.toString().indexOf("## Section 3");
|
||||
view.dispatch({ selection: { anchor: heading + 3 }, scrollIntoView: true });
|
||||
});
|
||||
await page.waitForTimeout(300);
|
||||
const caret = await wheel(".cm-scroller", 300, 25);
|
||||
assert.deepEqual(caret.jumps, [], "Wheel down with the caret in a short heading");
|
||||
assert.ok(spread(caret.heights) < 200, `The document keeps its height with the caret in a short heading: ${Math.min(...caret.heights)} to ${Math.max(...caret.heights)}`);
|
||||
|
||||
// Images in Write keep their space before they load.
|
||||
const image = page.locator(".cm-content img[data-md-src]").first();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
const view = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
view.scrollDOM.scrollTop = view.lineBlockAt(view.state.doc.toString().indexOf("![Picture 0]")).top;
|
||||
});
|
||||
await image.waitFor();
|
||||
assert.equal(await image.getAttribute("width"), "1400");
|
||||
assert.equal(await image.getAttribute("height"), "700");
|
||||
|
||||
// Read shows the same document without virtual lines.
|
||||
await chooseView(page, "Read");
|
||||
await page.locator(".md-page > .reading").waitFor();
|
||||
await page.waitForTimeout(300);
|
||||
await jump(".md-page", .6);
|
||||
await page.waitForTimeout(300);
|
||||
const reading = await wheel(".md-page", -300, 60);
|
||||
assert.deepEqual(reading.jumps, [], "Wheel up in Read");
|
||||
assert.equal(await page.locator(".md-page img[data-md-src]").first().getAttribute("height"), "700", "Images in Read keep their space before they load");
|
||||
}, { timeout: 30000 });
|
||||
@@ -1,6 +1,5 @@
|
||||
// The native PDF Viewer: the file tree marks PDF files without the module, the first PDF tab loads it, and each tab
|
||||
// renders its pages in one column with selectable text, page controls, zoom, a typed zoom, rotation, scrolling by wheel and
|
||||
// keyboard, and Reload. It also checks the opaque toolbar and the focus after Ctrl+Tab.
|
||||
// renders a page with selectable text, page controls, zoom, rotation, Page Up and Page Down, and Reload.
|
||||
// It also checks two tabs, one worker for each open tab, a protected PDF, a damaged file, Off and On, no network request,
|
||||
// no text read of a PDF, the owner ID of a tab transfer, a saved tab after a reload, both themes, and a narrow toolbar.
|
||||
// It replaces tests/browser.mjs of the PDF Viewer plugin.
|
||||
@@ -79,13 +78,8 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
await rendered("Page 1 of 2");
|
||||
assert.equal(await loaded(), true, "The first PDF tab loads the module");
|
||||
await active.getByRole("img", { name: "PDF page 1", exact: true }).waitFor();
|
||||
const sheet = number => active.locator(`.sheet[data-page="${number}"]`);
|
||||
const scroll = active.locator(".scroll");
|
||||
const scrollTop = () => scroll.evaluate(node => node.scrollTop);
|
||||
await sheet(1).locator(".textLayer span").first().waitFor();
|
||||
assert.match(await sheet(1).locator(".textLayer").innerText(), /Page one text selection/);
|
||||
assert.equal(await active.locator(".sheet").count(), 2, "Each page has a sheet in the column");
|
||||
assert.ok(await sheet(1).locator("canvas").evaluate(canvas => {
|
||||
assert.match(await active.locator(".textLayer").innerText(), /Page one text selection/);
|
||||
assert.ok(await active.locator("canvas").evaluate(canvas => {
|
||||
const data = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data;
|
||||
let colored = 0;
|
||||
for (let index = 0; index < data.length; index += 4) if (data[index] < 200 && data[index + 2] > 100) colored++;
|
||||
@@ -95,10 +89,6 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
assert.equal(await button("Fit width").getAttribute("aria-pressed"), "true");
|
||||
assert.equal(await button("Previous page").isDisabled(), true);
|
||||
assert.equal(await workers(), 1);
|
||||
// The toolbar and the status line are opaque, so a background image does not show through them.
|
||||
for (const selector of [".toolbar", ".status"]) {
|
||||
assert.match(await active.locator(selector).evaluate(node => getComputedStyle(node).backgroundColor), /^rgb\(/, `${selector} has an opaque fill`);
|
||||
}
|
||||
|
||||
// Both themes. The page stays white paper.
|
||||
for (const theme of ["dark", "light"]) {
|
||||
@@ -129,8 +119,7 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
await rendered("Page 2 of 2");
|
||||
await active.getByRole("img", { name: "PDF page 2", exact: true }).waitFor();
|
||||
assert.equal(await button("Next page").isDisabled(), true);
|
||||
const zoomField = active.getByRole("textbox", { name: "Zoom percent", exact: true });
|
||||
const zoomText = () => zoomField.inputValue();
|
||||
const zoomText = () => active.locator(".zoom").innerText();
|
||||
const before = await zoomText();
|
||||
await button("Zoom in").click();
|
||||
await rendered("Page 2 of 2");
|
||||
@@ -138,70 +127,13 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
assert.equal(await button("Fit width").getAttribute("aria-pressed"), "false");
|
||||
await button("Rotate clockwise").click();
|
||||
await rendered("Page 2 of 2");
|
||||
assert.ok(await sheet(2).locator("canvas").evaluate(canvas => canvas.width > canvas.height), "A rotated page is wider than high");
|
||||
for (let turn = 0; turn < 3; turn++) await button("Rotate clockwise").click();
|
||||
// A typed zoom.
|
||||
await zoomField.fill("137");
|
||||
await zoomField.press("Enter");
|
||||
assert.equal(await zoomText(), "137%");
|
||||
await zoomField.fill("text");
|
||||
await zoomField.press("Enter");
|
||||
assert.equal(await zoomText(), "137%", "Text that is not a number keeps the zoom");
|
||||
await zoomField.fill("9000");
|
||||
await zoomField.press("Enter");
|
||||
assert.equal(await zoomText(), "400%", "A typed zoom stays in the limits");
|
||||
const unfitted = button("Fit width").and(page.locator('[aria-pressed="false"]'));
|
||||
await unfitted.waitFor();
|
||||
const fitted = button("Fit width").and(page.locator('[aria-pressed="true"]'));
|
||||
const input = active.getByRole("spinbutton", { name: "Page number", exact: true });
|
||||
await input.fill("1");
|
||||
await input.press("Enter");
|
||||
await rendered("Page 1 of 2");
|
||||
// Page Down and Page Up scroll. At 400%, a page is higher than the tab. They do not jump to the next page, and they do not draw a page again at the ends.
|
||||
assert.equal(await scrollTop(), 0);
|
||||
await scroll.focus();
|
||||
const keepCanvas = number => sheet(number).locator("canvas").evaluate(canvas => { window.__PDF_CANVAS__ = canvas; });
|
||||
const sameCanvas = number => sheet(number).locator("canvas").evaluate(canvas => window.__PDF_CANVAS__ === canvas);
|
||||
await keepCanvas(1);
|
||||
assert.ok(await active.locator("canvas").evaluate(canvas => canvas.width > canvas.height), "A rotated page is wider than high");
|
||||
await active.locator(".scroll").focus();
|
||||
await page.keyboard.press("PageUp");
|
||||
await page.waitForTimeout(300);
|
||||
assert.equal(await scrollTop(), 0);
|
||||
assert.equal(await sameCanvas(1), true, "Page Up at the start does not draw the page again");
|
||||
await rendered("Page 1 of 2");
|
||||
await page.keyboard.press("PageDown");
|
||||
await page.waitForFunction(() => document.activeElement.scrollTop > 0);
|
||||
await page.waitForTimeout(400);
|
||||
assert.ok(await scrollTop() < await sheet(2).evaluate(node => node.offsetTop - node.previousElementSibling.offsetTop), "Page Down scrolls less than one page");
|
||||
await rendered("Page 1 of 2");
|
||||
assert.equal(await input.inputValue(), "1");
|
||||
await page.keyboard.press("End");
|
||||
await rendered("Page 2 of 2");
|
||||
assert.equal(await input.inputValue(), "2", "The page field follows the scroll position");
|
||||
await page.waitForTimeout(400);
|
||||
const end = await scrollTop();
|
||||
await keepCanvas(2);
|
||||
await page.keyboard.press("PageDown");
|
||||
await page.waitForTimeout(300);
|
||||
assert.equal(await scrollTop(), end);
|
||||
assert.equal(await sameCanvas(2), true, "Page Down at the end does not draw the page again");
|
||||
await rendered("Page 2 of 2");
|
||||
// The wheel shows the other pages.
|
||||
await page.keyboard.press("Home");
|
||||
await rendered("Page 1 of 2");
|
||||
await scroll.hover();
|
||||
await page.mouse.wheel(0, 5000);
|
||||
await rendered("Page 2 of 2");
|
||||
await active.getByRole("img", { name: "PDF page 2", exact: true }).waitFor();
|
||||
// Ctrl and the wheel change the zoom.
|
||||
await button("Fit width").click();
|
||||
await fitted.waitFor();
|
||||
await scroll.hover();
|
||||
await page.keyboard.down("Control");
|
||||
await page.mouse.wheel(0, -100);
|
||||
await page.keyboard.up("Control");
|
||||
await unfitted.waitFor();
|
||||
await button("Fit width").click();
|
||||
await rendered("Page 2 of 2");
|
||||
const input = active.getByRole("spinbutton", { name: "Page number", exact: true });
|
||||
await input.fill("1");
|
||||
await input.press("Enter");
|
||||
await rendered("Page 1 of 2");
|
||||
@@ -216,24 +148,6 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
assert.equal(await workers(), 2);
|
||||
await row("Other.PDF").click();
|
||||
assert.equal(await tab("Other").count(), 1, "A second open selects the same tab");
|
||||
// The tabs are New tab, Sample, and Other. Ctrl+Tab and Ctrl+Shift+Tab give the keyboard to the page area of the PDF tab.
|
||||
const focused = () => page.waitForFunction(() => document.activeElement?.matches(".pdf-viewer .scroll") && document.activeElement.offsetParent !== null);
|
||||
await page.keyboard.press("Control+Shift+Tab");
|
||||
await focused();
|
||||
assert.equal(await tab("Sample").getAttribute("aria-selected"), "true");
|
||||
await input.fill("1");
|
||||
await input.press("Enter");
|
||||
await rendered("Page 1 of 2");
|
||||
await page.keyboard.press("Control+Tab");
|
||||
await focused();
|
||||
await page.keyboard.press("Control+Shift+Tab");
|
||||
await focused();
|
||||
assert.equal(await tab("Sample").getAttribute("aria-selected"), "true");
|
||||
await page.keyboard.press("PageDown");
|
||||
await page.waitForFunction(() => document.activeElement.scrollTop > 0);
|
||||
await page.keyboard.press("Control+Tab");
|
||||
await rendered("Page 1 of 2");
|
||||
assert.equal(await tab("Other").getAttribute("aria-selected"), "true");
|
||||
await page.getByRole("button", { name: "Close Other", exact: true }).click();
|
||||
await tab("Other").waitFor({ state: "detached" });
|
||||
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 1);
|
||||
@@ -268,8 +182,6 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
|
||||
// Reload keeps the page and replaces the worker.
|
||||
await tab("Sample").click();
|
||||
await input.fill("2");
|
||||
await input.press("Enter");
|
||||
await rendered("Page 2 of 2");
|
||||
await button("Reload PDF").click();
|
||||
await rendered("Page 2 of 2");
|
||||
@@ -313,5 +225,5 @@ await runSmoke("features/pdf", async ({ page }) => {
|
||||
assert.equal(await tab("Sample").count(), 1);
|
||||
|
||||
assert.deepEqual(requests, [], "No network request leaves the app");
|
||||
console.log("PASS: PDF Viewer loads at first need, renders text and pages, scrolls, zooms, rotates, reloads, unlocks, reports a damaged file, keeps one worker per tab, restores its tab, and Off removes it");
|
||||
console.log("PASS: PDF Viewer loads at first need, renders text and pages, zooms, rotates, reloads, unlocks, reports a damaged file, keeps one worker per tab, restores its tab, and Off removes it");
|
||||
}, { timeout: 60000, viewport: { width: 1440, height: 1000 } });
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
// Project Management description drafts with images: an image pasted in an unsaved description survives a close,
|
||||
// a reopen, and a reload of the card. Save writes the image file. Cancel removes the image data and writes no image file.
|
||||
import assert from "node:assert/strict";
|
||||
import { runSmoke } from "../_harness/index.mjs";
|
||||
import { cardPath, draftPath, fileText, loadWorkspace, openBoard, pane, waitForFile } from "../_harness/pmFixture.mjs";
|
||||
|
||||
const imageFile = id => `.runestone/pm/images/${id}.json`;
|
||||
const draftImagesPath = id => draftPath(id).replace(/\.json$/, ".images.json");
|
||||
const json = async (page, path) => JSON.parse(await fileText(page, path) ?? "null");
|
||||
|
||||
await runSmoke("features/pmDraftImages", async ({ page }) => {
|
||||
await loadWorkspace(page);
|
||||
await openBoard(page, "Roadmap");
|
||||
const editor = page.locator("dialog.pm-card-editor[open]");
|
||||
const description = editor.locator('textarea[aria-label="Details (Markdown)"]');
|
||||
const descriptionAction = name => editor.locator(".pm-description-actions").getByRole("button", { name, exact: true });
|
||||
const openCard = async title => {
|
||||
await pane(page).locator(".pm-card-title", { hasText: new RegExp(`^${title}$`) }).click();
|
||||
await editor.waitFor();
|
||||
await editor.getByRole("button", { name: "Edit", exact: true }).click();
|
||||
};
|
||||
const closeCard = async () => {
|
||||
await editor.getByRole("button", { name: "Close card", exact: true }).click();
|
||||
await editor.waitFor({ state: "detached" });
|
||||
};
|
||||
// Paste a 1 by 1 PNG into the description. Returns the image ID of the new reference.
|
||||
const pasteImage = async name => {
|
||||
await description.evaluate((element, name) => {
|
||||
const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="), c => c.charCodeAt(0));
|
||||
const data = new DataTransfer();
|
||||
data.items.add(new File([png], name, { type: "image/png" }));
|
||||
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
|
||||
}, name);
|
||||
const reference = new RegExp(`!\\[${name.replace(".", "\\.")}\\]\\(pm-image:([0-9a-f-]{36})\\)`);
|
||||
await page.waitForFunction(source => new RegExp(source).test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value), reference.source);
|
||||
return reference.exec(await description.inputValue())[1];
|
||||
};
|
||||
// Wait until the gallery thumbnail of `name` shows the decoded image.
|
||||
const imageLoads = async name => {
|
||||
await page.waitForFunction(alt => {
|
||||
const image = document.querySelector(`dialog.pm-card-editor[open] .pm-card-images img[alt="${alt}"]`);
|
||||
return !!image?.complete && image.naturalWidth > 0;
|
||||
}, name);
|
||||
assert.equal(await editor.locator(".pm-card-images .pm-error").allInnerTexts().then(texts => texts.join("")), "");
|
||||
};
|
||||
|
||||
// A pasted image stays with the draft when the card closes. The image folder gets no file yet.
|
||||
await openCard("Card A");
|
||||
const first = await pasteImage("dot.png");
|
||||
await imageLoads("dot.png");
|
||||
await closeCard();
|
||||
await waitForFile(page, draftPath("card-a"), new RegExp(`pm-image:${first}`));
|
||||
assert.match((await json(page, draftImagesPath("card-a"))).images[first], /^data:image\/png;base64,iVBOR/);
|
||||
assert.equal(await fileText(page, imageFile(first)), undefined, "Only a save writes the image file");
|
||||
assert.match(await fileText(page, cardPath("card-a")), /\nBody of Card A\.\n$/, "Close keeps the saved description");
|
||||
|
||||
// The reopened card restores the draft and shows its image. Save writes the image file and ends the draft.
|
||||
await openCard("Card A");
|
||||
await imageLoads("dot.png");
|
||||
assert.match(await description.inputValue(), new RegExp(`pm-image:${first}`));
|
||||
await descriptionAction("Save").click();
|
||||
await waitForFile(page, cardPath("card-a"), new RegExp(`!\\[dot\\.png\\]\\(pm-image:${first}\\)`));
|
||||
assert.match(await fileText(page, imageFile(first)), /"data":"data:image\/png;base64,iVBOR/);
|
||||
assert.equal((await json(page, draftPath("card-a"))).body, null);
|
||||
assert.deepEqual((await json(page, draftImagesPath("card-a"))).images, {});
|
||||
await closeCard();
|
||||
await openCard("Card A");
|
||||
await imageLoads("dot.png");
|
||||
await closeCard();
|
||||
|
||||
// The draft saves after the paste, without another edit, so the image survives a reload of the app.
|
||||
await openCard("Card B");
|
||||
const second = await pasteImage("second.png");
|
||||
await waitForFile(page, draftImagesPath("card-b"), new RegExp(second));
|
||||
await waitForFile(page, draftPath("card-b"), new RegExp(`pm-image:${second}`));
|
||||
await page.reload();
|
||||
await page.locator('[data-tree-rel="note.md"]').waitFor();
|
||||
await openBoard(page, "Roadmap");
|
||||
await openCard("Card B");
|
||||
await imageLoads("second.png");
|
||||
|
||||
// Cancel removes the draft and its image data. The image folder gets no file.
|
||||
await descriptionAction("Cancel").click();
|
||||
await page.waitForFunction(rel => /"body":null/.test(window.__TEST__.files.get(rel) ?? ""), draftPath("card-b"));
|
||||
assert.deepEqual((await json(page, draftImagesPath("card-b"))).images, {});
|
||||
assert.equal(await fileText(page, imageFile(second)), undefined);
|
||||
assert.doesNotMatch(await fileText(page, cardPath("card-b")), /pm-image:/);
|
||||
await closeCard();
|
||||
console.log("PASS: a draft image survives a close, a reopen, and a reload. Save writes its file. Cancel leaves no image data.");
|
||||
});
|
||||
@@ -33,9 +33,9 @@ await runSmoke("find/documentFind", async ({ page }) => {
|
||||
async function onePanel() {
|
||||
assert.equal(await page.locator('.rs-find-bar:visible').count(), 1);
|
||||
assert.equal(await page.locator('.cm-search').count(), 0, 'No default CodeMirror search panel');
|
||||
// Read both widths in one task. Two separate reads can cross a layout change.
|
||||
const [bar, pane] = await page.locator('.rs-find-bar:visible').evaluate(node => [node, node.closest('.editor.pane-active')].map(element => element.getBoundingClientRect().width));
|
||||
assert.ok(Math.abs(bar - pane) < 3, 'Find spans the document pane');
|
||||
const bar = await page.locator('.rs-find-bar:visible').boundingBox();
|
||||
const pane = await page.locator('.editor.pane-active').boundingBox();
|
||||
assert.ok(Math.abs(bar.width - pane.width) < 3, 'Find spans the document pane');
|
||||
}
|
||||
async function sourceEditor() {
|
||||
await page.waitForFunction(() => !!document.querySelector('.source-editor .cm-content'));
|
||||
@@ -120,8 +120,6 @@ await runSmoke("find/documentFind", async ({ page }) => {
|
||||
await page.keyboard.press('F3');
|
||||
await page.screenshot({ path: `${output}/source-replace-${theme}.png` });
|
||||
await page.setViewportSize({ width: 800, height: 700 });
|
||||
// The outline closes in the resize event, one frame after the viewport changes. The pane width changes again at that point.
|
||||
await page.locator('.shell.right-open').waitFor({ state: 'detached' });
|
||||
await onePanel();
|
||||
assert.equal(await page.locator('.rs-find-bar').evaluate(node => node.scrollWidth <= node.clientWidth), true);
|
||||
await page.screenshot({ path: `${output}/source-narrow-${theme}.png` });
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
// Find takes typed text key by key in Write, Source, Read, and both sides of Split, also after Enter finds a match.
|
||||
import assert from "node:assert/strict";
|
||||
import { chooseView, mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||
|
||||
await runSmoke("find/typing", async ({ page }) => {
|
||||
const sample = "# Alpha\n\nAlpha alpha alphabet\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n| Beta | Two |\n\nLast Alpha paragraph.\n";
|
||||
await mockTauri(page, {
|
||||
state: { sample },
|
||||
commands: test => {
|
||||
const workspace = test.workspace({ root: "C:\\smoke-workspace", files: { "notes/welcome.md": test.state.sample } });
|
||||
return { ...workspace, workspace_search: () => [], "plugin:dialog|message": () => "Cancel" };
|
||||
},
|
||||
});
|
||||
const find = page.getByRole("textbox", { name: "Find in document", exact: true });
|
||||
const type = text => page.keyboard.type(text, { delay: 15 });
|
||||
const focused = () => find.evaluate(node => node === document.activeElement);
|
||||
const reading = { typed: "Alpha alp", removed: "Alpha aha" };
|
||||
|
||||
/**
|
||||
* Open Find, then type, delete, and type again without another click in the field.
|
||||
* After Enter, CodeMirror selects the text of the field in Write and Source, so the next key replaces it.
|
||||
* In Read, the caret stays at the end of the text, so the next key adds to it.
|
||||
*/
|
||||
async function typing(label, open, afterEnter = { typed: "p", removed: "ha" }) {
|
||||
await open();
|
||||
await page.keyboard.press("Control+f");
|
||||
await find.waitFor();
|
||||
assert.equal(await focused(), true, `${label}: Find has focus`);
|
||||
await type("Alpha");
|
||||
assert.equal(await find.inputValue(), "Alpha", `${label}: each key reaches the field`);
|
||||
await page.keyboard.press("Backspace");
|
||||
await type("a al");
|
||||
assert.equal(await find.inputValue(), "Alpha al", `${label}: Backspace and more keys reach the field`);
|
||||
assert.equal(await focused(), true, `${label}: Find keeps focus`);
|
||||
await page.keyboard.press("Enter");
|
||||
assert.equal(await focused(), true, `${label}: Enter keeps focus in Find`);
|
||||
await type("p");
|
||||
assert.equal(await find.inputValue(), afterEnter.typed, `${label}: keys after Enter reach the field`);
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.press("Backspace");
|
||||
await page.keyboard.press("Backspace");
|
||||
await type("ha");
|
||||
assert.equal(await find.inputValue(), afterEnter.removed, `${label}: Backspace after Enter acts on the field`);
|
||||
await page.keyboard.press("Escape");
|
||||
await find.waitFor({ state: "detached" });
|
||||
}
|
||||
|
||||
await page.goto(smokeUrl);
|
||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: "welcome.md" }).first().click();
|
||||
await page.locator(".cm-content").waitFor();
|
||||
|
||||
await typing("Write", async () => { await page.locator(".cm-content").click(); });
|
||||
await typing("Source", async () => {
|
||||
await chooseView(page, "Source");
|
||||
await page.locator(".source-editor .cm-content").click();
|
||||
});
|
||||
await typing("Read", async () => {
|
||||
await chooseView(page, "Read");
|
||||
await page.locator(".md-page > .reading").focus();
|
||||
}, reading);
|
||||
await chooseView(page, "Source");
|
||||
await chooseView(page, "Read beside");
|
||||
await typing("Split, the text side", async () => { await page.locator(".source-editor .cm-content").click(); });
|
||||
await typing("Split, the reading side", async () => { await page.locator(".md-page > .reading").click({ position: { x: 40, y: 10 } }); }, reading);
|
||||
|
||||
// A match stays selected until the search text changes, and the next search finds a match again.
|
||||
await page.locator(".md-page > .reading").click({ position: { x: 40, y: 10 } });
|
||||
await page.keyboard.press("Control+f");
|
||||
await type("Alpha");
|
||||
await page.keyboard.press("Enter");
|
||||
assert.equal(await page.evaluate(() => window.getSelection().toString()), "Alpha", "Enter selects the match");
|
||||
await type(" a");
|
||||
assert.equal(await find.inputValue(), "Alpha a", "A key after Enter adds to the text");
|
||||
assert.equal(await page.evaluate(() => window.getSelection().toString()), "", "A new key removes the selected match");
|
||||
await page.keyboard.press("Enter");
|
||||
assert.equal(await page.evaluate(() => window.getSelection().toString()), "Alpha a", "Enter selects the match of the longer text");
|
||||
await page.keyboard.press("Escape");
|
||||
});
|
||||
@@ -1,202 +0,0 @@
|
||||
// Split view with different tabs: two documents side by side, a browser tab beside a document, a browser tab that covers
|
||||
// the area and then moves into a pane, the close control of a plugin pane, and the Read beside toggle, in both themes.
|
||||
// Also the divider that resizes two panes, a tab that the user drags into a pane, and the new browser tab beside a browser tab.
|
||||
import assert from "node:assert/strict";
|
||||
import path from "node:path";
|
||||
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||
|
||||
await runSmoke("layout/mixedSplits", async ({ page }) => {
|
||||
const output = await outputDir("layout/mixedSplits");
|
||||
await page.addInitScript(() => localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false })));
|
||||
await mockTauri(page, {
|
||||
commands: test => {
|
||||
const workspace = test.workspace({
|
||||
root: "C:\\mixed-split-workspace",
|
||||
files: { "a.md": "# Alpha\n\nAlpha text.\n", "b.md": "# Bravo\n\nBravo text.\n" },
|
||||
});
|
||||
const snapshot = { profiles: [{ id: "user", name: "User" }], tabs: [], bookmarks: [], settings: { search: "duckduckgo", adblock: true, linkDestination: "internal", personalRules: "", homepage: "", filterLists: [] } };
|
||||
let next = 0;
|
||||
return {
|
||||
...workspace,
|
||||
browser_connect: () => "window-session",
|
||||
browser_request: ({ command, args }) => {
|
||||
if (command === "newTab") { globalThis.newTabUrls = [...(globalThis.newTabUrls || []), args.url ?? null]; const tabId = "native-" + (++next); snapshot.tabs.push({ id: tabId, profileId: "user", url: "about:blank", title: "Browser", loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
|
||||
if (command === "closeTab") snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.tabId);
|
||||
return structuredClone(snapshot);
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const pane = rel => page.locator(`[data-document-path="${rel}"]`);
|
||||
const browserPane = page.locator(".plugin-pane:not(.inactive)").filter({ has: page.locator('[data-browser-state="ready"]') });
|
||||
const tab = name => page.getByRole("tab", { name: new RegExp(name) });
|
||||
async function openToRight(name) {
|
||||
await tab(name).click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Open to the right", exact: true }).click();
|
||||
}
|
||||
async function box(locator) { const value = await locator.boundingBox(); assert.ok(value, "The pane is visible"); return value; }
|
||||
// A native tab drag: dragstart on the tab button, dragover at a place of the target, then the drop and dragend.
|
||||
async function dragOver(source, target, where) {
|
||||
const point = await target.evaluate((node, where) => {
|
||||
const r = node.getBoundingClientRect();
|
||||
return where === "down" ? { x: r.left + r.width / 2, y: r.bottom - 12 } : where === "right" ? { x: r.right - 12, y: r.top + r.height / 2 } : { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
||||
}, where);
|
||||
return source.evaluate((node, point) => {
|
||||
const transfer = new DataTransfer();
|
||||
node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, cancelable: true, dataTransfer: transfer }));
|
||||
const over = new DragEvent("dragover", { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y, dataTransfer: transfer });
|
||||
document.elementFromPoint(point.x, point.y).dispatchEvent(over);
|
||||
globalThis.tabDrag = { node, transfer, point };
|
||||
return over.defaultPrevented;
|
||||
}, point);
|
||||
}
|
||||
async function drop() {
|
||||
return page.evaluate(() => {
|
||||
const { node, transfer, point } = globalThis.tabDrag;
|
||||
const event = new DragEvent("drop", { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y, dataTransfer: transfer });
|
||||
document.elementFromPoint(point.x, point.y).dispatchEvent(event);
|
||||
node.dispatchEvent(new DragEvent("dragend", { bubbles: true, clientX: point.x, clientY: point.y, dataTransfer: transfer }));
|
||||
return event.defaultPrevented;
|
||||
});
|
||||
}
|
||||
async function setMode(mode) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, mode);
|
||||
}
|
||||
async function newBrowserTab() {
|
||||
await page.evaluate(async () => { const { pluginHost } = await import("/src/lib/plugins/registry.ts"); await pluginHost.get("browser").newTab(); });
|
||||
await page.locator('[data-browser-state="ready"]').last().waitFor();
|
||||
}
|
||||
|
||||
await page.goto(smokeUrl);
|
||||
await page.locator('[data-tree-rel="a.md"]').click(); await pane("a.md").locator(".cm-content").waitFor();
|
||||
// A click in the file tree replaces the current tab, so the second file opens from a new tab.
|
||||
await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
|
||||
await page.locator('[data-tree-rel="b.md"]').click(); await pane("b.md").locator(".cm-content").waitFor();
|
||||
assert.equal(await page.getByRole("tab").count(), 2);
|
||||
await page.waitForFunction(async () => { const { pluginHost } = await import("/src/lib/plugins/registry.ts"); return !!pluginHost.get("browser"); });
|
||||
|
||||
// Two different documents side by side.
|
||||
await openToRight("a.md");
|
||||
await pane("a.md").locator(".cm-content").waitFor();
|
||||
assert.equal(await page.locator(".document-pane").count(), 2);
|
||||
const left = await box(pane("b.md")), right = await box(pane("a.md"));
|
||||
assert.ok(right.x >= left.x + left.width - 1 && Math.abs(left.y - right.y) < 2, "The documents show side by side");
|
||||
assert.equal(await pane("a.md").locator(".breadcrumb").innerText(), "a.md", "A pane beside another pane names its file");
|
||||
await tab("a.md").click({ button: "right" });
|
||||
assert.equal(await page.getByRole("menuitem", { name: "Open to the right", exact: true }).isDisabled(), true, "A visible tab cannot open again");
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
// A new browser tab opens in the focused pane. The document that it replaces stays open as a tab.
|
||||
await newBrowserTab();
|
||||
assert.equal(await pane("a.md").count(), 0);
|
||||
assert.equal(await tab("a.md").count(), 1);
|
||||
const documentBox = await box(pane("b.md")), webBox = await box(browserPane);
|
||||
assert.ok(webBox.x >= documentBox.x + documentBox.width - 1, "The browser shows beside the document");
|
||||
assert.ok(Math.abs(webBox.width - documentBox.width) < 4, "The panes share the area");
|
||||
for (const theme of ["light", "dark"]) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, theme);
|
||||
await page.screenshot({ path: path.join(output, `document-and-browser-${theme}.png`) });
|
||||
}
|
||||
|
||||
// A click in the document pane makes its tab active. The browser stays visible.
|
||||
await pane("b.md").locator(".cm-content").click();
|
||||
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent?.includes("b.md"));
|
||||
assert.equal(await browserPane.count(), 1);
|
||||
// The document opens beside the browser, and the close control of the browser pane leaves the tab open.
|
||||
await openToRight("a.md");
|
||||
await pane("a.md").locator(".cm-content").waitFor();
|
||||
assert.equal(await page.locator(".document-pane").count(), 3);
|
||||
await browserPane.getByRole("button", { name: "Close split", exact: true }).click();
|
||||
assert.equal(await page.locator(".document-pane").count(), 2);
|
||||
assert.equal(await page.getByRole("tab", { name: /Browser/ }).count(), 1);
|
||||
await pane("a.md").getByRole("button", { name: "Close split", exact: true }).click();
|
||||
assert.equal(await page.locator(".document-pane").count(), 1);
|
||||
|
||||
// A browser tab that covers the whole area moves into the left pane when a document opens to the right.
|
||||
await page.getByRole("tab", { name: /Browser/ }).click();
|
||||
await browserPane.waitFor();
|
||||
assert.ok((await box(browserPane)).width > (await box(page.locator(".center"))).width - 4, "The browser covers the area");
|
||||
await openToRight("a.md");
|
||||
await pane("a.md").locator(".cm-content").waitFor();
|
||||
const coverLeft = await box(browserPane), coverRight = await box(pane("a.md"));
|
||||
assert.ok(coverRight.x >= coverLeft.x + coverLeft.width - 1, "The browser keeps the left pane");
|
||||
await pane("a.md").getByRole("button", { name: "Close split", exact: true }).click();
|
||||
await browserPane.waitFor();
|
||||
assert.ok((await box(browserPane)).width > (await box(page.locator(".center"))).width - 4, "The last pane gives the browser the whole area");
|
||||
|
||||
// Read beside is the toggle for the Read view beside the editor.
|
||||
await tab("b.md").click();
|
||||
await pane("b.md").locator(".cm-content").waitFor();
|
||||
await pane("b.md").getByRole("button", { name: "Read beside", exact: true }).click();
|
||||
await pane("b.md").locator(".md-page").waitFor();
|
||||
await pane("b.md").getByRole("button", { name: "Read beside", exact: true }).click();
|
||||
|
||||
// The divider between two panes changes their sizes, with the pointer and with the keyboard.
|
||||
await openToRight("a.md");
|
||||
await pane("a.md").locator(".cm-content").waitFor();
|
||||
const divider = page.getByRole("separator", { name: "Resize panes" });
|
||||
assert.equal(await divider.count(), 1);
|
||||
const area = await box(page.locator(".center"));
|
||||
const handle = await box(divider);
|
||||
await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(handle.x + handle.width / 2 - area.width * 0.2, handle.y + handle.height / 2, { steps: 4 });
|
||||
await page.mouse.up();
|
||||
const narrow = await box(pane("b.md")), wide = await box(pane("a.md"));
|
||||
assert.ok(Math.abs(narrow.width - area.width * 0.3) < 4, `The left pane has 30% of the area: ${narrow.width} of ${area.width}`);
|
||||
assert.ok(Math.abs(wide.x - (narrow.x + narrow.width)) < 2, "The right pane starts at the divider");
|
||||
assert.equal(await divider.getAttribute("aria-valuenow"), "30");
|
||||
await divider.focus(); await page.keyboard.press("ArrowRight");
|
||||
assert.equal(await divider.getAttribute("aria-valuenow"), "35");
|
||||
for (const mode of ["light", "dark"]) {
|
||||
await setMode(mode);
|
||||
await divider.hover();
|
||||
await page.screenshot({ path: path.join(output, `divider-${mode}.png`) });
|
||||
}
|
||||
await divider.dblclick();
|
||||
assert.equal(await divider.getAttribute("aria-valuenow"), "50");
|
||||
|
||||
// A new browser tab replaces the document in the focused pane. A document tab dragged to the bottom of the browser pane
|
||||
// opens below it.
|
||||
await newBrowserTab();
|
||||
assert.equal(await pane("a.md").count(), 0);
|
||||
assert.equal(await dragOver(tab("a.md"), browserPane, "down"), true, "The browser pane takes the tab");
|
||||
await page.locator('.drop-hint[data-drop-zone="down"]').waitFor();
|
||||
for (const mode of ["light", "dark"]) {
|
||||
await setMode(mode);
|
||||
await page.screenshot({ path: path.join(output, `tab-drop-${mode}.png`) });
|
||||
}
|
||||
assert.equal(await drop(), true);
|
||||
await pane("a.md").locator(".cm-content").waitFor();
|
||||
assert.equal(await page.locator(".drop-hint").count(), 0);
|
||||
const web = await box(browserPane), below = await box(pane("a.md"));
|
||||
assert.ok(below.y >= web.y + web.height - 1 && Math.abs(below.x - web.x) < 2, "The document shows below the browser");
|
||||
assert.equal(await page.getByRole("separator", { name: "Resize panes" }).count(), 2);
|
||||
// The browser tab dragged to the document pane replaces it there, and leaves its old pane. The first browser tab is not visible.
|
||||
assert.equal(await dragOver(tab("Browser").last(), pane("b.md"), "center"), true);
|
||||
assert.equal(await drop(), true);
|
||||
await page.waitForFunction(() => document.querySelectorAll(".document-pane").length === 2);
|
||||
assert.equal(await pane("b.md").count(), 0);
|
||||
assert.equal(await tab("b.md").count(), 1, "The replaced document stays open as a tab");
|
||||
const moved = await box(browserPane), rest = await box(pane("a.md"));
|
||||
assert.ok(rest.x >= moved.x + moved.width - 1, "The browser shows left of the document");
|
||||
// A drop on the pane that shows the tab changes nothing.
|
||||
assert.equal(await dragOver(tab("Browser").last(), browserPane, "center"), false);
|
||||
await drop();
|
||||
|
||||
// "New tab to the right" of a browser tab that covers the area opens a new browser tab beside it, not a copy of the page.
|
||||
await pane("a.md").getByRole("button", { name: "Close split", exact: true }).click();
|
||||
await browserPane.waitFor();
|
||||
assert.ok((await box(browserPane)).width > area.width - 4, "The browser covers the area");
|
||||
const before = await page.evaluate(() => globalThis.newTabUrls.length);
|
||||
await tab("Browser").last().click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "New tab to the right", exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelectorAll(".plugin-pane.embedded:not(.inactive)").length === 2);
|
||||
assert.deepEqual(await page.evaluate(start => globalThis.newTabUrls.slice(start), before), [null], "The new tab opens the home page");
|
||||
const [first, second] = await page.locator(".plugin-pane.embedded:not(.inactive)").evaluateAll(nodes => nodes.map(node => { const r = node.getBoundingClientRect(); return { x: r.x, width: r.width }; }).sort((a, b) => a.x - b.x));
|
||||
assert.ok(second.x >= first.x + first.width - 1 && first.width > area.width * 0.4, "The browser tabs show side by side");
|
||||
await page.screenshot({ path: path.join(output, "browser-beside-browser.png") });
|
||||
|
||||
console.log(JSON.stringify({ passed: ["two documents side by side", "browser beside a document", "replaced document stays a tab", "focus by click", "plugin pane close control", "covering browser moves into a pane", "last pane releases the browser", "Read beside toggle", "divider by pointer, keyboard, and double-click", "tab drop below a pane", "tab drop replaces a pane", "new browser tab beside a browser tab", "light/dark screenshots"], nativeDesktop: "not tested" }, null, 2));
|
||||
}, { timeout: 30000 });
|
||||
@@ -1,16 +1,15 @@
|
||||
// Sidebar layout persistence: the hidden outline, resized sidebars, the navigation view, and collapsed backlinks survive layout changes, tab changes, reloads, and reopened windows.
|
||||
// Sidebar layout persistence: the hidden outline, resized sidebars, and the navigation view survive layout changes, reloads, and reopened windows.
|
||||
import assert from "node:assert/strict";
|
||||
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||
import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||
|
||||
await runSmoke("layout/outline", async ({ browser }) => {
|
||||
const output = await outputDir("layout/outline");
|
||||
// Pages share one context, so a reopened window keeps the saved layout.
|
||||
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
// Unknown commands return null, as the original mock did.
|
||||
await mockTauri(context, {
|
||||
strict: false,
|
||||
commands: test => ({
|
||||
...test.workspace({ root: "D:\\LayoutTest", files: { "note.md": "# Layout test\n\nA note.\n", "data.txt": "Plain text.\n" } }),
|
||||
...test.workspace({ root: "D:\\LayoutTest", files: { "note.md": "# Layout test\n\nA note.\n" } }),
|
||||
plugins_snapshot: () => ({ root: "D:\\LayoutTest\\plugins", plugins: [] }),
|
||||
}),
|
||||
});
|
||||
@@ -33,15 +32,11 @@ await runSmoke("layout/outline", async ({ browser }) => {
|
||||
async function widths() {
|
||||
return page.locator(".shell").evaluate(element => [element.style.getPropertyValue("--left"), element.style.getPropertyValue("--right")]);
|
||||
}
|
||||
async function quickOpen(name) {
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).click();
|
||||
await page.locator(`[role="tab"][data-path="${name}"][aria-selected="true"]`).waitFor();
|
||||
}
|
||||
await reopen();
|
||||
await page.getByText("LayoutTest", { exact: true }).waitFor();
|
||||
await quickOpen("note.md");
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill("note.md");
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.md" }).click();
|
||||
await page.locator(".cm-content").waitFor();
|
||||
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
|
||||
await page.keyboard.press("Control+e");
|
||||
@@ -80,24 +75,6 @@ await runSmoke("layout/outline", async ({ browser }) => {
|
||||
await page.getByRole("button", { name: "Show outline", exact: true }).click();
|
||||
assert.deepEqual(await widths(), resized);
|
||||
console.log("PASS: collapsed sidebars retain their sizes and navigation view");
|
||||
|
||||
// Card e81770bc: collapsed backlinks stay collapsed while a tab without backlinks is active, and after a window reopen.
|
||||
const backlinks = () => page.getByRole("button", { name: /^Backlinks \d+$/ });
|
||||
await quickOpen("note.md");
|
||||
await backlinks().click();
|
||||
assert.equal(await backlinks().getAttribute("aria-expanded"), "false");
|
||||
await quickOpen("data.txt");
|
||||
await backlinks().waitFor({ state: "detached" });
|
||||
await quickOpen("note.md");
|
||||
assert.equal(await backlinks().getAttribute("aria-expanded"), "false");
|
||||
await page.screenshot({ path: `${output}/backlinks-collapsed-after-tab-change.png` });
|
||||
await reopen();
|
||||
await quickOpen("note.md");
|
||||
assert.equal(await backlinks().getAttribute("aria-expanded"), "false");
|
||||
await backlinks().click();
|
||||
assert.equal(await backlinks().getAttribute("aria-expanded"), "true");
|
||||
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("runestone.workbenchLayout")).backlinksOpen), true);
|
||||
console.log("PASS: collapsed backlinks survive a tab change and a window reopen");
|
||||
errors.push(...page.errors);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
@@ -51,7 +51,7 @@ await runSmoke("layout/panesAndSettings", async ({ browser }) => {
|
||||
const menu = page.getByRole("menu", { name: "File actions", exact: true });
|
||||
await menu.waitFor();
|
||||
const labels = await menu.locator(":scope > button, :scope > hr").evaluateAll(nodes => nodes.map(node => node.tagName === "HR" ? "|" : node.querySelector(".action-label").textContent));
|
||||
assert.deepEqual(labels, ["Open in new tab", "Open to the right", "Open in default app", "Open in terminal", "|", "Cut", "Copy", "Paste", "Make a copy", "|",
|
||||
assert.deepEqual(labels, ["Open in new tab", "Open in default app", "Open in terminal", "|", "Cut", "Copy", "Paste", "Make a copy", "|",
|
||||
"Rename", "Remove bookmark", "Pin", "Save as template", "|", "Show in Explorer", "Copy path", "|", "Undo file move", "Redo file move", "|", "Delete", "Delete permanently"]);
|
||||
const error = await page.evaluate(() => { const probe = document.createElement("span"); probe.style.color = "var(--rs-error)"; document.body.append(probe); const color = getComputedStyle(probe).color; probe.remove(); return color; });
|
||||
assert.equal(await menu.getByRole("menuitem", { name: "Delete", exact: true }).evaluate(node => getComputedStyle(node).color), error);
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
// A PDF file beside a note: "Open to the right" in the file tree opens the PDF in a new pane beside the note.
|
||||
// The user writes in the note and turns the pages of the PDF, and both panes stay visible. A drag of the divider resizes
|
||||
// both panes. A PDF that covers the area moves into the left pane when a note opens to its right. Both themes.
|
||||
import assert from "node:assert/strict";
|
||||
import path from "node:path";
|
||||
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||
import { samplePdf } from "../../fixtures/pdf/fixtures.mjs";
|
||||
|
||||
await runSmoke("layout/pdfBesideNote", async ({ page }) => {
|
||||
const output = await outputDir("layout/pdfBesideNote");
|
||||
await page.addInitScript(() => localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false })));
|
||||
await mockTauri(page, {
|
||||
state: { sample: [...samplePdf()] },
|
||||
commands: test => ({
|
||||
...test.workspace({ root: "C:\\pdf-beside-note", files: { "Sample.pdf": "", "note.md": "# Note\n\nReading notes.\n" } }),
|
||||
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
|
||||
spelling_menu_install: () => null,
|
||||
workspace_read_bytes: () => new Uint8Array(test.state.sample).buffer,
|
||||
}),
|
||||
});
|
||||
|
||||
const row = name => page.locator(`[data-tree-rel="${name}"]`);
|
||||
const note = page.locator('[data-document-path="note.md"]');
|
||||
const pdf = page.locator(".plugin-pane:not(.inactive)").filter({ has: page.locator(".pdf-viewer") });
|
||||
const status = pdf.locator(".pdf-viewer .status");
|
||||
async function box(locator) { const value = await locator.boundingBox(); assert.ok(value, "The pane is visible"); return value; }
|
||||
async function besideEachOther(left, right, message) {
|
||||
const a = await box(left), b = await box(right);
|
||||
assert.ok(b.x >= a.x + a.width - 1 && Math.abs(a.y - b.y) < 2, message);
|
||||
return [a, b];
|
||||
}
|
||||
|
||||
await page.goto(smokeUrl);
|
||||
await row("note.md").click();
|
||||
await note.locator(".cm-content").waitFor();
|
||||
|
||||
// The file tree opens the PDF in a new pane to the right of the note.
|
||||
await row("Sample.pdf").click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Open to the right", exact: true }).click();
|
||||
await status.filter({ hasText: /^Page 1 of 2$/ }).waitFor();
|
||||
assert.equal(await page.locator(".document-pane").count(), 2);
|
||||
await besideEachOther(note, pdf, "The PDF shows to the right of the note");
|
||||
|
||||
// Write in the note. The PDF stays visible.
|
||||
await note.locator(".cm-content").click();
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.keyboard.type("Typed beside the PDF.");
|
||||
assert.match(await note.locator(".cm-content").innerText(), /Typed beside the PDF\./);
|
||||
assert.equal(await pdf.count(), 1);
|
||||
// Turn a page of the PDF. The note stays visible and keeps the text.
|
||||
await pdf.getByRole("button", { name: "Next page", exact: true }).click();
|
||||
await status.filter({ hasText: /^Page 2 of 2$/ }).waitFor();
|
||||
assert.match(await note.locator(".cm-content").innerText(), /Typed beside the PDF\./);
|
||||
// Back to the note: the keyboard goes to the note.
|
||||
await note.locator(".cm-content").click();
|
||||
await page.keyboard.type(" More.");
|
||||
assert.match(await note.locator(".cm-content").innerText(), /Typed beside the PDF\. More\./);
|
||||
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent?.includes("note.md"));
|
||||
|
||||
// The divider gives the PDF more space.
|
||||
const divider = page.getByRole("separator", { name: "Resize panes" });
|
||||
const handle = await box(divider), area = await box(page.locator(".center"));
|
||||
await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(handle.x + handle.width / 2 - area.width * 0.15, handle.y + handle.height / 2, { steps: 4 });
|
||||
await page.mouse.up();
|
||||
const [left, right] = await besideEachOther(note, pdf, "The panes stay side by side after a resize");
|
||||
assert.ok(right.width > left.width + area.width * 0.2, "The PDF pane is wider than the note pane");
|
||||
for (const mode of ["light", "dark"]) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, mode);
|
||||
await page.screenshot({ path: path.join(output, `pdf-beside-note-${mode}.png`) });
|
||||
}
|
||||
|
||||
// A PDF that covers the area moves into the left pane when a note opens to its right.
|
||||
await pdf.getByRole("button", { name: "Close split", exact: true }).click();
|
||||
await page.getByRole("tab", { name: /Sample/ }).click();
|
||||
await status.waitFor();
|
||||
assert.ok((await box(pdf)).width > area.width - 4, "The PDF covers the area");
|
||||
await row("note.md").click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Open to the right", exact: true }).click();
|
||||
await note.locator(".cm-content").waitFor();
|
||||
await besideEachOther(pdf, note, "The PDF keeps the left pane");
|
||||
console.log(JSON.stringify({ passed: ["file tree opens a PDF to the right", "typing in the note beside the PDF", "page turn in the PDF beside the note", "divider resize", "covering PDF moves into a pane", "light/dark screenshots"], nativeDesktop: "not tested" }, null, 2));
|
||||
}, { timeout: 30000 });
|
||||
@@ -67,14 +67,8 @@ await runSmoke("layout/titleBar", async ({ browser }) => {
|
||||
await page.keyboard.press("Control+\\");
|
||||
await page.locator("aside.left").waitFor();
|
||||
|
||||
// With few tabs, the drag area fills the free space after the + button.
|
||||
const drag = page.locator(".window-drag-space");
|
||||
await open(names[0]);
|
||||
const center = await box(page.locator(".header-center")), free = await box(drag);
|
||||
assert.ok(free.width > 400 && Math.abs(free.right - center.right) <= 1, JSON.stringify({ center, free }));
|
||||
|
||||
// Tabs keep a readable width and scroll. Fades show hidden tabs, and the list names every tab.
|
||||
for (const name of names.slice(1)) await open(name);
|
||||
for (const name of names) await open(name);
|
||||
const widths = await page.locator("header .tab").evaluateAll(tabs => tabs.map(tab => tab.getBoundingClientRect().width));
|
||||
assert.ok(widths.every(width => width >= 120), JSON.stringify(widths));
|
||||
const strip = page.locator("header .tabs");
|
||||
@@ -99,9 +93,9 @@ await runSmoke("layout/titleBar", async ({ browser }) => {
|
||||
await list.waitFor({ state: "detached" });
|
||||
assert.equal(await strip.evaluate(node => node.classList.contains("fade-end")), true);
|
||||
|
||||
// When the tabs scroll, they use all space up to a drag area of 48 pixels. Caption buttons are square and fill the title bar height.
|
||||
assert.equal(Math.round((await box(drag)).width), 48);
|
||||
assert.ok(Math.abs((await box(drag)).right - (await box(page.locator(".header-center"))).right) <= 1);
|
||||
// A fixed drag area follows the tabs. Caption buttons are square and fill the title bar height.
|
||||
const drag = page.locator(".window-drag-space");
|
||||
assert.equal(Math.round((await box(drag)).width), 120);
|
||||
assert.equal(await drag.getAttribute("data-tauri-drag-region"), "");
|
||||
const captions = await page.locator(".window-controls .icon-btn").evaluateAll(buttons => buttons.map(button => ({ width: button.getBoundingClientRect().width, height: button.getBoundingClientRect().height, radius: getComputedStyle(button).borderRadius })));
|
||||
const height = (await box(page.locator("header.header"))).height;
|
||||
@@ -140,5 +134,5 @@ await runSmoke("layout/titleBar", async ({ browser }) => {
|
||||
assert.match(await mac.getByRole("button", { name: "Settings (⌘,)", exact: true }).getAttribute("aria-label"), /⌘/);
|
||||
await mac.locator("header.header").screenshot({ path: `${output}/header-mac.png` });
|
||||
assert.deepEqual([...page.errors, ...mac.errors], []);
|
||||
console.log("PASS: bottom bar of the side pane, ribbon fallback, readable tabs with fades and a list, tabs that fill the header up to the drag area, square caption buttons, Snap Layouts request, macOS layout, both themes, narrow window.");
|
||||
console.log("PASS: bottom bar of the side pane, ribbon fallback, readable tabs with fades and a list, fixed drag area, square caption buttons, Snap Layouts request, macOS layout, both themes, narrow window.");
|
||||
});
|
||||
|
||||
@@ -21,7 +21,7 @@ await runSmoke("layout/viewModes", async ({ browser }) => {
|
||||
const page = await openPage(context), settings = await openPage(context);
|
||||
const group = page.getByRole("radiogroup", { name: "View", exact: true });
|
||||
const radio = name => group.getByRole("radio", { name, exact: true });
|
||||
const split = page.locator(".chrome-bar").getByRole("button", { name: "Read beside", exact: true });
|
||||
const split = page.locator(".chrome-bar").getByRole("button", { name: "Split", exact: true });
|
||||
const checked = () => group.getByRole("radio", { checked: true }).getAttribute("aria-label");
|
||||
const status = () => page.locator(".status").innerText();
|
||||
async function open(name) {
|
||||
@@ -86,7 +86,7 @@ await runSmoke("layout/viewModes", async ({ browser }) => {
|
||||
await page.locator(".live-writer").waitFor();
|
||||
|
||||
// Split shows Read beside the current editor. Write and Source keep it. Read ends it.
|
||||
await chooseView(page, "Read beside");
|
||||
await chooseView(page, "Split");
|
||||
assert.equal(await split.getAttribute("aria-pressed"), "true");
|
||||
await page.locator(".body.split .live-writer").waitFor();
|
||||
await page.locator(".body.split .md-page").waitFor();
|
||||
@@ -97,10 +97,10 @@ await runSmoke("layout/viewModes", async ({ browser }) => {
|
||||
assert.equal(await split.getAttribute("aria-pressed"), "false");
|
||||
assert.equal(await page.locator(".body.split").count(), 0);
|
||||
assert.equal(await page.locator(".editor-wrap").isVisible(), false);
|
||||
await chooseView(page, "Read beside");
|
||||
await chooseView(page, "Split");
|
||||
await page.locator(".body.split .source-editor").waitFor();
|
||||
assert.equal(await checked(), "Source");
|
||||
await chooseView(page, "Read beside");
|
||||
await chooseView(page, "Split");
|
||||
await chooseView(page, "Write");
|
||||
|
||||
// The file title shows by default. The General setting hides it in Write and Read.
|
||||
@@ -123,9 +123,9 @@ await runSmoke("layout/viewModes", async ({ browser }) => {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); window.dispatchEvent(new Event("focus")); }, theme);
|
||||
await page.waitForFunction(mode => document.documentElement.dataset.theme === mode, theme);
|
||||
await page.locator(".chrome-bar").screenshot({ path: `${output}/bar-${theme}.png` });
|
||||
await chooseView(page, "Read beside");
|
||||
await chooseView(page, "Split");
|
||||
await page.locator(".chrome-bar").screenshot({ path: `${output}/bar-split-${theme}.png` });
|
||||
await chooseView(page, "Read beside");
|
||||
await chooseView(page, "Split");
|
||||
}
|
||||
|
||||
// The controls show icons only, at every width (UI-056). The names stay for assistive technology and tooltips.
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
// A drag of the tab that a pane shows, with real mouse input: the tab moves to a new pane on the right or bottom side of
|
||||
// its pane, and the pane shows the next tab. A browser tab that covers the area moves beside the document below it.
|
||||
// With only one tab, the drag shows no hint.
|
||||
import assert from "node:assert/strict";
|
||||
import path from "node:path";
|
||||
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||
|
||||
await runSmoke("layout/visibleTabDrag", async ({ page }) => {
|
||||
const output = await outputDir("layout/visibleTabDrag");
|
||||
await page.addInitScript(() => localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false })));
|
||||
await mockTauri(page, {
|
||||
commands: test => {
|
||||
const workspace = test.workspace({
|
||||
root: "C:\\visible-tab-drag-workspace",
|
||||
files: { "a.md": "# Alpha\n\nAlpha text.\n", "b.md": "# Bravo\n\nBravo text.\n", "c.md": "# Charlie\n\nCharlie text.\n" },
|
||||
});
|
||||
const snapshot = { profiles: [{ id: "user", name: "User" }], tabs: [], bookmarks: [], settings: { search: "duckduckgo", adblock: true, linkDestination: "internal", personalRules: "", homepage: "", filterLists: [] } };
|
||||
let next = 0;
|
||||
return {
|
||||
...workspace,
|
||||
browser_connect: () => "window-session",
|
||||
browser_request: ({ command }) => {
|
||||
if (command === "newTab") { const tabId = "native-" + (++next); snapshot.tabs.push({ id: tabId, profileId: "user", url: "about:blank", title: "Browser", loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
|
||||
return structuredClone(snapshot);
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const pane = rel => page.locator(`[data-document-path="${rel}"]`);
|
||||
const browserPane = page.locator(".plugin-pane:not(.inactive)").filter({ has: page.locator('[data-browser-state="ready"]') });
|
||||
const tab = name => page.getByRole("tab", { name: new RegExp(name) });
|
||||
const hint = page.locator(".drop-hint");
|
||||
async function box(locator) { const value = await locator.boundingBox(); assert.ok(value, "The element is visible"); return value; }
|
||||
const shown = () => page.locator("[data-document-path]").evaluateAll(nodes => nodes.map(node => node.getAttribute("data-document-path")));
|
||||
const activeTab = () => page.locator('[role="tab"][aria-selected="true"]').innerText();
|
||||
/** Press the mouse button on a tab and move the pointer to a part of a target. The button stays down. */
|
||||
async function dragTo(name, target, where) {
|
||||
const from = await box(tab(name)), to = await box(target);
|
||||
const point = where === "right" ? { x: to.x + to.width - 30, y: to.y + to.height / 2 }
|
||||
: where === "left" ? { x: to.x + 30, y: to.y + to.height / 2 }
|
||||
: where === "down" ? { x: to.x + to.width / 2, y: to.y + to.height - 30 }
|
||||
: { x: to.x + to.width / 2, y: to.y + to.height / 2 };
|
||||
await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(from.x + from.width / 2 + 8, from.y + from.height / 2 + 8, { steps: 3 });
|
||||
await page.mouse.move(point.x, point.y, { steps: 10 });
|
||||
// The browser fires dragover on the next move. A target that a step only enters gets no dragover.
|
||||
await page.mouse.move(point.x + 2, point.y + 2, { steps: 2 });
|
||||
}
|
||||
async function open(name) {
|
||||
await page.locator(`[data-tree-rel="${name}"]`).click();
|
||||
await pane(name).locator(".cm-content").waitFor();
|
||||
}
|
||||
|
||||
await page.goto(smokeUrl);
|
||||
await open("a.md");
|
||||
assert.equal(await page.getByRole("tab").count(), 1);
|
||||
|
||||
// The only tab has no other tab to leave in its pane. The drag shows no hint and changes nothing.
|
||||
await dragTo("a.md", pane("a.md"), "right");
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await hint.count(), 0, "The only tab cannot open a pane");
|
||||
await page.mouse.up();
|
||||
assert.deepEqual(await shown(), ["a.md"]);
|
||||
|
||||
// A click in the file tree replaces the current tab, so each more file opens from a new tab.
|
||||
for (const name of ["b.md", "c.md"]) {
|
||||
await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
|
||||
await open(name);
|
||||
}
|
||||
assert.deepEqual(await shown(), ["c.md"]);
|
||||
|
||||
// The middle of the pane already shows the tab, so it is no drop target. The right part opens a new pane.
|
||||
await dragTo("c.md", pane("c.md"), "center");
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await hint.count(), 0, "The middle of the pane does not take its own tab");
|
||||
const area = await box(page.locator("main.center"));
|
||||
await page.mouse.move(area.x + area.width - 30, area.y + area.height / 2, { steps: 5 });
|
||||
await page.locator('.drop-hint[data-drop-zone="right"]').waitFor();
|
||||
await page.screenshot({ path: path.join(output, "visible-tab-hint.png") });
|
||||
await page.mouse.up();
|
||||
await pane("b.md").locator(".cm-content").waitFor();
|
||||
assert.equal(await hint.count(), 0);
|
||||
// c.md is the last tab, so its pane shows the tab before it.
|
||||
assert.deepEqual(await shown(), ["b.md", "c.md"], "The tab moves to the right, and its pane shows the tab before it");
|
||||
assert.match(await activeTab(), /c\.md/, "The moved tab stays the active tab");
|
||||
const left = await box(pane("b.md")), right = await box(pane("c.md"));
|
||||
assert.ok(right.x >= left.x + left.width - 1 && Math.abs(left.y - right.y) < 2, "The panes show side by side");
|
||||
assert.equal(await page.getByRole("tab").count(), 3, "All tabs stay open");
|
||||
|
||||
// The tab of the left pane moves below it. The pane shows the only tab that no pane shows.
|
||||
await dragTo("b.md", pane("b.md"), "down");
|
||||
await page.locator('.drop-hint[data-drop-zone="down"]').waitFor();
|
||||
await page.mouse.up();
|
||||
await pane("a.md").locator(".cm-content").waitFor();
|
||||
assert.equal(await page.locator(".document-pane").count(), 3);
|
||||
const top = await box(pane("a.md")), bottom = await box(pane("b.md"));
|
||||
assert.ok(bottom.y >= top.y + top.height - 1 && Math.abs(top.x - bottom.x) < 2, "The moved tab shows below its old pane");
|
||||
assert.match(await activeTab(), /b\.md/);
|
||||
|
||||
// Each tab now shows in a pane, so a pane has no other tab to show. The drag shows no hint.
|
||||
await dragTo("a.md", pane("a.md"), "right");
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await hint.count(), 0, "No tab is free for the pane");
|
||||
await page.mouse.up();
|
||||
assert.equal(await page.locator(".document-pane").count(), 3);
|
||||
|
||||
// A browser tab that covers the area moves to a new pane on the right. The document below it shows on the left.
|
||||
for (let panes = 3; panes > 1; panes--) await page.getByRole("button", { name: "Close split", exact: true }).first().click();
|
||||
assert.equal(await page.locator(".document-pane").count(), 1);
|
||||
const below = (await shown())[0];
|
||||
await page.waitForFunction(async () => { const { pluginHost } = await import("/src/lib/plugins/registry.ts"); return !!pluginHost.get("browser"); });
|
||||
await page.evaluate(async () => { const { pluginHost } = await import("/src/lib/plugins/registry.ts"); await pluginHost.get("browser").newTab(); });
|
||||
await page.locator('[data-browser-state="ready"]').waitFor();
|
||||
assert.ok((await box(browserPane)).width > area.width - 4, "The browser covers the area");
|
||||
await dragTo("Browser", page.locator("main.center"), "right");
|
||||
await page.locator('.drop-hint[data-drop-zone="right"]').waitFor();
|
||||
await page.mouse.up();
|
||||
await pane(below).locator(".cm-content").waitFor();
|
||||
const documentBox = await box(pane(below)), webBox = await box(browserPane);
|
||||
assert.ok(webBox.x >= documentBox.x + documentBox.width - 1, "The browser shows to the right of the document");
|
||||
assert.match(await activeTab(), /Browser/);
|
||||
|
||||
// A tab that no pane shows opens in a new pane on the left side of the browser pane (card 156758f1).
|
||||
const free = ["a.md", "b.md", "c.md"].find(name => name !== below);
|
||||
await dragTo(free, browserPane, "left");
|
||||
await page.locator('.drop-hint[data-drop-zone="left"]').waitFor();
|
||||
const leftHint = await box(hint), browserBefore = await box(browserPane);
|
||||
assert.ok(Math.abs(leftHint.x - browserBefore.x) < 2 && leftHint.width < browserBefore.width * 0.6, "The hint covers the left half of the pane");
|
||||
assert.equal((await hint.innerText()).trim(), "Open to the left");
|
||||
await page.screenshot({ path: path.join(output, "left-drop-hint.png") });
|
||||
await page.mouse.up();
|
||||
await pane(free).locator(".cm-content").waitFor();
|
||||
const first = await box(pane(below)), middle = await box(pane(free)), last = await box(browserPane);
|
||||
assert.ok(first.x + first.width <= middle.x + 1 && middle.x + middle.width <= last.x + 1, "The new pane shows between the document and the browser");
|
||||
assert.match(await activeTab(), new RegExp(free.replace(".", "\\.")));
|
||||
|
||||
// The tab menu closes the split of a tab. The tab stays open, and the other panes stay.
|
||||
const tabCount = await page.getByRole("tab").count();
|
||||
const closeButtons = page.getByRole("button", { name: "Close split", exact: true });
|
||||
assert.equal(await closeButtons.count(), 3, "Each pane bar has a Close split button");
|
||||
assert.equal((await closeButtons.first().innerText()).trim(), "Close split", "The button shows its name");
|
||||
await closeButtons.first().screenshot({ path: path.join(output, "close-split-button.png") });
|
||||
// Screenshots of the pane bars in both themes and in a narrow window.
|
||||
const viewport = page.viewportSize();
|
||||
for (const mode of ["light", "dark"]) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, mode);
|
||||
await page.waitForTimeout(150);
|
||||
await page.screenshot({ path: path.join(output, `close-split-${mode}.png`) });
|
||||
}
|
||||
await page.setViewportSize({ width: 760, height: viewport.height });
|
||||
await page.waitForTimeout(200);
|
||||
await page.screenshot({ path: path.join(output, "close-split-narrow.png") });
|
||||
// A narrow pane shows only the icon of the button. The tooltip gives its name.
|
||||
await closeButtons.last().hover();
|
||||
await page.locator(".rs-tooltip:popover-open").filter({ hasText: "Close split" }).waitFor();
|
||||
await page.mouse.move(0, 0);
|
||||
await page.setViewportSize(viewport);
|
||||
await tab(free).click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Close split", exact: true }).click();
|
||||
await page.waitForFunction(count => document.querySelectorAll(".document-pane").length + document.querySelectorAll(".plugin-pane:not(.inactive)").length <= count, 3);
|
||||
assert.deepEqual((await shown()).filter(Boolean), [below], "The pane of the tab closes. The browser pane stays.");
|
||||
assert.equal(await page.getByRole("tab").count(), tabCount, "The tab stays open");
|
||||
// A tab that no pane shows has no Close split item.
|
||||
await tab(free).click({ button: "right" });
|
||||
assert.equal(await page.getByRole("menuitem", { name: "Close split", exact: true }).count(), 0);
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
console.log(JSON.stringify({ passed: ["one tab shows no hint", "own pane middle is no target", "visible tab moves right", "visible tab moves below", "no free tab shows no hint", "covering browser tab moves right", "free tab opens left of a pane", "tab menu closes a split and keeps the tab"], nativeDesktop: "not tested" }, null, 2));
|
||||
});
|
||||
@@ -72,7 +72,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(expected => window.__TEST__.files.get("notes/welcome.md") === expected, original + "Added in source.");
|
||||
|
||||
await chooseView(page, "Read beside");
|
||||
await chooseView(page, "Split");
|
||||
await page.locator(".md-page h1").first().waitFor();
|
||||
assert.ok(await page.locator(".source-editor").isVisible());
|
||||
await page.evaluate(() => {
|
||||
@@ -153,7 +153,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
|
||||
await page.locator(".md-page").evaluate(element => { element.scrollTop = 0; });
|
||||
await page.screenshot({ path: path.join(output, "reader-narrow.png") });
|
||||
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
|
||||
await chooseView(page, "Read beside");
|
||||
await chooseView(page, "Split");
|
||||
await page.waitForFunction(() => {
|
||||
const host = document.querySelector(".source-editor");
|
||||
const rendered = host?.querySelector(".cm-editor");
|
||||
@@ -168,7 +168,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
|
||||
await page.screenshot({ path: path.join(output, "reader-split-wide.png") });
|
||||
|
||||
// A second press ends the Split view.
|
||||
await chooseView(page, "Read beside");
|
||||
await chooseView(page, "Split");
|
||||
await page.locator(".md-page").waitFor({ state: "detached" });
|
||||
// The editor stores one line break character. The saved file keeps its own line breaks.
|
||||
assert.equal(await contents(), showcase.replace(/\r\n/g, "\n"));
|
||||
|
||||
@@ -26,7 +26,7 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
|
||||
const url = new URL(smokeUrl).href;
|
||||
const filler = Array.from({ length: 50 }, (_, i) => `Paragraph ${i}. Some text before the destination.\n`).join('\n');
|
||||
const source = '# Install and start\n\nChoose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).\n\n[Other document](other.md#caf%C3%A9-setup-1)\n\n[Missing section](#no-such-section)\n\n' + filler + '\n## Windows installer\n\nWindows instructions.\n\n' + filler + '\n## macOS installer (Apple Silicon)\n\nMac instructions.\n\n' + filler + '\n## Linux (Intel/AMD 64-bit)\n\nLinux instructions.\n';
|
||||
const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n\n' + filler;
|
||||
const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n';
|
||||
async function writerJump(label, line) {
|
||||
const link = page.locator('.cm-content .writer-link').filter({ hasText: label }).first();
|
||||
await link.click({ modifiers: ['Control'] });
|
||||
@@ -57,16 +57,6 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
|
||||
return !heading.hidden && rect.top >= box.top && rect.bottom <= box.bottom;
|
||||
}, text);
|
||||
}
|
||||
// A heading link puts the heading at the top of the view, below a gap of about 24 pixels.
|
||||
// The last heading of a short document cannot reach the top, so the checks use headings with text below them.
|
||||
async function headingAtTop(selector, text, scroller) {
|
||||
await page.waitForFunction(({ selector, text, scroller }) => [...document.querySelectorAll(selector)].some(node => {
|
||||
const offset = node.textContent.includes(text) ? node.getBoundingClientRect().top - node.closest(scroller).getBoundingClientRect().top : -1;
|
||||
return offset >= 0 && offset <= 60;
|
||||
}), { selector, text, scroller });
|
||||
}
|
||||
const writerHeadingAtTop = text => headingAtTop('.cm-line.writer-heading', text, '.cm-scroller');
|
||||
const readerHeadingAtTop = text => headingAtTop('.reading h2', text, '.md-page');
|
||||
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
|
||||
await page.setViewportSize({ width, height:1000 });
|
||||
await page.goto(url);
|
||||
@@ -82,12 +72,10 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
|
||||
await page.getByRole('button', { name:'Hide outline', exact:true }).click();
|
||||
}
|
||||
await writerJump('Windows setup', await jumpLine('## Windows installer'));
|
||||
await writerHeadingAtTop('Windows installer');
|
||||
await top();
|
||||
await writerJump('Windows setup', await jumpLine('## Windows installer'));
|
||||
await top();
|
||||
await writerJump('macOS setup', await jumpLine('## macOS installer'));
|
||||
await writerHeadingAtTop('macOS installer (Apple Silicon)');
|
||||
await top();
|
||||
await writerJump('Linux setup', await jumpLine('## Linux'));
|
||||
await page.screenshot({ path:`${output}/writer-${theme}-${width}.png` });
|
||||
@@ -103,26 +91,21 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
|
||||
const view = node ? EditorView.findFromDOM(node) : null;
|
||||
return view && view.state.doc.lineAt(view.state.selection.main.head).text === '## Café setup' && view.state.selection.main.head > 100;
|
||||
});
|
||||
// The card case: a link to a heading in another file.
|
||||
await writerHeadingAtTop('Café setup');
|
||||
await page.screenshot({ path:`${output}/other-file-${theme}-${width}.png` });
|
||||
assert.equal(await page.getByRole('tab', { name:'a.md', exact:true }).count(), 1);
|
||||
await page.getByRole('tab', { name:'a.md', exact:true }).click();
|
||||
await top();
|
||||
await chooseView(page, 'Read');
|
||||
await readerJump('Windows setup', 'Windows installer');
|
||||
await readerHeadingAtTop('Windows installer');
|
||||
await page.screenshot({ path:`${output}/reading-${theme}-${width}.png` });
|
||||
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
|
||||
await readerJump('macOS setup', 'macOS installer (Apple Silicon)');
|
||||
await readerHeadingAtTop('macOS installer (Apple Silicon)');
|
||||
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
|
||||
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
|
||||
await chooseView(page, 'Read beside');
|
||||
await chooseView(page, 'Split');
|
||||
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
|
||||
await readerJump('Windows setup', 'Windows installer');
|
||||
await page.screenshot({ path:`${output}/split-${theme}-${width}.png` });
|
||||
await chooseView(page, 'Read beside');
|
||||
await chooseView(page, 'Split');
|
||||
await chooseView(page, 'Source');
|
||||
await page.locator('.source-editor .cm-content').waitFor();
|
||||
await chooseView(page, 'Read');
|
||||
|
||||
@@ -129,7 +129,7 @@ await runSmoke("tables/formulas", async ({ page }) => {
|
||||
await page.keyboard.press('Control+e');
|
||||
assert.equal(await result(3, 1).innerText(), '12');
|
||||
assert.equal(await result(3, 3).innerText(), '58');
|
||||
for (const mode of ['Read', 'Read beside']) {
|
||||
for (const mode of ['Read', 'Split']) {
|
||||
await chooseView(page, mode);
|
||||
const preview = page.locator('.md-page table').first();
|
||||
await preview.waitFor();
|
||||
@@ -146,7 +146,7 @@ await runSmoke("tables/formulas", async ({ page }) => {
|
||||
assert.match(await total.innerText(), /=SUM\(D2:D3\)/);
|
||||
assert.match(await total.innerText(), /=SUM\(B2:B3\)/);
|
||||
await shot('formulas-off-split');
|
||||
await chooseView(page, 'Read beside');
|
||||
await chooseView(page, 'Split');
|
||||
await table.waitFor();
|
||||
assert.equal(await table.locator('.md-table-formula').count(), 0);
|
||||
assert.match(await cell(3, 3).innerText(), /=SUM\(D2:D3\)/);
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
// A click on a link in a table cell that took focus a moment earlier. The ProseMirror focus check runs before selectionchange, and the link source still opens at the clicked character.
|
||||
import assert from "node:assert/strict";
|
||||
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
||||
|
||||
await runSmoke("tables/linkClickAfterFocus", async ({ page }) => {
|
||||
await mockTauri(page, {
|
||||
commands: test => ({
|
||||
...test.workspace({
|
||||
root: "C:\\tab-menu-workspace",
|
||||
files: { "a.md": "| Name | Value |\n| --- | --- |\n| One | Text |\n| Two | Before [Guide](docs/guide.md) after |\n" },
|
||||
}),
|
||||
spelling_menu_install: () => null,
|
||||
}),
|
||||
});
|
||||
await page.goto(smokeUrl);
|
||||
await page.locator('[data-tree-rel="a.md"]').click();
|
||||
await page.locator('.writer-table').waitFor();
|
||||
await page.getByRole('cell', { name:'B2 · Row 2, column 2', exact:true }).click();
|
||||
await page.locator('.writer-cell-editor').waitFor();
|
||||
|
||||
// Force the order that load causes: the click moves the native selection, the focus check runs, and only then selectionchange reaches ProseMirror.
|
||||
// The focus check is the 20 ms timer in the focus handler of prosemirror-view. Its source is the only timer source that reads currentSelection.
|
||||
await page.evaluate(() => {
|
||||
const setTimeout = window.setTimeout, checks = [];
|
||||
const hold = event => event.stopImmediatePropagation();
|
||||
window.setTimeout = (run, delay, ...rest) => {
|
||||
if (delay !== 20 || !String(run).includes('currentSelection')) return setTimeout(run, delay, ...rest);
|
||||
checks.push(run);
|
||||
return 0;
|
||||
};
|
||||
document.addEventListener('selectionchange', hold, true);
|
||||
window.__runFocusCheck = () => {
|
||||
window.setTimeout = setTimeout;
|
||||
for (const check of checks) check();
|
||||
document.removeEventListener('selectionchange', hold, true);
|
||||
return checks.length;
|
||||
};
|
||||
});
|
||||
await page.keyboard.press('Enter');
|
||||
const linkCell = page.getByRole('cell', { name:'B3 · Row 3, column 2', exact:true });
|
||||
await linkCell.locator('.writer-cell-editor').waitFor();
|
||||
// Let the other timers of the new editor run. A flush after the click reads the native selection and hides the race.
|
||||
await page.waitForTimeout(100);
|
||||
const point = await linkCell.locator('a').evaluate(link => {
|
||||
const range = document.createRange();
|
||||
range.setStart(link.firstChild, 1); range.collapse(true);
|
||||
const rect = range.getBoundingClientRect();
|
||||
return { x: rect.x, y: rect.y + rect.height / 2 };
|
||||
});
|
||||
await page.mouse.click(point.x, point.y);
|
||||
assert.ok(await page.evaluate(() => window.__runFocusCheck()) > 0, 'The focus check ran after the click');
|
||||
|
||||
await page.locator('.is-source-editing .writer-cell-editor').waitFor();
|
||||
assert.equal(await linkCell.locator('.writer-link-target').innerText(), 'docs/guide.md', 'The click opens the link source');
|
||||
const caretPrefix = await page.evaluate(() => {
|
||||
const selection = getSelection(), range = document.createRange();
|
||||
range.selectNodeContents(document.querySelector('.is-source-editing .writer-cell-editor'));
|
||||
range.setEnd(selection.anchorNode, selection.anchorOffset);
|
||||
return range.toString();
|
||||
});
|
||||
assert.equal(caretPrefix, 'Before [G', 'The caret stays at the clicked label character');
|
||||
});
|
||||
@@ -59,7 +59,7 @@ await runSmoke("tabs/menus", async ({ page }) => {
|
||||
const view = async name => {
|
||||
await show("d.md");
|
||||
await item("View").click();
|
||||
await page.getByRole(name === "Read beside" ? "menuitemcheckbox" : "menuitemradio", { name, exact: true }).click();
|
||||
await page.getByRole(name === "Split" ? "menuitemcheckbox" : "menuitemradio", { name, exact: true }).click();
|
||||
};
|
||||
await show("d.md");
|
||||
await item("View").click();
|
||||
@@ -68,11 +68,11 @@ await runSmoke("tabs/menus", async ({ page }) => {
|
||||
await page.keyboard.press("Escape");
|
||||
await view("Read");
|
||||
await page.locator(".md-page").waitFor();
|
||||
await view("Read beside");
|
||||
await view("Split");
|
||||
await page.locator(".body.split .md-page").waitFor();
|
||||
await view("Source");
|
||||
await page.locator(".body.split .source-editor .cm-content").waitFor();
|
||||
await view("Read beside");
|
||||
await view("Split");
|
||||
await page.locator(".md-page").waitFor({ state: "detached" });
|
||||
await view("Write");
|
||||
await page.locator(".live-writer .cm-editor").waitFor();
|
||||
|
||||
@@ -65,9 +65,9 @@ await runSmoke("tabs/scroll", async ({ page }) => {
|
||||
await roundTrip('.cm-scroller', 'Writing');
|
||||
await chooseView(page, 'Read');
|
||||
await roundTrip('.md-page', 'Reading');
|
||||
await chooseView(page, 'Read beside');
|
||||
await chooseView(page, 'Split');
|
||||
await roundTrip('.md-page', 'Split preview');
|
||||
await chooseView(page, 'Read beside');
|
||||
await chooseView(page, 'Split');
|
||||
await chooseView(page, 'Source');
|
||||
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
|
||||
await chooseView(page, 'Source');
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { estimatedImageHeight, imageSize, rememberImageSize } from "../../../src/lib/workspace/imageSizes.ts";
|
||||
import { renderMarkdownHtml } from "../../../src/lib/workspace/noteHtml.ts";
|
||||
|
||||
test("a rendered image has size attributes only when its size is known", () => {
|
||||
const unknown = "data:image/png;base64,AAAA";
|
||||
const known = "data:image/png;base64,BBBB";
|
||||
rememberImageSize(known, 1400, 700);
|
||||
const urls = new Map([["a.png", unknown], ["b.png", known]]);
|
||||
assert.doesNotMatch(renderMarkdownHtml("", urls), /width=/);
|
||||
assert.match(renderMarkdownHtml("", urls), /width="1400" height="700"/);
|
||||
});
|
||||
|
||||
test("a large data URL keeps its size without the image data as the key", () => {
|
||||
const url = `data:image/png;base64,${"A".repeat(5000)}${"B".repeat(100)}${"C".repeat(5000)}`;
|
||||
const other = `data:image/png;base64,${"A".repeat(5000)}${"D".repeat(100)}${"C".repeat(5000)}`;
|
||||
rememberImageSize(url, 10, 20);
|
||||
assert.deepEqual(imageSize(url), { width: 10, height: 20 });
|
||||
assert.equal(imageSize(other), undefined);
|
||||
});
|
||||
|
||||
test("an image without a real size stays unknown", () => {
|
||||
rememberImageSize("data:image/svg+xml;base64,AAAA", 0, 0);
|
||||
assert.equal(imageSize("data:image/svg+xml;base64,AAAA"), undefined);
|
||||
});
|
||||
|
||||
test("the estimate scales a wide image to the text column and keeps a small image", () => {
|
||||
assert.equal(estimatedImageHeight('<img src="x" alt="">'), -1);
|
||||
assert.equal(estimatedImageHeight('<img width="1480" height="740">'), 370 + 45);
|
||||
assert.equal(estimatedImageHeight('<img width="100" height="50">'), 50 + 45);
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
|
||||
import { identifyPdf } from "../../../src/lib/features/pdfDocument.ts";
|
||||
import { PAGE_GAP, PAGE_MARGIN, fitZoom, mostVisiblePage, nextRotation, outputScale, pageBoxes, pageNumber, pagesInRange, zoomFromText, zoomLevel } from "../../../src/lib/features/pdf/model.ts";
|
||||
import { nextRotation, outputScale, pageNumber, zoomLevel } from "../../../src/lib/features/pdf/model.ts";
|
||||
import { FeatureSession } from "../../../src/lib/features/session.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../../../src/lib/features/types.ts";
|
||||
import type { PluginDocumentContext } from "../../../src/lib/plugins/sdk.ts";
|
||||
@@ -26,38 +26,6 @@ test("page and zoom inputs stay within supported bounds", () => {
|
||||
assert.deepEqual([0, 90, 180, 270].map(nextRotation), [90, 180, 270, 0]);
|
||||
});
|
||||
|
||||
test("a typed zoom is a percent within the limits", () => {
|
||||
assert.equal(zoomFromText("137"), 1.37);
|
||||
assert.equal(zoomFromText(" 150 % "), 1.5);
|
||||
assert.equal(zoomFromText("112,5"), 1.125);
|
||||
assert.equal(zoomFromText("9000"), 4);
|
||||
assert.equal(zoomFromText("1"), .25);
|
||||
for (const text of ["", " ", "text", "-50", "0", "1e999"]) assert.equal(zoomFromText(text), null);
|
||||
});
|
||||
|
||||
test("the pages are one column, and the scroll position gives the current page", () => {
|
||||
const sizes = [{ width: 600, height: 800 }, { width: 800, height: 600 }, { width: 600, height: 800 }];
|
||||
const boxes = pageBoxes(sizes, .5, 0);
|
||||
assert.deepEqual(boxes, [
|
||||
{ top: PAGE_MARGIN, width: 300, height: 400 },
|
||||
{ top: PAGE_MARGIN + 400 + PAGE_GAP, width: 400, height: 300 },
|
||||
{ top: PAGE_MARGIN + 700 + 2 * PAGE_GAP, width: 300, height: 400 },
|
||||
]);
|
||||
assert.deepEqual(pageBoxes(sizes, 1, 90).map(box => [box.width, box.height]), [[800, 600], [600, 800], [800, 600]]);
|
||||
assert.equal(fitZoom(sizes, 0, 400), .5);
|
||||
assert.equal(fitZoom(sizes, 90, 400), .5);
|
||||
assert.equal(fitZoom([{ width: 600, height: 900 }], 90, 450), .5);
|
||||
assert.equal(fitZoom([], 0, 400), 1);
|
||||
assert.deepEqual(pagesInRange(boxes, 0, 100), [1]);
|
||||
assert.deepEqual(pagesInRange(boxes, 400, 800), [1, 2, 3]);
|
||||
assert.deepEqual(pagesInRange(boxes, 5000, 6000), []);
|
||||
assert.equal(mostVisiblePage(boxes, 0, 300), 1);
|
||||
assert.equal(mostVisiblePage(boxes, 300, 600), 2);
|
||||
assert.equal(mostVisiblePage(boxes, 900, 1200), 3);
|
||||
assert.equal(mostVisiblePage(boxes, 0, 2000), 1, "The first page wins when several pages show in full");
|
||||
assert.equal(mostVisiblePage([], 0, 100), 1);
|
||||
});
|
||||
|
||||
test("large PDF pages respect canvas dimension and memory limits", () => {
|
||||
for (const [width, height] of [[612, 792], [20000, 500], [20000, 20000]]) {
|
||||
const scale = outputScale(width, height, 3);
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
// The image data of description drafts: an image in an unsaved description survives a close, and a discard leaves no image data.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { DescriptionDraft } from "../../../../src/lib/features/pm/storage/description-draft.ts";
|
||||
import { imageMarkdown, imagePath, saveImages } from "../../../../src/lib/features/pm/storage/images.ts";
|
||||
import { privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
|
||||
import { memoryWorkspace } from "./_memory.ts";
|
||||
|
||||
const one = "12345678-1234-1234-1234-123456789abc";
|
||||
const two = "87654321-1234-1234-1234-123456789abc";
|
||||
const data = "data:image/png;base64,aGVsbG8=";
|
||||
const other = "data:image/gif;base64,R0lGOD==";
|
||||
|
||||
/** A workspace that records the path of each write and creation, in order. */
|
||||
function recorded() {
|
||||
const workspace = memoryWorkspace({ [privateRulesPath]: "*\n" });
|
||||
const writes: string[] = [];
|
||||
const { write, create } = workspace;
|
||||
workspace.write = async (path, contents, expected) => { await write(path, contents, expected); writes.push(path); };
|
||||
workspace.create = async (path, contents) => { await create!(path, contents); writes.push(path); };
|
||||
return { workspace, writes };
|
||||
}
|
||||
|
||||
test("a draft from an earlier version, without an image record, still loads", async () => {
|
||||
const { workspace } = recorded();
|
||||
const draft = new DescriptionDraft(workspace, "task");
|
||||
workspace.files.set(draft.path, JSON.stringify({ schema: 1, body: `Old ${imageMarkdown("a.png", one)}` }) + "\n");
|
||||
const reopened = new DescriptionDraft(workspace, "task");
|
||||
assert.equal(await reopened.load(), `Old ${imageMarkdown("a.png", one)}`);
|
||||
assert.deepEqual(await reopened.loadImages(), new Map());
|
||||
await reopened.save("Newer text");
|
||||
assert.equal(workspace.files.has(reopened.imagesPath), false, "A draft without images makes no image record");
|
||||
});
|
||||
|
||||
test("the draft keeps the data of its unsaved images, and the image folder stays empty", async () => {
|
||||
const { workspace, writes } = recorded();
|
||||
const draft = new DescriptionDraft(workspace, "task");
|
||||
await draft.loadImages();
|
||||
const body = `Text\n${imageMarkdown("a.png", one)}`;
|
||||
await draft.save(body, new Map([[one, data]]));
|
||||
assert.deepEqual(writes, [draft.imagesPath, draft.path], "The image data comes before the reference");
|
||||
assert.equal([...workspace.files.keys()].some(path => path.startsWith(".runestone/pm/images/")), false);
|
||||
|
||||
// A text change does not write the image data again.
|
||||
await draft.save(`${body}\nMore`, new Map([[one, data]]));
|
||||
assert.deepEqual(writes, [draft.imagesPath, draft.path, draft.path]);
|
||||
|
||||
const reopened = new DescriptionDraft(workspace, "task");
|
||||
assert.equal(await reopened.load(), `${body}\nMore`);
|
||||
assert.deepEqual(await reopened.loadImages(), new Map([[one, data]]));
|
||||
// A later save writes the image file from the restored data.
|
||||
assert.deepEqual(await saveImages(workspace, body, await reopened.loadImages()), [one]);
|
||||
assert.match(workspace.files.get(imagePath(one))!, /data:image\/png;base64,aGVsbG8=/);
|
||||
});
|
||||
|
||||
test("a removed image keeps its data until the text without the reference is saved", async () => {
|
||||
const { workspace, writes } = recorded();
|
||||
const draft = new DescriptionDraft(workspace, "task");
|
||||
await draft.loadImages();
|
||||
await draft.save(`${imageMarkdown("a.png", one)}\n${imageMarkdown("b.gif", two)}`, new Map([[one, data], [two, other]]));
|
||||
writes.length = 0;
|
||||
await draft.save(imageMarkdown("a.png", one), new Map([[one, data]]));
|
||||
assert.deepEqual(writes, [draft.path, draft.imagesPath]);
|
||||
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[one, data]]));
|
||||
|
||||
// An image that replaces another one: the record holds both images while the text changes.
|
||||
writes.length = 0;
|
||||
await draft.save(imageMarkdown("b.gif", two), new Map([[two, other]]));
|
||||
assert.deepEqual(writes, [draft.imagesPath, draft.path, draft.imagesPath]);
|
||||
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[two, other]]));
|
||||
});
|
||||
|
||||
test("a discarded draft keeps no image data and writes no image file", async () => {
|
||||
const { workspace, writes } = recorded();
|
||||
const draft = new DescriptionDraft(workspace, "task");
|
||||
await draft.loadImages();
|
||||
await draft.save(imageMarkdown("a.png", one), new Map([[one, data]]));
|
||||
writes.length = 0;
|
||||
await draft.save(null, new Map([[one, data]]));
|
||||
assert.deepEqual(writes, [draft.path, draft.imagesPath], "The text goes first, so that no saved reference loses its data");
|
||||
assert.equal(await new DescriptionDraft(workspace, "task").load(), null);
|
||||
assert.equal(workspace.files.get(draft.imagesPath), JSON.stringify({ schema: 1, images: {} }) + "\n");
|
||||
assert.equal([...workspace.files.keys()].some(path => path.startsWith(".runestone/pm/images/")), false);
|
||||
});
|
||||
|
||||
test("an invalid image record stops the draft, and a stale writer cannot overwrite the images", async () => {
|
||||
const { workspace } = recorded();
|
||||
const draft = new DescriptionDraft(workspace, "task");
|
||||
for (const images of [null, [], { "../secret": data }, { [one]: "data:image/svg+xml;base64,PHN2Zz4=" }]) {
|
||||
workspace.files.set(draft.imagesPath, JSON.stringify({ schema: 1, images }));
|
||||
await assert.rejects(draft.loadImages(), /description draft is invalid/);
|
||||
}
|
||||
workspace.files.delete(draft.imagesPath);
|
||||
const first = new DescriptionDraft(workspace, "task"), second = new DescriptionDraft(workspace, "task");
|
||||
await first.loadImages();
|
||||
await second.loadImages();
|
||||
await first.save(imageMarkdown("a.png", one), new Map([[one, data]]));
|
||||
await assert.rejects(second.save(imageMarkdown("b.gif", two), new Map([[two, other]])), /exists/);
|
||||
assert.deepEqual(await new DescriptionDraft(workspace, "task").loadImages(), new Map([[one, data]]));
|
||||
});
|
||||
|
||||
test("an image save includes extra IDs, for example a card cover, and returns the saved IDs", async () => {
|
||||
const workspace = memoryWorkspace({ [privateRulesPath]: "*\n" });
|
||||
const pending = new Map([[one, data], [two, other]]);
|
||||
assert.deepEqual(await saveImages(workspace, "", pending, [], [two]), [two]);
|
||||
assert.equal(workspace.files.has(imagePath(one)), false);
|
||||
assert.equal(workspace.files.has(imagePath(two)), true);
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView, splitWithContent, showInActivePane, paneOf, releaseSolePlugin, dropInPane, moveToNewPane, resizeDocumentPanes } from "../../../src/lib/workspace/documentPanes.ts";
|
||||
import { paneBounds, splitDividers, splitSibling, stackLayout, setSplitRatio } from "../../../src/lib/workspace/splitLayout.ts";
|
||||
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane, splitDocumentView } from "../../../src/lib/workspace/documentPanes.ts";
|
||||
import { paneBounds } from "../../../src/lib/workspace/splitLayout.ts";
|
||||
import { registerSelection, selectedEditorText } from "../../../src/lib/editor/selection.ts";
|
||||
|
||||
test("opening a link to the right keeps its source and focuses an existing pane for duplicate targets", () => {
|
||||
@@ -71,114 +71,3 @@ test("selection readers remain available in both panes and disposal cannot clear
|
||||
assert.equal(selectedEditorText("b"), "");
|
||||
replacement();
|
||||
});
|
||||
|
||||
test("a pane shows a document or a plugin view, and each tab has at most one pane", () => {
|
||||
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b"], "a");
|
||||
const primary = state.active;
|
||||
state = splitWithContent(state, primary, { pluginKey: "browser" }, "web");
|
||||
assert.deepEqual(state.panes.map(pane => [pane.documentId, pane.pluginKey]), [["a", null], [null, "browser"]]);
|
||||
assert.equal(state.active, "web");
|
||||
assert.equal(splitWithContent(state, primary, { pluginKey: "browser" }, "again"), selectPane(state, "web"));
|
||||
// A document change does not remove the plugin pane.
|
||||
assert.equal(syncDocumentPanes(state, ["a", "b"], null), state);
|
||||
// A selected document replaces the view of the active pane. The view stays open as a tab.
|
||||
const replaced = syncDocumentPanes(state, ["a", "b"], "b");
|
||||
assert.deepEqual(replaced.panes.map(pane => [pane.documentId, pane.pluginKey]), [["a", null], ["b", null]]);
|
||||
// A plugin view replaces the document of the active pane, and a shown document selects its pane.
|
||||
state = showInActivePane(selectPane(replaced, primary), { pluginKey: "board" });
|
||||
assert.deepEqual(state.panes.map(pane => [pane.documentId, pane.pluginKey]), [[null, "board"], ["b", null]]);
|
||||
assert.equal(showInActivePane(state, { documentId: "b" }).active, "web");
|
||||
assert.equal(paneOf(state, { pluginKey: "board" })?.id, primary);
|
||||
});
|
||||
|
||||
test("a closed plugin view leaves its pane, and the last pane gives its plugin view back to the whole area", () => {
|
||||
let state = syncDocumentPanes(initialDocumentPanes(), ["a"], "a");
|
||||
state = splitWithContent(state, state.active, { pluginKey: "browser" }, "web", "down");
|
||||
assert.deepEqual(paneBounds(state.layout).web, { left: 0, top: 50, width: 100, height: 50 });
|
||||
assert.deepEqual(paneBounds(stackLayout({ direction: "right", first: "x", second: "y" })).y, { left: 0, top: 50, width: 100, height: 50 });
|
||||
const closed = syncDocumentPanes(state, ["a"], null, []);
|
||||
assert.deepEqual(closed.panes.map(pane => pane.id), ["document-main"]);
|
||||
const remaining = closeDocumentPane(state, "document-main");
|
||||
assert.equal(remaining.active, "web");
|
||||
const released = releaseSolePlugin(remaining);
|
||||
assert.equal(released.pluginKey, "browser");
|
||||
assert.deepEqual([released.state.panes[0].documentId, released.state.panes[0].pluginKey], [null, null]);
|
||||
assert.equal(releaseSolePlugin(closed).state, closed);
|
||||
});
|
||||
|
||||
test("the split sibling names the pane that a plugin view opened beside", () => {
|
||||
const tree = { direction: "right" as const, first: "a", second: { direction: "down" as const, first: "b", second: "c" } };
|
||||
assert.deepEqual(splitSibling(tree, "c"), { direction: "down", sibling: "b" });
|
||||
assert.deepEqual(splitSibling(tree, "a"), { direction: "right", sibling: "b" });
|
||||
assert.equal(splitSibling("a", "a"), null);
|
||||
});
|
||||
|
||||
test("a divider changes the ratio of its split, within limits, and the narrow layout keeps the ratio", () => {
|
||||
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b", "c"], "a");
|
||||
state = splitDocumentPane(state, state.active, "b", "right");
|
||||
state = splitWithContent(state, "right", { documentId: "c" }, "low", "down");
|
||||
const dividers = splitDividers(state.layout);
|
||||
assert.deepEqual(dividers.map(divider => [divider.path.join("/"), divider.direction, divider.ratio]), [["", "right", 0.5], ["second", "down", 0.5]]);
|
||||
state = resizeDocumentPanes(state, [], 0.3);
|
||||
state = resizeDocumentPanes(state, ["second"], 0.75);
|
||||
const bounds = paneBounds(state.layout);
|
||||
assert.equal(bounds["document-main"].width, 30);
|
||||
assert.deepEqual(bounds.right, { left: 30, top: 0, width: 70, height: 75 });
|
||||
assert.equal(bounds.low.top, 75);
|
||||
assert.equal(paneBounds(stackLayout(state.layout))["document-main"].height, 30);
|
||||
assert.equal(paneBounds(resizeDocumentPanes(state, [], 0.02).layout)["document-main"].width, 10, "A pane keeps a tenth of the split at least");
|
||||
assert.equal(setSplitRatio("only", [], 0.4), "only");
|
||||
assert.equal(resizeDocumentPanes(state, ["second", "first"], 0.4), state, "A path to a pane changes nothing");
|
||||
});
|
||||
|
||||
test("a tab drop replaces the content of a pane or opens a pane beside it, and the content leaves its old pane", () => {
|
||||
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b", "c"], "a");
|
||||
const main = state.active;
|
||||
state = splitWithContent(state, main, { pluginKey: "web" }, "right");
|
||||
// A document dropped in the browser pane replaces the browser there. The browser stays open as a tab.
|
||||
let next = dropInPane(state, { documentId: "b" }, "right", "center", "new");
|
||||
assert.deepEqual(next.panes.map(pane => [pane.documentId, pane.pluginKey]), [["a", null], ["b", null]]);
|
||||
assert.equal(next.active, "right");
|
||||
// A drop on the bottom side of a pane opens a new pane there.
|
||||
next = dropInPane(state, { documentId: "c" }, main, "down", "new");
|
||||
assert.deepEqual(paneBounds(next.layout).new, { left: 0, top: 50, width: 50, height: 50 });
|
||||
assert.equal(next.active, "new");
|
||||
// A drop on the left side of a pane opens a new pane before it.
|
||||
next = dropInPane(state, { documentId: "c" }, "right", "left", "new");
|
||||
assert.deepEqual(paneBounds(next.layout), { [main]: { left: 0, top: 0, width: 50, height: 100 }, new: { left: 50, top: 0, width: 25, height: 100 }, right: { left: 75, top: 0, width: 25, height: 100 } });
|
||||
assert.equal(next.active, "new");
|
||||
// A visible tab moves: its old pane closes.
|
||||
next = dropInPane(state, { pluginKey: "web" }, main, "down", "new");
|
||||
assert.deepEqual(next.panes.map(pane => [pane.id, pane.pluginKey]), [[main, null], ["new", "web"]]);
|
||||
assert.deepEqual(paneBounds(next.layout).new, { left: 0, top: 50, width: 100, height: 50 });
|
||||
next = dropInPane(state, { pluginKey: "web" }, main, "center", "new");
|
||||
assert.deepEqual(next.panes.map(pane => pane.pluginKey), ["web"]);
|
||||
// A drop on the pane that shows the content only makes it active.
|
||||
assert.equal(dropInPane(state, { pluginKey: "web" }, "right", "down", "new").panes.length, 2);
|
||||
assert.equal(dropInPane(state, { documentId: "a" }, "missing", "center", "new"), state);
|
||||
});
|
||||
|
||||
test("the content of a pane moves to a new pane beside it, and the pane shows other content", () => {
|
||||
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b", "c"], "a");
|
||||
const main = state.active;
|
||||
state = readDocumentPane(state, main, true);
|
||||
// The visible document moves to the right. Its pane shows the next document, in the default view.
|
||||
let next = moveToNewPane(state, main, { documentId: "b" }, { documentId: "a" }, "right", "new");
|
||||
assert.deepEqual(next.panes.map(pane => [pane.id, pane.documentId, pane.reading]), [[main, "b", false], ["new", "a", false]]);
|
||||
assert.deepEqual(paneBounds(next.layout).new, { left: 50, top: 0, width: 50, height: 100 });
|
||||
assert.equal(next.active, "new");
|
||||
// A plugin view that covers the area moves below. The pane keeps its document and its view.
|
||||
next = moveToNewPane(state, main, { documentId: "a" }, { pluginKey: "web" }, "down", "new");
|
||||
assert.deepEqual(next.panes.map(pane => [pane.documentId, pane.pluginKey, pane.reading]), [["a", null, true], [null, "web", false]]);
|
||||
assert.deepEqual(paneBounds(next.layout).new, { left: 0, top: 50, width: 100, height: 50 });
|
||||
// The visible document moves to a new pane on the left.
|
||||
next = moveToNewPane(state, main, { documentId: "b" }, { documentId: "a" }, "left", "new");
|
||||
assert.deepEqual(next.panes.map(pane => [pane.id, pane.documentId]), [[main, "b"], ["new", "a"]]);
|
||||
assert.deepEqual(paneBounds(next.layout), { new: { left: 0, top: 0, width: 50, height: 100 }, [main]: { left: 50, top: 0, width: 50, height: 100 } });
|
||||
next = moveToNewPane(state, main, { documentId: "a" }, { pluginKey: "web" }, "down", "new");
|
||||
// Content that a different pane shows cannot stay, and cannot move from this pane.
|
||||
assert.equal(moveToNewPane(next, main, { pluginKey: "web" }, { documentId: "a" }, "right", "third"), next);
|
||||
assert.equal(moveToNewPane(next, main, { documentId: "b" }, { pluginKey: "web" }, "right", "third"), next);
|
||||
assert.equal(moveToNewPane(state, "missing", { documentId: "b" }, { documentId: "a" }, "right", "new"), state);
|
||||
});
|
||||
|
||||
|
||||
@@ -10,20 +10,18 @@ test("missing and damaged layouts use defaults", () => {
|
||||
|
||||
test("invalid layout fields do not discard valid collapsed states", () => {
|
||||
for (const leftWidth of [0, -1, 159, 481, "260", null]) {
|
||||
assert.deepEqual(parseWorkbenchLayout(JSON.stringify({ leftOpen: false, rightOpen: false, leftWidth, rightWidth: 320, leftView: "unknown", backlinksOpen: "false" })), {
|
||||
assert.deepEqual(parseWorkbenchLayout(JSON.stringify({ leftOpen: false, rightOpen: false, leftWidth, rightWidth: 320, leftView: "unknown" })), {
|
||||
...DEFAULT_WORKBENCH_LAYOUT, leftOpen: false, rightOpen: false, rightWidth: 320,
|
||||
});
|
||||
}
|
||||
assert.deepEqual(parseWorkbenchLayout('{"leftOpen":"false","rightOpen":0}'), DEFAULT_WORKBENCH_LAYOUT);
|
||||
// A layout from an older version has no backlinks field. The section starts expanded.
|
||||
assert.equal(parseWorkbenchLayout('{"leftOpen":false}').backlinksOpen, true);
|
||||
});
|
||||
|
||||
test("layout survives storage round trips with hidden panels, all navigation views, and collapsed backlinks", () => {
|
||||
test("layout survives storage round trips with hidden panels and all navigation views", () => {
|
||||
const store = new Map<string, string>();
|
||||
for (const leftView of ["files", "search", "bookmarks"] as const) {
|
||||
for (const [leftWidth, backlinksOpen] of [[160, false], [321.5, true], [480, false]] as const) {
|
||||
const layout = { leftOpen: false, rightOpen: false, leftWidth, rightWidth: 400, leftView, backlinksOpen };
|
||||
for (const leftWidth of [160, 321.5, 480]) {
|
||||
const layout = { leftOpen: false, rightOpen: false, leftWidth, rightWidth: 400, leftView };
|
||||
saveWorkbenchLayout({ setItem: (key, value) => { store.set(key, value); } }, layout);
|
||||
assert.deepEqual(parseWorkbenchLayout(store.get(WORKBENCH_LAYOUT_KEY)!), layout);
|
||||
}
|
||||
|
||||
@@ -116,17 +116,3 @@ test('A failed write reaches the caller', async () => {
|
||||
handlers.set('settings_write', () => { throw 'Disk full'; });
|
||||
await assert.rejects(store.writeSection('customThemes', []), /Disk full/);
|
||||
});
|
||||
|
||||
test('The same data in a different key order is the same settings value', () => {
|
||||
const saved = { theme: 'harvest-moon', mode: 'dark', transparency: { enabled: true, amount: 18 }, targets: ['app', 'pm-all'] };
|
||||
// The host sends the keys back in alphabetical order.
|
||||
const fromHost = { mode: 'dark', targets: ['app', 'pm-all'], theme: 'harvest-moon', transparency: { amount: 18, enabled: true } };
|
||||
assert.notEqual(JSON.stringify(saved), JSON.stringify(fromHost));
|
||||
assert.ok(store.sameSettingsValue(saved, fromHost));
|
||||
assert.ok(!store.sameSettingsValue(saved, { ...fromHost, mode: 'light' }));
|
||||
assert.ok(!store.sameSettingsValue(saved, { ...fromHost, targets: ['pm-all', 'app'] }), 'The order of an array counts');
|
||||
assert.ok(!store.sameSettingsValue(saved, { ...fromHost, extra: 1 }));
|
||||
assert.ok(store.sameSettingsValue('en', 'en'));
|
||||
assert.ok(store.sameSettingsValue(null, null));
|
||||
assert.ok(!store.sameSettingsValue(null, {}));
|
||||
});
|
||||
|
||||
@@ -3,7 +3,6 @@ import { test } from 'node:test';
|
||||
import { parseCustomTheme } from '../../../src/lib/theme/customThemes.ts';
|
||||
import { SYNTAX_ROLES } from '../../../src/lib/theme/roles.ts';
|
||||
import { parseAppearance, normalizeAppearance, exportAppearanceTheme, BUILTIN_THEMES, THEMES, themeModes } from '../../../src/lib/theme/appearance.ts';
|
||||
import { sameSettingsValue } from '../../../src/lib/settings/store.ts';
|
||||
|
||||
test('Removed palettes preserve the saved mode with the default palette', () => {
|
||||
for (const theme of ['gpt', 'terminal', 'unknown', 'renamon', 'asuka-school']) {
|
||||
@@ -85,19 +84,3 @@ test('Background image references clamp the overlay and discard obsolete colors'
|
||||
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, overlay: NaN } }).newTabBackground, { imageId, overlay: 0, ...layout });
|
||||
assert.equal(normalizeAppearance({ newTabBackground: { imageId: 'invalid' } }).newTabBackground, undefined);
|
||||
});
|
||||
|
||||
test('A valid appearance from the host needs no new save, although the host sorted its keys', () => {
|
||||
// ThemeSync saves the normalized appearance only when it differs from the stored value.
|
||||
// A key-order difference made two windows save the same value to each other without end.
|
||||
const imageId = 'd10adda6-a2ec-4d73-a0a6-2cb1ed43bebc';
|
||||
const fromHost = [
|
||||
{ mode: 'dark', theme: 'harvest-moon', transparency: { amount: 18, enabled: true } },
|
||||
{ mode: 'light', newTabBackground: { imageId, overlay: 0.2, position: 'center', size: 'cover' }, theme: 'default' },
|
||||
];
|
||||
for (const stored of fromHost) {
|
||||
const normalized = normalizeAppearance(stored);
|
||||
assert.notEqual(JSON.stringify(normalized), JSON.stringify(stored), 'The fixture has a different key order');
|
||||
assert.ok(sameSettingsValue(stored, normalized), JSON.stringify(stored));
|
||||
}
|
||||
assert.ok(!sameSettingsValue({ mode: 'dark', theme: 'holo' }, normalizeAppearance({ mode: 'dark', theme: 'holo' })), 'A renamed theme still gets saved');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user