Preserve QPowerPoint subtitle lists in PPTX

This commit is contained in:
Курнат Андрей
2026-06-02 05:34:40 +03:00
parent 464484bb19
commit 57cce9ea96
6 changed files with 220 additions and 8 deletions
+88
View File
@@ -173,6 +173,86 @@ describe("powerPointOffice helpers", () => {
expect(imported.slides[0].subtitle).toBe("Plan\nBuild\nShip");
});
it("импортирует маркированные и нумерованные списки подзаголовка PPTX", async () => {
const bulletZip = new JSZip();
bulletZip.file(
"ppt/presentation.xml",
`<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><p:sldIdLst><p:sldId id="256" r:id="rId1"/></p:sldIdLst></p:presentation>`
);
bulletZip.file(
"ppt/_rels/presentation.xml.rels",
`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide1.xml"/></Relationships>`
);
bulletZip.file("ppt/slides/slide1.xml", slideXmlWithListSubtitle("План", ["Собрать требования", "Проверить импорт"], "bullet"));
const bulletBlob = await bulletZip.generateAsync({
type: "blob",
mimeType: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
});
const importedBullet = await importPptxFile(new File([bulletBlob], "Маркированный.pptx", { type: bulletBlob.type }));
expect(importedBullet.slides[0].subtitle).toBe("Собрать требования\nПроверить импорт");
expect(importedBullet.slides[0].subtitleListStyle).toBe("bullet");
const numberZip = new JSZip();
numberZip.file(
"ppt/presentation.xml",
`<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><p:sldIdLst><p:sldId id="256" r:id="rId1"/></p:sldIdLst></p:presentation>`
);
numberZip.file(
"ppt/_rels/presentation.xml.rels",
`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide1.xml"/></Relationships>`
);
numberZip.file("ppt/slides/slide1.xml", slideXmlWithListSubtitle("План", ["Шаг один", "Шаг два"], "number"));
const numberBlob = await numberZip.generateAsync({
type: "blob",
mimeType: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
});
const importedNumber = await importPptxFile(new File([numberBlob], "Нумерованный.pptx", { type: numberBlob.type }));
expect(importedNumber.slides[0].subtitle).toBe("Шаг один\nШаг два");
expect(importedNumber.slides[0].subtitleListStyle).toBe("number");
});
it("экспортирует списки подзаголовка PPTX как OOXML bullets", async () => {
const bulletBlob = await exportPptxBlob({
title: "Маркированный.pptx",
slides: [
{
id: "slide-1",
title: "План",
subtitle: "Собрать требования\nПроверить импорт",
subtitleListStyle: "bullet",
notes: "",
theme: "classic"
}
]
});
const bulletZip = await JSZip.loadAsync(await bulletBlob.arrayBuffer());
const bulletSlideXml = (await bulletZip.file("ppt/slides/slide1.xml")?.async("string")) ?? "";
expect(bulletSlideXml).toContain("<a:buChar");
const numberBlob = await exportPptxBlob({
title: "Нумерованный.pptx",
slides: [
{
id: "slide-1",
title: "План",
subtitle: "Шаг один\nШаг два",
subtitleListStyle: "number",
notes: "",
theme: "classic"
}
]
});
const numberZip = await JSZip.loadAsync(await numberBlob.arrayBuffer());
const numberSlideXml = (await numberZip.file("ppt/slides/slide1.xml")?.async("string")) ?? "";
expect(numberSlideXml).toContain("<a:buAutoNum");
});
it("импортирует изображения слайда из PPTX media relationships", async () => {
const zip = new JSZip();
zip.file(
@@ -486,6 +566,14 @@ function slideXmlWithManualBreakSubtitle(title: string, subtitleLines: string[])
.join("")}</a:p></p:txBody></p:sp></p:spTree></p:cSld></p:sld>`;
}
function slideXmlWithListSubtitle(title: string, subtitleLines: string[], listStyle: "bullet" | "number") {
const paragraphProperties =
listStyle === "number" ? '<a:pPr><a:buAutoNum type="arabicPeriod"/></a:pPr>' : '<a:pPr><a:buChar char="•"/></a:pPr>';
return `<p:sld xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><p:cSld><p:spTree><p:sp><p:txBody><a:p><a:r><a:t>${title}</a:t></a:r></a:p></p:txBody></p:sp><p:sp><p:txBody>${subtitleLines
.map((text) => `<a:p>${paragraphProperties}<a:r><a:t>${text}</a:t></a:r></a:p>`)
.join("")}</p:txBody></p:sp></p:spTree></p:cSld></p:sld>`;
}
function slideXmlWithPicture(title: string) {
return `<p:sld xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><p:cSld><p:spTree><p:sp><p:txBody><a:p><a:r><a:t>${title}</a:t></a:r></a:p></p:txBody></p:sp><p:pic><p:nvPicPr><p:cNvPr id="4" name="Picture 1" descr="Логотип"/></p:nvPicPr><p:blipFill><a:blip r:embed="rIdImage"/></p:blipFill><p:spPr><a:xfrm><a:off x="914400" y="1828800"/><a:ext cx="2743200" cy="1371600"/></a:xfrm></p:spPr></p:pic></p:spTree></p:cSld></p:sld>`;
}
+66 -4
View File
@@ -1,4 +1,4 @@
import type { Slide, SlideImage } from "../types";
import type { Slide, SlideImage, SlideListStyle } from "../types";
import { officeTitleFromFileName, PPTX_MIME_TYPE, readOfficeFileAsArrayBuffer } from "./fileHelpers";
export interface ImportedPowerPointDeck {
@@ -13,6 +13,7 @@ export interface ExportablePowerPointDeck {
interface SlideTextBlock {
text: string;
listStyle?: SlideListStyle;
color?: string;
fontSize?: number;
fontFamily?: string;
@@ -77,6 +78,10 @@ export async function importPptxFile(file: File): Promise<ImportedPowerPointDeck
const backgroundColor = slideBackgroundColor(parsedSlide);
const hidden = slideHidden(parsedSlide);
const transition = slideTransition(parsedSlide);
const subtitleListStyle = slideTextBlocks
.slice(1)
.map((block) => block.listStyle)
.find((style): style is SlideListStyle => Boolean(style));
return {
id: `pptx-slide-${index}`,
@@ -93,6 +98,7 @@ export async function importPptxFile(file: File): Promise<ImportedPowerPointDeck
...(slideTextBlocks[1]?.color ? { subtitleColor: slideTextBlocks[1].color } : {}),
...(slideTextBlocks[1]?.fontSize ? { subtitleFontSize: slideTextBlocks[1].fontSize } : {}),
...(slideTextBlocks[1]?.fontFamily ? { subtitleFontFamily: slideTextBlocks[1].fontFamily } : {}),
...(subtitleListStyle ? { subtitleListStyle } : {}),
images
};
})
@@ -183,7 +189,9 @@ export async function exportPptxBlob(deck: ExportablePowerPointDeck): Promise<Bl
const result = await pptx.write({ outputType: "blob" });
const blob = result instanceof Blob ? result : new Blob([result], { type: PPTX_MIME_TYPE });
return deck.slides.some((slide) => slide.hidden || slide.transition) ? applySlideXmlOverridesToPptxBlob(blob, deck.slides) : blob;
return deck.slides.some((slide) => slide.hidden || slide.transition || slide.subtitleListStyle)
? applySlideXmlOverridesToPptxBlob(blob, deck.slides)
: blob;
}
export function extractTextBlocks(xmlNode: unknown): string[] {
@@ -202,11 +210,13 @@ function extractSlideTextBlocks(slideXml: unknown): SlideTextBlock[] {
}
const runProperties = firstRecordByKey(textBody, "rPr");
const listStyle = textBodyListStyle(textBody);
const color = runTextColor(runProperties);
const fontSize = runTextFontSize(runProperties);
const fontFamily = runTextFontFamily(runProperties);
return {
text,
...(listStyle ? { listStyle } : {}),
...(color ? { color } : {}),
...(fontSize ? { fontSize } : {}),
...(fontFamily ? { fontFamily } : {})
@@ -228,6 +238,26 @@ function mergeOrderedSlideTextBlocks(styledBlocks: SlideTextBlock[], orderedText
});
}
function textBodyListStyle(textBody: Record<string, unknown>): SlideListStyle | undefined {
const paragraphStyles = toArray(textBody.p)
.map(paragraphListStyle)
.filter((style): style is SlideListStyle => Boolean(style));
return paragraphStyles.includes("number") ? "number" : paragraphStyles[0];
}
function paragraphListStyle(paragraph: unknown): SlideListStyle | undefined {
const paragraphProperties = childRecord(asRecord(paragraph), "pPr");
if (Object.keys(childRecord(paragraphProperties, "buAutoNum")).length > 0) {
return "number";
}
if (Object.keys(childRecord(paragraphProperties, "buChar")).length > 0) {
return "bullet";
}
return undefined;
}
function extractOrderedTextBodyTexts(xmlNode: unknown) {
return orderedElementsByName(xmlNode, "txBody").map(orderedTextBodyText).filter(Boolean);
}
@@ -482,7 +512,7 @@ async function applySlideXmlOverridesToPptxBlob(blob: Blob, slides: Slide[]) {
const zip = await JSZip.loadAsync(await blob.arrayBuffer());
await Promise.all(
slides.map(async (slide, index) => {
if (!slide.hidden && !slide.transition) {
if (!slide.hidden && !slide.transition && !slide.subtitleListStyle) {
return;
}
@@ -499,7 +529,8 @@ async function applySlideXmlOverridesToPptxBlob(blob: Blob, slides: Slide[]) {
function pptxSlideXmlWithOverrides(xml: string, slide: Slide) {
const withHiddenState = slide.hidden ? pptxSlideXmlWithHiddenState(xml) : xml;
return slide.transition ? pptxSlideXmlWithTransition(withHiddenState, slide.transition) : withHiddenState;
const withTransition = slide.transition ? pptxSlideXmlWithTransition(withHiddenState, slide.transition) : withHiddenState;
return slide.subtitleListStyle ? pptxSlideXmlWithSubtitleList(withTransition, slide.subtitleListStyle) : withTransition;
}
function pptxSlideXmlWithHiddenState(xml: string) {
@@ -524,6 +555,37 @@ function pptxSlideXmlWithTransition(xml: string, transition: NonNullable<Slide["
return xml.replace(/<p:sld\b[^>]*>/, (match) => `${match}${transitionXml}`);
}
function pptxSlideXmlWithSubtitleList(xml: string, listStyle: SlideListStyle) {
let textBodyIndex = 0;
return xml.replace(/<p:txBody\b[\s\S]*?<\/p:txBody>/g, (textBodyXml) => {
textBodyIndex += 1;
return textBodyIndex === 2 ? pptxTextBodyXmlWithList(textBodyXml, listStyle) : textBodyXml;
});
}
function pptxTextBodyXmlWithList(textBodyXml: string, listStyle: SlideListStyle) {
return textBodyXml.replace(/<a:p>[\s\S]*?<\/a:p>/g, (paragraphXml) => pptxParagraphXmlWithList(paragraphXml, listStyle));
}
function pptxParagraphXmlWithList(paragraphXml: string, listStyle: SlideListStyle) {
const listXml = pptxParagraphListXml(listStyle);
if (/<a:pPr\b[^>]*\/>/.test(paragraphXml)) {
return paragraphXml.replace(/<a:pPr\b([^>]*)\/>/, `<a:pPr$1>${listXml}</a:pPr>`);
}
if (/<a:pPr\b/.test(paragraphXml)) {
return paragraphXml.replace(/<a:pPr\b([^>]*)>([\s\S]*?)<\/a:pPr>/, (_match, attributes: string, content: string) => {
const contentWithoutBullet = content.replace(/<a:bu[A-Za-z]+\b[^>]*\/>/g, "");
return `<a:pPr${attributes}>${listXml}${contentWithoutBullet}</a:pPr>`;
});
}
return paragraphXml.replace("<a:p>", `<a:p><a:pPr>${listXml}</a:pPr>`);
}
function pptxParagraphListXml(listStyle: SlideListStyle) {
return listStyle === "number" ? '<a:buAutoNum type="arabicPeriod"/>' : '<a:buChar char="•"/>';
}
function normalizeHexColor(value?: string) {
const raw = value?.trim().replace(/^#/, "").toUpperCase() ?? "";
return /^[0-9A-F]{6}$/.test(raw) ? raw : "";