Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

feat(roundtrip): patch imported charts in place on data-only edits

hugohe378759bf62e9a
diff --git a/skills/ppt-master/scripts/authoring_roundtrip.py b/skills/ppt-master/scripts/authoring_roundtrip.py
index 4411b7fd..22ad4773 100644
--- a/skills/ppt-master/scripts/authoring_roundtrip.py
+++ b/skills/ppt-master/scripts/authoring_roundtrip.py
@@ -63,6 +63,8 @@ from svg_authoring_view import (
)
from svg_compatibility import normalize_single_child_group_filters
from svg_to_pptx.drawingml.utils import INHERITABLE_ATTRS, parse_transform_matrix
+from svg_to_pptx.native_objects.chart_patch import chart_edit_is_data_only, patch_chart_package
+from svg_to_pptx.native_objects.marker_common import _load_payload
SVG_NS = "http://www.w3.org/2000/svg"
@@ -1711,6 +1713,61 @@ def _native_restore_placeholder(
return placeholder
+def prepare_imported_chart_edit(
+ current: ET.Element,
+ baseline: ET.Element,
+ source: ET.Element,
+ *,
+ current_root: ET.Element | None = None,
+ baseline_root: ET.Element | None = None,
+) -> tuple[dict | None, str | None]:
+ """Reuse import-time JSON and source parts for a data-only chart change."""
+ if any(element.get("data-pptx-replace-with") != "chart"
+ or element.get("data-pptx-native-authority") != "json"
+ for element in (current, baseline)):
+ return None, None
+ edited = _load_payload(current, "chart")
+ original = _load_payload(baseline, "chart")
+ unchanged = edited == original
+ if not unchanged and not chart_edit_is_data_only(original, edited):
+ return None, "series/point topology or non-data JSON fields changed"
+ comparison = copy.deepcopy(_contextual_authoring_element(current, current_root))
+ reference = _contextual_authoring_element(baseline, baseline_root)
+ comparison.find(f'{{{SVG_NS}}}metadata[@type="application/json"]').text = (
+ reference.find(f'{{{SVG_NS}}}metadata[@type="application/json"]').text
+ )
+ ignored = frozenset({SOURCE_REF_ATTRIBUTE, "data-pptx-fallback-sha256"})
+ if semantic_subtree_sha256(comparison, ignored_attributes=ignored) != semantic_subtree_sha256(
+ reference, ignored_attributes=ignored,
+ ):
+ return None, "chart SVG geometry or presentation changed alongside its data"
+ package = _load_payload(source, "chart").get("source_package")
+ if unchanged:
+ return package, None
+ if package is None:
+ raise AuthoringRoundtripError("Data-only chart edit has no closed source package; reimport the source deck")
+ try:
+ return patch_chart_package(package, original, edited), None
+ except RuntimeError as exc:
+ raise AuthoringRoundtripError(f"Cannot preserve data-only chart edit: {exc}") from exc
+
+
+def chart_rebuild_warning(project_path: Path, source_slide: int, source_ref: str, reason: str) -> str:
+ """Report the object's recorded import losses when a chart must rebuild."""
+ report_path = project_path / "validation" / "conversion-report.json"
+ diagnostics = []
+ if report_path.is_file():
+ report = _load_json(report_path, context="import conversion report")
+ diagnostics = [item for item in report.get("diagnostics", [])
+ if item.get("slide_index") == source_slide
+ and str(item.get("shape_id")) == source_ref.split(":", 1)[-1]]
+ details = "; ".join(dict.fromkeys(
+ f"{item.get('code')}: {item.get('message')}" for item in diagnostics
+ )) or "no object-specific import diagnostics were recorded"
+ return (f"native-chart-rebuilt: {reason}; JSON rebuild may omit source-only formatting. "
+ f"Import diagnostics: {details}")
+
+
def _materialize_document(
project_path: Path,
document: AuthoringDocument,
@@ -1963,6 +2020,28 @@ def _materialize_document(
if clone.get(name) is None and source.get(name) is not None:
clone.set(name, str(source.get(name)))
_restore_preserved_effect_metadata(clone, source)
+ package, reason = prepare_imported_chart_edit(
+ element, baseline_occurrences[source_ref][0].element, source,
+ current_root=current_occurrences[source_ref][0].root,
+ baseline_root=baseline_occurrences[source_ref][0].root,
+ )
+ if package is not None:
+ metadata = clone.find(f'{{{SVG_NS}}}metadata[@type="application/json"]')
+ payload = _load_payload(clone, "chart")
+ payload["source_package"] = package
+ metadata.text = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
+ clone.set("data-pptx-roundtrip-object", "source-chart-package")
+ if reason:
+ message = chart_rebuild_warning(project_path, document.source_slide, source_ref, reason)
+ object_id = element.get("id") or source_ref
+ output_index = page.output_index if page else document.source_slide
+ warnings.append({
+ "code": "native-chart-rebuilt", "output_page": output_index,
+ "source_slide": document.source_slide, "object_id": object_id,
+ "source_ref": source_ref, "message": message,
+ })
+ print(f"[ROUNDTRIP][WARNING] page={output_index} object={object_id} "
+ f"source_ref={source_ref}: {message}", file=sys.stderr)
warning = _restore_unchanged_text_body(
clone, source, current_occurrences[source_ref][0], baseline_occurrences[source_ref][0],
)
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index a9247717..c8775f0e 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -973,7 +973,7 @@ Behavior:
- `--no-merge`: each dy-stacked line becomes an independent frame with its own placement.
- Detection is conservative: mixed-layout `<text>` falls back to per-line frames. Use `--reflow-text` only for resizable body copy and `--no-merge` only for independent line objects or absolute line positions.
- Native release export reads `svg_output/`; `-s <directory>` selects another project-relative SVG source. `-s final` remains an explicit diagnostic comparison against post-processed SVGs and does not change artifact ownership. `--enable-dangerous-nonconforming-svg-export` is a separate, explicitly requested flat compatibility path for either the default or selected source; it forces flat structure, restores no imported source object, and cannot combine with `--roundtrip` or `--quick-generate`.
-- `--roundtrip` accepts only `authoring-svg-flat/` and the source/contracts emitted by `pptx_to_svg.py --roundtrip`; predecessor root sidecars and alternate `-s` inputs fail. It restores unchanged refs from `analysis/roundtrip-svg/`, preserves unchanged Slide XML/relationships and source resources byte-for-byte, rebuilds a page whose authoring changed, and rebuilds every output page that references a changed resource. Closed unchanged chart packages recover exactly; editing their fallback disables stale replacement. Optional root `page_plan.json` uses the versioned deck-plan contract above; the no-plan path remains the identity export. Motion fields are compared independently with the import baseline: omitted slide `transition` preserves source motion even when importer defaults say `none`, while changed `defaults.animation` participates in animation replacement. Effect-only changes preserve source `advClick` / `advTm`; explicit advance settings or narration timings replace them. Explicit `-t <effect>` without `--transition-duration` on a source without transitions uses the default duration.
+- `--roundtrip` accepts only `authoring-svg-flat/` and the source/contracts emitted by `pptx_to_svg.py --roundtrip`; predecessor root sidecars and alternate `-s` inputs fail. It restores unchanged refs from `analysis/roundtrip-svg/`, preserves unchanged Slide XML/relationships and source resources byte-for-byte, rebuilds a page whose authoring changed, and rebuilds every output page that references a changed resource. Closed unchanged chart packages recover exactly; editing their fallback disables stale replacement. With `--native-charts-and-tables`, an imported JSON-first chart whose edit changes only numeric data (supported null gaps included), category labels, or series names — types, axis assignments, series/point counts, every non-data JSON field, and its SVG presentation unchanged against the `analysis/roundtrip-svg/` baseline — patches a copy of its source package: only the affected cache entries (`xVal` / `yVal` / `bubbleSize` for XY) and matching workbook cells change (new shared strings when an entry is shared), while `formatCode`, ranges, every other chart byte, and the style/colors/theme-override/workbook relationships stay as imported under independent part names. A data-only edit that cannot be patched safely (workbook reference not a single A1 row or column, formula cell, missing source package) fails with a repair message. Any other chart edit rebuilds from JSON and emits a non-blocking `native-chart-rebuilt` warning listing that object's import diagnostics from `validation/conversion-report.json`; source-only gradients, layouts, text overrides, and extensions can be lost on that path. Optional root `page_plan.json` uses the versioned deck-plan contract above; the no-plan path remains the identity export. Motion fields are compared independently with the import baseline: omitted slide `transition` preserves source motion even when importer defaults say `none`, while changed `defaults.animation` participates in animation replacement. Effect-only changes preserve source `advClick` / `advTm`; explicit advance settings or narration timings replace them. Explicit `-t <effect>` without `--transition-duration` on a source without transitions uses the default duration.
- `svg_final/` may be opened directly or inserted into PowerPoint as an SVG picture. PowerPoint's manual Convert-to-Shape operation is outside the compatibility contract.
- On every SVG-authoring route, each file in `svg_output/` is the complete visible
page-design source. Templates and locks may guide authoring, but finalize/export
diff --git a/skills/ppt-master/scripts/svg_quality/checker.py b/skills/ppt-master/scripts/svg_quality/checker.py
index c18ef9ef..95e950ce 100644
--- a/skills/ppt-master/scripts/svg_quality/checker.py
+++ b/skills/ppt-master/scripts/svg_quality/checker.py
@@ -1732,12 +1732,49 @@ class SVGQualityChecker:
result,
included_text_ids,
)
+ self._check_roundtrip_chart_edits(root, baseline_root, source_document, result)
result['passed'] = len(result['errors']) == 0
except Exception as exc:
result['errors'].append(f"Failed to read file: {exc}")
result['passed'] = False
return self._record_result(result)
+ @staticmethod
+ def _check_roundtrip_chart_edits(root, baseline_root, source_document, result: Dict) -> None:
+ """Surface source-only chart losses before the round-trip export."""
+ from authoring_roundtrip import (
+ _layered_ref_index,
+ _parse_svg,
+ chart_rebuild_warning,
+ prepare_imported_chart_edit,
+ )
+ baseline_by_ref = {node.get('data-pptx-source-ref'): node for node in baseline_root.iter()
+ if node.get('data-pptx-source-ref')}
+ candidates = [node for node in root.iter() if node.get('data-pptx-replace-with') == 'chart'
+ and node.get('data-pptx-source-ref') in baseline_by_ref]
+ if not candidates:
+ return
+ sources = _layered_ref_index(_parse_svg(source_document.layered_source_path))
+ project_path = source_document.authoring_path.parent.parent
+ for node in candidates:
+ source_ref = node.get('data-pptx-source-ref')
+ source = sources.get(source_ref)
+ if source is None:
+ continue
+ try:
+ _package, reason = prepare_imported_chart_edit(
+ node, baseline_by_ref[source_ref], source,
+ current_root=root, baseline_root=baseline_root,
+ )
+ except RuntimeError as exc:
+ result['errors'].append(f"{_element_label(node)}: {exc}")
+ continue
+ if reason:
+ result['warnings'].append(
+ f"{_element_label(node)} source_ref={source_ref}: "
+ + chart_rebuild_warning(project_path, source_document.source_slide, source_ref, reason)
+ )
+
@staticmethod
def _check_roundtrip_unsupported_table_edits(
root: ET.Element,
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_patch.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_patch.py
new file mode 100644
index 00000000..bfb2e6d7
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_patch.py
@@ -0,0 +1,464 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Imported Chart Data Patching
+
+Patch classic-chart caches and their embedded workbook without serializing the
+surrounding chart XML. See scripts/docs/conversion.md for the round-trip rule.
+
+Usage:
+ Import patch_chart_package from the round-trip materializer.
+
+Examples:
+ package = patch_chart_package(source_package, baseline, edited)
+
+Dependencies:
+ Standard library and sibling native chart helpers.
+"""
+
+from __future__ import annotations
+
+import base64
+import copy
+import hashlib
+import io
+import math
+import posixpath
+import re
+from dataclasses import dataclass
+from typing import Any
+from xml.etree import ElementTree as ET
+from xml.parsers import expat
+from xml.sax.saxutils import escape
+from zipfile import BadZipFile, ZipFile
+
+from .chart_data import validate_chart_payload
+
+
+NS = {
+ "c": "http://schemas.openxmlformats.org/drawingml/2006/chart",
+ "s": "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
+ "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
+}
+_START_TAG_RE = re.compile(rb'''<([^\s/>]+)(?:[^>"']|"[^"]*"|'[^']*')*>''')
+_RANGE_RE = re.compile(r"(?:'((?:[^']|'')+)'|([^!]+))!\$?([A-Z]+)\$?([1-9][0-9]*)"
+ r"(?::\$?([A-Z]+)\$?([1-9][0-9]*))?")
+
+
+@dataclass
+class _Span:
+ start: int
+ start_end: int
+ close: int
+ end: int
+ name: bytes
+ empty: bool
+
+
+class _XmlPatch:
+ """Address parsed elements while retaining all untouched source bytes."""
+
+ def __init__(self, data: bytes) -> None:
+ self.data = data
+ self.root = ET.fromstring(data)
+ self.edits: list[tuple[int, int, bytes]] = []
+ spans: list[_Span] = []
+ stack: list[_Span] = []
+ parser = expat.ParserCreate()
+
+ def start(_name, _attributes):
+ offset = parser.CurrentByteIndex
+ match = _START_TAG_RE.match(data, offset)
+ if match is None:
+ raise RuntimeError("Cannot locate source XML start tag")
+ empty = match.group().endswith(b"/>")
+ span = _Span(offset, match.end(), match.end() - 2, match.end(), match[1], empty)
+ spans.append(span)
+ stack.append(span)
+
+ def end(_name):
+ span = stack.pop()
+ if not span.empty:
+ span.close = parser.CurrentByteIndex
+ span.end = data.index(b">", span.close) + 1
+
+ parser.StartElementHandler = start
+ parser.EndElementHandler = end
+ parser.Parse(data, True)
+ self.spans = dict(zip(self.root.iter(), spans))
+
+ def replace(self, node: ET.Element, data: bytes) -> None:
+ span = self.spans[node]
+ self.edits.append((span.start, span.end, data))
+
+ def text(self, node: ET.Element, value: Any) -> None:
+ data = escape(str(value), {"\r": "&#13;"}).encode("utf-8")
+ span = self.spans[node]
+ if span.empty:
+ self.replace(node, self.data[span.start:span.close] + b">" + data + b"</" + span.name + b">")
+ else:
+ self.edits.append((span.start_end, span.close, data))
+
+ def attributes(self, node: ET.Element, values: dict[str, str | None]) -> None:
+ span = self.spans[node]
+ start = self.data[span.start:span.start_end]
+ for key, value in values.items():
+ pattern = re.compile(rb"\s+" + re.escape(key.encode()) + rb'''\s*=\s*(?:"[^"]*"|'[^']*')''')
+ replacement = b"" if value is None else (
+ b" " + key.encode() + b'="' + escape(value, {'"': "&quot;"}).encode("utf-8") + b'"'
+ )
+ if pattern.search(start):
+ start = pattern.sub(lambda _match: replacement, start, count=1)
+ elif value is not None:
+ offset = -2 if span.empty else -1
+ start = start[:offset] + replacement + start[offset:]
+ self.edits.append((span.start, span.start_end, start))
+
+ def append(self, node: ET.Element, data: bytes) -> None:
+ span = self.spans[node]
+ if span.empty:
+ self.replace(node, self.data[span.start:span.close] + b">" + data + b"</" + span.name + b">")
+ else:
+ self.edits.append((span.close, span.close, data))
+
+ def render(self) -> bytes:
+ result: list[bytes] = []
+ cursor = 0
+ for start, end, data in sorted(self.edits, key=lambda edit: (edit[0], edit[1])):
+ if start < cursor:
+ raise RuntimeError("Overlapping chart XML data edits")
+ result.extend((self.data[cursor:start], data))
+ cursor = end
+ result.append(self.data[cursor:])
+ patched = b"".join(result)
+ ET.fromstring(patched)
+ return patched
+
+
+def _data_shape(payload: dict[str, Any]) -> dict[str, Any]:
+ """Mask only data leaves, retaining field presence, counts and all options."""
+ result = copy.deepcopy(payload)
+ for plot in [result, *result.get("plots", [])]:
+ if isinstance(plot.get("categories"), list):
+ plot["categories"] = [None] * len(plot["categories"])
+ for series in plot.get("series", []):
+ if "name" in series:
+ series["name"] = None
+ for key in ("values", "x", "y", "sizes"):
+ if isinstance(series.get(key), list):
+ series[key] = [None] * len(series[key])
+ return result
+
+
+def chart_edit_is_data_only(baseline: dict[str, Any], edited: dict[str, Any]) -> bool:
+ """Require the same plot/series topology and every non-data JSON field."""
+ for plot in [edited, *edited.get("plots", [])]:
+ for series in plot.get("series", []):
+ if not isinstance(series.get("name", ""), str):
+ return False
+ for key in ("values", "x", "y", "sizes"):
+ if any(value is not None and (type(value) not in {int, float} or not math.isfinite(value))
+ for value in series.get(key, [])):
+ return False
+ return baseline != edited and _data_shape(baseline) == _data_shape(edited)
+
+
+def _range_cells(formula: str) -> tuple[str, list[str]]:
+ match = _RANGE_RE.fullmatch(formula)
+ if match is None:
+ raise RuntimeError(f"Cannot patch chart workbook range {formula!r}; use a single A1 row or column range")
+ quoted, plain, col, row, last_col, last_row = match.groups()
+ sheet = quoted.replace("''", "'") if quoted is not None else plain
+ last_col, last_row = last_col or col, last_row or row
+
+ def number(label):
+ value = 0
+ for char in label:
+ value = value * 26 + ord(char) - ord("A") + 1
+ return value
+
+ def label(value):
+ result = ""
+ while value:
+ value, digit = divmod(value - 1, 26)
+ result = chr(ord("A") + digit) + result
+ return result
+
+ c1, c2, r1, r2 = number(col), number(last_col), int(row), int(last_row)
+ if c2 < c1 or r2 < r1 or (c1 != c2 and r1 != r2):
+ raise RuntimeError(f"Cannot patch non-linear chart workbook range {formula!r}")
+ if c2 > 16384 or r2 > 1048576 or max(c2 - c1, r2 - r1) > 1_000_000:
+ raise RuntimeError(f"Chart workbook range exceeds worksheet bounds: {formula!r}")
+ return sheet, [f"{label(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)]
+
+
+def _patch_cache(
+ xml: _XmlPatch, owner: ET.Element, before: list, after: list,
+ cells: dict[tuple[str, str], Any],
+) -> None:
+ cache = next((node for node in owner.iter() if node.tag in {
+ f'{{{NS["c"]}}}{name}' for name in ("strCache", "numCache", "strLit", "numLit")
+ }), None)
+ if cache is None:
+ raise RuntimeError("Imported chart has no patchable data cache; reimport a chart with cached values")
+ formula = owner.find(".//c:f", NS)
+ if formula is not None:
+ sheet, addresses = _range_cells(formula.text or "")
+ if len(addresses) != len(after):
+ raise RuntimeError("Chart cache count differs from its workbook range; repair the source chart")
+ for address, old, value in zip(addresses, before, after):
+ key = (sheet, address)
+ if key in cells and cells[key][1] != value:
+ raise RuntimeError(f"Conflicting chart data for workbook cell {sheet}!{address}")
+ cells[key] = (old, value)
+ if before == after:
+ return
+ if cache.tag in {f'{{{NS["c"]}}}numCache', f'{{{NS["c"]}}}numLit'}:
+ try:
+ valid = all(value is None or math.isfinite(float(value)) for value in after)
+ except (ValueError, TypeError, OverflowError):
+ valid = False
+ if not valid:
+ raise RuntimeError("Source chart uses a numeric cache; retain numeric category labels")
+ count = cache.find("c:ptCount", NS)
+ if count is None:
+ raise RuntimeError("Imported chart cache has no ptCount; repair the source chart")
+ if count.get("val") != str(len(after)):
+ xml.attributes(count, {"val": str(len(after))})
+ points = {int(node.get("idx", "-1")): node for node in cache.findall("c:pt", NS)}
+ prefix = xml.spans[cache].name.rsplit(b":", 1)[0] + b":" if b":" in xml.spans[cache].name else b""
+ additions: dict[int, list[bytes]] = {}
+ for index, (old, value) in enumerate(zip(before, after)):
+ if old == value:
+ continue
+ point = points.get(index)
+ if value is None:
+ if point is not None:
+ xml.replace(point, b"")
+ elif point is not None:
+ leaf = point.find("c:v", NS)
+ if leaf is None:
+ raise RuntimeError("Imported chart point has no value; repair the source chart")
+ xml.text(leaf, value)
+ else:
+ tag = prefix.decode()
+ following = [xml.spans[node].start for idx, node in points.items() if idx > index]
+ anchor = min(following) if following else max(
+ (xml.spans[node].end for node in points.values()), default=xml.spans[count].end,
+ )
+ additions.setdefault(anchor, []).append(
+ f'<{tag}pt idx="{index}"><{tag}v>{escape(str(value))}</{tag}v></{tag}pt>'.encode("utf-8")
+ )
+ for anchor, fragments in additions.items():
+ xml.edits.append((anchor, anchor, b"".join(fragments)))
+
+
+def _patch_chart(data: bytes, baseline: dict, edited: dict) -> tuple[bytes, dict]:
+ xml = _XmlPatch(data)
+ plot_area = xml.root.find("c:chart/c:plotArea", NS)
+ plots = [node for node in plot_area if node.find("c:ser", NS) is not None] if plot_area is not None else []
+ old_plots, new_plots = baseline.get("plots", [baseline]), edited.get("plots", [edited])
+ if len(plots) != len(new_plots):
+ raise RuntimeError("Source chart plots do not match the import baseline; reimport the source deck")
+ cells: dict[tuple[str, str], Any] = {}
+ for plot, old_plot, new_plot in zip(plots, old_plots, new_plots):
+ series = plot.findall("c:ser", NS)
+ if len(series) != len(new_plot["series"]):
+ raise RuntimeError("Source chart series do not match the import baseline; reimport the source deck")
+ for node, old, new in zip(series, old_plot["series"], new_plot["series"]):
+ for key, tag in (("values", "val"), ("x", "xVal"), ("y", "yVal"), ("sizes", "bubbleSize")):
+ if key in new:
+ owner = node.find(f"c:{tag}", NS)
+ if owner is None:
+ raise RuntimeError(f"Source chart lacks c:{tag}; reimport the source deck")
+ _patch_cache(xml, owner, old[key], new[key], cells)
+ if "categories" in edited:
+ owner = node.find("c:cat", NS)
+ if owner is None:
+ raise RuntimeError("Source chart lacks categories; reimport the source deck")
+ _patch_cache(xml, owner, old_plot.get("categories", baseline["categories"]),
+ new_plot.get("categories", edited["categories"]), cells)
+ tx = node.find("c:tx", NS)
+ if tx is not None and tx.find("c:strRef", NS) is not None:
+ _patch_cache(xml, tx, [old["name"]], [new["name"]], cells)
+ elif old.get("name") != new.get("name"):
+ leaf = tx.find("c:v", NS) if tx is not None else None
+ if leaf is None:
+ name = xml.spans[node].name.decode()
+ prefix = name.rsplit(":", 1)[0] + ":" if ":" in name else ""
+ value = escape(new["name"], {"\r": "&#13;"})
+ content = f"<{prefix}v>{value}</{prefix}v>".encode("utf-8")
+ if tx is not None:
+ xml.append(tx, content)
+ else:
+ order = node.find("c:order", NS)
+ if order is None:
+ raise RuntimeError("Source chart series has no order; repair the source chart")
+ anchor = xml.spans[order].end
+ content = f"<{prefix}tx>".encode() + content + f"</{prefix}tx>".encode()
+ xml.edits.append((anchor, anchor, content))
+ else:
+ xml.text(leaf, new["name"])
+ return xml.render(), cells
+
+
+def _resolve(owner: str, target: str) -> str:
+ return posixpath.normpath(posixpath.join(posixpath.dirname(owner), target)).lstrip("/")
+
+
+def _patch_workbook(data: bytes, assignments: dict[tuple[str, str], Any]) -> bytes:
+ with ZipFile(io.BytesIO(data)) as archive:
+ parts = {name: archive.read(name) for name in archive.namelist()}
+ workbook = ET.fromstring(parts["xl/workbook.xml"])
+ relationships = ET.fromstring(parts["xl/_rels/workbook.xml.rels"])
+ targets = {rel.get("Id"): _resolve("xl/workbook.xml", rel.get("Target", "")) for rel in relationships}
+ sheets = {sheet.get("name"): targets[sheet.get(f'{{{NS["r"]}}}id')]
+ for sheet in workbook.findall("s:sheets/s:sheet", NS)}
+ strings_part = next((targets[rel.get("Id")] for rel in relationships
+ if rel.get("Type", "").endswith("/sharedStrings")), None)
+ strings = _XmlPatch(parts[strings_part]) if strings_part else None
+ string_values = ["".join(text.text or "" for text in node.findall("s:t", NS) + node.findall("s:r/s:t", NS))
+ for node in strings.root.findall("s:si", NS)] if strings else []
+ string_indices = {value: index for index, value in enumerate(string_values)}
+ additions: list[bytes] = []
+ sheets_xml = {name: _XmlPatch(parts[part]) for name, part in sheets.items()}
+ shared_count = sum(node.get("t") == "s" for xml in sheets_xml.values() for node in xml.root.iter())
+ old_shared_count = shared_count
+ for (sheet, address), (before, value) in assignments.items():
+ if before == value:
+ continue
+ if sheet not in sheets_xml:
+ raise RuntimeError(f"Chart workbook sheet {sheet!r} is missing")
+ xml = sheets_xml[sheet]
+ node = next((cell for cell in xml.root.findall("s:sheetData/s:row/s:c", NS)
+ if cell.get("r") == address), None)
+ leaf = node.find("s:v", NS) if node is not None else None
+ kind = node.get("t") if node is not None else None
+ old_value = leaf.text if leaf is not None else None
+ if kind == "s" and old_value is not None:
+ old_value = string_values[int(old_value)]
+ elif kind == "inlineStr":
+ old_value = "".join(node.find("s:is", NS).itertext())
+ if old_value == value or (kind in {None, "n"} and old_value is not None
+ and isinstance(value, (int, float)) and float(old_value) == value):
+ continue
+ if node is not None and node.find("s:f", NS) is not None:
+ raise RuntimeError(f"Chart workbook cell {sheet}!{address} is a formula; edit its source inputs")
+ # A fresh cell body preserves style/extension attributes and avoids shared-string alias edits.
+ cell = copy.deepcopy(node) if node is not None else ET.Element(f'{{{NS["s"]}}}c', {"r": address})
+ cell.tail = None
+ for child in list(cell):
+ if child.tag in {f'{{{NS["s"]}}}{tag}' for tag in ("v", "is")}:
+ cell.remove(child)
+ cell.attrib.pop("t", None)
+ if isinstance(value, str):
+ if strings is not None:
+ if value not in string_indices:
+ string_indices[value] = len(string_values) + len(additions)
+ tag = strings.spans[strings.root].name.decode().rsplit(":", 1)
+ prefix = tag[0] + ":" if len(tag) == 2 else ""
+ text_value = escape(value, {"\r": "&#13;"})
+ additions.append((f'<{prefix}si><{prefix}t xml:space="preserve">'
+ f'{text_value}</{prefix}t></{prefix}si>').encode("utf-8"))
+ cell.set("t", "s")
+ content = ET.Element(f'{{{NS["s"]}}}v')
+ content.text = str(string_indices[value])
+ cell.insert(0, content)
+ else:
+ cell.set("t", "inlineStr")
+ content = ET.Element(f'{{{NS["s"]}}}is')
+ text = ET.SubElement(content, f'{{{NS["s"]}}}t')
+ text.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")
+ text.text = value
+ cell.insert(0, content)
+ elif value is not None:
+ content = ET.Element(f'{{{NS["s"]}}}v')
+ content.text = str(value)
+ cell.insert(0, content)
+ shared_count += int(cell.get("t") == "s") - int(kind == "s")
+ replacement = ET.tostring(cell, encoding="utf-8")
+ if node is not None:
+ xml.replace(node, replacement)
+ else:
+ row_num = re.search(r"[0-9]+$", address).group()
+ row = next((row for row in xml.root.findall("s:sheetData/s:row", NS)
+ if row.get("r") == row_num), None)
+ if row is None:
+ raise RuntimeError(f"Chart workbook row {sheet}!{row_num} is missing; repair the source workbook")
+ column = re.match(r"[A-Z]+", address).group()
+ following = [cell for cell in row.findall("s:c", NS)
+ if (len(re.match(r"[A-Z]+", cell.get("r")).group()),
+ re.match(r"[A-Z]+", cell.get("r")).group()) > (len(column), column)]
+ if following:
+ anchor = xml.spans[following[0]].start
+ xml.edits.append((anchor, anchor, replacement))
+ else:
+ xml.append(row, replacement)
+ if not any(xml.edits for xml in sheets_xml.values()):
+ return data
+ for sheet, xml in sheets_xml.items():
+ if xml.edits:
+ parts[sheets[sheet]] = xml.render()
+ if strings is not None and (additions or shared_count != old_shared_count):
+ strings.attributes(strings.root, {"count": str(shared_count),
+ "uniqueCount": str(len(string_values) + len(additions))})
+ if additions:
+ strings.append(strings.root, b"".join(additions))
+ parts[strings_part] = strings.render()
+ output = io.BytesIO()
+ with ZipFile(output, "w") as result:
+ for info in archive.infolist():
+ result.writestr(info, parts[info.filename])
+ result.comment = archive.comment
+ return output.getvalue()
+
+
+def patch_chart_package(source: dict, baseline: dict, edited: dict) -> dict:
+ """Clone a validated source graph and patch only data in its chart/workbook."""
+ from . import _decode_source_chart_package
+
+ validate_chart_payload(edited)
+ decoded = _decode_source_chart_package({"source_package": source})
+ if decoded is None:
+ raise RuntimeError("Imported chart has no source package; reimport the source deck")
+ chart_part, _frame, parts, _types = decoded
+ parts[chart_part], cells = _patch_chart(parts[chart_part], baseline, edited)
+ chart_root = ET.fromstring(parts[chart_part])
+ external = chart_root.find("c:externalData", NS)
+ if cells and external is not None:
+ rels_name = posixpath.join(posixpath.dirname(chart_part), "_rels", posixpath.basename(chart_part) + ".rels")
+ rels = ET.fromstring(parts[rels_name])
+ rel = next((rel for rel in rels if rel.get("Id") == external.get(f'{{{NS["r"]}}}id')), None)
+ if rel is None:
+ raise RuntimeError("Chart workbook relationship is missing; repair the source chart")
+ workbook_part = _resolve(chart_part, rel.get("Target", ""))
+ try:
+ parts[workbook_part] = _patch_workbook(parts[workbook_part], cells)
+ except (BadZipFile, KeyError, ValueError, ET.ParseError) as exc:
+ raise RuntimeError(f"Cannot patch embedded chart workbook: {exc}; repair the source workbook") from exc
+
+ # Content-addressed copies keep other pages sharing the source graph immutable.
+ digest = hashlib.sha256()
+ for name, data in sorted(parts.items()):
+ digest.update(name.encode() + b"\0" + hashlib.sha256(data).digest())
+ suffix = "_data_" + digest.hexdigest()[:20]
+ names = {name: posixpath.splitext(name)[0] + suffix + posixpath.splitext(name)[1]
+ for name in parts if not name.endswith(".rels")}
+ for name in parts:
+ if not name.endswith(".rels"):
+ continue
+ parent, leaf = name.split("/_rels/", 1)
+ owner = parent + "/" + leaf[:-5]
+ new_owner = names[owner]
+ names[name] = posixpath.join(posixpath.dirname(new_owner), "_rels", posixpath.basename(new_owner) + ".rels")
+ rels = _XmlPatch(parts[name])
+ for rel in rels.root:
+ target = names[_resolve(owner, rel.get("Target", ""))]
+ rels.attributes(rel, {"Target": posixpath.relpath(target, posixpath.dirname(new_owner))})
+ parts[name] = rels.render()
+ result = copy.deepcopy(source)
+ result["chart_part"] = names[chart_part]
+ for item in result["parts"]:
+ data = parts[item["name"]]
+ item.update(name=names[item["name"]], payload=base64.b64encode(data).decode("ascii"),
+ sha256=hashlib.sha256(data).hexdigest())
+ return result
diff --git a/skills/ppt-master/scripts/tests/test_chart_inplace.py b/skills/ppt-master/scripts/tests/test_chart_inplace.py
new file mode 100644
index 00000000..1a38cabf
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_chart_inplace.py
@@ -0,0 +1,347 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Imported Chart In-place Data Regression Tests
+
+Exercise public import, checker and round-trip export on synthetic native charts
+with source-only formatting and embedded workbook data.
+
+Usage:
+ python3 -m unittest tests.test_chart_inplace
+
+Examples:
+ Run the module from the scripts directory.
+
+Dependencies:
+ python-pptx and the local importer, checker and exporter.
+"""
+
+from __future__ import annotations
+
+import copy
+import io
+import json
+import posixpath
+import tempfile
+import unittest
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+from xml.etree import ElementTree as ET
+from zipfile import ZipFile
+
+from pptx import Presentation
+from pptx.chart.data import CategoryChartData
+from pptx.enum.chart import XL_CHART_TYPE
+from pptx.util import Inches
+
+from pptx_to_svg.converter import ConvertOptions, convert_pptx_to_svg
+from svg_quality.checker import SVGQualityChecker
+from svg_to_pptx.pptx_package.cli import main as export_main
+
+
+NS = {
+ "a": "http://schemas.openxmlformats.org/drawingml/2006/main",
+ "c": "http://schemas.openxmlformats.org/drawingml/2006/chart",
+ "p": "http://schemas.openxmlformats.org/presentationml/2006/main",
+ "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
+ "s": "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
+ "svg": "http://www.w3.org/2000/svg",
+}
+REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
+CT_NS = "http://schemas.openxmlformats.org/package/2006/content-types"
+
+
+class ChartInplaceTests(unittest.TestCase):
+ def setUp(self) -> None:
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ self.workspace = self.root / "workspace"
+
+ def _import(self, *, values=(12, 34), shared_slide: bool = False, named: bool = True) -> None:
+ presentation = Presentation()
+ slide = presentation.slides.add_slide(presentation.slide_layouts[6])
+ data = CategoryChartData()
+ data.categories = ["First", "Second"]
+ data.add_series("Revenue", values)
+ frame = slide.shapes.add_chart(
+ XL_CHART_TYPE.COLUMN_CLUSTERED, Inches(1), Inches(1), Inches(6), Inches(4), data,
+ )
+ if shared_slide:
+ second = presentation.slides.add_slide(presentation.slide_layouts[6])
+ clone = copy.deepcopy(frame._element)
+ rel_id = second.part.relate_to(frame.chart.part, NS["r"] + "/chart")
+ clone.find(".//c:chart", NS).set(f'{{{NS["r"]}}}id', rel_id)
+ second.shapes._spTree.insert_element_before(clone, "p:extLst")
+ original = self.root / "original.pptx"
+ presentation.save(original)
+ with ZipFile(original) as archive:
+ parts = {name: archive.read(name) for name in archive.namelist()}
+ chart = ET.fromstring(parts["ppt/charts/chart1.xml"])
+ series = chart.find(".//c:ser", NS)
+ point = ET.fromstring(
+ f'<c:dPt xmlns:c="{NS["c"]}" xmlns:a="{NS["a"]}"><c:idx val="0"/>'
+ '<c:spPr><a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="112233"/>'
+ '</a:gs><a:gs pos="100000"><a:srgbClr val="445566"/></a:gs></a:gsLst>'
+ '<a:lin ang="5400000" scaled="1"/></a:gradFill>'
+ '<a:ln w="19050"><a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill></a:ln>'
+ '</c:spPr></c:dPt>'
+ )
+ series.insert(3, point)
+ series.insert(3, copy.deepcopy(point.find("c:spPr", NS)))
+ legend = ET.fromstring(
+ f'<c:legend xmlns:c="{NS["c"]}" xmlns:a="{NS["a"]}"><c:legendPos val="t"/>'
+ '<c:legendEntry><c:idx val="0"/><c:txPr><a:bodyPr/><a:lstStyle/><a:p><a:pPr>'
+ '<a:defRPr sz="2200"/></a:pPr><a:endParaRPr/></a:p></c:txPr></c:legendEntry>'
+ '<c:layout><c:manualLayout><c:x val="0.2"/><c:y val="0.1"/>'
+ '<c:w val="0.7"/><c:h val="0.12"/></c:manualLayout></c:layout></c:legend>'
+ )
+ chart.find("c:chart", NS).append(legend)
+ chart.insert(0, ET.Element(f'{{{NS["c"]}}}style', {"val": "10"}))
+ extension = ET.SubElement(ET.SubElement(chart, f'{{{NS["c"]}}}extLst'), f'{{{NS["c"]}}}ext',
+ {"uri": "{synthetic-preserved-extension}"})
+ ET.SubElement(extension, "{urn:chart-test}opaque", {"keep": "exact"}).text = "extension data"
+ for value in chart.findall(".//c:formatCode", NS):
+ value.text = "#,##0.00"
+ if not named:
+ series.remove(series.find("c:tx", NS))
+ # Serialize once before import: these are the exact bytes export must retain.
+ parts["ppt/charts/chart1.xml"] = ET.tostring(chart, encoding="utf-8", xml_declaration=True)
+ relationships = ET.fromstring(parts["ppt/charts/_rels/chart1.xml.rels"])
+ types = ET.fromstring(parts["[Content_Types].xml"])
+ for rid, filename, kind, content_type, content in (
+ ("rStyle", "style1.xml", "http://schemas.microsoft.com/office/2011/relationships/chartStyle",
+ "application/vnd.ms-office.chartstyle+xml",
+ '<cs:chartStyle xmlns:cs="http://schemas.microsoft.com/office/drawing/2012/chartStyle" id="10"/>'),
+ ("rColors", "colors1.xml", "http://schemas.microsoft.com/office/2011/relationships/chartColorStyle",
+ "application/vnd.ms-office.chartcolorstyle+xml",
+ '<cs:colorStyle xmlns:cs="http://schemas.microsoft.com/office/drawing/2012/chartStyle" id="10"/>'),
+ ("rTheme", "../theme/themeOverride1.xml", NS["r"] + "/themeOverride",
+ "application/vnd.openxmlformats-officedocument.themeOverride+xml",
+ f'<a:themeOverride xmlns:a="{NS["a"]}"/>'),
+ ):
+ name = posixpath.normpath(posixpath.join("ppt/charts", filename))
+ parts[name] = content.encode()
+ ET.SubElement(relationships, f"{{{REL_NS}}}Relationship", {"Id": rid, "Type": kind, "Target": filename})
+ ET.SubElement(types, f"{{{CT_NS}}}Override", {"PartName": "/" + name, "ContentType": content_type})
+ parts["ppt/charts/_rels/chart1.xml.rels"] = ET.tostring(relationships)
+ parts["[Content_Types].xml"] = ET.tostring(types)
+ self.source = parts
+ source = self.root / "source.pptx"
+ with ZipFile(source, "w") as archive:
+ for name, content in parts.items():
+ archive.writestr(name, content)
+ with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
+ convert_pptx_to_svg(source, self.workspace, ConvertOptions(inheritance_mode="both", roundtrip=True))
+ self.path = self.workspace / "authoring-svg-flat" / "slide_01.svg"
+ self.svg = ET.parse(self.path).getroot()
+ self.marker = next(node for node in self.svg.iter() if node.get("data-pptx-replace-with") == "chart")
+ self.metadata = self.marker.find('svg:metadata[@type="application/json"]', NS)
+ self.payload = json.loads(self.metadata.text)
+
+ def _save(self) -> None:
+ if json.loads(self.metadata.text) != self.payload:
+ self.metadata.text = json.dumps(self.payload, ensure_ascii=False)
+ self.path.write_bytes(ET.tostring(self.svg))
+
+ def _check(self) -> list:
+ self._save()
+ checker = SVGQualityChecker()
+ with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
+ results = checker.check_roundtrip_workspace(str(self.workspace))
+ self.assertTrue(results)
+ self.assertEqual(results[0]["errors"], [])
+ return results[0]["warnings"]
+
+ def _export(self) -> dict[str, bytes]:
+ self._save()
+ log = io.StringIO()
+ target = self.root / "result.pptx"
+ with redirect_stdout(log), redirect_stderr(log):
+ status = export_main([str(self.workspace), "--roundtrip", "--native-charts-and-tables", "-o", str(target)])
+ self.assertEqual(status, 0, log.getvalue())
+ self.log = log.getvalue()
+ with ZipFile(target) as archive:
+ return {name: archive.read(name) for name in archive.namelist()}
+
+ def _live_chart(self, parts: dict[str, bytes], slide: int = 1) -> tuple[str, ET.Element]:
+ page = ET.fromstring(parts[f"ppt/slides/slide{slide}.xml"])
+ rel_id = page.find(".//c:chart", NS).get(f'{{{NS["r"]}}}id')
+ rels = ET.fromstring(parts[f"ppt/slides/_rels/slide{slide}.xml.rels"])
+ target = next(rel.get("Target") for rel in rels if rel.get("Id") == rel_id)
+ name = posixpath.normpath(posixpath.join("ppt/slides", target))
+ return name, ET.fromstring(parts[name])
+
+ def _workbook(self, parts: dict[str, bytes], chart_part: str) -> dict[str, bytes]:
+ rels_name = posixpath.join(posixpath.dirname(chart_part), "_rels", posixpath.basename(chart_part) + ".rels")
+ rels = ET.fromstring(parts[rels_name])
+ target = next(rel.get("Target") for rel in rels if rel.get("Type").endswith("/package"))
+ name = posixpath.normpath(posixpath.join(posixpath.dirname(chart_part), target))
+ with ZipFile(io.BytesIO(parts[name])) as workbook:
+ return {name: workbook.read(name) for name in workbook.namelist()}
+
+ @staticmethod
+ def _cells(workbook: dict[str, bytes]) -> dict:
+ strings = ET.fromstring(workbook["xl/sharedStrings.xml"])
+ values = ["".join(node.itertext()) for node in strings.findall("s:si", NS)]
+ cells = {}
+ for cell in ET.fromstring(workbook["xl/worksheets/sheet1.xml"]).findall(".//s:c", NS):
+ value = cell.find("s:v", NS)
+ text = value.text if value is not None else None
+ cells[cell.get("r")] = values[int(text)] if cell.get("t") == "s" else text
+ return cells
+
+ def test_data_only_preserves_chart_bytes_and_dependency_graph(self) -> None:
+ self._import(shared_slide=True)
+ self.payload["series"][0].update(name="Income & costs", values=[21, 43])
+ self.payload["categories"] = ["新类别", "Second"]
+ self.assertEqual(self._check(), [])
+ parts = self._export()
+ name, chart = self._live_chart(parts)
+ # All differences are in existing cache text; namespaces, gradient, legend,
+ # c:style and extLst are not reserialized.
+ expected = self.source["ppt/charts/chart1.xml"]
+ for old, new in ((b">12<", b">21<"), (b">34<", b">43<"), (b">First<", ">新类别<".encode()),
+ (b">Revenue<", b">Income &amp; costs<")):
+ expected = expected.replace(old, new)
+ self.assertEqual(parts[name], expected)
+ self.assertNotEqual(name, "ppt/charts/chart1.xml")
+ rels_name = posixpath.join(posixpath.dirname(name), "_rels", posixpath.basename(name) + ".rels")
+ for rel in ET.fromstring(parts[rels_name]):
+ target = posixpath.normpath(posixpath.join(posixpath.dirname(name), rel.get("Target")))
+ self.assertIn(target, parts)
+ if rel.get("Id") in {"rStyle", "rColors", "rTheme"}:
+ old = next(item.get("Target") for item in ET.fromstring(self.source["ppt/charts/_rels/chart1.xml.rels"])
+ if item.get("Id") == rel.get("Id"))
+ self.assertEqual(parts[target], self.source[posixpath.normpath(posixpath.join("ppt/charts", old))])
+ workbook = self._workbook(parts, name)
+ self.assertEqual(self._cells(workbook), {"B1": "Income & costs", "A2": "新类别", "B2": "21",
+ "A3": "Second", "B3": "43"})
+ self.assertEqual(chart.find(".//c:formatCode", NS).text, "#,##0.00")
+ self.assertEqual(self._live_chart(parts, 2)[0], "ppt/charts/chart1.xml")
+ self.assertEqual(parts["ppt/charts/chart1.xml"], self.source["ppt/charts/chart1.xml"])
+ original_workbook = self._workbook(self.source, "ppt/charts/chart1.xml")
+ for part, data in original_workbook.items():
+ if part not in {"xl/worksheets/sheet1.xml", "xl/sharedStrings.xml"}:
+ self.assertEqual(workbook[part], data)
+
+ def test_series_change_rebuilds_and_warns_with_import_diagnostics(self) -> None:
+ self._import()
+ self.payload["series"].append({"name": "Added", "values": [7, 8]})
+ warning = "\n".join(self._check())
+ self.assertIn("native-chart-rebuilt", warning)
+ self.assertIn("chart-series-style-normalized", warning)
+ self.assertIn("chart-legend-entry-font-size-omitted", warning)
+ self.assertIn(self.marker.get("data-pptx-source-ref"), warning)
+ parts = self._export()
+ name, chart = self._live_chart(parts)
+ self.assertNotIn("_data_", name)
+ self.assertEqual(len(chart.findall(".//c:ser", NS)), 2)
+ self.assertIn("native-chart-rebuilt", self.log)
+
+ def test_non_data_field_change_does_not_patch(self) -> None:
+ self._import()
+ self.payload["style"]["colors"] = ["#ABCDEF"]
+ self.payload["series"][0]["values"] = [21, 43]
+ self.assertIn("native-chart-rebuilt", "\n".join(self._check()))
+ parts = self._export()
+ name, chart = self._live_chart(parts)
+ self.assertNotIn("_data_", name)
+ self.assertIsNone(chart.find(".//a:gradFill", NS))
+
+ def test_unchanged_chart_is_exact_passthrough(self) -> None:
+ self._import()
+ # Semantically unchanged authoring must restore the original package.
+ parts = self._export()
+ name, _chart = self._live_chart(parts)
+ self.assertEqual(name, "ppt/charts/chart1.xml")
+ self.assertEqual(parts[name], self.source[name])
+ self.assertEqual(self._workbook(parts, name), self._workbook(self.source, name))
+ self.assertNotIn("native-chart-rebuilt", self.log)
+
+ def test_json_whitespace_change_keeps_exact_source_chart(self) -> None:
+ self._import()
+ self.metadata.text = json.dumps(self.payload, ensure_ascii=False, indent=2)
+ parts = self._export()
+ name, _chart = self._live_chart(parts)
+ self.assertEqual(name, "ppt/charts/chart1.xml")
+ self.assertEqual(parts[name], self.source[name])
+ self.assertNotIn("native-chart-rebuilt", self.log)
+
+ def test_point_count_change_rebuilds_with_warning(self) -> None:
+ self._import()
+ self.payload["categories"].append("Third")
+ self.payload["series"][0]["values"].append(56)
+ self.payload["series"][0].pop("point_colors", None)
+ self.assertIn("native-chart-rebuilt", "\n".join(self._check()))
+ parts = self._export()
+ name, chart = self._live_chart(parts)
+ self.assertNotIn("_data_", name)
+ self.assertEqual(chart.find(".//c:val/c:numRef/c:numCache/c:ptCount", NS).get("val"), "3")
+
+ def test_name_edit_adds_missing_series_text_without_rebuilding(self) -> None:
+ self._import(named=False)
+ self.payload["series"][0]["name"] = "Named now"
+ parts = self._export()
+ name, chart = self._live_chart(parts)
+ self.assertIn("_data_", name)
+ self.assertEqual(chart.find(".//c:ser/c:tx/c:v", NS).text, "Named now")
+ self.assertIsNotNone(chart.find(".//c:dPt/c:spPr/a:gradFill", NS))
+
+ def test_ancestor_move_with_data_edit_uses_rebuild(self) -> None:
+ self._import()
+ parent = next(node for node in self.svg.iter() if self.marker in list(node))
+ wrapper = ET.Element(f'{{{NS["svg"]}}}g', {"transform": "translate(20 10)"})
+ parent.insert(list(parent).index(self.marker), wrapper)
+ parent.remove(self.marker)
+ wrapper.append(self.marker)
+ self.payload["series"][0]["values"] = [21, 43]
+ self.assertIn("native-chart-rebuilt", "\n".join(self._check()))
+
+ def test_null_gap_updates_cache_and_blank_workbook_cell(self) -> None:
+ self._import()
+ self.payload["series"][0]["values"] = [None, 43]
+ self.assertEqual(self._check(), [])
+ parts = self._export()
+ name, chart = self._live_chart(parts)
+ cache = chart.find(".//c:val/c:numRef/c:numCache", NS)
+ self.assertEqual(cache.find("c:ptCount", NS).get("val"), "2")
+ self.assertEqual([point.get("idx") for point in cache.findall("c:pt", NS)], ["1"])
+ self.assertIsNone(self._cells(self._workbook(parts, name))["B2"])
+
+ def test_fill_imported_gap_updates_missing_cell(self) -> None:
+ self._import(values=(None, 34))
+ self.payload["series"][0]["values"] = [21, 34]
+ parts = self._export()
+ name, chart = self._live_chart(parts)
+ self.assertEqual({point.get("idx"): point.find("c:v", NS).text
+ for point in chart.findall(".//c:val/c:numRef/c:numCache/c:pt", NS)},
+ {"0": "21", "1": "34"})
+ self.assertEqual(self._cells(self._workbook(parts, name))["B2"], "21")
+
+ def test_shared_string_edit_does_not_change_unrelated_cell(self) -> None:
+ self._import()
+ # Reuse an existing shared string through a data-only edit, then change
+ # the category in a fresh import; the unchanged series name must survive.
+ self.payload["categories"][0] = "Revenue"
+ parts = self._export()
+ chart_part, _ = self._live_chart(parts)
+ cells = self._cells(self._workbook(parts, chart_part))
+ self.assertEqual(cells["B1"], "Revenue")
+ self.assertEqual(cells["A2"], "Revenue")
+ # Use the exported PPTX as the next round's immutable source.
+ next_workspace = self.root / "next"
+ with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
+ convert_pptx_to_svg(self.root / "result.pptx", next_workspace,
+ ConvertOptions(inheritance_mode="both", roundtrip=True))
+ self.workspace = next_workspace
+ self.path = next_workspace / "authoring-svg-flat" / "slide_01.svg"
+ self.svg = ET.parse(self.path).getroot()
+ self.marker = next(node for node in self.svg.iter() if node.get("data-pptx-replace-with") == "chart")
+ self.metadata = self.marker.find('svg:metadata[@type="application/json"]', NS)
+ self.payload = json.loads(self.metadata.text)
+ self.payload["categories"][0] = "Changed"
+ parts = self._export()
+ name, _ = self._live_chart(parts)
+ cells = self._cells(self._workbook(parts, name))
+ self.assertEqual(cells["B1"], "Revenue")
+ self.assertEqual(cells["A2"], "Changed")