Sync snapshot (2026-08-19) (#110)
- Improve Docs pagination, anchored-object fidelity, password protection, recovery safety, and multilingual font fallback - Scale Sheets editing and saves for large workbooks with safer AI bulk operations, aggregation, undo, recovery, and richer visual fidelity - Expand Slides fidelity with 3D rendering, SmartArt and WordArt improvements, pattern and texture fills, and resource cleanup - Add AI PDF creation, text insertion, reading-position restore, safer atomic saves, and improved comments and page workflows - Add Markdown math rendering and protect linked assets across save, conversion, and document lifecycle operations - Read legacy DOC and PPT attachments locally and strengthen document package resource cleanup - Document default-on usage analytics with a persistent Settings opt-out and a dedicated, tested privacy page Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
04a994b9e9
commit
fe2e17403c
@@ -82,6 +82,11 @@ jobs:
|
||||
fi
|
||||
npm run check:theme-colors
|
||||
|
||||
# Keep tracked code comments and contributor-facing documentation
|
||||
# English-only; functional CJK strings and AI prompt examples are allowed.
|
||||
- name: Check comments/docs are English-only
|
||||
run: npm run check:english-comments
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
# GenOffice Privacy
|
||||
|
||||
Last updated: August 19, 2026
|
||||
|
||||
GenOffice opens, edits, and saves documents locally. Document editing does not
|
||||
upload files to GenOffice. AI features require a network connection and send
|
||||
requests only when you use them.
|
||||
|
||||
## Usage analytics
|
||||
|
||||
Usage analytics is enabled by default in packaged official builds, including
|
||||
the initial app launch before the onboarding notice is shown. Onboarding
|
||||
explains what is collected and where to turn it off.
|
||||
|
||||
You can disable reporting at any time under **Settings → General → Send
|
||||
anonymous usage statistics**. An explicit opt-out is remembered and stops all
|
||||
subsequent analytics events.
|
||||
|
||||
### Events and parameters
|
||||
|
||||
When enabled, the app sends these events:
|
||||
|
||||
- `app_launch` — no event-specific parameter
|
||||
- `file_open` — `ext`, the file extension such as `docx` or `xlsx`
|
||||
- `file_new` — `kind`, one of `docx`, `xlsx`, `pptx`, `md`, or `pdf`
|
||||
- `login_click` — no event-specific parameter
|
||||
- `login_success` — no event-specific parameter
|
||||
|
||||
Every event includes:
|
||||
|
||||
- `app_version`
|
||||
- `platform`
|
||||
- `os_version`
|
||||
- `ui_lang`
|
||||
- a per-process `session_id` derived from the process start time
|
||||
- `engagement_time_msec` with the fixed value `100`
|
||||
|
||||
The Google Analytics 4 payload also uses a random install UUID as `client_id`.
|
||||
Neither identifier is a Genspark account or email address.
|
||||
|
||||
## Network information
|
||||
|
||||
Events are sent to Google Analytics 4 using the Measurement Protocol over
|
||||
HTTPS. As the HTTPS recipient, Google necessarily sees the connection's public
|
||||
IP address and transport metadata, and may use them for coarse geolocation and
|
||||
security or spam-abuse processing. GenOffice does not add an IP address to the
|
||||
event payload.
|
||||
|
||||
## Data not collected by analytics
|
||||
|
||||
GenOffice analytics never sends:
|
||||
|
||||
- document content
|
||||
- file names
|
||||
- file paths
|
||||
- Genspark account identity
|
||||
- email addresses
|
||||
|
||||
The analytics metadata is injected only into packaged official builds and is
|
||||
not part of this repository. Source builds and forks without that packaged
|
||||
metadata install a no-op tracker and send no usage analytics; all features work
|
||||
the same.
|
||||
@@ -6,7 +6,7 @@
|
||||
[](https://github.com/genspark-ai/genoffice/releases/latest)
|
||||
[](https://github.com/genspark-ai/genoffice/releases)
|
||||
|
||||
[Website](https://genoffice.ai/) · [Download](https://github.com/genspark-ai/genoffice/releases/latest) · [Demo](https://www.youtube.com/watch?v=B2pLdMX95v4)
|
||||
[Website](https://genoffice.ai/) · [Download](https://github.com/genspark-ai/genoffice/releases/latest) · [Privacy](PRIVACY.md) · [Demo](https://www.youtube.com/watch?v=B2pLdMX95v4)
|
||||
|
||||
GenOffice is a free, open-source alternative to Microsoft Office for macOS,
|
||||
Windows, and Linux, built around AI editing as a first-class workflow rather
|
||||
@@ -38,12 +38,12 @@ layer.
|
||||
|
||||
| Platform | Requirements | Download |
|
||||
| ------------------------------------ | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **macOS** — Apple Silicon (arm64) | macOS 11+ | [GenOffice-0.7.204-arm64.dmg](https://github.com/genspark-ai/genoffice/releases/download/v0.7.204/GenOffice-0.7.204-arm64.dmg) |
|
||||
| **macOS** — Intel (x64) | macOS 11+ | [GenOffice-0.7.204.dmg](https://github.com/genspark-ai/genoffice/releases/download/v0.7.204/GenOffice-0.7.204.dmg) |
|
||||
| **Windows** (x64) | Windows 10+ | [GenOfficeSetup-v0.7.204.exe](https://github.com/genspark-ai/genoffice/releases/download/v0.7.204/GenOfficeSetup-v0.7.204.exe) |
|
||||
| **Linux** — Debian / Ubuntu | x86_64, glibc 2.34+ (Ubuntu 22.04 or newer) | [genoffice_0.7.204_amd64.deb](https://github.com/genspark-ai/genoffice/releases/download/v0.7.204/genoffice_0.7.204_amd64.deb) |
|
||||
| **Linux** — Fedora / RHEL / openSUSE | x86_64, glibc 2.34+ (Fedora 35+, RHEL 9+, Leap 15.6+) | [genoffice-0.7.204.x86_64.rpm](https://github.com/genspark-ai/genoffice/releases/download/v0.7.204/genoffice-0.7.204.x86_64.rpm) |
|
||||
| **Linux** — other distributions | x86_64, glibc 2.34+, FUSE 2 | [GenOffice-0.7.204.AppImage](https://github.com/genspark-ai/genoffice/releases/download/v0.7.204/GenOffice-0.7.204.AppImage) |
|
||||
| **macOS** — Apple Silicon (arm64) | macOS 11+ | [GenOffice-0.7.512-arm64.dmg](https://github.com/genspark-ai/genoffice/releases/download/v0.7.512/GenOffice-0.7.512-arm64.dmg) |
|
||||
| **macOS** — Intel (x64) | macOS 11+ | [GenOffice-0.7.512.dmg](https://github.com/genspark-ai/genoffice/releases/download/v0.7.512/GenOffice-0.7.512.dmg) |
|
||||
| **Windows** (x64) | Windows 10+ | [GenOfficeSetup-v0.7.512.exe](https://github.com/genspark-ai/genoffice/releases/download/v0.7.512/GenOfficeSetup-v0.7.512.exe) |
|
||||
| **Linux** — Debian / Ubuntu | x86_64, glibc 2.34+ (Ubuntu 22.04 or newer) | [genoffice_0.7.512_amd64.deb](https://github.com/genspark-ai/genoffice/releases/download/v0.7.512/genoffice_0.7.512_amd64.deb) |
|
||||
| **Linux** — Fedora / RHEL / openSUSE | x86_64, glibc 2.34+ (Fedora 35+, RHEL 9+, Leap 15.6+) | [genoffice-0.7.512.x86_64.rpm](https://github.com/genspark-ai/genoffice/releases/download/v0.7.512/genoffice-0.7.512.x86_64.rpm) |
|
||||
| **Linux** — other distributions | x86_64, glibc 2.34+, FUSE 2 | [GenOffice-0.7.512.AppImage](https://github.com/genspark-ai/genoffice/releases/download/v0.7.512/GenOffice-0.7.512.AppImage) |
|
||||
|
||||
All builds come from `main`; the macOS and Windows installers are signed.
|
||||
Older versions are on the [Releases](https://github.com/genspark-ai/genoffice/releases) page.
|
||||
@@ -54,14 +54,14 @@ The deb installs with apt — it pulls in the dependencies and adds GenOffice
|
||||
to the applications menu:
|
||||
|
||||
```bash
|
||||
sudo apt install ./genoffice_0.7.204_amd64.deb
|
||||
sudo apt install ./genoffice_0.7.512_amd64.deb
|
||||
```
|
||||
|
||||
On Fedora / RHEL-family / openSUSE, install the rpm instead:
|
||||
|
||||
```bash
|
||||
sudo dnf install ./genoffice-0.7.204.x86_64.rpm # Fedora / RHEL family
|
||||
sudo zypper install ./genoffice-0.7.204.x86_64.rpm # openSUSE
|
||||
sudo dnf install ./genoffice-0.7.512.x86_64.rpm # Fedora / RHEL family
|
||||
sudo zypper install ./genoffice-0.7.512.x86_64.rpm # openSUSE
|
||||
```
|
||||
|
||||
The AppImage instead runs in place: install the FUSE 2 runtime
|
||||
@@ -69,8 +69,8 @@ The AppImage instead runs in place: install the FUSE 2 runtime
|
||||
make the file executable, then run it:
|
||||
|
||||
```bash
|
||||
chmod +x GenOffice-0.7.204.AppImage
|
||||
./GenOffice-0.7.204.AppImage
|
||||
chmod +x GenOffice-0.7.512.AppImage
|
||||
./GenOffice-0.7.512.AppImage
|
||||
```
|
||||
|
||||
## Apps
|
||||
@@ -177,6 +177,12 @@ in to a Genspark account and need a network connection.
|
||||
Yes — real PDF text and image editing that rewrites the page content stream
|
||||
with the original fonts preserved, not cover-up annotations.
|
||||
|
||||
**Does GenOffice collect any data?**
|
||||
Official packaged builds send limited usage analytics by default, and you can
|
||||
disable reporting at any time under Settings → General. Analytics never sends
|
||||
document content, file names, file paths, account identity, or email addresses.
|
||||
See [GenOffice Privacy](PRIVACY.md) for the complete event and data disclosures.
|
||||
|
||||
## Security
|
||||
|
||||
See [SECURITY.md](SECURITY.md) for the process security posture (renderer
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
"electron-vite": "^5.0.0",
|
||||
"jsdom": "^28.0.0",
|
||||
"marked": "^17.0.6",
|
||||
"officecrypto-tool": "^0.0.19",
|
||||
"opentype.js": "^2.0.0",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
|
||||
+231
-41
@@ -64,13 +64,32 @@ import type {
|
||||
AttachmentImageResult,
|
||||
AttachmentMeta,
|
||||
AttachmentReadResult,
|
||||
DecryptOpenResult,
|
||||
DocsTabInfo,
|
||||
MenuCommand,
|
||||
OpenFileResult,
|
||||
OpenDocxResult,
|
||||
} from '../shared/ipc'
|
||||
import { ATTACHMENT_IMAGE_EXTS } from '../shared/ipc'
|
||||
import { findDocxPath } from '../shared/open-file'
|
||||
import { atomicWriteFile, looksLikeZip } from './atomic-write'
|
||||
import {
|
||||
commitDocPasswordSave,
|
||||
currentDocPasswordIntentRevision,
|
||||
decryptDocx,
|
||||
decryptRecoveryCopy,
|
||||
discardDocPasswordIntents,
|
||||
DocxDecryptError,
|
||||
docPasswordFor,
|
||||
encryptDocx,
|
||||
forgetDocPasswords,
|
||||
isEncryptedDocx,
|
||||
markDiskEncrypted,
|
||||
prepareRecoveryDocx,
|
||||
rememberDocPassword,
|
||||
renameDocPassword,
|
||||
setDocPassword,
|
||||
snapshotDocPassword,
|
||||
} from './docx-encryption'
|
||||
import { isExternallyModified, type DiskFileState } from './external-change'
|
||||
import { initDocsAutoUpdater } from './updater'
|
||||
|
||||
@@ -2035,6 +2054,9 @@ export function docsFileRenamed(wc: WebContents, oldPath: string, newPath: strin
|
||||
states.delete(oldPath)
|
||||
states.set(newPath, recorded)
|
||||
}
|
||||
// an encrypted document's password must follow the path, or the next save
|
||||
// finds no password under the new name and silently writes plaintext
|
||||
renameDocPassword(wc.id, oldPath, newPath)
|
||||
wc.send('docs:renamed', { oldPath, newPath })
|
||||
}
|
||||
|
||||
@@ -2208,6 +2230,7 @@ export function teardownDocsRenderer(contents: WebContents): void {
|
||||
docWritablePaths.delete(contents.id)
|
||||
pdfWritablePaths.delete(contents.id)
|
||||
docDiskStates.delete(contents.id)
|
||||
forgetDocPasswords(contents.id)
|
||||
if (!contents.isDestroyed()) contents.send('docs:teardown')
|
||||
}
|
||||
|
||||
@@ -2230,21 +2253,30 @@ function clearRecoveryCopy(filePath: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
interface MaybeRecoveredDocBytes {
|
||||
bytes: Buffer
|
||||
recovered: boolean
|
||||
}
|
||||
|
||||
/** On open, if a recovery copy newer than the original exists, ask whether to restore
|
||||
* (still points at the original path; only save persists it). */
|
||||
async function maybeRecoverDocBytes(filePath: string, original: Buffer): Promise<Buffer> {
|
||||
async function maybeRecoverDocBytes(
|
||||
filePath: string,
|
||||
original: Buffer,
|
||||
): Promise<MaybeRecoveredDocBytes> {
|
||||
const asPath = recoveryPathFor(filePath)
|
||||
try {
|
||||
if (!existsSync(asPath)) return original
|
||||
if (!existsSync(asPath)) return { bytes: original, recovered: false }
|
||||
if (statSync(asPath).mtimeMs <= statSync(filePath).mtimeMs) {
|
||||
// a crashed partial write bumps mtime yet corrupts the file — keep the copy then
|
||||
if (looksLikeZip(original)) {
|
||||
// a crashed partial write bumps mtime yet corrupts the file — keep the copy
|
||||
// then (an encrypted original is a CFB container, not a zip: intact too)
|
||||
if (looksLikeZip(original) || isEncryptedDocx(original)) {
|
||||
unlinkSync(asPath)
|
||||
return original
|
||||
return { bytes: original, recovered: false }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return original
|
||||
return { bytes: original, recovered: false }
|
||||
}
|
||||
const options = {
|
||||
type: 'question' as const,
|
||||
@@ -2261,23 +2293,56 @@ async function maybeRecoverDocBytes(filePath: string, original: Buffer): Promise
|
||||
: await dialog.showMessageBox(options)
|
||||
if (r.response === 0) {
|
||||
try {
|
||||
return await readFile(asPath)
|
||||
return { bytes: await readFile(asPath), recovered: true }
|
||||
} catch {
|
||||
return original
|
||||
return { bytes: original, recovered: false }
|
||||
}
|
||||
}
|
||||
clearRecoveryCopy(filePath)
|
||||
return original
|
||||
return { bytes: original, recovered: false }
|
||||
}
|
||||
|
||||
async function loadDocx(filePath: string, wcId: number): Promise<OpenFileResult | null> {
|
||||
async function loadDocx(
|
||||
filePath: string,
|
||||
wcId: number,
|
||||
password?: string,
|
||||
): Promise<OpenDocxResult> {
|
||||
if (typeof filePath !== 'string' || !/\.docx$/i.test(filePath)) return null
|
||||
if (!existsSync(filePath)) return null
|
||||
const original = await readFile(filePath)
|
||||
// Password-protected docx (ECMA-376 CFB container): without a password, hand
|
||||
// back a marker — the renderer prompts and retries via docs:open-decrypt.
|
||||
// No side effects (recents/write grant) until the password checks out.
|
||||
let plainBytes: Buffer = original
|
||||
const encrypted = isEncryptedDocx(original)
|
||||
if (encrypted) {
|
||||
const pwd = password ?? docPasswordFor(wcId, filePath)
|
||||
if (!pwd) return { needsPassword: true, path: filePath, name: basename(filePath) }
|
||||
plainBytes = await decryptDocx(original, pwd) // throws DocxDecryptError
|
||||
rememberDocPassword(wcId, filePath, pwd)
|
||||
} else {
|
||||
rememberDocPassword(wcId, filePath, null)
|
||||
}
|
||||
// the archive keeps the on-disk original as-is (encrypted ones included: they
|
||||
// reopen with the user's password), so a bad save never loses the source file
|
||||
const hash = await archiveOriginal(filePath, original)
|
||||
const bytes = await maybeRecoverDocBytes(filePath, original)
|
||||
const recovery = await maybeRecoverDocBytes(filePath, plainBytes)
|
||||
let bytes = recovery.bytes
|
||||
let recovered = recovery.recovered
|
||||
// recovery copies of a protected document are themselves encrypted (see
|
||||
// docs:write-recovery); an unreadable copy falls back to the original
|
||||
if (encrypted && isEncryptedDocx(bytes)) {
|
||||
try {
|
||||
bytes = await decryptRecoveryCopy(wcId, filePath, bytes)
|
||||
} catch {
|
||||
bytes = plainBytes
|
||||
recovered = false
|
||||
}
|
||||
}
|
||||
pushRecent(filePath)
|
||||
allowDocWrite(wcId, filePath)
|
||||
if (fileOpenedHook) fileOpenedHook(wcId, filePath)
|
||||
markDiskEncrypted(wcId, filePath, encrypted)
|
||||
// record the on-disk file, not the recovery copy: what matters is what save would overwrite
|
||||
await rememberDiskState(wcId, filePath, original)
|
||||
return {
|
||||
@@ -2285,6 +2350,8 @@ async function loadDocx(filePath: string, wcId: number): Promise<OpenFileResult
|
||||
name: basename(filePath),
|
||||
data: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer,
|
||||
hash,
|
||||
encrypted,
|
||||
recovered: recovered || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2333,6 +2400,7 @@ const TEXT_EXTS = new Set([
|
||||
/** office/pdf formats get text extracted via @genoffice/file-parse; images skip extraction and go multimodal (files:read-image) */
|
||||
const ATTACHMENT_EXTS = new Set([
|
||||
...TEXT_EXTS,
|
||||
'doc',
|
||||
'docx',
|
||||
'pdf',
|
||||
'pptx',
|
||||
@@ -2654,6 +2722,19 @@ function notifyFileSaved(wc: WebContents, filePath: string): void {
|
||||
if (fileSavedHook) fileSavedHook(wc, filePath)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired when a docx is opened INSIDE an existing tab (File > Open dialog or an
|
||||
* explicit path open). Sheets and slides have had this hook from the start;
|
||||
* docs only synced the tab on save-as/first-save, so a file opened into an
|
||||
* untitled tab kept the "Untitled Document" tab title until a save landed on a
|
||||
* NEW path — which a plain Ctrl+S to the original file never does (r115).
|
||||
*/
|
||||
let fileOpenedHook: ((wcId: number, filePath: string) => void) | null = null
|
||||
|
||||
export function setDocsFileOpenedHook(hook: (wcId: number, filePath: string) => void): void {
|
||||
fileOpenedHook = hook
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse lookup from a sheets sessionId to its file path. In shell mode the
|
||||
* project:* handlers are registered by this file, but only sheets-main knows the
|
||||
@@ -2844,6 +2925,66 @@ export function registerDocsIpc(): void {
|
||||
|
||||
ipcMain.handle('docs:open-path', (event, filePath: string) => loadDocx(filePath, event.sender.id))
|
||||
|
||||
// Review > Protect > Encrypt with Password: set/clear the open password.
|
||||
// Takes effect on the next save (docs:save / save-as / save-new all consult the store).
|
||||
ipcMain.handle(
|
||||
'docs:set-password',
|
||||
(event, filePath: string | null, password: string | null): { ok: boolean } => {
|
||||
if (tornDownWcIds.has(event.sender.id)) return { ok: false }
|
||||
if (filePath !== null && typeof filePath !== 'string') return { ok: false }
|
||||
if (password !== null && (typeof password !== 'string' || password.length === 0)) {
|
||||
return { ok: false }
|
||||
}
|
||||
// only the document this renderer legitimately has open (same grant as saving)
|
||||
if (filePath && !canDocWrite(event.sender.id, filePath)) return { ok: false }
|
||||
setDocPassword(event.sender.id, filePath, password)
|
||||
return { ok: true }
|
||||
},
|
||||
)
|
||||
|
||||
ipcMain.handle('docs:password-intent-revision', (event): number => {
|
||||
if (tornDownWcIds.has(event.sender.id)) return -1
|
||||
return currentDocPasswordIntentRevision()
|
||||
})
|
||||
|
||||
ipcMain.handle(
|
||||
'docs:discard-password-intents',
|
||||
(event, throughRevision: unknown): { ok: boolean } => {
|
||||
if (tornDownWcIds.has(event.sender.id)) return { ok: false }
|
||||
if (
|
||||
typeof throughRevision !== 'number' ||
|
||||
!Number.isSafeInteger(throughRevision) ||
|
||||
throughRevision < 0
|
||||
) {
|
||||
return { ok: false }
|
||||
}
|
||||
discardDocPasswordIntents(event.sender.id, throughRevision)
|
||||
return { ok: true }
|
||||
},
|
||||
)
|
||||
|
||||
// decrypt-and-open a password-protected docx; wrong-password keeps the renderer's prompt open
|
||||
ipcMain.handle(
|
||||
'docs:open-decrypt',
|
||||
async (event, filePath: string, password: string): Promise<DecryptOpenResult> => {
|
||||
if (typeof filePath !== 'string' || typeof password !== 'string' || password.length === 0) {
|
||||
return { ok: false, reason: 'error', error: 'invalid arguments' }
|
||||
}
|
||||
try {
|
||||
const result = await loadDocx(filePath, event.sender.id, password)
|
||||
if (!result) return { ok: false, reason: 'error', error: 'file not found' }
|
||||
// the file was swapped for a plain docx between prompt and submit — still an open
|
||||
if ('needsPassword' in result) return { ok: false, reason: 'error', error: 'not encrypted' }
|
||||
return { ok: true, result }
|
||||
} catch (err) {
|
||||
if (err instanceof DocxDecryptError) {
|
||||
return { ok: false, reason: err.reason, error: err.message }
|
||||
}
|
||||
return { ok: false, reason: 'error', error: String(err) }
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
ipcMain.handle('docs:consume-pending-open', (event) => {
|
||||
rendererReady = true
|
||||
// a tab spawned via New Tab loads the document queued for it specifically
|
||||
@@ -2901,12 +3042,32 @@ export function registerDocsIpc(): void {
|
||||
if (tornDownWcIds.has(event.sender.id) || !canDocWrite(event.sender.id, filePath)) {
|
||||
return { ok: false, error: 'save target is not an opened document' }
|
||||
}
|
||||
const bytes = Buffer.from(data)
|
||||
// Snapshot desired state: the disk password remains unchanged until the
|
||||
// atomic write succeeds, and a newer ribbon intent survives this save.
|
||||
const passwordState = snapshotDocPassword(event.sender.id, filePath)
|
||||
const bytes = passwordState.password
|
||||
? encryptDocx(Buffer.from(data), passwordState.password)
|
||||
: Buffer.from(data)
|
||||
await atomicWriteFile(filePath, bytes)
|
||||
// Teardown may have cleared all in-memory secrets while the atomic
|
||||
// write was pending. Never resurrect state for an orphaned renderer.
|
||||
if (tornDownWcIds.has(event.sender.id)) {
|
||||
return { ok: false, error: 'save target is not an opened document' }
|
||||
}
|
||||
await rememberDiskState(event.sender.id, filePath, bytes)
|
||||
if (tornDownWcIds.has(event.sender.id)) {
|
||||
return { ok: false, error: 'save target is not an opened document' }
|
||||
}
|
||||
// Commit immediately after the final await: intents received during
|
||||
// post-write bookkeeping are included, with no later async race.
|
||||
const passwordIntentPending = commitDocPasswordSave(
|
||||
event.sender.id,
|
||||
passwordState,
|
||||
filePath,
|
||||
)
|
||||
clearRecoveryCopy(filePath)
|
||||
pushRecent(filePath)
|
||||
return { ok: true }
|
||||
return { ok: true, passwordIntentPending }
|
||||
} catch (err) {
|
||||
return { ok: false, error: String(err) }
|
||||
}
|
||||
@@ -2923,7 +3084,12 @@ export function registerDocsIpc(): void {
|
||||
// copy while this write is in flight bumps the epoch and invalidates it
|
||||
const epoch = recoveryClearEpochs.get(filePath) ?? 0
|
||||
await mkdir(recoveryDir(), { recursive: true })
|
||||
await atomicWriteFile(recoveryPathFor(filePath), Buffer.from(data))
|
||||
// Recovery follows the current disk state, never the desired next-save
|
||||
// password. Missing state for an encrypted disk file skips the tick so
|
||||
// plaintext can never be written as its recovery copy.
|
||||
const bytes = prepareRecoveryDocx(event.sender.id, filePath, Buffer.from(data))
|
||||
if (!bytes) return { ok: false }
|
||||
await atomicWriteFile(recoveryPathFor(filePath), bytes)
|
||||
// The tab may have been closed ("Don't Save" clears the copy, teardown
|
||||
// revokes access) or the document saved (docs:save clears the copy) while
|
||||
// the write was in flight. A write that lost either race would offer
|
||||
@@ -2942,30 +3108,46 @@ export function registerDocsIpc(): void {
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle('docs:save-as', async (event, defaultName: string, data: ArrayBuffer) => {
|
||||
// an orphaned (closed-tab) renderer must not open dialogs or land new files
|
||||
if (tornDownWcIds.has(event.sender.id)) return { ok: false }
|
||||
const result = await saveDialog(event, {
|
||||
title: tm('dlgSaveAs'),
|
||||
defaultPath: defaultName,
|
||||
filters: [{ name: tm('filterWord'), extensions: ['docx'] }],
|
||||
})
|
||||
if (result.canceled || !result.filePath) return { ok: false }
|
||||
// the tab may have been closed while the dialog was open; checked before the
|
||||
// write because Save As may overwrite an existing file (no safe rollback)
|
||||
if (tornDownWcIds.has(event.sender.id)) return { ok: false }
|
||||
try {
|
||||
const bytes = Buffer.from(data)
|
||||
await atomicWriteFile(result.filePath, bytes)
|
||||
allowDocWrite(event.sender.id, result.filePath)
|
||||
await rememberDiskState(event.sender.id, result.filePath, bytes)
|
||||
pushRecent(result.filePath)
|
||||
notifyFileSaved(event.sender, result.filePath)
|
||||
return { ok: true, path: result.filePath }
|
||||
} catch (err) {
|
||||
return { ok: false, error: String(err) }
|
||||
}
|
||||
})
|
||||
ipcMain.handle(
|
||||
'docs:save-as',
|
||||
async (event, defaultName: string, data: ArrayBuffer, sourcePath?: string | null) => {
|
||||
// an orphaned (closed-tab) renderer must not open dialogs or land new files
|
||||
if (tornDownWcIds.has(event.sender.id)) return { ok: false }
|
||||
const result = await saveDialog(event, {
|
||||
title: tm('dlgSaveAs'),
|
||||
defaultPath: defaultName,
|
||||
filters: [{ name: tm('filterWord'), extensions: ['docx'] }],
|
||||
})
|
||||
if (result.canceled || !result.filePath) return { ok: false }
|
||||
// the tab may have been closed while the dialog was open; checked before the
|
||||
// write because Save As may overwrite an existing file (no safe rollback)
|
||||
if (tornDownWcIds.has(event.sender.id)) return { ok: false }
|
||||
try {
|
||||
const passwordState = snapshotDocPassword(
|
||||
event.sender.id,
|
||||
typeof sourcePath === 'string' && sourcePath ? sourcePath : null,
|
||||
)
|
||||
const bytes = passwordState.password
|
||||
? encryptDocx(Buffer.from(data), passwordState.password)
|
||||
: Buffer.from(data)
|
||||
await atomicWriteFile(result.filePath, bytes)
|
||||
if (tornDownWcIds.has(event.sender.id)) return { ok: false }
|
||||
allowDocWrite(event.sender.id, result.filePath)
|
||||
await rememberDiskState(event.sender.id, result.filePath, bytes)
|
||||
if (tornDownWcIds.has(event.sender.id)) return { ok: false }
|
||||
const passwordIntentPending = commitDocPasswordSave(
|
||||
event.sender.id,
|
||||
passwordState,
|
||||
result.filePath,
|
||||
)
|
||||
pushRecent(result.filePath)
|
||||
notifyFileSaved(event.sender, result.filePath)
|
||||
return { ok: true, path: result.filePath, passwordIntentPending }
|
||||
} catch (err) {
|
||||
return { ok: false, error: String(err) }
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
ipcMain.handle('docs:save-new', async (event, defaultName: string, data: ArrayBuffer) => {
|
||||
try {
|
||||
@@ -2973,7 +3155,10 @@ export function registerDocsIpc(): void {
|
||||
// itself to the default folder after the user chose Don't Save
|
||||
if (tornDownWcIds.has(event.sender.id)) return { ok: false }
|
||||
const filePath = uniquePathIn(defaultSaveDir(), defaultName)
|
||||
const bytes = Buffer.from(data)
|
||||
const passwordState = snapshotDocPassword(event.sender.id, null)
|
||||
const bytes = passwordState.password
|
||||
? encryptDocx(Buffer.from(data), passwordState.password)
|
||||
: Buffer.from(data)
|
||||
await atomicWriteFile(filePath, bytes)
|
||||
// teardown may have happened while the write was in flight — the path is
|
||||
// freshly created, so rolling it back is safe (mirrors docs:write-recovery)
|
||||
@@ -2983,9 +3168,14 @@ export function registerDocsIpc(): void {
|
||||
}
|
||||
allowDocWrite(event.sender.id, filePath)
|
||||
await rememberDiskState(event.sender.id, filePath, bytes)
|
||||
if (tornDownWcIds.has(event.sender.id)) {
|
||||
await unlink(filePath).catch(() => {})
|
||||
return { ok: false }
|
||||
}
|
||||
const passwordIntentPending = commitDocPasswordSave(event.sender.id, passwordState, filePath)
|
||||
pushRecent(filePath)
|
||||
notifyFileSaved(event.sender, filePath)
|
||||
return { ok: true, path: filePath }
|
||||
return { ok: true, path: filePath, passwordIntentPending }
|
||||
} catch (err) {
|
||||
return { ok: false, error: String(err) }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
/**
|
||||
* Password-protected (ECMA-376 encrypted) docx support. The single integration
|
||||
* point for the third-party crypto implementation (officecrypto-tool): if it
|
||||
* ever needs replacing, only this module changes.
|
||||
*
|
||||
* An encrypted docx is not a zip: Word/WPS repackage it as a CFB (OLE2)
|
||||
* container holding an EncryptionInfo stream (parameters) and an
|
||||
* EncryptedPackage stream (the ciphertext of the real docx zip). Both apps
|
||||
* write the same MS-OFFCRYPTO formats (Standard = AES-128/SHA-1, Agile =
|
||||
* AES-256/SHA-512), and both open either — so we decrypt both and re-encrypt
|
||||
* with Agile, matching Word 2013+ defaults.
|
||||
*/
|
||||
import officeCrypto from 'officecrypto-tool'
|
||||
|
||||
const CFB_MAGIC = Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1])
|
||||
const ENCRYPTED_STREAM_UTF16 = Buffer.from('EncryptedPackage', 'utf16le')
|
||||
|
||||
/** CFB (OLE2) container magic — for a .docx path this means "encrypted" (plain docx is a zip) */
|
||||
export function isCfbFile(bytes: Buffer): boolean {
|
||||
return bytes.length >= 8 && bytes.subarray(0, 8).equals(CFB_MAGIC)
|
||||
}
|
||||
|
||||
/** ECMA-376 encrypted OOXML: CFB magic + an EncryptedPackage stream in the directory. */
|
||||
export function isEncryptedDocx(bytes: Buffer): boolean {
|
||||
return isCfbFile(bytes) && bytes.includes(ENCRYPTED_STREAM_UTF16)
|
||||
}
|
||||
|
||||
export type DecryptFailReason = 'wrong-password' | 'unsupported'
|
||||
|
||||
export class DocxDecryptError extends Error {
|
||||
readonly reason: DecryptFailReason
|
||||
constructor(reason: DecryptFailReason, message: string) {
|
||||
super(message)
|
||||
this.reason = reason
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt an encrypted docx into plain zip bytes. Throws DocxDecryptError with
|
||||
* reason 'wrong-password' (verifier mismatch — reprompt) or 'unsupported'
|
||||
* (exotic scheme, e.g. WPS account encryption or Extensible encryption).
|
||||
*/
|
||||
export async function decryptDocx(bytes: Buffer, password: string): Promise<Buffer> {
|
||||
try {
|
||||
return await officeCrypto.decrypt(bytes, { password })
|
||||
} catch (err) {
|
||||
const message = String((err as Error)?.message ?? err)
|
||||
if (message.includes('password is incorrect')) {
|
||||
throw new DocxDecryptError('wrong-password', message)
|
||||
}
|
||||
throw new DocxDecryptError('unsupported', message)
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-encrypt plain docx zip bytes with ECMA-376 Agile (Word 2013+ default). */
|
||||
export function encryptDocx(bytes: Buffer, password: string): Buffer {
|
||||
return officeCrypto.encrypt(bytes, { password })
|
||||
}
|
||||
|
||||
// ── In-memory password state, keyed per renderer + file path.
|
||||
// Never persisted: a relaunch re-prompts, exactly like Word/WPS. ──
|
||||
|
||||
/** Password that can decrypt the bytes currently on disk. */
|
||||
const diskPasswords = new Map<number, Map<string, string>>()
|
||||
|
||||
interface PasswordIntent {
|
||||
password: string | null
|
||||
revision: number
|
||||
}
|
||||
|
||||
/** Desired password for the next successful save of an existing document. */
|
||||
const desiredPasswords = new Map<number, Map<string, PasswordIntent>>()
|
||||
/** Desired password for the next successful save of a pathless document. */
|
||||
const pendingNewDocPasswords = new Map<number, PasswordIntent>()
|
||||
let nextIntentRevision = 1
|
||||
|
||||
/** paths whose on-disk bytes are currently encrypted (tracked at open/save time:
|
||||
* deterministic, unlike probing the file, which can transiently fail) */
|
||||
const diskEncryptedPaths = new Map<number, Set<string>>()
|
||||
|
||||
function setDiskPassword(wcId: number, filePath: string, password: string | null): void {
|
||||
const forWc = diskPasswords.get(wcId) ?? new Map<string, string>()
|
||||
if (password) forWc.set(filePath, password)
|
||||
else forWc.delete(filePath)
|
||||
if (forWc.size > 0) diskPasswords.set(wcId, forWc)
|
||||
else diskPasswords.delete(wcId)
|
||||
}
|
||||
|
||||
/** Record the current on-disk password (null when the opened file is plain). */
|
||||
export function rememberDocPassword(wcId: number, filePath: string, password: string | null): void {
|
||||
setDiskPassword(wcId, filePath, password)
|
||||
}
|
||||
|
||||
/** Password for the bytes currently on disk, or null for plain documents. */
|
||||
export function docPasswordFor(wcId: number, filePath: string | null | undefined): string | null {
|
||||
if (!filePath) return null
|
||||
return diskPasswords.get(wcId)?.get(filePath) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Record the user's desired password for the next save. This deliberately does
|
||||
* not alter the password for the current on-disk bytes: recovery copies and
|
||||
* reopen must keep using that password until a save actually lands.
|
||||
*/
|
||||
export function setDocPassword(
|
||||
wcId: number,
|
||||
filePath: string | null,
|
||||
password: string | null,
|
||||
): void {
|
||||
const intent = { password, revision: nextIntentRevision++ }
|
||||
if (filePath) {
|
||||
const forWc = desiredPasswords.get(wcId) ?? new Map<string, PasswordIntent>()
|
||||
forWc.set(filePath, intent)
|
||||
desiredPasswords.set(wcId, forWc)
|
||||
return
|
||||
}
|
||||
pendingNewDocPasswords.set(wcId, intent)
|
||||
}
|
||||
|
||||
/** Capture a cutoff before document-swap cleanup is queued behind an in-flight save. */
|
||||
export function currentDocPasswordIntentRevision(): number {
|
||||
return nextIntentRevision - 1
|
||||
}
|
||||
|
||||
/**
|
||||
* The renderer accepted a different document. Discard only intents that
|
||||
* existed at the captured cutoff; a password chosen for the replacement
|
||||
* document while cleanup waits behind a save must survive.
|
||||
*/
|
||||
export function discardDocPasswordIntents(
|
||||
wcId: number,
|
||||
throughRevision = Number.MAX_SAFE_INTEGER,
|
||||
): void {
|
||||
const forWc = desiredPasswords.get(wcId)
|
||||
if (forWc) {
|
||||
for (const [path, intent] of forWc) {
|
||||
if (intent.revision <= throughRevision) forWc.delete(path)
|
||||
}
|
||||
if (forWc.size === 0) desiredPasswords.delete(wcId)
|
||||
}
|
||||
const pending = pendingNewDocPasswords.get(wcId)
|
||||
if (pending && pending.revision <= throughRevision) pendingNewDocPasswords.delete(wcId)
|
||||
}
|
||||
|
||||
export interface DocPasswordSaveSnapshot {
|
||||
readonly sourcePath: string | null
|
||||
readonly password: string | null
|
||||
readonly intentRevision: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot the effective desired state before a save starts. A failed write
|
||||
* leaves the snapshot uncommitted, while a successful write commits exactly
|
||||
* these bytes without consuming a newer intent recorded during the await.
|
||||
*/
|
||||
export function snapshotDocPassword(
|
||||
wcId: number,
|
||||
filePath: string | null,
|
||||
): DocPasswordSaveSnapshot {
|
||||
const intent = filePath
|
||||
? desiredPasswords.get(wcId)?.get(filePath)
|
||||
: pendingNewDocPasswords.get(wcId)
|
||||
return {
|
||||
sourcePath: filePath,
|
||||
password: intent ? intent.password : docPasswordFor(wcId, filePath),
|
||||
intentRevision: intent?.revision ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit password state only after the atomic file write succeeds. Save As and
|
||||
* first-save move a newer concurrent intent to the new path so it remains the
|
||||
* desired state for the following save. Returns whether such an intent remains.
|
||||
*/
|
||||
export function commitDocPasswordSave(
|
||||
wcId: number,
|
||||
snapshot: DocPasswordSaveSnapshot,
|
||||
savedPath: string,
|
||||
): boolean {
|
||||
setDiskPassword(wcId, savedPath, snapshot.password)
|
||||
markDiskEncrypted(wcId, savedPath, snapshot.password !== null)
|
||||
|
||||
const sourcePath = snapshot.sourcePath
|
||||
const forWc = desiredPasswords.get(wcId) ?? new Map<string, PasswordIntent>()
|
||||
|
||||
if (sourcePath === null) {
|
||||
const current = pendingNewDocPasswords.get(wcId)
|
||||
// The target may have stale state from an older document opened in this
|
||||
// renderer. Its new baseline is the just-written snapshot.
|
||||
forWc.delete(savedPath)
|
||||
if (current?.revision === snapshot.intentRevision) {
|
||||
pendingNewDocPasswords.delete(wcId)
|
||||
} else if (current) {
|
||||
pendingNewDocPasswords.delete(wcId)
|
||||
forWc.set(savedPath, current)
|
||||
}
|
||||
} else if (sourcePath === savedPath) {
|
||||
const current = forWc.get(sourcePath)
|
||||
if (current?.revision === snapshot.intentRevision) forWc.delete(sourcePath)
|
||||
} else {
|
||||
const current = forWc.get(sourcePath)
|
||||
forWc.delete(sourcePath)
|
||||
forWc.delete(savedPath)
|
||||
if (current && current.revision !== snapshot.intentRevision) {
|
||||
forWc.set(savedPath, current)
|
||||
}
|
||||
}
|
||||
|
||||
if (forWc.size > 0) desiredPasswords.set(wcId, forWc)
|
||||
else desiredPasswords.delete(wcId)
|
||||
return forWc.has(savedPath)
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare crash-recovery bytes using only the password for the current disk
|
||||
* file. Returning null for an encrypted file with missing state is deliberate:
|
||||
* skipping a recovery tick is safer than ever writing its plaintext.
|
||||
*/
|
||||
export function prepareRecoveryDocx(
|
||||
wcId: number,
|
||||
filePath: string,
|
||||
plainBytes: Buffer,
|
||||
): Buffer | null {
|
||||
if (!isDiskEncrypted(wcId, filePath)) return plainBytes
|
||||
const password = docPasswordFor(wcId, filePath)
|
||||
return password ? encryptDocx(plainBytes, password) : null
|
||||
}
|
||||
|
||||
/** Decrypt an encrypted recovery copy with the current disk password. */
|
||||
export async function decryptRecoveryCopy(
|
||||
wcId: number,
|
||||
filePath: string,
|
||||
bytes: Buffer,
|
||||
): Promise<Buffer> {
|
||||
if (!isEncryptedDocx(bytes)) return bytes
|
||||
const password = docPasswordFor(wcId, filePath)
|
||||
if (!password) {
|
||||
throw new DocxDecryptError('unsupported', 'missing password for encrypted recovery copy')
|
||||
}
|
||||
return decryptDocx(bytes, password)
|
||||
}
|
||||
|
||||
/** File renamed on disk: keep disk and desired state reachable under the new path. */
|
||||
export function renameDocPassword(wcId: number, oldPath: string, newPath: string): void {
|
||||
const forWc = diskPasswords.get(wcId)
|
||||
const password = forWc?.get(oldPath)
|
||||
if (forWc && password !== undefined) {
|
||||
forWc.delete(oldPath)
|
||||
forWc.set(newPath, password)
|
||||
}
|
||||
const desiredForWc = desiredPasswords.get(wcId)
|
||||
const desired = desiredForWc?.get(oldPath)
|
||||
if (desiredForWc && desired) {
|
||||
desiredForWc.delete(oldPath)
|
||||
desiredForWc.set(newPath, desired)
|
||||
}
|
||||
const encSet = diskEncryptedPaths.get(wcId)
|
||||
if (encSet?.delete(oldPath)) encSet.add(newPath)
|
||||
}
|
||||
|
||||
/**
|
||||
* Record whether the file's on-disk bytes are encrypted; called wherever the
|
||||
* main process learns the on-disk state (open, and after every save). Recovery
|
||||
* copies key off this: they are only encrypted when the on-disk original is,
|
||||
* so a post-crash reopen (which can only ever obtain the on-disk file's
|
||||
* password) can always decrypt them.
|
||||
*/
|
||||
export function markDiskEncrypted(wcId: number, filePath: string, encrypted: boolean): void {
|
||||
const forWc = diskEncryptedPaths.get(wcId) ?? new Set<string>()
|
||||
if (encrypted) forWc.add(filePath)
|
||||
else forWc.delete(filePath)
|
||||
diskEncryptedPaths.set(wcId, forWc)
|
||||
}
|
||||
|
||||
/** The file's on-disk bytes are encrypted (as last opened/saved by this renderer). */
|
||||
export function isDiskEncrypted(wcId: number, filePath: string): boolean {
|
||||
return diskEncryptedPaths.get(wcId)?.has(filePath) ?? false
|
||||
}
|
||||
|
||||
/** Renderer torn down (tab closed): its passwords must not outlive it. */
|
||||
export function forgetDocPasswords(wcId: number): void {
|
||||
diskPasswords.delete(wcId)
|
||||
desiredPasswords.delete(wcId)
|
||||
pendingNewDocPasswords.delete(wcId)
|
||||
diskEncryptedPaths.delete(wcId)
|
||||
}
|
||||
@@ -34,6 +34,18 @@ const api: DesktopApi = {
|
||||
},
|
||||
openDocx: () => ipcRenderer.invoke('docs:open'),
|
||||
openDocxPath: (path: string) => ipcRenderer.invoke('docs:open-path', path),
|
||||
openDocxDecrypt: (path: string, password: string) =>
|
||||
ipcRenderer.invoke('docs:open-decrypt', path, password),
|
||||
setDocPassword: (filePath: string | null, password: string | null) =>
|
||||
ipcRenderer.invoke('docs:set-password', filePath, password),
|
||||
docPasswordIntentRevision: async () => {
|
||||
const revision: unknown = await ipcRenderer.invoke('docs:password-intent-revision')
|
||||
return typeof revision === 'number' && Number.isSafeInteger(revision) && revision >= 0
|
||||
? revision
|
||||
: 0
|
||||
},
|
||||
discardDocPasswordIntents: (throughRevision: number) =>
|
||||
ipcRenderer.invoke('docs:discard-password-intents', throughRevision),
|
||||
consumePendingOpenDocx: () => ipcRenderer.invoke('docs:consume-pending-open'),
|
||||
consumeNewBlankDoc: () => ipcRenderer.invoke('docs:consume-new-blank'),
|
||||
onOpenDocx: (handler) => {
|
||||
@@ -57,8 +69,8 @@ const api: DesktopApi = {
|
||||
ipcRenderer.on('docs:teardown', listener)
|
||||
return () => ipcRenderer.removeListener('docs:teardown', listener)
|
||||
},
|
||||
saveDocxAs: (defaultName: string, data: ArrayBuffer) =>
|
||||
ipcRenderer.invoke('docs:save-as', defaultName, data),
|
||||
saveDocxAs: (defaultName: string, data: ArrayBuffer, sourcePath?: string | null) =>
|
||||
ipcRenderer.invoke('docs:save-as', defaultName, data, sourcePath ?? null),
|
||||
saveDocxNew: (defaultName: string, data: ArrayBuffer) =>
|
||||
ipcRenderer.invoke('docs:save-new', defaultName, data),
|
||||
getRecentFiles: () => ipcRenderer.invoke('docs:recent'),
|
||||
|
||||
+368
-65
@@ -17,10 +17,12 @@ import {
|
||||
BLANK_ORDERED_NUM_ID,
|
||||
DEFAULT_SECTION,
|
||||
applySectionSettings,
|
||||
verifyProtectionPassword,
|
||||
type Block,
|
||||
type CommentInfo,
|
||||
type CustomNumberingLevel,
|
||||
type DocProtection,
|
||||
type WriteProtection,
|
||||
type HeaderFooter,
|
||||
type HfImage,
|
||||
type NoteInfo,
|
||||
@@ -31,7 +33,7 @@ import {
|
||||
type ThemeColors,
|
||||
type ThemeFonts,
|
||||
} from '@genoffice/docx-engine'
|
||||
import type { AiSettings, OpenFileResult } from '../shared/ipc'
|
||||
import type { AiSettings, OpenDocxResult } from '../shared/ipc'
|
||||
import { AI_PROVIDERS } from '../shared/ipc'
|
||||
import { AiPanel } from './ai/AiPanel'
|
||||
import { asianCharCount, countWords, nonAsianWordCount } from './word-count'
|
||||
@@ -63,6 +65,9 @@ import {
|
||||
type PageNoteItem,
|
||||
pageAt,
|
||||
singleCutCell,
|
||||
columnLayoutSpecs,
|
||||
vAlignShiftSpecs,
|
||||
sectionBidi,
|
||||
sectionColGeom,
|
||||
sectionColumns,
|
||||
sectionFirstPages,
|
||||
@@ -82,8 +87,10 @@ import {
|
||||
setPageGaps,
|
||||
syncCutOverlays,
|
||||
syncFloatShifts,
|
||||
clampCellBoxTops,
|
||||
type PageGapSpec,
|
||||
} from './editor/pagination-gaps'
|
||||
import { setColumnLayout } from './editor/column-layout'
|
||||
import {
|
||||
MARKUP_AREA_W,
|
||||
clearMarginAnnotations,
|
||||
@@ -129,6 +136,7 @@ import {
|
||||
type ContextMenuState,
|
||||
} from './components/ContextMenu'
|
||||
import { PromptModal } from './components/PromptModal'
|
||||
import { ProtectDialog, type ProtectDialogResult } from './components/ProtectDialog'
|
||||
import { t, useI18n } from './i18n/locale'
|
||||
import {
|
||||
getActiveSubEditor,
|
||||
@@ -192,10 +200,7 @@ import {
|
||||
startNewComment as startNewCommentImpl,
|
||||
submitNewComment as submitNewCommentImpl,
|
||||
submitNote as submitNoteImpl,
|
||||
submitProtectModal as submitProtectModalImpl,
|
||||
toggleProtection as toggleProtectionImpl,
|
||||
type NotePrompt,
|
||||
type ProtectModalState,
|
||||
type ReviewContext,
|
||||
} from './review-actions'
|
||||
|
||||
@@ -338,8 +343,24 @@ export function App() {
|
||||
const { lang } = useI18n()
|
||||
const [doc, setDoc] = useState<DocState | null>(null)
|
||||
/** true until the pending-open / new-blank boot checks settle; the start screen stays hidden meanwhile */
|
||||
const bootPendingRef = useRef<Promise<[OpenFileResult | null, boolean]> | null>(null)
|
||||
const bootPendingRef = useRef<Promise<[OpenDocxResult, boolean]> | null>(null)
|
||||
const bootHandledRef = useRef(false)
|
||||
/** password prompt for an ECMA-376 encrypted docx; submit retries via openDocxDecrypt */
|
||||
const [docPwdPrompt, setDocPwdPrompt] = useState<{
|
||||
path: string
|
||||
name: string
|
||||
value: string
|
||||
/** i18n key of the inline failure line ('' = none) */
|
||||
errorKey: '' | 'appDocPwdWrong' | 'appDocPwdUnsupported'
|
||||
busy: boolean
|
||||
} | null>(null)
|
||||
/** Review > Protect: the combined Word-style Protect Document dialog */
|
||||
const [showProtectDialog, setShowProtectDialog] = useState(false)
|
||||
/** prompt for a document with a password to modify (w:writeProtection): enter it or open read-only */
|
||||
const [modifyPwdPrompt, setModifyPwdPrompt] = useState<{
|
||||
value: string
|
||||
errorKey: '' | 'appDocPwdWrong'
|
||||
} | null>(null)
|
||||
const [_recent, setRecent] = useState<string[]>([])
|
||||
const [settings, setSettings] = useState<AiSettings>(DEFAULT_SETTINGS)
|
||||
const [showAi, setShowAi] = useState(() => localStorage.getItem('aidocs.showAi') !== '0')
|
||||
@@ -568,8 +589,27 @@ export function App() {
|
||||
if (editor) editor.view.dispatch(editor.state.tr.setMeta('addToHistory', false))
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [revisionDisplay])
|
||||
// section breaks on tracked-deleted paragraph marks don't break in Word's
|
||||
// markup views (only the Original view restores them)
|
||||
const delSectBreaks = useMemo(
|
||||
() =>
|
||||
revisionDisplay === 'original'
|
||||
? undefined
|
||||
: new Set(
|
||||
(doc?.parsed.blocks ?? [])
|
||||
.filter((b) => b.paraMarkDel && b.docxIndex != null)
|
||||
.map((b) => b.docxIndex as number),
|
||||
),
|
||||
[doc, revisionDisplay],
|
||||
)
|
||||
const [protection, setProtection] = useState<DocProtection | null>(null)
|
||||
const [protectionDirty, setProtectionDirty] = useState(false)
|
||||
const [writeProtection, setWriteProtection] = useState<WriteProtection | null>(null)
|
||||
const [writeProtectionDirty, setWriteProtectionDirty] = useState(false)
|
||||
const [removePersonalInfo, setRemovePersonalInfo] = useState(false)
|
||||
const [removePersonalInfoDirty, setRemovePersonalInfoDirty] = useState(false)
|
||||
/** modify password entered (or set by the user this session) — false = write-locked, document read-only */
|
||||
const [modifyUnlocked, setModifyUnlocked] = useState(true)
|
||||
const [compareResult, setCompareResult] = useState<{
|
||||
otherName: string
|
||||
entries: CompareEntry[]
|
||||
@@ -749,9 +789,27 @@ export function App() {
|
||||
return () => window.removeEventListener('wheel', onWheel)
|
||||
}, [])
|
||||
|
||||
const isProtected = !!protection?.enforced && protection.edit === 'readOnly'
|
||||
// ---- protection enforcement (Review > Protect Document) ----
|
||||
const editRestriction = protection?.enforced ? protection.edit : null
|
||||
/** modify password set but not entered: honor-system write lock, document read-only */
|
||||
const writeLocked = !!writeProtection?.hash && !modifyUnlocked
|
||||
/** body is read-only (readOnly/forms/comments restriction or write lock) */
|
||||
const isProtected =
|
||||
writeLocked ||
|
||||
editRestriction === 'readOnly' ||
|
||||
editRestriction === 'forms' ||
|
||||
editRestriction === 'comments'
|
||||
/** comments restriction: body read-only but adding comments stays allowed */
|
||||
const commentsAllowed = !writeLocked && editRestriction === 'comments'
|
||||
/** trackedChanges restriction: editing allowed, revision recording forced on */
|
||||
const trackChangesForced = !writeLocked && editRestriction === 'trackedChanges'
|
||||
|
||||
// Read Mode / Restrict Editing: the document becomes read-only; Esc leaves Read Mode
|
||||
// the trackedChanges restriction keeps the recorder on (the ribbon toggle is disabled)
|
||||
useEffect(() => {
|
||||
if (trackChangesForced && !trackChanges) setTrackChanges(true)
|
||||
}, [trackChangesForced, trackChanges])
|
||||
|
||||
// Read Mode / Protect Document: the document becomes read-only; Esc leaves Read Mode
|
||||
useEffect(() => {
|
||||
if (!editor) return
|
||||
editor.setEditable(!readMode && !isProtected)
|
||||
@@ -952,11 +1010,25 @@ export function App() {
|
||||
protectionDirty,
|
||||
setProtection,
|
||||
setProtectionDirty,
|
||||
writeProtection,
|
||||
writeProtectionDirty,
|
||||
setWriteProtection,
|
||||
setWriteProtectionDirty,
|
||||
removePersonalInfo,
|
||||
removePersonalInfoDirty,
|
||||
setRemovePersonalInfo,
|
||||
setRemovePersonalInfoDirty,
|
||||
onWriteProtectionLoaded: (wp) => {
|
||||
setModifyUnlocked(!wp?.hash)
|
||||
setModifyPwdPrompt(wp?.hash ? { value: '', errorKey: '' } : null)
|
||||
},
|
||||
setCompareResult,
|
||||
promptDocxPassword: (info) =>
|
||||
setDocPwdPrompt({ path: info.path, name: info.name, value: '', errorKey: '', busy: false }),
|
||||
}
|
||||
|
||||
const loadFile = useCallback(
|
||||
(result: OpenFileResult | null) => loadFileImpl(fileCtxRef.current, result),
|
||||
(result: OpenDocxResult) => loadFileImpl(fileCtxRef.current, result),
|
||||
[],
|
||||
)
|
||||
|
||||
@@ -995,8 +1067,12 @@ export function App() {
|
||||
.then(async ([pending]) => {
|
||||
if (bootHandledRef.current) return
|
||||
bootHandledRef.current = true
|
||||
if (pending) await loadFile(pending)
|
||||
else await newFile()
|
||||
// A failed open (corrupt file etc.) falls back to a blank document —
|
||||
// otherwise the tab shows "Opening…" forever with only a status-bar
|
||||
// line explaining why (github.com/genspark-ai/genoffice issue #102).
|
||||
// 'password': the prompt is up; its cancel path lands on blank instead.
|
||||
const outcome = pending ? await loadFile(pending) : 'canceled'
|
||||
if (outcome === 'failed' || outcome === 'canceled') await newFile()
|
||||
})
|
||||
// Open failures also land on a blank document, or the tab stays at "Opening…" forever
|
||||
.catch(() => {
|
||||
@@ -1025,6 +1101,80 @@ export function App() {
|
||||
[loadFile],
|
||||
)
|
||||
|
||||
/** decrypt-and-open retry loop for the password prompt (wrong password stays in the dialog) */
|
||||
const submitDocPwd = async () => {
|
||||
if (!docPwdPrompt || docPwdPrompt.busy || !docPwdPrompt.value) return
|
||||
setDocPwdPrompt({ ...docPwdPrompt, busy: true, errorKey: '' })
|
||||
const res = await window.desktop.openDocxDecrypt(docPwdPrompt.path, docPwdPrompt.value)
|
||||
if (res.ok) {
|
||||
setDocPwdPrompt(null)
|
||||
const outcome = await loadFile(res.result)
|
||||
// decrypted fine but the content failed to parse: don't strand the boot screen
|
||||
if (outcome === 'failed' && !fileCtxRef.current.doc) void newFile()
|
||||
return
|
||||
}
|
||||
setDocPwdPrompt({
|
||||
...docPwdPrompt,
|
||||
value: res.reason === 'wrong-password' ? '' : docPwdPrompt.value,
|
||||
busy: false,
|
||||
errorKey: res.reason === 'wrong-password' ? 'appDocPwdWrong' : 'appDocPwdUnsupported',
|
||||
})
|
||||
}
|
||||
|
||||
const cancelDocPwd = () => {
|
||||
setDocPwdPrompt(null)
|
||||
// canceling a boot-time open leaves no document: land on blank, not "Opening…"
|
||||
if (!fileCtxRef.current.doc) void newFile()
|
||||
}
|
||||
|
||||
/** apply the diff the Protect Document dialog produced (undefined field = unchanged) */
|
||||
const applyProtectDialog = async (result: ProtectDialogResult) => {
|
||||
setShowProtectDialog(false)
|
||||
let changed = false
|
||||
if (result.openPassword !== undefined) {
|
||||
const cur = fileCtxRef.current.doc
|
||||
const res = await window.desktop.setDocPassword(cur?.filePath ?? null, result.openPassword)
|
||||
if (res.ok) {
|
||||
setDoc((d) => (d ? { ...d, encrypted: !!result.openPassword } : d))
|
||||
// the on-disk file only changes on the next save
|
||||
dirtyRef.current = true
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (result.writeProtection !== undefined) {
|
||||
setWriteProtection(result.writeProtection)
|
||||
setWriteProtectionDirty(true)
|
||||
// the user set (or removed) the modify password themselves: never lock them out
|
||||
setModifyUnlocked(true)
|
||||
dirtyRef.current = true
|
||||
changed = true
|
||||
}
|
||||
if (result.protection !== undefined) {
|
||||
setProtection(result.protection)
|
||||
setProtectionDirty(true)
|
||||
dirtyRef.current = true
|
||||
changed = true
|
||||
}
|
||||
if (result.removePersonalInfo !== undefined) {
|
||||
setRemovePersonalInfo(result.removePersonalInfo)
|
||||
setRemovePersonalInfoDirty(true)
|
||||
dirtyRef.current = true
|
||||
changed = true
|
||||
}
|
||||
if (changed) setStatus(t('appProtectUpdated'))
|
||||
}
|
||||
|
||||
/** modify-password prompt (write-protected document): verify, or fall back to read-only */
|
||||
const submitModifyPwd = async () => {
|
||||
if (!modifyPwdPrompt || !writeProtection) return
|
||||
if (await verifyProtectionPassword(modifyPwdPrompt.value, writeProtection)) {
|
||||
setModifyUnlocked(true)
|
||||
setModifyPwdPrompt(null)
|
||||
} else {
|
||||
setModifyPwdPrompt({ value: '', errorKey: 'appDocPwdWrong' })
|
||||
}
|
||||
}
|
||||
|
||||
const save = useCallback(
|
||||
(saveAs: boolean, auto = false) => saveImpl(fileCtxRef.current, saveAs, auto),
|
||||
[],
|
||||
@@ -1089,6 +1239,8 @@ export function App() {
|
||||
continuous: t('appBreakContinuous'),
|
||||
evenPage: t('appBreakEvenPage'),
|
||||
oddPage: t('appBreakOddPage'),
|
||||
// parse-only start type (single-column: acts like next page); the UI never inserts it
|
||||
nextColumn: t('appBreakNextPage'),
|
||||
}
|
||||
if (doc.filePath) {
|
||||
pendingSectionSaveRef.current = true
|
||||
@@ -1302,7 +1454,6 @@ export function App() {
|
||||
// ---- References: footnotes / endnotes ----
|
||||
|
||||
const [notePrompt, setNotePrompt] = useState<NotePrompt | null>(null)
|
||||
const [protectModal, setProtectModal] = useState<ProtectModalState | null>(null)
|
||||
|
||||
/** App state bundle for the extracted review actions (review-actions.ts); refreshed every render. */
|
||||
const reviewCtxRef = useRef<ReviewContext>(null as unknown as ReviewContext)
|
||||
@@ -1325,11 +1476,6 @@ export function App() {
|
||||
setShowComments,
|
||||
setInkAnnotations,
|
||||
setInksDirty,
|
||||
protection,
|
||||
setProtection,
|
||||
setProtectionDirty,
|
||||
protectModal,
|
||||
setProtectModal,
|
||||
setCompareResult,
|
||||
}
|
||||
|
||||
@@ -1381,8 +1527,6 @@ export function App() {
|
||||
)
|
||||
const removeInks = useCallback((ids: string[]) => removeInksImpl(reviewCtxRef.current, ids), [])
|
||||
const clearInks = useCallback(() => clearInksImpl(reviewCtxRef.current), [])
|
||||
const toggleProtection = useCallback(() => toggleProtectionImpl(reviewCtxRef.current), [])
|
||||
const submitProtectModal = useCallback(() => submitProtectModalImpl(reviewCtxRef.current), [])
|
||||
const compareWithFile = useCallback(() => compareWithFileImpl(reviewCtxRef.current), [])
|
||||
|
||||
const revisionCount = editor && doc ? revisionCountOfDoc(editor.state.doc) : 0
|
||||
@@ -1638,21 +1782,56 @@ export function App() {
|
||||
}))
|
||||
}, [endnotes, sections, section])
|
||||
|
||||
// canvas column-flow geometry (non-null when the cursor's section has equal-width columns —
|
||||
// same follow-the-cursor rule as the canvas page box): shared by canvas CSS / measuring state / preview.
|
||||
// canvas column mode:
|
||||
// - 'uniform': every section shares one equal-width multi-column spec (and is LTR) —
|
||||
// whole-page CSS multicol renders it (browser splits paragraphs across columns natively)
|
||||
// - 'mixed': some multi-column section coexists with other specs (or RTL columns) —
|
||||
// per-block column-layout decorations paint the engine's regions (block granularity)
|
||||
// - 'none': no multi-column sections.
|
||||
// equalWidth="0" (unequal local layout columns) is not modeled, matching the engine's scope
|
||||
const colFlow = useMemo(() => {
|
||||
const cur = sections[Math.min(activeSection, sections.length - 1)]
|
||||
if (!cur || sectionColumns(cur) <= 1) return null
|
||||
return sectionColGeom(cur)
|
||||
}, [sections, activeSection])
|
||||
const colMode = useMemo<'none' | 'uniform' | 'mixed'>(() => {
|
||||
if (sections.length === 0) return 'none'
|
||||
if (!sections.some((s) => sectionColumns(s) > 1)) return 'none'
|
||||
const g0 = sectionColGeom(sections[0])
|
||||
const uniform =
|
||||
!sections.some(sectionBidi) &&
|
||||
// a same-count nextColumn boundary advances a column — whole-page CSS
|
||||
// multicol can't paint that, so such documents go through mixed mode
|
||||
!sections.some((s, i) => i > 0 && s.startType === 'nextColumn') &&
|
||||
sections.every((s) => {
|
||||
const g = sectionColGeom(s)
|
||||
return (
|
||||
g.cols === g0.cols &&
|
||||
g.cols > 1 &&
|
||||
g.equalWidth &&
|
||||
Math.abs(g.colWidthPx - g0.colWidthPx) < 0.5 &&
|
||||
Math.abs(g.gapPx - g0.gapPx) < 0.5
|
||||
)
|
||||
})
|
||||
return uniform ? 'uniform' : 'mixed'
|
||||
}, [sections])
|
||||
|
||||
// single-flow measuring state for the columned canvas: temporarily drop CSS columns and
|
||||
// set the width to the column width so DOM measurement yields 1-D coordinates matching
|
||||
// the engine's column flow (synchronous layout round-trip, no visible flicker)
|
||||
// uniform-mode geometry for the whole-page CSS multicol path / measuring width swap
|
||||
const colFlow = useMemo(
|
||||
() => (colMode === 'uniform' ? sectionColGeom(sections[0]) : null),
|
||||
[colMode, sections],
|
||||
)
|
||||
|
||||
// sectPr w:vAlign pages carry visual block translates (vAlignShiftSpecs), so
|
||||
// measurement must neutralize them exactly like mixed-column translates
|
||||
const hasVAlign = useMemo(
|
||||
() => sections.some((s) => s.settings.vAlign === 'center' || s.settings.vAlign === 'bottom'),
|
||||
[sections],
|
||||
)
|
||||
|
||||
// single-flow measuring state for the columned canvas: uniform mode temporarily drops
|
||||
// the CSS columns and sets the width to the column width; mixed mode neutralizes the
|
||||
// per-block translates/gap compression (widths stay — line boxes must reflect column
|
||||
// wrapping). Either way DOM measurement yields 1-D coordinates matching the engine's
|
||||
// column flow (synchronous layout round-trip, no visible flicker)
|
||||
const measureSingleFlow = useCallback(
|
||||
function run<T>(pm: HTMLElement, fn: () => T): T {
|
||||
if (!colFlow || viewMode !== 'print') return fn()
|
||||
if ((colMode === 'none' && !hasVAlign) || viewMode !== 'print') return fn()
|
||||
pm.classList.add('measuring-columns')
|
||||
try {
|
||||
return fn()
|
||||
@@ -1660,17 +1839,17 @@ export function App() {
|
||||
pm.classList.remove('measuring-columns')
|
||||
}
|
||||
},
|
||||
[colFlow, viewMode],
|
||||
[colMode, hasVAlign, viewMode],
|
||||
)
|
||||
|
||||
// column-flow geometry gate: when the canvas column CSS is inactive, measure as full-width single flow; the geometry must drop cols to match
|
||||
// column-flow geometry gate: when the canvas column layout is inactive, measure as full-width single flow; the geometry must drop cols to match
|
||||
const colGeomsFor = useCallback(
|
||||
(geoms: SectionGeom[]): SectionGeom[] => {
|
||||
if (colFlow && viewMode === 'print') return geoms
|
||||
if (colMode !== 'none' && viewMode === 'print') return geoms
|
||||
for (const g of geoms) if (g.cols) g.cols = undefined
|
||||
return geoms
|
||||
},
|
||||
[colFlow, viewMode],
|
||||
[colMode, viewMode],
|
||||
)
|
||||
|
||||
// real TOC page-number backfill: compute each heading's (docHeading) page from the current real page slicing.
|
||||
@@ -1682,8 +1861,8 @@ export function App() {
|
||||
const factor = zoom / 100
|
||||
const { mBlocks, slices, secs } = measureSingleFlow(pm, () => {
|
||||
const origin = pm.getBoundingClientRect().top + effTopSingle * factor
|
||||
const { blocks, totalHeight } = measureBlocks(pm, origin, factor)
|
||||
const live = liveSections(sections, blocks)
|
||||
const { blocks, totalHeight, sectBreaks } = measureBlocks(pm, origin, factor)
|
||||
const live = liveSections(sections, blocks, sectBreaks, delSectBreaks)
|
||||
let s: PageSlice[]
|
||||
if (live.length > 0) {
|
||||
assignSections(blocks, live)
|
||||
@@ -1721,6 +1900,7 @@ export function App() {
|
||||
editor,
|
||||
section,
|
||||
sections,
|
||||
delSectBreaks,
|
||||
zoom,
|
||||
blockMetaOf,
|
||||
effTopSingle,
|
||||
@@ -1781,11 +1961,12 @@ export function App() {
|
||||
const measured = measureSingleFlow(pm, () => {
|
||||
const t0 = performance.now()
|
||||
const origin = pm.getBoundingClientRect().top + mTopPx * factor
|
||||
const { blocks, totalHeight, floats } = measureBlocks(pm, origin, factor)
|
||||
const { blocks, totalHeight, floats, sectBreaks } = measureBlocks(pm, origin, factor)
|
||||
tMeasure = performance.now() - t0
|
||||
// multi-section: assign blocks to sections by docxIndex; each section has its own content height / forced breaks.
|
||||
// liveSections: when a section-break block is deleted, that section merges into the next in real time (effective before saving)
|
||||
const secList = sections.length > 0 ? liveSections(sections, blocks) : null
|
||||
const secList =
|
||||
sections.length > 0 ? liveSections(sections, blocks, sectBreaks, delSectBreaks) : null
|
||||
if (secList) assignSections(blocks, secList)
|
||||
// the endnote area takes part in page slicing (placed together at the document end; overflows continue on later pages)
|
||||
const withEndnotes = appendEndnotesBlock(
|
||||
@@ -1961,8 +2142,11 @@ export function App() {
|
||||
// strip must not overflow the (portrait) canvas paper it is drawn on
|
||||
const canvasPaperW = pmRect.width / factor
|
||||
slices.slice(1).forEach((slice, k) => {
|
||||
// an even/odd section's zero-height blank page shares its start with the following page: draw only one gap band on the canvas
|
||||
if (slice.start === slices[k].start) return
|
||||
// a same-start predecessor that is zero-height is a deliberate blank page
|
||||
// (leading/double w:br, even/odd parity): it needs its own gap band so the
|
||||
// blank sheet paints (pad below covers its full paper height); other
|
||||
// same-start duplicates draw only one band
|
||||
if (slice.start === slices[k].start && slices[k].end > slices[k].start) return
|
||||
// gap = previous page's (its section's) bottom margin + inter-page band + this page's (its section's) top margin
|
||||
const prevSec = secList?.[slices[k].section]?.settings ?? section
|
||||
const nextSec = secList?.[slice.section]?.settings ?? section
|
||||
@@ -1977,7 +2161,9 @@ export function App() {
|
||||
}
|
||||
// a page ended early (explicit break / section break / keepNext) leaves unused
|
||||
// content height; pad the gap so the canvas paints the full paper height and the
|
||||
// footer stays at the paper bottom. Multi-column pages span columns × height, skip.
|
||||
// footer stays at the paper bottom. Uniform multi-column pages span columns ×
|
||||
// height with the browser compressing the flow, skip; mixed-column pages use the
|
||||
// engine's physical height and pull the gap up over the vacated stacked space.
|
||||
const prevContentH =
|
||||
twipsToPx(prevSec.pageHeight) -
|
||||
effectiveTopPx(prevSec, prevHf.headerPx) -
|
||||
@@ -1986,7 +2172,13 @@ export function App() {
|
||||
const items = pageNotes[k] ?? []
|
||||
const fnH =
|
||||
items.length > 0 ? items.reduce((s, n) => s + n.height, 0) + FOOTNOTE_SEPARATOR_H : 0
|
||||
const remaining = slices[k].regions ? 0 : Math.max(0, prevContentH - used)
|
||||
const physUsed = slices[k].regions
|
||||
? colMode === 'mixed'
|
||||
? (slices[k].physHeight ?? used)
|
||||
: null
|
||||
: used
|
||||
const remaining = physUsed === null ? 0 : Math.max(0, prevContentH - physUsed)
|
||||
const pullUp = physUsed === null ? 0 : Math.max(0, used - physUsed)
|
||||
// used excludes the reserved footnote height (footnoteExtraPx inflates capacity
|
||||
// bookkeeping, not DOM coordinates), and the notes area already extends the gap
|
||||
// by fnH: pad covers only the rest of the shortfall
|
||||
@@ -2070,6 +2262,7 @@ export function App() {
|
||||
pad > 0
|
||||
? { ...notesMetrics, marginBottom: notesMetrics.marginBottom + pad }
|
||||
: notesMetrics,
|
||||
...(pullUp > 0.5 ? { pullUp } : {}),
|
||||
...(blocks[i].breakBefore || (i > 0 && blocks[i - 1].breakAfter)
|
||||
? { suppressLeadMt: true }
|
||||
: {}),
|
||||
@@ -2083,7 +2276,25 @@ export function App() {
|
||||
const b = blocks.find(
|
||||
(bb) => bb.el && bb.top < slice.start && slice.start < bb.top + bb.height - 0.5,
|
||||
)
|
||||
if (!b?.el) return
|
||||
if (!b?.el) {
|
||||
// deliberate trailing blank page (document ends with a page break): no
|
||||
// anchor block exists — hang the gap at the document end so the blank
|
||||
// sheet paints (min-height extension below covers its paper height)
|
||||
if (k + 2 === slices.length) {
|
||||
gaps.push({
|
||||
pos: editor.state.doc.content.size,
|
||||
kind: 'inline',
|
||||
metrics:
|
||||
pad > 0
|
||||
? { ...notesMetrics, marginBottom: notesMetrics.marginBottom + pad }
|
||||
: notesMetrics,
|
||||
...(pullUp > 0.5 ? { pullUp } : {}),
|
||||
...hfProps,
|
||||
})
|
||||
markShown()
|
||||
}
|
||||
return
|
||||
}
|
||||
if (b.el.querySelector('tr')) {
|
||||
// in-table cut point: insert an in-table gap row (display:table-row widget)
|
||||
// before the broken row (next page's first row). Positioning must subtract the
|
||||
@@ -2222,6 +2433,7 @@ export function App() {
|
||||
marginLeft: (r.left - pmRect.left) / factor,
|
||||
marginRight: (pmRect.right - r.right) / factor,
|
||||
},
|
||||
...(pullUp > 0.5 ? { pullUp } : {}),
|
||||
...hfProps,
|
||||
})
|
||||
} else {
|
||||
@@ -2260,6 +2472,7 @@ export function App() {
|
||||
marginLeft: (elRect.left - pmRect.left) / factor,
|
||||
marginRight: (pmRect.right - elRect.right) / factor,
|
||||
},
|
||||
...(pullUp > 0.5 ? { pullUp } : {}),
|
||||
...(notes ? { notes, notesKey } : {}),
|
||||
...hfProps,
|
||||
})
|
||||
@@ -2312,8 +2525,22 @@ export function App() {
|
||||
tGapsBuild = performance.now() - tGaps0
|
||||
const tSet0 = performance.now()
|
||||
setPageGaps(editor.view, gaps, firstPageFloats)
|
||||
// mixed-column canvas: paint the engine's regions via per-block width/translate decorations
|
||||
const colSpecs =
|
||||
viewMode === 'print' && !readMode && colMode === 'mixed' && secList
|
||||
? columnLayoutSpecs(blocks, slices, secList)
|
||||
: []
|
||||
// sectPr w:vAlign pages ride the same visual-translate channel
|
||||
const vaSpecs =
|
||||
viewMode === 'print' && !readMode && secList && hfHs
|
||||
? vAlignShiftSpecs(blocks, slices, secList, sectionGeoms(secList, hfHs))
|
||||
: []
|
||||
setColumnLayout(editor.view, [...colSpecs, ...vaSpecs])
|
||||
// after setPageGaps: widget insertion is synchronous, so anchor rects are final
|
||||
syncFloatShifts(pm, floats, pm.getBoundingClientRect().top + mTopPx * factor, factor)
|
||||
// Word keeps anchored objects on the page: cell boxes lifted past the
|
||||
// paper top by a negative anchor offset are pushed back down
|
||||
clampCellBoxTops(pm, pm.getBoundingClientRect().top, factor)
|
||||
syncCutOverlays((pm.closest('.page-wrap') as HTMLElement) ?? pm, overlayCutAnchors, factor)
|
||||
syncMarginAnnotations(
|
||||
(pm.closest('.page-wrap') as HTMLElement) ?? pm,
|
||||
@@ -2321,6 +2548,7 @@ export function App() {
|
||||
comments,
|
||||
factor,
|
||||
doc.parsed.blocks,
|
||||
editor.view,
|
||||
)
|
||||
tSetGaps = performance.now() - tSet0
|
||||
// suppression collapses the DOM after this pass sliced; one follow-up remeasure re-syncs (sig goes stable, no loop)
|
||||
@@ -2358,7 +2586,30 @@ export function App() {
|
||||
// for real-device verification/troubleshooting: current slices and block geometry (read-only snapshot, no functional dependency)
|
||||
;(window as unknown as Record<string, unknown>).__pageDebug = {
|
||||
slices,
|
||||
blocks: blocks.map((b) => ({ top: b.top, height: b.height, docxIndex: b.docxIndex })),
|
||||
colMode,
|
||||
colSpecs: colSpecs.map((s) => ({
|
||||
w: s.widthPx === undefined ? null : Math.round(s.widthPx),
|
||||
dx: Math.round(s.dx),
|
||||
dy: Math.round(s.dy),
|
||||
cls: s.el.className.slice(0, 30),
|
||||
})),
|
||||
secs: secList?.map((s, i) => ({
|
||||
startType: s.startType,
|
||||
cols: sectionColumns(s),
|
||||
first: s.firstBlockIndex,
|
||||
last: s.lastBlockIndex,
|
||||
contentH: hfHs
|
||||
? Math.round(sectionGeoms(secList, hfHs)[i]?.contentHeight ?? -1)
|
||||
: undefined,
|
||||
})),
|
||||
blocks: blocks.map((b) => ({
|
||||
top: b.top,
|
||||
height: b.height,
|
||||
docxIndex: b.docxIndex,
|
||||
section: b.section,
|
||||
empty: b.emptyPara,
|
||||
nLines: b.lineBoxes?.length,
|
||||
})),
|
||||
tableRows: blocks
|
||||
.filter((b) => b.tableRows)
|
||||
.map((b) => ({
|
||||
@@ -2438,6 +2689,7 @@ export function App() {
|
||||
// display-mode toggles reflow the text (No Markup hides deletions) and gate
|
||||
// the change bars, but dispatch no doc change: remeasure must follow them
|
||||
revisionDisplay,
|
||||
delSectBreaks,
|
||||
])
|
||||
|
||||
// section at the cursor: the target the Layout tab acts on
|
||||
@@ -2967,7 +3219,7 @@ export function App() {
|
||||
onGotoRevision: (dir: 1 | -1) => {
|
||||
if (editor) gotoRevision(editor, dir)
|
||||
},
|
||||
onToggleProtection: toggleProtection,
|
||||
onProtectDoc: () => setShowProtectDialog(true),
|
||||
onCompare: () => void compareWithFile(),
|
||||
onViewMode: setViewMode,
|
||||
onReadMode: setReadMode,
|
||||
@@ -3071,7 +3323,7 @@ export function App() {
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`app ${readMode ? 'read-mode' : ''}${revisionDisplay !== 'all' ? ` rev-display-${revisionDisplay}` : ''}`}
|
||||
className={`app ${readMode ? 'read-mode' : ''}${revisionDisplay !== 'all' ? ` rev-display-${revisionDisplay}` : ''}${revisionDisplay === 'all' && viewMode === 'print' ? ' rev-balloon' : ''}`}
|
||||
>
|
||||
<ToastHost />
|
||||
{docCss && <style>{docCss}</style>}
|
||||
@@ -3133,6 +3385,11 @@ export function App() {
|
||||
revisionDisplay={revisionDisplay}
|
||||
revisionCount={revisionCount}
|
||||
isProtected={isProtected}
|
||||
commentsAllowed={commentsAllowed}
|
||||
trackChangesForced={trackChangesForced}
|
||||
protectActive={
|
||||
isProtected || trackChangesForced || (doc?.encrypted ?? false) || !!writeProtection?.hash
|
||||
}
|
||||
filePath={doc?.filePath ?? null}
|
||||
viewMode={viewMode}
|
||||
readMode={readMode}
|
||||
@@ -3483,8 +3740,10 @@ export function App() {
|
||||
<PaginationPreview
|
||||
section={section}
|
||||
sections={sections}
|
||||
delSectBreaks={delSectBreaks}
|
||||
hfParts={doc.parsed.hfParts ?? {}}
|
||||
colFlow={viewMode === 'print' ? colFlow : null}
|
||||
colMode={viewMode === 'print' ? colMode : 'none'}
|
||||
zoom={zoom}
|
||||
hf={{
|
||||
header,
|
||||
@@ -3507,6 +3766,9 @@ export function App() {
|
||||
endnoteItems={endnoteItems}
|
||||
sectionHfOverride={sectionHfOverride}
|
||||
clearPageGaps={() => {
|
||||
// column-layout decorations stay: the preview measures with the block widths
|
||||
// (line boxes must keep column wrapping); transforms are neutralized by its
|
||||
// measuring-columns state
|
||||
if (editor) setPageGaps(editor.view, [])
|
||||
const wrap = document.querySelector('.editor-scroll .page-wrap')
|
||||
if (wrap) {
|
||||
@@ -3575,38 +3837,79 @@ export function App() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{protectModal && (
|
||||
<div
|
||||
className="modal-backdrop"
|
||||
onMouseDown={(e) => e.target === e.currentTarget && setProtectModal(null)}
|
||||
>
|
||||
{docPwdPrompt && (
|
||||
<div className="modal-backdrop">
|
||||
<div className="modal">
|
||||
<h2>
|
||||
{protectModal.mode === 'set' ? t('appRestrictEditing') : t('appUnrestrictEditing')}
|
||||
</h2>
|
||||
<h2>{t('appDocPwdTitle')}</h2>
|
||||
<p className="pgnum-hint">{t('appDocPwdBody', { name: docPwdPrompt.name })}</p>
|
||||
<label className="pgnum-row">
|
||||
{protectModal.mode === 'set' ? t('appProtectPwdOptional') : t('appProtectPwdEnter')}
|
||||
{t('appDocPwdLabel')}
|
||||
<input
|
||||
type="password"
|
||||
autoFocus
|
||||
value={protectModal.value}
|
||||
disabled={docPwdPrompt.busy}
|
||||
value={docPwdPrompt.value}
|
||||
onChange={(e) =>
|
||||
setProtectModal({ ...protectModal, value: e.target.value, error: undefined })
|
||||
setDocPwdPrompt({ ...docPwdPrompt, value: e.target.value, errorKey: '' })
|
||||
}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') void submitProtectModal()
|
||||
if (e.key === 'Enter') void submitDocPwd()
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
{protectModal.error && (
|
||||
<p className="pgnum-hint" style={{ color: '#c62828' }}>
|
||||
{protectModal.error}
|
||||
</p>
|
||||
)}
|
||||
{protectModal.mode === 'set' && <p className="pgnum-hint">{t('appProtectPwdHint')}</p>}
|
||||
{docPwdPrompt.errorKey && <p className="modal-error">{t(docPwdPrompt.errorKey)}</p>}
|
||||
<div className="modal-actions">
|
||||
<button onClick={() => setProtectModal(null)}>{t('appCancel')}</button>
|
||||
<button className="btn-primary" onClick={() => void submitProtectModal()}>
|
||||
<button onClick={cancelDocPwd}>{t('appCancel')}</button>
|
||||
<button
|
||||
className="btn-primary"
|
||||
disabled={docPwdPrompt.busy || !docPwdPrompt.value}
|
||||
onClick={() => void submitDocPwd()}
|
||||
>
|
||||
{docPwdPrompt.busy ? t('appStartOpening') : t('appOk')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showProtectDialog && (
|
||||
<ProtectDialog
|
||||
encrypted={doc?.encrypted ?? false}
|
||||
writeProtection={writeProtection}
|
||||
protection={protection}
|
||||
removePersonalInfo={removePersonalInfo}
|
||||
onCancel={() => setShowProtectDialog(false)}
|
||||
onApply={(result) => void applyProtectDialog(result)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{modifyPwdPrompt && doc && (
|
||||
<div className="modal-backdrop">
|
||||
<div className="modal">
|
||||
<h2>{t('appModifyPwdTitle')}</h2>
|
||||
<p className="pgnum-hint">{t('appModifyPwdBody', { name: doc.fileName })}</p>
|
||||
<label>
|
||||
{t('appDocPwdLabel')}
|
||||
<input
|
||||
type="password"
|
||||
autoFocus
|
||||
value={modifyPwdPrompt.value}
|
||||
onChange={(e) => setModifyPwdPrompt({ value: e.target.value, errorKey: '' })}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') void submitModifyPwd()
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
{modifyPwdPrompt.errorKey && (
|
||||
<p className="modal-error">{t(modifyPwdPrompt.errorKey)}</p>
|
||||
)}
|
||||
<div className="modal-actions">
|
||||
<button onClick={() => setModifyPwdPrompt(null)}>{t('appOpenReadOnly')}</button>
|
||||
<button
|
||||
className="btn-primary"
|
||||
disabled={!modifyPwdPrompt.value}
|
||||
onClick={() => void submitModifyPwd()}
|
||||
>
|
||||
{t('appOk')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
liveSections,
|
||||
measureBlocks,
|
||||
pageNumbers,
|
||||
sectionBidi,
|
||||
sectionColGeom,
|
||||
sectionFirstPages,
|
||||
sectionGeoms,
|
||||
@@ -139,8 +140,10 @@ export interface HfSet {
|
||||
export function PaginationPreview({
|
||||
section,
|
||||
sections,
|
||||
delSectBreaks,
|
||||
hfParts,
|
||||
colFlow,
|
||||
colMode,
|
||||
zoom,
|
||||
hf,
|
||||
watermark,
|
||||
@@ -157,10 +160,14 @@ export function PaginationPreview({
|
||||
section: SectionSettings
|
||||
/** All sections: for per-page paper geometry (empty array = single section per `section`) */
|
||||
sections: SectionInfo[]
|
||||
/** section-break paragraphs whose mark is a tracked deletion (no break in markup views) */
|
||||
delSectBreaks?: Set<number>
|
||||
/** 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
|
||||
/** canvas column mode: 'uniform' = whole-page CSS multicol, 'mixed' = per-block layout decorations */
|
||||
colMode: 'none' | 'uniform' | 'mixed'
|
||||
zoom: number
|
||||
hf: HfSet
|
||||
watermark: string | null
|
||||
@@ -213,12 +220,21 @@ export function PaginationPreview({
|
||||
if (!pm) return
|
||||
clearPageGaps?.()
|
||||
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')
|
||||
// switch the columned canvas to the single-flow measuring state (uniform: CSS columns
|
||||
// off, width = column width; mixed: block translates off), matching engine column-flow
|
||||
// coordinates. vAlign documents carry the same visual translates on the canvas
|
||||
// (vAlignShiftSpecs) and the preview applies its own vOffset, so they must be
|
||||
// neutralized here too or the shifted rects double-apply.
|
||||
const measureNeutralize =
|
||||
colMode !== 'none' ||
|
||||
section.vAlign === 'center' ||
|
||||
section.vAlign === 'bottom' ||
|
||||
sections.some((s) => s.settings.vAlign === 'center' || s.settings.vAlign === 'bottom')
|
||||
if (measureNeutralize) pm.classList.add('measuring-columns')
|
||||
try {
|
||||
const origin = pm.getBoundingClientRect().top + canvasMTop * factor
|
||||
const { blocks, totalHeight, floats } = measureBlocks(pm, origin, factor)
|
||||
const live = liveSections(sections, blocks)
|
||||
const { blocks, totalHeight, floats, sectBreaks } = measureBlocks(pm, origin, factor)
|
||||
const live = liveSections(sections, blocks, sectBreaks, delSectBreaks)
|
||||
setSecs(live)
|
||||
if (live.length > 0) assignSections(blocks, live)
|
||||
const withEndnotes = appendEndnotesBlock(
|
||||
@@ -264,8 +280,8 @@ export function PaginationPreview({
|
||||
}
|
||||
})
|
||||
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
|
||||
// when the canvas column layout is inactive, measure as full-width single flow; the geometry drops column flow to match
|
||||
if (colMode === 'none') for (const g of geoms) if (g.cols) g.cols = undefined
|
||||
computed = sliceWithLineSplit(blocks, geoms, flowH, factor, blockMetaOf)
|
||||
} else {
|
||||
const contentH =
|
||||
@@ -324,7 +340,7 @@ export function PaginationPreview({
|
||||
setHtml(Array.from(pm.children, (c) => cloneBlockHtml(c as HTMLElement)).join(''))
|
||||
}
|
||||
} finally {
|
||||
if (colFlow) pm.classList.remove('measuring-columns')
|
||||
if (measureNeutralize) pm.classList.remove('measuring-columns')
|
||||
}
|
||||
// snapshot: measure once on open; deps intentionally empty
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
@@ -564,17 +580,32 @@ export function PaginationPreview({
|
||||
? slice.regions![ri + 1].top - region.top
|
||||
: undefined
|
||||
const multi = rg.cols > 1
|
||||
const rtl = multi && rSec != null && sectionBidi(rSec)
|
||||
const geo = rg as Partial<{ widths: number[]; gaps: number[] }> & typeof rg
|
||||
// per-column width/gap (w:equalWidth="0" lists differ per column);
|
||||
// gaps ride the columns as margins so unequal spaces work too
|
||||
const widthOf = (ci: number) =>
|
||||
multi ? (geo.widths?.[ci] ?? rg.colWidthPx) : undefined
|
||||
const gapAfter = (ci: number) =>
|
||||
multi && ci < region.columns.length - 1 ? (geo.gaps?.[ci] ?? rg.gapPx) : 0
|
||||
return (
|
||||
<div
|
||||
key={ri}
|
||||
className="pv-region"
|
||||
style={{ gap: rg.gapPx, ...(extent !== undefined ? { height: extent } : {}) }}
|
||||
style={{
|
||||
...(extent !== undefined ? { height: extent } : {}),
|
||||
// RTL section (w:bidi): columns fill right-to-left
|
||||
...(rtl ? { flexDirection: 'row-reverse' as const } : {}),
|
||||
}}
|
||||
>
|
||||
{region.columns.map((col, ci) => (
|
||||
<div
|
||||
key={ci}
|
||||
className="pv-col"
|
||||
style={{ width: multi ? rg.colWidthPx : undefined }}
|
||||
style={{
|
||||
width: widthOf(ci),
|
||||
...(rtl ? { marginLeft: gapAfter(ci) } : { marginRight: gapAfter(ci) }),
|
||||
}}
|
||||
>
|
||||
{col.repeatHeader && (
|
||||
<div className="pv-clip" style={{ height: col.repeatHeader.height }}>
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
/**
|
||||
* Word-style "Protect Document" dialog (Review > Protect), modeled on Word for
|
||||
* Mac's Password Protect sheet. One dialog covers all protection features:
|
||||
*
|
||||
* - Security: password to open (ECMA-376 whole-file encryption) and password
|
||||
* to modify (settings.xml w:writeProtection, honor-system).
|
||||
* - Protection: editing restriction (w:documentProtection) with the four Word
|
||||
* modes (tracked changes / comments / read only / forms) + optional password.
|
||||
* - Privacy: remove known author and organization metadata on save.
|
||||
*
|
||||
* The dialog only computes a diff (ProtectDialogResult); applying it (IPC for
|
||||
* the open password, dirty-state for the rest) is the caller's job.
|
||||
*/
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
hashProtectionPassword,
|
||||
verifyProtectionPassword,
|
||||
type DocProtection,
|
||||
type WriteProtection,
|
||||
} from '@genoffice/docx-engine'
|
||||
import { useI18n } from '../i18n/locale'
|
||||
|
||||
/** every field: undefined = unchanged; null = remove; value = set */
|
||||
export interface ProtectDialogResult {
|
||||
openPassword?: string | null
|
||||
writeProtection?: WriteProtection | null
|
||||
protection?: DocProtection | null
|
||||
removePersonalInfo?: boolean
|
||||
}
|
||||
|
||||
export const PROTECTION_MODES = ['trackedChanges', 'comments', 'readOnly', 'forms'] as const
|
||||
export type ProtectionMode = (typeof PROTECTION_MODES)[number]
|
||||
|
||||
const MODE_LABEL_KEYS = {
|
||||
trackedChanges: 'appProtectModeTracked',
|
||||
comments: 'appProtectModeComments',
|
||||
readOnly: 'appProtectModeReadOnly',
|
||||
forms: 'appProtectModeForms',
|
||||
} as const
|
||||
|
||||
/**
|
||||
* Existing passwords are only known as hashes, so the fields are prefilled
|
||||
* with an untypable sentinel that renders as dots: submitting it unchanged
|
||||
* keeps the password, clearing the field removes it.
|
||||
*/
|
||||
const KEEP = '\u0001'.repeat(8)
|
||||
|
||||
type ErrorKey = '' | 'appEncMismatch' | 'appWrongPassword'
|
||||
|
||||
export function ProtectDialog({
|
||||
encrypted,
|
||||
writeProtection,
|
||||
protection,
|
||||
removePersonalInfo,
|
||||
onCancel,
|
||||
onApply,
|
||||
}: {
|
||||
/** an open password is desired for the next save */
|
||||
encrypted: boolean
|
||||
writeProtection: WriteProtection | null
|
||||
protection: DocProtection | null
|
||||
removePersonalInfo: boolean
|
||||
onCancel: () => void
|
||||
onApply: (result: ProtectDialogResult) => void
|
||||
}) {
|
||||
const { t } = useI18n()
|
||||
const hadModifyPwd = !!writeProtection?.hash
|
||||
const wasEnforced = !!protection?.enforced
|
||||
/** changing/removing an enforced password-protected restriction needs the password */
|
||||
const locked = wasEnforced && !!protection?.hash
|
||||
|
||||
const [openPwd, setOpenPwd] = useState(encrypted ? KEEP : '')
|
||||
const [openPwd2, setOpenPwd2] = useState(encrypted ? KEEP : '')
|
||||
const [modifyPwd, setModifyPwd] = useState(hadModifyPwd ? KEEP : '')
|
||||
const [modifyPwd2, setModifyPwd2] = useState(hadModifyPwd ? KEEP : '')
|
||||
const [protectOn, setProtectOn] = useState(wasEnforced)
|
||||
const [mode, setMode] = useState<ProtectionMode>(
|
||||
PROTECTION_MODES.includes(protection?.edit as ProtectionMode)
|
||||
? (protection?.edit as ProtectionMode)
|
||||
: 'trackedChanges',
|
||||
)
|
||||
const [protectPwd, setProtectPwd] = useState(locked ? KEEP : '')
|
||||
const [unlockPwd, setUnlockPwd] = useState('')
|
||||
const [removePersonal, setRemovePersonal] = useState(removePersonalInfo)
|
||||
const [errorKey, setErrorKey] = useState<ErrorKey>('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const protectionChanged =
|
||||
protectOn !== wasEnforced ||
|
||||
(protectOn && (mode !== protection?.edit || protectPwd !== (locked ? KEEP : '')))
|
||||
|
||||
const submit = async () => {
|
||||
if (busy) return
|
||||
if (openPwd !== openPwd2 || modifyPwd !== modifyPwd2) {
|
||||
setErrorKey('appEncMismatch')
|
||||
return
|
||||
}
|
||||
setBusy(true)
|
||||
try {
|
||||
const result: ProtectDialogResult = {}
|
||||
|
||||
if (openPwd !== (encrypted ? KEEP : '')) {
|
||||
result.openPassword = openPwd === '' ? null : openPwd
|
||||
}
|
||||
|
||||
if (modifyPwd !== (hadModifyPwd ? KEEP : '')) {
|
||||
const recommended = writeProtection?.recommended ? { recommended: true } : {}
|
||||
result.writeProtection =
|
||||
modifyPwd === ''
|
||||
? writeProtection?.recommended
|
||||
? { recommended: true }
|
||||
: null
|
||||
: { ...recommended, ...(await hashProtectionPassword(modifyPwd)) }
|
||||
}
|
||||
|
||||
if (protectionChanged) {
|
||||
if (locked && !(await verifyProtectionPassword(unlockPwd, protection!))) {
|
||||
setErrorKey('appWrongPassword')
|
||||
return
|
||||
}
|
||||
if (!protectOn) {
|
||||
result.protection = null
|
||||
} else {
|
||||
const creds =
|
||||
protectPwd === KEEP && protection?.hash
|
||||
? {
|
||||
hash: protection.hash,
|
||||
salt: protection.salt,
|
||||
spinCount: protection.spinCount,
|
||||
algorithmSid: protection.algorithmSid,
|
||||
}
|
||||
: protectPwd && protectPwd !== KEEP
|
||||
? await hashProtectionPassword(protectPwd)
|
||||
: {}
|
||||
result.protection = { edit: mode, enforced: true, ...creds }
|
||||
}
|
||||
}
|
||||
|
||||
if (removePersonal !== removePersonalInfo) {
|
||||
result.removePersonalInfo = removePersonal
|
||||
}
|
||||
|
||||
onApply(result)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const onEnter = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') void submit()
|
||||
}
|
||||
const clearError = () => setErrorKey('')
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop">
|
||||
<div className="modal protect-dialog">
|
||||
<h2>{t('appProtectTitle')}</h2>
|
||||
|
||||
<h3 className="protect-section-title">{t('appProtectSecurity')}</h3>
|
||||
<label>
|
||||
{t('appProtectOpenPwd')}
|
||||
<input
|
||||
type="password"
|
||||
autoFocus
|
||||
maxLength={255}
|
||||
value={openPwd}
|
||||
onChange={(e) => {
|
||||
setOpenPwd(e.target.value)
|
||||
clearError()
|
||||
}}
|
||||
onKeyDown={onEnter}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('appEncConfirmLabel')}
|
||||
<input
|
||||
type="password"
|
||||
maxLength={255}
|
||||
value={openPwd2}
|
||||
onChange={(e) => {
|
||||
setOpenPwd2(e.target.value)
|
||||
clearError()
|
||||
}}
|
||||
onKeyDown={onEnter}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('appProtectModifyPwd')}
|
||||
<input
|
||||
type="password"
|
||||
maxLength={255}
|
||||
value={modifyPwd}
|
||||
onChange={(e) => {
|
||||
setModifyPwd(e.target.value)
|
||||
clearError()
|
||||
}}
|
||||
onKeyDown={onEnter}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('appEncConfirmLabel')}
|
||||
<input
|
||||
type="password"
|
||||
maxLength={255}
|
||||
value={modifyPwd2}
|
||||
onChange={(e) => {
|
||||
setModifyPwd2(e.target.value)
|
||||
clearError()
|
||||
}}
|
||||
onKeyDown={onEnter}
|
||||
/>
|
||||
</label>
|
||||
{(encrypted || hadModifyPwd) && <p className="pgnum-hint">{t('appProtectPwdKeepHint')}</p>}
|
||||
|
||||
<h3 className="protect-section-title">{t('appProtectSectionTitle')}</h3>
|
||||
<label className="protect-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={protectOn}
|
||||
onChange={(e) => {
|
||||
setProtectOn(e.target.checked)
|
||||
clearError()
|
||||
}}
|
||||
/>
|
||||
{t('appProtectFor')}
|
||||
</label>
|
||||
<div className="protect-modes">
|
||||
{PROTECTION_MODES.map((m) => (
|
||||
<label key={m} className="protect-check">
|
||||
<input
|
||||
type="radio"
|
||||
name="protect-mode"
|
||||
disabled={!protectOn}
|
||||
checked={mode === m}
|
||||
onChange={() => {
|
||||
setMode(m)
|
||||
clearError()
|
||||
}}
|
||||
/>
|
||||
{t(MODE_LABEL_KEYS[m])}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{protectOn && (
|
||||
<label>
|
||||
{t('appProtectPwdOptional')}
|
||||
<input
|
||||
type="password"
|
||||
maxLength={255}
|
||||
value={protectPwd}
|
||||
onChange={(e) => {
|
||||
setProtectPwd(e.target.value)
|
||||
clearError()
|
||||
}}
|
||||
onKeyDown={onEnter}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{locked && protectionChanged && (
|
||||
<label>
|
||||
{t('appProtectUnlockPwd')}
|
||||
<input
|
||||
type="password"
|
||||
value={unlockPwd}
|
||||
onChange={(e) => {
|
||||
setUnlockPwd(e.target.value)
|
||||
clearError()
|
||||
}}
|
||||
onKeyDown={onEnter}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
|
||||
<h3 className="protect-section-title">{t('appProtectPrivacy')}</h3>
|
||||
<label className="protect-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={removePersonal}
|
||||
onChange={(e) => setRemovePersonal(e.target.checked)}
|
||||
/>
|
||||
{t('appProtectRemovePersonal')}
|
||||
</label>
|
||||
|
||||
{errorKey && <p className="modal-error">{t(errorKey)}</p>}
|
||||
<div className="modal-actions">
|
||||
<button onClick={onCancel}>{t('appCancel')}</button>
|
||||
<button className="btn-primary" disabled={busy} onClick={() => void submit()}>
|
||||
{t('appOk')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -205,7 +205,13 @@ interface RibbonProps {
|
||||
onRejectRevision: (all: boolean) => void
|
||||
onGotoRevision: (dir: 1 | -1) => void
|
||||
isProtected: boolean
|
||||
onToggleProtection: () => void
|
||||
/** comments restriction: adding comments stays allowed although the body is read-only */
|
||||
commentsAllowed: boolean
|
||||
/** trackedChanges restriction: the recorder is forced on (toggle and accept/reject disabled) */
|
||||
trackChangesForced: boolean
|
||||
/** any protection is configured (highlights the Protect Document button) */
|
||||
protectActive: boolean
|
||||
onProtectDoc: () => void
|
||||
onCompare: () => void
|
||||
/** current document path (View → New Window opens it in another window) */
|
||||
filePath: string | null
|
||||
@@ -605,7 +611,10 @@ function RibbonInner({
|
||||
onRejectRevision,
|
||||
onGotoRevision,
|
||||
isProtected,
|
||||
onToggleProtection,
|
||||
commentsAllowed,
|
||||
trackChangesForced,
|
||||
protectActive,
|
||||
onProtectDoc,
|
||||
onCompare,
|
||||
filePath,
|
||||
viewMode,
|
||||
@@ -3234,7 +3243,10 @@ function RibbonInner({
|
||||
onRejectRevision={onRejectRevision}
|
||||
onGotoRevision={onGotoRevision}
|
||||
isProtected={isProtected}
|
||||
onToggleProtection={onToggleProtection}
|
||||
commentsAllowed={commentsAllowed}
|
||||
trackChangesForced={trackChangesForced}
|
||||
protectActive={protectActive}
|
||||
onProtectDoc={onProtectDoc}
|
||||
onCompare={onCompare}
|
||||
/>
|
||||
) : (
|
||||
|
||||
@@ -1060,6 +1060,15 @@ export function IconLock(props: IconProps) {
|
||||
)
|
||||
}
|
||||
|
||||
export function IconKey(props: IconProps) {
|
||||
return (
|
||||
<Svg {...props}>
|
||||
<circle cx="5.4" cy="10.6" r="2.5" />
|
||||
<path d="M 7.3 8.7 L 12.9 3.1 M 10.4 5.6 l 1.7 1.7 M 12.1 3.9 l 1.4 1.4" />
|
||||
</Svg>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- View ---------- */
|
||||
|
||||
function Magnifier({ children }: { children?: ReactNode }) {
|
||||
|
||||
@@ -524,9 +524,15 @@ interface ReviewTabProps extends TabProps {
|
||||
onAcceptRevision: (all: boolean) => void
|
||||
onRejectRevision: (all: boolean) => void
|
||||
onGotoRevision: (dir: 1 | -1) => void
|
||||
/** Restrict Editing (read-only) is enforced */
|
||||
/** an editing restriction or write lock makes the body read-only */
|
||||
isProtected: boolean
|
||||
onToggleProtection: () => void
|
||||
/** comments restriction: adding comments stays allowed although the body is read-only */
|
||||
commentsAllowed: boolean
|
||||
/** trackedChanges restriction: the recorder is forced on (toggle and accept/reject disabled) */
|
||||
trackChangesForced: boolean
|
||||
/** any protection is configured (highlights the Protect Document button) */
|
||||
protectActive: boolean
|
||||
onProtectDoc: () => void
|
||||
onCompare: () => void
|
||||
}
|
||||
|
||||
@@ -548,7 +554,10 @@ export function ReviewTab({
|
||||
onRejectRevision,
|
||||
onGotoRevision,
|
||||
isProtected,
|
||||
onToggleProtection,
|
||||
commentsAllowed,
|
||||
trackChangesForced,
|
||||
protectActive,
|
||||
onProtectDoc,
|
||||
onCompare,
|
||||
}: ReviewTabProps) {
|
||||
const { t } = useI18n()
|
||||
@@ -632,7 +641,7 @@ export function ReviewTab({
|
||||
<div className="ribbon-group-items">
|
||||
<button
|
||||
className="rb-big"
|
||||
disabled={!hasDoc || !canComment || isProtected}
|
||||
disabled={!hasDoc || !canComment || (isProtected && !commentsAllowed)}
|
||||
data-tip={canComment ? t('ribbonNewCommentTip') : t('ribbonNewCommentSelectTip')}
|
||||
onClick={onNewComment}
|
||||
>
|
||||
@@ -662,7 +671,7 @@ export function ReviewTab({
|
||||
<div className="ribbon-group-items">
|
||||
<button
|
||||
className={`rb-big ${trackChanges ? 'active' : ''}`}
|
||||
disabled={!hasDoc || isProtected}
|
||||
disabled={!hasDoc || isProtected || trackChangesForced}
|
||||
data-tip={t('ribbonTrackChangesTip')}
|
||||
onClick={() => onTrackChanges(!trackChanges)}
|
||||
>
|
||||
@@ -710,7 +719,7 @@ export function ReviewTab({
|
||||
<div className="rb-split-wrap">
|
||||
<button
|
||||
className="rb-big"
|
||||
disabled={!hasDoc || revisionCount === 0 || isProtected}
|
||||
disabled={!hasDoc || revisionCount === 0 || isProtected || trackChangesForced}
|
||||
data-tip={t('ribbonAcceptTip', { count: revisionCount })}
|
||||
onClick={() => toggleDropdown(setDropdown, 'acceptRev')}
|
||||
>
|
||||
@@ -744,7 +753,7 @@ export function ReviewTab({
|
||||
<div className="rb-split-wrap">
|
||||
<button
|
||||
className="rb-big"
|
||||
disabled={!hasDoc || revisionCount === 0 || isProtected}
|
||||
disabled={!hasDoc || revisionCount === 0 || isProtected || trackChangesForced}
|
||||
data-tip={t('ribbonRejectTip', { count: revisionCount })}
|
||||
onClick={() => toggleDropdown(setDropdown, 'rejectRev')}
|
||||
>
|
||||
@@ -825,15 +834,15 @@ export function ReviewTab({
|
||||
<div className="ribbon-group">
|
||||
<div className="ribbon-group-items">
|
||||
<button
|
||||
className={`rb-big ${isProtected ? 'active' : ''}`}
|
||||
className={`rb-big ${protectActive ? 'active' : ''}`}
|
||||
disabled={!hasDoc}
|
||||
data-tip={isProtected ? t('ribbonStopProtectionTip') : t('ribbonRestrictEditingTip')}
|
||||
onClick={onToggleProtection}
|
||||
title={t('ribbonProtectDocTip')}
|
||||
onClick={onProtectDoc}
|
||||
>
|
||||
<span className="rb-big-icon">
|
||||
<IconLock size={BIG} />
|
||||
</span>
|
||||
<span>{t('ribbonRestrictEditing')}</span>
|
||||
<span>{t('ribbonProtectDoc')}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="ribbon-group-label">{t('ribbonGroupProtect')}</div>
|
||||
|
||||
@@ -24,6 +24,13 @@ export interface DocState {
|
||||
hash: string
|
||||
/** created from the built-in blank template (its numbering ids are known) */
|
||||
isBlank?: boolean
|
||||
/** desired open password is set for the next save; toggled via Review > Protect */
|
||||
encrypted?: boolean
|
||||
}
|
||||
|
||||
/** A restored recovery snapshot has not reached the original path yet. */
|
||||
export function openedFileStartsDirty(result: { recovered?: boolean }): boolean {
|
||||
return result.recovered === true
|
||||
}
|
||||
|
||||
/** Pending numbering definitions to append (saved via SaveOptions.numbering) */
|
||||
|
||||
@@ -125,6 +125,12 @@ export function docStyleCss(parsed: ParsedDocFull): string {
|
||||
if (docGridPitchPt(readSections(parsed)) != null) {
|
||||
rules.push(`.doc-page, .doc-page * { --doc-line-grid:${cssGridLineExpr()} }`)
|
||||
}
|
||||
// settings.xml w:autoHyphenation: Word breaks words at line ends document-wide.
|
||||
// Chromium hyphenates only under an explicit lang; file-actions sets it on the
|
||||
// editor root from docDefaults w:lang.
|
||||
if (parsed.autoHyphenation) {
|
||||
rules.push('.doc-page { hyphens:auto; -webkit-hyphens:auto }')
|
||||
}
|
||||
const dd = parsed.docDefaults
|
||||
// Word applies the w:default="1" paragraph style (Normal) to every paragraph
|
||||
// without a w:pStyle, so its display merges into the document baseline here
|
||||
@@ -164,6 +170,9 @@ export function docStyleCss(parsed: ParsedDocFull): string {
|
||||
if (color) decls.push(`color:#${color}`)
|
||||
if (normal?.bold ?? dd?.bold) decls.push('font-weight:600')
|
||||
if (normal?.italic ?? dd?.italic) decls.push('font-style:italic')
|
||||
// default style's w:jc reaches unstyled paragraphs (explicit w:jc and
|
||||
// [data-style] alignment both override this inherited baseline)
|
||||
if (normal?.align && normal.align !== 'left') decls.push(`text-align:${normal.align}`)
|
||||
const lh =
|
||||
cssLineHeight(normal?.lineRule, normal?.lineRawTwips, normal?.lineSpacing) ??
|
||||
cssLineHeight(dd?.lineRule, dd?.lineRawTwips, dd?.lineSpacing)
|
||||
@@ -198,6 +207,14 @@ export function docStyleCss(parsed: ParsedDocFull): string {
|
||||
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} }`)
|
||||
// whole-table rPr beats the document baseline inside the table (Word's
|
||||
// table-style layer sits above docDefaults/Normal for unstyled cell text)
|
||||
{
|
||||
const decls: string[] = []
|
||||
if (t.wholeTable?.sizeHalfPoints) decls.push(`font-size:${t.wholeTable.sizeHalfPoints / 2}pt`)
|
||||
if (t.wholeTable?.italic) decls.push('font-style:italic')
|
||||
if (decls.length > 0) rules.push(`${sel} td, ${sel} th { ${decls.join(';')} }`)
|
||||
}
|
||||
// band1 = first data row after the header → even nth-child when a header row exists
|
||||
if (t.band1Fill) {
|
||||
rules.push(`${sel} tr:nth-child(even) td { background:#${t.band1Fill} }`)
|
||||
@@ -210,21 +227,31 @@ export function docStyleCss(parsed: ParsedDocFull): 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 (t.firstRow.sizeHalfPoints) decls.push(`font-size:${t.firstRow.sizeHalfPoints / 2}pt`)
|
||||
if (decls.length > 0)
|
||||
rules.push(`${sel} tr:first-child td, ${sel} tr:first-child th { ${decls.join(';')} }`)
|
||||
}
|
||||
if (t.paraSpacing) {
|
||||
{
|
||||
// Word precedence: paragraph style (Normal) > table style pPr > docDefaults —
|
||||
// emit only the table-style values Normal doesn't declare itself
|
||||
const ps = t.paraSpacing
|
||||
const decls: string[] = []
|
||||
if (ps.beforeTwips !== undefined && normal?.spaceBeforeTwips === undefined)
|
||||
if (ps?.beforeTwips !== undefined && normal?.spaceBeforeTwips === undefined)
|
||||
decls.push(`margin-top:${cssGridSpacingPt(ps.beforeTwips / 20)}`)
|
||||
if (ps.afterTwips !== undefined && normal?.spaceAfterTwips === undefined)
|
||||
if (ps?.afterTwips !== undefined && normal?.spaceAfterTwips === undefined)
|
||||
decls.push(`margin-bottom:${cssGridSpacingPt(ps.afterTwips / 20)}`)
|
||||
const psLh = cssLineHeight(ps.lineRule, ps.lineRawTwips, ps.lineSpacing)
|
||||
const psLh = cssLineHeight(ps?.lineRule, ps?.lineRawTwips, ps?.lineSpacing)
|
||||
const normalLh = cssLineHeight(normal?.lineRule, normal?.lineRawTwips, normal?.lineSpacing)
|
||||
if (psLh && !normalLh) decls.push(`line-height:${psLh}`)
|
||||
if (t.paraJc && t.paraJc !== 'left' && t.paraJc !== 'start' && normal?.align === undefined) {
|
||||
const align =
|
||||
t.paraJc === 'center'
|
||||
? 'center'
|
||||
: t.paraJc === 'right' || t.paraJc === 'end'
|
||||
? 'right'
|
||||
: 'justify'
|
||||
decls.push(`text-align:${align}`)
|
||||
}
|
||||
if (decls.length > 0) {
|
||||
rules.push(
|
||||
`${sel} td p, ${sel} th p, ${sel} td .doc-li, ${sel} th .doc-li { ${decls.join(';')} }`,
|
||||
@@ -276,6 +303,8 @@ export function docStyleCss(parsed: ParsedDocFull): string {
|
||||
if (d.indentFirstLineTwips)
|
||||
decls.push(`text-indent:${(d.indentFirstLineTwips / 20).toFixed(1)}pt`)
|
||||
if (d.align) decls.push(`text-align:${d.align}`)
|
||||
// style-level paragraph shading (explicit pPr w:shd is inline style and wins)
|
||||
if (d.shadingFill) decls.push(`background-color:#${d.shadingFill}`)
|
||||
// the static sheet guesses italic for h4-h6 (Word's built-in defaults);
|
||||
// a real style definition without w:i means upright
|
||||
if (info.headingLevel && info.headingLevel >= 4 && !d.italic) decls.push('font-style:normal')
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Word keeps an empty paragraph's pending format on its paragraph mark: type
|
||||
* in Calibri, press Enter, arrow up and back — typing still produces Calibri.
|
||||
* ProseMirror instead keeps the pending format in transient storedMarks,
|
||||
* which any selection move clears; the caret then re-derives marks from
|
||||
* adjacent text, and an empty paragraph has none — so navigation silently
|
||||
* reset new paragraphs to the document default (alpha ledger r114).
|
||||
*
|
||||
* This extension gives empty blocks a pilcrow memory via the shared
|
||||
* `caretMarks` attr: while the caret sits in an empty block *with* stored
|
||||
* marks, the marks are stamped onto the block; when the caret re-enters the
|
||||
* block bare (storedMarks === null, i.e. cleared by navigation — an explicit
|
||||
* empty array from a user toggle is respected), the stamp is restored as
|
||||
* storedMarks. Session-only: the attr is not persisted to the file.
|
||||
*/
|
||||
import { Extension } from '@tiptap/core'
|
||||
import type { Mark } from '@tiptap/pm/model'
|
||||
import { Plugin, PluginKey } from '@tiptap/pm/state'
|
||||
|
||||
/// Only pending FORMATTING survives; structural/annotation marks (comments,
|
||||
/// links, revisions) must never re-materialize from a caret memory.
|
||||
const FORMAT_MARKS = new Set(['bold', 'italic', 'underline', 'strike', 'docTextStyle'])
|
||||
|
||||
const serializeMarks = (marks: readonly Mark[]): string | null => {
|
||||
const kept = marks
|
||||
.filter((mark) => FORMAT_MARKS.has(mark.type.name))
|
||||
.map((mark) => ({ type: mark.type.name, attrs: mark.attrs }))
|
||||
return kept.length > 0 ? JSON.stringify(kept) : null
|
||||
}
|
||||
|
||||
export const CaretMarksMemory = Extension.create({
|
||||
name: 'caretMarksMemory',
|
||||
addProseMirrorPlugins() {
|
||||
return [
|
||||
new Plugin({
|
||||
key: new PluginKey('caretMarksMemory'),
|
||||
appendTransaction: (_transactions, _oldState, newState) => {
|
||||
const { selection, storedMarks, schema } = newState
|
||||
if (!selection.empty) return null
|
||||
const $from = selection.$from
|
||||
const block = $from.parent
|
||||
if (!block.isTextblock || block.content.size > 0) return null
|
||||
if (!('caretMarks' in block.attrs)) return null
|
||||
const blockPos = $from.before($from.depth)
|
||||
if (storedMarks !== null) {
|
||||
// Caret holds pending marks (fresh Enter split, or a ribbon
|
||||
// format on the empty block): stamp them so they survive
|
||||
// navigation. Kept out of history — this is caret bookkeeping,
|
||||
// not a user edit to undo.
|
||||
const snapshot = serializeMarks(storedMarks)
|
||||
if (snapshot === block.attrs.caretMarks) return null
|
||||
return newState.tr
|
||||
.setNodeMarkup(blockPos, undefined, { ...block.attrs, caretMarks: snapshot })
|
||||
.setStoredMarks(storedMarks)
|
||||
.setMeta('addToHistory', false)
|
||||
}
|
||||
// Bare re-entry: navigation cleared the stored marks — restore the
|
||||
// block's pilcrow memory.
|
||||
const stamped = block.attrs.caretMarks as string | null
|
||||
if (!stamped) return null
|
||||
try {
|
||||
const parsed = JSON.parse(stamped) as { type: string; attrs: Record<string, unknown> }[]
|
||||
const marks = parsed.flatMap((entry) => {
|
||||
const type = schema.marks[entry.type]
|
||||
return type && FORMAT_MARKS.has(entry.type) ? [type.create(entry.attrs)] : []
|
||||
})
|
||||
if (marks.length === 0) return null
|
||||
return newState.tr.setStoredMarks(marks)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
}),
|
||||
]
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
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>('columnLayout')
|
||||
|
||||
/**
|
||||
* Mixed-column canvas layout (documents whose sections disagree on column
|
||||
* count/width, so the uniform whole-page CSS multicol path can't apply).
|
||||
*
|
||||
* The engine keeps its 1-D single-flow virtual coordinates; this extension only
|
||||
* *paints* the flow into columns: each block in a multi-column region gets its
|
||||
* section's column width plus a constant per-column translate, and blocks of
|
||||
* later regions on the same page translate up over the space the columns
|
||||
* vacated (the page gap below pulls the next page up by the same amount).
|
||||
* Decorations are visual-only; measurement runs in the `.measuring-columns`
|
||||
* state, whose CSS neutralizes the transforms (widths stay — the engine's line
|
||||
* boxes must reflect column wrapping).
|
||||
*
|
||||
* v1 granularity: a block is placed whole into the column containing its top;
|
||||
* a block the engine split across columns paints overflowing its column bottom.
|
||||
*/
|
||||
export const ColumnLayoutExtension = Extension.create({
|
||||
name: 'columnLayout',
|
||||
|
||||
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 ColumnBlockSpec {
|
||||
/** top-level block element (same anchoring as page gaps) */
|
||||
el: HTMLElement
|
||||
/** column width (px); absent for single-column regions (natural width) */
|
||||
widthPx?: number
|
||||
/** translate; dy < 0 pulls content up over vacated column space */
|
||||
dx: number
|
||||
dy: number
|
||||
}
|
||||
|
||||
/** Rebuild the column-layout decorations (an empty list clears them). */
|
||||
export function setColumnLayout(view: EditorView, specs: ColumnBlockSpec[]): void {
|
||||
const decos: Decoration[] = []
|
||||
const styleOf = new Map<HTMLElement, string>()
|
||||
for (const spec of specs) {
|
||||
const style =
|
||||
(spec.widthPx !== undefined ? `--col-w:${round2(spec.widthPx)}px;` : '') +
|
||||
`--col-dx:${round2(spec.dx)}px;--col-dy:${round2(spec.dy)}px`
|
||||
styleOf.set(spec.el, style)
|
||||
let from: number
|
||||
let to: number
|
||||
try {
|
||||
const $inside = view.state.doc.resolve(view.posAtDOM(spec.el, 0))
|
||||
from = $inside.before(1)
|
||||
to = $inside.after(1)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
decos.push(
|
||||
Decoration.node(from, to, { class: 'doc-col-block', style }, { key: `col-${style}` }),
|
||||
)
|
||||
}
|
||||
const next = DecorationSet.create(view.state.doc, decos)
|
||||
const prev = key.getState(view.state)
|
||||
if (!prev || !sameCols(prev, next))
|
||||
view.dispatch(view.state.tr.setMeta(key, next).setMeta('addToHistory', false))
|
||||
// custom NodeViews (protected blocks etc.) don't apply node decorations — patch
|
||||
// their DOM directly, observer paused so PM never re-parses the mutation (same
|
||||
// technique as the phantom-rowspan sync). Re-applied by every remeasure pass.
|
||||
const obs = (view as unknown as { domObserver?: { stop(): void; start(): void } }).domObserver
|
||||
obs?.stop()
|
||||
try {
|
||||
for (const el of Array.from(
|
||||
view.dom.querySelectorAll<HTMLElement>('[data-col-patch]'),
|
||||
) as HTMLElement[]) {
|
||||
if (styleOf.has(el)) continue
|
||||
el.removeAttribute('data-col-patch')
|
||||
el.classList.remove('doc-col-block')
|
||||
for (const p of ['--col-w', '--col-dx', '--col-dy']) el.style.removeProperty(p)
|
||||
}
|
||||
for (const [el, style] of styleOf) {
|
||||
if (el.classList.contains('doc-col-block') && !el.hasAttribute('data-col-patch')) continue
|
||||
el.setAttribute('data-col-patch', '1')
|
||||
el.classList.add('doc-col-block')
|
||||
const parts = style.split(';')
|
||||
for (const p of ['--col-w', '--col-dx', '--col-dy']) el.style.removeProperty(p)
|
||||
for (const part of parts) {
|
||||
const i = part.indexOf(':')
|
||||
if (i > 0) el.style.setProperty(part.slice(0, i), part.slice(i + 1))
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
obs?.start()
|
||||
}
|
||||
}
|
||||
|
||||
const round2 = (n: number) => Math.round(n * 100) / 100
|
||||
|
||||
function sameCols(a: DecorationSet, b: DecorationSet): boolean {
|
||||
const fa = a.find()
|
||||
const fb = b.find()
|
||||
if (fa.length !== fb.length) return false
|
||||
const sig = (d: Decoration) => `${d.from}-${d.to}-${(d.spec as { key?: string }).key ?? ''}`
|
||||
const sa = fa.map(sig).sort()
|
||||
const sb = fb.map(sig).sort()
|
||||
return sa.every((s, i) => s === sb[i])
|
||||
}
|
||||
@@ -48,18 +48,36 @@ export function removeCommentFromDoc(editor: Editor, id: string): void {
|
||||
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 (node.isText) {
|
||||
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(' ') }))
|
||||
return
|
||||
}
|
||||
|
||||
// Cross-paragraph ranges live on block attrs rather than text marks.
|
||||
// Clear both endpoints in the same transaction so a deleted comment can
|
||||
// never be serialized back as orphaned commentRangeStart/End markers.
|
||||
const starts = Array.isArray(node.attrs?.commentStarts)
|
||||
? (node.attrs.commentStarts as string[])
|
||||
: []
|
||||
const ends = Array.isArray(node.attrs?.commentEnds) ? (node.attrs.commentEnds as string[]) : []
|
||||
if (!starts.includes(id) && !ends.includes(id)) return
|
||||
const remainingStarts = starts.filter((value) => value !== id)
|
||||
const remainingEnds = ends.filter((value) => value !== id)
|
||||
tr.setNodeMarkup(pos, undefined, {
|
||||
...node.attrs,
|
||||
commentStarts: remainingStarts.length > 0 ? remainingStarts : null,
|
||||
commentEnds: remainingEnds.length > 0 ? remainingEnds : null,
|
||||
})
|
||||
})
|
||||
if (tr.steps.length > 0) editor.view.dispatch(tr)
|
||||
}
|
||||
|
||||
@@ -407,6 +407,7 @@ function blockToPmNode(
|
||||
commentStarts: block.commentStarts ?? null,
|
||||
commentEnds: block.commentEnds ?? null,
|
||||
pPrChange: block.pPrChangeInfo ? JSON.stringify(block.pPrChangeInfo) : null,
|
||||
paraMarkDel: block.paraMarkDel ? JSON.stringify(block.paraMarkDel) : null,
|
||||
blockRevision: block.blockRevision ?? null,
|
||||
...formatAttrs(block.format),
|
||||
},
|
||||
@@ -427,6 +428,7 @@ function blockToPmNode(
|
||||
commentStarts: block.commentStarts ?? null,
|
||||
commentEnds: block.commentEnds ?? null,
|
||||
pPrChange: block.pPrChangeInfo ? JSON.stringify(block.pPrChangeInfo) : null,
|
||||
paraMarkDel: block.paraMarkDel ? JSON.stringify(block.paraMarkDel) : null,
|
||||
blockRevision: block.blockRevision ?? null,
|
||||
...formatAttrs(block.format),
|
||||
},
|
||||
@@ -446,6 +448,7 @@ function blockToPmNode(
|
||||
sdtShell: block.sdtShell ? JSON.stringify(block.sdtShell) : null,
|
||||
moveRevision: block.moveRevision ?? null,
|
||||
pPrChange: block.pPrChangeInfo ? JSON.stringify(block.pPrChangeInfo) : null,
|
||||
paraMarkDel: block.paraMarkDel ? JSON.stringify(block.paraMarkDel) : null,
|
||||
blockRevision: block.blockRevision ?? null,
|
||||
...formatAttrs(block.format),
|
||||
},
|
||||
@@ -492,6 +495,7 @@ function blockToPmNode(
|
||||
imageRotDeg: block.imageRotDeg ?? null,
|
||||
imageFlipH: block.imageFlipH ?? false,
|
||||
imageFlipV: block.imageFlipV ?? false,
|
||||
imageBorder: block.imageBorder ?? null,
|
||||
table: displayTable(block.table ?? null, rowCapTwips, budget),
|
||||
fieldDisplay: block.fieldDisplay ?? null,
|
||||
diagramDisplay: block.diagramDisplay ?? null,
|
||||
@@ -580,6 +584,16 @@ export function tableModelToPmNode(
|
||||
: model.colWidthsPct?.map((width) => Math.max(24, Math.round(width * 6.24)))
|
||||
const hasHeaderRow =
|
||||
model.rows.length > 1 && model.rows[0].every((cell) => cell.bold || cell.fill !== undefined)
|
||||
// w:tblpPr tables taller than any single page cannot float: Word flows/splits
|
||||
// them across pages, while the zero-flow-height float model collapses the
|
||||
// whole document to one page (137-row glossary, LO batch2 sample 0219).
|
||||
// Minimum height = one 12pt line per row; 12960 twips ≈ the shortest common
|
||||
// usable page (Letter, 1in margins).
|
||||
const minHeightTwips = model.rows.reduce(
|
||||
(sum, _row, i) => sum + Math.max(model.rowHeightsTwips?.[i] ?? 0, 240),
|
||||
0,
|
||||
)
|
||||
const tblFloat = minHeightTwips > 12960 ? null : (model.floatSide ?? null)
|
||||
const table: PmNode = {
|
||||
type: 'docTable',
|
||||
attrs: {
|
||||
@@ -594,6 +608,7 @@ export function tableModelToPmNode(
|
||||
cellMar: model.cellMarTwips ?? null,
|
||||
borders: model.borders ?? null,
|
||||
tblAlign: model.align ?? null,
|
||||
tblFloat,
|
||||
indentTwips: model.indentTwips ?? null,
|
||||
tblStyleId: model.tblStyleId ?? null,
|
||||
bidiVisual: model.bidiVisual ?? false,
|
||||
@@ -953,10 +968,11 @@ export function runsToInline(runs: Run[]): PmNode[] {
|
||||
continue
|
||||
}
|
||||
const marks = runMarks(run)
|
||||
// \n = soft line break, \f = in-paragraph page break (w:br w:type="page")
|
||||
for (const segment of run.text.split(/([\n\f])/)) {
|
||||
// \n = soft line break, \f = in-paragraph page break, \v = column break
|
||||
for (const segment of run.text.split(/([\n\f\v])/)) {
|
||||
if (segment === '\n') nodes.push({ type: 'hardBreak' })
|
||||
else if (segment === '\f') nodes.push({ type: 'hardBreak', attrs: { pageBreak: true } })
|
||||
else if (segment === '\v') nodes.push({ type: 'hardBreak', attrs: { colBreak: true } })
|
||||
else if (segment !== '') {
|
||||
nodes.push({ type: 'text', text: segment, ...(marks.length > 0 ? { marks } : {}) })
|
||||
}
|
||||
@@ -974,6 +990,8 @@ export function runsToInline(runs: Run[]): PmNode[] {
|
||||
wrap: run.image.wrap ?? null,
|
||||
offsetXEmu: run.image.offsetXEmu ?? null,
|
||||
offsetYEmu: run.image.offsetYEmu ?? null,
|
||||
border: run.image.border ?? null,
|
||||
lineCenterV: run.image.lineCenterV ?? false,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -2047,7 +2065,7 @@ export function inlineToRuns(content: PmNode[]): Run[] {
|
||||
const runs: Run[] = []
|
||||
for (const node of content) {
|
||||
if (node.type === 'hardBreak') {
|
||||
const ch = node.attrs?.pageBreak ? '\f' : '\n'
|
||||
const ch = node.attrs?.pageBreak ? '\f' : node.attrs?.colBreak ? '\v' : '\n'
|
||||
const prev = runs[runs.length - 1]
|
||||
const prevAtomic =
|
||||
prev && (prev.noteRef || prev.xeTerm !== undefined || prev.math || prev.ruby || prev.image)
|
||||
|
||||
@@ -138,9 +138,20 @@ export const ResolvedCommentsExtension = Extension.create({
|
||||
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) */
|
||||
/** fallback when the document's settings.xml declares no w:defaultTabStop (Word: 0.5") */
|
||||
const DEFAULT_TAB_TWIPS = 720
|
||||
|
||||
export interface TabStopStorage {
|
||||
/** settings.xml w:defaultTabStop (twips); 0 = zero-width default tabs (Word barely advances) */
|
||||
defaultTabStopTwips: number | null
|
||||
}
|
||||
|
||||
declare module '@tiptap/core' {
|
||||
interface Storage {
|
||||
tabStops: TabStopStorage
|
||||
}
|
||||
}
|
||||
|
||||
interface MeasuredTab {
|
||||
pos: number
|
||||
/** CSS tab-size (px) for this tab's decoration span */
|
||||
@@ -198,7 +209,10 @@ class TabLayoutView {
|
||||
this.measure()
|
||||
}
|
||||
|
||||
constructor(private view: EditorView) {
|
||||
constructor(
|
||||
private view: EditorView,
|
||||
private storage: TabStopStorage,
|
||||
) {
|
||||
this.measure()
|
||||
document.fonts?.addEventListener('loadingdone', this.onFontsLoaded)
|
||||
if (typeof ResizeObserver !== 'undefined') {
|
||||
@@ -396,8 +410,14 @@ class TabLayoutView {
|
||||
val = next.val
|
||||
leader = next.leader
|
||||
} else {
|
||||
const grid = DEFAULT_TAB_TWIPS / TWIPS_PER_PX
|
||||
target = (Math.floor((x + 0.5) / grid) + 1) * grid
|
||||
const gridTwips = this.storage.defaultTabStopTwips ?? DEFAULT_TAB_TWIPS
|
||||
if (gridTwips > 0) {
|
||||
const grid = gridTwips / TWIPS_PER_PX
|
||||
target = (Math.floor((x + 0.5) / grid) + 1) * grid
|
||||
} else {
|
||||
// defaultTabStop 0: Word advances the caret imperceptibly (tdf#168607)
|
||||
target = x + 0.5
|
||||
}
|
||||
}
|
||||
|
||||
// Width of the text between this tab and the next tab (or paragraph
|
||||
@@ -448,7 +468,11 @@ class TabLayoutView {
|
||||
|
||||
export const TabStopExtension = Extension.create({
|
||||
name: 'tabStops',
|
||||
addStorage() {
|
||||
return { defaultTabStopTwips: null } as TabStopStorage
|
||||
},
|
||||
addProseMirrorPlugins() {
|
||||
const storage = this.storage as TabStopStorage
|
||||
return [
|
||||
new Plugin({
|
||||
key: tabStopPluginKey,
|
||||
@@ -465,7 +489,7 @@ export const TabStopExtension = Extension.create({
|
||||
return this.getState(state)
|
||||
},
|
||||
},
|
||||
view: (view) => new TabLayoutView(view),
|
||||
view: (view) => new TabLayoutView(view, storage),
|
||||
}),
|
||||
]
|
||||
},
|
||||
@@ -502,6 +526,45 @@ export const DropCapExtension = Extension.create({
|
||||
},
|
||||
})
|
||||
|
||||
// ---- whitespace-only run line height (Word ignores their font size) ----
|
||||
|
||||
const wsRunPluginKey = new PluginKey<DecorationSet>('wsRunLineHeight')
|
||||
|
||||
/**
|
||||
* Word ignores the font size of whitespace-only runs (spaces/tabs) for line
|
||||
* height (tdf#137335): the oversized whitespace keeps its advance but the line
|
||||
* box stays governed by the text portions (strut on blank lines). Recomputed
|
||||
* from the live text so editing into such a run drops the suppression, and a
|
||||
* character style's font size is covered the same as a direct w:sz.
|
||||
*/
|
||||
export const WsRunLineHeightExtension = Extension.create({
|
||||
name: 'wsRunLineHeight',
|
||||
addProseMirrorPlugins() {
|
||||
return [
|
||||
new Plugin({
|
||||
key: wsRunPluginKey,
|
||||
props: {
|
||||
decorations(state) {
|
||||
const decos: Decoration[] = []
|
||||
state.doc.descendants((node, pos) => {
|
||||
if (!node.isText || !node.text) return
|
||||
if (!/^[ \t]+$/.test(node.text)) return
|
||||
// only runs with a font-size source can inflate the line
|
||||
const styled = node.marks.some(
|
||||
(m) =>
|
||||
m.type.name === 'docTextStyle' && (m.attrs.sizeHalfPoints || m.attrs.styleId),
|
||||
)
|
||||
if (!styled) return
|
||||
decos.push(Decoration.inline(pos, pos + node.nodeSize, { class: 'doc-ws-run' }))
|
||||
})
|
||||
return decos.length > 0 ? DecorationSet.create(state.doc, decos) : DecorationSet.empty
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
},
|
||||
})
|
||||
|
||||
// ---- adjacent-paragraph border merging (Word border groups) ----
|
||||
|
||||
const paraBorderMergePluginKey = new PluginKey<DecorationSet>('paraBorderMerge')
|
||||
@@ -672,6 +735,46 @@ export const MoveRevisionExtension = Extension.create({
|
||||
},
|
||||
})
|
||||
|
||||
// ---- deleted paragraph mark (w:pPr/w:rPr/w:del) collapse extension ----
|
||||
|
||||
const paraMarkDelPluginKey = new PluginKey<DecorationSet>('paraMarkDel')
|
||||
|
||||
/**
|
||||
* A paragraph whose mark is a tracked deletion and whose inline content is all
|
||||
* deleted leaves no trace in Word's All Markup view (the text lives in a margin
|
||||
* balloon); collapse it so pagination matches. Partially deleted paragraphs
|
||||
* (Word joins them into the next one) keep their height — approximate, but the
|
||||
* remaining text still occupies a line either way.
|
||||
*/
|
||||
export const ParaMarkDelExtension = Extension.create({
|
||||
name: 'paraMarkDel',
|
||||
addProseMirrorPlugins() {
|
||||
return [
|
||||
new Plugin({
|
||||
key: paraMarkDelPluginKey,
|
||||
props: {
|
||||
decorations(state) {
|
||||
const decos: Decoration[] = []
|
||||
state.doc.forEach((node, offset) => {
|
||||
if (!node.attrs?.paraMarkDel) return
|
||||
let visible = false
|
||||
node.forEach((child) => {
|
||||
if (!child.marks.some((m) => m.type.name === 'del')) visible = true
|
||||
})
|
||||
decos.push(
|
||||
Decoration.node(offset, offset + node.nodeSize, {
|
||||
class: visible ? 'doc-para-mark-del' : 'doc-para-mark-del doc-para-del-collapse',
|
||||
}),
|
||||
)
|
||||
})
|
||||
return decos.length > 0 ? DecorationSet.create(state.doc, decos) : DecorationSet.empty
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
},
|
||||
})
|
||||
|
||||
// ---- pPrChange (tracked paragraph format) rendering extension ----
|
||||
|
||||
const pPrChangePluginKey = new PluginKey<DecorationSet>('pPrChange')
|
||||
|
||||
@@ -68,6 +68,8 @@ import { symbolFontCovers } from '../font-check'
|
||||
import { dropActiveSubEditor, notifySubEditorState, setActiveSubEditor } from './active-editor'
|
||||
import { paraBorderCss } from './hf-dom'
|
||||
import { PaginationGapsExtension } from './pagination-gaps'
|
||||
import { CaretMarksMemory } from './caret-marks'
|
||||
import { ColumnLayoutExtension } from './column-layout'
|
||||
import { TableHandle } from './table-handle'
|
||||
import { TrackChangesExtension } from './revisions'
|
||||
import { inlineToRuns, runsToInline, textboxParaSignature, type PmNode as PmJson } from './convert'
|
||||
@@ -113,11 +115,13 @@ import {
|
||||
MoveRevisionExtension,
|
||||
PPrChangeExtension,
|
||||
ParaBorderMergeExtension,
|
||||
ParaMarkDelExtension,
|
||||
PendingCommentHighlightExtension,
|
||||
ResolvedCommentsExtension,
|
||||
SdtExtension,
|
||||
SearchHighlightExtension,
|
||||
TabStopExtension,
|
||||
WsRunLineHeightExtension,
|
||||
} from './decoration-extensions'
|
||||
import { AutoDirectionExtension } from './direction'
|
||||
export * from './marks'
|
||||
@@ -169,8 +173,15 @@ const anchorAttrs = {
|
||||
moveRevision: { default: null as string | null },
|
||||
/** JSON {author,date?,id?} when the paragraph has a pPrChange tracked format change */
|
||||
pPrChange: { default: null as string | null },
|
||||
/** JSON {author,date?,id?} when the paragraph mark is a tracked deletion (w:pPr/w:rPr/w:del) */
|
||||
paraMarkDel: { default: null as string | null },
|
||||
/** top-level insertion/deletion revision ({kind,author,date?}) */
|
||||
blockRevision: { default: null as Record<string, string> | null },
|
||||
/** JSON marks snapshot for an empty block's caret (Word's pilcrow
|
||||
formatting): stamped while the caret holds stored marks in an empty
|
||||
block, restored as storedMarks when the caret re-enters bare — arrow
|
||||
navigation must not drop the pending format (alpha ledger r114) */
|
||||
caretMarks: { default: null as string | null },
|
||||
}
|
||||
|
||||
/** Max explicit run size (half-points) when *every* text child declares one, else null.
|
||||
@@ -529,6 +540,10 @@ export const DocInlineImage = Node.create({
|
||||
wrap: { default: null as string | null },
|
||||
offsetXEmu: { default: null as number | null },
|
||||
offsetYEmu: { default: null as number | null },
|
||||
/** picture outline (pic:spPr a:ln solid fill, display-only) */
|
||||
border: { default: null as { color: string; widthPt: number } | null },
|
||||
/** positionV line/center: the picture centers on its anchor line (display only) */
|
||||
lineCenterV: { default: false },
|
||||
}
|
||||
},
|
||||
parseHTML() {
|
||||
@@ -543,6 +558,13 @@ export const DocInlineImage = Node.create({
|
||||
const w = Number(node.attrs.widthPx)
|
||||
const h = Number(node.attrs.heightPx)
|
||||
if (w > 0) attrs.style = `width:${w}px;${h > 0 ? `height:${h}px` : 'height:auto'}`
|
||||
const ib = node.attrs.border as { color: string; widthPt: number } | null
|
||||
if (ib) {
|
||||
// picture outline (document data, not chrome)
|
||||
attrs.style =
|
||||
`${attrs.style ? `${attrs.style};` : ''}border:${((ib.widthPt * 96) / 72).toFixed(1)}px ` +
|
||||
`solid #${String(ib.color).replace(/[^0-9A-Fa-f]/g, '')}`
|
||||
}
|
||||
const wrap = node.attrs.wrap as string | null
|
||||
if (wrap === 'front' || wrap === 'behind') {
|
||||
// no-wrap / behind-text anchor: absolute overlay at the anchor offset from
|
||||
@@ -563,6 +585,11 @@ export const DocInlineImage = Node.create({
|
||||
// square/tight/through wrap → real CSS float so the surrounding text wraps;
|
||||
// topBottom → block line of its own
|
||||
if (wrap) attrs.class += ` doc-inline-img--wrap-${wrap}`
|
||||
// positionV line/center: lift so the picture centers on the anchor line
|
||||
// (0.75em ≈ half a single-spaced line) instead of hanging below it
|
||||
if (node.attrs.lineCenterV && h > 0) {
|
||||
attrs.style = `${attrs.style ?? ''};margin-top:calc(0.75em - ${(h / 2).toFixed(1)}px)`
|
||||
}
|
||||
return ['img', attrs]
|
||||
},
|
||||
})
|
||||
@@ -654,13 +681,23 @@ export const DocHardBreak = Node.create({
|
||||
return {
|
||||
// in-paragraph page break (w:br w:type="page"): the pagination engine breaks after the containing block
|
||||
pageBreak: { default: false },
|
||||
// column break (w:br w:type="column"): next column, or next page in a single-column section
|
||||
colBreak: { default: false },
|
||||
}
|
||||
},
|
||||
parseHTML() {
|
||||
return [{ tag: 'br.doc-page-br', attrs: { pageBreak: true } }, { tag: 'br' }]
|
||||
return [
|
||||
{ tag: 'br.doc-page-br', attrs: { pageBreak: true } },
|
||||
{ tag: 'br.doc-col-br', attrs: { colBreak: true } },
|
||||
{ tag: 'br' },
|
||||
]
|
||||
},
|
||||
renderHTML({ node }) {
|
||||
return node.attrs.pageBreak ? ['br', { class: 'doc-page-br' }] : ['br']
|
||||
return node.attrs.pageBreak
|
||||
? ['br', { class: 'doc-page-br' }]
|
||||
: node.attrs.colBreak
|
||||
? ['br', { class: 'doc-col-br' }]
|
||||
: ['br']
|
||||
},
|
||||
addKeyboardShortcuts() {
|
||||
return {
|
||||
@@ -1341,6 +1378,7 @@ export const DocTable = Node.create({
|
||||
cellMar: { default: null as Record<string, number> | null },
|
||||
borders: { default: null as Record<string, unknown> | null },
|
||||
tblAlign: { default: null as string | null },
|
||||
tblFloat: { default: null as string | null },
|
||||
indentTwips: { default: null as number | null },
|
||||
tblStyleId: { default: null as string | null },
|
||||
/** SDT shell JSON when the table is a content-control member (chrome hit-testing) */
|
||||
@@ -1359,6 +1397,8 @@ export const DocTable = Node.create({
|
||||
const attrs: Record<string, string> = { class: 'doc-table' }
|
||||
if (node.attrs.docxIndex !== null) attrs['data-idx'] = String(node.attrs.docxIndex)
|
||||
if (node.attrs.tblStyleId) attrs['data-tbl-style'] = String(node.attrs.tblStyleId)
|
||||
const tblFloated = node.attrs.tblFloat === 'left' || node.attrs.tblFloat === 'right'
|
||||
if (tblFloated) attrs.class += ` doc-table-float-${node.attrs.tblFloat}`
|
||||
if (node.attrs.bidiVisual) attrs.dir = 'rtl'
|
||||
const styles: string[] = []
|
||||
let centerMargin: string | null = null
|
||||
@@ -1371,13 +1411,14 @@ export const DocTable = Node.create({
|
||||
// left-aligned ones spill right; indent comes out of the spill allowance
|
||||
else if (node.attrs.widthPx) {
|
||||
const widthPx = Number(node.attrs.widthPx)
|
||||
if (node.attrs.tblAlign === 'center') {
|
||||
if (node.attrs.tblAlign === 'center' && !tblFloated) {
|
||||
const paper =
|
||||
'calc(100% + var(--doc-margin-left,var(--doc-margin-right,0px)) + var(--doc-margin-right,0px))'
|
||||
styles.push(`width:min(${widthPx}px,${paper})`)
|
||||
centerMargin = `margin-left:calc((100% - min(${widthPx}px,${paper}))/2)`
|
||||
} else {
|
||||
const indented = node.attrs.tblAlign !== 'right' && Number(node.attrs.indentTwips) > 0
|
||||
const indented =
|
||||
!tblFloated && node.attrs.tblAlign !== 'right' && Number(node.attrs.indentTwips) > 0
|
||||
const indentPx = indented ? Number(node.attrs.indentTwips) / 15 : 0
|
||||
const spill = indentPx
|
||||
? `calc(100% + var(--doc-margin-right,0px) - ${indentPx.toFixed(1)}px)`
|
||||
@@ -1388,7 +1429,11 @@ export const DocTable = Node.create({
|
||||
const pad = cellPadCss(node.attrs.cellMar as Record<string, number> | null)
|
||||
if (pad) styles.push(`--doc-cell-pad:${pad}`)
|
||||
styles.push(...tableBordersCss(node.attrs.borders as TableBordersAttr | null))
|
||||
if (node.attrs.tblAlign === 'center') {
|
||||
// w:tblpPr positioning supersedes w:jc / w:tblInd: alignment or indent
|
||||
// margins would override the float stylesheet's wrap gaps
|
||||
if (tblFloated) {
|
||||
// no alignment/indent margins
|
||||
} else if (node.attrs.tblAlign === 'center') {
|
||||
if (centerMargin) styles.push(centerMargin)
|
||||
else styles.push('margin-left:auto', 'margin-right:auto')
|
||||
} else if (node.attrs.tblAlign === 'right') styles.push('margin-left:auto')
|
||||
@@ -1825,6 +1870,8 @@ export const DocProtected = Node.create({
|
||||
imageRotDeg: { default: null as number | null },
|
||||
imageFlipH: { default: false },
|
||||
imageFlipV: { default: false },
|
||||
/** picture outline (pic:spPr a:ln solid fill, display-only) */
|
||||
imageBorder: { default: null as { color: string; widthPt: number } | null },
|
||||
/** replacement bytes for an original image (crop/background removal/replace):
|
||||
* the drawing XML — and with it docxIndex, wrap and position — survives */
|
||||
imageReplace: { default: null as { base64: string; mime: string } | null },
|
||||
@@ -1925,6 +1972,28 @@ export const DocProtected = Node.create({
|
||||
*/
|
||||
function diagramSpecOf(diagram: DiagramDisplay): DomSpec {
|
||||
const shapeSpecs: DomSpec[] = diagram.shapes.map((s) => {
|
||||
// connectors (prst=line, zero cx or cy) render as solid rules along the axis
|
||||
if (s.lnHex && (s.wPx <= 0 || s.hPx <= 0)) {
|
||||
const w = Math.max(1, s.lnWPx ?? 1)
|
||||
const style = (
|
||||
s.hPx <= 0
|
||||
? [
|
||||
`left:${s.xPx}px`,
|
||||
`top:${(s.yPx - w / 2).toFixed(1)}px`,
|
||||
`width:${s.wPx}px`,
|
||||
`height:${w}px`,
|
||||
]
|
||||
: [
|
||||
`left:${(s.xPx - w / 2).toFixed(1)}px`,
|
||||
`top:${s.yPx}px`,
|
||||
`width:${w}px`,
|
||||
`height:${s.hPx}px`,
|
||||
]
|
||||
)
|
||||
.concat(`background:#${s.lnHex}`)
|
||||
.join(';')
|
||||
return ['span', { class: 'doc-diagram-shape', style }] as DomSpec
|
||||
}
|
||||
const radius =
|
||||
s.prst === 'ellipse' || s.prst === 'circle'
|
||||
? '50%'
|
||||
@@ -1938,6 +2007,9 @@ function diagramSpecOf(diagram: DiagramDisplay): DomSpec {
|
||||
`height:${s.hPx}px`,
|
||||
`border-radius:${radius}`,
|
||||
s.fillHex ? `background:#${s.fillHex}` : '',
|
||||
s.lnHex
|
||||
? `border:${Math.max(1, s.lnWPx ?? 1)}px solid #${s.lnHex};box-sizing:border-box`
|
||||
: '',
|
||||
s.rotDeg ? `transform:rotate(${s.rotDeg}deg)` : '',
|
||||
s.fontSizePt ? `font-size:${s.fontSizePt}pt` : '',
|
||||
s.textColorHex ? `color:#${s.textColorHex}` : '',
|
||||
@@ -2106,23 +2178,31 @@ function protectedDomSpec(node: PmNode): DomSpec {
|
||||
attrs['style'] = `text-align:${imageAlign}`
|
||||
}
|
||||
if (imageWrap) attrs.class += ` img-wrap-${String(imageWrap)}`
|
||||
// no-wrap / behind-text floats: approximate the anchor position — margin
|
||||
// alignment via text-align, numeric posOffset via a transform on the INNER
|
||||
// wrap (the outer block's rect feeds pagination measurement, which must
|
||||
// stay at the flow position; transforms leak into getBoundingClientRect)
|
||||
// no-wrap / behind-text anchors leave the flow like floating textboxes:
|
||||
// zero-height wrapper (doc-img-float), absolutely positioned inner wrap
|
||||
// (Word overlays them on the text instead of reserving a line)
|
||||
let imgWrapTransform = ''
|
||||
let imgFloatPos = ''
|
||||
if (imageWrap === 'front' || imageWrap === 'behind') {
|
||||
attrs.class += ' doc-img-float'
|
||||
const posH = node.attrs.imagePosH
|
||||
if ((posH === 'center' || posH === 'right') && !attrs['style']) {
|
||||
attrs['style'] = `text-align:${String(posH)}`
|
||||
}
|
||||
const tx =
|
||||
node.attrs.imageOffsetXEmu != null ? Number(node.attrs.imageOffsetXEmu) / EMU_PER_PX : 0
|
||||
const ty =
|
||||
node.attrs.imageOffsetYEmu != null ? Number(node.attrs.imageOffsetYEmu) / EMU_PER_PX : 0
|
||||
if (tx !== 0 || ty !== 0) {
|
||||
imgWrapTransform = `transform:translate(${tx.toFixed(1)}px,${ty.toFixed(1)}px)`
|
||||
if (posH === 'center') {
|
||||
imgFloatPos = `left:50%;top:${ty.toFixed(1)}px`
|
||||
imgWrapTransform = 'transform:translateX(-50%)'
|
||||
} else if (posH === 'right') {
|
||||
imgFloatPos = `right:0;top:${ty.toFixed(1)}px`
|
||||
} else {
|
||||
imgFloatPos = `left:${tx.toFixed(1)}px;top:${ty.toFixed(1)}px`
|
||||
}
|
||||
} else if (imageWrap && node.attrs.imageOffsetYEmu != null) {
|
||||
// wrapped floats keep their flow slot, but a negative vertical anchor
|
||||
// offset lifts the image (Word: logo above its anchor line must not push)
|
||||
const ty = Number(node.attrs.imageOffsetYEmu) / EMU_PER_PX
|
||||
if (ty < 0) imgWrapTransform = `margin-top:${ty.toFixed(1)}px`
|
||||
}
|
||||
const imgAttrs: Record<string, string> = {
|
||||
src: String(imageDataUrl),
|
||||
@@ -2133,6 +2213,12 @@ function protectedDomSpec(node: PmNode): DomSpec {
|
||||
`width:${Number(imageWidthPx)}px;` +
|
||||
(imageHeightPx ? `height:${Number(imageHeightPx)}px` : 'height:auto')
|
||||
}
|
||||
// picture outline (document data, not chrome): border adds outside the
|
||||
// extent, approximating Word's centered stroke
|
||||
const ib = node.attrs.imageBorder as { color: string; widthPt: number } | null
|
||||
const borderCss = ib
|
||||
? `border:${((ib.widthPt * 96) / 72).toFixed(1)}px solid #${String(ib.color).replace(/[^0-9A-Fa-f]/g, '')}`
|
||||
: ''
|
||||
// DrawingML order: flip mirrors the source, rot turns the result
|
||||
// (CSS applies right-to-left, so scale sits last)
|
||||
const xf: string[] = []
|
||||
@@ -2170,7 +2256,9 @@ function protectedDomSpec(node: PmNode): DomSpec {
|
||||
`width:${sw.toFixed(1)}px;height:${sh.toFixed(1)}px;max-width:none`
|
||||
// rot/flip turn the whole crop window, not the source inside it
|
||||
const wrapXf = [
|
||||
...(imgWrapTransform ? [imgWrapTransform.slice('transform:'.length)] : []),
|
||||
...(imgWrapTransform.startsWith('transform:')
|
||||
? [imgWrapTransform.slice('transform:'.length)]
|
||||
: []),
|
||||
...xf,
|
||||
]
|
||||
return [
|
||||
@@ -2181,7 +2269,7 @@ function protectedDomSpec(node: PmNode): DomSpec {
|
||||
'span',
|
||||
{
|
||||
class: 'doc-img-wrap doc-img-crop',
|
||||
style: `position:relative;display:inline-block;overflow:hidden;width:${W}px;height:${H}px${wrapXf.length ? `;transform:${wrapXf.join(' ')}` : ''}`,
|
||||
style: `position:${imgFloatPos ? `absolute;${imgFloatPos}` : 'relative'};display:inline-block;overflow:hidden;width:${W}px;height:${H}px${wrapXf.length ? `;transform:${wrapXf.join(' ')}` : ''}${imgWrapTransform && !imgWrapTransform.startsWith('transform:') ? `;${imgWrapTransform}` : ''}${borderCss ? `;${borderCss}` : ''}`,
|
||||
},
|
||||
['img', imgAttrs],
|
||||
['span', { class: 'img-resize-handle' }],
|
||||
@@ -2192,6 +2280,9 @@ function protectedDomSpec(node: PmNode): DomSpec {
|
||||
imgAttrs['style'] =
|
||||
`${imgAttrs['style'] ? `${imgAttrs['style']};` : ''}transform:${xf.join(' ')}`
|
||||
}
|
||||
if (borderCss) {
|
||||
imgAttrs['style'] = `${imgAttrs['style'] ? `${imgAttrs['style']};` : ''}${borderCss}`
|
||||
}
|
||||
return [
|
||||
'div',
|
||||
attrs,
|
||||
@@ -2200,7 +2291,11 @@ function protectedDomSpec(node: PmNode): DomSpec {
|
||||
'span',
|
||||
{
|
||||
class: 'doc-img-wrap',
|
||||
...(imgWrapTransform ? { style: `display:inline-block;${imgWrapTransform}` } : {}),
|
||||
...(imgFloatPos || imgWrapTransform
|
||||
? {
|
||||
style: `${imgFloatPos ? `position:absolute;${imgFloatPos};` : ''}display:inline-block${imgWrapTransform ? `;${imgWrapTransform}` : ''}`,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
['img', imgAttrs],
|
||||
['span', { class: 'img-resize-handle' }],
|
||||
@@ -3270,12 +3365,16 @@ export const editorExtensions = [
|
||||
LineFactorExtension,
|
||||
ListNumberingExtension,
|
||||
PaginationGapsExtension,
|
||||
CaretMarksMemory,
|
||||
ColumnLayoutExtension,
|
||||
TabStopExtension,
|
||||
WsRunLineHeightExtension,
|
||||
DropCapExtension,
|
||||
ParaBorderMergeExtension,
|
||||
SdtExtension,
|
||||
MoveRevisionExtension,
|
||||
PPrChangeExtension,
|
||||
ParaMarkDelExtension,
|
||||
RevisionOriginalExtension,
|
||||
AutoDirectionExtension,
|
||||
]
|
||||
|
||||
@@ -8,16 +8,24 @@
|
||||
* dashed leader from the anchor. The wrap gains `has-markup-area` +
|
||||
* `--markup-w` so the column takes real width (screenshots/regression capture
|
||||
* the wrap box); percentage-centered wrap overlays are re-centered in CSS.
|
||||
* - Revision bubbles (balloon mode): "Deleted:"/"Formatted:" balloons for
|
||||
* tracked deletions and format changes, which leave the text flow in that
|
||||
* mode (Word's All Markup balloons). Bubbles stack per page and overflow
|
||||
* past a page bottom is dropped, like Word's overflow pane.
|
||||
* - Change bars: vertical segments in the left page margin covering every line
|
||||
* that carries a tracked revision (Word's changed-line marks).
|
||||
*/
|
||||
import type { CommentInfo } from '@genoffice/docx-engine'
|
||||
import type { EditorView } from '@tiptap/pm/view'
|
||||
import type { Mark as PmMark } from '@tiptap/pm/model'
|
||||
import { t } from '../i18n/locale'
|
||||
|
||||
export const MARKUP_AREA_W = 200
|
||||
const BUBBLE_W = 168
|
||||
const BUBBLE_ENTRY_X = 12
|
||||
const BUBBLE_STACK_GAP = 6
|
||||
const CHANGE_BAR_X = 24
|
||||
const REV_TEXT_MAX = 220
|
||||
|
||||
const REV_SELECTOR =
|
||||
'.doc-ins, .doc-del, .has-move-from, .has-move-to, .has-rpr-change, .has-ppr-change'
|
||||
@@ -75,6 +83,156 @@ function makeBubble(root: CommentInfo, replies: CommentInfo[], onJump: () => voi
|
||||
return bubble
|
||||
}
|
||||
|
||||
function makeRevBubble(kind: 'del' | 'fmt', text: string): HTMLElement {
|
||||
const bubble = document.createElement('div')
|
||||
bubble.className = `comment-bubble rev-bubble rev-bubble-${kind}`
|
||||
const label = document.createElement('span')
|
||||
label.className = 'rev-bubble-label'
|
||||
label.textContent = `${t(kind === 'del' ? 'editorRevDeleted' : 'editorRevFormatted')}: `
|
||||
const body = document.createElement('span')
|
||||
body.className = 'rev-bubble-text'
|
||||
body.textContent = text.length > REV_TEXT_MAX ? `${text.slice(0, REV_TEXT_MAX)}…` : text
|
||||
bubble.append(label, body)
|
||||
return bubble
|
||||
}
|
||||
|
||||
/** "Formatted:" balloon text: the changed run props' new values (Word describes what the run became) */
|
||||
function fmtDesc(old: Record<string, unknown>, marks: readonly PmMark[]): string {
|
||||
const ts = marks.find((m) => m.type.name === 'docTextStyle')
|
||||
const bold = marks.some((m) => m.type.name === 'bold')
|
||||
const italic = marks.some((m) => m.type.name === 'italic')
|
||||
const parts: string[] = []
|
||||
const fontBits: string[] = []
|
||||
const newFont = (ts?.attrs.fontAscii ?? ts?.attrs.font) as string | null | undefined
|
||||
const oldFont = (old.fontAscii ?? old.font) as string | undefined
|
||||
if (newFont && newFont !== oldFont) fontBits.push(newFont)
|
||||
const newSz = ts?.attrs.sizeHalfPoints as number | null | undefined
|
||||
if (newSz && newSz !== old.sizeHalfPoints) fontBits.push(`${newSz / 2} pt`)
|
||||
if (fontBits.length > 0) parts.push(`${t('editorRevFont')}: ${fontBits.join(', ')}`)
|
||||
if (bold !== !!old.bold) parts.push(t(bold ? 'editorRevBold' : 'editorRevNotBold'))
|
||||
if (italic !== !!old.italic) parts.push(t(italic ? 'editorRevItalic' : 'editorRevNotItalic'))
|
||||
const newHl = (ts?.attrs.highlight as string | null | undefined) ?? null
|
||||
if (newHl !== (((old.highlight as string | undefined) ?? null) as string | null)) {
|
||||
parts.push(t('editorRevHighlight'))
|
||||
}
|
||||
return parts.join(', ') || t('editorFormatRevision')
|
||||
}
|
||||
|
||||
type RevItem = { kind: 'del' | 'fmt'; from: number; to: number; text: string }
|
||||
|
||||
/**
|
||||
* Tracked revisions that live in balloons, in document order, merged over
|
||||
* contiguous positions. A deleted paragraph mark bridges [end-1, end+1], so a
|
||||
* fully deleted paragraph chains with the next paragraph's leading deletion
|
||||
* into one balloon, matching Word's "XXX¶XXX¶" grouping.
|
||||
*/
|
||||
function revGroupsOf(view: EditorView): RevItem[] {
|
||||
const items: RevItem[] = []
|
||||
view.state.doc.descendants((node, pos) => {
|
||||
if (node.isTextblock) {
|
||||
if (node.attrs?.pPrChange) {
|
||||
items.push({ kind: 'fmt', from: pos + 1, to: pos + 1, text: t('editorFormatRevision') })
|
||||
}
|
||||
if (node.attrs?.paraMarkDel) {
|
||||
const end = pos + node.nodeSize
|
||||
items.push({ kind: 'del', from: end - 1, to: end + 1, text: '¶' })
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (!node.isText) return true
|
||||
if (node.marks.some((m) => m.type.name === 'del')) {
|
||||
items.push({ kind: 'del', from: pos, to: pos + node.nodeSize, text: node.text ?? '' })
|
||||
return true
|
||||
}
|
||||
const rpr = node.marks.find((m) => m.type.name === 'rprChange')
|
||||
if (rpr) {
|
||||
items.push({
|
||||
kind: 'fmt',
|
||||
from: pos,
|
||||
to: pos + node.nodeSize,
|
||||
text: fmtDesc((rpr.attrs.old ?? {}) as Record<string, unknown>, node.marks),
|
||||
})
|
||||
}
|
||||
return true
|
||||
})
|
||||
items.sort((a, b) => a.from - b.from || a.to - b.to)
|
||||
const groups: RevItem[] = []
|
||||
for (const it of items) {
|
||||
const last = groups[groups.length - 1]
|
||||
if (
|
||||
last &&
|
||||
last.kind === it.kind &&
|
||||
it.from <= last.to &&
|
||||
(it.kind === 'del' || it.text === last.text)
|
||||
) {
|
||||
last.to = Math.max(last.to, it.to)
|
||||
if (it.kind === 'del') last.text += it.text
|
||||
} else {
|
||||
groups.push({ ...it })
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
/** Nearest on-screen box before a hidden position: previous visible sibling, walking up. */
|
||||
function visibleRectNear(el: HTMLElement | null, pm: HTMLElement): DOMRect | null {
|
||||
let cur: HTMLElement | null = el
|
||||
while (cur && cur !== pm) {
|
||||
for (
|
||||
let sib = cur.previousElementSibling as HTMLElement | null;
|
||||
sib;
|
||||
sib = sib.previousElementSibling as HTMLElement | null
|
||||
) {
|
||||
const rects = sib.getClientRects()
|
||||
if (rects.length > 0) return rects[rects.length - 1]
|
||||
}
|
||||
cur = cur.parentElement
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function anchorPointFor(
|
||||
view: EditorView,
|
||||
pm: HTMLElement,
|
||||
pos: number,
|
||||
): { top: number; bottom: number; left: number } | null {
|
||||
const clamped = Math.max(0, Math.min(pos, view.state.doc.content.size))
|
||||
try {
|
||||
const c = view.coordsAtPos(clamped)
|
||||
if (c && (c.top !== 0 || c.left !== 0 || c.bottom !== 0)) {
|
||||
return { top: c.top, bottom: c.bottom, left: c.left }
|
||||
}
|
||||
} catch {
|
||||
/* position renders inside hidden (balloon-collapsed) content */
|
||||
}
|
||||
try {
|
||||
const { node } = view.domAtPos(clamped)
|
||||
const el = (node instanceof HTMLElement ? node : node.parentElement) as HTMLElement | null
|
||||
const rect = visibleRectNear(el, pm)
|
||||
if (rect) return { top: rect.bottom, bottom: rect.bottom, left: rect.right }
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Page bands (wrap coords) from the top-level page-gap widgets; one whole-doc band when absent. */
|
||||
function pageBandsOf(pm: HTMLElement, wrapRect: DOMRect, wrapH: number, f: number): Seg[] {
|
||||
const gaps = [...pm.querySelectorAll<HTMLElement>('.page-gap:not(.page-gap-inline)')]
|
||||
.map((g) => g.getBoundingClientRect())
|
||||
.filter((r) => r.height > 0)
|
||||
.sort((a, b) => a.top - b.top)
|
||||
if (gaps.length === 0) return [{ top: 0, bottom: wrapH }]
|
||||
const bands: Seg[] = []
|
||||
let top = 0
|
||||
for (const g of gaps) {
|
||||
bands.push({ top, bottom: (g.top - wrapRect.top) / f })
|
||||
top = (g.bottom - wrapRect.top) / f
|
||||
}
|
||||
bands.push({ top, bottom: wrapH })
|
||||
return bands
|
||||
}
|
||||
|
||||
export function clearMarginAnnotations(wrap: HTMLElement): void {
|
||||
wrap.querySelector(':scope > .page-margin-annotations')?.remove()
|
||||
wrap.classList.remove('has-markup-area')
|
||||
@@ -92,6 +250,7 @@ export function syncMarginAnnotations(
|
||||
comments: CommentInfo[],
|
||||
zoomFactor: number,
|
||||
blocks?: AnchorBlock[],
|
||||
view?: EditorView,
|
||||
): void {
|
||||
const f = zoomFactor
|
||||
const wrapRect = wrap.getBoundingClientRect()
|
||||
@@ -107,8 +266,6 @@ export function syncMarginAnnotations(
|
||||
}
|
||||
}
|
||||
}
|
||||
const bars = mergeSegs(segs)
|
||||
|
||||
// one bubble per open top-level thread that has an anchor range in the body
|
||||
const anchorOf = new Map<string, HTMLElement>()
|
||||
for (const span of pm.querySelectorAll<HTMLElement>('.doc-comment')) {
|
||||
@@ -116,18 +273,17 @@ export function syncMarginAnnotations(
|
||||
if (id && !anchorOf.has(id)) anchorOf.set(id, span)
|
||||
}
|
||||
}
|
||||
type Thread = {
|
||||
root: CommentInfo
|
||||
replies: CommentInfo[]
|
||||
type Placed = {
|
||||
top: number
|
||||
y: number
|
||||
x: number
|
||||
jump: () => void
|
||||
/** comments always render; only revision balloons overflow-drop (Word's overflow pane) */
|
||||
sticky: boolean
|
||||
make: () => HTMLElement
|
||||
}
|
||||
const threads: Thread[] = []
|
||||
const localThread = (c: CommentInfo, rect: DOMRect, blockAnchor: HTMLElement | null): Thread => ({
|
||||
root: c,
|
||||
replies: comments.filter((r) => r.parentId === c.id),
|
||||
const placed: Placed[] = []
|
||||
const localThread = (c: CommentInfo, rect: DOMRect, blockAnchor: HTMLElement | null): Placed => ({
|
||||
sticky: true,
|
||||
top: (rect.top - wrapRect.top) / f,
|
||||
// leader start: end of the marked range, or start of the anchor paragraph's
|
||||
// first line for range-less comments (bare w:commentReference on an empty run)
|
||||
@@ -135,15 +291,20 @@ export function syncMarginAnnotations(
|
||||
? (rect.top - wrapRect.top) / f + Math.min(rect.height / f, 16)
|
||||
: (rect.bottom - wrapRect.top) / f - 1,
|
||||
x: ((blockAnchor ? rect.left : rect.right) - wrapRect.left) / f,
|
||||
// block-anchored threads have no .doc-comment span: flash the block itself
|
||||
jump: blockAnchor ? () => flashEls([blockAnchor]) : () => flashAnchors(pm, c.id),
|
||||
make: () =>
|
||||
makeBubble(
|
||||
c,
|
||||
comments.filter((r) => r.parentId === c.id),
|
||||
// block-anchored threads have no .doc-comment span: flash the block itself
|
||||
blockAnchor ? () => flashEls([blockAnchor]) : () => flashAnchors(pm, c.id),
|
||||
),
|
||||
})
|
||||
for (const c of comments) {
|
||||
if (c.parentId || c.done) continue
|
||||
const el = anchorOf.get(c.id)
|
||||
const rect = el ? [...el.getClientRects()].find((r) => r.height > 0) : undefined
|
||||
if (rect) {
|
||||
threads.push(localThread(c, rect, null))
|
||||
placed.push(localThread(c, rect, null))
|
||||
continue
|
||||
}
|
||||
// no mark in the body: anchor to the block whose XML carries the reference
|
||||
@@ -156,11 +317,34 @@ export function syncMarginAnnotations(
|
||||
const blockEl =
|
||||
block && (pm.querySelector(`[data-idx="${block.docxIndex}"]`) as HTMLElement | null)
|
||||
const blockRect = blockEl && [...blockEl.getClientRects()].find((r) => r.height > 0)
|
||||
if (blockEl && blockRect) threads.push(localThread(c, blockRect, blockEl))
|
||||
if (blockEl && blockRect) placed.push(localThread(c, blockRect, blockEl))
|
||||
}
|
||||
threads.sort((a, b) => a.top - b.top)
|
||||
|
||||
if (bars.length === 0 && threads.length === 0) {
|
||||
// revision balloons: only in balloon mode (print view, All Markup), where the
|
||||
// deleted text / format chips have left the flow
|
||||
if (view && wrap.closest('.rev-balloon')) {
|
||||
for (const g of revGroupsOf(view)) {
|
||||
const p = anchorPointFor(view, pm, g.from)
|
||||
if (!p) continue
|
||||
// hidden deletions have no rects for the bar pass above: mark their anchor
|
||||
// line (the sibling-fallback anchor is a point — give it one line of bar)
|
||||
if (g.kind === 'del') {
|
||||
const top = (p.top - wrapRect.top) / f
|
||||
segs.push({ top, bottom: Math.max((p.bottom - wrapRect.top) / f, top + 12) })
|
||||
}
|
||||
placed.push({
|
||||
sticky: false,
|
||||
top: (p.top - wrapRect.top) / f,
|
||||
y: (p.bottom - wrapRect.top) / f - 1,
|
||||
x: (p.left - wrapRect.left) / f,
|
||||
make: () => makeRevBubble(g.kind, g.text),
|
||||
})
|
||||
}
|
||||
}
|
||||
placed.sort((a, b) => a.top - b.top)
|
||||
const bars = mergeSegs(segs)
|
||||
|
||||
if (bars.length === 0 && placed.length === 0) {
|
||||
clearMarginAnnotations(wrap)
|
||||
return
|
||||
}
|
||||
@@ -173,8 +357,8 @@ export function syncMarginAnnotations(
|
||||
}
|
||||
layer.textContent = ''
|
||||
|
||||
wrap.classList.toggle('has-markup-area', threads.length > 0)
|
||||
if (threads.length > 0) wrap.style.setProperty('--markup-w', `${MARKUP_AREA_W}px`)
|
||||
wrap.classList.toggle('has-markup-area', placed.length > 0)
|
||||
if (placed.length > 0) wrap.style.setProperty('--markup-w', `${MARKUP_AREA_W}px`)
|
||||
|
||||
const barX = (pmRect.left - wrapRect.left) / f + CHANGE_BAR_X
|
||||
for (const b of bars) {
|
||||
@@ -186,25 +370,41 @@ export function syncMarginAnnotations(
|
||||
layer.appendChild(el)
|
||||
}
|
||||
|
||||
if (threads.length === 0) return
|
||||
if (placed.length === 0) return
|
||||
const paperRight = (pmRect.right - wrapRect.left) / f
|
||||
const bubbleLeft = paperRight + BUBBLE_ENTRY_X
|
||||
const svg = document.createElementNS(SVG_NS, 'svg')
|
||||
svg.setAttribute('class', 'comment-leaders')
|
||||
layer.appendChild(svg)
|
||||
// stack per page band; a bubble that cannot start within its band is dropped
|
||||
// (Word routes those to the overflow pane)
|
||||
const bands = pageBandsOf(pm, wrapRect, wrapRect.height / f, f)
|
||||
let bandIdx = 0
|
||||
let prevBottom = -Infinity
|
||||
for (const t of threads) {
|
||||
const bubble = makeBubble(t.root, t.replies, t.jump)
|
||||
for (const p of placed) {
|
||||
while (bandIdx < bands.length - 1 && p.top >= bands[bandIdx + 1].top) {
|
||||
bandIdx++
|
||||
prevBottom = -Infinity
|
||||
}
|
||||
const bubble = p.make()
|
||||
bubble.style.left = `${bubbleLeft}px`
|
||||
bubble.style.width = `${BUBBLE_W}px`
|
||||
const top = Math.max(t.top, prevBottom + BUBBLE_STACK_GAP)
|
||||
const top = Math.max(p.top, prevBottom + BUBBLE_STACK_GAP, bands[bandIdx].top)
|
||||
bubble.style.top = `${top}px`
|
||||
layer.appendChild(bubble)
|
||||
if (
|
||||
!p.sticky &&
|
||||
top + bubble.offsetHeight > bands[bandIdx].bottom &&
|
||||
top > bands[bandIdx].top
|
||||
) {
|
||||
bubble.remove()
|
||||
continue
|
||||
}
|
||||
prevBottom = top + bubble.offsetHeight
|
||||
const path = document.createElementNS(SVG_NS, 'path')
|
||||
path.setAttribute(
|
||||
'd',
|
||||
`M ${t.x} ${t.y} L ${paperRight + BUBBLE_ENTRY_X / 2} ${t.y} L ${bubbleLeft} ${top + 9}`,
|
||||
`M ${p.x} ${p.y} L ${paperRight + BUBBLE_ENTRY_X / 2} ${p.y} L ${bubbleLeft} ${top + 9}`,
|
||||
)
|
||||
svg.appendChild(path)
|
||||
}
|
||||
|
||||
@@ -107,6 +107,9 @@ export type PageGapSpec = {
|
||||
/** page forced by an explicit break (w:br page / pageBreakBefore): Word drops the
|
||||
* lead block's space-before, so a node decoration zeroes its margin-top */
|
||||
suppressLeadMt?: boolean
|
||||
/** mixed-column page above: pull the gap (and everything below) up over the
|
||||
* vacated stacked-column space (negative margin-top, neutralized while measuring) */
|
||||
pullUp?: number
|
||||
} & ({ el: HTMLElement } | { pos: number; kind?: Exclude<GapKind, 'block'> })
|
||||
|
||||
/** Rebuild all page gaps (an empty list clears them); each gap carries its own margins (sections differ) */
|
||||
@@ -161,12 +164,16 @@ export function setPageGaps(
|
||||
pos = gap.pos
|
||||
kind = gap.kind ?? 'inline'
|
||||
}
|
||||
const mKey = `${metrics.marginTop},${metrics.marginBottom},${metrics.marginLeft},${metrics.marginRight}`
|
||||
const mKey = `${metrics.marginTop},${metrics.marginBottom},${metrics.marginLeft},${metrics.marginRight},${Math.round(gap.pullUp ?? 0)}`
|
||||
decos.push(
|
||||
Decoration.widget(
|
||||
pos,
|
||||
() => {
|
||||
const el = makeGapEl(metrics, kind)
|
||||
// margins don't apply to table-rows and cuts are zero-height markers;
|
||||
// tables inside mixed-column regions are out of scope anyway (v1)
|
||||
if (gap.pullUp && kind !== 'cut' && kind !== 'table')
|
||||
el.style.marginTop = `-${gap.pullUp}px`
|
||||
if (notes) el.appendChild(notes)
|
||||
if (hfEls && (kind === 'block' || kind === 'inline' || kind === 'cell')) {
|
||||
for (const hf of hfEls) el.appendChild(hf)
|
||||
@@ -370,6 +377,35 @@ export function syncFloatShifts(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Word keeps anchored objects on the page: a cell-anchored box whose negative
|
||||
* offset lifts it above the paper top (0219: a glossary title box -82pt above
|
||||
* a first-row cell paragraph rendered clipped off the paper) is pushed back
|
||||
* down to the paper edge. Cell boxes are overlay-only (zero flow footprint),
|
||||
* so the shift has no layout feedback. Idempotent via the same
|
||||
* --page-float-dy channel as syncFloatShifts.
|
||||
*/
|
||||
export function clampCellBoxTops(pm: HTMLElement, paperTop: number, factor: number): void {
|
||||
for (const box of Array.from(
|
||||
pm.querySelectorAll<HTMLElement>('.doc-cell-boxes > .doc-textbox, .doc-cell-boxes > div'),
|
||||
)) {
|
||||
const r = box.getBoundingClientRect()
|
||||
if (r.height <= 0) continue
|
||||
const applied = parseFloat(box.dataset.pageFloatDy ?? '0') || 0
|
||||
const naturalTop = r.top - applied * factor
|
||||
const next = Math.max(0, (paperTop - naturalTop) / factor)
|
||||
if (next < 0.5) {
|
||||
if (box.dataset.pageFloatDy) {
|
||||
box.style.removeProperty('--page-float-dy')
|
||||
delete box.dataset.pageFloatDy
|
||||
}
|
||||
} else if (Math.abs(next - applied) > 0.5 || !box.dataset.pageFloatDy) {
|
||||
box.style.setProperty('--page-float-dy', `${next.toFixed(1)}px`)
|
||||
box.dataset.pageFloatDy = String(next)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** remove all float display shifts (leaving print view) */
|
||||
export function clearFloatShifts(pm: HTMLElement): void {
|
||||
for (const el of Array.from(pm.querySelectorAll<HTMLElement>('[data-page-float-dy]'))) {
|
||||
|
||||
@@ -27,17 +27,20 @@ import {
|
||||
type DocProtection,
|
||||
type HeaderFooter,
|
||||
type NoteInfo,
|
||||
type ParsedDocFull,
|
||||
type SectionInfo,
|
||||
type SectionSettings,
|
||||
type SourceInfo,
|
||||
type StyleUpsert,
|
||||
type ThemeColors,
|
||||
type ThemeFonts,
|
||||
type WriteProtection,
|
||||
} from '@genoffice/docx-engine'
|
||||
import type { Dispatch, SetStateAction } from 'react'
|
||||
import type { OpenFileResult } from '../shared/ipc'
|
||||
import type { OpenDocxResult } from '../shared/ipc'
|
||||
import {
|
||||
hfVariantsFromParsed,
|
||||
openedFileStartsDirty,
|
||||
type DocState,
|
||||
type HfVariantKey,
|
||||
type HfVariantsState,
|
||||
@@ -164,7 +167,19 @@ export interface FileActionContext {
|
||||
protectionDirty: boolean
|
||||
setProtection: (value: DocProtection | null) => void
|
||||
setProtectionDirty: (dirty: boolean) => void
|
||||
writeProtection: WriteProtection | null
|
||||
writeProtectionDirty: boolean
|
||||
setWriteProtection: (value: WriteProtection | null) => void
|
||||
setWriteProtectionDirty: (dirty: boolean) => void
|
||||
removePersonalInfo: boolean
|
||||
removePersonalInfoDirty: boolean
|
||||
setRemovePersonalInfo: (value: boolean) => void
|
||||
setRemovePersonalInfoDirty: (dirty: boolean) => void
|
||||
/** document (re)loaded: App resets the modify-password session state and prompts when one is set */
|
||||
onWriteProtectionLoaded: (wp: WriteProtection | null) => void
|
||||
setCompareResult: (value: { otherName: string; entries: CompareEntry[] } | null) => void
|
||||
/** password-protected docx: open the password prompt (decrypt-retry loop lives in App) */
|
||||
promptDocxPassword: (info: { path: string; name: string }) => void
|
||||
}
|
||||
|
||||
/** Drop the undo stack: undo across an open/reparse boundary resurrects stale
|
||||
@@ -207,20 +222,54 @@ function resetEditorHistory(editor: Editor): void {
|
||||
editor.registerPlugin(history((plugin.spec as { config?: object }).config))
|
||||
}
|
||||
|
||||
/** doc-level layout inputs living outside CSS: default tab grid + hyphenation lang */
|
||||
function applyDocLayoutSettings(editor: Editor, parsed: ParsedDocFull): void {
|
||||
editor.storage.tabStops.defaultTabStopTwips = parsed.defaultTabStopTwips ?? null
|
||||
// Chromium only hyphenates under an explicit lang (the app shell is zh-CN);
|
||||
// scoped to autoHyphenation docs so CJK font fallback is untouched elsewhere
|
||||
const lang = parsed.autoHyphenation ? parsed.docDefaults?.lang : undefined
|
||||
if (lang) editor.view.dom.setAttribute('lang', lang)
|
||||
else editor.view.dom.removeAttribute('lang')
|
||||
}
|
||||
|
||||
/**
|
||||
* 'ok' loaded; 'canceled' dialog dismissed / no editor; 'password' the password
|
||||
* prompt took over (App resumes via loadFile once decrypted); 'failed' parse or
|
||||
* load error — the boot path falls back to a blank document instead of leaving
|
||||
* the tab on "Opening…" forever.
|
||||
*/
|
||||
export type LoadFileOutcome = 'ok' | 'canceled' | 'password' | 'failed'
|
||||
|
||||
export async function loadFile(
|
||||
ctx: FileActionContext,
|
||||
result: OpenFileResult | null,
|
||||
): Promise<void> {
|
||||
if (!result || !ctx.editor) return
|
||||
result: OpenDocxResult,
|
||||
): Promise<LoadFileOutcome> {
|
||||
if (!result || !ctx.editor) return 'canceled'
|
||||
if ('needsPassword' in result) {
|
||||
ctx.promptDocxPassword({ path: result.path, name: result.name })
|
||||
return 'password'
|
||||
}
|
||||
try {
|
||||
const parsed = await parseDocx(new Uint8Array(result.data))
|
||||
ctx.editor.storage.listNumbering.styles = parsed.styles
|
||||
ctx.editor.storage.listNumbering.docDefaults = parsed.docDefaults
|
||||
ctx.editor.storage.listNumbering.defs = parsed.numbering
|
||||
applyDocLayoutSettings(ctx.editor, parsed)
|
||||
ctx.editor.commands.setContent(blocksToPmDoc(parsed.blocks, readSections(parsed)) as never)
|
||||
resetEditorHistory(ctx.editor)
|
||||
noteDocumentSwapped()
|
||||
ctx.setDoc({ parsed, filePath: result.path, fileName: result.name, hash: result.hash })
|
||||
ctx.setDoc({
|
||||
parsed,
|
||||
filePath: result.path,
|
||||
fileName: result.name,
|
||||
hash: result.hash,
|
||||
encrypted: result.encrypted,
|
||||
})
|
||||
// this tab's document was replaced: a password parked for the previous
|
||||
// unsaved draft is stale and must not encrypt this document's saves.
|
||||
// Done here, not in the main process's loadDocx — Review > Compare also
|
||||
// opens files without replacing the current document.
|
||||
discardStalePasswordIntents()
|
||||
ctx.setAiPanelKey((k) => k + 1)
|
||||
ctx.setDocCss(docStyleCss(parsed))
|
||||
ctx.setSection(readSectionSettings(parsed))
|
||||
@@ -276,8 +325,15 @@ export async function loadFile(
|
||||
ctx.setTrackChanges(false)
|
||||
ctx.setProtection(parsed.protection)
|
||||
ctx.setProtectionDirty(false)
|
||||
ctx.setWriteProtection(parsed.writeProtection)
|
||||
ctx.setWriteProtectionDirty(false)
|
||||
ctx.setRemovePersonalInfo(parsed.removePersonalInfo)
|
||||
ctx.setRemovePersonalInfoDirty(false)
|
||||
ctx.onWriteProtectionLoaded(parsed.writeProtection)
|
||||
ctx.setCompareResult(null)
|
||||
ctx.dirtyRef.current = false
|
||||
// Recovery content still only exists in the autosave copy. Keep it dirty
|
||||
// until an explicit/automatic save lands it on the original path.
|
||||
ctx.dirtyRef.current = openedFileStartsDirty(result)
|
||||
const missing = checkMissingFonts(collectDocFonts(parsed))
|
||||
const verticalText = readSections(parsed).some((s) => s.settings.textDirection)
|
||||
if (verticalText) {
|
||||
@@ -293,8 +349,12 @@ export async function loadFile(
|
||||
ctx.setStatus(t('appOpenedFile', { name: result.name }))
|
||||
}
|
||||
void window.desktop.getRecentFiles().then(ctx.setRecent)
|
||||
return 'ok'
|
||||
} catch (err) {
|
||||
// visible failure: the status-bar line alone is easy to miss under the start screen
|
||||
ctx.setStatus(t('appOpenFailed', { error: String(err) }))
|
||||
showToast(t('appOpenFailed', { error: String(err) }), 'error')
|
||||
return 'failed'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,10 +367,14 @@ export async function newFile(ctx: FileActionContext): Promise<boolean | undefin
|
||||
ctx.editor.storage.listNumbering.styles = parsed.styles
|
||||
ctx.editor.storage.listNumbering.docDefaults = parsed.docDefaults
|
||||
ctx.editor.storage.listNumbering.defs = parsed.numbering
|
||||
applyDocLayoutSettings(ctx.editor, parsed)
|
||||
ctx.editor.commands.setContent(blocksToPmDoc(parsed.blocks, readSections(parsed)) as never)
|
||||
resetEditorHistory(ctx.editor)
|
||||
noteDocumentSwapped()
|
||||
ctx.setDoc({ parsed, filePath: null, fileName: t('appUntitledDocx'), hash: '', isBlank: true })
|
||||
// a fresh blank draft starts unencrypted: drop any pending password left by
|
||||
// the previous draft (its DocState, including the encrypted flag, is gone)
|
||||
discardStalePasswordIntents()
|
||||
ctx.setAiPanelKey((k) => k + 1)
|
||||
ctx.setDocCss(docStyleCss(parsed))
|
||||
ctx.setSection(readSectionSettings(parsed))
|
||||
@@ -343,6 +407,11 @@ export async function newFile(ctx: FileActionContext): Promise<boolean | undefin
|
||||
ctx.setTrackChanges(false)
|
||||
ctx.setProtection(null)
|
||||
ctx.setProtectionDirty(false)
|
||||
ctx.setWriteProtection(null)
|
||||
ctx.setWriteProtectionDirty(false)
|
||||
ctx.setRemovePersonalInfo(false)
|
||||
ctx.setRemovePersonalInfoDirty(false)
|
||||
ctx.onWriteProtectionLoaded(null)
|
||||
ctx.setCompareResult(null)
|
||||
ctx.dirtyRef.current = false
|
||||
ctx.setShowAi(true)
|
||||
@@ -497,6 +566,8 @@ export async function buildDocBytes(ctx: FileActionContext): Promise<Uint8Array
|
||||
partBinary: Object.keys(partBinary).length > 0 ? partBinary : undefined,
|
||||
comments: ctx.commentsDirty ? ctx.comments : undefined,
|
||||
protection: ctx.protectionDirty ? ctx.protection : undefined,
|
||||
writeProtection: ctx.writeProtectionDirty ? ctx.writeProtection : undefined,
|
||||
removePersonalInfo: ctx.removePersonalInfoDirty ? ctx.removePersonalInfo : undefined,
|
||||
inks,
|
||||
watermark: ctx.watermarkDirty ? ctx.watermark : undefined,
|
||||
footnotes: ctx.notesDirty ? ctx.footnotes : undefined,
|
||||
@@ -544,6 +615,25 @@ export async function writeRecoveryCopy(ctx: FileActionContext): Promise<void> {
|
||||
|
||||
const runSerializedSave = createSaveSerializer()
|
||||
|
||||
/**
|
||||
* Drop unsaved password intents left by a replaced document — queued behind any
|
||||
* in-flight save: writeRecoveryCopy silently save-new's a dirty pathless
|
||||
* draft, and that save must still consume the draft's desired password (the
|
||||
* draft stays protected on disk) before the swap-triggered clear lands.
|
||||
*/
|
||||
function discardStalePasswordIntents(): void {
|
||||
// Start the IPC now, before the replacement document can record a password.
|
||||
// The destructive half stays serialized behind an old in-flight save.
|
||||
const throughRevision = window.desktop.docPasswordIntentRevision()
|
||||
void runSerializedSave(
|
||||
async () => {
|
||||
await window.desktop.discardDocPasswordIntents(await throughRevision)
|
||||
return false // not a save: a queued save pass must never reuse this result
|
||||
},
|
||||
() => false,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Path assigned by the first save of a still-pathless document (silent save-new
|
||||
* or Save As). A queued save whose ctx snapshot predates that first save still
|
||||
@@ -560,7 +650,7 @@ export function save(ctx: FileActionContext, saveAs: boolean, auto = false): Pro
|
||||
// A save arriving mid-flight waits for the current one instead of failing.
|
||||
// Reuse the finished pass only when it left nothing behind — judged by the
|
||||
// composite dirty check (header/section/theme edits do not set dirtyRef), plus
|
||||
// the raced-with-typing flag. A pass that left anything runs its own pass;
|
||||
// in-flight edit/password races. A pass that left anything runs its own pass;
|
||||
// saveOnce resolves a stale pathless snapshot via pathlessDocSavedPath, so
|
||||
// the retry can no longer create a duplicate file.
|
||||
return runSerializedSave(
|
||||
@@ -589,13 +679,15 @@ async function saveOnce(ctx: FileActionContext, saveAs: boolean, auto: boolean):
|
||||
// a pathless snapshot may belong to a document that an earlier queued pass
|
||||
// already landed on disk — overwrite that file instead of creating another
|
||||
let savedPath = doc.filePath ?? pathlessDocSavedPath
|
||||
let passwordIntentPending = false
|
||||
if (saveAs || !savedPath) {
|
||||
// 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
|
||||
// Save As keeps the dialog; a new document's first save lands silently in the default
|
||||
// folder. The source path identifies the desired password state to snapshot.
|
||||
const result = saveAs
|
||||
? await window.desktop.saveDocxAs(autoName ?? doc.fileName, buffer)
|
||||
? await window.desktop.saveDocxAs(autoName ?? doc.fileName, buffer, doc.filePath)
|
||||
: await window.desktop.saveDocxNew(autoName ?? doc.fileName, buffer)
|
||||
if (!result.ok) {
|
||||
if (result.error) {
|
||||
@@ -605,6 +697,7 @@ async function saveOnce(ctx: FileActionContext, saveAs: boolean, auto: boolean):
|
||||
return false
|
||||
}
|
||||
savedPath = result.path!
|
||||
passwordIntentPending = result.passwordIntentPending === true
|
||||
if (!doc.filePath) pathlessDocSavedPath = savedPath
|
||||
} else {
|
||||
const result = await window.desktop.saveDocx(savedPath, buffer, auto)
|
||||
@@ -617,12 +710,13 @@ async function saveOnce(ctx: FileActionContext, saveAs: boolean, auto: boolean):
|
||||
}
|
||||
return false
|
||||
}
|
||||
passwordIntentPending = result.passwordIntentPending === true
|
||||
}
|
||||
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.
|
||||
if (editor.state.doc !== docSnapshot || passwordIntentPending) {
|
||||
// The user kept editing or chose another password after the main process
|
||||
// captured this save. Keep the live state dirty; replacing it with the
|
||||
// saved snapshot or marking it clean would consume the newer intent.
|
||||
if (passwordIntentPending) ctx.dirtyRef.current = true
|
||||
ctx.saveIncompleteRef.current = true
|
||||
ctx.setDoc((prev) =>
|
||||
prev
|
||||
@@ -636,7 +730,7 @@ async function saveOnce(ctx: FileActionContext, saveAs: boolean, auto: boolean):
|
||||
ctx.setStatus(
|
||||
auto ? t('appAutoSavedAt', { time: new Date().toLocaleTimeString() }) : t('appSaved'),
|
||||
)
|
||||
// No success toast: the doc is still dirty (edits raced the save), and the
|
||||
// No success toast: the doc is still dirty (state raced the save), and the
|
||||
// close-guard's saveUntilPersisted retries would repeat it on every pass —
|
||||
// the converging complete save below toasts once.
|
||||
return true
|
||||
@@ -646,6 +740,7 @@ async function saveOnce(ctx: FileActionContext, saveAs: boolean, auto: boolean):
|
||||
editor.storage.listNumbering.styles = reparsed.styles
|
||||
editor.storage.listNumbering.docDefaults = reparsed.docDefaults
|
||||
editor.storage.listNumbering.defs = reparsed.numbering
|
||||
applyDocLayoutSettings(editor, reparsed)
|
||||
const rebasedPm = blocksToPmDoc(reparsed.blocks, readSections(reparsed))
|
||||
let unchanged = false
|
||||
try {
|
||||
@@ -729,6 +824,11 @@ async function saveOnce(ctx: FileActionContext, saveAs: boolean, auto: boolean):
|
||||
ctx.setThemeColorsDirty(false)
|
||||
ctx.setProtection(reparsed.protection)
|
||||
ctx.setProtectionDirty(false)
|
||||
// no onWriteProtectionLoaded here: saving must not re-lock the session
|
||||
ctx.setWriteProtection(reparsed.writeProtection)
|
||||
ctx.setWriteProtectionDirty(false)
|
||||
ctx.setRemovePersonalInfo(reparsed.removePersonalInfo)
|
||||
ctx.setRemovePersonalInfoDirty(false)
|
||||
ctx.dirtyRef.current = false
|
||||
ctx.setStatus(
|
||||
auto ? t('appAutoSavedAt', { time: new Date().toLocaleTimeString() }) : t('appSaved'),
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -6,6 +6,10 @@ 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)
|
||||
Copyright (c) 2010, NHN Corporation (http://www.nhncorp.com),
|
||||
with Reserved Font Name Nanum, Naver Nanum, NanumGothic, Naver
|
||||
NanumGothic, NanumMyeongjo, Naver NanumMyeongjo, NanumBrush, Naver
|
||||
NanumBrush, NanumPen, Naver NanumPen.
|
||||
|
||||
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
|
||||
|
||||
@@ -69,6 +69,42 @@ Renamed because OFL reserves the "Noto" name
|
||||
for unmodified builds. Conjoining jamo keep native advances (shaping). Word
|
||||
counterpart line factors live in `lineHeightFactor()` of `line-metrics.ts`.
|
||||
|
||||
### GenOffice Gothic KR
|
||||
|
||||
| Font | Role |
|
||||
| ---------------------------------- | ----------------------------------------------- |
|
||||
| GenOffice Gothic KR (subset woff2) | real-metric face for NanumGothic-declaring docs |
|
||||
|
||||
Source: NanumGothic Regular from [google/fonts](https://github.com/google/fonts/tree/main/ofl/nanumgothic)
|
||||
(SIL OFL 1.1). Word for Mac renders NanumGothic documents with the OS
|
||||
_downloadable_ Nanum asset (FontServices subset Chromium cannot see): hangul
|
||||
0.94em, space 0.28em, digits 0.606em (M3 probe 2026-08-14), while the
|
||||
Batang-normalized subset above ships 1.0/0.333/0.596 — +6.4% per hangul line.
|
||||
Subset to the same ranges as the KR fallbacks (KS X 1001 syllables + jamo +
|
||||
Basic Latin/punctuation/fullwidth forms), advances **unmodified**
|
||||
(`tools/build-gothic-kr-font.py`) and checked in as
|
||||
`GenOfficeGothicKR-Regular-subset.woff2`. Renamed per OFL (the upstream
|
||||
Reserved Font Names include "Nanum" and "NanumGothic"; subsetting is a
|
||||
modification). The exact NHN copyright/Reserved Font Name notice and the full
|
||||
OFL 1.1 text are in `LICENSE-OFL.txt`.
|
||||
|
||||
## Tamil fallback
|
||||
|
||||
| Font | Role |
|
||||
| ----------------------- | ---------------------------------------- |
|
||||
| GenOffice Tamil (woff2) | Latha-metric stand-in for Tamil families |
|
||||
|
||||
Source: Noto Sans Tamil Regular from [notofonts](https://github.com/notofonts/notofonts.github.io)
|
||||
(SIL OFL 1.1). Word substitutes missing Tamil families with Latha; Chromium's
|
||||
macOS fallback (Tamil Sangam MN) shapes ~27% narrower (M3 probe: sentence R
|
||||
0.728, space 0.39×), far past what size-adjust can fix without inflating glyph
|
||||
ink (137%). Advances are rewritten to Latha's: the 109 cmap-shared codepoints
|
||||
exactly, remaining glyphs (GSUB conjunct/matra outputs) by the median
|
||||
Tamil-letter ratio (`tools/build-tamil-font.py`; shaped sentence R vs Latha
|
||||
0.994, every probe sentence within ±2.3%). The face ships no Latin letters
|
||||
(upstream Noto Sans Tamil has none); Latin falls through the chain. Renamed
|
||||
per OFL ("Noto" is a Reserved Font Name; advances are modified).
|
||||
|
||||
## Arabic fallback
|
||||
|
||||
| Font | Role |
|
||||
|
||||
@@ -188,6 +188,19 @@
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
/* Documents declaring NanumGothic: mac Word lays out with the OS *downloadable*
|
||||
* source asset Chromium cannot see (M3 probe sample 19: hangul 0.94em, space
|
||||
* 0.28, digits 0.606 vs the Batang-normalized subset's 1.0/0.333/0.596 —
|
||||
* +6.4% per hangul line, +19% per space). Real-metric source subset
|
||||
* (tools/build-gothic-kr-font.py), advances unmodified; renamed per OFL
|
||||
* ("Nanum" is a Reserved Font Name and subsetting is a modification). */
|
||||
@font-face {
|
||||
font-family: 'GenOffice Gothic KR';
|
||||
src: url('./GenOfficeGothicKR-Regular-subset.woff2') format('woff2');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
/*
|
||||
* Arabic fallback: unmodified Noto Naskh/Sans Arabic subsets (Arabic blocks +
|
||||
* presentation forms + digits/punctuation). Without them, missing Arabic fonts
|
||||
@@ -399,6 +412,18 @@
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
/* Tamil: Word substitutes missing Tamil families with Latha; Chromium's macOS
|
||||
* fallback (Tamil Sangam MN) shapes ~27% narrower (M3 probe: sentence R 0.728,
|
||||
* space 0.39x) — too far for size-adjust (137% would inflate glyph ink). Noto
|
||||
* Sans Tamil with advances rewritten to Latha's (tools/build-tamil-font.py;
|
||||
* shaped sentence R 0.994, all probe sentences within ±2.3%). */
|
||||
@font-face {
|
||||
font-family: 'GenOffice Tamil';
|
||||
src: url('./GenOfficeTamil-Regular.woff2') format('woff2');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
/* Caladea has no box-drawing glyphs, so U+2500 separator rules fall to the CJK
|
||||
* subset at 1em fullwidth and an 80-char rule overflows the column (Word draws
|
||||
* it ~0.65em on a single line). Menlo/Consolas keep them ~0.6em. */
|
||||
|
||||
@@ -98,14 +98,25 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: '已接受所有修订',
|
||||
appAllRevisionsRejected: '已拒绝所有修订',
|
||||
appNoRevisionsToHandle: '没有可处理的修订',
|
||||
appRestrictEditing: '限制编辑',
|
||||
appUnrestrictEditing: '解除限制编辑',
|
||||
appProtectTitle: '保护文档',
|
||||
appProtectSecurity: '安全性',
|
||||
appProtectOpenPwd: '打开此文档的密码(可选)',
|
||||
appProtectModifyPwd: '修改此文档的密码(可选)',
|
||||
appProtectPwdKeepHint: '已设置的密码以圆点显示:保持不变则保留,清空后确定则移除(保存后生效)',
|
||||
appProtectSectionTitle: '保护',
|
||||
appProtectFor: '保护文档:',
|
||||
appProtectModeTracked: '修订',
|
||||
appProtectModeComments: '批注',
|
||||
appProtectModeReadOnly: '只读',
|
||||
appProtectModeForms: '窗体',
|
||||
appProtectUnlockPwd: '输入保护密码以更改或解除',
|
||||
appProtectPrivacy: '隐私',
|
||||
appProtectRemovePersonal: '保存时删除此文件中的作者和组织元数据',
|
||||
appProtectUpdated: '保护设置已更新,保存后生效',
|
||||
appModifyPwdTitle: '文档受写保护',
|
||||
appModifyPwdBody: '“{name}”设有修改密码。输入密码以编辑,或以只读方式打开。',
|
||||
appOpenReadOnly: '只读打开',
|
||||
appProtectPwdOptional: '保护密码(可留空)',
|
||||
appProtectPwdEnter: '输入保护密码',
|
||||
appProtectPwdHint: '带密码时,解除限制需输入同一密码(Word 兼容哈希)',
|
||||
appProtectionEnabledPwd: '已启用限制编辑(带密码)',
|
||||
appProtectionEnabled: '已启用限制编辑',
|
||||
appProtectionRemoved: '已解除限制编辑',
|
||||
appWrongPassword: '密码不正确',
|
||||
// Compare
|
||||
appCompareFailed: '比较失败: {error}',
|
||||
@@ -152,6 +163,14 @@ export const appStrings = defineStrings({
|
||||
appRedo: '恢复',
|
||||
// Start screen
|
||||
appStartOpening: '正在打开…',
|
||||
appDocPwdTitle: '文档已加密',
|
||||
appDocPwdBody: '“{name}”设有打开密码,请输入密码以打开。',
|
||||
appDocPwdLabel: '密码',
|
||||
appDocPwdWrong: '密码不正确,请重试',
|
||||
appDocPwdUnsupported:
|
||||
'无法解密此文档:加密方式不受支持(例如 WPS 账号加密),请在原软件中解除加密后重试',
|
||||
appEncConfirmLabel: '确认密码',
|
||||
appEncMismatch: '两次输入的密码不一致',
|
||||
appRecentDocs: '最近使用的文档',
|
||||
// View
|
||||
appSplitPaneLabel: '拆分窗格(只读预览,可独立滚动)',
|
||||
@@ -394,15 +413,26 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'All changes accepted',
|
||||
appAllRevisionsRejected: 'All changes rejected',
|
||||
appNoRevisionsToHandle: 'No tracked changes to process',
|
||||
appRestrictEditing: 'Restrict Editing',
|
||||
appUnrestrictEditing: 'Remove Editing Restrictions',
|
||||
appProtectTitle: 'Protect Document',
|
||||
appProtectSecurity: 'Security',
|
||||
appProtectOpenPwd: 'Password to open this document (optional)',
|
||||
appProtectModifyPwd: 'Password to modify this document (optional)',
|
||||
appProtectPwdKeepHint:
|
||||
'An existing password shows as dots: leave it unchanged to keep it, or clear the field to remove it (applies when saved)',
|
||||
appProtectSectionTitle: 'Protection',
|
||||
appProtectFor: 'Protect document for:',
|
||||
appProtectModeTracked: 'Tracked changes',
|
||||
appProtectModeComments: 'Comments',
|
||||
appProtectModeReadOnly: 'Read only',
|
||||
appProtectModeForms: 'Forms',
|
||||
appProtectUnlockPwd: 'Enter the protection password to change or remove it',
|
||||
appProtectPrivacy: 'Privacy',
|
||||
appProtectRemovePersonal: 'Remove author and organization metadata from this file on save',
|
||||
appProtectUpdated: 'Protection settings updated; they apply when the document is saved',
|
||||
appModifyPwdTitle: 'Write-Protected',
|
||||
appModifyPwdBody: '"{name}" has a password to modify. Enter it to edit, or open read-only.',
|
||||
appOpenReadOnly: 'Open Read-Only',
|
||||
appProtectPwdOptional: 'Protection password (optional)',
|
||||
appProtectPwdEnter: 'Enter the protection password',
|
||||
appProtectPwdHint:
|
||||
'With a password set, the same password is required to remove restrictions (Word-compatible hash)',
|
||||
appProtectionEnabledPwd: 'Editing restricted (with password)',
|
||||
appProtectionEnabled: 'Editing restricted',
|
||||
appProtectionRemoved: 'Editing restrictions removed',
|
||||
appWrongPassword: 'Incorrect password',
|
||||
appCompareFailed: 'Compare failed: {error}',
|
||||
appCompareResult: 'Compare Results',
|
||||
@@ -446,6 +476,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'Undo',
|
||||
appRedo: 'Redo',
|
||||
appStartOpening: 'Opening…',
|
||||
appDocPwdTitle: 'Password Protected',
|
||||
appDocPwdBody: '"{name}" is password protected. Enter the password to open it.',
|
||||
appDocPwdLabel: 'Password',
|
||||
appDocPwdWrong: 'The password is incorrect. Try again.',
|
||||
appDocPwdUnsupported:
|
||||
"This document can't be decrypted: its encryption scheme is not supported (e.g. WPS account encryption). Remove the encryption in the original app and retry.",
|
||||
appEncConfirmLabel: 'Confirm password',
|
||||
appEncMismatch: "The passwords don't match",
|
||||
appRecentDocs: 'Recent Documents',
|
||||
appSplitPaneLabel: 'Split pane (read-only preview, scrolls independently)',
|
||||
appRemoveSplit: 'Remove Split',
|
||||
@@ -691,15 +729,27 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'すべての変更を承諾しました',
|
||||
appAllRevisionsRejected: 'すべての変更を元に戻しました',
|
||||
appNoRevisionsToHandle: '処理する変更履歴はありません',
|
||||
appRestrictEditing: '編集の制限',
|
||||
appUnrestrictEditing: '編集の制限の解除',
|
||||
appProtectTitle: '文書の保護',
|
||||
appProtectSecurity: 'セキュリティ',
|
||||
appProtectOpenPwd: 'この文書を開くパスワード(省略可)',
|
||||
appProtectModifyPwd: 'この文書を変更するパスワード(省略可)',
|
||||
appProtectPwdKeepHint:
|
||||
'設定済みのパスワードはドットで表示されます。そのままにすると保持、欄を空にすると削除されます(保存時に適用)',
|
||||
appProtectSectionTitle: '保護',
|
||||
appProtectFor: '文書を保護:',
|
||||
appProtectModeTracked: '変更履歴',
|
||||
appProtectModeComments: 'コメント',
|
||||
appProtectModeReadOnly: '読み取り専用',
|
||||
appProtectModeForms: 'フォーム',
|
||||
appProtectUnlockPwd: '変更・解除には保護パスワードを入力してください',
|
||||
appProtectPrivacy: 'プライバシー',
|
||||
appProtectRemovePersonal: '保存時にこのファイルから作成者と組織のメタデータを削除する',
|
||||
appProtectUpdated: '保護設定を更新しました。保存時に適用されます',
|
||||
appModifyPwdTitle: '書き込みパスワード',
|
||||
appModifyPwdBody:
|
||||
'「{name}」には書き込みパスワードが設定されています。編集するにはパスワードを入力するか、読み取り専用で開いてください。',
|
||||
appOpenReadOnly: '読み取り専用で開く',
|
||||
appProtectPwdOptional: '保護パスワード(省略可)',
|
||||
appProtectPwdEnter: '保護パスワードを入力',
|
||||
appProtectPwdHint:
|
||||
'パスワードを設定した場合、制限の解除には同じパスワードが必要です(Word 互換ハッシュ)',
|
||||
appProtectionEnabledPwd: '編集の制限を有効にしました(パスワード付き)',
|
||||
appProtectionEnabled: '編集の制限を有効にしました',
|
||||
appProtectionRemoved: '編集の制限を解除しました',
|
||||
appWrongPassword: 'パスワードが正しくありません',
|
||||
// Compare
|
||||
appCompareFailed: '比較に失敗しました: {error}',
|
||||
@@ -749,6 +799,15 @@ export const appStrings = defineStrings({
|
||||
appRedo: 'やり直し',
|
||||
// Start screen
|
||||
appStartOpening: '開いています…',
|
||||
appDocPwdTitle: 'パスワード保護されています',
|
||||
appDocPwdBody:
|
||||
'「{name}」はパスワードで保護されています。開くにはパスワードを入力してください。',
|
||||
appDocPwdLabel: 'パスワード',
|
||||
appDocPwdWrong: 'パスワードが正しくありません。もう一度入力してください。',
|
||||
appDocPwdUnsupported:
|
||||
'この文書は復号できません:サポートされていない暗号化方式です(WPS アカウント暗号化など)。元のアプリで暗号化を解除してから再試行してください。',
|
||||
appEncConfirmLabel: 'パスワードの確認',
|
||||
appEncMismatch: 'パスワードが一致しません',
|
||||
appRecentDocs: '最近使った文書',
|
||||
// View
|
||||
appSplitPaneLabel: '分割ウィンドウ(読み取り専用プレビュー、独立してスクロール可能)',
|
||||
@@ -1005,15 +1064,27 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: '모든 변경 내용을 적용했습니다',
|
||||
appAllRevisionsRejected: '모든 변경 내용을 적용하지 않았습니다',
|
||||
appNoRevisionsToHandle: '처리할 변경 내용이 없습니다',
|
||||
appRestrictEditing: '편집 제한',
|
||||
appUnrestrictEditing: '편집 제한 해제',
|
||||
appProtectTitle: '문서 보호',
|
||||
appProtectSecurity: '보안',
|
||||
appProtectOpenPwd: '이 문서를 열 암호(선택)',
|
||||
appProtectModifyPwd: '이 문서를 수정할 암호(선택)',
|
||||
appProtectPwdKeepHint:
|
||||
'설정된 암호는 점으로 표시됩니다. 그대로 두면 유지되고, 지우면 제거됩니다(저장 시 적용)',
|
||||
appProtectSectionTitle: '보호',
|
||||
appProtectFor: '문서 보호 대상:',
|
||||
appProtectModeTracked: '변경 내용 추적',
|
||||
appProtectModeComments: '메모',
|
||||
appProtectModeReadOnly: '읽기 전용',
|
||||
appProtectModeForms: '양식',
|
||||
appProtectUnlockPwd: '변경하거나 해제하려면 보호 암호를 입력하세요',
|
||||
appProtectPrivacy: '개인 정보 보호',
|
||||
appProtectRemovePersonal: '저장할 때 이 파일에서 작성자 및 조직 메타데이터 제거',
|
||||
appProtectUpdated: '보호 설정이 업데이트되었습니다. 저장 후 적용됩니다',
|
||||
appModifyPwdTitle: '쓰기 보호됨',
|
||||
appModifyPwdBody:
|
||||
'"{name}"에 수정 암호가 설정되어 있습니다. 편집하려면 암호를 입력하거나 읽기 전용으로 여세요.',
|
||||
appOpenReadOnly: '읽기 전용으로 열기',
|
||||
appProtectPwdOptional: '보호 암호(생략 가능)',
|
||||
appProtectPwdEnter: '보호 암호 입력',
|
||||
appProtectPwdHint:
|
||||
'암호를 설정한 경우 제한을 해제하려면 같은 암호가 필요합니다(Word 호환 해시)',
|
||||
appProtectionEnabledPwd: '편집 제한을 설정했습니다(암호 사용)',
|
||||
appProtectionEnabled: '편집 제한을 설정했습니다',
|
||||
appProtectionRemoved: '편집 제한을 해제했습니다',
|
||||
appWrongPassword: '암호가 올바르지 않습니다',
|
||||
// Compare
|
||||
appCompareFailed: '비교 실패: {error}',
|
||||
@@ -1064,6 +1135,14 @@ export const appStrings = defineStrings({
|
||||
appRedo: '다시 실행',
|
||||
// Start screen
|
||||
appStartOpening: '여는 중…',
|
||||
appDocPwdTitle: '암호로 보호됨',
|
||||
appDocPwdBody: '"{name}"은(는) 암호로 보호되어 있습니다. 열려면 암호를 입력하세요.',
|
||||
appDocPwdLabel: '암호',
|
||||
appDocPwdWrong: '암호가 올바르지 않습니다. 다시 시도하세요.',
|
||||
appDocPwdUnsupported:
|
||||
'이 문서를 해독할 수 없습니다. 지원되지 않는 암호화 방식(예: WPS 계정 암호화)일 수 있습니다. 원본 앱에서 암호화를 해제한 후 다시 시도하세요.',
|
||||
appEncConfirmLabel: '암호 확인',
|
||||
appEncMismatch: '암호가 일치하지 않습니다',
|
||||
appRecentDocs: '최근에 사용한 문서',
|
||||
// View
|
||||
appSplitPaneLabel: '분할 창(읽기 전용 미리 보기, 독립 스크롤 가능)',
|
||||
@@ -1314,15 +1393,29 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'Toutes les modifications ont été acceptées',
|
||||
appAllRevisionsRejected: 'Toutes les modifications ont été refusées',
|
||||
appNoRevisionsToHandle: 'Aucune modification suivie à traiter',
|
||||
appRestrictEditing: 'Restreindre la modification',
|
||||
appUnrestrictEditing: 'Supprimer la restriction de modification',
|
||||
appProtectTitle: 'Protéger le document',
|
||||
appProtectSecurity: 'Sécurité',
|
||||
appProtectOpenPwd: 'Mot de passe pour ouvrir ce document (facultatif)',
|
||||
appProtectModifyPwd: 'Mot de passe pour modifier ce document (facultatif)',
|
||||
appProtectPwdKeepHint:
|
||||
'Un mot de passe existant s’affiche sous forme de points : laissez-le inchangé pour le conserver, ou videz le champ pour le supprimer (appliqué à l’enregistrement)',
|
||||
appProtectSectionTitle: 'Protection',
|
||||
appProtectFor: 'Protéger le document pour :',
|
||||
appProtectModeTracked: 'Suivi des modifications',
|
||||
appProtectModeComments: 'Commentaires',
|
||||
appProtectModeReadOnly: 'Lecture seule',
|
||||
appProtectModeForms: 'Formulaires',
|
||||
appProtectUnlockPwd: 'Entrez le mot de passe de protection pour la modifier ou la supprimer',
|
||||
appProtectPrivacy: 'Confidentialité',
|
||||
appProtectRemovePersonal:
|
||||
'Supprimer les métadonnées d’auteur et d’organisation de ce fichier lors de l’enregistrement',
|
||||
appProtectUpdated:
|
||||
'Paramètres de protection mis à jour ; appliqués à l’enregistrement du document',
|
||||
appModifyPwdTitle: 'Protégé en écriture',
|
||||
appModifyPwdBody:
|
||||
'« {name} » a un mot de passe de modification. Saisissez-le pour modifier, ou ouvrez en lecture seule.',
|
||||
appOpenReadOnly: 'Ouvrir en lecture seule',
|
||||
appProtectPwdOptional: 'Mot de passe de protection (facultatif)',
|
||||
appProtectPwdEnter: 'Entrez le mot de passe de protection',
|
||||
appProtectPwdHint:
|
||||
'Avec un mot de passe, le même mot de passe est requis pour supprimer la restriction (hachage compatible Word)',
|
||||
appProtectionEnabledPwd: 'Modification restreinte (avec mot de passe)',
|
||||
appProtectionEnabled: 'Modification restreinte',
|
||||
appProtectionRemoved: 'Restriction de modification supprimée',
|
||||
appWrongPassword: 'Mot de passe incorrect',
|
||||
appCompareFailed: 'Échec de la comparaison : {error}',
|
||||
appCompareResult: 'Résultats de la comparaison',
|
||||
@@ -1369,6 +1462,15 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'Annuler',
|
||||
appRedo: 'Rétablir',
|
||||
appStartOpening: 'Ouverture…',
|
||||
appDocPwdTitle: 'Protégé par mot de passe',
|
||||
appDocPwdBody:
|
||||
'« {name} » est protégé par un mot de passe. Saisissez le mot de passe pour l’ouvrir.',
|
||||
appDocPwdLabel: 'Mot de passe',
|
||||
appDocPwdWrong: 'Le mot de passe est incorrect. Réessayez.',
|
||||
appDocPwdUnsupported:
|
||||
'Impossible de déchiffrer ce document : son chiffrement n’est pas pris en charge (p. ex. chiffrement par compte WPS). Supprimez le chiffrement dans l’application d’origine, puis réessayez.',
|
||||
appEncConfirmLabel: 'Confirmer le mot de passe',
|
||||
appEncMismatch: 'Les mots de passe ne correspondent pas',
|
||||
appRecentDocs: 'Documents récents',
|
||||
appSplitPaneLabel: 'Volet fractionné (aperçu en lecture seule, défilement indépendant)',
|
||||
appRemoveSplit: 'Annuler le fractionnement',
|
||||
@@ -1608,15 +1710,29 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'Alle Änderungen angenommen',
|
||||
appAllRevisionsRejected: 'Alle Änderungen abgelehnt',
|
||||
appNoRevisionsToHandle: 'Keine nachverfolgten Änderungen zu verarbeiten',
|
||||
appRestrictEditing: 'Bearbeitung einschränken',
|
||||
appUnrestrictEditing: 'Bearbeitungseinschränkungen aufheben',
|
||||
appProtectTitle: 'Dokument schützen',
|
||||
appProtectSecurity: 'Sicherheit',
|
||||
appProtectOpenPwd: 'Kennwort zum Öffnen dieses Dokuments (optional)',
|
||||
appProtectModifyPwd: 'Kennwort zum Ändern dieses Dokuments (optional)',
|
||||
appProtectPwdKeepHint:
|
||||
'Ein vorhandenes Kennwort wird als Punkte angezeigt: unverändert lassen, um es zu behalten, oder das Feld leeren, um es zu entfernen (wird beim Speichern angewendet)',
|
||||
appProtectSectionTitle: 'Schutz',
|
||||
appProtectFor: 'Dokument schützen für:',
|
||||
appProtectModeTracked: 'Änderungen nachverfolgen',
|
||||
appProtectModeComments: 'Kommentare',
|
||||
appProtectModeReadOnly: 'Schreibgeschützt',
|
||||
appProtectModeForms: 'Formulare',
|
||||
appProtectUnlockPwd: 'Geben Sie das Schutzkennwort ein, um ihn zu ändern oder aufzuheben',
|
||||
appProtectPrivacy: 'Datenschutz',
|
||||
appProtectRemovePersonal:
|
||||
'Autoren- und Organisationsmetadaten beim Speichern aus dieser Datei entfernen',
|
||||
appProtectUpdated:
|
||||
'Schutzeinstellungen aktualisiert; sie werden beim Speichern des Dokuments angewendet',
|
||||
appModifyPwdTitle: 'Schreibgeschützt',
|
||||
appModifyPwdBody:
|
||||
'„{name}“ hat ein Kennwort zum Ändern. Geben Sie es ein, um zu bearbeiten, oder öffnen Sie das Dokument schreibgeschützt.',
|
||||
appOpenReadOnly: 'Schreibgeschützt öffnen',
|
||||
appProtectPwdOptional: 'Schutzkennwort (optional)',
|
||||
appProtectPwdEnter: 'Schutzkennwort eingeben',
|
||||
appProtectPwdHint:
|
||||
'Mit Kennwort ist zum Aufheben der Einschränkung dasselbe Kennwort erforderlich (Word-kompatibler Hash)',
|
||||
appProtectionEnabledPwd: 'Bearbeitung eingeschränkt (mit Kennwort)',
|
||||
appProtectionEnabled: 'Bearbeitung eingeschränkt',
|
||||
appProtectionRemoved: 'Bearbeitungseinschränkungen aufgehoben',
|
||||
appWrongPassword: 'Falsches Kennwort',
|
||||
appCompareFailed: 'Vergleich fehlgeschlagen: {error}',
|
||||
appCompareResult: 'Vergleichsergebnisse',
|
||||
@@ -1663,6 +1779,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'Rückgängig',
|
||||
appRedo: 'Wiederholen',
|
||||
appStartOpening: 'Wird geöffnet…',
|
||||
appDocPwdTitle: 'Kennwortgeschützt',
|
||||
appDocPwdBody: '„{name}“ ist kennwortgeschützt. Geben Sie das Kennwort ein, um es zu öffnen.',
|
||||
appDocPwdLabel: 'Kennwort',
|
||||
appDocPwdWrong: 'Das Kennwort ist falsch. Versuchen Sie es erneut.',
|
||||
appDocPwdUnsupported:
|
||||
'Dieses Dokument kann nicht entschlüsselt werden: Die Verschlüsselung wird nicht unterstützt (z. B. WPS-Konto-Verschlüsselung). Entfernen Sie die Verschlüsselung in der Ursprungsanwendung und versuchen Sie es erneut.',
|
||||
appEncConfirmLabel: 'Kennwort bestätigen',
|
||||
appEncMismatch: 'Die Kennwörter stimmen nicht überein',
|
||||
appRecentDocs: 'Zuletzt verwendete Dokumente',
|
||||
appSplitPaneLabel: 'Geteilter Bereich (schreibgeschützte Vorschau, unabhängig scrollbar)',
|
||||
appRemoveSplit: 'Teilung aufheben',
|
||||
@@ -1903,15 +2027,28 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'Se aceptaron todos los cambios',
|
||||
appAllRevisionsRejected: 'Se rechazaron todos los cambios',
|
||||
appNoRevisionsToHandle: 'No hay cambios registrados para procesar',
|
||||
appRestrictEditing: 'Restringir edición',
|
||||
appUnrestrictEditing: 'Quitar restricciones de edición',
|
||||
appProtectTitle: 'Proteger documento',
|
||||
appProtectSecurity: 'Seguridad',
|
||||
appProtectOpenPwd: 'Contraseña para abrir este documento (opcional)',
|
||||
appProtectModifyPwd: 'Contraseña para modificar este documento (opcional)',
|
||||
appProtectPwdKeepHint:
|
||||
'Una contraseña existente se muestra como puntos: déjela sin cambios para conservarla o vacíe el campo para quitarla (se aplica al guardar)',
|
||||
appProtectSectionTitle: 'Protección',
|
||||
appProtectFor: 'Proteger el documento para:',
|
||||
appProtectModeTracked: 'Control de cambios',
|
||||
appProtectModeComments: 'Comentarios',
|
||||
appProtectModeReadOnly: 'Solo lectura',
|
||||
appProtectModeForms: 'Formularios',
|
||||
appProtectUnlockPwd: 'Escriba la contraseña de protección para cambiarla o quitarla',
|
||||
appProtectPrivacy: 'Privacidad',
|
||||
appProtectRemovePersonal:
|
||||
'Quitar los metadatos de autor y organización de este archivo al guardar',
|
||||
appProtectUpdated: 'Configuración de protección actualizada; se aplica al guardar el documento',
|
||||
appModifyPwdTitle: 'Protegido contra escritura',
|
||||
appModifyPwdBody:
|
||||
'«{name}» tiene una contraseña de modificación. Escríbala para editar o ábralo como solo lectura.',
|
||||
appOpenReadOnly: 'Abrir como solo lectura',
|
||||
appProtectPwdOptional: 'Contraseña de protección (opcional)',
|
||||
appProtectPwdEnter: 'Escriba la contraseña de protección',
|
||||
appProtectPwdHint:
|
||||
'Con contraseña, se requiere la misma contraseña para quitar las restricciones (hash compatible con Word)',
|
||||
appProtectionEnabledPwd: 'Edición restringida (con contraseña)',
|
||||
appProtectionEnabled: 'Edición restringida',
|
||||
appProtectionRemoved: 'Restricciones de edición quitadas',
|
||||
appWrongPassword: 'Contraseña incorrecta',
|
||||
appCompareFailed: 'Error al comparar: {error}',
|
||||
appCompareResult: 'Resultados de la comparación',
|
||||
@@ -1956,6 +2093,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'Deshacer',
|
||||
appRedo: 'Rehacer',
|
||||
appStartOpening: 'Abriendo…',
|
||||
appDocPwdTitle: 'Protegido con contraseña',
|
||||
appDocPwdBody: '«{name}» está protegido con contraseña. Escriba la contraseña para abrirlo.',
|
||||
appDocPwdLabel: 'Contraseña',
|
||||
appDocPwdWrong: 'La contraseña es incorrecta. Inténtelo de nuevo.',
|
||||
appDocPwdUnsupported:
|
||||
'No se puede descifrar este documento: su cifrado no es compatible (p. ej., cifrado por cuenta de WPS). Quite el cifrado en la aplicación original y vuelva a intentarlo.',
|
||||
appEncConfirmLabel: 'Confirmar contraseña',
|
||||
appEncMismatch: 'Las contraseñas no coinciden',
|
||||
appRecentDocs: 'Documentos recientes',
|
||||
appSplitPaneLabel:
|
||||
'Panel dividido (vista previa de solo lectura, desplazamiento independiente)',
|
||||
@@ -2191,15 +2336,27 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'ยอมรับการเปลี่ยนแปลงทั้งหมดแล้ว',
|
||||
appAllRevisionsRejected: 'ปฏิเสธการเปลี่ยนแปลงทั้งหมดแล้ว',
|
||||
appNoRevisionsToHandle: 'ไม่มีการเปลี่ยนแปลงที่ติดตามให้จัดการ',
|
||||
appRestrictEditing: 'จำกัดการแก้ไข',
|
||||
appUnrestrictEditing: 'ยกเลิกการจำกัดการแก้ไข',
|
||||
appProtectTitle: 'ป้องกันเอกสาร',
|
||||
appProtectSecurity: 'ความปลอดภัย',
|
||||
appProtectOpenPwd: 'รหัสผ่านสำหรับเปิดเอกสารนี้ (ไม่บังคับ)',
|
||||
appProtectModifyPwd: 'รหัสผ่านสำหรับแก้ไขเอกสารนี้ (ไม่บังคับ)',
|
||||
appProtectPwdKeepHint:
|
||||
'รหัสผ่านที่ตั้งไว้จะแสดงเป็นจุด: ปล่อยไว้ตามเดิมเพื่อคงไว้ หรือล้างช่องเพื่อลบ (มีผลเมื่อบันทึก)',
|
||||
appProtectSectionTitle: 'การป้องกัน',
|
||||
appProtectFor: 'ป้องกันเอกสารสำหรับ:',
|
||||
appProtectModeTracked: 'การติดตามการเปลี่ยนแปลง',
|
||||
appProtectModeComments: 'ข้อคิดเห็น',
|
||||
appProtectModeReadOnly: 'อ่านอย่างเดียว',
|
||||
appProtectModeForms: 'ฟอร์ม',
|
||||
appProtectUnlockPwd: 'ใส่รหัสผ่านป้องกันเพื่อเปลี่ยนหรือยกเลิก',
|
||||
appProtectPrivacy: 'ความเป็นส่วนตัว',
|
||||
appProtectRemovePersonal: 'ลบข้อมูลเมตาของผู้เขียนและองค์กรออกจากไฟล์นี้เมื่อบันทึก',
|
||||
appProtectUpdated: 'อัปเดตการตั้งค่าการป้องกันแล้ว มีผลเมื่อบันทึกเอกสาร',
|
||||
appModifyPwdTitle: 'มีการป้องกันการเขียน',
|
||||
appModifyPwdBody:
|
||||
'"{name}" มีรหัสผ่านสำหรับแก้ไข ใส่รหัสผ่านเพื่อแก้ไข หรือเปิดแบบอ่านอย่างเดียว',
|
||||
appOpenReadOnly: 'เปิดแบบอ่านอย่างเดียว',
|
||||
appProtectPwdOptional: 'รหัสผ่านป้องกัน (เว้นว่างได้)',
|
||||
appProtectPwdEnter: 'ใส่รหัสผ่านป้องกัน',
|
||||
appProtectPwdHint:
|
||||
'หากตั้งรหัสผ่าน จะต้องใช้รหัสผ่านเดียวกันเพื่อยกเลิกการจำกัด (แฮชที่เข้ากันได้กับ Word)',
|
||||
appProtectionEnabledPwd: 'เปิดใช้งานการจำกัดการแก้ไขแล้ว (มีรหัสผ่าน)',
|
||||
appProtectionEnabled: 'เปิดใช้งานการจำกัดการแก้ไขแล้ว',
|
||||
appProtectionRemoved: 'ยกเลิกการจำกัดการแก้ไขแล้ว',
|
||||
appWrongPassword: 'รหัสผ่านไม่ถูกต้อง',
|
||||
appCompareFailed: 'เปรียบเทียบไม่สำเร็จ: {error}',
|
||||
appCompareResult: 'ผลการเปรียบเทียบ',
|
||||
@@ -2243,6 +2400,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'เลิกทำ',
|
||||
appRedo: 'ทำซ้ำ',
|
||||
appStartOpening: 'กำลังเปิด…',
|
||||
appDocPwdTitle: 'มีการป้องกันด้วยรหัสผ่าน',
|
||||
appDocPwdBody: '"{name}" ได้รับการป้องกันด้วยรหัสผ่าน โปรดป้อนรหัสผ่านเพื่อเปิด',
|
||||
appDocPwdLabel: 'รหัสผ่าน',
|
||||
appDocPwdWrong: 'รหัสผ่านไม่ถูกต้อง โปรดลองอีกครั้ง',
|
||||
appDocPwdUnsupported:
|
||||
'ไม่สามารถถอดรหัสเอกสารนี้ได้: รูปแบบการเข้ารหัสไม่รองรับ (เช่น การเข้ารหัสด้วยบัญชี WPS) โปรดยกเลิกการเข้ารหัสในแอปต้นทางแล้วลองใหม่',
|
||||
appEncConfirmLabel: 'ยืนยันรหัสผ่าน',
|
||||
appEncMismatch: 'รหัสผ่านไม่ตรงกัน',
|
||||
appRecentDocs: 'เอกสารล่าสุด',
|
||||
appSplitPaneLabel: 'แยกหน้าต่าง (ตัวอย่างแบบอ่านอย่างเดียว เลื่อนแยกกันได้)',
|
||||
appRemoveSplit: 'ยกเลิกการแยก',
|
||||
@@ -2478,15 +2643,27 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'Semua perubahan diterima',
|
||||
appAllRevisionsRejected: 'Semua perubahan ditolak',
|
||||
appNoRevisionsToHandle: 'Tidak ada perubahan terlacak untuk diproses',
|
||||
appRestrictEditing: 'Batasi Pengeditan',
|
||||
appUnrestrictEditing: 'Hapus Pembatasan Pengeditan',
|
||||
appProtectTitle: 'Proteksi Dokumen',
|
||||
appProtectSecurity: 'Keamanan',
|
||||
appProtectOpenPwd: 'Kata sandi untuk membuka dokumen ini (opsional)',
|
||||
appProtectModifyPwd: 'Kata sandi untuk mengubah dokumen ini (opsional)',
|
||||
appProtectPwdKeepHint:
|
||||
'Kata sandi yang sudah ada ditampilkan sebagai titik: biarkan untuk mempertahankannya, atau kosongkan kolom untuk menghapusnya (berlaku saat disimpan)',
|
||||
appProtectSectionTitle: 'Proteksi',
|
||||
appProtectFor: 'Proteksi dokumen untuk:',
|
||||
appProtectModeTracked: 'Lacak perubahan',
|
||||
appProtectModeComments: 'Komentar',
|
||||
appProtectModeReadOnly: 'Hanya baca',
|
||||
appProtectModeForms: 'Formulir',
|
||||
appProtectUnlockPwd: 'Masukkan kata sandi proteksi untuk mengubah atau menghapusnya',
|
||||
appProtectPrivacy: 'Privasi',
|
||||
appProtectRemovePersonal: 'Hapus metadata penulis dan organisasi dari file ini saat menyimpan',
|
||||
appProtectUpdated: 'Pengaturan proteksi diperbarui; berlaku saat dokumen disimpan',
|
||||
appModifyPwdTitle: 'Terproteksi dari Penulisan',
|
||||
appModifyPwdBody:
|
||||
'"{name}" memiliki kata sandi untuk mengubah. Masukkan untuk mengedit, atau buka hanya-baca.',
|
||||
appOpenReadOnly: 'Buka Hanya-Baca',
|
||||
appProtectPwdOptional: 'Kata sandi proteksi (opsional)',
|
||||
appProtectPwdEnter: 'Masukkan kata sandi proteksi',
|
||||
appProtectPwdHint:
|
||||
'Jika kata sandi ditetapkan, kata sandi yang sama diperlukan untuk menghapus pembatasan (hash yang kompatibel dengan Word)',
|
||||
appProtectionEnabledPwd: 'Pembatasan pengeditan diaktifkan (dengan kata sandi)',
|
||||
appProtectionEnabled: 'Pembatasan pengeditan diaktifkan',
|
||||
appProtectionRemoved: 'Pembatasan pengeditan dihapus',
|
||||
appWrongPassword: 'Kata sandi salah',
|
||||
appCompareFailed: 'Gagal membandingkan: {error}',
|
||||
appCompareResult: 'Hasil Perbandingan',
|
||||
@@ -2530,6 +2707,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'Urungkan',
|
||||
appRedo: 'Ulangi',
|
||||
appStartOpening: 'Membuka…',
|
||||
appDocPwdTitle: 'Dilindungi Kata Sandi',
|
||||
appDocPwdBody: '"{name}" dilindungi kata sandi. Masukkan kata sandi untuk membukanya.',
|
||||
appDocPwdLabel: 'Kata sandi',
|
||||
appDocPwdWrong: 'Kata sandi salah. Coba lagi.',
|
||||
appDocPwdUnsupported:
|
||||
'Dokumen ini tidak dapat didekripsi: skema enkripsinya tidak didukung (mis. enkripsi akun WPS). Hapus enkripsi di aplikasi asal lalu coba lagi.',
|
||||
appEncConfirmLabel: 'Konfirmasi kata sandi',
|
||||
appEncMismatch: 'Kata sandi tidak cocok',
|
||||
appRecentDocs: 'Dokumen Terbaru',
|
||||
appSplitPaneLabel: 'Panel terpisah (pratinjau baca-saja, dapat digulir secara independen)',
|
||||
appRemoveSplit: 'Hapus Pemisahan',
|
||||
@@ -2767,15 +2952,28 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'Все изменения приняты',
|
||||
appAllRevisionsRejected: 'Все изменения отклонены',
|
||||
appNoRevisionsToHandle: 'Нет записанных исправлений для обработки',
|
||||
appRestrictEditing: 'Ограничить редактирование',
|
||||
appUnrestrictEditing: 'Снять ограничения редактирования',
|
||||
appProtectTitle: 'Защитить документ',
|
||||
appProtectSecurity: 'Безопасность',
|
||||
appProtectOpenPwd: 'Пароль для открытия этого документа (необязательно)',
|
||||
appProtectModifyPwd: 'Пароль для изменения этого документа (необязательно)',
|
||||
appProtectPwdKeepHint:
|
||||
'Существующий пароль отображается точками: оставьте без изменений, чтобы сохранить его, или очистите поле, чтобы удалить (применяется при сохранении)',
|
||||
appProtectSectionTitle: 'Защита',
|
||||
appProtectFor: 'Защитить документ для:',
|
||||
appProtectModeTracked: 'Отслеживание изменений',
|
||||
appProtectModeComments: 'Примечания',
|
||||
appProtectModeReadOnly: 'Только чтение',
|
||||
appProtectModeForms: 'Формы',
|
||||
appProtectUnlockPwd: 'Введите пароль защиты, чтобы изменить или снять её',
|
||||
appProtectPrivacy: 'Конфиденциальность',
|
||||
appProtectRemovePersonal:
|
||||
'Удалять метаданные автора и организации из этого файла при сохранении',
|
||||
appProtectUpdated: 'Параметры защиты обновлены; применяются при сохранении документа',
|
||||
appModifyPwdTitle: 'Защита от записи',
|
||||
appModifyPwdBody:
|
||||
'«{name}» имеет пароль для изменения. Введите его для редактирования или откройте только для чтения.',
|
||||
appOpenReadOnly: 'Открыть только для чтения',
|
||||
appProtectPwdOptional: 'Пароль защиты (необязательно)',
|
||||
appProtectPwdEnter: 'Введите пароль защиты',
|
||||
appProtectPwdHint:
|
||||
'Если задан пароль, для снятия ограничений потребуется тот же пароль (хэш, совместимый с Word)',
|
||||
appProtectionEnabledPwd: 'Ограничение редактирования включено (с паролем)',
|
||||
appProtectionEnabled: 'Ограничение редактирования включено',
|
||||
appProtectionRemoved: 'Ограничения редактирования сняты',
|
||||
appWrongPassword: 'Неверный пароль',
|
||||
appCompareFailed: 'Не удалось сравнить: {error}',
|
||||
appCompareResult: 'Результаты сравнения',
|
||||
@@ -2820,6 +3018,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'Отменить',
|
||||
appRedo: 'Вернуть',
|
||||
appStartOpening: 'Открытие…',
|
||||
appDocPwdTitle: 'Защищено паролем',
|
||||
appDocPwdBody: '«{name}» защищён паролем. Введите пароль, чтобы открыть документ.',
|
||||
appDocPwdLabel: 'Пароль',
|
||||
appDocPwdWrong: 'Неверный пароль. Попробуйте ещё раз.',
|
||||
appDocPwdUnsupported:
|
||||
'Не удаётся расшифровать документ: способ шифрования не поддерживается (например, шифрование через аккаунт WPS). Снимите шифрование в исходном приложении и повторите попытку.',
|
||||
appEncConfirmLabel: 'Подтверждение пароля',
|
||||
appEncMismatch: 'Пароли не совпадают',
|
||||
appRecentDocs: 'Последние документы',
|
||||
appSplitPaneLabel: 'Разделенная область (просмотр только для чтения, независимая прокрутка)',
|
||||
appRemoveSplit: 'Снять разделение',
|
||||
@@ -3055,15 +3261,26 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'تم قبول كل التغييرات',
|
||||
appAllRevisionsRejected: 'تم رفض كل التغييرات',
|
||||
appNoRevisionsToHandle: 'لا توجد تغييرات متعقبة للمعالجة',
|
||||
appRestrictEditing: 'تقييد التحرير',
|
||||
appUnrestrictEditing: 'إزالة قيود التحرير',
|
||||
appProtectTitle: 'حماية المستند',
|
||||
appProtectSecurity: 'الأمان',
|
||||
appProtectOpenPwd: 'كلمة مرور لفتح هذا المستند (اختيارية)',
|
||||
appProtectModifyPwd: 'كلمة مرور لتعديل هذا المستند (اختيارية)',
|
||||
appProtectPwdKeepHint:
|
||||
'تظهر كلمة المرور الحالية كنقاط: اتركها دون تغيير للاحتفاظ بها، أو امسح الحقل لإزالتها (يُطبَّق عند الحفظ)',
|
||||
appProtectSectionTitle: 'الحماية',
|
||||
appProtectFor: 'حماية المستند من أجل:',
|
||||
appProtectModeTracked: 'تعقُّب التغييرات',
|
||||
appProtectModeComments: 'التعليقات',
|
||||
appProtectModeReadOnly: 'للقراءة فقط',
|
||||
appProtectModeForms: 'النماذج',
|
||||
appProtectUnlockPwd: 'أدخل كلمة مرور الحماية لتغييرها أو إزالتها',
|
||||
appProtectPrivacy: 'الخصوصية',
|
||||
appProtectRemovePersonal: 'إزالة بيانات تعريف المؤلف والمؤسسة من هذا الملف عند الحفظ',
|
||||
appProtectUpdated: 'تم تحديث إعدادات الحماية؛ تُطبَّق عند حفظ المستند',
|
||||
appModifyPwdTitle: 'محمي ضد الكتابة',
|
||||
appModifyPwdBody: 'يحتوي "{name}" على كلمة مرور للتعديل. أدخلها للتحرير، أو افتحه للقراءة فقط.',
|
||||
appOpenReadOnly: 'فتح للقراءة فقط',
|
||||
appProtectPwdOptional: 'كلمة مرور الحماية (اختيارية)',
|
||||
appProtectPwdEnter: 'أدخل كلمة مرور الحماية',
|
||||
appProtectPwdHint:
|
||||
'عند تعيين كلمة مرور، تلزم كلمة المرور نفسها لإزالة القيود (تجزئة متوافقة مع Word)',
|
||||
appProtectionEnabledPwd: 'تم تمكين تقييد التحرير (بكلمة مرور)',
|
||||
appProtectionEnabled: 'تم تمكين تقييد التحرير',
|
||||
appProtectionRemoved: 'تمت إزالة قيود التحرير',
|
||||
appWrongPassword: 'كلمة المرور غير صحيحة',
|
||||
appCompareFailed: 'فشلت المقارنة: {error}',
|
||||
appCompareResult: 'نتائج المقارنة',
|
||||
@@ -3106,6 +3323,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'تراجع',
|
||||
appRedo: 'إعادة',
|
||||
appStartOpening: 'جارٍ الفتح…',
|
||||
appDocPwdTitle: 'محمي بكلمة مرور',
|
||||
appDocPwdBody: '"{name}" محمي بكلمة مرور. أدخل كلمة المرور لفتحه.',
|
||||
appDocPwdLabel: 'كلمة المرور',
|
||||
appDocPwdWrong: 'كلمة المرور غير صحيحة. حاول مرة أخرى.',
|
||||
appDocPwdUnsupported:
|
||||
'يتعذر فك تشفير هذا المستند: أسلوب التشفير غير مدعوم (مثل تشفير حساب WPS). أزل التشفير في التطبيق الأصلي ثم أعد المحاولة.',
|
||||
appEncConfirmLabel: 'تأكيد كلمة المرور',
|
||||
appEncMismatch: 'كلمتا المرور غير متطابقتين',
|
||||
appRecentDocs: 'المستندات الأخيرة',
|
||||
appSplitPaneLabel: 'جزء مقسوم (معاينة للقراءة فقط، تمرير مستقل)',
|
||||
appRemoveSplit: 'إزالة التقسيم',
|
||||
@@ -3342,15 +3567,27 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'Todas as alterações aceitas',
|
||||
appAllRevisionsRejected: 'Todas as alterações rejeitadas',
|
||||
appNoRevisionsToHandle: 'Nenhuma alteração controlada a processar',
|
||||
appRestrictEditing: 'Restringir edição',
|
||||
appUnrestrictEditing: 'Remover restrições de edição',
|
||||
appProtectTitle: 'Proteger documento',
|
||||
appProtectSecurity: 'Segurança',
|
||||
appProtectOpenPwd: 'Senha para abrir este documento (opcional)',
|
||||
appProtectModifyPwd: 'Senha para modificar este documento (opcional)',
|
||||
appProtectPwdKeepHint:
|
||||
'Uma senha existente é exibida como pontos: deixe-a inalterada para mantê-la ou limpe o campo para removê-la (aplica-se ao salvar)',
|
||||
appProtectSectionTitle: 'Proteção',
|
||||
appProtectFor: 'Proteger o documento para:',
|
||||
appProtectModeTracked: 'Controlar alterações',
|
||||
appProtectModeComments: 'Comentários',
|
||||
appProtectModeReadOnly: 'Somente leitura',
|
||||
appProtectModeForms: 'Formulários',
|
||||
appProtectUnlockPwd: 'Digite a senha de proteção para alterá-la ou removê-la',
|
||||
appProtectPrivacy: 'Privacidade',
|
||||
appProtectRemovePersonal: 'Remover metadados de autor e organização deste arquivo ao salvar',
|
||||
appProtectUpdated: 'Configurações de proteção atualizadas; aplicam-se ao salvar o documento',
|
||||
appModifyPwdTitle: 'Protegido contra gravação',
|
||||
appModifyPwdBody:
|
||||
'"{name}" tem uma senha de modificação. Digite-a para editar ou abra como somente leitura.',
|
||||
appOpenReadOnly: 'Abrir como somente leitura',
|
||||
appProtectPwdOptional: 'Senha de proteção (opcional)',
|
||||
appProtectPwdEnter: 'Digite a senha de proteção',
|
||||
appProtectPwdHint:
|
||||
'Com senha definida, a mesma senha é necessária para remover as restrições (hash compatível com o Word)',
|
||||
appProtectionEnabledPwd: 'Edição restrita (com senha)',
|
||||
appProtectionEnabled: 'Edição restrita',
|
||||
appProtectionRemoved: 'Restrições de edição removidas',
|
||||
appWrongPassword: 'Senha incorreta',
|
||||
appCompareFailed: 'Falha na comparação: {error}',
|
||||
appCompareResult: 'Resultados da comparação',
|
||||
@@ -3395,6 +3632,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'Desfazer',
|
||||
appRedo: 'Refazer',
|
||||
appStartOpening: 'Abrindo…',
|
||||
appDocPwdTitle: 'Protegido por senha',
|
||||
appDocPwdBody: '"{name}" está protegido por senha. Digite a senha para abri-lo.',
|
||||
appDocPwdLabel: 'Senha',
|
||||
appDocPwdWrong: 'A senha está incorreta. Tente novamente.',
|
||||
appDocPwdUnsupported:
|
||||
'Não é possível descriptografar este documento: o esquema de criptografia não é compatível (ex.: criptografia por conta WPS). Remova a criptografia no aplicativo original e tente novamente.',
|
||||
appEncConfirmLabel: 'Confirmar senha',
|
||||
appEncMismatch: 'As senhas não coincidem',
|
||||
appRecentDocs: 'Documentos recentes',
|
||||
appSplitPaneLabel: 'Painel dividido (visualização somente leitura, rolagem independente)',
|
||||
appRemoveSplit: 'Remover divisão',
|
||||
@@ -3630,15 +3875,29 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'Tutte le modifiche accettate',
|
||||
appAllRevisionsRejected: 'Tutte le modifiche rifiutate',
|
||||
appNoRevisionsToHandle: 'Nessuna revisione da elaborare',
|
||||
appRestrictEditing: 'Limita modifica',
|
||||
appUnrestrictEditing: 'Rimuovi limitazioni di modifica',
|
||||
appProtectTitle: 'Proteggi documento',
|
||||
appProtectSecurity: 'Sicurezza',
|
||||
appProtectOpenPwd: 'Password per aprire questo documento (facoltativa)',
|
||||
appProtectModifyPwd: 'Password per modificare questo documento (facoltativa)',
|
||||
appProtectPwdKeepHint:
|
||||
'Una password esistente è mostrata come puntini: lasciala invariata per mantenerla o svuota il campo per rimuoverla (applicata al salvataggio)',
|
||||
appProtectSectionTitle: 'Protezione',
|
||||
appProtectFor: 'Proteggi documento per:',
|
||||
appProtectModeTracked: 'Revisioni',
|
||||
appProtectModeComments: 'Commenti',
|
||||
appProtectModeReadOnly: 'Sola lettura',
|
||||
appProtectModeForms: 'Moduli',
|
||||
appProtectUnlockPwd: 'Inserisci la password di protezione per modificarla o rimuoverla',
|
||||
appProtectPrivacy: 'Privacy',
|
||||
appProtectRemovePersonal:
|
||||
'Rimuovi i metadati di autore e organizzazione da questo file al salvataggio',
|
||||
appProtectUpdated:
|
||||
'Impostazioni di protezione aggiornate; applicate al salvataggio del documento',
|
||||
appModifyPwdTitle: 'Protetto da scrittura',
|
||||
appModifyPwdBody:
|
||||
'"{name}" ha una password di modifica. Inseriscila per modificare o apri in sola lettura.',
|
||||
appOpenReadOnly: 'Apri in sola lettura',
|
||||
appProtectPwdOptional: 'Password di protezione (facoltativa)',
|
||||
appProtectPwdEnter: 'Inserisci la password di protezione',
|
||||
appProtectPwdHint:
|
||||
'Con una password impostata, per rimuovere le limitazioni è richiesta la stessa password (hash compatibile con Word)',
|
||||
appProtectionEnabledPwd: 'Modifica limitata (con password)',
|
||||
appProtectionEnabled: 'Modifica limitata',
|
||||
appProtectionRemoved: 'Limitazioni di modifica rimosse',
|
||||
appWrongPassword: 'Password errata',
|
||||
appCompareFailed: 'Confronto non riuscito: {error}',
|
||||
appCompareResult: 'Risultati del confronto',
|
||||
@@ -3683,6 +3942,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'Annulla',
|
||||
appRedo: 'Ripristina',
|
||||
appStartOpening: 'Apertura…',
|
||||
appDocPwdTitle: 'Protetto da password',
|
||||
appDocPwdBody: '"{name}" è protetto da password. Inserisci la password per aprirlo.',
|
||||
appDocPwdLabel: 'Password',
|
||||
appDocPwdWrong: 'La password non è corretta. Riprova.',
|
||||
appDocPwdUnsupported:
|
||||
'Impossibile decrittografare il documento: lo schema di crittografia non è supportato (ad es. crittografia con account WPS). Rimuovi la crittografia nell’app originale e riprova.',
|
||||
appEncConfirmLabel: 'Conferma password',
|
||||
appEncMismatch: 'Le password non corrispondono',
|
||||
appRecentDocs: 'Documenti recenti',
|
||||
appSplitPaneLabel: 'Riquadro diviso (anteprima in sola lettura, scorrimento indipendente)',
|
||||
appRemoveSplit: 'Rimuovi divisione',
|
||||
@@ -3920,15 +4187,28 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'Zaakceptowano wszystkie zmiany',
|
||||
appAllRevisionsRejected: 'Odrzucono wszystkie zmiany',
|
||||
appNoRevisionsToHandle: 'Brak śledzonych zmian do przetworzenia',
|
||||
appRestrictEditing: 'Ogranicz edytowanie',
|
||||
appUnrestrictEditing: 'Usuń ograniczenia edytowania',
|
||||
appProtectTitle: 'Chroń dokument',
|
||||
appProtectSecurity: 'Zabezpieczenia',
|
||||
appProtectOpenPwd: 'Hasło do otwarcia tego dokumentu (opcjonalne)',
|
||||
appProtectModifyPwd: 'Hasło do modyfikacji tego dokumentu (opcjonalne)',
|
||||
appProtectPwdKeepHint:
|
||||
'Istniejące hasło jest wyświetlane jako kropki: pozostaw bez zmian, aby je zachować, lub wyczyść pole, aby je usunąć (zastosowane przy zapisie)',
|
||||
appProtectSectionTitle: 'Ochrona',
|
||||
appProtectFor: 'Chroń dokument dla:',
|
||||
appProtectModeTracked: 'Śledzenie zmian',
|
||||
appProtectModeComments: 'Komentarze',
|
||||
appProtectModeReadOnly: 'Tylko do odczytu',
|
||||
appProtectModeForms: 'Formularze',
|
||||
appProtectUnlockPwd: 'Wprowadź hasło ochrony, aby ją zmienić lub usunąć',
|
||||
appProtectPrivacy: 'Prywatność',
|
||||
appProtectRemovePersonal: 'Usuwaj metadane autora i organizacji z tego pliku przy zapisywaniu',
|
||||
appProtectUpdated:
|
||||
'Zaktualizowano ustawienia ochrony; zostaną zastosowane przy zapisie dokumentu',
|
||||
appModifyPwdTitle: 'Chroniony przed zapisem',
|
||||
appModifyPwdBody:
|
||||
'Dokument „{name}” ma hasło modyfikacji. Wprowadź je, aby edytować, lub otwórz tylko do odczytu.',
|
||||
appOpenReadOnly: 'Otwórz tylko do odczytu',
|
||||
appProtectPwdOptional: 'Hasło ochrony (opcjonalne)',
|
||||
appProtectPwdEnter: 'Wprowadź hasło ochrony',
|
||||
appProtectPwdHint:
|
||||
'Przy ustawionym haśle to samo hasło jest wymagane do usunięcia ograniczeń (skrót zgodny z programem Word)',
|
||||
appProtectionEnabledPwd: 'Włączono ograniczenie edytowania (z hasłem)',
|
||||
appProtectionEnabled: 'Włączono ograniczenie edytowania',
|
||||
appProtectionRemoved: 'Usunięto ograniczenia edytowania',
|
||||
appWrongPassword: 'Nieprawidłowe hasło',
|
||||
appCompareFailed: 'Porównanie nie powiodło się: {error}',
|
||||
appCompareResult: 'Wyniki porównania',
|
||||
@@ -3973,6 +4253,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'Cofnij',
|
||||
appRedo: 'Ponów',
|
||||
appStartOpening: 'Otwieranie…',
|
||||
appDocPwdTitle: 'Chroniony hasłem',
|
||||
appDocPwdBody: '„{name}” jest chroniony hasłem. Wprowadź hasło, aby go otworzyć.',
|
||||
appDocPwdLabel: 'Hasło',
|
||||
appDocPwdWrong: 'Hasło jest nieprawidłowe. Spróbuj ponownie.',
|
||||
appDocPwdUnsupported:
|
||||
'Nie można odszyfrować tego dokumentu: schemat szyfrowania nie jest obsługiwany (np. szyfrowanie kontem WPS). Usuń szyfrowanie w oryginalnej aplikacji i spróbuj ponownie.',
|
||||
appEncConfirmLabel: 'Potwierdź hasło',
|
||||
appEncMismatch: 'Hasła nie są zgodne',
|
||||
appRecentDocs: 'Ostatnio używane dokumenty',
|
||||
appSplitPaneLabel: 'Podzielone okienko (podgląd tylko do odczytu, niezależne przewijanie)',
|
||||
appRemoveSplit: 'Usuń podział',
|
||||
@@ -4212,15 +4500,29 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'Alle wijzigingen geaccepteerd',
|
||||
appAllRevisionsRejected: 'Alle wijzigingen geweigerd',
|
||||
appNoRevisionsToHandle: 'Geen bijgehouden wijzigingen om te verwerken',
|
||||
appRestrictEditing: 'Bewerken beperken',
|
||||
appUnrestrictEditing: 'Bewerkingsbeperkingen opheffen',
|
||||
appProtectTitle: 'Document beveiligen',
|
||||
appProtectSecurity: 'Beveiliging',
|
||||
appProtectOpenPwd: 'Wachtwoord om dit document te openen (optioneel)',
|
||||
appProtectModifyPwd: 'Wachtwoord om dit document te wijzigen (optioneel)',
|
||||
appProtectPwdKeepHint:
|
||||
'Een bestaand wachtwoord wordt als stippen weergegeven: laat het ongewijzigd om het te behouden, of maak het veld leeg om het te verwijderen (toegepast bij opslaan)',
|
||||
appProtectSectionTitle: 'Bescherming',
|
||||
appProtectFor: 'Document beschermen voor:',
|
||||
appProtectModeTracked: 'Wijzigingen bijhouden',
|
||||
appProtectModeComments: 'Opmerkingen',
|
||||
appProtectModeReadOnly: 'Alleen-lezen',
|
||||
appProtectModeForms: 'Formulieren',
|
||||
appProtectUnlockPwd: 'Voer het beveiligingswachtwoord in om deze te wijzigen of te verwijderen',
|
||||
appProtectPrivacy: 'Privacy',
|
||||
appProtectRemovePersonal:
|
||||
'Metadata van auteur en organisatie bij het opslaan uit dit bestand verwijderen',
|
||||
appProtectUpdated:
|
||||
'Beveiligingsinstellingen bijgewerkt; toegepast bij het opslaan van het document',
|
||||
appModifyPwdTitle: 'Beveiligd tegen schrijven',
|
||||
appModifyPwdBody:
|
||||
'"{name}" heeft een wachtwoord voor wijzigen. Voer het in om te bewerken, of open alleen-lezen.',
|
||||
appOpenReadOnly: 'Alleen-lezen openen',
|
||||
appProtectPwdOptional: 'Beveiligingswachtwoord (optioneel)',
|
||||
appProtectPwdEnter: 'Voer het beveiligingswachtwoord in',
|
||||
appProtectPwdHint:
|
||||
'Als er een wachtwoord is ingesteld, is hetzelfde wachtwoord vereist om de beperkingen op te heffen (Word-compatibele hash)',
|
||||
appProtectionEnabledPwd: 'Bewerken beperkt (met wachtwoord)',
|
||||
appProtectionEnabled: 'Bewerken beperkt',
|
||||
appProtectionRemoved: 'Bewerkingsbeperkingen opgeheven',
|
||||
appWrongPassword: 'Onjuist wachtwoord',
|
||||
appCompareFailed: 'Vergelijken mislukt: {error}',
|
||||
appCompareResult: 'Vergelijkingsresultaten',
|
||||
@@ -4267,6 +4569,15 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'Ongedaan maken',
|
||||
appRedo: 'Opnieuw',
|
||||
appStartOpening: 'Openen…',
|
||||
appDocPwdTitle: 'Met wachtwoord beveiligd',
|
||||
appDocPwdBody:
|
||||
'"{name}" is met een wachtwoord beveiligd. Voer het wachtwoord in om het te openen.',
|
||||
appDocPwdLabel: 'Wachtwoord',
|
||||
appDocPwdWrong: 'Het wachtwoord is onjuist. Probeer het opnieuw.',
|
||||
appDocPwdUnsupported:
|
||||
'Dit document kan niet worden ontsleuteld: de versleuteling wordt niet ondersteund (bijv. WPS-accountversleuteling). Verwijder de versleuteling in de oorspronkelijke app en probeer het opnieuw.',
|
||||
appEncConfirmLabel: 'Wachtwoord bevestigen',
|
||||
appEncMismatch: 'De wachtwoorden komen niet overeen',
|
||||
appRecentDocs: 'Recente documenten',
|
||||
appSplitPaneLabel: 'Gesplitst deelvenster (alleen-lezen voorbeeld, onafhankelijk scrollen)',
|
||||
appRemoveSplit: 'Splitsing verwijderen',
|
||||
@@ -4505,15 +4816,28 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'Semua perubahan diterima',
|
||||
appAllRevisionsRejected: 'Semua perubahan ditolak',
|
||||
appNoRevisionsToHandle: 'Tiada perubahan terjejak untuk diproses',
|
||||
appRestrictEditing: 'Hadkan Penyuntingan',
|
||||
appUnrestrictEditing: 'Buang Sekatan Penyuntingan',
|
||||
appProtectTitle: 'Lindungi Dokumen',
|
||||
appProtectSecurity: 'Keselamatan',
|
||||
appProtectOpenPwd: 'Kata laluan untuk membuka dokumen ini (pilihan)',
|
||||
appProtectModifyPwd: 'Kata laluan untuk mengubah suai dokumen ini (pilihan)',
|
||||
appProtectPwdKeepHint:
|
||||
'Kata laluan sedia ada dipaparkan sebagai titik: biarkan untuk mengekalkannya, atau kosongkan medan untuk membuangnya (berkuat kuasa semasa menyimpan)',
|
||||
appProtectSectionTitle: 'Perlindungan',
|
||||
appProtectFor: 'Lindungi dokumen untuk:',
|
||||
appProtectModeTracked: 'Jejak perubahan',
|
||||
appProtectModeComments: 'Komen',
|
||||
appProtectModeReadOnly: 'Baca sahaja',
|
||||
appProtectModeForms: 'Borang',
|
||||
appProtectUnlockPwd: 'Masukkan kata laluan perlindungan untuk mengubah atau membuangnya',
|
||||
appProtectPrivacy: 'Privasi',
|
||||
appProtectRemovePersonal:
|
||||
'Buang metadata pengarang dan organisasi daripada fail ini semasa menyimpan',
|
||||
appProtectUpdated: 'Tetapan perlindungan dikemas kini; berkuat kuasa apabila dokumen disimpan',
|
||||
appModifyPwdTitle: 'Dilindungi Tulis',
|
||||
appModifyPwdBody:
|
||||
'"{name}" mempunyai kata laluan untuk mengubah suai. Masukkannya untuk mengedit, atau buka baca sahaja.',
|
||||
appOpenReadOnly: 'Buka Baca Sahaja',
|
||||
appProtectPwdOptional: 'Kata laluan perlindungan (pilihan)',
|
||||
appProtectPwdEnter: 'Masukkan kata laluan perlindungan',
|
||||
appProtectPwdHint:
|
||||
'Jika kata laluan ditetapkan, kata laluan yang sama diperlukan untuk membuang sekatan (cincangan serasi Word)',
|
||||
appProtectionEnabledPwd: 'Penyuntingan dihadkan (dengan kata laluan)',
|
||||
appProtectionEnabled: 'Penyuntingan dihadkan',
|
||||
appProtectionRemoved: 'Sekatan penyuntingan dibuang',
|
||||
appWrongPassword: 'Kata laluan salah',
|
||||
appCompareFailed: 'Perbandingan gagal: {error}',
|
||||
appCompareResult: 'Hasil Perbandingan',
|
||||
@@ -4557,6 +4881,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'Buat asal',
|
||||
appRedo: 'Buat semula',
|
||||
appStartOpening: 'Membuka…',
|
||||
appDocPwdTitle: 'Dilindungi Kata Laluan',
|
||||
appDocPwdBody: '"{name}" dilindungi kata laluan. Masukkan kata laluan untuk membukanya.',
|
||||
appDocPwdLabel: 'Kata laluan',
|
||||
appDocPwdWrong: 'Kata laluan salah. Cuba lagi.',
|
||||
appDocPwdUnsupported:
|
||||
'Dokumen ini tidak dapat dinyahsulit: skema penyulitannya tidak disokong (cth. penyulitan akaun WPS). Alih keluar penyulitan dalam aplikasi asal dan cuba lagi.',
|
||||
appEncConfirmLabel: 'Sahkan kata laluan',
|
||||
appEncMismatch: 'Kata laluan tidak sepadan',
|
||||
appRecentDocs: 'Dokumen Terkini',
|
||||
appSplitPaneLabel: 'Anak tetingkap terpisah (pratonton baca sahaja, tatal berasingan)',
|
||||
appRemoveSplit: 'Buang Pemisahan',
|
||||
@@ -4787,14 +5119,26 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'כל השינויים התקבלו',
|
||||
appAllRevisionsRejected: 'כל השינויים נדחו',
|
||||
appNoRevisionsToHandle: 'אין שינויים במעקב לטיפול',
|
||||
appRestrictEditing: 'הגבלת עריכה',
|
||||
appUnrestrictEditing: 'הסרת הגבלות עריכה',
|
||||
appProtectTitle: 'הגנה על המסמך',
|
||||
appProtectSecurity: 'אבטחה',
|
||||
appProtectOpenPwd: 'סיסמה לפתיחת מסמך זה (לא חובה)',
|
||||
appProtectModifyPwd: 'סיסמה לשינוי מסמך זה (לא חובה)',
|
||||
appProtectPwdKeepHint:
|
||||
'סיסמה קיימת מוצגת כנקודות: השאירו אותה ללא שינוי כדי לשמור עליה, או נקו את השדה כדי להסירה (חל בשמירה)',
|
||||
appProtectSectionTitle: 'הגנה',
|
||||
appProtectFor: 'הגנה על המסמך עבור:',
|
||||
appProtectModeTracked: 'מעקב אחר שינויים',
|
||||
appProtectModeComments: 'הערות',
|
||||
appProtectModeReadOnly: 'קריאה בלבד',
|
||||
appProtectModeForms: 'טפסים',
|
||||
appProtectUnlockPwd: 'הזינו את סיסמת ההגנה כדי לשנות או להסיר אותה',
|
||||
appProtectPrivacy: 'פרטיות',
|
||||
appProtectRemovePersonal: 'הסרת מטא-נתונים של המחבר והארגון מקובץ זה בעת השמירה',
|
||||
appProtectUpdated: 'הגדרות ההגנה עודכנו; הן חלות בשמירת המסמך',
|
||||
appModifyPwdTitle: 'מוגן מפני כתיבה',
|
||||
appModifyPwdBody: 'ל"{name}" מוגדרת סיסמת שינוי. הזינו אותה כדי לערוך, או פתחו לקריאה בלבד.',
|
||||
appOpenReadOnly: 'פתיחה לקריאה בלבד',
|
||||
appProtectPwdOptional: 'סיסמת הגנה (לא חובה)',
|
||||
appProtectPwdEnter: 'הזינו את סיסמת ההגנה',
|
||||
appProtectPwdHint: 'כאשר מוגדרת סיסמה, נדרשת אותה סיסמה להסרת ההגבלות (גיבוב תואם Word)',
|
||||
appProtectionEnabledPwd: 'הגבלת עריכה הופעלה (עם סיסמה)',
|
||||
appProtectionEnabled: 'הגבלת עריכה הופעלה',
|
||||
appProtectionRemoved: 'הגבלות העריכה הוסרו',
|
||||
appWrongPassword: 'סיסמה שגויה',
|
||||
appCompareFailed: 'ההשוואה נכשלה: {error}',
|
||||
appCompareResult: 'תוצאות השוואה',
|
||||
@@ -4838,6 +5182,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'ביטול פעולה',
|
||||
appRedo: 'ביצוע מחדש',
|
||||
appStartOpening: 'פותח…',
|
||||
appDocPwdTitle: 'מוגן בסיסמה',
|
||||
appDocPwdBody: '"{name}" מוגן בסיסמה. הזינו את הסיסמה כדי לפתוח אותו.',
|
||||
appDocPwdLabel: 'סיסמה',
|
||||
appDocPwdWrong: 'הסיסמה שגויה. נסו שוב.',
|
||||
appDocPwdUnsupported:
|
||||
'לא ניתן לפענח מסמך זה: שיטת ההצפנה אינה נתמכת (למשל הצפנת חשבון WPS). הסירו את ההצפנה ביישום המקורי ונסו שוב.',
|
||||
appEncConfirmLabel: 'אימות סיסמה',
|
||||
appEncMismatch: 'הסיסמאות אינן תואמות',
|
||||
appRecentDocs: 'מסמכים אחרונים',
|
||||
appSplitPaneLabel: 'חלונית מפוצלת (תצוגה מקדימה לקריאה בלבד, גלילה עצמאית)',
|
||||
appRemoveSplit: 'הסרת פיצול',
|
||||
@@ -5072,15 +5424,27 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: 'सभी परिवर्तन स्वीकार किए गए',
|
||||
appAllRevisionsRejected: 'सभी परिवर्तन अस्वीकार किए गए',
|
||||
appNoRevisionsToHandle: 'संसाधित करने के लिए कोई ट्रैक किया गया परिवर्तन नहीं',
|
||||
appRestrictEditing: 'संपादन प्रतिबंधित करें',
|
||||
appUnrestrictEditing: 'संपादन प्रतिबंध हटाएँ',
|
||||
appProtectTitle: 'दस्तावेज़ सुरक्षित करें',
|
||||
appProtectSecurity: 'सुरक्षा',
|
||||
appProtectOpenPwd: 'इस दस्तावेज़ को खोलने का पासवर्ड (वैकल्पिक)',
|
||||
appProtectModifyPwd: 'इस दस्तावेज़ को संशोधित करने का पासवर्ड (वैकल्पिक)',
|
||||
appProtectPwdKeepHint:
|
||||
'मौजूदा पासवर्ड बिंदुओं के रूप में दिखता है: बनाए रखने के लिए उसे वैसा ही छोड़ें, या हटाने के लिए फ़ील्ड खाली करें (सहेजने पर लागू)',
|
||||
appProtectSectionTitle: 'संरक्षण',
|
||||
appProtectFor: 'दस्तावेज़ को इसके लिए सुरक्षित करें:',
|
||||
appProtectModeTracked: 'परिवर्तन ट्रैकिंग',
|
||||
appProtectModeComments: 'टिप्पणियाँ',
|
||||
appProtectModeReadOnly: 'केवल पढ़ने के लिए',
|
||||
appProtectModeForms: 'फ़ॉर्म',
|
||||
appProtectUnlockPwd: 'बदलने या हटाने के लिए सुरक्षा पासवर्ड दर्ज करें',
|
||||
appProtectPrivacy: 'गोपनीयता',
|
||||
appProtectRemovePersonal: 'सहेजते समय इस फ़ाइल से लेखक और संगठन का मेटाडेटा हटाएँ',
|
||||
appProtectUpdated: 'सुरक्षा सेटिंग्स अपडेट हुईं; दस्तावेज़ सहेजने पर लागू होंगी',
|
||||
appModifyPwdTitle: 'लेखन-सुरक्षित',
|
||||
appModifyPwdBody:
|
||||
'"{name}" में संशोधन पासवर्ड सेट है। संपादित करने के लिए उसे दर्ज करें, या केवल पढ़ने के लिए खोलें।',
|
||||
appOpenReadOnly: 'केवल पढ़ने के लिए खोलें',
|
||||
appProtectPwdOptional: 'सुरक्षा पासवर्ड (वैकल्पिक)',
|
||||
appProtectPwdEnter: 'सुरक्षा पासवर्ड दर्ज करें',
|
||||
appProtectPwdHint:
|
||||
'पासवर्ड सेट होने पर, प्रतिबंध हटाने के लिए वही पासवर्ड आवश्यक है (Word-संगत हैश)',
|
||||
appProtectionEnabledPwd: 'संपादन प्रतिबंधित (पासवर्ड सहित)',
|
||||
appProtectionEnabled: 'संपादन प्रतिबंधित',
|
||||
appProtectionRemoved: 'संपादन प्रतिबंध हटाए गए',
|
||||
appWrongPassword: 'गलत पासवर्ड',
|
||||
appCompareFailed: 'तुलना विफल: {error}',
|
||||
appCompareResult: 'तुलना परिणाम',
|
||||
@@ -5124,6 +5488,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: 'पूर्ववत करें',
|
||||
appRedo: 'फिर से करें',
|
||||
appStartOpening: 'खोला जा रहा है…',
|
||||
appDocPwdTitle: 'पासवर्ड से सुरक्षित',
|
||||
appDocPwdBody: '"{name}" पासवर्ड से सुरक्षित है। खोलने के लिए पासवर्ड दर्ज करें।',
|
||||
appDocPwdLabel: 'पासवर्ड',
|
||||
appDocPwdWrong: 'पासवर्ड गलत है। फिर से प्रयास करें।',
|
||||
appDocPwdUnsupported:
|
||||
'इस दस्तावेज़ को डिक्रिप्ट नहीं किया जा सकता: इसकी एन्क्रिप्शन विधि समर्थित नहीं है (जैसे WPS खाता एन्क्रिप्शन)। मूल ऐप में एन्क्रिप्शन हटाकर फिर से प्रयास करें।',
|
||||
appEncConfirmLabel: 'पासवर्ड की पुष्टि करें',
|
||||
appEncMismatch: 'पासवर्ड मेल नहीं खाते',
|
||||
appRecentDocs: 'हाल के दस्तावेज़',
|
||||
appSplitPaneLabel: 'विभाजित फलक (केवल-पठन पूर्वावलोकन, स्वतंत्र स्क्रॉल)',
|
||||
appRemoveSplit: 'विभाजन हटाएँ',
|
||||
@@ -5353,14 +5725,25 @@ export const appStrings = defineStrings({
|
||||
appAllRevisionsAccepted: '已接受所有修訂',
|
||||
appAllRevisionsRejected: '已拒絕所有修訂',
|
||||
appNoRevisionsToHandle: '沒有可處理的修訂',
|
||||
appRestrictEditing: '限制編輯',
|
||||
appUnrestrictEditing: '解除限制編輯',
|
||||
appProtectTitle: '保護文件',
|
||||
appProtectSecurity: '安全性',
|
||||
appProtectOpenPwd: '開啟此文件的密碼(可選)',
|
||||
appProtectModifyPwd: '修改此文件的密碼(可選)',
|
||||
appProtectPwdKeepHint: '已設定的密碼以圓點顯示:保持不變則保留,清空後確定則移除(儲存後生效)',
|
||||
appProtectSectionTitle: '保護',
|
||||
appProtectFor: '保護文件:',
|
||||
appProtectModeTracked: '追蹤修訂',
|
||||
appProtectModeComments: '註解',
|
||||
appProtectModeReadOnly: '唯讀',
|
||||
appProtectModeForms: '表單',
|
||||
appProtectUnlockPwd: '輸入保護密碼以變更或解除',
|
||||
appProtectPrivacy: '隱私權',
|
||||
appProtectRemovePersonal: '儲存時移除此檔案中的作者與組織中繼資料',
|
||||
appProtectUpdated: '保護設定已更新,儲存後生效',
|
||||
appModifyPwdTitle: '文件受寫入保護',
|
||||
appModifyPwdBody: '「{name}」設有修改密碼。輸入密碼以編輯,或以唯讀方式開啟。',
|
||||
appOpenReadOnly: '唯讀開啟',
|
||||
appProtectPwdOptional: '保護密碼(可留空)',
|
||||
appProtectPwdEnter: '輸入保護密碼',
|
||||
appProtectPwdHint: '設有密碼時,解除限制需輸入同一密碼(Word 相容雜湊)',
|
||||
appProtectionEnabledPwd: '已啟用限制編輯(含密碼)',
|
||||
appProtectionEnabled: '已啟用限制編輯',
|
||||
appProtectionRemoved: '已解除限制編輯',
|
||||
appWrongPassword: '密碼不正確',
|
||||
appCompareFailed: '比較失敗: {error}',
|
||||
appCompareResult: '比較結果',
|
||||
@@ -5401,6 +5784,14 @@ export const appStrings = defineStrings({
|
||||
appUndo: '復原',
|
||||
appRedo: '重做',
|
||||
appStartOpening: '正在開啟…',
|
||||
appDocPwdTitle: '文件已加密',
|
||||
appDocPwdBody: '「{name}」設有開啟密碼,請輸入密碼以開啟。',
|
||||
appDocPwdLabel: '密碼',
|
||||
appDocPwdWrong: '密碼不正確,請重試',
|
||||
appDocPwdUnsupported:
|
||||
'無法解密此文件:加密方式不受支援(例如 WPS 帳號加密),請在原軟體中解除加密後重試',
|
||||
appEncConfirmLabel: '確認密碼',
|
||||
appEncMismatch: '兩次輸入的密碼不一致',
|
||||
appRecentDocs: '最近使用的文件',
|
||||
appSplitPaneLabel: '分割窗格(唯讀預覽,可獨立捲動)',
|
||||
appRemoveSplit: '取消分割',
|
||||
|
||||
@@ -17,6 +17,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: '移动图表',
|
||||
editorSectionBreak: '分节符',
|
||||
editorFormatRevision: '格式修订',
|
||||
editorRevDeleted: '删除',
|
||||
editorRevFormatted: '带格式的',
|
||||
editorRevFont: '字体',
|
||||
editorRevBold: '加粗',
|
||||
editorRevNotBold: '非加粗',
|
||||
editorRevItalic: '倾斜',
|
||||
editorRevNotItalic: '非倾斜',
|
||||
editorRevHighlight: '突出显示',
|
||||
editorProtectedContent: '受保护内容',
|
||||
editorOleExcel: 'Excel 工作表(嵌入对象)',
|
||||
editorOleWord: 'Word 文档(嵌入对象)',
|
||||
@@ -66,6 +74,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'Move chart',
|
||||
editorSectionBreak: 'Section Break',
|
||||
editorFormatRevision: 'Format revision',
|
||||
editorRevDeleted: 'Deleted',
|
||||
editorRevFormatted: 'Formatted',
|
||||
editorRevFont: 'Font',
|
||||
editorRevBold: 'Bold',
|
||||
editorRevNotBold: 'Not Bold',
|
||||
editorRevItalic: 'Italic',
|
||||
editorRevNotItalic: 'Not Italic',
|
||||
editorRevHighlight: 'Highlight',
|
||||
editorProtectedContent: 'Protected content',
|
||||
editorOleExcel: 'Excel worksheet (embedded)',
|
||||
editorOleWord: 'Word document (embedded)',
|
||||
@@ -115,6 +131,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'グラフの移動',
|
||||
editorSectionBreak: 'セクション区切り',
|
||||
editorFormatRevision: '書式の変更',
|
||||
editorRevDeleted: '削除',
|
||||
editorRevFormatted: '書式設定',
|
||||
editorRevFont: 'フォント',
|
||||
editorRevBold: '太字',
|
||||
editorRevNotBold: '太字解除',
|
||||
editorRevItalic: '斜体',
|
||||
editorRevNotItalic: '斜体解除',
|
||||
editorRevHighlight: '蛍光ペン',
|
||||
editorProtectedContent: '保護されたコンテンツ',
|
||||
editorOleExcel: 'Excel ワークシート(埋め込み)',
|
||||
editorOleWord: 'Word 文書(埋め込み)',
|
||||
@@ -164,6 +188,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: '차트 이동',
|
||||
editorSectionBreak: '구역 나누기',
|
||||
editorFormatRevision: '서식 수정',
|
||||
editorRevDeleted: '삭제',
|
||||
editorRevFormatted: '서식 있음',
|
||||
editorRevFont: '글꼴',
|
||||
editorRevBold: '굵게',
|
||||
editorRevNotBold: '굵게 해제',
|
||||
editorRevItalic: '기울임꼴',
|
||||
editorRevNotItalic: '기울임꼴 해제',
|
||||
editorRevHighlight: '강조',
|
||||
editorProtectedContent: '보호된 콘텐츠',
|
||||
editorOleExcel: 'Excel 워크시트(포함됨)',
|
||||
editorOleWord: 'Word 문서(포함됨)',
|
||||
@@ -213,6 +245,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'Déplacer le graphique',
|
||||
editorSectionBreak: 'Saut de section',
|
||||
editorFormatRevision: 'Révision de format',
|
||||
editorRevDeleted: 'Supprimé',
|
||||
editorRevFormatted: 'Mis en forme',
|
||||
editorRevFont: 'Police',
|
||||
editorRevBold: 'Gras',
|
||||
editorRevNotBold: 'Non Gras',
|
||||
editorRevItalic: 'Italique',
|
||||
editorRevNotItalic: 'Non Italique',
|
||||
editorRevHighlight: 'Surlignage',
|
||||
editorProtectedContent: 'Contenu protégé',
|
||||
editorOleExcel: 'Feuille Excel (objet incorporé)',
|
||||
editorOleWord: 'Document Word (objet incorporé)',
|
||||
@@ -262,6 +302,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'Diagramm verschieben',
|
||||
editorSectionBreak: 'Abschnittsumbruch',
|
||||
editorFormatRevision: 'Formatänderung',
|
||||
editorRevDeleted: 'Gelöscht',
|
||||
editorRevFormatted: 'Formatiert',
|
||||
editorRevFont: 'Schriftart',
|
||||
editorRevBold: 'Fett',
|
||||
editorRevNotBold: 'Nicht Fett',
|
||||
editorRevItalic: 'Kursiv',
|
||||
editorRevNotItalic: 'Nicht Kursiv',
|
||||
editorRevHighlight: 'Hervorheben',
|
||||
editorProtectedContent: 'Geschützter Inhalt',
|
||||
editorOleExcel: 'Excel-Arbeitsblatt (eingebettet)',
|
||||
editorOleWord: 'Word-Dokument (eingebettet)',
|
||||
@@ -311,6 +359,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'Mover gráfico',
|
||||
editorSectionBreak: 'Salto de sección',
|
||||
editorFormatRevision: 'Revisión de formato',
|
||||
editorRevDeleted: 'Eliminado',
|
||||
editorRevFormatted: 'Con formato',
|
||||
editorRevFont: 'Fuente',
|
||||
editorRevBold: 'Negrita',
|
||||
editorRevNotBold: 'Sin Negrita',
|
||||
editorRevItalic: 'Cursiva',
|
||||
editorRevNotItalic: 'Sin Cursiva',
|
||||
editorRevHighlight: 'Resaltar',
|
||||
editorProtectedContent: 'Contenido protegido',
|
||||
editorOleExcel: 'Hoja de Excel (objeto incrustado)',
|
||||
editorOleWord: 'Documento de Word (objeto incrustado)',
|
||||
@@ -360,6 +416,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'ย้ายแผนภูมิ',
|
||||
editorSectionBreak: 'ตัวแบ่งส่วน',
|
||||
editorFormatRevision: 'การแก้ไขรูปแบบ',
|
||||
editorRevDeleted: 'ลบแล้ว',
|
||||
editorRevFormatted: 'จัดรูปแบบแล้ว',
|
||||
editorRevFont: 'ฟอนต์',
|
||||
editorRevBold: 'ตัวหนา',
|
||||
editorRevNotBold: 'ไม่เป็นตัวหนา',
|
||||
editorRevItalic: 'ตัวเอียง',
|
||||
editorRevNotItalic: 'ไม่เป็นตัวเอียง',
|
||||
editorRevHighlight: 'เน้นข้อความ',
|
||||
editorProtectedContent: 'เนื้อหาที่ได้รับการป้องกัน',
|
||||
editorOleExcel: 'เวิร์กชีต Excel (ฝังตัว)',
|
||||
editorOleWord: 'เอกสาร Word (ฝังตัว)',
|
||||
@@ -409,6 +473,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'Pindahkan bagan',
|
||||
editorSectionBreak: 'Pemisah Bagian',
|
||||
editorFormatRevision: 'Revisi format',
|
||||
editorRevDeleted: 'Dihapus',
|
||||
editorRevFormatted: 'Diformat',
|
||||
editorRevFont: 'Font',
|
||||
editorRevBold: 'Tebal',
|
||||
editorRevNotBold: 'Tidak Tebal',
|
||||
editorRevItalic: 'Miring',
|
||||
editorRevNotItalic: 'Tidak Miring',
|
||||
editorRevHighlight: 'Sorotan',
|
||||
editorProtectedContent: 'Konten yang dilindungi',
|
||||
editorOleExcel: 'Lembar kerja Excel (tersemat)',
|
||||
editorOleWord: 'Dokumen Word (tersemat)',
|
||||
@@ -458,6 +530,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'Переместить диаграмму',
|
||||
editorSectionBreak: 'Разрыв раздела',
|
||||
editorFormatRevision: 'Изменение формата',
|
||||
editorRevDeleted: 'Удалено',
|
||||
editorRevFormatted: 'Форматирование',
|
||||
editorRevFont: 'Шрифт',
|
||||
editorRevBold: 'Полужирный',
|
||||
editorRevNotBold: 'Не полужирный',
|
||||
editorRevItalic: 'Курсив',
|
||||
editorRevNotItalic: 'Не курсив',
|
||||
editorRevHighlight: 'Выделение',
|
||||
editorProtectedContent: 'Защищенное содержимое',
|
||||
editorOleExcel: 'Лист Excel (внедрённый объект)',
|
||||
editorOleWord: 'Документ Word (внедрённый объект)',
|
||||
@@ -507,6 +587,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'نقل المخطط',
|
||||
editorSectionBreak: 'فاصل مقطعي',
|
||||
editorFormatRevision: 'مراجعة التنسيق',
|
||||
editorRevDeleted: 'محذوف',
|
||||
editorRevFormatted: 'منسق',
|
||||
editorRevFont: 'الخط',
|
||||
editorRevBold: 'غامق',
|
||||
editorRevNotBold: 'غير غامق',
|
||||
editorRevItalic: 'مائل',
|
||||
editorRevNotItalic: 'غير مائل',
|
||||
editorRevHighlight: 'تمييز',
|
||||
editorProtectedContent: 'محتوى محمي',
|
||||
editorOleExcel: 'ورقة عمل Excel (كائن مضمّن)',
|
||||
editorOleWord: 'مستند Word (كائن مضمّن)',
|
||||
@@ -556,6 +644,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'Mover gráfico',
|
||||
editorSectionBreak: 'Quebra de seção',
|
||||
editorFormatRevision: 'Revisão de formato',
|
||||
editorRevDeleted: 'Excluído',
|
||||
editorRevFormatted: 'Formatado',
|
||||
editorRevFont: 'Fonte',
|
||||
editorRevBold: 'Negrito',
|
||||
editorRevNotBold: 'Sem Negrito',
|
||||
editorRevItalic: 'Itálico',
|
||||
editorRevNotItalic: 'Sem Itálico',
|
||||
editorRevHighlight: 'Realce',
|
||||
editorProtectedContent: 'Conteúdo protegido',
|
||||
editorOleExcel: 'Planilha do Excel (objeto incorporado)',
|
||||
editorOleWord: 'Documento do Word (objeto incorporado)',
|
||||
@@ -605,6 +701,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'Sposta grafico',
|
||||
editorSectionBreak: 'Interruzione di sezione',
|
||||
editorFormatRevision: 'Revisione formato',
|
||||
editorRevDeleted: 'Eliminato',
|
||||
editorRevFormatted: 'Formattato',
|
||||
editorRevFont: 'Carattere',
|
||||
editorRevBold: 'Grassetto',
|
||||
editorRevNotBold: 'Non Grassetto',
|
||||
editorRevItalic: 'Corsivo',
|
||||
editorRevNotItalic: 'Non Corsivo',
|
||||
editorRevHighlight: 'Evidenziazione',
|
||||
editorProtectedContent: 'Contenuto protetto',
|
||||
editorOleExcel: 'Foglio Excel (oggetto incorporato)',
|
||||
editorOleWord: 'Documento Word (oggetto incorporato)',
|
||||
@@ -654,6 +758,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'Przenieś wykres',
|
||||
editorSectionBreak: 'Podział sekcji',
|
||||
editorFormatRevision: 'Zmiana formatowania',
|
||||
editorRevDeleted: 'Usunięto',
|
||||
editorRevFormatted: 'Sformatowano',
|
||||
editorRevFont: 'Czcionka',
|
||||
editorRevBold: 'Pogrubienie',
|
||||
editorRevNotBold: 'Bez pogrubienia',
|
||||
editorRevItalic: 'Kursywa',
|
||||
editorRevNotItalic: 'Bez kursywy',
|
||||
editorRevHighlight: 'Wyróżnienie',
|
||||
editorProtectedContent: 'Zawartość chroniona',
|
||||
editorOleExcel: 'Arkusz Excel (obiekt osadzony)',
|
||||
editorOleWord: 'Dokument Word (obiekt osadzony)',
|
||||
@@ -703,6 +815,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'Grafiek verplaatsen',
|
||||
editorSectionBreak: 'Sectie-einde',
|
||||
editorFormatRevision: 'Opmaakwijziging',
|
||||
editorRevDeleted: 'Verwijderd',
|
||||
editorRevFormatted: 'Opgemaakt',
|
||||
editorRevFont: 'Lettertype',
|
||||
editorRevBold: 'Vet',
|
||||
editorRevNotBold: 'Niet Vet',
|
||||
editorRevItalic: 'Cursief',
|
||||
editorRevNotItalic: 'Niet Cursief',
|
||||
editorRevHighlight: 'Markering',
|
||||
editorProtectedContent: 'Beveiligde inhoud',
|
||||
editorOleExcel: 'Excel-werkblad (ingesloten object)',
|
||||
editorOleWord: 'Word-document (ingesloten object)',
|
||||
@@ -752,6 +872,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'Alihkan carta',
|
||||
editorSectionBreak: 'Pemisah Seksyen',
|
||||
editorFormatRevision: 'Semakan format',
|
||||
editorRevDeleted: 'Dipadam',
|
||||
editorRevFormatted: 'Diformat',
|
||||
editorRevFont: 'Fon',
|
||||
editorRevBold: 'Tebal',
|
||||
editorRevNotBold: 'Tidak Tebal',
|
||||
editorRevItalic: 'Condong',
|
||||
editorRevNotItalic: 'Tidak Condong',
|
||||
editorRevHighlight: 'Serlahan',
|
||||
editorProtectedContent: 'Kandungan dilindungi',
|
||||
editorOleExcel: 'Hamparan Excel (objek terbenam)',
|
||||
editorOleWord: 'Dokumen Word (objek terbenam)',
|
||||
@@ -801,6 +929,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'הזזת תרשים',
|
||||
editorSectionBreak: 'מעבר מקטע',
|
||||
editorFormatRevision: 'שינוי עיצוב',
|
||||
editorRevDeleted: 'נמחק',
|
||||
editorRevFormatted: 'עוצב',
|
||||
editorRevFont: 'גופן',
|
||||
editorRevBold: 'מודגש',
|
||||
editorRevNotBold: 'לא מודגש',
|
||||
editorRevItalic: 'נטוי',
|
||||
editorRevNotItalic: 'לא נטוי',
|
||||
editorRevHighlight: 'סימון',
|
||||
editorProtectedContent: 'תוכן מוגן',
|
||||
editorOleExcel: 'גיליון Excel (אובייקט מוטבע)',
|
||||
editorOleWord: 'מסמך Word (אובייקט מוטבע)',
|
||||
@@ -850,6 +986,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: 'चार्ट ले जाएँ',
|
||||
editorSectionBreak: 'अनुभाग विराम',
|
||||
editorFormatRevision: 'स्वरूप संशोधन',
|
||||
editorRevDeleted: 'हटाया गया',
|
||||
editorRevFormatted: 'स्वरूपित',
|
||||
editorRevFont: 'फ़ॉन्ट',
|
||||
editorRevBold: 'बोल्ड',
|
||||
editorRevNotBold: 'बोल्ड नहीं',
|
||||
editorRevItalic: 'इटैलिक',
|
||||
editorRevNotItalic: 'इटैलिक नहीं',
|
||||
editorRevHighlight: 'हाइलाइट',
|
||||
editorProtectedContent: 'सुरक्षित सामग्री',
|
||||
editorOleExcel: 'Excel वर्कशीट (एम्बेडेड ऑब्जेक्ट)',
|
||||
editorOleWord: 'Word दस्तावेज़ (एम्बेडेड ऑब्जेक्ट)',
|
||||
@@ -899,6 +1043,14 @@ export const editorStrings = defineStrings({
|
||||
editorMoveChart: '移動圖表',
|
||||
editorSectionBreak: '分節符號',
|
||||
editorFormatRevision: '格式修訂',
|
||||
editorRevDeleted: '刪除',
|
||||
editorRevFormatted: '帶格式的',
|
||||
editorRevFont: '字型',
|
||||
editorRevBold: '加粗',
|
||||
editorRevNotBold: '非加粗',
|
||||
editorRevItalic: '傾斜',
|
||||
editorRevNotItalic: '非傾斜',
|
||||
editorRevHighlight: '醒目提示',
|
||||
editorProtectedContent: '受保護內容',
|
||||
editorOleExcel: 'Excel 工作表(內嵌物件)',
|
||||
editorOleWord: 'Word 文件(內嵌物件)',
|
||||
|
||||
@@ -636,9 +636,8 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: '修订',
|
||||
ribbonCompare: '比较',
|
||||
ribbonCompareTip: '比较:选择另一个文档,按段落对比差异',
|
||||
ribbonRestrictEditing: '限制编辑',
|
||||
ribbonRestrictEditingTip: '限制编辑:将文档设为只读',
|
||||
ribbonStopProtectionTip: '停止保护,恢复编辑',
|
||||
ribbonProtectDoc: '保护文档',
|
||||
ribbonProtectDocTip: '保护文档:打开密码、修改密码、编辑限制与隐私设置',
|
||||
ribbonGroupProtect: '保护',
|
||||
// View
|
||||
ribbonPrintLayout: '页面视图',
|
||||
@@ -1322,9 +1321,9 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: 'Tracking',
|
||||
ribbonCompare: 'Compare',
|
||||
ribbonCompareTip: 'Compare: pick another document and diff it by paragraph',
|
||||
ribbonRestrictEditing: 'Restrict Editing',
|
||||
ribbonRestrictEditingTip: 'Restrict editing: make the document read-only',
|
||||
ribbonStopProtectionTip: 'Stop protection and resume editing',
|
||||
ribbonProtectDoc: 'Protect Document',
|
||||
ribbonProtectDocTip:
|
||||
'Protect document: open/modify passwords, editing restrictions and privacy',
|
||||
ribbonGroupProtect: 'Protect',
|
||||
ribbonPrintLayout: 'Print Layout',
|
||||
ribbonPrintLayoutTip: 'Print Layout: show the document at page size',
|
||||
@@ -2026,9 +2025,8 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: '変更履歴',
|
||||
ribbonCompare: '比較',
|
||||
ribbonCompareTip: '比較:別のドキュメントを選択し、段落ごとに差分を比較',
|
||||
ribbonRestrictEditing: '編集の制限',
|
||||
ribbonRestrictEditingTip: '編集の制限:ドキュメントを読み取り専用に設定',
|
||||
ribbonStopProtectionTip: '保護を中止して編集を再開',
|
||||
ribbonProtectDoc: '文書の保護',
|
||||
ribbonProtectDocTip: '文書の保護:開く/書き込みパスワード、編集の制限、プライバシー設定',
|
||||
ribbonGroupProtect: '保護',
|
||||
// View
|
||||
ribbonPrintLayout: '印刷レイアウト',
|
||||
@@ -2729,9 +2727,8 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: '추적',
|
||||
ribbonCompare: '비교',
|
||||
ribbonCompareTip: '비교: 다른 문서를 선택하여 단락별로 차이 비교',
|
||||
ribbonRestrictEditing: '편집 제한',
|
||||
ribbonRestrictEditingTip: '편집 제한: 문서를 읽기 전용으로 설정',
|
||||
ribbonStopProtectionTip: '보호 중지 후 편집 다시 시작',
|
||||
ribbonProtectDoc: '문서 보호',
|
||||
ribbonProtectDocTip: '문서 보호: 열기/수정 암호, 편집 제한 및 개인 정보 설정',
|
||||
ribbonGroupProtect: '보호',
|
||||
// View
|
||||
ribbonPrintLayout: '인쇄 모양',
|
||||
@@ -3423,9 +3420,9 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonCompare: 'Comparer',
|
||||
ribbonCompareTip:
|
||||
'Comparer : choisir un autre document et comparer les différences paragraphe par paragraphe',
|
||||
ribbonRestrictEditing: 'Restreindre la modification',
|
||||
ribbonRestrictEditingTip: 'Restreindre la modification : rendre le document en lecture seule',
|
||||
ribbonStopProtectionTip: 'Désactiver la protection et reprendre la modification',
|
||||
ribbonProtectDoc: 'Protéger le document',
|
||||
ribbonProtectDocTip:
|
||||
'Protéger le document : mots de passe d’ouverture/modification, restrictions de modification et confidentialité',
|
||||
ribbonGroupProtect: 'Protéger',
|
||||
ribbonPrintLayout: 'Page',
|
||||
ribbonPrintLayoutTip: 'Mode Page : afficher le document au format de la page',
|
||||
@@ -4118,9 +4115,9 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: 'Nachverfolgung',
|
||||
ribbonCompare: 'Vergleichen',
|
||||
ribbonCompareTip: 'Vergleichen: ein anderes Dokument auswählen und absatzweise vergleichen',
|
||||
ribbonRestrictEditing: 'Bearbeitung einschränken',
|
||||
ribbonRestrictEditingTip: 'Bearbeitung einschränken: Dokument schreibgeschützt machen',
|
||||
ribbonStopProtectionTip: 'Schutz aufheben und Bearbeitung fortsetzen',
|
||||
ribbonProtectDoc: 'Dokument schützen',
|
||||
ribbonProtectDocTip:
|
||||
'Dokument schützen: Öffnen-/Ändern-Kennwörter, Bearbeitungseinschränkungen und Datenschutz',
|
||||
ribbonGroupProtect: 'Schützen',
|
||||
ribbonPrintLayout: 'Drucklayout',
|
||||
ribbonPrintLayoutTip: 'Drucklayout: Dokument in Seitengröße anzeigen',
|
||||
@@ -4816,9 +4813,9 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonCompare: 'Comparar',
|
||||
ribbonCompareTip:
|
||||
'Comparar: elegir otro documento y comparar las diferencias párrafo a párrafo',
|
||||
ribbonRestrictEditing: 'Restringir edición',
|
||||
ribbonRestrictEditingTip: 'Restringir edición: convertir el documento en solo lectura',
|
||||
ribbonStopProtectionTip: 'Suspender la protección y reanudar la edición',
|
||||
ribbonProtectDoc: 'Proteger documento',
|
||||
ribbonProtectDocTip:
|
||||
'Proteger documento: contraseñas de apertura/modificación, restricciones de edición y privacidad',
|
||||
ribbonGroupProtect: 'Proteger',
|
||||
ribbonPrintLayout: 'Diseño de impresión',
|
||||
ribbonPrintLayoutTip: 'Diseño de impresión: mostrar el documento al tamaño de la página',
|
||||
@@ -5503,9 +5500,8 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: 'การติดตาม',
|
||||
ribbonCompare: 'เปรียบเทียบ',
|
||||
ribbonCompareTip: 'เปรียบเทียบ: เลือกเอกสารอื่นแล้วเปรียบเทียบความแตกต่างทีละย่อหน้า',
|
||||
ribbonRestrictEditing: 'จำกัดการแก้ไข',
|
||||
ribbonRestrictEditingTip: 'จำกัดการแก้ไข: ตั้งค่าเอกสารเป็นอ่านอย่างเดียว',
|
||||
ribbonStopProtectionTip: 'หยุดการป้องกันและกลับมาแก้ไขต่อ',
|
||||
ribbonProtectDoc: 'ป้องกันเอกสาร',
|
||||
ribbonProtectDocTip: 'ป้องกันเอกสาร: รหัสผ่านเปิด/แก้ไข การจำกัดการแก้ไข และความเป็นส่วนตัว',
|
||||
ribbonGroupProtect: 'ป้องกัน',
|
||||
ribbonPrintLayout: 'เค้าโครงเหมือนพิมพ์',
|
||||
ribbonPrintLayoutTip: 'เค้าโครงเหมือนพิมพ์: แสดงเอกสารตามขนาดหน้ากระดาษ',
|
||||
@@ -6188,9 +6184,9 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: 'Pelacakan',
|
||||
ribbonCompare: 'Bandingkan',
|
||||
ribbonCompareTip: 'Bandingkan: pilih dokumen lain dan bandingkan perbedaannya per paragraf',
|
||||
ribbonRestrictEditing: 'Batasi Pengeditan',
|
||||
ribbonRestrictEditingTip: 'Batasi pengeditan: jadikan dokumen hanya-baca',
|
||||
ribbonStopProtectionTip: 'Hentikan perlindungan dan lanjutkan pengeditan',
|
||||
ribbonProtectDoc: 'Proteksi Dokumen',
|
||||
ribbonProtectDocTip:
|
||||
'Proteksi dokumen: kata sandi buka/ubah, pembatasan pengeditan, dan privasi',
|
||||
ribbonGroupProtect: 'Lindungi',
|
||||
ribbonPrintLayout: 'Tata Letak Cetak',
|
||||
ribbonPrintLayoutTip: 'Tata Letak Cetak: tampilkan dokumen sesuai ukuran halaman',
|
||||
@@ -6878,10 +6874,9 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: 'Запись исправлений',
|
||||
ribbonCompare: 'Сравнить',
|
||||
ribbonCompareTip: 'Сравнить: выбрать другой документ и сравнить различия по абзацам',
|
||||
ribbonRestrictEditing: 'Ограничить редактирование',
|
||||
ribbonRestrictEditingTip:
|
||||
'Ограничить редактирование: сделать документ доступным только для чтения',
|
||||
ribbonStopProtectionTip: 'Отключить защиту и продолжить редактирование',
|
||||
ribbonProtectDoc: 'Защитить документ',
|
||||
ribbonProtectDocTip:
|
||||
'Защита документа: пароли на открытие/изменение, ограничения редактирования и конфиденциальность',
|
||||
ribbonGroupProtect: 'Защитить',
|
||||
ribbonPrintLayout: 'Разметка страницы',
|
||||
ribbonPrintLayoutTip: 'Разметка страницы: показать документ в размере страницы',
|
||||
@@ -7563,9 +7558,8 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: 'تعقب',
|
||||
ribbonCompare: 'مقارنة',
|
||||
ribbonCompareTip: 'مقارنة: اختيار مستند آخر ومقارنة الاختلافات فقرة بفقرة',
|
||||
ribbonRestrictEditing: 'تقييد التحرير',
|
||||
ribbonRestrictEditingTip: 'تقييد التحرير: جعل المستند للقراءة فقط',
|
||||
ribbonStopProtectionTip: 'إيقاف الحماية واستئناف التحرير',
|
||||
ribbonProtectDoc: 'حماية المستند',
|
||||
ribbonProtectDocTip: 'حماية المستند: كلمات مرور الفتح/التعديل وقيود التحرير والخصوصية',
|
||||
ribbonGroupProtect: 'حماية',
|
||||
ribbonPrintLayout: 'تخطيط الطباعة',
|
||||
ribbonPrintLayoutTip: 'تخطيط الطباعة: عرض المستند بحجم الصفحة',
|
||||
@@ -8250,9 +8244,9 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: 'Controle',
|
||||
ribbonCompare: 'Comparar',
|
||||
ribbonCompareTip: 'Comparar: escolher outro documento e comparar as diferenças por parágrafo',
|
||||
ribbonRestrictEditing: 'Restringir Edição',
|
||||
ribbonRestrictEditingTip: 'Restringir edição: tornar o documento somente leitura',
|
||||
ribbonStopProtectionTip: 'Parar a proteção e retomar a edição',
|
||||
ribbonProtectDoc: 'Proteger Documento',
|
||||
ribbonProtectDocTip:
|
||||
'Proteger documento: senhas de abertura/modificação, restrições de edição e privacidade',
|
||||
ribbonGroupProtect: 'Proteger',
|
||||
ribbonPrintLayout: 'Layout de Impressão',
|
||||
ribbonPrintLayoutTip: 'Layout de impressão: mostrar o documento no tamanho da página',
|
||||
@@ -8943,9 +8937,9 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonCompare: 'Confronta',
|
||||
ribbonCompareTip:
|
||||
'Confronta: scegli un altro documento e confronta le differenze per paragrafo',
|
||||
ribbonRestrictEditing: 'Limita modifica',
|
||||
ribbonRestrictEditingTip: 'Limita modifica: rendi il documento di sola lettura',
|
||||
ribbonStopProtectionTip: 'Interrompi la protezione e riprendi la modifica',
|
||||
ribbonProtectDoc: 'Proteggi documento',
|
||||
ribbonProtectDocTip:
|
||||
'Proteggi documento: password di apertura/modifica, limitazioni di modifica e privacy',
|
||||
ribbonGroupProtect: 'Proteggi',
|
||||
ribbonPrintLayout: 'Layout di stampa',
|
||||
ribbonPrintLayoutTip: 'Layout di stampa: mostra il documento nelle dimensioni della pagina',
|
||||
@@ -9635,9 +9629,9 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: 'Śledzenie',
|
||||
ribbonCompare: 'Porównaj',
|
||||
ribbonCompareTip: 'Porównaj: wybierz inny dokument i porównaj różnice akapit po akapicie',
|
||||
ribbonRestrictEditing: 'Ogranicz edytowanie',
|
||||
ribbonRestrictEditingTip: 'Ogranicz edytowanie: ustaw dokument jako tylko do odczytu',
|
||||
ribbonStopProtectionTip: 'Zatrzymaj ochronę i wznów edytowanie',
|
||||
ribbonProtectDoc: 'Chroń dokument',
|
||||
ribbonProtectDocTip:
|
||||
'Ochrona dokumentu: hasła otwarcia/modyfikacji, ograniczenia edytowania i prywatność',
|
||||
ribbonGroupProtect: 'Ochrona',
|
||||
ribbonPrintLayout: 'Układ wydruku',
|
||||
ribbonPrintLayoutTip: 'Układ wydruku: pokaż dokument w rozmiarze strony',
|
||||
@@ -10328,9 +10322,9 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: 'Bijhouden',
|
||||
ribbonCompare: 'Vergelijken',
|
||||
ribbonCompareTip: 'Vergelijken: kies een ander document en vergelijk de verschillen per alinea',
|
||||
ribbonRestrictEditing: 'Bewerken beperken',
|
||||
ribbonRestrictEditingTip: 'Bewerken beperken: het document alleen-lezen maken',
|
||||
ribbonStopProtectionTip: 'Beveiliging stoppen en het bewerken hervatten',
|
||||
ribbonProtectDoc: 'Document beveiligen',
|
||||
ribbonProtectDocTip:
|
||||
'Document beveiligen: wachtwoorden voor openen/wijzigen, bewerkingsbeperkingen en privacy',
|
||||
ribbonGroupProtect: 'Beveiligen',
|
||||
ribbonPrintLayout: 'Afdrukweergave',
|
||||
ribbonPrintLayoutTip: 'Afdrukweergave: het document op paginagrootte weergeven',
|
||||
@@ -11020,9 +11014,9 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: 'Penjejakan',
|
||||
ribbonCompare: 'Banding',
|
||||
ribbonCompareTip: 'Banding: pilih dokumen lain dan bandingkan perbezaan mengikut perenggan',
|
||||
ribbonRestrictEditing: 'Hadkan Pengeditan',
|
||||
ribbonRestrictEditingTip: 'Hadkan pengeditan: jadikan dokumen baca sahaja',
|
||||
ribbonStopProtectionTip: 'Hentikan perlindungan dan sambung semula pengeditan',
|
||||
ribbonProtectDoc: 'Lindungi Dokumen',
|
||||
ribbonProtectDocTip:
|
||||
'Lindungi dokumen: kata laluan buka/ubah suai, sekatan penyuntingan dan privasi',
|
||||
ribbonGroupProtect: 'Lindungi',
|
||||
ribbonPrintLayout: 'Tataletak Cetakan',
|
||||
ribbonPrintLayoutTip: 'Tataletak cetakan: paparkan dokumen pada saiz halaman',
|
||||
@@ -11699,9 +11693,8 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: 'מעקב',
|
||||
ribbonCompare: 'השווה',
|
||||
ribbonCompareTip: 'השוואה: בחר מסמך אחר והשווה הבדלים לפי פיסקאות',
|
||||
ribbonRestrictEditing: 'הגבל עריכה',
|
||||
ribbonRestrictEditingTip: 'הגבלת עריכה: הפוך את המסמך לקריאה בלבד',
|
||||
ribbonStopProtectionTip: 'הפסק את ההגנה וחדש את העריכה',
|
||||
ribbonProtectDoc: 'הגנה על המסמך',
|
||||
ribbonProtectDocTip: 'הגנה על המסמך: סיסמאות פתיחה/שינוי, הגבלות עריכה ופרטיות',
|
||||
ribbonGroupProtect: 'הגנה',
|
||||
ribbonPrintLayout: 'פריסת הדפסה',
|
||||
ribbonPrintLayoutTip: 'פריסת הדפסה: הצג את המסמך בגודל העמוד',
|
||||
@@ -12386,9 +12379,8 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonCompare: 'तुलना करें',
|
||||
ribbonCompareTip:
|
||||
'तुलना करें: कोई दूसरा दस्तावेज़ चुनें और अनुच्छेद के अनुसार अंतर की तुलना करें',
|
||||
ribbonRestrictEditing: 'संपादन प्रतिबंधित करें',
|
||||
ribbonRestrictEditingTip: 'संपादन प्रतिबंधित करें: दस्तावेज़ को केवल-पढ़ने योग्य बनाएँ',
|
||||
ribbonStopProtectionTip: 'सुरक्षा रोकें और संपादन फिर से शुरू करें',
|
||||
ribbonProtectDoc: 'दस्तावेज़ सुरक्षित करें',
|
||||
ribbonProtectDocTip: 'दस्तावेज़ सुरक्षा: खोलने/संशोधन पासवर्ड, संपादन प्रतिबंध और गोपनीयता',
|
||||
ribbonGroupProtect: 'सुरक्षा',
|
||||
ribbonPrintLayout: 'प्रिंट लेआउट',
|
||||
ribbonPrintLayoutTip: 'प्रिंट लेआउट: दस्तावेज़ को पृष्ठ आकार में दिखाएँ',
|
||||
@@ -13062,9 +13054,8 @@ export const ribbonStrings = defineStrings({
|
||||
ribbonGroupTracking: '追蹤',
|
||||
ribbonCompare: '比較',
|
||||
ribbonCompareTip: '比較:選擇另一份文件,依段落比對差異',
|
||||
ribbonRestrictEditing: '限制編輯',
|
||||
ribbonRestrictEditingTip: '限制編輯:將文件設為唯讀',
|
||||
ribbonStopProtectionTip: '停止保護,恢復編輯',
|
||||
ribbonProtectDoc: '保護文件',
|
||||
ribbonProtectDocTip: '保護文件:開啟密碼、修改密碼、編輯限制與隱私設定',
|
||||
ribbonGroupProtect: '保護',
|
||||
ribbonPrintLayout: '整頁模式',
|
||||
ribbonPrintLayoutTip: '整頁模式:依頁面大小顯示文件',
|
||||
|
||||
@@ -136,6 +136,11 @@ export function lineHeightFactor(fontFamily: string): number {
|
||||
if (f.includes('pmingliu') || f.includes('mingliu') || f.includes('細明體')) {
|
||||
return 1.3029
|
||||
}
|
||||
// NanumGothic: mac Word lays out with the OS downloadable asset — factor =
|
||||
// its hhea total (1.15em) × Word's 1.3 EA multiplier (the same rule
|
||||
// reproduces Batang 1.3029, Malgun 1.7371, Meiryo 1.9429, Yu 1.44);
|
||||
// ink-band measured 20.24pt at 10pt/1.35x on regression sample run7/19
|
||||
if (/nanum ?gothic|나눔 ?고딕/.test(f)) return 1.495
|
||||
// Korean faces (Word probe 2026-08-13: Malgun 1.7371, Batang class 1.3029)
|
||||
if (KO_FONT_RE.test(f)) return /malgun|맑은/.test(f) ? 1.7371 : 1.3029
|
||||
// Japanese faces: MS (P)Mincho/Gothic substitute into the Hiragino class
|
||||
@@ -367,6 +372,8 @@ export const BUNDLED_FONTS = new Set([
|
||||
'Noto Serif CJK SC',
|
||||
'GenOffice Sans KR',
|
||||
'GenOffice Serif KR',
|
||||
'GenOffice Gothic KR',
|
||||
'GenOffice Tamil',
|
||||
'GenOffice Fullwidth TC',
|
||||
'GenOffice Songti SC',
|
||||
'Carlito GO',
|
||||
@@ -572,12 +579,15 @@ export function cssFontFamily(font: string): string {
|
||||
nfkc,
|
||||
)
|
||||
) {
|
||||
// vendor faces (Nanum...) missing locally follow Word's Batang-ward substitution;
|
||||
// Windows core faces (Malgun/Gulim/Dotum) map cleanly to the sans chain.
|
||||
// Installed Nanum resolves at the literal head (family name is 'NanumGothic',
|
||||
// unspaced, matching the declared name); when missing, mac Word may still use
|
||||
// the OS downloadable asset Chromium cannot see (M3 probe sample 19) — parity
|
||||
// there needs a bundled Nanum-normalized face, not chain order.
|
||||
// Nanum gothic-class declares: mac Word lays out with the OS downloadable
|
||||
// Nanum asset Chromium cannot see (M3 probe sample 19), so the bundled
|
||||
// real-metric subset leads the sans chain instead of the Batang-ward
|
||||
// substitution. Installed Nanum still resolves at the literal head.
|
||||
if (/nanum ?gothic|나눔 ?고딕/i.test(nfkc)) {
|
||||
return `${chain(font, 'GenOffice Gothic KR', ...KO_SANS)},sans-serif`
|
||||
}
|
||||
// other vendor faces missing locally follow Word's Batang-ward substitution;
|
||||
// Windows core faces (Malgun/Gulim/Dotum) map cleanly to the sans chain
|
||||
const knownCore = /malgun|맑은|gulim|굴림|dotum|돋움|apple (sd )?gothic/i.test(nfkc)
|
||||
const serif =
|
||||
/batang|바탕|myeongjo|myungjo|명조|gungsuh|궁서/i.test(nfkc) ||
|
||||
@@ -598,11 +608,12 @@ export function cssFontFamily(font: string): string {
|
||||
if (/nyala|ebrima|abyssinica|ethiopic/i.test(nfkc)) {
|
||||
return `${chain(font, 'GenOffice Ethiopic')},sans-serif`
|
||||
}
|
||||
// Tamil: macOS system faces stand in for Latha/Noto Sans Tamil; on Windows
|
||||
// the declared name resolves natively.
|
||||
// TODO: size-adjust alias to match Latha advances once sample 16 is re-shot
|
||||
// Tamil: Word substitutes missing Tamil families with Latha; the bundled
|
||||
// Latha-metric face (fonts.css) keeps line breaks aligned. On Windows the
|
||||
// declared name resolves natively ahead of it; macOS system faces stay as
|
||||
// coverage tails (the subset ships no Latin letters).
|
||||
if (/tamil|latha|vijaya|inaimathi/i.test(nfkc)) {
|
||||
return `${chain(font, 'InaiMathi', 'Tamil MN', 'Tamil Sangam MN')},sans-serif`
|
||||
return `${chain(font, 'GenOffice Tamil', 'InaiMathi', 'Tamil MN', 'Tamil Sangam MN')},sans-serif`
|
||||
}
|
||||
// unknown font family: guess serif-ness by name (Song/Ming/Serif → serif fallback)
|
||||
const serifLike = /宋|明|serif|song|ming/i.test(font)
|
||||
|
||||
@@ -9,6 +9,9 @@ export interface BlockBox {
|
||||
height: number
|
||||
/** paragraph pageBreakBefore: force a page break before the block */
|
||||
breakBefore?: boolean
|
||||
/** breakBefore comes from a leading w:br (real break character, not the
|
||||
* pageBreakBefore property): honored even on the document's blank first page */
|
||||
breakBeforeBr?: boolean
|
||||
/** block contains a page-break field (w:br type=page): force a page break after it */
|
||||
breakAfter?: boolean
|
||||
/** zero-height break carrier (floating-textbox anchor): the break survives a blank page */
|
||||
@@ -21,10 +24,19 @@ export interface BlockBox {
|
||||
docxIndex?: number
|
||||
/** owning section index (filled by assignSections) */
|
||||
section?: number
|
||||
/** CSS-floated block (square/tight/through image wrap, w:tblpPr table): the
|
||||
* wrapped text beside it carries the vertical extent, so it consumes no
|
||||
* column height itself (block boxes in normal flow stack ignoring floats) */
|
||||
floated?: boolean
|
||||
/** in-block line boundaries (relative to block top, ascending, each = a line's starting Y): used to split page-crossing blocks by line */
|
||||
lineOffsets?: number[]
|
||||
/** min lines kept on each side of a split (widow/orphan control): paragraphs 2, table rows 1 (default) */
|
||||
splitMinLines?: number
|
||||
/** no visible text/image (empty paragraph mark): flows but doesn't count toward column-balance quotas */
|
||||
emptyPara?: boolean
|
||||
/** non-reflowable block's rendered width (tables, protected textboxes/objects):
|
||||
* such a block never advances into a narrower column (Word turns the page instead) */
|
||||
fixedWidthPx?: number
|
||||
|
||||
// ── F2 line-level page-split extensions ─────────────────────────────────
|
||||
/**
|
||||
@@ -122,6 +134,12 @@ export interface PageSlice {
|
||||
* range (= first column start .. last column end); the span can reach columns × column height.
|
||||
*/
|
||||
regions?: PageRegion[]
|
||||
/**
|
||||
* Physical content height actually used on a regioned page (last region top +
|
||||
* its tallest column). The virtual span (end - start) can exceed the page's
|
||||
* content height by stacking columns; canvas gap padding/compression uses this.
|
||||
*/
|
||||
physHeight?: number
|
||||
}
|
||||
|
||||
/** Pagination geometry for one section */
|
||||
@@ -133,6 +151,10 @@ export interface SectionGeom {
|
||||
startType?: SectionInfo['startType']
|
||||
/** equal-width column count (w:cols w:num, default 1): page capacity = columns × column height */
|
||||
cols?: number
|
||||
/** per-column widths (px, length cols) — differ under w:equalWidth="0" */
|
||||
colWidths?: number[]
|
||||
/** nextColumn start with the same column count as the previous section: advance one column at the boundary */
|
||||
colBreakStart?: boolean
|
||||
}
|
||||
|
||||
export function computePageSlices(
|
||||
@@ -213,6 +235,7 @@ export function computeSectionedSlices(
|
||||
}
|
||||
if (block.breakAfter) pendingBreak = true
|
||||
}
|
||||
if (pendingBreak) newPage(Math.max(total, pageStart), curSection)
|
||||
|
||||
const end = Math.max(total, pageStart)
|
||||
return starts.map((s, i) => ({
|
||||
@@ -297,6 +320,15 @@ export function computeSectionedSlicesF2(
|
||||
let columnTurns = 0
|
||||
let runaway = false
|
||||
|
||||
// first block index of the current region (balancing walks this range for line boundaries)
|
||||
let regionStartBi = 0
|
||||
// an explicit column break inside the region disqualifies it from balancing
|
||||
// ("any effective page breaks stop the balancing act"); natural overflow turns
|
||||
// are re-distributed by the balance pass
|
||||
let regionBroke = false
|
||||
// main-loop block index, visible to the region closures for regionStartBi bookkeeping
|
||||
let curBi = 0
|
||||
|
||||
const pushColumn = (y: number, headerH = 0, headerTop = 0) => {
|
||||
if (++columnTurns > maxColumnTurns && !runaway) {
|
||||
runaway = true
|
||||
@@ -316,6 +348,8 @@ export function computeSectionedSlicesF2(
|
||||
colCount = colsOf(section)
|
||||
colH = Math.max(contentH - regionTop, 1)
|
||||
colIdx = 0
|
||||
regionStartBi = curBi
|
||||
regionBroke = false
|
||||
pages[pages.length - 1].regions.push({
|
||||
top: regionTop,
|
||||
height: colH,
|
||||
@@ -341,6 +375,82 @@ export function computeSectionedSlicesF2(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Word column balancing: a multi-column region closed mid-page by a continuous
|
||||
* column-count change redistributes its single-column content across the columns.
|
||||
* Word fills line quotas left to right — target = ceil(visible lines / cols) per
|
||||
* column, empty paragraph marks flow but don't count, and widow/orphan atomicity
|
||||
* keeps short paragraphs whole (trailing columns may stay empty). Explicit column
|
||||
* breaks disable it ("any effective page breaks stop the balancing act"), as do
|
||||
* tables (row structure, v1). Mutates the current region's entries/height;
|
||||
* returns the balanced region height, or null when not applicable.
|
||||
*/
|
||||
const tryBalanceRegion = (endBi: number, endY: number): number | null => {
|
||||
const page = pages[pages.length - 1]
|
||||
const region = page.regions[page.regions.length - 1]
|
||||
if (region.cols <= 1 || regionBroke || runaway) return null
|
||||
const startY = region.entries[0]?.y
|
||||
if (startY === undefined || region.entries[0].repeatHeader) return null
|
||||
// boundary units: block tops always cuttable; in-block line starts cuttable
|
||||
// per widow/orphan atomicity. Each unit carries the counted content height of
|
||||
// its piece (0 for empty paragraph marks — they flow but don't add quota)
|
||||
type Unit = { y: number; h: number; cut: boolean }
|
||||
const units: Unit[] = []
|
||||
// trailing whitespace before the closing block (space-after / inter-section
|
||||
// spacing) must not inflate the last column's extent
|
||||
let contentEnd = startY
|
||||
for (let i = regionStartBi; i < endBi; i++) {
|
||||
const b = blocks[i]
|
||||
if (b.tableRows) return null
|
||||
if (b.floated) continue
|
||||
if (b.top + b.height < startY + 0.01 || b.top > endY - 0.01) continue
|
||||
const bottom = Math.min(b.top + b.height, endY)
|
||||
// trailing empty paragraph marks are absorbed (they don't extend the region)
|
||||
if (!b.emptyPara) contentEnd = Math.max(contentEnd, bottom)
|
||||
const minKeep = b.widowControl !== false ? 2 : 1
|
||||
const lbs = b.lineBoxes && b.lineBoxes.length > 0 ? b.lineBoxes : null
|
||||
const n = lbs ? lbs.length : 1
|
||||
for (let k = 0; k < n; k++) {
|
||||
// a block split across the page boundary contributes only its lines within
|
||||
// the region (clip to startY); its clipped head is not a cut point
|
||||
const rawY = lbs ? b.top + lbs[k].offsetInBlock : b.top
|
||||
if (rawY > endY - 0.01) break
|
||||
const next = lbs && k + 1 < n ? Math.min(b.top + lbs[k + 1].offsetInBlock, bottom) : bottom
|
||||
if (next < startY + 0.01) continue
|
||||
const y = Math.max(rawY, startY)
|
||||
units.push({
|
||||
y,
|
||||
h: b.emptyPara ? 0 : Math.max(next - y, 0),
|
||||
cut: rawY >= startY - 0.01 && (k === 0 || (k >= minKeep && n - k >= minKeep)),
|
||||
})
|
||||
}
|
||||
}
|
||||
const countedH = units.reduce((s, u) => s + u.h, 0)
|
||||
if (countedH <= 0.01 || contentEnd - startY <= 0.01) return null
|
||||
const target = countedH / region.cols
|
||||
const cuts: number[] = []
|
||||
let acc = 0
|
||||
let prevCut = startY
|
||||
for (const u of units) {
|
||||
if (cuts.length >= region.cols - 1) break
|
||||
if (acc >= target - 0.01 && u.cut && u.y > prevCut + 0.01) {
|
||||
cuts.push(u.y)
|
||||
prevCut = u.y
|
||||
acc = 0
|
||||
}
|
||||
acc += u.h
|
||||
}
|
||||
while (cuts.length < region.cols - 1) cuts.push(endY) // trailing empty columns
|
||||
region.entries = [region.entries[0], ...cuts.map((y) => ({ y }))]
|
||||
// column extents measured to the content end (trailing whitespace excluded)
|
||||
const cutEdges = [startY, ...cuts, endY].map((y) => Math.min(y, contentEnd))
|
||||
let maxExtent = 0
|
||||
for (let k = 1; k < cutEdges.length; k++)
|
||||
maxExtent = Math.max(maxExtent, cutEdges[k] - cutEdges[k - 1])
|
||||
region.height = maxExtent
|
||||
return maxExtent
|
||||
}
|
||||
|
||||
// whether height h fits in the current column (runaway degrade: everything fits)
|
||||
const fits = (h: number): boolean => runaway || usedInCol + h <= colH + 0.01
|
||||
// whether the current column is empty (just changed columns or at column top)
|
||||
@@ -348,8 +458,10 @@ export function computeSectionedSlicesF2(
|
||||
// whether the current page is entirely blank (guards forced breaks against empty pages)
|
||||
const pageBlank = () => colIdx === 0 && regionTop <= 0.01 && usedInCol <= 0.01
|
||||
// place height h (unconditional accumulation)
|
||||
let anyContent = false
|
||||
const place = (h: number) => {
|
||||
usedInCol += h
|
||||
anyContent = true
|
||||
}
|
||||
|
||||
startPage(0, initSection)
|
||||
@@ -369,6 +481,7 @@ export function computeSectionedSlicesF2(
|
||||
// ── Main loop ───────────────────────────────────────────────────────────────
|
||||
for (let bi = 0; bi < blocks.length; bi++) {
|
||||
const block = blocks[bi]
|
||||
curBi = bi
|
||||
|
||||
// section change
|
||||
const bSection = block.section ?? curSection
|
||||
@@ -380,8 +493,12 @@ export function computeSectionedSlicesF2(
|
||||
if (g.forceBreak && block.top > pageStart) {
|
||||
startPage(block.top, bSection)
|
||||
} else if (newCols !== colCount) {
|
||||
// continuous section changing column count: open a new region in the remaining page height; if the page is used up, turn the page
|
||||
const regionBottom = regionTop + (colIdx > 0 ? colH : Math.min(usedInCol, colH))
|
||||
// continuous section changing column count: balance the closed multi-column
|
||||
// region (Word), then open a new region in the remaining page height; if the
|
||||
// page is used up, turn the page
|
||||
const balancedH = tryBalanceRegion(bi, block.top)
|
||||
const regionBottom =
|
||||
regionTop + (balancedH ?? (colIdx > 0 ? colH : Math.min(usedInCol, colH)))
|
||||
if (regionBottom >= contentH - 1) {
|
||||
startPage(block.top, bSection)
|
||||
} else {
|
||||
@@ -393,21 +510,72 @@ export function computeSectionedSlicesF2(
|
||||
colH = Math.max(contentH - regionTop, 1)
|
||||
const page = pages[pages.length - 1]
|
||||
page.regions[page.regions.length - 1].height = colH
|
||||
// nextColumn into a same-count section: advance one column at the boundary (no-op at a column top)
|
||||
if (g.colBreakStart && !colEmpty()) {
|
||||
regionBroke = true
|
||||
newColumn(block.top, bSection)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pageBreakBefore (highest priority: force a new page before this block; mid-column breaks also turn the page directly)
|
||||
if ((pendingBreak || block.breakBefore) && (pendingForce || !pageBlank())) {
|
||||
// a pending w:br plus this block's own leading w:br are two distinct break
|
||||
// characters: both turn the page, leaving a deliberate blank sheet between
|
||||
const doubleBreak = pendingBreak && block.breakBeforeBr && !pageBlank()
|
||||
if (doubleBreak) startPage(block.top, curSection)
|
||||
// a leading w:br on the document's first content still breaks (Word keeps the
|
||||
// blank first page); breaks landing on a later blank page stay suppressed
|
||||
if (
|
||||
(pendingBreak || block.breakBefore) &&
|
||||
(doubleBreak ||
|
||||
pendingForce ||
|
||||
!pageBlank() ||
|
||||
(block.breakBeforeBr && !anyContent && pages.length === 1))
|
||||
) {
|
||||
startPage(block.top, curSection)
|
||||
}
|
||||
pendingBreak = false
|
||||
pendingForce = false
|
||||
// column break: change column (turn the page on the last column); no-op at column top
|
||||
if (pendingColBreak && !colEmpty()) {
|
||||
regionBroke = true
|
||||
newColumn(block.top, curSection)
|
||||
}
|
||||
pendingColBreak = false
|
||||
|
||||
// overflow advancement for this block: a non-reflowable block (table/textbox)
|
||||
// never advances into a column narrower than itself — Word turns the page
|
||||
// instead (explicit column breaks above are honored regardless)
|
||||
const advance =
|
||||
block.fixedWidthPx === undefined
|
||||
? newColumn
|
||||
: (y: number, section: number, headerH = 0, headerTop = 0) => {
|
||||
const ws = geomOf(section).colWidths
|
||||
if (
|
||||
colIdx + 1 < colCount &&
|
||||
ws &&
|
||||
(ws[colIdx + 1] ?? Infinity) < block.fixedWidthPx! - 0.5
|
||||
) {
|
||||
startPage(y, section, headerH, headerTop)
|
||||
} else {
|
||||
newColumn(y, section, headerH, headerTop)
|
||||
}
|
||||
}
|
||||
|
||||
// CSS-floated block (wrapped image / w:tblpPr table): following block boxes
|
||||
// stack ignoring it (only their line boxes shorten), so it consumes no column
|
||||
// height — counting it would double-book the overlap and break pages early
|
||||
if (block.floated) {
|
||||
if (!fits(block.height) && !colEmpty()) advance(block.top, curSection)
|
||||
place(0)
|
||||
if (block.breakAfter) {
|
||||
pendingBreak = true
|
||||
if (block.breakForce) pendingForce = true
|
||||
}
|
||||
if (block.colBreakAfter) pendingColBreak = true
|
||||
continue
|
||||
}
|
||||
|
||||
// break-only paragraph: absorbed at the page bottom (overflowing the bottom margin)
|
||||
// unless less than half its height remains — then it opens a Word-style deliberate
|
||||
// blank page. The half-height tolerance far exceeds the ±few-px page-fill drift
|
||||
@@ -433,7 +601,7 @@ export function computeSectionedSlicesF2(
|
||||
place,
|
||||
() => Math.max(colH - usedInCol, 0),
|
||||
colEmpty,
|
||||
newColumn,
|
||||
advance,
|
||||
curSection,
|
||||
)
|
||||
if (block.spaceAfterPx) place(block.spaceAfterPx) // space after the table (may overflow into the bottom margin)
|
||||
@@ -511,7 +679,7 @@ export function computeSectionedSlicesF2(
|
||||
// Only abandon the constraint when chain + anchor demand can't fit even an
|
||||
// empty page (no solution; avoids infinite loops).
|
||||
if (!fits(chainPlusAnchorH) && !colEmpty() && chainPlusAnchorH <= colH) {
|
||||
newColumn(block.top, curSection)
|
||||
advance(block.top, curSection)
|
||||
}
|
||||
// place chain head through chain tail (the keepNext blocks)
|
||||
for (let k = bi; k <= effectiveChainEnd; k++) place(blocks[k].height)
|
||||
@@ -527,7 +695,7 @@ export function computeSectionedSlicesF2(
|
||||
// chain exceeds one page: only guarantee the chain head + anchor demand share a page (minimum guarantee)
|
||||
const headH = block.height + anchorNeedH
|
||||
if (!fits(headH) && !colEmpty()) {
|
||||
newColumn(block.top, curSection)
|
||||
advance(block.top, curSection)
|
||||
}
|
||||
if (!block.keepLines) {
|
||||
// place the chain head block
|
||||
@@ -541,7 +709,7 @@ export function computeSectionedSlicesF2(
|
||||
fits,
|
||||
place,
|
||||
colEmpty,
|
||||
newColumn,
|
||||
advance,
|
||||
curSection,
|
||||
)
|
||||
if (block.breakAfter) {
|
||||
@@ -557,7 +725,7 @@ export function computeSectionedSlicesF2(
|
||||
// keepLines: the whole paragraph must stay on one page (one column in multi-column layout)
|
||||
if (block.keepLines) {
|
||||
if (!fits(block.height) && block.height <= colH && !colEmpty()) {
|
||||
newColumn(block.top, curSection)
|
||||
advance(block.top, curSection)
|
||||
}
|
||||
if (!fits(block.height)) {
|
||||
// paragraph exceeds one page: hard line-level cut (best effort)
|
||||
@@ -570,7 +738,7 @@ export function computeSectionedSlicesF2(
|
||||
fits,
|
||||
place,
|
||||
colEmpty,
|
||||
newColumn,
|
||||
advance,
|
||||
curSection,
|
||||
)
|
||||
} else {
|
||||
@@ -580,7 +748,7 @@ export function computeSectionedSlicesF2(
|
||||
let offset = 0
|
||||
while (block.height - offset > colH - usedInCol + 0.01 && !runaway) {
|
||||
offset += Math.max(colH - usedInCol, 1)
|
||||
newColumn(block.top + Math.min(offset, block.height), curSection)
|
||||
advance(block.top + Math.min(offset, block.height), curSection)
|
||||
}
|
||||
place(block.height - offset)
|
||||
}
|
||||
@@ -606,7 +774,7 @@ export function computeSectionedSlicesF2(
|
||||
fits,
|
||||
place,
|
||||
colEmpty,
|
||||
newColumn,
|
||||
advance,
|
||||
curSection,
|
||||
)
|
||||
if (block.breakAfter) {
|
||||
@@ -616,6 +784,12 @@ export function computeSectionedSlicesF2(
|
||||
if (block.colBreakAfter) pendingColBreak = true
|
||||
}
|
||||
|
||||
// a trailing page break keeps its deliberate blank last page (Word: the final
|
||||
// paragraph mark lands after the break; LO dropping it is tdf#99090); a trailing
|
||||
// column break advances the same way (new page when the last column is used)
|
||||
if (pendingBreak) startPage(Math.max(total, pageStart), curSection)
|
||||
else if (pendingColBreak && !colEmpty()) newColumn(Math.max(total, pageStart), curSection)
|
||||
|
||||
// ── Output: flatten column starts into ranges, aggregate by page (pages with cols>1 regions get regions attached) ──
|
||||
const flat: ColEntry[] = []
|
||||
for (const p of pages) for (const r of p.regions) for (const e of r.entries) flat.push(e)
|
||||
@@ -627,6 +801,11 @@ export function computeSectionedSlicesF2(
|
||||
const entries = p.regions.flatMap((r) => r.entries)
|
||||
const first = entries[0]
|
||||
const multiCol = p.regions.length > 1 || p.regions.some((r) => r.cols > 1)
|
||||
const last = p.regions[p.regions.length - 1]
|
||||
const lastExtent = Math.min(
|
||||
last.height,
|
||||
Math.max(...last.entries.map((e) => endOf.get(e)! - e.y + (e.repeatHeader?.height ?? 0)), 0),
|
||||
)
|
||||
return {
|
||||
start: first.y,
|
||||
end: endOf.get(entries[entries.length - 1])!,
|
||||
@@ -644,6 +823,7 @@ export function computeSectionedSlicesF2(
|
||||
...(e.repeatHeader ? { repeatHeader: e.repeatHeader } : {}),
|
||||
})),
|
||||
})),
|
||||
physHeight: last.top + lastExtent,
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
@@ -1003,28 +1183,161 @@ export function docGridPitchPt(sections: SectionInfo[]): number | null {
|
||||
return pitch === null ? null : pitch / 20
|
||||
}
|
||||
|
||||
/** Equal-width column count of a section (w:cols w:num).
|
||||
* equalWidth="0" (local layout columns in PDF-converted docs, varying widths) is not modeled; treated as 1 column */
|
||||
/** Column count of a section (w:cols w:num; covers equal and explicit-width columns) */
|
||||
export function sectionColumns(s: SectionInfo): number {
|
||||
if (/<w:cols[^>]*w:equalWidth="0"/.test(s.sectPrXml ?? '')) return 1
|
||||
return Math.max(1, s.settings.columns ?? 1)
|
||||
}
|
||||
|
||||
/** Section column width/gap (px): equal-width columns divide evenly per w:cols w:space (default 720 twips) */
|
||||
/** Section column geometry (px). Equal-width columns divide evenly per w:cols
|
||||
* w:space (default 720 twips); w:equalWidth="0" reads the explicit w:col
|
||||
* width/space list (falling back to even division when the list is absent). */
|
||||
export function sectionColGeom(s: SectionInfo): {
|
||||
cols: number
|
||||
/** first column's width — the uniform width when equalWidth */
|
||||
colWidthPx: number
|
||||
gapPx: number
|
||||
equalWidth: boolean
|
||||
/** per-column widths (length cols) */
|
||||
widths: number[]
|
||||
/** gap after column k (length cols-1) */
|
||||
gaps: number[]
|
||||
} {
|
||||
const set = s.settings
|
||||
const contentW = twipsToPx(set.pageWidth - set.marginLeft - set.marginRight)
|
||||
const cols = sectionColumns(s)
|
||||
const gapPx = twipsToPx(set.colSpace ?? 720)
|
||||
return {
|
||||
cols,
|
||||
gapPx,
|
||||
colWidthPx: cols > 1 ? (contentW - gapPx * (cols - 1)) / cols : contentW,
|
||||
const even = cols > 1 ? (contentW - gapPx * (cols - 1)) / cols : contentW
|
||||
let equalWidth = true
|
||||
let widths = Array.from({ length: cols }, () => even)
|
||||
let gaps = Array.from({ length: Math.max(cols - 1, 0) }, () => gapPx)
|
||||
if (cols > 1 && /<w:cols[^>]*w:equalWidth="0"/.test(s.sectPrXml ?? '')) {
|
||||
const colsXml = /<w:cols\b[^>]*>([\s\S]*?)<\/w:cols>/.exec(s.sectPrXml ?? '')?.[1] ?? ''
|
||||
const list = Array.from(colsXml.matchAll(/<w:col\b([^>]*)\/?>/g), (m) => ({
|
||||
w: twipsToPx(parseInt(/w:w="(\d+)"/.exec(m[1])?.[1] ?? '0', 10)),
|
||||
space: twipsToPx(parseInt(/w:space="(\d+)"/.exec(m[1])?.[1] ?? '0', 10)),
|
||||
}))
|
||||
if (list.length === cols && list.every((c) => c.w > 0)) {
|
||||
equalWidth = false
|
||||
widths = list.map((c) => c.w)
|
||||
gaps = list.slice(0, -1).map((c) => c.space)
|
||||
}
|
||||
}
|
||||
return { cols, gapPx, colWidthPx: widths[0] ?? contentW, equalWidth, widths, gaps }
|
||||
}
|
||||
|
||||
/** RTL section (sectPr w:bidi): columns fill right-to-left (visual order only; engine indices stay logical) */
|
||||
export function sectionBidi(s: SectionInfo): boolean {
|
||||
return /<w:bidi(?:\s*\/>|\s+w:val="(?:1|true|on)")/.test(s.sectPrXml ?? '')
|
||||
}
|
||||
|
||||
/** One block's mixed-column canvas placement (consumed by editor/column-layout.ts) */
|
||||
export interface ColumnBlockPlacement {
|
||||
el: HTMLElement
|
||||
/** column width (px); absent in single-column regions */
|
||||
widthPx?: number
|
||||
dx: number
|
||||
dy: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Mixed-column canvas placements: for every block on a regioned page, the
|
||||
* column width plus a per-column constant translate mapping its stacked
|
||||
* single-flow position into the column slot. dy = region top − the column
|
||||
* start's offset from the page start (negative for later columns/regions:
|
||||
* they pull up over the vacated stacked space). Blocks are placed whole by
|
||||
* their top; floated/eless blocks are skipped.
|
||||
*/
|
||||
export function columnLayoutSpecs(
|
||||
blocks: BlockBox[],
|
||||
slices: PageSlice[],
|
||||
sections: SectionInfo[],
|
||||
): ColumnBlockPlacement[] {
|
||||
const specs: ColumnBlockPlacement[] = []
|
||||
if (blocks.length === 0) return specs
|
||||
let bi = 0
|
||||
for (const slice of slices) {
|
||||
if (!slice.regions) {
|
||||
while (bi < blocks.length && blocks[bi].top < slice.end - 0.5) bi++
|
||||
continue
|
||||
}
|
||||
for (const region of slice.regions) {
|
||||
const sec = sections[Math.max(0, Math.min(region.section, sections.length - 1))]
|
||||
if (!sec) continue
|
||||
const geom = sectionColGeom(sec)
|
||||
const rtl = geom.cols > 1 && sectionBidi(sec)
|
||||
// left edge of each column (LTR): cumulative widths + gaps
|
||||
const xs: number[] = []
|
||||
let x = 0
|
||||
for (let c = 0; c < geom.cols; c++) {
|
||||
xs.push(x)
|
||||
x += geom.widths[c] + (geom.gaps[c] ?? 0)
|
||||
}
|
||||
const totalW = x
|
||||
for (let c = 0; c < region.columns.length; c++) {
|
||||
const col = region.columns[c]
|
||||
const w = geom.widths[Math.min(c, geom.widths.length - 1)]
|
||||
const dx = geom.cols > 1 ? (rtl ? totalW - (xs[c] ?? 0) - w : (xs[c] ?? 0)) : 0
|
||||
const dy = region.top - (col.start - slice.start)
|
||||
const widthPx = geom.cols > 1 ? w : undefined
|
||||
if (widthPx === undefined && Math.abs(dx) < 0.01 && Math.abs(dy) < 0.01) {
|
||||
// untouched single-column region at its natural place: no decorations
|
||||
while (bi < blocks.length && blocks[bi].top < col.end - 0.5) bi++
|
||||
continue
|
||||
}
|
||||
while (bi < blocks.length && blocks[bi].top < col.end - 0.5) {
|
||||
const b = blocks[bi]
|
||||
bi++
|
||||
if (!b.el || b.floated) continue
|
||||
if (b.top < col.start - 0.5) continue
|
||||
specs.push({ el: b.el, ...(widthPx !== undefined ? { widthPx } : {}), dx, dy })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return specs
|
||||
}
|
||||
|
||||
/**
|
||||
* sectPr w:vAlign (center/bottom) page shifts: blocks of a vertically aligned
|
||||
* page translate down into the page's free space — purely visual, through the
|
||||
* same decoration channel as column placement (the page band already spans the
|
||||
* full page height, so shifted blocks stay inside their page). 'both'
|
||||
* (justified) keeps top alignment, as does a page where a block crosses either
|
||||
* boundary (shifting one half of a split block would tear it) and multi-column
|
||||
* pages.
|
||||
*/
|
||||
export function vAlignShiftSpecs(
|
||||
blocks: BlockBox[],
|
||||
slices: PageSlice[],
|
||||
sections: SectionInfo[],
|
||||
geoms: SectionGeom[],
|
||||
): ColumnBlockPlacement[] {
|
||||
const specs: ColumnBlockPlacement[] = []
|
||||
if (!sections.some((s) => s.settings.vAlign === 'center' || s.settings.vAlign === 'bottom'))
|
||||
return specs
|
||||
for (const slice of slices) {
|
||||
const va = sections[slice.section]?.settings.vAlign
|
||||
if (va !== 'center' && va !== 'bottom') continue
|
||||
if (slice.regions) continue
|
||||
const colH = geoms[slice.section]?.contentHeight ?? 0
|
||||
const free = colH - (slice.end - slice.start)
|
||||
if (free < 1) continue
|
||||
const dy = va === 'center' ? free / 2 : free
|
||||
const page: ColumnBlockPlacement[] = []
|
||||
let whole = true
|
||||
for (const b of blocks) {
|
||||
if (b.top + b.height <= slice.start + 0.5) continue
|
||||
if (b.top >= slice.end - 0.5) break
|
||||
if (b.top < slice.start - 0.5 || b.top + b.height > slice.end + 2) {
|
||||
whole = false
|
||||
break
|
||||
}
|
||||
if (!b.el || b.floated) continue
|
||||
page.push({ el: b.el, dx: 0, dy })
|
||||
}
|
||||
if (whole) specs.push(...page)
|
||||
}
|
||||
return specs
|
||||
}
|
||||
|
||||
/** SectionInfo[] → pagination geometry
|
||||
@@ -1038,9 +1351,17 @@ export function sectionGeoms(
|
||||
hfHeights?: SectionHfHeights[],
|
||||
): SectionGeom[] {
|
||||
return sections.map((s, i) => {
|
||||
const cols = sectionColumns(s)
|
||||
let forceBreak = false
|
||||
let colBreakStart = false
|
||||
if (i > 0) {
|
||||
if (s.startType !== 'continuous') {
|
||||
// nextColumn with the same multi-column count advances one column (Word,
|
||||
// tdf#135343 c14/c15); a changed count or a single-column layout acts like a
|
||||
// page break (tdf#135343 c12v3, n#750255)
|
||||
colBreakStart =
|
||||
s.startType === 'nextColumn' && cols > 1 && sectionColumns(sections[i - 1]) === cols
|
||||
const asContinuous = s.startType === 'continuous' || colBreakStart
|
||||
if (!asContinuous) {
|
||||
forceBreak = true
|
||||
} else {
|
||||
// continuous section: force a page break if the page size differs from the previous section (e.g. landscape → portrait)
|
||||
@@ -1053,7 +1374,6 @@ export function sectionGeoms(
|
||||
}
|
||||
const set = s.settings
|
||||
const hf = hfHeights?.[i]
|
||||
const cols = sectionColumns(s)
|
||||
return {
|
||||
contentHeight:
|
||||
twipsToPx(set.pageHeight) -
|
||||
@@ -1061,7 +1381,15 @@ export function sectionGeoms(
|
||||
effectiveBottomPx(set, hf?.footerPx ?? 0),
|
||||
forceBreak,
|
||||
startType: s.startType,
|
||||
...(cols > 1 ? { cols } : {}),
|
||||
// colWidths only for explicit-width columns: the narrower-column gate is
|
||||
// meaningless when every column is the same width
|
||||
...(cols > 1
|
||||
? {
|
||||
cols,
|
||||
...(sectionColGeom(s).equalWidth ? {} : { colWidths: sectionColGeom(s).widths }),
|
||||
}
|
||||
: {}),
|
||||
...(colBreakStart && !forceBreak ? { colBreakStart: true } : {}),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1271,10 +1599,18 @@ export function sectionFirstPages(slices: PageSlice[]): boolean[] {
|
||||
* page setup). This is derived and doesn't mutate the authoritative sections state,
|
||||
* so undoing the deletion restores naturally; readSections rebuilds after saving.
|
||||
*/
|
||||
export function liveSections(sections: SectionInfo[], blocks: BlockBox[]): SectionInfo[] {
|
||||
export function liveSections(
|
||||
sections: SectionInfo[],
|
||||
blocks: BlockBox[],
|
||||
/** boundaries in the DOM but not in the block list (zero-height section-break chips) */
|
||||
extraPresent?: Set<number>,
|
||||
/** break paragraphs whose mark is a tracked deletion: Word's markup view drops the break */
|
||||
trackedDeleted?: Set<number>,
|
||||
): SectionInfo[] {
|
||||
if (sections.length <= 1) return sections
|
||||
const present = new Set<number>()
|
||||
const present = new Set<number>(extraPresent)
|
||||
for (const b of blocks) if (b.docxIndex !== undefined) present.add(b.docxIndex)
|
||||
if (trackedDeleted) for (const i of trackedDeleted) present.delete(i)
|
||||
const out: SectionInfo[] = []
|
||||
let carryFirst: number | null = null
|
||||
let changed = false
|
||||
@@ -1323,7 +1659,14 @@ export function pageAt(slices: PageSlice[], y: number): number {
|
||||
export function visiblePageCount(slices: PageSlice[], upTo = slices.length): number {
|
||||
let n = 0
|
||||
for (let i = 0; i < Math.min(upTo, slices.length); i++) {
|
||||
if (i === 0 || slices[i].start !== slices[i - 1].start) n++
|
||||
// a zero-height predecessor is a deliberate blank page (leading/double w:br,
|
||||
// even/odd parity): the page after it is still its own visible page
|
||||
if (
|
||||
i === 0 ||
|
||||
slices[i].start !== slices[i - 1].start ||
|
||||
slices[i - 1].end === slices[i - 1].start
|
||||
)
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -1333,6 +1676,9 @@ export interface MeasuredContent {
|
||||
totalHeight: number
|
||||
/** absolutely-positioned boxes of floating-textbox anchors (virtual coords, shift-neutral) */
|
||||
floats: FloatBox[]
|
||||
/** docxIndex of section-break chips present in the DOM but excluded from the block
|
||||
* list (zero-height in Word): liveSections must still see their boundaries */
|
||||
sectBreaks: Set<number>
|
||||
}
|
||||
|
||||
/** one floating textbox/shape box: DOM element + gapless virtual position */
|
||||
@@ -1377,6 +1723,7 @@ export function measureBlocks(
|
||||
): MeasuredContent {
|
||||
const blocks: BlockBox[] = []
|
||||
const floats: FloatBox[] = []
|
||||
const sectBreaks = new Set<number>()
|
||||
let totalHeight = 0
|
||||
let gapAccum = 0
|
||||
for (const el of Array.from(pm.children) as HTMLElement[]) {
|
||||
@@ -1387,8 +1734,10 @@ export function measureBlocks(
|
||||
}
|
||||
// floating-anchor boxes: absolute children of a zero-height wrapper; record
|
||||
// shift-neutral virtual positions so pages can be extended to contain them
|
||||
if (el.classList.contains('doc-protected-floating')) {
|
||||
for (const box of Array.from(el.querySelectorAll(':scope > .doc-textbox'))) {
|
||||
if (el.classList.contains('doc-protected-floating') || el.classList.contains('doc-img-float')) {
|
||||
for (const box of Array.from(
|
||||
el.querySelectorAll(':scope > .doc-textbox, :scope > .doc-img-wrap'),
|
||||
)) {
|
||||
const b = (box as HTMLElement).getBoundingClientRect()
|
||||
if (b.height <= 0) continue
|
||||
const applied = parseFloat((box as HTMLElement).dataset.pageFloatDy ?? '0') || 0
|
||||
@@ -1399,16 +1748,30 @@ export function measureBlocks(
|
||||
})
|
||||
}
|
||||
}
|
||||
// sectPr-only paragraph: the section-break mark itself has no height in Word
|
||||
// (its editor chip must not occupy a page or hold a forced break's page open),
|
||||
// but its boundary must stay visible to liveSections or the section merges away
|
||||
if (el.classList.contains('doc-protected-sectbreak')) {
|
||||
const idx = el.getAttribute('data-idx')
|
||||
if (idx) sectBreaks.add(parseInt(idx, 10))
|
||||
continue
|
||||
}
|
||||
// Word ignores page-type w:br inside table cells — drop them before deriving flags
|
||||
const breakEls = Array.from(el.querySelectorAll('.doc-field-pagebreak, .doc-page-br')).filter(
|
||||
(b) => !b.closest('td, th'),
|
||||
)
|
||||
const hasBreak = breakEls.length > 0
|
||||
const hasColBreak = Array.from(el.querySelectorAll('.doc-col-br')).some(
|
||||
(b) => !b.closest('td, th'),
|
||||
)
|
||||
// zero-height blocks are skipped, except a break carrier (e.g. a floating
|
||||
// textbox whose anchor paragraph holds a page-type w:br) must still be seen
|
||||
if (rect.height <= 0 && !el.querySelector('.doc-field-pagebreak, .doc-page-br')) continue
|
||||
if (rect.height <= 0 && !hasBreak) continue
|
||||
// in-block gaps from mid-paragraph page breaks: subtract from block height and add to the gap accumulator for later blocks
|
||||
const innerGap = innerGapHeight(el)
|
||||
const top = (rect.top - origin - gapAccum) / zoomFactor
|
||||
const height = (rect.height - innerGap) / zoomFactor
|
||||
const idxAttr = el.getAttribute('data-idx')
|
||||
const breakEls = el.querySelectorAll('.doc-field-pagebreak, .doc-page-br')
|
||||
const hasBreak = breakEls.length > 0
|
||||
// break-only paragraph (br line + ProseMirror trailing-break phantom line): marked
|
||||
// for dedicated placement — Word pushes it into a deliberate blank page when its
|
||||
// line doesn't fit at the page bottom
|
||||
@@ -1422,11 +1785,27 @@ export function measureBlocks(
|
||||
r.setEndBefore(breakEls[0])
|
||||
leadingBreak = !r.toString().trim()
|
||||
}
|
||||
const floated =
|
||||
/(?:^|\s)img-wrap-(?:square|tight|through)-(?:left|right)(?:\s|$)/.test(el.className) ||
|
||||
el.classList.contains('doc-table-float-left') ||
|
||||
el.classList.contains('doc-table-float-right')
|
||||
const emptyPara = !(el.textContent ?? '').trim() && !el.querySelector('img')
|
||||
// non-reflowable blocks keep their rendered width in any column (tables,
|
||||
// anchored/inline textbox shapes; protected text paragraphs still reflow)
|
||||
const fixedWidth =
|
||||
el.tagName === 'TABLE' ||
|
||||
el.classList.contains('doc-protected-textboxes') ||
|
||||
!!el.querySelector('table')
|
||||
blocks.push({
|
||||
top,
|
||||
height,
|
||||
...(floated ? { floated: true } : {}),
|
||||
...(emptyPara ? { emptyPara: true } : {}),
|
||||
...(fixedWidth ? { fixedWidthPx: rect.width / zoomFactor } : {}),
|
||||
breakBefore: el.classList.contains('page-break-before') || leadingBreak || undefined,
|
||||
breakBeforeBr: leadingBreak || undefined,
|
||||
breakAfter: (hasBreak && !leadingBreak) || undefined,
|
||||
colBreakAfter: hasColBreak || undefined,
|
||||
breakForce: (hasBreak && rect.height <= 0) || undefined,
|
||||
el,
|
||||
...(breakOnly ? { breakOnlyLineH: height } : {}),
|
||||
@@ -1458,7 +1837,7 @@ export function measureBlocks(
|
||||
blocks[0].height += lead
|
||||
blocks[0].top = 0
|
||||
}
|
||||
return { blocks, totalHeight, floats }
|
||||
return { blocks, totalHeight, floats, sectBreaks }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1562,12 +1941,15 @@ export function sliceWithLineSplit(
|
||||
metaOf?: BlockMetaOf,
|
||||
): PageSlice[] {
|
||||
if (metaOf) applyBlockMeta(blocks, metaOf)
|
||||
const slices = computeSectionedSlicesF2(blocks, geoms, totalHeight)
|
||||
const changed = fillLineBoxes(blocks, geoms, zoomFactor, slices, metaOf)
|
||||
return insertParityBlanks(
|
||||
changed ? computeSectionedSlicesF2(blocks, geoms, totalHeight) : slices,
|
||||
geoms,
|
||||
)
|
||||
let slices = computeSectionedSlicesF2(blocks, geoms, totalHeight)
|
||||
// re-slicing can surface new candidate blocks (a block pushed to a page top only
|
||||
// after an earlier block gained line data) — iterate to a fixed point, bounded
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const changed = fillLineBoxes(blocks, geoms, zoomFactor, slices, metaOf)
|
||||
if (!changed) break
|
||||
slices = computeSectionedSlicesF2(blocks, geoms, totalHeight)
|
||||
}
|
||||
return insertParityBlanks(slices, geoms)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,19 +1,11 @@
|
||||
/**
|
||||
* Review-tab actions: footnotes/endnotes, comments, revisions, ink
|
||||
* annotations, document protection and compare. Extracted from App.tsx; the
|
||||
* App component passes a ReviewContext built fresh per call so state never
|
||||
* goes stale.
|
||||
* annotations and compare (document protection lives in ProtectDialog +
|
||||
* App.applyProtectDialog). Extracted from App.tsx; the App component passes a
|
||||
* ReviewContext built fresh per call so state never goes stale.
|
||||
*/
|
||||
import type { Editor } from '@tiptap/core'
|
||||
import {
|
||||
hashProtectionPassword,
|
||||
nextNoteId,
|
||||
parseDocx,
|
||||
verifyProtectionPassword,
|
||||
type CommentInfo,
|
||||
type DocProtection,
|
||||
type NoteInfo,
|
||||
} from '@genoffice/docx-engine'
|
||||
import { nextNoteId, parseDocx, type CommentInfo, type NoteInfo } from '@genoffice/docx-engine'
|
||||
import type { Dispatch, SetStateAction } from 'react'
|
||||
import type { DocState } from './doc-state'
|
||||
import {
|
||||
@@ -39,13 +31,6 @@ export interface NotePrompt {
|
||||
id?: string
|
||||
}
|
||||
|
||||
/** Protection toggle dialog: set = enable (password may be blank), unlock = removing requires password verification */
|
||||
export interface ProtectModalState {
|
||||
mode: 'set' | 'unlock'
|
||||
value: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
/** The App state the review actions need; built fresh per call. */
|
||||
export interface ReviewContext {
|
||||
editor: Editor | null
|
||||
@@ -66,11 +51,6 @@ export interface ReviewContext {
|
||||
setShowComments: (show: boolean) => void
|
||||
setInkAnnotations: Dispatch<SetStateAction<InkAnnotation[]>>
|
||||
setInksDirty: (dirty: boolean) => void
|
||||
protection: DocProtection | null
|
||||
setProtection: (value: DocProtection | null) => void
|
||||
setProtectionDirty: (dirty: boolean) => void
|
||||
protectModal: ProtectModalState | null
|
||||
setProtectModal: (value: ProtectModalState | null) => void
|
||||
setCompareResult: (value: { otherName: string; entries: CompareEntry[] } | null) => void
|
||||
}
|
||||
|
||||
@@ -244,51 +224,16 @@ export function clearInks(ctx: ReviewContext): void {
|
||||
ctx.setStatus(t('appInksCleared'))
|
||||
}
|
||||
|
||||
export function toggleProtection(ctx: ReviewContext): void {
|
||||
if (ctx.protection?.enforced && ctx.protection.edit === 'readOnly') {
|
||||
if (ctx.protection.hash) {
|
||||
ctx.setProtectModal({ mode: 'unlock', value: '' })
|
||||
} else {
|
||||
ctx.setProtection(null)
|
||||
ctx.setProtectionDirty(true)
|
||||
ctx.dirtyRef.current = true
|
||||
}
|
||||
} else {
|
||||
ctx.setProtectModal({ mode: 'set', value: '' })
|
||||
}
|
||||
}
|
||||
|
||||
export async function submitProtectModal(ctx: ReviewContext): Promise<void> {
|
||||
if (!ctx.protectModal) return
|
||||
if (ctx.protectModal.mode === 'set') {
|
||||
const pwd = ctx.protectModal.value
|
||||
const creds = pwd ? await hashProtectionPassword(pwd) : {}
|
||||
ctx.setProtection({ edit: 'readOnly', enforced: true, ...creds })
|
||||
ctx.setProtectionDirty(true)
|
||||
ctx.dirtyRef.current = true
|
||||
ctx.setProtectModal(null)
|
||||
ctx.setStatus(pwd ? t('appProtectionEnabledPwd') : t('appProtectionEnabled'))
|
||||
} else {
|
||||
const ok = ctx.protection
|
||||
? await verifyProtectionPassword(ctx.protectModal.value, ctx.protection)
|
||||
: true
|
||||
if (!ok) {
|
||||
ctx.setProtectModal({ ...ctx.protectModal, error: t('appWrongPassword') })
|
||||
return
|
||||
}
|
||||
ctx.setProtection(null)
|
||||
ctx.setProtectionDirty(true)
|
||||
ctx.dirtyRef.current = true
|
||||
ctx.setProtectModal(null)
|
||||
ctx.setStatus(t('appProtectionRemoved'))
|
||||
}
|
||||
}
|
||||
|
||||
/** Compare: pick a second .docx and diff it against the open document */
|
||||
export async function compareWithFile(ctx: ReviewContext): Promise<void> {
|
||||
if (!ctx.doc) return
|
||||
const other = await window.desktop.openDocx()
|
||||
if (!other) return
|
||||
// password-protected comparison target: not wired through the decrypt prompt (yet)
|
||||
if ('needsPassword' in other) {
|
||||
ctx.setStatus(t('appCompareFailed', { error: t('appDocPwdTitle') }))
|
||||
return
|
||||
}
|
||||
try {
|
||||
const otherParsed = await parseDocx(new Uint8Array(other.data))
|
||||
const entries = compareParagraphs(
|
||||
|
||||
@@ -2124,6 +2124,23 @@ th.cell-rev-del {
|
||||
column-fill: auto;
|
||||
}
|
||||
|
||||
/* mixed-column canvas layout (sections with differing column specs): blocks keep the
|
||||
engine's stacked flow and are painted into their column slot by a per-block width +
|
||||
constant translate; the width also applies in preview clones (line breaks must match) */
|
||||
.doc-page .doc-col-block {
|
||||
width: var(--col-w, auto);
|
||||
}
|
||||
|
||||
.editor-scroll .doc-page:not(.measuring-columns) .doc-col-block {
|
||||
transform: translate(var(--col-dx, 0px), var(--col-dy, 0px));
|
||||
}
|
||||
|
||||
/* single-flow measuring state: transforms and the column-space pull-up must not
|
||||
distort the 1-D virtual coordinates */
|
||||
.editor-scroll .doc-page.measuring-columns .page-gap {
|
||||
margin-top: 0 !important;
|
||||
}
|
||||
|
||||
/* page border (w:pgBorders): a box inset from the page edge */
|
||||
.page-bordered .doc-page {
|
||||
outline: 1.5px solid var(--docs-paper-ink-dim);
|
||||
@@ -2557,6 +2574,31 @@ th.cell-rev-del {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* balloon mode (print view, All Markup): deletions and format-change chrome move
|
||||
to margin balloons and leave the text flow (Word's balloon view); insertions
|
||||
stay inline. Collapsed paragraphs are fully deleted ones whose mark is also
|
||||
deleted — Word shows no trace of them in the body. */
|
||||
.rev-balloon .doc-del,
|
||||
.rev-balloon .doc-para-del-collapse {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* deleted table rows/cells leave the flow with their fills (Word shows them balloon-side only) */
|
||||
.rev-balloon tr.row-rev-del,
|
||||
.rev-balloon td.cell-rev-del,
|
||||
.rev-balloon th.cell-rev-del {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.rev-balloon .has-ppr-change {
|
||||
border-left: none;
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
.rev-balloon .has-ppr-change::after {
|
||||
content: none;
|
||||
}
|
||||
|
||||
/* Compare result pane */
|
||||
.compare-meta {
|
||||
padding: 8px 12px;
|
||||
@@ -3875,6 +3917,37 @@ th.cell-rev-del {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
/* wrapNone / behind-text anchored images: same zero-flow-height semantics */
|
||||
.doc-protected.doc-img-float {
|
||||
position: relative;
|
||||
height: 0;
|
||||
min-height: 0;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
border: none;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.doc-img-float > .doc-img-wrap {
|
||||
translate: 0 var(--page-float-dy, 0px);
|
||||
}
|
||||
|
||||
/* cell-anchored boxes share the float display-shift channel (paper-top clamp) */
|
||||
.doc-cell-boxes > .doc-textbox,
|
||||
.doc-cell-boxes > div {
|
||||
translate: 0 var(--page-float-dy, 0px);
|
||||
}
|
||||
.pv-clip .doc-cell-boxes > .doc-textbox,
|
||||
.pv-clip .doc-cell-boxes > div {
|
||||
translate: none;
|
||||
}
|
||||
|
||||
.pv-clip .doc-img-float > .doc-img-wrap {
|
||||
translate: none;
|
||||
}
|
||||
|
||||
/* anchor-paragraph text next to all-floating boxes keeps its flow line:
|
||||
the wrapper takes the stray line's height instead of collapsing */
|
||||
.doc-protected.doc-protected-floating.doc-protected-floating-stray {
|
||||
@@ -3989,11 +4062,27 @@ th.cell-rev-del {
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
/* empty section-break paragraphs: invisible unless hovered/selected */
|
||||
/* empty section-break paragraphs: zero flow height like Word's absorbed section
|
||||
mark (a 26px strip shifted every page below it); the label is an absolute
|
||||
overlay (transparent until the node is selected), so it never takes flow space */
|
||||
.doc-protected-sectbreak {
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
padding: 0 0 2px;
|
||||
padding: 0;
|
||||
border-width: 0;
|
||||
margin: 0;
|
||||
height: 0;
|
||||
min-height: 0;
|
||||
position: relative;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.doc-protected-sectbreak .doc-sectbreak-label {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.doc-protected-sectbreak:hover {
|
||||
@@ -4443,10 +4532,14 @@ th.cell-rev-del {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* SmartArt / drawing-canvas blocks: the shapes are the content — no chip box */
|
||||
/* SmartArt / drawing-canvas blocks: the shapes are the content — no chip box.
|
||||
Zero padding: the block footprint must equal the declared wp:extent so
|
||||
pagination matches Word (the dashed 1px border stays as hover chrome). */
|
||||
.doc-protected-diagram {
|
||||
border-color: transparent;
|
||||
background: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.doc-protected-diagram:hover {
|
||||
@@ -4641,9 +4734,21 @@ th.cell-rev-del {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* behind text / in front of text: the flowing canvas has no absolutely positioned layer; reduced opacity as an approximation */
|
||||
.doc-protected.img-wrap-behind {
|
||||
opacity: 0.45;
|
||||
/* floating tables (w:tblpPr): text flows around the free side */
|
||||
.doc-table.doc-table-float-left {
|
||||
float: left;
|
||||
margin: 2px 12px 6px 0;
|
||||
}
|
||||
|
||||
.doc-table.doc-table-float-right {
|
||||
float: right;
|
||||
margin: 2px 0 6px 12px;
|
||||
}
|
||||
|
||||
/* behind text: the absolutely positioned wrap drops under the flow's inline
|
||||
content (negative z-index stays above the paper: no intermediate background) */
|
||||
.img-wrap-behind > .doc-img-wrap {
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
.ProseMirror-focused
|
||||
@@ -6342,6 +6447,62 @@ body.docs-crop-active
|
||||
border-color: var(--word-blue);
|
||||
}
|
||||
|
||||
/* ---- Protect Document dialog (Review > Protect, Word's Password Protect layout) ---- */
|
||||
|
||||
.modal.protect-dialog {
|
||||
width: 480px;
|
||||
max-height: calc(100vh - 80px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.protect-dialog .protect-section-title {
|
||||
margin: 16px 0 10px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--border);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.protect-dialog h2 + .protect-section-title {
|
||||
margin-top: 0;
|
||||
padding-top: 0;
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
/* checkbox / radio rows: inline control, not the stacked full-width input */
|
||||
.protect-dialog label.protect-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.protect-dialog label.protect-check input {
|
||||
display: inline-block;
|
||||
width: auto;
|
||||
height: auto;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* the four Word protection modes, indented under the enable checkbox */
|
||||
.protect-dialog .protect-modes {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0 12px;
|
||||
margin: 0 0 10px 24px;
|
||||
}
|
||||
|
||||
.protect-dialog .protect-modes .protect-check {
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.protect-dialog .pgnum-hint {
|
||||
margin: -6px 0 12px;
|
||||
}
|
||||
|
||||
/* ---- print dialog (Word-style: page preview + range options) ---- */
|
||||
|
||||
.modal.print-dialog {
|
||||
@@ -7769,6 +7930,25 @@ tr > .page-gap-cut {
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
/* revision balloons (Deleted:/Formatted:) share the bubble frame, keyed by revision ink */
|
||||
.rev-bubble {
|
||||
cursor: default;
|
||||
border-left-color: var(--docs-paper-rev-ink);
|
||||
}
|
||||
|
||||
.rev-bubble .rev-bubble-label {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.rev-bubble .rev-bubble-text {
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.rev-bubble-del .rev-bubble-text {
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
/* nested table inside a cell (read-only child table) */
|
||||
/* anchored shapes/textboxes inside a cell: in-flow spacer sized to the boxes'
|
||||
extent (Word grows the row), boxes positioned absolutely within it */
|
||||
@@ -7779,6 +7959,12 @@ tr > .page-gap-cut {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
/* the zero-width host must not collapse an absolutely-positioned box:
|
||||
its own width (from the anchor extent) wins over the 100% cap */
|
||||
.doc-cell-boxes > .doc-textbox {
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.doc-nested-table {
|
||||
margin: 2px 0;
|
||||
}
|
||||
@@ -8268,3 +8454,14 @@ tr > .page-gap-cut {
|
||||
.shape-palette.rb-shape-gallery {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Whitespace-only runs: Word ignores their font size for line height (tdf#137335).
|
||||
Only the run's own [data-doc-style] span carries the oversized font-size — outer
|
||||
comment/ins/del spans inherit the paragraph size and contribute nothing — so zero
|
||||
that span and everything nested inside it (intermediate marks, the decoration),
|
||||
without touching ancestor spans that may also wrap real text. */
|
||||
.doc-page .doc-ws-run,
|
||||
.doc-page span[data-doc-style]:has(.doc-ws-run),
|
||||
.doc-page span[data-doc-style]:has(.doc-ws-run) span {
|
||||
line-height: 0;
|
||||
}
|
||||
|
||||
@@ -5,8 +5,27 @@ export interface OpenFileResult {
|
||||
data: ArrayBuffer
|
||||
/** sha256 of the original file; original archived under this hash */
|
||||
hash: string
|
||||
/** the on-disk file is password protected (opened via decrypt; saves re-encrypt) */
|
||||
encrypted?: boolean
|
||||
/** content came from a newer crash-recovery copy and still needs an explicit save */
|
||||
recovered?: boolean
|
||||
}
|
||||
|
||||
/** Password-protected (ECMA-376 encrypted) docx: the renderer prompts for the
|
||||
* open password and retries via openDocxDecrypt. */
|
||||
export interface OpenFileNeedsPassword {
|
||||
needsPassword: true
|
||||
path: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export type OpenDocxResult = OpenFileResult | OpenFileNeedsPassword | null
|
||||
|
||||
/** result of an openDocxDecrypt attempt; wrong-password keeps the prompt open */
|
||||
export type DecryptOpenResult =
|
||||
| { ok: true; result: OpenFileResult }
|
||||
| { ok: false; reason: 'wrong-password' | 'unsupported' | 'error'; error?: string }
|
||||
|
||||
export interface PickImageResult {
|
||||
/** raw image bytes, base64 encoded */
|
||||
base64: string
|
||||
@@ -153,14 +172,23 @@ export interface DesktopApi {
|
||||
/** press on the shell chrome (tab strip is a sibling WebContentsView whose
|
||||
* clicks produce no DOM event here) — dismiss open popovers */
|
||||
onChromePressed(handler: () => void): () => void
|
||||
openDocx(): Promise<OpenFileResult | null>
|
||||
openDocxPath(path: string): Promise<OpenFileResult | null>
|
||||
openDocx(): Promise<OpenDocxResult>
|
||||
openDocxPath(path: string): Promise<OpenDocxResult>
|
||||
/** decrypt-and-open a password-protected docx (path from a needsPassword result) */
|
||||
openDocxDecrypt(path: string, password: string): Promise<DecryptOpenResult>
|
||||
/** Review > Protect: set (or clear with null) the desired next-save password;
|
||||
* filePath null = document not saved yet, applied on its first successful save */
|
||||
setDocPassword(filePath: string | null, password: string | null): Promise<{ ok: boolean }>
|
||||
/** snapshot the current intent sequence before replacement cleanup is queued */
|
||||
docPasswordIntentRevision(): Promise<number>
|
||||
/** discard prior-document intents through a captured revision */
|
||||
discardDocPasswordIntents(throughRevision: number): Promise<{ ok: boolean }>
|
||||
/** mark the renderer ready and consume a file passed by Finder/Explorer at launch */
|
||||
consumePendingOpenDocx(): Promise<OpenFileResult | null>
|
||||
consumePendingOpenDocx(): Promise<OpenDocxResult>
|
||||
/** returns true when this tab was created via "New Document" and should start blank */
|
||||
consumeNewBlankDoc(): Promise<boolean>
|
||||
/** receive documents opened from Finder/Explorer while the app is running */
|
||||
onOpenDocx(handler: (result: OpenFileResult) => void): () => void
|
||||
onOpenDocx(handler: (result: Exclude<OpenDocxResult, null>) => void): () => void
|
||||
/** File was renamed externally (renamed in the shell Home list) — pushes old and new paths; renderer syncs its save path and title bar */
|
||||
onRenamedDocx(handler: (paths: { oldPath: string; newPath: string }) => void): () => void
|
||||
/** auto=true marks an autosave: an externally modified file then fails with
|
||||
@@ -170,20 +198,29 @@ export interface DesktopApi {
|
||||
path: string,
|
||||
data: ArrayBuffer,
|
||||
auto?: boolean,
|
||||
): Promise<{ ok: boolean; error?: string; reason?: 'external-modified' }>
|
||||
): Promise<{
|
||||
ok: boolean
|
||||
error?: string
|
||||
reason?: 'external-modified'
|
||||
/** a newer password choice arrived after this save's snapshot */
|
||||
passwordIntentPending?: boolean
|
||||
}>
|
||||
/** crash-recovery copy of a dirty document, stored under userData */
|
||||
writeRecoveryCopy(path: string, data: ArrayBuffer): Promise<{ ok: boolean }>
|
||||
/** tab closed but webContents kept alive (shell freeze workaround) — stop background timers */
|
||||
onTeardown(handler: () => void): () => void
|
||||
/** sourcePath: the document's current path — Save As uses its desired next-save
|
||||
* password and commits that state to the chosen path only after success */
|
||||
saveDocxAs(
|
||||
defaultName: string,
|
||||
data: ArrayBuffer,
|
||||
): Promise<{ ok: boolean; path?: string; error?: string }>
|
||||
sourcePath?: string | null,
|
||||
): Promise<{ ok: boolean; path?: string; error?: string; passwordIntentPending?: boolean }>
|
||||
/** first save of a new document: silently writes into the default folder, no dialog */
|
||||
saveDocxNew(
|
||||
defaultName: string,
|
||||
data: ArrayBuffer,
|
||||
): Promise<{ ok: boolean; path?: string; error?: string }>
|
||||
): Promise<{ ok: boolean; path?: string; error?: string; passwordIntentPending?: boolean }>
|
||||
getRecentFiles(): Promise<string[]>
|
||||
pickImage(): Promise<PickImageResult | null>
|
||||
/** vertical metrics of an installed family (exact name match), null when missing */
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Arrowing away from a fresh empty paragraph and back must not drop the
|
||||
* pending format (Word keeps it on the paragraph mark): Calibri text +
|
||||
* Enter + Up + Down + type used to produce the document default (r114).
|
||||
*/
|
||||
import { Editor } from '@tiptap/core'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { editorExtensions } from '../src/renderer/editor/extensions'
|
||||
|
||||
const CALIBRI = { font: 'Calibri', sizeHalfPoints: 24 }
|
||||
|
||||
const editorWithStyledText = () =>
|
||||
new Editor({
|
||||
element: document.createElement('div'),
|
||||
extensions: editorExtensions,
|
||||
content: {
|
||||
type: 'doc',
|
||||
content: [
|
||||
{
|
||||
type: 'docParagraph',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'hello',
|
||||
marks: [{ type: 'docTextStyle', attrs: CALIBRI }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} as never,
|
||||
})
|
||||
|
||||
const textStyleOf = (
|
||||
marks: readonly { type: { name: string }; attrs: Record<string, unknown> }[],
|
||||
) => marks.find((mark) => mark.type.name === 'docTextStyle')?.attrs
|
||||
|
||||
describe('caret marks memory (r114)', () => {
|
||||
it('keeps the pending format across arrow navigation out of and back into an empty paragraph', () => {
|
||||
const editor = editorWithStyledText()
|
||||
// caret at end of "hello", split like Enter does (marks carry as storedMarks)
|
||||
editor.commands.setTextSelection(6)
|
||||
editor.commands.splitBlock({ keepMarks: true })
|
||||
expect(editor.state.doc.childCount).toBe(2)
|
||||
// the plugin stamped the pending marks onto the empty paragraph
|
||||
const stamped = editor.state.doc.child(1).attrs.caretMarks as string | null
|
||||
expect(stamped).toContain('Calibri')
|
||||
|
||||
// arrow up (selection into the first paragraph) clears stored marks
|
||||
editor.commands.setTextSelection(3)
|
||||
// arrow back down into the empty paragraph
|
||||
editor.commands.setTextSelection(editor.state.doc.content.size - 1)
|
||||
const restored = editor.state.storedMarks
|
||||
expect(restored).not.toBeNull()
|
||||
expect(textStyleOf(restored!)).toMatchObject(CALIBRI)
|
||||
|
||||
// typing consumes the restored marks
|
||||
editor.view.dispatch(editor.state.tr.insertText('x'))
|
||||
const typed = editor.state.doc.child(1).firstChild!
|
||||
expect(typed.text).toBe('x')
|
||||
expect(textStyleOf(typed.marks)).toMatchObject(CALIBRI)
|
||||
editor.destroy()
|
||||
})
|
||||
|
||||
it('an explicitly cleared pending format is respected (empty storedMarks array wins)', () => {
|
||||
const editor = editorWithStyledText()
|
||||
editor.commands.setTextSelection(6)
|
||||
editor.commands.splitBlock({ keepMarks: true })
|
||||
// user clears formatting on the empty paragraph: storedMarks becomes []
|
||||
editor.view.dispatch(editor.state.tr.setStoredMarks([]))
|
||||
// stamp follows the clear
|
||||
expect(editor.state.doc.child(1).attrs.caretMarks).toBeNull()
|
||||
editor.destroy()
|
||||
})
|
||||
|
||||
it('does not invent marks for paragraphs that never had a pending format', () => {
|
||||
const editor = new Editor({
|
||||
element: document.createElement('div'),
|
||||
extensions: editorExtensions,
|
||||
content: {
|
||||
type: 'doc',
|
||||
content: [{ type: 'docParagraph' }, { type: 'docParagraph' }],
|
||||
} as never,
|
||||
})
|
||||
editor.commands.setTextSelection(1)
|
||||
editor.commands.setTextSelection(editor.state.doc.content.size - 1)
|
||||
expect(editor.state.storedMarks).toBeNull()
|
||||
editor.destroy()
|
||||
})
|
||||
})
|
||||
@@ -26,6 +26,11 @@ const para = (...content: JsonNode[]): JsonNode => ({
|
||||
attrs: { docxIndex: null },
|
||||
content,
|
||||
})
|
||||
const paraWithAttrs = (attrs: Record<string, unknown>, ...content: JsonNode[]): JsonNode => ({
|
||||
type: 'docParagraph',
|
||||
attrs: { docxIndex: null, ...attrs },
|
||||
content,
|
||||
})
|
||||
|
||||
function createEditor(content: JsonNode[]): Editor {
|
||||
return new Editor({
|
||||
@@ -74,7 +79,9 @@ describe('addCommentToSelection', () => {
|
||||
})
|
||||
|
||||
it('merges with an existing overlapping comment', () => {
|
||||
const editor = createEditor([para(text('ab'), text('cd', [{ type: 'comment', attrs: { ids: '1' } }]))])
|
||||
const editor = createEditor([
|
||||
para(text('ab'), text('cd', [{ type: 'comment', attrs: { ids: '1' } }])),
|
||||
])
|
||||
select(editor, 1, 5) // covers ab + cd
|
||||
addCommentToSelection(editor, '2')
|
||||
expect(commentIdsPerNode(editor)).toEqual(['2', '1 2'])
|
||||
@@ -91,7 +98,9 @@ describe('addCommentToSelection', () => {
|
||||
|
||||
describe('removeCommentFromDoc', () => {
|
||||
it('removes the mark when the id was the last one', () => {
|
||||
const editor = createEditor([para(text('x'), text('marked', [{ type: 'comment', attrs: { ids: '1' } }]))])
|
||||
const editor = createEditor([
|
||||
para(text('x'), text('marked', [{ type: 'comment', attrs: { ids: '1' } }])),
|
||||
])
|
||||
removeCommentFromDoc(editor, '1')
|
||||
expect(commentIdsPerNode(editor)).toEqual([null])
|
||||
editor.destroy()
|
||||
@@ -105,6 +114,19 @@ describe('removeCommentFromDoc', () => {
|
||||
expect(commentIdsPerNode(editor)).toEqual(['2'])
|
||||
editor.destroy()
|
||||
})
|
||||
|
||||
it('clears cross-paragraph endpoint attrs while retaining other comment ids', () => {
|
||||
const editor = createEditor([
|
||||
paraWithAttrs({ commentStarts: ['1', '2'] }, text('range starts')),
|
||||
paraWithAttrs({ commentEnds: ['1'] }, text('range ends')),
|
||||
])
|
||||
removeCommentFromDoc(editor, '1')
|
||||
expect(editor.state.doc.child(0).attrs.commentStarts).toEqual(['2'])
|
||||
expect(editor.state.doc.child(0).attrs.commentEnds).toBeNull()
|
||||
expect(editor.state.doc.child(1).attrs.commentStarts).toBeNull()
|
||||
expect(editor.state.doc.child(1).attrs.commentEnds).toBeNull()
|
||||
editor.destroy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('pending comment highlight', () => {
|
||||
|
||||
@@ -15,12 +15,12 @@ const COMMENTS_XML =
|
||||
'</w:comments>'
|
||||
|
||||
const COMMENTED_P =
|
||||
'<w:p><w:r><w:t>before </w:t></w:r>' +
|
||||
'<w:p><w:r><w:t xml:space="preserve">before </w:t></w:r>' +
|
||||
'<w:commentRangeStart w:id="7"/>' +
|
||||
'<w:r><w:t>marked</w:t></w:r>' +
|
||||
'<w:commentRangeEnd w:id="7"/>' +
|
||||
'<w:r><w:commentReference w:id="7"/></w:r>' +
|
||||
'<w:r><w:t> after</w:t></w:r></w:p>'
|
||||
'<w:r><w:t xml:space="preserve"> after</w:t></w:r></w:p>'
|
||||
|
||||
async function loadEditor() {
|
||||
const bytes = await buildDocx({
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
runsToInline,
|
||||
signatureOfBlock,
|
||||
signatureOfGenerated,
|
||||
tableModelToPmNode,
|
||||
type PmNode,
|
||||
} from '../src/renderer/editor/convert'
|
||||
|
||||
@@ -59,6 +60,8 @@ describe('runsToInline image runs', () => {
|
||||
wrap: null,
|
||||
offsetXEmu: null,
|
||||
offsetYEmu: null,
|
||||
border: null,
|
||||
lineCenterV: false,
|
||||
},
|
||||
},
|
||||
])
|
||||
@@ -79,6 +82,8 @@ describe('runsToInline image runs', () => {
|
||||
wrap: null,
|
||||
offsetXEmu: null,
|
||||
offsetYEmu: null,
|
||||
border: null,
|
||||
lineCenterV: false,
|
||||
},
|
||||
},
|
||||
])
|
||||
@@ -250,6 +255,25 @@ describe('section row-height cap (declared trHeight taller than a page)', () =>
|
||||
})
|
||||
})
|
||||
|
||||
describe('oversize floating tables (w:tblpPr) lose the float', () => {
|
||||
const row = [{ paras: ['x'] }]
|
||||
|
||||
it('a table taller than a page flows instead of floating', () => {
|
||||
const model: TableModel = { rows: Array.from({ length: 60 }, () => row), floatSide: 'left' }
|
||||
expect(tableModelToPmNode(model).attrs!.tblFloat).toBeNull()
|
||||
})
|
||||
|
||||
it('a small floating table keeps its side', () => {
|
||||
const model: TableModel = { rows: [row, row], floatSide: 'right' }
|
||||
expect(tableModelToPmNode(model).attrs!.tblFloat).toBe('right')
|
||||
})
|
||||
|
||||
it('declared row heights count toward the overflow estimate', () => {
|
||||
const model: TableModel = { rows: [row], rowHeightsTwips: [20000], floatSide: 'left' }
|
||||
expect(tableModelToPmNode(model).attrs!.tblFloat).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('run character shading (w:shd) mark mapping', () => {
|
||||
it('round-trips run.shading through the docTextStyle mark alongside highlight', () => {
|
||||
const inline = runsToInline([{ text: 'badge', shading: 'FFC000', highlight: 'yellow' }])
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isDocDirty, type DocDirtyState } from '../src/renderer/doc-dirty'
|
||||
import { openedFileStartsDirty } from '../src/renderer/doc-state'
|
||||
|
||||
function cleanState(): DocDirtyState {
|
||||
return {
|
||||
@@ -38,6 +39,13 @@ describe('isDocDirty', () => {
|
||||
expect(isDocDirty({ ...cleanState(), dirtyRef: { current: true } })).toBe(true)
|
||||
})
|
||||
|
||||
it('treats restored recovery content as unsaved body content', () => {
|
||||
const state = cleanState()
|
||||
state.dirtyRef.current = openedFileStartsDirty({ recovered: true })
|
||||
expect(isDocDirty(state)).toBe(true)
|
||||
expect(openedFileStartsDirty({})).toBe(false)
|
||||
})
|
||||
|
||||
// the regression: autosave ignored comment/protection edits; the recovery push ignored everything but the body
|
||||
it.each([
|
||||
['commentsDirty', { commentsDirty: true }],
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
commitDocPasswordSave,
|
||||
currentDocPasswordIntentRevision,
|
||||
decryptDocx,
|
||||
decryptRecoveryCopy,
|
||||
discardDocPasswordIntents,
|
||||
DocxDecryptError,
|
||||
docPasswordFor,
|
||||
encryptDocx,
|
||||
forgetDocPasswords,
|
||||
isDiskEncrypted,
|
||||
isEncryptedDocx,
|
||||
markDiskEncrypted,
|
||||
prepareRecoveryDocx,
|
||||
rememberDocPassword,
|
||||
renameDocPassword,
|
||||
setDocPassword,
|
||||
snapshotDocPassword,
|
||||
} from '../src/main/docx-encryption'
|
||||
|
||||
const plainDocx = () => readFileSync(join(__dirname, 'pagination-corpus/docx/kitchen-sink.docx'))
|
||||
|
||||
describe('isEncryptedDocx', () => {
|
||||
it('is false for a plain docx (zip) and random bytes', () => {
|
||||
expect(isEncryptedDocx(plainDocx())).toBe(false)
|
||||
expect(isEncryptedDocx(Buffer.from('not a docx at all'))).toBe(false)
|
||||
expect(isEncryptedDocx(Buffer.alloc(0))).toBe(false)
|
||||
})
|
||||
|
||||
it('is true for an ECMA-376 encrypted docx', () => {
|
||||
const encrypted = encryptDocx(plainDocx(), 'pw')
|
||||
expect(isEncryptedDocx(encrypted)).toBe(true)
|
||||
})
|
||||
|
||||
it('is false for a CFB container without an EncryptedPackage stream (legacy .doc shape)', () => {
|
||||
const cfbNoPackage = Buffer.concat([
|
||||
Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]),
|
||||
Buffer.alloc(512),
|
||||
])
|
||||
expect(isEncryptedDocx(cfbNoPackage)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('encryptDocx / decryptDocx', () => {
|
||||
it('round-trips byte-exact with the right password', async () => {
|
||||
const original = plainDocx()
|
||||
const encrypted = encryptDocx(original, 'S3cret!密码')
|
||||
expect(encrypted.subarray(0, 4)).not.toEqual(original.subarray(0, 4))
|
||||
const decrypted = await decryptDocx(encrypted, 'S3cret!密码')
|
||||
expect(Buffer.compare(decrypted, original)).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects a wrong password with reason wrong-password', async () => {
|
||||
const encrypted = encryptDocx(plainDocx(), 'right')
|
||||
const err = await decryptDocx(encrypted, 'wrong').catch((e) => e)
|
||||
expect(err).toBeInstanceOf(DocxDecryptError)
|
||||
expect((err as DocxDecryptError).reason).toBe('wrong-password')
|
||||
})
|
||||
|
||||
it('reports unrecognized containers as unsupported', async () => {
|
||||
// CFB magic but no usable encryption streams (e.g. proprietary/account encryption)
|
||||
const bogus = Buffer.concat([
|
||||
Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]),
|
||||
Buffer.alloc(4096),
|
||||
])
|
||||
const err = await decryptDocx(bogus, 'any').catch((e) => e)
|
||||
expect(err).toBeInstanceOf(DocxDecryptError)
|
||||
expect((err as DocxDecryptError).reason).toBe('unsupported')
|
||||
})
|
||||
})
|
||||
|
||||
// Interop lock: fixtures produced by real Microsoft Office, vendored from the
|
||||
// reference implementation's test suite (nolze/msoffcrypto-tool, MIT). The agile
|
||||
// one is >4096 bytes, covering multi-segment package decryption.
|
||||
describe('real Office files', () => {
|
||||
const fixture = (name: string) => readFileSync(join(__dirname, 'encrypted-fixtures', name))
|
||||
|
||||
it('decrypts a real Office agile-encrypted docx byte-exact (multi-segment)', async () => {
|
||||
const encrypted = fixture('office-agile-password.docx')
|
||||
expect(isEncryptedDocx(encrypted)).toBe(true)
|
||||
const decrypted = await decryptDocx(encrypted, 'Password1234_')
|
||||
expect(Buffer.compare(decrypted, fixture('office-agile-plain.docx'))).toBe(0)
|
||||
})
|
||||
|
||||
it('decrypts a real Office standard-encrypted docx byte-exact', async () => {
|
||||
const encrypted = fixture('office-standard-password.docx')
|
||||
expect(isEncryptedDocx(encrypted)).toBe(true)
|
||||
const decrypted = await decryptDocx(encrypted, 'Password1234_')
|
||||
expect(Buffer.compare(decrypted, fixture('office-standard-plain.docx'))).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('password store', () => {
|
||||
it('remembers per renderer + path, and forget drops the whole renderer', () => {
|
||||
rememberDocPassword(1, '/a.docx', 'pw-a')
|
||||
rememberDocPassword(1, '/b.docx', 'pw-b')
|
||||
rememberDocPassword(2, '/a.docx', 'pw-other')
|
||||
expect(docPasswordFor(1, '/a.docx')).toBe('pw-a')
|
||||
expect(docPasswordFor(1, '/b.docx')).toBe('pw-b')
|
||||
expect(docPasswordFor(2, '/a.docx')).toBe('pw-other')
|
||||
expect(docPasswordFor(1, '/c.docx')).toBeNull()
|
||||
expect(docPasswordFor(1, null)).toBeNull()
|
||||
forgetDocPasswords(1)
|
||||
expect(docPasswordFor(1, '/a.docx')).toBeNull()
|
||||
expect(docPasswordFor(2, '/a.docx')).toBe('pw-other')
|
||||
})
|
||||
|
||||
it('keeps the current disk password separate until old -> new saves successfully', () => {
|
||||
rememberDocPassword(3, '/x.docx', 'old')
|
||||
markDiskEncrypted(3, '/x.docx', true)
|
||||
setDocPassword(3, '/x.docx', 'new')
|
||||
|
||||
const save = snapshotDocPassword(3, '/x.docx')
|
||||
expect(save.password).toBe('new')
|
||||
expect(docPasswordFor(3, '/x.docx')).toBe('old')
|
||||
|
||||
expect(commitDocPasswordSave(3, save, '/x.docx')).toBe(false)
|
||||
expect(docPasswordFor(3, '/x.docx')).toBe('new')
|
||||
expect(isDiskEncrypted(3, '/x.docx')).toBe(true)
|
||||
expect(snapshotDocPassword(3, '/x.docx').password).toBe('new')
|
||||
})
|
||||
|
||||
it('keeps the current disk password separate until old -> none saves successfully', () => {
|
||||
rememberDocPassword(30, '/x.docx', 'old')
|
||||
markDiskEncrypted(30, '/x.docx', true)
|
||||
setDocPassword(30, '/x.docx', null)
|
||||
|
||||
const save = snapshotDocPassword(30, '/x.docx')
|
||||
expect(save.password).toBeNull()
|
||||
expect(docPasswordFor(30, '/x.docx')).toBe('old')
|
||||
|
||||
expect(commitDocPasswordSave(30, save, '/x.docx')).toBe(false)
|
||||
expect(docPasswordFor(30, '/x.docx')).toBeNull()
|
||||
expect(isDiskEncrypted(30, '/x.docx')).toBe(false)
|
||||
})
|
||||
|
||||
it('accepting a plain replacement clears stale disk and desired password state', () => {
|
||||
rememberDocPassword(37, '/x.docx', 'old')
|
||||
setDocPassword(37, '/x.docx', 'desired')
|
||||
rememberDocPassword(37, '/x.docx', null)
|
||||
markDiskEncrypted(37, '/x.docx', false)
|
||||
expect(docPasswordFor(37, '/x.docx')).toBeNull()
|
||||
// Auxiliary opens (for example Compare) do not discard the active
|
||||
// document's intent; accepting a replacement does so explicitly.
|
||||
expect(snapshotDocPassword(37, '/x.docx').password).toBe('desired')
|
||||
discardDocPasswordIntents(37)
|
||||
expect(snapshotDocPassword(37, '/x.docx').password).toBeNull()
|
||||
})
|
||||
|
||||
it('replacement cleanup preserves intents created after its captured cutoff', () => {
|
||||
setDocPassword(38, null, 'old-draft')
|
||||
setDocPassword(38, '/old.docx', 'old-path')
|
||||
const cutoff = currentDocPasswordIntentRevision()
|
||||
|
||||
setDocPassword(38, null, 'replacement-draft')
|
||||
setDocPassword(38, '/new.docx', 'replacement-path')
|
||||
discardDocPasswordIntents(38, cutoff)
|
||||
|
||||
expect(snapshotDocPassword(38, null).password).toBe('replacement-draft')
|
||||
expect(snapshotDocPassword(38, '/new.docx').password).toBe('replacement-path')
|
||||
expect(snapshotDocPassword(38, '/old.docx').password).toBeNull()
|
||||
})
|
||||
|
||||
it('a failed save leaves desired state pending, and success does not consume a newer intent', () => {
|
||||
rememberDocPassword(31, '/x.docx', 'old')
|
||||
markDiskEncrypted(31, '/x.docx', true)
|
||||
setDocPassword(31, '/x.docx', 'first')
|
||||
|
||||
const failed = snapshotDocPassword(31, '/x.docx')
|
||||
// No commit: an atomic-write failure keeps both the disk baseline and intent.
|
||||
expect(docPasswordFor(31, '/x.docx')).toBe('old')
|
||||
expect(snapshotDocPassword(31, '/x.docx')).toEqual(failed)
|
||||
|
||||
setDocPassword(31, '/x.docx', 'newer')
|
||||
expect(commitDocPasswordSave(31, failed, '/x.docx')).toBe(true)
|
||||
expect(docPasswordFor(31, '/x.docx')).toBe('first')
|
||||
expect(snapshotDocPassword(31, '/x.docx').password).toBe('newer')
|
||||
})
|
||||
|
||||
it('parks a password for a pathless document until its first successful save', () => {
|
||||
setDocPassword(4, null, 'pw-pending')
|
||||
const firstSave = snapshotDocPassword(4, null)
|
||||
expect(firstSave.password).toBe('pw-pending')
|
||||
expect(snapshotDocPassword(4, null)).toEqual(firstSave)
|
||||
expect(commitDocPasswordSave(4, firstSave, '/first.docx')).toBe(false)
|
||||
expect(docPasswordFor(4, '/first.docx')).toBe('pw-pending')
|
||||
|
||||
// Clearing before another pathless save makes that save plain.
|
||||
setDocPassword(4, null, 'pw-2')
|
||||
setDocPassword(4, null, null)
|
||||
expect(snapshotDocPassword(4, null).password).toBeNull()
|
||||
// teardown drops it too
|
||||
setDocPassword(5, null, 'pw-3')
|
||||
forgetDocPasswords(5)
|
||||
expect(snapshotDocPassword(5, null).password).toBeNull()
|
||||
})
|
||||
|
||||
it('moves a pathless or Save As concurrent intent to the landed path', () => {
|
||||
setDocPassword(32, null, 'first')
|
||||
const firstSave = snapshotDocPassword(32, null)
|
||||
setDocPassword(32, null, 'newer')
|
||||
expect(commitDocPasswordSave(32, firstSave, '/new.docx')).toBe(true)
|
||||
expect(docPasswordFor(32, '/new.docx')).toBe('first')
|
||||
expect(snapshotDocPassword(32, '/new.docx').password).toBe('newer')
|
||||
|
||||
rememberDocPassword(33, '/old.docx', 'disk-old')
|
||||
setDocPassword(33, '/old.docx', 'save-as')
|
||||
const saveAs = snapshotDocPassword(33, '/old.docx')
|
||||
setDocPassword(33, '/old.docx', null)
|
||||
expect(commitDocPasswordSave(33, saveAs, '/copy.docx')).toBe(true)
|
||||
expect(docPasswordFor(33, '/old.docx')).toBe('disk-old')
|
||||
expect(docPasswordFor(33, '/copy.docx')).toBe('save-as')
|
||||
expect(snapshotDocPassword(33, '/copy.docx').password).toBeNull()
|
||||
})
|
||||
|
||||
it('follows a file rename, only for the renderer that owns it', () => {
|
||||
rememberDocPassword(6, '/old.docx', 'pw-r')
|
||||
setDocPassword(6, '/old.docx', 'pw-next')
|
||||
rememberDocPassword(7, '/other.docx', 'pw-o')
|
||||
markDiskEncrypted(6, '/old.docx', true)
|
||||
renameDocPassword(6, '/old.docx', '/new.docx')
|
||||
expect(docPasswordFor(6, '/old.docx')).toBeNull()
|
||||
expect(docPasswordFor(6, '/new.docx')).toBe('pw-r')
|
||||
expect(snapshotDocPassword(6, '/new.docx').password).toBe('pw-next')
|
||||
// the on-disk-encrypted flag follows the rename with the password
|
||||
expect(isDiskEncrypted(6, '/old.docx')).toBe(false)
|
||||
expect(isDiskEncrypted(6, '/new.docx')).toBe(true)
|
||||
// renaming a path with no stored password is a no-op
|
||||
renameDocPassword(7, '/old.docx', '/new.docx')
|
||||
expect(docPasswordFor(7, '/new.docx')).toBeNull()
|
||||
expect(docPasswordFor(7, '/other.docx')).toBe('pw-o')
|
||||
})
|
||||
|
||||
it('tracks on-disk encryption per renderer + path, dropped on teardown', () => {
|
||||
markDiskEncrypted(8, '/enc.docx', true)
|
||||
expect(isDiskEncrypted(8, '/enc.docx')).toBe(true)
|
||||
expect(isDiskEncrypted(8, '/plain.docx')).toBe(false)
|
||||
expect(isDiskEncrypted(9, '/enc.docx')).toBe(false)
|
||||
// a plain save turns it off (password removed via the ribbon, then saved)
|
||||
markDiskEncrypted(8, '/enc.docx', false)
|
||||
expect(isDiskEncrypted(8, '/enc.docx')).toBe(false)
|
||||
markDiskEncrypted(8, '/enc.docx', true)
|
||||
setDocPassword(8, '/enc.docx', 'desired')
|
||||
setDocPassword(8, null, 'pathless')
|
||||
forgetDocPasswords(8)
|
||||
expect(isDiskEncrypted(8, '/enc.docx')).toBe(false)
|
||||
expect(docPasswordFor(8, '/enc.docx')).toBeNull()
|
||||
expect(snapshotDocPassword(8, '/enc.docx').password).toBeNull()
|
||||
expect(snapshotDocPassword(8, null).password).toBeNull()
|
||||
})
|
||||
|
||||
it('encrypts and decrypts recovery with the disk password after desired new or none', async () => {
|
||||
const plain = plainDocx()
|
||||
rememberDocPassword(34, '/enc.docx', 'disk-old')
|
||||
markDiskEncrypted(34, '/enc.docx', true)
|
||||
|
||||
setDocPassword(34, '/enc.docx', 'desired-new')
|
||||
const whileChanging = prepareRecoveryDocx(34, '/enc.docx', plain)
|
||||
expect(whileChanging).not.toBeNull()
|
||||
await expect(decryptRecoveryCopy(34, '/enc.docx', whileChanging!)).resolves.toEqual(plain)
|
||||
await expect(decryptDocx(whileChanging!, 'desired-new')).rejects.toMatchObject({
|
||||
reason: 'wrong-password',
|
||||
})
|
||||
|
||||
setDocPassword(34, '/enc.docx', null)
|
||||
const whileRemoving = prepareRecoveryDocx(34, '/enc.docx', plain)
|
||||
expect(whileRemoving).not.toBeNull()
|
||||
await expect(decryptDocx(whileRemoving!, 'disk-old')).resolves.toEqual(plain)
|
||||
})
|
||||
|
||||
it('never returns plaintext recovery bytes for an encrypted disk file without its password', () => {
|
||||
markDiskEncrypted(35, '/enc.docx', true)
|
||||
expect(prepareRecoveryDocx(35, '/enc.docx', plainDocx())).toBeNull()
|
||||
|
||||
markDiskEncrypted(36, '/plain.docx', false)
|
||||
setDocPassword(36, '/plain.docx', 'desired-next-save')
|
||||
const plain = plainDocx()
|
||||
expect(prepareRecoveryDocx(36, '/plain.docx', plain)).toBe(plain)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,48 @@
|
||||
msoffcrypto-tool test fixtures
|
||||
|
||||
The four local fixtures are unmodified copies from
|
||||
https://github.com/nolze/msoffcrypto-tool:
|
||||
|
||||
Upstream revision: 6d9e72c58de2cf7df1ab45ac0d74ebedac8c58e3
|
||||
|
||||
- office-agile-password.docx
|
||||
Upstream: tests/inputs/example_password.docx
|
||||
Git blob SHA-1: e36bff91729b1bf720b4b1b6762f6b9d0151e01c
|
||||
https://github.com/nolze/msoffcrypto-tool/blob/6d9e72c58de2cf7df1ab45ac0d74ebedac8c58e3/tests/inputs/example_password.docx
|
||||
|
||||
- office-agile-plain.docx
|
||||
Upstream: tests/outputs/example.docx
|
||||
Git blob SHA-1: f3ec419252eb007be00bfa7cc4e0d0b78abaff07
|
||||
https://github.com/nolze/msoffcrypto-tool/blob/6d9e72c58de2cf7df1ab45ac0d74ebedac8c58e3/tests/outputs/example.docx
|
||||
|
||||
- office-standard-password.docx
|
||||
Upstream: tests/inputs/ecma376standard_password.docx
|
||||
Git blob SHA-1: 81030b5fc2ff6699056fcf27721bad49b836c7c8
|
||||
https://github.com/nolze/msoffcrypto-tool/blob/6d9e72c58de2cf7df1ab45ac0d74ebedac8c58e3/tests/inputs/ecma376standard_password.docx
|
||||
|
||||
- office-standard-plain.docx
|
||||
Upstream: tests/outputs/ecma376standard_password_plain.docx
|
||||
Git blob SHA-1: 4cb088b5c070bcaf7be9a8892fbfe7f37ff7be0a
|
||||
https://github.com/nolze/msoffcrypto-tool/blob/6d9e72c58de2cf7df1ab45ac0d74ebedac8c58e3/tests/outputs/ecma376standard_password_plain.docx
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2015 nolze
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -12,6 +12,40 @@ const FONTS = join(__dirname, '../src/renderer/fonts')
|
||||
const sans = readWoff2(join(FONTS, 'GenOfficeSansKR-Regular-subset.woff2'))
|
||||
const serif = readWoff2(join(FONTS, 'GenOfficeSerifKR-Regular-subset.woff2'))
|
||||
|
||||
const PRIMARY_NAME_IDS = new Set([1, 2, 3, 4, 6, 16, 17, 18, 20, 21, 22, 25])
|
||||
|
||||
function decodeUtf16Be(value: Buffer): string {
|
||||
const swapped = Buffer.alloc(value.length)
|
||||
for (let i = 0; i + 1 < value.length; i += 2) {
|
||||
swapped[i] = value[i + 1]
|
||||
swapped[i + 1] = value[i]
|
||||
}
|
||||
return swapped.toString('utf16le')
|
||||
}
|
||||
|
||||
function primaryFontNames(font: ReturnType<typeof readWoff2>): Array<{
|
||||
nameId: number
|
||||
value: string
|
||||
}> {
|
||||
const table = font.tables.get('name')
|
||||
if (!table) throw new Error('font has no name table')
|
||||
const count = table.readUInt16BE(2)
|
||||
const storageOffset = table.readUInt16BE(4)
|
||||
const names = []
|
||||
for (let i = 0; i < count; i++) {
|
||||
const recordOffset = 6 + i * 12
|
||||
const platformId = table.readUInt16BE(recordOffset)
|
||||
const nameId = table.readUInt16BE(recordOffset + 6)
|
||||
if (!PRIMARY_NAME_IDS.has(nameId)) continue
|
||||
const length = table.readUInt16BE(recordOffset + 8)
|
||||
const offset = table.readUInt16BE(recordOffset + 10)
|
||||
const raw = table.subarray(storageOffset + offset, storageOffset + offset + length)
|
||||
const value = platformId === 0 || platformId === 3 ? decodeUtf16Be(raw) : raw.toString('latin1')
|
||||
names.push({ nameId, value })
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
describe('GenOffice Sans KR (Malgun-normalized)', () => {
|
||||
it('hangul syllables and compatibility jamo stay 1.0em', () => {
|
||||
for (const cp of [0xac00, 0xae4e, 0xd558, 0x3131]) {
|
||||
@@ -65,6 +99,35 @@ describe('GenOffice Serif KR (Batang-normalized)', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('GenOffice Gothic KR (real source metrics, unmodified)', () => {
|
||||
const gothicKr = readWoff2(join(FONTS, 'GenOfficeGothicKR-Regular-subset.woff2'))
|
||||
|
||||
it('keeps the M3 probe truth: hangul 0.94em, space 0.28em, digits 0.606em', () => {
|
||||
for (const cp of [0xac00, 0xd55c, 0xae00]) {
|
||||
expect(advanceEm(gothicKr, cp), `U+${cp.toString(16)}`).toBeCloseTo(0.94, 3)
|
||||
}
|
||||
expect(advanceEm(gothicKr, 0x20)).toBeCloseTo(0.28, 3)
|
||||
for (let cp = 0x30; cp <= 0x39; cp++) {
|
||||
expect(advanceEm(gothicKr, cp), `digit ${cp - 0x30}`).toBeCloseTo(0.606, 3)
|
||||
}
|
||||
})
|
||||
|
||||
it('covers KS X 1001 syllables and Basic Latin', () => {
|
||||
expect(advanceEm(gothicKr, 0xd558)).toBeCloseTo(0.94, 3)
|
||||
expect(advanceEm(gothicKr, 0x41)).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('keeps every primary font identifier clear of Reserved Font Names', () => {
|
||||
const names = primaryFontNames(gothicKr)
|
||||
expect(names.length).toBeGreaterThan(0)
|
||||
for (const { nameId, value } of names) {
|
||||
expect(value, `name ID ${nameId}`).not.toMatch(/nanum/i)
|
||||
}
|
||||
expect(names).toContainEqual({ nameId: 1, value: 'GenOffice Gothic KR' })
|
||||
expect(names).toContainEqual({ nameId: 6, value: 'GenOfficeGothicKR-Regular' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('bundled SC subset fullwidth coverage (TC serif chain shim)', () => {
|
||||
it('U+FF0D/FF0F/FF3C/FF3F/FF5E map to 1.0em glyphs', () => {
|
||||
const sc = readWoff2(join(FONTS, 'NotoSerifCJKsc-Regular-subset.woff2'))
|
||||
|
||||
@@ -652,7 +652,7 @@ describe('cssFontFamily', () => {
|
||||
)
|
||||
})
|
||||
|
||||
describe('KR chains (M3 probe: theme Latin head, real Nanum)', () => {
|
||||
describe('KR chains (M3 probe: theme Latin head, downloadable source face)', () => {
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
it('missing KR variant gets the theme Latin head ahead of the Batang chain', () => {
|
||||
@@ -673,18 +673,33 @@ describe('cssFontFamily', () => {
|
||||
expect(cssFontFamily('Batang')).not.toContain("'KR Theme Latin GO'")
|
||||
})
|
||||
|
||||
it('installed NanumGothic resolves at the literal head of the sans chain', () => {
|
||||
it('the matching source family leads the bundled real-metric face', () => {
|
||||
stubCanvas(['NanumGothic'])
|
||||
expect(cssFontFamily('NanumGothic')).toBe(
|
||||
"'NanumGothic','Malgun Gothic','GenOffice Sans KR','Apple SD Gothic Neo','Noto Sans KR',sans-serif",
|
||||
"'NanumGothic','GenOffice Gothic KR','Malgun Gothic','GenOffice Sans KR','Apple SD Gothic Neo','Noto Sans KR',sans-serif",
|
||||
)
|
||||
})
|
||||
|
||||
it('missing Nanum names keep the Batang-normalized serif chain', () => {
|
||||
it('the localized source name takes the bundled face when missing', () => {
|
||||
expect(cssFontFamily('나눔고딕')).toBe(
|
||||
"'나눔고딕','GenOffice Gothic KR','Malgun Gothic','GenOffice Sans KR','Apple SD Gothic Neo','Noto Sans KR',sans-serif",
|
||||
)
|
||||
})
|
||||
|
||||
it('other source-vendor families keep the Batang-normalized serif chain', () => {
|
||||
expect(cssFontFamily('NanumBarunGothic')).toBe(
|
||||
"'NanumBarunGothic','GenOffice Batang','GenOffice Serif KR','GenOffice Myungjo','Noto Serif KR',serif",
|
||||
)
|
||||
})
|
||||
|
||||
it('Tamil declares lead the bundled Latha-metric face', () => {
|
||||
expect(cssFontFamily('Latha')).toBe(
|
||||
"'Latha','GenOffice Tamil','InaiMathi','Tamil MN','Tamil Sangam MN',sans-serif",
|
||||
)
|
||||
expect(cssFontFamily('Noto Sans Tamil')).toBe(
|
||||
"'Noto Sans Tamil','GenOffice Tamil','InaiMathi','Tamil MN','Tamil Sangam MN',sans-serif",
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -718,6 +733,8 @@ describe('Korean line metrics', () => {
|
||||
expect(lineHeightFactor('Gulim')).toBe(1.3029)
|
||||
expect(lineHeightFactor('Dotum')).toBe(1.3029)
|
||||
expect(lineHeightFactor('NanumMyeongjo')).toBe(1.3029)
|
||||
expect(lineHeightFactor('NanumGothic')).toBe(1.495)
|
||||
expect(lineHeightFactor('나눔고딕')).toBe(1.495)
|
||||
expect(lineHeightFactor('Malgun Gothic')).toBe(1.7371)
|
||||
expect(lineHeightFactor('맑은 고딕')).toBe(1.7371)
|
||||
expect(lineHeightFactor('Noto Sans CJK KR')).toBe(1.3029)
|
||||
|
||||
@@ -273,6 +273,30 @@ describe('native editable tables', () => {
|
||||
editor.destroy()
|
||||
})
|
||||
|
||||
it('a floating table (w:tblpPr) drops alignment/indent margins for the float gaps', async () => {
|
||||
const { editor } = await openTable()
|
||||
const table = editor.state.doc.firstChild!
|
||||
editor.view.dispatch(
|
||||
editor.state.tr.setNodeMarkup(0, undefined, {
|
||||
...table.attrs,
|
||||
widthPx: 400,
|
||||
tblFloat: 'right',
|
||||
tblAlign: 'center',
|
||||
indentTwips: 1450,
|
||||
}),
|
||||
)
|
||||
const spec = editor.schema.nodes.docTable.spec.toDOM!(editor.state.doc.firstChild!) as [
|
||||
string,
|
||||
Record<string, string>,
|
||||
]
|
||||
expect(spec[1].class).toContain('doc-table-float-right')
|
||||
expect(spec[1].style ?? '').not.toContain('margin-left:')
|
||||
expect(spec[1].style ?? '').not.toContain('margin-right:')
|
||||
// the indent must not shrink the float width either
|
||||
expect(spec[1].style ?? '').not.toContain('96.7px')
|
||||
editor.destroy()
|
||||
})
|
||||
|
||||
it('clamps a drag-committed grid without any selection inside the table', async () => {
|
||||
const { editor } = await openTable()
|
||||
// the resize handle sets no selection; a table NodeSelection is not "in table" either
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
makeGapEl,
|
||||
syncCutOverlays,
|
||||
syncPhantomRowspans,
|
||||
clampCellBoxTops,
|
||||
} from '../src/renderer/editor/pagination-gaps'
|
||||
import { createLineRectsCache, singleCutCell } from '../src/renderer/pagination'
|
||||
|
||||
@@ -186,3 +187,35 @@ describe('createLineRectsCache', () => {
|
||||
expect(rectsOf(other, 1)).not.toBe(a)
|
||||
})
|
||||
})
|
||||
|
||||
describe('clampCellBoxTops', () => {
|
||||
const boxAt = (pm: HTMLElement, top: number, height = 45): HTMLElement => {
|
||||
const cell = document.createElement('div')
|
||||
cell.className = 'doc-cell-boxes'
|
||||
const box = document.createElement('div')
|
||||
box.className = 'doc-textbox'
|
||||
box.getBoundingClientRect = () => ({ top, bottom: top + height, height, width: 100 }) as DOMRect
|
||||
cell.appendChild(box)
|
||||
pm.appendChild(cell)
|
||||
return box
|
||||
}
|
||||
|
||||
it('pushes a box lifted above the paper top back to the edge; leaves on-page boxes alone', () => {
|
||||
const pm = document.createElement('div')
|
||||
const above = boxAt(pm, -62)
|
||||
const inside = boxAt(pm, 30)
|
||||
clampCellBoxTops(pm, 0, 1)
|
||||
expect(above.style.getPropertyValue('--page-float-dy')).toBe('62.0px')
|
||||
expect(inside.style.getPropertyValue('--page-float-dy')).toBe('')
|
||||
})
|
||||
|
||||
it('is idempotent: a re-run against the already-shifted rect keeps the same dy', () => {
|
||||
const pm = document.createElement('div')
|
||||
const box = boxAt(pm, -62)
|
||||
clampCellBoxTops(pm, 0, 1)
|
||||
// after the translate the live rect reads at the paper top
|
||||
box.getBoundingClientRect = () => ({ top: 0, bottom: 45, height: 45, width: 100 }) as DOMRect
|
||||
clampCellBoxTops(pm, 0, 1)
|
||||
expect(box.style.getPropertyValue('--page-float-dy')).toBe('62.0px')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4,6 +4,9 @@ import {
|
||||
appendEndnotesBlock,
|
||||
assignSections,
|
||||
cellCutYs,
|
||||
columnLayoutSpecs,
|
||||
vAlignShiftSpecs,
|
||||
sectionColGeom,
|
||||
computePageSlices,
|
||||
computeSectionedSlices,
|
||||
computeSectionedSlicesF2,
|
||||
@@ -25,6 +28,7 @@ import {
|
||||
tableHeaderFlags,
|
||||
tableRowFlags,
|
||||
type BlockBox,
|
||||
type PageSlice,
|
||||
type TableRowBox,
|
||||
} from '../src/renderer/pagination'
|
||||
|
||||
@@ -193,9 +197,12 @@ describe('computePageSlices', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('breakAfter at the end of the document does not create an empty page', () => {
|
||||
it('breakAfter at the end of the document keeps its deliberate blank page (tdf#99090)', () => {
|
||||
const slices = computePageSlices([block(0, 100, { breakAfter: true })], 800, 100)
|
||||
expect(slices).toEqual([{ start: 0, end: 100, section: 0 }])
|
||||
expect(slices).toEqual([
|
||||
{ start: 0, end: 100, section: 0 },
|
||||
{ start: 100, end: 100, section: 0 },
|
||||
])
|
||||
})
|
||||
|
||||
it('push and hard split combined: normal spanning block before a huge block', () => {
|
||||
@@ -258,17 +265,17 @@ describe('visiblePageCount', () => {
|
||||
{ start: 1600, end: 2000, section: 1 },
|
||||
]
|
||||
|
||||
it('counts parity-blank pairs once so NUMPAGES matches the drawn pages', () => {
|
||||
expect(visiblePageCount(withBlank)).toBe(3)
|
||||
it('counts a zero-height blank as its own page (parity/deliberate blanks are drawn sheets)', () => {
|
||||
expect(visiblePageCount(withBlank)).toBe(4)
|
||||
expect(visiblePageCount([{ start: 0, end: 800, section: 0 }])).toBe(1)
|
||||
expect(visiblePageCount([])).toBe(0)
|
||||
})
|
||||
|
||||
it('maps a physical pageAt index to its visible page number', () => {
|
||||
// y=900 lands on physical slice 3 (the real page after the blank) = visible page 2
|
||||
expect(visiblePageCount(withBlank, pageAt(withBlank, 900))).toBe(2)
|
||||
// y=900 lands on physical slice 3 (the real page after the blank) = visible page 3
|
||||
expect(visiblePageCount(withBlank, pageAt(withBlank, 900))).toBe(3)
|
||||
expect(visiblePageCount(withBlank, pageAt(withBlank, 0))).toBe(1)
|
||||
expect(visiblePageCount(withBlank, pageAt(withBlank, 1700))).toBe(3)
|
||||
expect(visiblePageCount(withBlank, pageAt(withBlank, 1700))).toBe(4)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -358,6 +365,15 @@ describe('multi-section slicing', () => {
|
||||
expect(Math.round(geoms[0].contentHeight)).toBe(Math.round(((16838 - 2880) / 1440) * 96))
|
||||
})
|
||||
|
||||
it('sectionGeoms: nextColumn starts a new page in a single-column layout, flows in a multi-column one (n750255)', () => {
|
||||
const single = sec({})
|
||||
const afterSingle = sec({}, { startType: 'nextColumn' })
|
||||
const twoCol = sec({ columns: 2 }, { startType: 'nextColumn' })
|
||||
const afterTwoCol = sec({ columns: 2 }, { startType: 'nextColumn' })
|
||||
const geoms = sectionGeoms([single, afterSingle, twoCol, afterTwoCol])
|
||||
expect(geoms.map((g) => g.forceBreak)).toEqual([false, true, true, false])
|
||||
})
|
||||
|
||||
it('effectiveHfRefs: undefined variants inherit forward section by section', () => {
|
||||
const sections = [
|
||||
sec({}, { headerRefs: { default: 'rH1', first: 'rHF1' }, footerRefs: { default: 'rF1' } }),
|
||||
@@ -536,6 +552,63 @@ describe('computeSectionedSlicesF2 — line-level pagination', () => {
|
||||
expect(slices.length).toBe(1)
|
||||
})
|
||||
|
||||
it('a floated block consumes no column height (wrapped text carries the extent)', () => {
|
||||
// float 180px tall, wrapped paragraphs stack to 150 ≤ 200: everything is one
|
||||
// page — counting the float would double-book the overlap and break early
|
||||
const blocks = [
|
||||
{ ...block(0, 180), floated: true },
|
||||
block(0, 60),
|
||||
block(60, 60),
|
||||
block(120, 30),
|
||||
]
|
||||
const slices = computeSectionedSlicesF2(blocks, geoms1, 180)
|
||||
expect(slices.length).toBe(1)
|
||||
})
|
||||
|
||||
it('a floated block taller than the remaining column moves whole to the next page', () => {
|
||||
const blocks = [block(0, 150), { ...block(150, 180), floated: true }, block(150, 40)]
|
||||
const slices = computeSectionedSlicesF2(blocks, geoms1, 330)
|
||||
expect(slices.length).toBe(2)
|
||||
expect(slices[1].start).toBe(150)
|
||||
})
|
||||
|
||||
it('a leading w:br on the first content keeps the blank first page (fdo#78907)', () => {
|
||||
const b = { ...block(0, 100), breakBefore: true, breakBeforeBr: true }
|
||||
const slices = computeSectionedSlicesF2([b], geoms1, 100)
|
||||
expect(slices).toEqual([
|
||||
{ start: 0, end: 0, section: 0 },
|
||||
{ start: 0, end: 100, section: 0 },
|
||||
])
|
||||
})
|
||||
|
||||
it('a pageBreakBefore property on the first content stays suppressed', () => {
|
||||
const b = { ...block(0, 100), breakBefore: true }
|
||||
const slices = computeSectionedSlicesF2([b], geoms1, 100)
|
||||
expect(slices.length).toBe(1)
|
||||
})
|
||||
|
||||
it('a pending w:br plus a leading w:br are two page turns with a blank sheet between (tdf#154478)', () => {
|
||||
const blocks = [
|
||||
{ ...block(0, 100), breakAfter: true },
|
||||
{ ...block(100, 100), breakBefore: true, breakBeforeBr: true },
|
||||
]
|
||||
const slices = computeSectionedSlicesF2(blocks, geoms1, 200)
|
||||
expect(slices).toEqual([
|
||||
{ start: 0, end: 100, section: 0 },
|
||||
{ start: 100, end: 100, section: 0 },
|
||||
{ start: 100, end: 200, section: 0 },
|
||||
])
|
||||
})
|
||||
|
||||
it('a trailing w:br keeps its deliberate blank last page (tdf#99090)', () => {
|
||||
const blocks = [{ ...block(0, 100), breakAfter: true }]
|
||||
const slices = computeSectionedSlicesF2(blocks, geoms1, 100)
|
||||
expect(slices).toEqual([
|
||||
{ start: 0, end: 100, section: 0 },
|
||||
{ start: 100, end: 100, section: 0 },
|
||||
])
|
||||
})
|
||||
|
||||
it('paragraph that fits entirely is not split', () => {
|
||||
// 3 lines × 50px = 150 < 200, no page break
|
||||
const b = lineBlock(0, [50, 50, 50])
|
||||
@@ -1561,6 +1634,329 @@ describe('computeSectionedSlicesF2 — multi-column flow', () => {
|
||||
expect(cols[1].repeatHeader).toMatchObject({ top: 0, height: 30 })
|
||||
})
|
||||
|
||||
it('sectionGeoms: nextColumn with the same multi-column count advances a column; a changed count breaks the page (tdf135343)', () => {
|
||||
const fourCol = sec({ columns: 4 })
|
||||
const twoColRtl = sec({ columns: 2 }, { startType: 'nextColumn' })
|
||||
const geoms = sectionGeoms([fourCol, twoColRtl])
|
||||
expect(geoms[1].forceBreak).toBe(true) // 4 → 2: acts like a page break (c12v3)
|
||||
expect(geoms[1].colBreakStart).toBeUndefined()
|
||||
|
||||
const threeCol = sec({ columns: 3 }, { startType: 'continuous' })
|
||||
const threeColNext = sec({ columns: 3 }, { startType: 'nextColumn' })
|
||||
const geoms2 = sectionGeoms([threeCol, threeColNext])
|
||||
expect(geoms2[1].forceBreak).toBe(false) // 3 → 3: column advance (c14/c15)
|
||||
expect(geoms2[1].colBreakStart).toBe(true)
|
||||
})
|
||||
|
||||
it('colBreakStart advances one column at the section boundary (0876 shape)', () => {
|
||||
const blocks: BlockBox[] = [
|
||||
{ ...lineBlock(0, [40, 40]), section: 0 },
|
||||
{ ...lineBlock(80, [40]), section: 1 },
|
||||
]
|
||||
const geoms = [
|
||||
{ contentHeight: 200, forceBreak: false, cols: 3 },
|
||||
{ contentHeight: 200, forceBreak: false, cols: 3, colBreakStart: true },
|
||||
]
|
||||
const slices = computeSectionedSlicesF2(blocks, geoms, 120)
|
||||
expect(slices).toHaveLength(1)
|
||||
const cols = slices[0].regions![0].columns
|
||||
expect(cols).toHaveLength(2)
|
||||
expect(cols[1]).toMatchObject({ start: 80, end: 120 })
|
||||
})
|
||||
|
||||
it('continuous column-count change balances the closed region at line granularity (0089 shape)', () => {
|
||||
// 1-col title (60), 4-col index of 6 short lines (20 each), 1-col body: the
|
||||
// index balances 2/2/2/0, so the body region starts 40px below the index top
|
||||
const blocks: BlockBox[] = [
|
||||
{ ...lineBlock(0, [60]), section: 0 },
|
||||
...Array.from({ length: 6 }, (_, i) => ({
|
||||
...lineBlock(60 + i * 20, [20]),
|
||||
section: 1,
|
||||
})),
|
||||
{ ...lineBlock(180, [50]), section: 2 },
|
||||
]
|
||||
const geoms = [
|
||||
{ contentHeight: 400, forceBreak: false },
|
||||
{ contentHeight: 400, forceBreak: false, cols: 4 },
|
||||
{ contentHeight: 400, forceBreak: false },
|
||||
]
|
||||
const slices = computeSectionedSlicesF2(blocks, geoms, 230)
|
||||
expect(slices).toHaveLength(1)
|
||||
const regions = slices[0].regions!
|
||||
expect(regions).toHaveLength(3)
|
||||
const idx = regions[1]
|
||||
expect(idx.height).toBe(40)
|
||||
expect(idx.columns.map((c) => [c.start, c.end])).toEqual([
|
||||
[60, 100],
|
||||
[100, 140],
|
||||
[140, 180],
|
||||
[180, 180],
|
||||
])
|
||||
// the body region opens right under the balanced index
|
||||
expect(regions[2].top).toBe(100)
|
||||
expect(slices[0].physHeight).toBe(150) // 100 + 50 body line
|
||||
})
|
||||
|
||||
it('natural column overflow still balances on a continuous close (0876 shape)', () => {
|
||||
// five 2-line paragraphs (10 lines) in a 2-col region of height 160: col1
|
||||
// naturally overflows at 8 lines, but the continuous single-column close
|
||||
// re-balances to the line quota (5) — widow/orphan atomicity keeps the
|
||||
// 2-line paragraph whole, so the cut lands at the next paragraph top (6/4)
|
||||
const blocks: BlockBox[] = [
|
||||
...Array.from({ length: 5 }, (_, i) => ({
|
||||
...lineBlock(i * 40, [20, 20]),
|
||||
section: 0,
|
||||
})),
|
||||
{ ...lineBlock(200, [30]), section: 1 },
|
||||
]
|
||||
const geoms = [
|
||||
{ contentHeight: 160, forceBreak: false, cols: 2 },
|
||||
{ contentHeight: 160, forceBreak: false },
|
||||
]
|
||||
const slices = computeSectionedSlicesF2(blocks, geoms, 230)
|
||||
expect(slices).toHaveLength(1)
|
||||
const regions = slices[0].regions!
|
||||
expect(regions[0].columns.map((c) => [c.start, c.end])).toEqual([
|
||||
[0, 120],
|
||||
[120, 200],
|
||||
])
|
||||
expect(regions[0].height).toBe(120)
|
||||
expect(regions[1].top).toBe(120)
|
||||
})
|
||||
|
||||
it('balance splits a long paragraph at a widow/orphan-safe line boundary', () => {
|
||||
// one 10-line paragraph, 2 columns: quota 5, k=5 leaves 5 lines each side
|
||||
const blocks: BlockBox[] = [
|
||||
{
|
||||
...lineBlock(
|
||||
0,
|
||||
Array.from({ length: 10 }, () => 20),
|
||||
),
|
||||
section: 0,
|
||||
},
|
||||
{ ...lineBlock(200, [30]), section: 1 },
|
||||
]
|
||||
const geoms = [
|
||||
{ contentHeight: 400, forceBreak: false, cols: 2 },
|
||||
{ contentHeight: 400, forceBreak: false },
|
||||
]
|
||||
const regions = computeSectionedSlicesF2(blocks, geoms, 230)[0].regions!
|
||||
expect(regions[0].columns.map((c) => [c.start, c.end])).toEqual([
|
||||
[0, 100],
|
||||
[100, 200],
|
||||
])
|
||||
})
|
||||
|
||||
it('empty paragraphs flow into balanced columns but do not count toward the quota', () => {
|
||||
// 4 text lines + 2 trailing empties, 2 cols: quota 2 → cut after 2 text lines
|
||||
const blocks: BlockBox[] = [
|
||||
{ ...lineBlock(0, [20]), section: 0 },
|
||||
{ ...lineBlock(20, [20]), section: 0 },
|
||||
{ ...lineBlock(40, [20]), section: 0 },
|
||||
{ ...lineBlock(60, [20]), section: 0 },
|
||||
{ ...lineBlock(80, [20]), section: 0, emptyPara: true },
|
||||
{ ...lineBlock(100, [20]), section: 0, emptyPara: true },
|
||||
{ ...lineBlock(120, [30]), section: 1 },
|
||||
]
|
||||
const geoms = [
|
||||
{ contentHeight: 400, forceBreak: false, cols: 2 },
|
||||
{ contentHeight: 400, forceBreak: false },
|
||||
]
|
||||
const regions = computeSectionedSlicesF2(blocks, geoms, 150)[0].regions!
|
||||
expect(regions[0].columns.map((c) => c.start)).toEqual([0, 40])
|
||||
expect(regions[0].height).toBe(40) // trailing empties are absorbed: extent = 2 text lines
|
||||
})
|
||||
|
||||
it('a manual column break disables balancing for its region', () => {
|
||||
const blocks: BlockBox[] = [
|
||||
{ ...lineBlock(0, [20], { colBreakAfter: true }), section: 0 },
|
||||
{ ...lineBlock(20, [20]), section: 0 },
|
||||
{ ...lineBlock(40, [50]), section: 1 },
|
||||
]
|
||||
const geoms = [
|
||||
{ contentHeight: 400, forceBreak: false, cols: 2 },
|
||||
{ contentHeight: 400, forceBreak: false },
|
||||
]
|
||||
const slices = computeSectionedSlicesF2(blocks, geoms, 90)
|
||||
// unbalanced (a turn happened): the region keeps the full page height, the next section starts a new page
|
||||
expect(slices).toHaveLength(2)
|
||||
expect(slices[0].regions![0].columns.map((c) => c.start)).toEqual([0, 20])
|
||||
expect(slices[1].start).toBe(40)
|
||||
})
|
||||
|
||||
it('columnLayoutSpecs: width + per-column constant translate, later regions pull up', () => {
|
||||
const els = Array.from({ length: 4 }, () => ({}) as HTMLElement)
|
||||
const blocks: BlockBox[] = [
|
||||
{ ...lineBlock(0, [20]), section: 1, el: els[0] },
|
||||
{ ...lineBlock(20, [20]), section: 1, el: els[1] },
|
||||
{ ...lineBlock(40, [20]), section: 1, el: els[2] },
|
||||
{ ...lineBlock(60, [50]), section: 2, el: els[3] },
|
||||
]
|
||||
const slices: PageSlice[] = [
|
||||
{
|
||||
start: 0,
|
||||
end: 110,
|
||||
section: 1,
|
||||
physHeight: 70,
|
||||
regions: [
|
||||
{
|
||||
top: 0,
|
||||
height: 20,
|
||||
section: 1,
|
||||
columns: [
|
||||
{ start: 0, end: 20 },
|
||||
{ start: 20, end: 40 },
|
||||
{ start: 40, end: 60 },
|
||||
],
|
||||
},
|
||||
{ top: 20, height: 100, section: 2, columns: [{ start: 60, end: 110 }] },
|
||||
],
|
||||
},
|
||||
]
|
||||
const secs = [
|
||||
sec({}),
|
||||
sec({ columns: 3, colSpace: 720 }, { startType: 'continuous' }),
|
||||
sec({}, { startType: 'continuous' }),
|
||||
]
|
||||
const specs = columnLayoutSpecs(blocks, slices, secs)
|
||||
const g = sectionColGeom(secs[1])
|
||||
expect(specs).toHaveLength(4)
|
||||
expect(specs[0]).toMatchObject({ el: els[0], widthPx: g.colWidthPx, dx: 0, dy: 0 })
|
||||
expect(specs[1]).toMatchObject({ el: els[1], dx: g.colWidthPx + g.gapPx, dy: -20 })
|
||||
expect(specs[2]).toMatchObject({ el: els[2], dx: 2 * (g.colWidthPx + g.gapPx), dy: -40 })
|
||||
// the single-column body pulls up over the vacated stacked space (region top 20, col start offset 60)
|
||||
expect(specs[3]).toMatchObject({ el: els[3], dx: 0, dy: -40 })
|
||||
expect(specs[3].widthPx).toBeUndefined()
|
||||
})
|
||||
|
||||
it('vAlignShiftSpecs: center/bottom pages translate whole blocks into the free space', () => {
|
||||
const els = Array.from({ length: 4 }, () => ({}) as HTMLElement)
|
||||
const blocks: BlockBox[] = [
|
||||
{ ...lineBlock(0, [20]), section: 0, el: els[0] },
|
||||
{ ...lineBlock(20, [20]), section: 0, el: els[1] },
|
||||
{ ...lineBlock(40, [30]), section: 1, el: els[2] },
|
||||
{ ...lineBlock(70, [30]), section: 2, el: els[3] },
|
||||
]
|
||||
const slices: PageSlice[] = [
|
||||
{ start: 0, end: 40, section: 0 },
|
||||
{ start: 40, end: 70, section: 1 },
|
||||
{ start: 70, end: 100, section: 2 },
|
||||
]
|
||||
const secs = [
|
||||
sec({ vAlign: 'center' }),
|
||||
sec({ vAlign: 'bottom' }, { startType: 'nextPage' }),
|
||||
sec({}, { startType: 'nextPage' }),
|
||||
]
|
||||
const geoms = [
|
||||
{ contentHeight: 100, forceBreak: false },
|
||||
{ contentHeight: 100, forceBreak: true },
|
||||
{ contentHeight: 100, forceBreak: true },
|
||||
]
|
||||
const specs = vAlignShiftSpecs(blocks, slices, secs, geoms)
|
||||
// center page: free = 100-40 = 60 → dy 30 for both blocks; bottom page: dy 70
|
||||
expect(specs).toHaveLength(3)
|
||||
expect(specs[0]).toMatchObject({ el: els[0], dx: 0, dy: 30 })
|
||||
expect(specs[1]).toMatchObject({ el: els[1], dx: 0, dy: 30 })
|
||||
expect(specs[2]).toMatchObject({ el: els[2], dx: 0, dy: 70 })
|
||||
})
|
||||
|
||||
it('vAlignShiftSpecs: a block crossing the page boundary keeps the page top-aligned', () => {
|
||||
const els = Array.from({ length: 2 }, () => ({}) as HTMLElement)
|
||||
const blocks: BlockBox[] = [
|
||||
{ ...lineBlock(0, [30, 30]), section: 0, el: els[0] },
|
||||
{ ...lineBlock(60, [20]), section: 0, el: els[1] },
|
||||
]
|
||||
// the first block spans the page-1/page-2 boundary at 40
|
||||
const slices: PageSlice[] = [
|
||||
{ start: 0, end: 40, section: 0 },
|
||||
{ start: 40, end: 80, section: 0 },
|
||||
]
|
||||
const secs = [sec({ vAlign: 'center' })]
|
||||
const geoms = [{ contentHeight: 100, forceBreak: false }]
|
||||
expect(vAlignShiftSpecs(blocks, slices, secs, geoms)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('sectionColGeom: w:equalWidth="0" reads the explicit w:col width/space list (1290 shape)', () => {
|
||||
const s = sec(
|
||||
{ columns: 2, colSpace: 720 },
|
||||
{
|
||||
sectPrXml:
|
||||
'<w:sectPr><w:cols w:num="2" w:space="720" w:equalWidth="0"><w:col w:w="2640" w:space="720"/><w:col w:w="6000"/></w:cols></w:sectPr>',
|
||||
},
|
||||
)
|
||||
const g = sectionColGeom(s)
|
||||
expect(g.equalWidth).toBe(false)
|
||||
expect(g.widths.map(Math.round)).toEqual([176, 400])
|
||||
expect(g.gaps.map(Math.round)).toEqual([48])
|
||||
expect(Math.round(g.colWidthPx)).toBe(176)
|
||||
// equal-width fallback when the list is absent
|
||||
const eq = sectionColGeom(sec({ columns: 2, colSpace: 720 }))
|
||||
expect(eq.equalWidth).toBe(true)
|
||||
expect(eq.widths).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('columnLayoutSpecs: unequal columns place blocks at cumulative offsets with per-column widths', () => {
|
||||
const els = Array.from({ length: 2 }, () => ({}) as HTMLElement)
|
||||
const blocks: BlockBox[] = [
|
||||
{ ...lineBlock(0, [20]), section: 0, el: els[0] },
|
||||
{ ...lineBlock(20, [20]), section: 0, el: els[1] },
|
||||
]
|
||||
const slices: PageSlice[] = [
|
||||
{
|
||||
start: 0,
|
||||
end: 40,
|
||||
section: 0,
|
||||
physHeight: 20,
|
||||
regions: [
|
||||
{
|
||||
top: 0,
|
||||
height: 100,
|
||||
section: 0,
|
||||
columns: [
|
||||
{ start: 0, end: 20 },
|
||||
{ start: 20, end: 40 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
const secs = [
|
||||
sec(
|
||||
{ columns: 2, colSpace: 720 },
|
||||
{
|
||||
sectPrXml:
|
||||
'<w:sectPr><w:cols w:num="2" w:space="720" w:equalWidth="0"><w:col w:w="2640" w:space="720"/><w:col w:w="6000"/></w:cols></w:sectPr>',
|
||||
},
|
||||
),
|
||||
]
|
||||
const specs = columnLayoutSpecs(blocks, slices, secs)
|
||||
const g = sectionColGeom(secs[0])
|
||||
expect(specs[0]).toMatchObject({ el: els[0], widthPx: g.widths[0], dx: 0, dy: 0 })
|
||||
expect(specs[1].widthPx).toBeCloseTo(g.widths[1], 3)
|
||||
expect(specs[1].dx).toBeCloseTo(g.widths[0] + g.gaps[0], 3)
|
||||
expect(specs[1].dy).toBe(-20)
|
||||
})
|
||||
|
||||
it('a fixed-width block never advances into a narrower column: the page turns instead (1270 shape)', () => {
|
||||
// region cols [400, 200]; a 300px-wide table overflowing col1 must not land in the 200px col2
|
||||
const blocks: BlockBox[] = [
|
||||
{ ...lineBlock(0, [50]), section: 0 },
|
||||
{ ...lineBlock(50, [80]), section: 0, fixedWidthPx: 300 },
|
||||
]
|
||||
const geoms = [{ contentHeight: 100, forceBreak: false, cols: 2, colWidths: [400, 200] }]
|
||||
const slices = computeSectionedSlicesF2(blocks, geoms, 130)
|
||||
expect(slices).toHaveLength(2)
|
||||
expect(slices[1].start).toBe(50)
|
||||
// reflowable text still advances into the narrow column
|
||||
const flowBlocks: BlockBox[] = [
|
||||
{ ...lineBlock(0, [50]), section: 0 },
|
||||
{ ...lineBlock(50, [80]), section: 0 },
|
||||
]
|
||||
const flow = computeSectionedSlicesF2(flowBlocks, geoms, 130)
|
||||
expect(flow).toHaveLength(1)
|
||||
expect(flow[0].regions![0].columns).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('pageAt locates by page start (column spans do not affect it)', () => {
|
||||
const slices = computeSectionedSlicesF2(
|
||||
[lineBlock(0, [50, 50, 50, 50, 50, 50, 50, 50, 50, 50])],
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
// Protect Document dialog (Review > Protect): the dialog turns form state into
|
||||
// a diff (ProtectDialogResult) — untouched sections must stay undefined, and
|
||||
// removing a password-protected restriction must verify the password first.
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { act, createElement } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { hashProtectionPassword, verifyProtectionPassword } from '@genoffice/docx-engine'
|
||||
import { ProtectDialog, type ProtectDialogResult } from '../src/renderer/components/ProtectDialog'
|
||||
|
||||
type Props = Parameters<typeof ProtectDialog>[0]
|
||||
|
||||
const DEFAULTS: Omit<Props, 'onApply' | 'onCancel'> = {
|
||||
encrypted: false,
|
||||
writeProtection: null,
|
||||
protection: null,
|
||||
removePersonalInfo: false,
|
||||
}
|
||||
|
||||
async function mount(partial: Partial<Props>) {
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const onApply = vi.fn<(result: ProtectDialogResult) => void>()
|
||||
const onCancel = vi.fn()
|
||||
let root: Root
|
||||
await act(async () => {
|
||||
root = createRoot(host)
|
||||
root.render(createElement(ProtectDialog, { ...DEFAULTS, onApply, onCancel, ...partial }))
|
||||
})
|
||||
const passwordInputs = () => [
|
||||
...host.querySelectorAll<HTMLInputElement>('input[type="password"]'),
|
||||
]
|
||||
const setValue = async (input: HTMLInputElement, value: string) => {
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!
|
||||
await act(async () => {
|
||||
setter.call(input, value)
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
})
|
||||
}
|
||||
const click = async (el: Element) => {
|
||||
await act(async () => {
|
||||
;(el as HTMLElement).click()
|
||||
})
|
||||
}
|
||||
// submit hashes/verifies passwords asynchronously (iterated SHA-512); keep
|
||||
// flushing until the expected outcome shows up instead of guessing a delay
|
||||
const submit = async (done: () => boolean) => {
|
||||
await click(host.querySelector('.btn-primary')!)
|
||||
const start = Date.now()
|
||||
while (!done() && Date.now() - start < 10_000) {
|
||||
await act(async () => {
|
||||
await new Promise((r) => setTimeout(r, 10))
|
||||
})
|
||||
}
|
||||
expect(done()).toBe(true)
|
||||
}
|
||||
const applied = () => onApply.mock.calls.length > 0
|
||||
const errorShown = () => host.querySelector('.modal-error') !== null
|
||||
const cleanup = async () => {
|
||||
await act(async () => root.unmount())
|
||||
host.remove()
|
||||
}
|
||||
return {
|
||||
host,
|
||||
onApply,
|
||||
onCancel,
|
||||
passwordInputs,
|
||||
setValue,
|
||||
click,
|
||||
submit,
|
||||
applied,
|
||||
errorShown,
|
||||
cleanup,
|
||||
}
|
||||
}
|
||||
|
||||
describe('ProtectDialog', () => {
|
||||
it('submitting untouched state yields an all-undefined diff (even when passwords exist)', async () => {
|
||||
const wp = await hashProtectionPassword('modify-pw', 1000)
|
||||
const d = await mount({ encrypted: true, writeProtection: wp })
|
||||
await d.submit(d.applied)
|
||||
expect(d.onApply).toHaveBeenCalledWith({})
|
||||
await d.cleanup()
|
||||
})
|
||||
|
||||
it('clearing the open-password field of an encrypted document requests removal', async () => {
|
||||
const d = await mount({ encrypted: true })
|
||||
const [open, openConfirm] = d.passwordInputs()
|
||||
await d.setValue(open, '')
|
||||
await d.setValue(openConfirm, '')
|
||||
await d.submit(d.applied)
|
||||
expect(d.onApply).toHaveBeenCalledWith({ openPassword: null })
|
||||
await d.cleanup()
|
||||
})
|
||||
|
||||
it('mismatched confirmation blocks the submit', async () => {
|
||||
const d = await mount({})
|
||||
const [open, openConfirm] = d.passwordInputs()
|
||||
await d.setValue(open, 'abc')
|
||||
await d.setValue(openConfirm, 'abd')
|
||||
await d.submit(d.errorShown)
|
||||
expect(d.onApply).not.toHaveBeenCalled()
|
||||
await d.cleanup()
|
||||
})
|
||||
|
||||
it('setting a modify password produces verifiable writeProtection credentials', async () => {
|
||||
const d = await mount({})
|
||||
const [, , modify, modifyConfirm] = d.passwordInputs()
|
||||
await d.setValue(modify, 'to-modify')
|
||||
await d.setValue(modifyConfirm, 'to-modify')
|
||||
await d.submit(d.applied)
|
||||
const result = d.onApply.mock.calls[0][0]
|
||||
expect(result.openPassword).toBeUndefined()
|
||||
expect(result.writeProtection?.hash).toBeTruthy()
|
||||
expect(await verifyProtectionPassword('to-modify', result.writeProtection!)).toBe(true)
|
||||
await d.cleanup()
|
||||
})
|
||||
|
||||
it('enabling a comments restriction without password enforces mode only', async () => {
|
||||
const d = await mount({})
|
||||
const [enable] = d.host.querySelectorAll('input[type="checkbox"]')
|
||||
await d.click(enable)
|
||||
const radios = d.host.querySelectorAll('input[type="radio"]')
|
||||
await d.click(radios[1]) // trackedChanges, comments, readOnly, forms
|
||||
await d.submit(d.applied)
|
||||
expect(d.onApply).toHaveBeenCalledWith({
|
||||
protection: { edit: 'comments', enforced: true },
|
||||
})
|
||||
await d.cleanup()
|
||||
})
|
||||
|
||||
it('removing a password-protected restriction requires the correct password', async () => {
|
||||
const creds = await hashProtectionPassword('lock-pw', 1000)
|
||||
const d = await mount({ protection: { edit: 'readOnly', enforced: true, ...creds } })
|
||||
const [enable] = d.host.querySelectorAll('input[type="checkbox"]')
|
||||
await d.click(enable) // uncheck → unlock-password field appears
|
||||
const unlock = d.passwordInputs().at(-1)!
|
||||
await d.setValue(unlock, 'wrong')
|
||||
await d.submit(d.errorShown)
|
||||
expect(d.onApply).not.toHaveBeenCalled()
|
||||
|
||||
await d.setValue(d.passwordInputs().at(-1)!, 'lock-pw')
|
||||
await d.submit(d.applied)
|
||||
expect(d.onApply).toHaveBeenCalledWith({ protection: null })
|
||||
await d.cleanup()
|
||||
})
|
||||
|
||||
it('changing only the mode of an unlocked restriction keeps the existing hash', async () => {
|
||||
const creds = await hashProtectionPassword('lock-pw', 1000)
|
||||
const d = await mount({ protection: { edit: 'readOnly', enforced: true, ...creds } })
|
||||
const radios = d.host.querySelectorAll('input[type="radio"]')
|
||||
await d.click(radios[0]) // switch readOnly → trackedChanges
|
||||
await d.setValue(d.passwordInputs().at(-1)!, 'lock-pw')
|
||||
await d.submit(d.applied)
|
||||
const result = d.onApply.mock.calls[0][0]
|
||||
expect(result.protection).toMatchObject({ edit: 'trackedChanges', enforced: true })
|
||||
expect(result.protection?.hash).toBe(creds.hash)
|
||||
await d.cleanup()
|
||||
})
|
||||
|
||||
it('toggling privacy reports only the privacy change', async () => {
|
||||
const d = await mount({})
|
||||
const checkboxes = d.host.querySelectorAll('input[type="checkbox"]')
|
||||
await d.click(checkboxes[checkboxes.length - 1])
|
||||
await d.submit(d.applied)
|
||||
expect(d.onApply).toHaveBeenCalledWith({ removePersonalInfo: true })
|
||||
await d.cleanup()
|
||||
})
|
||||
})
|
||||
@@ -248,7 +248,10 @@ function ribbonProps(editor: Editor, formatState: RibbonFormatState) {
|
||||
onRejectRevision: noop,
|
||||
onGotoRevision: noop,
|
||||
isProtected: false,
|
||||
onToggleProtection: noop,
|
||||
commentsAllowed: false,
|
||||
trackChangesForced: false,
|
||||
protectActive: false,
|
||||
onProtectDoc: noop,
|
||||
onCompare: noop,
|
||||
filePath: null,
|
||||
viewMode: 'print' as const,
|
||||
|
||||
@@ -115,7 +115,10 @@ function ribbonProps(editor: Editor) {
|
||||
onRejectRevision: noop,
|
||||
onGotoRevision: noop,
|
||||
isProtected: false,
|
||||
onToggleProtection: noop,
|
||||
commentsAllowed: false,
|
||||
trackChangesForced: false,
|
||||
protectActive: false,
|
||||
onProtectDoc: noop,
|
||||
onCompare: noop,
|
||||
filePath: null,
|
||||
viewMode: 'print' as const,
|
||||
|
||||
@@ -2,9 +2,12 @@ import { Editor } from '@tiptap/core'
|
||||
import { parseDocx, saveDocx } from '@genoffice/docx-engine'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx'
|
||||
import { docStyleCss } from '../src/renderer/doc-style-css'
|
||||
import { blocksToPmDoc, pmDocToSavePlan, type PmNode } from '../src/renderer/editor/convert'
|
||||
import { editorExtensions } from '../src/renderer/editor/extensions'
|
||||
|
||||
;(globalThis as { CSS?: unknown }).CSS ??= { escape: (s: string) => s }
|
||||
|
||||
const STYLE =
|
||||
'<w:style w:type="table" w:styleId="GridBlue"><w:name w:val="Grid Blue"/>' +
|
||||
'<w:tblStylePr w:type="firstRow"><w:rPr><w:b/></w:rPr>' +
|
||||
@@ -36,4 +39,31 @@ describe('table styles in the editor', () => {
|
||||
expect(await saveDocx(parsed, plan.saveBlocks)).toEqual(source)
|
||||
editor.destroy()
|
||||
})
|
||||
|
||||
it('whole-table rPr/pPr (sz, jc, spacing) reach cell text via docStyleCss (LO calendar family)', async () => {
|
||||
// Calendar2-shaped style: whole-table 14pt centered text against 32pt docDefaults
|
||||
const style =
|
||||
'<w:style w:type="table" w:styleId="Calendar2"><w:name w:val="Calendar 2"/>' +
|
||||
'<w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/><w:jc w:val="center"/></w:pPr>' +
|
||||
'<w:rPr><w:sz w:val="28"/></w:rPr>' +
|
||||
'<w:tblStylePr w:type="firstRow"><w:rPr><w:sz w:val="32"/><w:color w:val="5B9BD5"/></w:rPr></w:tblStylePr>' +
|
||||
'</w:style>'
|
||||
const table =
|
||||
'<w:tbl><w:tblPr><w:tblStyle w:val="Calendar2"/><w:tblLook w:firstRow="1"/></w:tblPr>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>Mon</w:t></w:r></w:p></w:tc></w:tr>' +
|
||||
'<w:tr><w:tc><w:p><w:r><w:t>1</w:t></w:r></w:p></w:tc></w:tr>' +
|
||||
'</w:tbl>'
|
||||
const parsed = await parseDocx(await buildDocx({ bodyXml: table, extraStylesXml: style }))
|
||||
const display = parsed.styles.get('Calendar2')!.tableDisplay!
|
||||
expect(display.wholeTable?.sizeHalfPoints).toBe(28)
|
||||
expect(display.paraJc).toBe('center')
|
||||
expect(display.firstRow?.sizeHalfPoints).toBe(32)
|
||||
|
||||
const css = docStyleCss(parsed as never)
|
||||
const sel = '.doc-page table[data-tbl-style="Calendar2"]'
|
||||
expect(css).toContain(`${sel} td, ${sel} th { font-size:14pt }`)
|
||||
expect(css).toMatch(/tr:first-child td[^{]*\{[^}]*font-size:16pt/)
|
||||
expect(css).toMatch(/td p[^{]*\{[^}]*text-align:center/)
|
||||
expect(css).toMatch(/td p[^{]*\{[^}]*margin-bottom:0/)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Advance-width contract of the bundled Tamil face (fonts/README.md): advances
|
||||
* rewritten to Word's Latha (tools/build-tamil-font.py). A regenerated woff2
|
||||
* that loses the normalization would drift Tamil line breaks ~27% vs Word
|
||||
* (M3 probe 2026-08-14: Tamil Sangam MN sentence R 0.728, space 0.39x).
|
||||
*/
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { advanceEm, readWoff2 } from './helpers/woff2-metrics'
|
||||
|
||||
const FONTS = join(__dirname, '../src/renderer/fonts')
|
||||
const tamil = readWoff2(join(FONTS, 'GenOfficeTamil-Regular.woff2'))
|
||||
|
||||
describe('GenOffice Tamil (Latha-normalized)', () => {
|
||||
it('space and digits match Latha', () => {
|
||||
expect(advanceEm(tamil, 0x20)).toBeCloseTo(0.578, 3)
|
||||
for (let cp = 0x30; cp <= 0x39; cp++) {
|
||||
expect(advanceEm(tamil, cp), `digit ${cp - 0x30}`).toBeCloseTo(0.5, 3)
|
||||
}
|
||||
})
|
||||
|
||||
it('Tamil letters and matras match Latha', () => {
|
||||
const expected: Record<number, number> = {
|
||||
0x0b85: 1.133, // அ
|
||||
0x0b86: 1.352, // ஆ
|
||||
0x0b95: 0.797, // க
|
||||
0x0ba4: 0.836, // த
|
||||
0x0bae: 0.965, // ம
|
||||
0x0bbe: 0.617, // ா
|
||||
0x0bbf: 0.188, // ி
|
||||
0x0bc1: 0.496, // ு
|
||||
}
|
||||
for (const [cp, adv] of Object.entries(expected)) {
|
||||
expect(advanceEm(tamil, Number(cp)), `U+${Number(cp).toString(16)}`).toBeCloseTo(adv, 3)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -44,5 +44,9 @@
|
||||
"vite": "^7.3.1",
|
||||
"vitest": "^4.1.10"
|
||||
},
|
||||
"author": "GenOffice"
|
||||
"author": "GenOffice",
|
||||
"dependencies": {
|
||||
"@tiptap/extension-mathematics": "3.29.2",
|
||||
"katex": "^0.16.47"
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,136 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'
|
||||
import { basename, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
||||
|
||||
export const MARKDOWN_CONVERSION_TTL_MS = 7 * 24 * 60 * 60 * 1000
|
||||
const SESSION_MARKER = '.genoffice-markdown-conversion.json'
|
||||
|
||||
interface ConversionSessionMarker {
|
||||
version: 1
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
function errorCode(error: unknown): string {
|
||||
return (error as NodeJS.ErrnoException | null)?.code ?? ''
|
||||
}
|
||||
|
||||
function isPathInside(root: string, candidate: string): boolean {
|
||||
const fromRoot = relative(root, candidate)
|
||||
return (
|
||||
fromRoot.length > 0 &&
|
||||
fromRoot !== '..' &&
|
||||
!fromRoot.startsWith(`..${sep}`) &&
|
||||
!isAbsolute(fromRoot)
|
||||
)
|
||||
}
|
||||
|
||||
function replaceControlCharacters(value: string): string {
|
||||
return [...value].map((character) => (character.charCodeAt(0) < 32 ? '_' : character)).join('')
|
||||
}
|
||||
|
||||
function safeBaseName(input: string): string {
|
||||
const raw = basename(input)
|
||||
const ext = extname(raw)
|
||||
return (
|
||||
replaceControlCharacters(raw.slice(0, raw.length - ext.length))
|
||||
.replace(/[/\\:*?"<>|]+/g, '_')
|
||||
.replace(/\s+/g, '_')
|
||||
.replace(/^\.+/, '')
|
||||
.slice(0, 100)
|
||||
.replace(/[. ]+$/g, '') || 'Untitled'
|
||||
)
|
||||
}
|
||||
|
||||
async function readSessionMarker(directory: string): Promise<ConversionSessionMarker | null> {
|
||||
try {
|
||||
const value = JSON.parse(await readFile(join(directory, SESSION_MARKER), 'utf8')) as {
|
||||
version?: unknown
|
||||
createdAt?: unknown
|
||||
}
|
||||
if (
|
||||
value.version !== 1 ||
|
||||
typeof value.createdAt !== 'number' ||
|
||||
!Number.isFinite(value.createdAt) ||
|
||||
value.createdAt < 0
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return { version: 1, createdAt: value.createdAt }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes only marked GenOffice session directories older than the TTL.
|
||||
* Unknown files/directories under the cache root are deliberately ignored.
|
||||
*/
|
||||
export async function cleanupStaleMarkdownConversions(
|
||||
root: string,
|
||||
now = Date.now(),
|
||||
ttlMs = MARKDOWN_CONVERSION_TTL_MS,
|
||||
): Promise<string[]> {
|
||||
const absoluteRoot = resolve(root)
|
||||
await mkdir(absoluteRoot, { recursive: true })
|
||||
const removed: string[] = []
|
||||
for (const entry of await readdir(absoluteRoot, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory() || !entry.name.startsWith('session-')) continue
|
||||
const directory = join(absoluteRoot, entry.name)
|
||||
if (!isPathInside(absoluteRoot, directory)) continue
|
||||
const marker = await readSessionMarker(directory)
|
||||
if (!marker || now - marker.createdAt < ttlMs) continue
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
removed.push(directory)
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
export async function createMarkdownConversionSession(
|
||||
root: string,
|
||||
options: { now?: number; id?: string; ttlMs?: number } = {},
|
||||
): Promise<string> {
|
||||
const now = options.now ?? Date.now()
|
||||
const absoluteRoot = resolve(root)
|
||||
await cleanupStaleMarkdownConversions(
|
||||
absoluteRoot,
|
||||
now,
|
||||
options.ttlMs ?? MARKDOWN_CONVERSION_TTL_MS,
|
||||
)
|
||||
const rawId = options.id ?? randomUUID()
|
||||
const id = rawId.replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 80) || randomUUID()
|
||||
const directory = join(absoluteRoot, `session-${now}-${id}`)
|
||||
if (!isPathInside(absoluteRoot, directory)) {
|
||||
throw new Error('invalid Markdown conversion session path')
|
||||
}
|
||||
await mkdir(directory)
|
||||
const marker: ConversionSessionMarker = { version: 1, createdAt: now }
|
||||
await writeFile(join(directory, SESSION_MARKER), `${JSON.stringify(marker)}\n`, { flag: 'wx' })
|
||||
return directory
|
||||
}
|
||||
|
||||
export async function writeMarkdownConversion(
|
||||
sessionDirectory: string,
|
||||
suggestedName: string,
|
||||
bytes: Buffer,
|
||||
id = randomUUID(),
|
||||
): Promise<string> {
|
||||
const marker = await readSessionMarker(sessionDirectory)
|
||||
if (!marker) throw new Error('invalid Markdown conversion session')
|
||||
const base = safeBaseName(suggestedName)
|
||||
const safeId = id.replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 80) || randomUUID()
|
||||
for (let suffix = 0; suffix < 100_000; suffix++) {
|
||||
const tail = suffix === 0 ? '' : `-${suffix}`
|
||||
const target = join(sessionDirectory, `${base}-${safeId}${tail}.docx`)
|
||||
if (!isPathInside(resolve(sessionDirectory), resolve(target))) {
|
||||
throw new Error('invalid Markdown conversion output path')
|
||||
}
|
||||
try {
|
||||
await writeFile(target, bytes, { flag: 'wx' })
|
||||
return target
|
||||
} catch (error) {
|
||||
if (errorCode(error) === 'EEXIST') continue
|
||||
throw error
|
||||
}
|
||||
}
|
||||
throw new Error('Markdown conversion name space exhausted')
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { basename, dirname, extname, join, resolve, sep } from 'node:path'
|
||||
import { basename, dirname, extname, join, relative, resolve, sep } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import {
|
||||
BrowserWindow,
|
||||
@@ -25,6 +25,20 @@ import {
|
||||
} from '@genoffice/electron-utils'
|
||||
import { createI18n, getUiLang } from '@genoffice/i18n'
|
||||
import { atomicWriteFile } from './atomic-write'
|
||||
import {
|
||||
copyImageIntoOwnedAssets,
|
||||
discardPendingOwnedAssets,
|
||||
extractMarkdownImageSources,
|
||||
pendingOwnedAssetsForDocument,
|
||||
prepareAssetsForSaveAs,
|
||||
reconcileOwnedAssets,
|
||||
renameOwnedAssetDocument,
|
||||
resolveSafeRelativeImagePath,
|
||||
resolveSourcePendingAfterSaveAs,
|
||||
rollbackPreparedSaveAsAssets,
|
||||
writeImageIntoOwnedAssets,
|
||||
} from './asset-lifecycle'
|
||||
import { createMarkdownConversionSession, writeMarkdownConversion } from './conversion-lifecycle'
|
||||
import { MARKDOWN_CHANNELS } from '../shared/ipc'
|
||||
import type {
|
||||
ExportDocxRequest,
|
||||
@@ -314,11 +328,20 @@ export function setMarkdownFileSavedHook(hook: (wc: WebContents, path: string) =
|
||||
|
||||
/** Fired after a "convert & open in Docs" export — the shell routes the new .docx to a docs tab */
|
||||
let docxExportedHook: ((path: string) => void) | null = null
|
||||
/** One marked cache session per app process. Old crash leftovers are removed after seven days. */
|
||||
let conversionSessionPromise: Promise<string> | null = null
|
||||
|
||||
export function setMarkdownDocxExportedHook(hook: (path: string) => void): void {
|
||||
docxExportedHook = hook
|
||||
}
|
||||
|
||||
function markdownConversionSession(): Promise<string> {
|
||||
conversionSessionPromise ??= createMarkdownConversionSession(
|
||||
join(app.getPath('userData'), 'markdown-conversions'),
|
||||
)
|
||||
return conversionSessionPromise
|
||||
}
|
||||
|
||||
/** Shell menu export entry: ask the renderer to serialize and run the export flow */
|
||||
export function sendMarkdownExportRequest(contents: WebContents, format: ExportFormat): void {
|
||||
if (!contents.isDestroyed()) contents.send(MARKDOWN_CHANNELS.exportRequest, format)
|
||||
@@ -344,6 +367,9 @@ export function markdownFileRenamed(contents: WebContents, oldPath: string, newP
|
||||
if (openPathByWc.get(wcId) === oldPath) openPathByWc.set(wcId, newPath)
|
||||
const allowed = allowedByWc.get(wcId)
|
||||
if (allowed?.has(oldPath)) allowed.add(newPath)
|
||||
void renameOwnedAssetDocument(oldPath, newPath).catch((error) => {
|
||||
console.warn('[markdown] asset manifest rename sync failed:', error)
|
||||
})
|
||||
if (!contents.isDestroyed()) contents.send(MARKDOWN_CHANNELS.fileRenamed, newPath)
|
||||
}
|
||||
|
||||
@@ -371,7 +397,16 @@ export async function requestMarkdownClose(
|
||||
? await dialog.showMessageBox(parent, options)
|
||||
: await dialog.showMessageBox(options)
|
||||
if (response === 2) return false
|
||||
if (response === 1) return true
|
||||
if (response === 1) {
|
||||
const documentPath = savePathByWc.get(contents.id)
|
||||
if (documentPath) {
|
||||
const discarded = await discardPendingOwnedAssets(documentPath)
|
||||
if (discarded.errors.length > 0) {
|
||||
console.warn('[markdown] pending asset discard incomplete:', discarded.errors)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return new Promise<boolean>((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
closeSaveWaiters.delete(contents.id)
|
||||
@@ -460,7 +495,7 @@ const DISPLAY_IMAGE_EXTS = new Set([
|
||||
* open document's directory are served.
|
||||
*/
|
||||
function registerImageProtocol(): void {
|
||||
protocol.handle('md-asset', (request) => {
|
||||
protocol.handle('md-asset', async (request) => {
|
||||
let target: string
|
||||
try {
|
||||
target = decodeURIComponent(new URL(request.url).pathname)
|
||||
@@ -472,12 +507,15 @@ function registerImageProtocol(): void {
|
||||
if (!DISPLAY_IMAGE_EXTS.has(extname(target).toLowerCase()) || !existsSync(target)) {
|
||||
return new Response(null, { status: 404 })
|
||||
}
|
||||
const inDocDir = [...new Set([...openPathByWc.values(), ...savePathByWc.values()])].some(
|
||||
(doc) => {
|
||||
const dir = resolve(dirname(doc))
|
||||
return target === dir || target.startsWith(dir + sep)
|
||||
},
|
||||
)
|
||||
let inDocDir = false
|
||||
for (const doc of new Set([...openPathByWc.values(), ...savePathByWc.values()])) {
|
||||
const dir = resolve(dirname(doc))
|
||||
if (target === dir || !target.startsWith(dir + sep)) continue
|
||||
if (await resolveSafeRelativeImagePath(doc, relative(dir, target))) {
|
||||
inDocDir = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!inDocDir) return new Response(null, { status: 403 })
|
||||
return net.fetch(pathToFileURL(target).toString())
|
||||
})
|
||||
@@ -512,15 +550,45 @@ function registerMarkdownIpc(): void {
|
||||
if (typeof request?.text !== 'string') {
|
||||
return done({ ok: false, error: 'markdown: bad save request' })
|
||||
}
|
||||
if (
|
||||
request.imageSources !== undefined &&
|
||||
(!Array.isArray(request.imageSources) ||
|
||||
request.imageSources.some((source) => typeof source !== 'string'))
|
||||
) {
|
||||
return done({ ok: false, error: 'markdown: bad image references' })
|
||||
}
|
||||
const mode: SaveMode = request.mode === 'saveAs' ? 'saveAs' : 'save'
|
||||
const pathAtRequest = savePathByWc.get(e.sender.id)
|
||||
const pendingAtRequest = pathAtRequest
|
||||
? await pendingOwnedAssetsForDocument(pathAtRequest)
|
||||
: []
|
||||
try {
|
||||
const suggestedName =
|
||||
typeof request.suggestedName === 'string' ? request.suggestedName : undefined
|
||||
const target = await resolveSaveTarget(e, mode, suggestedName)
|
||||
if (target === 'canceled') return done({ ok: true, canceled: true })
|
||||
if (!target) return done({ ok: false, error: 'markdown: no save target' })
|
||||
const isNewPath = savePathByWc.get(e.sender.id) !== target
|
||||
await writeTextAtomic(target, request.text)
|
||||
const currentPath = pathAtRequest
|
||||
const isNewPath = currentPath !== target
|
||||
const imageSources = [...(request.imageSources ?? [])]
|
||||
const knownImageSources = new Set(imageSources)
|
||||
for (const source of extractMarkdownImageSources(request.text)) {
|
||||
if (knownImageSources.has(source)) continue
|
||||
knownImageSources.add(source)
|
||||
imageSources.push(source)
|
||||
}
|
||||
const prepared =
|
||||
currentPath && resolve(dirname(currentPath)) !== resolve(dirname(target))
|
||||
? await prepareAssetsForSaveAs(currentPath, target, request.text, imageSources)
|
||||
: null
|
||||
const textToWrite = prepared?.text ?? request.text
|
||||
const savedImageSources = prepared?.imageSources ?? imageSources
|
||||
try {
|
||||
await writeTextAtomic(target, textToWrite)
|
||||
} catch (error) {
|
||||
if (prepared) await rollbackPreparedSaveAsAssets(prepared).catch(() => {})
|
||||
throw error
|
||||
}
|
||||
savePathByWc.set(e.sender.id, target)
|
||||
// keep the reload path in sync — a stale openPathByWc would make a
|
||||
// reloaded renderer load the OLD file and then save it over the new one
|
||||
@@ -529,8 +597,33 @@ function registerMarkdownIpc(): void {
|
||||
allowed.add(target)
|
||||
allowedByWc.set(e.sender.id, allowed)
|
||||
dirtyByWc.delete(e.sender.id)
|
||||
const pendingNames = prepared
|
||||
? prepared.created.map((record) => record.name)
|
||||
: currentPath && resolve(currentPath) === resolve(target)
|
||||
? pendingAtRequest
|
||||
: []
|
||||
const reconciled = await reconcileOwnedAssets(target, savedImageSources, { pendingNames })
|
||||
if (reconciled.errors.length > 0) {
|
||||
console.warn('[markdown] asset reconciliation incomplete:', reconciled.errors)
|
||||
}
|
||||
if (mode === 'saveAs' && currentPath && resolve(currentPath) !== resolve(target)) {
|
||||
const sourceResolved = await resolveSourcePendingAfterSaveAs(
|
||||
currentPath,
|
||||
pendingAtRequest,
|
||||
)
|
||||
if (sourceResolved.errors.length > 0) {
|
||||
console.warn(
|
||||
'[markdown] source asset reconciliation incomplete:',
|
||||
sourceResolved.errors,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (isNewPath) fileSavedHook?.(e.sender, target)
|
||||
return done({ ok: true, path: target })
|
||||
return done({
|
||||
ok: true,
|
||||
path: target,
|
||||
...(prepared?.rewrites.length ? { imageRewrites: prepared.rewrites } : {}),
|
||||
})
|
||||
} catch (err) {
|
||||
return done({ ok: false, error: err instanceof Error ? err.message : String(err) })
|
||||
}
|
||||
@@ -550,14 +643,7 @@ function registerMarkdownIpc(): void {
|
||||
})
|
||||
const source = picked.filePaths[0]
|
||||
if (picked.canceled || !source) return null
|
||||
const assetsDir = join(dirname(docPath), 'assets')
|
||||
await mkdir(assetsDir, { recursive: true })
|
||||
const ext = extname(source)
|
||||
const base = basename(source, ext).replace(/[/\\:*?"<>|]/g, '_')
|
||||
let name = `${base}${ext}`
|
||||
for (let n = 1; existsSync(join(assetsDir, name)); n++) name = `${base}-${n}${ext}`
|
||||
await copyFile(source, join(assetsDir, name))
|
||||
return `assets/${name}`
|
||||
return copyImageIntoOwnedAssets(docPath, source)
|
||||
})
|
||||
|
||||
ipcMain.handle(
|
||||
@@ -568,12 +654,7 @@ function registerMarkdownIpc(): void {
|
||||
if (!docPath || typeof data?.base64 !== 'string' || !data.base64) return null
|
||||
// keep in sync with readImage's MIME map — every authored asset must stay DOCX-exportable
|
||||
if (!['png', 'jpg', 'jpeg', 'gif'].includes(ext)) return null
|
||||
const assetsDir = join(dirname(docPath), 'assets')
|
||||
await mkdir(assetsDir, { recursive: true })
|
||||
let name = `image.${ext}`
|
||||
for (let n = 1; existsSync(join(assetsDir, name)); n++) name = `image-${n}.${ext}`
|
||||
await writeFile(join(assetsDir, name), Buffer.from(data.base64, 'base64'))
|
||||
return `assets/${name}`
|
||||
return writeImageIntoOwnedAssets(docPath, `image.${ext}`, Buffer.from(data.base64, 'base64'))
|
||||
},
|
||||
)
|
||||
|
||||
@@ -589,10 +670,8 @@ function registerMarkdownIpc(): void {
|
||||
async (e, src: unknown): Promise<ImageData | null> => {
|
||||
const docPath = savePathByWc.get(e.sender.id)
|
||||
if (!docPath || typeof src !== 'string' || /^[a-z][a-z0-9+.-]*:/i.test(src)) return null
|
||||
const docDir = resolve(dirname(docPath))
|
||||
const target = resolve(docDir, src)
|
||||
// images must live inside the document's directory (assets/ convention)
|
||||
if (target !== docDir && !target.startsWith(docDir + sep)) return null
|
||||
const target = await resolveSafeRelativeImagePath(docPath, src)
|
||||
if (!target) return null
|
||||
const mime = MIME_BY_EXT[extname(target).toLowerCase()]
|
||||
if (!mime || !existsSync(target)) return null
|
||||
try {
|
||||
@@ -617,12 +696,14 @@ function registerMarkdownIpc(): void {
|
||||
try {
|
||||
const bytes = Buffer.from(request.base64, 'base64')
|
||||
if (request.mode === 'openInDocs') {
|
||||
// silent convert next to the .md (untitled documents go to the default save folder)
|
||||
const docPath = savePathByWc.get(e.sender.id)
|
||||
const dir = docPath ? dirname(docPath) : configuredDefaultSaveDir(app)
|
||||
let target = join(dir, `${safeName}.docx`)
|
||||
for (let n = 1; existsSync(target); n++) target = join(dir, `${safeName}-${n}.docx`)
|
||||
await writeFile(target, bytes)
|
||||
// Each conversion gets an app-owned cache file. A marked session is
|
||||
// retained for the life of open Docs tabs; crash leftovers expire
|
||||
// after the explicit TTL enforced when the next session starts.
|
||||
const target = await writeMarkdownConversion(
|
||||
await markdownConversionSession(),
|
||||
safeName,
|
||||
bytes,
|
||||
)
|
||||
docxExportedHook?.(target)
|
||||
return { ok: true, path: target }
|
||||
}
|
||||
|
||||
@@ -53,6 +53,36 @@ function bytesToBase64(bytes: Uint8Array): string {
|
||||
return btoa(binary)
|
||||
}
|
||||
|
||||
function imageSourcesFromEditor(editor: Editor): string[] {
|
||||
const sources: string[] = []
|
||||
editor.state.doc.descendants((node) => {
|
||||
if (node.type.name === 'image' && typeof node.attrs.src === 'string') {
|
||||
sources.push(node.attrs.src)
|
||||
}
|
||||
})
|
||||
return sources
|
||||
}
|
||||
|
||||
function applyImageRewrites(
|
||||
editor: Editor,
|
||||
rewrites: ReadonlyArray<{ from: string; to: string }>,
|
||||
): void {
|
||||
const bySource = new Map(rewrites.map(({ from, to }) => [from, to]))
|
||||
if (bySource.size === 0) return
|
||||
let transaction = editor.state.tr
|
||||
let changed = false
|
||||
editor.state.doc.descendants((node, pos) => {
|
||||
if (node.type.name !== 'image') return
|
||||
const replacement = bySource.get(String(node.attrs.src ?? ''))
|
||||
if (!replacement || replacement === node.attrs.src) return
|
||||
transaction = transaction.setNodeMarkup(pos, undefined, { ...node.attrs, src: replacement })
|
||||
changed = true
|
||||
})
|
||||
if (!changed) return
|
||||
transaction.setMeta('addToHistory', false).setMeta('uiOnly', true)
|
||||
editor.view.dispatch(transaction)
|
||||
}
|
||||
|
||||
/** Measure a document image via the DOM (the editor already displays it) */
|
||||
function measureImage(displaySrc: string): Promise<{ width: number; height: number } | null> {
|
||||
return new Promise((resolvePromise) => {
|
||||
@@ -85,7 +115,8 @@ export default function App() {
|
||||
const [slashState, setSlashState] = useState<SlashMenuState | null>(null)
|
||||
const [fmOpen, setFmOpen] = useState(false)
|
||||
const [fmText, setFmText] = useState('')
|
||||
const [aiOpen, setAiOpen] = useState(true)
|
||||
// Persisted so a closed AI panel stays closed on next launch (docs/slides parity)
|
||||
const [aiOpen, setAiOpen] = useState(() => localStorage.getItem('mdapp.showAi') !== '0')
|
||||
const [aiPreset, setAiPreset] = useState<AiPreset | null>(null)
|
||||
const [autoSave, setAutoSave] = useState(() => localStorage.getItem('mdapp.autoSave') === '1')
|
||||
const [zoom, setZoom] = useState(100)
|
||||
@@ -219,11 +250,16 @@ export default function App() {
|
||||
const fmAtSave = envelopeRef.current.frontmatter
|
||||
const body = current.getMarkdown()
|
||||
const text = serializeDocText(envelopeRef.current, body)
|
||||
const result = await window.markdownApi.save({ text, mode, suggestedName })
|
||||
const imageSources = imageSourcesFromEditor(current)
|
||||
const result = await window.markdownApi.save({ text, imageSources, mode, suggestedName })
|
||||
if (result.ok && 'path' in result) {
|
||||
setFilePath(result.path)
|
||||
const unchanged =
|
||||
editorRef.current?.state.doc === docAtSave && envelopeRef.current.frontmatter === fmAtSave
|
||||
if (result.imageRewrites?.length && editorRef.current) {
|
||||
applyImageRewrites(editorRef.current, result.imageRewrites)
|
||||
}
|
||||
setImageBaseDir(dirOf(result.path))
|
||||
setFilePath(result.path)
|
||||
if (unchanged) {
|
||||
dirtyRef.current = false
|
||||
setDirty(false)
|
||||
@@ -399,6 +435,10 @@ export default function App() {
|
||||
localStorage.setItem('mdapp.autoSave', autoSave ? '1' : '0')
|
||||
}, [autoSave])
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem('mdapp.showAi', aiOpen ? '1' : '0')
|
||||
}, [aiOpen])
|
||||
|
||||
// autosave: every 30s and on window blur, silently persist pending changes
|
||||
// (same policy as the docs app; untitled documents are skipped — the first
|
||||
// save must go through the explicit save path that names the file)
|
||||
|
||||
@@ -104,6 +104,7 @@ export function AiPanel({
|
||||
const [panelWidth, setPanelWidth] = useState(() => clampPanelWidth(preferredWidthRef.current))
|
||||
const [resizing, setResizing] = useState(false)
|
||||
const asideRef = useRef<HTMLElement>(null)
|
||||
const mountedRef = useRef(true)
|
||||
|
||||
useEffect(() => {
|
||||
const dock = asideRef.current?.closest('.ai-dock') as HTMLElement | null
|
||||
@@ -254,6 +255,16 @@ export function AiPanel({
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
loopRef.current?.cancel()
|
||||
const editor = depsRef.current.getEditor()
|
||||
if (editor) clearAiHighlights(editor)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// ── chat-history persistence: bind to the file, restore prior transcript ──
|
||||
useEffect(() => {
|
||||
const api = window.projectApi
|
||||
@@ -342,8 +353,10 @@ export function AiPanel({
|
||||
void (async () => {
|
||||
try {
|
||||
settingsRef.current = await window.markdownApi.getAiSettings()
|
||||
if (!mountedRef.current) return
|
||||
await loop.run(instruction)
|
||||
} catch (err) {
|
||||
if (!mountedRef.current) return
|
||||
patchLast({
|
||||
streaming: false,
|
||||
text: err instanceof Error ? err.message : String(err),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { NodeViewContent, NodeViewWrapper } from '@tiptap/react'
|
||||
import type { NodeViewProps } from '@tiptap/react'
|
||||
import { t } from '../i18n/locale'
|
||||
@@ -38,13 +38,31 @@ const LANGUAGES = [
|
||||
|
||||
export function CodeBlockView({ node, updateAttributes, editor }: NodeViewProps) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
const copyTimerRef = useRef<number | null>(null)
|
||||
const mountedRef = useRef(true)
|
||||
const language = String(node.attrs.language ?? '') || 'plaintext'
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
if (copyTimerRef.current !== null) window.clearTimeout(copyTimerRef.current)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const copy = () => {
|
||||
void navigator.clipboard.writeText(node.textContent).then(() => {
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 1500)
|
||||
})
|
||||
void navigator.clipboard
|
||||
.writeText(node.textContent)
|
||||
.then(() => {
|
||||
if (!mountedRef.current) return
|
||||
if (copyTimerRef.current !== null) window.clearTimeout(copyTimerRef.current)
|
||||
setCopied(true)
|
||||
copyTimerRef.current = window.setTimeout(() => {
|
||||
copyTimerRef.current = null
|
||||
setCopied(false)
|
||||
}, 1500)
|
||||
})
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -70,6 +70,8 @@ function dragHandlePlugin(editor: Editor): Plugin {
|
||||
menu.className = 'md-block-menu'
|
||||
menu.style.display = 'none'
|
||||
|
||||
const previousContainerPosition = container?.style.position ?? ''
|
||||
const setContainerPosition = Boolean(container && !container.style.position)
|
||||
if (container) {
|
||||
container.style.position ||= 'relative'
|
||||
container.append(handle, menu)
|
||||
@@ -234,10 +236,11 @@ function dragHandlePlugin(editor: Editor): Plugin {
|
||||
}, 250)
|
||||
}
|
||||
|
||||
const onHandleMouseMove = (event: MouseEvent) => event.stopPropagation()
|
||||
view.dom.addEventListener('mousemove', onMouseMove)
|
||||
view.dom.addEventListener('mouseenter', cancelHide)
|
||||
view.dom.addEventListener('mouseleave', scheduleHide)
|
||||
handle.addEventListener('mousemove', (e) => e.stopPropagation())
|
||||
handle.addEventListener('mousemove', onHandleMouseMove)
|
||||
handle.addEventListener('mouseenter', cancelHide)
|
||||
handle.addEventListener('mouseleave', scheduleHide)
|
||||
grip.addEventListener('dragstart', onDragStart)
|
||||
@@ -256,9 +259,18 @@ function dragHandlePlugin(editor: Editor): Plugin {
|
||||
view.dom.removeEventListener('mousemove', onMouseMove)
|
||||
view.dom.removeEventListener('mouseenter', cancelHide)
|
||||
view.dom.removeEventListener('mouseleave', scheduleHide)
|
||||
handle.removeEventListener('mousemove', onHandleMouseMove)
|
||||
handle.removeEventListener('mouseenter', cancelHide)
|
||||
handle.removeEventListener('mouseleave', scheduleHide)
|
||||
grip.removeEventListener('dragstart', onDragStart)
|
||||
grip.removeEventListener('click', onGripClick)
|
||||
plus.removeEventListener('click', onPlusClick)
|
||||
document.removeEventListener('scroll', onScrollOrLeave, true)
|
||||
handle.remove()
|
||||
menu.remove()
|
||||
if (container && setContainerPosition && container.style.position === 'relative') {
|
||||
container.style.position = previousContainerPosition
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
@@ -11,6 +11,7 @@ import { LocalImage } from './localImage'
|
||||
import { BlockDragHandle } from './blockDragHandle'
|
||||
import { BlockKeymap } from './blockKeymap'
|
||||
import { AiHighlight } from './aiHighlight'
|
||||
import { buildMathExtensions } from './math'
|
||||
import { SlashCommand } from './slashCommand'
|
||||
import type { SlashController, SlashItem } from './slashCommand'
|
||||
import { t } from '../i18n/locale'
|
||||
@@ -44,6 +45,8 @@ export function buildExtensions(options: BuildExtensionsOptions): AnyExtension[]
|
||||
TableKit.configure({ table: { resizable: false, renderWrapper: true } }),
|
||||
TaskList,
|
||||
TaskItem.configure({ nested: true }),
|
||||
// KaTeX-rendered $...$ / $$...$$ formulas (issue #100)
|
||||
...buildMathExtensions(),
|
||||
LocalImage,
|
||||
BlockDragHandle,
|
||||
BlockKeymap,
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { AnyExtension } from '@tiptap/core'
|
||||
import { Extension } from '@tiptap/core'
|
||||
import { Plugin } from '@tiptap/pm/state'
|
||||
import { BlockMath, InlineMath } from '@tiptap/extension-mathematics'
|
||||
import { openMathEditor } from './mathEdit'
|
||||
|
||||
/**
|
||||
* Stricter inline tokenizer than the upstream default (`$...$` with any
|
||||
* content): the content must not start or end with whitespace and the
|
||||
* closing `$` must not be followed by a digit, so running text with
|
||||
* currency amounts ("paid $5 and $10") never turns into formulas.
|
||||
*/
|
||||
const STRICT_INLINE_MATH_RE = /^\$(?!\s)([^$\n]*[^\s$])\$(?!\d)/
|
||||
|
||||
const StrictInlineMath = InlineMath.extend({
|
||||
markdownTokenizer: {
|
||||
name: 'inlineMath',
|
||||
level: 'inline',
|
||||
start: (src: string) => src.indexOf('$'),
|
||||
tokenize: (src: string) => {
|
||||
const match = STRICT_INLINE_MATH_RE.exec(src)
|
||||
if (!match) return undefined
|
||||
return { type: 'inlineMath', raw: match[0], latex: match[1].trim() }
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
/** Math nodes are atoms — clicking one opens the LaTeX edit popover. */
|
||||
const MathClickEdit = Extension.create({
|
||||
name: 'mathClickEdit',
|
||||
|
||||
addProseMirrorPlugins() {
|
||||
const editor = this.editor
|
||||
return [
|
||||
new Plugin({
|
||||
props: {
|
||||
handleClickOn: (view, _pos, node, nodePos, event) => {
|
||||
if (node.type.name !== 'blockMath' && node.type.name !== 'inlineMath') return false
|
||||
if (!view.editable) return false
|
||||
const target = event.target as HTMLElement | null
|
||||
const anchor = target?.closest?.('.tiptap-mathematics-render') ?? target
|
||||
if (!anchor) return false
|
||||
openMathEditor(editor, { pos: nodePos, anchor: anchor.getBoundingClientRect() })
|
||||
return true
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
},
|
||||
})
|
||||
|
||||
export function buildMathExtensions(): AnyExtension[] {
|
||||
return [BlockMath, StrictInlineMath, MathClickEdit]
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import katex from 'katex'
|
||||
import type { Editor } from '@tiptap/core'
|
||||
import { t } from '../i18n/locale'
|
||||
|
||||
/** Anchor rectangle in viewport coordinates (a DOMRect or a caret box) */
|
||||
interface AnchorRect {
|
||||
left: number
|
||||
top: number
|
||||
bottom: number
|
||||
}
|
||||
|
||||
interface OpenMathOptions {
|
||||
/** position of an existing math node to edit; null → insert a new block formula */
|
||||
pos: number | null
|
||||
anchor: AnchorRect
|
||||
}
|
||||
|
||||
let activePop: { el: HTMLElement; dispose: () => void } | null = null
|
||||
|
||||
function closeActive(): void {
|
||||
activePop?.dispose()
|
||||
activePop = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating LaTeX editor for math nodes: textarea + live KaTeX preview.
|
||||
* Apply with the button or Cmd/Ctrl+Enter, dismiss with Esc or an outside
|
||||
* click. Applying an empty input deletes the node.
|
||||
*/
|
||||
export function openMathEditor(editor: Editor, options: OpenMathOptions): void {
|
||||
closeActive()
|
||||
const { pos, anchor } = options
|
||||
const node = pos === null ? null : editor.state.doc.nodeAt(pos)
|
||||
const isBlock = node ? node.type.name === 'blockMath' : true
|
||||
const expectedType = node?.type.name ?? null
|
||||
|
||||
/** the node at `pos`, but only while it is still the math node we opened on */
|
||||
const targetNode = () => {
|
||||
if (pos === null) return null
|
||||
const target = editor.state.doc.nodeAt(pos)
|
||||
return target && target.type.name === expectedType ? target : null
|
||||
}
|
||||
|
||||
const pop = document.createElement('div')
|
||||
pop.className = 'md-math-pop'
|
||||
|
||||
const input = document.createElement('textarea')
|
||||
input.className = 'md-math-input'
|
||||
input.rows = isBlock ? 4 : 2
|
||||
input.placeholder = t('mathPlaceholder')
|
||||
input.value = String(node?.attrs.latex ?? '')
|
||||
input.spellcheck = false
|
||||
|
||||
const preview = document.createElement('div')
|
||||
preview.className = 'md-math-preview'
|
||||
|
||||
const row = document.createElement('div')
|
||||
row.className = 'md-math-actions'
|
||||
const apply = document.createElement('button')
|
||||
apply.className = 'md-math-apply'
|
||||
apply.textContent = t('linkApply')
|
||||
row.appendChild(apply)
|
||||
if (pos !== null) {
|
||||
const del = document.createElement('button')
|
||||
del.className = 'md-math-delete'
|
||||
del.textContent = t('blockDelete')
|
||||
del.addEventListener('click', () => {
|
||||
const target = targetNode()
|
||||
if (target) {
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.deleteRange({ from: pos, to: pos + target.nodeSize })
|
||||
.run()
|
||||
}
|
||||
close()
|
||||
})
|
||||
row.appendChild(del)
|
||||
}
|
||||
|
||||
const renderPreview = (): void => {
|
||||
const latex = input.value.trim()
|
||||
preview.classList.toggle('md-math-preview-empty', latex === '')
|
||||
if (latex === '') {
|
||||
preview.textContent = ''
|
||||
return
|
||||
}
|
||||
katex.render(latex, preview, { throwOnError: false, displayMode: isBlock })
|
||||
}
|
||||
input.addEventListener('input', renderPreview)
|
||||
|
||||
const applyLatex = (): void => {
|
||||
const latex = input.value.trim()
|
||||
if (pos === null) {
|
||||
if (latex) editor.chain().focus().insertBlockMath({ latex }).run()
|
||||
} else {
|
||||
const target = targetNode()
|
||||
if (target) {
|
||||
if (!latex) {
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.deleteRange({ from: pos, to: pos + target.nodeSize })
|
||||
.run()
|
||||
} else if (target.type.name === 'blockMath') {
|
||||
editor.chain().focus().updateBlockMath({ latex, pos }).run()
|
||||
} else {
|
||||
editor.chain().focus().updateInlineMath({ latex, pos }).run()
|
||||
}
|
||||
}
|
||||
}
|
||||
close()
|
||||
}
|
||||
apply.addEventListener('click', applyLatex)
|
||||
|
||||
pop.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.stopPropagation()
|
||||
close()
|
||||
editor.commands.focus()
|
||||
} else if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
|
||||
event.preventDefault()
|
||||
applyLatex()
|
||||
}
|
||||
})
|
||||
|
||||
const onPointerDown = (event: PointerEvent): void => {
|
||||
if (!pop.contains(event.target as Node)) close()
|
||||
}
|
||||
document.addEventListener('pointerdown', onPointerDown, true)
|
||||
|
||||
// any document change (typing in the editor, an AI edit, …) invalidates
|
||||
// `pos` — close instead of ever applying against a stale position
|
||||
const onTransaction = ({ transaction }: { transaction: { docChanged: boolean } }): void => {
|
||||
if (transaction.docChanged) close()
|
||||
}
|
||||
editor.on('transaction', onTransaction)
|
||||
|
||||
const close = (): void => {
|
||||
document.removeEventListener('pointerdown', onPointerDown, true)
|
||||
editor.off('transaction', onTransaction)
|
||||
pop.remove()
|
||||
if (activePop?.el === pop) activePop = null
|
||||
}
|
||||
|
||||
pop.append(input, preview, row)
|
||||
document.body.appendChild(pop)
|
||||
activePop = { el: pop, dispose: close }
|
||||
|
||||
// position below the anchor, clamped to the viewport — measured only after
|
||||
// the preview has rendered, so a tall formula flips above the anchor
|
||||
renderPreview()
|
||||
const width = pop.offsetWidth
|
||||
const height = pop.offsetHeight
|
||||
const margin = 8
|
||||
const left = Math.max(margin, Math.min(anchor.left, window.innerWidth - width - margin))
|
||||
let top = anchor.bottom + 6
|
||||
if (top + height > window.innerHeight - margin) {
|
||||
top = Math.max(margin, anchor.top - height - 6)
|
||||
}
|
||||
pop.style.left = `${left}px`
|
||||
pop.style.top = `${top}px`
|
||||
|
||||
input.focus()
|
||||
input.setSelectionRange(input.value.length, input.value.length)
|
||||
}
|
||||
|
||||
/** Open the popover in insert mode, anchored at the current caret. */
|
||||
export function openMathCreate(editor: Editor): void {
|
||||
const coords = editor.view.coordsAtPos(editor.state.selection.from)
|
||||
openMathEditor(editor, { pos: null, anchor: coords })
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { Suggestion } from '@tiptap/suggestion'
|
||||
import type { SuggestionProps } from '@tiptap/suggestion'
|
||||
import type { StringKey } from '../i18n/locale'
|
||||
import { t } from '../i18n/locale'
|
||||
import { openMathCreate } from './mathEdit'
|
||||
|
||||
export interface SlashItem {
|
||||
id: string
|
||||
@@ -123,6 +124,15 @@ export function buildSlashItems(extra?: { insertImage?: () => void }): SlashItem
|
||||
keywords: ['divider', 'rule', '---'],
|
||||
run: (e, r) => void blockChain(e, r).setHorizontalRule().run(),
|
||||
},
|
||||
{
|
||||
id: 'math',
|
||||
labelKey: 'insertMath',
|
||||
keywords: ['formula', 'equation', 'latex', 'katex', '$$'],
|
||||
run: (e, r) => {
|
||||
blockChain(e, r).run()
|
||||
openMathCreate(e)
|
||||
},
|
||||
},
|
||||
]
|
||||
if (extra?.insertImage) {
|
||||
items.push({
|
||||
|
||||
@@ -4,6 +4,8 @@ import {
|
||||
TABLE_HEADER_FILL,
|
||||
buildBlankDocx,
|
||||
generateTableModelXml,
|
||||
latexToOmml,
|
||||
mathParagraphXml,
|
||||
parseDocx,
|
||||
saveDocx,
|
||||
} from '@genoffice/docx-engine'
|
||||
@@ -46,6 +48,12 @@ function runsFromInline(content: JSONContent[] | undefined): Run[] {
|
||||
runs.push({ text: '\n' })
|
||||
continue
|
||||
}
|
||||
if (child.type === 'inlineMath') {
|
||||
// Run[] cannot carry OMML — keep the LaTeX source visible instead
|
||||
const latex = String(child.attrs?.latex ?? '')
|
||||
if (latex) runs.push({ text: `$${latex}$`, font: CODE_FONT })
|
||||
continue
|
||||
}
|
||||
if (child.type !== 'text' || !child.text) continue
|
||||
const run: Run = { text: child.text }
|
||||
for (const mark of child.marks ?? []) {
|
||||
@@ -226,6 +234,20 @@ function walkBlock(ctx: WalkContext, node: JSONContent, base?: ParaFormat): void
|
||||
case 'table':
|
||||
ctx.blocks.push({ kind: 'xml', xml: generateTableModelXml(mapTable(node)) })
|
||||
break
|
||||
case 'blockMath': {
|
||||
const latex = String(node.attrs?.latex ?? '')
|
||||
try {
|
||||
ctx.blocks.push({ kind: 'xml', xml: mathParagraphXml(latexToOmml(latex)) })
|
||||
} catch {
|
||||
// LaTeX outside the OMML converter's subset: keep the source visible
|
||||
pushParagraph(ctx, {
|
||||
type: 'paragraph',
|
||||
runs: [{ text: `$$${latex}$$`, font: CODE_FONT }],
|
||||
format: base,
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
default: {
|
||||
// unknown block: keep its text so nothing silently disappears
|
||||
const text = plainText(node)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import katexCss from 'katex/dist/katex.min.css?inline'
|
||||
|
||||
/** Print-theme CSS: mirrors the editor typography so the PDF matches the canvas */
|
||||
const PRINT_CSS = `
|
||||
* { box-sizing: border-box; }
|
||||
@@ -50,12 +52,17 @@ export function buildPrintHtml(editorRoot: HTMLElement, title: string): string {
|
||||
for (const bar of clone.querySelectorAll('.md-codeblock-bar')) bar.remove()
|
||||
|
||||
const escapedTitle = title.replace(/&/g, '&').replace(/</g, '<')
|
||||
// <base> lets the inlined KaTeX CSS resolve its relative font URLs from the
|
||||
// print iframe (which otherwise has no document URL to resolve against)
|
||||
const escapedBase = document.baseURI.replace(/"/g, '"')
|
||||
return [
|
||||
'<!doctype html>',
|
||||
'<html>',
|
||||
'<head>',
|
||||
'<meta charset="utf-8">',
|
||||
`<base href="${escapedBase}">`,
|
||||
`<title>${escapedTitle}</title>`,
|
||||
`<style>${katexCss}</style>`,
|
||||
`<style>${PRINT_CSS}</style>`,
|
||||
'</head>',
|
||||
`<body>${clone.innerHTML}</body>`,
|
||||
|
||||
@@ -36,6 +36,8 @@ export const strings = {
|
||||
insertTable: '插入表格',
|
||||
insertImage: '插入图片',
|
||||
insertHr: '分隔线',
|
||||
insertMath: '公式',
|
||||
mathPlaceholder: '输入 LaTeX 公式,如 E = mc^2',
|
||||
slashNoResults: '无匹配项',
|
||||
fmProperties: '属性',
|
||||
codeCopy: '复制',
|
||||
@@ -142,6 +144,8 @@ export const strings = {
|
||||
insertTable: 'Insert table',
|
||||
insertImage: 'Insert image',
|
||||
insertHr: 'Divider',
|
||||
insertMath: 'Formula',
|
||||
mathPlaceholder: 'Enter LaTeX, e.g. E = mc^2',
|
||||
slashNoResults: 'No results',
|
||||
fmProperties: 'Properties',
|
||||
codeCopy: 'Copy',
|
||||
@@ -250,6 +254,8 @@ export const strings = {
|
||||
insertTable: '表を挿入',
|
||||
insertImage: '画像を挿入',
|
||||
insertHr: '区切り線',
|
||||
insertMath: '数式',
|
||||
mathPlaceholder: 'LaTeX を入力(例:E = mc^2)',
|
||||
slashNoResults: '該当なし',
|
||||
fmProperties: 'プロパティ',
|
||||
codeCopy: 'コピー',
|
||||
@@ -358,6 +364,8 @@ export const strings = {
|
||||
insertTable: '표 삽입',
|
||||
insertImage: '이미지 삽입',
|
||||
insertHr: '구분선',
|
||||
insertMath: '수식',
|
||||
mathPlaceholder: 'LaTeX 입력 (예: E = mc^2)',
|
||||
slashNoResults: '결과 없음',
|
||||
fmProperties: '속성',
|
||||
codeCopy: '복사',
|
||||
@@ -467,6 +475,8 @@ export const strings = {
|
||||
insertTable: 'Insérer un tableau',
|
||||
insertImage: 'Insérer une image',
|
||||
insertHr: 'Séparateur',
|
||||
insertMath: 'Formule',
|
||||
mathPlaceholder: 'Saisir du LaTeX, ex. E = mc^2',
|
||||
slashNoResults: 'Aucun résultat',
|
||||
fmProperties: 'Propriétés',
|
||||
codeCopy: 'Copier',
|
||||
@@ -577,6 +587,8 @@ export const strings = {
|
||||
insertTable: 'Tabelle einfügen',
|
||||
insertImage: 'Bild einfügen',
|
||||
insertHr: 'Trennlinie',
|
||||
insertMath: 'Formel',
|
||||
mathPlaceholder: 'LaTeX eingeben, z. B. E = mc^2',
|
||||
slashNoResults: 'Keine Treffer',
|
||||
fmProperties: 'Eigenschaften',
|
||||
codeCopy: 'Kopieren',
|
||||
@@ -685,6 +697,8 @@ export const strings = {
|
||||
insertTable: 'Insertar tabla',
|
||||
insertImage: 'Insertar imagen',
|
||||
insertHr: 'Separador',
|
||||
insertMath: 'Fórmula',
|
||||
mathPlaceholder: 'Escribe LaTeX, p. ej. E = mc^2',
|
||||
slashNoResults: 'Sin resultados',
|
||||
fmProperties: 'Propiedades',
|
||||
codeCopy: 'Copiar',
|
||||
@@ -794,6 +808,8 @@ export const strings = {
|
||||
insertTable: 'แทรกตาราง',
|
||||
insertImage: 'แทรกรูปภาพ',
|
||||
insertHr: 'เส้นแบ่ง',
|
||||
insertMath: 'สูตร',
|
||||
mathPlaceholder: 'ป้อน LaTeX เช่น E = mc^2',
|
||||
slashNoResults: 'ไม่พบรายการ',
|
||||
fmProperties: 'คุณสมบัติ',
|
||||
codeCopy: 'คัดลอก',
|
||||
@@ -902,6 +918,8 @@ export const strings = {
|
||||
insertTable: 'Sisipkan tabel',
|
||||
insertImage: 'Sisipkan gambar',
|
||||
insertHr: 'Pembatas',
|
||||
insertMath: 'Rumus',
|
||||
mathPlaceholder: 'Masukkan LaTeX, mis. E = mc^2',
|
||||
slashNoResults: 'Tidak ada hasil',
|
||||
fmProperties: 'Properti',
|
||||
codeCopy: 'Salin',
|
||||
@@ -1010,6 +1028,8 @@ export const strings = {
|
||||
insertTable: 'Вставить таблицу',
|
||||
insertImage: 'Вставить изображение',
|
||||
insertHr: 'Разделитель',
|
||||
insertMath: 'Формула',
|
||||
mathPlaceholder: 'Введите LaTeX, напр. E = mc^2',
|
||||
slashNoResults: 'Нет результатов',
|
||||
fmProperties: 'Свойства',
|
||||
codeCopy: 'Копировать',
|
||||
@@ -1118,6 +1138,8 @@ export const strings = {
|
||||
insertTable: 'إدراج جدول',
|
||||
insertImage: 'إدراج صورة',
|
||||
insertHr: 'فاصل',
|
||||
insertMath: 'معادلة',
|
||||
mathPlaceholder: 'أدخل LaTeX، مثل E = mc^2',
|
||||
slashNoResults: 'لا نتائج',
|
||||
fmProperties: 'خصائص',
|
||||
codeCopy: 'نسخ',
|
||||
@@ -1226,6 +1248,8 @@ export const strings = {
|
||||
insertTable: 'Inserir tabela',
|
||||
insertImage: 'Inserir imagem',
|
||||
insertHr: 'Divisor',
|
||||
insertMath: 'Fórmula',
|
||||
mathPlaceholder: 'Digite LaTeX, ex.: E = mc^2',
|
||||
slashNoResults: 'Sem resultados',
|
||||
fmProperties: 'Propriedades',
|
||||
codeCopy: 'Copiar',
|
||||
@@ -1334,6 +1358,8 @@ export const strings = {
|
||||
insertTable: 'Inserisci tabella',
|
||||
insertImage: 'Inserisci immagine',
|
||||
insertHr: 'Divisore',
|
||||
insertMath: 'Formula',
|
||||
mathPlaceholder: 'Inserisci LaTeX, es. E = mc^2',
|
||||
slashNoResults: 'Nessun risultato',
|
||||
fmProperties: 'Proprietà',
|
||||
codeCopy: 'Copia',
|
||||
@@ -1442,6 +1468,8 @@ export const strings = {
|
||||
insertTable: 'Wstaw tabelę',
|
||||
insertImage: 'Wstaw obraz',
|
||||
insertHr: 'Separator',
|
||||
insertMath: 'Wzór',
|
||||
mathPlaceholder: 'Wpisz LaTeX, np. E = mc^2',
|
||||
slashNoResults: 'Brak wyników',
|
||||
fmProperties: 'Właściwości',
|
||||
codeCopy: 'Kopiuj',
|
||||
@@ -1550,6 +1578,8 @@ export const strings = {
|
||||
insertTable: 'Tabel invoegen',
|
||||
insertImage: 'Afbeelding invoegen',
|
||||
insertHr: 'Scheidingslijn',
|
||||
insertMath: 'Formule',
|
||||
mathPlaceholder: 'Voer LaTeX in, bijv. E = mc^2',
|
||||
slashNoResults: 'Geen resultaten',
|
||||
fmProperties: 'Eigenschappen',
|
||||
codeCopy: 'Kopiëren',
|
||||
@@ -1658,6 +1688,8 @@ export const strings = {
|
||||
insertTable: 'Sisip jadual',
|
||||
insertImage: 'Sisip imej',
|
||||
insertHr: 'Pemisah',
|
||||
insertMath: 'Rumus',
|
||||
mathPlaceholder: 'Masukkan LaTeX, cth. E = mc^2',
|
||||
slashNoResults: 'Tiada hasil',
|
||||
fmProperties: 'Sifat',
|
||||
codeCopy: 'Salin',
|
||||
@@ -1766,6 +1798,8 @@ export const strings = {
|
||||
insertTable: 'הוספת טבלה',
|
||||
insertImage: 'הוספת תמונה',
|
||||
insertHr: 'קו מפריד',
|
||||
insertMath: 'נוסחה',
|
||||
mathPlaceholder: 'הזן LaTeX, למשל E = mc^2',
|
||||
slashNoResults: 'אין תוצאות',
|
||||
fmProperties: 'מאפיינים',
|
||||
codeCopy: 'העתק',
|
||||
@@ -1873,6 +1907,8 @@ export const strings = {
|
||||
insertTable: 'तालिका सम्मिलित करें',
|
||||
insertImage: 'छवि सम्मिलित करें',
|
||||
insertHr: 'विभाजक',
|
||||
insertMath: 'सूत्र',
|
||||
mathPlaceholder: 'LaTeX दर्ज करें, जैसे E = mc^2',
|
||||
slashNoResults: 'कोई परिणाम नहीं',
|
||||
fmProperties: 'गुण',
|
||||
codeCopy: 'कॉपी',
|
||||
@@ -1981,6 +2017,8 @@ export const strings = {
|
||||
insertTable: '插入表格',
|
||||
insertImage: '插入圖片',
|
||||
insertHr: '分隔線',
|
||||
insertMath: '公式',
|
||||
mathPlaceholder: '輸入 LaTeX 公式,如 E = mc^2',
|
||||
slashNoResults: '無符合項目',
|
||||
fmProperties: '屬性',
|
||||
codeCopy: '複製',
|
||||
|
||||
@@ -5,6 +5,7 @@ import { LocaleProvider } from './i18n/locale'
|
||||
import type { UiTheme } from '../shared/ipc'
|
||||
import '@genoffice/ui/tokens.css'
|
||||
import '@genoffice/ui/screentip.css'
|
||||
import 'katex/dist/katex.min.css'
|
||||
import './styles.css'
|
||||
import { installScreenTips } from '@genoffice/ui'
|
||||
|
||||
|
||||
@@ -2170,3 +2170,120 @@ html.genoffice-popover-open .ribbon-tabs {
|
||||
.md-block-menu-item.danger:hover {
|
||||
background: var(--danger-bg);
|
||||
}
|
||||
|
||||
/* ---- math (KaTeX) nodes & LaTeX edit popover ---- */
|
||||
|
||||
.tiptap-mathematics-render {
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
span.tiptap-mathematics-render {
|
||||
display: inline-block;
|
||||
padding: 0 2px;
|
||||
}
|
||||
|
||||
div.tiptap-mathematics-render {
|
||||
padding: 8px 12px;
|
||||
margin: 0.5em 0;
|
||||
text-align: center;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.tiptap-mathematics-render--editable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.tiptap-mathematics-render--editable:hover {
|
||||
background: var(--hover);
|
||||
}
|
||||
|
||||
.tiptap-mathematics-render.ProseMirror-selectednode {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
/* KaTeX parse failure: show the raw source in the code font */
|
||||
.tiptap-mathematics-render.block-math-error,
|
||||
.tiptap-mathematics-render.inline-math-error {
|
||||
color: var(--danger);
|
||||
font-family: 'SF Mono', Menlo, Consolas, monospace;
|
||||
font-size: 0.85em;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.md-math-pop {
|
||||
position: fixed;
|
||||
z-index: 40;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
width: 400px;
|
||||
padding: 10px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 10px 32px var(--md-shadow-color);
|
||||
}
|
||||
|
||||
.md-math-input {
|
||||
resize: vertical;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 6px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
padding: 6px 8px;
|
||||
font-family: 'SF Mono', Menlo, Consolas, monospace;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.md-math-input:focus {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.md-math-preview {
|
||||
display: flex;
|
||||
/* `safe` keeps the start edge reachable when a tall formula scrolls */
|
||||
align-items: safe center;
|
||||
justify-content: safe center;
|
||||
min-height: 36px;
|
||||
max-height: 40vh;
|
||||
padding: 6px 8px;
|
||||
border-radius: 6px;
|
||||
background: var(--hover);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.md-math-preview-empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.md-math-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.md-math-actions button {
|
||||
height: 26px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
font-size: 12.5px;
|
||||
padding: 0 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.md-math-apply {
|
||||
background: var(--color-btn-primary);
|
||||
color: var(--color-btn-primary-text);
|
||||
}
|
||||
|
||||
.md-math-delete {
|
||||
background: transparent;
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.md-math-delete:hover {
|
||||
background: var(--danger-bg);
|
||||
}
|
||||
|
||||
@@ -31,6 +31,8 @@ export type SaveMode = 'save' | 'saveAs'
|
||||
export interface SaveMarkdownRequest {
|
||||
/** full document text (frontmatter included) */
|
||||
text: string
|
||||
/** Authored image paths in document order; the main process validates every path. */
|
||||
imageSources: string[]
|
||||
mode: SaveMode
|
||||
/**
|
||||
* Silent first save for an untitled document (AI auto-naming): saves to a
|
||||
@@ -41,7 +43,14 @@ export interface SaveMarkdownRequest {
|
||||
}
|
||||
|
||||
export type SaveMarkdownResult =
|
||||
{ ok: true; path: string } | { ok: true; canceled: true } | { ok: false; error: string }
|
||||
| {
|
||||
ok: true
|
||||
path: string
|
||||
/** Save As may relocate local images into the new document's assets directory. */
|
||||
imageRewrites?: Array<{ from: string; to: string }>
|
||||
}
|
||||
| { ok: true; canceled: true }
|
||||
| { ok: false; error: string }
|
||||
|
||||
/** AI channels are app-wide shared ipcMain handlers (shell registers via docs-main registerAiIpc); pass-through only */
|
||||
export const AI_CHANNELS = {
|
||||
@@ -64,7 +73,7 @@ export interface ExportDocxRequest {
|
||||
base64: string
|
||||
/** file name (no extension) suggested in the dialog / used for the silent convert */
|
||||
suggestedName: string
|
||||
/** 'dialog' = save dialog; 'openInDocs' = silent save next to the .md, then open in AI Docs */
|
||||
/** 'dialog' = save dialog; 'openInDocs' = app-managed temporary copy opened in AI Docs */
|
||||
mode: 'dialog' | 'openInDocs'
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,490 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
discardPendingOwnedAssets,
|
||||
extractMarkdownImageSources,
|
||||
prepareAssetsForSaveAs,
|
||||
readOwnedAssetManifest,
|
||||
reconcileOwnedAssets,
|
||||
rewriteMarkdownImageSources,
|
||||
rollbackPreparedSaveAsAssets,
|
||||
writeImageIntoOwnedAssets,
|
||||
} from '../src/main/asset-lifecycle'
|
||||
|
||||
const tempDirectories: string[] = []
|
||||
|
||||
async function temporaryDirectory(prefix: string): Promise<string> {
|
||||
const directory = await mkdtemp(join(tmpdir(), prefix))
|
||||
tempDirectories.push(directory)
|
||||
return directory
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
tempDirectories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })),
|
||||
)
|
||||
})
|
||||
|
||||
describe('Markdown owned asset lifecycle', () => {
|
||||
it("deletes only pending owned files when edits are explicitly discarded with Don't Save", async () => {
|
||||
const directory = await temporaryDirectory('markdown-assets-discard-')
|
||||
const documentPath = join(directory, 'note.md')
|
||||
const authored = await writeImageIntoOwnedAssets(
|
||||
documentPath,
|
||||
'pending.png',
|
||||
Buffer.from('pending image'),
|
||||
)
|
||||
|
||||
const result = await discardPendingOwnedAssets(documentPath)
|
||||
|
||||
expect(result.errors).toEqual([])
|
||||
expect(result.deleted).toEqual(['pending.png'])
|
||||
expect(existsSync(join(directory, authored))).toBe(false)
|
||||
expect(await readOwnedAssetManifest(documentPath)).toMatchObject({
|
||||
files: [],
|
||||
pending: {},
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves saved references and relinquishes modified pending files instead of deleting them', async () => {
|
||||
const directory = await temporaryDirectory('markdown-assets-discard-safe-')
|
||||
const documentPath = join(directory, 'note.md')
|
||||
const saved = await writeImageIntoOwnedAssets(
|
||||
documentPath,
|
||||
'saved.png',
|
||||
Buffer.from('saved image'),
|
||||
)
|
||||
await reconcileOwnedAssets(documentPath, [saved])
|
||||
const modified = await writeImageIntoOwnedAssets(
|
||||
documentPath,
|
||||
'modified.png',
|
||||
Buffer.from('original pending image'),
|
||||
)
|
||||
await writeFile(join(directory, modified), 'user modified image')
|
||||
|
||||
const result = await discardPendingOwnedAssets(documentPath)
|
||||
|
||||
expect(result.deleted).toEqual([])
|
||||
expect(result.preserved).toEqual(['modified.png'])
|
||||
expect(await readFile(join(directory, saved), 'utf8')).toBe('saved image')
|
||||
expect(await readFile(join(directory, modified), 'utf8')).toBe('user modified image')
|
||||
expect((await readOwnedAssetManifest(documentPath))?.files.map((file) => file.name)).toEqual([
|
||||
'saved.png',
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps a deleted insertion undoable until save, then collects it', async () => {
|
||||
const directory = await temporaryDirectory('markdown-assets-gc-')
|
||||
const documentPath = join(directory, 'note.md')
|
||||
const authored = await writeImageIntoOwnedAssets(
|
||||
documentPath,
|
||||
'pasted.png',
|
||||
Buffer.from('image bytes'),
|
||||
)
|
||||
const assetPath = join(directory, authored)
|
||||
|
||||
expect(existsSync(assetPath)).toBe(true)
|
||||
// Deleting the image node changes only editor state. The on-disk file stays
|
||||
// available if the user invokes Undo before saving.
|
||||
expect(existsSync(assetPath)).toBe(true)
|
||||
|
||||
const result = await reconcileOwnedAssets(documentPath, [])
|
||||
expect(result.errors).toEqual([])
|
||||
expect(result.deleted).toEqual(['pasted.png'])
|
||||
expect(existsSync(assetPath)).toBe(false)
|
||||
expect((await readOwnedAssetManifest(documentPath))?.files).toEqual([])
|
||||
})
|
||||
|
||||
it('deduplicates repeated references and protects assets shared by saved sibling documents', async () => {
|
||||
const directory = await temporaryDirectory('markdown-assets-shared-')
|
||||
const firstDocument = join(directory, 'first.md')
|
||||
const secondDocument = join(directory, 'second.md')
|
||||
const authored = await writeImageIntoOwnedAssets(
|
||||
firstDocument,
|
||||
'shared.png',
|
||||
Buffer.from('shared image'),
|
||||
)
|
||||
const assetPath = join(directory, authored)
|
||||
|
||||
// A save in a sibling document must not collect first.md's still-undoable insertion.
|
||||
await reconcileOwnedAssets(secondDocument, [])
|
||||
expect(existsSync(assetPath)).toBe(true)
|
||||
|
||||
await reconcileOwnedAssets(firstDocument, [authored, authored])
|
||||
await reconcileOwnedAssets(secondDocument, [authored])
|
||||
await reconcileOwnedAssets(firstDocument, [])
|
||||
expect(existsSync(assetPath)).toBe(true)
|
||||
|
||||
await reconcileOwnedAssets(secondDocument, [authored])
|
||||
expect(existsSync(assetPath)).toBe(true)
|
||||
await reconcileOwnedAssets(secondDocument, [])
|
||||
expect(existsSync(assetPath)).toBe(false)
|
||||
})
|
||||
|
||||
it('conservatively preserves an owned asset referenced by a sibling Markdown file', async () => {
|
||||
const directory = await temporaryDirectory('markdown-assets-sibling-')
|
||||
const documentPath = join(directory, 'owner.md')
|
||||
const siblingPath = join(directory, 'sibling.md')
|
||||
const authored = await writeImageIntoOwnedAssets(
|
||||
documentPath,
|
||||
'shared.png',
|
||||
Buffer.from('shared image'),
|
||||
)
|
||||
const assetPath = join(directory, authored)
|
||||
await writeFile(siblingPath, ``)
|
||||
|
||||
await reconcileOwnedAssets(documentPath, [])
|
||||
expect(existsSync(assetPath)).toBe(true)
|
||||
|
||||
await writeFile(siblingPath, '# No image now')
|
||||
await reconcileOwnedAssets(documentPath, [])
|
||||
expect(existsSync(assetPath)).toBe(false)
|
||||
})
|
||||
|
||||
it('preserves an HTML-only sibling reference until that reference is removed', async () => {
|
||||
const directory = await temporaryDirectory('markdown-assets-html-sibling-')
|
||||
const documentPath = join(directory, 'owner.md')
|
||||
const siblingPath = join(directory, 'sibling.markdown')
|
||||
const authored = await writeImageIntoOwnedAssets(
|
||||
documentPath,
|
||||
'shared.png',
|
||||
Buffer.from('shared image'),
|
||||
)
|
||||
const assetPath = join(directory, authored)
|
||||
await writeFile(
|
||||
siblingPath,
|
||||
`<IMG data-src="ignored.png" SRC='assets/shared.png' srcset="ignored-2x.png 2x">`,
|
||||
)
|
||||
|
||||
await reconcileOwnedAssets(documentPath, [])
|
||||
expect(existsSync(assetPath)).toBe(true)
|
||||
|
||||
await writeFile(siblingPath, '<p>No image now</p>')
|
||||
await reconcileOwnedAssets(documentPath, [])
|
||||
expect(existsSync(assetPath)).toBe(false)
|
||||
})
|
||||
|
||||
it('retains owned assets when a sibling HTML image tag is malformed', async () => {
|
||||
const directory = await temporaryDirectory('markdown-assets-html-ambiguous-')
|
||||
const documentPath = join(directory, 'owner.md')
|
||||
const siblingPath = join(directory, 'sibling.md')
|
||||
const authored = await writeImageIntoOwnedAssets(
|
||||
documentPath,
|
||||
'shared.png',
|
||||
Buffer.from('shared image'),
|
||||
)
|
||||
await writeFile(siblingPath, '<img src="assets/shared.png>')
|
||||
|
||||
const result = await reconcileOwnedAssets(documentPath, [])
|
||||
|
||||
expect(result.deleted).toEqual([])
|
||||
expect(existsSync(join(directory, authored))).toBe(true)
|
||||
})
|
||||
|
||||
it('retains owned assets when a sibling HTML image tag has duplicate src attributes', async () => {
|
||||
const directory = await temporaryDirectory('markdown-assets-html-duplicate-src-')
|
||||
const documentPath = join(directory, 'owner.md')
|
||||
const siblingPath = join(directory, 'sibling.md')
|
||||
const authored = await writeImageIntoOwnedAssets(
|
||||
documentPath,
|
||||
'shared.png',
|
||||
Buffer.from('shared image'),
|
||||
)
|
||||
await writeFile(siblingPath, `<img src="${authored}" SRC="assets/other.png">`)
|
||||
|
||||
const result = await reconcileOwnedAssets(documentPath, [])
|
||||
|
||||
expect(result.deleted).toEqual([])
|
||||
expect(existsSync(join(directory, authored))).toBe(true)
|
||||
})
|
||||
|
||||
it('never deletes untracked or user-modified files', async () => {
|
||||
const directory = await temporaryDirectory('markdown-assets-user-')
|
||||
const documentPath = join(directory, 'note.md')
|
||||
const owned = await writeImageIntoOwnedAssets(
|
||||
documentPath,
|
||||
'owned.png',
|
||||
Buffer.from('original'),
|
||||
)
|
||||
const assetsDirectory = join(directory, 'assets')
|
||||
const manualPath = join(assetsDirectory, 'manual.png')
|
||||
await writeFile(manualPath, 'manual')
|
||||
await writeFile(join(directory, owned), 'user replaced this file')
|
||||
|
||||
await reconcileOwnedAssets(documentPath, [])
|
||||
|
||||
expect(await readFile(manualPath, 'utf8')).toBe('manual')
|
||||
expect(await readFile(join(directory, owned), 'utf8')).toBe('user replaced this file')
|
||||
expect((await readOwnedAssetManifest(documentPath))?.files).toEqual([])
|
||||
})
|
||||
|
||||
it('copies every safe local image on Save As without touching the old document assets', async () => {
|
||||
const sourceDirectory = await temporaryDirectory('markdown-assets-source-')
|
||||
const targetDirectory = await temporaryDirectory('markdown-assets-target-')
|
||||
const sourceDocument = join(sourceDirectory, 'source.md')
|
||||
const targetDocument = join(targetDirectory, 'copy.md')
|
||||
const owned = await writeImageIntoOwnedAssets(
|
||||
sourceDocument,
|
||||
'owned.png',
|
||||
Buffer.from('owned source'),
|
||||
)
|
||||
await mkdir(join(sourceDirectory, 'images'))
|
||||
await writeFile(join(sourceDirectory, 'images', 'manual.png'), 'manual source')
|
||||
|
||||
// A different user-managed file at the preferred destination must not be overwritten.
|
||||
await mkdir(join(targetDirectory, 'assets'))
|
||||
await writeFile(join(targetDirectory, 'assets', 'owned.png'), 'target user file')
|
||||
const text = [
|
||||
``,
|
||||
'',
|
||||
``,
|
||||
'',
|
||||
].join('\n')
|
||||
const imageSources = [owned, 'images/manual.png', owned, '../outside.png']
|
||||
|
||||
const prepared = await prepareAssetsForSaveAs(
|
||||
sourceDocument,
|
||||
targetDocument,
|
||||
text,
|
||||
imageSources,
|
||||
)
|
||||
await writeFile(targetDocument, prepared.text)
|
||||
await reconcileOwnedAssets(targetDocument, prepared.imageSources)
|
||||
|
||||
expect(prepared.rewrites).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ from: owned, to: 'assets/owned-1.png' },
|
||||
{ from: 'images/manual.png', to: 'assets/manual.png' },
|
||||
]),
|
||||
)
|
||||
expect(prepared.text).toContain('')
|
||||
expect(prepared.text).toContain('')
|
||||
expect(prepared.text).toContain('')
|
||||
expect(prepared.text).toContain('')
|
||||
expect(await readFile(join(targetDirectory, 'assets', 'owned.png'), 'utf8')).toBe(
|
||||
'target user file',
|
||||
)
|
||||
expect(await readFile(join(targetDirectory, 'assets', 'owned-1.png'), 'utf8')).toBe(
|
||||
'owned source',
|
||||
)
|
||||
expect(await readFile(join(targetDirectory, 'assets', 'manual.png'), 'utf8')).toBe(
|
||||
'manual source',
|
||||
)
|
||||
expect(await readFile(join(sourceDirectory, owned), 'utf8')).toBe('owned source')
|
||||
expect(await readFile(join(sourceDirectory, 'images', 'manual.png'), 'utf8')).toBe(
|
||||
'manual source',
|
||||
)
|
||||
expect((await readOwnedAssetManifest(targetDocument))?.files.map((file) => file.name)).toEqual([
|
||||
'manual.png',
|
||||
'owned-1.png',
|
||||
])
|
||||
})
|
||||
|
||||
it('copies and rewrites raw HTML image sources on Save As', async () => {
|
||||
const sourceDirectory = await temporaryDirectory('markdown-assets-html-source-')
|
||||
const targetDirectory = await temporaryDirectory('markdown-assets-html-target-')
|
||||
const sourceDocument = join(sourceDirectory, 'source.md')
|
||||
const targetDocument = join(targetDirectory, 'copy.md')
|
||||
await mkdir(join(sourceDirectory, 'images'))
|
||||
await writeFile(join(sourceDirectory, 'images', 'html.png'), 'html image')
|
||||
const text =
|
||||
`<figure data-kind="keep"><IMG alt="preview" SRC='images/html.png'></figure>\n` +
|
||||
'<img src=images/html.png />'
|
||||
|
||||
const prepared = await prepareAssetsForSaveAs(sourceDocument, targetDocument, text, [])
|
||||
|
||||
expect(prepared.rewrites).toEqual([{ from: 'images/html.png', to: 'assets/html.png' }])
|
||||
expect(prepared.text).toBe(
|
||||
`<figure data-kind="keep"><IMG alt="preview" SRC='assets/html.png'></figure>\n` +
|
||||
'<img src=assets/html.png />',
|
||||
)
|
||||
expect(prepared.imageSources).toEqual(['assets/html.png'])
|
||||
expect(await readFile(join(targetDirectory, 'assets', 'html.png'), 'utf8')).toBe('html image')
|
||||
})
|
||||
|
||||
it('rejects traversal image sources during Save As', async () => {
|
||||
const root = await temporaryDirectory('markdown-assets-traversal-')
|
||||
const sourceDirectory = join(root, 'source')
|
||||
const targetDirectory = join(root, 'target')
|
||||
await mkdir(sourceDirectory)
|
||||
await mkdir(targetDirectory)
|
||||
await writeFile(join(root, 'outside.png'), 'outside image')
|
||||
const sourceDocument = join(sourceDirectory, 'source.md')
|
||||
const targetDocument = join(targetDirectory, 'copy.md')
|
||||
const text = '<img src="../outside.png">'
|
||||
|
||||
const prepared = await prepareAssetsForSaveAs(sourceDocument, targetDocument, text, [])
|
||||
|
||||
expect(prepared.rewrites).toEqual([])
|
||||
expect(prepared.created).toEqual([])
|
||||
expect(prepared.text).toBe(text)
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'rejects image symlinks that escape the source document directory',
|
||||
async () => {
|
||||
const root = await temporaryDirectory('markdown-assets-symlink-')
|
||||
const sourceDirectory = join(root, 'source')
|
||||
const targetDirectory = join(root, 'target')
|
||||
await mkdir(sourceDirectory)
|
||||
await mkdir(targetDirectory)
|
||||
const outsidePath = join(root, 'outside.png')
|
||||
await writeFile(outsidePath, 'outside image')
|
||||
await symlink(outsidePath, join(sourceDirectory, 'linked.png'))
|
||||
const sourceDocument = join(sourceDirectory, 'source.md')
|
||||
const targetDocument = join(targetDirectory, 'copy.md')
|
||||
const text = '<img src="linked.png">'
|
||||
|
||||
const prepared = await prepareAssetsForSaveAs(sourceDocument, targetDocument, text, [])
|
||||
|
||||
expect(prepared.rewrites).toEqual([])
|
||||
expect(prepared.created).toEqual([])
|
||||
expect(prepared.text).toBe(text)
|
||||
},
|
||||
)
|
||||
|
||||
it('persists pending ownership removal when rollback cannot delete a shared copied file', async () => {
|
||||
const sourceDirectory = await temporaryDirectory('markdown-assets-rollback-source-')
|
||||
const targetDirectory = await temporaryDirectory('markdown-assets-rollback-target-')
|
||||
const sourceDocument = join(sourceDirectory, 'source.md')
|
||||
const targetDocument = join(targetDirectory, 'copy.md')
|
||||
await writeFile(sourceDocument, '# Source')
|
||||
await writeFile(join(sourceDirectory, 'local.png'), 'source image')
|
||||
const prepared = await prepareAssetsForSaveAs(
|
||||
sourceDocument,
|
||||
targetDocument,
|
||||
'',
|
||||
['local.png'],
|
||||
)
|
||||
const copied = prepared.imageSources[0]!
|
||||
const siblingDocument = join(targetDirectory, 'sibling.md')
|
||||
await writeFile(siblingDocument, ``)
|
||||
await reconcileOwnedAssets(siblingDocument, [copied])
|
||||
|
||||
await rollbackPreparedSaveAsAssets(prepared)
|
||||
|
||||
expect(existsSync(join(targetDirectory, copied))).toBe(true)
|
||||
expect(await readOwnedAssetManifest(targetDocument)).toMatchObject({
|
||||
files: [{ name: 'local.png' }],
|
||||
documents: { 'sibling.md': ['local.png'] },
|
||||
pending: {},
|
||||
})
|
||||
})
|
||||
|
||||
it('persists pending ownership removal when a copied file fails hash validation', async () => {
|
||||
const sourceDirectory = await temporaryDirectory('markdown-assets-hash-source-')
|
||||
const targetDirectory = await temporaryDirectory('markdown-assets-hash-target-')
|
||||
const sourceDocument = join(sourceDirectory, 'source.md')
|
||||
const targetDocument = join(targetDirectory, 'copy.md')
|
||||
await writeFile(sourceDocument, '# Source')
|
||||
await writeFile(join(sourceDirectory, 'local.png'), 'source image')
|
||||
const prepared = await prepareAssetsForSaveAs(
|
||||
sourceDocument,
|
||||
targetDocument,
|
||||
'',
|
||||
['local.png'],
|
||||
)
|
||||
const copied = prepared.imageSources[0]!
|
||||
await writeFile(join(targetDirectory, copied), 'user changed the copied file')
|
||||
|
||||
await rollbackPreparedSaveAsAssets(prepared)
|
||||
|
||||
expect(await readFile(join(targetDirectory, copied), 'utf8')).toBe(
|
||||
'user changed the copied file',
|
||||
)
|
||||
expect(await readOwnedAssetManifest(targetDocument)).toMatchObject({
|
||||
files: [{ name: 'local.png' }],
|
||||
pending: {},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('serialized Markdown image references', () => {
|
||||
it('extracts destinations with titles and duplicate references', () => {
|
||||
expect(
|
||||
extractMarkdownImageSources(
|
||||
'\n\n',
|
||||
),
|
||||
).toEqual(['assets/a.png', 'assets/b image.png', 'assets/a.png'])
|
||||
})
|
||||
|
||||
it('extracts and rewrites mixed Markdown and HTML image sources without touching lookalikes', () => {
|
||||
const text = [
|
||||
'',
|
||||
'<IMG data-src="ignored.png" SRC = "assets/b&c.png" srcset="ignored-2x.png 2x">',
|
||||
"<img class=x src='assets/c.png'>",
|
||||
'<img src=assets/d.png />',
|
||||
].join('\n')
|
||||
const rewritten = rewriteMarkdownImageSources(
|
||||
text,
|
||||
new Map([
|
||||
['assets/a.png', 'assets/a-new.png'],
|
||||
['assets/b&c.png', 'assets/b&new.png'],
|
||||
['assets/c.png', "assets/c's.png"],
|
||||
['assets/d.png', 'assets/d new.png'],
|
||||
['ignored.png', 'assets/must-not-change.png'],
|
||||
]),
|
||||
)
|
||||
|
||||
expect(extractMarkdownImageSources(text)).toEqual([
|
||||
'assets/a.png',
|
||||
'assets/b&c.png',
|
||||
'assets/c.png',
|
||||
'assets/d.png',
|
||||
])
|
||||
expect(rewritten).toBe(
|
||||
[
|
||||
'',
|
||||
'<IMG data-src="ignored.png" SRC = "assets/b&new.png" srcset="ignored-2x.png 2x">',
|
||||
"<img class=x src='assets/c's.png'>",
|
||||
'<img src=assets/d new.png />',
|
||||
].join('\n'),
|
||||
)
|
||||
expect(extractMarkdownImageSources(rewritten)).toEqual([
|
||||
'assets/a-new.png',
|
||||
'assets/b&new.png',
|
||||
"assets/c's.png",
|
||||
'assets/d new.png',
|
||||
])
|
||||
})
|
||||
|
||||
it('does not treat image examples inside Markdown code as rendered assets', () => {
|
||||
const text = [
|
||||
'`<img src="assets/inline.png">`',
|
||||
'```html',
|
||||
'<img src="assets/fenced.png">',
|
||||
'```',
|
||||
'~~~markdown',
|
||||
'',
|
||||
'~~~',
|
||||
' <img src="assets/indented.png">',
|
||||
'<img src="assets/rendered.png">',
|
||||
'',
|
||||
].join('\n')
|
||||
const rewritten = rewriteMarkdownImageSources(
|
||||
text,
|
||||
new Map([
|
||||
['assets/inline.png', 'assets/inline-new.png'],
|
||||
['assets/fenced.png', 'assets/fenced-new.png'],
|
||||
['assets/fenced-markdown.png', 'assets/fenced-markdown-new.png'],
|
||||
['assets/indented.png', 'assets/indented-new.png'],
|
||||
['assets/rendered.png', 'assets/rendered-new.png'],
|
||||
['assets/rendered-markdown.png', 'assets/rendered-markdown-new.png'],
|
||||
]),
|
||||
)
|
||||
|
||||
expect(extractMarkdownImageSources(text)).toEqual([
|
||||
'assets/rendered.png',
|
||||
'assets/rendered-markdown.png',
|
||||
])
|
||||
expect(rewritten).toContain('`<img src="assets/inline.png">`')
|
||||
expect(rewritten).toContain('<img src="assets/fenced.png">')
|
||||
expect(rewritten).toContain('')
|
||||
expect(rewritten).toContain(' <img src="assets/indented.png">')
|
||||
expect(rewritten).toContain('<img src="assets/rendered-new.png">')
|
||||
expect(rewritten).toContain('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,395 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
type IpcHandler = (event: { sender: FakeWebContents }, ...args: unknown[]) => unknown
|
||||
|
||||
interface FakeWebContents {
|
||||
id: number
|
||||
listeners: Map<string, () => void>
|
||||
isDestroyed: ReturnType<typeof vi.fn>
|
||||
loadFile: ReturnType<typeof vi.fn>
|
||||
loadURL: ReturnType<typeof vi.fn>
|
||||
once: ReturnType<typeof vi.fn>
|
||||
send: ReturnType<typeof vi.fn>
|
||||
setWindowOpenHandler: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
const handlers = new Map<string, IpcHandler>()
|
||||
const showMessageBox = vi.fn()
|
||||
const showSaveDialogWithMemory = vi.fn()
|
||||
const webContents: FakeWebContents[] = []
|
||||
let nextWebContentsId = 1
|
||||
|
||||
function makeWebContents(): FakeWebContents {
|
||||
const listeners = new Map<string, () => void>()
|
||||
const contents: FakeWebContents = {
|
||||
id: nextWebContentsId++,
|
||||
listeners,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
loadFile: vi.fn(),
|
||||
loadURL: vi.fn(),
|
||||
once: vi.fn((event: string, listener: () => void) => listeners.set(event, listener)),
|
||||
send: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
}
|
||||
webContents.push(contents)
|
||||
return contents
|
||||
}
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: {
|
||||
getPath: vi.fn(() => tmpdir()),
|
||||
on: vi.fn(),
|
||||
quit: vi.fn(),
|
||||
whenReady: vi.fn(() => new Promise(() => {})),
|
||||
},
|
||||
BrowserWindow: class {
|
||||
static fromWebContents() {
|
||||
return null
|
||||
}
|
||||
static getFocusedWindow() {
|
||||
return null
|
||||
}
|
||||
},
|
||||
dialog: {
|
||||
showMessageBox: (...args: unknown[]) => showMessageBox(...args),
|
||||
},
|
||||
ipcMain: {
|
||||
handle: vi.fn((channel: string, handler: IpcHandler) => handlers.set(channel, handler)),
|
||||
on: vi.fn((channel: string, handler: IpcHandler) => handlers.set(channel, handler)),
|
||||
removeHandler: vi.fn(),
|
||||
},
|
||||
net: { fetch: vi.fn() },
|
||||
protocol: { handle: vi.fn() },
|
||||
shell: { openExternal: vi.fn() },
|
||||
WebContentsView: class {
|
||||
webContents = makeWebContents()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@genoffice/electron-utils', () => ({
|
||||
configuredDefaultSaveDir: vi.fn(() => tmpdir()),
|
||||
contextMenuLabels: vi.fn(() => ({})),
|
||||
installContextMenu: vi.fn(),
|
||||
installNavigationGuard: vi.fn(),
|
||||
safeExternalUrl: vi.fn(() => null),
|
||||
showOpenDialogWithMemory: vi.fn(),
|
||||
showSaveDialogWithMemory: (...args: unknown[]) => showSaveDialogWithMemory(...args),
|
||||
}))
|
||||
|
||||
import {
|
||||
readOwnedAssetManifest,
|
||||
reconcileOwnedAssets,
|
||||
writeImageIntoOwnedAssets,
|
||||
} from '../src/main/asset-lifecycle'
|
||||
import { createMarkdownView, requestMarkdownClose } from '../src/main/markdown-main'
|
||||
import { MARKDOWN_CHANNELS } from '../src/shared/ipc'
|
||||
|
||||
const temporaryDirectories: string[] = []
|
||||
|
||||
async function createDocument(): Promise<string> {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'markdown-close-assets-'))
|
||||
temporaryDirectories.push(directory)
|
||||
const documentPath = join(directory, 'note.md')
|
||||
await writeFile(documentPath, '# Saved document')
|
||||
return documentPath
|
||||
}
|
||||
|
||||
function markDirty(contents: FakeWebContents): void {
|
||||
handlers.get(MARKDOWN_CHANNELS.dirtyChanged)?.({ sender: contents }, true)
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks()
|
||||
showMessageBox.mockReset()
|
||||
showSaveDialogWithMemory.mockReset()
|
||||
for (const contents of webContents.splice(0)) contents.listeners.get('destroyed')?.()
|
||||
await Promise.all(
|
||||
temporaryDirectories
|
||||
.splice(0)
|
||||
.map((directory) => rm(directory, { recursive: true, force: true })),
|
||||
)
|
||||
})
|
||||
|
||||
describe('requestMarkdownClose asset cleanup', () => {
|
||||
it("deletes pending owned assets on Don't Save while preserving saved assets", async () => {
|
||||
const documentPath = await createDocument()
|
||||
const saved = await writeImageIntoOwnedAssets(
|
||||
documentPath,
|
||||
'saved.png',
|
||||
Buffer.from('saved image'),
|
||||
)
|
||||
await reconcileOwnedAssets(documentPath, [saved])
|
||||
const pending = await writeImageIntoOwnedAssets(
|
||||
documentPath,
|
||||
'pending.png',
|
||||
Buffer.from('pending image'),
|
||||
)
|
||||
const view = createMarkdownView(documentPath)
|
||||
const contents = view.webContents as unknown as FakeWebContents
|
||||
markDirty(contents)
|
||||
showMessageBox.mockResolvedValue({ response: 1 })
|
||||
|
||||
await expect(requestMarkdownClose(contents as never)).resolves.toBe(true)
|
||||
|
||||
expect(existsSync(join(dirname(documentPath), saved))).toBe(true)
|
||||
expect(existsSync(join(dirname(documentPath), pending))).toBe(false)
|
||||
expect(await readOwnedAssetManifest(documentPath)).toMatchObject({
|
||||
files: [{ name: 'saved.png' }],
|
||||
pending: {},
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves pending owned assets when close is canceled', async () => {
|
||||
const documentPath = await createDocument()
|
||||
const pending = await writeImageIntoOwnedAssets(
|
||||
documentPath,
|
||||
'pending.png',
|
||||
Buffer.from('pending image'),
|
||||
)
|
||||
const view = createMarkdownView(documentPath)
|
||||
const contents = view.webContents as unknown as FakeWebContents
|
||||
markDirty(contents)
|
||||
showMessageBox.mockResolvedValue({ response: 2 })
|
||||
|
||||
await expect(requestMarkdownClose(contents as never)).resolves.toBe(false)
|
||||
|
||||
expect(existsSync(join(dirname(documentPath), pending))).toBe(true)
|
||||
expect(await readOwnedAssetManifest(documentPath)).toMatchObject({
|
||||
files: [{ name: 'pending.png' }],
|
||||
pending: { 'note.md': ['pending.png'] },
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves referenced assets when the user successfully saves before closing', async () => {
|
||||
const documentPath = await createDocument()
|
||||
const pending = await writeImageIntoOwnedAssets(
|
||||
documentPath,
|
||||
'pending.png',
|
||||
Buffer.from('pending image'),
|
||||
)
|
||||
const view = createMarkdownView(documentPath)
|
||||
const contents = view.webContents as unknown as FakeWebContents
|
||||
markDirty(contents)
|
||||
showMessageBox.mockResolvedValue({ response: 0 })
|
||||
|
||||
const closing = requestMarkdownClose(contents as never)
|
||||
await vi.waitFor(() =>
|
||||
expect(contents.send).toHaveBeenCalledWith(MARKDOWN_CHANNELS.closeSaveRequest),
|
||||
)
|
||||
const saveResult = await handlers.get(MARKDOWN_CHANNELS.save)?.(
|
||||
{ sender: contents },
|
||||
{
|
||||
text: ``,
|
||||
imageSources: [pending],
|
||||
mode: 'save',
|
||||
},
|
||||
)
|
||||
handlers.get(MARKDOWN_CHANNELS.closeSaveResult)?.({ sender: contents }, true)
|
||||
|
||||
await expect(closing).resolves.toBe(true)
|
||||
expect(saveResult).toMatchObject({ ok: true, path: documentPath })
|
||||
expect(existsSync(join(dirname(documentPath), pending))).toBe(true)
|
||||
expect(await readOwnedAssetManifest(documentPath)).toMatchObject({
|
||||
files: [{ name: 'pending.png' }],
|
||||
documents: { 'note.md': ['pending.png'] },
|
||||
pending: {},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('Save As source pending ownership', () => {
|
||||
it('clears the old document key for same-directory Save As without deleting new references', async () => {
|
||||
const sourcePath = await createDocument()
|
||||
const saved = await writeImageIntoOwnedAssets(
|
||||
sourcePath,
|
||||
'saved.png',
|
||||
Buffer.from('saved image'),
|
||||
)
|
||||
await reconcileOwnedAssets(sourcePath, [saved])
|
||||
await writeFile(sourcePath, ``)
|
||||
const pending = await writeImageIntoOwnedAssets(
|
||||
sourcePath,
|
||||
'pending.png',
|
||||
Buffer.from('pending image'),
|
||||
)
|
||||
const targetPath = join(dirname(sourcePath), 'copy.md')
|
||||
showSaveDialogWithMemory.mockResolvedValue({ canceled: false, filePath: targetPath })
|
||||
const view = createMarkdownView(sourcePath)
|
||||
const contents = view.webContents as unknown as FakeWebContents
|
||||
|
||||
const saveResult = await handlers.get(MARKDOWN_CHANNELS.save)?.(
|
||||
{ sender: contents },
|
||||
{
|
||||
text: `\n`,
|
||||
imageSources: [saved, pending],
|
||||
mode: 'saveAs',
|
||||
},
|
||||
)
|
||||
|
||||
expect(saveResult).toMatchObject({ ok: true, path: targetPath })
|
||||
expect(existsSync(join(dirname(sourcePath), pending))).toBe(true)
|
||||
expect(await readFile(sourcePath, 'utf8')).toBe(``)
|
||||
expect(await readOwnedAssetManifest(targetPath)).toMatchObject({
|
||||
files: [{ name: 'pending.png' }, { name: 'saved.png' }],
|
||||
documents: {
|
||||
'copy.md': ['pending.png', 'saved.png'],
|
||||
'note.md': ['saved.png'],
|
||||
},
|
||||
pending: {},
|
||||
})
|
||||
})
|
||||
|
||||
it('removes cross-directory source orphans while preserving old saved references', async () => {
|
||||
const sourcePath = await createDocument()
|
||||
const saved = await writeImageIntoOwnedAssets(
|
||||
sourcePath,
|
||||
'saved.png',
|
||||
Buffer.from('saved image'),
|
||||
)
|
||||
await reconcileOwnedAssets(sourcePath, [saved])
|
||||
await writeFile(sourcePath, ``)
|
||||
const pending = await writeImageIntoOwnedAssets(
|
||||
sourcePath,
|
||||
'pending.png',
|
||||
Buffer.from('pending image'),
|
||||
)
|
||||
const targetDirectory = await mkdtemp(join(tmpdir(), 'markdown-save-as-target-'))
|
||||
temporaryDirectories.push(targetDirectory)
|
||||
const targetPath = join(targetDirectory, 'copy.md')
|
||||
showSaveDialogWithMemory.mockResolvedValue({ canceled: false, filePath: targetPath })
|
||||
const view = createMarkdownView(sourcePath)
|
||||
const contents = view.webContents as unknown as FakeWebContents
|
||||
|
||||
const saveResult = await handlers.get(MARKDOWN_CHANNELS.save)?.(
|
||||
{ sender: contents },
|
||||
{
|
||||
text: `\n`,
|
||||
imageSources: [saved, pending],
|
||||
mode: 'saveAs',
|
||||
},
|
||||
)
|
||||
|
||||
expect(saveResult).toMatchObject({
|
||||
ok: true,
|
||||
path: targetPath,
|
||||
imageRewrites: [
|
||||
{ from: saved, to: 'assets/saved.png' },
|
||||
{ from: pending, to: 'assets/pending.png' },
|
||||
],
|
||||
})
|
||||
expect(existsSync(join(dirname(sourcePath), pending))).toBe(false)
|
||||
expect(await readFile(join(dirname(sourcePath), saved), 'utf8')).toBe('saved image')
|
||||
expect(await readFile(sourcePath, 'utf8')).toBe(``)
|
||||
expect(await readOwnedAssetManifest(sourcePath)).toMatchObject({
|
||||
files: [{ name: 'saved.png' }],
|
||||
documents: { 'note.md': ['saved.png'] },
|
||||
pending: {},
|
||||
})
|
||||
expect(await readOwnedAssetManifest(targetPath)).toMatchObject({
|
||||
files: [{ name: 'pending.png' }, { name: 'saved.png' }],
|
||||
documents: { 'copy.md': ['pending.png', 'saved.png'] },
|
||||
pending: {},
|
||||
})
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'resolves source pending ownership even when destination reconciliation reports an error',
|
||||
async () => {
|
||||
const sourcePath = await createDocument()
|
||||
const keep = await writeImageIntoOwnedAssets(
|
||||
sourcePath,
|
||||
'keep.png',
|
||||
Buffer.from('keep image'),
|
||||
)
|
||||
const orphan = await writeImageIntoOwnedAssets(
|
||||
sourcePath,
|
||||
'orphan.png',
|
||||
Buffer.from('orphan image'),
|
||||
)
|
||||
// Simulate a source file that already references one still-pending asset.
|
||||
await writeFile(sourcePath, ``)
|
||||
|
||||
const targetDirectory = await mkdtemp(join(tmpdir(), 'markdown-save-as-error-target-'))
|
||||
temporaryDirectories.push(targetDirectory)
|
||||
const targetPath = join(targetDirectory, 'copy.md')
|
||||
const blocked = await writeImageIntoOwnedAssets(
|
||||
targetPath,
|
||||
'blocked.png',
|
||||
Buffer.from('unrelated target asset'),
|
||||
)
|
||||
const blockedPath = join(targetDirectory, blocked)
|
||||
await chmod(blockedPath, 0)
|
||||
showSaveDialogWithMemory.mockResolvedValue({ canceled: false, filePath: targetPath })
|
||||
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const view = createMarkdownView(sourcePath)
|
||||
const contents = view.webContents as unknown as FakeWebContents
|
||||
|
||||
let saveResult: unknown
|
||||
try {
|
||||
saveResult = await handlers.get(MARKDOWN_CHANNELS.save)?.(
|
||||
{ sender: contents },
|
||||
{
|
||||
text: `\n`,
|
||||
imageSources: [keep, orphan],
|
||||
mode: 'saveAs',
|
||||
},
|
||||
)
|
||||
} finally {
|
||||
await chmod(blockedPath, 0o600)
|
||||
}
|
||||
|
||||
expect(saveResult).toMatchObject({ ok: true, path: targetPath })
|
||||
expect(warning).toHaveBeenCalledWith(
|
||||
'[markdown] asset reconciliation incomplete:',
|
||||
expect.arrayContaining([expect.stringContaining('blocked.png')]),
|
||||
)
|
||||
expect(existsSync(join(dirname(sourcePath), keep))).toBe(true)
|
||||
expect(existsSync(join(dirname(sourcePath), orphan))).toBe(false)
|
||||
expect(await readOwnedAssetManifest(sourcePath)).toMatchObject({
|
||||
files: [{ name: 'keep.png' }],
|
||||
pending: {},
|
||||
})
|
||||
expect(existsSync(join(targetDirectory, 'assets', 'keep.png'))).toBe(true)
|
||||
expect(existsSync(join(targetDirectory, 'assets', 'orphan.png'))).toBe(true)
|
||||
},
|
||||
)
|
||||
|
||||
it('preserves source pending ownership and rolls back copied assets when Save As fails', async () => {
|
||||
const sourcePath = await createDocument()
|
||||
const pending = await writeImageIntoOwnedAssets(
|
||||
sourcePath,
|
||||
'pending.png',
|
||||
Buffer.from('pending image'),
|
||||
)
|
||||
const targetDirectory = await mkdtemp(join(tmpdir(), 'markdown-save-as-failure-'))
|
||||
temporaryDirectories.push(targetDirectory)
|
||||
const targetPath = join(targetDirectory, 'copy.md')
|
||||
// A directory at the picked file path makes the final atomic rename fail
|
||||
// after destination assets have already been prepared.
|
||||
await mkdir(targetPath)
|
||||
showSaveDialogWithMemory.mockResolvedValue({ canceled: false, filePath: targetPath })
|
||||
const view = createMarkdownView(sourcePath)
|
||||
const contents = view.webContents as unknown as FakeWebContents
|
||||
|
||||
const saveResult = await handlers.get(MARKDOWN_CHANNELS.save)?.(
|
||||
{ sender: contents },
|
||||
{
|
||||
text: ``,
|
||||
imageSources: [pending],
|
||||
mode: 'saveAs',
|
||||
},
|
||||
)
|
||||
|
||||
expect(saveResult).toMatchObject({ ok: false })
|
||||
expect(existsSync(join(dirname(sourcePath), pending))).toBe(true)
|
||||
expect(await readOwnedAssetManifest(sourcePath)).toMatchObject({
|
||||
files: [{ name: 'pending.png' }],
|
||||
pending: { 'note.md': ['pending.png'] },
|
||||
})
|
||||
expect(existsSync(join(targetDirectory, 'assets', 'pending.png'))).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,81 @@
|
||||
import { mkdtemp, mkdir, readdir, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join, relative } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
MARKDOWN_CONVERSION_TTL_MS,
|
||||
cleanupStaleMarkdownConversions,
|
||||
createMarkdownConversionSession,
|
||||
writeMarkdownConversion,
|
||||
} from '../src/main/conversion-lifecycle'
|
||||
|
||||
const tempDirectories: string[] = []
|
||||
|
||||
async function temporaryDirectory(prefix: string): Promise<string> {
|
||||
const directory = await mkdtemp(join(tmpdir(), prefix))
|
||||
tempDirectories.push(directory)
|
||||
return directory
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
tempDirectories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })),
|
||||
)
|
||||
})
|
||||
|
||||
describe('Markdown convert-and-open cache', () => {
|
||||
it('puts repeated conversions in an app-owned session instead of beside the Markdown file', async () => {
|
||||
const sourceDirectory = await temporaryDirectory('markdown-convert-source-')
|
||||
const cacheRoot = await temporaryDirectory('markdown-convert-cache-')
|
||||
await writeFile(join(sourceDirectory, 'notes.md'), '# Notes')
|
||||
const session = await createMarkdownConversionSession(cacheRoot, {
|
||||
now: 1_000,
|
||||
id: 'test-session',
|
||||
})
|
||||
|
||||
const first = await writeMarkdownConversion(
|
||||
session,
|
||||
'notes',
|
||||
Buffer.from('first docx'),
|
||||
'first',
|
||||
)
|
||||
const second = await writeMarkdownConversion(
|
||||
session,
|
||||
'notes',
|
||||
Buffer.from('second docx'),
|
||||
'second',
|
||||
)
|
||||
|
||||
expect(first).not.toBe(second)
|
||||
expect(dirname(first)).toBe(session)
|
||||
expect(dirname(second)).toBe(session)
|
||||
expect(await readdir(sourceDirectory)).toEqual(['notes.md'])
|
||||
})
|
||||
|
||||
it('cleans only marked sessions after the explicit TTL', async () => {
|
||||
const cacheRoot = await temporaryDirectory('markdown-convert-ttl-')
|
||||
const old = await createMarkdownConversionSession(cacheRoot, { now: 1, id: 'old' })
|
||||
const unknown = join(cacheRoot, 'session-user-data')
|
||||
await mkdir(unknown)
|
||||
await writeFile(join(unknown, 'keep.txt'), 'keep')
|
||||
|
||||
const removed = await cleanupStaleMarkdownConversions(cacheRoot, MARKDOWN_CONVERSION_TTL_MS + 2)
|
||||
|
||||
expect(removed).toEqual([old])
|
||||
expect(await readdir(unknown)).toEqual(['keep.txt'])
|
||||
})
|
||||
|
||||
it('sanitizes generated names so output cannot escape the marked session', async () => {
|
||||
const cacheRoot = await temporaryDirectory('markdown-convert-safe-')
|
||||
const session = await createMarkdownConversionSession(cacheRoot, { now: 1, id: 'safe' })
|
||||
const output = await writeMarkdownConversion(
|
||||
session,
|
||||
'../../outside',
|
||||
Buffer.from('docx'),
|
||||
'../bad-id',
|
||||
)
|
||||
|
||||
expect(relative(session, output).startsWith('..')).toBe(false)
|
||||
expect(output.endsWith('.docx')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -75,6 +75,31 @@ describe('docx export', () => {
|
||||
expect(table?.table?.rows[1]?.[1]?.paras.join('')).toBe('1')
|
||||
})
|
||||
|
||||
it('block math becomes a native OMML equation', async () => {
|
||||
const editor = createEditor('$$\n\\frac{a}{b}\n$$')
|
||||
const mapping = await mapDocToSaveBlocks(editor.getJSON(), noImages)
|
||||
const xml = mapping.blocks.find((b) => b.kind === 'xml')
|
||||
expect(xml && 'xml' in xml && xml.xml).toContain('<m:oMath>')
|
||||
})
|
||||
|
||||
it('block math outside the OMML subset keeps its LaTeX source visible', async () => {
|
||||
const editor = createEditor('$$\n\\notacommand{x}\n$$')
|
||||
const mapping = await mapDocToSaveBlocks(editor.getJSON(), noImages)
|
||||
const texts = mapping.blocks.map((b) =>
|
||||
b.kind === 'generated' ? (b.block.runs ?? []).map((r) => r.text).join('') : '',
|
||||
)
|
||||
expect(texts.join('\n')).toContain('$$\\notacommand{x}$$')
|
||||
})
|
||||
|
||||
it('inline math keeps its LaTeX in the run text', async () => {
|
||||
const editor = createEditor('value $x_{1}$ end')
|
||||
const mapping = await mapDocToSaveBlocks(editor.getJSON(), noImages)
|
||||
const texts = mapping.blocks.map((b) =>
|
||||
b.kind === 'generated' ? (b.block.runs ?? []).map((r) => r.text).join('') : '',
|
||||
)
|
||||
expect(texts.join('\n')).toContain('$x_{1}$')
|
||||
})
|
||||
|
||||
it('task lists render checkbox glyphs', async () => {
|
||||
const parsed = await exportAndParse('- [x] done\n- [ ] open')
|
||||
const texts = parsed.blocks.map((b) => (b.runs ?? []).map((r) => r.text).join(''))
|
||||
|
||||
@@ -95,6 +95,69 @@ describe('markdown round-trip for GFM nodes', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('math nodes — $ / $$ syntax (issue #100)', () => {
|
||||
const editor = createEditor()
|
||||
|
||||
function collect(node: Record<string, unknown>, type: string): Record<string, unknown>[] {
|
||||
const hits: Record<string, unknown>[] = []
|
||||
if (node.type === type) hits.push(node)
|
||||
for (const child of (node.content as Record<string, unknown>[] | undefined) ?? []) {
|
||||
hits.push(...collect(child, type))
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
it('$$ array environment parses to block math with row breaks (\\\\) intact', () => {
|
||||
const md = [
|
||||
'$$',
|
||||
'\\begin{array}{ll}',
|
||||
'\\max & f = 1.25 x_{1} + 1.5 x_{2}, \\\\',
|
||||
'\\text{s.t.} & 0.025 x_{1} + 0.05 x_{2} \\le 400, \\\\',
|
||||
'& x_{1}, x_{2} \\ge 0.',
|
||||
'\\end{array}',
|
||||
'$$',
|
||||
].join('\n')
|
||||
const manager = editor.markdown!
|
||||
const doc = manager.parse(md) as Record<string, unknown>
|
||||
const nodes = collect(doc, 'blockMath')
|
||||
expect(nodes.length).toBe(1)
|
||||
const latex = String((nodes[0].attrs as { latex: string }).latex)
|
||||
expect(latex).toContain('\\begin{array}{ll}')
|
||||
// the markdown escape pass must not eat the \\ row separators
|
||||
expect(latex).toContain('\\\\')
|
||||
|
||||
const out = manager.serialize(doc)
|
||||
expect(out).toContain('\\begin{array}{ll}')
|
||||
expect(out).toContain('\\\\')
|
||||
expect(JSON.stringify(manager.parse(out))).toBe(JSON.stringify(doc))
|
||||
})
|
||||
|
||||
it('$$ aligned environment round-trips', () => {
|
||||
const md = '$$\n\\begin{aligned}\na &= b + c \\\\\nd &= e\n\\end{aligned}\n$$'
|
||||
const { out, stable } = roundTrip(editor, md)
|
||||
expect(out).toContain('\\begin{aligned}')
|
||||
expect(out).toContain('\\\\')
|
||||
expect(stable).toBe(true)
|
||||
})
|
||||
|
||||
it('inline $x_{1}$ becomes an inline math node and round-trips', () => {
|
||||
const manager = editor.markdown!
|
||||
const doc = manager.parse('the variable $x_{1}$ is free') as Record<string, unknown>
|
||||
const nodes = collect(doc, 'inlineMath')
|
||||
expect(nodes.length).toBe(1)
|
||||
expect((nodes[0].attrs as { latex: string }).latex).toBe('x_{1}')
|
||||
expect(manager.serialize(doc)).toBe('the variable $x_{1}$ is free')
|
||||
})
|
||||
|
||||
it('currency amounts in plain text never turn into formulas', () => {
|
||||
const manager = editor.markdown!
|
||||
const md = 'I paid $5 and $10 in total'
|
||||
const doc = manager.parse(md) as Record<string, unknown>
|
||||
expect(collect(doc, 'inlineMath').length).toBe(0)
|
||||
expect(manager.serialize(doc)).toBe(md)
|
||||
})
|
||||
})
|
||||
|
||||
describe('only pure markdown syntax is ever produced', () => {
|
||||
const editor = createEditor()
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildSlashItems, filterSlashItems } from '../src/renderer/editor/slashCommand'
|
||||
import { resolveImageSrc, unresolveImageSrc } from '../src/renderer/editor/localImage'
|
||||
|
||||
@@ -7,6 +7,7 @@ import { resolveImageSrc, unresolveImageSrc } from '../src/renderer/editor/local
|
||||
const editors: import('@tiptap/core').Editor[] = []
|
||||
afterEach(() => {
|
||||
for (const e of editors.splice(0)) e.destroy()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('filterSlashItems', () => {
|
||||
@@ -228,3 +229,50 @@ describe('buildPrintHtml', () => {
|
||||
expect(html).not.toContain('<select')
|
||||
})
|
||||
})
|
||||
|
||||
describe('BlockDragHandle teardown', () => {
|
||||
it('removes every long-lived listener and restores the container style', async () => {
|
||||
const { Editor } = await import('@tiptap/core')
|
||||
const { buildExtensions } = await import('../src/renderer/editor/extensions')
|
||||
const wrapper = document.createElement('div')
|
||||
const element = document.createElement('div')
|
||||
wrapper.appendChild(element)
|
||||
document.body.appendChild(wrapper)
|
||||
const editor = new Editor({
|
||||
element,
|
||||
extensions: buildExtensions({
|
||||
slashController: { onOpen() {}, onUpdate() {}, onKeyDown: () => false, onClose() {} },
|
||||
slashItems: () => [],
|
||||
}),
|
||||
content: 'block',
|
||||
})
|
||||
|
||||
const handle = wrapper.querySelector<HTMLElement>('.md-block-gutter')!
|
||||
const grip = handle.querySelector<HTMLButtonElement>('.md-gutter-grip')!
|
||||
const plus = handle.querySelector<HTMLButtonElement>('.md-gutter-plus')!
|
||||
const handleRemove = vi.spyOn(handle, 'removeEventListener')
|
||||
const gripRemove = vi.spyOn(grip, 'removeEventListener')
|
||||
const plusRemove = vi.spyOn(plus, 'removeEventListener')
|
||||
const documentRemove = vi.spyOn(document, 'removeEventListener')
|
||||
const editorRemove = vi.spyOn(editor.view.dom, 'removeEventListener')
|
||||
|
||||
editor.destroy()
|
||||
|
||||
expect(editorRemove).toHaveBeenCalledWith('mousemove', expect.any(Function))
|
||||
expect(editorRemove).toHaveBeenCalledWith('mouseenter', expect.any(Function))
|
||||
expect(editorRemove).toHaveBeenCalledWith('mouseleave', expect.any(Function))
|
||||
expect(handleRemove).toHaveBeenCalledWith('mousemove', expect.any(Function))
|
||||
expect(handleRemove).toHaveBeenCalledWith('mouseenter', expect.any(Function))
|
||||
expect(handleRemove).toHaveBeenCalledWith('mouseleave', expect.any(Function))
|
||||
expect(gripRemove).toHaveBeenCalledWith('dragstart', expect.any(Function))
|
||||
expect(gripRemove).toHaveBeenCalledWith('click', expect.any(Function))
|
||||
expect(plusRemove).toHaveBeenCalledWith('click', expect.any(Function))
|
||||
expect(documentRemove).toHaveBeenCalledWith('scroll', expect.any(Function), true)
|
||||
expect(wrapper.style.position).toBe('')
|
||||
expect(wrapper.querySelector('.md-block-gutter')).toBeNull()
|
||||
expect(wrapper.querySelector('.md-block-menu')).toBeNull()
|
||||
|
||||
wrapper.remove()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { act, createElement, type ReactElement } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('@tiptap/react', async () => {
|
||||
const react = await import('react')
|
||||
return {
|
||||
NodeViewWrapper: ({
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
children: import('react').ReactNode
|
||||
className?: string
|
||||
}) => react.createElement('div', { className }, children),
|
||||
NodeViewContent: () => react.createElement('code'),
|
||||
}
|
||||
})
|
||||
|
||||
import { AiPanel, type MarkdownAiDeps } from '../src/renderer/ai/AiPanel'
|
||||
import { CodeBlockView } from '../src/renderer/editor/CodeBlockView'
|
||||
|
||||
const mountedRoots: Array<{ root: Root; container: HTMLElement }> = []
|
||||
|
||||
function mount(element: ReactElement): { root: Root; container: HTMLElement } {
|
||||
const container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
const root = createRoot(container)
|
||||
act(() => root.render(element))
|
||||
mountedRoots.push({ root, container })
|
||||
return { root, container }
|
||||
}
|
||||
|
||||
function unmount(root: Root): void {
|
||||
const mounted = mountedRoots.find((entry) => entry.root === root)
|
||||
act(() => root.unmount())
|
||||
mounted?.container.remove()
|
||||
if (mounted) mountedRoots.splice(mountedRoots.indexOf(mounted), 1)
|
||||
}
|
||||
|
||||
function typeInto(textarea: HTMLTextAreaElement, text: string): void {
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!
|
||||
act(() => {
|
||||
setter.call(textarea, text)
|
||||
textarea.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
})
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
Element.prototype.scrollTo ??= () => {}
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const { root, container } of mountedRoots.splice(0)) {
|
||||
act(() => root.unmount())
|
||||
container.remove()
|
||||
}
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('CodeBlockView teardown', () => {
|
||||
it('clears copy feedback timeout when its node view unmounts', async () => {
|
||||
vi.useFakeTimers()
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
configurable: true,
|
||||
value: { writeText: vi.fn(async () => {}) },
|
||||
})
|
||||
const clearTimeout = vi.spyOn(window, 'clearTimeout')
|
||||
const { root, container } = mount(
|
||||
createElement(CodeBlockView, {
|
||||
node: { attrs: { language: null }, textContent: 'const answer = 42' },
|
||||
updateAttributes: vi.fn(),
|
||||
editor: { isEditable: true },
|
||||
} as never),
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
container.querySelector<HTMLButtonElement>('.md-codeblock-copy')!.click()
|
||||
await Promise.resolve()
|
||||
})
|
||||
unmount(root)
|
||||
|
||||
expect(clearTimeout).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('AiPanel teardown', () => {
|
||||
it('cancels an in-flight IPC stream when the panel/tab unmounts', async () => {
|
||||
vi.useFakeTimers()
|
||||
const aiStream = vi.fn(async () => {})
|
||||
const aiStreamCancel = vi.fn(async () => {})
|
||||
const onAiStream = vi.fn(() => () => {})
|
||||
Object.defineProperty(window, 'markdownApi', {
|
||||
configurable: true,
|
||||
value: {
|
||||
getAiSettings: vi.fn(async () => ({})),
|
||||
aiStream,
|
||||
aiStreamCancel,
|
||||
onAiStream,
|
||||
},
|
||||
})
|
||||
Object.defineProperty(window, 'projectApi', { configurable: true, value: undefined })
|
||||
const deps: MarkdownAiDeps = {
|
||||
getEditor: () => null,
|
||||
getSnapshot: () => '',
|
||||
restoreSnapshot: () => {},
|
||||
onRunDone: () => {},
|
||||
}
|
||||
const { root, container } = mount(
|
||||
createElement(AiPanel, { deps, filePath: null, onCollapse: () => {} }),
|
||||
)
|
||||
const textarea = container.querySelector<HTMLTextAreaElement>('textarea')!
|
||||
typeInto(textarea, 'keep streaming')
|
||||
|
||||
await act(async () => {
|
||||
container.querySelector<HTMLButtonElement>('.ai-send-btn')!.click()
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
})
|
||||
expect(aiStream).toHaveBeenCalledTimes(1)
|
||||
|
||||
unmount(root)
|
||||
|
||||
expect(aiStreamCancel).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
import { rename, rm, writeFile } from 'node:fs/promises'
|
||||
|
||||
/**
|
||||
* Write PDF bytes beside the destination, then atomically replace it.
|
||||
* Any failed write or rename removes the partially written temp file.
|
||||
*/
|
||||
export async function writePdfAtomically(targetPath: string, bytes: Uint8Array): Promise<void> {
|
||||
const tmp = `${targetPath}.gensave-${process.pid}.tmp`
|
||||
try {
|
||||
await writeFile(tmp, bytes)
|
||||
await rename(tmp, targetPath)
|
||||
} catch (err) {
|
||||
await rm(tmp, { force: true })
|
||||
throw err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
|
||||
/** A4 portrait in PDF points */
|
||||
const A4_SIZE: [number, number] = [595.28, 841.89]
|
||||
|
||||
/**
|
||||
* Minimal single-page blank PDF backing the shell's "New PDF" entry — the PDF
|
||||
* module has no in-memory blank mode, so the file must exist before it opens
|
||||
* (same pattern as the blank workbook in sheets).
|
||||
*/
|
||||
export async function blankPdfBuffer(): Promise<Buffer> {
|
||||
const doc = await PDFDocument.create()
|
||||
doc.addPage(A4_SIZE)
|
||||
return Buffer.from(await doc.save())
|
||||
}
|
||||
@@ -2,4 +2,4 @@
|
||||
* System font location moved to @genoffice/font-metrics (shared with the docs
|
||||
* metrics pipeline); re-exported here to keep pdf-main import paths stable.
|
||||
*/
|
||||
export { findSystemFont, isTruetype } from '@genoffice/font-metrics'
|
||||
export { findFontCovering, findSystemFont, isTruetype } from '@genoffice/font-metrics'
|
||||
|
||||
+224
-18
@@ -1,7 +1,16 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { readFile, rename, writeFile } from 'node:fs/promises'
|
||||
import {
|
||||
constants,
|
||||
copyFileSync,
|
||||
existsSync,
|
||||
linkSync,
|
||||
readFileSync,
|
||||
statSync,
|
||||
unlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs'
|
||||
import { readFile, writeFile } from 'node:fs/promises'
|
||||
import { userInfo } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { basename, dirname, join } from 'node:path'
|
||||
import { BrowserWindow, WebContentsView, app, dialog, ipcMain, shell } from 'electron'
|
||||
import type { WebContents } from 'electron'
|
||||
import {
|
||||
@@ -18,6 +27,7 @@ import { PDF_CHANNELS } from '../shared/ipc'
|
||||
import type {
|
||||
ExportImagesRequest,
|
||||
ExportImagesResult,
|
||||
PdfAutoRenameResult,
|
||||
ExtractPagesRequest,
|
||||
ExtractPagesResult,
|
||||
InsertBlankPageRequest,
|
||||
@@ -45,6 +55,7 @@ import type {
|
||||
ValidateTextEditsRequest,
|
||||
} from '../shared/ipc'
|
||||
import type { SavedSignature } from '../shared/ipc'
|
||||
import { writePdfAtomically } from './atomic-write'
|
||||
import {
|
||||
cropPagesBytes,
|
||||
extractPagesBytes,
|
||||
@@ -456,6 +467,143 @@ export function pdfIsDirty(webContentsId: number): boolean {
|
||||
return dirtyByWc.has(webContentsId)
|
||||
}
|
||||
|
||||
// ── Content-derived auto-naming (pdf's analog of sheets' autoRenameWorkbook) ──
|
||||
|
||||
/** Paths of shell-created blank PDFs still carrying their untitled name; only these may auto-rename */
|
||||
const untitledPdfPaths = new Set<string>()
|
||||
/** Shell hook fired after an auto-rename so the tab title / recents / project mapping follow the file */
|
||||
let pdfRenamedHook: ((wc: WebContents, oldPath: string, newPath: string) => void) | null = null
|
||||
|
||||
/** Called by the shell right after "New PDF" writes the blank file to disk */
|
||||
export function markPdfUntitledPath(path: string): void {
|
||||
untitledPdfPaths.add(path)
|
||||
}
|
||||
|
||||
export function setPdfRenamedHook(
|
||||
hook: (wc: WebContents, oldPath: string, newPath: string) => void,
|
||||
): void {
|
||||
pdfRenamedHook = hook
|
||||
}
|
||||
|
||||
/** Sanitize a proposed base name into a safe filename: strip illegal path chars, collapse whitespace, cap length; null if nothing survives. (Mirrors docs' deriveAutoFileName.) */
|
||||
function sanitizeAutoRenameBase(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()
|
||||
.replace(/^\.+|\.+$/g, '')
|
||||
.trim()
|
||||
if (!cleaned) return null
|
||||
return cleaned.length > 40 ? cleaned.slice(0, 40).trim() : cleaned
|
||||
}
|
||||
|
||||
export type NoClobberMoveResult = 'moved' | 'occupied' | 'failed'
|
||||
|
||||
export interface NoClobberFileOps {
|
||||
link(source: string, target: string): void
|
||||
copyExclusive(source: string, target: string): void
|
||||
unlink(path: string): void
|
||||
identity(path: string): string
|
||||
readSource(path: string): Buffer
|
||||
matchesSource(path: string, bytes: Buffer): boolean
|
||||
restoreSource(path: string, bytes: Buffer): void
|
||||
}
|
||||
|
||||
const defaultNoClobberFileOps: NoClobberFileOps = {
|
||||
link: linkSync,
|
||||
copyExclusive: (source, target) => copyFileSync(source, target, constants.COPYFILE_EXCL),
|
||||
unlink: unlinkSync,
|
||||
identity: (path) => {
|
||||
const stats = statSync(path, { bigint: true })
|
||||
return `${stats.dev}:${stats.ino}`
|
||||
},
|
||||
readSource: (path) => readFileSync(path),
|
||||
matchesSource: (path, bytes) => readFileSync(path).equals(bytes),
|
||||
restoreSource: (path, bytes) => writeFileSync(path, bytes, { flag: 'wx', flush: true }),
|
||||
}
|
||||
|
||||
function fileErrorCode(error: unknown): string | undefined {
|
||||
return error && typeof error === 'object' && 'code' in error
|
||||
? String((error as NodeJS.ErrnoException).code)
|
||||
: undefined
|
||||
}
|
||||
|
||||
const LINK_COPY_FALLBACK_CODES = new Set(['ENOSYS', 'ENOTSUP', 'EOPNOTSUPP', 'EPERM', 'EXDEV'])
|
||||
|
||||
/**
|
||||
* Same-directory no-clobber move. A hard link reserves the exact destination
|
||||
* atomically and without copying PDF bytes; filesystems without hard-link
|
||||
* support fall back to an exclusive copy. Removing the old directory entry
|
||||
* completes the move. If that final unlink fails, the reserved destination is
|
||||
* removed only while it is still the exact entry we created.
|
||||
*/
|
||||
export function movePdfFileNoClobber(
|
||||
source: string,
|
||||
target: string,
|
||||
overrides: Partial<NoClobberFileOps> = {},
|
||||
): NoClobberMoveResult {
|
||||
const ops = { ...defaultNoClobberFileOps, ...overrides }
|
||||
let sourceBytes: Buffer
|
||||
try {
|
||||
sourceBytes = ops.readSource(source)
|
||||
} catch {
|
||||
return 'failed'
|
||||
}
|
||||
try {
|
||||
ops.link(source, target)
|
||||
} catch (linkError) {
|
||||
const code = fileErrorCode(linkError)
|
||||
if (code === 'EEXIST') return 'occupied'
|
||||
if (!code || !LINK_COPY_FALLBACK_CODES.has(code)) return 'failed'
|
||||
try {
|
||||
ops.copyExclusive(source, target)
|
||||
} catch (copyError) {
|
||||
return fileErrorCode(copyError) === 'EEXIST' ? 'occupied' : 'failed'
|
||||
}
|
||||
}
|
||||
|
||||
let createdIdentity: string
|
||||
try {
|
||||
createdIdentity = ops.identity(target)
|
||||
} catch {
|
||||
// The source is still intact. Do not remove a target that no longer
|
||||
// proves to be the entry this operation created.
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
try {
|
||||
ops.unlink(source)
|
||||
} catch {
|
||||
try {
|
||||
if (ops.identity(target) === createdIdentity && ops.matchesSource(target, sourceBytes)) {
|
||||
ops.unlink(target)
|
||||
}
|
||||
} catch {
|
||||
// Preserve an entry that no longer proves to be ours.
|
||||
}
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
try {
|
||||
if (ops.identity(target) === createdIdentity && ops.matchesSource(target, sourceBytes)) {
|
||||
return 'moved'
|
||||
}
|
||||
} catch {
|
||||
// Restore below from the in-memory source snapshot.
|
||||
}
|
||||
|
||||
// A concurrent actor replaced or removed target between reservation and
|
||||
// source unlink. Recreate the original source path before reporting failure.
|
||||
try {
|
||||
ops.restoreSource(source, sourceBytes)
|
||||
} catch {
|
||||
// Best effort: an actor with write access to the directory may also have
|
||||
// raced the source path. Never claim success or grant the suspect target.
|
||||
}
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
/**
|
||||
* Close guard for the pdf renderer: true means proceed with closing.
|
||||
* Clean → true; dirty → Save / Don't Save / Cancel. On Save, ask the renderer to
|
||||
@@ -611,6 +759,60 @@ function registerPdfIpc(): void {
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle(PDF_CHANNELS.isUntitled, (e, path: unknown): boolean => {
|
||||
return (
|
||||
typeof path === 'string' &&
|
||||
!!allowedByWc.get(e.sender.id)?.has(path) &&
|
||||
untitledPdfPaths.has(path)
|
||||
)
|
||||
})
|
||||
|
||||
ipcMain.handle(
|
||||
PDF_CHANNELS.autoRename,
|
||||
(e, path: unknown, baseName: unknown): PdfAutoRenameResult => {
|
||||
if (typeof path !== 'string' || !allowedByWc.get(e.sender.id)?.has(path)) {
|
||||
return { renamed: false }
|
||||
}
|
||||
// Only shell-created blanks still carrying their untitled name; user-chosen names never move
|
||||
if (!untitledPdfPaths.has(path)) return { renamed: false }
|
||||
if (typeof baseName !== 'string') return { renamed: false }
|
||||
const base = sanitizeAutoRenameBase(baseName)
|
||||
if (!base) return { renamed: false }
|
||||
const dir = dirname(path)
|
||||
// The file being renamed does not occupy its own name: a proposed base equal
|
||||
// to the current stem must be a no-op, not a hop to the next numbered suffix
|
||||
let target: string | null = null
|
||||
for (let suffix = 1; suffix <= 10_000; suffix++) {
|
||||
const candidate = join(dir, suffix === 1 ? `${base}.pdf` : `${base}-${suffix}.pdf`)
|
||||
if (candidate === path) return { renamed: false }
|
||||
const result = movePdfFileNoClobber(path, candidate)
|
||||
if (result === 'moved') {
|
||||
target = candidate
|
||||
break
|
||||
}
|
||||
if (result === 'failed') {
|
||||
console.warn('[pdf] auto-rename failed')
|
||||
return { renamed: false }
|
||||
}
|
||||
}
|
||||
if (!target) return { renamed: false }
|
||||
|
||||
// Replace rather than mutate the grant set: the old path is revoked in
|
||||
// the same operation that grants the new one, even if it is recreated.
|
||||
allowedByWc.set(e.sender.id, new Set([target]))
|
||||
if (openPathByWc.get(e.sender.id) === path) openPathByWc.set(e.sender.id, target)
|
||||
untitledPdfPaths.delete(path)
|
||||
try {
|
||||
pdfRenamedHook?.(e.sender, path, target)
|
||||
} catch (err) {
|
||||
// Filesystem and renderer bookkeeping are already committed. A shell
|
||||
// title/recents hook must not make the renderer keep using oldPath.
|
||||
console.warn('[pdf] auto-rename hook failed:', err)
|
||||
}
|
||||
return { renamed: true, path: target, name: basename(target) }
|
||||
},
|
||||
)
|
||||
|
||||
ipcMain.handle(PDF_CHANNELS.listPageImages, async (e, path: unknown) => {
|
||||
if (typeof path !== 'string' || !allowedByWc.get(e.sender.id)?.has(path)) {
|
||||
throw new Error('pdf: path not granted to this view')
|
||||
@@ -704,6 +906,20 @@ function registerPdfIpc(): void {
|
||||
return listEditFonts()
|
||||
})
|
||||
|
||||
ipcMain.handle(
|
||||
PDF_CHANNELS.canDrawText,
|
||||
async (_e, text: unknown, font: unknown, bold: unknown, italic: unknown): Promise<boolean> => {
|
||||
if (typeof text !== 'string') return false
|
||||
const { canDrawText } = await import('./text-edit')
|
||||
return canDrawText(
|
||||
text,
|
||||
typeof font === 'string' ? font : undefined,
|
||||
bold === true,
|
||||
italic === true,
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
PDF_CHANNELS.extractPages,
|
||||
async (e, request: ExtractPagesRequest): Promise<ExtractPagesResult> => {
|
||||
@@ -752,9 +968,7 @@ function registerPdfIpc(): void {
|
||||
new Uint8Array(await readFile(other)),
|
||||
typeof afterPageIndex === 'number' ? afterPageIndex : -1,
|
||||
)
|
||||
const tmp = `${path}.gensave-${process.pid}.tmp`
|
||||
await writeFile(tmp, merged)
|
||||
await rename(tmp, path)
|
||||
await writePdfAtomically(path, merged)
|
||||
return { ok: true, insertedCount: count }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) }
|
||||
@@ -774,9 +988,7 @@ function registerPdfIpc(): void {
|
||||
new Uint8Array(await readFile(path)),
|
||||
typeof afterPageIndex === 'number' ? afterPageIndex : -1,
|
||||
)
|
||||
const tmp = `${path}.gensave-${process.pid}.tmp`
|
||||
await writeFile(tmp, bytes)
|
||||
await rename(tmp, path)
|
||||
await writePdfAtomically(path, bytes)
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) }
|
||||
@@ -909,9 +1121,7 @@ function registerPdfIpc(): void {
|
||||
new Uint8Array(await readFile(other)),
|
||||
pages,
|
||||
)
|
||||
const tmp = `${path}.gensave-${process.pid}.tmp`
|
||||
await writeFile(tmp, merged)
|
||||
await rename(tmp, path)
|
||||
await writePdfAtomically(path, merged)
|
||||
return { ok: true, removed, inserted }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) }
|
||||
@@ -931,9 +1141,7 @@ function registerPdfIpc(): void {
|
||||
}
|
||||
try {
|
||||
const bytes = await setPageSizeBytes(new Uint8Array(await readFile(path)), width, height)
|
||||
const tmp = `${path}.gensave-${process.pid}.tmp`
|
||||
await writeFile(tmp, bytes)
|
||||
await rename(tmp, path)
|
||||
await writePdfAtomically(path, bytes)
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) }
|
||||
@@ -981,9 +1189,7 @@ function registerPdfIpc(): void {
|
||||
}
|
||||
try {
|
||||
const bytes = await cropPagesBytes(new Uint8Array(await readFile(path)), pages, rect)
|
||||
const tmp = `${path}.gensave-${process.pid}.tmp`
|
||||
await writeFile(tmp, bytes)
|
||||
await rename(tmp, path)
|
||||
await writePdfAtomically(path, bytes)
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { readFile, rename, rm, writeFile } from 'node:fs/promises'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import {
|
||||
PDFArray,
|
||||
PDFBool,
|
||||
@@ -28,6 +28,7 @@ import type {
|
||||
TextEditFailure,
|
||||
TextInsertFailure,
|
||||
} from '../shared/ipc'
|
||||
import { writePdfAtomically } from './atomic-write'
|
||||
|
||||
const num = (v: number) => Math.round(v * 100) / 100
|
||||
const STATIC_FORM_FILLS_KEY = PDFName.of('GenOfficeStaticFormFills')
|
||||
@@ -845,14 +846,7 @@ export async function savePdfToPath(
|
||||
request,
|
||||
)
|
||||
await verifyContentEdits(bytes, request, skips)
|
||||
const tmp = `${targetPath}.gensave-${process.pid}.tmp`
|
||||
try {
|
||||
await writeFile(tmp, bytes)
|
||||
await rename(tmp, targetPath)
|
||||
} catch (err) {
|
||||
await rm(tmp, { force: true })
|
||||
throw err
|
||||
}
|
||||
await writePdfAtomically(targetPath, bytes)
|
||||
return skips
|
||||
}
|
||||
|
||||
@@ -886,12 +880,18 @@ export async function applySaveRequest(
|
||||
const applied = await applyTextEdits(bytes, request.textEdits)
|
||||
bytes = applied.bytes
|
||||
skippedTextEdits = applied.skipped
|
||||
for (const s of skippedTextEdits) {
|
||||
console.warn(`[pdf] text edit skipped on page ${s.pageIndex + 1}: ${s.reason}`)
|
||||
}
|
||||
}
|
||||
if (request.textInserts && request.textInserts.length > 0) {
|
||||
const { applyTextInserts } = await import('./text-edit')
|
||||
const applied = await applyTextInserts(bytes, request.textInserts)
|
||||
bytes = applied.bytes
|
||||
skippedTextInserts = applied.skipped
|
||||
for (const s of skippedTextInserts) {
|
||||
console.warn(`[pdf] text insert skipped on page ${s.pageIndex + 1}: ${s.reason}`)
|
||||
}
|
||||
}
|
||||
if (request.imageEdits && request.imageEdits.length > 0) {
|
||||
const { applyImageEdits } = await import('./image-edit')
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { PDFDict, PDFDocument, PDFName, PDFRawStream, decodePDFRawStream } from 'pdf-lib'
|
||||
import { fontCoversText } from './font-cmap'
|
||||
import { findSystemFont, isTruetype } from './font-locate'
|
||||
import { findFontCovering, findSystemFont, isTruetype } from './font-locate'
|
||||
import { identityCffCharset, subsetTtf } from './font-subset'
|
||||
import { pdfiumWasmPath } from './wasm-path'
|
||||
import type {
|
||||
@@ -144,29 +144,67 @@ export function loadPdfium(): Promise<Pdfium> {
|
||||
return pdfiumPromise
|
||||
}
|
||||
|
||||
/** Fallback fonts for rebuilt runs, first readable file wins; must be single-face sfnt (no .ttc) */
|
||||
const FALLBACK_FONTS = [
|
||||
/** Fallback font files for rebuilt runs, tried first; must be single-face sfnt (no .ttc).
|
||||
arialuni.ttf only exists where legacy Office installed it — modern Windows relies on
|
||||
the system-face lookup below (inserted text has no original font to inherit, so a
|
||||
missing fallback used to fail EVERY Insert Text save on Windows). */
|
||||
const FALLBACK_FONT_PATHS = [
|
||||
'/System/Library/Fonts/Supplemental/Arial Unicode.ttf',
|
||||
'C:\\Windows\\Fonts\\arialuni.ttf',
|
||||
'/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',
|
||||
]
|
||||
|
||||
let fallbackFontBytes: Buffer | null | undefined
|
||||
/** [PostScript name, family] fallbacks resolved through the installed-font index
|
||||
(which extracts single faces from .ttc collections). Latin faces lead so plain
|
||||
Latin text keeps a neutral look; CJK/Hangul faces follow and win only when the
|
||||
text needs their coverage (each candidate is coverage-gated). */
|
||||
const FALLBACK_SYSTEM_FACES: readonly (readonly [string, string])[] = [
|
||||
['ArialMT', 'Arial'],
|
||||
['SegoeUI', 'Segoe UI'],
|
||||
['Helvetica', 'Helvetica'],
|
||||
['MicrosoftYaHei', 'Microsoft YaHei'],
|
||||
['SimSun', 'SimSun'],
|
||||
['PingFangSC-Regular', 'PingFang SC'],
|
||||
['HiraginoSans-W3', 'Hiragino Sans'],
|
||||
['YuGothic-Regular', 'Yu Gothic'],
|
||||
['MSGothic', 'MS Gothic'],
|
||||
['MalgunGothic', 'Malgun Gothic'],
|
||||
['AppleSDGothicNeo-Regular', 'Apple SD Gothic Neo'],
|
||||
['NotoSansCJKsc-Regular', 'Noto Sans CJK SC'],
|
||||
['DejaVuSans', 'DejaVu Sans'],
|
||||
['LiberationSans-Regular', 'Liberation Sans'],
|
||||
]
|
||||
|
||||
function loadFallbackFont(): Buffer {
|
||||
if (fallbackFontBytes === undefined) {
|
||||
fallbackFontBytes = null
|
||||
for (const p of FALLBACK_FONTS) {
|
||||
try {
|
||||
fallbackFontBytes = readFileSync(p)
|
||||
break
|
||||
} catch {
|
||||
/* try next */
|
||||
}
|
||||
const fallbackPathCache = new Map<string, Buffer | null>()
|
||||
|
||||
function readFallbackPath(p: string): Buffer | null {
|
||||
let bytes = fallbackPathCache.get(p)
|
||||
if (bytes === undefined) {
|
||||
try {
|
||||
bytes = readFileSync(p)
|
||||
} catch {
|
||||
bytes = null
|
||||
}
|
||||
fallbackPathCache.set(p, bytes)
|
||||
}
|
||||
if (!fallbackFontBytes) throw new Error('no fallback font available for text editing')
|
||||
return fallbackFontBytes
|
||||
return bytes
|
||||
}
|
||||
|
||||
/** First fallback face whose cmap covers `drawn`; when no curated candidate does,
|
||||
scan the whole installed-font index — the browser preview resolves per-char
|
||||
fallback across every installed font, so text the user already SEES must find
|
||||
an embeddable face too. Null only when nothing monochrome covers the text
|
||||
(color-emoji faces display but cannot embed as PDF text). */
|
||||
export function fallbackFontFor(drawn: string): Buffer | null {
|
||||
for (const p of FALLBACK_FONT_PATHS) {
|
||||
const bytes = readFallbackPath(p)
|
||||
if (bytes && fontCoversText(bytes, drawn)) return bytes
|
||||
}
|
||||
for (const [ps, family] of FALLBACK_SYSTEM_FACES) {
|
||||
const bytes = findSystemFont(ps, family)
|
||||
if (bytes && fontCoversText(bytes, drawn)) return bytes
|
||||
}
|
||||
return findFontCovering(drawn)
|
||||
}
|
||||
|
||||
export type EditFontStyle = 'regular' | 'bold' | 'italic' | 'bolditalic'
|
||||
@@ -267,6 +305,22 @@ export function listEditFonts(): string[] {
|
||||
return Object.keys(EDIT_FONT_PATHS).filter((id) => loadEditFont(id) !== null)
|
||||
}
|
||||
|
||||
/** Can this machine draw `text` into the PDF at all? Mirrors rebuildFontBytes'
|
||||
resolution for an insert (the chosen edit font, else any fallback face), so the
|
||||
renderer can reject an undrawable insert at confirm time instead of at save. */
|
||||
export function canDrawText(text: string, font?: string, bold = false, italic = false): boolean {
|
||||
const drawn = text.replace(/\n/g, '')
|
||||
if (font) {
|
||||
const style: EditFontStyle =
|
||||
bold && italic ? 'bolditalic' : bold ? 'bold' : italic ? 'italic' : 'regular'
|
||||
for (const s of style === 'regular' ? (['regular'] as const) : ([style, 'regular'] as const)) {
|
||||
const bytes = loadEditFont(font, s)
|
||||
if (bytes && fontCoversText(bytes, drawn)) return true
|
||||
}
|
||||
}
|
||||
return fallbackFontFor(drawn) !== null
|
||||
}
|
||||
|
||||
/** Whitespace-insensitive, radical- and NFKC-folded comparison key. pdf.js and pdfium
|
||||
disagree on compatibility codepoints — some fonts' cmaps yield radical-block
|
||||
codepoints (Kangxi U+2F00, which NFKC decomposes, and the Radicals Supplement
|
||||
@@ -971,14 +1025,27 @@ async function rebuildFontBytes(
|
||||
}
|
||||
}
|
||||
}
|
||||
const fallback = loadFallbackFont()
|
||||
// Chars beyond even the fallback face (emoji, rare CJK extensions) would embed as
|
||||
// missing glyphs and then fail read-back verification, blocking the whole save —
|
||||
// reject this one edit instead (it is reported as skipped, everything else saves)
|
||||
if (!fontCoversText(fallback, drawn)) {
|
||||
const fallback = fallbackFontFor(drawn)
|
||||
// No face covers the text (emoji, rare CJK extensions — or a machine with none of
|
||||
// the fallback fonts): embedding missing glyphs would fail read-back verification
|
||||
// and block the whole save — reject this one edit instead (it is reported as
|
||||
// skipped with this reason, everything else saves)
|
||||
if (!fallback) {
|
||||
throw new Error('the replacement contains characters no available font can draw')
|
||||
}
|
||||
return subsetTtf(fallback, drawn)
|
||||
const sub = await subsetTtf(fallback, drawn)
|
||||
try {
|
||||
// CFF-flavored fallbacks (e.g. PingFang) need the charset rewrite for viewer
|
||||
// compat; a no-op for TrueType faces
|
||||
return identityCffCharset(sub)
|
||||
} catch {
|
||||
// TrueType subsets never needed the rewrite, so the raw subset is safe. A CFF
|
||||
// subset without it can save fine yet render BLANK in viewers that resolve CID
|
||||
// through the charset (Acrobat) — reject this edit (reported as skipped with
|
||||
// this reason) instead of embedding bytes that look saved but display nothing.
|
||||
if (isTruetype(sub)) return sub
|
||||
throw new Error('the fallback font for this text could not be embedded')
|
||||
}
|
||||
}
|
||||
|
||||
/** Extra leading between stacked lines, multiple of the font size (matches the preview CSS) */
|
||||
|
||||
@@ -8,8 +8,12 @@ const api: PdfApi = {
|
||||
consumePending: () => ipcRenderer.invoke(PDF_CHANNELS.consumePending),
|
||||
readFile: (path) => ipcRenderer.invoke(PDF_CHANNELS.readFile, path),
|
||||
save: (request) => ipcRenderer.invoke(PDF_CHANNELS.save, request),
|
||||
autoRename: (path, baseName) => ipcRenderer.invoke(PDF_CHANNELS.autoRename, path, baseName),
|
||||
isUntitled: (path) => ipcRenderer.invoke(PDF_CHANNELS.isUntitled, path),
|
||||
validateTextEdits: (request) => ipcRenderer.invoke(PDF_CHANNELS.validateTextEdits, request),
|
||||
listEditFonts: () => ipcRenderer.invoke(PDF_CHANNELS.listEditFonts),
|
||||
canDrawText: (text, font, bold, italic) =>
|
||||
ipcRenderer.invoke(PDF_CHANNELS.canDrawText, text, font, bold, italic),
|
||||
listPageImages: (path) => ipcRenderer.invoke(PDF_CHANNELS.listPageImages, path),
|
||||
listStaticFormFills: (path) => ipcRenderer.invoke(PDF_CHANNELS.listStaticFormFills, path),
|
||||
pageImagePng: (request) => ipcRenderer.invoke(PDF_CHANNELS.pageImagePng, request),
|
||||
|
||||
+344
-1484
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,170 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { CSSProperties, RefObject } from 'react'
|
||||
import { AnnotationMode, TextLayer } from 'pdfjs-dist/legacy/build/pdf.mjs'
|
||||
import type { PDFDocumentProxy, RenderTask } from 'pdfjs-dist'
|
||||
import { pdfRectToCss, quadToRect } from './annotations'
|
||||
import type { LocalMarkup, PageGeom } from './annotations'
|
||||
|
||||
/** Which items in the container are within the (expanded) viewport — shared lazy-render basis
|
||||
for pages/thumbnails. Rebuild the observer when enabled flips (sidebar toggles unmount/remount the root) */
|
||||
export function useVisibleSet(
|
||||
rootRef: RefObject<HTMLElement | null>,
|
||||
count: number,
|
||||
rootMargin: string,
|
||||
enabled = true,
|
||||
): { visible: Set<number>; setItemRef: (idx: number) => (el: HTMLElement | null) => void } {
|
||||
const [visible, setVisible] = useState<Set<number>>(new Set())
|
||||
const itemRefs = useRef<(HTMLElement | null)[]>([])
|
||||
useEffect(() => {
|
||||
const root = rootRef.current
|
||||
if (!enabled || !root || count === 0) return
|
||||
const io = new IntersectionObserver(
|
||||
(entries) => {
|
||||
setVisible((prev) => {
|
||||
const next = new Set(prev)
|
||||
for (const e of entries) {
|
||||
const idx = Number((e.target as HTMLElement).dataset.idx)
|
||||
if (e.isIntersecting) next.add(idx)
|
||||
else next.delete(idx)
|
||||
}
|
||||
return next
|
||||
})
|
||||
},
|
||||
{ root, rootMargin },
|
||||
)
|
||||
for (const el of itemRefs.current) if (el) io.observe(el)
|
||||
return () => io.disconnect()
|
||||
}, [rootRef, count, rootMargin, enabled])
|
||||
return {
|
||||
visible,
|
||||
setItemRef: (idx) => (el) => {
|
||||
itemRefs.current[idx] = el
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Single page: renders canvas + text layer (select/copy) when visible, released once off-viewport */
|
||||
export function PdfPage({
|
||||
doc,
|
||||
pageNo,
|
||||
scale,
|
||||
rotationDelta,
|
||||
visible,
|
||||
onRenderState,
|
||||
}: {
|
||||
doc: PDFDocumentProxy
|
||||
pageNo: number
|
||||
scale: number
|
||||
/** Unsaved rotation delta (clockwise degrees) */
|
||||
rotationDelta: number
|
||||
visible: boolean
|
||||
onRenderState: (doc: PDFDocumentProxy, pageNo: number, pending: boolean) => void
|
||||
}) {
|
||||
const holderRef = useRef<HTMLDivElement>(null)
|
||||
useEffect(() => {
|
||||
const holder = holderRef.current
|
||||
if (!holder) return
|
||||
// Offscreen pages still release their bitmap. For an in-place rerender (save
|
||||
// reload, zoom, rotation), keep the previous canvas visible until its replacement
|
||||
// is fully rendered so the page never flashes white between document instances.
|
||||
if (!visible) {
|
||||
holder.replaceChildren()
|
||||
// A page captured by the post-save barrier may scroll out before its replacement
|
||||
// renders. Its overlays are no longer mounted, so treat the cleared offscreen page
|
||||
// as settled instead of making the whole document wait for the timeout.
|
||||
onRenderState(doc, pageNo, false)
|
||||
return
|
||||
}
|
||||
// Visibility may change while a save reload is running. Register newly visible
|
||||
// pages dynamically so global preview cleanup cannot outrun their bitmap swap.
|
||||
onRenderState(doc, pageNo, true)
|
||||
let cancelled = false
|
||||
let renderTask: RenderTask | null = null
|
||||
void (async () => {
|
||||
const page = await doc.getPage(pageNo)
|
||||
if (cancelled) return
|
||||
const viewport = page.getViewport({ scale, rotation: (page.rotate + rotationDelta) % 360 })
|
||||
// Cap at 2x: on hi-dpi screens a 3x-dpr full-page bitmap doubles memory with no visible gain
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2)
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = Math.floor(viewport.width * dpr)
|
||||
canvas.height = Math.floor(viewport.height * dpr)
|
||||
canvas.style.width = `${Math.floor(viewport.width)}px`
|
||||
canvas.style.height = `${Math.floor(viewport.height)}px`
|
||||
renderTask = page.render({
|
||||
canvas,
|
||||
viewport,
|
||||
// FormLayer renders interactive widgets as HTML. Exclude their saved appearance
|
||||
// streams from the page bitmap or filled values are drawn twice after a reload.
|
||||
annotationMode: AnnotationMode.ENABLE_FORMS,
|
||||
transform: dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : undefined,
|
||||
})
|
||||
try {
|
||||
await renderTask.promise
|
||||
} catch {
|
||||
return // cancelled
|
||||
}
|
||||
if (cancelled) return
|
||||
const textDiv = document.createElement('div')
|
||||
textDiv.className = 'textLayer'
|
||||
holder.replaceChildren(canvas, textDiv)
|
||||
// Notify after the bitmap swap, but before the browser paints. A post-save
|
||||
// reload uses this to remove the matching edit previews in the same frame.
|
||||
onRenderState(doc, pageNo, false)
|
||||
const textLayer = new TextLayer({
|
||||
textContentSource: page.streamTextContent(),
|
||||
container: textDiv,
|
||||
viewport,
|
||||
})
|
||||
try {
|
||||
await textLayer.render()
|
||||
} catch {
|
||||
/* cancelled */
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
renderTask?.cancel()
|
||||
}
|
||||
}, [doc, pageNo, scale, rotationDelta, visible, onRenderState])
|
||||
return <div ref={holderRef} className="pdf-page-content" />
|
||||
}
|
||||
|
||||
/** Overlay for unsaved markups. Purely visual (pointer-events: none) so the text
|
||||
* underneath stays selectable; clicking is handled by the page-level hit test. */
|
||||
export function MarkupOverlay({
|
||||
markups,
|
||||
geom,
|
||||
scale,
|
||||
selectedId,
|
||||
}: {
|
||||
markups: LocalMarkup[]
|
||||
geom: PageGeom
|
||||
scale: number
|
||||
selectedId: string | null
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{markups.flatMap((m) =>
|
||||
m.quads.map((q, i) => {
|
||||
const [r, g, b] = m.color
|
||||
const style: CSSProperties = pdfRectToCss(geom, quadToRect(q), scale)
|
||||
if (m.type === 'highlight') {
|
||||
style.background = `rgba(${r * 255}, ${g * 255}, ${b * 255}, 0.4)`
|
||||
} else {
|
||||
const bar = `rgb(${r * 255}, ${g * 255}, ${b * 255})`
|
||||
if (m.type === 'underline') style.borderBottom = `2px solid ${bar}`
|
||||
else style.backgroundImage = `linear-gradient(${bar}, ${bar})`
|
||||
}
|
||||
return (
|
||||
<div
|
||||
key={`${m.id}-${i}`}
|
||||
className={`pdf-markup pdf-markup-${m.type}${m.id === selectedId ? ' pdf-markup-selected' : ''}`}
|
||||
style={style}
|
||||
/>
|
||||
)
|
||||
}),
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import { Fragment, useEffect, useRef } from 'react'
|
||||
import type { ReactElement } from 'react'
|
||||
import type { PDFDocumentProxy } from 'pdfjs-dist'
|
||||
import { geomDispSize, pdfRectToCss } from './annotations'
|
||||
import type { LocalMarkup, PageGeom } from './annotations'
|
||||
import { DrawLayer } from './DrawLayer'
|
||||
import type { LocalDrawing } from './DrawLayer'
|
||||
import { ImageEditLayer } from './ImageEditLayer'
|
||||
import type { LocalImageEdit } from './ImageEditLayer'
|
||||
import { MarkupOverlay } from './PdfPage'
|
||||
import {
|
||||
textEditPreviewContent,
|
||||
textEditPreviewParts,
|
||||
textInsertPreviewStyle,
|
||||
} from './text-edit-preview'
|
||||
import type { LocalTextEdit, LocalTextInsert } from './text-edit-preview'
|
||||
import { STROKE_WIDTH } from './view-config'
|
||||
import type { StampInput } from '../shared/ipc'
|
||||
|
||||
interface RenderTaskHandle {
|
||||
promise: Promise<unknown>
|
||||
cancel: () => void
|
||||
}
|
||||
|
||||
interface RenderedThumb {
|
||||
doc: PDFDocumentProxy
|
||||
pageNo: number
|
||||
rotationDelta: number
|
||||
rasterW: number
|
||||
}
|
||||
|
||||
function releaseCanvasPixels(canvas: HTMLCanvasElement): void {
|
||||
canvas.width = 0
|
||||
canvas.height = 0
|
||||
}
|
||||
|
||||
/** Thumbnail: rendered once per (doc, page, rotation, raster width) while visible.
|
||||
* Offscreen thumbnails release their canvas allocation and raster again when
|
||||
* shown. rasterW only changes when a sidebar drag ends, so a resize re-rasters
|
||||
* each visible thumb once; while dragging the canvas just CSS-stretches. */
|
||||
export function PdfThumb({
|
||||
doc,
|
||||
pageNo,
|
||||
rotationDelta,
|
||||
visible,
|
||||
rasterW,
|
||||
}: {
|
||||
doc: PDFDocumentProxy
|
||||
pageNo: number
|
||||
rotationDelta: number
|
||||
visible: boolean
|
||||
rasterW: number
|
||||
}) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const renderedRef = useRef<RenderedThumb | null>(null)
|
||||
const renderSettledRef = useRef<Promise<void>>(Promise.resolve())
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
if (!visible) {
|
||||
renderedRef.current = null
|
||||
releaseCanvasPixels(canvas)
|
||||
return
|
||||
}
|
||||
const rendered = renderedRef.current
|
||||
if (
|
||||
rendered?.doc === doc &&
|
||||
rendered.pageNo === pageNo &&
|
||||
rendered.rotationDelta === rotationDelta &&
|
||||
rendered.rasterW === rasterW
|
||||
) {
|
||||
return
|
||||
}
|
||||
renderedRef.current = null
|
||||
let disposed = false
|
||||
let renderTask: RenderTaskHandle | null = null
|
||||
const previousRenderSettled = renderSettledRef.current
|
||||
const renderSettled = (async () => {
|
||||
// pdf.js owns the canvas until RenderTask.promise settles, including after
|
||||
// cancel(). Never hand the same canvas to the replacement task sooner.
|
||||
await previousRenderSettled
|
||||
if (disposed) return
|
||||
try {
|
||||
const page = await doc.getPage(pageNo)
|
||||
if (disposed) return
|
||||
const rotation = (page.rotate + rotationDelta) % 360
|
||||
const scale = rasterW / page.getViewport({ scale: 1, rotation }).width
|
||||
const viewport = page.getViewport({ scale, rotation })
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2)
|
||||
canvas.width = Math.floor(viewport.width * dpr)
|
||||
canvas.height = Math.floor(viewport.height * dpr)
|
||||
renderTask = page.render({
|
||||
canvas,
|
||||
viewport,
|
||||
transform: dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : undefined,
|
||||
})
|
||||
await renderTask.promise
|
||||
if (!disposed) renderedRef.current = { doc, pageNo, rotationDelta, rasterW }
|
||||
} catch {
|
||||
if (!disposed) renderedRef.current = null
|
||||
} finally {
|
||||
renderTask = null
|
||||
}
|
||||
})()
|
||||
renderSettledRef.current = renderSettled
|
||||
return () => {
|
||||
disposed = true
|
||||
renderTask?.cancel()
|
||||
}
|
||||
}, [doc, pageNo, rotationDelta, visible, rasterW])
|
||||
|
||||
// Capture the node: React may clear canvasRef before passive unmount cleanup runs.
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current
|
||||
return () => {
|
||||
if (canvas) releaseCanvasPixels(canvas)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return <canvas ref={canvasRef} style={{ width: '100%' }} />
|
||||
}
|
||||
|
||||
export interface ThumbMenu {
|
||||
x: number
|
||||
y: number
|
||||
origIdx: number
|
||||
}
|
||||
|
||||
/** Read-only mirror of the pending-edit overlays, scaled into a page thumbnail so the
|
||||
* sidebar tracks unsaved edits like the canvas does. Children render at scale 1 (display
|
||||
* coords) and the container scales down; CSS kills all inner pointer events so thumbnail
|
||||
* click/drag/context-menu behavior is untouched. */
|
||||
export function ThumbPendingOverlay({
|
||||
geom,
|
||||
k,
|
||||
markups,
|
||||
drawings,
|
||||
textEdits,
|
||||
textInserts,
|
||||
imageEdits,
|
||||
stamps,
|
||||
}: {
|
||||
geom: PageGeom
|
||||
k: number
|
||||
markups: LocalMarkup[]
|
||||
drawings: LocalDrawing[]
|
||||
textEdits: LocalTextEdit[]
|
||||
textInserts: LocalTextInsert[]
|
||||
imageEdits: LocalImageEdit[]
|
||||
stamps: StampInput[]
|
||||
}): ReactElement {
|
||||
const disp = geomDispSize(geom)
|
||||
const noop = () => {}
|
||||
return (
|
||||
<div
|
||||
className="pdf-thumb-overlay"
|
||||
style={{ width: disp.width, height: disp.height, transform: `scale(${k})` }}
|
||||
>
|
||||
{imageEdits.length > 0 && (
|
||||
<ImageEditLayer
|
||||
geom={geom}
|
||||
scale={1}
|
||||
edits={imageEdits}
|
||||
existing={[]}
|
||||
selectedId={null}
|
||||
selectedKey={null}
|
||||
editHint=""
|
||||
onSelectEdit={noop}
|
||||
onSelectExisting={noop}
|
||||
/>
|
||||
)}
|
||||
{stamps.map((s, si) => (
|
||||
<img
|
||||
key={si}
|
||||
className="pdf-stamp-preview"
|
||||
src={`data:image/png;base64,${s.image}`}
|
||||
alt=""
|
||||
style={{ ...pdfRectToCss(geom, s.rect, 1), opacity: s.opacity ?? 1 }}
|
||||
/>
|
||||
))}
|
||||
<MarkupOverlay markups={markups} geom={geom} scale={1} selectedId={null} />
|
||||
{drawings.length > 0 && (
|
||||
<DrawLayer
|
||||
geom={geom}
|
||||
scale={1}
|
||||
pageWidth={disp.width}
|
||||
pageHeight={disp.height}
|
||||
drawings={drawings}
|
||||
savedNotes={[]}
|
||||
activeNoteKey={null}
|
||||
noteOpenTitle=""
|
||||
tool={null}
|
||||
color={[0, 0, 0]}
|
||||
strokeWidth={STROKE_WIDTH}
|
||||
selectedId={null}
|
||||
selectTitle=""
|
||||
onCommit={noop}
|
||||
onNoteAt={noop}
|
||||
onNoteOpen={noop}
|
||||
onSelect={noop}
|
||||
/>
|
||||
)}
|
||||
{textInserts.map((insert) => (
|
||||
<div
|
||||
key={insert.id}
|
||||
className="pdf-textinsert-preview"
|
||||
style={textInsertPreviewStyle(insert, geom, 1)}
|
||||
>
|
||||
{insert.input.text}
|
||||
</div>
|
||||
))}
|
||||
{textEdits.map((te) => {
|
||||
const { style, coverStyle } = textEditPreviewParts(te, geom, 1)
|
||||
return (
|
||||
<Fragment key={te.id}>
|
||||
{coverStyle && <div className="pdf-textedit-cover" style={coverStyle} />}
|
||||
<div className="pdf-textedit-preview" style={style}>
|
||||
{textEditPreviewContent(te, 1)}
|
||||
</div>
|
||||
</Fragment>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useState } from 'react'
|
||||
import type { ReactElement } from 'react'
|
||||
import { cssRgb } from './DrawLayer'
|
||||
import type { SignatureData } from './SignatureDialog'
|
||||
|
||||
/** Scale factor applied when placing a signature: 1/3 of the displayed page width,
|
||||
capped at 1/6 of its height so tall images stay signature-sized */
|
||||
export const signPlaceK = (sig: SignatureData, dispW: number, dispH: number): number =>
|
||||
Math.min(dispW / 3 / sig.width, dispH / 6 / sig.height)
|
||||
|
||||
/** Inserted images land at up to half the page, never above natural size
|
||||
(0.75 ≈ px→pt, so a screen-resolution image keeps its printed size) */
|
||||
export const imagePlaceK = (sig: SignatureData, dispW: number, dispH: number): number =>
|
||||
Math.min(dispW / 2 / sig.width, dispH / 2 / sig.height, 0.75)
|
||||
export const staticFormFillPlaceK = (): number => 1
|
||||
|
||||
/** Click-to-place overlay: a translucent ghost of the pending signature follows the
|
||||
cursor at its actual landing size, and clicking drops it centered on that point */
|
||||
export function SignDropOverlay({
|
||||
sig,
|
||||
dispW,
|
||||
dispH,
|
||||
scale,
|
||||
color,
|
||||
title,
|
||||
onPlace,
|
||||
placeK = signPlaceK,
|
||||
}: {
|
||||
sig: SignatureData
|
||||
/** Displayed page size at scale=1 (view coords) */
|
||||
dispW: number
|
||||
dispH: number
|
||||
scale: number
|
||||
color: [number, number, number]
|
||||
title: string
|
||||
onPlace: (vx: number, vy: number) => void
|
||||
/** Landing-size rule; defaults to signature sizing (image insert passes its own) */
|
||||
placeK?: (sig: SignatureData, dispW: number, dispH: number) => number
|
||||
}): ReactElement {
|
||||
const [pt, setPt] = useState<[number, number] | null>(null)
|
||||
const k = placeK(sig, dispW, dispH) * scale
|
||||
const w = sig.width * k
|
||||
const h = sig.height * k
|
||||
return (
|
||||
<div
|
||||
className="pdf-sign-drop"
|
||||
data-tip={title}
|
||||
onPointerMove={(e) => {
|
||||
const box = e.currentTarget.getBoundingClientRect()
|
||||
setPt([e.clientX - box.left, e.clientY - box.top])
|
||||
}}
|
||||
onPointerLeave={() => setPt(null)}
|
||||
onClick={(e) => {
|
||||
const box = e.currentTarget.getBoundingClientRect()
|
||||
onPlace((e.clientX - box.left) / scale, (e.clientY - box.top) / scale)
|
||||
}}
|
||||
>
|
||||
{pt && (
|
||||
<div
|
||||
className="pdf-sign-ghost"
|
||||
style={{
|
||||
left: Math.min(Math.max(pt[0] - w / 2, 0), Math.max(dispW * scale - w, 0)),
|
||||
top: Math.min(Math.max(pt[1] - h / 2, 0), Math.max(dispH * scale - h, 0)),
|
||||
width: w,
|
||||
height: h,
|
||||
}}
|
||||
>
|
||||
{sig.kind === 'image' ? (
|
||||
<img src={`data:image/png;base64,${sig.image}`} alt="" draggable={false} />
|
||||
) : (
|
||||
<svg viewBox={`0 0 ${sig.width} ${sig.height}`} preserveAspectRatio="none">
|
||||
{sig.paths.map((p, i) => {
|
||||
const pts: string[] = []
|
||||
for (let j = 0; j < p.length; j += 2) pts.push(`${p[j]},${p[j + 1]}`)
|
||||
return (
|
||||
<polyline
|
||||
key={i}
|
||||
points={pts.join(' ')}
|
||||
fill="none"
|
||||
stroke={cssRgb(color)}
|
||||
strokeWidth={2.4}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -55,11 +55,14 @@ export function AiPanel({
|
||||
api,
|
||||
onCollapse,
|
||||
preset,
|
||||
onRunDone,
|
||||
}: {
|
||||
api: PdfAiDeps
|
||||
onCollapse: () => void
|
||||
/** Ribbon AI buttons push a one-shot prompt; a new nonce triggers an auto-run */
|
||||
preset?: { text: string; nonce: number } | null
|
||||
/** Fired when a run that mutated the document finishes (drives the untitled-blank auto-save) */
|
||||
onRunDone?: () => void
|
||||
}): ReactElement {
|
||||
const { lang, t } = useI18n()
|
||||
const [chat, setChat] = useState<ChatEntry[]>([])
|
||||
@@ -87,6 +90,10 @@ export function AiPanel({
|
||||
langRef.current = lang
|
||||
const apiRef = useRef(api)
|
||||
apiRef.current = api
|
||||
const onRunDoneRef = useRef(onRunDone)
|
||||
onRunDoneRef.current = onRunDone
|
||||
/** Any tool in the current run reported mutated: true */
|
||||
const runMutatedRef = useRef(false)
|
||||
|
||||
const patchLast = (patch: Partial<ChatEntry> | ((last: ChatEntry) => Partial<ChatEntry>)) => {
|
||||
setChat((prev) => {
|
||||
@@ -113,6 +120,7 @@ export function AiPanel({
|
||||
gotoPage: (p) => apiRef.current.gotoPage(p),
|
||||
addMarkup: (type, idx, rects) => apiRef.current.addMarkup(type, idx, rects),
|
||||
editText: (input) => apiRef.current.editText(input),
|
||||
insertText: (input) => apiRef.current.insertText(input),
|
||||
editFonts: () => apiRef.current.editFonts(),
|
||||
formEdits: () => apiRef.current.formEdits(),
|
||||
applyFormEdit: (v) => apiRef.current.applyFormEdit(v),
|
||||
@@ -141,6 +149,7 @@ export function AiPanel({
|
||||
},
|
||||
onToolExecuted: ({ call, execution }) => {
|
||||
setPhase('working')
|
||||
if (execution.mutated) runMutatedRef.current = true
|
||||
patchLast((last) => ({
|
||||
tools: [
|
||||
...(last.tools ?? []),
|
||||
@@ -167,6 +176,10 @@ export function AiPanel({
|
||||
text: final || (last.tools?.length ? last.text : tGlobal('aiNoReply')),
|
||||
}))
|
||||
setBusy(false)
|
||||
if (runMutatedRef.current) {
|
||||
runMutatedRef.current = false
|
||||
onRunDoneRef.current?.()
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
setChat((prev) => {
|
||||
@@ -216,6 +229,7 @@ export function AiPanel({
|
||||
setPrompt('')
|
||||
setBusy(true)
|
||||
setPhase('thinking')
|
||||
runMutatedRef.current = false
|
||||
void (async () => {
|
||||
try {
|
||||
settingsRef.current = await window.pdfApi.getAiSettings()
|
||||
|
||||
@@ -14,6 +14,7 @@ const SYSTEM_PROMPT = `You are GenOffice's PDF assistant, helping the user read,
|
||||
- The text passed to markup_text must be a verbatim fragment that actually exists on the page; read first, then mark; one call marks one passage.
|
||||
- edit_text replaces text in place without reflowing the page: keep the replacement close to the original length, and edit one short run per call (a phrase or a line). old_text must be verbatim from the page.
|
||||
- edit_block rewrites a whole paragraph and reflows it within the paragraph's width (it may grow downward but never pushes other content). Use it when the change affects more than a line's worth of text; paragraph_text must uniquely identify the paragraph.
|
||||
- insert_text adds NEW text and never touches existing text — use it to write on blank pages or into empty areas (titles, notes, drafting content from scratch). Position with x/y in points from the page's top-left; pass max_width to auto-wrap paragraphs. A PDF page has no reflow: place blocks yourself and mind the page bounds (a typical A4 page is 595 × 842 pt). For existing text always use edit_text/edit_block instead.
|
||||
- To add an image: get a direct URL first (image_search for real photos, generate_image for illustrations/icons), then insert_image. When the user names a location ("next to the title"), position with anchor_text taken verbatim from the page; explicit coordinates are PDF points measured from the page's top-left corner.
|
||||
- To move, resize, rotate, replace, or delete an image that is already in the document, call list_page_images first and reference its per-page image numbers. For "change/AI-edit this image": generate_image with the desired edit, then replace_image with the returned URL — never delete + reinsert (that loses the footprint and z-order).
|
||||
- Before filling forms, you must call list_form_fields to learn field names, types, and options.
|
||||
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
MarkupType,
|
||||
PageImageRef,
|
||||
TextEditInput,
|
||||
TextInsertInput,
|
||||
} from '../../shared/ipc'
|
||||
import { groupPageBlocks } from '../text-block'
|
||||
import { joinBlockLines, measurePt, wrapText } from '../text-wrap'
|
||||
@@ -38,6 +39,8 @@ export interface PdfAiDeps {
|
||||
addMarkup(type: MarkupType, origIdx: number, rects: [number, number, number, number][]): void
|
||||
/** Queue a pending text edit (dry-run validated against the file when possible); null = accepted, string = rejection reason */
|
||||
editText(input: TextEditInput): Promise<string | null>
|
||||
/** Queue a pending insert of a new text object (same pipeline as the UI "add text" tool) */
|
||||
insertText(input: TextInsertInput): void
|
||||
/** Edit-font ids available on this machine (EDIT_FONTS subset) */
|
||||
editFonts(): string[]
|
||||
formEdits(): ReadonlyMap<string, FormValueInput>
|
||||
@@ -212,6 +215,47 @@ export const AGENT_TOOLS: AgentToolDef[] = [
|
||||
required: ['page', 'paragraph_text', 'new_text'],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'insert_text',
|
||||
description:
|
||||
'Add NEW text to a page (drawn as new content on top of the page; takes effect on save). Use this for blank pages or empty areas — to change text that already exists, use edit_text or edit_block instead. x/y are the TOP-LEFT corner of the text block in points measured from the page top-left as displayed; with no x/y the block is centered horizontally near the top. "\\n" starts a new line; pass max_width to auto-wrap long paragraphs within that width.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
page: { type: 'integer', description: 'Page number (1-based)' },
|
||||
text: { type: 'string', description: 'Text to insert; "\\n" separates lines/paragraphs' },
|
||||
x: {
|
||||
type: 'number',
|
||||
description: 'Left edge of the text block in points from the page left edge',
|
||||
},
|
||||
y: {
|
||||
type: 'number',
|
||||
description: 'Top edge of the text block in points from the page TOP edge',
|
||||
},
|
||||
font_size: { type: 'number', description: 'Font size in PDF points; defaults to 14' },
|
||||
color: { type: 'string', description: 'Text color as #RRGGBB hex; defaults to black' },
|
||||
max_width: {
|
||||
type: 'number',
|
||||
description:
|
||||
'Wrap width in points: paragraphs are re-wrapped to fit; omit to keep the given line breaks as-is',
|
||||
},
|
||||
align: {
|
||||
type: 'string',
|
||||
enum: ['left', 'center', 'right'],
|
||||
description: 'Line alignment within max_width (or the widest line); defaults to left',
|
||||
},
|
||||
font: {
|
||||
type: 'string',
|
||||
enum: ['arial', 'times', 'courier'],
|
||||
description:
|
||||
'Font for the text; ignored when the face lacks glyphs for it (e.g. CJK). Omit for automatic',
|
||||
},
|
||||
bold: { type: 'boolean', description: 'Set the text in the bold variant' },
|
||||
italic: { type: 'boolean', description: 'Set the text in the italic variant' },
|
||||
},
|
||||
required: ['page', 'text'],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'image_search',
|
||||
description:
|
||||
@@ -762,6 +806,103 @@ async function editBlock(deps: PdfAiDeps, input: Record<string, unknown>): Promi
|
||||
}
|
||||
}
|
||||
|
||||
/** Insert a brand-new text block (the blank-page counterpart of edit_text/edit_block) */
|
||||
async function insertTextTool(
|
||||
deps: PdfAiDeps,
|
||||
input: Record<string, unknown>,
|
||||
): Promise<ToolExecution> {
|
||||
const summary = t('aiToolInsertText', { page: Number(input.page) })
|
||||
if (deps.readOnly()) return err(READONLY_OUTPUT, summary)
|
||||
const r = resolvePage(deps, input.page)
|
||||
if ('bad' in r) return err(r.bad, summary)
|
||||
const geom = deps.pageGeom(r.origIdx)
|
||||
if (!geom) return err('Document not ready', summary)
|
||||
const text = String(input.text ?? '')
|
||||
.replace(/\r\n/g, '\n')
|
||||
.trim()
|
||||
if (!text) return err('text must not be empty', summary)
|
||||
|
||||
const fontSize = input.font_size === undefined ? 14 : Number(input.font_size)
|
||||
if (!(fontSize > 0)) return err('font_size must be a positive number', summary)
|
||||
let color: [number, number, number] = [0, 0, 0]
|
||||
if (input.color !== undefined) {
|
||||
const hex = HEX_COLOR.exec(String(input.color))
|
||||
if (!hex) return err(`Invalid color "${String(input.color)}"; use #RRGGBB`, summary)
|
||||
const v = parseInt(hex[1]!, 16)
|
||||
color = [(v >> 16) & 255, (v >> 8) & 255, v & 255]
|
||||
}
|
||||
const font = input.font === undefined ? undefined : String(input.font)
|
||||
if (font !== undefined && !deps.editFonts().includes(font)) {
|
||||
const avail = deps.editFonts()
|
||||
return err(
|
||||
avail.length > 0
|
||||
? `Font "${font}" is not available; choose one of: ${avail.join(', ')}`
|
||||
: 'No selectable fonts are available on this machine; omit the font parameter',
|
||||
summary,
|
||||
)
|
||||
}
|
||||
const align = input.align === undefined ? 'left' : String(input.align)
|
||||
if (align !== 'left' && align !== 'center' && align !== 'right')
|
||||
return err("align must be 'left', 'center' or 'right'", summary)
|
||||
const maxWidth = input.max_width === undefined ? undefined : Number(input.max_width)
|
||||
if (maxWidth !== undefined && !(maxWidth > 0))
|
||||
return err('max_width must be a positive number', summary)
|
||||
|
||||
// measure/wrap with the face that will actually be embedded (same as edit_block)
|
||||
const bold = input.bold === true ? true : undefined
|
||||
const italic = input.italic === true ? true : undefined
|
||||
const cssFamily =
|
||||
(font ? EDIT_FONTS.find((f) => f.id === font)?.css : undefined) ??
|
||||
getComputedStyle(document.body).fontFamily
|
||||
const cssStyle = `${italic ? 'italic ' : ''}${bold ? 'bold' : ''}`.trim()
|
||||
const lines = maxWidth
|
||||
? text
|
||||
.split('\n')
|
||||
.flatMap((p) => (p.trim() ? wrapText(p, maxWidth, fontSize, cssFamily, cssStyle) : ['']))
|
||||
: text.split('\n')
|
||||
const lineWidths = lines.map((l) => measurePt(l, fontSize, cssFamily, cssStyle))
|
||||
const blockW = maxWidth ?? Math.max(...lineWidths, 1)
|
||||
const lineLeading = fontSize * 1.2
|
||||
const blockH = lineLeading * (lines.length - 1) + fontSize * 1.2
|
||||
|
||||
// display-space position (top-left origin, points at scale 1), clamped to the page
|
||||
const size = geomDispSize(geom)
|
||||
let tx = input.x === undefined ? (size.width - blockW) / 2 : Number(input.x)
|
||||
let ty = input.y === undefined ? 72 : Number(input.y)
|
||||
if (!Number.isFinite(tx) || !Number.isFinite(ty))
|
||||
return err('x and y must be numbers (points from the page top-left as displayed)', summary)
|
||||
tx = Math.min(Math.max(tx, 0), Math.max(size.width - blockW, 0))
|
||||
ty = Math.min(Math.max(ty, 0), Math.max(size.height - blockH, 0))
|
||||
|
||||
deps.insertText({
|
||||
pageIndex: r.origIdx,
|
||||
// TextInsertInput.origin is the first-line baseline in PDF user space
|
||||
origin: viewToPdf(geom, tx, ty + fontSize),
|
||||
text: lines.join('\n'),
|
||||
fontSize,
|
||||
color,
|
||||
font,
|
||||
bold,
|
||||
italic,
|
||||
lineLeading,
|
||||
lineXOffsets:
|
||||
align === 'left'
|
||||
? undefined
|
||||
: lineWidths.map((w) => {
|
||||
const slack = Math.max(0, blockW - w)
|
||||
return align === 'center' ? slack / 2 : slack
|
||||
}),
|
||||
align: align === 'left' ? undefined : align,
|
||||
rotate: ((geom.rot % 360) + 360) % 360,
|
||||
})
|
||||
deps.gotoPage(r.origIdx + 1)
|
||||
return {
|
||||
output: `Inserted ${lines.length} line(s) of text on page ${r.origIdx + 1} at x=${fmt(tx)}, y=${fmt(ty)}, ${fontSize} pt (unsaved; the user can drag/edit it, undo with ⌘Z, save with ⌘S).`,
|
||||
mutated: true,
|
||||
summary,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Image tools ─────────────────────────────────────────────────────
|
||||
// Model-facing coordinates are display-space points: what the user sees, with a
|
||||
// top-left origin and page rotation applied (viewToPdf/pdfRectToCss, same as the
|
||||
@@ -1238,6 +1379,8 @@ export async function executePdfTool(
|
||||
return editText(deps, input)
|
||||
case 'edit_block':
|
||||
return editBlock(deps, input)
|
||||
case 'insert_text':
|
||||
return insertTextTool(deps, input)
|
||||
case 'image_search':
|
||||
return imageSearchTool(deps, input)
|
||||
case 'generate_image':
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { LocalMarkup } from './annotations'
|
||||
import type { LocalDrawing } from './DrawLayer'
|
||||
import type { LocalImageEdit } from './ImageEditLayer'
|
||||
import type { SavedNoteAnnot } from './note-threads'
|
||||
import type { HeaderFooterConfig, WatermarkConfig } from './stamps'
|
||||
import type { LocalTextEdit, LocalTextInsert } from './text-edit-preview'
|
||||
import type { FormValueInput, MarkupType, MetadataInput, PageImageRef } from '../shared/ipc'
|
||||
|
||||
/** pdf.js AnnotationType codes for the markup subtypes we can delete */
|
||||
export const MARKUP_TYPE_BY_ANNOT: Record<number, MarkupType> = {
|
||||
9: 'highlight',
|
||||
10: 'underline',
|
||||
12: 'strikeout',
|
||||
}
|
||||
|
||||
export const rectsNear = (a: readonly number[], b: readonly number[], tolerance = 2): boolean =>
|
||||
a.length === 4 &&
|
||||
b.length === 4 &&
|
||||
a.every((value, index) => Math.abs(value - b[index]!) <= tolerance)
|
||||
|
||||
/** Full snapshot of unsaved edits (for undo/redo; data is small, whole-copy replace is safest) */
|
||||
/** Watermark/header-footer are kept as config and rendered in final page order only at save time, so page numbers survive reorders/deletions */
|
||||
export interface StampConfig {
|
||||
wm: WatermarkConfig | null
|
||||
hf: HeaderFooterConfig | null
|
||||
}
|
||||
|
||||
/** A markup annotation already saved in the file (read via pdf.js getAnnotations) */
|
||||
export interface SavedMarkupAnnot {
|
||||
pageIndex: number
|
||||
/** PDF object number (pdf.js id "123R" → 123) */
|
||||
objNum: number
|
||||
type: MarkupType
|
||||
quads: number[][]
|
||||
rect: [number, number, number, number]
|
||||
}
|
||||
|
||||
/** Pending deletion of a saved markup or note annotation */
|
||||
export interface LocalAnnotDelete {
|
||||
id: string
|
||||
annot: SavedMarkupAnnot | SavedNoteAnnot
|
||||
}
|
||||
|
||||
/** Pending in-place content edit of a note comment saved in the file.
|
||||
`annot.contents` stays the on-disk text — the save path matches by it. */
|
||||
export interface LocalNoteEdit {
|
||||
id: string
|
||||
annot: SavedNoteAnnot
|
||||
contents: string
|
||||
}
|
||||
|
||||
export interface EditSnapshot {
|
||||
markups: LocalMarkup[]
|
||||
annotDeletes: LocalAnnotDelete[]
|
||||
noteEdits: LocalNoteEdit[]
|
||||
drawings: LocalDrawing[]
|
||||
textEdits: LocalTextEdit[]
|
||||
textInserts: LocalTextInsert[]
|
||||
imageEdits: LocalImageEdit[]
|
||||
stampCfg: StampConfig | null
|
||||
formEdits: Map<string, FormValueInput>
|
||||
rotations: Map<number, number>
|
||||
deleted: Set<number>
|
||||
order: number[] | null
|
||||
metadata: MetadataInput | null
|
||||
}
|
||||
|
||||
/** What a running save wrote, captured when the save starts. The post-save reload
|
||||
subtracts exactly this instead of wiping all edit state, so anything the user did
|
||||
while the write was in flight stays pending on the reloaded document. */
|
||||
export interface SavedSnapshot {
|
||||
markupIds: Set<string>
|
||||
annotDeleteIds: Set<string>
|
||||
noteEditIds: Set<string>
|
||||
/** objNum → /Contents this save wrote via noteEdits. A re-edit of the same note made
|
||||
while the write was in flight still carries the pre-save on-disk text as its match
|
||||
key; the post-save subtraction retargets it to what the file now says. */
|
||||
noteEditWritten: Map<number, string>
|
||||
drawingIds: Set<string>
|
||||
textEditIds: Set<string>
|
||||
textInsertIds: Set<string>
|
||||
imageEditIds: Set<string>
|
||||
stampCfg: StampConfig | null
|
||||
formEdits: Map<string, FormValueInput>
|
||||
rotations: Map<number, number>
|
||||
metadata: MetadataInput | null
|
||||
/** Old original page index → its index in the saved file (saved deletions/reorder applied) */
|
||||
pageMap: Map<number, number>
|
||||
}
|
||||
|
||||
/** Selected annotation with the anchor of its floating delete popup; a stamp click selects the whole watermark/header-footer set */
|
||||
export type AnnotSelection =
|
||||
| {
|
||||
kind: 'markup' | 'drawing' | 'textEdit' | 'textInsert' | 'imageEdit'
|
||||
id: string
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
| { kind: 'savedMarkup'; annot: SavedMarkupAnnot; x: number; y: number }
|
||||
| { kind: 'pageImage'; ref: PageImageRef; x: number; y: number }
|
||||
| { kind: 'stamp'; x: number; y: number }
|
||||
@@ -10,6 +10,8 @@ const fillFormStrings = {
|
||||
deleteInsertedText: 'Delete inserted text',
|
||||
insertedTextDeleted: 'Inserted text deleted',
|
||||
textInsertSkipped: 'Inserted text could not be saved on page(s): {pages}',
|
||||
textInsertNoFont:
|
||||
'No installed font can draw this text in the PDF (emoji and special symbols are not supported)',
|
||||
formComplete: 'Finish filling',
|
||||
formMissingRequired: '{count} required fields are still empty',
|
||||
formCompleteDone: 'Form completion check passed',
|
||||
@@ -46,6 +48,7 @@ const localizedFillFormStrings = {
|
||||
deleteInsertedText: '删除插入的文字',
|
||||
insertedTextDeleted: '已删除插入的文字',
|
||||
textInsertSkipped: '第 {pages} 页的插入文字无法保存',
|
||||
textInsertNoFont: '没有字体能在 PDF 中绘制这段文字(暂不支持 emoji 等特殊符号)',
|
||||
formComplete: '完成填写',
|
||||
formMissingRequired: '还有 {count} 个必填字段未填写',
|
||||
formCompleteDone: '表单填写检查完成',
|
||||
@@ -79,6 +82,7 @@ const localizedFillFormStrings = {
|
||||
deleteInsertedText: '刪除插入的文字',
|
||||
insertedTextDeleted: '已刪除插入的文字',
|
||||
textInsertSkipped: '第 {pages} 頁的插入文字無法儲存',
|
||||
textInsertNoFont: '沒有字體能在 PDF 中繪製這段文字(暫不支援 emoji 等特殊符號)',
|
||||
formComplete: '完成填寫',
|
||||
formMissingRequired: '還有 {count} 個必填欄位未填寫',
|
||||
formCompleteDone: '表單填寫檢查完成',
|
||||
@@ -238,6 +242,7 @@ export const strings = {
|
||||
aiToolImageSearch: '搜索图片"{query}"',
|
||||
aiToolGenImage: '生成图片',
|
||||
aiToolListImages: '读取文档图片',
|
||||
aiToolInsertText: '插入文字到第 {page} 页',
|
||||
aiToolInsertImage: '插入图片到第 {page} 页',
|
||||
aiToolMoveImage: '调整第 {page} 页的图片',
|
||||
aiToolRotateImage: '旋转第 {page} 页的图片',
|
||||
@@ -476,6 +481,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'Search images "{query}"',
|
||||
aiToolGenImage: 'Generate image',
|
||||
aiToolListImages: 'List document images',
|
||||
aiToolInsertText: 'Insert text on page {page}',
|
||||
aiToolInsertImage: 'Insert image on page {page}',
|
||||
aiToolMoveImage: 'Adjust image on page {page}',
|
||||
aiToolRotateImage: 'Rotate image on page {page}',
|
||||
@@ -716,6 +722,7 @@ export const strings = {
|
||||
aiToolImageSearch: '画像を検索「{query}」',
|
||||
aiToolGenImage: '画像を生成',
|
||||
aiToolListImages: '文書内の画像を取得',
|
||||
aiToolInsertText: 'ページ {page} にテキストを挿入',
|
||||
aiToolInsertImage: 'ページ {page} に画像を挿入',
|
||||
aiToolMoveImage: 'ページ {page} の画像を調整',
|
||||
aiToolRotateImage: 'ページ {page} の画像を回転',
|
||||
@@ -956,6 +963,7 @@ export const strings = {
|
||||
aiToolImageSearch: '이미지 검색 "{query}"',
|
||||
aiToolGenImage: '이미지 생성',
|
||||
aiToolListImages: '문서 이미지 읽기',
|
||||
aiToolInsertText: '{page}페이지에 텍스트 삽입',
|
||||
aiToolInsertImage: '{page}페이지에 이미지 삽입',
|
||||
aiToolMoveImage: '{page}페이지의 이미지 조정',
|
||||
aiToolRotateImage: '{page}페이지 이미지 회전',
|
||||
@@ -1197,6 +1205,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'Rechercher des images « {query} »',
|
||||
aiToolGenImage: 'Générer une image',
|
||||
aiToolListImages: 'Lire les images du document',
|
||||
aiToolInsertText: 'Insérer du texte page {page}',
|
||||
aiToolInsertImage: 'Insérer une image page {page}',
|
||||
aiToolMoveImage: 'Ajuster une image page {page}',
|
||||
aiToolRotateImage: "Rotation de l'image page {page}",
|
||||
@@ -1441,6 +1450,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'Bilder suchen „{query}"',
|
||||
aiToolGenImage: 'Bild generieren',
|
||||
aiToolListImages: 'Dokumentbilder lesen',
|
||||
aiToolInsertText: 'Text auf Seite {page} einfügen',
|
||||
aiToolInsertImage: 'Bild auf Seite {page} einfügen',
|
||||
aiToolMoveImage: 'Bild auf Seite {page} anpassen',
|
||||
aiToolRotateImage: 'Bild auf Seite {page} drehen',
|
||||
@@ -1683,6 +1693,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'Buscar imágenes "{query}"',
|
||||
aiToolGenImage: 'Generar imagen',
|
||||
aiToolListImages: 'Leer las imágenes del documento',
|
||||
aiToolInsertText: 'Insertar texto en la página {page}',
|
||||
aiToolInsertImage: 'Insertar imagen en la página {page}',
|
||||
aiToolMoveImage: 'Ajustar imagen en la página {page}',
|
||||
aiToolRotateImage: 'Girar imagen de la página {page}',
|
||||
@@ -1925,6 +1936,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'ค้นหารูปภาพ "{query}"',
|
||||
aiToolGenImage: 'สร้างรูปภาพ',
|
||||
aiToolListImages: 'อ่านรูปภาพในเอกสาร',
|
||||
aiToolInsertText: 'แทรกข้อความในหน้า {page}',
|
||||
aiToolInsertImage: 'แทรกรูปภาพในหน้า {page}',
|
||||
aiToolMoveImage: 'ปรับรูปภาพในหน้า {page}',
|
||||
aiToolRotateImage: 'หมุนรูปภาพหน้า {page}',
|
||||
@@ -2165,6 +2177,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'Cari gambar "{query}"',
|
||||
aiToolGenImage: 'Buat gambar',
|
||||
aiToolListImages: 'Baca gambar dokumen',
|
||||
aiToolInsertText: 'Sisipkan teks di halaman {page}',
|
||||
aiToolInsertImage: 'Sisipkan gambar di halaman {page}',
|
||||
aiToolMoveImage: 'Sesuaikan gambar di halaman {page}',
|
||||
aiToolRotateImage: 'Memutar gambar di halaman {page}',
|
||||
@@ -2407,6 +2420,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'Поиск изображений «{query}»',
|
||||
aiToolGenImage: 'Генерация изображения',
|
||||
aiToolListImages: 'Чтение изображений документа',
|
||||
aiToolInsertText: 'Вставка текста на стр. {page}',
|
||||
aiToolInsertImage: 'Вставка изображения на стр. {page}',
|
||||
aiToolMoveImage: 'Правка изображения на стр. {page}',
|
||||
aiToolRotateImage: 'Поворот изображения на стр. {page}',
|
||||
@@ -2649,6 +2663,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'البحث عن صور "{query}"',
|
||||
aiToolGenImage: 'إنشاء صورة',
|
||||
aiToolListImages: 'قراءة صور المستند',
|
||||
aiToolInsertText: 'إدراج نص في الصفحة {page}',
|
||||
aiToolInsertImage: 'إدراج صورة في الصفحة {page}',
|
||||
aiToolMoveImage: 'تعديل صورة في الصفحة {page}',
|
||||
aiToolRotateImage: 'تدوير الصورة في الصفحة {page}',
|
||||
@@ -2889,6 +2904,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'Pesquisar imagens "{query}"',
|
||||
aiToolGenImage: 'Gerar imagem',
|
||||
aiToolListImages: 'Ler as imagens do documento',
|
||||
aiToolInsertText: 'Inserir texto na página {page}',
|
||||
aiToolInsertImage: 'Inserir imagem na página {page}',
|
||||
aiToolMoveImage: 'Ajustar imagem na página {page}',
|
||||
aiToolRotateImage: 'Girar imagem da página {page}',
|
||||
@@ -3132,6 +3148,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'Cerca immagini "{query}"',
|
||||
aiToolGenImage: 'Genera immagine',
|
||||
aiToolListImages: 'Leggi le immagini del documento',
|
||||
aiToolInsertText: 'Inserisci testo a pagina {page}',
|
||||
aiToolInsertImage: 'Inserisci immagine a pagina {page}',
|
||||
aiToolMoveImage: 'Regola immagine a pagina {page}',
|
||||
aiToolRotateImage: 'Ruota immagine a pagina {page}',
|
||||
@@ -3376,6 +3393,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'Szukaj obrazów „{query}"',
|
||||
aiToolGenImage: 'Generuj obraz',
|
||||
aiToolListImages: 'Odczytaj obrazy dokumentu',
|
||||
aiToolInsertText: 'Wstaw tekst na stronie {page}',
|
||||
aiToolInsertImage: 'Wstaw obraz na stronie {page}',
|
||||
aiToolMoveImage: 'Dostosuj obraz na stronie {page}',
|
||||
aiToolRotateImage: 'Obrót obrazu na stronie {page}',
|
||||
@@ -3620,6 +3638,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'Afbeeldingen zoeken "{query}"',
|
||||
aiToolGenImage: 'Afbeelding genereren',
|
||||
aiToolListImages: 'Documentafbeeldingen lezen',
|
||||
aiToolInsertText: 'Tekst invoegen op pagina {page}',
|
||||
aiToolInsertImage: 'Afbeelding invoegen op pagina {page}',
|
||||
aiToolMoveImage: 'Afbeelding aanpassen op pagina {page}',
|
||||
aiToolRotateImage: 'Afbeelding op pagina {page} draaien',
|
||||
@@ -3862,6 +3881,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'Cari imej "{query}"',
|
||||
aiToolGenImage: 'Jana imej',
|
||||
aiToolListImages: 'Baca imej dokumen',
|
||||
aiToolInsertText: 'Sisipkan teks pada halaman {page}',
|
||||
aiToolInsertImage: 'Sisipkan imej pada halaman {page}',
|
||||
aiToolMoveImage: 'Laraskan imej pada halaman {page}',
|
||||
aiToolRotateImage: 'Memutar imej di halaman {page}',
|
||||
@@ -4100,6 +4120,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'חיפוש תמונות "{query}"',
|
||||
aiToolGenImage: 'יצירת תמונה',
|
||||
aiToolListImages: 'קריאת תמונות המסמך',
|
||||
aiToolInsertText: 'הוספת טקסט בעמוד {page}',
|
||||
aiToolInsertImage: 'הוספת תמונה בעמוד {page}',
|
||||
aiToolMoveImage: 'התאמת תמונה בעמוד {page}',
|
||||
aiToolRotateImage: 'סיבוב תמונה בעמוד {page}',
|
||||
@@ -4339,6 +4360,7 @@ export const strings = {
|
||||
aiToolImageSearch: 'छवियां खोजें "{query}"',
|
||||
aiToolGenImage: 'छवि बनाएं',
|
||||
aiToolListImages: 'दस्तावेज़ की छवियां पढ़ें',
|
||||
aiToolInsertText: 'पृष्ठ {page} पर टेक्स्ट डालें',
|
||||
aiToolInsertImage: 'पृष्ठ {page} पर छवि डालें',
|
||||
aiToolMoveImage: 'पृष्ठ {page} की छवि समायोजित करें',
|
||||
aiToolRotateImage: 'पृष्ठ {page} की छवि घुमाएँ',
|
||||
@@ -4576,6 +4598,7 @@ export const strings = {
|
||||
aiToolImageSearch: '搜尋圖片「{query}」',
|
||||
aiToolGenImage: '生成圖片',
|
||||
aiToolListImages: '讀取文件圖片',
|
||||
aiToolInsertText: '插入文字到第 {page} 頁',
|
||||
aiToolInsertImage: '插入圖片到第 {page} 頁',
|
||||
aiToolMoveImage: '調整第 {page} 頁的圖片',
|
||||
aiToolRotateImage: '旋轉第 {page} 頁的圖片',
|
||||
|
||||
@@ -0,0 +1,495 @@
|
||||
import type { ReactElement, ReactNode } from 'react'
|
||||
|
||||
// ── ribbon icons (aligned with slides' rb-big visual language) ──
|
||||
|
||||
/** Constant painted stroke instead of proportional scaling — same rule as the
|
||||
* slides icons: ~1.5px lines at 20px+, ~1.25px on 13-19px glyphs, ~1.1px below.
|
||||
* stroke-width is in 24-canvas units: units = painted-px × 24 / rendered-px. */
|
||||
export function pinnedStroke(size: number): number {
|
||||
const painted = size >= 20 ? 1.5 : size >= 13 ? 1.25 : 1.1
|
||||
return (painted * 24) / size
|
||||
}
|
||||
|
||||
export function Icon({
|
||||
size = 28,
|
||||
children,
|
||||
}: {
|
||||
size?: number
|
||||
children: ReactNode
|
||||
}): ReactElement {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={pinnedStroke(size)}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden
|
||||
>
|
||||
{children}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export const IconThumbs = () => (
|
||||
<Icon>
|
||||
<rect x="4.5" y="5" width="6" height="6.5" rx="1" />
|
||||
<rect x="4.5" y="14" width="6" height="5" rx="1" />
|
||||
<path d="M14 6 L19.5 6 M14 10 L19.5 10 M14 15 L19.5 15 M14 18 L19.5 18" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconHighlight = () => (
|
||||
<Icon>
|
||||
<path d="M6.04 15.09 L13.54 7.59 L16.63 10.68 L9.13 18.18 L6.04 18.18 L6.04 15.09 Z" />
|
||||
<path d="M13.54 6.71 L15.75 4.5 L18.84 7.59 L16.63 9.79" />
|
||||
<path d="M5.16 19.5 L17.51 19.5" strokeWidth={2.2} />
|
||||
</Icon>
|
||||
)
|
||||
export const IconUnderline = () => (
|
||||
<Icon>
|
||||
<path d="M7.56 4.5 L7.56 11.17 A 4.44 4.44 0 0 0 16.44 11.17 L16.44 4.5" />
|
||||
<path d="M5.89 19.5 L18.11 19.5" strokeWidth={1.85} />
|
||||
</Icon>
|
||||
)
|
||||
export const IconStrike = () => (
|
||||
<Icon>
|
||||
<path d="M16.29 7.21 C15.72 5.52 14.03 4.5 12 4.5 C9.52 4.5 7.71 5.85 7.71 7.88 C7.71 9.46 8.73 10.36 10.65 10.93" />
|
||||
<path d="M8.62 16.91 C9.18 18.48 10.87 19.5 13.02 19.5 C15.5 19.5 17.41 18.26 17.41 16.12 C17.41 15.44 17.3 14.88 16.96 14.42" />
|
||||
<path d="M4.67 12.28 L19.33 12.28" strokeWidth={1.65} />
|
||||
</Icon>
|
||||
)
|
||||
export const IconEditText = () => (
|
||||
<Icon>
|
||||
<path d="M5 5.5 L14.5 5.5 M9.75 5.5 L9.75 15.5 M7.5 15.5 L12 15.5" />
|
||||
<path d="M16.7 10.3 L19.7 13.3 L13.4 19.6 L10.4 20.1 L10.9 17.1 Z" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconInk = () => (
|
||||
<Icon>
|
||||
<path d="M16.15 4.85 L19.15 7.85 L8.9 18.1 L4.9 19.1 L5.9 15.1 Z" />
|
||||
<path d="M14.15 6.85 L17.15 9.85" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconRect = () => (
|
||||
<Icon>
|
||||
<rect x="4.5" y="6.64" width="15" height="10.71" rx="1.07" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconEllipse = () => (
|
||||
<Icon>
|
||||
<ellipse cx="12" cy="12" rx="7.5" ry="5.57" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconArrow = () => (
|
||||
<Icon>
|
||||
<path d="M4.5 19.2 L19.5 4.8" />
|
||||
<path d="M12.9 4.8 L19.5 4.8 L19.5 11.4" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconNote = () => (
|
||||
<Icon>
|
||||
<path d="M4.5 5.57 L19.5 5.57 L19.5 15.21 L10.93 15.21 L6.64 18.43 L6.64 15.21 L4.5 15.21 Z" />
|
||||
<path d="M8.25 9.32 L15.75 9.32 M8.25 12 L13.07 12" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconSign = () => (
|
||||
<Icon>
|
||||
<path d="M5.5 15.1 C7.8 12.3 9.5 9 9.2 7 C9 5.7 7.9 5.9 7.6 7.4 C7.2 9.6 8.6 13.4 10.5 14.9 C12 16.1 13.9 15.3 14.7 13.8 C15.1 13 15.9 13 16.3 13.8 C16.7 14.7 17.7 15 18.5 14.4" />
|
||||
<path d="M4.75 18.6 L19.25 18.6" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconPreviousField = () => (
|
||||
<Icon>
|
||||
<rect x="6" y="4.5" width="12" height="15" rx="1.5" />
|
||||
<path d="M14.5 8 L10.5 12 L14.5 16" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconNextField = () => (
|
||||
<Icon>
|
||||
<rect x="6" y="4.5" width="12" height="15" rx="1.5" />
|
||||
<path d="M9.5 8 L13.5 12 L9.5 16" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconCompleteForm = () => (
|
||||
<Icon>
|
||||
<rect x="4.5" y="5" width="15" height="14" rx="1.5" />
|
||||
<path d="M8 12 L10.8 14.8 L16.5 9" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconFormText = () => (
|
||||
<Icon>
|
||||
<path d="M5 6 H19 M12 6 V19 M8.5 19 H15.5" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconFormCheck = () => (
|
||||
<Icon>
|
||||
<path d="M4.5 12.5 L9.5 17.5 L19.5 6.5" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconFormCross = () => (
|
||||
<Icon>
|
||||
<path d="M6 6 L18 18 M18 6 L6 18" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconExportImg = () => (
|
||||
<Icon>
|
||||
<rect x="4.5" y="6.75" width="15" height="10.5" rx="1" />
|
||||
<circle cx="9" cy="10.55" r="1.2" />
|
||||
<path d="M4.8 14.95 L9 11.75 L12.4 14.35 L15 12.35 L19.2 15.75" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconInsertImage = () => (
|
||||
<Icon>
|
||||
<rect x="4.5" y="6" width="11.5" height="9.5" rx="1" />
|
||||
<circle cx="8" cy="9.2" r="1.1" />
|
||||
<path d="M4.8 13.6 L8 11.2 L11 13.4 L13.2 11.8 L15.8 13.9" />
|
||||
<path d="M18.6 13.4 V19 M15.8 16.2 H21.4" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconEditImage = () => (
|
||||
<Icon>
|
||||
<rect x="4.5" y="6" width="12.5" height="10" rx="1" />
|
||||
<circle cx="8.3" cy="9.4" r="1.1" />
|
||||
<path d="M4.8 14 L8.3 11.4 L11.5 13.7 L13.8 12" />
|
||||
<path d="M14.2 18.9 L19.7 13.4 A1.06 1.06 0 0 0 18.2 11.9 L12.7 17.4 L12.2 19.4 Z" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconNight = () => (
|
||||
<Icon>
|
||||
<path d="M19.5 13.48 A 7.58 7.58 0 0 1 10.52 4.5 A 7.58 7.58 0 1 0 19.5 13.48 Z" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconSpread = () => (
|
||||
<Icon>
|
||||
<rect x="4.5" y="6" width="6.5" height="12" rx="1" />
|
||||
<rect x="13" y="6" width="6.5" height="12" rx="1" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconSinglePage = () => (
|
||||
<Icon>
|
||||
<rect x="6.81" y="4.5" width="10.38" height="15" rx="1.15" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconWatermark = () => (
|
||||
<Icon>
|
||||
<rect x="4.5" y="5.04" width="15" height="13.93" rx="1.07" />
|
||||
<path d="M7.71 15.75 L15.75 7.71" />
|
||||
<path d="M7.71 11.46 L11.46 7.71 M12.54 15.75 L16.29 12" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconProps = () => (
|
||||
<Icon>
|
||||
<circle cx="12" cy="12" r="7.5" />
|
||||
<path d="M12 10.96 L12 15.65" />
|
||||
<circle cx="12" cy="8.46" r="0.94" fill="currentColor" stroke="none" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconRotateL = () => (
|
||||
<Icon>
|
||||
<path d="M8.28 10.3 L4.53 10.3 L4.53 6.55" />
|
||||
<path d="M4.75 9.98 A 7.5 7.5 0 1 1 4.53 12.98" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconRotateR = () => (
|
||||
<Icon>
|
||||
<path d="M15.72 10.3 L19.47 10.3 L19.47 6.55" />
|
||||
<path d="M19.25 9.98 A 7.5 7.5 0 1 0 19.47 12.98" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconDeletePage = () => (
|
||||
<Icon>
|
||||
<path d="M7.7 4.5 H13.7 L17.2 8 V18.5 A1 1 0 0 1 16.2 19.5 H7.7 A1 1 0 0 1 6.7 18.5 V5.5 A1 1 0 0 1 7.7 4.5 Z" />
|
||||
<path d="M13.7 4.5 V8 H17.2" />
|
||||
<path d="M9.7 11.75 L14.2 16.25 M14.2 11.75 L9.7 16.25" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconExtract = () => (
|
||||
<Icon>
|
||||
<path d="M7.2 4.5 H13.2 L16.7 8 V11.5" />
|
||||
<path d="M6.2 5.5 V18.5 A1 1 0 0 0 7.2 19.5 H11.2" />
|
||||
<path d="M14.95 13.5 V19 M12.2 16.5 L14.95 19.25 L17.7 16.5" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconInsertPdf = () => (
|
||||
<Icon>
|
||||
<path d="M7.7 4.5 H13.7 L17.2 8 V18.5 A1 1 0 0 1 16.2 19.5 H7.7 A1 1 0 0 1 6.7 18.5 V5.5 A1 1 0 0 1 7.7 4.5 Z" />
|
||||
<path d="M13.7 4.5 V8 H17.2" />
|
||||
<path d="M11.95 11 V17 M8.95 14 H14.95" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconInsertBlank = () => (
|
||||
<Icon>
|
||||
<rect x="6.7" y="4.5" width="10.5" height="15" rx="1" strokeDasharray="2.2 1.8" />
|
||||
<path d="M11.95 9.5 V14.5 M9.45 12 H14.45" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconRotateAll = () => (
|
||||
<Icon>
|
||||
<rect x="8.5" y="8.5" width="7" height="9" rx="0.8" />
|
||||
<path d="M6.2 6.2 A 8.2 8.2 0 0 1 17.8 6.2" />
|
||||
<path d="M17.8 3.4 L17.8 6.4 L14.8 6.4" />
|
||||
<path d="M17.8 17.8 A 8.2 8.2 0 0 1 6.2 17.8" />
|
||||
<path d="M6.2 20.6 L6.2 17.6 L9.2 17.6" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconReverse = () => (
|
||||
<Icon>
|
||||
<path d="M9 5.5 L9 18 M6.5 8 L9 5.5 L11.5 8" />
|
||||
<path d="M15 6 L15 18.5 M12.5 16 L15 18.5 L17.5 16" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconSplitPdf = () => (
|
||||
<Icon>
|
||||
<rect x="4.5" y="6.5" width="6.2" height="11" rx="0.8" />
|
||||
<rect x="13.3" y="6.5" width="6.2" height="11" rx="0.8" />
|
||||
<path d="M12 4.6 V7 M12 9.4 V11.8 M12 14.2 V16.6 M12 19 V19.4" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconMergePdf = () => (
|
||||
<Icon>
|
||||
<path d="M4.5 6.5 H8.5 V17.5 H4.5 Z" />
|
||||
<path d="M15.5 6.5 H19.5 V17.5 H15.5 Z" />
|
||||
<path d="M10 9 L12 12 L10 15 M14 9 L12 12 L14 15" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconMergePages = () => (
|
||||
<Icon>
|
||||
<rect x="5" y="4.5" width="14" height="15" rx="1" />
|
||||
<path d="M12 4.5 V19.5 M5 12 H19" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const IconReplacePages = () => (
|
||||
<Icon>
|
||||
<rect x="4.5" y="7.5" width="9" height="12" rx="1" />
|
||||
<rect x="10.5" y="4.5" width="9" height="12" rx="1" strokeDasharray="2.2 1.8" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconSplitPages = () => (
|
||||
<Icon>
|
||||
<rect x="5" y="4.5" width="14" height="15" rx="1" />
|
||||
<path d="M12 4.5 V19.5" strokeDasharray="2.2 1.8" />
|
||||
<path d="M8.2 12 L5.8 12 M6.6 10.8 L5.4 12 L6.6 13.2 M15.8 12 L18.2 12 M17.4 10.8 L18.6 12 L17.4 13.2" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconCropPages = () => (
|
||||
<Icon>
|
||||
<path d="M7.5 4.5 V16.5 H19.5" />
|
||||
<path d="M4.5 7.5 H16.5 V19.5" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconPageSize = () => (
|
||||
<Icon>
|
||||
<rect x="4.5" y="4.5" width="15" height="15" rx="1" />
|
||||
<rect x="8.5" y="8.5" width="7" height="9" rx="0.8" strokeDasharray="2 1.6" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconFitWidth = () => (
|
||||
<Icon>
|
||||
<path d="M4.5 5.57 L4.5 18.43 M19.5 5.57 L19.5 18.43" />
|
||||
<path d="M7.71 12 L16.29 12 M10.07 9.64 L7.71 12 L10.07 14.36 M13.93 9.64 L16.29 12 L13.93 14.36" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconFitPage = () => (
|
||||
<Icon>
|
||||
<rect x="7" y="4.5" width="10" height="15" rx="1" />
|
||||
<path d="M12 8 L12 16 M9.8 10.2 L12 8 L14.2 10.2 M9.8 13.8 L12 16 L14.2 13.8" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconOutline = () => (
|
||||
<Icon>
|
||||
<path d="M4.84 4.78 L19.5 4.78 M8.22 9.29 L19.5 9.29 M8.22 13.8 L19.5 13.8 M11.61 18.32 L19.5 18.32" />
|
||||
<circle cx="5.4" cy="9.29" r="0.9" fill="currentColor" stroke="none" />
|
||||
<circle cx="5.4" cy="13.8" r="0.9" fill="currentColor" stroke="none" />
|
||||
<circle cx="8.79" cy="18.32" r="0.9" fill="currentColor" stroke="none" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconDrawColor = () => (
|
||||
<Icon>
|
||||
<path d="M12 4.5 C14.2 7.3 17.25 9.2 17.25 12.4 C17.25 15.4 14.9 17.5 12 17.5 C9.1 17.5 6.75 15.4 6.75 12.4 C6.75 9.2 9.8 7.3 12 4.5 Z" />
|
||||
</Icon>
|
||||
)
|
||||
/* dropdown chevron, same glyph as slides' RbCaret */
|
||||
export const RbCaret = () => (
|
||||
<svg className="rb-caret" width="10" height="10" viewBox="0 0 24 24" fill="none" aria-hidden>
|
||||
<path
|
||||
d="M5.5 9.25 12 15.75l6.5-6.5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2.6"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
export const IconSearch = () => (
|
||||
<Icon>
|
||||
<circle cx="10.61" cy="10.61" r="6.11" />
|
||||
<path d="M15.28 15.28 L19.5 19.5" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconPrint = () => (
|
||||
<Icon>
|
||||
<path d="M7.71 8.79 L7.71 4.5 L16.29 4.5 L16.29 8.79" />
|
||||
<rect x="5.04" y="8.79" width="13.93" height="6.96" rx="1.07" />
|
||||
<path d="M7.71 13.07 L16.29 13.07 L16.29 19.5 L7.71 19.5 Z" />
|
||||
</Icon>
|
||||
)
|
||||
/** Design-supplied glyphs on the 1:16 stroke:canvas ratio (24-canvas / 1.5 stroke),
|
||||
* geometry shared with docs/slides/sheets. */
|
||||
export const IconRatio = ({ size = 16, children }: { size?: number; children: ReactNode }) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden
|
||||
>
|
||||
{children}
|
||||
</svg>
|
||||
)
|
||||
export const IconUndo = () => (
|
||||
<IconRatio>
|
||||
<path d="M5.91026 4L2.5 7.14791L5.91026 10.8205" />
|
||||
<path d="M3.96154 7.41028H15.1636C18.5169 7.41028 21.3646 10.1484 21.4953 13.5C21.6334 17.0416 18.707 20.0769 15.1636 20.0769H6.88384" />
|
||||
</IconRatio>
|
||||
)
|
||||
export const IconRedo = () => (
|
||||
<IconRatio>
|
||||
<path d="M18.0897 4L21.5 7.14791L18.0897 10.8205" />
|
||||
<path d="M20.0385 7.41028H8.83636C5.4831 7.41028 2.63537 10.1484 2.5047 13.5C2.36657 17.0416 5.29296 20.0769 8.83636 20.0769H17.1162" />
|
||||
</IconRatio>
|
||||
)
|
||||
export const IconSave = () => (
|
||||
<IconRatio>
|
||||
<path d="M3 4.5C3 3.67158 3.67158 3 4.5 3H17.1407L21 6.60325V19.5C21 20.3285 20.3285 21 19.5 21H4.5C3.67158 21 3 20.3285 3 19.5V4.5Z" />
|
||||
<path d="M12.0042 3L12 6.6923C12 6.86225 11.7761 7 11.5 7H7.5C7.22385 7 7 6.86225 7 6.6923V3H12.0042Z" />
|
||||
<path d="M7 13H17" />
|
||||
<path d="M7 17H12.0042" />
|
||||
</IconRatio>
|
||||
)
|
||||
|
||||
// ── selection-popup icons (14px; bring-forward / send-backward / trash) ──
|
||||
|
||||
export const IconLayerUp = () => (
|
||||
<Icon size={18}>
|
||||
<rect x="9.5" y="4.5" width="10" height="10" rx="1" />
|
||||
<path d="M14.5 19.5 H5.5 A1 1 0 0 1 4.5 18.5 V9.5" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconLayerDown = () => (
|
||||
<Icon size={18}>
|
||||
<rect x="4.5" y="9.5" width="10" height="10" rx="1" />
|
||||
<path d="M9.5 4.5 H18.5 A1 1 0 0 1 19.5 5.5 V14.5" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconTrash = () => (
|
||||
<Icon size={18}>
|
||||
<path d="M4.5 6.5 H19.5" />
|
||||
<path d="M9 6.5 V5 A1 1 0 0 1 10 4 H14 A1 1 0 0 1 15 5 V6.5" />
|
||||
<path d="M6.5 6.5 L7.3 18.6 A1.4 1.4 0 0 0 8.7 19.9 H15.3 A1.4 1.4 0 0 0 16.7 18.6 L17.5 6.5" />
|
||||
<path d="M10.2 10 V16 M13.8 10 V16" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconRotateCw = () => (
|
||||
<Icon size={18}>
|
||||
<path d="M18.5 8.5 A7.5 7.5 0 1 0 19.5 12" />
|
||||
<path d="M19 4 V8.5 H14.5" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconRotateCcw = () => (
|
||||
<Icon size={18}>
|
||||
<path d="M5.5 8.5 A7.5 7.5 0 1 1 4.5 12" />
|
||||
<path d="M5 4 V8.5 H9.5" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconSwapImage = () => (
|
||||
<Icon size={18}>
|
||||
<rect x="4" y="6.5" width="11" height="11" rx="1" />
|
||||
<circle cx="7.5" cy="10" r="1.2" />
|
||||
<path d="M4.5 16 L8.5 12.5 L11 15 L12.5 13.5 L15 16" />
|
||||
<path d="M17 4.5 H19 A1 1 0 0 1 20 5.5 V13" />
|
||||
<path d="M18.2 11.2 L20 13 L21.8 11.2" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconFlipH = () => (
|
||||
<Icon size={18}>
|
||||
<path d="M12 3.5 V20.5" strokeDasharray="2.6 2.2" />
|
||||
<path d="M8.5 7 V17 L3.5 17 Z" />
|
||||
<path d="M15.5 7 V17 L20.5 17 Z" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconFlipV = () => (
|
||||
<Icon size={18}>
|
||||
<path d="M3.5 12 H20.5" strokeDasharray="2.6 2.2" />
|
||||
<path d="M7 8.5 H17 L17 3.5 Z" />
|
||||
<path d="M7 15.5 H17 L17 20.5 Z" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconCrop = () => (
|
||||
<Icon size={18}>
|
||||
<path d="M7 3.5 V17 H20.5" />
|
||||
<path d="M3.5 7 H17 V20.5" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconCutout = () => (
|
||||
<Icon size={18}>
|
||||
<path d="M13.5 6.5 L17.5 10.5 L8 20 H4 V16 Z" />
|
||||
<path d="M16 4 L20 8" />
|
||||
<path d="M18.5 12.5 L19.4 14.6 L21.5 15.5 L19.4 16.4 L18.5 18.5 L17.6 16.4 L15.5 15.5 L17.6 14.6 Z" />
|
||||
</Icon>
|
||||
)
|
||||
export const IconOpacity = () => (
|
||||
<Icon size={18}>
|
||||
<path d="M12 3.5 C12 3.5 5.5 10 5.5 14.5 A6.5 6.5 0 0 0 18.5 14.5 C18.5 10 12 3.5 12 3.5 Z" />
|
||||
<path d="M12 18.2 A3.7 3.7 0 0 1 8.3 14.5" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
/** One-click AI feature glyphs (same 24-canvas/1.5-stroke artwork as the docs ribbon) */
|
||||
export const IconAiSummarize = () => (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden
|
||||
>
|
||||
<path d="M13.875 21H12H6.5C5.39543 21 4.5 20.1046 4.5 19V5C4.5 3.89543 5.39543 3 6.5 3H17.5C18.6046 3 19.5 3.89543 19.5 5V9V12V13" />
|
||||
<path d="M8.00001 7H16" />
|
||||
<path d="M8.00007 10.2032H14.0001" />
|
||||
<path d="M8.00007 13.4062H12.0001" />
|
||||
<path
|
||||
d="M17 14L17.2579 14.697C17.5961 15.611 17.7652 16.068 18.0986 16.4014C18.432 16.7348 18.889 16.9039 19.803 17.2421L20.5 17.5L19.803 17.7579C18.889 18.0961 18.432 18.2652 18.0986 18.5986C17.7652 18.932 17.5961 19.389 17.2579 20.303L17 21L16.7421 20.303C16.4039 19.389 16.2348 18.932 15.9014 18.5986C15.568 18.2652 15.111 18.0961 14.197 17.7579L13.5 17.5L14.197 17.2421C15.111 16.9039 15.568 16.7348 15.9014 16.4014C16.2348 16.068 16.4039 15.611 16.7421 14.697L17 14Z"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
export const IconAiKeyPoints = () => (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden
|
||||
>
|
||||
<path d="M4 5H20" />
|
||||
<path d="M4 9H16" />
|
||||
<path d="M4 13H11" />
|
||||
<path d="M4 17H10" />
|
||||
<path
|
||||
d="M17 14L17.2579 14.697C17.5961 15.611 17.7652 16.068 18.0986 16.4014C18.432 16.7348 18.889 16.9039 19.803 17.2421L20.5 17.5L19.803 17.7579C18.889 18.0961 18.432 18.2652 18.0986 18.5986C17.7652 18.932 17.5961 19.389 17.2579 20.303L17 21L16.7421 20.303C16.4039 19.389 16.2348 18.932 15.9014 18.5986C15.568 18.2652 15.111 18.0961 14.197 17.7579L13.5 17.5L14.197 17.2421C15.111 16.9039 15.568 16.7348 15.9014 16.4014C16.2348 16.068 16.4039 15.611 16.7421 14.697L17 14Z"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user