fix(markdown): add paginated PNG export with resilient image loading (#476)
* fix(markdown): render pasted formulas and export pages as PNG * fix(markdown): tolerate broken export images and split math paste work * style(markdown): format PNG export regression fixture * fix(html2docx): narrow optional page background screenshot IDs --------- Co-authored-by: merrick-2002 <merrick@mainfunc.ai>
This commit is contained in:
@@ -208,7 +208,7 @@ jobs:
|
||||
- name: Install Chromium for layout tests
|
||||
run: npx playwright install chromium
|
||||
|
||||
- name: Markdown opt-in round-trip browser tests
|
||||
- name: Markdown browser tests
|
||||
run: npx playwright test --config apps/markdown/playwright.config.ts
|
||||
|
||||
# Electron needs a display server on Linux runners. DEBUG=pw:browser
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"katex": "^0.16.47",
|
||||
"json5": "^2.2.3",
|
||||
"mermaid": "^11.17.2",
|
||||
"wavedrom": "^3.7.0"
|
||||
"wavedrom": "^3.7.0",
|
||||
"pdfjs-dist": "^6.2.108"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ const port = Number(process.env.MARKDOWN_DEV_PORT) || 5177
|
||||
/** Browser-only renderer coverage: it must not boot the Electron shell. */
|
||||
export default defineConfig({
|
||||
testDir: './tests/browser',
|
||||
testMatch: 'roundtrip-serializer.spec.ts',
|
||||
testMatch: '*.spec.ts',
|
||||
outputDir: '../../test-results/markdown-roundtrip',
|
||||
timeout: 30_000,
|
||||
workers: 1,
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
|
||||
/** Only dialog-approved folders are registered; renderers never supply output paths. */
|
||||
export class ImageExportSessions {
|
||||
private sessions = new Map<string, { owner: number; dir: string; pages: number }>()
|
||||
|
||||
async start(owner: number, parent: string, name: string): Promise<string> {
|
||||
const base =
|
||||
name
|
||||
.replace(/[/\\:*?"<>|]/g, '_')
|
||||
.slice(0, 80)
|
||||
.trim() || 'Untitled'
|
||||
const dir = await mkdtemp(join(parent, `${base}-images-`))
|
||||
const id = randomUUID()
|
||||
this.sessions.set(id, { owner, dir, pages: 0 })
|
||||
return id
|
||||
}
|
||||
|
||||
private get(owner: number, id: string) {
|
||||
const session = this.sessions.get(id)
|
||||
if (!session || session.owner !== owner) throw new Error('Export session is not authorized')
|
||||
return session
|
||||
}
|
||||
|
||||
async write(owner: number, id: string, page: number, base64: string): Promise<void> {
|
||||
const session = this.get(owner, id)
|
||||
if (!Number.isSafeInteger(page) || page !== session.pages + 1)
|
||||
throw new Error('Invalid export page number')
|
||||
if (typeof base64 !== 'string') throw new Error('Invalid PNG data')
|
||||
const bytes = Buffer.from(base64, 'base64')
|
||||
if (!bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
|
||||
throw new Error('Invalid PNG data')
|
||||
await writeFile(join(session.dir, `page-${String(page).padStart(2, '0')}.png`), bytes, {
|
||||
flag: 'wx',
|
||||
})
|
||||
session.pages = page
|
||||
}
|
||||
|
||||
async finish(owner: number, id: string, success: boolean): Promise<string | null> {
|
||||
const session = this.get(owner, id)
|
||||
this.sessions.delete(id)
|
||||
if (!success || !session.pages) {
|
||||
await rm(session.dir, { recursive: true, force: true })
|
||||
if (success) throw new Error('Cannot complete an empty image export')
|
||||
return null
|
||||
}
|
||||
return session.dir
|
||||
}
|
||||
|
||||
async dispose(owner: number): Promise<void> {
|
||||
await Promise.all(
|
||||
[...this.sessions.entries()]
|
||||
.filter(([, session]) => session.owner === owner)
|
||||
.map(([id]) => this.finish(owner, id, false)),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { readFile, writeFile } from 'node:fs/promises'
|
||||
import { basename, dirname, extname, join, relative, resolve } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import {
|
||||
@@ -30,6 +29,8 @@ import {
|
||||
} from '@genoffice/electron-utils'
|
||||
import { createI18n, getUiLang } from '@genoffice/i18n'
|
||||
import { generateImageTool } from '@genoffice/ai-search'
|
||||
import { ImageExportSessions } from './image-export'
|
||||
import { printMarkdownPdf } from './print-pdf'
|
||||
import { atomicWriteFile } from './atomic-write'
|
||||
import {
|
||||
copyImageIntoOwnedAssets,
|
||||
@@ -51,6 +52,7 @@ import type {
|
||||
ExportDocxRequest,
|
||||
ExportFormat,
|
||||
ExportPdfRequest,
|
||||
ImageExportPreparation,
|
||||
ExportResult,
|
||||
ImageData,
|
||||
SaveMarkdownRequest,
|
||||
@@ -690,6 +692,8 @@ function registerImageProtocol(): void {
|
||||
})
|
||||
}
|
||||
|
||||
const imageExports = new ImageExportSessions()
|
||||
|
||||
let ipcRegistered = false
|
||||
|
||||
function registerMarkdownIpc(): void {
|
||||
@@ -964,29 +968,69 @@ function registerMarkdownIpc(): void {
|
||||
configuredDefaultSaveDir(app),
|
||||
)
|
||||
if (picked.canceled || !picked.filePath) return { ok: true, canceled: true }
|
||||
// sheets-style: render the print HTML in a hidden scripting-disabled window
|
||||
const workDir = await mkdtemp(join(tmpdir(), 'genoffice-md-pdf-'))
|
||||
const printWin = new BrowserWindow({
|
||||
show: false,
|
||||
webPreferences: { sandbox: true, javascript: false },
|
||||
})
|
||||
try {
|
||||
const htmlPath = join(workDir, 'print.html')
|
||||
await writeFile(htmlPath, request.html, 'utf8')
|
||||
await printWin.loadFile(htmlPath)
|
||||
const pdf = await printWin.webContents.printToPDF({
|
||||
pageSize: 'A4',
|
||||
printBackground: true,
|
||||
margins: { top: 0.6, bottom: 0.6, left: 0.6, right: 0.6 },
|
||||
})
|
||||
const pdf = await printMarkdownPdf(request.html)
|
||||
await writeFile(picked.filePath, pdf)
|
||||
openExportedPdf(picked.filePath)
|
||||
return { ok: true, path: picked.filePath }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) }
|
||||
} finally {
|
||||
printWin.destroy()
|
||||
await rm(workDir, { recursive: true, force: true })
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
MARKDOWN_CHANNELS.prepareImageExport,
|
||||
async (e, request: ExportPdfRequest): Promise<ImageExportPreparation> => {
|
||||
if (typeof request?.html !== 'string' || !request.html)
|
||||
return { ok: false, error: 'Empty document' }
|
||||
let id: string | undefined
|
||||
try {
|
||||
const win = BrowserWindow.fromWebContents(e.sender) ?? undefined
|
||||
const picked = await showOpenDialogWithMemory(
|
||||
dialog,
|
||||
win,
|
||||
{
|
||||
properties: ['openDirectory', 'createDirectory'],
|
||||
},
|
||||
configuredDefaultSaveDir(app),
|
||||
)
|
||||
if (picked.canceled || !picked.filePaths[0]) return { ok: true, canceled: true }
|
||||
id = await imageExports.start(
|
||||
e.sender.id,
|
||||
picked.filePaths[0],
|
||||
String(request.suggestedName || tm('untitledFile')),
|
||||
)
|
||||
const pdf = await printMarkdownPdf(request.html)
|
||||
if (e.sender.isDestroyed()) throw new Error('Document closed during export')
|
||||
return { ok: true, id, pdfBase64: pdf.toString('base64') }
|
||||
} catch (err) {
|
||||
if (id) await imageExports.finish(e.sender.id, id, false).catch(() => {})
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) }
|
||||
}
|
||||
},
|
||||
)
|
||||
ipcMain.handle(
|
||||
MARKDOWN_CHANNELS.writeExportImage,
|
||||
async (e, id: string, page: number, base64: string) => {
|
||||
try {
|
||||
await imageExports.write(e.sender.id, id, page, base64)
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) }
|
||||
}
|
||||
},
|
||||
)
|
||||
ipcMain.handle(
|
||||
MARKDOWN_CHANNELS.finishImageExport,
|
||||
async (e, id: string, success: boolean): Promise<ExportResult> => {
|
||||
try {
|
||||
const dir = await imageExports.finish(e.sender.id, id, success === true)
|
||||
if (!dir) return { ok: true, canceled: true }
|
||||
shell.showItemInFolder(join(dir, 'page-01.png'))
|
||||
return { ok: true, path: dir }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) }
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -1039,6 +1083,9 @@ function grantAndTrack(wc: WebContents, openPath?: string | null): void {
|
||||
return { action: 'deny' }
|
||||
})
|
||||
wc.once('destroyed', () => {
|
||||
void imageExports
|
||||
.dispose(wcId)
|
||||
.catch((err) => console.warn('[markdown] image export cleanup:', err))
|
||||
openPathByWc.delete(wcId)
|
||||
allowedByWc.delete(wcId)
|
||||
savePathByWc.delete(wcId)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { BrowserWindow } from 'electron'
|
||||
|
||||
/** Shared pagination for PDF and PNG export. Document scripts remain disabled. */
|
||||
export async function printMarkdownPdf(html: string): Promise<Buffer> {
|
||||
const workDir = await mkdtemp(join(tmpdir(), 'genoffice-md-print-'))
|
||||
let printWin: BrowserWindow | undefined
|
||||
try {
|
||||
printWin = new BrowserWindow({
|
||||
show: false,
|
||||
webPreferences: { sandbox: true, javascript: false },
|
||||
})
|
||||
const htmlPath = join(workDir, 'print.html')
|
||||
await writeFile(htmlPath, html, 'utf8')
|
||||
await printWin.loadFile(htmlPath)
|
||||
return await printWin.webContents.printToPDF({
|
||||
pageSize: 'A4',
|
||||
printBackground: true,
|
||||
margins: { top: 0.6, bottom: 0.6, left: 0.6, right: 0.6 },
|
||||
})
|
||||
} finally {
|
||||
printWin?.destroy()
|
||||
await rm(workDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,12 @@ const api: MarkdownApi = {
|
||||
},
|
||||
exportDocx: (request) => ipcRenderer.invoke(MARKDOWN_CHANNELS.exportDocx, request),
|
||||
exportPdf: (request) => ipcRenderer.invoke(MARKDOWN_CHANNELS.exportPdf, request),
|
||||
prepareImageExport: (request) =>
|
||||
ipcRenderer.invoke(MARKDOWN_CHANNELS.prepareImageExport, request),
|
||||
writeExportImage: (id, page, base64) =>
|
||||
ipcRenderer.invoke(MARKDOWN_CHANNELS.writeExportImage, id, page, base64),
|
||||
finishImageExport: (id, success) =>
|
||||
ipcRenderer.invoke(MARKDOWN_CHANNELS.finishImageExport, id, success),
|
||||
getLanguage: () => ipcRenderer.invoke(MARKDOWN_CHANNELS.getLanguage),
|
||||
onLanguageChanged: (handler) => {
|
||||
const listener = (_e: Electron.IpcRendererEvent, lang: Lang) => handler(lang)
|
||||
|
||||
@@ -14,6 +14,8 @@ import { EditorContent, useEditor } from '@tiptap/react'
|
||||
import { FindPanel, type FindFocusRequest, type FindPanelStrings } from '@genoffice/ui'
|
||||
import type { Editor } from '@tiptap/core'
|
||||
import { TextSelection } from '@tiptap/pm/state'
|
||||
import { exportImages } from './export/imageExport'
|
||||
import type { StringKey } from './i18n/locale'
|
||||
import { useI18n } from './i18n/locale'
|
||||
import {
|
||||
buildFrontmatterRaw,
|
||||
@@ -130,6 +132,11 @@ export default function App() {
|
||||
const [filePath, setFilePath] = useState<string | null>(null)
|
||||
const [dirty, setDirty] = useState(false)
|
||||
const [saveState, setSaveState] = useState<SaveState>('idle')
|
||||
const exportingImagesRef = useRef(false)
|
||||
const [imageExportStatus, setImageExportStatus] = useState<{
|
||||
key: StringKey
|
||||
params?: Record<string, string | number>
|
||||
} | null>(null)
|
||||
const [slashState, setSlashState] = useState<SlashMenuState | null>(null)
|
||||
const [fmOpen, setFmOpen] = useState(false)
|
||||
const [fmText, setFmText] = useState('')
|
||||
@@ -402,6 +409,44 @@ export default function App() {
|
||||
(filePathRef.current
|
||||
? filePathRef.current.replace(/^.*[/\\]/, '').replace(/\.(md|markdown)$/i, '')
|
||||
: deriveAutoFileName(current)) || 'Untitled'
|
||||
if (format === 'png') {
|
||||
if (exportingImagesRef.current) return false
|
||||
exportingImagesRef.current = true
|
||||
setImageExportStatus({ key: 'appExportingImages' })
|
||||
try {
|
||||
await document.fonts.ready
|
||||
await Promise.all(
|
||||
[
|
||||
...current.view.dom.querySelectorAll<HTMLImageElement>(
|
||||
'img[src]:not(.ProseMirror-separator)',
|
||||
),
|
||||
].map((image) => image.decode().catch(() => {})),
|
||||
)
|
||||
const result = await exportImages(
|
||||
buildPrintHtml(current.view.dom, suggestedName),
|
||||
suggestedName,
|
||||
(count) => setImageExportStatus({ key: 'appExportImagesProgress', params: { count } }),
|
||||
)
|
||||
if (!result.ok) throw new Error(result.error)
|
||||
if ('canceled' in result) {
|
||||
setImageExportStatus(null)
|
||||
return false
|
||||
}
|
||||
setImageExportStatus({
|
||||
key: 'appExportImagesDone',
|
||||
params: { count: result.count ?? 0, dir: result.path },
|
||||
})
|
||||
return true
|
||||
} catch (err) {
|
||||
setImageExportStatus({
|
||||
key: 'appExportImagesFailed',
|
||||
params: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
return false
|
||||
} finally {
|
||||
exportingImagesRef.current = false
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (format === 'pdf') {
|
||||
const html = buildPrintHtml(current.view.dom, suggestedName)
|
||||
@@ -860,6 +905,11 @@ export default function App() {
|
||||
</div>
|
||||
<footer className="status-bar">
|
||||
<div className="status-left">
|
||||
{imageExportStatus && (
|
||||
<span className="status-item status-export" role="status">
|
||||
{t(imageExportStatus.key, imageExportStatus.params)}
|
||||
</span>
|
||||
)}
|
||||
{fileName && <span className="status-item status-file">{fileName}</span>}
|
||||
</div>
|
||||
<div className="status-right">
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { ExportResult } from '../../shared/ipc'
|
||||
|
||||
/** Same 192 DPI output as Docs; render and write one page at a time. */
|
||||
export async function exportImages(
|
||||
html: string,
|
||||
suggestedName: string,
|
||||
onProgress: (count: number) => void,
|
||||
): Promise<ExportResult & { count?: number }> {
|
||||
const target = await window.markdownApi.prepareImageExport({ html, suggestedName })
|
||||
if (!target.ok || 'canceled' in target) return target
|
||||
let task: import('pdfjs-dist').PDFDocumentLoadingTask | undefined
|
||||
let canvas: HTMLCanvasElement | undefined
|
||||
try {
|
||||
const pdfjs = await import('pdfjs-dist/legacy/build/pdf.mjs')
|
||||
const { default: workerUrl } = await import('pdfjs-dist/legacy/build/pdf.worker.min.mjs?url')
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = workerUrl
|
||||
task = pdfjs.getDocument({
|
||||
data: Uint8Array.from(atob(target.pdfBase64), (char) => char.charCodeAt(0)),
|
||||
useWasm: false,
|
||||
})
|
||||
const pdf = await task.promise
|
||||
onProgress(pdf.numPages)
|
||||
canvas = document.createElement('canvas')
|
||||
for (let i = 1; i <= pdf.numPages; i++) {
|
||||
const page = await pdf.getPage(i)
|
||||
const viewport = page.getViewport({ scale: 192 / 72 })
|
||||
canvas.width = Math.ceil(viewport.width)
|
||||
canvas.height = Math.ceil(viewport.height)
|
||||
await page.render({ canvas, viewport }).promise
|
||||
page.cleanup()
|
||||
const pngBase64 = canvas.toDataURL('image/png').split(',')[1]
|
||||
const result = await window.markdownApi.writeExportImage(target.id, i, pngBase64)
|
||||
if (!result.ok) throw new Error(result.error || 'Image write failed')
|
||||
}
|
||||
const result = await window.markdownApi.finishImageExport(target.id, true)
|
||||
return { ...result, count: pdf.numPages }
|
||||
} catch (err) {
|
||||
await window.markdownApi.finishImageExport(target.id, false).catch(() => {})
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) }
|
||||
} finally {
|
||||
if (canvas) canvas.width = canvas.height = 0
|
||||
await task?.destroy()
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,10 @@ export function buildPrintHtml(editorRoot: HTMLElement, title: string): string {
|
||||
el.removeAttribute('contenteditable')
|
||||
|
||||
// editor-only code block chrome (language picker + copy button) must not print
|
||||
for (const bar of clone.querySelectorAll('.md-codeblock-bar, .md-diagram-error')) bar.remove()
|
||||
for (const bar of clone.querySelectorAll(
|
||||
'.md-codeblock-bar, .md-diagram-error, .ProseMirror-separator',
|
||||
))
|
||||
bar.remove()
|
||||
// a rendered diagram block prints as its picture; an unrendered one keeps its source
|
||||
for (const block of clone.querySelectorAll('[data-diagram="rendered"] pre')) block.remove()
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
export const strings = {
|
||||
zh: {
|
||||
appExportingImages: '正在导出图片…',
|
||||
appExportImagesProgress: '正在导出 {count} 张图片…',
|
||||
appExportImagesDone: '已导出 {count} 张图片到 {dir}',
|
||||
appExportImagesFailed: '导出图片失败:{error}',
|
||||
aiToolReadFm: '读取文档属性',
|
||||
aiToolWriteDoc: '撰写文档',
|
||||
aiToolWriteDocFailed: '文档撰写失败',
|
||||
@@ -198,6 +202,10 @@ export const strings = {
|
||||
zoomOut: '缩小',
|
||||
},
|
||||
en: {
|
||||
appExportingImages: 'Exporting images…',
|
||||
appExportImagesProgress: 'Exporting {count} images…',
|
||||
appExportImagesDone: 'Exported {count} images to {dir}',
|
||||
appExportImagesFailed: 'Image export failed: {error}',
|
||||
aiToolReadFm: 'Read document properties',
|
||||
aiToolWriteDoc: 'Wrote the content',
|
||||
aiToolWriteDocFailed: 'Writing failed',
|
||||
@@ -402,6 +410,10 @@ export const strings = {
|
||||
zoomOut: 'Zoom out',
|
||||
},
|
||||
ja: {
|
||||
appExportingImages: '画像をエクスポート中…',
|
||||
appExportImagesProgress: '{count} 枚の画像をエクスポート中…',
|
||||
appExportImagesDone: '{count} 枚の画像を {dir} にエクスポートしました',
|
||||
appExportImagesFailed: '画像のエクスポートに失敗しました:{error}',
|
||||
aiToolReadFm: 'ドキュメントのプロパティを読み取り',
|
||||
aiToolWriteDoc: '本文を作成しました',
|
||||
aiToolWriteDocFailed: '本文の作成に失敗しました',
|
||||
@@ -604,6 +616,10 @@ export const strings = {
|
||||
zoomOut: '縮小',
|
||||
},
|
||||
ko: {
|
||||
appExportingImages: '이미지 내보내는 중…',
|
||||
appExportImagesProgress: '이미지 {count}장 내보내는 중…',
|
||||
appExportImagesDone: '이미지 {count}장을 {dir}에 내보냈습니다',
|
||||
appExportImagesFailed: '이미지 내보내기 실패: {error}',
|
||||
aiToolReadFm: '문서 속성 읽기',
|
||||
aiToolWriteDoc: '본문을 작성했습니다',
|
||||
aiToolWriteDocFailed: '본문 작성 실패',
|
||||
@@ -807,6 +823,10 @@ export const strings = {
|
||||
zoomOut: '축소',
|
||||
},
|
||||
fr: {
|
||||
appExportingImages: 'Exportation des images…',
|
||||
appExportImagesProgress: 'Exportation de {count} images…',
|
||||
appExportImagesDone: '{count} images exportées vers {dir}',
|
||||
appExportImagesFailed: 'Échec de l’exportation des images : {error}',
|
||||
aiToolReadFm: 'Lecture des propriétés du document',
|
||||
aiToolWriteDoc: 'Contenu rédigé',
|
||||
aiToolWriteDocFailed: 'Échec de la rédaction',
|
||||
@@ -1015,6 +1035,10 @@ export const strings = {
|
||||
zoomOut: 'Zoom arrière',
|
||||
},
|
||||
de: {
|
||||
appExportingImages: 'Bilder werden exportiert…',
|
||||
appExportImagesProgress: '{count} Bilder werden exportiert…',
|
||||
appExportImagesDone: '{count} Bilder nach {dir} exportiert',
|
||||
appExportImagesFailed: 'Bildexport fehlgeschlagen: {error}',
|
||||
aiToolReadFm: 'Dokumenteigenschaften lesen',
|
||||
aiToolWriteDoc: 'Inhalt geschrieben',
|
||||
aiToolWriteDocFailed: 'Schreiben fehlgeschlagen',
|
||||
@@ -1222,6 +1246,10 @@ export const strings = {
|
||||
zoomOut: 'Verkleinern',
|
||||
},
|
||||
es: {
|
||||
appExportingImages: 'Exportando imágenes…',
|
||||
appExportImagesProgress: 'Exportando {count} imágenes…',
|
||||
appExportImagesDone: 'Se exportaron {count} imágenes a {dir}',
|
||||
appExportImagesFailed: 'Error al exportar imágenes: {error}',
|
||||
aiToolReadFm: 'Leer propiedades del documento',
|
||||
aiToolWriteDoc: 'Contenido redactado',
|
||||
aiToolWriteDocFailed: 'Falló la redacción',
|
||||
@@ -1430,6 +1458,10 @@ export const strings = {
|
||||
zoomOut: 'Alejar',
|
||||
},
|
||||
th: {
|
||||
appExportingImages: 'กำลังส่งออกรูปภาพ…',
|
||||
appExportImagesProgress: 'กำลังส่งออกรูปภาพ {count} รูป…',
|
||||
appExportImagesDone: 'ส่งออกรูปภาพ {count} รูปไปยัง {dir} แล้ว',
|
||||
appExportImagesFailed: 'ส่งออกรูปภาพไม่สำเร็จ: {error}',
|
||||
aiToolReadFm: 'อ่านคุณสมบัติเอกสาร',
|
||||
aiToolWriteDoc: 'เขียนเนื้อหาแล้ว',
|
||||
aiToolWriteDocFailed: 'เขียนเนื้อหาไม่สำเร็จ',
|
||||
@@ -1630,6 +1662,10 @@ export const strings = {
|
||||
zoomOut: 'ย่อ',
|
||||
},
|
||||
id: {
|
||||
appExportingImages: 'Mengekspor gambar…',
|
||||
appExportImagesProgress: 'Mengekspor {count} gambar…',
|
||||
appExportImagesDone: '{count} gambar diekspor ke {dir}',
|
||||
appExportImagesFailed: 'Gagal mengekspor gambar: {error}',
|
||||
aiToolReadFm: 'Baca properti dokumen',
|
||||
aiToolWriteDoc: 'Konten ditulis',
|
||||
aiToolWriteDocFailed: 'Penulisan gagal',
|
||||
@@ -1833,6 +1869,10 @@ export const strings = {
|
||||
zoomOut: 'Perkecil',
|
||||
},
|
||||
ru: {
|
||||
appExportingImages: 'Экспорт изображений…',
|
||||
appExportImagesProgress: 'Экспорт {count} изображений…',
|
||||
appExportImagesDone: 'Экспортировано {count} изображений в {dir}',
|
||||
appExportImagesFailed: 'Не удалось экспортировать изображения: {error}',
|
||||
aiToolReadFm: 'Чтение свойств документа',
|
||||
aiToolWriteDoc: 'Текст написан',
|
||||
aiToolWriteDocFailed: 'Не удалось написать текст',
|
||||
@@ -2037,6 +2077,10 @@ export const strings = {
|
||||
zoomOut: 'Уменьшить',
|
||||
},
|
||||
ar: {
|
||||
appExportingImages: 'جارٍ تصدير الصور…',
|
||||
appExportImagesProgress: 'جارٍ تصدير {count} صورة…',
|
||||
appExportImagesDone: 'تم تصدير {count} صورة إلى {dir}',
|
||||
appExportImagesFailed: 'فشل تصدير الصور: {error}',
|
||||
aiToolReadFm: 'قراءة خصائص المستند',
|
||||
aiToolWriteDoc: 'تمت كتابة المحتوى',
|
||||
aiToolWriteDocFailed: 'فشلت الكتابة',
|
||||
@@ -2237,6 +2281,10 @@ export const strings = {
|
||||
zoomOut: 'تصغير',
|
||||
},
|
||||
pt: {
|
||||
appExportingImages: 'Exportando imagens…',
|
||||
appExportImagesProgress: 'Exportando {count} imagens…',
|
||||
appExportImagesDone: '{count} imagens exportadas para {dir}',
|
||||
appExportImagesFailed: 'Falha ao exportar imagens: {error}',
|
||||
aiToolReadFm: 'Ler propriedades do documento',
|
||||
aiToolWriteDoc: 'Conteúdo escrito',
|
||||
aiToolWriteDocFailed: 'Falha ao escrever',
|
||||
@@ -2443,6 +2491,10 @@ export const strings = {
|
||||
zoomOut: 'Reduzir',
|
||||
},
|
||||
it: {
|
||||
appExportingImages: 'Esportazione delle immagini…',
|
||||
appExportImagesProgress: 'Esportazione di {count} immagini…',
|
||||
appExportImagesDone: '{count} immagini esportate in {dir}',
|
||||
appExportImagesFailed: 'Esportazione delle immagini non riuscita: {error}',
|
||||
aiToolReadFm: 'Lettura delle proprietà del documento',
|
||||
aiToolWriteDoc: 'Contenuto scritto',
|
||||
aiToolWriteDocFailed: 'Scrittura non riuscita',
|
||||
@@ -2649,6 +2701,10 @@ export const strings = {
|
||||
zoomOut: 'Riduci',
|
||||
},
|
||||
pl: {
|
||||
appExportingImages: 'Eksportowanie obrazów…',
|
||||
appExportImagesProgress: 'Eksportowanie {count} obrazów…',
|
||||
appExportImagesDone: 'Wyeksportowano {count} obrazów do {dir}',
|
||||
appExportImagesFailed: 'Eksport obrazów nie powiódł się: {error}',
|
||||
aiToolReadFm: 'Odczyt właściwości dokumentu',
|
||||
aiToolWriteDoc: 'Napisano treść',
|
||||
aiToolWriteDocFailed: 'Pisanie nie powiodło się',
|
||||
@@ -2853,6 +2909,10 @@ export const strings = {
|
||||
zoomOut: 'Pomniejsz',
|
||||
},
|
||||
cs: {
|
||||
appExportingImages: 'Exportují se obrázky…',
|
||||
appExportImagesProgress: 'Exportuje se {count} obrázků…',
|
||||
appExportImagesDone: 'Exportováno {count} obrázků do {dir}',
|
||||
appExportImagesFailed: 'Export obrázků se nezdařil: {error}',
|
||||
aiToolReadFm: 'Číst vlastnosti dokumentu',
|
||||
aiToolWriteDoc: 'Obsah napsán',
|
||||
aiToolWriteDocFailed: 'Psaní se nezdařilo',
|
||||
@@ -3056,6 +3116,10 @@ export const strings = {
|
||||
mermaidError: 'Chyba syntaxe diagramu',
|
||||
},
|
||||
nl: {
|
||||
appExportingImages: 'Afbeeldingen exporteren…',
|
||||
appExportImagesProgress: '{count} afbeeldingen exporteren…',
|
||||
appExportImagesDone: '{count} afbeeldingen geëxporteerd naar {dir}',
|
||||
appExportImagesFailed: 'Exporteren van afbeeldingen mislukt: {error}',
|
||||
aiToolReadFm: 'Documenteigenschappen lezen',
|
||||
aiToolWriteDoc: 'Inhoud geschreven',
|
||||
aiToolWriteDocFailed: 'Schrijven mislukt',
|
||||
@@ -3261,6 +3325,10 @@ export const strings = {
|
||||
zoomOut: 'Uitzoomen',
|
||||
},
|
||||
ms: {
|
||||
appExportingImages: 'Mengeksport imej…',
|
||||
appExportImagesProgress: 'Mengeksport {count} imej…',
|
||||
appExportImagesDone: '{count} imej dieksport ke {dir}',
|
||||
appExportImagesFailed: 'Eksport imej gagal: {error}',
|
||||
aiToolReadFm: 'Baca sifat dokumen',
|
||||
aiToolWriteDoc: 'Kandungan ditulis',
|
||||
aiToolWriteDocFailed: 'Penulisan gagal',
|
||||
@@ -3464,6 +3532,10 @@ export const strings = {
|
||||
zoomOut: 'Zum keluar',
|
||||
},
|
||||
he: {
|
||||
appExportingImages: 'מייצא תמונות…',
|
||||
appExportImagesProgress: 'מייצא {count} תמונות…',
|
||||
appExportImagesDone: '{count} תמונות יוצאו אל {dir}',
|
||||
appExportImagesFailed: 'ייצוא התמונות נכשל: {error}',
|
||||
aiToolReadFm: 'קריאת מאפייני המסמך',
|
||||
aiToolWriteDoc: 'התוכן נכתב',
|
||||
aiToolWriteDocFailed: 'הכתיבה נכשלה',
|
||||
@@ -3663,6 +3735,10 @@ export const strings = {
|
||||
zoomOut: 'הקטנה',
|
||||
},
|
||||
hi: {
|
||||
appExportingImages: 'छवियाँ निर्यात की जा रही हैं…',
|
||||
appExportImagesProgress: '{count} छवियाँ निर्यात की जा रही हैं…',
|
||||
appExportImagesDone: '{count} छवियाँ {dir} में निर्यात की गईं',
|
||||
appExportImagesFailed: 'छवि निर्यात विफल: {error}',
|
||||
aiToolReadFm: 'दस्तावेज़ गुण पढ़ें',
|
||||
aiToolWriteDoc: 'सामग्री लिख दी',
|
||||
aiToolWriteDocFailed: 'लिखने में विफल',
|
||||
@@ -3866,6 +3942,10 @@ export const strings = {
|
||||
zoomOut: 'ज़ूम आउट',
|
||||
},
|
||||
'zh-TW': {
|
||||
appExportingImages: '正在匯出圖片…',
|
||||
appExportImagesProgress: '正在匯出 {count} 張圖片…',
|
||||
appExportImagesDone: '已匯出 {count} 張圖片到 {dir}',
|
||||
appExportImagesFailed: '匯出圖片失敗:{error}',
|
||||
aiToolReadFm: '讀取文件屬性',
|
||||
aiToolWriteDoc: '撰寫文件',
|
||||
aiToolWriteDocFailed: '文件撰寫失敗',
|
||||
|
||||
@@ -27,6 +27,9 @@ export const MARKDOWN_CHANNELS = {
|
||||
exportRequest: 'markdown:export-request',
|
||||
exportDocx: 'markdown:export-docx',
|
||||
exportPdf: 'markdown:export-pdf',
|
||||
prepareImageExport: 'markdown:prepare-image-export',
|
||||
writeExportImage: 'markdown:write-export-image',
|
||||
finishImageExport: 'markdown:finish-image-export',
|
||||
consumeHeadlessExport: 'markdown:consume-headless-export',
|
||||
headlessExportDone: 'markdown:headless-export-done',
|
||||
printRequest: 'markdown:print-request',
|
||||
@@ -104,7 +107,7 @@ export interface ImageSearchResult {
|
||||
error?: string
|
||||
}
|
||||
|
||||
export type ExportFormat = 'pdf' | 'docx' | 'docs'
|
||||
export type ExportFormat = 'pdf' | 'docx' | 'docs' | 'png'
|
||||
|
||||
export interface ExportDocxRequest {
|
||||
/** .docx bytes, base64 */
|
||||
@@ -123,6 +126,11 @@ export interface ExportPdfRequest {
|
||||
outPath?: string
|
||||
}
|
||||
|
||||
export type ImageExportPreparation =
|
||||
| { ok: true; id: string; pdfBase64: string }
|
||||
| { ok: true; canceled: true }
|
||||
| { ok: false; error: string }
|
||||
|
||||
export type ExportResult =
|
||||
{ ok: true; path: string } | { ok: true; canceled: true } | { ok: false; error: string }
|
||||
|
||||
@@ -190,6 +198,13 @@ export interface MarkdownApi {
|
||||
onPrintRequest(handler: () => void): () => void
|
||||
exportDocx(request: ExportDocxRequest): Promise<ExportResult>
|
||||
exportPdf(request: ExportPdfRequest): Promise<ExportResult>
|
||||
prepareImageExport(request: Omit<ExportPdfRequest, 'outPath'>): Promise<ImageExportPreparation>
|
||||
writeExportImage(
|
||||
id: string,
|
||||
page: number,
|
||||
pngBase64: string,
|
||||
): Promise<{ ok: boolean; error?: string }>
|
||||
finishImageExport(id: string, success: boolean): Promise<ExportResult>
|
||||
getLanguage(): Promise<Lang>
|
||||
onLanguageChanged(handler: (lang: Lang) => void): () => void
|
||||
getTheme(): Promise<UiTheme>
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { expect, type Page } from '@playwright/test'
|
||||
const rebaseSource = '<details>\n<img src="assets/old.png">\n</details>\n'
|
||||
const source = 'Title\n=====\n\n* item \n\n\n'
|
||||
|
||||
export async function openSource(
|
||||
page: Page,
|
||||
enabled: boolean,
|
||||
rebase = false,
|
||||
text = source,
|
||||
): Promise<void> {
|
||||
page.on('pageerror', (error) => console.log('[browser-error]', error.message))
|
||||
page.on('console', (message) => {
|
||||
if (message.type() === 'error') console.log('[browser-console]', message.text())
|
||||
})
|
||||
await page.addInitScript(
|
||||
({ text, enabled, rebase }) => {
|
||||
if (enabled) localStorage.setItem('mdapp.experimentalRoundTrip', '1')
|
||||
localStorage.setItem('mdapp.showAi', '0')
|
||||
const off = () => {}
|
||||
window.markdownApi = {
|
||||
getLanguage: async () => 'en',
|
||||
getTheme: async () => 'light',
|
||||
onLanguageChanged: () => off,
|
||||
onThemeChanged: () => off,
|
||||
getAutoSaveDefault: async () => ({ on: false, updatedAt: 0 }),
|
||||
onAutoSaveDefaultChanged: () => off,
|
||||
getAiPanelPrefs: async () => ({
|
||||
fontSize: 'default',
|
||||
customFontSize: 14,
|
||||
spellcheck: true,
|
||||
}),
|
||||
onAiPanelPrefsChanged: () => off,
|
||||
consumePending: async () => '/fixtures/polish.md',
|
||||
readFile: async () => text,
|
||||
consumeHeadlessExport: async () => null,
|
||||
headlessExportDone: () => {},
|
||||
setDirty: () => {},
|
||||
save: async ({ text }) => {
|
||||
document.body.dataset.saved = text
|
||||
return {
|
||||
ok: true,
|
||||
path: '/fixtures/polish.md',
|
||||
imageRewrites: rebase ? [{ from: 'assets/old.png', to: 'assets/new.png' }] : [],
|
||||
writtenText: rebase ? text.replace('assets/old.png', 'assets/new.png') : undefined,
|
||||
}
|
||||
},
|
||||
onSaveRequest: (handler) => {
|
||||
const save = () => handler('save')
|
||||
window.addEventListener('test:save', save)
|
||||
return () => window.removeEventListener('test:save', save)
|
||||
},
|
||||
onReadTextRequest: (handler) => {
|
||||
window.addEventListener('test:read-source', handler)
|
||||
return () => window.removeEventListener('test:read-source', handler)
|
||||
},
|
||||
sendReadTextResult: (result) =>
|
||||
window.dispatchEvent(new CustomEvent('test:read-source-result', { detail: result })),
|
||||
sendSaveRequestAck: () => {},
|
||||
onCloseSaveRequest: () => off,
|
||||
sendCloseSaveResult: () => {},
|
||||
onFileRenamed: () => off,
|
||||
pickImage: async () => null,
|
||||
saveImage: async () => null,
|
||||
readImage: async () => null,
|
||||
onExportRequest: (handler) => {
|
||||
const exportFile = (event: Event) => handler((event as CustomEvent).detail)
|
||||
window.addEventListener('test:export', exportFile)
|
||||
return () => window.removeEventListener('test:export', exportFile)
|
||||
},
|
||||
prepareImageExport: async () => ({ ok: true, canceled: true }),
|
||||
writeExportImage: async () => ({ ok: false, error: 'not used in renderer coverage' }),
|
||||
finishImageExport: async () => ({ ok: false, error: 'not used in renderer coverage' }),
|
||||
onPrintRequest: () => off,
|
||||
exportDocx: async () => ({ ok: false, error: 'not used in renderer coverage' }),
|
||||
exportPdf: async () => ({ ok: false, error: 'not used in renderer coverage' }),
|
||||
onChromePressed: () => off,
|
||||
onViewImage: () => off,
|
||||
getAiSettings: async () => ({ providers: [] }),
|
||||
aiGskStatus: async () => ({ loggedIn: false }),
|
||||
aiStream: async () => {},
|
||||
aiStreamCancel: async () => {},
|
||||
onAiStream: () => off,
|
||||
webSearch: async () => ({
|
||||
results: [],
|
||||
method: 'error',
|
||||
error: 'not used in renderer coverage',
|
||||
}),
|
||||
imageSearch: async () => ({
|
||||
images: [],
|
||||
method: 'error',
|
||||
error: 'not used in renderer coverage',
|
||||
}),
|
||||
fetchImage: async () => null,
|
||||
aiGenerateImage: async () => ({ error: 'not used in renderer coverage' }),
|
||||
}
|
||||
},
|
||||
{ text: rebase ? rebaseSource : text, enabled, rebase },
|
||||
)
|
||||
await page.goto(`http://localhost:${Number(process.env.MARKDOWN_DEV_PORT) || 5177}`)
|
||||
await expect(page.locator('.doc-editor')).toBeVisible()
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
import { openSource } from './helpers'
|
||||
|
||||
for (const outcome of ['canceled', 'failed', 'completed']) {
|
||||
const canceled = outcome === 'canceled'
|
||||
test(`PNG export ${outcome} with a broken image`, async ({ page }) => {
|
||||
const pdf = await PDFDocument.create()
|
||||
for (let i = 0; i < 2; i++)
|
||||
pdf.addPage([120, 120]).drawRectangle({ x: 10, y: 10, width: 80, height: 80 })
|
||||
const pdfBase64 = Buffer.from(await pdf.save()).toString('base64')
|
||||
await openSource(page, false, false, '# Export\n\n\n')
|
||||
await page.evaluate(
|
||||
({ canceled, outcome, pdfBase64 }) => {
|
||||
window.markdownApi.prepareImageExport = async () => {
|
||||
document.body.dataset.picked = 'true'
|
||||
return canceled ? { ok: true, canceled: true } : { ok: true, id: 'fixture', pdfBase64 }
|
||||
}
|
||||
window.markdownApi.writeExportImage = async (_id, pageNumber, bytes) => {
|
||||
document.body.dataset.pngHeader = bytes.slice(0, 11)
|
||||
return pageNumber === 1 || outcome === 'completed'
|
||||
? { ok: true }
|
||||
: { ok: false, error: 'Disk is full' }
|
||||
}
|
||||
window.markdownApi.finishImageExport = async (_id, success) => {
|
||||
document.body.dataset.finished = String(success)
|
||||
return success
|
||||
? { ok: true, path: '/export/report-images' }
|
||||
: { ok: true, canceled: true }
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent('test:export', { detail: 'png' }))
|
||||
},
|
||||
{ canceled, outcome, pdfBase64 },
|
||||
)
|
||||
await expect(page.locator('body')).toHaveAttribute('data-picked', 'true')
|
||||
if (canceled) {
|
||||
await expect(page.locator('.status-export')).toHaveCount(0)
|
||||
await expect(page.locator('body')).not.toHaveAttribute('data-png-header')
|
||||
await expect(page.locator('body')).not.toHaveAttribute('data-finished')
|
||||
} else if (outcome === 'completed') {
|
||||
await expect(page.locator('.status-export')).toContainText('/export/report-images')
|
||||
await expect(page.locator('body')).toHaveAttribute('data-png-header', 'iVBORw0KGgo')
|
||||
await expect(page.locator('body')).toHaveAttribute('data-finished', 'true')
|
||||
} else {
|
||||
await expect(page.locator('.status-export')).toHaveText('Image export failed: Disk is full')
|
||||
await expect(page.locator('body')).toHaveAttribute('data-png-header', 'iVBORw0KGgo')
|
||||
await expect(page.locator('body')).toHaveAttribute('data-finished', 'false')
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,94 +1,9 @@
|
||||
import { expect, test, type Page } from '@playwright/test'
|
||||
import { expect, test } from '@playwright/test'
|
||||
import type { Editor } from '@tiptap/core'
|
||||
import { openSource } from './helpers'
|
||||
const rebaseSource = '<details>\n<img src="assets/old.png">\n</details>\n'
|
||||
const source = 'Title\n=====\n\n* item \n\n\n'
|
||||
|
||||
async function openSource(page: Page, enabled: boolean, rebase = false): Promise<void> {
|
||||
page.on('pageerror', (error) => console.log('[browser-error]', error.message))
|
||||
page.on('console', (message) => {
|
||||
if (message.type() === 'error') console.log('[browser-console]', message.text())
|
||||
})
|
||||
await page.addInitScript(
|
||||
({ text, enabled, rebase }) => {
|
||||
if (enabled) localStorage.setItem('mdapp.experimentalRoundTrip', '1')
|
||||
localStorage.setItem('mdapp.showAi', '0')
|
||||
const off = () => {}
|
||||
window.markdownApi = {
|
||||
getLanguage: async () => 'en',
|
||||
getTheme: async () => 'light',
|
||||
onLanguageChanged: () => off,
|
||||
onThemeChanged: () => off,
|
||||
getAutoSaveDefault: async () => ({ on: false, updatedAt: 0 }),
|
||||
onAutoSaveDefaultChanged: () => off,
|
||||
getAiPanelPrefs: async () => ({
|
||||
fontSize: 'default',
|
||||
customFontSize: 14,
|
||||
spellcheck: true,
|
||||
}),
|
||||
onAiPanelPrefsChanged: () => off,
|
||||
consumePending: async () => '/fixtures/polish.md',
|
||||
readFile: async () => text,
|
||||
consumeHeadlessExport: async () => null,
|
||||
headlessExportDone: () => {},
|
||||
setDirty: () => {},
|
||||
save: async ({ text }) => {
|
||||
document.body.dataset.saved = text
|
||||
return {
|
||||
ok: true,
|
||||
path: '/fixtures/polish.md',
|
||||
imageRewrites: rebase ? [{ from: 'assets/old.png', to: 'assets/new.png' }] : [],
|
||||
writtenText: rebase ? text.replace('assets/old.png', 'assets/new.png') : undefined,
|
||||
}
|
||||
},
|
||||
onSaveRequest: (handler) => {
|
||||
const save = () => handler('save')
|
||||
window.addEventListener('test:save', save)
|
||||
return () => window.removeEventListener('test:save', save)
|
||||
},
|
||||
onReadTextRequest: (handler) => {
|
||||
window.addEventListener('test:read-source', handler)
|
||||
return () => window.removeEventListener('test:read-source', handler)
|
||||
},
|
||||
sendReadTextResult: (result) =>
|
||||
window.dispatchEvent(new CustomEvent('test:read-source-result', { detail: result })),
|
||||
sendSaveRequestAck: () => {},
|
||||
onCloseSaveRequest: () => off,
|
||||
sendCloseSaveResult: () => {},
|
||||
onFileRenamed: () => off,
|
||||
pickImage: async () => null,
|
||||
saveImage: async () => null,
|
||||
readImage: async () => null,
|
||||
onExportRequest: () => off,
|
||||
onPrintRequest: () => off,
|
||||
exportDocx: async () => ({ ok: false, error: 'not used in renderer coverage' }),
|
||||
exportPdf: async () => ({ ok: false, error: 'not used in renderer coverage' }),
|
||||
onChromePressed: () => off,
|
||||
onViewImage: () => off,
|
||||
getAiSettings: async () => ({ providers: [] }),
|
||||
aiGskStatus: async () => ({ loggedIn: false }),
|
||||
aiStream: async () => {},
|
||||
aiStreamCancel: async () => {},
|
||||
onAiStream: () => off,
|
||||
webSearch: async () => ({
|
||||
results: [],
|
||||
method: 'error',
|
||||
error: 'not used in renderer coverage',
|
||||
}),
|
||||
imageSearch: async () => ({
|
||||
images: [],
|
||||
method: 'error',
|
||||
error: 'not used in renderer coverage',
|
||||
}),
|
||||
fetchImage: async () => null,
|
||||
aiGenerateImage: async () => ({ error: 'not used in renderer coverage' }),
|
||||
}
|
||||
},
|
||||
{ text: rebase ? rebaseSource : source, enabled, rebase },
|
||||
)
|
||||
await page.goto(`http://localhost:${Number(process.env.MARKDOWN_DEV_PORT) || 5177}`)
|
||||
await expect(page.locator('.doc-editor')).toBeVisible()
|
||||
}
|
||||
|
||||
for (const enabled of [false, true]) {
|
||||
test(`save and MCP read use the ${enabled ? 'opt-in' : 'default'} serializer`, async ({
|
||||
page,
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
import { ImageExportSessions } from '../src/main/image-export'
|
||||
|
||||
const roots: string[] = []
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })))
|
||||
roots.length = 0
|
||||
})
|
||||
const png =
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLttAAAAABJRU5ErkJggg=='
|
||||
async function setup() {
|
||||
const root = await mkdtemp(join(tmpdir(), 'markdown-images-test-'))
|
||||
roots.push(root)
|
||||
const sessions = new ImageExportSessions()
|
||||
const id = await sessions.start(1, root, 'Report')
|
||||
return { root, sessions, id }
|
||||
}
|
||||
|
||||
it('writes numbered pages into a new folder without overwriting another export', async () => {
|
||||
const { root, sessions, id } = await setup()
|
||||
await sessions.write(1, id, 1, png)
|
||||
await sessions.write(1, id, 2, png)
|
||||
const dir = await sessions.finish(1, id, true)
|
||||
expect(await readdir(dir!)).toEqual(['page-01.png', 'page-02.png'])
|
||||
expect(await readFile(join(dir!, 'page-01.png'))).toEqual(Buffer.from(png, 'base64'))
|
||||
await sessions.start(1, root, 'Report')
|
||||
expect((await readdir(root)).length).toBe(2)
|
||||
await sessions.dispose(1)
|
||||
expect(await readdir(root)).toEqual([dir!.split(/[\\/]/).pop()])
|
||||
})
|
||||
|
||||
it('rejects writes from another renderer, invalid pages and invalid PNG data', async () => {
|
||||
const { sessions, id } = await setup()
|
||||
await expect(sessions.write(2, id, 1, png)).rejects.toThrow(/authorized/)
|
||||
await expect(sessions.write(1, id, -1, png)).rejects.toThrow(/page/)
|
||||
await expect(sessions.write(1, id, 1, 'not png')).rejects.toThrow(/PNG/)
|
||||
await sessions.write(1, id, 1, png)
|
||||
await expect(sessions.write(1, id, 1, png)).rejects.toThrow(/page/)
|
||||
})
|
||||
|
||||
it('removes partial images when export fails and revokes the session', async () => {
|
||||
const { root, sessions, id } = await setup()
|
||||
await sessions.write(1, id, 1, png)
|
||||
expect(await sessions.finish(1, id, false)).toBeNull()
|
||||
expect(await readdir(root)).toEqual([])
|
||||
await expect(sessions.write(1, id, 2, png)).rejects.toThrow(/authorized/)
|
||||
})
|
||||
|
||||
it('disposes only the closing renderer’s unfinished export', async () => {
|
||||
const { root, sessions, id } = await setup()
|
||||
const other = await sessions.start(2, root, '../other')
|
||||
await sessions.dispose(1)
|
||||
await expect(sessions.write(1, id, 1, png)).rejects.toThrow(/authorized/)
|
||||
await sessions.write(2, other, 1, png)
|
||||
const dir = await sessions.finish(2, other, true)
|
||||
expect(dir!.startsWith(root + '/')).toBe(true)
|
||||
expect(await readdir(dir!)).toEqual(['page-01.png'])
|
||||
})
|
||||
|
||||
it('does not report an empty export as successful', async () => {
|
||||
const { root, sessions, id } = await setup()
|
||||
await expect(sessions.finish(1, id, true)).rejects.toThrow(/empty/)
|
||||
expect(await readdir(root)).toEqual([])
|
||||
})
|
||||
@@ -33,13 +33,14 @@ describe('buildPrintHtml', () => {
|
||||
it('strips editor-only chrome from the clone', () => {
|
||||
const html = buildPrintHtml(
|
||||
editorRoot(
|
||||
'<p contenteditable="true">text</p>' +
|
||||
'<p contenteditable="true">text<img class="ProseMirror-separator" alt=""></p>' +
|
||||
'<div class="md-codeblock-bar"><button>copy</button></div>',
|
||||
),
|
||||
'Notes',
|
||||
)
|
||||
expect(html).not.toContain('contenteditable')
|
||||
expect(html).not.toContain('md-codeblock-bar')
|
||||
expect(html).not.toContain('ProseMirror-separator')
|
||||
expect(html).toContain('<p>text</p>')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -633,6 +633,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: '导出为 PDF…',
|
||||
menuExportImages: '导出为图片…',
|
||||
menuExportHtml: '导出为单文件 HTML…',
|
||||
menuOpenInDocs: '转换为 Docs 文档并打开',
|
||||
menuPrint: '打印…',
|
||||
@@ -714,6 +715,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'Export as PDF…',
|
||||
menuExportImages: 'Export as Images…',
|
||||
menuExportHtml: 'Export as Single-File HTML…',
|
||||
menuOpenInDocs: 'Convert and Open in Docs',
|
||||
menuPrint: 'Print…',
|
||||
@@ -803,6 +805,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'PDF として書き出す…',
|
||||
menuExportImages: '画像としてエクスポート…',
|
||||
menuExportHtml: '単一ファイル HTML として書き出す…',
|
||||
menuOpenInDocs: 'Docs 文書に変換して開く',
|
||||
menuPrint: '印刷…',
|
||||
@@ -892,6 +895,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'PDF로 내보내기…',
|
||||
menuExportImages: '이미지로 내보내기…',
|
||||
menuExportHtml: '단일 파일 HTML로 내보내기…',
|
||||
menuOpenInDocs: 'Docs 문서로 변환하여 열기',
|
||||
menuPrint: '인쇄…',
|
||||
@@ -980,6 +984,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'Exporter en PDF…',
|
||||
menuExportImages: 'Exporter en images…',
|
||||
menuExportHtml: 'Exporter en HTML (fichier unique)…',
|
||||
menuOpenInDocs: 'Convertir et ouvrir dans Docs',
|
||||
menuPrint: 'Imprimer…',
|
||||
@@ -1070,6 +1075,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'Als PDF exportieren…',
|
||||
menuExportImages: 'Als Bilder exportieren…',
|
||||
menuExportHtml: 'Als Einzeldatei-HTML exportieren…',
|
||||
menuOpenInDocs: 'In Docs umwandeln und öffnen',
|
||||
menuPrint: 'Drucken…',
|
||||
@@ -1160,6 +1166,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'Exportar como PDF…',
|
||||
menuExportImages: 'Exportar como imágenes…',
|
||||
menuExportHtml: 'Exportar como HTML de archivo único…',
|
||||
menuOpenInDocs: 'Convertir y abrir en Docs',
|
||||
menuPrint: 'Imprimir…',
|
||||
@@ -1250,6 +1257,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'ส่งออกเป็น PDF…',
|
||||
menuExportImages: 'ส่งออกเป็นรูปภาพ…',
|
||||
menuExportHtml: 'ส่งออกเป็น HTML ไฟล์เดียว…',
|
||||
menuOpenInDocs: 'แปลงและเปิดใน Docs',
|
||||
menuPrint: 'พิมพ์…',
|
||||
@@ -1336,6 +1344,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'Ekspor sebagai PDF…',
|
||||
menuExportImages: 'Ekspor sebagai gambar…',
|
||||
menuExportHtml: 'Ekspor sebagai HTML satu file…',
|
||||
menuOpenInDocs: 'Konversi dan buka di Docs',
|
||||
menuPrint: 'Cetak…',
|
||||
@@ -1426,6 +1435,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'Экспортировать в PDF…',
|
||||
menuExportImages: 'Экспорт в изображения…',
|
||||
menuExportHtml: 'Экспортировать в один файл HTML…',
|
||||
menuOpenInDocs: 'Преобразовать и открыть в Docs',
|
||||
menuPrint: 'Печать…',
|
||||
@@ -1516,6 +1526,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'تصدير بتنسيق PDF…',
|
||||
menuExportImages: 'تصدير كصور…',
|
||||
menuExportHtml: 'تصدير كملف HTML واحد…',
|
||||
menuOpenInDocs: 'التحويل والفتح في Docs',
|
||||
menuPrint: 'طباعة…',
|
||||
@@ -1602,6 +1613,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'Exportar como PDF…',
|
||||
menuExportImages: 'Exportar como imagens…',
|
||||
menuExportHtml: 'Exportar como HTML de arquivo único…',
|
||||
menuOpenInDocs: 'Converter e abrir no Docs',
|
||||
menuPrint: 'Imprimir…',
|
||||
@@ -1692,6 +1704,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'Esporta come PDF…',
|
||||
menuExportImages: 'Esporta come immagini…',
|
||||
menuExportHtml: 'Esporta come HTML a file singolo…',
|
||||
menuOpenInDocs: 'Converti e apri in Docs',
|
||||
menuPrint: 'Stampa…',
|
||||
@@ -1782,6 +1795,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'Eksportuj jako PDF…',
|
||||
menuExportImages: 'Eksportuj jako obrazy…',
|
||||
menuExportHtml: 'Eksportuj jako pojedynczy plik HTML…',
|
||||
menuOpenInDocs: 'Konwertuj i otwórz w Docs',
|
||||
menuPrint: 'Drukuj…',
|
||||
@@ -1872,6 +1886,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'Exportovat jako PDF…',
|
||||
menuExportImages: 'Exportovat jako obrázky…',
|
||||
menuExportHtml: 'Exportovat jako samostatné HTML…',
|
||||
menuOpenInDocs: 'Převést a otevřít v Docs',
|
||||
menuPrint: 'Tisk…',
|
||||
@@ -1960,6 +1975,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'Exporteren als PDF…',
|
||||
menuExportImages: 'Exporteren als afbeeldingen…',
|
||||
menuExportHtml: 'Exporteren als één HTML-bestand…',
|
||||
menuOpenInDocs: 'Converteren en openen in Docs',
|
||||
menuPrint: 'Afdrukken…',
|
||||
@@ -2050,6 +2066,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'Eksport sebagai PDF…',
|
||||
menuExportImages: 'Eksport sebagai imej…',
|
||||
menuExportHtml: 'Eksport sebagai HTML fail tunggal…',
|
||||
menuOpenInDocs: 'Tukar dan buka dalam Docs',
|
||||
menuPrint: 'Cetak…',
|
||||
@@ -2139,6 +2156,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'ייצוא כ-PDF…',
|
||||
menuExportImages: 'ייצוא כתמונות…',
|
||||
menuExportHtml: 'ייצוא כ-HTML בקובץ יחיד…',
|
||||
menuOpenInDocs: 'המרה ופתיחה ב-Docs',
|
||||
menuPrint: 'הדפסה…',
|
||||
@@ -2226,6 +2244,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: 'PDF के रूप में निर्यात…',
|
||||
menuExportImages: 'छवियों के रूप में निर्यात…',
|
||||
menuExportHtml: 'एकल-फ़ाइल HTML के रूप में निर्यात…',
|
||||
menuOpenInDocs: 'Docs में बदलें और खोलें',
|
||||
menuPrint: 'प्रिंट करें…',
|
||||
@@ -2316,6 +2335,7 @@ const tMain = createI18n({
|
||||
menuNewHtml: 'AI HTML',
|
||||
menuNewPdf: 'AI PDF',
|
||||
menuExportPdf: '匯出為 PDF…',
|
||||
menuExportImages: '匯出為圖片…',
|
||||
menuExportHtml: '匯出為單檔 HTML…',
|
||||
menuOpenInDocs: '轉換為 Docs 文件並開啟',
|
||||
menuPrint: '列印…',
|
||||
@@ -4075,6 +4095,13 @@ function buildMarkdownMenu(): void {
|
||||
if (tab) sendMarkdownExportRequest(tab.webContents, 'pdf')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: tm('menuExportImages'),
|
||||
click: () => {
|
||||
const tab = tabManager?.activeMarkdownTab()
|
||||
if (tab) sendMarkdownExportRequest(tab.webContents, 'png')
|
||||
},
|
||||
},
|
||||
{
|
||||
label: tm('menuOpenInDocs'),
|
||||
click: () => {
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { test, expect } from '@playwright/test'
|
||||
import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { PNG } from 'pngjs'
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
import { launchShell, closeAndSaveVideo, waitForPageWithUrl } from './helpers'
|
||||
|
||||
async function exportMenu(app: import('@playwright/test').ElectronApplication, label: string) {
|
||||
await app.evaluate(({ Menu, BrowserWindow }, text) => {
|
||||
const find = (items: Electron.MenuItem[]): Electron.MenuItem | undefined => {
|
||||
for (const item of items) {
|
||||
if (item.label === text) return item
|
||||
const child = item.submenu && find(item.submenu.items)
|
||||
if (child) return child
|
||||
}
|
||||
}
|
||||
const menu = find(Menu.getApplicationMenu()!.items)
|
||||
if (!menu) throw new Error(`Missing File menu item: ${text}`)
|
||||
menu.click(undefined as never, BrowserWindow.getFocusedWindow()!, undefined as never)
|
||||
}, label)
|
||||
}
|
||||
|
||||
test('Markdown File menu exports paginated PNG files with formula and local image', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'markdown-image-export-'))
|
||||
const source = join(dir, 'report.md')
|
||||
const image = new PNG({ width: 80, height: 50 })
|
||||
for (let p = 0; p < image.data.length; p += 4) {
|
||||
image.data[p] = 230
|
||||
image.data[p + 1] = 20
|
||||
image.data[p + 2] = 20
|
||||
image.data[p + 3] = 255
|
||||
}
|
||||
await writeFile(join(dir, 'red.png'), PNG.sync.write(image))
|
||||
await writeFile(
|
||||
source,
|
||||
'# Export test\n\n$E=mc^2$\n\n\n\n' +
|
||||
Array.from(
|
||||
{ length: 65 },
|
||||
(_, i) => `Paragraph ${i + 1}: pagination must preserve every line.`,
|
||||
).join('\n\n'),
|
||||
)
|
||||
const launched = await launchShell({
|
||||
onboardingSeen: true,
|
||||
videoDir: 'markdown-image-export',
|
||||
openFile: source,
|
||||
})
|
||||
try {
|
||||
const page = await waitForPageWithUrl(launched.app, '://markdown/')
|
||||
await expect(page.locator('.doc-editor h1')).toHaveText('Export test')
|
||||
await expect(page.locator('.doc-editor .katex')).toHaveCount(1)
|
||||
await page.waitForFunction(() =>
|
||||
[
|
||||
...document.querySelectorAll<HTMLImageElement>(
|
||||
'.doc-editor img[src]:not(.ProseMirror-separator)',
|
||||
),
|
||||
].every((img) => img.complete && img.naturalWidth > 0),
|
||||
)
|
||||
await launched.app.evaluate(({ dialog, shell }, dir) => {
|
||||
dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [dir] })
|
||||
dialog.showSaveDialog = async () => ({ canceled: false, filePath: `${dir}/reference.pdf` })
|
||||
shell.showItemInFolder = () => {}
|
||||
}, dir)
|
||||
await exportMenu(launched.app, 'Export as Images…')
|
||||
await expect(page.locator('.status-export')).toContainText(
|
||||
/Exported \d+ images|Image export failed/,
|
||||
{ timeout: 45_000 },
|
||||
)
|
||||
await expect(page.locator('.status-export')).toContainText(/Exported \d+ images/)
|
||||
const folders = (await readdir(dir)).filter((name) => name.startsWith('report-images-'))
|
||||
expect(folders).toHaveLength(1)
|
||||
const output = join(dir, folders[0])
|
||||
const files = (await readdir(output)).sort()
|
||||
expect(files.length).toBeGreaterThan(1)
|
||||
for (const file of files) {
|
||||
const png = PNG.sync.read(await readFile(join(output, file)))
|
||||
expect(png.width).toBeGreaterThan(1500)
|
||||
expect(png.height).toBeGreaterThan(2200)
|
||||
// Every page has painted content, not just the correct PNG header.
|
||||
let ink = 0
|
||||
for (let i = 0; i < png.data.length; i += 4) if (png.data[i] < 200) ink++
|
||||
expect(ink).toBeGreaterThan(100)
|
||||
}
|
||||
const firstBytes = await readFile(join(output, files[0]))
|
||||
await test.info().attach('exported-page-01', { body: firstBytes, contentType: 'image/png' })
|
||||
const first = PNG.sync.read(firstBytes)
|
||||
let red = 0
|
||||
for (let i = 0; i < first.data.length; i += 4)
|
||||
if (first.data[i] > 180 && first.data[i + 1] < 70 && first.data[i + 2] < 70) red++
|
||||
expect(red).toBeGreaterThan(500)
|
||||
|
||||
// Both outputs must use the same print pagination.
|
||||
await exportMenu(launched.app, 'Export as PDF…')
|
||||
await expect.poll(async () => (await readdir(dir)).includes('reference.pdf')).toBe(true)
|
||||
const pdfBytes = await readFile(join(dir, 'reference.pdf'))
|
||||
expect(pdfBytes.toString('latin1')).toContain('KaTeX')
|
||||
const pdf = await PDFDocument.load(pdfBytes)
|
||||
expect(files.length).toBe(pdf.getPageCount())
|
||||
|
||||
await launched.app.evaluate(({ dialog }) => {
|
||||
dialog.showOpenDialog = async () => ({ canceled: true, filePaths: [] })
|
||||
})
|
||||
// PDF export may open another tab; select the Markdown editor again.
|
||||
const shellPage = await waitForPageWithUrl(launched.app, 'shell/out')
|
||||
await shellPage.locator('.tab-bar .tab-item', { hasText: 'report.md' }).click()
|
||||
await exportMenu(launched.app, 'Export as Images…')
|
||||
await expect(page.locator('.status-export')).toHaveCount(0)
|
||||
expect((await readdir(dir)).filter((name) => name.startsWith('report-images-'))).toEqual(
|
||||
folders,
|
||||
)
|
||||
} finally {
|
||||
await closeAndSaveVideo(launched, 'markdown-image-export')
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
Generated
+2
-1
@@ -122,7 +122,8 @@
|
||||
"json5": "^2.2.3",
|
||||
"katex": "^0.16.47",
|
||||
"mermaid": "^11.17.2",
|
||||
"wavedrom": "^3.7.0"
|
||||
"wavedrom": "^3.7.0",
|
||||
"pdfjs-dist": "^6.2.108"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@genoffice/agent-core": "*",
|
||||
|
||||
@@ -314,11 +314,7 @@ export async function convertHtmlToDocx(
|
||||
const shotIds: string[] = []
|
||||
const shotNodes = new Map<string, any>()
|
||||
const pageBgShotIds = new Set<string>(
|
||||
ir
|
||||
.filter(
|
||||
(node): node is ValidatedIr & { shotId: string } => node.type === 'pagebg' && !!node.shotId,
|
||||
)
|
||||
.map((node) => node.shotId),
|
||||
ir.flatMap((node) => (node.type === 'pagebg' && node.shotId ? [node.shotId] : [])),
|
||||
)
|
||||
const collectRunShots = (runs: any[] | undefined) => {
|
||||
for (const run of runs || []) {
|
||||
|
||||
Reference in New Issue
Block a user