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: SVG 可视化编辑器,支持元素级批注标注 (#81)
Dongjie Wucc053506fb03
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.mdindex 3ff4fbbf..88c78b60 100644--- a/skills/ppt-master/SKILL.md+++ b/skills/ppt-master/SKILL.md@@ -336,6 +336,39 @@ Full effect list, anchor logic, and limits: [`references/animations.md`](referen> ❌ **NEVER** export from `svg_output/` — MUST use `-s final` (exports from `svg_final/`)> ❌ **NEVER** use `--only` (it suppresses one of the two output files)+**Step 7.4: SVG Editor — MUST execute**++After PPTX export, **MUST** start the SVG editor for the user:++```bash+python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --no-browser+```++Then tell the user:+> SVG 编辑器已启动,请在浏览器打开: http://localhost:5000+> 在浏览器中选择元素并添加批注,完成后在编辑器中点击"保存",然后回来告诉我。++**❌ NEVER skip Step 7.4.** After PPTX export, always start the editor. Do not ask the user whether they want it — just start it. The user decides whether to use it or ignore it.++**Edit Loop (When User Requests Annotation-Based Editing):**++When the user indicates they have submitted annotations (e.g. "已提交标注", "标注好了", "继续修改", "根据标注改", "帮我改", "改好了", or any similar intent — do NOT require exact wording, recognize the user's intent to have AI read and apply the saved annotations):++1. The server will have auto-shut down after the user saved (port is released). If it's still running, kill it.+2. Run `python3 ${SKILL_DIR}/scripts/check_annotations.py <project_path>` to discover annotations+3. If no annotations found, inform the user and stop+4. Read each annotated SVG file from `svg_output/`+5. For each annotation: modify the target SVG element per the user's instruction+6. Remove `data-edit-target` and `data-edit-annotation` attributes from modified elements+7. Remove temporary `_edit_N` id attributes from elements that did not have a user-assigned id originally+8. Re-run Step 7 post-processing: `finalize_svg.py` → `svg_to_pptx.py`+9. Re-start the SVG editor server:+ ```bash+ python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --no-browser+ ```+10. Tell the user: "标注已处理,PPT 已更新。编辑器已重启: http://localhost:5000 。无需标注时告诉我即可。"+11. Wait for the user's next message. If they indicate they are done (e.g. "好了", "可以了", "不需要了", "结束"), the editing loop ends. If they submit more annotations, return to step 1.+---## Role Switching Protocoldiff --git a/skills/ppt-master/requirements.txt b/skills/ppt-master/requirements.txtindex 83fde5bc..1259c053 100644--- a/skills/ppt-master/requirements.txt+++ b/skills/ppt-master/requirements.txt@@ -102,3 +102,10 @@ curl_cffi>=0.7.0google-genai>=1.0.0# OpenAI-compatible backend / OpenAI 兼容后端 (IMAGE_BACKEND=openai)openai>=1.0.0++# ─────────────────────────────────────────────────────────────+# SVG Editor / SVG 编辑器 (skills/ppt-master/scripts/svg_editor/server.py)+# ─────────────────────────────────────────────────────────────+# Localhost web editor for annotating SVG elements with edit instructions.+# 本地 Web 编辑器,用于在 SVG 元素上添加编辑标注指令+flask>=3.0.0diff --git a/skills/ppt-master/scripts/check_annotations.py b/skills/ppt-master/scripts/check_annotations.pynew file mode 100644index 00000000..d00ba347--- /dev/null+++ b/skills/ppt-master/scripts/check_annotations.py@@ -0,0 +1,126 @@+#!/usr/bin/env python3+"""+PPT Master - SVG Annotation Checker++Scans SVG files for edit annotations (data-edit-target / data-edit-annotation attributes)+and prints a human-readable summary. Used by AI agents to discover pending annotations.++Usage:+ python3 scripts/check_annotations.py <project_dir>+ python3 scripts/check_annotations.py <svg_file>++Examples:+ python3 scripts/check_annotations.py projects/my-project+ python3 scripts/check_annotations.py projects/my-project/svg_output/slide_01.svg++Dependencies:+ None (only uses standard library)+"""++import argparse+import sys+import xml.etree.ElementTree as ET+from pathlib import Path+from typing import Optional+++def scan_svg_file(svg_path: Path) -> list[dict]:+ """Scan a single SVG file for edit annotations."""+ try:+ tree = ET.parse(svg_path)+ except ET.ParseError:+ return []++ root = tree.getroot()+ annotations = []++ for elem in root.iter():+ if elem.get('data-edit-target') == 'true':+ tag = elem.tag+ if '}' in tag:+ tag = tag.split('}', 1)[1]++ content_preview = ''+ if tag == 'text' and elem.text:+ content_preview = elem.text.strip()[:50]++ annotations.append({+ 'element_id': elem.get('id', '(no id)'),+ 'tag': tag,+ 'annotation': elem.get('data-edit-annotation', ''),+ 'content_preview': content_preview,+ })++ return annotations+++def scan_directory(dir_path: Path) -> dict[str, list[dict]]:+ """Scan all SVG files in svg_output/ for edit annotations."""+ svg_dir = dir_path / 'svg_output'+ if not svg_dir.exists():+ return {}++ results = {}+ for svg_file in sorted(svg_dir.glob('*.svg')):+ annotations = scan_svg_file(svg_file)+ if annotations:+ results[svg_file.name] = annotations++ return results+++def print_results(results: dict[str, list[dict]]) -> None:+ """Print annotation results in human-readable format."""+ if not results:+ print("[OK] No annotations found.")+ return++ total = sum(len(anns) for anns in results.values())+ file_count = len(results)+ ann_word = "annotation" if total == 1 else "annotations"+ file_word = "file" if file_count == 1 else "files"+ print(f"Found {total} {ann_word} in {file_count} {file_word}:\n")++ for filename, annotations in results.items():+ print(f"{filename}")+ for i, ann in enumerate(annotations, 1):+ content = f' "{ann["content_preview"]}"' if ann['content_preview'] else ''+ print(f" [{i}] <{ann['tag']} id=\"{ann['element_id']}\">{content}")+ print(f" → {ann['annotation']}")+ print()+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description='Check SVG files for edit annotations',+ formatter_class=argparse.RawDescriptionHelpFormatter,+ )+ parser.add_argument('path', help='Project directory or single SVG file path')+ return parser+++def main(argv: Optional[list[str]] = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)++ target = Path(args.path).resolve()++ if not target.exists():+ print(f"Error: Path not found: {target}", file=sys.stderr)+ return 1++ if target.is_file() and target.suffix == '.svg':+ annotations = scan_svg_file(target)+ results = {target.name: annotations} if annotations else {}+ elif target.is_dir():+ results = scan_directory(target)+ else:+ print(f"Error: Expected a project directory or .svg file, got: {target}", file=sys.stderr)+ return 1++ print_results(results)+ return 0+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/skills/ppt-master/scripts/svg_editor/__init__.py b/skills/ppt-master/scripts/svg_editor/__init__.pynew file mode 100644index 00000000..43dad892--- /dev/null+++ b/skills/ppt-master/scripts/svg_editor/__init__.py@@ -0,0 +1,2 @@+#!/usr/bin/env python3+"""SVG Editor subpackage for ppt-master — annotation read/write utilities and web server."""diff --git a/skills/ppt-master/scripts/svg_editor/annotations.py b/skills/ppt-master/scripts/svg_editor/annotations.pynew file mode 100644index 00000000..103e2713--- /dev/null+++ b/skills/ppt-master/scripts/svg_editor/annotations.py@@ -0,0 +1,83 @@+#!/usr/bin/env python3+"""+PPT Master - SVG Annotation Utilities++Read, write, and manage edit annotations in SVG files.+Annotations are stored as custom XML attributes (data-edit-target, data-edit-annotation)+on SVG elements, enabling AI-driven targeted editing.++Usage:+ (library module — imported by server.py and check_annotations.py)++Dependencies:+ None (only uses standard library)+"""++import xml.etree.ElementTree as ET+from typing import Optional++SVG_NS = 'http://www.w3.org/2000/svg'++# Register namespace to avoid ns0: prefix in output+ET.register_namespace('', SVG_NS)+++def assign_temp_ids(root: ET.Element) -> None:+ """Assign deterministic temp ids (_edit_0, _edit_1, ...) to elements without one.++ Clears any leftover _edit_N ids from previous sessions first, to avoid+ shifted numbering when elements are added/removed between sessions.+ """+ for elem in root.iter():+ eid = elem.get('id', '')+ if eid.startswith('_edit_'):+ elem.attrib.pop('id', None)++ counter = 0+ for elem in root.iter():+ if elem is root:+ continue+ if elem.get('id') is None:+ elem.set('id', f'_edit_{counter}')+ counter += 1+++def _find_by_id(root: ET.Element, element_id: str) -> Optional[ET.Element]:+ """Find an element by its id attribute in the SVG tree."""+ for elem in root.iter():+ if elem.get('id') == element_id:+ return elem+ return None+++def parse_annotations(root: ET.Element) -> list[dict]:+ """Extract all annotations from an SVG element tree."""+ annotations = []+ for elem in root.iter():+ if elem.get('data-edit-target') == 'true':+ annotations.append({+ 'element_id': elem.get('id', ''),+ 'tag': elem.tag.split('}', 1)[1] if '}' in elem.tag else elem.tag,+ 'annotation': elem.get('data-edit-annotation', ''),+ })+ return annotations+++def set_annotation(root: ET.Element, element_id: str, annotation: str) -> bool:+ """Add or update an annotation on an SVG element. Returns True if found."""+ elem = _find_by_id(root, element_id)+ if elem is None:+ return False+ elem.set('data-edit-target', 'true')+ elem.set('data-edit-annotation', annotation)+ return True+++def remove_annotation(root: ET.Element, element_id: str) -> bool:+ """Remove annotation attributes from an SVG element. Returns True if found."""+ elem = _find_by_id(root, element_id)+ if elem is None:+ return False+ elem.attrib.pop('data-edit-target', None)+ elem.attrib.pop('data-edit-annotation', None)+ return Truediff --git a/skills/ppt-master/scripts/svg_editor/server.py b/skills/ppt-master/scripts/svg_editor/server.pynew file mode 100644index 00000000..35f0d7c5--- /dev/null+++ b/skills/ppt-master/scripts/svg_editor/server.py@@ -0,0 +1,290 @@+#!/usr/bin/env python3+"""+PPT Master - SVG Editor Server++Flask backend for the SVG annotation editor.+Serves the web UI and provides API endpoints for reading/writing SVG annotations.++Usage:+ python3 scripts/svg_editor/server.py <project_dir>++Examples:+ python3 scripts/svg_editor/server.py projects/my-project+ python3 scripts/svg_editor/server.py projects/my-project --port 8080++Dependencies:+ flask>=3.0.0+"""++import argparse+import os+import sys+import threading+import time+import webbrowser+import xml.etree.ElementTree as ET+from pathlib import Path+from typing import Optional++from flask import Flask, jsonify, request, send_from_directory++# Local — sys.path injection for sibling module (code-style.md §3)+_SCRIPTS_DIR = Path(__file__).resolve().parent+if str(_SCRIPTS_DIR) not in sys.path:+ sys.path.insert(0, str(_SCRIPTS_DIR))++from annotations import ( # noqa: E402+ assign_temp_ids,+ parse_annotations,+ set_annotation,+ remove_annotation,+)+++def create_app(project_dir: str, idle_timeout: int = 900) -> Flask:+ """Create and configure the Flask app for a given project directory."""+ project_path = Path(project_dir).resolve()+ svg_dir = project_path / 'svg_output'++ app = Flask(__name__, static_folder='static', static_url_path='/static')+ app.config['PROJECT_PATH'] = project_path+ app.config['SVG_DIR'] = svg_dir++ # In-memory annotation store: {filename: {element_id: annotation_text}}+ app.config['ANNOTATIONS'] = {}++ # Idle timeout: auto-shutdown if no one connects within idle_timeout seconds+ app.config['LAST_REQUEST_TIME'] = time.time()++ @app.before_request+ def _update_activity():+ app.config['LAST_REQUEST_TIME'] = time.time()++ def _idle_watchdog():+ while True:+ time.sleep(10)+ elapsed = time.time() - app.config['LAST_REQUEST_TIME']+ if elapsed > idle_timeout:+ print(f"SVG Editor idle for {idle_timeout}s, shutting down.")+ # os._exit: Flask dev server has no clean shutdown mechanism;+ # data is safe because idle timeout only fires when no requests are in flight.+ os._exit(0)++ watchdog = threading.Thread(target=_idle_watchdog, daemon=True)+ watchdog.start()++ @app.route('/api/shutdown', methods=['POST'])+ def shutdown():+ def _stop():+ time.sleep(0.5) # Let HTTP response flush before killing the process+ print("SVG Editor shutting down (user saved annotations).")+ # os._exit: save-all already wrote to disk; 0.5s delay ensures response is sent.+ os._exit(0)+ threading.Thread(target=_stop, daemon=True).start()+ return jsonify({'status': 'ok'})++ @app.route('/')+ def index():+ return send_from_directory(app.static_folder, 'index.html')++ @app.route('/api/slides')+ def get_slides():+ svg_dir = app.config['SVG_DIR']+ if not svg_dir.exists():+ return jsonify({'slides': []})++ annotations = app.config['ANNOTATIONS']+ slides = []+ for svg_file in sorted(svg_dir.glob('*.svg')):+ has_disk_anns = False+ try:+ tree = ET.parse(str(svg_file))+ for elem in tree.getroot().iter():+ if elem.get('data-edit-target') == 'true':+ has_disk_anns = True+ break+ except ET.ParseError:+ pass++ has_mem_anns = svg_file.name in annotations and len(annotations[svg_file.name]) > 0++ slides.append({+ 'name': svg_file.name,+ 'annotated': has_disk_anns or has_mem_anns,+ 'annotation_count': len(annotations.get(svg_file.name, {})),+ })++ return jsonify({'slides': slides})++ def _safe_svg_path(name: str):+ """Validate slide name and return safe path. Returns None if invalid.++ The early string checks reject obvious bad inputs; the resolve()+startswith()+ check is the authoritative path traversal guard.+ """+ if '/' in name or '\\' in name or '..' in name:+ return None+ svg_file = (svg_dir / name).resolve()+ if not str(svg_file).startswith(str(svg_dir.resolve())):+ return None+ return svg_file++ @app.route('/api/slide/<name>')+ def get_slide(name: str):+ svg_file = _safe_svg_path(name)+ if svg_file is None:+ return jsonify({'error': 'Invalid slide name'}), 400+ if not svg_file.exists():+ return jsonify({'error': 'Slide not found'}), 404++ try:+ tree = ET.parse(str(svg_file))+ root = tree.getroot()+ except ET.ParseError as e:+ return jsonify({'error': f'Failed to parse SVG: {e}'}), 500++ assign_temp_ids(root)++ disk_annotations = parse_annotations(root)++ mem_annotations = app.config['ANNOTATIONS'].get(name, {})+ merged = {}+ for ann in disk_annotations:+ merged[ann['element_id']] = ann['annotation']+ merged.update(mem_annotations)++ annotations_list = []+ for elem in root.iter():+ eid = elem.get('id')+ if eid and eid in merged:+ tag = elem.tag+ if '}' in tag:+ tag = tag.split('}', 1)[1]+ annotations_list.append({+ 'element_id': eid,+ 'tag': tag,+ 'annotation': merged[eid],+ })++ content = ET.tostring(root, encoding='unicode', xml_declaration=False)++ return jsonify({+ 'name': name,+ 'content': content,+ 'annotations': annotations_list,+ })++ @app.route('/api/slide/<name>/annotate', methods=['POST'])+ def post_annotate(name: str):+ data = request.get_json()+ if not data or 'element_id' not in data or 'annotation' not in data:+ return jsonify({'error': 'Missing element_id or annotation'}), 400++ element_id = data['element_id']+ annotation = data['annotation']++ if not isinstance(element_id, str) or not isinstance(annotation, str):+ return jsonify({'error': 'element_id and annotation must be strings'}), 400++ if len(element_id) > 200:+ return jsonify({'error': 'element_id too long (max 200 chars)'}), 400++ if len(annotation) > 10000:+ return jsonify({'error': 'Annotation too long (max 10000 chars)'}), 400++ if name not in app.config['ANNOTATIONS']:+ app.config['ANNOTATIONS'][name] = {}++ app.config['ANNOTATIONS'][name][element_id] = annotation++ return jsonify({+ 'status': 'ok',+ 'annotations_count': len(app.config['ANNOTATIONS'][name]),+ })++ @app.route('/api/slide/<name>/annotate/<element_id>', methods=['DELETE'])+ def delete_annotate(name: str, element_id: str):+ annotations = app.config['ANNOTATIONS']+ if name in annotations and element_id in annotations[name]:+ del annotations[name][element_id]++ return jsonify({+ 'status': 'ok',+ 'annotations_count': len(annotations.get(name, {})),+ })++ @app.route('/api/save-all', methods=['POST'])+ def save_all():+ annotations = app.config['ANNOTATIONS']+ svg_dir = app.config['SVG_DIR']+ modified = []++ for filename, anns in annotations.items():+ if not anns:+ continue++ svg_file = _safe_svg_path(filename)+ if svg_file is None or not svg_file.exists():+ continue++ try:+ tree = ET.parse(str(svg_file))+ root = tree.getroot()+ except ET.ParseError:+ continue++ assign_temp_ids(root)++ # Clear all existing annotations from the file before writing current state+ for elem in root.iter():+ elem.attrib.pop('data-edit-target', None)+ elem.attrib.pop('data-edit-annotation', None)++ for element_id, annotation_text in anns.items():+ set_annotation(root, element_id, annotation_text)++ tree.write(str(svg_file), encoding='UTF-8', xml_declaration=True)+ modified.append(filename)++ app.config['ANNOTATIONS'] = {}++ return jsonify({'status': 'ok', 'files_modified': modified})++ return app+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description='PPT Master SVG Editor',+ formatter_class=argparse.RawDescriptionHelpFormatter,+ )+ parser.add_argument('project_dir', help='Path to project directory (contains svg_output/)')+ parser.add_argument('--port', type=int, default=5000, help='Port to listen on (default: 5000)')+ parser.add_argument('--no-browser', action='store_true', help='Do not auto-open browser')+ parser.add_argument('--timeout', type=int, default=900, help='Idle timeout in seconds (default: 900 = 15min)')+ return parser+++def main(argv: Optional[list[str]] = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)++ project_path = Path(args.project_dir).resolve()+ if not (project_path / 'svg_output').exists():+ print(f"Error: {project_path / 'svg_output'} does not exist", file=sys.stderr)+ return 1++ app = create_app(str(project_path), idle_timeout=args.timeout)++ url = f'http://localhost:{args.port}'+ if not args.no_browser:+ webbrowser.open(url)++ print(f"SVG Editor running at {url}")+ print(f"Project: {project_path}")+ app.run(host='127.0.0.1', port=args.port, debug=False)+ return 0+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/skills/ppt-master/scripts/svg_editor/static/app.js b/skills/ppt-master/scripts/svg_editor/static/app.jsnew file mode 100644index 00000000..1df19c8d--- /dev/null+++ b/skills/ppt-master/scripts/svg_editor/static/app.js@@ -0,0 +1,385 @@+/* ============================================================+ PPT Master - SVG Editor | app.js+ Vanilla JS, IIFE pattern+ ============================================================ */+(function () {+ "use strict";++ // ---- DOM refs ---------------------------------------------------+ var slideListEl = document.getElementById("slide-list");+ var svgPlaceholder = document.getElementById("svg-placeholder");+ var svgContent = document.getElementById("svg-content");+ var selectedElementEl = document.getElementById("selected-element");+ var annotationInput = document.getElementById("annotation-input");+ var annotationText = document.getElementById("annotation-text");+ var btnAddAnnotation = document.getElementById("btn-add-annotation");+ var annotationsEl = document.getElementById("annotations");+ var btnSave = document.getElementById("btn-save");+ var modalOverlay = document.getElementById("modal-overlay");+ var modalMessage = document.getElementById("modal-message");+ var modalConfirm = document.getElementById("modal-confirm");+ var modalCancel = document.getElementById("modal-cancel");++ // ---- State ------------------------------------------------------+ var currentSlide = null; // filename, e.g. "slide_01.svg"+ var selectedElementId = null; // id attr of the clicked SVG element+ var slideAnnotations = {}; // {element_id: annotation_text} for current slide++ // ================================================================+ // 1. loadSlides -- GET /api/slides+ // ================================================================+ function loadSlides() {+ fetch("/api/slides")+ .then(function (res) { return res.json(); })+ .then(function (data) {+ slideListEl.innerHTML = "";+ (data.slides || []).forEach(function (s) {+ var item = document.createElement("div");+ item.className = "slide-item" + (s.name === currentSlide ? " active" : "");+ item.setAttribute("data-name", s.name);++ var nameSpan = document.createElement("span");+ nameSpan.className = "slide-name";+ nameSpan.textContent = s.name;+ item.appendChild(nameSpan);++ if (s.annotation_count > 0) {+ var badge = document.createElement("span");+ badge.className = "badge";+ badge.textContent = s.annotation_count;+ item.appendChild(badge);+ }++ item.addEventListener("click", function () {+ selectSlide(s.name, item);+ });+ slideListEl.appendChild(item);+ });+ })+ .catch(function (err) {+ console.error("loadSlides:", err);+ showError("Failed to load slides: " + err.message);+ });+ }++ // ================================================================+ // 2. selectSlide -- GET /api/slide/{name}+ // ================================================================+ function selectSlide(name, el) {+ // Update active class in sidebar+ document.querySelectorAll(".slide-item").forEach(function (it) {+ it.classList.remove("active");+ });+ if (el) el.classList.add("active");++ currentSlide = name;+ selectedElementId = null;+ slideAnnotations = {};++ // Reset right panel+ clearSelection();++ fetch("/api/slide/" + encodeURIComponent(name))+ .then(function (res) { return res.json(); })+ .then(function (data) {+ if (data.error) {+ console.error("selectSlide:", data.error);+ return;+ }+ // Render SVG+ svgPlaceholder.style.display = "none";+ svgContent.style.display = "block";+ svgContent.innerHTML = sanitizeSvg(data.content);++ // Build annotations map from response+ (data.annotations || []).forEach(function (a) {+ slideAnnotations[a.element_id] = a.annotation;+ });++ setupSvgInteraction();+ refreshAnnotationVisuals();+ updateAnnotationList();+ })+ .catch(function (err) {+ console.error("selectSlide:", err);+ showError("Failed to load slide: " + err.message);+ });+ }++ // ================================================================+ // 3. setupSvgInteraction+ // ================================================================+ var SKIP_TAGS = ["defs", "style", "title", "desc"];++ function setupSvgInteraction() {+ var svg = svgContent.querySelector("svg");+ if (!svg) return;++ var allEls = svg.querySelectorAll("*");+ allEls.forEach(function (el) {+ var tag = el.tagName.toLowerCase();+ if (SKIP_TAGS.indexOf(tag) !== -1) return;+ if (el === svg) return;++ el.classList.add("svg-selectable");++ el.addEventListener("click", function (e) {+ e.stopPropagation();+ selectElement(el);+ });+ });++ // Click on blank area clears selection+ svg.addEventListener("click", function (e) {+ if (e.target === svg) clearSelection();+ });+ }++ // ================================================================+ // 4. selectElement+ // ================================================================+ function selectElement(elem) {+ // Remove old highlight+ if (selectedElementId) {+ var old = svgContent.querySelector("#" + CSS.escape(selectedElementId));+ if (old) old.classList.remove("svg-selected");+ }++ selectedElementId = elem.id || null;+ elem.classList.add("svg-selected");++ // Update right panel info+ selectedElementEl.classList.remove("empty");+ var tag = elem.tagName.toLowerCase();+ var id = elem.id || "(no id)";+ selectedElementEl.innerHTML =+ '<span class="el-tag"><' + escapeHtml(tag) + '></span>' ++ '<span class="el-id">' + escapeHtml(id) + '</span>';++ // Show annotation input, pre-fill if annotation already exists+ annotationInput.style.display = "block";+ annotationText.value = slideAnnotations[selectedElementId] || "";+ annotationText.focus();+ }++ // ================================================================+ // 5. clearSelection+ // ================================================================+ function clearSelection() {+ if (selectedElementId) {+ var el = svgContent.querySelector("#" + CSS.escape(selectedElementId));+ if (el) el.classList.remove("svg-selected");+ }+ selectedElementId = null;+ selectedElementEl.classList.add("empty");+ selectedElementEl.innerHTML = "点击 SVG 元素进行选择";+ annotationInput.style.display = "none";+ annotationText.value = "";+ }++ // ================================================================+ // 6. Add annotation -- POST /api/slide/{name}/annotate+ // ================================================================+ btnAddAnnotation.addEventListener("click", function () {+ if (!currentSlide || !selectedElementId) return;++ var text = annotationText.value.trim();+ if (!text) return;++ fetch("/api/slide/" + encodeURIComponent(currentSlide) + "/annotate", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ element_id: selectedElementId,+ annotation: text+ })+ })+ .then(function (res) { return res.json(); })+ .then(function () {+ slideAnnotations[selectedElementId] = text;+ refreshAnnotationVisuals();+ updateAnnotationList();+ annotationText.value = "";+ // Reload slide list to update badge counts+ loadSlides();+ })+ .catch(function (err) {+ console.error("addAnnotation:", err);+ showError("Failed to add annotation: " + err.message);+ });+ });++ // ================================================================+ // 7. removeAnnotation -- DELETE /api/slide/{name}/annotate/{id}+ // ================================================================+ function removeAnnotation(elementId) {+ if (!currentSlide) return;++ fetch("/api/slide/" + encodeURIComponent(currentSlide) + "/annotate/" + encodeURIComponent(elementId), {+ method: "DELETE"+ })+ .then(function (res) { return res.json(); })+ .then(function () {+ delete slideAnnotations[elementId];+ refreshAnnotationVisuals();+ updateAnnotationList();+ loadSlides();+ })+ .catch(function (err) {+ console.error("removeAnnotation:", err);+ showError("Failed to remove annotation: " + err.message);+ });+ }++ // ================================================================+ // 8. refreshAnnotationVisuals+ // ================================================================+ function refreshAnnotationVisuals() {+ // Clear all annotated marks+ svgContent.querySelectorAll(".svg-annotated").forEach(function (el) {+ el.classList.remove("svg-annotated");+ });+ // Apply marks+ Object.keys(slideAnnotations).forEach(function (eid) {+ var el = svgContent.querySelector("#" + CSS.escape(eid));+ if (el) el.classList.add("svg-annotated");+ });+ }++ // ================================================================+ // 9. updateAnnotationList+ // ================================================================+ function updateAnnotationList() {+ annotationsEl.innerHTML = "";++ var ids = Object.keys(slideAnnotations);+ if (ids.length === 0) {+ annotationsEl.innerHTML = '<div class="annotations-empty">暂无标注</div>';+ return;+ }++ ids.forEach(function (eid) {+ var item = document.createElement("div");+ item.className = "annotation-item";++ // Try to resolve tag from live SVG+ var tag = "";+ var el = svgContent.querySelector("#" + CSS.escape(eid));+ if (el) tag = el.tagName.toLowerCase();++ var header = document.createElement("div");+ header.className = "ann-header";++ var leftSpan = document.createElement("span");+ if (tag) {+ var tagSpan = document.createElement("span");+ tagSpan.className = "ann-tag";+ tagSpan.textContent = "<" + tag + ">";+ leftSpan.appendChild(tagSpan);+ }+ var idSpan = document.createElement("span");+ idSpan.className = "ann-id";+ idSpan.textContent = eid;+ leftSpan.appendChild(idSpan);++ header.appendChild(leftSpan);++ var removeBtn = document.createElement("button");+ removeBtn.className = "ann-remove";+ removeBtn.innerHTML = "×";+ removeBtn.title = "删除标注";+ removeBtn.addEventListener("click", function () {+ removeAnnotation(eid);+ });+ header.appendChild(removeBtn);++ item.appendChild(header);++ var textDiv = document.createElement("div");+ textDiv.className = "ann-text";+ textDiv.textContent = slideAnnotations[eid];+ item.appendChild(textDiv);++ annotationsEl.appendChild(item);+ });+ }++ // ================================================================+ // 10. Save all -- two-step: confirm then save + shutdown+ // ================================================================+ var CONFIRM_MSG = "点击提交后页面将关闭,请确认已完成所有批注。";+ var SUCCESS_MSG = "标注已提交\n\n请告诉AI你已经提交标注,继续修改";++ btnSave.addEventListener("click", function () {+ // Step 1: show confirmation+ modalMessage.textContent = CONFIRM_MSG;+ modalConfirm.style.display = "";+ modalCancel.style.display = "";+ modalOverlay.style.display = "flex";+ });++ modalConfirm.addEventListener("click", function () {+ // Step 2: save + shutdown+ modalConfirm.style.display = "none";+ modalCancel.style.display = "none";++ fetch("/api/save-all", { method: "POST" })+ .then(function (res) { return res.json(); })+ .then(function (data) {+ if (data.error) {+ modalMessage.textContent = "保存失败:" + data.error;+ } else {+ modalMessage.textContent = SUCCESS_MSG;+ fetch("/api/shutdown", { method: "POST" }).catch(function () {});+ }+ })+ .catch(function (err) {+ modalMessage.textContent = "保存失败:" + err;+ });+ });++ modalCancel.addEventListener("click", function () {+ modalOverlay.style.display = "none";+ });++ // Close modal on overlay click+ modalOverlay.addEventListener("click", function (e) {+ if (e.target === modalOverlay) {+ modalOverlay.style.display = "none";+ }+ });++ // ================================================================+ // Utility+ // ================================================================+ function sanitizeSvg(svgString) {+ var doc = new DOMParser().parseFromString(svgString, "image/svg+xml");+ doc.querySelectorAll("script,foreignObject").forEach(function (el) { el.remove(); });+ doc.querySelectorAll("*").forEach(function (el) {+ Array.from(el.attributes).forEach(function (attr) {+ if (attr.name.indexOf("on") === 0) el.removeAttribute(attr.name);+ });+ });+ return new XMLSerializer().serializeToString(doc.documentElement);+ }++ function showError(msg) {+ var banner = document.createElement("div");+ banner.style.cssText = "position:fixed;top:0;left:0;right:0;padding:10px 16px;background:#ef4444;color:#fff;font-size:13px;text-align:center;z-index:999;cursor:pointer;";+ banner.textContent = msg;+ banner.onclick = function () { banner.remove(); };+ document.body.appendChild(banner);+ setTimeout(function () { banner.remove(); }, 5000);+ }++ function escapeHtml(str) {+ var d = document.createElement("div");+ d.appendChild(document.createTextNode(str));+ return d.innerHTML;+ }++ // ================================================================+ // Boot+ // ================================================================+ loadSlides();+})();diff --git a/skills/ppt-master/scripts/svg_editor/static/index.html b/skills/ppt-master/scripts/svg_editor/static/index.htmlnew file mode 100644index 00000000..b54550fb--- /dev/null+++ b/skills/ppt-master/scripts/svg_editor/static/index.html@@ -0,0 +1,50 @@+<!DOCTYPE html>+<html lang="zh-CN">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>PPT Master - SVG Editor</title>+ <link rel="stylesheet" href="/static/style.css">+</head>+<body>+ <div id="app">+ <div id="panel-left">+ <div class="panel-header">幻灯片</div>+ <div id="slide-list"></div>+ </div>+ <div id="panel-center">+ <div id="svg-container">+ <div id="svg-placeholder">选择左侧幻灯片开始编辑</div>+ <div id="svg-content" style="display:none;"></div>+ </div>+ </div>+ <div id="panel-right">+ <div class="panel-header">批注面板</div>+ <div id="selection-info">+ <div class="section-label">当前选中</div>+ <div id="selected-element" class="empty">点击 SVG 元素进行选择</div>+ </div>+ <div id="annotation-input" style="display:none;">+ <div class="section-label">修改指令</div>+ <textarea id="annotation-text" placeholder="描述你希望 AI 如何修改这个元素..."></textarea>+ <button id="btn-add-annotation">添加标注</button>+ </div>+ <div id="annotation-list">+ <div class="section-label">本页标注</div>+ <div id="annotations"></div>+ </div>+ <button id="btn-save" class="btn-save">保存所有标注到 SVG</button>+ </div>+ </div>+ <div id="modal-overlay" style="display:none;">+ <div id="modal">+ <div id="modal-message"></div>+ <div id="modal-buttons">+ <button id="modal-confirm">确认提交</button>+ <button id="modal-cancel">取消</button>+ </div>+ </div>+ </div>+ <script src="/static/app.js"></script>+</body>+</html>diff --git a/skills/ppt-master/scripts/svg_editor/static/style.css b/skills/ppt-master/scripts/svg_editor/static/style.cssnew file mode 100644index 00000000..2abf5139--- /dev/null+++ b/skills/ppt-master/scripts/svg_editor/static/style.css@@ -0,0 +1,471 @@+/* ============================================================+ PPT Master - SVG Editor | Dark theme, three-panel layout+ ============================================================ */++/* ---------- Reset & Base ---------- */+*, *::before, *::after {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+}++html, body {+ height: 100%;+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;+ font-size: 14px;+ color: #e0e0e0;+ background: #1a1a2e;+ overflow: hidden;+}++/* ---------- App shell ---------- */+#app {+ display: flex;+ height: 100vh;+ width: 100vw;+}++/* ======================== LEFT PANEL ======================== */+#panel-left {+ width: 200px;+ min-width: 200px;+ background: #16162a;+ border-right: 1px solid #2a2a4a;+ display: flex;+ flex-direction: column;+ overflow: hidden;+}++#panel-left .panel-header {+ padding: 14px 16px;+ font-weight: 600;+ font-size: 15px;+ border-bottom: 1px solid #2a2a4a;+ flex-shrink: 0;+}++#slide-list {+ flex: 1;+ overflow-y: auto;+ padding: 8px 0;+}++/* Scrollbar */+#slide-list::-webkit-scrollbar {+ width: 6px;+}+#slide-list::-webkit-scrollbar-track {+ background: transparent;+}+#slide-list::-webkit-scrollbar-thumb {+ background: #3a3a5a;+ border-radius: 3px;+}++/* Slide item */+.slide-item {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 10px 16px;+ cursor: pointer;+ transition: background 0.15s;+ border-left: 3px solid transparent;+ user-select: none;+}++.slide-item:hover {+ background: #1f1f38;+}++.slide-item.active {+ background: #1e3a5f;+ border-left-color: #4a9eff;+}++.slide-item .slide-name {+ flex: 1;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ font-size: 13px;+}++.slide-item .badge {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ min-width: 20px;+ height: 20px;+ padding: 0 5px;+ border-radius: 10px;+ background: #f5c542;+ color: #1a1a2e;+ font-size: 11px;+ font-weight: 700;+ line-height: 1;+}++/* ======================== CENTER PANEL ======================== */+#panel-center {+ flex: 1;+ display: flex;+ align-items: stretch;+ justify-content: stretch;+ background: #12121f;+ overflow: hidden;+}++#svg-container {+ flex: 1;+ display: flex;+ align-items: center;+ justify-content: center;+ overflow: auto;+ padding: 24px;+}++#svg-placeholder {+ color: #5a5a7a;+ font-size: 16px;+ user-select: none;+}++#svg-content {+ background: #ffffff;+ border-radius: 4px;+ box-shadow: 0 4px 24px rgba(0, 0, 0, 0.5);+ max-width: 100%;+ max-height: 100%;+ overflow: visible;+ position: relative;+}++#svg-content svg {+ display: block;+ max-width: 100%;+ max-height: calc(100vh - 72px);+ height: auto;+}++/* ---------- SVG element interaction states ---------- */+.svg-selectable {+ cursor: pointer;+ transition: outline 0.12s ease;+}++.svg-selectable:hover {+ outline: 2px solid #4a9eff;+ outline-offset: 2px;+}++.svg-selected {+ outline: 2px solid #4a9eff !important;+ outline-offset: 2px;+}++.svg-annotated {+ outline: 2px solid #f59e0b !important;+ outline-offset: 2px;+}++/* ======================== RIGHT PANEL ======================== */+#panel-right {+ width: 280px;+ min-width: 280px;+ background: #16162a;+ border-left: 1px solid #2a2a4a;+ display: flex;+ flex-direction: column;+ overflow: hidden;+}++#panel-right .panel-header {+ padding: 14px 16px;+ font-weight: 600;+ font-size: 15px;+ border-bottom: 1px solid #2a2a4a;+ flex-shrink: 0;+}++/* --- Selection info --- */+#selection-info {+ padding: 12px 16px;+ border-bottom: 1px solid #2a2a4a;+ flex-shrink: 0;+}++.section-label {+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.8px;+ color: #7a7a9a;+ margin-bottom: 8px;+ font-weight: 600;+}++#selected-element {+ font-size: 13px;+ word-break: break-all;+}++#selected-element.empty {+ color: #5a5a7a;+ font-style: italic;+}++#selected-element .el-tag {+ display: inline-block;+ padding: 2px 8px;+ background: #2a2a4a;+ border-radius: 4px;+ font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;+ font-size: 12px;+ color: #7ab4ff;+ margin-right: 6px;+}++#selected-element .el-id {+ font-size: 12px;+ color: #a0a0c0;+}++/* --- Annotation input --- */+#annotation-input {+ padding: 12px 16px;+ border-bottom: 1px solid #2a2a4a;+ flex-shrink: 0;+}++#annotation-text {+ width: 100%;+ min-height: 80px;+ max-height: 160px;+ resize: vertical;+ padding: 10px 12px;+ font-size: 13px;+ font-family: inherit;+ color: #e0e0e0;+ background: #1e1e36;+ border: 1px solid #3a3a5a;+ border-radius: 6px;+ outline: none;+ transition: border-color 0.2s;+}++#annotation-text:focus {+ border-color: #4a9eff;+}++#annotation-text::placeholder {+ color: #5a5a7a;+}++#btn-add-annotation {+ margin-top: 10px;+ width: 100%;+ padding: 9px 0;+ font-size: 13px;+ font-weight: 600;+ color: #fff;+ background: #4a9eff;+ border: none;+ border-radius: 6px;+ cursor: pointer;+ transition: background 0.15s;+}++#btn-add-annotation:hover {+ background: #3a8eef;+}++#btn-add-annotation:active {+ background: #2a7edf;+}++/* --- Annotation list --- */+#annotation-list {+ flex: 1;+ overflow-y: auto;+ padding: 12px 16px;+ display: flex;+ flex-direction: column;+}++#annotation-list::-webkit-scrollbar {+ width: 6px;+}+#annotation-list::-webkit-scrollbar-track {+ background: transparent;+}+#annotation-list::-webkit-scrollbar-thumb {+ background: #3a3a5a;+ border-radius: 3px;+}++#annotations {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.annotation-item {+ background: #1e1e36;+ border: 1px solid #2a2a4a;+ border-radius: 6px;+ padding: 10px 12px;+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.annotation-item .ann-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+}++.annotation-item .ann-tag {+ font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;+ font-size: 11px;+ color: #f59e0b;+ background: rgba(245, 158, 11, 0.1);+ padding: 2px 6px;+ border-radius: 3px;+}++.annotation-item .ann-id {+ font-size: 11px;+ color: #7a7a9a;+}++.annotation-item .ann-remove {+ background: none;+ border: none;+ color: #ff6b6b;+ cursor: pointer;+ font-size: 16px;+ line-height: 1;+ padding: 0 4px;+ border-radius: 3px;+ transition: background 0.15s;+}++.annotation-item .ann-remove:hover {+ background: rgba(255, 107, 107, 0.15);+}++.annotation-item .ann-text {+ font-size: 13px;+ color: #c0c0d8;+ word-break: break-word;+ white-space: pre-wrap;+}++.annotations-empty {+ color: #5a5a7a;+ font-size: 13px;+ font-style: italic;+}++/* --- Save button --- */+#btn-save {+ margin: 12px 16px 16px;+ padding: 11px 0;+ font-size: 14px;+ font-weight: 600;+ color: #1a1a2e;+ background: #f5c542;+ border: none;+ border-radius: 6px;+ cursor: pointer;+ flex-shrink: 0;+ transition: background 0.15s;+}++#btn-save:hover {+ background: #e5b532;+}++#btn-save:active {+ background: #d5a522;+}++/* ======================== MODAL ======================== */+#modal-overlay {+ position: fixed;+ inset: 0;+ background: rgba(0, 0, 0, 0.65);+ display: flex;+ align-items: center;+ justify-content: center;+ z-index: 1000;+}++#modal {+ background: #1e1e36;+ border: 1px solid #3a3a5a;+ border-radius: 10px;+ padding: 28px 32px;+ max-width: 480px;+ width: 90%;+ box-shadow: 0 8px 40px rgba(0, 0, 0, 0.5);+ text-align: center;+}++#modal-message {+ font-size: 14px;+ line-height: 1.7;+ color: #d0d0e8;+ margin-bottom: 20px;+ white-space: pre-line;+ text-align: left;+}++#modal-buttons {+ display: flex;+ gap: 12px;+ justify-content: center;+}++#modal-confirm {+ padding: 10px 32px;+ font-size: 14px;+ font-weight: 600;+ color: #1a1a2e;+ background: #f5c542;+ border: none;+ border-radius: 6px;+ cursor: pointer;+ transition: background 0.15s;+}++#modal-confirm:hover {+ background: #e5b532;+}++#modal-cancel {+ padding: 10px 32px;+ font-size: 14px;+ font-weight: 600;+ color: #a0a0c0;+ background: transparent;+ border: 1px solid #3a3a5a;+ border-radius: 6px;+ cursor: pointer;+ transition: background 0.15s;+}++#modal-cancel:hover {+ background: #2a2a4a;+}++/* ======================== UTILITY ======================== */+.visually-hidden {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+}