Initial public release

This commit is contained in:
GenOffice
2026-08-02 19:52:16 +08:00
commit d2fe8ddaae
994 changed files with 348937 additions and 0 deletions
+44
View File
@@ -0,0 +1,44 @@
name: Bug report
description: Something is broken or behaves unexpectedly
labels: [bug]
body:
- type: dropdown
id: app
attributes:
label: App
description: Which part of the suite is affected?
options:
- GenOffice Docs (docs)
- GenOffice Sheets (sheets)
- GenOffice Slides (slides)
- GenOffice PDF (pdf)
- Shell / home screen
- AI panel / providers
- Build / packaging
- Other
validations:
required: true
- type: input
id: version
attributes:
label: Version and OS
description: App version (or commit) and operating system
placeholder: '0.1.0 on macOS 15.3 / Windows 11'
validations:
required: true
- type: textarea
id: what-happened
attributes:
label: What happened?
description: >
What did you do, what did you expect, and what happened instead?
If a document triggers the bug, attach a minimal sample file if
possible (please remove anything confidential first).
placeholder: Steps to reproduce, expected behavior, actual behavior.
validations:
required: true
- type: textarea
id: logs
attributes:
label: Logs / screenshots
description: Console output, stack traces, or screenshots, if any.
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: true
contact_links:
- name: Security vulnerability
url: https://github.com/genspark-ai/genoffice/security/advisories/new
about: Please report security issues privately, never as a public issue.
@@ -0,0 +1,30 @@
name: Feature request
description: Suggest a new capability or an improvement
labels: [enhancement]
body:
- type: dropdown
id: app
attributes:
label: App
options:
- GenOffice Docs (docs)
- GenOffice Sheets (sheets)
- GenOffice Slides (slides)
- GenOffice PDF (pdf)
- Shell / home screen
- AI panel / providers
- Whole suite
validations:
required: true
- type: textarea
id: problem
attributes:
label: Problem
description: What are you trying to do that is currently hard or impossible?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed solution
description: How would you like it to work? Alternatives you considered are welcome too.
+27
View File
@@ -0,0 +1,27 @@
## Summary
- What changed?
- Why is this change needed?
## Related issue
Closes #
## Validation
- [ ] `npm run format:check`
- [ ] `npm run lint`
- [ ] `npm run typecheck`
- [ ] `npm test`
List any checks not run and explain why:
## Screenshots or recordings
Include before/after evidence for visible changes, or write "Not applicable."
## Contributor checklist
- [ ] The change is focused and does not include unrelated reformatting or refactoring.
- [ ] User-facing strings use the existing i18n resources.
- [ ] File open/save changes include an appropriate round-trip or fidelity test.
+86
View File
@@ -0,0 +1,86 @@
name: CI
# Test gate for every PR and push: changed-file formatting, lint, typecheck across
# all workspaces, and the full unit-test suite (engine packages and app tests; the
# sheets suite also runs the Rust xlsx-sidecar tests). Packaging/signing is handled
# by separate release automation — this workflow never builds installers.
on:
push:
branches: [main, 'dev_*', 'release_*']
pull_request:
branches: [main]
workflow_dispatch:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
cache-dependency-path: package-lock.json
- name: Setup Rust
# SHA-pinned (third-party action); the ref no longer selects the
# toolchain, so it is passed explicitly.
uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable branch, 2026-07
with:
toolchain: stable
- name: Cache cargo (xlsx-sidecar)
uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1
with:
workspaces: apps/sheets/native/xlsx-engine
- name: Install dependencies
run: npm ci
- name: Check dependency licenses
run: npm run licenses
- name: Check Rust dependency licenses (xlsx-sidecar)
uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1
with:
command: check licenses
manifest-path: apps/sheets/native/xlsx-engine/Cargo.toml
- name: Check formatting
env:
FORMAT_BASE_REF: ${{ github.event.pull_request.base.sha || github.event.before }}
# For PRs the checkout is the PR merge commit, so its first parent is the
# exact main revision the merge was built against. The event's base.sha can
# lag behind a fast-moving main, which pulls unrelated main-side files into
# the changed-file set and fails the check on files the PR never touched.
run: |
if [ "${{ github.event_name }}" = "pull_request" ]; then
FORMAT_BASE_REF=$(git rev-parse HEAD^1)
fi
npm run format:check
- name: Lint
run: npm run lint
- name: Typecheck
run: npm run typecheck
- name: Regenerate test fixtures
run: npm run fixtures
- name: Test
run: npm test
+32
View File
@@ -0,0 +1,32 @@
node_modules
out/
dist/
release/
*.log
.DS_Store
.refs/
.env
.env.*
electron-builder.env
~$*
# Local ad-hoc e2e driver scripts (not pushed); the folder and README are tracked, the scripts are not
/scripts/drivers/driver.*.mjs
/probe*.mjs
/apps/shell/build/THIRD-PARTY-NOTICES.txt
/example/
/.task/
/docs-archive/
.idea/
.claude/
# Local build artifacts dropped in the repo root
/*.dmg
/*.exe
/*.zip
/windows/
.cursor/rules/git-remote.mdc
__pycache__/
/notes/
/MEMORY.md
+1
View File
@@ -0,0 +1 @@
20
+15
View File
@@ -0,0 +1,15 @@
node_modules/
dist/
out/
release/
.build/
target/
coverage/
# Generated artifacts and dependency-managed metadata.
package-lock.json
apps/*/build/
apps/shell/build/THIRD-PARTY-NOTICES.txt
# Local-only acceptance drivers are intentionally outside CI.
scripts/drivers/driver.*.mjs
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/prettierrc",
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"endOfLine": "lf"
}
+74
View File
@@ -0,0 +1,74 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of 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, color, religion, or sexual
identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall
community
Examples of unacceptable behavior include:
- The use of 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 others' private information, such as a physical or email address,
without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for
moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement through the
repository's security advisory channel or the contact listed in
[SECURITY.md](SECURITY.md). All complaints will be reviewed and investigated
promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
+145
View File
@@ -0,0 +1,145 @@
# Contributing to GenOffice
Thanks for your interest in contributing. This document covers the local
setup, the checks a change must pass, and the conventions used in this
repository.
## Repository layout
- `apps/*` — the five Electron apps (docs, sheets, slides, pdf, shell).
Each app is an npm workspace with its own `src/main` (Electron main
process), `src/renderer` (React UI), and `tests/`.
- `packages/*` — pure TypeScript engine and shared packages (no Electron
dependency, unit-tested): docx/pptx engines, AI agent core, providers,
i18n, UI kit.
- `apps/sheets/native/xlsx-engine` — Rust xlsx engine (runs as a sidecar process) for xlsx import/export.
## Getting started
Prerequisites: Node 20+, npm 10+, and a Rust toolchain (`cargo` on PATH,
needed only for the sheets xlsx sidecar).
```bash
npm install
npm run fixtures # generate test .docx fixtures (one-time, and after docx-engine changes)
npm run dev # all editors + shell against Vite dev servers
npm run dev:docs # or run a single app
```
## Checks every change must pass
CI runs these on every PR; please run them locally first:
```bash
npm run format:check # Prettier check for uncommitted changed/new files
npm run lint # ESLint across the repo (0 errors required; warnings allowed)
npm run typecheck # tsc --noEmit across every workspace
npm test # engine + app unit tests (also runs the Rust sidecar tests)
npm run licenses # production dependency licenses within the permissive allowlist
```
Formatting is intentionally incremental: existing files are not reformatted
unless they are part of your change. Run these exact commands before committing:
```bash
npm run format # format uncommitted changed/new files
npm run format:check # verify uncommitted changed/new files
npm run format:check -- --base origin/main # verify committed files on your branch
```
CI supplies the PR or push base automatically and checks only files changed from
that base. This keeps the formatter gate useful without creating a repository-wide
formatting diff.
## Building installers
```bash
npm run dist:mac -w @genoffice/shell # dmg + zip
npm run dist:win -w @genoffice/shell # nsis installer
```
Without Apple or Windows signing credentials in the environment these produce
unsigned artifacts: code signing and notarization are skipped with a warning
rather than failing. That is the expected result for a contributor build.
`dist:win` additionally expects the xlsx sidecar at the MinGW cross-compilation
path. Building on Windows leaves it under the MSVC target instead, so stage it
first:
```bash
cargo build --release --target x86_64-pc-windows-gnu # from apps/sheets/native/xlsx-engine
```
or copy an existing `target/release/xlsx-sidecar.exe` to
`target/x86_64-pc-windows-gnu/release/`.
## Environment variables
None are required — the apps run with all of these unset. They exist for
testing and local overrides:
| Variable | Effect |
| -------------------------------------------------------- | ---------------------------------------------------------------------- |
| `GENOFFICE_USER_DATA` | Override the Electron userData directory (test isolation) |
| `GENOFFICE_LANG` | Force the UI language instead of following the OS locale |
| `GENOFFICE_FAKE_UPDATE` | Exercise the updater UI without a real release feed |
| `GENOFFICE_CLOUD_SLIDE`, `GENOFFICE_CLOUD_SLIDE_TIER` | Route slide generation through the cloud endpoint |
| `GSK_API_KEY`, `GSK_CLI_PATH` | Genspark credentials / CLI location for the built-in AI provider |
| `AI_SEARCH_DISABLE_GSK`, `SERPER_API_KEY` | Disable the gsk search backend / supply a Serper key instead |
| `XLSX_SIDECAR_PATH`, `XLSX_OPEN_PATH`, `XLSX_DEBUG_PORT` | Point at a locally built xlsx sidecar and its debug port |
| `*_DEV_PORT`, `*_RENDERER_URL` | Per-app Vite dev server ports and renderer URLs (set by `npm run dev`) |
AI features degrade rather than break without credentials: requests surface an
inline sign-in prompt, and web search falls back to a keyless backend.
## Coding conventions
- **English only** in code, comments, commit messages, and docs. User-facing
strings go through the i18n resources (`src/renderer/i18n/`, plus the inline
main-process dictionaries in `src/main/`), which are the only places
non-English text belongs (plus test fixture text).
- TypeScript everywhere; avoid adding new `any` surfaces where a precise type
is cheap.
- Tests live in `apps/*/tests` and `packages/*/tests` (vitest). New engine
behavior needs a unit test; renderer-only UI tweaks generally don't.
- Local Playwright/Electron acceptance drivers belong in `scripts/drivers/`
(gitignored, excluded from CI) — see `scripts/drivers/README.md`.
- The Word-fidelity scripts (`scripts/docs-word-fidelity.mjs`,
`scripts/pagination-baseline-word.mjs`) need macOS with Microsoft Word
installed and AppleScript automation permission granted; they are optional
local tools and never run in CI.
- Keep files from growing without bound: if you are adding a substantial new
concern to an already-large file, prefer a new module.
## Commit and PR guidelines
- Small, focused commits with imperative English subject lines
(e.g. `fix docx table border round-trip`, `add slides chart legend parsing`).
- A PR should explain _why_ the change is needed, and mention which of the
checks above you ran.
- File format fidelity is the core product promise: for changes touching
open/save paths (docx/xlsx/pptx), include a round-trip test proving
untouched content survives byte-for-byte.
## Reporting bugs and requesting features
Use the issue templates. For suspected security issues, do **not** open a
public issue — follow [SECURITY.md](SECURITY.md).
## Code of conduct
All community spaces follow the
[Contributor Covenant](CODE_OF_CONDUCT.md); participation implies acceptance.
## License and CLA
There is no CLA (contributor license agreement), and we do not plan to add
one. By contributing, you agree that your contributions are licensed under
the [Apache License 2.0](LICENSE) that covers this project — inbound =
outbound, per Apache-2.0 §5. Because community contributions keep their
Apache-2.0 terms, the open-source core cannot be retroactively relicensed.
The `ee/` directory is reserved for future enterprise modules under a
[separate license](ee/LICENSE) and does not accept external contributions —
pull requests from outside the maintainer team must not modify files under
`ee/` (enforced via [CODEOWNERS](.github/CODEOWNERS)).
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Mainfunc, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+14
View File
@@ -0,0 +1,14 @@
GenOffice
Copyright 2026 Mainfunc, Inc.
This product includes software developed at Mainfunc, Inc.
Bundled third-party components are listed in THIRD-PARTY-NOTICES.txt, which
tools/gen-third-party-notices.mjs generates at packaging time. It is not
checked into this repository; in a release build it ships inside the
application bundle (Contents/Resources on macOS, resources/ on Windows).
Run `node tools/gen-third-party-notices.mjs` to produce it from a source
checkout.
Bundled fonts and their licenses are documented in
apps/docs/src/renderer/fonts/README.md.
+99
View File
@@ -0,0 +1,99 @@
# GenOffice
An AI-native office suite for macOS and Windows: word processor, spreadsheet,
presentations, and PDF — five Electron apps sharing one engine layer, built
around AI editing as a first-class workflow rather than a bolted-on chat box.
## Apps
| App | Product | What it is |
| ------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apps/docs` | **GenOffice Docs** | `.docx` word processor. Byte-preserving round trip: only dirty paragraphs are regenerated (paragraph patch), everything else in the original file is kept byte-for-byte, so opening and saving never breaks layout in Word. Paginated view whose line metrics reproduce the original document's layout, tracked changes, comments, styles, equations, ink. |
| `apps/sheets` | **GenOffice Sheets** | `.xlsx` spreadsheet. UI built on the open-source [Univer](https://github.com/dream-num/univer) core (Apache-2.0) with a large layer of in-house extensions; xlsx import/export runs through an in-house Rust sidecar (calamine + IronCalc), charts are rendered in-house (Konva), plus pivot tables, slicers, conditional formatting, and formula tracing. |
| `apps/slides` | **GenOffice Slides** | `.pptx` presentations. In-house pptx parse/render/edit engine with masters, charts, cropping, ink, and text shaping (HarfBuzz metrics). |
| `apps/pdf` | **GenOffice PDF** | PDF viewer/editor on pdf.js + pdf-lib: annotations, forms, outlines, stamps, signatures, page operations, print. |
| `apps/shell` | **GenOffice** | The suite shell: home screen, tabbed hosting of the four editors, auto-update. |
Every app embeds the same AI panel: block-granular AI editing with version
snapshots and diffs in docs, a tool-calling agent over workbook/slide/PDF
state in the others.
**AI providers.** The apps sign in to a Genspark account and route model
calls through the Genspark service side; no model API key is stored locally.
## Engine packages
All pure TypeScript, unit-tested, no Electron dependency:
- `packages/docx-engine` — docx parsing → block tree (with `docxIndex` anchors
- passthrough), OOXML fragment generation, byte-level paragraph patching.
- `packages/pptx-engine` / `packages/pptx-render` — pptx model and rendering.
- `packages/file-parse` — text extraction for AI attachments (office formats,
text formats).
- `packages/agent-core` — the AI agent loop and skill composition shared by
every app.
- `packages/ai-provider` — provider abstraction and streaming for the model
backends.
- `packages/ai-search` — Genspark auth + web/image search tools.
- `packages/i18n`, `packages/ui`, `packages/project-store`,
`packages/electron-utils` — shared i18n core, React UI kit, recent-files
store, and Electron main-process helpers.
## Development
```bash
npm install
npm run fixtures # generate test .docx fixtures
npm test # engine + app unit tests (docs/sheets/slides need no display)
npm run typecheck # tsc --noEmit across every workspace
npm run dev # all four editors + shell against Vite dev servers
npm run dev:docs # a single app (same pattern works per workspace)
npm run dist:mac # package macOS dmg (regenerates third-party notices)
npm run dist:win # package Windows nsis installer
```
The sheets app additionally needs a Rust toolchain for its xlsx sidecar
(`cargo` on PATH); `npm run build -w @genoffice/sheets` compiles it
automatically.
Local UI/e2e driver scripts (Playwright + Electron, for local acceptance, not
committed by default) live in [`scripts/drivers/`](scripts/drivers/README.md).
## Architecture notes (docx round trip)
```
open docx ─► archive original by hash (never touched)
─► docx-engine parses word/document.xml top-level elements (w:p / w:tbl / …)
─► Block tree, each block anchored by docxIndex + original XML slice
─► TipTap streaming editor (manual + AI editing, dirty tracking)
save ─► dirty blocks → OOXML fragments (referencing existing styles only)
─► splice into original document.xml (untouched blocks keep original bytes)
─► repack zip; all other entries copied byte-for-byte
```
The same philosophy holds in sheets and slides: the original file is the
source of truth, edits are applied as narrow patches, and everything the
editor didn't touch survives the round trip untouched.
## Security
See [SECURITY.md](SECURITY.md) for the process security posture (renderer
sandboxing, IPC validation, external-link gating) and the threat models for
AI-generated content.
## Third-party notices
`npm run notices` regenerates the bundled third-party license summary
(`tools/gen-third-party-notices.mjs`); all runtime dependencies are
MIT/Apache-2.0/OFL, and the bundled fonts (Liberation, Carlito, Caladea, Noto
CJK subsets) are OFL/Apache.
## License
GenOffice is licensed under the [Apache License 2.0](LICENSE), with one
exception: the `ee/` directory is reserved for future enterprise modules and
is covered by the [GenOffice Enterprise License](ee/LICENSE).
The GenOffice and Genspark names and logos are trademarks of Mainfunc, Inc.
The Apache-2.0 license does not grant permission to use them (see section 6);
forks should use their own branding.
+85
View File
@@ -0,0 +1,85 @@
# Security Policy
## Reporting a Vulnerability
Please report suspected vulnerabilities privately via GitHub's
[private vulnerability reporting](../../security/advisories/new) on this
repository. Do not open public issues for security reports. We aim to
acknowledge reports within 72 hours.
## Process Security Posture
All application windows run with the full Electron renderer lockdown:
- `contextIsolation: true`, `nodeIntegration: false`, `sandbox: true` for every
document window and tab view (docs, sheets, slides, pdf, shell, updater).
- Renderers reach the main process only through typed, validated IPC channels
(payloads are schema-checked in the main process; sheets uses zod end to end).
- Every `shell.openExternal` call goes through a single shared gate
(`@genoffice/electron-utils` → `safeExternalUrl`) that parses the URL and
enforces a protocol allowlist (http/https; pdf link annotations additionally
allow mailto). `file:`, `javascript:`, and custom schemes are always rejected.
- No API keys are hardcoded. AI requests are proxied through the signed-in
account by default; user-supplied keys stay in the OS-level settings store.
## Threat Model: AI-Generated Layout Scripts (slides)
The slides AI can adjust slide layouts by emitting a small script that is
parsed with Acorn and evaluated by a constrained AST interpreter
(`apps/slides/src/renderer/ai/layout-script-interpreter.ts`). The source looks
like a small, synchronous subset of JavaScript for model compatibility, but it
is not passed to `eval`, `Function`, a VM context, a worker, or the JavaScript
engine as executable source.
**What the script can do by design:** read prototype-free JSON copies of
`els`/`canvas`, perform bounded arithmetic/control flow, use explicitly
implemented string/array/regular-expression/Math helpers, and call
`setBox/moveBy/resizeBy/setText/setStyle/setFill/setStroke/log`. Every edit
primitive validates its arguments (element existence, read-only flags, finite
numbers, hex colors) and writes only into an op buffer that is applied through
the same command pipeline as manual edits.
**Interpreter boundary:**
1. Identifiers resolve only in interpreter-owned lexical scopes seeded with the
documented data and callables. There are no ambient globals, module loader,
DOM, network, IPC bridge, timers, process APIs, or dynamic code primitives.
2. Property reads are dispatched by value type. Data objects expose own JSON
fields only; arrays, strings, and regexes expose a small method allowlist.
Host prototypes and function properties are never traversed, including
through computed property names.
3. Calls accept only interpreter-created functions or explicit builtins. A host
function obtained through a constructor/prototype chain cannot be
represented.
4. Inputs and values crossing into edit primitives are recursively copied as
JSON-like, prototype-free data. Errors discard all buffered operations;
logs are capped.
5. Execution has statement/expression and call-depth limits to bound runaway
loops or recursion.
The Electron renderer sandbox remains defense in depth, but it is not the
layout-script security boundary. The interpreter is designed so a layout
script cannot obtain renderer capabilities in the first place.
If you find a way for a layout script to reach anything beyond the injected
primitives (network, storage, IPC channels not reachable by design, or the
main process), that is a vulnerability — please report it.
## Threat Model: Rendering AI-Generated HTML (slides export)
The HTML-to-pptx export pipeline renders AI-generated HTML in a hidden
`BrowserWindow`. That window is treated as hostile content: full renderer
lockdown (`sandbox: true`, `contextIsolation: true`, `nodeIntegration: false`),
no preload script, no IPC surface — the main process drives it exclusively
through `executeJavaScript` and destroys it under a watchdog timeout.
## Out of Scope
- The cloud AI services this client talks to are operated separately and are
not part of this repository; issues with them should be reported through the
service provider's channels.
- Vulnerabilities that require an already-compromised machine or a modified
binary. This includes the deliberate environment-variable override points
for local development (`GSK_CLI_PATH`, `XLSX_SIDECAR_PATH`): setting them
requires control of the process environment, which is equivalent to code
execution on the machine.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

+22
View File
@@ -0,0 +1,22 @@
import react from '@vitejs/plugin-react'
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
export default defineConfig({
// Main and preload use only electron + node builtins; bundle everything so
// the packaged app doesn't rely on node_modules at runtime.
// @genoffice/* deps ship as raw TS source with extensionless imports, so they
// must be bundled — externalizing them yields ERR_MODULE_NOT_FOUND under Node
// (same setup as apps/slides).
main: {
plugins: [externalizeDepsPlugin({ exclude: ['@genoffice/electron-utils'] })],
},
preload: {},
renderer: {
plugins: [react()],
server: {
// Overridable so multiple genoffice dev instances can coexist (default 5173).
port: Number(process.env.DOCS_DEV_PORT) || 5173,
strictPort: Boolean(process.env.DOCS_DEV_PORT),
},
},
})
+96
View File
@@ -0,0 +1,96 @@
{
"name": "@genoffice/docs",
"productName": "GenOffice Docs",
"version": "0.1.0",
"license": "Apache-2.0",
"private": true,
"description": "AI-native streaming docx editor with paragraph-patch save",
"main": "out/main/index.js",
"scripts": {
"dev": "electron-vite dev",
"dev:renderer": "vite --config vite.renderer.config.ts",
"build": "electron-vite build",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"dist:mac": "electron-vite build && electron-builder --mac",
"dist:win": "electron-vite build && electron-builder --win",
"dist:dir": "electron-vite build && electron-builder --dir"
},
"devDependencies": {
"@genoffice/agent-core": "*",
"@genoffice/i18n": "*",
"@genoffice/ai-provider": "*",
"@genoffice/ai-search": "*",
"@genoffice/docx-engine": "*",
"@genoffice/file-parse": "*",
"@genoffice/project-store": "*",
"@genoffice/ui": "*",
"@tiptap/core": "^3.28.0",
"@tiptap/extensions": "^3.28.0",
"@tiptap/pm": "^3.28.0",
"@tiptap/react": "^3.28.0",
"@types/opentype.js": "^1.3.8",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.0.4",
"electron": "^41.0.3",
"electron-builder": "^26.0.12",
"electron-vite": "^5.0.0",
"jsdom": "^28.0.0",
"opentype.js": "^2.0.0",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"typescript": "^5.9.3",
"vite": "^7.3.1",
"vitest": "^4.1.0"
},
"author": "GenOffice",
"build": {
"appId": "com.genoffice.docs",
"productName": "GenOffice Docs",
"electronVersion": "41.7.1",
"artifactName": "AIDocx-${version}-${arch}.${ext}",
"directories": {
"output": "release"
},
"files": [
"out/**"
],
"fileAssociations": [
{
"ext": "docx",
"name": "Word Document",
"role": "Editor"
}
],
"npmRebuild": false,
"mac": {
"target": [
"dmg",
"zip"
],
"category": "public.app-category.productivity",
"identity": null
},
"win": {
"target": [
{
"target": "nsis",
"arch": [
"x64"
]
}
]
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true
}
},
"dependencies": {
"@genoffice/electron-utils": "*",
"electron-updater": "^6.8.9",
"pdf-lib": "^1.17.1"
}
}
+791
View File
@@ -0,0 +1,791 @@
/**
* Pagination corpus generation script
* Run: tsx apps/docs/scripts/generate-corpus.ts
* Output: apps/docs/tests/pagination-corpus/docx/*.docx
* apps/docs/tests/pagination-corpus/meta/*.json
*/
import { mkdirSync, writeFileSync, copyFileSync, existsSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import JSZip from 'jszip'
const __dirname = dirname(fileURLToPath(import.meta.url))
const REPO_ROOT = join(__dirname, '../../..')
const DOCX_OUT = join(__dirname, '../tests/pagination-corpus/docx')
const META_OUT = join(__dirname, '../tests/pagination-corpus/meta')
mkdirSync(DOCX_OUT, { recursive: true })
mkdirSync(META_OUT, { recursive: true })
const XML_DECL = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
const DOC_NS =
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' +
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ' +
'xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ' +
'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
'xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"'
const STYLES_XML =
XML_DECL +
'<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:docDefaults><w:rPrDefault><w:rPr>' +
'<w:rFonts w:ascii="Calibri" w:eastAsia="宋体" w:hAnsi="Calibri"/>' +
'<w:sz w:val="24"/><w:szCs w:val="24"/>' +
'</w:rPr></w:rPrDefault>' +
'<w:pPrDefault><w:pPr>' +
'<w:spacing w:after="160" w:line="276" w:lineRule="auto"/>' +
'</w:pPr></w:pPrDefault></w:docDefaults>' +
'<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>' +
'<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/>' +
'<w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/>' +
'<w:pPr><w:keepNext/><w:spacing w:before="240" w:after="120"/><w:outlineLvl w:val="0"/></w:pPr>' +
'<w:rPr><w:b/><w:sz w:val="32"/><w:szCs w:val="32"/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/>' +
'<w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/>' +
'<w:pPr><w:keepNext/><w:spacing w:before="200" w:after="120"/><w:outlineLvl w:val="1"/></w:pPr>' +
'<w:rPr><w:b/><w:sz w:val="28"/><w:szCs w:val="28"/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="Heading3"><w:name w:val="heading 3"/>' +
'<w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/>' +
'<w:pPr><w:keepNext/><w:spacing w:before="160" w:after="120"/><w:outlineLvl w:val="2"/></w:pPr>' +
'<w:rPr><w:b/><w:sz w:val="26"/><w:szCs w:val="26"/></w:rPr></w:style>' +
'<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/>' +
'<w:basedOn w:val="Normal"/><w:pPr><w:ind w:left="720"/></w:pPr></w:style>' +
'</w:styles>'
// A4 page + standard margins + docGrid (Chinese document grid)
const A4_SECT_PR =
'<w:sectPr>' +
'<w:pgSz w:w="11906" w:h="16838"/>' +
'<w:pgMar w:top="1440" w:right="1800" w:bottom="1440" w:left="1800" w:header="708" w:footer="708" w:gutter="0"/>' +
'</w:sectPr>'
// A4 + docGrid (standard Chinese document grid: line=360, type=lines)
const A4_SECT_WITH_DOCGRID =
'<w:sectPr>' +
'<w:pgSz w:w="11906" w:h="16838"/>' +
'<w:pgMar w:top="1440" w:right="1800" w:bottom="1440" w:left="1800" w:header="708" w:footer="708" w:gutter="0"/>' +
'<w:docGrid w:type="lines" w:linePitch="312"/>' +
'</w:sectPr>'
// US Letter landscape
const LETTER_LANDSCAPE_SECT_PR =
'<w:sectPr>' +
'<w:pgSz w:w="15840" w:h="12240" w:orient="landscape"/>' +
'<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>' +
'</w:sectPr>'
interface DocSpec {
name: string
bodyXml: string
sectPr?: string
extraStylesXml?: string
footnotesXml?: string
meta: {
title: string
tags: string[]
description: string
}
}
async function buildDocx(spec: DocSpec): Promise<Uint8Array> {
const zip = new JSZip()
const sectPr = spec.sectPr ?? A4_SECT_PR
const extraStyles = spec.extraStylesXml ?? ''
const hasFootnotes = !!spec.footnotesXml
const stylesXml = extraStyles
? STYLES_XML.replace('</w:styles>', extraStyles + '</w:styles>')
: STYLES_XML
const contentTypeOverrides = [
'<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>',
'<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>',
hasFootnotes
? '<Override PartName="/word/footnotes.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml"/>'
: '',
].join('')
zip.file(
'[Content_Types].xml',
`${XML_DECL}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
'<Default Extension="xml" ContentType="application/xml"/>' +
contentTypeOverrides +
'</Types>',
)
zip.file(
'_rels/.rels',
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>' +
'</Relationships>',
)
const docRels = [
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>',
hasFootnotes
? '<Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes" Target="footnotes.xml"/>'
: '',
].join('')
zip.file(
'word/_rels/document.xml.rels',
`${XML_DECL}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${docRels}</Relationships>`,
)
zip.file('word/styles.xml', stylesXml)
if (hasFootnotes) zip.file('word/footnotes.xml', spec.footnotesXml!)
zip.file(
'word/document.xml',
`${XML_DECL}<w:document ${DOC_NS}><w:body>${spec.bodyXml}${sectPr}</w:body></w:document>`,
)
return zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE' })
}
// ---- Paragraph helpers ----
const p = (text: string, style?: string, extra?: string): string => {
const pStyle = style ? `<w:pStyle w:val="${style}"/>` : ''
const pPr = pStyle || extra ? `<w:pPr>${pStyle}${extra ?? ''}</w:pPr>` : ''
return `<w:p>${pPr}<w:r><w:t xml:space="preserve">${escXml(text)}</w:t></w:r></w:p>`
}
const pBreak = (): string => '<w:p><w:r><w:br w:type="page"/></w:r></w:p>'
const escXml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
// build a paragraph from repeated text
function loremParagraph(n: number, lang: 'en' | 'zh'): string {
if (lang === 'en') {
const words =
'Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat'.split(
' ',
)
let text = ''
for (let i = 0; i < n; i++) text += words[i % words.length] + ' '
return p(text.trim())
} else {
const chars =
'在中国经济社会发展的重要历史时期,人工智能技术的广泛应用正在深刻改变各行各业的生产方式和商业模式。数字化转型已成为企业保持竞争力的关键战略,各类组织机构纷纷加快推进信息化建设步伐。'
let text = ''
for (let i = 0; i < n; i++) text += chars[i % chars.length]
return p(text)
}
}
// generate table rows
function tableRows(rows: number, cols: number, withHeader = false): string {
let xml = ''
const colWidth = Math.floor(8000 / cols)
for (let r = 0; r < rows; r++) {
const isHeader = withHeader && r === 0
xml += '<w:tr>'
for (let c = 0; c < cols; c++) {
const fill = isHeader ? '<w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/>' : ''
const cellText = isHeader ? `列${c + 1}标题` : `第${r + 1}行第${c + 1}列`
xml +=
`<w:tc><w:tcPr><w:tcW w:w="${colWidth}" w:type="dxa"/>${fill}</w:tcPr>` +
`<w:p>${isHeader ? '<w:pPr/>' : ''}<w:r>${isHeader ? '<w:rPr><w:b/></w:rPr>' : ''}<w:t>${escXml(cellText)}</w:t></w:r></w:p></w:tc>`
}
xml += '</w:tr>'
}
return xml
}
function table(rows: number, cols: number, withHeader = false): string {
const colWidth = Math.floor(8000 / cols)
const border = (n: string) => `<w:${n} w:val="single" w:sz="4" w:space="0" w:color="auto"/>`
const borders =
'<w:tblBorders>' +
['top', 'left', 'bottom', 'right', 'insideH', 'insideV'].map(border).join('') +
'</w:tblBorders>'
const gridCols = Array.from({ length: cols }, () => `<w:gridCol w:w="${colWidth}"/>`).join('')
return (
`<w:tbl><w:tblPr><w:tblW w:w="8000" w:type="dxa"/>${borders}</w:tblPr>` +
`<w:tblGrid>${gridCols}</w:tblGrid>` +
tableRows(rows, cols, withHeader) +
'</w:tbl>'
)
}
// ---- Corpus specs ----
const specs: DocSpec[] = []
// 01. Simple English document (2 pages)
{
let body = p('Simple English Document', 'Heading1')
for (let i = 0; i < 40; i++) body += loremParagraph(30, 'en')
specs.push({
name: '01-simple-english',
bodyXml: body,
meta: {
title: 'Simple English Document',
tags: ['english', 'multi-page', 'simple'],
description: 'Pure English long text, ~2 pages, no special formatting',
},
})
}
// 02. Long pure-Chinese document (with docGrid)
{
let body = p('中文长篇文档测试', 'Heading1')
for (let i = 0; i < 50; i++) body += loremParagraph(50, 'zh')
specs.push({
name: '02-chinese-long-docgrid',
bodyXml: body,
sectPr: A4_SECT_WITH_DOCGRID,
meta: {
title: 'Long Chinese text (docGrid)',
tags: ['chinese', 'docGrid', 'multi-page'],
description:
'Pure Chinese with a w:docGrid lines grid, typical Chinese official-document format',
},
})
}
// 03. Mixed Chinese-English
{
let body = p('中英文混排文档', 'Heading1')
for (let i = 0; i < 20; i++) {
body += loremParagraph(20, 'zh')
body += loremParagraph(20, 'en')
}
specs.push({
name: '03-mixed-lang',
bodyXml: body,
meta: {
title: 'Mixed Chinese-English',
tags: ['mixed-language', 'multi-page'],
description: 'Alternating Chinese/English paragraphs, tests mixed-language pagination',
},
})
}
// 04. Multilevel headings (keepNext styles)
{
let body = ''
for (let h = 1; h <= 5; h++) {
body += p(`第${h}章 标题层级测试`, 'Heading1')
body += p(`第${h}.1节`, 'Heading2')
for (let i = 0; i < 8; i++) body += loremParagraph(30, 'zh')
body += p(`第${h}.2节`, 'Heading2')
body += p(`第${h}.2.1小节`, 'Heading3')
for (let i = 0; i < 6; i++) body += loremParagraph(30, 'zh')
}
specs.push({
name: '04-headings-keepnext',
bodyXml: body,
sectPr: A4_SECT_WITH_DOCGRID,
meta: {
title: 'Multilevel headings document',
tags: ['headings', 'keepNext', 'multi-section', 'docGrid'],
description:
'5 chapters of multilevel headings (with keepNext styles), tests heading page-break behavior',
},
})
}
// 05. Long table across pages
{
let body = p('长表格跨页测试', 'Heading1')
body += p('以下表格含 30 行,跨多页:')
body += table(30, 4, true)
body += p('表格后续正文段落。')
specs.push({
name: '05-long-table',
bodyXml: body,
meta: {
title: 'Long table across pages',
tags: ['table', 'cross-page', 'table-header'],
description: '30-row 4-column table, tests table splitting across pages',
},
})
}
// 06. With footnotes (full footnotes.xml structure)
{
// footnote documents need footnotes.xml + a Content-Type override + rels
// built directly with the customBuildDocxWithFootnotes function
const FOOTNOTE_COUNT = 20
let body = p('含脚注文档测试', 'Heading1')
for (let i = 1; i <= FOOTNOTE_COUNT; i++) {
body +=
`<w:p><w:r><w:t xml:space="preserve">第${i}段正文,包含参考引用。</w:t></w:r>` +
`<w:r><w:rPr><w:vertAlign w:val="superscript"/></w:rPr><w:footnoteReference w:id="${i}"/></w:r></w:p>`
}
for (let i = 0; i < 20; i++) body += loremParagraph(20, 'zh')
// generate footnotes.xml (with the separator + each footnote)
const FOOTNOTES_NS = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'
let footnotesXml = `${XML_DECL}<w:footnotes ${FOOTNOTES_NS}>`
// two built-in system footnotes: separator and continuationSeparator
footnotesXml +=
'<w:footnote w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:footnote>'
footnotesXml +=
'<w:footnote w:type="continuationSeparator" w:id="0"><w:p><w:r><w:continuationSeparator/></w:r></w:p></w:footnote>'
for (let i = 1; i <= FOOTNOTE_COUNT; i++) {
footnotesXml +=
`<w:footnote w:id="${i}"><w:p>` +
`<w:r><w:rPr><w:vertAlign w:val="superscript"/></w:rPr><w:t>${i}</w:t></w:r>` +
`<w:r><w:t xml:space="preserve"> 这是第${i}条脚注内容,详见参考文献。</w:t></w:r>` +
`</w:p></w:footnote>`
}
footnotesXml += '</w:footnotes>'
specs.push({
name: '06-with-footnotes',
bodyXml: body,
footnotesXml,
meta: {
title: 'Document with footnotes',
tags: ['footnotes', 'multi-page'],
description: "20 footnote references, tests footnote placeholders' impact on pagination",
},
})
}
// 07. With page breaks
{
let body = p('分页符测试文档', 'Heading1')
body += p('第一页内容')
for (let i = 0; i < 5; i++) body += loremParagraph(20, 'zh')
body += pBreak()
body += p('第二页(强制分页符后)')
for (let i = 0; i < 5; i++) body += loremParagraph(20, 'zh')
body += pBreak()
body += p('第三页')
for (let i = 0; i < 8; i++) body += loremParagraph(20, 'zh')
specs.push({
name: '07-page-breaks',
bodyXml: body,
meta: {
title: 'Manual page breaks',
tags: ['page-break', 'forced-break'],
description: 'Two manual page breaks, tests breakAfter logic',
},
})
}
// 08. Multi-section mixed paper (A4 portrait + A4 landscape)
{
const sect1 =
'<w:sectPr><w:type w:val="continuous"/>' +
'<w:pgSz w:w="11906" w:h="16838"/>' +
'<w:pgMar w:top="1440" w:right="1800" w:bottom="1440" w:left="1800" w:header="708" w:footer="708" w:gutter="0"/>' +
'</w:sectPr>'
let body = p('多节文档 - 第一节(A4 竖向)', 'Heading1')
for (let i = 0; i < 15; i++) body += loremParagraph(25, 'zh')
// insert a section break (sectPr embedded in the paragraph's pPr)
body += `<w:p><w:pPr>${sect1}</w:pPr></w:p>`
body += p('第二节(A4 横向)', 'Heading1')
for (let i = 0; i < 10; i++) body += loremParagraph(25, 'zh')
specs.push({
name: '08-multi-section-paper',
bodyXml: body,
sectPr: LETTER_LANDSCAPE_SECT_PR,
meta: {
title: 'Multi-section mixed paper sizes',
tags: ['multi-section', 'landscape', 'portrait', 'section-break'],
description: 'Two sections: A4 portrait + landscape, tests pagination at section switches',
},
})
}
// 09. Large paragraph (within one page)
{
let body = p('大段落测试', 'Heading1')
// one large paragraph, close to but not exceeding a page
let bigPara = ''
for (let i = 0; i < 200; i++) bigPara += '这是一段很长的文字内容,用于测试大段落的分页处理行为。'
body += `<w:p><w:r><w:t xml:space="preserve">${escXml(bigPara)}</w:t></w:r></w:p>`
body += p('段落后继续内容')
for (let i = 0; i < 5; i++) body += loremParagraph(30, 'zh')
specs.push({
name: '09-large-paragraph',
bodyXml: body,
meta: {
title: 'Large paragraph (cross-page)',
tags: ['large-paragraph', 'cross-page'],
description: 'One oversized paragraph spanning pages, tests intra-block splitting',
},
})
}
// 10. Chinese official-document format (docGrid + standard page margins)
{
let body = ''
body +=
`<w:p><w:pPr><w:jc w:val="center"/><w:spacing w:before="480" w:after="240"/></w:pPr>` +
`<w:r><w:rPr><w:b/><w:sz w:val="44"/><w:szCs w:val="44"/></w:rPr><w:t>关于深化体制改革的通知</w:t></w:r></w:p>`
body += `<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>各省、自治区、直辖市人民政府:</w:t></w:r></w:p>`
for (let i = 0; i < 8; i++) {
body +=
`<w:p><w:pPr><w:ind w:firstLine="480"/></w:pPr>` +
`<w:r><w:t xml:space="preserve">${escXml('  ' + '为贯彻落实党中央、国务院关于深化体制改革的重要决策部署,切实推进政府职能转变,优化营商环境,提升治理效能,现就有关事项通知如下:'.repeat(3))}</w:t></w:r></w:p>`
}
body += `<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:t>国务院办公厅</w:t></w:r></w:p>`
body += `<w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:t>二○二六年七月二十六日</w:t></w:r></w:p>`
// attachments
for (let i = 1; i <= 3; i++) {
body += p(`附件${i}:相关事项说明`, 'Heading2')
for (let j = 0; j < 10; j++) body += loremParagraph(40, 'zh')
}
specs.push({
name: '10-cn-official-doc',
bodyXml: body,
sectPr: A4_SECT_WITH_DOCGRID,
meta: {
title: 'Chinese official-document format',
tags: ['chinese', 'official-doc', 'docGrid', 'firstLine-indent', 'center-justify'],
description:
'Standard government document format: centered large title + first-line-indented body + signature block, docGrid',
},
})
}
// 11. Table-dense (multiple tables)
{
let body = p('多表格文档', 'Heading1')
for (let t = 0; t < 5; t++) {
body += p(`表格 ${t + 1}`)
body += table(8, 3, true)
body += p('表格说明文字:以上数据来自系统统计。')
}
specs.push({
name: '11-multi-tables',
bodyXml: body,
meta: {
title: 'Multi-table document',
tags: ['table', 'multi-table', 'table-header'],
description: '5 tables interleaved with text, tests pagination of text between tables',
},
})
}
// 12. Orphan heading test (heading right at the page bottom)
{
let body = p('标题孤悬测试', 'Heading1')
// fill until close to the page end
for (let i = 0; i < 30; i++) body += loremParagraph(15, 'en')
// the heading here should sit at the page bottom, with the following content on the next page
body += p('这是一个可能孤悬的二级标题', 'Heading2')
body += p('标题后面的正文段落,标题不应孤悬。')
for (let i = 0; i < 10; i++) body += loremParagraph(20, 'en')
specs.push({
name: '12-orphan-heading',
bodyXml: body,
meta: {
title: 'Orphan heading test',
tags: ['headings', 'keepNext', 'orphan', 'widow'],
description: 'Heading lands right at the page bottom, tests keepNext orphan prevention',
},
})
}
// 13. Long pure-English document (3+ pages)
{
let body = p('Long English Report', 'Heading1')
body += p('Abstract', 'Heading2')
for (let i = 0; i < 15; i++) body += loremParagraph(40, 'en')
body += p('Introduction', 'Heading2')
for (let i = 0; i < 20; i++) body += loremParagraph(35, 'en')
body += p('Methodology', 'Heading2')
for (let i = 0; i < 20; i++) body += loremParagraph(35, 'en')
body += p('Results', 'Heading2')
for (let i = 0; i < 15; i++) body += loremParagraph(30, 'en')
body += p('Conclusion', 'Heading2')
for (let i = 0; i < 10; i++) body += loremParagraph(30, 'en')
specs.push({
name: '13-english-report',
bodyXml: body,
meta: {
title: 'English Report (3+ pages)',
tags: ['english', 'headings', 'multi-page', 'long'],
description: 'English report format, 4-section heading structure, 3+ pages',
},
})
}
// 14. Long Chinese document (no docGrid)
{
let body = p('中文文档(无网格)', 'Heading1')
for (let i = 0; i < 60; i++) body += loremParagraph(40, 'zh')
specs.push({
name: '14-chinese-no-docgrid',
bodyXml: body,
meta: {
title: 'Long Chinese text (no docGrid)',
tags: ['chinese', 'no-docGrid', 'multi-page'],
description: 'Pure Chinese without docGrid, contrast test against 02',
},
})
}
// 15. Mixed elements (headings + tables + body)
{
let body = p('混合内容文档', 'Heading1')
for (let section = 1; section <= 4; section++) {
body += p(`第${section}节 内容概述`, 'Heading2')
for (let i = 0; i < 5; i++) body += loremParagraph(25, 'zh')
body += p(`第${section}.1 数据汇总`, 'Heading3')
body += table(6, 3, true)
for (let i = 0; i < 3; i++) body += loremParagraph(20, 'zh')
body += p(`第${section}.2 分析结论`, 'Heading3')
for (let i = 0; i < 6; i++) body += loremParagraph(25, 'zh')
}
specs.push({
name: '15-mixed-content',
bodyXml: body,
sectPr: A4_SECT_WITH_DOCGRID,
meta: {
title: 'Mixed content (headings + tables + body)',
tags: ['mixed', 'table', 'headings', 'docGrid'],
description: 'Headings, tables and body text mixed — the most common report structure',
},
})
}
// 16. Numbered-list document
{
const _NUMBERING_XML =
XML_DECL +
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
'<w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/>' +
'<w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum>' +
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
'</w:numbering>'
// inline numbering into extra styles (no separate file; simplified approach)
let body = p('编号列表文档', 'Heading1')
for (let i = 1; i <= 50; i++) {
body +=
`<w:p><w:pPr><w:pStyle w:val="ListParagraph"/><w:numPr><w:ilvl w:val="0"/><w:numId w:val="0"/></w:numPr></w:pPr>` +
`<w:r><w:t xml:space="preserve">${i}. 列表项目:${escXml('这是第' + i + '条列表内容,用于测试编号列表的分页行为。')}</w:t></w:r></w:p>`
}
specs.push({
name: '16-numbered-list',
bodyXml: body,
meta: {
title: 'Numbered-list document',
tags: ['numbered-list', 'list-paragraph', 'multi-page'],
description: '50 numbered list items, tests list pagination across pages',
},
})
}
// 17. Short single-page document
{
let body = p('单页短文档', 'Heading1')
body += p('这是一份很短的文档,所有内容都在第一页内。')
body += p('第二段内容。')
body += p('第三段内容,文档到此结束。')
specs.push({
name: '17-single-page',
bodyXml: body,
meta: {
title: 'Short single-page document',
tags: ['single-page', 'short'],
description: 'All content fits on one page, baseline case',
},
})
}
// 18. Paragraphs with the pageBreakBefore property
{
let body = p('pageBreakBefore 测试', 'Heading1')
for (let i = 0; i < 5; i++) body += loremParagraph(20, 'zh')
body += `<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>此段落设置了 pageBreakBefore 属性</w:t></w:r></w:p>`
for (let i = 0; i < 5; i++) body += loremParagraph(20, 'zh')
body += `<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>第二个 pageBreakBefore 段落</w:t></w:r></w:p>`
for (let i = 0; i < 5; i++) body += loremParagraph(20, 'zh')
specs.push({
name: '18-page-break-before',
bodyXml: body,
meta: {
title: 'pageBreakBefore property',
tags: ['pageBreakBefore', 'forced-break'],
description: 'Two paragraphs with the pageBreakBefore property, tests breakBefore logic',
},
})
}
// 19. Large table (over one page)
{
let body = p('超大表格测试', 'Heading1')
body += p('以下表格超过一页:')
body += table(60, 3, true)
body += p('超大表格后续内容。')
specs.push({
name: '19-oversized-table',
bodyXml: body,
meta: {
title: 'Oversized table (>1 page)',
tags: ['table', 'cross-page', 'large-table', 'pixel-cut'],
description: '60-row table exceeding one page, triggers the pixel hard-cut logic',
},
})
}
// 20. Chinese official document (shorter, ~1.5 pages)
{
let body =
`<w:p><w:pPr><w:jc w:val="center"/></w:pPr>` +
`<w:r><w:rPr><w:b/><w:sz w:val="36"/></w:rPr><w:t>人工智能办公系统建设方案</w:t></w:r></w:p>`
body += `<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>信息化建设工作小组</w:t></w:r></w:p>`
body += `<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t>2026年7月</w:t></w:r></w:p>`
for (let i = 0; i < 12; i++) {
body +=
`<w:p><w:pPr><w:ind w:firstLine="480"/></w:pPr>` +
`<w:r><w:t xml:space="preserve">${escXml('  本方案旨在系统推进办公自动化智能升级,通过引入先进的人工智能技术,全面提升行政办公效率,降低运营成本,改善用户体验,为现代化治理体系建设提供有力支撑。'.repeat(2))}</w:t></w:r></w:p>`
}
specs.push({
name: '20-cn-short-report',
bodyXml: body,
sectPr: A4_SECT_WITH_DOCGRID,
meta: {
title: 'Short Chinese report (~1.5 pages)',
tags: ['chinese', 'docGrid', 'short-report', 'center-title'],
description: '~1.5-page Chinese report, centered title, first-line-indented body',
},
})
}
// 21. Multi-section continuation (continuous section)
{
const sect1Continuous =
'<w:sectPr><w:type w:val="continuous"/>' +
'<w:pgSz w:w="11906" w:h="16838"/>' +
'<w:pgMar w:top="1440" w:right="1800" w:bottom="1440" w:left="1800" w:header="708" w:footer="708" w:gutter="0"/>' +
'</w:sectPr>'
let body = p('连续节分隔符测试', 'Heading1')
for (let i = 0; i < 10; i++) body += loremParagraph(25, 'zh')
body += `<w:p><w:pPr>${sect1Continuous}</w:pPr></w:p>`
body += p('续页节(内容紧接上节)', 'Heading2')
for (let i = 0; i < 15; i++) body += loremParagraph(25, 'zh')
specs.push({
name: '21-continuous-section',
bodyXml: body,
meta: {
title: 'Continuous section break',
tags: ['multi-section', 'continuous-section'],
description:
'Contains a continuous section break, tests section switching without a forced page break',
},
})
}
// 22. Multi-column document
{
const twoColSect =
'<w:sectPr>' +
'<w:pgSz w:w="11906" w:h="16838"/>' +
'<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>' +
'<w:cols w:num="2" w:space="720"/>' +
'</w:sectPr>'
let body = p('双栏布局文档', 'Heading1')
for (let i = 0; i < 30; i++) body += loremParagraph(20, 'zh')
specs.push({
name: '22-two-columns',
bodyXml: body,
sectPr: twoColSect,
meta: {
title: 'Two-column layout',
tags: ['two-column', 'columns', 'layout'],
description: 'Two-column layout, tests pagination with columns',
},
})
}
// 23. tblHeader repeated headers across pages
{
const border = (n: string) => `<w:${n} w:val="single" w:sz="4" w:space="0" w:color="auto"/>`
const borders =
'<w:tblBorders>' +
['top', 'left', 'bottom', 'right', 'insideH', 'insideV'].map(border).join('') +
'</w:tblBorders>'
let rows =
'<w:tr><w:trPr><w:tblHeader/></w:trPr>' +
['列A表头', '列B表头']
.map(
(t) =>
`<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/><w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/></w:tcPr>` +
`<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>${t}</w:t></w:r></w:p></w:tc>`,
)
.join('') +
'</w:tr>'
for (let r = 1; r <= 45; r++) {
const cantSplit = r % 10 === 0 ? '<w:trPr><w:cantSplit/></w:trPr>' : ''
rows +=
`<w:tr>${cantSplit}` +
[1, 2]
.map(
(c) =>
`<w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr>` +
`<w:p><w:r><w:t>第${r}行${c === 1 ? 'A' : 'B'}</w:t></w:r></w:p></w:tc>`,
)
.join('') +
'</w:tr>'
}
const body =
p('tblHeader 跨页表头重复测试', 'Heading1') +
`<w:tbl><w:tblPr>${borders}</w:tblPr>${rows}</w:tbl>` +
p('表后段落。')
specs.push({
name: '23-tblheader-repeat',
bodyXml: body,
meta: {
title: 'tblHeader repeated header',
tags: ['table', 'tblHeader', 'cantSplit'],
description:
'Cross-page table with a tblHeader first row (repeated header placeholder on following pages) + some cantSplit rows',
},
})
}
// write the files
async function writeAll() {
for (const spec of specs) {
const bytes = await buildDocx(spec)
const docxPath = join(DOCX_OUT, `${spec.name}.docx`)
writeFileSync(docxPath, bytes)
const metaPath = join(META_OUT, `${spec.name}.json`)
writeFileSync(metaPath, JSON.stringify({ ...spec.meta, file: `${spec.name}.docx` }, null, 2))
console.log(`✓ ${spec.name}.docx (${(bytes.length / 1024).toFixed(1)} KB)`)
}
// copy existing fixtures (simple files, already in the docx directory)
const existingFiles = [
{ src: join(REPO_ROOT, 'fixtures/generated/simple.docx'), name: 'fixture-simple.docx' },
{
src: join(REPO_ROOT, 'fixtures/generated/kitchen-sink.docx'),
name: 'fixture-kitchen-sink.docx',
},
]
for (const f of existingFiles) {
if (existsSync(f.src)) {
const dst = join(DOCX_OUT, f.name)
copyFileSync(f.src, dst)
console.log(`✓ ${f.name} (copied from fixtures)`)
// meta
const title = f.name.replace(/^fixture-/, '').replace('.docx', '')
const metaPath = join(META_OUT, f.name.replace('.docx', '.json'))
writeFileSync(
metaPath,
JSON.stringify(
{
title,
file: f.name,
tags: ['fixture', 'real-world'],
description: `Real test file copied from repo fixtures`,
},
null,
2,
),
)
}
}
console.log(
`\ntotal ${specs.length + existingFiles.length} corpus files (${specs.length} programmatically built, ${existingFiles.length} from fixtures)`,
)
}
writeAll().catch((err) => {
console.error(err)
process.exit(1)
})
File diff suppressed because it is too large Load Diff
+3
View File
@@ -0,0 +1,3 @@
import { startDocsStandalone } from './docs-main'
startDocsStandalone()
+244
View File
@@ -0,0 +1,244 @@
import { app, dialog } from 'electron'
import type { BrowserWindow } from 'electron'
import { autoUpdater } from 'electron-updater'
import type { UpdateInfo } from 'electron-updater'
import { createI18n, getUiLang } from '@genoffice/i18n'
/**
* Full-package auto-update for the standalone GenOffice Docs app over the generic
* provider (Azure CDN).
*
* electron-builder bakes the publish URL into resources/app-update.yml at
* package time and emits the update feed (latest.yml on Windows,
* latest-mac.yml on macOS) next to the installers; the release pipeline
* uploads both to the CDN. Standalone docs builds currently ship without a
* publish config, so packaged runs simply log the missing-feed error.
*
* Unlike the shell's modal update window, docs keeps the flow minimal:
* updates download silently in the background and a single native dialog
* offers "Restart & Install" once the payload is ready. Declining defers the
* install to normal app quit (autoInstallOnAppQuit).
*/
const tUpd = createI18n({
zh: {
updTitle: '软件更新',
updHeadline: '发现新版本',
updDesc: '新版本包含性能改进与问题修复,建议立即更新。',
updInstall: '立即重启安装',
updLater: '稍后再说',
},
en: {
updTitle: 'Software Update',
updHeadline: 'A new version is available',
updDesc:
'This update includes performance improvements and bug fixes. We recommend updating now.',
updInstall: 'Restart & Install',
updLater: 'Remind me later',
},
ja: {
updTitle: 'ソフトウェアアップデート',
updHeadline: '新しいバージョンがあります',
updDesc:
'このアップデートにはパフォーマンス改善とバグ修正が含まれます。今すぐの更新をおすすめします。',
updInstall: '再起動してインストール',
updLater: '後で通知',
},
ko: {
updTitle: '소프트웨어 업데이트',
updHeadline: '새 버전이 있습니다',
updDesc:
'이 업데이트에는 성능 개선과 버그 수정이 포함되어 있습니다. 지금 업데이트하는 것을 권장합니다.',
updInstall: '다시 시작 및 설치',
updLater: '나중에 알림',
},
fr: {
updTitle: 'Mise à jour logicielle',
updHeadline: 'Une nouvelle version est disponible',
updDesc:
'Cette mise à jour apporte des améliorations de performances et des corrections de bogues. Nous vous recommandons de mettre à jour maintenant.',
updInstall: 'Redémarrer et installer',
updLater: 'Plus tard',
},
de: {
updTitle: 'Softwareaktualisierung',
updHeadline: 'Eine neue Version ist verfügbar',
updDesc:
'Dieses Update enthält Leistungsverbesserungen und Fehlerbehebungen. Wir empfehlen, jetzt zu aktualisieren.',
updInstall: 'Neu starten und installieren',
updLater: 'Später erinnern',
},
es: {
updTitle: 'Actualización de software',
updHeadline: 'Hay una nueva versión disponible',
updDesc:
'Esta actualización incluye mejoras de rendimiento y correcciones de errores. Recomendamos actualizar ahora.',
updInstall: 'Reiniciar e instalar',
updLater: 'Recordar más tarde',
},
th: {
updTitle: 'อัปเดตซอฟต์แวร์',
updHeadline: 'มีเวอร์ชันใหม่พร้อมใช้งาน',
updDesc: 'การอัปเดตนี้มีการปรับปรุงประสิทธิภาพและแก้ไขข้อบกพร่อง แนะนำให้อัปเดตทันที',
updInstall: 'รีสตาร์ทและติดตั้ง',
updLater: 'เตือนภายหลัง',
},
id: {
updTitle: 'Pembaruan Perangkat Lunak',
updHeadline: 'Versi baru tersedia',
updDesc:
'Pembaruan ini mencakup peningkatan kinerja dan perbaikan bug. Kami menyarankan untuk memperbarui sekarang.',
updInstall: 'Mulai Ulang & Pasang',
updLater: 'Ingatkan nanti',
},
ru: {
updTitle: 'Обновление программы',
updHeadline: 'Доступна новая версия',
updDesc:
'Это обновление содержит улучшения производительности и исправления ошибок. Рекомендуем обновиться сейчас.',
updInstall: 'Перезапустить и установить',
updLater: 'Напомнить позже',
},
ar: {
updTitle: 'تحديث البرنامج',
updHeadline: 'يتوفر إصدار جديد',
updDesc: 'يتضمن هذا التحديث تحسينات في الأداء وإصلاحات للأخطاء. نوصي بالتحديث الآن.',
updInstall: 'إعادة التشغيل والتثبيت',
updLater: 'ذكّرني لاحقًا',
},
pt: {
updTitle: 'Atualização de Software',
updHeadline: 'Uma nova versão está disponível',
updDesc:
'Esta atualização inclui melhorias de desempenho e correções de erros. Recomendamos atualizar agora.',
updInstall: 'Reiniciar e instalar',
updLater: 'Lembrar mais tarde',
},
it: {
updTitle: 'Aggiornamento software',
updHeadline: 'È disponibile una nuova versione',
updDesc:
'Questo aggiornamento include miglioramenti delle prestazioni e correzioni di bug. Consigliamo di aggiornare subito.',
updInstall: 'Riavvia e installa',
updLater: 'Ricordamelo più tardi',
},
pl: {
updTitle: 'Aktualizacja oprogramowania',
updHeadline: 'Dostępna jest nowa wersja',
updDesc:
'Ta aktualizacja zawiera ulepszenia wydajności i poprawki błędów. Zalecamy aktualizację teraz.',
updInstall: 'Uruchom ponownie i zainstaluj',
updLater: 'Przypomnij później',
},
nl: {
updTitle: 'Software-update',
updHeadline: 'Er is een nieuwe versie beschikbaar',
updDesc:
'Deze update bevat prestatieverbeteringen en foutoplossingen. We raden aan nu bij te werken.',
updInstall: 'Opnieuw starten en installeren',
updLater: 'Later herinneren',
},
ms: {
updTitle: 'Kemas Kini Perisian',
updHeadline: 'Versi baharu tersedia',
updDesc:
'Kemas kini ini merangkumi penambahbaikan prestasi dan pembetulan pepijat. Kami syorkan kemas kini sekarang.',
updInstall: 'Mula Semula & Pasang',
updLater: 'Ingatkan kemudian',
},
he: {
updTitle: 'עדכון תוכנה',
updHeadline: 'גרסה חדשה זמינה',
updDesc: 'עדכון זה כולל שיפורי ביצועים ותיקוני באגים. מומלץ לעדכן עכשיו.',
updInstall: 'הפעל מחדש והתקן',
updLater: 'הזכר לי מאוחר יותר',
},
hi: {
updTitle: 'सॉफ़्टवेयर अपडेट',
updHeadline: 'नया संस्करण उपलब्ध है',
updDesc:
'इस अपडेट में प्रदर्शन सुधार और बग फ़िक्स शामिल हैं। हम अभी अपडेट करने की सलाह देते हैं।',
updInstall: 'पुनरारंभ करें और इंस्टॉल करें',
updLater: 'बाद में याद दिलाएँ',
},
'zh-TW': {
updTitle: '軟體更新',
updHeadline: '發現新版本',
updDesc: '新版本包含效能改進與問題修復,建議立即更新。',
updInstall: '立即重新啟動安裝',
updLater: '稍後再說',
},
})
const FIRST_CHECK_DELAY_MS = 15_000
const RECHECK_INTERVAL_MS = 4 * 60 * 60 * 1000
let started = false
// version the user declined this session — don't nag again until next launch
let dismissedVersion: string | null = null
function log(...args: unknown[]): void {
console.log('[docs-updater]', ...args)
}
async function promptInstall(win: BrowserWindow | null, info: UpdateInfo): Promise<void> {
const lang = getUiLang()
const options = {
type: 'info' as const,
title: tUpd(lang, 'updTitle'),
message: `${tUpd(lang, 'updHeadline')} (${info.version})`,
detail: tUpd(lang, 'updDesc'),
buttons: [tUpd(lang, 'updInstall'), tUpd(lang, 'updLater')],
defaultId: 0,
cancelId: 1,
}
const { response } =
win && !win.isDestroyed()
? await dialog.showMessageBox(win, options)
: await dialog.showMessageBox(options)
if (response === 0) {
autoUpdater.quitAndInstall(true, true)
} else {
// autoInstallOnAppQuit still applies the update on normal quit
dismissedVersion = info.version
}
}
export function initDocsAutoUpdater(getWindow: () => BrowserWindow | null): void {
if (started) return
started = true
// Unpacked runs have no app-update.yml and must not hit the CDN with a dev
// version. Windows updates via NSIS (latest.yml); macOS via the zip target
// (latest-mac.yml) — Squirrel.Mac additionally requires a signed app, so
// unsigned local builds check but never install.
if (!app.isPackaged) return
if (process.platform !== 'win32' && process.platform !== 'darwin') return
autoUpdater.autoDownload = true
autoUpdater.autoInstallOnAppQuit = true
// full-package policy: never attempt blockmap differential downloads
// (the publish pipeline does not upload .blockmap files)
autoUpdater.disableDifferentialDownload = true
autoUpdater.on('error', (err) => {
// background check/download failures are expected offline; log only
log('error:', err instanceof Error ? err.message : err)
})
autoUpdater.on('update-downloaded', (info: UpdateInfo) => {
if (info.version === dismissedVersion) return
log('downloaded:', info.version)
promptInstall(getWindow(), info).catch((err) => {
log('install prompt failed:', err instanceof Error ? err.message : err)
})
})
const check = (): void => {
autoUpdater
.checkForUpdates()
.catch((err) => log('check failed:', err instanceof Error ? err.message : err))
}
setTimeout(check, FIRST_CHECK_DELAY_MS)
setInterval(check, RECHECK_INTERVAL_MS)
}
+127
View File
@@ -0,0 +1,127 @@
import { contextBridge, ipcRenderer, webUtils } from 'electron'
import type { IpcRendererEvent } from 'electron'
import type {
AiChatRequest,
AiSettings,
AiStreamChunk,
AiStreamRequest,
DesktopApi,
MenuCommand,
} from '../shared/ipc'
import type { ProjectApi } from '@genoffice/project-store'
const api: DesktopApi = {
getLanguage: () => ipcRenderer.invoke('app:get-language'),
onLanguageChanged: (handler) => {
const listener = (
_event: IpcRendererEvent,
lang: 'zh' | 'en' | 'ja' | 'ko' | 'fr' | 'de' | 'es' | 'th' | 'id' | 'ru' | 'ar',
) => handler(lang)
ipcRenderer.on('app:language-changed', listener)
return () => ipcRenderer.removeListener('app:language-changed', listener)
},
openDocx: () => ipcRenderer.invoke('docs:open'),
openDocxPath: (path: string) => ipcRenderer.invoke('docs:open-path', path),
consumePendingOpenDocx: () => ipcRenderer.invoke('docs:consume-pending-open'),
consumeNewBlankDoc: () => ipcRenderer.invoke('docs:consume-new-blank'),
onOpenDocx: (handler) => {
const listener = (_event: IpcRendererEvent, result: Parameters<typeof handler>[0]) =>
handler(result)
ipcRenderer.on('docs:opened', listener)
return () => ipcRenderer.removeListener('docs:opened', listener)
},
onRenamedDocx: (handler) => {
const listener = (_event: IpcRendererEvent, paths: Parameters<typeof handler>[0]) =>
handler(paths)
ipcRenderer.on('docs:renamed', listener)
return () => ipcRenderer.removeListener('docs:renamed', listener)
},
saveDocx: (path: string, data: ArrayBuffer) => ipcRenderer.invoke('docs:save', path, data),
writeRecoveryCopy: (path: string, data: ArrayBuffer) =>
ipcRenderer.invoke('docs:write-recovery', path, data),
saveDocxAs: (defaultName: string, data: ArrayBuffer) =>
ipcRenderer.invoke('docs:save-as', defaultName, data),
saveDocxNew: (defaultName: string, data: ArrayBuffer) =>
ipcRenderer.invoke('docs:save-new', defaultName, data),
getRecentFiles: () => ipcRenderer.invoke('docs:recent'),
pickImage: () => ipcRenderer.invoke('docs:pick-image'),
print: () => ipcRenderer.invoke('docs:print'),
exportPdf: (
defaultName: string,
pageWidthTwips: number,
pageHeightTwips: number,
outPath?: string,
) => ipcRenderer.invoke('docs:export-pdf', defaultName, pageWidthTwips, pageHeightTwips, outPath),
printPdfBuffer: (pageWidthTwips: number, pageHeightTwips: number) =>
ipcRenderer.invoke('docs:print-pdf-buffer', pageWidthTwips, pageHeightTwips),
saveMergedPdf: (defaultName: string, base64Parts: string[], outPath?: string) =>
ipcRenderer.invoke('docs:save-merged-pdf', defaultName, base64Parts, outPath),
getAiSettings: () => ipcRenderer.invoke('ai:get-settings'),
setAiSettings: (settings: AiSettings) => ipcRenderer.invoke('ai:set-settings', settings),
aiChat: (request: AiChatRequest) => ipcRenderer.invoke('ai:chat', request),
aiStream: (request: AiStreamRequest) => ipcRenderer.invoke('ai:stream', request),
aiStreamCancel: (requestId: string) => ipcRenderer.invoke('ai:stream-cancel', requestId),
aiGskStatus: (withEmail?: boolean) => ipcRenderer.invoke('ai:gsk-status', withEmail),
aiGskLogin: () => ipcRenderer.invoke('ai:gsk-login'),
webSearch: (query: string, maxResults?: number) =>
ipcRenderer.invoke('ai:web-search', query, maxResults),
imageSearch: (query: string, maxResults?: number) =>
ipcRenderer.invoke('ai:image-search', query, maxResults),
fetchImage: (url: string) => ipcRenderer.invoke('ai:fetch-image', url),
pickAttachments: () => ipcRenderer.invoke('files:pick'),
addAttachmentPaths: (paths: string[]) => ipcRenderer.invoke('files:add', paths),
addPastedImage: (data: ArrayBuffer, ext: string) =>
ipcRenderer.invoke('files:add-pasted-image', data, ext),
readAttachment: (path: string, offset: number, maxChars: number) =>
ipcRenderer.invoke('files:read', path, offset, maxChars),
readAttachmentImage: (path: string) => ipcRenderer.invoke('files:read-image', path),
getPathForFile: (file: File) => webUtils.getPathForFile(file),
openNewTab: (openPath?: string | null) => ipcRenderer.invoke('win:new', openPath ?? null),
listDocsTabs: () => ipcRenderer.invoke('win:list'),
focusDocsTab: (id: string) => ipcRenderer.invoke('win:focus', id),
onAiStream: (handler: (chunk: AiStreamChunk) => void) => {
const listener = (_event: IpcRendererEvent, chunk: AiStreamChunk) => handler(chunk)
ipcRenderer.on('ai:stream-chunk', listener)
return () => ipcRenderer.removeListener('ai:stream-chunk', listener)
},
onMenuCommand: (handler: (command: MenuCommand, payload?: string) => void) => {
const listener = (_event: IpcRendererEvent, command: MenuCommand, payload?: string) =>
handler(command, payload)
ipcRenderer.on('menu:command', listener)
return () => ipcRenderer.removeListener('menu:command', listener)
},
onCloseCheck: (handler: () => void) => {
const listener = () => handler()
ipcRenderer.on('docs:close-check', listener)
return () => ipcRenderer.removeListener('docs:close-check', listener)
},
reportCloseCheck: (state: { dirty: boolean; autoSave: boolean; filePath?: string | null }) =>
ipcRenderer.send('docs:close-check-result', {
dirty: state?.dirty === true,
autoSave: state?.autoSave === true,
filePath: typeof state?.filePath === 'string' ? state.filePath : null,
}),
onCloseSaveRequest: (handler: () => void) => {
const listener = () => handler()
ipcRenderer.on('docs:close-save-request', listener)
return () => ipcRenderer.removeListener('docs:close-save-request', listener)
},
reportCloseSaveResult: (ok: boolean) => ipcRenderer.send('docs:close-save-result', ok === true),
}
const projectApi: ProjectApi = {
resolveChat: (args) => ipcRenderer.invoke('project:resolveChat', args),
appendChat: (args) => ipcRenderer.invoke('project:appendChat', args),
loadChat: (args) => ipcRenderer.invoke('project:loadChat', args),
rebindChat: (args) => ipcRenderer.invoke('project:rebindChat', args),
// P1 extensions
listProjects: () => ipcRenderer.invoke('project:list'),
createProject: (args) => ipcRenderer.invoke('project:create', args),
renameProject: (args) => ipcRenderer.invoke('project:rename', args),
deleteProject: (args) => ipcRenderer.invoke('project:delete', args),
moveFile: (args) => ipcRenderer.invoke('project:moveFile', args),
getTimeline: (args) => ipcRenderer.invoke('project:timeline', args),
}
contextBridge.exposeInMainWorld('desktop', api)
contextBridge.exposeInMainWorld('projectApi', projectApi)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+976
View File
@@ -0,0 +1,976 @@
import type { Editor } from '@tiptap/core'
import type { Node as PmDocNode, Schema } from '@tiptap/pm/model'
import type { Transaction } from '@tiptap/pm/state'
import { generateTocFieldXml, type TocEntry } from '@genoffice/docx-engine'
import { t } from '../i18n/locale'
/**
* Structured edit commands: the model emits a
* batchUpdate-style JSON envelope and code applies it deterministically on the
* PM doc — one transaction per envelope, so one undo reverts the whole round.
* The docx round trip is untouched: changed nodes become dirty via the normal
* signature comparison and regenerate on save; docxIndex anchors are never
* modified here.
*/
// ---- command types (§4) ----
/** All given conditions filter with AND; at least one condition is required */
export interface Target {
/** 'image' matches protected image blocks (docProtected + blockType image) */
nodeType?: 'docHeading' | 'docParagraph' | 'docListItem' | 'image'
/** Restrict heading level (only with nodeType: 'docHeading') */
headingLevel?: number
/** The block's plain text contains this substring (case-sensitive unless matchCase: false) */
containsText?: string
matchCase?: boolean
/** By block index (the index output by buildDocumentContext, 0-based, current PM doc top-level order) */
blockIndexes?: number[]
/** 'selection' = only blocks covered by the current selection; default = whole document */
scope?: 'selection' | 'document'
}
/** Run-level style; only keys listed in fields take effect, and null clears the property */
export interface UpdateTextStyle {
target: Target
style: {
color?: string | null
highlight?: string | null
sizeHalfPoints?: number | null
font?: string | null
bold?: boolean
italic?: boolean
underline?: boolean
strike?: boolean
/** Super/subscript (enum values aligned with Google TextStyle.baselineOffset) */
baselineOffset?: 'SUPERSCRIPT' | 'SUBSCRIPT' | 'NONE' | null
/** Hyperlink (aligned with Google TextStyle.link); null removes the link */
link?: { url: string } | null
}
fields: Array<keyof UpdateTextStyle['style']>
}
/** Paragraph-level format; likewise constrained by the fields mask */
export interface UpdateParagraphStyle {
target: Target
style: {
align?: 'left' | 'center' | 'right' | 'justify' | null
lineSpacing?: number | null
indentLeft?: number | null
indentRight?: number | null
/** First-line indent in twips; positive = first-line indent, negative = hanging indent (aligned with Google indentFirstLine) */
indentFirstLine?: number | null
spaceBefore?: number | null
spaceAfter?: number | null
pageBreakBefore?: boolean
shadingFill?: string | null
/** Paragraph borders, a subset of "tblr" (simplified Google borderTop/Bottom/Left/Right) */
borders?: string | null
}
fields: Array<keyof UpdateParagraphStyle['style']>
}
/** Paragraph promote/demote; level 0 = demote to body paragraph, 1-6 = the corresponding heading level */
export interface SetHeadingLevel {
target: Target
level: 0 | 1 | 2 | 3 | 4 | 5 | 6
}
/** Whole-document find & replace (plain text, no cross-block matching) */
export interface ReplaceAllText {
containsText: string
replaceText: string
matchCase?: boolean
}
export interface DeleteBlocks {
target: Target
}
/** Move the blocks in blockIndexes (relative order kept) after afterBlockIndex; -1 = document start */
export interface MoveBlocks {
blockIndexes: number[]
afterBlockIndex: number
}
/**
* Paragraphs to list (name and semantics aligned with Google's createParagraphBullets).
* BULLET*-prefixed presets = unordered, NUMBERED* = ordered; heading blocks aren't converted (counted in matched but unchanged).
*/
export interface CreateParagraphBullets {
target: Target
bulletPreset?: string
}
/** List items back to body paragraphs (aligned with Google's deleteParagraphBullets) */
export interface DeleteParagraphBullets {
target: Target
}
/** Image block properties; giving only one of widthPx/heightPx scales the other side by the original ratio */
export interface UpdateImageProperties {
target: Target
properties: {
widthPx?: number | null
heightPx?: number | null
align?: 'left' | 'center' | 'right' | null
}
fields: Array<keyof UpdateImageProperties['properties']>
}
/**
* Insert a TOC field after the given block (a real TOC field; Word recomputes page numbers on open).
* Entries come from the current document's heading blocks; the command fails when there are no headings.
*/
export interface InsertToc {
/** Insert after this block index; -1 = document start */
afterBlockIndex: number
}
export type Command =
| { updateTextStyle: UpdateTextStyle }
| { updateParagraphStyle: UpdateParagraphStyle }
| { setHeadingLevel: SetHeadingLevel }
| { replaceAllText: ReplaceAllText }
| { deleteBlocks: DeleteBlocks }
| { moveBlocks: MoveBlocks }
| { createParagraphBullets: CreateParagraphBullets }
| { deleteParagraphBullets: DeleteParagraphBullets }
| { updateImageProperties: UpdateImageProperties }
| { insertToc: InsertToc }
/** numbering context so converted list items join real docx numbering on save */
export interface CommandContext {
numIds?: { bullet: string | null; ordered: string | null } | null
/** record the envelope's changes as tracked revisions under this author */
track?: { author: string } | null
}
export interface CommandEnvelope {
commands: Command[]
}
export interface CommandResult {
command: string
matched: number
changed: number
skippedProtected: number
detail?: string
}
export interface ExecuteOutcome {
ok: boolean
results: CommandResult[]
summary: string
error?: string
}
// ---- envelope extraction ----
/** pull a command envelope out of a model response; null = not command mode */
export function parseCommandEnvelope(raw: string): CommandEnvelope | null {
const text = raw.trim()
const fence = /```json\s*([\s\S]*?)```/.exec(text)
const candidate = fence ? fence[1].trim() : text.startsWith('{') ? text : null
if (!candidate) return null
try {
const parsed: unknown = JSON.parse(candidate)
if (
parsed &&
typeof parsed === 'object' &&
Array.isArray((parsed as CommandEnvelope).commands)
) {
return parsed as CommandEnvelope
}
} catch {
// not JSON: content mode
}
return null
}
// ---- validation (whole-envelope: any invalid command rejects everything) ----
const NODE_TYPES = ['docHeading', 'docParagraph', 'docListItem', 'image'] as const
const TEXT_STYLE_KEYS = [
'color',
'highlight',
'sizeHalfPoints',
'font',
'bold',
'italic',
'underline',
'strike',
'baselineOffset',
'link',
] as const
const PARA_STYLE_KEYS = [
'align',
'lineSpacing',
'indentLeft',
'indentRight',
'indentFirstLine',
'spaceBefore',
'spaceAfter',
'pageBreakBefore',
'shadingFill',
'borders',
] as const
const BASELINE_OFFSETS = ['SUPERSCRIPT', 'SUBSCRIPT', 'NONE'] as const
const COMMAND_NAMES = [
'updateTextStyle',
'updateParagraphStyle',
'setHeadingLevel',
'replaceAllText',
'deleteBlocks',
'moveBlocks',
'createParagraphBullets',
'deleteParagraphBullets',
'updateImageProperties',
'insertToc',
] as const
const IMAGE_PROP_KEYS = ['widthPx', 'heightPx', 'align'] as const
type CommandName = (typeof COMMAND_NAMES)[number]
function validateTarget(target: unknown, where: string): string | null {
if (!target || typeof target !== 'object') return `${where}: missing target`
const t = target as Target
if (t.nodeType !== undefined && !NODE_TYPES.includes(t.nodeType)) {
return `${where}: unknown nodeType "${String(t.nodeType)}"`
}
if (
t.headingLevel !== undefined &&
(!Number.isInteger(t.headingLevel) || t.headingLevel < 1 || t.headingLevel > 6)
) {
return `${where}: headingLevel must be an integer between 1 and 6`
}
if (
t.blockIndexes !== undefined &&
(!Array.isArray(t.blockIndexes) || t.blockIndexes.some((i) => !Number.isInteger(i) || i < 0))
) {
return `${where}: blockIndexes must be an array of non-negative integers`
}
const hasCondition =
t.nodeType !== undefined ||
t.headingLevel !== undefined ||
typeof t.containsText === 'string' ||
(Array.isArray(t.blockIndexes) && t.blockIndexes.length > 0) ||
t.scope === 'selection'
if (!hasCondition) return `${where}: target requires at least one condition`
return null
}
function validateStyleCommand(
payload: { target?: unknown; style?: unknown; fields?: unknown },
allowedKeys: readonly string[],
where: string,
): string | null {
const targetError = validateTarget(payload.target, where)
if (targetError) return targetError
if (!payload.style || typeof payload.style !== 'object') return `${where}: missing style`
if (!Array.isArray(payload.fields) || payload.fields.length === 0) {
return `${where}: fields must not be empty`
}
const bad = payload.fields.filter((f) => !allowedKeys.includes(String(f)))
if (bad.length > 0) return `${where}: unknown fields ${bad.map(String).join(', ')}`
return null
}
export function validateEnvelope(envelope: unknown): string | null {
if (!envelope || typeof envelope !== 'object') return 'the envelope must be an object'
const commands = (envelope as CommandEnvelope).commands
if (!Array.isArray(commands) || commands.length === 0) return 'commands must be a non-empty array'
for (let i = 0; i < commands.length; i++) {
const command = commands[i] as Record<string, unknown>
if (!command || typeof command !== 'object') return `command #${i}: must be an object`
const keys = Object.keys(command)
if (keys.length !== 1) return `command #${i}: must be a single-key object`
const name = keys[0]
const where = `command #${i} ${name}`
if (!COMMAND_NAMES.includes(name as CommandName)) return `${where}: unknown command`
const payload = command[name] as Record<string, unknown>
if (!payload || typeof payload !== 'object') return `${where}: parameters must be an object`
let error: string | null = null
switch (name as CommandName) {
case 'updateTextStyle': {
error = validateStyleCommand(payload, TEXT_STYLE_KEYS, where)
if (!error) {
const style = payload.style as UpdateTextStyle['style']
if (
style.baselineOffset != null &&
!(BASELINE_OFFSETS as readonly string[]).includes(style.baselineOffset)
) {
error = `${where}: baselineOffset must be SUPERSCRIPT/SUBSCRIPT/NONE`
} else if (style.link != null && typeof style.link.url !== 'string') {
error = `${where}: link must be { url } or null`
}
}
break
}
case 'updateParagraphStyle':
error = validateStyleCommand(payload, PARA_STYLE_KEYS, where)
break
case 'setHeadingLevel': {
error = validateTarget(payload.target, where)
const level = payload.level
if (!error && (!Number.isInteger(level) || Number(level) < 0 || Number(level) > 6)) {
error = `${where}: level must be an integer between 0 and 6`
}
break
}
case 'replaceAllText':
if (typeof payload.containsText !== 'string' || payload.containsText === '') {
error = `${where}: containsText must not be empty`
} else if (typeof payload.replaceText !== 'string') {
error = `${where}: replaceText must be a string`
}
break
case 'deleteBlocks':
error = validateTarget(payload.target, where)
break
case 'moveBlocks':
if (
!Array.isArray(payload.blockIndexes) ||
payload.blockIndexes.length === 0 ||
payload.blockIndexes.some((i) => !Number.isInteger(i) || Number(i) < 0)
) {
error = `${where}: blockIndexes must be a non-empty array of non-negative integers`
} else if (
!Number.isInteger(payload.afterBlockIndex) ||
Number(payload.afterBlockIndex) < -1
) {
error = `${where}: afterBlockIndex must be an integer ≥ -1`
}
break
case 'createParagraphBullets': {
error = validateTarget(payload.target, where)
const preset = payload.bulletPreset
if (
!error &&
preset !== undefined &&
(typeof preset !== 'string' || !/^(BULLET|NUMBERED)/.test(preset))
) {
error = `${where}: bulletPreset must start with BULLET or NUMBERED`
}
break
}
case 'deleteParagraphBullets':
error = validateTarget(payload.target, where)
break
case 'updateImageProperties': {
error = validateTarget(payload.target, where)
if (!error) {
if (!payload.properties || typeof payload.properties !== 'object') {
error = `${where}: missing properties`
} else if (!Array.isArray(payload.fields) || payload.fields.length === 0) {
error = `${where}: fields must not be empty`
} else {
const bad = payload.fields.filter(
(f) => !(IMAGE_PROP_KEYS as readonly string[]).includes(String(f)),
)
if (bad.length > 0) error = `${where}: unknown fields ${bad.map(String).join(', ')}`
}
}
break
}
case 'insertToc':
if (!Number.isInteger(payload.afterBlockIndex) || Number(payload.afterBlockIndex) < -1) {
error = `${where}: afterBlockIndex must be an integer ≥ -1`
}
break
}
if (error) return error
}
return null
}
// ---- target matching ----
interface TopBlock {
index: number
pos: number
node: PmDocNode
}
interface SelRange {
from: number
to: number
}
function topLevelBlocks(doc: PmDocNode): TopBlock[] {
const out: TopBlock[] = []
let index = 0
doc.forEach((node, offset) => {
out.push({ index, pos: offset, node })
index++
})
return out
}
function blockText(node: PmDocNode): string {
if (node.type.name === 'docProtected') {
return [node.attrs.label, node.attrs.previewText].filter(Boolean).join(' ')
}
return node.textContent
}
function matchTarget(doc: PmDocNode, target: Target, sel: SelRange): TopBlock[] {
return topLevelBlocks(doc).filter((b) => {
if (target.blockIndexes && !target.blockIndexes.includes(b.index)) return false
if (target.nodeType === 'image') {
if (b.node.type.name !== 'docProtected' || b.node.attrs.blockType !== 'image') return false
} else if (target.nodeType && b.node.type.name !== target.nodeType) {
return false
}
if (target.headingLevel !== undefined) {
if (b.node.type.name !== 'docHeading') return false
if (Number(b.node.attrs.level) !== target.headingLevel) return false
}
if (target.containsText) {
const text = blockText(b.node)
const hit =
target.matchCase === false
? text.toLowerCase().includes(target.containsText.toLowerCase())
: text.includes(target.containsText)
if (!hit) return false
}
if (target.scope === 'selection') {
const from = b.pos
const to = b.pos + b.node.nodeSize
const overlaps = to > sel.from && from < sel.to
const caretInside = sel.from === sel.to && sel.from >= from && sel.from <= to
if (!overlaps && !caretInside) return false
}
return true
})
}
// ---- executors (each reads tr.doc fresh, so sequential commands compose) ----
const BOOL_MARK_TYPES: Record<string, string> = {
bold: 'bold',
italic: 'italic',
underline: 'underline',
strike: 'strike',
}
const TEXT_ATTR_KEYS = ['color', 'highlight', 'sizeHalfPoints', 'font'] as const
function markChanged(tr: Transaction, pos: number): boolean {
const node = tr.doc.nodeAt(pos)
if (!node) return false
tr.setNodeMarkup(pos, undefined, { ...node.attrs, aiChanged: true })
return true
}
function runUpdateTextStyle(
tr: Transaction,
schema: Schema,
cmd: UpdateTextStyle,
sel: SelRange,
): CommandResult {
const matched = matchTarget(tr.doc, cmd.target, sel)
const boolFields = cmd.fields.filter((f) => f in BOOL_MARK_TYPES)
// patch applied onto each text node's existing docTextStyle attrs
const markPatch: Record<string, unknown> = {}
for (const f of cmd.fields) {
if ((TEXT_ATTR_KEYS as readonly string[]).includes(f)) {
markPatch[f] = cmd.style[f as (typeof TEXT_ATTR_KEYS)[number]] ?? null
} else if (f === 'baselineOffset') {
const value = cmd.style.baselineOffset
markPatch.vertAlign =
value === 'SUPERSCRIPT' ? 'superscript' : value === 'SUBSCRIPT' ? 'subscript' : null
}
}
const hasLink = cmd.fields.includes('link')
let changed = 0
let skippedProtected = 0
for (const b of matched) {
if (b.node.type.name === 'docProtected') {
skippedProtected++
continue
}
const before = b.node
const from = b.pos + 1
const to = from + b.node.content.size
if (from < to) {
for (const f of boolFields) {
const markType = schema.marks[BOOL_MARK_TYPES[f]]
if (cmd.style[f]) tr.addMark(from, to, markType.create())
else tr.removeMark(from, to, markType)
}
if (hasLink) {
if (cmd.style.link?.url) {
tr.addMark(from, to, schema.marks.link.create({ href: cmd.style.link.url, rId: null }))
} else {
tr.removeMark(from, to, schema.marks.link)
}
}
if (Object.keys(markPatch).length > 0) {
// merge per text node: only fields-listed attrs change, the rest survive
b.node.forEach((child, offset) => {
if (!child.isText) return
const childFrom = from + offset
const childTo = childFrom + child.nodeSize
const existing = child.marks.find((m) => m.type.name === 'docTextStyle')?.attrs ?? {}
const merged: Record<string, unknown> = {
color: existing.color ?? null,
sizeHalfPoints: existing.sizeHalfPoints ?? null,
font: existing.font ?? null,
highlight: existing.highlight ?? null,
vertAlign: existing.vertAlign ?? null,
...markPatch,
}
const empty = Object.values(merged).every((v) => v === null)
if (empty) tr.removeMark(childFrom, childTo, schema.marks.docTextStyle)
else tr.addMark(childFrom, childTo, schema.marks.docTextStyle.create(merged))
})
}
}
const after = tr.doc.nodeAt(b.pos)
if (after && !after.eq(before)) {
changed++
markChanged(tr, b.pos)
}
}
return { command: 'updateTextStyle', matched: matched.length, changed, skippedProtected }
}
function runUpdateParagraphStyle(
tr: Transaction,
cmd: UpdateParagraphStyle,
sel: SelRange,
): CommandResult {
const matched = matchTarget(tr.doc, cmd.target, sel)
let changed = 0
let skippedProtected = 0
for (const b of matched) {
if (b.node.type.name === 'docProtected') {
skippedProtected++
continue
}
const attrs: Record<string, unknown> = { ...b.node.attrs }
for (const f of cmd.fields) {
attrs[f] = cmd.style[f] ?? (f === 'pageBreakBefore' ? false : null)
}
const dirty = cmd.fields.some((f) => attrs[f] !== b.node.attrs[f])
if (!dirty) continue
tr.setNodeMarkup(b.pos, undefined, { ...attrs, aiChanged: true })
changed++
}
return { command: 'updateParagraphStyle', matched: matched.length, changed, skippedProtected }
}
function runSetHeadingLevel(
tr: Transaction,
schema: Schema,
cmd: SetHeadingLevel,
sel: SelRange,
): CommandResult {
const matched = matchTarget(tr.doc, cmd.target, sel)
let changed = 0
let skippedProtected = 0
for (const b of matched) {
if (b.node.type.name === 'docProtected') {
skippedProtected++
continue
}
const isHeading = b.node.type.name === 'docHeading'
if (cmd.level === 0 && b.node.type.name === 'docParagraph') continue
if (cmd.level > 0 && isHeading && Number(b.node.attrs.level) === cmd.level) continue
const type = cmd.level === 0 ? schema.nodes.docParagraph : schema.nodes.docHeading
// styleId is tied to the old block role; generate.ts picks heading styles by level
const attrs: Record<string, unknown> = {
...b.node.attrs,
styleId: null,
aiChanged: true,
}
if (cmd.level > 0) attrs.level = cmd.level
tr.setNodeMarkup(b.pos, type, attrs)
changed++
}
return { command: 'setHeadingLevel', matched: matched.length, changed, skippedProtected }
}
function runReplaceAllText(tr: Transaction, schema: Schema, cmd: ReplaceAllText): CommandResult {
const matchCase = cmd.matchCase !== false
const needle = matchCase ? cmd.containsText : cmd.containsText.toLowerCase()
const blocks = topLevelBlocks(tr.doc)
const replacements: Array<{ from: number; to: number; marks: PmDocNode['marks'] }> = []
const touchedIndexes = new Set<number>()
let skippedProtected = 0
for (const b of blocks) {
if (b.node.type.name === 'docProtected') {
if (blockText(b.node).includes(cmd.containsText)) skippedProtected++
continue
}
b.node.forEach((child, offset) => {
if (!child.isText || !child.text) return
const hay = matchCase ? child.text : child.text.toLowerCase()
let at = hay.indexOf(needle)
while (at !== -1) {
const from = b.pos + 1 + offset + at
replacements.push({ from, to: from + needle.length, marks: child.marks })
touchedIndexes.add(b.index)
at = hay.indexOf(needle, at + needle.length)
}
})
}
// apply back-to-front so earlier positions stay valid
for (const r of [...replacements].reverse()) {
if (cmd.replaceText) tr.replaceWith(r.from, r.to, schema.text(cmd.replaceText, r.marks))
else tr.delete(r.from, r.to)
}
if (touchedIndexes.size > 0) {
for (const b of topLevelBlocks(tr.doc)) {
if (touchedIndexes.has(b.index)) markChanged(tr, b.pos)
}
}
return {
command: 'replaceAllText',
matched: touchedIndexes.size,
changed: touchedIndexes.size,
skippedProtected,
detail: t('aiCmdReplacedCount', { count: replacements.length }),
}
}
function runDeleteBlocks(
tr: Transaction,
schema: Schema,
cmd: DeleteBlocks,
sel: SelRange,
): CommandResult {
const blocks = topLevelBlocks(tr.doc)
const matched = matchTarget(tr.doc, cmd.target, sel)
if (matched.length === blocks.length && matched.length > 0) {
// doc requires block+: deleting everything leaves one empty paragraph
tr.replaceWith(0, tr.doc.content.size, schema.nodes.docParagraph.create())
return {
command: 'deleteBlocks',
matched: matched.length,
changed: matched.length,
skippedProtected: 0,
}
}
for (const b of [...matched].sort((a, z) => z.pos - a.pos)) {
tr.delete(b.pos, b.pos + b.node.nodeSize)
}
return {
command: 'deleteBlocks',
matched: matched.length,
changed: matched.length,
skippedProtected: 0,
}
}
function runMoveBlocks(tr: Transaction, cmd: MoveBlocks): CommandResult {
const blocks = topLevelBlocks(tr.doc)
const movedSet = new Set(cmd.blockIndexes)
const outOfRange = cmd.blockIndexes.filter((i) => i >= blocks.length)
if (outOfRange.length > 0)
throw new Error(`moveBlocks: block indexes out of range ${outOfRange.join(', ')}`)
if (cmd.afterBlockIndex >= blocks.length) {
throw new Error(`moveBlocks: afterBlockIndex out of range ${cmd.afterBlockIndex}`)
}
if (movedSet.has(cmd.afterBlockIndex)) {
throw new Error('moveBlocks: afterBlockIndex must not be one of the moved blocks')
}
// moved blocks keep document order; aiChanged marks the landing highlight
const moved = [...movedSet]
.sort((a, z) => a - z)
.map((i) => {
const node = blocks[i].node
if (node.type.name === 'docProtected') return node
return node.type.create({ ...node.attrs, aiChanged: true }, node.content, node.marks)
})
const rest = blocks.filter((b) => !movedSet.has(b.index))
let insertAt = 0
if (cmd.afterBlockIndex >= 0) {
insertAt = rest.findIndex((b) => b.index === cmd.afterBlockIndex) + 1
}
const children = [
...rest.slice(0, insertAt).map((b) => b.node),
...moved,
...rest.slice(insertAt).map((b) => b.node),
]
tr.replaceWith(0, tr.doc.content.size, children)
return {
command: 'moveBlocks',
matched: moved.length,
changed: moved.length,
skippedProtected: 0,
}
}
function runCreateParagraphBullets(
tr: Transaction,
schema: Schema,
cmd: CreateParagraphBullets,
sel: SelRange,
context: CommandContext,
): CommandResult {
const matched = matchTarget(tr.doc, cmd.target, sel)
const kind = cmd.bulletPreset?.startsWith('NUMBERED') ? 'ordered' : 'bullet'
const numId = context.numIds?.[kind] ?? null
let changed = 0
let skippedProtected = 0
for (const b of matched) {
if (b.node.type.name === 'docProtected') {
skippedProtected++
continue
}
// headings keep their role; converting them to list items would drop the level
if (b.node.type.name === 'docHeading') continue
if (b.node.type.name === 'docListItem') {
if (b.node.attrs.kind === kind) continue
tr.setNodeMarkup(b.pos, undefined, {
...b.node.attrs,
kind,
numId: numId ?? b.node.attrs.numId,
aiChanged: true,
})
changed++
continue
}
tr.setNodeMarkup(b.pos, schema.nodes.docListItem, {
...b.node.attrs,
styleId: null,
kind,
numId,
ilvl: 0,
aiChanged: true,
})
changed++
}
return { command: 'createParagraphBullets', matched: matched.length, changed, skippedProtected }
}
function runDeleteParagraphBullets(
tr: Transaction,
schema: Schema,
cmd: DeleteParagraphBullets,
sel: SelRange,
): CommandResult {
const matched = matchTarget(tr.doc, cmd.target, sel)
let changed = 0
let skippedProtected = 0
for (const b of matched) {
if (b.node.type.name === 'docProtected') {
skippedProtected++
continue
}
if (b.node.type.name !== 'docListItem') continue
tr.setNodeMarkup(b.pos, schema.nodes.docParagraph, {
...b.node.attrs,
styleId: null,
aiChanged: true,
})
changed++
}
return { command: 'deleteParagraphBullets', matched: matched.length, changed, skippedProtected }
}
function runUpdateImageProperties(
tr: Transaction,
cmd: UpdateImageProperties,
sel: SelRange,
): CommandResult {
const matched = matchTarget(tr.doc, cmd.target, sel)
let changed = 0
for (const b of matched) {
if (b.node.type.name !== 'docProtected' || b.node.attrs.blockType !== 'image') continue
const attrs: Record<string, unknown> = { ...b.node.attrs }
if (cmd.fields.includes('align')) attrs.imageAlign = cmd.properties.align ?? null
const wantW = cmd.fields.includes('widthPx') ? (cmd.properties.widthPx ?? null) : null
const wantH = cmd.fields.includes('heightPx') ? (cmd.properties.heightPx ?? null) : null
const curW = Number(b.node.attrs.imageWidthPx) || null
const curH = Number(b.node.attrs.imageHeightPx) || null
if (wantW && wantH) {
attrs.imageWidthPx = Math.round(wantW)
attrs.imageHeightPx = Math.round(wantH)
} else if (wantW && curW && curH) {
attrs.imageWidthPx = Math.round(wantW)
attrs.imageHeightPx = Math.round((wantW * curH) / curW)
} else if (wantH && curW && curH) {
attrs.imageHeightPx = Math.round(wantH)
attrs.imageWidthPx = Math.round((wantH * curW) / curH)
}
// save-side patching needs both dimensions; a lone dimension with unknown
// original size cannot be scaled and is skipped
const dirty = Object.keys(attrs).some((k) => attrs[k] !== b.node.attrs[k])
if (!dirty) continue
tr.setNodeMarkup(b.pos, undefined, attrs)
changed++
}
return { command: 'updateImageProperties', matched: matched.length, changed, skippedProtected: 0 }
}
function runInsertToc(tr: Transaction, schema: Schema, cmd: InsertToc): CommandResult {
const blocks = topLevelBlocks(tr.doc)
const entries: TocEntry[] = []
for (const b of blocks) {
if (b.node.type.name === 'docHeading' && b.node.textContent.trim()) {
entries.push({ level: Number(b.node.attrs.level) || 1, text: b.node.textContent })
}
}
if (entries.length === 0) {
throw new Error(
'insertToc: the document has no headings (levels 1-6), cannot generate a table of contents',
)
}
if (cmd.afterBlockIndex >= blocks.length) {
throw new Error(`insertToc: afterBlockIndex out of range ${cmd.afterBlockIndex}`)
}
// one protected block per TOC line (same shape as the ribbon's TOC button);
// the begin fldChar is dirty so Word recalculates page numbers on open
const nodes = generateTocFieldXml(entries).map((xml, i) =>
schema.nodes.docProtected.create({
docxIndex: null,
blockType: 'passthrough',
label: 'TOC field',
genXml: xml,
fieldDisplay: { kind: 'tocLine', left: entries[i].text, right: '', level: entries[i].level },
}),
)
const pos =
cmd.afterBlockIndex === -1
? 0
: blocks[cmd.afterBlockIndex].pos + blocks[cmd.afterBlockIndex].node.nodeSize
tr.insert(pos, nodes)
return {
command: 'insertToc',
matched: entries.length,
changed: nodes.length,
skippedProtected: 0,
}
}
// ---- entry point ----
function summarize(results: CommandResult[]): string {
const total = results.reduce((sum, r) => sum + r.changed, 0)
if (total === 0) {
const skipped = results.reduce((sum, r) => sum + r.skippedProtected, 0)
return skipped > 0 ? t('aiCmdNoneSkipped', { count: skipped }) : t('aiCmdNone')
}
const parts = results.map((r) => {
let part: string
switch (r.command) {
case 'updateTextStyle':
part = t('aiCmdTextStyle', { count: r.changed })
break
case 'updateParagraphStyle':
part = t('aiCmdParaStyle', { count: r.changed })
break
case 'setHeadingLevel':
part = t('aiCmdHeading', { count: r.changed })
break
case 'replaceAllText':
part = t('aiCmdReplaceAll', {
count: r.changed,
detail: r.detail ?? t('aiCmdReplaceFallback'),
})
break
case 'deleteBlocks':
part = t('aiCmdDeleted', { count: r.changed })
break
case 'moveBlocks':
part = t('aiCmdMoved', { count: r.changed })
break
case 'createParagraphBullets':
part = t('aiCmdToList', { count: r.changed })
break
case 'deleteParagraphBullets':
part = t('aiCmdToBody', { count: r.changed })
break
case 'updateImageProperties':
part = t('aiCmdImages', { count: r.changed })
break
case 'insertToc':
part = t('aiCmdToc', { count: r.matched })
break
default:
part = `${r.command}: ${r.changed}`
}
if (r.skippedProtected > 0) part += t('aiCmdSkipped', { count: r.skippedProtected })
return part
})
return parts.join(';')
}
export function executeCommands(
editor: Editor,
envelope: CommandEnvelope,
context: CommandContext = {},
): ExecuteOutcome {
const validationError = validateEnvelope(envelope)
if (validationError) return { ok: false, results: [], summary: '', error: validationError }
const tr = editor.state.tr
const schema = editor.schema
const selection = editor.state.selection
const results: CommandResult[] = []
try {
for (const command of envelope.commands) {
// selection positions mapped through the steps applied so far
const sel: SelRange = {
from: tr.mapping.map(selection.from),
to: tr.mapping.map(selection.to),
}
if ('updateTextStyle' in command) {
results.push(runUpdateTextStyle(tr, schema, command.updateTextStyle, sel))
} else if ('updateParagraphStyle' in command) {
results.push(runUpdateParagraphStyle(tr, command.updateParagraphStyle, sel))
} else if ('setHeadingLevel' in command) {
results.push(runSetHeadingLevel(tr, schema, command.setHeadingLevel, sel))
} else if ('replaceAllText' in command) {
results.push(runReplaceAllText(tr, schema, command.replaceAllText))
} else if ('deleteBlocks' in command) {
results.push(runDeleteBlocks(tr, schema, command.deleteBlocks, sel))
} else if ('createParagraphBullets' in command) {
results.push(
runCreateParagraphBullets(tr, schema, command.createParagraphBullets, sel, context),
)
} else if ('deleteParagraphBullets' in command) {
results.push(runDeleteParagraphBullets(tr, schema, command.deleteParagraphBullets, sel))
} else if ('updateImageProperties' in command) {
results.push(runUpdateImageProperties(tr, command.updateImageProperties, sel))
} else if ('insertToc' in command) {
results.push(runInsertToc(tr, schema, command.insertToc))
} else {
results.push(runMoveBlocks(tr, command.moveBlocks))
}
}
} catch (e) {
return {
ok: false,
results: [],
summary: '',
error: e instanceof Error ? e.message : String(e),
}
}
if (tr.steps.length > 0) {
// route through the TrackChanges recorder so AI format/text edits become
// reviewable revisions under the AI author (same pipeline as manual edits)
const storage = editor.storage.trackChanges as { enabled: boolean; author: string } | undefined
if (context.track && storage) {
const prev = { enabled: storage.enabled, author: storage.author }
storage.enabled = true
storage.author = context.track.author
try {
editor.view.dispatch(tr)
} finally {
storage.enabled = prev.enabled
storage.author = prev.author
}
} else {
editor.view.dispatch(tr)
}
}
return { ok: true, results, summary: summarize(results) }
}
@@ -0,0 +1,4 @@
export const DOCS_AGENT_MAX_TURNS = 50
export const DOCS_CONTINUE_INSTRUCTION =
'Continue the current task using the existing conversation and document state. Finish only the outstanding work. Do not repeat edits or steps that are already complete.'
+23
View File
@@ -0,0 +1,23 @@
import type { Editor } from '@tiptap/core'
import type { AgentSkill } from '@genoffice/agent-core'
import { AGENT_SYSTEM_PROMPT, buildDocContext, type AiTrack, type NumIds } from './protocol'
import { AGENT_TOOLS, executeTool } from './tools'
/**
* The docx capability as an AgentSkill: document skeleton context, the five
* document tools, and the local executor. Future apps register their own
* skills (Excel / PPT) against the same agent loop.
*/
export function createDocsSkill(
getEditor: () => Editor,
getNumIds: () => NumIds,
getTrack?: () => AiTrack | undefined,
): AgentSkill {
return {
id: 'docx',
systemPrompt: AGENT_SYSTEM_PROMPT,
tools: AGENT_TOOLS,
buildContext: () => buildDocContext(getEditor()),
executeTool: (call) => executeTool(getEditor(), call, getNumIds(), getTrack?.()),
}
}
+99
View File
@@ -0,0 +1,99 @@
import type { AgentSkill } from '@genoffice/agent-core'
import type { AttachmentMeta } from '../../shared/ipc'
import { ATTACHMENT_IMAGE_EXTS } from '../../shared/ipc'
import { t } from '../i18n/locale'
/**
* Chat-attachment capability as an AgentSkill: the per-turn context lists the
* attached local files, and read_attachment pages through their extracted
* text (parsing happens in the main process; files never leave the machine).
*/
const READ_CHUNK_CHARS = 24_000
const FILES_SYSTEM_PROMPT = `## Attachments
The user may attach local files to the conversation (see the "attachment list" in each turn's context).
- When the user's request involves attachment content, read it with read_attachment first, then answer or write; do not guess content from file names.
- Long files are read in pages: the result reports the total character count and the current range; to continue, set offset to the end position of the previous slice.
- Image attachments (png/jpg/gif/webp) are already sent as images with the user message — just look at them; read_attachment is only for text-like attachments.
- Do not call read_attachment when there are no attachments or they are unrelated to the request.`
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes}B`
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)}KB`
return `${(bytes / 1024 / 1024).toFixed(1)}MB`
}
export function createFilesSkill(getAttachments: () => AttachmentMeta[]): AgentSkill {
return {
id: 'files',
systemPrompt: FILES_SYSTEM_PROMPT,
tools: [
{
name: 'read_attachment',
description:
'Read the text content of an attachment (parsed locally). Long files are paged: read offset=0 first, then decide whether to continue based on the returned total character count.',
inputSchema: {
type: 'object',
properties: {
index: {
type: 'integer',
description: 'attachment index (0-based, see the attachment list)',
},
offset: { type: 'integer', description: 'start character position, default 0' },
},
required: ['index'],
},
},
],
buildContext: () => {
const list = getAttachments()
if (list.length === 0) return ''
const lines = list.map((a, i) => `${i} | ${a.name} | .${a.ext} | ${formatSize(a.sizeBytes)}`)
return `Attachment list (index | file name | type | size):\n${lines.join('\n')}`
},
executeTool: async (call) => {
if (call.name !== 'read_attachment') {
return { output: `unknown tool: ${call.name}`, isError: true, summary: call.name }
}
const list = getAttachments()
const index = Number(call.input.index)
const att = Number.isInteger(index) ? list[index] : undefined
if (!att) {
return {
output: 'invalid attachment index (see the attachment list)',
isError: true,
summary: t('aiSumReadAttachment'),
}
}
// no text extraction for images: already provided as a multimodal image with the user message on send
if (ATTACHMENT_IMAGE_EXTS.has(att.ext)) {
return {
output: `${att.name} is an image attachment already sent as an image with the user message; just look at the image in the message, no text to read.`,
mutated: false,
summary: t('aiSumImageAttachment', { name: att.name }),
}
}
const offset = Math.max(0, Number(call.input.offset) || 0)
const result = await window.desktop.readAttachment(att.path, offset, READ_CHUNK_CHARS)
if (!result.ok) {
return {
output: result.error ?? 'read failed',
isError: true,
summary: t('aiSumRead', { name: att.name }),
}
}
const end = (result.offset ?? 0) + (result.text?.length ?? 0)
const header = `File ${att.name}, total characters ${result.totalChars}, this slice ${result.offset}-${end}${
end < (result.totalChars ?? 0)
? ' (not finished, continue with offset=' + end + ')'
: ' (end of file)'
}`
return {
output: `${header}\n---\n${result.text ?? ''}`,
mutated: false,
summary: t('aiSumReadAttachmentName', { name: att.name }),
}
},
}
}
+849
View File
@@ -0,0 +1,849 @@
import type { Editor } from '@tiptap/core'
import type { Node as ProseMirrorNode } from '@tiptap/pm/model'
import {
TABLE_HEADER_FILL,
type Block,
type TableCell,
type TableModel,
} from '@genoffice/docx-engine'
import { pmTableToModel, tableModelToPmNode, type PmMark, type PmNode } from '../editor/convert'
import { equationBlockJson, inlineEquationNodeJson } from '../editor/equation'
import { TRACK_IGNORE } from '../editor/revisions'
import { countWords } from '../word-count'
/**
* Agent protocol: the model runs a multi-turn tool-use loop — it reads the document skeleton
* (block list with numbered addressing), reads full block content on demand,
* and mutates the document exclusively through tools (tools.ts). Questions
* are answered directly in chat without touching the document. Context size
* stays bounded: previews are clipped and full content is pulled lazily.
*/
// ---- context budgets (characters, ≈4 chars/token) ----
const SELECTION_MAX_CHARS = 24_000
const DOC_CONTEXT_MAX_CHARS = 8_000
const PREVIEW_MAX_CHARS = 60
const PREVIEW_TIGHT_CHARS = 20
/**
* Guide for the apply_commands tool: format,
* structure and batch operations travel as a batchUpdate-style JSON envelope
* executed deterministically by commands.ts.
*/
export const COMMANDS_GUIDE = [
"The command format mimics documents.batchUpdate of the Google Docs API: each command is a single-key object; the fields array has the same semantics as Google's FieldMask — only the listed fields are updated, everything not listed is left untouched. Differences from Google: target uses semantic addressing (node type / text containment / block index), colors are 6-digit hex (no #), lengths are in twips, font sizes are in half-points.",
'',
'The commands input is an array of commands executed in order. Command schema (TypeScript):',
'```',
'interface Target { // all conditions are ANDed; provide at least one',
" nodeType?: 'docHeading' | 'docParagraph' | 'docListItem' | 'image' // image = image block",
" headingLevel?: number // only together with nodeType: 'docHeading'",
' containsText?: string // block plain text contains this substring',
' matchCase?: boolean // defaults to true',
' blockIndexes?: number[] // indexes from the "document block list"',
" scope?: 'selection' | 'document' // selection = only blocks covered by the current selection",
'}',
"{ updateTextStyle: { target, style: { color?, highlight?, sizeHalfPoints?, font?, bold?, italic?, underline?, strike?, baselineOffset?: 'SUPERSCRIPT'|'SUBSCRIPT'|'NONE', link?: {url}|null }, fields: string[] } } // value null = clear that property",
"{ updateParagraphStyle: { target, style: { align?: 'left'|'center'|'right'|'justify', lineSpacing?, indentLeft?, indentRight?, indentFirstLine?, spaceBefore?, spaceAfter?, pageBreakBefore?, shadingFill?, borders?: subset of 'tblr'|null }, fields: string[] } } // indentFirstLine positive = first-line indent, negative = hanging; a two-character indent for CJK text ≈ font size in pt × 40 twips",
'{ setHeadingLevel: { target, level: 0-6 } } // 0 = demote to body paragraph',
'{ replaceAllText: { containsText, replaceText, matchCase? } }',
'{ deleteBlocks: { target } }',
'{ moveBlocks: { blockIndexes: number[], afterBlockIndex: number } } // -1 = start of document',
'{ createParagraphBullets: { target, bulletPreset? } } // paragraphs to list; BULLET_* prefix = unordered, NUMBERED_* = ordered (default unordered); heading blocks are not converted',
'{ deleteParagraphBullets: { target } } // list items back to body paragraphs',
"{ updateImageProperties: { target, properties: { widthPx?, heightPx?, align?: 'left'|'center'|'right' }, fields } } // image blocks only; giving one dimension scales proportionally",
'{ insertToc: { afterBlockIndex } } // insert a TOC field after that block index (-1 = start of document); entries come from current headings, Word computes page numbers on open; fails if the document has no headings',
'```',
'',
'Common recipes:',
'- "Make all headings red" → commands: [{"updateTextStyle":{"target":{"nodeType":"docHeading"},"style":{"color":"FF0000"},"fields":["color"]}}]',
'- "1.5 line spacing for the whole document" → one updateParagraphStyle each for docParagraph / docHeading / docListItem, style {"lineSpacing":1.5}, fields ["lineSpacing"]',
'- "Demote the \'Risk Notice\' level-2 heading to level 3" → commands: [{"setHeadingLevel":{"target":{"nodeType":"docHeading","headingLevel":2,"containsText":"Risk Notice"},"level":3}}]',
'- "Delete blocks 3 to 5" → commands: [{"deleteBlocks":{"target":{"blockIndexes":[3,4,5]}}}]',
'- "Turn blocks 2 to 4 into a numbered list" → commands: [{"createParagraphBullets":{"target":{"blockIndexes":[2,3,4]},"bulletPreset":"NUMBERED_DECIMAL_ALPHA_ROMAN"}}]',
'- "Center all images" → commands: [{"updateImageProperties":{"target":{"nodeType":"image"},"properties":{"align":"center"},"fields":["align"]}}]',
'- "Two-character first-line indent for the whole document" (11 pt font) → one updateParagraphStyle for docParagraph, style {"indentFirstLine":440}, fields ["indentFirstLine"]',
'- "Insert a table of contents at the beginning" → commands: [{"insertToc":{"afterBlockIndex":-1}}]; if the user wants the TOC on its own page, also apply updateParagraphStyle to the first body block after the TOC with style {"pageBreakBefore":true}, fields ["pageBreakBefore"]',
'- Cover page recipe: use insert_content to insert one paragraph each for title/subtitle/date at the start of the document, then updateTextStyle to enlarge the title font (e.g. {"sizeHalfPoints":72}, fields ["sizeHalfPoints"]), updateParagraphStyle to center everything and give the title {"spaceBefore":4800}, and finally set {"pageBreakBefore":true} on the first body block after the cover',
'',
'Discipline:',
'- Read the "document block list" before issuing commands; anything like "paragraph N / a certain section" must be addressed with block indexes from the list — never guess;',
'- Put only the properties the user explicitly asked for into fields;',
'- Protected blocks such as images cannot be modified with style commands (they are skipped); to change table content, use read_blocks to get the <table> and rewrite it wholesale with replace_blocks.',
'',
'Known error cases (must avoid):',
'BC-1 Putting properties the user did not ask for into fields, wiping existing formatting by mistake;',
'BC-2 A "whole document" formatting operation only changed docParagraph and missed docHeading/docListItem;',
'BC-3 Addressing by word/character position (no such addressing exists); use block indexes or text containment instead;',
'BC-4 Using replaceAllText sentence by sentence for rewrites such as translation/abbreviation; use the replace_blocks tool instead;',
].join('\n')
const HTML_RULES = [
'The html tool input is a restricted HTML fragment. Rules:',
'- Only these tags are allowed: h1 h2 h3 h4 h5 h6 p ul ol li strong em u s a br table thead tbody tr th td pre code blockquote',
'- Tables: use <th> for the first (header) row; cells contain plain text only (<br> may split lines); nested tables / merged cells are not supported; once inserted the table is protected as a whole, only cell text remains editable',
'- Use <pre> for code samples (monospace font + shading, line breaks preserved); use <blockquote> for quotations (indent + left bar)',
'- Use <formula>LaTeX</formula> for math (produces native Word equations): as a top-level block it becomes its own centered paragraph; placed inside <p>/<li>/<h*> text it is an inline formula flowing with the text, e.g. <p>From <formula>E = mc^2</formula> we know…</p>; supports the common subset of \\frac \\sqrt super/subscripts \\sum \\int \\lim matrix environments Greek letters etc., the align environment is not supported; invalid LaTeX fails the whole call — fix and retry',
'- Do not include <html>/<body>, markdown code fences, or explanatory text',
'- Organize long content into sections with h2/h3 (unless the user only wants a single paragraph)',
'- Keep the same language as the original document / user instruction, unless translation is requested',
].join('\n')
/**
* Agent system prompt: document-first, intent resolution, act via tools,
* answer in chat.
*/
export const AGENT_SYSTEM_PROMPT = [
'You are the document assistant built into the local document editor GenOffice Docs. You read and modify the currently open document exclusively through tools; there is no other modification channel.',
'',
'# Intent resolution',
'- The user asks to modify/generate/translate/format → call the appropriate tools, then summarize what was done in one or two sentences;',
'- The user is asking a question or consulting (word count, structure, "what is this about", writing advice, etc.) → answer directly in plain text without calling modification tools;',
'- For statistics such as word count or block count, quote the "full-text stats" from the "document block list" directly — do not count yourself;',
'- When intent is unclear, read the document first (the block list in the message, and read_blocks for full text if needed), then decide.',
'',
'# Tool usage',
'- Every user message carries the latest "document block list" (index|type|content preview; previews may be truncated); after modifications, call get_document_context if you need the latest state;',
'- When a list preview is truncated, read the full content with read_blocks before rewriting; never rewrite based on a truncated preview;',
'- Content changes: use insert_content for new content, and replace_blocks to rewrite/replace existing blocks (pass a block index range and the new HTML);',
'- Formatting, structure, and batch operations (color/font size/line spacing/alignment/indent/heading level/find & replace/delete/move/list conversion) go through apply_commands — do not rewrite whole blocks with replace_blocks;',
'- When the user has text selected, the message includes the selection block indexes and content; rewrite-style requests apply to the selection by default;',
'- Web search: use web_search when you need up-to-date information/data/fact checking; search before writing about uncertain facts — do not fabricate;',
'- Illustrations: when the user wants pictures, first image_search (English keywords work better) → pick a suitable result → insert_image with its imageUrl to insert into the document;',
'- Charts: use insert_chart for data visualization (bar/line/pie; saved as native Word charts); use edit_chart to change the data of an existing chart block in the block list; data must be real, from the document or search results;',
'- One reply may chain multiple tools; after everything is done, always finish with a short plain-text summary.',
'',
'# HTML fragment rules',
HTML_RULES,
'',
'# apply_commands command guide',
COMMANDS_GUIDE,
].join('\n')
export { countWords }
// ---- selection scope ----
export interface SelectionScope {
/** top-level child indexes covered by the selection (inclusive) */
startIndex: number
endIndex: number
/** true when the user has an actual range selected (not just a caret) */
isRange: boolean
}
export function getSelectionScope(editor: Editor): SelectionScope {
const { from, to, empty } = editor.state.selection
const doc = editor.state.doc
let startIndex = -1
let endIndex = -1
let index = 0
doc.forEach((node, offset) => {
const nodeFrom = offset
const nodeTo = offset + node.nodeSize
if (nodeTo > from && nodeFrom < to) {
if (startIndex === -1) startIndex = index
endIndex = index
} else if (empty && from >= nodeFrom && from <= nodeTo && startIndex === -1) {
startIndex = index
endIndex = index
}
index++
})
if (startIndex === -1) {
startIndex = doc.childCount - 1
endIndex = doc.childCount - 1
}
return { startIndex, endIndex, isRange: !empty }
}
/** ProseMirror positions of a top-level child index range */
export function blockRangePositions(
editor: Editor,
startIndex: number,
endIndex: number,
): { from: number; to: number } {
const doc = editor.state.doc
let from = 0
let to = 0
let index = 0
doc.forEach((node, offset) => {
if (index === startIndex) from = offset
if (index === endIndex) to = offset + node.nodeSize
index++
})
return { from, to }
}
// ---- blocks -> restricted HTML ----
function escapeHtml(text: string): string {
return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
}
function inlineToHtml(content: PmNode[] | undefined): string {
if (!content) return ''
let html = ''
for (const node of content) {
if (node.type === 'hardBreak') {
html += '<br>'
continue
}
if (node.type === 'docInlineMath') {
// editor-created formulas round-trip as LaTeX; parsed-from-docx ones
// degrade to the flat token strip (structure lost if the model rewrites)
const source = String(node.attrs?.latex ?? '') || String(node.attrs?.text ?? '')
if (source) html += `<formula>${escapeHtml(source)}</formula>`
continue
}
if (node.type === 'docRuby') {
html += escapeHtml(String(node.attrs?.base ?? ''))
continue
}
if (node.type !== 'text' || !node.text) continue
let text = escapeHtml(node.text)
const marks = node.marks ?? []
const has = (type: string) => marks.some((m: PmMark) => m.type === type)
if (has('bold')) text = `<strong>${text}</strong>`
if (has('italic')) text = `<em>${text}</em>`
if (has('underline')) text = `<u>${text}</u>`
if (has('strike')) text = `<s>${text}</s>`
const link = marks.find((m: PmMark) => m.type === 'link')
if (link?.attrs?.href) text = `<a href="${escapeHtml(String(link.attrs.href))}">${text}</a>`
html += text
}
return html
}
/** plain text of a paragraph's inline content, hard breaks as newlines */
function inlineToPlainText(content: PmNode[] | undefined): string {
if (!content) return ''
return content
.map((n) => (n.type === 'hardBreak' ? '\n' : n.type === 'text' ? (n.text ?? '') : ''))
.join('')
}
/** paragraph carries the <pre> preset (see CODE_BLOCK_PRESET) */
function isCodeParagraph(node: PmNode): boolean {
return (
node.attrs?.shadingFill === CODE_BLOCK_PRESET.shadingFill &&
node.attrs?.borders === CODE_BLOCK_PRESET.borders
)
}
/** paragraph carries the <blockquote> preset (see QUOTE_BLOCK_PRESET) */
function isQuoteParagraph(node: PmNode): boolean {
return node.attrs?.borders === QUOTE_BLOCK_PRESET.borders && Number(node.attrs?.indentLeft) > 0
}
/** table block -> restricted <table> HTML so the model can read and rewrite it */
function tableToHtml(table: TableModel): string {
const headerRow =
table.rows.length > 1 && table.rows[0].every((c) => c.bold || c.fill !== undefined)
const rows = table.rows.map((row, r) => {
const tag = headerRow && r === 0 ? 'th' : 'td'
const cells = row
.map((cell) => `<${tag}>${cell.paras.map(escapeHtml).join('<br>')}</${tag}>`)
.join('')
return `<tr>${cells}</tr>`
})
return `<table>${rows.join('')}</table>`
}
/**
* Serialize top-level nodes [startIndex, endIndex] into restricted HTML.
* Consecutive list items of the same kind are grouped into ul/ol.
*/
export function serializeRangeToHtml(editor: Editor, startIndex: number, endIndex: number): string {
const json = editor.getJSON() as PmNode
const children = (json.content ?? []).slice(startIndex, endIndex + 1)
const parts: string[] = []
let listBuffer: { kind: string; items: string[] } | null = null
const flushList = () => {
if (!listBuffer) return
const tag = listBuffer.kind === 'ordered' ? 'ol' : 'ul'
parts.push(`<${tag}>${listBuffer.items.join('')}</${tag}>`)
listBuffer = null
}
for (const node of children) {
if (node.type === 'docHeading') {
flushList()
const level = Math.min(Math.max(Number(node.attrs?.level) || 1, 1), 6)
parts.push(`<h${level}>${inlineToHtml(node.content)}</h${level}>`)
} else if (node.type === 'docListItem') {
const kind = (node.attrs?.kind as string) ?? 'bullet'
if (!listBuffer || listBuffer.kind !== kind) {
flushList()
listBuffer = { kind, items: [] }
}
listBuffer.items.push(`<li>${inlineToHtml(node.content)}</li>`)
} else if (node.type === 'docParagraph') {
flushList()
if (isCodeParagraph(node)) {
parts.push(`<pre>${escapeHtml(inlineToPlainText(node.content))}</pre>`)
} else if (isQuoteParagraph(node)) {
parts.push(`<blockquote>${inlineToHtml(node.content)}</blockquote>`)
} else {
parts.push(`<p>${inlineToHtml(node.content)}</p>`)
}
} else if (node.type === 'docTable') {
flushList()
parts.push(tableToHtml(pmTableToModel(node)))
} else {
flushList()
const formula = node.attrs?.formulaDisplay as { tokens?: string[]; latex?: string } | null
if (formula?.latex) {
// full LaTeX recovered: the model can rewrite the formula losslessly
parts.push(`<formula>${escapeHtml(formula.latex)}</formula>`)
} else if (formula?.tokens?.length) {
parts.push(
`<p>[Protected formula: ${escapeHtml(formula.tokens.join(' '))}, structure is read-only, kept as is]</p>`,
)
} else {
const label = String(node.attrs?.label ?? node.attrs?.blockType ?? 'content')
parts.push(`<p>[Protected content: ${escapeHtml(label)}, kept as is]</p>`)
}
}
}
flushList()
return parts.join('\n')
}
// ---- document context + layered request builders ----
interface ContextEntry {
index: number
type: string
preview: string
isHeading: boolean
}
/**
* Numbered structure snapshot for command-mode addressing: one line per
* top-level block. Block numbers MUST equal the live PM doc order at execution
* time, so this is rebuilt per request and never cached.
*/
export function buildDocumentContext(editor: Editor): string {
const entries: ContextEntry[] = []
let index = 0
editor.state.doc.forEach((node) => {
let type: string
let preview: string
let isHeading = false
if (node.type.name === 'docHeading') {
type = `h${Math.min(Math.max(Number(node.attrs.level) || 1, 1), 6)}`
preview = node.textContent
isHeading = true
} else if (node.type.name === 'docListItem') {
type = 'li'
preview = node.textContent
} else if (node.type.name === 'docTable') {
type = 'table'
preview = node.textContent
} else if (node.type.name === 'docProtected') {
type = String(node.attrs.label || node.attrs.blockType || 'protected')
preview = String(node.attrs.previewText ?? '')
} else {
type = 'p'
preview = node.textContent
}
entries.push({ index, type, preview: preview.replace(/\s+/g, ' ').trim(), isHeading })
index++
})
const render = (bodyMax: number) =>
entries.map(
(e) => `${e.index}|${e.type}|${clip(e.preview, e.isHeading ? PREVIEW_MAX_CHARS : bodyMax)}`,
)
let lines = render(PREVIEW_MAX_CHARS)
if (lines.join('\n').length > DOC_CONTEXT_MAX_CHARS) lines = render(PREVIEW_TIGHT_CHARS)
if (lines.join('\n').length > DOC_CONTEXT_MAX_CHARS) {
// keep both ends (numbering must stay verifiable), elide the middle
let dropStart = Math.floor(lines.length / 3)
let dropEnd = lines.length - Math.floor(lines.length / 3)
while (
dropStart > 1 &&
dropEnd < lines.length - 1 &&
[...lines.slice(0, dropStart), ...lines.slice(dropEnd)].join('\n').length >
DOC_CONTEXT_MAX_CHARS
) {
dropStart = Math.max(1, dropStart - 10)
dropEnd = Math.min(lines.length - 1, dropEnd + 10)
}
lines = [
...lines.slice(0, dropStart),
`…(${dropEnd - dropStart} blocks elided here; numbering is continuous, extrapolate indexes if needed)…`,
...lines.slice(dropEnd),
]
}
const scope = getSelectionScope(editor)
const selLine = scope.isRange
? scope.startIndex === scope.endIndex
? `Current selection: block ${scope.startIndex}`
: `Current selection: blocks ${scope.startIndex}-${scope.endIndex}`
: `No selection; cursor is in block ${scope.startIndex}`
// authoritative stats for answer mode (previews above may be clipped)
const fullText = editor.state.doc.textContent
const statsLine = `Full-text stats: words ${countWords(fullText)}, characters (no spaces) ${
fullText.replace(/\s/g, '').length
}, characters (with spaces) ${fullText.length}`
return [
`The document has ${entries.length} blocks, listed below (index|type|content preview):`,
...lines,
statsLine,
selLine,
].join('\n')
}
function clip(text: string, max: number): string {
return text.length > max ? text.slice(0, max) + '…' : text
}
/**
* Per-turn context: fresh document skeleton + selection fragment injected
* as a selection chip.
*/
export function buildDocContext(editor: Editor): string {
const isEmptyDoc = editor.state.doc.textContent.trim() === ''
const scope = getSelectionScope(editor)
const selectionHtml = scope.isRange
? clip(serializeRangeToHtml(editor, scope.startIndex, scope.endIndex), SELECTION_MAX_CHARS)
: ''
return [
isEmptyDoc
? 'The document is currently blank.'
: `Document block list:\n${buildDocumentContext(editor)}`,
selectionHtml
? `Content selected by the user (blocks ${scope.startIndex}-${scope.endIndex}):\n${selectionHtml}`
: '',
]
.filter(Boolean)
.join('\n\n')
}
// ---- restricted HTML fragment -> PmNode[] ----
export interface NumIds {
bullet: string | null
ordered: string | null
}
/**
* Preset paragraph formats for <pre> / <blockquote>: combinations of existing
* Block-model properties, so these blocks stay fully editable and round-trip
* byte-stable through parse -> generate -> parse (no schema/signature change).
*/
export const CODE_BLOCK_PRESET = {
font: 'Consolas',
shadingFill: 'F2F2F2',
borders: 'tblr',
} as const
export const QUOTE_BLOCK_PRESET = {
color: '666666',
indentLeft: 720,
borders: 'l',
} as const
/** pick an existing numbering id of the right kind so new list items join real docx numbering */
export function findNumId(blocks: Block[], kind: 'bullet' | 'ordered'): string | null {
for (const block of blocks) {
if (block.type === 'listItem' && block.list?.kind === kind) return block.list.numId
}
return null
}
const INLINE_MARK_TAGS: Record<string, string> = {
strong: 'bold',
b: 'bold',
em: 'italic',
i: 'italic',
u: 'underline',
s: 'strike',
del: 'strike',
strike: 'strike',
}
function parseInline(element: Node, marks: PmMark[]): PmNode[] {
const nodes: PmNode[] = []
element.childNodes.forEach((child) => {
if (child.nodeType === Node.TEXT_NODE) {
const text = (child.textContent ?? '').replace(/\s+/g, ' ')
if (text)
nodes.push({ type: 'text', text, ...(marks.length > 0 ? { marks: [...marks] } : {}) })
return
}
if (child.nodeType !== Node.ELEMENT_NODE) return
const el = child as Element
const tag = el.tagName.toLowerCase()
if (tag === 'br') {
nodes.push({ type: 'hardBreak' })
return
}
if (tag === 'a') {
const href = el.getAttribute('href') ?? ''
nodes.push(...parseInline(el, [...marks, { type: 'link', attrs: { href, rId: null } }]))
return
}
if (tag === 'formula') {
const latex = (el.textContent ?? '').trim()
if (!latex) return
try {
nodes.push(inlineEquationNodeJson(latex))
} catch (e) {
const reason = e instanceof Error ? e.message : String(e)
throw new Error(`Cannot parse the LaTeX in <formula> (${reason}): ${latex}`, { cause: e })
}
return
}
const markType = INLINE_MARK_TAGS[tag]
if (markType) {
const next = marks.some((m) => m.type === markType) ? marks : [...marks, { type: markType }]
nodes.push(...parseInline(el, next))
return
}
// unknown inline tag (span etc.): keep its text content
nodes.push(...parseInline(el, marks))
})
return nodes
}
function blockNode(type: string, attrs: Record<string, unknown>, content: PmNode[]): PmNode {
const node: PmNode = {
type,
attrs: { docxIndex: null, styleId: null, aiChanged: true, ...attrs },
}
if (content.length > 0) node.content = content
return node
}
function parseList(
el: Element,
kind: 'bullet' | 'ordered',
ilvl: number,
numIds: NumIds,
out: PmNode[],
): void {
el.childNodes.forEach((child) => {
if (child.nodeType !== Node.ELEMENT_NODE) return
const item = child as Element
const tag = item.tagName.toLowerCase()
if (tag === 'ul' || tag === 'ol') {
parseList(item, tag === 'ol' ? 'ordered' : 'bullet', ilvl + 1, numIds, out)
return
}
if (tag !== 'li') return
// extract nested lists first so their items follow this one
const nested: Element[] = []
item.querySelectorAll(':scope > ul, :scope > ol').forEach((n) => {
nested.push(n)
n.remove()
})
out.push(
blockNode(
'docListItem',
{ kind, numId: numIds[kind], ilvl: Math.min(ilvl, 4) },
parseInline(item, []),
),
)
for (const n of nested) {
parseList(n, n.tagName.toLowerCase() === 'ol' ? 'ordered' : 'bullet', ilvl + 1, numIds, out)
}
})
}
/** paragraph texts of one table cell: <br> and nested <p>/<div> split paragraphs */
function cellParas(cell: Element): string[] {
const paras: string[] = []
let current = ''
const push = () => {
paras.push(current.replace(/\s+/g, ' ').trim())
current = ''
}
const walk = (node: Node) => {
node.childNodes.forEach((child) => {
if (child.nodeType === Node.TEXT_NODE) {
current += child.textContent ?? ''
return
}
if (child.nodeType !== Node.ELEMENT_NODE) return
const el = child as Element
const tag = el.tagName.toLowerCase()
if (tag === 'br') push()
else if (tag === 'p' || tag === 'div') {
if (current.trim()) push()
walk(el)
push()
} else walk(el)
})
}
walk(cell)
if (current.trim()) push()
const out = paras.filter((p, i) => p !== '' || (i > 0 && i < paras.length - 1))
return out.length > 0 ? out : ['']
}
/**
* <table> -> protected table block: display TableModel + generated w:tbl
* fragment. Cell texts are patched into the fragment at save time via the
* existing genXml branch of pmDocToSavePlan (patchTableCellTexts), so the
* model row/col counts must mirror the generated grid.
*/
function parseTable(el: Element): PmNode | null {
const trs = Array.from(el.querySelectorAll('tr'))
if (trs.length === 0) return null
const rawRows = trs.map((tr) => Array.from(tr.children).filter((c) => /^t[hd]$/i.test(c.tagName)))
const cols = Math.max(...rawRows.map((r) => r.length))
if (cols === 0) return null
const headerRow = rawRows[0].some((c) => c.tagName.toLowerCase() === 'th')
const rows: TableCell[][] = rawRows.map((cells, r) => {
const isHeader = headerRow && r === 0
const row: TableCell[] = cells.map((cell) => ({
paras: cellParas(cell),
...(isHeader ? { bold: true, fill: TABLE_HEADER_FILL } : {}),
}))
while (row.length < cols)
row.push({ paras: [''], ...(isHeader ? { bold: true, fill: TABLE_HEADER_FILL } : {}) })
return row
})
const table: TableModel = { rows }
return tableModelToPmNode(table)
}
/** <pre> -> mono/shaded paragraph; newlines preserved as hard breaks */
function parseCodeBlock(el: Element): PmNode | null {
const text = (el.textContent ?? '').replace(/^\n/, '').replace(/\s+$/, '')
if (!text) return null
const mark: PmMark = { type: 'docTextStyle', attrs: { font: CODE_BLOCK_PRESET.font } }
const content: PmNode[] = []
text.split('\n').forEach((line, i) => {
if (i > 0) content.push({ type: 'hardBreak' })
if (line !== '') content.push({ type: 'text', text: line, marks: [mark] })
})
return blockNode(
'docParagraph',
{ shadingFill: CODE_BLOCK_PRESET.shadingFill, borders: CODE_BLOCK_PRESET.borders },
content,
)
}
/** <blockquote> -> indented gray paragraph with a left border */
function parseBlockquote(el: Element): PmNode | null {
const mark: PmMark = { type: 'docTextStyle', attrs: { color: QUOTE_BLOCK_PRESET.color } }
const inline = parseInline(el, [mark])
if (inline.length === 0) return null
return blockNode(
'docParagraph',
{ indentLeft: QUOTE_BLOCK_PRESET.indentLeft, borders: QUOTE_BLOCK_PRESET.borders },
inline,
)
}
/**
* Parse a restricted HTML fragment returned by the model into top-level PmNodes.
* Tolerates markdown code fences and plain-text responses.
*/
export function parseHtmlFragment(raw: string, numIds: NumIds): PmNode[] {
let text = raw.trim()
const fence = /```(?:html)?\s*([\s\S]*?)```/.exec(text)
if (fence) text = fence[1].trim()
if (!text) return []
// plain text response (no tags): one paragraph per blank-line-separated chunk
if (!/<[a-z][\s\S]*>/i.test(text)) {
return text
.split(/\n{2,}/)
.map((para) =>
blockNode('docParagraph', {}, [{ type: 'text', text: para.replace(/\s+/g, ' ').trim() }]),
)
.filter((n) => n.content?.[0]?.text)
}
const parsed = new DOMParser().parseFromString(text, 'text/html')
const out: PmNode[] = []
const pushFormula = (el: Element) => {
const latex = (el.textContent ?? '').trim()
if (!latex) return
try {
out.push(equationBlockJson(latex))
} catch (e) {
const reason = e instanceof Error ? e.message : String(e)
throw new Error(`Cannot parse the LaTeX in <formula> (${reason}): ${latex}`, { cause: e })
}
}
parsed.body.childNodes.forEach((child) => {
if (child.nodeType === Node.TEXT_NODE) {
const t = (child.textContent ?? '').trim()
if (t) out.push(blockNode('docParagraph', {}, [{ type: 'text', text: t }]))
return
}
if (child.nodeType !== Node.ELEMENT_NODE) return
const el = child as Element
const tag = el.tagName.toLowerCase()
const headingMatch = /^h([1-6])$/.exec(tag)
if (headingMatch) {
out.push(blockNode('docHeading', { level: Number(headingMatch[1]) }, parseInline(el, [])))
} else if (tag === 'ul' || tag === 'ol') {
parseList(el, tag === 'ol' ? 'ordered' : 'bullet', 0, numIds, out)
} else if (tag === 'table') {
const node = parseTable(el)
if (node) out.push(node)
} else if (tag === 'pre') {
const node = parseCodeBlock(el)
if (node) out.push(node)
} else if (tag === 'blockquote') {
const node = parseBlockquote(el)
if (node) out.push(node)
} else if (tag === 'formula') {
pushFormula(el)
} else if (tag === 'p' || tag === 'div') {
const inline = parseInline(el, [])
if (inline.length > 0) out.push(blockNode('docParagraph', {}, inline))
} else {
// unknown block-ish tag: salvage the text
const t = (el.textContent ?? '').trim()
if (t) out.push(blockNode('docParagraph', {}, [{ type: 'text', text: t }]))
}
})
return out
}
// ---- applying parsed fragments ----
/** record the AI's content change as tracked revisions under this author */
export interface AiTrack {
author: string
}
function revisionDate(): string {
return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')
}
/** blocks whose content ins/del marks can fully represent (tracked replace) */
const TRACKABLE_TYPES = new Set(['docParagraph', 'docHeading', 'docListItem'])
/**
* Replace the top-level block range with the parsed nodes (marked aiChanged).
* With `track`, and when both sides are plain text blocks, this becomes a
* tracked rewrite instead: the old blocks stay struck through
* (del) and the new blocks follow with ins marks — accept/reject via Review.
*/
export function replaceBlockRange(
editor: Editor,
startIndex: number,
endIndex: number,
nodes: PmNode[],
track?: AiTrack,
): boolean {
if (nodes.length === 0) return false
const { from, to } = blockRangePositions(editor, startIndex, endIndex)
const pmNodes = nodes.map((n) => editor.schema.nodeFromJSON(n))
let oldTrackable = true
editor.state.doc.nodesBetween(from, to, (node, _pos, parent) => {
if (parent === editor.state.doc && !TRACKABLE_TYPES.has(node.type.name)) oldTrackable = false
return false
})
const newTrackable = nodes.every((n) => TRACKABLE_TYPES.has(n.type))
if (track && oldTrackable && newTrackable) {
const { ins, del } = editor.schema.marks
const date = revisionDate()
// revision marks are the change indicator; no yellow aiChanged on top
const tracked = nodes.map((n) =>
editor.schema.nodeFromJSON({ ...n, attrs: { ...n.attrs, aiChanged: false } }),
)
const inserted = tracked.reduce((size, n) => size + n.nodeSize, 0)
const tr = editor.state.tr
tr.setMeta(TRACK_IGNORE, true)
if (editor.state.doc.textBetween(from, to, '\n').trim() === '') {
// nothing to strike through (blank paragraphs): replace outright
tr.replaceWith(from, to, tracked)
tr.addMark(from, from + inserted, ins.create({ author: track.author, date }))
} else {
tr.insert(to, tracked)
tr.addMark(to, to + inserted, ins.create({ author: track.author, date }))
tr.addMark(from, to, del.create({ author: track.author, date }))
}
editor.view.dispatch(tr)
return true
}
if (track) {
const date = revisionDate()
const oldNodes: ProseMirrorNode[] = []
editor.state.doc.nodesBetween(from, to, (node, _pos, parent) => {
if (parent === editor.state.doc) {
oldNodes.push(
node.type.create(
{
...node.attrs,
aiChanged: false,
blockRevision: { kind: 'del', author: track.author, date },
},
node.content,
node.marks,
),
)
}
return false
})
const inserted = pmNodes.map((node) =>
node.type.create(
{
...node.attrs,
aiChanged: false,
blockRevision: { kind: 'ins', author: track.author, date },
},
node.content,
node.marks,
),
)
const tr = editor.state.tr.replaceWith(from, to, [...oldNodes, ...inserted])
tr.setMeta(TRACK_IGNORE, true)
editor.view.dispatch(tr)
return true
}
editor.view.dispatch(editor.state.tr.replaceWith(from, to, pmNodes))
return true
}
/** insert the parsed nodes after the given top-level block index */
export function insertBlocksAfter(
editor: Editor,
index: number,
nodes: PmNode[],
track?: AiTrack,
): boolean {
if (nodes.length === 0) return false
const { to } = blockRangePositions(editor, index, index)
const pmNodes = nodes.map((n) =>
editor.schema.nodeFromJSON(track ? { ...n, attrs: { ...n.attrs, aiChanged: false } } : n),
)
const tr = editor.state.tr.insert(to, pmNodes)
if (track) {
const date = revisionDate()
let offset = to
for (const node of pmNodes) {
if (TRACKABLE_TYPES.has(node.type.name)) {
tr.addMark(
offset,
offset + node.nodeSize,
editor.schema.marks.ins.create({ author: track.author, date }),
)
} else {
tr.setNodeMarkup(offset, undefined, {
...node.attrs,
blockRevision: { kind: 'ins', author: track.author, date },
})
}
offset += node.nodeSize
}
tr.setMeta(TRACK_IGNORE, true)
}
editor.view.dispatch(tr)
return true
}
+590
View File
@@ -0,0 +1,590 @@
import type { Editor } from '@tiptap/core'
import type { ChartDisplay, NewChart } from '@genoffice/docx-engine'
import type { AgentToolCall, AgentToolDef } from '../../shared/ipc'
import { t } from '../i18n/locale'
import { executeCommands, type Command, type CommandEnvelope } from './commands'
import {
blockRangePositions,
buildDocumentContext,
insertBlocksAfter,
parseHtmlFragment,
replaceBlockRange,
serializeRangeToHtml,
type AiTrack,
type NumIds,
} from './protocol'
/**
* Local agent tools: a document-context reader plus a script-style execution
* channel. The "execution backend" is the in-process ProseMirror doc, split
* into three safe primitives plus the deterministic command engine.
*/
const READ_MAX_CHARS = 24_000
export const AGENT_TOOLS: AgentToolDef[] = [
{
name: 'get_document_context',
description:
'Get the latest state of the current document: block list (index|type|content preview), full-text stats (word/character counts) and the current selection. Block indexes change after modifications; call this when you need up-to-date indexes.',
inputSchema: { type: 'object', properties: {}, required: [] },
},
{
name: 'read_blocks',
description:
'Read the full content of a block range (restricted HTML). Previews in the block list are truncated; you must read the full original text with this tool before rewriting.',
inputSchema: {
type: 'object',
properties: {
startBlockIndex: { type: 'integer', description: 'start block index (0-based, inclusive)' },
endBlockIndex: { type: 'integer', description: 'end block index (inclusive)' },
},
required: ['startBlockIndex', 'endBlockIndex'],
},
},
{
name: 'insert_content',
description:
'Insert new content at a given position (restricted HTML, may contain multiple blocks). For writing/continuing/generating new content; to rewrite existing content use replace_blocks.',
inputSchema: {
type: 'object',
properties: {
html: { type: 'string', description: 'restricted HTML fragment to insert' },
afterBlockIndex: {
type: 'integer',
description:
'insert after this block index; -1 = start of document; omitted = after the block containing the cursor',
},
},
required: ['html'],
},
},
{
name: 'replace_blocks',
description:
'Replace a block range with new content (restricted HTML). For rewriting/translating/condensing/expanding existing content; the new block count may differ from the old.',
inputSchema: {
type: 'object',
properties: {
startBlockIndex: { type: 'integer', description: 'start block index (0-based, inclusive)' },
endBlockIndex: { type: 'integer', description: 'end block index (inclusive)' },
html: { type: 'string', description: 'replacement restricted HTML fragment' },
},
required: ['startBlockIndex', 'endBlockIndex', 'html'],
},
},
{
name: 'apply_commands',
description:
'Execute formatting/structure/batch commands (batchUpdate style, see the command guide in the system prompt): text style, paragraph format, heading level, find & replace, delete/move blocks, list conversion, image properties.',
inputSchema: {
type: 'object',
properties: {
commands: {
type: 'array',
description: 'array of commands executed in order; each command is a single-key object',
items: { type: 'object' },
},
},
required: ['commands'],
},
},
{
name: 'web_search',
description:
'Search the web for textual information (references/data/facts). Use when you need up-to-date information or are unsure about a fact. Returns titles/links/snippets.',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string', description: 'search keywords' },
maxResults: { type: 'integer', description: 'maximum number of results, default 6' },
},
required: ['query'],
},
},
{
name: 'image_search',
description:
'Search for images. Returns a list of image imageUrl entries; after picking one, insert it into the document with insert_image.',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string', description: 'image search keywords (English works better)' },
maxResults: { type: 'integer', description: 'maximum number of results, default 8' },
},
required: ['query'],
},
},
{
name: 'insert_image',
description:
'Download a direct image link (an imageUrl from image_search) and insert it into the document (at the cursor / end of document).',
inputSchema: {
type: 'object',
properties: {
url: { type: 'string', description: 'direct image link' },
maxWidthPx: { type: 'integer', description: 'maximum width (px), default 480' },
},
required: ['url'],
},
},
{
name: 'insert_chart',
description:
'Insert a chart (saved as a native Word chart). Data must be real: from the document content or web_search results — do not make up numbers.',
inputSchema: {
type: 'object',
properties: {
kind: { type: 'string', enum: ['bar', 'line', 'pie'], description: 'chart type' },
title: { type: 'string', description: 'chart title' },
categories: {
type: 'array',
items: { type: 'string' },
description: 'category (x axis / sector) labels',
},
series: {
type: 'array',
description:
'data series; values has the same length as categories, use null for missing data. Pie charts use only the first series',
items: {
type: 'object',
properties: {
name: { type: 'string' },
values: { type: 'array', items: { type: ['number', 'null'] } },
},
required: ['values'],
},
},
afterBlockIndex: {
type: 'integer',
description:
'insert after this block index; -1 = start of document; omitted = after the block containing the cursor',
},
},
required: ['kind', 'categories', 'series'],
},
},
{
name: 'edit_chart',
description:
'Edit the data of an existing chart in the document (title/category labels/series names/values). Chart blocks in the block list can be edited; ' +
'the category count and the number of values per series must match the original chart (data points cannot be added or removed).',
inputSchema: {
type: 'object',
properties: {
blockIndex: { type: 'integer', description: 'block index of the chart' },
title: { type: 'string', description: 'new title (omit to keep)' },
categories: {
type: 'array',
items: { type: ['string', 'null'] },
description:
'new category labels, same length as the original; pass null for positions to keep',
},
series: {
type: 'array',
description: 'series to change',
items: {
type: 'object',
properties: {
index: { type: 'integer', description: 'series index (0-based)' },
name: { type: 'string', description: 'new series name (omit to keep)' },
values: {
type: 'array',
items: { type: ['number', 'null'] },
description:
'new values, same length as the original series; pass null for positions to keep',
},
},
required: ['index'],
},
},
},
required: ['blockIndex'],
},
},
]
export interface ToolExecution {
/** result text fed back to the model */
output: string
isError?: boolean
/** true when the tool changed the document */
mutated: boolean
/** short human-readable label for the chat activity chip */
summary: string
}
const fail = (summary: string, output: string): ToolExecution => ({
output,
isError: true,
mutated: false,
summary,
})
function clampRange(
editor: Editor,
start: unknown,
end: unknown,
): { start: number; end: number } | null {
const count = editor.state.doc.childCount
if (!Number.isInteger(start) || !Number.isInteger(end)) return null
const s = Number(start)
const e = Number(end)
if (s < 0 || e < s || s >= count) return null
return { start: s, end: Math.min(e, count - 1) }
}
/** Read the natural size of a dataURL image. */
function imageSizeOf(dataUrl: string): Promise<{ width: number; height: number }> {
return new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => resolve({ width: img.naturalWidth || 1, height: img.naturalHeight || 1 })
img.onerror = () => reject(new Error('image load failed'))
img.src = dataUrl
})
}
/** Async tools: web search / image search / insert web image. */
async function executeAsyncTool(editor: Editor, call: AgentToolCall): Promise<ToolExecution> {
switch (call.name) {
case 'web_search': {
const query = String(call.input.query ?? '').trim()
if (!query) return fail(t('aiSumWebSearch'), 'query must not be empty')
const r = await window.desktop.webSearch(query, Number(call.input.maxResults) || 6)
const lines: string[] = []
if (r.answer) lines.push(`Direct answer: ${r.answer}\n`)
r.results.forEach((it, i) =>
lines.push(`${i + 1}. ${it.title}\n ${it.url}\n ${it.snippet}`),
)
return {
output: lines.join('\n') || '(no results)',
mutated: false,
summary: t('aiSumWebSearchDone', { query, count: r.results.length }),
}
}
case 'image_search': {
const query = String(call.input.query ?? '').trim()
if (!query) return fail(t('aiSumImageSearch'), 'query must not be empty')
const r = await window.desktop.imageSearch(query, Number(call.input.maxResults) || 8)
const lines = r.images.map(
(im, i) =>
`${i + 1}. ${im.title || '(untitled)'} [${im.width ?? '?'}x${im.height ?? '?'}]\n ${im.imageUrl}`,
)
return {
output: lines.join('\n') || '(no images)',
mutated: false,
summary: t('aiSumImageSearchDone', { query, count: r.images.length }),
}
}
case 'insert_image': {
const url = String(call.input.url ?? '')
if (!/^https?:\/\//.test(url)) return fail(t('aiSumInsertImage'), 'invalid url')
const fetched = await window.desktop.fetchImage(url)
if (!fetched)
return fail(t('aiSumInsertImage'), 'download failed (the image may not be accessible)')
const dataUrl = `data:${fetched.mime};base64,${fetched.base64}`
const maxW = Number(call.input.maxWidthPx) || 480
try {
const natural = await imageSizeOf(dataUrl)
const scale = Math.min(1, maxW / natural.width)
const w = Math.round(natural.width * scale)
const h = Math.round(natural.height * scale)
editor
.chain()
.focus()
.insertContent({
type: 'docProtected',
attrs: {
docxIndex: null,
blockType: 'image',
label: 'Image (web)',
imageDataUrl: dataUrl,
imageWidthPx: w,
imageHeightPx: h,
genImage: { base64: fetched.base64, mime: fetched.mime, widthPx: w, heightPx: h },
},
})
.run()
return {
output: `Inserted the image (${w}×${h}px).`,
mutated: true,
summary: t('aiSumInsertWebImage'),
}
} catch {
return fail(t('aiSumInsertImage'), 'the image could not be decoded')
}
}
default:
return fail(t('aiSumUnknownTool'), call.name)
}
}
export function executeTool(
editor: Editor,
call: AgentToolCall,
numIds: NumIds,
track?: AiTrack,
): ToolExecution | Promise<ToolExecution> {
// async tools (search/image insertion) take a separate Promise branch; the other sync tools keep returning synchronously (doesn't break existing tests).
if (call.name === 'web_search' || call.name === 'image_search' || call.name === 'insert_image') {
return executeAsyncTool(editor, call)
}
switch (call.name) {
case 'get_document_context':
return {
output: buildDocumentContext(editor),
mutated: false,
summary: t('aiSumReadDocContext'),
}
case 'read_blocks': {
const range = clampRange(editor, call.input.startBlockIndex, call.input.endBlockIndex)
if (!range) return fail(t('aiSumReadBlocks'), 'block index invalid or out of range')
const html = serializeRangeToHtml(editor, range.start, range.end)
const clipped =
html.length > READ_MAX_CHARS ? html.slice(0, READ_MAX_CHARS) + '\n…(truncated)' : html
return {
output: clipped || '(range is empty)',
mutated: false,
summary: t('aiSumReadBlocksRange', { start: range.start, end: range.end }),
}
}
case 'insert_content': {
const html = String(call.input.html ?? '')
let nodes: ReturnType<typeof parseHtmlFragment>
try {
nodes = parseHtmlFragment(html, numIds)
} catch (e) {
return fail(t('aiSumInsertContent'), e instanceof Error ? e.message : String(e))
}
if (nodes.length === 0)
return fail(t('aiSumInsertContent'), 'html did not parse into any content blocks')
const count = editor.state.doc.childCount
const docIsEmpty = editor.state.doc.textContent.trim() === ''
if (docIsEmpty) {
// the blank template's single empty paragraph gets replaced
replaceBlockRange(editor, 0, count - 1, nodes, track)
return {
output: `Inserted ${nodes.length} block(s) (the document was empty). Block indexes have changed; use get_document_context if needed.`,
mutated: true,
summary: t('aiSumInsertedBlocks', { count: nodes.length }),
}
}
const cursorScope = call.input.afterBlockIndex === undefined
const after = cursorScope
? getCursorBlockIndex(editor)
: Math.min(Math.max(Number(call.input.afterBlockIndex), -1), count - 1)
if (!Number.isInteger(after)) return fail(t('aiSumInsertContent'), 'invalid afterBlockIndex')
// -1 hits blockRangePositions' 0/0 default, i.e. insert at doc start
insertBlocksAfter(editor, after, nodes, track)
return {
output: `Inserted ${nodes.length} block(s) after block ${after}. Subsequent block indexes have shifted; use get_document_context if needed.`,
mutated: true,
summary: t('aiSumInsertedBlocks', { count: nodes.length }),
}
}
case 'replace_blocks': {
const range = clampRange(editor, call.input.startBlockIndex, call.input.endBlockIndex)
if (!range) return fail(t('aiSumReplaceContent'), 'block index invalid or out of range')
let nodes: ReturnType<typeof parseHtmlFragment>
try {
nodes = parseHtmlFragment(String(call.input.html ?? ''), numIds)
} catch (e) {
return fail(t('aiSumReplaceContent'), e instanceof Error ? e.message : String(e))
}
if (nodes.length === 0)
return fail(t('aiSumReplaceContent'), 'html did not parse into any content blocks')
replaceBlockRange(editor, range.start, range.end, nodes, track)
return {
output: `Replaced blocks ${range.start}-${range.end} with ${nodes.length} block(s). Block indexes have changed; use get_document_context if needed.`,
mutated: true,
summary: t('aiSumReplacedBlocks', { start: range.start, end: range.end }),
}
}
case 'insert_chart': {
const kind = String(call.input.kind ?? '') as NewChart['kind']
if (!['bar', 'line', 'pie'].includes(kind))
return fail(t('aiSumInsertChart'), 'kind must be one of bar/line/pie')
const categories = Array.isArray(call.input.categories)
? (call.input.categories as unknown[]).map((c) => String(c ?? ''))
: []
const seriesIn = Array.isArray(call.input.series)
? (call.input.series as ReadonlyArray<{ name?: unknown; values?: unknown } | null>)
: []
if (!categories.length || !seriesIn.length)
return fail(t('aiSumInsertChart'), 'categories and series must not be empty')
const series = seriesIn.map((s, i) => {
const values: unknown[] = Array.isArray(s?.values) ? s.values : []
return {
name: String(s?.name ?? `Series ${i + 1}`),
values: categories.map((_, j) => {
const v = values[j] ?? null
const n = Number(v)
return v != null && Number.isFinite(n) ? n : null
}),
}
})
const title = String(call.input.title ?? '').trim() || 'Chart title'
const spec: NewChart = { kind, title, categories, series }
const display: ChartDisplay = { partPath: '', kind, title, categories, series }
const count = editor.state.doc.childCount
const after =
call.input.afterBlockIndex === undefined
? getCursorBlockIndex(editor)
: Math.min(Math.max(Number(call.input.afterBlockIndex), -1), count - 1)
if (!Number.isInteger(after)) return fail(t('aiSumInsertChart'), 'invalid afterBlockIndex')
const { to } = blockRangePositions(editor, after, after)
editor
.chain()
.insertContentAt(to, {
type: 'docProtected',
attrs: {
docxIndex: null,
blockType: 'chart',
label: 'Chart',
genChart: spec,
chartDisplay: display,
},
})
.run()
return {
output: `Inserted a ${kind} chart "${title}" (${categories.length} categories × ${series.length} series).`,
mutated: true,
summary: t('aiSumInsertedChart', { title }),
}
}
case 'edit_chart': {
const idx = Number(call.input.blockIndex)
if (!Number.isInteger(idx) || idx < 0 || idx >= editor.state.doc.childCount) {
return fail(t('aiSumEditChart'), 'blockIndex invalid or out of range')
}
const node = editor.state.doc.child(idx)
// native docx charts are passthrough blocks + chartDisplay; AI/UI-created ones are blockType 'chart'
const display =
node.type.name === 'docProtected' ? (node.attrs.chartDisplay as ChartDisplay | null) : null
if (!display)
return fail(
t('aiSumEditChart'),
`block ${idx} is not a chart (or the chart has no editable data cache)`,
)
const isNative = display.partPath !== '' // native chart part from docx: data-point structure is immutable
const next: ChartDisplay = {
...display,
categories: [...display.categories],
series: display.series.map((s) => ({ ...s, values: [...s.values] })),
}
if (call.input.title !== undefined) next.title = String(call.input.title)
if (call.input.categories !== undefined) {
const cats = call.input.categories
if (!Array.isArray(cats) || cats.length !== display.categories.length) {
return fail(
t('aiSumEditChart'),
`categories must match the original category count (${display.categories.length})`,
)
}
cats.forEach((c, i) => {
if (c != null) next.categories[i] = String(c)
})
}
const serIn = Array.isArray(call.input.series)
? (call.input.series as ReadonlyArray<{
index?: unknown
name?: unknown
values?: unknown
} | null>)
: []
for (const s of serIn) {
const si = Number(s?.index)
const orig = display.series[si]
if (!Number.isInteger(si) || !orig)
return fail(
t('aiSumEditChart'),
`series index ${s?.index} is invalid (${display.series.length} series in total)`,
)
if (s?.name !== undefined) next.series[si]!.name = String(s.name)
if (s?.values !== undefined) {
const values: unknown[] | null = Array.isArray(s.values) ? s.values : null
if (!values || values.length !== orig.values.length) {
return fail(
t('aiSumEditChart'),
`values of series ${si} must match the original series length (${orig.values.length})`,
)
}
for (let j = 0; j < values.length; j++) {
const v = values[j]
if (v == null) continue
const n = Number(v)
if (!Number.isFinite(n))
return fail(t('aiSumEditChart'), `value ${j} of series ${si} is not a number`)
if (isNative && orig.values[j] == null) {
return fail(
t('aiSumEditChart'),
`data point ${j} of series ${si} is empty in the original chart; empty points of a native chart cannot be written`,
)
}
next.series[si]!.values[j] = n
}
}
}
// generated charts (genChart) update the spec in sync; the chart part is rebuilt from the new data on save
const gen = node.attrs.genChart as NewChart | null
const nextGen: NewChart | null = gen
? {
...gen,
title: next.title ?? gen.title,
categories: [...next.categories],
series: next.series.map((s) => ({ name: s.name ?? '', values: [...s.values] })),
}
: null
const { from } = blockRangePositions(editor, idx, idx)
editor.view.dispatch(
editor.state.tr.setNodeMarkup(from, undefined, {
...node.attrs,
chartDisplay: next,
genChart: nextGen,
}),
)
return {
output: `Updated the data of chart "${next.title ?? ''}" (changes are written back to the chart on save).`,
mutated: true,
summary: t('aiSumEditedChart', { index: idx }),
}
}
case 'apply_commands': {
const commands = call.input.commands
if (!Array.isArray(commands) || commands.length === 0) {
return fail(t('aiSumApplyCommands'), 'commands must be a non-empty array')
}
const envelope: CommandEnvelope = { commands: commands as Command[] }
const outcome = executeCommands(editor, envelope, { numIds, track })
if (!outcome.ok)
return fail(t('aiSumApplyCommands'), outcome.error ?? 'command execution failed')
const changed = outcome.results.reduce((sum, r) => sum + r.changed, 0)
return {
output: outcome.summary,
mutated: changed > 0,
summary: outcome.summary,
}
}
default:
return fail(call.name, `unknown tool: ${call.name}`)
}
}
/** top-level index of the block containing the caret (doc end as fallback) */
function getCursorBlockIndex(editor: Editor): number {
const { from } = editor.state.selection
let result = editor.state.doc.childCount - 1
let index = 0
editor.state.doc.forEach((node, offset) => {
if (from >= offset && from <= offset + node.nodeSize) result = index
index++
})
return result
}
+14
View File
@@ -0,0 +1,14 @@
import { createIpcTransport, type AgentTransport } from '@genoffice/agent-core'
import type { AiSettings } from '../../shared/ipc'
import { t } from '../i18n/locale'
/** The shared IPC transport wired to the docs preload bridge (window.desktop). */
export function createElectronTransport(getSettings: () => AiSettings): AgentTransport {
return createIpcTransport<AiSettings>({
onStream: (listener) => window.desktop.onAiStream(listener),
start: (request) => void window.desktop.aiStream(request),
cancel: (requestId) => void window.desktop.aiStreamCancel(requestId),
getSettings,
unknownErrorText: () => t('aiUnknownError'),
})
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

@@ -0,0 +1,242 @@
import { useEffect, useRef, useState } from 'react'
import type { CommentInfo } from '@genoffice/docx-engine'
import { useI18n } from '../i18n/locale'
import { IconComment, IconTrash } from './icons'
function formatDate(iso?: string): string {
if (!iso) return ''
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return ''
return d.toLocaleString(undefined, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
}
/** anchor text quoted from the document, to orient comments whose range spans paragraphs */
function anchorTextOf(id: string): string {
const spans = document.querySelectorAll<HTMLElement>('.ProseMirror .doc-comment')
let text = ''
for (const span of spans) {
if ((span.dataset.commentIds ?? '').split(' ').includes(id)) text += span.textContent ?? ''
}
return text
}
function jumpTo(id: string) {
const spans = document.querySelectorAll<HTMLElement>('.ProseMirror .doc-comment')
const targets = [...spans].filter((s) => (s.dataset.commentIds ?? '').split(' ').includes(id))
if (targets.length === 0) return
targets[0].scrollIntoView({ behavior: 'smooth', block: 'center' })
for (const t of targets) {
t.classList.remove('doc-comment-flash')
// restart the CSS animation when jumping to the same comment twice
void t.offsetWidth
t.classList.add('doc-comment-flash')
}
}
/**
* Word's comments pane: list + jump-to-anchor, a composer when New Comment was
* clicked (composing), and per-comment delete.
*/
export function CommentsPanel({
comments,
composing,
onSubmitNew,
onReply,
onResolve,
onCancelNew,
onDelete,
onClose,
}: {
comments: CommentInfo[]
/** show the new-comment composer (selection captured by the caller) */
composing: boolean
onSubmitNew: (text: string) => void
/** Reply to a comment (anchor shares the parent comment's range) */
onReply: (parentId: string, text: string) => void
/** Resolve/reopen the whole thread */
onResolve: (id: string, done: boolean) => void
onCancelNew: () => void
onDelete: (id: string) => void
onClose: () => void
}) {
const { t } = useI18n()
const [activeId, setActiveId] = useState<string | null>(null)
const [draft, setDraft] = useState('')
const draftRef = useRef<HTMLTextAreaElement>(null)
const [replyTo, setReplyTo] = useState<string | null>(null)
const [replyDraft, setReplyDraft] = useState('')
// Word: resolved comments are collapsed/hidden by default
const [showResolved, setShowResolved] = useState(false)
const topLevel = comments.filter((c) => !c.parentId)
const openThreads = topLevel.filter((c) => !c.done)
const resolvedThreads = topLevel.filter((c) => c.done)
const repliesOf = (id: string) => comments.filter((c) => c.parentId === id)
const submitReply = () => {
const text = replyDraft.trim()
if (!text || !replyTo) return
onReply(replyTo, text)
setReplyDraft('')
setReplyTo(null)
}
useEffect(() => {
if (composing) draftRef.current?.focus()
}, [composing])
const submit = () => {
const text = draft.trim()
if (!text) return
onSubmitNew(text)
setDraft('')
}
const renderThread = (c: CommentInfo) => {
const anchor = anchorTextOf(c.id)
const replies = repliesOf(c.id)
return (
<div key={c.id} className={`comment-thread ${c.done ? 'resolved' : ''}`}>
<button
className={`comment-card ${activeId === c.id ? 'active' : ''}`}
onClick={() => {
setActiveId(c.id)
jumpTo(c.id)
}}
>
<div className="comment-card-head">
<span className="comment-avatar">{(c.initials || c.author || '?').slice(0, 2)}</span>
<span className="comment-author">{c.author || t('appUnknownAuthor')}</span>
<span className="comment-date">{formatDate(c.date)}</span>
{c.done && <span className="comment-resolved-badge">{t('appResolved')}</span>}
<span
className="comment-card-del"
title={replies.length > 0 ? t('appDeleteCommentWithReplies') : t('appDeleteComment')}
role="button"
aria-label={t('appDeleteComment')}
tabIndex={0}
onClick={(e) => {
e.stopPropagation()
onDelete(c.id)
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.stopPropagation()
onDelete(c.id)
}
}}
>
<IconTrash size={13} />
</span>
</div>
{anchor && <div className="comment-anchor">“{anchor.slice(0, 60)}”</div>}
<div className="comment-text">{c.text}</div>
</button>
{replies.map((r) => (
<div key={r.id} className="comment-reply">
<div className="comment-card-head">
<span className="comment-avatar">{(r.initials || r.author || '?').slice(0, 2)}</span>
<span className="comment-author">{r.author || t('appUnknownAuthor')}</span>
<span className="comment-date">{formatDate(r.date)}</span>
<span
className="comment-card-del"
title={t('appDeleteReply')}
role="button"
tabIndex={0}
onClick={(e) => {
e.stopPropagation()
onDelete(r.id)
}}
>
<IconTrash size={12} />
</span>
</div>
<div className="comment-text">{r.text}</div>
</div>
))}
<div className="comment-thread-actions">
{replyTo === c.id ? (
<div className="comment-reply-compose">
<textarea
autoFocus
placeholder={t('appReplyPlaceholder')}
value={replyDraft}
onChange={(e) => setReplyDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) submitReply()
if (e.key === 'Escape') setReplyTo(null)
}}
/>
<div className="comment-compose-actions">
<button onClick={() => setReplyTo(null)}>{t('appCancel')}</button>
<button className="primary" disabled={!replyDraft.trim()} onClick={submitReply}>
{t('appReply')}
</button>
</div>
</div>
) : (
<>
<button onClick={() => setReplyTo(c.id)}>{t('appReply')}</button>
<button onClick={() => onResolve(c.id, !c.done)}>
{c.done ? t('appReopen') : t('appResolve')}
</button>
</>
)}
</div>
</div>
)
}
return (
<aside className="comments-pane">
<div className="comments-pane-head">
<span className="comments-pane-title">
<IconComment size={14} /> {t('appCommentsTitle', { n: comments.length })}
</span>
<button className="comments-pane-close" title={t('appClose')} onClick={onClose}>
✕
</button>
</div>
{composing && (
<div className="comment-compose">
<textarea
ref={draftRef}
placeholder={t('appCommentPlaceholder')}
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) submit()
if (e.key === 'Escape') onCancelNew()
}}
/>
<div className="comment-compose-actions">
<button onClick={onCancelNew}>{t('appCancel')}</button>
<button className="primary" disabled={!draft.trim()} onClick={submit}>
{t('appCommentBtn')}
</button>
</div>
</div>
)}
<div className="comments-pane-list">
{openThreads.map(renderThread)}
{resolvedThreads.length > 0 && (
<div className="comments-resolved-group">
<button className="comments-resolved-toggle" onClick={() => setShowResolved((v) => !v)}>
<span className={`comments-resolved-caret ${showResolved ? 'open' : ''}`}>▸</span>
{t('appResolvedComments', { n: resolvedThreads.length })}
</button>
{showResolved && resolvedThreads.map(renderThread)}
</div>
)}
{comments.length === 0 && !composing && (
<div className="comments-empty">{t('appNoComments')}</div>
)}
</div>
</aside>
)
}
@@ -0,0 +1,77 @@
import { Fragment } from 'react'
import type { CompareEntry } from '../editor/compare'
import { summarize } from '../editor/compare'
import { useI18n } from '../i18n/locale'
import { IconCompare } from './icons'
/**
* Review → Compare result pane: paragraph-level differences between the open
* document and a chosen second file. Unchanged stretches collapse to a count.
*/
export function ComparePanel({
otherName,
entries,
onClose,
}: {
otherName: string
entries: CompareEntry[]
onClose: () => void
}) {
const { t } = useI18n()
const { added, removed, changed } = summarize(entries)
const rows: Array<{ key: number; entry?: CompareEntry; sameCount?: number }> = []
let sameRun = 0
entries.forEach((entry, i) => {
if (entry.kind === 'same') {
sameRun++
return
}
if (sameRun > 0) {
rows.push({ key: rows.length, sameCount: sameRun })
sameRun = 0
}
rows.push({ key: rows.length, entry })
void i
})
if (sameRun > 0) rows.push({ key: rows.length, sameCount: sameRun })
return (
<aside className="comments-pane compare-pane">
<div className="comments-pane-head">
<span className="comments-pane-title">
<IconCompare size={14} /> {t('appCompareResult')}
</span>
<button className="comments-pane-close" title={t('appClose')} onClick={onClose}>
✕
</button>
</div>
<div className="compare-meta">
{t('appCompareWithPrefix')}
<b>{otherName}</b>
{t('appCompareStats', { added, removed, changed })}
</div>
<div className="comments-pane-list">
{added + removed + changed === 0 && (
<div className="comments-empty">{t('appCompareIdentical')}</div>
)}
{rows.map((row) => (
<Fragment key={row.key}>
{row.sameCount !== undefined && (
<div className="compare-same">{t('appCompareSameRun', { n: row.sameCount })}</div>
)}
{row.entry && (
<div className={`compare-card compare-${row.entry.kind}`}>
{row.entry.kind !== 'added' && (
<div className="compare-left">{row.entry.left || t('appEmptyParagraph')}</div>
)}
{row.entry.kind !== 'removed' && (
<div className="compare-right">{row.entry.right || t('appEmptyParagraph')}</div>
)}
</div>
)}
</Fragment>
))}
</div>
</aside>
)
}
@@ -0,0 +1,639 @@
import { useEffect, useRef, useState } from 'react'
import type { Editor } from '@tiptap/core'
import { useI18n, type StringKey } from '../i18n/locale'
import { fontFamiliesFor } from '../font-list'
import { cssFontFamily } from '../line-metrics'
import { setParaAttrs, activeParaAttrs } from './ribbon-tabs'
import { IconSparkle } from './icons'
/**
* Editor context menu (right click in the document body):
* Cut/Copy/Paste · Font… · Paragraph… · Synonyms · Translate · Hyperlink… · New Comment.
*/
export interface ContextMenuState {
x: number
y: number
}
interface EditorContextMenuProps {
editor: Editor
menu: ContextMenuState
onClose: () => void
onFontDialog: () => void
onParagraphDialog: () => void
onLink: () => void
onNewComment: () => void
onAiPreset: (instruction: string) => void
/** List items: restart numbering / continue numbering (shown when the cursor is on a docListItem) */
onRestartNumbering?: () => void
onContinueNumbering?: () => void
/** F9 update fields (shown when the cursor is on an inline field) */
onUpdateFields?: () => void
}
/** target languages mirrored from the Review → Translate dropdown; the localized label also goes into the LLM prompt */
const TRANSLATE_TARGETS: Array<{ labelKey: StringKey }> = [
{ labelKey: 'appLangEnglish' },
{ labelKey: 'appLangSimplifiedChinese' },
{ labelKey: 'appLangJapanese' },
{ labelKey: 'appLangKorean' },
{ labelKey: 'appLangFrench' },
{ labelKey: 'appLangGerman' },
{ labelKey: 'appLangSpanish' },
]
const MENU_WIDTH = 240
export function EditorContextMenu({
editor,
menu,
onClose,
onFontDialog,
onParagraphDialog,
onLink,
onNewComment,
onAiPreset,
onRestartNumbering,
onContinueNumbering,
onUpdateFields,
}: EditorContextMenuProps) {
const { t } = useI18n()
const ref = useRef<HTMLDivElement>(null)
const [submenu, setSubmenu] = useState<string | null>(null)
const { from, to } = editor.state.selection
const hasSelection = from !== to
const selectedText = hasSelection ? editor.state.doc.textBetween(from, to, ' ').trim() : ''
// Synonyms targets a word / short phrase, not long selections
const synonymText = selectedText.length > 0 && selectedText.length <= 20 ? selectedText : ''
// keep the menu inside the viewport (flip up / clamp left near the edges)
const [pos, setPos] = useState({ left: menu.x, top: menu.y })
useEffect(() => {
const el = ref.current
if (!el) return
const rect = el.getBoundingClientRect()
let left = menu.x
let top = menu.y
if (left + rect.width > window.innerWidth - 8) left = window.innerWidth - rect.width - 8
if (top + rect.height > window.innerHeight - 8) top = Math.max(8, menu.y - rect.height)
setPos({ left, top })
}, [menu])
useEffect(() => {
const close = (e: MouseEvent) => {
if (!ref.current?.contains(e.target as Node)) onClose()
}
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
}
window.addEventListener('mousedown', close)
window.addEventListener('keydown', onKey)
window.addEventListener('blur', onClose)
return () => {
window.removeEventListener('mousedown', close)
window.removeEventListener('keydown', onKey)
window.removeEventListener('blur', onClose)
}
}, [onClose])
const run = (action: () => void) => () => {
onClose()
action()
}
const protAttrs = editor.getAttributes('docProtected')
const isImage = protAttrs?.blockType === 'image'
const isFloating =
isImage ||
(Array.isArray(protAttrs?.textboxes) && (protAttrs.textboxes as unknown[]).length > 0)
const currentWrap = (protAttrs?.imageWrap as string | null) ?? null
const setWrap = (wrap: string | null) =>
editor.chain().focus().updateAttributes('docProtected', { imageWrap: wrap }).run()
/** Plain-text insertion: no HTML parsing (insertContent(string) would treat < > as tags) */
const insertPlainText = (text: string) => {
const lines = text.replace(/\r/g, '').split('\n')
if (lines.length === 1) {
editor.chain().focus().insertContent({ type: 'text', text: lines[0] }).run()
return
}
editor
.chain()
.focus()
.insertContent(
lines.map((line) => ({
type: 'docParagraph',
...(line ? { content: [{ type: 'text', text: line }] } : {}),
})),
)
.run()
}
const clipboard = async (action: 'cut' | 'copy' | 'paste' | 'pastePlain') => {
if (action === 'paste') {
// rich paste: prefer HTML (parsed by editor paste rules, keeps formatting), otherwise plain text
try {
const items = await navigator.clipboard.read()
for (const item of items) {
if (item.types.includes('text/html')) {
const html = await (await item.getType('text/html')).text()
editor
.chain()
.focus()
.insertContent(html, { parseOptions: { preserveWhitespace: true } })
.run()
return
}
}
} catch {
/* clipboard.read unavailable (permission/format): fall back to plain text */
}
const text = await navigator.clipboard.readText()
if (text) insertPlainText(text)
} else if (action === 'pastePlain') {
const text = await navigator.clipboard.readText()
if (text) insertPlainText(text)
} else {
editor.commands.focus()
document.execCommand(action)
}
}
const item = (
label: string,
opts: {
key?: string
disabled?: boolean
onClick?: () => void
submenuKey?: string
ai?: boolean
},
) => (
<button
className="ctx-item"
disabled={opts.disabled}
title={opts.ai ? t('appAiBadgeTip') : undefined}
onMouseEnter={() => setSubmenu(opts.submenuKey ?? null)}
onClick={opts.submenuKey ? undefined : opts.onClick}
>
<span className="ctx-label">{label}</span>
{opts.ai && (
<span className="copilot-badge copilot-badge-menu">
<IconSparkle size={10} />
</span>
)}
{opts.key && <span className="ctx-key">{opts.key}</span>}
{opts.submenuKey && <span className="ctx-arrow">›</span>}
</button>
)
return (
<div
ref={ref}
className="ctx-menu"
style={{ left: pos.left, top: pos.top, minWidth: MENU_WIDTH }}
onContextMenu={(e) => e.preventDefault()}
>
{item(t('appCut'), {
key: '⌘X',
disabled: !hasSelection,
onClick: run(() => void clipboard('cut')),
})}
{item(t('appCopy'), {
key: '⌘C',
disabled: !hasSelection,
onClick: run(() => void clipboard('copy')),
})}
{item(t('appPaste'), { key: '⌘V', onClick: run(() => void clipboard('paste')) })}
{item(t('appPastePlain'), { onClick: run(() => void clipboard('pastePlain')) })}
<div className="ctx-sep" />
{item(t('appFontMenu'), { key: '⌘D', onClick: run(onFontDialog) })}
{item(t('appParagraphMenu'), { key: '⌥⌘M', onClick: run(onParagraphDialog) })}
{editor.isActive('instrField') && onUpdateFields && (
<>
<div className="ctx-sep" />
{item(t('appUpdateField'), { key: 'F9', onClick: run(() => onUpdateFields()) })}
</>
)}
{editor.isActive('docListItem') && !!editor.getAttributes('docListItem').numId && (
<>
<div className="ctx-sep" />
{item(t('appRestartNumbering'), {
disabled: !onRestartNumbering,
onClick: run(() => onRestartNumbering?.()),
})}
{item(t('appContinueNumbering'), {
disabled: !onContinueNumbering,
onClick: run(() => onContinueNumbering?.()),
})}
</>
)}
<div className="ctx-sep" />
{item(t('appSynonyms'), {
disabled: !synonymText,
ai: true,
onClick: run(() => onAiPreset(t('appSynonymsPrompt', { text: synonymText }))),
})}
<div className="ctx-item-wrap" onMouseLeave={() => setSubmenu(null)}>
{item(t('appTranslate'), { disabled: !hasSelection, submenuKey: 'translate', ai: true })}
{submenu === 'translate' && hasSelection && (
<div className="ctx-submenu">
{TRANSLATE_TARGETS.map((target) => (
<button
key={target.labelKey}
className="ctx-item"
onClick={run(() =>
onAiPreset(
t('appTranslateSelectionPrompt', {
lang: t(target.labelKey),
text: selectedText,
}),
),
)}
>
<span className="ctx-label">
{t('appTranslateTo', { lang: t(target.labelKey) })}
</span>
</button>
))}
</div>
)}
</div>
{isFloating && (
<>
<div className="ctx-sep" />
<div className="ctx-item-wrap" onMouseLeave={() => setSubmenu(null)}>
{item(t('appWrapTextMenu'), { submenuKey: 'wrap' })}
{submenu === 'wrap' && (
<div className="ctx-submenu">
{WRAP_OPTIONS.map((opt) => (
<button
key={String(opt.value)}
className="ctx-item"
onClick={run(() => setWrap(opt.value))}
>
<span className="ctx-label">
{currentWrap === opt.value ? '✓ ' : ''}
{t(opt.labelKey)}
</span>
</button>
))}
</div>
)}
</div>
</>
)}
<div className="ctx-sep" />
{item(t('appHyperlinkMenu'), { key: '⌘K', onClick: run(onLink) })}
{item(t('appNewComment'), { disabled: !hasSelection, onClick: run(onNewComment) })}
</div>
)
}
/** Wrap options from Word's image context menu (inline/square/top-bottom/behind text/in front of text); shared with the Picture Format tab */
export const WRAP_OPTIONS: Array<{ labelKey: StringKey; value: string | null }> = [
{ labelKey: 'appWrapInline', value: null },
{ labelKey: 'appWrapSquareLeft', value: 'square-left' },
{ labelKey: 'appWrapSquareRight', value: 'square-right' },
{ labelKey: 'appWrapTopBottom', value: 'topBottom' },
{ labelKey: 'appWrapBehind', value: 'behind' },
{ labelKey: 'appWrapFront', value: 'front' },
]
/* ================= Font dialog ================= */
const FONT_SIZES = [9, 10, 10.5, 11, 12, 14, 16, 18, 20, 22, 24, 28, 36, 48, 72]
const FONT_STYLES: Array<{ key: string; nameKey: StringKey }> = [
{ key: 'regular', nameKey: 'appFontRegular' },
{ key: 'italic', nameKey: 'appFontItalic' },
{ key: 'bold', nameKey: 'appFontBold' },
{ key: 'boldItalic', nameKey: 'appFontBoldItalic' },
]
export function FontDialog({ editor, onClose }: { editor: Editor; onClose: () => void }) {
const { t, lang } = useI18n()
const fontFamilies = fontFamiliesFor(lang)
const textAttrs = editor.getAttributes('docTextStyle')
const initialStyle = editor.isActive('bold')
? editor.isActive('italic')
? 'boldItalic'
: 'bold'
: editor.isActive('italic')
? 'italic'
: 'regular'
const [font, setFont] = useState((textAttrs.font as string | null) ?? '')
const [size, setSize] = useState(
textAttrs.sizeHalfPoints ? Number(textAttrs.sizeHalfPoints) / 2 : 11,
)
const [style, setStyle] = useState<string>(initialStyle)
const [color, setColor] = useState(`#${(textAttrs.color as string | null) ?? '000000'}`)
const [underline, setUnderline] = useState(editor.isActive('underline'))
const [strike, setStrike] = useState(editor.isActive('strike'))
const [vertAlign, setVertAlign] = useState<string>((textAttrs.vertAlign as string | null) ?? '')
const apply = () => {
const hex = color.replace('#', '').toUpperCase()
let chain = editor
.chain()
.focus()
.setMark('docTextStyle', {
color: hex === '000000' ? null : hex,
sizeHalfPoints: Math.round(size * 2),
font: font || null,
highlight: textAttrs.highlight ?? null,
vertAlign: vertAlign || null,
})
const wantBold = style === 'bold' || style === 'boldItalic'
const wantItalic = style === 'italic' || style === 'boldItalic'
chain = wantBold ? chain.setMark('bold') : chain.unsetMark('bold')
chain = wantItalic ? chain.setMark('italic') : chain.unsetMark('italic')
chain = underline ? chain.setMark('underline') : chain.unsetMark('underline')
chain = strike ? chain.setMark('strike') : chain.unsetMark('strike')
chain.run()
onClose()
}
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal">
<h2>{t('appFontDialogTitle')}</h2>
<div className="font-dialog-row">
<label>
{t('appFontFamilyLabel')}
<select value={font} onChange={(e) => setFont(e.target.value)}>
<option value="">{t('appDefaultBodyFont')}</option>
{fontFamilies.map((f) => (
<option key={f} value={f} style={{ fontFamily: cssFontFamily(f) }}>
{f}
</option>
))}
{font && !fontFamilies.includes(font) && <option value={font}>{font}</option>}
</select>
</label>
<label>
{t('appFontStyleLabel')}
<select value={style} onChange={(e) => setStyle(e.target.value)}>
{FONT_STYLES.map((s) => (
<option key={s.key} value={s.key}>
{t(s.nameKey)}
</option>
))}
</select>
</label>
<label>
{t('appFontSizeLabel')}
<select value={size} onChange={(e) => setSize(Number(e.target.value))}>
{!FONT_SIZES.includes(size) && <option value={size}>{size}</option>}
{FONT_SIZES.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</select>
</label>
</div>
<div className="font-dialog-row">
<label>
{t('appFontColor')}
<input
type="color"
className="font-color-input"
value={color}
onChange={(e) => setColor(e.target.value)}
/>
</label>
<label className="font-check">
<input
type="checkbox"
checked={underline}
onChange={(e) => setUnderline(e.target.checked)}
/>
{t('appUnderline')}
</label>
<label className="font-check">
<input type="checkbox" checked={strike} onChange={(e) => setStrike(e.target.checked)} />
{t('appStrikethrough')}
</label>
<label className="font-check">
<input
type="checkbox"
checked={vertAlign === 'superscript'}
onChange={(e) => setVertAlign(e.target.checked ? 'superscript' : '')}
/>
{t('appSuperscript')}
</label>
<label className="font-check">
<input
type="checkbox"
checked={vertAlign === 'subscript'}
onChange={(e) => setVertAlign(e.target.checked ? 'subscript' : '')}
/>
{t('appSubscript')}
</label>
</div>
<div
className="font-preview"
style={{
fontFamily: font ? cssFontFamily(font) : undefined,
fontSize: `${Math.min(size, 28)}pt`,
fontWeight: style === 'bold' || style === 'boldItalic' ? 600 : 400,
fontStyle: style === 'italic' || style === 'boldItalic' ? 'italic' : 'normal',
color,
textDecoration:
[underline ? 'underline' : '', strike ? 'line-through' : ''].join(' ').trim() ||
undefined,
}}
>
{t('appFontPreviewSample')}
</div>
<div className="modal-actions">
<button className="btn-ghost" onClick={onClose}>
{t('appCancel')}
</button>
<button className="btn-primary" onClick={apply}>
{t('appOk')}
</button>
</div>
</div>
</div>
)
}
/* ================= Paragraph dialog ================= */
const PT_PER_TWIP = 1 / 20
const ALIGN_OPTIONS: Array<{ key: string; nameKey: StringKey }> = [
{ key: '', nameKey: 'appAlignLeft' },
{ key: 'center', nameKey: 'appAlignCenter' },
{ key: 'right', nameKey: 'appAlignRight' },
{ key: 'justify', nameKey: 'appAlignJustify' },
]
const LINE_SPACINGS: Array<{ value: number; nameKey: StringKey }> = [
{ value: 1, nameKey: 'appLineSingle' },
{ value: 1.15, nameKey: 'appLine115' },
{ value: 1.5, nameKey: 'appLine15' },
{ value: 2, nameKey: 'appLineDouble' },
{ value: 2.5, nameKey: 'appLine25' },
{ value: 3, nameKey: 'appLineTriple' },
]
export function ParagraphDialog({ editor, onClose }: { editor: Editor; onClose: () => void }) {
const { t } = useI18n()
const attrs = activeParaAttrs(editor)
const [align, setAlign] = useState<string>((attrs.align as string | null) ?? '')
// Line spacing rule: multiples are the preset select values; 'atLeast'/'exact'
// take a pt value (w:spacing w:lineRule + w:line, already modeled by parse/save)
const rawTwips = Number(attrs.lineRawTwips) || 0
const initRule =
attrs.lineRule === 'exact' || attrs.lineRule === 'atLeast' ? (attrs.lineRule as string) : ''
const initMultiple =
Number(attrs.lineSpacing) || (attrs.lineRule === 'auto' && rawTwips ? rawTwips / 240 : 1)
const [lineRule, setLineRule] = useState<string>(initRule)
const [lineSpacing, setLineSpacing] = useState<number>(Math.round(initMultiple * 100) / 100)
const [linePt, setLinePt] = useState<number>(rawTwips ? Math.round(rawTwips / 2) / 10 : 12)
const twipsToPt = (v: unknown) => Math.round((Number(v) || 0) * PT_PER_TWIP)
const [indentLeft, setIndentLeft] = useState(twipsToPt(attrs.indentLeft))
const [indentRight, setIndentRight] = useState(twipsToPt(attrs.indentRight))
const [indentFirstLine, setIndentFirstLine] = useState(twipsToPt(attrs.indentFirstLine))
const [spaceBefore, setSpaceBefore] = useState(twipsToPt(attrs.spaceBefore))
const [spaceAfter, setSpaceAfter] = useState(twipsToPt(attrs.spaceAfter))
const apply = () => {
const ptToTwips = (pt: number) => (pt > 0 ? Math.round(pt / PT_PER_TWIP) : null)
const spacing =
lineRule === 'exact' || lineRule === 'atLeast'
? { lineSpacing: null, lineRule, lineRawTwips: Math.max(20, Math.round(linePt * 20)) }
: {
lineSpacing: lineSpacing === 1 ? null : lineSpacing,
lineRule: null,
lineRawTwips: null,
}
setParaAttrs(editor, {
align: align || null,
...spacing,
indentLeft: ptToTwips(indentLeft),
indentRight: ptToTwips(indentRight),
indentFirstLine: ptToTwips(indentFirstLine),
spaceBefore: ptToTwips(spaceBefore),
spaceAfter: ptToTwips(spaceAfter),
})
onClose()
}
const numInput = (label: string, value: number, set: (v: number) => void) => (
<label>
{label}
<span className="para-num">
<input
type="number"
min={0}
max={400}
value={value}
onChange={(e) => set(Math.max(0, Number(e.target.value) || 0))}
/>
<span className="para-unit">pt</span>
</span>
</label>
)
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal">
<h2>{t('appParagraph')}</h2>
<div className="font-dialog-row">
<label>
{t('appAlignment')}
<select value={align} onChange={(e) => setAlign(e.target.value)}>
{ALIGN_OPTIONS.map((o) => (
<option key={o.key} value={o.key}>
{t(o.nameKey)}
</option>
))}
</select>
</label>
<label>
{t('appLineSpacingLabel')}
<select
value={lineRule || String(lineSpacing)}
onChange={(e) => {
const v = e.target.value
if (v === 'exact' || v === 'atLeast' || v === 'multiple') {
setLineRule(v === 'multiple' ? '' : v)
if (v === 'multiple') setLineSpacing(1.25)
} else {
setLineRule('')
setLineSpacing(Number(v))
}
}}
>
{!lineRule && !LINE_SPACINGS.some((s) => s.value === lineSpacing) && (
<option value={lineSpacing}>{t('appLineMultiple', { n: lineSpacing })}</option>
)}
{LINE_SPACINGS.map((s) => (
<option key={s.value} value={s.value}>
{t(s.nameKey)}
</option>
))}
<option value="atLeast">{t('appLineAtLeast')}</option>
<option value="exact">{t('appLineExactly')}</option>
</select>
</label>
{lineRule === 'exact' || lineRule === 'atLeast' ? (
<label>
{t('appLineValue')}
<span className="para-num">
<input
type="number"
min={1}
max={1584}
step={0.5}
value={linePt}
onChange={(e) => setLinePt(Math.max(0, Number(e.target.value) || 0))}
/>
<span className="para-unit">pt</span>
</span>
</label>
) : (
<label>
{t('appLineValue')}
<span className="para-num">
<input
type="number"
min={0.06}
max={132}
step={0.05}
value={lineSpacing}
onChange={(e) => setLineSpacing(Math.max(0.06, Number(e.target.value) || 1))}
/>
<span className="para-unit">×</span>
</span>
</label>
)}
</div>
<div className="font-dialog-row">
{numInput(t('appIndentLeft'), indentLeft, setIndentLeft)}
{numInput(t('appIndentRight'), indentRight, setIndentRight)}
{numInput(t('appIndentFirstLine'), indentFirstLine, setIndentFirstLine)}
</div>
<div className="font-dialog-row">
{numInput(t('appSpaceBefore'), spaceBefore, setSpaceBefore)}
{numInput(t('appSpaceAfter'), spaceAfter, setSpaceAfter)}
</div>
<div className="modal-actions">
<button className="btn-ghost" onClick={onClose}>
{t('appCancel')}
</button>
<button className="btn-primary" onClick={apply}>
{t('appOk')}
</button>
</div>
</div>
</div>
)
}
@@ -0,0 +1,199 @@
import { useMemo, useState } from 'react'
import type { Editor } from '@tiptap/core'
import { latexToOmml, ommlToMathML } from '@genoffice/docx-engine'
import { t, useI18n, type StringKey } from '../i18n/locale'
import { equationBlockJson, inlineEquationNodeJson } from '../editor/equation'
/** Built-in equation library (the common preset set for the "Insert Equation" dropdown) */
export const BUILTIN_EQUATIONS: Array<{ name: string; nameKey: StringKey; latex: string }> = [
{ name: 'Area of Circle', nameKey: 'appEqCircleArea', latex: 'A = \\pi r^2' },
{
name: 'Binomial Theorem',
nameKey: 'appEqBinomial',
latex: '(x+a)^n = \\sum_{k=0}^{n} \\binom{n}{k} x^k a^{n-k}',
},
{
name: 'Expansion of a Sum',
nameKey: 'appEqSumExpansion',
latex: '(1+x)^n = 1 + \\frac{nx}{1!} + \\frac{n(n-1)x^2}{2!} + \\cdots',
},
{
name: 'Fourier Series',
nameKey: 'appEqFourier',
latex:
'f(x) = a_0 + \\sum_{n=1}^{\\infty} \\left( a_n \\cos \\frac{n\\pi x}{L} + b_n \\sin \\frac{n\\pi x}{L} \\right)',
},
{ name: 'Pythagorean Theorem', nameKey: 'appEqPythagorean', latex: 'a^2 + b^2 = c^2' },
{
name: 'Quadratic Formula',
nameKey: 'appEqQuadratic',
latex: 'x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}',
},
{
name: 'Taylor Expansion',
nameKey: 'appEqTaylor',
latex:
'e^x = 1 + \\frac{x}{1!} + \\frac{x^2}{2!} + \\frac{x^3}{3!} + \\cdots, -\\infty < x < \\infty',
},
{
name: 'Trig Identity',
nameKey: 'appEqTrigIdentity',
latex:
'\\sin \\alpha \\pm \\sin \\beta = 2 \\sin \\frac{1}{2} (\\alpha \\pm \\beta) \\cos \\frac{1}{2} (\\alpha \\mp \\beta)',
},
]
/** Build an equation block from LaTeX and insert it (protected block, genXml goes through the save path) */
export function insertEquationFromLatex(editor: Editor, latex: string): void {
editor.chain().focus().insertContent(equationBlockJson(latex)).run()
}
/** Insert an inline equation at the cursor that flows with the text */
export function insertInlineEquationFromLatex(editor: Editor, latex: string): void {
editor.chain().focus().insertContent(inlineEquationNodeJson(latex)).run()
}
/** Equation re-edit target (inline = inline node; block = standalone protected equation block) */
export interface MathEditTarget {
pos: number
latex: string
kind: 'inline' | 'block'
}
/** MathML preview (returns null with an error message when the LaTeX is invalid) */
function previewOf(latex: string): { mathml: string } | { error: string } | null {
if (!latex.trim()) return null
try {
const omml = latexToOmml(latex)
const mathml = ommlToMathML(`<m:oMath>${omml}</m:oMath>`)
return mathml ? { mathml } : { error: t('appPreviewUnavailable') }
} catch (e) {
return { error: e instanceof Error ? e.message : String(e) }
}
}
/** Insert Equation dialog: LaTeX input + live MathML preview, shared by the ribbon and the native menu */
export function EquationModal({
editor,
onClose,
editTarget,
}: {
editor: Editor
onClose: () => void
/** When provided, "re-edit equation" mode: update that node instead of inserting */
editTarget?: MathEditTarget
}) {
const { t } = useI18n()
const [latex, setLatex] = useState(editTarget?.latex ?? '')
const [inline, setInline] = useState(editTarget?.kind === 'inline')
const preview = useMemo(() => previewOf(latex), [latex])
const canInsert = preview !== null && 'mathml' in preview
const insert = () => {
if (!canInsert) return
if (editTarget) {
const node = editor.state.doc.nodeAt(editTarget.pos)
if (editTarget.kind === 'inline' && node?.type.name === 'docInlineMath') {
const next = inlineEquationNodeJson(latex)
editor.view.dispatch(editor.state.tr.setNodeMarkup(editTarget.pos, undefined, next.attrs))
} else if (editTarget.kind === 'block' && node?.type.name === 'docProtected') {
// rebuilt from LaTeX: the block loses its original anchor and saves as
// freshly generated OMML (that is the point of a full re-edit)
const next = editor.schema.nodeFromJSON(equationBlockJson(latex))
editor.view.dispatch(
editor.state.tr.replaceWith(editTarget.pos, editTarget.pos + node.nodeSize, next),
)
}
} else if (inline) {
insertInlineEquationFromLatex(editor, latex)
} else {
insertEquationFromLatex(editor, latex)
}
onClose()
}
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal equation-modal">
<h2>{t('appInsertEquation')}</h2>
<label>
LaTeX
<input
value={latex}
onChange={(e) => setLatex(e.target.value)}
placeholder={t('appLatexPlaceholder')}
onKeyDown={(e) => e.key === 'Enter' && insert()}
autoFocus
/>
</label>
<div className="equation-preview">
{preview === null && (
<span className="equation-preview-hint">{t('appLatexPreviewHint')}</span>
)}
{preview !== null && 'error' in preview && (
<span className="equation-preview-error">{preview.error}</span>
)}
{preview !== null && 'mathml' in preview && (
<span dangerouslySetInnerHTML={{ __html: preview.mathml }} />
)}
</div>
{!editTarget && (
<label className="equation-inline-toggle">
<input type="checkbox" checked={inline} onChange={(e) => setInline(e.target.checked)} />
{t('appInlineEquationToggle')}
</label>
)}
<div className="modal-actions">
<button className="btn-ghost" onClick={onClose}>
{t('appCancel')}
</button>
<button className="btn-primary" disabled={!canInsert} onClick={insert}>
{editTarget ? t('appUpdate') : t('appInsert')}
</button>
</div>
</div>
</div>
)
}
/** Built-in equation gallery (ribbon Equation ▾ dropdown), with MathML thumbnail previews */
export function EquationGallery({
editor,
onPick,
onCustom,
}: {
editor: Editor
onPick: () => void
onCustom: () => void
}) {
const { t } = useI18n()
return (
<div className="equation-gallery">
{BUILTIN_EQUATIONS.map((eq) => {
const preview = previewOf(eq.latex)
return (
<button
key={eq.nameKey}
className="equation-gallery-item"
title={t(eq.nameKey)}
onClick={() => {
insertEquationFromLatex(editor, eq.latex)
onPick()
}}
>
<span className="equation-gallery-name">{t(eq.nameKey)}</span>
{preview !== null && 'mathml' in preview && (
<span
className="equation-gallery-preview"
dangerouslySetInnerHTML={{ __html: preview.mathml }}
/>
)}
</button>
)
})}
<button className="equation-gallery-custom" onClick={onCustom}>
{t('appInsertNewEquation')}
</button>
</div>
)
}
@@ -0,0 +1,222 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { Editor } from '@tiptap/core'
import { useI18n } from '../i18n/locale'
import { searchPluginKey } from '../editor/extensions'
interface Range {
from: number
to: number
}
interface FindOptions {
matchCase: boolean
wholeWord: boolean
}
const isWordChar = (ch: string | undefined) => !!ch && /[\p{L}\p{N}_]/u.test(ch)
/** collect matches inside editable textblocks (protected blocks excluded) */
function findMatches(editor: Editor, query: string, opts: FindOptions): Range[] {
const found: Range[] = []
if (!query) return found
const needle = opts.matchCase ? query : query.toLowerCase()
editor.state.doc.descendants((node, pos) => {
if (!node.isTextblock) return true
// flatten the block's inline content so matches spanning marks are found
let text = ''
const posAt: number[] = []
node.forEach((child, offset) => {
if (child.isText && child.text) {
for (let k = 0; k < child.text.length; k++) posAt.push(pos + 1 + offset + k)
text += child.text
} else {
posAt.push(pos + 1 + offset)
text += '\u0000' // leaf placeholder (hard break) never matches
}
})
const haystack = opts.matchCase ? text : text.toLowerCase()
let i = 0
while ((i = haystack.indexOf(needle, i)) !== -1) {
const isWhole =
!opts.wholeWord || (!isWordChar(text[i - 1]) && !isWordChar(text[i + query.length]))
if (isWhole) {
found.push({ from: posAt[i], to: posAt[i + query.length - 1] + 1 })
i += query.length
} else {
i += 1
}
}
return false
})
return found
}
interface FindPanelProps {
editor: Editor
onClose: () => void
}
export function FindPanel({ editor, onClose }: FindPanelProps) {
const { t } = useI18n()
const [query, setQuery] = useState('')
const [replacement, setReplacement] = useState('')
const [matches, setMatches] = useState<Range[]>([])
const [index, setIndex] = useState(0)
const [matchCase, setMatchCase] = useState(false)
const [wholeWord, setWholeWord] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
const highlight = useCallback(
(ranges: Range[], activeIndex: number) => {
editor.view.dispatch(editor.state.tr.setMeta(searchPluginKey, { ranges, activeIndex }))
},
[editor],
)
const scrollTo = useCallback(
(range: Range) => {
const { node } = editor.view.domAtPos(range.from)
const el = node instanceof HTMLElement ? node : node.parentElement
el?.scrollIntoView({ block: 'center' })
},
[editor],
)
const refresh = useCallback(
(q: string, keepIndex = 0, opts?: Partial<FindOptions>) => {
const ranges = findMatches(editor, q, { matchCase, wholeWord, ...opts })
const active = ranges.length === 0 ? 0 : Math.min(keepIndex, ranges.length - 1)
setMatches(ranges)
setIndex(active)
highlight(ranges, active)
if (ranges.length > 0) scrollTo(ranges[active])
return ranges
},
[editor, highlight, scrollTo, matchCase, wholeWord],
)
useEffect(() => {
inputRef.current?.focus()
inputRef.current?.select()
}, [])
// stay in sync while the document changes underneath (typing, AI edits)
useEffect(() => {
const onUpdate = () => {
if (!query) return
const ranges = findMatches(editor, query, { matchCase, wholeWord })
setMatches(ranges)
setIndex((i) => Math.min(i, Math.max(ranges.length - 1, 0)))
}
editor.on('update', onUpdate)
return () => {
editor.off('update', onUpdate)
}
}, [editor, query, matchCase, wholeWord])
const close = useCallback(() => {
highlight([], 0)
onClose()
}, [highlight, onClose])
const step = useCallback(
(dir: 1 | -1) => {
if (matches.length === 0) return
const next = (index + dir + matches.length) % matches.length
setIndex(next)
highlight(matches, next)
scrollTo(matches[next])
},
[matches, index, highlight, scrollTo],
)
const replaceOne = useCallback(() => {
const m = matches[index]
if (!m) return
editor.commands.command(({ tr }) => {
tr.insertText(replacement, m.from, m.to)
return true
})
refresh(query, index)
}, [editor, matches, index, replacement, query, refresh])
const replaceAll = useCallback(() => {
if (matches.length === 0) return
editor.commands.command(({ tr }) => {
for (const m of [...matches].reverse()) tr.insertText(replacement, m.from, m.to)
return true
})
refresh(query)
}, [editor, matches, replacement, query, refresh])
return (
<div className="find-panel">
<div className="find-row">
<input
ref={inputRef}
className="find-input"
placeholder={t('appFindPlaceholder')}
value={query}
onChange={(e) => {
setQuery(e.target.value)
refresh(e.target.value)
}}
onKeyDown={(e) => {
if (e.key === 'Enter') step(e.shiftKey ? -1 : 1)
if (e.key === 'Escape') close()
}}
/>
<button
className={`find-opt ${matchCase ? 'on' : ''}`}
title={t('appMatchCase')}
onClick={() => {
setMatchCase(!matchCase)
refresh(query, index, { matchCase: !matchCase })
}}
>
Aa
</button>
<button
className={`find-opt ${wholeWord ? 'on' : ''}`}
title={t('appWholeWord')}
onClick={() => {
setWholeWord(!wholeWord)
refresh(query, index, { wholeWord: !wholeWord })
}}
>
W
</button>
<span className="find-count">
{query ? (matches.length === 0 ? t('appNoResults') : `${index + 1}/${matches.length}`) : ''}
</span>
<button className="find-btn" title={t('appPrevMatch')} onClick={() => step(-1)} disabled={matches.length === 0}>
‹
</button>
<button className="find-btn" title={t('appNextMatch')} onClick={() => step(1)} disabled={matches.length === 0}>
›
</button>
<button className="find-btn find-close" title={t('appCloseEsc')} onClick={close}>
✕
</button>
</div>
<div className="find-row">
<input
className="find-input"
placeholder={t('appReplacePlaceholder')}
value={replacement}
onChange={(e) => setReplacement(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') replaceOne()
if (e.key === 'Escape') close()
}}
/>
<button className="find-action" onClick={replaceOne} disabled={matches.length === 0}>
{t('appReplace')}
</button>
<button className="find-action" onClick={replaceAll} disabled={matches.length === 0}>
{t('appReplaceAll')}
</button>
</div>
</div>
)
}
@@ -0,0 +1,186 @@
import { useEffect, useRef, useState } from 'react'
import { TOTAL_PAGES_MARK, type HfImage, type HfParagraph, type Run } from '@genoffice/docx-engine'
import { useI18n } from '../i18n/locale'
import { cssFontFamily } from '../line-metrics'
export interface HfValue {
text: string
pageNumber?: boolean
paras?: HfParagraph[]
}
function runStyle(run: Run): React.CSSProperties {
const style: React.CSSProperties = {}
if (run.bold) style.fontWeight = 600
if (run.italic) style.fontStyle = 'italic'
if (run.underline) style.textDecoration = 'underline'
if (run.strike) style.textDecoration = `${style.textDecoration ?? ''} line-through`.trim()
if (run.color) style.color = `#${run.color}`
if (run.sizeHalfPoints) style.fontSize = `${run.sizeHalfPoints / 2}pt`
if (run.font) style.fontFamily = cssFontFamily(run.font)
return style
}
/** effective paragraphs: rich paras when present, else the legacy single line */
function parasOf(value: HfValue): HfParagraph[] {
if (value.paras?.length) return value.paras
const runs: Run[] = value.text ? [{ text: value.text }] : []
if (value.pageNumber && !value.text.includes('#')) {
runs.push({ text: runs.length > 0 ? ' #' : '#' })
}
return [{ align: 'center', runs }]
}
/**
* Header / footer zone on the page: renders the rich paragraphs,
* double-click enters in-place editing (plain text per paragraph; each line
* keeps its paragraph format and first-run styling), blur commits. The '#'
* marker stands for the automatic page number.
*/
export function HeaderFooterArea({
kind,
value,
images,
readOnly,
onCommit,
pageNo,
pageTotal,
}: {
kind: 'header' | 'footer'
value: HfValue
/** logo and other images in the part, display-only (text edits do not affect their saved bytes) */
images?: HfImage[]
readOnly?: boolean
onCommit: (next: HfValue) => void
/** Page number shown for '#' (may be a section-formatted string); the continuous-flow canvas has no real page number, defaults to 1 */
pageNo?: number | string
/** Total page count shown for TOTAL_PAGES_MARK (NUMPAGES field), defaults to 1 */
pageTotal?: number
}) {
const { t } = useI18n()
const [editing, setEditing] = useState(false)
const editRef = useRef<HTMLDivElement>(null)
const paras = parasOf(value)
// The editing surface is a standalone element: content is injected here and React
// does not manage its children; after commit the whole element unmounts, so text
// nodes produced while typing don't linger (keeps section/variant switches clean)
useEffect(() => {
if (!editing) return
const el = editRef.current
if (!el) return
el.innerText = paras.map((p) => p.runs.map((r) => r.text).join('')).join('\n')
el.focus()
const sel = window.getSelection()
if (sel) {
sel.selectAllChildren(el)
sel.collapseToEnd()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [editing])
const commit = () => {
const el = editRef.current
setEditing(false)
if (!el) return
const lines = el.innerText.replace(/\n+$/, '').split('\n')
const nextParas: HfParagraph[] = lines.map((line, i) => {
const template = paras[Math.min(i, paras.length - 1)]
const style = template.runs[0] ?? {}
return { ...template, runs: line === '' ? [] : [{ ...style, text: line }] }
})
const text = nextParas.map((p) => p.runs.map((r) => r.text).join('')).join('')
onCommit({ ...value, text, paras: nextParas })
}
const display = (text: string) => {
const t = text.replaceAll(TOTAL_PAGES_MARK, String(pageTotal ?? 1))
return value.pageNumber ? t.replace('#', String(pageNo ?? 1)) : t
}
return (
<div
className={`page-hf page-hf-${kind}${editing ? ' page-hf-editing' : ''}`}
title={
readOnly
? undefined
: t(kind === 'header' ? 'appDblclickEditHeader' : 'appDblclickEditFooter') +
(value.pageNumber ? t('appHfPageNumHint') : '')
}
onDoubleClick={() => {
if (!readOnly && !editing) setEditing(true)
}}
>
{images && images.length > 0 && (
<div className="page-hf-images" contentEditable={false}>
{images.map((img, i) => (
<img
key={i}
src={img.dataUrl}
alt=""
draggable={false}
style={{
...(img.widthPx ? { width: img.widthPx } : {}),
...(img.heightPx ? { height: img.heightPx } : {}),
}}
/>
))}
</div>
)}
{editing ? (
<div
ref={editRef}
className="page-hf-edit-surface"
contentEditable
suppressContentEditableWarning
onBlur={commit}
onKeyDown={(e) => {
if (e.key === 'Escape') {
e.preventDefault()
;(e.target as HTMLElement).blur()
}
}}
/>
) : (
<HfContent paras={paras} display={display} />
)}
</div>
)
}
function HfContent({
paras,
display,
}: {
paras: HfParagraph[]
display: (text: string) => string
}) {
return (
<>
{paras.map((para, i) => (
<div
key={i}
className="page-hf-para"
style={{
...(para.bidi ? { direction: 'rtl' as const } : {}),
...(para.align
? {
textAlign:
para.align === 'left' || para.align === 'center' || para.align === 'right'
? para.align
: ('justify' as const),
}
: {}),
}}
>
{para.runs.length === 0 ? ' ' : null}
{para.runs.map((run, j) => (
<span key={j} style={runStyle(run)}>
{display(run.text)}
</span>
))}
</div>
))}
</>
)
}
@@ -0,0 +1,237 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { PointerEvent as ReactPointerEvent } from 'react'
import {
HIGHLIGHTER_ALPHA,
nextInkId,
strokeHitTest,
strokePathD,
type InkAnnotation,
type InkPoint,
type InkStroke,
type InkTool,
} from '../editor/ink'
/**
* Transparent drawing layer covering the page (pen/highlighter/eraser). Lives inside
* .page-wrap, which is inside the zoomed .doc-zoom container — pointer
* coordinates are divided by the zoom factor so stroke geometry is stored at
* 100% zoom, matching the engine's EMU offsets on save.
*
* Finished strokes are anchored to the nearest body paragraph (data-idx) and
* stored relative to its top-left corner, so they follow the paragraph when
* content above reflows.
*/
interface InkOverlayProps {
tool: InkTool
/** hex without '#' */
color: string
width: number
zoom: number
annotations: InkAnnotation[]
onAdd: (annotation: InkAnnotation) => void
onRemove: (ids: string[]) => void
}
/** overlay-relative top-left of every anchored paragraph, at 100% zoom */
type AnchorPositions = Map<number, InkPoint>
const ERASER_RADIUS = 6
function measureAnchors(overlay: HTMLElement, zoomFactor: number): AnchorPositions {
const positions: AnchorPositions = new Map()
const base = overlay.getBoundingClientRect()
const blocks = overlay.parentElement?.querySelectorAll<HTMLElement>('.ProseMirror > [data-idx]')
for (const el of blocks ? Array.from(blocks) : []) {
const idx = parseInt(el.dataset.idx ?? '', 10)
if (!Number.isFinite(idx)) continue
const rect = el.getBoundingClientRect()
positions.set(idx, {
x: (rect.left - base.left) / zoomFactor,
y: (rect.top - base.top) / zoomFactor,
})
}
return positions
}
/** anchor for a stroke: the paragraph whose top is closest above its first point */
function pickAnchor(positions: AnchorPositions, start: InkPoint): number | null {
let best: number | null = null
let bestTop = -Infinity
for (const [idx, pos] of positions) {
if (pos.y <= start.y && pos.y > bestTop) {
bestTop = pos.y
best = idx
}
}
if (best !== null) return best
// stroke above every paragraph: fall back to the topmost one
let top = Infinity
for (const [idx, pos] of positions) {
if (pos.y < top) {
top = pos.y
best = idx
}
}
return best
}
export function InkOverlay({ tool, color, width, zoom, annotations, onAdd, onRemove }: InkOverlayProps) {
const overlayRef = useRef<HTMLDivElement>(null)
const [anchors, setAnchors] = useState<AnchorPositions>(new Map())
const [livePoints, setLivePoints] = useState<InkPoint[] | null>(null)
const drawingRef = useRef<InkPoint[] | null>(null)
const erasedRef = useRef<Set<string>>(new Set())
const zoomFactor = zoom / 100
const drawing = tool === 'pen' || tool === 'highlighter'
const remeasure = useCallback(() => {
const overlay = overlayRef.current
if (overlay) setAnchors(measureAnchors(overlay, zoomFactor))
}, [zoomFactor])
// paragraph positions shift on every edit/zoom/resize; observe the page and
// re-measure so anchored strokes stay glued to their paragraphs
useEffect(() => {
remeasure()
const page = overlayRef.current?.parentElement
if (!page) return
const observer = new ResizeObserver(remeasure)
observer.observe(page)
const mutations = new MutationObserver(remeasure)
mutations.observe(page, { childList: true, subtree: true, characterData: true })
return () => {
observer.disconnect()
mutations.disconnect()
}
}, [remeasure, annotations])
const localPoint = (e: ReactPointerEvent): InkPoint => {
const rect = overlayRef.current!.getBoundingClientRect()
return { x: (e.clientX - rect.left) / zoomFactor, y: (e.clientY - rect.top) / zoomFactor }
}
const eraseAt = useCallback(
(point: InkPoint) => {
const hits: string[] = []
for (const ann of annotations) {
if (erasedRef.current.has(ann.id)) continue
const pos = anchors.get(ann.anchorIndex)
if (!pos) continue
const rel = { x: point.x - pos.x, y: point.y - pos.y }
if (ann.stroke) {
if (strokeHitTest(ann.stroke, rel, ERASER_RADIUS)) hits.push(ann.id)
} else if (ann.image) {
const { offsetXPx: x, offsetYPx: y, widthPx: w, heightPx: h } = ann.image
if (rel.x >= x && rel.x <= x + w && rel.y >= y && rel.y <= y + h) hits.push(ann.id)
}
}
if (hits.length > 0) {
for (const id of hits) erasedRef.current.add(id)
onRemove(hits)
}
},
[annotations, anchors, onRemove],
)
const onPointerDown = (e: ReactPointerEvent) => {
if (tool === 'select' || e.button !== 0) return
e.preventDefault()
;(e.target as HTMLElement).setPointerCapture(e.pointerId)
const point = localPoint(e)
if (tool === 'eraser') {
erasedRef.current = new Set()
drawingRef.current = [] // non-null marks "eraser drag active"
eraseAt(point)
return
}
drawingRef.current = [point]
setLivePoints([point])
}
const onPointerMove = (e: ReactPointerEvent) => {
if (!drawingRef.current) return
const point = localPoint(e)
if (tool === 'eraser') {
eraseAt(point)
return
}
const points = drawingRef.current
const last = points[points.length - 1]
if (Math.hypot(point.x - last.x, point.y - last.y) < 0.8) return
points.push(point)
setLivePoints([...points])
}
const onPointerUp = () => {
const points = drawingRef.current
drawingRef.current = null
if (tool !== 'pen' && tool !== 'highlighter') return
setLivePoints(null)
if (!points || points.length === 0) return
const anchorIndex = pickAnchor(anchors, points[0])
if (anchorIndex === null) return
const pos = anchors.get(anchorIndex)!
const stroke: InkStroke = {
tool,
color,
width,
points: points.map((p) => ({ x: p.x - pos.x, y: p.y - pos.y })),
}
onAdd({ id: nextInkId(), anchorIndex, stroke })
}
const strokeStyle = (s: InkStroke) => ({
stroke: `#${s.color}`,
strokeWidth: s.width,
strokeOpacity: s.tool === 'highlighter' ? HIGHLIGHTER_ALPHA : 1,
fill: 'none' as const,
strokeLinecap: 'round' as const,
strokeLinejoin: 'round' as const,
})
return (
<div
ref={overlayRef}
className={`ink-overlay ${tool !== 'select' ? `ink-active ink-tool-${tool}` : ''}`}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}
>
<svg className="ink-svg" aria-hidden>
{annotations.map((ann) => {
const pos = anchors.get(ann.anchorIndex)
if (!pos) return null
if (ann.stroke) {
return (
<path
key={ann.id}
d={strokePathD(ann.stroke.points)}
transform={`translate(${pos.x} ${pos.y})`}
{...strokeStyle(ann.stroke)}
/>
)
}
if (ann.image?.dataUrl) {
return (
<image
key={ann.id}
href={ann.image.dataUrl}
x={pos.x + ann.image.offsetXPx}
y={pos.y + ann.image.offsetYPx}
width={ann.image.widthPx}
height={ann.image.heightPx}
/>
)
}
return null
})}
{livePoints && drawing && (
<path d={strokePathD(livePoints)} {...strokeStyle({ tool, color, width, points: livePoints })} />
)}
</svg>
</div>
)
}
@@ -0,0 +1,33 @@
import type { Editor } from '@tiptap/core'
import { t } from '../i18n/locale'
/** Word's navigation pane: heading outline with click-to-jump. */
export function NavPane({ editor }: { editor: Editor }) {
const headings: Array<{ text: string; level: number; pos: number }> = []
editor.state.doc.forEach((node, offset) => {
if (node.type.name === 'docHeading' && node.textContent.trim()) {
headings.push({ text: node.textContent, level: Number(node.attrs.level) || 1, pos: offset })
}
})
return (
<aside className="nav-pane">
<div className="nav-pane-title">{t('appNavTitle')}</div>
<div className="nav-pane-list">
{headings.map((h, i) => (
<button
key={`${h.pos}-${i}`}
className={`nav-item nav-l${Math.min(h.level, 4)}`}
title={h.text}
onClick={() => {
const dom = editor.view.nodeDOM(h.pos) as HTMLElement | null
dom?.scrollIntoView({ behavior: 'smooth', block: 'start' })
}}
>
{h.text}
</button>
))}
{headings.length === 0 && <div className="nav-empty">{t('appNavNoHeadings')}</div>}
</div>
</aside>
)
}
@@ -0,0 +1,585 @@
import { useEffect, useMemo, useState } from 'react'
import type {
HeaderFooter,
HfImage,
HfPartInfo,
SectionInfo,
SectionSettings,
} from '@genoffice/docx-engine'
import {
appendEndnotesBlock,
assignSections,
effectiveBottomPx,
effectiveHfRefs,
effectiveTopPx,
formatPageNumber,
liveSections,
measureBlocks,
pageNumbers,
sectionColGeom,
sectionFirstPages,
sectionGeoms,
sectionPageBox,
sliceWithLineSplit,
type BlockBox,
type BlockMetaOf,
type PageNoteItem,
type PageSlice,
type SectionHfHeights,
} from '../pagination'
import { estimateHfHeight, FOOTNOTE_SEPARATOR_H } from '../line-metrics'
import { toRoman } from '../note-format'
import { useI18n } from '../i18n/locale'
import { HeaderFooterArea } from './HeaderFooterArea'
const twipsToPx = (twips: number) => (twips / 1440) * 96
export interface HfSet {
header: HeaderFooter | null
footer: HeaderFooter | null
headerFirst: HeaderFooter | null
footerFirst: HeaderFooter | null
headerEven: HeaderFooter | null
footerEven: HeaderFooter | null
titlePg: boolean
evenOddHf: boolean
/** images in each variant part (logos etc., display-only) */
images?: Partial<
Record<
'header' | 'footer' | 'headerFirst' | 'footerFirst' | 'headerEven' | 'footerEven',
HfImage[]
>
>
}
/**
* Pagination preview: a read-only snapshot of real page slicing over the canvas's continuous
* flow. Each page = a full content clone + overflow clipping + negative-margin offset; the
* clone is fixed at the canvas content width (line breaks from measurement must not change),
* and paper size/margins render per each page's section (mixed portrait/landscape across
* sections is real). Headers/footers render per page by Word variant rules (first page /
* odd-even), with real page numbers.
*/
export function PaginationPreview({
section,
sections,
hfParts,
colFlow,
zoom,
hf,
watermark,
pageColor,
blockMetaOf,
pageFootnotesOf,
endnoteItems,
sectionHfOverride,
onExportPdf,
onClose,
}: {
/** Canvas geometry (final section): for the measurement origin / clone width */
section: SectionSettings
/** All sections: for per-page paper geometry (empty array = single section per `section`) */
sections: SectionInfo[]
/** rId → header/footer parts (multi-section picks by each section's references) */
hfParts: Record<string, HfPartInfo>
/** Canvas column-flow geometry (non-null when the canvas column CSS is active): shared by the measuring state / clone wrap width */
colFlow: { cols: number; colWidthPx: number; gapPx: number } | null
zoom: number
hf: HfSet
watermark: string | null
pageColor: string | null
/** docxIndex → parse-layer pagination constraints (keepNext/widow/table-row flags) */
blockMetaOf?: BlockMetaOf
/** Per-page footnote collection (referencing page → entry list), for page-bottom rendering */
pageFootnotesOf?: (blocks: BlockBox[], slices: PageSlice[]) => PageNoteItem[][]
/** Endnote entries (placed together at the document end, take part in slicing, may continue across pages) */
endnoteItems?: PageNoteItem[]
/** Multi-section: unsaved per-section header/footer edit overrides (default variant) */
sectionHfOverride?: (sectionIndex: number, kind: 'header' | 'footer') => HeaderFooter | null
onExportPdf: () => void
onClose: () => void
}) {
const { t } = useI18n()
const [slices, setSlices] = useState<PageSlice[]>([])
const [pageNotes, setPageNotes] = useState<PageNoteItem[][]>([])
/** Top Y of the endnote area (virtual coordinates); null = no endnotes */
const [endnotesTop, setEndnotesTop] = useState<number | null>(null)
const [html, setHtml] = useState('')
/** Live section list: a section whose break block was deleted (unsaved) merges into the next, matching the canvas */
const [secs, setSecs] = useState<SectionInfo[]>(sections)
const canvasContentW = twipsToPx(section.pageWidth - section.marginLeft - section.marginRight)
// clone wrap width = measurement width: a columned canvas measures single-flow at column width; the clone must match to reproduce line breaks
const wrapW = colFlow?.colWidthPx ?? canvasContentW
// canvas content-area top = effective top margin after header push-down (matches --page-pad)
const canvasMTop = effectiveTopPx(
section,
estimateHfHeight(hf.header, canvasContentW, hf.images?.header),
)
/** Settings of the page's section (single-section documents fall back to the canvas geometry) */
const settingsOf = (slice: PageSlice): SectionSettings =>
secs[Math.min(slice.section, secs.length - 1)]?.settings ?? section
useEffect(() => {
const pm = document.querySelector('.editor-scroll .ProseMirror') as HTMLElement | null
if (!pm) return
const factor = zoom / 100
// switch the columned canvas to the single-flow measuring state (CSS columns off, width = column width), matching engine column-flow coordinates
if (colFlow) pm.classList.add('measuring-columns')
try {
const origin = pm.getBoundingClientRect().top + canvasMTop * factor
const { blocks, totalHeight } = measureBlocks(pm, origin, factor)
const live = liveSections(sections, blocks)
setSecs(live)
if (live.length > 0) assignSections(blocks, live)
const withEndnotes = appendEndnotesBlock(
blocks,
totalHeight,
endnoteItems ?? [],
FOOTNOTE_SEPARATOR_H,
)
const flowH = withEndnotes?.totalHeight ?? totalHeight
setEndnotesTop(withEndnotes?.top ?? null)
let computed: PageSlice[]
if (live.length > 0) {
// each section's default-variant header/footer estimated heights → body push-down (matching the canvas)
const refs = effectiveHfRefs(live)
const hfHs: SectionHfHeights[] = live.map((s, i) => {
const set = s.settings
const w = twipsToPx(set.pageWidth - set.marginLeft - set.marginRight)
const pick = (kind: 'header' | 'footer'): HeaderFooter | null => {
if (i === live.length - 1) return kind === 'header' ? hf.header : hf.footer
const ov = sectionHfOverride?.(i, kind)
if (ov) return ov
const rId = refs[i]?.[kind]?.default
const part = rId ? hfParts[rId] : undefined
return part
? { text: part.text, pageNumber: part.hasPageNumber, paras: part.paras }
: null
}
const imagesOf = (kind: 'header' | 'footer') => {
const rId = refs[i]?.[kind]?.default
const fromPart = rId ? hfParts[rId]?.images : undefined
if (fromPart?.length) return fromPart
return i === live.length - 1 ? hf.images?.[kind] : undefined
}
return {
headerPx: estimateHfHeight(pick('header'), w, imagesOf('header')),
footerPx: estimateHfHeight(pick('footer'), w, imagesOf('footer')),
}
})
const geoms = sectionGeoms(live, hfHs)
// when the canvas column CSS is inactive, measure as full-width single flow; the geometry drops column flow to match
if (!colFlow) for (const g of geoms) if (g.cols) g.cols = undefined
computed = sliceWithLineSplit(blocks, geoms, flowH, factor, blockMetaOf)
} else {
const contentH =
twipsToPx(section.pageHeight) -
effectiveTopPx(section, estimateHfHeight(hf.header, canvasContentW, hf.images?.header)) -
effectiveBottomPx(section, estimateHfHeight(hf.footer, canvasContentW, hf.images?.footer))
computed = sliceWithLineSplit(
blocks,
[
{
contentHeight: contentH,
forceBreak: false,
...(colFlow ? { cols: colFlow.cols } : {}),
},
],
flowH,
factor,
blockMetaOf,
)
}
setSlices(computed)
setPageNotes(pageFootnotesOf ? pageFootnotesOf(blocks, computed) : [])
setHtml(pm.innerHTML)
} finally {
if (colFlow) pm.classList.remove('measuring-columns')
}
// snapshot: measure once on open; deps intentionally empty
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.stopPropagation()
onClose()
}
}
window.addEventListener('keydown', onKey, true)
return () => window.removeEventListener('keydown', onKey, true)
}, [onClose])
const multiSection = secs.length > 1
const effRefs = useMemo(() => effectiveHfRefs(secs), [secs])
// single-section also uses pageNumbers: pgNumType w:start renumbering applies to single-section documents too
const nums = useMemo(
() => (secs.length > 0 ? pageNumbers(slices, secs) : slices.map((_, i) => i + 1)),
[slices, secs],
)
const firsts = useMemo(() => sectionFirstPages(slices), [slices])
// line positions of endnote entries in virtual coordinates (matching appendEndnotesBlock's line boxes)
const endnoteRows = useMemo(() => {
if (endnotesTop === null || !endnoteItems || endnoteItems.length === 0) return []
let off = endnotesTop
return endnoteItems.map((item, i) => {
const height = (i === 0 ? FOOTNOTE_SEPARATOR_H : 0) + item.height
const row = { item, top: off, height, withSeparator: i === 0 }
off += height
return row
})
}, [endnotesTop, endnoteItems])
const toHf = (rId: string | undefined): HeaderFooter | null => {
const part = rId ? hfParts[rId] : undefined
if (!part) return null
return {
text: part.text,
pageNumber: part.hasPageNumber,
paras: part.paras.length > 0 ? part.paras : undefined,
}
}
/** Single section: reuse the editing state (unsaved header edits are visible); multi-section: pick parts by each section's references */
const hfFor = (
i: number,
): {
header: HeaderFooter | null
footer: HeaderFooter | null
headerImages?: HfImage[]
footerImages?: HfImage[]
} => {
const pageNo = nums[i]
if (!multiSection) {
if (hf.titlePg && i === 0) {
return {
header: hf.headerFirst,
footer: hf.footerFirst,
headerImages: hf.images?.headerFirst,
footerImages: hf.images?.footerFirst,
}
}
if (hf.evenOddHf && pageNo % 2 === 0) {
return {
header: hf.headerEven,
footer: hf.footerEven,
headerImages: hf.images?.headerEven,
footerImages: hf.images?.footerEven,
}
}
return {
header: hf.header,
footer: hf.footer,
headerImages: hf.images?.header,
footerImages: hf.images?.footer,
}
}
const slice = slices[i]
const sec = secs[Math.min(slice.section, secs.length - 1)]
const refs = effRefs[Math.min(slice.section, effRefs.length - 1)]
const variant =
sec.titlePg && firsts[i] ? 'first' : hf.evenOddHf && pageNo % 2 === 0 ? 'even' : 'default'
// unsaved per-section header/footer edits take priority over document parts (default variant)
const ovHeader = variant === 'default' ? sectionHfOverride?.(slice.section, 'header') : null
const ovFooter = variant === 'default' ? sectionHfOverride?.(slice.section, 'footer') : null
const headerRId = refs.header[variant]
const footerRId = refs.footer[variant]
return {
header: ovHeader ?? toHf(headerRId),
footer: ovFooter ?? toHf(footerRId),
headerImages: headerRId ? hfParts[headerRId]?.images : undefined,
footerImages: footerRId ? hfParts[footerRId]?.images : undefined,
}
}
return (
<div className="pagination-preview">
<div className="pv-toolbar">
<span className="pv-title">{t('appPaginationPreview')}</span>
<span className="pv-count">{t('appTotalPagesN', { n: slices.length })}</span>
<span className="pv-hint">{t('appPvHint')}</span>
<button className="pv-close" title={t('appPvExportTip')} onClick={onExportPdf}>
{t('appExportPdf')}
</button>
<button className="pv-close" onClick={onClose}>
{t('appClose')}
</button>
</div>
<div className="pv-scroll">
{slices.map((slice, i) => {
const parts = hfFor(i)
const s = settingsOf(slice)
const pageBox = sectionPageBox(s)
const pageW = pageBox.width
const pageH = pageBox.height
const secContentW = pageBox.contentWidth
// effective margins after this page's variant header/footer push-down (an over-tall header pushes the body down)
const mTop = effectiveTopPx(s, estimateHfHeight(parts.header, secContentW))
const mBottom = effectiveBottomPx(s, estimateHfHeight(parts.footer, secContentW))
const contentH = pageH - mTop - mBottom
// page vertical alignment (sectPr w:vAlign): content of non-full pages shifts down as a whole
const usedH = Math.min(slice.end - slice.start, contentH)
const vSpare = Math.max(0, contentH - usedH)
const vOffset = s.vAlign === 'center' ? vSpare / 2 : s.vAlign === 'bottom' ? vSpare : 0
// page numbers display in the owning section's number format (w:pgNumType w:fmt)
const pageNoText = formatPageNumber(
nums[i],
secs[Math.min(slice.section, secs.length - 1)]?.pageNumberFmt,
)
return (
<div
key={i}
className="pv-page"
style={
{
width: pageW,
height: pageH,
'--pv-page-h': `${pageH}px`,
'--page-w': `${pageW}px`,
'--page-h': `${pageH}px`,
'--header-dist': `${pageBox.headerDist}px`,
'--footer-dist': `${pageBox.footerDist}px`,
'--pv-mr': `${twipsToPx(s.marginRight)}px`,
padding: `${mTop}px ${twipsToPx(s.marginRight)}px ${mBottom}px ${twipsToPx(s.marginLeft)}px`,
background: pageColor ? `#${pageColor}` : undefined,
} as React.CSSProperties
}
>
{watermark && (
<div className="page-watermark" aria-hidden="true">
{watermark}
</div>
)}
{parts.header && (
<HeaderFooterArea
kind="header"
value={parts.header}
images={parts.headerImages}
readOnly
onCommit={() => {}}
pageNo={pageNoText}
pageTotal={slices.length}
/>
)}
{slice.repeatHeader && !slice.regions && (
// tblHeader repeated headers: a broken table's page first renders a clone of the source table's header rows
// (the engine already reserved repeatHeader.height on this page)
<div className="pv-clip" style={{ height: slice.repeatHeader.height }}>
<div
className="pv-offset"
style={{ marginTop: -slice.repeatHeader.top, width: wrapW }}
>
<div
className="doc-page pv-content"
dangerouslySetInnerHTML={{ __html: html }}
/>
</div>
</div>
)}
{slice.regions ? (
// column flow: regions stack vertically; within a region, columns are narrow-clipped side by side (column-leading repeated headers follow their column)
slice.regions.map((region, ri) => {
const rSec = secs[Math.min(region.section, secs.length - 1)]
const rg = rSec
? sectionColGeom(rSec)
: (colFlow ?? { cols: 1, colWidthPx: canvasContentW, gapPx: 0 })
const extent =
ri + 1 < slice.regions!.length
? slice.regions![ri + 1].top - region.top
: undefined
const multi = rg.cols > 1
return (
<div
key={ri}
className="pv-region"
style={{ gap: rg.gapPx, ...(extent !== undefined ? { height: extent } : {}) }}
>
{region.columns.map((col, ci) => (
<div
key={ci}
className="pv-col"
style={{ width: multi ? rg.colWidthPx : undefined }}
>
{col.repeatHeader && (
<div className="pv-clip" style={{ height: col.repeatHeader.height }}>
<div
className="pv-offset"
style={{ marginTop: -col.repeatHeader.top, width: wrapW }}
>
<div
className="doc-page pv-content"
dangerouslySetInnerHTML={{ __html: html }}
/>
</div>
</div>
)}
<div
className="pv-clip"
style={{
height: Math.min(
col.end - col.start,
region.height - (col.repeatHeader?.height ?? 0),
),
}}
>
<div
className="pv-offset"
style={{ marginTop: -col.start, width: wrapW }}
>
<div
className="doc-page pv-content"
dangerouslySetInnerHTML={{ __html: html }}
/>
</div>
</div>
</div>
))}
</div>
)
})
) : (
<div
className="pv-clip"
style={{
// last page opens to full capacity: slice bounds can drift a few
// lines short of the clone's real height (page-crossing tables),
// silently dropping the document tail from export/print (#86);
// past the real content bottom the window is empty anyway
height:
i === slices.length - 1 && vOffset <= 0.5
? contentH - (slice.repeatHeader?.height ?? 0)
: Math.min(
slice.end - slice.start,
contentH - (slice.repeatHeader?.height ?? 0),
),
...(vOffset > 0.5 ? { marginTop: vOffset } : {}),
}}
>
{/* the offset lives on a separate wrapper: print rules zero out .doc-page's margin;
width is fixed to the measured wrap width (columned canvas = column width), so wider landscape-section paper doesn't reflow */}
<div className="pv-offset" style={{ marginTop: -slice.start, width: wrapW }}>
<div
className="doc-page pv-content"
dangerouslySetInnerHTML={{ __html: html }}
/>
</div>
</div>
)}
{(pageNotes[i]?.length ?? 0) > 0 && (
// page-bottom footnotes (Word behavior: placed at the bottom of the page's content area, separator on top)
<div
className="pv-footnotes"
style={{
left: twipsToPx(s.marginLeft),
width: pageW - twipsToPx(s.marginLeft) - twipsToPx(s.marginRight),
bottom: twipsToPx(s.marginBottom),
height:
pageNotes[i]!.reduce((sum, n) => sum + n.height, 0) + FOOTNOTE_SEPARATOR_H,
}}
>
{pageNotes[i]!.map((n) => (
// entries get fixed heights from the estimates, strictly matching the engine's reservation
<div key={n.id} className="pv-footnote" style={{ height: n.height }}>
<sup>{n.no}</sup>
{n.richParas
? n.richParas.map((para, pi) => (
<span key={pi}>
{pi > 0 && <br />}
{para.map((run, ri) => (
<span
key={ri}
style={{
fontWeight: run.bold ? 600 : undefined,
fontStyle: run.italic ? 'italic' : undefined,
textDecoration:
[run.underline && 'underline', run.strike && 'line-through']
.filter(Boolean)
.join(' ') || undefined,
color: run.color ? `#${run.color}` : undefined,
fontSize: run.sizeHalfPoints
? `${run.sizeHalfPoints / 2}pt`
: undefined,
}}
>
{run.text}
</span>
))}
</span>
))
: n.text}
</div>
))}
</div>
)}
{(() => {
// endnotes: immediately after the body's end, placed on pages per the slices, may continue across pages
const rows = endnoteRows.filter(
(r) => r.top >= slice.start - 0.5 && r.top < slice.end - 0.5,
)
if (rows.length === 0) return null
return (
<div
className={`pv-endnotes${rows[0].withSeparator ? ' with-separator' : ''}`}
style={{
left: twipsToPx(s.marginLeft),
width: pageW - twipsToPx(s.marginLeft) - twipsToPx(s.marginRight),
top: mTop + (slice.repeatHeader?.height ?? 0) + (rows[0].top - slice.start),
}}
>
{rows.map(({ item: n, height, withSeparator }) => (
<div key={n.id} className="pv-footnote" style={{ height }}>
{withSeparator && <div className="pv-endnote-separator" />}
<sup>{toRoman(n.no)}</sup>
{n.richParas
? n.richParas.map((para, pi) => (
<span key={pi}>
{pi > 0 && <br />}
{para.map((run, ri) => (
<span
key={ri}
style={{
fontWeight: run.bold ? 600 : undefined,
fontStyle: run.italic ? 'italic' : undefined,
textDecoration:
[run.underline && 'underline', run.strike && 'line-through']
.filter(Boolean)
.join(' ') || undefined,
color: run.color ? `#${run.color}` : undefined,
fontSize: run.sizeHalfPoints
? `${run.sizeHalfPoints / 2}pt`
: undefined,
}}
>
{run.text}
</span>
))}
</span>
))
: n.text}
</div>
))}
</div>
)
})()}
{parts.footer && (
<HeaderFooterArea
kind="footer"
value={parts.footer}
images={parts.footerImages}
readOnly
onCommit={() => {}}
pageNo={pageNoText}
pageTotal={slices.length}
/>
)}
<div className="pv-pageno">{i + 1}</div>
</div>
)
})}
</div>
</div>
)
}
@@ -0,0 +1,552 @@
/**
* Picture Format dialogs: remove background (tolerance cutout) + crop.
*
* Remove background: same interaction as slides' CutoutDialog — a tolerance slider with live
* preview; the preview computes on a ≤520px downsampled copy, applying recomputes at the
* original resolution and returns a transparent PNG dataUrl.
*
* Crop: drag 8 handles on the preview (or drag inside the box to move) to pick the kept
* region; applying bakes the selection into a new dataUrl at the original resolution
* (png keeps transparency, jpeg stays jpeg). Reuses the .modal-backdrop/.modal styles.
*/
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { removeBackground, sampleBackgroundColors, type PixelImage, type RGB } from '../cutout'
import { useI18n, type StringKey } from '../i18n/locale'
/** Longest side of the preview canvas (px) */
const PREVIEW_MAX = 520
const DEFAULT_TOLERANCE = 30
const CROP_HANDLE_GUTTER = 6
export function fitCropPreview(
naturalWidth: number,
naturalHeight: number,
maxWidth = PREVIEW_MAX,
maxHeight = PREVIEW_MAX,
): { w: number; h: number } {
const scale = Math.min(1, maxWidth / naturalWidth, maxHeight / naturalHeight)
return {
w: Math.max(1, Math.round(naturalWidth * scale)),
h: Math.max(1, Math.round(naturalHeight * scale)),
}
}
/** Checkerboard backdrop: visualizes transparent areas */
const CHECKERBOARD: React.CSSProperties = {
background: 'repeating-conic-gradient(#d5d5d5 0% 25%, #ffffff 0% 50%) 0 0 / 16px 16px',
}
/* ================= Remove background ================= */
interface CutoutProps {
dataUrl: string
/** Apply: the background-removed PNG dataUrl (with alpha channel) */
onApply: (pngDataUrl: string) => void
onCancel: () => void
}
export function CutoutDialog({ dataUrl, onApply, onCancel }: CutoutProps) {
const { t } = useI18n()
const [tolerance, setTolerance] = useState(DEFAULT_TOLERANCE)
const [loaded, setLoaded] = useState(false)
const [error, setError] = useState<StringKey | null>(null)
const [removedPct, setRemovedPct] = useState(0)
const [applying, setApplying] = useState(false)
const canvasRef = useRef<HTMLCanvasElement>(null)
/** Original-resolution pixels (used on apply) */
const fullRef = useRef<PixelImage | null>(null)
/** Downsampled pixels (for the slider's live preview) */
const previewRef = useRef<PixelImage | null>(null)
/** Background representative colors (from original-resolution border sampling, shared by preview/apply for consistency) */
const bgColorsRef = useRef<RGB[]>([])
const rafRef = useRef<number | null>(null)
const renderPreview = useCallback((tol: number) => {
const pv = previewRef.current
const canvas = canvasRef.current
if (!pv || !canvas) return
const result = removeBackground(pv, tol, bgColorsRef.current)
canvas.getContext('2d')!.putImageData(new ImageData(result.data, pv.width, pv.height), 0, 0)
setRemovedPct(Math.round((result.removedCount / (pv.width * pv.height)) * 100))
}, [])
useEffect(() => {
let cancelled = false
const img = new Image()
img.onload = () => {
if (cancelled) return
const w = img.naturalWidth
const h = img.naturalHeight
if (!w || !h) {
setError('ribbonImageLoadFail')
return
}
const grab = (dw: number, dh: number): PixelImage => {
const c = document.createElement('canvas')
c.width = dw
c.height = dh
const ctx = c.getContext('2d')!
ctx.drawImage(img, 0, 0, dw, dh)
const d = ctx.getImageData(0, 0, dw, dh)
return { data: d.data, width: dw, height: dh }
}
const full = grab(w, h)
const scale = Math.min(1, PREVIEW_MAX / Math.max(w, h))
const preview =
scale < 1
? grab(Math.max(1, Math.round(w * scale)), Math.max(1, Math.round(h * scale)))
: full
fullRef.current = full
previewRef.current = preview
bgColorsRef.current = sampleBackgroundColors(full)
const canvas = canvasRef.current
if (canvas) {
canvas.width = preview.width
canvas.height = preview.height
}
setLoaded(true)
renderPreview(DEFAULT_TOLERANCE)
}
img.onerror = () => {
if (!cancelled) setError('ribbonImageLoadFail')
}
img.src = dataUrl
return () => {
cancelled = true
}
}, [dataUrl, renderPreview])
const onTolerance = (v: number) => {
setTolerance(v)
if (rafRef.current != null) cancelAnimationFrame(rafRef.current)
rafRef.current = requestAnimationFrame(() => {
rafRef.current = null
renderPreview(v)
})
}
useEffect(
() => () => {
if (rafRef.current != null) cancelAnimationFrame(rafRef.current)
},
[],
)
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault()
onCancel()
}
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onCancel])
const apply = () => {
const full = fullRef.current
if (!full || applying) return
setApplying(true)
// let the "processing…" state render before the heavy recompute
window.setTimeout(() => {
try {
const result = removeBackground(full, tolerance, bgColorsRef.current)
const c = document.createElement('canvas')
c.width = full.width
c.height = full.height
c.getContext('2d')!.putImageData(new ImageData(result.data, full.width, full.height), 0, 0)
onApply(c.toDataURL('image/png'))
} catch {
setApplying(false)
setError('ribbonImageProcessFail')
}
}, 30)
}
return (
<div className="modal-backdrop" onClick={onCancel}>
<div
className="modal"
style={{ maxWidth: PREVIEW_MAX + 48 }}
onClick={(e) => e.stopPropagation()}
>
<h2>{t('ribbonRemoveBg')}</h2>
<div
style={{
...CHECKERBOARD,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
minHeight: 160,
maxHeight: PREVIEW_MAX,
borderRadius: 4,
overflow: 'hidden',
}}
>
{error ? (
<span
style={{ color: '#c33', background: '#fff', padding: '4px 10px', borderRadius: 4 }}
>
{t(error)}
</span>
) : (
<canvas
ref={canvasRef}
style={{
maxWidth: '100%',
maxHeight: PREVIEW_MAX,
display: loaded ? 'block' : 'none',
}}
/>
)}
{!loaded && !error && <span style={{ color: '#888' }}>{t('ribbonLoading')}</span>}
</div>
<label style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12 }}>
<span style={{ whiteSpace: 'nowrap' }}>{t('ribbonCutoutTolerance')}</span>
<input
type="range"
min={0}
max={100}
step={1}
value={tolerance}
disabled={!loaded || applying}
onChange={(e) => onTolerance(Number(e.target.value))}
style={{ flex: 1 }}
/>
<span style={{ width: 32, textAlign: 'right' }}>{tolerance}</span>
</label>
<div style={{ fontSize: 12, color: '#888', marginTop: 4 }}>
{t('ribbonCutoutHint', { pct: removedPct })}
</div>
<div className="modal-actions">
<button onClick={onCancel} disabled={applying}>
{t('ribbonCancel')}
</button>
<button className="primary" onClick={apply} disabled={!loaded || !!error || applying}>
{applying ? t('ribbonProcessing') : t('ribbonApply')}
</button>
</div>
</div>
</div>
)
}
/* ================= Crop ================= */
/** Crop region (0..1 ratios, relative to the whole image) */
interface CropRect {
l: number
t: number
r: number
b: number
}
type CropHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'move'
/** Minimum crop-box side (preview px), prevents dragging to 0 */
const MIN_CROP_PX = 16
interface CropProps {
dataUrl: string
/** Apply: the cropped dataUrl (png/jpeg follows the original format) */
onApply: (croppedDataUrl: string) => void
onCancel: () => void
}
export function CropDialog({ dataUrl, onApply, onCancel }: CropProps) {
const { t } = useI18n()
const [loaded, setLoaded] = useState(false)
const [error, setError] = useState<StringKey | null>(null)
const [crop, setCrop] = useState<CropRect>({ l: 0, t: 0, r: 1, b: 1 })
/** Preview display size (CSS px) */
const [view, setView] = useState<{ w: number; h: number } | null>(null)
const imgRef = useRef<HTMLImageElement | null>(null)
const boxRef = useRef<HTMLDivElement>(null)
const dragRef = useRef<{
handle: CropHandle
startX: number
startY: number
start: CropRect
} | null>(null)
const updateView = useCallback(() => {
const img = imgRef.current
if (!img) return
const maxWidth = Math.max(80, Math.min(PREVIEW_MAX, window.innerWidth - 92))
const maxHeight = Math.max(80, Math.min(PREVIEW_MAX, window.innerHeight - 220))
setView(fitCropPreview(img.naturalWidth, img.naturalHeight, maxWidth, maxHeight))
}, [])
useEffect(() => {
document.body.classList.add('docs-crop-active')
return () => document.body.classList.remove('docs-crop-active')
}, [])
useEffect(() => {
window.addEventListener('resize', updateView)
return () => window.removeEventListener('resize', updateView)
}, [updateView])
useEffect(() => {
let cancelled = false
const img = new Image()
img.onload = () => {
if (cancelled) return
if (!img.naturalWidth || !img.naturalHeight) {
setError('ribbonImageLoadFail')
return
}
imgRef.current = img
updateView()
setLoaded(true)
}
img.onerror = () => {
if (!cancelled) setError('ribbonImageLoadFail')
}
img.src = dataUrl
return () => {
cancelled = true
}
}, [dataUrl, updateView])
const apply = useCallback(() => {
const img = imgRef.current
if (!img) return
const w = img.naturalWidth
const h = img.naturalHeight
const sx = Math.round(crop.l * w)
const sy = Math.round(crop.t * h)
const sw = Math.max(1, Math.round((crop.r - crop.l) * w))
const sh = Math.max(1, Math.round((crop.b - crop.t) * h))
try {
const c = document.createElement('canvas')
c.width = sw
c.height = sh
c.getContext('2d')!.drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh)
// jpeg has no alpha channel; keep jpeg to avoid size bloat. Others (png/gif) all output png to preserve transparency
const isJpeg = /^data:image\/jpeg/.test(dataUrl)
onApply(isJpeg ? c.toDataURL('image/jpeg', 0.92) : c.toDataURL('image/png'))
} catch {
setError('ribbonImageProcessFail')
}
}, [crop, dataUrl, onApply])
// Esc cancels / Enter applies
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault()
onCancel()
} else if (e.key === 'Enter' && loaded && !error) {
e.preventDefault()
apply()
}
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onCancel, apply, loaded, error])
const startDrag = (handle: CropHandle) => (e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
dragRef.current = { handle, startX: e.clientX, startY: e.clientY, start: crop }
}
useEffect(() => {
if (!view) return
const minW = MIN_CROP_PX / view.w
const minH = MIN_CROP_PX / view.h
const onMove = (e: MouseEvent) => {
const drag = dragRef.current
if (!drag) return
const dx = (e.clientX - drag.startX) / view.w
const dy = (e.clientY - drag.startY) / view.h
const s = drag.start
let { l, t, r, b } = s
if (drag.handle === 'move') {
const w = s.r - s.l
const h = s.b - s.t
l = Math.min(Math.max(0, s.l + dx), 1 - w)
t = Math.min(Math.max(0, s.t + dy), 1 - h)
r = l + w
b = t + h
} else {
if (drag.handle.includes('w')) l = Math.min(Math.max(0, s.l + dx), s.r - minW)
if (drag.handle.includes('e')) r = Math.max(Math.min(1, s.r + dx), s.l + minW)
if (drag.handle.includes('n')) t = Math.min(Math.max(0, s.t + dy), s.b - minH)
if (drag.handle.includes('s')) b = Math.max(Math.min(1, s.b + dy), s.t + minH)
}
setCrop({ l, t, r, b })
}
const onUp = () => {
dragRef.current = null
}
window.addEventListener('mousemove', onMove)
window.addEventListener('mouseup', onUp)
return () => {
window.removeEventListener('mousemove', onMove)
window.removeEventListener('mouseup', onUp)
}
}, [view])
/** Shared handle style */
const handleStyle = (pos: CropHandle): React.CSSProperties => {
const base: React.CSSProperties = {
position: 'absolute',
width: 10,
height: 10,
background: '#fff',
border: '1.5px solid #2b5797',
borderRadius: 2,
boxSizing: 'border-box',
zIndex: 2,
}
const cursors: Record<string, string> = {
nw: 'nwse-resize',
se: 'nwse-resize',
ne: 'nesw-resize',
sw: 'nesw-resize',
n: 'ns-resize',
s: 'ns-resize',
e: 'ew-resize',
w: 'ew-resize',
}
base.cursor = cursors[pos]
if (pos.includes('n')) base.top = -5
if (pos.includes('s')) base.bottom = -5
if (pos.includes('w')) base.left = -5
if (pos.includes('e')) base.right = -5
if (pos === 'n' || pos === 's') {
base.left = '50%'
base.marginLeft = -5
}
if (pos === 'e' || pos === 'w') {
base.top = '50%'
base.marginTop = -5
}
return base
}
const HANDLES: CropHandle[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']
return (
<div className="modal-backdrop" onClick={onCancel}>
<div
className="modal crop-modal"
style={{
width: PREVIEW_MAX + 48 + CROP_HANDLE_GUTTER * 2,
maxWidth: 'calc(100vw - 32px)',
maxHeight: 'calc(100vh - 32px)',
boxSizing: 'border-box',
overflowY: 'auto',
}}
onClick={(e) => e.stopPropagation()}
>
<h2>{t('ribbonCrop')}</h2>
<div
style={{
...CHECKERBOARD,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
minHeight: 160,
borderRadius: 4,
padding: CROP_HANDLE_GUTTER,
boxSizing: 'border-box',
overflow: 'hidden',
}}
>
{error ? (
<span
style={{ color: '#c33', background: '#fff', padding: '4px 10px', borderRadius: 4 }}
>
{t(error)}
</span>
) : loaded && view ? (
<div
ref={boxRef}
style={{ position: 'relative', width: view.w, height: view.h, userSelect: 'none' }}
>
<img
src={dataUrl}
width={view.w}
height={view.h}
draggable={false}
style={{ display: 'block' }}
/>
{/* the four masks outside the crop box */}
{(() => {
const px = (v: number, total: number) => Math.round(v * total)
const dim: React.CSSProperties = {
position: 'absolute',
background: 'rgba(0,0,0,0.45)',
}
return (
<>
<div
style={{ ...dim, left: 0, top: 0, width: '100%', height: px(crop.t, view.h) }}
/>
<div
style={{
...dim,
left: 0,
bottom: 0,
width: '100%',
height: view.h - px(crop.b, view.h),
}}
/>
<div
style={{
...dim,
left: 0,
top: px(crop.t, view.h),
width: px(crop.l, view.w),
height: px(crop.b, view.h) - px(crop.t, view.h),
}}
/>
<div
style={{
...dim,
right: 0,
top: px(crop.t, view.h),
width: view.w - px(crop.r, view.w),
height: px(crop.b, view.h) - px(crop.t, view.h),
}}
/>
</>
)
})()}
{/* crop box + handles */}
<div
style={{
position: 'absolute',
left: `${crop.l * 100}%`,
top: `${crop.t * 100}%`,
width: `${(crop.r - crop.l) * 100}%`,
height: `${(crop.b - crop.t) * 100}%`,
border: '1.5px solid #2b5797',
boxSizing: 'border-box',
cursor: 'move',
}}
onMouseDown={startDrag('move')}
>
{HANDLES.map((pos) => (
<div key={pos} style={handleStyle(pos)} onMouseDown={startDrag(pos)} />
))}
</div>
</div>
) : (
<span style={{ color: '#888' }}>{t('ribbonLoading')}</span>
)}
</div>
<div style={{ fontSize: 12, color: '#888', marginTop: 8 }}>{t('ribbonCropHint')}</div>
<div className="modal-actions">
<button onClick={onCancel}>{t('ribbonCancel')}</button>
<button className="primary" onClick={apply} disabled={!loaded || !!error}>
{t('ribbonApply')}
</button>
</div>
</div>
</div>
)
}
@@ -0,0 +1,81 @@
import { useEffect, useRef, useState } from 'react'
import { useI18n } from '../i18n/locale'
/**
* In-app replacement for window.prompt, which Electron renderers do not
* support. Single-line by default; multiline renders a textarea (notes).
*/
export function PromptModal({
title,
placeholder,
initial = '',
multiline = false,
allowEmpty = false,
onSubmit,
onClose,
}: {
title: string
placeholder?: string
initial?: string
multiline?: boolean
/** submit button stays enabled for empty input (e.g. clearing a value) */
allowEmpty?: boolean
onSubmit: (value: string) => void
onClose: () => void
}) {
const { t } = useI18n()
const [value, setValue] = useState(initial)
const inputRef = useRef<HTMLInputElement>(null)
const textareaRef = useRef<HTMLTextAreaElement>(null)
useEffect(() => {
const el = multiline ? textareaRef.current : inputRef.current
el?.focus()
el?.select()
}, [multiline])
const submit = () => {
if (!allowEmpty && !value.trim()) return
onSubmit(value.trim())
onClose()
}
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal">
<h2>{title}</h2>
<label>
{multiline ? (
<textarea
ref={textareaRef}
className="prompt-textarea"
rows={4}
value={value}
placeholder={placeholder}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) submit()
}}
/>
) : (
<input
ref={inputRef}
value={value}
placeholder={placeholder}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') submit()
}}
/>
)}
</label>
<div className="modal-actions">
<button className="btn-ghost" onClick={onClose}>{t('appCancel')}</button>
<button className="btn-primary" disabled={!allowEmpty && !value.trim()} onClick={submit}>
{t('appOk')}
</button>
</div>
</div>
</div>
)
}
File diff suppressed because it is too large Load Diff
+190
View File
@@ -0,0 +1,190 @@
import { useRef, useState } from 'react'
import type { MouseEvent as ReactMouseEvent } from 'react'
import type { Editor } from '@tiptap/core'
import type { SectionSettings, TabStop } from '@genoffice/docx-engine'
import { t, type StringKey } from '../i18n/locale'
const twipsToPx = (twips: number) => (twips / 1440) * 96
/** Horizontal ruler above the page: inch numbers, gray margin zones, tab stops. */
export function Ruler({
section,
editor,
onTabStopsChange,
}: {
section: SectionSettings
editor: Editor | null
onTabStopsChange: (stops: TabStop[] | null) => void
}) {
const width = twipsToPx(section.pageWidth)
const marginLeft = twipsToPx(section.marginLeft)
const marginRight = twipsToPx(section.marginRight)
const inches = Math.floor(section.pageWidth / 1440)
const ticks: number[] = []
for (let i = 1; i <= inches; i++) ticks.push(i)
// Default Word tab interval: 0.5in = 720 twips
const DEFAULT_TAB_TWIPS = 720
// Tab stop type cycling (Word: click ruler button to cycle L/C/R/Decimal/Bar)
const [nextTabType, setNextTabType] = useState<TabStop['val']>('left')
const TAB_TYPE_CYCLE: TabStop['val'][] = ['left', 'center', 'right', 'decimal']
const TAB_TYPE_LABELS: Record<string, string> = {
left: 'L',
center: '⊥',
right: '⌐',
decimal: '.',
bar: '|',
}
const TAB_TYPE_NAME_KEYS: Record<TabStop['val'], StringKey> = {
left: 'appTabLeft',
center: 'appTabCenter',
right: 'appTabRight',
decimal: 'appTabDecimal',
bar: 'appTabBar',
clear: 'appTabBar',
}
// Get current tab stops from focused paragraph
const currentTabStops = (): TabStop[] => {
if (!editor) return []
const attrs = editor.isActive('docHeading')
? editor.getAttributes('docHeading')
: editor.isActive('docListItem')
? editor.getAttributes('docListItem')
: editor.getAttributes('docParagraph')
const raw = attrs?.tabStops as string | null
if (!raw) return []
try {
const parsed = JSON.parse(raw)
return Array.isArray(parsed) ? parsed : []
} catch {
return []
}
}
const stops = currentTabStops()
// Drag state
const dragRef = useRef<{ stopIndex: number; startX: number; origPos: number } | null>(null)
// Click on ruler: add tab stop at position, skip margin zones
const handleRulerClick = (e: ReactMouseEvent<HTMLDivElement>) => {
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
const x = e.clientX - rect.left
if (x < marginLeft || x > width - marginRight) return
const posTwips = Math.round((x / width) * section.pageWidth)
// snap to nearest 60 twips (~0.04in)
const snapped = Math.round(posTwips / 60) * 60
const existing = stops.filter((s) => Math.abs(s.pos - snapped) > 60)
const newStop: TabStop = { pos: snapped, val: nextTabType }
const newStops = [...existing, newStop].sort((a, b) => a.pos - b.pos)
onTabStopsChange(newStops.length > 0 ? newStops : null)
}
// Drag tab stop to new position or drop outside to delete
const handleTabMouseDown = (e: ReactMouseEvent<HTMLSpanElement>, stopIndex: number) => {
e.stopPropagation()
e.preventDefault()
const rect = (e.currentTarget.closest('.ruler') as HTMLElement).getBoundingClientRect()
dragRef.current = { stopIndex, startX: e.clientX, origPos: stops[stopIndex].pos }
const onMouseMove = (ev: MouseEvent) => {
if (!dragRef.current) return
const x = ev.clientX - rect.left
const posTwips = Math.round((x / width) * section.pageWidth)
const snapped = Math.round(posTwips / 60) * 60
// visual only update via CSS custom property (no state update for perf)
const marker = document.querySelector(
`[data-ruler-stop="${stopIndex}"]`,
) as HTMLElement | null
if (marker) marker.style.left = `${twipsToPx(snapped)}px`
}
const onMouseUp = (ev: MouseEvent) => {
document.removeEventListener('mousemove', onMouseMove)
document.removeEventListener('mouseup', onMouseUp)
if (!dragRef.current) return
const x = ev.clientX - rect.left
// drop outside the content area: delete the stop
if (x < marginLeft || x > width - marginRight) {
const newStops = stops.filter((_, i) => i !== dragRef.current!.stopIndex)
onTabStopsChange(newStops.length > 0 ? newStops : null)
} else {
const posTwips = Math.round((x / width) * section.pageWidth)
const snapped = Math.round(posTwips / 60) * 60
const newStops = stops
.map((s, i) => (i === dragRef.current!.stopIndex ? { ...s, pos: snapped } : s))
.sort((a, b) => a.pos - b.pos)
onTabStopsChange(newStops)
}
dragRef.current = null
}
document.addEventListener('mousemove', onMouseMove)
document.addEventListener('mouseup', onMouseUp)
}
// Default tab stop markers (light gray) when no custom stops defined
const defaultStops: number[] = []
if (stops.length === 0) {
const contentWidth = section.pageWidth - section.marginLeft - section.marginRight
for (let pos = DEFAULT_TAB_TWIPS; pos < contentWidth; pos += DEFAULT_TAB_TWIPS) {
defaultStops.push(section.marginLeft + pos)
}
}
return (
<div className="ruler" style={{ width }} onClick={handleRulerClick}>
{/* Tab type selector button at far left */}
<button
className="ruler-tab-type"
title={t('appTabTypeTip', { type: t(TAB_TYPE_NAME_KEYS[nextTabType]) })}
onClick={(e) => {
e.stopPropagation()
const idx = TAB_TYPE_CYCLE.indexOf(nextTabType)
setNextTabType(TAB_TYPE_CYCLE[(idx + 1) % TAB_TYPE_CYCLE.length])
}}
>
{TAB_TYPE_LABELS[nextTabType]}
</button>
<div className="ruler-zone" style={{ left: 0, width: marginLeft }} />
<div className="ruler-zone" style={{ left: width - marginRight, width: marginRight }} />
{ticks.map((i) => (
<span key={i} className="ruler-num" style={{ left: twipsToPx(i * 1440) }}>
{i}
</span>
))}
{/* Default tab stop guides (light, no interaction) */}
{defaultStops.map((posTwips) => (
<span
key={`def-${posTwips}`}
className="ruler-tab-default"
style={{ left: twipsToPx(posTwips) }}
/>
))}
{/* Custom tab stops (interactive) */}
{stops.map((stop, i) => (
<span
key={`${stop.pos}-${i}`}
data-ruler-stop={i}
className={`ruler-tab ruler-tab-${stop.val}`}
style={{ left: twipsToPx(stop.pos) }}
title={
t('appTabStopTitle', {
type: t(TAB_TYPE_NAME_KEYS[stop.val]),
pos: Math.round((stop.pos / 144) * 10) / 10,
}) + (stop.leader ? t('appTabLeader', { leader: stop.leader }) : '')
}
onMouseDown={(e) => handleTabMouseDown(e, i)}
>
{TAB_TYPE_LABELS[stop.val]}
</span>
))}
</div>
)
}
@@ -0,0 +1,143 @@
import { useEffect, useState } from 'react'
import type { CSSProperties } from 'react'
import type { StyleInfo } from '@genoffice/docx-engine'
import { useI18n } from '../i18n/locale'
import { cssFontFamily } from '../line-metrics'
/**
* Styles popup (Word's styles dialog): lists the document's paragraph/character
* styles, click to apply; "Update" rewrites the style definition from the current
* selection's formatting (styles.xml upsert), and the bottom row creates a new
* style from the selection. Style edits/creations go through
* SaveOptions.styleUpserts and the canvas CSS refreshes immediately.
*/
export function StylesPanel({
styles,
activeParaStyleId,
onApply,
onUpdateFromSelection,
onCreateFromSelection,
onClose,
}: {
styles: Map<string, StyleInfo>
activeParaStyleId: string | null
/** Apply a style: type decides paragraph (styleId attr) vs character (docTextStyle mark) */
onApply: (styleId: string, type: 'paragraph' | 'character') => void
onUpdateFromSelection: (styleId: string, type: 'paragraph' | 'character', name: string) => void
onCreateFromSelection: (name: string, type: 'paragraph' | 'character') => void
onClose: () => void
}) {
const { t } = useI18n()
const [newName, setNewName] = useState('')
const [newType, setNewType] = useState<'paragraph' | 'character'>('paragraph')
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
}
window.addEventListener('keydown', onKeyDown)
return () => window.removeEventListener('keydown', onKeyDown)
}, [onClose])
const previewCss = (info: StyleInfo): CSSProperties => {
const d = info.display
const css: CSSProperties = {}
if (d?.bold) css.fontWeight = 600
if (d?.italic) css.fontStyle = 'italic'
if (d?.underline) css.textDecoration = 'underline'
if (d?.color) css.color = `#${d.color}`
if (d?.sizeHalfPoints) css.fontSize = `${Math.min(d.sizeHalfPoints / 2, 18)}pt`
if (d?.font) css.fontFamily = cssFontFamily(d.font)
return css
}
const groups: Array<{ label: string; type: 'paragraph' | 'character'; items: StyleInfo[] }> = [
{ label: t('appParagraphStyles'), type: 'paragraph', items: [] },
{ label: t('appCharacterStyles'), type: 'character', items: [] },
]
for (const info of styles.values()) {
if (info.type === 'paragraph') groups[0].items.push(info)
else if (info.type === 'character' && info.styleId !== 'FollowedHyperlink') {
groups[1].items.push(info)
}
}
const create = () => {
const name = newName.trim()
if (!name) return
onCreateFromSelection(name, newType)
setNewName('')
}
return (
<div className="modal-backdrop" onClick={onClose}>
<div className="styles-modal" onClick={(e) => e.stopPropagation()}>
<div className="styles-panel-head">
<span>{t('appStylesTitle')}</span>
<button className="styles-panel-close" onClick={onClose} title={t('appClose')}>
×
</button>
</div>
<div className="styles-panel-body">
{groups.map(
(group) =>
group.items.length > 0 && (
<div key={group.type}>
<div className="styles-panel-group">{group.label}</div>
{group.items.map((info) => (
<div
key={info.styleId}
className={`styles-panel-row ${
group.type === 'paragraph' && info.styleId === activeParaStyleId
? 'active'
: ''
}`}
>
<button
className="styles-panel-name"
style={previewCss(info)}
title={t('appApplyStyle', { name: info.name })}
onClick={() => onApply(info.styleId, group.type)}
>
{info.name}
</button>
<button
className="styles-panel-update"
title={t('appUpdateStyleTip')}
onClick={() => onUpdateFromSelection(info.styleId, group.type, info.name)}
>
{t('appUpdate')}
</button>
</div>
))}
</div>
),
)}
</div>
<div className="styles-panel-new">
<div className="styles-panel-group">{t('appNewStyleFromSelection')}</div>
<div className="styles-panel-new-row">
<input
value={newName}
placeholder={t('appStyleNamePlaceholder')}
onChange={(e) => setNewName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') create()
}}
/>
<select
value={newType}
onChange={(e) => setNewType(e.target.value as 'paragraph' | 'character')}
>
<option value="paragraph">{t('appParagraph')}</option>
<option value="character">{t('appCharacter')}</option>
</select>
<button disabled={!newName.trim()} onClick={create}>
{t('appNew')}
</button>
</div>
</div>
</div>
</div>
)
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,500 @@
import { useState } from 'react'
import { type SectionSettings, type ThemeColors, type ThemeFonts } from '@genoffice/docx-engine'
import { PromptModal } from './PromptModal'
import { useI18n, type StringKey } from '../i18n/locale'
import {
IconCaret,
IconPageBorders,
IconPageColor,
IconTheme,
IconThemeColors,
IconThemeFonts,
IconWatermark,
} from './icons'
/** icon size for the big icon-over-label ribbon buttons (slides ribbon parity) */
import { BIG, TabProps, toggleDropdown } from './ribbon-tabs'
const PAGE_COLORS: Array<{ nameKey: StringKey; hex: string | null }> = [
{ nameKey: 'ribbonColorWhite', hex: null },
{ nameKey: 'ribbonColorLightYellow', hex: 'FFF9E6' },
{ nameKey: 'ribbonColorBeige', hex: 'F5F0E6' },
{ nameKey: 'ribbonColorLightGreen', hex: 'EAF5EA' },
{ nameKey: 'ribbonColorLightBlue', hex: 'E8F1FB' },
{ nameKey: 'ribbonColorLightPurple', hex: 'F3EEFB' },
{ nameKey: 'ribbonColorLightGray', hex: 'F2F2F2' },
{ nameKey: 'ribbonColorDarkGray', hex: '333333' },
{ nameKey: 'ribbonColorBlack', hex: '000000' },
]
/** Word-like theme presets: font pair + color scheme applied together */
const THEME_PRESETS: Array<{ nameKey: StringKey; fonts: ThemeFonts; colors: ThemeColors }> = [
{
nameKey: 'ribbonThemeOffice',
fonts: { major: 'Calibri Light', minor: 'Calibri', eastAsia: '等线' },
colors: {
name: 'Office',
dk2: '44546A',
lt2: 'E7E6E6',
accent1: '4472C4',
accent2: 'ED7D31',
accent3: 'A5A5A5',
accent4: 'FFC000',
accent5: '5B9BD5',
accent6: '70AD47',
},
},
{
nameKey: 'ribbonThemeFacet',
fonts: { major: 'Trebuchet MS', minor: 'Trebuchet MS', eastAsia: '微软雅黑' },
colors: {
name: 'Facet',
dk2: '3E3D2D',
lt2: 'E1DFDD',
accent1: '90C226',
accent2: '54A021',
accent3: 'E6B91E',
accent4: 'E76618',
accent5: 'C42F1A',
accent6: '918655',
},
},
{
nameKey: 'ribbonThemeIon',
fonts: { major: 'Century Gothic', minor: 'Century Gothic', eastAsia: '黑体' },
colors: {
name: 'Ion',
dk2: '1B587C',
lt2: 'E8ECEE',
accent1: '4E8542',
accent2: '604878',
accent3: 'C19859',
accent4: 'CA7B4F',
accent5: '415D6B',
accent6: '8EA5AF',
},
},
{
nameKey: 'ribbonThemeRetrospect',
fonts: { major: 'Calibri Light', minor: 'Calibri', eastAsia: '仿宋' },
colors: {
name: 'Retrospect',
dk2: '637052',
lt2: 'CCDDEA',
accent1: 'E48312',
accent2: 'BD582C',
accent3: '865640',
accent4: '9B8357',
accent5: 'C2BC80',
accent6: '94A088',
},
},
]
const THEME_FONT_PRESETS: Array<{ nameKey: StringKey; fonts: ThemeFonts }> = [
{
nameKey: 'ribbonThemeFontOffice',
fonts: { major: 'Calibri Light', minor: 'Calibri', eastAsia: '等线' },
},
{ nameKey: 'ribbonThemeFontSongti', fonts: { major: '黑体', minor: '宋体', eastAsia: '宋体' } },
{
nameKey: 'ribbonThemeFontYahei',
fonts: { major: '微软雅黑', minor: '微软雅黑', eastAsia: '微软雅黑' },
},
{ nameKey: 'ribbonThemeFontKaiti', fonts: { major: '楷体', minor: '楷体', eastAsia: '楷体' } },
{
nameKey: 'ribbonThemeFontTimes',
fonts: { major: 'Times New Roman', minor: 'Times New Roman', eastAsia: '宋体' },
},
{ nameKey: 'ribbonThemeFontArial', fonts: { major: 'Arial', minor: 'Arial', eastAsia: '黑体' } },
]
const THEME_COLOR_PRESETS: Array<{ nameKey: StringKey; colors: ThemeColors }> = [
{
nameKey: 'ribbonThemeOffice',
colors: {
name: 'Office',
dk2: '44546A',
lt2: 'E7E6E6',
accent1: '4472C4',
accent2: 'ED7D31',
accent3: 'A5A5A5',
accent4: 'FFC000',
accent5: '5B9BD5',
accent6: '70AD47',
},
},
{
nameKey: 'ribbonPaletteGrayscale',
colors: {
name: 'Grayscale',
dk2: '3F3F3F',
lt2: 'B3B3B3',
accent1: '5B5B5B',
accent2: '8C8C8C',
accent3: 'A6A6A6',
accent4: '737373',
accent5: '404040',
accent6: 'D9D9D9',
},
},
{
nameKey: 'ribbonColorBlue',
colors: {
name: 'Blue',
dk2: '17406D',
lt2: 'DBEFF9',
accent1: '0F6FC6',
accent2: '009DD9',
accent3: '0BD0D9',
accent4: '10CF9B',
accent5: '7CCA62',
accent6: 'A5C249',
},
},
{
nameKey: 'ribbonColorGreen',
colors: {
name: 'Green',
dk2: '455F51',
lt2: 'E3DED1',
accent1: '549E39',
accent2: '8AB833',
accent3: 'C0CF3A',
accent4: '029676',
accent5: '4AB5C4',
accent6: '0989B1',
},
},
{
nameKey: 'ribbonPaletteRedViolet',
colors: {
name: 'Red Violet',
dk2: '5F5F5F',
lt2: 'FFFDF7',
accent1: 'A83D4C',
accent2: 'D2554B',
accent3: 'E1734C',
accent4: '8D3B4B',
accent5: '54387F',
accent6: '7A99AC',
},
},
{
nameKey: 'ribbonColorOrange',
colors: {
name: 'Orange',
dk2: '637052',
lt2: 'CCDDEA',
accent1: 'E48312',
accent2: 'BD582C',
accent3: '865640',
accent4: '9B8357',
accent5: 'C2BC80',
accent6: '94A088',
},
},
]
const WATERMARK_KEYS: StringKey[] = [
'ribbonWatermarkConfidential',
'ribbonWatermarkNoCopy',
'ribbonWatermarkDraft',
'ribbonWatermarkSample',
]
interface DesignTabProps extends TabProps {
pageColor: string | null
onPageColor: (hex: string | null) => void
section: SectionSettings | null
onSection: (next: SectionSettings) => void
watermark: string | null
onWatermark: (text: string | null) => void
themeFonts: ThemeFonts | null
onThemeFonts: (fonts: ThemeFonts) => void
onThemeColors: (colors: ThemeColors) => void
}
export function DesignTab({
hasDoc,
dropdown,
setDropdown,
pageColor,
onPageColor,
section,
onSection,
watermark,
onWatermark,
themeFonts,
onThemeFonts,
onThemeColors,
}: DesignTabProps) {
const { t, lang } = useI18n()
const watermarkPresets = [
...WATERMARK_KEYS.map((key) => t(key)),
...(lang !== 'en' ? ['CONFIDENTIAL', 'DRAFT'] : []),
]
const [watermarkPromptOpen, setWatermarkPromptOpen] = useState(false)
const applyTheme = (preset: (typeof THEME_PRESETS)[number]) => {
onThemeFonts(preset.fonts)
onThemeColors(preset.colors)
setDropdown(() => null)
}
const customWatermark = () => {
setWatermarkPromptOpen(true)
setDropdown(() => null)
}
return (
<>
<div className="ribbon-group">
<div className="ribbon-group-items">
<div className="rb-split-wrap">
<button
className="rb-big"
disabled={!hasDoc}
title={t('ribbonThemesTip')}
onClick={() => toggleDropdown(setDropdown, 'theme')}
>
<span className="rb-big-icon">
<IconTheme size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonThemes')}</span>
</button>
{dropdown === 'theme' && (
<div className="layout-menu">
{THEME_PRESETS.map((p) => (
<button key={p.nameKey} onClick={() => applyTheme(p)}>
<span className="theme-accent-row">
{['accent1', 'accent2', 'accent3', 'accent4'].map((k) => (
<span
key={k}
className="theme-accent-dot"
style={{ background: `#${p.colors[k as 'accent1']}` }}
/>
))}
</span>
{t(p.nameKey)}
</button>
))}
</div>
)}
</div>
<div className="rb-split-wrap">
<button
className="rb-big"
disabled={!hasDoc}
title={t('ribbonThemeFontsTip')}
onClick={() => toggleDropdown(setDropdown, 'themefonts')}
>
<span className="rb-big-icon">
<IconThemeFonts size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonFonts')}</span>
</button>
{dropdown === 'themefonts' && (
<div className="layout-menu">
{THEME_FONT_PRESETS.map((p) => (
<button
key={p.nameKey}
className={
themeFonts?.minor === p.fonts.minor && themeFonts?.major === p.fonts.major
? 'active'
: ''
}
onClick={() => {
onThemeFonts(p.fonts)
setDropdown(() => null)
}}
>
{t(p.nameKey)}
</button>
))}
</div>
)}
</div>
<div className="rb-split-wrap">
<button
className="rb-big"
disabled={!hasDoc}
title={t('ribbonThemeColorsTip')}
onClick={() => toggleDropdown(setDropdown, 'themecolors')}
>
<span className="rb-big-icon">
<IconThemeColors size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonColors')}</span>
</button>
{dropdown === 'themecolors' && (
<div className="layout-menu">
{THEME_COLOR_PRESETS.map((p) => (
<button
key={p.nameKey}
onClick={() => {
onThemeColors(p.colors)
setDropdown(() => null)
}}
>
<span className="theme-accent-row">
{['accent1', 'accent2', 'accent3', 'accent4'].map((k) => (
<span
key={k}
className="theme-accent-dot"
style={{ background: `#${p.colors[k as 'accent1']}` }}
/>
))}
</span>
{t(p.nameKey)}
</button>
))}
</div>
)}
</div>
</div>
<div className="ribbon-group-label">{t('ribbonGroupDocFormatting')}</div>
</div>
<div className="ribbon-sep" />
<div className="ribbon-group">
<div className="ribbon-group-items">
<div className="rb-split-wrap">
<button
className="rb-big"
disabled={!hasDoc}
title={t('ribbonPageColorTip')}
onClick={() => toggleDropdown(setDropdown, 'pagecolor')}
>
<span className="rb-big-icon rb-big-icon-colored">
<IconPageColor size={BIG} />
<span
className="rb-color-bar"
style={{ background: pageColor ? `#${pageColor}` : '#fff' }}
/>
<IconCaret />
</span>
<span>{t('ribbonPageColor')}</span>
</button>
{dropdown === 'pagecolor' && (
<div className="color-palette color-palette-page">
{PAGE_COLORS.map((c) => (
<button
key={c.hex ?? 'auto'}
className={`color-swatch ${(pageColor ?? null) === c.hex ? 'selected' : ''}`}
title={t(c.nameKey)}
style={{ background: c.hex ? `#${c.hex}` : '#ffffff' }}
onClick={() => {
onPageColor(c.hex)
setDropdown(() => null)
}}
/>
))}
<button
className="color-none"
onClick={() => {
onPageColor(null)
setDropdown(() => null)
}}
>
{t('ribbonNoColor')}
</button>
</div>
)}
</div>
<div className="rb-split-wrap">
<button
className={`rb-big ${watermark ? 'active' : ''}`}
disabled={!hasDoc}
title={t('ribbonWatermarkTip')}
onClick={() => toggleDropdown(setDropdown, 'watermark')}
>
<span className="rb-big-icon">
<IconWatermark size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonWatermark')}</span>
</button>
{dropdown === 'watermark' && (
<div className="layout-menu">
{watermarkPresets.map((text) => (
<button
key={text}
className={watermark === text ? 'active' : ''}
onClick={() => {
onWatermark(text)
setDropdown(() => null)
}}
>
{text}
</button>
))}
<button onClick={customWatermark}>{t('ribbonWatermarkCustom')}</button>
<button
className={!watermark ? 'active' : ''}
onClick={() => {
onWatermark(null)
setDropdown(() => null)
}}
>
{t('ribbonWatermarkRemove')}
</button>
</div>
)}
</div>
<div className="rb-split-wrap">
<button
className={`rb-big ${section?.pageBorder ? 'active' : ''}`}
disabled={!hasDoc || !section}
title={t('ribbonPageBordersTip')}
onClick={() => toggleDropdown(setDropdown, 'pgborders')}
>
<span className="rb-big-icon">
<IconPageBorders size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonPageBorders')}</span>
</button>
{dropdown === 'pgborders' && section && (
<div className="layout-menu">
<button
className={section.pageBorder ? 'active' : ''}
onClick={() => {
onSection({ ...section, pageBorder: true })
setDropdown(() => null)
}}
>
{t('ribbonPageBorderBox')}
</button>
<button
className={!section.pageBorder ? 'active' : ''}
onClick={() => {
onSection({ ...section, pageBorder: false })
setDropdown(() => null)
}}
>
{t('ribbonNone')}
</button>
</div>
)}
</div>
</div>
<div className="ribbon-group-label">{t('ribbonGroupPageBackground')}</div>
</div>
{watermarkPromptOpen && (
<PromptModal
title={t('ribbonWatermarkCustomTitle')}
placeholder={t('ribbonWatermarkPh')}
initial={watermark ?? ''}
allowEmpty
onSubmit={(text) => onWatermark(text || null)}
onClose={() => setWatermarkPromptOpen(false)}
/>
)}
</>
)
}
/* ================= Layout ================= */
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,470 @@
import { type SectionSettings } from '@genoffice/docx-engine'
import { WRAP_OPTIONS } from './ContextMenu'
import { useI18n, type StringKey } from '../i18n/locale'
import {
IconCaret,
IconColumns,
IconMargins,
IconOrientation,
IconPageBreak,
IconPageSize,
IconPosition,
IconWrapText,
} from './icons'
/** icon size for the big icon-over-label ribbon buttons (slides ribbon parity) */
import { BIG, TabProps, activeParaAttrs, setParaAttrs, toggleDropdown } from './ribbon-tabs'
const MARGIN_PRESETS: Array<{
key: string
nameKey: StringKey
descKey: StringKey
top: number
right: number
bottom: number
left: number
}> = [
{
key: 'normal',
nameKey: 'ribbonMarginNormal',
descKey: 'ribbonMarginNormalDesc',
top: 1440,
right: 1440,
bottom: 1440,
left: 1440,
},
{
key: 'narrow',
nameKey: 'ribbonMarginNarrow',
descKey: 'ribbonMarginNarrowDesc',
top: 720,
right: 720,
bottom: 720,
left: 720,
},
{
key: 'moderate',
nameKey: 'ribbonMarginModerate',
descKey: 'ribbonMarginModerateDesc',
top: 1440,
right: 1080,
bottom: 1440,
left: 1080,
},
{
key: 'wide',
nameKey: 'ribbonMarginWide',
descKey: 'ribbonMarginWideDesc',
top: 1440,
right: 2880,
bottom: 1440,
left: 2880,
},
]
const PAPER_SIZES = [
{ key: 'a4', name: 'A4', desc: '21 × 29.7 cm', w: 11906, h: 16838 },
{ key: 'letter', name: 'Letter', desc: '21.59 × 27.94 cm', w: 12240, h: 15840 },
{ key: 'legal', name: 'Legal', desc: '21.59 × 35.56 cm', w: 12240, h: 20160 },
{ key: 'b5', name: 'B5 (JIS)', desc: '18.2 × 25.7 cm', w: 10319, h: 14572 },
]
interface LayoutTabProps extends TabProps {
section: SectionSettings | null
onSection: (next: SectionSettings) => void
/** Multi-section documents: index of the cursor's section (0-based); null for single-section */
activeSection: number | null
onInsertSectionBreak: (type: 'nextPage' | 'continuous' | 'evenPage' | 'oddPage') => void
}
const PT_PER_TWIP = 1 / 20
export function LayoutTab({
editor,
hasDoc,
dropdown,
setDropdown,
section,
onSection,
activeSection,
onInsertSectionBreak,
}: LayoutTabProps) {
const { t } = useI18n()
const paraAttrs = activeParaAttrs(editor)
const enabled = hasDoc && !!section
// Arrange group: enabled when a floating object (image/textbox) is selected; maps to Word's Position / Wrap Text
const protAttrs = editor.getAttributes('docProtected')
const isImage = protAttrs?.blockType === 'image' && !!protAttrs.imageDataUrl
const isFloatingBox =
Array.isArray(protAttrs?.textboxes) && (protAttrs.textboxes as unknown[]).length > 0
const canWrap = hasDoc && (isImage || isFloatingBox)
// position presets go through imagePatchOf (original-document images only); newly inserted objects work after saving
const canPosition = hasDoc && isImage && protAttrs?.docxIndex != null
const currentWrap = (protAttrs?.imageWrap as string | null) ?? null
const applyWrap = (value: string | null) => {
const cleared =
value === null
? { imagePosH: null, imagePosV: null, imageOffsetXEmu: null, imageOffsetYEmu: null }
: {}
editor
.chain()
.focus()
.updateAttributes('docProtected', { imageWrap: value, ...cleared })
.run()
setDropdown(() => null)
}
const applyPositionPreset = (h: 'left' | 'center' | 'right', v: 'top' | 'center' | 'bottom') => {
editor
.chain()
.focus()
.updateAttributes('docProtected', {
imageWrap: h === 'right' ? 'square-right' : 'square-left',
imagePosH: h,
imagePosV: v,
imageOffsetXEmu: null,
imageOffsetYEmu: null,
})
.run()
setDropdown(() => null)
}
const applyInlinePosition = () => applyWrap(null)
const setOrientation = (orientation: 'portrait' | 'landscape') => {
if (!section || section.orientation === orientation) return
onSection({
...section,
orientation,
pageWidth: section.pageHeight,
pageHeight: section.pageWidth,
})
setDropdown(() => null)
}
const setPaper = (w: number, h: number) => {
if (!section) return
const landscape = section.orientation === 'landscape'
onSection({ ...section, pageWidth: landscape ? h : w, pageHeight: landscape ? w : h })
setDropdown(() => null)
}
const ptInput = (attr: string, title: string) => {
const twips = Number(paraAttrs[attr]) || 0
return (
<label className="layout-num" title={title}>
<span>{title}</span>
<input
type="number"
min={0}
max={400}
step={1}
disabled={!hasDoc}
value={Math.round(twips * PT_PER_TWIP)}
onChange={(e) => {
const pt = Math.max(0, Number(e.target.value) || 0)
setParaAttrs(editor, { [attr]: pt > 0 ? Math.round(pt / PT_PER_TWIP) : null })
}}
/>
<span className="layout-unit">pt</span>
</label>
)
}
return (
<>
<div className="ribbon-group">
<div className="ribbon-group-items">
<div className="rb-split-wrap">
<button
className="rb-big"
disabled={!enabled}
title={t('ribbonMargins')}
onClick={() => toggleDropdown(setDropdown, 'margins')}
>
<span className="rb-big-icon">
<IconMargins size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonMargins')}</span>
</button>
{dropdown === 'margins' && section && (
<div className="layout-menu">
{MARGIN_PRESETS.map((m) => (
<button
key={m.key}
className={
section.marginTop === m.top && section.marginLeft === m.left ? 'active' : ''
}
onClick={() => {
onSection({
...section,
marginTop: m.top,
marginRight: m.right,
marginBottom: m.bottom,
marginLeft: m.left,
})
setDropdown(() => null)
}}
>
<b>{t(m.nameKey)}</b>
<span>{t(m.descKey)}</span>
</button>
))}
</div>
)}
</div>
<div className="rb-split-wrap">
<button
className="rb-big"
disabled={!enabled}
title={t('ribbonOrientation')}
onClick={() => toggleDropdown(setDropdown, 'orient')}
>
<span className="rb-big-icon">
<IconOrientation size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonOrientation')}</span>
</button>
{dropdown === 'orient' && section && (
<div className="layout-menu">
<button
className={section.orientation === 'portrait' ? 'active' : ''}
onClick={() => setOrientation('portrait')}
>
<b>{t('ribbonPortrait')}</b>
</button>
<button
className={section.orientation === 'landscape' ? 'active' : ''}
onClick={() => setOrientation('landscape')}
>
<b>{t('ribbonLandscape')}</b>
</button>
</div>
)}
</div>
<div className="rb-split-wrap">
<button
className="rb-big"
disabled={!enabled}
title={t('ribbonPaperSize')}
onClick={() => toggleDropdown(setDropdown, 'paper')}
>
<span className="rb-big-icon">
<IconPageSize size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonPaperSize')}</span>
</button>
{dropdown === 'paper' && section && (
<div className="layout-menu">
{PAPER_SIZES.map((p) => {
const portraitW = Math.min(section.pageWidth, section.pageHeight)
return (
<button
key={p.key}
className={portraitW === p.w ? 'active' : ''}
onClick={() => setPaper(p.w, p.h)}
>
<b>{p.name}</b>
<span>{p.desc}</span>
</button>
)
})}
</div>
)}
</div>
<div className="rb-split-wrap">
<button
className={`rb-big ${section && section.columns > 1 ? 'active' : ''}`}
disabled={!enabled}
title={t('ribbonColumns')}
onClick={() => toggleDropdown(setDropdown, 'columns')}
>
<span className="rb-big-icon">
<IconColumns size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonColumns')}</span>
</button>
{dropdown === 'columns' && section && (
<div className="layout-menu">
{[1, 2, 3].map((n) => (
<button
key={n}
className={section.columns === n ? 'active' : ''}
onClick={() => {
onSection({ ...section, columns: n })
setDropdown(() => null)
}}
>
{n === 1
? t('ribbonOneColumn')
: n === 2
? t('ribbonTwoColumns')
: t('ribbonThreeColumns')}
</button>
))}
</div>
)}
</div>
<div className="rb-split-wrap">
<button
className="rb-big"
disabled={!enabled}
title={t('ribbonSectionBreakTip')}
onClick={() => toggleDropdown(setDropdown, 'sectbreak')}
>
<span className="rb-big-icon">
<IconPageBreak size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonSectionBreak')}</span>
</button>
{dropdown === 'sectbreak' && (
<div className="layout-menu">
<button
onClick={() => {
onInsertSectionBreak('nextPage')
setDropdown(() => null)
}}
>
<b>{t('ribbonBreakNextPage')}</b>
<span>{t('ribbonBreakNextPageDesc')}</span>
</button>
<button
onClick={() => {
onInsertSectionBreak('continuous')
setDropdown(() => null)
}}
>
<b>{t('ribbonBreakContinuous')}</b>
<span>{t('ribbonBreakContinuousDesc')}</span>
</button>
<button
onClick={() => {
onInsertSectionBreak('evenPage')
setDropdown(() => null)
}}
>
<b>{t('ribbonBreakEvenPage')}</b>
<span>{t('ribbonBreakEvenPageDesc')}</span>
</button>
<button
onClick={() => {
onInsertSectionBreak('oddPage')
setDropdown(() => null)
}}
>
<b>{t('ribbonBreakOddPage')}</b>
<span>{t('ribbonBreakOddPageDesc')}</span>
</button>
</div>
)}
</div>
</div>
<div className="ribbon-group-label">
{activeSection !== null
? t('ribbonGroupPageSetupSection', { n: activeSection + 1 })
: t('ribbonGroupPageSetup')}
</div>
</div>
<div className="ribbon-sep" />
<div className="ribbon-group">
<div className="ribbon-group-items layout-para">
<div className="layout-col">
{ptInput('indentLeft', t('ribbonIndentLeft'))}
{ptInput('indentRight', t('ribbonIndentRight'))}
</div>
<div className="layout-col">
{ptInput('spaceBefore', t('ribbonSpaceBefore'))}
{ptInput('spaceAfter', t('ribbonSpaceAfter'))}
</div>
</div>
<div className="ribbon-group-label">{t('ribbonGroupParagraphSelected')}</div>
</div>
<div className="ribbon-sep" />
<div className="ribbon-group">
<div className="ribbon-group-items">
<div className="rb-split-wrap">
<button
className="rb-big"
disabled={!canPosition}
title={t('ribbonPosition')}
onClick={() => toggleDropdown(setDropdown, 'arrange-pos')}
>
<span className="rb-big-icon">
<IconPosition size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonPosition')}</span>
</button>
{dropdown === 'arrange-pos' && (
<div className="layout-menu">
<button
className={currentWrap ? '' : 'active'}
onClick={() => applyInlinePosition()}
>
<b>{t('appWrapInline')}</b>
</button>
<div className="pos-grid">
{(['top', 'center', 'bottom'] as const).map((v) =>
(['left', 'center', 'right'] as const).map((h) => (
<button
key={`${v}-${h}`}
className={`pos-cell ph-${h} pv-${v}${
protAttrs?.imagePosH === h && protAttrs?.imagePosV === v ? ' active' : ''
}`}
title={t('ribbonPosition')}
onClick={() => applyPositionPreset(h, v)}
>
<span className="pos-dot" />
</button>
)),
)}
</div>
</div>
)}
</div>
<div className="rb-split-wrap">
<button
className="rb-big"
disabled={!canWrap}
title={t('ribbonWrapText')}
onClick={() => toggleDropdown(setDropdown, 'arrange-wrap')}
>
<span className="rb-big-icon">
<IconWrapText size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonWrapText')}</span>
</button>
{dropdown === 'arrange-wrap' && (
<div className="layout-menu">
{WRAP_OPTIONS.map((opt) => (
<button
key={String(opt.value)}
className={currentWrap === opt.value ? 'active' : ''}
onClick={() => applyWrap(opt.value)}
>
<b>{t(opt.labelKey)}</b>
</button>
))}
</div>
)}
</div>
</div>
<div className="ribbon-group-label">{t('ribbonGroupArrange')}</div>
</div>
</>
)
}
/* ================= References ================= */
@@ -0,0 +1,637 @@
import { useState } from 'react'
import type { Editor } from '@tiptap/core'
import {
bibliographyLine,
citationText,
generateCaptionXml,
generateIndexFieldXml,
generateTocFieldXml,
type Block,
type SourceInfo,
type TocEntry,
} from '@genoffice/docx-engine'
import { PromptModal } from './PromptModal'
import { t, useI18n, type StringKey } from '../i18n/locale'
import {
IconBook,
IconCaption,
IconCaret,
IconCitation,
IconEndnote,
IconFootnote,
IconIndex,
IconRefresh,
IconToc,
} from './icons'
/** icon size for the big icon-over-label ribbon buttons (slides ribbon parity) */
import { BIG, TabProps, toggleDropdown } from './ribbon-tabs'
function collectTocEntries(editor: Editor): TocEntry[] {
const entries: TocEntry[] = []
editor.state.doc.forEach((node) => {
if (node.type.name === 'docHeading' && node.textContent.trim()) {
entries.push({ level: Number(node.attrs.level) || 1, text: node.textContent })
}
})
return entries
}
/** Heading entries + real page numbers (headingPages and collectTocEntries share document order) */
function collectTocEntriesWithPages(
editor: Editor,
headingPages?: () => number[] | null,
): TocEntry[] {
const entries = collectTocEntries(editor)
const pages = headingPages?.()
if (pages && pages.length === entries.length) {
return entries.map((e, i) => ({ ...e, pageNo: pages[i] }))
}
return entries
}
/** PM nodes for a freshly generated TOC field (one docProtected per line) */
function tocFieldNodes(entries: TocEntry[]): Array<Record<string, unknown>> {
return generateTocFieldXml(entries).map((xml, i) => ({
type: 'docProtected',
attrs: {
docxIndex: null,
blockType: 'passthrough',
label: t('ribbonTocFieldLabel'),
genXml: xml,
fieldDisplay: {
kind: 'tocLine',
left: entries[i].text,
right: entries[i].pageNo !== undefined ? String(entries[i].pageNo) : '',
level: entries[i].level,
},
},
}))
}
const PAGE_BREAK_PARAGRAPH_XML = '<w:p><w:r><w:br w:type="page"/></w:r></w:p>'
/** OOXML of a top-level PM node: editor-generated fragment or original slice */
function xmlOfNode(node: { attrs: Record<string, unknown> }, blocks: Block[]): string {
if (node.attrs.genXml) return String(node.attrs.genXml)
const idx = node.attrs.docxIndex
if (idx === null || idx === undefined) return ''
return blocks.find((b) => b.docxIndex === idx)?.originalXml ?? ''
}
/**
* Find the TOC field region (field begin ... matching end, tracked by fldChar
* depth across top-level blocks) and replace it with a regenerated dirty TOC
* field built from the current headings.
*/
function updateTocField(
editor: Editor,
blocks: Block[],
headingPages?: () => number[] | null,
): void {
const entries = collectTocEntriesWithPages(editor, headingPages)
if (entries.length === 0) {
window.alert(t('ribbonTocNoHeadings'))
return
}
const doc = editor.state.doc
let from = -1
let to = -1
let keepPageBreak = false
let depth = 0
let found = false
doc.forEach((node, offset) => {
if (found) return
const xml = xmlOfNode(node as never, blocks)
if (from === -1) {
if (/<w:instrText[^>]*>\s*TOC[\s\\]/.test(xml)) {
from = offset
depth = 0
} else {
return
}
}
depth += (xml.match(/w:fldCharType="begin"/g) ?? []).length
depth -= (xml.match(/w:fldCharType="end"/g) ?? []).length
if (depth <= 0) {
to = offset + node.nodeSize
keepPageBreak = /<w:br\s[^>]*w:type="page"/.test(xml)
found = true
}
})
const nodes = tocFieldNodes(entries)
if (keepPageBreak) {
nodes.push({
type: 'docProtected',
attrs: {
docxIndex: null,
blockType: 'passthrough',
label: t('ribbonPageBreak'),
genXml: PAGE_BREAK_PARAGRAPH_XML,
fieldDisplay: { kind: 'pageBreak' },
},
})
}
if (from === -1 || !found) {
window.alert(t('ribbonTocNotFound'))
return
}
editor
.chain()
.focus()
.deleteRange({ from, to })
.insertContentAt(from, nodes as never)
.run()
}
const CAPTION_LABEL_KEYS = [
'ribbonCaptionFigure',
'ribbonCaptionTable',
'ribbonCaptionEquation',
] as const
/** Caption dialog: label + optional description, numbered by existing SEQ fields */
function CaptionModal({
editor,
blocks,
onClose,
}: {
editor: Editor
blocks: Block[]
onClose: () => void
}) {
const { t } = useI18n()
const CAPTION_LABELS = CAPTION_LABEL_KEYS.map((k) => t(k))
const [label, setLabel] = useState<string>(() => t(CAPTION_LABEL_KEYS[0]))
const [text, setText] = useState('')
const nextNumber = (lbl: string): number => {
let count = 0
const re = new RegExp(`SEQ\\s+${lbl}[\\s\\\\]`)
editor.state.doc.forEach((node) => {
if (node.type.name !== 'docProtected') return
if (re.test(xmlOfNode(node as never, blocks))) count += 1
})
return count + 1
}
const insert = () => {
const number = nextNumber(label)
const xml = generateCaptionXml(label, number, text.trim())
const display = `${label} ${number}${text.trim() ? ` ${text.trim()}` : ''}`
editor
.chain()
.focus()
.insertContent({
type: 'docProtected',
attrs: {
docxIndex: null,
blockType: 'passthrough',
label: t('ribbonCaption'),
genXml: xml,
fieldDisplay: { kind: 'text', left: display },
},
} as never)
.run()
onClose()
}
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal">
<h2>{t('ribbonCaptionInsertTitle')}</h2>
<label>
{t('ribbonCaptionLabel')}
<select value={label} onChange={(e) => setLabel(e.target.value)}>
{CAPTION_LABELS.map((l) => (
<option key={l} value={l}>
{l}
</option>
))}
</select>
</label>
<label>
{t('ribbonCaption')}
<input
value={text}
onChange={(e) => setText(e.target.value)}
placeholder={t('ribbonCaptionPh', { label, n: nextNumber(label) })}
onKeyDown={(e) => e.key === 'Enter' && insert()}
/>
</label>
<div className="modal-actions">
<button className="btn-ghost" onClick={onClose}>
{t('ribbonCancel')}
</button>
<button className="btn-primary" onClick={insert}>
{t('ribbonInsert')}
</button>
</div>
</div>
</div>
)
}
const SOURCE_TYPES: Array<{ key: string; nameKey: StringKey }> = [
{ key: 'Book', nameKey: 'ribbonSourceBook' },
{ key: 'JournalArticle', nameKey: 'ribbonSourceJournal' },
{ key: 'InternetSite', nameKey: 'ribbonSourceWebsite' },
{ key: 'Report', nameKey: 'ribbonSourceReport' },
{ key: 'Misc', nameKey: 'ribbonSourceMisc' },
]
/** Create Source dialog for the citation manager */
function SourceModal({
sources,
onAdd,
onClose,
}: {
sources: SourceInfo[]
onAdd: (source: SourceInfo) => void
onClose: () => void
}) {
const { t } = useI18n()
const [type, setType] = useState('Book')
const [author, setAuthor] = useState('')
const [title, setTitle] = useState('')
const [year, setYear] = useState('')
const [publisher, setPublisher] = useState('')
const [url, setUrl] = useState('')
const add = () => {
if (!title.trim()) return
// unique tag derived from author/title initials + year
const base = (author.trim() || title.trim()).replace(/[\s,,、]+/g, '').slice(0, 8) || 'Src'
let tag = `${base}${year.trim()}`
let n = 1
while (sources.some((s) => s.tag === tag)) tag = `${base}${year.trim()}_${++n}`
onAdd({
tag,
type,
author: author.trim(),
title: title.trim(),
year: year.trim(),
...(publisher.trim() ? { publisher: publisher.trim() } : {}),
...(url.trim() ? { url: url.trim() } : {}),
})
onClose()
}
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal">
<h2>{t('ribbonSourceCreateTitle')}</h2>
<label>
{t('ribbonSourceType')}
<select value={type} onChange={(e) => setType(e.target.value)}>
{SOURCE_TYPES.map((s) => (
<option key={s.key} value={s.key}>
{t(s.nameKey)}
</option>
))}
</select>
</label>
<label>
{t('ribbonSourceAuthor')}
<input
value={author}
onChange={(e) => setAuthor(e.target.value)}
placeholder={t('ribbonSourceAuthorPh')}
/>
</label>
<label>
{t('ribbonSourceTitle')}
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder={t('ribbonSourceTitlePh')}
/>
</label>
<label>
{t('ribbonSourceYear')}
<input value={year} onChange={(e) => setYear(e.target.value)} placeholder="2026" />
</label>
<label>
{type === 'JournalArticle'
? t('ribbonSourceJournalName')
: type === 'InternetSite'
? t('ribbonSourceSiteName')
: t('ribbonSourcePublisher')}
<input value={publisher} onChange={(e) => setPublisher(e.target.value)} />
</label>
{type === 'InternetSite' && (
<label>
URL
<input value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://…" />
</label>
)}
<div className="modal-actions">
<button className="btn-ghost" onClick={onClose}>
{t('ribbonCancel')}
</button>
<button className="btn-primary" disabled={!title.trim()} onClick={add}>
{t('ribbonAdd')}
</button>
</div>
</div>
</div>
)
}
interface ReferencesTabProps extends TabProps {
blocks: Block[]
onInsertNote: (kind: 'footnote' | 'endnote') => void
sources: SourceInfo[]
onAddSource: (source: SourceInfo) => void
/** TOC page-number backfill: docHeadings in document order → real page numbers */
headingPages?: () => number[] | null
}
export function ReferencesTab({
editor,
hasDoc,
blocks,
dropdown,
setDropdown,
onInsertNote,
sources,
onAddSource,
headingPages,
}: ReferencesTabProps) {
const { t } = useI18n()
const [captionOpen, setCaptionOpen] = useState(false)
const [sourceOpen, setSourceOpen] = useState(false)
const insertToc = () => {
const entries = collectTocEntriesWithPages(editor, headingPages)
if (entries.length === 0) {
window.alert(t('ribbonTocNoHeadings'))
return
}
editor
.chain()
.focus()
.insertContent(tocFieldNodes(entries) as never)
.run()
}
const insertCitation = (source: SourceInfo) => {
editor
.chain()
.focus()
.insertContent({ type: 'text', text: citationText(source) } as never)
.run()
setDropdown(() => null)
}
const insertBibliography = () => {
if (sources.length === 0) {
window.alert(t('ribbonNoSources'))
return
}
const nodes: Array<Record<string, unknown>> = [
{
type: 'docHeading',
attrs: { docxIndex: null, styleId: null, aiChanged: false, level: 1 },
content: [{ type: 'text', text: t('ribbonBibliographyHeading') }],
},
...sources.map((s) => ({
type: 'docParagraph',
attrs: { docxIndex: null, styleId: null, aiChanged: false },
content: [{ type: 'text', text: bibliographyLine(s) }],
})),
]
editor
.chain()
.focus()
.insertContent(nodes as never)
.run()
setDropdown(() => null)
}
const [xePrompt, setXePrompt] = useState<{ initial: string; at: number } | null>(null)
const markIndexEntry = () => {
const { from, to } = editor.state.selection
setXePrompt({ initial: editor.state.doc.textBetween(from, to, ' ').trim(), at: to })
}
const submitIndexEntry = (term: string) => {
if (!xePrompt) return
editor
.chain()
.focus()
.insertContentAt(Math.min(xePrompt.at, editor.state.doc.content.size), {
type: 'docXeMark',
attrs: { term },
} as never)
.run()
}
const insertIndex = () => {
const terms: string[] = []
editor.state.doc.descendants((node) => {
if (node.type.name === 'docXeMark') terms.push(String(node.attrs.term))
})
if (terms.length === 0) {
window.alert(t('ribbonNoIndexEntries'))
return
}
const unique = [...new Set(terms.map((t) => t.trim()).filter(Boolean))].sort((a, b) =>
a.localeCompare(b, 'zh-CN'),
)
const nodes = generateIndexFieldXml(unique).map((xml, i) => ({
type: 'docProtected',
attrs: {
docxIndex: null,
blockType: 'passthrough',
label: t('ribbonIndexFieldLabel'),
genXml: xml,
fieldDisplay: { kind: 'tocLine', left: unique[i], right: '', level: 1 },
},
}))
editor
.chain()
.focus()
.insertContent(nodes as never)
.run()
}
return (
<>
<div className="ribbon-group">
<div className="ribbon-group-items">
<button
className="rb-big"
disabled={!hasDoc}
title={t('ribbonTocTip')}
onClick={insertToc}
>
<span className="rb-big-icon">
<IconToc size={BIG} />
</span>
<span>{t('ribbonToc')}</span>
</button>
<button
className="rb-big"
disabled={!hasDoc}
title={t('ribbonTocUpdateTip')}
onClick={() => updateTocField(editor, blocks, headingPages)}
>
<span className="rb-big-icon">
<IconRefresh size={BIG} />
</span>
<span>{t('ribbonTocUpdate')}</span>
</button>
</div>
<div className="ribbon-group-label">{t('ribbonToc')}</div>
</div>
<div className="ribbon-sep" />
<div className="ribbon-group">
<div className="ribbon-group-items">
<button
className="rb-big"
disabled={!hasDoc}
title={t('ribbonFootnoteTip')}
onClick={() => onInsertNote('footnote')}
>
<span className="rb-big-icon">
<IconFootnote size={BIG} />
</span>
<span>{t('ribbonFootnote')}</span>
</button>
<button
className="rb-big"
disabled={!hasDoc}
title={t('ribbonEndnoteTip')}
onClick={() => onInsertNote('endnote')}
>
<span className="rb-big-icon">
<IconEndnote size={BIG} />
</span>
<span>{t('ribbonEndnote')}</span>
</button>
</div>
<div className="ribbon-group-label">{t('ribbonGroupFootnotes')}</div>
</div>
<div className="ribbon-sep" />
<div className="ribbon-group">
<div className="ribbon-group-items">
<div className="rb-split-wrap">
<button
className="rb-big"
disabled={!hasDoc}
title={t('ribbonCitationTip')}
onClick={() => toggleDropdown(setDropdown, 'citation')}
>
<span className="rb-big-icon">
<IconCitation size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonCitation')}</span>
</button>
{dropdown === 'citation' && (
<div className="layout-menu">
{sources.map((s) => (
<button key={s.tag} title={s.title} onClick={() => insertCitation(s)}>
{citationText(s)} {s.title.slice(0, 12)}
</button>
))}
<button
onClick={() => {
setSourceOpen(true)
setDropdown(() => null)
}}
>
{t('ribbonAddNewSource')}
</button>
</div>
)}
</div>
<button
className="rb-big"
disabled={!hasDoc}
title={t('ribbonBibliographyTip')}
onClick={insertBibliography}
>
<span className="rb-big-icon">
<IconBook size={BIG} />
</span>
<span>{t('ribbonBibliography')}</span>
</button>
<button
className="rb-big"
disabled={!hasDoc}
title={t('ribbonCaptionTip')}
onClick={() => setCaptionOpen(true)}
>
<span className="rb-big-icon">
<IconCaption size={BIG} />
</span>
<span>{t('ribbonCaption')}</span>
</button>
<div className="rb-split-wrap">
<button
className="rb-big"
disabled={!hasDoc}
title={t('ribbonIndexTip')}
onClick={() => toggleDropdown(setDropdown, 'index')}
>
<span className="rb-big-icon">
<IconIndex size={BIG} />
<IconCaret />
</span>
<span>{t('ribbonIndex')}</span>
</button>
{dropdown === 'index' && (
<div className="layout-menu">
<button
onClick={() => {
markIndexEntry()
setDropdown(() => null)
}}
>
{t('ribbonMarkEntry')}
</button>
<button
onClick={() => {
insertIndex()
setDropdown(() => null)
}}
>
{t('ribbonInsertIndex')}
</button>
</div>
)}
</div>
</div>
<div className="ribbon-group-label">{t('ribbonGroupCitationsIndex')}</div>
</div>
{captionOpen && (
<CaptionModal editor={editor} blocks={blocks} onClose={() => setCaptionOpen(false)} />
)}
{sourceOpen && (
<SourceModal sources={sources} onAdd={onAddSource} onClose={() => setSourceOpen(false)} />
)}
{xePrompt && (
<PromptModal
title={t('ribbonMarkEntryTitle')}
placeholder={t('ribbonMarkEntryPh')}
initial={xePrompt.initial}
onSubmit={submitIndexEntry}
onClose={() => setXePrompt(null)}
/>
)}
</>
)
}
/* ================= Review ================= */
File diff suppressed because it is too large Load Diff
+178
View File
@@ -0,0 +1,178 @@
/**
* Core image cutout (background removal) algorithm — pure functions, no DOM dependency, easy to unit test.
* Shares its source with apps/slides/src/renderer/cutout.ts (keep the algorithms identical; sync changes to both).
*
* Approach A: edge flood fill with color tolerance (magic-wand style removal, a simplified take on PowerPoint's "Remove Background"):
* 1. Sample a ring along the image border (corners included); greedy clustering yields ≤4 background representative colors.
* 2. With "color distance to any representative ≤ tolerance threshold" as the passable condition, 4-connected flood fill from the edges.
* 3. Flooded pixels get alpha 0. Only background connected to the edge is removed;
* enclosed regions inside shapes matching the background color (e.g. white highlights on a white shirt) are unaffected.
*
* TODO (approach B): brush-marked "keep/remove" regions + region growing for interactive edge refinement.
*/
/** Pixel map isomorphic to canvas ImageData (RGBA row-major), easy to construct directly in Node unit tests. */
export interface PixelImage {
data: Uint8ClampedArray
width: number
height: number
}
export type RGB = readonly [number, number, number]
export interface CutoutResult {
/** Processed RGBA pixels (a new array, input unchanged; can be fed straight to new ImageData) */
data: Uint8ClampedArray<ArrayBuffer>
/** Number of pixels made transparent (only counts pixels that weren't already fully transparent) */
removedCount: number
}
/**
* Tolerance 0..100 → color-distance threshold.
* Distance is per-channel RMS (0..255 scale); at tolerance 100 the threshold 255 ≈ black-white distance,
* i.e. at max nearly every color connected to the edge is judged background.
*/
export function toleranceToThreshold(tolerance: number): number {
const t = Math.max(0, Math.min(100, tolerance))
return (t * 255) / 100
}
/** Color distance: per-channel RMS, range 0..255 (black vs white = 255). */
export function colorDistance(a: RGB, b: RGB): number {
const dr = a[0] - b[0]
const dg = a[1] - b[1]
const db = a[2] - b[2]
return Math.sqrt((dr * dr + dg * dg + db * db) / 3)
}
/** Cluster-merge distance for sample clustering (0..255 scale) */
const CLUSTER_DIST = 30
/** Clusters below this share are treated as edge noise, not background representatives */
const MIN_CLUSTER_RATIO = 0.05
/** Alpha below this counts as "already transparent": skipped in sampling, passable for flood fill */
const ALPHA_TRANSPARENT = 16
/**
* Sample background representative colors along the image border (corners included);
* greedy-cluster and return in descending cluster size.
* Fully transparent pixels don't participate; tiny clusters (edge noise) are filtered out.
*/
export function sampleBackgroundColors(img: PixelImage, maxColors = 4): RGB[] {
const { data, width: w, height: h } = img
if (w <= 0 || h <= 0) return []
// sample the border ring at a stride, capped at ~512 sample points
const perimeter = Math.max(1, 2 * (w + h) - 4)
const step = Math.max(1, Math.floor(perimeter / 512))
const sampleIdx: number[] = []
for (let x = 0; x < w; x += step) {
sampleIdx.push((0 * w + x) * 4)
sampleIdx.push(((h - 1) * w + x) * 4)
}
for (let y = 0; y < h; y += step) {
sampleIdx.push((y * w + 0) * 4)
sampleIdx.push((y * w + w - 1) * 4)
}
// greedy clustering: merge into the nearest cluster (running mean), otherwise open a new one
const clusters: Array<{ sr: number; sg: number; sb: number; n: number }> = []
for (const i of sampleIdx) {
if ((data[i + 3] ?? 0) < ALPHA_TRANSPARENT) continue
const c: RGB = [data[i]!, data[i + 1]!, data[i + 2]!]
let best: (typeof clusters)[number] | null = null
let bestD = Infinity
for (const cl of clusters) {
const d = colorDistance([cl.sr / cl.n, cl.sg / cl.n, cl.sb / cl.n], c)
if (d < bestD) {
bestD = d
best = cl
}
}
if (best && bestD <= CLUSTER_DIST) {
best.sr += c[0]
best.sg += c[1]
best.sb += c[2]
best.n += 1
} else {
clusters.push({ sr: c[0], sg: c[1], sb: c[2], n: 1 })
}
}
const total = clusters.reduce((s, c) => s + c.n, 0)
if (total === 0) return []
return clusters
.filter((c) => c.n >= Math.max(1, total * MIN_CLUSTER_RATIO))
.sort((a, b) => b.n - a.n)
.slice(0, maxColors)
.map((c) => [Math.round(c.sr / c.n), Math.round(c.sg / c.n), Math.round(c.sb / c.n)] as const)
}
/**
* Background removal: 4-connected flood fill from the edges; pixels close to a background
* representative (within tolerance) and connected to the edge get alpha 0.
* Returns a new pixel array; the input is not modified.
*
* @param tolerance tolerance 0..100 (see toleranceToThreshold)
* @param bgColors background representative colors; defaults to auto-sampling from the border
*/
export function removeBackground(
img: PixelImage,
tolerance: number,
bgColors: RGB[] = sampleBackgroundColors(img),
): CutoutResult {
const { data: src, width: w, height: h } = img
const out = new Uint8ClampedArray(src)
if (w <= 0 || h <= 0 || bgColors.length === 0) return { data: out, removedCount: 0 }
const thr = toleranceToThreshold(tolerance)
// compare distances with the sum of squares (restoring the /3 of per-channel RMS), skipping sqrt
const thr2 = thr * thr * 3
/** Whether a pixel "looks like background": already transparent, or within tolerance of any background representative */
const isBgLike = (i: number): boolean => {
const p = i * 4
if ((src[p + 3] ?? 0) < ALPHA_TRANSPARENT) return true
const r = src[p]!
const g = src[p + 1]!
const b = src[p + 2]!
for (const c of bgColors) {
const dr = r - c[0]
const dg = g - c[1]
const db = b - c[2]
if (dr * dr + dg * dg + db * db <= thr2) return true
}
return false
}
const visited = new Uint8Array(w * h)
const stack: number[] = []
const trySeed = (i: number) => {
if (!visited[i] && isBgLike(i)) {
visited[i] = 1
stack.push(i)
}
}
// seeds: all passable pixels along the border ring
for (let x = 0; x < w; x++) {
trySeed(x)
trySeed((h - 1) * w + x)
}
for (let y = 0; y < h; y++) {
trySeed(y * w)
trySeed(y * w + w - 1)
}
let removedCount = 0
while (stack.length > 0) {
const i = stack.pop()!
const p = i * 4
if (out[p + 3]! > 0) {
out[p + 3] = 0
removedCount++
}
const x = i % w
if (x > 0) trySeed(i - 1)
if (x < w - 1) trySeed(i + 1)
if (i >= w) trySeed(i - w)
if (i < w * (h - 1)) trySeed(i + w)
}
return { data: out, removedCount }
}
+59
View File
@@ -0,0 +1,59 @@
/**
* Shared document-state types and header/footer helpers used by App.tsx and
* the extracted action modules (file-actions, review-actions, …).
*/
import type { HeaderFooter, HfPartInfo, ParsedDocFull } from '@genoffice/docx-engine'
/** first-page / even-page header & footer variants */
export type HfVariantKey = 'headerFirst' | 'footerFirst' | 'headerEven' | 'footerEven'
export type HfVariantsState = Record<HfVariantKey, HeaderFooter | null>
export type HfView = 'default' | 'first' | 'even'
export const EMPTY_HF_VARIANTS: HfVariantsState = {
headerFirst: null,
footerFirst: null,
headerEven: null,
footerEven: null,
}
export interface DocState {
parsed: ParsedDocFull
/** null until a new document is saved for the first time */
filePath: string | null
fileName: string
hash: string
/** created from the built-in blank template (its numbering ids are known) */
isBlank?: boolean
}
/** Pending numbering definitions to append (saved via SaveOptions.numbering) */
export interface PendingNumbering {
newDefs: Array<{
numId: string
kind: 'bullet' | 'ordered'
levels?: import('@genoffice/docx-engine').CustomNumberingLevel[]
}>
restartNums: Array<{
numId: string
abstractNumId: string
startOverrides: Record<number, number>
}>
}
export function hfFromPart(part: HfPartInfo | null | undefined): HeaderFooter | null {
if (!part || (!part.text && !part.hasPageNumber && part.paras.length === 0)) return null
return {
text: part.text,
pageNumber: part.hasPageNumber,
paras: part.paras.length > 0 ? part.paras : undefined,
}
}
export function hfVariantsFromParsed(parsed: ParsedDocFull): HfVariantsState {
return {
headerFirst: hfFromPart(parsed.headerFirst),
footerFirst: hfFromPart(parsed.footerFirst),
headerEven: hfFromPart(parsed.headerEven),
footerEven: hfFromPart(parsed.footerEven),
}
}
+123
View File
@@ -0,0 +1,123 @@
import type { ParsedDocFull, ThemeColors, ThemeFonts } from '@genoffice/docx-engine'
import { cssFontFamily, cssLineHeight, lineHeightFactor, textHasCjk } from './line-metrics'
/**
* CSS for the document theme (Design ▸ Themes / Fonts / Colors). Kept separate from
* docStyleCss so the page reflects a theme pick immediately instead of only after
* save + reopen in Word: App re-renders this from live state, while
* docStyleCss is regenerated only on parse.
*/
export function docThemeCss(
fonts: ThemeFonts | null | undefined,
colors: ThemeColors | null | undefined,
): string {
const rules: string[] = []
if (fonts?.minor) {
// Body font: the theme's minor latin face (docDefaults still wins for runs that name a font)
rules.push(`.doc-page { font-family:${cssFontFamily(fonts.minor)} }`)
}
if (fonts?.major) {
const headings = [1, 2, 3, 4, 5, 6].map((n) => `.doc-page h${n}`).join(', ')
rules.push(`${headings} { font-family:${cssFontFamily(fonts.major)} }`)
}
if (colors?.accent1) {
// Heading color + the accent variable the ribbon's style presets already read
rules.push(`.doc-page { --theme-accent:#${colors.accent1} }`)
const headings = [1, 2, 3, 4].map((n) => `.doc-page h${n}`).join(', ')
rules.push(`${headings} { color:#${colors.accent1} }`)
}
return rules.join('\n')
}
/**
* Per-document CSS generated from styles.xml, so paragraphs render with their
* style's font size / color / spacing (display-only; the save
* path never touches styles.xml).
*/
/** Body contains CJK text (drives the document-level line-height factor). */
export function docHasCjk(parsed: ParsedDocFull): boolean {
return parsed.blocks.some((b) => !b.hidden && (b.runs ?? []).some((r) => textHasCjk(r.text)))
}
/**
* Document-level line-height factor: bodies containing CJK use the Chinese font's
* factor (Word takes the max of in-line fonts; the declared eastAsia default font
* doesn't reflect actual content, and pure-English documents shouldn't get CJK
* line height). Recomputed live while editing via App's liveDocCjk.
*/
export function docLineFactor(parsed: ParsedDocFull, hasCjk: boolean): number {
const dd = parsed.docDefaults
return hasCjk
? lineHeightFactor(dd?.eastAsiaFont ?? '宋体')
: lineHeightFactor(dd?.asciiFont ?? 'Calibri')
}
export function docStyleCss(parsed: ParsedDocFull): string {
const rules: string[] = []
const dd = parsed.docDefaults
{
const decls: string[] = []
// Paragraph level also overrides this variable per paragraph's text (blockAttrs
// at parse time + live decorations in LineFactorExtension).
const factor = docLineFactor(parsed, docHasCjk(parsed))
decls.push(`--doc-line-factor:${factor}`)
decls.push(`font-family:${cssFontFamily(dd?.asciiFont ?? 'Calibri')}`)
if (dd?.sizeHalfPoints) decls.push(`font-size:${dd.sizeHalfPoints / 2}pt`)
if (dd?.color) decls.push(`color:#${dd.color}`)
if (dd?.bold) decls.push('font-weight:600')
if (dd?.italic) decls.push('font-style:italic')
const lh = cssLineHeight(dd?.lineRule, dd?.lineRawTwips, dd?.lineSpacing)
decls.push(`line-height:${lh ?? `calc(${factor} * 1)`}`)
rules.push(`.doc-page { ${decls.join(';')} }`)
}
// table styles: tables carrying data-tbl-style are colored by style (explicit cell shading
// is inline style and naturally overrides these rules; parse gives exact display after save)
for (const info of parsed.styles.values()) {
const t = info.tableDisplay
if (info.type !== 'table' || !t) continue
const sel = `.doc-page table[data-tbl-style="${CSS.escape(info.styleId)}"]`
if (t.fill) rules.push(`${sel} td, ${sel} th { background:#${t.fill} }`)
if (t.band1Fill) {
rules.push(`${sel} tr:nth-child(odd):not(:first-child) td { background:#${t.band1Fill} }`)
}
if (t.band2Fill) {
rules.push(`${sel} tr:nth-child(even):not(:first-child) td { background:#${t.band2Fill} }`)
}
if (t.firstRow) {
const decls: string[] = []
if (t.firstRow.fill) decls.push(`background:#${t.firstRow.fill}`)
if (t.firstRow.bold) decls.push('font-weight:600')
if (t.firstRow.color) decls.push(`color:#${t.firstRow.color}`)
if (decls.length > 0) rules.push(`${sel} tr:first-child td { ${decls.join(';')} }`)
}
}
for (const info of parsed.styles.values()) {
const d = info.display
if (!d) continue
const decls: string[] = []
if (d.sizeHalfPoints) decls.push(`font-size:${d.sizeHalfPoints / 2}pt`)
if (d.color) decls.push(`color:#${d.color}`)
if (d.bold) decls.push('font-weight:600')
if (d.italic) decls.push('font-style:italic')
if (d.underline || d.strike) {
decls.push(
`text-decoration:${[d.underline && 'underline', d.strike && 'line-through'].filter(Boolean).join(' ')}`,
)
}
if (d.font) decls.push(`font-family:${cssFontFamily(d.font)}`)
if (d.charSpacingTwips) decls.push(`letter-spacing:${d.charSpacingTwips / 20}pt`)
const styleLh = cssLineHeight(d.lineRule, d.lineRawTwips, d.lineSpacing)
if (styleLh) decls.push(`line-height:${styleLh}`)
if (d.spaceBeforeTwips !== undefined)
decls.push(`margin-top:${(d.spaceBeforeTwips / 20).toFixed(1)}pt`)
if (d.spaceAfterTwips !== undefined)
decls.push(`margin-bottom:${(d.spaceAfterTwips / 20).toFixed(1)}pt`)
if (d.indentLeftTwips) decls.push(`margin-left:${(d.indentLeftTwips / 20).toFixed(1)}pt`)
if (d.indentRightTwips) decls.push(`margin-right:${(d.indentRightTwips / 20).toFixed(1)}pt`)
if (d.indentFirstLineTwips)
decls.push(`text-indent:${(d.indentFirstLineTwips / 20).toFixed(1)}pt`)
if (decls.length === 0) continue
rules.push(`.doc-page [data-style="${CSS.escape(info.styleId)}"] { ${decls.join(';')} }`)
}
return rules.join('\n')
}
@@ -0,0 +1,51 @@
import type { Editor } from '@tiptap/core'
/**
* Tracks which textbox sub-editor (if any) should receive ribbon commands.
* The last-focused sub-editor stays active until the main editor takes focus
* back, so clicking a ribbon button (which briefly steals focus) still routes
* the command into the textbox — mirroring how Word keeps the shape selected.
*/
type Listener = (docChanged: boolean) => void
let active: Editor | null = null
const listeners = new Set<Listener>()
function emit(docChanged: boolean): void {
for (const fn of listeners) fn(docChanged)
}
/** the sub-editor ribbon commands should target, or null for the main editor */
export function getActiveSubEditor(): Editor | null {
if (active?.isDestroyed) active = null
return active
}
/** pass null when the main editor regains focus */
export function setActiveSubEditor(editor: Editor | null): void {
if (active === editor) return
active = editor
emit(false)
}
/** deactivate a sub-editor that is being destroyed */
export function dropActiveSubEditor(editor: Editor): void {
if (active === editor) {
active = null
emit(false)
}
}
/** sub-editors call this on every transaction so the ribbon re-renders */
export function notifySubEditorState(docChanged: boolean): void {
emit(docChanged)
}
/** App subscribes to re-render the ribbon and mark the document dirty */
export function subscribeSubEditorState(fn: Listener): () => void {
listeners.add(fn)
return () => {
listeners.delete(fn)
}
}
+88
View File
@@ -0,0 +1,88 @@
/**
* Comment mark operations for Review → New/Delete Comment.
*
* The comment mark stores space-separated ids so overlapping comments share
* one mark instance; adding/removing an id therefore rewrites the ids attr
* per text node instead of blindly stacking marks.
*/
import type { Editor } from '@tiptap/core'
import type { CommentInfo } from '@genoffice/docx-engine'
import { TRACK_IGNORE } from './revisions'
/** smallest unused numeric comment id */
export function nextCommentId(comments: CommentInfo[]): string {
const max = comments.reduce((acc, c) => Math.max(acc, parseInt(c.id, 10) || 0), 0)
return String(max + 1)
}
/** attach `id` to every text node in the current selection; false when selection is empty */
export function addCommentToSelection(editor: Editor, id: string): boolean {
const { state } = editor
const { from, to } = state.selection
if (from === to) return false
const markType = state.schema.marks.comment
const tr = state.tr
tr.setMeta(TRACK_IGNORE, true)
state.doc.nodesBetween(from, to, (node, pos) => {
if (!node.isText) return
const start = Math.max(pos, from)
const end = Math.min(pos + node.nodeSize, to)
if (start >= end) return
const existing = node.marks.find((m) => m.type === markType)
const ids = new Set(
String(existing?.attrs.ids ?? '')
.split(' ')
.filter(Boolean),
)
ids.add(id)
tr.addMark(start, end, markType.create({ ids: [...ids].sort().join(' ') }))
})
editor.view.dispatch(tr)
return true
}
/** strip `id` from every comment mark in the document (mark removed when it was the last id) */
export function removeCommentFromDoc(editor: Editor, id: string): void {
const { state } = editor
const markType = state.schema.marks.comment
const tr = state.tr
tr.setMeta(TRACK_IGNORE, true)
state.doc.descendants((node, pos) => {
if (!node.isText) return
const existing = node.marks.find((m) => m.type === markType)
if (!existing) return
const ids = String(existing.attrs.ids ?? '')
.split(' ')
.filter(Boolean)
if (!ids.includes(id)) return
const remaining = ids.filter((x) => x !== id)
const from = pos
const to = pos + node.nodeSize
if (remaining.length === 0) tr.removeMark(from, to, markType)
else tr.addMark(from, to, markType.create({ ids: remaining.join(' ') }))
})
if (tr.steps.length > 0) editor.view.dispatch(tr)
}
/** Append `newId` to every text range anchored by the `parentId` comment (Word: replies share the parent anchor) */
export function addReplyToCommentRange(editor: Editor, parentId: string, newId: string): boolean {
const { state } = editor
const markType = state.schema.marks.comment
const tr = state.tr
tr.setMeta(TRACK_IGNORE, true)
let found = false
state.doc.descendants((node, pos) => {
if (!node.isText) return
const existing = node.marks.find((m) => m.type === markType)
if (!existing) return
const ids = String(existing.attrs.ids ?? '')
.split(' ')
.filter(Boolean)
if (!ids.includes(parentId)) return
found = true
const merged = [...new Set([...ids, newId])].sort()
tr.addMark(pos, pos + node.nodeSize, markType.create({ ids: merged.join(' ') }))
})
if (found && tr.steps.length > 0) editor.view.dispatch(tr)
return found
}
+82
View File
@@ -0,0 +1,82 @@
/**
* Review → Compare: paragraph-level diff of two documents (pure, unit-testable).
* Word builds a merged revision document; this lightweight version reports
* per-paragraph additions / removals / edits for a side panel.
*/
import type { Block } from '@genoffice/docx-engine'
export interface CompareEntry {
kind: 'same' | 'removed' | 'added' | 'changed'
/** paragraph text in the current document */
left?: string
/** paragraph text in the compared document */
right?: string
}
/** visible block -> comparable plain text (tables/objects fall back to previews) */
export function blockTexts(blocks: Block[]): string[] {
return blocks
.filter((b) => !b.hidden)
.map((b) => {
if (b.runs) return b.runs.map((r) => r.text).join('')
return b.previewText ?? ''
})
}
/** LCS-based paragraph diff; a removal directly followed by an addition merges into 'changed' */
export function compareParagraphs(left: string[], right: string[]): CompareEntry[] {
const n = left.length
const m = right.length
// lcs[i][j] = LCS length of left[i:], right[j:]
const lcs: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0))
for (let i = n - 1; i >= 0; i--) {
for (let j = m - 1; j >= 0; j--) {
lcs[i][j] =
left[i] === right[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1])
}
}
const raw: CompareEntry[] = []
let i = 0
let j = 0
while (i < n && j < m) {
if (left[i] === right[j]) {
raw.push({ kind: 'same', left: left[i], right: right[j] })
i++
j++
} else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
raw.push({ kind: 'removed', left: left[i] })
i++
} else {
raw.push({ kind: 'added', right: right[j] })
j++
}
}
while (i < n) raw.push({ kind: 'removed', left: left[i++] })
while (j < m) raw.push({ kind: 'added', right: right[j++] })
const out: CompareEntry[] = []
for (const entry of raw) {
const prev = out[out.length - 1]
if (entry.kind === 'added' && prev?.kind === 'removed' && prev.right === undefined) {
prev.kind = 'changed'
prev.right = entry.right
continue
}
out.push(entry)
}
return out
}
export interface CompareSummary {
added: number
removed: number
changed: number
}
export function summarize(entries: CompareEntry[]): CompareSummary {
return {
added: entries.filter((e) => e.kind === 'added').length,
removed: entries.filter((e) => e.kind === 'removed').length,
changed: entries.filter((e) => e.kind === 'changed').length,
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,335 @@
import type { Editor } from '@tiptap/core'
import { DATE_LOCALES, getLang, t, type StringKey } from '../i18n/locale'
import type { PmNode } from './convert'
/**
* Built-in cover page library (the preset gallery behind Insert → Cover
* Page). Everything is built from layout primitives the engine
* already supports: paragraph shading / single-line borders / alignment /
* spacing + text color / size / bold / italic. No drawing objects, so the
* result holds up in Word after saving.
*/
export interface CoverPara {
text?: string
bold?: boolean
italic?: boolean
/** hex without '#' */
color?: string
sizeHalfPoints?: number
align?: 'left' | 'center' | 'right'
/** twips */
spaceBefore?: number
spaceAfter?: number
shadingFill?: string
/** subset of "tblr" */
borders?: string
indentLeft?: number
indentRight?: number
}
export interface CoverPreset {
id: string
name: string
paras: CoverPara[]
}
const TITLE = () => t('editorCoverTitle')
const SUBTITLE = () => t('editorCoverSubtitle')
const AUTHOR = () => t('editorCoverAuthor')
function today(): string {
return new Date().toLocaleDateString(DATE_LOCALES[getLang()], {
year: 'numeric',
month: 'long',
day: 'numeric',
})
}
/** name/paras are both lazily evaluated so they follow the current UI language */
function preset(id: string, nameKey: StringKey, paras: () => CoverPara[]): CoverPreset {
return {
id,
get name() {
return t(nameKey)
},
get paras() {
return paras()
},
}
}
/* palette */
const NAVY = '1F3864'
const BLUE = '2B579A'
const TEAL = '1C7C74'
const GRAY = '595959'
const LIGHT = 'A6A6A6'
const DARK = '262626'
const RED = 'C0504D'
const GOLD = 'BF8F00'
export const COVER_PRESETS: CoverPreset[] = [
preset('classic', 'editorCoverClassic', () => [
{ spaceBefore: 3600 },
{ text: TITLE(), bold: true, sizeHalfPoints: 72, align: 'center', spaceAfter: 240 },
{
text: SUBTITLE(),
color: GRAY,
sizeHalfPoints: 28,
align: 'center',
borders: 't',
spaceAfter: 4800,
},
{ text: AUTHOR(), sizeHalfPoints: 24, align: 'center' },
{ text: today(), color: GRAY, sizeHalfPoints: 22, align: 'center' },
]),
preset('banded', 'editorCoverBanded', () => [
{ spaceBefore: 2400 },
{
text: TITLE(),
bold: true,
color: 'FFFFFF',
sizeHalfPoints: 64,
align: 'center',
shadingFill: NAVY,
spaceBefore: 600,
spaceAfter: 600,
},
{
text: SUBTITLE(),
color: 'FFFFFF',
sizeHalfPoints: 26,
align: 'center',
shadingFill: BLUE,
spaceAfter: 5200,
},
{ text: `${AUTHOR()} · ${today()}`, color: GRAY, sizeHalfPoints: 22, align: 'center' },
]),
preset('boxed', 'editorCoverBoxed', () => [
{ spaceBefore: 3000 },
{
text: TITLE(),
bold: true,
sizeHalfPoints: 60,
align: 'center',
borders: 'tblr',
spaceBefore: 400,
spaceAfter: 400,
indentLeft: 720,
indentRight: 720,
},
{
text: SUBTITLE(),
color: GRAY,
sizeHalfPoints: 26,
align: 'center',
spaceBefore: 360,
spaceAfter: 5200,
},
{ text: AUTHOR(), sizeHalfPoints: 24, align: 'center' },
{ text: today(), color: GRAY, sizeHalfPoints: 22, align: 'center' },
]),
preset('sideline', 'editorCoverSideline', () => [
{ spaceBefore: 3600 },
{
text: TITLE(),
bold: true,
color: NAVY,
sizeHalfPoints: 64,
align: 'left',
borders: 'l',
indentLeft: 360,
spaceAfter: 200,
},
{
text: SUBTITLE(),
color: GRAY,
sizeHalfPoints: 26,
align: 'left',
borders: 'l',
indentLeft: 360,
spaceAfter: 5600,
},
{ text: AUTHOR(), sizeHalfPoints: 22, align: 'left' },
{ text: today(), color: GRAY, sizeHalfPoints: 22, align: 'left' },
]),
preset('modern', 'editorCoverModern', () => [
{ spaceBefore: 4200 },
{ text: TITLE(), bold: true, color: DARK, sizeHalfPoints: 80, align: 'left', spaceAfter: 120 },
{ text: SUBTITLE(), color: TEAL, sizeHalfPoints: 28, align: 'left', spaceAfter: 5600 },
{ text: `${AUTHOR()} · ${today()}`, color: LIGHT, sizeHalfPoints: 22, align: 'left' },
]),
preset('elegant', 'editorCoverElegant', () => [
{ spaceBefore: 3600 },
{
text: TITLE(),
italic: true,
sizeHalfPoints: 64,
align: 'center',
borders: 'tb',
spaceBefore: 300,
spaceAfter: 300,
indentLeft: 1080,
indentRight: 1080,
},
{
text: SUBTITLE(),
italic: true,
color: GRAY,
sizeHalfPoints: 24,
align: 'center',
spaceBefore: 400,
spaceAfter: 5200,
},
{ text: `${AUTHOR()} · ${today()}`, color: GRAY, sizeHalfPoints: 20, align: 'center' },
]),
preset('minimal', 'editorCoverMinimal', () => [
{ spaceBefore: 5400 },
{ text: TITLE(), color: LIGHT, sizeHalfPoints: 88, align: 'left', spaceAfter: 300 },
{ text: SUBTITLE(), color: GRAY, sizeHalfPoints: 24, align: 'left', spaceAfter: 4800 },
{ text: today(), color: LIGHT, sizeHalfPoints: 20, align: 'left' },
]),
preset('dark', 'editorCoverDark', () => [
{ shadingFill: DARK, spaceBefore: 2000, spaceAfter: 0 },
{
text: TITLE(),
bold: true,
color: 'FFFFFF',
sizeHalfPoints: 68,
align: 'center',
shadingFill: DARK,
spaceBefore: 800,
spaceAfter: 200,
},
{
text: SUBTITLE(),
color: 'D9D9D9',
sizeHalfPoints: 26,
align: 'center',
shadingFill: DARK,
spaceAfter: 800,
},
{ shadingFill: DARK, spaceAfter: 4400 },
{ text: `${AUTHOR()} · ${today()}`, color: GRAY, sizeHalfPoints: 22, align: 'center' },
]),
preset('accent', 'editorCoverAccent', () => [
{ spaceBefore: 3600 },
{ text: TITLE(), bold: true, color: RED, sizeHalfPoints: 68, align: 'left', spaceAfter: 160 },
{
text: SUBTITLE(),
color: GRAY,
sizeHalfPoints: 26,
align: 'left',
borders: 'b',
spaceAfter: 5600,
},
{ text: AUTHOR(), sizeHalfPoints: 22, align: 'right' },
{ text: today(), color: GRAY, sizeHalfPoints: 20, align: 'right' },
]),
preset('badge', 'editorCoverBadge', () => [
{ spaceBefore: 3200 },
{ text: '· · ·', color: GOLD, sizeHalfPoints: 28, align: 'center', spaceAfter: 200 },
{
text: TITLE(),
bold: true,
sizeHalfPoints: 60,
align: 'center',
borders: 'tb',
spaceBefore: 240,
spaceAfter: 240,
indentLeft: 1440,
indentRight: 1440,
},
{
text: SUBTITLE(),
color: GOLD,
sizeHalfPoints: 24,
align: 'center',
spaceBefore: 300,
spaceAfter: 5200,
},
{ text: `${AUTHOR()} · ${today()}`, color: GRAY, sizeHalfPoints: 20, align: 'center' },
]),
preset('facet', 'editorCoverFacet', () => [
{ spaceBefore: 4200 },
{ text: TITLE(), bold: true, color: TEAL, sizeHalfPoints: 64, align: 'right', spaceAfter: 160 },
{
text: SUBTITLE(),
color: GRAY,
sizeHalfPoints: 26,
align: 'right',
borders: 'b',
spaceAfter: 5600,
},
{ text: `${AUTHOR()} · ${today()}`, color: LIGHT, sizeHalfPoints: 20, align: 'right' },
]),
preset('annual', 'editorCoverAnnual', () => [
{ spaceBefore: 3000 },
{
text: String(new Date().getFullYear()),
bold: true,
color: BLUE,
sizeHalfPoints: 144,
align: 'left',
spaceAfter: 0,
},
{
text: TITLE(),
bold: true,
sizeHalfPoints: 56,
align: 'left',
borders: 't',
spaceBefore: 200,
spaceAfter: 120,
},
{ text: SUBTITLE(), color: GRAY, sizeHalfPoints: 24, align: 'left', spaceAfter: 4800 },
{ text: AUTHOR(), color: GRAY, sizeHalfPoints: 22, align: 'left' },
]),
]
function paraNode(p: CoverPara): PmNode {
const marks: Array<{ type: string; attrs?: Record<string, unknown> }> = []
if (p.bold) marks.push({ type: 'bold' })
if (p.italic) marks.push({ type: 'italic' })
if (p.color || p.sizeHalfPoints) {
marks.push({
type: 'docTextStyle',
attrs: {
color: p.color ?? null,
sizeHalfPoints: p.sizeHalfPoints ?? null,
font: null,
highlight: null,
vertAlign: null,
},
})
}
return {
type: 'docParagraph',
attrs: {
docxIndex: null,
aiChanged: false,
align: p.align ?? null,
spaceBefore: p.spaceBefore ?? null,
spaceAfter: p.spaceAfter ?? null,
shadingFill: p.shadingFill ?? null,
borders: p.borders ?? null,
indentLeft: p.indentLeft ?? null,
indentRight: p.indentRight ?? null,
},
...(p.text ? { content: [{ type: 'text', text: p.text, marks }] } : {}),
}
}
/** Cover paragraphs + one trailing page-break empty paragraph (pushes existing content to page 2) */
export function buildCoverNodes(preset: CoverPreset): PmNode[] {
return [
...preset.paras.map(paraNode),
{ type: 'docParagraph', attrs: { docxIndex: null, aiChanged: false, pageBreakBefore: true } },
]
}
/** Insert the cover at the very start of the document (Word behavior: cover is always page 1) */
export function insertCoverPage(editor: Editor, preset: CoverPreset): void {
editor.chain().focus().insertContentAt(0, buildCoverNodes(preset)).run()
}
@@ -0,0 +1,523 @@
import { Extension } from '@tiptap/core'
import { Plugin, PluginKey } from '@tiptap/pm/state'
import { Decoration, DecorationSet, type EditorView } from '@tiptap/pm/view'
import type { Node as ProseMirrorNode } from '@tiptap/pm/model'
import {} from '@tiptap/pm/tables'
import { t } from '../i18n/locale'
import { type TabStop } from '@genoffice/docx-engine'
/**
* Custom schema mirroring the docx-engine Block model 1:1.
* Every top-level node carries `docxIndex` (patch anchor, null = new) and
* `aiChanged` (diff highlighting for AI edits).
*/
import { SearchHighlight } from './extensions'
import { revisionDisplayState } from './marks'
export const searchPluginKey = new PluginKey<DecorationSet>('docSearch')
/** decorates search hits; FindPanel pushes ranges via setMeta(searchPluginKey) */
export const SearchHighlightExtension = Extension.create({
name: 'docSearch',
addProseMirrorPlugins() {
return [
new Plugin({
key: searchPluginKey,
state: {
init: () => DecorationSet.empty,
apply(tr, old) {
const meta = tr.getMeta(searchPluginKey) as SearchHighlight | undefined
if (meta) {
return DecorationSet.create(
tr.doc,
meta.ranges.map((r, i) =>
Decoration.inline(r.from, r.to, {
class: i === meta.activeIndex ? 'search-hit search-hit-active' : 'search-hit',
}),
),
)
}
return old.map(tr.mapping, tr.doc)
},
},
props: {
decorations(state) {
return this.getState(state)
},
},
}),
]
},
})
export const pendingCommentPluginKey = new PluginKey<DecorationSet>('pendingComment')
/**
* keeps the to-be-commented range visibly highlighted while the comment
* composer holds focus (the native selection highlight disappears on blur)
*/
export const PendingCommentHighlightExtension = Extension.create({
name: 'pendingComment',
addProseMirrorPlugins() {
return [
new Plugin({
key: pendingCommentPluginKey,
state: {
init: () => DecorationSet.empty,
apply(tr, old) {
const meta = tr.getMeta(pendingCommentPluginKey) as
{ from: number; to: number } | null | undefined
if (meta === null) return DecorationSet.empty
if (meta) {
return DecorationSet.create(tr.doc, [
Decoration.inline(meta.from, meta.to, { class: 'comment-pending' }),
])
}
return old.map(tr.mapping, tr.doc)
},
},
props: {
decorations(state) {
return this.getState(state)
},
},
}),
]
},
})
export const resolvedCommentsPluginKey = new PluginKey<Set<string>>('resolvedComments')
/**
* Word hides the in-text shading of resolved comment threads. App pushes the
* resolved id set via meta; spans whose ids are all resolved get un-highlighted.
*/
export const ResolvedCommentsExtension = Extension.create({
name: 'resolvedComments',
addProseMirrorPlugins() {
return [
new Plugin({
key: resolvedCommentsPluginKey,
state: {
init: () => new Set<string>(),
apply(tr, old) {
const meta = tr.getMeta(resolvedCommentsPluginKey) as Set<string> | undefined
return meta ?? old
},
},
props: {
decorations(state) {
const done = resolvedCommentsPluginKey.getState(state)
if (!done || done.size === 0) return null
const markType = state.schema.marks.comment
const decos: Decoration[] = []
state.doc.descendants((node, pos) => {
if (!node.isText) return
const mark = node.marks.find((m) => m.type === markType)
if (!mark) return
const ids = String(mark.attrs.ids ?? '')
.split(' ')
.filter(Boolean)
if (ids.length === 0 || !ids.every((id) => done.has(id))) return
decos.push(
Decoration.inline(pos, pos + node.nodeSize, { class: 'doc-comment-resolved' }),
)
})
return DecorationSet.create(state.doc, decos)
},
},
}),
]
},
})
// ---- tab stop rendering extension ----
const tabStopPluginKey = new PluginKey<DecorationSet>('tabStops')
const TWIPS_PER_PX = 15
/** w:defaultTabStop; 720 twips (0.5") is Word's default (settings.xml is not parsed yet) */
const DEFAULT_TAB_TWIPS = 720
interface MeasuredTab {
pos: number
/** CSS tab-size (px) for this tab's decoration span */
cssSize: number
leader?: string
/** run carries the underline mark: browsers do not draw text-decoration
* across a tab advance, so the gap gets a border-bottom line instead */
underlined?: boolean
}
/**
* Measures every tab character (in any textblock, including table cells) and
* turns it into a tab-stop jump: the paragraph gets `tab-size: 0` (class
* has-tab-stops) and each tab char gets an inline decoration with a per-span
* `tab-size: <length>`. Chromium ignores letter-/word-spacing on tab chars,
* but honors a length tab-size: the tab advances to the next multiple of it
* counted from the paragraph's content edge — with size = stop position and
* the tab left of the stop, it lands exactly on the stop. The tab stays a
* plain text character, so an ancestor <u>'s underline is drawn across the
* gap — signature blanks like "By: ____" depend on this.
*
* Word measures stops from the text column edge (page margin / cell content
* edge) while CSS measures from the paragraph content edge, so the paragraph
* indent (margin/padding-left) is subtracted when converting.
*
* Measure → decorate → re-measure converges (a tab's target is absolute, not
* cumulative) and is guarded by a signature check to avoid dispatch loops.
*/
class TabLayoutView {
private lastSig = ''
constructor(private view: EditorView) {
this.measure()
// font swaps change text metrics, which shifts every tab's start x
document.fonts?.ready.then(() => this.measure()).catch(() => {})
}
update() {
this.measure()
}
destroy() {}
private measure() {
const { view } = this
if (!view.dom.isConnected) return
const paras: Array<{ node: ProseMirrorNode; pos: number }> = []
view.state.doc.descendants((node, pos) => {
if (!node.isTextblock) return true
if (node.textContent.includes('\t')) paras.push({ node, pos })
return false
})
const paraRanges: Array<{ from: number; to: number }> = []
const tabs: MeasuredTab[] = []
for (const para of paras) {
const measured = this.measureParagraph(para.node, para.pos)
if (!measured) continue
paraRanges.push({ from: para.pos, to: para.pos + para.node.nodeSize })
tabs.push(...measured)
}
const sig = JSON.stringify([paraRanges, tabs])
if (sig === this.lastSig) return
this.lastSig = sig
const old = tabStopPluginKey.getState(view.state)
if (tabs.length === 0 && paraRanges.length === 0 && (!old || old === DecorationSet.empty))
return
const decos: Decoration[] = []
for (const r of paraRanges)
decos.push(Decoration.node(r.from, r.to, { class: 'has-tab-stops' }))
for (const t of tabs) {
const leader = t.leader && t.leader !== 'none' ? ` doc-tab-leader-${t.leader}` : ''
const underline = t.underlined ? ' doc-tab-underline' : ''
decos.push(
Decoration.inline(t.pos, t.pos + 1, {
class: `doc-tab${leader}${underline}`,
style: `tab-size:${t.cssSize}px`,
}),
)
}
view.dispatch(view.state.tr.setMeta(tabStopPluginKey, decos).setMeta('addToHistory', false))
}
/** null = paragraph not measurable right now (hidden, not mounted...) */
private measureParagraph(node: ProseMirrorNode, pos: number): MeasuredTab[] | null {
const { view } = this
const el = view.nodeDOM(pos)
if (!(el instanceof HTMLElement) || el.offsetWidth === 0) return null
const rect = el.getBoundingClientRect()
if (rect.width === 0) return null
// rects are in screen px (affected by the page zoom transform); widths we
// emit are layout px, so divide all measured distances by the scale factor
const zoom = rect.width / el.offsetWidth
const cs = window.getComputedStyle(el)
if (cs.direction === 'rtl') return null
// Word's tab-stop origin: the text column edge (excludes paragraph indent,
// whether it is margin-left on docParagraph or padding-left on list items)
const marginLeft = parseFloat(cs.marginLeft) || 0
const paddingLeft = parseFloat(cs.paddingLeft) || 0
const originX = rect.left - marginLeft * zoom
// CSS tab-size origin: the paragraph content edge, offset from the column
// edge by the full indent
const contentEdge = marginLeft + paddingLeft
let stops: TabStop[] = []
const raw = node.attrs?.tabStops as string | null
if (raw) {
try {
const parsed = JSON.parse(raw)
if (Array.isArray(parsed)) stops = parsed
} catch {
/* ignore malformed */
}
}
const stopsPx = stops
.filter((s) => s.val !== 'clear' && s.val !== 'bar' && Number.isFinite(s.pos))
.map((s) => ({ x: s.pos / TWIPS_PER_PX, val: s.val, leader: s.leader }))
.sort((a, b) => a.x - b.x)
// doc positions of every tab char in this paragraph
const tabPositions: number[] = []
const tabUnderlined = new Map<number, boolean>()
node.forEach((child, offset) => {
if (!child.isText || !child.text) return
const underlined = child.marks.some((m) => m.type.name === 'underline')
for (let i = 0; i < child.text.length; i++) {
if (child.text[i] !== '\t') continue
const p = pos + 1 + offset + i
tabPositions.push(p)
if (underlined) tabUnderlined.set(p, true)
}
})
const paraEnd = pos + node.nodeSize - 1
const out: MeasuredTab[] = []
for (let i = 0; i < tabPositions.length; i++) {
const tabPos = tabPositions[i]
let coords: { left: number }
try {
coords = view.coordsAtPos(tabPos, 1)
} catch {
continue
}
const x = (coords.left - originX) / zoom
const next = stopsPx.find((s) => s.x > x + 0.5)
let target: number
let val: TabStop['val'] = 'left'
let leader: string | undefined
if (next) {
target = next.x
val = next.val
leader = next.leader
} else {
const grid = DEFAULT_TAB_TWIPS / TWIPS_PER_PX
target = (Math.floor((x + 0.5) / grid) + 1) * grid
}
if (val === 'right' || val === 'decimal' || val === 'center') {
// text between this tab and the next tab (or paragraph end) is aligned
// at the stop; decimal is approximated as right (no '.'-splitting)
const segStart = tabPos + 1
const segEnd = i + 1 < tabPositions.length ? tabPositions[i + 1] : paraEnd
let segWidth = 0
if (segEnd > segStart) {
try {
const endCoords = view.coordsAtPos(segEnd, -1)
segWidth = Math.max(0, (endCoords.left - coords.left) / zoom)
} catch {
/* keep 0 */
}
}
target -= val === 'center' ? segWidth / 2 : segWidth
}
// convert the Word-space target to a CSS tab-size: the next multiple of
// it past the tab's position must be the target itself, so it needs to
// stay greater than the tab's content-edge-relative x
const cssSize = Math.max(target - contentEdge, x - contentEdge + 0.5, 0.5)
// 0.5px rounding damps measure→decorate→re-measure oscillation
out.push({
pos: tabPos,
cssSize: Math.round(cssSize * 2) / 2,
leader,
underlined: tabUnderlined.get(tabPos),
})
}
return out
}
}
export const TabStopExtension = Extension.create({
name: 'tabStops',
addProseMirrorPlugins() {
return [
new Plugin({
key: tabStopPluginKey,
state: {
init: () => DecorationSet.empty,
apply(tr, old) {
const meta = tr.getMeta(tabStopPluginKey) as Decoration[] | undefined
if (meta) return DecorationSet.create(tr.doc, meta)
return old.map(tr.mapping, tr.doc)
},
},
props: {
decorations(state) {
return this.getState(state)
},
},
view: (view) => new TabLayoutView(view),
}),
]
},
})
// ---- drop cap rendering extension ----
const dropCapPluginKey = new PluginKey<DecorationSet>('dropCap')
export const DropCapExtension = Extension.create({
name: 'dropCap',
addProseMirrorPlugins() {
return [
new Plugin({
key: dropCapPluginKey,
props: {
decorations(state) {
const decos: Decoration[] = []
state.doc.forEach((node, offset) => {
const raw = node.attrs?.dropCap as string | null
if (!raw) return
decos.push(
Decoration.node(offset, offset + node.nodeSize, {
'data-drop-cap': raw,
class: 'has-drop-cap',
}),
)
})
return decos.length > 0 ? DecorationSet.create(state.doc, decos) : DecorationSet.empty
},
},
}),
]
},
})
// ---- SDT (structured document tag) rendering extension ----
const sdtPluginKey = new PluginKey<DecorationSet>('sdt')
export const SdtExtension = Extension.create({
name: 'sdt',
addProseMirrorPlugins() {
return [
new Plugin({
key: sdtPluginKey,
props: {
decorations(state) {
const decos: Decoration[] = []
state.doc.forEach((node, offset) => {
const raw = node.attrs?.sdtShell as string | null
if (!raw) return
let alias = ''
try {
const parsed = JSON.parse(raw)
alias = parsed?.alias || parsed?.tag || t('editorContentControl')
} catch {
/* ignore */
}
decos.push(
Decoration.node(offset, offset + node.nodeSize, {
'data-sdt-alias': alias,
class: 'has-sdt',
}),
)
})
return decos.length > 0 ? DecorationSet.create(state.doc, decos) : DecorationSet.empty
},
},
}),
]
},
})
// ---- move revision rendering extension ----
const moveRevisionPluginKey = new PluginKey<DecorationSet>('moveRevision')
export const MoveRevisionExtension = Extension.create({
name: 'moveRevision',
addProseMirrorPlugins() {
return [
new Plugin({
key: moveRevisionPluginKey,
props: {
decorations(state) {
const decos: Decoration[] = []
state.doc.forEach((node, offset) => {
const rev = node.attrs?.moveRevision as string | null
if (!rev) return
decos.push(
Decoration.node(offset, offset + node.nodeSize, {
'data-move-revision': rev,
class: rev === 'from' ? 'has-move-from' : 'has-move-to',
}),
)
})
return decos.length > 0 ? DecorationSet.create(state.doc, decos) : DecorationSet.empty
},
},
}),
]
},
})
// ---- pPrChange (tracked paragraph format) rendering extension ----
const pPrChangePluginKey = new PluginKey<DecorationSet>('pPrChange')
export const PPrChangeExtension = Extension.create({
name: 'pPrChange',
addProseMirrorPlugins() {
return [
new Plugin({
key: pPrChangePluginKey,
props: {
decorations(state) {
const decos: Decoration[] = []
state.doc.forEach((node, offset) => {
const raw = node.attrs?.pPrChange as string | null
if (!raw) return
let author = ''
let old: Record<string, unknown> = {}
try {
const parsed = JSON.parse(raw)
author = parsed?.author || ''
old = (parsed?.old ?? {}) as Record<string, unknown>
} catch {
/* ignore */
}
// original view: override with the pre-revision paragraph format (mirroring the restore subset of revisions.ts reject)
let style = ''
if (revisionDisplayState.mode === 'original') {
const styles = [
`text-align:${(old.align as string) ?? 'start'}`,
`margin-left:${old.indentLeft ? Number(old.indentLeft) / 20 : 0}pt`,
`margin-right:${old.indentRight ? Number(old.indentRight) / 20 : 0}pt`,
`text-indent:${old.indentFirstLine ? Number(old.indentFirstLine) / 20 : 0}pt`,
`margin-top:${old.spaceBefore ? Number(old.spaceBefore) / 20 : 0}pt`,
`margin-bottom:${old.spaceAfter ? Number(old.spaceAfter) / 20 : 0}pt`,
`background:${old.shadingFill ? `#${old.shadingFill}` : 'transparent'}`,
]
if (old.lineRule === 'exact' || old.lineRule === 'atLeast') {
styles.push(`line-height:${Number(old.lineRawTwips || 240) / 20}pt`)
} else if (old.lineSpacing) {
styles.push(`line-height:${Number(old.lineSpacing) * 1.2}`)
} else {
styles.push('line-height:inherit')
}
style = styles.join(';')
}
decos.push(
Decoration.node(offset, offset + node.nodeSize, {
'data-ppr-change-author': author,
'data-ppr-change-label': t('editorFormatRevision'),
class: 'has-ppr-change',
...(style ? { style } : {}),
}),
)
})
return decos.length > 0 ? DecorationSet.create(state.doc, decos) : DecorationSet.empty
},
},
}),
]
},
})
+51
View File
@@ -0,0 +1,51 @@
import { latexToOmml, mathParagraphXml, mathTokensOf, ommlToMathML } from '@genoffice/docx-engine'
import { t } from '../i18n/locale'
import type { PmNode } from './convert'
/**
* Protected display-equation block built from LaTeX (throws on syntax outside
* the supported subset). Shared by the insert dialog/gallery and the AI
* <formula> tag; genXml carries the OMML through the save path.
*/
/** MathML for inline flow (ommlToMathML emits display="block" for equations) */
export function inlineMathML(omml: string): string {
return ommlToMathML(omml).replace(/ display="block"/g, ' display="inline"')
}
/**
* Atomic inline formula node built from LaTeX (throws on unsupported syntax).
* Flows with paragraph text; saves as a Run.math (<m:oMath> emitted verbatim).
*/
export function inlineEquationNodeJson(latex: string): PmNode {
const inner = latexToOmml(latex)
const omml = `<m:oMath>${inner}</m:oMath>`
return {
type: 'docInlineMath',
attrs: {
omml,
mathml: inlineMathML(omml),
latex: latex.trim(),
text: mathTokensOf(omml).join(''),
},
}
}
export function equationBlockJson(latex: string): PmNode {
const omml = latexToOmml(latex)
return {
type: 'docProtected',
attrs: {
docxIndex: null,
blockType: 'passthrough',
label: t('editorEquation'),
previewText: latex.trim(),
genXml: mathParagraphXml(omml),
formulaDisplay: {
tokens: mathTokensOf(omml),
mathml: ommlToMathML(`<m:oMath>${omml}</m:oMath>`),
omml: `<m:oMath>${omml}</m:oMath>`,
latex: latex.trim(),
},
},
}
}
File diff suppressed because it is too large Load Diff
+34
View File
@@ -0,0 +1,34 @@
import type { Editor } from '@tiptap/core'
/** Word's ribbon indent step: half an inch, in twips */
const STEP = 720
/** Ribbon increase/decrease indent: list items change level, plain paragraphs and headings snap to the next half-inch stop */
export function stepParagraphIndent(editor: Editor, delta: 1 | -1): boolean {
if (editor.isActive('docListItem')) {
const ilvl = Number(editor.getAttributes('docListItem').ilvl) || 0
const next = Math.min(Math.max(ilvl + delta, 0), 8)
return editor.chain().focus().updateAttributes('docListItem', { ilvl: next }).run()
}
return editor
.chain()
.focus()
.command(({ state, tr, dispatch }) => {
const { from, to } = state.selection
let changed = false
state.doc.nodesBetween(from, to, (node, pos) => {
if (node.type.name !== 'docParagraph' && node.type.name !== 'docHeading') return
const cur = Number(node.attrs.indentLeft) || 0
const next =
delta > 0
? Math.floor(cur / STEP) * STEP + STEP
: Math.max(Math.ceil(cur / STEP) * STEP - STEP, 0)
if (next === cur) return
tr.setNodeMarkup(pos, undefined, { ...node.attrs, indentLeft: next || null })
changed = true
})
if (changed && dispatch) dispatch(tr)
return changed
})
.run()
}
+246
View File
@@ -0,0 +1,246 @@
import type { InkInfo, NewInkImage } from '@genoffice/docx-engine'
/**
* Ink annotations (freehand drawing strokes) — editor-side model.
*
* Strokes live on a transparent overlay above the page. Each stroke is
* anchored to a body paragraph: its points are stored relative to that
* paragraph's top-left corner at 100% zoom, which maps 1:1 onto the engine's
* wp:anchor offsets (positionH from column, positionV from paragraph). At
* save time every stroke is rasterized into a transparent PNG floating
* picture; the vector points travel along in wp:docPr descr so reopening the
* file in our editor restores live, erasable strokes.
*/
export type InkTool = 'select' | 'pen' | 'highlighter' | 'eraser'
export interface InkPoint {
x: number
y: number
}
export interface InkStroke {
tool: 'pen' | 'highlighter'
/** hex without '#' */
color: string
/** stroke width in px at 100% zoom */
width: number
/** px relative to the anchor paragraph's top-left, 100% zoom */
points: InkPoint[]
}
/**
* One annotation on the overlay. Editor-drawn annotations carry `stroke`
* (editable vectors); annotations restored from a document without a
* readable payload carry `image` instead (movable/erasable as a whole).
*/
export interface InkAnnotation {
id: string
/** docxIndex of the anchor paragraph in the current parsed doc */
anchorIndex: number
stroke?: InkStroke
image?: {
dataUrl: string
offsetXPx: number
offsetYPx: number
widthPx: number
heightPx: number
}
}
let inkIdSeq = 0
export const nextInkId = () => `ink${Date.now()}-${inkIdSeq++}`
// ---- payload (wp:docPr descr) round-trip ----
const PAYLOAD_VERSION = 1
export function encodeInkPayload(stroke: InkStroke): string {
return JSON.stringify({
v: PAYLOAD_VERSION,
tool: stroke.tool,
color: stroke.color,
width: stroke.width,
// round to 0.1px: descr must stay reasonably small on long strokes
points: stroke.points.map((p) => [Math.round(p.x * 10) / 10, Math.round(p.y * 10) / 10]),
})
}
export function decodeInkPayload(payload: string): InkStroke | null {
try {
const data = JSON.parse(payload) as {
v?: number
tool?: string
color?: string
width?: number
points?: [number, number][]
}
if (data.v !== PAYLOAD_VERSION || !Array.isArray(data.points) || data.points.length === 0) {
return null
}
return {
tool: data.tool === 'highlighter' ? 'highlighter' : 'pen',
color: typeof data.color === 'string' ? data.color : '000000',
width: typeof data.width === 'number' && data.width > 0 ? data.width : 2,
points: data.points.map(([x, y]) => ({ x, y })),
}
} catch {
return null
}
}
/** Restore overlay annotations from a freshly parsed document. */
export function annotationsFromParsed(inks: InkInfo[]): InkAnnotation[] {
return inks.map((ink) => {
const stroke = ink.payload ? decodeInkPayload(ink.payload) : null
if (stroke) return { id: nextInkId(), anchorIndex: ink.anchorIndex, stroke }
return {
id: nextInkId(),
anchorIndex: ink.anchorIndex,
image: {
dataUrl: ink.dataUrl ?? '',
offsetXPx: ink.offsetXPx,
offsetYPx: ink.offsetYPx,
widthPx: ink.widthPx,
heightPx: ink.heightPx,
},
}
})
}
// ---- geometry ----
export interface InkBounds {
x: number
y: number
w: number
h: number
}
/** bounding box of a stroke including its line width (+1px antialias margin) */
export function strokeBounds(stroke: InkStroke): InkBounds {
let minX = Infinity
let minY = Infinity
let maxX = -Infinity
let maxY = -Infinity
for (const p of stroke.points) {
if (p.x < minX) minX = p.x
if (p.y < minY) minY = p.y
if (p.x > maxX) maxX = p.x
if (p.y > maxY) maxY = p.y
}
const pad = stroke.width / 2 + 1
return {
x: minX - pad,
y: minY - pad,
w: maxX - minX + pad * 2,
h: maxY - minY + pad * 2,
}
}
/** distance from a point to the segment ab */
function segmentDistance(p: InkPoint, a: InkPoint, b: InkPoint): number {
const dx = b.x - a.x
const dy = b.y - a.y
const lenSq = dx * dx + dy * dy
const t =
lenSq === 0 ? 0 : Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / lenSq))
const cx = a.x + t * dx
const cy = a.y + t * dy
return Math.hypot(p.x - cx, p.y - cy)
}
/** true when the point is within `threshold` of any segment of the stroke */
export function strokeHitTest(stroke: InkStroke, point: InkPoint, threshold: number): boolean {
const reach = threshold + stroke.width / 2
const pts = stroke.points
if (pts.length === 1) return Math.hypot(point.x - pts[0].x, point.y - pts[0].y) <= reach
for (let i = 1; i < pts.length; i++) {
if (segmentDistance(point, pts[i - 1], pts[i]) <= reach) return true
}
return false
}
/** SVG path data through the stroke points (simple polyline) */
export function strokePathD(points: InkPoint[]): string {
if (points.length === 0) return ''
if (points.length === 1) {
// dot: tiny segment so stroke-linecap can render it
return `M ${points[0].x} ${points[0].y} L ${points[0].x + 0.01} ${points[0].y}`
}
return points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' ')
}
export const HIGHLIGHTER_ALPHA = 0.45
// ---- save-time rasterization ----
/** raster output of one annotation: transparent PNG + placement */
export interface InkRaster {
base64: string
widthPx: number
heightPx: number
offsetXPx: number
offsetYPx: number
}
/** default renderer: draw the stroke on a transparent canvas at 2x scale */
export function rasterizeStroke(stroke: InkStroke): InkRaster {
const bounds = strokeBounds(stroke)
const scale = 2
const canvas = document.createElement('canvas')
canvas.width = Math.max(1, Math.ceil(bounds.w * scale))
canvas.height = Math.max(1, Math.ceil(bounds.h * scale))
const ctx = canvas.getContext('2d')!
ctx.scale(scale, scale)
ctx.translate(-bounds.x, -bounds.y)
ctx.strokeStyle = `#${stroke.color}`
ctx.lineWidth = stroke.width
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
if (stroke.tool === 'highlighter') ctx.globalAlpha = HIGHLIGHTER_ALPHA
ctx.beginPath()
const pts = stroke.points
ctx.moveTo(pts[0].x, pts[0].y)
if (pts.length === 1) ctx.lineTo(pts[0].x + 0.01, pts[0].y)
for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x, pts[i].y)
ctx.stroke()
return {
base64: canvas.toDataURL('image/png').split(',')[1],
widthPx: Math.max(1, Math.ceil(bounds.w)),
heightPx: Math.max(1, Math.ceil(bounds.h)),
offsetXPx: bounds.x,
offsetYPx: bounds.y,
}
}
/**
* Build the engine's ink list for a save. Annotations whose anchor paragraph
* no longer exists in the save plan are dropped (their paragraph was deleted).
*/
export function buildInkImages(
annotations: InkAnnotation[],
saveBlockIndexByDocx: Map<number, number>,
rasterize: (stroke: InkStroke) => InkRaster = rasterizeStroke,
): NewInkImage[] {
const out: NewInkImage[] = []
for (const ann of annotations) {
const blockIndex = saveBlockIndexByDocx.get(ann.anchorIndex)
if (blockIndex === undefined) continue
if (ann.stroke) {
const raster = rasterize(ann.stroke)
out.push({ blockIndex, ...raster, payload: encodeInkPayload(ann.stroke) })
} else if (ann.image && ann.image.dataUrl.startsWith('data:image/png;base64,')) {
// restored foreign/opaque annotation: carry the original PNG through
out.push({
blockIndex,
base64: ann.image.dataUrl.slice('data:image/png;base64,'.length),
widthPx: ann.image.widthPx,
heightPx: ann.image.heightPx,
offsetXPx: ann.image.offsetXPx,
offsetYPx: ann.image.offsetYPx,
})
}
}
return out
}
+449
View File
@@ -0,0 +1,449 @@
import { Extension, Mark } from '@tiptap/core'
import { Plugin, PluginKey } from '@tiptap/pm/state'
import { Decoration, DecorationSet } from '@tiptap/pm/view'
import {} from '@tiptap/pm/tables'
import { cssFontFamily } from '../line-metrics'
import { t } from '../i18n/locale'
import {} from '@genoffice/docx-engine'
/**
* Custom schema mirroring the docx-engine Block model 1:1.
* Every top-level node carries `docxIndex` (patch anchor, null = new) and
* `aiChanged` (diff highlighting for AI edits).
*/
export const BoldMark = Mark.create({
name: 'bold',
parseHTML() {
return [
{ tag: 'strong' },
// Word-pasted <b style="font-weight:normal"> doesn't count as bold
{
tag: 'b',
getAttrs: (el) => ((el as HTMLElement).style.fontWeight !== 'normal' ? null : false),
},
{
style: 'font-weight',
getAttrs: (value) =>
value === 'bold' || value === 'bolder' || parseInt(String(value), 10) >= 600
? null
: false,
},
]
},
renderHTML() {
return ['strong', 0]
},
addKeyboardShortcuts() {
return { 'Mod-b': () => this.editor.commands.toggleMark('bold') }
},
})
export const ItalicMark = Mark.create({
name: 'italic',
parseHTML() {
return [{ tag: 'em' }, { tag: 'i' }, { style: 'font-style=italic' }]
},
renderHTML() {
return ['em', 0]
},
addKeyboardShortcuts() {
return { 'Mod-i': () => this.editor.commands.toggleMark('italic') }
},
})
export const UnderlineMark = Mark.create({
name: 'underline',
parseHTML() {
return [
{ tag: 'u' },
{
style: 'text-decoration',
getAttrs: (value) => (String(value).includes('underline') ? null : false),
},
]
},
renderHTML() {
return ['u', 0]
},
addKeyboardShortcuts() {
return { 'Mod-u': () => this.editor.commands.toggleMark('underline') }
},
})
export const StrikeMark = Mark.create({
name: 'strike',
parseHTML() {
return [
{ tag: 's' },
{ tag: 'del' },
{ tag: 'strike' },
{
style: 'text-decoration',
getAttrs: (value) => (String(value).includes('line-through') ? null : false),
},
]
},
renderHTML() {
return ['s', 0]
},
})
export const LinkMark = Mark.create({
name: 'link',
inclusive: false,
addAttributes() {
return {
href: { default: '' },
rId: { default: null as string | null },
tooltip: { default: null as string | null },
}
},
parseHTML() {
return [
{
tag: 'a[href]',
getAttrs: (el) => ({
href: (el as HTMLElement).getAttribute('href') ?? '',
tooltip: (el as HTMLElement).getAttribute('title'),
}),
},
]
},
renderHTML({ mark }) {
return [
'a',
{
href: mark.attrs.href,
class: 'doc-link',
...(mark.attrs.tooltip ? { title: String(mark.attrs.tooltip) } : {}),
},
0,
]
},
})
/**
* Word comment range: rendered as a highlighted span carrying its comment ids
* (space-separated), so the comments panel can jump to it. `inclusive: false`
* keeps typing at the range edges from silently extending the comment.
*/
export const CommentMark = Mark.create({
name: 'comment',
inclusive: false,
addAttributes() {
return {
ids: { default: '' },
}
},
parseHTML() {
return [{ tag: 'span[data-comment-ids]' }]
},
renderHTML({ mark }) {
return ['span', { 'data-comment-ids': mark.attrs.ids, class: 'doc-comment' }, 0]
},
})
/**
* Tracked insertion (w:ins). Rendered underlined in the revision color; hover
* shows author/date. `inclusive: false` so typing at the edge of someone
* else's insertion doesn't inherit their authorship — the track-changes
* recorder marks new input itself.
*/
export const InsMark = Mark.create({
name: 'ins',
inclusive: false,
addAttributes() {
return {
author: { default: '' },
date: { default: null as string | null },
id: { default: null as string | null },
}
},
parseHTML() {
return [{ tag: 'span[data-ins-author]' }]
},
renderHTML({ mark }) {
return [
'span',
{
'data-ins-author': mark.attrs.author,
class: 'doc-ins',
title: `${t('editorInsertedBy', { author: String(mark.attrs.author) })}${mark.attrs.date ? ` · ${String(mark.attrs.date).slice(0, 10)}` : ''}`,
},
0,
]
},
})
/** Tracked deletion (w:del). Rendered struck-through in the revision color. */
export const DelMark = Mark.create({
name: 'del',
inclusive: false,
addAttributes() {
return {
author: { default: '' },
date: { default: null as string | null },
id: { default: null as string | null },
}
},
parseHTML() {
return [{ tag: 'span[data-del-author]' }]
},
renderHTML({ mark }) {
return [
'span',
{
'data-del-author': mark.attrs.author,
class: 'doc-del',
title: `${t('editorDeletedBy', { author: String(mark.attrs.author) })}${mark.attrs.date ? ` · ${String(mark.attrs.date).slice(0, 10)}` : ''}`,
},
0,
]
},
})
/** OOXML named highlight color -> CSS color, for on-screen rendering */
export const HIGHLIGHT_CSS: Record<string, string> = {
yellow: '#FFFF00',
green: '#00FF00',
cyan: '#00FFFF',
magenta: '#FF00FF',
blue: '#0000FF',
red: '#FF0000',
darkBlue: '#00008B',
darkCyan: '#008B8B',
darkGreen: '#006400',
darkMagenta: '#8B008B',
darkRed: '#8B0000',
darkYellow: '#808000',
darkGray: '#808080',
lightGray: '#C0C0C0',
black: '#000000',
white: '#FFFFFF',
}
/** Cross-reference (REF field): gray background, title hints the target bookmark, text is the cached display result */
export const RefFieldMark = Mark.create({
name: 'refField',
addAttributes() {
return { name: { default: '' } }
},
parseHTML() {
return [{ tag: 'span[data-ref-field]' }]
},
renderHTML({ mark }) {
return [
'span',
{
'data-ref-field': String(mark.attrs.name),
class: 'doc-ref-field',
title: t('editorCrossReference', { name: String(mark.attrs.name) }),
},
0,
]
},
})
/** Revision display mode (synced by App; in original mode the extension below restores old formatting via decorations) */
export const revisionDisplayState = { mode: 'all' as 'all' | 'none' | 'original' }
const revisionOriginalKey = new PluginKey('revisionOriginal')
/**
* Original view (shown as if rejected): for text with rPrChange, restore the pre-revision
* modeled formatting via inner decorations (mirroring revisions.ts reject logic). The inner
* span can override bold/italic, color, font size, and font; undoing underline/strikethrough
* isn't possible in CSS, so it stays approximate.
*/
export const RevisionOriginalExtension = Extension.create({
name: 'revisionOriginal',
addProseMirrorPlugins() {
return [
new Plugin({
key: revisionOriginalKey,
props: {
decorations(state) {
if (revisionDisplayState.mode !== 'original') return DecorationSet.empty
const decos: Decoration[] = []
state.doc.descendants((node, pos) => {
if (!node.isText) return
const rpr = node.marks.find((m) => m.type.name === 'rprChange')
if (!rpr) return
const old = (rpr.attrs.old ?? {}) as Record<string, unknown>
const styles = [
`font-weight:${old.bold ? 600 : 400}`,
`font-style:${old.italic ? 'italic' : 'normal'}`,
]
if (old.color) styles.push(`color:#${old.color}`)
if (old.sizeHalfPoints) styles.push(`font-size:${Number(old.sizeHalfPoints) / 2}pt`)
if (old.font) styles.push(`font-family:${cssFontFamily(String(old.font))}`)
decos.push(Decoration.inline(pos, pos + node.nodeSize, { style: styles.join(';') }))
})
return decos.length > 0 ? DecorationSet.create(state.doc, decos) : DecorationSet.empty
},
},
}),
]
},
})
/** Run-level format revision (w:rPrChange): shown with an amber squiggle; accept/reject on the Review tab */
export const RprChangeMark = Mark.create({
name: 'rprChange',
addAttributes() {
return {
author: { default: '' },
date: { default: null as string | null },
id: { default: null as string | null },
old: { default: null as Record<string, unknown> | null, rendered: false },
}
},
parseHTML() {
return [{ tag: 'span[data-rpr-change]' }]
},
renderHTML({ mark }) {
return [
'span',
{
'data-rpr-change': '1',
class: 'has-rpr-change',
title: t('editorFormatChangeBy', {
author: String(mark.attrs.author || t('editorUnknownAuthor')),
}),
},
0,
]
},
})
/** Generic inline field (DATE/TIME/NUMPAGES/FILENAME…): text is the cached result, recomputed on F9 */
export const InstrFieldMark = Mark.create({
name: 'instrField',
addAttributes() {
return { instr: { default: '' } }
},
parseHTML() {
return [{ tag: 'span[data-instr-field]' }]
},
renderHTML({ mark }) {
return [
'span',
{
'data-instr-field': String(mark.attrs.instr),
class: 'doc-ref-field',
title: t('editorFieldHint', { instr: String(mark.attrs.instr) }),
},
0,
]
},
})
/** Inline styles of foreign HTML → docTextStyle attrs (returns false when no usable style, so no mark is applied) */
function textStyleAttrsFromDom(el: HTMLElement): Record<string, unknown> | false {
const attrs: Record<string, unknown> = {}
const st = el.style
const hex = (css: string): string | null => {
if (!css) return null
const rgb = /rgba?\((\d+)[,\s]+(\d+)[,\s]+(\d+)/.exec(css)
if (rgb) {
return [rgb[1], rgb[2], rgb[3]]
.map((n) => Number(n).toString(16).padStart(2, '0'))
.join('')
.toUpperCase()
}
const m = /^#([0-9a-fA-F]{6})$/.exec(css.trim())
return m ? m[1].toUpperCase() : null
}
const color = hex(st.color)
if (color && color !== '000000') attrs.color = color
const size = st.fontSize
if (size) {
const v = parseFloat(size)
if (Number.isFinite(v) && v > 0) {
if (size.endsWith('pt')) attrs.sizeHalfPoints = Math.round(v * 2)
else if (size.endsWith('px')) attrs.sizeHalfPoints = Math.round(v * 1.5)
}
}
const family = st.fontFamily
?.split(',')[0]
?.trim()
.replace(/^["']|["']$/g, '')
if (family) attrs.font = family
const spacing = parseFloat(st.letterSpacing)
if (Number.isFinite(spacing) && spacing !== 0) {
attrs.charSpacingTwips = Math.round(
st.letterSpacing.endsWith('px') ? spacing * 15 : spacing * 20,
)
}
if (st.verticalAlign === 'super') attrs.vertAlign = 'superscript'
else if (st.verticalAlign === 'sub') attrs.vertAlign = 'subscript'
const styleId = el.getAttribute('data-style')
if (styleId) attrs.styleId = styleId
return Object.keys(attrs).length > 0 ? attrs : false
}
/** color: hex without '#'; sizeHalfPoints: OOXML half-points; highlight: OOXML named color */
export const TextStyleMark = Mark.create({
name: 'docTextStyle',
addAttributes() {
return {
color: { default: null as string | null },
sizeHalfPoints: { default: null as number | null },
font: { default: null as string | null },
charSpacingTwips: { default: null as number | null },
// letter spacing (em, negative = condensed) converted from w:w scaling; precomputed by convert per run text
charScaleEm: { default: null as number | null },
highlight: { default: null as string | null },
vertAlign: { default: null as 'superscript' | 'subscript' | null },
// East Asian emphasis mark (w:em val); saving is kept faithful by rawRPr
em: { default: null as string | null },
styleId: { default: null as string | null },
// raw rPr slice pass-through (not rendered; on save mergeRPrModel preserves unmodeled attributes)
rawRPr: { default: null as string | null, rendered: false },
}
},
parseHTML() {
return [
{
tag: 'span[data-doc-style]',
getAttrs: (el) => textStyleAttrsFromDom(el as HTMLElement) || {},
},
{ tag: 'sup', attrs: { vertAlign: 'superscript' } },
{ tag: 'sub', attrs: { vertAlign: 'subscript' } },
// inline-styled span from foreign paste (color/size/font); no mark applied when no usable style
{ tag: 'span', getAttrs: (el) => textStyleAttrsFromDom(el as HTMLElement) },
]
},
renderHTML({ mark }) {
const styles: string[] = []
if (mark.attrs.color) styles.push(`color:#${mark.attrs.color}`)
if (mark.attrs.sizeHalfPoints)
styles.push(`font-size:${Number(mark.attrs.sizeHalfPoints) / 2}pt`)
if (mark.attrs.font) styles.push(`font-family:${cssFontFamily(String(mark.attrs.font))}`)
const spacingPt = mark.attrs.charSpacingTwips ? Number(mark.attrs.charSpacingTwips) / 20 : 0
const scaleEm = mark.attrs.charScaleEm ? Number(mark.attrs.charScaleEm) : 0
if (spacingPt && scaleEm) styles.push(`letter-spacing:calc(${spacingPt}pt + ${scaleEm}em)`)
else if (spacingPt) styles.push(`letter-spacing:${spacingPt}pt`)
else if (scaleEm) styles.push(`letter-spacing:${scaleEm}em`)
if (mark.attrs.highlight) {
styles.push(
`background-color:${HIGHLIGHT_CSS[mark.attrs.highlight as string] ?? mark.attrs.highlight}`,
)
}
if (mark.attrs.vertAlign === 'superscript') styles.push('vertical-align:super;font-size:0.75em')
if (mark.attrs.vertAlign === 'subscript') styles.push('vertical-align:sub;font-size:0.75em')
if (mark.attrs.em) {
const em = String(mark.attrs.em)
const shape = em === 'circle' ? 'open circle' : em === 'comma' ? 'filled sesame' : 'filled dot'
// Word renders Chinese emphasis marks (dot/underDot) below the text; comma/circle kenten go above
const pos = em === 'comma' || em === 'circle' ? 'over' : 'under'
styles.push(`text-emphasis:${shape}`, `text-emphasis-position:${pos} right`)
}
const attrs: Record<string, string> = { 'data-doc-style': '1', style: styles.join(';') }
if (mark.attrs.styleId) attrs['data-style'] = String(mark.attrs.styleId)
return ['span', attrs, 0]
},
})
// ---- textbox sub-editor schema ----
+151
View File
@@ -0,0 +1,151 @@
import { decodeSymbolText, isSymbolFont, type NumberingDef } from '@genoffice/docx-engine'
/** Word represents bullets with Symbol/Wingdings private-use characters; map them to common glyphs */
const BULLET_GLYPHS: Record<string, string> = {
'': '•',
'': '▪',
'': '➢',
'': '❖',
'': '✓',
o: '◦',
}
const DEFAULT_BULLETS = ['•', '◦', '▪', '•', '◦', '▪', '•', '◦', '▪']
function toLetters(value: number): string {
// Word: 1..26 -> A..Z, 27 -> AA (repeated same letter, not positional notation)
const n = ((value - 1) % 26) + 1
const repeat = Math.floor((value - 1) / 26) + 1
return String.fromCharCode(64 + n).repeat(repeat)
}
const ROMAN: Array<[number, string]> = [
[1000, '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'],
]
function toRoman(value: number): string {
let n = Math.max(1, value)
let out = ''
for (const [v, s] of ROMAN) {
while (n >= v) {
out += s
n -= v
}
}
return out
}
const CN_DIGITS = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
function toChinese(value: number): string {
if (value <= 0 || value > 9999) return String(value)
if (value < 10) return CN_DIGITS[value]
const units = ['', '十', '百', '千']
const digits = String(value).split('').map(Number)
let out = ''
for (let i = 0; i < digits.length; i++) {
const d = digits[i]
const unit = units[digits.length - 1 - i]
if (d === 0) {
if (!out.endsWith('零') && i < digits.length - 1) out += '零'
} else {
out += CN_DIGITS[d] + unit
}
}
out = out.replace(/零+$/, '')
// 10-19 drop the leading "one" digit: read as "shi x" rather than "yi shi x"
return out.replace(/^一十/, '十')
}
export function formatNumber(value: number, numFmt: string): string {
switch (numFmt) {
case 'decimalZero':
return value < 10 && value >= 0 ? `0${value}` : String(value)
case 'lowerLetter':
return toLetters(value).toLowerCase()
case 'upperLetter':
return toLetters(value)
case 'lowerRoman':
return toRoman(value).toLowerCase()
case 'upperRoman':
return toRoman(value)
case 'chineseCounting':
case 'chineseCountingThousand':
case 'japaneseCounting':
return toChinese(value)
case 'decimalEnclosedCircle':
return value >= 1 && value <= 20 ? String.fromCodePoint(0x2460 + value - 1) : String(value)
case 'none':
return ''
default:
return String(value)
}
}
export interface ListItemRef {
numId: string | null
ilvl: number
}
/**
* Word numbering semantics: counters accumulate document-wide per abstractNum
* (plain paragraphs in between don't break the sequence); when a level appears,
* its deeper levels reset; startOverride applies the first time that numId uses
* the level. Returns a marker array the same length as items; items without a
* definition return null (CSS fallback handles them).
*/
export function computeListMarkers(
items: ListItemRef[],
defs: Map<string, NumberingDef>,
): (string | null)[] {
const counters = new Map<string, number[]>()
const overrideApplied = new Set<string>()
return items.map((item) => {
const def = item.numId !== null ? defs.get(item.numId) : undefined
if (!def) return null
const lvl = Math.max(0, item.ilvl)
const level = def.levels[lvl]
if (!level) return null
if (level.numFmt === 'bullet') {
// symbol-encoded marker fonts (Wingdings "l" = ●): decode by font first
const decoded = level.font ? decodeSymbolText(level.font, level.lvlText) : null
const glyph = decoded ?? BULLET_GLYPHS[level.lvlText] ?? level.lvlText
// undecodable symbol-font glyphs, private-use or empty ones fall back to the per-level default
if (!glyph || /[-]/.test(glyph) || (decoded === null && isSymbolFont(level.font)))
return DEFAULT_BULLETS[lvl % 9]
return glyph
}
const c = counters.get(def.abstractNumId) ?? []
counters.set(def.abstractNumId, c)
const overrideKey = `${def.numId}:${lvl}`
if (def.startOverrides[lvl] !== undefined && !overrideApplied.has(overrideKey)) {
overrideApplied.add(overrideKey)
c[lvl] = def.startOverrides[lvl]
} else {
c[lvl] = (c[lvl] ?? level.start - 1) + 1
}
c.length = lvl + 1
const marker = level.lvlText.replace(/%(\d)/g, (_, d: string) => {
const refLvl = Number(d) - 1
const refDef = def.levels[refLvl]
const value = c[refLvl] ?? refDef?.start ?? 1
return formatNumber(value, refDef?.numFmt ?? 'decimal')
})
return marker || null
})
}
@@ -0,0 +1,141 @@
import { Extension } from '@tiptap/core'
import { Plugin, PluginKey } from '@tiptap/pm/state'
import { Decoration, DecorationSet } from '@tiptap/pm/view'
import type { EditorView } from '@tiptap/pm/view'
const key = new PluginKey<DecorationSet>('paginationGaps')
/**
* Always-on pagination in the canvas: renders a "page gap" widget before each
* page-leading block (previous page's bottom margin + gray inter-page band +
* next page's top margin). Decorations are visual only; document content and
* saving are unaffected. Positions are driven by App's pagination measurement;
* gaps map along transactions while editing and are rebuilt wholesale after a debounce.
*/
export const PaginationGapsExtension = Extension.create({
name: 'paginationGaps',
addProseMirrorPlugins() {
return [
new Plugin<DecorationSet>({
key,
state: {
init: () => DecorationSet.empty,
apply(tr, set) {
const next = tr.getMeta(key) as DecorationSet | undefined
if (next) return next
return set.map(tr.mapping, tr.doc)
},
},
props: {
decorations(state) {
return key.getState(state)
},
},
}),
]
},
})
export interface GapMetrics {
marginTop: number
marginBottom: number
marginLeft: number
marginRight: number
}
const GAP_BAND = 28
function makeGapEl(m: GapMetrics, kind: 'block' | 'inline' | 'table' | 'cut'): HTMLElement {
const gap = document.createElement(kind === 'table' ? 'tr' : 'div')
gap.contentEditable = 'false'
if (kind === 'cut') {
// in-row table break cut point: zero-height dashed marker (takes no layout height, coordinate bookkeeping unchanged)
gap.className = 'page-gap-cut'
return gap
}
gap.style.height = `${m.marginBottom + GAP_BAND + m.marginTop}px`
gap.style.setProperty('--gap-mb', `${m.marginBottom}px`)
gap.style.setProperty('--gap-mt', `${m.marginTop}px`)
if (kind === 'table') {
// A real spanning cell is required here. Chromium's collapsed-border table
// painting can leak the neighboring row's border/fill through a cell-less
// display:table-row, leaving a colored remnant in the gray page gutter.
gap.className = 'page-gap page-gap-inline page-gap-table'
const cell = document.createElement('td')
cell.colSpan = 1000
cell.contentEditable = 'false'
const fill = document.createElement('div')
fill.className = 'page-gap-table-fill'
cell.appendChild(fill)
gap.appendChild(cell)
return gap
}
gap.className = kind === 'inline' ? 'page-gap page-gap-inline' : 'page-gap'
gap.style.marginLeft = `-${m.marginLeft}px`
gap.style.marginRight = `-${m.marginRight}px`
// inline-block (not block-level): avoids block-in-inline anonymous-box splitting,
// which would re-apply text-indent/alignment on continuation lines and drift line
// breaks; negative margins don't widen an inline-block, so width explicitly adds the bleed
if (kind === 'inline') gap.style.width = `calc(100% + ${m.marginLeft + m.marginRight}px)`
return gap
}
/** Page gap anchor: el = top-level page-leading block (inserted before it); pos = document position at a mid-paragraph/mid-table break */
export type PageGapSpec = {
metrics: GapMetrics
/** Previous page's bottom footnote area (a ready-made positioned/sized element) and its content signature (change triggers rebuild) */
notes?: HTMLElement
notesKey?: string
} & ({ el: HTMLElement } | { pos: number; kind?: 'inline' | 'table' | 'cut' })
/** Rebuild all page gaps (an empty list clears them); each gap carries its own margins (sections differ) */
export function setPageGaps(view: EditorView, gaps: PageGapSpec[]): void {
const decos: Decoration[] = []
for (const gap of gaps) {
const { metrics, notes } = gap
let pos: number
let kind: 'block' | 'inline' | 'table' | 'cut'
if ('el' in gap) {
kind = 'block'
try {
const inside = view.posAtDOM(gap.el, 0)
pos = view.state.doc.resolve(inside).before(1)
} catch {
continue
}
} else {
pos = gap.pos
kind = gap.kind ?? 'inline'
}
const mKey = `${metrics.marginTop},${metrics.marginBottom},${metrics.marginLeft},${metrics.marginRight}`
decos.push(
Decoration.widget(
pos,
() => {
const el = makeGapEl(metrics, kind)
if (notes) el.appendChild(notes)
return el
},
{
side: -1,
key: `page-gap-${kind[0]}-${pos}-${mKey}${gap.notesKey ? `-${gap.notesKey}` : ''}`,
},
),
)
}
const next = DecorationSet.create(view.state.doc, decos)
const prev = key.getState(view.state)
if (prev && sameGaps(prev, next)) return
view.dispatch(view.state.tr.setMeta(key, next).setMeta('addToHistory', false))
}
function sameGaps(a: DecorationSet, b: DecorationSet): boolean {
const keyOf = (d: Decoration) => (d.spec as { key?: string }).key ?? ''
const af = a.find()
const bf = b.find()
return (
af.length === bf.length &&
af.every((d, i) => d.from === bf[i].from && keyOf(d) === keyOf(bf[i]))
)
}
@@ -0,0 +1,579 @@
import type { Node as PmNode } from '@tiptap/pm/model'
import {} from '@tiptap/pm/state'
import type { EditorView } from '@tiptap/pm/view'
import {} from '@tiptap/pm/tables'
import { cssFontFamily } from '../line-metrics'
import { t } from '../i18n/locale'
import {
type ChartDisplay,
type FieldDisplay,
type FormulaDisplay,
type TableModel,
type TextboxDisplay,
} from '@genoffice/docx-engine'
/**
* Custom schema mirroring the docx-engine Block model 1:1.
* Every top-level node carries `docxIndex` (patch anchor, null = new) and
* `aiChanged` (diff highlighting for AI edits).
*/
import {
DomSpec,
ProtectedContentEditor,
TableBordersAttr,
cellPadCss,
preventProtectedLineBreak,
protectedText,
tableBordersCss,
} from './extensions'
// Word: links and TOC entries jump on modifier+click only
const jumpHint = () =>
navigator.platform.toLowerCase().includes('mac') ? t('editorJumpHintMac') : t('editorJumpHintWin')
/** Rendering of a field result; safe visible text becomes editable on double-click. */
export function renderFieldSpec(field: FieldDisplay): DomSpec | null {
if (field.kind === 'tocLine') {
const attrs: Record<string, string> = {
class: `doc-toc-line doc-toc-l${Math.min(field.level ?? 1, 4)}`,
'data-toc-title': field.left ?? '',
title: jumpHint(),
}
if (field.anchor) attrs['data-toc-anchor'] = field.anchor
return [
'div',
attrs,
['span', { class: 'doc-toc-title', contenteditable: 'false' }, field.left || '\u00a0'],
['span', { class: 'doc-toc-dots' }],
['span', { class: 'doc-toc-page', contenteditable: 'false' }, field.right ?? ''],
]
}
if (field.kind === 'pageBreak') {
return ['div', { class: 'doc-field-pagebreak' }, ['span', {}, t('editorPageBreak')]]
}
if (field.kind === 'text' && field.left) {
return ['div', { class: 'doc-field-text', contenteditable: 'false' }, field.left]
}
return null
}
export function renderFormulaSpec(formula: FormulaDisplay): DomSpec {
const tokenStrip: DomSpec = [
'span',
{ class: 'doc-formula' + (formula.mathml ? ' doc-formula-has-math' : '') },
...formula.tokens.map((token, index): DomSpec => [
'span',
{
class: 'doc-formula-token',
'data-token-index': String(index),
contenteditable: 'false',
},
token || '\u00a0',
]),
]
if (!formula.mathml) return tokenStrip
// the MathML host is empty in the spec; buildProtectedDom injects the markup
// (renderSpec cannot emit raw MathML)
return [
'span',
{ class: 'doc-formula-wrap' },
['span', { class: 'doc-formula-math', contenteditable: 'false' }],
tokenStrip,
]
}
// ---- embedded charts: SVG preview + editable data grid ----
/** Office theme default accent colors, used for new charts */
const CHART_PALETTE = ['4472C4', 'ED7D31', 'A5A5A5', 'FFC000', '5B9BD5', '70AD47']
const chartColor = (i: number) => `#${CHART_PALETTE[i % CHART_PALETTE.length]}`
/**
* Chart preview + data grid. The grid is a chart data sheet
* (rows = series, columns = categories); its cells and the title become
* editable on double-click, everything else stays protected.
*/
export function renderChartSpec(chart: ChartDisplay): DomSpec {
const children: DomSpec[] = []
if (chart.title !== undefined) {
children.push([
'div',
{ class: 'doc-chart-title', contenteditable: 'false' },
chart.title || '\u00a0',
])
}
// SVG preview drawn imperatively after mount (renderSpec has no SVG namespace)
children.push(['div', { class: 'doc-chart-canvas' }])
const colCount = Math.max(chart.categories.length, ...chart.series.map((s) => s.values.length))
const headCells: DomSpec[] = [['th', { class: 'doc-chart-corner' }, '\u00a0']]
for (let c = 0; c < colCount; c++) {
headCells.push([
'th',
{ class: 'doc-chart-cell doc-chart-cat', 'data-cat': String(c), contenteditable: 'false' },
chart.categories[c] || '\u00a0',
])
}
const rows: DomSpec[] = [['tr', {}, ...headCells]]
chart.series.forEach((ser, s) => {
const cells: DomSpec[] = [
[
'th',
{
class: `doc-chart-name${ser.name !== undefined ? ' doc-chart-cell' : ''}`,
'data-ser': String(s),
contenteditable: 'false',
style: `border-left-color:${chartColor(s)}`,
},
ser.name ?? t('editorChartSeries', { num: s + 1 }),
],
]
for (let c = 0; c < colCount; c++) {
const value = ser.values[c]
cells.push([
'td',
{
// cache gaps have no pt to patch; they stay read-only
class: value === null ? 'doc-chart-gap' : 'doc-chart-cell doc-chart-val',
'data-ser': String(s),
'data-val': String(c),
contenteditable: 'false',
},
value === null || value === undefined ? '' : String(value),
])
}
rows.push(['tr', {}, ...cells])
})
children.push(['table', { class: 'doc-chart-data' }, ...rows])
return ['div', { class: 'doc-chart' }, ...children]
}
const SVG_NS = 'http://www.w3.org/2000/svg'
interface ChartGeom {
width: number
height: number
left: number
right: number
top: number
bottom: number
}
/** draw the read-only SVG preview into the node's .doc-chart-canvas */
export function drawChartSvg(dom: HTMLElement, chart: ChartDisplay | null): void {
const canvas = dom.querySelector<HTMLElement>('.doc-chart-canvas')
if (!canvas || !chart?.series.length) return
const geom: ChartGeom = { width: 560, height: 240, left: 46, right: 12, top: 12, bottom: 26 }
const svg = document.createElementNS(SVG_NS, 'svg')
svg.setAttribute('viewBox', `0 0 ${geom.width} ${geom.height}`)
svg.setAttribute('class', 'doc-chart-svg')
if (chart.kind === 'pie') drawPie(svg, chart, geom)
else drawAxes(svg, chart, geom)
canvas.replaceChildren(svg)
}
function svgEl(
parent: Element,
tag: string,
attrs: Record<string, string>,
text?: string,
): Element {
const el = document.createElementNS(SVG_NS, tag)
for (const [key, value] of Object.entries(attrs)) el.setAttribute(key, value)
if (text !== undefined) el.textContent = text
parent.appendChild(el)
return el
}
/** bar / line / area charts share the same axes and scale */
function drawAxes(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
const values = chart.series.flatMap((s) => s.values).filter((v): v is number => v !== null)
const max = Math.max(0, ...values)
const min = Math.min(0, ...values)
const span = max - min || 1
const plotW = geom.width - geom.left - geom.right
const plotH = geom.height - geom.top - geom.bottom
const cols = Math.max(chart.categories.length, ...chart.series.map((s) => s.values.length), 1)
const yOf = (v: number) => geom.top + plotH - ((v - min) / span) * plotH
const slotW = plotW / cols
// horizontal gridlines with value labels
const steps = 4
for (let i = 0; i <= steps; i++) {
const v = min + (span / steps) * i
const y = yOf(v)
svgEl(svg, 'line', {
x1: String(geom.left),
y1: String(y),
x2: String(geom.width - geom.right),
y2: String(y),
class: 'doc-chart-grid',
})
svgEl(
svg,
'text',
{
x: String(geom.left - 6),
y: String(y + 3),
class: 'doc-chart-axis-label',
'text-anchor': 'end',
},
formatAxisValue(v),
)
}
// category labels
chart.categories.forEach((cat, c) => {
if (c >= cols) return
svgEl(
svg,
'text',
{
x: String(geom.left + slotW * c + slotW / 2),
y: String(geom.height - geom.bottom + 14),
class: 'doc-chart-axis-label',
'text-anchor': 'middle',
},
cat,
)
})
if (chart.kind === 'bar') {
const groupPad = slotW * 0.15
const barW = (slotW - groupPad * 2) / chart.series.length
chart.series.forEach((ser, s) => {
ser.values.forEach((value, c) => {
if (value === null) return
const x = geom.left + slotW * c + groupPad + barW * s
const y0 = yOf(0)
const y1 = yOf(value)
svgEl(svg, 'rect', {
x: String(x + barW * 0.08),
y: String(Math.min(y0, y1)),
width: String(barW * 0.84),
height: String(Math.max(1, Math.abs(y0 - y1))),
fill: chartColor(s),
})
})
})
} else {
// line / area / other: one polyline per series through slot centers
chart.series.forEach((ser, s) => {
const points = ser.values
.map((value, c) =>
value === null ? null : `${geom.left + slotW * c + slotW / 2},${yOf(value)}`,
)
.filter((p): p is string => p !== null)
if (points.length === 0) return
if (chart.kind === 'area' && points.length > 1) {
const first = points[0].split(',')[0]
const last = points[points.length - 1].split(',')[0]
svgEl(svg, 'polygon', {
points: `${first},${yOf(0)} ${points.join(' ')} ${last},${yOf(0)}`,
fill: chartColor(s),
'fill-opacity': '0.35',
stroke: 'none',
})
}
svgEl(svg, 'polyline', {
points: points.join(' '),
fill: 'none',
stroke: chartColor(s),
'stroke-width': '2',
})
})
}
}
/** pie preview renders the first series only */
function drawPie(svg: SVGElement, chart: ChartDisplay, geom: ChartGeom): void {
const values = chart.series[0].values.map((v) => (v === null || v < 0 ? 0 : v))
const total = values.reduce((a, b) => a + b, 0)
if (total <= 0) return
const cx = geom.width / 2
const cy = geom.height / 2
const r = Math.min(geom.width, geom.height) / 2 - 16
let angle = -Math.PI / 2
values.forEach((value, i) => {
if (value === 0) return
const sweep = (value / total) * Math.PI * 2
const x1 = cx + r * Math.cos(angle)
const y1 = cy + r * Math.sin(angle)
angle += sweep
const x2 = cx + r * Math.cos(angle)
const y2 = cy + r * Math.sin(angle)
const large = sweep > Math.PI ? 1 : 0
const d =
values.filter((v) => v > 0).length === 1
? `M ${cx - r} ${cy} A ${r} ${r} 0 1 1 ${cx - r} ${cy - 0.01} Z`
: `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2} Z`
svgEl(svg, 'path', { d, fill: chartColor(i), stroke: '#fff', 'stroke-width': '1' })
})
}
function formatAxisValue(v: number): string {
const rounded = Math.round(v * 100) / 100
return Math.abs(rounded) >= 1000 ? String(Math.round(rounded)) : String(rounded)
}
/** Edit chart title / series names / category labels / cached values in place. */
export function wireChartEditing(
dom: HTMLElement,
getNode: () => PmNode,
getPos: () => number | undefined,
view: EditorView,
): (ProtectedContentEditor & { cleanup(): void }) | null {
const chart = getNode().attrs.chartDisplay as ChartDisplay | null
if (!chart) return null
const targets = Array.from(dom.querySelectorAll<HTMLElement>('.doc-chart-cell, .doc-chart-title'))
if (targets.length === 0) return null
const setEditable = (editable: boolean) => {
for (const target of targets)
target.setAttribute('contenteditable', editable ? 'true' : 'false')
}
const commit = () => {
const current = getNode()
const model = current.attrs.chartDisplay as ChartDisplay | null
if (!model) return
const next: ChartDisplay = {
...model,
categories: [...model.categories],
series: model.series.map((s) => ({ ...s, values: [...s.values] })),
}
const title = dom.querySelector<HTMLElement>('.doc-chart-title')
if (title && next.title !== undefined) next.title = protectedText(title).trim()
for (const cat of Array.from(dom.querySelectorAll<HTMLElement>('.doc-chart-cat'))) {
const c = parseInt(cat.dataset.cat ?? '', 10)
if (c >= 0 && c < next.categories.length) next.categories[c] = protectedText(cat).trim()
}
for (const name of Array.from(
dom.querySelectorAll<HTMLElement>('.doc-chart-name.doc-chart-cell'),
)) {
const s = parseInt(name.dataset.ser ?? '', 10)
if (next.series[s]) next.series[s].name = protectedText(name).trim()
}
for (const cell of Array.from(dom.querySelectorAll<HTMLElement>('.doc-chart-val'))) {
const s = parseInt(cell.dataset.ser ?? '', 10)
const c = parseInt(cell.dataset.val ?? '', 10)
const ser = next.series[s]
if (!ser || c < 0 || c >= ser.values.length) continue
const parsed = Number(protectedText(cell).trim().replace(/,/g, ''))
// unparseable input keeps the original number instead of corrupting the cache
if (Number.isFinite(parsed)) ser.values[c] = parsed
}
if (JSON.stringify(next) === JSON.stringify(model)) return
const pos = getPos()
if (typeof pos !== 'number') return
view.dispatch(
view.state.tr.setNodeMarkup(pos, undefined, { ...current.attrs, chartDisplay: next }),
)
}
for (const target of targets) target.addEventListener('keydown', preventProtectedLineBreak)
window.addEventListener('ai-docs-commit-tables', commit)
return {
setEditable,
commit,
cleanup: () => {
for (const target of targets) target.removeEventListener('keydown', preventProtectedLineBreak)
window.removeEventListener('ai-docs-commit-tables', commit)
},
}
}
/** rendering of an anchored textbox (code box / callout card); text is editable in place */
/** CSS clip-path/borderRadius for DrawingML prstGeom shapes. */
const PRST_CSS: Record<string, { clipPath?: string; borderRadius?: string }> = {
roundRect: { borderRadius: '12%' },
ellipse: { borderRadius: '50%' },
triangle: { clipPath: 'polygon(50% 0%, 0% 100%, 100% 100%)' },
rtTriangle: { clipPath: 'polygon(0% 0%, 0% 100%, 100% 100%)' },
diamond: { clipPath: 'polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%)' },
parallelogram: { clipPath: 'polygon(15% 0%, 100% 0%, 85% 100%, 0% 100%)' },
pentagon: { clipPath: 'polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%)' },
hexagon: { clipPath: 'polygon(25% 0%, 75% 0%, 100% 50%, 75% 100%, 25% 100%, 0% 50%)' },
star5: {
clipPath:
'polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%)',
},
rightArrow: { clipPath: 'polygon(0% 25%, 65% 25%, 65% 0%, 100% 50%, 65% 100%, 65% 75%, 0% 75%)' },
leftRightArrow: {
clipPath:
'polygon(0% 50%, 20% 0%, 20% 30%, 80% 30%, 80% 0%, 100% 50%, 80% 100%, 80% 70%, 20% 70%, 20% 100%)',
},
}
/**
* WordArt preset CSS approximation applied to the entire textbox container.
* color: used as -webkit-text-fill-color; stroke: optional -webkit-text-stroke.
*/
const WORDART_CSS: Record<string, { color: string; stroke?: string; textShadow?: string }> = {
'wordArt-1': { color: '#4472C4' },
'wordArt-2': { color: '#7B2FBE', stroke: '1px #4472C4' },
'wordArt-3': { color: 'transparent', stroke: '2px #4472C4' },
'wordArt-4': { color: '#1F3864', textShadow: '2px 2px 4px rgba(0,0,0,0.5)' },
'wordArt-5': { color: '#ED7D31', textShadow: '0 0 8px #ED7D31, 0 0 16px #ED7D31' },
'wordArt-6': { color: '#C00000' },
}
export function textboxBoxStyle(box: TextboxDisplay): string {
const insetTop = box.insetTopPx ?? 4.8
const insetRight = box.insetRightPx ?? 9.6
const insetBottom = box.insetBottomPx ?? 4.8
const insetLeft = box.insetLeftPx ?? 9.6
const shapeStyle = box.prst ? PRST_CSS[box.prst] : undefined
const waStyle = box.wordArtId ? WORDART_CSS[box.wordArtId] : undefined
return [
box.fill ? `background:#${box.fill}` : '',
box.borderColor && !shapeStyle?.clipPath ? `border-color:#${box.borderColor}` : '',
box.borderColor && shapeStyle?.clipPath ? `outline:2px solid #${box.borderColor}` : '',
box.widthPx ? `width:${box.widthPx}px` : '',
// Word clips fixed-height (noAutofit) boxes instead of growing them
box.heightPx ? `height:${box.heightPx}px` : '',
`padding:${insetTop}px ${insetRight}px ${insetBottom}px ${insetLeft}px`,
shapeStyle?.clipPath ? `clip-path:${shapeStyle.clipPath}` : '',
shapeStyle?.borderRadius ? `border-radius:${shapeStyle.borderRadius}` : '',
waStyle?.color ? `-webkit-text-fill-color:${waStyle.color}` : '',
waStyle?.stroke ? `-webkit-text-stroke:${waStyle.stroke}` : '',
waStyle?.textShadow ? `text-shadow:${waStyle.textShadow}` : '',
]
.filter(Boolean)
.join(';')
}
export function renderTextboxSpec(box: TextboxDisplay): DomSpec {
const style = textboxBoxStyle(box)
const boxAttrs: Record<string, string> = { class: 'doc-textbox' }
if (style) boxAttrs.style = style
const paras: DomSpec[] = box.paras.map((para) => {
const spans: DomSpec[] = para.runs.map((run) => {
const runStyle = [
run.color ? `color:#${run.color}` : '',
run.bold ? 'font-weight:700' : '',
run.italic ? 'font-style:italic' : '',
run.underline ? 'text-decoration:underline' : '',
run.font ? `font-family:${cssFontFamily(run.font)}` : '',
run.sizeHalfPoints ? `font-size:${run.sizeHalfPoints / 2}pt` : '',
]
.filter(Boolean)
.join(';')
return runStyle ? ['span', { style: runStyle }, run.text] : ['span', {}, run.text]
})
const pStyles = [
para.align ? `text-align:${para.align}` : '',
para.lineSpacing ? `line-height:${para.lineSpacing * 1.2}` : '',
para.indentLeft ? `margin-left:${para.indentLeft / 20}pt` : '',
para.indentRight ? `margin-right:${para.indentRight / 20}pt` : '',
para.indentFirstLine ? `text-indent:${para.indentFirstLine / 20}pt` : '',
para.spaceBefore ? `margin-top:${para.spaceBefore / 20}pt` : '',
para.spaceAfter ? `margin-bottom:${para.spaceAfter / 20}pt` : '',
]
.filter(Boolean)
.join(';')
const pAttrs: Record<string, string> = {
class: `doc-textbox-para${spans.length === 0 ? ' doc-textbox-para-empty' : ''}`,
}
if (pStyles) pAttrs.style = pStyles
// empty paragraphs hold a <br> so the caret can land on them while editing
return spans.length > 0 ? ['div', pAttrs, ...spans] : ['div', pAttrs, ['br', {}]]
})
return ['div', boxAttrs, ...paras]
}
/** read-only <table> DOM spec from the display model (vMerge -> rowSpan) */
export function renderTableSpec(model: TableModel): DomSpec {
// grid positions per row (accounting for colSpan) so vertical merges line up
const positions: number[][] = model.rows.map((row) => {
let col = 0
return row.map((cell) => {
const at = col
col += cell.colSpan ?? 1
return at
})
})
const bodyRows: DomSpec[] = model.rows.map((row, ri) => {
const tds: DomSpec[] = []
row.forEach((cell, ci) => {
if (cell.vMerge === 'continue') return
let rowSpan = 1
if (cell.vMerge === 'restart') {
const gridCol = positions[ri][ci]
for (let r = ri + 1; r < model.rows.length; r++) {
const idx = positions[r].indexOf(gridCol)
if (idx === -1 || model.rows[r][idx].vMerge !== 'continue') break
rowSpan++
}
}
const style = [
cell.textDirection === 'tbRl'
? 'writing-mode:vertical-rl'
: cell.textDirection === 'btLr'
? 'writing-mode:sideways-lr'
: '',
cell.fill ? `background:#${cell.fill}` : '',
cell.color ? `color:#${cell.color}` : '',
cell.bold ? 'font-weight:600' : '',
cell.align ? `text-align:${cell.align}` : '',
...(['top', 'left', 'bottom', 'right'] as const).map((side) =>
cell.cellMarTwips?.[side] !== undefined
? `padding-${side}:${(cell.cellMarTwips[side]! / 15).toFixed(1)}px`
: '',
),
]
.filter(Boolean)
.join(';')
const tdAttrs: Record<string, string> = {}
if (style) tdAttrs.style = style
if (cell.colSpan && cell.colSpan > 1) tdAttrs.colspan = String(cell.colSpan)
if (rowSpan > 1) tdAttrs.rowspan = String(rowSpan)
const content: unknown[] = []
cell.paras.forEach((p, i) => {
if (i > 0) content.push(['br', {}])
if (p !== '') content.push(p)
})
for (const nt of cell.nestedTables ?? []) content.push(renderTableSpec(nt))
if (content.length === 0) content.push('\u00a0')
tds.push(['td', tdAttrs, ...content])
})
return ['tr', {}, ...tds]
})
const tableChildren: unknown[] = []
const colPx = !model.widthPct
? model.colWidthsTwips?.map((w) => Math.max(24, Math.round(w / 15)))
: undefined
if (colPx) {
tableChildren.push(['colgroup', {}, ...colPx.map((w) => ['col', { style: `width:${w}px` }])])
} else if (model.colWidthsPct) {
tableChildren.push([
'colgroup',
{},
...model.colWidthsPct.map((w) => ['col', { style: `width:${w.toFixed(2)}%` }]),
])
}
tableChildren.push(['tbody', {}, ...bodyRows])
const tableAttrs: Record<string, string> = { class: 'doc-table' }
if (model.bidiVisual) tableAttrs.dir = 'rtl'
const tableStyles: string[] = []
if (model.widthPct) tableStyles.push(`width:${model.widthPct}%`)
else if (colPx) tableStyles.push(`width:${colPx.reduce((sum, w) => sum + w, 0)}px`)
const pad = cellPadCss(model.cellMarTwips ?? null)
if (pad) tableStyles.push(`--doc-cell-pad:${pad}`)
tableStyles.push(...tableBordersCss((model.borders as TableBordersAttr | undefined) ?? null))
if (model.align === 'center') tableStyles.push('margin-left:auto', 'margin-right:auto')
else if (model.align === 'right') tableStyles.push('margin-left:auto')
else if (model.indentTwips)
tableStyles.push(`margin-left:${(model.indentTwips / 15).toFixed(1)}px`)
if (tableStyles.length > 0) tableAttrs.style = tableStyles.join(';')
return ['table', tableAttrs, ...tableChildren]
}
// ---- marks ----
+935
View File
@@ -0,0 +1,935 @@
/**
* Word revisions (track changes) support for the TipTap editor.
*
* - TrackChangesExtension records edits as ins / del marks while enabled
* (Word: Review → Track Changes).
* - collectRevisions / accept* / reject* implement Accept/Reject Changes.
*
* Semantics of a text range carrying BOTH marks (inserted while tracking,
* then deleted while tracking): the text never existed in the base document,
* so both accepting and rejecting remove it.
*/
import { Extension, type Editor } from '@tiptap/core'
import type { Node as PmNode } from '@tiptap/pm/model'
import { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'
import {
AddMarkStep,
Mapping,
RemoveMarkStep,
ReplaceAroundStep,
ReplaceStep,
} from '@tiptap/pm/transform'
import { t } from '../i18n/locale'
export interface RevisionRange {
from: number
to: number
kind:
| 'ins'
| 'del'
| 'both'
| 'pPrChange'
| 'moveFrom'
| 'moveTo'
| 'rPrChange'
| 'rowIns'
| 'rowDel'
| 'cellIns'
| 'cellDel'
| 'blockIns'
| 'blockDel'
author: string
date?: string
}
/** transactions carrying this meta are never recorded as revisions */
export const TRACK_IGNORE = 'trackIgnore'
const TRACKED_FORMAT_MARKS = new Set(['bold', 'italic', 'underline', 'strike', 'docTextStyle'])
const TEXT_STYLE_FIELDS = [
'color',
'sizeHalfPoints',
'font',
'charSpacingTwips',
'charScaleEm',
'highlight',
'vertAlign',
'styleId',
] as const
const PARAGRAPH_NODE_TYPES = new Set(['docParagraph', 'docHeading', 'docListItem'])
const PARAGRAPH_FORMAT_FIELDS = [
'align',
'lineSpacing',
'lineRule',
'lineRawTwips',
'indentLeft',
'indentRight',
'indentFirstLine',
'spaceBefore',
'spaceAfter',
'pageBreakBefore',
'shadingFill',
'borders',
'tabStops',
'dropCap',
'bidi',
] as const
const PARAGRAPH_STRUCTURE_FIELDS = ['styleId', 'level', 'kind', 'numId', 'ilvl'] as const
const xmlAttr = (value: string) =>
value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')
interface ParagraphSnapshot {
type: string
format: Record<string, unknown>
styleId: unknown
level: unknown
kind: unknown
numId: unknown
ilvl: unknown
}
function paragraphSnapshot(node: PmNode): ParagraphSnapshot {
const format: Record<string, unknown> = {}
for (const field of PARAGRAPH_FORMAT_FIELDS) format[field] = node.attrs[field] ?? null
return {
type: node.type.name,
format,
styleId: node.attrs.styleId ?? null,
level: node.attrs.level ?? null,
kind: node.attrs.kind ?? null,
numId: node.attrs.numId ?? null,
ilvl: node.attrs.ilvl ?? null,
}
}
function paragraphPropertiesChanged(before: PmNode, after: PmNode): boolean {
if (before.type !== after.type) return true
return [...PARAGRAPH_FORMAT_FIELDS, ...PARAGRAPH_STRUCTURE_FIELDS].some(
(field) => (before.attrs[field] ?? null) !== (after.attrs[field] ?? null),
)
}
function formatSnapshot(node: PmNode): Record<string, unknown> {
const textStyle = node.marks.find((m) => m.type.name === 'docTextStyle')
const snapshot: Record<string, unknown> = {
bold: node.marks.some((m) => m.type.name === 'bold'),
italic: node.marks.some((m) => m.type.name === 'italic'),
underline: node.marks.some((m) => m.type.name === 'underline'),
strike: node.marks.some((m) => m.type.name === 'strike'),
}
for (const field of TEXT_STYLE_FIELDS) {
const value = textStyle?.attrs[field]
if (value !== null && value !== undefined) snapshot[field] = value
}
return snapshot
}
/** contiguous revision ranges in document order (adjacent same-kind ranges merged) */
export function collectRevisions(doc: PmNode): RevisionRange[] {
const out: RevisionRange[] = []
// Table row / cell revisions (trPr w:ins/w:del, tcPr w:cellIns/w:cellDel).
// Text ins/del marks inside such a row/cell belong to the same revision and
// are suppressed in the text pass (Word: one revision per inserted/deleted row).
const tableRevs: RevisionRange[] = []
const suppressed: Array<{ from: number; to: number; kind: 'ins' | 'del' }> = []
doc.forEach((node, pos) => {
const revision = node.attrs?.blockRevision as {
kind?: 'ins' | 'del'
author?: string
date?: string
} | null
if (!revision?.kind) return
out.push({
from: pos,
to: pos + node.nodeSize,
kind: revision.kind === 'ins' ? 'blockIns' : 'blockDel',
author: revision.author ?? '',
...(revision.date ? { date: revision.date } : {}),
})
suppressed.push({ from: pos, to: pos + node.nodeSize, kind: revision.kind })
})
doc.descendants((node, pos) => {
const name = node.type.name
if (name !== 'docTableRow' && name !== 'docTableCell' && name !== 'docTableHeader') return
const isRow = name === 'docTableRow'
const rev = (isRow ? node.attrs?.rowRevision : node.attrs?.cellRevision) as {
kind?: 'ins' | 'del'
author?: string
date?: string
} | null
if (!rev?.kind) return
tableRevs.push({
from: pos,
to: pos + node.nodeSize,
kind: isRow
? rev.kind === 'ins'
? 'rowIns'
: 'rowDel'
: rev.kind === 'ins'
? 'cellIns'
: 'cellDel',
author: rev.author ?? '',
...(rev.date ? { date: rev.date } : {}),
})
suppressed.push({ from: pos, to: pos + node.nodeSize, kind: rev.kind })
})
const isSuppressed = (pos: number, kind: 'ins' | 'del' | 'both') =>
suppressed.some((s) => pos >= s.from && pos < s.to && (kind === 'both' || s.kind === kind))
// First pass: collect paragraph revisions at any depth, including table cells.
doc.descendants((node, pos) => {
if (!PARAGRAPH_NODE_TYPES.has(node.type.name)) return
const pPrChange = node.attrs?.pPrChange as string | null
const moveRevision = node.attrs?.moveRevision as string | null
if (pPrChange) {
let author = ''
let date: string | undefined
try {
const parsed = JSON.parse(pPrChange)
author = parsed?.author ?? ''
date = parsed?.date
} catch {
/* ignore */
}
out.push({
from: pos,
to: pos + node.nodeSize,
kind: 'pPrChange',
author,
...(date ? { date } : {}),
})
} else if (moveRevision === 'from' || moveRevision === 'to') {
out.push({
from: pos,
to: pos + node.nodeSize,
kind: moveRevision === 'from' ? 'moveFrom' : 'moveTo',
author: '',
})
}
})
// Second pass: collect run-level text revisions (ins/del marks)
doc.descendants((node, pos) => {
if (!node.isText) return
const ins = node.marks.find((m) => m.type.name === 'ins')
const del = node.marks.find((m) => m.type.name === 'del')
if (!ins && !del) {
const rpr = node.marks.find((m) => m.type.name === 'rprChange')
if (!rpr) return
const author = String(rpr.attrs.author ?? '')
const prev = out[out.length - 1]
if (prev && prev.to === pos && prev.kind === 'rPrChange' && prev.author === author) {
prev.to = pos + node.nodeSize
} else {
out.push({
from: pos,
to: pos + node.nodeSize,
kind: 'rPrChange',
author,
...(rpr.attrs.date ? { date: String(rpr.attrs.date) } : {}),
})
}
return
}
const kind: 'ins' | 'del' | 'both' = ins && del ? 'both' : ins ? 'ins' : 'del'
if (isSuppressed(pos, kind)) return
const src = del ?? ins!
const author = String(src.attrs.author ?? '')
const prev = out[out.length - 1]
if (prev && prev.to === pos && prev.kind === kind && prev.author === author) {
prev.to = pos + node.nodeSize
} else {
out.push({
from: pos,
to: pos + node.nodeSize,
kind,
author,
...(src.attrs.date ? { date: String(src.attrs.date) } : {}),
})
}
})
out.push(...tableRevs)
return out.sort((a, b) => a.from - b.from)
}
/** strip a tracked-change marker element from raw trPr/tcPr bytes; empty container → null */
function stripTrackMarker(raw: string | null, tag: string, container: string): string | null {
if (!raw) return raw
const out = raw
.replace(new RegExp(`<${tag}[^>]*/>`, 'g'), '')
.replace(new RegExp(`<${tag}[^>]*>[\\s\\S]*?</${tag}>`, 'g'), '')
if (new RegExp(`^<${container}(?:\\s[^>]*)?>\\s*</${container}>$`).test(out)) return null
return out
}
function applyRevisions(editor: Editor, ranges: RevisionRange[], mode: 'accept' | 'reject'): void {
if (ranges.length === 0) return
const { state } = editor
const tr = state.tr
tr.setMeta(TRACK_IGNORE, true)
// reverse order keeps earlier positions valid while later ranges mutate
for (const r of [...ranges].sort((a, b) => b.from - a.from)) {
if (r.kind === 'blockIns' || r.kind === 'blockDel') {
const revisionKind = r.kind === 'blockIns' ? 'ins' : 'del'
const removeNode = mode === 'accept' ? revisionKind === 'del' : revisionKind === 'ins'
const nodePos = tr.mapping.map(r.from, -1)
const node = tr.doc.nodeAt(nodePos)
if (!node) continue
if (removeNode) {
if (tr.doc.childCount > 1) tr.delete(nodePos, nodePos + node.nodeSize)
} else {
tr.setNodeMarkup(nodePos, undefined, { ...node.attrs, blockRevision: null })
}
continue
}
if (r.kind === 'pPrChange') {
const $pos = state.doc.resolve(r.from + 1)
if ($pos.parent.attrs && $pos.parent.attrs.pPrChange != null) {
const nodePos = $pos.before($pos.depth)
if (mode === 'reject') {
const oldFormatStr = $pos.parent.attrs.pPrChange as string
let old: Record<string, unknown> = {}
try {
const info = JSON.parse(oldFormatStr)
old = (info?.old ?? {}) as Record<string, unknown>
if (info?.oldAlign !== undefined) old = { ...old, align: info.oldAlign }
} catch {
/* ignore */
}
const oldFormat = (
old.format && typeof old.format === 'object' ? old.format : old
) as Record<string, unknown>
const restore: Record<string, unknown> = {}
for (const field of PARAGRAPH_FORMAT_FIELDS) restore[field] = oldFormat[field] ?? null
const hasStructureSnapshot = typeof old.type === 'string'
if (hasStructureSnapshot) {
for (const field of PARAGRAPH_STRUCTURE_FIELDS) restore[field] = old[field] ?? null
}
const oldTypeName = typeof old.type === 'string' ? old.type : $pos.parent.type.name
const oldType = state.schema.nodes[oldTypeName] ?? $pos.parent.type
tr.setNodeMarkup(nodePos, oldType, {
...$pos.parent.attrs,
pPrChange: null,
...restore,
})
} else {
// accept: just clear the pPrChange attr (keep current format)
tr.setNodeMarkup(nodePos, undefined, { ...$pos.parent.attrs, pPrChange: null })
}
}
continue
}
if (r.kind === 'rPrChange') {
// accept = keep the current format; reject = restore the pre-revision modeled format subset.
// Both clear the rprChange mark and strip the w:rPrChange record from rawRPr (takes effect on save)
state.doc.nodesBetween(r.from, r.to, (node, pos) => {
if (!node.isText) return
const from = Math.max(pos, r.from)
const to = Math.min(pos + node.nodeSize, r.to)
const rpr = node.marks.find((m) => m.type.name === 'rprChange')
const ts = node.marks.find((m) => m.type.name === 'docTextStyle')
if (mode === 'reject' && rpr) {
const old = (rpr.attrs.old ?? {}) as Record<string, unknown>
for (const flag of ['bold', 'italic', 'underline', 'strike'] as const) {
const markType = state.schema.marks[flag]
if (!markType) continue
if (old[flag]) tr.addMark(from, to, markType.create())
else tr.removeMark(from, to, markType)
}
const tsType = state.schema.marks.docTextStyle
if (tsType) {
const baseAttrs = ts ? { ...ts.attrs } : {}
const nextAttrs: Record<string, unknown> = { ...baseAttrs }
for (const field of TEXT_STYLE_FIELDS) nextAttrs[field] = old[field] ?? null
// Reject goes back to the modeled old format. rawRPr contains the new
// format plus the revision record, so rebuild instead of preserving it.
nextAttrs.rawRPr = null
const hasAny = TEXT_STYLE_FIELDS.some(
(field) => nextAttrs[field] !== null && nextAttrs[field] !== undefined,
)
if (ts || hasAny) tr.addMark(from, to, tsType.create(nextAttrs))
}
}
if (ts?.attrs.rawRPr && /<w:rPrChange/.test(String(ts.attrs.rawRPr))) {
const raw = String(ts.attrs.rawRPr).replace(
/<w:rPrChange[\s\S]*?<\/w:rPrChange>|<w:rPrChange[^>]*\/>/,
'',
)
// the reject branch already rebuilt docTextStyle above; strip the record here only on accept or when nothing was rebuilt
const cur = mode === 'reject' ? null : ts
if (cur) tr.addMark(from, to, cur.type.create({ ...cur.attrs, rawRPr: raw }))
else if (mode === 'reject') {
// reject: drop the old format's rawRPr too (modeled fields restored, unmodeled attrs abandoned)
}
}
})
tr.removeMark(r.from, r.to, state.schema.marks.rprChange)
continue
}
if (r.kind === 'moveFrom' || r.kind === 'moveTo') {
// moveFrom/moveTo: translate to del/ins logic using the same remove/keep semantics
const effectiveKind = r.kind === 'moveFrom' ? 'del' : 'ins'
const removeText = mode === 'accept' ? effectiveKind !== 'ins' : effectiveKind !== 'del'
if (removeText) {
const $from = state.doc.resolve(r.from)
const $to = state.doc.resolve(r.to)
if ($from.depth >= 1 && $from.sameParent($to) && state.doc.childCount > 1) {
tr.delete($from.before(), $to.after())
} else {
tr.delete(r.from, r.to)
}
} else if (mode === 'accept') {
tr.removeMark(r.from, r.to, state.schema.marks.ins)
} else {
tr.removeMark(r.from, r.to, state.schema.marks.del)
}
// Also clear the moveRevision attr from the node
try {
const $pos = state.doc.resolve(r.from + 1)
const nodePos = $pos.before($pos.depth)
if ($pos.parent.attrs?.moveRevision) {
tr.setNodeMarkup(nodePos, undefined, { ...$pos.parent.attrs, moveRevision: null })
}
} catch {
/* ignore if node is being deleted */
}
continue
}
if (
r.kind === 'rowIns' ||
r.kind === 'rowDel' ||
r.kind === 'cellIns' ||
r.kind === 'cellDel'
) {
const isRow = r.kind === 'rowIns' || r.kind === 'rowDel'
const revKind = r.kind === 'rowIns' || r.kind === 'cellIns' ? 'ins' : 'del'
const removeNode = mode === 'accept' ? revKind === 'del' : revKind === 'ins'
const node = state.doc.nodeAt(r.from)
if (!node) continue
if (removeNode && isRow) {
// accepting a deleted row / rejecting an inserted row = remove the whole row; if it is the only row, remove the whole table
const $pos = state.doc.resolve(r.from)
if ($pos.parent.childCount <= 1) tr.delete($pos.before(), $pos.after())
else tr.delete(r.from, r.to)
} else if (removeNode) {
// a cell cannot be removed outright (table grid self-repair would re-add an empty one): clear it in place and strip the marker
tr.setNodeMarkup(r.from, undefined, {
...node.attrs,
cellRevision: null,
rawTcPr: stripTrackMarker(
node.attrs.rawTcPr as string | null,
revKind === 'ins' ? 'w:cellIns' : 'w:cellDel',
'w:tcPr',
),
})
const empty = state.schema.nodes.docParagraph.createAndFill()
if (empty) tr.replaceWith(r.from + 1, r.to - 1, empty)
} else {
// keep the content: clear the revision marker and strip the record from the raw trPr/tcPr bytes (takes effect on save)
const attrs = isRow
? {
...node.attrs,
rowRevision: null,
rawTrPr: stripTrackMarker(
node.attrs.rawTrPr as string | null,
revKind === 'ins' ? 'w:ins' : 'w:del',
'w:trPr',
),
}
: {
...node.attrs,
cellRevision: null,
rawTcPr: stripTrackMarker(
node.attrs.rawTcPr as string | null,
revKind === 'ins' ? 'w:cellIns' : 'w:cellDel',
'w:tcPr',
),
}
tr.setNodeMarkup(r.from, undefined, attrs)
const markType = state.schema.marks[revKind]
if (markType) tr.removeMark(r.from + 1, r.to - 1, markType)
}
continue
}
const removeText = mode === 'accept' ? r.kind !== 'ins' : r.kind !== 'del'
if (removeText) {
// a revision covering a block's entire content removes the block itself
// (Word: rejecting an inserted paragraph deletes the paragraph, not just
// its text), unless it is the document's last remaining block
const $from = state.doc.resolve(r.from)
const $to = state.doc.resolve(r.to)
if (
$from.parent.isTextblock &&
$from.sameParent($to) &&
r.from === $from.start() &&
r.to === $to.end() &&
$from.depth === 1 &&
state.doc.childCount > 1
) {
tr.delete($from.before(), $to.after())
} else {
tr.delete(r.from, r.to)
}
} else if (mode === 'accept') {
tr.removeMark(r.from, r.to, state.schema.marks.ins)
} else {
tr.removeMark(r.from, r.to, state.schema.marks.del)
}
}
editor.view.dispatch(tr)
}
export function acceptAllRevisions(editor: Editor): void {
applyRevisions(editor, collectRevisions(editor.state.doc), 'accept')
}
export function rejectAllRevisions(editor: Editor): void {
applyRevisions(editor, collectRevisions(editor.state.doc), 'reject')
}
/** accept / reject only the revisions of one author (e.g. the AI assistant) */
export function applyRevisionsBy(editor: Editor, author: string, mode: 'accept' | 'reject'): void {
applyRevisions(
editor,
collectRevisions(editor.state.doc).filter((r) => r.author === author),
mode,
)
}
/** the revision containing the selection head, else the next one, else the first */
function currentRevision(editor: Editor): RevisionRange | null {
const ranges = collectRevisions(editor.state.doc)
if (ranges.length === 0) return null
const head = editor.state.selection.head
return (
ranges.find((r) => head >= r.from && head <= r.to) ??
ranges.find((r) => r.from > head) ??
ranges[0]
)
}
export function acceptCurrentRevision(editor: Editor): boolean {
const r = currentRevision(editor)
if (!r) return false
applyRevisions(editor, [r], 'accept')
return true
}
export function rejectCurrentRevision(editor: Editor): boolean {
const r = currentRevision(editor)
if (!r) return false
applyRevisions(editor, [r], 'reject')
return true
}
/** move the selection to the next / previous revision (wraps around) */
export function gotoRevision(editor: Editor, dir: 1 | -1): boolean {
const ranges = collectRevisions(editor.state.doc)
if (ranges.length === 0) return false
// compare range starts so adjacent revisions (shared boundary) still advance
const anchor = editor.state.selection.from
const target =
dir === 1
? (ranges.find((r) => r.from > anchor) ?? ranges[0])
: ([...ranges].reverse().find((r) => r.from < anchor) ?? ranges[ranges.length - 1])
const tr = editor.state.tr
// between: row/cell-level revision range endpoints are not text positions; snap to the nearest selectable text position
tr.setSelection(TextSelection.between(tr.doc.resolve(target.from), tr.doc.resolve(target.to)))
tr.scrollIntoView()
tr.setMeta(TRACK_IGNORE, true)
editor.view.dispatch(tr)
return true
}
export interface TrackChangesStorage {
enabled: boolean
author: string
}
declare module '@tiptap/core' {
interface Storage {
trackChanges: TrackChangesStorage
}
}
/**
* Records edits as tracked changes while `storage.enabled`:
* - inserted content gets the ins mark
* - deleted inline content is re-inserted struck through with the del mark
* (deleting your own tracked insertion really deletes it)
*
* Block-level deletions (paragraph merges) are not re-materialized — only the
* inline text of the change is tracked. Accept/reject and save fidelity work
* on run-level w:ins / w:del, matching the engine's revision model.
*/
export const TrackChangesExtension = Extension.create<object, TrackChangesStorage>({
name: 'trackChanges',
addStorage() {
return { enabled: false, author: t('editorDefaultAuthor') }
},
addKeyboardShortcuts() {
const storage = this.storage
/**
* Backspace over text already marked deleted is a no-op (the recorder puts it
* straight back), which would trap the caret. Word skips such text, so step
* over the struck run and delete the live character in front of it instead.
*/
const skipStruckRun = (): boolean => {
if (!storage.enabled) return false
const { state, view } = this.editor
const { selection, schema } = state
const delType = schema.marks.del
if (!delType || !selection.empty) return false
const $pos = selection.$from
if ($pos.parentOffset === 0) return false
const isStruck = (offset: number): boolean => {
const index = $pos.parent.childAfter(offset).index
const child = $pos.parent.maybeChild(index)
return !!child?.marks.some((mark) => mark.type === delType)
}
if (!isStruck($pos.parentOffset - 1)) return false
const blockStart = $pos.start()
let offset = $pos.parentOffset - 1
while (offset > 0 && isStruck(offset - 1)) offset -= 1
if (offset === 0) {
// nothing live left in this block: park the caret before the struck run
view.dispatch(state.tr.setSelection(TextSelection.create(state.doc, blockStart)))
return true
}
const runStart = blockStart + offset
this.editor.commands.command(({ tr, dispatch }) => {
tr.setSelection(TextSelection.create(tr.doc, runStart))
if (dispatch) dispatch(tr)
return true
})
return this.editor.commands.deleteRange({ from: runStart - 1, to: runStart })
}
return { Backspace: skipStruckRun }
},
addProseMirrorPlugins() {
const storage = this.storage
return [
new Plugin({
key: new PluginKey('trackChangesRecorder'),
appendTransaction: (transactions, oldState, newState) => {
if (!storage.enabled) return null
const tracked = transactions.filter(
(t) => t.docChanged && !t.getMeta(TRACK_IGNORE) && !t.getMeta('history$'),
)
if (tracked.length === 0) return null
const insType = newState.schema.marks.ins
const delType = newState.schema.marks.del
if (!insType || !delType) return null
const now = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')
const insMark = insType.create({ author: storage.author, date: now })
const delMark = delType.create({ author: storage.author, date: now })
// flatten steps across transactions with a shared mapping to the final doc
const steps = tracked.flatMap((t) =>
t.steps.map((step, i) => ({ step, docBefore: t.docs[i] })),
)
const mapping = new Mapping(steps.map(({ step }) => step.getMap()))
const tr = newState.tr
tr.setMeta(TRACK_IGNORE, true)
let changed = false
const recordedFormatRanges = new Set<string>()
// Paragraph-property commands are SetNodeMarkup/ReplaceAround operations.
// Comparing mapped textblocks catches alignment, spacing, indentation,
// styles, heading conversions, and list level/type changes without
// depending on the command's concrete ProseMirror step class.
const fullMapping = new Mapping(
tracked.flatMap((transaction) => transaction.steps.map((step) => step.getMap())),
)
const oldAnchors = new Map<number, { node: PmNode; pos: number }>()
oldState.doc.forEach((node, pos) => {
const index = node.attrs?.docxIndex
if (typeof index === 'number') oldAnchors.set(index, { node, pos })
})
const newAnchors = new Map<number, { node: PmNode; pos: number }>()
newState.doc.forEach((node, pos) => {
const index = node.attrs?.docxIndex
if (typeof index === 'number') newAnchors.set(index, { node, pos })
})
const matchedNewPositions = new Set<number>()
const movedNewPositions = new Set<number>()
const deletedBlocks: Array<{ node: PmNode; pos: number }> = []
oldState.doc.forEach((before, oldPos) => {
const index = before.attrs?.docxIndex
if (typeof index === 'number') {
const match = newAnchors.get(index)
if (match) {
matchedNewPositions.add(match.pos)
const mapped = fullMapping.map(oldPos, -1)
if (
mapped !== match.pos &&
(before.attrs?.blockRevision as { kind?: string } | null)?.kind !== 'ins'
) {
deletedBlocks.push({ node: before, pos: mapped })
movedNewPositions.add(match.pos)
}
} else if (
(before.attrs?.blockRevision as { kind?: string } | null)?.kind !== 'ins'
) {
deletedBlocks.push({ node: before, pos: fullMapping.map(oldPos, -1) })
}
return
}
const mapped = fullMapping.map(oldPos, -1)
const after = newState.doc.nodeAt(mapped)
if (
after &&
(after.type === before.type ||
(PARAGRAPH_NODE_TYPES.has(after.type.name) &&
PARAGRAPH_NODE_TYPES.has(before.type.name)))
)
matchedNewPositions.add(mapped)
else if ((before.attrs?.blockRevision as { kind?: string } | null)?.kind !== 'ins') {
deletedBlocks.push({ node: before, pos: mapped })
}
})
for (const { node, pos } of deletedBlocks.sort((a, b) => b.pos - a.pos)) {
tr.insert(
tr.mapping.map(pos, -1),
node.type.create(
{
...node.attrs,
blockRevision: { kind: 'del', author: storage.author, date: now },
},
node.content,
node.marks,
),
)
changed = true
}
newState.doc.forEach((node, pos) => {
const index = node.attrs?.docxIndex
const knownAnchor = typeof index === 'number' && oldAnchors.has(index)
if (
(!movedNewPositions.has(pos) && (knownAnchor || matchedNewPositions.has(pos))) ||
node.attrs?.blockRevision
)
return
tr.setNodeMarkup(tr.mapping.map(pos, 1), undefined, {
...node.attrs,
blockRevision: { kind: 'ins', author: storage.author, date: now },
})
changed = true
})
// Native table row commands preserve the table anchor. Record the
// single contiguous row span they insert/delete using trPr revisions.
for (const [index, oldTable] of oldAnchors) {
const nextTable = newAnchors.get(index)
if (oldTable.node.type.name !== 'docTable' || nextTable?.node.type.name !== 'docTable')
continue
const oldRows = Array.from({ length: oldTable.node.childCount }, (_, i) =>
oldTable.node.child(i),
)
const newRows = Array.from({ length: nextTable.node.childCount }, (_, i) =>
nextTable.node.child(i),
)
let prefix = 0
while (
prefix < oldRows.length &&
prefix < newRows.length &&
oldRows[prefix].eq(newRows[prefix])
)
prefix++
let suffix = 0
while (
suffix < oldRows.length - prefix &&
suffix < newRows.length - prefix &&
oldRows[oldRows.length - 1 - suffix].eq(newRows[newRows.length - 1 - suffix])
)
suffix++
const oldMiddle = oldRows.slice(prefix, oldRows.length - suffix)
const newMiddle = newRows.slice(prefix, newRows.length - suffix)
const rowPos = (rowIndex: number) => {
let pos = nextTable.pos + 1
for (let i = 0; i < rowIndex; i++) pos += newRows[i].nodeSize
return pos
}
if (oldMiddle.length === 0 && newMiddle.length > 0) {
for (let i = 0; i < newMiddle.length; i++) {
const pos = tr.mapping.map(rowPos(prefix + i), 1)
tr.setNodeMarkup(pos, undefined, {
...newMiddle[i].attrs,
rowRevision: { kind: 'ins', author: storage.author, date: now },
rawTrPr:
`<w:trPr><w:ins w:id="0" w:author="${xmlAttr(storage.author)}"` +
` w:date="${now}"/></w:trPr>`,
})
}
changed = true
} else if (oldMiddle.length > 0 && newMiddle.length === 0) {
const insertionPos = rowPos(prefix)
for (const row of [...oldMiddle].reverse()) {
tr.insert(
tr.mapping.map(insertionPos, -1),
row.type.create(
{
...row.attrs,
rowRevision: { kind: 'del', author: storage.author, date: now },
rawTrPr:
`<w:trPr><w:del w:id="0" w:author="${xmlAttr(storage.author)}"` +
` w:date="${now}"/></w:trPr>`,
},
row.content,
row.marks,
),
)
}
changed = true
}
}
oldState.doc.descendants((before, oldPos) => {
if (!PARAGRAPH_NODE_TYPES.has(before.type.name)) return
const newPos = fullMapping.map(oldPos, -1)
const after = newState.doc.nodeAt(newPos)
if (
!after ||
!PARAGRAPH_NODE_TYPES.has(after.type.name) ||
!paragraphPropertiesChanged(before, after) ||
after.attrs.pPrChange
) {
return
}
tr.setNodeMarkup(newPos, undefined, {
...after.attrs,
pPrChange: JSON.stringify({
author: storage.author,
date: now,
old: paragraphSnapshot(before),
}),
})
changed = true
})
steps.forEach(({ step, docBefore }, idx) => {
if (
(step instanceof AddMarkStep || step instanceof RemoveMarkStep) &&
TRACKED_FORMAT_MARKS.has(step.mark.type.name)
) {
const rprType = newState.schema.marks.rprChange
if (!rprType) return
const tail = mapping.slice(idx + 1)
docBefore.nodesBetween(step.from, step.to, (node, pos) => {
if (!node.isText) return
const sourceFrom = Math.max(pos, step.from)
const sourceTo = Math.min(pos + node.nodeSize, step.to)
const from = tr.mapping.map(tail.map(sourceFrom, 1), 1)
const to = tr.mapping.map(tail.map(sourceTo, -1), -1)
if (from >= to) return
const key = `${from}:${to}`
if (recordedFormatRanges.has(key)) return
recordedFormatRanges.add(key)
const existing = node.marks.find((m) => m.type.name === 'rprChange')
tr.addMark(
from,
to,
existing ??
rprType.create({
author: storage.author,
date: now,
old: formatSnapshot(node),
}),
)
changed = true
})
return
}
if (!(step instanceof ReplaceStep) && !(step instanceof ReplaceAroundStep)) return
if (step instanceof ReplaceAroundStep) {
const before = docBefore.nodeAt(step.from)
const tail = mapping.slice(idx + 1)
const after = newState.doc.nodeAt(tail.map(step.from, -1))
if (
before &&
after &&
PARAGRAPH_NODE_TYPES.has(before.type.name) &&
PARAGRAPH_NODE_TYPES.has(after.type.name) &&
before.content.eq(after.content) &&
paragraphPropertiesChanged(before, after)
) {
return
}
}
const from = step.from
const to = step.to
const slice = step.slice
const tail = mapping.slice(idx + 1)
let insertsWholeBlocks = slice.openStart === 0 && slice.content.childCount > 0
slice.content.forEach((child) => {
if (!child.isBlock) insertsWholeBlocks = false
})
// mark inserted content
if (slice.size > 0 && !insertsWholeBlocks) {
const a = tr.mapping.map(tail.map(from, 1), 1)
const b = tr.mapping.map(tail.map(from + slice.size, -1), -1)
if (a < b) {
tr.removeMark(a, b, delType)
tr.addMark(a, b, insMark)
changed = true
}
}
// re-materialize deleted inline content, struck through
if (to > from) {
const removed = docBefore.slice(from, to)
// only inline slices (deletions within one paragraph) are re-inserted
let inlineOnly = removed.content.childCount > 0
removed.content.forEach((child) => {
if (!child.isInline) inlineOnly = false
})
if (inlineOnly && removed.openStart === 0 && removed.openEnd === 0) {
const keep: PmNode[] = []
removed.content.forEach((child) => {
const ownIns = child.marks.some(
(m) => m.type === insType && m.attrs.author === storage.author,
)
if (ownIns) return // deleting your own insertion removes it outright
if (child.marks.some((m) => m.type === delType)) keep.push(child)
else keep.push(child.mark([...child.marks, delMark]))
})
if (keep.length > 0) {
const pos = tr.mapping.map(tail.map(from + slice.size, -1), -1)
const end = keep.reduce((at, child) => {
tr.insert(at, child)
return at + child.nodeSize
}, pos)
// Leave the caret in front of the struck text, not behind it.
// Behind it, the next Backspace targets content that is already
// marked deleted — which this plugin restores verbatim — so the
// user could only ever strike one character per position.
if (newState.selection.empty && tr.mapping.map(newState.selection.from) === end) {
tr.setSelection(TextSelection.create(tr.doc, pos))
}
changed = true
}
}
}
})
return changed ? tr : null
},
}),
]
},
})
@@ -0,0 +1,185 @@
import type { Node as PmNode } from '@tiptap/pm/model'
import type { Command, EditorState, Transaction } from '@tiptap/pm/state'
import { TableMap, isInTable, selectedRect } from '@tiptap/pm/tables'
export const MIN_TABLE_COLUMN_PX = 40
function finiteWidth(value: unknown, fallback: number): number {
const width = Number(value)
return Number.isFinite(width) && width > 0 ? width : fallback
}
/**
* Fit a table grid into the section content box. Requested columns keep their
* requested size where possible; unselected columns give up space first.
*/
export function fitColumnWidths(
current: number[],
requested: ReadonlyMap<number, number>,
maxWidth: number,
minimum = MIN_TABLE_COLUMN_PX,
): number[] {
if (current.length === 0) return []
const limit = Math.max(1, finiteWidth(maxWidth, 1))
const floor = Math.min(Math.max(1, minimum), limit / current.length)
const widths = current.map((width, index) =>
Math.max(floor, finiteWidth(requested.get(index), finiteWidth(width, floor))),
)
let excess = widths.reduce((sum, width) => sum + width, 0) - limit
const shrink = (indexes: number[]) => {
if (excess <= 0.01 || indexes.length === 0) return
const capacity = indexes.reduce((sum, index) => sum + Math.max(0, widths[index] - floor), 0)
if (capacity <= 0.01) return
const take = Math.min(excess, capacity)
for (const index of indexes) {
const available = Math.max(0, widths[index] - floor)
widths[index] -= take * (available / capacity)
}
excess -= take
}
const untouched = widths.map((_, index) => index).filter((index) => !requested.has(index))
const changed = widths.map((_, index) => index).filter((index) => requested.has(index))
shrink(untouched)
shrink(changed)
// Floating point drift must never write an oversized OOXML grid.
const total = widths.reduce((sum, width) => sum + width, 0)
if (total > limit)
widths[widths.length - 1] = Math.max(floor, widths[widths.length - 1] - (total - limit))
const rounded = widths.map((width) => Math.max(1, Math.round(width * 100) / 100))
const roundedTotal = rounded.reduce((sum, width) => sum + width, 0)
if (roundedTotal > limit) {
rounded[rounded.length - 1] = Math.max(
1,
Math.round((rounded[rounded.length - 1] - (roundedTotal - limit)) * 100) / 100,
)
}
return rounded
}
interface GridTarget {
table: PmNode
tableStart: number
map: TableMap
/** requested column range [left, right); empty for whole-grid constraints */
left: number
right: number
}
function targetFromSelection(state: EditorState): GridTarget | null {
if (!isInTable(state)) return null
const rect = selectedRect(state)
return {
table: rect.table,
tableStart: rect.tableStart,
map: rect.map,
left: rect.left,
right: rect.right,
}
}
/** Resize handles never set a selection; locate the table from the dragged cell's pos instead. */
function targetFromCellPos(state: EditorState, cellPos: number): GridTarget | null {
if (cellPos < 0 || cellPos > state.doc.content.size) return null
const $cell = state.doc.resolve(cellPos)
if ($cell.parent.type.spec.tableRole !== 'row' || !$cell.nodeAfter) return null
const table = $cell.node(-1)
if (table.type.spec.tableRole !== 'table') return null
return { table, tableStart: $cell.start(-1), map: TableMap.get(table), left: 0, right: 0 }
}
function tableGridWidths(
state: EditorState,
target: GridTarget,
maxWidth: number,
): number[] | null {
const { map, table, tableStart } = target
const columns = map.width
if (columns <= 0) return null
const pct = (table.attrs.colWidthsPct as number[] | null) ?? []
const fallback = maxWidth / columns
const widths: number[] = []
for (let col = 0; col < columns; col++) {
const cellPos = map.map[col]
const cell = state.doc.nodeAt(tableStart + cellPos)
const cellRect = map.findCell(cellPos)
const slot = col - cellRect.left
const declared = (cell?.attrs.colwidth as number[] | null)?.[slot]
widths.push(finiteWidth(declared, finiteWidth((pct[col] / 100) * maxWidth, fallback)))
}
return widths
}
function writeGridWidths(
state: EditorState,
tr: Transaction,
target: GridTarget,
widths: number[],
): Transaction {
const { map, table, tableStart } = target
const seen = new Set<number>()
for (let row = 0; row < map.height; row++) {
for (let col = 0; col < map.width; col++) {
const cellPos = map.map[row * map.width + col]
if (seen.has(cellPos)) continue
seen.add(cellPos)
const pos = tableStart + cellPos
const cell = state.doc.nodeAt(pos)
if (!cell) continue
const cellRect = map.findCell(cellPos)
tr = tr.setNodeMarkup(pos, undefined, {
...cell.attrs,
colwidth: widths.slice(cellRect.left, cellRect.right),
})
}
}
const total = widths.reduce((sum, width) => sum + width, 0)
tr = tr.setNodeMarkup(tableStart - 1, undefined, {
...table.attrs,
widthPx: total,
widthPct: null,
colWidthsPct: widths.map((width) => (width / total) * 100),
})
return tr
}
function resizeColumns(
state: EditorState,
dispatch: ((tr: Transaction) => void) | undefined,
desiredPx: number | null,
maxWidthPx: number,
target: GridTarget | null,
): boolean {
if (!target) return false
const current = tableGridWidths(state, target, maxWidthPx)
if (!current) return false
const requested = new Map<number, number>()
if (desiredPx !== null) {
for (let col = target.left; col < target.right; col++) requested.set(col, desiredPx)
}
const widths = fitColumnWidths(current, requested, maxWidthPx)
const changed = widths.some((width, index) => Math.abs(width - current[index]) > 0.01)
if (!changed && desiredPx !== null) return true
dispatch?.(writeGridWidths(state, state.tr, target, widths))
return true
}
/** Ribbon command: resize selected columns and redistribute the remaining grid. */
export function setSelectedColumnWidth(desiredPx: number, maxWidthPx: number): Command {
return (state, dispatch) =>
resizeColumns(state, dispatch, desiredPx, maxWidthPx, targetFromSelection(state))
}
/** Drag-resize cleanup: proportionally clamp an overflowing grid to the content box. */
export function constrainSelectedTableWidth(maxWidthPx: number): Command {
return (state, dispatch) =>
resizeColumns(state, dispatch, null, maxWidthPx, targetFromSelection(state))
}
/** Same clamp keyed off the drag handle's cell pos, for drags that start without a selection. */
export function constrainTableWidthAtCell(cellPos: number, maxWidthPx: number): Command {
return (state, dispatch) =>
resizeColumns(state, dispatch, null, maxWidthPx, targetFromCellPos(state, cellPos))
}
@@ -0,0 +1,36 @@
import type { Editor } from '@tiptap/core'
import type { DocDefaults, StyleInfo } from '@genoffice/docx-engine'
const TEXT_BLOCK_TYPES = new Set(['docParagraph', 'docHeading', 'docListItem'])
function styleSize(styleId: unknown, styles: Map<string, StyleInfo> | undefined): number | null {
if (typeof styleId !== 'string' || !styleId) return null
const size = styles?.get(styleId)?.display?.sizeHalfPoints
return typeof size === 'number' && size > 0 ? size : null
}
/** Resolve the font size Word displays at the caret without adding direct formatting. */
export function effectiveSizeHalfPoints(
editor: Editor,
styles?: Map<string, StyleInfo>,
docDefaults?: DocDefaults,
): number | null {
const textAttrs = editor.getAttributes('docTextStyle')
const directSize = Number(textAttrs.sizeHalfPoints)
if (Number.isFinite(directSize) && directSize > 0) return directSize
const characterStyleSize = styleSize(textAttrs.styleId, styles)
if (characterStyleSize !== null) return characterStyleSize
const { $from } = editor.state.selection
for (let depth = $from.depth; depth > 0; depth -= 1) {
const node = $from.node(depth)
if (!TEXT_BLOCK_TYPES.has(node.type.name)) continue
const paragraphStyleSize = styleSize(node.attrs.styleId, styles)
if (paragraphStyleSize !== null) return paragraphStyleSize
break
}
const defaultSize = docDefaults?.sizeHalfPoints
return typeof defaultSize === 'number' && defaultSize > 0 ? defaultSize : null
}
+13
View File
@@ -0,0 +1,13 @@
/// <reference types="vite/client" />
import type { DesktopApi } from '../shared/ipc'
import type { ProjectApi } from '@genoffice/project-store'
declare global {
interface Window {
desktop: DesktopApi
projectApi: ProjectApi
}
}
export {}
+730
View File
@@ -0,0 +1,730 @@
/**
* Document lifecycle: open/new (full state reset from a parsed docx), the
* save pipeline (PM doc → save plan → docx bytes → reparse), and PDF export.
* Extracted from App.tsx; the App component passes a FileActionContext built
* fresh per call (wrapped in useCallback with the original dependency lists)
* so state never goes stale.
*/
import type { Editor } from '@tiptap/core'
import {
applyPageNumType,
applySectionSettings,
applySectionStartType,
buildBlankDocx,
findChartWorkbookPath,
parseChartPartXml,
parseDocx,
patchChartPartXml,
patchChartWorkbookXlsxBase64,
readDocxPartBase64,
readPageColor,
readSections,
readSectionSettings,
saveDocx,
type CommentInfo,
type DocProtection,
type HeaderFooter,
type NoteInfo,
type SectionInfo,
type SectionSettings,
type SourceInfo,
type StyleUpsert,
type ThemeColors,
type ThemeFonts,
} from '@genoffice/docx-engine'
import type { Dispatch, SetStateAction } from 'react'
import type { OpenFileResult } from '../shared/ipc'
import {
hfVariantsFromParsed,
type DocState,
type HfVariantKey,
type HfVariantsState,
type HfView,
type PendingNumbering,
} from './doc-state'
import { docStyleCss } from './doc-style-css'
import type { CompareEntry } from './editor/compare'
import { blocksToPmDoc, pmDocToSavePlan, type PmNode } from './editor/convert'
import {
annotationsFromParsed,
buildInkImages,
type InkAnnotation,
type InkTool,
} from './editor/ink'
import { t, getLang } from './i18n/locale'
import { checkMissingFonts, collectDocFonts } from './font-check'
import { defaultEastAsiaFontFor } from './font-list'
import { hasPrintableHeaderFooter } from './pagination'
/** The App state the file actions need; built fresh per call. */
export interface FileActionContext {
editor: Editor | null
doc: DocState | null
dirtyRef: { current: boolean }
saveInFlightRef: { current: boolean }
saveIncompleteRef: { current: boolean }
pendingMixedExportRef: { current: boolean | string }
setStatus: (status: string) => void
setRecent: (paths: string[]) => void
setShowAi: (show: boolean) => void
setDoc: Dispatch<SetStateAction<DocState | null>>
setAiPanelKey: Dispatch<SetStateAction<number>>
setDocCss: (css: string) => void
setShowPagePreview: (show: boolean) => void
section: SectionSettings | null
sectionDirty: boolean
sections: SectionInfo[]
sectionsDirty: number[]
trailingStartType: SectionInfo['startType'] | null
setSection: (value: SectionSettings | null) => void
setSections: (value: SectionInfo[]) => void
setSectionDirty: (dirty: boolean) => void
setSectionsDirty: (value: number[]) => void
setTrailingStartType: (value: SectionInfo['startType'] | null) => void
pageColor: string | null
pageColorDirty: boolean
setPageColor: (value: string | null) => void
setPageColorDirty: (dirty: boolean) => void
header: HeaderFooter | null
headerDirty: boolean
footer: HeaderFooter | null
footerDirty: boolean
setHeader: (value: HeaderFooter | null) => void
setHeaderDirty: (dirty: boolean) => void
setFooter: (value: HeaderFooter | null) => void
setFooterDirty: (dirty: boolean) => void
hfVariants: HfVariantsState
hfVariantsDirty: HfVariantKey[]
setHfVariants: (value: HfVariantsState) => void
setHfVariantsDirty: (value: HfVariantKey[]) => void
sectionHfEdits: Record<string, HeaderFooter>
setSectionHfEdits: (value: Record<string, HeaderFooter>) => void
titlePg: boolean
titlePgDirty: boolean
evenOddHf: boolean
evenOddHfDirty: boolean
setTitlePg: (value: boolean) => void
setTitlePgDirty: (dirty: boolean) => void
setEvenOddHf: (value: boolean) => void
setEvenOddHfDirty: (dirty: boolean) => void
setHfView: (view: HfView) => void
pgNumEdit: { fmt?: string; start?: number } | null
pgNumDirtySections: number[]
setPgNumEdit: (value: { fmt?: string; start?: number } | null) => void
setPgNumDirtySections: (value: number[]) => void
pendingNumbering: PendingNumbering
numberingDirty: boolean
setPendingNumbering: (value: PendingNumbering) => void
styleUpserts: Record<string, StyleUpsert>
setStyleUpserts: (value: Record<string, StyleUpsert>) => void
comments: CommentInfo[]
commentsDirty: boolean
setComments: (value: CommentInfo[]) => void
setCommentsDirty: (dirty: boolean) => void
setShowComments: (show: boolean) => void
setCommentComposing: (composing: boolean) => void
watermark: string | null
watermarkDirty: boolean
setWatermark: (value: string | null) => void
setWatermarkDirty: (dirty: boolean) => void
inkAnnotations: InkAnnotation[]
inksDirty: boolean
setInkAnnotations: (value: InkAnnotation[]) => void
setInksDirty: (dirty: boolean) => void
setInkTool: (tool: InkTool) => void
footnotes: NoteInfo[]
endnotes: NoteInfo[]
notesDirty: boolean
setFootnotes: (value: NoteInfo[]) => void
setEndnotes: (value: NoteInfo[]) => void
setNotesDirty: (dirty: boolean) => void
sources: SourceInfo[]
sourcesDirty: boolean
setSources: (value: SourceInfo[]) => void
setSourcesDirty: (dirty: boolean) => void
themeFonts: ThemeFonts | null
themeFontsDirty: boolean
themeColors: ThemeColors | null
themeColorsDirty: boolean
setThemeFonts: (value: ThemeFonts | null) => void
setThemeFontsDirty: (dirty: boolean) => void
setThemeColors: (value: ThemeColors | null) => void
setThemeColorsDirty: (dirty: boolean) => void
setTrackChanges: (on: boolean) => void
protection: DocProtection | null
protectionDirty: boolean
setProtection: (value: DocProtection | null) => void
setProtectionDirty: (dirty: boolean) => void
setCompareResult: (value: { otherName: string; entries: CompareEntry[] } | null) => void
}
export async function loadFile(
ctx: FileActionContext,
result: OpenFileResult | null,
): Promise<void> {
if (!result || !ctx.editor) return
try {
const parsed = await parseDocx(new Uint8Array(result.data))
ctx.editor.storage.listNumbering.defs = parsed.numbering
ctx.editor.commands.setContent(blocksToPmDoc(parsed.blocks) as never)
ctx.setDoc({ parsed, filePath: result.path, fileName: result.name, hash: result.hash })
ctx.setAiPanelKey((k) => k + 1)
ctx.setDocCss(docStyleCss(parsed))
ctx.setSection(readSectionSettings(parsed))
ctx.setSections(readSections(parsed))
ctx.setSectionDirty(false)
ctx.setPageColor(readPageColor(parsed))
ctx.setPageColorDirty(false)
ctx.setHeader(
parsed.headerText || parsed.headerParas?.length
? { text: parsed.headerText ?? '', paras: parsed.headerParas ?? undefined }
: null,
)
ctx.setHeaderDirty(false)
ctx.setFooter(
parsed.footerText || parsed.footerHasPageNumber || parsed.footerParas?.length
? {
text: parsed.footerText ?? '',
pageNumber: parsed.footerHasPageNumber,
paras: parsed.footerParas ?? undefined,
}
: null,
)
ctx.setFooterDirty(false)
ctx.setHfVariants(hfVariantsFromParsed(parsed))
ctx.setHfVariantsDirty([])
ctx.setTitlePg(parsed.titlePg ?? false)
ctx.setTitlePgDirty(false)
ctx.setEvenOddHf(parsed.evenAndOddHeaders ?? false)
ctx.setEvenOddHfDirty(false)
ctx.setHfView('default')
ctx.setShowComments(false)
ctx.setComments(parsed.comments)
ctx.setCommentsDirty(false)
ctx.setWatermark(parsed.watermarkText ?? null)
ctx.setWatermarkDirty(false)
ctx.setInkAnnotations(annotationsFromParsed(parsed.inks))
ctx.setInksDirty(false)
ctx.setInkTool('select')
ctx.setFootnotes(parsed.footnotes)
ctx.setEndnotes(parsed.endnotes)
ctx.setNotesDirty(false)
ctx.setSources(parsed.sources)
ctx.setSourcesDirty(false)
ctx.setThemeFonts(parsed.themeFonts ?? null)
ctx.setThemeFontsDirty(false)
ctx.setThemeColors(parsed.themeColors ?? null)
ctx.setThemeColorsDirty(false)
ctx.setCommentComposing(false)
ctx.setTrackChanges(false)
ctx.setProtection(parsed.protection)
ctx.setProtectionDirty(false)
ctx.setCompareResult(null)
ctx.dirtyRef.current = false
const missing = checkMissingFonts(collectDocFonts(parsed))
const verticalText = readSections(parsed).some((s) => s.settings.textDirection)
if (verticalText) {
// visible degradation: vertical writing is not rendered yet, never silently
ctx.setStatus(t('appVerticalTextNotice'))
} else if (missing.length > 0) {
const names = missing
.slice(0, 3)
.map((m) => (m.substitute ? `${m.name} → ${m.substitute}` : m.name))
.join(', ')
ctx.setStatus(t('appFontsMissing', { names: missing.length > 3 ? `${names}…` : names }))
} else {
ctx.setStatus(t('appOpenedFile', { name: result.name }))
}
void window.desktop.getRecentFiles().then(ctx.setRecent)
} catch (err) {
ctx.setStatus(t('appOpenFailed', { error: String(err) }))
}
}
/** new document from the built-in blank template (AI can then generate into it) */
export async function newFile(ctx: FileActionContext): Promise<boolean | undefined> {
if (!ctx.editor) return
try {
const bytes = await buildBlankDocx({ eastAsiaFont: defaultEastAsiaFontFor(getLang()) })
const parsed = await parseDocx(bytes)
ctx.editor.storage.listNumbering.defs = parsed.numbering
ctx.editor.commands.setContent(blocksToPmDoc(parsed.blocks) as never)
ctx.setDoc({ parsed, filePath: null, fileName: t('appUntitledDocx'), hash: '', isBlank: true })
ctx.setAiPanelKey((k) => k + 1)
ctx.setDocCss(docStyleCss(parsed))
ctx.setSection(readSectionSettings(parsed))
ctx.setSections(readSections(parsed))
ctx.setSectionDirty(false)
ctx.setPageColor(readPageColor(parsed))
ctx.setPageColorDirty(false)
ctx.setHeader(null)
ctx.setHeaderDirty(false)
ctx.setFooter(null)
ctx.setFooterDirty(false)
ctx.setShowComments(false)
ctx.setComments([])
ctx.setCommentsDirty(false)
ctx.setWatermark(null)
ctx.setWatermarkDirty(false)
ctx.setInkAnnotations([])
ctx.setInksDirty(false)
ctx.setInkTool('select')
ctx.setFootnotes(parsed.footnotes)
ctx.setEndnotes(parsed.endnotes)
ctx.setNotesDirty(false)
ctx.setSources([])
ctx.setSourcesDirty(false)
ctx.setThemeFonts(parsed.themeFonts ?? null)
ctx.setThemeFontsDirty(false)
ctx.setThemeColors(parsed.themeColors ?? null)
ctx.setThemeColorsDirty(false)
ctx.setCommentComposing(false)
ctx.setTrackChanges(false)
ctx.setProtection(null)
ctx.setProtectionDirty(false)
ctx.setCompareResult(null)
ctx.dirtyRef.current = false
ctx.setShowAi(true)
ctx.setStatus(t('appNewDocCreated'))
return true
} catch (err) {
ctx.setStatus(t('appNewFailed', { error: String(err) }))
return false
}
}
/** Plain text of a PM node's inline content. */
function pmNodeText(node: PmNode): string {
if (node.text) return node.text
return (node.content ?? []).map(pmNodeText).join('')
}
/** Sanitize a heading into a safe filename base: strip illegal path chars, collapse whitespace, cap length; null if invalid. (Mirrors slides' draft naming.) */
function sanitizeFileBaseName(raw: string): string | null {
const cleaned = raw
// eslint-disable-next-line no-control-regex -- stripping control chars is the point here
.replace(/[\\/:*?"<>|\u0000-\u001f]/g, ' ')
.replace(/\s+/g, ' ')
.trim()
// Strip leading/trailing dots (Windows disallows a trailing dot; a hidden-file prefix is meaningless here)
.replace(/^\.+|\.+$/g, '')
.trim()
if (!cleaned) return null
return cleaned.length > 40 ? cleaned.slice(0, 40).trim() : cleaned
}
/**
* Docs' analog of slides' deckName: a still-untitled document takes its file name
* from the first heading, so the first silent save (and with it the shell tab
* title) picks up a content-derived name instead of "Untitled.docx".
*/
function deriveAutoFileName(editor: Editor): string | null {
const body = (editor.getJSON() as PmNode).content ?? []
for (const node of body) {
if (node.type !== 'docHeading') continue
const base = sanitizeFileBaseName(pmNodeText(node))
if (base) return `${base}.docx`
}
return null
}
/**
* Serialize the current editor/document state to .docx bytes — the shared
* serialization half of save(); no dialogs, no state changes. Also used for
* crash-recovery copies.
*/
export async function buildDocBytes(ctx: FileActionContext): Promise<Uint8Array | null> {
const { doc, editor } = ctx
if (!doc || !editor) return null
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, doc.parsed.blocks)
// chart data edits patch the chart's own zip part, not the body XML
const partXml: Record<string, string> = {}
const partBinary: Record<string, string> = {}
for (const { partPath, patch } of plan.chartPatches) {
const originalPart = doc.parsed.extras.chartParts[partPath]
if (originalPart) {
const patchedXml = patchChartPartXml(originalPart, patch)
partXml[partPath] = patchedXml
// Also update the embedded workbook so Word's "Edit Data" shows correct data
const wbPath = await findChartWorkbookPath(doc.parsed.internal.originalBytes, partPath)
if (wbPath) {
const existingBase64 = await readDocxPartBase64(doc.parsed.internal.originalBytes, wbPath)
if (existingBase64) {
const display = parseChartPartXml(patchedXml, partPath)
if (display) {
const namedSeries = display.series.map((s, i) => ({
name: s.name ?? `Series${i + 1}`,
values: s.values as (number | null)[],
}))
const updated = await patchChartWorkbookXlsxBase64(
existingBase64,
display.categories,
namedSeries,
)
if (updated) partBinary[wbPath] = updated
}
}
}
}
}
// Ink must be passed whenever any annotation exists (not only when
// dirty): a regenerated anchor paragraph loses its ink run, and the
// engine re-injects the full layer from this list.
const inks =
ctx.inksDirty || ctx.inkAnnotations.length > 0
? buildInkImages(ctx.inkAnnotations, plan.saveBlockIndexByDocx)
: undefined
// page-setup edits for non-final sections: rewrite the sectPr inside their section-break paragraphs (the final section uses options.section)
let saveBlocks = plan.saveBlocks
const dirtySectionIdxs = [...new Set([...ctx.sectionsDirty, ...ctx.pgNumDirtySections])]
if (dirtySectionIdxs.length > 0) {
const rewrites = new Map<number, string>()
for (const si of dirtySectionIdxs) {
const sec = ctx.sections[si]
if (!sec || si === ctx.sections.length - 1) continue
const blk = doc.parsed.blocks.find((b) => b.docxIndex === sec.lastBlockIndex)
if (!blk?.originalXml || !sec.sectPrXml) continue
let sectPr = applySectionSettings(sec.sectPrXml, sec.settings)
sectPr = applySectionStartType(sectPr, sec.startType)
// touch w:pgNumType only when the page-number format was edited (avoids dropping unmodeled attrs like chapStyle)
if (ctx.pgNumDirtySections.includes(si)) {
sectPr = applyPageNumType(sectPr, sec.pageNumberFmt, sec.pageNumberStart)
}
rewrites.set(sec.lastBlockIndex, blk.originalXml.replace(sec.sectPrXml, sectPr))
}
saveBlocks = saveBlocks.map((fb) =>
fb.kind === 'original' && rewrites.has(fb.docxIndex)
? { kind: 'xml' as const, xml: rewrites.get(fb.docxIndex)!, docxIndex: fb.docxIndex }
: fb,
)
}
// header/footer edits for non-final sections: the engine writes parts/references per section
const sectionHf = Object.entries(ctx.sectionHfEdits).map(([key, hf]) => {
const [lastBlockIndex, kind] = key.split(':')
return { lastBlockIndex: Number(lastBlockIndex), kind: kind as 'header' | 'footer', hf }
})
const bytes = await saveDocx(doc.parsed, saveBlocks, {
section: ctx.sectionDirty && ctx.section ? ctx.section : undefined,
sectionStartType: ctx.trailingStartType ?? undefined,
pgNumType: ctx.pgNumEdit ?? undefined,
sectionHf: sectionHf.length > 0 ? sectionHf : undefined,
numbering: ctx.numberingDirty ? ctx.pendingNumbering : undefined,
styleUpserts:
Object.keys(ctx.styleUpserts).length > 0 ? Object.values(ctx.styleUpserts) : undefined,
pageColor: ctx.pageColorDirty ? ctx.pageColor : undefined,
header: ctx.headerDirty && ctx.header ? ctx.header : undefined,
footer: ctx.footerDirty && ctx.footer ? ctx.footer : undefined,
headerFirst:
ctx.hfVariantsDirty.includes('headerFirst') && ctx.hfVariants.headerFirst
? ctx.hfVariants.headerFirst
: undefined,
footerFirst:
ctx.hfVariantsDirty.includes('footerFirst') && ctx.hfVariants.footerFirst
? ctx.hfVariants.footerFirst
: undefined,
headerEven:
ctx.hfVariantsDirty.includes('headerEven') && ctx.hfVariants.headerEven
? ctx.hfVariants.headerEven
: undefined,
footerEven:
ctx.hfVariantsDirty.includes('footerEven') && ctx.hfVariants.footerEven
? ctx.hfVariants.footerEven
: undefined,
titlePg: ctx.titlePgDirty ? ctx.titlePg : undefined,
evenAndOddHeaders: ctx.evenOddHfDirty ? ctx.evenOddHf : undefined,
partXml: Object.keys(partXml).length > 0 ? partXml : undefined,
partBinary: Object.keys(partBinary).length > 0 ? partBinary : undefined,
comments: ctx.commentsDirty ? ctx.comments : undefined,
protection: ctx.protectionDirty ? ctx.protection : undefined,
inks,
watermark: ctx.watermarkDirty ? ctx.watermark : undefined,
footnotes: ctx.notesDirty ? ctx.footnotes : undefined,
endnotes: ctx.notesDirty ? ctx.endnotes : undefined,
sources: ctx.sourcesDirty ? ctx.sources : undefined,
themeFonts: ctx.themeFontsDirty && ctx.themeFonts ? ctx.themeFonts : undefined,
themeColors: ctx.themeColorsDirty && ctx.themeColors ? ctx.themeColors : undefined,
})
return bytes
}
/**
* Crash-recovery copy: serialize the dirty document and hand the
* bytes to the main process, which stores them under userData. Best-effort —
* a failure only means this tick's copy is skipped.
*/
export async function writeRecoveryCopy(ctx: FileActionContext): Promise<void> {
const { doc } = ctx
if (!doc?.filePath || !ctx.dirtyRef.current || ctx.saveInFlightRef.current) return
try {
const bytes = await buildDocBytes(ctx)
if (!bytes) return
const buffer = bytes.buffer.slice(
bytes.byteOffset,
bytes.byteOffset + bytes.byteLength,
) as ArrayBuffer
await window.desktop.writeRecoveryCopy(doc.filePath, buffer)
} catch {
/* best-effort */
}
}
export async function save(
ctx: FileActionContext,
saveAs: boolean,
auto = false,
): Promise<boolean> {
const { doc, editor } = ctx
if (!doc || !editor) return false
if (ctx.saveInFlightRef.current) return false
ctx.saveInFlightRef.current = true
ctx.saveIncompleteRef.current = false
try {
// flush pending in-place table cell / textbox edits into the PM doc first
window.dispatchEvent(new Event('ai-docs-commit-tables'))
// identity snapshot: detects edits that arrive while the save is in flight
const docSnapshot = editor.state.doc
const selectionPos = editor.state.selection.from
const bytes = await buildDocBytes(ctx)
if (!bytes) return false
const buffer = bytes.buffer.slice(
bytes.byteOffset,
bytes.byteOffset + bytes.byteLength,
) as ArrayBuffer
let savedPath = doc.filePath
if (saveAs || !doc.filePath) {
// A never-saved document still called "Untitled" gets a name derived from its first heading
const autoName =
!doc.filePath && doc.fileName === t('appUntitledDocx') ? deriveAutoFileName(editor) : null
// Save As keeps the dialog; a new document's first save lands silently in the default folder
const result = saveAs
? await window.desktop.saveDocxAs(autoName ?? doc.fileName, buffer)
: await window.desktop.saveDocxNew(autoName ?? doc.fileName, buffer)
if (!result.ok) {
if (result.error) ctx.setStatus(t('appSaveFailed', { error: result.error }))
return false
}
savedPath = result.path!
} else {
const result = await window.desktop.saveDocx(doc.filePath, buffer)
if (!result.ok) {
ctx.setStatus(t('appSaveFailed', { error: result.error ?? '' }))
return false
}
}
if (editor.state.doc !== docSnapshot) {
// The user kept editing while the save was in flight. Replacing the
// editor content with the reparsed (pre-edit) snapshot would silently
// drop those keystrokes, so keep the live editor + parsed state as-is
// and leave the document dirty; the next save persists the newer edits.
ctx.saveIncompleteRef.current = true
ctx.setDoc((prev) =>
prev
? {
...prev,
filePath: savedPath,
fileName: savedPath?.split(/[\\/]/).pop() ?? prev.fileName,
}
: prev,
)
ctx.setStatus(
auto ? t('appAutoSavedAt', { time: new Date().toLocaleTimeString() }) : t('appSaved'),
)
return true
}
// Reload from saved bytes so docxIndex anchors point at the new file.
const reparsed = await parseDocx(bytes)
editor.storage.listNumbering.defs = reparsed.numbering
editor.commands.setContent(blocksToPmDoc(reparsed.blocks) as never)
ctx.setDocCss(docStyleCss(reparsed))
if (auto) {
// silent save: keep the caret where the user was typing
editor.commands.setTextSelection(Math.min(selectionPos, editor.state.doc.content.size))
}
ctx.setDoc((prev) =>
prev
? {
...prev,
parsed: reparsed,
filePath: savedPath,
fileName: savedPath?.split(/[\\/]/).pop() ?? prev.fileName,
}
: prev,
)
ctx.setSection(readSectionSettings(reparsed))
ctx.setSections(readSections(reparsed))
ctx.setSectionDirty(false)
ctx.setSectionsDirty([])
ctx.setTrailingStartType(null)
ctx.setPageColor(readPageColor(reparsed))
ctx.setPageColorDirty(false)
ctx.setHeader(
reparsed.headerText || reparsed.headerParas?.length
? { text: reparsed.headerText ?? '', paras: reparsed.headerParas ?? undefined }
: null,
)
ctx.setHeaderDirty(false)
ctx.setFooter(
reparsed.footerText || reparsed.footerHasPageNumber || reparsed.footerParas?.length
? {
text: reparsed.footerText ?? '',
pageNumber: reparsed.footerHasPageNumber,
paras: reparsed.footerParas ?? undefined,
}
: null,
)
ctx.setFooterDirty(false)
ctx.setHfVariants(hfVariantsFromParsed(reparsed))
ctx.setSectionHfEdits({})
ctx.setPgNumEdit(null)
ctx.setPgNumDirtySections([])
ctx.setPendingNumbering({ newDefs: [], restartNums: [] })
ctx.setStyleUpserts({})
ctx.setHfVariantsDirty([])
ctx.setTitlePg(reparsed.titlePg ?? false)
ctx.setTitlePgDirty(false)
ctx.setEvenOddHf(reparsed.evenAndOddHeaders ?? false)
ctx.setEvenOddHfDirty(false)
ctx.setComments(reparsed.comments)
ctx.setCommentsDirty(false)
ctx.setWatermark(reparsed.watermarkText ?? null)
ctx.setWatermarkDirty(false)
ctx.setInkAnnotations(annotationsFromParsed(reparsed.inks))
ctx.setInksDirty(false)
ctx.setFootnotes(reparsed.footnotes)
ctx.setEndnotes(reparsed.endnotes)
ctx.setNotesDirty(false)
ctx.setSources(reparsed.sources)
ctx.setSourcesDirty(false)
ctx.setThemeFonts(reparsed.themeFonts ?? null)
ctx.setThemeFontsDirty(false)
ctx.setThemeColors(reparsed.themeColors ?? null)
ctx.setThemeColorsDirty(false)
ctx.setProtection(reparsed.protection)
ctx.setProtectionDirty(false)
ctx.dirtyRef.current = false
ctx.setStatus(
auto ? t('appAutoSavedAt', { time: new Date().toLocaleTimeString() }) : t('appSaved'),
)
return true
} catch (err) {
ctx.setStatus(t('appSaveFailed', { error: String(err) }))
return false
} finally {
ctx.saveInFlightRef.current = false
}
}
export async function exportPdf(ctx: FileActionContext, outPath?: string): Promise<void> {
const { doc } = ctx
if (!doc) return
ctx.setStatus(t('appExportingPdf'))
// with the pagination preview open: group by actual pv-page size. Mixed paper →
// print group by group (other pages hidden for printing), then merge in page order
// with pdf-lib; each page keeps its section's paper size
const pvPages = [...document.querySelectorAll('.pv-page')] as HTMLElement[]
if (pvPages.length > 0) {
const pxToTwips = (px: number) => Math.round((px / 96) * 1440)
const groups: Array<{ w: number; h: number; from: number; to: number }> = []
pvPages.forEach((page, i) => {
const w = pxToTwips(parseFloat(page.style.width))
const h = pxToTwips(parseFloat(page.style.height))
const last = groups[groups.length - 1]
if (last && last.w === w && last.h === h) last.to = i
else groups.push({ w, h, from: i, to: i })
})
if (groups.length > 1) {
const parts: string[] = []
try {
for (const g of groups) {
pvPages.forEach((page, i) =>
page.classList.toggle('pv-print-skip', i < g.from || i > g.to),
)
const part = await window.desktop.printPdfBuffer(g.w, g.h)
if (!part.ok || !part.base64) {
ctx.setStatus(
t('appExportPdfFailed', { error: part.error ?? t('appPrintGroupFailed') }),
)
return
}
parts.push(part.base64)
}
} finally {
pvPages.forEach((page) => page.classList.remove('pv-print-skip'))
}
const result = await window.desktop.saveMergedPdf(doc.fileName, parts, outPath)
ctx.setStatus(
result.ok
? t('appExportedPdfMixed', { path: result.path ?? '', n: groups.length })
: result.error
? t('appExportPdfFailed', { error: result.error })
: t('appExportPdfCanceled'),
)
return
}
// preview open but uniform paper: single export at the preview size
const g = groups[0]
if (g) {
const result = await window.desktop.exportPdf(doc.fileName, g.w, g.h, outPath)
ctx.setStatus(
result.ok
? t('appExportedPdf', { path: result.path ?? '' })
: result.error
? t('appExportPdfFailed', { error: result.error })
: t('appExportPdfCanceled'),
)
return
}
}
// preview closed: mixed paper auto-opens the preview and uses the merge path; uniform paper exports directly
const sizeKey = (w: number, h: number) => `${w}x${h}`
const counts = new Map<string, { w: number; h: number; n: number }>()
const list =
ctx.sections.length > 0
? ctx.sections.map((sec) => sec.settings)
: ctx.section
? [ctx.section]
: []
for (const st of list) {
const key = sizeKey(st.pageWidth, st.pageHeight)
const cur = counts.get(key) ?? { w: st.pageWidth, h: st.pageHeight, n: 0 }
cur.n += 1
counts.set(key, cur)
}
// headers/footers exist once on the edit canvas (not once per page), so direct
// print would show them on the last page only — force the preview-merge path too
const mixedPaper = counts.size > 1
if (
mixedPaper ||
hasPrintableHeaderFooter({
edited: [
ctx.header,
ctx.footer,
...(ctx.titlePg ? [ctx.hfVariants.headerFirst, ctx.hfVariants.footerFirst] : []),
...(ctx.evenOddHf ? [ctx.hfVariants.headerEven, ctx.hfVariants.footerEven] : []),
...Object.values(ctx.sectionHfEdits),
],
sections: ctx.sections,
hfParts: doc.parsed.hfParts ?? undefined,
evenOddHf: ctx.evenOddHf,
})
) {
ctx.setShowPagePreview(true)
ctx.pendingMixedExportRef.current = outPath ?? true
if (mixedPaper) ctx.setStatus(t('appMixedExportOpening'))
return
}
const major = [...counts.values()][0]
const result = await window.desktop.exportPdf(
doc.fileName,
major?.w ?? ctx.section?.pageWidth ?? 12240,
major?.h ?? ctx.section?.pageHeight ?? 15840,
outPath,
)
ctx.setStatus(
result.ok
? t('appExportedPdf', { path: result.path ?? '' })
: result.error
? t('appExportPdfFailed', { error: result.error })
: t('appExportPdfCanceled'),
)
}
+86
View File
@@ -0,0 +1,86 @@
import type { ParsedDoc } from '@genoffice/docx-engine'
import { cssFontFamily } from './line-metrics'
/** bundled web fonts (fonts.css) — always "available" but they are the
* one-size-fits-all fallback, so landing on them still counts as a miss */
const BUNDLED = new Set([
'Noto Sans CJK SC',
'Noto Serif CJK SC',
'Carlito',
'Caladea',
'Liberation Serif',
'Liberation Sans',
'Liberation Mono',
])
const GENERIC = new Set(['serif', 'sans-serif', 'monospace'])
/** every distinct font family the document declares */
export function collectDocFonts(parsed: ParsedDoc): string[] {
const names = new Set<string>()
const add = (font?: string) => {
if (font) names.add(font)
}
for (const b of parsed.blocks) {
for (const r of b.runs ?? []) add(r.font)
for (const tb of b.textboxes ?? []) {
for (const p of tb.paras) for (const r of p.runs) add(r.font)
}
}
add(parsed.docDefaults?.asciiFont)
add(parsed.docDefaults?.eastAsiaFont)
for (const s of parsed.styles.values()) add(s.display?.font)
return [...names]
}
// document.fonts.check is useless here: Chromium answers true for any family
// (system-fallback rendering counts). Detect availability by measuring — an
// unresolvable family inherits the exact metrics of the generic fallback.
const SAMPLE = '永体宋黑Wmg10'
function ctx2d(): CanvasRenderingContext2D | null {
try {
return document.createElement('canvas').getContext('2d')
} catch {
return null
}
}
function fontAvailableIn(cx: CanvasRenderingContext2D, family: string): boolean {
const q = `"${family.replace(/"/g, '')}"`
const width = (stack: string): number => {
cx.font = `16px ${stack}`
return cx.measureText(SAMPLE).width
}
return (
width(`${q}, monospace`) !== width('monospace') ||
width(`${q}, sans-serif`) !== width('sans-serif')
)
}
export interface FontSubstitution {
name: string
/** first available family in the fallback chain, null = only bundled fallback left */
substitute: string | null
}
/**
* Declared fonts that don't resolve on this system, with the family that
* actually renders instead (issue #75: substitution used to be silent).
*/
export function checkMissingFonts(names: string[]): FontSubstitution[] {
if (typeof document === 'undefined') return []
const cx = ctx2d()
if (!cx) return []
const out: FontSubstitution[] = []
for (const name of names) {
if (fontAvailableIn(cx, name)) continue
const chain = cssFontFamily(name)
.split(',')
.map((s) => s.trim().replace(/^'|'$/g, ''))
.filter((c) => c !== name && !GENERIC.has(c))
const substitute = chain.find((c) => !BUNDLED.has(c) && fontAvailableIn(cx, c)) ?? null
out.push({ name, substitute })
}
return out
}
+75
View File
@@ -0,0 +1,75 @@
import type { Lang } from '@genoffice/i18n'
/**
* Font dropdown candidates grouped by script, ordered per UI language so the
* fonts a user is most likely to want appear at the top (e.g. Western fonts
* for the US market, Japanese fonts for the Japanese market).
*/
const LATIN = [
'Calibri',
'Arial',
'Times New Roman',
'Georgia',
'Verdana',
'Tahoma',
'Cambria',
'Garamond',
'Trebuchet MS',
'Segoe UI',
'Courier New',
'Impact',
]
// GB/T 9704 official-document fonts included so government documents can be
// authored from scratch (values are free-typed either way; the combobox accepts any name)
const SIMPLIFIED_CHINESE = [
'等线',
'宋体',
'黑体',
'微软雅黑',
'楷体',
'仿宋',
'仿宋_GB2312',
'楷体_GB2312',
'方正小标宋简体',
]
const JAPANESE = ['Yu Gothic', 'Yu Mincho', 'Meiryo', 'MS Gothic', 'MS Mincho']
const KOREAN = ['Malgun Gothic', 'Batang', 'Gulim', 'Dotum']
const TRADITIONAL_CHINESE = ['Microsoft JhengHei', 'PMingLiU']
export function fontFamiliesFor(lang: Lang): readonly string[] {
switch (lang) {
case 'zh':
return [...SIMPLIFIED_CHINESE, ...LATIN, ...JAPANESE, ...KOREAN, ...TRADITIONAL_CHINESE]
case 'zh-TW':
return [...TRADITIONAL_CHINESE, ...LATIN, ...SIMPLIFIED_CHINESE, ...JAPANESE, ...KOREAN]
case 'ja':
return [...JAPANESE, ...LATIN, ...SIMPLIFIED_CHINESE, ...KOREAN, ...TRADITIONAL_CHINESE]
case 'ko':
return [...KOREAN, ...LATIN, ...JAPANESE, ...SIMPLIFIED_CHINESE, ...TRADITIONAL_CHINESE]
default:
return [...LATIN, ...JAPANESE, ...SIMPLIFIED_CHINESE, ...KOREAN, ...TRADITIONAL_CHINESE]
}
}
/**
* docDefaults w:eastAsia font for new blank documents, matching what Word
* ships per market (zh → SimSun, ja → Yu Mincho, ko → Malgun Gothic,
* zh-TW → PMingLiU). English and every other language return undefined —
* like en-US Word, whose theme leaves the East Asian slot empty and lets
* per-script substitution kick in only when CJK text actually appears.
* Latin default stays Calibri for every language.
*/
export function defaultEastAsiaFontFor(lang: Lang): string | undefined {
switch (lang) {
case 'zh':
return '宋体'
case 'ja':
return 'Yu Mincho'
case 'ko':
return 'Malgun Gothic'
case 'zh-TW':
return 'PMingLiU'
default:
return undefined
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,110 @@
Digitized data copyright (c) 2010 Google Corporation
with Reserved Font Arimo, Tinos and Cousine.
Copyright (c) 2012 Red Hat, Inc.
with Reserved Font Name Liberation.
Copyright (c) 2010-2013 by tyPoland Lukasz Dziedzic (team@latofonts.com)
with Reserved Font Name "Carlito".
Copyright 2014-2021 Adobe (http://www.adobe.com/), Google LLC
with Reserved Font Name "Source". (Noto Sans CJK / Noto Serif CJK)
Note: the Caladea fonts in this directory are NOT under this license;
they are licensed under the Apache License 2.0 (see LICENSE at the
repository root; copyright Huerta Tipografica).
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
PREAMBLE The goals of the Open Font License (OFL) are to stimulate
worldwide development of collaborative font projects, to support the font
creation efforts of academic and linguistic communities, and to provide
a free and open framework in which fonts may be shared and improved in
partnership with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves.
The fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply to
any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such.
This may include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components
as distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting ? in part or in whole ?
any of the components of the Original Version, by changing formats or
by porting the Font Software to a new environment.
"Author" refers to any designer, engineer, programmer, technical writer
or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining a
copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,in
Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the
corresponding Copyright Holder. This restriction only applies to the
primary font name as presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole, must
be distributed entirely under this license, and must not be distributed
under any other license. The requirement for fonts to remain under
this license does not apply to any document created using the Font
Software.
TERMINATION
This license becomes null and void if any of the above conditions are not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
Binary file not shown.

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