Sync snapshot (2026-08-30) (#168)
- Docs: DOCX rendering fidelity - drop caps, hidden (vanish) runs, paragraph pattern shading, floating-table anchoring and clamping, footnote sizing, justified-line spacing - Docs: editing - page breaks split the paragraph correctly, URLs auto-linkify, Insert Hyperlink prefills from the selection, more stable table pagination - Sheets: large streamed workbooks are splittable and formula-capable for the AI; copy_range carries live formulas; range sort up to 200k cells; 1M-cell copies over 2x faster - Sheets: correctness - sort by raw values, shared-formula edits, typed cached strings, empty-string cells, note edits reach the save; risky structural deletes are rejected up front - Sheets: AI chat can export sheets as standalone files; the formula bar grows to fit wrapped formulas - Slides: right-to-left support - paragraph direction toggle, RTL tables, mirrored margins and bullets - Slides: rendering - scaled gradients, embedded fonts, complex-script shaping, chart plot layouts and legends, theme-override colors - Shell: open documents by dropping them onto the window; per-type document icons for OS file associations - AI: localized busy message for overloaded providers; degenerate tool loops stopped with a unified turn budget - Markdown: prompts to save before pasting images into untitled documents Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
co-authored by
GenOffice
parent
583a045212
commit
2239cce9e7
@@ -1,365 +0,0 @@
|
||||
/**
|
||||
* pptx rendering fidelity comparison pipeline.
|
||||
*
|
||||
* Reference side: LibreOffice headless (default) or PowerPoint for Mac (--ref powerpoint)
|
||||
* export to PDF → pdftoppm PNG per page (96dpi, 16:9 → 1280×720).
|
||||
* (PowerPoint AppleScript needs its first-run screens clicked through once per machine;
|
||||
* before that the process starts windowless and every apple event times out.)
|
||||
* Our side: playwright drives the packaged GenOffice Slides (Electron) with zoom locked at 100%,
|
||||
* clicks through the thumbnails page by page, and screenshots the canvas element .stage-rel.
|
||||
* Compare: pixelmatch per-pixel diff (bilinear-scaled to the same size first), emitting a side-by-side HTML report.
|
||||
*
|
||||
* Usage: node tools/fidelity-compare.mjs <a.pptx> [b.pptx …] [--max-slides N] [--out DIR] [--ref powerpoint]
|
||||
* Prereq: npm run build -w @genoffice/slides; brew: libreoffice + poppler (pdftoppm).
|
||||
*/
|
||||
/* global document, window, MouseEvent -- used inside page.evaluate() browser context */
|
||||
import { _electron as electron } from 'playwright-core'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import * as fs from 'node:fs'
|
||||
import * as os from 'node:os'
|
||||
import * as path from 'node:path'
|
||||
import { PNG } from 'pngjs'
|
||||
import pixelmatch from 'pixelmatch'
|
||||
|
||||
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..')
|
||||
const ELECTRON_BIN = path.join(
|
||||
ROOT,
|
||||
'node_modules/electron/dist/Electron.app/Contents/MacOS/Electron',
|
||||
)
|
||||
const APP_DIR = path.join(ROOT, 'apps/slides')
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
const files = []
|
||||
let maxSlides = 12
|
||||
let outDir = '/tmp/fidelity/run'
|
||||
let refKind = 'libreoffice'
|
||||
let refCache = null
|
||||
let pptTimeout = 120_000
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === '--max-slides') maxSlides = parseInt(args[++i], 10)
|
||||
else if (args[i] === '--out') outDir = args[++i]
|
||||
else if (args[i] === '--ref')
|
||||
refKind = args[++i] // libreoffice | powerpoint
|
||||
else if (args[i] === '--ref-cache')
|
||||
refCache = path.resolve(args[++i]) // previous run's outDir: reuse <cache>/<deck>/ref instead of re-exporting
|
||||
else if (args[i] === '--ppt-timeout') pptTimeout = parseInt(args[++i], 10)
|
||||
else files.push(path.resolve(args[i]))
|
||||
}
|
||||
if (!files.length) {
|
||||
console.error('usage: node tools/fidelity-compare.mjs <a.pptx> … [--max-slides N] [--out DIR]')
|
||||
process.exit(1)
|
||||
}
|
||||
fs.rmSync(outDir, { recursive: true, force: true })
|
||||
fs.mkdirSync(outDir, { recursive: true })
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
||||
|
||||
/**
|
||||
* Thumbnail indexes of visible slides, in presentation order. LibreOffice/PowerPoint skip
|
||||
* hidden slides (show="0") when exporting PDF, so the reference page k maps to thumbnail
|
||||
* visibleSlideIndexes(pptx)[k], not k.
|
||||
*/
|
||||
function visibleSlideIndexes(pptx) {
|
||||
const read = (entry) =>
|
||||
execFileSync('unzip', ['-p', pptx, entry], { maxBuffer: 64 * 1024 * 1024 }).toString('utf8')
|
||||
const rels = read('ppt/_rels/presentation.xml.rels')
|
||||
const relMap = {}
|
||||
for (const tag of rels.match(/<Relationship\b[^>]*>/g) ?? []) {
|
||||
const id = tag.match(/ Id="([^"]+)"/)?.[1]
|
||||
const target = tag.match(/ Target="([^"]+)"/)?.[1]
|
||||
if (id && target) relMap[id] = target
|
||||
}
|
||||
const pres = read('ppt/presentation.xml')
|
||||
const sldIds = [...pres.matchAll(/<p:sldId\b[^>]*r:id="([^"]+)"/g)].map((m) => m[1])
|
||||
const visible = []
|
||||
sldIds.forEach((rid, i) => {
|
||||
const target = relMap[rid]?.replace(/^\/?(ppt\/)?/, 'ppt/')
|
||||
if (!target) return
|
||||
const hidden = /<p:sld\b[^>]*\bshow="0"/.test(read(target).slice(0, 4096))
|
||||
if (!hidden) visible.push(i)
|
||||
})
|
||||
return { visible, total: sldIds.length }
|
||||
}
|
||||
|
||||
/** LibreOffice → PDF → PNG per page; returns the array of png paths. */
|
||||
function exportRef(pptx, dir) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
if (refKind === 'powerpoint') {
|
||||
exportPdfViaPowerPoint(pptx, path.join(dir, 'ref.pdf'))
|
||||
} else {
|
||||
execFileSync('soffice', ['--headless', '--convert-to', 'pdf', '--outdir', dir, pptx], {
|
||||
stdio: 'pipe',
|
||||
timeout: 120_000,
|
||||
})
|
||||
const pdf = path.join(dir, path.basename(pptx).replace(/\.pptx$/i, '.pdf'))
|
||||
if (!fs.existsSync(pdf)) throw new Error('soffice produced no pdf: ' + pdf)
|
||||
fs.renameSync(pdf, path.join(dir, 'ref.pdf'))
|
||||
}
|
||||
execFileSync('pdftoppm', ['-png', '-r', '96', path.join(dir, 'ref.pdf'), path.join(dir, 'ref')], {
|
||||
stdio: 'pipe',
|
||||
})
|
||||
return fs
|
||||
.readdirSync(dir)
|
||||
.filter((f) => /^ref-\d+\.png$/.test(f))
|
||||
.sort((a, b) => parseInt(a.match(/\d+/)[0], 10) - parseInt(b.match(/\d+/)[0], 10))
|
||||
.map((f) => path.join(dir, f))
|
||||
}
|
||||
|
||||
/**
|
||||
* PowerPoint for Mac → PDF via AppleScript. The file is copied into PowerPoint's sandbox
|
||||
* container so neither open nor save trips a TCC consent prompt. A modal dialog (e.g. repair
|
||||
* prompt on a corrupt deck) would hang osascript forever, so on timeout PowerPoint is killed
|
||||
* to unblock the remaining decks.
|
||||
*/
|
||||
function exportPdfViaPowerPoint(pptx, outPdf) {
|
||||
const box = path.join(
|
||||
process.env.HOME,
|
||||
'Library/Containers/com.microsoft.Powerpoint/Data/fidelity-tmp',
|
||||
)
|
||||
fs.mkdirSync(box, { recursive: true })
|
||||
const src = path.join(box, 'in.pptx')
|
||||
const pdf = path.join(box, 'out.pdf')
|
||||
// Stale Office owner-lock files (~$in.pptx, left by a killed save) make every
|
||||
// subsequent open fail with -9074 until removed
|
||||
for (const f of fs.readdirSync(path.dirname(src))) {
|
||||
if (f.startsWith('~$')) fs.rmSync(path.join(path.dirname(src), f), { force: true })
|
||||
}
|
||||
const script = `
|
||||
tell application "Microsoft PowerPoint"
|
||||
open (POSIX file "${src}")
|
||||
set p to active presentation
|
||||
save p in (POSIX file "${pdf}") as save as PDF
|
||||
close p saving no
|
||||
end tell`
|
||||
const killPpt = () => {
|
||||
try {
|
||||
execFileSync('pkill', ['-x', 'Microsoft PowerPoint'], { stdio: 'ignore' })
|
||||
} catch {
|
||||
/* no process to kill */
|
||||
}
|
||||
}
|
||||
const attempt = () => {
|
||||
fs.copyFileSync(pptx, src)
|
||||
fs.rmSync(pdf, { force: true })
|
||||
try {
|
||||
execFileSync('osascript', ['-e', script], { stdio: 'pipe', timeout: pptTimeout })
|
||||
} catch (e) {
|
||||
throw new Error('PowerPoint export failed: ' + (e.message ?? e), { cause: e })
|
||||
} finally {
|
||||
fs.rmSync(src, { force: true })
|
||||
}
|
||||
// A poison deck can leave PowerPoint alive but window-less; every later open
|
||||
// then fails with -9074, so any failure mode must kill before the next deck.
|
||||
if (!fs.existsSync(pdf)) throw new Error('PowerPoint produced no pdf')
|
||||
}
|
||||
try {
|
||||
attempt()
|
||||
} catch {
|
||||
killPpt()
|
||||
execFileSync('sleep', ['3'])
|
||||
try {
|
||||
attempt()
|
||||
} catch (e) {
|
||||
killPpt()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
fs.renameSync(pdf, outPdf)
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens GenOffice Slides and, page by page, composites the main canvas's Konva layers into a PNG
|
||||
* (in-page toDataURL, unaffected by window size/zoom/DPR; output = slide logical pixels 1280×720).
|
||||
*/
|
||||
async function shootOurs(pptx, dir, thumbIndexes) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
// Own userData → own single-instance lock: a dev run or the installed app must not kill the eval instance
|
||||
const userData =
|
||||
process.env.GENOFFICE_USER_DATA ?? path.join(os.tmpdir(), 'genoffice-fidelity-userdata')
|
||||
fs.mkdirSync(userData, { recursive: true })
|
||||
const app = await electron.launch({
|
||||
executablePath: ELECTRON_BIN,
|
||||
args: [APP_DIR, pptx],
|
||||
env: { ...process.env, GENOFFICE_USER_DATA: userData },
|
||||
timeout: 30_000,
|
||||
})
|
||||
try {
|
||||
const page =
|
||||
app.windows().find((w) => !w.url().startsWith('devtools://')) ?? (await app.firstWindow())
|
||||
// wait for the open to finish (thumbnails appear)
|
||||
for (let i = 0; i < 60; i++) {
|
||||
const n = await page.evaluate(() => document.querySelectorAll('.thumb').length)
|
||||
if (n > 0) break
|
||||
await sleep(500)
|
||||
}
|
||||
const total = await page.evaluate(() => document.querySelectorAll('.thumb').length)
|
||||
// Hide the "Click to add title" placeholder hints; the event re-renders the canvas
|
||||
// even on single-slide decks where no slide switch follows.
|
||||
await page.evaluate(() => {
|
||||
window.__genofficeHidePhPrompts = true
|
||||
window.dispatchEvent(new Event('genoffice:hide-ph-prompts'))
|
||||
})
|
||||
await sleep(300)
|
||||
const shots = []
|
||||
for (const idx of thumbIndexes.filter((i) => i < total)) {
|
||||
await page.evaluate((i) => {
|
||||
const thumbs = document.querySelectorAll('.thumb')
|
||||
thumbs[i]?.dispatchEvent(new MouseEvent('click', { bubbles: true }))
|
||||
}, idx)
|
||||
await sleep(600) // wait for image decode / repaint
|
||||
// Office-private FontFaces (doc-fonts.ts) may still be loading on first pages:
|
||||
// wait for the renderer's sync flag (bounded), then for the face loads it started
|
||||
for (let i = 0; i < 20; i++) {
|
||||
if (await page.evaluate(() => window.__genofficeDocFontsSynced !== false)) break
|
||||
await sleep(150)
|
||||
}
|
||||
await page.evaluate(() => document.fonts.ready).catch(() => {})
|
||||
const dataUrl = await page.evaluate(() => {
|
||||
const stage = document.querySelector('.stage-rel')
|
||||
if (!stage) return null
|
||||
const canvases = [...stage.querySelectorAll('canvas')]
|
||||
if (!canvases.length) return null
|
||||
const w = stage.clientWidth
|
||||
const h = stage.clientHeight
|
||||
const out = document.createElement('canvas')
|
||||
out.width = w
|
||||
out.height = h
|
||||
const ctx = out.getContext('2d')
|
||||
ctx.fillStyle = '#ffffff'
|
||||
ctx.fillRect(0, 0, w, h)
|
||||
// Each canvas is larger than the slide (CANVAS_BLEED ring for the page shadow) and
|
||||
// CSS-transformed by zoom; place it by its on-screen box mapped into slide-logical
|
||||
// coordinates so the output is exactly the slide rect at widthPx × heightPx.
|
||||
const sr = stage.getBoundingClientRect()
|
||||
for (const c of canvases) {
|
||||
const r = c.getBoundingClientRect()
|
||||
ctx.drawImage(
|
||||
c,
|
||||
((r.left - sr.left) * w) / sr.width,
|
||||
((r.top - sr.top) * h) / sr.height,
|
||||
(r.width * w) / sr.width,
|
||||
(r.height * h) / sr.height,
|
||||
)
|
||||
}
|
||||
return out.toDataURL('image/png')
|
||||
})
|
||||
if (!dataUrl) throw new Error('canvas compositing failed (thumb ' + (idx + 1) + ')')
|
||||
const f = path.join(dir, `ours-${shots.length + 1}.png`)
|
||||
fs.writeFileSync(f, Buffer.from(dataUrl.split(',')[1], 'base64'))
|
||||
shots.push(f)
|
||||
}
|
||||
return shots
|
||||
} finally {
|
||||
await app.close().catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
/** RGBA bilinear scaling. */
|
||||
function resize(png, w, h) {
|
||||
const out = new PNG({ width: w, height: h })
|
||||
for (let y = 0; y < h; y++) {
|
||||
const sy = (y * png.height) / h
|
||||
const y0 = Math.min(Math.floor(sy), png.height - 1)
|
||||
const y1 = Math.min(y0 + 1, png.height - 1)
|
||||
const fy = sy - y0
|
||||
for (let x = 0; x < w; x++) {
|
||||
const sx = (x * png.width) / w
|
||||
const x0 = Math.min(Math.floor(sx), png.width - 1)
|
||||
const x1 = Math.min(x0 + 1, png.width - 1)
|
||||
const fx = sx - x0
|
||||
for (let c = 0; c < 4; c++) {
|
||||
const p00 = png.data[(y0 * png.width + x0) * 4 + c]
|
||||
const p01 = png.data[(y0 * png.width + x1) * 4 + c]
|
||||
const p10 = png.data[(y1 * png.width + x0) * 4 + c]
|
||||
const p11 = png.data[(y1 * png.width + x1) * 4 + c]
|
||||
out.data[(y * w + x) * 4 + c] =
|
||||
p00 * (1 - fx) * (1 - fy) + p01 * fx * (1 - fy) + p10 * (1 - fx) * fy + p11 * fx * fy
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function diffPair(refPath, oursPath, diffPath) {
|
||||
const ref = PNG.sync.read(fs.readFileSync(refPath))
|
||||
let ours = PNG.sync.read(fs.readFileSync(oursPath))
|
||||
if (ours.width !== ref.width || ours.height !== ref.height)
|
||||
ours = resize(ours, ref.width, ref.height)
|
||||
const diff = new PNG({ width: ref.width, height: ref.height })
|
||||
const bad = pixelmatch(ref.data, ours.data, diff.data, ref.width, ref.height, { threshold: 0.18 })
|
||||
fs.writeFileSync(diffPath, PNG.sync.write(diff))
|
||||
return bad / (ref.width * ref.height)
|
||||
}
|
||||
|
||||
const rows = []
|
||||
for (const pptx of files) {
|
||||
const name = path.basename(pptx).replace(/\.pptx$/i, '')
|
||||
const deckDir = path.join(outDir, name)
|
||||
console.log(`\n=== ${name} ===`)
|
||||
let refs
|
||||
try {
|
||||
const cached = refCache && path.join(refCache, name, 'ref')
|
||||
if (
|
||||
cached &&
|
||||
fs.existsSync(cached) &&
|
||||
fs.readdirSync(cached).some((f) => /^ref-\d+\.png$/.test(f))
|
||||
) {
|
||||
fs.cpSync(cached, path.join(deckDir, 'ref'), { recursive: true })
|
||||
refs = fs
|
||||
.readdirSync(path.join(deckDir, 'ref'))
|
||||
.filter((f) => /^ref-\d+\.png$/.test(f))
|
||||
.sort((a, b) => parseInt(a.match(/\d+/)[0], 10) - parseInt(b.match(/\d+/)[0], 10))
|
||||
.map((f) => path.join(deckDir, 'ref', f))
|
||||
console.log(` reusing ${refs.length} cached reference page(s)`)
|
||||
} else {
|
||||
refs = exportRef(pptx, path.join(deckDir, 'ref'))
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('reference export failed:', e.message)
|
||||
continue
|
||||
}
|
||||
let visible
|
||||
try {
|
||||
const scan = visibleSlideIndexes(pptx)
|
||||
// LibreOffice omits hidden slides from the PDF; PowerPoint may include them. Trust the
|
||||
// page count: a full-length PDF means no mapping is needed.
|
||||
visible = refs.length >= scan.total ? refs.map((_, i) => i) : scan.visible
|
||||
if (visible.length < scan.total)
|
||||
console.log(
|
||||
` ${scan.total - visible.length} hidden slide(s) skipped to match the PDF export`,
|
||||
)
|
||||
} catch (e) {
|
||||
console.error(' visible-slide scan failed, assuming none hidden:', e.message)
|
||||
visible = refs.map((_, i) => i)
|
||||
}
|
||||
const n = Math.min(refs.length, visible.length, maxSlides)
|
||||
const ours = await shootOurs(pptx, path.join(deckDir, 'ours'), visible.slice(0, n))
|
||||
for (let i = 0; i < Math.min(n, ours.length); i++) {
|
||||
const diffPath = path.join(deckDir, `diff-${i + 1}.png`)
|
||||
const pct = diffPair(refs[i], ours[i], diffPath)
|
||||
rows.push({ deck: name, slide: i + 1, pct, ref: refs[i], ours: ours[i], diff: diffPath })
|
||||
console.log(` slide ${i + 1}: mismatch ${(pct * 100).toFixed(1)}%`)
|
||||
}
|
||||
}
|
||||
|
||||
// HTML report
|
||||
const rel = (p) => path.relative(outDir, p)
|
||||
const html = `<!doctype html><meta charset="utf-8"><title>pptx fidelity comparison</title>
|
||||
<style>body{font:13px -apple-system,sans-serif;margin:16px;background:#f6f6f8}
|
||||
h2{margin:24px 0 8px}table{border-collapse:collapse}td{padding:4px;vertical-align:top;text-align:center}
|
||||
img{width:420px;border:1px solid #ccc;background:#fff}
|
||||
.pct{font-weight:600}.bad{color:#c00}.ok{color:#080}</style>
|
||||
<h1>pptx fidelity comparison (reference: ${refKind})</h1>
|
||||
${rows
|
||||
.map(
|
||||
(r) => `
|
||||
<h2>${r.deck} · slide ${r.slide} · <span class="pct ${r.pct > 0.08 ? 'bad' : 'ok'}">${(r.pct * 100).toFixed(1)}% mismatch</span></h2>
|
||||
<table><tr><td>reference<br><img src="${rel(r.ref)}"></td><td>GenOffice Slides<br><img src="${rel(r.ours)}"></td><td>diff<br><img src="${rel(r.diff)}"></td></tr></table>`,
|
||||
)
|
||||
.join('')}
|
||||
`
|
||||
fs.writeFileSync(path.join(outDir, 'report.html'), html)
|
||||
console.log('\nreport →', path.join(outDir, 'report.html'))
|
||||
const worst = [...rows].sort((a, b) => b.pct - a.pct).slice(0, 8)
|
||||
console.log('worst slides:')
|
||||
for (const r of worst) console.log(` ${r.deck} #${r.slide}: ${(r.pct * 100).toFixed(1)}%`)
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Generates the per-file-type document icons that electron-builder bakes into
|
||||
* the OS file associations (apps/shell/electron-builder.cjs fileAssociations
|
||||
* `icon` field): <type>.icns for the macOS CFBundleDocumentTypes entry and
|
||||
* <type>.ico for the NSIS DefaultIcon registry value.
|
||||
*
|
||||
* Source of truth is the shell renderer's file-type tiles
|
||||
* (apps/shell/src/renderer/src/assets/file-*.svg) so Finder/Explorer show the
|
||||
* same visual language as the in-app recent-files list. The SVGs are
|
||||
* rasterized with the system Chrome via Playwright (transparent background),
|
||||
* then packed with `iconutil` (icns, macOS host only) and a hand-rolled
|
||||
* PNG-entry ICO container.
|
||||
*
|
||||
* Regenerate after changing any file-*.svg:
|
||||
* node tools/gen-file-association-icons.mjs
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { chromium } from 'playwright'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const svgDir = join(root, 'apps/shell/src/renderer/src/assets')
|
||||
const outDir = join(root, 'apps/shell/build')
|
||||
|
||||
// One icon per visual type; associations for xlsm/xls/csv/markdown reuse
|
||||
// these via the fileAssociations `icon` field.
|
||||
const TYPES = {
|
||||
docx: 'file-docx.svg',
|
||||
xlsx: 'file-xlsx.svg',
|
||||
pptx: 'file-pptx.svg',
|
||||
pdf: 'file-pdf.svg',
|
||||
md: 'file-md.svg',
|
||||
}
|
||||
|
||||
// macOS icons carry the standard app-icon grid margin (824/1024 content, same
|
||||
// treatment as build/icon-mac.png) so they sit at the same optical size as
|
||||
// neighboring icons in Finder. Windows icons are conventionally full-bleed.
|
||||
const MAC_CONTENT_RATIO = 824 / 1024
|
||||
// canvas px -> .iconset entry names (16..1024 covers all @1x/@2x slots below)
|
||||
const MAC_CANVAS_SIZES = [16, 32, 64, 128, 256, 512, 1024]
|
||||
const ICONSET_ENTRIES = [
|
||||
['icon_16x16.png', 16],
|
||||
['icon_16x16@2x.png', 32],
|
||||
['icon_32x32.png', 32],
|
||||
['icon_32x32@2x.png', 64],
|
||||
['icon_128x128.png', 128],
|
||||
['icon_128x128@2x.png', 256],
|
||||
['icon_256x256.png', 256],
|
||||
['icon_256x256@2x.png', 512],
|
||||
['icon_512x512.png', 512],
|
||||
['icon_512x512@2x.png', 1024],
|
||||
]
|
||||
const WIN_SIZES = [16, 24, 32, 48, 64, 128, 256]
|
||||
|
||||
/** ICO container with PNG-compressed entries (supported since Vista). */
|
||||
function buildIco(entries) {
|
||||
const header = Buffer.alloc(6)
|
||||
header.writeUInt16LE(0, 0)
|
||||
header.writeUInt16LE(1, 2) // type: icon
|
||||
header.writeUInt16LE(entries.length, 4)
|
||||
const dir = Buffer.alloc(16 * entries.length)
|
||||
let offset = header.length + dir.length
|
||||
entries.forEach(({ size, png }, i) => {
|
||||
const o = i * 16
|
||||
dir.writeUInt8(size >= 256 ? 0 : size, o) // 0 means 256
|
||||
dir.writeUInt8(size >= 256 ? 0 : size, o + 1)
|
||||
dir.writeUInt8(0, o + 2) // palette
|
||||
dir.writeUInt8(0, o + 3) // reserved
|
||||
dir.writeUInt16LE(1, o + 4) // planes
|
||||
dir.writeUInt16LE(32, o + 6) // bpp
|
||||
dir.writeUInt32LE(png.length, o + 8)
|
||||
dir.writeUInt32LE(offset, o + 12)
|
||||
offset += png.length
|
||||
})
|
||||
return Buffer.concat([header, dir, ...entries.map((e) => e.png)])
|
||||
}
|
||||
|
||||
async function renderPng(page, svgDataUrl, canvasSize, contentSize) {
|
||||
await page.setViewportSize({ width: canvasSize, height: canvasSize })
|
||||
await page.setContent(
|
||||
`<body style="margin:0"><div style="width:${canvasSize}px;height:${canvasSize}px;display:flex;align-items:center;justify-content:center">` +
|
||||
`<img src="${svgDataUrl}" style="width:${contentSize}px;height:${contentSize}px"></div></body>`,
|
||||
)
|
||||
return page.screenshot({ omitBackground: true })
|
||||
}
|
||||
|
||||
const browser = await chromium.launch({ channel: 'chrome', headless: true })
|
||||
const page = await browser.newPage({ deviceScaleFactor: 1 })
|
||||
const tmp = mkdtempSync(join(tmpdir(), 'genoffice-file-icons-'))
|
||||
|
||||
try {
|
||||
for (const [type, svgName] of Object.entries(TYPES)) {
|
||||
const svg = readFileSync(join(svgDir, svgName))
|
||||
const dataUrl = `data:image/svg+xml;base64,${svg.toString('base64')}`
|
||||
|
||||
const macPngs = new Map()
|
||||
for (const size of MAC_CANVAS_SIZES) {
|
||||
macPngs.set(size, await renderPng(page, dataUrl, size, Math.round(size * MAC_CONTENT_RATIO)))
|
||||
}
|
||||
const iconset = join(tmp, `${type}.iconset`)
|
||||
mkdirSync(iconset, { recursive: true })
|
||||
for (const [name, size] of ICONSET_ENTRIES) {
|
||||
writeFileSync(join(iconset, name), macPngs.get(size))
|
||||
}
|
||||
execFileSync('iconutil', ['-c', 'icns', iconset, '-o', join(outDir, `${type}.icns`)])
|
||||
|
||||
const winEntries = []
|
||||
for (const size of WIN_SIZES) {
|
||||
winEntries.push({ size, png: await renderPng(page, dataUrl, size, size) })
|
||||
}
|
||||
writeFileSync(join(outDir, `${type}.ico`), buildIco(winEntries))
|
||||
|
||||
console.log(`generated ${type}.icns + ${type}.ico`)
|
||||
}
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
await browser.close()
|
||||
}
|
||||
@@ -1,493 +0,0 @@
|
||||
/**
|
||||
* xlsx rendering fidelity comparison pipeline (sheets counterpart of fidelity-compare.mjs).
|
||||
*
|
||||
* Reference side: Microsoft Excel for Mac via AppleScript → PDF → pdftoppm PNG (96dpi).
|
||||
* The file is copied into Excel's sandbox container to avoid TCC prompts; osascript runs
|
||||
* under a timeout and Excel is killed on hang (modal repair prompts on corrupt files).
|
||||
* `save as active sheet` still exports the whole workbook, so the comparison scope is
|
||||
* PDF page 1 ↔ the sheet active on open (fine for single-sheet/content-on-sheet-1 samples).
|
||||
* Our side: playwright drives the built shell (apps/shell/out) with the xlsx as argv,
|
||||
* waits for the sheets view, composites the Univer canvases and crops off the
|
||||
* row/column headers so the crop matches the print output's content-only framing.
|
||||
* Compare: pixelmatch (weak signal here — print layout vs grid viewport never aligns
|
||||
* pixel-perfectly; the HTML report's side-by-side is the primary artifact).
|
||||
*
|
||||
* Usage: node tools/sheets-fidelity-compare.mjs <a.xlsx> [b.xlsx …] [--out DIR]
|
||||
* Prereq: npm run build:all; brew: poppler (pdftoppm); Excel launched manually once.
|
||||
*/
|
||||
/* global document, window, PointerEvent */
|
||||
import { _electron as electron } from 'playwright-core'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import * as fs from 'node:fs'
|
||||
import * as os from 'node:os'
|
||||
import * as path from 'node:path'
|
||||
import { PNG } from 'pngjs'
|
||||
import pixelmatch from 'pixelmatch'
|
||||
|
||||
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..')
|
||||
const ELECTRON_BIN = path.join(
|
||||
ROOT,
|
||||
'node_modules/electron/dist/Electron.app/Contents/MacOS/Electron',
|
||||
)
|
||||
const SHELL_DIR = path.join(ROOT, 'apps/shell')
|
||||
const EXCEL_BOX = path.join(
|
||||
process.env.HOME,
|
||||
'Library/Containers/com.microsoft.Excel/Data/fidelity-tmp',
|
||||
)
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
const files = []
|
||||
let outDir = '/tmp/sheets-fidelity/run'
|
||||
let keep = false
|
||||
let reshoot = false
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === '--out') outDir = args[++i]
|
||||
else if (args[i] === '--keep') keep = true
|
||||
else if (args[i] === '--reshoot') reshoot = true
|
||||
else files.push(path.resolve(args[i]))
|
||||
}
|
||||
if (!files.length) {
|
||||
console.error(
|
||||
'usage: node tools/sheets-fidelity-compare.mjs <a.xlsx> … [--out DIR] [--keep] [--reshoot]',
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
if (!keep && !reshoot) fs.rmSync(outDir, { recursive: true, force: true })
|
||||
fs.mkdirSync(outDir, { recursive: true })
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
||||
|
||||
/**
|
||||
* Sheet names in workbook order with visibility. The whole-workbook PDF
|
||||
* starts from the first visible sheet Excel actually prints — empty sheets
|
||||
* produce no page — so `active` marks the first visible sheet with any cell,
|
||||
* the one our side must show to compare against PDF page 1.
|
||||
*/
|
||||
function sheetInfo(xlsx) {
|
||||
try {
|
||||
const wb = execFileSync('unzip', ['-p', xlsx, 'xl/workbook.xml'], {
|
||||
maxBuffer: 64e6,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
}).toString()
|
||||
const rels = execFileSync('unzip', ['-p', xlsx, 'xl/_rels/workbook.xml.rels'], {
|
||||
maxBuffer: 64e6,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
}).toString()
|
||||
// Attribute order varies by writer (some put Target before Id).
|
||||
const relTargets = Object.fromEntries(
|
||||
[...rels.matchAll(/<Relationship [^>]*>/g)]
|
||||
.map((m) => [m[0].match(/ Id="([^"]+)"/)?.[1], m[0].match(/ Target="([^"]+)"/)?.[1]])
|
||||
.filter(([id, target]) => id && target),
|
||||
)
|
||||
const sheets = [...wb.matchAll(/<sheet [^>]*>/g)].map((m) => ({
|
||||
name: m[0]
|
||||
.match(/ name="([^"]+)"/)[1]
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"'),
|
||||
visible: !/ state="(hidden|veryHidden)"/.test(m[0]),
|
||||
relId: m[0].match(/ r:id="([^"]+)"/)?.[1],
|
||||
active: false,
|
||||
}))
|
||||
const hasCells = (sheet) => {
|
||||
const target = relTargets[sheet.relId]
|
||||
if (!target) return true // unknown mapping: assume printable
|
||||
const part = target.replace(/^\/?(xl\/)?/, 'xl/').replace('xl/./', 'xl/')
|
||||
try {
|
||||
const xml = execFileSync('unzip', ['-p', xlsx, part], {
|
||||
maxBuffer: 256e6,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
}).toString()
|
||||
return /<c[ >]/.test(xml)
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
const target = sheets.find((s) => s.visible && hasCells(s)) ?? sheets.find((s) => s.visible)
|
||||
if (target) {
|
||||
target.active = true
|
||||
const part = relTargets[target.relId]?.replace(/^\/?(xl\/)?/, 'xl/').replace('xl/./', 'xl/')
|
||||
if (part) {
|
||||
try {
|
||||
const xml = execFileSync('unzip', ['-p', xlsx, part], {
|
||||
maxBuffer: 256e6,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
}).toString()
|
||||
target.rightToLeft = /<sheetView [^>]*rightToLeft="(1|true)"/.test(xml)
|
||||
} catch {
|
||||
/* keep undefined */
|
||||
}
|
||||
}
|
||||
}
|
||||
return sheets
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** Excel → PDF → PNGs; returns png paths. Kills Excel on osascript timeout. */
|
||||
function exportRef(xlsx, dir) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
fs.mkdirSync(EXCEL_BOX, { recursive: true })
|
||||
const src = path.join(EXCEL_BOX, 'in.xlsx')
|
||||
const pdf = path.join(EXCEL_BOX, 'out.pdf')
|
||||
fs.copyFileSync(xlsx, src)
|
||||
fs.rmSync(pdf, { force: true })
|
||||
const script = `
|
||||
tell application "Microsoft Excel"
|
||||
set display alerts to false
|
||||
open workbook workbook file name "${src}" update links do not update links
|
||||
set wb to active workbook
|
||||
save workbook as wb filename "${pdf}" file format PDF file format
|
||||
close active workbook saving no
|
||||
end tell`
|
||||
try {
|
||||
execFileSync('osascript', ['-e', script], { stdio: 'pipe', timeout: 120_000 })
|
||||
} catch (e) {
|
||||
try {
|
||||
execFileSync('pkill', ['-x', 'Microsoft Excel'], { stdio: 'ignore' })
|
||||
} catch {
|
||||
/* no process to kill */
|
||||
}
|
||||
throw new Error('Excel export failed: ' + (e.stderr?.toString() || e.message), { cause: e })
|
||||
} finally {
|
||||
fs.rmSync(src, { force: true })
|
||||
}
|
||||
if (!fs.existsSync(pdf)) throw new Error('Excel produced no pdf')
|
||||
fs.renameSync(pdf, path.join(dir, 'ref.pdf'))
|
||||
execFileSync('pdftoppm', ['-png', '-r', '96', path.join(dir, 'ref.pdf'), path.join(dir, 'ref')], {
|
||||
stdio: 'pipe',
|
||||
})
|
||||
return fs
|
||||
.readdirSync(dir)
|
||||
.filter((f) => /^ref-\d+\.png$/.test(f))
|
||||
.sort((a, b) => parseInt(a.match(/\d+/)[0], 10) - parseInt(b.match(/\d+/)[0], 10))
|
||||
.map((f) => path.join(dir, f))
|
||||
}
|
||||
|
||||
/**
|
||||
* Launch the shell with the xlsx as argv, wait for the sheets view (footer sheet tabs are
|
||||
* DOM — any sheet name in body.textContent means the load finished), composite the Univer
|
||||
* canvases and crop the row/col header band (46×24 CSS px at the canvas's own scale).
|
||||
*/
|
||||
async function shootOurs(xlsx, dir, sheets) {
|
||||
const names = sheets.map((s) => s.name)
|
||||
const firstVisible = sheets.find((s) => s.active)?.name
|
||||
// RTL sheets put the row-header strip on the RIGHT — crop that side instead.
|
||||
const rightToLeft = sheets.find((s) => s.active)?.rightToLeft === true
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'genoffice-fidelity-'))
|
||||
const app = await electron.launch({
|
||||
executablePath: ELECTRON_BIN,
|
||||
args: [SHELL_DIR, xlsx],
|
||||
env: {
|
||||
...process.env,
|
||||
GENOFFICE_USER_DATA: userDataDir,
|
||||
AI_OFFICE_USER_DATA: userDataDir,
|
||||
GENOFFICE_LANG: 'en',
|
||||
},
|
||||
timeout: 30_000,
|
||||
})
|
||||
try {
|
||||
// the sheets editor is a WebContentsView that appears as its own page
|
||||
let page
|
||||
const deadline = Date.now() + 30_000
|
||||
while (!page) {
|
||||
for (const w of app.windows()) {
|
||||
const href = await w.evaluate(() => window.location.href).catch(() => '')
|
||||
if (href.includes('sheets/out')) page = w
|
||||
}
|
||||
if (page) break
|
||||
if (Date.now() > deadline) throw new Error('sheets view never appeared')
|
||||
await app.waitForEvent('window', { timeout: 1_000 }).catch(() => {})
|
||||
}
|
||||
await app.evaluate(({ BrowserWindow }) => {
|
||||
BrowserWindow.getAllWindows()[0]?.setBounds({ x: 0, y: 0, width: 1600, height: 1000 })
|
||||
})
|
||||
for (let i = 0; i < 80; i++) {
|
||||
const loaded = await page
|
||||
.evaluate(
|
||||
(ns) =>
|
||||
!!document.querySelector('#univer-container canvas') &&
|
||||
(ns.length === 0 || ns.some((n) => document.body.textContent.includes(n))),
|
||||
names,
|
||||
)
|
||||
.catch(() => false)
|
||||
if (loaded) break
|
||||
await sleep(500)
|
||||
}
|
||||
// PDF page 1 comes from the sheet Excel had active on open (activeTab), but our
|
||||
// side may land elsewhere — click the matching footer tab so both sides align.
|
||||
// The app can activate a later sheet moments AFTER load looks done, overriding an
|
||||
// early click (and an early "already active" read is equally untrustworthy), so
|
||||
// keep clicking until the tab reads active on two consecutive one-second checks.
|
||||
// Clicking a sheet tab while the workbook is still indexing desyncs the tab
|
||||
// highlight from the grid canvas (the tab reads active but the canvas keeps the
|
||||
// stored activeTab). The lazy loader's status line reads "Indexing …" while the
|
||||
// worksheet part streams in and flips to a lingering "Streaming …" once indexing
|
||||
// completes, so wait for that flip — with a short stability grace because the
|
||||
// first status can appear a beat after load looks done, and non-lazy books never
|
||||
// show either marker.
|
||||
let calm = 0
|
||||
for (let i = 0; i < 120 && calm < 3; i++) {
|
||||
const status = await page
|
||||
.evaluate(() => {
|
||||
const text = document.body.textContent
|
||||
return text.includes('Streaming') ? 'done' : text.includes('Indexing') ? 'busy' : 'idle'
|
||||
})
|
||||
.catch(() => 'idle')
|
||||
if (status === 'done') break
|
||||
calm = status === 'idle' ? calm + 1 : 0
|
||||
if (calm < 3) await sleep(500)
|
||||
}
|
||||
// Sheet names can carry trailing spaces in workbook.xml while the tab DOM trims
|
||||
// them, so compare both sides trimmed.
|
||||
const wanted = firstVisible?.trim()
|
||||
const isActive = () =>
|
||||
page
|
||||
.evaluate((n) => {
|
||||
const tab = [...document.querySelectorAll('span.univer-truncate')].find(
|
||||
(el) => el.textContent.trim() === n,
|
||||
)
|
||||
const holder = tab?.closest('[class*="cursor-pointer"]')
|
||||
return !!holder && /univer-bg-white/.test(holder.className)
|
||||
}, wanted)
|
||||
.catch(() => false)
|
||||
const settle = async () => {
|
||||
let settled = 0
|
||||
for (let attempt = 0; attempt < 10 && settled < 2; attempt++) {
|
||||
const active = await page
|
||||
.evaluate((n) => {
|
||||
const tabs = [...document.querySelectorAll('span.univer-truncate')].filter((el) =>
|
||||
el.textContent.trim(),
|
||||
)
|
||||
const target = tabs.find((el) => el.textContent.trim() === n)
|
||||
if (!target) return false
|
||||
const holder = target.closest('[class*="cursor-pointer"]')
|
||||
if (holder && /univer-bg-white/.test(holder.className)) return true
|
||||
holder?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))
|
||||
target.click()
|
||||
return false
|
||||
}, wanted)
|
||||
.catch(() => false)
|
||||
settled = active ? settled + 1 : 0
|
||||
if (settled < 2) await sleep(1_000)
|
||||
}
|
||||
}
|
||||
if (wanted) {
|
||||
// A slow workbook can self-activate its stored activeTab long after the settle
|
||||
// loop passed, flipping the sheet mid-wait — hold until the target tab survives
|
||||
// a full paint wait, so every settle is followed by one before the shot.
|
||||
for (let round = 0; round < 5; round++) {
|
||||
await settle()
|
||||
await sleep(3_000) // canvas paint, chart/image async render
|
||||
if (await isActive()) break
|
||||
}
|
||||
} else {
|
||||
await sleep(3_000) // canvas paint, chart/image async render
|
||||
}
|
||||
// park the selection in the viewport's bottom-right corner so the A1 highlight
|
||||
// doesn't sit on top of the content being compared. The point must hit the
|
||||
// grid canvas itself: a drawing overlay (picture/chart DOM) would swallow
|
||||
// the click, select the drawing, and leave the load-time selection behind.
|
||||
{
|
||||
const box = await page
|
||||
.evaluate((rtl) => {
|
||||
const c = [...document.querySelectorAll('#univer-container canvas')].find(
|
||||
(x) => x.width > 200 && x.height > 200,
|
||||
)
|
||||
if (!c) return null
|
||||
const r = c.getBoundingClientRect()
|
||||
for (let dx = 50; dx < r.width - 100; dx += 120) {
|
||||
for (const dy of [50, 170, 290]) {
|
||||
// The far corner is bottom-left on a mirrored sheet (and the
|
||||
// right edge hosts the header strip + scrollbar there).
|
||||
const x = rtl ? r.left + dx : r.right - dx
|
||||
const y = r.bottom - dy
|
||||
const hit = document.elementFromPoint(x, y)
|
||||
// Univer stacks several canvases; any of them means "the grid".
|
||||
if (hit && hit.tagName === 'CANVAS' && hit.closest('#univer-container')) {
|
||||
return { x, y }
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}, rightToLeft)
|
||||
.catch(() => null)
|
||||
if (box) {
|
||||
await page.mouse.click(box.x, box.y).catch(() => {})
|
||||
await sleep(400)
|
||||
}
|
||||
}
|
||||
// Last line of defense: a late self-activation can land between the settle
|
||||
// rounds and the shot (it cost prod_008 a whole run) — re-check the tab
|
||||
// right before the screenshot and re-settle once if it flipped.
|
||||
if (wanted && !(await isActive())) {
|
||||
await settle()
|
||||
await sleep(3_000)
|
||||
}
|
||||
// Native screenshot clipped to the grid area. Charts, pictures, shapes
|
||||
// and text boxes render as a DOM overlay (WorkbookVisuals), not into the
|
||||
// Univer canvases — a canvas-only composite silently drops the whole
|
||||
// drawing layer (run1/run5 mis-triaged it as "never rendered").
|
||||
const clip = await page.evaluate((rtl) => {
|
||||
const c = [...document.querySelectorAll('#univer-container canvas')].find(
|
||||
(x) => x.width > 200 && x.height > 200,
|
||||
)
|
||||
if (!c) return null
|
||||
const r = c.getBoundingClientRect()
|
||||
return {
|
||||
x: r.left + (rtl ? 0 : 46),
|
||||
y: r.top + 24,
|
||||
width: r.width - 46,
|
||||
height: r.height - 24,
|
||||
}
|
||||
}, rightToLeft)
|
||||
if (!clip) throw new Error('grid canvas not found')
|
||||
const f = path.join(dir, 'ours-1.png')
|
||||
await page.screenshot({ path: f, clip })
|
||||
return [f]
|
||||
} finally {
|
||||
await app.close().catch(() => app.process().kill())
|
||||
fs.rmSync(userDataDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** RGBA bilinear scaling. */
|
||||
function resize(png, w, h) {
|
||||
const out = new PNG({ width: w, height: h })
|
||||
for (let y = 0; y < h; y++) {
|
||||
const sy = (y * png.height) / h
|
||||
const y0 = Math.min(Math.floor(sy), png.height - 1)
|
||||
const y1 = Math.min(y0 + 1, png.height - 1)
|
||||
const fy = sy - y0
|
||||
for (let x = 0; x < w; x++) {
|
||||
const sx = (x * png.width) / w
|
||||
const x0 = Math.min(Math.floor(sx), png.width - 1)
|
||||
const x1 = Math.min(x0 + 1, png.width - 1)
|
||||
const fx = sx - x0
|
||||
for (let c = 0; c < 4; c++) {
|
||||
const p00 = png.data[(y0 * png.width + x0) * 4 + c]
|
||||
const p01 = png.data[(y0 * png.width + x1) * 4 + c]
|
||||
const p10 = png.data[(y1 * png.width + x0) * 4 + c]
|
||||
const p11 = png.data[(y1 * png.width + x1) * 4 + c]
|
||||
out.data[(y * w + x) * 4 + c] =
|
||||
p00 * (1 - fx) * (1 - fy) + p01 * fx * (1 - fy) + p10 * (1 - fx) * fy + p11 * fx * fy
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function diffPair(refPath, oursPath, diffPath) {
|
||||
const ref = PNG.sync.read(fs.readFileSync(refPath))
|
||||
let ours = PNG.sync.read(fs.readFileSync(oursPath))
|
||||
if (ours.width !== ref.width || ours.height !== ref.height)
|
||||
ours = resize(ours, ref.width, ref.height)
|
||||
const diff = new PNG({ width: ref.width, height: ref.height })
|
||||
const bad = pixelmatch(ref.data, ours.data, diff.data, ref.width, ref.height, { threshold: 0.18 })
|
||||
fs.writeFileSync(diffPath, PNG.sync.write(diff))
|
||||
return bad / (ref.width * ref.height)
|
||||
}
|
||||
|
||||
const rows = []
|
||||
for (const xlsx of files) {
|
||||
const name = path.basename(xlsx).replace(/\.xlsx$/i, '')
|
||||
const fileDir = path.join(outDir, name)
|
||||
console.log(`\n=== ${name} ===`)
|
||||
if (keep) {
|
||||
const cachedRefDir = path.join(fileDir, 'ref')
|
||||
// pdftoppm zero-pads page numbers on multi-page refs (ref-01.png).
|
||||
const refPages = fs.existsSync(cachedRefDir)
|
||||
? fs
|
||||
.readdirSync(cachedRefDir)
|
||||
.filter((f) => /^ref-\d+\.png$/.test(f))
|
||||
.sort((a, b) => parseInt(a.match(/\d+/)[0], 10) - parseInt(b.match(/\d+/)[0], 10))
|
||||
: []
|
||||
const cachedOurs = path.join(fileDir, 'ours', 'ours-1.png')
|
||||
if (refPages.length && fs.existsSync(cachedOurs)) {
|
||||
const cachedRef = path.join(cachedRefDir, refPages[0])
|
||||
const diffPath = path.join(fileDir, 'diff-1.png')
|
||||
const pct = diffPair(cachedRef, cachedOurs, diffPath)
|
||||
rows.push({
|
||||
file: name,
|
||||
pct,
|
||||
pages: refPages.length,
|
||||
ref: cachedRef,
|
||||
ours: cachedOurs,
|
||||
diff: diffPath,
|
||||
})
|
||||
console.log(` cached: mismatch ${(pct * 100).toFixed(1)}%`)
|
||||
continue
|
||||
}
|
||||
}
|
||||
const sheets = sheetInfo(xlsx)
|
||||
let refs
|
||||
const refDir = path.join(fileDir, 'ref')
|
||||
const cachedRefs = reshoot
|
||||
? fs.existsSync(refDir)
|
||||
? fs
|
||||
.readdirSync(refDir)
|
||||
.filter((f) => /^ref-\d+\.png$/.test(f))
|
||||
.sort((a, b) => parseInt(a.match(/\d+/)[0], 10) - parseInt(b.match(/\d+/)[0], 10))
|
||||
.map((f) => path.join(refDir, f))
|
||||
: []
|
||||
: []
|
||||
try {
|
||||
// --reshoot: keep the Excel reference from a previous run (no Excel
|
||||
// round-trip), redo only the GenOffice shot and the diff.
|
||||
refs = cachedRefs.length ? cachedRefs : exportRef(xlsx, refDir)
|
||||
} catch (e) {
|
||||
console.error(' reference export failed:', e.message.split('\n')[0])
|
||||
rows.push({ file: name, error: 'ref: ' + e.message.split('\n')[0] })
|
||||
continue
|
||||
}
|
||||
let ours
|
||||
try {
|
||||
ours = await shootOurs(xlsx, path.join(fileDir, 'ours'), sheets)
|
||||
} catch (e) {
|
||||
console.error(' genoffice shot failed:', e.message.split('\n')[0])
|
||||
rows.push({ file: name, error: 'ours: ' + e.message.split('\n')[0] })
|
||||
continue
|
||||
}
|
||||
const diffPath = path.join(fileDir, 'diff-1.png')
|
||||
const pct = diffPair(refs[0], ours[0], diffPath)
|
||||
rows.push({ file: name, pct, pages: refs.length, ref: refs[0], ours: ours[0], diff: diffPath })
|
||||
console.log(` page 1: mismatch ${(pct * 100).toFixed(1)}% (ref pages: ${refs.length})`)
|
||||
}
|
||||
|
||||
const rel = (p) => path.relative(outDir, p)
|
||||
const html = `<!doctype html><meta charset="utf-8"><title>xlsx fidelity comparison</title>
|
||||
<style>body{font:13px -apple-system,sans-serif;margin:16px;background:#f6f6f8}
|
||||
h2{margin:24px 0 8px}table{border-collapse:collapse}td{padding:4px;vertical-align:top;text-align:center}
|
||||
img{width:420px;border:1px solid #ccc;background:#fff}
|
||||
.pct{font-weight:600}.bad{color:#c00}.ok{color:#080}.err{color:#c00;font-weight:600}</style>
|
||||
<h1>xlsx fidelity comparison (reference: Excel)</h1>
|
||||
${rows
|
||||
.map((r) =>
|
||||
r.error
|
||||
? `<h2>${r.file} · <span class="err">${r.error}</span></h2>`
|
||||
: `
|
||||
<h2>${r.file} · <span class="pct ${r.pct > 0.2 ? 'bad' : 'ok'}">${(r.pct * 100).toFixed(1)}% mismatch</span> · ${r.pages} ref page(s)</h2>
|
||||
<table><tr><td>Excel<br><img src="${rel(r.ref)}"></td><td>GenOffice Sheets<br><img src="${rel(r.ours)}"></td><td>diff<br><img src="${rel(r.diff)}"></td></tr></table>`,
|
||||
)
|
||||
.join('')}
|
||||
`
|
||||
fs.writeFileSync(path.join(outDir, 'report.html'), html)
|
||||
fs.writeFileSync(
|
||||
path.join(outDir, 'summary.json'),
|
||||
JSON.stringify(
|
||||
rows.map(({ file, pct, pages, error }) => ({ file, pct, pages, error })),
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
console.log('\nreport →', path.join(outDir, 'report.html'))
|
||||
const worst = rows
|
||||
.filter((r) => !r.error)
|
||||
.sort((a, b) => b.pct - a.pct)
|
||||
.slice(0, 10)
|
||||
console.log('worst files:')
|
||||
for (const r of worst) console.log(` ${r.file}: ${(r.pct * 100).toFixed(1)}%`)
|
||||
console.log('errors:', rows.filter((r) => r.error).length)
|
||||
Reference in New Issue
Block a user