Sync snapshot (2026-08-09) (#75)
- PDF: in-place text editing — paragraph block selection with reflow, bold/italic and alignment controls, selection-level text color, original-font preservation - PDF: AI image tools (search/generate, insert, transform, delete) plus image rotation and in-place replacement - Docs: picture rotation and mirror flips, in-place image byte swap for crop/background removal, and several Word-fidelity rendering fixes - Docs: fix a renderer hang on tab-heavy forms and a crash when exporting large documents - Slides: AI picture tools (crop, opacity, replace), picture border controls, in-place picture source swap - Linux: AppImage and deb packaging with stable/beta auto-update channels - Refresh the README and clean up internal design-audit artifacts Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
767b87bded
commit
e249c3ba81
@@ -73,6 +73,15 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
npm run format:check
|
npm run format:check
|
||||||
|
|
||||||
|
- name: Check theme colors
|
||||||
|
env:
|
||||||
|
FORMAT_BASE_REF: ${{ github.event.pull_request.base.sha || github.event.before }}
|
||||||
|
run: |
|
||||||
|
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
||||||
|
FORMAT_BASE_REF=$(git rev-parse HEAD^1)
|
||||||
|
fi
|
||||||
|
npm run check:theme-colors
|
||||||
|
|
||||||
- name: Lint
|
- name: Lint
|
||||||
run: npm run lint
|
run: npm run lint
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,329 @@
|
|||||||
|
name: Linux Build
|
||||||
|
|
||||||
|
# Linux counterpart of windows-build.yml / mac-build.yml: same trigger set,
|
||||||
|
# same determine-mode gate, GitHub Release per release build.
|
||||||
|
#
|
||||||
|
# Differences forced by the platform:
|
||||||
|
# - No code signing or notarization: Linux has no signing requirement, so
|
||||||
|
# the whole signing-mode machinery collapses to the is_release gate.
|
||||||
|
# - Two artifacts per build: AppImage (self-contained, any distro) and deb
|
||||||
|
# (apt install). Both come out of a single electron-builder --linux run;
|
||||||
|
# targets and deb metadata live in apps/shell/electron-builder.cjs.
|
||||||
|
# - Auto-update covers AppImage runs only: electron-updater's
|
||||||
|
# AppImageUpdater replaces the .AppImage in place; deb installs run no
|
||||||
|
# updater (users upgrade via `apt install ./<new>.deb`). Release builds
|
||||||
|
# bake GENOFFICE_UPDATE_URL into app-update.yml and publish the
|
||||||
|
# electron-updater feed to the CDN as beta-linux.yml (per-merge beta
|
||||||
|
# channel, same model as beta.yml / beta-mac.yml); latest-linux.yml and
|
||||||
|
# the GenOffice.AppImage / GenOffice.deb marketing aliases are written by
|
||||||
|
# the promote workflow (scripts/promote-stable.cjs --linux). Smoke builds
|
||||||
|
# get no publish config and no feed.
|
||||||
|
# - Version: same rule as Windows/mac — major.minor from
|
||||||
|
# apps/shell/package.json, patch = run number minus a per-train baseline.
|
||||||
|
# (The 0.5 train used a negative baseline to continue after the manually
|
||||||
|
# published linux-v0.5.149 release; from 0.6 on the baseline follows the
|
||||||
|
# same predicted-first-main-build rule as the other platforms.)
|
||||||
|
# - Release tags are prefixed linux-v so they never collide with the
|
||||||
|
# Windows workflow's v* tags or the mac workflow's mac-v* tags. The
|
||||||
|
# manually published linux-v0.5.149 already follows this scheme.
|
||||||
|
# - The xlsx sidecar needs no staging step: like mac, the linux
|
||||||
|
# extraResources entry points at cargo's host-native target/release
|
||||||
|
# output, which build:all produces on the ubuntu runner.
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main, 'dev_*', 'release_*']
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
# One build per branch at a time, newest push wins (same rationale as
|
||||||
|
# windows-build.yml / mac-build.yml).
|
||||||
|
concurrency:
|
||||||
|
group: linux-build-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write # for GitHub Release creation
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
# -------------------------------------------------------------- mode
|
||||||
|
# Same rule as windows-build.yml: main IS the release channel.
|
||||||
|
determine-mode:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
is_release: ${{ steps.mode.outputs.is_release }}
|
||||||
|
steps:
|
||||||
|
- id: mode
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
if [[ "${{ github.ref }}" == "refs/heads/main" || "${{ github.ref }}" =~ ^refs/heads/release_ ]]; then
|
||||||
|
echo "is_release=true" >> "$GITHUB_OUTPUT"
|
||||||
|
else
|
||||||
|
echo "is_release=false" >> "$GITHUB_OUTPUT"
|
||||||
|
fi
|
||||||
|
echo "ref=${{ github.ref }}"
|
||||||
|
|
||||||
|
# -------------------------------------------------------------- build
|
||||||
|
build:
|
||||||
|
needs: determine-mode
|
||||||
|
# 22.04, not -latest: the xlsx sidecar is compiled on the runner and
|
||||||
|
# links the host glibc. Building on 24.04 (glibc 2.39) would produce a
|
||||||
|
# sidecar that refuses to start on the Ubuntu 22.04 / glibc 2.34+ floor
|
||||||
|
# the README and release notes promise. x64 artifacts.
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
|
- name: Setup Node
|
||||||
|
uses: actions/setup-node@v7
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: package-lock.json
|
||||||
|
|
||||||
|
- name: Setup Rust
|
||||||
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
|
||||||
|
- name: Cache cargo (xlsx-sidecar)
|
||||||
|
uses: Swatinem/rust-cache@v2
|
||||||
|
with:
|
||||||
|
workspaces: apps/sheets/native/xlsx-engine
|
||||||
|
|
||||||
|
- name: Cache electron binaries
|
||||||
|
uses: actions/cache@v6
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cache/electron
|
||||||
|
~/.cache/electron-builder
|
||||||
|
key: electron-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
|
||||||
|
restore-keys: electron-${{ runner.os }}-
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
|
# ---- derive version FIRST so packaging can bake it in --------------
|
||||||
|
# major.minor from apps/shell/package.json, patch = run number minus a
|
||||||
|
# per-train baseline (same scheme as windows/mac). When bumping
|
||||||
|
# major.minor in package.json, set BASE to the predicted run number of
|
||||||
|
# the FIRST main build of the new train (the clamp below then covers a
|
||||||
|
# slightly-high prediction, same as the other platforms). The .0 clamp
|
||||||
|
# is guarded by a tag-exists check: only the train's FIRST release
|
||||||
|
# build may claim .0; a later release build still below the (padded)
|
||||||
|
# baseline fails fast here — fix by setting BASE to the run number of
|
||||||
|
# the build that published .0.
|
||||||
|
- name: Derive version + date
|
||||||
|
id: version
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
MM=$(node -p "require('./apps/shell/package.json').version.split('.').slice(0,2).join('.')")
|
||||||
|
BASE=70 # run number of the main build that published linux-v0.6.0
|
||||||
|
PATCH=$(( ${{ github.run_number }} - BASE ))
|
||||||
|
if [ "$PATCH" -lt 0 ]; then
|
||||||
|
if [ "${{ needs.determine-mode.outputs.is_release }}" = "true" ]; then
|
||||||
|
# ls-remote --exit-code: 0 = tag exists, 2 = absent (good path);
|
||||||
|
# anything else means the lookup failed — abort rather than
|
||||||
|
# risk re-claiming an existing .0.
|
||||||
|
RC=0; git ls-remote --exit-code origin "refs/tags/linux-v$MM.0" >/dev/null || RC=$?
|
||||||
|
if [ "$RC" -eq 0 ]; then
|
||||||
|
echo "::error::linux-v$MM.0 is already released but run ${{ github.run_number }} is still below BASE=$BASE — set BASE to the run number of the build that published linux-v$MM.0 so this train continues at .1, .2, ..."
|
||||||
|
exit 1
|
||||||
|
elif [ "$RC" -ne 2 ]; then
|
||||||
|
echo "::error::git ls-remote failed (exit $RC) while checking for tag linux-v$MM.0"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
FULL="$MM.0"
|
||||||
|
else
|
||||||
|
FULL="$MM.0-pre.${{ github.run_number }}"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
FULL="$MM.$PATCH"
|
||||||
|
fi
|
||||||
|
DATETIME="$(date -u '+%Y-%m-%d %H:%M:%S') UTC"
|
||||||
|
COMMIT="$(echo '${{ github.sha }}' | cut -c1-7)"
|
||||||
|
echo "full=$FULL" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "datetime=$DATETIME" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "commit=$COMMIT" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "Version=$FULL Datetime=$DATETIME Commit=$COMMIT"
|
||||||
|
|
||||||
|
# ---- build ----------------------------------------------------------
|
||||||
|
# Same order as Windows/mac: notices -> build:all (sheets' build runs
|
||||||
|
# `cargo build` for the sidecar; the linux extraResources path is the
|
||||||
|
# host target/release binary, so no staging step is needed).
|
||||||
|
- name: Build modules
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
npm run notices
|
||||||
|
npm run build:all
|
||||||
|
|
||||||
|
# ---- package (AppImage + deb, no signing) -----------------------
|
||||||
|
# Release builds inject GENOFFICE_UPDATE_URL so electron-builder bakes
|
||||||
|
# app-update.yml into the app and writes latest-linux.yml next to the
|
||||||
|
# artifacts (the updater feed the CDN publish step uploads as
|
||||||
|
# beta-linux.yml). Smoke builds omit it: no publish config, no feed,
|
||||||
|
# in-app auto-update stays disabled.
|
||||||
|
- name: Package (electron-builder AppImage+deb, with update feed)
|
||||||
|
if: needs.determine-mode.outputs.is_release == 'true'
|
||||||
|
working-directory: apps/shell
|
||||||
|
env:
|
||||||
|
GENOFFICE_UPDATE_URL: ${{ secrets.GENOFFICE_UPDATE_URL }}
|
||||||
|
run: npx electron-builder --linux "-c.extraMetadata.version=${{ steps.version.outputs.full }}"
|
||||||
|
|
||||||
|
- name: Package (electron-builder AppImage+deb, smoke)
|
||||||
|
if: needs.determine-mode.outputs.is_release != 'true'
|
||||||
|
working-directory: apps/shell
|
||||||
|
run: npx electron-builder --linux "-c.extraMetadata.version=${{ steps.version.outputs.full }}"
|
||||||
|
|
||||||
|
- name: Inspect output
|
||||||
|
id: artifact
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
cd apps/shell/release
|
||||||
|
ls -lh *.AppImage *.deb
|
||||||
|
# latest-linux.yml only exists when a publish config was present,
|
||||||
|
# i.e. release builds with GENOFFICE_UPDATE_URL injected — smoke
|
||||||
|
# builds intentionally have no update feed.
|
||||||
|
if [[ "${{ needs.determine-mode.outputs.is_release }}" == "true" ]]; then
|
||||||
|
ls -lh latest-linux.yml
|
||||||
|
fi
|
||||||
|
APPIMAGE=$(ls GenOffice-*.AppImage | head -n1)
|
||||||
|
DEB=$(ls genoffice_*.deb | head -n1)
|
||||||
|
echo "appimage_name=$APPIMAGE" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "deb_name=$DEB" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "appimage_size_mb=$(( $(stat -c%s "$APPIMAGE") / 1024 / 1024 ))" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "deb_size_mb=$(( $(stat -c%s "$DEB") / 1024 / 1024 ))" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "appimage_md5=$(md5sum "$APPIMAGE" | cut -d' ' -f1)" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "deb_md5=$(md5sum "$DEB" | cut -d' ' -f1)" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Upload workflow artifact
|
||||||
|
uses: actions/upload-artifact@v7.0.1
|
||||||
|
with:
|
||||||
|
name: genoffice-linux-v${{ steps.version.outputs.full }}
|
||||||
|
path: |
|
||||||
|
apps/shell/release/*.AppImage
|
||||||
|
apps/shell/release/*.deb
|
||||||
|
apps/shell/release/latest-linux.yml
|
||||||
|
retention-days: 30
|
||||||
|
|
||||||
|
# ---- CDN publish (release builds only) --------------------------
|
||||||
|
# Same model as mac: uploads AppImage + deb, rewrites feed URLs to
|
||||||
|
# absolute CDN paths, archives GenOffice-linux-<version>.yml for the
|
||||||
|
# promote workflow and moves beta-linux.yml last (no-cache). The
|
||||||
|
# GenOffice.AppImage / GenOffice.deb marketing aliases are NOT touched
|
||||||
|
# by beta publishes — the promote workflow re-points them. The script
|
||||||
|
# refuses to publish unless the version is strictly newer than the CDN's.
|
||||||
|
- name: Publish to CDN
|
||||||
|
if: needs.determine-mode.outputs.is_release == 'true'
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
AZURE_STORAGE_CONNECTION_STRING: ${{ secrets.AZURE_STORAGE_CONNECTION_STRING }}
|
||||||
|
GENOFFICE_UPDATE_URL: ${{ secrets.GENOFFICE_UPDATE_URL }}
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
# The storage container / blob prefix are substrings of the secret
|
||||||
|
# URL, so GitHub's automatic masking does not cover them — mask
|
||||||
|
# them explicitly before the upload script logs anything.
|
||||||
|
URL="${GENOFFICE_UPDATE_URL%/}"
|
||||||
|
REL="${URL#*://*/}"
|
||||||
|
echo "::add-mask::${REL%%/*}"
|
||||||
|
echo "::add-mask::${REL#*/}"
|
||||||
|
node scripts/linux-release-upload.cjs --channel beta
|
||||||
|
|
||||||
|
# ---- Job summary ------------------------------------------------
|
||||||
|
- name: Step summary
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
{
|
||||||
|
echo "## GenOffice Linux v${{ steps.version.outputs.full }}"
|
||||||
|
echo ""
|
||||||
|
echo "| Artifact | Size |"
|
||||||
|
echo "|----------|------|"
|
||||||
|
echo "| \`${{ steps.artifact.outputs.appimage_name }}\` | ${{ steps.artifact.outputs.appimage_size_mb }} MB |"
|
||||||
|
echo "| \`${{ steps.artifact.outputs.deb_name }}\` | ${{ steps.artifact.outputs.deb_size_mb }} MB |"
|
||||||
|
echo ""
|
||||||
|
if [[ "${{ needs.determine-mode.outputs.is_release }}" == "true" ]]; then
|
||||||
|
echo "Release build — published as GitHub Release \`linux-v${{ steps.version.outputs.full }}\`"
|
||||||
|
echo "and to the update CDN (feed \`beta-linux.yml\`; the stable feed and the"
|
||||||
|
echo "\`GenOffice.AppImage\` / \`GenOffice.deb\` aliases only move on promote)."
|
||||||
|
else
|
||||||
|
echo "Smoke build — workflow artifact only, no GitHub Release, no CDN."
|
||||||
|
fi
|
||||||
|
} >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|
||||||
|
# ---- Compose release-notes body -------------------------------
|
||||||
|
# Body format follows the manually published linux-v0.5.149 release
|
||||||
|
# (install instructions + MD5 lines) plus the build-metadata table the
|
||||||
|
# other platforms include.
|
||||||
|
- name: Compose release notes
|
||||||
|
if: needs.determine-mode.outputs.is_release == 'true'
|
||||||
|
id: notes
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
VER="${{ steps.version.outputs.full }}"
|
||||||
|
RUN_URL="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
||||||
|
COMMIT_URL="${{ github.server_url }}/${{ github.repository }}/commit/${{ github.sha }}"
|
||||||
|
APPIMAGE="${{ steps.artifact.outputs.appimage_name }}"
|
||||||
|
DEB="${{ steps.artifact.outputs.deb_name }}"
|
||||||
|
BODY="apps/shell/release/release-notes.md"
|
||||||
|
{
|
||||||
|
echo "## GenOffice Linux \`v${VER}\` (x64)"
|
||||||
|
echo ""
|
||||||
|
echo "AI-native office suite (Docs / Sheets / Slides / PDF) — AppImage + deb."
|
||||||
|
echo ""
|
||||||
|
echo "### Build metadata"
|
||||||
|
echo "| Field | Value |"
|
||||||
|
echo "|-------|-------|"
|
||||||
|
echo "| Version | \`${VER}\` |"
|
||||||
|
echo "| Built | \`${{ steps.version.outputs.datetime }}\` |"
|
||||||
|
echo "| Commit | [\`${{ steps.version.outputs.commit }}\`](${COMMIT_URL}) |"
|
||||||
|
echo "| Build ID | [${{ github.run_id }}](${RUN_URL}) |"
|
||||||
|
echo "| AppImage size | ${{ steps.artifact.outputs.appimage_size_mb }} MB |"
|
||||||
|
echo "| deb size | ${{ steps.artifact.outputs.deb_size_mb }} MB |"
|
||||||
|
echo ""
|
||||||
|
echo "## Debian / Ubuntu (recommended)"
|
||||||
|
echo ""
|
||||||
|
echo '```bash'
|
||||||
|
echo "sudo apt install ./${DEB}"
|
||||||
|
echo '```'
|
||||||
|
echo ""
|
||||||
|
echo "Installs dependencies automatically and adds GenOffice to the applications menu."
|
||||||
|
echo ""
|
||||||
|
echo "## Other distros (AppImage)"
|
||||||
|
echo ""
|
||||||
|
echo "Requirements: x86_64, glibc 2.34+ (Ubuntu 22.04 or newer), FUSE 2 runtime (\`libfuse2\`; on Ubuntu 24.04 \`libfuse2t64\`)."
|
||||||
|
echo ""
|
||||||
|
echo '```bash'
|
||||||
|
echo "chmod +x ${APPIMAGE}"
|
||||||
|
echo "./${APPIMAGE}"
|
||||||
|
echo '```'
|
||||||
|
echo ""
|
||||||
|
echo "MD5: AppImage ${{ steps.artifact.outputs.appimage_md5 }}, deb ${{ steps.artifact.outputs.deb_md5 }}"
|
||||||
|
echo ""
|
||||||
|
echo "In-app auto-update works for AppImage runs via \`beta-linux.yml\` (beta channel; the stable feed moves when a version is promoted). deb installs update via \`apt install\` with the newer package."
|
||||||
|
} > "$BODY"
|
||||||
|
cat "$BODY"
|
||||||
|
echo "path=$BODY" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
# ---- GitHub Release (release builds only) ----------------------
|
||||||
|
# Tag is prefixed linux-v: this workflow's run numbers are unrelated
|
||||||
|
# to the Windows/mac workflows', so sharing tag namespaces would
|
||||||
|
# collide.
|
||||||
|
- name: Create GitHub Release
|
||||||
|
if: needs.determine-mode.outputs.is_release == 'true'
|
||||||
|
uses: softprops/action-gh-release@v3
|
||||||
|
with:
|
||||||
|
tag_name: 'linux-v${{ steps.version.outputs.full }}'
|
||||||
|
name: 'GenOffice Linux v${{ steps.version.outputs.full }}'
|
||||||
|
body_path: ${{ steps.notes.outputs.path }}
|
||||||
|
draft: false
|
||||||
|
prerelease: false
|
||||||
|
files: |
|
||||||
|
apps/shell/release/*.AppImage
|
||||||
|
apps/shell/release/*.deb
|
||||||
|
apps/shell/release/latest-linux.yml
|
||||||
@@ -1,13 +1,14 @@
|
|||||||
name: Promote to Stable
|
name: Promote to Stable
|
||||||
|
|
||||||
# Manually promote an already-published beta build to the stable update
|
# Manually promote an already-published beta build to the stable update
|
||||||
# channel. No rebuild: rewrites latest.yml / latest-mac.yml on the CDN to
|
# channel. No rebuild: rewrites latest.yml / latest-mac.yml /
|
||||||
# the versioned feed archive uploaded when the build went to beta, and
|
# latest-linux.yml on the CDN to the versioned feed archive uploaded when
|
||||||
# re-points the marketing download aliases (GenOffice.dmg /
|
# the build went to beta, and re-points the marketing download aliases
|
||||||
# GenOfficeSetup.exe) to the promoted version by downloading the installer
|
# (GenOffice.dmg / GenOfficeSetup.exe / GenOffice.AppImage + GenOffice.deb)
|
||||||
# and re-uploading it under the alias name (server-side copy cannot read
|
# to the promoted version by downloading the installer and re-uploading it
|
||||||
# the private source container).
|
# under the alias name (server-side copy cannot read the private source
|
||||||
# Windows and mac version sequences are independent. Empty inputs default
|
# container).
|
||||||
|
# Per-platform version sequences are independent. Empty inputs default
|
||||||
# to each platform's newest beta version; type "skip" to leave a platform
|
# to each platform's newest beta version; type "skip" to leave a platform
|
||||||
# untouched.
|
# untouched.
|
||||||
|
|
||||||
@@ -22,6 +23,10 @@ on:
|
|||||||
description: 'windows version to promote (x.y.z; empty = latest beta; "skip" = leave windows untouched)'
|
description: 'windows version to promote (x.y.z; empty = latest beta; "skip" = leave windows untouched)'
|
||||||
required: false
|
required: false
|
||||||
default: ''
|
default: ''
|
||||||
|
linux_version:
|
||||||
|
description: 'linux version to promote (x.y.z; empty = latest beta; "skip" = leave linux untouched)'
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
force:
|
force:
|
||||||
description: 'allow rollback (skip the newer-version guard)'
|
description: 'allow rollback (skip the newer-version guard)'
|
||||||
type: boolean
|
type: boolean
|
||||||
@@ -49,6 +54,7 @@ jobs:
|
|||||||
GENOFFICE_UPDATE_URL: ${{ secrets.GENOFFICE_UPDATE_URL }}
|
GENOFFICE_UPDATE_URL: ${{ secrets.GENOFFICE_UPDATE_URL }}
|
||||||
MAC_VERSION: ${{ inputs.mac_version }}
|
MAC_VERSION: ${{ inputs.mac_version }}
|
||||||
WIN_VERSION: ${{ inputs.win_version }}
|
WIN_VERSION: ${{ inputs.win_version }}
|
||||||
|
LINUX_VERSION: ${{ inputs.linux_version }}
|
||||||
FORCE: ${{ inputs.force }}
|
FORCE: ${{ inputs.force }}
|
||||||
run: |
|
run: |
|
||||||
set -eu
|
set -eu
|
||||||
@@ -57,13 +63,15 @@ jobs:
|
|||||||
# the beta feed and re-validates everything server-side.
|
# the beta feed and re-validates everything server-side.
|
||||||
[ -z "$MAC_VERSION" ] && MAC_VERSION="latest"
|
[ -z "$MAC_VERSION" ] && MAC_VERSION="latest"
|
||||||
[ -z "$WIN_VERSION" ] && WIN_VERSION="latest"
|
[ -z "$WIN_VERSION" ] && WIN_VERSION="latest"
|
||||||
|
[ -z "$LINUX_VERSION" ] && LINUX_VERSION="latest"
|
||||||
[ "$MAC_VERSION" = "skip" ] && MAC_VERSION=""
|
[ "$MAC_VERSION" = "skip" ] && MAC_VERSION=""
|
||||||
[ "$WIN_VERSION" = "skip" ] && WIN_VERSION=""
|
[ "$WIN_VERSION" = "skip" ] && WIN_VERSION=""
|
||||||
if [ -z "$MAC_VERSION" ] && [ -z "$WIN_VERSION" ]; then
|
[ "$LINUX_VERSION" = "skip" ] && LINUX_VERSION=""
|
||||||
echo "nothing to promote — both platforms set to skip"
|
if [ -z "$MAC_VERSION" ] && [ -z "$WIN_VERSION" ] && [ -z "$LINUX_VERSION" ]; then
|
||||||
|
echo "nothing to promote — all platforms set to skip"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
for v in "$MAC_VERSION" "$WIN_VERSION"; do
|
for v in "$MAC_VERSION" "$WIN_VERSION" "$LINUX_VERSION"; do
|
||||||
if [ -n "$v" ] && [ "$v" != "latest" ] && ! printf '%s' "$v" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then
|
if [ -n "$v" ] && [ "$v" != "latest" ] && ! printf '%s' "$v" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then
|
||||||
echo "invalid version: $v (expected x.y.z, \"latest\", or \"skip\")"
|
echo "invalid version: $v (expected x.y.z, \"latest\", or \"skip\")"
|
||||||
exit 1
|
exit 1
|
||||||
@@ -81,5 +89,6 @@ jobs:
|
|||||||
ARGS=""
|
ARGS=""
|
||||||
[ -n "$MAC_VERSION" ] && ARGS="$ARGS --mac $MAC_VERSION"
|
[ -n "$MAC_VERSION" ] && ARGS="$ARGS --mac $MAC_VERSION"
|
||||||
[ -n "$WIN_VERSION" ] && ARGS="$ARGS --win $WIN_VERSION"
|
[ -n "$WIN_VERSION" ] && ARGS="$ARGS --win $WIN_VERSION"
|
||||||
|
[ -n "$LINUX_VERSION" ] && ARGS="$ARGS --linux $LINUX_VERSION"
|
||||||
[ "$FORCE" = "true" ] && ARGS="$ARGS --force"
|
[ "$FORCE" = "true" ] && ARGS="$ARGS --force"
|
||||||
node scripts/promote-stable.cjs $ARGS
|
node scripts/promote-stable.cjs $ARGS
|
||||||
|
|||||||
@@ -13,3 +13,6 @@ apps/shell/build/THIRD-PARTY-NOTICES.txt
|
|||||||
|
|
||||||
# Local-only acceptance drivers are intentionally outside CI.
|
# Local-only acceptance drivers are intentionally outside CI.
|
||||||
scripts/drivers/driver.*.mjs
|
scripts/drivers/driver.*.mjs
|
||||||
|
|
||||||
|
# Vendored third-party sources stay byte-identical to upstream.
|
||||||
|
packages/*/src/vendor/
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
Guidance for AI agents and human contributors working in this repo.
|
||||||
|
|
||||||
|
## Theming rules (mandatory)
|
||||||
|
|
||||||
|
The suite supports light / dark / system UI themes. The switching mechanism is a
|
||||||
|
`data-theme` attribute on `<html>` plus CSS custom properties defined once in
|
||||||
|
`packages/ui/src/tokens.css` (light defaults in `:root`, overrides in
|
||||||
|
`[data-theme='dark']`, and a `prefers-color-scheme` media-query fallback for
|
||||||
|
system mode).
|
||||||
|
|
||||||
|
1. **UI chrome colors must use semantic tokens.** Never write raw `#hex` /
|
||||||
|
`rgb()` in renderer CSS rules or chrome-related inline styles — reference
|
||||||
|
`var(--surface)`, `var(--text)`, `var(--hover)`, etc. from
|
||||||
|
`packages/ui/src/tokens.css`. Raw values are allowed only on custom-property
|
||||||
|
definition lines (`--x: #...;` — token, accent, or app-scoped variable
|
||||||
|
definitions). CI enforces this for new/changed renderer CSS lines
|
||||||
|
(`tools/check-theme-colors.mjs`).
|
||||||
|
2. **Every new token gets both values.** Adding a token means adding it to all
|
||||||
|
three blocks in `tokens.css` (light, dark, system-dark fallback).
|
||||||
|
3. **Accent colors stay per-app.** Each app defines `--accent` /
|
||||||
|
`--accent-dark` / `--accent-soft` (and its dark-adjusted values) in its own
|
||||||
|
`styles.css`. Shared rules reference `var(--accent)` and inherit the app's
|
||||||
|
brand color.
|
||||||
|
4. **Document content never follows the theme.** Page surfaces, cell fills,
|
||||||
|
slide content, PDF page bitmaps, export/print stylesheets, chart palettes,
|
||||||
|
highlight color maps, stamps, and WordArt presets are document data: they
|
||||||
|
stay hardcoded, must not reference chrome tokens, and must render/export
|
||||||
|
identically in both themes. (Word-style "dark chrome, white paper".)
|
||||||
|
5. **Canvas-drawn UI affordances go through a constants table.** Konva/canvas
|
||||||
|
editing chrome (selection frames, guides, handles) reads from the app's
|
||||||
|
canvas color table (e.g. `canvas-colors.ts`) keyed by the current theme —
|
||||||
|
no inline hex in draw calls.
|
||||||
|
|
||||||
|
## Build gotchas
|
||||||
|
|
||||||
|
- App main-process code (`apps/*/src/main`) is compiled into the **shell**
|
||||||
|
build. After changing it, rebuild the shell or the change silently does not
|
||||||
|
run.
|
||||||
|
- In dev mode, preload changes require a rebuild — a stale preload leaves the
|
||||||
|
renderer blank.
|
||||||
|
- Workspace packages listed in an app's `dependencies` must also be added to
|
||||||
|
the `externalizeDepsPlugin` `exclude` list, or the packaged app crashes on
|
||||||
|
launch.
|
||||||
|
- `useI18n()`'s `t` is not referentially stable; never put it in a hook
|
||||||
|
dependency array. Store the key and translate at render time.
|
||||||
@@ -1,13 +1,28 @@
|
|||||||
# GenOffice
|
# GenOffice
|
||||||
|
|
||||||
An AI-native office suite for macOS and Windows: word processor, spreadsheet,
|
An AI-native office suite for macOS, Windows, and Linux: word processor,
|
||||||
presentations, PDF, and Markdown — six Electron apps sharing one engine layer,
|
spreadsheet, presentations, PDF, and Markdown — six Electron apps sharing one
|
||||||
built around AI editing as a first-class workflow rather than a bolted-on chat box.
|
engine layer, built around AI editing as a first-class workflow rather than a
|
||||||
|
bolted-on chat box.
|
||||||
|
|
||||||
[](https://www.youtube.com/watch?v=B2pLdMX95v4)
|
[](https://www.youtube.com/watch?v=B2pLdMX95v4)
|
||||||
|
|
||||||
[Watch the demo video on YouTube](https://www.youtube.com/watch?v=B2pLdMX95v4)
|
[Watch the demo video on YouTube](https://www.youtube.com/watch?v=B2pLdMX95v4)
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **Real PDF editing** — retype text and edit images in the page itself, original fonts preserved.
|
||||||
|
- **Byte-preserving `.docx` editing** — only what you touched changes; Word never notices.
|
||||||
|
- **Word-faithful pagination** — page breaks land where Word puts them.
|
||||||
|
- **In-house spreadsheet engine** — Rust `.xlsx` sidecar, own charts, pivot tables, slicers.
|
||||||
|
- **In-house `.pptx` engine** — masters, layouts, smart guides, non-destructive crop.
|
||||||
|
- **Markdown to Word, fully local** — the same OOXML engine, no Pandoc, no cloud.
|
||||||
|
- **AI that edits documents** — block-level edits with snapshots and diffs, document-aware agents.
|
||||||
|
- **Agent tools built in** — web/image search, image generation, media analysis.
|
||||||
|
- **Light / dark / system themes.**
|
||||||
|
- **macOS, Windows, Linux.**
|
||||||
|
- **Free & open-source (Apache-2.0).**
|
||||||
|
|
||||||
## Download
|
## Download
|
||||||
|
|
||||||
| Platform | Requirements | Download |
|
| Platform | Requirements | Download |
|
||||||
@@ -40,20 +55,31 @@ chmod +x GenOffice-0.5.149.AppImage
|
|||||||
|
|
||||||
## Apps
|
## Apps
|
||||||
|
|
||||||
| App | Product | What it is |
|
| App | Product | What it is |
|
||||||
| ------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| --------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `apps/docs` | **GenOffice Docs** | `.docx` word processor. Byte-preserving round trip: only dirty paragraphs are regenerated (paragraph patch), everything else in the original file is kept byte-for-byte, so opening and saving never breaks layout in Word. Paginated view whose line metrics reproduce the original document's layout, tracked changes, comments, styles, equations, ink. |
|
| `apps/docs` | **GenOffice Docs** | `.docx` word processor. Byte-preserving round trip: only dirty paragraphs are regenerated (paragraph patch), everything else in the original file is kept byte-for-byte, so opening and saving never breaks layout in Word. Paginated view whose line metrics reproduce the original document's layout, tracked changes, comments, styles, equations, ink. |
|
||||||
| `apps/sheets` | **GenOffice Sheets** | `.xlsx` spreadsheet. UI built on the open-source [Univer](https://github.com/dream-num/univer) core (Apache-2.0) with a large layer of in-house extensions; `.xlsx` import/export runs through an in-house Rust sidecar (calamine + IronCalc), charts are rendered in-house (Konva), plus pivot tables, slicers, conditional formatting, and formula tracing. |
|
| `apps/sheets` | **GenOffice Sheets** | `.xlsx` spreadsheet. UI built on the open-source [Univer](https://github.com/dream-num/univer) core (Apache-2.0) with a large layer of in-house extensions; `.xlsx` import/export runs through an in-house Rust sidecar (calamine + IronCalc), charts are rendered in-house (Konva), plus pivot tables, slicers, conditional formatting, and formula tracing. |
|
||||||
| `apps/slides` | **GenOffice Slides** | `.pptx` presentations. In-house `.pptx` parse/render/edit engine with masters, charts, cropping, ink, and text shaping (HarfBuzz metrics). |
|
| `apps/slides` | **GenOffice Slides** | `.pptx` presentations. In-house `.pptx` parse/render/edit engine with masters, charts, cropping, ink, and text shaping (HarfBuzz metrics). |
|
||||||
| `apps/pdf` | **GenOffice PDF** | `.pdf` viewer/editor on pdf.js + pdf-lib: annotations, forms, outlines, stamps, signatures, page operations, and printing support. |
|
| `apps/pdf` | **GenOffice PDF** | `.pdf` viewer/editor on [pdf.js](https://github.com/mozilla/pdf.js) (Apache-2.0) + [pdf-lib](https://github.com/Hopding/pdf-lib) (MIT): annotations, forms, outlines, stamps, signatures, page operations, and printing support. True text editing — paragraph selection with in-block reflow, alignment restoration, original-font preservation — and content-stream image insert/edit, all rewriting page content streams through [PDFium](https://pdfium.googlesource.com/pdfium/) wasm (BSD-3-Clause) with subset-embedded fonts — no cover-up annotations. |
|
||||||
| `apps/shell` | **GenOffice** | The suite shell: home screen, tabbed hosting of the five editors, auto-update. |
|
| `apps/markdown` | **GenOffice Markdown** | `.md` / `.markdown` editor: Tiptap block editor over plain Markdown files — headings, lists, tables, images, code blocks — saved back as plain Markdown, hosted in shell tabs. |
|
||||||
|
| `apps/shell` | **GenOffice** | The suite shell: home screen, tabbed hosting of the five editors, light/dark/system theme, auto-update. |
|
||||||
|
|
||||||
Every app embeds the same AI panel: block-granular AI editing with version
|
Every app embeds the same AI panel: block-granular AI editing with version
|
||||||
snapshots and diffs in docs, a tool-calling agent over workbook/slide/PDF
|
snapshots and diffs in docs, a tool-calling agent over workbook/slide/PDF
|
||||||
state in the others.
|
state in the others.
|
||||||
|
|
||||||
**AI providers.** The apps sign in to a Genspark account and route model
|
The whole suite ships light / dark / system UI themes built on shared design
|
||||||
calls through the Genspark service side; no model API key is stored locally.
|
tokens (`packages/ui`), with a CI guard that keeps chrome colors on the token
|
||||||
|
system. Document surfaces stay light in dark mode — Word-style dark chrome
|
||||||
|
around white paper — so files render and export identically in both themes.
|
||||||
|
|
||||||
|
**AI backend (Genspark).** The apps sign in to a Genspark account through a
|
||||||
|
device-code flow; no model API key is entered or stored by the user. Model
|
||||||
|
calls route through the Genspark proxy (Claude, GPT, and Gemini families).
|
||||||
|
The same account also unlocks the Genspark ("gsk") tool endpoints the agents
|
||||||
|
build on — web and image search, image generation and editing,
|
||||||
|
image/audio/video analysis, and audio transcription — all reachable through
|
||||||
|
`packages/ai-search` for anyone extending the agent layer.
|
||||||
|
|
||||||
## Engine packages
|
## Engine packages
|
||||||
|
|
||||||
@@ -85,6 +111,7 @@ npm run dev # all five editors + shell against Vite dev servers
|
|||||||
npm run dev:docs # a single app (same pattern works per workspace)
|
npm run dev:docs # a single app (same pattern works per workspace)
|
||||||
npm run dist:mac # package macOS dmg (regenerates third-party notices)
|
npm run dist:mac # package macOS dmg (regenerates third-party notices)
|
||||||
npm run dist:win # package Windows nsis installer
|
npm run dist:win # package Windows nsis installer
|
||||||
|
npm run dist:linux # package Linux AppImage + deb
|
||||||
```
|
```
|
||||||
|
|
||||||
The sheets app additionally needs a Rust toolchain for its xlsx sidecar
|
The sheets app additionally needs a Rust toolchain for its xlsx sidecar
|
||||||
@@ -116,12 +143,37 @@ See [SECURITY.md](SECURITY.md) for the process security posture (renderer
|
|||||||
sandboxing, IPC validation, external-link gating) and the threat models for
|
sandboxing, IPC validation, external-link gating) and the threat models for
|
||||||
AI-generated content.
|
AI-generated content.
|
||||||
|
|
||||||
|
## Acknowledgements
|
||||||
|
|
||||||
|
GenOffice would not be possible without these open-source projects:
|
||||||
|
|
||||||
|
- [Electron](https://www.electronjs.org/) — the desktop runtime for every app.
|
||||||
|
- [Univer](https://github.com/dream-num/univer) (Apache-2.0) — the spreadsheet
|
||||||
|
UI core that Sheets extends.
|
||||||
|
- [PDFium](https://pdfium.googlesource.com/pdfium/) (BSD-3-Clause, bundled via
|
||||||
|
[@embedpdf/pdfium](https://github.com/embedpdf/embed-pdf-viewer)) — the
|
||||||
|
content-stream engine behind true PDF text and image editing.
|
||||||
|
- [pdf.js](https://github.com/mozilla/pdf.js) (Apache-2.0) and
|
||||||
|
[pdf-lib](https://github.com/Hopding/pdf-lib) (MIT) — PDF rendering and
|
||||||
|
document assembly.
|
||||||
|
- [Tiptap](https://tiptap.dev/) / [ProseMirror](https://prosemirror.net/) —
|
||||||
|
the block editors in Docs and Markdown.
|
||||||
|
- [Konva](https://konvajs.org/) — canvas rendering for Slides and Sheets
|
||||||
|
charts.
|
||||||
|
- [HarfBuzz](https://github.com/harfbuzz/harfbuzz) (wasm) — text-shaping
|
||||||
|
metrics for complex scripts.
|
||||||
|
- [calamine](https://github.com/tafia/calamine) and
|
||||||
|
[IronCalc](https://github.com/ironcalc/IronCalc) — the read and calc layers
|
||||||
|
of the Rust xlsx sidecar.
|
||||||
|
- Liberation, Carlito, Caladea, and Noto CJK fonts (OFL/Apache-2.0) — bundled
|
||||||
|
document fonts.
|
||||||
|
|
||||||
## Third-party notices
|
## Third-party notices
|
||||||
|
|
||||||
`npm run notices` regenerates the bundled third-party license summary
|
`npm run notices` regenerates the bundled third-party license summary
|
||||||
(`tools/gen-third-party-notices.mjs`); all runtime dependencies are
|
(`tools/gen-third-party-notices.mjs`); all runtime dependencies are
|
||||||
MIT/Apache-2.0/OFL, and the bundled fonts (Liberation, Carlito, Caladea, Noto
|
MIT/Apache-2.0/BSD-3-Clause/OFL, and the bundled fonts (Liberation, Carlito,
|
||||||
CJK subsets) are OFL/Apache.
|
Caladea, Noto CJK subsets) are OFL/Apache.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
@@ -2154,7 +2154,13 @@ function allowPdfWrite(wcId: number, filePath: string): void {
|
|||||||
pdfWritablePaths.set(wcId, set)
|
pdfWritablePaths.set(wcId, set)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Fidelity-harness escape hatch: headless runs have no save dialog to authorize
|
||||||
|
// paths, so an explicitly configured directory (set only by our test scripts)
|
||||||
|
// is treated as pre-authorized for PDF export.
|
||||||
|
const testExportDir = process.env.GENOFFICE_TEST_EXPORT_DIR || null
|
||||||
|
|
||||||
function canPdfWrite(wcId: number, filePath: string): boolean {
|
function canPdfWrite(wcId: number, filePath: string): boolean {
|
||||||
|
if (testExportDir && filePath.startsWith(testExportDir + '/')) return true
|
||||||
return pdfWritablePaths.get(wcId)?.has(filePath) === true
|
return pdfWritablePaths.get(wcId)?.has(filePath) === true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3238,6 +3244,26 @@ function sendCommand(command: MenuCommand, payload?: string): void {
|
|||||||
activeDocsWebContents()?.send('menu:command', command, payload)
|
activeDocsWebContents()?.send('menu:command', command, payload)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-tab View-menu toggle state (AI Sidebar / Dark Mode), reported by each
|
||||||
|
* renderer whenever it changes. The template can't hardcode `checked` — the
|
||||||
|
* state lives in the renderer and differs per tab — so builds read the active
|
||||||
|
* tab's last report, and reports from the active tab patch the built menu in
|
||||||
|
* place (buildDocsMenu also re-runs on every tab focus switch).
|
||||||
|
* Defaults mirror the renderer's initial state: sidebar shown, light canvas.
|
||||||
|
*/
|
||||||
|
const viewMenuStateByWebContents = new Map<number, { aiSidebar: boolean; darkCanvas: boolean }>()
|
||||||
|
|
||||||
|
function activeViewMenuState(): { aiSidebar: boolean; darkCanvas: boolean } {
|
||||||
|
const id = activeDocsWebContents()?.id
|
||||||
|
return (
|
||||||
|
(id !== undefined ? viewMenuStateByWebContents.get(id) : undefined) ?? {
|
||||||
|
aiSidebar: true,
|
||||||
|
darkCanvas: false,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/** shell-injected items appended to the File menu (e.g. Back to Home); persists
|
/** shell-injected items appended to the File menu (e.g. Back to Home); persists
|
||||||
* across the internal rebuilds pushRecent() triggers */
|
* across the internal rebuilds pushRecent() triggers */
|
||||||
let extraFileMenuItems: MenuItemConstructorOptions[] = []
|
let extraFileMenuItems: MenuItemConstructorOptions[] = []
|
||||||
@@ -3378,8 +3404,20 @@ export function buildDocsMenu(): void {
|
|||||||
{ label: tm('menuPageWidth'), click: () => sendCommand('zoom-page-width') },
|
{ label: tm('menuPageWidth'), click: () => sendCommand('zoom-page-width') },
|
||||||
{ label: tm('menuWholePage'), click: () => sendCommand('zoom-whole-page') },
|
{ label: tm('menuWholePage'), click: () => sendCommand('zoom-whole-page') },
|
||||||
{ type: 'separator' },
|
{ type: 'separator' },
|
||||||
{ label: tm('menuAiSidebar'), click: () => sendCommand('toggle-ai') },
|
{
|
||||||
{ label: tm('menuDarkMode'), click: () => sendCommand('toggle-dark') },
|
id: 'docs-menu-ai-sidebar',
|
||||||
|
type: 'checkbox',
|
||||||
|
checked: activeViewMenuState().aiSidebar,
|
||||||
|
label: tm('menuAiSidebar'),
|
||||||
|
click: () => sendCommand('toggle-ai'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'docs-menu-dark-mode',
|
||||||
|
type: 'checkbox',
|
||||||
|
checked: activeViewMenuState().darkCanvas,
|
||||||
|
label: tm('menuDarkMode'),
|
||||||
|
click: () => sendCommand('toggle-dark'),
|
||||||
|
},
|
||||||
{ type: 'separator' },
|
{ type: 'separator' },
|
||||||
{ role: 'togglefullscreen', label: tm('menuFullscreen') },
|
{ role: 'togglefullscreen', label: tm('menuFullscreen') },
|
||||||
...(isDev ? [{ role: 'toggleDevTools' as const }] : []),
|
...(isDev ? [{ role: 'toggleDevTools' as const }] : []),
|
||||||
@@ -3545,6 +3583,24 @@ interface DocsCloseState {
|
|||||||
const closeCheckWaiters = new Map<number, (state: DocsCloseState) => void>()
|
const closeCheckWaiters = new Map<number, (state: DocsCloseState) => void>()
|
||||||
const closeSaveWaiters = new Map<number, (ok: boolean) => void>()
|
const closeSaveWaiters = new Map<number, (ok: boolean) => void>()
|
||||||
|
|
||||||
|
ipcMain.on('docs:view-menu-state', (event, state: unknown) => {
|
||||||
|
const s = state as { aiSidebar?: unknown; darkCanvas?: unknown } | null
|
||||||
|
const next = { aiSidebar: s?.aiSidebar === true, darkCanvas: s?.darkCanvas === true }
|
||||||
|
if (!viewMenuStateByWebContents.has(event.sender.id)) {
|
||||||
|
const id = event.sender.id
|
||||||
|
event.sender.once('destroyed', () => viewMenuStateByWebContents.delete(id))
|
||||||
|
}
|
||||||
|
viewMenuStateByWebContents.set(event.sender.id, next)
|
||||||
|
// patch the live menu only for the active tab; an inactive tab's state gets
|
||||||
|
// picked up by the buildDocsMenu run its next focus triggers
|
||||||
|
if (event.sender.id !== activeDocsWebContents()?.id) return
|
||||||
|
const menu = Menu.getApplicationMenu()
|
||||||
|
const ai = menu?.getMenuItemById('docs-menu-ai-sidebar')
|
||||||
|
if (ai) ai.checked = next.aiSidebar
|
||||||
|
const dark = menu?.getMenuItemById('docs-menu-dark-mode')
|
||||||
|
if (dark) dark.checked = next.darkCanvas
|
||||||
|
})
|
||||||
|
|
||||||
ipcMain.on('docs:close-check-result', (event, state: unknown) => {
|
ipcMain.on('docs:close-check-result', (event, state: unknown) => {
|
||||||
const waiter = closeCheckWaiters.get(event.sender.id)
|
const waiter = closeCheckWaiters.get(event.sender.id)
|
||||||
if (!waiter) return
|
if (!waiter) return
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import type {
|
|||||||
AiStreamRequest,
|
AiStreamRequest,
|
||||||
DesktopApi,
|
DesktopApi,
|
||||||
MenuCommand,
|
MenuCommand,
|
||||||
|
UiTheme,
|
||||||
} from '../shared/ipc'
|
} from '../shared/ipc'
|
||||||
import type { ProjectApi } from '@genoffice/project-store'
|
import type { ProjectApi } from '@genoffice/project-store'
|
||||||
|
|
||||||
@@ -20,6 +21,12 @@ const api: DesktopApi = {
|
|||||||
ipcRenderer.on('app:language-changed', listener)
|
ipcRenderer.on('app:language-changed', listener)
|
||||||
return () => ipcRenderer.removeListener('app:language-changed', listener)
|
return () => ipcRenderer.removeListener('app:language-changed', listener)
|
||||||
},
|
},
|
||||||
|
getTheme: () => ipcRenderer.invoke('app:get-theme'),
|
||||||
|
onThemeChanged: (handler) => {
|
||||||
|
const listener = (_event: IpcRendererEvent, theme: UiTheme) => handler(theme)
|
||||||
|
ipcRenderer.on('app:theme-changed', listener)
|
||||||
|
return () => ipcRenderer.removeListener('app:theme-changed', listener)
|
||||||
|
},
|
||||||
openDocx: () => ipcRenderer.invoke('docs:open'),
|
openDocx: () => ipcRenderer.invoke('docs:open'),
|
||||||
openDocxPath: (path: string) => ipcRenderer.invoke('docs:open-path', path),
|
openDocxPath: (path: string) => ipcRenderer.invoke('docs:open-path', path),
|
||||||
consumePendingOpenDocx: () => ipcRenderer.invoke('docs:consume-pending-open'),
|
consumePendingOpenDocx: () => ipcRenderer.invoke('docs:consume-pending-open'),
|
||||||
@@ -101,6 +108,11 @@ const api: DesktopApi = {
|
|||||||
ipcRenderer.on('docs:close-check', listener)
|
ipcRenderer.on('docs:close-check', listener)
|
||||||
return () => ipcRenderer.removeListener('docs:close-check', listener)
|
return () => ipcRenderer.removeListener('docs:close-check', listener)
|
||||||
},
|
},
|
||||||
|
reportViewMenuState: (state: { aiSidebar: boolean; darkCanvas: boolean }) =>
|
||||||
|
ipcRenderer.send('docs:view-menu-state', {
|
||||||
|
aiSidebar: state?.aiSidebar === true,
|
||||||
|
darkCanvas: state?.darkCanvas === true,
|
||||||
|
}),
|
||||||
reportCloseCheck: (state: { dirty: boolean; autoSave: boolean; filePath?: string | null }) =>
|
reportCloseCheck: (state: { dirty: boolean; autoSave: boolean; filePath?: string | null }) =>
|
||||||
ipcRenderer.send('docs:close-check-result', {
|
ipcRenderer.send('docs:close-check-result', {
|
||||||
dirty: state?.dirty === true,
|
dirty: state?.dirty === true,
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ import {
|
|||||||
type BlockMeta,
|
type BlockMeta,
|
||||||
type PageNoteItem,
|
type PageNoteItem,
|
||||||
pageAt,
|
pageAt,
|
||||||
|
singleCutCell,
|
||||||
sectionColGeom,
|
sectionColGeom,
|
||||||
sectionColumns,
|
sectionColumns,
|
||||||
sectionFirstPages,
|
sectionFirstPages,
|
||||||
@@ -120,6 +121,7 @@ import { isDocDirty } from './doc-dirty'
|
|||||||
import {
|
import {
|
||||||
EMPTY_HF_VARIANTS,
|
EMPTY_HF_VARIANTS,
|
||||||
hfFromPart,
|
hfFromPart,
|
||||||
|
restingHfAreaVariant,
|
||||||
type DocState,
|
type DocState,
|
||||||
type HfVariantKey,
|
type HfVariantKey,
|
||||||
type HfVariantsState,
|
type HfVariantsState,
|
||||||
@@ -313,7 +315,17 @@ export function App() {
|
|||||||
const [titlePgDirty, setTitlePgDirty] = useState(false)
|
const [titlePgDirty, setTitlePgDirty] = useState(false)
|
||||||
const [evenOddHf, setEvenOddHf] = useState(false)
|
const [evenOddHf, setEvenOddHf] = useState(false)
|
||||||
const [evenOddHfDirty, setEvenOddHfDirty] = useState(false)
|
const [evenOddHfDirty, setEvenOddHfDirty] = useState(false)
|
||||||
const [hfView, setHfView] = useState<HfView>('default')
|
const [hfView, setHfViewState] = useState<HfView>('default')
|
||||||
|
/** false until the user picks a variant (chip/toggle); resting areas then follow their page's variant instead */
|
||||||
|
const [hfViewTouched, setHfViewTouched] = useState(false)
|
||||||
|
const setHfView = (v: HfView) => {
|
||||||
|
setHfViewState(v)
|
||||||
|
setHfViewTouched(true)
|
||||||
|
}
|
||||||
|
const [pageInfo, setPageInfo] = useState({ current: 1, total: 1 })
|
||||||
|
// last page's number for the document-end footer: text for the page marker, num for
|
||||||
|
// even/odd parity (section restarts / pageNumberFmt make both differ from the physical count)
|
||||||
|
const [lastPageNo, setLastPageNo] = useState<{ text: string; num: number } | null>(null)
|
||||||
/** Page-number-format dialog + pending final-section pgNumType write (non-final sections rewrite sectPr via pgNumDirtySections) */
|
/** Page-number-format dialog + pending final-section pgNumType write (non-final sections rewrite sectPr via pgNumDirtySections) */
|
||||||
const [pgNumModal, setPgNumModal] = useState<{ fmt: string; start: string } | null>(null)
|
const [pgNumModal, setPgNumModal] = useState<{ fmt: string; start: string } | null>(null)
|
||||||
const [pgNumEdit, setPgNumEdit] = useState<{ fmt?: string; start?: number } | null>(null)
|
const [pgNumEdit, setPgNumEdit] = useState<{ fmt?: string; start?: number } | null>(null)
|
||||||
@@ -351,18 +363,30 @@ export function App() {
|
|||||||
}
|
}
|
||||||
return sectionHfEdits[`${sec.lastBlockIndex}:${kind}`] ?? fromPart()
|
return sectionHfEdits[`${sec.lastBlockIndex}:${kind}`] ?? fromPart()
|
||||||
}
|
}
|
||||||
|
/** Variant an on-canvas area shows/edits: explicit chip choice wins; at rest the header area is page 1 and the footer area the last page */
|
||||||
|
const areaView = (kind: 'header' | 'footer'): HfView =>
|
||||||
|
hfViewTouched
|
||||||
|
? effHfView
|
||||||
|
: restingHfAreaVariant(kind, {
|
||||||
|
titlePg,
|
||||||
|
evenOddHf,
|
||||||
|
pageCount: pageInfo.total,
|
||||||
|
...(lastPageNo ? { lastPageNo: lastPageNo.num } : {}),
|
||||||
|
})
|
||||||
|
const headerAreaView = areaView('header')
|
||||||
|
const footerAreaView = areaView('footer')
|
||||||
const shownHeader =
|
const shownHeader =
|
||||||
effHfView === 'first'
|
headerAreaView === 'first'
|
||||||
? hfVariants.headerFirst
|
? hfVariants.headerFirst
|
||||||
: effHfView === 'even'
|
: headerAreaView === 'even'
|
||||||
? hfVariants.headerEven
|
? hfVariants.headerEven
|
||||||
: multiHf
|
: multiHf
|
||||||
? sectionHfValue('header')
|
? sectionHfValue('header')
|
||||||
: header
|
: header
|
||||||
const shownFooter =
|
const shownFooter =
|
||||||
effHfView === 'first'
|
footerAreaView === 'first'
|
||||||
? hfVariants.footerFirst
|
? hfVariants.footerFirst
|
||||||
: effHfView === 'even'
|
: footerAreaView === 'even'
|
||||||
? hfVariants.footerEven
|
? hfVariants.footerEven
|
||||||
: multiHf
|
: multiHf
|
||||||
? sectionHfValue('footer')
|
? sectionHfValue('footer')
|
||||||
@@ -371,10 +395,11 @@ export function App() {
|
|||||||
const hfImagesOf = (kind: 'header' | 'footer') => {
|
const hfImagesOf = (kind: 'header' | 'footer') => {
|
||||||
const parsed = doc?.parsed
|
const parsed = doc?.parsed
|
||||||
if (!parsed) return undefined
|
if (!parsed) return undefined
|
||||||
if (effHfView === 'first') {
|
const view = kind === 'header' ? headerAreaView : footerAreaView
|
||||||
|
if (view === 'first') {
|
||||||
return (kind === 'header' ? parsed.headerFirst : parsed.footerFirst)?.images
|
return (kind === 'header' ? parsed.headerFirst : parsed.footerFirst)?.images
|
||||||
}
|
}
|
||||||
if (effHfView === 'even') {
|
if (view === 'even') {
|
||||||
return (kind === 'header' ? parsed.headerEven : parsed.footerEven)?.images
|
return (kind === 'header' ? parsed.headerEven : parsed.footerEven)?.images
|
||||||
}
|
}
|
||||||
if (multiHf) {
|
if (multiHf) {
|
||||||
@@ -386,13 +411,14 @@ export function App() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const commitHf = (kind: 'header' | 'footer', next: HeaderFooter) => {
|
const commitHf = (kind: 'header' | 'footer', next: HeaderFooter) => {
|
||||||
|
const view = kind === 'header' ? headerAreaView : footerAreaView
|
||||||
// multi-section and not the final one: use the per-section edit channel (that section becomes its own part; earlier sections are unaffected)
|
// multi-section and not the final one: use the per-section edit channel (that section becomes its own part; earlier sections are unaffected)
|
||||||
if (effHfView === 'default' && multiHf && hfSectionClamped < sections.length - 1) {
|
if (view === 'default' && multiHf && hfSectionClamped < sections.length - 1) {
|
||||||
const sec = sections[hfSectionClamped]
|
const sec = sections[hfSectionClamped]
|
||||||
setSectionHfEdits((m) => ({ ...m, [`${sec.lastBlockIndex}:${kind}`]: next }))
|
setSectionHfEdits((m) => ({ ...m, [`${sec.lastBlockIndex}:${kind}`]: next }))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (effHfView === 'default') {
|
if (view === 'default') {
|
||||||
if (kind === 'header') {
|
if (kind === 'header') {
|
||||||
setHeader(next)
|
setHeader(next)
|
||||||
setHeaderDirty(true)
|
setHeaderDirty(true)
|
||||||
@@ -403,7 +429,7 @@ export function App() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
const key: HfVariantKey =
|
const key: HfVariantKey =
|
||||||
effHfView === 'first'
|
view === 'first'
|
||||||
? kind === 'header'
|
? kind === 'header'
|
||||||
? 'headerFirst'
|
? 'headerFirst'
|
||||||
: 'footerFirst'
|
: 'footerFirst'
|
||||||
@@ -506,10 +532,6 @@ export function App() {
|
|||||||
const [ctxMenu, setCtxMenu] = useState<ContextMenuState | null>(null)
|
const [ctxMenu, setCtxMenu] = useState<ContextMenuState | null>(null)
|
||||||
const [showFontDialog, setShowFontDialog] = useState(false)
|
const [showFontDialog, setShowFontDialog] = useState(false)
|
||||||
const [showParaDialog, setShowParaDialog] = useState(false)
|
const [showParaDialog, setShowParaDialog] = useState(false)
|
||||||
const [pageInfo, setPageInfo] = useState({ current: 1, total: 1 })
|
|
||||||
// last page's displayed number for the document-end footer '#' marker
|
|
||||||
// (section restarts / pageNumberFmt make it differ from the physical count)
|
|
||||||
const [lastPageNo, setLastPageNo] = useState<number | string | null>(null)
|
|
||||||
const [, forceRender] = useReducer((x: number) => x + 1, 0)
|
const [, forceRender] = useReducer((x: number) => x + 1, 0)
|
||||||
const dirtyRef = useRef(false)
|
const dirtyRef = useRef(false)
|
||||||
// serializes save(): overlapping saves (Cmd+S vs autosave timer vs blur) would
|
// serializes save(): overlapping saves (Cmd+S vs autosave timer vs blur) would
|
||||||
@@ -651,6 +673,11 @@ export function App() {
|
|||||||
|
|
||||||
useEffect(() => window.desktop.onTeardown?.(() => setTornDown(true)), [])
|
useEffect(() => window.desktop.onTeardown?.(() => setTornDown(true)), [])
|
||||||
|
|
||||||
|
// keep the native View menu's checkmarks (AI Sidebar / Dark Mode) in sync
|
||||||
|
useEffect(() => {
|
||||||
|
window.desktop.reportViewMenuState?.({ aiSidebar: showAi, darkCanvas })
|
||||||
|
}, [showAi, darkCanvas])
|
||||||
|
|
||||||
// Crash-recovery copy: while the document is dirty, push a serialized
|
// Crash-recovery copy: while the document is dirty, push a serialized
|
||||||
// copy to the main process every 30s; a normal save (or discarding on close) removes
|
// copy to the main process every 30s; a normal save (or discarding on close) removes
|
||||||
// it, and reopening the file offers Restore/Discard when a newer copy exists.
|
// it, and reopening the file offers Restore/Discard when a newer copy exists.
|
||||||
@@ -763,7 +790,11 @@ export function App() {
|
|||||||
setTitlePgDirty,
|
setTitlePgDirty,
|
||||||
setEvenOddHf,
|
setEvenOddHf,
|
||||||
setEvenOddHfDirty,
|
setEvenOddHfDirty,
|
||||||
setHfView,
|
// opening a document resets to the resting per-page variant selection
|
||||||
|
setHfView: (v: HfView) => {
|
||||||
|
setHfViewState(v)
|
||||||
|
setHfViewTouched(false)
|
||||||
|
},
|
||||||
pgNumEdit,
|
pgNumEdit,
|
||||||
pgNumDirtySections,
|
pgNumDirtySections,
|
||||||
setPgNumEdit,
|
setPgNumEdit,
|
||||||
@@ -1614,14 +1645,16 @@ export function App() {
|
|||||||
// document-end footer shows the last page's displayed number, not the physical count
|
// document-end footer shows the last page's displayed number, not the physical count
|
||||||
if (slices.length > 0) {
|
if (slices.length > 0) {
|
||||||
const lastIdx = slices.length - 1
|
const lastIdx = slices.length - 1
|
||||||
setLastPageNo(
|
const num = secList ? pageNumbers(slices, secList)[lastIdx] : slices.length
|
||||||
secList
|
setLastPageNo({
|
||||||
|
num,
|
||||||
|
text: secList
|
||||||
? formatPageNumber(
|
? formatPageNumber(
|
||||||
pageNumbers(slices, secList)[lastIdx],
|
num,
|
||||||
secList[Math.min(slices[lastIdx].section, secList.length - 1)]?.pageNumberFmt,
|
secList[Math.min(slices[lastIdx].section, secList.length - 1)]?.pageNumberFmt,
|
||||||
)
|
)
|
||||||
: slices.length,
|
: String(num),
|
||||||
)
|
})
|
||||||
}
|
}
|
||||||
// Auto-refresh TOC page numbers from the fresh slicing, like Word's field
|
// Auto-refresh TOC page numbers from the fresh slicing, like Word's field
|
||||||
// update. Gated on dirtyRef — our pagination approximates Word's, so a
|
// update. Gated on dirtyRef — our pagination approximates Word's, so a
|
||||||
@@ -1710,6 +1743,9 @@ export function App() {
|
|||||||
const hfSig = (v: HeaderFooter | null | undefined) =>
|
const hfSig = (v: HeaderFooter | null | undefined) =>
|
||||||
v ? `${v.text}·${v.pageNumber ? 1 : 0}·${v.paras?.length ?? 0}` : ''
|
v ? `${v.text}·${v.pageNumber ? 1 : 0}·${v.paras?.length ?? 0}` : ''
|
||||||
const visiblePages = visiblePageCount(slices)
|
const visiblePages = visiblePageCount(slices)
|
||||||
|
// stopgap until per-section canvas geometry: a landscape section's header/footer
|
||||||
|
// strip must not overflow the (portrait) canvas paper it is drawn on
|
||||||
|
const canvasPaperW = pmRect.width / factor
|
||||||
slices.slice(1).forEach((slice, k) => {
|
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
|
// 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
|
if (slice.start === slices[k].start) return
|
||||||
@@ -1741,7 +1777,7 @@ export function App() {
|
|||||||
})
|
})
|
||||||
el.style.top = 'auto'
|
el.style.top = 'auto'
|
||||||
el.style.bottom = `${GAP_BAND + metrics.marginTop + box.footerDist}px`
|
el.style.bottom = `${GAP_BAND + metrics.marginTop + box.footerDist}px`
|
||||||
el.style.width = `${box.width - 120}px`
|
el.style.width = `${Math.min(box.width, canvasPaperW) - 120}px`
|
||||||
hfEls.push(el)
|
hfEls.push(el)
|
||||||
}
|
}
|
||||||
if (hfHasVisibleContent(gapHeader.value, gapHeader.images)) {
|
if (hfHasVisibleContent(gapHeader.value, gapHeader.images)) {
|
||||||
@@ -1755,7 +1791,7 @@ export function App() {
|
|||||||
})
|
})
|
||||||
el.style.bottom = 'auto'
|
el.style.bottom = 'auto'
|
||||||
el.style.top = `calc(100% - ${Math.max(0, metrics.marginTop - box.headerDist)}px)`
|
el.style.top = `calc(100% - ${Math.max(0, metrics.marginTop - box.headerDist)}px)`
|
||||||
el.style.width = `${box.width - 120}px`
|
el.style.width = `${Math.min(box.width, canvasPaperW) - 120}px`
|
||||||
hfEls.push(el)
|
hfEls.push(el)
|
||||||
}
|
}
|
||||||
const hfProps =
|
const hfProps =
|
||||||
@@ -1811,6 +1847,7 @@ export function App() {
|
|||||||
)
|
)
|
||||||
const elTop = b.el.getBoundingClientRect().top
|
const elTop = b.el.getBoundingClientRect().top
|
||||||
let matched = false
|
let matched = false
|
||||||
|
let cutRow: Element | null = null
|
||||||
for (const tr of Array.from(b.el.querySelectorAll('tr')).filter(
|
for (const tr of Array.from(b.el.querySelectorAll('tr')).filter(
|
||||||
(r) =>
|
(r) =>
|
||||||
!r.closest('.doc-nested-table') && !r.classList.contains('page-repeat-header'),
|
!r.closest('.doc-nested-table') && !r.classList.contains('page-repeat-header'),
|
||||||
@@ -1818,6 +1855,9 @@ export function App() {
|
|||||||
const trTop = tr.getBoundingClientRect().top
|
const trTop = tr.getBoundingClientRect().top
|
||||||
const gapsAbove = gapRects.reduce((s, g) => (g.top <= trTop ? s + g.height : s), 0)
|
const gapsAbove = gapRects.reduce((s, g) => (g.top <= trTop ? s + g.height : s), 0)
|
||||||
const off = (trTop - elTop - gapsAbove) / factor
|
const off = (trTop - elTop - gapsAbove) / factor
|
||||||
|
// last real row starting at/above the cut = the row the cut falls inside
|
||||||
|
if (!tr.classList.contains('page-gap') && off <= slice.start - b.top + 0.5)
|
||||||
|
cutRow = tr
|
||||||
if (Math.abs(off - (slice.start - b.top)) < 1.5) {
|
if (Math.abs(off - (slice.start - b.top)) < 1.5) {
|
||||||
matched = true
|
matched = true
|
||||||
try {
|
try {
|
||||||
@@ -1874,11 +1914,31 @@ export function App() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!matched) {
|
if (!matched) {
|
||||||
// inline cut point (page break mid-line): the cut falls in a line's band gap; locate the first line after it and insert a zero-height dashed marker
|
// in-row cut point (page break between a cell's lines): anchor at the first line after it
|
||||||
const anchor = nextLineAnchor(b.el, slice.start - b.top, factor)
|
const anchor = nextLineAnchor(b.el, slice.start - b.top, factor)
|
||||||
const pos = anchor ? posFromAnchor(editor.view, anchor) : undefined
|
const pos = anchor ? posFromAnchor(editor.view, anchor) : undefined
|
||||||
// no hfProps: a zero-height cut marker can't host header/footer strips
|
if (anchor == null || pos == null) return
|
||||||
if (pos != null) gaps.push({ pos, kind: 'cut', metrics })
|
const cutCell = singleCutCell(cutRow)
|
||||||
|
if (cutCell) {
|
||||||
|
// single-column row: insert a real inline gap band; bleed to the paper
|
||||||
|
// edges from the anchor's block (the widget's containing block)
|
||||||
|
const r = (
|
||||||
|
anchor.node.parentElement?.closest('td > *, th > *') ?? cutCell
|
||||||
|
).getBoundingClientRect()
|
||||||
|
gaps.push({
|
||||||
|
pos,
|
||||||
|
kind: 'cell',
|
||||||
|
metrics: {
|
||||||
|
...metrics,
|
||||||
|
marginLeft: metrics.marginLeft + (r.left - pmRect.left) / factor,
|
||||||
|
marginRight: metrics.marginRight + (pmRect.right - r.right) / factor,
|
||||||
|
},
|
||||||
|
...hfProps,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
// multi-cell row: keep the zero-height dashed marker (no hfProps — it can't host header/footer strips)
|
||||||
|
gaps.push({ pos, kind: 'cut', metrics })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -2740,7 +2800,7 @@ export function App() {
|
|||||||
</button>
|
</button>
|
||||||
{titlePg && (
|
{titlePg && (
|
||||||
<button
|
<button
|
||||||
className={effHfView === 'first' ? 'on' : ''}
|
className={headerAreaView === 'first' ? 'on' : ''}
|
||||||
onClick={() => setHfView('first')}
|
onClick={() => setHfView('first')}
|
||||||
>
|
>
|
||||||
{t('appFirstPage')}
|
{t('appFirstPage')}
|
||||||
@@ -2748,7 +2808,7 @@ export function App() {
|
|||||||
)}
|
)}
|
||||||
{(titlePg || evenOddHf) && (
|
{(titlePg || evenOddHf) && (
|
||||||
<button
|
<button
|
||||||
className={effHfView === 'default' ? 'on' : ''}
|
className={headerAreaView === 'default' ? 'on' : ''}
|
||||||
onClick={() => setHfView('default')}
|
onClick={() => setHfView('default')}
|
||||||
>
|
>
|
||||||
{evenOddHf ? t('appOddPage') : t('appDefaultPage')}
|
{evenOddHf ? t('appOddPage') : t('appDefaultPage')}
|
||||||
@@ -2756,7 +2816,7 @@ export function App() {
|
|||||||
)}
|
)}
|
||||||
{evenOddHf && (
|
{evenOddHf && (
|
||||||
<button
|
<button
|
||||||
className={effHfView === 'even' ? 'on' : ''}
|
className={headerAreaView === 'even' ? 'on' : ''}
|
||||||
onClick={() => setHfView('even')}
|
onClick={() => setHfView('even')}
|
||||||
>
|
>
|
||||||
{t('appEvenPage')}
|
{t('appEvenPage')}
|
||||||
@@ -2765,7 +2825,7 @@ export function App() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{(multiHf ||
|
{(multiHf ||
|
||||||
effHfView !== 'default' ||
|
(hfViewTouched && effHfView !== 'default') ||
|
||||||
shownHeader?.text ||
|
shownHeader?.text ||
|
||||||
shownHeader?.paras?.length ||
|
shownHeader?.paras?.length ||
|
||||||
hfImagesOf('header')?.length) && (
|
hfImagesOf('header')?.length) && (
|
||||||
@@ -2833,7 +2893,7 @@ export function App() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{(multiHf ||
|
{(multiHf ||
|
||||||
effHfView !== 'default' ||
|
(hfViewTouched && effHfView !== 'default') ||
|
||||||
shownFooter?.text ||
|
shownFooter?.text ||
|
||||||
shownFooter?.pageNumber ||
|
shownFooter?.pageNumber ||
|
||||||
shownFooter?.paras?.length ||
|
shownFooter?.paras?.length ||
|
||||||
@@ -2844,7 +2904,7 @@ export function App() {
|
|||||||
images={hfImagesOf('footer')}
|
images={hfImagesOf('footer')}
|
||||||
readOnly={isProtected || readMode}
|
readOnly={isProtected || readMode}
|
||||||
onCommit={(next) => commitHf('footer', next)}
|
onCommit={(next) => commitHf('footer', next)}
|
||||||
pageNo={lastPageNo ?? pageInfo.total}
|
pageNo={lastPageNo?.text ?? pageInfo.total}
|
||||||
pageTotal={pageInfo.total}
|
pageTotal={pageInfo.total}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,6 +1,13 @@
|
|||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { TOTAL_PAGES_MARK, type HfImage, type HfParagraph, type Run } from '@genoffice/docx-engine'
|
import {
|
||||||
|
PAGE_MARK,
|
||||||
|
TOTAL_PAGES_MARK,
|
||||||
|
type HfImage,
|
||||||
|
type HfParagraph,
|
||||||
|
type Run,
|
||||||
|
} from '@genoffice/docx-engine'
|
||||||
import { useI18n } from '../i18n/locale'
|
import { useI18n } from '../i18n/locale'
|
||||||
|
import { hfUsesLegacyHash } from '../editor/hf-dom'
|
||||||
import { cssDualFontFamily, cssFontFamily } from '../line-metrics'
|
import { cssDualFontFamily, cssFontFamily } from '../line-metrics'
|
||||||
|
|
||||||
export interface HfValue {
|
export interface HfValue {
|
||||||
@@ -9,6 +16,10 @@ export interface HfValue {
|
|||||||
paras?: HfParagraph[]
|
paras?: HfParagraph[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** visible edit-surface stand-ins for the invisible private-use field sentinels */
|
||||||
|
const PAGE_TOKEN = '{PAGE}'
|
||||||
|
const TOTAL_TOKEN = '{NUMPAGES}'
|
||||||
|
|
||||||
function runStyle(run: Run): React.CSSProperties {
|
function runStyle(run: Run): React.CSSProperties {
|
||||||
const style: React.CSSProperties = {}
|
const style: React.CSSProperties = {}
|
||||||
if (run.bold) style.fontWeight = 600
|
if (run.bold) style.fontWeight = 600
|
||||||
@@ -26,8 +37,8 @@ function runStyle(run: Run): React.CSSProperties {
|
|||||||
function parasOf(value: HfValue): HfParagraph[] {
|
function parasOf(value: HfValue): HfParagraph[] {
|
||||||
if (value.paras?.length) return value.paras
|
if (value.paras?.length) return value.paras
|
||||||
const runs: Run[] = value.text ? [{ text: value.text }] : []
|
const runs: Run[] = value.text ? [{ text: value.text }] : []
|
||||||
if (value.pageNumber && !value.text.includes('#')) {
|
if (value.pageNumber && !value.text.includes('#') && !value.text.includes(PAGE_MARK)) {
|
||||||
runs.push({ text: runs.length > 0 ? ' #' : '#' })
|
runs.push({ text: runs.length > 0 ? ` ${PAGE_MARK}` : PAGE_MARK })
|
||||||
}
|
}
|
||||||
return [{ align: 'center', runs }]
|
return [{ align: 'center', runs }]
|
||||||
}
|
}
|
||||||
@@ -35,8 +46,8 @@ function parasOf(value: HfValue): HfParagraph[] {
|
|||||||
/**
|
/**
|
||||||
* Header / footer zone on the page: renders the rich paragraphs,
|
* Header / footer zone on the page: renders the rich paragraphs,
|
||||||
* double-click enters in-place editing (plain text per paragraph; each line
|
* double-click enters in-place editing (plain text per paragraph; each line
|
||||||
* keeps its paragraph format and first-run styling), blur commits. The '#'
|
* keeps its paragraph format and first-run styling), blur commits. PAGE /
|
||||||
* marker stands for the automatic page number.
|
* NUMPAGES sentinels edit as visible {PAGE} / {NUMPAGES} tokens.
|
||||||
*/
|
*/
|
||||||
export function HeaderFooterArea({
|
export function HeaderFooterArea({
|
||||||
kind,
|
kind,
|
||||||
@@ -72,7 +83,13 @@ export function HeaderFooterArea({
|
|||||||
if (!editing) return
|
if (!editing) return
|
||||||
const el = editRef.current
|
const el = editRef.current
|
||||||
if (!el) return
|
if (!el) return
|
||||||
el.innerText = paras.map((p) => p.runs.map((r) => r.text).join('')).join('\n')
|
// table-row (cells) paragraphs stay out of the text editing flow
|
||||||
|
el.innerText = paras
|
||||||
|
.filter((p) => !p.cells)
|
||||||
|
.map((p) => p.runs.map((r) => r.text).join(''))
|
||||||
|
.join('\n')
|
||||||
|
.replaceAll(PAGE_MARK, PAGE_TOKEN)
|
||||||
|
.replaceAll(TOTAL_PAGES_MARK, TOTAL_TOKEN)
|
||||||
cancelRef.current = false
|
cancelRef.current = false
|
||||||
initialTextRef.current = el.innerText
|
initialTextRef.current = el.innerText
|
||||||
el.focus()
|
el.focus()
|
||||||
@@ -93,19 +110,36 @@ export function HeaderFooterArea({
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (el.innerText === initialTextRef.current) return
|
if (el.innerText === initialTextRef.current) return
|
||||||
const lines = el.innerText.replace(/\n+$/, '').split('\n')
|
const lines = el.innerText
|
||||||
const nextParas: HfParagraph[] = lines.map((line, i) => {
|
.replace(/\n+$/, '')
|
||||||
const template = paras[Math.min(i, paras.length - 1)]
|
.replaceAll(PAGE_TOKEN, PAGE_MARK)
|
||||||
|
.replaceAll(TOTAL_TOKEN, TOTAL_PAGES_MARK)
|
||||||
|
.split('\n')
|
||||||
|
const textParas = paras.filter((p) => !p.cells)
|
||||||
|
const templates: HfParagraph[] =
|
||||||
|
textParas.length > 0 ? textParas : [{ align: 'center', runs: [] }]
|
||||||
|
const edited: HfParagraph[] = lines.map((line, i) => {
|
||||||
|
const template = templates[Math.min(i, templates.length - 1)]
|
||||||
const style = template.runs[0] ?? {}
|
const style = template.runs[0] ?? {}
|
||||||
return { ...template, runs: line === '' ? [] : [{ ...style, text: line }] }
|
return { ...template, runs: line === '' ? [] : [{ ...style, text: line }] }
|
||||||
})
|
})
|
||||||
const text = nextParas.map((p) => p.runs.map((r) => r.text).join('')).join('')
|
// splice cells rows back at their original positions among the text paragraphs
|
||||||
|
const nextParas: HfParagraph[] = []
|
||||||
|
let ei = 0
|
||||||
|
for (const p of paras) {
|
||||||
|
if (p.cells) nextParas.push(p)
|
||||||
|
else if (ei < edited.length) nextParas.push(edited[ei++])
|
||||||
|
}
|
||||||
|
nextParas.push(...edited.slice(ei))
|
||||||
|
const text = edited.map((p) => p.runs.map((r) => r.text).join('')).join('')
|
||||||
onCommit({ ...value, text, paras: nextParas })
|
onCommit({ ...value, text, paras: nextParas })
|
||||||
}
|
}
|
||||||
|
|
||||||
const display = (text: string) => {
|
const display = (text: string) => {
|
||||||
const t = text.replaceAll(TOTAL_PAGES_MARK, String(pageTotal ?? 1))
|
const t = text
|
||||||
return value.pageNumber ? t.replace('#', String(pageNo ?? 1)) : t
|
.replaceAll(TOTAL_PAGES_MARK, String(pageTotal ?? 1))
|
||||||
|
.replaceAll(PAGE_MARK, String(pageNo ?? 1))
|
||||||
|
return hfUsesLegacyHash(value) ? t.replace('#', String(pageNo ?? 1)) : t
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -115,7 +149,11 @@ export function HeaderFooterArea({
|
|||||||
readOnly
|
readOnly
|
||||||
? undefined
|
? undefined
|
||||||
: t(kind === 'header' ? 'appDblclickEditHeader' : 'appDblclickEditFooter') +
|
: t(kind === 'header' ? 'appDblclickEditHeader' : 'appDblclickEditFooter') +
|
||||||
(value.pageNumber ? t('appHfPageNumHint') : '')
|
(value.pageNumber
|
||||||
|
? hfUsesLegacyHash(value)
|
||||||
|
? t('appHfPageNumHint')
|
||||||
|
: t('appHfPageNumHint').replace('#', PAGE_TOKEN)
|
||||||
|
: '')
|
||||||
}
|
}
|
||||||
onDoubleClick={() => {
|
onDoubleClick={() => {
|
||||||
if (!readOnly && !editing) setEditing(true)
|
if (!readOnly && !editing) setEditing(true)
|
||||||
@@ -169,30 +207,59 @@ function HfContent({
|
|||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{paras.map((para, i) => (
|
{paras.map((para, i) =>
|
||||||
<div
|
para.cells ? (
|
||||||
key={i}
|
// layout-table row: read-only flex columns (excluded from text editing)
|
||||||
className="page-hf-para"
|
<div key={i} className="page-hf-para page-hf-row">
|
||||||
style={{
|
{para.cells.map((cell, j) => (
|
||||||
...(para.bidi ? { direction: 'rtl' as const } : {}),
|
<div
|
||||||
...(para.align
|
key={j}
|
||||||
? {
|
className="page-hf-cell"
|
||||||
textAlign:
|
style={{
|
||||||
para.align === 'left' || para.align === 'center' || para.align === 'right'
|
...(cell.widthPct ? { width: `${cell.widthPct}%` } : {}),
|
||||||
? para.align
|
...(cell.align
|
||||||
: ('justify' as const),
|
? {
|
||||||
}
|
textAlign:
|
||||||
: {}),
|
cell.align === 'left' || cell.align === 'center' || cell.align === 'right'
|
||||||
}}
|
? cell.align
|
||||||
>
|
: ('justify' as const),
|
||||||
{para.runs.length === 0 ? ' ' : null}
|
}
|
||||||
{para.runs.map((run, j) => (
|
: {}),
|
||||||
<span key={j} style={runStyle(run)}>
|
}}
|
||||||
{display(run.text)}
|
>
|
||||||
</span>
|
{cell.runs.map((run, k) => (
|
||||||
))}
|
<span key={k} style={runStyle(run)}>
|
||||||
</div>
|
{display(run.text)}
|
||||||
))}
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
key={i}
|
||||||
|
className="page-hf-para"
|
||||||
|
style={{
|
||||||
|
...(para.bidi ? { direction: 'rtl' as const } : {}),
|
||||||
|
...(para.align
|
||||||
|
? {
|
||||||
|
textAlign:
|
||||||
|
para.align === 'left' || para.align === 'center' || para.align === 'right'
|
||||||
|
? para.align
|
||||||
|
: ('justify' as const),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{para.runs.length === 0 ? ' ' : null}
|
||||||
|
{para.runs.map((run, j) => (
|
||||||
|
<span key={j} style={runStyle(run)}>
|
||||||
|
{display(run.text)}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,60 @@ import { HeaderFooterArea } from './HeaderFooterArea'
|
|||||||
|
|
||||||
const twipsToPx = (twips: number) => (twips / 1440) * 96
|
const twipsToPx = (twips: number) => (twips / 1440) * 96
|
||||||
|
|
||||||
|
/** Snapshot of one top-level canvas block for pruned per-page clones (virtual gapless coordinates, layout px) */
|
||||||
|
export interface CloneChild {
|
||||||
|
html: string
|
||||||
|
vTop: number
|
||||||
|
vBottom: number
|
||||||
|
/** CSS margins (layout px): spacer heights must exclude them to keep flow positions exact */
|
||||||
|
mt: number
|
||||||
|
mb: number
|
||||||
|
/** zero-height marker (hidden bookmarks etc.): always kept, never worth pruning */
|
||||||
|
zero: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-page full-document clones cost pages × doc DOM; past this budget (top-level
|
||||||
|
* blocks × pages) a 300+-page document OOMs the renderer during preview/export
|
||||||
|
* ("Promise was collected"), so pages switch to pruned clones: blocks outside the
|
||||||
|
* page window collapse into fixed-height spacers.
|
||||||
|
*/
|
||||||
|
const CLONE_PRUNE_BUDGET = 150_000
|
||||||
|
/** window slack around a page (px): keeps neighbours whose floats/overflow bleed into the page */
|
||||||
|
const CLONE_PRUNE_PAD = 2000
|
||||||
|
|
||||||
|
/** pruned clone for one page window: blocks intersecting [from-pad, to+pad] verbatim, pruned runs as spacers (exported for tests) */
|
||||||
|
export function prunedCloneHtml(kids: CloneChild[], from: number, to: number): string {
|
||||||
|
const lo = from - CLONE_PRUNE_PAD
|
||||||
|
const hi = to + CLONE_PRUNE_PAD
|
||||||
|
const parts: string[] = []
|
||||||
|
let lastKept: CloneChild | null = null
|
||||||
|
let pruned = false
|
||||||
|
for (const c of kids) {
|
||||||
|
if (!c.zero && (c.vBottom <= lo || c.vTop >= hi)) {
|
||||||
|
pruned = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (pruned) {
|
||||||
|
// spacer replaces the pruned run; its height re-derives the next block's
|
||||||
|
// border-box top from the previous kept block's margin edge (spacers
|
||||||
|
// suppress margin collapse, so both adjacent margins apply in full)
|
||||||
|
const base = lastKept ? lastKept.vBottom + lastKept.mb : 0
|
||||||
|
const h = Math.max(0, c.vTop - c.mt - base)
|
||||||
|
parts.push(
|
||||||
|
`<div class="pv-prune-spacer" style="margin:0;border:0;padding:0;height:${h}px"></div>`,
|
||||||
|
)
|
||||||
|
pruned = false
|
||||||
|
}
|
||||||
|
parts.push(c.html)
|
||||||
|
// zero markers advance the flow position too (a spacer may have been
|
||||||
|
// emitted before them); skipping them leaves `base` stale and the next
|
||||||
|
// spacer re-adds the distance already consumed, shifting content down
|
||||||
|
lastKept = c
|
||||||
|
}
|
||||||
|
return parts.join('')
|
||||||
|
}
|
||||||
|
|
||||||
export interface HfSet {
|
export interface HfSet {
|
||||||
header: HeaderFooter | null
|
header: HeaderFooter | null
|
||||||
footer: HeaderFooter | null
|
footer: HeaderFooter | null
|
||||||
@@ -105,6 +159,8 @@ export function PaginationPreview({
|
|||||||
/** Top Y of the endnote area (virtual coordinates); null = no endnotes */
|
/** Top Y of the endnote area (virtual coordinates); null = no endnotes */
|
||||||
const [endnotesTop, setEndnotesTop] = useState<number | null>(null)
|
const [endnotesTop, setEndnotesTop] = useState<number | null>(null)
|
||||||
const [html, setHtml] = useState('')
|
const [html, setHtml] = useState('')
|
||||||
|
/** non-null = pruned-clone mode (large documents): per-page windows instead of full clones */
|
||||||
|
const [cloneKids, setCloneKids] = useState<CloneChild[] | null>(null)
|
||||||
/** Live section list: a section whose break block was deleted (unsaved) merges into the next, matching the canvas */
|
/** Live section list: a section whose break block was deleted (unsaved) merges into the next, matching the canvas */
|
||||||
const [secs, setSecs] = useState<SectionInfo[]>(sections)
|
const [secs, setSecs] = useState<SectionInfo[]>(sections)
|
||||||
|
|
||||||
@@ -193,7 +249,41 @@ export function PaginationPreview({
|
|||||||
}
|
}
|
||||||
setSlices(computed)
|
setSlices(computed)
|
||||||
setPageNotes(pageFootnotesOf ? pageFootnotesOf(blocks, computed) : [])
|
setPageNotes(pageFootnotesOf ? pageFootnotesOf(blocks, computed) : [])
|
||||||
setHtml(pm.innerHTML)
|
// Per-page full clones explode on large documents (pages × doc DOM →
|
||||||
|
// renderer OOM / "Promise was collected" during printToPDF). Past the
|
||||||
|
// budget, snapshot per-block geometry and render pruned windows instead.
|
||||||
|
const kidEls = Array.from(pm.children) as HTMLElement[]
|
||||||
|
if (computed.length * kidEls.length >= CLONE_PRUNE_BUDGET) {
|
||||||
|
const metas: CloneChild[] = []
|
||||||
|
let gapAccum = 0
|
||||||
|
for (const el of kidEls) {
|
||||||
|
const rect = el.getBoundingClientRect()
|
||||||
|
if (el.classList.contains('page-gap')) {
|
||||||
|
gapAccum += rect.height
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let innerGap = 0
|
||||||
|
for (const g of el.querySelectorAll('.page-gap-inline'))
|
||||||
|
innerGap += g.getBoundingClientRect().height
|
||||||
|
const cs = window.getComputedStyle(el)
|
||||||
|
const vTop = (rect.top - origin - gapAccum) / factor
|
||||||
|
const h = (rect.height - innerGap) / factor
|
||||||
|
gapAccum += innerGap
|
||||||
|
metas.push({
|
||||||
|
html: el.outerHTML,
|
||||||
|
vTop,
|
||||||
|
vBottom: vTop + h,
|
||||||
|
mt: parseFloat(cs.marginTop) || 0,
|
||||||
|
mb: parseFloat(cs.marginBottom) || 0,
|
||||||
|
zero: rect.height <= 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
setCloneKids(metas)
|
||||||
|
setHtml('')
|
||||||
|
} else {
|
||||||
|
setCloneKids(null)
|
||||||
|
setHtml(pm.innerHTML)
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (colFlow) pm.classList.remove('measuring-columns')
|
if (colFlow) pm.classList.remove('measuring-columns')
|
||||||
}
|
}
|
||||||
@@ -374,7 +464,15 @@ export function PaginationPreview({
|
|||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className="doc-page pv-content"
|
className="doc-page pv-content"
|
||||||
dangerouslySetInnerHTML={{ __html: html }}
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: cloneKids
|
||||||
|
? prunedCloneHtml(
|
||||||
|
cloneKids,
|
||||||
|
slice.repeatHeader.top,
|
||||||
|
slice.repeatHeader.top + slice.repeatHeader.height,
|
||||||
|
)
|
||||||
|
: html,
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -411,7 +509,15 @@ export function PaginationPreview({
|
|||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className="doc-page pv-content"
|
className="doc-page pv-content"
|
||||||
dangerouslySetInnerHTML={{ __html: html }}
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: cloneKids
|
||||||
|
? prunedCloneHtml(
|
||||||
|
cloneKids,
|
||||||
|
col.repeatHeader.top,
|
||||||
|
col.repeatHeader.top + col.repeatHeader.height,
|
||||||
|
)
|
||||||
|
: html,
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -431,7 +537,11 @@ export function PaginationPreview({
|
|||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className="doc-page pv-content"
|
className="doc-page pv-content"
|
||||||
dangerouslySetInnerHTML={{ __html: html }}
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: cloneKids
|
||||||
|
? prunedCloneHtml(cloneKids, col.start, col.end)
|
||||||
|
: html,
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -463,7 +573,16 @@ export function PaginationPreview({
|
|||||||
<div className="pv-offset" style={{ marginTop: -slice.start, width: wrapW }}>
|
<div className="pv-offset" style={{ marginTop: -slice.start, width: wrapW }}>
|
||||||
<div
|
<div
|
||||||
className="doc-page pv-content"
|
className="doc-page pv-content"
|
||||||
dangerouslySetInnerHTML={{ __html: html }}
|
dangerouslySetInnerHTML={{
|
||||||
|
__html: cloneKids
|
||||||
|
? prunedCloneHtml(
|
||||||
|
cloneKids,
|
||||||
|
slice.start,
|
||||||
|
// last page opens its clip to full capacity; the window must cover it
|
||||||
|
i === slices.length - 1 ? slice.start + contentH : slice.end,
|
||||||
|
)
|
||||||
|
: html,
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -185,7 +185,12 @@ export function CutoutDialog({ dataUrl, onApply, onCancel }: CutoutProps) {
|
|||||||
>
|
>
|
||||||
{error ? (
|
{error ? (
|
||||||
<span
|
<span
|
||||||
style={{ color: '#c33', background: '#fff', padding: '4px 10px', borderRadius: 4 }}
|
style={{
|
||||||
|
color: 'var(--danger)',
|
||||||
|
background: 'var(--surface)',
|
||||||
|
padding: '4px 10px',
|
||||||
|
borderRadius: 4,
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{t(error)}
|
{t(error)}
|
||||||
</span>
|
</span>
|
||||||
@@ -199,7 +204,9 @@ export function CutoutDialog({ dataUrl, onApply, onCancel }: CutoutProps) {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{!loaded && !error && <span style={{ color: '#888' }}>{t('ribbonLoading')}</span>}
|
{!loaded && !error && (
|
||||||
|
<span style={{ color: 'var(--text-muted)' }}>{t('ribbonLoading')}</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<label style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12 }}>
|
<label style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12 }}>
|
||||||
<span style={{ whiteSpace: 'nowrap' }}>{t('ribbonCutoutTolerance')}</span>
|
<span style={{ whiteSpace: 'nowrap' }}>{t('ribbonCutoutTolerance')}</span>
|
||||||
@@ -215,7 +222,7 @@ export function CutoutDialog({ dataUrl, onApply, onCancel }: CutoutProps) {
|
|||||||
/>
|
/>
|
||||||
<span style={{ width: 32, textAlign: 'right' }}>{tolerance}</span>
|
<span style={{ width: 32, textAlign: 'right' }}>{tolerance}</span>
|
||||||
</label>
|
</label>
|
||||||
<div style={{ fontSize: 12, color: '#888', marginTop: 4 }}>
|
<div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4 }}>
|
||||||
{t('ribbonCutoutHint', { pct: removedPct })}
|
{t('ribbonCutoutHint', { pct: removedPct })}
|
||||||
</div>
|
</div>
|
||||||
<div className="modal-actions">
|
<div className="modal-actions">
|
||||||
@@ -458,7 +465,12 @@ export function CropDialog({ dataUrl, onApply, onCancel }: CropProps) {
|
|||||||
>
|
>
|
||||||
{error ? (
|
{error ? (
|
||||||
<span
|
<span
|
||||||
style={{ color: '#c33', background: '#fff', padding: '4px 10px', borderRadius: 4 }}
|
style={{
|
||||||
|
color: 'var(--danger)',
|
||||||
|
background: 'var(--surface)',
|
||||||
|
padding: '4px 10px',
|
||||||
|
borderRadius: 4,
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{t(error)}
|
{t(error)}
|
||||||
</span>
|
</span>
|
||||||
@@ -536,10 +548,12 @@ export function CropDialog({ dataUrl, onApply, onCancel }: CropProps) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<span style={{ color: '#888' }}>{t('ribbonLoading')}</span>
|
<span style={{ color: 'var(--text-muted)' }}>{t('ribbonLoading')}</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div style={{ fontSize: 12, color: '#888', marginTop: 8 }}>{t('ribbonCropHint')}</div>
|
<div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 8 }}>
|
||||||
|
{t('ribbonCropHint')}
|
||||||
|
</div>
|
||||||
<div className="modal-actions">
|
<div className="modal-actions">
|
||||||
<button onClick={onCancel}>{t('ribbonCancel')}</button>
|
<button onClick={onCancel}>{t('ribbonCancel')}</button>
|
||||||
<button className="primary" onClick={apply} disabled={!loaded || !!error}>
|
<button className="primary" onClick={apply} disabled={!loaded || !!error}>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { memo, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
|||||||
import type { CSSProperties, ReactNode } from 'react'
|
import type { CSSProperties, ReactNode } from 'react'
|
||||||
import type { ChainedCommands, Editor } from '@tiptap/core'
|
import type { ChainedCommands, Editor } from '@tiptap/core'
|
||||||
import type { Command } from '@tiptap/pm/state'
|
import type { Command } from '@tiptap/pm/state'
|
||||||
|
import type { Node as PMNode } from '@tiptap/pm/model'
|
||||||
import {
|
import {
|
||||||
addColumnAfter,
|
addColumnAfter,
|
||||||
addColumnBefore,
|
addColumnBefore,
|
||||||
@@ -89,8 +90,12 @@ import {
|
|||||||
IconPalette,
|
IconPalette,
|
||||||
IconPaste,
|
IconPaste,
|
||||||
IconPilcrow,
|
IconPilcrow,
|
||||||
|
IconFlipH,
|
||||||
|
IconFlipV,
|
||||||
IconRemoveBg,
|
IconRemoveBg,
|
||||||
IconReplacePicture,
|
IconReplacePicture,
|
||||||
|
IconRotateLeft,
|
||||||
|
IconRotateRight,
|
||||||
IconRowDelete,
|
IconRowDelete,
|
||||||
IconRowInsertAbove,
|
IconRowInsertAbove,
|
||||||
IconRowInsertBelow,
|
IconRowInsertBelow,
|
||||||
@@ -284,6 +289,11 @@ const FONT_SIZES = [
|
|||||||
5, 5.5, 6.5, 7.5, 8, 9, 10, 10.5, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72,
|
5, 5.5, 6.5, 7.5, 8, 9, 10, 10.5, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72,
|
||||||
]
|
]
|
||||||
|
|
||||||
|
// A+/A- clicks closer together than this coalesce into one trailing apply;
|
||||||
|
// must sit above burst-click spacing (~100-200ms) yet stay short enough that
|
||||||
|
// the deferred re-layout still feels attached to the click.
|
||||||
|
const FONT_STEP_COALESCE_MS = 300
|
||||||
|
|
||||||
const THEME_COLORS: Array<{ nameKey: StringKey; hex: string }> = [
|
const THEME_COLORS: Array<{ nameKey: StringKey; hex: string }> = [
|
||||||
{ nameKey: 'ribbonColorWhite', hex: 'FFFFFF' },
|
{ nameKey: 'ribbonColorWhite', hex: 'FFFFFF' },
|
||||||
{ nameKey: 'ribbonColorBlack', hex: '000000' },
|
{ nameKey: 'ribbonColorBlack', hex: '000000' },
|
||||||
@@ -669,6 +679,15 @@ function RibbonInner({
|
|||||||
const [penHighlight, setPenHighlight] = useState('yellow')
|
const [penHighlight, setPenHighlight] = useState('yellow')
|
||||||
const [painter, setPainter] = useState<PainterState | null>(null)
|
const [painter, setPainter] = useState<PainterState | null>(null)
|
||||||
const ribbonRef = useRef<HTMLDivElement>(null)
|
const ribbonRef = useRef<HTMLDivElement>(null)
|
||||||
|
const fontStepRef = useRef<{
|
||||||
|
pending: number | null
|
||||||
|
applied: number | null
|
||||||
|
timer: number | null
|
||||||
|
// editor snapshot the deferred apply validates against (stale-apply guard)
|
||||||
|
anchor: number
|
||||||
|
head: number
|
||||||
|
doc: PMNode | null
|
||||||
|
}>({ pending: null, applied: null, timer: null, anchor: -1, head: -1, doc: null })
|
||||||
const lastRegularTab = useRef<(typeof TABS)[number]>('home')
|
const lastRegularTab = useRef<(typeof TABS)[number]>('home')
|
||||||
const wasInTable = useRef(false)
|
const wasInTable = useRef(false)
|
||||||
const wasInImage = useRef(false)
|
const wasInImage = useRef(false)
|
||||||
@@ -783,10 +802,9 @@ function RibbonInner({
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Replace the selected image's bytes (shared by Replace Picture / remove background / crop).
|
* Replace the selected image's bytes (shared by Replace Picture / remove background / crop).
|
||||||
* The original image's patch-save only supports size/alignment/wrap; swapping bytes must go
|
* Original images (docxIndex set) swap bytes in place via the imageReplace patch: the
|
||||||
* through the genImage new-image embed branch, so docxIndex is cleared (on save the old
|
* drawing XML survives, so wrap/position/docxIndex — and with them the Position gallery —
|
||||||
* block is treated as deleted, the new image is written at the same position, and
|
* keep working. Images not yet saved (genImage) just update their pending payload.
|
||||||
* alignment/wrap are inherited from attributes).
|
|
||||||
* Display size keeps the current width; height adapts to the new image's aspect ratio.
|
* Display size keeps the current width; height adapts to the new image's aspect ratio.
|
||||||
*/
|
*/
|
||||||
const applyPictureBytes = async (dataUrl: string) => {
|
const applyPictureBytes = async (dataUrl: string) => {
|
||||||
@@ -800,6 +818,7 @@ function RibbonInner({
|
|||||||
const currentW = Number(attrs.imageWidthPx) || Math.min(natural.width, 620)
|
const currentW = Number(attrs.imageWidthPx) || Math.min(natural.width, 620)
|
||||||
const w = Math.max(1, Math.round(currentW))
|
const w = Math.max(1, Math.round(currentW))
|
||||||
const h = Math.max(1, Math.round((currentW * natural.height) / natural.width))
|
const h = Math.max(1, Math.round((currentW * natural.height) / natural.width))
|
||||||
|
const isOriginal = attrs.docxIndex !== null && attrs.docxIndex !== undefined
|
||||||
editor
|
editor
|
||||||
.chain()
|
.chain()
|
||||||
.focus()
|
.focus()
|
||||||
@@ -807,8 +826,9 @@ function RibbonInner({
|
|||||||
imageDataUrl: dataUrl,
|
imageDataUrl: dataUrl,
|
||||||
imageWidthPx: w,
|
imageWidthPx: w,
|
||||||
imageHeightPx: h,
|
imageHeightPx: h,
|
||||||
genImage: { base64: m[2], mime: m[1], widthPx: w, heightPx: h },
|
...(isOriginal
|
||||||
docxIndex: null,
|
? { imageReplace: { base64: m[2], mime: m[1] } }
|
||||||
|
: { genImage: { base64: m[2], mime: m[1], widthPx: w, heightPx: h } }),
|
||||||
})
|
})
|
||||||
.run()
|
.run()
|
||||||
} catch {
|
} catch {
|
||||||
@@ -822,6 +842,30 @@ function RibbonInner({
|
|||||||
await applyPictureBytes(`data:${picked.mime};base64,${picked.base64}`)
|
await applyPictureBytes(`data:${picked.mime};base64,${picked.base64}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const rotatePicture = (deltaDeg: number) => {
|
||||||
|
if (!canEdit) return
|
||||||
|
const attrs = editor.getAttributes('docProtected')
|
||||||
|
if (attrs?.blockType !== 'image') return
|
||||||
|
const next = ((((Number(attrs.imageRotDeg) || 0) + deltaDeg) % 360) + 360) % 360
|
||||||
|
editor
|
||||||
|
.chain()
|
||||||
|
.focus()
|
||||||
|
.updateAttributes('docProtected', { imageRotDeg: next || null })
|
||||||
|
.run()
|
||||||
|
}
|
||||||
|
|
||||||
|
const flipPicture = (axis: 'h' | 'v') => {
|
||||||
|
if (!canEdit) return
|
||||||
|
const attrs = editor.getAttributes('docProtected')
|
||||||
|
if (attrs?.blockType !== 'image') return
|
||||||
|
const key = axis === 'h' ? 'imageFlipH' : 'imageFlipV'
|
||||||
|
editor
|
||||||
|
.chain()
|
||||||
|
.focus()
|
||||||
|
.updateAttributes('docProtected', { [key]: !attrs[key] })
|
||||||
|
.run()
|
||||||
|
}
|
||||||
|
|
||||||
/** Set the image display size proportionally (cm input; either side drives the other) */
|
/** Set the image display size proportionally (cm input; either side drives the other) */
|
||||||
const setPictureSizeCm = (dim: 'w' | 'h', cm: number) => {
|
const setPictureSizeCm = (dim: 'w' | 'h', cm: number) => {
|
||||||
if (!canEdit) return
|
if (!canEdit) return
|
||||||
@@ -1216,18 +1260,59 @@ function RibbonInner({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const stepFontSize = (dir: 1 | -1) => {
|
const stepFontSize = (dir: 1 | -1) => {
|
||||||
const idx = FONT_SIZES.findIndex((s) => s >= currentSize)
|
const step = (base: number): number => {
|
||||||
let next: number
|
const idx = FONT_SIZES.findIndex((s) => s >= base)
|
||||||
if (dir === 1)
|
if (dir === 1)
|
||||||
next =
|
return FONT_SIZES[
|
||||||
FONT_SIZES[
|
|
||||||
Math.min(
|
Math.min(
|
||||||
idx === -1 ? FONT_SIZES.length : idx + (FONT_SIZES[idx] === currentSize ? 1 : 0),
|
idx === -1 ? FONT_SIZES.length : idx + (FONT_SIZES[idx] === base ? 1 : 0),
|
||||||
FONT_SIZES.length - 1,
|
FONT_SIZES.length - 1,
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
else next = FONT_SIZES[Math.max(idx === -1 ? FONT_SIZES.length - 1 : idx - 1, 0)]
|
return FONT_SIZES[Math.max(idx === -1 ? FONT_SIZES.length - 1 : idx - 1, 0)]
|
||||||
setTextStyle({ sizeHalfPoints: Math.round(next * 2) })
|
}
|
||||||
|
// Every applied size change re-paginates the whole document synchronously —
|
||||||
|
// ~700ms per click on table-heavy documents — so clicking A+/A- in a burst
|
||||||
|
// froze the UI for seconds. Apply the first click immediately (a single
|
||||||
|
// click keeps instant feedback); clicks landing inside the coalesce window
|
||||||
|
// only advance the pending size, and one trailing apply lays out the final
|
||||||
|
// size. `pending` also covers fs.fontSizePt lagging the last apply within
|
||||||
|
// the window.
|
||||||
|
const st = fontStepRef.current
|
||||||
|
const next = step(st.pending ?? currentSize)
|
||||||
|
st.pending = next
|
||||||
|
if (st.timer === null) {
|
||||||
|
st.applied = next
|
||||||
|
setTextStyle({ sizeHalfPoints: Math.round(next * 2) })
|
||||||
|
} else {
|
||||||
|
window.clearTimeout(st.timer)
|
||||||
|
}
|
||||||
|
// Snapshot after the (possible) leading apply: the deferred apply is only
|
||||||
|
// valid while nothing else has touched the editor. A selection move, an
|
||||||
|
// undo, or a size set another way each shows up as a selection or document
|
||||||
|
// change and must invalidate the pending step instead of being overwritten.
|
||||||
|
const target = ed
|
||||||
|
st.anchor = target.state.selection.anchor
|
||||||
|
st.head = target.state.selection.head
|
||||||
|
st.doc = target.state.doc
|
||||||
|
st.timer = window.setTimeout(() => {
|
||||||
|
st.timer = null
|
||||||
|
const pending = st.pending
|
||||||
|
st.pending = null
|
||||||
|
if (pending === null || pending === st.applied || !canEdit) return
|
||||||
|
if (
|
||||||
|
target.state.selection.anchor !== st.anchor ||
|
||||||
|
target.state.selection.head !== st.head ||
|
||||||
|
target.state.doc !== st.doc
|
||||||
|
)
|
||||||
|
return
|
||||||
|
st.applied = pending
|
||||||
|
// deliberately no focus(): a deferred apply must never pull focus back
|
||||||
|
target
|
||||||
|
.chain()
|
||||||
|
.setMark('docTextStyle', { sizeHalfPoints: Math.round(pending * 2) })
|
||||||
|
.run()
|
||||||
|
}, FONT_STEP_COALESCE_MS)
|
||||||
}
|
}
|
||||||
|
|
||||||
const toggleVertAlign = (kind: 'superscript' | 'subscript') => {
|
const toggleVertAlign = (kind: 'superscript' | 'subscript') => {
|
||||||
@@ -1625,6 +1710,40 @@ function RibbonInner({
|
|||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
<div className="table-tool-row">
|
||||||
|
<button
|
||||||
|
className="table-tool-button"
|
||||||
|
disabled={!canEdit}
|
||||||
|
title={t('ribbonRotateRight')}
|
||||||
|
onClick={() => rotatePicture(90)}
|
||||||
|
>
|
||||||
|
<IconRotateRight />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="table-tool-button"
|
||||||
|
disabled={!canEdit}
|
||||||
|
title={t('ribbonRotateLeft')}
|
||||||
|
onClick={() => rotatePicture(-90)}
|
||||||
|
>
|
||||||
|
<IconRotateLeft />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={fs.imageFlipH ? 'table-tool-button active' : 'table-tool-button'}
|
||||||
|
disabled={!canEdit}
|
||||||
|
title={t('ribbonFlipH')}
|
||||||
|
onClick={() => flipPicture('h')}
|
||||||
|
>
|
||||||
|
<IconFlipH />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={fs.imageFlipV ? 'table-tool-button active' : 'table-tool-button'}
|
||||||
|
disabled={!canEdit}
|
||||||
|
title={t('ribbonFlipV')}
|
||||||
|
onClick={() => flipPicture('v')}
|
||||||
|
>
|
||||||
|
<IconFlipV />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
<div className="ribbon-group-label">{t('ribbonGroupArrange')}</div>
|
<div className="ribbon-group-label">{t('ribbonGroupArrange')}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="ribbon-sep" />
|
<div className="ribbon-sep" />
|
||||||
|
|||||||
@@ -337,6 +337,44 @@ export function IconCrop(props: IconProps) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function IconRotateRight(props: IconProps) {
|
||||||
|
return (
|
||||||
|
<Svg {...props}>
|
||||||
|
<path d="M 12.4 6.2 a 4.6 4.6 0 1 0 0.6 3.3" />
|
||||||
|
<path d="M 12.7 3.2 v 3 h -3" />
|
||||||
|
</Svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IconRotateLeft(props: IconProps) {
|
||||||
|
return (
|
||||||
|
<Svg {...props}>
|
||||||
|
<path d="M 3.6 6.2 a 4.6 4.6 0 1 1 -0.6 3.3" />
|
||||||
|
<path d="M 3.3 3.2 v 3 h 3" />
|
||||||
|
</Svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IconFlipH(props: IconProps) {
|
||||||
|
return (
|
||||||
|
<Svg {...props}>
|
||||||
|
<path d="M 8 2.6 v 10.8" strokeDasharray="1.7 1.5" />
|
||||||
|
<path d="M 6 5.2 L 2.6 8 L 6 10.8 Z" />
|
||||||
|
<path d="M 10 5.2 L 13.4 8 L 10 10.8 Z" fill="currentColor" />
|
||||||
|
</Svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IconFlipV(props: IconProps) {
|
||||||
|
return (
|
||||||
|
<Svg {...props}>
|
||||||
|
<path d="M 2.6 8 h 10.8" strokeDasharray="1.7 1.5" />
|
||||||
|
<path d="M 5.2 6 L 8 2.6 L 10.8 6 Z" />
|
||||||
|
<path d="M 5.2 10 L 8 13.4 L 10.8 10 Z" fill="currentColor" />
|
||||||
|
</Svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
export function IconReplacePicture(props: IconProps) {
|
export function IconReplacePicture(props: IconProps) {
|
||||||
return (
|
return (
|
||||||
<Svg {...props}>
|
<Svg {...props}>
|
||||||
@@ -1506,7 +1544,7 @@ export function GensparkMark({ size = 30 }: { size?: number }) {
|
|||||||
>
|
>
|
||||||
<path
|
<path
|
||||||
d="M105.115 0H24.6428C11.0443 0 0 11.0686 0 24.6915V105.334C0 118.981 11.0199 130.025 24.6428 130.025H105.115C118.714 130.025 129.758 118.957 129.758 105.334V24.6915C129.758 11.0443 118.714 0 105.115 0ZM71.5201 35.2735C85.5078 33.1571 86.7729 31.9164 88.865 17.88C88.938 17.4421 89.3028 17.1259 89.7407 17.1259C90.1786 17.1259 90.5435 17.4421 90.6164 17.88C92.7328 31.8921 93.9735 33.1571 107.961 35.2735C108.399 35.3465 108.715 35.7114 108.715 36.1493C108.715 36.5871 108.399 36.952 107.961 37.025C93.9249 39.1414 92.7085 40.4064 90.5677 54.6131C90.5191 54.9537 90.2516 55.197 89.911 55.197C89.5704 55.197 89.3028 54.9537 89.2542 54.6131C87.1134 40.4064 85.5565 39.1658 71.4958 37.025C71.0579 36.952 70.7417 36.5871 70.7417 36.1493C70.7417 35.7114 71.0579 35.3465 71.4958 35.2735H71.5201ZM101.758 78.5261C101.758 78.8181 101.563 79.037 101.271 79.0856C92.3193 80.4236 91.5652 81.2264 90.2029 90.2759C90.1786 90.4948 89.9839 90.6408 89.7893 90.6408C89.5703 90.6408 89.4001 90.4948 89.3758 90.2759C88.0135 81.2507 87.0161 80.4479 78.0883 79.0856C77.7964 79.037 77.6017 78.7937 77.6017 78.5261C77.6017 78.2342 77.7964 78.0153 78.0883 77.9666C86.9918 76.6287 87.7703 75.8259 89.1326 66.898C89.1812 66.6061 89.4244 66.4115 89.692 66.4115C89.9839 66.4115 90.2028 66.6061 90.2515 66.898C91.5894 75.8259 92.3923 76.6043 101.296 77.9666C101.588 78.0153 101.782 78.2585 101.782 78.5261H101.758ZM16.5178 54.8077C16.5178 54.1023 17.0286 53.4941 17.7341 53.3968C40.1388 50.0154 42.1093 47.9963 45.4907 25.5672C45.588 24.8861 46.1961 24.3509 46.9016 24.3509C47.6071 24.3509 48.191 24.8617 48.3126 25.5672C51.694 47.9963 53.6887 50.0154 76.0691 53.3968C76.7503 53.4941 77.2855 54.1023 77.2855 54.8077C77.2855 55.5132 76.7746 56.1214 76.0691 56.2187C53.5914 59.6244 51.6696 61.6192 48.2639 84.3645C48.1909 84.8754 47.7287 85.2889 47.2179 85.2889C46.707 85.2889 46.2448 84.8997 46.1718 84.3645C42.7418 61.6435 40.2604 59.6244 17.7584 56.2187C17.0772 56.1214 16.542 55.5132 16.542 54.8077H16.5178ZM112.097 109.591C112.097 111.416 110.613 112.9 108.813 112.9H21.2614C19.4369 112.9 17.9774 111.416 17.9774 109.591V102.658C17.9774 100.834 19.4612 99.3497 21.2614 99.3497H108.813C110.637 99.3497 112.097 100.834 112.097 102.658V109.591Z"
|
d="M105.115 0H24.6428C11.0443 0 0 11.0686 0 24.6915V105.334C0 118.981 11.0199 130.025 24.6428 130.025H105.115C118.714 130.025 129.758 118.957 129.758 105.334V24.6915C129.758 11.0443 118.714 0 105.115 0ZM71.5201 35.2735C85.5078 33.1571 86.7729 31.9164 88.865 17.88C88.938 17.4421 89.3028 17.1259 89.7407 17.1259C90.1786 17.1259 90.5435 17.4421 90.6164 17.88C92.7328 31.8921 93.9735 33.1571 107.961 35.2735C108.399 35.3465 108.715 35.7114 108.715 36.1493C108.715 36.5871 108.399 36.952 107.961 37.025C93.9249 39.1414 92.7085 40.4064 90.5677 54.6131C90.5191 54.9537 90.2516 55.197 89.911 55.197C89.5704 55.197 89.3028 54.9537 89.2542 54.6131C87.1134 40.4064 85.5565 39.1658 71.4958 37.025C71.0579 36.952 70.7417 36.5871 70.7417 36.1493C70.7417 35.7114 71.0579 35.3465 71.4958 35.2735H71.5201ZM101.758 78.5261C101.758 78.8181 101.563 79.037 101.271 79.0856C92.3193 80.4236 91.5652 81.2264 90.2029 90.2759C90.1786 90.4948 89.9839 90.6408 89.7893 90.6408C89.5703 90.6408 89.4001 90.4948 89.3758 90.2759C88.0135 81.2507 87.0161 80.4479 78.0883 79.0856C77.7964 79.037 77.6017 78.7937 77.6017 78.5261C77.6017 78.2342 77.7964 78.0153 78.0883 77.9666C86.9918 76.6287 87.7703 75.8259 89.1326 66.898C89.1812 66.6061 89.4244 66.4115 89.692 66.4115C89.9839 66.4115 90.2028 66.6061 90.2515 66.898C91.5894 75.8259 92.3923 76.6043 101.296 77.9666C101.588 78.0153 101.782 78.2585 101.782 78.5261H101.758ZM16.5178 54.8077C16.5178 54.1023 17.0286 53.4941 17.7341 53.3968C40.1388 50.0154 42.1093 47.9963 45.4907 25.5672C45.588 24.8861 46.1961 24.3509 46.9016 24.3509C47.6071 24.3509 48.191 24.8617 48.3126 25.5672C51.694 47.9963 53.6887 50.0154 76.0691 53.3968C76.7503 53.4941 77.2855 54.1023 77.2855 54.8077C77.2855 55.5132 76.7746 56.1214 76.0691 56.2187C53.5914 59.6244 51.6696 61.6192 48.2639 84.3645C48.1909 84.8754 47.7287 85.2889 47.2179 85.2889C46.707 85.2889 46.2448 84.8997 46.1718 84.3645C42.7418 61.6435 40.2604 59.6244 17.7584 56.2187C17.0772 56.1214 16.542 55.5132 16.542 54.8077H16.5178ZM112.097 109.591C112.097 111.416 110.613 112.9 108.813 112.9H21.2614C19.4369 112.9 17.9774 111.416 17.9774 109.591V102.658C17.9774 100.834 19.4612 99.3497 21.2614 99.3497H108.813C110.637 99.3497 112.097 100.834 112.097 102.658V109.591Z"
|
||||||
fill="#000"
|
fill="currentColor"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -29,6 +29,8 @@ export interface RibbonFormatState {
|
|||||||
imageAlign: string | null
|
imageAlign: string | null
|
||||||
imageWidthPx: number | null
|
imageWidthPx: number | null
|
||||||
imageHeightPx: number | null
|
imageHeightPx: number | null
|
||||||
|
imageFlipH: boolean
|
||||||
|
imageFlipV: boolean
|
||||||
imageHasDocxIndex: boolean
|
imageHasDocxIndex: boolean
|
||||||
textboxSelected: boolean
|
textboxSelected: boolean
|
||||||
shapeFill: string | null
|
shapeFill: string | null
|
||||||
@@ -77,6 +79,8 @@ export const EMPTY_FORMAT_STATE: RibbonFormatState = {
|
|||||||
imageAlign: null,
|
imageAlign: null,
|
||||||
imageWidthPx: null,
|
imageWidthPx: null,
|
||||||
imageHeightPx: null,
|
imageHeightPx: null,
|
||||||
|
imageFlipH: false,
|
||||||
|
imageFlipV: false,
|
||||||
imageHasDocxIndex: false,
|
imageHasDocxIndex: false,
|
||||||
textboxSelected: false,
|
textboxSelected: false,
|
||||||
shapeFill: null,
|
shapeFill: null,
|
||||||
@@ -193,6 +197,8 @@ export function computeFormatState(
|
|||||||
imageAlign: str(protAttrs.imageAlign),
|
imageAlign: str(protAttrs.imageAlign),
|
||||||
imageWidthPx: num(protAttrs.imageWidthPx),
|
imageWidthPx: num(protAttrs.imageWidthPx),
|
||||||
imageHeightPx: num(protAttrs.imageHeightPx),
|
imageHeightPx: num(protAttrs.imageHeightPx),
|
||||||
|
imageFlipH: !!protAttrs.imageFlipH,
|
||||||
|
imageFlipV: !!protAttrs.imageFlipV,
|
||||||
imageHasDocxIndex: protAttrs.docxIndex != null,
|
imageHasDocxIndex: protAttrs.docxIndex != null,
|
||||||
textboxSelected: Array.isArray(protAttrs.textboxes) && protAttrs.textboxes.length > 0,
|
textboxSelected: Array.isArray(protAttrs.textboxes) && protAttrs.textboxes.length > 0,
|
||||||
shapeFill: Array.isArray(protAttrs.textboxes)
|
shapeFill: Array.isArray(protAttrs.textboxes)
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type { CSSProperties } from 'react'
|
|||||||
import type { Editor } from '@tiptap/core'
|
import type { Editor } from '@tiptap/core'
|
||||||
import { ShapePreview, WORDART_PRESETS, wordArtStrokePx } from '@genoffice/ui'
|
import { ShapePreview, WORDART_PRESETS, wordArtStrokePx } from '@genoffice/ui'
|
||||||
import type { ChartDisplay, HeaderFooter, NewChart } from '@genoffice/docx-engine'
|
import type { ChartDisplay, HeaderFooter, NewChart } from '@genoffice/docx-engine'
|
||||||
|
import { hfHasPageField, hfWithoutPageMarks } from '../editor/hf-dom'
|
||||||
import { EquationGallery, EquationModal } from './EquationModal'
|
import { EquationGallery, EquationModal } from './EquationModal'
|
||||||
import { COVER_PRESETS, insertCoverPage, type CoverPreset } from '../editor/cover-pages'
|
import { COVER_PRESETS, insertCoverPage, type CoverPreset } from '../editor/cover-pages'
|
||||||
import { startShapeDrawMode } from '../editor/shape-draw'
|
import { startShapeDrawMode } from '../editor/shape-draw'
|
||||||
@@ -1066,12 +1067,8 @@ export function InsertTab({
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (footer?.pageNumber || footer?.text.includes('#')) {
|
if (hfHasPageField(footer)) onFooter(hfWithoutPageMarks(footer!))
|
||||||
onFooter({ text: (footer?.text ?? '').replace(/#/g, ''), pageNumber: false })
|
if (hfHasPageField(header)) onHeader(hfWithoutPageMarks(header!))
|
||||||
}
|
|
||||||
if (header?.pageNumber || header?.text.includes('#')) {
|
|
||||||
onHeader({ text: (header?.text ?? '').replace(/#/g, ''), pageNumber: false })
|
|
||||||
}
|
|
||||||
setDropdown(() => null)
|
setDropdown(() => null)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -49,6 +49,21 @@ export function hfFromPart(part: HfPartInfo | null | undefined): HeaderFooter |
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Variant a resting canvas header/footer area shows (no variant chip picked):
|
||||||
|
* the header area sits on page 1 (titlePg -> first-page variant, blank when
|
||||||
|
* that part is absent — Word semantics), the footer area on the last page.
|
||||||
|
*/
|
||||||
|
export function restingHfAreaVariant(
|
||||||
|
kind: 'header' | 'footer',
|
||||||
|
opts: { titlePg: boolean; evenOddHf: boolean; pageCount: number; lastPageNo?: number },
|
||||||
|
): HfView {
|
||||||
|
if (kind === 'header') return opts.titlePg ? 'first' : 'default'
|
||||||
|
if (opts.titlePg && opts.pageCount <= 1) return 'first'
|
||||||
|
if (opts.evenOddHf && (opts.lastPageNo ?? opts.pageCount) % 2 === 0) return 'even'
|
||||||
|
return 'default'
|
||||||
|
}
|
||||||
|
|
||||||
export function hfVariantsFromParsed(parsed: ParsedDocFull): HfVariantsState {
|
export function hfVariantsFromParsed(parsed: ParsedDocFull): HfVariantsState {
|
||||||
return {
|
return {
|
||||||
headerFirst: hfFromPart(parsed.headerFirst),
|
headerFirst: hfFromPart(parsed.headerFirst),
|
||||||
|
|||||||
@@ -3,8 +3,10 @@ import {
|
|||||||
cssDualFontFamily,
|
cssDualFontFamily,
|
||||||
cssFontFamily,
|
cssFontFamily,
|
||||||
cssLineHeight,
|
cssLineHeight,
|
||||||
|
krLineFactor,
|
||||||
lineHeightFactor,
|
lineHeightFactor,
|
||||||
textHasCjk,
|
textHasCjk,
|
||||||
|
isKoreanFontName,
|
||||||
} from './line-metrics'
|
} from './line-metrics'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -55,9 +57,16 @@ export function docHasCjk(parsed: ParsedDocFull): boolean {
|
|||||||
* line height). Recomputed live while editing via App's liveDocCjk.
|
* line height). Recomputed live while editing via App's liveDocCjk.
|
||||||
*/
|
*/
|
||||||
export function docLineFactor(parsed: ParsedDocFull, hasCjk: boolean): number {
|
export function docLineFactor(parsed: ParsedDocFull, hasCjk: boolean): number {
|
||||||
const dd = parsed.docDefaults
|
// Normal's EA face wins over docDefaults (a Normal declaring e.g. Noto KR must
|
||||||
|
// not fall back to the SimSun 1.3 factor). font === fontAscii means only a
|
||||||
|
// Latin slot was declared (StyleDisplay.font is EA-first) — not an EA choice.
|
||||||
|
const normal = defaultParaDisplay(parsed)
|
||||||
|
const normalEa =
|
||||||
|
normal?.font && (normal.font !== normal.fontAscii || isKoreanFontName(normal.font))
|
||||||
|
? normal.font
|
||||||
|
: undefined
|
||||||
return hasCjk
|
return hasCjk
|
||||||
? lineHeightFactor(dd?.eastAsiaFont ?? '宋体')
|
? lineHeightFactor(normalEa ?? parsed.docDefaults?.eastAsiaFont ?? 'SimSun')
|
||||||
: lineHeightFactor(docBodyFont(parsed) ?? 'Calibri')
|
: lineHeightFactor(docBodyFont(parsed) ?? 'Calibri')
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,6 +102,12 @@ export function docStyleCss(parsed: ParsedDocFull): string {
|
|||||||
// Latin factor for per-paragraph overrides (blockAttrs): pure-Western paragraphs
|
// Latin factor for per-paragraph overrides (blockAttrs): pure-Western paragraphs
|
||||||
// follow the body font's real single-line metric instead of a flat 1.2
|
// follow the body font's real single-line metric instead of a flat 1.2
|
||||||
decls.push(`--doc-line-factor-latin:${lineHeightFactor(docBodyFont(parsed) ?? 'Calibri')}`)
|
decls.push(`--doc-line-factor-latin:${lineHeightFactor(docBodyFont(parsed) ?? 'Calibri')}`)
|
||||||
|
// Korean factor for hangul paragraphs (Batang-class 1.15 unless the EA face says otherwise)
|
||||||
|
const normalEaKr =
|
||||||
|
normal?.font && (normal.font !== normal.fontAscii || isKoreanFontName(normal.font))
|
||||||
|
? normal.font
|
||||||
|
: undefined
|
||||||
|
decls.push(`--doc-line-factor-kr:${krLineFactor(normalEaKr ?? dd?.eastAsiaFont)}`)
|
||||||
// dual-slot baseline: Latin families first, then the East Asian chain
|
// dual-slot baseline: Latin families first, then the East Asian chain
|
||||||
const baseAscii = normal?.fontAscii ?? dd?.asciiFont
|
const baseAscii = normal?.fontAscii ?? dd?.asciiFont
|
||||||
const baseEa = normal?.font ?? dd?.eastAsiaFont
|
const baseEa = normal?.font ?? dd?.eastAsiaFont
|
||||||
@@ -114,14 +129,15 @@ export function docStyleCss(parsed: ParsedDocFull): string {
|
|||||||
cssLineHeight(dd?.lineRule, dd?.lineRawTwips, dd?.lineSpacing)
|
cssLineHeight(dd?.lineRule, dd?.lineRawTwips, dd?.lineSpacing)
|
||||||
decls.push(`line-height:${lh ?? `calc(${factor} * 1)`}`)
|
decls.push(`line-height:${lh ?? `calc(${factor} * 1)`}`)
|
||||||
rules.push(`.doc-page { ${decls.join(';')} }`)
|
rules.push(`.doc-page { ${decls.join(';')} }`)
|
||||||
// docDefaults paragraph spacing is Word's real fallback (the static stylesheet's
|
// Word's fallback when neither Normal nor docDefaults declares w:spacing is 0
|
||||||
// 8pt is a guess); declared per block so --doc-line-factor set inline on a
|
// (the static stylesheet's 8pt guess inflated undeclared docs, table cells worst);
|
||||||
// paragraph re-evaluates the line-height var (it wouldn't through inheritance)
|
// declared per block so --doc-line-factor set inline on a paragraph re-evaluates
|
||||||
|
// the line-height var (it wouldn't through inheritance)
|
||||||
const blockSel =
|
const blockSel =
|
||||||
'.doc-page p, .doc-page .doc-li, .doc-page h1, .doc-page h2, .doc-page h3, .doc-page h4, .doc-page h5, .doc-page h6'
|
'.doc-page p, .doc-page .doc-li, .doc-page h1, .doc-page h2, .doc-page h3, .doc-page h4, .doc-page h5, .doc-page h6'
|
||||||
const blockDecls = [
|
const blockDecls = [
|
||||||
`margin-top:${((normal?.spaceBeforeTwips ?? dd?.spaceBeforeTwips ?? 0) / 20).toFixed(1)}pt`,
|
`margin-top:${((normal?.spaceBeforeTwips ?? dd?.spaceBeforeTwips ?? 0) / 20).toFixed(1)}pt`,
|
||||||
`margin-bottom:${((normal?.spaceAfterTwips ?? dd?.spaceAfterTwips ?? 160) / 20).toFixed(1)}pt`,
|
`margin-bottom:${((normal?.spaceAfterTwips ?? dd?.spaceAfterTwips ?? 0) / 20).toFixed(1)}pt`,
|
||||||
`line-height:${lh ?? `calc(${factor} * 1)`}`,
|
`line-height:${lh ?? `calc(${factor} * 1)`}`,
|
||||||
]
|
]
|
||||||
rules.push(`${blockSel} { ${blockDecls.join(';')} }`)
|
rules.push(`${blockSel} { ${blockDecls.join(';')} }`)
|
||||||
@@ -205,8 +221,8 @@ export function docStyleCss(parsed: ParsedDocFull): string {
|
|||||||
decls.push(`margin-top:${(d.spaceBeforeTwips / 20).toFixed(1)}pt`)
|
decls.push(`margin-top:${(d.spaceBeforeTwips / 20).toFixed(1)}pt`)
|
||||||
if (d.spaceAfterTwips !== undefined)
|
if (d.spaceAfterTwips !== undefined)
|
||||||
decls.push(`margin-bottom:${(d.spaceAfterTwips / 20).toFixed(1)}pt`)
|
decls.push(`margin-bottom:${(d.spaceAfterTwips / 20).toFixed(1)}pt`)
|
||||||
if (d.indentLeftTwips) decls.push(`margin-left:${(d.indentLeftTwips / 20).toFixed(1)}pt`)
|
if (d.indentRightTwips)
|
||||||
if (d.indentRightTwips) decls.push(`margin-right:${(d.indentRightTwips / 20).toFixed(1)}pt`)
|
decls.push(`margin-inline-end:${(d.indentRightTwips / 20).toFixed(1)}pt`)
|
||||||
if (d.indentFirstLineTwips)
|
if (d.indentFirstLineTwips)
|
||||||
decls.push(`text-indent:${(d.indentFirstLineTwips / 20).toFixed(1)}pt`)
|
decls.push(`text-indent:${(d.indentFirstLineTwips / 20).toFixed(1)}pt`)
|
||||||
if (d.align) decls.push(`text-align:${d.align}`)
|
if (d.align) decls.push(`text-align:${d.align}`)
|
||||||
@@ -216,6 +232,15 @@ export function docStyleCss(parsed: ParsedDocFull): string {
|
|||||||
if (decls.length > 0) {
|
if (decls.length > 0) {
|
||||||
rules.push(`.doc-page [data-style="${CSS.escape(info.styleId)}"] { ${decls.join(';')} }`)
|
rules.push(`.doc-page [data-style="${CSS.escape(info.styleId)}"] { ${decls.join(';')} }`)
|
||||||
}
|
}
|
||||||
|
// Word merges indents per property (direct ind > numbering level ind > style ind), never
|
||||||
|
// adds them: list items run on --li-left geometry, so the style indent must not also apply
|
||||||
|
// as a margin — it only feeds the --li-left fallback chain (styles.css)
|
||||||
|
if (d.indentLeftTwips) {
|
||||||
|
const s = `[data-style="${CSS.escape(info.styleId)}"]`
|
||||||
|
const pt = (d.indentLeftTwips / 20).toFixed(1)
|
||||||
|
rules.push(`.doc-page ${s}:not(.doc-li) { margin-inline-start:${pt}pt }`)
|
||||||
|
rules.push(`.doc-page .doc-li${s} { --style-li-left:${pt}pt }`)
|
||||||
|
}
|
||||||
// w:contextualSpacing: consecutive same-style paragraphs swallow the spacing
|
// w:contextualSpacing: consecutive same-style paragraphs swallow the spacing
|
||||||
// between them (ListParagraph/ListBullet carry this — Word lists are tight)
|
// between them (ListParagraph/ListBullet carry this — Word lists are tight)
|
||||||
if (d.contextualSpacing) {
|
if (d.contextualSpacing) {
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
patchTextboxParas,
|
patchTextboxParas,
|
||||||
generateTableModelXml,
|
generateTableModelXml,
|
||||||
type Block,
|
type Block,
|
||||||
|
type CellBorder,
|
||||||
type ChartDisplay,
|
type ChartDisplay,
|
||||||
type ChartPatch,
|
type ChartPatch,
|
||||||
type ChartSeriesPatch,
|
type ChartSeriesPatch,
|
||||||
@@ -31,12 +32,14 @@ import {
|
|||||||
type Run,
|
type Run,
|
||||||
type SaveBlock,
|
type SaveBlock,
|
||||||
type SdtShell,
|
type SdtShell,
|
||||||
|
type SectionInfo,
|
||||||
type TableCell,
|
type TableCell,
|
||||||
type TableModel,
|
type TableModel,
|
||||||
type TextboxDisplay,
|
type TextboxDisplay,
|
||||||
type TextboxParaPatch,
|
type TextboxParaPatch,
|
||||||
} from '@genoffice/docx-engine'
|
} from '@genoffice/docx-engine'
|
||||||
import { t } from '../i18n/locale'
|
import { t } from '../i18n/locale'
|
||||||
|
import { textHasComplexScript } from '../line-metrics'
|
||||||
import { inlineMathML } from './equation'
|
import { inlineMathML } from './equation'
|
||||||
import { isStraightLineKind } from './shape-svg'
|
import { isStraightLineKind } from './shape-svg'
|
||||||
|
|
||||||
@@ -55,11 +58,11 @@ export interface PmNode {
|
|||||||
|
|
||||||
// ---- Block[] -> ProseMirror doc ----
|
// ---- Block[] -> ProseMirror doc ----
|
||||||
|
|
||||||
export function blocksToPmDoc(blocks: Block[]): PmNode {
|
export function blocksToPmDoc(blocks: Block[], sections?: SectionInfo[]): PmNode {
|
||||||
const content: PmNode[] = []
|
const content: PmNode[] = []
|
||||||
for (const block of blocks) {
|
for (const block of blocks) {
|
||||||
if (block.hidden) continue
|
if (block.hidden) continue
|
||||||
content.push(blockToPmNode(block))
|
content.push(blockToPmNode(block, sectionRowCapTwips(sections, block.docxIndex)))
|
||||||
}
|
}
|
||||||
if (content.length === 0) {
|
if (content.length === 0) {
|
||||||
content.push({
|
content.push({
|
||||||
@@ -87,10 +90,46 @@ function formatAttrs(format: ParaFormat | undefined): Record<string, unknown> {
|
|||||||
tabStops: format?.tabStops ? JSON.stringify(format.tabStops) : null,
|
tabStops: format?.tabStops ? JSON.stringify(format.tabStops) : null,
|
||||||
dropCap: format?.dropCap ? JSON.stringify(format.dropCap) : null,
|
dropCap: format?.dropCap ? JSON.stringify(format.dropCap) : null,
|
||||||
bidi: format?.bidi ?? false,
|
bidi: format?.bidi ?? false,
|
||||||
|
autoSpace: format?.autoSpace ?? null,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function blockToPmNode(block: Block): PmNode {
|
/** Effective row-height ceiling: one page of section content (Word truncates taller rows within the page) */
|
||||||
|
function sectionRowCapTwips(
|
||||||
|
sections: SectionInfo[] | undefined,
|
||||||
|
docxIndex: number | null,
|
||||||
|
): number | null {
|
||||||
|
if (!sections?.length || docxIndex == null) return null
|
||||||
|
const sec =
|
||||||
|
sections.find((s) => docxIndex >= s.firstBlockIndex && docxIndex <= s.lastBlockIndex) ??
|
||||||
|
sections[sections.length - 1]
|
||||||
|
const cap = sec.settings.pageHeight - sec.settings.marginTop - sec.settings.marginBottom
|
||||||
|
return cap > 0 ? cap : null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cap declared row heights (incl. nested tables); returns the input model when nothing exceeds the cap */
|
||||||
|
export function capTableRowHeights(model: TableModel, capTwips: number): TableModel {
|
||||||
|
let changed = false
|
||||||
|
const rowHeightsTwips = model.rowHeightsTwips?.map((h) => {
|
||||||
|
if (h != null && h > capTwips) {
|
||||||
|
changed = true
|
||||||
|
return capTwips
|
||||||
|
}
|
||||||
|
return h
|
||||||
|
})
|
||||||
|
const rows = model.rows.map((row) =>
|
||||||
|
row.map((cell) => {
|
||||||
|
if (!cell.nestedTables?.length) return cell
|
||||||
|
const nested = cell.nestedTables.map((nt) => capTableRowHeights(nt, capTwips))
|
||||||
|
if (nested.every((nt, i) => nt === cell.nestedTables![i])) return cell
|
||||||
|
changed = true
|
||||||
|
return { ...cell, nestedTables: nested }
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
return changed ? { ...model, rows, rowHeightsTwips } : model
|
||||||
|
}
|
||||||
|
|
||||||
|
function blockToPmNode(block: Block, rowCapTwips: number | null = null): PmNode {
|
||||||
switch (block.type) {
|
switch (block.type) {
|
||||||
case 'heading':
|
case 'heading':
|
||||||
return {
|
return {
|
||||||
@@ -154,6 +193,7 @@ function blockToPmNode(block: Block): PmNode {
|
|||||||
block.table ?? { rows: [[{ paras: [''] }]] },
|
block.table ?? { rows: [[{ paras: [''] }]] },
|
||||||
block.docxIndex,
|
block.docxIndex,
|
||||||
block.blockRevision ?? null,
|
block.blockRevision ?? null,
|
||||||
|
rowCapTwips,
|
||||||
)
|
)
|
||||||
default:
|
default:
|
||||||
// image / passthrough: protected whole-unit blocks
|
// image / passthrough: protected whole-unit blocks
|
||||||
@@ -175,9 +215,20 @@ function blockToPmNode(block: Block): PmNode {
|
|||||||
imageOffsetYEmu: block.imageOffsetYEmu ?? null,
|
imageOffsetYEmu: block.imageOffsetYEmu ?? null,
|
||||||
imagePosH: block.imagePosH ?? null,
|
imagePosH: block.imagePosH ?? null,
|
||||||
imagePosV: block.imagePosV ?? null,
|
imagePosV: block.imagePosV ?? null,
|
||||||
table: block.table ?? null,
|
imageRotDeg: block.imageRotDeg ?? null,
|
||||||
|
imageFlipH: block.imageFlipH ?? false,
|
||||||
|
imageFlipV: block.imageFlipV ?? false,
|
||||||
|
table:
|
||||||
|
block.table && rowCapTwips != null
|
||||||
|
? capTableRowHeights(block.table, rowCapTwips)
|
||||||
|
: (block.table ?? null),
|
||||||
fieldDisplay: block.fieldDisplay ?? null,
|
fieldDisplay: block.fieldDisplay ?? null,
|
||||||
decorative: block.decorative ?? false,
|
decorative: block.decorative ?? false,
|
||||||
|
ruleColorHex: block.ruleColorHex ?? null,
|
||||||
|
ruleThicknessPx: block.ruleThicknessPx ?? null,
|
||||||
|
ruleWidthPx: block.ruleWidthPx ?? null,
|
||||||
|
brokenImage: block.brokenImage ?? false,
|
||||||
|
invisibleMarker: block.invisibleMarker ?? false,
|
||||||
textboxes: block.textboxes ?? null,
|
textboxes: block.textboxes ?? null,
|
||||||
formulaDisplay: block.formulaDisplay ?? null,
|
formulaDisplay: block.formulaDisplay ?? null,
|
||||||
chartDisplay: block.chartDisplay ?? null,
|
chartDisplay: block.chartDisplay ?? null,
|
||||||
@@ -199,11 +250,41 @@ function cellRowSpan(model: TableModel, row: number, cell: number, positions: nu
|
|||||||
return span
|
return span
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function cellBorderPx(b: CellBorder | undefined): number {
|
||||||
|
if (!b || b.style === 'none' || b.style === 'nil') return 0
|
||||||
|
return Math.max(1, Math.round(((b.szEighths ?? 4) / 8 / 72) * 96))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Inner clip-box height (twips) for cells of hRule="exact" rows — Word clips overflow
|
||||||
|
* instead of growing the row. null = not exact, or the cell spans rows (its clip height
|
||||||
|
* would be the sum of the spanned rows; not handled yet). */
|
||||||
|
export function cellClipTwips(
|
||||||
|
model: TableModel,
|
||||||
|
rowIndex: number,
|
||||||
|
cell: TableCell,
|
||||||
|
rowSpan: number,
|
||||||
|
): number | null {
|
||||||
|
if (rowSpan > 1 || model.rowHeightRules?.[rowIndex] !== 'exact') return null
|
||||||
|
const h = model.rowHeightsTwips?.[rowIndex]
|
||||||
|
if (!h) return null
|
||||||
|
const padTop = cell.cellMarTwips?.top ?? model.cellMarTwips?.top ?? 0
|
||||||
|
const padBottom = cell.cellMarTwips?.bottom ?? model.cellMarTwips?.bottom ?? 0
|
||||||
|
// collapsed borders straddle the row edges: half of each eats into the row height
|
||||||
|
const bTop = cell.borders?.top ?? (rowIndex === 0 ? model.borders?.top : model.borders?.insideH)
|
||||||
|
const bBottom =
|
||||||
|
cell.borders?.bottom ??
|
||||||
|
(rowIndex === model.rows.length - 1 ? model.borders?.bottom : model.borders?.insideH)
|
||||||
|
const borderTwips = Math.round(((cellBorderPx(bTop) + cellBorderPx(bBottom)) / 2) * 15)
|
||||||
|
return Math.max(0, h - padTop - padBottom - borderTwips)
|
||||||
|
}
|
||||||
|
|
||||||
export function tableModelToPmNode(
|
export function tableModelToPmNode(
|
||||||
model: TableModel,
|
model: TableModel,
|
||||||
docxIndex: number | null = null,
|
docxIndex: number | null = null,
|
||||||
blockRevision: Block['blockRevision'] | null = null,
|
blockRevision: Block['blockRevision'] | null = null,
|
||||||
|
rowCapTwips: number | null = null,
|
||||||
): PmNode {
|
): PmNode {
|
||||||
|
if (rowCapTwips != null) model = capTableRowHeights(model, rowCapTwips)
|
||||||
const positions = model.rows.map((row) => {
|
const positions = model.rows.map((row) => {
|
||||||
let column = 0
|
let column = 0
|
||||||
return row.map((cell) => {
|
return row.map((cell) => {
|
||||||
@@ -242,6 +323,7 @@ export function tableModelToPmNode(
|
|||||||
type: 'docTableRow',
|
type: 'docTableRow',
|
||||||
attrs: {
|
attrs: {
|
||||||
heightTwips: model.rowHeightsTwips?.[rowIndex] ?? null,
|
heightTwips: model.rowHeightsTwips?.[rowIndex] ?? null,
|
||||||
|
heightRule: model.rowHeightRules?.[rowIndex] ?? null,
|
||||||
rawTrPr: model.rawTrPrs?.[rowIndex] ?? null,
|
rawTrPr: model.rawTrPrs?.[rowIndex] ?? null,
|
||||||
rowRevision: model.rowRevisions?.[rowIndex] ?? null,
|
rowRevision: model.rowRevisions?.[rowIndex] ?? null,
|
||||||
},
|
},
|
||||||
@@ -249,12 +331,14 @@ export function tableModelToPmNode(
|
|||||||
if (cell.vMerge === 'continue') return []
|
if (cell.vMerge === 'continue') return []
|
||||||
const start = positions[rowIndex][cellIndex]
|
const start = positions[rowIndex][cellIndex]
|
||||||
const colspan = cell.colSpan ?? 1
|
const colspan = cell.colSpan ?? 1
|
||||||
|
const rowspan = cellRowSpan(model, rowIndex, cellIndex, positions)
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
type: hasHeaderRow && rowIndex === 0 ? 'docTableHeader' : 'docTableCell',
|
type: hasHeaderRow && rowIndex === 0 ? 'docTableHeader' : 'docTableCell',
|
||||||
attrs: {
|
attrs: {
|
||||||
colspan,
|
colspan,
|
||||||
rowspan: cellRowSpan(model, rowIndex, cellIndex, positions),
|
rowspan,
|
||||||
|
clipHeightTwips: cellClipTwips(model, rowIndex, cell, rowspan),
|
||||||
colwidth: widthPx ? widthPx.slice(start, start + colspan) : null,
|
colwidth: widthPx ? widthPx.slice(start, start + colspan) : null,
|
||||||
cellMar: cell.cellMarTwips ?? null,
|
cellMar: cell.cellMarTwips ?? null,
|
||||||
textDirection: cell.textDirection ?? null,
|
textDirection: cell.textDirection ?? null,
|
||||||
@@ -267,38 +351,7 @@ export function tableModelToPmNode(
|
|||||||
rawTcPr: cell.rawTcPr ?? null,
|
rawTcPr: cell.rawTcPr ?? null,
|
||||||
cellRevision: cell.cellRevision ?? null,
|
cellRevision: cell.cellRevision ?? null,
|
||||||
},
|
},
|
||||||
content: [
|
content: cellContentNodes(cell),
|
||||||
...(cell.richParas?.length
|
|
||||||
? cell.richParas
|
|
||||||
: (cell.paras.length > 0 ? cell.paras : ['']).map((text) => ({
|
|
||||||
align: cell.align,
|
|
||||||
runs: text === '' ? [] : [{ text, bold: cell.bold, color: cell.color }],
|
|
||||||
}))
|
|
||||||
).map((paragraph) => {
|
|
||||||
const list = 'list' in paragraph ? paragraph.list : undefined
|
|
||||||
return list
|
|
||||||
? {
|
|
||||||
type: 'docListItem',
|
|
||||||
attrs: {
|
|
||||||
...formatAttrs(paragraph),
|
|
||||||
kind: list.kind,
|
|
||||||
numId: list.numId,
|
|
||||||
ilvl: list.ilvl,
|
|
||||||
},
|
|
||||||
content: runsToInline(paragraph.runs),
|
|
||||||
}
|
|
||||||
: {
|
|
||||||
type: 'docParagraph',
|
|
||||||
attrs: formatAttrs(paragraph),
|
|
||||||
content: runsToInline(paragraph.runs),
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
// nested tables: read-only atomic child-table nodes (placed after paragraphs; fidelity on save comes from the outer table's bytes)
|
|
||||||
...(cell.nestedTables ?? []).map((nt) => ({
|
|
||||||
type: 'docNestedTable',
|
|
||||||
attrs: { model: nt },
|
|
||||||
})),
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
}),
|
}),
|
||||||
@@ -309,6 +362,44 @@ export function tableModelToPmNode(
|
|||||||
return table
|
return table
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** cell paragraphs with nested tables (read-only atoms) spliced in at their anchors */
|
||||||
|
function cellContentNodes(cell: TableCell): PmNode[] {
|
||||||
|
const paraNodes: PmNode[] = (
|
||||||
|
cell.richParas?.length
|
||||||
|
? cell.richParas
|
||||||
|
: (cell.paras.length > 0 ? cell.paras : ['']).map((text) => ({
|
||||||
|
align: cell.align,
|
||||||
|
runs: text === '' ? [] : [{ text, bold: cell.bold, color: cell.color }],
|
||||||
|
}))
|
||||||
|
).map((paragraph) => {
|
||||||
|
const list = 'list' in paragraph ? paragraph.list : undefined
|
||||||
|
return list
|
||||||
|
? {
|
||||||
|
type: 'docListItem',
|
||||||
|
attrs: {
|
||||||
|
...formatAttrs(paragraph),
|
||||||
|
kind: list.kind,
|
||||||
|
numId: list.numId,
|
||||||
|
ilvl: list.ilvl,
|
||||||
|
},
|
||||||
|
content: runsToInline(paragraph.runs),
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
type: 'docParagraph',
|
||||||
|
attrs: formatAttrs(paragraph),
|
||||||
|
content: runsToInline(paragraph.runs),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// fidelity on save comes from the outer table's bytes; reverse insertion keeps anchors valid
|
||||||
|
const nested = cell.nestedTables ?? []
|
||||||
|
const content = [...paraNodes]
|
||||||
|
for (let i = nested.length - 1; i >= 0; i--) {
|
||||||
|
const at = Math.min(cell.nestedTableAnchors?.[i] ?? paraNodes.length, paraNodes.length)
|
||||||
|
content.splice(at, 0, { type: 'docNestedTable', attrs: { model: nested[i] } })
|
||||||
|
}
|
||||||
|
return content
|
||||||
|
}
|
||||||
|
|
||||||
export function tableStructureSignature(table: PmNode): string {
|
export function tableStructureSignature(table: PmNode): string {
|
||||||
return JSON.stringify({
|
return JSON.stringify({
|
||||||
widths: table.attrs?.colWidthsPct ?? null,
|
widths: table.attrs?.colWidthsPct ?? null,
|
||||||
@@ -388,10 +479,14 @@ export function pmTableToModel(table: PmNode): TableModel {
|
|||||||
let maximumColumns = 0
|
let maximumColumns = 0
|
||||||
|
|
||||||
const rowHeightsTwips: Array<number | null> = []
|
const rowHeightsTwips: Array<number | null> = []
|
||||||
|
const rowHeightRules: NonNullable<TableModel['rowHeightRules']> = []
|
||||||
const rawTrPrs: Array<string | null> = []
|
const rawTrPrs: Array<string | null> = []
|
||||||
const rowRevisions: TableModel['rowRevisions'] = []
|
const rowRevisions: TableModel['rowRevisions'] = []
|
||||||
for (const rowNode of table.content ?? []) {
|
for (const rowNode of table.content ?? []) {
|
||||||
rowHeightsTwips.push((rowNode.attrs?.heightTwips as number | null) ?? null)
|
rowHeightsTwips.push((rowNode.attrs?.heightTwips as number | null) ?? null)
|
||||||
|
rowHeightRules.push(
|
||||||
|
(rowNode.attrs?.heightRule as NonNullable<TableModel['rowHeightRules']>[number]) ?? null,
|
||||||
|
)
|
||||||
rawTrPrs.push((rowNode.attrs?.rawTrPr as string | null) ?? null)
|
rawTrPrs.push((rowNode.attrs?.rawTrPr as string | null) ?? null)
|
||||||
rowRevisions.push(
|
rowRevisions.push(
|
||||||
(rowNode.attrs?.rowRevision as NonNullable<TableModel['rowRevisions']>[number]) ?? null,
|
(rowNode.attrs?.rowRevision as NonNullable<TableModel['rowRevisions']>[number]) ?? null,
|
||||||
@@ -430,10 +525,16 @@ export function pmTableToModel(table: PmNode): TableModel {
|
|||||||
(n) => n.type === 'docParagraph' || n.type === 'docListItem',
|
(n) => n.type === 'docParagraph' || n.type === 'docListItem',
|
||||||
)
|
)
|
||||||
// nested tables round-trip with the model: text edits use the surgical patch, structural regeneration emits the whole table (nested tables no longer dropped)
|
// nested tables round-trip with the model: text edits use the surgical patch, structural regeneration emits the whole table (nested tables no longer dropped)
|
||||||
const nestedModels = (cellNode.content ?? [])
|
const nestedModels: TableModel[] = []
|
||||||
.filter((n) => n.type === 'docNestedTable')
|
const nestedAnchors: number[] = []
|
||||||
.map((n) => n.attrs?.model as TableModel | null)
|
let paraCount = 0
|
||||||
.filter((m): m is TableModel => !!m)
|
for (const n of cellNode.content ?? []) {
|
||||||
|
if (n.type === 'docParagraph' || n.type === 'docListItem') paraCount++
|
||||||
|
else if (n.type === 'docNestedTable' && n.attrs?.model) {
|
||||||
|
nestedModels.push(n.attrs.model as TableModel)
|
||||||
|
nestedAnchors.push(paraCount)
|
||||||
|
}
|
||||||
|
}
|
||||||
entries.push({
|
entries.push({
|
||||||
column: cursor,
|
column: cursor,
|
||||||
cell: {
|
cell: {
|
||||||
@@ -452,7 +553,9 @@ export function pmTableToModel(table: PmNode): TableModel {
|
|||||||
: {}),
|
: {}),
|
||||||
runs: inlineToRuns(paragraph.content ?? []),
|
runs: inlineToRuns(paragraph.content ?? []),
|
||||||
})),
|
})),
|
||||||
...(nestedModels.length > 0 ? { nestedTables: nestedModels } : {}),
|
...(nestedModels.length > 0
|
||||||
|
? { nestedTables: nestedModels, nestedTableAnchors: nestedAnchors }
|
||||||
|
: {}),
|
||||||
colSpan: colspan > 1 ? colspan : undefined,
|
colSpan: colspan > 1 ? colspan : undefined,
|
||||||
vMerge: rowspan > 1 ? 'restart' : undefined,
|
vMerge: rowspan > 1 ? 'restart' : undefined,
|
||||||
},
|
},
|
||||||
@@ -488,7 +591,7 @@ export function pmTableToModel(table: PmNode): TableModel {
|
|||||||
rows,
|
rows,
|
||||||
...(colWidthsPct ? { colWidthsPct } : {}),
|
...(colWidthsPct ? { colWidthsPct } : {}),
|
||||||
...(colWidthsTwips ? { colWidthsTwips } : {}),
|
...(colWidthsTwips ? { colWidthsTwips } : {}),
|
||||||
...(rowHeightsTwips.some((h) => h !== null) ? { rowHeightsTwips } : {}),
|
...(rowHeightsTwips.some((h) => h !== null) ? { rowHeightsTwips, rowHeightRules } : {}),
|
||||||
...(rawTrPrs.some((r) => r !== null) ? { rawTrPrs } : {}),
|
...(rawTrPrs.some((r) => r !== null) ? { rawTrPrs } : {}),
|
||||||
...(rowRevisions.some((revision) => revision !== null) ? { rowRevisions } : {}),
|
...(rowRevisions.some((revision) => revision !== null) ? { rowRevisions } : {}),
|
||||||
// null (cleared) → '' removes explicitly; undefined leaves it alone
|
// null (cleared) → '' removes explicitly; undefined leaves it alone
|
||||||
@@ -562,6 +665,19 @@ export function runsToInline(runs: Run[]): PmNode[] {
|
|||||||
nodes.push({ type: 'text', text: segment, ...(marks.length > 0 ? { marks } : {}) })
|
nodes.push({ type: 'text', text: segment, ...(marks.length > 0 ? { marks } : {}) })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// A run can carry both w:t text and a w:drawing; generate.ts writes the
|
||||||
|
// text before the drawing, so emit the image after the text segments
|
||||||
|
if (run.image) {
|
||||||
|
nodes.push({
|
||||||
|
type: 'docInlineImage',
|
||||||
|
attrs: {
|
||||||
|
dataUrl: run.image.dataUrl,
|
||||||
|
widthPx: run.image.widthPx ?? null,
|
||||||
|
heightPx: run.image.heightPx ?? null,
|
||||||
|
xml: run.image.xml,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
if (run.xeTerm !== undefined) {
|
if (run.xeTerm !== undefined) {
|
||||||
nodes.push({ type: 'docXeMark', attrs: { term: run.xeTerm } })
|
nodes.push({ type: 'docXeMark', attrs: { term: run.xeTerm } })
|
||||||
}
|
}
|
||||||
@@ -628,6 +744,8 @@ function runMarks(run: Run): PmMark[] {
|
|||||||
sizeHalfPoints: run.sizeHalfPoints ?? null,
|
sizeHalfPoints: run.sizeHalfPoints ?? null,
|
||||||
font: run.font ?? null,
|
font: run.font ?? null,
|
||||||
fontAscii: run.fontAscii ?? null,
|
fontAscii: run.fontAscii ?? null,
|
||||||
|
// cs chain only kicks in for complex-script text (Word's w:cs semantics)
|
||||||
|
csFont: run.csFont && textHasComplexScript(run.text) ? run.csFont : null,
|
||||||
charSpacingTwips: run.charSpacingTwips ?? null,
|
charSpacingTwips: run.charSpacingTwips ?? null,
|
||||||
charScaleEm: run.charScalePct ? charScaleEm(run.text, run.charScalePct) : null,
|
charScaleEm: run.charScalePct ? charScaleEm(run.text, run.charScalePct) : null,
|
||||||
highlight: run.highlight ?? null,
|
highlight: run.highlight ?? null,
|
||||||
@@ -824,10 +942,16 @@ export function pmDocToSavePlan(doc: PmNode, originalBlocks: Block[]): SavePlan
|
|||||||
chartDisplay.heightPx !== original.chartDisplay?.heightPx)
|
chartDisplay.heightPx !== original.chartDisplay?.heightPx)
|
||||||
? { w: chartDisplay.widthPx, h: chartDisplay.heightPx }
|
? { w: chartDisplay.widthPx, h: chartDisplay.heightPx }
|
||||||
: null
|
: null
|
||||||
if (imagePatch && original.originalXml) {
|
const imageReplace =
|
||||||
|
original.type === 'image'
|
||||||
|
? (node.attrs?.imageReplace as { base64: string; mime: string } | null)
|
||||||
|
: null
|
||||||
|
if ((imagePatch || imageReplace) && original.originalXml) {
|
||||||
changedCount++
|
changedCount++
|
||||||
let xml = patchImageParagraphXml(original.originalXml, imagePatch)
|
let xml = imagePatch
|
||||||
if (imagePatch.wrap !== undefined) {
|
? patchImageParagraphXml(original.originalXml, imagePatch)
|
||||||
|
: original.originalXml
|
||||||
|
if (imagePatch?.wrap !== undefined) {
|
||||||
const posOffset =
|
const posOffset =
|
||||||
imagePatch.posOffsetX !== undefined && imagePatch.posOffsetY !== undefined
|
imagePatch.posOffsetX !== undefined && imagePatch.posOffsetY !== undefined
|
||||||
? { x: imagePatch.posOffsetX, y: imagePatch.posOffsetY }
|
? { x: imagePatch.posOffsetX, y: imagePatch.posOffsetY }
|
||||||
@@ -837,10 +961,24 @@ export function pmDocToSavePlan(doc: PmNode, originalBlocks: Block[]): SavePlan
|
|||||||
? { h: imagePatch.posH, v: imagePatch.posV }
|
? { h: imagePatch.posH, v: imagePatch.posV }
|
||||||
: undefined
|
: undefined
|
||||||
xml = applyImageWrap(xml, imagePatch.wrap, posOffset, marginAlign)
|
xml = applyImageWrap(xml, imagePatch.wrap, posOffset, marginAlign)
|
||||||
} else if (imagePatch.posOffsetX !== undefined || imagePatch.posOffsetY !== undefined) {
|
} else if (
|
||||||
|
imagePatch &&
|
||||||
|
(imagePatch.posOffsetX !== undefined || imagePatch.posOffsetY !== undefined)
|
||||||
|
) {
|
||||||
// posOffset changed without wrap change: patchImageParagraphXml already rewrote it
|
// posOffset changed without wrap change: patchImageParagraphXml already rewrote it
|
||||||
}
|
}
|
||||||
pushBlock({ kind: 'xml', xml })
|
pushBlock({
|
||||||
|
kind: 'xml',
|
||||||
|
xml,
|
||||||
|
...(imageReplace
|
||||||
|
? {
|
||||||
|
replaceImage: {
|
||||||
|
base64: imageReplace.base64,
|
||||||
|
mime: imageReplace.mime as NewImage['mime'],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
})
|
||||||
} else if (tableTexts && original.originalXml) {
|
} else if (tableTexts && original.originalXml) {
|
||||||
changedCount++
|
changedCount++
|
||||||
pushBlock({ kind: 'xml', xml: patchTableCellTexts(original.originalXml, tableTexts) })
|
pushBlock({ kind: 'xml', xml: patchTableCellTexts(original.originalXml, tableTexts) })
|
||||||
@@ -958,6 +1096,9 @@ export function pmDocToSavePlan(doc: PmNode, originalBlocks: Block[]): SavePlan
|
|||||||
if (align) image.align = align
|
if (align) image.align = align
|
||||||
const wrap = node.attrs.imageWrap as ImageWrap | null
|
const wrap = node.attrs.imageWrap as ImageWrap | null
|
||||||
if (wrap) image.wrap = wrap
|
if (wrap) image.wrap = wrap
|
||||||
|
if (node.attrs.imageRotDeg) image.rotDeg = Number(node.attrs.imageRotDeg)
|
||||||
|
if (node.attrs.imageFlipH) image.flipH = true
|
||||||
|
if (node.attrs.imageFlipV) image.flipV = true
|
||||||
pushBlock({ kind: 'image', image })
|
pushBlock({ kind: 'image', image })
|
||||||
} else if (node.attrs?.genChart) {
|
} else if (node.attrs?.genChart) {
|
||||||
// in-place edits live in chartDisplay; the saved part reflects them
|
// in-place edits live in chartDisplay; the saved part reflects them
|
||||||
@@ -1075,6 +1216,9 @@ function imageFromProtectedAttrs(node: PmNode): NewImage | null {
|
|||||||
if (align) image.align = align
|
if (align) image.align = align
|
||||||
const wrap = node.attrs?.imageWrap as ImageWrap | null
|
const wrap = node.attrs?.imageWrap as ImageWrap | null
|
||||||
if (wrap) image.wrap = wrap
|
if (wrap) image.wrap = wrap
|
||||||
|
if (node.attrs?.imageRotDeg) image.rotDeg = Number(node.attrs.imageRotDeg)
|
||||||
|
if (node.attrs?.imageFlipH) image.flipH = true
|
||||||
|
if (node.attrs?.imageFlipV) image.flipV = true
|
||||||
return image
|
return image
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1146,6 +1290,10 @@ interface ImageBlockPatch {
|
|||||||
/** margin-relative align pair (Word position-gallery presets); undefined = keep */
|
/** margin-relative align pair (Word position-gallery presets); undefined = keep */
|
||||||
posH?: 'left' | 'center' | 'right'
|
posH?: 'left' | 'center' | 'right'
|
||||||
posV?: 'top' | 'center' | 'bottom'
|
posV?: 'top' | 'center' | 'bottom'
|
||||||
|
/** rotation (deg clockwise, 0 removes) / mirror flips; undefined = keep */
|
||||||
|
rotDeg?: number
|
||||||
|
flipH?: boolean
|
||||||
|
flipV?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
/** size/align/wrap changes on an original image block; null when untouched */
|
/** size/align/wrap changes on an original image block; null when untouched */
|
||||||
@@ -1177,6 +1325,12 @@ function imagePatchOf(node: PmNode, original: Block): ImageBlockPatch | null {
|
|||||||
if (posOffsetY !== undefined && posOffsetY !== (original.imageOffsetYEmu ?? undefined)) {
|
if (posOffsetY !== undefined && posOffsetY !== (original.imageOffsetYEmu ?? undefined)) {
|
||||||
patch.posOffsetY = posOffsetY
|
patch.posOffsetY = posOffsetY
|
||||||
}
|
}
|
||||||
|
const rotDeg = node.attrs?.imageRotDeg != null ? Number(node.attrs.imageRotDeg) : 0
|
||||||
|
if (rotDeg !== (original.imageRotDeg ?? 0)) patch.rotDeg = rotDeg
|
||||||
|
const flipH = !!node.attrs?.imageFlipH
|
||||||
|
const flipV = !!node.attrs?.imageFlipV
|
||||||
|
if (flipH !== (original.imageFlipH ?? false)) patch.flipH = flipH
|
||||||
|
if (flipV !== (original.imageFlipV ?? false)) patch.flipV = flipV
|
||||||
const posH = (node.attrs?.imagePosH as ImageBlockPatch['posH'] | null) ?? null
|
const posH = (node.attrs?.imagePosH as ImageBlockPatch['posH'] | null) ?? null
|
||||||
const posV = (node.attrs?.imagePosV as ImageBlockPatch['posV'] | null) ?? null
|
const posV = (node.attrs?.imagePosV as ImageBlockPatch['posV'] | null) ?? null
|
||||||
if (
|
if (
|
||||||
@@ -1388,6 +1542,7 @@ function nodeFormat(node: PmNode): ParaFormat | undefined {
|
|||||||
if (node.attrs?.spaceAfter != null) format.spaceAfter = Number(node.attrs.spaceAfter)
|
if (node.attrs?.spaceAfter != null) format.spaceAfter = Number(node.attrs.spaceAfter)
|
||||||
if (node.attrs?.pageBreakBefore) format.pageBreakBefore = true
|
if (node.attrs?.pageBreakBefore) format.pageBreakBefore = true
|
||||||
if (node.attrs?.bidi) format.bidi = true
|
if (node.attrs?.bidi) format.bidi = true
|
||||||
|
if (node.attrs?.autoSpace != null) format.autoSpace = node.attrs.autoSpace as boolean
|
||||||
if (node.attrs?.shadingFill) format.shadingFill = String(node.attrs.shadingFill)
|
if (node.attrs?.shadingFill) format.shadingFill = String(node.attrs.shadingFill)
|
||||||
if (node.attrs?.borders) format.borders = String(node.attrs.borders)
|
if (node.attrs?.borders) format.borders = String(node.attrs.borders)
|
||||||
if (node.attrs?.tabStops) {
|
if (node.attrs?.tabStops) {
|
||||||
@@ -1512,7 +1667,7 @@ export function inlineToRuns(content: PmNode[]): Run[] {
|
|||||||
const ch = node.attrs?.pageBreak ? '\f' : '\n'
|
const ch = node.attrs?.pageBreak ? '\f' : '\n'
|
||||||
const prev = runs[runs.length - 1]
|
const prev = runs[runs.length - 1]
|
||||||
const prevAtomic =
|
const prevAtomic =
|
||||||
prev && (prev.noteRef || prev.xeTerm !== undefined || prev.math || prev.ruby)
|
prev && (prev.noteRef || prev.xeTerm !== undefined || prev.math || prev.ruby || prev.image)
|
||||||
if (prev && !prevAtomic) prev.text += ch
|
if (prev && !prevAtomic) prev.text += ch
|
||||||
else runs.push({ text: ch })
|
else runs.push({ text: ch })
|
||||||
continue
|
continue
|
||||||
@@ -1546,6 +1701,22 @@ export function inlineToRuns(content: PmNode[]): Run[] {
|
|||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if (node.type === 'docInlineImage') {
|
||||||
|
const dataUrl = String(node.attrs?.dataUrl ?? '')
|
||||||
|
const xml = String(node.attrs?.xml ?? '')
|
||||||
|
if (dataUrl && xml) {
|
||||||
|
runs.push({
|
||||||
|
text: '',
|
||||||
|
image: {
|
||||||
|
dataUrl,
|
||||||
|
xml,
|
||||||
|
...(node.attrs?.widthPx ? { widthPx: Number(node.attrs.widthPx) } : {}),
|
||||||
|
...(node.attrs?.heightPx ? { heightPx: Number(node.attrs.heightPx) } : {}),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
if (node.type !== 'text' || !node.text) continue
|
if (node.type !== 'text' || !node.text) continue
|
||||||
const run: Run = { text: node.text }
|
const run: Run = { text: node.text }
|
||||||
for (const mark of node.marks ?? []) {
|
for (const mark of node.marks ?? []) {
|
||||||
@@ -1579,6 +1750,7 @@ export function inlineToRuns(content: PmNode[]): Run[] {
|
|||||||
if (mark.attrs?.sizeHalfPoints) run.sizeHalfPoints = Number(mark.attrs.sizeHalfPoints)
|
if (mark.attrs?.sizeHalfPoints) run.sizeHalfPoints = Number(mark.attrs.sizeHalfPoints)
|
||||||
if (mark.attrs?.font) run.font = String(mark.attrs.font)
|
if (mark.attrs?.font) run.font = String(mark.attrs.font)
|
||||||
if (mark.attrs?.fontAscii) run.fontAscii = String(mark.attrs.fontAscii)
|
if (mark.attrs?.fontAscii) run.fontAscii = String(mark.attrs.fontAscii)
|
||||||
|
if (mark.attrs?.csFont) run.csFont = String(mark.attrs.csFont)
|
||||||
if (mark.attrs?.charSpacingTwips) run.charSpacingTwips = Number(mark.attrs.charSpacingTwips)
|
if (mark.attrs?.charSpacingTwips) run.charSpacingTwips = Number(mark.attrs.charSpacingTwips)
|
||||||
if (mark.attrs?.highlight) run.highlight = String(mark.attrs.highlight)
|
if (mark.attrs?.highlight) run.highlight = String(mark.attrs.highlight)
|
||||||
if (mark.attrs?.vertAlign === 'superscript' || mark.attrs?.vertAlign === 'subscript') {
|
if (mark.attrs?.vertAlign === 'superscript' || mark.attrs?.vertAlign === 'subscript') {
|
||||||
@@ -1613,10 +1785,12 @@ function mergeRuns(runs: Run[]): Run[] {
|
|||||||
run.xeTerm !== undefined ||
|
run.xeTerm !== undefined ||
|
||||||
run.math ||
|
run.math ||
|
||||||
run.ruby ||
|
run.ruby ||
|
||||||
|
run.image ||
|
||||||
prev?.noteRef ||
|
prev?.noteRef ||
|
||||||
prev?.xeTerm !== undefined ||
|
prev?.xeTerm !== undefined ||
|
||||||
prev?.math ||
|
prev?.math ||
|
||||||
prev?.ruby
|
prev?.ruby ||
|
||||||
|
prev?.image
|
||||||
if (prev && !atomic && runStyleKey(prev) === runStyleKey(run)) prev.text += run.text
|
if (prev && !atomic && runStyleKey(prev) === runStyleKey(run)) prev.text += run.text
|
||||||
else merged.push({ ...run })
|
else merged.push({ ...run })
|
||||||
}
|
}
|
||||||
@@ -1709,6 +1883,7 @@ function normalizedFormat(format: ParaFormat | undefined): unknown {
|
|||||||
format.borders ?? null,
|
format.borders ?? null,
|
||||||
format.tabStops ? JSON.stringify(format.tabStops) : null,
|
format.tabStops ? JSON.stringify(format.tabStops) : null,
|
||||||
format.dropCap ? JSON.stringify(format.dropCap) : null,
|
format.dropCap ? JSON.stringify(format.dropCap) : null,
|
||||||
|
format.autoSpace ?? null,
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -171,31 +171,93 @@ interface MeasuredTab {
|
|||||||
/** nodes are immutable, so the has-tab verdict per textblock never goes stale */
|
/** nodes are immutable, so the has-tab verdict per textblock never goes stale */
|
||||||
const paraHasTabCache = new WeakMap<ProseMirrorNode, boolean>()
|
const paraHasTabCache = new WeakMap<ProseMirrorNode, boolean>()
|
||||||
|
|
||||||
|
const MEASURE_RETRY_MAX = 10
|
||||||
|
/**
|
||||||
|
* Distinct decoration signatures tolerated between external invalidations
|
||||||
|
* (edit / resize / font load). A convergent measure→decorate→re-measure
|
||||||
|
* settles within a couple of dispatches; seeing a signature twice (or an
|
||||||
|
* ever-drifting stream of new ones) means decorating keeps changing the very
|
||||||
|
* layout being measured. Each dispatch re-enters update() synchronously, so
|
||||||
|
* an unguarded oscillation recurses until the stack overflows (observed on
|
||||||
|
* tab-heavy government forms: the renderer hangs at 100% CPU).
|
||||||
|
*/
|
||||||
|
const MEASURE_SIGS_MAX = 8
|
||||||
|
|
||||||
class TabLayoutView {
|
class TabLayoutView {
|
||||||
private lastSig = ''
|
private lastSig = ''
|
||||||
|
private seenSigs = new Set<string>()
|
||||||
|
private frozen = false
|
||||||
|
private retryRaf = 0
|
||||||
|
private retries = 0
|
||||||
|
private resizeObserver?: ResizeObserver
|
||||||
|
private lastDomWidth = -1
|
||||||
|
// font swaps change text metrics, which shifts every tab's start x
|
||||||
|
private onFontsLoaded = () => {
|
||||||
|
this.invalidate()
|
||||||
|
this.measure()
|
||||||
|
}
|
||||||
|
|
||||||
constructor(private view: EditorView) {
|
constructor(private view: EditorView) {
|
||||||
this.measure()
|
this.measure()
|
||||||
// font swaps change text metrics, which shifts every tab's start x
|
document.fonts?.addEventListener('loadingdone', this.onFontsLoaded)
|
||||||
document.fonts?.ready.then(() => this.measure()).catch(() => {})
|
if (typeof ResizeObserver !== 'undefined') {
|
||||||
|
// width-only trigger: height changes on every keystroke
|
||||||
|
this.resizeObserver = new ResizeObserver(() => {
|
||||||
|
const w = this.view.dom.offsetWidth
|
||||||
|
if (w === this.lastDomWidth) return
|
||||||
|
this.lastDomWidth = w
|
||||||
|
this.invalidate()
|
||||||
|
this.measure()
|
||||||
|
})
|
||||||
|
this.resizeObserver.observe(view.dom)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** external layout input changed: start a fresh convergence run */
|
||||||
|
private invalidate() {
|
||||||
|
this.seenSigs.clear()
|
||||||
|
this.frozen = false
|
||||||
}
|
}
|
||||||
|
|
||||||
update(view: EditorView, prevState: EditorState) {
|
update(view: EditorView, prevState: EditorState) {
|
||||||
// selection-only transactions change neither the doc nor tab layout; the
|
if (view.state.doc !== prevState.doc) {
|
||||||
// plugin-state check keeps the measure→decorate→re-measure convergence alive
|
this.invalidate()
|
||||||
if (
|
} else if (
|
||||||
view.state.doc === prevState.doc &&
|
// selection-only transactions change neither the doc nor tab layout; the
|
||||||
|
// plugin-state check keeps the measure→decorate→re-measure convergence alive
|
||||||
tabStopPluginKey.getState(view.state) === tabStopPluginKey.getState(prevState)
|
tabStopPluginKey.getState(view.state) === tabStopPluginKey.getState(prevState)
|
||||||
)
|
) {
|
||||||
return
|
return
|
||||||
|
}
|
||||||
this.measure()
|
this.measure()
|
||||||
}
|
}
|
||||||
|
|
||||||
destroy() {}
|
destroy() {
|
||||||
|
document.fonts?.removeEventListener('loadingdone', this.onFontsLoaded)
|
||||||
|
this.resizeObserver?.disconnect()
|
||||||
|
if (this.retryRaf) cancelAnimationFrame(this.retryRaf)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** initial-load dispatches measure before the DOM is measurable; retry on rAF (bounded) */
|
||||||
|
private scheduleRetry() {
|
||||||
|
if (this.retryRaf || this.retries >= MEASURE_RETRY_MAX) return
|
||||||
|
this.retries++
|
||||||
|
this.retryRaf = requestAnimationFrame(() => {
|
||||||
|
this.retryRaf = 0
|
||||||
|
this.measure()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
private measure() {
|
private measure() {
|
||||||
|
if (this.retryRaf) {
|
||||||
|
cancelAnimationFrame(this.retryRaf)
|
||||||
|
this.retryRaf = 0
|
||||||
|
}
|
||||||
const { view } = this
|
const { view } = this
|
||||||
if (!view.dom.isConnected) return
|
if (!view.dom.isConnected) {
|
||||||
|
this.scheduleRetry()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const paras: Array<{ node: ProseMirrorNode; pos: number }> = []
|
const paras: Array<{ node: ProseMirrorNode; pos: number }> = []
|
||||||
view.state.doc.descendants((node, pos) => {
|
view.state.doc.descendants((node, pos) => {
|
||||||
@@ -211,15 +273,32 @@ class TabLayoutView {
|
|||||||
|
|
||||||
const paraRanges: Array<{ from: number; to: number }> = []
|
const paraRanges: Array<{ from: number; to: number }> = []
|
||||||
const tabs: MeasuredTab[] = []
|
const tabs: MeasuredTab[] = []
|
||||||
|
let measurable = false
|
||||||
for (const para of paras) {
|
for (const para of paras) {
|
||||||
const measured = this.measureParagraph(para.node, para.pos)
|
const measured = this.measureParagraph(para.node, para.pos)
|
||||||
if (!measured) continue
|
if (!measured) continue
|
||||||
|
measurable = true
|
||||||
paraRanges.push({ from: para.pos, to: para.pos + para.node.nodeSize })
|
paraRanges.push({ from: para.pos, to: para.pos + para.node.nodeSize })
|
||||||
tabs.push(...measured)
|
tabs.push(...measured)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (paras.length > 0 && !measurable) {
|
||||||
|
this.scheduleRetry()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.retries = 0
|
||||||
|
|
||||||
const sig = JSON.stringify([paraRanges, tabs])
|
const sig = JSON.stringify([paraRanges, tabs])
|
||||||
if (sig === this.lastSig) return
|
if (sig === this.lastSig) return
|
||||||
|
if (this.frozen) return
|
||||||
|
if (this.seenSigs.has(sig) || this.seenSigs.size >= MEASURE_SIGS_MAX) {
|
||||||
|
// oscillation: keep the current decorations until an edit/resize/font
|
||||||
|
// load invalidates, instead of dispatching (and recursing) forever
|
||||||
|
this.frozen = true
|
||||||
|
console.warn('[docs] tab-stop layout did not converge; keeping current tab decorations')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.seenSigs.add(sig)
|
||||||
this.lastSig = sig
|
this.lastSig = sig
|
||||||
|
|
||||||
const old = tabStopPluginKey.getState(view.state)
|
const old = tabStopPluginKey.getState(view.state)
|
||||||
@@ -258,7 +337,10 @@ class TabLayoutView {
|
|||||||
// whether it is margin-left on docParagraph or padding-left on list items)
|
// whether it is margin-left on docParagraph or padding-left on list items)
|
||||||
const marginLeft = parseFloat(cs.marginLeft) || 0
|
const marginLeft = parseFloat(cs.marginLeft) || 0
|
||||||
const paddingLeft = parseFloat(cs.paddingLeft) || 0
|
const paddingLeft = parseFloat(cs.paddingLeft) || 0
|
||||||
|
const paddingRight = parseFloat(cs.paddingRight) || 0
|
||||||
const originX = rect.left - marginLeft * zoom
|
const originX = rect.left - marginLeft * zoom
|
||||||
|
// paragraph right content edge in tab-origin space
|
||||||
|
const paraW = marginLeft + el.clientWidth - paddingRight
|
||||||
// CSS tab-size origin: the paragraph content edge, offset from the column
|
// CSS tab-size origin: the paragraph content edge, offset from the column
|
||||||
// edge by the full indent
|
// edge by the full indent
|
||||||
const contentEdge = marginLeft + paddingLeft
|
const contentEdge = marginLeft + paddingLeft
|
||||||
@@ -317,22 +399,36 @@ class TabLayoutView {
|
|||||||
target = (Math.floor((x + 0.5) / grid) + 1) * grid
|
target = (Math.floor((x + 0.5) / grid) + 1) * grid
|
||||||
}
|
}
|
||||||
|
|
||||||
if (val === 'right' || val === 'decimal' || val === 'center') {
|
// Width of the text between this tab and the next tab (or paragraph
|
||||||
// text between this tab and the next tab (or paragraph end) is aligned
|
// end), measured from the tab's END so it excludes the tab's current
|
||||||
// at the stop; decimal is approximated as right (no '.'-splitting)
|
// advance — otherwise the computed target depends on the layout being
|
||||||
const segStart = tabPos + 1
|
// measured and re-measure never reaches a fixed point.
|
||||||
const segEnd = i + 1 < tabPositions.length ? tabPositions[i + 1] : paraEnd
|
const segStart = tabPos + 1
|
||||||
let segWidth = 0
|
const segEnd = i + 1 < tabPositions.length ? tabPositions[i + 1] : paraEnd
|
||||||
if (segEnd > segStart) {
|
let segWidth = 0
|
||||||
try {
|
if (segEnd > segStart) {
|
||||||
const endCoords = view.coordsAtPos(segEnd, -1)
|
try {
|
||||||
segWidth = Math.max(0, (endCoords.left - coords.left) / zoom)
|
const startCoords = view.coordsAtPos(segStart, 1)
|
||||||
} catch {
|
const endCoords = view.coordsAtPos(segEnd, -1)
|
||||||
/* keep 0 */
|
segWidth = Math.max(0, (endCoords.left - startCoords.left) / zoom)
|
||||||
}
|
} catch {
|
||||||
|
/* keep 0 */
|
||||||
}
|
}
|
||||||
target -= val === 'center' ? segWidth / 2 : segWidth
|
|
||||||
}
|
}
|
||||||
|
// right/decimal/center align the segment at the stop; decimal is
|
||||||
|
// approximated as right (no '.'-splitting)
|
||||||
|
if (val === 'right' || val === 'decimal') target -= segWidth
|
||||||
|
else if (val === 'center') target -= segWidth / 2
|
||||||
|
// A right/center/decimal stop that would push the segment past the
|
||||||
|
// paragraph width pins it flush to the right edge (Word never wraps such
|
||||||
|
// TOC-style lines; Chromium would). In-column left stops are excluded —
|
||||||
|
// they advance to the stop and let the following text wrap naturally —
|
||||||
|
// but a left stop past the right edge pins too: Word keeps its segment
|
||||||
|
// on the same line (TOC page numbers), while an unpinned oversize
|
||||||
|
// tab-size wraps the whole paragraph word by word. The 1px slack keeps
|
||||||
|
// the 0.5px cssSize round-up from re-triggering wrap.
|
||||||
|
if (target + segWidth > paraW - 1 && (val !== 'left' || target > paraW - 1))
|
||||||
|
target = Math.max(x + 0.5, paraW - segWidth - 1)
|
||||||
// convert the Word-space target to a CSS tab-size: the next multiple of
|
// convert the Word-space target to a CSS tab-size: the next multiple of
|
||||||
// it past the tab's position must be the target itself, so it needs to
|
// it past the tab's position must be the target itself, so it needs to
|
||||||
// stay greater than the tab's content-edge-relative x
|
// stay greater than the tab's content-edge-relative x
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { Editor, Extension, Node } from '@tiptap/core'
|
|||||||
import type { ChainedCommands, RawCommands } from '@tiptap/core'
|
import type { ChainedCommands, RawCommands } from '@tiptap/core'
|
||||||
import { UndoRedo } from '@tiptap/extensions'
|
import { UndoRedo } from '@tiptap/extensions'
|
||||||
import { DOMSerializer } from '@tiptap/pm/model'
|
import { DOMSerializer } from '@tiptap/pm/model'
|
||||||
import type { Node as PmNode } from '@tiptap/pm/model'
|
import type { DOMOutputSpec, Node as PmNode } from '@tiptap/pm/model'
|
||||||
import {
|
import {
|
||||||
NodeSelection,
|
NodeSelection,
|
||||||
Plugin,
|
Plugin,
|
||||||
@@ -22,7 +22,12 @@ import {
|
|||||||
isInTable,
|
isInTable,
|
||||||
tableEditing,
|
tableEditing,
|
||||||
} from '@tiptap/pm/tables'
|
} from '@tiptap/pm/tables'
|
||||||
import { cssLineHeight, textHasCjk } from '../line-metrics'
|
import {
|
||||||
|
autospaceBoundaries,
|
||||||
|
autospacePadBetween,
|
||||||
|
cssLineHeight,
|
||||||
|
paraLineFactorCss,
|
||||||
|
} from '../line-metrics'
|
||||||
import { noteMarkText } from '../note-format'
|
import { noteMarkText } from '../note-format'
|
||||||
import { t } from '../i18n/locale'
|
import { t } from '../i18n/locale'
|
||||||
import {
|
import {
|
||||||
@@ -37,7 +42,8 @@ import {
|
|||||||
type TableModel,
|
type TableModel,
|
||||||
type TextboxDisplay,
|
type TextboxDisplay,
|
||||||
} from '@genoffice/docx-engine'
|
} from '@genoffice/docx-engine'
|
||||||
import { computeListMarkers, type ListItemRef } from './numbering'
|
import { bulletMarkerScale, computeListMarkerInfos, type ListItemRef } from './numbering'
|
||||||
|
import { symbolFontCovers } from '../font-check'
|
||||||
import { dropActiveSubEditor, notifySubEditorState, setActiveSubEditor } from './active-editor'
|
import { dropActiveSubEditor, notifySubEditorState, setActiveSubEditor } from './active-editor'
|
||||||
import { PaginationGapsExtension } from './pagination-gaps'
|
import { PaginationGapsExtension } from './pagination-gaps'
|
||||||
import { TrackChangesExtension } from './revisions'
|
import { TrackChangesExtension } from './revisions'
|
||||||
@@ -116,6 +122,8 @@ const anchorAttrs = {
|
|||||||
pageBreakBefore: { default: false },
|
pageBreakBefore: { default: false },
|
||||||
/** RTL paragraph (w:bidi); align is already the visual value */
|
/** RTL paragraph (w:bidi); align is already the visual value */
|
||||||
bidi: { default: false },
|
bidi: { default: false },
|
||||||
|
/** CJK-Latin/digit auto spacing (w:autoSpaceDE/DN); null = Word default on */
|
||||||
|
autoSpace: { default: null as boolean | null },
|
||||||
shadingFill: { default: null as string | null },
|
shadingFill: { default: null as string | null },
|
||||||
/** subset of "tblr": which sides have a single-line border */
|
/** subset of "tblr": which sides have a single-line border */
|
||||||
borders: { default: null as string | null },
|
borders: { default: null as string | null },
|
||||||
@@ -133,8 +141,30 @@ const anchorAttrs = {
|
|||||||
blockRevision: { default: null as Record<string, string> | null },
|
blockRevision: { default: null as Record<string, string> | null },
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Max explicit run size (half-points) when *every* text child declares one, else null.
|
||||||
|
* Any run inheriting the body size keeps the inherited strut (conservative: never shrinks a line Word would keep tall). */
|
||||||
|
function explicitStrutHalfPoints(node: { descendants?: PmNode['descendants'] }): number | null {
|
||||||
|
if (!node.descendants) return null
|
||||||
|
let max: number | null = null
|
||||||
|
let inherited = false
|
||||||
|
node.descendants((child) => {
|
||||||
|
if (inherited) return false
|
||||||
|
if (!child.isText) return true
|
||||||
|
const sz = child.marks.find((m) => m.type.name === 'docTextStyle')?.attrs.sizeHalfPoints as
|
||||||
|
number | null | undefined
|
||||||
|
if (sz == null) inherited = true
|
||||||
|
else max = Math.max(max ?? 0, sz)
|
||||||
|
return false
|
||||||
|
})
|
||||||
|
return inherited ? null : max
|
||||||
|
}
|
||||||
|
|
||||||
function blockAttrs(
|
function blockAttrs(
|
||||||
node: { attrs: Record<string, unknown>; textContent?: string },
|
node: {
|
||||||
|
attrs: Record<string, unknown>
|
||||||
|
textContent?: string
|
||||||
|
descendants?: PmNode['descendants']
|
||||||
|
},
|
||||||
{
|
{
|
||||||
includeIndent = true,
|
includeIndent = true,
|
||||||
listGeometry = false,
|
listGeometry = false,
|
||||||
@@ -157,6 +187,8 @@ function blockAttrs(
|
|||||||
if (classes.length > 0) attrs['class'] = classes.join(' ')
|
if (classes.length > 0) attrs['class'] = classes.join(' ')
|
||||||
const styles: string[] = []
|
const styles: string[] = []
|
||||||
if (node.attrs.bidi) styles.push('direction:rtl', 'unicode-bidi:isolate')
|
if (node.attrs.bidi) styles.push('direction:rtl', 'unicode-bidi:isolate')
|
||||||
|
// explicit autoSpaceDE/DN off also disables the browser's native 1/8em gap
|
||||||
|
if (node.attrs.autoSpace === false) styles.push('text-autospace:no-autospace')
|
||||||
if (node.attrs.align) {
|
if (node.attrs.align) {
|
||||||
styles.push(`text-align:${node.attrs.align === 'distribute' ? 'justify' : node.attrs.align}`)
|
styles.push(`text-align:${node.attrs.align === 'distribute' ? 'justify' : node.attrs.align}`)
|
||||||
}
|
}
|
||||||
@@ -164,11 +196,13 @@ function blockAttrs(
|
|||||||
// line height): CJK paragraphs get the CJK factor, pure-Western ones the document's
|
// line height): CJK paragraphs get the CJK factor, pure-Western ones the document's
|
||||||
// font-aware Latin factor (doc-style-css sets --doc-line-factor-latin per body font)
|
// font-aware Latin factor (doc-style-css sets --doc-line-factor-latin per body font)
|
||||||
if (node.textContent) {
|
if (node.textContent) {
|
||||||
styles.push(
|
styles.push(`--doc-line-factor:${paraLineFactorCss(node.textContent)}`)
|
||||||
`--doc-line-factor:${
|
// Word's line strut follows run sizes; without this the paragraph inherits the
|
||||||
textHasCjk(node.textContent) ? 1.3 : 'var(--doc-line-factor-latin,1.2)'
|
// body size (often larger than table-cell runs) and every line box inflates.
|
||||||
}`,
|
// Shrink-only: a large run already lifts its own line, and Word sizes each
|
||||||
)
|
// line by the runs on it, so the strut must never exceed the inherited size
|
||||||
|
const strut = explicitStrutHalfPoints(node)
|
||||||
|
if (strut) styles.push(`--doc-strut:${strut / 2}pt`, 'font-size:min(var(--doc-strut), 1em)')
|
||||||
}
|
}
|
||||||
const lh = cssLineHeight(
|
const lh = cssLineHeight(
|
||||||
(node.attrs.lineRule as 'auto' | 'atLeast' | 'exact' | null) ?? undefined,
|
(node.attrs.lineRule as 'auto' | 'atLeast' | 'exact' | null) ?? undefined,
|
||||||
@@ -328,6 +362,40 @@ export const DocRuby = Node.create({
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inline picture in a table cell (document content: sizes stay in px, no theme
|
||||||
|
* tokens). `xml` is the exact <w:drawing> fragment that saves verbatim.
|
||||||
|
*/
|
||||||
|
export const DocInlineImage = Node.create({
|
||||||
|
name: 'docInlineImage',
|
||||||
|
inline: true,
|
||||||
|
group: 'inline',
|
||||||
|
atom: true,
|
||||||
|
selectable: true,
|
||||||
|
addAttributes() {
|
||||||
|
return {
|
||||||
|
dataUrl: { default: '' },
|
||||||
|
widthPx: { default: null as number | null },
|
||||||
|
heightPx: { default: null as number | null },
|
||||||
|
xml: { default: '' },
|
||||||
|
}
|
||||||
|
},
|
||||||
|
parseHTML() {
|
||||||
|
return [{ tag: 'img[data-inline-image]' }]
|
||||||
|
},
|
||||||
|
renderHTML({ node }) {
|
||||||
|
const attrs: Record<string, string> = {
|
||||||
|
'data-inline-image': '1',
|
||||||
|
class: 'doc-inline-img',
|
||||||
|
src: String(node.attrs.dataUrl),
|
||||||
|
}
|
||||||
|
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'}`
|
||||||
|
return ['img', attrs]
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Atomic inline formula flowing with the text. `omml` is the exact <m:oMath>
|
* Atomic inline formula flowing with the text. `omml` is the exact <m:oMath>
|
||||||
* fragment that saves verbatim; `mathml` renders natively in Chromium;
|
* fragment that saves verbatim; `mathml` renders natively in Chromium;
|
||||||
@@ -583,31 +651,70 @@ declare module '@tiptap/core' {
|
|||||||
* attribute via node decoration, and display with CSS.
|
* attribute via node decoration, and display with CSS.
|
||||||
* defs are written into storage by App when a document is opened/re-parsed; items without a definition fall back to CSS counters.
|
* defs are written into storage by App when a document is opened/re-parsed; items without a definition fall back to CSS counters.
|
||||||
*/
|
*/
|
||||||
// ── Live line-height factor ────────────────────────────────
|
// ── Live line-height factor + strut font-size ────────────────────────────────
|
||||||
// blockAttrs bakes --doc-line-factor into toDOM output, but ProseMirror reuses a
|
// blockAttrs bakes --doc-line-factor and the strut font-size into toDOM output,
|
||||||
// block's DOM while typing (sameMarkup ignores content), so a block typed after
|
// but ProseMirror reuses a block's DOM while typing (sameMarkup ignores content),
|
||||||
// creation keeps its creation-time factor until save/reopen. These node
|
// so a block edited after creation keeps its creation-time values until
|
||||||
// decorations recompute the factor from the live text on every doc change;
|
// save/reopen. These node decorations recompute both from the live content on
|
||||||
// unchanged nodes are structurally shared, so the WeakMap makes a pass cheap.
|
// every doc change; unchanged nodes are structurally shared, so the WeakMap
|
||||||
|
// makes a pass cheap. Dropping font-size from a decoration removes the baked
|
||||||
|
// value too (ProseMirror's patchAttributes calls style.removeProperty for every
|
||||||
|
// property named in the previous decoration style).
|
||||||
|
|
||||||
const LINE_FACTOR_BLOCKS = new Set(['docParagraph', 'docHeading', 'docListItem'])
|
const LINE_FACTOR_BLOCKS = new Set(['docParagraph', 'docHeading', 'docListItem'])
|
||||||
const lineFactorCjkCache = new WeakMap<PmNode, boolean>()
|
const lineFactorCache = new WeakMap<PmNode, string>()
|
||||||
|
|
||||||
|
// zero-width span whose CSS margin adds the half of Word's autoSpaceDE/DN gap
|
||||||
|
// that Chromium's text-autospace does not supply (see .doc-autospace-pad)
|
||||||
|
const autospacePadDom = () => {
|
||||||
|
const span = document.createElement('span')
|
||||||
|
span.className = 'doc-autospace-pad'
|
||||||
|
return span
|
||||||
|
}
|
||||||
|
|
||||||
|
const autospaceOffsetsCache = new WeakMap<PmNode, number[]>()
|
||||||
|
|
||||||
|
/** offsets (relative to the block's content start) of CJK-Latin pad boundaries */
|
||||||
|
function autospaceOffsets(node: PmNode): number[] {
|
||||||
|
let offsets = autospaceOffsetsCache.get(node)
|
||||||
|
if (offsets === undefined) {
|
||||||
|
const found: number[] = []
|
||||||
|
let offset = 0
|
||||||
|
let prevText = '' // reset by non-text inlines: pads need direct adjacency
|
||||||
|
node.forEach((child) => {
|
||||||
|
if (child.isText && child.text) {
|
||||||
|
if (autospacePadBetween(prevText, child.text)) found.push(offset)
|
||||||
|
for (const i of autospaceBoundaries(child.text)) found.push(offset + i)
|
||||||
|
prevText = child.text
|
||||||
|
} else {
|
||||||
|
prevText = ''
|
||||||
|
}
|
||||||
|
offset += child.nodeSize
|
||||||
|
})
|
||||||
|
offsets = found
|
||||||
|
autospaceOffsetsCache.set(node, offsets)
|
||||||
|
}
|
||||||
|
return offsets
|
||||||
|
}
|
||||||
|
|
||||||
function lineFactorDecos(doc: PmNode): DecorationSet {
|
function lineFactorDecos(doc: PmNode): DecorationSet {
|
||||||
const decos: Decoration[] = []
|
const decos: Decoration[] = []
|
||||||
doc.descendants((node, pos) => {
|
doc.descendants((node, pos) => {
|
||||||
if (!LINE_FACTOR_BLOCKS.has(node.type.name)) return true
|
if (!LINE_FACTOR_BLOCKS.has(node.type.name)) return true
|
||||||
if (node.textContent) {
|
if (node.textContent) {
|
||||||
let cjk = lineFactorCjkCache.get(node)
|
let style = lineFactorCache.get(node)
|
||||||
if (cjk === undefined) {
|
if (style === undefined) {
|
||||||
cjk = textHasCjk(node.textContent)
|
style = `--doc-line-factor:${paraLineFactorCss(node.textContent)}`
|
||||||
lineFactorCjkCache.set(node, cjk)
|
const strut = explicitStrutHalfPoints(node)
|
||||||
|
if (strut) style += `;--doc-strut:${strut / 2}pt;font-size:min(var(--doc-strut), 1em)`
|
||||||
|
lineFactorCache.set(node, style)
|
||||||
|
}
|
||||||
|
decos.push(Decoration.node(pos, pos + node.nodeSize, { style }))
|
||||||
|
if (node.attrs.autoSpace !== false) {
|
||||||
|
for (const off of autospaceOffsets(node)) {
|
||||||
|
decos.push(Decoration.widget(pos + 1 + off, autospacePadDom, { key: 'doc-autospace' }))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
decos.push(
|
|
||||||
Decoration.node(pos, pos + node.nodeSize, {
|
|
||||||
style: `--doc-line-factor:${cjk ? 1.3 : 'var(--doc-line-factor-latin,1.2)'}`,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
})
|
})
|
||||||
@@ -618,23 +725,53 @@ export const LineFactorExtension = Extension.create({
|
|||||||
name: 'lineFactorLive',
|
name: 'lineFactorLive',
|
||||||
addProseMirrorPlugins() {
|
addProseMirrorPlugins() {
|
||||||
const key = new PluginKey<DecorationSet>('lineFactorLive')
|
const key = new PluginKey<DecorationSet>('lineFactorLive')
|
||||||
|
const editor = this.editor
|
||||||
return [
|
return [
|
||||||
new Plugin<DecorationSet>({
|
new Plugin<DecorationSet>({
|
||||||
key,
|
key,
|
||||||
state: {
|
state: {
|
||||||
init: (_config, state) => lineFactorDecos(state.doc),
|
init: (_config, state) => lineFactorDecos(state.doc),
|
||||||
apply: (tr, old) => (tr.docChanged ? lineFactorDecos(tr.doc) : old),
|
apply: (tr, old) => {
|
||||||
|
if (tr.getMeta(key)) return lineFactorDecos(tr.doc)
|
||||||
|
if (!tr.docChanged) return old
|
||||||
|
// inserting pad widgets next to an active IME composition aborts it;
|
||||||
|
// keep the old set mapped and refresh on compositionend
|
||||||
|
if (editor?.view?.composing) return old.map(tr.mapping, tr.doc)
|
||||||
|
return lineFactorDecos(tr.doc)
|
||||||
|
},
|
||||||
},
|
},
|
||||||
props: {
|
props: {
|
||||||
decorations(state) {
|
decorations(state) {
|
||||||
return key.getState(state)
|
return key.getState(state)
|
||||||
},
|
},
|
||||||
|
handleDOMEvents: {
|
||||||
|
compositionend: (view) => {
|
||||||
|
window.setTimeout(() => {
|
||||||
|
if (!view.isDestroyed) view.dispatch(view.state.tr.setMeta(key, true))
|
||||||
|
})
|
||||||
|
return false
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
function firstRunSizeHalfPoints(node: PmNode): number | null {
|
||||||
|
let sz: number | null = null
|
||||||
|
node.descendants((child) => {
|
||||||
|
if (sz !== null) return false
|
||||||
|
if (child.isText) {
|
||||||
|
const mark = child.marks.find((m) => m.type.name === 'docTextStyle')
|
||||||
|
sz = (mark?.attrs.sizeHalfPoints as number | null) ?? null
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
return sz
|
||||||
|
}
|
||||||
|
|
||||||
export const ListNumberingExtension = Extension.create<object, ListNumberingStorage>({
|
export const ListNumberingExtension = Extension.create<object, ListNumberingStorage>({
|
||||||
name: 'listNumbering',
|
name: 'listNumbering',
|
||||||
addStorage() {
|
addStorage() {
|
||||||
@@ -645,41 +782,55 @@ export const ListNumberingExtension = Extension.create<object, ListNumberingStor
|
|||||||
const compute = (doc: PmNode): DecorationSet | null => {
|
const compute = (doc: PmNode): DecorationSet | null => {
|
||||||
if (storage.defs.size === 0) return null
|
if (storage.defs.size === 0) return null
|
||||||
const refs: ListItemRef[] = []
|
const refs: ListItemRef[] = []
|
||||||
const nodes: Array<{ pos: number; size: number; attrs: Record<string, unknown> }> = []
|
const nodes: Array<{ pos: number; node: PmNode }> = []
|
||||||
doc.descendants((node, pos) => {
|
doc.descendants((node, pos) => {
|
||||||
if (node.type.name === 'docListItem') {
|
if (node.type.name === 'docListItem') {
|
||||||
refs.push({
|
refs.push({
|
||||||
numId: (node.attrs.numId as string | null) ?? null,
|
numId: (node.attrs.numId as string | null) ?? null,
|
||||||
ilvl: Number(node.attrs.ilvl) || 0,
|
ilvl: Number(node.attrs.ilvl) || 0,
|
||||||
})
|
})
|
||||||
nodes.push({ pos, size: node.nodeSize, attrs: node.attrs })
|
nodes.push({ pos, node })
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
if (refs.length === 0) return null
|
if (refs.length === 0) return null
|
||||||
const markers = computeListMarkers(refs, storage.defs)
|
const markers = computeListMarkerInfos(refs, storage.defs)
|
||||||
const decos: Decoration[] = []
|
const decos: Decoration[] = []
|
||||||
markers.forEach((marker, i) => {
|
markers.forEach((marker, i) => {
|
||||||
if (marker === null) return
|
if (marker === null) return
|
||||||
const attrs: Record<string, string> = { 'data-marker': marker }
|
const styles: string[] = []
|
||||||
|
let text = marker.text
|
||||||
|
if (marker.symbolFont && marker.symbolChar) {
|
||||||
|
if (symbolFontCovers(marker.symbolFont, marker.symbolChar)) {
|
||||||
|
text = marker.symbolChar
|
||||||
|
styles.push(`--li-marker-font:"${marker.symbolFont}"`)
|
||||||
|
} else {
|
||||||
|
// substitute glyph: pin a Latin font (CJK fallback draws ・) and compensate its smaller bullet;
|
||||||
|
// --li-marker-lh:0 keeps the scaled em box from stretching the line
|
||||||
|
styles.push(`--li-marker-font:Arial,'Helvetica Neue',sans-serif`)
|
||||||
|
const scale = bulletMarkerScale(text)
|
||||||
|
if (scale !== 1) styles.push(`--li-marker-scale:${scale}`, '--li-marker-lh:0')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const attrs: Record<string, string> = { 'data-marker': text }
|
||||||
// geometry fallback: when the paragraph has no w:ind of its own, use the numbering.xml level's indent;
|
// geometry fallback: when the paragraph has no w:ind of its own, use the numbering.xml level's indent;
|
||||||
// marker font size always comes from the level's rPr (independent of paragraph text size)
|
// marker font size comes from the level's rPr, else follows the item's first text run (Word rule)
|
||||||
const def = refs[i].numId !== null ? storage.defs.get(refs[i].numId as string) : undefined
|
const def = refs[i].numId !== null ? storage.defs.get(refs[i].numId as string) : undefined
|
||||||
const level = def?.levels[Math.max(0, refs[i].ilvl)]
|
const level = def?.levels[Math.max(0, refs[i].ilvl)]
|
||||||
if (level) {
|
if (level) {
|
||||||
const styles: string[] = []
|
const nodeAttrs = nodes[i].node.attrs
|
||||||
const nodeAttrs = nodes[i].attrs
|
|
||||||
if (!nodeAttrs.indentLeft && level.indentLeft) {
|
if (!nodeAttrs.indentLeft && level.indentLeft) {
|
||||||
styles.push(`--li-left:${level.indentLeft / 20}pt`)
|
styles.push(`--li-left:${level.indentLeft / 20}pt`)
|
||||||
}
|
}
|
||||||
if (!nodeAttrs.indentFirstLine && level.hanging) {
|
if (!nodeAttrs.indentFirstLine && level.hanging) {
|
||||||
styles.push(`--li-hang:${level.hanging / 20}pt`)
|
styles.push(`--li-hang:${level.hanging / 20}pt`)
|
||||||
}
|
}
|
||||||
if (level.szHalfPoints) styles.push(`--li-marker-size:${level.szHalfPoints / 2}pt`)
|
const szHalf = level.szHalfPoints ?? firstRunSizeHalfPoints(nodes[i].node)
|
||||||
if (styles.length > 0) attrs.style = styles.join(';')
|
if (szHalf) styles.push(`--li-marker-size:${szHalf / 2}pt`)
|
||||||
}
|
}
|
||||||
decos.push(Decoration.node(nodes[i].pos, nodes[i].pos + nodes[i].size, attrs))
|
if (styles.length > 0) attrs.style = styles.join(';')
|
||||||
|
decos.push(Decoration.node(nodes[i].pos, nodes[i].pos + nodes[i].node.nodeSize, attrs))
|
||||||
})
|
})
|
||||||
return DecorationSet.create(doc, decos)
|
return DecorationSet.create(doc, decos)
|
||||||
}
|
}
|
||||||
@@ -719,6 +870,8 @@ const tableCellAttrs = {
|
|||||||
cellRevision: { default: null as Record<string, string> | null },
|
cellRevision: { default: null as Record<string, string> | null },
|
||||||
cellMar: { default: null as Record<string, number> | null },
|
cellMar: { default: null as Record<string, number> | null },
|
||||||
textDirection: { default: null as string | null },
|
textDirection: { default: null as string | null },
|
||||||
|
/** inner clip-box height (twips) when the row is hRule="exact" (computed in convert.ts) */
|
||||||
|
clipHeightTwips: { default: null as number | null },
|
||||||
colspan: { default: 1 },
|
colspan: { default: 1 },
|
||||||
rowspan: { default: 1 },
|
rowspan: { default: 1 },
|
||||||
colwidth: { default: null as number[] | null },
|
colwidth: { default: null as number[] | null },
|
||||||
@@ -801,6 +954,34 @@ function tableCellHtml(node: PmNode): Record<string, string> {
|
|||||||
return attrs
|
return attrs
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** exact-height rows clip via a fixed-height inner box: td height is min-height
|
||||||
|
* semantics in CSS table layout, so the td itself can never produce overflow */
|
||||||
|
export function cellClipStyle(vAlign: string | null, clipTwips: number): string {
|
||||||
|
return [
|
||||||
|
`height:${(clipTwips / 15).toFixed(1)}px`,
|
||||||
|
// replicate the td's vertical-align inside the fixed box (the box fills the cell);
|
||||||
|
// 'safe' falls back to start when content overflows — Word keeps the top and clips
|
||||||
|
// the bottom edge regardless of vAlign
|
||||||
|
...(vAlign === 'center'
|
||||||
|
? ['display:grid', 'align-content:safe center']
|
||||||
|
: vAlign === 'bottom'
|
||||||
|
? ['display:grid', 'align-content:safe end']
|
||||||
|
: []),
|
||||||
|
].join(';')
|
||||||
|
}
|
||||||
|
|
||||||
|
function tableCellSpec(tag: 'td' | 'th', node: PmNode): DOMOutputSpec {
|
||||||
|
const attrs = tableCellHtml(node)
|
||||||
|
const clip = node.attrs.clipHeightTwips as number | null
|
||||||
|
// 0 is a real clip height (padding/borders consume the whole exact row)
|
||||||
|
if (clip == null) return [tag, attrs, 0]
|
||||||
|
return [
|
||||||
|
tag,
|
||||||
|
attrs,
|
||||||
|
['div', { class: 'cell-clip', style: cellClipStyle(node.attrs.vAlign, clip) }, 0],
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
export type TableBordersAttr = Partial<
|
export type TableBordersAttr = Partial<
|
||||||
Record<
|
Record<
|
||||||
'top' | 'left' | 'bottom' | 'right' | 'insideH' | 'insideV',
|
'top' | 'left' | 'bottom' | 'right' | 'insideH' | 'insideV',
|
||||||
@@ -919,6 +1100,7 @@ export const DocTableRow = Node.create({
|
|||||||
addAttributes() {
|
addAttributes() {
|
||||||
return {
|
return {
|
||||||
heightTwips: { default: null as number | null },
|
heightTwips: { default: null as number | null },
|
||||||
|
heightRule: { default: null as 'atLeast' | 'exact' | null },
|
||||||
rawTrPr: { default: null as string | null },
|
rawTrPr: { default: null as string | null },
|
||||||
/** trPr w:ins/w:del row-level revision ({kind, author, ...} | null) */
|
/** trPr w:ins/w:del row-level revision ({kind, author, ...} | null) */
|
||||||
rowRevision: { default: null as Record<string, string> | null },
|
rowRevision: { default: null as Record<string, string> | null },
|
||||||
@@ -931,18 +1113,23 @@ export const DocTableRow = Node.create({
|
|||||||
const h = node.attrs.heightTwips as number | null
|
const h = node.attrs.heightTwips as number | null
|
||||||
const rev = node.attrs.rowRevision as { kind?: string; author?: string } | null
|
const rev = node.attrs.rowRevision as { kind?: string; author?: string } | null
|
||||||
const attrs: Record<string, string> = {}
|
const attrs: Record<string, string> = {}
|
||||||
if (h) attrs.style = `height:${((h / 1440) * 96).toFixed(1)}px`
|
const classes: string[] = []
|
||||||
|
if (h) {
|
||||||
|
attrs.style = `height:${((h / 1440) * 96).toFixed(1)}px`
|
||||||
|
if (node.attrs.heightRule === 'exact') classes.push('row-h-exact')
|
||||||
|
}
|
||||||
if (rev?.kind) {
|
if (rev?.kind) {
|
||||||
attrs.class = `row-rev-${rev.kind}`
|
classes.push(`row-rev-${rev.kind}`)
|
||||||
if (rev.author) attrs.title = rev.author
|
if (rev.author) attrs.title = rev.author
|
||||||
}
|
}
|
||||||
|
if (classes.length > 0) attrs.class = classes.join(' ')
|
||||||
return ['tr', attrs, 0]
|
return ['tr', attrs, 0]
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
export const DocTableCell = Node.create({
|
export const DocTableCell = Node.create({
|
||||||
name: 'docTableCell',
|
name: 'docTableCell',
|
||||||
content: '(docParagraph | docListItem)+ docNestedTable*',
|
content: '(docParagraph | docListItem | docNestedTable)+',
|
||||||
isolating: true,
|
isolating: true,
|
||||||
addAttributes() {
|
addAttributes() {
|
||||||
return tableCellAttrs
|
return tableCellAttrs
|
||||||
@@ -951,13 +1138,13 @@ export const DocTableCell = Node.create({
|
|||||||
return [{ tag: 'td' }]
|
return [{ tag: 'td' }]
|
||||||
},
|
},
|
||||||
renderHTML({ node }) {
|
renderHTML({ node }) {
|
||||||
return ['td', tableCellHtml(node), 0]
|
return tableCellSpec('td', node)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
export const DocTableHeader = Node.create({
|
export const DocTableHeader = Node.create({
|
||||||
name: 'docTableHeader',
|
name: 'docTableHeader',
|
||||||
content: '(docParagraph | docListItem)+ docNestedTable*',
|
content: '(docParagraph | docListItem | docNestedTable)+',
|
||||||
isolating: true,
|
isolating: true,
|
||||||
addAttributes() {
|
addAttributes() {
|
||||||
return tableCellAttrs
|
return tableCellAttrs
|
||||||
@@ -966,7 +1153,7 @@ export const DocTableHeader = Node.create({
|
|||||||
return [{ tag: 'th' }]
|
return [{ tag: 'th' }]
|
||||||
},
|
},
|
||||||
renderHTML({ node }) {
|
renderHTML({ node }) {
|
||||||
return ['th', tableCellHtml(node), 0]
|
return tableCellSpec('th', node)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -1215,6 +1402,14 @@ export const DocProtected = Node.create({
|
|||||||
fieldDisplay: { default: null as FieldDisplay | null },
|
fieldDisplay: { default: null as FieldDisplay | null },
|
||||||
/** decorative rule drawing: render as a horizontal line, not a chip */
|
/** decorative rule drawing: render as a horizontal line, not a chip */
|
||||||
decorative: { default: false },
|
decorative: { default: false },
|
||||||
|
/** stroke display of a decorative rule; null = default 1px full-width line */
|
||||||
|
ruleColorHex: { default: null as string | null },
|
||||||
|
ruleThicknessPx: { default: null as number | null },
|
||||||
|
ruleWidthPx: { default: null as number | null },
|
||||||
|
/** broken picture (missing rel/media): empty frame + alt text at the declared extent */
|
||||||
|
brokenImage: { default: false },
|
||||||
|
/** invisible body-level marker (stray bookmarkEnd…): render nothing, keep position */
|
||||||
|
invisibleMarker: { default: false },
|
||||||
/** display-only anchored textboxes (code boxes, callout cards) */
|
/** display-only anchored textboxes (code boxes, callout cards) */
|
||||||
textboxes: { default: null as TextboxDisplay[] | null },
|
textboxes: { default: null as TextboxDisplay[] | null },
|
||||||
/** editable OMML leaf tokens; formula structure remains protected */
|
/** editable OMML leaf tokens; formula structure remains protected */
|
||||||
@@ -1227,6 +1422,13 @@ export const DocProtected = Node.create({
|
|||||||
genImage: {
|
genImage: {
|
||||||
default: null as { base64: string; mime: string; widthPx: number; heightPx: number } | null,
|
default: null as { base64: string; mime: string; widthPx: number; heightPx: number } | null,
|
||||||
},
|
},
|
||||||
|
/** picture rotation (deg clockwise, 0-359) and mirror flips (a:xfrm rot/flipH/flipV) */
|
||||||
|
imageRotDeg: { default: null as number | null },
|
||||||
|
imageFlipH: { default: false },
|
||||||
|
imageFlipV: { default: false },
|
||||||
|
/** 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 },
|
||||||
/** new chart awaiting embedding at save time (data snapshot; edits live in chartDisplay) */
|
/** new chart awaiting embedding at save time (data snapshot; edits live in chartDisplay) */
|
||||||
genChart: { default: null as NewChart | null },
|
genChart: { default: null as NewChart | null },
|
||||||
}
|
}
|
||||||
@@ -1335,9 +1537,21 @@ function protectedDomSpec(node: PmNode): DomSpec {
|
|||||||
'data-idx': docxIndex === null ? '' : String(docxIndex),
|
'data-idx': docxIndex === null ? '' : String(docxIndex),
|
||||||
class: `doc-protected doc-protected-${blockType}`,
|
class: `doc-protected doc-protected-${blockType}`,
|
||||||
}
|
}
|
||||||
|
if (node.attrs.invisibleMarker) {
|
||||||
|
attrs.class += ' doc-protected-invisible'
|
||||||
|
return ['div', attrs]
|
||||||
|
}
|
||||||
if (decorative) {
|
if (decorative) {
|
||||||
attrs.class += ' doc-protected-rule'
|
attrs.class += ' doc-protected-rule'
|
||||||
return ['div', attrs, ['span', { class: 'doc-rule-line' }]]
|
const { ruleColorHex, ruleThicknessPx, ruleWidthPx } = node.attrs
|
||||||
|
// document stroke color/size, not chrome: inline hardcoded values
|
||||||
|
let style = ''
|
||||||
|
if (ruleColorHex) style += `background:#${String(ruleColorHex)};`
|
||||||
|
if (ruleThicknessPx) style += `height:${Number(ruleThicknessPx)}px;`
|
||||||
|
if (ruleWidthPx) style += `width:${Number(ruleWidthPx)}px;max-width:100%;`
|
||||||
|
const lineAttrs: Record<string, string> = { class: 'doc-rule-line' }
|
||||||
|
if (style) lineAttrs.style = style
|
||||||
|
return ['div', attrs, ['span', lineAttrs]]
|
||||||
}
|
}
|
||||||
if (Array.isArray(textboxes) && textboxes.length > 0) {
|
if (Array.isArray(textboxes) && textboxes.length > 0) {
|
||||||
attrs.class += ' doc-protected-textboxes'
|
attrs.class += ' doc-protected-textboxes'
|
||||||
@@ -1373,7 +1587,7 @@ function protectedDomSpec(node: PmNode): DomSpec {
|
|||||||
return ['div', attrs, ['span', { class: 'doc-sectbreak-label' }, String(label)]]
|
return ['div', attrs, ['span', { class: 'doc-sectbreak-label' }, String(label)]]
|
||||||
}
|
}
|
||||||
if (blockType === 'image' && imageDataUrl) {
|
if (blockType === 'image' && imageDataUrl) {
|
||||||
const { imageWidthPx, imageHeightPx, imageAlign, imageWrap } = node.attrs
|
const { imageWidthPx, imageHeightPx, imageAlign, imageWrap, imageRotDeg } = node.attrs
|
||||||
if (imageAlign === 'center' || imageAlign === 'right') {
|
if (imageAlign === 'center' || imageAlign === 'right') {
|
||||||
attrs['style'] = `text-align:${imageAlign}`
|
attrs['style'] = `text-align:${imageAlign}`
|
||||||
}
|
}
|
||||||
@@ -1387,6 +1601,16 @@ function protectedDomSpec(node: PmNode): DomSpec {
|
|||||||
`width:${Number(imageWidthPx)}px;` +
|
`width:${Number(imageWidthPx)}px;` +
|
||||||
(imageHeightPx ? `height:${Number(imageHeightPx)}px` : 'height:auto')
|
(imageHeightPx ? `height:${Number(imageHeightPx)}px` : 'height:auto')
|
||||||
}
|
}
|
||||||
|
// DrawingML order: flip mirrors the source, rot turns the result
|
||||||
|
// (CSS applies right-to-left, so scale sits last)
|
||||||
|
const xf: string[] = []
|
||||||
|
if (imageRotDeg) xf.push(`rotate(${Number(imageRotDeg)}deg)`)
|
||||||
|
if (node.attrs.imageFlipH) xf.push('scaleX(-1)')
|
||||||
|
if (node.attrs.imageFlipV) xf.push('scaleY(-1)')
|
||||||
|
if (xf.length) {
|
||||||
|
imgAttrs['style'] =
|
||||||
|
`${imgAttrs['style'] ? `${imgAttrs['style']};` : ''}transform:${xf.join(' ')}`
|
||||||
|
}
|
||||||
return [
|
return [
|
||||||
'div',
|
'div',
|
||||||
attrs,
|
attrs,
|
||||||
@@ -1434,6 +1658,24 @@ function protectedDomSpec(node: PmNode): DomSpec {
|
|||||||
['span', { class: 'box-resize-handle', contenteditable: 'false' }],
|
['span', { class: 'box-resize-handle', contenteditable: 'false' }],
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
// Broken picture (missing rel/media): empty frame at the declared extent
|
||||||
|
// with centered alt text. Frame/text colors stand in for document content
|
||||||
|
// (must look identical in both themes), hence hardcoded inline.
|
||||||
|
if (node.attrs.brokenImage) {
|
||||||
|
attrs.class += ' doc-protected-broken-img'
|
||||||
|
const { imageWidthPx, imageHeightPx, imageAlign } = node.attrs
|
||||||
|
if (imageAlign === 'center' || imageAlign === 'right') {
|
||||||
|
attrs.style = `text-align:${imageAlign}`
|
||||||
|
}
|
||||||
|
let style = 'border:1px solid #999;color:#888;'
|
||||||
|
if (imageWidthPx) style += `width:${Number(imageWidthPx)}px;`
|
||||||
|
if (imageHeightPx) style += `height:${Number(imageHeightPx)}px;`
|
||||||
|
return [
|
||||||
|
'div',
|
||||||
|
attrs,
|
||||||
|
['span', { class: 'doc-broken-img-frame', style }, String(previewText || label || '')],
|
||||||
|
]
|
||||||
|
}
|
||||||
// OLE embed with a packaged preview picture: show the picture with a
|
// OLE embed with a packaged preview picture: show the picture with a
|
||||||
// friendly type caption instead of a bare "Embedded object" label
|
// friendly type caption instead of a bare "Embedded object" label
|
||||||
const oleCaption = label === 'Embedded object' ? oleTypeLabel(node.attrs.oleProgId) : null
|
const oleCaption = label === 'Embedded object' ? oleTypeLabel(node.attrs.oleProgId) : null
|
||||||
@@ -2108,9 +2350,11 @@ function imageResizePlugin(): Plugin {
|
|||||||
// CSS `zoom` scales client coordinates; divide it back out
|
// CSS `zoom` scales client coordinates; divide it back out
|
||||||
const zoomEl = document.querySelector('.doc-zoom') as HTMLElement | null
|
const zoomEl = document.querySelector('.doc-zoom') as HTMLElement | null
|
||||||
const zoom = zoomEl ? parseFloat(getComputedStyle(zoomEl).zoom || '1') || 1 : 1
|
const zoom = zoomEl ? parseFloat(getComputedStyle(zoomEl).zoom || '1') || 1 : 1
|
||||||
const startRect = img.getBoundingClientRect()
|
// Layout-box measurements: getBoundingClientRect would include the
|
||||||
const startW = startRect.width / zoom
|
// rotation/flip transform, swapping width/height for 90°-rotated images
|
||||||
const ratio = startRect.height / startRect.width
|
const startW = img.offsetWidth
|
||||||
|
const ratio = img.offsetHeight / Math.max(1, img.offsetWidth)
|
||||||
|
const priorStyle = img.getAttribute('style')
|
||||||
const startX = event.clientX
|
const startX = event.clientX
|
||||||
|
|
||||||
const widthAt = (e: MouseEvent) => Math.max(24, startW + (e.clientX - startX) / zoom)
|
const widthAt = (e: MouseEvent) => Math.max(24, startW + (e.clientX - startX) / zoom)
|
||||||
@@ -2122,6 +2366,12 @@ function imageResizePlugin(): Plugin {
|
|||||||
const onUp = (e: MouseEvent) => {
|
const onUp = (e: MouseEvent) => {
|
||||||
window.removeEventListener('mousemove', onMove)
|
window.removeEventListener('mousemove', onMove)
|
||||||
window.removeEventListener('mouseup', onUp)
|
window.removeEventListener('mouseup', onUp)
|
||||||
|
// A plain click on the handle must not rewrite the stored size
|
||||||
|
if (Math.abs(e.clientX - startX) < 2) {
|
||||||
|
if (priorStyle === null) img.removeAttribute('style')
|
||||||
|
else img.setAttribute('style', priorStyle)
|
||||||
|
return
|
||||||
|
}
|
||||||
const w = Math.round(widthAt(e))
|
const w = Math.round(widthAt(e))
|
||||||
const node = view.state.doc.nodeAt(pos)
|
const node = view.state.doc.nodeAt(pos)
|
||||||
if (!node) return
|
if (!node) return
|
||||||
@@ -2208,6 +2458,10 @@ function floatingObjectDragPlugin(): Plugin {
|
|||||||
const visual = wrapper.querySelector(
|
const visual = wrapper.querySelector(
|
||||||
isTextbox ? '.doc-textbox' : '.doc-protected-img',
|
isTextbox ? '.doc-textbox' : '.doc-protected-img',
|
||||||
) as HTMLElement | null
|
) as HTMLElement | null
|
||||||
|
// Images may already carry a rotation/flip transform: the drag translate
|
||||||
|
// must compose with it (prepended = applied in screen space) and the
|
||||||
|
// original must come back on mouseup, or the orientation vanishes
|
||||||
|
const baseTransform = visual?.style.transform ?? ''
|
||||||
|
|
||||||
// 3px threshold keeps plain clicks (select, first click of a
|
// 3px threshold keeps plain clicks (select, first click of a
|
||||||
// double-click-to-edit) from nudging the object
|
// double-click-to-edit) from nudging the object
|
||||||
@@ -2217,13 +2471,16 @@ function floatingObjectDragPlugin(): Plugin {
|
|||||||
const dy = (e.clientY - startY) / zoom
|
const dy = (e.clientY - startY) / zoom
|
||||||
if (!dragging && Math.abs(dx) < 3 && Math.abs(dy) < 3) return
|
if (!dragging && Math.abs(dx) < 3 && Math.abs(dy) < 3) return
|
||||||
dragging = true
|
dragging = true
|
||||||
if (visual) visual.style.transform = `translate(${dx}px, ${dy}px)`
|
if (visual) {
|
||||||
|
visual.style.transform =
|
||||||
|
`translate(${dx}px, ${dy}px)` + (baseTransform ? ` ${baseTransform}` : '')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const onUp = (e: MouseEvent) => {
|
const onUp = (e: MouseEvent) => {
|
||||||
window.removeEventListener('mousemove', onMove)
|
window.removeEventListener('mousemove', onMove)
|
||||||
window.removeEventListener('mouseup', onUp)
|
window.removeEventListener('mouseup', onUp)
|
||||||
if (visual) visual.style.transform = ''
|
if (visual) visual.style.transform = baseTransform
|
||||||
|
|
||||||
const dx = (e.clientX - startX) / zoom
|
const dx = (e.clientX - startX) / zoom
|
||||||
const dy = (e.clientY - startY) / zoom
|
const dy = (e.clientY - startY) / zoom
|
||||||
@@ -2364,6 +2621,7 @@ export const editorExtensions = [
|
|||||||
DocNoteRef,
|
DocNoteRef,
|
||||||
DocXeMark,
|
DocXeMark,
|
||||||
DocRuby,
|
DocRuby,
|
||||||
|
DocInlineImage,
|
||||||
DocInlineMath,
|
DocInlineMath,
|
||||||
DocParagraph,
|
DocParagraph,
|
||||||
DocHeading,
|
DocHeading,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import {
|
import {
|
||||||
|
PAGE_MARK,
|
||||||
TOTAL_PAGES_MARK,
|
TOTAL_PAGES_MARK,
|
||||||
type HeaderFooter,
|
type HeaderFooter,
|
||||||
type HfImage,
|
type HfImage,
|
||||||
@@ -10,7 +11,7 @@ import { cssDualFontFamily, cssFontFamily } from '../line-metrics'
|
|||||||
/**
|
/**
|
||||||
* Plain-DOM header/footer rendering for the canvas page gaps (M4 always-on
|
* Plain-DOM header/footer rendering for the canvas page gaps (M4 always-on
|
||||||
* pagination). Mirrors HeaderFooterArea's read-only display: same classes,
|
* pagination). Mirrors HeaderFooterArea's read-only display: same classes,
|
||||||
* same '#' / NUMPAGES substitution — but built imperatively because page gaps
|
* same PAGE_MARK / NUMPAGES substitution — but built imperatively because page gaps
|
||||||
* are ProseMirror widget decorations, not React children.
|
* are ProseMirror widget decorations, not React children.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -30,34 +31,90 @@ function applyRunStyle(span: HTMLElement, run: Run): void {
|
|||||||
function parasOf(value: HeaderFooter): HfParagraph[] {
|
function parasOf(value: HeaderFooter): HfParagraph[] {
|
||||||
if (value.paras?.length) return value.paras
|
if (value.paras?.length) return value.paras
|
||||||
const runs: Run[] = value.text ? [{ text: value.text }] : []
|
const runs: Run[] = value.text ? [{ text: value.text }] : []
|
||||||
if (value.pageNumber && !value.text.includes('#')) {
|
if (value.pageNumber && !value.text.includes('#') && !value.text.includes(PAGE_MARK)) {
|
||||||
runs.push({ text: runs.length > 0 ? ' #' : '#' })
|
runs.push({ text: runs.length > 0 ? ` ${PAGE_MARK}` : PAGE_MARK })
|
||||||
}
|
}
|
||||||
return [{ align: 'center', runs }]
|
return [{ align: 'center', runs }]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** parsed parts carry PAGE fields as PAGE_MARK; only mark-free values fall back to the user-typed '#' (mirrors HeaderFooterArea) */
|
||||||
|
function paraHasPageMark(p: HfParagraph): boolean {
|
||||||
|
return [p.runs, ...(p.cells?.map((c) => c.runs) ?? [])].some((rs) =>
|
||||||
|
rs.some((r) => r.text.includes(PAGE_MARK)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hfUsesLegacyHash(value: HeaderFooter): boolean {
|
||||||
|
if (!value.pageNumber) return false
|
||||||
|
if (value.text.includes(PAGE_MARK)) return false
|
||||||
|
return !value.paras?.some(paraHasPageMark)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hfHasPageField(value: HeaderFooter | null | undefined): boolean {
|
||||||
|
return Boolean(
|
||||||
|
value &&
|
||||||
|
(value.pageNumber || value.text.includes(PAGE_MARK) || value.paras?.some(paraHasPageMark)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove Page Numbers: strip PAGE_MARK fields (legacy parts: only the first user-typed '#'), keeping literal '#' text and rich formatting.
|
||||||
|
* Layout-table rows (`cells`) pass through untouched: they are display-only and saving keeps
|
||||||
|
* the part's original w:tbl bytes, so a table-held PAGE field cannot be removed. */
|
||||||
|
export function hfWithoutPageMarks(value: HeaderFooter): HeaderFooter {
|
||||||
|
let legacyHash = hfUsesLegacyHash(value)
|
||||||
|
const strip = (t: string) => {
|
||||||
|
const out = t.replaceAll(PAGE_MARK, '')
|
||||||
|
if (legacyHash && out.includes('#')) {
|
||||||
|
legacyHash = false
|
||||||
|
return out.replace('#', '')
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
if (!value.paras?.length) return { ...value, text: strip(value.text), pageNumber: false }
|
||||||
|
const paras = value.paras
|
||||||
|
.map((p) =>
|
||||||
|
p.cells
|
||||||
|
? p
|
||||||
|
: { ...p, runs: p.runs.map((r) => ({ ...r, text: strip(r.text) })).filter((r) => r.text) },
|
||||||
|
)
|
||||||
|
// dedicated page-number paragraphs go away entirely; table rows and user-typed blank lines stay
|
||||||
|
.filter((p, i) => p.cells != null || p.runs.length > 0 || value.paras![i].runs.length === 0)
|
||||||
|
const text = paras
|
||||||
|
.map((p) => [...p.runs, ...(p.cells?.flatMap((c) => c.runs) ?? [])].map((r) => r.text).join(''))
|
||||||
|
.join('')
|
||||||
|
if (!text) return { ...value, text: '', paras: undefined, pageNumber: false }
|
||||||
|
return { ...value, text, paras, pageNumber: false }
|
||||||
|
}
|
||||||
|
|
||||||
export function hfHasVisibleContent(
|
export function hfHasVisibleContent(
|
||||||
value: HeaderFooter | null | undefined,
|
value: HeaderFooter | null | undefined,
|
||||||
images?: HfImage[],
|
images?: HfImage[],
|
||||||
): boolean {
|
): boolean {
|
||||||
if (images?.length) return true
|
if (images?.length) return true
|
||||||
if (!value) return false
|
if (!value) return false
|
||||||
return Boolean(value.text || value.pageNumber || value.paras?.some((p) => p.runs.length > 0))
|
return Boolean(
|
||||||
|
value.text ||
|
||||||
|
value.pageNumber ||
|
||||||
|
value.paras?.some((p) => p.runs.length > 0 || p.cells?.length),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function makeGapHfEl(opts: {
|
export function makeGapHfEl(opts: {
|
||||||
kind: 'header' | 'footer'
|
kind: 'header' | 'footer'
|
||||||
value: HeaderFooter
|
value: HeaderFooter
|
||||||
images?: HfImage[]
|
images?: HfImage[]
|
||||||
/** page number shown for the '#' marker (may be a section-formatted string) */
|
/** page number shown for the PAGE marker (may be a section-formatted string) */
|
||||||
pageNo: number | string
|
pageNo: number | string
|
||||||
/** total page count shown for the NUMPAGES marker */
|
/** total page count shown for the NUMPAGES marker */
|
||||||
pageTotal: number
|
pageTotal: number
|
||||||
}): HTMLElement {
|
}): HTMLElement {
|
||||||
const { kind, value, images, pageNo, pageTotal } = opts
|
const { kind, value, images, pageNo, pageTotal } = opts
|
||||||
|
const legacyHash = hfUsesLegacyHash(value)
|
||||||
const display = (text: string) => {
|
const display = (text: string) => {
|
||||||
const substituted = text.replaceAll(TOTAL_PAGES_MARK, String(pageTotal))
|
const substituted = text
|
||||||
return value.pageNumber ? substituted.replace('#', String(pageNo)) : substituted
|
.replaceAll(TOTAL_PAGES_MARK, String(pageTotal))
|
||||||
|
.replaceAll(PAGE_MARK, String(pageNo))
|
||||||
|
return legacyHash ? substituted.replace('#', String(pageNo)) : substituted
|
||||||
}
|
}
|
||||||
const wrap = document.createElement('div')
|
const wrap = document.createElement('div')
|
||||||
wrap.className = `page-hf page-hf-${kind} page-gap-hf`
|
wrap.className = `page-hf page-hf-${kind} page-gap-hf`
|
||||||
@@ -79,6 +136,30 @@ export function makeGapHfEl(opts: {
|
|||||||
for (const para of parasOf(value)) {
|
for (const para of parasOf(value)) {
|
||||||
const p = document.createElement('div')
|
const p = document.createElement('div')
|
||||||
p.className = 'page-hf-para'
|
p.className = 'page-hf-para'
|
||||||
|
if (para.cells) {
|
||||||
|
// layout-table row: flex columns sized by the cell widths
|
||||||
|
p.classList.add('page-hf-row')
|
||||||
|
for (const cell of para.cells) {
|
||||||
|
const cellEl = document.createElement('div')
|
||||||
|
cellEl.className = 'page-hf-cell'
|
||||||
|
if (cell.widthPct) cellEl.style.width = `${cell.widthPct}%`
|
||||||
|
if (cell.align) {
|
||||||
|
cellEl.style.textAlign =
|
||||||
|
cell.align === 'left' || cell.align === 'center' || cell.align === 'right'
|
||||||
|
? cell.align
|
||||||
|
: 'justify'
|
||||||
|
}
|
||||||
|
for (const run of cell.runs) {
|
||||||
|
const span = document.createElement('span')
|
||||||
|
span.textContent = display(run.text)
|
||||||
|
applyRunStyle(span, run)
|
||||||
|
cellEl.append(span)
|
||||||
|
}
|
||||||
|
p.append(cellEl)
|
||||||
|
}
|
||||||
|
wrap.append(p)
|
||||||
|
continue
|
||||||
|
}
|
||||||
if (para.bidi) p.style.direction = 'rtl'
|
if (para.bidi) p.style.direction = 'rtl'
|
||||||
if (para.align) {
|
if (para.align) {
|
||||||
p.style.textAlign =
|
p.style.textAlign =
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { Extension, Mark } from '@tiptap/core'
|
|||||||
import { Plugin, PluginKey } from '@tiptap/pm/state'
|
import { Plugin, PluginKey } from '@tiptap/pm/state'
|
||||||
import { Decoration, DecorationSet } from '@tiptap/pm/view'
|
import { Decoration, DecorationSet } from '@tiptap/pm/view'
|
||||||
import {} from '@tiptap/pm/tables'
|
import {} from '@tiptap/pm/tables'
|
||||||
import { cssDualFontFamily, cssFontFamily } from '../line-metrics'
|
import { cssCsFontFamily, cssDualFontFamily, cssFontFamily } from '../line-metrics'
|
||||||
import { isEastAsianFontName } from '../font-list'
|
import { isEastAsianFontName } from '../font-list'
|
||||||
import { t } from '../i18n/locale'
|
import { t } from '../i18n/locale'
|
||||||
import {} from '@genoffice/docx-engine'
|
import {} from '@genoffice/docx-engine'
|
||||||
@@ -358,7 +358,13 @@ export function fontAttrsFromFamilyChain(chain: string | undefined): Record<stri
|
|||||||
const families = (chain ?? '')
|
const families = (chain ?? '')
|
||||||
.split(',')
|
.split(',')
|
||||||
.map((x) => x.trim().replace(/^["']|["']$/g, ''))
|
.map((x) => x.trim().replace(/^["']|["']$/g, ''))
|
||||||
.filter((x) => x && !/^(serif|sans-serif|monospace|cursive|fantasy|system-ui)$/i.test(x))
|
.filter(
|
||||||
|
(x) =>
|
||||||
|
x &&
|
||||||
|
!/^(serif|sans-serif|monospace|cursive|fantasy|system-ui)$/i.test(x) &&
|
||||||
|
// internal fonts.css aliases (GenOffice Songti SC etc.) are not user picks
|
||||||
|
!/^genoffice /i.test(x),
|
||||||
|
)
|
||||||
const ea = families.find(
|
const ea = families.find(
|
||||||
(f, i) => isEastAsianFontName(f) && (i === 0 || !/^noto (sans|serif) cjk sc$/i.test(f)),
|
(f, i) => isEastAsianFontName(f) && (i === 0 || !/^noto (sans|serif) cjk sc$/i.test(f)),
|
||||||
)
|
)
|
||||||
@@ -417,6 +423,8 @@ export const TextStyleMark = Mark.create({
|
|||||||
font: { default: null as string | null },
|
font: { default: null as string | null },
|
||||||
// Latin slot (w:ascii/w:hAnsi) when it differs from the primary/eastAsia font
|
// Latin slot (w:ascii/w:hAnsi) when it differs from the primary/eastAsia font
|
||||||
fontAscii: { default: null as string | null },
|
fontAscii: { default: null as string | null },
|
||||||
|
// complex-script slot (w:cs); convert sets it only when the run text needs it
|
||||||
|
csFont: { default: null as string | null },
|
||||||
charSpacingTwips: { default: null as number | null },
|
charSpacingTwips: { default: null as number | null },
|
||||||
// letter spacing (em, negative = condensed) converted from w:w scaling; precomputed by convert per run text
|
// letter spacing (em, negative = condensed) converted from w:w scaling; precomputed by convert per run text
|
||||||
charScaleEm: { default: null as number | null },
|
charScaleEm: { default: null as number | null },
|
||||||
@@ -446,11 +454,18 @@ export const TextStyleMark = Mark.create({
|
|||||||
if (mark.attrs.color) styles.push(`color:#${mark.attrs.color}`)
|
if (mark.attrs.color) styles.push(`color:#${mark.attrs.color}`)
|
||||||
if (mark.attrs.sizeHalfPoints)
|
if (mark.attrs.sizeHalfPoints)
|
||||||
styles.push(`font-size:${Number(mark.attrs.sizeHalfPoints) / 2}pt`)
|
styles.push(`font-size:${Number(mark.attrs.sizeHalfPoints) / 2}pt`)
|
||||||
if (mark.attrs.font || mark.attrs.fontAscii) {
|
if (mark.attrs.font || mark.attrs.fontAscii || mark.attrs.csFont) {
|
||||||
const ea = mark.attrs.font ? String(mark.attrs.font) : null
|
const ea = mark.attrs.font ? String(mark.attrs.font) : null
|
||||||
const ascii = mark.attrs.fontAscii ? String(mark.attrs.fontAscii) : null
|
const ascii = mark.attrs.fontAscii ? String(mark.attrs.fontAscii) : null
|
||||||
|
const cs = mark.attrs.csFont ? String(mark.attrs.csFont) : null
|
||||||
styles.push(
|
styles.push(
|
||||||
`font-family:${ea && ascii ? cssDualFontFamily(ascii, ea) : cssFontFamily((ea ?? ascii)!)}`,
|
`font-family:${
|
||||||
|
cs
|
||||||
|
? cssCsFontFamily(cs, ascii ?? undefined, ea ?? undefined)
|
||||||
|
: ea && ascii
|
||||||
|
? cssDualFontFamily(ascii, ea)
|
||||||
|
: cssFontFamily((ea ?? ascii)!)
|
||||||
|
}`,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
const spacingPt = mark.attrs.charSpacingTwips ? Number(mark.attrs.charSpacingTwips) / 20 : 0
|
const spacingPt = mark.attrs.charSpacingTwips ? Number(mark.attrs.charSpacingTwips) / 20 : 0
|
||||||
|
|||||||
@@ -1,3 +1,10 @@
|
|||||||
// Implementation lives in the engine (parse-time TOC numbering reuses it);
|
// Implementation lives in the engine (parse-time TOC numbering reuses it);
|
||||||
// this module keeps the historical import path for the editor.
|
// this module keeps the historical import path for the editor.
|
||||||
export { computeListMarkers, formatNumber, type ListItemRef } from '@genoffice/docx-engine'
|
export {
|
||||||
|
bulletMarkerScale,
|
||||||
|
computeListMarkerInfos,
|
||||||
|
computeListMarkers,
|
||||||
|
formatNumber,
|
||||||
|
type ListItemRef,
|
||||||
|
type ListMarkerInfo,
|
||||||
|
} from '@genoffice/docx-engine'
|
||||||
|
|||||||
@@ -47,7 +47,9 @@ export interface GapMetrics {
|
|||||||
/** height of the gray inter-page band inside a page gap */
|
/** height of the gray inter-page band inside a page gap */
|
||||||
export const GAP_BAND = 28
|
export const GAP_BAND = 28
|
||||||
|
|
||||||
function makeGapEl(m: GapMetrics, kind: 'block' | 'inline' | 'table' | 'cut'): HTMLElement {
|
export type GapKind = 'block' | 'inline' | 'table' | 'cut' | 'cell'
|
||||||
|
|
||||||
|
export function makeGapEl(m: GapMetrics, kind: GapKind): HTMLElement {
|
||||||
const gap = document.createElement(kind === 'table' ? 'tr' : 'div')
|
const gap = document.createElement(kind === 'table' ? 'tr' : 'div')
|
||||||
gap.contentEditable = 'false'
|
gap.contentEditable = 'false'
|
||||||
if (kind === 'cut') {
|
if (kind === 'cut') {
|
||||||
@@ -72,13 +74,19 @@ function makeGapEl(m: GapMetrics, kind: 'block' | 'inline' | 'table' | 'cut'): H
|
|||||||
gap.appendChild(cell)
|
gap.appendChild(cell)
|
||||||
return gap
|
return gap
|
||||||
}
|
}
|
||||||
gap.className = kind === 'inline' ? 'page-gap page-gap-inline' : 'page-gap'
|
gap.className =
|
||||||
|
kind === 'cell'
|
||||||
|
? // in-cell gap (single-column in-row table cut): inline gap + opaque bands covering the cell's fill/borders
|
||||||
|
'page-gap page-gap-inline page-gap-cell'
|
||||||
|
: kind === 'inline'
|
||||||
|
? 'page-gap page-gap-inline'
|
||||||
|
: 'page-gap'
|
||||||
gap.style.marginLeft = `-${m.marginLeft}px`
|
gap.style.marginLeft = `-${m.marginLeft}px`
|
||||||
gap.style.marginRight = `-${m.marginRight}px`
|
gap.style.marginRight = `-${m.marginRight}px`
|
||||||
// inline-block (not block-level): avoids block-in-inline anonymous-box splitting,
|
// inline-block (not block-level): avoids block-in-inline anonymous-box splitting,
|
||||||
// which would re-apply text-indent/alignment on continuation lines and drift line
|
// which would re-apply text-indent/alignment on continuation lines and drift line
|
||||||
// breaks; negative margins don't widen an inline-block, so width explicitly adds the bleed
|
// breaks; negative margins don't widen an inline-block, so width explicitly adds the bleed
|
||||||
if (kind === 'inline') gap.style.width = `calc(100% + ${m.marginLeft + m.marginRight}px)`
|
if (kind !== 'block') gap.style.width = `calc(100% + ${m.marginLeft + m.marginRight}px)`
|
||||||
return gap
|
return gap
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,7 +103,7 @@ export type PageGapSpec = {
|
|||||||
* (the slicing engine already reserved their height on the new page) */
|
* (the slicing engine already reserved their height on the new page) */
|
||||||
repeatHeaderEls?: HTMLElement[]
|
repeatHeaderEls?: HTMLElement[]
|
||||||
repeatHeaderKey?: string
|
repeatHeaderKey?: string
|
||||||
} & ({ el: HTMLElement } | { pos: number; kind?: 'inline' | 'table' | 'cut' })
|
} & ({ 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) */
|
/** Rebuild all page gaps (an empty list clears them); each gap carries its own margins (sections differ) */
|
||||||
export function setPageGaps(view: EditorView, gaps: PageGapSpec[]): void {
|
export function setPageGaps(view: EditorView, gaps: PageGapSpec[]): void {
|
||||||
@@ -105,7 +113,7 @@ export function setPageGaps(view: EditorView, gaps: PageGapSpec[]): void {
|
|||||||
ordinal++
|
ordinal++
|
||||||
const { metrics, notes, hfEls } = gap
|
const { metrics, notes, hfEls } = gap
|
||||||
let pos: number
|
let pos: number
|
||||||
let kind: 'block' | 'inline' | 'table' | 'cut'
|
let kind: GapKind
|
||||||
if ('el' in gap) {
|
if ('el' in gap) {
|
||||||
kind = 'block'
|
kind = 'block'
|
||||||
try {
|
try {
|
||||||
@@ -125,7 +133,7 @@ export function setPageGaps(view: EditorView, gaps: PageGapSpec[]): void {
|
|||||||
() => {
|
() => {
|
||||||
const el = makeGapEl(metrics, kind)
|
const el = makeGapEl(metrics, kind)
|
||||||
if (notes) el.appendChild(notes)
|
if (notes) el.appendChild(notes)
|
||||||
if (hfEls && (kind === 'block' || kind === 'inline')) {
|
if (hfEls && (kind === 'block' || kind === 'inline' || kind === 'cell')) {
|
||||||
for (const hf of hfEls) el.appendChild(hf)
|
for (const hf of hfEls) el.appendChild(hf)
|
||||||
} else if (hfEls && kind === 'table') {
|
} else if (hfEls && kind === 'table') {
|
||||||
// table-row gaps position their strips inside the absolutely-filled cell;
|
// table-row gaps position their strips inside the absolutely-filled cell;
|
||||||
@@ -141,7 +149,8 @@ export function setPageGaps(view: EditorView, gaps: PageGapSpec[]): void {
|
|||||||
// position without changing the page, so an ordinal key lets sameGaps
|
// position without changing the page, so an ordinal key lets sameGaps
|
||||||
// skip the dispatch entirely and lets PM reuse the widget DOM when a
|
// skip the dispatch entirely and lets PM reuse the widget DOM when a
|
||||||
// dispatch does happen
|
// dispatch does happen
|
||||||
key: `page-gap-${kind[0]}-${ordinal}-${mKey}${gap.notesKey ? `-${gap.notesKey}` : ''}${gap.hfKey ? `-${gap.hfKey}` : ''}`,
|
// full kind, not kind[0]: 'cut' and 'cell' would collide and skip the rebuild
|
||||||
|
key: `page-gap-${kind}-${ordinal}-${mKey}${gap.notesKey ? `-${gap.notesKey}` : ''}${gap.hfKey ? `-${gap.hfKey}` : ''}`,
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -3,13 +3,21 @@ import {} from '@tiptap/pm/state'
|
|||||||
import type { EditorView } from '@tiptap/pm/view'
|
import type { EditorView } from '@tiptap/pm/view'
|
||||||
import {} from '@tiptap/pm/tables'
|
import {} from '@tiptap/pm/tables'
|
||||||
import { WORDART_PRESETS, wordArtStrokePx } from '@genoffice/ui'
|
import { WORDART_PRESETS, wordArtStrokePx } from '@genoffice/ui'
|
||||||
import { cssDualFontFamily, cssFontFamily } from '../line-metrics'
|
import {
|
||||||
|
autospaceBoundaries,
|
||||||
|
autospacePadBetween,
|
||||||
|
cssCsFontFamily,
|
||||||
|
cssDualFontFamily,
|
||||||
|
cssFontFamily,
|
||||||
|
textHasComplexScript,
|
||||||
|
} from '../line-metrics'
|
||||||
import { shapeBackgroundCss } from './shape-svg'
|
import { shapeBackgroundCss } from './shape-svg'
|
||||||
import { t } from '../i18n/locale'
|
import { t } from '../i18n/locale'
|
||||||
import {
|
import {
|
||||||
type ChartDisplay,
|
type ChartDisplay,
|
||||||
type FieldDisplay,
|
type FieldDisplay,
|
||||||
type FormulaDisplay,
|
type FormulaDisplay,
|
||||||
|
type Run,
|
||||||
type TableModel,
|
type TableModel,
|
||||||
type TextboxDisplay,
|
type TextboxDisplay,
|
||||||
} from '@genoffice/docx-engine'
|
} from '@genoffice/docx-engine'
|
||||||
@@ -25,11 +33,13 @@ import {
|
|||||||
ProtectedContentEditor,
|
ProtectedContentEditor,
|
||||||
TableBordersAttr,
|
TableBordersAttr,
|
||||||
borderLineCss,
|
borderLineCss,
|
||||||
|
cellClipStyle,
|
||||||
cellPadCss,
|
cellPadCss,
|
||||||
preventProtectedLineBreak,
|
preventProtectedLineBreak,
|
||||||
protectedText,
|
protectedText,
|
||||||
tableBordersCss,
|
tableBordersCss,
|
||||||
} from './extensions'
|
} from './extensions'
|
||||||
|
import { cellClipTwips } from './convert'
|
||||||
|
|
||||||
// Word: links and TOC entries jump on modifier+click only
|
// Word: links and TOC entries jump on modifier+click only
|
||||||
const jumpHint = () =>
|
const jumpHint = () =>
|
||||||
@@ -460,31 +470,72 @@ export function textboxBoxStyle(box: TextboxDisplay): string {
|
|||||||
.join(';')
|
.join(';')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const AUTOSPACE_PAD_SPEC: DomSpec = ['span', { class: 'doc-autospace-pad' }]
|
||||||
|
|
||||||
|
/** static-DOM counterpart of the editor's autospace pad decorations */
|
||||||
|
function padSegments(text: string): unknown[] {
|
||||||
|
const cuts = autospaceBoundaries(text)
|
||||||
|
if (cuts.length === 0) return [text]
|
||||||
|
const out: unknown[] = []
|
||||||
|
let start = 0
|
||||||
|
for (const cut of cuts) {
|
||||||
|
out.push(text.slice(start, cut), AUTOSPACE_PAD_SPEC)
|
||||||
|
start = cut
|
||||||
|
}
|
||||||
|
out.push(text.slice(start))
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** run → styled <span> spec, shared by textbox and table-cell rendering */
|
||||||
|
export function runSpanSpec(run: Run, autoSpace?: boolean): DomSpec {
|
||||||
|
const cs = run.csFont && textHasComplexScript(run.text) ? run.csFont : undefined
|
||||||
|
const runStyle = [
|
||||||
|
run.color ? `color:#${run.color}` : '',
|
||||||
|
run.bold ? 'font-weight:700' : '',
|
||||||
|
run.italic ? 'font-style:italic' : '',
|
||||||
|
run.underline ? 'text-decoration:underline' : '',
|
||||||
|
run.font || run.fontAscii || cs
|
||||||
|
? `font-family:${
|
||||||
|
cs
|
||||||
|
? cssCsFontFamily(cs, run.fontAscii, run.font)
|
||||||
|
: run.font && run.fontAscii
|
||||||
|
? cssDualFontFamily(run.fontAscii, run.font)
|
||||||
|
: cssFontFamily((run.font ?? run.fontAscii)!)
|
||||||
|
}`
|
||||||
|
: '',
|
||||||
|
run.sizeHalfPoints ? `font-size:${run.sizeHalfPoints / 2}pt` : '',
|
||||||
|
// explicit autoSpaceDE/DN off also disables the browser's native gap (same as the editor path)
|
||||||
|
autoSpace === false ? 'text-autospace:no-autospace' : '',
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(';')
|
||||||
|
const content = autoSpace === false ? [run.text] : padSegments(run.text)
|
||||||
|
return runStyle ? ['span', { style: runStyle }, ...content] : ['span', {}, ...content]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** run spans with pads at run-boundary CJK-Latin seams (empty runs keep their span, no pad) */
|
||||||
|
function runSpansWithPads(runs: Run[], autoSpace?: boolean): DomSpec[] {
|
||||||
|
const out: DomSpec[] = []
|
||||||
|
let prevText = ''
|
||||||
|
for (const run of runs) {
|
||||||
|
if (run.text !== '') {
|
||||||
|
if (autoSpace !== false && autospacePadBetween(prevText, run.text)) {
|
||||||
|
out.push(AUTOSPACE_PAD_SPEC)
|
||||||
|
}
|
||||||
|
prevText = run.text
|
||||||
|
}
|
||||||
|
out.push(runSpanSpec(run, autoSpace))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
export function renderTextboxSpec(box: TextboxDisplay): DomSpec {
|
export function renderTextboxSpec(box: TextboxDisplay): DomSpec {
|
||||||
const style = textboxBoxStyle(box)
|
const style = textboxBoxStyle(box)
|
||||||
const boxAttrs: Record<string, string> = { class: 'doc-textbox' }
|
const boxAttrs: Record<string, string> = { class: 'doc-textbox' }
|
||||||
if (style) boxAttrs.style = style
|
if (style) boxAttrs.style = style
|
||||||
|
|
||||||
const paras: DomSpec[] = box.paras.map((para) => {
|
const paras: DomSpec[] = box.paras.map((para) => {
|
||||||
const spans: DomSpec[] = para.runs.map((run) => {
|
const spans: DomSpec[] = runSpansWithPads(para.runs, para.autoSpace)
|
||||||
const runStyle = [
|
|
||||||
run.color ? `color:#${run.color}` : '',
|
|
||||||
run.bold ? 'font-weight:700' : '',
|
|
||||||
run.italic ? 'font-style:italic' : '',
|
|
||||||
run.underline ? 'text-decoration:underline' : '',
|
|
||||||
run.font || run.fontAscii
|
|
||||||
? `font-family:${
|
|
||||||
run.font && run.fontAscii
|
|
||||||
? cssDualFontFamily(run.fontAscii, run.font)
|
|
||||||
: cssFontFamily((run.font ?? run.fontAscii)!)
|
|
||||||
}`
|
|
||||||
: '',
|
|
||||||
run.sizeHalfPoints ? `font-size:${run.sizeHalfPoints / 2}pt` : '',
|
|
||||||
]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join(';')
|
|
||||||
return runStyle ? ['span', { style: runStyle }, run.text] : ['span', {}, run.text]
|
|
||||||
})
|
|
||||||
const pStyles = [
|
const pStyles = [
|
||||||
para.align ? `text-align:${para.align}` : '',
|
para.align ? `text-align:${para.align}` : '',
|
||||||
para.lineSpacing ? `line-height:${para.lineSpacing * 1.2}` : '',
|
para.lineSpacing ? `line-height:${para.lineSpacing * 1.2}` : '',
|
||||||
@@ -563,14 +614,48 @@ export function renderTableSpec(model: TableModel): DomSpec {
|
|||||||
if (style) tdAttrs.style = style
|
if (style) tdAttrs.style = style
|
||||||
if (cell.colSpan && cell.colSpan > 1) tdAttrs.colspan = String(cell.colSpan)
|
if (cell.colSpan && cell.colSpan > 1) tdAttrs.colspan = String(cell.colSpan)
|
||||||
if (rowSpan > 1) tdAttrs.rowspan = String(rowSpan)
|
if (rowSpan > 1) tdAttrs.rowspan = String(rowSpan)
|
||||||
|
// run-level styles preserved; <br> separators keep innerText \n-split
|
||||||
|
// semantics that nested-table edit write-back depends on
|
||||||
|
const paraBlocks: unknown[][] = cell.richParas?.length
|
||||||
|
? cell.richParas.map((p) => [
|
||||||
|
...runSpansWithPads(
|
||||||
|
p.runs.filter((run) => run.text !== ''),
|
||||||
|
p.autoSpace,
|
||||||
|
),
|
||||||
|
])
|
||||||
|
: cell.paras.map((p) => (p === '' ? [] : [...padSegments(p)]))
|
||||||
|
// nested tables spliced in at their paragraph anchors (cells with them are never editable)
|
||||||
|
const nested = cell.nestedTables ?? []
|
||||||
|
const anchorOf = (i: number) =>
|
||||||
|
Math.min(cell.nestedTableAnchors?.[i] ?? paraBlocks.length, paraBlocks.length)
|
||||||
const content: unknown[] = []
|
const content: unknown[] = []
|
||||||
cell.paras.forEach((p, i) => {
|
let ni = 0
|
||||||
if (i > 0) content.push(['br', {}])
|
let lastWasTable = false
|
||||||
if (p !== '') content.push(p)
|
paraBlocks.forEach((blk, pi) => {
|
||||||
|
while (ni < nested.length && anchorOf(ni) <= pi) {
|
||||||
|
content.push(renderTableSpec(nested[ni++]))
|
||||||
|
lastWasTable = true
|
||||||
|
}
|
||||||
|
if (pi > 0 && !lastWasTable) content.push(['br', {}])
|
||||||
|
content.push(...blk)
|
||||||
|
lastWasTable = false
|
||||||
})
|
})
|
||||||
for (const nt of cell.nestedTables ?? []) content.push(renderTableSpec(nt))
|
while (ni < nested.length) content.push(renderTableSpec(nested[ni++]))
|
||||||
if (content.length === 0) content.push('\u00a0')
|
if (content.length === 0) content.push('\u00a0')
|
||||||
tds.push(['td', tdAttrs, ...content])
|
const clip = cellClipTwips(model, ri, cell, rowSpan)
|
||||||
|
if (clip !== null) {
|
||||||
|
tds.push([
|
||||||
|
'td',
|
||||||
|
tdAttrs,
|
||||||
|
[
|
||||||
|
'div',
|
||||||
|
{ class: 'cell-clip', style: cellClipStyle(cell.vAlign ?? null, clip) },
|
||||||
|
...content,
|
||||||
|
],
|
||||||
|
])
|
||||||
|
} else {
|
||||||
|
tds.push(['td', tdAttrs, ...content])
|
||||||
|
}
|
||||||
})
|
})
|
||||||
const trAttrs: Record<string, string> = {}
|
const trAttrs: Record<string, string> = {}
|
||||||
const rh = model.rowHeightsTwips?.[ri]
|
const rh = model.rowHeightsTwips?.[ri]
|
||||||
|
|||||||
@@ -182,7 +182,7 @@ export async function loadFile(
|
|||||||
try {
|
try {
|
||||||
const parsed = await parseDocx(new Uint8Array(result.data))
|
const parsed = await parseDocx(new Uint8Array(result.data))
|
||||||
ctx.editor.storage.listNumbering.defs = parsed.numbering
|
ctx.editor.storage.listNumbering.defs = parsed.numbering
|
||||||
ctx.editor.commands.setContent(blocksToPmDoc(parsed.blocks) as never)
|
ctx.editor.commands.setContent(blocksToPmDoc(parsed.blocks, readSections(parsed)) as never)
|
||||||
resetEditorHistory(ctx.editor)
|
resetEditorHistory(ctx.editor)
|
||||||
noteDocumentSwapped()
|
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 })
|
||||||
@@ -270,7 +270,7 @@ export async function newFile(ctx: FileActionContext): Promise<boolean | undefin
|
|||||||
const bytes = await buildBlankDocx({ eastAsiaFont: defaultEastAsiaFontFor(getLang()) })
|
const bytes = await buildBlankDocx({ eastAsiaFont: defaultEastAsiaFontFor(getLang()) })
|
||||||
const parsed = await parseDocx(bytes)
|
const parsed = await parseDocx(bytes)
|
||||||
ctx.editor.storage.listNumbering.defs = parsed.numbering
|
ctx.editor.storage.listNumbering.defs = parsed.numbering
|
||||||
ctx.editor.commands.setContent(blocksToPmDoc(parsed.blocks) as never)
|
ctx.editor.commands.setContent(blocksToPmDoc(parsed.blocks, readSections(parsed)) as never)
|
||||||
resetEditorHistory(ctx.editor)
|
resetEditorHistory(ctx.editor)
|
||||||
noteDocumentSwapped()
|
noteDocumentSwapped()
|
||||||
ctx.setDoc({ parsed, filePath: null, fileName: t('appUntitledDocx'), hash: '', isBlank: true })
|
ctx.setDoc({ parsed, filePath: null, fileName: t('appUntitledDocx'), hash: '', isBlank: true })
|
||||||
@@ -607,7 +607,7 @@ async function saveOnce(ctx: FileActionContext, saveAs: boolean, auto: boolean):
|
|||||||
// Reload from saved bytes so docxIndex anchors point at the new file.
|
// Reload from saved bytes so docxIndex anchors point at the new file.
|
||||||
const reparsed = await parseDocx(bytes)
|
const reparsed = await parseDocx(bytes)
|
||||||
editor.storage.listNumbering.defs = reparsed.numbering
|
editor.storage.listNumbering.defs = reparsed.numbering
|
||||||
const rebasedPm = blocksToPmDoc(reparsed.blocks)
|
const rebasedPm = blocksToPmDoc(reparsed.blocks, readSections(reparsed))
|
||||||
let unchanged = false
|
let unchanged = false
|
||||||
try {
|
try {
|
||||||
unchanged = editor.state.doc.eq(editor.schema.nodeFromJSON(rebasedPm))
|
unchanged = editor.state.doc.eq(editor.schema.nodeFromJSON(rebasedPm))
|
||||||
|
|||||||
@@ -1,17 +1,5 @@
|
|||||||
import type { ParsedDoc } from '@genoffice/docx-engine'
|
import type { ParsedDoc } from '@genoffice/docx-engine'
|
||||||
import { cssFontFamily } from './line-metrics'
|
import { BUNDLED_FONTS, cssFontFamily, isBundledFont } from './line-metrics'
|
||||||
|
|
||||||
/** bundled web fonts (fonts.css) — always "available" but they are the
|
|
||||||
* one-size-fits-all fallback, so landing on them still counts as a miss */
|
|
||||||
const BUNDLED = new Set([
|
|
||||||
'Noto Sans CJK SC',
|
|
||||||
'Noto Serif CJK SC',
|
|
||||||
'Carlito',
|
|
||||||
'Caladea',
|
|
||||||
'Liberation Serif',
|
|
||||||
'Liberation Sans',
|
|
||||||
'Liberation Mono',
|
|
||||||
])
|
|
||||||
|
|
||||||
const GENERIC = new Set(['serif', 'sans-serif', 'monospace'])
|
const GENERIC = new Set(['serif', 'sans-serif', 'monospace'])
|
||||||
|
|
||||||
@@ -58,6 +46,41 @@ function fontAvailableIn(cx: CanvasRenderingContext2D, family: string): boolean
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const symbolCoverCache = new Map<string, boolean>()
|
||||||
|
/** outside the F020-F0FF range every symbol-encoded legacy font maps, so this always draws .notdef */
|
||||||
|
const PUA_TOFU = '\uE000'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Family installed AND covering every char of text — macOS ships a Symbol.ttf
|
||||||
|
* without the F0xx cmap. An uncovered PUA char renders the stack's .notdef
|
||||||
|
* (whose metrics differ from any other stack's), so the only reliable probe is
|
||||||
|
* comparing against a known .notdef in the same stack.
|
||||||
|
*/
|
||||||
|
export function symbolFontCovers(family: string, text: string): boolean {
|
||||||
|
const key = `${family}\u0000${text}`
|
||||||
|
const hit = symbolCoverCache.get(key)
|
||||||
|
if (hit !== undefined) return hit
|
||||||
|
const cx = ctx2d()
|
||||||
|
let covers = false
|
||||||
|
if (cx) {
|
||||||
|
cx.font = `32px "${family.replace(/"/g, '')}"`
|
||||||
|
const metrics = (s: string): string => {
|
||||||
|
const m = cx.measureText(s)
|
||||||
|
return [
|
||||||
|
m.width,
|
||||||
|
m.actualBoundingBoxLeft,
|
||||||
|
m.actualBoundingBoxRight,
|
||||||
|
m.actualBoundingBoxAscent,
|
||||||
|
m.actualBoundingBoxDescent,
|
||||||
|
].join()
|
||||||
|
}
|
||||||
|
const tofu = metrics(PUA_TOFU)
|
||||||
|
covers = [...text].every((ch) => ch <= ' ' || metrics(ch) !== tofu)
|
||||||
|
}
|
||||||
|
symbolCoverCache.set(key, covers)
|
||||||
|
return covers
|
||||||
|
}
|
||||||
|
|
||||||
export interface FontSubstitution {
|
export interface FontSubstitution {
|
||||||
name: string
|
name: string
|
||||||
/** first available family in the fallback chain, null = only bundled fallback left */
|
/** first available family in the fallback chain, null = only bundled fallback left */
|
||||||
@@ -74,12 +97,13 @@ export function checkMissingFonts(names: string[]): FontSubstitution[] {
|
|||||||
if (!cx) return []
|
if (!cx) return []
|
||||||
const out: FontSubstitution[] = []
|
const out: FontSubstitution[] = []
|
||||||
for (const name of names) {
|
for (const name of names) {
|
||||||
if (fontAvailableIn(cx, name)) continue
|
// a declared bundled face resolves in canvas yet still renders the subset fallback — report it
|
||||||
|
if (!isBundledFont(name) && fontAvailableIn(cx, name)) continue
|
||||||
const chain = cssFontFamily(name)
|
const chain = cssFontFamily(name)
|
||||||
.split(',')
|
.split(',')
|
||||||
.map((s) => s.trim().replace(/^'|'$/g, ''))
|
.map((s) => s.trim().replace(/^'|'$/g, ''))
|
||||||
.filter((c) => c !== name && !GENERIC.has(c))
|
.filter((c) => c !== name && !GENERIC.has(c))
|
||||||
const substitute = chain.find((c) => !BUNDLED.has(c) && fontAvailableIn(cx, c)) ?? null
|
const substitute = chain.find((c) => !BUNDLED_FONTS.has(c) && fontAvailableIn(cx, c)) ?? null
|
||||||
out.push({ name, substitute })
|
out.push({ name, substitute })
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -7,12 +7,17 @@ freely redistributable with the app. Licenses: Carlito and Liberation are
|
|||||||
|
|
||||||
| Font | License | Metric-compatible Word counterpart |
|
| Font | License | Metric-compatible Word counterpart |
|
||||||
| ---------------- | ---------- | ---------------------------------- |
|
| ---------------- | ---------- | ---------------------------------- |
|
||||||
| Carlito | OFL 1.1 | Calibri (Word's default body font) |
|
| Carlito GO | OFL 1.1 | Calibri (Word's default body font) |
|
||||||
| Caladea | Apache-2.0 | Cambria |
|
| Caladea | Apache-2.0 | Cambria |
|
||||||
| Liberation Serif | OFL 1.1 | Times New Roman |
|
| Liberation Serif | OFL 1.1 | Times New Roman |
|
||||||
| Liberation Sans | OFL 1.1 | Arial |
|
| Liberation Sans | OFL 1.1 | Arial |
|
||||||
| Liberation Mono | OFL 1.1 | Courier New |
|
| Liberation Mono | OFL 1.1 | Courier New |
|
||||||
|
|
||||||
|
"Carlito GO" (`Carlito-*.ttf`) is a derivative of Carlito 1.103: a build-time patch
|
||||||
|
(`tools/patch-carlito-vi.py`) rebuilds Vietnamese precomposed glyphs whose above mark
|
||||||
|
(circumflex/breve) was dropped (Ậ/Ệ/Ộ in Regular/Bold); advance widths are unchanged.
|
||||||
|
Renamed per OFL 1.1 §2 — "Carlito" is a Reserved Font Name.
|
||||||
|
|
||||||
Purpose: when a Word font declared by the document is missing on this machine, the
|
Purpose: when a Word font declared by the document is missing on this machine, the
|
||||||
browser's silent fallback (Helvetica etc.) changes glyph widths, so line-break points
|
browser's silent fallback (Helvetica etc.) changes glyph widths, so line-break points
|
||||||
and pagination diverge from Word. Falling back to a metric-compatible font keeps
|
and pagination diverge from Word. Falling back to a metric-compatible font keeps
|
||||||
@@ -34,3 +39,49 @@ forms + basic Latin
|
|||||||
(`pyftsubset --text-file=gb2312 --unicodes="U+0020-024F,U+2000-206F,U+3000-303F,U+FF00-FFEF" --flavor=woff2`).
|
(`pyftsubset --text-file=gb2312 --unicodes="U+0020-024F,U+2000-206F,U+3000-303F,U+FF00-FFEF" --flavor=woff2`).
|
||||||
Rare characters outside the subset still fall through to system fonts (shown as
|
Rare characters outside the subset still fall through to system fonts (shown as
|
||||||
missing glyphs in minimal environments); bold is synthesized by the browser.
|
missing glyphs in minimal environments); bold is synthesized by the browser.
|
||||||
|
|
||||||
|
The serif subset also backs the `GenOffice Fullwidth TC` face (`fonts.css`), a
|
||||||
|
unicode-range shim (U+FF0D/FF0F/FF3C/FF3F/FF5E) slotted before Songti TC in the
|
||||||
|
Traditional Chinese serif chain: Songti TC draws those fullwidth glyphs at
|
||||||
|
~0.2-0.5em of ink inside the 1em advance, so a PMingLiU document's U+FF0F
|
||||||
|
rendered as a spaced half-width slash. Real PMingLiU (Windows) still wins by
|
||||||
|
chain order; advances are 1.0em everywhere, so line breaking is unchanged.
|
||||||
|
|
||||||
|
## Korean fallback
|
||||||
|
|
||||||
|
| Font | Role |
|
||||||
|
| --------------------------------- | ------------------------------------------------ |
|
||||||
|
| GenOffice Serif KR (subset woff2) | Batang-metric stand-in for Korean serif families |
|
||||||
|
| GenOffice Sans KR (subset woff2) | fallback for Korean sans families (Malgun etc.) |
|
||||||
|
|
||||||
|
Source: Noto Serif/Sans CJK KR Regular from [notofonts/noto-cjk](https://github.com/notofonts/noto-cjk)
|
||||||
|
(SIL OFL 1.1), subset with fonttools to the 2,350 KS X 1001 syllables + jamo
|
||||||
|
(U+1100-11FF, U+3130-318F) + basic Latin/CJK punctuation/fullwidth forms
|
||||||
|
(`U+0020-024F,U+2000-206F,U+3000-303F,U+FF00-FFEF`), then hmtx-normalized to the
|
||||||
|
metrics of the Windows faces Word substitutes for missing Korean fonts: hangul
|
||||||
|
syllables/compatibility jamo → 1.0em (Noto CJK KR ships 0.92/0.966em, which
|
||||||
|
would shift line breaks ~8% vs Word), serif digits → 0.596em and space →
|
||||||
|
0.333em (measured Batang values), sans Basic Latin (U+0020-007E, U+00A0) →
|
||||||
|
measured Malgun Gothic advances (space 0.352em, digits 0.551em; Noto's 0.224em
|
||||||
|
space alone drifted Korean sans line breaks ~3%/line —
|
||||||
|
`tools/normalize-kr-sans-hmtx.py`, asserted by `tests/kr-font-metrics.test.ts`).
|
||||||
|
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`.
|
||||||
|
|
||||||
|
## Arabic fallback
|
||||||
|
|
||||||
|
| Font | Role |
|
||||||
|
| -------------------------------- | -------------------------------------------------------- |
|
||||||
|
| Noto Naskh Arabic (subset woff2) | fallback for naskh/serif-class Arabic families (default) |
|
||||||
|
| Noto Sans Arabic (subset woff2) | fallback for kufi/sans-class Arabic families |
|
||||||
|
|
||||||
|
Source: Noto Naskh/Sans Arabic Regular from [notofonts/arabic](https://github.com/notofonts/arabic)
|
||||||
|
(SIL OFL 1.1), subset with fonttools to the Arabic blocks + presentation forms +
|
||||||
|
digits/punctuation, keeping all shaping features
|
||||||
|
(`pyftsubset --unicodes="U+0020-024F,U+0600-06FF,U+0750-077F,U+08A0-08FF,U+FB50-FDFF,U+FE70-FEFF,U+2000-206F" --layout-features='*' --flavor=woff2`).
|
||||||
|
Names are kept ("Noto ..."): glyphs and advances are unmodified, so the OFL
|
||||||
|
Reserved Font Name clause does not apply. The upstream fonts carry no Latin
|
||||||
|
letters (only digits/punctuation); Latin text in a cs-font run falls through to
|
||||||
|
the rest of the chain. Word substitutes a missing Arabic font with a naskh-style
|
||||||
|
serif, so unknown Arabic families default to the Naskh chain.
|
||||||
|
|||||||
@@ -9,26 +9,28 @@
|
|||||||
* the offline pagination model (lo-fonts measures the same set of files).
|
* the offline pagination model (lo-fonts measures the same set of files).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/* "Carlito GO": Carlito with Vietnamese stacked diacritics fixed at build time
|
||||||
|
(tools/patch-carlito-vi.py); renamed per OFL Reserved Font Name clause */
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'Carlito';
|
font-family: 'Carlito GO';
|
||||||
src: url('./Carlito-Regular.ttf');
|
src: url('./Carlito-Regular.ttf');
|
||||||
font-weight: normal;
|
font-weight: normal;
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
}
|
}
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'Carlito';
|
font-family: 'Carlito GO';
|
||||||
src: url('./Carlito-Bold.ttf');
|
src: url('./Carlito-Bold.ttf');
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
}
|
}
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'Carlito';
|
font-family: 'Carlito GO';
|
||||||
src: url('./Carlito-Italic.ttf');
|
src: url('./Carlito-Italic.ttf');
|
||||||
font-weight: normal;
|
font-weight: normal;
|
||||||
font-style: italic;
|
font-style: italic;
|
||||||
}
|
}
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: 'Carlito';
|
font-family: 'Carlito GO';
|
||||||
src: url('./Carlito-BoldItalic.ttf');
|
src: url('./Carlito-BoldItalic.ttf');
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
font-style: italic;
|
font-style: italic;
|
||||||
@@ -152,3 +154,111 @@
|
|||||||
font-weight: normal;
|
font-weight: normal;
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Korean fallback: Noto Sans/Serif CJK KR subsets (KS X 1001 syllables + jamo),
|
||||||
|
* renamed per OFL since advances are normalized to the Windows faces Word
|
||||||
|
* substitutes (Batang/Malgun): hangul 1.0em; serif digits/space match Batang;
|
||||||
|
* sans Basic Latin matches Malgun (tools/normalize-kr-sans-hmtx.py).
|
||||||
|
*/
|
||||||
|
@font-face {
|
||||||
|
font-family: 'GenOffice Sans KR';
|
||||||
|
src: url('./GenOfficeSansKR-Regular-subset.woff2') format('woff2');
|
||||||
|
font-weight: normal;
|
||||||
|
font-style: normal;
|
||||||
|
}
|
||||||
|
@font-face {
|
||||||
|
font-family: 'GenOffice Serif KR';
|
||||||
|
src: url('./GenOfficeSerifKR-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
|
||||||
|
* fall through to the CJK/generic tail and Chromium picks a Geeza Pro-style UI
|
||||||
|
* face — larger and heavier than the naskh serif Word substitutes.
|
||||||
|
*/
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Noto Naskh Arabic';
|
||||||
|
src: url('./NotoNaskhArabic-Regular-subset.woff2') format('woff2');
|
||||||
|
font-weight: normal;
|
||||||
|
font-style: normal;
|
||||||
|
}
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Noto Sans Arabic';
|
||||||
|
src: url('./NotoSansArabic-Regular-subset.woff2') format('woff2');
|
||||||
|
font-weight: normal;
|
||||||
|
font-style: normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* macOS's PMingLiU stand-in (Songti TC) draws these fullwidth glyphs at
|
||||||
|
* ~0.2-0.5em of ink inside the 1em advance — U+FF0F looks like a spaced
|
||||||
|
* half-width slash. Serve them from the bundled Noto subset (ink matches
|
||||||
|
* PMingLiU); real PMingLiU still precedes this face in the TC serif chain. */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'GenOffice Fullwidth TC';
|
||||||
|
src: url('./NotoSerifCJKsc-Regular-subset.woff2') format('woff2');
|
||||||
|
unicode-range: U+FF0D, U+FF0F, U+FF3C, U+FF3F, U+FF5E;
|
||||||
|
font-weight: normal;
|
||||||
|
font-style: normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* macOS Chromium refuses to synthesize bold for 'Songti SC' requested by family
|
||||||
|
* name at weight 600/700 (only 900 selects Black). This local() alias, registered
|
||||||
|
* at weight normal only, forces Blink to synthesize bold at >=600. On Windows the
|
||||||
|
* local() sources don't resolve and the chain falls through to SimSun. */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'GenOffice Songti SC';
|
||||||
|
src: local('STSongti-SC-Regular'), local('Songti SC Regular');
|
||||||
|
font-weight: normal;
|
||||||
|
font-style: normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Superscript/subscript digits are outside the KR subsets and would fall
|
||||||
|
* through to AppleMyungjo, whose U+2082 is a full-width (1.0em) glyph —
|
||||||
|
* "Cu₂O" rendered as "Cu₂ O". Serve them from bundled latin faces instead. */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'GenOffice Sans KR';
|
||||||
|
src: url('./Carlito-Regular.ttf') format('truetype');
|
||||||
|
unicode-range: U+2070-209F, U+00B2-00B3, U+00B9;
|
||||||
|
font-weight: normal;
|
||||||
|
font-style: normal;
|
||||||
|
}
|
||||||
|
@font-face {
|
||||||
|
font-family: 'GenOffice Serif KR';
|
||||||
|
/* Carlito, not Caladea/LiberationSerif: only Carlito covers the whole block */
|
||||||
|
src: url('./Carlito-Regular.ttf') format('truetype');
|
||||||
|
unicode-range: U+2070-209F, U+00B2-00B3, U+00B9;
|
||||||
|
font-weight: normal;
|
||||||
|
font-style: normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Same for the Cambria→Caladea chain and the CJK SC subsets: none covers the
|
||||||
|
* sub/superscript block, so BaSO₄ falls to a system symbol font (small, dark
|
||||||
|
* glyphs). Ranges list only codepoints the substitute face actually has (and
|
||||||
|
* skip glyphs the base face covers itself, e.g. Caladea's ²³¹ⁿ), so everything
|
||||||
|
* else keeps today's fallback. Liberation Serif for the serif faces (style
|
||||||
|
* match), Carlito for the sans one. Normal weight only, like the KR fix. */
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Caladea';
|
||||||
|
src: url('./LiberationSerif-Regular.ttf') format('truetype');
|
||||||
|
unicode-range: U+2074-2079, U+2080-2094;
|
||||||
|
font-weight: normal;
|
||||||
|
font-style: normal;
|
||||||
|
}
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Noto Serif CJK SC';
|
||||||
|
src: url('./LiberationSerif-Regular.ttf') format('truetype');
|
||||||
|
unicode-range: U+2074-2079, U+207F, U+2080-2094;
|
||||||
|
font-weight: normal;
|
||||||
|
font-style: normal;
|
||||||
|
}
|
||||||
|
@font-face {
|
||||||
|
font-family: 'Noto Sans CJK SC';
|
||||||
|
src: url('./Carlito-Regular.ttf') format('truetype');
|
||||||
|
unicode-range: U+2070-2071, U+2074-2094;
|
||||||
|
font-weight: normal;
|
||||||
|
font-style: normal;
|
||||||
|
}
|
||||||
|
|||||||
@@ -31,6 +31,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBg: '去除背景',
|
ribbonRemoveBg: '去除背景',
|
||||||
ribbonRemoveBgTip: '去除背景:基于颜色容差抠图(替换为透明 PNG)',
|
ribbonRemoveBgTip: '去除背景:基于颜色容差抠图(替换为透明 PNG)',
|
||||||
ribbonCrop: '裁剪',
|
ribbonCrop: '裁剪',
|
||||||
|
ribbonRotateRight: '向右旋转 90°',
|
||||||
|
ribbonRotateLeft: '向左旋转 90°',
|
||||||
|
ribbonFlipH: '水平翻转',
|
||||||
|
ribbonFlipV: '垂直翻转',
|
||||||
ribbonCropTip: '裁剪图片(拖动手柄,Enter 确认)',
|
ribbonCropTip: '裁剪图片(拖动手柄,Enter 确认)',
|
||||||
ribbonCropHint: '拖动手柄或在框内拖动选择保留区域;Enter 应用,Esc 取消',
|
ribbonCropHint: '拖动手柄或在框内拖动选择保留区域;Enter 应用,Esc 取消',
|
||||||
ribbonReplacePicture: '替换图片',
|
ribbonReplacePicture: '替换图片',
|
||||||
@@ -696,6 +700,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBgTip:
|
ribbonRemoveBgTip:
|
||||||
'Remove background: color-tolerance cutout (replaced with a transparent PNG)',
|
'Remove background: color-tolerance cutout (replaced with a transparent PNG)',
|
||||||
ribbonCrop: 'Crop',
|
ribbonCrop: 'Crop',
|
||||||
|
ribbonRotateRight: 'Rotate Right 90°',
|
||||||
|
ribbonRotateLeft: 'Rotate Left 90°',
|
||||||
|
ribbonFlipH: 'Flip Horizontal',
|
||||||
|
ribbonFlipV: 'Flip Vertical',
|
||||||
ribbonCropTip: 'Crop the picture (drag the handles, Enter to confirm)',
|
ribbonCropTip: 'Crop the picture (drag the handles, Enter to confirm)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'Drag the handles or move the box to choose the area to keep; Enter to apply, Esc to cancel',
|
'Drag the handles or move the box to choose the area to keep; Enter to apply, Esc to cancel',
|
||||||
@@ -1353,6 +1361,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBg: '背景の削除',
|
ribbonRemoveBg: '背景の削除',
|
||||||
ribbonRemoveBgTip: '背景の削除:色の許容差に基づく切り抜き(透明 PNG に置き換え)',
|
ribbonRemoveBgTip: '背景の削除:色の許容差に基づく切り抜き(透明 PNG に置き換え)',
|
||||||
ribbonCrop: 'トリミング',
|
ribbonCrop: 'トリミング',
|
||||||
|
ribbonRotateRight: '右へ90°回転',
|
||||||
|
ribbonRotateLeft: '左へ90°回転',
|
||||||
|
ribbonFlipH: '左右反転',
|
||||||
|
ribbonFlipV: '上下反転',
|
||||||
ribbonCropTip: '画像をトリミング(ハンドルをドラッグ、Enter で確定)',
|
ribbonCropTip: '画像をトリミング(ハンドルをドラッグ、Enter で確定)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'ハンドルをドラッグするか枠内を移動して残す範囲を選択。Enter で適用、Esc でキャンセル',
|
'ハンドルをドラッグするか枠内を移動して残す範囲を選択。Enter で適用、Esc でキャンセル',
|
||||||
@@ -2031,6 +2043,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBg: '배경 제거',
|
ribbonRemoveBg: '배경 제거',
|
||||||
ribbonRemoveBgTip: '배경 제거: 색 허용 오차 기반 추출(투명 PNG로 대체)',
|
ribbonRemoveBgTip: '배경 제거: 색 허용 오차 기반 추출(투명 PNG로 대체)',
|
||||||
ribbonCrop: '자르기',
|
ribbonCrop: '자르기',
|
||||||
|
ribbonRotateRight: '오른쪽으로 90° 회전',
|
||||||
|
ribbonRotateLeft: '왼쪽으로 90° 회전',
|
||||||
|
ribbonFlipH: '좌우 대칭',
|
||||||
|
ribbonFlipV: '상하 대칭',
|
||||||
ribbonCropTip: '그림 자르기(핸들을 끌고 Enter 키로 확인)',
|
ribbonCropTip: '그림 자르기(핸들을 끌고 Enter 키로 확인)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'핸들을 끌거나 상자를 이동해 유지할 영역을 선택하세요. Enter로 적용, Esc로 취소',
|
'핸들을 끌거나 상자를 이동해 유지할 영역을 선택하세요. Enter로 적용, Esc로 취소',
|
||||||
@@ -2707,6 +2723,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBgTip:
|
ribbonRemoveBgTip:
|
||||||
"Supprimer l'arrière-plan : détourage par tolérance de couleur (remplacé par un PNG transparent)",
|
"Supprimer l'arrière-plan : détourage par tolérance de couleur (remplacé par un PNG transparent)",
|
||||||
ribbonCrop: 'Rogner',
|
ribbonCrop: 'Rogner',
|
||||||
|
ribbonRotateRight: 'Rotation 90° à droite',
|
||||||
|
ribbonRotateLeft: 'Rotation 90° à gauche',
|
||||||
|
ribbonFlipH: 'Retourner horizontalement',
|
||||||
|
ribbonFlipV: 'Retourner verticalement',
|
||||||
ribbonCropTip: "Rogner l'image (faites glisser les poignées, Entrée pour confirmer)",
|
ribbonCropTip: "Rogner l'image (faites glisser les poignées, Entrée pour confirmer)",
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'Faites glisser les poignées ou déplacez le cadre pour choisir la zone à conserver ; Entrée pour appliquer, Échap pour annuler',
|
'Faites glisser les poignées ou déplacez le cadre pour choisir la zone à conserver ; Entrée pour appliquer, Échap pour annuler',
|
||||||
@@ -3375,6 +3395,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBgTip:
|
ribbonRemoveBgTip:
|
||||||
'Hintergrund entfernen: Freistellen per Farbtoleranz (durch transparentes PNG ersetzt)',
|
'Hintergrund entfernen: Freistellen per Farbtoleranz (durch transparentes PNG ersetzt)',
|
||||||
ribbonCrop: 'Zuschneiden',
|
ribbonCrop: 'Zuschneiden',
|
||||||
|
ribbonRotateRight: '90° nach rechts drehen',
|
||||||
|
ribbonRotateLeft: '90° nach links drehen',
|
||||||
|
ribbonFlipH: 'Horizontal spiegeln',
|
||||||
|
ribbonFlipV: 'Vertikal spiegeln',
|
||||||
ribbonCropTip: 'Bild zuschneiden (Ziehpunkte ziehen, Eingabetaste zum Bestätigen)',
|
ribbonCropTip: 'Bild zuschneiden (Ziehpunkte ziehen, Eingabetaste zum Bestätigen)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'Ziehpunkte ziehen oder Rahmen verschieben, um den zu behaltenden Bereich zu wählen; Eingabetaste zum Anwenden, Esc zum Abbrechen',
|
'Ziehpunkte ziehen oder Rahmen verschieben, um den zu behaltenden Bereich zu wählen; Eingabetaste zum Anwenden, Esc zum Abbrechen',
|
||||||
@@ -4043,6 +4067,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBgTip:
|
ribbonRemoveBgTip:
|
||||||
'Quitar fondo: recorte por tolerancia de color (reemplazado por un PNG transparente)',
|
'Quitar fondo: recorte por tolerancia de color (reemplazado por un PNG transparente)',
|
||||||
ribbonCrop: 'Recortar',
|
ribbonCrop: 'Recortar',
|
||||||
|
ribbonRotateRight: 'Girar 90° a la derecha',
|
||||||
|
ribbonRotateLeft: 'Girar 90° a la izquierda',
|
||||||
|
ribbonFlipH: 'Voltear horizontalmente',
|
||||||
|
ribbonFlipV: 'Voltear verticalmente',
|
||||||
ribbonCropTip: 'Recortar la imagen (arrastre los controladores, Entrar para confirmar)',
|
ribbonCropTip: 'Recortar la imagen (arrastre los controladores, Entrar para confirmar)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'Arrastre los controladores o mueva el cuadro para elegir el área que desea conservar; Entrar para aplicar, Esc para cancelar',
|
'Arrastre los controladores o mueva el cuadro para elegir el área que desea conservar; Entrar para aplicar, Esc para cancelar',
|
||||||
@@ -4713,6 +4741,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBg: 'เอาพื้นหลังออก',
|
ribbonRemoveBg: 'เอาพื้นหลังออก',
|
||||||
ribbonRemoveBgTip: 'เอาพื้นหลังออก: ตัดภาพตามค่าความคลาดเคลื่อนของสี (แทนที่ด้วย PNG โปร่งใส)',
|
ribbonRemoveBgTip: 'เอาพื้นหลังออก: ตัดภาพตามค่าความคลาดเคลื่อนของสี (แทนที่ด้วย PNG โปร่งใส)',
|
||||||
ribbonCrop: 'ครอบตัด',
|
ribbonCrop: 'ครอบตัด',
|
||||||
|
ribbonRotateRight: 'หมุนขวา 90°',
|
||||||
|
ribbonRotateLeft: 'หมุนซ้าย 90°',
|
||||||
|
ribbonFlipH: 'พลิกแนวนอน',
|
||||||
|
ribbonFlipV: 'พลิกแนวตั้ง',
|
||||||
ribbonCropTip: 'ครอบตัดรูปภาพ (ลากจุดจับ กด Enter เพื่อยืนยัน)',
|
ribbonCropTip: 'ครอบตัดรูปภาพ (ลากจุดจับ กด Enter เพื่อยืนยัน)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'ลากจุดจับหรือย้ายกรอบเพื่อเลือกพื้นที่ที่จะเก็บไว้ กด Enter เพื่อนำไปใช้ Esc เพื่อยกเลิก',
|
'ลากจุดจับหรือย้ายกรอบเพื่อเลือกพื้นที่ที่จะเก็บไว้ กด Enter เพื่อนำไปใช้ Esc เพื่อยกเลิก',
|
||||||
@@ -5366,6 +5398,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBgTip:
|
ribbonRemoveBgTip:
|
||||||
'Hapus latar belakang: pemotongan berdasarkan toleransi warna (diganti dengan PNG transparan)',
|
'Hapus latar belakang: pemotongan berdasarkan toleransi warna (diganti dengan PNG transparan)',
|
||||||
ribbonCrop: 'Pangkas',
|
ribbonCrop: 'Pangkas',
|
||||||
|
ribbonRotateRight: 'Putar Kanan 90°',
|
||||||
|
ribbonRotateLeft: 'Putar Kiri 90°',
|
||||||
|
ribbonFlipH: 'Balik Horizontal',
|
||||||
|
ribbonFlipV: 'Balik Vertikal',
|
||||||
ribbonCropTip: 'Pangkas gambar (seret gagang, Enter untuk mengonfirmasi)',
|
ribbonCropTip: 'Pangkas gambar (seret gagang, Enter untuk mengonfirmasi)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'Seret gagang atau pindahkan kotak untuk memilih area yang dipertahankan; Enter untuk menerapkan, Esc untuk membatalkan',
|
'Seret gagang atau pindahkan kotak untuk memilih area yang dipertahankan; Enter untuk menerapkan, Esc untuk membatalkan',
|
||||||
@@ -6026,6 +6062,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBg: 'Удалить фон',
|
ribbonRemoveBg: 'Удалить фон',
|
||||||
ribbonRemoveBgTip: 'Удалить фон: вырезание по допуску цвета (заменяется прозрачным PNG)',
|
ribbonRemoveBgTip: 'Удалить фон: вырезание по допуску цвета (заменяется прозрачным PNG)',
|
||||||
ribbonCrop: 'Обрезка',
|
ribbonCrop: 'Обрезка',
|
||||||
|
ribbonRotateRight: 'Повернуть вправо на 90°',
|
||||||
|
ribbonRotateLeft: 'Повернуть влево на 90°',
|
||||||
|
ribbonFlipH: 'Отразить по горизонтали',
|
||||||
|
ribbonFlipV: 'Отразить по вертикали',
|
||||||
ribbonCropTip: 'Обрезать рисунок (перетащите маркеры, Enter — подтвердить)',
|
ribbonCropTip: 'Обрезать рисунок (перетащите маркеры, Enter — подтвердить)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'Перетащите маркеры или переместите рамку, чтобы выбрать сохраняемую область; Enter — применить, Esc — отмена',
|
'Перетащите маркеры или переместите рамку, чтобы выбрать сохраняемую область; Enter — применить, Esc — отмена',
|
||||||
@@ -6689,6 +6729,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBg: 'إزالة الخلفية',
|
ribbonRemoveBg: 'إزالة الخلفية',
|
||||||
ribbonRemoveBgTip: 'إزالة الخلفية: اقتصاص حسب تفاوت اللون (تُستبدل بصورة PNG شفافة)',
|
ribbonRemoveBgTip: 'إزالة الخلفية: اقتصاص حسب تفاوت اللون (تُستبدل بصورة PNG شفافة)',
|
||||||
ribbonCrop: 'اقتصاص',
|
ribbonCrop: 'اقتصاص',
|
||||||
|
ribbonRotateRight: 'تدوير لليمين 90 درجة',
|
||||||
|
ribbonRotateLeft: 'تدوير لليسار 90 درجة',
|
||||||
|
ribbonFlipH: 'انعكاس أفقي',
|
||||||
|
ribbonFlipV: 'انعكاس رأسي',
|
||||||
ribbonCropTip: 'اقتصاص الصورة (اسحب المقابض، Enter للتأكيد)',
|
ribbonCropTip: 'اقتصاص الصورة (اسحب المقابض، Enter للتأكيد)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'اسحب المقابض أو حرّك الإطار لاختيار المنطقة المراد الاحتفاظ بها؛ Enter للتطبيق وEsc للإلغاء',
|
'اسحب المقابض أو حرّك الإطار لاختيار المنطقة المراد الاحتفاظ بها؛ Enter للتطبيق وEsc للإلغاء',
|
||||||
@@ -7343,6 +7387,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBgTip:
|
ribbonRemoveBgTip:
|
||||||
'Remover plano de fundo: recorte por tolerância de cor (substituído por um PNG transparente)',
|
'Remover plano de fundo: recorte por tolerância de cor (substituído por um PNG transparente)',
|
||||||
ribbonCrop: 'Cortar',
|
ribbonCrop: 'Cortar',
|
||||||
|
ribbonRotateRight: 'Girar 90° para a direita',
|
||||||
|
ribbonRotateLeft: 'Girar 90° para a esquerda',
|
||||||
|
ribbonFlipH: 'Inverter horizontalmente',
|
||||||
|
ribbonFlipV: 'Inverter verticalmente',
|
||||||
ribbonCropTip: 'Cortar a imagem (arraste as alças, Enter para confirmar)',
|
ribbonCropTip: 'Cortar a imagem (arraste as alças, Enter para confirmar)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'Arraste as alças ou mova a caixa para escolher a área a manter; Enter para aplicar, Esc para cancelar',
|
'Arraste as alças ou mova a caixa para escolher a área a manter; Enter para aplicar, Esc para cancelar',
|
||||||
@@ -8004,6 +8052,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBgTip:
|
ribbonRemoveBgTip:
|
||||||
'Rimuovi sfondo: ritaglio in base alla tolleranza del colore (sostituito con un PNG trasparente)',
|
'Rimuovi sfondo: ritaglio in base alla tolleranza del colore (sostituito con un PNG trasparente)',
|
||||||
ribbonCrop: 'Ritaglia',
|
ribbonCrop: 'Ritaglia',
|
||||||
|
ribbonRotateRight: 'Ruota a destra di 90°',
|
||||||
|
ribbonRotateLeft: 'Ruota a sinistra di 90°',
|
||||||
|
ribbonFlipH: 'Capovolgi orizzontalmente',
|
||||||
|
ribbonFlipV: 'Capovolgi verticalmente',
|
||||||
ribbonCropTip: "Ritaglia l'immagine (trascina le maniglie, Invio per confermare)",
|
ribbonCropTip: "Ritaglia l'immagine (trascina le maniglie, Invio per confermare)",
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
"Trascina le maniglie o sposta il riquadro per scegliere l'area da mantenere; Invio per applicare, Esc per annullare",
|
"Trascina le maniglie o sposta il riquadro per scegliere l'area da mantenere; Invio per applicare, Esc per annullare",
|
||||||
@@ -8671,6 +8723,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBgTip:
|
ribbonRemoveBgTip:
|
||||||
'Usuń tło: wycinanie na podstawie tolerancji koloru (zastąpione przezroczystym plikiem PNG)',
|
'Usuń tło: wycinanie na podstawie tolerancji koloru (zastąpione przezroczystym plikiem PNG)',
|
||||||
ribbonCrop: 'Przytnij',
|
ribbonCrop: 'Przytnij',
|
||||||
|
ribbonRotateRight: 'Obróć w prawo o 90°',
|
||||||
|
ribbonRotateLeft: 'Obróć w lewo o 90°',
|
||||||
|
ribbonFlipH: 'Odbij w poziomie',
|
||||||
|
ribbonFlipV: 'Odbij w pionie',
|
||||||
ribbonCropTip: 'Przytnij obraz (przeciągnij uchwyty, Enter, aby potwierdzić)',
|
ribbonCropTip: 'Przytnij obraz (przeciągnij uchwyty, Enter, aby potwierdzić)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'Przeciągnij uchwyty lub przesuń ramkę, aby wybrać obszar do zachowania; Enter, aby zastosować, Esc, aby anulować',
|
'Przeciągnij uchwyty lub przesuń ramkę, aby wybrać obszar do zachowania; Enter, aby zastosować, Esc, aby anulować',
|
||||||
@@ -9333,6 +9389,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBgTip:
|
ribbonRemoveBgTip:
|
||||||
'Achtergrond verwijderen: uitsnijden op basis van kleurtolerantie (vervangen door een transparante PNG)',
|
'Achtergrond verwijderen: uitsnijden op basis van kleurtolerantie (vervangen door een transparante PNG)',
|
||||||
ribbonCrop: 'Bijsnijden',
|
ribbonCrop: 'Bijsnijden',
|
||||||
|
ribbonRotateRight: '90° rechtsom draaien',
|
||||||
|
ribbonRotateLeft: '90° linksom draaien',
|
||||||
|
ribbonFlipH: 'Horizontaal spiegelen',
|
||||||
|
ribbonFlipV: 'Verticaal spiegelen',
|
||||||
ribbonCropTip: 'De afbeelding bijsnijden (sleep de grepen, Enter om te bevestigen)',
|
ribbonCropTip: 'De afbeelding bijsnijden (sleep de grepen, Enter om te bevestigen)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'Sleep de grepen of verplaats het kader om het te behouden gebied te kiezen; Enter om toe te passen, Esc om te annuleren',
|
'Sleep de grepen of verplaats het kader om het te behouden gebied te kiezen; Enter om toe te passen, Esc om te annuleren',
|
||||||
@@ -9999,6 +10059,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBgTip:
|
ribbonRemoveBgTip:
|
||||||
'Alih keluar latar belakang: potongan berdasarkan toleransi warna (digantikan dengan PNG lutsinar)',
|
'Alih keluar latar belakang: potongan berdasarkan toleransi warna (digantikan dengan PNG lutsinar)',
|
||||||
ribbonCrop: 'Pangkas',
|
ribbonCrop: 'Pangkas',
|
||||||
|
ribbonRotateRight: 'Putar Kanan 90°',
|
||||||
|
ribbonRotateLeft: 'Putar Kiri 90°',
|
||||||
|
ribbonFlipH: 'Balikkan Melintang',
|
||||||
|
ribbonFlipV: 'Balikkan Menegak',
|
||||||
ribbonCropTip: 'Pangkas gambar (seret pemegang, Enter untuk mengesahkan)',
|
ribbonCropTip: 'Pangkas gambar (seret pemegang, Enter untuk mengesahkan)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'Seret pemegang atau alihkan kotak untuk memilih kawasan yang hendak dikekalkan; Enter untuk menggunakan, Esc untuk membatalkan',
|
'Seret pemegang atau alihkan kotak untuk memilih kawasan yang hendak dikekalkan; Enter untuk menggunakan, Esc untuk membatalkan',
|
||||||
@@ -10660,6 +10724,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBg: 'הסרת רקע',
|
ribbonRemoveBg: 'הסרת רקע',
|
||||||
ribbonRemoveBgTip: 'הסרת רקע: חיתוך לפי סבילות צבע (מוחלף ב-PNG שקוף)',
|
ribbonRemoveBgTip: 'הסרת רקע: חיתוך לפי סבילות צבע (מוחלף ב-PNG שקוף)',
|
||||||
ribbonCrop: 'חיתוך',
|
ribbonCrop: 'חיתוך',
|
||||||
|
ribbonRotateRight: 'סיבוב 90° ימינה',
|
||||||
|
ribbonRotateLeft: 'סיבוב 90° שמאלה',
|
||||||
|
ribbonFlipH: 'היפוך אופקי',
|
||||||
|
ribbonFlipV: 'היפוך אנכי',
|
||||||
ribbonCropTip: 'חיתוך התמונה (גרור את הידיות, Enter לאישור)',
|
ribbonCropTip: 'חיתוך התמונה (גרור את הידיות, Enter לאישור)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'גרור את הידיות או הזז את המסגרת כדי לבחור את האזור שיישמר; Enter להחלה, Esc לביטול',
|
'גרור את הידיות או הזז את המסגרת כדי לבחור את האזור שיישמר; Enter להחלה, Esc לביטול',
|
||||||
@@ -11310,6 +11378,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBgTip:
|
ribbonRemoveBgTip:
|
||||||
'पृष्ठभूमि हटाएँ: रंग सहनशीलता के आधार पर कटआउट (पारदर्शी PNG से बदला जाता है)',
|
'पृष्ठभूमि हटाएँ: रंग सहनशीलता के आधार पर कटआउट (पारदर्शी PNG से बदला जाता है)',
|
||||||
ribbonCrop: 'काट-छाँट करें',
|
ribbonCrop: 'काट-छाँट करें',
|
||||||
|
ribbonRotateRight: '90° दाएँ घुमाएँ',
|
||||||
|
ribbonRotateLeft: '90° बाएँ घुमाएँ',
|
||||||
|
ribbonFlipH: 'क्षैतिज पलटें',
|
||||||
|
ribbonFlipV: 'लंबवत पलटें',
|
||||||
ribbonCropTip: 'चित्र की काट-छाँट करें (हैंडल खींचें, पुष्टि के लिए Enter दबाएँ)',
|
ribbonCropTip: 'चित्र की काट-छाँट करें (हैंडल खींचें, पुष्टि के लिए Enter दबाएँ)',
|
||||||
ribbonCropHint:
|
ribbonCropHint:
|
||||||
'रखे जाने वाले क्षेत्र को चुनने के लिए हैंडल खींचें या बॉक्स को हिलाएँ; लागू करने के लिए Enter, रद्द करने के लिए Esc',
|
'रखे जाने वाले क्षेत्र को चुनने के लिए हैंडल खींचें या बॉक्स को हिलाएँ; लागू करने के लिए Enter, रद्द करने के लिए Esc',
|
||||||
@@ -11972,6 +12044,10 @@ export const ribbonStrings = defineStrings({
|
|||||||
ribbonRemoveBg: '移除背景',
|
ribbonRemoveBg: '移除背景',
|
||||||
ribbonRemoveBgTip: '移除背景:依色彩容許度去背(取代為透明 PNG)',
|
ribbonRemoveBgTip: '移除背景:依色彩容許度去背(取代為透明 PNG)',
|
||||||
ribbonCrop: '裁剪',
|
ribbonCrop: '裁剪',
|
||||||
|
ribbonRotateRight: '向右旋轉 90°',
|
||||||
|
ribbonRotateLeft: '向左旋轉 90°',
|
||||||
|
ribbonFlipH: '水平翻轉',
|
||||||
|
ribbonFlipV: '垂直翻轉',
|
||||||
ribbonCropTip: '裁剪圖片(拖曳控點,Enter 確認)',
|
ribbonCropTip: '裁剪圖片(拖曳控點,Enter 確認)',
|
||||||
ribbonCropHint: '拖曳控點或在框內拖曳以選擇保留區域;Enter 套用,Esc 取消',
|
ribbonCropHint: '拖曳控點或在框內拖曳以選擇保留區域;Enter 套用,Esc 取消',
|
||||||
ribbonReplacePicture: '取代圖片',
|
ribbonReplacePicture: '取代圖片',
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ export interface FontMetricsProvider {
|
|||||||
*/
|
*/
|
||||||
function charAdvanceEm(code: number): number {
|
function charAdvanceEm(code: number): number {
|
||||||
if (
|
if (
|
||||||
|
isHangul(code) ||
|
||||||
(code >= 0x3000 && code <= 0x30ff) ||
|
(code >= 0x3000 && code <= 0x30ff) ||
|
||||||
(code >= 0x3400 && code <= 0x9fff) ||
|
(code >= 0x3400 && code <= 0x9fff) ||
|
||||||
(code >= 0xf900 && code <= 0xfaff) ||
|
(code >= 0xf900 && code <= 0xfaff) ||
|
||||||
@@ -94,6 +95,10 @@ export class HeuristicMetrics implements FontMetricsProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Korean font names (Windows/Noto/Source Han/Nanum faces + bundled subsets) */
|
||||||
|
const KO_FONT_RE =
|
||||||
|
/malgun|맑은|batang|바탕|myeongjo|myungjo|명조|gungsuh|궁서|gulim|굴림|dotum|돋움|nanum|나눔|genoffice (sans|serif) kr|(noto|source han) (sans|serif)[^,]*\bk(r|orean)?\b/i
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Per-font line-height factor (based on measured Windows font metrics).
|
* Per-font line-height factor (based on measured Windows font metrics).
|
||||||
* PMingLiU/MingLiU: ~1.0em; SimSun and other Simplified fonts: ~1.3em; Western: 1.2em.
|
* PMingLiU/MingLiU: ~1.0em; SimSun and other Simplified fonts: ~1.3em; Western: 1.2em.
|
||||||
@@ -104,6 +109,12 @@ export function lineHeightFactor(fontFamily: string): number {
|
|||||||
if (f.includes('pmingliu') || f.includes('mingliu') || f.includes('細明體')) {
|
if (f.includes('pmingliu') || f.includes('mingliu') || f.includes('細明體')) {
|
||||||
return 1.0
|
return 1.0
|
||||||
}
|
}
|
||||||
|
// Korean faces: Word lays out East Asian auto line rule at winTotal × 1.3
|
||||||
|
// (probe-verified vs Word PDFs): Malgun 1.3301 × 1.3 ≈ 1.73, Batang/Gulim 1.0 × 1.3
|
||||||
|
if (KO_FONT_RE.test(f)) return /malgun|맑은/.test(f) ? 1.73 : 1.3
|
||||||
|
// Noto/Source Han SC declares substitute into the SimSun class when missing
|
||||||
|
// (bundled subsets count as missing), so they take the SimSun factor
|
||||||
|
if (/^(noto|source han) (sans|serif)( cjk)? ?(sc|cn)\b/.test(f)) return 1.3
|
||||||
// expanded Simplified Chinese fonts (SimSun/NSimSun/SimHei/FangSong/KaiTi/Microsoft YaHei)
|
// expanded Simplified Chinese fonts (SimSun/NSimSun/SimHei/FangSong/KaiTi/Microsoft YaHei)
|
||||||
if (
|
if (
|
||||||
f.includes('simsun') ||
|
f.includes('simsun') ||
|
||||||
@@ -114,6 +125,8 @@ export function lineHeightFactor(fontFamily: string): number {
|
|||||||
f.includes('kaiti') ||
|
f.includes('kaiti') ||
|
||||||
f.includes('microsoft yahei') ||
|
f.includes('microsoft yahei') ||
|
||||||
f.includes('microsoftyahei') ||
|
f.includes('microsoftyahei') ||
|
||||||
|
f.includes('dengxian') ||
|
||||||
|
f.includes('等线') ||
|
||||||
f.includes('simhei') ||
|
f.includes('simhei') ||
|
||||||
f.includes('simfang') ||
|
f.includes('simfang') ||
|
||||||
f.includes('simkai')
|
f.includes('simkai')
|
||||||
@@ -237,6 +250,28 @@ export function computeLineHeight(
|
|||||||
* measures a mixed-script sample against both generic fallbacks: a family that
|
* measures a mixed-script sample against both generic fallbacks: a family that
|
||||||
* changes neither width doesn't exist.
|
* changes neither width doesn't exist.
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* Bundled web fonts (fonts.css). The canvas probe resolves them, but they are
|
||||||
|
* last-resort subset faces, so substitution decisions treat them as missing.
|
||||||
|
*/
|
||||||
|
export const BUNDLED_FONTS = new Set([
|
||||||
|
'Noto Sans CJK SC',
|
||||||
|
'Noto Serif CJK SC',
|
||||||
|
'GenOffice Sans KR',
|
||||||
|
'GenOffice Serif KR',
|
||||||
|
'GenOffice Fullwidth TC',
|
||||||
|
'GenOffice Songti SC',
|
||||||
|
'Carlito GO',
|
||||||
|
'Caladea',
|
||||||
|
'Liberation Serif',
|
||||||
|
'Liberation Sans',
|
||||||
|
'Liberation Mono',
|
||||||
|
])
|
||||||
|
const BUNDLED_LC = new Set([...BUNDLED_FONTS].map((f) => f.toLowerCase()))
|
||||||
|
export function isBundledFont(name: string): boolean {
|
||||||
|
return BUNDLED_LC.has(name.toLowerCase())
|
||||||
|
}
|
||||||
|
|
||||||
const fontAvailableCache = new Map<string, boolean>()
|
const fontAvailableCache = new Map<string, boolean>()
|
||||||
export function isFontAvailable(font: string): boolean {
|
export function isFontAvailable(font: string): boolean {
|
||||||
if (typeof document === 'undefined') return false
|
if (typeof document === 'undefined') return false
|
||||||
@@ -271,7 +306,7 @@ export function cssFontFamily(font: string): string {
|
|||||||
// CJK fallback at chain end (GB2312 subset bundled in fonts.css): no tofu even without system Chinese fonts
|
// CJK fallback at chain end (GB2312 subset bundled in fonts.css): no tofu even without system Chinese fonts
|
||||||
const CJK_SERIF = 'Noto Serif CJK SC'
|
const CJK_SERIF = 'Noto Serif CJK SC'
|
||||||
const CJK_SANS = 'Noto Sans CJK SC'
|
const CJK_SANS = 'Noto Sans CJK SC'
|
||||||
if (f.includes('calibri')) return `${chain(font, 'Carlito', CJK_SANS)},sans-serif`
|
if (f.includes('calibri')) return `${chain(font, 'Carlito GO', CJK_SANS)},sans-serif`
|
||||||
if (f.includes('cambria') && !f.includes('math'))
|
if (f.includes('cambria') && !f.includes('math'))
|
||||||
return `${chain(font, 'Caladea', CJK_SERIF)},serif`
|
return `${chain(font, 'Caladea', CJK_SERIF)},serif`
|
||||||
if (f.includes('times')) return `${chain(font, 'Liberation Serif', CJK_SERIF)},serif`
|
if (f.includes('times')) return `${chain(font, 'Liberation Serif', CJK_SERIF)},serif`
|
||||||
@@ -286,8 +321,11 @@ export function cssFontFamily(font: string): string {
|
|||||||
f.includes('zhongsong')
|
f.includes('zhongsong')
|
||||||
)
|
)
|
||||||
return `${chain(font, 'STZhongsong', 'Songti SC', 'STSong', 'SimSun', CJK_SERIF)},serif`
|
return `${chain(font, 'STZhongsong', 'Songti SC', 'STSong', 'SimSun', CJK_SERIF)},serif`
|
||||||
|
// 'GenOffice Songti SC' (fonts.css local() alias of Songti SC): macOS Chromium
|
||||||
|
// refuses synthetic bold for 'Songti SC' by name at weight 600/700; the alias,
|
||||||
|
// registered weight-normal only, lets Blink synthesize. Unresolvable elsewhere.
|
||||||
if (f.includes('simsun') || f.includes('宋体') || f.includes('nsimsun')) {
|
if (f.includes('simsun') || f.includes('宋体') || f.includes('nsimsun')) {
|
||||||
return `${chain(font, 'Songti SC', 'STSong', 'SimSun', CJK_SERIF)},serif`
|
return `${chain(font, 'GenOffice Songti SC', 'STSong', 'SimSun', CJK_SERIF)},serif`
|
||||||
}
|
}
|
||||||
if (f.includes('simhei') || f.includes('黑体') || f.includes('细黑') || f.includes('xihei'))
|
if (f.includes('simhei') || f.includes('黑体') || f.includes('细黑') || f.includes('xihei'))
|
||||||
return `${chain(font, 'Heiti SC', 'STHeiti', 'SimHei', 'PingFang SC', CJK_SANS)},sans-serif`
|
return `${chain(font, 'Heiti SC', 'STHeiti', 'SimHei', 'PingFang SC', CJK_SANS)},sans-serif`
|
||||||
@@ -304,19 +342,39 @@ export function cssFontFamily(font: string): string {
|
|||||||
// Japanese/Korean/Traditional Chinese: fall back within the same script (win/mac family names as mutual backups) so Han glyphs don't render with Simplified forms
|
// Japanese/Korean/Traditional Chinese: fall back within the same script (win/mac family names as mutual backups) so Han glyphs don't render with Simplified forms
|
||||||
const JA_SANS = ['Yu Gothic', 'Hiragino Sans', 'Meiryo', 'Noto Sans JP']
|
const JA_SANS = ['Yu Gothic', 'Hiragino Sans', 'Meiryo', 'Noto Sans JP']
|
||||||
const JA_SERIF = ['Yu Mincho', 'Hiragino Mincho ProN', 'MS Mincho', 'Noto Serif JP']
|
const JA_SERIF = ['Yu Mincho', 'Hiragino Mincho ProN', 'MS Mincho', 'Noto Serif JP']
|
||||||
const KO_SANS = ['Malgun Gothic', 'Apple SD Gothic Neo', 'Noto Sans KR']
|
const KO_SANS = ['Malgun Gothic', 'GenOffice Sans KR', 'Apple SD Gothic Neo', 'Noto Sans KR']
|
||||||
const KO_SERIF = ['Batang', 'AppleMyungjo', 'Noto Serif KR']
|
const KO_SERIF = ['Batang', 'GenOffice Serif KR', 'AppleMyungjo', 'Noto Serif KR']
|
||||||
const TC_SANS = ['Microsoft JhengHei', 'PingFang TC', 'Heiti TC', 'Noto Sans TC']
|
const TC_SANS = ['Microsoft JhengHei', 'PingFang TC', 'Heiti TC', 'Noto Sans TC']
|
||||||
const TC_SERIF = ['PMingLiU', 'MingLiU', 'Songti TC', 'Noto Serif TC']
|
// 'GenOffice Fullwidth TC' (fonts.css): fullwidth U+FF0D/FF0F/FF3C/FF3F/FF5E whose Songti TC glyphs look half-width
|
||||||
|
const TC_SERIF = ['PMingLiU', 'MingLiU', 'GenOffice Fullwidth TC', 'Songti TC', 'Noto Serif TC']
|
||||||
|
const SC_SANS = ['PingFang SC', 'Microsoft YaHei', CJK_SANS]
|
||||||
|
const SC_SERIF = ['GenOffice Songti SC', 'STSong', 'SimSun', CJK_SERIF]
|
||||||
const nfkc = font.normalize('NFKC')
|
const nfkc = font.normalize('NFKC')
|
||||||
|
// Arabic: bundled Noto subsets stand in for missing fonts; Chromium's silent
|
||||||
|
// fallback is a Geeza Pro-style UI face, larger and heavier than the naskh
|
||||||
|
// serif Word substitutes. Unknown Arabic names default to the naskh chain.
|
||||||
|
if (
|
||||||
|
/[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/.test(font) ||
|
||||||
|
/naskh|kufi|arabic|urdu|geeza|amiri|scheherazade|lateef|harmattan|aldhabi|andalus|nastaliq|al bayan|baghdad|damascus|diwan|farisi|mishafi|nadeem|beirut/i.test(
|
||||||
|
nfkc,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
const sans = /kufi|sans|dubai|segoe/i.test(nfkc)
|
||||||
|
const chainFor = sans
|
||||||
|
? ['Noto Sans Arabic', 'Geeza Pro']
|
||||||
|
: ['Noto Naskh Arabic', 'Geeza Pro', 'Al Bayan']
|
||||||
|
return `${chain(font, ...chainFor)},${sans ? 'sans-serif' : 'serif'}`
|
||||||
|
}
|
||||||
// Word substitutes a *missing* East Asian font with the locale's default face —
|
// Word substitutes a *missing* East Asian font with the locale's default face —
|
||||||
// a serif (Mincho/Batang) — regardless of the requested font's classification.
|
// a serif (Mincho/Batang) — regardless of the requested font's classification.
|
||||||
// Classic Windows faces (Malgun/Meiryo/Yu Gothic...) have solid macOS
|
// Classic Windows faces (Malgun/Meiryo/Yu Gothic...) have solid macOS
|
||||||
// equivalents in the chains and keep their classification.
|
// equivalents in the chains and keep their classification.
|
||||||
const missingLocally = () => !isFontAvailable(font)
|
const missingLocally = () => isBundledFont(font) || !isFontAvailable(font)
|
||||||
// Noto CJK / Source Han / Nanum regional variants route by suffix; the generic
|
// Noto CJK / Source Han / Nanum regional variants route by suffix; the generic
|
||||||
// fallback tail below would otherwise land them on the bundled Simplified-only subset
|
// fallback tail below would otherwise land them on the bundled Simplified-only subset
|
||||||
const cjkVariant = /^(?:noto|source han) (sans|serif)(?: cjk)? ?(jp|kr|k\b|tc|tw|hk)/i.exec(nfkc)
|
const cjkVariant = /^(?:noto|source han) (sans|serif)(?: cjk)? ?(jp|kr|k|tc|tw|hk|sc|cn)\b/i.exec(
|
||||||
|
nfkc,
|
||||||
|
)
|
||||||
if (cjkVariant) {
|
if (cjkVariant) {
|
||||||
const serif = /serif/i.test(cjkVariant[1]) || missingLocally()
|
const serif = /serif/i.test(cjkVariant[1]) || missingLocally()
|
||||||
const region = cjkVariant[2].toLowerCase()
|
const region = cjkVariant[2].toLowerCase()
|
||||||
@@ -329,10 +387,16 @@ export function cssFontFamily(font: string): string {
|
|||||||
? serif
|
? serif
|
||||||
? KO_SERIF
|
? KO_SERIF
|
||||||
: KO_SANS
|
: KO_SANS
|
||||||
: serif
|
: region === 'sc' || region === 'cn'
|
||||||
? TC_SERIF
|
? serif
|
||||||
: TC_SANS
|
? SC_SERIF
|
||||||
return `${chain(font, ...chainFor)},${serif ? 'serif' : 'sans-serif'}`
|
: SC_SANS
|
||||||
|
: serif
|
||||||
|
? TC_SERIF
|
||||||
|
: TC_SANS
|
||||||
|
// a bundled face at the chain head would win over the substitution; it stays only as the tail safety net
|
||||||
|
const head = isBundledFont(font) ? [] : [font]
|
||||||
|
return `${chain(...head, ...chainFor)},${serif ? 'serif' : 'sans-serif'}`
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
/[-ヿ]|mincho|meiryo|hiragino|osaka|yugoth|yu (gothic|mincho)|ms (ui )?p?(gothic|mincho)|明朝|biz ud|kozuka|小塚/i.test(
|
/[-ヿ]|mincho|meiryo|hiragino|osaka|yugoth|yu (gothic|mincho)|ms (ui )?p?(gothic|mincho)|明朝|biz ud|kozuka|小塚/i.test(
|
||||||
@@ -375,12 +439,43 @@ export function cssFontFamily(font: string): string {
|
|||||||
*/
|
*/
|
||||||
export function cssDualFontFamily(ascii: string, eastAsia: string): string {
|
export function cssDualFontFamily(ascii: string, eastAsia: string): string {
|
||||||
if (ascii === eastAsia) return cssFontFamily(ascii)
|
if (ascii === eastAsia) return cssFontFamily(ascii)
|
||||||
|
// Korean ascii face (e.g. theme latin = Malgun): its fallback chain covers hangul
|
||||||
|
// and would swallow the eastAsia font, so keep only the literal family
|
||||||
|
if (KO_FONT_RE.test(ascii.normalize('NFKC'))) {
|
||||||
|
return `'${ascii.replace(/'/g, '')}',${cssFontFamily(eastAsia)}`
|
||||||
|
}
|
||||||
const latin = cssFontFamily(ascii)
|
const latin = cssFontFamily(ascii)
|
||||||
.split(',')
|
.split(',')
|
||||||
.filter((f) => !/noto (sans|serif) cjk/i.test(f) && !/^(serif|sans-serif|monospace)$/.test(f))
|
.filter((f) => !/noto (sans|serif) cjk/i.test(f) && !/^(serif|sans-serif|monospace)$/.test(f))
|
||||||
return `${latin.join(',')},${cssFontFamily(eastAsia)}`
|
return `${latin.join(',')},${cssFontFamily(eastAsia)}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Text contains complex-script characters (Arabic/Hebrew/Syriac/Thaana/NKo), i.e. the w:cs font slot applies */
|
||||||
|
export function textHasComplexScript(text: string): boolean {
|
||||||
|
return /[\u0590-\u05FF\u0600-\u077F\u0780-\u07FF\u08A0-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/.test(
|
||||||
|
text,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fallback chain for a run whose text hits the w:cs slot: the cs chain leads
|
||||||
|
* (minus its generic tail) so complex-script glyphs use it, then the run's
|
||||||
|
* Latin/East Asian chain for everything else.
|
||||||
|
*/
|
||||||
|
export function cssCsFontFamily(cs: string, ascii?: string, eastAsia?: string): string {
|
||||||
|
const base =
|
||||||
|
ascii && eastAsia && ascii !== eastAsia
|
||||||
|
? cssDualFontFamily(ascii, eastAsia)
|
||||||
|
: ascii || eastAsia
|
||||||
|
? cssFontFamily((ascii || eastAsia)!)
|
||||||
|
: ''
|
||||||
|
if (!base) return cssFontFamily(cs)
|
||||||
|
const head = cssFontFamily(cs)
|
||||||
|
.split(',')
|
||||||
|
.filter((f) => !/^(serif|sans-serif|monospace)$/.test(f))
|
||||||
|
return [...new Set([...head, ...base.split(',')])].join(',')
|
||||||
|
}
|
||||||
|
|
||||||
/** Text contains CJK characters (decides the line-height factor: CJK lines measure ~1.3em per Chinese font metrics) */
|
/** Text contains CJK characters (decides the line-height factor: CJK lines measure ~1.3em per Chinese font metrics) */
|
||||||
export function textHasCjk(text: string): boolean {
|
export function textHasCjk(text: string): boolean {
|
||||||
for (const ch of text) {
|
for (const ch of text) {
|
||||||
@@ -389,6 +484,30 @@ export function textHasCjk(text: string): boolean {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Text contains hangul (Korean paragraphs take the Korean line factor, not the 1.3 Chinese one) */
|
||||||
|
export function textHasHangul(text: string): boolean {
|
||||||
|
for (const ch of text) {
|
||||||
|
if (isHangul(ch.codePointAt(0) ?? 0)) return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Per-paragraph --doc-line-factor value by script (approximates Word's max-of-inline-fonts line height) */
|
||||||
|
export function paraLineFactorCss(text: string): string {
|
||||||
|
if (textHasHangul(text)) return 'var(--doc-line-factor-kr,1.3)'
|
||||||
|
if (textHasCjk(text)) return '1.3'
|
||||||
|
return 'var(--doc-line-factor-latin,1.2)'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** --doc-line-factor-kr source: the document's East Asian face when Korean, else the Batang-class default */
|
||||||
|
export function krLineFactor(fontFamily: string | undefined): number {
|
||||||
|
return fontFamily && isKoreanFontName(fontFamily) ? lineHeightFactor(fontFamily) : 1.3
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isKoreanFontName(fontFamily: string): boolean {
|
||||||
|
return KO_FONT_RE.test(fontFamily.normalize('NFKC'))
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Word line spacing → editing-canvas CSS line-height value (shared by extensions/docStyleCss).
|
* Word line spacing → editing-canvas CSS line-height value (shared by extensions/docStyleCss).
|
||||||
*
|
*
|
||||||
@@ -426,6 +545,7 @@ export function snapSpacingToGrid(spacingTwips: number, docGrid: DocGrid | undef
|
|||||||
|
|
||||||
function isCjk(cp: number): boolean {
|
function isCjk(cp: number): boolean {
|
||||||
return (
|
return (
|
||||||
|
isHangul(cp) ||
|
||||||
(cp >= 0x3000 && cp <= 0x30ff) ||
|
(cp >= 0x3000 && cp <= 0x30ff) ||
|
||||||
(cp >= 0x3400 && cp <= 0x9fff) ||
|
(cp >= 0x3400 && cp <= 0x9fff) ||
|
||||||
(cp >= 0xf900 && cp <= 0xfaff) ||
|
(cp >= 0xf900 && cp <= 0xfaff) ||
|
||||||
@@ -433,6 +553,73 @@ function isCjk(cp: number): boolean {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isHangul(cp: number): boolean {
|
||||||
|
return (
|
||||||
|
(cp >= 0xac00 && cp <= 0xd7a3) ||
|
||||||
|
(cp >= 0x1100 && cp <= 0x11ff) ||
|
||||||
|
(cp >= 0x3130 && cp <= 0x318f) ||
|
||||||
|
(cp >= 0xa960 && cp <= 0xa97f) ||
|
||||||
|
(cp >= 0xd7b0 && cp <= 0xd7ff)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── CJK-Latin autospace pads ────────────────────────────────────────────────
|
||||||
|
// Word's autoSpaceDE/DN gap measures ~1/4em while Chromium's text-autospace is
|
||||||
|
// fixed at 1/8em; the renderer inserts a zero-width .doc-autospace-pad span
|
||||||
|
// whose margin supplies the other 1/8em. Pads only go between a directly
|
||||||
|
// adjacent CJK letter and a Latin letter/digit — never next to spaces or
|
||||||
|
// punctuation — matching where Chromium applies its native gap.
|
||||||
|
|
||||||
|
/** Han/kana/hangul letters; CJK punctuation and full/halfwidth forms get no gap */
|
||||||
|
function isCjkAutospaceSide(cp: number): boolean {
|
||||||
|
if (cp >= 0x3000 && cp <= 0x303f) return false
|
||||||
|
if (cp === 0x30fb) return false
|
||||||
|
if (cp >= 0xff00 && cp <= 0xffef) return false
|
||||||
|
return isCjk(cp)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLatinAlnum(cp: number): boolean {
|
||||||
|
if ((cp >= 0x30 && cp <= 0x39) || (cp >= 0x41 && cp <= 0x5a) || (cp >= 0x61 && cp <= 0x7a)) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// Latin-1 Supplement / Extended letters, minus multiply/divide signs
|
||||||
|
return cp >= 0xc0 && cp <= 0x24f && cp !== 0xd7 && cp !== 0xf7
|
||||||
|
}
|
||||||
|
|
||||||
|
export function needsAutospacePad(prevCp: number, nextCp: number): boolean {
|
||||||
|
return (
|
||||||
|
(isCjkAutospaceSide(prevCp) && isLatinAlnum(nextCp)) ||
|
||||||
|
(isLatinAlnum(prevCp) && isCjkAutospaceSide(nextCp))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function lastCodePoint(text: string): number {
|
||||||
|
const tail = text.charCodeAt(text.length - 1)
|
||||||
|
if (tail >= 0xdc00 && tail <= 0xdfff && text.length > 1) {
|
||||||
|
return text.codePointAt(text.length - 2)!
|
||||||
|
}
|
||||||
|
return tail
|
||||||
|
}
|
||||||
|
|
||||||
|
/** pad between two adjacent stretches of text (last char of prev vs first of next) */
|
||||||
|
export function autospacePadBetween(prev: string, next: string): boolean {
|
||||||
|
if (!prev || !next) return false
|
||||||
|
return needsAutospacePad(lastCodePoint(prev), next.codePointAt(0)!)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** UTF-16 offsets inside text where a pad belongs (between offset-1 and offset) */
|
||||||
|
export function autospaceBoundaries(text: string): number[] {
|
||||||
|
const out: number[] = []
|
||||||
|
let prev = -1
|
||||||
|
for (let i = 0; i < text.length;) {
|
||||||
|
const cp = text.codePointAt(i)!
|
||||||
|
if (prev >= 0 && needsAutospacePad(prev, cp)) out.push(i)
|
||||||
|
prev = cp
|
||||||
|
i += cp > 0xffff ? 2 : 1
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Line-break simulation ───────────────────────────────────────────────────
|
// ─── Line-break simulation ───────────────────────────────────────────────────
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -443,6 +630,7 @@ function isCjk(cp: number): boolean {
|
|||||||
function cjkLineHFactor(fontFamily: string): number {
|
function cjkLineHFactor(fontFamily: string): number {
|
||||||
const f = fontFamily.toLowerCase()
|
const f = fontFamily.toLowerCase()
|
||||||
if (f.includes('pmingliu') || f.includes('mingliu')) return 1.0
|
if (f.includes('pmingliu') || f.includes('mingliu')) return 1.0
|
||||||
|
if (KO_FONT_RE.test(f)) return lineHeightFactor(fontFamily)
|
||||||
return 1.3
|
return 1.3
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,18 +2,33 @@ import { createRoot } from 'react-dom/client'
|
|||||||
import { htmlLang, type Lang } from '@genoffice/i18n'
|
import { htmlLang, type Lang } from '@genoffice/i18n'
|
||||||
import { App } from './App'
|
import { App } from './App'
|
||||||
import { LocaleProvider, setModuleLang } from './i18n/locale'
|
import { LocaleProvider, setModuleLang } from './i18n/locale'
|
||||||
|
import type { UiTheme } from '../shared/ipc'
|
||||||
|
import '@genoffice/ui/tokens.css'
|
||||||
import './styles.css'
|
import './styles.css'
|
||||||
import './fonts/fonts.css'
|
import './fonts/fonts.css'
|
||||||
|
|
||||||
|
function applyTheme(theme: UiTheme): void {
|
||||||
|
if (theme === 'system') document.documentElement.removeAttribute('data-theme')
|
||||||
|
else document.documentElement.setAttribute('data-theme', theme)
|
||||||
|
}
|
||||||
|
|
||||||
async function bootstrap(): Promise<void> {
|
async function bootstrap(): Promise<void> {
|
||||||
let lang: Lang = 'zh'
|
let lang: Lang = 'zh'
|
||||||
|
let theme: UiTheme = 'system'
|
||||||
try {
|
try {
|
||||||
lang = await window.desktop.getLanguage()
|
// per-promise catch: standalone runs have no app:get-theme handler, and
|
||||||
|
// that rejection must not drop a resolved language
|
||||||
|
;[lang, theme] = await Promise.all([
|
||||||
|
window.desktop.getLanguage().catch(() => 'zh' as const),
|
||||||
|
window.desktop.getTheme().catch(() => 'system' as const),
|
||||||
|
])
|
||||||
} catch {
|
} catch {
|
||||||
/* dev renderer without the preload handler */
|
/* dev renderer without the preload bridge */
|
||||||
}
|
}
|
||||||
setModuleLang(lang)
|
setModuleLang(lang)
|
||||||
document.documentElement.lang = htmlLang(lang)
|
document.documentElement.lang = htmlLang(lang)
|
||||||
|
applyTheme(theme)
|
||||||
|
window.desktop?.onThemeChanged(applyTheme)
|
||||||
createRoot(document.getElementById('root')!).render(
|
createRoot(document.getElementById('root')!).render(
|
||||||
<LocaleProvider initial={lang}>
|
<LocaleProvider initial={lang}>
|
||||||
<App />
|
<App />
|
||||||
|
|||||||
@@ -69,6 +69,9 @@ export interface TableRowBox {
|
|||||||
/** in-row safe cut points (relative to row top, px, ascending): spanning all cells without splitting any text line/image.
|
/** in-row safe cut points (relative to row top, px, ascending): spanning all cells without splitting any text line/image.
|
||||||
* Word allows in-row page breaks by default; without cut points or with cantSplit the row is atomic */
|
* Word allows in-row page breaks by default; without cut points or with cantSplit the row is atomic */
|
||||||
cutYs?: number[]
|
cutYs?: number[]
|
||||||
|
/** bottom of the lowest content band (text/image rects) relative to row top (px, 0 = empty row):
|
||||||
|
* lets pagination clip declared-height fill below the content instead of pushing pages */
|
||||||
|
contentBottom?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One column of a multi-column page: a content range in the continuous flow (in-column break semantics match pages) */
|
/** One column of a multi-column page: a content range in the continuous flow (in-column break semantics match pages) */
|
||||||
@@ -271,18 +274,30 @@ export function computeSectionedSlicesF2(
|
|||||||
let colCount = 1 // column count of the current region
|
let colCount = 1 // column count of the current region
|
||||||
let colH = contentH // column height of the current region
|
let colH = contentH // column height of the current region
|
||||||
let colIdx = 0 // current column index
|
let colIdx = 0 // current column index
|
||||||
let colStart = 0 // starting Y of the current column (absolute)
|
|
||||||
let usedInCol = 0 // height used in the current column
|
let usedInCol = 0 // height used in the current column
|
||||||
let pendingBreak = false
|
let pendingBreak = false
|
||||||
let pendingColBreak = false
|
let pendingColBreak = false
|
||||||
|
|
||||||
|
// Safety net: a document legitimately needs at most a few column turns per
|
||||||
|
// block (forced breaks, line/row splits) — far beyond that means a placement
|
||||||
|
// loop stopped converging. Degrade by treating everything as fitting (the
|
||||||
|
// rest piles onto the current page, with a warning) instead of looping forever.
|
||||||
|
const maxColumnTurns = Math.max(65536, blocks.length * 8)
|
||||||
|
let columnTurns = 0
|
||||||
|
let runaway = false
|
||||||
|
|
||||||
const pushColumn = (y: number, headerH = 0, headerTop = 0) => {
|
const pushColumn = (y: number, headerH = 0, headerTop = 0) => {
|
||||||
|
if (++columnTurns > maxColumnTurns && !runaway) {
|
||||||
|
runaway = true
|
||||||
|
console.warn(
|
||||||
|
`[pagination] column-turn limit ${maxColumnTurns} exceeded at y=${y}; placing remaining content without page breaks`,
|
||||||
|
)
|
||||||
|
}
|
||||||
const page = pages[pages.length - 1]
|
const page = pages[pages.length - 1]
|
||||||
page.regions[page.regions.length - 1].entries.push({
|
page.regions[page.regions.length - 1].entries.push({
|
||||||
y,
|
y,
|
||||||
...(headerH > 0 ? { repeatHeader: { top: headerTop, height: headerH } } : {}),
|
...(headerH > 0 ? { repeatHeader: { top: headerTop, height: headerH } } : {}),
|
||||||
})
|
})
|
||||||
colStart = y
|
|
||||||
usedInCol = headerH
|
usedInCol = headerH
|
||||||
}
|
}
|
||||||
// open a new region at the current page's regionTop (column count/height per section)
|
// open a new region at the current page's regionTop (column count/height per section)
|
||||||
@@ -315,8 +330,8 @@ export function computeSectionedSlicesF2(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// whether height h fits in the current column
|
// whether height h fits in the current column (runaway degrade: everything fits)
|
||||||
const fits = (h: number): boolean => usedInCol + h <= colH + 0.01
|
const fits = (h: number): boolean => runaway || usedInCol + h <= colH + 0.01
|
||||||
// whether the current column is empty (just changed columns or at column top)
|
// whether the current column is empty (just changed columns or at column top)
|
||||||
const colEmpty = () => usedInCol <= 0.01
|
const colEmpty = () => usedInCol <= 0.01
|
||||||
// whether the current page is entirely blank (guards forced breaks against empty pages)
|
// whether the current page is entirely blank (guards forced breaks against empty pages)
|
||||||
@@ -383,7 +398,17 @@ export function computeSectionedSlicesF2(
|
|||||||
|
|
||||||
// ── Tables: row-level page breaking ────────────────────────────────────
|
// ── Tables: row-level page breaking ────────────────────────────────────
|
||||||
if (block.tableRows && block.tableRows.length > 0) {
|
if (block.tableRows && block.tableRows.length > 0) {
|
||||||
_placeTable(block, block.tableRows, colH, fits, place, colEmpty, newColumn, curSection)
|
_placeTable(
|
||||||
|
block,
|
||||||
|
block.tableRows,
|
||||||
|
colH,
|
||||||
|
fits,
|
||||||
|
place,
|
||||||
|
() => Math.max(colH - usedInCol, 0),
|
||||||
|
colEmpty,
|
||||||
|
newColumn,
|
||||||
|
curSection,
|
||||||
|
)
|
||||||
if (block.spaceAfterPx) place(block.spaceAfterPx) // space after the table (may overflow into the bottom margin)
|
if (block.spaceAfterPx) place(block.spaceAfterPx) // space after the table (may overflow into the bottom margin)
|
||||||
if (block.breakAfter) pendingBreak = true
|
if (block.breakAfter) pendingBreak = true
|
||||||
if (block.colBreakAfter) pendingColBreak = true
|
if (block.colBreakAfter) pendingColBreak = true
|
||||||
@@ -417,11 +442,15 @@ export function computeSectionedSlicesF2(
|
|||||||
curSection,
|
curSection,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
// no line data: hard cut
|
// no line data: hard pixel cuts consuming the remainder column by
|
||||||
while (!fits(block.height)) {
|
// column. (Retesting the full block height after each turn never
|
||||||
newColumn(colStart + colH, curSection)
|
// fits a block taller than one column and used to loop forever.)
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
place(block.height)
|
place(block.height - offset)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
place(block.height)
|
place(block.height)
|
||||||
@@ -462,10 +491,13 @@ export function computeSectionedSlicesF2(
|
|||||||
let chainH = 0
|
let chainH = 0
|
||||||
for (let k = bi; k <= effectiveChainEnd; k++) chainH += blocks[k].height
|
for (let k = bi; k <= effectiveChainEnd; k++) chainH += blocks[k].height
|
||||||
|
|
||||||
// anchor first-line height (only relevant when the anchor lacks breakBefore)
|
// anchor first-line height (only relevant when the anchor lacks breakBefore);
|
||||||
|
// anchored tables count their first row only (Word keeps the heading with the table head, not the whole table)
|
||||||
const anchorFirstLineH =
|
const anchorFirstLineH =
|
||||||
!anchorHasBreak && anchorBlock
|
!anchorHasBreak && anchorBlock
|
||||||
? (anchorBlock.lineBoxes?.[0]?.height ?? anchorBlock.height)
|
? (anchorBlock.lineBoxes?.[0]?.height ??
|
||||||
|
anchorBlock.tableRows?.[0]?.height ??
|
||||||
|
anchorBlock.height)
|
||||||
: 0
|
: 0
|
||||||
const chainPlusAnchorH = chainH + anchorFirstLineH
|
const chainPlusAnchorH = chainH + anchorFirstLineH
|
||||||
|
|
||||||
@@ -573,6 +605,7 @@ function _placeTable(
|
|||||||
contentH: number,
|
contentH: number,
|
||||||
fits: (h: number) => boolean,
|
fits: (h: number) => boolean,
|
||||||
place: (h: number) => void,
|
place: (h: number) => void,
|
||||||
|
remain: () => number,
|
||||||
pageEmpty: () => boolean,
|
pageEmpty: () => boolean,
|
||||||
newPage: (y: number, section: number, headerH?: number, headerTop?: number) => void,
|
newPage: (y: number, section: number, headerH?: number, headerTop?: number) => void,
|
||||||
curSection: number,
|
curSection: number,
|
||||||
@@ -605,43 +638,63 @@ function _placeTable(
|
|||||||
const repeatH = placedHeader && ri >= headerRows ? headerHeight : 0
|
const repeatH = placedHeader && ri >= headerRows ? headerHeight : 0
|
||||||
|
|
||||||
if (!fits(row.height)) {
|
if (!fits(row.height)) {
|
||||||
|
const contentEnd =
|
||||||
|
row.contentBottom !== undefined ? Math.min(row.contentBottom, row.height) : row.height
|
||||||
// in-row page break (Word default): without cantSplit and with safe cut points,
|
// in-row page break (Word default): without cantSplit and with safe cut points,
|
||||||
// place segment by segment at the cut points. If the first segment doesn't fit,
|
// place segment by segment at the cut points. If the first segment doesn't fit,
|
||||||
// turn the page first (equivalent to pushing the whole row); rows taller than a page also flow segment by segment
|
// turn the page first (equivalent to pushing the whole row)
|
||||||
let cuts = !row.cantSplit && row.cutYs ? [...row.cutYs] : []
|
let cuts = !row.cantSplit && row.cutYs ? [...row.cutYs] : []
|
||||||
if (!row.cantSplit && row.height > contentH) {
|
const placeSegments = (bounds: number[]) => {
|
||||||
// A fixed-height row can be taller than a page while containing only one
|
|
||||||
// text band, so DOM line sampling may provide too few natural cuts. Keep
|
|
||||||
// every segment page-sized; natural inter-band cuts remain preferred and
|
|
||||||
// a hard content-band cut is only inserted where no legal cut advances.
|
|
||||||
const bounded: number[] = []
|
|
||||||
let previous = 0
|
|
||||||
for (const candidate of [...cuts, row.height]) {
|
|
||||||
while (candidate - previous > contentH + 0.01) {
|
|
||||||
previous += contentH
|
|
||||||
bounded.push(previous)
|
|
||||||
}
|
|
||||||
if (candidate < row.height - 0.5 && candidate > previous + 0.5) {
|
|
||||||
bounded.push(candidate)
|
|
||||||
previous = candidate
|
|
||||||
}
|
|
||||||
}
|
|
||||||
cuts = bounded
|
|
||||||
}
|
|
||||||
if (cuts.length > 0) {
|
|
||||||
let prev = 0
|
let prev = 0
|
||||||
for (const cut of [...cuts, row.height]) {
|
for (const cut of bounds) {
|
||||||
const seg = cut - prev
|
const seg = cut - prev
|
||||||
if (seg <= 0.5) continue
|
if (seg <= 0.5) continue
|
||||||
if (!fits(seg) && !pageEmpty()) newPage(rowCursor + prev, curSection, repeatH, block.top)
|
if (!fits(seg) && !pageEmpty()) newPage(rowCursor + prev, curSection, repeatH, block.top)
|
||||||
place(seg)
|
place(seg)
|
||||||
prev = cut
|
prev = cut
|
||||||
}
|
}
|
||||||
|
return prev
|
||||||
|
}
|
||||||
|
// Only rows taller than a page get their declared-height fill clipped to the
|
||||||
|
// page remainder (Word truncates over-tall rows within the page). Page-sized
|
||||||
|
// rows keep the fill glued to the last segment: a clipped fill would desync
|
||||||
|
// bookkeeping from DOM height, leaking shading/empty rows past the page edge.
|
||||||
|
if (row.height > contentH + 0.01) {
|
||||||
|
if (!row.cantSplit && contentEnd > contentH) {
|
||||||
|
// A fixed-height row can be taller than a page while containing only one
|
||||||
|
// text band, so DOM line sampling may provide too few natural cuts. Keep
|
||||||
|
// every segment page-sized; natural inter-band cuts remain preferred and
|
||||||
|
// a hard content-band cut is only inserted where no legal cut advances.
|
||||||
|
const bounded: number[] = []
|
||||||
|
let previous = 0
|
||||||
|
for (const candidate of [...cuts, contentEnd]) {
|
||||||
|
while (candidate - previous > contentH + 0.01) {
|
||||||
|
previous += contentH
|
||||||
|
bounded.push(previous)
|
||||||
|
}
|
||||||
|
if (candidate < row.height - 0.5 && candidate > previous + 0.5) {
|
||||||
|
bounded.push(candidate)
|
||||||
|
previous = candidate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cuts = bounded
|
||||||
|
}
|
||||||
|
cuts = cuts.filter((c) => c < contentEnd - 0.01)
|
||||||
|
if (cuts.length > 0 || contentEnd < row.height - 0.5) {
|
||||||
|
const prev = placeSegments([...cuts, contentEnd])
|
||||||
|
const fill = row.height - prev
|
||||||
|
if (fill > 0.5) place(Math.min(fill, remain()))
|
||||||
|
rowCursor += row.height
|
||||||
|
if (row.isHeader && ri < headerRows) placedHeader = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
} else if (cuts.length > 0) {
|
||||||
|
placeSegments([...cuts, row.height])
|
||||||
rowCursor += row.height
|
rowCursor += row.height
|
||||||
if (row.isHeader && ri < headerRows) placedHeader = true
|
if (row.isHeader && ri < headerRows) placedHeader = true
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// cantSplit / no cut points: the row is atomic; turn the page first if it doesn't fit
|
// cantSplit / empty / no cut points: the row is atomic; turn the page first if it doesn't fit
|
||||||
if (!pageEmpty()) newPage(rowCursor, curSection, repeatH, block.top)
|
if (!pageEmpty()) newPage(rowCursor, curSection, repeatH, block.top)
|
||||||
}
|
}
|
||||||
place(row.height)
|
place(row.height)
|
||||||
@@ -764,12 +817,10 @@ function _placeParaBlock(
|
|||||||
if (splitLine > 0) {
|
if (splitLine > 0) {
|
||||||
const newHead = nLines - splitLine
|
const newHead = nLines - splitLine
|
||||||
if (newHead === 1) {
|
if (newHead === 1) {
|
||||||
// widow at page top: keep the last line on the current page too
|
// widow at page top: give up one line here so the next page gets 2 lines (Word)
|
||||||
splitLine += 1
|
splitLine -= 1
|
||||||
if (splitLine >= nLines) {
|
// fewer than 2 lines left at page bottom would be an orphan: push the whole paragraph
|
||||||
// whole paragraph on the current page? then fits(totalH) should have been true; this is an edge case, push to the next page
|
if (splitLine < 2) splitLine = -1
|
||||||
splitLine = -1
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (!widowOn) {
|
} else if (!widowOn) {
|
||||||
@@ -1220,12 +1271,21 @@ export function measureBlocks(
|
|||||||
const top = (rect.top - origin - gapAccum) / zoomFactor
|
const top = (rect.top - origin - gapAccum) / zoomFactor
|
||||||
const height = (rect.height - innerGap) / zoomFactor
|
const height = (rect.height - innerGap) / zoomFactor
|
||||||
const idxAttr = el.getAttribute('data-idx')
|
const idxAttr = el.getAttribute('data-idx')
|
||||||
|
const hasBreak = !!el.querySelector('.doc-field-pagebreak, .doc-page-br')
|
||||||
|
// break-only paragraph: count the whole block (br line + ProseMirror trailing-break
|
||||||
|
// phantom line) as trailing space so it never pushes to — and blanks — a page. Word's
|
||||||
|
// real rule is that the br/paragraph-mark line must fit or the paragraph pushes into a
|
||||||
|
// deliberate blank page, but our page fill drifts a few px per page in both directions,
|
||||||
|
// and a fit-check flips borderline pages into spurious mid-document blanks (worse than
|
||||||
|
// occasionally dropping an intentional one)
|
||||||
|
const breakOnly = hasBreak && !(el.textContent ?? '').trim() && !el.querySelector('img')
|
||||||
blocks.push({
|
blocks.push({
|
||||||
top,
|
top,
|
||||||
height,
|
height,
|
||||||
breakBefore: el.classList.contains('page-break-before') || undefined,
|
breakBefore: el.classList.contains('page-break-before') || undefined,
|
||||||
breakAfter: el.querySelector('.doc-field-pagebreak, .doc-page-br') ? true : undefined,
|
breakAfter: hasBreak || undefined,
|
||||||
el,
|
el,
|
||||||
|
...(breakOnly ? { spaceAfterPx: height } : {}),
|
||||||
...(idxAttr ? { docxIndex: parseInt(idxAttr, 10) } : {}),
|
...(idxAttr ? { docxIndex: parseInt(idxAttr, 10) } : {}),
|
||||||
})
|
})
|
||||||
gapAccum += innerGap
|
gapAccum += innerGap
|
||||||
@@ -1238,7 +1298,7 @@ export function measureBlocks(
|
|||||||
for (let i = 0; i + 1 < blocks.length; i++) {
|
for (let i = 0; i + 1 < blocks.length; i++) {
|
||||||
const gap = blocks[i + 1].top - (blocks[i].top + blocks[i].height)
|
const gap = blocks[i + 1].top - (blocks[i].top + blocks[i].height)
|
||||||
if (gap > 0.5) {
|
if (gap > 0.5) {
|
||||||
blocks[i].spaceAfterPx = gap
|
blocks[i].spaceAfterPx = (blocks[i].spaceAfterPx ?? 0) + gap
|
||||||
blocks[i].height += gap
|
blocks[i].height += gap
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1352,14 +1412,23 @@ export function fillLineBoxes(
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
let changed = false
|
let changed = false
|
||||||
for (const block of blocks) {
|
for (let i = 0; i < blocks.length; i++) {
|
||||||
|
const block = blocks[i]
|
||||||
if (!block.el || block.lineBoxes || block.tableRows) continue
|
if (!block.el || block.lineBoxes || block.tableRows) continue
|
||||||
const contentH = geomOf(block.section ?? 0)?.contentHeight ?? 0
|
const contentH = geomOf(block.section ?? 0)?.contentHeight ?? 0
|
||||||
if (contentH <= 0) continue
|
if (contentH <= 0) continue
|
||||||
const bottom = block.top + block.height
|
const bottom = block.top + block.height
|
||||||
const crossing = breaks.some((y) => block.top < y && y < bottom)
|
const crossing = breaks.some((y) => block.top < y && y < bottom)
|
||||||
const atPageTop = breaks.some((y) => Math.abs(block.top - y) < 0.5)
|
const atPageTop = breaks.some((y) => Math.abs(block.top - y) < 0.5)
|
||||||
if (block.height <= contentH && !crossing && !atPageTop) continue
|
if (
|
||||||
|
block.height <= contentH &&
|
||||||
|
!crossing &&
|
||||||
|
!atPageTop &&
|
||||||
|
// tables anchoring a keepNext chain always need row data: the chain head only
|
||||||
|
// has to share a page with the first row, so the whole-table height is misleading
|
||||||
|
!(i > 0 && blocks[i - 1].keepNext && !block.keepNext && block.el.querySelector('tr'))
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
// line boxes tile only the text area (block height includes the merged-in space-after, which lines must not cover)
|
// line boxes tile only the text area (block height includes the merged-in space-after, which lines must not cover)
|
||||||
const textH = block.height - (block.spaceAfterPx ?? 0)
|
const textH = block.height - (block.spaceAfterPx ?? 0)
|
||||||
@@ -1493,14 +1562,22 @@ function domTableRows(el: HTMLElement, blockHeight: number, zoomFactor: number):
|
|||||||
if (off > 0.5) tops.push(off)
|
if (off > 0.5) tops.push(off)
|
||||||
}
|
}
|
||||||
return tileBoxes(tops, blockHeight).map((b, i) => {
|
return tileBoxes(tops, blockHeight).map((b, i) => {
|
||||||
const cutYs = trs[i]
|
if (!trs[i]) return { height: b.height }
|
||||||
? rowCutYs(trs[i], b.offsetInBlock, b.height, elTop, gapAbove, zoomFactor)
|
const { cuts, contentBottom } = rowCutYs(
|
||||||
: []
|
trs[i],
|
||||||
return { height: b.height, ...(cutYs.length > 0 ? { cutYs } : {}) }
|
b.offsetInBlock,
|
||||||
|
b.height,
|
||||||
|
elTop,
|
||||||
|
gapAbove,
|
||||||
|
zoomFactor,
|
||||||
|
)
|
||||||
|
return { height: b.height, contentBottom, ...(cuts.length > 0 ? { cutYs: cuts } : {}) }
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/** In-row safe cut points (relative to row top, px, ascending): span all cells without splitting any text-line/image rect */
|
/** In-row safe cut points (relative to row top, px, ascending): line-level candidates
|
||||||
|
* per cell (Word breaks between any two lines), rejecting cuts that would cross a
|
||||||
|
* line box in another cell. Also reports the lowest content-band bottom. */
|
||||||
function rowCutYs(
|
function rowCutYs(
|
||||||
tr: Element,
|
tr: Element,
|
||||||
rowTop: number,
|
rowTop: number,
|
||||||
@@ -1508,35 +1585,70 @@ function rowCutYs(
|
|||||||
elTop: number,
|
elTop: number,
|
||||||
gapAbove: (top: number) => number,
|
gapAbove: (top: number) => number,
|
||||||
zoomFactor: number,
|
zoomFactor: number,
|
||||||
): number[] {
|
): { cuts: number[]; contentBottom: number } {
|
||||||
const bands: Array<[number, number]> = []
|
const cells = Array.from(tr.children).filter((c) => c.tagName === 'TD' || c.tagName === 'TH')
|
||||||
const add = (r: DOMRect) => {
|
|
||||||
if (r.height <= 0 || r.width <= 0) return
|
|
||||||
bands.push([
|
|
||||||
(r.top - elTop - gapAbove(r.top)) / zoomFactor - rowTop,
|
|
||||||
(r.bottom - elTop - gapAbove(r.bottom)) / zoomFactor - rowTop,
|
|
||||||
])
|
|
||||||
}
|
|
||||||
const walker = document.createTreeWalker(tr, NodeFilter.SHOW_TEXT)
|
|
||||||
const range = document.createRange()
|
const range = document.createRange()
|
||||||
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
const cellBands: Array<Array<[number, number]>> = []
|
||||||
if (n.parentElement?.closest('.page-gap')) continue
|
for (const cell of cells) {
|
||||||
range.selectNodeContents(n)
|
const bands: Array<[number, number]> = []
|
||||||
for (const r of range.getClientRects()) add(r)
|
const add = (r: DOMRect) => {
|
||||||
|
if (r.height <= 0 || r.width <= 0) return
|
||||||
|
bands.push([
|
||||||
|
(r.top - elTop - gapAbove(r.top)) / zoomFactor - rowTop,
|
||||||
|
(r.bottom - elTop - gapAbove(r.bottom)) / zoomFactor - rowTop,
|
||||||
|
])
|
||||||
|
}
|
||||||
|
const walker = document.createTreeWalker(cell, NodeFilter.SHOW_TEXT)
|
||||||
|
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
||||||
|
if (n.parentElement?.closest('.page-gap')) continue
|
||||||
|
range.selectNodeContents(n)
|
||||||
|
for (const r of range.getClientRects()) add(r)
|
||||||
|
}
|
||||||
|
for (const obj of cell.querySelectorAll('img, svg, canvas')) {
|
||||||
|
// in-cell gap decorations may carry header/footer images: not row content
|
||||||
|
if (obj.closest('.page-gap')) continue
|
||||||
|
add(obj.getBoundingClientRect())
|
||||||
|
}
|
||||||
|
if (bands.length > 0) cellBands.push(bands)
|
||||||
}
|
}
|
||||||
for (const obj of tr.querySelectorAll('img, svg, canvas')) add(obj.getBoundingClientRect())
|
const contentBottom = cellBands.reduce(
|
||||||
if (bands.length === 0) return []
|
(max, bands) => bands.reduce((m, [, b]) => Math.max(m, b), max),
|
||||||
bands.sort((a, b) => a[0] - b[0])
|
0,
|
||||||
const merged: Array<[number, number]> = []
|
)
|
||||||
for (const band of bands) {
|
return { cuts: cellCutYs(cellBands, rowHeight), contentBottom }
|
||||||
const last = merged[merged.length - 1]
|
}
|
||||||
if (last && band[0] < last[1] + 1) last[1] = Math.max(last[1], band[1])
|
|
||||||
else merged.push([band[0], band[1]])
|
/** Rects sharing vertical overlap collapse into one line interval (same criterion as domLineRects) */
|
||||||
|
function clusterLineBands(bands: Array<[number, number]>): Array<[number, number]> {
|
||||||
|
const sorted = [...bands].sort((a, b) => a[0] - b[0])
|
||||||
|
const lines: Array<[number, number]> = []
|
||||||
|
for (const [top, bottom] of sorted) {
|
||||||
|
const last = lines[lines.length - 1]
|
||||||
|
if (last && top < last[1] - 1) last[1] = Math.max(last[1], bottom)
|
||||||
|
else lines.push([top, bottom])
|
||||||
}
|
}
|
||||||
|
return lines
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pure core of rowCutYs (testable without DOM): per-cell rect bands → safe cut ys.
|
||||||
|
* Candidates are midpoints between a cell's consecutive lines (a zero gap still
|
||||||
|
* counts); a candidate falling inside any cell's line box is unsafe (0.5px
|
||||||
|
* tolerance for sub-pixel jitter). */
|
||||||
|
export function cellCutYs(cellBands: Array<Array<[number, number]>>, rowHeight: number): number[] {
|
||||||
|
const cellLines = cellBands.map(clusterLineBands)
|
||||||
|
const candidates: number[] = []
|
||||||
|
for (const lines of cellLines) {
|
||||||
|
for (let i = 0; i + 1 < lines.length; i++) {
|
||||||
|
candidates.push((lines[i][1] + lines[i + 1][0]) / 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
candidates.sort((a, b) => a - b)
|
||||||
const cuts: number[] = []
|
const cuts: number[] = []
|
||||||
for (let i = 0; i + 1 < merged.length; i++) {
|
for (const y of candidates) {
|
||||||
const cut = (merged[i][1] + merged[i + 1][0]) / 2
|
if (y <= 2 || y >= rowHeight - 2) continue
|
||||||
if (cut > 2 && cut < rowHeight - 2) cuts.push(cut)
|
if (cellLines.some((lines) => lines.some(([t, b]) => y > t + 0.5 && y < b - 0.5))) continue
|
||||||
|
if (cuts.length > 0 && y - cuts[cuts.length - 1] < 1) continue
|
||||||
|
cuts.push(y)
|
||||||
}
|
}
|
||||||
return cuts
|
return cuts
|
||||||
}
|
}
|
||||||
@@ -1684,6 +1796,16 @@ export function nextLineAnchor(
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** In-row cut decoration policy: a single-cell row can host a real inline gap band
|
||||||
|
* (one cell spans the whole cut) — returns that cell; multi-cell rows keep the
|
||||||
|
* zero-height cut marker (same-y bands across cells are not modeled) — returns null. */
|
||||||
|
export function singleCutCell(row: Element | null): Element | null {
|
||||||
|
const cells = row
|
||||||
|
? Array.from(row.children).filter((c) => c.tagName === 'TD' || c.tagName === 'TH')
|
||||||
|
: []
|
||||||
|
return cells.length === 1 ? cells[0] : null
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Index of each non-first-page page-leading block (a page gap should be inserted before it).
|
* Index of each non-first-page page-leading block (a page gap should be inserted before it).
|
||||||
* Hard pixel-cut boundaries (inside over-page big blocks, with no matching block) are skipped.
|
* Hard pixel-cut boundaries (inside over-page big blocks, with no matching block) are skipped.
|
||||||
|
|||||||
+702
-357
File diff suppressed because it is too large
Load Diff
@@ -131,6 +131,8 @@ export type MenuCommand =
|
|||||||
| 'export-pdf'
|
| 'export-pdf'
|
||||||
| 'word-count'
|
| 'word-count'
|
||||||
|
|
||||||
|
export type UiTheme = 'light' | 'dark' | 'system'
|
||||||
|
|
||||||
export interface DesktopApi {
|
export interface DesktopApi {
|
||||||
/** current UI language (persisted by the shell in app-settings.json) */
|
/** current UI language (persisted by the shell in app-settings.json) */
|
||||||
getLanguage(): Promise<'zh' | 'en' | 'ja' | 'ko' | 'fr' | 'de' | 'es' | 'th' | 'id' | 'ru' | 'ar'>
|
getLanguage(): Promise<'zh' | 'en' | 'ja' | 'ko' | 'fr' | 'de' | 'es' | 'th' | 'id' | 'ru' | 'ar'>
|
||||||
@@ -140,6 +142,10 @@ export interface DesktopApi {
|
|||||||
lang: 'zh' | 'en' | 'ja' | 'ko' | 'fr' | 'de' | 'es' | 'th' | 'id' | 'ru' | 'ar',
|
lang: 'zh' | 'en' | 'ja' | 'ko' | 'fr' | 'de' | 'es' | 'th' | 'id' | 'ru' | 'ar',
|
||||||
) => void,
|
) => void,
|
||||||
): () => void
|
): () => void
|
||||||
|
/** current UI theme preference (persisted by the shell in app-settings.json) */
|
||||||
|
getTheme(): Promise<UiTheme>
|
||||||
|
/** theme switched from the shell home page */
|
||||||
|
onThemeChanged(handler: (theme: UiTheme) => void): () => void
|
||||||
openDocx(): Promise<OpenFileResult | null>
|
openDocx(): Promise<OpenFileResult | null>
|
||||||
openDocxPath(path: string): Promise<OpenFileResult | null>
|
openDocxPath(path: string): Promise<OpenFileResult | null>
|
||||||
/** mark the renderer ready and consume a file passed by Finder/Explorer at launch */
|
/** mark the renderer ready and consume a file passed by Finder/Explorer at launch */
|
||||||
@@ -259,4 +265,6 @@ export interface DesktopApi {
|
|||||||
/** Close guard chose "Save": main process asks the renderer to run the full save flow */
|
/** Close guard chose "Save": main process asks the renderer to run the full save flow */
|
||||||
onCloseSaveRequest(handler: () => void): () => void
|
onCloseSaveRequest(handler: () => void): () => void
|
||||||
reportCloseSaveResult(ok: boolean): void
|
reportCloseSaveResult(ok: boolean): void
|
||||||
|
/** keep the native View menu's checkbox items in sync with renderer state */
|
||||||
|
reportViewMenuState(state: { aiSidebar: boolean; darkCanvas: boolean }): void
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
/**
|
||||||
|
* CJK-Latin autospace pad widgets: Chromium's text-autospace delivers 1/8em of
|
||||||
|
* Word's ~1/4em autoSpaceDE/DN gap; a .doc-autospace-pad widget at each boundary
|
||||||
|
* supplies the rest and must follow live edits.
|
||||||
|
*/
|
||||||
|
import { Editor } from '@tiptap/core'
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { editorExtensions } from '../src/renderer/editor/extensions'
|
||||||
|
|
||||||
|
const padCount = (editor: Editor): number =>
|
||||||
|
editor.view.dom.querySelectorAll('.doc-autospace-pad').length
|
||||||
|
|
||||||
|
const paragraphDoc = (text: string, attrs?: Record<string, unknown>) =>
|
||||||
|
({
|
||||||
|
type: 'doc',
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: 'docParagraph',
|
||||||
|
...(attrs ? { attrs } : {}),
|
||||||
|
content: text ? [{ type: 'text', text }] : [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}) as never
|
||||||
|
|
||||||
|
const makeEditor = (content: unknown) =>
|
||||||
|
new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: content as never,
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('autospace pad decorations', () => {
|
||||||
|
it('pads each CJK-Latin/digit boundary, skipping space/punctuation seams', () => {
|
||||||
|
const editor = makeEditor(paragraphDoc('テスト17.0km ペン'))
|
||||||
|
expect(padCount(editor)).toBe(1)
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('covers hangul boundaries', () => {
|
||||||
|
const editor = makeEditor(paragraphDoc('한글A와 B'))
|
||||||
|
expect(padCount(editor)).toBe(2)
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('adds no pads when the paragraph turns autoSpace off', () => {
|
||||||
|
const editor = makeEditor(paragraphDoc('ペン12', { autoSpace: false }))
|
||||||
|
expect(padCount(editor)).toBe(0)
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('pads across styled-run boundaries', () => {
|
||||||
|
const editor = makeEditor({
|
||||||
|
type: 'doc',
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: 'docParagraph',
|
||||||
|
content: [
|
||||||
|
{ type: 'text', text: 'ペン' },
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
text: '12',
|
||||||
|
marks: [{ type: 'docTextStyle', attrs: { sizeHalfPoints: 24 } }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
expect(padCount(editor)).toBe(1)
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('follows live edits', () => {
|
||||||
|
const editor = makeEditor(paragraphDoc('ペン'))
|
||||||
|
expect(padCount(editor)).toBe(0)
|
||||||
|
|
||||||
|
editor.commands.insertContentAt(3, '12')
|
||||||
|
expect(padCount(editor)).toBe(1)
|
||||||
|
|
||||||
|
editor.commands.deleteRange({ from: 3, to: 5 })
|
||||||
|
expect(padCount(editor)).toBe(0)
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import type { Block, GeneratedBlock } from '@genoffice/docx-engine'
|
import type { Block, GeneratedBlock, SectionInfo, TableModel } from '@genoffice/docx-engine'
|
||||||
import {
|
import {
|
||||||
blocksToPmDoc,
|
blocksToPmDoc,
|
||||||
|
capTableRowHeights,
|
||||||
inlineToRuns,
|
inlineToRuns,
|
||||||
pmDocToSavePlan,
|
pmDocToSavePlan,
|
||||||
|
runsToInline,
|
||||||
signatureOfBlock,
|
signatureOfBlock,
|
||||||
signatureOfGenerated,
|
signatureOfGenerated,
|
||||||
type PmNode,
|
type PmNode,
|
||||||
@@ -34,6 +36,49 @@ describe('inlineToRuns hard break after atomic runs', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('runsToInline image runs', () => {
|
||||||
|
it('keeps sibling w:t text on a run that also carries a drawing', () => {
|
||||||
|
const runs = [
|
||||||
|
{
|
||||||
|
text: 'caption',
|
||||||
|
bold: true,
|
||||||
|
image: { dataUrl: 'data:image/png;base64,QUJD', xml: '<w:drawing/>', widthPx: 96 },
|
||||||
|
},
|
||||||
|
]
|
||||||
|
const inline = runsToInline(runs)
|
||||||
|
// generate.ts writes the text before the drawing, so the editor mirrors it
|
||||||
|
expect(inline).toEqual([
|
||||||
|
{ type: 'text', text: 'caption', marks: [{ type: 'bold' }] },
|
||||||
|
{
|
||||||
|
type: 'docInlineImage',
|
||||||
|
attrs: {
|
||||||
|
dataUrl: 'data:image/png;base64,QUJD',
|
||||||
|
widthPx: 96,
|
||||||
|
heightPx: null,
|
||||||
|
xml: '<w:drawing/>',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('emits only the image atom for a text-less drawing run', () => {
|
||||||
|
const inline = runsToInline([
|
||||||
|
{ text: '', image: { dataUrl: 'data:image/png;base64,QUJD', xml: '<w:drawing/>' } },
|
||||||
|
])
|
||||||
|
expect(inline).toEqual([
|
||||||
|
{
|
||||||
|
type: 'docInlineImage',
|
||||||
|
attrs: {
|
||||||
|
dataUrl: 'data:image/png;base64,QUJD',
|
||||||
|
widthPx: null,
|
||||||
|
heightPx: null,
|
||||||
|
xml: '<w:drawing/>',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('paragraph format signatures', () => {
|
describe('paragraph format signatures', () => {
|
||||||
const base: Block = {
|
const base: Block = {
|
||||||
id: 'b0',
|
id: 'b0',
|
||||||
@@ -139,3 +184,62 @@ describe('split twin bookmark/comment anchors', () => {
|
|||||||
expect(twin.block.commentEnds).toBeUndefined()
|
expect(twin.block.commentEnds).toBeUndefined()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('section row-height cap (declared trHeight taller than a page)', () => {
|
||||||
|
const section = (firstBlockIndex: number, lastBlockIndex: number): SectionInfo => ({
|
||||||
|
settings: {
|
||||||
|
pageWidth: 12240,
|
||||||
|
pageHeight: 15840,
|
||||||
|
orientation: 'portrait',
|
||||||
|
marginTop: 1440,
|
||||||
|
marginRight: 1800,
|
||||||
|
marginBottom: 1440,
|
||||||
|
marginLeft: 1800,
|
||||||
|
pageBorder: false,
|
||||||
|
columns: 1,
|
||||||
|
},
|
||||||
|
startType: 'nextPage',
|
||||||
|
firstBlockIndex,
|
||||||
|
lastBlockIndex,
|
||||||
|
sectPrXml: '',
|
||||||
|
titlePg: false,
|
||||||
|
headerRefs: {},
|
||||||
|
footerRefs: {},
|
||||||
|
})
|
||||||
|
const tableBlock: Block = {
|
||||||
|
id: 'b0',
|
||||||
|
type: 'table',
|
||||||
|
docxIndex: 0,
|
||||||
|
originalXml: '<w:tbl/>',
|
||||||
|
table: {
|
||||||
|
rows: [[{ paras: ['x'] }], [{ paras: ['y'] }]],
|
||||||
|
rowHeightsTwips: [31680, 500],
|
||||||
|
rowHeightRules: ['atLeast', 'atLeast'],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
it('caps declared row heights at one page of section content', () => {
|
||||||
|
const doc = blocksToPmDoc([tableBlock], [section(0, 0)])
|
||||||
|
const rows = doc.content![0].content!
|
||||||
|
// 15840 - 1440 - 1440
|
||||||
|
expect(rows[0].attrs!.heightTwips).toBe(12960)
|
||||||
|
expect(rows[1].attrs!.heightTwips).toBe(500)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('leaves heights unchanged without section info', () => {
|
||||||
|
const doc = blocksToPmDoc([tableBlock])
|
||||||
|
expect(doc.content![0].content![0].attrs!.heightTwips).toBe(31680)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('capTableRowHeights recurses into nested tables and is identity below the cap', () => {
|
||||||
|
const nested: TableModel = { rows: [[{ paras: ['n'] }]], rowHeightsTwips: [20000] }
|
||||||
|
const model: TableModel = {
|
||||||
|
rows: [[{ paras: ['x'], nestedTables: [nested] }]],
|
||||||
|
rowHeightsTwips: [31680],
|
||||||
|
}
|
||||||
|
const capped = capTableRowHeights(model, 12960)
|
||||||
|
expect(capped.rowHeightsTwips).toEqual([12960])
|
||||||
|
expect(capped.rows[0][0].nestedTables![0].rowHeightsTwips).toEqual([12960])
|
||||||
|
expect(capTableRowHeights(model, 40000)).toBe(model)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -4,7 +4,8 @@
|
|||||||
* immediately.
|
* immediately.
|
||||||
*/
|
*/
|
||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import { docThemeCss } from '../src/renderer/doc-style-css'
|
import type { ParsedDocFull, StyleDisplay, StyleInfo } from '@genoffice/docx-engine'
|
||||||
|
import { docLineFactor, docStyleCss, docThemeCss } from '../src/renderer/doc-style-css'
|
||||||
|
|
||||||
describe('docThemeCss', () => {
|
describe('docThemeCss', () => {
|
||||||
it('emits body and heading fonts from the theme font pair', () => {
|
it('emits body and heading fonts from the theme font pair', () => {
|
||||||
@@ -25,3 +26,102 @@ describe('docThemeCss', () => {
|
|||||||
expect(docThemeCss({ major: '', minor: '' }, {})).toBe('')
|
expect(docThemeCss({ major: '', minor: '' }, {})).toBe('')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('docLineFactor — CJK factor source', () => {
|
||||||
|
const parsedWith = (
|
||||||
|
normalDisplay: StyleDisplay | undefined,
|
||||||
|
eastAsiaFont?: string,
|
||||||
|
): ParsedDocFull => {
|
||||||
|
const styles = new Map<string, StyleInfo>()
|
||||||
|
if (normalDisplay) {
|
||||||
|
styles.set('Normal', {
|
||||||
|
styleId: 'Normal',
|
||||||
|
name: 'Normal',
|
||||||
|
type: 'paragraph',
|
||||||
|
isDefault: true,
|
||||||
|
display: normalDisplay,
|
||||||
|
} as StyleInfo)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
styles,
|
||||||
|
docDefaults: eastAsiaFont ? { eastAsiaFont } : {},
|
||||||
|
blocks: [],
|
||||||
|
} as unknown as ParsedDocFull
|
||||||
|
}
|
||||||
|
|
||||||
|
it("Normal's declared EA face wins over docDefaults", () => {
|
||||||
|
const parsed = parsedWith({ font: 'Noto Sans KR', fontAscii: 'Calibri' }, 'SimSun')
|
||||||
|
expect(docLineFactor(parsed, true)).toBe(1.3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a Latin-only Normal (font === fontAscii) does not override the docDefaults EA font', () => {
|
||||||
|
const parsed = parsedWith({ font: 'Calibri', fontAscii: 'Calibri' }, 'SimSun')
|
||||||
|
expect(docLineFactor(parsed, true)).toBe(1.3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back to the SimSun-class factor without any declared EA font', () => {
|
||||||
|
expect(docLineFactor(parsedWith(undefined), true)).toBe(1.3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a same-slot Korean Normal (Malgun in both slots) still wins for the kr factor', () => {
|
||||||
|
;(globalThis as { CSS?: unknown }).CSS ??= { escape: (s: string) => s }
|
||||||
|
const parsed = parsedWith({ font: 'Malgun Gothic', fontAscii: 'Malgun Gothic' }, 'Batang')
|
||||||
|
expect(docStyleCss(parsed)).toContain('--doc-line-factor-kr:1.73')
|
||||||
|
expect(docLineFactor(parsed, true)).toBe(1.73)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('kr factor skips a Latin-only Normal and reads the docDefaults EA font', () => {
|
||||||
|
// node test env has no CSS.escape
|
||||||
|
;(globalThis as { CSS?: unknown }).CSS ??= { escape: (s: string) => s }
|
||||||
|
const parsed = parsedWith({ font: 'Calibri', fontAscii: 'Calibri' }, 'Malgun Gothic')
|
||||||
|
expect(docStyleCss(parsed)).toContain('--doc-line-factor-kr:1.73')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('docStyleCss — paragraph spacing fallback', () => {
|
||||||
|
const parsedWith = (docDefaults: Record<string, unknown>): ParsedDocFull => {
|
||||||
|
;(globalThis as { CSS?: unknown }).CSS ??= { escape: (s: string) => s }
|
||||||
|
return { styles: new Map(), docDefaults, blocks: [] } as unknown as ParsedDocFull
|
||||||
|
}
|
||||||
|
const blockRule = (css: string): string =>
|
||||||
|
css.split('\n').find((l) => l.startsWith('.doc-page p,')) ?? ''
|
||||||
|
|
||||||
|
it('undeclared spacing renders with zero margins like Word', () => {
|
||||||
|
const rule = blockRule(docStyleCss(parsedWith({})))
|
||||||
|
expect(rule).toContain('margin-top:0.0pt')
|
||||||
|
expect(rule).toContain('margin-bottom:0.0pt')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('declared docDefaults spacing still applies', () => {
|
||||||
|
const rule = blockRule(docStyleCss(parsedWith({ spaceAfterTwips: 200, spaceBeforeTwips: 40 })))
|
||||||
|
expect(rule).toContain('margin-top:2.0pt')
|
||||||
|
expect(rule).toContain('margin-bottom:10.0pt')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('docStyleCss — style indent vs list geometry', () => {
|
||||||
|
const parsedWithStyle = (display: StyleDisplay): ParsedDocFull => {
|
||||||
|
;(globalThis as { CSS?: unknown }).CSS ??= { escape: (s: string) => s }
|
||||||
|
const styles = new Map<string, StyleInfo>()
|
||||||
|
styles.set('ListParagraph', {
|
||||||
|
styleId: 'ListParagraph',
|
||||||
|
name: 'List Paragraph',
|
||||||
|
type: 'paragraph',
|
||||||
|
display,
|
||||||
|
} as StyleInfo)
|
||||||
|
return { styles, docDefaults: {}, blocks: [] } as unknown as ParsedDocFull
|
||||||
|
}
|
||||||
|
|
||||||
|
// Word overrides indents per property (direct > numbering > style), never adds them:
|
||||||
|
// the style indent must skip .doc-li margins and only feed the --li-left fallback
|
||||||
|
it('style w:ind skips list items and becomes the --li-left fallback', () => {
|
||||||
|
const css = docStyleCss(parsedWithStyle({ indentLeftTwips: 720 }))
|
||||||
|
expect(css).toContain(
|
||||||
|
'.doc-page [data-style="ListParagraph"]:not(.doc-li) { margin-inline-start:36.0pt }',
|
||||||
|
)
|
||||||
|
expect(css).toContain(
|
||||||
|
'.doc-page .doc-li[data-style="ListParagraph"] { --style-li-left:36.0pt }',
|
||||||
|
)
|
||||||
|
expect(css).not.toContain('margin-left')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -63,4 +63,12 @@ describe('checkMissingFonts', () => {
|
|||||||
stubCanvas(['黑体'])
|
stubCanvas(['黑体'])
|
||||||
expect(checkMissingFonts(['黑体'])).toEqual([])
|
expect(checkMissingFonts(['黑体'])).toEqual([])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('declared bundled subset faces still count as missing', () => {
|
||||||
|
// 'GenOffice Songti SC' (internal alias) resolves but is never reported
|
||||||
|
stubCanvas(['Noto Sans CJK SC', 'GenOffice Songti SC', 'STSong'])
|
||||||
|
expect(checkMissingFonts(['Noto Sans CJK SC'])).toEqual([
|
||||||
|
{ name: 'Noto Sans CJK SC', substitute: 'STSong' },
|
||||||
|
])
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import { Editor } from '@tiptap/core'
|
import { Editor } from '@tiptap/core'
|
||||||
import { editorExtensions } from '../src/renderer/editor/extensions'
|
import { editorExtensions } from '../src/renderer/editor/extensions'
|
||||||
|
import { blocksToPmDoc } from '../src/renderer/editor/convert'
|
||||||
import { fontAttrsFromFamilyChain } from '../src/renderer/editor/marks'
|
import { fontAttrsFromFamilyChain } from '../src/renderer/editor/marks'
|
||||||
import { cssDualFontFamily, cssFontFamily } from '../src/renderer/line-metrics'
|
import { cssDualFontFamily, cssFontFamily } from '../src/renderer/line-metrics'
|
||||||
|
|
||||||
@@ -80,9 +81,61 @@ describe('fontAttrsFromFamilyChain', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('skips internal GenOffice aliases even at the chain head', () => {
|
||||||
|
expect(
|
||||||
|
fontAttrsFromFamilyChain("'GenOffice Songti SC','STSong','SimSun','Noto Serif CJK SC',serif"),
|
||||||
|
).toEqual({ font: 'STSong' })
|
||||||
|
})
|
||||||
|
|
||||||
it('handles foreign single-family styles', () => {
|
it('handles foreign single-family styles', () => {
|
||||||
expect(fontAttrsFromFamilyChain('SimSun')).toEqual({ font: 'SimSun' })
|
expect(fontAttrsFromFamilyChain('SimSun')).toEqual({ font: 'SimSun' })
|
||||||
expect(fontAttrsFromFamilyChain('Calibri')).toEqual({ font: 'Calibri', fontAscii: 'Calibri' })
|
expect(fontAttrsFromFamilyChain('Calibri')).toEqual({ font: 'Calibri', fontAscii: 'Calibri' })
|
||||||
expect(fontAttrsFromFamilyChain(undefined)).toEqual({})
|
expect(fontAttrsFromFamilyChain(undefined)).toEqual({})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('complex-script (w:cs) render chain', () => {
|
||||||
|
function editorHtml(text: string, attrs: Record<string, unknown>): string {
|
||||||
|
const editor = new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: {
|
||||||
|
type: 'doc',
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: 'docParagraph',
|
||||||
|
attrs: { docxIndex: null },
|
||||||
|
content: [{ type: 'text', text, marks: [{ type: 'docTextStyle', attrs }] }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const html = editor.getHTML()
|
||||||
|
editor.destroy()
|
||||||
|
return html
|
||||||
|
}
|
||||||
|
|
||||||
|
it('csFont leads the family chain, then the Latin chain', () => {
|
||||||
|
const html = editorHtml('مرحبا Contract', {
|
||||||
|
font: 'Calibri',
|
||||||
|
fontAscii: 'Calibri',
|
||||||
|
csFont: 'Arabic Typesetting',
|
||||||
|
})
|
||||||
|
expect(html).toContain(
|
||||||
|
'font-family: "Arabic Typesetting", "Noto Naskh Arabic", "Geeza Pro", "Al Bayan", "Calibri", "Carlito GO", "Noto Sans CJK SC", sans-serif',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('run marks get csFont only when the text is complex-script', () => {
|
||||||
|
const runs = [
|
||||||
|
{ text: 'مرحبا', csFont: 'Amiri', font: 'Calibri', fontAscii: 'Calibri' },
|
||||||
|
{ text: 'latin only', csFont: 'Amiri', font: 'Calibri', fontAscii: 'Calibri' },
|
||||||
|
]
|
||||||
|
const doc = blocksToPmDoc([{ type: 'paragraph', docxIndex: 0, runs } as never])
|
||||||
|
const marks = doc.content![0].content!.map(
|
||||||
|
(n) => n.marks!.find((m) => m.type === 'docTextStyle')!.attrs!,
|
||||||
|
)
|
||||||
|
expect(marks[0].csFont).toBe('Amiri')
|
||||||
|
expect(marks[1].csFont).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -0,0 +1,211 @@
|
|||||||
|
/**
|
||||||
|
* Minimal WOFF2 reader for advance-width assertions on the bundled KR subsets.
|
||||||
|
*
|
||||||
|
* Only supports what those files use: CFF flavor (no glyf/loca transform),
|
||||||
|
* untransformed hmtx, cmap formats 4/12. Avoids adding a woff2 dependency.
|
||||||
|
*/
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { brotliDecompressSync } from 'node:zlib'
|
||||||
|
|
||||||
|
const KNOWN_TAGS = [
|
||||||
|
'cmap',
|
||||||
|
'head',
|
||||||
|
'hhea',
|
||||||
|
'hmtx',
|
||||||
|
'maxp',
|
||||||
|
'name',
|
||||||
|
'OS/2',
|
||||||
|
'post',
|
||||||
|
'cvt ',
|
||||||
|
'fpgm',
|
||||||
|
'glyf',
|
||||||
|
'loca',
|
||||||
|
'prep',
|
||||||
|
'CFF ',
|
||||||
|
'VORG',
|
||||||
|
'EBDT',
|
||||||
|
'EBLC',
|
||||||
|
'gasp',
|
||||||
|
'hdmx',
|
||||||
|
'kern',
|
||||||
|
'LTSH',
|
||||||
|
'PCLT',
|
||||||
|
'VDMX',
|
||||||
|
'vhea',
|
||||||
|
'vmtx',
|
||||||
|
'BASE',
|
||||||
|
'GDEF',
|
||||||
|
'GPOS',
|
||||||
|
'GSUB',
|
||||||
|
'EBSC',
|
||||||
|
'JSTF',
|
||||||
|
'MATH',
|
||||||
|
'CBDT',
|
||||||
|
'CBLC',
|
||||||
|
'COLR',
|
||||||
|
'CPAL',
|
||||||
|
'SVG ',
|
||||||
|
'sbix',
|
||||||
|
'acnt',
|
||||||
|
'avar',
|
||||||
|
'bdat',
|
||||||
|
'bloc',
|
||||||
|
'bsln',
|
||||||
|
'cvar',
|
||||||
|
'fdsc',
|
||||||
|
'feat',
|
||||||
|
'fmtx',
|
||||||
|
'fvar',
|
||||||
|
'gvar',
|
||||||
|
'hsty',
|
||||||
|
'just',
|
||||||
|
'lcar',
|
||||||
|
'mort',
|
||||||
|
'morx',
|
||||||
|
'opbd',
|
||||||
|
'prop',
|
||||||
|
'trak',
|
||||||
|
'Zapf',
|
||||||
|
'Silf',
|
||||||
|
'Glat',
|
||||||
|
'Gloc',
|
||||||
|
'Feat',
|
||||||
|
'Sill',
|
||||||
|
]
|
||||||
|
|
||||||
|
function uintBase128(buf: Buffer, off: number): [number, number] {
|
||||||
|
let v = 0
|
||||||
|
for (let i = 0; i < 5; i++) {
|
||||||
|
const b = buf[off++]
|
||||||
|
v = v * 128 + (b & 0x7f)
|
||||||
|
if (!(b & 0x80)) return [v, off]
|
||||||
|
}
|
||||||
|
throw new Error('bad UIntBase128')
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Woff2Font {
|
||||||
|
unitsPerEm: number
|
||||||
|
tables: Map<string, Buffer>
|
||||||
|
cmap: Map<number, number>
|
||||||
|
advances: number[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readWoff2(path: string): Woff2Font {
|
||||||
|
const buf = readFileSync(path)
|
||||||
|
if (buf.toString('latin1', 0, 4) !== 'wOF2') throw new Error('not woff2')
|
||||||
|
const numTables = buf.readUInt16BE(12)
|
||||||
|
const totalCompressedSize = buf.readUInt32BE(20)
|
||||||
|
let off = 48
|
||||||
|
const entries: { tag: string; len: number }[] = []
|
||||||
|
for (let i = 0; i < numTables; i++) {
|
||||||
|
const flags = buf[off++]
|
||||||
|
let tag: string
|
||||||
|
if ((flags & 0x3f) === 0x3f) {
|
||||||
|
tag = buf.toString('latin1', off, off + 4)
|
||||||
|
off += 4
|
||||||
|
} else {
|
||||||
|
tag = KNOWN_TAGS[flags & 0x3f]
|
||||||
|
}
|
||||||
|
const transform = (flags >> 6) & 0x3
|
||||||
|
let len: number
|
||||||
|
;[len, off] = uintBase128(buf, off)
|
||||||
|
const transformed = tag === 'glyf' || tag === 'loca' ? transform !== 3 : transform !== 0
|
||||||
|
if (transformed) throw new Error(`transformed table ${tag} unsupported`)
|
||||||
|
entries.push({ tag, len })
|
||||||
|
}
|
||||||
|
const raw = brotliDecompressSync(buf.subarray(off, off + totalCompressedSize))
|
||||||
|
const tables = new Map<string, Buffer>()
|
||||||
|
let pos = 0
|
||||||
|
for (const { tag, len } of entries) {
|
||||||
|
tables.set(tag, raw.subarray(pos, pos + len))
|
||||||
|
pos += len
|
||||||
|
}
|
||||||
|
const head = tables.get('head')!
|
||||||
|
const hhea = tables.get('hhea')!
|
||||||
|
const maxp = tables.get('maxp')!
|
||||||
|
const hmtxBuf = tables.get('hmtx')!
|
||||||
|
const numGlyphs = maxp.readUInt16BE(4)
|
||||||
|
const numHMetrics = hhea.readUInt16BE(34)
|
||||||
|
const advances: number[] = []
|
||||||
|
for (let g = 0; g < numGlyphs; g++) {
|
||||||
|
advances.push(
|
||||||
|
g < numHMetrics ? hmtxBuf.readUInt16BE(g * 4) : hmtxBuf.readUInt16BE((numHMetrics - 1) * 4),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
unitsPerEm: head.readUInt16BE(18),
|
||||||
|
tables,
|
||||||
|
cmap: parseCmap(tables.get('cmap')!),
|
||||||
|
advances,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseCmap(cmap: Buffer): Map<number, number> {
|
||||||
|
const n = cmap.readUInt16BE(2)
|
||||||
|
let best = -1
|
||||||
|
let bestScore = -1
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const platform = cmap.readUInt16BE(4 + i * 8)
|
||||||
|
const encoding = cmap.readUInt16BE(6 + i * 8)
|
||||||
|
const offset = cmap.readUInt32BE(8 + i * 8)
|
||||||
|
const format = cmap.readUInt16BE(offset)
|
||||||
|
const score =
|
||||||
|
platform === 3 && encoding === 10 && format === 12
|
||||||
|
? 3
|
||||||
|
: platform === 3 && encoding === 1 && format === 4
|
||||||
|
? 2
|
||||||
|
: format === 12 || format === 4
|
||||||
|
? 1
|
||||||
|
: 0
|
||||||
|
if (score > bestScore) {
|
||||||
|
bestScore = score
|
||||||
|
best = offset
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const out = new Map<number, number>()
|
||||||
|
const format = cmap.readUInt16BE(best)
|
||||||
|
if (format === 12) {
|
||||||
|
const nGroups = cmap.readUInt32BE(best + 12)
|
||||||
|
for (let i = 0; i < nGroups; i++) {
|
||||||
|
const p = best + 16 + i * 12
|
||||||
|
const start = cmap.readUInt32BE(p)
|
||||||
|
const end = cmap.readUInt32BE(p + 4)
|
||||||
|
const gid = cmap.readUInt32BE(p + 8)
|
||||||
|
for (let c = start; c <= end; c++) out.set(c, gid + (c - start))
|
||||||
|
}
|
||||||
|
} else if (format === 4) {
|
||||||
|
const segCountX2 = cmap.readUInt16BE(best + 6)
|
||||||
|
const segCount = segCountX2 / 2
|
||||||
|
const endP = best + 14
|
||||||
|
const startP = endP + segCountX2 + 2
|
||||||
|
const deltaP = startP + segCountX2
|
||||||
|
const rangeP = deltaP + segCountX2
|
||||||
|
for (let s = 0; s < segCount; s++) {
|
||||||
|
const end = cmap.readUInt16BE(endP + s * 2)
|
||||||
|
const start = cmap.readUInt16BE(startP + s * 2)
|
||||||
|
const delta = cmap.readInt16BE(deltaP + s * 2)
|
||||||
|
const rangeOff = cmap.readUInt16BE(rangeP + s * 2)
|
||||||
|
for (let c = start; c <= end && c !== 0xffff; c++) {
|
||||||
|
let gid: number
|
||||||
|
if (rangeOff === 0) {
|
||||||
|
gid = (c + delta) & 0xffff
|
||||||
|
} else {
|
||||||
|
const gi = rangeP + s * 2 + rangeOff + (c - start) * 2
|
||||||
|
gid = cmap.readUInt16BE(gi)
|
||||||
|
if (gid !== 0) gid = (gid + delta) & 0xffff
|
||||||
|
}
|
||||||
|
if (gid !== 0) out.set(c, gid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new Error(`cmap format ${format} unsupported`)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** advance of a codepoint in em (throws if unmapped) */
|
||||||
|
export function advanceEm(font: Woff2Font, cp: number): number {
|
||||||
|
const gid = font.cmap.get(cp)
|
||||||
|
if (gid === undefined) throw new Error(`U+${cp.toString(16)} not in cmap`)
|
||||||
|
return font.advances[gid] / font.unitsPerEm
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { PAGE_MARK, TOTAL_PAGES_MARK, type HeaderFooter } from '@genoffice/docx-engine'
|
||||||
|
import { hfHasPageField, hfWithoutPageMarks, makeGapHfEl } from '../src/renderer/editor/hf-dom'
|
||||||
|
import { restingHfAreaVariant } from '../src/renderer/doc-state'
|
||||||
|
|
||||||
|
describe('page-number substitution (PAGE_MARK)', () => {
|
||||||
|
it('fills the PAGE field position and keeps a literal # intact', () => {
|
||||||
|
const value: HeaderFooter = {
|
||||||
|
text: `[Course #] | Page ${PAGE_MARK}`,
|
||||||
|
pageNumber: true,
|
||||||
|
paras: [{ align: 'center', runs: [{ text: '[Course #] | Page ' }, { text: PAGE_MARK }] }],
|
||||||
|
}
|
||||||
|
const el = makeGapHfEl({ kind: 'footer', value, pageNo: 3, pageTotal: 7 })
|
||||||
|
expect(el.textContent).toBe('[Course #] | Page 3')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('legacy user-typed # (no PAGE_MARK anywhere) still substitutes', () => {
|
||||||
|
const value: HeaderFooter = {
|
||||||
|
text: '- # -',
|
||||||
|
pageNumber: true,
|
||||||
|
paras: [{ align: 'center', runs: [{ text: '- # -' }] }],
|
||||||
|
}
|
||||||
|
const el = makeGapHfEl({ kind: 'footer', value, pageNo: 2, pageTotal: 5 })
|
||||||
|
expect(el.textContent).toBe('- 2 -')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('substitutes every PAGE_MARK and the NUMPAGES total', () => {
|
||||||
|
const value: HeaderFooter = {
|
||||||
|
text: `${PAGE_MARK} / ${TOTAL_PAGES_MARK}`,
|
||||||
|
pageNumber: true,
|
||||||
|
paras: [{ runs: [{ text: `${PAGE_MARK} / ${TOTAL_PAGES_MARK}` }] }],
|
||||||
|
}
|
||||||
|
const el = makeGapHfEl({ kind: 'footer', value, pageNo: 4, pageTotal: 9 })
|
||||||
|
expect(el.textContent).toBe('4 / 9')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('pageNumber without any marker appends a PAGE_MARK run (legacy single line)', () => {
|
||||||
|
const value: HeaderFooter = { text: 'Confidential', pageNumber: true }
|
||||||
|
const el = makeGapHfEl({ kind: 'footer', value, pageNo: 6, pageTotal: 8 })
|
||||||
|
expect(el.textContent).toBe('Confidential 6')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('restingHfAreaVariant (canvas area variant when no chip is picked)', () => {
|
||||||
|
it('header area sits on page 1: first variant when titlePg is on', () => {
|
||||||
|
expect(restingHfAreaVariant('header', { titlePg: true, evenOddHf: false, pageCount: 2 })).toBe(
|
||||||
|
'first',
|
||||||
|
)
|
||||||
|
expect(restingHfAreaVariant('header', { titlePg: false, evenOddHf: false, pageCount: 2 })).toBe(
|
||||||
|
'default',
|
||||||
|
)
|
||||||
|
expect(restingHfAreaVariant('header', { titlePg: false, evenOddHf: true, pageCount: 2 })).toBe(
|
||||||
|
'default',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('footer area sits on the last page', () => {
|
||||||
|
expect(restingHfAreaVariant('footer', { titlePg: true, evenOddHf: false, pageCount: 1 })).toBe(
|
||||||
|
'first',
|
||||||
|
)
|
||||||
|
expect(restingHfAreaVariant('footer', { titlePg: true, evenOddHf: false, pageCount: 2 })).toBe(
|
||||||
|
'default',
|
||||||
|
)
|
||||||
|
expect(
|
||||||
|
restingHfAreaVariant('footer', {
|
||||||
|
titlePg: false,
|
||||||
|
evenOddHf: true,
|
||||||
|
pageCount: 2,
|
||||||
|
lastPageNo: 2,
|
||||||
|
}),
|
||||||
|
).toBe('even')
|
||||||
|
expect(
|
||||||
|
restingHfAreaVariant('footer', {
|
||||||
|
titlePg: false,
|
||||||
|
evenOddHf: true,
|
||||||
|
pageCount: 3,
|
||||||
|
lastPageNo: 3,
|
||||||
|
}),
|
||||||
|
).toBe('default')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('parity follows the displayed last page number, not the physical count', () => {
|
||||||
|
expect(
|
||||||
|
restingHfAreaVariant('footer', {
|
||||||
|
titlePg: false,
|
||||||
|
evenOddHf: true,
|
||||||
|
pageCount: 3,
|
||||||
|
lastPageNo: 4,
|
||||||
|
}),
|
||||||
|
).toBe('even')
|
||||||
|
expect(
|
||||||
|
restingHfAreaVariant('footer', {
|
||||||
|
titlePg: false,
|
||||||
|
evenOddHf: true,
|
||||||
|
pageCount: 4,
|
||||||
|
lastPageNo: 3,
|
||||||
|
}),
|
||||||
|
).toBe('default')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('hfWithoutPageMarks (ribbon Remove Page Numbers)', () => {
|
||||||
|
it('strips only PAGE_MARK fields, keeping literal # and rich formatting', () => {
|
||||||
|
const value: HeaderFooter = {
|
||||||
|
text: `[Course #] | Page ${PAGE_MARK}`,
|
||||||
|
pageNumber: true,
|
||||||
|
paras: [
|
||||||
|
{ align: 'right', runs: [{ text: '[Course #] | Page ', bold: true }, { text: PAGE_MARK }] },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
expect(hfWithoutPageMarks(value)).toEqual({
|
||||||
|
text: '[Course #] | Page ',
|
||||||
|
pageNumber: false,
|
||||||
|
paras: [{ align: 'right', runs: [{ text: '[Course #] | Page ', bold: true }] }],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('legacy part (no sentinel): strips only the first user-typed #', () => {
|
||||||
|
const value: HeaderFooter = {
|
||||||
|
text: 'p# of #',
|
||||||
|
pageNumber: true,
|
||||||
|
paras: [{ align: 'center', runs: [{ text: 'p# of #' }] }],
|
||||||
|
}
|
||||||
|
expect(hfWithoutPageMarks(value)).toEqual({
|
||||||
|
text: 'p of #',
|
||||||
|
pageNumber: false,
|
||||||
|
paras: [{ align: 'center', runs: [{ text: 'p of #' }] }],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('page-number-only footer removes as empty (no leftover paragraph shell)', () => {
|
||||||
|
const value: HeaderFooter = {
|
||||||
|
text: PAGE_MARK,
|
||||||
|
pageNumber: true,
|
||||||
|
paras: [{ align: 'center', runs: [{ text: PAGE_MARK }] }],
|
||||||
|
}
|
||||||
|
const next = hfWithoutPageMarks(value)
|
||||||
|
expect(next).toEqual({ text: '', pageNumber: false })
|
||||||
|
expect(next.paras).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('multi-paragraph part: the dedicated page-number paragraph is dropped, blank lines stay', () => {
|
||||||
|
const value: HeaderFooter = {
|
||||||
|
text: `Confidential${PAGE_MARK}`,
|
||||||
|
pageNumber: true,
|
||||||
|
paras: [
|
||||||
|
{ align: 'left', runs: [{ text: 'Confidential', bold: true }] },
|
||||||
|
{ align: 'left', runs: [] },
|
||||||
|
{ align: 'center', runs: [{ text: PAGE_MARK }] },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
expect(hfWithoutPageMarks(value)).toEqual({
|
||||||
|
text: 'Confidential',
|
||||||
|
pageNumber: false,
|
||||||
|
paras: [
|
||||||
|
{ align: 'left', runs: [{ text: 'Confidential', bold: true }] },
|
||||||
|
{ align: 'left', runs: [] },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('layout-table rows survive removal untouched (display-only; save keeps the w:tbl bytes)', () => {
|
||||||
|
const cells = [
|
||||||
|
{ runs: [{ text: 'ACME Corp' }], widthPct: 50 },
|
||||||
|
{ runs: [{ text: `Page ${PAGE_MARK}` }], widthPct: 50 },
|
||||||
|
]
|
||||||
|
const value: HeaderFooter = {
|
||||||
|
text: `ACME CorpPage ${PAGE_MARK}`,
|
||||||
|
pageNumber: true,
|
||||||
|
paras: [{ runs: [], cells }],
|
||||||
|
}
|
||||||
|
const next = hfWithoutPageMarks(value)
|
||||||
|
expect(next.paras).toEqual([{ runs: [], cells }])
|
||||||
|
expect(next.pageNumber).toBe(false)
|
||||||
|
expect(next.text).toContain('ACME Corp')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('mixed part: the dedicated page paragraph goes, the table row stays', () => {
|
||||||
|
const row = { runs: [], cells: [{ runs: [{ text: 'Logo | Title' }] }] }
|
||||||
|
const value: HeaderFooter = {
|
||||||
|
text: `Logo | Title${PAGE_MARK}`,
|
||||||
|
pageNumber: true,
|
||||||
|
paras: [row, { align: 'center', runs: [{ text: PAGE_MARK }] }],
|
||||||
|
}
|
||||||
|
expect(hfWithoutPageMarks(value)).toEqual({
|
||||||
|
text: 'Logo | Title',
|
||||||
|
pageNumber: false,
|
||||||
|
paras: [row],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('hfHasPageField ignores a literal # when no page number is set', () => {
|
||||||
|
expect(hfHasPageField({ text: 'Item #5', pageNumber: false })).toBe(false)
|
||||||
|
expect(hfHasPageField({ text: `p ${PAGE_MARK}`, pageNumber: true })).toBe(true)
|
||||||
|
expect(hfHasPageField(null)).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Editor } from '@tiptap/core'
|
import { Editor } from '@tiptap/core'
|
||||||
import { NodeSelection } from '@tiptap/pm/state'
|
import { NodeSelection } from '@tiptap/pm/state'
|
||||||
import { parseDocx, saveDocx } from '@genoffice/docx-engine'
|
import { parseDocx, saveDocx } from '@genoffice/docx-engine'
|
||||||
|
import JSZip from 'jszip'
|
||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import {
|
import {
|
||||||
buildDocx,
|
buildDocx,
|
||||||
@@ -9,8 +10,8 @@ import {
|
|||||||
import { blocksToPmDoc, pmDocToSavePlan, type PmNode } from '../src/renderer/editor/convert'
|
import { blocksToPmDoc, pmDocToSavePlan, type PmNode } from '../src/renderer/editor/convert'
|
||||||
import { editorExtensions } from '../src/renderer/editor/extensions'
|
import { editorExtensions } from '../src/renderer/editor/extensions'
|
||||||
|
|
||||||
async function openImageDoc() {
|
async function openImageDoc(bodyXml = IMAGE_PARAGRAPH_XML, extraRels?: string) {
|
||||||
const source = await buildDocx({ bodyXml: IMAGE_PARAGRAPH_XML, withImage: true })
|
const source = await buildDocx({ bodyXml, withImage: true, extraRels })
|
||||||
const parsed = await parseDocx(source)
|
const parsed = await parseDocx(source)
|
||||||
const editor = new Editor({
|
const editor = new Editor({
|
||||||
element: document.createElement('div'),
|
element: document.createElement('div'),
|
||||||
@@ -88,4 +89,200 @@ describe('image wrap in the editor', () => {
|
|||||||
editor.destroy()
|
editor.destroy()
|
||||||
editor2.destroy()
|
editor2.destroy()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('rotation + flip round-trip through a:xfrm and clear cleanly', async () => {
|
||||||
|
// the minimal shared fixture has no pic:spPr; rotation lives on the pic xfrm
|
||||||
|
const withXfrm = IMAGE_PARAGRAPH_XML.replace(
|
||||||
|
'</pic:blipFill></pic:pic>',
|
||||||
|
'</pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm>' +
|
||||||
|
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic>',
|
||||||
|
)
|
||||||
|
const source = await buildDocx({ bodyXml: withXfrm, withImage: true })
|
||||||
|
const parsed = await parseDocx(source)
|
||||||
|
const editor = new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: blocksToPmDoc(parsed.blocks) as never,
|
||||||
|
})
|
||||||
|
editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0)))
|
||||||
|
editor.commands.updateAttributes('docProtected', { imageRotDeg: 90, imageFlipH: true })
|
||||||
|
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
|
||||||
|
expect(plan.changedCount).toBe(1)
|
||||||
|
const saved = await saveDocx(parsed, plan.saveBlocks)
|
||||||
|
|
||||||
|
const reparsed = await parseDocx(saved)
|
||||||
|
expect(reparsed.blocks[0].imageRotDeg).toBe(90)
|
||||||
|
expect(reparsed.blocks[0].imageFlipH).toBe(true)
|
||||||
|
expect(reparsed.blocks[0].imageFlipV).toBeUndefined()
|
||||||
|
|
||||||
|
// untouched re-save stays byte-identical; clearing removes the attributes
|
||||||
|
const editor2 = new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: blocksToPmDoc(reparsed.blocks) as never,
|
||||||
|
})
|
||||||
|
const plan2 = pmDocToSavePlan(editor2.getJSON() as PmNode, reparsed.blocks)
|
||||||
|
expect(plan2.changedCount).toBe(0)
|
||||||
|
expect(await saveDocx(reparsed, plan2.saveBlocks)).toEqual(saved)
|
||||||
|
|
||||||
|
editor2.view.dispatch(editor2.state.tr.setSelection(NodeSelection.create(editor2.state.doc, 0)))
|
||||||
|
editor2.commands.updateAttributes('docProtected', { imageRotDeg: null, imageFlipH: false })
|
||||||
|
const plan3 = pmDocToSavePlan(editor2.getJSON() as PmNode, reparsed.blocks)
|
||||||
|
expect(plan3.changedCount).toBe(1)
|
||||||
|
const cleared = await saveDocx(reparsed, plan3.saveBlocks)
|
||||||
|
const p3 = await parseDocx(cleared)
|
||||||
|
expect(p3.blocks[0].imageRotDeg).toBeUndefined()
|
||||||
|
expect(p3.blocks[0].imageFlipH).toBeUndefined()
|
||||||
|
expect(cleared.length).toBeGreaterThan(0)
|
||||||
|
editor.destroy()
|
||||||
|
editor2.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('imageReplace swaps bytes in place, keeping the drawing XML and wrap', async () => {
|
||||||
|
// 1x1 transparent GIF
|
||||||
|
const GIF_B64 = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
|
||||||
|
const { editor, parsed } = await openImageDoc()
|
||||||
|
editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0)))
|
||||||
|
editor.commands.updateAttributes('docProtected', {
|
||||||
|
imageWrap: 'square-right',
|
||||||
|
imageReplace: { base64: GIF_B64, mime: 'image/gif' },
|
||||||
|
})
|
||||||
|
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
|
||||||
|
expect(plan.changedCount).toBe(1)
|
||||||
|
const saved = await saveDocx(parsed, plan.saveBlocks)
|
||||||
|
|
||||||
|
const reparsed = await parseDocx(saved)
|
||||||
|
const blk = reparsed.blocks[0]
|
||||||
|
// still an original image block (docxIndex-anchored), wrap applied, new bytes served
|
||||||
|
expect(blk.type).toBe('image')
|
||||||
|
expect(blk.imageWrap).toBe('square-right')
|
||||||
|
expect(blk.imageDataUrl?.startsWith('data:image/gif;base64,')).toBe(true)
|
||||||
|
|
||||||
|
// an untouched re-save of the reparsed doc stays byte-identical
|
||||||
|
const editor2 = new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: blocksToPmDoc(reparsed.blocks) as never,
|
||||||
|
})
|
||||||
|
const plan2 = pmDocToSavePlan(editor2.getJSON() as PmNode, reparsed.blocks)
|
||||||
|
expect(plan2.changedCount).toBe(0)
|
||||||
|
expect(await saveDocx(reparsed, plan2.saveBlocks)).toEqual(saved)
|
||||||
|
editor.destroy()
|
||||||
|
editor2.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('flip-only saves keep a Word-authored effectExtent untouched', async () => {
|
||||||
|
// Flips do not change the bounding box: Word-authored padding for shadow /
|
||||||
|
// glow effects must survive a mirror toggle byte-for-byte
|
||||||
|
const wordEffectExtent = '<wp:effectExtent l="9525" t="19050" r="28575" b="38100"/>'
|
||||||
|
const withEffect = IMAGE_PARAGRAPH_XML.replace(
|
||||||
|
'<wp:extent cx="914400" cy="914400"/>',
|
||||||
|
`<wp:extent cx="914400" cy="914400"/>${wordEffectExtent}`,
|
||||||
|
).replace(
|
||||||
|
'</pic:blipFill></pic:pic>',
|
||||||
|
'</pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm>' +
|
||||||
|
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic>',
|
||||||
|
)
|
||||||
|
const source = await buildDocx({ bodyXml: withEffect, withImage: true })
|
||||||
|
const parsed = await parseDocx(source)
|
||||||
|
const editor = new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: blocksToPmDoc(parsed.blocks) as never,
|
||||||
|
})
|
||||||
|
editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0)))
|
||||||
|
editor.commands.updateAttributes('docProtected', { imageFlipH: true })
|
||||||
|
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
|
||||||
|
expect(plan.changedCount).toBe(1)
|
||||||
|
const saved = await saveDocx(parsed, plan.saveBlocks)
|
||||||
|
const docXml = await (await JSZip.loadAsync(saved)).file('word/document.xml')!.async('string')
|
||||||
|
expect(docXml).toContain('flipH="1"')
|
||||||
|
expect(docXml).toContain(wordEffectExtent)
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('90° rotation of a non-square image records the bounding-box overflow in effectExtent', async () => {
|
||||||
|
// 2:1 landscape picture (1828800 x 914400 EMU): turned 90° it overflows the
|
||||||
|
// unrotated footprint by (w-h)/2 = 457200 EMU on top/bottom, and needs that
|
||||||
|
// recorded in wp:effectExtent or Word crops / misplaces the drawing
|
||||||
|
const nonSquare = IMAGE_PARAGRAPH_XML.replace(
|
||||||
|
'<wp:extent cx="914400" cy="914400"/>',
|
||||||
|
'<wp:extent cx="1828800" cy="914400"/>',
|
||||||
|
).replace(
|
||||||
|
'</pic:blipFill></pic:pic>',
|
||||||
|
'</pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1828800" cy="914400"/></a:xfrm>' +
|
||||||
|
'<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic>',
|
||||||
|
)
|
||||||
|
const source = await buildDocx({ bodyXml: nonSquare, withImage: true })
|
||||||
|
const parsed = await parseDocx(source)
|
||||||
|
const editor = new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: blocksToPmDoc(parsed.blocks) as never,
|
||||||
|
})
|
||||||
|
editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0)))
|
||||||
|
editor.commands.updateAttributes('docProtected', { imageRotDeg: 90 })
|
||||||
|
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
|
||||||
|
expect(plan.changedCount).toBe(1)
|
||||||
|
const saved = await saveDocx(parsed, plan.saveBlocks)
|
||||||
|
|
||||||
|
const zip = await JSZip.loadAsync(saved)
|
||||||
|
const docXml = await zip.file('word/document.xml')!.async('string')
|
||||||
|
// (bboxW - cx)/2 = (914400 - 1828800)/2 clamps to 0; (bboxH - cy)/2 = 457200
|
||||||
|
expect(docXml).toContain('<wp:effectExtent l="0" t="457200" r="0" b="457200"/>')
|
||||||
|
// clearing the rotation zeroes the extra space again
|
||||||
|
const reparsed = await parseDocx(saved)
|
||||||
|
const editor2 = new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: blocksToPmDoc(reparsed.blocks) as never,
|
||||||
|
})
|
||||||
|
editor2.view.dispatch(editor2.state.tr.setSelection(NodeSelection.create(editor2.state.doc, 0)))
|
||||||
|
editor2.commands.updateAttributes('docProtected', { imageRotDeg: null })
|
||||||
|
const cleared = await saveDocx(
|
||||||
|
reparsed,
|
||||||
|
pmDocToSavePlan(editor2.getJSON() as PmNode, reparsed.blocks).saveBlocks,
|
||||||
|
)
|
||||||
|
const clearedXml = await (
|
||||||
|
await JSZip.loadAsync(cleared)
|
||||||
|
)
|
||||||
|
.file('word/document.xml')!
|
||||||
|
.async('string')
|
||||||
|
expect(clearedXml).toContain('<wp:effectExtent l="0" t="0" r="0" b="0"/>')
|
||||||
|
editor.destroy()
|
||||||
|
editor2.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('imageReplace strips a stale external r:link and svgBlip extension', async () => {
|
||||||
|
const GIF_B64 = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
|
||||||
|
// Word "insert and link" SVG picture: the blip carries the raster fallback
|
||||||
|
// (r:embed), an external link (r:link), and the Office-2016 svgBlip extension
|
||||||
|
const linkedBody = IMAGE_PARAGRAPH_XML.replace(
|
||||||
|
'<a:blip r:embed="rId10"/>',
|
||||||
|
'<a:blip r:embed="rId10" r:link="rId11">' +
|
||||||
|
'<a:extLst><a:ext uri="{96DAC541-7B7A-43D3-8B79-37D633B846F1}">' +
|
||||||
|
'<asvg:svgBlip xmlns:asvg="http://schemas.microsoft.com/office/drawing/2016/SVG/main" r:embed="rId10"/>' +
|
||||||
|
'</a:ext></a:extLst></a:blip>',
|
||||||
|
)
|
||||||
|
const linkRel =
|
||||||
|
'<Relationship Id="rId11" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="file:///C:/old.png" TargetMode="External"/>'
|
||||||
|
const { editor, parsed } = await openImageDoc(linkedBody, linkRel)
|
||||||
|
editor.view.dispatch(editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, 0)))
|
||||||
|
editor.commands.updateAttributes('docProtected', {
|
||||||
|
imageReplace: { base64: GIF_B64, mime: 'image/gif' },
|
||||||
|
})
|
||||||
|
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
|
||||||
|
expect(plan.changedCount).toBe(1)
|
||||||
|
const saved = await saveDocx(parsed, plan.saveBlocks)
|
||||||
|
|
||||||
|
// Word would refresh a surviving r:link from the old file, and prefers a
|
||||||
|
// surviving svgBlip over the retargeted embed — both must be gone
|
||||||
|
const zip = await JSZip.loadAsync(saved)
|
||||||
|
const docXml = await zip.file('word/document.xml')!.async('string')
|
||||||
|
expect(docXml).not.toContain('r:link')
|
||||||
|
expect(docXml).not.toContain('svgBlip')
|
||||||
|
const reparsed2 = await parseDocx(saved)
|
||||||
|
expect(reparsed2.blocks[0].imageDataUrl?.startsWith('data:image/gif;base64,')).toBe(true)
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
/**
|
||||||
|
* Advance-width contract of the bundled KR subsets (fonts/README.md):
|
||||||
|
* hangul 1.0em; serif digits/space follow Batang; sans Basic Latin follows
|
||||||
|
* Malgun Gothic (tools/normalize-kr-sans-hmtx.py). A regenerated woff2 that
|
||||||
|
* loses the normalization would silently shift Korean line breaks vs Word.
|
||||||
|
*/
|
||||||
|
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 sans = readWoff2(join(FONTS, 'GenOfficeSansKR-Regular-subset.woff2'))
|
||||||
|
const serif = readWoff2(join(FONTS, 'GenOfficeSerifKR-Regular-subset.woff2'))
|
||||||
|
|
||||||
|
describe('GenOffice Sans KR (Malgun-normalized)', () => {
|
||||||
|
it('hangul syllables and compatibility jamo stay 1.0em', () => {
|
||||||
|
for (const cp of [0xac00, 0xae4e, 0xd558, 0x3131]) {
|
||||||
|
expect(advanceEm(sans, cp), `U+${cp.toString(16)}`).toBe(1)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('space and digits match Malgun Gothic', () => {
|
||||||
|
expect(advanceEm(sans, 0x20)).toBeCloseTo(0.352, 3)
|
||||||
|
expect(advanceEm(sans, 0xa0)).toBeCloseTo(0.352, 3)
|
||||||
|
for (let cp = 0x30; cp <= 0x39; cp++) {
|
||||||
|
expect(advanceEm(sans, cp), `digit ${cp - 0x30}`).toBeCloseTo(0.551, 3)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('Basic Latin letters match Malgun Gothic', () => {
|
||||||
|
const expected: Record<string, number> = {
|
||||||
|
A: 0.658,
|
||||||
|
J: 0.36,
|
||||||
|
M: 0.917,
|
||||||
|
W: 0.954,
|
||||||
|
a: 0.52,
|
||||||
|
i: 0.246,
|
||||||
|
m: 0.88,
|
||||||
|
'.': 0.219,
|
||||||
|
',': 0.219,
|
||||||
|
'(': 0.305,
|
||||||
|
')': 0.305,
|
||||||
|
'/': 0.396,
|
||||||
|
'%': 0.836,
|
||||||
|
}
|
||||||
|
for (const [ch, adv] of Object.entries(expected)) {
|
||||||
|
expect(advanceEm(sans, ch.codePointAt(0)!), ch).toBeCloseTo(adv, 3)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('fullwidth forms keep the 1.0em CJK advance', () => {
|
||||||
|
expect(advanceEm(sans, 0x3000)).toBe(1)
|
||||||
|
expect(advanceEm(sans, 0xff10)).toBe(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('GenOffice Serif KR (Batang-normalized)', () => {
|
||||||
|
it('hangul 1.0em, digits 0.596em, space 0.333em', () => {
|
||||||
|
expect(advanceEm(serif, 0xac00)).toBe(1)
|
||||||
|
expect(advanceEm(serif, 0x3131)).toBe(1)
|
||||||
|
expect(advanceEm(serif, 0x20)).toBeCloseTo(0.333, 3)
|
||||||
|
for (let cp = 0x30; cp <= 0x39; cp++) {
|
||||||
|
expect(advanceEm(serif, cp), `digit ${cp - 0x30}`).toBeCloseTo(0.596, 3)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
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'))
|
||||||
|
for (const cp of [0xff0d, 0xff0f, 0xff3c, 0xff3f, 0xff5e]) {
|
||||||
|
expect(advanceEm(sc, cp), `U+${cp.toString(16)}`).toBe(1)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -12,6 +12,26 @@ const factorOf = (editor: Editor, index = 0): string => {
|
|||||||
return p.style.getPropertyValue('--doc-line-factor')
|
return p.style.getPropertyValue('--doc-line-factor')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// jsdom's CSSOM drops the min() font-size, so assert the --doc-strut custom
|
||||||
|
// property it references (font-size:min(var(--doc-strut), 1em) rides along)
|
||||||
|
const fontSizeOf = (editor: Editor, index = 0): string => {
|
||||||
|
const p = editor.view.dom.querySelectorAll('p')[index] as HTMLElement
|
||||||
|
return p.style.getPropertyValue('--doc-strut')
|
||||||
|
}
|
||||||
|
|
||||||
|
const sizedParagraph = (text: string, sizeHalfPoints: number) =>
|
||||||
|
({
|
||||||
|
type: 'doc',
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: 'docParagraph',
|
||||||
|
content: [
|
||||||
|
{ type: 'text', text, marks: [{ type: 'docTextStyle', attrs: { sizeHalfPoints } }] },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}) as never
|
||||||
|
|
||||||
describe('live line-height factor decorations', () => {
|
describe('live line-height factor decorations', () => {
|
||||||
it('typing CJK into a paragraph created empty switches its factor to 1.3', () => {
|
it('typing CJK into a paragraph created empty switches its factor to 1.3', () => {
|
||||||
const editor = new Editor({
|
const editor = new Editor({
|
||||||
@@ -46,3 +66,49 @@ describe('live line-height factor decorations', () => {
|
|||||||
editor.destroy()
|
editor.destroy()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('live strut font-size decorations', () => {
|
||||||
|
it('changing the run font size updates the paragraph strut font-size', () => {
|
||||||
|
const editor = new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: sizedParagraph('sized', 24),
|
||||||
|
})
|
||||||
|
expect(fontSizeOf(editor)).toBe('12pt')
|
||||||
|
|
||||||
|
editor.commands.setTextSelection({ from: 1, to: 6 })
|
||||||
|
editor.commands.setMark('docTextStyle', { sizeHalfPoints: 28 })
|
||||||
|
expect(fontSizeOf(editor)).toBe('14pt')
|
||||||
|
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('removes the strut font-size when part of the text loses its explicit size', () => {
|
||||||
|
const editor = new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: sizedParagraph('sized', 24),
|
||||||
|
})
|
||||||
|
expect(fontSizeOf(editor)).toBe('12pt')
|
||||||
|
|
||||||
|
editor.commands.setTextSelection({ from: 1, to: 3 })
|
||||||
|
editor.commands.unsetMark('docTextStyle')
|
||||||
|
expect(fontSizeOf(editor)).toBe('')
|
||||||
|
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('deleting the only sized run removes the paragraph strut font-size', () => {
|
||||||
|
const editor = new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: sizedParagraph('sized', 24),
|
||||||
|
})
|
||||||
|
expect(fontSizeOf(editor)).toBe('12pt')
|
||||||
|
|
||||||
|
editor.commands.deleteRange({ from: 1, to: 6 })
|
||||||
|
expect(fontSizeOf(editor)).toBe('')
|
||||||
|
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -9,16 +9,25 @@
|
|||||||
* - computeLineMetrics main entry (various font sizes/rules/grids)
|
* - computeLineMetrics main entry (various font sizes/rules/grids)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { describe, it, expect } from 'vitest'
|
import { afterEach, describe, it, expect, vi } from 'vitest'
|
||||||
import {
|
import {
|
||||||
HeuristicMetrics,
|
HeuristicMetrics,
|
||||||
|
autospaceBoundaries,
|
||||||
|
autospacePadBetween,
|
||||||
computeLineHeight,
|
computeLineHeight,
|
||||||
|
cssCsFontFamily,
|
||||||
|
cssDualFontFamily,
|
||||||
cssFontFamily,
|
cssFontFamily,
|
||||||
cssLineHeight,
|
cssLineHeight,
|
||||||
|
krLineFactor,
|
||||||
|
lineHeightFactor,
|
||||||
|
paraLineFactorCss,
|
||||||
snapSpacingToGrid,
|
snapSpacingToGrid,
|
||||||
simulateLines,
|
simulateLines,
|
||||||
computeLineMetrics,
|
computeLineMetrics,
|
||||||
textHasCjk,
|
textHasCjk,
|
||||||
|
textHasComplexScript,
|
||||||
|
textHasHangul,
|
||||||
} from '../src/renderer/line-metrics'
|
} from '../src/renderer/line-metrics'
|
||||||
|
|
||||||
const TWIPS_TO_PX = 96 / 1440
|
const TWIPS_TO_PX = 96 / 1440
|
||||||
@@ -334,12 +343,12 @@ describe('cssLineHeight', () => {
|
|||||||
|
|
||||||
describe('cssFontFamily', () => {
|
describe('cssFontFamily', () => {
|
||||||
it('common Word fonts → metric-compatible fallback + CJK safety net', () => {
|
it('common Word fonts → metric-compatible fallback + CJK safety net', () => {
|
||||||
expect(cssFontFamily('Calibri')).toBe("'Calibri','Carlito','Noto Sans CJK SC',sans-serif")
|
expect(cssFontFamily('Calibri')).toBe("'Calibri','Carlito GO','Noto Sans CJK SC',sans-serif")
|
||||||
expect(cssFontFamily('Times New Roman')).toBe(
|
expect(cssFontFamily('Times New Roman')).toBe(
|
||||||
"'Times New Roman','Liberation Serif','Noto Serif CJK SC',serif",
|
"'Times New Roman','Liberation Serif','Noto Serif CJK SC',serif",
|
||||||
)
|
)
|
||||||
expect(cssFontFamily('宋体')).toBe(
|
expect(cssFontFamily('宋体')).toBe(
|
||||||
"'宋体','Songti SC','STSong','SimSun','Noto Serif CJK SC',serif",
|
"'宋体','GenOffice Songti SC','STSong','SimSun','Noto Serif CJK SC',serif",
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -380,16 +389,77 @@ describe('cssFontFamily', () => {
|
|||||||
expect(cssFontFamily('Meiryo')).not.toContain('CJK SC')
|
expect(cssFontFamily('Meiryo')).not.toContain('CJK SC')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('SC-variant declares (Word substitutes missing East Asian fonts with a serif)', () => {
|
||||||
|
function stubCanvas(availableFamilies: string[]) {
|
||||||
|
const known = new Set(availableFamilies)
|
||||||
|
let width = 50
|
||||||
|
const fake = {
|
||||||
|
set font(spec: string) {
|
||||||
|
const family = /"([^"]+)"/.exec(spec)?.[1]
|
||||||
|
width = family !== undefined && known.has(family) ? 100 : 50
|
||||||
|
},
|
||||||
|
measureText: () => ({ width }),
|
||||||
|
}
|
||||||
|
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(
|
||||||
|
fake as unknown as CanvasRenderingContext2D,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => vi.restoreAllMocks())
|
||||||
|
|
||||||
|
it('missing SC sans routes to the SimSun-class serif chain', () => {
|
||||||
|
expect(cssFontFamily('Noto Sans SC')).toBe(
|
||||||
|
"'Noto Sans SC','GenOffice Songti SC','STSong','SimSun','Noto Serif CJK SC',serif",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('bundled subset faces count as missing and never lead the chain', () => {
|
||||||
|
expect(cssFontFamily('Noto Sans CJK SC')).toBe(
|
||||||
|
"'GenOffice Songti SC','STSong','SimSun','Noto Serif CJK SC',serif",
|
||||||
|
)
|
||||||
|
expect(cssFontFamily('Noto Serif CJK SC')).toBe(
|
||||||
|
"'GenOffice Songti SC','STSong','SimSun','Noto Serif CJK SC',serif",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('true SC serif declares keep their name at the head', () => {
|
||||||
|
expect(cssFontFamily('Noto Serif SC')).toBe(
|
||||||
|
"'Noto Serif SC','GenOffice Songti SC','STSong','SimSun','Noto Serif CJK SC',serif",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('locally installed SC sans keeps the declared name and a sans chain', () => {
|
||||||
|
stubCanvas(['Source Han Sans CN'])
|
||||||
|
expect(cssFontFamily('Source Han Sans CN')).toBe(
|
||||||
|
"'Source Han Sans CN','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',sans-serif",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('jp/kr/tc variants keep their same-script substitution', () => {
|
||||||
|
expect(cssFontFamily('Noto Sans CJK JP')).toBe(
|
||||||
|
"'Noto Sans CJK JP','Yu Mincho','Hiragino Mincho ProN','MS Mincho','Noto Serif JP',serif",
|
||||||
|
)
|
||||||
|
expect(cssFontFamily('Source Han Sans K')).toBe(
|
||||||
|
"'Source Han Sans K','Batang','GenOffice Serif KR','AppleMyungjo','Noto Serif KR',serif",
|
||||||
|
)
|
||||||
|
expect(cssFontFamily('Noto Sans CJK TC')).toBe(
|
||||||
|
"'Noto Sans CJK TC','PMingLiU','MingLiU','GenOffice Fullwidth TC','Songti TC','Noto Serif TC',serif",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
it('Korean/Traditional Chinese fonts → same-script fallback chain', () => {
|
it('Korean/Traditional Chinese fonts → same-script fallback chain', () => {
|
||||||
expect(cssFontFamily('맑은 고딕')).toBe(
|
expect(cssFontFamily('맑은 고딕')).toBe(
|
||||||
"'맑은 고딕','Malgun Gothic','Apple SD Gothic Neo','Noto Sans KR',sans-serif",
|
"'맑은 고딕','Malgun Gothic','GenOffice Sans KR','Apple SD Gothic Neo','Noto Sans KR',sans-serif",
|
||||||
|
)
|
||||||
|
expect(cssFontFamily('Batang')).toBe(
|
||||||
|
"'Batang','GenOffice Serif KR','AppleMyungjo','Noto Serif KR',serif",
|
||||||
)
|
)
|
||||||
expect(cssFontFamily('Batang')).toBe("'Batang','AppleMyungjo','Noto Serif KR',serif")
|
|
||||||
expect(cssFontFamily('微軟正黑體')).toBe(
|
expect(cssFontFamily('微軟正黑體')).toBe(
|
||||||
"'微軟正黑體','Microsoft JhengHei','PingFang TC','Heiti TC','Noto Sans TC',sans-serif",
|
"'微軟正黑體','Microsoft JhengHei','PingFang TC','Heiti TC','Noto Sans TC',sans-serif",
|
||||||
)
|
)
|
||||||
expect(cssFontFamily('新細明體')).toBe(
|
expect(cssFontFamily('新細明體')).toBe(
|
||||||
"'新細明體','PMingLiU','MingLiU','Songti TC','Noto Serif TC',serif",
|
"'新細明體','PMingLiU','MingLiU','GenOffice Fullwidth TC','Songti TC','Noto Serif TC',serif",
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -400,4 +470,197 @@ describe('textHasCjk', () => {
|
|||||||
expect(textHasCjk('English only, 123.')).toBe(false)
|
expect(textHasCjk('English only, 123.')).toBe(false)
|
||||||
expect(textHasCjk('')).toBe(false)
|
expect(textHasCjk('')).toBe(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('hangul counts as CJK (syllables + jamo)', () => {
|
||||||
|
expect(textHasCjk('한국어 문서')).toBe(true)
|
||||||
|
expect(textHasCjk('가')).toBe(true)
|
||||||
|
expect(textHasCjk('ㄱㄴ')).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── Korean fidelity ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('Korean line metrics', () => {
|
||||||
|
it('hangul advances 1.0em in the heuristic model', () => {
|
||||||
|
const m = new HeuristicMetrics()
|
||||||
|
const style = { fontFamily: 'Batang', fontSizePx: 16, bold: false, italic: false }
|
||||||
|
expect(m.measure('한', style)).toBeCloseTo(16, 5)
|
||||||
|
expect(m.measure('한글날', style)).toBeCloseTo(48, 5)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('Korean font line factors: Batang-class 1.3, Malgun 1.73, Noto KR 1.3', () => {
|
||||||
|
expect(lineHeightFactor('Batang')).toBe(1.3)
|
||||||
|
expect(lineHeightFactor('바탕')).toBe(1.3)
|
||||||
|
expect(lineHeightFactor('Gulim')).toBe(1.3)
|
||||||
|
expect(lineHeightFactor('Dotum')).toBe(1.3)
|
||||||
|
expect(lineHeightFactor('NanumMyeongjo')).toBe(1.3)
|
||||||
|
expect(lineHeightFactor('Malgun Gothic')).toBe(1.73)
|
||||||
|
expect(lineHeightFactor('맑은 고딕')).toBe(1.73)
|
||||||
|
expect(lineHeightFactor('Noto Sans CJK KR')).toBe(1.3)
|
||||||
|
expect(lineHeightFactor('Noto Serif KR')).toBe(1.3)
|
||||||
|
expect(lineHeightFactor('Source Han Sans K')).toBe(1.3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('Chinese/Japanese factors unchanged', () => {
|
||||||
|
expect(lineHeightFactor('SimSun')).toBe(1.3)
|
||||||
|
expect(lineHeightFactor('DengXian')).toBe(1.3)
|
||||||
|
expect(lineHeightFactor('等线')).toBe(1.3)
|
||||||
|
expect(lineHeightFactor('PMingLiU')).toBe(1.0)
|
||||||
|
expect(lineHeightFactor('Calibri')).toBe(1.22)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('SC-variant declares take the SimSun factor (their substitution target when missing)', () => {
|
||||||
|
expect(lineHeightFactor('Noto Sans CJK SC')).toBe(1.3)
|
||||||
|
expect(lineHeightFactor('Noto Serif SC')).toBe(1.3)
|
||||||
|
expect(lineHeightFactor('Source Han Sans CN')).toBe(1.3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('textHasHangul separates Korean from other CJK', () => {
|
||||||
|
expect(textHasHangul('보고서 2026')).toBe(true)
|
||||||
|
expect(textHasHangul('\u4e2d\u6587')).toBe(false)
|
||||||
|
expect(textHasHangul('かな')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('paraLineFactorCss routes by script', () => {
|
||||||
|
expect(paraLineFactorCss('한국어')).toBe('var(--doc-line-factor-kr,1.3)')
|
||||||
|
expect(paraLineFactorCss('\u4e2d\u6587')).toBe('1.3')
|
||||||
|
expect(paraLineFactorCss('latin')).toBe('var(--doc-line-factor-latin,1.2)')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('krLineFactor follows the EA face, defaulting to Batang-class', () => {
|
||||||
|
expect(krLineFactor('Batang')).toBe(1.3)
|
||||||
|
expect(krLineFactor('맑은 고딕')).toBe(1.73)
|
||||||
|
expect(krLineFactor(undefined)).toBe(1.3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('Korean ascii face in a dual-slot chain keeps only the literal family', () => {
|
||||||
|
expect(cssDualFontFamily('맑은 고딕', 'Batang')).toBe(
|
||||||
|
"'맑은 고딕','Batang','GenOffice Serif KR','AppleMyungjo','Noto Serif KR',serif",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('hangul wraps per syllable like other CJK', () => {
|
||||||
|
const m = new HeuristicMetrics()
|
||||||
|
const lines = simulateLines(
|
||||||
|
[{ text: '한글한글한글', sizeHalfPoints: 24 }],
|
||||||
|
16 * 4 + 1, // 4 syllables per line at 12pt (16px)
|
||||||
|
m,
|
||||||
|
12,
|
||||||
|
'Batang',
|
||||||
|
)
|
||||||
|
expect(lines.length).toBe(2)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('autospaceBoundaries', () => {
|
||||||
|
it('finds kana-Latin and kana-digit boundaries', () => {
|
||||||
|
expect(autospaceBoundaries('ペン12')).toEqual([2])
|
||||||
|
expect(autospaceBoundaries('12ペン')).toEqual([2])
|
||||||
|
expect(autospaceBoundaries('テスト17.0km')).toEqual([3])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('covers Han and hangul on the CJK side', () => {
|
||||||
|
expect(autospaceBoundaries('A漢B')).toEqual([1, 2])
|
||||||
|
expect(autospaceBoundaries('한글A')).toEqual([2])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('needs direct adjacency: spaces and punctuation get no pad', () => {
|
||||||
|
expect(autospaceBoundaries('ペン 12')).toEqual([])
|
||||||
|
expect(autospaceBoundaries('ペン、12')).toEqual([])
|
||||||
|
expect(autospaceBoundaries('。A')).toEqual([])
|
||||||
|
expect(autospaceBoundaries('あ・A')).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ignores fullwidth/halfwidth forms and non-CJK astral chars', () => {
|
||||||
|
expect(autospaceBoundaries('A' + '1')).toEqual([])
|
||||||
|
expect(autospaceBoundaries('アA')).toEqual([])
|
||||||
|
expect(autospaceBoundaries('あ\u{1F600}A')).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('autospacePadBetween', () => {
|
||||||
|
it('pads only when the seam chars are directly adjacent CJK and Latin', () => {
|
||||||
|
expect(autospacePadBetween('ペン', '12')).toBe(true)
|
||||||
|
expect(autospacePadBetween('12', 'ペン')).toBe(true)
|
||||||
|
expect(autospacePadBetween('ペン ', '12')).toBe(false)
|
||||||
|
expect(autospacePadBetween('ペン', ' 12')).toBe(false)
|
||||||
|
expect(autospacePadBetween('', '12')).toBe(false)
|
||||||
|
expect(autospacePadBetween('ペン', '')).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── Arabic fidelity ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('cssFontFamily Arabic', () => {
|
||||||
|
it('naskh/serif-class names get the bundled Naskh chain', () => {
|
||||||
|
expect(cssFontFamily('Noto Naskh Arabic')).toBe(
|
||||||
|
"'Noto Naskh Arabic','Geeza Pro','Al Bayan',serif",
|
||||||
|
)
|
||||||
|
expect(cssFontFamily('Arabic Typesetting')).toBe(
|
||||||
|
"'Arabic Typesetting','Noto Naskh Arabic','Geeza Pro','Al Bayan',serif",
|
||||||
|
)
|
||||||
|
expect(cssFontFamily('Amiri')).toContain("'Noto Naskh Arabic'")
|
||||||
|
expect(cssFontFamily('Scheherazade New')).toContain("'Noto Naskh Arabic'")
|
||||||
|
})
|
||||||
|
|
||||||
|
it('kufi/sans-class names get the Sans Arabic chain', () => {
|
||||||
|
expect(cssFontFamily('Noto Sans Arabic')).toBe("'Noto Sans Arabic','Geeza Pro',sans-serif")
|
||||||
|
expect(cssFontFamily('Noto Kufi Arabic')).toBe(
|
||||||
|
"'Noto Kufi Arabic','Noto Sans Arabic','Geeza Pro',sans-serif",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('unknown Arabic names (by script in the name) default to the naskh chain', () => {
|
||||||
|
expect(cssFontFamily('الخط الديواني')).toBe(
|
||||||
|
"'الخط الديواني','Noto Naskh Arabic','Geeza Pro','Al Bayan',serif",
|
||||||
|
)
|
||||||
|
expect(cssFontFamily('Urdu Typesetting')).toContain("'Noto Naskh Arabic'")
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not capture CJK or Latin families', () => {
|
||||||
|
expect(cssFontFamily('SimSun')).not.toContain('Arabic')
|
||||||
|
expect(cssFontFamily('Calibri')).not.toContain('Arabic')
|
||||||
|
expect(cssFontFamily('Batang')).not.toContain('Arabic')
|
||||||
|
expect(cssFontFamily('SomeCustomFont')).not.toContain('Arabic')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('textHasComplexScript', () => {
|
||||||
|
it('detects Arabic, Hebrew and presentation forms', () => {
|
||||||
|
expect(textHasComplexScript('مرحبا')).toBe(true)
|
||||||
|
expect(textHasComplexScript('שלום')).toBe(true)
|
||||||
|
expect(textHasComplexScript('ﻻ')).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('is false for Latin and CJK', () => {
|
||||||
|
expect(textHasComplexScript('hello 123')).toBe(false)
|
||||||
|
expect(textHasComplexScript('\u4e2d\u6587')).toBe(false)
|
||||||
|
expect(textHasComplexScript('かな한글')).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('cssCsFontFamily', () => {
|
||||||
|
it('cs chain leads, base Latin chain follows with its generic tail', () => {
|
||||||
|
expect(cssCsFontFamily('Arabic Typesetting', 'Calibri', 'Calibri')).toBe(
|
||||||
|
"'Arabic Typesetting','Noto Naskh Arabic','Geeza Pro','Al Bayan','Calibri','Carlito GO','Noto Sans CJK SC',sans-serif",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps a dual-slot base after the cs chain', () => {
|
||||||
|
const chain = cssCsFontFamily('Amiri', 'Times New Roman', 'SimSun')
|
||||||
|
expect(chain.startsWith("'Amiri','Noto Naskh Arabic'")).toBe(true)
|
||||||
|
expect(chain).toContain("'Times New Roman'")
|
||||||
|
expect(chain).toContain("'SimSun'")
|
||||||
|
})
|
||||||
|
|
||||||
|
it('cs-only run falls back to the plain cs chain', () => {
|
||||||
|
expect(cssCsFontFamily('Noto Naskh Arabic')).toBe(
|
||||||
|
"'Noto Naskh Arabic','Geeza Pro','Al Bayan',serif",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('deduplicates shared families', () => {
|
||||||
|
const chain = cssCsFontFamily('Noto Naskh Arabic', 'Noto Naskh Arabic')
|
||||||
|
expect(chain.match(/'Noto Naskh Arabic'/g)?.length).toBe(1)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ describe('native editable tables', () => {
|
|||||||
sizeHalfPoints: null,
|
sizeHalfPoints: null,
|
||||||
font: 'Calibri',
|
font: 'Calibri',
|
||||||
fontAscii: 'Calibri',
|
fontAscii: 'Calibri',
|
||||||
|
csFont: null,
|
||||||
charSpacingTwips: null,
|
charSpacingTwips: null,
|
||||||
charScaleEm: null,
|
charScaleEm: null,
|
||||||
highlight: null,
|
highlight: null,
|
||||||
@@ -339,4 +340,44 @@ describe('native editable tables', () => {
|
|||||||
expect(whole.editor.state.doc.firstChild?.type.name).not.toBe('docTable')
|
expect(whole.editor.state.doc.firstChild?.type.name).not.toBe('docTable')
|
||||||
whole.editor.destroy()
|
whole.editor.destroy()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('wraps hRule="exact" row cells in a fixed-height clip box; atLeast rows stay unwrapped', async () => {
|
||||||
|
const xml =
|
||||||
|
'<w:tbl><w:tblPr/><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||||
|
'<w:tr><w:trPr><w:trHeight w:val="907" w:hRule="exact"/></w:trPr>' +
|
||||||
|
'<w:tc><w:p><w:r><w:t>X</w:t></w:r></w:p></w:tc></w:tr>' +
|
||||||
|
'<w:tr><w:trPr><w:trHeight w:val="907" w:hRule="atLeast"/></w:trPr>' +
|
||||||
|
'<w:tc><w:p><w:r><w:t>Y</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||||
|
const parsed = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||||
|
const editor = new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: blocksToPmDoc(parsed.blocks) as never,
|
||||||
|
})
|
||||||
|
const rows = editor.view.dom.querySelectorAll('tr')
|
||||||
|
const clip = rows[0].querySelector(':scope > td > div.cell-clip') as HTMLElement
|
||||||
|
expect(clip).toBeTruthy()
|
||||||
|
expect(clip.style.height).toBe('60.5px')
|
||||||
|
expect(rows[1].querySelector('.cell-clip')).toBeNull()
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('still wraps an exact row whose padding consumes the whole height (clip height 0)', async () => {
|
||||||
|
const xml =
|
||||||
|
'<w:tbl><w:tblPr><w:tblCellMar><w:top w:w="500" w:type="dxa"/>' +
|
||||||
|
'<w:bottom w:w="500" w:type="dxa"/></w:tblCellMar></w:tblPr>' +
|
||||||
|
'<w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid>' +
|
||||||
|
'<w:tr><w:trPr><w:trHeight w:val="907" w:hRule="exact"/></w:trPr>' +
|
||||||
|
'<w:tc><w:p><w:r><w:t>X</w:t></w:r></w:p></w:tc></w:tr></w:tbl>'
|
||||||
|
const parsed = await parseDocx(await buildDocx({ bodyXml: xml }))
|
||||||
|
const editor = new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: blocksToPmDoc(parsed.blocks) as never,
|
||||||
|
})
|
||||||
|
const clip = editor.view.dom.querySelector('td > div.cell-clip') as HTMLElement
|
||||||
|
expect(clip).toBeTruthy()
|
||||||
|
expect(clip.style.height).toBe('0px')
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -4,7 +4,12 @@ import { parseDocx, saveDocx, type NumberingDef } from '@genoffice/docx-engine'
|
|||||||
import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx'
|
import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx'
|
||||||
import { blocksToPmDoc } from '../src/renderer/editor/convert'
|
import { blocksToPmDoc } from '../src/renderer/editor/convert'
|
||||||
import { editorExtensions } from '../src/renderer/editor/extensions'
|
import { editorExtensions } from '../src/renderer/editor/extensions'
|
||||||
import { computeListMarkers, formatNumber } from '../src/renderer/editor/numbering'
|
import {
|
||||||
|
bulletMarkerScale,
|
||||||
|
computeListMarkerInfos,
|
||||||
|
computeListMarkers,
|
||||||
|
formatNumber,
|
||||||
|
} from '../src/renderer/editor/numbering'
|
||||||
|
|
||||||
function def(
|
function def(
|
||||||
partial: Partial<NumberingDef> & Pick<NumberingDef, 'numId' | 'levels'>,
|
partial: Partial<NumberingDef> & Pick<NumberingDef, 'numId' | 'levels'>,
|
||||||
@@ -236,4 +241,73 @@ describe('computeListMarkers', () => {
|
|||||||
)
|
)
|
||||||
expect(markers).toEqual(['●', '▪', '•', '•', '•'])
|
expect(markers).toEqual(['●', '▪', '•', '•', '•'])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('bullet infos carry the original glyph (U+F0xx form) and the declared symbol font', () => {
|
||||||
|
const mk = (numId: string, lvlText: string, font?: string) =>
|
||||||
|
def({
|
||||||
|
numId,
|
||||||
|
levels: { 0: { numFmt: 'bullet', lvlText, start: 1, ...(font ? { font } : {}) } },
|
||||||
|
})
|
||||||
|
const infos = computeListMarkerInfos(
|
||||||
|
[
|
||||||
|
{ numId: '1', ilvl: 0 },
|
||||||
|
{ numId: '2', ilvl: 0 },
|
||||||
|
{ numId: '3', ilvl: 0 },
|
||||||
|
{ numId: '4', ilvl: 0 },
|
||||||
|
{ numId: '5', ilvl: 0 },
|
||||||
|
],
|
||||||
|
defs(
|
||||||
|
mk('1', '\uF0B7', 'Symbol'),
|
||||||
|
mk('2', 'l', 'Wingdings'), // raw byte normalized to U+F0xx
|
||||||
|
mk('3', '\uF0C1', 'Symbol'), // undecodable → default text, glyph still kept
|
||||||
|
mk('4', '\uF0B7'), // no symbol font → plain substitute
|
||||||
|
def({ numId: '5', levels: DECIMAL_3LVL.levels }),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
expect(infos[0]).toEqual({ text: '•', symbolChar: '\uF0B7', symbolFont: 'Symbol' })
|
||||||
|
expect(infos[1]).toEqual({ text: '●', symbolChar: '\uF06C', symbolFont: 'Wingdings' })
|
||||||
|
expect(infos[2]).toEqual({ text: '•', symbolChar: '\uF0C1', symbolFont: 'Symbol' })
|
||||||
|
expect(infos[3]).toEqual({ text: '•' })
|
||||||
|
expect(infos[4]).toEqual({ text: '1.' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('upscales only solid round substitute glyphs', () => {
|
||||||
|
expect(bulletMarkerScale('•')).toBe(1.25)
|
||||||
|
expect(bulletMarkerScale('●')).toBe(1.35)
|
||||||
|
expect(bulletMarkerScale('▪')).toBe(1)
|
||||||
|
expect(bulletMarkerScale('1.')).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('substitutes uncovered symbol bullets with a pinned font + scale and follows the first run size', async () => {
|
||||||
|
const numberingXml =
|
||||||
|
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' +
|
||||||
|
'<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
|
||||||
|
'<w:abstractNum w:abstractNumId="0">' +
|
||||||
|
'<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val=""/>' +
|
||||||
|
'<w:rPr><w:rFonts w:ascii="Symbol" w:hAnsi="Symbol"/></w:rPr></w:lvl>' +
|
||||||
|
'</w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>' +
|
||||||
|
'</w:numbering>'
|
||||||
|
const source = await buildDocx({
|
||||||
|
bodyXml:
|
||||||
|
'<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr>' +
|
||||||
|
'<w:r><w:rPr><w:sz w:val="24"/></w:rPr><w:t>item</w:t></w:r></w:p>',
|
||||||
|
numberingXml,
|
||||||
|
})
|
||||||
|
const parsed = await parseDocx(source)
|
||||||
|
const editor = new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
})
|
||||||
|
editor.storage.listNumbering.defs = parsed.numbering
|
||||||
|
editor.commands.setContent(blocksToPmDoc(parsed.blocks) as never)
|
||||||
|
const el = editor.view.dom.querySelector('.doc-li')!
|
||||||
|
// no canvas in the test DOM → coverage probe fails → substitution path
|
||||||
|
expect(el.getAttribute('data-marker')).toBe('•')
|
||||||
|
const style = el.getAttribute('style') ?? ''
|
||||||
|
expect(style).toContain("--li-marker-font: Arial,'Helvetica Neue',sans-serif")
|
||||||
|
expect(style).toContain('--li-marker-scale: 1.25')
|
||||||
|
expect(style).toContain('--li-marker-lh: 0')
|
||||||
|
expect(style).toContain('--li-marker-size: 12pt')
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { GAP_BAND, makeGapEl } from '../src/renderer/editor/pagination-gaps'
|
||||||
|
import { singleCutCell } from '../src/renderer/pagination'
|
||||||
|
|
||||||
|
const rowOf = (cells: number): HTMLTableRowElement => {
|
||||||
|
const tr = document.createElement('tr')
|
||||||
|
for (let i = 0; i < cells; i++) tr.appendChild(document.createElement('td'))
|
||||||
|
return tr
|
||||||
|
}
|
||||||
|
|
||||||
|
const m = { marginTop: 96, marginBottom: 96, marginLeft: 90, marginRight: 90 }
|
||||||
|
|
||||||
|
describe('in-row table cut decorations', () => {
|
||||||
|
it('single-cell row: real inline gap band, not a zero-height cut marker', () => {
|
||||||
|
const tr = rowOf(1)
|
||||||
|
expect(singleCutCell(tr)).toBe(tr.firstElementChild)
|
||||||
|
const el = makeGapEl(m, 'cell')
|
||||||
|
// page-gap-inline is what the measurement gap-subtraction keys on
|
||||||
|
expect(el.classList.contains('page-gap')).toBe(true)
|
||||||
|
expect(el.classList.contains('page-gap-inline')).toBe(true)
|
||||||
|
expect(el.classList.contains('page-gap-cut')).toBe(false)
|
||||||
|
expect(el.style.height).toBe(`${96 + GAP_BAND + 96}px`)
|
||||||
|
expect(el.style.getPropertyValue('--gap-mb')).toBe('96px')
|
||||||
|
expect(el.style.width).toBe('calc(100% + 180px)')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('multi-cell / missing rows keep the zero-height cut marker', () => {
|
||||||
|
expect(singleCutCell(rowOf(2))).toBeNull()
|
||||||
|
expect(singleCutCell(null)).toBeNull()
|
||||||
|
expect(makeGapEl(m, 'cut').className).toBe('page-gap-cut')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { prunedCloneHtml, type CloneChild } from '../src/renderer/components/PaginationPreview'
|
||||||
|
|
||||||
|
const kid = (partial: Partial<CloneChild> & Pick<CloneChild, 'html' | 'vTop' | 'vBottom'>) => ({
|
||||||
|
mt: 0,
|
||||||
|
mb: 0,
|
||||||
|
zero: false,
|
||||||
|
...partial,
|
||||||
|
})
|
||||||
|
|
||||||
|
/** spacer heights in document order, parsed from the pruned HTML */
|
||||||
|
const spacerHeights = (html: string): number[] =>
|
||||||
|
[...html.matchAll(/pv-prune-spacer" style="[^"]*height:([\d.]+)px/g)].map((m) => Number(m[1]))
|
||||||
|
|
||||||
|
// window pad is 2000px (CLONE_PRUNE_PAD): from=10000/to=11000 keeps [8000, 13000]
|
||||||
|
const FROM = 10000
|
||||||
|
const TO = 11000
|
||||||
|
|
||||||
|
describe('prunedCloneHtml', () => {
|
||||||
|
it('keeps in-window blocks verbatim without spacers', () => {
|
||||||
|
const kids = [
|
||||||
|
kid({ html: '<p id="a"></p>', vTop: 8100, vBottom: 8200 }),
|
||||||
|
kid({ html: '<p id="b"></p>', vTop: 8300, vBottom: 8400 }),
|
||||||
|
]
|
||||||
|
const out = prunedCloneHtml(kids, FROM, TO)
|
||||||
|
expect(out).toBe('<p id="a"></p><p id="b"></p>')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('replaces a leading pruned run with a spacer that restores the next block top', () => {
|
||||||
|
const kids = [
|
||||||
|
kid({ html: '<p id="p"></p>', vTop: 0, vBottom: 500, mb: 5 }),
|
||||||
|
kid({ html: '<p id="a"></p>', vTop: 9000, vBottom: 9200, mt: 10 }),
|
||||||
|
]
|
||||||
|
const out = prunedCloneHtml(kids, FROM, TO)
|
||||||
|
expect(out).not.toContain('id="p"')
|
||||||
|
// spacer height re-derives A's border top from flow start: vTop - mt - 0
|
||||||
|
expect(spacerHeights(out)).toEqual([8990])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('spacer after a mid-run kept block excludes the space before it', () => {
|
||||||
|
const kids = [
|
||||||
|
kid({ html: '<p id="a"></p>', vTop: 8100, vBottom: 8200, mb: 10 }),
|
||||||
|
kid({ html: '<p id="p1"></p>', vTop: 13500, vBottom: 14000 }),
|
||||||
|
kid({ html: '<p id="b"></p>', vTop: 8500, vBottom: 8600, mt: 20 }),
|
||||||
|
]
|
||||||
|
// contrived order aside: any kept block after a pruned run gets a spacer
|
||||||
|
// based on the previous kept block's margin edge (8200 + 10)
|
||||||
|
const out = prunedCloneHtml(kids, FROM, TO)
|
||||||
|
expect(spacerHeights(out)).toEqual([8500 - 20 - (8200 + 10)])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('advances the flow base across zero-height markers (regression: stale spacer base)', () => {
|
||||||
|
const kids = [
|
||||||
|
kid({ html: '<p id="p1"></p>', vTop: 1000, vBottom: 2000 }),
|
||||||
|
kid({ html: '<span id="z"></span>', vTop: 3000, vBottom: 3000, zero: true }),
|
||||||
|
kid({ html: '<p id="p2"></p>', vTop: 4000, vBottom: 5000 }),
|
||||||
|
kid({ html: '<p id="b"></p>', vTop: 9000, vBottom: 9500, mt: 20 }),
|
||||||
|
]
|
||||||
|
const out = prunedCloneHtml(kids, FROM, TO)
|
||||||
|
// marker is always kept even though it sits outside the window
|
||||||
|
expect(out).toContain('id="z"')
|
||||||
|
expect(out).not.toContain('id="p1"')
|
||||||
|
expect(out).not.toContain('id="p2"')
|
||||||
|
// spacer1 places the marker at 3000; spacer2 must start from the marker's
|
||||||
|
// flow position (3000), not from the pre-marker base — the buggy stale
|
||||||
|
// base would re-add the 3000px already consumed and shift B a page down
|
||||||
|
expect(spacerHeights(out)).toEqual([3000, 9000 - 20 - 3000])
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -3,6 +3,7 @@ import type { SectionInfo } from '@genoffice/docx-engine'
|
|||||||
import {
|
import {
|
||||||
appendEndnotesBlock,
|
appendEndnotesBlock,
|
||||||
assignSections,
|
assignSections,
|
||||||
|
cellCutYs,
|
||||||
computePageSlices,
|
computePageSlices,
|
||||||
computeSectionedSlices,
|
computeSectionedSlices,
|
||||||
computeSectionedSlicesF2,
|
computeSectionedSlicesF2,
|
||||||
@@ -16,6 +17,8 @@ import {
|
|||||||
pageNumbers,
|
pageNumbers,
|
||||||
pageStartBlocks,
|
pageStartBlocks,
|
||||||
applyBlockMeta,
|
applyBlockMeta,
|
||||||
|
fillLineBoxes,
|
||||||
|
measureBlocks,
|
||||||
sectionFirstPages,
|
sectionFirstPages,
|
||||||
sectionGeoms,
|
sectionGeoms,
|
||||||
sectionPageBox,
|
sectionPageBox,
|
||||||
@@ -564,6 +567,17 @@ describe('computeSectionedSlicesF2 — line-level pagination', () => {
|
|||||||
expect(slices[1].start).toBe(150) // mainBlock pushed down whole; new page starts at top=150
|
expect(slices[1].start).toBe(150) // mainBlock pushed down whole; new page starts at top=150
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('widowControl: gives up one line at the page bottom so the next page gets 2 lines', () => {
|
||||||
|
// Page height 300; 150px used → exactly 3 of 4 lines fit → a naive split leaves a 1-line widow
|
||||||
|
// Word takes one line back: 2 lines stay, 2 go to the next page (no whole-paragraph push)
|
||||||
|
const beforeBlock = lineBlock(0, [50, 50, 50])
|
||||||
|
const mainBlock = lineBlock(150, [50, 50, 50, 50], { widowControl: true })
|
||||||
|
const geoms = [{ contentHeight: 300, forceBreak: false }]
|
||||||
|
const slices = computeSectionedSlicesF2([beforeBlock, mainBlock], geoms, 350)
|
||||||
|
expect(slices.length).toBe(2)
|
||||||
|
expect(slices[1].start).toBe(250) // 2+2 split; a whole push would start at 150
|
||||||
|
})
|
||||||
|
|
||||||
it('widowControl=false: a single line may remain at the page bottom', () => {
|
it('widowControl=false: a single line may remain at the page bottom', () => {
|
||||||
const beforeBlock = lineBlock(0, [50, 50, 50]) // 150px
|
const beforeBlock = lineBlock(0, [50, 50, 50]) // 150px
|
||||||
const mainBlock = lineBlock(150, [50, 50, 50, 50], { widowControl: false }) // 200px
|
const mainBlock = lineBlock(150, [50, 50, 50, 50], { widowControl: false }) // 200px
|
||||||
@@ -589,6 +603,30 @@ describe('computeSectionedSlicesF2 — line-level pagination', () => {
|
|||||||
expect(() => computeSectionedSlicesF2([b], geoms1, 300)).not.toThrow()
|
expect(() => computeSectionedSlicesF2([b], geoms1, 300)).not.toThrow()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('keepLines without line data taller than a page terminates with hard cuts', () => {
|
||||||
|
// First slicing pass has no lineBoxes yet; a keepLines paragraph taller
|
||||||
|
// than the page used to re-test its full height after every column turn
|
||||||
|
// and loop forever (form-gov renderer hang).
|
||||||
|
const b = block(0, 1000, { keepLines: true })
|
||||||
|
const slices = computeSectionedSlicesF2([b], geoms1, 1000)
|
||||||
|
expect(slices.length).toBe(5) // 1000px / 200px pages
|
||||||
|
expect(slices[0].start).toBe(0)
|
||||||
|
expect(slices[slices.length - 1].end).toBe(1000)
|
||||||
|
// pages advance monotonically
|
||||||
|
for (let i = 1; i < slices.length; i++) {
|
||||||
|
expect(slices[i].start).toBeGreaterThan(slices[i - 1].start)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keepLines without line data on a partly used page fills the remainder then hard-cuts', () => {
|
||||||
|
const before = block(0, 150)
|
||||||
|
const b = block(150, 500, { keepLines: true })
|
||||||
|
const slices = computeSectionedSlicesF2([before, b], geoms1, 650)
|
||||||
|
// 50px fills page 1 (matches the _hardCutLines policy), then 200px cuts
|
||||||
|
expect(slices.map((s) => s.start)).toEqual([0, 200, 400, 600])
|
||||||
|
expect(slices[slices.length - 1].end).toBe(650)
|
||||||
|
})
|
||||||
|
|
||||||
it('keepNext: chain head stays on the same page as the first line of the next paragraph', () => {
|
it('keepNext: chain head stays on the same page as the first line of the next paragraph', () => {
|
||||||
// Block A (100px keepNext) + block B (100px) — page height 200
|
// Block A (100px keepNext) + block B (100px) — page height 200
|
||||||
// 120px of the page is used; A alone fits (100px → 220px > 200), but A + B's first line must share a page
|
// 120px of the page is used; A alone fits (100px → 220px > 200), but A + B's first line must share a page
|
||||||
@@ -721,6 +759,242 @@ describe('computeSectionedSlicesF2 — table row-level page breaks', () => {
|
|||||||
const slices = computeSectionedSlicesF2([b], [{ contentHeight: 200, forceBreak: false }], 600)
|
const slices = computeSectionedSlicesF2([b], [{ contentHeight: 200, forceBreak: false }], 600)
|
||||||
expect(slices.map((slice) => slice.start)).toEqual([0, 150, 350, 500])
|
expect(slices.map((slice) => slice.start)).toEqual([0, 150, 350, 500])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('page-sized declared-fill row is pushed whole, not clipped (fill clipping is over-tall only)', () => {
|
||||||
|
const rows: TableRowBox[] = [{ height: 50 }, { height: 180, contentBottom: 20 }]
|
||||||
|
const b = makeTableBlock(0, rows)
|
||||||
|
const slices = computeSectionedSlicesF2([b], geoms1, 230)
|
||||||
|
expect(slices.map((slice) => slice.start)).toEqual([0, 50])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('page-sized rows after a pushed fill row keep whole-row placement', () => {
|
||||||
|
const rows: TableRowBox[] = [
|
||||||
|
{ height: 50 },
|
||||||
|
{ height: 180, contentBottom: 20 },
|
||||||
|
{ height: 40, contentBottom: 30 },
|
||||||
|
]
|
||||||
|
const b = makeTableBlock(0, rows)
|
||||||
|
const slices = computeSectionedSlicesF2([b], geoms1, 270)
|
||||||
|
expect(slices.map((slice) => slice.start)).toEqual([0, 50, 230])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('empty rows that do not fit are pushed whole, not absorbed by clipped-fill bookkeeping', () => {
|
||||||
|
// empty rows report contentBottom 0 and no cuts; each must turn the page like an atomic row
|
||||||
|
const rows: TableRowBox[] = [
|
||||||
|
{ height: 190, contentBottom: 190 },
|
||||||
|
...Array.from({ length: 4 }, () => ({ height: 30, contentBottom: 0 })),
|
||||||
|
]
|
||||||
|
const b = makeTableBlock(0, rows)
|
||||||
|
const slices = computeSectionedSlicesF2([b], geoms1, 310)
|
||||||
|
expect(slices.map((slice) => slice.start)).toEqual([0, 190])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('trailing padding of a page-sized row stays glued to its last text band (no fill strip past the page)', () => {
|
||||||
|
// two text bands (cut at 45, content ends at 80) + shaded bottom padding to 120
|
||||||
|
const rows: TableRowBox[] = [{ height: 110 }, { height: 120, cutYs: [45], contentBottom: 80 }]
|
||||||
|
const b = makeTableBlock(0, rows)
|
||||||
|
const slices = computeSectionedSlicesF2([b], geoms1, 230)
|
||||||
|
// last segment spans 45..120 and does not fit the 45px remainder → breaks at the cut
|
||||||
|
expect(slices.map((slice) => slice.start)).toEqual([0, 155])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('declared row taller than a page with top-only content: one clipped page, no empty segment pages', () => {
|
||||||
|
const rows: TableRowBox[] = [{ height: 600, contentBottom: 40 }]
|
||||||
|
const b = makeTableBlock(0, rows)
|
||||||
|
const slices = computeSectionedSlicesF2([b], geoms1, 600)
|
||||||
|
expect(slices).toEqual([{ start: 0, end: 600, section: 0 }])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('content below the fold still pushes the row to the next page (not clipped)', () => {
|
||||||
|
const rows: TableRowBox[] = [{ height: 50 }, { height: 100, contentBottom: 80 }]
|
||||||
|
const b = makeTableBlock(0, rows)
|
||||||
|
const slices = computeSectionedSlicesF2([b], [{ contentHeight: 120, forceBreak: false }], 150)
|
||||||
|
expect(slices.map((slice) => slice.start)).toEqual([0, 50])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rows with natural cut points keep the segment path even with contentBottom set', () => {
|
||||||
|
const rows: TableRowBox[] = [
|
||||||
|
{ height: 50 },
|
||||||
|
{ height: 200, cutYs: [60, 120], contentBottom: 190 },
|
||||||
|
]
|
||||||
|
const b = makeTableBlock(0, rows)
|
||||||
|
const slices = computeSectionedSlicesF2([b], [{ contentHeight: 120, forceBreak: false }], 250)
|
||||||
|
expect(slices[1].start).toBe(110)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('fill below the last content band collapses into a clipped remainder, not empty pages', () => {
|
||||||
|
const rows: TableRowBox[] = [{ height: 600, cutYs: [50], contentBottom: 80 }]
|
||||||
|
const b = makeTableBlock(0, rows)
|
||||||
|
const slices = computeSectionedSlicesF2([b], geoms1, 600)
|
||||||
|
expect(slices).toEqual([{ start: 0, end: 600, section: 0 }])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('multi-page content keeps page-sized segments; only the fill tail is clipped', () => {
|
||||||
|
const rows: TableRowBox[] = [{ height: 900, contentBottom: 450 }]
|
||||||
|
const b = makeTableBlock(0, rows)
|
||||||
|
const slices = computeSectionedSlicesF2([b], geoms1, 900)
|
||||||
|
expect(slices.map((slice) => slice.start)).toEqual([0, 200, 400])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('computeSectionedSlicesF2 — keepNext chain anchored by a table', () => {
|
||||||
|
it('the heading only keeps with the first table row; the table breaks by rows', () => {
|
||||||
|
const filler = block(0, 80)
|
||||||
|
const heading = block(80, 20, { keepNext: true })
|
||||||
|
const rows: TableRowBox[] = Array.from({ length: 6 }, () => ({ height: 30 }))
|
||||||
|
const table = block(100, 180, { tableRows: rows })
|
||||||
|
const slices = computeSectionedSlicesF2([filler, heading, table], geoms1, 280)
|
||||||
|
// whole-table anchor height would push heading + table to page 2 (start 80)
|
||||||
|
expect(slices.map((slice) => slice.start)).toEqual([0, 190])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('fillLineBoxes — keepNext-anchored tables', () => {
|
||||||
|
const geoms = [{ contentHeight: 200, forceBreak: false }]
|
||||||
|
const tableEl = () => {
|
||||||
|
const el = document.createElement('div')
|
||||||
|
el.innerHTML = '<table><tbody><tr><td></td></tr></tbody></table>'
|
||||||
|
return el
|
||||||
|
}
|
||||||
|
|
||||||
|
it('samples table rows even when the table fits on one page', () => {
|
||||||
|
const heading: BlockBox = { top: 0, height: 20, keepNext: true }
|
||||||
|
const table: BlockBox = { top: 20, height: 60, el: tableEl() }
|
||||||
|
expect(fillLineBoxes([heading, table], geoms, 1)).toBe(true)
|
||||||
|
expect(table.tableRows).toEqual([{ height: 60, contentBottom: 0 }])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('leaves non-anchored fitting tables unsampled', () => {
|
||||||
|
const para: BlockBox = { top: 0, height: 20 }
|
||||||
|
const table: BlockBox = { top: 20, height: 60, el: tableEl() }
|
||||||
|
expect(fillLineBoxes([para, table], geoms, 1)).toBe(false)
|
||||||
|
expect(table.tableRows).toBeUndefined()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('measureBlocks — break-only paragraphs', () => {
|
||||||
|
it('a page-break-only paragraph does not create a blank page when only one line fits', () => {
|
||||||
|
const rectOf = (top: number, height: number) =>
|
||||||
|
({
|
||||||
|
top,
|
||||||
|
height,
|
||||||
|
bottom: top + height,
|
||||||
|
left: 0,
|
||||||
|
right: 100,
|
||||||
|
width: 100,
|
||||||
|
x: 0,
|
||||||
|
y: top,
|
||||||
|
toJSON: () => ({}),
|
||||||
|
}) as DOMRect
|
||||||
|
const pm = document.createElement('div')
|
||||||
|
const addPara = (top: number, height: number, html: string) => {
|
||||||
|
const el = document.createElement('p')
|
||||||
|
el.innerHTML = html
|
||||||
|
el.getBoundingClientRect = () => rectOf(top, height)
|
||||||
|
pm.appendChild(el)
|
||||||
|
}
|
||||||
|
// page height 200: 27px left after the filler; the break paragraph's DOM height is
|
||||||
|
// two line boxes (br + trailingBreak) = 44px
|
||||||
|
addPara(0, 173, 'filler text')
|
||||||
|
addPara(173, 44, '<br class="doc-page-br"><br class="ProseMirror-trailingBreak">')
|
||||||
|
addPara(217, 100, 'after the break')
|
||||||
|
const { blocks, totalHeight } = measureBlocks(pm, 0, 1)
|
||||||
|
expect(blocks[1].breakAfter).toBe(true)
|
||||||
|
expect(blocks[1].spaceAfterPx).toBe(44)
|
||||||
|
const geoms = [{ contentHeight: 200, forceBreak: false }]
|
||||||
|
const slices = computeSectionedSlicesF2(blocks, geoms, totalHeight)
|
||||||
|
// break paragraph overflows the bottom margin; page 2 starts at the following block
|
||||||
|
expect(slices.map((s) => s.start)).toEqual([0, 217])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('overflows the bottom margin instead of blanking a page even when no space is left', () => {
|
||||||
|
const rectOf = (top: number, height: number) =>
|
||||||
|
({
|
||||||
|
top,
|
||||||
|
height,
|
||||||
|
bottom: top + height,
|
||||||
|
left: 0,
|
||||||
|
right: 100,
|
||||||
|
width: 100,
|
||||||
|
x: 0,
|
||||||
|
y: top,
|
||||||
|
toJSON: () => ({}),
|
||||||
|
}) as DOMRect
|
||||||
|
const pm = document.createElement('div')
|
||||||
|
const addPara = (top: number, height: number, html: string) => {
|
||||||
|
const el = document.createElement('p')
|
||||||
|
el.innerHTML = html
|
||||||
|
el.getBoundingClientRect = () => rectOf(top, height)
|
||||||
|
pm.appendChild(el)
|
||||||
|
}
|
||||||
|
// page height 200: only 15px left, less than even the br line — the break paragraph
|
||||||
|
// still stays (whole block is trailing space) rather than pushing into a blank page;
|
||||||
|
// Word would blank here, but a fit-check turns page-fill drift into spurious blanks
|
||||||
|
addPara(0, 185, 'filler text')
|
||||||
|
addPara(185, 44, '<br class="doc-page-br"><br class="ProseMirror-trailingBreak">')
|
||||||
|
addPara(229, 100, 'after the break')
|
||||||
|
const { blocks, totalHeight } = measureBlocks(pm, 0, 1)
|
||||||
|
const geoms = [{ contentHeight: 200, forceBreak: false }]
|
||||||
|
const slices = computeSectionedSlicesF2(blocks, geoms, totalHeight)
|
||||||
|
expect(slices.map((s) => s.start)).toEqual([0, 229])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('cellCutYs — line-level in-row cut candidates', () => {
|
||||||
|
it('emits a boundary between adjacent lines even with zero gap', () => {
|
||||||
|
const lines: Array<[number, number]> = [
|
||||||
|
[0, 15],
|
||||||
|
[15, 30],
|
||||||
|
[30, 45],
|
||||||
|
]
|
||||||
|
expect(cellCutYs([lines], 45)).toEqual([15, 30])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('clusters same-line rects (overlapping spans) into one line box', () => {
|
||||||
|
const rects: Array<[number, number]> = [
|
||||||
|
[0, 15],
|
||||||
|
[1, 14],
|
||||||
|
[15, 30],
|
||||||
|
]
|
||||||
|
expect(cellCutYs([rects], 30)).toEqual([15])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('drops a candidate that crosses another cell line box', () => {
|
||||||
|
const cellA: Array<[number, number]> = [
|
||||||
|
[0, 15],
|
||||||
|
[15, 30],
|
||||||
|
]
|
||||||
|
const cellB: Array<[number, number]> = [[5, 25]]
|
||||||
|
expect(cellCutYs([cellA, cellB], 30)).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps only boundaries safe across all cells and dedupes near-identical ones', () => {
|
||||||
|
const cellA: Array<[number, number]> = [
|
||||||
|
[0, 20],
|
||||||
|
[20, 60],
|
||||||
|
]
|
||||||
|
const cellB: Array<[number, number]> = [
|
||||||
|
[0, 20.3],
|
||||||
|
[20.3, 40],
|
||||||
|
[40, 60],
|
||||||
|
]
|
||||||
|
// 20/20.3 coincide within jitter → one cut; B's 40 falls inside A's [20,60] line
|
||||||
|
expect(cellCutYs([cellA, cellB], 60)).toEqual([20])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects candidates hugging the row edges', () => {
|
||||||
|
const lines: Array<[number, number]> = [
|
||||||
|
[0, 1.5],
|
||||||
|
[2, 28],
|
||||||
|
[28.5, 30],
|
||||||
|
]
|
||||||
|
expect(cellCutYs([lines], 30)).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns nothing for empty or single-line rows', () => {
|
||||||
|
expect(cellCutYs([], 100)).toEqual([])
|
||||||
|
expect(cellCutYs([[[0, 20]]], 100)).toEqual([])
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('insertParityBlanks — even/odd section blank pages', () => {
|
describe('insertParityBlanks — even/odd section blank pages', () => {
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
/**
|
||||||
|
* Word's line strut follows run sizes: a paragraph whose runs all declare an
|
||||||
|
* explicit size must carry that size (max of runs) on the block element, or the
|
||||||
|
* inherited body size inflates every line box (table cells often run smaller
|
||||||
|
* than Normal). Any run inheriting the body size keeps the inherited strut.
|
||||||
|
*/
|
||||||
|
import { Editor } from '@tiptap/core'
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { editorExtensions } from '../src/renderer/editor/extensions'
|
||||||
|
|
||||||
|
const sized = (text: string, sizeHalfPoints: number) => ({
|
||||||
|
type: 'text',
|
||||||
|
text,
|
||||||
|
marks: [{ type: 'docTextStyle', attrs: { sizeHalfPoints } }],
|
||||||
|
})
|
||||||
|
|
||||||
|
const editorWith = (content: unknown[]): Editor =>
|
||||||
|
new Editor({
|
||||||
|
element: document.createElement('div'),
|
||||||
|
extensions: editorExtensions,
|
||||||
|
content: { type: 'doc', content } as never,
|
||||||
|
})
|
||||||
|
|
||||||
|
// jsdom's CSSOM drops the min() font-size, so assert the --doc-strut custom
|
||||||
|
// property it references (font-size:min(var(--doc-strut), 1em) rides along)
|
||||||
|
const pFontSize = (editor: Editor, index = 0): string => {
|
||||||
|
const p = editor.view.dom.querySelectorAll('p')[index] as HTMLElement
|
||||||
|
return p.style.getPropertyValue('--doc-strut')
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('paragraph strut font-size from run sizes', () => {
|
||||||
|
it('all runs explicit: the paragraph carries the max run size', () => {
|
||||||
|
const editor = editorWith([
|
||||||
|
{ type: 'docParagraph', content: [sized('small ', 17), sized('big', 20)] },
|
||||||
|
])
|
||||||
|
expect(pFontSize(editor)).toBe('10pt')
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a run inheriting the body size suppresses the strut override', () => {
|
||||||
|
const editor = editorWith([
|
||||||
|
{ type: 'docParagraph', content: [sized('sized ', 17), { type: 'text', text: 'plain' }] },
|
||||||
|
])
|
||||||
|
expect(pFontSize(editor)).toBe('')
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a docTextStyle mark without sizeHalfPoints counts as inherited', () => {
|
||||||
|
const editor = editorWith([
|
||||||
|
{
|
||||||
|
type: 'docParagraph',
|
||||||
|
content: [
|
||||||
|
sized('sized ', 17),
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
text: 'red',
|
||||||
|
marks: [{ type: 'docTextStyle', attrs: { color: 'FF0000' } }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
])
|
||||||
|
expect(pFontSize(editor)).toBe('')
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('an empty paragraph emits no font-size', () => {
|
||||||
|
const editor = editorWith([{ type: 'docParagraph' }])
|
||||||
|
expect(pFontSize(editor)).toBe('')
|
||||||
|
editor.destroy()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
/**
|
||||||
|
* Static protected DOM (read-only tables / textboxes) gets the same
|
||||||
|
* .doc-autospace-pad spans the editor adds via decorations.
|
||||||
|
*/
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { DOMSerializer } from '@tiptap/pm/model'
|
||||||
|
import type { TableModel, TextboxDisplay } from '@genoffice/docx-engine'
|
||||||
|
import { renderTableSpec, renderTextboxSpec } from '../src/renderer/editor/protected-render'
|
||||||
|
|
||||||
|
const render = (spec: unknown): HTMLElement =>
|
||||||
|
DOMSerializer.renderSpec(document, spec as never).dom as HTMLElement
|
||||||
|
|
||||||
|
const pads = (dom: HTMLElement) => dom.querySelectorAll('.doc-autospace-pad')
|
||||||
|
|
||||||
|
describe('renderTableSpec autospace pads', () => {
|
||||||
|
it('pads boundaries inside plain cell paragraphs without changing the text', () => {
|
||||||
|
const dom = render(renderTableSpec({ rows: [[{ paras: ['ペン12'] }]] }))
|
||||||
|
expect(pads(dom)).toHaveLength(1)
|
||||||
|
expect(dom.querySelector('td')!.textContent).toBe('ペン12')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('pads inside and between rich-cell runs', () => {
|
||||||
|
const model: TableModel = {
|
||||||
|
rows: [
|
||||||
|
[
|
||||||
|
{
|
||||||
|
paras: ['ペン12', 'A漢'],
|
||||||
|
richParas: [
|
||||||
|
{ runs: [{ text: 'ペン' }, { text: '12', bold: true }] },
|
||||||
|
{ runs: [{ text: 'A漢' }] },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const dom = render(renderTableSpec(model))
|
||||||
|
expect(pads(dom)).toHaveLength(2)
|
||||||
|
expect(dom.querySelector('td')!.textContent).toBe('ペン12A漢')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('adds none for space-separated seams', () => {
|
||||||
|
const dom = render(renderTableSpec({ rows: [[{ paras: ['ペン 12'] }]] }))
|
||||||
|
expect(pads(dom)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('skips pads and disables native autospace when the paragraph turns autoSpace off', () => {
|
||||||
|
const model: TableModel = {
|
||||||
|
rows: [
|
||||||
|
[
|
||||||
|
{
|
||||||
|
paras: ['ペン12A漢'],
|
||||||
|
richParas: [{ runs: [{ text: 'ペン12' }, { text: 'A漢' }], autoSpace: false }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const dom = render(renderTableSpec(model))
|
||||||
|
expect(pads(dom)).toHaveLength(0)
|
||||||
|
const spans = dom.querySelectorAll('td span')
|
||||||
|
expect(spans.length).toBe(2)
|
||||||
|
spans.forEach((s) => {
|
||||||
|
expect(s.getAttribute('style')).toMatch(/text-autospace:\s*no-autospace/)
|
||||||
|
})
|
||||||
|
expect(dom.querySelector('td')!.textContent).toBe('ペン12A漢')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('gates pads per paragraph: only the autoSpace-off one loses them', () => {
|
||||||
|
const model: TableModel = {
|
||||||
|
rows: [
|
||||||
|
[
|
||||||
|
{
|
||||||
|
paras: ['ペン12', 'ペン12'],
|
||||||
|
richParas: [
|
||||||
|
{ runs: [{ text: 'ペン12' }] },
|
||||||
|
{ runs: [{ text: 'ペン12' }], autoSpace: false },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const dom = render(renderTableSpec(model))
|
||||||
|
expect(pads(dom)).toHaveLength(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('renderTextboxSpec autospace pads', () => {
|
||||||
|
it('pads across run boundaries and inside run text', () => {
|
||||||
|
const box: TextboxDisplay = {
|
||||||
|
paras: [{ runs: [{ text: 'テスト' }, { text: '17.0km', bold: true }] }],
|
||||||
|
}
|
||||||
|
const dom = render(renderTextboxSpec(box))
|
||||||
|
expect(pads(dom)).toHaveLength(1)
|
||||||
|
expect(dom.textContent).toBe('テスト17.0km')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('autoSpace=false paragraph gets zero pads and native autospace off', () => {
|
||||||
|
const box: TextboxDisplay = {
|
||||||
|
paras: [{ runs: [{ text: 'テスト' }, { text: '17.0km', bold: true }], autoSpace: false }],
|
||||||
|
}
|
||||||
|
const dom = render(renderTextboxSpec(box))
|
||||||
|
expect(pads(dom)).toHaveLength(0)
|
||||||
|
dom.querySelectorAll('span').forEach((s) => {
|
||||||
|
expect(s.getAttribute('style')).toMatch(/text-autospace:\s*no-autospace/)
|
||||||
|
})
|
||||||
|
expect(dom.textContent).toBe('テスト17.0km')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { DOMSerializer } from '@tiptap/pm/model'
|
||||||
|
import type { TableModel } from '@genoffice/docx-engine'
|
||||||
|
import { renderTableSpec } from '../src/renderer/editor/protected-render'
|
||||||
|
|
||||||
|
function renderTable(model: TableModel): HTMLElement {
|
||||||
|
const { dom } = DOMSerializer.renderSpec(document, renderTableSpec(model) as never)
|
||||||
|
return dom as HTMLElement
|
||||||
|
}
|
||||||
|
|
||||||
|
/** innerText equivalent (<br> → \n); jsdom does not implement innerText */
|
||||||
|
function cellText(td: Element): string {
|
||||||
|
let out = ''
|
||||||
|
td.childNodes.forEach((n) => {
|
||||||
|
out += n.nodeName === 'BR' ? '\n' : (n.textContent ?? '')
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
const cell = (paras: string[], richParas?: TableModel['rows'][0][0]['richParas']) => ({
|
||||||
|
paras,
|
||||||
|
...(richParas ? { richParas } : {}),
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('renderTableSpec rich cell content', () => {
|
||||||
|
it('renders run-level sz/color/bold from richParas', () => {
|
||||||
|
const model: TableModel = {
|
||||||
|
rows: [
|
||||||
|
[
|
||||||
|
cell(
|
||||||
|
['Big red', 'plain'],
|
||||||
|
[
|
||||||
|
{
|
||||||
|
runs: [
|
||||||
|
{ text: 'Big ', sizeHalfPoints: 15, color: 'FF0000', bold: true },
|
||||||
|
{ text: 'red', sizeHalfPoints: 15, italic: true },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ runs: [{ text: 'plain' }] },
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const td = renderTable(model).querySelector('td')!
|
||||||
|
const spans = td.querySelectorAll('span')
|
||||||
|
expect(spans).toHaveLength(3)
|
||||||
|
// renderSpec assigns style via cssText, so jsdom normalizes (spaces, rgb());
|
||||||
|
// assert on the attribute string, not CSSOM property reads
|
||||||
|
const first = spans[0].getAttribute('style')!
|
||||||
|
expect(first).toMatch(/font-size:\s*7\.5pt/)
|
||||||
|
expect(first).toMatch(/color:\s*(#FF0000|rgb\(255,\s*0,\s*0\))/i)
|
||||||
|
expect(first).toMatch(/font-weight:\s*700/)
|
||||||
|
const second = spans[1].getAttribute('style')!
|
||||||
|
expect(second).toMatch(/font-size:\s*7\.5pt/)
|
||||||
|
expect(second).toMatch(/font-style:\s*italic/)
|
||||||
|
expect(spans[2].getAttribute('style')).toBeNull()
|
||||||
|
expect(cellText(td)).toBe('Big red\nplain')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps innerText line semantics identical to the paras fallback', () => {
|
||||||
|
const paras = ['a', '', 'b']
|
||||||
|
const rich = renderTable({
|
||||||
|
rows: [[cell(paras, [{ runs: [{ text: 'a' }] }, { runs: [] }, { runs: [{ text: 'b' }] }])]],
|
||||||
|
}).querySelector('td')!
|
||||||
|
const plain = renderTable({ rows: [[cell(paras)]] }).querySelector('td')!
|
||||||
|
expect(cellText(rich)).toBe('a\n\nb')
|
||||||
|
expect(cellText(rich)).toBe(cellText(plain))
|
||||||
|
expect(rich.querySelectorAll('br')).toHaveLength(plain.querySelectorAll('br').length)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back to plain paras when richParas is absent', () => {
|
||||||
|
const td = renderTable({ rows: [[cell(['x', 'y'])]] }).querySelector('td')!
|
||||||
|
expect(td.querySelectorAll('span')).toHaveLength(0)
|
||||||
|
expect(cellText(td)).toBe('x\ny')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps the nbsp placeholder for cells whose richParas hold no text', () => {
|
||||||
|
const td = renderTable({ rows: [[cell([''], [{ runs: [] }])]] }).querySelector('td')!
|
||||||
|
expect(td.textContent).toBe('\u00a0')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('leads with the cs font chain for complex-script run text', () => {
|
||||||
|
const fonts = { font: 'Calibri', fontAscii: 'Calibri', csFont: 'Traditional Arabic' }
|
||||||
|
const model: TableModel = {
|
||||||
|
rows: [
|
||||||
|
[
|
||||||
|
cell(
|
||||||
|
['مرحبا Hi'],
|
||||||
|
[
|
||||||
|
{
|
||||||
|
runs: [
|
||||||
|
{ text: 'مرحبا', ...fonts },
|
||||||
|
{ text: 'Hi', ...fonts },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const spans = renderTable(model).querySelectorAll('td span')
|
||||||
|
const arabic = spans[0].getAttribute('style')!
|
||||||
|
expect(arabic).toMatch(/font-family:\s*['"]Traditional Arabic['"]/)
|
||||||
|
expect(arabic).toContain('Calibri')
|
||||||
|
// csFont present but text is Latin-only: keep the plain Latin chain
|
||||||
|
const latin = spans[1].getAttribute('style')!
|
||||||
|
expect(latin).toMatch(/font-family:\s*['"]Calibri['"]/)
|
||||||
|
expect(latin).not.toContain('Traditional Arabic')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('cell-level color/bold stay as td-level fallback', () => {
|
||||||
|
const model: TableModel = {
|
||||||
|
rows: [
|
||||||
|
[
|
||||||
|
{
|
||||||
|
...cell(['t'], [{ runs: [{ text: 't' }] }]),
|
||||||
|
color: '112233',
|
||||||
|
bold: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
const td = renderTable(model).querySelector('td')!
|
||||||
|
const tdStyle = td.getAttribute('style')!
|
||||||
|
expect(tdStyle).toMatch(/color:\s*(#112233|rgb\(17,\s*34,\s*51\))/i)
|
||||||
|
expect(tdStyle).toMatch(/font-weight:\s*600/)
|
||||||
|
expect(td.querySelector('span')!.getAttribute('style')).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -3,7 +3,13 @@
|
|||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"jsx": "react-jsx",
|
"jsx": "react-jsx",
|
||||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
"types": ["node"]
|
"types": ["node"],
|
||||||
|
"paths": {
|
||||||
|
// resolve workspace types from this checkout's sources: in a git worktree
|
||||||
|
// node_modules is a symlink into the main checkout, so bare specifiers
|
||||||
|
// would typecheck against the other checkout's (possibly stale) types
|
||||||
|
"@genoffice/docx-engine": ["../../packages/docx-engine/src/index.ts"]
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"include": ["src", "tests", "electron.vite.config.ts", "vitest.config.ts"]
|
"include": ["src", "tests", "electron.vite.config.ts", "vitest.config.ts"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,6 @@
|
|||||||
"@genoffice/ui": "*",
|
"@genoffice/ui": "*",
|
||||||
"@tiptap/core": "3.29.2",
|
"@tiptap/core": "3.29.2",
|
||||||
"@tiptap/extension-code-block": "3.29.2",
|
"@tiptap/extension-code-block": "3.29.2",
|
||||||
"@tiptap/extension-highlight": "3.29.2",
|
|
||||||
"@tiptap/extension-image": "3.29.2",
|
"@tiptap/extension-image": "3.29.2",
|
||||||
"@tiptap/extension-list": "3.29.2",
|
"@tiptap/extension-list": "3.29.2",
|
||||||
"@tiptap/extension-table": "3.29.2",
|
"@tiptap/extension-table": "3.29.2",
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import type { Lang } from '@genoffice/i18n'
|
|||||||
import type { AiStreamChunk } from '@genoffice/ai-provider'
|
import type { AiStreamChunk } from '@genoffice/ai-provider'
|
||||||
import type { ProjectApi } from '@genoffice/project-store'
|
import type { ProjectApi } from '@genoffice/project-store'
|
||||||
import { AI_CHANNELS, MARKDOWN_CHANNELS } from '../shared/ipc'
|
import { AI_CHANNELS, MARKDOWN_CHANNELS } from '../shared/ipc'
|
||||||
import type { ExportFormat, MarkdownApi, SaveMode } from '../shared/ipc'
|
import type { ExportFormat, MarkdownApi, SaveMode, UiTheme } from '../shared/ipc'
|
||||||
|
|
||||||
const api: MarkdownApi = {
|
const api: MarkdownApi = {
|
||||||
consumePending: () => ipcRenderer.invoke(MARKDOWN_CHANNELS.consumePending),
|
consumePending: () => ipcRenderer.invoke(MARKDOWN_CHANNELS.consumePending),
|
||||||
@@ -43,6 +43,12 @@ const api: MarkdownApi = {
|
|||||||
ipcRenderer.on(MARKDOWN_CHANNELS.languageChanged, listener)
|
ipcRenderer.on(MARKDOWN_CHANNELS.languageChanged, listener)
|
||||||
return () => ipcRenderer.removeListener(MARKDOWN_CHANNELS.languageChanged, listener)
|
return () => ipcRenderer.removeListener(MARKDOWN_CHANNELS.languageChanged, listener)
|
||||||
},
|
},
|
||||||
|
getTheme: () => ipcRenderer.invoke(MARKDOWN_CHANNELS.getTheme),
|
||||||
|
onThemeChanged: (handler) => {
|
||||||
|
const listener = (_e: Electron.IpcRendererEvent, theme: UiTheme) => handler(theme)
|
||||||
|
ipcRenderer.on(MARKDOWN_CHANNELS.themeChanged, listener)
|
||||||
|
return () => ipcRenderer.removeListener(MARKDOWN_CHANNELS.themeChanged, listener)
|
||||||
|
},
|
||||||
getAiSettings: () => ipcRenderer.invoke(AI_CHANNELS.getSettings),
|
getAiSettings: () => ipcRenderer.invoke(AI_CHANNELS.getSettings),
|
||||||
aiStream: (request) => ipcRenderer.invoke(AI_CHANNELS.stream, request),
|
aiStream: (request) => ipcRenderer.invoke(AI_CHANNELS.stream, request),
|
||||||
aiStreamCancel: (requestId) => ipcRenderer.invoke(AI_CHANNELS.streamCancel, requestId),
|
aiStreamCancel: (requestId) => ipcRenderer.invoke(AI_CHANNELS.streamCancel, requestId),
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
frontmatterInner,
|
frontmatterInner,
|
||||||
parseDocText,
|
parseDocText,
|
||||||
serializeDocText,
|
serializeDocText,
|
||||||
|
stripLegacyFencedDivs,
|
||||||
type DocEnvelope,
|
type DocEnvelope,
|
||||||
} from './markdown/docText'
|
} from './markdown/docText'
|
||||||
import { buildExtensions } from './editor/extensions'
|
import { buildExtensions } from './editor/extensions'
|
||||||
@@ -18,7 +19,7 @@ import { SlashMenu, type SlashMenuHandle } from './components/SlashMenu'
|
|||||||
import { TableMenu } from './components/TableMenu'
|
import { TableMenu } from './components/TableMenu'
|
||||||
import { FrontmatterPanel } from './components/FrontmatterPanel'
|
import { FrontmatterPanel } from './components/FrontmatterPanel'
|
||||||
import { AiPanel, GensparkMark, type AiPreset, type MarkdownAiDeps } from './ai/AiPanel'
|
import { AiPanel, GensparkMark, type AiPreset, type MarkdownAiDeps } from './ai/AiPanel'
|
||||||
import { exportDocxBytes } from './export/docxExport'
|
import { DOCX_MAX_IMAGE_PX, exportDocxBytes } from './export/docxExport'
|
||||||
import { buildPrintHtml } from './export/printHtml'
|
import { buildPrintHtml } from './export/printHtml'
|
||||||
import { resolveImageSrc } from './editor/localImage'
|
import { resolveImageSrc } from './editor/localImage'
|
||||||
import type { ExportFormat, SaveMode } from '../shared/ipc'
|
import type { ExportFormat, SaveMode } from '../shared/ipc'
|
||||||
@@ -58,9 +59,6 @@ function measureImage(displaySrc: string): Promise<{ width: number; height: numb
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/** widest image that fits the A4 text column */
|
|
||||||
const DOCX_MAX_IMAGE_PX = 620
|
|
||||||
|
|
||||||
/** File name for an AI-generated untitled document: first heading, else first words */
|
/** File name for an AI-generated untitled document: first heading, else first words */
|
||||||
export function deriveAutoFileName(editor: Editor): string {
|
export function deriveAutoFileName(editor: Editor): string {
|
||||||
const doc = editor.state.doc
|
const doc = editor.state.doc
|
||||||
@@ -85,6 +83,7 @@ export default function App() {
|
|||||||
const [fmText, setFmText] = useState('')
|
const [fmText, setFmText] = useState('')
|
||||||
const [aiOpen, setAiOpen] = useState(true)
|
const [aiOpen, setAiOpen] = useState(true)
|
||||||
const [aiPreset, setAiPreset] = useState<AiPreset | null>(null)
|
const [aiPreset, setAiPreset] = useState<AiPreset | null>(null)
|
||||||
|
const [autoSave, setAutoSave] = useState(() => localStorage.getItem('mdapp.autoSave') === '1')
|
||||||
|
|
||||||
const statusRef = useRef<LoadStatus>('loading')
|
const statusRef = useRef<LoadStatus>('loading')
|
||||||
const dirtyRef = useRef(false)
|
const dirtyRef = useRef(false)
|
||||||
@@ -160,7 +159,7 @@ export default function App() {
|
|||||||
editor
|
editor
|
||||||
.chain()
|
.chain()
|
||||||
.setMeta('addToHistory', false)
|
.setMeta('addToHistory', false)
|
||||||
.setContent(envelope.body, { contentType: 'markdown' })
|
.setContent(stripLegacyFencedDivs(envelope.body), { contentType: 'markdown' })
|
||||||
.run()
|
.run()
|
||||||
setFilePath(path)
|
setFilePath(path)
|
||||||
const inner = frontmatterInner(envelope.frontmatter)
|
const inner = frontmatterInner(envelope.frontmatter)
|
||||||
@@ -302,6 +301,28 @@ export default function App() {
|
|||||||
}
|
}
|
||||||
}, [doSave])
|
}, [doSave])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
localStorage.setItem('mdapp.autoSave', autoSave ? '1' : '0')
|
||||||
|
}, [autoSave])
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!autoSave || !filePath) return
|
||||||
|
const tick = () => {
|
||||||
|
if (!dirtyRef.current) return
|
||||||
|
if (editorRef.current?.view.composing) return // don't interrupt IME input
|
||||||
|
void doSave('save')
|
||||||
|
}
|
||||||
|
const id = window.setInterval(tick, 30_000)
|
||||||
|
window.addEventListener('blur', tick)
|
||||||
|
return () => {
|
||||||
|
window.clearInterval(id)
|
||||||
|
window.removeEventListener('blur', tick)
|
||||||
|
}
|
||||||
|
}, [autoSave, filePath, doSave])
|
||||||
|
|
||||||
const aiDeps: MarkdownAiDeps = {
|
const aiDeps: MarkdownAiDeps = {
|
||||||
getEditor: () => editorRef.current,
|
getEditor: () => editorRef.current,
|
||||||
getSnapshot: () => editorRef.current?.getMarkdown() ?? '',
|
getSnapshot: () => editorRef.current?.getMarkdown() ?? '',
|
||||||
@@ -344,6 +365,10 @@ export default function App() {
|
|||||||
<Ribbon
|
<Ribbon
|
||||||
editor={editor}
|
editor={editor}
|
||||||
disabled={status !== 'ready'}
|
disabled={status !== 'ready'}
|
||||||
|
dirty={dirty}
|
||||||
|
onSave={() => void doSave('save')}
|
||||||
|
autoSave={autoSave}
|
||||||
|
onToggleAutoSave={setAutoSave}
|
||||||
imageEnabled={Boolean(filePath)}
|
imageEnabled={Boolean(filePath)}
|
||||||
onInsertImage={insertImage}
|
onInsertImage={insertImage}
|
||||||
frontmatterOpen={fmOpen}
|
frontmatterOpen={fmOpen}
|
||||||
|
|||||||
@@ -833,7 +833,7 @@ export function GensparkMark({ size = 18 }: { size?: number }): React.JSX.Elemen
|
|||||||
>
|
>
|
||||||
<path
|
<path
|
||||||
d="M105.115 0H24.6428C11.0443 0 0 11.0686 0 24.6915V105.334C0 118.981 11.0199 130.025 24.6428 130.025H105.115C118.714 130.025 129.758 118.957 129.758 105.334V24.6915C129.758 11.0443 118.714 0 105.115 0ZM71.5201 35.2735C85.5078 33.1571 86.7729 31.9164 88.865 17.88C88.938 17.4421 89.3028 17.1259 89.7407 17.1259C90.1786 17.1259 90.5435 17.4421 90.6164 17.88C92.7328 31.8921 93.9735 33.1571 107.961 35.2735C108.399 35.3465 108.715 35.7114 108.715 36.1493C108.715 36.5871 108.399 36.952 107.961 37.025C93.9249 39.1414 92.7085 40.4064 90.5677 54.6131C90.5191 54.9537 90.2516 55.197 89.911 55.197C89.5704 55.197 89.3028 54.9537 89.2542 54.6131C87.1134 40.4064 85.5565 39.1658 71.4958 37.025C71.0579 36.952 70.7417 36.5871 70.7417 36.1493C70.7417 35.7114 71.0579 35.3465 71.4958 35.2735H71.5201ZM101.758 78.5261C101.758 78.8181 101.563 79.037 101.271 79.0856C92.3193 80.4236 91.5652 81.2264 90.2029 90.2759C90.1786 90.4948 89.9839 90.6408 89.7893 90.6408C89.5703 90.6408 89.4001 90.4948 89.3758 90.2759C88.0135 81.2507 87.0161 80.4479 78.0883 79.0856C77.7964 79.037 77.6017 78.7937 77.6017 78.5261C77.6017 78.2342 77.7964 78.0153 78.0883 77.9666C86.9918 76.6287 87.7703 75.8259 89.1326 66.898C89.1812 66.6061 89.4244 66.4115 89.692 66.4115C89.9839 66.4115 90.2028 66.6061 90.2515 66.898C91.5894 75.8259 92.3923 76.6043 101.296 77.9666C101.588 78.0153 101.782 78.2585 101.782 78.5261H101.758ZM16.5178 54.8077C16.5178 54.1023 17.0286 53.4941 17.7341 53.3968C40.1388 50.0154 42.1093 47.9963 45.4907 25.5672C45.588 24.8861 46.1961 24.3509 46.9016 24.3509C47.6071 24.3509 48.191 24.8617 48.3126 25.5672C51.694 47.9963 53.6887 50.0154 76.0691 53.3968C76.7503 53.4941 77.2855 54.1023 77.2855 54.8077C77.2855 55.5132 76.7746 56.1214 76.0691 56.2187C53.5914 59.6244 51.6696 61.6192 48.2639 84.3645C48.1909 84.8754 47.7287 85.2889 47.2179 85.2889C46.707 85.2889 46.2448 84.8997 46.1718 84.3645C42.7418 61.6435 40.2604 59.6244 17.7584 56.2187C17.0772 56.1214 16.542 55.5132 16.542 54.8077H16.5178ZM112.097 109.591C112.097 111.416 110.613 112.9 108.813 112.9H21.2614C19.4369 112.9 17.9774 111.416 17.9774 109.591V102.658C17.9774 100.834 19.4612 99.3497 21.2614 99.3497H108.813C110.637 99.3497 112.097 100.834 112.097 102.658V109.591Z"
|
d="M105.115 0H24.6428C11.0443 0 0 11.0686 0 24.6915V105.334C0 118.981 11.0199 130.025 24.6428 130.025H105.115C118.714 130.025 129.758 118.957 129.758 105.334V24.6915C129.758 11.0443 118.714 0 105.115 0ZM71.5201 35.2735C85.5078 33.1571 86.7729 31.9164 88.865 17.88C88.938 17.4421 89.3028 17.1259 89.7407 17.1259C90.1786 17.1259 90.5435 17.4421 90.6164 17.88C92.7328 31.8921 93.9735 33.1571 107.961 35.2735C108.399 35.3465 108.715 35.7114 108.715 36.1493C108.715 36.5871 108.399 36.952 107.961 37.025C93.9249 39.1414 92.7085 40.4064 90.5677 54.6131C90.5191 54.9537 90.2516 55.197 89.911 55.197C89.5704 55.197 89.3028 54.9537 89.2542 54.6131C87.1134 40.4064 85.5565 39.1658 71.4958 37.025C71.0579 36.952 70.7417 36.5871 70.7417 36.1493C70.7417 35.7114 71.0579 35.3465 71.4958 35.2735H71.5201ZM101.758 78.5261C101.758 78.8181 101.563 79.037 101.271 79.0856C92.3193 80.4236 91.5652 81.2264 90.2029 90.2759C90.1786 90.4948 89.9839 90.6408 89.7893 90.6408C89.5703 90.6408 89.4001 90.4948 89.3758 90.2759C88.0135 81.2507 87.0161 80.4479 78.0883 79.0856C77.7964 79.037 77.6017 78.7937 77.6017 78.5261C77.6017 78.2342 77.7964 78.0153 78.0883 77.9666C86.9918 76.6287 87.7703 75.8259 89.1326 66.898C89.1812 66.6061 89.4244 66.4115 89.692 66.4115C89.9839 66.4115 90.2028 66.6061 90.2515 66.898C91.5894 75.8259 92.3923 76.6043 101.296 77.9666C101.588 78.0153 101.782 78.2585 101.782 78.5261H101.758ZM16.5178 54.8077C16.5178 54.1023 17.0286 53.4941 17.7341 53.3968C40.1388 50.0154 42.1093 47.9963 45.4907 25.5672C45.588 24.8861 46.1961 24.3509 46.9016 24.3509C47.6071 24.3509 48.191 24.8617 48.3126 25.5672C51.694 47.9963 53.6887 50.0154 76.0691 53.3968C76.7503 53.4941 77.2855 54.1023 77.2855 54.8077C77.2855 55.5132 76.7746 56.1214 76.0691 56.2187C53.5914 59.6244 51.6696 61.6192 48.2639 84.3645C48.1909 84.8754 47.7287 85.2889 47.2179 85.2889C46.707 85.2889 46.2448 84.8997 46.1718 84.3645C42.7418 61.6435 40.2604 59.6244 17.7584 56.2187C17.0772 56.1214 16.542 55.5132 16.542 54.8077H16.5178ZM112.097 109.591C112.097 111.416 110.613 112.9 108.813 112.9H21.2614C19.4369 112.9 17.9774 111.416 17.9774 109.591V102.658C17.9774 100.834 19.4612 99.3497 21.2614 99.3497H108.813C110.637 99.3497 112.097 100.834 112.097 102.658V109.591Z"
|
||||||
fill="#000"
|
fill="currentColor"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,21 +2,31 @@ import type { AgentSkill } from '@genoffice/agent-core'
|
|||||||
import type { Editor } from '@tiptap/core'
|
import type { Editor } from '@tiptap/core'
|
||||||
import { AGENT_TOOLS, buildDocContext, executeTool, markDocSeen } from './tools'
|
import { AGENT_TOOLS, buildDocContext, executeTool, markDocSeen } from './tools'
|
||||||
|
|
||||||
|
const MARKDOWN_RULES = [
|
||||||
|
'All markdown passed to tools must be pure GFM. Rules:',
|
||||||
|
'- Allowed syntax, and nothing else: `#`–`######` headings, paragraphs, `**bold**`, `*italic*`, `~~strikethrough~~`, `` `inline code` ``, `[links](url)`, ``, `-` / `1.` lists, `- [ ]` task lists, `>` blockquotes, ``` fenced code blocks, `|` pipe tables, `---` horizontal rules, hard line breaks (two trailing spaces).',
|
||||||
|
'- Never emit raw HTML — no tag of any kind (`<span>`, `<div>`, `<p>`, `<img>`, `<br>`, `<u>`, `<mark>`, …) and no style attributes. The editor forces everything through its GFM-only schema: semantic tags degrade to plain GFM and all other tags and styling are silently dropped.',
|
||||||
|
'- Never emit non-GFM extensions: `==highlight==`, `++underline++`, `:::` fenced divs, footnotes, math, or emoji shortcodes. They are not parsed and end up as literal text in the document.',
|
||||||
|
'- This editor has no colored text, fonts, font sizes, underline, highlight, alignment, or line spacing. If the user asks for such styling, explain that pure markdown cannot express it — never fake it with HTML.',
|
||||||
|
'- Express emphasis through structure instead: headings for hierarchy, bold for key phrases, blockquotes for callout-style notes, tables for comparisons.',
|
||||||
|
].join('\n')
|
||||||
|
|
||||||
const AGENT_SYSTEM_PROMPT = [
|
const AGENT_SYSTEM_PROMPT = [
|
||||||
'You are the writing assistant inside GenOffice Markdown, a markdown document editor.',
|
'You are the writing assistant inside GenOffice Markdown, a markdown document editor.',
|
||||||
'You read and edit the open document through tools that address top-level blocks by 0-based index.',
|
'You read and edit the open document through tools that address top-level blocks by 0-based index.',
|
||||||
'',
|
'',
|
||||||
|
'## Markdown syntax rules',
|
||||||
|
MARKDOWN_RULES,
|
||||||
|
'',
|
||||||
'## Editing rules',
|
'## Editing rules',
|
||||||
'- The per-message document state lists every block as `index | type | preview`. Previews are truncated — use read_blocks when you need full text.',
|
'- The per-message document state lists every block as `index | type | preview`. Previews are truncated — use read_blocks when you need full text.',
|
||||||
'- Write standard GFM markdown: headings, lists, task lists (`- [ ]`), tables, fenced code blocks, blockquotes, images, horizontal rules.',
|
|
||||||
'- Two extra fenced-div blocks are available: `:::callout {type="info|tip|warning|danger"}` for admonitions and `:::toggle {summary="Title"}` for collapsible sections, each closed with `:::` on its own line.',
|
|
||||||
'- Prefer replace_blocks for rewrites and formatting changes; insert_content for additions. Batch related edits into as few calls as possible.',
|
'- Prefer replace_blocks for rewrites and formatting changes; insert_content for additions. Batch related edits into as few calls as possible.',
|
||||||
'- After a mutating call, block indexes change — refresh with get_document_context before more index-based edits.',
|
'- After a mutating call, block indexes change — refresh with get_document_context before more index-based edits.',
|
||||||
'- If a tool reports the document changed under you, refresh the context and re-plan instead of retrying blindly.',
|
'- If a tool reports the document changed under you, refresh the context and re-plan instead of retrying blindly.',
|
||||||
'',
|
'',
|
||||||
'## Writing a new document',
|
'## Writing a new document',
|
||||||
'- When the document is blank and the user asks for content, write the full document in one insert_content call: start with a single `#` title, use `##` sections, keep paragraphs short.',
|
'- When the document is blank and the user asks for content, write the full document in one insert_content call: start with a single `#` title, use `##` sections, keep paragraphs short.',
|
||||||
'- Use tables for comparisons, task lists for actionable items, callouts for important notes.',
|
'- Use tables for comparisons, task lists for actionable items, blockquotes for important notes.',
|
||||||
'- Never invent facts or numbers; use web_search when the topic needs current information and attribute sources.',
|
'- Never invent facts or numbers; use web_search when the topic needs current information and attribute sources.',
|
||||||
'',
|
'',
|
||||||
'## Conversation',
|
'## Conversation',
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { Editor, JSONContent } from '@tiptap/core'
|
|||||||
import type { Node as PmNode } from '@tiptap/pm/model'
|
import type { Node as PmNode } from '@tiptap/pm/model'
|
||||||
import type { AgentToolCall, AgentToolDef, ToolExecution } from '@genoffice/agent-core'
|
import type { AgentToolCall, AgentToolDef, ToolExecution } from '@genoffice/agent-core'
|
||||||
import { markAiRange } from '../editor/aiHighlight'
|
import { markAiRange } from '../editor/aiHighlight'
|
||||||
|
import { stripLegacyFencedDivs } from '../markdown/docText'
|
||||||
import { t } from '../i18n/locale'
|
import { t } from '../i18n/locale'
|
||||||
|
|
||||||
const CONTEXT_MAX_CHARS = 8000
|
const CONTEXT_MAX_CHARS = 8000
|
||||||
@@ -166,7 +167,12 @@ function blockRange(doc: PmNode, from: number, to: number): { from: number; to:
|
|||||||
}
|
}
|
||||||
|
|
||||||
function parseMarkdownToNodes(editor: Editor, markdown: string): PmNode[] {
|
function parseMarkdownToNodes(editor: Editor, markdown: string): PmNode[] {
|
||||||
const json = editor.markdown?.parse(markdown)
|
// model output guard: `:::` fenced divs are not GFM and would land as
|
||||||
|
// literal text — strip the fences and keep the body (same as file open).
|
||||||
|
// Raw HTML needs no guard: parse runs it through the schema, so semantic
|
||||||
|
// tags degrade to their GFM equivalents (<b>→bold, <img>→image) and
|
||||||
|
// anything the schema cannot represent loses its styling, keeping text.
|
||||||
|
const json = editor.markdown?.parse(stripLegacyFencedDivs(markdown))
|
||||||
const content = json?.content ?? []
|
const content = json?.content ?? []
|
||||||
return content.map((c) => editor.schema.nodeFromJSON(c))
|
return content.map((c) => editor.schema.nodeFromJSON(c))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,16 +8,14 @@ import { GensparkMark } from '../ai/AiPanel'
|
|||||||
import { liftFromList } from '../editor/slashCommand'
|
import { liftFromList } from '../editor/slashCommand'
|
||||||
import {
|
import {
|
||||||
IconBullets,
|
IconBullets,
|
||||||
IconHighlight,
|
|
||||||
IconHr,
|
IconHr,
|
||||||
IconIndentDec,
|
|
||||||
IconIndentInc,
|
|
||||||
IconInlineCode,
|
IconInlineCode,
|
||||||
IconLink,
|
IconLink,
|
||||||
IconNumbered,
|
IconNumbered,
|
||||||
IconPicture,
|
IconPicture,
|
||||||
IconProperties,
|
IconProperties,
|
||||||
IconRedo,
|
IconRedo,
|
||||||
|
IconSave,
|
||||||
IconTable,
|
IconTable,
|
||||||
IconTaskList,
|
IconTaskList,
|
||||||
IconUndo,
|
IconUndo,
|
||||||
@@ -26,6 +24,10 @@ import {
|
|||||||
interface Props {
|
interface Props {
|
||||||
editor: Editor | null
|
editor: Editor | null
|
||||||
disabled: boolean
|
disabled: boolean
|
||||||
|
dirty: boolean
|
||||||
|
onSave: () => void
|
||||||
|
autoSave: boolean
|
||||||
|
onToggleAutoSave: (on: boolean) => void
|
||||||
imageEnabled: boolean
|
imageEnabled: boolean
|
||||||
onInsertImage: () => void
|
onInsertImage: () => void
|
||||||
frontmatterOpen: boolean
|
frontmatterOpen: boolean
|
||||||
@@ -35,18 +37,7 @@ interface Props {
|
|||||||
onAiPreset: (instruction: string) => void
|
onAiPreset: (instruction: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
type BlockStyle =
|
type BlockStyle = 'paragraph' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'quote' | 'codeBlock'
|
||||||
| 'paragraph'
|
|
||||||
| 'h1'
|
|
||||||
| 'h2'
|
|
||||||
| 'h3'
|
|
||||||
| 'h4'
|
|
||||||
| 'h5'
|
|
||||||
| 'h6'
|
|
||||||
| 'quote'
|
|
||||||
| 'codeBlock'
|
|
||||||
| 'callout'
|
|
||||||
| 'toggle'
|
|
||||||
|
|
||||||
const STYLE_LABEL: Record<BlockStyle, StringKey> = {
|
const STYLE_LABEL: Record<BlockStyle, StringKey> = {
|
||||||
paragraph: 'styleParagraph',
|
paragraph: 'styleParagraph',
|
||||||
@@ -58,17 +49,12 @@ const STYLE_LABEL: Record<BlockStyle, StringKey> = {
|
|||||||
h6: 'styleH6',
|
h6: 'styleH6',
|
||||||
quote: 'styleQuote',
|
quote: 'styleQuote',
|
||||||
codeBlock: 'styleCodeBlock',
|
codeBlock: 'styleCodeBlock',
|
||||||
callout: 'insertCallout',
|
|
||||||
toggle: 'insertToggle',
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function applyBlockStyle(editor: Editor, style: BlockStyle): void {
|
function applyBlockStyle(editor: Editor, style: BlockStyle): void {
|
||||||
// block-type conversions are illegal inside list items — leave the list first
|
// block-type conversions are illegal inside list items — leave the list first
|
||||||
liftFromList(editor)
|
liftFromList(editor)
|
||||||
const chain = editor.chain().focus()
|
const chain = editor.chain().focus()
|
||||||
// unwrap wrappers the target style does not keep
|
|
||||||
if (style !== 'callout' && editor.isActive('callout')) chain.unsetCallout()
|
|
||||||
if (style !== 'toggle' && editor.isActive('toggle')) chain.unsetToggle()
|
|
||||||
switch (style) {
|
switch (style) {
|
||||||
case 'paragraph':
|
case 'paragraph':
|
||||||
chain.setParagraph().run()
|
chain.setParagraph().run()
|
||||||
@@ -79,12 +65,6 @@ function applyBlockStyle(editor: Editor, style: BlockStyle): void {
|
|||||||
case 'codeBlock':
|
case 'codeBlock':
|
||||||
chain.setCodeBlock().run()
|
chain.setCodeBlock().run()
|
||||||
break
|
break
|
||||||
case 'callout':
|
|
||||||
chain.setCallout().run()
|
|
||||||
break
|
|
||||||
case 'toggle':
|
|
||||||
chain.setToggle().run()
|
|
||||||
break
|
|
||||||
default:
|
default:
|
||||||
chain.setHeading({ level: Number(style.slice(1)) as 1 | 2 | 3 | 4 | 5 | 6 }).run()
|
chain.setHeading({ level: Number(style.slice(1)) as 1 | 2 | 3 | 4 | 5 | 6 }).run()
|
||||||
}
|
}
|
||||||
@@ -162,6 +142,10 @@ function IconBtn({
|
|||||||
export function Ribbon({
|
export function Ribbon({
|
||||||
editor,
|
editor,
|
||||||
disabled,
|
disabled,
|
||||||
|
dirty,
|
||||||
|
onSave,
|
||||||
|
autoSave,
|
||||||
|
onToggleAutoSave,
|
||||||
imageEnabled,
|
imageEnabled,
|
||||||
onInsertImage,
|
onInsertImage,
|
||||||
frontmatterOpen,
|
frontmatterOpen,
|
||||||
@@ -179,31 +163,24 @@ export function Ribbon({
|
|||||||
editor,
|
editor,
|
||||||
selector: ({ editor: e }) => {
|
selector: ({ editor: e }) => {
|
||||||
if (!e) return null
|
if (!e) return null
|
||||||
const style: BlockStyle = e.isActive('callout')
|
const style: BlockStyle = e.isActive('codeBlock')
|
||||||
? 'callout'
|
? 'codeBlock'
|
||||||
: e.isActive('toggle')
|
: e.isActive('blockquote')
|
||||||
? 'toggle'
|
? 'quote'
|
||||||
: e.isActive('codeBlock')
|
: e.isActive('heading')
|
||||||
? 'codeBlock'
|
? (`h${e.getAttributes('heading').level}` as BlockStyle)
|
||||||
: e.isActive('blockquote')
|
: 'paragraph'
|
||||||
? 'quote'
|
|
||||||
: e.isActive('heading')
|
|
||||||
? (`h${e.getAttributes('heading').level}` as BlockStyle)
|
|
||||||
: 'paragraph'
|
|
||||||
return {
|
return {
|
||||||
style,
|
style,
|
||||||
empty: e.isEmpty,
|
empty: e.isEmpty,
|
||||||
bold: e.isActive('bold'),
|
bold: e.isActive('bold'),
|
||||||
italic: e.isActive('italic'),
|
italic: e.isActive('italic'),
|
||||||
strike: e.isActive('strike'),
|
strike: e.isActive('strike'),
|
||||||
underline: e.isActive('underline'),
|
|
||||||
highlight: e.isActive('highlight'),
|
|
||||||
code: e.isActive('code'),
|
code: e.isActive('code'),
|
||||||
link: e.isActive('link'),
|
link: e.isActive('link'),
|
||||||
bullet: e.isActive('bulletList'),
|
bullet: e.isActive('bulletList'),
|
||||||
ordered: e.isActive('orderedList'),
|
ordered: e.isActive('orderedList'),
|
||||||
task: e.isActive('taskList'),
|
task: e.isActive('taskList'),
|
||||||
inList: e.isActive('listItem') || e.isActive('taskItem'),
|
|
||||||
canUndo: e.can().undo(),
|
canUndo: e.can().undo(),
|
||||||
canRedo: e.can().redo(),
|
canRedo: e.can().redo(),
|
||||||
}
|
}
|
||||||
@@ -231,8 +208,9 @@ export function Ribbon({
|
|||||||
setLinkOpen(false)
|
setLinkOpen(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
const listItemName = state?.task ? 'taskItem' : 'listItem'
|
// 20px inline-row rendering, same as the docs toolbar these icons come from
|
||||||
const ICON = 16
|
// (pinned stroke paints 1.5px at this size per the suite-wide icon rules)
|
||||||
|
const ICON = 20
|
||||||
|
|
||||||
const aiPresets = [
|
const aiPresets = [
|
||||||
{ kind: 'summarize', btn: 'aiSummarizeBtn', prompt: 'aiSummarizePrompt' },
|
{ kind: 'summarize', btn: 'aiSummarizeBtn', prompt: 'aiSummarizePrompt' },
|
||||||
@@ -242,236 +220,230 @@ export function Ribbon({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="ribbon">
|
<div className="ribbon">
|
||||||
<div className="ribbon-group">
|
{/* quick-access row above the toolbar (save / undo / redo / autosave), same as the docs QAT row */}
|
||||||
<div className="ribbon-group-items">
|
<div className="ribbon-tabs">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className={`rb-big ai-entry${aiOpen ? ' active' : ''}`}
|
className="qa-btn"
|
||||||
title={t('aiOpenAssistant')}
|
title={t('save')}
|
||||||
disabled={disabled}
|
disabled={off || !dirty}
|
||||||
onMouseDown={(e) => e.preventDefault()}
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
onClick={onToggleAi}
|
onClick={onSave}
|
||||||
>
|
>
|
||||||
<span className="rb-big-icon">
|
<IconSave size={16} />
|
||||||
<GensparkMark size={26} />
|
</button>
|
||||||
</span>
|
<button
|
||||||
<span>Genspark AI</span>
|
type="button"
|
||||||
</button>
|
className="qa-btn"
|
||||||
{aiPresets.map(({ kind, btn, prompt }) => (
|
|
||||||
<button
|
|
||||||
key={kind}
|
|
||||||
type="button"
|
|
||||||
className="rb-big ai-entry"
|
|
||||||
title={t(prompt)}
|
|
||||||
disabled={off || state?.empty}
|
|
||||||
onMouseDown={(e) => e.preventDefault()}
|
|
||||||
onClick={() => onAiPreset(t(prompt))}
|
|
||||||
>
|
|
||||||
<span className="rb-big-icon">
|
|
||||||
<span className="ai-feature-icon" aria-hidden="true">
|
|
||||||
<AiFeatureIcon kind={kind} />
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
<span>{t(btn)}</span>
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="rb-sep" />
|
|
||||||
|
|
||||||
<div className="rb-group">
|
|
||||||
<IconBtn
|
|
||||||
title={t('undo')}
|
title={t('undo')}
|
||||||
disabled={off || !state?.canUndo}
|
disabled={off || !state?.canUndo}
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
onClick={() => editor?.chain().focus().undo().run()}
|
onClick={() => editor?.chain().focus().undo().run()}
|
||||||
>
|
>
|
||||||
<IconUndo size={ICON} />
|
<IconUndo size={16} />
|
||||||
</IconBtn>
|
</button>
|
||||||
<IconBtn
|
<button
|
||||||
|
type="button"
|
||||||
|
className="qa-btn"
|
||||||
title={t('redo')}
|
title={t('redo')}
|
||||||
disabled={off || !state?.canRedo}
|
disabled={off || !state?.canRedo}
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
onClick={() => editor?.chain().focus().redo().run()}
|
onClick={() => editor?.chain().focus().redo().run()}
|
||||||
>
|
>
|
||||||
<IconRedo size={ICON} />
|
<IconRedo size={16} />
|
||||||
</IconBtn>
|
</button>
|
||||||
|
<label className={`autosave-toggle${autoSave ? ' on' : ''}`} title={t('autoSaveTip')}>
|
||||||
|
<span className="autosave-knob" />
|
||||||
|
<span className="autosave-text">{t('autoSave')}</span>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={autoSave}
|
||||||
|
onChange={(e) => onToggleAutoSave(e.target.checked)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="rb-sep" />
|
<div className="ribbon-body">
|
||||||
|
<div className="ribbon-group">
|
||||||
<select
|
<div className="ribbon-group-items">
|
||||||
className="rb-style"
|
<button
|
||||||
value={state?.style ?? 'paragraph'}
|
type="button"
|
||||||
disabled={off}
|
className={`rb-big ai-entry${aiOpen ? ' active' : ''}`}
|
||||||
onChange={(e) => editor && applyBlockStyle(editor, e.target.value as BlockStyle)}
|
title={t('aiOpenAssistant')}
|
||||||
>
|
disabled={disabled}
|
||||||
{(Object.keys(STYLE_LABEL) as BlockStyle[]).map((s) => (
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
<option key={s} value={s}>
|
onClick={onToggleAi}
|
||||||
{t(STYLE_LABEL[s])}
|
>
|
||||||
</option>
|
<span className="rb-big-icon">
|
||||||
))}
|
<GensparkMark size={26} />
|
||||||
</select>
|
</span>
|
||||||
|
<span>Genspark AI</span>
|
||||||
<div className="rb-sep" />
|
</button>
|
||||||
|
{aiPresets.map(({ kind, btn, prompt }) => (
|
||||||
<div className="rb-group">
|
<button
|
||||||
<IconBtn
|
key={kind}
|
||||||
title={t('bold')}
|
type="button"
|
||||||
active={state?.bold}
|
className="rb-big ai-entry"
|
||||||
disabled={off}
|
title={t(prompt)}
|
||||||
onClick={() => editor?.chain().focus().toggleBold().run()}
|
disabled={off || state?.empty}
|
||||||
>
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
<span className="rb-glyph" style={{ fontWeight: 800 }}>
|
onClick={() => onAiPreset(t(prompt))}
|
||||||
B
|
>
|
||||||
</span>
|
<span className="rb-big-icon">
|
||||||
</IconBtn>
|
<span className="ai-feature-icon" aria-hidden="true">
|
||||||
<IconBtn
|
<AiFeatureIcon kind={kind} />
|
||||||
title={t('italic')}
|
</span>
|
||||||
active={state?.italic}
|
</span>
|
||||||
disabled={off}
|
<span>{t(btn)}</span>
|
||||||
onClick={() => editor?.chain().focus().toggleItalic().run()}
|
|
||||||
>
|
|
||||||
<span className="rb-glyph" style={{ fontStyle: 'italic' }}>
|
|
||||||
I
|
|
||||||
</span>
|
|
||||||
</IconBtn>
|
|
||||||
<IconBtn
|
|
||||||
title={t('underline')}
|
|
||||||
active={state?.underline}
|
|
||||||
disabled={off}
|
|
||||||
onClick={() => editor?.chain().focus().toggleUnderline().run()}
|
|
||||||
>
|
|
||||||
<span className="rb-glyph" style={{ textDecoration: 'underline' }}>
|
|
||||||
U
|
|
||||||
</span>
|
|
||||||
</IconBtn>
|
|
||||||
<IconBtn
|
|
||||||
title={t('strike')}
|
|
||||||
active={state?.strike}
|
|
||||||
disabled={off}
|
|
||||||
onClick={() => editor?.chain().focus().toggleStrike().run()}
|
|
||||||
>
|
|
||||||
<span className="rb-glyph" style={{ textDecoration: 'line-through' }}>
|
|
||||||
S
|
|
||||||
</span>
|
|
||||||
</IconBtn>
|
|
||||||
<IconBtn
|
|
||||||
title={t('highlight')}
|
|
||||||
active={state?.highlight}
|
|
||||||
disabled={off}
|
|
||||||
onClick={() => editor?.chain().focus().toggleHighlight().run()}
|
|
||||||
>
|
|
||||||
<IconHighlight size={ICON} />
|
|
||||||
</IconBtn>
|
|
||||||
<IconBtn
|
|
||||||
title={t('inlineCode')}
|
|
||||||
active={state?.code}
|
|
||||||
disabled={off}
|
|
||||||
onClick={() => editor?.chain().focus().toggleCode().run()}
|
|
||||||
>
|
|
||||||
<IconInlineCode size={ICON} />
|
|
||||||
</IconBtn>
|
|
||||||
<span className="rb-link-anchor">
|
|
||||||
<IconBtn title={t('link')} active={state?.link} disabled={off} onClick={openLink}>
|
|
||||||
<IconLink size={ICON} />
|
|
||||||
</IconBtn>
|
|
||||||
{linkOpen && (
|
|
||||||
<span className="rb-link-pop" onMouseDown={(e) => e.stopPropagation()}>
|
|
||||||
<input
|
|
||||||
ref={linkInputRef}
|
|
||||||
value={linkUrl}
|
|
||||||
placeholder={t('linkPlaceholder')}
|
|
||||||
onChange={(e) => setLinkUrl(e.target.value)}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === 'Enter') applyLink()
|
|
||||||
if (e.key === 'Escape') setLinkOpen(false)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<button type="button" onClick={applyLink}>
|
|
||||||
{t('linkApply')}
|
|
||||||
</button>
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rb-sep" />
|
||||||
|
|
||||||
|
<select
|
||||||
|
className="rb-style"
|
||||||
|
value={state?.style ?? 'paragraph'}
|
||||||
|
disabled={off}
|
||||||
|
onChange={(e) => editor && applyBlockStyle(editor, e.target.value as BlockStyle)}
|
||||||
|
>
|
||||||
|
{(Object.keys(STYLE_LABEL) as BlockStyle[]).map((s) => (
|
||||||
|
<option key={s} value={s}>
|
||||||
|
{t(STYLE_LABEL[s])}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<div className="rb-sep" />
|
||||||
|
|
||||||
|
<div className="rb-group">
|
||||||
|
<IconBtn
|
||||||
|
title={t('bold')}
|
||||||
|
active={state?.bold}
|
||||||
|
disabled={off}
|
||||||
|
onClick={() => editor?.chain().focus().toggleBold().run()}
|
||||||
|
>
|
||||||
|
<span className="rb-glyph" style={{ fontWeight: 800 }}>
|
||||||
|
B
|
||||||
</span>
|
</span>
|
||||||
)}
|
</IconBtn>
|
||||||
</span>
|
<IconBtn
|
||||||
</div>
|
title={t('italic')}
|
||||||
|
active={state?.italic}
|
||||||
|
disabled={off}
|
||||||
|
onClick={() => editor?.chain().focus().toggleItalic().run()}
|
||||||
|
>
|
||||||
|
<span className="rb-glyph" style={{ fontStyle: 'italic' }}>
|
||||||
|
I
|
||||||
|
</span>
|
||||||
|
</IconBtn>
|
||||||
|
<IconBtn
|
||||||
|
title={t('strike')}
|
||||||
|
active={state?.strike}
|
||||||
|
disabled={off}
|
||||||
|
onClick={() => editor?.chain().focus().toggleStrike().run()}
|
||||||
|
>
|
||||||
|
<span className="rb-glyph" style={{ textDecoration: 'line-through' }}>
|
||||||
|
S
|
||||||
|
</span>
|
||||||
|
</IconBtn>
|
||||||
|
<IconBtn
|
||||||
|
title={t('inlineCode')}
|
||||||
|
active={state?.code}
|
||||||
|
disabled={off}
|
||||||
|
onClick={() => editor?.chain().focus().toggleCode().run()}
|
||||||
|
>
|
||||||
|
<IconInlineCode size={ICON} />
|
||||||
|
</IconBtn>
|
||||||
|
<span className="rb-link-anchor">
|
||||||
|
<IconBtn title={t('link')} active={state?.link} disabled={off} onClick={openLink}>
|
||||||
|
<IconLink size={ICON} />
|
||||||
|
</IconBtn>
|
||||||
|
{linkOpen && (
|
||||||
|
<span className="rb-link-pop" onMouseDown={(e) => e.stopPropagation()}>
|
||||||
|
<input
|
||||||
|
ref={linkInputRef}
|
||||||
|
value={linkUrl}
|
||||||
|
placeholder={t('linkPlaceholder')}
|
||||||
|
onChange={(e) => setLinkUrl(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') applyLink()
|
||||||
|
if (e.key === 'Escape') setLinkOpen(false)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<button type="button" onClick={applyLink}>
|
||||||
|
{t('linkApply')}
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="rb-sep" />
|
<div className="rb-sep" />
|
||||||
|
|
||||||
|
<div className="rb-group">
|
||||||
|
<IconBtn
|
||||||
|
title={t('bulletList')}
|
||||||
|
active={state?.bullet}
|
||||||
|
disabled={off}
|
||||||
|
onClick={() => editor?.chain().focus().toggleBulletList().run()}
|
||||||
|
>
|
||||||
|
<IconBullets size={ICON} />
|
||||||
|
</IconBtn>
|
||||||
|
<IconBtn
|
||||||
|
title={t('orderedList')}
|
||||||
|
active={state?.ordered}
|
||||||
|
disabled={off}
|
||||||
|
onClick={() => editor?.chain().focus().toggleOrderedList().run()}
|
||||||
|
>
|
||||||
|
<IconNumbered size={ICON} />
|
||||||
|
</IconBtn>
|
||||||
|
<IconBtn
|
||||||
|
title={t('taskList')}
|
||||||
|
active={state?.task}
|
||||||
|
disabled={off}
|
||||||
|
onClick={() => editor?.chain().focus().toggleTaskList().run()}
|
||||||
|
>
|
||||||
|
<IconTaskList size={ICON} />
|
||||||
|
</IconBtn>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rb-sep" />
|
||||||
|
|
||||||
|
<div className="rb-group">
|
||||||
|
<IconBtn
|
||||||
|
title={t('insertTable')}
|
||||||
|
disabled={off}
|
||||||
|
onClick={() =>
|
||||||
|
editor?.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run()
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<IconTable size={ICON} />
|
||||||
|
</IconBtn>
|
||||||
|
<IconBtn title={t('insertImage')} disabled={off || !imageEnabled} onClick={onInsertImage}>
|
||||||
|
<IconPicture size={ICON} />
|
||||||
|
</IconBtn>
|
||||||
|
<IconBtn
|
||||||
|
title={t('insertHr')}
|
||||||
|
disabled={off}
|
||||||
|
onClick={() => editor?.chain().focus().setHorizontalRule().run()}
|
||||||
|
>
|
||||||
|
<IconHr size={ICON} />
|
||||||
|
</IconBtn>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rb-spacer" />
|
||||||
|
|
||||||
<div className="rb-group">
|
|
||||||
<IconBtn
|
<IconBtn
|
||||||
title={t('bulletList')}
|
title={t('fmProperties')}
|
||||||
active={state?.bullet}
|
active={frontmatterOpen}
|
||||||
disabled={off}
|
disabled={disabled}
|
||||||
onClick={() => editor?.chain().focus().toggleBulletList().run()}
|
onClick={onToggleFrontmatter}
|
||||||
>
|
>
|
||||||
<IconBullets size={ICON} />
|
<IconProperties size={ICON} />
|
||||||
</IconBtn>
|
|
||||||
<IconBtn
|
|
||||||
title={t('orderedList')}
|
|
||||||
active={state?.ordered}
|
|
||||||
disabled={off}
|
|
||||||
onClick={() => editor?.chain().focus().toggleOrderedList().run()}
|
|
||||||
>
|
|
||||||
<IconNumbered size={ICON} />
|
|
||||||
</IconBtn>
|
|
||||||
<IconBtn
|
|
||||||
title={t('taskList')}
|
|
||||||
active={state?.task}
|
|
||||||
disabled={off}
|
|
||||||
onClick={() => editor?.chain().focus().toggleTaskList().run()}
|
|
||||||
>
|
|
||||||
<IconTaskList size={ICON} />
|
|
||||||
</IconBtn>
|
|
||||||
<IconBtn
|
|
||||||
title={t('outdent')}
|
|
||||||
disabled={off || !state?.inList}
|
|
||||||
onClick={() => editor?.chain().focus().liftListItem(listItemName).run()}
|
|
||||||
>
|
|
||||||
<IconIndentDec size={ICON} />
|
|
||||||
</IconBtn>
|
|
||||||
<IconBtn
|
|
||||||
title={t('indent')}
|
|
||||||
disabled={off || !state?.inList}
|
|
||||||
onClick={() => editor?.chain().focus().sinkListItem(listItemName).run()}
|
|
||||||
>
|
|
||||||
<IconIndentInc size={ICON} />
|
|
||||||
</IconBtn>
|
</IconBtn>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="rb-sep" />
|
|
||||||
|
|
||||||
<div className="rb-group">
|
|
||||||
<IconBtn
|
|
||||||
title={t('insertTable')}
|
|
||||||
disabled={off}
|
|
||||||
onClick={() =>
|
|
||||||
editor?.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run()
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<IconTable size={ICON} />
|
|
||||||
</IconBtn>
|
|
||||||
<IconBtn title={t('insertImage')} disabled={off || !imageEnabled} onClick={onInsertImage}>
|
|
||||||
<IconPicture size={ICON} />
|
|
||||||
</IconBtn>
|
|
||||||
<IconBtn
|
|
||||||
title={t('insertHr')}
|
|
||||||
disabled={off}
|
|
||||||
onClick={() => editor?.chain().focus().setHorizontalRule().run()}
|
|
||||||
>
|
|
||||||
<IconHr size={ICON} />
|
|
||||||
</IconBtn>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="rb-spacer" />
|
|
||||||
|
|
||||||
<IconBtn
|
|
||||||
title={t('fmProperties')}
|
|
||||||
active={frontmatterOpen}
|
|
||||||
disabled={disabled}
|
|
||||||
onClick={onToggleFrontmatter}
|
|
||||||
>
|
|
||||||
<IconProperties size={ICON} />
|
|
||||||
</IconBtn>
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,11 +31,14 @@ function Btn({
|
|||||||
onClick: () => void
|
onClick: () => void
|
||||||
children: ReactNode
|
children: ReactNode
|
||||||
}) {
|
}) {
|
||||||
|
// data-tip drives the fast custom tooltip (the native title is too slow to
|
||||||
|
// explain icon-only buttons)
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className={`tm-btn${danger ? ' danger' : ''}`}
|
className={`tm-btn${danger ? ' danger' : ''}`}
|
||||||
title={title}
|
aria-label={title}
|
||||||
|
data-tip={title}
|
||||||
onMouseDown={(e) => e.preventDefault()}
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
>
|
>
|
||||||
@@ -107,7 +110,7 @@ export function TableMenu({ editor, scrollRef }: Props) {
|
|||||||
<Btn title={t('tableRowBelow')} onClick={() => run((c) => c.addRowAfter())}>
|
<Btn title={t('tableRowBelow')} onClick={() => run((c) => c.addRowAfter())}>
|
||||||
<IconRowInsertBelow size={ICON} />
|
<IconRowInsertBelow size={ICON} />
|
||||||
</Btn>
|
</Btn>
|
||||||
<Btn title={t('tableDeleteRow')} onClick={() => run((c) => c.deleteRow())}>
|
<Btn title={t('tableDeleteRow')} danger onClick={() => run((c) => c.deleteRow())}>
|
||||||
<IconRowDelete size={ICON} />
|
<IconRowDelete size={ICON} />
|
||||||
</Btn>
|
</Btn>
|
||||||
<span className="tm-sep" />
|
<span className="tm-sep" />
|
||||||
@@ -117,7 +120,7 @@ export function TableMenu({ editor, scrollRef }: Props) {
|
|||||||
<Btn title={t('tableColRight')} onClick={() => run((c) => c.addColumnAfter())}>
|
<Btn title={t('tableColRight')} onClick={() => run((c) => c.addColumnAfter())}>
|
||||||
<IconColInsertRight size={ICON} />
|
<IconColInsertRight size={ICON} />
|
||||||
</Btn>
|
</Btn>
|
||||||
<Btn title={t('tableDeleteCol')} onClick={() => run((c) => c.deleteColumn())}>
|
<Btn title={t('tableDeleteCol')} danger onClick={() => run((c) => c.deleteColumn())}>
|
||||||
<IconColDelete size={ICON} />
|
<IconColDelete size={ICON} />
|
||||||
</Btn>
|
</Btn>
|
||||||
<span className="tm-sep" />
|
<span className="tm-sep" />
|
||||||
|
|||||||
@@ -15,17 +15,10 @@ export {
|
|||||||
IconTable,
|
IconTable,
|
||||||
IconPicture,
|
IconPicture,
|
||||||
IconLink,
|
IconLink,
|
||||||
IconHighlight,
|
IconSave,
|
||||||
IconUndo,
|
IconUndo,
|
||||||
IconRedo,
|
IconRedo,
|
||||||
IconCopy,
|
IconCopy,
|
||||||
IconRowInsertAbove,
|
|
||||||
IconRowInsertBelow,
|
|
||||||
IconColInsertLeft,
|
|
||||||
IconColInsertRight,
|
|
||||||
IconRowDelete,
|
|
||||||
IconColDelete,
|
|
||||||
IconTableDelete,
|
|
||||||
} from '../../../../docs/src/renderer/components/icons'
|
} from '../../../../docs/src/renderer/components/icons'
|
||||||
|
|
||||||
interface IconProps {
|
interface IconProps {
|
||||||
@@ -77,24 +70,6 @@ export function IconHr(props: IconProps) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function IconCallout(props: IconProps) {
|
|
||||||
return (
|
|
||||||
<Svg {...props}>
|
|
||||||
<path d="M3 2.8v10.4" />
|
|
||||||
<path d="M5.8 5.2h7.2M5.8 8h5" />
|
|
||||||
</Svg>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function IconToggle(props: IconProps) {
|
|
||||||
return (
|
|
||||||
<Svg {...props}>
|
|
||||||
<path d="M3.2 4.2l3.2 2.4-3.2 2.4z" fill="currentColor" stroke="none" />
|
|
||||||
<path d="M8.6 5.4h5M8.6 8h5M4 12h9.6" />
|
|
||||||
</Svg>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function IconProperties(props: IconProps) {
|
export function IconProperties(props: IconProps) {
|
||||||
return (
|
return (
|
||||||
<Svg {...props}>
|
<Svg {...props}>
|
||||||
@@ -103,6 +78,79 @@ export function IconProperties(props: IconProps) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── table-menu glyphs: insert = explicit "+", delete = explicit "×" ──
|
||||||
|
* (redrawn locally — the docs arrow variants read as "move" at 15px) */
|
||||||
|
|
||||||
|
export function IconRowInsertAbove(props: IconProps) {
|
||||||
|
return (
|
||||||
|
<Svg {...props}>
|
||||||
|
<path d="M8 1.7v4M6 3.7h4" />
|
||||||
|
<rect x="2.2" y="7.8" width="11.6" height="6" rx="0.8" />
|
||||||
|
<path d="M2.2 10.8h11.6" strokeWidth="1" />
|
||||||
|
</Svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IconRowInsertBelow(props: IconProps) {
|
||||||
|
return (
|
||||||
|
<Svg {...props}>
|
||||||
|
<rect x="2.2" y="2.2" width="11.6" height="6" rx="0.8" />
|
||||||
|
<path d="M2.2 5.2h11.6" strokeWidth="1" />
|
||||||
|
<path d="M8 10.3v4M6 12.3h4" />
|
||||||
|
</Svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IconColInsertLeft(props: IconProps) {
|
||||||
|
return (
|
||||||
|
<Svg {...props}>
|
||||||
|
<path d="M1.7 8h4M3.7 6v4" />
|
||||||
|
<rect x="7.8" y="2.2" width="6" height="11.6" rx="0.8" />
|
||||||
|
<path d="M10.8 2.2v11.6" strokeWidth="1" />
|
||||||
|
</Svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IconColInsertRight(props: IconProps) {
|
||||||
|
return (
|
||||||
|
<Svg {...props}>
|
||||||
|
<rect x="2.2" y="2.2" width="6" height="11.6" rx="0.8" />
|
||||||
|
<path d="M5.2 2.2v11.6" strokeWidth="1" />
|
||||||
|
<path d="M10.3 8h4M12.3 6v4" />
|
||||||
|
</Svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IconRowDelete(props: IconProps) {
|
||||||
|
return (
|
||||||
|
<Svg {...props}>
|
||||||
|
<path d="M3.4 2.6h9.2M3.4 13.4h9.2" opacity="0.4" strokeWidth="1" />
|
||||||
|
<rect x="2.2" y="5" width="11.6" height="6" rx="0.8" />
|
||||||
|
<path d="M6.8 6.8l2.4 2.4M9.2 6.8l-2.4 2.4" />
|
||||||
|
</Svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IconColDelete(props: IconProps) {
|
||||||
|
return (
|
||||||
|
<Svg {...props}>
|
||||||
|
<path d="M2.6 3.4v9.2M13.4 3.4v9.2" opacity="0.4" strokeWidth="1" />
|
||||||
|
<rect x="5" y="2.2" width="6" height="11.6" rx="0.8" />
|
||||||
|
<path d="M6.8 6.8l2.4 2.4M9.2 6.8l-2.4 2.4" />
|
||||||
|
</Svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IconTableDelete(props: IconProps) {
|
||||||
|
return (
|
||||||
|
<Svg {...props}>
|
||||||
|
<rect x="2" y="2.6" width="9" height="8.4" rx="0.8" />
|
||||||
|
<path d="M2 5.4h9M6.5 2.6v8.4" strokeWidth="1" />
|
||||||
|
<path d="M10.7 10.4l3.2 3.2M13.9 10.4l-3.2 3.2" />
|
||||||
|
</Svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
export function IconHeaderRow(props: IconProps) {
|
export function IconHeaderRow(props: IconProps) {
|
||||||
return (
|
return (
|
||||||
<Svg {...props}>
|
<Svg {...props}>
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
import { NodeViewContent, NodeViewWrapper } from '@tiptap/react'
|
|
||||||
import type { NodeViewProps } from '@tiptap/react'
|
|
||||||
import { t } from '../i18n/locale'
|
|
||||||
|
|
||||||
export function ToggleView({ node, updateAttributes, editor, getPos }: NodeViewProps) {
|
|
||||||
const open: boolean = node.attrs.open !== false
|
|
||||||
|
|
||||||
// fold state is display-only and never serializes — flip it outside the
|
|
||||||
// undo history and tagged uiOnly so it neither dirties the document nor
|
|
||||||
// becomes a Cmd+Z step
|
|
||||||
const flipOpen = () => {
|
|
||||||
const pos = getPos()
|
|
||||||
if (typeof pos !== 'number') return
|
|
||||||
const tr = editor.state.tr
|
|
||||||
.setNodeMarkup(pos, undefined, { ...node.attrs, open: !open })
|
|
||||||
.setMeta('addToHistory', false)
|
|
||||||
.setMeta('uiOnly', true)
|
|
||||||
editor.view.dispatch(tr)
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<NodeViewWrapper className={`md-toggle ${open ? 'is-open' : 'is-closed'}`} data-toggle="">
|
|
||||||
<div className="md-toggle-header" contentEditable={false}>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="md-toggle-caret"
|
|
||||||
aria-expanded={open}
|
|
||||||
onMouseDown={(e) => e.preventDefault()}
|
|
||||||
onClick={flipOpen}
|
|
||||||
>
|
|
||||||
<svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true">
|
|
||||||
<path d="M4 2l4 4-4 4" stroke="currentColor" strokeWidth="1.6" fill="none" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
<input
|
|
||||||
className="md-toggle-summary"
|
|
||||||
value={node.attrs.summary ?? ''}
|
|
||||||
placeholder={t('toggleSummaryPlaceholder')}
|
|
||||||
readOnly={!editor.isEditable}
|
|
||||||
onChange={(e) => updateAttributes({ summary: e.target.value })}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<NodeViewContent className="md-toggle-body" style={open ? undefined : { display: 'none' }} />
|
|
||||||
</NodeViewWrapper>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -52,13 +52,16 @@ function dragHandlePlugin(editor: Editor): Plugin {
|
|||||||
plus.type = 'button'
|
plus.type = 'button'
|
||||||
plus.className = 'md-gutter-btn md-gutter-plus'
|
plus.className = 'md-gutter-btn md-gutter-plus'
|
||||||
plus.innerHTML = PLUS_SVG
|
plus.innerHTML = PLUS_SVG
|
||||||
plus.title = t('blockAddBelow')
|
plus.dataset.tip = t('blockAddBelow')
|
||||||
|
plus.setAttribute('aria-label', t('blockAddBelow'))
|
||||||
|
|
||||||
const grip = document.createElement('button')
|
const grip = document.createElement('button')
|
||||||
grip.type = 'button'
|
grip.type = 'button'
|
||||||
grip.className = 'md-gutter-btn md-gutter-grip'
|
grip.className = 'md-gutter-btn md-gutter-grip'
|
||||||
grip.draggable = true
|
grip.draggable = true
|
||||||
grip.innerHTML = GRIP_SVG
|
grip.innerHTML = GRIP_SVG
|
||||||
|
grip.dataset.tip = t('blockGripHint')
|
||||||
|
grip.setAttribute('aria-label', t('blockGripHint'))
|
||||||
|
|
||||||
handle.append(plus, grip)
|
handle.append(plus, grip)
|
||||||
|
|
||||||
@@ -194,6 +197,9 @@ function dragHandlePlugin(editor: Editor): Plugin {
|
|||||||
)
|
)
|
||||||
return
|
return
|
||||||
hideMenu()
|
hideMenu()
|
||||||
|
// the open menu blocked the grace-period hide — don't leave the gutter
|
||||||
|
// stranded unless the pointer is back over the editor (hover re-syncs it)
|
||||||
|
if (!(event.target instanceof Node) || !view.dom.contains(event.target)) hideHandle()
|
||||||
}
|
}
|
||||||
|
|
||||||
const onScrollOrLeave = () => {
|
const onScrollOrLeave = () => {
|
||||||
@@ -201,9 +207,29 @@ function dragHandlePlugin(editor: Editor): Plugin {
|
|||||||
hideMenu()
|
hideMenu()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The gutter sits 52px left of the block with a page-background gap in
|
||||||
|
// between, so reaching it always raises mouseleave on the editor first.
|
||||||
|
// Hide on a grace period instead of instantly; entering the gutter (or
|
||||||
|
// coming back into the editor) cancels the pending hide.
|
||||||
|
let hideTimer: number | null = null
|
||||||
|
const cancelHide = () => {
|
||||||
|
if (hideTimer !== null) window.clearTimeout(hideTimer)
|
||||||
|
hideTimer = null
|
||||||
|
}
|
||||||
|
const scheduleHide = () => {
|
||||||
|
cancelHide()
|
||||||
|
hideTimer = window.setTimeout(() => {
|
||||||
|
hideTimer = null
|
||||||
|
if (menu.style.display !== 'block') hideHandle()
|
||||||
|
}, 250)
|
||||||
|
}
|
||||||
|
|
||||||
view.dom.addEventListener('mousemove', onMouseMove)
|
view.dom.addEventListener('mousemove', onMouseMove)
|
||||||
view.dom.addEventListener('mouseleave', onScrollOrLeave)
|
view.dom.addEventListener('mouseenter', cancelHide)
|
||||||
|
view.dom.addEventListener('mouseleave', scheduleHide)
|
||||||
handle.addEventListener('mousemove', (e) => e.stopPropagation())
|
handle.addEventListener('mousemove', (e) => e.stopPropagation())
|
||||||
|
handle.addEventListener('mouseenter', cancelHide)
|
||||||
|
handle.addEventListener('mouseleave', scheduleHide)
|
||||||
grip.addEventListener('dragstart', onDragStart)
|
grip.addEventListener('dragstart', onDragStart)
|
||||||
grip.addEventListener('click', onGripClick)
|
grip.addEventListener('click', onGripClick)
|
||||||
plus.addEventListener('click', onPlusClick)
|
plus.addEventListener('click', onPlusClick)
|
||||||
@@ -216,8 +242,10 @@ function dragHandlePlugin(editor: Editor): Plugin {
|
|||||||
if (!prevState.doc.eq(view.state.doc)) hideMenu()
|
if (!prevState.doc.eq(view.state.doc)) hideMenu()
|
||||||
},
|
},
|
||||||
destroy() {
|
destroy() {
|
||||||
|
cancelHide()
|
||||||
view.dom.removeEventListener('mousemove', onMouseMove)
|
view.dom.removeEventListener('mousemove', onMouseMove)
|
||||||
view.dom.removeEventListener('mouseleave', onScrollOrLeave)
|
view.dom.removeEventListener('mouseenter', cancelHide)
|
||||||
|
view.dom.removeEventListener('mouseleave', scheduleHide)
|
||||||
document.removeEventListener('mousedown', onDocMouseDown, true)
|
document.removeEventListener('mousedown', onDocMouseDown, true)
|
||||||
document.removeEventListener('scroll', onScrollOrLeave, true)
|
document.removeEventListener('scroll', onScrollOrLeave, true)
|
||||||
handle.remove()
|
handle.remove()
|
||||||
|
|||||||
@@ -1,71 +0,0 @@
|
|||||||
import { Node, createBlockMarkdownSpec, mergeAttributes } from '@tiptap/core'
|
|
||||||
|
|
||||||
export const CALLOUT_TYPES = ['info', 'tip', 'warning', 'danger'] as const
|
|
||||||
export type CalloutType = (typeof CALLOUT_TYPES)[number]
|
|
||||||
|
|
||||||
declare module '@tiptap/core' {
|
|
||||||
interface Commands<ReturnType> {
|
|
||||||
callout: {
|
|
||||||
/** wrap the selection in a callout (no-op when already inside one) */
|
|
||||||
setCallout: (attrs?: { type?: CalloutType }) => ReturnType
|
|
||||||
/** unwrap the callout around the selection */
|
|
||||||
unsetCallout: () => ReturnType
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Admonition block serialized as a Pandoc-style fenced div:
|
|
||||||
*
|
|
||||||
* :::callout {type="warning"}
|
|
||||||
* body…
|
|
||||||
* :::
|
|
||||||
*/
|
|
||||||
export const Callout = Node.create({
|
|
||||||
name: 'callout',
|
|
||||||
group: 'block',
|
|
||||||
content: 'block+',
|
|
||||||
defining: true,
|
|
||||||
|
|
||||||
addAttributes() {
|
|
||||||
return {
|
|
||||||
type: {
|
|
||||||
default: 'info',
|
|
||||||
parseHTML: (el) => el.getAttribute('data-type') || 'info',
|
|
||||||
renderHTML: (attrs) => ({ 'data-type': attrs.type }),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
parseHTML() {
|
|
||||||
return [{ tag: 'div[data-callout]' }]
|
|
||||||
},
|
|
||||||
|
|
||||||
renderHTML({ HTMLAttributes }) {
|
|
||||||
return ['div', mergeAttributes(HTMLAttributes, { 'data-callout': '', class: 'md-callout' }), 0]
|
|
||||||
},
|
|
||||||
|
|
||||||
addCommands() {
|
|
||||||
return {
|
|
||||||
setCallout:
|
|
||||||
(attrs) =>
|
|
||||||
({ commands, editor }) => {
|
|
||||||
if (editor.isActive(this.name)) return true
|
|
||||||
return commands.wrapIn(this.name, { type: attrs?.type ?? 'info' })
|
|
||||||
},
|
|
||||||
unsetCallout:
|
|
||||||
() =>
|
|
||||||
({ commands }) =>
|
|
||||||
commands.lift(this.name),
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
...createBlockMarkdownSpec({
|
|
||||||
nodeName: 'callout',
|
|
||||||
defaultAttributes: { type: 'info' },
|
|
||||||
allowedAttributes: ['type'],
|
|
||||||
serializeAttributes: (attrs) =>
|
|
||||||
attrs.type && attrs.type !== 'info' ? `type="${attrs.type}"` : '',
|
|
||||||
content: 'block',
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
@@ -3,13 +3,10 @@ import StarterKit from '@tiptap/starter-kit'
|
|||||||
import { Markdown } from '@tiptap/markdown'
|
import { Markdown } from '@tiptap/markdown'
|
||||||
import { TableKit } from '@tiptap/extension-table'
|
import { TableKit } from '@tiptap/extension-table'
|
||||||
import { TaskItem, TaskList } from '@tiptap/extension-list'
|
import { TaskItem, TaskList } from '@tiptap/extension-list'
|
||||||
import { Highlight } from '@tiptap/extension-highlight'
|
|
||||||
import { CodeBlock } from '@tiptap/extension-code-block'
|
import { CodeBlock } from '@tiptap/extension-code-block'
|
||||||
import { ReactNodeViewRenderer } from '@tiptap/react'
|
import { ReactNodeViewRenderer } from '@tiptap/react'
|
||||||
import { Placeholder } from '@tiptap/extensions'
|
import { Placeholder } from '@tiptap/extensions'
|
||||||
import { CodeBlockView } from './CodeBlockView'
|
import { CodeBlockView } from './CodeBlockView'
|
||||||
import { Callout } from './callout'
|
|
||||||
import { Toggle } from './toggle'
|
|
||||||
import { LocalImage } from './localImage'
|
import { LocalImage } from './localImage'
|
||||||
import { BlockDragHandle } from './blockDragHandle'
|
import { BlockDragHandle } from './blockDragHandle'
|
||||||
import { BlockKeymap } from './blockKeymap'
|
import { BlockKeymap } from './blockKeymap'
|
||||||
@@ -25,27 +22,29 @@ export interface BuildExtensionsOptions {
|
|||||||
|
|
||||||
export function buildExtensions(options: BuildExtensionsOptions): AnyExtension[] {
|
export function buildExtensions(options: BuildExtensionsOptions): AnyExtension[] {
|
||||||
return [
|
return [
|
||||||
// StarterKit v3 bundles bold/italic/strike/code/UNDERLINE/link/lists/history —
|
|
||||||
// toggleUnderline etc. need no extra extension package
|
|
||||||
StarterKit.configure({
|
StarterKit.configure({
|
||||||
// LocalImage replaces the plain image; links open externally via main-process guard
|
// LocalImage replaces the plain image; links open externally via main-process guard
|
||||||
link: { openOnClick: false },
|
link: { openOnClick: false },
|
||||||
// replaced by the NodeView-enhanced variant below (language picker + copy)
|
// replaced by the NodeView-enhanced variant below (language picker + copy)
|
||||||
codeBlock: false,
|
codeBlock: false,
|
||||||
|
// underline would serialize as `++text++` — not part of GFM
|
||||||
|
underline: false,
|
||||||
}),
|
}),
|
||||||
CodeBlock.extend({
|
CodeBlock.extend({
|
||||||
addNodeView() {
|
addNodeView() {
|
||||||
return ReactNodeViewRenderer(CodeBlockView)
|
return ReactNodeViewRenderer(CodeBlockView)
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
Highlight,
|
// 4-space nesting: the default 2 spaces is below the content column of
|
||||||
Markdown,
|
// ordered items ("1. " = 3), so strict CommonMark parsers (GitHub) would
|
||||||
TableKit.configure({ table: { resizable: false } }),
|
// flatten sub-lists in the saved file. 4 is safe for every marker width.
|
||||||
|
Markdown.configure({ indentation: { style: 'space', size: 4 } }),
|
||||||
|
// column widths are not expressible in GFM tables — no resizable columns;
|
||||||
|
// the wrapper div gives wide tables a horizontal scrollbar
|
||||||
|
TableKit.configure({ table: { resizable: false, renderWrapper: true } }),
|
||||||
TaskList,
|
TaskList,
|
||||||
TaskItem.configure({ nested: true }),
|
TaskItem.configure({ nested: true }),
|
||||||
LocalImage,
|
LocalImage,
|
||||||
Callout,
|
|
||||||
Toggle,
|
|
||||||
BlockDragHandle,
|
BlockDragHandle,
|
||||||
BlockKeymap,
|
BlockKeymap,
|
||||||
AiHighlight,
|
AiHighlight,
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { Image } from '@tiptap/extension-image'
|
import { Image } from '@tiptap/extension-image'
|
||||||
import { mergeAttributes } from '@tiptap/core'
|
|
||||||
import { Plugin, PluginKey } from '@tiptap/pm/state'
|
import { Plugin, PluginKey } from '@tiptap/pm/state'
|
||||||
|
|
||||||
/** Directory of the open .md file; relative image paths resolve against it for display */
|
/** Directory of the open .md file; relative image paths resolve against it for display */
|
||||||
@@ -29,6 +28,23 @@ export function resolveImageSrc(src: string, baseDir: string | null = imageBaseD
|
|||||||
return toAssetUrl(`${baseDir.replace(/\\/g, '/').replace(/\/$/, '')}/${src}`)
|
return toAssetUrl(`${baseDir.replace(/\\/g, '/').replace(/\/$/, '')}/${src}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse of {@link resolveImageSrc}: map a display URL (md-asset://) back to
|
||||||
|
* the authored path so DOM-parsed content (copy/paste inside the editor) never
|
||||||
|
* bakes display URLs into the stored document / serialized markdown.
|
||||||
|
*/
|
||||||
|
export function unresolveImageSrc(src: string, baseDir: string | null = imageBaseDir): string {
|
||||||
|
if (!src.startsWith('md-asset://')) return src
|
||||||
|
let path = decodeURIComponent(src.slice('md-asset://'.length))
|
||||||
|
// Windows drive paths were prefixed with '/' to form a valid URL path
|
||||||
|
if (/^\/[a-zA-Z]:\//.test(path)) path = path.slice(1)
|
||||||
|
if (baseDir) {
|
||||||
|
const base = `${baseDir.replace(/\\/g, '/').replace(/\/$/, '')}/`
|
||||||
|
if (path.startsWith(base)) return path.slice(base.length)
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
const EXT_BY_MIME: Record<string, string> = {
|
const EXT_BY_MIME: Record<string, string> = {
|
||||||
'image/png': 'png',
|
'image/png': 'png',
|
||||||
'image/jpeg': 'jpg',
|
'image/jpeg': 'jpg',
|
||||||
@@ -72,13 +88,24 @@ async function persistAndInsert(
|
|||||||
* Pasted / dropped image files are persisted into `assets/` beside the file.
|
* Pasted / dropped image files are persisted into `assets/` beside the file.
|
||||||
*/
|
*/
|
||||||
export const LocalImage = Image.extend({
|
export const LocalImage = Image.extend({
|
||||||
renderHTML({ node, HTMLAttributes }) {
|
addAttributes() {
|
||||||
return [
|
return {
|
||||||
'img',
|
...this.parent?.(),
|
||||||
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
|
// resolved at the attribute level so the renderer displays the
|
||||||
src: resolveImageSrc(String(node.attrs.src ?? '')),
|
// md-asset:// URL while the stored value keeps the authored path
|
||||||
}),
|
src: {
|
||||||
]
|
default: null,
|
||||||
|
parseHTML: (element) => unresolveImageSrc(element.getAttribute('src') ?? ''),
|
||||||
|
renderHTML: (attrs) => ({ src: resolveImageSrc(String(attrs.src ?? '')) }),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
renderMarkdown: (node) => {
|
||||||
|
const src = String(node.attrs?.src ?? '')
|
||||||
|
const alt = String(node.attrs?.alt ?? '')
|
||||||
|
const title = String(node.attrs?.title ?? '')
|
||||||
|
return title ? `` : ``
|
||||||
},
|
},
|
||||||
|
|
||||||
addProseMirrorPlugins() {
|
addProseMirrorPlugins() {
|
||||||
|
|||||||
@@ -32,8 +32,8 @@ function chain(editor: Editor, range: Range) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Block-type conversions (heading/callout/toggle/…) are illegal inside a list
|
* Block-type conversions (heading/code block/…) are illegal inside a list
|
||||||
* item — wrapIn/setHeading would silently fail after the range was already
|
* item — setHeading would silently fail after the range was already
|
||||||
* deleted. Lift the current item out of its list(s) first (Notion behavior).
|
* deleted. Lift the current item out of its list(s) first (Notion behavior).
|
||||||
*/
|
*/
|
||||||
export function liftFromList(editor: Editor): void {
|
export function liftFromList(editor: Editor): void {
|
||||||
@@ -110,18 +110,6 @@ export function buildSlashItems(extra?: { insertImage?: () => void }): SlashItem
|
|||||||
keywords: ['codeblock', '```'],
|
keywords: ['codeblock', '```'],
|
||||||
run: (e, r) => void blockChain(e, r).toggleCodeBlock().run(),
|
run: (e, r) => void blockChain(e, r).toggleCodeBlock().run(),
|
||||||
},
|
},
|
||||||
{
|
|
||||||
id: 'callout',
|
|
||||||
labelKey: 'insertCallout',
|
|
||||||
keywords: ['admonition', 'note', 'info'],
|
|
||||||
run: (e, r) => void blockChain(e, r).setCallout().run(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'toggle',
|
|
||||||
labelKey: 'insertToggle',
|
|
||||||
keywords: ['details', 'collapse', 'fold'],
|
|
||||||
run: (e, r) => void blockChain(e, r).setToggle().run(),
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
id: 'table',
|
id: 'table',
|
||||||
labelKey: 'insertTable',
|
labelKey: 'insertTable',
|
||||||
|
|||||||
@@ -1,81 +0,0 @@
|
|||||||
import { Node, createBlockMarkdownSpec, mergeAttributes } from '@tiptap/core'
|
|
||||||
import { ReactNodeViewRenderer } from '@tiptap/react'
|
|
||||||
import { ToggleView } from './ToggleView'
|
|
||||||
|
|
||||||
declare module '@tiptap/core' {
|
|
||||||
interface Commands<ReturnType> {
|
|
||||||
toggleBlock: {
|
|
||||||
/** wrap the selection in a collapsible toggle block */
|
|
||||||
setToggle: (attrs?: { summary?: string }) => ReturnType
|
|
||||||
/** unwrap the toggle block around the selection */
|
|
||||||
unsetToggle: () => ReturnType
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Collapsible block serialized as a fenced div:
|
|
||||||
*
|
|
||||||
* :::toggle {summary="Section title"}
|
|
||||||
* hidden body…
|
|
||||||
* :::
|
|
||||||
*
|
|
||||||
* `open` is editor-only display state and never reaches the markdown.
|
|
||||||
*/
|
|
||||||
export const Toggle = Node.create({
|
|
||||||
name: 'toggle',
|
|
||||||
group: 'block',
|
|
||||||
content: 'block+',
|
|
||||||
defining: true,
|
|
||||||
|
|
||||||
addAttributes() {
|
|
||||||
return {
|
|
||||||
summary: {
|
|
||||||
default: '',
|
|
||||||
parseHTML: (el) => el.getAttribute('data-summary') ?? '',
|
|
||||||
renderHTML: (attrs) => ({ 'data-summary': attrs.summary }),
|
|
||||||
},
|
|
||||||
open: {
|
|
||||||
default: true,
|
|
||||||
parseHTML: (el) => el.getAttribute('data-open') !== 'false',
|
|
||||||
renderHTML: (attrs) => ({ 'data-open': attrs.open ? 'true' : 'false' }),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
parseHTML() {
|
|
||||||
return [{ tag: 'div[data-toggle]' }]
|
|
||||||
},
|
|
||||||
|
|
||||||
renderHTML({ HTMLAttributes }) {
|
|
||||||
return ['div', mergeAttributes(HTMLAttributes, { 'data-toggle': '', class: 'md-toggle' }), 0]
|
|
||||||
},
|
|
||||||
|
|
||||||
addNodeView() {
|
|
||||||
return ReactNodeViewRenderer(ToggleView)
|
|
||||||
},
|
|
||||||
|
|
||||||
addCommands() {
|
|
||||||
return {
|
|
||||||
setToggle:
|
|
||||||
(attrs) =>
|
|
||||||
({ commands, editor }) => {
|
|
||||||
if (editor.isActive(this.name)) return true
|
|
||||||
return commands.wrapIn(this.name, { summary: attrs?.summary ?? '', open: true })
|
|
||||||
},
|
|
||||||
unsetToggle:
|
|
||||||
() =>
|
|
||||||
({ commands }) =>
|
|
||||||
commands.lift(this.name),
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
...createBlockMarkdownSpec({
|
|
||||||
nodeName: 'toggle',
|
|
||||||
defaultAttributes: { summary: '', open: true },
|
|
||||||
allowedAttributes: ['summary'],
|
|
||||||
serializeAttributes: (attrs) =>
|
|
||||||
attrs.summary ? `summary="${String(attrs.summary).replace(/"/g, '\\"')}"` : '',
|
|
||||||
content: 'block',
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
@@ -22,6 +22,9 @@ import type {
|
|||||||
/** Resolve an authored image src to embeddable bytes; null → fall back to alt text */
|
/** Resolve an authored image src to embeddable bytes; null → fall back to alt text */
|
||||||
export type ImageLoader = (src: string) => Promise<NewImage | null>
|
export type ImageLoader = (src: string) => Promise<NewImage | null>
|
||||||
|
|
||||||
|
/** widest image that fits the A4 text column */
|
||||||
|
export const DOCX_MAX_IMAGE_PX = 620
|
||||||
|
|
||||||
export interface DocxMapping {
|
export interface DocxMapping {
|
||||||
blocks: SaveBlock[]
|
blocks: SaveBlock[]
|
||||||
options: SaveOptions
|
options: SaveOptions
|
||||||
@@ -33,12 +36,6 @@ const INDENT_STEP = 360
|
|||||||
const DECIMAL_ABSTRACT_NUM_ID = '1'
|
const DECIMAL_ABSTRACT_NUM_ID = '1'
|
||||||
const CODE_FONT = 'Consolas'
|
const CODE_FONT = 'Consolas'
|
||||||
const CODE_FILL = 'F2F3F5'
|
const CODE_FILL = 'F2F3F5'
|
||||||
const CALLOUT_FILL: Record<string, string> = {
|
|
||||||
info: 'E8F0FE',
|
|
||||||
tip: 'E6F4EA',
|
|
||||||
warning: 'FEF3E2',
|
|
||||||
danger: 'FCE8E6',
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── inline content → Run[] ──
|
// ── inline content → Run[] ──
|
||||||
|
|
||||||
@@ -55,8 +52,6 @@ function runsFromInline(content: JSONContent[] | undefined): Run[] {
|
|||||||
if (mark.type === 'bold') run.bold = true
|
if (mark.type === 'bold') run.bold = true
|
||||||
else if (mark.type === 'italic') run.italic = true
|
else if (mark.type === 'italic') run.italic = true
|
||||||
else if (mark.type === 'strike') run.strike = true
|
else if (mark.type === 'strike') run.strike = true
|
||||||
else if (mark.type === 'underline') run.underline = true
|
|
||||||
else if (mark.type === 'highlight') run.highlight = 'yellow'
|
|
||||||
else if (mark.type === 'code') run.font = CODE_FONT
|
else if (mark.type === 'code') run.font = CODE_FONT
|
||||||
else if (mark.type === 'link' && typeof mark.attrs?.href === 'string') {
|
else if (mark.type === 'link' && typeof mark.attrs?.href === 'string') {
|
||||||
run.link = { href: mark.attrs.href }
|
run.link = { href: mark.attrs.href }
|
||||||
@@ -176,7 +171,11 @@ function mapTable(node: JSONContent): TableModel {
|
|||||||
function walkBlock(ctx: WalkContext, node: JSONContent, base?: ParaFormat): void {
|
function walkBlock(ctx: WalkContext, node: JSONContent, base?: ParaFormat): void {
|
||||||
switch (node.type) {
|
switch (node.type) {
|
||||||
case 'paragraph':
|
case 'paragraph':
|
||||||
pushParagraph(ctx, { type: 'paragraph', runs: runsFromInline(node.content), format: base })
|
pushParagraph(ctx, {
|
||||||
|
type: 'paragraph',
|
||||||
|
runs: runsFromInline(node.content),
|
||||||
|
format: base,
|
||||||
|
})
|
||||||
break
|
break
|
||||||
case 'heading': {
|
case 'heading': {
|
||||||
const level = Math.min(Math.max(Number(node.attrs?.level) || 1, 1), 6) as number
|
const level = Math.min(Math.max(Number(node.attrs?.level) || 1, 1), 6) as number
|
||||||
@@ -227,27 +226,6 @@ function walkBlock(ctx: WalkContext, node: JSONContent, base?: ParaFormat): void
|
|||||||
case 'table':
|
case 'table':
|
||||||
ctx.blocks.push({ kind: 'xml', xml: generateTableModelXml(mapTable(node)) })
|
ctx.blocks.push({ kind: 'xml', xml: generateTableModelXml(mapTable(node)) })
|
||||||
break
|
break
|
||||||
case 'callout': {
|
|
||||||
const fill = CALLOUT_FILL[String(node.attrs?.type ?? 'info')] ?? CALLOUT_FILL.info
|
|
||||||
for (const child of node.content ?? []) {
|
|
||||||
walkBlock(ctx, child, mergeFormat(base, { indentLeft: 120, shadingFill: fill }))
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
case 'toggle': {
|
|
||||||
const summary = String(node.attrs?.summary ?? '')
|
|
||||||
if (summary) {
|
|
||||||
pushParagraph(ctx, {
|
|
||||||
type: 'paragraph',
|
|
||||||
runs: [{ text: summary, bold: true }],
|
|
||||||
format: base,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
for (const child of node.content ?? []) {
|
|
||||||
walkBlock(ctx, child, mergeFormat(base, { indentLeft: INDENT_STEP }))
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
default: {
|
default: {
|
||||||
// unknown block: keep its text so nothing silently disappears
|
// unknown block: keep its text so nothing silently disappears
|
||||||
const text = plainText(node)
|
const text = plainText(node)
|
||||||
|
|||||||
@@ -24,26 +24,21 @@ pre code { background: none; padding: 0; font-size: 0.85em; line-height: 1.6; }
|
|||||||
hr { border: none; border-top: 2px solid #e4e7eb; margin: 1.6em 0; }
|
hr { border: none; border-top: 2px solid #e4e7eb; margin: 1.6em 0; }
|
||||||
a { color: #0a69da; }
|
a { color: #0a69da; }
|
||||||
img { max-width: 100%; height: auto; }
|
img { max-width: 100%; height: auto; }
|
||||||
table { border-collapse: collapse; margin: 0.8em 0; break-inside: avoid; }
|
.tableWrapper { margin: 0.8em 0; }
|
||||||
th, td { border: 1px solid #d0d5db; padding: 5px 10px; }
|
table { border-collapse: collapse; width: 100%; margin: 0; break-inside: avoid; }
|
||||||
|
th, td { border: 1px solid #d0d5db; padding: 6px 10px; vertical-align: top; text-align: start; }
|
||||||
|
th > p, td > p { margin: 0; }
|
||||||
th { background: #f6f8fa; font-weight: 600; }
|
th { background: #f6f8fa; font-weight: 600; }
|
||||||
ul[data-type='taskList'] { list-style: none; padding-left: 0.4em; }
|
ul[data-type='taskList'] { list-style: none; padding-left: 0.4em; }
|
||||||
ul[data-type='taskList'] li { display: flex; gap: 8px; }
|
ul[data-type='taskList'] li { display: flex; gap: 8px; }
|
||||||
ul[data-type='taskList'] li > label { flex: 0 0 auto; margin-top: 0.3em; }
|
ul[data-type='taskList'] li > label { flex: 0 0 auto; margin-top: 0.3em; }
|
||||||
ul[data-type='taskList'] li[data-checked='true'] > div { color: #8b929b; text-decoration: line-through; }
|
ul[data-type='taskList'] li[data-checked='true'] > div { color: #8b929b; text-decoration: line-through; }
|
||||||
.md-callout { margin: 0.8em 0; padding: 10px 14px; border-radius: 8px; border-left: 4px solid #3b82f6; background: rgba(59,130,246,0.08); break-inside: avoid; }
|
|
||||||
.md-callout[data-type='tip'] { border-left-color: #10b981; background: rgba(16,185,129,0.08); }
|
|
||||||
.md-callout[data-type='warning'] { border-left-color: #f59e0b; background: rgba(245,158,11,0.1); }
|
|
||||||
.md-callout[data-type='danger'] { border-left-color: #ef4444; background: rgba(239,68,68,0.08); }
|
|
||||||
.md-toggle { margin: 0.6em 0; }
|
|
||||||
.print-toggle-summary { font-weight: 600; margin: 0.4em 0 0.2em; }
|
|
||||||
.md-toggle-body { margin-left: 1.2em; }
|
|
||||||
`
|
`
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build a self-contained print HTML document from the live editor DOM.
|
* Build a self-contained print HTML document from the live editor DOM.
|
||||||
* Toggles are expanded and their summary inputs flattened to text; editor-only
|
* Editor-only chrome (contenteditable, code block bars) never makes it into
|
||||||
* chrome (contenteditable, drag handles) never makes it into the clone.
|
* the clone.
|
||||||
*/
|
*/
|
||||||
export function buildPrintHtml(editorRoot: HTMLElement, title: string): string {
|
export function buildPrintHtml(editorRoot: HTMLElement, title: string): string {
|
||||||
const clone = editorRoot.cloneNode(true) as HTMLElement
|
const clone = editorRoot.cloneNode(true) as HTMLElement
|
||||||
@@ -54,23 +49,6 @@ export function buildPrintHtml(editorRoot: HTMLElement, title: string): string {
|
|||||||
// editor-only code block chrome (language picker + copy button) must not print
|
// editor-only code block chrome (language picker + copy button) must not print
|
||||||
for (const bar of clone.querySelectorAll('.md-codeblock-bar')) bar.remove()
|
for (const bar of clone.querySelectorAll('.md-codeblock-bar')) bar.remove()
|
||||||
|
|
||||||
// cloneNode does not carry input value properties — walk original and clone
|
|
||||||
// toggles in parallel (same document order) to recover the live summaries
|
|
||||||
const liveToggles = editorRoot.querySelectorAll('.md-toggle')
|
|
||||||
const cloneToggles = clone.querySelectorAll('.md-toggle')
|
|
||||||
cloneToggles.forEach((toggle, i) => {
|
|
||||||
const header = toggle.querySelector('.md-toggle-header')
|
|
||||||
if (header) {
|
|
||||||
const summary = document.createElement('div')
|
|
||||||
summary.className = 'print-toggle-summary'
|
|
||||||
summary.textContent =
|
|
||||||
liveToggles[i]?.querySelector<HTMLInputElement>('.md-toggle-summary')?.value ?? ''
|
|
||||||
header.replaceWith(summary)
|
|
||||||
}
|
|
||||||
const body = toggle.querySelector<HTMLElement>('.md-toggle-body')
|
|
||||||
if (body) body.style.display = ''
|
|
||||||
})
|
|
||||||
|
|
||||||
const escapedTitle = title.replace(/&/g, '&').replace(/</g, '<')
|
const escapedTitle = title.replace(/&/g, '&').replace(/</g, '<')
|
||||||
return [
|
return [
|
||||||
'<!doctype html>',
|
'<!doctype html>',
|
||||||
|
|||||||
@@ -18,6 +18,9 @@ export const strings = {
|
|||||||
styleCodeBlock: '代码块',
|
styleCodeBlock: '代码块',
|
||||||
undo: '撤销',
|
undo: '撤销',
|
||||||
redo: '重做',
|
redo: '重做',
|
||||||
|
save: '保存 (⌘S)',
|
||||||
|
autoSave: '自动保存',
|
||||||
|
autoSaveTip: '自动保存(每 30 秒及窗口失焦时)',
|
||||||
bold: '加粗',
|
bold: '加粗',
|
||||||
italic: '斜体',
|
italic: '斜体',
|
||||||
strike: '删除线',
|
strike: '删除线',
|
||||||
@@ -33,13 +36,8 @@ export const strings = {
|
|||||||
insertTable: '插入表格',
|
insertTable: '插入表格',
|
||||||
insertImage: '插入图片',
|
insertImage: '插入图片',
|
||||||
insertHr: '分隔线',
|
insertHr: '分隔线',
|
||||||
insertCallout: '标注块',
|
|
||||||
insertToggle: '折叠块',
|
|
||||||
slashNoResults: '无匹配项',
|
slashNoResults: '无匹配项',
|
||||||
toggleSummaryPlaceholder: '折叠标题…',
|
|
||||||
fmProperties: '属性',
|
fmProperties: '属性',
|
||||||
underline: '下划线',
|
|
||||||
highlight: '高亮',
|
|
||||||
codeCopy: '复制',
|
codeCopy: '复制',
|
||||||
codeCopied: '已复制',
|
codeCopied: '已复制',
|
||||||
tableRowAbove: '上方插入行',
|
tableRowAbove: '上方插入行',
|
||||||
@@ -50,11 +48,15 @@ export const strings = {
|
|||||||
tableDeleteCol: '删除列',
|
tableDeleteCol: '删除列',
|
||||||
tableToggleHeaderRow: '切换表头行',
|
tableToggleHeaderRow: '切换表头行',
|
||||||
tableDeleteTable: '删除表格',
|
tableDeleteTable: '删除表格',
|
||||||
|
imageAlignLeft: '左对齐',
|
||||||
|
imageAlignCenter: '居中',
|
||||||
|
imageAlignRight: '右对齐',
|
||||||
blockAddBelow: '在下方添加',
|
blockAddBelow: '在下方添加',
|
||||||
blockDuplicate: '复制块',
|
blockDuplicate: '复制块',
|
||||||
blockMoveUp: '上移',
|
blockMoveUp: '上移',
|
||||||
blockMoveDown: '下移',
|
blockMoveDown: '下移',
|
||||||
blockDelete: '删除',
|
blockDelete: '删除',
|
||||||
|
blockGripHint: '拖拽移动,点击打开菜单',
|
||||||
aiUnknownError: 'AI 请求失败,请重试',
|
aiUnknownError: 'AI 请求失败,请重试',
|
||||||
aiTimeoutError: 'AI 响应超时',
|
aiTimeoutError: 'AI 响应超时',
|
||||||
aiCreditsExhausted: '积分不足,请前往 genspark.ai 充值',
|
aiCreditsExhausted: '积分不足,请前往 genspark.ai 充值',
|
||||||
@@ -121,6 +123,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'Code block',
|
styleCodeBlock: 'Code block',
|
||||||
undo: 'Undo',
|
undo: 'Undo',
|
||||||
redo: 'Redo',
|
redo: 'Redo',
|
||||||
|
save: 'Save (⌘S)',
|
||||||
|
autoSave: 'AutoSave',
|
||||||
|
autoSaveTip: 'AutoSave (every 30 seconds and when the window loses focus)',
|
||||||
bold: 'Bold',
|
bold: 'Bold',
|
||||||
italic: 'Italic',
|
italic: 'Italic',
|
||||||
strike: 'Strikethrough',
|
strike: 'Strikethrough',
|
||||||
@@ -136,13 +141,8 @@ export const strings = {
|
|||||||
insertTable: 'Insert table',
|
insertTable: 'Insert table',
|
||||||
insertImage: 'Insert image',
|
insertImage: 'Insert image',
|
||||||
insertHr: 'Divider',
|
insertHr: 'Divider',
|
||||||
insertCallout: 'Callout',
|
|
||||||
insertToggle: 'Toggle',
|
|
||||||
slashNoResults: 'No results',
|
slashNoResults: 'No results',
|
||||||
toggleSummaryPlaceholder: 'Toggle title…',
|
|
||||||
fmProperties: 'Properties',
|
fmProperties: 'Properties',
|
||||||
underline: 'Underline',
|
|
||||||
highlight: 'Highlight',
|
|
||||||
codeCopy: 'Copy',
|
codeCopy: 'Copy',
|
||||||
codeCopied: 'Copied',
|
codeCopied: 'Copied',
|
||||||
tableRowAbove: 'Insert row above',
|
tableRowAbove: 'Insert row above',
|
||||||
@@ -153,11 +153,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'Delete column',
|
tableDeleteCol: 'Delete column',
|
||||||
tableToggleHeaderRow: 'Toggle header row',
|
tableToggleHeaderRow: 'Toggle header row',
|
||||||
tableDeleteTable: 'Delete table',
|
tableDeleteTable: 'Delete table',
|
||||||
|
imageAlignLeft: 'Align left',
|
||||||
|
imageAlignCenter: 'Center',
|
||||||
|
imageAlignRight: 'Align right',
|
||||||
blockAddBelow: 'Add block below',
|
blockAddBelow: 'Add block below',
|
||||||
blockDuplicate: 'Duplicate',
|
blockDuplicate: 'Duplicate',
|
||||||
blockMoveUp: 'Move up',
|
blockMoveUp: 'Move up',
|
||||||
blockMoveDown: 'Move down',
|
blockMoveDown: 'Move down',
|
||||||
blockDelete: 'Delete',
|
blockDelete: 'Delete',
|
||||||
|
blockGripHint: 'Drag to move, click for menu',
|
||||||
aiUnknownError: 'AI request failed, please retry',
|
aiUnknownError: 'AI request failed, please retry',
|
||||||
aiTimeoutError: 'AI response timed out',
|
aiTimeoutError: 'AI response timed out',
|
||||||
aiCreditsExhausted: 'Out of credits — top up at genspark.ai',
|
aiCreditsExhausted: 'Out of credits — top up at genspark.ai',
|
||||||
@@ -225,6 +229,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'コードブロック',
|
styleCodeBlock: 'コードブロック',
|
||||||
undo: '元に戻す',
|
undo: '元に戻す',
|
||||||
redo: 'やり直す',
|
redo: 'やり直す',
|
||||||
|
save: '上書き保存 (⌘S)',
|
||||||
|
autoSave: '自動保存',
|
||||||
|
autoSaveTip: '自動保存(30 秒ごと、およびウィンドウのフォーカスが外れたとき)',
|
||||||
bold: '太字',
|
bold: '太字',
|
||||||
italic: '斜体',
|
italic: '斜体',
|
||||||
strike: '取り消し線',
|
strike: '取り消し線',
|
||||||
@@ -240,13 +247,8 @@ export const strings = {
|
|||||||
insertTable: '表を挿入',
|
insertTable: '表を挿入',
|
||||||
insertImage: '画像を挿入',
|
insertImage: '画像を挿入',
|
||||||
insertHr: '区切り線',
|
insertHr: '区切り線',
|
||||||
insertCallout: 'コールアウト',
|
|
||||||
insertToggle: 'トグル',
|
|
||||||
slashNoResults: '該当なし',
|
slashNoResults: '該当なし',
|
||||||
toggleSummaryPlaceholder: 'トグルのタイトル…',
|
|
||||||
fmProperties: 'プロパティ',
|
fmProperties: 'プロパティ',
|
||||||
underline: '下線',
|
|
||||||
highlight: 'ハイライト',
|
|
||||||
codeCopy: 'コピー',
|
codeCopy: 'コピー',
|
||||||
codeCopied: 'コピーしました',
|
codeCopied: 'コピーしました',
|
||||||
tableRowAbove: '上に行を挿入',
|
tableRowAbove: '上に行を挿入',
|
||||||
@@ -257,11 +259,15 @@ export const strings = {
|
|||||||
tableDeleteCol: '列を削除',
|
tableDeleteCol: '列を削除',
|
||||||
tableToggleHeaderRow: 'ヘッダー行を切り替え',
|
tableToggleHeaderRow: 'ヘッダー行を切り替え',
|
||||||
tableDeleteTable: '表を削除',
|
tableDeleteTable: '表を削除',
|
||||||
|
imageAlignLeft: '左揃え',
|
||||||
|
imageAlignCenter: '中央揃え',
|
||||||
|
imageAlignRight: '右揃え',
|
||||||
blockAddBelow: '下にブロックを追加',
|
blockAddBelow: '下にブロックを追加',
|
||||||
blockDuplicate: 'ブロックを複製',
|
blockDuplicate: 'ブロックを複製',
|
||||||
blockMoveUp: '上へ移動',
|
blockMoveUp: '上へ移動',
|
||||||
blockMoveDown: '下へ移動',
|
blockMoveDown: '下へ移動',
|
||||||
blockDelete: '削除',
|
blockDelete: '削除',
|
||||||
|
blockGripHint: 'ドラッグで移動、クリックでメニュー',
|
||||||
aiUnknownError: 'AI リクエストに失敗しました。再試行してください',
|
aiUnknownError: 'AI リクエストに失敗しました。再試行してください',
|
||||||
aiTimeoutError: 'AI の応答がタイムアウトしました',
|
aiTimeoutError: 'AI の応答がタイムアウトしました',
|
||||||
aiCreditsExhausted: 'クレジット不足です。genspark.ai でチャージしてください',
|
aiCreditsExhausted: 'クレジット不足です。genspark.ai でチャージしてください',
|
||||||
@@ -329,6 +335,9 @@ export const strings = {
|
|||||||
styleCodeBlock: '코드 블록',
|
styleCodeBlock: '코드 블록',
|
||||||
undo: '실행 취소',
|
undo: '실행 취소',
|
||||||
redo: '다시 실행',
|
redo: '다시 실행',
|
||||||
|
save: '저장 (⌘S)',
|
||||||
|
autoSave: '자동 저장',
|
||||||
|
autoSaveTip: '자동 저장(30초마다, 창 포커스가 해제될 때)',
|
||||||
bold: '굵게',
|
bold: '굵게',
|
||||||
italic: '기울임꼴',
|
italic: '기울임꼴',
|
||||||
strike: '취소선',
|
strike: '취소선',
|
||||||
@@ -344,13 +353,8 @@ export const strings = {
|
|||||||
insertTable: '표 삽입',
|
insertTable: '표 삽입',
|
||||||
insertImage: '이미지 삽입',
|
insertImage: '이미지 삽입',
|
||||||
insertHr: '구분선',
|
insertHr: '구분선',
|
||||||
insertCallout: '콜아웃',
|
|
||||||
insertToggle: '토글',
|
|
||||||
slashNoResults: '결과 없음',
|
slashNoResults: '결과 없음',
|
||||||
toggleSummaryPlaceholder: '토글 제목…',
|
|
||||||
fmProperties: '속성',
|
fmProperties: '속성',
|
||||||
underline: '밑줄',
|
|
||||||
highlight: '형광펜',
|
|
||||||
codeCopy: '복사',
|
codeCopy: '복사',
|
||||||
codeCopied: '복사됨',
|
codeCopied: '복사됨',
|
||||||
tableRowAbove: '위에 행 삽입',
|
tableRowAbove: '위에 행 삽입',
|
||||||
@@ -361,11 +365,15 @@ export const strings = {
|
|||||||
tableDeleteCol: '열 삭제',
|
tableDeleteCol: '열 삭제',
|
||||||
tableToggleHeaderRow: '머리글 행 전환',
|
tableToggleHeaderRow: '머리글 행 전환',
|
||||||
tableDeleteTable: '표 삭제',
|
tableDeleteTable: '표 삭제',
|
||||||
|
imageAlignLeft: '왼쪽 정렬',
|
||||||
|
imageAlignCenter: '가운데 정렬',
|
||||||
|
imageAlignRight: '오른쪽 정렬',
|
||||||
blockAddBelow: '아래에 블록 추가',
|
blockAddBelow: '아래에 블록 추가',
|
||||||
blockDuplicate: '블록 복제',
|
blockDuplicate: '블록 복제',
|
||||||
blockMoveUp: '위로 이동',
|
blockMoveUp: '위로 이동',
|
||||||
blockMoveDown: '아래로 이동',
|
blockMoveDown: '아래로 이동',
|
||||||
blockDelete: '삭제',
|
blockDelete: '삭제',
|
||||||
|
blockGripHint: '드래그로 이동, 클릭하면 메뉴',
|
||||||
aiUnknownError: 'AI 요청이 실패했습니다. 다시 시도하세요',
|
aiUnknownError: 'AI 요청이 실패했습니다. 다시 시도하세요',
|
||||||
aiTimeoutError: 'AI 응답 시간 초과',
|
aiTimeoutError: 'AI 응답 시간 초과',
|
||||||
aiCreditsExhausted: '크레딧이 부족합니다. genspark.ai에서 충전하세요',
|
aiCreditsExhausted: '크레딧이 부족합니다. genspark.ai에서 충전하세요',
|
||||||
@@ -433,6 +441,10 @@ export const strings = {
|
|||||||
styleCodeBlock: 'Bloc de code',
|
styleCodeBlock: 'Bloc de code',
|
||||||
undo: 'Annuler',
|
undo: 'Annuler',
|
||||||
redo: 'Rétablir',
|
redo: 'Rétablir',
|
||||||
|
save: 'Enregistrer (⌘S)',
|
||||||
|
autoSave: 'Enregistrement automatique',
|
||||||
|
autoSaveTip:
|
||||||
|
'Enregistrement automatique (toutes les 30 secondes et lorsque la fenêtre perd le focus)',
|
||||||
bold: 'Gras',
|
bold: 'Gras',
|
||||||
italic: 'Italique',
|
italic: 'Italique',
|
||||||
strike: 'Barré',
|
strike: 'Barré',
|
||||||
@@ -448,13 +460,8 @@ export const strings = {
|
|||||||
insertTable: 'Insérer un tableau',
|
insertTable: 'Insérer un tableau',
|
||||||
insertImage: 'Insérer une image',
|
insertImage: 'Insérer une image',
|
||||||
insertHr: 'Séparateur',
|
insertHr: 'Séparateur',
|
||||||
insertCallout: 'Encadré',
|
|
||||||
insertToggle: 'Bloc dépliant',
|
|
||||||
slashNoResults: 'Aucun résultat',
|
slashNoResults: 'Aucun résultat',
|
||||||
toggleSummaryPlaceholder: 'Titre du bloc…',
|
|
||||||
fmProperties: 'Propriétés',
|
fmProperties: 'Propriétés',
|
||||||
underline: 'Souligné',
|
|
||||||
highlight: 'Surligner',
|
|
||||||
codeCopy: 'Copier',
|
codeCopy: 'Copier',
|
||||||
codeCopied: 'Copié',
|
codeCopied: 'Copié',
|
||||||
tableRowAbove: 'Insérer une ligne au-dessus',
|
tableRowAbove: 'Insérer une ligne au-dessus',
|
||||||
@@ -465,11 +472,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'Supprimer la colonne',
|
tableDeleteCol: 'Supprimer la colonne',
|
||||||
tableToggleHeaderRow: 'Basculer la ligne d’en-tête',
|
tableToggleHeaderRow: 'Basculer la ligne d’en-tête',
|
||||||
tableDeleteTable: 'Supprimer le tableau',
|
tableDeleteTable: 'Supprimer le tableau',
|
||||||
|
imageAlignLeft: 'Aligner à gauche',
|
||||||
|
imageAlignCenter: 'Centrer',
|
||||||
|
imageAlignRight: 'Aligner à droite',
|
||||||
blockAddBelow: 'Ajouter un bloc en dessous',
|
blockAddBelow: 'Ajouter un bloc en dessous',
|
||||||
blockDuplicate: 'Dupliquer',
|
blockDuplicate: 'Dupliquer',
|
||||||
blockMoveUp: 'Déplacer vers le haut',
|
blockMoveUp: 'Déplacer vers le haut',
|
||||||
blockMoveDown: 'Déplacer vers le bas',
|
blockMoveDown: 'Déplacer vers le bas',
|
||||||
blockDelete: 'Supprimer',
|
blockDelete: 'Supprimer',
|
||||||
|
blockGripHint: 'Glisser pour déplacer, cliquer pour le menu',
|
||||||
aiUnknownError: 'La requête IA a échoué, réessayez',
|
aiUnknownError: 'La requête IA a échoué, réessayez',
|
||||||
aiTimeoutError: 'Délai de réponse IA dépassé',
|
aiTimeoutError: 'Délai de réponse IA dépassé',
|
||||||
aiCreditsExhausted: 'Crédits épuisés — rechargez sur genspark.ai',
|
aiCreditsExhausted: 'Crédits épuisés — rechargez sur genspark.ai',
|
||||||
@@ -538,6 +549,10 @@ export const strings = {
|
|||||||
styleCodeBlock: 'Codeblock',
|
styleCodeBlock: 'Codeblock',
|
||||||
undo: 'Rückgängig',
|
undo: 'Rückgängig',
|
||||||
redo: 'Wiederholen',
|
redo: 'Wiederholen',
|
||||||
|
save: 'Speichern (⌘S)',
|
||||||
|
autoSave: 'Automatisches Speichern',
|
||||||
|
autoSaveTip:
|
||||||
|
'Automatisches Speichern (alle 30 Sekunden und wenn das Fenster den Fokus verliert)',
|
||||||
bold: 'Fett',
|
bold: 'Fett',
|
||||||
italic: 'Kursiv',
|
italic: 'Kursiv',
|
||||||
strike: 'Durchgestrichen',
|
strike: 'Durchgestrichen',
|
||||||
@@ -553,13 +568,8 @@ export const strings = {
|
|||||||
insertTable: 'Tabelle einfügen',
|
insertTable: 'Tabelle einfügen',
|
||||||
insertImage: 'Bild einfügen',
|
insertImage: 'Bild einfügen',
|
||||||
insertHr: 'Trennlinie',
|
insertHr: 'Trennlinie',
|
||||||
insertCallout: 'Hinweisbox',
|
|
||||||
insertToggle: 'Aufklappblock',
|
|
||||||
slashNoResults: 'Keine Treffer',
|
slashNoResults: 'Keine Treffer',
|
||||||
toggleSummaryPlaceholder: 'Titel des Blocks…',
|
|
||||||
fmProperties: 'Eigenschaften',
|
fmProperties: 'Eigenschaften',
|
||||||
underline: 'Unterstrichen',
|
|
||||||
highlight: 'Hervorheben',
|
|
||||||
codeCopy: 'Kopieren',
|
codeCopy: 'Kopieren',
|
||||||
codeCopied: 'Kopiert',
|
codeCopied: 'Kopiert',
|
||||||
tableRowAbove: 'Zeile oberhalb einfügen',
|
tableRowAbove: 'Zeile oberhalb einfügen',
|
||||||
@@ -570,11 +580,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'Spalte löschen',
|
tableDeleteCol: 'Spalte löschen',
|
||||||
tableToggleHeaderRow: 'Kopfzeile umschalten',
|
tableToggleHeaderRow: 'Kopfzeile umschalten',
|
||||||
tableDeleteTable: 'Tabelle löschen',
|
tableDeleteTable: 'Tabelle löschen',
|
||||||
|
imageAlignLeft: 'Linksbündig',
|
||||||
|
imageAlignCenter: 'Zentrieren',
|
||||||
|
imageAlignRight: 'Rechtsbündig',
|
||||||
blockAddBelow: 'Block darunter hinzufügen',
|
blockAddBelow: 'Block darunter hinzufügen',
|
||||||
blockDuplicate: 'Duplizieren',
|
blockDuplicate: 'Duplizieren',
|
||||||
blockMoveUp: 'Nach oben',
|
blockMoveUp: 'Nach oben',
|
||||||
blockMoveDown: 'Nach unten',
|
blockMoveDown: 'Nach unten',
|
||||||
blockDelete: 'Löschen',
|
blockDelete: 'Löschen',
|
||||||
|
blockGripHint: 'Ziehen zum Verschieben, Klick für Menü',
|
||||||
aiUnknownError: 'KI-Anfrage fehlgeschlagen, bitte erneut versuchen',
|
aiUnknownError: 'KI-Anfrage fehlgeschlagen, bitte erneut versuchen',
|
||||||
aiTimeoutError: 'Zeitüberschreitung der KI-Antwort',
|
aiTimeoutError: 'Zeitüberschreitung der KI-Antwort',
|
||||||
aiCreditsExhausted: 'Guthaben aufgebraucht — bei genspark.ai aufladen',
|
aiCreditsExhausted: 'Guthaben aufgebraucht — bei genspark.ai aufladen',
|
||||||
@@ -642,6 +656,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'Bloque de código',
|
styleCodeBlock: 'Bloque de código',
|
||||||
undo: 'Deshacer',
|
undo: 'Deshacer',
|
||||||
redo: 'Rehacer',
|
redo: 'Rehacer',
|
||||||
|
save: 'Guardar (⌘S)',
|
||||||
|
autoSave: 'Autoguardado',
|
||||||
|
autoSaveTip: 'Autoguardado (cada 30 segundos y cuando la ventana pierde el foco)',
|
||||||
bold: 'Negrita',
|
bold: 'Negrita',
|
||||||
italic: 'Cursiva',
|
italic: 'Cursiva',
|
||||||
strike: 'Tachado',
|
strike: 'Tachado',
|
||||||
@@ -657,13 +674,8 @@ export const strings = {
|
|||||||
insertTable: 'Insertar tabla',
|
insertTable: 'Insertar tabla',
|
||||||
insertImage: 'Insertar imagen',
|
insertImage: 'Insertar imagen',
|
||||||
insertHr: 'Separador',
|
insertHr: 'Separador',
|
||||||
insertCallout: 'Nota destacada',
|
|
||||||
insertToggle: 'Bloque plegable',
|
|
||||||
slashNoResults: 'Sin resultados',
|
slashNoResults: 'Sin resultados',
|
||||||
toggleSummaryPlaceholder: 'Título del bloque…',
|
|
||||||
fmProperties: 'Propiedades',
|
fmProperties: 'Propiedades',
|
||||||
underline: 'Subrayado',
|
|
||||||
highlight: 'Resaltar',
|
|
||||||
codeCopy: 'Copiar',
|
codeCopy: 'Copiar',
|
||||||
codeCopied: 'Copiado',
|
codeCopied: 'Copiado',
|
||||||
tableRowAbove: 'Insertar fila arriba',
|
tableRowAbove: 'Insertar fila arriba',
|
||||||
@@ -674,11 +686,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'Eliminar columna',
|
tableDeleteCol: 'Eliminar columna',
|
||||||
tableToggleHeaderRow: 'Alternar fila de encabezado',
|
tableToggleHeaderRow: 'Alternar fila de encabezado',
|
||||||
tableDeleteTable: 'Eliminar tabla',
|
tableDeleteTable: 'Eliminar tabla',
|
||||||
|
imageAlignLeft: 'Alinear a la izquierda',
|
||||||
|
imageAlignCenter: 'Centrar',
|
||||||
|
imageAlignRight: 'Alinear a la derecha',
|
||||||
blockAddBelow: 'Añadir bloque debajo',
|
blockAddBelow: 'Añadir bloque debajo',
|
||||||
blockDuplicate: 'Duplicar',
|
blockDuplicate: 'Duplicar',
|
||||||
blockMoveUp: 'Mover arriba',
|
blockMoveUp: 'Mover arriba',
|
||||||
blockMoveDown: 'Mover abajo',
|
blockMoveDown: 'Mover abajo',
|
||||||
blockDelete: 'Eliminar',
|
blockDelete: 'Eliminar',
|
||||||
|
blockGripHint: 'Arrastra para mover, clic para el menú',
|
||||||
aiUnknownError: 'La solicitud de IA falló, reinténtalo',
|
aiUnknownError: 'La solicitud de IA falló, reinténtalo',
|
||||||
aiTimeoutError: 'La respuesta de IA agotó el tiempo',
|
aiTimeoutError: 'La respuesta de IA agotó el tiempo',
|
||||||
aiCreditsExhausted: 'Sin créditos — recarga en genspark.ai',
|
aiCreditsExhausted: 'Sin créditos — recarga en genspark.ai',
|
||||||
@@ -747,6 +763,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'บล็อกโค้ด',
|
styleCodeBlock: 'บล็อกโค้ด',
|
||||||
undo: 'เลิกทำ',
|
undo: 'เลิกทำ',
|
||||||
redo: 'ทำซ้ำ',
|
redo: 'ทำซ้ำ',
|
||||||
|
save: 'บันทึก (⌘S)',
|
||||||
|
autoSave: 'บันทึกอัตโนมัติ',
|
||||||
|
autoSaveTip: 'บันทึกอัตโนมัติ (ทุก 30 วินาทีและเมื่อหน้าต่างไม่ได้โฟกัส)',
|
||||||
bold: 'ตัวหนา',
|
bold: 'ตัวหนา',
|
||||||
italic: 'ตัวเอียง',
|
italic: 'ตัวเอียง',
|
||||||
strike: 'ขีดฆ่า',
|
strike: 'ขีดฆ่า',
|
||||||
@@ -762,13 +781,8 @@ export const strings = {
|
|||||||
insertTable: 'แทรกตาราง',
|
insertTable: 'แทรกตาราง',
|
||||||
insertImage: 'แทรกรูปภาพ',
|
insertImage: 'แทรกรูปภาพ',
|
||||||
insertHr: 'เส้นแบ่ง',
|
insertHr: 'เส้นแบ่ง',
|
||||||
insertCallout: 'กล่องข้อความ',
|
|
||||||
insertToggle: 'บล็อกพับเก็บ',
|
|
||||||
slashNoResults: 'ไม่พบรายการ',
|
slashNoResults: 'ไม่พบรายการ',
|
||||||
toggleSummaryPlaceholder: 'ชื่อบล็อก…',
|
|
||||||
fmProperties: 'คุณสมบัติ',
|
fmProperties: 'คุณสมบัติ',
|
||||||
underline: 'ขีดเส้นใต้',
|
|
||||||
highlight: 'ไฮไลต์',
|
|
||||||
codeCopy: 'คัดลอก',
|
codeCopy: 'คัดลอก',
|
||||||
codeCopied: 'คัดลอกแล้ว',
|
codeCopied: 'คัดลอกแล้ว',
|
||||||
tableRowAbove: 'แทรกแถวด้านบน',
|
tableRowAbove: 'แทรกแถวด้านบน',
|
||||||
@@ -779,11 +793,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'ลบคอลัมน์',
|
tableDeleteCol: 'ลบคอลัมน์',
|
||||||
tableToggleHeaderRow: 'สลับแถวส่วนหัว',
|
tableToggleHeaderRow: 'สลับแถวส่วนหัว',
|
||||||
tableDeleteTable: 'ลบตาราง',
|
tableDeleteTable: 'ลบตาราง',
|
||||||
|
imageAlignLeft: 'จัดชิดซ้าย',
|
||||||
|
imageAlignCenter: 'จัดกึ่งกลาง',
|
||||||
|
imageAlignRight: 'จัดชิดขวา',
|
||||||
blockAddBelow: 'เพิ่มบล็อกด้านล่าง',
|
blockAddBelow: 'เพิ่มบล็อกด้านล่าง',
|
||||||
blockDuplicate: 'ทำสำเนา',
|
blockDuplicate: 'ทำสำเนา',
|
||||||
blockMoveUp: 'ย้ายขึ้น',
|
blockMoveUp: 'ย้ายขึ้น',
|
||||||
blockMoveDown: 'ย้ายลง',
|
blockMoveDown: 'ย้ายลง',
|
||||||
blockDelete: 'ลบ',
|
blockDelete: 'ลบ',
|
||||||
|
blockGripHint: 'ลากเพื่อย้าย คลิกเพื่อเปิดเมนู',
|
||||||
aiUnknownError: 'คำขอ AI ล้มเหลว โปรดลองอีกครั้ง',
|
aiUnknownError: 'คำขอ AI ล้มเหลว โปรดลองอีกครั้ง',
|
||||||
aiTimeoutError: 'การตอบกลับของ AI หมดเวลา',
|
aiTimeoutError: 'การตอบกลับของ AI หมดเวลา',
|
||||||
aiCreditsExhausted: 'เครดิตหมด — เติมได้ที่ genspark.ai',
|
aiCreditsExhausted: 'เครดิตหมด — เติมได้ที่ genspark.ai',
|
||||||
@@ -851,6 +869,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'Blok kode',
|
styleCodeBlock: 'Blok kode',
|
||||||
undo: 'Urungkan',
|
undo: 'Urungkan',
|
||||||
redo: 'Ulangi',
|
redo: 'Ulangi',
|
||||||
|
save: 'Simpan (⌘S)',
|
||||||
|
autoSave: 'Simpan Otomatis',
|
||||||
|
autoSaveTip: 'Simpan otomatis (setiap 30 detik dan saat jendela kehilangan fokus)',
|
||||||
bold: 'Tebal',
|
bold: 'Tebal',
|
||||||
italic: 'Miring',
|
italic: 'Miring',
|
||||||
strike: 'Coret',
|
strike: 'Coret',
|
||||||
@@ -866,13 +887,8 @@ export const strings = {
|
|||||||
insertTable: 'Sisipkan tabel',
|
insertTable: 'Sisipkan tabel',
|
||||||
insertImage: 'Sisipkan gambar',
|
insertImage: 'Sisipkan gambar',
|
||||||
insertHr: 'Pembatas',
|
insertHr: 'Pembatas',
|
||||||
insertCallout: 'Sorotan',
|
|
||||||
insertToggle: 'Blok lipat',
|
|
||||||
slashNoResults: 'Tidak ada hasil',
|
slashNoResults: 'Tidak ada hasil',
|
||||||
toggleSummaryPlaceholder: 'Judul blok…',
|
|
||||||
fmProperties: 'Properti',
|
fmProperties: 'Properti',
|
||||||
underline: 'Garis bawah',
|
|
||||||
highlight: 'Sorot',
|
|
||||||
codeCopy: 'Salin',
|
codeCopy: 'Salin',
|
||||||
codeCopied: 'Disalin',
|
codeCopied: 'Disalin',
|
||||||
tableRowAbove: 'Sisipkan baris di atas',
|
tableRowAbove: 'Sisipkan baris di atas',
|
||||||
@@ -883,11 +899,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'Hapus kolom',
|
tableDeleteCol: 'Hapus kolom',
|
||||||
tableToggleHeaderRow: 'Alihkan baris header',
|
tableToggleHeaderRow: 'Alihkan baris header',
|
||||||
tableDeleteTable: 'Hapus tabel',
|
tableDeleteTable: 'Hapus tabel',
|
||||||
|
imageAlignLeft: 'Rata kiri',
|
||||||
|
imageAlignCenter: 'Tengah',
|
||||||
|
imageAlignRight: 'Rata kanan',
|
||||||
blockAddBelow: 'Tambah blok di bawah',
|
blockAddBelow: 'Tambah blok di bawah',
|
||||||
blockDuplicate: 'Duplikat',
|
blockDuplicate: 'Duplikat',
|
||||||
blockMoveUp: 'Pindah ke atas',
|
blockMoveUp: 'Pindah ke atas',
|
||||||
blockMoveDown: 'Pindah ke bawah',
|
blockMoveDown: 'Pindah ke bawah',
|
||||||
blockDelete: 'Hapus',
|
blockDelete: 'Hapus',
|
||||||
|
blockGripHint: 'Seret untuk memindahkan, klik untuk menu',
|
||||||
aiUnknownError: 'Permintaan AI gagal, coba lagi',
|
aiUnknownError: 'Permintaan AI gagal, coba lagi',
|
||||||
aiTimeoutError: 'Respons AI kehabisan waktu',
|
aiTimeoutError: 'Respons AI kehabisan waktu',
|
||||||
aiCreditsExhausted: 'Kredit habis — isi ulang di genspark.ai',
|
aiCreditsExhausted: 'Kredit habis — isi ulang di genspark.ai',
|
||||||
@@ -955,6 +975,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'Блок кода',
|
styleCodeBlock: 'Блок кода',
|
||||||
undo: 'Отменить',
|
undo: 'Отменить',
|
||||||
redo: 'Повторить',
|
redo: 'Повторить',
|
||||||
|
save: 'Сохранить (⌘S)',
|
||||||
|
autoSave: 'Автосохранение',
|
||||||
|
autoSaveTip: 'Автосохранение (каждые 30 секунд и при потере фокуса окном)',
|
||||||
bold: 'Полужирный',
|
bold: 'Полужирный',
|
||||||
italic: 'Курсив',
|
italic: 'Курсив',
|
||||||
strike: 'Зачёркнутый',
|
strike: 'Зачёркнутый',
|
||||||
@@ -970,13 +993,8 @@ export const strings = {
|
|||||||
insertTable: 'Вставить таблицу',
|
insertTable: 'Вставить таблицу',
|
||||||
insertImage: 'Вставить изображение',
|
insertImage: 'Вставить изображение',
|
||||||
insertHr: 'Разделитель',
|
insertHr: 'Разделитель',
|
||||||
insertCallout: 'Выноска',
|
|
||||||
insertToggle: 'Сворачиваемый блок',
|
|
||||||
slashNoResults: 'Нет результатов',
|
slashNoResults: 'Нет результатов',
|
||||||
toggleSummaryPlaceholder: 'Заголовок блока…',
|
|
||||||
fmProperties: 'Свойства',
|
fmProperties: 'Свойства',
|
||||||
underline: 'Подчёркнутый',
|
|
||||||
highlight: 'Выделение',
|
|
||||||
codeCopy: 'Копировать',
|
codeCopy: 'Копировать',
|
||||||
codeCopied: 'Скопировано',
|
codeCopied: 'Скопировано',
|
||||||
tableRowAbove: 'Вставить строку выше',
|
tableRowAbove: 'Вставить строку выше',
|
||||||
@@ -987,11 +1005,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'Удалить столбец',
|
tableDeleteCol: 'Удалить столбец',
|
||||||
tableToggleHeaderRow: 'Переключить строку заголовка',
|
tableToggleHeaderRow: 'Переключить строку заголовка',
|
||||||
tableDeleteTable: 'Удалить таблицу',
|
tableDeleteTable: 'Удалить таблицу',
|
||||||
|
imageAlignLeft: 'По левому краю',
|
||||||
|
imageAlignCenter: 'По центру',
|
||||||
|
imageAlignRight: 'По правому краю',
|
||||||
blockAddBelow: 'Добавить блок ниже',
|
blockAddBelow: 'Добавить блок ниже',
|
||||||
blockDuplicate: 'Дублировать',
|
blockDuplicate: 'Дублировать',
|
||||||
blockMoveUp: 'Переместить вверх',
|
blockMoveUp: 'Переместить вверх',
|
||||||
blockMoveDown: 'Переместить вниз',
|
blockMoveDown: 'Переместить вниз',
|
||||||
blockDelete: 'Удалить',
|
blockDelete: 'Удалить',
|
||||||
|
blockGripHint: 'Перетащите для перемещения, клик — меню',
|
||||||
aiUnknownError: 'Сбой запроса ИИ, попробуйте ещё раз',
|
aiUnknownError: 'Сбой запроса ИИ, попробуйте ещё раз',
|
||||||
aiTimeoutError: 'Тайм-аут ответа ИИ',
|
aiTimeoutError: 'Тайм-аут ответа ИИ',
|
||||||
aiCreditsExhausted: 'Кредиты закончились — пополните на genspark.ai',
|
aiCreditsExhausted: 'Кредиты закончились — пополните на genspark.ai',
|
||||||
@@ -1059,6 +1081,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'كتلة تعليمات برمجية',
|
styleCodeBlock: 'كتلة تعليمات برمجية',
|
||||||
undo: 'تراجع',
|
undo: 'تراجع',
|
||||||
redo: 'إعادة',
|
redo: 'إعادة',
|
||||||
|
save: 'حفظ (⌘S)',
|
||||||
|
autoSave: 'حفظ تلقائي',
|
||||||
|
autoSaveTip: 'حفظ تلقائي (كل 30 ثانية وعند فقدان النافذة للتركيز)',
|
||||||
bold: 'غامق',
|
bold: 'غامق',
|
||||||
italic: 'مائل',
|
italic: 'مائل',
|
||||||
strike: 'يتوسطه خط',
|
strike: 'يتوسطه خط',
|
||||||
@@ -1074,13 +1099,8 @@ export const strings = {
|
|||||||
insertTable: 'إدراج جدول',
|
insertTable: 'إدراج جدول',
|
||||||
insertImage: 'إدراج صورة',
|
insertImage: 'إدراج صورة',
|
||||||
insertHr: 'فاصل',
|
insertHr: 'فاصل',
|
||||||
insertCallout: 'تنبيه',
|
|
||||||
insertToggle: 'كتلة قابلة للطي',
|
|
||||||
slashNoResults: 'لا نتائج',
|
slashNoResults: 'لا نتائج',
|
||||||
toggleSummaryPlaceholder: 'عنوان الكتلة…',
|
|
||||||
fmProperties: 'خصائص',
|
fmProperties: 'خصائص',
|
||||||
underline: 'تسطير',
|
|
||||||
highlight: 'تمييز',
|
|
||||||
codeCopy: 'نسخ',
|
codeCopy: 'نسخ',
|
||||||
codeCopied: 'تم النسخ',
|
codeCopied: 'تم النسخ',
|
||||||
tableRowAbove: 'إدراج صف أعلى',
|
tableRowAbove: 'إدراج صف أعلى',
|
||||||
@@ -1091,11 +1111,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'حذف العمود',
|
tableDeleteCol: 'حذف العمود',
|
||||||
tableToggleHeaderRow: 'تبديل صف العناوين',
|
tableToggleHeaderRow: 'تبديل صف العناوين',
|
||||||
tableDeleteTable: 'حذف الجدول',
|
tableDeleteTable: 'حذف الجدول',
|
||||||
|
imageAlignLeft: 'محاذاة لليسار',
|
||||||
|
imageAlignCenter: 'توسيط',
|
||||||
|
imageAlignRight: 'محاذاة لليمين',
|
||||||
blockAddBelow: 'إضافة كتلة أسفل',
|
blockAddBelow: 'إضافة كتلة أسفل',
|
||||||
blockDuplicate: 'تكرار',
|
blockDuplicate: 'تكرار',
|
||||||
blockMoveUp: 'نقل لأعلى',
|
blockMoveUp: 'نقل لأعلى',
|
||||||
blockMoveDown: 'نقل لأسفل',
|
blockMoveDown: 'نقل لأسفل',
|
||||||
blockDelete: 'حذف',
|
blockDelete: 'حذف',
|
||||||
|
blockGripHint: 'اسحب للنقل، وانقر لفتح القائمة',
|
||||||
aiUnknownError: 'فشل طلب الذكاء الاصطناعي، أعد المحاولة',
|
aiUnknownError: 'فشل طلب الذكاء الاصطناعي، أعد المحاولة',
|
||||||
aiTimeoutError: 'انتهت مهلة استجابة الذكاء الاصطناعي',
|
aiTimeoutError: 'انتهت مهلة استجابة الذكاء الاصطناعي',
|
||||||
aiCreditsExhausted: 'نفدت الأرصدة — أعد الشحن على genspark.ai',
|
aiCreditsExhausted: 'نفدت الأرصدة — أعد الشحن على genspark.ai',
|
||||||
@@ -1163,6 +1187,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'Bloco de código',
|
styleCodeBlock: 'Bloco de código',
|
||||||
undo: 'Desfazer',
|
undo: 'Desfazer',
|
||||||
redo: 'Refazer',
|
redo: 'Refazer',
|
||||||
|
save: 'Salvar (⌘S)',
|
||||||
|
autoSave: 'Salvamento automático',
|
||||||
|
autoSaveTip: 'Salvamento automático (a cada 30 segundos e quando a janela perde o foco)',
|
||||||
bold: 'Negrito',
|
bold: 'Negrito',
|
||||||
italic: 'Itálico',
|
italic: 'Itálico',
|
||||||
strike: 'Tachado',
|
strike: 'Tachado',
|
||||||
@@ -1178,13 +1205,8 @@ export const strings = {
|
|||||||
insertTable: 'Inserir tabela',
|
insertTable: 'Inserir tabela',
|
||||||
insertImage: 'Inserir imagem',
|
insertImage: 'Inserir imagem',
|
||||||
insertHr: 'Divisor',
|
insertHr: 'Divisor',
|
||||||
insertCallout: 'Destaque',
|
|
||||||
insertToggle: 'Bloco recolhível',
|
|
||||||
slashNoResults: 'Sem resultados',
|
slashNoResults: 'Sem resultados',
|
||||||
toggleSummaryPlaceholder: 'Título do bloco…',
|
|
||||||
fmProperties: 'Propriedades',
|
fmProperties: 'Propriedades',
|
||||||
underline: 'Sublinhado',
|
|
||||||
highlight: 'Realçar',
|
|
||||||
codeCopy: 'Copiar',
|
codeCopy: 'Copiar',
|
||||||
codeCopied: 'Copiado',
|
codeCopied: 'Copiado',
|
||||||
tableRowAbove: 'Inserir linha acima',
|
tableRowAbove: 'Inserir linha acima',
|
||||||
@@ -1195,11 +1217,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'Excluir coluna',
|
tableDeleteCol: 'Excluir coluna',
|
||||||
tableToggleHeaderRow: 'Alternar linha de cabeçalho',
|
tableToggleHeaderRow: 'Alternar linha de cabeçalho',
|
||||||
tableDeleteTable: 'Excluir tabela',
|
tableDeleteTable: 'Excluir tabela',
|
||||||
|
imageAlignLeft: 'Alinhar à esquerda',
|
||||||
|
imageAlignCenter: 'Centralizar',
|
||||||
|
imageAlignRight: 'Alinhar à direita',
|
||||||
blockAddBelow: 'Adicionar bloco abaixo',
|
blockAddBelow: 'Adicionar bloco abaixo',
|
||||||
blockDuplicate: 'Duplicar',
|
blockDuplicate: 'Duplicar',
|
||||||
blockMoveUp: 'Mover para cima',
|
blockMoveUp: 'Mover para cima',
|
||||||
blockMoveDown: 'Mover para baixo',
|
blockMoveDown: 'Mover para baixo',
|
||||||
blockDelete: 'Excluir',
|
blockDelete: 'Excluir',
|
||||||
|
blockGripHint: 'Arraste para mover, clique para o menu',
|
||||||
aiUnknownError: 'A solicitação de IA falhou, tente novamente',
|
aiUnknownError: 'A solicitação de IA falhou, tente novamente',
|
||||||
aiTimeoutError: 'A resposta da IA expirou',
|
aiTimeoutError: 'A resposta da IA expirou',
|
||||||
aiCreditsExhausted: 'Créditos esgotados — recarregue em genspark.ai',
|
aiCreditsExhausted: 'Créditos esgotados — recarregue em genspark.ai',
|
||||||
@@ -1267,6 +1293,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'Blocco di codice',
|
styleCodeBlock: 'Blocco di codice',
|
||||||
undo: 'Annulla',
|
undo: 'Annulla',
|
||||||
redo: 'Ripeti',
|
redo: 'Ripeti',
|
||||||
|
save: 'Salva (⌘S)',
|
||||||
|
autoSave: 'Salvataggio automatico',
|
||||||
|
autoSaveTip: 'Salvataggio automatico (ogni 30 secondi e quando la finestra perde il focus)',
|
||||||
bold: 'Grassetto',
|
bold: 'Grassetto',
|
||||||
italic: 'Corsivo',
|
italic: 'Corsivo',
|
||||||
strike: 'Barrato',
|
strike: 'Barrato',
|
||||||
@@ -1282,13 +1311,8 @@ export const strings = {
|
|||||||
insertTable: 'Inserisci tabella',
|
insertTable: 'Inserisci tabella',
|
||||||
insertImage: 'Inserisci immagine',
|
insertImage: 'Inserisci immagine',
|
||||||
insertHr: 'Divisore',
|
insertHr: 'Divisore',
|
||||||
insertCallout: 'Richiamo',
|
|
||||||
insertToggle: 'Blocco comprimibile',
|
|
||||||
slashNoResults: 'Nessun risultato',
|
slashNoResults: 'Nessun risultato',
|
||||||
toggleSummaryPlaceholder: 'Titolo del blocco…',
|
|
||||||
fmProperties: 'Proprietà',
|
fmProperties: 'Proprietà',
|
||||||
underline: 'Sottolineato',
|
|
||||||
highlight: 'Evidenzia',
|
|
||||||
codeCopy: 'Copia',
|
codeCopy: 'Copia',
|
||||||
codeCopied: 'Copiato',
|
codeCopied: 'Copiato',
|
||||||
tableRowAbove: 'Inserisci riga sopra',
|
tableRowAbove: 'Inserisci riga sopra',
|
||||||
@@ -1299,11 +1323,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'Elimina colonna',
|
tableDeleteCol: 'Elimina colonna',
|
||||||
tableToggleHeaderRow: 'Attiva/disattiva riga di intestazione',
|
tableToggleHeaderRow: 'Attiva/disattiva riga di intestazione',
|
||||||
tableDeleteTable: 'Elimina tabella',
|
tableDeleteTable: 'Elimina tabella',
|
||||||
|
imageAlignLeft: 'Allinea a sinistra',
|
||||||
|
imageAlignCenter: 'Centra',
|
||||||
|
imageAlignRight: 'Allinea a destra',
|
||||||
blockAddBelow: 'Aggiungi blocco sotto',
|
blockAddBelow: 'Aggiungi blocco sotto',
|
||||||
blockDuplicate: 'Duplica',
|
blockDuplicate: 'Duplica',
|
||||||
blockMoveUp: 'Sposta su',
|
blockMoveUp: 'Sposta su',
|
||||||
blockMoveDown: 'Sposta giù',
|
blockMoveDown: 'Sposta giù',
|
||||||
blockDelete: 'Elimina',
|
blockDelete: 'Elimina',
|
||||||
|
blockGripHint: 'Trascina per spostare, clicca per il menu',
|
||||||
aiUnknownError: 'Richiesta IA non riuscita, riprova',
|
aiUnknownError: 'Richiesta IA non riuscita, riprova',
|
||||||
aiTimeoutError: 'Timeout della risposta IA',
|
aiTimeoutError: 'Timeout della risposta IA',
|
||||||
aiCreditsExhausted: 'Crediti esauriti — ricarica su genspark.ai',
|
aiCreditsExhausted: 'Crediti esauriti — ricarica su genspark.ai',
|
||||||
@@ -1371,6 +1399,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'Blok kodu',
|
styleCodeBlock: 'Blok kodu',
|
||||||
undo: 'Cofnij',
|
undo: 'Cofnij',
|
||||||
redo: 'Ponów',
|
redo: 'Ponów',
|
||||||
|
save: 'Zapisz (⌘S)',
|
||||||
|
autoSave: 'Autozapis',
|
||||||
|
autoSaveTip: 'Autozapis (co 30 sekund oraz gdy okno traci fokus)',
|
||||||
bold: 'Pogrubienie',
|
bold: 'Pogrubienie',
|
||||||
italic: 'Kursywa',
|
italic: 'Kursywa',
|
||||||
strike: 'Przekreślenie',
|
strike: 'Przekreślenie',
|
||||||
@@ -1386,13 +1417,8 @@ export const strings = {
|
|||||||
insertTable: 'Wstaw tabelę',
|
insertTable: 'Wstaw tabelę',
|
||||||
insertImage: 'Wstaw obraz',
|
insertImage: 'Wstaw obraz',
|
||||||
insertHr: 'Separator',
|
insertHr: 'Separator',
|
||||||
insertCallout: 'Wyróżnienie',
|
|
||||||
insertToggle: 'Blok zwijany',
|
|
||||||
slashNoResults: 'Brak wyników',
|
slashNoResults: 'Brak wyników',
|
||||||
toggleSummaryPlaceholder: 'Tytuł bloku…',
|
|
||||||
fmProperties: 'Właściwości',
|
fmProperties: 'Właściwości',
|
||||||
underline: 'Podkreślenie',
|
|
||||||
highlight: 'Wyróżnienie',
|
|
||||||
codeCopy: 'Kopiuj',
|
codeCopy: 'Kopiuj',
|
||||||
codeCopied: 'Skopiowano',
|
codeCopied: 'Skopiowano',
|
||||||
tableRowAbove: 'Wstaw wiersz powyżej',
|
tableRowAbove: 'Wstaw wiersz powyżej',
|
||||||
@@ -1403,11 +1429,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'Usuń kolumnę',
|
tableDeleteCol: 'Usuń kolumnę',
|
||||||
tableToggleHeaderRow: 'Przełącz wiersz nagłówka',
|
tableToggleHeaderRow: 'Przełącz wiersz nagłówka',
|
||||||
tableDeleteTable: 'Usuń tabelę',
|
tableDeleteTable: 'Usuń tabelę',
|
||||||
|
imageAlignLeft: 'Wyrównaj do lewej',
|
||||||
|
imageAlignCenter: 'Wyśrodkuj',
|
||||||
|
imageAlignRight: 'Wyrównaj do prawej',
|
||||||
blockAddBelow: 'Dodaj blok poniżej',
|
blockAddBelow: 'Dodaj blok poniżej',
|
||||||
blockDuplicate: 'Duplikuj',
|
blockDuplicate: 'Duplikuj',
|
||||||
blockMoveUp: 'Przenieś w górę',
|
blockMoveUp: 'Przenieś w górę',
|
||||||
blockMoveDown: 'Przenieś w dół',
|
blockMoveDown: 'Przenieś w dół',
|
||||||
blockDelete: 'Usuń',
|
blockDelete: 'Usuń',
|
||||||
|
blockGripHint: 'Przeciągnij, aby przenieść; kliknij, aby otworzyć menu',
|
||||||
aiUnknownError: 'Żądanie AI nie powiodło się, spróbuj ponownie',
|
aiUnknownError: 'Żądanie AI nie powiodło się, spróbuj ponownie',
|
||||||
aiTimeoutError: 'Przekroczono czas odpowiedzi AI',
|
aiTimeoutError: 'Przekroczono czas odpowiedzi AI',
|
||||||
aiCreditsExhausted: 'Brak kredytów — doładuj na genspark.ai',
|
aiCreditsExhausted: 'Brak kredytów — doładuj na genspark.ai',
|
||||||
@@ -1475,6 +1505,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'Codeblok',
|
styleCodeBlock: 'Codeblok',
|
||||||
undo: 'Ongedaan maken',
|
undo: 'Ongedaan maken',
|
||||||
redo: 'Opnieuw',
|
redo: 'Opnieuw',
|
||||||
|
save: 'Opslaan (⌘S)',
|
||||||
|
autoSave: 'Automatisch opslaan',
|
||||||
|
autoSaveTip: 'Automatisch opslaan (elke 30 seconden en wanneer het venster de focus verliest)',
|
||||||
bold: 'Vet',
|
bold: 'Vet',
|
||||||
italic: 'Cursief',
|
italic: 'Cursief',
|
||||||
strike: 'Doorhalen',
|
strike: 'Doorhalen',
|
||||||
@@ -1490,13 +1523,8 @@ export const strings = {
|
|||||||
insertTable: 'Tabel invoegen',
|
insertTable: 'Tabel invoegen',
|
||||||
insertImage: 'Afbeelding invoegen',
|
insertImage: 'Afbeelding invoegen',
|
||||||
insertHr: 'Scheidingslijn',
|
insertHr: 'Scheidingslijn',
|
||||||
insertCallout: 'Callout',
|
|
||||||
insertToggle: 'Uitklapblok',
|
|
||||||
slashNoResults: 'Geen resultaten',
|
slashNoResults: 'Geen resultaten',
|
||||||
toggleSummaryPlaceholder: 'Bloktitel…',
|
|
||||||
fmProperties: 'Eigenschappen',
|
fmProperties: 'Eigenschappen',
|
||||||
underline: 'Onderstrepen',
|
|
||||||
highlight: 'Markeren',
|
|
||||||
codeCopy: 'Kopiëren',
|
codeCopy: 'Kopiëren',
|
||||||
codeCopied: 'Gekopieerd',
|
codeCopied: 'Gekopieerd',
|
||||||
tableRowAbove: 'Rij boven invoegen',
|
tableRowAbove: 'Rij boven invoegen',
|
||||||
@@ -1507,11 +1535,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'Kolom verwijderen',
|
tableDeleteCol: 'Kolom verwijderen',
|
||||||
tableToggleHeaderRow: 'Kopregel wisselen',
|
tableToggleHeaderRow: 'Kopregel wisselen',
|
||||||
tableDeleteTable: 'Tabel verwijderen',
|
tableDeleteTable: 'Tabel verwijderen',
|
||||||
|
imageAlignLeft: 'Links uitlijnen',
|
||||||
|
imageAlignCenter: 'Centreren',
|
||||||
|
imageAlignRight: 'Rechts uitlijnen',
|
||||||
blockAddBelow: 'Blok onder toevoegen',
|
blockAddBelow: 'Blok onder toevoegen',
|
||||||
blockDuplicate: 'Dupliceren',
|
blockDuplicate: 'Dupliceren',
|
||||||
blockMoveUp: 'Omhoog',
|
blockMoveUp: 'Omhoog',
|
||||||
blockMoveDown: 'Omlaag',
|
blockMoveDown: 'Omlaag',
|
||||||
blockDelete: 'Verwijderen',
|
blockDelete: 'Verwijderen',
|
||||||
|
blockGripHint: 'Sleep om te verplaatsen, klik voor menu',
|
||||||
aiUnknownError: 'AI-verzoek mislukt, probeer opnieuw',
|
aiUnknownError: 'AI-verzoek mislukt, probeer opnieuw',
|
||||||
aiTimeoutError: 'AI-antwoord time-out',
|
aiTimeoutError: 'AI-antwoord time-out',
|
||||||
aiCreditsExhausted: 'Credits op — waardeer op via genspark.ai',
|
aiCreditsExhausted: 'Credits op — waardeer op via genspark.ai',
|
||||||
@@ -1579,6 +1611,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'Blok kod',
|
styleCodeBlock: 'Blok kod',
|
||||||
undo: 'Buat asal',
|
undo: 'Buat asal',
|
||||||
redo: 'Buat semula',
|
redo: 'Buat semula',
|
||||||
|
save: 'Simpan (⌘S)',
|
||||||
|
autoSave: 'Autosimpan',
|
||||||
|
autoSaveTip: 'Autosimpan (setiap 30 saat dan apabila tetingkap hilang fokus)',
|
||||||
bold: 'Tebal',
|
bold: 'Tebal',
|
||||||
italic: 'Condong',
|
italic: 'Condong',
|
||||||
strike: 'Garis lorek',
|
strike: 'Garis lorek',
|
||||||
@@ -1594,13 +1629,8 @@ export const strings = {
|
|||||||
insertTable: 'Sisip jadual',
|
insertTable: 'Sisip jadual',
|
||||||
insertImage: 'Sisip imej',
|
insertImage: 'Sisip imej',
|
||||||
insertHr: 'Pemisah',
|
insertHr: 'Pemisah',
|
||||||
insertCallout: 'Seruan',
|
|
||||||
insertToggle: 'Blok lipat',
|
|
||||||
slashNoResults: 'Tiada hasil',
|
slashNoResults: 'Tiada hasil',
|
||||||
toggleSummaryPlaceholder: 'Tajuk blok…',
|
|
||||||
fmProperties: 'Sifat',
|
fmProperties: 'Sifat',
|
||||||
underline: 'Garis bawah',
|
|
||||||
highlight: 'Sorotan',
|
|
||||||
codeCopy: 'Salin',
|
codeCopy: 'Salin',
|
||||||
codeCopied: 'Disalin',
|
codeCopied: 'Disalin',
|
||||||
tableRowAbove: 'Sisip baris di atas',
|
tableRowAbove: 'Sisip baris di atas',
|
||||||
@@ -1611,11 +1641,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'Padam lajur',
|
tableDeleteCol: 'Padam lajur',
|
||||||
tableToggleHeaderRow: 'Togol baris pengepala',
|
tableToggleHeaderRow: 'Togol baris pengepala',
|
||||||
tableDeleteTable: 'Padam jadual',
|
tableDeleteTable: 'Padam jadual',
|
||||||
|
imageAlignLeft: 'Jajar kiri',
|
||||||
|
imageAlignCenter: 'Tengah',
|
||||||
|
imageAlignRight: 'Jajar kanan',
|
||||||
blockAddBelow: 'Tambah blok di bawah',
|
blockAddBelow: 'Tambah blok di bawah',
|
||||||
blockDuplicate: 'Pendua',
|
blockDuplicate: 'Pendua',
|
||||||
blockMoveUp: 'Alih ke atas',
|
blockMoveUp: 'Alih ke atas',
|
||||||
blockMoveDown: 'Alih ke bawah',
|
blockMoveDown: 'Alih ke bawah',
|
||||||
blockDelete: 'Padam',
|
blockDelete: 'Padam',
|
||||||
|
blockGripHint: 'Seret untuk alih, klik untuk menu',
|
||||||
aiUnknownError: 'Permintaan AI gagal, cuba lagi',
|
aiUnknownError: 'Permintaan AI gagal, cuba lagi',
|
||||||
aiTimeoutError: 'Respons AI tamat masa',
|
aiTimeoutError: 'Respons AI tamat masa',
|
||||||
aiCreditsExhausted: 'Kredit habis — tambah nilai di genspark.ai',
|
aiCreditsExhausted: 'Kredit habis — tambah nilai di genspark.ai',
|
||||||
@@ -1683,6 +1717,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'בלוק קוד',
|
styleCodeBlock: 'בלוק קוד',
|
||||||
undo: 'בטל',
|
undo: 'בטל',
|
||||||
redo: 'בצע שוב',
|
redo: 'בצע שוב',
|
||||||
|
save: 'שמירה (⌘S)',
|
||||||
|
autoSave: 'שמירה אוטומטית',
|
||||||
|
autoSaveTip: 'שמירה אוטומטית (כל 30 שניות וכאשר החלון מאבד מיקוד)',
|
||||||
bold: 'מודגש',
|
bold: 'מודגש',
|
||||||
italic: 'נטוי',
|
italic: 'נטוי',
|
||||||
strike: 'קו חוצה',
|
strike: 'קו חוצה',
|
||||||
@@ -1698,13 +1735,8 @@ export const strings = {
|
|||||||
insertTable: 'הוספת טבלה',
|
insertTable: 'הוספת טבלה',
|
||||||
insertImage: 'הוספת תמונה',
|
insertImage: 'הוספת תמונה',
|
||||||
insertHr: 'קו מפריד',
|
insertHr: 'קו מפריד',
|
||||||
insertCallout: 'הבלטה',
|
|
||||||
insertToggle: 'בלוק מתקפל',
|
|
||||||
slashNoResults: 'אין תוצאות',
|
slashNoResults: 'אין תוצאות',
|
||||||
toggleSummaryPlaceholder: 'כותרת הבלוק…',
|
|
||||||
fmProperties: 'מאפיינים',
|
fmProperties: 'מאפיינים',
|
||||||
underline: 'קו תחתון',
|
|
||||||
highlight: 'הדגשה',
|
|
||||||
codeCopy: 'העתק',
|
codeCopy: 'העתק',
|
||||||
codeCopied: 'הועתק',
|
codeCopied: 'הועתק',
|
||||||
tableRowAbove: 'הוסף שורה מעל',
|
tableRowAbove: 'הוסף שורה מעל',
|
||||||
@@ -1715,11 +1747,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'מחק עמודה',
|
tableDeleteCol: 'מחק עמודה',
|
||||||
tableToggleHeaderRow: 'החלף שורת כותרת',
|
tableToggleHeaderRow: 'החלף שורת כותרת',
|
||||||
tableDeleteTable: 'מחק טבלה',
|
tableDeleteTable: 'מחק טבלה',
|
||||||
|
imageAlignLeft: 'יישור לשמאל',
|
||||||
|
imageAlignCenter: 'מרכוז',
|
||||||
|
imageAlignRight: 'יישור לימין',
|
||||||
blockAddBelow: 'הוסף בלוק מתחת',
|
blockAddBelow: 'הוסף בלוק מתחת',
|
||||||
blockDuplicate: 'שכפל',
|
blockDuplicate: 'שכפל',
|
||||||
blockMoveUp: 'הזז למעלה',
|
blockMoveUp: 'הזז למעלה',
|
||||||
blockMoveDown: 'הזז למטה',
|
blockMoveDown: 'הזז למטה',
|
||||||
blockDelete: 'מחק',
|
blockDelete: 'מחק',
|
||||||
|
blockGripHint: 'גרירה להזזה, לחיצה לתפריט',
|
||||||
aiUnknownError: 'בקשת ה-AI נכשלה, נסו שוב',
|
aiUnknownError: 'בקשת ה-AI נכשלה, נסו שוב',
|
||||||
aiTimeoutError: 'תגובת ה-AI חרגה מהזמן',
|
aiTimeoutError: 'תגובת ה-AI חרגה מהזמן',
|
||||||
aiCreditsExhausted: 'נגמרו הקרדיטים — טענו ב-genspark.ai',
|
aiCreditsExhausted: 'נגמרו הקרדיטים — טענו ב-genspark.ai',
|
||||||
@@ -1787,6 +1823,9 @@ export const strings = {
|
|||||||
styleCodeBlock: 'कोड ब्लॉक',
|
styleCodeBlock: 'कोड ब्लॉक',
|
||||||
undo: 'पूर्ववत करें',
|
undo: 'पूर्ववत करें',
|
||||||
redo: 'फिर से करें',
|
redo: 'फिर से करें',
|
||||||
|
save: 'सहेजें (⌘S)',
|
||||||
|
autoSave: 'स्वतः सहेजना',
|
||||||
|
autoSaveTip: 'स्वतः सहेजना (हर 30 सेकंड में और विंडो का फ़ोकस हटने पर)',
|
||||||
bold: 'बोल्ड',
|
bold: 'बोल्ड',
|
||||||
italic: 'इटैलिक',
|
italic: 'इटैलिक',
|
||||||
strike: 'स्ट्राइकथ्रू',
|
strike: 'स्ट्राइकथ्रू',
|
||||||
@@ -1802,13 +1841,8 @@ export const strings = {
|
|||||||
insertTable: 'तालिका सम्मिलित करें',
|
insertTable: 'तालिका सम्मिलित करें',
|
||||||
insertImage: 'छवि सम्मिलित करें',
|
insertImage: 'छवि सम्मिलित करें',
|
||||||
insertHr: 'विभाजक',
|
insertHr: 'विभाजक',
|
||||||
insertCallout: 'कॉलआउट',
|
|
||||||
insertToggle: 'टॉगल ब्लॉक',
|
|
||||||
slashNoResults: 'कोई परिणाम नहीं',
|
slashNoResults: 'कोई परिणाम नहीं',
|
||||||
toggleSummaryPlaceholder: 'ब्लॉक शीर्षक…',
|
|
||||||
fmProperties: 'गुण',
|
fmProperties: 'गुण',
|
||||||
underline: 'रेखांकित',
|
|
||||||
highlight: 'हाइलाइट',
|
|
||||||
codeCopy: 'कॉपी',
|
codeCopy: 'कॉपी',
|
||||||
codeCopied: 'कॉपी हो गया',
|
codeCopied: 'कॉपी हो गया',
|
||||||
tableRowAbove: 'ऊपर पंक्ति जोड़ें',
|
tableRowAbove: 'ऊपर पंक्ति जोड़ें',
|
||||||
@@ -1819,11 +1853,15 @@ export const strings = {
|
|||||||
tableDeleteCol: 'स्तंभ हटाएँ',
|
tableDeleteCol: 'स्तंभ हटाएँ',
|
||||||
tableToggleHeaderRow: 'शीर्षक पंक्ति टॉगल करें',
|
tableToggleHeaderRow: 'शीर्षक पंक्ति टॉगल करें',
|
||||||
tableDeleteTable: 'तालिका हटाएँ',
|
tableDeleteTable: 'तालिका हटाएँ',
|
||||||
|
imageAlignLeft: 'बाएँ संरेखित करें',
|
||||||
|
imageAlignCenter: 'केंद्र में रखें',
|
||||||
|
imageAlignRight: 'दाएँ संरेखित करें',
|
||||||
blockAddBelow: 'नीचे ब्लॉक जोड़ें',
|
blockAddBelow: 'नीचे ब्लॉक जोड़ें',
|
||||||
blockDuplicate: 'डुप्लिकेट',
|
blockDuplicate: 'डुप्लिकेट',
|
||||||
blockMoveUp: 'ऊपर ले जाएँ',
|
blockMoveUp: 'ऊपर ले जाएँ',
|
||||||
blockMoveDown: 'नीचे ले जाएँ',
|
blockMoveDown: 'नीचे ले जाएँ',
|
||||||
blockDelete: 'हटाएँ',
|
blockDelete: 'हटाएँ',
|
||||||
|
blockGripHint: 'खींचकर स्थानांतरित करें, मेनू के लिए क्लिक करें',
|
||||||
aiUnknownError: 'AI अनुरोध विफल, पुनः प्रयास करें',
|
aiUnknownError: 'AI अनुरोध विफल, पुनः प्रयास करें',
|
||||||
aiTimeoutError: 'AI प्रतिक्रिया समय समाप्त',
|
aiTimeoutError: 'AI प्रतिक्रिया समय समाप्त',
|
||||||
aiCreditsExhausted: 'क्रेडिट समाप्त — genspark.ai पर रिचार्ज करें',
|
aiCreditsExhausted: 'क्रेडिट समाप्त — genspark.ai पर रिचार्ज करें',
|
||||||
@@ -1891,6 +1929,9 @@ export const strings = {
|
|||||||
styleCodeBlock: '程式碼區塊',
|
styleCodeBlock: '程式碼區塊',
|
||||||
undo: '復原',
|
undo: '復原',
|
||||||
redo: '重做',
|
redo: '重做',
|
||||||
|
save: '儲存 (⌘S)',
|
||||||
|
autoSave: '自動儲存',
|
||||||
|
autoSaveTip: '自動儲存(每 30 秒及視窗失去焦點時)',
|
||||||
bold: '粗體',
|
bold: '粗體',
|
||||||
italic: '斜體',
|
italic: '斜體',
|
||||||
strike: '刪除線',
|
strike: '刪除線',
|
||||||
@@ -1906,13 +1947,8 @@ export const strings = {
|
|||||||
insertTable: '插入表格',
|
insertTable: '插入表格',
|
||||||
insertImage: '插入圖片',
|
insertImage: '插入圖片',
|
||||||
insertHr: '分隔線',
|
insertHr: '分隔線',
|
||||||
insertCallout: '標註區塊',
|
|
||||||
insertToggle: '摺疊區塊',
|
|
||||||
slashNoResults: '無符合項目',
|
slashNoResults: '無符合項目',
|
||||||
toggleSummaryPlaceholder: '摺疊標題…',
|
|
||||||
fmProperties: '屬性',
|
fmProperties: '屬性',
|
||||||
underline: '底線',
|
|
||||||
highlight: '醒目提示',
|
|
||||||
codeCopy: '複製',
|
codeCopy: '複製',
|
||||||
codeCopied: '已複製',
|
codeCopied: '已複製',
|
||||||
tableRowAbove: '上方插入列',
|
tableRowAbove: '上方插入列',
|
||||||
@@ -1923,11 +1959,15 @@ export const strings = {
|
|||||||
tableDeleteCol: '刪除欄',
|
tableDeleteCol: '刪除欄',
|
||||||
tableToggleHeaderRow: '切換表頭列',
|
tableToggleHeaderRow: '切換表頭列',
|
||||||
tableDeleteTable: '刪除表格',
|
tableDeleteTable: '刪除表格',
|
||||||
|
imageAlignLeft: '靠左對齊',
|
||||||
|
imageAlignCenter: '置中',
|
||||||
|
imageAlignRight: '靠右對齊',
|
||||||
blockAddBelow: '在下方新增',
|
blockAddBelow: '在下方新增',
|
||||||
blockDuplicate: '複製區塊',
|
blockDuplicate: '複製區塊',
|
||||||
blockMoveUp: '上移',
|
blockMoveUp: '上移',
|
||||||
blockMoveDown: '下移',
|
blockMoveDown: '下移',
|
||||||
blockDelete: '刪除',
|
blockDelete: '刪除',
|
||||||
|
blockGripHint: '拖曳移動,點擊開啟選單',
|
||||||
aiUnknownError: 'AI 請求失敗,請重試',
|
aiUnknownError: 'AI 請求失敗,請重試',
|
||||||
aiTimeoutError: 'AI 回應逾時',
|
aiTimeoutError: 'AI 回應逾時',
|
||||||
aiCreditsExhausted: '點數不足,請前往 genspark.ai 儲值',
|
aiCreditsExhausted: '點數不足,請前往 genspark.ai 儲值',
|
||||||
|
|||||||
@@ -2,11 +2,23 @@ import { createRoot } from 'react-dom/client'
|
|||||||
import { htmlLang, type Lang } from '@genoffice/i18n'
|
import { htmlLang, type Lang } from '@genoffice/i18n'
|
||||||
import App from './App'
|
import App from './App'
|
||||||
import { LocaleProvider } from './i18n/locale'
|
import { LocaleProvider } from './i18n/locale'
|
||||||
|
import type { UiTheme } from '../shared/ipc'
|
||||||
|
import '@genoffice/ui/tokens.css'
|
||||||
import './styles.css'
|
import './styles.css'
|
||||||
|
|
||||||
|
function applyTheme(theme: UiTheme): void {
|
||||||
|
if (theme === 'system') document.documentElement.removeAttribute('data-theme')
|
||||||
|
else document.documentElement.setAttribute('data-theme', theme)
|
||||||
|
}
|
||||||
|
|
||||||
void (async () => {
|
void (async () => {
|
||||||
const lang: Lang = await window.markdownApi.getLanguage().catch(() => 'zh' as const)
|
const [lang, theme] = await Promise.all([
|
||||||
document.documentElement.lang = htmlLang(lang)
|
window.markdownApi.getLanguage().catch(() => 'zh' as const),
|
||||||
|
window.markdownApi.getTheme().catch(() => 'system' as const),
|
||||||
|
])
|
||||||
|
document.documentElement.lang = htmlLang(lang as Lang)
|
||||||
|
applyTheme(theme)
|
||||||
|
window.markdownApi.onThemeChanged(applyTheme)
|
||||||
createRoot(document.getElementById('root')!).render(
|
createRoot(document.getElementById('root')!).render(
|
||||||
<LocaleProvider initial={lang}>
|
<LocaleProvider initial={lang}>
|
||||||
<App />
|
<App />
|
||||||
|
|||||||
@@ -60,6 +60,51 @@ export function buildFrontmatterRaw(inner: string): string {
|
|||||||
return trimmed === '' ? '' : `${FENCE}\n${trimmed}\n${FENCE}\n\n`
|
return trimmed === '' ? '' : `${FENCE}\n${trimmed}\n${FENCE}\n\n`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One-way migration for legacy documents: earlier versions serialized callout
|
||||||
|
* and toggle blocks as Pandoc-style fenced divs (`:::callout {type="…"}` /
|
||||||
|
* `:::toggle {summary="…"}` / `:::`). Those extensions are gone — without this
|
||||||
|
* strip the fence lines would show up as literal `:::` text in the editor.
|
||||||
|
* The body content is kept; a toggle summary degrades to a bold paragraph.
|
||||||
|
*/
|
||||||
|
export function stripLegacyFencedDivs(body: string): string {
|
||||||
|
const lines = body.split('\n')
|
||||||
|
const out: string[] = []
|
||||||
|
let codeFence: string | null = null
|
||||||
|
let openDivs = 0
|
||||||
|
for (const line of lines) {
|
||||||
|
const fence = /^(`{3,}|~{3,})/.exec(line.trimStart())
|
||||||
|
if (codeFence) {
|
||||||
|
out.push(line)
|
||||||
|
if (fence && fence[1][0] === codeFence[0] && fence[1].length >= codeFence.length) {
|
||||||
|
codeFence = null
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (fence) {
|
||||||
|
codeFence = fence[1]
|
||||||
|
out.push(line)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// the attribute block is matched greedily to the last `}` on the line:
|
||||||
|
// the legacy serializer escaped only quotes, so a summary containing `}`
|
||||||
|
// (e.g. {summary="a } b"}) would not match a [^}]* pattern
|
||||||
|
const open = /^:::(callout|toggle)\s*(\{.*\})?\s*$/.exec(line)
|
||||||
|
if (open) {
|
||||||
|
openDivs++
|
||||||
|
const summary = open[2] ? /summary="((?:[^"\\]|\\.)*)"/.exec(open[2]) : null
|
||||||
|
if (summary?.[1]) out.push(`**${summary[1].replace(/\\"/g, '"')}**`, '')
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (openDivs > 0 && /^:::\s*$/.test(line)) {
|
||||||
|
openDivs--
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out.push(line)
|
||||||
|
}
|
||||||
|
return out.join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
/** Reassemble the full file text from the envelope and the (re)serialized body */
|
/** Reassemble the full file text from the envelope and the (re)serialized body */
|
||||||
export function serializeDocText(envelope: DocEnvelope, body: string): string {
|
export function serializeDocText(envelope: DocEnvelope, body: string): string {
|
||||||
let text = envelope.frontmatter + body
|
let text = envelope.frontmatter + body
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -19,8 +19,12 @@ export const MARKDOWN_CHANNELS = {
|
|||||||
exportPdf: 'markdown:export-pdf',
|
exportPdf: 'markdown:export-pdf',
|
||||||
getLanguage: 'app:get-language',
|
getLanguage: 'app:get-language',
|
||||||
languageChanged: 'app:language-changed',
|
languageChanged: 'app:language-changed',
|
||||||
|
getTheme: 'app:get-theme',
|
||||||
|
themeChanged: 'app:theme-changed',
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
|
export type UiTheme = 'light' | 'dark' | 'system'
|
||||||
|
|
||||||
export type SaveMode = 'save' | 'saveAs'
|
export type SaveMode = 'save' | 'saveAs'
|
||||||
|
|
||||||
export interface SaveMarkdownRequest {
|
export interface SaveMarkdownRequest {
|
||||||
@@ -122,6 +126,8 @@ export interface MarkdownApi {
|
|||||||
exportPdf(request: ExportPdfRequest): Promise<ExportResult>
|
exportPdf(request: ExportPdfRequest): Promise<ExportResult>
|
||||||
getLanguage(): Promise<Lang>
|
getLanguage(): Promise<Lang>
|
||||||
onLanguageChanged(handler: (lang: Lang) => void): () => void
|
onLanguageChanged(handler: (lang: Lang) => void): () => void
|
||||||
|
getTheme(): Promise<UiTheme>
|
||||||
|
onThemeChanged(handler: (theme: UiTheme) => void): () => void
|
||||||
getAiSettings(): Promise<AiSettings>
|
getAiSettings(): Promise<AiSettings>
|
||||||
aiStream(request: AiStreamRequest): Promise<void>
|
aiStream(request: AiStreamRequest): Promise<void>
|
||||||
aiStreamCancel(requestId: string): Promise<void>
|
aiStreamCancel(requestId: string): Promise<void>
|
||||||
|
|||||||
@@ -78,6 +78,36 @@ describe('insert_content', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('model output is sanitized to pure GFM', () => {
|
||||||
|
it('raw HTML in tool input degrades to plain text', () => {
|
||||||
|
const editor = createEditor()
|
||||||
|
executeTool(
|
||||||
|
editor,
|
||||||
|
call('insert_content', {
|
||||||
|
afterIndex: -1,
|
||||||
|
markdown: '<p style="text-align: center"><span style="color: red">note</span> here</p>',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
const md = editor.getMarkdown()
|
||||||
|
expect(md).toContain('note here')
|
||||||
|
expect(md).not.toContain('<')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('legacy ::: fenced divs in tool input are stripped, keeping the body', () => {
|
||||||
|
const editor = createEditor()
|
||||||
|
executeTool(
|
||||||
|
editor,
|
||||||
|
call('insert_content', {
|
||||||
|
afterIndex: -1,
|
||||||
|
markdown: ':::callout {type="warning"}\nBe careful.\n:::',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
const md = editor.getMarkdown()
|
||||||
|
expect(md).toContain('Be careful.')
|
||||||
|
expect(md).not.toContain(':::')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('replace_blocks', () => {
|
describe('replace_blocks', () => {
|
||||||
it('rewrites a block range', () => {
|
it('rewrites a block range', () => {
|
||||||
const editor = createEditor('# A\n\nold text\n\nkeep me')
|
const editor = createEditor('# A\n\nold text\n\nkeep me')
|
||||||
|
|||||||
@@ -1,5 +1,46 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import { parseDocText, serializeDocText } from '../src/renderer/markdown/docText'
|
import {
|
||||||
|
parseDocText,
|
||||||
|
serializeDocText,
|
||||||
|
stripLegacyFencedDivs,
|
||||||
|
} from '../src/renderer/markdown/docText'
|
||||||
|
|
||||||
|
describe('stripLegacyFencedDivs', () => {
|
||||||
|
it('removes callout fences and keeps the body', () => {
|
||||||
|
const out = stripLegacyFencedDivs(':::callout {type="warning"}\nBe careful.\n:::')
|
||||||
|
expect(out).toBe('Be careful.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('turns a toggle summary into a bold paragraph', () => {
|
||||||
|
const out = stripLegacyFencedDivs(':::toggle {summary="More info"}\nHidden body.\n:::')
|
||||||
|
expect(out).toBe('**More info**\n\nHidden body.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('handles a toggle summary containing a closing brace', () => {
|
||||||
|
const out = stripLegacyFencedDivs(':::toggle {summary="a } b"}\nBody.\n:::')
|
||||||
|
expect(out).toBe('**a } b**\n\nBody.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('handles nested legacy divs', () => {
|
||||||
|
const out = stripLegacyFencedDivs(':::callout\n:::toggle {summary="S"}\nbody\n:::\n:::')
|
||||||
|
expect(out).toBe('**S**\n\nbody')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('leaves ::: lines inside fenced code blocks alone', () => {
|
||||||
|
const md = '```\n:::callout\n:::\n```'
|
||||||
|
expect(stripLegacyFencedDivs(md)).toBe(md)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('leaves unrelated ::: text alone', () => {
|
||||||
|
const md = 'a line with ::: in the middle\n:::\nplain'
|
||||||
|
expect(stripLegacyFencedDivs(md)).toBe(md)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('passes plain documents through unchanged', () => {
|
||||||
|
const md = '# Title\n\nHello **world**\n\n- item'
|
||||||
|
expect(stripLegacyFencedDivs(md)).toBe(md)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('parseDocText', () => {
|
describe('parseDocText', () => {
|
||||||
it('plain document without frontmatter', () => {
|
it('plain document without frontmatter', () => {
|
||||||
|
|||||||
@@ -92,18 +92,6 @@ describe('docx export', () => {
|
|||||||
expect(code?.runs?.[0]?.text).toContain('const b = 2')
|
expect(code?.runs?.[0]?.text).toContain('const b = 2')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('callout and toggle degrade to styled paragraphs, keeping all text', async () => {
|
|
||||||
const md =
|
|
||||||
':::callout {type="warning"}\nBe careful.\n:::\n\n:::toggle {summary="More"}\nHidden.\n:::'
|
|
||||||
const parsed = await exportAndParse(md)
|
|
||||||
const texts = parsed.blocks.map((b) => (b.runs ?? []).map((r) => r.text).join(''))
|
|
||||||
expect(texts).toContain('Be careful.')
|
|
||||||
expect(texts).toContain('More')
|
|
||||||
expect(texts).toContain('Hidden.')
|
|
||||||
const summary = parsed.blocks.find((b) => (b.runs ?? [])[0]?.text === 'More')
|
|
||||||
expect(summary?.runs?.[0]?.bold).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('links survive as hyperlink runs', async () => {
|
it('links survive as hyperlink runs', async () => {
|
||||||
const parsed = await exportAndParse('Visit [Genspark](https://genspark.ai) now.')
|
const parsed = await exportAndParse('Visit [Genspark](https://genspark.ai) now.')
|
||||||
const para = parsed.blocks.find((b) => b.type === 'paragraph')
|
const para = parsed.blocks.find((b) => b.type === 'paragraph')
|
||||||
@@ -127,16 +115,17 @@ describe('docx export', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('inline mark coverage in docx export', () => {
|
describe('legacy HTML content degrades to plain runs in docx export', () => {
|
||||||
it('underline and highlight survive as run properties', async () => {
|
it('legacy styled HTML keeps its text without the styling', async () => {
|
||||||
const editor = createEditor('plain')
|
const parsed = await exportAndParse(
|
||||||
editor.commands.setContent('some ==marked== and <u>underlined</u> text', {
|
'<p style="text-align: center"><span style="color: #e11d48">red</span> mid</p>\n\n' +
|
||||||
contentType: 'markdown',
|
'plain <span style="background-color: #ffff00">lit</span> end',
|
||||||
})
|
)
|
||||||
const bytes = await exportDocxBytes(editor.getJSON(), noImages)
|
const texts = parsed.blocks.map((b) => (b.runs ?? []).map((r) => r.text).join(''))
|
||||||
const parsed = await parseDocx(bytes)
|
expect(texts.some((t) => t.includes('red') && t.includes('mid'))).toBe(true)
|
||||||
|
expect(texts.some((t) => t.includes('lit'))).toBe(true)
|
||||||
const runs = parsed.blocks.flatMap((b) => b.runs ?? [])
|
const runs = parsed.blocks.flatMap((b) => b.runs ?? [])
|
||||||
expect(runs.find((r) => r.highlight)?.text).toBe('marked')
|
expect(runs.every((r) => !r.color && !r.highlight)).toBe(true)
|
||||||
expect(runs.find((r) => r.underline)?.text).toBe('underlined')
|
expect(parsed.blocks.every((b) => b.format?.align !== 'center')).toBe(true)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -36,41 +36,9 @@ function roundTrip(editor: Editor, md: string): { out: string; stable: boolean }
|
|||||||
return { out, stable: JSON.stringify(first) === JSON.stringify(second) }
|
return { out, stable: JSON.stringify(first) === JSON.stringify(second) }
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('markdown round-trip for M2 nodes', () => {
|
describe('markdown round-trip for GFM nodes', () => {
|
||||||
const editor = createEditor()
|
const editor = createEditor()
|
||||||
|
|
||||||
it('callout with a non-default type', () => {
|
|
||||||
const md = ':::callout {type="warning"}\nBe careful.\n:::'
|
|
||||||
const { out, stable } = roundTrip(editor, md)
|
|
||||||
expect(out).toContain(':::callout')
|
|
||||||
expect(out).toContain('type="warning"')
|
|
||||||
expect(out).toContain('Be careful.')
|
|
||||||
expect(stable).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('callout with the default type omits the attribute', () => {
|
|
||||||
const { out, stable } = roundTrip(editor, ':::callout\nNote text.\n:::')
|
|
||||||
expect(out).toContain(':::callout')
|
|
||||||
expect(out).not.toContain('type=')
|
|
||||||
expect(stable).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('toggle keeps its summary and drops editor-only open state', () => {
|
|
||||||
const md = ':::toggle {summary="More info"}\nHidden body.\n:::'
|
|
||||||
const { out, stable } = roundTrip(editor, md)
|
|
||||||
expect(out).toContain(':::toggle')
|
|
||||||
expect(out).toContain('summary="More info"')
|
|
||||||
expect(out).not.toContain('open=')
|
|
||||||
expect(stable).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('callout containing a list', () => {
|
|
||||||
const md = ':::callout {type="tip"}\n- one\n- two\n:::'
|
|
||||||
const { out, stable } = roundTrip(editor, md)
|
|
||||||
expect(out).toContain('- one')
|
|
||||||
expect(stable).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('task list', () => {
|
it('task list', () => {
|
||||||
const md = '- [ ] open item\n- [x] done item'
|
const md = '- [ ] open item\n- [x] done item'
|
||||||
const { out, stable } = roundTrip(editor, md)
|
const { out, stable } = roundTrip(editor, md)
|
||||||
@@ -95,49 +63,92 @@ describe('markdown round-trip for M2 nodes', () => {
|
|||||||
expect(stable).toBe(true)
|
expect(stable).toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('plain constructs still round-trip alongside the custom nodes', () => {
|
it('plain constructs round-trip', () => {
|
||||||
const md = '# Title\n\n> quoted\n\n```js\ncode()\n```\n\n---'
|
const md = '# Title\n\n> quoted\n\n```js\ncode()\n```\n\n---'
|
||||||
const { out, stable } = roundTrip(editor, md)
|
const { out, stable } = roundTrip(editor, md)
|
||||||
expect(out).toContain('# Title')
|
expect(out).toContain('# Title')
|
||||||
expect(out).toContain('```js')
|
expect(out).toContain('```js')
|
||||||
expect(stable).toBe(true)
|
expect(stable).toBe(true)
|
||||||
})
|
})
|
||||||
})
|
|
||||||
|
|
||||||
describe('highlight and code block language', () => {
|
|
||||||
const editor = createEditor()
|
|
||||||
|
|
||||||
it('==highlight== round-trips', () => {
|
|
||||||
const { out, stable } = roundTrip(editor, 'some ==marked text== here')
|
|
||||||
expect(out).toContain('==marked text==')
|
|
||||||
expect(stable).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('code block language survives the round-trip', () => {
|
it('code block language survives the round-trip', () => {
|
||||||
const { out, stable } = roundTrip(editor, '```python\nprint(1)\n```')
|
const { out, stable } = roundTrip(editor, '```python\nprint(1)\n```')
|
||||||
expect(out).toContain('```python')
|
expect(out).toContain('```python')
|
||||||
expect(stable).toBe(true)
|
expect(stable).toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('nested lists serialize with 4-space indents (strict-CommonMark safe)', () => {
|
||||||
|
// 2-space indents would be below the ordered item's content column ("1. "
|
||||||
|
// = 3 chars), so GitHub would flatten the sub-list when re-parsing the file
|
||||||
|
const ordered = roundTrip(editor, '1. one\n - sub\n2. two')
|
||||||
|
expect(ordered.out).toContain('\n - sub')
|
||||||
|
expect(ordered.stable).toBe(true)
|
||||||
|
|
||||||
|
const bullets = roundTrip(editor, '- a\n - b\n - c')
|
||||||
|
expect(bullets.out).toContain('\n - b')
|
||||||
|
expect(bullets.out).toContain('\n - c')
|
||||||
|
expect(bullets.stable).toBe(true)
|
||||||
|
|
||||||
|
// files saved by earlier versions used 2-space indents — still parsed as nested
|
||||||
|
const legacy = roundTrip(editor, '- a\n - b')
|
||||||
|
expect(legacy.out).toContain('\n - b')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('underline (ships inside StarterKit v3)', () => {
|
describe('only pure markdown syntax is ever produced', () => {
|
||||||
const editor = createEditor()
|
const editor = createEditor()
|
||||||
|
|
||||||
it('toggleUnderline applies the mark', () => {
|
it('underline and highlight commands are gone', () => {
|
||||||
editor.commands.setContent('word', { contentType: 'markdown' })
|
// both would serialize as non-GFM syntax (`++u++` / `==mark==`)
|
||||||
editor.commands.selectAll()
|
expect('toggleUnderline' in editor.commands).toBe(false)
|
||||||
expect(editor.commands.toggleUnderline()).toBe(true)
|
expect('toggleHighlight' in editor.commands).toBe(false)
|
||||||
expect(editor.isActive('underline')).toBe(true)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('an underline applied in the editor survives serialize → reparse', () => {
|
it('alignment and line-height commands are gone', () => {
|
||||||
editor.commands.setContent('word', { contentType: 'markdown' })
|
expect('setTextAlign' in editor.commands).toBe(false)
|
||||||
editor.commands.selectAll()
|
expect('setLineHeight' in editor.commands).toBe(false)
|
||||||
editor.commands.toggleUnderline()
|
})
|
||||||
const md = editor.getMarkdown()
|
|
||||||
expect(md).toContain('word')
|
it('callout and toggle nodes are gone from the schema', () => {
|
||||||
editor.commands.setContent(md, { contentType: 'markdown' })
|
expect(editor.schema.nodes.callout).toBeUndefined()
|
||||||
editor.commands.selectAll()
|
expect(editor.schema.nodes.toggle).toBeUndefined()
|
||||||
expect(editor.isActive('underline')).toBe(true)
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('legacy HTML content degrades to plain markdown, keeping the text', () => {
|
||||||
|
const editor = createEditor()
|
||||||
|
|
||||||
|
function parseAndSerialize(md: string): string {
|
||||||
|
const manager = editor.markdown!
|
||||||
|
return manager.serialize(manager.parse(md))
|
||||||
|
}
|
||||||
|
|
||||||
|
it('a styled span drops the styling but keeps the text', () => {
|
||||||
|
const out = parseAndSerialize('a <span style="color: #ff0000">red text</span> b')
|
||||||
|
expect(out).not.toContain('<span')
|
||||||
|
expect(out).toContain('red text')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('an aligned paragraph becomes a plain paragraph with marks intact', () => {
|
||||||
|
const out = parseAndSerialize(
|
||||||
|
'<p style="text-align: center">centered <strong>text</strong></p>',
|
||||||
|
)
|
||||||
|
expect(out).not.toContain('<p')
|
||||||
|
expect(out).toContain('centered **text**')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('an aligned heading becomes a plain heading', () => {
|
||||||
|
const out = parseAndSerialize('<h2 style="text-align: right">title</h2>')
|
||||||
|
expect(out).toBe('## title')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a resized image goes back to pure image syntax', () => {
|
||||||
|
const out = parseAndSerialize('<img src="assets/d.png" alt="d" width="300" align="center">')
|
||||||
|
expect(out).toBe('')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('u and mark tags drop the tag but keep the text', () => {
|
||||||
|
const out = parseAndSerialize('a <u>underlined</u> and <mark>marked</mark> b')
|
||||||
|
expect(out).toBe('a underlined and marked b')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { afterEach, describe, expect, it } from 'vitest'
|
import { afterEach, describe, expect, it } from 'vitest'
|
||||||
import { buildSlashItems, filterSlashItems } from '../src/renderer/editor/slashCommand'
|
import { buildSlashItems, filterSlashItems } from '../src/renderer/editor/slashCommand'
|
||||||
import { resolveImageSrc } from '../src/renderer/editor/localImage'
|
import { resolveImageSrc, unresolveImageSrc } from '../src/renderer/editor/localImage'
|
||||||
|
|
||||||
// Undestroyed views leave DOMObserver flush timers that fire after jsdom teardown
|
// Undestroyed views leave DOMObserver flush timers that fire after jsdom teardown
|
||||||
// ("document is not defined" unhandled error) — destroy every editor we create.
|
// ("document is not defined" unhandled error) — destroy every editor we create.
|
||||||
@@ -88,15 +88,14 @@ describe('slash block commands inside a list (lift-first behavior)', () => {
|
|||||||
return found
|
return found
|
||||||
}
|
}
|
||||||
|
|
||||||
it('callout from a list item lifts out of the list instead of silently failing', async () => {
|
it('code block from a list item lifts out of the list instead of silently failing', async () => {
|
||||||
const editor = await editorWith('- first\n- second x/')
|
const editor = await editorWith('- first\n- second x/')
|
||||||
const caret = caretAfter(editor, 'x/')
|
const caret = caretAfter(editor, 'x/')
|
||||||
editor.commands.setTextSelection(caret)
|
editor.commands.setTextSelection(caret)
|
||||||
const callout = buildSlashItems().find((i) => i.id === 'callout')!
|
const code = buildSlashItems().find((i) => i.id === 'code')!
|
||||||
callout.run(editor, { from: caret - 1, to: caret })
|
code.run(editor, { from: caret - 1, to: caret })
|
||||||
expect(editor.isActive('callout')).toBe(true)
|
expect(editor.isActive('codeBlock')).toBe(true)
|
||||||
const md = editor.getMarkdown()
|
const md = editor.getMarkdown()
|
||||||
expect(md).toContain(':::callout')
|
|
||||||
expect(md).toContain('- first')
|
expect(md).toContain('- first')
|
||||||
expect(md).not.toContain('- second x')
|
expect(md).not.toContain('- second x')
|
||||||
})
|
})
|
||||||
@@ -111,13 +110,13 @@ describe('slash block commands inside a list (lift-first behavior)', () => {
|
|||||||
expect(editor.getMarkdown()).toContain('## todo x')
|
expect(editor.getMarkdown()).toContain('## todo x')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('toggle from a nested list item escapes every level', async () => {
|
it('heading from a nested list item escapes every level', async () => {
|
||||||
const editor = await editorWith('- outer\n - inner x/')
|
const editor = await editorWith('- outer\n - inner x/')
|
||||||
const caret = caretAfter(editor, 'x/')
|
const caret = caretAfter(editor, 'x/')
|
||||||
editor.commands.setTextSelection(caret)
|
editor.commands.setTextSelection(caret)
|
||||||
const toggle = buildSlashItems().find((i) => i.id === 'toggle')!
|
const h3 = buildSlashItems().find((i) => i.id === 'h3')!
|
||||||
toggle.run(editor, { from: caret - 1, to: caret })
|
h3.run(editor, { from: caret - 1, to: caret })
|
||||||
expect(editor.isActive('toggle')).toBe(true)
|
expect(editor.isActive('heading', { level: 3 })).toBe(true)
|
||||||
expect(editor.isActive('listItem')).toBe(false)
|
expect(editor.isActive('listItem')).toBe(false)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -181,6 +180,32 @@ describe('block keymap commands (secondbrain parity)', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('unresolveImageSrc', () => {
|
||||||
|
it('leaves non md-asset URLs untouched', () => {
|
||||||
|
expect(unresolveImageSrc('https://x.test/a.png', '/docs')).toBe('https://x.test/a.png')
|
||||||
|
expect(unresolveImageSrc('assets/p.png', '/docs')).toBe('assets/p.png')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('maps a resolved URL back to the authored relative path', () => {
|
||||||
|
const url = resolveImageSrc('assets/p.png', '/Users/me/notes')
|
||||||
|
expect(unresolveImageSrc(url, '/Users/me/notes')).toBe('assets/p.png')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('decodes encoded segments', () => {
|
||||||
|
const url = resolveImageSrc('assets/图 1.png', '/n')
|
||||||
|
expect(unresolveImageSrc(url, '/n')).toBe('assets/图 1.png')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps an absolute path when it lives outside the base dir', () => {
|
||||||
|
expect(unresolveImageSrc('md-asset:///tmp/pic.png', '/docs')).toBe('/tmp/pic.png')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('round-trips Windows base dirs', () => {
|
||||||
|
const url = resolveImageSrc('assets/p.png', 'C:\\notes')
|
||||||
|
expect(unresolveImageSrc(url, 'C:\\notes')).toBe('assets/p.png')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('resolveImageSrc on Windows paths', () => {
|
describe('resolveImageSrc on Windows paths', () => {
|
||||||
it('keeps the drive colon unencoded in md-asset URLs', () => {
|
it('keeps the drive colon unencoded in md-asset URLs', () => {
|
||||||
expect(resolveImageSrc('C:\\Users\\me\\pic.png', null)).toBe('md-asset:///C:/Users/me/pic.png')
|
expect(resolveImageSrc('C:\\Users\\me\\pic.png', null)).toBe('md-asset:///C:/Users/me/pic.png')
|
||||||
|
|||||||
@@ -14,8 +14,10 @@
|
|||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@embedpdf/pdfium": "^2.15.0",
|
||||||
"@genoffice/agent-core": "*",
|
"@genoffice/agent-core": "*",
|
||||||
"@genoffice/ai-provider": "*",
|
"@genoffice/ai-provider": "*",
|
||||||
|
"@genoffice/ai-search": "*",
|
||||||
"@genoffice/electron-utils": "*",
|
"@genoffice/electron-utils": "*",
|
||||||
"@genoffice/i18n": "*",
|
"@genoffice/i18n": "*",
|
||||||
"@genoffice/ui": "*",
|
"@genoffice/ui": "*",
|
||||||
@@ -24,6 +26,7 @@
|
|||||||
"@vitejs/plugin-react": "^5.0.4",
|
"@vitejs/plugin-react": "^5.0.4",
|
||||||
"electron": "^43.3.0",
|
"electron": "^43.3.0",
|
||||||
"electron-vite": "^5.0.0",
|
"electron-vite": "^5.0.0",
|
||||||
|
"harfbuzzjs": "^0.10.3",
|
||||||
"jsdom": "^28.0.0",
|
"jsdom": "^28.0.0",
|
||||||
"pdf-lib": "^1.17.1",
|
"pdf-lib": "^1.17.1",
|
||||||
"pdfjs-dist": "^6.2.108",
|
"pdfjs-dist": "^6.2.108",
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
/** Minimal sfnt cmap reader: can the face map every char of a string?
|
||||||
|
Formats 4 and 12 only — which covers every face in EDIT_FONT_PATHS. */
|
||||||
|
|
||||||
|
const u16 = (b: Buffer, o: number) => b.readUInt16BE(o)
|
||||||
|
const u32 = (b: Buffer, o: number) => b.readUInt32BE(o)
|
||||||
|
|
||||||
|
function tableOffset(font: Buffer, tag: string): number {
|
||||||
|
const numTables = u16(font, 4)
|
||||||
|
for (let i = 0; i < numTables; i++) {
|
||||||
|
const rec = 12 + i * 16
|
||||||
|
if (font.toString('latin1', rec, rec + 4) === tag) return u32(font, rec + 8)
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Subtable {
|
||||||
|
offset: number
|
||||||
|
format: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function cmapSubtable(font: Buffer): Subtable | null {
|
||||||
|
const cmap = tableOffset(font, 'cmap')
|
||||||
|
if (cmap < 0) return null
|
||||||
|
const n = u16(font, cmap + 2)
|
||||||
|
let best: Subtable | null = null
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const rec = cmap + 4 + i * 8
|
||||||
|
const platform = u16(font, rec)
|
||||||
|
const encoding = u16(font, rec + 2)
|
||||||
|
if (platform !== 0 && !(platform === 3 && (encoding === 1 || encoding === 10))) continue
|
||||||
|
const offset = cmap + u32(font, rec + 4)
|
||||||
|
const format = u16(font, offset)
|
||||||
|
if (format === 12) return { offset, format }
|
||||||
|
if (format === 4 && !best) best = { offset, format }
|
||||||
|
}
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Glyph id for a codepoint, 0 = unmapped (.notdef) */
|
||||||
|
function glyphId(font: Buffer, sub: Subtable, cp: number): number {
|
||||||
|
const o = sub.offset
|
||||||
|
if (sub.format === 12) {
|
||||||
|
const groups = u32(font, o + 12)
|
||||||
|
for (let i = 0; i < groups; i++) {
|
||||||
|
const g = o + 16 + i * 12
|
||||||
|
if (cp < u32(font, g)) return 0 // groups are sorted ascending
|
||||||
|
if (cp <= u32(font, g + 4)) return u32(font, g + 8) + (cp - u32(font, g))
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if (cp > 0xffff) return 0
|
||||||
|
const segX2 = u16(font, o + 6)
|
||||||
|
const ends = o + 14
|
||||||
|
const starts = ends + segX2 + 2
|
||||||
|
const deltas = starts + segX2
|
||||||
|
const rangeOffs = deltas + segX2
|
||||||
|
for (let s = 0; s < segX2; s += 2) {
|
||||||
|
if (cp > u16(font, ends + s)) continue
|
||||||
|
if (cp < u16(font, starts + s)) return 0
|
||||||
|
const ro = u16(font, rangeOffs + s)
|
||||||
|
if (ro === 0) return (cp + font.readInt16BE(deltas + s)) & 0xffff
|
||||||
|
const gi = u16(font, rangeOffs + s + ro + (cp - u16(font, starts + s)) * 2)
|
||||||
|
return gi === 0 ? 0 : (gi + font.readInt16BE(deltas + s)) & 0xffff
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasGlyph = (font: Buffer, sub: Subtable, cp: number): boolean => glyphId(font, sub, cp) !== 0
|
||||||
|
|
||||||
|
/** True when the font maps every drawn char of text (unparseable font = false).
|
||||||
|
Only line breaks are excluded: Unicode spaces (NBSP, U+3000, …) are drawn like any
|
||||||
|
glyph and must be mapped — \s would silently exempt them. */
|
||||||
|
export function fontCoversText(font: Buffer, text: string): boolean {
|
||||||
|
const chars = [...text.replace(/[\r\n]/g, '')]
|
||||||
|
if (chars.length === 0) return true
|
||||||
|
try {
|
||||||
|
const sub = cmapSubtable(font)
|
||||||
|
return sub !== null && chars.every((c) => hasGlyph(font, sub, c.codePointAt(0)!))
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
/**
|
||||||
|
* Locate an installed font matching a PDF font's PostScript name (nameID 6) or family
|
||||||
|
* (nameID 1/16), for text-edit rebuilds that keep the original typeface. The index is
|
||||||
|
* built from targeted fd reads of each face's name table only — CJK collections run
|
||||||
|
* 100MB+ (PingFang.ttc ~180MB), so whole-file reads at scan time are not an option.
|
||||||
|
*/
|
||||||
|
import { closeSync, openSync, readFileSync, readdirSync, readSync, statSync } from 'node:fs'
|
||||||
|
import type { Dirent } from 'node:fs'
|
||||||
|
import { homedir } from 'node:os'
|
||||||
|
import { join } from 'node:path'
|
||||||
|
|
||||||
|
const norm = (s: string) =>
|
||||||
|
s
|
||||||
|
.normalize('NFKC')
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[\s\-_]/g, '')
|
||||||
|
|
||||||
|
function fontDirs(): string[] {
|
||||||
|
switch (process.platform) {
|
||||||
|
case 'darwin':
|
||||||
|
return [
|
||||||
|
'/System/Library/Fonts',
|
||||||
|
'/System/Library/Fonts/Supplemental',
|
||||||
|
'/Library/Fonts',
|
||||||
|
join(homedir(), 'Library/Fonts'),
|
||||||
|
// On-demand system font assets: PingFang and other CJK faces live here on
|
||||||
|
// recent macOS ( <hash>.asset/AssetData/*.ttc ), not under /System/Library/Fonts
|
||||||
|
'/System/Library/AssetsV2/com_apple_MobileAsset_Font7',
|
||||||
|
'/System/Library/AssetsV2/com_apple_MobileAsset_Font6',
|
||||||
|
]
|
||||||
|
case 'win32':
|
||||||
|
return ['C:\\Windows\\Fonts', join(homedir(), 'AppData/Local/Microsoft/Windows/Fonts')]
|
||||||
|
default:
|
||||||
|
return ['/usr/share/fonts', '/usr/local/share/fonts', join(homedir(), '.fonts')]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const TTC_TAG = 0x74746366 // 'ttcf'
|
||||||
|
const OTTO_TAG = 0x4f54544f // CFF-flavored sfnt (e.g. PingFang on recent macOS)
|
||||||
|
const SFNT_FLAVORS = new Set([0x00010000, 0x74727565, OTTO_TAG]) // 1.0 / 'true' / 'OTTO'
|
||||||
|
|
||||||
|
/** Picks FPDFText_LoadFont's font_type: glyf faces embed as FontFile2 (TRUETYPE),
|
||||||
|
CFF faces as FontFile3 (TYPE1) */
|
||||||
|
export const isTruetype = (b: Buffer): boolean => b.length >= 4 && b.readUInt32BE(0) !== OTTO_TAG
|
||||||
|
|
||||||
|
function readAt(fd: number, pos: number, len: number): Buffer {
|
||||||
|
const buf = Buffer.alloc(len)
|
||||||
|
if (readSync(fd, buf, 0, len, pos) !== len) throw new Error('short read')
|
||||||
|
return buf
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FaceNames {
|
||||||
|
ps: string[]
|
||||||
|
families: string[]
|
||||||
|
subfamilies: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseNames(buf: Buffer): FaceNames {
|
||||||
|
const out: FaceNames = { ps: [], families: [], subfamilies: [] }
|
||||||
|
const count = buf.readUInt16BE(2)
|
||||||
|
const strBase = buf.readUInt16BE(4)
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
const r = 6 + 12 * i
|
||||||
|
if (r + 12 > buf.length) break
|
||||||
|
const platform = buf.readUInt16BE(r)
|
||||||
|
const encoding = buf.readUInt16BE(r + 2)
|
||||||
|
const nameId = buf.readUInt16BE(r + 6)
|
||||||
|
const list =
|
||||||
|
nameId === 6
|
||||||
|
? out.ps
|
||||||
|
: nameId === 1 || nameId === 16
|
||||||
|
? out.families
|
||||||
|
: nameId === 2 || nameId === 17
|
||||||
|
? out.subfamilies
|
||||||
|
: null
|
||||||
|
if (!list) continue
|
||||||
|
const len = buf.readUInt16BE(r + 8)
|
||||||
|
const off = strBase + buf.readUInt16BE(r + 10)
|
||||||
|
if (off + len > buf.length) continue
|
||||||
|
let s: string
|
||||||
|
if (platform === 0 || platform === 3) {
|
||||||
|
s = Buffer.from(buf.subarray(off, off + len))
|
||||||
|
.swap16()
|
||||||
|
.toString('utf16le')
|
||||||
|
} else if (platform === 1 && encoding === 0) {
|
||||||
|
s = buf.toString('latin1', off, off + len)
|
||||||
|
} else {
|
||||||
|
continue // Mac-platform legacy CJK codepages: not decodable here
|
||||||
|
}
|
||||||
|
if (s && !list.includes(s)) list.push(s)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Names of the face whose offset table starts at `offset`; null for non-sfnt faces */
|
||||||
|
function readFaceNames(fd: number, offset: number): FaceNames | null {
|
||||||
|
const head = readAt(fd, offset, 12)
|
||||||
|
if (!SFNT_FLAVORS.has(head.readUInt32BE(0))) return null
|
||||||
|
const numTables = head.readUInt16BE(4)
|
||||||
|
if (numTables === 0 || numTables > 64) return null
|
||||||
|
const dir = readAt(fd, offset + 12, 16 * numTables)
|
||||||
|
for (let t = 0; t < numTables; t++) {
|
||||||
|
if (dir.toString('latin1', 16 * t, 16 * t + 4) !== 'name') continue
|
||||||
|
const tblOff = dir.readUInt32BE(16 * t + 8)
|
||||||
|
const tblLen = dir.readUInt32BE(16 * t + 12)
|
||||||
|
if (tblLen < 6 || tblLen > 1 << 20) return null
|
||||||
|
return parseNames(readAt(fd, tblOff, tblLen))
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FaceRef {
|
||||||
|
path: string
|
||||||
|
/** Position of the face's offset table within the file (0 unless .ttc) */
|
||||||
|
offset: number
|
||||||
|
/** Normalized family + subfamily text, for style ranking on family matches */
|
||||||
|
style: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FontIndex {
|
||||||
|
byPs: Map<string, FaceRef>
|
||||||
|
byFamily: Map<string, FaceRef[]>
|
||||||
|
}
|
||||||
|
|
||||||
|
function* fontFiles(dir: string, depth: number): Generator<string> {
|
||||||
|
let entries: Dirent[]
|
||||||
|
try {
|
||||||
|
entries = readdirSync(dir, { withFileTypes: true })
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for (const e of entries) {
|
||||||
|
const full = join(dir, e.name)
|
||||||
|
let isDir = e.isDirectory()
|
||||||
|
let isFile = e.isFile()
|
||||||
|
if (e.isSymbolicLink()) {
|
||||||
|
try {
|
||||||
|
const st = statSync(full)
|
||||||
|
isDir = st.isDirectory()
|
||||||
|
isFile = st.isFile()
|
||||||
|
} catch {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (isDir && depth > 0) yield* fontFiles(full, depth - 1)
|
||||||
|
else if (isFile && /\.(ttf|otf|ttc|otc)$/i.test(e.name)) yield full
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function indexFile(path: string, index: FontIndex): void {
|
||||||
|
let fd: number
|
||||||
|
try {
|
||||||
|
fd = openSync(path, 'r')
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const offsets =
|
||||||
|
readAt(fd, 0, 4).readUInt32BE(0) === TTC_TAG
|
||||||
|
? ((): number[] => {
|
||||||
|
const n = readAt(fd, 8, 4).readUInt32BE(0)
|
||||||
|
if (n > 64) return []
|
||||||
|
const o = readAt(fd, 12, 4 * n)
|
||||||
|
return Array.from({ length: n }, (_, i) => o.readUInt32BE(4 * i))
|
||||||
|
})()
|
||||||
|
: [0]
|
||||||
|
for (const offset of offsets) {
|
||||||
|
let names: FaceNames | null
|
||||||
|
try {
|
||||||
|
names = readFaceNames(fd, offset)
|
||||||
|
} catch {
|
||||||
|
names = null
|
||||||
|
}
|
||||||
|
if (!names) continue
|
||||||
|
const face: FaceRef = {
|
||||||
|
path,
|
||||||
|
offset,
|
||||||
|
style: norm([...names.families, ...names.subfamilies].join(' ')),
|
||||||
|
}
|
||||||
|
for (const p of names.ps) if (!index.byPs.has(norm(p))) index.byPs.set(norm(p), face)
|
||||||
|
for (const f of names.families) {
|
||||||
|
const k = norm(f)
|
||||||
|
index.byFamily.set(k, [...(index.byFamily.get(k) ?? []), face])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* unreadable or malformed file: skip */
|
||||||
|
} finally {
|
||||||
|
closeSync(fd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let index: FontIndex | null = null
|
||||||
|
|
||||||
|
function buildIndex(): FontIndex {
|
||||||
|
const built: FontIndex = { byPs: new Map(), byFamily: new Map() }
|
||||||
|
for (const dir of fontDirs()) for (const path of fontFiles(dir, 2)) indexFile(path, built)
|
||||||
|
return built
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Extract a single face from a ttc into a standalone sfnt (rewrite the table directory,
|
||||||
|
copy table data; passthrough for plain ttf) */
|
||||||
|
function extractFace(buf: Buffer, offset: number): Buffer {
|
||||||
|
if (buf.readUInt32BE(0) !== TTC_TAG) return buf
|
||||||
|
const numTables = buf.readUInt16BE(offset + 4)
|
||||||
|
let total = 12 + 16 * numTables
|
||||||
|
const entries: Array<{ dirPos: number; tOff: number; tLen: number; newOff: number }> = []
|
||||||
|
for (let t = 0; t < numTables; t++) {
|
||||||
|
const e = offset + 12 + 16 * t
|
||||||
|
const tLen = buf.readUInt32BE(e + 12)
|
||||||
|
entries.push({ dirPos: e, tOff: buf.readUInt32BE(e + 8), tLen, newOff: total })
|
||||||
|
total += (tLen + 3) & ~3
|
||||||
|
}
|
||||||
|
const out = Buffer.alloc(total)
|
||||||
|
buf.copy(out, 0, offset, offset + 12)
|
||||||
|
for (let t = 0; t < numTables; t++) {
|
||||||
|
const e = entries[t]!
|
||||||
|
buf.copy(out, 12 + 16 * t, e.dirPos, e.dirPos + 8)
|
||||||
|
out.writeUInt32BE(e.newOff, 12 + 16 * t + 8)
|
||||||
|
out.writeUInt32BE(e.tLen, 12 + 16 * t + 12)
|
||||||
|
buf.copy(out, e.newOff, e.tOff, e.tOff + e.tLen)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
const faceCache = new Map<string, Buffer>()
|
||||||
|
|
||||||
|
// "bolditalic" deliberately has no atomic alternative: a BoldItalic face must yield
|
||||||
|
// ['bold', 'italic'] so it can score against each want separately (a keep-original
|
||||||
|
// bold toggle on an italic run wants both tokens; an atomic token would score zero).
|
||||||
|
// "oblique" folds into "italic": families like Helvetica name their slanted faces
|
||||||
|
// Oblique, and an italic want must still count them as hits.
|
||||||
|
const styleTokens = (ps: string): string[] =>
|
||||||
|
(
|
||||||
|
norm(ps).match(
|
||||||
|
/semibold|extrabold|bold|italic|oblique|light|thin|medium|heavy|black|regular|w\d/g,
|
||||||
|
) ?? []
|
||||||
|
).map((t) => (t === 'oblique' ? 'italic' : t))
|
||||||
|
|
||||||
|
const REGULARISH = ['regular', 'medium', 'w3', 'w4']
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Standalone sfnt bytes of the installed font best matching (psName, family):
|
||||||
|
* exact PostScript name first, then family with the PS name's style tokens
|
||||||
|
* (Regular preferred when there are none). Null when nothing matches.
|
||||||
|
*/
|
||||||
|
export function findSystemFont(psName: string, family: string): Buffer | null {
|
||||||
|
index ??= buildIndex()
|
||||||
|
let face = psName ? index.byPs.get(norm(psName)) : undefined
|
||||||
|
if (!face && family) {
|
||||||
|
const candidates = index.byFamily.get(norm(family))
|
||||||
|
if (candidates?.length) {
|
||||||
|
const want = styleTokens(psName)
|
||||||
|
// Token-level comparison, not substring: a wanted "bold" must not also credit
|
||||||
|
// Semibold/ExtraBold faces (the tokenizer consumes the longest alternative
|
||||||
|
// first), and unmatched face tokens push style variants below the exact face
|
||||||
|
// instead of tying with it (BoldItalic loses to Bold on a bold-only want via
|
||||||
|
// the extras penalty, but beats both single-style faces when both are wanted).
|
||||||
|
// With no wanted tokens, Regular-ish tokens count as wanted so the Regular
|
||||||
|
// face outranks untagged subfamilies.
|
||||||
|
const score = (f: FaceRef) => {
|
||||||
|
const have = styleTokens(f.style)
|
||||||
|
const wanted = want.length > 0 ? want : REGULARISH
|
||||||
|
const hits = want.filter((t) => have.includes(t)).length
|
||||||
|
const extras = have.filter((t) => !wanted.includes(t)).length
|
||||||
|
const regularBonus = want.length === 0 && have.some((t) => REGULARISH.includes(t)) ? 1 : 0
|
||||||
|
return hits * 4 - extras + regularBonus
|
||||||
|
}
|
||||||
|
face = [...candidates].sort((a, b) => score(b) - score(a))[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!face) return null
|
||||||
|
const key = `${face.path}#${face.offset}`
|
||||||
|
let bytes = faceCache.get(key)
|
||||||
|
if (!bytes) {
|
||||||
|
try {
|
||||||
|
bytes = extractFace(readFileSync(face.path), face.offset)
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
if (faceCache.size >= 4) faceCache.clear()
|
||||||
|
faceCache.set(key, bytes)
|
||||||
|
}
|
||||||
|
return bytes
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { hbSubsetWasmPath } from './wasm-path'
|
||||||
|
|
||||||
|
/** hb-subset.wasm exports we call (numbers are pointers into its linear memory) */
|
||||||
|
interface HbSubset {
|
||||||
|
memory: WebAssembly.Memory
|
||||||
|
malloc(size: number): number
|
||||||
|
free(ptr: number): void
|
||||||
|
hb_blob_create(data: number, len: number, mode: number, userData: number, destroy: number): number
|
||||||
|
hb_blob_destroy(blob: number): void
|
||||||
|
hb_blob_get_data(blob: number, len: number): number
|
||||||
|
hb_blob_get_length(blob: number): number
|
||||||
|
hb_face_create(blob: number, index: number): number
|
||||||
|
hb_face_destroy(face: number): void
|
||||||
|
hb_face_reference_blob(face: number): number
|
||||||
|
hb_set_add(set: number, value: number): void
|
||||||
|
hb_set_clear(set: number): void
|
||||||
|
hb_set_invert(set: number): void
|
||||||
|
hb_subset_input_create_or_fail(): number
|
||||||
|
hb_subset_input_destroy(input: number): void
|
||||||
|
hb_subset_input_set(input: number, setType: number): number
|
||||||
|
hb_subset_input_unicode_set(input: number): number
|
||||||
|
hb_subset_or_fail(face: number, input: number): number
|
||||||
|
}
|
||||||
|
|
||||||
|
const HB_MEMORY_MODE_WRITABLE = 2
|
||||||
|
const HB_SUBSET_SETS_LAYOUT_FEATURE_TAG = 6
|
||||||
|
|
||||||
|
let hbPromise: Promise<HbSubset> | null = null
|
||||||
|
|
||||||
|
function loadHb(): Promise<HbSubset> {
|
||||||
|
hbPromise ??= (async () => {
|
||||||
|
const wasmBytes = readFileSync(hbSubsetWasmPath())
|
||||||
|
const { instance } = await WebAssembly.instantiate(wasmBytes)
|
||||||
|
return instance.exports as unknown as HbSubset
|
||||||
|
})()
|
||||||
|
return hbPromise
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Serialized: the wasm instance has one linear memory */
|
||||||
|
let chain: Promise<unknown> = Promise.resolve()
|
||||||
|
|
||||||
|
/** Subset a TrueType font to the glyphs needed for text (layout features kept).
|
||||||
|
Same hb-subset calls as the subset-font npm package, without its fontverter/
|
||||||
|
lodash/require.resolve baggage that breaks under a bundled main process. */
|
||||||
|
export function subsetTtf(font: Buffer, text: string): Promise<Buffer> {
|
||||||
|
const run = chain.then(() => subsetTtfInner(font, text))
|
||||||
|
chain = run.catch(() => undefined)
|
||||||
|
return run
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read one CFF INDEX at `p`, returning item [start,end) pairs and the end position */
|
||||||
|
function readCffIndex(b: Buffer, p: number): { items: [number, number][]; end: number } {
|
||||||
|
const count = b.readUInt16BE(p)
|
||||||
|
if (count === 0) return { items: [], end: p + 2 }
|
||||||
|
const offSize = b[p + 2]!
|
||||||
|
const readOff = (i: number) => b.readUIntBE(p + 3 + i * offSize, offSize)
|
||||||
|
const dataStart = p + 3 + (count + 1) * offSize - 1
|
||||||
|
const items: [number, number][] = []
|
||||||
|
for (let i = 0; i < count; i++) items.push([dataStart + readOff(i), dataStart + readOff(i + 1)])
|
||||||
|
return { items, end: dataStart + readOff(count) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Operator -> last operands of a CFF DICT */
|
||||||
|
function parseCffDict(b: Buffer, start: number, end: number): Map<number, number[]> {
|
||||||
|
const ops = new Map<number, number[]>()
|
||||||
|
let operands: number[] = []
|
||||||
|
let i = start
|
||||||
|
while (i < end) {
|
||||||
|
const b0 = b[i]!
|
||||||
|
if (b0 <= 21) {
|
||||||
|
let op = b0
|
||||||
|
if (b0 === 12) op = 1200 + b[++i]!
|
||||||
|
ops.set(op, operands)
|
||||||
|
operands = []
|
||||||
|
i++
|
||||||
|
} else if (b0 === 28) {
|
||||||
|
operands.push(b.readInt16BE(i + 1))
|
||||||
|
i += 3
|
||||||
|
} else if (b0 === 29) {
|
||||||
|
operands.push(b.readInt32BE(i + 1))
|
||||||
|
i += 5
|
||||||
|
} else if (b0 === 30) {
|
||||||
|
// real number: nibbles until an 0xf terminator
|
||||||
|
i++
|
||||||
|
while (i < end && (b[i]! & 0x0f) !== 0x0f && b[i]! >> 4 !== 0x0f) i++
|
||||||
|
i++
|
||||||
|
operands.push(NaN)
|
||||||
|
} else if (b0 >= 32 && b0 <= 246) {
|
||||||
|
operands.push(b0 - 139)
|
||||||
|
i++
|
||||||
|
} else if (b0 >= 247 && b0 <= 250) {
|
||||||
|
operands.push((b0 - 247) * 256 + b[i + 1]! + 108)
|
||||||
|
i += 2
|
||||||
|
} else if (b0 >= 251 && b0 <= 254) {
|
||||||
|
operands.push(-(b0 - 251) * 256 - b[i + 1]! - 108)
|
||||||
|
i += 2
|
||||||
|
} else {
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ops
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rewrite a CID-keyed CFF's charset to the identity mapping, in a copy of the font.
|
||||||
|
*
|
||||||
|
* PDFium authors text by GID (Identity-H with CID=GID), but a CID-keyed CFF subset keeps
|
||||||
|
* the ORIGINAL CIDs in its charset — conforming viewers (Acrobat/mupdf/poppler) resolve
|
||||||
|
* CID→glyph through the charset, find nothing at CID=GID, and render blanks. An identity
|
||||||
|
* charset (glyph i ⇔ CID i) makes both interpretations agree. The 5-byte format-2 range
|
||||||
|
* always fits over the old charset in place (offsets elsewhere stay valid; the leftover
|
||||||
|
* bytes become dead space, which CFF permits). Throws when the font is not rewritable —
|
||||||
|
* callers fall back to another face. Non-CID CFFs and glyf-flavored fonts pass through.
|
||||||
|
*/
|
||||||
|
export function identityCffCharset(font: Buffer): Buffer {
|
||||||
|
if (font.length < 12 || font.readUInt32BE(0) !== 0x4f54544f) return font // not OTTO
|
||||||
|
const numTables = font.readUInt16BE(4)
|
||||||
|
let cffOff = -1
|
||||||
|
for (let t = 0; t < numTables; t++) {
|
||||||
|
if (font.toString('latin1', 12 + 16 * t, 12 + 16 * t + 4) === 'CFF ') {
|
||||||
|
cffOff = font.readUInt32BE(12 + 16 * t + 8)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cffOff < 0) return font
|
||||||
|
const hdrSize = font[cffOff + 2]!
|
||||||
|
const nameIndex = readCffIndex(font, cffOff + hdrSize)
|
||||||
|
const topIndex = readCffIndex(font, nameIndex.end)
|
||||||
|
const top = topIndex.items[0]
|
||||||
|
if (!top) throw new Error('CFF top DICT missing')
|
||||||
|
const ops = parseCffDict(font, top[0], top[1])
|
||||||
|
if (!ops.has(1230)) return font // not CID-keyed: GID addressing already works
|
||||||
|
const charsetOff = ops.get(15)?.[0]
|
||||||
|
const charStringsOff = ops.get(17)?.[0]
|
||||||
|
if (charsetOff === undefined || charsetOff <= 2 || charStringsOff === undefined)
|
||||||
|
throw new Error('CID-keyed CFF without a custom charset')
|
||||||
|
const nGlyphs = font.readUInt16BE(cffOff + charStringsOff)
|
||||||
|
const cs = cffOff + charsetOff
|
||||||
|
// The identity range must fit inside the old charset (in-place rewrite): size it first
|
||||||
|
const fmt = font[cs]!
|
||||||
|
let oldSize: number
|
||||||
|
if (fmt === 0) {
|
||||||
|
oldSize = 1 + 2 * (nGlyphs - 1)
|
||||||
|
} else if (fmt === 1 || fmt === 2) {
|
||||||
|
const step = fmt === 1 ? 3 : 4 // Range1: u16 first + u8 nLeft; Range2: u16 first + u16 nLeft
|
||||||
|
let covered = 1
|
||||||
|
let p = cs + 1
|
||||||
|
while (covered < nGlyphs) {
|
||||||
|
covered += (fmt === 1 ? font[p + 2]! : font.readUInt16BE(p + 2)) + 1
|
||||||
|
p += step
|
||||||
|
}
|
||||||
|
oldSize = p - cs
|
||||||
|
} else {
|
||||||
|
throw new Error(`unknown CFF charset format ${fmt}`)
|
||||||
|
}
|
||||||
|
const out = Buffer.from(font)
|
||||||
|
if (nGlyphs >= 2 && oldSize >= 5) {
|
||||||
|
out[cs] = 2 // one range: glyphs 1..nGlyphs-1 become CIDs 1..nGlyphs-1
|
||||||
|
out.writeUInt16BE(1, cs + 1)
|
||||||
|
out.writeUInt16BE(nGlyphs - 2, cs + 3)
|
||||||
|
} else if (nGlyphs >= 2 && oldSize === 4 && nGlyphs - 2 <= 0xff) {
|
||||||
|
out[cs] = 1
|
||||||
|
out.writeUInt16BE(1, cs + 1)
|
||||||
|
out[cs + 3] = nGlyphs - 2
|
||||||
|
} else if (nGlyphs !== 1) {
|
||||||
|
throw new Error('CFF charset too small for an in-place identity rewrite')
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
async function subsetTtfInner(font: Buffer, text: string): Promise<Buffer> {
|
||||||
|
const hb = await loadHb()
|
||||||
|
const input = hb.hb_subset_input_create_or_fail()
|
||||||
|
if (!input) throw new Error('hb_subset_input_create_or_fail failed')
|
||||||
|
|
||||||
|
const fontPtr = hb.malloc(font.byteLength)
|
||||||
|
// Views are re-taken after every alloc: malloc may grow (and detach) the memory
|
||||||
|
new Uint8Array(hb.memory.buffer).set(font, fontPtr)
|
||||||
|
const blob = hb.hb_blob_create(fontPtr, font.byteLength, HB_MEMORY_MODE_WRITABLE, 0, 0)
|
||||||
|
const face = hb.hb_face_create(blob, 0)
|
||||||
|
hb.hb_blob_destroy(blob)
|
||||||
|
|
||||||
|
let subset = 0
|
||||||
|
let result = 0
|
||||||
|
try {
|
||||||
|
// Keep all layout features (equivalent of hb-subset --font-features='*')
|
||||||
|
const features = hb.hb_subset_input_set(input, HB_SUBSET_SETS_LAYOUT_FEATURE_TAG)
|
||||||
|
hb.hb_set_clear(features)
|
||||||
|
hb.hb_set_invert(features)
|
||||||
|
|
||||||
|
const unicodes = hb.hb_subset_input_unicode_set(input)
|
||||||
|
for (const ch of text) hb.hb_set_add(unicodes, ch.codePointAt(0)!)
|
||||||
|
|
||||||
|
subset = hb.hb_subset_or_fail(face, input)
|
||||||
|
if (!subset) throw new Error('hb_subset_or_fail failed (corrupt font?)')
|
||||||
|
|
||||||
|
result = hb.hb_face_reference_blob(subset)
|
||||||
|
const len = hb.hb_blob_get_length(result)
|
||||||
|
if (!len) throw new Error('hb-subset produced an empty font')
|
||||||
|
const data = hb.hb_blob_get_data(result, 0)
|
||||||
|
return Buffer.from(new Uint8Array(hb.memory.buffer).subarray(data, data + len))
|
||||||
|
} finally {
|
||||||
|
if (result) hb.hb_blob_destroy(result)
|
||||||
|
if (subset) hb.hb_face_destroy(subset)
|
||||||
|
hb.hb_face_destroy(face)
|
||||||
|
hb.hb_subset_input_destroy(input)
|
||||||
|
hb.free(fontPtr)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,482 @@
|
|||||||
|
import { nativeImage } from 'electron'
|
||||||
|
import { FPDF_PAGEOBJ_TEXT, chainPdfium, loadPdfium, saveDoc, withDocument } from './text-edit'
|
||||||
|
import type { Pdfium } from './text-edit'
|
||||||
|
import type {
|
||||||
|
ImageEditFailure,
|
||||||
|
ImageEditInput,
|
||||||
|
PageImageRef,
|
||||||
|
PagePreviewRequest,
|
||||||
|
} from '../shared/ipc'
|
||||||
|
|
||||||
|
const FPDF_PAGEOBJ_IMAGE = 3
|
||||||
|
const FPDF_BITMAP_BGRA = 4
|
||||||
|
|
||||||
|
type Rect = readonly [number, number, number, number]
|
||||||
|
|
||||||
|
interface PageObj {
|
||||||
|
obj: number
|
||||||
|
index: number
|
||||||
|
type: number
|
||||||
|
bounds: [number, number, number, number]
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectObjects(m: Pdfium, page: number): PageObj[] {
|
||||||
|
const out: PageObj[] = []
|
||||||
|
const bl = m._malloc(4)
|
||||||
|
const bb = m._malloc(4)
|
||||||
|
const br = m._malloc(4)
|
||||||
|
const bt = m._malloc(4)
|
||||||
|
const count = m._FPDFPage_CountObjects(page)
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
const obj = m._FPDFPage_GetObject(page, i)
|
||||||
|
if (!m._FPDFPageObj_GetBounds(obj, bl, bb, br, bt)) continue
|
||||||
|
out.push({
|
||||||
|
obj,
|
||||||
|
index: i,
|
||||||
|
type: m._FPDFPageObj_GetType(obj),
|
||||||
|
bounds: [m.HEAPF32[bl >> 2]!, m.HEAPF32[bb >> 2]!, m.HEAPF32[br >> 2]!, m.HEAPF32[bt >> 2]!],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
for (const p of [bl, bb, br, bt]) m._free(p)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bounds travel renderer→main unchanged, so matching is tight; the tolerance only
|
||||||
|
absorbs float32 round-trips. Closest candidate within tolerance wins. */
|
||||||
|
const MATCH_TOL = 2
|
||||||
|
|
||||||
|
function matchImage(objects: PageObj[], rect: Rect): PageObj | null {
|
||||||
|
let best: PageObj | null = null
|
||||||
|
let bestD = Infinity
|
||||||
|
for (const o of objects) {
|
||||||
|
if (o.type !== FPDF_PAGEOBJ_IMAGE) continue
|
||||||
|
const d = Math.max(
|
||||||
|
Math.abs(o.bounds[0] - rect[0]),
|
||||||
|
Math.abs(o.bounds[1] - rect[1]),
|
||||||
|
Math.abs(o.bounds[2] - rect[2]),
|
||||||
|
Math.abs(o.bounds[3] - rect[3]),
|
||||||
|
)
|
||||||
|
if (d <= MATCH_TOL && d < bestD) {
|
||||||
|
best = o
|
||||||
|
bestD = d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
const firstTextIndex = (objects: PageObj[]): number | undefined =>
|
||||||
|
objects.find((o) => o.type === FPDF_PAGEOBJ_TEXT)?.index
|
||||||
|
|
||||||
|
/** Decode a PNG/JPEG into straight-alpha BGRA (pdfium splits alpha into an SMask itself) */
|
||||||
|
function decodeImage(b64: string): { width: number; height: number; bgra: Buffer } {
|
||||||
|
const img = nativeImage.createFromBuffer(Buffer.from(b64, 'base64'))
|
||||||
|
if (img.isEmpty()) throw new Error('could not decode the image data')
|
||||||
|
const { width, height } = img.getSize()
|
||||||
|
// toBitmap() hands back premultiplied BGRA; un-premultiply so translucent pixels
|
||||||
|
// keep their color once pdfium separates them into image + SMask
|
||||||
|
const bgra = Buffer.from(img.toBitmap())
|
||||||
|
for (let i = 0; i < bgra.length; i += 4) {
|
||||||
|
const a = bgra[i + 3]!
|
||||||
|
if (a > 0 && a < 255) {
|
||||||
|
bgra[i] = Math.min(255, Math.round((bgra[i]! * 255) / a))
|
||||||
|
bgra[i + 1] = Math.min(255, Math.round((bgra[i + 1]! * 255) / a))
|
||||||
|
bgra[i + 2] = Math.min(255, Math.round((bgra[i + 2]! * 255) / a))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { width, height, bgra }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Content matrix for a footprint rect, counter-rotated against the page's display
|
||||||
|
rotation so the image shows upright (same table as save-pdf's addImageStamp) */
|
||||||
|
function imageMatrix(rect: Rect, rotate: number): number[] {
|
||||||
|
const [x1, y1, x2, y2] = rect
|
||||||
|
const w = x2 - x1
|
||||||
|
const h = y2 - y1
|
||||||
|
switch (((rotate % 360) + 360) % 360) {
|
||||||
|
case 90:
|
||||||
|
return [0, h, -w, 0, x2, y1]
|
||||||
|
case 180:
|
||||||
|
return [-w, 0, 0, -h, x2, y2]
|
||||||
|
case 270:
|
||||||
|
return [0, -h, w, 0, x1, y2]
|
||||||
|
default:
|
||||||
|
return [w, 0, 0, h, x1, y1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertImage(m: Pdfium, doc: number, page: number, edit: ImageEditInput): void {
|
||||||
|
if (edit.kind !== 'insertImage') return
|
||||||
|
const { width, height, bgra } = decodeImage(edit.image)
|
||||||
|
const bufPtr = m._malloc(bgra.length)
|
||||||
|
m.HEAPU8.set(bgra, bufPtr)
|
||||||
|
const bmp = m._FPDFBitmap_CreateEx(width, height, FPDF_BITMAP_BGRA, bufPtr, width * 4)
|
||||||
|
if (!bmp) {
|
||||||
|
m._free(bufPtr)
|
||||||
|
throw new Error('FPDFBitmap_CreateEx failed')
|
||||||
|
}
|
||||||
|
const imgObj = m._FPDFPageObj_NewImageObj(doc)
|
||||||
|
const ok = imgObj && m._FPDFImageObj_SetBitmap(0, 0, imgObj, bmp)
|
||||||
|
m._FPDFBitmap_Destroy(bmp)
|
||||||
|
m._free(bufPtr)
|
||||||
|
if (!ok) {
|
||||||
|
if (imgObj) m._FPDFPageObj_Destroy(imgObj)
|
||||||
|
throw new Error('FPDFImageObj_SetBitmap failed')
|
||||||
|
}
|
||||||
|
const matPtr = m._malloc(24)
|
||||||
|
m.HEAPF32.set(imageMatrix(edit.rect, edit.rotate ?? 0), matPtr >> 2)
|
||||||
|
m._FPDFPageObj_SetMatrix(imgObj, matPtr)
|
||||||
|
m._free(matPtr)
|
||||||
|
const textIdx = edit.layer === 'belowText' ? firstTextIndex(collectObjects(m, page)) : undefined
|
||||||
|
if (textIdx !== undefined && m._FPDFPage_InsertObjectAtIndex) {
|
||||||
|
if (!m._FPDFPage_InsertObjectAtIndex(page, imgObj, textIdx)) {
|
||||||
|
m._FPDFPageObj_Destroy(imgObj)
|
||||||
|
throw new Error('FPDFPage_InsertObjectAtIndex failed')
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
m._FPDFPage_InsertObject(page, imgObj)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Move an object to the requested z-band (remove + reinsert; the page owns it again after) */
|
||||||
|
function moveToLayer(m: Pdfium, page: number, obj: number, layer: 'belowText' | 'aboveText'): void {
|
||||||
|
if (!m._FPDFPage_RemoveObject(page, obj)) throw new Error('FPDFPage_RemoveObject failed')
|
||||||
|
const textIdx = layer === 'belowText' ? firstTextIndex(collectObjects(m, page)) : undefined
|
||||||
|
if (textIdx !== undefined && m._FPDFPage_InsertObjectAtIndex) {
|
||||||
|
if (!m._FPDFPage_InsertObjectAtIndex(page, obj, textIdx)) {
|
||||||
|
// The object is already off the page here — re-attach it (topmost) instead of
|
||||||
|
// destroying it, or a skipped layer change would silently delete page content
|
||||||
|
m._FPDFPage_InsertObject(page, obj)
|
||||||
|
throw new Error('FPDFPage_InsertObjectAtIndex failed')
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
m._FPDFPage_InsertObject(page, obj)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Screen-clockwise quarter turns as PDF user-space matrices (y-up flips handedness) */
|
||||||
|
const QUARTER_TURN_MATS: ReadonlyArray<readonly [number, number, number, number]> = [
|
||||||
|
[1, 0, 0, 1],
|
||||||
|
[0, -1, 1, 0],
|
||||||
|
[-1, 0, 0, -1],
|
||||||
|
[0, 1, -1, 0],
|
||||||
|
]
|
||||||
|
|
||||||
|
/** Optional center rotation, then the axis-aligned map old bounds → final rect
|
||||||
|
(content orientation otherwise survives, as before) */
|
||||||
|
function applyImageGeometry(
|
||||||
|
m: Pdfium,
|
||||||
|
obj: number,
|
||||||
|
bounds: Rect,
|
||||||
|
rect: Rect,
|
||||||
|
quarterTurns?: number,
|
||||||
|
): void {
|
||||||
|
let [ox1, oy1, ox2, oy2] = bounds
|
||||||
|
const turns = (((quarterTurns ?? 0) % 4) + 4) % 4
|
||||||
|
if (turns) {
|
||||||
|
const cx = (ox1 + ox2) / 2
|
||||||
|
const cy = (oy1 + oy2) / 2
|
||||||
|
const [a, b, c, d] = QUARTER_TURN_MATS[turns]!
|
||||||
|
m._FPDFPageObj_Transform(obj, a, b, c, d, cx - a * cx - c * cy, cy - b * cx - d * cy)
|
||||||
|
if (turns % 2 === 1) {
|
||||||
|
const w = ox2 - ox1
|
||||||
|
const h = oy2 - oy1
|
||||||
|
;[ox1, oy1, ox2, oy2] = [cx - h / 2, cy - w / 2, cx + h / 2, cy + w / 2]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const [nx1, ny1, nx2, ny2] = rect
|
||||||
|
const ow = ox2 - ox1
|
||||||
|
const oh = oy2 - oy1
|
||||||
|
if (ow > 1e-6 && oh > 1e-6 && (nx1 !== ox1 || ny1 !== oy1 || nx2 !== ox2 || ny2 !== oy2)) {
|
||||||
|
const sx = (nx2 - nx1) / ow
|
||||||
|
const sy = (ny2 - ny1) / oh
|
||||||
|
// Post-multiplied axis-aligned map old bounds → new rect
|
||||||
|
m._FPDFPageObj_Transform(obj, sx, 0, 0, sy, nx1 - sx * ox1, ny1 - sy * oy1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function transformImage(m: Pdfium, page: number, edit: ImageEditInput): void {
|
||||||
|
if (edit.kind !== 'transformImage') return
|
||||||
|
const target = matchImage(collectObjects(m, page), edit.oldRect)
|
||||||
|
if (!target) throw new Error('the image could not be located on the page')
|
||||||
|
// Layer move first: it is the only part that can fail, so a skipped edit is
|
||||||
|
// reported before any geometry has been touched
|
||||||
|
if (edit.layer) moveToLayer(m, page, target.obj, edit.layer)
|
||||||
|
applyImageGeometry(m, target.obj, target.bounds, edit.rect, edit.quarterTurns)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Swap the image object's pixels for a new bitmap (matrix untouched: the footprint,
|
||||||
|
z-order and any original rotation stay), then apply the shared geometry pass */
|
||||||
|
function replaceImage(m: Pdfium, page: number, edit: ImageEditInput): void {
|
||||||
|
if (edit.kind !== 'replaceImage') return
|
||||||
|
const target = matchImage(collectObjects(m, page), edit.oldRect)
|
||||||
|
if (!target) throw new Error('the image could not be located on the page')
|
||||||
|
if (edit.layer) moveToLayer(m, page, target.obj, edit.layer)
|
||||||
|
const { width, height, bgra } = decodeImage(edit.image)
|
||||||
|
const bufPtr = m._malloc(bgra.length)
|
||||||
|
m.HEAPU8.set(bgra, bufPtr)
|
||||||
|
const bmp = m._FPDFBitmap_CreateEx(width, height, FPDF_BITMAP_BGRA, bufPtr, width * 4)
|
||||||
|
if (!bmp) {
|
||||||
|
m._free(bufPtr)
|
||||||
|
throw new Error('FPDFBitmap_CreateEx failed')
|
||||||
|
}
|
||||||
|
// Pass the owning page so pdfium drops its cached render of the old pixels
|
||||||
|
const pagesPtr = m._malloc(4)
|
||||||
|
m.HEAP32[pagesPtr >> 2] = page
|
||||||
|
const ok = m._FPDFImageObj_SetBitmap(pagesPtr, 1, target.obj, bmp)
|
||||||
|
m._free(pagesPtr)
|
||||||
|
m._FPDFBitmap_Destroy(bmp)
|
||||||
|
m._free(bufPtr)
|
||||||
|
if (!ok) throw new Error('FPDFImageObj_SetBitmap failed')
|
||||||
|
applyImageGeometry(m, target.obj, target.bounds, edit.rect, edit.quarterTurns)
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteImage(m: Pdfium, page: number, edit: ImageEditInput): void {
|
||||||
|
if (edit.kind !== 'deleteImage') return
|
||||||
|
const target = matchImage(collectObjects(m, page), edit.oldRect)
|
||||||
|
if (!target) throw new Error('the image could not be located on the page')
|
||||||
|
if (!m._FPDFPage_RemoveObject(page, target.obj)) throw new Error('FPDFPage_RemoveObject failed')
|
||||||
|
m._FPDFPageObj_Destroy(target.obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImageEditsResult {
|
||||||
|
bytes: Uint8Array
|
||||||
|
skipped: ImageEditFailure[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Apply content-stream image ops, fail-soft per edit (mirrors applyTextEdits) */
|
||||||
|
export function applyImageEdits(
|
||||||
|
bytes: Uint8Array,
|
||||||
|
edits: ImageEditInput[],
|
||||||
|
): Promise<ImageEditsResult> {
|
||||||
|
return chainPdfium(async () => {
|
||||||
|
const m = await loadPdfium()
|
||||||
|
const skipped: ImageEditFailure[] = []
|
||||||
|
return withDocument(m, bytes, async (doc) => {
|
||||||
|
const pageCount = m._FPDF_GetPageCount(doc)
|
||||||
|
const byPage = new Map<number, { edit: ImageEditInput; editIndex: number }[]>()
|
||||||
|
for (const [editIndex, edit] of edits.entries()) {
|
||||||
|
if (edit.pageIndex < 0 || edit.pageIndex >= pageCount) {
|
||||||
|
skipped.push({ editIndex, pageIndex: edit.pageIndex, reason: 'page does not exist' })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
byPage.set(edit.pageIndex, [...(byPage.get(edit.pageIndex) ?? []), { edit, editIndex }])
|
||||||
|
}
|
||||||
|
let appliedTotal = 0
|
||||||
|
for (const [pageIndex, pageEdits] of byPage) {
|
||||||
|
const page = m._FPDF_LoadPage(doc, pageIndex)
|
||||||
|
if (!page) throw new Error(`could not load page ${pageIndex + 1}`)
|
||||||
|
try {
|
||||||
|
let applied = 0
|
||||||
|
// Objects are re-collected inside each op: every mutation shifts indices
|
||||||
|
for (const { edit, editIndex } of pageEdits) {
|
||||||
|
try {
|
||||||
|
if (edit.kind === 'insertImage') insertImage(m, doc, page, edit)
|
||||||
|
else if (edit.kind === 'transformImage') transformImage(m, page, edit)
|
||||||
|
else if (edit.kind === 'replaceImage') replaceImage(m, page, edit)
|
||||||
|
else deleteImage(m, page, edit)
|
||||||
|
applied++
|
||||||
|
} catch (err) {
|
||||||
|
skipped.push({
|
||||||
|
editIndex,
|
||||||
|
pageIndex,
|
||||||
|
reason: err instanceof Error ? err.message : String(err),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (applied > 0 && !m._FPDFPage_GenerateContent(page)) {
|
||||||
|
throw new Error(`could not regenerate page ${pageIndex + 1}`)
|
||||||
|
}
|
||||||
|
appliedTotal += applied
|
||||||
|
} finally {
|
||||||
|
m._FPDF_ClosePage(page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { bytes: appliedTotal > 0 ? saveDoc(m, doc) : bytes, skipped }
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Enumerate every page's content-stream images (rect + z-band relative to text) */
|
||||||
|
export function listPageImages(bytes: Uint8Array): Promise<PageImageRef[]> {
|
||||||
|
return chainPdfium(async () => {
|
||||||
|
const m = await loadPdfium()
|
||||||
|
return withDocument(m, bytes, async (doc) => {
|
||||||
|
const out: PageImageRef[] = []
|
||||||
|
const pageCount = m._FPDF_GetPageCount(doc)
|
||||||
|
for (let pageIndex = 0; pageIndex < pageCount; pageIndex++) {
|
||||||
|
const page = m._FPDF_LoadPage(doc, pageIndex)
|
||||||
|
if (!page) continue
|
||||||
|
try {
|
||||||
|
const objects = collectObjects(m, page)
|
||||||
|
const textIdx = firstTextIndex(objects)
|
||||||
|
for (const o of objects) {
|
||||||
|
if (o.type !== FPDF_PAGEOBJ_IMAGE) continue
|
||||||
|
// Sub-3pt objects are decoration/artifacts; not worth an edit target
|
||||||
|
if (o.bounds[2] - o.bounds[0] < 3 || o.bounds[3] - o.bounds[1] < 3) continue
|
||||||
|
out.push({
|
||||||
|
pageIndex,
|
||||||
|
rect: o.bounds,
|
||||||
|
aboveText: textIdx !== undefined && o.index > textIdx,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
m._FPDF_ClosePage(page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Render one existing image object to PNG (base64) for the renderer's ghost preview */
|
||||||
|
export function renderImagePng(
|
||||||
|
bytes: Uint8Array,
|
||||||
|
pageIndex: number,
|
||||||
|
rect: Rect,
|
||||||
|
): Promise<string | null> {
|
||||||
|
return chainPdfium(async () => {
|
||||||
|
const m = await loadPdfium()
|
||||||
|
return withDocument(m, bytes, async (doc) => {
|
||||||
|
const page = m._FPDF_LoadPage(doc, pageIndex)
|
||||||
|
if (!page) return null
|
||||||
|
try {
|
||||||
|
const target = matchImage(collectObjects(m, page), rect)
|
||||||
|
if (!target) return null
|
||||||
|
const bmp = m._FPDFImageObj_GetRenderedBitmap(doc, page, target.obj)
|
||||||
|
if (!bmp) return null
|
||||||
|
try {
|
||||||
|
const w = m._FPDFBitmap_GetWidth(bmp)
|
||||||
|
const h = m._FPDFBitmap_GetHeight(bmp)
|
||||||
|
const stride = m._FPDFBitmap_GetStride(bmp)
|
||||||
|
const buf = m._FPDFBitmap_GetBuffer(bmp)
|
||||||
|
if (!w || !h || !buf) return null
|
||||||
|
const tight = Buffer.alloc(w * h * 4)
|
||||||
|
for (let row = 0; row < h; row++) {
|
||||||
|
tight.set(
|
||||||
|
m.HEAPU8.subarray(buf + row * stride, buf + row * stride + w * 4),
|
||||||
|
row * w * 4,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const png = nativeImage.createFromBitmap(tight, { width: w, height: h }).toPNG()
|
||||||
|
return png.toString('base64')
|
||||||
|
} finally {
|
||||||
|
m._FPDFBitmap_Destroy(bmp)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
m._FPDF_ClosePage(page)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Live-preview render: rasterize a page region with the given image objects removed
|
||||||
|
* (in memory only — the file is untouched). The renderer patches the region over its
|
||||||
|
* PDF.js canvas so a moved/resized/deleted image disappears immediately instead of
|
||||||
|
* lingering until save. Unmatched rects are skipped fail-soft.
|
||||||
|
*/
|
||||||
|
export function renderPagePreviewPng(
|
||||||
|
bytes: Uint8Array,
|
||||||
|
request: Omit<PagePreviewRequest, 'path'>,
|
||||||
|
): Promise<string | null> {
|
||||||
|
const { pageIndex, excludeRects, clip, pxWidth, rotate } = request
|
||||||
|
return chainPdfium(async () => {
|
||||||
|
const m = await loadPdfium()
|
||||||
|
return withDocument(m, bytes, async (doc) => {
|
||||||
|
const page = m._FPDF_LoadPage(doc, pageIndex)
|
||||||
|
if (!page) return null
|
||||||
|
try {
|
||||||
|
for (const rect of excludeRects) {
|
||||||
|
const target = matchImage(collectObjects(m, page), rect)
|
||||||
|
if (target && m._FPDFPage_RemoveObject(page, target.obj)) {
|
||||||
|
m._FPDFPageObj_Destroy(target.obj)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Page size in display orientation (pdfium already applies /Rotate; the
|
||||||
|
// unsaved delta passed as quarter turns swaps the axes again when odd)
|
||||||
|
const baseW = m._FPDF_GetPageWidthF(page)
|
||||||
|
const baseH = m._FPDF_GetPageHeightF(page)
|
||||||
|
const turns = ((rotate % 4) + 4) % 4
|
||||||
|
const dispW = turns % 2 === 1 ? baseH : baseW
|
||||||
|
const dispH = turns % 2 === 1 ? baseW : baseH
|
||||||
|
if (clip.width <= 0 || clip.height <= 0 || pxWidth <= 0) return null
|
||||||
|
const k = pxWidth / clip.width
|
||||||
|
const w = Math.max(1, Math.round(pxWidth))
|
||||||
|
const h = Math.max(1, Math.round(clip.height * k))
|
||||||
|
const bufPtr = m._malloc(w * h * 4)
|
||||||
|
const bmp = m._FPDFBitmap_CreateEx(w, h, FPDF_BITMAP_BGRA, bufPtr, w * 4)
|
||||||
|
if (!bmp) {
|
||||||
|
m._free(bufPtr)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
m._FPDFBitmap_FillRect(bmp, 0, 0, w, h, 0xffffffff)
|
||||||
|
m._FPDF_RenderPageBitmap(
|
||||||
|
bmp,
|
||||||
|
page,
|
||||||
|
Math.round(-clip.x * k),
|
||||||
|
Math.round(-clip.y * k),
|
||||||
|
Math.round(dispW * k),
|
||||||
|
Math.round(dispH * k),
|
||||||
|
turns,
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
const tight = Buffer.from(m.HEAPU8.subarray(bufPtr, bufPtr + w * h * 4))
|
||||||
|
const png = nativeImage.createFromBitmap(tight, { width: w, height: h }).toPNG()
|
||||||
|
return png.toString('base64')
|
||||||
|
} finally {
|
||||||
|
m._FPDFBitmap_Destroy(bmp)
|
||||||
|
m._free(bufPtr)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
m._FPDF_ClosePage(page)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read-back verification on the final saved bytes (pageIndex already remapped to the
|
||||||
|
* final document): inserts and transforms must be findable at their target rect.
|
||||||
|
* Deletes are not re-checked — RemoveObject's status is verified at apply time, and a
|
||||||
|
* second identical image at the same bounds would read as a false failure.
|
||||||
|
*/
|
||||||
|
export function verifyImageEdits(
|
||||||
|
bytes: Uint8Array,
|
||||||
|
edits: { pageIndex: number; rect: Rect }[],
|
||||||
|
): Promise<{ pageIndex: number; reason: string }[]> {
|
||||||
|
return chainPdfium(async () => {
|
||||||
|
const m = await loadPdfium()
|
||||||
|
return withDocument(m, bytes, async (doc) => {
|
||||||
|
const failures: { pageIndex: number; reason: string }[] = []
|
||||||
|
const pageCount = m._FPDF_GetPageCount(doc)
|
||||||
|
const byPage = new Map<number, Rect[]>()
|
||||||
|
for (const e of edits) {
|
||||||
|
if (e.pageIndex < 0 || e.pageIndex >= pageCount) {
|
||||||
|
failures.push({ pageIndex: e.pageIndex, reason: 'page missing from saved output' })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
byPage.set(e.pageIndex, [...(byPage.get(e.pageIndex) ?? []), e.rect])
|
||||||
|
}
|
||||||
|
for (const [pageIndex, rects] of byPage) {
|
||||||
|
const page = m._FPDF_LoadPage(doc, pageIndex)
|
||||||
|
if (!page) {
|
||||||
|
for (const _ of rects)
|
||||||
|
failures.push({ pageIndex, reason: 'page unreadable in saved output' })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const objects = collectObjects(m, page)
|
||||||
|
for (const rect of rects) {
|
||||||
|
if (!matchImage(objects, rect)) {
|
||||||
|
failures.push({ pageIndex, reason: 'image missing from saved output' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
m._FPDF_ClosePage(page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return failures
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
showSaveDialogWithMemory,
|
showSaveDialogWithMemory,
|
||||||
} from '@genoffice/electron-utils'
|
} from '@genoffice/electron-utils'
|
||||||
import { createI18n, getUiLang } from '@genoffice/i18n'
|
import { createI18n, getUiLang } from '@genoffice/i18n'
|
||||||
|
import { gskGenerateImage, hasGskAuth } from '@genoffice/ai-search'
|
||||||
import { PDF_CHANNELS } from '../shared/ipc'
|
import { PDF_CHANNELS } from '../shared/ipc'
|
||||||
import type {
|
import type {
|
||||||
ExportImagesRequest,
|
ExportImagesRequest,
|
||||||
@@ -20,8 +21,11 @@ import type {
|
|||||||
ExtractPagesResult,
|
ExtractPagesResult,
|
||||||
InsertPdfRequest,
|
InsertPdfRequest,
|
||||||
InsertPdfResult,
|
InsertPdfResult,
|
||||||
|
PagePreviewRequest,
|
||||||
SavePdfRequest,
|
SavePdfRequest,
|
||||||
SavePdfResult,
|
SavePdfResult,
|
||||||
|
TextEditValidation,
|
||||||
|
ValidateTextEditsRequest,
|
||||||
} from '../shared/ipc'
|
} from '../shared/ipc'
|
||||||
import { extractPagesBytes, insertPdfBytes, savePdfToPath } from './save-pdf'
|
import { extractPagesBytes, insertPdfBytes, savePdfToPath } from './save-pdf'
|
||||||
|
|
||||||
@@ -389,13 +393,91 @@ function registerPdfIpc(): void {
|
|||||||
return { ok: false, error: 'pdf: target path not granted to this view' }
|
return { ok: false, error: 'pdf: target path not granted to this view' }
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await savePdfToPath(path, target, request)
|
const { skippedTextEdits, skippedImageEdits } = await savePdfToPath(path, target, request)
|
||||||
return { ok: true }
|
return {
|
||||||
|
ok: true,
|
||||||
|
...(skippedTextEdits.length > 0 ? { skippedTextEdits } : {}),
|
||||||
|
...(skippedImageEdits.length > 0 ? { skippedImageEdits } : {}),
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return { ok: false, error: err instanceof Error ? err.message : String(err) }
|
return { ok: false, error: err instanceof Error ? err.message : String(err) }
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
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')
|
||||||
|
}
|
||||||
|
// Lazy import like the text-edit paths: pdfium wasm only loads when the feature is used
|
||||||
|
const { listPageImages } = await import('./image-edit')
|
||||||
|
return listPageImages(new Uint8Array(await readFile(path)))
|
||||||
|
})
|
||||||
|
|
||||||
|
ipcMain.handle(
|
||||||
|
PDF_CHANNELS.pageImagePng,
|
||||||
|
async (
|
||||||
|
e,
|
||||||
|
request: { path: string; pageIndex: number; rect: [number, number, number, number] },
|
||||||
|
) => {
|
||||||
|
const { path, pageIndex, rect } = request ?? {}
|
||||||
|
if (
|
||||||
|
typeof path !== 'string' ||
|
||||||
|
!allowedByWc.get(e.sender.id)?.has(path) ||
|
||||||
|
typeof pageIndex !== 'number' ||
|
||||||
|
!Array.isArray(rect)
|
||||||
|
) {
|
||||||
|
throw new Error('pdf: path not granted to this view')
|
||||||
|
}
|
||||||
|
const { renderImagePng } = await import('./image-edit')
|
||||||
|
return renderImagePng(new Uint8Array(await readFile(path)), pageIndex, rect)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
ipcMain.handle(PDF_CHANNELS.pagePreviewPng, async (e, request: PagePreviewRequest) => {
|
||||||
|
const { path, pageIndex, excludeRects, clip, pxWidth, rotate } = request ?? {}
|
||||||
|
if (
|
||||||
|
typeof path !== 'string' ||
|
||||||
|
!allowedByWc.get(e.sender.id)?.has(path) ||
|
||||||
|
typeof pageIndex !== 'number' ||
|
||||||
|
!Array.isArray(excludeRects) ||
|
||||||
|
typeof clip !== 'object' ||
|
||||||
|
typeof pxWidth !== 'number' ||
|
||||||
|
typeof rotate !== 'number'
|
||||||
|
) {
|
||||||
|
throw new Error('pdf: path not granted to this view')
|
||||||
|
}
|
||||||
|
const { renderPagePreviewPng } = await import('./image-edit')
|
||||||
|
return renderPagePreviewPng(new Uint8Array(await readFile(path)), {
|
||||||
|
pageIndex,
|
||||||
|
excludeRects,
|
||||||
|
clip,
|
||||||
|
pxWidth,
|
||||||
|
rotate,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
ipcMain.handle(
|
||||||
|
PDF_CHANNELS.validateTextEdits,
|
||||||
|
async (e, request: ValidateTextEditsRequest): Promise<TextEditValidation[]> => {
|
||||||
|
const { path, edits } = request ?? {}
|
||||||
|
if (
|
||||||
|
typeof path !== 'string' ||
|
||||||
|
!allowedByWc.get(e.sender.id)?.has(path) ||
|
||||||
|
!Array.isArray(edits)
|
||||||
|
) {
|
||||||
|
throw new Error('pdf: path not granted to this view')
|
||||||
|
}
|
||||||
|
// Same lazy import as the save path: the pdfium wasm only loads when text editing is used
|
||||||
|
const { validateTextEdits } = await import('./text-edit')
|
||||||
|
return validateTextEdits(new Uint8Array(await readFile(path)), edits)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
ipcMain.handle(PDF_CHANNELS.listEditFonts, async (): Promise<string[]> => {
|
||||||
|
const { listEditFonts } = await import('./text-edit')
|
||||||
|
return listEditFonts()
|
||||||
|
})
|
||||||
|
|
||||||
ipcMain.handle(
|
ipcMain.handle(
|
||||||
PDF_CHANNELS.extractPages,
|
PDF_CHANNELS.extractPages,
|
||||||
async (e, request: ExtractPagesRequest): Promise<ExtractPagesResult> => {
|
async (e, request: ExtractPagesRequest): Promise<ExtractPagesResult> => {
|
||||||
@@ -484,6 +566,29 @@ function registerPdfIpc(): void {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// pdf-owned (unlike ai:image-search / ai:fetch-image, which the shell registers app-wide):
|
||||||
|
// slides' ai:generate-image is only registered once a slides view exists, so pdf needs its own
|
||||||
|
ipcMain.handle(
|
||||||
|
PDF_CHANNELS.generateImage,
|
||||||
|
async (_e, op: { prompt?: unknown; aspectRatio?: unknown }) => {
|
||||||
|
if (!hasGskAuth())
|
||||||
|
return {
|
||||||
|
error: 'Genspark account is not logged in on this machine; ask the user to log in first',
|
||||||
|
}
|
||||||
|
const prompt = String(op?.prompt ?? '').trim()
|
||||||
|
if (!prompt) return { error: 'prompt must not be empty' }
|
||||||
|
try {
|
||||||
|
const r = await gskGenerateImage({
|
||||||
|
prompt,
|
||||||
|
aspectRatio: op?.aspectRatio ? String(op.aspectRatio) : undefined,
|
||||||
|
})
|
||||||
|
return { url: r.url }
|
||||||
|
} catch (err) {
|
||||||
|
return { error: err instanceof Error ? err.message : String(err) }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
ipcMain.on(PDF_CHANNELS.dirtyChanged, (e, dirty: unknown) => {
|
ipcMain.on(PDF_CHANNELS.dirtyChanged, (e, dirty: unknown) => {
|
||||||
if (dirty === true) dirtyByWc.add(e.sender.id)
|
if (dirty === true) dirtyByWc.add(e.sender.id)
|
||||||
else dirtyByWc.delete(e.sender.id)
|
else dirtyByWc.delete(e.sender.id)
|
||||||
|
|||||||
@@ -13,9 +13,11 @@ import type { PDFPage, PDFRef } from 'pdf-lib'
|
|||||||
import type {
|
import type {
|
||||||
DrawingInput,
|
DrawingInput,
|
||||||
FormValueInput,
|
FormValueInput,
|
||||||
|
ImageEditFailure,
|
||||||
MarkupInput,
|
MarkupInput,
|
||||||
MetadataInput,
|
MetadataInput,
|
||||||
SavePdfRequest,
|
SavePdfRequest,
|
||||||
|
TextEditFailure,
|
||||||
} from '../shared/ipc'
|
} from '../shared/ipc'
|
||||||
|
|
||||||
const num = (v: number) => Math.round(v * 100) / 100
|
const num = (v: number) => Math.round(v * 100) / 100
|
||||||
@@ -332,13 +334,78 @@ function applyMetadata(pdfDoc: PDFDocument, meta: MetadataInput): void {
|
|||||||
* The source file is only ever read: Save As (targetPath !== sourcePath) must never mutate
|
* The source file is only ever read: Save As (targetPath !== sourcePath) must never mutate
|
||||||
* the original document, and a failed or cancelled save leaves both paths untouched.
|
* the original document, and a failed or cancelled save leaves both paths untouched.
|
||||||
* In-place Save passes targetPath === sourcePath.
|
* In-place Save passes targetPath === sourcePath.
|
||||||
|
* Returns the text edits that no longer matched the document and were skipped.
|
||||||
*/
|
*/
|
||||||
|
export interface SavePdfSkips {
|
||||||
|
skippedTextEdits: TextEditFailure[]
|
||||||
|
skippedImageEdits: ImageEditFailure[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Original page index → index in the saved file (after this request's deletions/reorder);
|
||||||
|
null = the page is gone from the output */
|
||||||
|
function finalPageIndex(request: SavePdfRequest, p: number): number | null {
|
||||||
|
if (request.pageOrder) {
|
||||||
|
const i = request.pageOrder.indexOf(p)
|
||||||
|
return i >= 0 ? i : null
|
||||||
|
}
|
||||||
|
const del = request.deletedPages ?? []
|
||||||
|
if (del.includes(p)) return null
|
||||||
|
return p - del.filter((d) => d < p).length
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read-back verification of applied content-stream edits against the final bytes.
|
||||||
|
* Anything that fails here would have been silent data loss; the caller aborts the
|
||||||
|
* save before the bytes reach disk, keeping the original file and the pending edits.
|
||||||
|
*/
|
||||||
|
async function verifyContentEdits(
|
||||||
|
bytes: Uint8Array,
|
||||||
|
request: SavePdfRequest,
|
||||||
|
skips: SavePdfSkips,
|
||||||
|
): Promise<void> {
|
||||||
|
const failures: { pageIndex: number; reason: string }[] = []
|
||||||
|
const appliedText = (request.textEdits ?? []).filter(
|
||||||
|
(e) =>
|
||||||
|
!skips.skippedTextEdits.some((s) => s.pageIndex === e.pageIndex && s.oldText === e.oldText),
|
||||||
|
)
|
||||||
|
if (appliedText.length > 0) {
|
||||||
|
const { verifyTextEdits } = await import('./text-edit')
|
||||||
|
const remapped = appliedText.flatMap((e) => {
|
||||||
|
const pageIndex = finalPageIndex(request, e.pageIndex)
|
||||||
|
return pageIndex === null ? [] : [{ pageIndex, newText: e.newText }]
|
||||||
|
})
|
||||||
|
failures.push(...(await verifyTextEdits(bytes, remapped)))
|
||||||
|
}
|
||||||
|
const appliedImages = (request.imageEdits ?? []).filter(
|
||||||
|
(e, i) => e.kind !== 'deleteImage' && !skips.skippedImageEdits.some((s) => s.editIndex === i),
|
||||||
|
)
|
||||||
|
if (appliedImages.length > 0) {
|
||||||
|
const { verifyImageEdits } = await import('./image-edit')
|
||||||
|
const remapped = appliedImages.flatMap((e) => {
|
||||||
|
const pageIndex = finalPageIndex(request, e.pageIndex)
|
||||||
|
return pageIndex === null || e.kind === 'deleteImage' ? [] : [{ pageIndex, rect: e.rect }]
|
||||||
|
})
|
||||||
|
failures.push(...(await verifyImageEdits(bytes, remapped)))
|
||||||
|
}
|
||||||
|
if (failures.length > 0) {
|
||||||
|
const pages = [...new Set(failures.map((f) => f.pageIndex + 1))].sort((a, b) => a - b)
|
||||||
|
// "save-verify-failed pages=…" is parsed by the renderer to localize the notice
|
||||||
|
throw new Error(
|
||||||
|
`save-verify-failed pages=${pages.join(',')}: ${failures[0]!.reason}; the file was not written`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function savePdfToPath(
|
export async function savePdfToPath(
|
||||||
sourcePath: string,
|
sourcePath: string,
|
||||||
targetPath: string,
|
targetPath: string,
|
||||||
request: SavePdfRequest,
|
request: SavePdfRequest,
|
||||||
): Promise<void> {
|
): Promise<SavePdfSkips> {
|
||||||
const bytes = await applySaveRequest(new Uint8Array(await readFile(sourcePath)), request)
|
const { bytes, ...skips } = await applySaveRequest(
|
||||||
|
new Uint8Array(await readFile(sourcePath)),
|
||||||
|
request,
|
||||||
|
)
|
||||||
|
await verifyContentEdits(bytes, request, skips)
|
||||||
const tmp = `${targetPath}.gensave-${process.pid}.tmp`
|
const tmp = `${targetPath}.gensave-${process.pid}.tmp`
|
||||||
try {
|
try {
|
||||||
await writeFile(tmp, bytes)
|
await writeFile(tmp, bytes)
|
||||||
@@ -347,13 +414,38 @@ export async function savePdfToPath(
|
|||||||
await rm(tmp, { force: true })
|
await rm(tmp, { force: true })
|
||||||
throw err
|
throw err
|
||||||
}
|
}
|
||||||
|
return skips
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AppliedSaveRequest {
|
||||||
|
bytes: Uint8Array
|
||||||
|
/** Text edits that could not be matched to the document; the rest of the request is in `bytes` */
|
||||||
|
skippedTextEdits: TextEditFailure[]
|
||||||
|
/** Same, for content-stream image operations */
|
||||||
|
skippedImageEdits: ImageEditFailure[]
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Apply markups + form values + page ops, returning new bytes. Original objects are not reordered (pdf-lib keeps untouched objects). */
|
/** Apply markups + form values + page ops, returning new bytes. Original objects are not reordered (pdf-lib keeps untouched objects). */
|
||||||
export async function applySaveRequest(
|
export async function applySaveRequest(
|
||||||
bytes: Uint8Array,
|
bytes: Uint8Array,
|
||||||
request: SavePdfRequest,
|
request: SavePdfRequest,
|
||||||
): Promise<Uint8Array> {
|
): Promise<AppliedSaveRequest> {
|
||||||
|
let skippedTextEdits: TextEditFailure[] = []
|
||||||
|
let skippedImageEdits: ImageEditFailure[] = []
|
||||||
|
if (request.textEdits && request.textEdits.length > 0) {
|
||||||
|
// Content-stream rewrite must land before pdf-lib touches the bytes: everything
|
||||||
|
// below annotates on top of whatever the pages now say
|
||||||
|
const { applyTextEdits } = await import('./text-edit')
|
||||||
|
const applied = await applyTextEdits(bytes, request.textEdits)
|
||||||
|
bytes = applied.bytes
|
||||||
|
skippedTextEdits = applied.skipped
|
||||||
|
}
|
||||||
|
if (request.imageEdits && request.imageEdits.length > 0) {
|
||||||
|
const { applyImageEdits } = await import('./image-edit')
|
||||||
|
const applied = await applyImageEdits(bytes, request.imageEdits)
|
||||||
|
bytes = applied.bytes
|
||||||
|
skippedImageEdits = applied.skipped
|
||||||
|
}
|
||||||
const pdfDoc = await PDFDocument.load(bytes, { updateMetadata: false })
|
const pdfDoc = await PDFDocument.load(bytes, { updateMetadata: false })
|
||||||
if (request.formValues.length > 0) applyFormValues(pdfDoc, request.formValues)
|
if (request.formValues.length > 0) applyFormValues(pdfDoc, request.formValues)
|
||||||
const pages = pdfDoc.getPages()
|
const pages = pdfDoc.getPages()
|
||||||
@@ -406,12 +498,20 @@ export async function applySaveRequest(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
return await pdfDoc.save({ useObjectStreams: false })
|
return {
|
||||||
|
bytes: await pdfDoc.save({ useObjectStreams: false }),
|
||||||
|
skippedTextEdits,
|
||||||
|
skippedImageEdits,
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Form values beyond WinAnsi (e.g. CJK) make pdf-lib's appearance generation fail:
|
// Form values beyond WinAnsi (e.g. CJK) make pdf-lib's appearance generation fail:
|
||||||
// skip it and set NeedAppearances so viewers rebuild them (Acrobat/pdfjs both support this)
|
// skip it and set NeedAppearances so viewers rebuild them (Acrobat/pdfjs both support this)
|
||||||
if (request.formValues.length === 0) throw err
|
if (request.formValues.length === 0) throw err
|
||||||
pdfDoc.getForm().acroForm.dict.set(PDFName.of('NeedAppearances'), PDFBool.True)
|
pdfDoc.getForm().acroForm.dict.set(PDFName.of('NeedAppearances'), PDFBool.True)
|
||||||
return await pdfDoc.save({ useObjectStreams: false, updateFieldAppearances: false })
|
return {
|
||||||
|
bytes: await pdfDoc.save({ useObjectStreams: false, updateFieldAppearances: false }),
|
||||||
|
skippedTextEdits,
|
||||||
|
skippedImageEdits,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user