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

fix(svg-authoring): enforce unique top-level group anchors

hugohe37f5041939fcf
diff --git a/skills/ppt-master/references/animations.md b/skills/ppt-master/references/animations.md
index 44c5ca7b..e4d2f28b 100644
--- a/skills/ppt-master/references/animations.md
+++ b/skills/ppt-master/references/animations.md
@@ -150,7 +150,7 @@ Flags:
## 5. Anchor Logic — Top-Level `<g id="...">`
-Per-element animations are anchored on **top-level `<g id="...">` content groups** in the SVG (e.g. `<g id="cover-title">`, `<g id="card-1">`). One group produces one animation-pane entrance row; whether that row needs a click depends on the selected Start mode.
+Per-element animations are anchored on **top-level `<g id="...">` content groups** in the SVG (e.g. `<g id="cover-title">`, `<g id="card-1">`). IDs must be unique within the page. One group produces one animation-pane entrance row; whether that row needs a click depends on the selected Start mode. Nested implementation groups may remain anonymous because the sidecar does not target them.
Aim for **3–8 content groups per slide**. This is also the granularity PowerPoint uses for group-select / group-move, so it improves editing ergonomics regardless of animation.
diff --git a/skills/ppt-master/references/executor-base.md b/skills/ppt-master/references/executor-base.md
index eabf3922..ab732d87 100644
--- a/skills/ppt-master/references/executor-base.md
+++ b/skills/ppt-master/references/executor-base.md
@@ -248,7 +248,7 @@ Before drawing each page, look up its entry in `page_charts` to decide which cha
## 3. Execution Guidelines
- **Proximity**: group related elements with tight spacing; separate unrelated groups
-- **Element grouping (Mandatory)**: wrap every logical Slide-local content unit — title, core-message line, each content block, card, list item, and diagram — in a top-level `<g id="...">` with a descriptive id. Flat free-design/brand-only pages use ordinary semantic groups for every logical unit. On structured template pages, slot `<g>` elements are already semantic groups and direct Master/Layout atoms are the required exception to grouping. Authored native preset fragments (`preset_shape_svg.py`) already are one atomic `<g id>` each and count as one ordinary content group. When a preset needs labels or decorations, put the preset and those siblings inside a separate parent content group; never put them inside the preset group itself.
+- **Element grouping (Mandatory)**: wrap every logical Slide-local content unit — title, core-message line, each content block, card, list item, and diagram — in a top-level `<g id="...">` with a descriptive, page-unique id. Nested implementation groups within that unit may remain anonymous; they are not independent animation targets. Flat free-design/brand-only pages use ordinary semantic groups for every logical unit. On structured template pages, slot `<g>` elements are already semantic groups and direct Master/Layout atoms are the required exception to grouping. Authored native preset fragments (`preset_shape_svg.py`) already are one atomic `<g id>` each and count as one ordinary content group. When a preset needs labels or decorations, put the preset and those siblings inside a separate parent content group; never put them inside the preset group itself.
- **Spec adherence**: follow color, layout, canvas format, and typography in the spec
- **Template structure**: if templates exist, inherit the visual framework
- **Main-agent ownership**: SVG generation must run in the main agent (not sub-agents) — pages share upstream context for cross-page visual continuity
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.md
index 2f05e6a5..c029b44d 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -547,9 +547,9 @@ These forms are needed only when the stated PPT behavior matters:
### 4.3 Element Grouping (Mandatory)
-Wrap logically related Slide-local elements in top-level `<g id="...">` groups. This is **required on every generated page**, not an optional convenience: it produces real PowerPoint groups in the exported PPTX and gives each content unit a stable animation anchor. Plain `<g>` is the grouping primitive; keep alpha on individual descendants per §2.2. Flat free-design/brand-only pages use only ordinary semantic groups. On structured template pages, direct atomic Master/Layout elements are the required exception and a top-level slot `<g>` is already a semantic group.
+Wrap logically related Slide-local elements in top-level `<g id="...">` groups. This is **required on every generated page**, not an optional convenience: it produces real PowerPoint groups in the exported PPTX and gives each content unit a stable animation anchor. Plain `<g>` is the grouping primitive; keep alpha on individual descendants per §2.2. Flat free-design/brand-only pages use only ordinary semantic groups. On structured template pages, direct atomic Master/Layout elements are the required exception and a top-level slot `<g>` is already a semantic group. Nested implementation groups inside one named content unit may remain anonymous unless another specialized contract requires an id; they are not independent animation targets.
-**Semantic-group rule**: direct Slide content uses semantic groups. Aim for **3–8 ordinary top-level content `<g id>` groups per slide**; on structured template pages, slot groups and atomic Master/Layout objects are excluded. Each ordinary group becomes one entrance step under the chosen animation trigger. Leaving Slide-local titles, body lines, list items, cards, or decorative clusters as ungrouped top-level atoms is a contract violation.
+**Semantic-group rule**: direct Slide content uses semantic groups. Aim for **3–8 ordinary top-level content `<g id>` groups per slide**; on structured template pages, slot groups and atomic Master/Layout objects are excluded. Each ordinary group becomes one entrance step under the chosen animation trigger. Leaving Slide-local titles, body lines, list items, cards, or decorative clusters as ungrouped top-level atoms is an authoring-contract violation reported as an aggregate Checker warning.
**Structural atoms and slots are excluded automatically.** `data-pptx-layer` and `data-pptx-placeholder` semantics are read first; otherwise explicit `data-pptx-role` values (`background`, `decoration`, `header`, `footer`, `chrome`, `watermark`, `page-number`, `logo`) mark Slide-local static framing (§4.1, [`semantic-svg.md`](semantic-svg.md)). A normal slot group has exactly one direct compatible carrier; several drawing atoms require the explicit composite `object` proxy fallback. Native chart/table carrier groups retain their specialized §7 contract.
@@ -573,11 +573,11 @@ separate parent content group; never put them inside the preset group itself.
**Forbidden**:
- One giant `<g>` around the whole slide (collapses to a single animation step).
-- Many ungrouped Slide-local `<rect>` / `<text>` / `<path>` atoms — fallback animation caps at 8 primitives, dense pages may skip animation, and selection/editing degrades.
+- Many ungrouped Slide-local `<rect>` / `<text>` / `<path>` atoms — they have no stable sidecar target and selection/editing degrades. Primitive fallback applies only when the root contains no top-level `<g>` at all; it is capped at 8 visible primitives.
- One group per icon / text line / mark (too many steps).
- Anonymous top-level groups — every top-level semantic group needs a descriptive `id`.
-**Naming — required.** A descriptive `id` on every top-level content `<g>` (`card-1`, `step-discover`, `header`, `footer`) is mandatory; it is the animation anchor and the group identity in PPTX. Without it, the exporter falls back to at most 8 top-level primitives or skips animation on dense pages.
+**Naming — required.** A descriptive, page-unique `id` on every top-level content `<g>` (`card-1`, `step-discover`, `header`, `footer`) is mandatory; it is the stable SVG-side animation and trace anchor. An anonymous top-level group still converts, but `animations.json` cannot reference it; an anonymous one-child implementation wrapper may also flatten. Primitive fallback is unrelated and applies only to roots with no top-level groups.
```xml
<g id="card-benefits-1">
diff --git a/skills/ppt-master/scripts/animation_config.py b/skills/ppt-master/scripts/animation_config.py
index 275022ab..7a1c9506 100644
--- a/skills/ppt-master/scripts/animation_config.py
+++ b/skills/ppt-master/scripts/animation_config.py
@@ -89,15 +89,20 @@ def main(argv: list[str] | None = None) -> int:
output_path=args.output,
force=args.force,
)
- except FileExistsError as exc:
+ except (FileExistsError, ValueError) as exc:
print(f'Error: {exc}', file=sys.stderr)
- print('Use --force to overwrite.', file=sys.stderr)
+ if isinstance(exc, FileExistsError):
+ print('Use --force to overwrite.', file=sys.stderr)
return 1
print(f'Animation config scaffold written: {output_path}')
return 0
if args.command == 'list-groups':
- lines, anonymous = build_group_listing(project_path)
+ try:
+ lines, anonymous = build_group_listing(project_path)
+ except ValueError as exc:
+ print(f'Error: {exc}', file=sys.stderr)
+ return 1
for line in lines:
print(line)
for warning in anonymous:
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 7a7339f0..2ed76fdb 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -39,6 +39,7 @@ except ImportError:
try:
from svg_to_pptx.animation_config import (
load_animation_config as _load_animation_config,
+ usable_animation_group_id as _usable_animation_group_id,
validate_animation_config as _validate_animation_config,
validate_animation_config_errors as _validate_animation_config_errors,
validate_transition_config as _validate_transition_config,
@@ -49,6 +50,9 @@ except ImportError as exc:
_validate_animation_config_errors = None
_validate_transition_config = None
_animation_config_import_error = str(exc)
+
+ def _usable_animation_group_id(raw: str | None) -> str | None:
+ return raw if raw and raw.strip() else None
else:
_animation_config_import_error = None
@@ -285,6 +289,7 @@ except ImportError:
try:
from svg_to_pptx.semantic_markers import (
SEMANTIC_ATTRS as _SEMANTIC_ATTRS,
+ is_static_page_frame as _is_static_page_frame,
validate_semantic_markers as _validate_semantic_markers,
)
except ImportError:
@@ -292,6 +297,7 @@ except ImportError:
'data-pptx-page-role',
'data-pptx-role',
})
+ _is_static_page_frame = None
_validate_semantic_markers = None
try:
@@ -1231,7 +1237,7 @@ class SVGQualityChecker:
self._check_preset_geometry_transforms(root, result)
# 8. Check object-level animation anchor quality.
- self._check_animation_group_ids(root, result)
+ self._check_animation_group_ids(root, svg_path, result)
# 8b. Check <pattern> elements declare a PPTX preset.
self._check_pattern_fills(root, result)
@@ -3359,19 +3365,143 @@ class SVGQualityChecker:
visit(root, _IDENTITY_MATRIX)
result['errors'].extend(sorted(issues))
- def _check_animation_group_ids(self, root: ET.Element, result: Dict):
- """Warn when visible top-level groups cannot be customized."""
+ @staticmethod
+ def _is_full_canvas_root_rect(
+ root: ET.Element,
+ element: ET.Element,
+ ) -> bool:
+ """Return whether one direct rect is the ordinary full-page backdrop."""
+ if (
+ _local_name(element) != 'rect'
+ or _parse_project_geometry_length is None
+ or any(
+ element.get(attribute)
+ for attribute in ('transform', 'filter', 'clip-path')
+ )
+ ):
+ return False
+ viewbox = _parse_viewbox_values(root.get('viewBox') or '')
+ if viewbox is None:
+ return False
+
+ parent_by_id = {id(element): root}
+
+ def inherited(name: str, default: str) -> str:
+ return _effective_presentation_value(
+ element,
+ name,
+ parent_by_id,
+ ) or default
+
+ try:
+ values = {
+ name: _parse_project_geometry_length(
+ element.get(name) or '0',
+ name,
+ )
+ for name in ('x', 'y', 'width', 'height', 'rx', 'ry')
+ }
+ stroke_width = _parse_project_geometry_length(
+ inherited('stroke-width', '1'),
+ 'stroke-width',
+ )
+ stroke_opacity = (
+ _parse_project_opacity(inherited('stroke-opacity', '1'))
+ if _parse_project_opacity is not None else 1.0
+ )
+ except ValueError:
+ return False
+ fill = inherited('fill', '#000000').strip().lower()
+ stroke = inherited('stroke', 'none').strip().lower()
+ if (
+ fill == 'none'
+ or (
+ stroke != 'none'
+ and stroke_width > 0
+ and stroke_opacity > 0
+ )
+ ):
+ return False
+
+ view_x, view_y, view_width, view_height = viewbox
+ tolerance = 0.5
+ return (
+ values['rx'] == 0
+ and values['ry'] == 0
+ and abs(values['x'] - view_x) <= tolerance
+ and abs(values['y'] - view_y) <= tolerance
+ and abs(values['width'] - view_width) <= tolerance
+ and abs(values['height'] - view_height) <= tolerance
+ )
+
+ def _check_animation_group_ids(
+ self,
+ root: ET.Element,
+ svg_path: Path,
+ result: Dict,
+ ):
+ """Validate top-level animation anchors without policing inner groups."""
non_visual = {'defs', 'title', 'desc', 'metadata', 'style'}
- for index, child in enumerate(list(root), start=1):
- tag = child.tag.split('}', 1)[-1]
+ group_indexes: Dict[str, List[int]] = defaultdict(list)
+ ungrouped: List[str] = []
+ visual_index = 0
+
+ for child in root:
+ tag = _local_name(child)
if tag in non_visual:
continue
- if tag == 'g' and not child.get('id'):
- result['warnings'].append(
- f"Top-level visible <g> #{index} has no id; "
- "object-level animation config cannot reference it"
+ visual_index += 1
+ is_first_visual = visual_index == 1
+
+ if tag == 'g':
+ group_id = _usable_animation_group_id(child.get('id'))
+ if group_id is None:
+ result['warnings'].append(
+ f"Top-level visible <g> #{visual_index} has no id; "
+ "object-level animation config cannot reference it"
+ )
+ continue
+ group_indexes[group_id].append(visual_index)
+ continue
+
+ if svg_path.parent.name != 'svg_output':
+ continue
+ if child.get('data-pptx-layer') is not None:
+ continue
+ if (
+ _is_static_page_frame is not None
+ and _is_static_page_frame(
+ child.get('data-pptx-role'),
+ child.get('data-pptx-placeholder'),
+ )
+ ):
+ continue
+ if is_first_visual and self._is_full_canvas_root_rect(root, child):
+ continue
+ child_id = (child.get('id') or '').strip()
+ ungrouped.append(
+ f'<{tag} id="{child_id}">'
+ if child_id else f'<{tag}> #{visual_index}'
+ )
+
+ for group_id, indexes in sorted(group_indexes.items()):
+ if len(indexes) > 1:
+ positions = ', '.join(str(item) for item in indexes)
+ result['errors'].append(
+ f'Duplicate top-level group id {group_id!r} at visible '
+ f'positions {positions}; animation target ids must be unique'
)
+ if ungrouped:
+ samples = ', '.join(ungrouped[:3])
+ if len(ungrouped) > 3:
+ samples += ', ...'
+ result['warnings'].append(
+ f'{len(ungrouped)} ungrouped top-level Slide-local element(s) '
+ f'in svg_output ({samples}); wrap each logical content unit '
+ 'in a top-level <g id="...">'
+ )
+
# OOXML ST_PresetPatternVal enum — anything outside this set produces a
# PPTX schema violation ("PowerPoint found a problem with the content").
_OOXML_PATTERN_PRESETS = frozenset({
diff --git a/skills/ppt-master/scripts/svg_to_pptx/animation_config.py b/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
index 6f8e9fed..20af3e82 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
@@ -61,6 +61,11 @@ def is_chrome_id(elem_id: str | None) -> bool:
return any(t in _CHROME_ID_TOKENS for t in tokens if t)
+def usable_animation_group_id(raw: str | None) -> str | None:
+ """Return one nonblank SVG animation anchor verbatim, else ``None``."""
+ return raw if raw and raw.strip() else None
+
+
def scan_svg_targets(svg_path: Path) -> tuple[list[GroupTarget], list[str]]:
"""Scan one SVG for top-level visible group ids and anonymous groups."""
root = ET.parse(str(svg_path)).getroot()
@@ -75,8 +80,8 @@ def scan_svg_targets(svg_path: Path) -> tuple[list[GroupTarget], list[str]]:
visual_index += 1
if tag != 'g':
continue
- group_id = child.get('id')
- if not group_id:
+ group_id = usable_animation_group_id(child.get('id'))
+ if group_id is None:
anonymous_groups.append(f'{svg_path.stem}: top-level group #{visual_index}')
continue
role = child.get('data-pptx-role')
@@ -107,6 +112,31 @@ def scan_svg_targets(svg_path: Path) -> tuple[list[GroupTarget], list[str]]:
return targets, anonymous_groups
+def _duplicate_target_ids(targets: list[GroupTarget]) -> tuple[str, ...]:
+ """Return duplicate top-level animation anchors in deterministic order."""
+ counts: dict[str, int] = {}
+ for target in targets:
+ counts[target.group_id] = counts.get(target.group_id, 0) + 1
+ return tuple(sorted(group_id for group_id, count in counts.items() if count > 1))
+
+
+def _duplicate_target_error(slide_name: str, duplicates: tuple[str, ...]) -> str:
+ rendered = ', '.join(repr(group_id) for group_id in duplicates)
+ return (
+ f'SVG slide "{slide_name}" has duplicate top-level group id(s): '
+ f'{rendered}; animation target ids must be unique'
+ )
+
+
+def _require_unique_target_ids(
+ slide_name: str,
+ targets: list[GroupTarget],
+) -> None:
+ duplicates = _duplicate_target_ids(targets)
+ if duplicates:
+ raise ValueError(_duplicate_target_error(slide_name, duplicates))
+
+
def scan_project_targets(project_path: Path) -> tuple[dict[str, list[GroupTarget]], list[str]]:
"""Scan ``svg_output/*.svg`` for animation targets."""
svg_dir = project_path / 'svg_output'
@@ -428,6 +458,14 @@ def validate_animation_config(
for item in anonymous_groups:
warnings.append(f'{item} has no id and cannot be customized in animations.json')
+ duplicates_by_slide: dict[str, tuple[str, ...]] = {}
+ for slide_name, targets in targets_by_slide.items():
+ duplicates = _duplicate_target_ids(targets)
+ if duplicates:
+ duplicates_by_slide[slide_name] = duplicates
+ for slide_name, duplicates in duplicates_by_slide.items():
+ warnings.append(_duplicate_target_error(slide_name, duplicates))
+
known_slides = set(targets_by_slide)
slides = config.get('slides', {})
if not isinstance(slides, dict):
@@ -442,14 +480,20 @@ def validate_animation_config(
if not isinstance(slide_cfg, dict):
continue
+ slide_targets = targets_by_slide.get(slide_name, [])
+ duplicate_ids = duplicates_by_slide.get(slide_name, ())
+ ambiguous_ids = set(duplicate_ids)
known_groups = {
target.group_id: target
- for target in targets_by_slide.get(slide_name, [])
+ for target in slide_targets
+ if target.group_id not in ambiguous_ids
}
groups = slide_cfg.get('groups', {})
if not isinstance(groups, dict):
continue
for group_id, group_cfg in groups.items():
+ if group_id in ambiguous_ids:
+ continue
if group_id not in known_groups:
warnings.append(
f'animations.json references missing group: {slide_name}/{group_id}'
@@ -485,6 +529,7 @@ def build_scaffold(project_path: Path) -> dict[str, Any]:
targets_by_slide, _anonymous = scan_project_targets(project_path)
slides: dict[str, Any] = {}
for slide_name, targets in targets_by_slide.items():
+ _require_unique_target_ids(slide_name, targets)
groups: dict[str, Any] = {}
for target in targets:
if target.chrome:
@@ -515,6 +560,7 @@ def build_group_listing(project_path: Path) -> tuple[list[str], list[str]]:
targets_by_slide, anonymous = scan_project_targets(project_path)
lines: list[str] = []
for slide_name, targets in targets_by_slide.items():
+ _require_unique_target_ids(slide_name, targets)
ids = [t.group_id for t in targets if not t.chrome]
if not ids:
lines.append(f'{slide_name}: (no animatable groups)')
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
index 97f78b93..691b9a3b 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -73,7 +73,7 @@ from .elements import (
project_image_errors,
project_nested_svg_crop_errors,
)
-from ..animation_config import is_chrome_id
+from ..animation_config import is_chrome_id, usable_animation_group_id
from ..native_objects import (
NativeMarkerAttributeError,
convert_native_object,
@@ -632,7 +632,7 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
if local_opacity is None:
local_opacity = 1.0
- elem_id = elem.get('id')
+ elem_id = usable_animation_group_id(elem.get('id'))
semantic_role = elem.get('data-pptx-role')
placeholder = elem.get('data-pptx-placeholder')
has_explicit_semantics = (
diff --git a/skills/ppt-master/scripts/test_svg_quality_checker.py b/skills/ppt-master/scripts/test_svg_quality_checker.py
index 14b19eca..e8f5f78c 100644
--- a/skills/ppt-master/scripts/test_svg_quality_checker.py
+++ b/skills/ppt-master/scripts/test_svg_quality_checker.py
@@ -17,6 +17,7 @@ SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))
+from animation_config import main as animation_config_main
from svg_quality_checker import SVGQualityChecker
from pptx_shapes import (
CONNECTOR_PRESET_TYPES,
@@ -30,6 +31,11 @@ from pptx_to_svg.preset_authoring import (
)
from pptx_to_svg.emu_units import Xfrm
from pptx_to_svg.txbody_to_svg import convert_vertical_txbody
+from svg_to_pptx.animation_config import (
+ build_group_listing,
+ build_scaffold,
+ validate_animation_config,
+)
from svg_to_pptx.drawingml.converter import (
SvgNativeConversionError,
convert_svg_to_slide_shapes,
@@ -81,6 +87,14 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):
svg_path.write_text(content, encoding='utf-8')
return SVGQualityChecker().check_file(str(svg_path))
+ def _check_svg_output(self, content: str) -> dict:
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ output_dir = Path(tmp_dir) / 'svg_output'
+ output_dir.mkdir()
+ svg_path = output_dir / 'fixture.svg'
+ svg_path.write_text(content, encoding='utf-8')
+ return SVGQualityChecker().check_file(str(svg_path))
+
@staticmethod
def _text_bound_warnings(result: dict) -> list[str]:
return [
@@ -119,6 +133,200 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):
):
convert_svg_to_slide_shapes(svg_path)
+ def test_top_level_group_ids_are_unique_animation_anchors(self):
+ duplicate = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
+ <g id="card"><rect x="10" y="10" width="20" height="20" fill="#000000"/></g>
+ <g id="card"><rect x="40" y="10" width="20" height="20" fill="#000000"/></g>
+</svg>'''
+ result = self._check(duplicate)
+ self.assertTrue(any(
+ "Duplicate top-level group id 'card'" in error
+ for error in result['errors']
+ ))
+
+ nested_anonymous = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
+ <g id="card"><g><rect x="10" y="10" width="20" height="20" fill="#000000"/></g></g>
+</svg>'''
+ nested_result = self._check(nested_anonymous)
+ self.assertFalse(any(
+ 'Top-level visible <g>' in warning
+ for warning in nested_result['warnings']
+ ))
+
+ blank = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
+ <g id=" ">
+ <rect x="10" y="10" width="20" height="20" fill="#000000"/>
+ <rect x="40" y="10" width="20" height="20" fill="#000000"/>
+ </g>
+</svg>'''
+ blank_result = self._check(blank)
+ self.assertTrue(any(
+ 'Top-level visible <g> #1 has no id' in warning
+ for warning in blank_result['warnings']
+ ))
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ svg_path = Path(tmp_dir) / 'blank-id.svg'
+ svg_path.write_text(blank, encoding='utf-8')
+ conversion = convert_svg_to_slide_shapes(svg_path)
+ self.assertEqual(conversion[3], [])
+ self.assertIn('<p:grpSp>', conversion[0])
+
+ def test_svg_output_aggregates_only_ordinary_ungrouped_root_atoms(self):
+ content = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"
+ data-pptx-page-role="content">
+ <rect x="0" y="0" width="100" height="100" fill="#FFFFFF"/>
+ <rect id="layout-rule" x="0" y="5" width="100" height="2"
+ fill="#CCCCCC" data-pptx-layer="layout"/>
+ <rect id="footer-rule" x="0" y="95" width="100" height="2"
+ fill="#CCCCCC" data-pptx-role="footer"/>
+ <g id="card"><g><rect x="10" y="10" width="30" height="20" fill="#EEEEEE"/></g></g>
+ <rect id="loose-card" x="50" y="10" width="30" height="20" fill="#EEEEEE"/>
+ <text id="loose-title" x="50" y="45" font-size="20">Loose</text>
+</svg>'''
+ result = self._check_svg_output(content)
+ warnings = [
+ warning for warning in result['warnings']
+ if 'ungrouped top-level Slide-local element(s)' in warning
+ ]
+ self.assertEqual(len(warnings), 1)
+ self.assertIn('2 ungrouped', warnings[0])
+ self.assertIn('<rect id="loose-card">', warnings[0])
+ self.assertIn('<text id="loose-title">', warnings[0])
+
+ outlined_canvas = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
+ <rect id="outline" x="0" y="0" width="100" height="100"
+ fill="none" stroke="#000000"/>
+</svg>'''
+ outline_result = self._check_svg_output(outlined_canvas)
+ self.assertTrue(any(
+ '1 ungrouped top-level Slide-local element(s)' in warning
+ for warning in outline_result['warnings']
+ ))
+
+ inherited_no_fill = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"
+ fill="none">
+ <rect id="outline" x="0" y="0" width="100" height="100"/>
+</svg>'''
+ inherited_result = self._check_svg_output(inherited_no_fill)
+ self.assertTrue(any(
+ '1 ungrouped top-level Slide-local element(s)' in warning
+ for warning in inherited_result['warnings']
+ ))
+
+ zero_width_stroke = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
+ <rect x="0" y="0" width="100" height="100" fill="#FFFFFF"
+ stroke="#000000" stroke-width="0"/>
+</svg>'''
+ zero_stroke_result = self._check_svg_output(zero_width_stroke)
+ self.assertFalse(any(
+ 'ungrouped top-level Slide-local element(s)' in warning
+ for warning in zero_stroke_result['warnings']
+ ))
+
+ ordinary_result = self._check(content)
+ self.assertFalse(any(
+ 'ungrouped top-level Slide-local element(s)' in warning
+ for warning in ordinary_result['warnings']
+ ))
+
+ def test_animation_tools_reject_duplicate_top_level_group_ids(self):
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ project = Path(tmp_dir)
+ output_dir = project / 'svg_output'
+ output_dir.mkdir()
+ (output_dir / 'fixture.svg').write_text(
+ '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
+ <g id="card"><rect x="10" y="10" width="20" height="20" fill="#000000"/></g>
+ <g id="card"><rect x="40" y="10" width="20" height="20" fill="#000000"/></g>
+</svg>''',
+ encoding='utf-8',
+ )
+ config = {
+ 'version': 1,
+ 'slides': {'fixture': {'groups': {'card': {}}}},
+ }
+ diagnostics = validate_animation_config(project, config)
+ self.assertEqual(
+ sum(
+ 'duplicate top-level group id(s)' in item
+ for item in diagnostics
+ ),
+ 1,
+ )
+ self.assertFalse(any(
+ 'references missing group' in item
+ for item in diagnostics
+ ))
+ with self.assertRaisesRegex(ValueError, 'duplicate top-level group id'):
+ build_scaffold(project)
+ with self.assertRaisesRegex(ValueError, 'duplicate top-level group id'):
+ build_group_listing(project)
+
+ (project / 'animations.json').write_text(
+ json.dumps(config),
+ encoding='utf-8',
+ )
+ for arguments in (
+ ['scaffold', str(project), '--force'],
+ ['list-groups', str(project)],
+ ['validate', str(project)],
+ ):
+ with self.subTest(command=arguments[0]):
+ stderr = io.StringIO()
+ with patch('sys.stderr', stderr):
+ self.assertEqual(animation_config_main(arguments), 1)
+ self.assertIn(
+ 'duplicate top-level group id',
+ stderr.getvalue(),
+ )
+
+ def test_animation_group_ids_are_scoped_to_each_slide(self):
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ project = Path(tmp_dir)
+ output_dir = project / 'svg_output'
+ output_dir.mkdir()
+ for slide_name in ('01_cover', '02_content'):
+ (output_dir / f'{slide_name}.svg').write_text(
+ '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
+ <g id="card"><rect x="10" y="10" width="20" height="20" fill="#000000"/></g>
+</svg>''',
+ encoding='utf-8',
+ )
+ scaffold = build_scaffold(project)
+ self.assertEqual(
+ set(scaffold['slides']),
+ {'01_cover', '02_content'},
+ )
+ self.assertEqual(
+ scaffold['slides']['01_cover']['groups'],
+ {'card': {}},
+ )
+ lines, anonymous = build_group_listing(project)
+ self.assertEqual(
+ lines,
+ ['01_cover: card', '02_content: card'],
+ )
+ self.assertEqual(anonymous, [])
+
+ def test_animation_scan_ignores_anonymous_nested_groups(self):
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ project = Path(tmp_dir)
+ output_dir = project / 'svg_output'
+ output_dir.mkdir()
+ (output_dir / 'fixture.svg').write_text(
+ '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
+ <g id="card"><g><rect x="10" y="10" width="20" height="20" fill="#000000"/></g></g>
+ <g id=" "><rect x="40" y="10" width="20" height="20" fill="#000000"/></g>
+</svg>''',
+ encoding='utf-8',
+ )
+ lines, anonymous = build_group_listing(project)
+ self.assertEqual(lines, ['fixture: card'])
+ self.assertEqual(
+ anonymous,
+ ['fixture: top-level group #2'],
+ )
+
def _nested_crop_source(
self,
*,