fix(preview): repair PptxGenJS slide masters so previews render
vue-office-pptx shows zero slides when generated decks omit unused master declarations; rewrite the preview copy without changing the stored file.main
parent
3910cfb117
commit
eeaaa7f64c
|
|
@ -18,6 +18,7 @@
|
|||
"docx-preview": "^0.3.7",
|
||||
"dompurify": "^3.4.11",
|
||||
"highlight.js": "^11.11.1",
|
||||
"jszip": "3.10.1",
|
||||
"katex": "^0.16.45",
|
||||
"marked": "^17.0.5",
|
||||
"marked-katex-extension": "^5.1.8",
|
||||
|
|
@ -42,6 +43,7 @@
|
|||
"@vitejs/plugin-vue": "6.0.6",
|
||||
"@vitejs/plugin-vue-jsx": "5.1.5",
|
||||
"@vue/tsconfig": "^0.9.1",
|
||||
"@xmldom/xmldom": "0.9.12",
|
||||
"less": "^4.6.4",
|
||||
"less-loader": "^12.3.2",
|
||||
"npm-run-all2": "^8.0.4",
|
||||
|
|
@ -2331,6 +2333,16 @@
|
|||
"@xtuc/long": "4.2.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@xmldom/xmldom": {
|
||||
"version": "0.9.12",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@xmldom/xmldom/-/xmldom-0.9.12.tgz",
|
||||
"integrity": "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.6"
|
||||
}
|
||||
},
|
||||
"node_modules/@xterm/addon-fit": {
|
||||
"version": "0.10.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@xterm/addon-fit/-/addon-fit-0.10.0.tgz",
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@
|
|||
"docx-preview": "^0.3.7",
|
||||
"dompurify": "^3.4.11",
|
||||
"highlight.js": "^11.11.1",
|
||||
"jszip": "3.10.1",
|
||||
"katex": "^0.16.45",
|
||||
"marked": "^17.0.5",
|
||||
"marked-katex-extension": "^5.1.8",
|
||||
|
|
@ -50,6 +51,7 @@
|
|||
"@vitejs/plugin-vue": "6.0.6",
|
||||
"@vitejs/plugin-vue-jsx": "5.1.5",
|
||||
"@vue/tsconfig": "^0.9.1",
|
||||
"@xmldom/xmldom": "0.9.12",
|
||||
"less": "^4.6.4",
|
||||
"less-loader": "^12.3.2",
|
||||
"npm-run-all2": "^8.0.4",
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import 'highlight.js/styles/github.css';
|
|||
import 'katex/dist/katex.min.css';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { sanitizeHTML, sanitizeMarkdownHTML } from '@/utils/security';
|
||||
import { preparePptxPreview, isCompletePptxRender } from '@/utils/pptxPreview';
|
||||
import { renderDocumentPreviewMarkdown } from '@/utils/documentPreviewMarkdown';
|
||||
import { buildHtmlPreview } from '@/utils/htmlPreview';
|
||||
import { openMermaidFullscreen } from '@/utils/mermaidViewer';
|
||||
|
|
@ -57,6 +58,10 @@ const excelHtml = ref('');
|
|||
const mermaidSvg = ref('');
|
||||
const htmlViewMode = ref<'render' | 'source'>('render');
|
||||
const pptxData = shallowRef<ArrayBuffer | null>(null);
|
||||
let pptxSlideCount = 0;
|
||||
function onPptxRendered(result: unknown) {
|
||||
if (!isCompletePptxRender(result, pptxSlideCount)) error.value = t('preview.loadFailed');
|
||||
}
|
||||
const docxContainer = ref<HTMLElement | null>(null);
|
||||
const imageNaturalWidth = ref(0);
|
||||
const imageNaturalHeight = ref(0);
|
||||
|
|
@ -429,7 +434,10 @@ async function loadPreview() {
|
|||
break;
|
||||
}
|
||||
case 'pptx': {
|
||||
pptxData.value = await blob.arrayBuffer();
|
||||
const prepared = await preparePptxPreview(await blob.arrayBuffer());
|
||||
if (getPreviewSourceKey() !== sourceKey || !props.active) return;
|
||||
pptxSlideCount = prepared.slideCount;
|
||||
pptxData.value = prepared.data;
|
||||
break;
|
||||
}
|
||||
case 'mermaid': {
|
||||
|
|
@ -457,6 +465,7 @@ function cleanup() {
|
|||
mermaidSvg.value = '';
|
||||
htmlViewMode.value = 'render';
|
||||
pptxData.value = null;
|
||||
pptxSlideCount = 0;
|
||||
imageNaturalWidth.value = 0;
|
||||
imageNaturalHeight.value = 0;
|
||||
loadedForId = '';
|
||||
|
|
@ -566,7 +575,7 @@ onUnmounted(() => {
|
|||
|
||||
<!-- PPTX -->
|
||||
<div v-else-if="previewType === 'pptx' && pptxData" ref="previewContent" tabindex="0" :aria-label="fileName" class="preview-pptx">
|
||||
<vue-office-pptx :src="pptxData" @rendered="() => {}" @error="(e: any) => { error = e?.message || $t('preview.loadFailed'); }" />
|
||||
<vue-office-pptx :key="loadedForId" :src="pptxData" @rendered="onPptxRendered" @error="(e: any) => { error = e?.message || $t('preview.loadFailed'); }" />
|
||||
</div>
|
||||
|
||||
<!-- Excel -->
|
||||
|
|
|
|||
|
|
@ -0,0 +1,67 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import JSZip from 'jszip'
|
||||
import { DOMParser, XMLSerializer } from '@xmldom/xmldom'
|
||||
import { preparePptxPreview, isCompletePptxRender } from './pptxPreview'
|
||||
|
||||
Object.assign(globalThis, { DOMParser, XMLSerializer })
|
||||
const typesNs = 'http://schemas.openxmlformats.org/package/2006/content-types'
|
||||
const relsNs = 'http://schemas.openxmlformats.org/package/2006/relationships'
|
||||
const masterType = 'application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml'
|
||||
const missingPart = '/ppt/slideMasters/slideMaster2.xml'
|
||||
|
||||
async function fixture({ dangling = true, reference = '', external = false, prefix = '' } = {}) {
|
||||
const zip = new JSZip()
|
||||
zip.file('ppt/presentation.xml', '<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:sldIdLst><p:sldId id="256"/><p:sldId id="257"/></p:sldIdLst></p:presentation>')
|
||||
zip.file('ppt/slides/slide1.xml', '<slide>First slide</slide>')
|
||||
zip.file('ppt/slides/slide2.xml', '<slide>Second slide</slide>')
|
||||
zip.file('ppt/slideMasters/slideMaster1.xml', '<master/>')
|
||||
const tag = prefix ? `${prefix}:` : ''
|
||||
zip.file('[Content_Types].xml', `<${tag}Types xmlns${prefix ? ':' + prefix : ''}="${typesNs}"><${tag}Override PartName="/ppt/slideMasters/slideMaster1.xml" ContentType="${masterType}"/>${dangling ? `<${tag}Override PartName="${missingPart}" ContentType="${masterType}"/>` : ''}</${tag}Types>`)
|
||||
zip.file('ppt/slideLayouts/_rels/slideLayout1.xml.rels', `<Relationships xmlns="${relsNs}"><Relationship Id="rId1" Target="${reference || '../slideMasters/slideMaster1.xml'}"${external ? ' TargetMode="External"' : ''}/></Relationships>`)
|
||||
return zip.generateAsync({ type: 'arraybuffer' })
|
||||
}
|
||||
|
||||
test('removes unused missing masters from a preview copy and preserves every other part', async () => {
|
||||
const input = await fixture()
|
||||
const originalBytes = new Uint8Array(input).slice()
|
||||
const result = await preparePptxPreview(input)
|
||||
assert.equal(result.slideCount, 2)
|
||||
assert.deepEqual(new Uint8Array(input), originalBytes)
|
||||
const before = await JSZip.loadAsync(input), after = await JSZip.loadAsync(result.data)
|
||||
const xml = await after.file('[Content_Types].xml')!.async('string')
|
||||
assert.ok(!xml.includes(missingPart))
|
||||
assert.ok(xml.includes('/ppt/slideMasters/slideMaster1.xml'))
|
||||
assert.deepEqual(Object.keys(before.files), Object.keys(after.files))
|
||||
for (const part of Object.values(before.files)) {
|
||||
if (!part.dir && part.name !== '[Content_Types].xml') {
|
||||
assert.deepEqual(await part.async('uint8array'), await after.file(part.name)!.async('uint8array'))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('does not repack a valid presentation', async () => {
|
||||
const input = await fixture({ dangling: false })
|
||||
assert.equal((await preparePptxPreview(input)).data, input)
|
||||
})
|
||||
|
||||
test('never removes missing masters referenced by relative, absolute or encoded OPC paths', async () => {
|
||||
for (const reference of ['../slideMasters/slideMaster2.xml', '/ppt/slideMasters/slideMaster2.xml', '../slideMasters/slideMaster%32.xml']) {
|
||||
await assert.rejects(preparePptxPreview(await fixture({ reference })), /references a missing slide master/)
|
||||
}
|
||||
})
|
||||
|
||||
test('supports namespace prefixes and ignores external relationships', async () => {
|
||||
const input = await fixture({ prefix: 'ct', reference: '../slideMasters/slideMaster2.xml', external: true })
|
||||
const result = await preparePptxPreview(input)
|
||||
const zip = await JSZip.loadAsync(result.data)
|
||||
assert.ok(!(await zip.file('[Content_Types].xml')!.async('string')).includes(missingPart))
|
||||
})
|
||||
|
||||
test('zero and partial render success events must be treated as failures', () => {
|
||||
for (const result of [null, undefined, {}, { slides: [] }, { slides: [{}] }]) {
|
||||
assert.equal(isCompletePptxRender(result, 2), false)
|
||||
}
|
||||
assert.equal(isCompletePptxRender({ slides: [{}, {}] }, 2), true)
|
||||
assert.equal(isCompletePptxRender({ slides: [] }, 0), false)
|
||||
})
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
import JSZip from 'jszip'
|
||||
|
||||
const CONTENT_TYPES_NS = 'http://schemas.openxmlformats.org/package/2006/content-types'
|
||||
const RELATIONSHIPS_NS = 'http://schemas.openxmlformats.org/package/2006/relationships'
|
||||
const PRESENTATION_NS = 'http://schemas.openxmlformats.org/presentationml/2006/main'
|
||||
const SLIDE_MASTER_TYPE = 'application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml'
|
||||
|
||||
function parseXml(source: string): Document {
|
||||
const document = new DOMParser().parseFromString(source, 'application/xml')
|
||||
if (document.getElementsByTagName('parsererror').length) throw new Error('Invalid PPTX metadata')
|
||||
return document
|
||||
}
|
||||
|
||||
/** Resolve an OPC relationship relative to its owning part, not its _rels directory. */
|
||||
function relationshipTarget(relsPath: string, target: string): string {
|
||||
const base = relsPath === '_rels/.rels' ? '' : relsPath.slice(0, relsPath.lastIndexOf('/_rels/') + 1)
|
||||
return decodeURIComponent(new URL(target, `https://pptx.invalid/${base}`).pathname.slice(1))
|
||||
}
|
||||
|
||||
/**
|
||||
* PptxGenJS 4.0.1 declares a master per slide even when only one master is stored.
|
||||
* Office ignores these unused entries; vue-office aborts parsing and returns zero
|
||||
* slides. Repair only missing, unreferenced master declarations in a preview copy.
|
||||
* Never remove a referenced part or alter the downloaded original.
|
||||
*/
|
||||
export async function preparePptxPreview(data: ArrayBuffer): Promise<{ data: ArrayBuffer; slideCount: number }> {
|
||||
const zip = await JSZip.loadAsync(data)
|
||||
const typesPart = zip.file('[Content_Types].xml')
|
||||
const presentationPart = zip.file('ppt/presentation.xml')
|
||||
if (!typesPart || !presentationPart) throw new Error('Invalid PPTX package')
|
||||
const types = parseXml(await typesPart.async('string'))
|
||||
const presentation = parseXml(await presentationPart.async('string'))
|
||||
const slideCount = presentation.getElementsByTagNameNS(PRESENTATION_NS, 'sldId').length
|
||||
if (!slideCount) throw new Error('PPTX contains no slides')
|
||||
|
||||
const missingMasters = Array.from(types.getElementsByTagNameNS(CONTENT_TYPES_NS, 'Override')).filter(entry => {
|
||||
const partName = entry.getAttribute('PartName') || ''
|
||||
return entry.getAttribute('ContentType') === SLIDE_MASTER_TYPE
|
||||
&& partName.startsWith('/ppt/slideMasters/') && !zip.file(decodeURIComponent(partName.slice(1)))
|
||||
})
|
||||
if (!missingMasters.length) return { data, slideCount }
|
||||
|
||||
const references = new Set<string>()
|
||||
for (const part of Object.values(zip.files)) {
|
||||
if (part.dir || !part.name.endsWith('.rels')) continue
|
||||
const relations = parseXml(await part.async('string'))
|
||||
for (const rel of Array.from(relations.getElementsByTagNameNS(RELATIONSHIPS_NS, 'Relationship'))) {
|
||||
const target = rel.getAttribute('Target')
|
||||
if (target && rel.getAttribute('TargetMode') !== 'External') references.add(relationshipTarget(part.name, target))
|
||||
}
|
||||
}
|
||||
for (const entry of missingMasters) {
|
||||
const partName = decodeURIComponent(entry.getAttribute('PartName')!.slice(1))
|
||||
if (references.has(partName)) throw new Error('PPTX references a missing slide master')
|
||||
entry.parentNode!.removeChild(entry)
|
||||
}
|
||||
zip.file('[Content_Types].xml', new XMLSerializer().serializeToString(types))
|
||||
return { data: await zip.generateAsync({ type: 'arraybuffer' }), slideCount }
|
||||
}
|
||||
|
||||
/** The renderer can swallow parsing errors and report successful empty/partial output. */
|
||||
export function isCompletePptxRender(result: unknown, expectedSlides: number): boolean {
|
||||
const slides = (result as { slides?: unknown[] } | null)?.slides
|
||||
return expectedSlides > 0 && Array.isArray(slides) && slides.length === expectedSlides
|
||||
}
|
||||
Loading…
Reference in New Issue