Finish Phase 0: lint, codegen, contributor docs and the two remaining spikes
Repository basics: - CONTRIBUTING.md and CODE_OF_CONDUCT.md (Contributor Covenant 2.1) - SPDX AGPL-3.0-or-later headers on all hand-written sources, checked in CI - golangci-lint (shared .golangci.yml), ESLint and Prettier, all run in CI API codegen from api/openapi.yaml (npm run generate, drift fails CI): - Go types via oapi-codegen in Server/internal/api - a contract test that the router and the spec list the same routes - Dart models via Phone-App/tool/generate_api.dart; the app uses them Spike: shared Tiptap editor in a Flutter WebView (ADR-4) - @docwell/editor-bridge builds the editor into one HTML page with a versioned JSON protocol; Phone-App hosts it with webview_flutter and a native toolbar. Integration test passes on an Android API 35 emulator. - flutter_inappwebview dropped: its Android plugin fails on AGP 9. Spike: Wails v3 desktop (ADR-11) - system tray, docwell:// deep links (page and space only) with single-instance hand-off, and the built-in updater with a required ed25519 signing key. Verified on Windows. - regenerated build assets register the scheme and drop template placeholders. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e717c1d69f
commit
ba394b8fac
193 files changed
+6425
-399
No files matched your search
@@ -0,0 +1,46 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
//
|
||||
// Checks that hand-written source files carry an SPDX license header, or adds it.
|
||||
// Usage: node .github/scripts/spdx.mjs . [--check]
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const repo = process.argv[2];
|
||||
const check = process.argv.includes("--check");
|
||||
const ID = "SPDX-License-Identifier: AGPL-3.0-or-later";
|
||||
|
||||
const files = execFileSync("git", ["ls-files", "--cached", "--others", "--exclude-standard"], {
|
||||
cwd: repo,
|
||||
encoding: "utf8",
|
||||
})
|
||||
.split("\n")
|
||||
.filter((f) => /\.(go|ts|vue|dart|js|mjs|rs|sh|css)$/.test(f))
|
||||
.filter((f) => !f.endsWith(".d.ts"))
|
||||
.filter((f) => !f.startsWith("Desktop-App/build/") && !f.startsWith("Desktop-App/frontend/bindings/"))
|
||||
.filter((f) => !f.includes("node_modules/") && !f.startsWith("Phone-App/build/"));
|
||||
|
||||
const missing = [];
|
||||
for (const f of files) {
|
||||
const path = join(repo, f);
|
||||
let src = readFileSync(path, "utf8");
|
||||
if (src.includes("SPDX-License-Identifier")) continue;
|
||||
if (/^\/\/ Code generated .* DO NOT EDIT\.$/m.test(src)) continue;
|
||||
missing.push(f);
|
||||
if (check) continue;
|
||||
const ext = f.split(".").pop();
|
||||
if (ext === "vue") src = `<!-- ${ID} -->\n${src}`;
|
||||
else if (ext === "css") src = `/* ${ID} */\n\n${src}`;
|
||||
else if (ext === "sh") {
|
||||
if (src.startsWith("#!")) {
|
||||
const nl = src.indexOf("\n");
|
||||
src = `${src.slice(0, nl + 1)}# ${ID}\n${src.slice(nl + 1)}`;
|
||||
} else src = `# ${ID}\n\n${src}`;
|
||||
} else src = `// ${ID}\n\n${src}`;
|
||||
writeFileSync(path, src);
|
||||
}
|
||||
console.log(`${check ? "missing" : "added"}: ${missing.length}`);
|
||||
if (check && missing.length) {
|
||||
console.log(missing.join("\n"));
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -22,6 +22,14 @@ jobs:
|
||||
run: |
|
||||
rustup target add wasm32-wasip1
|
||||
go generate ./internal/ycrdt
|
||||
- name: Go types are up to date
|
||||
if: matrix.module == 'Server'
|
||||
working-directory: Server
|
||||
env:
|
||||
GOWORK: "off"
|
||||
run: |
|
||||
go generate ./internal/api
|
||||
git diff --exit-code internal/api
|
||||
- name: Vet and test
|
||||
working-directory: ${{ matrix.module }}
|
||||
env:
|
||||
@@ -30,6 +38,13 @@ jobs:
|
||||
test -z "$(gofmt -l .)" || (gofmt -l . && exit 1)
|
||||
go vet ./...
|
||||
go test -race ./...
|
||||
- name: Lint
|
||||
uses: golangci/golangci-lint-action@v8
|
||||
env:
|
||||
GOWORK: "off"
|
||||
with:
|
||||
version: v2.14
|
||||
working-directory: ${{ matrix.module }}
|
||||
|
||||
frontend:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -40,6 +55,10 @@ jobs:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- name: License headers
|
||||
run: node .github/scripts/spdx.mjs . --check
|
||||
- run: npm run lint
|
||||
- run: npm run format:check
|
||||
- name: API types are up to date
|
||||
run: |
|
||||
npm run generate -w @docwell/api-client
|
||||
@@ -74,6 +93,14 @@ jobs:
|
||||
run: |
|
||||
go test ./...
|
||||
go build -o bin/ .
|
||||
- name: Lint
|
||||
if: runner.os == 'Linux'
|
||||
uses: golangci/golangci-lint-action@v8
|
||||
env:
|
||||
GOWORK: "off"
|
||||
with:
|
||||
version: v2.14
|
||||
working-directory: Desktop-App
|
||||
|
||||
mobile:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -86,6 +113,11 @@ jobs:
|
||||
with:
|
||||
channel: stable
|
||||
- run: flutter pub get
|
||||
- name: Dart models are up to date
|
||||
run: |
|
||||
dart run tool/generate_api.dart
|
||||
git diff --exit-code lib/api/generated
|
||||
- run: dart format --set-exit-if-changed lib test tool
|
||||
- run: flutter analyze
|
||||
- run: flutter test
|
||||
|
||||
|
||||
@@ -34,3 +34,8 @@ coverage.out
|
||||
# Local design kit and planning docs (not part of the build)
|
||||
/Design/
|
||||
/docs/
|
||||
|
||||
# Editor page built by Packages/editor-bridge and copied into the apps
|
||||
/Phone-App/assets/editor/*
|
||||
!/Phone-App/assets/editor/.gitkeep
|
||||
/Phone-App/android/build/
|
||||
@@ -0,0 +1,34 @@
|
||||
# golangci-lint v2, shared by every Go module (run from the module folder).
|
||||
version: "2"
|
||||
|
||||
linters:
|
||||
default: standard
|
||||
enable:
|
||||
- bodyclose
|
||||
- errorlint
|
||||
- gosec
|
||||
- misspell
|
||||
- unconvert
|
||||
settings:
|
||||
errcheck:
|
||||
exclude-functions:
|
||||
# Writing a response body fails only when the client went away.
|
||||
- (net/http.ResponseWriter).Write
|
||||
- (*encoding/json.Encoder).Encode
|
||||
- (*github.com/coder/websocket.Conn).CloseNow
|
||||
gosec:
|
||||
excludes:
|
||||
- G104 # unchecked errors: errcheck covers these, with the exclusions above
|
||||
exclusions:
|
||||
presets:
|
||||
- std-error-handling
|
||||
paths:
|
||||
# Wails project template, regenerated by the Wails CLI.
|
||||
- build/
|
||||
rules:
|
||||
- path: _test\.go
|
||||
linters: [errcheck, gosec]
|
||||
# yrs.wasm is wasm32: its pointers and lengths are 32-bit by definition.
|
||||
- path: internal/ycrdt/
|
||||
text: G115
|
||||
linters: [gosec]
|
||||
@@ -0,0 +1,17 @@
|
||||
node_modules/
|
||||
dist/
|
||||
Phone-App/
|
||||
Spikes/
|
||||
Desktop-App/build/
|
||||
Desktop-App/frontend/bindings/
|
||||
Packages/api-client/src/schema.d.ts
|
||||
*.md
|
||||
*.yaml
|
||||
*.yml
|
||||
package-lock.json
|
||||
target/
|
||||
pb_data/
|
||||
Database/
|
||||
Docker*/
|
||||
api/
|
||||
.claude/
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"printWidth": 120
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
# Code of Conduct
|
||||
|
||||
Docwell follows the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/). This page summarizes it; the linked text is the one that applies.
|
||||
|
||||
## Our pledge
|
||||
|
||||
We want taking part in Docwell to be a harassment-free experience for everyone, whatever their age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, colour, religion, or sexual identity and orientation.
|
||||
|
||||
## Expected behaviour
|
||||
|
||||
- Be kind and patient with other people.
|
||||
- Respect differing opinions, viewpoints and experiences.
|
||||
- Give constructive feedback, and accept it gracefully.
|
||||
- Take responsibility for your mistakes, apologise to the people they affected, and learn from them.
|
||||
- Focus on what is best for the community as a whole.
|
||||
|
||||
## Unacceptable behaviour
|
||||
|
||||
- Sexualized language or imagery, and sexual attention or advances of any kind.
|
||||
- Trolling, insulting or derogatory comments, and personal or political attacks.
|
||||
- Public or private harassment.
|
||||
- Publishing someone else's private information, such as a physical or email address, without their explicit permission.
|
||||
- Any other conduct that could reasonably be considered inappropriate in a professional setting.
|
||||
|
||||
## Scope
|
||||
|
||||
This applies in every project space (issues, pull requests, discussions, chat) and when someone officially represents the project in public.
|
||||
|
||||
## Reporting
|
||||
|
||||
Report unacceptable behaviour to the maintainers privately through GitHub (a direct message to a maintainer, or a private security advisory for anything sensitive). Every report is reviewed promptly and fairly, and maintainers keep the reporter's identity private.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Maintainers decide what action to take, following the Covenant's enforcement guidelines:
|
||||
|
||||
1. **Correction**: a private, written warning explaining what was inappropriate.
|
||||
2. **Warning**: a warning with consequences for continued behaviour, including no interaction with the people involved for a set time.
|
||||
3. **Temporary ban**: no interaction with the community for a set time.
|
||||
4. **Permanent ban**: no interaction with the community at all.
|
||||
|
||||
## Attribution
|
||||
|
||||
Adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1, licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
|
||||
@@ -0,0 +1,61 @@
|
||||
# Contributing to Docwell
|
||||
|
||||
Thanks for helping. This page covers how to set up the repository, the checks a change has to pass, and how to send it.
|
||||
|
||||
By taking part you agree to follow the [Code of Conduct](CODE_OF_CONDUCT.md).
|
||||
|
||||
## Before you start
|
||||
|
||||
- For anything bigger than a small fix, open an issue first so we can agree on the approach.
|
||||
- Feature priorities (MVP, v1, v2) are fixed per phase. Work outside the current phase is unlikely to be merged yet.
|
||||
- Report security problems privately to the maintainers, not in a public issue.
|
||||
|
||||
## Setup
|
||||
|
||||
Follow **Development** in the [README](README.md): Go 1.26+, Node 22+, Rust with the `wasm32-wasip1` target, Flutter 3.44+, the Wails v3 CLI and the PocketBase binary.
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
## Checks
|
||||
|
||||
CI runs all of these. Run the ones for the parts you touched before you push.
|
||||
|
||||
| Area | Commands |
|
||||
|---|---|
|
||||
| Go (`Server/`, `Web-App/`, `Desktop-App/`) | `gofmt -l .`, `go vet ./...`, `golangci-lint run`, `go test ./...` (from each module) |
|
||||
| Frontend (`Packages/`, `Server/admin/`, `Web-App/frontend/`, `Desktop-App/frontend/`) | `npm run lint`, `npm run format:check`, `npm run typecheck`, `npm test` (from the repo root) |
|
||||
| Mobile (`Phone-App/`) | `dart format --set-exit-if-changed lib test`, `flutter analyze`, `flutter test` |
|
||||
| API contract | `npm run generate` (from the repo root) after editing `api/openapi.yaml`, and commit the regenerated files |
|
||||
| License headers | `node .github/scripts/spdx.mjs . --check` |
|
||||
|
||||
`npm run format` and `npm run lint:fix` fix most frontend problems for you.
|
||||
|
||||
## API changes
|
||||
|
||||
`api/openapi.yaml` is the source of truth for every client. Change it first, then regenerate:
|
||||
|
||||
- TypeScript types: `Packages/api-client/src/schema.d.ts`
|
||||
- Go types: `Server/internal/api/api.gen.go`
|
||||
- Dart models: `Phone-App/lib/api/generated/`
|
||||
|
||||
`npm run generate` regenerates all three. CI fails if the committed files differ from what the contract generates.
|
||||
|
||||
## Code style
|
||||
|
||||
- Match the code around your change: naming, comment density and idiom.
|
||||
- Authorization rules belong in `Server/internal/access` as pure functions with tests.
|
||||
- Every new source file starts with `SPDX-License-Identifier: AGPL-3.0-or-later` in a comment. `node .github/scripts/spdx.mjs .` adds it.
|
||||
- Comments and docs are in plain English: short sentences, and explain why rather than what.
|
||||
|
||||
## Commits and pull requests
|
||||
|
||||
- Keep each pull request to one change. Split refactors from behaviour changes.
|
||||
- Write commit subjects in the imperative ("Add page trash", not "Added page trash").
|
||||
- Describe what changed, why, and how you tested it. Include screenshots for UI changes.
|
||||
- Add or update tests for behaviour changes.
|
||||
|
||||
## License
|
||||
|
||||
Docwell is licensed under the [GNU AGPL v3.0 or later](LICENSE). By sending a contribution you agree that it is licensed under the same terms.
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
set -eu
|
||||
|
||||
: "${PB_ADMIN_EMAIL:?PB_ADMIN_EMAIL is required}"
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// Token check used by docwell-server: returns the "users" record that owns the
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// Initial Docwell schema. All record API rules stay null (superuser only): PocketBase
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// Organizations and the role hierarchy (same model as DriverVault):
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// Collaboration storage. The server talks to PocketBase over JSON only, so the
|
||||
|
||||
@@ -67,6 +67,11 @@ dev_mode:
|
||||
type: primary
|
||||
exit_policy: shutdown
|
||||
|
||||
# URL schemes the installers register with the OS (deeplink.go handles them).
|
||||
protocols:
|
||||
- scheme: docwell
|
||||
description: Docwell link
|
||||
|
||||
# File Associations
|
||||
# More information at: https://v3.wails.io/noit/done/yet
|
||||
fileAssociations:
|
||||
|
||||
@@ -1,34 +1,46 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>My Product</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>docwell-desktop.exe</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.example.docwelldesktop</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>0.1.0</string>
|
||||
<key>CFBundleGetInfoString</key>
|
||||
<string>This is a comment</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.1.0</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>icons</string>
|
||||
<key>CFBundleIconName</key>
|
||||
<string>appicon</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>12.0.0</string>
|
||||
<key>NSHighResolutionCapable</key>
|
||||
<string>true</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>© 2026, My Company</string>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsLocalNetworking</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>docwell-desktop</string>
|
||||
<key>CFBundleGetInfoString</key>
|
||||
<string>Docwell desktop app</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>icons</string>
|
||||
<key>CFBundleIconName</key>
|
||||
<string>appicon</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>app.docwell.desktop</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>Docwell</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.0.1</string>
|
||||
<key>CFBundleURLTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>wails.com.docwell</string>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>docwell</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>0.0.1</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>12.0.0</string>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsLocalNetworking</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>NSHighResolutionCapable</key>
|
||||
<string>true</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>Copyright (c) 2026 Docwell contributors</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,29 +1,41 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>My Product</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>docwell-desktop.exe</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.example.docwelldesktop</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>0.1.0</string>
|
||||
<key>CFBundleGetInfoString</key>
|
||||
<string>This is a comment</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.1.0</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>icons</string>
|
||||
<key>CFBundleIconName</key>
|
||||
<string>appicon</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>12.0.0</string>
|
||||
<key>NSHighResolutionCapable</key>
|
||||
<string>true</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>© 2026, My Company</string>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>docwell-desktop</string>
|
||||
<key>CFBundleGetInfoString</key>
|
||||
<string>Docwell desktop app</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>icons</string>
|
||||
<key>CFBundleIconName</key>
|
||||
<string>appicon</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>app.docwell.desktop</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>Docwell</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.0.1</string>
|
||||
<key>CFBundleURLTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>wails.com.docwell</string>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>docwell</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>0.0.1</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>12.0.0</string>
|
||||
<key>NSHighResolutionCapable</key>
|
||||
<string>true</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>Copyright (c) 2026 Docwell contributors</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,61 +1,56 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>docwell-desktop.exe</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.example.docwelldesktop.dev</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>My Product (Dev)</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>My Product (Dev)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.1.0-dev</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>0.1.0</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>MinimumOSVersion</key>
|
||||
<string>15.0</string>
|
||||
<key>UILaunchStoryboardName</key>
|
||||
<string>LaunchScreen</string>
|
||||
<key>UIRequiredDeviceCapabilities</key>
|
||||
<array>
|
||||
<string>arm64</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations~ipad</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsArbitraryLoads</key>
|
||||
<true/>
|
||||
<key>NSAllowsLocalNetworking</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<!-- Development mode enabled -->
|
||||
<key>WailsDevelopmentMode</key>
|
||||
<true/>
|
||||
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>© 2026, My Company</string>
|
||||
|
||||
|
||||
<key>CFBundleGetInfoString</key>
|
||||
<string>This is a comment</string>
|
||||
|
||||
</dict>
|
||||
<dict>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>Docwell (Dev)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>docwell-desktop</string>
|
||||
<key>CFBundleGetInfoString</key>
|
||||
<string>Docwell desktop app</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>app.docwell.desktop.dev</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>Docwell (Dev)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.0.1-dev</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>0.0.1</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>MinimumOSVersion</key>
|
||||
<string>15.0</string>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsArbitraryLoads</key>
|
||||
<true/>
|
||||
<key>NSAllowsLocalNetworking</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>Copyright (c) 2026 Docwell contributors</string>
|
||||
<key>UILaunchStoryboardName</key>
|
||||
<string>LaunchScreen</string>
|
||||
<key>UIRequiredDeviceCapabilities</key>
|
||||
<array>
|
||||
<string>arm64</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations~ipad</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>WailsDevelopmentMode</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,59 +1,54 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>docwell-desktop.exe</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.example.docwelldesktop</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>My Product</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>My Product</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>0.1.0</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>MinimumOSVersion</key>
|
||||
<string>15.0</string>
|
||||
<key>UILaunchStoryboardName</key>
|
||||
<string>LaunchScreen</string>
|
||||
<key>UIRequiredDeviceCapabilities</key>
|
||||
<array>
|
||||
<string>arm64</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations~ipad</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsArbitraryLoads</key>
|
||||
<false/>
|
||||
<key>NSAllowsLocalNetworking</key>
|
||||
<true/>
|
||||
</dict>
|
||||
|
||||
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>© 2026, My Company</string>
|
||||
|
||||
|
||||
<key>CFBundleGetInfoString</key>
|
||||
<string>This is a comment</string>
|
||||
|
||||
</dict>
|
||||
<dict>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>Docwell</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>docwell-desktop</string>
|
||||
<key>CFBundleGetInfoString</key>
|
||||
<string>Docwell desktop app</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>app.docwell.desktop</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>Docwell</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.0.1</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>0.0.1</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>MinimumOSVersion</key>
|
||||
<string>15.0</string>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsArbitraryLoads</key>
|
||||
<false/>
|
||||
<key>NSAllowsLocalNetworking</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>Copyright (c) 2026 Docwell contributors</string>
|
||||
<key>UILaunchStoryboardName</key>
|
||||
<string>LaunchScreen</string>
|
||||
<key>UIRequiredDeviceCapabilities</key>
|
||||
<array>
|
||||
<string>arm64</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations~ipad</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -16,14 +16,14 @@
|
||||
<rect key="frame" x="0.0" y="0.0" width="393" height="852"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<subviews>
|
||||
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="My Product" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="GJd-Yh-RWb">
|
||||
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Docwell" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="GJd-Yh-RWb">
|
||||
<rect key="frame" x="0.0" y="397" width="393" height="43"/>
|
||||
<fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
|
||||
<nil key="textColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
|
||||
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="A docwell-desktop application" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumFontSize="9" translatesAutoresizingMaskIntoConstraints="NO" id="MN2-I3-ftu">
|
||||
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Docwell desktop app" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumFontSize="9" translatesAutoresizingMaskIntoConstraints="NO" id="MN2-I3-ftu">
|
||||
<rect key="frame" x="0.0" y="448" width="393" height="21"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<nil key="textColor"/>
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- iOS development entitlements. Applied to device builds only
|
||||
(task ios:package IOS_PLATFORM=device). Add capability keys here
|
||||
(e.g. aps-environment) as your app needs them. -->
|
||||
<key>get-task-allow</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
<dict>
|
||||
<key>get-task-allow</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -13,20 +13,20 @@
|
||||
C0DEBEEF00000000000000F4 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C0DEBEEF0000000000000104 /* Security.framework */; };
|
||||
C0DEBEEF00000000000000F5 /* CoreFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C0DEBEEF0000000000000105 /* CoreFoundation.framework */; };
|
||||
C0DEBEEF00000000000000F6 /* libresolv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = C0DEBEEF0000000000000106 /* libresolv.tbd */; };
|
||||
C0DEBEEF00000000000000F7 /* My Product.a in Frameworks */ = {isa = PBXBuildFile; fileRef = C0DEBEEF0000000000000107 /* My Product.a */; };
|
||||
C0DEBEEF00000000000000F7 /* Docwell.a in Frameworks */ = {isa = PBXBuildFile; fileRef = C0DEBEEF0000000000000107 /* Docwell.a */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
C0DEBEEF0000000000000002 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
|
||||
C0DEBEEF0000000000000003 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
C0DEBEEF0000000000000004 /* My Product.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "My Product.app"; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
C0DEBEEF0000000000000004 /* Docwell.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Docwell.app"; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
C0DEBEEF0000000000000101 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
|
||||
C0DEBEEF0000000000000102 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
|
||||
C0DEBEEF0000000000000103 /* WebKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WebKit.framework; path = System/Library/Frameworks/WebKit.framework; sourceTree = SDKROOT; };
|
||||
C0DEBEEF0000000000000104 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; };
|
||||
C0DEBEEF0000000000000105 /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = System/Library/Frameworks/CoreFoundation.framework; sourceTree = SDKROOT; };
|
||||
C0DEBEEF0000000000000106 /* libresolv.tbd */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.text-based-dylib-definition; name = libresolv.tbd; path = usr/lib/libresolv.tbd; sourceTree = SDKROOT; };
|
||||
C0DEBEEF0000000000000107 /* My Product.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "My Product.a"; path = "../../../bin/My Product.a"; sourceTree = SOURCE_ROOT; };
|
||||
C0DEBEEF0000000000000107 /* Docwell.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "Docwell.a"; path = "../../../bin/Docwell.a"; sourceTree = SOURCE_ROOT; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
@@ -42,7 +42,7 @@
|
||||
C0DEBEEF0000000000000020 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C0DEBEEF0000000000000004 /* My Product.app */,
|
||||
C0DEBEEF0000000000000004 /* Docwell.app */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -65,7 +65,7 @@
|
||||
C0DEBEEF0000000000000104 /* Security.framework */,
|
||||
C0DEBEEF0000000000000105 /* CoreFoundation.framework */,
|
||||
C0DEBEEF0000000000000106 /* libresolv.tbd */,
|
||||
C0DEBEEF0000000000000107 /* My Product.a */,
|
||||
C0DEBEEF0000000000000107 /* Docwell.a */,
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
@@ -73,9 +73,9 @@
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
C0DEBEEF0000000000000040 /* My Product */ = {
|
||||
C0DEBEEF0000000000000040 /* Docwell */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = C0DEBEEF0000000000000070 /* Build configuration list for PBXNativeTarget "My Product" */;
|
||||
buildConfigurationList = C0DEBEEF0000000000000070 /* Build configuration list for PBXNativeTarget "Docwell" */;
|
||||
buildPhases = (
|
||||
C0DEBEEF0000000000000055 /* Prebuild: Wails Go Archive */,
|
||||
C0DEBEEF0000000000000050 /* Sources */,
|
||||
@@ -85,9 +85,9 @@
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = "My Product";
|
||||
productName = "My Product";
|
||||
productReference = C0DEBEEF0000000000000004 /* My Product.app */;
|
||||
name = "Docwell";
|
||||
productName = "Docwell";
|
||||
productReference = C0DEBEEF0000000000000004 /* Docwell.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
@@ -97,7 +97,7 @@
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastUpgradeCheck = 1500;
|
||||
ORGANIZATIONNAME = "My Company";
|
||||
ORGANIZATIONNAME = "Docwell contributors";
|
||||
TargetAttributes = {
|
||||
C0DEBEEF0000000000000040 = {
|
||||
CreatedOnToolsVersion = 15.0;
|
||||
@@ -116,7 +116,7 @@
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
C0DEBEEF0000000000000040 /* My Product */,
|
||||
C0DEBEEF0000000000000040 /* Docwell */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
@@ -126,7 +126,7 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C0DEBEEF00000000000000F7 /* My Product.a in Frameworks */,
|
||||
C0DEBEEF00000000000000F7 /* Docwell.a in Frameworks */,
|
||||
C0DEBEEF00000000000000F1 /* UIKit.framework in Frameworks */,
|
||||
C0DEBEEF00000000000000F2 /* Foundation.framework in Frameworks */,
|
||||
C0DEBEEF00000000000000F3 /* WebKit.framework in Frameworks */,
|
||||
@@ -155,7 +155,7 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "set -e\nAPP_ROOT=\"${PROJECT_DIR}/../../..\"\nPLATFORM=${PLATFORM_NAME:-iphonesimulator}\nSDK_PATH=${SDKROOT:-$(xcrun --sdk ${PLATFORM} --show-sdk-path)}\nif [ ${PLATFORM} = iphonesimulator ]; then GO_TARGET=arm64-apple-ios15.0-simulator; MIN_FLAG=-mios-simulator-version-min=15.0; else GO_TARGET=arm64-apple-ios15.0; MIN_FLAG=-miphoneos-version-min=15.0; fi\nexport GOOS=ios\nexport GOARCH=arm64\nexport CGO_ENABLED=1\nexport CGO_CFLAGS=\"-isysroot ${SDK_PATH} -target ${GO_TARGET} ${MIN_FLAG}\"\nexport CGO_LDFLAGS=\"-isysroot ${SDK_PATH} -target ${GO_TARGET}\"\ncd \"${APP_ROOT}\"\n# Ensure overlay exists\nif [ ! -f build/ios/xcode/overlay.json ]; then\n wails3 ios overlay:gen -out build/ios/xcode/overlay.json -config build/config.yml || true\nfi\n# Always rebuild the Go c-archive; Go's build cache keeps this fast\n# and avoids stale binaries when .go sources change.\necho \"Building Go c-archive...\"\ngo build -buildmode=c-archive -overlay build/ios/xcode/overlay.json -o \"bin/My Product.a\"\n";
|
||||
shellScript = "set -e\nAPP_ROOT=\"${PROJECT_DIR}/../../..\"\nPLATFORM=${PLATFORM_NAME:-iphonesimulator}\nSDK_PATH=${SDKROOT:-$(xcrun --sdk ${PLATFORM} --show-sdk-path)}\nif [ ${PLATFORM} = iphonesimulator ]; then GO_TARGET=arm64-apple-ios15.0-simulator; MIN_FLAG=-mios-simulator-version-min=15.0; else GO_TARGET=arm64-apple-ios15.0; MIN_FLAG=-miphoneos-version-min=15.0; fi\nexport GOOS=ios\nexport GOARCH=arm64\nexport CGO_ENABLED=1\nexport CGO_CFLAGS=\"-isysroot ${SDK_PATH} -target ${GO_TARGET} ${MIN_FLAG}\"\nexport CGO_LDFLAGS=\"-isysroot ${SDK_PATH} -target ${GO_TARGET}\"\ncd \"${APP_ROOT}\"\n# Ensure overlay exists\nif [ ! -f build/ios/xcode/overlay.json ]; then\n wails3 ios overlay:gen -out build/ios/xcode/overlay.json -config build/config.yml || true\nfi\n# Always rebuild the Go c-archive; Go's build cache keeps this fast\n# and avoids stale binaries when .go sources change.\necho \"Building Go c-archive...\"\ngo build -buildmode=c-archive -overlay build/ios/xcode/overlay.json -o \"bin/Docwell.a\"\n";
|
||||
};
|
||||
/* End PBXShellScriptBuildPhase section */
|
||||
|
||||
@@ -180,8 +180,8 @@
|
||||
"$(inherited)",
|
||||
"-ObjC",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "com.example.docwelldesktop";
|
||||
PRODUCT_NAME = "My Product";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "app.docwell.desktop";
|
||||
PRODUCT_NAME = "Docwell";
|
||||
CODE_SIGNING_ALLOWED = NO;
|
||||
SDKROOT = iphoneos;
|
||||
};
|
||||
@@ -196,8 +196,8 @@
|
||||
"$(inherited)",
|
||||
"-ObjC",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "com.example.docwelldesktop";
|
||||
PRODUCT_NAME = "My Product";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "app.docwell.desktop";
|
||||
PRODUCT_NAME = "Docwell";
|
||||
CODE_SIGNING_ALLOWED = NO;
|
||||
SDKROOT = iphoneos;
|
||||
};
|
||||
@@ -206,7 +206,7 @@
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
C0DEBEEF0000000000000070 /* Build configuration list for PBXNativeTarget "My Product" */ = {
|
||||
C0DEBEEF0000000000000070 /* Build configuration list for PBXNativeTarget "Docwell" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
C0DEBEEF0000000000000090 /* Debug */,
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
[Desktop Entry]
|
||||
Version=1.0
|
||||
Name=My Product
|
||||
Comment=A docwell-desktop application
|
||||
Name=Docwell
|
||||
Comment=Docwell desktop app
|
||||
# The Exec line includes %u to pass the URL to the application
|
||||
Exec=/usr/local/bin/docwell-desktop.exe %u
|
||||
Exec=/usr/local/bin/docwell-desktop %u
|
||||
Terminal=false
|
||||
Type=Application
|
||||
Icon=docwell-desktop.exe
|
||||
Icon=docwell-desktop
|
||||
Categories=Utility;
|
||||
StartupWMClass=docwell-desktop.exe
|
||||
StartupWMClass=docwell-desktop
|
||||
|
||||
|
||||
MimeType=x-scheme-handler/docwell;
|
||||
@@ -3,26 +3,25 @@
|
||||
#
|
||||
# The lines below are called `modelines`. See `:help modeline`
|
||||
|
||||
name: "docwell-desktop.exe"
|
||||
name: "docwell-desktop"
|
||||
arch: ${GOARCH}
|
||||
platform: "linux"
|
||||
version: "0.1.0"
|
||||
version: "0.0.1"
|
||||
section: "default"
|
||||
priority: "extra"
|
||||
maintainer: ${GIT_COMMITTER_NAME} <${GIT_COMMITTER_EMAIL}>
|
||||
description: "A docwell-desktop application"
|
||||
vendor: "My Company"
|
||||
homepage: "https://wails.io"
|
||||
license: "MIT"
|
||||
description: "Docwell desktop app"
|
||||
vendor: "Docwell contributors"
|
||||
license: "AGPL-3.0-or-later"
|
||||
release: "1"
|
||||
|
||||
contents:
|
||||
- src: "./bin/docwell-desktop.exe"
|
||||
dst: "/usr/local/bin/docwell-desktop.exe"
|
||||
- src: "./bin/docwell-desktop"
|
||||
dst: "/usr/local/bin/docwell-desktop"
|
||||
- src: "./build/appicon.png"
|
||||
dst: "/usr/share/icons/hicolor/128x128/apps/docwell-desktop.exe.png"
|
||||
- src: "./build/linux/docwell-desktop.exe.desktop"
|
||||
dst: "/usr/share/applications/docwell-desktop.exe.desktop"
|
||||
dst: "/usr/share/icons/hicolor/128x128/apps/docwell-desktop.png"
|
||||
- src: "./build/linux/docwell-desktop.desktop"
|
||||
dst: "/usr/share/applications/docwell-desktop.desktop"
|
||||
|
||||
# Default dependencies for the GTK4 + WebKitGTK 6.0 stack (Ubuntu 24.04+ / Debian 13+)
|
||||
depends:
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
{
|
||||
"fixed": {
|
||||
"file_version": "0.1.0"
|
||||
"file_version": "0.0.1"
|
||||
},
|
||||
"info": {
|
||||
"0000": {
|
||||
"ProductVersion": "0.1.0",
|
||||
"CompanyName": "My Company",
|
||||
"FileDescription": "A docwell-desktop application",
|
||||
"LegalCopyright": "© 2026, My Company",
|
||||
"ProductName": "My Product",
|
||||
"Comments": "This is a comment"
|
||||
"0409": {
|
||||
"ProductVersion": "0.0.1",
|
||||
"CompanyName": "Docwell contributors",
|
||||
"FileDescription": "Docwell desktop app",
|
||||
"LegalCopyright": "Copyright (c) 2026 Docwell contributors",
|
||||
"ProductName": "Docwell",
|
||||
"Comments": "Docwell desktop app"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,16 +8,16 @@
|
||||
!define INFO_PROJECTNAME "docwell-desktop"
|
||||
!endif
|
||||
!ifndef INFO_COMPANYNAME
|
||||
!define INFO_COMPANYNAME "My Company"
|
||||
!define INFO_COMPANYNAME "Docwell contributors"
|
||||
!endif
|
||||
!ifndef INFO_PRODUCTNAME
|
||||
!define INFO_PRODUCTNAME "My Product"
|
||||
!define INFO_PRODUCTNAME "Docwell"
|
||||
!endif
|
||||
!ifndef INFO_PRODUCTVERSION
|
||||
!define INFO_PRODUCTVERSION "0.1.0"
|
||||
!define INFO_PRODUCTVERSION "0.0.1"
|
||||
!endif
|
||||
!ifndef INFO_COPYRIGHT
|
||||
!define INFO_COPYRIGHT "© 2026, My Company"
|
||||
!define INFO_COPYRIGHT "Copyright (c) 2026 Docwell contributors"
|
||||
!endif
|
||||
!ifndef PRODUCT_EXECUTABLE
|
||||
!define PRODUCT_EXECUTABLE "${INFO_PROJECTNAME}.exe"
|
||||
@@ -253,9 +253,13 @@ RequestExecutionLevel "${REQUEST_EXECUTION_LEVEL}"
|
||||
!macro wails.associateCustomProtocols
|
||||
; Create custom protocols associations
|
||||
|
||||
!insertmacro CUSTOM_PROTOCOL_ASSOCIATE "docwell" "Docwell link" "$INSTDIR\${PRODUCT_EXECUTABLE},0" "$INSTDIR\${PRODUCT_EXECUTABLE} $\"%1$\""
|
||||
|
||||
!macroend
|
||||
|
||||
!macro wails.unassociateCustomProtocols
|
||||
; Delete app custom protocol associations
|
||||
|
||||
!insertmacro CUSTOM_PROTOCOL_UNASSOCIATE "docwell"
|
||||
|
||||
!macroend
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
|
||||
<assemblyIdentity type="win32" name="com.example.docwelldesktop" version="0.1.0" processorArchitecture="*"/>
|
||||
<assemblyIdentity type="win32" name="app.docwell.desktop" version="0.0.1" processorArchitecture="*"/>
|
||||
<dependency>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// deepLinkScheme is registered with the OS by the installers (build/config.yml).
|
||||
const deepLinkScheme = "docwell"
|
||||
|
||||
// openRouteEvent carries an app route (e.g. "/p/abc123") to the frontend.
|
||||
const openRouteEvent = "docwell:open-route"
|
||||
|
||||
// deepLinkRoutes are the app routes a link may open: a page or a space.
|
||||
var deepLinkRoutes = []string{"p", "s"}
|
||||
|
||||
var recordID = regexp.MustCompile(`^[A-Za-z0-9]{1,32}$`)
|
||||
|
||||
// routeFromDeepLink turns docwell://p/<id> into the app route /p/<id>.
|
||||
// Anything else is refused: links come from other apps and web pages, so
|
||||
// they may only navigate, never change settings such as the server address.
|
||||
func routeFromDeepLink(raw string) (string, error) {
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || !strings.EqualFold(u.Scheme, deepLinkScheme) {
|
||||
return "", errors.New("not a docwell:// link")
|
||||
}
|
||||
if u.Host == "" && strings.Trim(u.Path, "/") == "" {
|
||||
return "/", nil
|
||||
}
|
||||
parts := strings.Split(strings.Trim(u.Host+u.Path, "/"), "/")
|
||||
if len(parts) != 2 || !slices.Contains(deepLinkRoutes, parts[0]) || !recordID.MatchString(parts[1]) {
|
||||
return "", errors.New("unsupported docwell:// link")
|
||||
}
|
||||
return "/" + parts[0] + "/" + parts[1], nil
|
||||
}
|
||||
|
||||
// deepLinkFromArgs finds a docwell:// link among command-line arguments,
|
||||
// which is how Windows and Linux pass it to the app.
|
||||
func deepLinkFromArgs(args []string) (string, bool) {
|
||||
for _, a := range args {
|
||||
if strings.HasPrefix(strings.ToLower(a), deepLinkScheme+"://") {
|
||||
return a, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// LinkService routes docwell:// links into the app. It is bound to the
|
||||
// frontend, which asks for a link that arrived before it was listening (the
|
||||
// one the app was launched with) and then follows openRouteEvent.
|
||||
type LinkService struct {
|
||||
mu sync.Mutex
|
||||
pending string
|
||||
// emit sends a route to the frontend; set once the app exists.
|
||||
emit func(route string)
|
||||
// listening turns true when the frontend first calls TakePending.
|
||||
listening bool
|
||||
}
|
||||
|
||||
// open handles a link from the OS. Bad links are logged and ignored.
|
||||
func (s *LinkService) open(raw string) {
|
||||
route, err := routeFromDeepLink(raw)
|
||||
if err != nil {
|
||||
slog.Warn("ignoring link", "link", raw, "err", err)
|
||||
return
|
||||
}
|
||||
slog.Info("opening link", "route", route)
|
||||
s.mu.Lock()
|
||||
var emit func(string)
|
||||
if s.listening {
|
||||
emit = s.emit
|
||||
} else {
|
||||
s.pending = route
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if emit != nil {
|
||||
emit(route)
|
||||
}
|
||||
}
|
||||
|
||||
// TakePending returns the route the app was opened with, once. The frontend
|
||||
// calls it after subscribing to openRouteEvent, so later links are emitted.
|
||||
func (s *LinkService) TakePending() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.listening = s.emit != nil
|
||||
route := s.pending
|
||||
s.pending = ""
|
||||
return route
|
||||
}
|
||||
|
||||
func (s *LinkService) setEmitter(emit func(route string)) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.emit = emit
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRouteFromDeepLink(t *testing.T) {
|
||||
ok := map[string]string{
|
||||
"docwell://": "/",
|
||||
"docwell://p/abc123": "/p/abc123",
|
||||
"docwell://p/abc123/": "/p/abc123",
|
||||
"DOCWELL://s/space01": "/s/space01",
|
||||
"docwell:///p/abc123": "/p/abc123",
|
||||
" docwell://p/abc123\n ": "/p/abc123",
|
||||
}
|
||||
for in, want := range ok {
|
||||
got, err := routeFromDeepLink(in)
|
||||
if err != nil || got != want {
|
||||
t.Errorf("routeFromDeepLink(%q) = %q, %v; want %q", in, got, err, want)
|
||||
}
|
||||
}
|
||||
|
||||
bad := []string{
|
||||
"https://p/abc123",
|
||||
"docwell://settings/server",
|
||||
"docwell://p/../../etc",
|
||||
"docwell://p/abc123/extra",
|
||||
"docwell://p/",
|
||||
"docwell://p/a%2Fb",
|
||||
"docwell://p/javascript:alert(1)",
|
||||
"not a url",
|
||||
}
|
||||
for _, in := range bad {
|
||||
if got, err := routeFromDeepLink(in); err == nil {
|
||||
t.Errorf("routeFromDeepLink(%q) = %q, want an error", in, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeepLinkFromArgs(t *testing.T) {
|
||||
if got, ok := deepLinkFromArgs([]string{`C:\Docwell\docwell.exe`, "docwell://p/abc"}); !ok || got != "docwell://p/abc" {
|
||||
t.Errorf("got %q, %v", got, ok)
|
||||
}
|
||||
if _, ok := deepLinkFromArgs([]string{"docwell.exe", "--verbose"}); ok {
|
||||
t.Error("found a link where there is none")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinkServiceKeepsEarlyLinkUntilTaken(t *testing.T) {
|
||||
var s LinkService
|
||||
var sent []string
|
||||
s.setEmitter(func(r string) { sent = append(sent, r) })
|
||||
s.open("docwell://p/early")
|
||||
s.open("docwell://settings/server") // ignored
|
||||
if got := s.TakePending(); got != "/p/early" {
|
||||
t.Fatalf("pending = %q", got)
|
||||
}
|
||||
if got := s.TakePending(); got != "" {
|
||||
t.Fatalf("pending taken twice: %q", got)
|
||||
}
|
||||
if len(sent) != 0 {
|
||||
t.Fatalf("emitted before the frontend listened: %v", sent)
|
||||
}
|
||||
|
||||
s.open("docwell://s/space1")
|
||||
if len(sent) != 1 || sent[0] != "/s/space1" || s.TakePending() != "" {
|
||||
t.Fatalf("sent = %v", sent)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
import * as LinkService from "./linkservice.js";
|
||||
import * as SettingsService from "./settingsservice.js";
|
||||
export {
|
||||
LinkService,
|
||||
SettingsService
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
/**
|
||||
* LinkService routes docwell:// links into the app. It is bound to the
|
||||
* frontend, which asks for a link that arrived before it was listening (the
|
||||
* one the app was launched with) and then follows openRouteEvent.
|
||||
* @module
|
||||
*/
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import { Call as $Call, CancellablePromise as $CancellablePromise, Create as $Create } from "@wailsio/runtime";
|
||||
|
||||
/**
|
||||
* TakePending returns the route the app was opened with, once. The frontend
|
||||
* calls it after subscribing to openRouteEvent, so later links are emitted.
|
||||
*/
|
||||
export function TakePending(): $CancellablePromise<string> {
|
||||
return $Call.ByID(3299338673);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
// Make sure event data creation code is registered with the runtime.
|
||||
import "../github.com/wailsapp/wails/v3/internal/eventcreate.js";
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import "@docwell/web-app/style.css";
|
||||
import { createDocwellApp, type Platform } from "@docwell/web-app/app";
|
||||
import { SettingsService } from "../bindings/docwell/desktop";
|
||||
import { Events } from "@wailsio/runtime";
|
||||
import { LinkService, SettingsService } from "../bindings/docwell/desktop";
|
||||
|
||||
// The desktop app runs the same UI as Web-App; only config loading differs.
|
||||
/** Emitted by deeplink.go with an app route when the OS opens a docwell:// link. */
|
||||
const OPEN_ROUTE_EVENT = "docwell:open-route";
|
||||
|
||||
// The desktop app runs the same UI as Web-App; config loading and deep links differ.
|
||||
const desktopPlatform: Platform = {
|
||||
kind: "desktop",
|
||||
async loadConfig() {
|
||||
@@ -10,6 +16,11 @@ const desktopPlatform: Platform = {
|
||||
const ws = settings.serverUrl.replace(/^http/, "ws");
|
||||
return { apiUrl: settings.serverUrl, collabUrl: `${ws}/collab`, version: "desktop" };
|
||||
},
|
||||
onOpenRoute(open) {
|
||||
Events.On(OPEN_ROUTE_EVENT, (e) => open(String(e.data)));
|
||||
// The link the app was launched with arrived before this listener.
|
||||
void LinkService.TakePending().then((route) => route && open(route));
|
||||
},
|
||||
};
|
||||
|
||||
createDocwellApp(desktopPlatform);
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import vue from "@vitejs/plugin-vue";
|
||||
import wails from "@wailsio/runtime/plugins/vite";
|
||||
|
||||
@@ -11,5 +11,6 @@ require (
|
||||
github.com/godbus/dbus/v5 v5.2.2 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
golang.org/x/mod v0.41.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
)
|
||||
@@ -24,6 +24,8 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/wailsapp/wails/v3 v3.0.0 h1:lBe89kFu23bVz1dc1H9v0srkHQgWsy7BAKpH4sLQuDw=
|
||||
github.com/wailsapp/wails/v3 v3.0.0/go.mod h1:U3p3/QfSer2XxXM3XWhwis9O7LvvuNKN/AcGoEFD+K8=
|
||||
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
|
||||
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
|
||||
+36
-1
@@ -9,6 +9,7 @@ import (
|
||||
"log"
|
||||
|
||||
"github.com/wailsapp/wails/v3/pkg/application"
|
||||
"github.com/wailsapp/wails/v3/pkg/events"
|
||||
)
|
||||
|
||||
//go:embed all:frontend/dist
|
||||
@@ -20,11 +21,28 @@ func main() {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
links := &LinkService{}
|
||||
updates, updatesOn, err := updateConfig(updateManifestURL, updatePublicKey)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
app := application.New(application.Options{
|
||||
Name: "Docwell",
|
||||
Description: "Docwell desktop app",
|
||||
Services: []application.Service{
|
||||
application.NewService(settings),
|
||||
application.NewService(links),
|
||||
},
|
||||
// A docwell:// link starts a second process on Windows and Linux; it
|
||||
// hands the link to the running app and exits.
|
||||
SingleInstance: &application.SingleInstanceOptions{
|
||||
UniqueID: "app.docwell.desktop",
|
||||
OnSecondInstanceLaunch: func(d application.SecondInstanceData) {
|
||||
if link, ok := deepLinkFromArgs(d.Args); ok {
|
||||
links.open(link)
|
||||
}
|
||||
},
|
||||
},
|
||||
Assets: application.AssetOptions{
|
||||
Handler: application.AssetFileServerFS(assets),
|
||||
@@ -34,7 +52,7 @@ func main() {
|
||||
},
|
||||
})
|
||||
|
||||
app.Window.NewWithOptions(application.WebviewWindowOptions{
|
||||
win := app.Window.NewWithOptions(application.WebviewWindowOptions{
|
||||
Title: "Docwell",
|
||||
Width: 1280,
|
||||
Height: 800,
|
||||
@@ -49,6 +67,23 @@ func main() {
|
||||
URL: "/",
|
||||
})
|
||||
|
||||
links.setEmitter(func(route string) {
|
||||
showWindow(win)
|
||||
app.Event.Emit(openRouteEvent, route)
|
||||
})
|
||||
// The link the app was launched with (an Apple Event on macOS, an
|
||||
// argument on Windows and Linux).
|
||||
app.Event.OnApplicationEvent(events.Common.ApplicationLaunchedWithUrl, func(e *application.ApplicationEvent) {
|
||||
links.open(e.Context().URL())
|
||||
})
|
||||
|
||||
if updatesOn {
|
||||
if err := app.Updater.Init(updates); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
newTray(app, win, updatesOn)
|
||||
|
||||
if err := app.Run(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"log/slog"
|
||||
|
||||
"github.com/wailsapp/wails/v3/pkg/application"
|
||||
)
|
||||
|
||||
//go:embed build/appicon.png
|
||||
var trayIcon []byte
|
||||
|
||||
// newTray adds the system tray icon: click to bring the window back, and a
|
||||
// menu to check for updates or quit.
|
||||
func newTray(app *application.App, win *application.WebviewWindow, updates bool) *application.SystemTray {
|
||||
menu := app.NewMenu()
|
||||
menu.Add("Open Docwell").OnClick(func(*application.Context) { showWindow(win) })
|
||||
if updates {
|
||||
menu.Add("Check for updates…").OnClick(func(*application.Context) {
|
||||
go func() {
|
||||
// Shows the updater's own window when a release is found.
|
||||
if err := app.Updater.CheckAndInstall(context.Background()); err != nil {
|
||||
slog.Warn("update check failed", "err", err)
|
||||
}
|
||||
}()
|
||||
})
|
||||
}
|
||||
menu.AddSeparator()
|
||||
menu.Add("Quit Docwell").OnClick(func(*application.Context) { app.Quit() })
|
||||
|
||||
tray := app.SystemTray.New()
|
||||
tray.SetIcon(trayIcon)
|
||||
tray.SetTooltip("Docwell")
|
||||
tray.SetMenu(menu)
|
||||
tray.OnClick(func() { showWindow(win) })
|
||||
return tray
|
||||
}
|
||||
|
||||
func showWindow(win *application.WebviewWindow) {
|
||||
win.Show()
|
||||
win.UnMinimise()
|
||||
win.Focus()
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/wailsapp/wails/v3/pkg/updater"
|
||||
"github.com/wailsapp/wails/v3/pkg/updater/providers/endpoint"
|
||||
)
|
||||
|
||||
// Set by release builds, for example:
|
||||
//
|
||||
// go build -ldflags "-X main.version=0.2.0 -X main.updateManifestURL=https://… -X main.updatePublicKey=<base64>"
|
||||
//
|
||||
// Without a manifest URL (development builds) the app never updates itself.
|
||||
var (
|
||||
version = "0.0.1"
|
||||
updateManifestURL = ""
|
||||
// updatePublicKey is the base64 ed25519 key that release signatures are
|
||||
// checked against. The release feed cannot replace it.
|
||||
updatePublicKey = ""
|
||||
)
|
||||
|
||||
// updateCheckInterval is how often a running app looks for a new release.
|
||||
const updateCheckInterval = 6 * time.Hour
|
||||
|
||||
// updateConfig builds the updater settings, or returns ok=false when this
|
||||
// build has no update feed. A feed without a signing key is refused, so a
|
||||
// compromised or proxied download host cannot ship an unsigned binary.
|
||||
func updateConfig(manifestURL, publicKey string) (cfg updater.Config, ok bool, err error) {
|
||||
if manifestURL == "" {
|
||||
return cfg, false, nil
|
||||
}
|
||||
key, err := base64.StdEncoding.DecodeString(publicKey)
|
||||
if err != nil || len(key) == 0 {
|
||||
return cfg, false, errors.New("update feed is set but the signing key is missing or not base64")
|
||||
}
|
||||
// The manifest gets ?platform=windows&arch=amd64&version=… appended, so
|
||||
// one URL serves every platform.
|
||||
feed, err := endpoint.New(endpoint.Config{URL: manifestURL})
|
||||
if err != nil {
|
||||
return cfg, false, err
|
||||
}
|
||||
return updater.Config{
|
||||
CurrentVersion: version,
|
||||
Providers: []updater.Provider{feed},
|
||||
PublicKey: key,
|
||||
CheckInterval: updateCheckInterval,
|
||||
}, true, nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/wailsapp/wails/v3/pkg/updater"
|
||||
)
|
||||
|
||||
// fakeHost stands in for the Wails app; Check only emits events.
|
||||
type fakeHost struct{}
|
||||
|
||||
func (fakeHost) Emit(string, ...any) bool { return true }
|
||||
func (fakeHost) OnEvent(string, func(any)) func() { return func() {} }
|
||||
func (fakeHost) OpenWindow(updater.WindowOptions) updater.WindowHandle { return nil }
|
||||
func (fakeHost) Quit() {}
|
||||
|
||||
func TestUpdateConfigNeedsFeedAndKey(t *testing.T) {
|
||||
if _, ok, err := updateConfig("", ""); ok || err != nil {
|
||||
t.Fatalf("no feed: ok=%v err=%v, want updates off", ok, err)
|
||||
}
|
||||
if _, _, err := updateConfig("https://updates.docwell.test/desktop.json", ""); err == nil {
|
||||
t.Fatal("a feed without a signing key must be refused")
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateFeed serves a signed manifest the way a release would publish it
|
||||
// and checks the updater finds the new version for this platform.
|
||||
func TestUpdateFeed(t *testing.T) {
|
||||
pub, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
binary := []byte("docwell 9.9.9")
|
||||
digest := sha256.Sum256(binary)
|
||||
b64 := base64.StdEncoding.EncodeToString
|
||||
|
||||
var query string
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /desktop.json", func(w http.ResponseWriter, r *http.Request) {
|
||||
query = r.URL.RawQuery
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"schemaVersion": 1,
|
||||
"version": "9.9.9",
|
||||
"notes": "Faster sync",
|
||||
"artifacts": []map[string]any{{
|
||||
"url": "/docwell-9.9.9",
|
||||
"platform": runtime.GOOS,
|
||||
"arch": runtime.GOARCH,
|
||||
"size": len(binary),
|
||||
"digestAlgo": "sha256",
|
||||
"digest": b64(digest[:]),
|
||||
"signatureAlgo": "ed25519",
|
||||
"signature": b64(ed25519.Sign(priv, digest[:])),
|
||||
}},
|
||||
})
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
cfg, ok, err := updateConfig(srv.URL+"/desktop.json", b64(pub))
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("updateConfig: ok=%v err=%v", ok, err)
|
||||
}
|
||||
cfg.CheckInterval = 0
|
||||
u := updater.New(fakeHost{})
|
||||
if err := u.Init(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rel, err := u.Check(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rel == nil || rel.Version != "9.9.9" || rel.Verification == nil || len(rel.Verification.Signature) == 0 {
|
||||
t.Fatalf("release = %+v", rel)
|
||||
}
|
||||
if want := "arch=" + runtime.GOARCH; !strings.Contains(query, want) || !strings.Contains(query, "version="+version) {
|
||||
t.Errorf("manifest query %q should carry platform, arch and version", query)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
# Starts PocketBase, docwell-server and docwell-web; exits when any of them stops.
|
||||
set -eu
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ApiError, createClient, isManager } from "./index";
|
||||
|
||||
@@ -31,7 +33,10 @@ describe("createClient", () => {
|
||||
expect(err.code).toBe("validation");
|
||||
expect(err.fields).toEqual({ email: "taken" });
|
||||
|
||||
const mfa = await createClient({ baseUrl: "", fetch: vi.fn(async () => jsonResponse(401, { error: "mfa_required", mfaId: "m1" })) })
|
||||
const mfa = await createClient({
|
||||
baseUrl: "",
|
||||
fetch: vi.fn(async () => jsonResponse(401, { error: "mfa_required", mfaId: "m1" })),
|
||||
})
|
||||
.auth.login("a@b.c", "pw")
|
||||
.catch((e) => e);
|
||||
expect(mfa.mfaId).toBe("m1");
|
||||
@@ -52,7 +57,9 @@ describe("createClient", () => {
|
||||
});
|
||||
|
||||
it("sends workspace membership changes", async () => {
|
||||
const fetch = vi.fn(async () => jsonResponse(200, { user: { id: "u", email: "a@b.c", name: "A" }, role: "member" }));
|
||||
const fetch = vi.fn(async () =>
|
||||
jsonResponse(200, { user: { id: "u", email: "a@b.c", name: "A" }, role: "member" }),
|
||||
);
|
||||
await createClient({ baseUrl: "", fetch }).workspaces.setMember("w 1", "a@b.c", "member");
|
||||
const [url, init] = fetch.mock.calls[0] as unknown as [string, RequestInit];
|
||||
expect(url).toBe("/api/v1/workspaces/w%201/members");
|
||||
@@ -61,8 +68,12 @@ describe("createClient", () => {
|
||||
});
|
||||
|
||||
it("keeps the server's message", async () => {
|
||||
const fetch = vi.fn(async () => jsonResponse(409, { error: "conflict", message: "organization still has members" }));
|
||||
const err = await createClient({ baseUrl: "", fetch }).orgs.remove("o1").catch((e) => e);
|
||||
const fetch = vi.fn(async () =>
|
||||
jsonResponse(409, { error: "conflict", message: "organization still has members" }),
|
||||
);
|
||||
const err = await createClient({ baseUrl: "", fetch })
|
||||
.orgs.remove("o1")
|
||||
.catch((e) => e);
|
||||
expect(err.code).toBe("conflict");
|
||||
expect(err.serverMessage).toBe("organization still has members");
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import type { components } from "./schema";
|
||||
|
||||
type Schemas = components["schemas"];
|
||||
@@ -118,14 +120,16 @@ export function createClient(opts: ClientOptions) {
|
||||
list: (params: { page?: number; perPage?: number; q?: string; organization?: string } = {}) =>
|
||||
request<UserList>("GET", `/api/v1/users${query(params)}`),
|
||||
create: (input: CreateUserRequest) => post<User>("/api/v1/users", input),
|
||||
update: (id: string, patch: UpdateUserRequest) => request<User>("PATCH", `/api/v1/users/${encodeURIComponent(id)}`, patch),
|
||||
update: (id: string, patch: UpdateUserRequest) =>
|
||||
request<User>("PATCH", `/api/v1/users/${encodeURIComponent(id)}`, patch),
|
||||
remove: (id: string) => request<void>("DELETE", `/api/v1/users/${encodeURIComponent(id)}`),
|
||||
},
|
||||
|
||||
orgs: {
|
||||
list: () => request<Organization[]>("GET", "/api/v1/orgs"),
|
||||
create: (name: string) => post<Organization>("/api/v1/orgs", { name }),
|
||||
rename: (id: string, name: string) => request<Organization>("PATCH", `/api/v1/orgs/${encodeURIComponent(id)}`, { name }),
|
||||
rename: (id: string, name: string) =>
|
||||
request<Organization>("PATCH", `/api/v1/orgs/${encodeURIComponent(id)}`, { name }),
|
||||
remove: (id: string) => request<void>("DELETE", `/api/v1/orgs/${encodeURIComponent(id)}`),
|
||||
},
|
||||
|
||||
@@ -135,7 +139,8 @@ export function createClient(opts: ClientOptions) {
|
||||
rename: (id: string, name: string) =>
|
||||
request<Workspace>("PATCH", `/api/v1/workspaces/${encodeURIComponent(id)}`, { name }),
|
||||
remove: (id: string) => request<void>("DELETE", `/api/v1/workspaces/${encodeURIComponent(id)}`),
|
||||
members: (id: string) => request<WorkspaceMember[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/members`),
|
||||
members: (id: string) =>
|
||||
request<WorkspaceMember[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/members`),
|
||||
setMember: (id: string, email: string, role: WorkspaceRole) =>
|
||||
request<WorkspaceMember>("PUT", `/api/v1/workspaces/${encodeURIComponent(id)}/members`, { email, role }),
|
||||
removeMember: (id: string, userId: string) =>
|
||||
@@ -172,7 +177,10 @@ export function createClient(opts: ClientOptions) {
|
||||
request<PageContent>("PUT", `/api/v1/pages/${encodeURIComponent(id)}/content`, { content }),
|
||||
versions: (id: string) => request<PageVersion[]>("GET", `/api/v1/pages/${encodeURIComponent(id)}/versions`),
|
||||
version: (id: string, versionId: string) =>
|
||||
request<PageContent>("GET", `/api/v1/pages/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}`),
|
||||
request<PageContent>(
|
||||
"GET",
|
||||
`/api/v1/pages/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}`,
|
||||
),
|
||||
restoreVersion: (id: string, versionId: string) =>
|
||||
post<PageContent>(`/api/v1/pages/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}/restore`),
|
||||
move: (id: string, parent: string, index: number) =>
|
||||
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<title>Docwell editor</title>
|
||||
<script type="module" crossorigin>(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};function n(e){this.content=e}n.prototype={constructor:n,find:function(e){for(var t=0;t<this.content.length;t+=2)if(this.content[t]===e)return t;return-1},get:function(e){var t=this.find(e);return t==-1?void 0:this.content[t+1]},update:function(e,t,r){var i=r&&r!=e?this.remove(r):this,a=i.find(e),o=i.content.slice();return a==-1?o.push(r||e,t):(o[a+1]=t,r&&(o[a]=r)),new n(o)},remove:function(e){var t=this.find(e);if(t==-1)return this;var r=this.content.slice();return r.splice(t,2),new n(r)},addToStart:function(e,t){return new n([e,t].concat(this.remove(e).content))},addToEnd:function(e,t){var r=this.remove(e).content.slice();return r.push(e,t),new n(r)},addBefore:function(e,t,r){var i=this.remove(t),a=i.content.slice(),o=i.find(e);return a.splice(o==-1?a.length:o,0,t,r),new n(a)},forEach:function(e){for(var t=0;t<this.content.length;t+=2)e(this.content[t],this.content[t+1])},prepend:function(e){return e=n.from(e),e.size?new n(e.content.concat(this.subtract(e).content)):this},append:function(e){return e=n.from(e),e.size?new n(this.subtract(e).content.concat(e.content)):this},subtract:function(e){var t=this;e=n.from(e);for(var r=0;r<e.content.length;r+=2)t=t.remove(e.content[r]);return t},toObject:function(){var e={};return this.forEach(function(t,n){e[t]=n}),e},get size(){return this.content.length>>1}},n.from=function(e){if(e instanceof n)return e;var t=[];if(e)for(var r in e)t.push(r,e[r]);return new n(t)};function r(e,t,n){for(let i=0;;i++){if(i==e.childCount||i==t.childCount)return e.childCount==t.childCount?null:n;let s=e.child(i),c=t.child(i);if(s==c)n+=s.nodeSize;else{if(!s.sameMarkup(c))return n;if(s.isText&&s.text!=c.text){let e=s.text,t=c.text,r=0;for(;e[r]==t[r];r++)n++;return r&&r<e.length&&r<t.length&&o(e.charCodeAt(r-1))&&a(e.charCodeAt(r))&&n--,n}if(s.content.size||c.content.size){let e=r(s.content,c.content,n+1);if(e!=null)return e}n+=s.nodeSize}}}function i(e,t,n,r){for(let s=e.childCount,c=t.childCount;;){if(s==0||c==0)return s==c?null:{a:n,b:r};let l=e.child(--s),u=t.child(--c),d=l.nodeSize;if(l==u)n-=d,r-=d;else{if(!l.sameMarkup(u))return{a:n,b:r};if(l.isText&&l.text!=u.text){let e=l.text,t=u.text,i=e.length,s=t.length;for(;i>0&&s>0&&e[i-1]==t[s-1];)i--,s--,n--,r--;return i&&s&&i<e.length&&o(e.charCodeAt(i-1))&&a(e.charCodeAt(i))&&(n++,r++),{a:n,b:r}}if(l.content.size||u.content.size){let e=i(l.content,u.content,n-1,r-1);if(e)return e}n-=d,r-=d}}}function a(e){return e>=56320&&e<57344}function o(e){return e>=55296&&e<56320}var s=class e{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let t=0;t<e.length;t++)this.size+=e[t].nodeSize}nodesBetween(e,t,n,r=0,i){for(let a=0,o=0;o<t;a++){let s=this.content[a],c=o+s.nodeSize;if(c>e&&n(s,r+o,i||null,a)!==!1&&s.content.size){let i=o+1;s.nodesBetween(Math.max(0,e-i),Math.min(s.content.size,t-i),n,r+i)}o=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,r){let i=``,a=!0;return this.nodesBetween(e,t,(o,s)=>{let c=o.isText?o.text.slice(Math.max(e,s)-s,t-s):o.isLeaf?r?typeof r==`function`?r(o):r:o.type.spec.leafText?o.type.spec.leafText(o):``:``;o.isBlock&&(o.isLeaf&&c||o.isTextblock)&&n&&(a?a=!1:i+=n),i+=c},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,i=this.content.slice(),a=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),a=1);a<t.content.length;a++)i.push(t.content[a]);return new e(i,this.size+t.size)}cut(t,n=this.size){if(t==0&&n==this.size)return this;let r=[],i=0;if(n>t)for(let e=0,a=0;a<n;e++){let o=this.content[e],s=a+o.nodeSize;s>t&&((a<t||s>n)&&(o=o.isText?o.cut(Math.max(0,t-a),Math.min(o.text.length,n-a)):o.cut(Math.max(0,t-a-1),Math.min(o.content.size,n-a-1))),r.push(o),i+=o.nodeSize),a=s}return new e(r,i)}cutByIndex(t,n){return t==n?e.empty:t==0&&n==this.content.length?this:new e(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let i=this.content.slice(),a=this.size+n.nodeSize-r.nodeSize;return i[t]=n,new e(i,a)}addToStart(t){return new e([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new e(this.content.concat(t),this.size+t.nodeSize)}eq(Line truncated
|
||||
`)}};he.empty=new he(!0);var ge=class{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==``&&this.tokens.pop(),this.tokens[0]==``&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw SyntaxError(e+` (in content expression '`+this.string+`')`)}};function _e(e){let t=[];do t.push(ve(e));while(e.eat(`|`));return t.length==1?t[0]:{type:`choice`,exprs:t}}function ve(e){let t=[];do t.push(ye(e));while(e.next&&e.next!=`)`&&e.next!=`|`);return t.length==1?t[0]:{type:`seq`,exprs:t}}function ye(e){let t=Ce(e);for(;;)if(e.eat(`+`))t={type:`plus`,expr:t};else if(e.eat(`*`))t={type:`star`,expr:t};else if(e.eat(`?`))t={type:`opt`,expr:t};else if(e.eat(`{`))t=xe(e,t);else break;return t}function be(e){/\D/.test(e.next)&&e.err(`Expected number, got '`+e.next+`'`);let t=Number(e.next);return e.pos++,t}function xe(e,t){let n=be(e),r=n;return e.eat(`,`)&&(r=e.next==`}`?-1:be(e)),e.eat(`}`)||e.err(`Unclosed braced range`),{type:`range`,min:n,max:r,expr:t}}function Se(e,t){let n=e.nodeTypes,r=n[t];if(r)return[r];let i=[];for(let e in n){let r=n[e];r.isInGroup(t)&&i.push(r)}return i.length==0&&e.err(`No node type or group '`+t+`' found`),i}function Ce(e){if(e.eat(`(`)){let t=_e(e);return e.eat(`)`)||e.err(`Missing closing paren`),t}if(/\W/.test(e.next))e.err(`Unexpected token '`+e.next+`'`);else{let t=Se(e,e.next).map(t=>(e.inline==null?e.inline=t.isInline:e.inline!=t.isInline&&e.err(`Mixing inline and block content`),{type:`name`,value:t}));return e.pos++,t.length==1?t[0]:{type:`choice`,exprs:t}}}function we(e){let t=[[]];return i(a(e,0),n()),t;function n(){return t.push([])-1}function r(e,n,r){let i={term:r,to:n};return t[e].push(i),i}function i(e,t){e.forEach(e=>e.to=t)}function a(e,t){if(e.type==`choice`)return e.exprs.reduce((e,n)=>e.concat(a(n,t)),[]);if(e.type==`seq`)for(let r=0;;r++){let o=a(e.exprs[r],t);if(r==e.exprs.length-1)return o;i(o,t=n())}else if(e.type==`star`){let o=n();return r(t,o),i(a(e.expr,o),o),[r(o)]}else if(e.type==`plus`){let o=n();return i(a(e.expr,t),o),i(a(e.expr,o),o),[r(o)]}else if(e.type==`opt`)return[r(t)].concat(a(e.expr,t));else if(e.type==`range`){let o=t;for(let t=0;t<e.min;t++){let t=n();i(a(e.expr,o),t),o=t}if(e.max==-1)i(a(e.expr,o),o);else for(let t=e.min;t<e.max;t++){let t=n();r(o,t),i(a(e.expr,o),t),o=t}return[r(o)]}else if(e.type==`name`)return[r(t,void 0,e.value)];else throw Error(`Unknown expr type`)}}function Te(e,t){return t-e}function Ee(e,t){let n=[];return r(t),n.sort(Te);function r(t){let i=e[t];if(i.length==1&&!i[0].term)return r(i[0].to);n.push(t);for(let e=0;e<i.length;e++){let{term:t,to:a}=i[e];!t&&n.indexOf(a)==-1&&r(a)}}}function De(e){let t=Object.create(null);return n(Ee(e,0));function n(r){let i=[];r.forEach(t=>{e[t].forEach(({term:t,to:n})=>{if(!t)return;let r;for(let e=0;e<i.length;e++)i[e][0]==t&&(r=i[e][1]);Ee(e,n).forEach(e=>{r||i.push([t,r=[]]),r.indexOf(e)==-1&&r.push(e)})})});let a=t[r.join(`,`)]=new he(r.indexOf(e.length-1)>-1);for(let e=0;e<i.length;e++){let r=i[e][1].sort(Te);a.next.push({type:i[e][0],next:t[r.join(`,`)]||n(r)})}return a}}function Oe(e,t){for(let n=0,r=[e];n<r.length;n++){let e=r[n],i=!e.validEnd,a=[];for(let t=0;t<e.next.length;t++){let{type:n,next:o}=e.next[t];a.push(n.name),i&&!(n.isText||n.hasRequiredAttrs())&&(i=!1),r.indexOf(o)==-1&&r.push(o)}i&&t.err(`Only non-generatable nodes (`+a.join(`, `)+`) in a required position (see https://prosemirror.net/docs/guide/#generatable)`)}}function ke(e){let t=Object.create(null);for(let n in e){let r=e[n];if(!r.hasDefault)return null;t[n]=r.default}return t}function Ae(e,t){let n=Object.create(null);for(let r in e){let i=e[r],a=t&&t[r];if(a===void 0){if(i.hasDefault)a=i.default;else throw RangeError(`No value supplied for attribute `+r)}else i.validate&&i.validate(a);n[r]=a}return n}function je(e,t){let n=Object.create(null);if(t)for(let r in t)n[r]=new Pe(e,r,t[r]);return n}var Me=class e{constructor(e,t,n){this.name=e,this.schema=t,this.spec=n,this.markSet=null,this.groups=n.group?n.group.split(` `):[],this.attrs=je(e,n.attrs),this.defaultAttrs=ke(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(n.inline||e==`text`),this.isText=e==`text`}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==he.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(e){return this.groups.indexOf(e)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?`pre`:`normal`)}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Ae(this.attrs,e)}create(e=null,t,n){if(this.isText)throw Error(`NodeType.create can't construct text nodes`);return new de(this,this.coLine truncated
|
||||
`);else if(a.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(a.linebreakReplacement.create())){let e=n.split(/\r?\n|\r/);for(let n=0;n<e.length;n++)n&&this.insertNode(a.linebreakReplacement.create(),t,!0),e[n]&&this.insertNode(a.text(e[n]),t,!/\S/.test(e[n]));n=``}else n=n.replace(/\r?\n|\r/g,` `);n&&this.insertNode(a.text(n),t,!/\S/.test(n)),this.findInText(e)}else this.findInside(e)}addElement(e,t,n){let r=this.localPreserveWS,i=this.top;(e.tagName==`PRE`||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let a=e.nodeName.toLowerCase(),o;Ue.hasOwnProperty(a)&&this.parser.normalizeLists&&Xe(e);let s=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(o=this.parser.matchTag(e,this,n));out:if(s?s.ignore:He.hasOwnProperty(a))this.findInside(e),this.ignoreFallback(e,t);else if(!s||s.skip||s.closeParent){s&&s.closeParent?this.open=Math.max(0,this.open-1):s&&s.skip.nodeType&&(e=s.skip);let n,r=this.needsBlock;if(Ve.hasOwnProperty(a))i.content.length&&i.content[0].isInline&&this.open&&(this.open--,i=this.top),n=!0,i.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,t);break out}let o=s&&s.skip?t:this.readStyles(e,t);o&&this.addAll(e,o),n&&this.sync(i),this.needsBlock=r}else{let n=this.readStyles(e,t);n&&this.addElementByRule(e,s,n,s.consuming===!1?o:void 0)}this.localPreserveWS=r}leafFallback(e,t){e.nodeName==`BR`&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(`
|
||||
`),t)}ignoreFallback(e,t){e.nodeName!=`BR`||this.top.type&&this.top.type.inlineContent||this.findPlace(this.parser.schema.text(`-`),t,!0)}readStyles(e,t){let n=e.style;if(n&&n.length)for(let e=0;e<this.parser.matchedStyles.length;e++){let r=this.parser.matchedStyles[e],i=n.getPropertyValue(r);if(i)for(let e;;){let n=this.parser.matchStyle(r,i,this,e);if(!n)break;if(n.ignore)return null;if(t=n.clearMark?t.filter(e=>!n.clearMark(e)):t.concat(this.parser.schema.marks[n.mark].create(n.attrs)),n.consuming===!1)e=n;else break}}return t}addElementByRule(e,t,n,r){let i,a;if(t.node){if(a=this.parser.schema.nodes[t.node],a.isLeaf)this.insertNode(a.create(t.attrs),n,e.nodeName==`BR`)||this.leafFallback(e,n);else{let e=this.enter(a,t.attrs||null,n,t.preserveWhitespace);e&&(i=!0,n=e)}}else{let e=this.parser.schema.marks[t.mark];n=n.concat(e.create(t.attrs))}let o=this.top;if(a&&a.isLeaf)this.findInside(e);else if(r)this.addElement(e,n,r);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(e=>this.insertNode(e,n,!1));else{let r=e;typeof t.contentElement==`string`?r=e.querySelector(t.contentElement):typeof t.contentElement==`function`?r=t.contentElement(e):t.contentElement&&(r=t.contentElement),this.findAround(e,r,!0),this.addAll(r,n),this.findAround(e,r,!1)}i&&this.sync(o)&&this.open--}addAll(e,t,n,r){let i=n||0;for(let a=n?e.childNodes[n]:e.firstChild,o=r==null?null:e.childNodes[r];a!=o;a=a.nextSibling,++i)this.findAtPoint(e,i),this.addDOM(a,t);this.findAtPoint(e,i)}findPlace(e,t,n){let r,i;for(let t=this.open,a=0;t>=0;t--){let o=this.nodes[t],s=o.findWrapping(e);if(s&&(!r||r.length>s.length+a)&&(r=s,i=o,!s.length))break;if(o.solid){if(n)break;a+=2}}if(!r)return null;this.sync(i);for(let e=0;e<r.length;e++)t=this.enterInner(r[e],null,t,!1);return t}insertNode(e,t,n){if(e.isInline&&this.needsBlock&&!this.top.type){let e=this.textblockFromContext();e&&(t=this.enterInner(e,null,t))}let r=this.findPlace(e,t,n);if(r){this.closeExtra();let t=this.top;t.match&&=t.match.matchType(e.type);let n=d.none;for(let i of r.concat(e.marks))(t.type?t.type.allowsMarkType(i.type):$e(i.type,e.type))&&(n=i.addToSet(n));return t.content.push(e.mark(n)),!0}return!1}enter(e,t,n,r){let i=this.findPlace(e.create(t),n,!1);return i&&=this.enterInner(e,t,n,!0,r),i}enterInner(e,t,n,r=!1,i){this.closeExtra();let a=this.top;a.match=a.match&&a.match.matchType(e);let o=qe(e,i,a.options);a.options&Ke&&a.content.length==0&&(o|=Ke);let s=d.none;return n=n.filter(t=>!(a.type?a.type.allowsMarkType(t.type):$e(t.type,e))||(s=t.addToSet(s),!1)),this.nodes.push(new Je(e,t,s,r,null,o)),this.open++,n}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--)if(this.nodes[t]==e)return this.open=t,!0;else this.localPreserveWS&&(this.nodes[t].options|=We);return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let n=this.nodes[t].content;for(let t=n.length-1;t>=0;t--)e+=n[t].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==e&&this.find[n].offset==t&&(this.find[n].pos=this.currentPos)}findInside(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].pos==null&&e.nodeType==1&&e.contains(this.find[t].node)&&(this.find[t].pos=this.currentPos)}findAround(e,t,n){if(e!=t&&this.find)for(let r=0;r<this.find.length;r++)this.find[r].pos==null&&e.nodeType==1&&e.contains(this.find[r].node)&&t.compareDocumentPosition(this.find[r].node)&(n?2:4)&&(this.find[r].pos=this.currentPos)}findInText(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].node==e&&(this.find[t].pos=this.currentPos-(e.nodeValue.length-this.find[t].offset))}matchesContext(e){if(e.indexOf(`|`)>-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split(`/`),n=this.options.context,r=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),i=-(n?n.depth+1:0)+ +!r,a=(e,o)=>{for(;e>=0;e--){let s=t[e];if(s==``){if(e==t.length-1||e==0)continue;for(;o>=i;o--)if(a(e-1,o))return!0;return!1}{let e=o>0||o==0&&r?this.nodes[o].type:n&&o>=i?n.node(o-i).type:null;if(!e||e.name!=s&&!e.isInGroup(s))return!1;o--}}return!0};return a(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let n=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let e in this.parser.schema.nodes){let t=this.parser.schema.nodes[e];if(t.isTextblock&&t.defaultAttrs)return t}}};function Xe(e){for(let t=e.firstChild,n=null;t;t=t.nextSibling){let e=t.nodeType==1?t.nodeName.toLowerCase():null;e&&Ue.hasOwnProperty(e)&&n?(n.appendChild(t),t=n):e==`li`?n=t:e&&(n=null)}}function Ze(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatcheLine truncated
|
||||
`))}})}function Gt(e,t,n){let r=e.resolve(t),i=r.index();return r.parent.canReplaceWith(i,i+1,n)}function Kt(e,t,n,r,i){let a=e.doc.nodeAt(t);if(!a)throw RangeError(`No node at given position`);n||=a.type;let o=n.create(r,null,i||a.marks);if(a.isLeaf)return e.replaceWith(t,t+a.nodeSize,o);if(!n.validContent(a.content))throw RangeError(`Invalid content for node type `+n.name);e.step(new kt(t,t+a.nodeSize,t+1,t+a.nodeSize-1,new p(s.from(o),0,0),1,!0))}function qt(e,t,n=1,r){let i=e.resolve(t),a=i.depth-n,o=r&&r[r.length-1]||i.parent;if(a<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let e=i.depth-1,t=n-2;e>a;e--,t--){let n=i.node(e),a=i.index(e);if(n.type.spec.isolating)return!1;let o=n.content.cutByIndex(a,n.childCount),s=r&&r[t+1];s&&(o=o.replaceChild(0,s.type.create(s.attrs)));let c=r&&r[t]||n;if(!n.canReplace(a+1,n.childCount)||!c.type.validContent(o))return!1}let s=i.indexAfter(a),c=r&&r[0];return i.node(a).canReplaceWith(s,s,c?c.type:i.node(a+1).type)}function Jt(e,t,n=1,r){let i=e.doc.resolve(t),a=s.empty,o=s.empty;for(let e=i.depth,t=i.depth-n,c=n-1;e>t;e--,c--){a=s.from(i.node(e).copy(a));let t=r&&r[c];o=s.from(t?t.type.create(t.attrs,o):i.node(e).copy(o))}e.step(new Ot(t,t,new p(a.append(o),n,n),!0))}function Yt(e,t){let n=e.resolve(t),r=n.index();return Zt(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function Xt(e,t){t.content.size||e.type.compatibleContent(t.type);let n=e.contentMatchAt(e.childCount),{linebreakReplacement:r}=e.type.schema;for(let i=0;i<t.childCount;i++){let a=t.child(i),o=a.type==r?e.type.schema.nodes.text:a.type;if(n=n.matchType(o),!n||!e.type.allowsMarks(a.marks))return!1}return n.validEnd}function Zt(e,t){return!!(e&&t&&!e.isLeaf&&Xt(e,t))}function Qt(e,t,n=-1){let r=e.resolve(t);for(let e=r.depth;;e--){let i,a,o=r.index(e);if(e==r.depth?(i=r.nodeBefore,a=r.nodeAfter):n>0?(i=r.node(e+1),o++,a=r.node(e).maybeChild(o)):(i=r.node(e).maybeChild(o-1),a=r.node(e+1)),i&&!i.isTextblock&&Zt(i,a)&&r.node(e).canReplace(o,o+1))return t;if(e==0)break;t=n<0?r.before(e):r.after(e)}}function $t(e,t,n){let r=null,{linebreakReplacement:i}=e.doc.type.schema,a=e.doc.resolve(t-n),o=a.node().type;if(i&&o.inlineContent){let e=o.whitespace==`pre`,t=!!o.contentMatch.matchType(i);e&&!t?r=!1:!e&&t&&(r=!0)}let s=e.steps.length;if(r===!1){let r=e.doc.resolve(t+n);Wt(e,r.node(),r.before(),s)}o.inlineContent&&Nt(e,t+n-1,o,a.node().contentMatchAt(a.index()),r==null);let c=e.mapping.slice(s),l=c.map(t-n);if(e.step(new Ot(l,c.map(t+n,-1),p.empty,!0)),r===!0){let t=e.doc.resolve(l);Ut(e,t.node(),t.before(),e.steps.length)}return e}function en(e,t,n){let r=e.resolve(t);if(r.parent.canReplaceWith(r.index(),r.index(),n))return t;if(r.parentOffset==0)for(let e=r.depth-1;e>=0;e--){let t=r.index(e);if(r.node(e).canReplaceWith(t,t,n))return r.before(e+1);if(t>0)return null}if(r.parentOffset==r.parent.content.size)for(let e=r.depth-1;e>=0;e--){let t=r.indexAfter(e);if(r.node(e).canReplaceWith(t,t,n))return r.after(e+1);if(t<r.node(e).childCount)return null}return null}function tn(e,t,n){let r=e.resolve(t);if(!n.content.size)return t;let i=n.content;for(let e=0;e<n.openStart;e++)i=i.firstChild.content;for(let e=1;e<=(n.openStart==0&&n.size?2:1);e++)for(let t=r.depth;t>=0;t--){let n=t==r.depth?0:r.pos<=(r.start(t+1)+r.end(t+1))/2?-1:1,a=r.index(t)+ +(n>0),o=r.node(t),s=!1;if(e==1)s=o.canReplace(a,a,i);else{let e=o.contentMatchAt(a).findWrapping(i.firstChild.type);s=e&&o.canReplaceWith(a,a,e[0])}if(s)return n==0?r.pos:n<0?r.before(t+1):r.after(t+1)}return null}function nn(e,t,n=t,r=p.empty){if(t==n&&!r.size)return null;let i=e.resolve(t),a=e.resolve(n);return rn(i,a,r)?new Ot(t,n,r):new an(i,a,r).fit()}function rn(e,t,n){return!n.openStart&&!n.openEnd&&e.start()==t.start()&&e.parent.canReplace(e.index(),t.index(),n.content)}var an=class{constructor(e,t,n){this.$from=e,this.$to=t,this.unplaced=n,this.frontier=[],this.placed=s.empty;for(let t=0;t<=e.depth;t++){let n=e.node(t);this.frontier.push({type:n.type,match:n.contentMatchAt(e.indexAfter(t))})}for(let t=e.depth;t>0;t--)this.placed=s.from(e.node(t).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let e=this.findFittable();e?this.placeNodes(e):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,n=this.$from,r=this.close(e<0?this.$to:n.doc.resolve(e));if(!r)return null;let i=this.placed,a=n.depth,o=r.depth;for(;a&&o&&i.childCount==1;)i=i.firstChild.content,a--,o--;let s=new p(i,a,o);return e>-1?new kt(n.pos,e,this.$to.pos,this.$to.end(),s,t):s.size||n.pos!=this.$to.pos?new Ot(n.pos,r.pos,s):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,n=0,r=this.unplaced.openEnd;n<e;n++){let i=t.firstChild;if(t.childCount>1&&(r=0),i.type.spec.isolating&&r<=n){e=n;break}t=i.content}for(let t=1;t<=2;t++)for(let n=t=Line truncated
|
||||
`).scrollIntoView()),!0)};function cr(e){for(let t=0;t<e.edgeCount;t++){let{type:n}=e.edge(t);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}var lr=(e,t)=>{let{$head:n,$anchor:r}=e.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),a=n.indexAfter(-1),o=cr(i.contentMatchAt(a));if(!o||!i.canReplaceWith(a,a,o))return!1;if(t){let r=n.after(),i=e.tr.replaceWith(r,r,o.createAndFill());i.setSelection(S.near(i.doc.resolve(r),1)),t(i.scrollIntoView())}return!0},ur=(e,t)=>{let n=e.selection,{$from:r,$to:i}=n;if(n instanceof kn||r.parent.inlineContent||i.parent.inlineContent)return!1;let a=cr(i.parent.contentMatchAt(i.indexAfter()));if(!a||!a.isTextblock)return!1;if(t){let n=(!r.parentOffset&&i.index()<i.parent.childCount?r:i).pos,o=e.tr.insert(n,a.createAndFill());o.setSelection(C.create(o.doc,n+1)),t(o.scrollIntoView())}return!0},dr=(e,t)=>{let{$cursor:n}=e.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let r=n.before();if(qt(e.doc,r))return t&&t(e.tr.split(r).scrollIntoView()),!0}let r=n.blockRange(),i=r&&Ft(r);return i!=null&&(t&&t(e.tr.lift(r,i).scrollIntoView()),!0)};function fr(e){return(t,n)=>{if(t.selection instanceof w&&t.selection.node.isBlock){let{$from:e}=t.selection;return!e.parentOffset||!qt(t.doc,e.pos)?!1:(n&&n(t.tr.split(e.pos).scrollIntoView()),!0)}if(!t.selection.$from.depth)return!1;let r=t.tr;!t.selection.empty&&(t.selection instanceof C||t.selection instanceof kn)&&r.deleteSelection();let{$from:i}=r.selection,a=r.steps.length,o=[],s,c,l=!1,u=!1;for(let t=i.depth;;t--)if(i.node(t).isBlock){l=i.end(t)==i.pos+(i.depth-t),u=i.start(t)==i.pos-(i.depth-t),c=cr(i.node(t-1).contentMatchAt(i.indexAfter(t-1)));let n=e&&e(i.parent,l,i);o.unshift(n||(l&&c?{type:c}:null)),s=t;break}else{if(t==1)return!1;o.unshift(null)}let d=i.pos,f=qt(r.doc,d,o.length,o);if(f||=(o[0]=c?{type:c}:null,qt(r.doc,d,o.length,o)),!f)return!1;if(r.split(d,o.length,o),!l&&u&&i.node(s).type!=c){let e=r.mapping.slice(a),t=e.map(i.before(s)),n=r.doc.resolve(t);c&&i.node(s-1).canReplaceWith(n.index(),n.index()+1,c)&&r.setNodeMarkup(e.map(i.before(s)),c)}return n&&n(r.scrollIntoView()),!0}}var pr=fr(),mr=(e,t)=>{let{$from:n,to:r}=e.selection,i,a=n.sharedDepth(r);return a!=0&&(i=n.before(a),t&&t(e.tr.setSelection(w.create(e.doc,i))),!0)},hr=(e,t)=>(t&&t(e.tr.setSelection(new kn(e.doc))),!0);function gr(e,t,n){let r=t.nodeBefore,i=t.nodeAfter,a=t.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&t.parent.canReplace(a-1,a)?(n&&n(e.tr.delete(t.pos-r.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(a,a+1)||!(i.isTextblock||Yt(e.doc,t.pos))?!1:(n&&n(e.tr.join(t.pos).scrollIntoView()),!0)}function _r(e,t,n,r){let i=t.nodeBefore,a=t.nodeAfter,o,c,l=i.type.spec.isolating||a.type.spec.isolating;if(!l&&gr(e,t,n))return!0;let u=!l&&t.parent.canReplace(t.index(),t.index()+1);if(u&&(o=(c=i.contentMatchAt(i.childCount)).findWrapping(a.type))&&c.matchType(o[0]||a.type).validEnd){if(n){let r=t.pos+a.nodeSize,c=s.empty;for(let e=o.length-1;e>=0;e--)c=s.from(o[e].create(null,c));c=s.from(i.copy(c));let l=e.tr.step(new kt(t.pos-1,r,t.pos,r,new p(c,1,0),o.length,!0)),u=l.doc.resolve(r+2*o.length);u.nodeAfter&&u.nodeAfter.type==i.type&&Yt(l.doc,u.pos)&&l.join(u.pos),n(l.scrollIntoView())}return!0}let d=a.type.spec.isolating||r>0&&l?null:S.findFrom(t,1),f=d&&d.$from.blockRange(d.$to),m=f&&Ft(f);if(m!=null&&m>=t.depth)return n&&n(e.tr.lift(f,m).scrollIntoView()),!0;if(u&&Zn(a,`start`,!0)&&Zn(i,`end`)){let r=i,o=[];for(;o.push(r),!r.isTextblock;)r=r.lastChild;let c=a,l=1;for(;!c.isTextblock;c=c.firstChild)l++;if(r.canReplace(r.childCount,r.childCount,c.content)){if(n){let r=s.empty;for(let e=o.length-1;e>=0;e--)r=s.from(o[e].copy(r));n(e.tr.step(new kt(t.pos-o.length,t.pos+a.nodeSize,t.pos+l,t.pos+a.nodeSize-l,new p(r,o.length,0),0,!0)).scrollIntoView())}return!0}}return!1}function vr(e){return function(t,n){let r=t.selection,i=e<0?r.$from:r.$to,a=i.depth;for(;i.node(a).isInline;){if(!a)return!1;a--}return i.node(a).isTextblock?(n&&n(t.tr.setSelection(C.create(t.doc,e<0?i.start(a):i.end(a)))),!0):!1}}var yr=vr(-1),br=vr(1);function xr(e,t=null){return function(n,r){let{$from:i,$to:a}=n.selection,o=i.blockRange(a),s=o&&Lt(o,e,t);return s?(r&&r(n.tr.wrap(o,s).scrollIntoView()),!0):!1}}function Sr(e,t=null){return function(n,r){let i=!1;for(let r=0;r<n.selection.ranges.length&&!i;r++){let{$from:{pos:a},$to:{pos:o}}=n.selection.ranges[r];n.doc.nodesBetween(a,o,(r,a)=>{if(i)return!1;if(r.isTextblock&&!r.hasMarkup(e,t)){if(r.type==e)i=!0;else{let t=n.doc.resolve(a),r=t.index();i=t.parent.canReplaceWith(r,r+1,e)}}})}if(!i)return!1;if(r){let i=n.tr;for(let r=0;r<n.selection.ranges.length;r++){let{$from:{pos:a},$to:{pos:o}}=n.selection.ranges[r];i.setBlockType(a,o,e,t)}r(i.scrollIntoView())}return!0}}function Cr(...e){return function(t,n,r){for(let i=0;i<e.length;i++)if(e[i](t,n,r))return!0;return!1}}var wr=Cr(Gn,qn,Qn),Tr=Cr(Gn,tr,nr),Er={Enter:Cr(sr,urLine truncated
|
||||
`),u&&t==e.nodeValue.length)for(let t=e,n;t;t=t.parentNode){if(n=t.nextSibling){n.nodeName==`BR`&&(o=s={node:n.parentNode,offset:Ir(n)+1});break}let e=t.pmViewDesc;if(e&&e.node&&e.node.isBlock)break}}else{let n=e.childNodes[t-1];u=n&&(n.nodeName==`BR`||n.contentEditable==`false`)}}if(ci&&l.focusNode&&l.focusNode!=s.node&&D(l.focusNode)){let e=l.focusNode.childNodes[l.focusOffset];e&&e.contentEditable==`false`&&(r=!0)}if(!(r||u&&fi)&&Vr(o.node,o.offset,l.anchorNode,l.anchorOffset)&&Vr(s.node,s.offset,l.focusNode,l.focusOffset))return;let d=!1;if((c.extend||e==t)&&!(u&&ci)){c.collapse(o.node,o.offset);try{e!=t&&c.extend(s.node,s.offset),d=!0}catch{}}if(!d){if(e>t){let e=o;o=s,s=e}let n=document.createRange();n.setEnd(s.node,s.offset),n.setStart(o.node,o.offset),c.removeAllRanges(),c.addRange(n)}}ignoreMutation(e){return!this.contentDOM&&e.type!=`selection`}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let n=0,r=0;r<this.children.length;r++){let i=this.children[r],a=n+i.size;if(n==a?e<=a&&t>=n:e<a&&t>n){let r=n+i.border,o=a-i.border;if(e>=r&&t<=o){this.dirty=e==n||t==a?$i:Qi,e==r&&t==o&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=ea:i.markDirty(e-r,t-r);return}i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?$i:ea}n=a}this.dirty=$i}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let n=e==1?$i:Qi;t.dirty<n&&(t.dirty=n)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}},na=class extends ta{constructor(e,t,n,r){let i,a=t.type.toDOM;if(typeof a==`function`&&(a=a(n,()=>{if(!i)return r;if(i.parent)return i.parent.posBeforeChild(i)})),!t.type.spec.raw){let e=D(a)?a:document.createElement(`span`);e!=a&&(e.appendChild(a),a=e),e.hasAttribute(`contenteditable`)||(e.contentEditable=`false`),e.classList.add(`ProseMirror-widget`)}super(e,[],a,null),this.widget=t,this.widget=t,i=this}matchesWidget(e){return this.dirty==Zi&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!=`selection`||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}},ra=class extends ta{constructor(e,t,n,r){super(e,[],t,null),this.textDOM=n,this.text=r}get size(){return this.text.length}localPosFromDOM(e,t){return e==this.textDOM?this.posAtStart+t:this.posAtStart+(t?this.size:0)}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type===`characterData`&&e.target.nodeValue==e.oldValue}},ia=class e extends ta{constructor(e,t,n,r,i){super(e,[],n,r),this.mark=t,this.spec=i}static create(t,n,r,i){let a=i.nodeViews[n.type.name],o=a&&a(n,i,r);return o&&o.dom||(o=et.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new e(t,n,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&ea||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=ea&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=Zi){let e=this.parent;for(;!e.node;)e=e.parent;e.dirty<this.dirty&&(e.dirty=this.dirty),this.dirty=Zi}}slice(t,n,r){let i=e.create(this.parent,this.mark,!0,r),a=this.children,o=this.size;n<o&&(a=Ta(a,n,o,r)),t>0&&(a=Ta(a,0,t,r));for(let e=0;e<a.length;e++)a[e].parent=i;return i.children=a,i}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}},aa=class e extends ta{constructor(e,t,n,r,i,a,o){super(e,[],i,a),this.node=t,this.outerDeco=n,this.innerDeco=r,this.nodeDOM=o}static create(t,n,r,i,a,o){let s=a.nodeViews[n.type.name],c,l=s&&s(n,a,()=>{if(!c)return o;if(c.parent)return c.parent.posBeforeChild(c)},r,i),u=l&&l.dom,d=l&&l.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(!O(u))throw RangeError(`Text must be rendered as a DOM text node`)}else if(!u){let e=et.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs);({dom:u,contentDOM:d}=e)}!d&&!n.isText&&u.nodeName!=`BR`&&(u.hasAttribute(`contenteditable`)||(u.contentEditable=`false`),n.type.spec.draggable&&(u.draggable=!0));let f=u;return u=ga(u,r,n),l?c=new la(t,n,r,i,u,d||null,f,l):n.isText?new sa(t,n,r,i,u,f):new e(t,n,r,i,u,d||null,f)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace==`pre`&&(t.preserveWhitespace=`full`),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let e=this.children.length-1;e>=0;e--){let n=this.children[e];if(this.dom.contains(n.dom.parentNode)){t.contentElement=n.dom.parentNode;bLine truncated
|
||||
|
||||
`),slice:t}}function oo(e,t,n,r,i){let a=i.parent.type.spec.code,o,c;if(!n&&!t)return null;let l=!!t&&(r||a||!n);if(l){if(e.someProp(`transformPastedText`,n=>{t=n(t,a||r,e)}),a)return c=new p(s.from(e.state.schema.text(t.replace(/\r\n?/g,`
|
||||
`))),0,0),e.someProp(`transformPasted`,t=>{c=t(c,e,!0)}),c;let n=e.someProp(`clipboardTextParser`,n=>n(t,i,r,e));if(n)c=n;else{let n=i.marks(),{schema:r}=e.state,a=et.fromSchema(r);o=document.createElement(`div`),t.split(/(?:\r\n?|\n)+/).forEach(e=>{let t=o.appendChild(document.createElement(`p`));e&&t.appendChild(a.serializeNode(r.text(e,n)))})}}else e.someProp(`transformPastedHTML`,t=>{n=t(n,e)}),o=yo(n),_i&&bo(o);let u=o&&o.querySelector(`[data-pm-slice]`),d=u&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(u.getAttribute(`data-pm-slice`)||``);if(d&&d[3])for(let e=+d[3];e>0;e--){let e=o.firstChild;for(;e&&!D(e);)e=e.nextSibling;if(!e)break;o=e}if(c||=(e.someProp(`clipboardParser`)||e.someProp(`domParser`)||Be.fromSchema(e.state.schema)).parseSlice(o,{preserveWhitespace:!!(l||d),context:i,ruleFromNode(e){return e.nodeName==`BR`&&!e.nextSibling&&e.parentNode&&!so.test(e.parentNode.nodeName)?{ignore:!0}:null}}),d)c=xo(mo(c,+d[1],+d[2]),d[4]);else if(c=p.maxOpen(co(c.content,i),!0),c.openStart||c.openEnd){let e=0,t=0;for(let t=c.content.firstChild;e<c.openStart&&!t.type.spec.isolating;e++,t=t.firstChild);for(let e=c.content.lastChild;t<c.openEnd&&!e.type.spec.isolating;t++,e=e.lastChild);c=mo(c,e,t)}return e.someProp(`transformPasted`,t=>{c=t(c,e,l)}),c}var so=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function co(e,t){if(e.childCount<2)return e;for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.index(n)),i,a=[];if(e.forEach(e=>{if(!a)return;let t=r.findWrapping(e.type),n;if(!t)return a=null;if(n=a.length&&i.length&&uo(t,i,e,a[a.length-1],0))a[a.length-1]=n;else{a.length&&(a[a.length-1]=fo(a[a.length-1],i.length));let n=lo(e,t);a.push(n),r=r.matchType(n.type),i=t}}),a)return s.from(a)}return e}function lo(e,t,n=0){for(let r=t.length-1;r>=n;r--)e=t[r].create(null,s.from(e));return e}function uo(e,t,n,r,i){if(i<e.length&&i<t.length&&e[i]==t[i]){let a=uo(e,t,n,r.lastChild,i+1);if(a)return r.copy(r.content.replaceChild(r.childCount-1,a));if(r.contentMatchAt(r.childCount).matchType(i==e.length-1?n.type:e[i+1]))return r.copy(r.content.append(s.from(lo(n,e,i+1))))}}function fo(e,t){if(t==0)return e;let n=e.content.replaceChild(e.childCount-1,fo(e.lastChild,t-1)),r=e.contentMatchAt(e.childCount).fillBefore(s.empty,!0);return e.copy(n.append(r))}function po(e,t,n,r,i,a){let o=t<0?e.firstChild:e.lastChild,c=o.content;return e.childCount>1&&(a=0),i<r-1&&(c=po(c,t,n,r,i+1,a)),i>=n&&(c=t<0?o.contentMatchAt(0).fillBefore(c,a<=i).append(c):c.append(o.contentMatchAt(o.childCount).fillBefore(s.empty,!0))),e.replaceChild(t<0?0:e.childCount-1,o.copy(c))}function mo(e,t,n){return t<e.openStart&&(e=new p(po(e.content,-1,t,e.openStart,0,e.openEnd),t,e.openEnd)),n<e.openEnd&&(e=new p(po(e.content,1,n,e.openEnd,0,0),e.openStart,n)),e}var ho={thead:[`table`],tbody:[`table`],tfoot:[`table`],caption:[`table`],colgroup:[`table`],col:[`table`,`colgroup`],tr:[`table`,`tbody`],td:[`table`,`tbody`,`tr`],th:[`table`,`tbody`,`tr`]};function go(){return document.implementation.createHTMLDocument(`title`)}var _o=null;function vo(e){let t=window.trustedTypes;if(!t)return e;if(!_o){if(_o=t.defaultPolicy)try{return _o.createHTML(e)}catch{}_o=t.createPolicy(`ProseMirrorClipboard`,{createHTML:e=>e})}return _o.createHTML(e)}function yo(e){let t=/^(\s*<meta [^>]*>)*/.exec(e);t&&(e=e.slice(t[0].length));let n=go(),r=n.body,i=/<([a-z][^>\s]+)/i.exec(e),a;if((a=i&&ho[i[1].toLowerCase()])&&(e=a.map(e=>`<`+e+`>`).join(``)+e+a.map(e=>`</`+e+`>`).reverse().join(``)),r.innerHTML=vo(e),a)for(let e=0;e<a.length;e++)r=r.querySelector(a[e])||r;for(let e=0;e<n.styleSheets.length;e++){let t=n.styleSheets[e];for(let e=0;e<t.rules.length;e++){let n=t.rules[e];if(n instanceof CSSStyleRule){let e=r.querySelectorAll(n.selectorText);for(let t=0;t<e.length;t++)e[t].style.cssText+=n.style.cssText}}}return r}function bo(e){let t=e.querySelectorAll(ui?`span:not([class]):not([style])`:`span.Apple-converted-space`);for(let n=0;n<t.length;n++){let r=t[n];r.childNodes.length==1&&r.textContent==`\xA0`&&r.parentNode&&r.parentNode.replaceChild(e.ownerDocument.createTextNode(` `),r)}}function xo(e,t){if(!e.size)return e;let n=e.content.firstChild.type.schema,r;try{r=JSON.parse(t)}catch{return e}let{content:i,openStart:a,openEnd:o}=e;for(let e=r.length-2;e>=0;e-=2){let t=n.nodes[r[e]];if(!t||t.hasRequiredAttrs())break;try{i=s.from(t.create(r[e+1],i))}catch{break}a++,o++}return new p(i,a,o)}var So={},Co={},wo={touchstart:!0,touchmove:!0},To=class{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:``,button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariCompoLine truncated
|
||||
|
||||
`,textSerializers:o={}}=n||{},s=``;return e.nodesBetween(r,i,(e,n,c,l)=>{e.isBlock&&n>r&&(s+=a);let u=o?.[e.type.name];if(u)return c&&(s+=u({node:e,pos:n,parent:c,index:l,range:t})),!1;if(e.isText){var d;s+=e==null||(d=e.text)==null?void 0:d.slice(Math.max(r,n)-n,i-n)}}),s}function Hu(e,t){return Vu(e,{from:0,to:e.content.size},t)}function Uu(e){return Object.fromEntries(Object.entries(e.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Wu(e,t){let n=j(t,e.schema),{from:r,to:i}=e.selection,a=[];e.doc.nodesBetween(r,i,e=>{a.push(e)});let o=a.reverse().find(e=>e.type.name===n.name);return o?{...o.attrs}:{}}function Gu(e,t){let n=$l(typeof t==`string`?t:t.name,e.schema);return n===`node`?Wu(e,t):n===`mark`?du(e,t):{}}function Ku(e,t=JSON.stringify){let n={};return e.filter(e=>{let r=t(e);return Object.prototype.hasOwnProperty.call(n,r)?!1:n[r]=!0})}function qu(e){let t=Ku(e);return t.length===1?t:t.filter((e,n)=>!t.filter((e,t)=>t!==n).some(t=>e.oldRange.from>=t.oldRange.from&&e.oldRange.to<=t.oldRange.to&&e.newRange.from>=t.newRange.from&&e.newRange.to<=t.newRange.to))}function Ju(e){let{mapping:t,steps:n}=e,r=[],i=t.invert();return t.maps.forEach((e,a)=>{let o=[];if(e.ranges.length)e.forEach((e,t)=>{o.push({from:e,to:t})});else{let{from:e,to:t}=n[a];if(e===void 0||t===void 0)return;o.push({from:e,to:t})}let s=t.slice(a);o.forEach(({from:e,to:t})=>{let n=s.map(e,-1),a=s.map(t),o=i.map(n,-1),c=i.map(a);r.push({oldRange:{from:o,to:c},newRange:{from:n,to:a}})})}),qu(r)}function Yu(e,t,n){let r=[];return e===t?n.resolve(e).marks().forEach(t=>{let i=ml(n.resolve(e),t.type);i&&r.push({mark:t,...i})}):n.nodesBetween(e,t,(e,t)=>{e&&e?.nodeSize!==void 0&&r.push(...e.marks.map(n=>({from:t,to:t+e.nodeSize,mark:n})))}),r}var Xu=(e,t,n,r=20)=>{let i=e.doc.resolve(n),a=r,o=null;for(;a>0&&o===null;){let e=i.node(a);e?.type.name===t?o=e:--a}return[o,a]},Zu=e=>{let t=e.depth-1;if(t<0)return null;let n=e.index(t);return n===0?null:e.node(t).child(n-1)};function Qu(e,t){return t.nodes[e]||t.marks[e]||null}function $u(e,t,n){return Object.fromEntries(Object.entries(n).filter(([n])=>{let r=e.find(e=>e.type===t&&e.name===n);return r?r.attribute.keepOnSplit:!1}))}var ed=(e,t=500)=>{let n=``,r=e.parentOffset;return e.parent.nodesBetween(Math.max(0,r-t),r,(e,t,i,a)=>{var o;let s=(o=e.type.spec).toText?.call(o,{node:e,pos:t,parent:i,index:a})||e.textContent||`%leaf%`;n+=e.isAtom&&!e.isText?s:s.slice(0,Math.max(0,r-t))}),n};function td(e,t,n={}){let{empty:r,ranges:i}=e.selection,a=t?hl(t,e.schema):null;if(r)return!!(e.storedMarks||e.selection.$from.marks()).filter(e=>!a||a.name===e.type.name).find(e=>dl(e.attrs,n,{strict:!1}));let o=0,s=[];if(i.forEach(({$from:t,$to:n})=>{let r=t.pos,i=n.pos;e.doc.nodesBetween(r,i,(e,t)=>{if(a&&e.inlineContent&&!e.type.allowsMarkType(a))return!1;if(!e.isText&&!e.marks.length)return;let n=Math.max(r,t),c=Math.min(i,t+e.nodeSize),l=c-n;o+=l,s.push(...e.marks.map(e=>({mark:e,from:n,to:c})))})}),o===0)return!1;let c=s.filter(e=>!a||a.name===e.mark.type.name).filter(e=>dl(e.mark.attrs,n,{strict:!1})).reduce((e,t)=>e+t.to-t.from,0),l=s.filter(e=>!a||e.mark.type!==a&&e.mark.type.excludes(a)).reduce((e,t)=>e+t.to-t.from,0);return(c>0?c+l:c)>=o}function nd(e,t,n={}){if(!t)return Jl(e,null,n)||td(e,null,n);let r=$l(t,e.schema);return r===`node`?Jl(e,t,n):r===`mark`&&td(e,t,n)}var rd=(e,t)=>{let{$from:n,$to:r,$anchor:i}=e.selection;if(t){let n=hu(e=>e.type.name===t)(e.selection);if(!n)return!1;let r=e.doc.resolve(n.pos+1);return i.pos+1===r.end()}return!(r.parentOffset<r.parent.nodeSize-2||n.pos!==r.pos)},id=e=>{let{$from:t,$to:n}=e.selection;return!(t.parentOffset>0||t.pos!==n.pos)};function ad(e,t){return Array.isArray(t)?t.some(t=>(typeof t==`string`?t:t.name)===e.name):t}function od(e,t){let{nodeExtensions:n}=Eu(t),r=n.find(t=>t.name===e);if(!r)return!1;let i=N(M(r,`group`,{name:r.name,options:r.options,storage:r.storage}));return typeof i==`string`&&i.split(` `).includes(`list`)}function sd(e,{checkChildren:t=!0,ignoreWhitespace:n=!1}={}){if(n){if(e.type.name===`hardBreak`)return!0;if(e.isText)return!/\S/.test(e.text??``)}if(e.isText)return!e.text;if(e.isAtom||e.isLeaf)return!1;if(e.content.childCount===0)return!0;if(t){let r=!0;return e.content.forEach(e=>{r!==!1&&(sd(e,{ignoreWhitespace:n,checkChildren:t})||(r=!1))}),r}return!1}function cd(e){return e instanceof w}function ld(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.apply==`function`&&typeof t.getMap==`function`&&typeof t.invert==`function`&&typeof t.map==`function`&&typeof t.merge==`function`&&typeof t.toJSON==`function`}function ud(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!ld(t))return!1;let n=t.toJSON();return!(typeof n!=`object`||!n||n.stepType!==`replace`)}var dd=class e{constructor(e){this.position=e}static fromJSON(t){return new e(t.position)}toJSON(){return{position:this.position}}};function fd(e,t){let n=t.mapping.mapResult(e.position);return{position:new dd(n.pos),mapResult:n}}function pdLine truncated
|
||||
`),i=n.isParagraphContinuation??(e=>kf(e,n.blockTokens)),a=0;for(let e of r){if(!e.trim()||!i(e))break;a+=1}return{mainContent:[e,...r.slice(0,a).map(e=>e.trimStart())].join(`
|
||||
`),nestedContent:r.slice(a).join(`
|
||||
`)}}function jf(e,t,n){let r=e.split(`
|
||||
`),i=[],a=``,o=0,s=t.baseIndentSize||2;for(;o<r.length;){let e=r[o],u=e.match(t.itemPattern);if(!u){if(i.length>0)break;if(e.trim()===``){o+=1,a=`${a}${e}\n`;continue}return}let d=t.extractItemData(u),{indentLevel:f,mainContent:p}=d;a=`${a}${e}\n`;let m=[p];for(o+=1;o<r.length;){var c;let e=r[o];if(e.trim()===``){var l;let t=r.slice(o+1).findIndex(e=>e.trim()!==``);if(t===-1)break;if((((l=r[o+1+t].match(/^(\s*)/))==null||(l=l[1])==null?void 0:l.length)||0)>f){m.push(e),a=`${a}${e}\n`,o+=1;continue}break}if((((c=e.match(/^(\s*)/))==null||(c=c[1])==null?void 0:c.length)||0)>f)m.push(e),a=`${a}${e}\n`,o+=1;else break}let h,g=m.slice(1);if(g.length>0){let e=Af(p,g.map(e=>Of(e,f+s)).join(`
|
||||
`),n);d.mainContent=e.mainContent;let r=e.nestedContent;r.trim()&&(h=t.customNestedParser?t.customNestedParser(r):n.blockTokens(r))}let _=t.createToken(d,h);i.push(_)}if(i.length!==0)return{items:i,raw:a.slice(0,e.length)}}var Mf=4;function Nf(e){let t=0;for(let n of e)t=n===` `?t+Mf-t%Mf:t+1;return t}function Pf(e,t,n,r,i){if(!e||!Array.isArray(e.content))return``;let a=typeof n==`function`?n(r):n,[o,...s]=e.content,c=t.renderChildren([o]),l=`${a}${i?.indentMainContent?c.split(`
|
||||
`).map((e,n)=>n===0?e:t.indent(e)).join(`
|
||||
`):c}`;return s&&s.length>0&&s.forEach((e,n)=>{let r=t.renderChild?.call(t,e,n+1)??t.renderChildren([e]);if(r!=null){let n=e=>{if(!i?.alignNestedToPrefix)return t.indent(e);let n=t.indent(``),r=Nf(a);return(Nf(n)>=r?n:` `.repeat(r))+e},o=r.split(`
|
||||
`).map(e=>n(e||``)).join(`
|
||||
`);l+=e.type===`paragraph`?`\n\n${o}`:`\n${o}`}}),l}function Ff(e,t){let n={...e};return Ef(e)&&Ef(t)&&Object.keys(t).forEach(r=>{Ef(t[r])&&Ef(e[r])?n[r]=Ff(e[r],t[r]):n[r]=t[r]}),n}function If(e,t,n={}){let{state:r}=t,{doc:i,tr:a}=r,o=e;i.descendants((t,r)=>{let i=a.mapping.map(r),s=a.mapping.map(r)+t.nodeSize,c=null;if(t.marks.forEach(e=>{if(e!==o)return!1;c=e}),!c)return;let l=!1;if(Object.keys(n).forEach(e=>{n[e]!==c.attrs[e]&&(l=!0)}),l){let t=e.type.create({...e.attrs,...n});a.removeMark(i,s,e.type),a.addMark(i,s,t)}}),a.docChanged&&t.view.dispatch(a)}var Lf=class{constructor(e){this.find=e.find,this.handler=e.handler,this.undoable=e.undoable??!0}},Rf=(e,t)=>{if(ul(t))return t.exec(e);let n=t(e);if(!n)return null;let r=[n.text];return r.index=n.index,r.input=e,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn(`[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".`),r.push(n.replaceWith)),r};function zf(e){let{editor:t,from:n,to:r,text:i,insertText:a}=e;if(!a)return{inputTransaction:null,tr:t.view.state.tr};let o=t.view.state.tr.insertText(i,n,r);return{inputTransaction:o,tr:Vn.create({doc:o.doc,selection:o.selection,storedMarks:o.storedMarks}).tr}}function Bf(e){let{editor:t,from:n,to:r,text:i,rule:a,match:o,plugin:s,insertText:c}=e,{view:l}=t,{inputTransaction:u,tr:d}=zf({editor:t,from:n,to:r,text:i,insertText:c}),f=u?n+i.length:r,p=qc({state:l.state,transaction:d}),m={from:n-(o[0].length-i.length),to:f},{commands:h,chain:g,can:_}=new Jc({editor:t,state:p});return a.handler({state:p,range:m,match:o,commands:h,chain:g,can:_})===null||!d.steps.length?!1:(u&&(l.dispatch(u),!l.state.doc.eq(u.doc))||(zc(d),d.setMeta(`inputRule`,!0),a.undoable&&d.setMeta(s,{transform:d,from:n,to:f,text:i}),l.dispatch(d)),!0)}function Vf(e,t,n){let r=t[0].length-n.length;if(r<=0)return!0;let i=e.parentOffset-r;return i>=0&&e.parent.textBetween(i,e.parentOffset)===t[0].slice(0,r)}function Hf(e){let{editor:t,from:n,to:r,text:i,rules:a,plugin:o,insertText:s}=e,{view:c}=t;if(c.composing)return!1;let l=c.state.doc.resolve(n);if(l.parent.type.spec.code||(l.nodeBefore||l.nodeAfter)?.marks.find(e=>e.type.spec.code))return!1;let u=ed(l)+i;for(let e of a){let a=Rf(u,e.find);if(a&&Vf(l,a,i)&&Bf({editor:t,from:n,to:r,text:i,rule:e,match:a,plugin:o,insertText:s}))return!0}return!1}function Uf(e){let{editor:t,rules:n}=e,r=new T({state:{init(){return null},apply(e,i,a){let o=e.getMeta(r);if(o)return o;let c=e.getMeta(`applyInputRules`);return c&&setTimeout(()=>{let{text:e}=c;e=typeof e==`string`?e:_u(s.from(e),a.schema);let{from:i}=c,o=i+e.length;Hf({editor:t,from:i,to:o,text:e,rules:n,plugin:r})}),e.selectionSet||e.docChanged?null:i}},props:{handleTextInput(e,i,a,o){return Hf({editor:t,from:i,to:a,text:o,rules:n,plugin:r,insertText:!0})},handleDOMEvents:{compositionend:e=>(setTimeout(()=>{let{$cursor:i}=e.state.selection;i&&Hf({editor:t,from:i.pos,to:i.pos,text:``,rules:n,plugin:r})}),!1)},handleKeyDown(e,i){if(i.key!==`Enter`)return!1;let{$cursor:a}=e.state.selection;return a?Hf({editor:t,from:a.pos,to:a.pos,text:`
|
||||
`,rules:n,plugin:r}):!1}},isInputRules:!0});return r}var Wf=class{constructor(e={}){this.type=`extendable`,this.parent=null,this.child=null,this.name=``,this.config={name:this.name},this.config={...this.config,...e},this.name=this.config.name}get options(){return{...N(M(this,`addOptions`,{name:this.name}))}}get storage(){return{...N(M(this,`addStorage`,{name:this.name,options:this.options}))}}configure(e={}){let t=this.extend({...this.config,addOptions:()=>Ff(this.options,e)});return t.name=this.name,t.parent=this.parent,this.child=null,t}extend(e={}){let t=new this.constructor({...this.config,...e});return t.parent=this,this.child=t,t.name=`name`in e?e.name:t.parent.name,t}},Gf=class e extends Wf{constructor(...e){super(...e),this.type=`mark`}static create(t={}){let n=typeof t==`function`?t():t;return new e(n)}static handleExit({editor:e,mark:t}){let{tr:n}=e.state,r=e.state.selection.$from;if(r.pos===r.end()){let i=r.marks();if(!i.find(e=>e?.type.name===t.name))return!1;let a=i.find(e=>e?.type.name===t.name);return a&&n.removeStoredMark(a),n.insertText(` `,r.pos),e.view.dispatch(n),!0}return!1}configure(e){return super.configure(e)}extend(e){let t=typeof e==`function`?e():e;return super.extend(t)}},Kf=class{constructor(e){this.find=e.find,this.handler=e.handler}},qf=(e,t,n)=>{if(ul(t))return[...e.matchAll(t)];let r=t(e,n);return r?r.map(t=>{let n=[t.text];return n.index=t.index,n.input=e,n.data=t.data,t.replaceWith&&(t.text.includes(t.replaceWith)||console.warn(`[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".`),n.push(t.replaceWith)),n}):[]};function Jf(e){let{editor:t,state:n,from:r,to:i,rule:a,pasteEvent:o,dropEvent:s}=e,{commands:c,chain:l,can:u}=new Jc({editor:t,state:n}),d=[];return n.doc.nodesBetween(r,i,(e,t)=>{var f;if((f=e.type)!=null&&(f=f.spec)!=null&&f.code||!(e.isText||e.isTextblock||e.isInline))return;let p=e.content?.size??e.nodeSize??0,m=Math.max(r,t),h=Math.min(i,t+p);m>=h||qf(e.isText?e.text||``:e.textBetween(m-t,h-t,void 0,``),a.find,o).forEach(e=>{if(e.index===void 0)return;let t=m+e.index+1,r=t+e[0].length,i={from:n.tr.mapping.map(t),to:n.tr.mapping.map(r)},f=a.handler({state:n,range:i,match:e,commands:c,chain:l,can:u,pasteEvent:o,dropEvent:s});d.push(f)})}),d.every(e=>e!==null)}var Yf=null,Xf=e=>{var t;let n=new ClipboardEvent(`paste`,{clipboardData:new DataTransfer});return(t=n.clipboardData)==null||t.setData(`text/html`,e),n};function Zf(e){let{editor:t,rules:n}=e,r=null,i=!1,a=!1,o=typeof ClipboardEvent<`u`?new ClipboardEvent(`paste`):null,c;try{c=typeof DragEvent<`u`?new DragEvent(`drop`):null}catch{c=null}let l=({state:e,from:n,to:r,rule:i,pasteEvt:a})=>{let s=e.tr,l=qc({state:e,transaction:s});if(Jf({editor:t,state:l,from:Math.max(n-1,0),to:r.b-1,rule:i,pasteEvent:a,dropEvent:c})&&s.steps.length){try{c=typeof DragEvent<`u`?new DragEvent(`drop`):null}catch{c=null}return o=typeof ClipboardEvent<`u`?new ClipboardEvent(`paste`):null,s}};return t.on(`destroy`,()=>{Yf===t&&(Yf=null)}),n.map(e=>new T({view(e){let n=n=>{r=e.dom.parentElement?.contains(n.target)?e.dom.parentElement:null,r&&(Yf=t)},i=()=>{Yf&&=null};return window.addEventListener(`dragstart`,n),window.addEventListener(`dragend`,i),{destroy(){window.removeEventListener(`dragstart`,n),window.removeEventListener(`dragend`,i)}}},props:{handleDOMEvents:{drop:(e,t)=>{if(a=r===e.dom.parentElement,c=t,!a){let e=Yf;e?.isEditable&&setTimeout(()=>{if(e.isDestroyed)return;let t=e.state.selection;t&&e.commands.deleteRange({from:t.from,to:t.to})},10)}return!1},paste:(e,t)=>{let n=t.clipboardData?.getData(`text/html`);return o=t,i=!!n?.includes(`data-pm-slice`),!1}}},appendTransaction:(t,n,r)=>{let c=t[0],u=c.getMeta(`uiEvent`)===`paste`&&!i,d=c.getMeta(`uiEvent`)===`drop`&&!a,f=c.getMeta(`applyPasteRules`),p=!!f;if(!u&&!d&&!p)return;if(p){let{text:t}=f;t=typeof t==`string`?t:_u(s.from(t),r.schema);let{from:n}=f,i=n+t.length,a=Xf(t);return l({rule:e,state:r,from:n,to:{b:i},pasteEvt:a})}let m=n.doc.content.findDiffStart(r.doc.content),h=n.doc.content.findDiffEnd(r.doc.content);if(wf(m)&&h&&m!==h.b)return l({rule:e,state:r,from:m,to:h,pasteEvt:o})}}))}var Qf=class{constructor(e,t){this.splittableMarks=[],this.nonClearableMarks=[],this.decorationManager=null,this.editor=t,this.baseExtensions=e,this.extensions=Bu(e),this.hasSchemaSpec=t.options.schemaSpec!==void 0,this.schema=Ru(this.extensions,t,t.options.schemaSpec),this.setupExtensions()}get commands(){return this.extensions.reduce((e,t)=>{let n=M(t,`addCommands`,{name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:this.editor,type:Qu(t.name,this.schema)});return n?{...e,...n()}:e},{})}get plugins(){let{editor:e}=this,t=zu([...this.extensions].reverse()).flatMap(t=>{let n={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:e,type:Qu(t.name,this.schema)},r=[],i=M(t,`addKeyboardShortcuts`,n),a={};if(t.type===`mark`&&M(t,`exitable`,n)&&(a.ArrowRight=()=>Gf.handleExit({editor:e,mark:t})),i){leLine truncated
|
||||
|
||||
`)}}})]}}),ep=F.create({name:`commands`,addCommands(){return{...Xd}}}),tp=F.create({name:`delete`,onUpdate({transaction:e,appendedTransactions:t}){var n;let r=()=>{var n,r;if(((n=this.editor.options.coreExtensionOptions)==null||(n=n.delete)==null||(r=n.filterTransaction)==null?void 0:r.call(n,e))??e.getMeta(`y-sync$`))return;let i=fu(e.before,[e,...t]);Ju(i).forEach(t=>{i.mapping.mapResult(t.oldRange.from).deletedAfter&&i.mapping.mapResult(t.oldRange.to).deletedBefore&&i.before.nodesBetween(t.oldRange.from,t.oldRange.to,(n,r)=>{let a=r+n.nodeSize-2,o=t.oldRange.from<=r&&a<=t.oldRange.to;this.editor.emit(`delete`,{type:`node`,node:n,from:r,to:a,newFrom:i.mapping.map(r),newTo:i.mapping.map(a),deletedRange:t.oldRange,newRange:t.newRange,partial:!o,editor:this.editor,transaction:e,combinedTransform:i})})});let a=i.mapping;i.steps.forEach((t,n)=>{if(t instanceof Ct){let r=a.slice(n).map(t.from,-1),o=a.slice(n).map(t.to),s=a.invert().map(r,-1),c=a.invert().map(o),l=r>0&&i.doc.nodeAt(r-1)?.marks.some(e=>e.eq(t.mark)),u=i.doc.nodeAt(o)?.marks.some(e=>e.eq(t.mark));this.editor.emit(`delete`,{type:`mark`,mark:t.mark,from:t.from,to:t.to,deletedRange:{from:s,to:c},newRange:{from:r,to:o},partial:!!(u||l),editor:this.editor,transaction:e,combinedTransform:i})}})};((n=this.editor.options.coreExtensionOptions)==null||(n=n.delete)==null?void 0:n.async)??!0?setTimeout(r,0):r()}}),np=F.create({name:`drop`,addProseMirrorPlugins(){return[new T({key:new E(`tiptapDrop`),props:{handleDrop:(e,t,n,r)=>{this.editor.emit(`drop`,{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),rp=F.create({name:`editable`,addProseMirrorPlugins(){return[new T({key:new E(`editable`),props:{editable:()=>this.editor.options.editable}})]}}),ip=new E(`focusEvents`),ap=F.create({name:`focusEvents`,addProseMirrorPlugins(){let{editor:e}=this;return[new T({key:ip,props:{handleDOMEvents:{focus:(t,n)=>{e.isFocused=!0;let r=e.state.tr.setMeta(`focus`,{event:n}).setMeta(`addToHistory`,!1);return t.dispatch(r),!1},blur:(t,n)=>{e.isFocused=!1;let r=e.state.tr.setMeta(`blur`,{event:n}).setMeta(`addToHistory`,!1);return t.dispatch(r),!1}}}})]}}),op=F.create({name:`keymap`,addKeyboardShortcuts(){let e=()=>this.editor.commands.first(({commands:e})=>[()=>e.undoInputRule(),()=>e.command(({tr:t})=>{let{selection:n,doc:r}=t,{empty:i,$anchor:a}=n,{pos:o,parent:s}=a,c=a.parent.isTextblock&&o>0?t.doc.resolve(o-1):a,l=c.parent.type.spec.isolating,u=a.pos-a.parentOffset,d=l&&c.parent.childCount===1?u===a.pos:S.atStart(r).from===o;return!i||!s.type.isTextblock||s.textContent.length||!d||d&&a.parent.type.name===`paragraph`?!1:e.clearNodes()}),()=>e.deleteSelection(),()=>e.joinBackward(),()=>e.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:e})=>[()=>e.deleteSelection(),()=>e.deleteCurrentNode(),()=>e.joinForward(),()=>e.selectNodeForward()]),n={Enter:()=>this.editor.commands.first(({commands:e})=>[()=>e.newlineInCode(),()=>e.createParagraphNear(),()=>e.liftEmptyBlock(),()=>e.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:e,"Mod-Backspace":e,"Shift-Backspace":e,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},r={...n},i={...n,"Ctrl-h":e,"Alt-Backspace":e,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return Sl()||Gl()?i:r},addProseMirrorPlugins(){return[new T({key:new E(`clearDocument`),appendTransaction:(e,t,n)=>{if(e.some(e=>e.getMeta(`composition`)))return;let r=e.some(e=>e.docChanged)&&!t.doc.eq(n.doc),i=e.some(e=>e.getMeta(`preventClearDocument`));if(!r||i)return;let{empty:a,from:o,to:s}=t.selection,c=S.atStart(t.doc).from,l=S.atEnd(t.doc).to;if(a||o!==c||s!==l||!sd(n.doc))return;let u=n.tr,d=qc({state:n,transaction:u}),{commands:f}=new Jc({editor:this.editor,state:d});if(f.clearNodes(),u.steps.length)return u}})]}}),sp=F.create({name:`paste`,addProseMirrorPlugins(){return[new T({key:new E(`tiptapPaste`),props:{handlePaste:(e,t,n)=>{this.editor.emit(`paste`,{editor:this.editor,event:t,slice:n})}}})]}}),cp=F.create({name:`tabindex`,addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new T({key:new E(`tabindex`),props:{attributes:()=>!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:this.options.value??`0`}}})]}}),lp=F.create({name:`textDirection`,addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];let{nodeExtensions:e}=Eu(this.extensions);return[{types:e.filter(e=>e.name!==`text`).map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{let t=e.getAttribute(`dir`);return t&&(t===`ltr`||t===`rtl`||t===`auto`)?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new T({key:new E(`textDirection`),props:{attributes:()=>{let e=this.options.direction;return e?{dir:e}:{}}}})]}}),up=!1;function dp(e){if(up)return;up=!0;let t;try{let n=Ot.fromJSON(e,{from:0,tLine truncated
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.ProseMirror {
|
||||
word-wrap: break-word;
|
||||
white-space: pre-wrap;
|
||||
white-space: break-spaces;
|
||||
-webkit-font-variant-ligatures: none;
|
||||
font-variant-ligatures: none;
|
||||
font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */
|
||||
}
|
||||
|
||||
.ProseMirror [contenteditable="false"] {
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.ProseMirror [contenteditable="false"] [contenteditable="true"] {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.ProseMirror pre {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
img.ProseMirror-separator {
|
||||
display: inline !important;
|
||||
border: none !important;
|
||||
margin: 0 !important;
|
||||
width: 0 !important;
|
||||
height: 0 !important;
|
||||
}
|
||||
|
||||
.ProseMirror-gapcursor {
|
||||
display: none;
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.ProseMirror-gapcursor:after {
|
||||
content: "";
|
||||
display: block;
|
||||
position: absolute;
|
||||
top: -2px;
|
||||
width: 20px;
|
||||
border-top: 1px solid black;
|
||||
animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
|
||||
}
|
||||
|
||||
@keyframes ProseMirror-cursor-blink {
|
||||
to {
|
||||
visibility: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
.ProseMirror-hideselection *::selection {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.ProseMirror-hideselection *::-moz-selection {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.ProseMirror-hideselection * {
|
||||
caret-color: transparent;
|
||||
}
|
||||
|
||||
.ProseMirror-focused .ProseMirror-gapcursor {
|
||||
display: block;
|
||||
}`,mp=class extends ef{constructor(e={}){super(),this.css=null,this.className=`tiptap`,this.editorView=null,this.isFocused=!1,this.destroyed=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.hasWarnedStaleDecorationRead=!1,this.options={element:typeof document<`u`?document.createElement(`div`):null,content:``,injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:e})=>{throw e},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:fd,createMappablePosition:pd},this.setOptions(e),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on(`beforeCreate`,this.options.onBeforeCreate),this.emit(`beforeCreate`,{editor:this}),this.on(`mount`,this.options.onMount),this.on(`unmount`,this.options.onUnmount),this.on(`contentError`,this.options.onContentError),this.on(`create`,this.options.onCreate),this.on(`update`,this.options.onUpdate),this.on(`selectionUpdate`,this.options.onSelectionUpdate),this.on(`transaction`,this.options.onTransaction),this.on(`focus`,this.options.onFocus),this.on(`blur`,this.options.onBlur),this.on(`destroy`,this.options.onDestroy),this.on(`drop`,({event:e,slice:t,moved:n})=>this.options.onDrop(e,t,n)),this.on(`paste`,({event:e,slice:t})=>this.options.onPaste(e,t)),this.on(`delete`,this.options.onDelete);let t=this.createDoc();if(!this.editorState){let e=bl(t,this.options.autofocus);this.editorState=Vn.create({doc:t,schema:this.schema,selection:e||void 0})}dp(this.schema),this.options.element&&this.mount(this.options.element)}mount(e){if(typeof document>`u`)throw Error(`[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.`);this.createView(e),this.emit(`mount`,{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit(`create`,{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){this.editorState=this.editorView.state;let e=this.editorView.dom;e?.editor&&delete e.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove==`function`?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(e){console.warn(`Failed to remove CSS element:`,e)}this.css=null,this.emit(`unmount`,{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager?this.commandManager.chain():Jc.createFakeChain()}can(){return this.commandManager?this.commandManager.can():Jc.createFallbackCan()}injectCSS(){this.options.injectCSS&&typeof document<`u`&&(this.css=Cf(pp,this.options.injectNonce))}setOptions(e={}){this.options={...this.options,...e},this.editorView&&this.state&&!this.isDestroyed&&(this.options.editorProps&&this.view.setProps({...this.options.editorProps,attributes:this.getEditorViewAttributes()}),this.view.updateState(this.state))}setEditable(e,t=!0){this.setOptions({editable:e}),t&&this.emit(`update`,{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:e=>{this.editorState=e},dispatch:e=>{this.dispatchTransaction(e)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(e,t)=>{if(this.editorView)return this.editorView[t];if(t===`state`)return this.editorState;if(t in e)return Reflect.get(e,t);throw Error(`[tiptap error]: The editor view is not available. Cannot access view['${t}']. The editor may not be mounted yet.`)}})}get state(){return tf&&!this.hasWarnedStaleDecorationRead&&$d(this)&&(this.hasWarnedStaleDecorationRead=!0,console.warn("[tiptap warn]: `editor.state` was read while decoration `create()` was running. It returns the pre-transaction document. Use the `state` argument passed to `create()` instead. Helpers like `editor.isActive()` read `editor.state` too, so pass `state` to their standalone versions instead of calling them on the editor.")),this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(e,t){let n=Ou(t)?t(e,[...this.state.plugins]):[...this.state.plugins,e],r=this.state.recoLine truncated
|
||||
|
||||
`,textSerializers:n={}}=e||{};return Hu(this.state.doc,{blockSeparator:t,textSerializers:{...Uu(this.schema),...n}})}get isEmpty(){return sd(this.state.doc)}destroy(){this.destroyed||(this.destroyed=!0,this.emit(`destroy`),this.unmount(),this.removeAllListeners(),this.extensionManager.destroy(),this.extensionManager=null,this.schema=null,this.commandManager=null,this.extensionStorage={})}get isDestroyed(){return this.editorView?.isDestroyed??!0}$node(e,t){return this.$doc?.querySelector(e,t)||null}$nodes(e,t){return this.$doc?.querySelectorAll(e,t)||null}$pos(e){let t=this.state.doc.resolve(e),n=e>0&&t.nodeAfter&&!t.nodeAfter.isText&&t.nodeAfter.isAtom?t.nodeAfter:null;return new fp(t,this,!1,n)}get $doc(){return this.$pos(0)}};function hp(e){return new Lf({find:e.find,handler:({state:t,range:n,match:r})=>{let i=N(e.getAttributes,void 0,r);if(i===!1||i===null)return null;let{tr:a}=t,o=r[r.length-1],s=r[0];if(o){let r=s.search(/\S/),c=n.from+s.indexOf(o),l=c+o.length;if(Yu(n.from,n.to,t.doc).filter(t=>t.mark.type.excluded.find(n=>n===e.type&&n!==t.mark.type)).filter(e=>e.to>c).length)return null;l<n.to&&a.delete(l,n.to),c>n.from&&a.delete(n.from+r,c);let u=n.from+r+o.length;a.addMark(n.from+r,u,e.type.create(i||{})),a.removeStoredMark(e.type)}},undoable:e.undoable})}function gp(e){return new Lf({find:e.find,handler:({state:t,range:n,match:r})=>{let i=N(e.getAttributes,void 0,r)||{},{tr:a}=t,o=n.from,s=n.to,c=e.type.create(i);if(r[1]){let e=o+r[0].lastIndexOf(r[1]);e>s?e=s:s=e+r[1].length;let t=r[0][r[0].length-1];a.insertText(t,o+r[0].length-1),a.replaceWith(e,s,c)}else if(r[0]){let t=e.type.isInline?o:o-1;a.insert(t,e.type.create(i)).delete(a.mapping.map(o),a.mapping.map(s))}a.scrollIntoView()},undoable:e.undoable})}function _p(e){return new Lf({find:e.find,handler:({state:t,range:n,match:r})=>{let i=t.doc.resolve(n.from),a=N(e.getAttributes,void 0,r)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),e.type))return null;t.tr.delete(n.from,n.to).setBlockType(n.from,n.from,e.type,a)},undoable:e.undoable})}function vp(e){return new Lf({find:e.find,handler:({state:t,range:n,match:r,chain:i})=>{let a=N(e.getAttributes,void 0,r)||{},o=t.tr.delete(n.from,n.to),s=o.doc.resolve(n.from).blockRange(),c=s&&Lt(s,e.type,a);if(!c)return null;if(o.wrap(s,c),e.keepMarks&&e.editor){let{selection:n,storedMarks:r}=t,{splittableMarks:i}=e.editor.extensionManager,a=r||n.$to.parentOffset&&n.$from.marks();if(a){let e=a.filter(e=>i.includes(e.type.name));o.ensureMarks(e)}}if(e.keepAttributes){let t=e.type.name===`bulletList`||e.type.name===`orderedList`?`listItem`:`taskList`;i().updateAttributes(t,a).run()}let l=o.doc.resolve(n.from-1).nodeBefore;l&&l.type===e.type&&Yt(o.doc,n.from-1)&&(!e.joinPredicate||e.joinPredicate(r,l))&&o.join(n.from-1)},undoable:e.undoable})}var yp=class e extends Wf{constructor(...e){super(...e),this.type=`node`}static create(t={}){let n=typeof t==`function`?t():t;return new e(n)}configure(e){return super.configure(e)}extend(e){let t=typeof e==`function`?e():e;return super.extend(t)}};function bp(e){return new Kf({find:e.find,handler:({state:t,range:n,match:r,pasteEvent:i})=>{let a=N(e.getAttributes,void 0,r,i);if(a===!1||a===null)return null;let{tr:o}=t,s=r[r.length-1],c=r[0],l=n.to;if(s){let i=c.search(/\S/),u=n.from+c.indexOf(s),d=u+s.length;if(Yu(n.from,n.to,t.doc).filter(t=>t.mark.type.excluded.find(n=>n===e.type&&n!==t.mark.type)).filter(e=>e.to>u).length)return null;d<n.to&&o.delete(d,n.to),u>n.from&&o.delete(n.from+i,u),l=n.from+i+s.length,o.addMark(n.from+i,l,e.type.create(a||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(e.type)}}})}var xp=()=>new Map,Sp=e=>{let t=xp();return e.forEach((e,n)=>{t.set(n,e)}),t},Cp=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},wp=(e,t)=>{let n=[];for(let[r,i]of e)n.push(t(i,r));return n},Tp=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},Ep=()=>new Set,Dp=e=>e[e.length-1],Op=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},kp=Array.from,Ap=(e,t)=>{for(let n=0;n<e.length;n++)if(!t(e[n],n,e))return!1;return!0},jp=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},Mp=(e,t)=>{let n=Array(e);for(let r=0;r<e;r++)n[r]=t(r,n);return n},Np=Array.isArray,Pp=class{constructor(){this._observers=xp()}on(e,t){return Cp(this._observers,e,Ep).add(t),t}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return kp((this._observers.get(e)||xp()).values()).forEach(e=>e(...t))}destroy(){this._observers=xp()}},Fp=class{constructor(){this._observers=xp()}on(e,t){Cp(this._observers,e,Ep).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return kp((this._observers.get(e)||xp()).values()).forEach(e=>e(...t))}destroy(){this._observers=xp()}},IpLine truncated
|
||||
`)}},Jh=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[oh]?sh(e,t):Np(e)?Ap(e,e=>jp(t,t=>Jh(e,t))):ch(e)?mh(e,(e,n)=>Jh(e,t[n])):!1,Yh=class{static _dilutes=!1;extends(e){let[t,n]=[this.shape,e.shape];return this.constructor._dilutes&&([n,t]=[t,n]),Jh(t,n)}equals(e){return this.constructor===e.constructor&&xh(this.shape,e.shape)}[Kh](){return!0}[oh](e){return this.equals(e)}validate(e){return this.check(e)}check(e,t){km()}get nullable(){return Eg(this,Vg)}get optional(){return new ig(this)}cast(e){return Gg(e,this),e}expect(e){return Gg(e,this),e}},Xh=class extends Yh{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t=void 0){let n=e?.constructor===this.shape&&(this._c==null||this._c(e));return!n&&t?.extend(null,this.shape.name,e?.constructor.name,e?.constructor===this.shape?`Check failed`:`Constructor match failed`),n}},B=(e,t=null)=>new Xh(e,t);B(Xh);var Zh=class extends Yh{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape(e);return!n&&t?.extend(null,`custom prop`,e?.constructor.name,`failed to check custom prop`),n}},V=e=>new Zh(e);B(Zh);var Qh=class extends Yh{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape.some(t=>t===e);return!n&&t?.extend(null,this.shape.join(` | `),e.toString()),n}},$h=(...e)=>new Qh(e),eg=B(Qh),tg=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,e=>`\\`+e)),ng=e=>{if(Ig.check(e))return[tg(e)];if(eg.check(e))return e.shape.map(e=>e+``);if(Fg.check(e))return[`[+-]?\\d+.?\\d*`];if(Lg.check(e))return[`.*`];if(Dg.check(e))return e.shape.map(ng).flat(1);R()};B(class extends Yh{constructor(e){super(),this.shape=e,this._r=RegExp(`^`+e.map(ng).map(e=>`(${e.join(`|`)})`).join(``)+`$`)}check(e,t){let n=this._r.exec(e)!=null;return!n&&t?.extend(null,this._r.toString(),e.toString(),`String doesn't match string template.`),n}});var rg=Symbol(`optional`),ig=class extends Yh{constructor(e){super(),this.shape=e}check(e,t){let n=e===void 0||this.shape.check(e);return!n&&t?.extend(null,`undefined (optional)`,`()`),n}get[rg](){return!0}},ag=B(ig),og=class extends Yh{check(e,t){return t?.extend(null,`never`,typeof e),!1}};new og,B(og);var sg=class e extends Yh{constructor(e,t=!1){super(),this.shape=e,this._isPartial=t}static _dilutes=!0;get partial(){return new e(this.shape,!0)}check(e,t){return e==null?(t?.extend(null,`object`,`null`),!1):mh(this.shape,(n,r)=>{let i=this._isPartial&&!hh(e,r)||n.check(e[r],t);return!i&&t?.extend(r.toString(),n.toString(),typeof e[r],`Object property does not match`),i})}},cg=e=>new sg(e),lg=B(sg),ug=V(e=>e!=null&&(e.constructor===Object||e.constructor==null)),dg=class extends Yh{constructor(e,t){super(),this.shape={keys:e,values:t}}check(e,t){return e!=null&&mh(e,(n,r)=>{let i=this.shape.keys.check(r,t);return!i&&t?.extend(r+``,`Record`,typeof e,i?`Key doesn't match schema`:`Value doesn't match value`),i&&this.shape.values.check(n,t)})}},fg=(e,t)=>new dg(e,t),pg=B(dg),mg=class extends Yh{constructor(e){super(),this.shape=e}check(e,t){return e!=null&&mh(this.shape,(n,r)=>{let i=n.check(e[r],t);return!i&&t?.extend(r.toString(),`Tuple`,typeof n),i})}},hg=(...e)=>new mg(e);B(mg);var gg=class extends Yh{constructor(e){super(),this.shape=e.length===1?e[0]:new Tg(e)}check(e,t){let n=Np(e)&&Ap(e,e=>this.shape.check(e));return!n&&t?.extend(null,`Array`,``),n}},_g=(...e)=>new gg(e),vg=B(gg),yg=V(e=>Np(e)),bg=class extends Yh{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t){let n=e instanceof this.shape&&(this._c==null||this._c(e));return!n&&t?.extend(null,this.shape.name,e?.constructor.name),n}},xg=(e,t=null)=>new bg(e,t);B(bg);var Sg=xg(Yh),Cg=B(class extends Yh{constructor(e){super(),this.len=e.length-1,this.args=hg(...e.slice(-1)),this.res=e[this.len]}check(e,t){let n=e.constructor===Function&&e.length<=this.len;return!n&&t?.extend(null,`function`,typeof e),n}}),wg=V(e=>typeof e==`function`);B(class extends Yh{constructor(e){super(),this.shape=e}check(e,t){let n=Ap(this.shape,n=>n.check(e,t));return!n&&t?.extend(null,`Intersectinon`,typeof e),n}},e=>e.shape.length>0);var Tg=class extends Yh{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,t){let n=jp(this.shape,n=>n.check(e,t));return t?.extend(null,`Union`,typeof e),n}},Eg=(...e)=>e.findIndex(e=>Dg.check(e))>=0?Eg(...e.map(e=>Wg(e)).map(e=>Dg.check(e)?e.shape:[e]).flat(1)):e.length===1?e[0]:new Tg(e),Dg=B(Tg),Og=()=>!0,kg=V(Og),Ag=B(Zh,e=>e.shape===Og),jg=V(e=>typeof e==`bigint`),Mg=V(e=>e===jg),Ng=V(e=>typeof e==`symbol`);V(e=>e===Ng);var Pg=V(e=>typeof e==`number`),Fg=V(e=>e===Pg),Ig=V(e=>typeof e==`string`),Lg=V(e=>e===Ig),Rg=V(e=>typeof e==`boolean`),zg=V(e=>e===Rg),Bg=$h(void 0);B(Qh,e=>e.shape.length===1&&e.shape[0]===void 0),$h(void 0);var Vg=$h(null),Hg=B(Qh,e=>e.shape.length===1&&e.shape[0]===null);B(Uint8Array),B(Xh,e=>e.shape===Uint8Array);var Ug=Eg(Pg,Ig,Vg,Bg,jg,Rg,Ng);(()=>{let e=_g(kg),t=fg(Ig,kg),n=Eg(Pg,Ig,Vg,Rg,e,t);return e.shape=n,t.shape.values=n,n})();var Wg=e=>{if(Sg.check(e))return e;if(ug.check(e)){let t={};for(let n in Line truncated
|
||||
`;n.right=new J(H(o,U(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Bb(i)),n.right.integrate(e,0),n.forward()}$y(e,t,n,s)},ab=(e,t,n,r,i)=>{let a=t,o=xp();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===q){let e=a.content;o.set(e.key,e)}a=a.right}let s=0,c=!1;for(;t!==a;){if(n===t&&(c=!0),!t.deleted){let n=t.content;switch(n.constructor){case q:{let{key:a,value:l}=n,u=r.get(a)??null;(o.get(a)!==n||u===l)&&(t.delete(e),s++,!c&&(i.get(a)??null)===l&&u!==l&&(u===null?i.delete(a):i.set(a,u))),!c&&!t.deleted&&eb(i,n);break}}}t=t.right}return s},ob=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===q){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},sb=e=>{let t=0;return W(e.doc,n=>{let r=e._start,i=e._start,a=xp(),o=Sp(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case q:eb(o,i.content);break;default:t+=ab(n,r,i,a,o),a=Sp(o),r=i}i=i.right}}),t},cb=e=>{let t=new Set,n=e.doc;for(let[r,i]of e.afterState.entries()){let a=e.beforeState.get(r)||0;i!==a&&Vv(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===q&&e.constructor!==wb&&t.add(e.parent)})}W(n,n=>{w_(e,e.deleteSet,e=>{if(e instanceof wb||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===q?t.add(r):ob(n,e)});for(let e of t)sb(e)})},lb=(e,t,n)=>{let r=n,i=Sp(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Xb:case Mb:case Bb:n<t.right.length&&Rv(e,H(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}a&&ab(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&Sy(o._searchMarker,t.index,-r+n),t},ub=class extends fy{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(this._changes===null){let e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];W(e,e=>{let n=new Map,r=new Map,i=this.target._start,a=null,o={},s=``,c=0,l=0,u=()=>{if(a!==null){let e=null;switch(a){case`delete`:l>0&&(e={delete:l}),l=0;break;case`insert`:(typeof s==`object`||s.length>0)&&(e={insert:s},n.size>0&&(e.attributes={},n.forEach((t,n)=>{t!==null&&(e.attributes[n]=t)}))),s=``;break;case`retain`:c>0&&(e={retain:c},ph(o)||(e.attributes=lh({},o))),c=0}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case Xb:case Mb:this.adds(i)?this.deletes(i)||(u(),a=`insert`,s=i.content.getContent()[0],u()):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=1):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=1);break;case Bb:this.adds(i)?this.deletes(i)||(a!==`insert`&&(u(),a=`insert`),s+=i.content.str):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=i.length):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=i.length);break;case q:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(Yy(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),Yy(s,r.get(t)??null)?delete o[t]:o[t]=s));else if(this.deletes(i)){r.set(t,s);let e=n.get(t)??null;Yy(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(Yy(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),eb(n,i.content));break}}i=i.right}for(u();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},db=class e extends G{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??my(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let n=new ub(this,e,t);Cy(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??my();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===Bb&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):W(this.doc,n=>{let r=new Xy(null,this._start,0,new Map);for(let i=0;i<e.length;i++){let a=e[i];if(a.insert!==void 0){let o=!t&&typeof a.insert==`string`&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
|
||||
`?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&rb(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&lb(n,r,a.delete):ib(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??my();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(Av(s,e)||t!==void 0&&Av(s,t))switch(s.content.constructor){case Bb:{let r=i.get(`ychange`);e!==void 0&&!Av(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!Av(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case Xb:case Mb:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case q:Av(s,e)&&(c(),eb(i,s.content))}s=s.right}c()};return e||t?W(a,n=>{e&&jv(n,e),t&&jv(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):W(r,r=>{let i=Qy(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),rb(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):W(r,r=>{let i=Qy(r,this,e,!n);rb(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):W(n,n=>{lb(n,Qy(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):W(r,r=>{let i=Qy(r,this,e,!1);i.right!==null&&ib(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):W(this.doc,t=>{Iy(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):W(this.doc,n=>{Ly(n,this,e,t)})}getAttribute(e){return Ry(this,e)}getAttributes(){return zy(this)}_write(e){e.writeTypeRef(Gb)}},fb=e=>new db,pb=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??my()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===K||t.constructor===mb)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},mb=class e extends G{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof G?e.clone():e)),t}get length(){return this.doc??my(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new pb(this,e)}querySelector(e){e=e.toUpperCase();let t=new pb(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),kp(new pb(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Cy(this,e,new _b(this,t,e))}toString(){return Oy(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),Dy(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):W(this.doc,n=>{Ny(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)W(this.doc,n=>{let r=e&&e instanceof G?e._item:e;jy(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw Om(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):W(this.doc,n=>{Fy(n,this,e,t)})}toArray(){return Ty(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Ay(this,e)}slice(e=0,t=this.length){return wy(this,e,t)}forEach(e){Dy(this,e)}_write(e){e.writeTypeRef(qb)}},hb=e=>new mb,K=class e extends mb{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return dh(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof G?e.Line truncated
|
||||
`).map(e=>e.trim()===``?`>`:`> ${e}`);n.push(i.join(`
|
||||
`))}),n.join(`
|
||||
>
|
||||
`)},addCommands(){return{setBlockquote:()=>({commands:e})=>e.wrapIn(this.name),toggleBlockquote:()=>({commands:e})=>e.toggleWrap(this.name),unsetBlockquote:()=>({commands:e})=>e.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote(),Backspace:()=>Aw(this.editor,this.type)}},addInputRules(){return[vp({find:jw,type:this.type})]}}),Nw=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,Pw=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,Fw=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,Iw=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,Lw=Gf.create({name:`bold`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`strong`},{tag:`b`,getAttrs:e=>e.style.fontWeight!==`normal`&&null},{style:`font-weight=400`,clearMark:e=>e.type.name===this.name},{style:`font-weight`,getAttrs:e=>/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}]},renderHTML({HTMLAttributes:e}){return kw(`strong`,{...P(this.options.HTMLAttributes,e),children:kw(`slot`,{})})},markdownTokenName:`strong`,parseMarkdown:(e,t)=>t.applyMark(`bold`,t.parseInline(e.tokens||[])),markdownOptions:{htmlReopen:{open:`<strong>`,close:`</strong>`}},renderMarkdown:(e,t)=>`**${t.renderChildren(e)}**`,addCommands(){return{setBold:()=>({commands:e})=>e.setMark(this.name),toggleBold:()=>({commands:e})=>e.toggleMark(this.name),unsetBold:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[hp({find:Nw,type:this.type}),hp({find:Fw,type:this.type})]},addPasteRules(){return[bp({find:Pw,type:this.type}),bp({find:Iw,type:this.type})]}}),Rw=e=>{let t=/`([^`]+)`(?!`)$/.exec(e);return!t||t.index>0&&e[t.index-1]==="`"?null:{index:t.index,text:t[0],replaceWith:t[1]}},zw=e=>{let t=/`([^`]+)`(?!`)/g,n=[],r;for(;(r=t.exec(e))!==null;)r.index>0&&e[r.index-1]==="`"||n.push({index:r.index,text:r[0],replaceWith:r[1]});return n};function Bw(e){let t=new Set((e.match(/`+/g)||[]).map(e=>e.length)),n=1;for(;t.has(n);)n+=1;return n}var Vw=Gf.create({name:`code`,addOptions(){return{HTMLAttributes:{}}},excludes:`_`,code:!0,exitable:!0,parseHTML(){return[{tag:`code`}]},renderHTML({HTMLAttributes:e}){return[`code`,P(this.options.HTMLAttributes,e),0]},markdownTokenName:`codespan`,parseMarkdown:(e,t)=>t.applyMark(`code`,[{type:`text`,text:e.text||``}]),renderMarkdown:(e,t,n)=>{var r;if(!e.content)return``;let i=typeof(n==null||(r=n.meta)==null?void 0:r.markText)==`string`?n.meta.markText:``,a="`".repeat(Bw(i)),o=i.startsWith("`")||i.endsWith("`")?` `:``;return`${a}${o}${t.renderChildren(e.content)}${o}${a}`},addCommands(){return{setCode:()=>({commands:e})=>e.setMark(this.name),toggleCode:()=>({commands:e})=>e.toggleMark(this.name),unsetCode:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[hp({find:Rw,type:this.type})]},addPasteRules(){return[bp({find:zw,type:this.type})]}}),Hw=4,Uw=/^```([a-z]+)?[\s\n]$/,Ww=/^~~~([a-z]+)?[\s\n]$/,Gw=yp.create({name:`codeBlock`,addOptions(){return{languageClassPrefix:`language-`,exitOnTripleEnter:!0,exitOnArrowDown:!0,exitOnArrowUp:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:Hw,HTMLAttributes:{}}},content:`text*`,marks:``,group:`block`,code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:e=>{let{languageClassPrefix:t}=this.options;return t&&[...e.firstElementChild?.classList||[]].filter(e=>e.startsWith(t)).map(e=>e.replace(t,``))[0]||null},rendered:!1}}},parseHTML(){return[{tag:`pre`,preserveWhitespace:`full`}]},renderHTML({node:e,HTMLAttributes:t}){return[`pre`,P(this.options.HTMLAttributes,t),[`code`,{class:e.attrs.language?this.options.languageClassPrefix+e.attrs.language:null},0]]},markdownTokenName:`code`,parseMarkdown:(e,t)=>e.raw?.startsWith("```")===!1&&e.raw?.startsWith(`~~~`)===!1&&e.codeBlockStyle!==`indented`?[]:t.createNode(`codeBlock`,{language:e.lang||null},e.text?[t.createTextNode(e.text)]:[]),renderMarkdown:(e,t)=>{let n=``,r=e.attrs?.language||``;return n=e.content?[`\`\`\`${r}`,t.renderChildren(e.content),"```"].join(`
|
||||
`):`\`\`\`${r}\n\n\`\`\``,n},addCommands(){return{setCodeBlock:e=>({commands:t})=>t.setNode(this.name,e),toggleCodeBlock:e=>({commands:t})=>t.toggleNode(this.name,`paragraph`,e)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{let{empty:e,$anchor:t}=this.editor.state.selection,n=t.pos===1;return!e||t.parent.type.name!==this.name?!1:n||!t.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:e})=>{if(!this.options.enableTabIndentation)return!1;let t=this.options.tabSize??Hw,{state:n}=e,{selection:r}=n,{$from:i,empty:a}=r;if(i.parent.type!==this.type)return!1;let o=` `.repeat(t);return a?e.commands.insertContent(o):e.commands.command(({tr:e})=>{let{from:t,to:i}=r,a=n.doc.textBetween(t,i,`
|
||||
`,`
|
||||
`).split(`
|
||||
`).map(e=>o+e).join(`
|
||||
`);return e.replaceWith(t,i,n.schema.text(a)),!0})},"Shift-Tab":({editor:e})=>{if(!this.options.enableTabIndentation)return!1;let t=this.options.tabSize??Hw,{state:n}=e,{selection:r}=n,{$from:i,empty:a}=r;return i.parent.type===this.type?a?e.commands.command(({tr:e})=>{let{pos:r}=i,a=i.start(),o=i.end(),s=n.doc.textBetween(a,o,`
|
||||
`,`
|
||||
`).split(`
|
||||
`),c=0,l=0,u=r-a;for(let e=0;e<s.length;e+=1){if(l+s[e].length>=u){c=e;break}l+=s[e].length+1}let d=s[c].match(/^ */)?.[0]||``,f=Math.min(d.length,t);if(f===0)return!0;let p=a;for(let e=0;e<c;e+=1)p+=s[e].length+1;return e.delete(p,p+f),r-p<=f&&e.setSelection(C.create(e.doc,p)),!0}):e.commands.command(({tr:e})=>{let{from:i,to:a}=r,o=n.doc.textBetween(i,a,`
|
||||
`,`
|
||||
`).split(`
|
||||
`).map(e=>{let n=e.match(/^ */)?.[0]||``,r=Math.min(n.length,t);return e.slice(r)}).join(`
|
||||
`);return e.replaceWith(i,a,n.schema.text(o)),!0}):!1},Enter:({editor:e})=>{if(!this.options.exitOnTripleEnter)return!1;let{state:t}=e,{selection:n}=t,{$from:r,empty:i}=n;if(!i||r.parent.type!==this.type)return!1;let a=r.parentOffset===r.parent.nodeSize-2,o=r.parent.textContent.endsWith(`
|
||||
|
||||
`);return!a||!o?!1:e.chain().command(({tr:e})=>(e.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowUp:({editor:e})=>{if(!this.options.exitOnArrowUp)return!1;let{state:t}=e,{selection:n}=t,{$from:r,empty:i}=n;if(!i||r.parent.type!==this.type||r.parentOffset!==0)return!1;let a=r.before();return a>0?!1:e.commands.insertDefaultBlock({pos:a})},ArrowDown:({editor:e})=>{if(!this.options.exitOnArrowDown)return!1;let{state:t}=e,{selection:n,doc:r}=t,{$from:i,empty:a}=n;if(!a||i.parent.type!==this.type||i.parentOffset!==i.parent.nodeSize-2)return!1;let o=i.after();return o===void 0?!1:r.nodeAt(o)?e.commands.command(({tr:e})=>(e.setSelection(S.near(r.resolve(o))),!0)):e.commands.exitCode()}}},addInputRules(){return[_p({find:Uw,type:this.type,getAttributes:e=>({language:e[1]})}),_p({find:Ww,type:this.type,getAttributes:e=>({language:e[1]})})]},addProseMirrorPlugins(){return[new T({key:new E(`codeBlockVSCodeHandler`),props:{handlePaste:(e,t)=>{if(!t.clipboardData||this.editor.isActive(this.type.name))return!1;let n=t.clipboardData.getData(`text/plain`),r=t.clipboardData.getData(`vscode-editor-data`),i=(r?JSON.parse(r):void 0)?.mode;if(!n||!i)return!1;let{tr:a,schema:o}=e.state,s=o.text(n.replace(/\r\n?/g,`
|
||||
`));return a.replaceSelectionWith(this.type.create({language:i},s)),a.selection.$from.parent.type!==this.type&&a.setSelection(C.near(a.doc.resolve(Math.max(0,a.selection.from-2)))),a.setMeta(`paste`,!0),e.dispatch(a),!0}}})]}}),Kw=yp.create({name:`doc`,topNode:!0,content:`block+`,renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,`
|
||||
|
||||
`):``}),qw=yp.create({name:`hardBreak`,markdownTokenName:`br`,addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:`inline`,selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:`br`}]},renderHTML({HTMLAttributes:e}){return[`br`,P(this.options.HTMLAttributes,e)]},renderText(){return`
|
||||
`},renderMarkdown:()=>`
|
||||
`,parseMarkdown:()=>({type:`hardBreak`}),addCommands(){return{setHardBreak:()=>({commands:e,chain:t,state:n,editor:r})=>e.first([()=>e.exitCode(),()=>e.command(()=>{let{selection:e,storedMarks:i}=n;if(e.$from.parent.type.spec.isolating)return!1;let{keepMarks:a}=this.options,{splittableMarks:o}=r.extensionManager,s=i||e.$to.parentOffset&&e.$from.marks();return t().insertContent({type:this.name}).command(({tr:e,dispatch:t})=>{if(t&&s&&a){let t=s.filter(e=>o.includes(e.type.name));e.ensureMarks(t)}return!0}).scrollIntoView().run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),Jw=yp.create({name:`heading`,addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:`inline*`,group:`block`,defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(e=>({tag:`h${e}`,attrs:{level:e}}))},renderHTML({node:e,HTMLAttributes:t}){return[`h${this.options.levels.includes(e.attrs.level)?e.attrs.level:this.options.levels[0]}`,P(this.options.HTMLAttributes,t),0]},parseMarkdown(e,t){let n=e.depth||1;return this.options.levels.includes(n)?t.createNode(`heading`,{level:n},t.parseInline(e.tokens||[])):t.createNode(`paragraph`,void 0,t.parseInline(e.tokens||[]))},renderMarkdown:(e,t)=>{let n=e.attrs?.level?parseInt(e.attrs.level,10):1,r=`#`.repeat(n);return e.content?`${r} ${t.renderChildren(e.content)}`:``},addCommands(){return{setHeading:e=>({commands:t})=>this.options.levels.includes(e.level)?t.setNode(this.name,e):!1,toggleHeading:e=>({commands:t})=>this.options.levels.includes(e.level)?t.toggleNode(this.name,`paragraph`,e):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((e,t)=>({...e,[`Mod-Alt-${t}`]:()=>this.editor.commands.toggleHeading({level:t})}),{})},addInputRules(){return this.options.levels.map(e=>_p({find:RegExp(`^(#{${Math.min(...this.options.levels)},${e}})\\s$`),type:this.type,getAttributes:{level:e}}))}}),Yw=yp.create({name:`horizontalRule`,addOptions(){return{HTMLAttributes:{},nextNodeType:`paragraph`}},group:`block`,parseHTML(){return[{tag:`hr`}]},renderHTML({HTMLAttributes:e}){return[`hr`,P(this.options.HTMLAttributes,e)]},markdownTokenName:`hr`,parseMarkdown:(e,t)=>t.createNode(`horizontalRule`),renderMarkdown:()=>`---`,addCommands(){return{setHorizontalRule:()=>({chain:e,state:t})=>{if(!Sf(t,t.schema.nodes[this.name]))return!1;let{selection:n}=t,{$to:r}=n,i=e();return cd(n)?i.insertContentAt(r.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:e,tr:t,dispatch:n})=>{if(n){let{$to:n}=t.selection,r=n.end();if(n.nodeAfter)n.nodeAfter.isTextblock?t.setSelection(C.create(t.doc,n.pos+1)):n.nodeAfter.isBlock?t.setSelection(w.create(t.doc,n.pos)):t.setSelection(C.create(t.doc,n.pos));else{let i=(e.schema.nodes[this.options.nextNodeType]||n.parent.type.contentMatch.defaultType)?.create();i&&(t.insert(r,i),t.setSelection(C.create(t.doc,r+1)))}t.scrollIntoView()}return!0}).run()}}},addInputRules(){return[gp({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),Xw=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Zw=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Qw=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,$w=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,eT=Gf.create({name:`italic`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`em`},{tag:`i`,getAttrs:e=>e.style.fontStyle!==`normal`&&null},{style:`font-style=normal`,clearMark:e=>e.type.name===this.name},{style:`font-style=italic`}]},renderHTML({HTMLAttributes:e}){return[`em`,P(this.options.HTMLAttributes,e),0]},addCommands(){return{setItalic:()=>({commands:e})=>e.setMark(this.name),toggleItalic:()=>({commands:e})=>e.toggleMark(this.name),unsetItalic:()=>({commands:e})=>e.unsetMark(this.name)}},markdownTokenName:`em`,parseMarkdown:(e,t)=>t.applyMark(`italic`,t.parseInline(e.tokens||[])),markdownOptions:{htmlReopen:{open:`<em>`,close:`</em>`}},renderMarkdown:(e,t)=>`*${t.renderChildren(e)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[hp({find:Xw,type:this.type}),hp({find:Qw,type:this.type})]},addPasteRules(){return[bp({find:Zw,type:this.type}),bp({find:$w,type:this.type})]}}),tT=`aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zLine truncated
|
||||
`,DE=`️`,OE=``,kE=``,AE=null,jE=null;function ME(e=[]){let t={};gT.groups=t;let n=new gT;AE??=IE(tT),jE??=IE(nT),Q(n,`'`,qT),Q(n,`{`,AT),Q(n,`}`,jT),Q(n,`[`,MT),Q(n,`]`,NT),Q(n,`(`,PT),Q(n,`)`,FT),Q(n,`<`,IT),Q(n,`>`,LT),Q(n,`(`,RT),Q(n,`)`,zT),Q(n,`「`,BT),Q(n,`」`,VT),Q(n,`『`,HT),Q(n,`』`,UT),Q(n,`<`,WT),Q(n,`>`,GT),Q(n,`&`,KT),Q(n,`*`,JT),Q(n,`@`,YT),Q(n,"`",ZT),Q(n,`^`,QT),Q(n,`:`,$T),Q(n,`,`,eE),Q(n,`$`,tE),Q(n,`.`,nE),Q(n,`=`,rE),Q(n,`!`,iE),Q(n,`-`,aE),Q(n,`%`,oE),Q(n,`|`,sE),Q(n,`+`,cE),Q(n,`#`,lE),Q(n,`?`,uE),Q(n,`"`,dE),Q(n,`/`,mE),Q(n,`;`,pE),Q(n,`~`,hE),Q(n,`_`,gE),Q(n,`\\`,XT),Q(n,`・`,fE);let r=Z(n,CE,DT,{[rT]:!0});Z(r,CE,r);let i=Z(r,bE,bT,{[oT]:!0}),a=Z(r,xE,xT,{[sT]:!0}),o=Z(n,bE,vT,{[iT]:!0});Z(o,CE,i),Z(o,bE,o),Z(i,CE,i),Z(i,bE,i);let s=Z(n,xE,yT,{[aT]:!0});Z(s,bE),Z(s,CE,a),Z(s,xE,s),Z(a,CE,a),Z(a,bE),Z(a,xE,a);let c=Q(n,EE,kT,{[fT]:!0}),l=Q(n,TE,OT,{[fT]:!0}),u=Z(n,wE,OT,{[fT]:!0});Q(n,kE,u),Q(l,EE,c),Q(l,kE,u),Z(l,wE,u),Q(u,TE),Q(u,EE),Z(u,wE,u),Q(u,kE,u);let d=Z(n,SE,_E,{[lT]:!0});Q(d,`#`),Z(d,SE,d),Q(d,DE,d);let f=Q(d,OE);Q(f,`#`),Z(f,SE,d);let p=[[bE,o],[CE,i]],m=[[bE,null],[xE,s],[CE,a]];for(let e=0;e<AE.length;e++)FE(n,AE[e],CT,vT,p);for(let e=0;e<jE.length;e++)FE(n,jE[e],wT,yT,m);mT(CT,{tld:!0,ascii:!0},t),mT(wT,{utld:!0,alpha:!0},t),FE(n,`file`,TT,vT,p),FE(n,`mailto`,TT,vT,p),FE(n,`http`,ET,vT,p),FE(n,`https`,ET,vT,p),FE(n,`ftp`,ET,vT,p),FE(n,`ftps`,ET,vT,p),mT(TT,{scheme:!0,ascii:!0},t),mT(ET,{slashscheme:!0,ascii:!0},t),e=e.sort((e,t)=>e[0]>t[0]?1:-1);for(let t=0;t<e.length;t++){let r=e[t][0],i=e[t][1]?{[uT]:!0}:{[dT]:!0};r.indexOf(`-`)>=0?i[cT]=!0:bE.test(r)?CE.test(r)?i[oT]=!0:i[iT]=!0:i[rT]=!0,_T(n,r,r,i)}return _T(n,`localhost`,ST,{ascii:!0}),n.jd=new gT(vE),{start:n,tokens:Object.assign({groups:t},yE)}}function NE(e,t){let n=PE(t.replace(/[A-Z]/g,e=>e.toLowerCase())),r=n.length,i=[],a=0,o=0;for(;o<r;){let s=e,c=null,l=0,u=null,d=-1,f=-1;for(;o<r&&(c=s.go(n[o]));)s=c,s.accepts()?(d=0,f=0,u=s):d>=0&&(d+=n[o].length,f++),l+=n[o].length,a+=n[o].length,o++;a-=d,o-=f,l-=d,i.push({t:u.t,v:t.slice(a-l,a),s:a-l,e:a})}return i}function PE(e){let t=[],n=e.length,r=0;for(;r<n;){let i=e.charCodeAt(r),a,o=i<55296||i>56319||r+1===n||(a=e.charCodeAt(r+1))<56320||a>57343?e[r]:e.slice(r,r+2);t.push(o),r+=o.length}return t}function FE(e,t,n,r,i){let a,o=t.length;for(let n=0;n<o-1;n++){let o=t[n];e.j[o]?a=e.j[o]:(a=new gT(r),a.jr=i.slice(),e.j[o]=a),e=a}return a=new gT(n),a.jr=i.slice(),e.j[t[o-1]]=a,a}function IE(e){let t=[],n=[],r=0;for(;r<e.length;){let i=0;for(;`0123456789`.indexOf(e[r+i])>=0;)i++;if(i>0){t.push(n.join(``));for(let t=parseInt(e.substring(r,r+i),10);t>0;t--)n.pop();r+=i}else n.push(e[r]),r++}return t}var LE={defaultProtocol:`http`,events:null,format:zE,formatHref:zE,nl2br:!1,tagName:`a`,target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],ignoreClasses:[],render:null};function RE(e,t=null){let n=Object.assign({},LE);e&&(n=Object.assign(n,e instanceof RE?e.o:e));let r=n.ignoreTags,i=[];for(let e=0;e<r.length;e++)i.push(r[e].toUpperCase());this.o=n,t&&(this.defaultRender=t),this.ignoreTags=i,this.ignoreClasses=n.ignoreClasses.slice()}RE.prototype={o:LE,ignoreTags:[],ignoreClasses:[],isIgnoredClass(e){if(typeof e!=`string`||this.ignoreClasses.length===0)return!1;let t=e.split(/\s+/);for(let e=0;e<t.length;e++)if(this.ignoreClasses.indexOf(t[e])>=0)return!0;return!1},defaultRender(e){return e},check(e){return this.get(`validate`,e.toString(),e)},get(e,t,n){let r=t!=null,i=this.o[e];return i&&(typeof i==`object`?(i=n.t in i?i[n.t]:LE[e],typeof i==`function`&&r&&(i=i(t,n))):typeof i==`function`&&r&&(i=i(t,n.t,n)),i)},getObj(e,t,n){let r=this.o[e];return typeof r==`function`&&t!=null&&(r=r(t,n.t,n)),r},render(e){let t=e.render(this);return(this.get(`render`,null,e)||this.defaultRender)(t,e.t,e)}};function zE(e){return e}function BE(e,t){this.t=`token`,this.v=e,this.tk=t}BE.prototype={isLink:!1,toString(){return this.v},toHref(e){return this.toString()},toFormattedString(e){let t=this.toString(),n=e.get(`truncate`,t,this),r=e.get(`format`,t,this);return n&&r.length>n?r.substring(0,n)+`…`:r},toFormattedHref(e){return e.get(`formatHref`,this.toHref(e.get(`defaultProtocol`)),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(e=LE.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(e),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(e){return{type:this.t,value:this.toFormattedString(e),isLink:this.isLink,href:this.toFormattedHref(e),start:this.startIndex(),end:this.endIndex()}},validate(e){return e.get(`validate`,this.toString(),this)},render(e){let t=this,n=this.toHref(e.get(`defaultProtocol`)),r=e.get(`formatHref`,n,this),i=e.get(`tagName`,n,t),a=this.toFormattedString(e),o={},s=e.get(`className`,n,t),c=e.get(`target`,n,t),l=e.get(`rel`,n,t),u=e.getObj(`attributes`,n,t),d=e.getObj(`events`,n,t);return o.href=r,s&&(o.clLine truncated
|
||||
1. Must only contain digits, lowercase ASCII letters or "-"
|
||||
2. Cannot start or end with "-"
|
||||
3. "-" cannot repeat`);$.customSchemes.push([e,t])}function eD(){$.scanner=ME($.customSchemes);for(let e=0;e<$.tokenQueue.length;e++)$.tokenQueue[e][1]({scanner:$.scanner});$.parser=qE($.scanner.tokens);for(let e=0;e<$.pluginQueue.length;e++)$.pluginQueue[e][1]({scanner:$.scanner,parser:$.parser});return $.initialized=!0,$}function tD(e){return $.initialized||eD(),JE($.parser.start,e,NE($.scanner.start,e))}tD.scan=NE;function nD(e,t=null,n=null){if(t&&typeof t==`object`){if(n)throw Error(`linkifyjs: Invalid link type ${t}; must be a string`);n=t,t=null}let r=new RE(n),i=tD(e),a=[];for(let e=0;e<i.length;e++){let n=i[e];n.isLink&&(!t||n.t===t)&&r.check(n)&&a.push(n.toFormattedObject(r))}return a}var rD=`[\0- \xA0 -\u2029 ]`,iD=new RegExp(rD),aD=RegExp(`${rD}$`),oD=RegExp(`${rD}+$`),sD=new RegExp(rD,`g`);function cD(e,t,n){let r=e.doc.resolve(t.to);if(!r.nodeBefore?.isText)return;let i=e.doc.textBetween(t.from,t.to,``,``).match(oD)?.[0];if(!i)return;let a=t.to-i.length,o=Yu(a,t.to,e.doc).filter(e=>e.mark.type===n);if(!o.length)return;let{nodeAfter:s}=r;if(s&&o.some(e=>e.mark.isInSet(s.marks)))return;let c=e.storedMarks;e.removeMark(a,t.to,n),e.setStoredMarks(c),e.selection.empty&&e.selection.from===t.to&&e.removeStoredMark(n)}function lD(e){return e.length===1?e[0].isLink:e.length===3&&e[1].isLink?[`()`,`[]`].includes(e[0].value+e[2].value):!1}function uD(e){return new T({key:new E(`autolink`),appendTransaction:(t,n,r)=>{let i=t.some(e=>e.docChanged)&&!n.doc.eq(r.doc),a=t.some(e=>e.getMeta(`preventAutolink`));if(!i||a)return;let{tr:o}=r,s=fu(n.doc,[...t]);if(!t.some(Kc)){let t=[];s.steps.forEach((e,n)=>{if(!(e instanceof Ot)||!e.slice.size)return;let r=s.mapping.slice(n+1),i=r.map(e.from,1),a=r.map(e.from+e.slice.size,-1);i<a&&t.push({from:i,to:a})}),t.sort((e,t)=>t.to-e.to),t.forEach(t=>cD(o,t,e.type))}if(Ju(s).forEach(({newRange:t})=>{let n=pu(r.doc,t,e=>e.isTextblock),i,a;if(n.length>1)i=n[0],a=r.doc.textBetween(i.pos,i.pos+i.node.nodeSize,void 0,` `);else if(n.length){let e=r.doc.textBetween(t.from,t.to,` `,` `);if(!aD.test(e))return;i=n[0],a=r.doc.textBetween(i.pos,t.to,void 0,` `)}if(i&&a){let t=a.split(iD).filter(Boolean);if(t.length<=0)return!1;let n=t[t.length-1],s=i.pos+a.lastIndexOf(n);if(!n)return!1;let c=tD(n).map(t=>t.toObject(e.defaultProtocol));if(!lD(c))return!1;c.filter(e=>e.isLink).map(e=>({...e,from:s+e.start+1,to:s+e.end+1})).filter(e=>!r.schema.marks.code||!r.doc.rangeHasMark(e.from,e.to,r.schema.marks.code)).filter(t=>e.validate(t.value)).filter(t=>e.shouldAutoLink(t.value)).forEach(t=>{Yu(t.from,t.to,r.doc).some(t=>t.mark.type===e.type)||o.addMark(t.from,t.to,e.type.create({href:t.href}))})}}),o.steps.length)return o}})}function dD(e){return new T({key:new E(`handleClickLink`),props:{handleClick:(t,n,r)=>{if(r.button!==0||!t.editable)return!1;let i=null;if(r.target instanceof HTMLAnchorElement)i=r.target;else{let t=r.target;if(!t)return!1;let n=e.editor.view.dom;i=t.closest(`a`),i&&!n.contains(i)&&(i=null)}if(!i)return!1;let a=!1;if(e.enableClickSelection&&(a=e.editor.commands.extendMarkRange(e.type.name)),e.openOnClick){let n=Gu(t.state,e.type.name),r=i.href??n.href,o=i.target??n.target;r&&(window.open(r,o),a=!0)}return a}}})}var fD=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)$/,pD=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)/g;function mD(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;--r)n+=1;return n%2==1}function hD(e,t){let n=0,r=0;for(;r<t;){if(e[r]!=="`"||n===0&&mD(e,r)){r+=1;continue}let i=0;for(;r<t&&e[r]==="`";)i+=1,r+=1;n===0?n=i:i===n&&(n=0)}return n>0}function gD(e,t,n){let[,r,i]=t;return(t.index?e[t.index-1]:void 0)===`!`||mD(e,t.index??0)||hD(e,t.index??0)?!1:!!r.trim()&&n(i)}function _D(e){let[t,n,r,,i,a,o]=e,s=i??a??o;return{index:e.index??0,text:t,replaceWith:n,data:{href:r,title:s||null,markdown:!0}}}function vD(e,t){return e.index<t.index+t.text.length&&t.index<e.index+e.text.length}function yD(e){return{href:e.data?.href,title:e.data?.title??null}}function bD(e){let t=hp({find:t=>{let n=fD.exec(t);return!n||!gD(t,n,e.isAllowedHref)?null:_D(n)},type:e.type,getAttributes:yD});return new Lf({find:t.find,handler:e=>{let n=t.handler(e);return n!==null&&e.state.tr.steps.length&&e.state.tr.setMeta(`preventAutolink`,!0),n}})}function xD(e){let t=bp({find:t=>{let n=[];for(let r of t.matchAll(pD))gD(t,r,e.isAllowedHref)&&n.push(_D(r));let r=(e.findPlainUrls?.call(e,t)??[]).filter(e=>!n.some(t=>vD(t,e)));return[...n,...r]},type:e.type,getAttributes:yD});return new Kf({find:t.find,handler:e=>{let n=t.handler(e);return n!==null&&e.state.tr.steps.length&&e.match.data?.markdown&&e.state.tr.setMeta(`preventAutolink`,!0),n}})}function SD(e){return new T({key:new E(`handlePasteLink`),props:{handlePaste:(t,n,r)=>{let{shouldAutoLink:i}=e,{state:a}=t,{selection:o}=a,{empty:s}=o;if(s)return!1;let c=``;r.content.forEach(e=>{c+=e.textContent});let l=nD(c,{defaultProtocol:Line truncated
|
||||
`):``,markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(TD,this.editor.getAttributes(ED)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let e=vp({find:DD,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(e=vp({find:DD,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(ED),editor:this.editor})),[e]}}),kD=(e,t,n)=>{let{selection:r}=e;if(!r.empty)return null;let{$from:i}=r;if(!i.parent.isTextblock||i.parentOffset!==i.parent.content.size)return null;let a=-1;for(let e=i.depth;e>0;--e)if(i.node(e).type.name===t){a=e;break}if(a<0)return null;let o=i.node(a),s=i.index(a);if(s+1>=o.childCount)return null;let c=o.child(s+1);if(!n.includes(c.type.name))return null;let l=e.schema.nodes[t],u=!1;if(c.forEach(e=>{e.type===l&&e.childCount>1&&(u=!0)}),!u)return null;let d=e.doc.resolve(i.after()).nodeAfter;if(!d||!n.includes(d.type.name))return null;let f=[];return d.forEach(e=>{f.push(e)}),f.length===0?null:{listItemDepth:a,nestedList:d,nestedListPos:i.after(),insertPos:i.after(a),items:f}},AD=(e,t,n,r)=>{let i=kD(e,n,r);if(!i)return!1;let{selection:a}=e,{nestedList:o,nestedListPos:c,insertPos:l,items:u}=i,d=e.tr;d.delete(c,c+o.nodeSize);let f=d.mapping.map(l);return d.insert(f,s.from(u)),d.setSelection(a.map(d.doc,d.mapping)),t&&t(d),!0},jD=(e,t,n)=>AD(e.state,e.view.dispatch,t,n),MD=(e,t)=>F.create({name:`${e}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){let n=()=>jD(this.editor,e,t);return{Delete:n,"Mod-Delete":n}}}),ND=[[1e3,`m`],[900,`cm`],[500,`d`],[400,`cd`],[100,`c`],[90,`xc`],[50,`l`],[40,`xl`],[10,`x`],[9,`ix`],[5,`v`],[4,`iv`],[1,`i`]],PD=`abcdefghijklmnopqrstuvwxyz`,FD=String.raw`\d+|[ivxlcdmIVXLCDM]+|${`[a-zA-Z]{1,2}`}`;function ID(e){let t=e,n=``;for(let[e,r]of ND)for(;t>=e;)n+=r,t-=e;return n}function LD(e){return ID(e).toUpperCase()}function RD(e){let t=e.toLowerCase(),n=0,r=0;for(;n<t.length;){let e=!1;for(let[i,a]of ND)if(t.startsWith(a,n)){r+=i,n+=a.length,e=!0;break}if(!e)return 0}return r}function zD(e){if(!/^[ivxlcdmIVXLCDM]+$/.test(e))return!1;let t=RD(e);return t<=0?!1:(e===e.toLowerCase()?ID(t):LD(t))===e}function BD(e){let t=e.toLowerCase();if(t.length===1)return t.charCodeAt(0)-97+1;if(t.length===2){let e=t.charCodeAt(0)-97,n=t.charCodeAt(1)-97;return(e+1)*26+n+1}return 0}function VD(e){if(e<=26)return PD[e-1];let t=Math.floor((e-1)/26)-1,n=(e-1)%26;return t<0?PD[n]:PD[t]+PD[n]}function HD(e){if(e&&!/^\d+$/.test(e)){if(zD(e))return e===e.toLowerCase()?`i`:`I`;if(/^[a-z]{1,2}$/.test(e))return`a`;if(/^[A-Z]{1,2}$/.test(e))return`A`}}function UD(e){if(/^\d+$/.test(e))return parseInt(e,10);let t=HD(e);if(t===`i`||t===`I`)return RD(e);if(t===`a`||t===`A`){let t=BD(e);return t>0?t:1}let n=parseInt(e,10);return Number.isNaN(n)?1:n}function WD(e,t){if(e===`numeric`)return String(t);switch(e){case`a`:return VD(t);case`A`:return VD(t).toUpperCase();case`i`:return ID(t);case`I`:return LD(t);default:return String(t)}}function GD(e){if(e.length===0)return!1;let t=HD(e[0])??`numeric`,n=UD(e[0]);if(n<1)return!1;for(let r=0;r<e.length;r++){let i=WD(t,n+r);if(e[r]!==i)return!1}return!0}function KD(e){return{type:HD(e),start:UD(e)}}function qD(e){let{type:t,start:n}=KD(e),r={};return t&&(r.type=t),n!==1&&(r.start=n),r}function JD(e,t,n=`. `){let r=t+1;if(!e||e===`1`)return`${r}${n}`;switch(e){case`a`:return`${VD(r)}${n}`;case`A`:return`${VD(r).toUpperCase()}${n}`;case`i`:return`${ID(r)}${n}`;case`I`:return`${LD(r)}${n}`;default:return`${r}${n}`}}function YD(e){return!e[0]||e[0].type===`paragraph`?e:[{type:`paragraph`,content:[]},...e]}function XD(e){let t=e.content?.[0];return t?.type===`paragraph`&&!t.content?.length}var ZD=` `,QD=1,$D=e=>(e?.level??QD)>QD;function eO(e){let t=e.tokens?.[0];return!!(e.text&&e.tokens?.length===1&&t?.type===`list`&&t.ordered&&t.raw===e.text)}function tO(e,t){return t.tokenizeInline?t.parseInline(t.tokenizeInline(e)):t.parseInline([{type:`text`,raw:e,text:e}])}var nO=yp.create({name:`listItem`,addOptions(){return{HTMLAttributes:{},bulletListTypeName:`bulletList`,orderedListTypeName:`orderedList`}},content:`paragraph block*`,defining:!0,parseHTML(){return[{tag:`li`}]},renderHTML({HTMLAttributes:e}){return[`li`,P(this.options.HTMLAttributes,e),0]},markdownTokenName:`list_item`,parseMarkdown:(e,t)=>{if(e.type!==`list_item`)return[];let n=t.parseBlockChildren??t.parseChildren,r=[];if(e.tokens&&e.tokens.length>0){if(eO(e))return{type:`listItem`,content:[{type:`paragraph`,content:tO(e.text||``,t)}]};let[i,...a]=e.tokens;if(i.type===`heading`)return{type:`listItem`,content:[{type:`paragraph`,content:t.parseInline(i.tokens??[])},...a.length>0?n(a):[]]};Line truncated
|
||||
`).trim(),contentLines:m,raw:g.join(`
|
||||
`)}),r=h,n=h}return[t,r]}var bO=RegExp(`^(${FD})([.)])\\s+(.+)$`);function xO(e){let t=e.split(`
|
||||
`).filter(e=>e.trim().length>0);if(t.length===0)return null;let n=[];for(let e of t){let t=e.trim().match(bO);if(!t)return null;n.push({marker:t[1],content:t[3]})}return GD(n.map(e=>e.marker))?{type:`orderedList`,attrs:qD(n[0].marker),content:n.map(e=>({type:`listItem`,content:[{type:`paragraph`,content:[{type:`text`,text:e.content}]}]}))}:null}function SO(e,t,n){let r=[],i=0;for(;i<e.length;){let a=e[i];if(a.indent===t){let{paragraphLines:o,blockLines:s}=vO(a.contentLines),c=o.join(`
|
||||
`).trim(),l=[];c&&l.push({type:`paragraph`,raw:c,tokens:n.inlineTokens(c)});let u=s.join(`
|
||||
`).trim();if(u){let e=n.blockTokens(u);l.push(...e)}let d=i+1,f=[];for(;d<e.length&&e[d].indent>t;)f.push(e[d]),d+=1;if(f.length>0){let e=SO(f,Math.min(...f.map(e=>e.indent)),n);l.push({type:`list`,ordered:!0,start:f[0].number,typeMarker:f[0].type,items:e,raw:f.map(e=>e.raw).join(`
|
||||
`)})}r.push({type:`list_item`,raw:a.raw,tokens:l}),i=d}else i+=1}return r}function CO(e,t){return e.map(e=>{if(e.type!==`list_item`)return t.parseChildren([e])[0];let n=[];return e.tokens&&e.tokens.length>0&&e.tokens.forEach(e=>{if(e.type===`paragraph`||e.type===`list`||e.type===`blockquote`||e.type===`code`)n.push(...t.parseChildren([e]));else if(e.type===`text`&&e.tokens){let r=t.parseChildren([e]);n.push({type:`paragraph`,content:r})}else{let r=t.parseChildren([e]);r.length>0&&n.push(...r)}}),{type:`listItem`,content:n}})}var wO=64;function TO(e,t){let n=[],r=0;for(;n.length<t;){let t=e.indexOf(`
|
||||
`,r);if(t===-1)return n.push(e.slice(r)),n;n.push(e.slice(r,t)),r=t+1}return n}function EO(e){let t=e.indexOf(`
|
||||
`),n=t===-1?e:e.slice(0,t);if(!fO.test(n))return[[],0,[]];let r=wO,i=TO(e,r),a=yO(i);for(;a[1]===i.length&&i.length===r;)r*=2,i=TO(e,r),a=yO(i);return[a[0],a[1],i]}var DO=`listItem`,OO=`textStyle`,kO=/^(\d+)\.\s$/;function AO(e){let t=e.match(/list-style-type\s*:\s*([^;]+)/i);if(!t)return null;switch(t[1].trim().toLowerCase()){case`upper-roman`:return`I`;case`lower-roman`:return`i`;case`upper-alpha`:case`upper-latin`:return`A`;case`lower-alpha`:case`lower-latin`:return`a`;default:return null}}var jO=yp.create({name:`orderedList`,addOptions(){return{itemTypeName:`listItem`,HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:`block list`,content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:e=>e.hasAttribute(`start`)?parseInt(e.getAttribute(`start`)||``,10):1},type:{default:null,parseHTML:e=>{let t=e.getAttribute(`type`);if(t)return t;let n=e.getAttribute(`style`);if(n){let e=AO(n);if(e)return e}let r=e.querySelector(`li`);if(r){let e=r.getAttribute(`style`);if(e){let t=AO(e);if(t)return t}}return null}}}},parseHTML(){return[{tag:`ol`}]},renderHTML({HTMLAttributes:e}){let{start:t,type:n,...r}=e,i=P(this.options.HTMLAttributes,r);return t!==1&&(i.start=t),n&&n!==`1`&&(i.type=n),[`ol`,i,0]},markdownTokenName:`list`,parseMarkdown:(e,t)=>{if(e.type!==`list`||!e.ordered)return[];let n=e.start||1,r=e.typeMarker,i=e.items?CO(e.items,t):[],a={};return n!==1&&(a.start=n),r&&(a.type=r),Object.keys(a).length>0?{type:`orderedList`,attrs:a,content:i}:{type:`orderedList`,content:i}},renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,`
|
||||
`):``,markdownTokenizer:{name:`orderedList`,level:`block`,start:()=>-1,tokenize:(e,t,n)=>{let[r,i,a]=EO(e);if(r.length===0)return;let o=SO(r,r[0].indent,n);if(o.length!==0)return{type:`list`,ordered:!0,start:r[0]?.number||1,typeMarker:r[0]?.type,items:o,raw:a.slice(0,i).join(`
|
||||
`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(DO,this.editor.getAttributes(OO)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addProseMirrorPlugins(){return[new T({props:{handlePaste:(e,t)=>{if((t.clipboardData?.getData(`text/html`))?.trim())return!1;let n=t.clipboardData?.getData(`text/plain`);if(!n)return!1;let r=xO(n);if(!r)return!1;try{let t=e.state.schema.nodeFromJSON(r),n=e.state.tr.replaceSelectionWith(t);return e.dispatch(n),!0}catch{return!1}}}})]},addInputRules(){let e=(e,t)=>(!t.attrs.type||t.attrs.type===`1`)&&t.childCount+t.attrs.start===+e[1],t=vp({find:kO,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:e});return(this.options.keepMarks||this.options.keepAttributes)&&(t=vp({find:kO,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(OO)}),joinPredicate:e,editor:this.editor})),[t]}}),MO=/^\s*(\[([( |x])?\])\s$/,NO=`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0`,PO=(e,t,n)=>{var r;return(n==null||(r=n.checkboxLabel)==null?void 0:r.call(n,e,t))||`Task item checkbox for ${e.textContent||`empty task item`}`},FO=yp.create({name:`taskItem`,addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:`taskList`,a11y:void 0}},content(){return this.options.nested?`paragraph block*`:`paragraph+`},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:e=>{let t=e.getAttribute(`data-checked`);return t===``||t===`true`},renderHTML:e=>({"data-checked":e.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51,contentElement:e=>e.querySelector(`div`)??e}]},renderHTML({node:e,HTMLAttributes:t}){return[`li`,P(this.options.HTMLAttributes,t,{"data-type":this.name}),[`label`,[`input`,{type:`checkbox`,checked:e.attrs.checked?`checked`:null}],[`span`]],[`div`,0]]},parseMarkdown:(e,t)=>{let n=[];if(e.tokens&&e.tokens.length>0?n.push(t.createNode(`paragraph`,{},t.parseInline(e.tokens))):e.text?n.push(t.createNode(`paragraph`,{},[t.createNode(`text`,{text:e.text})])):n.push(t.createNode(`paragraph`,{},[])),e.nestedTokens&&e.nestedTokens.length>0){let r=t.parseChildren(e.nestedTokens);n.push(...r)}return t.createNode(`taskItem`,{checked:e.checked||!1},n)},renderMarkdown:(e,t)=>Pf(e,t,`- [${e.attrs?.checked?`x`:` `}] `,void 0,{indentMainContent:!0}),addExtensions(){return this.options.nested?[MD(this.name,[this.options.taskListTypeName])]:[]},addKeyboardShortcuts(){let e={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...e,Tab:()=>this.editor.commands.sinkListItem(this.name)}:e},addNodeView(){return({node:e,HTMLAttributes:t,getPos:n,editor:r})=>{let i=document.createElement(`li`),a=document.createElement(`label`),o=document.createElement(`span`),s=document.createElement(`input`),c=document.createElement(`div`);o.style.cssText=NO;let l=e=>{let t=PO(e,e.attrs.checked,this.options.a11y);s.setAttribute(`aria-label`,t),o.textContent=t};l(e),a.contentEditable=`false`,s.type=`checkbox`,s.addEventListener(`mousedown`,e=>e.preventDefault()),s.addEventListener(`change`,t=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){s.checked=!s.checked;return}let{checked:i}=t.target;r.isEditable&&typeof n==`function`&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:e})=>{let t=n();if(typeof t!=`number`)return!1;let r=e.doc.nodeAt(t);return e.setNodeMarkup(t,void 0,{...r?.attrs,checked:i}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(e,i)||(s.checked=!s.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([e,t])=>{i.setAttribute(e,t)}),i.dataset.checked=e.attrs.checked,s.checked=e.attrs.checked,a.append(s,o),i.append(a,c),Object.entries(t).forEach(([e,t])=>{i.setAttribute(e,t)});let u=new Set(Object.keys(t));return{dom:i,contentDOM:c,update:e=>{if(e.type!==this.type)return!1;i.dataset.checked=e.attrs.checked,s.checked=e.attrs.checked,l(e);let t=r.extensionManager.attributes,n=Mu(e,t),a=new Set(Object.keys(n)),o=this.options.HTMLAttributes;return u.forEach(e=>{a.has(e)||(e in o?i.setAttribute(e,o[e]):i.removeAttribute(e))}),Object.entries(n).forEach(([e,t])=>{t==null?e in o?i.setAttribute(e,o[e]):i.removeAttribute(e):i.setAttribute(e,t)}),u=a,!0}}}},addInputRules(){return[vp({find:MO,type:this.type,getAttributes:e=>({checked:e[e.length-1]===`x`})})]}}),IO=yp.create({name:`taskList`,addOptions(){return{itemTypeName:`taskItem`,HTMLAttributes:{}}},group:`block list`,content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`uLine truncated
|
||||
`):``,markdownTokenizer:{name:`taskList`,level:`block`,start(e){let t=e.match(/^\s*[-+*]\s+\[([ xX])\]\s+/)?.index;return t===void 0?-1:t},tokenize(e,t,n){let r=e=>{let t=jf(e,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:e=>({indentLevel:e[1].length,mainContent:e[4],checked:e[3].toLowerCase()===`x`}),createToken:(e,t)=>({type:`taskItem`,raw:``,mainContent:e.mainContent,indentLevel:e.indentLevel,checked:e.checked,text:e.mainContent,tokens:n.inlineTokens(e.mainContent),nestedTokens:t}),customNestedParser:r},n);if(t){let r={type:`taskList`,raw:t.raw,items:t.items},i=e.slice(t.raw.length);return i.trim()?[r,...n.blockTokens(i)]:[r]}return n.blockTokens(e)},i=jf(e,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:e=>({indentLevel:e[1].length,mainContent:e[4],checked:e[3].toLowerCase()===`x`}),createToken:(e,t)=>({type:`taskItem`,raw:``,mainContent:e.mainContent,indentLevel:e.indentLevel,checked:e.checked,text:e.mainContent,tokens:n.inlineTokens(e.mainContent),nestedTokens:t}),customNestedParser:r},n);if(i)return{type:`taskList`,raw:i.raw,items:i.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:e})=>e.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});F.create({name:`listKit`,addExtensions(){let e=[];return this.options.bulletList!==!1&&e.push(OD.configure(this.options.bulletList)),this.options.listItem!==!1&&e.push(nO.configure(this.options.listItem)),this.options.listKeymap!==!1&&e.push(dO.configure(this.options.listKeymap)),this.options.orderedList!==!1&&e.push(jO.configure(this.options.orderedList)),this.options.taskItem!==!1&&e.push(FO.configure(this.options.taskItem)),this.options.taskList!==!1&&e.push(IO.configure(this.options.taskList)),e}});var LO=` `,RO=`\xA0`,zO=yp.create({name:`paragraph`,priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:`block`,content:`inline*`,parseHTML(){return[{tag:`p`}]},renderHTML({HTMLAttributes:e}){return[`p`,P(this.options.HTMLAttributes,e),0]},parseMarkdown:(e,t)=>{let n=e.tokens||[];if(n.length===1&&n[0].type===`image`)return t.parseChildren([n[0]]);let r=t.parseInline(n);return n.length===1&&n[0].type===`text`&&(n[0].raw===LO||n[0].text===LO||n[0].raw===RO||n[0].text===RO)&&r.length===1&&r[0].type===`text`&&(r[0].text===LO||r[0].text===RO)?t.createNode(`paragraph`,void 0,[]):t.createNode(`paragraph`,void 0,r)},renderMarkdown:(e,t,n)=>{if(!e)return``;let r=Array.isArray(e.content)?e.content:[];if(r.length===0){var i,a;let e=Array.isArray(n==null||(i=n.previousNode)==null?void 0:i.content)?n.previousNode.content:[];return(n==null||(a=n.previousNode)==null?void 0:a.type)===`paragraph`&&e.length===0?LO:``}return t.renderChildren(r)},addCommands(){return{setParagraph:()=>({commands:e})=>e.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),BO=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,VO=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,HO=Gf.create({name:`strike`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`s`},{tag:`del`},{tag:`strike`},{style:`text-decoration`,consuming:!1,getAttrs:e=>e.includes(`line-through`)?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`s`,P(this.options.HTMLAttributes,e),0]},markdownTokenName:`del`,parseMarkdown:(e,t)=>t.applyMark(`strike`,t.parseInline(e.tokens||[])),renderMarkdown:(e,t)=>`~~${t.renderChildren(e)}~~`,addCommands(){return{setStrike:()=>({commands:e})=>e.setMark(this.name),toggleStrike:()=>({commands:e})=>e.toggleMark(this.name),unsetStrike:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[hp({find:BO,type:this.type})]},addPasteRules(){return[bp({find:VO,type:this.type})]}}),UO=yp.create({name:`text`,group:`inline`,parseMarkdown:e=>({type:`text`,text:e.text||``}),renderMarkdown:e=>e.text||``}),WO=Gf.create({name:`underline`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`u`},{style:`text-decoration`,consuming:!1,getAttrs:e=>e.includes(`underline`)?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`u`,P(this.options.HTMLAttributes,e),0]},parseMarkdown(e,t){return t.applyMark(this.name||`underline`,t.parseInline(e.tokens||[]))},renderMarkdown(e,t){return`<u>${t.renderChildren(e)}</u>`},markdownTokenizer:{name:`underline`,level:`inline`,start(e){return e.toLowerCase().indexOf(`<u>`)},tokenize(e,t,n){if(!/^<u>/i.test(e))return;let r=/\\[\s\S]|`+|<\/u>/gi;r.lastIndex=3;let i=r.exec(e);for(;i;){if(i[0].startsWith("`")){let t=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/.exec(e.slice(i.index));t&&(r.lastIndex=i.index+t[0].length)}else if(!i[0].startsWith(`\\`)){let t=e.slice(3,i.index);return t?{type:`underline`,raw:e.slice(0,r.lastIndex),text:t,tokens:n.inlineTokens(t)}:void 0}i=r.exec(e)}}},addCommands(){return{setUnderline:()=>({commands:e})=>e.setMark(this.name),toggleULine truncated
|
||||
<style rel="stylesheet" crossorigin>/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */
|
||||
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial}}}@layer theme{:root,:host{--font-sans:"Inter Variable", "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;--font-serif:"Source Serif 4 Variable", "Source Serif 4", "Iowan Old Style", Georgia, serif;--font-mono:"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--radius-xs:4px;--radius-sm:6px;--radius-md:10px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-surface:var(--dw-surface);--color-surface-raised:var(--dw-surface-raised);--color-surface-hover:var(--dw-surface-hover);--color-line:var(--dw-line);--color-line-strong:var(--dw-line-strong);--color-ink:var(--dw-ink);--color-ink-muted:var(--dw-ink-muted);--color-ink-faint:var(--dw-ink-faint);--color-primary:var(--dw-primary);--color-primary-hover:var(--dw-primary-hover);--color-on-primary:var(--dw-on-primary);--color-accent:var(--dw-accent);--color-accent-soft:var(--dw-accent-soft);--color-selection:var(--dw-selection);--color-success:var(--dw-success);--color-success-soft:var(--dw-success-soft);--color-warning:var(--dw-warning);--color-warning-soft:var(--dw-warning-soft);--color-danger:var(--dw-danger);--color-danger-soft:var(--dw-danger-soft);--color-on-danger:var(--dw-on-danger);--color-info:var(--dw-info);--color-info-soft:var(--dw-info-soft);--color-code-bg:var(--dw-code-bg);--text-ui-xs:12px;--text-ui-xs--line-height:16px;--text-ui-xs--letter-spacing:.01em;--text-ui-xs--font-weight:500;--text-ui-sm:13px;--text-ui-sm--line-height:18px;--text-ui-md:14px;--text-ui-md--line-height:20px;--text-doc-h1:30px;--text-doc-h1--line-height:38px;--text-doc-h2:24px;--text-doc-h2--line-height:32px;--text-doc-h3:18px;--text-doc-h3--line-height:28px;--text-doc-body:16px;--text-doc-body--line-height:27px;--text-code:14px;--text-code--line-height:22px;--spacing-control-sm:28px;--spacing-control-md:34px}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;colLine truncated
|
||||
/*$vite$:1*/</style>
|
||||
</head>
|
||||
<body>
|
||||
<main id="editor"></main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,13 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<title>Docwell editor</title>
|
||||
</head>
|
||||
<body>
|
||||
<main id="editor"></main>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@docwell/editor-bridge",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"type": "module",
|
||||
"description": "The Docwell editor as a standalone page for native WebViews (ADR-4)",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build && node scripts/copy-to-apps.mjs",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@docwell/editor": "*",
|
||||
"@docwell/ui": "*",
|
||||
"@tiptap/core": "^3.32.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"jsdom": "^30.1.3",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^8.3.5",
|
||||
"vite-plugin-singlefile": "^2.3.4",
|
||||
"vitest": "^5.0.5",
|
||||
"vue-tsc": "^3.3.14"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Copies the built editor page into the apps that bundle it.
|
||||
import { copyFileSync, mkdirSync } from "node:fs";
|
||||
|
||||
const targets = ["../../Phone-App/assets/editor"];
|
||||
for (const dir of targets) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
copyFileSync("dist/index.html", `${dir}/index.html`);
|
||||
console.log(`copied dist/index.html to ${dir}/`);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorBridge } from "./bridge";
|
||||
import { PROTOCOL_VERSION, type EditorMessage } from "./protocol";
|
||||
|
||||
const doc = {
|
||||
type: "doc",
|
||||
content: [{ type: "paragraph", content: [{ type: "text", text: "Hello" }] }],
|
||||
};
|
||||
|
||||
let bridge: EditorBridge | undefined;
|
||||
afterEach(() => bridge?.destroy());
|
||||
|
||||
function setup() {
|
||||
const sent: EditorMessage[] = [];
|
||||
const el = document.createElement("div");
|
||||
document.body.append(el);
|
||||
bridge = new EditorBridge(el, (m) => sent.push(m));
|
||||
return { bridge, sent, el };
|
||||
}
|
||||
|
||||
describe("EditorBridge", () => {
|
||||
it("says it is ready with the protocol version", () => {
|
||||
const { sent } = setup();
|
||||
expect(sent[0]).toEqual({ type: "ready", version: PROTOCOL_VERSION });
|
||||
});
|
||||
|
||||
it("loads content without echoing it back as a change", () => {
|
||||
const { bridge, sent, el } = setup();
|
||||
bridge.receive(JSON.stringify({ type: "setContent", content: doc }));
|
||||
expect(el.textContent).toContain("Hello");
|
||||
expect(bridge.content).toEqual(doc);
|
||||
expect(sent.some((m) => m.type === "change")).toBe(false);
|
||||
});
|
||||
|
||||
it("applies toolbar commands and reports the change and toolbar state", () => {
|
||||
const { bridge, sent } = setup();
|
||||
bridge.receive({ type: "setContent", content: doc });
|
||||
bridge.receive({ type: "command", command: "heading1" });
|
||||
|
||||
expect(bridge.content.content?.[0]?.type).toBe("heading");
|
||||
const change = sent.filter((m) => m.type === "change").at(-1);
|
||||
expect(change?.type === "change" && change.content.content?.[0]?.type).toBe("heading");
|
||||
const state = sent.filter((m) => m.type === "state").at(-1);
|
||||
expect(state?.type === "state" && state.state.active).toContain("heading1");
|
||||
expect(state?.type === "state" && state.state.canUndo).toBe(true);
|
||||
});
|
||||
|
||||
it("reports bad messages instead of throwing", () => {
|
||||
const { bridge, sent } = setup();
|
||||
bridge.receive("not json");
|
||||
bridge.receive({ type: "command", command: "explode" as never });
|
||||
expect(sent.filter((m) => m.type === "error")).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { Editor, type JSONContent } from "@tiptap/core";
|
||||
import { docwellExtensions, type ExtensionOptions } from "@docwell/editor/extensions";
|
||||
import { CollabProvider } from "@docwell/editor/provider";
|
||||
import { PROTOCOL_VERSION, type Command, type EditorMessage, type EditorState, type HostMessage } from "./protocol";
|
||||
|
||||
const commands: Record<Command, (e: Editor) => boolean> = {
|
||||
bold: (e) => e.chain().focus().toggleBold().run(),
|
||||
italic: (e) => e.chain().focus().toggleItalic().run(),
|
||||
strike: (e) => e.chain().focus().toggleStrike().run(),
|
||||
code: (e) => e.chain().focus().toggleCode().run(),
|
||||
heading1: (e) => e.chain().focus().toggleHeading({ level: 1 }).run(),
|
||||
heading2: (e) => e.chain().focus().toggleHeading({ level: 2 }).run(),
|
||||
heading3: (e) => e.chain().focus().toggleHeading({ level: 3 }).run(),
|
||||
bulletList: (e) => e.chain().focus().toggleBulletList().run(),
|
||||
orderedList: (e) => e.chain().focus().toggleOrderedList().run(),
|
||||
blockquote: (e) => e.chain().focus().toggleBlockquote().run(),
|
||||
codeBlock: (e) => e.chain().focus().toggleCodeBlock().run(),
|
||||
undo: (e) => e.chain().focus().undo().run(),
|
||||
redo: (e) => e.chain().focus().redo().run(),
|
||||
};
|
||||
|
||||
/** Which toolbar commands are "on" at the selection. */
|
||||
const activeChecks: [Command, (e: Editor) => boolean][] = [
|
||||
["bold", (e) => e.isActive("bold")],
|
||||
["italic", (e) => e.isActive("italic")],
|
||||
["strike", (e) => e.isActive("strike")],
|
||||
["code", (e) => e.isActive("code")],
|
||||
["heading1", (e) => e.isActive("heading", { level: 1 })],
|
||||
["heading2", (e) => e.isActive("heading", { level: 2 })],
|
||||
["heading3", (e) => e.isActive("heading", { level: 3 })],
|
||||
["bulletList", (e) => e.isActive("bulletList")],
|
||||
["orderedList", (e) => e.isActive("orderedList")],
|
||||
["blockquote", (e) => e.isActive("blockquote")],
|
||||
["codeBlock", (e) => e.isActive("codeBlock")],
|
||||
];
|
||||
|
||||
/**
|
||||
* The Docwell editor driven by a native host instead of a Vue UI: the host
|
||||
* renders the toolbar and sends commands, the page reports content and
|
||||
* toolbar state back.
|
||||
*/
|
||||
export class EditorBridge {
|
||||
private editor: Editor;
|
||||
private provider: CollabProvider | null = null;
|
||||
private lastState = "";
|
||||
private editable = true;
|
||||
|
||||
constructor(
|
||||
private readonly el: HTMLElement,
|
||||
private readonly send: (msg: EditorMessage) => void,
|
||||
) {
|
||||
this.editor = this.create({});
|
||||
send({ type: "ready", version: PROTOCOL_VERSION });
|
||||
}
|
||||
|
||||
/** Handles one message from the host. Bad input is reported, never thrown. */
|
||||
receive(raw: string | HostMessage): void {
|
||||
try {
|
||||
const msg: HostMessage = typeof raw === "string" ? JSON.parse(raw) : raw;
|
||||
this.handle(msg);
|
||||
} catch (err) {
|
||||
this.send({ type: "error", message: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
}
|
||||
|
||||
get content(): JSONContent {
|
||||
return this.editor.getJSON();
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
this.editor.destroy();
|
||||
this.provider?.destroy();
|
||||
}
|
||||
|
||||
private handle(msg: HostMessage): void {
|
||||
switch (msg.type) {
|
||||
case "hello":
|
||||
this.send({ type: "ready", version: PROTOCOL_VERSION });
|
||||
this.lastState = "";
|
||||
this.reportState(this.editor);
|
||||
return;
|
||||
case "setContent":
|
||||
// Not echoed back as a change: the host already has this content.
|
||||
this.editor.commands.setContent(msg.content ?? "", { emitUpdate: false });
|
||||
this.reportState(this.editor);
|
||||
return;
|
||||
case "setEditable":
|
||||
this.editable = msg.editable;
|
||||
this.editor.setEditable(msg.editable);
|
||||
return;
|
||||
case "setTheme":
|
||||
document.documentElement.classList.toggle("dark", msg.dark);
|
||||
return;
|
||||
case "command": {
|
||||
const run = commands[msg.command];
|
||||
if (!run) throw new Error(`unknown command ${msg.command}`);
|
||||
run(this.editor);
|
||||
return;
|
||||
}
|
||||
case "focus":
|
||||
this.editor.commands.focus();
|
||||
return;
|
||||
case "blur":
|
||||
this.editor.commands.blur();
|
||||
return;
|
||||
case "connect":
|
||||
this.connect(msg);
|
||||
return;
|
||||
default:
|
||||
throw new Error(`unknown message ${(msg as { type: string }).type}`);
|
||||
}
|
||||
}
|
||||
|
||||
private connect(msg: Extract<HostMessage, { type: "connect" }>): void {
|
||||
this.provider?.destroy();
|
||||
const provider = new CollabProvider({ url: msg.url, page: msg.page, token: () => msg.token });
|
||||
provider.onChange(() => this.send({ type: "collab", status: provider.status }));
|
||||
this.provider = provider;
|
||||
this.editor.destroy();
|
||||
this.editor = this.create({ collab: { provider, user: msg.user } });
|
||||
}
|
||||
|
||||
private create(opts: ExtensionOptions): Editor {
|
||||
this.el.replaceChildren();
|
||||
return new Editor({
|
||||
element: this.el,
|
||||
editable: this.editable,
|
||||
extensions: docwellExtensions(opts),
|
||||
editorProps: { attributes: { class: "dw-prose" } },
|
||||
onUpdate: ({ editor }) => this.send({ type: "change", content: editor.getJSON() }),
|
||||
onSelectionUpdate: ({ editor }) => this.reportState(editor),
|
||||
onTransaction: ({ editor }) => this.reportState(editor),
|
||||
onFocus: ({ editor }) => this.reportState(editor),
|
||||
onBlur: ({ editor }) => this.reportState(editor),
|
||||
});
|
||||
}
|
||||
|
||||
/** Sends the toolbar state, only when it changed. */
|
||||
private reportState(e: Editor): void {
|
||||
const state: EditorState = {
|
||||
active: activeChecks.filter(([, on]) => on(e)).map(([name]) => name),
|
||||
canUndo: e.can().undo(),
|
||||
canRedo: e.can().redo(),
|
||||
focused: e.isFocused,
|
||||
};
|
||||
const json = JSON.stringify(state);
|
||||
if (json === this.lastState) return;
|
||||
this.lastState = json;
|
||||
this.send({ type: "state", state });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Entry point of the editor page that native apps load into a WebView.
|
||||
import { EditorBridge } from "./bridge";
|
||||
import type { HostMessage } from "./protocol";
|
||||
import { send } from "./transport";
|
||||
import "./style.css";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
/** The native app calls window.docwell.receive(json) to drive the editor. */
|
||||
docwell: { receive(msg: string | HostMessage): void };
|
||||
}
|
||||
}
|
||||
|
||||
const bridge = new EditorBridge(document.getElementById("editor")!, send);
|
||||
window.docwell = { receive: (msg) => bridge.receive(msg) };
|
||||
@@ -0,0 +1,58 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Messages between the editor page and the native app hosting it (ADR-4).
|
||||
// Both directions are JSON. Keep Phone-App/lib/editor/bridge.dart in sync.
|
||||
|
||||
import type { JSONContent } from "@tiptap/core";
|
||||
|
||||
/** Formatting the native toolbar can apply. */
|
||||
export type Command =
|
||||
| "bold"
|
||||
| "italic"
|
||||
| "strike"
|
||||
| "code"
|
||||
| "heading1"
|
||||
| "heading2"
|
||||
| "heading3"
|
||||
| "bulletList"
|
||||
| "orderedList"
|
||||
| "blockquote"
|
||||
| "codeBlock"
|
||||
| "undo"
|
||||
| "redo";
|
||||
|
||||
/** Native app → editor, through `window.docwell.receive(json)`. */
|
||||
export type HostMessage =
|
||||
/**
|
||||
* Sent by the host once the page has loaded; the editor answers "ready".
|
||||
* The "ready" sent at start-up is lost when the host's channel is not set
|
||||
* up yet, so the host asks again instead of relying on it.
|
||||
*/
|
||||
| { type: "hello" }
|
||||
| { type: "setContent"; content: JSONContent | null }
|
||||
| { type: "setEditable"; editable: boolean }
|
||||
| { type: "setTheme"; dark: boolean }
|
||||
| { type: "command"; command: Command }
|
||||
| { type: "focus" }
|
||||
| { type: "blur" }
|
||||
/** Edit the live document over docwell-server's /collab WebSocket. */
|
||||
| { type: "connect"; url: string; page: string; token: string; user: { name: string; color: string } };
|
||||
|
||||
/** What the toolbar needs to show which buttons are on. */
|
||||
export interface EditorState {
|
||||
active: Command[];
|
||||
canUndo: boolean;
|
||||
canRedo: boolean;
|
||||
focused: boolean;
|
||||
}
|
||||
|
||||
/** Editor → native app. */
|
||||
export type EditorMessage =
|
||||
| { type: "ready"; version: number }
|
||||
| { type: "change"; content: JSONContent }
|
||||
| { type: "state"; state: EditorState }
|
||||
| { type: "collab"; status: string }
|
||||
| { type: "error"; message: string };
|
||||
|
||||
/** Bumped when a message changes shape, so the app can refuse a stale bundle. */
|
||||
export const PROTOCOL_VERSION = 1;
|
||||
@@ -0,0 +1,18 @@
|
||||
/* SPDX-License-Identifier: AGPL-3.0-or-later */
|
||||
|
||||
@import "tailwindcss";
|
||||
@import "@docwell/ui/theme.css";
|
||||
@import "@docwell/editor/editor.css";
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--color-surface);
|
||||
color: var(--color-ink);
|
||||
/* The native app owns scrolling chrome; the page only scrolls the document. */
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
|
||||
#editor {
|
||||
padding: 16px max(16px, env(safe-area-inset-right)) 96px max(16px, env(safe-area-inset-left));
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import type { EditorMessage } from "./protocol";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
/** The webview_flutter JavaScriptChannel the Flutter app adds (or any host injecting the same object). */
|
||||
DocwellNative?: { postMessage(json: string): void };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to the host that loaded the page. In a plain browser tab
|
||||
* (development) it posts to the parent frame and logs to the console.
|
||||
*/
|
||||
export function send(msg: EditorMessage): void {
|
||||
const json = JSON.stringify(msg);
|
||||
if (window.DocwellNative) {
|
||||
window.DocwellNative.postMessage(json);
|
||||
} else {
|
||||
window.parent.postMessage(json, "*");
|
||||
console.debug("[docwell bridge]", msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["vite/client", "vitest/globals"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "vite.config.ts", "../editor/src/**/*", "../env.d.ts"]
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import { defineConfig } from "vitest/config";
|
||||
import { viteSingleFile } from "vite-plugin-singlefile";
|
||||
|
||||
export default defineConfig({
|
||||
// One self-contained index.html (scripts, styles and fonts inlined), so a
|
||||
// WebView can load it from app assets without a server.
|
||||
plugins: [tailwindcss(), viteSingleFile()],
|
||||
build: {
|
||||
outDir: "dist",
|
||||
emptyOutDir: true,
|
||||
},
|
||||
test: {
|
||||
environment: "jsdom",
|
||||
},
|
||||
});
|
||||
@@ -7,6 +7,8 @@
|
||||
"main": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./extensions": "./src/extensions.ts",
|
||||
"./provider": "./src/provider.ts",
|
||||
"./editor.css": "./src/editor.css"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { JSONContent } from "@tiptap/core";
|
||||
import { EditorContent, useEditor } from "@tiptap/vue-3";
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/* SPDX-License-Identifier: AGPL-3.0-or-later */
|
||||
|
||||
/* Document styles for the Docwell editor, from the design system's Document
|
||||
type scale. Uses tokens from @docwell/ui/theme.css. */
|
||||
|
||||
@@ -10,16 +12,54 @@
|
||||
min-height: 12rem;
|
||||
}
|
||||
/* Paragraph blocks sit space-2 apart; a heading gets space-5 above it. */
|
||||
.dw-prose > * + * { margin-top: 8px; }
|
||||
.dw-prose > :is(h1, h2, h3) { margin-top: 20px; }
|
||||
.dw-prose h1 { font-family: var(--font-serif); font-size: var(--text-doc-h1); line-height: var(--text-doc-h1--line-height); font-weight: 600; }
|
||||
.dw-prose h2 { font-family: var(--font-serif); font-size: var(--text-doc-h2); line-height: var(--text-doc-h2--line-height); font-weight: 600; }
|
||||
.dw-prose h3 { font-size: var(--text-doc-h3); line-height: var(--text-doc-h3--line-height); font-weight: 600; }
|
||||
.dw-prose ul { list-style: disc; padding-left: 1.5rem; }
|
||||
.dw-prose ol { list-style: decimal; padding-left: 1.5rem; }
|
||||
.dw-prose a { color: var(--color-accent); text-decoration: underline; text-underline-offset: 2px; }
|
||||
.dw-prose blockquote { border-left: 3px solid var(--color-line); padding-left: 1rem; color: var(--color-ink-muted); }
|
||||
.dw-prose code { font-family: var(--font-mono); font-size: 0.9em; background: var(--color-code-bg); padding: 0.1em 0.3em; border-radius: var(--radius-xs); }
|
||||
.dw-prose > * + * {
|
||||
margin-top: 8px;
|
||||
}
|
||||
.dw-prose > :is(h1, h2, h3) {
|
||||
margin-top: 20px;
|
||||
}
|
||||
.dw-prose h1 {
|
||||
font-family: var(--font-serif);
|
||||
font-size: var(--text-doc-h1);
|
||||
line-height: var(--text-doc-h1--line-height);
|
||||
font-weight: 600;
|
||||
}
|
||||
.dw-prose h2 {
|
||||
font-family: var(--font-serif);
|
||||
font-size: var(--text-doc-h2);
|
||||
line-height: var(--text-doc-h2--line-height);
|
||||
font-weight: 600;
|
||||
}
|
||||
.dw-prose h3 {
|
||||
font-size: var(--text-doc-h3);
|
||||
line-height: var(--text-doc-h3--line-height);
|
||||
font-weight: 600;
|
||||
}
|
||||
.dw-prose ul {
|
||||
list-style: disc;
|
||||
padding-left: 1.5rem;
|
||||
}
|
||||
.dw-prose ol {
|
||||
list-style: decimal;
|
||||
padding-left: 1.5rem;
|
||||
}
|
||||
.dw-prose a {
|
||||
color: var(--color-accent);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
.dw-prose blockquote {
|
||||
border-left: 3px solid var(--color-line);
|
||||
padding-left: 1rem;
|
||||
color: var(--color-ink-muted);
|
||||
}
|
||||
.dw-prose code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.9em;
|
||||
background: var(--color-code-bg);
|
||||
padding: 0.1em 0.3em;
|
||||
border-radius: var(--radius-xs);
|
||||
}
|
||||
.dw-prose pre {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--text-code);
|
||||
@@ -29,9 +69,19 @@
|
||||
border-radius: var(--radius-md);
|
||||
overflow-x: auto;
|
||||
}
|
||||
.dw-prose pre code { background: none; padding: 0; font-size: inherit; }
|
||||
.dw-prose hr { border: none; border-top: 1px solid var(--color-line); margin: 24px 0; }
|
||||
.dw-prose ::selection { background: var(--color-selection); }
|
||||
.dw-prose pre code {
|
||||
background: none;
|
||||
padding: 0;
|
||||
font-size: inherit;
|
||||
}
|
||||
.dw-prose hr {
|
||||
border: none;
|
||||
border-top: 1px solid var(--color-line);
|
||||
margin: 24px 0;
|
||||
}
|
||||
.dw-prose ::selection {
|
||||
background: var(--color-selection);
|
||||
}
|
||||
.dw-prose p.is-editor-empty:first-child::before {
|
||||
content: attr(data-placeholder);
|
||||
color: var(--color-ink-faint);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import type { AnyExtension } from "@tiptap/core";
|
||||
import Collaboration from "@tiptap/extension-collaboration";
|
||||
import CollaborationCaret from "@tiptap/extension-collaboration-caret";
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
export { default as DocwellEditor } from "./DocwellEditor.vue";
|
||||
export type { JSONContent } from "@tiptap/core";
|
||||
export { docwellExtensions, userColor, type CollabUser, type ExtensionOptions } from "./extensions";
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import * as decoding from "lib0/decoding";
|
||||
import * as encoding from "lib0/encoding";
|
||||
import { Awareness, applyAwarenessUpdate, encodeAwarenessUpdate, removeAwarenessStates } from "y-protocols/awareness";
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
// A one- or two-word status. The word carries the meaning, never the color alone.
|
||||
withDefaults(defineProps<{ tone?: "neutral" | "accent" | "success" | "warning" | "danger" | "info" }>(), {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts" generic="Target">
|
||||
import { computed } from "vue";
|
||||
|
||||
@@ -16,7 +17,11 @@ const shown = computed(() => {
|
||||
<nav :aria-label="label ?? 'Breadcrumb'">
|
||||
<ol class="flex flex-wrap items-center gap-1 text-ui-sm">
|
||||
<li v-for="(it, i) in shown" :key="i" class="inline-flex min-w-0 items-center gap-1 text-ink-muted">
|
||||
<span v-if="i === shown.length - 1" aria-current="page" class="max-w-64 truncate px-1 py-0.5 font-medium text-ink">
|
||||
<span
|
||||
v-if="i === shown.length - 1"
|
||||
aria-current="page"
|
||||
class="max-w-64 truncate px-1 py-0.5 font-medium text-ink"
|
||||
>
|
||||
{{ it.label }}
|
||||
</span>
|
||||
<RouterLink
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import DwIcon from "./DwIcon.vue";
|
||||
import type { IconName } from "./icons";
|
||||
@@ -27,7 +28,8 @@ withDefaults(
|
||||
{
|
||||
'border-transparent bg-primary text-on-primary enabled:hover:bg-primary-hover': variant === 'primary',
|
||||
'border-line-strong bg-surface-raised text-ink enabled:hover:bg-surface-hover': variant === 'secondary',
|
||||
'border-transparent bg-transparent text-ink-muted enabled:hover:bg-surface-hover enabled:hover:text-ink': variant === 'ghost',
|
||||
'border-transparent bg-transparent text-ink-muted enabled:hover:bg-surface-hover enabled:hover:text-ink':
|
||||
variant === 'ghost',
|
||||
'border-transparent bg-danger text-on-danger': variant === 'danger',
|
||||
},
|
||||
]"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import DwIcon from "./DwIcon.vue";
|
||||
@@ -5,7 +6,12 @@ import type { IconName } from "./icons";
|
||||
|
||||
// A tinted panel for a note, tip, warning or error. note uses the drop glyph.
|
||||
const props = withDefaults(
|
||||
defineProps<{ tone?: "note" | "info" | "success" | "warning" | "danger"; title?: string; icon?: IconName; size?: "doc" | "ui" }>(),
|
||||
defineProps<{
|
||||
tone?: "note" | "info" | "success" | "warning" | "danger";
|
||||
title?: string;
|
||||
icon?: IconName;
|
||||
size?: "doc" | "ui";
|
||||
}>(),
|
||||
{ tone: "note", size: "doc" },
|
||||
);
|
||||
const defaultIcon = { note: "drop", info: "info", success: "check", warning: "alert", danger: "error" } as const;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { iconPaths, type IconName } from "./icons";
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import horizontal from "./assets/docwell-horizontal.svg";
|
||||
import horizontalReversed from "./assets/docwell-horizontal-reversed.svg";
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import DwIcon from "./DwIcon.vue";
|
||||
import type { IconName } from "./icons";
|
||||
@@ -20,7 +21,11 @@ const emit = defineEmits<{ select: [item: SlashMenuItem, index: number] }>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="w-80 max-w-full rounded-md border border-line bg-surface-raised p-1 shadow-menu" role="listbox" :aria-label="label">
|
||||
<div
|
||||
class="w-80 max-w-full rounded-md border border-line bg-surface-raised p-1 shadow-menu"
|
||||
role="listbox"
|
||||
:aria-label="label"
|
||||
>
|
||||
<div v-if="query != null" class="px-2 pt-2 pb-1 font-mono text-ui-xs text-ink-muted">/{{ query }}</div>
|
||||
<div
|
||||
v-for="(it, i) in items"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import { useId } from "vue";
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import DwIcon from "./DwIcon.vue";
|
||||
import type { IconName } from "./icons";
|
||||
@@ -26,7 +27,9 @@ const emit = defineEmits<{ toggle: [] }>();
|
||||
:aria-selected="active"
|
||||
:aria-expanded="hasChildren ? expanded : undefined"
|
||||
class="group flex h-control-sm items-center gap-1 rounded-sm pr-1 text-ui-md transition-colors duration-[120ms]"
|
||||
:class="active ? 'bg-accent-soft font-semibold text-accent' : 'text-ink-muted hover:bg-surface-hover hover:text-ink'"
|
||||
:class="
|
||||
active ? 'bg-accent-soft font-semibold text-accent' : 'text-ink-muted hover:bg-surface-hover hover:text-ink'
|
||||
"
|
||||
:style="{ paddingLeft: `${8 + depth * 16}px` }"
|
||||
>
|
||||
<button
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
/**
|
||||
* Docwell's own outline icons: a 24-unit grid, 1.75 stroke, round caps and
|
||||
* joins, drawn in currentColor. The first group is the design system's set
|
||||
@@ -34,7 +36,17 @@ export const iconPaths = {
|
||||
"sign-out": ["M14 4h5v16h-5", "M10 8l-4 4 4 4", "M6 12h9"],
|
||||
sidebar: ["M4 5h16v14H4z", "M9.5 5v14"],
|
||||
home: ["M4 11l8-7 8 7", "M6 9.5V20h12V9.5", "M10 20v-5h4v5"],
|
||||
sun: ["M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z", "M12 3v1.5", "M12 19.5V21", "M3 12h1.5", "M19.5 12H21", "M5.6 5.6l1.1 1.1", "M17.3 17.3l1.1 1.1", "M5.6 18.4l1.1-1.1", "M17.3 6.7l1.1-1.1"],
|
||||
sun: [
|
||||
"M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z",
|
||||
"M12 3v1.5",
|
||||
"M12 19.5V21",
|
||||
"M3 12h1.5",
|
||||
"M19.5 12H21",
|
||||
"M5.6 5.6l1.1 1.1",
|
||||
"M17.3 17.3l1.1 1.1",
|
||||
"M5.6 18.4l1.1-1.1",
|
||||
"M17.3 6.7l1.1-1.1",
|
||||
],
|
||||
moon: ["M19.5 14.5A8 8 0 0 1 9.5 4.5a8 8 0 1 0 10 10z"],
|
||||
monitor: ["M4 5h16v11H4z", "M9 20h6", "M12 16v4"],
|
||||
selector: ["M8 9l4-4 4 4", "M8 15l4 4 4-4"],
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
export { default as DwBadge } from "./DwBadge.vue";
|
||||
export { default as DwBreadcrumbs } from "./DwBreadcrumbs.vue";
|
||||
export { default as DwButton } from "./DwButton.vue";
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/* SPDX-License-Identifier: AGPL-3.0-or-later */
|
||||
|
||||
/* Docwell design system for Tailwind CSS v4: the tokens from
|
||||
Design/docwell-all/3-design-system/source/tokens.json, plus the component
|
||||
classes. Import after `@import "tailwindcss";` in each app's main stylesheet.
|
||||
@@ -48,7 +50,6 @@
|
||||
--color-info-soft: var(--dw-info-soft);
|
||||
--color-code-bg: var(--dw-code-bg);
|
||||
|
||||
|
||||
/* Interface text styles: text-ui-xs … text-ui-lg. */
|
||||
--text-ui-xs: 12px;
|
||||
--text-ui-xs--line-height: 16px;
|
||||
@@ -183,7 +184,16 @@ body {
|
||||
}
|
||||
|
||||
/* Keyboard focus: 2px focus-ring outline, 2px offset, on every interactive element. */
|
||||
:where(a, button, [role="button"], [role="treeitem"], summary, select, input[type="checkbox"], input[type="radio"]):focus-visible {
|
||||
:where(
|
||||
a,
|
||||
button,
|
||||
[role="button"],
|
||||
[role="treeitem"],
|
||||
summary,
|
||||
select,
|
||||
input[type="checkbox"],
|
||||
input[type="radio"]
|
||||
):focus-visible {
|
||||
outline: 2px solid var(--dw-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { ref, watchEffect } from "vue";
|
||||
|
||||
export type ThemeMode = "system" | "light" | "dark";
|
||||
|
||||
@@ -4,3 +4,7 @@ android.useAndroidX=true
|
||||
android.newDsl=false
|
||||
# This builtInKotlin flag was added by the Flutter template
|
||||
android.builtInKotlin=false
|
||||
|
||||
# Plugins live in the pub cache, often on another drive than the project on
|
||||
# Windows; Kotlin incremental caches fail across drives.
|
||||
kotlin.incremental=false
|
||||
Whitespace-only changes.
@@ -0,0 +1,90 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Drives the real editor page in a real WebView (ADR-4 spike). Build the page
|
||||
// first: npm run build -w @docwell/editor-bridge. Then, on a device:
|
||||
// flutter test integration_test
|
||||
|
||||
import 'package:docwell_mobile/editor/bridge.dart';
|
||||
import 'package:docwell_mobile/editor/editor_screen.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
const doc = {
|
||||
'type': 'doc',
|
||||
'content': [
|
||||
{
|
||||
'type': 'paragraph',
|
||||
'content': [
|
||||
{'type': 'text', 'text': 'Hello from Flutter'},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/// Pumps frames until [done] holds; the WebView works on its own thread.
|
||||
Future<void> pumpUntil(
|
||||
WidgetTester tester,
|
||||
bool Function() done, {
|
||||
String? reason,
|
||||
}) async {
|
||||
final end = DateTime.now().add(const Duration(seconds: 30));
|
||||
while (!done()) {
|
||||
if (DateTime.now().isAfter(end)) fail('timed out: $reason');
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
testWidgets('loads content, formats from the native toolbar, reports back', (
|
||||
tester,
|
||||
) async {
|
||||
EditorBridge? bridge;
|
||||
final changes = <Map<String, dynamic>>[];
|
||||
final started = DateTime.now();
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: EditorScreen(
|
||||
title: 'Test page',
|
||||
content: doc,
|
||||
onBridge: (b) => bridge = b,
|
||||
onChanged: changes.add,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => bridge?.isReady ?? false,
|
||||
reason: 'editor page ready',
|
||||
);
|
||||
debugPrint(
|
||||
'editor ready after ${DateTime.now().difference(started).inMilliseconds} ms',
|
||||
);
|
||||
expect(bridge!.error, isNull);
|
||||
|
||||
await bridge!.focus();
|
||||
await tester.tap(find.byKey(const Key('tool-heading1')));
|
||||
await pumpUntil(tester, () => changes.isNotEmpty, reason: 'change event');
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => bridge!.state.active.contains(EditorCommand.heading1),
|
||||
reason: 'toolbar state',
|
||||
);
|
||||
|
||||
final first = (changes.last['content'] as List).first as Map;
|
||||
expect(first['type'], 'heading');
|
||||
expect(first['attrs'], {'level': 1});
|
||||
expect((first['content'] as List).first['text'], 'Hello from Flutter');
|
||||
expect(bridge!.state.canUndo, isTrue);
|
||||
|
||||
await tester.tap(find.byTooltip('Undo'));
|
||||
await pumpUntil(
|
||||
tester,
|
||||
() => (changes.last['content'] as List).first['type'] == 'paragraph',
|
||||
reason: 'undo',
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
/// Minimal docwell-server client. Will be replaced by a client generated
|
||||
/// from api/openapi.yaml.
|
||||
import 'generated/models.dart';
|
||||
|
||||
export 'generated/models.dart';
|
||||
|
||||
/// Minimal docwell-server client. Requests are written by hand; the models
|
||||
/// are generated from api/openapi.yaml (tool/generate_api.dart).
|
||||
class DocwellApi {
|
||||
DocwellApi(String baseUrl, {http.Client? client})
|
||||
: baseUrl = baseUrl.replaceAll(RegExp(r'/+$'), ''),
|
||||
@@ -63,35 +69,9 @@ class DocwellApi {
|
||||
}
|
||||
}
|
||||
|
||||
class User {
|
||||
User({
|
||||
required this.id,
|
||||
required this.email,
|
||||
required this.name,
|
||||
this.role = 'user',
|
||||
this.organization = '',
|
||||
this.organizationName = '',
|
||||
});
|
||||
|
||||
factory User.fromJson(Map<String, dynamic> json) => User(
|
||||
id: json['id'] as String,
|
||||
email: json['email'] as String,
|
||||
name: json['name'] as String,
|
||||
role: json['role'] as String? ?? 'user',
|
||||
organization: json['organization'] as String? ?? '',
|
||||
organizationName: json['organizationName'] as String? ?? '',
|
||||
);
|
||||
|
||||
final String id;
|
||||
final String email;
|
||||
final String name;
|
||||
|
||||
/// Instance role: user, admin (of their organization) or superadmin.
|
||||
final String role;
|
||||
final String organization;
|
||||
final String organizationName;
|
||||
|
||||
bool get isManager => role == 'admin' || role == 'superadmin';
|
||||
extension UserRoles on User {
|
||||
/// Admins manage their organization; superadmins manage everything.
|
||||
bool get isManager => role == Role.admin || role == Role.superadmin;
|
||||
}
|
||||
|
||||
class DocwellApiException implements Exception {
|
||||
|
||||
@@ -0,0 +1,965 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Code generated by tool/generate_api.dart from api/openapi.yaml. DO NOT EDIT.
|
||||
|
||||
// ignore_for_file: constant_identifier_names
|
||||
|
||||
class ApiError {
|
||||
const ApiError({required this.error, this.message, this.fields, this.mfaId});
|
||||
|
||||
factory ApiError.fromJson(Map<String, dynamic> json) => ApiError(
|
||||
error: json['error'] as String,
|
||||
message: json['message'] == null ? null : json['message'] as String,
|
||||
fields: json['fields'] == null
|
||||
? null
|
||||
: (json['fields'] as Map<String, dynamic>).map(
|
||||
(k, e) => MapEntry(k, e as String),
|
||||
),
|
||||
mfaId: json['mfaId'] == null ? null : json['mfaId'] as String,
|
||||
);
|
||||
|
||||
/// invalid_json, validation, invalid_credentials, mfa_required, unauthorized, forbidden, account_disabled, signup_disabled, domain_not_allowed, invalid_token, invalid, not_found, conflict, internal
|
||||
final String error;
|
||||
|
||||
/// Human-readable explanation
|
||||
final String? message;
|
||||
|
||||
final Map<String, String>? fields;
|
||||
|
||||
final String? mfaId;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'error': error,
|
||||
'message': ?message,
|
||||
'fields': ?fields,
|
||||
'mfaId': ?mfaId,
|
||||
};
|
||||
}
|
||||
|
||||
/// Instance role. admin manages their own organization; superadmin manages everything.
|
||||
enum Role {
|
||||
user('user'),
|
||||
admin('admin'),
|
||||
superadmin('superadmin');
|
||||
|
||||
const Role(this.value);
|
||||
final String value;
|
||||
|
||||
static Role fromJson(String value) => values.firstWhere(
|
||||
(e) => e.value == value,
|
||||
orElse: () => throw FormatException('unknown Role', value),
|
||||
);
|
||||
|
||||
String toJson() => value;
|
||||
}
|
||||
|
||||
enum WorkspaceRole {
|
||||
owner('owner'),
|
||||
admin('admin'),
|
||||
member('member'),
|
||||
guest('guest');
|
||||
|
||||
const WorkspaceRole(this.value);
|
||||
final String value;
|
||||
|
||||
static WorkspaceRole fromJson(String value) => values.firstWhere(
|
||||
(e) => e.value == value,
|
||||
orElse: () => throw FormatException('unknown WorkspaceRole', value),
|
||||
);
|
||||
|
||||
String toJson() => value;
|
||||
}
|
||||
|
||||
enum UserStatus {
|
||||
active('active'),
|
||||
invited('invited'),
|
||||
disabled('disabled');
|
||||
|
||||
const UserStatus(this.value);
|
||||
final String value;
|
||||
|
||||
static UserStatus fromJson(String value) => values.firstWhere(
|
||||
(e) => e.value == value,
|
||||
orElse: () => throw FormatException('unknown UserStatus', value),
|
||||
);
|
||||
|
||||
String toJson() => value;
|
||||
}
|
||||
|
||||
class User {
|
||||
const User({
|
||||
required this.id,
|
||||
required this.email,
|
||||
required this.name,
|
||||
required this.avatar,
|
||||
required this.locale,
|
||||
required this.theme,
|
||||
required this.status,
|
||||
required this.verified,
|
||||
required this.created,
|
||||
required this.role,
|
||||
required this.organization,
|
||||
required this.organizationName,
|
||||
});
|
||||
|
||||
factory User.fromJson(Map<String, dynamic> json) => User(
|
||||
id: json['id'] as String,
|
||||
email: json['email'] as String,
|
||||
name: json['name'] as String,
|
||||
avatar: json['avatar'] as String,
|
||||
locale: json['locale'] as String,
|
||||
theme: json['theme'] as String,
|
||||
status: UserStatus.fromJson(json['status'] as String),
|
||||
verified: json['verified'] as bool,
|
||||
created: json['created'] as String,
|
||||
role: Role.fromJson(json['role'] as String),
|
||||
organization: json['organization'] as String,
|
||||
organizationName: json['organizationName'] as String,
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
final String email;
|
||||
|
||||
final String name;
|
||||
|
||||
final String avatar;
|
||||
|
||||
final String locale;
|
||||
|
||||
final String theme;
|
||||
|
||||
final UserStatus status;
|
||||
|
||||
final bool verified;
|
||||
|
||||
final String created;
|
||||
|
||||
final Role role;
|
||||
|
||||
/// Organization id
|
||||
final String organization;
|
||||
|
||||
final String organizationName;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'email': email,
|
||||
'name': name,
|
||||
'avatar': avatar,
|
||||
'locale': locale,
|
||||
'theme': theme,
|
||||
'status': status.toJson(),
|
||||
'verified': verified,
|
||||
'created': created,
|
||||
'role': role.toJson(),
|
||||
'organization': organization,
|
||||
'organizationName': organizationName,
|
||||
};
|
||||
}
|
||||
|
||||
class CreateUserRequest {
|
||||
const CreateUserRequest({
|
||||
required this.email,
|
||||
required this.password,
|
||||
required this.name,
|
||||
this.role,
|
||||
this.organization,
|
||||
});
|
||||
|
||||
factory CreateUserRequest.fromJson(Map<String, dynamic> json) =>
|
||||
CreateUserRequest(
|
||||
email: json['email'] as String,
|
||||
password: json['password'] as String,
|
||||
name: json['name'] as String,
|
||||
role: json['role'] == null
|
||||
? null
|
||||
: Role.fromJson(json['role'] as String),
|
||||
organization: json['organization'] == null
|
||||
? null
|
||||
: json['organization'] as String,
|
||||
);
|
||||
|
||||
final String email;
|
||||
|
||||
final String password;
|
||||
|
||||
final String name;
|
||||
|
||||
final Role? role;
|
||||
|
||||
/// Superadmins only; admins always create in their own
|
||||
final String? organization;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'email': email,
|
||||
'password': password,
|
||||
'name': name,
|
||||
'role': ?role?.toJson(),
|
||||
'organization': ?organization,
|
||||
};
|
||||
}
|
||||
|
||||
enum UpdateUserRequestStatus {
|
||||
active('active'),
|
||||
invited('invited'),
|
||||
disabled('disabled');
|
||||
|
||||
const UpdateUserRequestStatus(this.value);
|
||||
final String value;
|
||||
|
||||
static UpdateUserRequestStatus fromJson(String value) => values.firstWhere(
|
||||
(e) => e.value == value,
|
||||
orElse: () =>
|
||||
throw FormatException('unknown UpdateUserRequestStatus', value),
|
||||
);
|
||||
|
||||
String toJson() => value;
|
||||
}
|
||||
|
||||
class UpdateUserRequest {
|
||||
const UpdateUserRequest({
|
||||
this.email,
|
||||
this.name,
|
||||
this.role,
|
||||
this.password,
|
||||
this.status,
|
||||
this.verified,
|
||||
this.organization,
|
||||
});
|
||||
|
||||
factory UpdateUserRequest.fromJson(Map<String, dynamic> json) =>
|
||||
UpdateUserRequest(
|
||||
email: json['email'] == null ? null : json['email'] as String,
|
||||
name: json['name'] == null ? null : json['name'] as String,
|
||||
role: json['role'] == null
|
||||
? null
|
||||
: Role.fromJson(json['role'] as String),
|
||||
password: json['password'] == null ? null : json['password'] as String,
|
||||
status: json['status'] == null
|
||||
? null
|
||||
: UpdateUserRequestStatus.fromJson(json['status'] as String),
|
||||
verified: json['verified'] == null ? null : json['verified'] as bool,
|
||||
organization: json['organization'] == null
|
||||
? null
|
||||
: json['organization'] as String,
|
||||
);
|
||||
|
||||
final String? email;
|
||||
|
||||
final String? name;
|
||||
|
||||
final Role? role;
|
||||
|
||||
final String? password;
|
||||
|
||||
final UpdateUserRequestStatus? status;
|
||||
|
||||
final bool? verified;
|
||||
|
||||
/// Superadmins only; empty string detaches
|
||||
final String? organization;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'email': ?email,
|
||||
'name': ?name,
|
||||
'role': ?role?.toJson(),
|
||||
'password': ?password,
|
||||
'status': ?status?.toJson(),
|
||||
'verified': ?verified,
|
||||
'organization': ?organization,
|
||||
};
|
||||
}
|
||||
|
||||
class NameRequest {
|
||||
const NameRequest({required this.name});
|
||||
|
||||
factory NameRequest.fromJson(Map<String, dynamic> json) =>
|
||||
NameRequest(name: json['name'] as String);
|
||||
|
||||
final String name;
|
||||
|
||||
Map<String, dynamic> toJson() => {'name': name};
|
||||
}
|
||||
|
||||
class Organization {
|
||||
const Organization({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.created,
|
||||
required this.members,
|
||||
required this.workspaces,
|
||||
});
|
||||
|
||||
factory Organization.fromJson(Map<String, dynamic> json) => Organization(
|
||||
id: json['id'] as String,
|
||||
name: json['name'] as String,
|
||||
created: json['created'] as String,
|
||||
members: (json['members'] as num).toInt(),
|
||||
workspaces: (json['workspaces'] as num).toInt(),
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
final String name;
|
||||
|
||||
final String created;
|
||||
|
||||
final int members;
|
||||
|
||||
final int workspaces;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'created': created,
|
||||
'members': members,
|
||||
'workspaces': workspaces,
|
||||
};
|
||||
}
|
||||
|
||||
class Workspace {
|
||||
const Workspace({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.slug,
|
||||
required this.organization,
|
||||
required this.organizationName,
|
||||
required this.role,
|
||||
required this.created,
|
||||
});
|
||||
|
||||
factory Workspace.fromJson(Map<String, dynamic> json) => Workspace(
|
||||
id: json['id'] as String,
|
||||
name: json['name'] as String,
|
||||
slug: json['slug'] as String,
|
||||
organization: json['organization'] as String,
|
||||
organizationName: json['organizationName'] as String,
|
||||
role: WorkspaceRole.fromJson(json['role'] as String),
|
||||
created: json['created'] as String,
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
final String name;
|
||||
|
||||
final String slug;
|
||||
|
||||
final String organization;
|
||||
|
||||
final String organizationName;
|
||||
|
||||
final WorkspaceRole role;
|
||||
|
||||
final String created;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'slug': slug,
|
||||
'organization': organization,
|
||||
'organizationName': organizationName,
|
||||
'role': role.toJson(),
|
||||
'created': created,
|
||||
};
|
||||
}
|
||||
|
||||
class WorkspaceMemberUser {
|
||||
const WorkspaceMemberUser({
|
||||
required this.id,
|
||||
required this.email,
|
||||
required this.name,
|
||||
});
|
||||
|
||||
factory WorkspaceMemberUser.fromJson(Map<String, dynamic> json) =>
|
||||
WorkspaceMemberUser(
|
||||
id: json['id'] as String,
|
||||
email: json['email'] as String,
|
||||
name: json['name'] as String,
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
final String email;
|
||||
|
||||
final String name;
|
||||
|
||||
Map<String, dynamic> toJson() => {'id': id, 'email': email, 'name': name};
|
||||
}
|
||||
|
||||
class WorkspaceMember {
|
||||
const WorkspaceMember({required this.user, required this.role});
|
||||
|
||||
factory WorkspaceMember.fromJson(Map<String, dynamic> json) =>
|
||||
WorkspaceMember(
|
||||
user: WorkspaceMemberUser.fromJson(
|
||||
json['user'] as Map<String, dynamic>,
|
||||
),
|
||||
role: WorkspaceRole.fromJson(json['role'] as String),
|
||||
);
|
||||
|
||||
final WorkspaceMemberUser user;
|
||||
|
||||
final WorkspaceRole role;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'user': user.toJson(),
|
||||
'role': role.toJson(),
|
||||
};
|
||||
}
|
||||
|
||||
enum SpaceRole {
|
||||
admin('admin'),
|
||||
editor('editor'),
|
||||
commenter('commenter'),
|
||||
viewer('viewer');
|
||||
|
||||
const SpaceRole(this.value);
|
||||
final String value;
|
||||
|
||||
static SpaceRole fromJson(String value) => values.firstWhere(
|
||||
(e) => e.value == value,
|
||||
orElse: () => throw FormatException('unknown SpaceRole', value),
|
||||
);
|
||||
|
||||
String toJson() => value;
|
||||
}
|
||||
|
||||
/// Role that workspace members (not guests) get in an open space without an explicit role.
|
||||
enum SpaceDefaultRole {
|
||||
editor('editor'),
|
||||
commenter('commenter'),
|
||||
viewer('viewer');
|
||||
|
||||
const SpaceDefaultRole(this.value);
|
||||
final String value;
|
||||
|
||||
static SpaceDefaultRole fromJson(String value) => values.firstWhere(
|
||||
(e) => e.value == value,
|
||||
orElse: () => throw FormatException('unknown SpaceDefaultRole', value),
|
||||
);
|
||||
|
||||
String toJson() => value;
|
||||
}
|
||||
|
||||
/// open - every workspace member gets the default role; private - explicit members only.
|
||||
enum SpaceVisibility {
|
||||
open('open'),
|
||||
private('private');
|
||||
|
||||
const SpaceVisibility(this.value);
|
||||
final String value;
|
||||
|
||||
static SpaceVisibility fromJson(String value) => values.firstWhere(
|
||||
(e) => e.value == value,
|
||||
orElse: () => throw FormatException('unknown SpaceVisibility', value),
|
||||
);
|
||||
|
||||
String toJson() => value;
|
||||
}
|
||||
|
||||
class Space {
|
||||
const Space({
|
||||
required this.id,
|
||||
required this.workspace,
|
||||
required this.name,
|
||||
required this.slug,
|
||||
required this.icon,
|
||||
required this.description,
|
||||
required this.visibility,
|
||||
required this.defaultRole,
|
||||
required this.role,
|
||||
required this.created,
|
||||
});
|
||||
|
||||
factory Space.fromJson(Map<String, dynamic> json) => Space(
|
||||
id: json['id'] as String,
|
||||
workspace: json['workspace'] as String,
|
||||
name: json['name'] as String,
|
||||
slug: json['slug'] as String,
|
||||
icon: json['icon'] as String,
|
||||
description: json['description'] as String,
|
||||
visibility: SpaceVisibility.fromJson(json['visibility'] as String),
|
||||
defaultRole: SpaceDefaultRole.fromJson(json['defaultRole'] as String),
|
||||
role: SpaceRole.fromJson(json['role'] as String),
|
||||
created: json['created'] as String,
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
final String workspace;
|
||||
|
||||
final String name;
|
||||
|
||||
final String slug;
|
||||
|
||||
final String icon;
|
||||
|
||||
final String description;
|
||||
|
||||
final SpaceVisibility visibility;
|
||||
|
||||
final SpaceDefaultRole defaultRole;
|
||||
|
||||
final SpaceRole role;
|
||||
|
||||
final String created;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'workspace': workspace,
|
||||
'name': name,
|
||||
'slug': slug,
|
||||
'icon': icon,
|
||||
'description': description,
|
||||
'visibility': visibility.toJson(),
|
||||
'defaultRole': defaultRole.toJson(),
|
||||
'role': role.toJson(),
|
||||
'created': created,
|
||||
};
|
||||
}
|
||||
|
||||
class SpaceMemberUser {
|
||||
const SpaceMemberUser({
|
||||
required this.id,
|
||||
required this.email,
|
||||
required this.name,
|
||||
});
|
||||
|
||||
factory SpaceMemberUser.fromJson(Map<String, dynamic> json) =>
|
||||
SpaceMemberUser(
|
||||
id: json['id'] as String,
|
||||
email: json['email'] as String,
|
||||
name: json['name'] as String,
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
final String email;
|
||||
|
||||
final String name;
|
||||
|
||||
Map<String, dynamic> toJson() => {'id': id, 'email': email, 'name': name};
|
||||
}
|
||||
|
||||
class SpaceMember {
|
||||
const SpaceMember({required this.user, required this.role});
|
||||
|
||||
factory SpaceMember.fromJson(Map<String, dynamic> json) => SpaceMember(
|
||||
user: SpaceMemberUser.fromJson(json['user'] as Map<String, dynamic>),
|
||||
role: SpaceRole.fromJson(json['role'] as String),
|
||||
);
|
||||
|
||||
final SpaceMemberUser user;
|
||||
|
||||
final SpaceRole role;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'user': user.toJson(),
|
||||
'role': role.toJson(),
|
||||
};
|
||||
}
|
||||
|
||||
class PageNode {
|
||||
const PageNode({
|
||||
required this.id,
|
||||
required this.parent,
|
||||
required this.title,
|
||||
required this.icon,
|
||||
required this.position,
|
||||
required this.updated,
|
||||
});
|
||||
|
||||
factory PageNode.fromJson(Map<String, dynamic> json) => PageNode(
|
||||
id: json['id'] as String,
|
||||
parent: json['parent'] as String,
|
||||
title: json['title'] as String,
|
||||
icon: json['icon'] as String,
|
||||
position: json['position'] as String,
|
||||
updated: json['updated'] as String,
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
/// Parent page id; empty at the top level
|
||||
final String parent;
|
||||
|
||||
final String title;
|
||||
|
||||
final String icon;
|
||||
|
||||
/// Fractional sort key among siblings
|
||||
final String position;
|
||||
|
||||
final String updated;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'parent': parent,
|
||||
'title': title,
|
||||
'icon': icon,
|
||||
'position': position,
|
||||
'updated': updated,
|
||||
};
|
||||
}
|
||||
|
||||
class PageRef {
|
||||
const PageRef({required this.id, required this.title, required this.icon});
|
||||
|
||||
factory PageRef.fromJson(Map<String, dynamic> json) => PageRef(
|
||||
id: json['id'] as String,
|
||||
title: json['title'] as String,
|
||||
icon: json['icon'] as String,
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
final String title;
|
||||
|
||||
final String icon;
|
||||
|
||||
Map<String, dynamic> toJson() => {'id': id, 'title': title, 'icon': icon};
|
||||
}
|
||||
|
||||
class Page {
|
||||
const Page({
|
||||
required this.id,
|
||||
required this.workspace,
|
||||
required this.space,
|
||||
required this.parent,
|
||||
required this.title,
|
||||
required this.icon,
|
||||
required this.created,
|
||||
required this.updated,
|
||||
required this.deletedAt,
|
||||
required this.inTrash,
|
||||
required this.ancestors,
|
||||
required this.role,
|
||||
});
|
||||
|
||||
factory Page.fromJson(Map<String, dynamic> json) => Page(
|
||||
id: json['id'] as String,
|
||||
workspace: json['workspace'] as String,
|
||||
space: json['space'] as String,
|
||||
parent: json['parent'] as String,
|
||||
title: json['title'] as String,
|
||||
icon: json['icon'] as String,
|
||||
created: json['created'] as String,
|
||||
updated: json['updated'] as String,
|
||||
deletedAt: json['deletedAt'] as String,
|
||||
inTrash: json['inTrash'] as bool,
|
||||
ancestors: (json['ancestors'] as List)
|
||||
.map((e) => PageRef.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
role: SpaceRole.fromJson(json['role'] as String),
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
final String workspace;
|
||||
|
||||
final String space;
|
||||
|
||||
final String parent;
|
||||
|
||||
final String title;
|
||||
|
||||
final String icon;
|
||||
|
||||
final String created;
|
||||
|
||||
final String updated;
|
||||
|
||||
/// When the page itself was trashed; empty otherwise
|
||||
final String deletedAt;
|
||||
|
||||
/// The page or one of its ancestors is in the trash
|
||||
final bool inTrash;
|
||||
|
||||
/// Root first
|
||||
final List<PageRef> ancestors;
|
||||
|
||||
final SpaceRole role;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'workspace': workspace,
|
||||
'space': space,
|
||||
'parent': parent,
|
||||
'title': title,
|
||||
'icon': icon,
|
||||
'created': created,
|
||||
'updated': updated,
|
||||
'deletedAt': deletedAt,
|
||||
'inTrash': inTrash,
|
||||
'ancestors': ancestors.map((e) => e.toJson()).toList(),
|
||||
'role': role.toJson(),
|
||||
};
|
||||
}
|
||||
|
||||
class PageContent {
|
||||
const PageContent({required this.content, required this.updated});
|
||||
|
||||
factory PageContent.fromJson(Map<String, dynamic> json) => PageContent(
|
||||
content: json['content'] == null
|
||||
? null
|
||||
: json['content'] as Map<String, dynamic>,
|
||||
updated: json['updated'] as String,
|
||||
);
|
||||
|
||||
/// Tiptap JSON with type "doc"; null for a page that was never edited
|
||||
final Map<String, dynamic>? content;
|
||||
|
||||
final String updated;
|
||||
|
||||
Map<String, dynamic> toJson() => {'content': content, 'updated': updated};
|
||||
}
|
||||
|
||||
class PageVersion {
|
||||
const PageVersion({
|
||||
required this.id,
|
||||
required this.author,
|
||||
required this.label,
|
||||
required this.created,
|
||||
});
|
||||
|
||||
factory PageVersion.fromJson(Map<String, dynamic> json) => PageVersion(
|
||||
id: json['id'] as String,
|
||||
author: json['author'] as String,
|
||||
label: json['label'] as String,
|
||||
created: json['created'] as String,
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
/// Name (or email) of the last person who edited before it was taken
|
||||
final String author;
|
||||
|
||||
final String label;
|
||||
|
||||
final String created;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'author': author,
|
||||
'label': label,
|
||||
'created': created,
|
||||
};
|
||||
}
|
||||
|
||||
class TrashedPage {
|
||||
const TrashedPage({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.icon,
|
||||
required this.deletedAt,
|
||||
});
|
||||
|
||||
factory TrashedPage.fromJson(Map<String, dynamic> json) => TrashedPage(
|
||||
id: json['id'] as String,
|
||||
title: json['title'] as String,
|
||||
icon: json['icon'] as String,
|
||||
deletedAt: json['deletedAt'] as String,
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
final String title;
|
||||
|
||||
final String icon;
|
||||
|
||||
final String deletedAt;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'title': title,
|
||||
'icon': icon,
|
||||
'deletedAt': deletedAt,
|
||||
};
|
||||
}
|
||||
|
||||
class Session {
|
||||
const Session({required this.token, required this.user});
|
||||
|
||||
factory Session.fromJson(Map<String, dynamic> json) => Session(
|
||||
token: json['token'] as String,
|
||||
user: User.fromJson(json['user'] as Map<String, dynamic>),
|
||||
);
|
||||
|
||||
final String token;
|
||||
|
||||
final User user;
|
||||
|
||||
Map<String, dynamic> toJson() => {'token': token, 'user': user.toJson()};
|
||||
}
|
||||
|
||||
class UserList {
|
||||
const UserList({
|
||||
required this.items,
|
||||
required this.page,
|
||||
required this.perPage,
|
||||
required this.totalItems,
|
||||
});
|
||||
|
||||
factory UserList.fromJson(Map<String, dynamic> json) => UserList(
|
||||
items: (json['items'] as List)
|
||||
.map((e) => User.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
page: (json['page'] as num).toInt(),
|
||||
perPage: (json['perPage'] as num).toInt(),
|
||||
totalItems: (json['totalItems'] as num).toInt(),
|
||||
);
|
||||
|
||||
final List<User> items;
|
||||
|
||||
final int page;
|
||||
|
||||
final int perPage;
|
||||
|
||||
final int totalItems;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'items': items.map((e) => e.toJson()).toList(),
|
||||
'page': page,
|
||||
'perPage': perPage,
|
||||
'totalItems': totalItems,
|
||||
};
|
||||
}
|
||||
|
||||
class AuthMethods {
|
||||
const AuthMethods({
|
||||
required this.password,
|
||||
required this.otp,
|
||||
required this.mfa,
|
||||
required this.oauth2,
|
||||
required this.signup,
|
||||
});
|
||||
|
||||
factory AuthMethods.fromJson(Map<String, dynamic> json) => AuthMethods(
|
||||
password: json['password'] as bool,
|
||||
otp: json['otp'] as bool,
|
||||
mfa: json['mfa'] as bool,
|
||||
oauth2: (json['oauth2'] as List).map((e) => e as String).toList(),
|
||||
signup: json['signup'] as bool,
|
||||
);
|
||||
|
||||
final bool password;
|
||||
|
||||
final bool otp;
|
||||
|
||||
final bool mfa;
|
||||
|
||||
final List<String> oauth2;
|
||||
|
||||
final bool signup;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'password': password,
|
||||
'otp': otp,
|
||||
'mfa': mfa,
|
||||
'oauth2': oauth2.map((e) => e).toList(),
|
||||
'signup': signup,
|
||||
};
|
||||
}
|
||||
|
||||
class SignupRequest {
|
||||
const SignupRequest({
|
||||
required this.email,
|
||||
required this.password,
|
||||
required this.name,
|
||||
});
|
||||
|
||||
factory SignupRequest.fromJson(Map<String, dynamic> json) => SignupRequest(
|
||||
email: json['email'] as String,
|
||||
password: json['password'] as String,
|
||||
name: json['name'] as String,
|
||||
);
|
||||
|
||||
final String email;
|
||||
|
||||
final String password;
|
||||
|
||||
final String name;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'email': email,
|
||||
'password': password,
|
||||
'name': name,
|
||||
};
|
||||
}
|
||||
|
||||
class LoginRequest {
|
||||
const LoginRequest({required this.email, required this.password, this.mfaId});
|
||||
|
||||
factory LoginRequest.fromJson(Map<String, dynamic> json) => LoginRequest(
|
||||
email: json['email'] as String,
|
||||
password: json['password'] as String,
|
||||
mfaId: json['mfaId'] == null ? null : json['mfaId'] as String,
|
||||
);
|
||||
|
||||
final String email;
|
||||
|
||||
final String password;
|
||||
|
||||
final String? mfaId;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'email': email,
|
||||
'password': password,
|
||||
'mfaId': ?mfaId,
|
||||
};
|
||||
}
|
||||
|
||||
class EmailRequest {
|
||||
const EmailRequest({required this.email});
|
||||
|
||||
factory EmailRequest.fromJson(Map<String, dynamic> json) =>
|
||||
EmailRequest(email: json['email'] as String);
|
||||
|
||||
final String email;
|
||||
|
||||
Map<String, dynamic> toJson() => {'email': email};
|
||||
}
|
||||
|
||||
enum StatusStatus {
|
||||
ok('ok'),
|
||||
unavailable('unavailable');
|
||||
|
||||
const StatusStatus(this.value);
|
||||
final String value;
|
||||
|
||||
static StatusStatus fromJson(String value) => values.firstWhere(
|
||||
(e) => e.value == value,
|
||||
orElse: () => throw FormatException('unknown StatusStatus', value),
|
||||
);
|
||||
|
||||
String toJson() => value;
|
||||
}
|
||||
|
||||
class Status {
|
||||
const Status({required this.status, this.db});
|
||||
|
||||
factory Status.fromJson(Map<String, dynamic> json) => Status(
|
||||
status: StatusStatus.fromJson(json['status'] as String),
|
||||
db: json['db'] == null ? null : json['db'] as String,
|
||||
);
|
||||
|
||||
final StatusStatus status;
|
||||
|
||||
final String? db;
|
||||
|
||||
Map<String, dynamic> toJson() => {'status': status.toJson(), 'db': ?db};
|
||||
}
|
||||
|
||||
class Version {
|
||||
const Version({required this.name, required this.version});
|
||||
|
||||
factory Version.fromJson(Map<String, dynamic> json) =>
|
||||
Version(name: json['name'] as String, version: json['version'] as String);
|
||||
|
||||
final String name;
|
||||
|
||||
final String version;
|
||||
|
||||
Map<String, dynamic> toJson() => {'name': name, 'version': version};
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// The native side of the editor bridge (ADR-4). The editor page lives in
|
||||
// Packages/editor-bridge; keep these messages in sync with its protocol.ts.
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
/// Protocol version this app speaks. The page reports its own in "ready".
|
||||
const editorProtocolVersion = 1;
|
||||
|
||||
/// Formatting the native toolbar can apply.
|
||||
enum EditorCommand {
|
||||
bold,
|
||||
italic,
|
||||
strike,
|
||||
code,
|
||||
heading1,
|
||||
heading2,
|
||||
heading3,
|
||||
bulletList,
|
||||
orderedList,
|
||||
blockquote,
|
||||
codeBlock,
|
||||
undo,
|
||||
redo,
|
||||
}
|
||||
|
||||
/// Toolbar state reported by the page.
|
||||
@immutable
|
||||
class EditorState {
|
||||
const EditorState({
|
||||
this.active = const {},
|
||||
this.canUndo = false,
|
||||
this.canRedo = false,
|
||||
this.focused = false,
|
||||
});
|
||||
|
||||
factory EditorState.fromJson(Map<String, dynamic> json) => EditorState(
|
||||
active: {
|
||||
for (final name in (json['active'] as List).cast<String>())
|
||||
...EditorCommand.values.where((c) => c.name == name),
|
||||
},
|
||||
canUndo: json['canUndo'] as bool,
|
||||
canRedo: json['canRedo'] as bool,
|
||||
focused: json['focused'] as bool,
|
||||
);
|
||||
|
||||
final Set<EditorCommand> active;
|
||||
final bool canUndo;
|
||||
final bool canRedo;
|
||||
final bool focused;
|
||||
}
|
||||
|
||||
/// Drives the editor page. It does not know about the WebView: [evaluate]
|
||||
/// runs JavaScript in the page, and the host passes every message the page
|
||||
/// sends to [handleMessage].
|
||||
class EditorBridge extends ChangeNotifier {
|
||||
EditorBridge({required this.evaluate, this._content});
|
||||
|
||||
final Future<void> Function(String script) evaluate;
|
||||
|
||||
Map<String, dynamic>? _content;
|
||||
EditorState _state = const EditorState();
|
||||
bool _ready = false;
|
||||
String? _error;
|
||||
final _readyCompleter = Completer<void>();
|
||||
final _changes = StreamController<Map<String, dynamic>>.broadcast();
|
||||
|
||||
/// The latest document (Tiptap JSON), null until there is one.
|
||||
Map<String, dynamic>? get content => _content;
|
||||
EditorState get state => _state;
|
||||
bool get isReady => _ready;
|
||||
|
||||
/// Live-editing status after [connect]: connecting, connected, offline,
|
||||
/// denied or changed (see CollabStatus in @docwell/editor).
|
||||
String? get collabStatus => _collabStatus;
|
||||
String? _collabStatus;
|
||||
|
||||
/// Set when the page is missing, outdated or reported a problem.
|
||||
String? get error => _error;
|
||||
|
||||
/// Completes once the page answered and holds the initial content.
|
||||
Future<void> get ready => _readyCompleter.future;
|
||||
|
||||
/// Every edit the user makes.
|
||||
Stream<Map<String, dynamic>> get changes => _changes.stream;
|
||||
|
||||
/// Call once the page has loaded.
|
||||
Future<void> hello() => _post({'type': 'hello'});
|
||||
|
||||
Future<void> run(EditorCommand c) =>
|
||||
_post({'type': 'command', 'command': c.name});
|
||||
|
||||
Future<void> setContent(Map<String, dynamic>? content) {
|
||||
_content = content;
|
||||
return _post({'type': 'setContent', 'content': content});
|
||||
}
|
||||
|
||||
Future<void> setEditable(bool editable) =>
|
||||
_post({'type': 'setEditable', 'editable': editable});
|
||||
|
||||
Future<void> setTheme({required bool dark}) =>
|
||||
_post({'type': 'setTheme', 'dark': dark});
|
||||
|
||||
Future<void> focus() => _post({'type': 'focus'});
|
||||
|
||||
/// Edits the live page through docwell-server instead of local content.
|
||||
Future<void> connect({
|
||||
required String url,
|
||||
required String page,
|
||||
required String token,
|
||||
required String userName,
|
||||
required String userColor,
|
||||
}) => _post({
|
||||
'type': 'connect',
|
||||
'url': url,
|
||||
'page': page,
|
||||
'token': token,
|
||||
'user': {'name': userName, 'color': userColor},
|
||||
});
|
||||
|
||||
/// Handles one JSON message from the page.
|
||||
void handleMessage(String json) {
|
||||
final msg = jsonDecode(json) as Map<String, dynamic>;
|
||||
switch (msg['type']) {
|
||||
case 'ready':
|
||||
final version = msg['version'] as int;
|
||||
if (version != editorProtocolVersion) {
|
||||
_error =
|
||||
'Editor page speaks protocol $version, app expects '
|
||||
'$editorProtocolVersion';
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
// The page may say ready twice (start-up and hello); load content once.
|
||||
if (_ready) return;
|
||||
_ready = true;
|
||||
unawaited(
|
||||
setContent(_content).then((_) {
|
||||
if (!_readyCompleter.isCompleted) _readyCompleter.complete();
|
||||
}),
|
||||
);
|
||||
notifyListeners();
|
||||
case 'change':
|
||||
_content = msg['content'] as Map<String, dynamic>;
|
||||
_changes.add(_content!);
|
||||
case 'state':
|
||||
_state = EditorState.fromJson(msg['state'] as Map<String, dynamic>);
|
||||
notifyListeners();
|
||||
case 'collab':
|
||||
_collabStatus = msg['status'] as String;
|
||||
notifyListeners();
|
||||
case 'error':
|
||||
_error = msg['message'] as String;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _post(Map<String, dynamic> msg) =>
|
||||
evaluate('window.docwell.receive(${jsonEncode(jsonEncode(msg))})');
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_changes.close();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:webview_flutter/webview_flutter.dart';
|
||||
|
||||
import 'bridge.dart';
|
||||
|
||||
/// Where Packages/editor-bridge copies its build (`npm run build -w @docwell/editor-bridge`).
|
||||
const editorAsset = 'assets/editor/index.html';
|
||||
|
||||
/// The JavaScript channel the page posts to (see transport.ts).
|
||||
const _channel = 'DocwellNative';
|
||||
|
||||
/// The shared Tiptap editor in a WebView, with a native toolbar (ADR-4).
|
||||
class EditorScreen extends StatefulWidget {
|
||||
const EditorScreen({
|
||||
super.key,
|
||||
required this.title,
|
||||
this.content,
|
||||
this.onChanged,
|
||||
this.onBridge,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final Map<String, dynamic>? content;
|
||||
final ValueChanged<Map<String, dynamic>>? onChanged;
|
||||
|
||||
/// Hands out the bridge once the WebView exists (tests drive it).
|
||||
final ValueChanged<EditorBridge>? onBridge;
|
||||
|
||||
@override
|
||||
State<EditorScreen> createState() => _EditorScreenState();
|
||||
}
|
||||
|
||||
class _EditorScreenState extends State<EditorScreen> {
|
||||
final _web = WebViewController();
|
||||
late final EditorBridge _bridge = EditorBridge(
|
||||
content: widget.content,
|
||||
evaluate: _web.runJavaScript,
|
||||
);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_bridge.addListener(() => setState(() {}));
|
||||
_bridge.changes.listen((c) => widget.onChanged?.call(c));
|
||||
_web
|
||||
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
||||
..setBackgroundColor(Colors.transparent)
|
||||
..addJavaScriptChannel(
|
||||
_channel,
|
||||
onMessageReceived: (m) => _bridge.handleMessage(m.message),
|
||||
)
|
||||
..setNavigationDelegate(
|
||||
NavigationDelegate(
|
||||
onPageFinished: (_) async {
|
||||
if (!mounted) return;
|
||||
final dark = Theme.of(context).brightness == Brightness.dark;
|
||||
await _bridge.setTheme(dark: dark);
|
||||
await _bridge.hello();
|
||||
},
|
||||
// The page is bundled and never navigates; links open nowhere.
|
||||
onNavigationRequest: (req) => req.url.startsWith('file:')
|
||||
? NavigationDecision.navigate
|
||||
: NavigationDecision.prevent,
|
||||
),
|
||||
)
|
||||
..loadFlutterAsset(editorAsset);
|
||||
widget.onBridge?.call(_bridge);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_bridge.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(widget.title)),
|
||||
body: Column(
|
||||
children: [
|
||||
if (_bridge.error != null)
|
||||
MaterialBanner(
|
||||
content: Text(_bridge.error!),
|
||||
actions: const [SizedBox.shrink()],
|
||||
),
|
||||
Expanded(
|
||||
child: Stack(
|
||||
children: [
|
||||
WebViewWidget(controller: _web),
|
||||
if (!_bridge.isReady)
|
||||
const Center(child: CircularProgressIndicator()),
|
||||
],
|
||||
),
|
||||
),
|
||||
_Toolbar(bridge: _bridge),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Formatting buttons above the keyboard, lit up from the page's state.
|
||||
class _Toolbar extends StatelessWidget {
|
||||
const _Toolbar({required this.bridge});
|
||||
|
||||
final EditorBridge bridge;
|
||||
|
||||
static const _buttons = [
|
||||
(EditorCommand.bold, Icons.format_bold, 'Bold'),
|
||||
(EditorCommand.italic, Icons.format_italic, 'Italic'),
|
||||
(EditorCommand.strike, Icons.format_strikethrough, 'Strikethrough'),
|
||||
(EditorCommand.heading1, Icons.title, 'Heading'),
|
||||
(EditorCommand.bulletList, Icons.format_list_bulleted, 'Bulleted list'),
|
||||
(EditorCommand.orderedList, Icons.format_list_numbered, 'Numbered list'),
|
||||
(EditorCommand.blockquote, Icons.format_quote, 'Quote'),
|
||||
(EditorCommand.codeBlock, Icons.code, 'Code block'),
|
||||
];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final state = bridge.state;
|
||||
return Material(
|
||||
elevation: 2,
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: [
|
||||
IconButton(
|
||||
tooltip: 'Undo',
|
||||
icon: const Icon(Icons.undo),
|
||||
onPressed: state.canUndo
|
||||
? () => bridge.run(EditorCommand.undo)
|
||||
: null,
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Redo',
|
||||
icon: const Icon(Icons.redo),
|
||||
onPressed: state.canRedo
|
||||
? () => bridge.run(EditorCommand.redo)
|
||||
: null,
|
||||
),
|
||||
for (final (command, icon, label) in _buttons)
|
||||
IconButton(
|
||||
key: Key('tool-${command.name}'),
|
||||
tooltip: label,
|
||||
icon: Icon(icon),
|
||||
isSelected: state.active.contains(command),
|
||||
onPressed: bridge.isReady ? () => bridge.run(command) : null,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+38
-4
@@ -3,6 +3,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'api/docwell_api.dart';
|
||||
import 'editor/editor_screen.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const DocwellApp());
|
||||
@@ -178,10 +179,30 @@ class HomeScreen extends StatefulWidget {
|
||||
State<HomeScreen> createState() => _HomeScreenState();
|
||||
}
|
||||
|
||||
String _roleLabel(String role) => switch (role) {
|
||||
'superadmin' => 'Superadmin',
|
||||
'admin' => 'Admin',
|
||||
_ => 'User',
|
||||
String _roleLabel(Role role) => switch (role) {
|
||||
Role.superadmin => 'Superadmin',
|
||||
Role.admin => 'Admin',
|
||||
Role.user => 'User',
|
||||
};
|
||||
|
||||
/// A local page for trying the WebView editor before pages sync to mobile.
|
||||
const _scratchPage = {
|
||||
'type': 'doc',
|
||||
'content': [
|
||||
{
|
||||
'type': 'heading',
|
||||
'attrs': {'level': 1},
|
||||
'content': [
|
||||
{'type': 'text', 'text': 'Scratch page'},
|
||||
],
|
||||
},
|
||||
{
|
||||
'type': 'paragraph',
|
||||
'content': [
|
||||
{'type': 'text', 'text': 'This is the same editor as the web app.'},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
class _HomeScreenState extends State<HomeScreen> {
|
||||
@@ -238,6 +259,19 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
return Text('Connected · v${snap.data}');
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
OutlinedButton.icon(
|
||||
icon: const Icon(Icons.edit_note),
|
||||
label: const Text('Try the editor'),
|
||||
onPressed: () => Navigator.of(context).push(
|
||||
MaterialPageRoute<void>(
|
||||
builder: (_) => const EditorScreen(
|
||||
title: 'Scratch page',
|
||||
content: _scratchPage,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
+104
-1
@@ -57,11 +57,24 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.3.3"
|
||||
file:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file
|
||||
sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.0.1"
|
||||
flutter:
|
||||
dependency: "direct main"
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_driver:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_lints:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
@@ -75,6 +88,11 @@ packages:
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
fuchsia_remote_debug_protocol:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
http:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -91,6 +109,11 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.1.2"
|
||||
integration_test:
|
||||
dependency: "direct dev"
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
leak_tracker:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -155,6 +178,30 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.9.1"
|
||||
platform:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: platform
|
||||
sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.2.0"
|
||||
plugin_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: plugin_platform_interface
|
||||
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.8"
|
||||
process:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: process
|
||||
sha256: "4242ba3508d37e01808bdf71ad1d5bb93a8d671bf2e7450e6b1b353fb0808891"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.0.6"
|
||||
sky_engine:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
@@ -192,6 +239,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.4.1"
|
||||
sync_http:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: sync_http
|
||||
sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.1"
|
||||
term_glyph:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -240,6 +295,54 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
webdriver:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: webdriver
|
||||
sha256: "28b82ec894fed45dd71c23ba62d1af973ed97dd59a4f5790a4d38b0b13e5657e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.2.0"
|
||||
webview_flutter:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: webview_flutter
|
||||
sha256: d53e1ccf5516f25017e3c9d44c39034db352d20fa34fe200674270242c2c5111
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.14.1"
|
||||
webview_flutter_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: webview_flutter_android
|
||||
sha256: "4de8b3d1ff4ebe1bdb42e68a5e4f809194a3cb0117a8f495f590004f00da3964"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.14.1"
|
||||
webview_flutter_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: webview_flutter_platform_interface
|
||||
sha256: "1221c1b12f5278791042f2ec2841743784cf25c5a644e23d6680e5d718824f04"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.15.1"
|
||||
webview_flutter_wkwebview:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: webview_flutter_wkwebview
|
||||
sha256: "0f784be1b080e5b918ef7c2c070c1f4616899fd23f1d001feb74b4978f92bdbc"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.26.2"
|
||||
yaml:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: yaml
|
||||
sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.1.4"
|
||||
sdks:
|
||||
dart: ">=3.12.2 <4.0.0"
|
||||
flutter: ">=3.18.0-18.0.pre.54"
|
||||
flutter: ">=3.44.0"
|
||||
@@ -35,7 +35,7 @@ dependencies:
|
||||
# Use with the CupertinoIcons class for iOS style icons.
|
||||
cupertino_icons: ^1.0.8
|
||||
http: ^1.6.0
|
||||
|
||||
webview_flutter: ^4.14.1
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
@@ -46,6 +46,9 @@ dev_dependencies:
|
||||
# package. See that file for information about deactivating specific lint
|
||||
# rules and activating additional ones.
|
||||
flutter_lints: ^6.0.0
|
||||
yaml: ^3.1.4
|
||||
integration_test:
|
||||
sdk: flutter
|
||||
|
||||
# For information on the generic Dart part of this file, see the
|
||||
# following page: https://dart.dev/tools/pub/pubspec
|
||||
@@ -58,6 +61,10 @@ flutter:
|
||||
# the material Icons class.
|
||||
uses-material-design: true
|
||||
|
||||
# The shared editor page, built by Packages/editor-bridge (ADR-4).
|
||||
assets:
|
||||
- assets/editor/
|
||||
|
||||
# To add assets to your application, add an assets section, like this:
|
||||
# assets:
|
||||
# - images/a_dot_burr.jpeg
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:docwell_mobile/editor/bridge.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
/// Decodes what the bridge asked the page to receive.
|
||||
Map<String, dynamic> sentMessage(String script) {
|
||||
final m = RegExp(
|
||||
r'^window\.docwell\.receive\((.*)\)$',
|
||||
dotAll: true,
|
||||
).firstMatch(script)!;
|
||||
return jsonDecode(jsonDecode(m[1]!) as String) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
void main() {
|
||||
const doc = {
|
||||
'type': 'doc',
|
||||
'content': [
|
||||
{'type': 'paragraph'},
|
||||
],
|
||||
};
|
||||
|
||||
late List<Map<String, dynamic>> sent;
|
||||
late EditorBridge bridge;
|
||||
setUp(() {
|
||||
sent = [];
|
||||
bridge = EditorBridge(
|
||||
content: doc,
|
||||
evaluate: (js) async => sent.add(sentMessage(js)),
|
||||
);
|
||||
});
|
||||
|
||||
test('loads the content once the page is ready, only once', () async {
|
||||
bridge.handleMessage('{"type":"ready","version":$editorProtocolVersion}');
|
||||
bridge.handleMessage('{"type":"ready","version":$editorProtocolVersion}');
|
||||
await bridge.ready;
|
||||
expect(bridge.isReady, isTrue);
|
||||
expect(sent, [
|
||||
{'type': 'setContent', 'content': doc},
|
||||
]);
|
||||
});
|
||||
|
||||
test('refuses a page that speaks another protocol version', () {
|
||||
bridge.handleMessage('{"type":"ready","version":99}');
|
||||
expect(bridge.isReady, isFalse);
|
||||
expect(bridge.error, contains('protocol 99'));
|
||||
});
|
||||
|
||||
test('sends commands and tracks content and toolbar state', () async {
|
||||
final changes = <Map<String, dynamic>>[];
|
||||
bridge.changes.listen(changes.add);
|
||||
|
||||
await bridge.run(EditorCommand.bold);
|
||||
bridge.handleMessage(
|
||||
'{"type":"state","state":{"active":["bold","heading2","future"],'
|
||||
'"canUndo":true,"canRedo":false,"focused":true}}',
|
||||
);
|
||||
bridge.handleMessage('{"type":"change","content":{"type":"doc"}}');
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(sent.last, {'type': 'command', 'command': 'bold'});
|
||||
expect(bridge.state.active, {EditorCommand.bold, EditorCommand.heading2});
|
||||
expect(bridge.state.canUndo, isTrue);
|
||||
expect(bridge.content, {'type': 'doc'});
|
||||
expect(changes, [
|
||||
{'type': 'doc'},
|
||||
]);
|
||||
});
|
||||
|
||||
test('escapes content safely into the script', () async {
|
||||
await bridge.setContent({
|
||||
'type': 'doc',
|
||||
'text': "it's \"quoted\" </script> \u2028",
|
||||
});
|
||||
expect(sent.last['content']['text'], "it's \"quoted\" </script> \u2028");
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:docwell_mobile/api/docwell_api.dart';
|
||||
@@ -11,6 +13,12 @@ const ann = {
|
||||
'id': 'u1',
|
||||
'email': 'ann@docwell.test',
|
||||
'name': 'Ann',
|
||||
'avatar': '',
|
||||
'locale': 'en',
|
||||
'theme': 'system',
|
||||
'status': 'active',
|
||||
'verified': true,
|
||||
'created': '2026-10-01 09:00:00.000Z',
|
||||
'role': 'admin',
|
||||
'organization': 'o1',
|
||||
'organizationName': 'Acme',
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Generates Dart models from the schemas in api/openapi.yaml.
|
||||
//
|
||||
// dart run tool/generate_api.dart (from Phone-App/)
|
||||
//
|
||||
// Handles what the contract uses: objects, string enums, $ref, arrays, maps
|
||||
// (additionalProperties) and "object or null". Inline objects and enums become
|
||||
// classes named after their parent and property (WorkspaceMember.user ->
|
||||
// WorkspaceMemberUser).
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:yaml/yaml.dart';
|
||||
|
||||
const _specPath = '../api/openapi.yaml';
|
||||
const _outPath = 'lib/api/generated/models.dart';
|
||||
|
||||
void main() {
|
||||
final spec = loadYaml(File(_specPath).readAsStringSync()) as YamlMap;
|
||||
final schemas = (spec['components'] as YamlMap)['schemas'] as YamlMap;
|
||||
final gen = _Generator({
|
||||
for (final e in schemas.entries)
|
||||
if ((e.value as YamlMap)['enum'] != null) e.key as String,
|
||||
});
|
||||
for (final entry in schemas.entries) {
|
||||
gen.schema(_className(entry.key as String), entry.value as YamlMap);
|
||||
}
|
||||
File(_outPath)
|
||||
..createSync(recursive: true)
|
||||
..writeAsStringSync(gen.render());
|
||||
final fmt = Process.runSync('dart', ['format', _outPath], runInShell: true);
|
||||
if (fmt.exitCode != 0) {
|
||||
stderr.write(fmt.stderr);
|
||||
exit(fmt.exitCode);
|
||||
}
|
||||
stdout.writeln('wrote $_outPath (${schemas.length} schemas)');
|
||||
}
|
||||
|
||||
/// Schema names that would hide a dart:core type get an Api prefix (Error -> ApiError).
|
||||
const _coreNames = {
|
||||
'Error',
|
||||
'Exception',
|
||||
'Object',
|
||||
'Type',
|
||||
'List',
|
||||
'Map',
|
||||
'Set',
|
||||
'Duration',
|
||||
'Uri',
|
||||
};
|
||||
|
||||
String _className(String schema) =>
|
||||
_coreNames.contains(schema) ? 'Api$schema' : schema;
|
||||
|
||||
class _Field {
|
||||
_Field(this.name, this.type, this.required, this.description);
|
||||
final String name;
|
||||
final _Type type;
|
||||
final bool required;
|
||||
final String? description;
|
||||
}
|
||||
|
||||
/// A Dart type plus how to convert it from and to JSON.
|
||||
class _Type {
|
||||
_Type(this.dart, this.fromJson, this.toJson, {this.nullable = false});
|
||||
final String dart;
|
||||
final String Function(String v) fromJson;
|
||||
final String Function(String v) toJson;
|
||||
final bool nullable;
|
||||
}
|
||||
|
||||
class _Generator {
|
||||
_Generator(this.enumSchemas);
|
||||
|
||||
final Set<String> enumSchemas;
|
||||
final _out = <String>[];
|
||||
|
||||
String render() => [
|
||||
'// SPDX-License-Identifier: AGPL-3.0-or-later',
|
||||
'',
|
||||
'// Code generated by tool/generate_api.dart from api/openapi.yaml. DO NOT EDIT.',
|
||||
'',
|
||||
'// ignore_for_file: constant_identifier_names',
|
||||
'',
|
||||
..._out,
|
||||
].join('\n');
|
||||
|
||||
void schema(String name, YamlMap s) {
|
||||
if (s['enum'] != null) {
|
||||
_enum(name, s);
|
||||
} else if (s['type'] == 'object') {
|
||||
_class(name, s);
|
||||
} else {
|
||||
throw UnsupportedError('schema $name: type ${s['type']}');
|
||||
}
|
||||
}
|
||||
|
||||
void _enum(String name, YamlMap s) {
|
||||
final values = (s['enum'] as YamlList).cast<String>();
|
||||
final b = StringBuffer();
|
||||
_doc(b, s['description'] as String?, '');
|
||||
b.writeln('enum $name {');
|
||||
for (final v in values) {
|
||||
b.writeln(" ${_ident(v)}('$v'),");
|
||||
}
|
||||
b.writeln(' ;');
|
||||
b.writeln();
|
||||
b.writeln(' const $name(this.value);');
|
||||
b.writeln(' final String value;');
|
||||
b.writeln();
|
||||
b.writeln(' static $name fromJson(String value) =>');
|
||||
b.writeln(' values.firstWhere((e) => e.value == value,');
|
||||
b.writeln(
|
||||
" orElse: () => throw FormatException('unknown $name', value));",
|
||||
);
|
||||
b.writeln();
|
||||
b.writeln(' String toJson() => value;');
|
||||
b.writeln('}');
|
||||
_out.add(b.toString());
|
||||
}
|
||||
|
||||
void _class(String name, YamlMap s) {
|
||||
final required = ((s['required'] as YamlList?) ?? YamlList())
|
||||
.cast<String>();
|
||||
final props = (s['properties'] as YamlMap?) ?? YamlMap();
|
||||
final fields = <_Field>[];
|
||||
for (final e in props.entries) {
|
||||
final prop = e.key as String;
|
||||
final ps = e.value as YamlMap;
|
||||
fields.add(
|
||||
_Field(
|
||||
prop,
|
||||
_type(name + _pascal(prop), ps),
|
||||
required.contains(prop),
|
||||
ps['description'] as String?,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final b = StringBuffer();
|
||||
_doc(b, s['description'] as String?, '');
|
||||
b.writeln('class $name {');
|
||||
if (fields.isEmpty) {
|
||||
b.writeln(' const $name();');
|
||||
} else {
|
||||
b.writeln(' const $name({');
|
||||
for (final f in fields) {
|
||||
b.writeln(
|
||||
' ${f.required ? 'required ' : ''}this.${_ident(f.name)},',
|
||||
);
|
||||
}
|
||||
b.writeln(' });');
|
||||
}
|
||||
b.writeln();
|
||||
b.writeln(' factory $name.fromJson(Map<String, dynamic> json) => $name(');
|
||||
for (final f in fields) {
|
||||
final v = "json['${f.name}']";
|
||||
final conv = f.required && !f.type.nullable
|
||||
? f.type.fromJson(v)
|
||||
: '$v == null ? null : ${f.type.fromJson(v)}';
|
||||
b.writeln(' ${_ident(f.name)}: $conv,');
|
||||
}
|
||||
b.writeln(' );');
|
||||
for (final f in fields) {
|
||||
b.writeln();
|
||||
_doc(b, f.description, ' ');
|
||||
final opt = !f.required || f.type.nullable;
|
||||
b.writeln(' final ${f.type.dart}${opt ? '?' : ''} ${_ident(f.name)};');
|
||||
}
|
||||
b.writeln();
|
||||
b.writeln(' Map<String, dynamic> toJson() => {');
|
||||
for (final f in fields) {
|
||||
final id = _ident(f.name);
|
||||
// `id?` short-circuits the conversion chain when the value is null.
|
||||
final plain = f.type.toJson('x') == 'x';
|
||||
final maybe = plain ? id : f.type.toJson('$id?');
|
||||
if (f.required) {
|
||||
b.writeln(
|
||||
" '${f.name}': ${f.type.nullable ? maybe : f.type.toJson(id)},",
|
||||
);
|
||||
} else {
|
||||
b.writeln(" '${f.name}': ?$maybe,");
|
||||
}
|
||||
}
|
||||
b.writeln(' };');
|
||||
b.writeln('}');
|
||||
_out.add(b.toString());
|
||||
}
|
||||
|
||||
_Type _type(String inlineName, YamlMap s) {
|
||||
final ref = s[r'$ref'] as String?;
|
||||
if (ref != null) {
|
||||
final target = _className(ref.split('/').last);
|
||||
return _Type(
|
||||
target,
|
||||
(v) =>
|
||||
'$target.fromJson($v as ${_isEnumRef(s) ? 'String' : 'Map<String, dynamic>'})',
|
||||
(v) => '$v.toJson()',
|
||||
);
|
||||
}
|
||||
final oneOf = s['oneOf'] as YamlList?;
|
||||
if (oneOf != null) {
|
||||
final nonNull = oneOf
|
||||
.cast<YamlMap>()
|
||||
.where((o) => o['type'] != 'null')
|
||||
.toList();
|
||||
if (nonNull.length != 1 || nonNull.length == oneOf.length) {
|
||||
throw UnsupportedError(
|
||||
'$inlineName: only "T or null" oneOf is supported',
|
||||
);
|
||||
}
|
||||
final t = _type(inlineName, nonNull.single);
|
||||
return _Type(t.dart, t.fromJson, t.toJson, nullable: true);
|
||||
}
|
||||
if (s['enum'] != null) {
|
||||
_enum(inlineName, s);
|
||||
return _Type(
|
||||
inlineName,
|
||||
(v) => '$inlineName.fromJson($v as String)',
|
||||
(v) => '$v.toJson()',
|
||||
);
|
||||
}
|
||||
switch (s['type']) {
|
||||
case 'string':
|
||||
return _Type('String', (v) => '$v as String', (v) => v);
|
||||
case 'integer':
|
||||
return _Type('int', (v) => '($v as num).toInt()', (v) => v);
|
||||
case 'number':
|
||||
return _Type('double', (v) => '($v as num).toDouble()', (v) => v);
|
||||
case 'boolean':
|
||||
return _Type('bool', (v) => '$v as bool', (v) => v);
|
||||
case 'array':
|
||||
final item = _type(inlineName, s['items'] as YamlMap);
|
||||
return _Type(
|
||||
'List<${item.dart}>',
|
||||
(v) => '($v as List).map((e) => ${item.fromJson('e')}).toList()',
|
||||
(v) => '$v.map((e) => ${item.toJson('e')}).toList()',
|
||||
);
|
||||
case 'object':
|
||||
final extra = s['additionalProperties'];
|
||||
if (s['properties'] != null) {
|
||||
_class(inlineName, s);
|
||||
return _Type(
|
||||
inlineName,
|
||||
(v) => '$inlineName.fromJson($v as Map<String, dynamic>)',
|
||||
(v) => '$v.toJson()',
|
||||
);
|
||||
}
|
||||
if (extra is YamlMap) {
|
||||
final val = _type(inlineName, extra);
|
||||
final plain = val.toJson('e') == 'e';
|
||||
return _Type(
|
||||
'Map<String, ${val.dart}>',
|
||||
(v) =>
|
||||
'($v as Map<String, dynamic>).map((k, e) => MapEntry(k, ${val.fromJson('e')}))',
|
||||
(v) =>
|
||||
plain ? v : '$v.map((k, e) => MapEntry(k, ${val.toJson('e')}))',
|
||||
);
|
||||
}
|
||||
return _Type(
|
||||
'Map<String, dynamic>',
|
||||
(v) => '$v as Map<String, dynamic>',
|
||||
(v) => v,
|
||||
);
|
||||
}
|
||||
throw UnsupportedError('$inlineName: type ${s['type']}');
|
||||
}
|
||||
|
||||
// Enum schemas are referenced by name; the spec's enums are all strings.
|
||||
bool _isEnumRef(YamlMap s) =>
|
||||
enumSchemas.contains((s[r'$ref'] as String).split('/').last);
|
||||
|
||||
static void _doc(StringBuffer b, String? text, String indent) {
|
||||
if (text == null) return;
|
||||
for (final line in text.trim().split('\n')) {
|
||||
b.writeln('$indent/// ${line.trim()}');
|
||||
}
|
||||
}
|
||||
|
||||
static String _pascal(String s) => s[0].toUpperCase() + s.substring(1);
|
||||
|
||||
static const _reserved = {
|
||||
'default',
|
||||
'enum',
|
||||
'class',
|
||||
'new',
|
||||
'switch',
|
||||
'in',
|
||||
'is',
|
||||
};
|
||||
|
||||
static String _ident(String s) {
|
||||
final id = s.replaceAllMapped(
|
||||
RegExp(r'[-_ ](\w)'),
|
||||
(m) => m[1]!.toUpperCase(),
|
||||
);
|
||||
return _reserved.contains(id) ? '${id}_' : id;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
An open-source, self-hostable knowledge base and collaborative document editor. It is wiki-first like Docmost and Outline, and will grow Notion-style databases later.
|
||||
|
||||
> Status: **Phase 0 scaffold.** All services build and run, but no product features exist yet.
|
||||
> Status: **Phase 0 done; Phase 1 (MVP wiki) in progress.** Sign-in, organizations, workspaces, spaces, the page tree, the editor and real-time collaboration with page history work. Most of the MVP (search, comments, sharing, import and export) is still to come.
|
||||
|
||||
## Components
|
||||
|
||||
@@ -13,7 +13,7 @@ An open-source, self-hostable knowledge base and collaborative document editor.
|
||||
| `Web-App/` | **docwell-web**: serves the end-user web app | Go 1.26, Vue 3, Tailwind CSS 4, Tiptap |
|
||||
| `Desktop-App/` | Desktop app; reuses the web app UI | Wails v3 |
|
||||
| `Phone-App/` | Mobile app (Android, iOS) | Flutter |
|
||||
| `Packages/` | Shared frontend code: `@docwell/editor`, `@docwell/ui`, `@docwell/api-client` | TypeScript |
|
||||
| `Packages/` | Shared frontend code: `@docwell/editor`, `@docwell/ui`, `@docwell/api-client`, and `@docwell/editor-bridge` (the editor as one HTML page for the phone app's WebView) | TypeScript |
|
||||
| `Docker/` | The three services as separate containers | docker compose |
|
||||
| `Docker-AIO/` | Everything in one container | docker compose |
|
||||
|
||||
@@ -91,24 +91,29 @@ npm run dev:admin
|
||||
# Desktop app (from Desktop-App/)
|
||||
wails3 dev
|
||||
|
||||
# Mobile app (from Phone-App/), e.g. on an Android emulator
|
||||
# Mobile app (from Phone-App/), e.g. on an Android emulator. Build the editor
|
||||
# page into its assets first: npm run build -w @docwell/editor-bridge
|
||||
flutter run
|
||||
```
|
||||
|
||||
Tests and checks:
|
||||
Tests and checks (CI runs all of them; see [CONTRIBUTING.md](CONTRIBUTING.md)):
|
||||
|
||||
```bash
|
||||
go test ./Server/... ./Web-App/... ./Desktop-App/
|
||||
npm run typecheck && npm test
|
||||
npm run lint && npm run format:check && npm run typecheck && npm test
|
||||
cd Phone-App && flutter analyze && flutter test
|
||||
```
|
||||
|
||||
After changing `api/openapi.yaml`, regenerate the TypeScript types:
|
||||
Go code is linted with `golangci-lint run` from each module folder.
|
||||
|
||||
After changing `api/openapi.yaml`, regenerate the TypeScript, Go and Dart types:
|
||||
|
||||
```bash
|
||||
npm run generate -w @docwell/api-client
|
||||
npm run generate
|
||||
```
|
||||
|
||||
Desktop release builds set the update feed and its signing key; see [Desktop-App/updates.go](Desktop-App/updates.go). Development builds never update themselves.
|
||||
|
||||
## License
|
||||
|
||||
[GNU Affero General Public License v3.0 or later](LICENSE).
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import { DwBadge, DwButton, DwLogo, useTheme } from "@docwell/ui";
|
||||
import { useRouter } from "vue-router";
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { createApp } from "vue";
|
||||
import { createRouter, createWebHistory } from "vue-router";
|
||||
import App from "./App.vue";
|
||||
@@ -11,10 +13,30 @@ const router = createRouter({
|
||||
{ path: "/", name: "overview", component: () => import("./views/OverviewView.vue") },
|
||||
{ path: "/users", name: "users", component: () => import("./views/UsersView.vue") },
|
||||
{ path: "/organizations", name: "organizations", component: () => import("./views/OrganizationsView.vue") },
|
||||
{ path: "/authentication", name: "authentication", component: () => import("./views/PlaceholderView.vue"), meta: { title: "Authentication", superadmin: true } },
|
||||
{ path: "/storage", name: "storage", component: () => import("./views/PlaceholderView.vue"), meta: { title: "Storage", superadmin: true } },
|
||||
{ path: "/email", name: "email", component: () => import("./views/PlaceholderView.vue"), meta: { title: "Email", superadmin: true } },
|
||||
{ path: "/maintenance", name: "maintenance", component: () => import("./views/PlaceholderView.vue"), meta: { title: "Maintenance", superadmin: true } },
|
||||
{
|
||||
path: "/authentication",
|
||||
name: "authentication",
|
||||
component: () => import("./views/PlaceholderView.vue"),
|
||||
meta: { title: "Authentication", superadmin: true },
|
||||
},
|
||||
{
|
||||
path: "/storage",
|
||||
name: "storage",
|
||||
component: () => import("./views/PlaceholderView.vue"),
|
||||
meta: { title: "Storage", superadmin: true },
|
||||
},
|
||||
{
|
||||
path: "/email",
|
||||
name: "email",
|
||||
component: () => import("./views/PlaceholderView.vue"),
|
||||
meta: { title: "Email", superadmin: true },
|
||||
},
|
||||
{
|
||||
path: "/maintenance",
|
||||
name: "maintenance",
|
||||
component: () => import("./views/PlaceholderView.vue"),
|
||||
meta: { title: "Maintenance", superadmin: true },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { ApiError, createClient, createTokenStore, isManager, type User } from "@docwell/api-client";
|
||||
import { computed, ref } from "vue";
|
||||
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
/* SPDX-License-Identifier: AGPL-3.0-or-later */
|
||||
|
||||
@import "tailwindcss";
|
||||
@import "@docwell/ui/theme.css";
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import { ApiError } from "@docwell/api-client";
|
||||
import { DwBadge, DwButton, DwCallout, DwLogo, DwTextField } from "@docwell/ui";
|
||||
@@ -16,7 +17,8 @@ const messages: Record<string, string> = {
|
||||
invalid_credentials: "Wrong email or password.",
|
||||
forbidden: "Only organization admins and superadmins can use the admin panel.",
|
||||
account_disabled: "This account is disabled.",
|
||||
mfa_required: "This account uses two-step sign-in. Sign in to the web app first; MFA for the admin panel is not supported yet.",
|
||||
mfa_required:
|
||||
"This account uses two-step sign-in. Sign in to the web app first; MFA for the admin panel is not supported yet.",
|
||||
};
|
||||
|
||||
async function submit() {
|
||||
@@ -24,7 +26,8 @@ async function submit() {
|
||||
error.value = "";
|
||||
try {
|
||||
await signIn(email.value, password.value);
|
||||
const redirect = typeof route.query.redirect === "string" && route.query.redirect.startsWith("/") ? route.query.redirect : "/";
|
||||
const redirect =
|
||||
typeof route.query.redirect === "string" && route.query.redirect.startsWith("/") ? route.query.redirect : "/";
|
||||
router.replace(redirect);
|
||||
} catch (e) {
|
||||
error.value = e instanceof ApiError ? (messages[e.code] ?? "Sign-in failed.") : "Can't reach the server.";
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { Organization } from "@docwell/api-client";
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
@@ -96,14 +97,11 @@ async function remove(o: Organization) {
|
||||
<form v-if="editing" class="mt-4 flex flex-wrap items-end gap-2 dw-card !p-4" @submit.prevent="save">
|
||||
<label class="flex flex-1 flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Name</span>
|
||||
<input
|
||||
v-model="draft"
|
||||
required
|
||||
maxlength="120"
|
||||
class="dw-input w-full"
|
||||
/>
|
||||
<input v-model="draft" required maxlength="120" class="dw-input w-full" />
|
||||
</label>
|
||||
<DwButton type="submit" variant="primary" :disabled="busy || !draft.trim()">{{ editing === "new" ? "Create" : "Save" }}</DwButton>
|
||||
<DwButton type="submit" variant="primary" :disabled="busy || !draft.trim()">{{
|
||||
editing === "new" ? "Create" : "Save"
|
||||
}}</DwButton>
|
||||
<DwButton variant="ghost" :disabled="busy" @click="editing = null">Cancel</DwButton>
|
||||
</form>
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import { ApiError, type Status, type Version } from "@docwell/api-client";
|
||||
import { DwCallout } from "@docwell/ui";
|
||||
@@ -44,7 +45,10 @@ onMounted(async () => {
|
||||
{{ readiness ? (readiness.status === "ok" ? "Connected" : "Unavailable") : "…" }}
|
||||
</div>
|
||||
</div>
|
||||
<RouterLink to="/users" class="rounded-md border border-line bg-surface-raised p-4 transition-colors duration-[120ms] hover:border-line-strong">
|
||||
<RouterLink
|
||||
to="/users"
|
||||
class="rounded-md border border-line bg-surface-raised p-4 transition-colors duration-[120ms] hover:border-line-strong"
|
||||
>
|
||||
<div class="text-ui-sm text-ink-muted">Users</div>
|
||||
<div class="mt-1 text-ui-lg" data-testid="user-count">{{ userCount ?? "…" }}</div>
|
||||
</RouterLink>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<template>
|
||||
<h1 class="text-2xl font-semibold tracking-tight">{{ $route.meta.title }}</h1>
|
||||
<p class="mt-2 text-ui-md text-ink-muted">Not built yet. See docs/PLAN.md, section 8.</p>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { Organization, Role, User, UserList } from "@docwell/api-client";
|
||||
import { DwBadge, DwButton, DwCallout } from "@docwell/ui";
|
||||
@@ -60,7 +61,14 @@ function startNew() {
|
||||
|
||||
function startEdit(u: User) {
|
||||
editing.value = u;
|
||||
Object.assign(form, { name: u.name, email: u.email, password: "", role: u.role, organization: u.organization, status: u.status });
|
||||
Object.assign(form, {
|
||||
name: u.name,
|
||||
email: u.email,
|
||||
password: "",
|
||||
role: u.role,
|
||||
organization: u.organization,
|
||||
status: u.status,
|
||||
});
|
||||
}
|
||||
|
||||
const isSelf = computed(() => editing.value !== "new" && editing.value?.id === currentUser.value?.id);
|
||||
@@ -112,7 +120,6 @@ async function remove(u: User) {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -127,7 +134,13 @@ async function remove(u: User) {
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex flex-wrap gap-2">
|
||||
<input v-model="search" type="search" placeholder="Search name or email" aria-label="Search users" class="dw-input sm:w-64" />
|
||||
<input
|
||||
v-model="search"
|
||||
type="search"
|
||||
placeholder="Search name or email"
|
||||
aria-label="Search users"
|
||||
class="dw-input sm:w-64"
|
||||
/>
|
||||
<select v-if="isSuperadmin" v-model="orgFilter" aria-label="Filter by organization" class="dw-input sm:w-56">
|
||||
<option value="">All organizations</option>
|
||||
<option value="none">No organization</option>
|
||||
@@ -149,7 +162,14 @@ async function remove(u: User) {
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">{{ editing === "new" ? "Password" : "New password (optional)" }}</span>
|
||||
<input v-model="form.password" type="password" autocomplete="new-password" :required="editing === 'new'" minlength="8" class="dw-input" />
|
||||
<input
|
||||
v-model="form.password"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
:required="editing === 'new'"
|
||||
minlength="8"
|
||||
class="dw-input"
|
||||
/>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">Role</span>
|
||||
@@ -173,7 +193,9 @@ async function remove(u: User) {
|
||||
</select>
|
||||
</label>
|
||||
<div class="flex gap-2 sm:col-span-2">
|
||||
<DwButton type="submit" variant="primary" :disabled="busy">{{ editing === "new" ? "Create user" : "Save" }}</DwButton>
|
||||
<DwButton type="submit" variant="primary" :disabled="busy">{{
|
||||
editing === "new" ? "Create user" : "Save"
|
||||
}}</DwButton>
|
||||
<DwButton variant="ghost" :disabled="busy" @click="editing = null">Cancel</DwButton>
|
||||
</div>
|
||||
</form>
|
||||
@@ -197,12 +219,23 @@ async function remove(u: User) {
|
||||
<td class="px-4 py-2">{{ roleLabel[u.role] }}</td>
|
||||
<td v-if="isSuperadmin" class="px-4 py-2">{{ u.organizationName || "—" }}</td>
|
||||
<td class="px-4 py-2">
|
||||
<DwBadge :tone="u.status === 'active' ? 'success' : u.status === 'disabled' ? 'danger' : 'neutral'" class="capitalize">{{ u.status }}</DwBadge>
|
||||
<DwBadge
|
||||
:tone="u.status === 'active' ? 'success' : u.status === 'disabled' ? 'danger' : 'neutral'"
|
||||
class="capitalize"
|
||||
>{{ u.status }}</DwBadge
|
||||
>
|
||||
</td>
|
||||
<td class="px-4 py-2 text-right whitespace-nowrap">
|
||||
<template v-if="canEdit(u)">
|
||||
<DwButton variant="ghost" size="sm" @click="startEdit(u)">Edit</DwButton>
|
||||
<DwButton v-if="u.id !== currentUser?.id" variant="ghost" size="sm" class="!text-danger" :disabled="busy" @click="remove(u)">
|
||||
<DwButton
|
||||
v-if="u.id !== currentUser?.id"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="!text-danger"
|
||||
:disabled="busy"
|
||||
@click="remove(u)"
|
||||
>
|
||||
Delete
|
||||
</DwButton>
|
||||
</template>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import vue from "@vitejs/plugin-vue";
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
+27
-3
@@ -3,7 +3,31 @@ module docwell/server
|
||||
go 1.26
|
||||
|
||||
require (
|
||||
github.com/coder/websocket v1.8.15 // indirect
|
||||
github.com/tetratelabs/wazero v1.12.0 // indirect
|
||||
golang.org/x/sys v0.44.0 // indirect
|
||||
github.com/coder/websocket v1.8.15
|
||||
github.com/oapi-codegen/runtime v1.8.0
|
||||
github.com/tetratelabs/wazero v1.12.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect
|
||||
github.com/getkin/kin-openapi v0.142.0 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.23.1 // indirect
|
||||
github.com/go-openapi/swag/jsonname v0.26.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/oapi-codegen/oapi-codegen/v2 v2.8.1 // indirect
|
||||
github.com/oasdiff/yaml v0.1.1 // indirect
|
||||
github.com/oasdiff/yaml3 v0.0.14 // indirect
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect
|
||||
github.com/speakeasy-api/jsonpath v0.6.3 // indirect
|
||||
github.com/speakeasy-api/openapi v1.24.0 // indirect
|
||||
github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/mod v0.38.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
golang.org/x/tools v0.48.0 // indirect
|
||||
)
|
||||
|
||||
tool github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen
|
||||
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user