| 1 | """Motion sidecar loading, SVG target scanning, and validation.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import json |
| 6 | import math |
| 7 | import re |
| 8 | from dataclasses import dataclass |
| 9 | from pathlib import Path |
| 10 | from typing import Any |
| 11 | from xml.etree import ElementTree as ET |
| 12 | |
| 13 | from pptx_animations import ( |
| 14 | ANIMATIONS, |
| 15 | ANIMATION_AFTER_EFFECTS, |
| 16 | ANIMATION_MODES, |
| 17 | ANIMATION_RESTARTS, |
| 18 | ANIMATION_TIMING_OPTION_FIELDS, |
| 19 | ANIMATION_TRIGGERS, |
| 20 | animation_effect_supports_bounce_end, |
| 21 | animation_seconds_to_milliseconds, |
| 22 | normalize_animation_effect, |
| 23 | normalize_animation_effect_options, |
| 24 | normalize_animation_effect_request, |
| 25 | normalize_animation_trigger, |
| 26 | ) |
| 27 | from pptx_transitions import ( |
| 28 | normalize_transition_effect, |
| 29 | normalize_transition_effect_request, |
| 30 | validate_seconds, |
| 31 | ) |
| 32 | from slide_roster import discover_slide_svgs |
| 33 | |
| 34 | from .drawingml.utils import SVG_NS |
| 35 | from .pptx_package.narration import AUDIO_CONTENT_TYPES |
| 36 | from .semantic_markers import is_static_page_frame |
| 37 | |
| 38 | |
| 39 | _NON_VISUAL_TAGS = frozenset(('defs', 'title', 'desc', 'metadata', 'style')) |
| 40 | _INHERITANCE_SENSITIVE_ANIMATION_FIELDS = frozenset({ |
| 41 | 'effect', |
| 42 | 'effect_options', |
| 43 | 'repeat_count', |
| 44 | 'repeat_duration', |
| 45 | 'accelerate', |
| 46 | 'decelerate', |
| 47 | 'bounce_end', |
| 48 | }) |
| 49 | _GROUP_EFFECT_FIELDS = frozenset({ |
| 50 | 'effect', |
| 51 | 'effect_options', |
| 52 | 'duration', |
| 53 | 'delay', |
| 54 | 'order', |
| 55 | 'trigger', |
| 56 | 'trigger_shape', |
| 57 | *ANIMATION_TIMING_OPTION_FIELDS, |
| 58 | 'after_effect', |
| 59 | 'sound', |
| 60 | }) |
| 61 | _CHROME_ID_TOKENS = frozenset({ |
| 62 | 'background', 'bg', |
| 63 | 'decoration', 'decorations', 'decor', |
| 64 | 'header', 'footer', |
| 65 | 'chrome', 'watermark', |
| 66 | 'pagenumber', 'pagenum', 'slidenumber', 'slidenum', |
| 67 | 'logo', 'nav', 'rule', |
| 68 | }) |
| 69 | |
| 70 | |
| 71 | @dataclass(frozen=True) |
| 72 | class GroupTarget: |
| 73 | """Top-level SVG group available for PowerPoint animation anchoring.""" |
| 74 | |
| 75 | slide: str |
| 76 | group_id: str |
| 77 | order: int |
| 78 | chrome: bool = False |
| 79 | structurally_static: bool = False |
| 80 | |
| 81 | |
| 82 | @dataclass(frozen=True) |
| 83 | class MorphPair: |
| 84 | """One explicit PowerPoint Morph identity across adjacent slides.""" |
| 85 | |
| 86 | source_slide: str |
| 87 | destination_slide: str |
| 88 | key: str |
| 89 | source_group_id: str |
| 90 | destination_group_id: str |
| 91 | |
| 92 | @property |
| 93 | def shape_name(self) -> str: |
| 94 | """Return the Selection Pane name PowerPoint uses for forced matching.""" |
| 95 | return f'!!{self.key}' |
| 96 | |
| 97 | |
| 98 | def _tag_name(elem: ET.Element) -> str: |
| 99 | return elem.tag.replace(f'{{{SVG_NS}}}', '') |
| 100 | |
| 101 | |
| 102 | def is_chrome_id(elem_id: str | None) -> bool: |
| 103 | """Return whether a group id represents static slide chrome.""" |
| 104 | if not elem_id: |
| 105 | return False |
| 106 | lower = elem_id.lower() |
| 107 | compact = lower.replace('-', '').replace('_', '') |
| 108 | if compact in _CHROME_ID_TOKENS: |
| 109 | return True |
| 110 | tokens = re.split(r'[-_]', lower) |
| 111 | return any(t in _CHROME_ID_TOKENS for t in tokens if t) |
| 112 | |
| 113 | |
| 114 | def usable_animation_group_id(raw: str | None) -> str | None: |
| 115 | """Return one nonblank SVG animation anchor verbatim, else ``None``.""" |
| 116 | return raw if raw and raw.strip() else None |
| 117 | |
| 118 | |
| 119 | def scan_svg_targets(svg_path: Path) -> tuple[list[GroupTarget], list[str]]: |
| 120 | """Scan one SVG for top-level visible group ids and anonymous groups.""" |
| 121 | root = ET.parse(str(svg_path)).getroot() |
| 122 | targets: list[GroupTarget] = [] |
| 123 | anonymous_groups: list[str] = [] |
| 124 | visual_index = 0 |
| 125 | |
| 126 | for child in root: |
| 127 | tag = _tag_name(child) |
| 128 | if tag in _NON_VISUAL_TAGS: |
| 129 | continue |
| 130 | visual_index += 1 |
| 131 | if tag != 'g': |
| 132 | continue |
| 133 | group_id = usable_animation_group_id(child.get('id')) |
| 134 | if group_id is None: |
| 135 | anonymous_groups.append(f'{svg_path.stem}: top-level group #{visual_index}') |
| 136 | continue |
| 137 | role = child.get('data-pptx-role') |
| 138 | placeholder = child.get('data-pptx-placeholder') |
| 139 | has_explicit_semantics = role is not None or placeholder is not None |
| 140 | has_structural_layer = child.get('data-pptx-layer') is not None |
| 141 | semantic_static = ( |
| 142 | has_explicit_semantics |
| 143 | and is_static_page_frame(role, placeholder) |
| 144 | ) |
| 145 | structurally_static = has_structural_layer or semantic_static |
| 146 | if has_structural_layer: |
| 147 | chrome = True |
| 148 | elif has_explicit_semantics: |
| 149 | chrome = semantic_static |
| 150 | else: |
| 151 | chrome = is_chrome_id(group_id) |
| 152 | targets.append( |
| 153 | GroupTarget( |
| 154 | slide=svg_path.stem, |
| 155 | group_id=group_id, |
| 156 | order=visual_index, |
| 157 | chrome=chrome, |
| 158 | structurally_static=structurally_static, |
| 159 | ) |
| 160 | ) |
| 161 | |
| 162 | return targets, anonymous_groups |
| 163 | |
| 164 | |
| 165 | def _duplicate_target_ids(targets: list[GroupTarget]) -> tuple[str, ...]: |
| 166 | """Return duplicate top-level animation anchors in deterministic order.""" |
| 167 | counts: dict[str, int] = {} |
| 168 | for target in targets: |
| 169 | counts[target.group_id] = counts.get(target.group_id, 0) + 1 |
| 170 | return tuple(sorted(group_id for group_id, count in counts.items() if count > 1)) |
| 171 | |
| 172 | |
| 173 | def _duplicate_target_error(slide_name: str, duplicates: tuple[str, ...]) -> str: |
| 174 | rendered = ', '.join(repr(group_id) for group_id in duplicates) |
| 175 | return ( |
| 176 | f'SVG slide "{slide_name}" has duplicate top-level group id(s): ' |
| 177 | f'{rendered}; animation target ids must be unique' |
| 178 | ) |
| 179 | |
| 180 | |
| 181 | def _require_unique_target_ids( |
| 182 | slide_name: str, |
| 183 | targets: list[GroupTarget], |
| 184 | ) -> None: |
| 185 | duplicates = _duplicate_target_ids(targets) |
| 186 | if duplicates: |
| 187 | raise ValueError(_duplicate_target_error(slide_name, duplicates)) |
| 188 | |
| 189 | |
| 190 | def scan_project_targets( |
| 191 | project_path: Path, |
| 192 | *, |
| 193 | svg_files: list[Path] | None = None, |
| 194 | ) -> tuple[dict[str, list[GroupTarget]], list[str]]: |
| 195 | """Scan selected SVG files, defaulting to ``svg_output/*.svg``.""" |
| 196 | targets_by_slide: dict[str, list[GroupTarget]] = {} |
| 197 | anonymous_groups: list[str] = [] |
| 198 | if svg_files is None: |
| 199 | svg_dir = project_path / 'svg_output' |
| 200 | if not svg_dir.is_dir(): |
| 201 | return targets_by_slide, [f'svg_output directory not found: {svg_dir}'] |
| 202 | svg_files = discover_slide_svgs(svg_dir) |
| 203 | |
| 204 | for svg_path in svg_files: |
| 205 | targets, anonymous = scan_svg_targets(svg_path) |
| 206 | targets_by_slide[svg_path.stem] = targets |
| 207 | anonymous_groups.extend(anonymous) |
| 208 | |
| 209 | return targets_by_slide, anonymous_groups |
| 210 | |
| 211 | |
| 212 | def default_config_path(project_path: Path) -> Path: |
| 213 | return project_path / 'animations.json' |
| 214 | |
| 215 | |
| 216 | def load_animation_config(project_path: Path, config_path: str | None = None) -> dict[str, Any] | None: |
| 217 | """Load animation config; only an absent default sidecar is optional.""" |
| 218 | if config_path is not None: |
| 219 | if not config_path.strip(): |
| 220 | raise ValueError('Animation config path must be non-empty') |
| 221 | path = Path(config_path) |
| 222 | else: |
| 223 | path = default_config_path(project_path) |
| 224 | if config_path is not None and not path.is_absolute(): |
| 225 | path = project_path / path |
| 226 | if not path.exists(): |
| 227 | if config_path is not None: |
| 228 | raise FileNotFoundError(f'Animation config does not exist: {path}') |
| 229 | return None |
| 230 | |
| 231 | with open(path, 'r', encoding='utf-8') as f: |
| 232 | data = json.load(f) |
| 233 | if not isinstance(data, dict): |
| 234 | raise ValueError(f'Animation config must be a JSON object: {path}') |
| 235 | if data.get('version', 1) != 1: |
| 236 | raise ValueError(f'Unsupported animation config version: {data.get("version")}') |
| 237 | return data |
| 238 | |
| 239 | |
| 240 | def _valid_transition_effect(effect: str) -> bool: |
| 241 | try: |
| 242 | normalize_transition_effect(effect) |
| 243 | except ValueError: |
| 244 | return False |
| 245 | return True |
| 246 | |
| 247 | |
| 248 | def _animation_effect_error(effect: object, label: str) -> str | None: |
| 249 | if not isinstance(effect, str): |
| 250 | return f'animations.json {label} animation effect must be a string' |
| 251 | try: |
| 252 | normalize_animation_effect(effect) |
| 253 | except ValueError: |
| 254 | valid = ', '.join((*ANIMATIONS, *ANIMATION_MODES, 'none')) |
| 255 | return ( |
| 256 | f'animations.json {label} has unknown animation effect: {effect}; ' |
| 257 | f'valid effects: {valid}' |
| 258 | ) |
| 259 | return None |
| 260 | |
| 261 | |
| 262 | def resolve_slide_animation_config( |
| 263 | default_animation: dict[str, Any], |
| 264 | slide_animation: dict[str, Any], |
| 265 | ) -> dict[str, Any]: |
| 266 | """Merge one slide animation over defaults using writer inheritance rules.""" |
| 267 | resolved = dict(default_animation) |
| 268 | if 'effect' in slide_animation and 'effect_options' not in slide_animation: |
| 269 | resolved.pop('effect_options', None) |
| 270 | resolved.update(slide_animation) |
| 271 | return resolved |
| 272 | |
| 273 | |
| 274 | def animation_group_effect_entries( |
| 275 | group_cfg: dict[str, Any], |
| 276 | *, |
| 277 | path: str, |
| 278 | ) -> tuple[tuple[str, dict[str, Any]], ...]: |
| 279 | """Expand one legacy group block or one ordered multi-effect envelope.""" |
| 280 | if 'effects' not in group_cfg: |
| 281 | return ((path, group_cfg),) |
| 282 | |
| 283 | extra_fields = sorted(set(group_cfg) - {'effects'}) |
| 284 | if extra_fields: |
| 285 | rendered = ', '.join(repr(field) for field in extra_fields) |
| 286 | raise ValueError( |
| 287 | f'animations.json {path} cannot combine "effects" with ' |
| 288 | f'other group-level field(s): {rendered}' |
| 289 | ) |
| 290 | effects = group_cfg['effects'] |
| 291 | if not isinstance(effects, list): |
| 292 | raise ValueError(f'animations.json {path}.effects must be an array') |
| 293 | if not effects: |
| 294 | raise ValueError( |
| 295 | f'animations.json {path}.effects must contain at least one effect' |
| 296 | ) |
| 297 | |
| 298 | entries: list[tuple[str, dict[str, Any]]] = [] |
| 299 | for index, effect_cfg in enumerate(effects): |
| 300 | effect_path = f'{path}.effects[{index}]' |
| 301 | if not isinstance(effect_cfg, dict): |
| 302 | raise ValueError( |
| 303 | f'animations.json {effect_path} must be an object' |
| 304 | ) |
| 305 | if 'effect' not in effect_cfg: |
| 306 | raise ValueError( |
| 307 | f'animations.json {effect_path}.effect is required' |
| 308 | ) |
| 309 | entries.append((effect_path, effect_cfg)) |
| 310 | return tuple(entries) |
| 311 | |
| 312 | |
| 313 | def _animation_parameter_errors( |
| 314 | value: dict[str, Any], |
| 315 | label: str, |
| 316 | *, |
| 317 | inherited_effect: object, |
| 318 | sound_is_path: bool = True, |
| 319 | ) -> list[str]: |
| 320 | """Validate PowerPoint effect/timing parameters shared by all scopes.""" |
| 321 | errors: list[str] = [] |
| 322 | effect = value.get('effect', inherited_effect) |
| 323 | effect_options = value.get('effect_options') |
| 324 | if effect_options is not None and 'effect' not in value: |
| 325 | errors.append( |
| 326 | f'animations.json {label} effect_options requires an explicit effect' |
| 327 | ) |
| 328 | else: |
| 329 | try: |
| 330 | normalize_animation_effect_request( |
| 331 | effect, |
| 332 | effect_options, |
| 333 | allow_none=True, |
| 334 | allow_modes=True, |
| 335 | ) |
| 336 | except ValueError as exc: |
| 337 | errors.append(f'animations.json {label}: {exc}') |
| 338 | |
| 339 | repeat_count = value.get('repeat_count') |
| 340 | repeat_duration = value.get('repeat_duration') |
| 341 | if repeat_count is not None: |
| 342 | if ( |
| 343 | isinstance(repeat_count, bool) |
| 344 | or not isinstance(repeat_count, (int, float)) |
| 345 | or not math.isfinite(float(repeat_count)) |
| 346 | or float(repeat_count) <= 0 |
| 347 | or float(repeat_count) * 1000 > 4_294_967_295 |
| 348 | ): |
| 349 | errors.append( |
| 350 | f'animations.json {label} repeat_count must be a positive number: ' |
| 351 | f'{repeat_count!r}' |
| 352 | ) |
| 353 | if repeat_duration is not None: |
| 354 | try: |
| 355 | animation_seconds_to_milliseconds( |
| 356 | repeat_duration, |
| 357 | f'animations.json {label} repeat_duration', |
| 358 | allow_zero=False, |
| 359 | ) |
| 360 | except ValueError as exc: |
| 361 | errors.append(str(exc)) |
| 362 | if repeat_count is not None and repeat_duration is not None: |
| 363 | errors.append( |
| 364 | f'animations.json {label} repeat_count and repeat_duration ' |
| 365 | 'are mutually exclusive' |
| 366 | ) |
| 367 | |
| 368 | for field in ('auto_reverse', 'rewind'): |
| 369 | if field in value and not isinstance(value[field], bool): |
| 370 | errors.append( |
| 371 | f'animations.json {label} {field} must be a boolean: ' |
| 372 | f'{value[field]!r}' |
| 373 | ) |
| 374 | ratios: dict[str, float] = {} |
| 375 | for field in ('accelerate', 'decelerate', 'bounce_end'): |
| 376 | if field not in value: |
| 377 | continue |
| 378 | raw_ratio = value[field] |
| 379 | if ( |
| 380 | isinstance(raw_ratio, bool) |
| 381 | or not isinstance(raw_ratio, (int, float)) |
| 382 | or not math.isfinite(float(raw_ratio)) |
| 383 | or not 0 <= float(raw_ratio) <= 1 |
| 384 | ): |
| 385 | errors.append( |
| 386 | f'animations.json {label} {field} must be between 0 and 1: ' |
| 387 | f'{raw_ratio!r}' |
| 388 | ) |
| 389 | else: |
| 390 | ratios[field] = float(raw_ratio) |
| 391 | if ratios.get('accelerate', 0) + ratios.get('decelerate', 0) > 1: |
| 392 | errors.append( |
| 393 | f'animations.json {label} accelerate + decelerate must not exceed 1' |
| 394 | ) |
| 395 | if ratios.get('bounce_end', 0) and ratios.get('decelerate', 0): |
| 396 | errors.append( |
| 397 | f'animations.json {label} bounce_end and decelerate are ' |
| 398 | 'mutually exclusive in PowerPoint' |
| 399 | ) |
| 400 | |
| 401 | if 'restart' in value and value['restart'] not in ANIMATION_RESTARTS: |
| 402 | errors.append( |
| 403 | f'animations.json {label} restart must be one of ' |
| 404 | f'{", ".join(ANIMATION_RESTARTS)}: {value["restart"]!r}' |
| 405 | ) |
| 406 | |
| 407 | if 'after_effect' in value: |
| 408 | after_effect = value['after_effect'] |
| 409 | if isinstance(after_effect, str): |
| 410 | after_type = after_effect |
| 411 | after_color = None |
| 412 | elif isinstance(after_effect, dict): |
| 413 | unknown = set(after_effect) - {'type', 'color'} |
| 414 | for field in sorted(unknown): |
| 415 | errors.append( |
| 416 | f'animations.json {label} after_effect has unknown field: {field}' |
| 417 | ) |
| 418 | after_type = after_effect.get('type', 'none') |
| 419 | after_color = after_effect.get('color') |
| 420 | else: |
| 421 | after_type = None |
| 422 | after_color = None |
| 423 | errors.append( |
| 424 | f'animations.json {label} after_effect must be a string or object' |
| 425 | ) |
| 426 | if after_type is not None and after_type not in ANIMATION_AFTER_EFFECTS: |
| 427 | errors.append( |
| 428 | f'animations.json {label} after_effect.type must be one of ' |
| 429 | f'{", ".join(ANIMATION_AFTER_EFFECTS)}: {after_type!r}' |
| 430 | ) |
| 431 | elif after_type == 'dim': |
| 432 | if after_color is None: |
| 433 | errors.append( |
| 434 | f'animations.json {label} dim after_effect requires color' |
| 435 | ) |
| 436 | else: |
| 437 | try: |
| 438 | normalize_animation_effect_options( |
| 439 | 'emphasis_change_fill_color', |
| 440 | {'color': after_color}, |
| 441 | ) |
| 442 | except ValueError as exc: |
| 443 | errors.append(f'animations.json {label}: {exc}') |
| 444 | elif after_color is not None: |
| 445 | errors.append( |
| 446 | f'animations.json {label} after_effect.color is valid only ' |
| 447 | 'with type "dim"' |
| 448 | ) |
| 449 | |
| 450 | if 'sound' in value: |
| 451 | sound = value['sound'] |
| 452 | if sound_is_path and ( |
| 453 | not isinstance(sound, str) or not sound.strip() |
| 454 | ): |
| 455 | errors.append( |
| 456 | f'animations.json {label} sound must be a non-empty path string' |
| 457 | ) |
| 458 | elif sound_is_path and Path(sound).suffix.lower() not in AUDIO_CONTENT_TYPES: |
| 459 | errors.append( |
| 460 | f'animations.json {label} sound must use .m4a, .mp3, or .wav' |
| 461 | ) |
| 462 | return errors |
| 463 | |
| 464 | |
| 465 | def _animation_trigger_error(trigger: object, label: str) -> str | None: |
| 466 | if not isinstance(trigger, str): |
| 467 | return f'animations.json {label} animation trigger must be a string' |
| 468 | try: |
| 469 | normalize_animation_trigger(trigger) |
| 470 | except ValueError: |
| 471 | valid = ', '.join(ANIMATION_TRIGGERS) |
| 472 | return ( |
| 473 | f'animations.json {label} has unknown animation trigger: {trigger}; ' |
| 474 | f'valid triggers: {valid}' |
| 475 | ) |
| 476 | return None |
| 477 | |
| 478 | |
| 479 | def _unknown_field_errors( |
| 480 | value: dict[str, Any], |
| 481 | allowed: frozenset[str], |
| 482 | label: str, |
| 483 | ) -> list[str]: |
| 484 | return [ |
| 485 | f'animations.json {label} has unknown field: {field}' |
| 486 | for field in sorted(set(value) - allowed) |
| 487 | ] |
| 488 | |
| 489 | |
| 490 | def validate_transition_config(config: dict[str, Any]) -> list[str]: |
| 491 | """Return fatal transition-sidecar errors that must block export.""" |
| 492 | errors: list[str] = [] |
| 493 | defaults = config.get('defaults', {}) |
| 494 | default_effect = 'fade' |
| 495 | if not isinstance(defaults, dict): |
| 496 | errors.append('animations.json field "defaults" must be an object') |
| 497 | else: |
| 498 | errors.extend( |
| 499 | _transition_scope_errors( |
| 500 | defaults, |
| 501 | 'defaults', |
| 502 | inherited_effect='fade', |
| 503 | ) |
| 504 | ) |
| 505 | transition_defaults = defaults.get('transition', {}) |
| 506 | if isinstance(transition_defaults, dict): |
| 507 | value = transition_defaults.get('effect', default_effect) |
| 508 | if isinstance(value, str) and _valid_transition_effect(value): |
| 509 | default_effect = value |
| 510 | |
| 511 | slides = config.get('slides', {}) |
| 512 | if not isinstance(slides, dict): |
| 513 | errors.append('animations.json field "slides" must be an object') |
| 514 | return errors |
| 515 | for slide_name, slide_cfg in slides.items(): |
| 516 | if not isinstance(slide_cfg, dict): |
| 517 | errors.append(f'animations.json slide "{slide_name}" must be an object') |
| 518 | continue |
| 519 | errors.extend( |
| 520 | _transition_scope_errors( |
| 521 | slide_cfg, |
| 522 | f'slide "{slide_name}"', |
| 523 | inherited_effect=default_effect, |
| 524 | ) |
| 525 | ) |
| 526 | errors.extend(_morph_scope_errors(slide_name, slide_cfg)) |
| 527 | return errors |
| 528 | |
| 529 | |
| 530 | def _transition_scope_errors( |
| 531 | scope: dict[str, Any], |
| 532 | label: str, |
| 533 | *, |
| 534 | inherited_effect: str, |
| 535 | ) -> list[str]: |
| 536 | if 'transition' not in scope: |
| 537 | return [] |
| 538 | transition = scope['transition'] |
| 539 | if not isinstance(transition, dict): |
| 540 | return [f'animations.json {label} field "transition" must be an object'] |
| 541 | |
| 542 | errors = _unknown_field_errors( |
| 543 | transition, |
| 544 | frozenset({'effect', 'effect_options', 'duration', 'auto_advance'}), |
| 545 | f'{label} transition', |
| 546 | ) |
| 547 | effect = transition.get('effect', inherited_effect) |
| 548 | effect_options = transition.get('effect_options') |
| 549 | if effect_options is not None and 'effect' not in transition: |
| 550 | errors.append( |
| 551 | f'animations.json {label} transition effect_options requires ' |
| 552 | 'an explicit effect' |
| 553 | ) |
| 554 | else: |
| 555 | try: |
| 556 | normalize_transition_effect_request(effect, effect_options) |
| 557 | except ValueError as exc: |
| 558 | errors.append(f'animations.json {label} transition: {exc}') |
| 559 | try: |
| 560 | duration_allows_zero = ( |
| 561 | normalize_transition_effect(effect) is None |
| 562 | ) |
| 563 | except ValueError: |
| 564 | duration_allows_zero = False |
| 565 | for field, allow_zero in ( |
| 566 | ('duration', duration_allows_zero), |
| 567 | ('auto_advance', True), |
| 568 | ): |
| 569 | if field not in transition: |
| 570 | continue |
| 571 | try: |
| 572 | validate_seconds( |
| 573 | transition[field], |
| 574 | f'animations.json {label} transition {field}', |
| 575 | allow_zero=allow_zero, |
| 576 | ) |
| 577 | except ValueError as exc: |
| 578 | errors.append(str(exc)) |
| 579 | return errors |
| 580 | |
| 581 | |
| 582 | def _morph_scope_errors( |
| 583 | slide_name: object, |
| 584 | slide_cfg: dict[str, Any], |
| 585 | ) -> list[str]: |
| 586 | """Validate one destination slide's deterministic Morph declaration.""" |
| 587 | if 'morph' not in slide_cfg: |
| 588 | return [] |
| 589 | label = f'slide "{slide_name}" morph' |
| 590 | morph = slide_cfg['morph'] |
| 591 | if not isinstance(morph, dict): |
| 592 | return [f'animations.json {label} must be an object'] |
| 593 | |
| 594 | errors = _unknown_field_errors( |
| 595 | morph, |
| 596 | frozenset({'from', 'pairs'}), |
| 597 | label, |
| 598 | ) |
| 599 | source_slide = morph.get('from') |
| 600 | if not isinstance(source_slide, str) or not source_slide.strip(): |
| 601 | errors.append( |
| 602 | f'animations.json {label} field "from" must be a non-empty slide stem' |
| 603 | ) |
| 604 | |
| 605 | pairs = morph.get('pairs') |
| 606 | if not isinstance(pairs, dict) or not pairs: |
| 607 | errors.append( |
| 608 | f'animations.json {label} field "pairs" must be a non-empty object' |
| 609 | ) |
| 610 | else: |
| 611 | source_groups: dict[str, str] = {} |
| 612 | destination_groups: dict[str, str] = {} |
| 613 | for key, pair in pairs.items(): |
| 614 | pair_label = f'{label} pair "{key}"' |
| 615 | if ( |
| 616 | not isinstance(key, str) |
| 617 | or not key.strip() |
| 618 | or key != key.strip() |
| 619 | or key.startswith('!!') |
| 620 | or any(ord(char) < 32 for char in key) |
| 621 | ): |
| 622 | errors.append( |
| 623 | f'animations.json {pair_label} key must be a trimmed, ' |
| 624 | 'non-empty name without the !! prefix or control characters' |
| 625 | ) |
| 626 | if not isinstance(pair, dict): |
| 627 | errors.append(f'animations.json {pair_label} must be an object') |
| 628 | continue |
| 629 | errors.extend( |
| 630 | _unknown_field_errors( |
| 631 | pair, |
| 632 | frozenset({'from', 'to'}), |
| 633 | pair_label, |
| 634 | ) |
| 635 | ) |
| 636 | for field in ('from', 'to'): |
| 637 | value = pair.get(field) |
| 638 | if not isinstance(value, str) or not value.strip(): |
| 639 | errors.append( |
| 640 | f'animations.json {pair_label} field "{field}" must ' |
| 641 | 'be a non-empty top-level group id' |
| 642 | ) |
| 643 | source_group = pair.get('from') |
| 644 | if isinstance(source_group, str) and source_group.strip(): |
| 645 | previous = source_groups.setdefault(source_group, str(key)) |
| 646 | if previous != str(key): |
| 647 | errors.append( |
| 648 | f'animations.json {label} source group ' |
| 649 | f'"{source_group}" is assigned to both "{previous}" ' |
| 650 | f'and "{key}"' |
| 651 | ) |
| 652 | destination_group = pair.get('to') |
| 653 | if isinstance(destination_group, str) and destination_group.strip(): |
| 654 | previous = destination_groups.setdefault( |
| 655 | destination_group, |
| 656 | str(key), |
| 657 | ) |
| 658 | if previous != str(key): |
| 659 | errors.append( |
| 660 | f'animations.json {label} destination group ' |
| 661 | f'"{destination_group}" is assigned to both "{previous}" ' |
| 662 | f'and "{key}"' |
| 663 | ) |
| 664 | |
| 665 | transition = slide_cfg.get('transition') |
| 666 | if not isinstance(transition, dict) or 'effect' not in transition: |
| 667 | errors.append( |
| 668 | f'animations.json {label} requires an explicit slide transition ' |
| 669 | 'effect "morph"' |
| 670 | ) |
| 671 | else: |
| 672 | try: |
| 673 | effect, options = normalize_transition_effect_request( |
| 674 | transition.get('effect'), |
| 675 | transition.get('effect_options'), |
| 676 | ) |
| 677 | except ValueError: |
| 678 | pass |
| 679 | else: |
| 680 | if effect != 'morph': |
| 681 | errors.append( |
| 682 | f'animations.json {label} requires transition effect "morph"' |
| 683 | ) |
| 684 | elif options.get('morph_by', 'object') != 'object': |
| 685 | errors.append( |
| 686 | f'animations.json {label} requires Morph by object' |
| 687 | ) |
| 688 | return errors |
| 689 | |
| 690 | |
| 691 | def _resolve_morph_pairs( |
| 692 | slide_order: list[str], |
| 693 | config: dict[str, Any], |
| 694 | ) -> tuple[list[MorphPair], list[str]]: |
| 695 | """Resolve sidecar Morph declarations against the actual slide order.""" |
| 696 | slides = config.get('slides', {}) |
| 697 | if not isinstance(slides, dict): |
| 698 | return [], ['animations.json field "slides" must be an object'] |
| 699 | |
| 700 | order_by_slide = {slide_name: index for index, slide_name in enumerate(slide_order)} |
| 701 | pairs: list[MorphPair] = [] |
| 702 | errors: list[str] = [] |
| 703 | assignments: dict[str, dict[str, str]] = {} |
| 704 | keys: dict[str, dict[str, str]] = {} |
| 705 | declared_keys_by_destination: dict[str, set[str]] = {} |
| 706 | |
| 707 | for destination_slide, slide_cfg in slides.items(): |
| 708 | if not isinstance(slide_cfg, dict) or 'morph' not in slide_cfg: |
| 709 | continue |
| 710 | scope_errors = _morph_scope_errors(destination_slide, slide_cfg) |
| 711 | if scope_errors: |
| 712 | errors.extend(scope_errors) |
| 713 | continue |
| 714 | destination_index = order_by_slide.get(str(destination_slide)) |
| 715 | if destination_index is None: |
| 716 | errors.append( |
| 717 | 'animations.json morph destination slide is missing: ' |
| 718 | f'{destination_slide}' |
| 719 | ) |
| 720 | continue |
| 721 | if destination_index == 0: |
| 722 | errors.append( |
| 723 | 'animations.json first slide cannot declare an incoming Morph: ' |
| 724 | f'{destination_slide}' |
| 725 | ) |
| 726 | continue |
| 727 | |
| 728 | morph = slide_cfg['morph'] |
| 729 | source_slide = str(morph['from']) |
| 730 | expected_source = slide_order[destination_index - 1] |
| 731 | if source_slide != expected_source: |
| 732 | errors.append( |
| 733 | f'animations.json slide "{destination_slide}" morph.from must ' |
| 734 | f'reference the immediately preceding slide "{expected_source}", ' |
| 735 | f'not "{source_slide}"' |
| 736 | ) |
| 737 | continue |
| 738 | |
| 739 | declared_keys_by_destination[str(destination_slide)] = set( |
| 740 | morph['pairs'] |
| 741 | ) |
| 742 | for key, pair in morph['pairs'].items(): |
| 743 | resolved = MorphPair( |
| 744 | source_slide=source_slide, |
| 745 | destination_slide=str(destination_slide), |
| 746 | key=str(key), |
| 747 | source_group_id=str(pair['from']), |
| 748 | destination_group_id=str(pair['to']), |
| 749 | ) |
| 750 | pair_conflict = False |
| 751 | for slide_name, group_id in ( |
| 752 | (resolved.source_slide, resolved.source_group_id), |
| 753 | (resolved.destination_slide, resolved.destination_group_id), |
| 754 | ): |
| 755 | slide_assignments = assignments.setdefault(slide_name, {}) |
| 756 | previous_key = slide_assignments.setdefault(group_id, resolved.key) |
| 757 | if previous_key != resolved.key: |
| 758 | errors.append( |
| 759 | f'animations.json Morph group "{slide_name}/{group_id}" ' |
| 760 | f'is assigned to both "{previous_key}" and "{resolved.key}"' |
| 761 | ) |
| 762 | pair_conflict = True |
| 763 | slide_keys = keys.setdefault(slide_name, {}) |
| 764 | previous_group = slide_keys.setdefault(resolved.key, group_id) |
| 765 | if previous_group != group_id: |
| 766 | errors.append( |
| 767 | f'animations.json Morph key "{resolved.key}" maps to both ' |
| 768 | f'"{slide_name}/{previous_group}" and ' |
| 769 | f'"{slide_name}/{group_id}"' |
| 770 | ) |
| 771 | pair_conflict = True |
| 772 | if not pair_conflict: |
| 773 | pairs.append(resolved) |
| 774 | |
| 775 | for destination_slide, declared_keys in declared_keys_by_destination.items(): |
| 776 | destination_index = order_by_slide[destination_slide] |
| 777 | source_slide = slide_order[destination_index - 1] |
| 778 | shared_keys = ( |
| 779 | set(keys.get(source_slide, {})) |
| 780 | & set(keys.get(destination_slide, {})) |
| 781 | ) |
| 782 | unexpected_keys = sorted(shared_keys - declared_keys) |
| 783 | if unexpected_keys: |
| 784 | errors.append( |
| 785 | f'animations.json slide "{destination_slide}" Morph would ' |
| 786 | 'force undeclared adjacent key(s): ' |
| 787 | + ', '.join(f'"{key}"' for key in unexpected_keys) |
| 788 | ) |
| 789 | return pairs, list(dict.fromkeys(errors)) |
| 790 | |
| 791 | |
| 792 | def resolve_morph_pairs( |
| 793 | slide_order: list[str], |
| 794 | config: dict[str, Any] | None, |
| 795 | ) -> tuple[MorphPair, ...]: |
| 796 | """Return validated deterministic Morph pairs in authored order.""" |
| 797 | if not config: |
| 798 | return () |
| 799 | pairs, errors = _resolve_morph_pairs(slide_order, config) |
| 800 | if errors: |
| 801 | raise ValueError('; '.join(errors)) |
| 802 | return tuple(pairs) |
| 803 | |
| 804 | |
| 805 | def validate_animation_config_errors(config: dict[str, Any]) -> list[str]: |
| 806 | """Return fatal object-animation errors that must block export.""" |
| 807 | errors = _unknown_field_errors( |
| 808 | config, |
| 809 | frozenset({'version', 'defaults', 'slides'}), |
| 810 | 'top level', |
| 811 | ) |
| 812 | defaults = config.get('defaults', {}) |
| 813 | if not isinstance(defaults, dict): |
| 814 | errors.append('animations.json field "defaults" must be an object') |
| 815 | else: |
| 816 | errors.extend( |
| 817 | _unknown_field_errors( |
| 818 | defaults, |
| 819 | frozenset({'transition', 'animation'}), |
| 820 | 'defaults', |
| 821 | ) |
| 822 | ) |
| 823 | errors.extend(_animation_scope_errors(defaults, 'defaults')) |
| 824 | |
| 825 | slides = config.get('slides', {}) |
| 826 | if not isinstance(slides, dict): |
| 827 | errors.append('animations.json field "slides" must be an object') |
| 828 | return list(dict.fromkeys(errors)) |
| 829 | |
| 830 | for slide_name, slide_cfg in slides.items(): |
| 831 | if not isinstance(slide_cfg, dict): |
| 832 | errors.append(f'animations.json slide "{slide_name}" must be an object') |
| 833 | continue |
| 834 | errors.extend( |
| 835 | _unknown_field_errors( |
| 836 | slide_cfg, |
| 837 | frozenset({'transition', 'animation', 'groups', 'morph'}), |
| 838 | f'slide "{slide_name}"', |
| 839 | ) |
| 840 | ) |
| 841 | errors.extend( |
| 842 | _animation_scope_errors(slide_cfg, f'slide "{slide_name}"') |
| 843 | ) |
| 844 | errors.extend(_animation_group_errors(slide_name, slide_cfg)) |
| 845 | errors.extend(_resolved_animation_parameter_errors(config)) |
| 846 | return list(dict.fromkeys(errors)) |
| 847 | |
| 848 | |
| 849 | def _animation_scope_errors(scope: dict[str, Any], label: str) -> list[str]: |
| 850 | if 'animation' not in scope: |
| 851 | return [] |
| 852 | animation = scope['animation'] |
| 853 | if not isinstance(animation, dict): |
| 854 | return [f'animations.json {label} field "animation" must be an object'] |
| 855 | |
| 856 | errors = _unknown_field_errors( |
| 857 | animation, |
| 858 | frozenset({ |
| 859 | 'effect', |
| 860 | 'effect_options', |
| 861 | 'duration', |
| 862 | 'stagger', |
| 863 | 'trigger', |
| 864 | *ANIMATION_TIMING_OPTION_FIELDS, |
| 865 | 'after_effect', |
| 866 | 'sound', |
| 867 | }), |
| 868 | f'{label} animation', |
| 869 | ) |
| 870 | if 'effect' in animation: |
| 871 | effect_error = _animation_effect_error(animation['effect'], label) |
| 872 | if effect_error: |
| 873 | errors.append(effect_error) |
| 874 | |
| 875 | for field, allow_zero in (('duration', False), ('stagger', True)): |
| 876 | if field not in animation: |
| 877 | continue |
| 878 | try: |
| 879 | animation_seconds_to_milliseconds( |
| 880 | animation[field], |
| 881 | f'animations.json {label} animation {field}', |
| 882 | allow_zero=allow_zero, |
| 883 | ) |
| 884 | except ValueError as exc: |
| 885 | errors.append(str(exc)) |
| 886 | |
| 887 | if 'trigger' in animation: |
| 888 | trigger_error = _animation_trigger_error(animation['trigger'], label) |
| 889 | if trigger_error: |
| 890 | errors.append(trigger_error) |
| 891 | errors.extend( |
| 892 | _animation_parameter_errors( |
| 893 | animation, |
| 894 | f'{label} animation', |
| 895 | inherited_effect='auto', |
| 896 | ) |
| 897 | ) |
| 898 | return errors |
| 899 | |
| 900 | |
| 901 | def _animation_group_errors( |
| 902 | slide_name: object, |
| 903 | slide_cfg: dict[str, Any], |
| 904 | ) -> list[str]: |
| 905 | if 'groups' not in slide_cfg: |
| 906 | return [] |
| 907 | groups = slide_cfg['groups'] |
| 908 | if not isinstance(groups, dict): |
| 909 | return [ |
| 910 | f'animations.json slide "{slide_name}" field "groups" must be an object' |
| 911 | ] |
| 912 | |
| 913 | errors: list[str] = [] |
| 914 | for group_id, group_cfg in groups.items(): |
| 915 | path = ( |
| 916 | f'slides[{json.dumps(str(slide_name), ensure_ascii=False)}]' |
| 917 | f'.groups[{json.dumps(str(group_id), ensure_ascii=False)}]' |
| 918 | ) |
| 919 | if not isinstance(group_cfg, dict): |
| 920 | errors.append(f'animations.json {path} must be an object') |
| 921 | continue |
| 922 | |
| 923 | if 'effects' not in group_cfg: |
| 924 | errors.extend( |
| 925 | _animation_effect_entry_errors( |
| 926 | group_cfg, |
| 927 | path, |
| 928 | require_effect=False, |
| 929 | target_group_id=str(group_id), |
| 930 | ) |
| 931 | ) |
| 932 | continue |
| 933 | |
| 934 | extra_fields = sorted(set(group_cfg) - {'effects'}) |
| 935 | if extra_fields: |
| 936 | rendered = ', '.join(repr(field) for field in extra_fields) |
| 937 | errors.append( |
| 938 | f'animations.json {path} cannot combine "effects" with ' |
| 939 | f'other group-level field(s): {rendered}' |
| 940 | ) |
| 941 | effects = group_cfg['effects'] |
| 942 | if not isinstance(effects, list): |
| 943 | errors.append(f'animations.json {path}.effects must be an array') |
| 944 | continue |
| 945 | if not effects: |
| 946 | errors.append( |
| 947 | f'animations.json {path}.effects must contain at least one effect' |
| 948 | ) |
| 949 | continue |
| 950 | for index, effect_cfg in enumerate(effects): |
| 951 | effect_path = f'{path}.effects[{index}]' |
| 952 | if not isinstance(effect_cfg, dict): |
| 953 | errors.append( |
| 954 | f'animations.json {effect_path} must be an object' |
| 955 | ) |
| 956 | continue |
| 957 | errors.extend( |
| 958 | _animation_effect_entry_errors( |
| 959 | effect_cfg, |
| 960 | effect_path, |
| 961 | require_effect=True, |
| 962 | target_group_id=str(group_id), |
| 963 | ) |
| 964 | ) |
| 965 | return errors |
| 966 | |
| 967 | |
| 968 | def _animation_effect_entry_errors( |
| 969 | effect_cfg: dict[str, Any], |
| 970 | path: str, |
| 971 | *, |
| 972 | require_effect: bool, |
| 973 | target_group_id: str, |
| 974 | ) -> list[str]: |
| 975 | """Validate one legacy group block or one ``effects[]`` row.""" |
| 976 | errors = _unknown_field_errors( |
| 977 | effect_cfg, |
| 978 | _GROUP_EFFECT_FIELDS, |
| 979 | path, |
| 980 | ) |
| 981 | if require_effect and 'effect' not in effect_cfg: |
| 982 | errors.append(f'animations.json {path}.effect is required') |
| 983 | elif 'effect' in effect_cfg: |
| 984 | effect_error = _animation_effect_error(effect_cfg['effect'], path) |
| 985 | if effect_error: |
| 986 | errors.append(effect_error) |
| 987 | |
| 988 | for field, allow_zero in (('duration', False), ('delay', True)): |
| 989 | if field not in effect_cfg: |
| 990 | continue |
| 991 | try: |
| 992 | animation_seconds_to_milliseconds( |
| 993 | effect_cfg[field], |
| 994 | f'animations.json {path}.{field}', |
| 995 | allow_zero=allow_zero, |
| 996 | ) |
| 997 | except ValueError as exc: |
| 998 | errors.append(str(exc)) |
| 999 | |
| 1000 | if 'order' in effect_cfg: |
| 1001 | order = effect_cfg['order'] |
| 1002 | if isinstance(order, bool) or not isinstance(order, int) or order <= 0: |
| 1003 | errors.append( |
| 1004 | f'animations.json {path}.order must be a positive integer: ' |
| 1005 | f'{order!r}' |
| 1006 | ) |
| 1007 | |
| 1008 | if 'trigger' in effect_cfg: |
| 1009 | trigger_error = _animation_trigger_error(effect_cfg['trigger'], path) |
| 1010 | if trigger_error: |
| 1011 | errors.append(trigger_error) |
| 1012 | |
| 1013 | if 'trigger_shape' in effect_cfg: |
| 1014 | trigger_shape = effect_cfg['trigger_shape'] |
| 1015 | if not isinstance(trigger_shape, str) or not trigger_shape.strip(): |
| 1016 | errors.append( |
| 1017 | f'animations.json {path}.trigger_shape must be a ' |
| 1018 | f'non-empty group id: {trigger_shape!r}' |
| 1019 | ) |
| 1020 | elif trigger_shape == target_group_id: |
| 1021 | errors.append( |
| 1022 | f'animations.json {path}.trigger_shape must reference ' |
| 1023 | 'a different group' |
| 1024 | ) |
| 1025 | if effect_cfg.get('effect') == 'none': |
| 1026 | errors.append( |
| 1027 | f'animations.json {path}.trigger_shape cannot be used ' |
| 1028 | 'with effect "none"' |
| 1029 | ) |
| 1030 | if ( |
| 1031 | 'trigger' in effect_cfg |
| 1032 | and effect_cfg.get('trigger') != 'on-click' |
| 1033 | ): |
| 1034 | errors.append( |
| 1035 | f'animations.json {path}.trigger_shape requires ' |
| 1036 | 'trigger "on-click" when trigger is explicit' |
| 1037 | ) |
| 1038 | |
| 1039 | errors.extend( |
| 1040 | _animation_parameter_errors( |
| 1041 | effect_cfg, |
| 1042 | path, |
| 1043 | inherited_effect='auto', |
| 1044 | ) |
| 1045 | ) |
| 1046 | return errors |
| 1047 | |
| 1048 | |
| 1049 | def _bounce_support_error( |
| 1050 | animation: dict[str, Any], |
| 1051 | label: str, |
| 1052 | ) -> str | None: |
| 1053 | """Return a writer-equivalent bounce support error for one resolved scope.""" |
| 1054 | bounce_end = animation.get('bounce_end') |
| 1055 | if ( |
| 1056 | isinstance(bounce_end, bool) |
| 1057 | or not isinstance(bounce_end, (int, float)) |
| 1058 | or not math.isfinite(float(bounce_end)) |
| 1059 | or float(bounce_end) <= 0 |
| 1060 | ): |
| 1061 | return None |
| 1062 | try: |
| 1063 | effect, options = normalize_animation_effect_request( |
| 1064 | animation.get('effect', 'auto'), |
| 1065 | animation.get('effect_options'), |
| 1066 | allow_none=True, |
| 1067 | allow_modes=True, |
| 1068 | ) |
| 1069 | except ValueError: |
| 1070 | return None |
| 1071 | if effect is None or effect in ANIMATION_MODES: |
| 1072 | return None |
| 1073 | if animation_effect_supports_bounce_end(effect, options): |
| 1074 | return None |
| 1075 | return ( |
| 1076 | f'animations.json {label} effect {effect!r} has no behavior that ' |
| 1077 | 'supports bounce_end' |
| 1078 | ) |
| 1079 | |
| 1080 | |
| 1081 | def _resolved_animation_parameter_errors(config: dict[str, Any]) -> list[str]: |
| 1082 | """Validate effective animation parameters after sidecar inheritance.""" |
| 1083 | defaults = config.get('defaults', {}) |
| 1084 | default_animation: dict[str, Any] = {'effect': 'none'} |
| 1085 | if isinstance(defaults, dict): |
| 1086 | value = defaults.get('animation', {}) |
| 1087 | if isinstance(value, dict): |
| 1088 | default_animation = resolve_slide_animation_config( |
| 1089 | default_animation, |
| 1090 | value, |
| 1091 | ) |
| 1092 | |
| 1093 | errors: list[str] = [] |
| 1094 | default_error = _bounce_support_error(default_animation, 'defaults animation') |
| 1095 | if default_error: |
| 1096 | errors.append(default_error) |
| 1097 | |
| 1098 | slides = config.get('slides', {}) |
| 1099 | if not isinstance(slides, dict): |
| 1100 | return errors |
| 1101 | for slide_name, slide_cfg in slides.items(): |
| 1102 | if not isinstance(slide_cfg, dict): |
| 1103 | continue |
| 1104 | slide_value = slide_cfg.get('animation', {}) |
| 1105 | if not isinstance(slide_value, dict): |
| 1106 | continue |
| 1107 | slide_animation = resolve_slide_animation_config( |
| 1108 | default_animation, |
| 1109 | slide_value, |
| 1110 | ) |
| 1111 | if _INHERITANCE_SENSITIVE_ANIMATION_FIELDS & set(slide_value): |
| 1112 | errors.extend( |
| 1113 | _animation_parameter_errors( |
| 1114 | slide_animation, |
| 1115 | f'slide "{slide_name}" animation', |
| 1116 | inherited_effect='auto', |
| 1117 | ) |
| 1118 | ) |
| 1119 | error = _bounce_support_error( |
| 1120 | slide_animation, |
| 1121 | f'slide "{slide_name}" animation', |
| 1122 | ) |
| 1123 | if error: |
| 1124 | errors.append(error) |
| 1125 | |
| 1126 | groups = slide_cfg.get('groups', {}) |
| 1127 | if not isinstance(groups, dict): |
| 1128 | continue |
| 1129 | for group_id, group_cfg in groups.items(): |
| 1130 | if not isinstance(group_cfg, dict): |
| 1131 | continue |
| 1132 | path = ( |
| 1133 | f'slides[{json.dumps(str(slide_name), ensure_ascii=False)}]' |
| 1134 | f'.groups[{json.dumps(str(group_id), ensure_ascii=False)}]' |
| 1135 | ) |
| 1136 | try: |
| 1137 | effect_entries = animation_group_effect_entries( |
| 1138 | group_cfg, |
| 1139 | path=path, |
| 1140 | ) |
| 1141 | except ValueError: |
| 1142 | continue |
| 1143 | for effect_path, effect_cfg in effect_entries: |
| 1144 | if not ( |
| 1145 | _INHERITANCE_SENSITIVE_ANIMATION_FIELDS |
| 1146 | & set(effect_cfg) |
| 1147 | ): |
| 1148 | continue |
| 1149 | inherited_group_animation = { |
| 1150 | field: slide_animation[field] |
| 1151 | for field in ( |
| 1152 | 'effect', |
| 1153 | 'effect_options', |
| 1154 | 'duration', |
| 1155 | *ANIMATION_TIMING_OPTION_FIELDS, |
| 1156 | 'after_effect', |
| 1157 | 'sound', |
| 1158 | ) |
| 1159 | if field in slide_animation |
| 1160 | } |
| 1161 | group_animation = resolve_slide_animation_config( |
| 1162 | inherited_group_animation, |
| 1163 | effect_cfg, |
| 1164 | ) |
| 1165 | errors.extend( |
| 1166 | _animation_parameter_errors( |
| 1167 | group_animation, |
| 1168 | effect_path, |
| 1169 | inherited_effect='none', |
| 1170 | ) |
| 1171 | ) |
| 1172 | error = _bounce_support_error( |
| 1173 | group_animation, |
| 1174 | effect_path, |
| 1175 | ) |
| 1176 | if error: |
| 1177 | errors.append(error) |
| 1178 | return errors |
| 1179 | |
| 1180 | |
| 1181 | def _declared_animation_sounds( |
| 1182 | config: dict[str, Any], |
| 1183 | ) -> tuple[tuple[str, object], ...]: |
| 1184 | """Return explicitly declared sidecar sound values with scope labels.""" |
| 1185 | sounds: list[tuple[str, object]] = [] |
| 1186 | defaults = config.get('defaults', {}) |
| 1187 | if isinstance(defaults, dict): |
| 1188 | animation = defaults.get('animation', {}) |
| 1189 | if isinstance(animation, dict) and 'sound' in animation: |
| 1190 | sounds.append(('defaults animation', animation['sound'])) |
| 1191 | |
| 1192 | slides = config.get('slides', {}) |
| 1193 | if not isinstance(slides, dict): |
| 1194 | return tuple(sounds) |
| 1195 | for slide_name, slide_cfg in slides.items(): |
| 1196 | if not isinstance(slide_cfg, dict): |
| 1197 | continue |
| 1198 | animation = slide_cfg.get('animation', {}) |
| 1199 | if isinstance(animation, dict) and 'sound' in animation: |
| 1200 | sounds.append((f'slide "{slide_name}" animation', animation['sound'])) |
| 1201 | groups = slide_cfg.get('groups', {}) |
| 1202 | if not isinstance(groups, dict): |
| 1203 | continue |
| 1204 | for group_id, group_cfg in groups.items(): |
| 1205 | if not isinstance(group_cfg, dict): |
| 1206 | continue |
| 1207 | path = ( |
| 1208 | f'slides[{json.dumps(str(slide_name), ensure_ascii=False)}]' |
| 1209 | f'.groups[{json.dumps(str(group_id), ensure_ascii=False)}]' |
| 1210 | ) |
| 1211 | try: |
| 1212 | effect_entries = animation_group_effect_entries( |
| 1213 | group_cfg, |
| 1214 | path=path, |
| 1215 | ) |
| 1216 | except ValueError: |
| 1217 | continue |
| 1218 | for effect_path, effect_cfg in effect_entries: |
| 1219 | if 'sound' in effect_cfg: |
| 1220 | sounds.append((effect_path, effect_cfg['sound'])) |
| 1221 | return tuple(sounds) |
| 1222 | |
| 1223 | |
| 1224 | def _animation_sound_path_errors( |
| 1225 | project_path: Path, |
| 1226 | config: dict[str, Any], |
| 1227 | ) -> list[str]: |
| 1228 | """Validate declared animation sound files against the project root.""" |
| 1229 | errors: list[str] = [] |
| 1230 | project_root = project_path.resolve() |
| 1231 | for label, raw_sound in _declared_animation_sounds(config): |
| 1232 | if not isinstance(raw_sound, str) or not raw_sound.strip(): |
| 1233 | continue |
| 1234 | sound_path = Path(raw_sound) |
| 1235 | if sound_path.suffix.lower() not in AUDIO_CONTENT_TYPES: |
| 1236 | errors.append( |
| 1237 | f'animations.json {label} sound must use .m4a, .mp3, or .wav' |
| 1238 | ) |
| 1239 | continue |
| 1240 | if not sound_path.is_absolute(): |
| 1241 | sound_path = project_root / sound_path |
| 1242 | sound_path = sound_path.resolve() |
| 1243 | if not sound_path.exists(): |
| 1244 | errors.append( |
| 1245 | f'animations.json {label} sound file not found: {sound_path}' |
| 1246 | ) |
| 1247 | elif not sound_path.is_file(): |
| 1248 | errors.append( |
| 1249 | f'animations.json {label} sound path is not a regular file: ' |
| 1250 | f'{sound_path}' |
| 1251 | ) |
| 1252 | return errors |
| 1253 | |
| 1254 | |
| 1255 | def validate_animation_config( |
| 1256 | project_path: Path, |
| 1257 | config: dict[str, Any] | None = None, |
| 1258 | config_path: str | None = None, |
| 1259 | *, |
| 1260 | svg_files: list[Path] | None = None, |
| 1261 | ) -> list[str]: |
| 1262 | """Return sidecar-reference diagnostics for the selected SVG slides. |
| 1263 | |
| 1264 | Fatal field/type/value checks are owned by |
| 1265 | :func:`validate_animation_config_errors`. Anonymous groups are warnings; |
| 1266 | references to invalid sound files, missing slides/groups, and structural |
| 1267 | targets are fatal at export call sites. Slides omitted from a sparse |
| 1268 | sidecar inherit defaults. |
| 1269 | """ |
| 1270 | if config is None: |
| 1271 | config = load_animation_config(project_path, config_path) |
| 1272 | if not config: |
| 1273 | return [] |
| 1274 | |
| 1275 | warnings = _animation_sound_path_errors(project_path, config) |
| 1276 | targets_by_slide, anonymous_groups = scan_project_targets( |
| 1277 | project_path, |
| 1278 | svg_files=svg_files, |
| 1279 | ) |
| 1280 | for item in anonymous_groups: |
| 1281 | warnings.append(f'{item} has no id and cannot be customized in animations.json') |
| 1282 | |
| 1283 | duplicates_by_slide: dict[str, tuple[str, ...]] = {} |
| 1284 | for slide_name, targets in targets_by_slide.items(): |
| 1285 | duplicates = _duplicate_target_ids(targets) |
| 1286 | if duplicates: |
| 1287 | duplicates_by_slide[slide_name] = duplicates |
| 1288 | for slide_name, duplicates in duplicates_by_slide.items(): |
| 1289 | warnings.append(_duplicate_target_error(slide_name, duplicates)) |
| 1290 | |
| 1291 | known_slides = set(targets_by_slide) |
| 1292 | known_groups_by_slide: dict[str, dict[str, GroupTarget]] = {} |
| 1293 | for slide_name, slide_targets in targets_by_slide.items(): |
| 1294 | ambiguous_ids = set(duplicates_by_slide.get(slide_name, ())) |
| 1295 | known_groups_by_slide[slide_name] = { |
| 1296 | target.group_id: target |
| 1297 | for target in slide_targets |
| 1298 | if target.group_id not in ambiguous_ids |
| 1299 | } |
| 1300 | default_animation: dict[str, Any] = {'effect': 'none'} |
| 1301 | defaults = config.get('defaults', {}) |
| 1302 | if isinstance(defaults, dict): |
| 1303 | animation_value = defaults.get('animation', {}) |
| 1304 | if isinstance(animation_value, dict): |
| 1305 | default_animation = resolve_slide_animation_config( |
| 1306 | default_animation, |
| 1307 | animation_value, |
| 1308 | ) |
| 1309 | slides = config.get('slides', {}) |
| 1310 | if not isinstance(slides, dict): |
| 1311 | return list(dict.fromkeys(warnings)) |
| 1312 | for slide_name, slide_cfg in slides.items(): |
| 1313 | if slide_name not in known_slides: |
| 1314 | warnings.append(f'animations.json references missing slide: {slide_name}') |
| 1315 | continue |
| 1316 | if not isinstance(slide_cfg, dict): |
| 1317 | continue |
| 1318 | |
| 1319 | slide_animation = default_animation |
| 1320 | animation_value = slide_cfg.get('animation', {}) |
| 1321 | if isinstance(animation_value, dict): |
| 1322 | slide_animation = resolve_slide_animation_config( |
| 1323 | default_animation, |
| 1324 | animation_value, |
| 1325 | ) |
| 1326 | slide_targets = targets_by_slide.get(slide_name, []) |
| 1327 | duplicate_ids = duplicates_by_slide.get(slide_name, ()) |
| 1328 | ambiguous_ids = set(duplicate_ids) |
| 1329 | known_groups = known_groups_by_slide.get(slide_name, {}) |
| 1330 | groups = slide_cfg.get('groups', {}) |
| 1331 | if not isinstance(groups, dict): |
| 1332 | continue |
| 1333 | for group_id, group_cfg in groups.items(): |
| 1334 | path = ( |
| 1335 | f'slides[{json.dumps(str(slide_name), ensure_ascii=False)}]' |
| 1336 | f'.groups[{json.dumps(str(group_id), ensure_ascii=False)}]' |
| 1337 | ) |
| 1338 | if group_id in ambiguous_ids: |
| 1339 | continue |
| 1340 | if group_id not in known_groups: |
| 1341 | warnings.append( |
| 1342 | f'animations.json {path} references a missing group' |
| 1343 | ) |
| 1344 | continue |
| 1345 | target = known_groups[group_id] |
| 1346 | if not isinstance(group_cfg, dict): |
| 1347 | continue |
| 1348 | try: |
| 1349 | effect_entries = animation_group_effect_entries( |
| 1350 | group_cfg, |
| 1351 | path=path, |
| 1352 | ) |
| 1353 | except ValueError: |
| 1354 | continue |
| 1355 | if ( |
| 1356 | target.structurally_static |
| 1357 | and any( |
| 1358 | normalize_animation_effect( |
| 1359 | effect_cfg.get( |
| 1360 | 'effect', |
| 1361 | slide_animation.get('effect', 'none'), |
| 1362 | ), |
| 1363 | allow_none=True, |
| 1364 | allow_modes=True, |
| 1365 | ) |
| 1366 | is not None |
| 1367 | for _effect_path, effect_cfg in effect_entries |
| 1368 | ) |
| 1369 | ): |
| 1370 | warnings.append( |
| 1371 | f'animations.json {path} references a non-animatable ' |
| 1372 | 'structural group' |
| 1373 | ) |
| 1374 | for effect_path, effect_cfg in effect_entries: |
| 1375 | trigger_shape = effect_cfg.get('trigger_shape') |
| 1376 | if ( |
| 1377 | not isinstance(trigger_shape, str) |
| 1378 | or not trigger_shape.strip() |
| 1379 | ): |
| 1380 | continue |
| 1381 | if trigger_shape in ambiguous_ids: |
| 1382 | warnings.append( |
| 1383 | f'animations.json {effect_path}.trigger_shape ' |
| 1384 | f'references ambiguous group {trigger_shape!r}' |
| 1385 | ) |
| 1386 | continue |
| 1387 | trigger_target = known_groups.get(trigger_shape) |
| 1388 | if trigger_target is None: |
| 1389 | warnings.append( |
| 1390 | f'animations.json {effect_path}.trigger_shape ' |
| 1391 | f'references missing group {trigger_shape!r}' |
| 1392 | ) |
| 1393 | elif trigger_target.structurally_static: |
| 1394 | warnings.append( |
| 1395 | f'animations.json {effect_path}.trigger_shape ' |
| 1396 | f'references non-triggerable structural group ' |
| 1397 | f'{trigger_shape!r}' |
| 1398 | ) |
| 1399 | |
| 1400 | morph_pairs, morph_errors = _resolve_morph_pairs( |
| 1401 | list(targets_by_slide), |
| 1402 | config, |
| 1403 | ) |
| 1404 | warnings.extend(morph_errors) |
| 1405 | for pair in morph_pairs: |
| 1406 | for slide_name, group_id in ( |
| 1407 | (pair.source_slide, pair.source_group_id), |
| 1408 | (pair.destination_slide, pair.destination_group_id), |
| 1409 | ): |
| 1410 | target = known_groups_by_slide.get(slide_name, {}).get(group_id) |
| 1411 | if target is None: |
| 1412 | warnings.append( |
| 1413 | 'animations.json Morph references missing or ambiguous group: ' |
| 1414 | f'{slide_name}/{group_id}' |
| 1415 | ) |
| 1416 | elif target.structurally_static: |
| 1417 | warnings.append( |
| 1418 | 'animations.json Morph references structural group: ' |
| 1419 | f'{slide_name}/{group_id}' |
| 1420 | ) |
| 1421 | return list(dict.fromkeys(warnings)) |
| 1422 | |
| 1423 | |
| 1424 | def build_scaffold(project_path: Path) -> dict[str, Any]: |
| 1425 | """Build an editable animation override scaffold from current SVGs. |
| 1426 | |
| 1427 | Chrome groups are omitted — layer/slide-number placeholder semantics are |
| 1428 | authoritative, followed by an explicit structural role. ``is_chrome_id`` |
| 1429 | remains only for marker-free legacy SVGs. Listing static page framing in |
| 1430 | the scaffold would be pure noise. A ``defaults`` stub is emitted up front |
| 1431 | to remind the editor that deck-wide overrides exist and most pages should |
| 1432 | inherit them. |
| 1433 | """ |
| 1434 | transition_defaults = {'effect': 'fade', 'duration': 0.4} |
| 1435 | animation_defaults = { |
| 1436 | 'effect': 'none', |
| 1437 | 'duration': 0.4, |
| 1438 | 'stagger': 0.5, |
| 1439 | 'trigger': 'after-previous', |
| 1440 | } |
| 1441 | targets_by_slide, _anonymous = scan_project_targets(project_path) |
| 1442 | slides: dict[str, Any] = {} |
| 1443 | for slide_name, targets in targets_by_slide.items(): |
| 1444 | _require_unique_target_ids(slide_name, targets) |
| 1445 | groups: dict[str, Any] = {} |
| 1446 | for target in targets: |
| 1447 | if target.chrome: |
| 1448 | continue |
| 1449 | groups[target.group_id] = {} |
| 1450 | slides[slide_name] = { |
| 1451 | 'transition': dict(transition_defaults), |
| 1452 | 'animation': dict(animation_defaults), |
| 1453 | 'groups': groups, |
| 1454 | } |
| 1455 | return { |
| 1456 | 'version': 1, |
| 1457 | 'defaults': { |
| 1458 | 'transition': transition_defaults, |
| 1459 | 'animation': animation_defaults, |
| 1460 | }, |
| 1461 | 'slides': slides, |
| 1462 | } |
| 1463 | |
| 1464 | |
| 1465 | def build_group_listing(project_path: Path) -> tuple[list[str], list[str]]: |
| 1466 | """Return one compact line per slide: ``<slide>: id1, id2, id3``. |
| 1467 | |
| 1468 | Chrome groups are excluded — matches ``build_scaffold``'s policy so the |
| 1469 | listing reflects exactly what an editor can override. Returns |
| 1470 | ``(lines, anonymous_warnings)``. |
| 1471 | """ |
| 1472 | targets_by_slide, anonymous = scan_project_targets(project_path) |
| 1473 | lines: list[str] = [] |
| 1474 | for slide_name, targets in targets_by_slide.items(): |
| 1475 | _require_unique_target_ids(slide_name, targets) |
| 1476 | ids = [t.group_id for t in targets if not t.chrome] |
| 1477 | if not ids: |
| 1478 | lines.append(f'{slide_name}: (no animatable groups)') |
| 1479 | else: |
| 1480 | lines.append(f'{slide_name}: {", ".join(ids)}') |
| 1481 | return lines, anonymous |
| 1482 | |
| 1483 | |
| 1484 | def write_scaffold( |
| 1485 | project_path: Path, |
| 1486 | output_path: str | None = None, |
| 1487 | *, |
| 1488 | force: bool = False, |
| 1489 | ) -> Path: |
| 1490 | """Write ``animations.json`` scaffold and return its path.""" |
| 1491 | if output_path: |
| 1492 | path = Path(output_path) |
| 1493 | else: |
| 1494 | path = default_config_path(project_path) |
| 1495 | if output_path and not path.is_absolute(): |
| 1496 | path = project_path / path |
| 1497 | if path.exists() and not force: |
| 1498 | raise FileExistsError(f'Animation config already exists: {path}') |
| 1499 | |
| 1500 | scaffold = build_scaffold(project_path) |
| 1501 | path.write_text( |
| 1502 | json.dumps(scaffold, ensure_ascii=False, indent=2) + '\n', |
| 1503 | encoding='utf-8', |
| 1504 | ) |
| 1505 | return path |
| 1506 |