Skip to content

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

feat(svg-editor): add staged direct editing controls

hugohe3a09436154993
diff --git a/.gitignore b/.gitignore
index ab68ea09..2593be2b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -172,6 +172,9 @@ yarn.lock
*.lock
.lock
+# Live preview direct-edit history (per-project, regenerated on edit)
+.live_edits.jsonl
+
# Personal notes
TODO.md
PERSONAL_NOTES.md
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index 24d1e92b..8aa020bf 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -417,7 +417,7 @@ python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --live
- Run it as a long-running side process/session; do not wait for it to exit before generating SVG pages. Do not wait for user confirmation after startup.
- **Service must keep running** until one of: (a) the user clicks **Exit preview** in the browser, or (b) the user explicitly asks in chat to stop it. Generation continues even if the user closes the editor.
- **Do NOT read or apply submitted annotations during generation.** Users may annotate at any time, but Executor proceeds without touching them. The window to apply annotations opens only after Step 7 completes — see [`workflows/live-preview.md`](workflows/live-preview.md).
-- UI button semantics and editor details: see [`workflows/live-preview.md`](workflows/live-preview.md) Notes.
+- The editor also supports **staged direct edits** (text content + SVG element attributes previewed immediately, then written to `svg_output/` only when the user clicks **Apply changes**; `Ctrl+Z` / Undo drops staged edits) alongside annotation; re-export stays chat-driven. Full scope and editor details: see [`workflows/live-preview.md`](workflows/live-preview.md) Notes.
**Pre-generation Batch Read (Mandatory)**: before the first SVG, batch-read every distinct layout SVG referenced in `spec_lock.page_layouts` and every distinct chart SVG referenced in `spec_lock.page_charts` (plus any §VII backup charts). One read per file, up front — do not re-read these during page generation. See executor-base.md §1.0.
@@ -527,7 +527,9 @@ Full effect list, anchor logic, and limits: [`references/animations.md`](referen
> ❌ **NEVER** force `-s output` for the legacy/preview pptx (PowerPoint's internal SVG parser drops icons and rounded corners). The default auto-split already gives native the high-fidelity source it needs without touching legacy.
> ❌ **NEVER** use `--only` (it suppresses one of the two output files)
-> **Post-export annotation window**: the preview service from Step 6 typically remains running after export. If the user submitted annotations in the browser (during Executor or after export) and now asks to apply them — they may quote the browser prompt (`Annotations saved. ... apply my annotations`), say "apply my annotations" / "应用注解" / equivalent — run [`live-preview`](workflows/live-preview.md) Step 2 to apply and re-export. Annotations submitted during generation are also handled here, not earlier.
+> **Post-export annotation window**: the preview service from Step 6 typically remains running after export. If the user submitted annotations in the browser (during Executor or after export) and now asks to apply them — they may quote the browser prompt (`Changes saved to svg_output...` / `修改已保存到 svg_output...`), say "apply my annotations" / "应用注解" / equivalent — run [`live-preview`](workflows/live-preview.md) Step 2 to apply and re-export. Annotations submitted during generation are also handled here, not earlier.
+
+> **Direct edits in the browser**: the user may also stage text / SVG attribute edits in the preview. These land in `svg_output/` only after the user clicks **Apply changes**. If they ask to "re-export" / "重新导出" after applying such edits, just re-run Step 7.2–7.3 (finalize + export); no annotation-application step is needed unless they also saved AI-needed annotations.
> **Preview not running?** Any time the user mentions "live preview", "preview", "看效果", or wants to select/click a slide element and the service is not running, run [`live-preview`](workflows/live-preview.md) Step 1 to start it. If the service is already running, just point them at the URL — do not restart.
diff --git a/skills/ppt-master/scripts/svg_editor/annotations.py b/skills/ppt-master/scripts/svg_editor/annotations.py
index 103e2713..d9284fc1 100644
--- a/skills/ppt-master/scripts/svg_editor/annotations.py
+++ b/skills/ppt-master/scripts/svg_editor/annotations.py
@@ -81,3 +81,105 @@ def remove_annotation(root: ET.Element, element_id: str) -> bool:
elem.attrib.pop('data-edit-target', None)
elem.attrib.pop('data-edit-annotation', None)
return True
+
+
+# ---------------------------------------------------------------------------
+# Direct (AI-free) editing — used by server.py POST /api/slide/<name>/edit.
+# These mutate the element itself (text content / presentation attributes)
+# instead of leaving an annotation marker for the AI to act on. Value
+# validation is the caller's responsibility; these helpers only write.
+# ---------------------------------------------------------------------------
+
+# Attributes that must never be edited from the browser property panel.
+PROTECTED_ATTRS = frozenset({
+ 'id', 'class', 'data-edit-target', 'data-edit-annotation',
+})
+PROTECTED_ATTR_SUFFIXES = frozenset({
+ 'href',
+})
+
+
+def is_editable_attr(key: str) -> bool:
+ """Return True when a raw SVG attribute is safe to edit from the UI."""
+ key_lower = key.lower()
+ if key_lower in PROTECTED_ATTRS:
+ return False
+ if key_lower.startswith('on'):
+ return False
+ if key_lower in PROTECTED_ATTR_SUFFIXES or key_lower.endswith(':href'):
+ return False
+ return True
+
+
+def set_text(root: ET.Element, element_id: str, text: str) -> tuple[bool, Optional[str]]:
+ """Set an element's text content (L1). Returns (ok, reason).
+
+ Refuses elements that own <tspan> children: overwriting ``.text`` there
+ would orphan the tspans and destroy the multi-line layout. The caller
+ should target the specific <tspan> instead.
+ """
+ elem = _find_by_id(root, element_id)
+ if elem is None:
+ return False, 'not-found'
+ for child in elem:
+ ctag = child.tag.split('}', 1)[1] if '}' in child.tag else child.tag
+ if ctag == 'tspan':
+ return False, 'has-tspan-children'
+ elem.text = text
+ return True, None
+
+
+def set_attributes(
+ root: ET.Element, element_id: str, attrs: dict,
+) -> tuple[bool, Optional[str]]:
+ """Set whitelisted presentation attributes (L2). Returns (ok, reason).
+
+ Enforces is_editable_attr as a hard gate (defence in depth — server.py
+ also validates values before calling here). Writes nothing if any key is
+ disallowed, so a rejected request leaves the element untouched.
+ """
+ elem = _find_by_id(root, element_id)
+ if elem is None:
+ return False, 'not-found'
+ for key in attrs:
+ if not is_editable_attr(key):
+ return False, f'attr-not-allowed:{key}'
+ for key, value in attrs.items():
+ elem.set(key, str(value))
+ return True, None
+
+
+def remove_attribute(
+ root: ET.Element, element_id: str, key: str,
+) -> tuple[bool, Optional[str]]:
+ """Remove a whitelisted attribute (used by undo when the old value was unset).
+
+ Returns (ok, reason). Enforces is_editable_attr so undo can only touch the
+ same surface a direct edit could.
+ """
+ if not is_editable_attr(key):
+ return False, f'attr-not-allowed:{key}'
+ elem = _find_by_id(root, element_id)
+ if elem is None:
+ return False, 'not-found'
+ elem.attrib.pop(key, None)
+ return True, None
+
+
+def strip_unused_temp_ids(root: ET.Element, keep_ids: set) -> None:
+ """Drop transient ``_edit_N`` ids except those in ``keep_ids`` and any
+ element still carrying a submitted annotation (its id is the AI's locator).
+
+ Mirrors the cleanup in server.py's save-all so a direct edit never
+ strips the id an unsaved/saved annotation depends on.
+ """
+ protected = set(keep_ids)
+ for elem in root.iter():
+ if elem.get('data-edit-target') == 'true':
+ eid = elem.get('id')
+ if eid:
+ protected.add(eid)
+ for elem in root.iter():
+ eid = elem.get('id', '')
+ if eid.startswith('_edit_') and eid not in protected:
+ elem.attrib.pop('id', None)
diff --git a/skills/ppt-master/scripts/svg_editor/server.py b/skills/ppt-master/scripts/svg_editor/server.py
index 6d70997c..d0efa2d8 100644
--- a/skills/ppt-master/scripts/svg_editor/server.py
+++ b/skills/ppt-master/scripts/svg_editor/server.py
@@ -51,9 +51,12 @@ if str(_FINALIZE_DIR) not in sys.path:
from annotations import ( # noqa: E402
assign_temp_ids,
+ is_editable_attr,
parse_annotations,
set_annotation,
- remove_annotation,
+ set_attributes,
+ set_text,
+ strip_unused_temp_ids,
)
from embed_icons import ( # noqa: E402
parse_use_element,
@@ -185,6 +188,100 @@ def _inline_icons(content: str) -> tuple[str, list[dict]]:
return new_content, warnings
+# ---------------------------------------------------------------------------
+# Staged-edit value validation (POST /api/slide/<name>/edit).
+# The browser may expose raw element attributes, so validation protects only
+# invariants and dangerous value forms rather than a tiny style whitelist.
+# ---------------------------------------------------------------------------
+
+# Reject CSS-injection vectors in color-like values; mirrors frontend checks.
+_UNSAFE_COLOR_RE = re.compile(r'[;:@\\]|url\s*\(', re.IGNORECASE)
+# Generic SVG attribute names: namespaces, hyphenated attrs, and data-* attrs.
+_SAFE_ATTR_NAME_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_.:-]*$')
+_MAX_ATTR_VALUE_LEN = 256
+_MAX_EDIT_TEXT_LEN = 5000
+_ADDABLE_BATCH_ATTRS = frozenset({
+ 'fill', 'stroke', 'opacity',
+ 'font-size', 'font-family', 'font-weight', 'text-anchor',
+})
+
+
+def _is_safe_color(value: str) -> bool:
+ return len(value) < _MAX_ATTR_VALUE_LEN and not _UNSAFE_COLOR_RE.search(value)
+
+
+def _validate_edit_attrs(attrs: dict, existing_attrs: set[str]) -> Optional[str]:
+ """Return an error string if any attr/value is disallowed, else None."""
+ for key, value in attrs.items():
+ if not isinstance(key, str) or not _SAFE_ATTR_NAME_RE.match(key):
+ return f'invalid attribute name: {key}'
+ if not is_editable_attr(key):
+ return f'attribute not editable: {key}'
+ if key not in existing_attrs and key != 'transform' and key not in _ADDABLE_BATCH_ATTRS:
+ return f'attribute does not exist on element: {key}'
+ if not isinstance(value, str):
+ return f'value must be a string: {key}'
+ if len(value) > _MAX_ATTR_VALUE_LEN:
+ return f'value too long: {key}'
+ if key in ('fill', 'stroke', 'color', 'stop-color', 'flood-color', 'lighting-color'):
+ if not _is_safe_color(value):
+ return f'unsafe color value: {key}'
+ if key == 'transform' and re.search(r'nan|inf', value, re.IGNORECASE):
+ return f'invalid transform value: {key}'
+ if any(c in value for c in '<>"'):
+ return f'invalid value: {key}'
+ if re.search(r'javascript\s*:|data\s*:|url\s*\(', value, re.IGNORECASE):
+ return f'unsafe value: {key}'
+ return None
+
+
+_EDIT_LOG_NAME = '.live_edits.jsonl'
+
+
+def _append_edit_log(project_path: Path, record: dict) -> None:
+ """Append one applied edit record (old→new) to the project's history.
+
+ The on-disk JSONL is the durable trail the user can review to see exactly
+ what changed. Un-applied staged edits stay in memory only.
+ """
+ try:
+ with open(project_path / _EDIT_LOG_NAME, 'a', encoding='utf-8') as fh:
+ fh.write(json.dumps(record, ensure_ascii=False) + '\n')
+ except OSError as exc:
+ logger.warning('edit log append failed: %s', exc)
+
+
+def _find_by_id(root: ET.Element, element_id: str) -> Optional[ET.Element]:
+ for elem in root.iter():
+ if elem.get('id') == element_id:
+ return elem
+ return None
+
+
+def _apply_edit_record(root: ET.Element, record: dict) -> tuple[bool, Optional[str]]:
+ element_id = record.get('element_id')
+ if not isinstance(element_id, str):
+ return False, 'invalid-record'
+ if 'text' in record:
+ ok, reason = set_text(root, element_id, str(record.get('text') or ''))
+ if not ok:
+ return ok, reason
+ attrs = record.get('attrs')
+ if attrs:
+ ok, reason = set_attributes(root, element_id, attrs)
+ if not ok:
+ return ok, reason
+ return True, None
+
+
+def _apply_edit_records(root: ET.Element, records: list[dict]) -> tuple[bool, Optional[str]]:
+ for record in records:
+ ok, reason = _apply_edit_record(root, record)
+ if not ok:
+ return ok, reason
+ return True, None
+
+
def create_app(
project_dir: str,
idle_timeout: int = 900,
@@ -206,6 +303,10 @@ def create_app(
# In-memory annotation store: {filename: {element_id: annotation_text}}
app.config['ANNOTATIONS'] = {}
+ # Per-file staged direct edits. They affect the browser preview immediately,
+ # but are written to svg_output/ only by /api/save-all.
+ app.config['PENDING_EDITS'] = {}
+
# Idle timeout: auto-shutdown if no one connects within idle_timeout seconds
app.config['LAST_REQUEST_TIME'] = time.time()
@@ -363,7 +464,10 @@ def create_app(
logger.warning('stat failed: %s: %s', path_str, exc)
return jsonify({'error': f'Failed to stat SVG: {exc}'}), 500
- cached = _cache_get(_SLIDE_CACHE, _SLIDE_CACHE_LOCK, path_str, mtime)
+ pending_edits = app.config['PENDING_EDITS'].get(name) or []
+ cached = None if pending_edits else _cache_get(
+ _SLIDE_CACHE, _SLIDE_CACHE_LOCK, path_str, mtime,
+ )
if cached is not None:
content, warnings, disk_annotations, id_to_tag = cached
else:
@@ -375,6 +479,10 @@ def create_app(
return jsonify({'error': f'Failed to parse SVG: {exc}'}), 500
assign_temp_ids(root)
+ if pending_edits:
+ ok, reason = _apply_edit_records(root, pending_edits)
+ if not ok:
+ return jsonify({'error': f'Failed to apply pending edits: {reason}'}), 500
disk_annotations = parse_annotations(root)
id_to_tag: dict[str, str] = {}
for elem in root.iter():
@@ -386,10 +494,11 @@ def create_app(
id_to_tag[eid] = tag
content = ET.tostring(root, encoding='unicode', xml_declaration=False)
content, warnings = _inline_icons(content)
- _cache_put(
- _SLIDE_CACHE, _SLIDE_CACHE_LOCK, path_str, mtime,
- (content, warnings, disk_annotations, id_to_tag),
- )
+ if not pending_edits:
+ _cache_put(
+ _SLIDE_CACHE, _SLIDE_CACHE_LOCK, path_str, mtime,
+ (content, warnings, disk_annotations, id_to_tag),
+ )
mem_annotations = app.config['ANNOTATIONS'].get(name, {})
merged: dict[str, str] = {}
@@ -412,6 +521,7 @@ def create_app(
'annotations': annotations_list,
'warnings': warnings,
'mtime': mtime,
+ 'undo_depth': len(pending_edits),
})
@app.route('/api/slide/<name>/annotate', methods=['POST'])
@@ -457,13 +567,111 @@ def create_app(
'annotations_count': len(annotations.get(name, {})),
})
+ @app.route('/api/slide/<name>/edit', methods=['POST'])
+ def post_edit(name: str):
+ """Stage a direct (AI-free) edit to one element.
+
+ Body: ``{element_id, text?: str, attrs?: {fill, font-size, ...}}``.
+ The edit is visible in preview, but disk writes happen only in
+ /api/save-all alongside annotation persistence.
+ """
+ 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
+
+ data = request.get_json(silent=True) or {}
+ element_id = data.get('element_id')
+ if not isinstance(element_id, str) or not element_id or len(element_id) > 200:
+ return jsonify({'error': 'Missing or invalid element_id'}), 400
+
+ new_text = data.get('text')
+ attrs = data.get('attrs')
+ if new_text is None and not attrs:
+ return jsonify({'error': 'Nothing to edit (no text or attrs)'}), 400
+
+ if new_text is not None:
+ if not isinstance(new_text, str) or len(new_text) > _MAX_EDIT_TEXT_LEN:
+ return jsonify({'error': 'Invalid or too-long text'}), 400
+ if attrs is not None:
+ if not isinstance(attrs, dict):
+ return jsonify({'error': 'attrs must be an object'}), 400
+
+ try:
+ tree = ET.parse(str(svg_file))
+ root = tree.getroot()
+ except ET.ParseError as exc:
+ return jsonify({'error': f'Failed to parse SVG: {exc}'}), 500
+
+ assign_temp_ids(root)
+ pending = app.config['PENDING_EDITS'].get(name) or []
+ ok, reason = _apply_edit_records(root, pending)
+ if not ok:
+ return jsonify({'error': f'Failed to replay pending edits: {reason}'}), 500
+
+ # Locate the target up front to capture old values before mutating —
+ # these feed the staged record and eventual edit log.
+ target = _find_by_id(root, element_id)
+ if target is None:
+ return jsonify({'error': 'Element not found'}), 404
+ if attrs is not None:
+ attr_err = _validate_edit_attrs(attrs, set(target.attrib.keys()))
+ if attr_err:
+ return jsonify({'error': attr_err}), 400
+
+ changes = []
+ staged: dict = {'element_id': element_id}
+ if new_text is not None:
+ old_text = target.text or ''
+ ok, reason = set_text(root, element_id, new_text)
+ if not ok:
+ return jsonify({'error': f'Text edit failed: {reason}'}), (
+ 404 if reason == 'not-found' else 400
+ )
+ changes.append({'kind': 'text', 'key': None, 'old': old_text, 'new': new_text})
+ staged['text'] = new_text
+ if attrs:
+ old_attrs = {k: target.get(k) for k in attrs}
+ ok, reason = set_attributes(root, element_id, attrs)
+ if not ok:
+ return jsonify({'error': f'Attribute edit failed: {reason}'}), (
+ 404 if reason == 'not-found' else 400
+ )
+ for k, v in attrs.items():
+ changes.append({'kind': 'attr', 'key': k, 'old': old_attrs[k], 'new': v})
+ staged['attrs'] = attrs
+
+ staged['changes'] = changes
+ pending = app.config['PENDING_EDITS'].setdefault(name, [])
+ pending.append(staged)
+ return jsonify({'status': 'ok', 'undo_depth': len(pending)})
+
+ @app.route('/api/slide/<name>/undo', methods=['POST'])
+ def post_undo(name: str):
+ """Drop the most recent staged direct edit on this slide (LIFO)."""
+ 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
+
+ stack = app.config['PENDING_EDITS'].get(name) or []
+ if not stack:
+ return jsonify({'status': 'empty', 'undo_depth': 0})
+ stack.pop()
+ return jsonify({'status': 'ok', 'undo_depth': len(stack)})
+
@app.route('/api/save-all', methods=['POST'])
def save_all():
annotations = app.config['ANNOTATIONS']
- svg_dir = app.config['SVG_DIR']
+ pending_edits = app.config['PENDING_EDITS']
modified = []
- for filename, anns in annotations.items():
+ filenames = sorted(set(annotations.keys()) | set(pending_edits.keys()))
+ for filename in filenames:
+ anns = annotations.get(filename, {})
+ edits = pending_edits.get(filename, [])
# anns may be empty when the user deleted all annotations — still
# need to write so the on-disk data-edit-* attributes are cleared.
@@ -479,6 +687,10 @@ def create_app(
assign_temp_ids(root)
+ ok, reason = _apply_edit_records(root, edits)
+ if not ok:
+ return jsonify({'error': f'Failed to apply edits in {filename}: {reason}'}), 400
+
# Clear all existing annotations from the file before writing current state
for elem in root.iter():
elem.attrib.pop('data-edit-target', None)
@@ -491,15 +703,21 @@ def create_app(
# Only annotated elements need to keep their id so the AI can locate them
# via check_annotations.py; the rest are pollution.
annotated_ids = set(anns.keys())
- for elem in root.iter():
- eid = elem.get('id', '')
- if eid.startswith('_edit_') and eid not in annotated_ids:
- elem.attrib.pop('id', None)
+ strip_unused_temp_ids(root, annotated_ids)
tree.write(str(svg_file), encoding='UTF-8', xml_declaration=True)
+ ts = time.time()
+ for edit in edits:
+ for chg in edit.get('changes', []):
+ _append_edit_log(project_path, {
+ 'ts': ts, 'file': filename, 'element_id': edit.get('element_id'),
+ 'action': 'edit', 'kind': chg.get('kind'), 'key': chg.get('key'),
+ 'old': chg.get('old'), 'new': chg.get('new'),
+ })
modified.append(filename)
app.config['ANNOTATIONS'] = {}
+ app.config['PENDING_EDITS'] = {}
return jsonify({'status': 'ok', 'files_modified': modified})
diff --git a/skills/ppt-master/scripts/svg_editor/static/app.js b/skills/ppt-master/scripts/svg_editor/static/app.js
index 3522cd68..4c712b4d 100644
--- a/skills/ppt-master/scripts/svg_editor/static/app.js
+++ b/skills/ppt-master/scripts/svg_editor/static/app.js
@@ -14,12 +14,19 @@
placeholder_select_slide: "Select a slide on the left to begin",
label_selected_element: "Selected element",
empty_selected_element: "Click an element on the slide to select it",
+ btn_select_group: "Select parent group",
+ label_batch_edit: "Batch edit",
+ label_group_edit: "Group edit",
+ section_geometry: "Geometry",
+ section_style: "Style",
+ section_text_style: "Text",
+ section_raw_attrs: "Raw attributes",
label_edit_instruction: "Edit instruction",
placeholder_annotation: "Describe how the AI should modify this element...",
placeholder_annotation_multi: "Describe how to modify all {count} elements...",
btn_add_annotation: "Add annotation",
label_annotations_on_slide: "Annotations on this slide",
- btn_submit_annotations: "Submit annotations",
+ btn_submit_annotations: "Apply changes",
btn_exit_preview: "Exit preview",
modal_submit: "Submit",
modal_cancel: "Cancel",
@@ -36,14 +43,21 @@
err_add_annotation: "Failed to add annotation: ",
err_remove_annotation: "Failed to remove annotation: ",
err_save: "Save failed: ",
+ err_edit: "Edit failed: ",
+ label_direct_edit: "Object attributes (pending until Apply changes)",
+ prop_multiline_hint: "Multi-line — select a single line (tspan) to edit text",
+ edit_saved_hint: "Change staged. Click Apply changes to write it to svg_output.",
+ btn_undo: "Undo",
+ undo_done: "Reverted last staged edit",
+ undo_empty: "No staged edit to undo",
err_empty_svg: "Slide loaded but the canvas is empty. The SVG may be malformed or missing a root <svg> element.",
warn_icon_inline: "{count} icon(s) failed to render: {names}",
warn_svg_no_dims: "SVG is missing width/height attributes. Please ask the AI to strictly follow shared-standards.md §4 and include width & height in the SVG root element.",
slide_error_tooltip: "Failed to parse this slide: ",
reload_banner: "This slide was updated on disk. Click to reload.",
- modal_confirm_submit: "Submit annotations to disk?\n\nThe preview service will keep running. Click Exit preview when you want to stop it.",
- modal_success_submit: "Annotations saved.\n\nReturn to the chat and tell the AI to apply them (e.g. \"apply my annotations\"). The preview service is still running.",
- modal_confirm_exit: "Exit preview and stop the local server?\n\nUnsaved annotations will be discarded.",
+ modal_confirm_submit: "Apply staged attribute edits and annotations to disk?\n\nThe preview service will keep running. Click Exit preview when you want to stop it.",
+ modal_success_submit: "Changes saved to svg_output.\n\nReturn to the chat to re-export the PPTX or apply AI-needed annotations. The preview service is still running.",
+ modal_confirm_exit: "Exit preview and stop the local server?\n\nUnapplied edits and annotations will be discarded.",
modal_success_exit: "Preview stopped.\n\nYou can close this tab and return to the chat.",
modal_stopping: "Stopping preview server...",
lang_toggle_title: "Switch language",
@@ -61,12 +75,19 @@
placeholder_select_slide: "在左侧选择一张幻灯片开始",
label_selected_element: "已选元素",
empty_selected_element: "点击幻灯片中的元素进行选择",
+ btn_select_group: "选择父级组",
+ label_batch_edit: "批量编辑",
+ label_group_edit: "组编辑",
+ section_geometry: "几何",
+ section_style: "样式",
+ section_text_style: "文本",
+ section_raw_attrs: "原始属性",
label_edit_instruction: "修改说明",
placeholder_annotation: "描述希望 AI 如何修改该元素……",
placeholder_annotation_multi: "描述希望如何修改所选 {count} 个元素……",
btn_add_annotation: "添加标注",
label_annotations_on_slide: "本页标注",
- btn_submit_annotations: "提交标注",
+ btn_submit_annotations: "应用修改",
btn_exit_preview: "退出预览",
modal_submit: "提交",
modal_cancel: "取消",
@@ -83,14 +104,21 @@
err_add_annotation: "添加标注失败:",
err_remove_annotation: "删除标注失败:",
err_save: "保存失败:",
+ err_edit: "编辑失败:",
+ label_direct_edit: "对象属性(点击应用修改后写入)",
+ prop_multiline_hint: "多行文本——选中单行(tspan)编辑文字",
+ edit_saved_hint: "修改已暂存。点击“应用修改”后写入 svg_output。",
+ btn_undo: "撤销",
+ undo_done: "已撤销上一条暂存修改",
+ undo_empty: "没有可撤销的暂存修改",
err_empty_svg: "幻灯片已加载但画布为空。SVG 可能损坏或缺少根 <svg> 元素。",
warn_icon_inline: "{count} 个图标渲染失败:{names}",
warn_svg_no_dims: "SVG 缺少 width/height 属性,预览可能异常。请让 AI 严格遵守 shared-standards.md §4 规范,在 SVG 根元素中补全 width 和 height。",
slide_error_tooltip: "该幻灯片解析失败:",
reload_banner: "当前页已在磁盘上更新,点此重新加载。",
- modal_confirm_submit: "确认将标注保存到磁盘?\n\n预览服务会继续运行。需要关闭时请点击退出预览。",
- modal_success_submit: "标注已保存。\n\n请回到对话窗口并告诉 AI 应用这些标注(例如\"应用我的标注\")。预览服务仍在运行。",
- modal_confirm_exit: "退出预览并停止本地服务?\n\n未保存的标注将被丢弃。",
+ modal_confirm_submit: "确认将暂存属性修改和标注写入磁盘?\n\n预览服务会继续运行。需要关闭时请点击退出预览。",
+ modal_success_submit: "修改已保存到 svg_output。\n\n请回到对话窗口重新导出 PPTX,或让 AI 应用需要判断的标注。预览服务仍在运行。",
+ modal_confirm_exit: "退出预览并停止本地服务?\n\n未应用的属性修改和标注将被丢弃。",
modal_success_exit: "预览已停止。\n\n可以关闭本标签页并回到对话窗口。",
modal_stopping: "正在停止预览服务……",
lang_toggle_title: "切换语言",
@@ -153,6 +181,7 @@
// Re-render dynamic regions so they pick up the new language
updateSelectionPanel();
updateAnnotationList();
+ updateUndoButton();
loadSlides();
}
@@ -165,6 +194,7 @@
var annotationText = document.getElementById("annotation-text");
var btnAddAnnotation = document.getElementById("btn-add-annotation");
var annotationsEl = document.getElementById("annotations");
+ var btnUndo = document.getElementById("btn-undo");
var btnSave = document.getElementById("btn-save");
var btnExitPreview = document.getElementById("btn-exit-preview");
var modalOverlay = document.getElementById("modal-overlay");
@@ -190,6 +220,8 @@
var pendingModalAction = "submit";
var slideMtimes = {}; // {name: mtime} — last-seen mtime for each slide
var reloadBannerEl = null; // singleton banner element shown when currentSlide mtime drifts
+ var editStackCount = {}; // {name: staged edit count} — mirrors backend PENDING_EDITS
+ var savedHintShown = false; // show the "staged edit" hint once per session
function currentSlideIndex() {
if (!currentSlide) return -1;
@@ -412,9 +444,11 @@
slideAnnotations[a.element_id] = a.annotation;
});
+ editStackCount[name] = data.undo_depth || 0;
setupSvgInteraction();
refreshAnnotationVisuals();
updateAnnotationList();
+ updateUndoButton();
})
.catch(function (err) {
console.error("selectSlide:", err);
@@ -459,7 +493,14 @@
// Backend assign_temp_ids() guarantees every element has an id, so
// closest("[id]") will always find a hit. The exclusion of `svg`
// itself routes "click outside any real shape" to clearSelection.
- var picked = target.closest("[id]");
+ // Icon placeholders are expanded only for browser preview. If a
+ // click lands on a generated child, edit the disk-backed data-icon
+ // group instead of an inner preview-only node.
+ var picked = e.altKey && target.closest
+ ? target.closest("g[id]")
+ : null;
+ picked = picked || (target.closest && target.closest("[data-icon][id]")) ||
+ target.closest("[id]");
if (!picked || picked === svg) {
clearSelection();
return;
@@ -537,12 +578,14 @@
selectedElementEl.innerHTML =
'<span class="el-tag">&lt;' + escapeHtml(tag) + '&gt;</span>' +
'<span class="el-id">' + escapeHtml(eid) + '</span>';
- propsEl.innerHTML = renderPropertyTable(getElementProperties(el));
+ propsEl.innerHTML = renderEditableProps(el);
+ attachPropEditors(el);
}
} else {
selectedElementEl.innerHTML =
'<span class="multi-count">' + escapeHtml(t("multi_selected", { count: count })) + '</span>';
propsEl.innerHTML = renderMultiSelectSummary(Array.from(selectedElementIds));
+ attachMultiSelectionEditors(Array.from(selectedElementIds));
}
annotationInput.style.display = "block";
@@ -716,6 +759,19 @@
// ================================================================
function initKeyboardShortcuts() {
document.addEventListener("keydown", function (e) {
+ // Ctrl+Z / Cmd+Z: drop the last staged edit. Let inputs/selects handle
+ // their own native undo when focused.
+ if ((e.ctrlKey || e.metaKey) && (e.key === "z" || e.key === "Z")) {
+ var ae = document.activeElement;
+ if (ae && (ae === annotationText || ae.tagName === "INPUT" ||
+ ae.tagName === "TEXTAREA" || ae.tagName === "SELECT")) {
+ return;
+ }
+ e.preventDefault();
+ runUndo();
+ return;
+ }
+
// Ctrl+A / Cmd+A: select all elements
if ((e.ctrlKey || e.metaKey) && e.key === "a") {
// Don't intercept if focus is in textarea
@@ -949,7 +1005,16 @@
modalMessage.textContent = t("err_save") + data.error;
} else {
modalMessage.textContent = t("modal_success_submit");
- loadSlides();
+ editStackCount = {};
+ savedHintShown = false;
+ updateUndoButton();
+ var activeSlide = currentSlide;
+ loadSlides().then(function () {
+ if (activeSlide) {
+ var item = slideListEl.querySelector('.slide-item[data-name="' + cssAttr(activeSlide) + '"]');
+ selectSlide(activeSlide, item || undefined);
+ }
+ });
}
})
.catch(function (err) {
@@ -1068,53 +1133,256 @@
}, 2000);
}
+ // ---- Direct-edit undo + save hint --------------------------------
+ function updateUndoButton() {
+ if (!btnUndo) return;
+ var n = (currentSlide && editStackCount[currentSlide]) || 0;
+ btnUndo.disabled = n === 0;
+ btnUndo.textContent = n > 0 ? (t("btn_undo") + " (" + n + ")") : t("btn_undo");
+ }
+
+ function runUndo() {
+ if (!currentSlide || !editStackCount[currentSlide]) return;
+ fetch("/api/slide/" + encodeURIComponent(currentSlide) + "/undo", { method: "POST" })
+ .then(jsonOrThrow)
+ .then(function (data) {
+ if (data.status === "empty") {
+ editStackCount[currentSlide] = 0;
+ updateUndoButton();
+ showWarning(t("undo_empty"));
+ return;
+ }
+ if (data.mtime !== undefined && data.mtime !== null) {
+ slideMtimes[currentSlide] = data.mtime;
+ }
+ // Reload the page so the canvas reflects the reverted SVG;
+ // selectSlide refreshes editStackCount + the undo button.
+ var item = slideListEl.querySelector('.slide-item[data-name="' + cssAttr(currentSlide) + '"]');
+ selectSlide(currentSlide, item || undefined);
+ showWarning(t("undo_done"));
+ })
+ .catch(function (err) {
+ showError(t("err_edit") + err.message);
+ });
+ }
+
+ function maybeShowSavedHint() {
+ if (savedHintShown) return;
+ savedHintShown = true;
+ showWarning(t("edit_saved_hint"));
+ }
+
// ================================================================
// Property extraction & rendering
// ================================================================
- function getElementProperties(elem) {
- var props = {};
- var tag = elem.tagName.toLowerCase();
- var style = window.getComputedStyle(elem);
+ // Editable property panel for a single selected element: computed geometry,
+ // text content where safe, and the element's own SVG attributes.
+ function renderEditableProps(el) {
+ var tag = el.tagName.toLowerCase();
+ var isGroup = tag === "g";
+ var html = '<div class="prop-caption">' +
+ escapeHtml(isGroup ? t("label_group_edit") : t("label_direct_edit")) + '</div>';
+
+ var parentGroup = nearestParentGroup(el);
+ if (parentGroup && !isGroup) {
+ html += '<table class="prop-table"><tr><td class="prop-key">group</td><td class="prop-val">' +
+ '<button type="button" class="btn-select-group" data-group-id="' +
+ escapeHtml(parentGroup.id) + '">' + escapeHtml(t("btn_select_group")) +
+ '</button></td></tr></table>';
+ }
- // Position (common to all)
+ html += '<div class="prop-section">' + escapeHtml(t("section_geometry")) + '</div>';
+ html += '<table class="prop-table">';
+ // Geometry: position + size in render coords — editable, folded into
+ // the element's transform matrix on commit (works for any element type).
try {
- var bbox = elem.getBBox();
- props["position"] = Math.round(bbox.x) + ", " + Math.round(bbox.y);
- props["size"] = Math.round(bbox.width) + " x " + Math.round(bbox.height);
- } catch (e) {
- // no geometry
- }
+ var rb = computeRenderBox(el);
+ html += '<tr><td class="prop-key">position</td><td class="prop-val geo-cell">' +
+ '<input type="number" class="prop-edit prop-edit-geo" data-geo="x" value="' + Math.round(rb.x) + '">' +
+ '<input type="number" class="prop-edit prop-edit-geo" data-geo="y" value="' + Math.round(rb.y) + '">' +
+ '</td></tr>';
+ html += '<tr><td class="prop-key">size</td><td class="prop-val geo-cell">' +
+ '<input type="number" class="prop-edit prop-edit-geo" data-geo="w" min="1" value="' + Math.round(rb.w) + '">' +
+ '<input type="number" class="prop-edit prop-edit-geo" data-geo="h" min="1" value="' + Math.round(rb.h) + '">' +
+ '</td></tr>';
+ } catch (e) { /* no geometry */ }
+ html += '</table>';
+ // L1: text content — only when the element owns no <tspan> children.
if (tag === "text" || tag === "tspan") {
- props["font"] = style.fontFamily || elem.getAttribute("font-family") || "";
- props["font-size"] = style.fontSize || elem.getAttribute("font-size") || "";
- props["font-weight"] = style.fontWeight || elem.getAttribute("font-weight") || "";
- props["fill"] = style.fill || elem.getAttribute("fill") || "";
- props["anchor"] = elem.getAttribute("text-anchor") || style.textAnchor || "";
- var text = elem.textContent || "";
- if (text.length > 50) text = text.substring(0, 50) + "...";
- props["content"] = text;
- } else if (tag === "rect") {
- props["fill"] = elem.getAttribute("fill") || style.fill || "";
- props["stroke"] = elem.getAttribute("stroke") || style.stroke || "";
- } else if (tag === "circle") {
- props["r"] = elem.getAttribute("r") || "";
- props["fill"] = elem.getAttribute("fill") || style.fill || "";
- props["stroke"] = elem.getAttribute("stroke") || style.stroke || "";
- } else if (tag === "ellipse") {
- props["rx"] = elem.getAttribute("rx") || "";
- props["ry"] = elem.getAttribute("ry") || "";
- props["fill"] = elem.getAttribute("fill") || style.fill || "";
- } else if (tag === "image") {
- var href = elem.getAttribute("href") || elem.getAttribute("xlink:href") || "";
- var parts = href.split("/");
- props["file"] = parts[parts.length - 1] || href;
- } else if (tag === "path") {
- props["fill"] = elem.getAttribute("fill") || style.fill || "";
- props["stroke"] = elem.getAttribute("stroke") || style.stroke || "";
+ html += '<div class="prop-section">' + escapeHtml(t("section_text_style")) + '</div>';
+ html += '<table class="prop-table">';
+ if (el.querySelector("tspan")) {
+ html += '<tr><td class="prop-key">content</td><td class="prop-val prop-note">' +
+ escapeHtml(t("prop_multiline_hint")) + '</td></tr>';
+ } else {
+ html += '<tr><td class="prop-key">content</td><td class="prop-val">' +
+ '<textarea class="prop-edit prop-edit-content" rows="2">' +
+ escapeHtml(el.textContent || "") + '</textarea></td></tr>';
+ }
+ html += '</table>';
+ }
+
+ html += '<div class="prop-section">' + escapeHtml(t("section_raw_attrs")) + '</div>';
+ html += '<table class="prop-table">';
+ ownAttributeSpecs(el).forEach(function (spec) {
+ html += '<tr><td class="prop-key">' + escapeHtml(spec.key) + '</td><td class="prop-val">';
+ if (!spec.editable) {
+ html += '<span class="prop-ro">' + escapeHtml(spec.value) + '</span>';
+ } else {
+ html += renderAttributeControl(spec);
+ }
+ html += '</td></tr>';
+ });
+
+ html += '</table>';
+ return html;
+ }
+
+ function nearestParentGroup(el) {
+ var node = el ? el.parentElement : null;
+ while (node && node !== svgContent) {
+ if (node.tagName && node.tagName.toLowerCase() === "g" && node.id) return node;
+ node = node.parentElement;
+ }
+ return null;
+ }
+
+ function ownAttributeSpecs(el) {
+ var specs = [];
+ Array.from(el.attributes).forEach(function (attr) {
+ var key = attr.name;
+ if (key === "class" || key === "data-edit-target" || key === "data-edit-annotation") return;
+ specs.push({
+ key: key,
+ value: attr.value,
+ editable: isEditableAttributeName(key)
+ });
+ });
+ return specs;
+ }
+
+ function isEditableAttributeName(key) {
+ var k = String(key).toLowerCase();
+ if (k === "id" || k === "class" || k === "href" || k === "xlink:href") return false;
+ if (k.indexOf("on") === 0) return false;
+ return /^[A-Za-z_][A-Za-z0-9_.:-]*$/.test(key);
+ }
+
+ function isColorAttribute(key, value) {
+ var k = String(key).toLowerCase();
+ if (["fill", "stroke", "color", "stop-color", "flood-color", "lighting-color"].indexOf(k) !== -1) {
+ return isSafeColor(value);
+ }
+ return false;
+ }
+
+ function renderAttributeControl(spec) {
+ if (isColorAttribute(spec.key, spec.value)) {
+ return '<input type="color" class="prop-edit prop-edit-color" data-key="' +
+ escapeHtml(spec.key) + '" value="' + normalizeHexForPicker(spec.value) + '">' +
+ '<input type="text" class="prop-edit prop-edit-color-text" data-key="' +
+ escapeHtml(spec.key) + '" value="' + escapeHtml(spec.value) + '">';
+ }
+ if (spec.value.length > 60 || spec.key === "d" || spec.key === "points" || spec.key === "style") {
+ return '<textarea class="prop-edit prop-edit-attr-area" rows="2" data-key="' +
+ escapeHtml(spec.key) + '">' + escapeHtml(spec.value) + '</textarea>';
+ }
+ return '<input type="text" class="prop-edit prop-edit-attr" data-key="' +
+ escapeHtml(spec.key) + '" value="' + escapeHtml(spec.value) + '">';
+ }
+
+ // ---- Geometry (position/size) helpers ----------------------------
+ // Edits fold into the element's own transform matrix so they apply
+ // uniformly regardless of how the element is positioned (x/y, cx/cy, d…).
+
+ function computeRenderBox(el) {
+ // Local geometry bbox (excludes the element's OWN transform) ...
+ var bbox = el.getBBox();
+ // ... times the element CTM (includes own + ancestor transforms) =
+ // the on-screen box in the svg root user space (= svg_output coords).
+ var ctm = el.getCTM();
+ if (!ctm) return { x: bbox.x, y: bbox.y, w: bbox.width, h: bbox.height };
+ var corners = [
+ { x: bbox.x, y: bbox.y },
+ { x: bbox.x + bbox.width, y: bbox.y },
+ { x: bbox.x, y: bbox.y + bbox.height },
+ { x: bbox.x + bbox.width, y: bbox.y + bbox.height }
+ ];
+ var minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+ corners.forEach(function (p) {
+ var sx = p.x * ctm.a + p.y * ctm.c + ctm.e;
+ var sy = p.x * ctm.b + p.y * ctm.d + ctm.f;
+ minX = Math.min(minX, sx); minY = Math.min(minY, sy);
+ maxX = Math.max(maxX, sx); maxY = Math.max(maxY, sy);
+ });
+ return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
+ }
+
+ function ownMatrix(el) {
+ var t = el.transform && el.transform.baseVal;
+ if (t && t.numberOfItems) {
+ var c = t.consolidate();
+ if (c) {
+ var m = c.matrix;
+ return new DOMMatrix([m.a, m.b, m.c, m.d, m.e, m.f]);
+ }
}
+ return new DOMMatrix();
+ }
- return props;
+ function parentCTM(el) {
+ // parent → svg-root user space; identity when parent is the outer <svg>.
+ var p = el.parentNode;
+ var pm = (p && p.getCTM) ? p.getCTM() : null;
+ return pm ? new DOMMatrix([pm.a, pm.b, pm.c, pm.d, pm.e, pm.f]) : new DOMMatrix();
+ }
+
+ function matrixAfterMove(el, rb, nx, ny) {
+ // Desired shift in root coords, mapped into parent space (linear part only).
+ var pm = parentCTM(el);
+ var rx = nx - rb.x, ry = ny - rb.y;
+ var det = pm.a * pm.d - pm.b * pm.c || 1;
+ var dpx = (pm.d * rx - pm.c * ry) / det;
+ var dpy = (-pm.b * rx + pm.a * ry) / det;
+ return new DOMMatrix().translate(dpx, dpy).multiply(ownMatrix(el));
+ }
+
+ function matrixAfterResize(el, rb, nw, nh) {
+ var pm = parentCTM(el);
+ var sx = nw / rb.w, sy = nh / rb.h;
+ // Anchor = render top-left, mapped to parent coords (full inverse).
+ var im = pm.inverse();
+ var ax = im.a * rb.x + im.c * rb.y + im.e;
+ var ay = im.b * rb.x + im.d * rb.y + im.f;
+ return new DOMMatrix()
+ .translate(ax, ay).scale(sx, sy).translate(-ax, -ay)
+ .multiply(ownMatrix(el));
+ }
+
+ function matrixToString(m) {
+ var r = function (v) { return Math.round(v * 1e6) / 1e6; };
+ var values = [m.a, m.b, m.c, m.d, m.e, m.f].map(r);
+ if (!values.every(function (v) { return Number.isFinite(v); })) return null;
+ return "matrix(" + values.join(",") + ")";
+ }
+
+ function refreshGeoInputs(el, panel) {
+ var rb = computeRenderBox(el);
+ var vals = { x: Math.round(rb.x), y: Math.round(rb.y), w: Math.round(rb.w), h: Math.round(rb.h) };
+ Object.keys(vals).forEach(function (k) {
+ var inp = panel.querySelector('.prop-edit-geo[data-geo="' + k + '"]');
+ if (inp && document.activeElement !== inp) inp.value = vals[k];
+ });
+ }
+
+ function normalizeHexForPicker(val) {
+ var s = String(val).trim();
+ if (/^#[0-9a-fA-F]{6}$/.test(s)) return s;
+ if (/^#[0-9a-fA-F]{3}$/.test(s)) {
+ return "#" + s[1] + s[1] + s[2] + s[2] + s[3] + s[3];
+ }
+ return "#000000";
}
function isSafeColor(val) {
@@ -1123,70 +1391,408 @@
return val.length < 100 && !/[;:@\\]|url\s*\(/i.test(val);
}
- function renderPropertyTable(props) {
- var html = '<table class="prop-table">';
- Object.keys(props).forEach(function (key) {
- var val = props[key];
- if (!val) return;
- html += '<tr><td class="prop-key">' + escapeHtml(key) + '</td><td class="prop-val">';
- if ((key === "fill" || key === "stroke") && isSafeColor(val)) {
- html += '<span class="prop-color" style="background:' + escapeHtml(val) + ';"></span>';
- }
- html += escapeHtml(val) + '</td></tr>';
+ function splitNumberUnit(value) {
+ var m = String(value || "").trim().match(/^(-?\d+(?:\.\d+)?)([A-Za-z%]*)$/);
+ if (!m) return null;
+ return { num: parseFloat(m[1]), unit: m[2] || "" };
+ }
+
+ function shiftedAttrValue(el, key, delta) {
+ var parsed = splitNumberUnit(el.getAttribute(key));
+ if (!parsed || !Number.isFinite(parsed.num)) return null;
+ var next = Math.round((parsed.num + delta) * 1000) / 1000;
+ return String(next) + parsed.unit;
+ }
+
+ function canUseRawGeometry(el) {
+ var own = ownMatrix(el);
+ var parent = parentCTM(el);
+ var close = function (a, b) { return Math.abs(a - b) < 1e-6; };
+ return close(own.a, 1) && close(own.b, 0) && close(own.c, 0) &&
+ close(own.d, 1) && close(own.e, 0) && close(own.f, 0) &&
+ close(parent.a, 1) && close(parent.b, 0) && close(parent.c, 0) &&
+ close(parent.d, 1) && close(parent.e, 0) && close(parent.f, 0);
+ }
+
+ function rawMoveAttrs(el, dx, dy) {
+ if (!canUseRawGeometry(el)) return null;
+ var tag = el.tagName.toLowerCase();
+ var attrs = {};
+ var add = function (key, delta) {
+ if (!el.hasAttribute(key)) return false;
+ var next = shiftedAttrValue(el, key, delta);
+ if (next === null) return false;
+ attrs[key] = next;
+ return true;
+ };
+
+ if (["rect", "image", "use", "text", "tspan"].indexOf(tag) !== -1) {
+ return add("x", dx) && add("y", dy) ? attrs : null;
+ }
+ if (tag === "circle" || tag === "ellipse") {
+ return add("cx", dx) && add("cy", dy) ? attrs : null;
+ }
+ if (tag === "line") {
+ return add("x1", dx) && add("x2", dx) && add("y1", dy) && add("y2", dy) ? attrs : null;
+ }
+ return null;
+ }
+
+ function attrsForMove(el, dx, dy) {
+ var attrs = rawMoveAttrs(el, dx, dy);
+ if (attrs) return attrs;
+ var rb = computeRenderBox(el);
+ var moved = matrixAfterMove(el, rb, rb.x + dx, rb.y + dy);
+ var tstr = matrixToString(moved);
+ return tstr ? { transform: tstr } : null;
+ }
+
+ function computeElementsBox(elements) {
+ var minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+ elements.forEach(function (el) {
+ var rb = computeRenderBox(el);
+ minX = Math.min(minX, rb.x);
+ minY = Math.min(minY, rb.y);
+ maxX = Math.max(maxX, rb.x + rb.w);
+ maxY = Math.max(maxY, rb.y + rb.h);
});
- html += '</table>';
- return html;
+ return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
}
- function renderMultiSelectSummary(ids) {
- var typeCounts = {};
- var sharedFontSize = null;
- var allHaveFontSize = true;
+ function topLevelSelectedElements(ids) {
+ var els = ids.map(function (eid) {
+ return svgContent.querySelector("#" + CSS.escape(eid));
+ }).filter(Boolean);
+ return els.filter(function (el) {
+ return !els.some(function (other) {
+ return other !== el && other.contains(el);
+ });
+ });
+ }
- ids.forEach(function (eid) {
- var el = svgContent.querySelector("#" + CSS.escape(eid));
- if (!el) return;
- var tag = el.tagName.toLowerCase();
- typeCounts[tag] = (typeCounts[tag] || 0) + 1;
-
- if (tag === "text" || tag === "tspan") {
- var fs = window.getComputedStyle(el).fontSize || el.getAttribute("font-size") || "";
- if (sharedFontSize === null) {
- sharedFontSize = fs;
- } else if (sharedFontSize !== fs) {
- sharedFontSize = "mixed";
+ function attachPropEditors(el) {
+ var eid = el.id;
+ var panel = elementPropsEl;
+
+ var groupBtn = panel.querySelector(".btn-select-group");
+ if (groupBtn) {
+ groupBtn.addEventListener("click", function () {
+ var gid = groupBtn.getAttribute("data-group-id");
+ var groupEl = gid ? svgContent.querySelector("#" + CSS.escape(gid)) : null;
+ if (groupEl) selectElement(groupEl, false);
+ });
+ }
+
+ // L1: text content (fires on blur/change).
+ var contentBox = panel.querySelector(".prop-edit-content");
+ if (contentBox) {
+ contentBox.addEventListener("change", function () {
+ var newText = contentBox.value;
+ stageEditRequest(eid, { text: newText })
+ .then(function () { el.textContent = newText; })
+ .catch(function (err) { showError(t("err_edit") + err.message); });
+ });
+ }
+
+ // Raw own attributes: color picker + text input stay in sync.
+ panel.querySelectorAll(".prop-edit-color").forEach(function (picker) {
+ var key = picker.getAttribute("data-key");
+ var textInput = panel.querySelector('.prop-edit-color-text[data-key="' + key + '"]');
+ picker.addEventListener("input", function () {
+ if (textInput) textInput.value = picker.value;
+ });
+ picker.addEventListener("change", function () {
+ stageAttr(el, eid, key, picker.value);
+ });
+ });
+ panel.querySelectorAll(".prop-edit-color-text").forEach(function (textInput) {
+ var key = textInput.getAttribute("data-key");
+ var picker = panel.querySelector('input.prop-edit-color[data-key="' + key + '"]');
+ textInput.addEventListener("change", function () {
+ var v = textInput.value.trim();
+ if (picker) picker.value = normalizeHexForPicker(v);
+ stageAttr(el, eid, key, v);
+ });
+ });
+
+ panel.querySelectorAll(".prop-edit-attr, .prop-edit-attr-area").forEach(function (input) {
+ var key = input.getAttribute("data-key");
+ input.addEventListener("change", function () {
+ stageAttr(el, eid, key, input.value.trim());
+ });
+ });
+
+ // Geometry: position (move) + size (resize), folded into the transform.
+ if (panel.querySelector(".prop-edit-geo")) {
+ var readGeo = function (k) {
+ var inp = panel.querySelector('.prop-edit-geo[data-geo="' + k + '"]');
+ return inp ? parseFloat(inp.value) : NaN;
+ };
+ var commitGeo = function (mode) {
+ var rb;
+ try { rb = computeRenderBox(el); } catch (e) { return; }
+ var newM;
+ var attrs = null;
+ if (mode === "move") {
+ var nx = readGeo("x"), ny = readGeo("y");
+ if (isNaN(nx) || isNaN(ny)) return;
+ if (Math.abs(nx - rb.x) < 1e-6 && Math.abs(ny - rb.y) < 1e-6) return;
+ attrs = attrsForMove(el, nx - rb.x, ny - rb.y);
+ if (!attrs) newM = matrixAfterMove(el, rb, nx, ny);
+ } else {
+ var nw = readGeo("w"), nh = readGeo("h");
+ if (isNaN(nw) || isNaN(nh) || nw <= 0 || nh <= 0 || rb.w <= 0 || rb.h <= 0) {
+ showError(t("err_edit") + "size");
+ return;
+ }
+ if (Math.abs(nw - rb.w) < 1e-6 && Math.abs(nh - rb.h) < 1e-6) return;
+ newM = matrixAfterResize(el, rb, nw, nh);
}
- } else {
- allHaveFontSize = false;
+ if (!attrs) {
+ var tstr = matrixToString(newM);
+ if (!tstr) {
+ showError(t("err_edit") + "transform");
+ return;
+ }
+ attrs = { transform: tstr };
+ }
+ stageEditRequest(eid, { attrs: attrs })
+ .then(function () {
+ Object.keys(attrs).forEach(function (key) {
+ el.setAttribute(key, attrs[key]);
+ });
+ refreshGeoInputs(el, panel);
+ })
+ .catch(function (err) { showError(t("err_edit") + err.message); });
+ };
+ panel.querySelectorAll('.prop-edit-geo[data-geo="x"], .prop-edit-geo[data-geo="y"]').forEach(function (inp) {
+ inp.addEventListener("change", function () { commitGeo("move"); });
+ });
+ panel.querySelectorAll('.prop-edit-geo[data-geo="w"], .prop-edit-geo[data-geo="h"]').forEach(function (inp) {
+ inp.addEventListener("change", function () { commitGeo("resize"); });
+ });
+ }
+ }
+
+ function stageAttr(el, eid, key, value) {
+ if ((key === "fill" || key === "stroke") && !isSafeColor(value)) {
+ showError(t("err_edit") + key);
+ return;
+ }
+ var attrs = {};
+ attrs[key] = value;
+ stageEditRequest(eid, { attrs: attrs })
+ .then(function () { el.setAttribute(key, value); })
+ .catch(function (err) { showError(t("err_edit") + err.message); });
+ }
+
+ function stageEditRequest(eid, payload) {
+ var body = { element_id: eid };
+ if (payload.text !== undefined) body.text = payload.text;
+ if (payload.attrs !== undefined) body.attrs = payload.attrs;
+ return fetch("/api/slide/" + encodeURIComponent(currentSlide) + "/edit", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ }).then(jsonOrThrow).then(function (data) {
+ if (data && data.undo_depth !== undefined) {
+ editStackCount[currentSlide] = data.undo_depth;
+ updateUndoButton();
}
+ maybeShowSavedHint();
+ return data;
});
+ }
- var summary = '<div class="multi-summary">';
- var parts = [];
- Object.keys(typeCounts).forEach(function (tag) {
- parts.push(typeCounts[tag] + " " + tag);
+ function renderMultiSelectSummary(ids) {
+ var moveEls = topLevelSelectedElements(ids);
+ var summary = '<div class="prop-caption">' + escapeHtml(t("label_batch_edit")) + '</div>';
+
+ if (moveEls.length > 0) {
+ try {
+ var rb = computeElementsBox(moveEls);
+ summary += '<div class="prop-section">' + escapeHtml(t("section_geometry")) + '</div>';
+ summary += '<table class="prop-table"><tr><td class="prop-key">x / y</td>' +
+ '<td class="prop-val geo-cell">' +
+ '<input type="number" class="prop-edit prop-edit-multi-geo" data-geo="x" value="' +
+ Math.round(rb.x) + '">' +
+ '<input type="number" class="prop-edit prop-edit-multi-geo" data-geo="y" value="' +
+ Math.round(rb.y) + '">' +
+ '</td></tr></table>';
+ } catch (e) { /* no multi geometry */ }
+ }
+ summary += '<div class="prop-section">' + escapeHtml(t("section_style")) + '</div>';
+ summary += '<table class="prop-table">';
+ batchEditSpecs(moveEls).forEach(function (spec) {
+ summary += '<tr><td class="prop-key">' + escapeHtml(spec.key) + '</td><td class="prop-val">';
+ summary += renderBatchControl(spec);
+ summary += '</td></tr>';
});
- summary += parts.join(", ");
+ summary += '</table>';
+ return summary;
+ }
- if (allHaveFontSize && sharedFontSize && sharedFontSize !== "mixed") {
- summary += ' | font-size: ' + escapeHtml(sharedFontSize);
- } else if (allHaveFontSize && sharedFontSize === "mixed") {
- summary += ' | font-size: ' + escapeHtml(t("multi_mixed"));
+ function batchEditSpecs(elements) {
+ var keys = [
+ { key: "fill", type: "color" },
+ { key: "stroke", type: "color" },
+ { key: "opacity", type: "number", min: "0", max: "1", step: "0.05" }
+ ];
+ if (elements.length > 0 && elements.every(isTextElement)) {
+ keys = keys.concat([
+ { key: "font-size", type: "text" },
+ { key: "font-family", type: "text" },
+ { key: "font-weight", type: "select",
+ options: ["", "normal", "bold", "300", "400", "500", "600", "700", "800"] },
+ { key: "text-anchor", type: "select", options: ["", "start", "middle", "end"] }
+ ]);
}
- summary += '</div>';
+ return keys.map(function (spec) {
+ var value = commonAttrValue(elements, spec.key);
+ var copy = Object.assign({}, spec);
+ copy.value = value === null ? "" : value;
+ copy.mixed = value === null;
+ return copy;
+ });
+ }
- // Element list
- summary += '<div class="multi-el-list">';
- ids.forEach(function (eid) {
- var el = svgContent.querySelector("#" + CSS.escape(eid));
- if (!el) return;
- var tag = el.tagName.toLowerCase();
- summary += '<div class="multi-el-item"><span class="el-tag">&lt;' +
- escapeHtml(tag) + '&gt;</span>' + escapeHtml(eid) + '</div>';
+ function isTextElement(el) {
+ var tag = el.tagName.toLowerCase();
+ return tag === "text" || tag === "tspan";
+ }
+
+ function commonAttrValue(elements, key) {
+ if (elements.length === 0) return "";
+ var first = attrOrComputedValue(elements[0], key);
+ for (var i = 1; i < elements.length; i++) {
+ if (attrOrComputedValue(elements[i], key) !== first) return null;
+ }
+ return first;
+ }
+
+ function attrOrComputedValue(el, key) {
+ var value = el.getAttribute(key);
+ if (value !== null && value !== "") return value;
+ var style = window.getComputedStyle(el);
+ var map = {
+ "fill": "fill",
+ "stroke": "stroke",
+ "opacity": "opacity",
+ "font-size": "fontSize",
+ "font-family": "fontFamily",
+ "font-weight": "fontWeight",
+ "text-anchor": "textAnchor"
+ };
+ return (map[key] && style[map[key]]) || "";
+ }
+
+ function renderBatchControl(spec) {
+ var placeholder = spec.mixed ? t("multi_mixed") : "";
+ if (spec.type === "color") {
+ return '<input type="color" class="prop-edit prop-edit-batch-color" data-key="' +
+ escapeHtml(spec.key) + '" value="' + normalizeHexForPicker(spec.value) + '">' +
+ '<input type="text" class="prop-edit prop-edit-batch" data-key="' +
+ escapeHtml(spec.key) + '" placeholder="' + escapeHtml(placeholder) +
+ '" value="' + escapeHtml(spec.mixed ? "" : spec.value) + '">';
+ }
+ if (spec.type === "number") {
+ return '<input type="number" class="prop-edit prop-edit-batch" data-key="' +
+ escapeHtml(spec.key) + '" min="' + escapeHtml(spec.min || "") +
+ '" max="' + escapeHtml(spec.max || "") + '" step="' +
+ escapeHtml(spec.step || "1") + '" placeholder="' + escapeHtml(placeholder) +
+ '" value="' + escapeHtml(spec.mixed ? "" : spec.value) + '">';
+ }
+ if (spec.type === "select") {
+ var html = '<select class="prop-edit prop-edit-batch" data-key="' + escapeHtml(spec.key) + '">';
+ spec.options.forEach(function (opt) {
+ var label = opt || placeholder || "";
+ var selected = !spec.mixed && spec.value === opt ? " selected" : "";
+ html += '<option value="' + escapeHtml(opt) + '"' + selected + '>' +
+ escapeHtml(label) + '</option>';
+ });
+ html += '</select>';
+ return html;
+ }
+ return '<input type="text" class="prop-edit prop-edit-batch" data-key="' +
+ escapeHtml(spec.key) + '" placeholder="' + escapeHtml(placeholder) +
+ '" value="' + escapeHtml(spec.mixed ? "" : spec.value) + '">';
+ }
+
+ function attachMultiSelectionEditors(ids) {
+ var panel = elementPropsEl;
+ var moveEls = topLevelSelectedElements(ids);
+ if (moveEls.length === 0) return;
+
+ var readGeo = function (k) {
+ var inp = panel.querySelector('.prop-edit-multi-geo[data-geo="' + k + '"]');
+ return inp ? parseFloat(inp.value) : NaN;
+ };
+ var commitMove = function () {
+ var rb;
+ try { rb = computeElementsBox(moveEls); } catch (e) { return; }
+ var nx = readGeo("x"), ny = readGeo("y");
+ if (isNaN(nx) || isNaN(ny)) return;
+ var dx = nx - rb.x, dy = ny - rb.y;
+ if (Math.abs(dx) < 1e-6 && Math.abs(dy) < 1e-6) return;
+
+ var jobs = [];
+ moveEls.forEach(function (el) {
+ var attrs;
+ try { attrs = attrsForMove(el, dx, dy); } catch (e) { attrs = null; }
+ if (!attrs) return;
+ jobs.push(stageEditRequest(el.id, { attrs: attrs }).then(function () {
+ Object.keys(attrs).forEach(function (key) {
+ el.setAttribute(key, attrs[key]);
+ });
+ }));
+ });
+
+ Promise.all(jobs)
+ .then(function () { updateSelectionPanel(); })
+ .catch(function (err) { showError(t("err_edit") + err.message); });
+ };
+
+ panel.querySelectorAll(".prop-edit-multi-geo").forEach(function (inp) {
+ inp.addEventListener("change", commitMove);
});
- summary += '</div>';
- return summary;
+ panel.querySelectorAll(".prop-edit-batch-color").forEach(function (picker) {
+ var key = picker.getAttribute("data-key");
+ var text = panel.querySelector('.prop-edit-batch[data-key="' + key + '"]');
+ picker.addEventListener("input", function () {
+ if (text) text.value = picker.value;
+ });
+ picker.addEventListener("change", function () {
+ if (text) text.value = picker.value;
+ commitBatchAttr(key, picker.value, moveEls);
+ });
+ });
+
+ panel.querySelectorAll(".prop-edit-batch").forEach(function (input) {
+ input.addEventListener("change", function () {
+ var key = input.getAttribute("data-key");
+ var value = input.value.trim();
+ if (!value) return;
+ commitBatchAttr(key, value, moveEls);
+ });
+ });
+ }
+
+ function commitBatchAttr(key, value, elements) {
+ if ((key === "fill" || key === "stroke") && !isSafeColor(value)) {
+ showError(t("err_edit") + key);
+ return;
+ }
+ var jobs = elements.map(function (el) {
+ var attrs = {};
+ attrs[key] = value;
+ return stageEditRequest(el.id, { attrs: attrs }).then(function () {
+ el.setAttribute(key, value);
+ });
+ });
+ Promise.all(jobs)
+ .then(function () { updateSelectionPanel(); })
+ .catch(function (err) { showError(t("err_edit") + err.message); });
}
// ================================================================
@@ -1209,4 +1815,5 @@
initRubberBand();
initKeyboardShortcuts();
initSlideNav();
+ if (btnUndo) btnUndo.addEventListener("click", runUndo);
})();
diff --git a/skills/ppt-master/scripts/svg_editor/static/index.html b/skills/ppt-master/scripts/svg_editor/static/index.html
index fcffb3d2..278c530b 100644
--- a/skills/ppt-master/scripts/svg_editor/static/index.html
+++ b/skills/ppt-master/scripts/svg_editor/static/index.html
@@ -47,6 +47,7 @@
<div id="annotations"></div>
</div>
<div id="preview-actions">
+ <button id="btn-undo" class="btn-undo" data-i18n="btn_undo" disabled>Undo</button>
<button id="btn-save" class="btn-save" data-i18n="btn_submit_annotations">Submit annotations</button>
<button id="btn-exit-preview" class="btn-exit-preview" data-i18n="btn_exit_preview">Exit preview</button>
</div>
diff --git a/skills/ppt-master/scripts/svg_editor/static/style.css b/skills/ppt-master/scripts/svg_editor/static/style.css
index 1381d1ec..381cac38 100644
--- a/skills/ppt-master/scripts/svg_editor/static/style.css
+++ b/skills/ppt-master/scripts/svg_editor/static/style.css
@@ -530,6 +530,29 @@ html, body {
background: #1e1e36;
}
+.btn-undo {
+ padding: 10px 0;
+ font-size: 13px;
+ font-weight: 600;
+ color: #c0c0d8;
+ background: transparent;
+ border: 1px solid #3a3a5a;
+ border-radius: 6px;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s, color 0.15s;
+}
+
+.btn-undo:hover:not(:disabled) {
+ color: #ffffff;
+ background: #2a2a4a;
+ border-color: #5a5a7a;
+}
+
+.btn-undo:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
+
/* ======================== MODAL ======================== */
#modal-overlay {
position: fixed;
@@ -650,6 +673,133 @@ html, body {
border: 1px solid #3a3a5a;
}
+/* --- Direct-edit controls --- */
+.prop-caption {
+ font-size: 10px;
+ text-transform: uppercase;
+ letter-spacing: 0.6px;
+ color: #6a8ec0;
+ margin-bottom: 6px;
+ font-weight: 600;
+}
+
+.prop-section {
+ margin-top: 10px;
+ margin-bottom: 4px;
+ font-size: 10px;
+ color: #8a8aaa;
+ text-transform: uppercase;
+ letter-spacing: 0.4px;
+ font-weight: 600;
+}
+
+.prop-section:first-of-type {
+ margin-top: 0;
+}
+
+.prop-table .prop-ro {
+ color: #8a8aaa;
+}
+
+.prop-table .prop-note {
+ color: #8a8aaa;
+ font-family: inherit;
+ font-style: italic;
+}
+
+.prop-edit {
+ font-family: inherit;
+ color: #e0e0e0;
+ background: #1e1e36;
+ border: 1px solid #3a3a5a;
+ border-radius: 4px;
+ outline: none;
+ font-size: 12px;
+ transition: border-color 0.15s;
+}
+
+.prop-edit:focus {
+ border-color: #4a9eff;
+}
+
+textarea.prop-edit-content,
+textarea.prop-edit-attr-area {
+ width: 100%;
+ resize: vertical;
+ padding: 6px 8px;
+ line-height: 1.4;
+}
+
+input.prop-edit-attr {
+ width: 100%;
+ padding: 4px 6px;
+}
+
+input.prop-edit-number {
+ width: 72px;
+ padding: 4px 6px;
+}
+
+select.prop-edit-select {
+ width: 100%;
+ padding: 4px 6px;
+}
+
+input.prop-edit-color {
+ width: 30px;
+ height: 24px;
+ padding: 0;
+ vertical-align: middle;
+ cursor: pointer;
+ background: #1e1e36;
+}
+
+input.prop-edit-color-text {
+ width: calc(100% - 40px);
+ margin-left: 6px;
+ padding: 4px 6px;
+ vertical-align: middle;
+}
+
+input.prop-edit-batch,
+select.prop-edit-batch {
+ width: 100%;
+ padding: 4px 6px;
+}
+
+input.prop-edit-batch-color + input.prop-edit-batch {
+ width: calc(100% - 40px);
+ margin-left: 6px;
+ vertical-align: middle;
+}
+
+input.prop-edit-geo {
+ width: 56px;
+ padding: 4px 6px;
+ margin-right: 4px;
+}
+
+input.prop-edit-multi-geo {
+ width: 56px;
+ padding: 4px 6px;
+ margin-right: 4px;
+}
+
+.btn-select-group {
+ width: 100%;
+ padding: 5px 7px;
+ color: #d8e6ff;
+ background: #24365a;
+ border: 1px solid #3e5f98;
+ border-radius: 4px;
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.btn-select-group:hover {
+ background: #2d4370;
+}
+
.multi-el-list {
margin-top: 6px;
max-height: 100px;
diff --git a/skills/ppt-master/workflows/live-preview.md b/skills/ppt-master/workflows/live-preview.md
index 63508d74..1bb47d76 100644
--- a/skills/ppt-master/workflows/live-preview.md
+++ b/skills/ppt-master/workflows/live-preview.md
@@ -12,7 +12,7 @@ description: Start the browser SVG editor when it is not running, and apply subm
- **Start (Step 1)** — preview service is not currently running and the user wants to look at the deck or click an element. Typical cases: post-export re-entry in a fresh chat, or the user clicked **Exit preview** earlier and now wants it back.
- **Apply annotations (Step 2)** — Step 7 has produced at least one PPTX, and the user signals that submitted annotations should now be applied. Triggers include:
- - quoting the browser prompt (`Annotations saved. ... apply my annotations ...`)
+ - quoting the browser prompt (`Changes saved to svg_output...` / `修改已保存到 svg_output...`)
- saying `apply my annotations` / `apply my edits` / `应用注解` / `开始应用` / 等价表达
## When NOT to Run
@@ -37,7 +37,8 @@ python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path>
The server binds `127.0.0.1:5050`, opens the browser on a local desktop, and edits `<project_path>/svg_output/` in place. After it prints `SVG Editor running at http://localhost:5050`, tell the user in their language, in one short message:
- editor is at `http://localhost:5050`
-- click an element → write the change → click **Submit annotations** → return to the chat and say `apply my annotations` (or quote the browser prompt)
+- **Direct edit** (deterministic tweaks — wording, color, coordinates, SVG attributes): select an element → change the controls in the right panel → preview updates immediately, but nothing is written to `svg_output/` until **Apply changes**. `Ctrl+Z` or the **Undo** button drops staged edits step by step; applied changes are logged to `<project>/.live_edits.jsonl`. Re-export stays chat-driven: say "re-export" / "重新导出" to refresh the PPTX.
+- **Annotate** (changes that need AI judgement / re-layout): select an element → write the instruction → click **Add annotation** to stage it → click **Apply changes** to write annotation markers → return to the chat and say `apply my annotations` (or quote the browser prompt)
- to skip the editor, just describe the change in chat
Do not wait for confirmation before launching — the user already asked for preview, so launching is the response. Port conflicts → `--port <other>` and report the new URL. Remote access → see the appendix.
@@ -72,7 +73,10 @@ Triggered by the user signals listed in "When to Run".
## Notes (editor invariants — referenced from SKILL.md Step 6)
- **UI**: bilingual (EN/中); auto-detects from `navigator.language`, persists in `localStorage`, toggled via the **中 / EN** button on the right panel. Slide navigation: first/prev/next/last buttons at the top of the center panel, plus `←` / `→` / `Home` / `End` (suppressed while typing in the annotation textarea).
-- **Buttons**: `Add annotation` stages locally; `Submit annotations` writes to disk and keeps the service running; `Exit preview` is the only UI action that stops Flask.
+- **Buttons**: `Add annotation` stages annotation text in memory; `Apply changes` writes staged direct edits plus annotation markers to disk and keeps the service running; `Exit preview` is the only UI action that stops Flask.
+- **Direct edit (no AI)**: selection mode determines the right-panel surface. Single element = full object inspector (geometry, safe text content, raw SVG attributes except protected fields like `id`, UI `class`, event handlers, and hrefs). SVG `<g>` group = group-level edit surface; select via `Alt/Option` + click or **Select parent group** from a child element. Multi-select = limited batch editor over top-level selected objects only: shared x/y plus `fill` / `stroke` / `opacity`; text style fields (`font-size` / `font-family` / `font-weight` / `text-anchor`) appear only when every selected object is `text`/`tspan`. Preview updates immediately; disk writes wait for **Apply changes**.
+- **Undo**: `Ctrl+Z` or the **Undo** button drops the last staged direct edit on the current slide (per-slide LIFO, this session). Applied old→new history is appended to `<project>/.live_edits.jsonl`; un-applied staged edits are in-memory only.
+- **Re-export is chat-driven**: applying changes updates `svg_output/` only. Refreshing the PPTX (finalize + svg_to_pptx) stays a chat step — the editor never runs the export pipeline.
- **Stop conditions**: the service stops when the user clicks **Exit preview** in the browser, asks in chat to stop it, the idle timeout fires, or the process is killed externally.
- **Port**: default `5050`; override with `--port <other>`.
- **Idle timeout**: plain mode `900s`, `--live` mode `7200s`; override with `--timeout <seconds>` (`0` disables).