/** * Read `p:spTree` into the shape node column of PptxSourceModel source. * * simple autoshape (`p:sp`), embedded raster image (`p:pic`), connector * (`p:cxnSp`), and group (`p:grpSp`) are represented in typed. graphicFrame is table / * Convert supported subset of chart/SmartArt to typed, and other unsupported nodes * Save as raw shape node. Even within a typed node, unsupported child elements/attributes are raw * sidecar . * * If `orderedChildren` is passed, use preserve-order XML parse result and * z-order between tags.when omitted, falls back to the legacy per-tag ordering * do. */ import type { PartPath, RawSidecarId, SourceBlipEffects, SourceCellBorders, SourceChart, SourceConnector, SourceEffectList, SourceGeometry, SourceGroup, SourceImage, SourceImageCrop, SourceImageStretch, SourceNodeId, SourcePlaceholder, SourceRawShapeNode, SourceShape, SourceShapeNode, SourceShapeStyle, SourceSmartArt, SourceStyleReference, SourceTable, SourceTableCell, SourceTableColumn, SourceTableRow, SourceTransform, } from "../source/index.js"; import { asEmu, asOoxmlPercent, asRelationshipId, asSourceNodeId } from "../source/index.js"; import { unsafeOoxmlBoundaryAssertion } from "../unsafe-type-assertion.js"; import { parseCustomGeometry } from "./custom-geometry.js"; import { isTrue, numericAttr, parseBlipEffects, parseColorElement, parseEffectList, parseFill, parseImageFillTile, parseLine, parseOutline, parseTransform, } from "./drawing.js"; import { collectUnknownSidecars, makeSidecar } from "./raw-node.js"; import { getShapeTreeContainerPropertyKeys, isShapeTreeZOrderChildKey, } from "./shape-tree-child-classification.js"; import { parseTextBody } from "./text.js"; import { getAttr, getChild, getChildArray, getChildText, getNamespacedAttr, hasChild, localName, type XmlNode, type XmlOrderedNode, } from "./xml.js"; const KNOWN_SHAPE_CHILDREN: ReadonlySet = new Set(["nvSpPr", "spPr", "style", "txBody"]); const KNOWN_CONNECTOR_CHILDREN: ReadonlySet = new Set(["nvCxnSpPr", "spPr", "style"]); const KNOWN_GROUP_CHILDREN: ReadonlySet = new Set(["nvGrpSpPr", "grpSpPr"]); const KNOWN_PICTURE_CHILDREN: ReadonlySet = new Set(["nvPicPr", "blipFill", "spPr"]); const KNOWN_BLIP_FILL_CHILDREN: ReadonlySet = new Set([ "blip", "srcRect", "stretch", "tile", ]); const KNOWN_BLIP_CHILDREN: ReadonlySet = new Set([ "grayscl", "biLevel", "blur", "lum", "duotone", "clrChange", ]); const KNOWN_EFFECT_CHILDREN: ReadonlySet = new Set([ "outerShdw", "innerShdw", "glow", "softEdge", ]); const KNOWN_GRAPHIC_FRAME_CHILDREN: ReadonlySet = new Set([ "nvGraphicFramePr", "xfrm", "graphic", ]); const KNOWN_GRAPHIC_CHILDREN: ReadonlySet = new Set(["graphicData"]); const KNOWN_GRAPHIC_DATA_CHILDREN: ReadonlySet = new Set(["tbl"]); const KNOWN_TABLE_CHILDREN: ReadonlySet = new Set(["tblPr", "tblGrid", "tr"]); const KNOWN_TABLE_CELL_CHILDREN: ReadonlySet = new Set(["txBody", "tcPr"]); const KNOWN_TABLE_CELL_PROPERTIES_CHILDREN: ReadonlySet = new Set([ "lnL", "lnR", "lnT", "lnB", "solidFill", "noFill", "gradFill", "blipFill", "pattFill", "grpFill", ]); // Children of `a:spPr` interpreted as typed data. Everything else (custGeom / effectLst / scene3d / // extLst etc.) are retained as raw sidecars. For the fill type, parseFill uses typed/raw. // decides typed/raw handling and this prevents double-counting. const KNOWN_SP_PR_CHILDREN: ReadonlySet = new Set([ "xfrm", "prstGeom", "solidFill", "noFill", "gradFill", "blipFill", "pattFill", "grpFill", "ln", "effectLst", ]); const SHAPE_TREE_NODE_TAGS: ReadonlySet = new Set([ "sp", "pic", "cxnSp", "grpSp", "graphicFrame", ]); const CHART_GRAPHIC_DATA_URIS: ReadonlySet = new Set([ "http://schemas.openxmlformats.org/drawingml/2006/chart", "http://purl.oclc.org/ooxml/drawingml/chart", ]); const SMARTART_DIAGRAM_URIS: ReadonlySet = new Set([ "http://schemas.openxmlformats.org/drawingml/2006/diagram", "http://purl.oclc.org/ooxml/drawingml/diagram", ]); /** Read `p:spTree` and return the shape node column. */ export function parseShapeTree( spTree: XmlNode | undefined, partPath: PartPath, nextId: () => RawSidecarId, orderedChildren?: readonly XmlOrderedNode[], ): SourceShapeNode[] { if (!spTree) return []; if (orderedChildren !== undefined) { return parseShapeTreeOrdered(spTree, partPath, nextId, orderedChildren); } const nodes: SourceShapeNode[] = []; let orderingSlot = 0; for (const key of Object.keys(spTree)) { if (key.startsWith("@_")) continue; if (key === "#text") continue; const local = localName(key); // The group's own non-visual properties are not nodes, so exclude them. if (local === "nvGrpSpPr" || local === "grpSpPr") continue; const value = spTree[key]; const items = Array.isArray(value) ? value : [value]; for (const item of items) { const node = unsafeOoxmlBoundaryAssertion(item); if (local === "sp") { nodes.push(parseShape(node, partPath, nextId, orderingSlot)); } else if (local === "pic") { nodes.push(parseImage(node, partPath, nextId, orderingSlot)); } else if (local === "cxnSp") { nodes.push(parseConnector(node, partPath, nextId, orderingSlot)); } else if (local === "grpSp") { nodes.push(parseGroup(node, partPath, nextId, orderingSlot)); } else if (local === "graphicFrame") { nodes.push(parseGraphicFrame(node, partPath, nextId, orderingSlot)); } else if (local === "AlternateContent") { const parsed = parseAlternateContent(node, partPath, nextId, orderingSlot); nodes.push(...parsed); } else { nodes.push(parseRawShapeNode(key, node, partPath, nextId, orderingSlot)); } orderingSlot++; } } return nodes; } function parseShapeTreeOrdered( spTree: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, orderedChildren: readonly XmlOrderedNode[], ): SourceShapeNode[] { const nodes: SourceShapeNode[] = []; const tagCounters: Record = {}; const containerPropertyKeys = getShapeTreeContainerPropertyKeys(spTree); let orderingSlot = 0; for (const child of orderedChildren) { const key = orderedElementKey(child); if (key === undefined || key.startsWith("#")) continue; const local = localName(key); if (local === "AlternateContent") { const index = tagCounters[key] ?? 0; tagCounters[key] = index + 1; const alternateContents = getQualifiedChildArray(spTree, key); const alternateContent = alternateContents[index]; if (alternateContent !== undefined) { nodes.push(...parseAlternateContent(alternateContent, partPath, nextId, orderingSlot)); orderingSlot++; } continue; } // The container's own properties are not z-order nodes. Every other child must remain in // the typed sequence, including unsupported extensions, so topology edits cannot mistake // shapes separated by preserved XML for consecutive siblings. if (!isShapeTreeZOrderChildKey(key, containerPropertyKeys)) continue; const index = tagCounters[key] ?? 0; tagCounters[key] = index + 1; const node = getQualifiedChildArray(spTree, key)[index]; if (node === undefined) continue; nodes.push( SHAPE_TREE_NODE_TAGS.has(local) ? parseShapeTreeNode(local, node, child, partPath, nextId, orderingSlot) : parseRawShapeNode(key, node, partPath, nextId, orderingSlot), ); orderingSlot++; } return nodes; } function parseShapeTreeNode( local: string, node: XmlNode, orderedNode: XmlOrderedNode | undefined, partPath: PartPath, nextId: () => RawSidecarId, orderingSlot: number, ): SourceShapeNode { if (local === "sp") return parseShape(node, partPath, nextId, orderingSlot, orderedNode); if (local === "pic") return parseImage(node, partPath, nextId, orderingSlot); if (local === "cxnSp") { return parseConnector(node, partPath, nextId, orderingSlot, orderedNode); } if (local === "grpSp") { const orderedKey = orderedNode === undefined ? undefined : orderedElementKey(orderedNode); const orderedGroupChildren = unsafeOoxmlBoundaryAssertion< readonly XmlOrderedNode[] | undefined >(orderedKey === undefined ? undefined : orderedNode?.[orderedKey]); return parseGroup(node, partPath, nextId, orderingSlot, orderedGroupChildren); } if (local === "graphicFrame") { return parseGraphicFrame(node, partPath, nextId, orderingSlot, orderedNode); } return parseRawShapeNode(`p:${local}`, node, partPath, nextId, orderingSlot); } function parseShape( sp: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, orderingSlot: number, orderedNode?: XmlOrderedNode, ): SourceShape { const nvSpPr = getChild(sp, "nvSpPr"); const cNvPr = getChild(nvSpPr, "cNvPr"); const nodeId = sourceNodeId(cNvPr); const name = getAttr(cNvPr, "name"); const placeholder = parsePlaceholderChild(getChild(nvSpPr, "nvPr")); const spPr = getChild(sp, "spPr"); const transform = parseTransform(spPr); const geometry = parseGeometry(spPr, orderedNestedChildChildren(orderedNode, "sp", "spPr")); const fill = parseFill(spPr, nextId); const outline = parseOutline(spPr, nextId); const effects = parseEffectList(getChild(spPr, "effectLst")); const style = parseShapeStyle(getChild(sp, "style")); const textBody = parseTextBody( getChild(sp, "txBody"), partPath, nextId, nodeId, orderingSlot, orderedNestedChildChildren(orderedNode, "sp", "txBody"), ); const rawSidecars = [ ...collectUnknownSidecars(sp, KNOWN_SHAPE_CHILDREN, nextId), ...collectUnknownSidecars(spPr, KNOWN_SP_PR_CHILDREN, nextId), ...collectEffectSidecars(spPr, effects, nextId), ]; return { kind: "shape", ...(nodeId !== undefined ? { nodeId } : {}), ...(name !== undefined ? { name } : {}), ...(transform !== undefined ? { transform } : {}), ...(geometry !== undefined ? { geometry } : {}), ...(fill !== undefined ? { fill } : {}), ...(outline !== undefined ? { outline } : {}), ...(effects !== undefined ? { effects } : {}), ...(style !== undefined ? { style } : {}), ...(textBody !== undefined ? { textBody } : {}), ...(placeholder !== undefined ? { placeholder } : {}), handle: { partPath, ...(nodeId !== undefined ? { nodeId } : {}), orderingSlot }, ...(rawSidecars.length > 0 ? { rawSidecars } : {}), }; } function parseConnector( cxnSp: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, orderingSlot: number, orderedNode?: XmlOrderedNode, ): SourceConnector { const nvCxnSpPr = getChild(cxnSp, "nvCxnSpPr"); const cNvPr = getChild(nvCxnSpPr, "cNvPr"); const cNvCxnSpPr = getChild(nvCxnSpPr, "cNvCxnSpPr"); const nodeId = sourceNodeId(cNvPr); const name = getAttr(cNvPr, "name"); const connection = parseConnectorConnection(cNvCxnSpPr); const spPr = getChild(cxnSp, "spPr"); const transform = parseTransform(spPr); const geometry = parseGeometry(spPr, orderedNestedChildChildren(orderedNode, "cxnSp", "spPr")); const outline = parseOutline(spPr, nextId); const effects = parseEffectList(getChild(spPr, "effectLst")); const style = parseShapeStyle(getChild(cxnSp, "style")); const rawSidecars = [ ...collectUnknownSidecars(cxnSp, KNOWN_CONNECTOR_CHILDREN, nextId), ...collectUnknownSidecars(spPr, KNOWN_SP_PR_CHILDREN, nextId), ...collectEffectSidecars(spPr, effects, nextId), ]; return { kind: "connector", ...(nodeId !== undefined ? { nodeId } : {}), ...(name !== undefined ? { name } : {}), ...(connection !== undefined ? { connection } : {}), ...(transform !== undefined ? { transform } : {}), ...(geometry !== undefined ? { geometry } : {}), ...(outline !== undefined ? { outline } : {}), ...(effects !== undefined ? { effects } : {}), ...(style !== undefined ? { style } : {}), handle: { partPath, ...(nodeId !== undefined ? { nodeId } : {}), orderingSlot }, ...(rawSidecars.length > 0 ? { rawSidecars } : {}), }; } function parseConnectorConnection( cNvCxnSpPr: XmlNode | undefined, ): SourceConnector["connection"] | undefined { const start = parseConnectorConnectionEndpoint(getChild(cNvCxnSpPr, "stCxn")); const end = parseConnectorConnectionEndpoint(getChild(cNvCxnSpPr, "endCxn")); return start !== undefined || end !== undefined ? { ...(start !== undefined ? { start } : {}), ...(end !== undefined ? { end } : {}), } : undefined; } function parseConnectorConnectionEndpoint( node: XmlNode | undefined, ): NonNullable["start"] | undefined { const shapeId = getAttr(node, "id"); const connectionSiteIndex = numericAttr(node, "idx"); if (shapeId === undefined || connectionSiteIndex === undefined) return undefined; return { shapeId: asSourceNodeId(shapeId), connectionSiteIndex, }; } function parseShapeStyle(style: XmlNode | undefined): SourceShapeStyle | undefined { if (style === undefined) return undefined; const fillRef = parseStyleReference(getChild(style, "fillRef")); const lineRef = parseStyleReference(getChild(style, "lnRef")); const effectRef = parseStyleReference(getChild(style, "effectRef")); const parsed: SourceShapeStyle = { ...(fillRef !== undefined ? { fillRef } : {}), ...(lineRef !== undefined ? { lineRef } : {}), ...(effectRef !== undefined ? { effectRef } : {}), }; return Object.keys(parsed).length > 0 ? parsed : undefined; } function parseStyleReference(ref: XmlNode | undefined): SourceStyleReference | undefined { if (ref === undefined) return undefined; const index = numericAttr(ref, "idx") ?? 0; const color = parseColorElement(ref); return { index, ...(color !== undefined ? { color } : {}), }; } function parseGroup( grpSp: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, orderingSlot: number, orderedChildren?: readonly XmlOrderedNode[], ): SourceGroup { const nvGrpSpPr = getChild(grpSp, "nvGrpSpPr"); const cNvPr = getChild(nvGrpSpPr, "cNvPr"); const nodeId = sourceNodeId(cNvPr); const name = getAttr(cNvPr, "name"); const grpSpPr = getChild(grpSp, "grpSpPr"); const transform = parseTransform(grpSpPr); const childTransform = parseChildTransform(grpSpPr); const fill = parseFill(grpSpPr, nextId); const effects = parseEffectList(getChild(grpSpPr, "effectLst")); const rawSidecars = [ ...(groupNonVisualPropertiesAreMinimal(nvGrpSpPr) ? [] : [makeSidecar("p:nvGrpSpPr", nvGrpSpPr, nextId)]), ...collectUnknownSidecars(grpSp, KNOWN_GROUP_CHILDREN, nextId), ...collectUnknownSidecars(grpSpPr, KNOWN_SP_PR_CHILDREN, nextId), ...collectEffectSidecars(grpSpPr, effects, nextId), ]; return { kind: "group", ...(nodeId !== undefined ? { nodeId } : {}), ...(name !== undefined ? { name } : {}), ...(transform !== undefined ? { transform } : {}), ...(childTransform !== undefined ? { childTransform } : {}), ...(fill !== undefined ? { fill } : {}), ...(effects !== undefined ? { effects } : {}), children: parseShapeTree(grpSp, partPath, nextId, orderedChildren), handle: { partPath, ...(nodeId !== undefined ? { nodeId } : {}), orderingSlot }, ...(rawSidecars.length > 0 ? { rawSidecars } : {}), }; } function groupNonVisualPropertiesAreMinimal(nonVisual: XmlNode | undefined): boolean { if (nonVisual === undefined) return false; const cNvPr = getChild(nonVisual, "cNvPr"); const cNvGrpSpPr = getChild(nonVisual, "cNvGrpSpPr"); const nvPr = getChild(nonVisual, "nvPr"); if ( cNvPr === undefined || cNvGrpSpPr === undefined || nvPr === undefined || getChildArray(nonVisual, "cNvPr").length !== 1 || getChildArray(nonVisual, "cNvGrpSpPr").length !== 1 || getChildArray(nonVisual, "nvPr").length !== 1 ) { return false; } const knownChildren = new Set(["cNvPr", "cNvGrpSpPr", "nvPr"]); if ( Object.keys(nonVisual).some( (key) => !key.startsWith("@_") && key !== "#text" && !knownChildren.has(localName(key)), ) ) { return false; } return ( xmlNodeAttributesAreAllowed(nonVisual, new Set()) && xmlNodeHasOnlyAttributes(cNvPr, new Set(["id", "name"])) && xmlNodeHasOnlyAttributes(cNvGrpSpPr, new Set()) && xmlNodeHasOnlyAttributes(nvPr, new Set()) ); } function xmlNodeHasOnlyAttributes(node: XmlNode, allowed: ReadonlySet): boolean { return Object.keys(node).every((key) => { if (key === "#text") return String(node[key]).trim().length === 0; if (!key.startsWith("@_")) return false; const qualifiedName = key.slice(2); return ( qualifiedName === "xmlns" || qualifiedName.startsWith("xmlns:") || (!qualifiedName.includes(":") && allowed.has(qualifiedName)) ); }); } function xmlNodeAttributesAreAllowed(node: XmlNode, allowed: ReadonlySet): boolean { return Object.keys(node) .filter((key) => key.startsWith("@_")) .every((key) => { const qualifiedName = key.slice(2); return ( qualifiedName === "xmlns" || qualifiedName.startsWith("xmlns:") || (!qualifiedName.includes(":") && allowed.has(qualifiedName)) ); }); } function parseImage( pic: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, orderingSlot: number, ): SourceImage { const nvPicPr = getChild(pic, "nvPicPr"); const cNvPr = getChild(nvPicPr, "cNvPr"); const nodeId = sourceNodeId(cNvPr); const name = getAttr(cNvPr, "name"); const placeholder = parsePlaceholderChild(getChild(nvPicPr, "nvPr")); const blipFill = getChild(pic, "blipFill"); const blip = getChild(blipFill, "blip"); const embed = getNamespacedAttr(blip, "embed"); const crop = parseCrop(getChild(blipFill, "srcRect")); const stretchNode = getChild(blipFill, "stretch"); const tileNode = getChild(blipFill, "tile"); const stretchCount = countChildrenByLocalName(blipFill, "stretch"); const tileCount = countChildrenByLocalName(blipFill, "tile"); const stretch = parseStretch(stretchNode); const tile = parseImageFillTile(tileNode); const blipFillMode = stretchCount === 1 && tileCount === 0 ? "stretch" : tileCount === 1 && stretchCount === 0 ? "tile" : undefined; const blipEffects = parseBlipEffects(blip); const spPr = getChild(pic, "spPr"); const transform = parseTransform(spPr); const effects = parseEffectList(getChild(spPr, "effectLst")); const rawSidecars = [ ...collectUnknownSidecars(pic, KNOWN_PICTURE_CHILDREN, nextId), ...collectUnknownSidecars(spPr, KNOWN_SP_PR_CHILDREN, nextId), ...collectEffectSidecars(spPr, effects, nextId), // Retains fill mode such as `a:stretch` / `a:tile` and recolor operation under blip. ...collectUnknownSidecars(blipFill, KNOWN_BLIP_FILL_CHILDREN, nextId), ...collectBlipEffectSidecars(blip, blipEffects, nextId), ]; return { kind: "image", ...(nodeId !== undefined ? { nodeId } : {}), ...(name !== undefined ? { name } : {}), ...(transform !== undefined ? { transform } : {}), ...(embed !== undefined ? { blipRelationshipId: asRelationshipId(embed) } : {}), ...(crop !== undefined ? { crop } : {}), ...(blipFillMode !== undefined ? { blipFillMode } : {}), ...(stretch !== undefined ? { stretch } : {}), ...(tile !== undefined ? { tile } : {}), ...(effects !== undefined ? { effects } : {}), ...(blipEffects !== undefined ? { blipEffects } : {}), ...(placeholder !== undefined ? { placeholder } : {}), handle: { partPath, ...(nodeId !== undefined ? { nodeId } : {}), ...(embed !== undefined ? { relationshipId: asRelationshipId(embed) } : {}), orderingSlot, }, ...(rawSidecars.length > 0 ? { rawSidecars } : {}), }; } function countChildrenByLocalName(parent: XmlNode | undefined, name: string): number { if (parent === undefined) return 0; return Object.entries(parent).reduce((count, [key, value]) => { if (key.startsWith("@_") || localName(key) !== name) return count; return count + (Array.isArray(value) ? value.length : 1); }, 0); } function collectEffectSidecars( spPr: XmlNode | undefined, effects: SourceEffectList | undefined, nextId: () => RawSidecarId, ) { const effectList = getChild(spPr, "effectLst"); if (effectList === undefined) return []; const sidecars = collectUnknownSidecars(effectList, KNOWN_EFFECT_CHILDREN, nextId); const supportedChildren = [ ["outerShdw", effects?.outerShadow], ["innerShdw", effects?.innerShadow], ["glow", effects?.glow], ["softEdge", effects?.softEdge], ] as const; for (const [name, parsed] of supportedChildren) { const node = getChild(effectList, name); if (node !== undefined && parsed === undefined) { sidecars.push(makeSidecar(`a:${name}`, node, nextId)); } } return sidecars; } function collectBlipEffectSidecars( blip: XmlNode | undefined, effects: SourceBlipEffects | undefined, nextId: () => RawSidecarId, ) { if (blip === undefined) return []; const sidecars = collectUnknownSidecars(blip, KNOWN_BLIP_CHILDREN, nextId); const supportedChildren = [ ["grayscl", effects?.grayscale === true], ["biLevel", effects?.biLevel], ["blur", effects?.blur], ["lum", effects?.lum], ["duotone", effects?.duotone], ["clrChange", effects?.clrChange], ] as const; for (const [name, parsed] of supportedChildren) { const node = getChild(blip, name); if (node !== undefined && (parsed === undefined || parsed === false)) { sidecars.push(makeSidecar(`a:${name}`, node, nextId)); } } return sidecars; } function parseGraphicFrame( graphicFrame: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, orderingSlot: number, orderedNode?: XmlOrderedNode, ): SourceShapeNode { const graphic = getChild(graphicFrame, "graphic"); const graphicData = getChild(graphic, "graphicData"); const uri = getAttr(graphicData, "uri"); if (uri !== undefined && CHART_GRAPHIC_DATA_URIS.has(uri)) { const parsedChart = parseChartGraphicFrame(graphicFrame, partPath, nextId, orderingSlot); if (parsedChart !== undefined) return parsedChart; } if (uri !== undefined && SMARTART_DIAGRAM_URIS.has(uri)) { const parsedSmartArt = parseSmartArtGraphicFrame(graphicFrame, partPath, nextId, orderingSlot); if (parsedSmartArt !== undefined) return parsedSmartArt; } const table = getChild(graphicData, "tbl"); if (table === undefined) { return parseRawShapeNode("p:graphicFrame", graphicFrame, partPath, nextId, orderingSlot); } const orderedGraphicChildren = orderedNestedChildChildren(orderedNode, "graphicFrame", "graphic"); const orderedGraphicDataChildren = orderedChildChildren(orderedGraphicChildren, "graphicData"); const orderedTableChildren = orderedChildChildren(orderedGraphicDataChildren, "tbl"); const parsedTable = parseTable( table, graphicFrame, partPath, nextId, orderingSlot, orderedTableChildren, ); if (parsedTable === undefined) { return parseRawShapeNode("p:graphicFrame", graphicFrame, partPath, nextId, orderingSlot); } return parsedTable; } function parseAlternateContent( alternateContent: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, orderingSlot: number, ): SourceShapeNode[] { const branches = [ ...getChildArray(alternateContent, "Choice"), ...getChildArray(alternateContent, "Fallback"), ]; for (const branch of branches) { const parsed = parseAlternateContentBranch(branch, partPath, nextId, orderingSlot); if (parsed.length > 0) { if (parsed.every((node) => node.kind === "raw")) { continue; } return parsed.map((node) => attachRawSidecar(node, makeSidecar("mc:AlternateContent", alternateContent, nextId)), ); } } return [ parseRawShapeNode("mc:AlternateContent", alternateContent, partPath, nextId, orderingSlot), ]; } function attachRawSidecar( node: T, sidecar: ReturnType, ): T { if (node.kind === "raw") return node; return { ...node, rawSidecars: [...(node.rawSidecars ?? []), sidecar], }; } function parseAlternateContentBranch( branch: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, orderingSlot: number, ): SourceShapeNode[] { const nodes: SourceShapeNode[] = []; for (const key of Object.keys(branch)) { if (key.startsWith("@_") || key === "#text") continue; const local = localName(key); const value = branch[key]; const items = Array.isArray(value) ? value : [value]; for (const item of items) { const node = unsafeOoxmlBoundaryAssertion(item); if (local === "sp") nodes.push(parseShape(node, partPath, nextId, orderingSlot)); else if (local === "pic") nodes.push(parseImage(node, partPath, nextId, orderingSlot)); else if (local === "cxnSp") { nodes.push(parseConnector(node, partPath, nextId, orderingSlot)); } else if (local === "grpSp") { nodes.push(parseGroup(node, partPath, nextId, orderingSlot)); } else if (local === "graphicFrame") { nodes.push(parseGraphicFrame(node, partPath, nextId, orderingSlot)); } else { nodes.push(parseRawShapeNode(key, node, partPath, nextId, orderingSlot)); } } } return nodes; } function parseChartGraphicFrame( graphicFrame: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, orderingSlot: number, ): SourceChart | undefined { const graphic = getChild(graphicFrame, "graphic"); const graphicData = getChild(graphic, "graphicData"); const chart = getChild(graphicData, "chart"); const rId = getNamespacedAttr(chart, "id") ?? getAttr(chart, "id"); if (rId === undefined) return undefined; const nvGraphicFramePr = getChild(graphicFrame, "nvGraphicFramePr"); const cNvPr = getChild(nvGraphicFramePr, "cNvPr"); const nodeId = sourceNodeId(cNvPr); const name = getAttr(cNvPr, "name"); const transform = parseTransform(graphicFrame); const placeholder = parsePlaceholderChild(getChild(nvGraphicFramePr, "nvPr")); const rawSidecars = [ ...collectUnknownSidecars(graphicFrame, KNOWN_GRAPHIC_FRAME_CHILDREN, nextId), ...collectUnknownSidecars(graphic, KNOWN_GRAPHIC_CHILDREN, nextId), ...collectUnknownSidecars(graphicData, EMPTY_KNOWN, nextId), ]; return { kind: "chart", ...(nodeId !== undefined ? { nodeId } : {}), ...(name !== undefined ? { name } : {}), ...(transform !== undefined ? { transform } : {}), chartRelationshipId: asRelationshipId(rId), ...(placeholder !== undefined ? { placeholder } : {}), handle: { partPath, ...(nodeId !== undefined ? { nodeId } : {}), relationshipId: asRelationshipId(rId), orderingSlot, }, ...(rawSidecars.length > 0 ? { rawSidecars } : {}), }; } function parseSmartArtGraphicFrame( graphicFrame: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, orderingSlot: number, ): SourceSmartArt | undefined { const graphic = getChild(graphicFrame, "graphic"); const graphicData = getChild(graphic, "graphicData"); const relIds = getChild(graphicData, "relIds"); const dmRId = getNamespacedAttr(relIds, "dm") ?? getAttr(relIds, "dm"); if (dmRId === undefined) return undefined; const nvGraphicFramePr = getChild(graphicFrame, "nvGraphicFramePr"); const cNvPr = getChild(nvGraphicFramePr, "cNvPr"); const nodeId = sourceNodeId(cNvPr); const name = getAttr(cNvPr, "name"); const transform = parseTransform(graphicFrame); const placeholder = parsePlaceholderChild(getChild(nvGraphicFramePr, "nvPr")); const rawSidecars = [ ...collectUnknownSidecars(graphicFrame, KNOWN_GRAPHIC_FRAME_CHILDREN, nextId), ...collectUnknownSidecars(graphic, KNOWN_GRAPHIC_CHILDREN, nextId), ...collectUnknownSidecars(graphicData, EMPTY_KNOWN, nextId), ]; return { kind: "smartArt", ...(nodeId !== undefined ? { nodeId } : {}), ...(name !== undefined ? { name } : {}), ...(transform !== undefined ? { transform } : {}), dataRelationshipId: asRelationshipId(dmRId), ...(placeholder !== undefined ? { placeholder } : {}), handle: { partPath, ...(nodeId !== undefined ? { nodeId } : {}), relationshipId: asRelationshipId(dmRId), orderingSlot, }, ...(rawSidecars.length > 0 ? { rawSidecars } : {}), }; } function parseTable( tbl: XmlNode, graphicFrame: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, orderingSlot: number, orderedTableChildren?: readonly XmlOrderedNode[], ): SourceTable | undefined { const columns = parseTableColumns(getChild(tbl, "tblGrid")); if (columns.length === 0) return undefined; const nvGraphicFramePr = getChild(graphicFrame, "nvGraphicFramePr"); const cNvPr = getChild(nvGraphicFramePr, "cNvPr"); const nodeId = sourceNodeId(cNvPr); const name = getAttr(cNvPr, "name"); const tblPr = getChild(tbl, "tblPr"); const tableStyleId = getChildText(tblPr, "tableStyleId"); const graphic = getChild(graphicFrame, "graphic"); const graphicData = getChild(graphic, "graphicData"); const transform = parseTransform(graphicFrame); const placeholder = parsePlaceholderChild(getChild(nvGraphicFramePr, "nvPr")); const rows = parseTableRows(tbl, partPath, nextId, nodeId, orderingSlot, orderedTableChildren); const rawSidecars = [ ...collectUnknownSidecars(graphicFrame, KNOWN_GRAPHIC_FRAME_CHILDREN, nextId), ...collectUnknownSidecars(graphic, KNOWN_GRAPHIC_CHILDREN, nextId), ...collectUnknownSidecars(graphicData, KNOWN_GRAPHIC_DATA_CHILDREN, nextId), ...collectUnknownSidecars(tbl, KNOWN_TABLE_CHILDREN, nextId), ]; return { kind: "table", ...(nodeId !== undefined ? { nodeId } : {}), ...(name !== undefined ? { name } : {}), ...(transform !== undefined ? { transform } : {}), table: { columns, rows, ...(tableStyleId !== undefined ? { tableStyleId } : {}), }, ...(placeholder !== undefined ? { placeholder } : {}), handle: { partPath, ...(nodeId !== undefined ? { nodeId } : {}), orderingSlot }, ...(rawSidecars.length > 0 ? { rawSidecars } : {}), }; } function parseTableColumns(tblGrid: XmlNode | undefined): SourceTableColumn[] { return getChildArray(tblGrid, "gridCol").map((col) => ({ width: emuAttr(col, "w") })); } function parseTableRows( tbl: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, tableNodeId: SourceNodeId | undefined, tableOrderingSlot: number, orderedTableChildren?: readonly XmlOrderedNode[], ): SourceTableRow[] { const orderedRows = orderedChildChildrenList(orderedTableChildren, "tr"); return getChildArray(tbl, "tr").map((tr, rowIndex) => ({ height: emuAttr(tr, "h"), cells: getChildArray(tr, "tc").map((tc, cellIndex) => { const orderedCells = orderedChildChildrenList(orderedRows[rowIndex], "tc"); return parseTableCell( tc, partPath, nextId, tableNodeId, tableOrderingSlot, rowIndex, cellIndex, orderedCells[cellIndex], ); }), })); } function parseTableCell( tc: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, tableNodeId: SourceNodeId | undefined, tableOrderingSlot: number, rowIndex: number, cellIndex: number, orderedCellChildren?: readonly XmlOrderedNode[], ): SourceTableCell { const tcPr = getChild(tc, "tcPr"); const textBody = parseTextBody( getChild(tc, "txBody"), partPath, nextId, tableNodeId, tableOrderingSlot, orderedChildChildren(orderedCellChildren, "txBody"), { rowIndex, cellIndex }, ); const fill = parseFill(tcPr, nextId); const borders = parseCellBorders(tcPr, nextId); const marginLeft = numericAttr(tcPr, "marL"); const marginRight = numericAttr(tcPr, "marR"); const marginTop = numericAttr(tcPr, "marT"); const marginBottom = numericAttr(tcPr, "marB"); const rawSidecars = [ ...collectUnknownSidecars(tc, KNOWN_TABLE_CELL_CHILDREN, nextId), ...collectUnknownSidecars(tcPr, KNOWN_TABLE_CELL_PROPERTIES_CHILDREN, nextId), ]; return { ...(textBody !== undefined ? { textBody } : {}), ...(fill !== undefined ? { fill } : {}), ...(borders !== undefined ? { borders } : {}), ...(marginLeft !== undefined ? { marginLeft: asEmu(marginLeft) } : {}), ...(marginRight !== undefined ? { marginRight: asEmu(marginRight) } : {}), ...(marginTop !== undefined ? { marginTop: asEmu(marginTop) } : {}), ...(marginBottom !== undefined ? { marginBottom: asEmu(marginBottom) } : {}), gridSpan: numericAttr(tc, "gridSpan") ?? 1, rowSpan: numericAttr(tc, "rowSpan") ?? 1, hMerge: isTrue(getAttr(tc, "hMerge") ?? getAttr(tcPr, "hMerge")), vMerge: isTrue(getAttr(tc, "vMerge") ?? getAttr(tcPr, "vMerge")), ...(rawSidecars.length > 0 ? { rawSidecars } : {}), }; } function parseCellBorders( tcPr: XmlNode | undefined, nextId: () => RawSidecarId, ): SourceCellBorders | undefined { const left = parseLine(getChild(tcPr, "lnL"), nextId); const right = parseLine(getChild(tcPr, "lnR"), nextId); const top = parseLine(getChild(tcPr, "lnT"), nextId); const bottom = parseLine(getChild(tcPr, "lnB"), nextId); if (left === undefined && right === undefined && top === undefined && bottom === undefined) { return undefined; } return { ...(top !== undefined ? { top } : {}), ...(bottom !== undefined ? { bottom } : {}), ...(left !== undefined ? { left } : {}), ...(right !== undefined ? { right } : {}), }; } function parseRawShapeNode( key: string, node: XmlNode, partPath: PartPath, nextId: () => RawSidecarId, orderingSlot: number, ): SourceRawShapeNode { const nonVisual = getChild(node, "nvSpPr") ?? getChild(node, "nvPicPr") ?? getChild(node, "nvGraphicFramePr"); const nodeId = sourceNodeId(getChild(nonVisual, "cNvPr")); const placeholder = parsePlaceholderChild(getChild(nonVisual, "nvPr")); return { kind: "raw", ...(nodeId !== undefined ? { nodeId } : {}), raw: makeSidecar(key, node, nextId), ...(placeholder !== undefined ? { placeholder } : {}), handle: { partPath, ...(nodeId !== undefined ? { nodeId } : {}), orderingSlot }, }; } function parsePlaceholderChild( nonVisualProperties: XmlNode | undefined, ): SourcePlaceholder | undefined { if (!hasChild(nonVisualProperties, "ph")) return undefined; const ph = getChild(nonVisualProperties, "ph") ?? {}; const type = getAttr(ph, "type"); const index = numericAttr(ph, "idx"); const orientation = getAttr(ph, "orient"); const size = getAttr(ph, "sz"); const customPrompt = getAttr(ph, "hasCustomPrompt"); return { ...(type !== undefined ? { type } : {}), ...(index !== undefined ? { index } : {}), ...(orientation !== undefined ? { orientation } : {}), ...(size !== undefined ? { size } : {}), ...(customPrompt !== undefined ? { hasCustomPrompt: isTrue(customPrompt) } : {}), }; } function parseGeometry( spPr: XmlNode | undefined, orderedSpPr?: readonly XmlOrderedNode[], ): SourceGeometry | undefined { const prstGeom = getChild(spPr, "prstGeom"); if (prstGeom) { const preset = getAttr(prstGeom, "prst"); const adjustValues = parseAdjustValues(getChild(prstGeom, "avLst")); return preset !== undefined ? { preset, ...(Object.keys(adjustValues).length > 0 ? { adjustValues } : {}), } : undefined; } const customPaths = parseCustomGeometry( getChild(spPr, "custGeom"), orderedChildChildren(orderedSpPr, "custGeom"), ); if (customPaths !== undefined) return { kind: "custom", paths: customPaths }; return undefined; } function parseAdjustValues(avLst: XmlNode | undefined): Record { const adjustValues: Record = {}; for (const guide of getChildArray(avLst, "gd")) { const name = getAttr(guide, "name"); const formula = getAttr(guide, "fmla"); const match = formula?.match(/val\s+(-?\d+)/); if (name !== undefined && match !== undefined && match !== null) { adjustValues[name] = Number(match[1]); } } return adjustValues; } function parseChildTransform(grpSpPr: XmlNode | undefined): SourceTransform | undefined { const xfrm = getChild(grpSpPr, "xfrm"); const childOff = getChild(xfrm, "chOff"); const childExt = getChild(xfrm, "chExt"); const offsetX = numericAttr(childOff, "x"); const offsetY = numericAttr(childOff, "y"); const width = numericAttr(childExt, "cx"); const height = numericAttr(childExt, "cy"); if ( offsetX === undefined || offsetY === undefined || width === undefined || height === undefined ) { return undefined; } return { offsetX: asEmu(offsetX), offsetY: asEmu(offsetY), width: asEmu(width), height: asEmu(height), }; } function parseCrop(srcRect: XmlNode | undefined): SourceImageCrop | undefined { if (!srcRect) return undefined; const left = numericAttr(srcRect, "l"); const top = numericAttr(srcRect, "t"); const right = numericAttr(srcRect, "r"); const bottom = numericAttr(srcRect, "b"); const crop: SourceImageCrop = { ...(left !== undefined ? { left: asOoxmlPercent(left) } : {}), ...(top !== undefined ? { top: asOoxmlPercent(top) } : {}), ...(right !== undefined ? { right: asOoxmlPercent(right) } : {}), ...(bottom !== undefined ? { bottom: asOoxmlPercent(bottom) } : {}), }; return Object.keys(crop).length > 0 ? crop : undefined; } function parseStretch(stretch: XmlNode | undefined): SourceImageStretch | undefined { const fillRect = getChild(stretch, "fillRect"); if (fillRect === undefined) return undefined; const left = (numericAttr(fillRect, "l") ?? 0) / 100000; const top = (numericAttr(fillRect, "t") ?? 0) / 100000; const right = (numericAttr(fillRect, "r") ?? 0) / 100000; const bottom = (numericAttr(fillRect, "b") ?? 0) / 100000; if (left === 0 && top === 0 && right === 0 && bottom === 0) return undefined; return { left, top, right, bottom }; } function sourceNodeId(cNvPr: XmlNode | undefined): SourceNodeId | undefined { const id = getAttr(cNvPr, "id"); return id !== undefined ? asSourceNodeId(id) : undefined; } function emuAttr(node: XmlNode | undefined, attrName: string) { return asEmu(numericAttr(node, attrName) ?? 0); } const EMPTY_KNOWN: ReadonlySet = new Set(); function orderedChildChildren( parent: readonly XmlOrderedNode[] | undefined, childLocalName: string, ): readonly XmlOrderedNode[] | undefined { const child = parent?.find((entry) => { const key = orderedElementKey(entry); return key !== undefined && localName(key) === childLocalName; }); if (child === undefined) return undefined; const key = orderedElementKey(child); const value = key !== undefined ? child[key] : undefined; return Array.isArray(value) ? (value as readonly XmlOrderedNode[]) : undefined; } function orderedChildChildrenList( parent: readonly XmlOrderedNode[] | undefined, childLocalName: string, ): readonly (readonly XmlOrderedNode[] | undefined)[] { if (parent === undefined) return []; return parent .filter((entry) => { const key = orderedElementKey(entry); return key !== undefined && localName(key) === childLocalName; }) .map((entry) => { const key = orderedElementKey(entry); const value = key !== undefined ? entry[key] : undefined; return Array.isArray(value) ? (value as readonly XmlOrderedNode[]) : undefined; }); } function orderedNestedChildChildren( node: XmlOrderedNode | undefined, parentLocalName: string, childLocalName: string, ): readonly XmlOrderedNode[] | undefined { if (node === undefined) return undefined; const parentKey = Object.keys(node).find( (key) => key !== ":@" && localName(key) === parentLocalName, ); const parentChildren = parentKey === undefined ? undefined : node[parentKey]; return orderedChildChildren( Array.isArray(parentChildren) ? (parentChildren as readonly XmlOrderedNode[]) : undefined, childLocalName, ); } function orderedElementKey(node: XmlOrderedNode): string | undefined { return Object.keys(node).find((key) => key !== ":@"); } function getQualifiedChildArray(node: XmlNode, key: string): XmlNode[] { const value = node[key]; if (value === undefined || value === null) return []; return unsafeOoxmlBoundaryAssertion(Array.isArray(value) ? value : [value]); }