Preserve QPowerPoint manual line breaks
This commit is contained in:
@@ -151,6 +151,28 @@ describe("powerPointOffice helpers", () => {
|
||||
expect(imported.slides[0].subtitle).toBe("Plan\nBuild\nShip");
|
||||
});
|
||||
|
||||
it("сохраняет ручные переносы строк a:br внутри абзаца PPTX при импорте", async () => {
|
||||
const zip = new JSZip();
|
||||
zip.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>`
|
||||
);
|
||||
zip.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>`
|
||||
);
|
||||
zip.file("ppt/slides/slide1.xml", slideXmlWithManualBreakSubtitle("Roadmap", ["Plan", "Build", "Ship"]));
|
||||
|
||||
const blob = await zip.generateAsync({
|
||||
type: "blob",
|
||||
mimeType: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
|
||||
});
|
||||
const imported = await importPptxFile(new File([blob], "Roadmap.pptx", { type: blob.type }));
|
||||
|
||||
expect(imported.slides[0].title).toBe("Roadmap");
|
||||
expect(imported.slides[0].subtitle).toBe("Plan\nBuild\nShip");
|
||||
});
|
||||
|
||||
it("импортирует изображения слайда из PPTX media relationships", async () => {
|
||||
const zip = new JSZip();
|
||||
zip.file(
|
||||
@@ -368,6 +390,12 @@ function slideXmlWithMultilineSubtitle(title: string, subtitleParagraphs: string
|
||||
.join("")}</p:txBody></p:sp></p:spTree></p:cSld></p:sld>`;
|
||||
}
|
||||
|
||||
function slideXmlWithManualBreakSubtitle(title: string, subtitleLines: string[]) {
|
||||
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><a:p>${subtitleLines
|
||||
.map((text, index) => `${index > 0 ? "<a:br/>" : ""}<a:r><a:t>${text}</a:t></a:r>`)
|
||||
.join("")}</a:p></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>`;
|
||||
}
|
||||
|
||||
+127
-2
@@ -43,6 +43,7 @@ export async function importPptxFile(file: File): Promise<ImportedPowerPointDeck
|
||||
|
||||
const zip = await loadZip(file);
|
||||
const parser = await createXmlParser();
|
||||
const orderedParser = await createOrderedXmlParser();
|
||||
const title = officeTitleFromFileName(file.name, "Презентация QPowerPoint.pptx");
|
||||
const presentationXml = await readOptionalParsedXml(zip, parser, "ppt/presentation.xml");
|
||||
const presentationRelationshipsXml = await readOptionalParsedXml(zip, parser, "ppt/_rels/presentation.xml.rels");
|
||||
@@ -56,11 +57,14 @@ export async function importPptxFile(file: File): Promise<ImportedPowerPointDeck
|
||||
slidePaths.map(async ({ path, index }) => {
|
||||
const slideXml = await readRequiredZipText(zip, path, "Не удалось прочитать слайд PowerPoint.");
|
||||
const parsedSlide = parser.parse(slideXml);
|
||||
const slideTextBlocks = extractSlideTextBlocks(parsedSlide);
|
||||
const orderedSlide = orderedParser.parse(slideXml);
|
||||
const slideTextBlocks = mergeOrderedSlideTextBlocks(extractSlideTextBlocks(parsedSlide), extractOrderedTextBodyTexts(orderedSlide));
|
||||
const images = await extractSlideImages(zip, parser, parsedSlide, path, index);
|
||||
const notesPath = await slideNotesPath(zip, parser, path);
|
||||
const notesXml = notesPath ? await readOptionalZipText(zip, notesPath) : await readOptionalZipText(zip, `ppt/notesSlides/notesSlide${index}.xml`);
|
||||
const notes = notesXml ? extractTextBlocks(parser.parse(notesXml)).join("\n") : "";
|
||||
const notes = notesXml
|
||||
? extractOrderedTextBodyTexts(orderedParser.parse(notesXml)).join("\n") || extractTextBlocks(parser.parse(notesXml)).join("\n")
|
||||
: "";
|
||||
const backgroundColor = slideBackgroundColor(parsedSlide);
|
||||
|
||||
return {
|
||||
@@ -199,6 +203,44 @@ function extractSlideTextBlocks(slideXml: unknown): SlideTextBlock[] {
|
||||
return blocks.length > 0 ? blocks : extractTextBlocks(slideXml).map((text) => ({ text }));
|
||||
}
|
||||
|
||||
function mergeOrderedSlideTextBlocks(styledBlocks: SlideTextBlock[], orderedTexts: string[]) {
|
||||
if (orderedTexts.length === 0) {
|
||||
return styledBlocks;
|
||||
}
|
||||
|
||||
return orderedTexts.map((text, index) => {
|
||||
const styledBlock = styledBlocks[index] ?? { text };
|
||||
return { ...styledBlock, text };
|
||||
});
|
||||
}
|
||||
|
||||
function extractOrderedTextBodyTexts(xmlNode: unknown) {
|
||||
return orderedElementsByName(xmlNode, "txBody").map(orderedTextBodyText).filter(Boolean);
|
||||
}
|
||||
|
||||
function orderedTextBodyText(textBody: unknown) {
|
||||
const paragraphs = orderedDirectElements(textBody, "p").map(orderedParagraphText).filter(Boolean);
|
||||
return paragraphs.length > 0 ? paragraphs.join("\n") : "";
|
||||
}
|
||||
|
||||
function orderedParagraphText(paragraph: unknown) {
|
||||
return normalizeTextWithLineBreaks(
|
||||
orderedElementChildren(paragraph)
|
||||
.map((child) => {
|
||||
const name = orderedElementName(child);
|
||||
if (name === "r" || name === "fld") {
|
||||
return orderedXmlText(child);
|
||||
}
|
||||
if (name === "br") {
|
||||
return "\n";
|
||||
}
|
||||
|
||||
return "";
|
||||
})
|
||||
.join("")
|
||||
);
|
||||
}
|
||||
|
||||
function extractTextBodyText(textBody: Record<string, unknown>) {
|
||||
const paragraphs = toArray(textBody.p)
|
||||
.map((paragraph) => normalizeWhitespace(extractTextBlocks(paragraph).join("")))
|
||||
@@ -288,6 +330,15 @@ export function normalizeWhitespace(value: string): string {
|
||||
return value.replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
function normalizeTextWithLineBreaks(value: string): string {
|
||||
return value
|
||||
.split("\n")
|
||||
.map(normalizeWhitespace)
|
||||
.join("\n")
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim();
|
||||
}
|
||||
|
||||
async function extractSlideImages(
|
||||
zip: ZipArchive,
|
||||
parser: { parse: (xml: string) => unknown },
|
||||
@@ -461,6 +512,18 @@ async function createXmlParser(): Promise<{ parse: (xml: string) => unknown }> {
|
||||
});
|
||||
}
|
||||
|
||||
async function createOrderedXmlParser(): Promise<{ parse: (xml: string) => unknown }> {
|
||||
const moduleName = "fast-xml-parser";
|
||||
const parserModule = (await import(moduleName)) as { XMLParser: XmlParserConstructor };
|
||||
return new parserModule.XMLParser({
|
||||
ignoreAttributes: false,
|
||||
removeNSPrefix: true,
|
||||
textNodeName: "#text",
|
||||
trimValues: true,
|
||||
preserveOrder: true
|
||||
});
|
||||
}
|
||||
|
||||
async function readOptionalParsedXml(zip: ZipArchive, parser: { parse: (xml: string) => unknown }, path: string): Promise<unknown> {
|
||||
const xml = await readOptionalZipText(zip, path);
|
||||
return xml ? parser.parse(xml) : undefined;
|
||||
@@ -529,6 +592,68 @@ function isXmlAttributeKey(key: string) {
|
||||
return key.startsWith("@_") || ["id", "name", "descr", "x", "y", "cx", "cy", "embed", "link"].includes(key);
|
||||
}
|
||||
|
||||
function orderedElementsByName(node: unknown, name: string): unknown[] {
|
||||
const elements: unknown[] = [];
|
||||
visitOrderedElements(node, (element) => {
|
||||
if (orderedElementName(element) === name) {
|
||||
elements.push(element);
|
||||
}
|
||||
});
|
||||
return elements;
|
||||
}
|
||||
|
||||
function visitOrderedElements(node: unknown, visitor: (element: unknown) => void): void {
|
||||
if (Array.isArray(node)) {
|
||||
node.forEach((item) => visitOrderedElements(item, visitor));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!node || typeof node !== "object") {
|
||||
return;
|
||||
}
|
||||
|
||||
visitor(node);
|
||||
orderedElementChildren(node).forEach((child) => visitOrderedElements(child, visitor));
|
||||
}
|
||||
|
||||
function orderedDirectElements(node: unknown, name: string) {
|
||||
return orderedElementChildren(node).filter((child) => orderedElementName(child) === name);
|
||||
}
|
||||
|
||||
function orderedElementName(node: unknown) {
|
||||
return Object.keys(asRecord(node)).find((key) => key !== ":@") ?? "";
|
||||
}
|
||||
|
||||
function orderedElementChildren(node: unknown): unknown[] {
|
||||
const name = orderedElementName(node);
|
||||
return name ? toArray(asRecord(node)[name]) : [];
|
||||
}
|
||||
|
||||
function orderedXmlText(node: unknown): string {
|
||||
if (node === null || node === undefined) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (typeof node === "string" || typeof node === "number") {
|
||||
return String(node);
|
||||
}
|
||||
|
||||
if (Array.isArray(node)) {
|
||||
return node.map(orderedXmlText).join("");
|
||||
}
|
||||
|
||||
if (typeof node !== "object") {
|
||||
return "";
|
||||
}
|
||||
|
||||
const record = node as Record<string, unknown>;
|
||||
if (typeof record["#text"] === "string" || typeof record["#text"] === "number") {
|
||||
return String(record["#text"]);
|
||||
}
|
||||
|
||||
return orderedElementChildren(node).map(orderedXmlText).join("");
|
||||
}
|
||||
|
||||
function slideIndexFromPath(path: string): number | undefined {
|
||||
const match = slidePathPattern.exec(path);
|
||||
return match ? Number(match[1]) : undefined;
|
||||
|
||||
Reference in New Issue
Block a user