Agent-driven creation of editable, tastefully crafted visual artifacts.
Python
Release editable design toolkit
Junyanye2a8ef0d09119
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..962bccb--- /dev/null+++ b/.gitignore@@ -0,0 +1,9 @@+.DS_Store+._*+__pycache__/+*.pyc+node_modules/+out/+.trace/+*.tar.gz+*.zipdiff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..d645695--- /dev/null+++ b/LICENSE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/README.md b/README.mdindex bfea415..4fc05f6 100644--- a/README.md+++ b/README.md@@ -15,6 +15,7 @@ Editable Visual Design turns a prompt into a structured design artifact with rea- [Overview](#overview)- [Why Editable Visual Design](#why-editable-visual-design)- [Three Core Ideas](#three-core-ideas)+- [Toolkit](#toolkit)- [Gallery](#gallery)- [🎯 Campaigns](#campaigns)- [📚 Information Design](#information-design)@@ -23,6 +24,7 @@ Editable Visual Design turns a prompt into a structured design artifact with rea- [🎨 Art Design](#art-design)- [Quick Start](#quick-start)- [Acknowledgements](#acknowledgements)+- [License](#license)## Why Editable Visual Design@@ -49,6 +51,17 @@ An image model provides art direction—composition, hierarchy, color, and spatiThe result contains real text, semantic layers, and independent assets that can be selected, moved, edited, and exported. Deterministic checks cover the canvas, fonts, layer contracts, rendering, and editor round trips.+## Toolkit++This repository now ships the code behind the workflow as two independent Codex skills:++| Skill | Purpose | Main outputs |+| --- | --- | --- |+| [`editable-design`](./skills/editable-design/) | Create polished fixed-canvas visual designs from a brief | HTML, PNG, mouse editor, animated layer breakdown, and Agent Design Replay |+| [`html-to-pptx`](./skills/html-to-pptx/) | Optionally convert compatible HTML into editable PowerPoint | Editable `.pptx` with independently selectable elements where the source structure permits |++`editable-design` is the complete core workflow and does not require PowerPoint support. `html-to-pptx` is a sibling tool that runs only when a PPTX is requested. Installation is covered in [Quick Start](#quick-start); the standalone [Toolkit guide](./TOOLKIT.md) and each skill's README contain the detailed requirements and direct commands.+## GalleryThirteen prompts across five visual-design categories, with final renderings, editable demonstrations, and Agent Design Replays.@@ -666,7 +679,34 @@ There is Chinese text near the middle reading “文化科技大會,” and addi## Quick Start-Editable Visual Design is implemented as the `poster-building` skill. The installable skill package and a reproducible starter project are being prepared for the public release. Until then, the Gallery publishes the original prompts and rendered outcomes, with editable demonstrations and Agent Design Replays being added case by case.+Clone the repository and install the main skill into Codex:++```bash+git clone https://github.com/yejy53/Editable-Design.git+cd Editable-Design++mkdir -p ~/.codex/skills+cp -R skills/editable-design ~/.codex/skills/+npm ci --prefix ~/.codex/skills/editable-design/scripts+~/.codex/skills/editable-design/scripts/doctor.sh+```++Then ask Codex to use it:++```text+Use $editable-design to create a polished 3:4 campaign poster for ...+```++Optional editable PowerPoint export is provided by the companion skill:++```bash+cp -R skills/html-to-pptx ~/.codex/skills/+python3 -m pip install -r ~/.codex/skills/html-to-pptx/requirements.txt+python3 -m playwright install chromium+~/.codex/skills/html-to-pptx/scripts/doctor.sh+```++See [`editable-design`](./skills/editable-design/README.md) and [`html-to-pptx`](./skills/html-to-pptx/README.md) for requirements, capability notes, and direct CLI usage. To build a clean source archive containing both skills, run `./pack.sh`.## Acknowledgements@@ -676,3 +716,7 @@ We are grateful to the open-source projects that have helped shape the public co- [OpenDesign](https://github.com/EthanGuo2022/OpenDesign), for advancing open, agent-driven, editable visual artifacts and visible design trajectories.And thanks to the broader open-source design and Coding Agent communities for making this work possible.++## License++This community project is provided under the [Apache License 2.0](./LICENSE) and is not an official OpenAI project. See [Third-party notices](./THIRD_PARTY_NOTICES.md) for dependency attribution.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..36ae7d0--- /dev/null+++ b/THIRD_PARTY_NOTICES.md@@ -0,0 +1,6 @@+# Third-party notices++Each skill contains its own dependency notices. Dependencies are installed separately and are not vendored in this repository unless explicitly stated.++- See `skills/editable-design/THIRD_PARTY_NOTICES.md`.+- See `skills/html-to-pptx/THIRD_PARTY_NOTICES.md`.diff --git a/TOOLKIT.md b/TOOLKIT.mdnew file mode 100644index 0000000..d366b55--- /dev/null+++ b/TOOLKIT.md@@ -0,0 +1,81 @@+# Editable Design Toolkit++Agent-driven creation of editable, tastefully crafted visual artifacts.++This repository packages two independent Codex skills. The main skill turns a visual brief into a fixed-canvas design with real text, semantic HTML layers, independent imagery, rendered output, an editor, an animated layer breakdown, and an evidence-backed Design Replay. The companion skill converts compatible HTML into an editable PowerPoint file when that format is explicitly requested.++See the public [Editable Visual Design Gallery](https://github.com/yejy53/Editable-Design#gallery) for prompts, final renderings, editable demonstrations, and Agent Design Replays.++## Included Skills++| Skill | Purpose | Main outputs |+| --- | --- | --- |+| [`editable-design`](skills/editable-design/) | Create polished posters, covers, campaign graphics, information designs, menus, banners, and social cards | `index.html`, rendered PNG, `editor.html`, `layers.html`, and `replay/index.html` |+| [`html-to-pptx`](skills/html-to-pptx/) | Convert compatible fixed-canvas HTML into an editable PowerPoint file | Editable `.pptx` with independently selectable elements where the source structure permits |++The skills are siblings, not nested dependencies. `editable-design` completes its normal HTML and PNG delivery without PowerPoint support. `html-to-pptx` runs only when the user asks for a PPTX and can also convert compatible HTML produced elsewhere.++## Install++Clone the repository, then install the skill or skills you need:++```bash+git clone https://github.com/yejy53/Editable-Design.git+cd Editable-Design++mkdir -p ~/.codex/skills+cp -R skills/editable-design ~/.codex/skills/+cp -R skills/html-to-pptx ~/.codex/skills/ # optional+```++Install the Editable Design runtime dependency and verify the browser setup:++```bash+npm ci --prefix ~/.codex/skills/editable-design/scripts+~/.codex/skills/editable-design/scripts/doctor.sh+```++For optional PowerPoint export, install its Python dependencies and Playwright browser:++```bash+python3 -m pip install -r ~/.codex/skills/html-to-pptx/requirements.txt+python3 -m playwright install chromium+~/.codex/skills/html-to-pptx/scripts/doctor.sh+```++Detailed requirements and direct CLI usage are documented in each skill's README:++- [`editable-design` setup and capability notes](skills/editable-design/README.md)+- [`html-to-pptx` setup and conversion commands](skills/html-to-pptx/README.md)++## Use in Codex++Ask Codex to use the installed skill by name:++```text+Use $editable-design to create a polished 3:4 campaign poster for ...+```++For a completed compatible HTML design:++```text+Use $html-to-pptx to convert this design into an editable PowerPoint file.+```++Image generation is host-dependent. When it is unavailable, Editable Design can use live typography, HTML geometry, local icons, and user-provided assets where those are sufficient; it does not silently replace an intrinsically photographic or illustrative brief with a materially weaker design.++Design Replay is a local evidence artifact and may contain the original brief, prompts, attachment paths, and design decisions. Review it before sharing.++## Package a Release++Create a source archive without installed dependencies or temporary files:++```bash+./pack.sh+```++The output path is printed when packaging completes. You can also package either skill independently with its own `pack.sh`.++## License++This community project is provided under the [Apache License 2.0](LICENSE) and is not an official OpenAI project. See [Third-party notices](THIRD_PARTY_NOTICES.md) for dependency attribution.diff --git a/pack.sh b/pack.shnew file mode 100755index 0000000..dd70113--- /dev/null+++ b/pack.sh@@ -0,0 +1,24 @@+#!/usr/bin/env bash+set -euo pipefail++toolkit_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+name="editable-design-toolkit"+out="${1:-${TMPDIR:-/tmp}/${name}.tar.gz}"+stage="$(mktemp -d)"+trap 'rm -rf "$stage"' EXIT++mkdir -p "$stage/$name/skills" "$(dirname "$out")"+for file in LICENSE THIRD_PARTY_NOTICES.md .gitignore pack.sh; do+ cp -p "$toolkit_dir/$file" "$stage/$name/$file"+done+cp -p "$toolkit_dir/TOOLKIT.md" "$stage/$name/README.md"+cp -R "$toolkit_dir/skills/editable-design" "$stage/$name/skills/"+cp -R "$toolkit_dir/skills/html-to-pptx" "$stage/$name/skills/"++find "$stage/$name" -name '.DS_Store' -delete+find "$stage/$name" -name '._*' -delete+find "$stage/$name" -type d \( -name node_modules -o -name __pycache__ \) -prune -exec rm -rf {} ++find "$stage/$name" -type f \( -name '*.tar.gz' -o -name '*.zip' \) -delete++tar -czf "$out" -C "$stage" "$name"+printf '%s\n' "$out"diff --git a/skills/editable-design/LICENSE b/skills/editable-design/LICENSEnew file mode 100644index 0000000..d645695--- /dev/null+++ b/skills/editable-design/LICENSE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/skills/editable-design/README.md b/skills/editable-design/README.mdnew file mode 100644index 0000000..0271664--- /dev/null+++ b/skills/editable-design/README.md@@ -0,0 +1,29 @@+# Editable Design++Editable Design is a Codex-first preview skill for fixed-canvas visual work: posters, marketing graphics, covers, menus, banners, and social cards. It produces a clean HTML design, rendered PNG, mouse-editable HTML, an animated layer breakdown, and an evidence-backed Design Replay.++## Requirements++- Codex with local filesystem access+- Node.js 22.12 or newer+- A Chromium-based browser+- Bash on macOS or Linux++Install the browser validation dependency once:++```bash+npm ci --prefix scripts+scripts/doctor.sh+```++Set `EDITABLE_DESIGN_BROWSER=/path/to/chromium` only when automatic browser discovery fails.++Editable PPTX is provided by the separate companion skill `html-to-pptx`. Editable Design never exports PPTX unless the user asks for it after the core design is complete.++## Capability fallback++Image generation is host-dependent. When it is unavailable, the skill uses live typography, HTML geometry, local icons, and user-provided assets when those can satisfy the request. It does not silently replace an intrinsically photographic or illustrative request with a materially weaker design.++Replay is a local evidence artifact and may contain the original brief, prompts, attachment paths, and design decisions. Review it before sharing.++This community project is provided under the [Apache License 2.0](LICENSE). It is not an official OpenAI project.diff --git a/skills/editable-design/SKILL.md b/skills/editable-design/SKILL.mdnew file mode 100755index 0000000..8b5e326--- /dev/null+++ b/skills/editable-design/SKILL.md@@ -0,0 +1,582 @@+---+name: editable-design+description: Create and render fixed-canvas editable visual designs, including posters, marketing graphics, covers, menus, banners, and social cards. Default outputs include fixed and editable HTML, PNG, a mouse editor with scan and exploded layer views, and an evidence-backed Design Replay. Do not use for websites, slide decks, videos, or standalone logo systems. Always use this skill when the project contains `poster.json`.+---++# Editable Design++Design the complete requested fixed-canvas visual, verify it, then deliver it. The default+deliverable is a fixed-canvas `index.html`, a mouse-editable `editor.html` with+scan and exploded-layer views, a poster-specific visual system built from+generated artwork, live typography, and/or HTML geometry, and a rendered PNG.+It also includes `replay/index.html`, a deterministic visual account of the real+input, reference, plan, asset prompts, code, review, and layer output, plus a+standalone animated `layers.html` breakdown.++## Communicate clearly++Assume the user is a nontechnical knowledge worker. Talk about their poster,+choices, progress, and results. Keep tools, commands, files, renderers, browser+software, dependencies, source control, paths, and exit codes out of user-facing+messages unless the user asks or must take action.++Use no more than one short update for each user-visible phase: preparing,+designing, and delivering. If a phase takes longer than 60 seconds, give one+plain-language update. Keep recoverable technical problems private; say only that+you hit a problem and are trying another method.++**You are the designer, not a consultant.** Decide the layout, hierarchy,+palette, type, composition, and white space yourself. Do not generate design+options or pause for a visual selection unless the user explicitly asks to+compare designs. When undecided, pick one and say why; do not hand the choice+back.++Ask one concise group of up to three discovery questions only when the missing+information would materially change the finished poster or force you to invent+something. **The only thing you must ask about is fact**: prices, dates and+times, locations, contact details, exact brand and product names, legal notices.+Inventing one of those ships a falsehood, which is worse than leaving it out.+Everything else is a judgement call, and judgement is your job.++## Choose the execution path++Use the **one-shot fast path** only when all of these are true:++- this is a new poster in an empty or projectless workspace;+- the layout needs no generated shipping imagery, because type, colour, or CSS+ shapes carry it;+- the request does not involve multiple artwork slots, a cutout subject, print+ DPI, or revising an existing poster; and+- the deliverable is a single screen-resolution render.++Use the **capability path** otherwise.++## Generate the imagery++Generated artwork is a first-class visual material, not a required full-canvas+layer. Use it wherever photographic, illustrative, material, atmospheric, or+subject-specific content carries the design. Live typography and HTML geometry+may instead form the primary visual system when their precision, repetition,+and spatial relationships are the composition.++Do not replace imagery the design genuinely needs with a generic gradient, flat+fill, or improvised CSS illustration. Equally, do not generate a backdrop merely+to prove that artwork was used.++Generated support does not need to dominate the page; compact visual assets are+worthwhile when they make a section easier to scan, compare, or remember.++Avoid model-authored SVG illustrations. Graphic content is either generated+raster artwork or it is typography and geometry.++Codex's bundled Node runtime includes Lucide; for common small icons, prefer a+coherent locally embedded Lucide subset over ad hoc CSS drawing, without adding+runtime external requests.++### Choose the reference mode++Treat reference handling as a four-value mode even when the host exposes no+formal setting:++- `auto` — the default. Resolve it to `art-directed` for every new poster,+ including an open brief and the one-shot fast path; the composition reference+ is a standard design step, not an optional enhancement that depends on the+ user describing a finished picture. Resolve it to `off` only when the user+ explicitly declines reference generation, or when a small revision to an+ existing poster does not change its composition. Resolve it to `reproduce`+ when the user supplied an image as the target or asked to match one closely. A+ loose style or mood reference does not imply reproduction.+- `off` — skip composition-reference generation.+- `art-directed` — generate one enhanced, non-shipping composition concept.+- `reproduce` — treat the supplied reference as a high-fidelity specification.++Respect an explicit user choice over `auto`. Whenever `art-directed` is active,+run the creative prompt enhancer below; it is not a separate switch.++When image generation is unavailable, resolve `auto` to `off` when live+typography, HTML geometry, local icons, and user-provided assets can satisfy the+request. If the requested result fundamentally requires generated photography,+illustration, or cutouts, report the missing capability instead of silently+substituting a materially weaker design. A supplied target can still use+`reproduce` without image generation when it can be rebuilt from live elements.++### Create an art-directed composition reference++Generate **one reference composition** before planning anything, and read the+layout off it. Pass the request through a+**creative prompt-enhancement step** and ask the image model for one opinionated,+fully art-directed finished-poster concept rather than a literal transcription.+Lock every user-specified fact, string, subject, required placement, palette+requirement, and exclusion. Freely intensify only the composition, hierarchy,+crop, scale relationships, photographic direction, lighting, materiality,+typography treatment, grid behaviour, and spatial rhythm. This reference-only+step deliberately has more creative freedom than shipping-asset generation,+and it is the only step where the image model is allowed to render text.++Creative expansion changes the design language, not the requested content. Do+not invent facts, dates, locations, prices, brand names, slogans, people,+products, narrative subjects, or extra scene objects. Preserve minimalism when+requested, but express it through tension, scale, atmosphere, material depth,+and precise hierarchy rather than by making the frame merely empty.++Three boundaries make this safe. Breaking any of them wrecks the rest of the run:++- **The reference never becomes artwork.** Save it under `reference/`, never+ `assets/`, and never crop it into a backdrop — it has generated lettering all+ over it.+- **The reference's pixels never ship.** Every character is re-set in HTML. A+ generated glyph cannot be edited or re-flowed, and generated Chinese in+ particular is often subtly wrong. Its *wording*, though, is fair game: if the+ reference invented a line that fits, adopt it as live HTML text and name the+ added lines in the handoff. Facts are the exception. Prices, dates, locations+ and brand names still come from the user; a plausible date the image model+ made up is still a false date.+- **Choose the shipping asset architecture after reading the reference.** The+ reference determines composition, hierarchy, visual regions, and depth+ relationships; it does not require a backdrop. Generate a clean full-bleed+ backdrop when the integrated design decision selects a continuous scene.+ Otherwise generate the selected slots, cutouts, or fragments, or rebuild the+ graphic relationships as live typography and geometry when the reference's+ visual force is fundamentally graphic and modular.++Read off the reference: major visual regions and their proportions, band+positions when they are actually present, visual weight, palette relationships,+text-bearing regions, depth and overlap relationships, and any supporting+visuals, large or small, that materially contribute to meaning, comparison, or+recall. Write these observations into the integrated design plan below. Before+calling the image model, save the exact enhanced prompt in+`reference/composition-prompt.md`; after the result is imported as+`reference/composition-reference.png`, record both under `P02_reference`. These+are evidence for the Replay, not extra design prose.++### High-fidelity reproduction++When the user asks for the reference to be reproduced closely — "make it look+like this" — or supplied the image explicitly as the target, treat it as a+specification rather than a sketch. Work element by element: match positions, proportions,+decorative marks and where each colour sits, and adopt its wording wholesale+as live HTML text.++Two things do not change under this mode. Text is still re-set in HTML, never+lifted as pixels. And facts still come from the user.++Say in the handoff that you were reproducing a reference, and name whatever you+could not reproduce — a hand-drawn contour edge, a texture, a script face that+is not installed.++### Choose the asset architecture before prompting++Before finalizing the asset plan, identify every visual component that+materially contributes to subject, hierarchy, atmosphere, comparison, recall,+semantic distinction, or fidelity to the reference. Let the composition+determine the asset count. Generate all main and supporting assets needed for+the finished poster, and do not consolidate distinct visual roles merely to+reduce generation work.++Use the image model proactively for supporting visual assets when they would+strengthen communication; do not reserve generated imagery only for the main+visual or explicitly requested detail shots.++A generated raster is not the only way to preserve a strong visual reference.+For example, a dense Memphis-style exhibition poster may be strongest as a live+modular composition: monumental typography, saturated colour fields, black+keylines, checker and halftone patterns, label rails, inline pictograms, and+independently placed icon panels. Rebuild those relationships as live HTML/CSS+geometry and inline SVG when flattening them into a background would weaken+their structure, precision, or editability. This is a complete visual system+derived from the same mandatory art-directed reference, not a fallback from+generated imagery.++Choose by visual topology, not by habit. No topology is the default:++- **Slot matrix** — one image per bounded card, product cell, specimen, or+ timeline node; HTML owns the grid and captions.+- **Code-native modular field** — live typography, colour blocks, rules,+ patterns, icon cells, diagrams, and inline geometry form the primary visual+ system. Use this when the reference's force comes from graphic composition,+ precision, repetition, and modular rhythm rather than photographic material.+- **Continuous scene** — one zoned full-bleed backdrop plus HTML typography.+ Use this when the meaningful imagery depends on shared lighting, perspective,+ atmosphere, or physical continuity.+- **Cutout stack** — independent transparent subjects arranged across explicit+ back, middle, text, and foreground layers.+- **Layered collage** — a base field plus a small set of independently placed+ photo fragments, paper pieces, textures, stickers, or cutouts.++Keep elements together when their shared lighting, perspective, material, or+physical interaction makes them one visually continuous scene. Separate or+rebuild them independently when their position, crop, replacement, repetition,+semantic role, or overlap is part of the design. Do not split elements that+share continuous light and perspective merely to make the file count larger;+their seams will show.++Visuals assigned to distinct meanings must remain perceptually and semantically+distinct. Reuse is acceptable only when each instance clearly communicates its+own intended meaning; unintended repetition is a defect.++For a slot matrix, cutout stack, or layered collage, read+[Asset architecture](references/asset-architecture.md). When two or more+shipping assets are needed, create `asset-plan.json` before generating anything;+record each asset's form, target rectangle, layer order, and dependencies.++### Prompt the shipping assets++Before writing shipping prompts, read [Imagery](references/imagery.md) and+follow it exactly. The art-directed composition reference may render poster+text; shipping assets may not.++Use one call per distinct asset. After every shipping prompt and destination+filename is frozen, dispatch up to ten independent generations concurrently in+one batch; do not split a run of ten or fewer assets into smaller waves. For+more than ten, use consecutive batches of ten. Parallelism applies only to+assets without dependencies on another returned image; corrections based on a+returned image remain sequential. Orchestrate the batch with all-settled+semantics rather than fail-fast semantics so one rejected call cannot cancel or+hide the successful results.++Let the whole batch settle, preserve every successful result, and retry only the+failed calls immediately rather than rerunning or delaying the successful ones.+Retry a transient failure once with the same prompt. For a safety refusal or an+obvious prompt-specific failure, revise only that asset's prompt and retry it+once; stop automatic retries after that second attempt and continue with the+successful assets while choosing a safe substitute or reporting the missing+slot. Do not ask for several unrelated cutouts in one sheet: one call returns+one raster, not several independently editable transparent files.++Import all successful results in one post-batch pass with+`scripts/import-asset.sh GENERATED_PATH assets/NAME.png`. Check dimensions,+unwanted lettering, and obvious slot mismatch together in that same pass, then+record the prompt file and selected asset results once. Do not pause for+per-image narration, rewrite already-frozen planning files between successful+results, or introduce a second selection phase when the outputs satisfy their+slot prompts. For ten or fewer independent assets, post-generation handling+should add only local import and one consolidated inspection, not another+multi-minute reasoning stage.++## Start new posters immediately++Before setup, if the intended target directory already exists or the workspace+contains an apparent same-title poster project, ask whether to continue that+project or create a new one. Do not treat matching titles, copy, assets, or+timestamps as authorization to modify user-owned files. Make no writes to the+existing project until the user answers; skip this confirmation only when the+user explicitly identified that existing project as the target. This collision+check happens before and overrides the immediate-setup rule below.++For a new poster in an empty or projectless workspace, make setup the first task+action. From an existing parent directory, run this skill's+`scripts/init-poster.sh TARGET`; do not set the command's working directory to a+target that does not exist yet. Do not run a second initializer.++It copies the starter plus project-local runtime scripts and reports whether a+renderer is available. Change into the target before running the remaining+commands. **Complete this before asking any discovery questions**, then open the starter's+`index.html` in the browser so the user sees the placeholder layout while you+work. Begin the trace in the same breath:++```bash+scripts/trace.sh init "<one line about this poster>"+```++Immediately write the active user-authored brief to `brief.md`, verbatim and in+order, including user-supplied attachment paths. Do not copy ambient UI state,+system instructions, or hidden context into it. Record it with+`scripts/trace.sh artifact brief.md P01_input`. This is the Replay's source of+truth; the trace label is not a substitute for the original request.++If no renderer is available, do not abort: the HTML is still deliverable, it just+produces no PNG. Say so once in the final handoff rather than repeatedly.++In a delegated, background, or invisible thread, initialize normally but do not+open a browser purely for preview. **Reading the render is not preview and is+never skipped.**++## One-shot build++After setup and any necessary clarification, design and produce the poster in one+focused pass. Trace only the stable artifacts named below.++1. Read `index.html`, `poster.json`, and the contract in `README.md`. Read other+ files only when the implementation needs them. Avoid broad scans and+ speculative research.+2. **Fix the canvas.** Infer the size from the intended use, and tell the user+ which one you chose and why in your first update. Write it into `poster.json`;+ the root element's `width`/`height` must equal its `data-canvas-*` values.+ `scripts/trace.sh decision canvas "<W>x<H>" "<why>" P09_canvas`+3. **Complete the reference stage before planning the design or shipping+ assets.** Resolve the reference mode. Under `art-directed`, save the enhanced+ prompt, generate and import the composition reference, read it, and record its+ prompt and image under `P02_reference`. Under `reproduce`, inspect the supplied+ target as the specification. Under `off`, continue without creating reference+ artifacts.+4. **Make one integrated design decision after the reference settles.** In one+ pass decide the final live HTML wording, information hierarchy, asset+ topology, text and image regions, layer order, palette roles, font stacks,+ and asset or region geometry. Keep every user-supplied string verbatim; name+ any non-factual wording adopted from the reference in the handoff. Write the+ decision once in `design-plan.md`. When two or more shipping assets are+ required, also write the minimal machine-readable `asset-plan.json` from+ that same decision. Record both together under `P11_asset_plan`.+5. **Generate the artwork** per the batching, retry, import, and inspection+ policy above, into `assets/`. Record the completed batch once. In multi-asset+ runs, every+ `asset-plan.json` entry's `prompt` value must exactly match one `##` heading+ in `prompts.md`, and the imported filename stem should match the asset `id`:+ `scripts/trace.sh artifact prompts.md P12_generate_imagery`.+6. **Make one complete layout patch.** One file, CSS inline, zero external+ requests, absolute positioning inside the canvas, fixed px for every layout+ dimension. Declare the palette and font stacks on `:root` and reference them+ throughout. Do not write comments.+ For selected Lucide icons, resolve them from the bundled runtime at build+ time and inline only their SVG markup in the poster HTML; keep their size,+ stroke width, and color treatment consistent, and add no runtime import.+7. **Check the final HTML font stacks once** with+ `scripts/check-fonts.sh index.html`. A missing family raises no error in the+ browser, and a family marked `latin only` must not set CJK text. Fix any+ failure before rendering.+8. **Clear the scaffolding**, see below.+9. **Check the deterministic contract**:+ `scripts/check-poster.sh index.html`. Fix every failure before opening Chrome.+10. **Run the editable-layout preflight before the first render**:+ `scripts/trace.sh run P14_contract -- node <poster-building-skill>/scripts/check-contract.mjs index.html`.+ It+ checks fixed geometry, layer and group structure, viewport stability, font+ loading, and whether live-text hit areas are blocked by another layer. Fix+ every failure now; this is the cheap point to change structure.+11. **Render**: `scripts/trace.sh run P15_render -- scripts/render-poster.sh+ index.html out/poster.png`. It reads the PNG's real pixel dimensions back and+ compares them with `poster.json`; a mismatch is an error.+12. **Review, fix, and optimize the render** through the single review loop below.+ Keep every real pass in `render-review.md`; do not create a second review+ record for optimization. After the final render, record the consolidated+ review once under `P16_read_render`, and record the current `index.html` and+ `out/poster.png` under `P15_html` so Replay cannot select an obsolete version.+13. **Wire the bundled editor runtime** without changing `index.html`:+ `node scripts/wire-editor.mjs index.html`. Confirm that `editor.html`,+ `layer-editor.css`, and `layer-editor.js` exist, then+ `scripts/trace.sh artifact editor.html P17_editor`.+14. **Verify the editor and exploded view** with+ `scripts/trace.sh run P17_verify -- node <poster-building-skill>/scripts/verify.mjs index.html`.+ The same browser+ run writes the verified standalone result to `layers.html`; do not launch a+ second generation pass. It must pass the+ geometry-plus-pixel zero-drift, edit/export round-trip, overview/background+ component extraction, one-level gallery spread, theme, scan, replay, collapse, and+ standalone-render checks. After it passes, record+ `scripts/trace.sh artifact layers.html P17_layers`. Read+ [Editor and exploded views](references/editor-runtime.md) for setup and+ commands.+15. **Generate the Agent Design Replay** only after the poster and editing+ contract pass: `node scripts/build-replay.mjs .`, then+ `node scripts/verify-replay.mjs replay/index.html`. Record the `replay/`+ directory under `P18_replay`, then `scripts/trace.sh finish ok`. For an+ older project without those project-local scripts, run this skill's bundled+ `scripts/build-replay.mjs PROJECT` and `scripts/verify-replay.mjs+ PROJECT/replay/index.html` instead. Open the generated Replay once and+ confirm that the seven nodes, Prompt/result pairs, render, Review, and layer+ preview load. The fixed+ template, not the agent, designs this page. Read+ [Agent design replay](references/replay-contract.md) only when recording or+ diagnosing its evidence contract.++## Record the creative path without constraining it++The Replay is a post-build view of real artifacts. It does not add a visual+selection gate, require multiple directions, or change how the poster is+designed. Preserve the exact user request, enhanced reference prompt, plan,+shipping prompts, imported results, HTML, render review, and verified layer+output while working; the builder groups them into seven story stages.++Do not ask the model to redesign the Replay, summarize the run from memory, add+generic “why this was done” commentary, or reconstruct missing prompts. The+viewer displays recorded Agent content and marks absent evidence as missing.+Optional alternatives and selection branches appear only when the run actually+contains them.++## Capability path++### Project setup++- For a new poster use the flow in **Start new posters immediately** and keep the+ starter's canvas, runtime, and validation contract. Its preview scaffolding is+ not a composition, asset-topology, image-coverage, or text-placement guide.+- For an existing poster, preserve its file organisation, `poster.json`, and+ asset paths. A copy change is only a copy change; do not re-flow the layout+ along the way.+- Keep poster code within the project directory.++### Shape the poster++- Hierarchy is the whole job. A viewer takes a poster in three passes: hook,+ then claim, then detail. Build that staircase with size, weight, colour, and+ white space, and make the steps genuinely different. Two elements of similar+ visual weight fight each other and both lose.+- White space is structure, not what is left over.+- Build a controlled palette with explicit roles for the field, text, accents,+ and semantic states. Add colours when the brand, reference, imagery, or+ information encoding requires them; no colour exists merely to fill space.+- Commit to one direction — editorial, luxury, brutalist, playful, technical —+ and let it drive every decision.+- Give every typeface a clear role and verify that it covers the script it sets.+ Use as many families as the composition genuinely needs while preserving a+ coherent hierarchy. Every step of the size ramp must be clearly different+ from the last.+- For vertical CJK type, set `white-space: nowrap` and centre it with flex.+ `text-align` controls the vertical axis under `writing-mode`, so a fixed-width+ box leaves the text against its right edge.+- Where text sits over artwork, guarantee contrast explicitly: a solid panel, a+ scrim, or a directional gradient sized to the text block. Do not count on the+ image being dark enough exactly where you need it.+- Do not default to a coloured or black text box: first use an existing calm region or a local scrim, and add a panel only when its material, edges, palette, and overlap make it an intentional part of the composition rather than a generic card.+- When unsure about the layout, read [Layout and typography](references/layout-typography.md).++### Build the default editing contract++Every poster ships with the bundled editor runtime for human+micro-adjustments and presentation. It can drag layers; resize width, height, or+both with side and corner handles; edit text; change font size or a declared+font family; delete and undo; save a local draft; scan and spread layers into an+exploded view; and download clean edited or exploded HTML. A manually resized+text width remains fixed during later text or font-size edits so the user's+intended wrapping is preserved. It is not a second design application.++Mark each independently movable semantic unit with a unique `data-layer-id`;+keep full-bleed backdrops, textures, scrims, fixed frames, and+`data-explode-group` wrappers unmarked. Use `hf-slot` for independently editable+styled-text leaves, and use a non-nested `data-explode-group` only when it+contains at least two meaningful leaf layers; never nest layer IDs or explode+groups. Declare selectable font stacks on `:root` with a generic fallback.+Keep the prebuilt editor runtime unchanged, generate `editor.html` only with+`node scripts/wire-editor.mjs index.html`, render and validate `index.html`, and+run the bundled browser verification before delivery.++### Deliver the standalone layer breakdown++Every poster includes `layers.html` in addition to the live breakdown in+`editor.html`. The bundled `scripts/verify.mjs` generates and verifies it in one+browser run. Groups remain whole modules by default; when fewer than five+primary content components would be visible, the same one-level gallery also+adds the grouped text leaves as companion tiles so the breakdown does not feel+empty. Do not hand-edit it, wire it back into the editor, or substitute it for+the poster render. Read+[Editor and exploded views](references/editor-runtime.md) before diagnosing a+failure.++### Clear the scaffolding before delivery++Apply the starter cleanup contract in `README.md` and record the sweep with+`scripts/trace.sh artifact cleanup-checklist.json P14_cleanup`. Preserve the+placeholder only when the user explicitly asked to work on the starter itself.++### Add only what this poster needs++- Before prompting generated artwork, and again when artwork comes back wrong,+ read [Imagery](references/imagery.md).+- When the design calls for product matrices, collage fragments, multiple+ cutouts, or foreground/background occlusion, read+ [Asset architecture](references/asset-architecture.md).+- For print, pass `--dpi 300`; the scale factor is derived at 96 px/inch. Only+ meaningful for a canvas sized in print dimensions. The renderer produces PNG+ only; there is no PDF path.+- Add no poster-specific interactivity, media queries, or CDN.+ The bundled default editor shell is the only interaction layer.++## Read the render++**Read the rendered image yourself. A poster you have not looked at is not+finished.**++When a visual reference exists, inspect it beside the current render before+deciding to finalize. Compare the focal subject's scale and position, headline+placement, major information regions, whitespace distribution, alignment,+required supporting details, reading order, and overall visual density. Name+only material differences that can be pointed to in the pixels.++During visual review, check for missing meaningful visual support, unintended+repetition, and mismatches between visuals and their associated content. Treat+them as defects when they weaken comprehension, hierarchy, or fidelity to the+request or reference.++When the reference includes typography, reject a result that looks more+templated, crowded, or hierarchically flat; rework the type before finalizing.++The reference is a benchmark for composition, hierarchy, completeness, and+quality, not automatically a pixel-perfect target. A difference is acceptable+when it deliberately adapts the design to live editable typography or+independently movable assets, or when the current solution is visibly as strong+as or stronger than the reference while preserving the request's intent. Do not+accept an element merely because it remains technically inside the canvas: it is+still defective when it sits visibly too close to a frame, rule, image edge, or+neighboring object. Do not+excuse a weaker focal subject, enlarged dead space, missing structure, reduced+density, poorer contrast, or lost detail as artistic variation unless the+change clearly improves the whole poster.++No script can do this step. The renderer proves the dimensions are right; it+cannot prove that text is not sitting on top of text, or that the artwork+brought its own placeholder lettering — and those two are the main reasons a+poster is scrapped.++Work down the list, and only count what you can point at. Do not evaluate taste:++- **Read every piece of text on the image out loud, line by line.** Anything you+ cannot read is a defect, however correct it looks in the markup+- Any text clipped, cut off by an edge, covered by another layer, or obscured+- Any placeholder copy: LOGO, TITLE, EVENT DETAILS, SUBTITLE, Lorem ipsum, or a+ lone brand-shaped word. This almost always came from generated artwork rather+ than from you+- Any two elements overlapping badly enough that one is unreadable+- For text intended to sit in a panel, ribbon, card, or dark field, compare its visible bounds with that carrier at pixel level; any text or backing that spills outside, misaligns with, or visibly floats above the carrier is a defect even when fully legible.+- Contrast wherever text sits over artwork. If it is short, add a solid panel, a+ scrim, or a directional gradient++For every actual render-review cycle, append one numbered pass to+`render-review.md` with its concrete findings, the changes applied, and the+result confirmed by the next render. A clean render records `none` for findings+and changes and `pass` for the result. Fix, re-render, and read again until no+defect remains. A taste preference is not a defect — do not invent one so you+have something to say.++After defects are resolved, perform exactly one optimization assessment against+the reference and request. Compare visual-asset count, semantic variety,+icon-to-copy pairing, and regions that changed from image-supported to text-only.+If one clear opportunity would materially improve scanning, recall, or fidelity,+apply only the highest-impact enhancement, update the asset plan and prompts when+needed, rerender, and append the real pass. If none exists, write `Optimization:+none` in the current pass and do not rerender. Record the consolidated file once+after the final render:+`scripts/trace.sh artifact render-review.md P16_read_render`.++If the same problem survives two fixes, your diagnosis is wrong. Stop, look at+the image again, and change your assumption rather than your wording.++## Optional PPTX handoff++The mouse-editable HTML is built in and is not an optional integration. Finish+and deliver the core design before discussing PowerPoint. When the separate+`html-to-pptx` skill is available, tell the user once that an editable PPTX can+also be exported. Do not generate it unless the user asks. After they ask, use+`html-to-pptx` with `index.html` or an editor-downloaded `*.edited.html` beside+its assets; never pass `editor.html`. PPTX availability must not delay or weaken+the HTML, editor, PNG, layer breakdown, or Replay delivery.++## Deliver++Give the location of the PNG, `index.html`, `editor.html`, `layers.html`, and+`replay/index.html`, the canvas size and the font families used, and the text+you read line by line off the render. Tell the+user that `editor.html` supports mouse dragging, eight-handle width/height+resizing, double-click text editing, and scan/explode/collapse views.+Treat Replay as a local evidence artifact by default and warn before sharing it,+because it may contain the original brief, prompts, attachment paths, and design+decisions.+State anything still wrong and exactly how it falls short; do not describe it+as finished.++When you cannot finish, name the obstacle — which fact is missing, which two+requirements contradict each other, how the amount of content and the canvas size+fail to fit — and say what you need. Do not disguise a design problem as missing+information.++Keep commands, exit codes, renderer names, and other internals out of the handoff+unless the user asks.diff --git a/skills/editable-design/THIRD_PARTY_NOTICES.md b/skills/editable-design/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..1f187a9--- /dev/null+++ b/skills/editable-design/THIRD_PARTY_NOTICES.md@@ -0,0 +1,9 @@+# Third-party notices++Editable Design uses or interoperates with the following third-party software. Dependencies are installed separately and are not included in the release archive unless explicitly stated.++- `puppeteer-core` — Apache License 2.0.+- Puppeteer's transitive npm dependencies — Apache-2.0, MIT, ISC, BSD-2-Clause, BSD-3-Clause, and 0BSD packages as recorded in `scripts/package-lock.json`.+- Pillow — HPND License; optional local cutout-processing dependency.++Generated or user-supplied artwork is not included in this repository's license merely because it is processed by the skill. Bundled Editable Design runtime files retain their Apache-2.0 license when copied into generated projects.diff --git a/skills/editable-design/agents/openai.yaml b/skills/editable-design/agents/openai.yamlnew file mode 100755index 0000000..b8d4772--- /dev/null+++ b/skills/editable-design/agents/openai.yaml@@ -0,0 +1,4 @@+interface:+ display_name: "Editable Design"+ short_description: "Create editable fixed-canvas visual designs"+ default_prompt: "Use $editable-design to create and render a polished fixed-canvas design with editable HTML and a layer breakdown."diff --git a/skills/editable-design/assets/editor/layer-editor.css b/skills/editable-design/assets/editor/layer-editor.cssnew file mode 100755index 0000000..93ac4c6--- /dev/null+++ b/skills/editable-design/assets/editor/layer-editor.css@@ -0,0 +1,262 @@+/* ============================================================+ layer-editor —— 海报图层微调编辑器外壳样式+ 全部以 hf- 前缀命名,与海报本身的样式完全隔离。+ 与 layer-editor.js 配套;移除这两个文件即还原为纯海报。+ ============================================================ */++body.hf-on{+ display:block;padding:0;margin:0;+ background:#15171a;+ font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;+}++/* ---------- 舞台:承载缩放后的画布 ---------- */+.hf-stage-wrap{+ position:fixed;left:0;top:52px;right:300px;bottom:0;+ overflow:auto;display:flex;align-items:flex-start;justify-content:center;+ padding:28px;transition:background-color .24s ease;+}+.hf-stage{position:relative;flex:none;}+.hf-canvas{transform-origin:top left;}++/* ---------- 拆解视图:完整总览 + 背景 + 一级内容组件 ---------- */+.hf-exploded-board{+ position:absolute;left:0;top:0;overflow:hidden;transform-origin:top left;+ background:var(--hf-exploded-bg,#0b0c0d);color:var(--hf-exploded-fg,#f4f1e8);isolation:isolate;+}+.hf-exploded-item{+ position:absolute;overflow:hidden;transform-origin:top left;will-change:transform,opacity,filter;+}+.hf-exploded-scan{+ position:absolute;z-index:40;overflow:hidden;pointer-events:none;opacity:0;+ border-radius:18px;mix-blend-mode:screen;+ box-shadow:inset 0 0 0 1px rgba(188,255,243,.36),inset 0 0 42px rgba(113,244,222,.09);+}+.hf-exploded-scan-grid{+ position:absolute;inset:0;opacity:0;+ background-image:+ linear-gradient(rgba(151,255,237,.16) 1px,transparent 1px),+ linear-gradient(90deg,rgba(151,255,237,.16) 1px,transparent 1px);+ background-size:48px 48px;+ mask-image:linear-gradient(180deg,transparent,black 12%,black 88%,transparent);+}+.hf-exploded-scan-beam{+ position:absolute;left:-3%;top:0;width:106%;height:18%;opacity:0;+ background:linear-gradient(180deg,transparent 0%,rgba(118,255,231,.08) 28%,+ rgba(185,255,244,.25) 50%,rgba(255,255,255,.96) 55%,+ rgba(104,255,230,.34) 58%,transparent 100%);+ filter:drop-shadow(0 0 18px rgba(152,255,237,.9));+}+.hf-exploded-item{+ cursor:pointer;filter:drop-shadow(0 16px 28px var(--hf-exploded-shadow,rgba(0,0,0,.28)));+ transition:transform .22s cubic-bezier(.22,1,.36,1),filter .18s,opacity .18s;+}+.hf-exploded-item[data-exploded-group]{cursor:default;}+.hf-exploded-item:is([data-exploded-overview],[data-exploded-background]){+ cursor:default;border:1px solid var(--hf-exploded-border,rgba(244,241,232,.42));+ border-radius:16px;box-sizing:border-box;+}+.hf-exploded-label{+ position:absolute;left:18px;top:18px;z-index:8;max-width:calc(100% - 36px);+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap;pointer-events:none;+ padding:12px 18px;border:1px solid var(--hf-exploded-border,rgba(255,255,255,.22));border-radius:999px;+ background:var(--hf-exploded-label-bg,rgba(11,12,13,.78));backdrop-filter:blur(10px);+ color:var(--hf-exploded-label-fg,#f4f1e8);+ font:650 28px/1 -apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif;+ letter-spacing:.35px;opacity:0;transform:translateY(6px);+ transition:opacity .16s ease,transform .22s cubic-bezier(.22,1,.36,1);+}+.hf-exploded-settled.hf-exploded-interacted .hf-exploded-item:is(:hover,:focus-visible) .hf-exploded-label{+ opacity:1;transform:translateY(0);+}+.hf-exploded-settled .hf-exploded-item:hover{+ transform:translateY(-8px) scale(1.015);+ filter:drop-shadow(0 18px 34px rgba(0,0,0,.38)) brightness(1.08);+}+.hf-exploded-animating .hf-exploded-item{pointer-events:none;}+.hf-exploded-crop{position:absolute;left:0;top:0;overflow:hidden;}+.hf-exploded-source{+ max-width:none!important;max-height:none!important;transform:none!important;+ pointer-events:none!important;+}+.hf-exploded-on .hf-stage > .hf-canvas,+.hf-exploded-on .hf-stage > .hf-guides{display:none;}+.hf-exploded-on .hf-stage-wrap{background-color:var(--hf-exploded-bg,#0b0c0d);}++@media (prefers-reduced-motion:reduce){+ .hf-exploded-item{transition:none;}+ .hf-exploded-scan{display:none;}+}++/* ---------- 顶部工具条 ---------- */+.hf-bar{+ position:fixed;left:0;right:0;top:0;height:52px;z-index:9000;+ display:flex;align-items:center;gap:8px;padding:0 14px;+ background:#1e2126;border-bottom:1px solid #32363d;color:#e6e8ea;+ font-size:13px;+}+.hf-bar .hf-title{+ font-weight:600;letter-spacing:.5px;margin-right:6px;+ max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;+}+.hf-bar .hf-sep{width:1px;height:22px;background:#3a3f47;margin:0 4px;}+.hf-btn{+ appearance:none;border:1px solid #3a3f47;background:#282c33;color:#e6e8ea;+ padding:6px 12px;border-radius:6px;font-size:12.5px;cursor:pointer;+ font-family:inherit;transition:background .12s,border-color .12s;white-space:nowrap;+}+.hf-btn:hover{background:#333840;border-color:#4a505a;}+.hf-btn:active{background:#22262c;}+.hf-btn.active{background:#4a3d20;border-color:#a78635;color:#ffe28a;}+.hf-btn.primary{background:#2f6f4f;border-color:#3c8a63;}+.hf-btn.primary:hover{background:#37805c;}+.hf-btn.danger:hover{background:#5d2b2b;border-color:#7a3a3a;}+.hf-btn[disabled]{opacity:.4;cursor:default;}+.hf-btn[disabled]:hover{background:#282c33;border-color:#3a3f47;}+.hf-zoom{margin-left:auto;display:flex;align-items:center;gap:8px;color:#9aa2ad;}+.hf-zoom output{min-width:46px;text-align:right;font-variant-numeric:tabular-nums;color:#e6e8ea;}++/* ---------- 右侧面板 ---------- */+.hf-panel{+ position:fixed;right:0;top:52px;bottom:0;width:300px;z-index:9000;+ background:#1e2126;border-left:1px solid #32363d;color:#e6e8ea;+ display:flex;flex-direction:column;+}+.hf-panel h4{+ margin:0;padding:13px 14px 9px;font-size:11px;font-weight:600;+ letter-spacing:1.4px;text-transform:uppercase;color:#7d8792;+ display:flex;align-items:center;gap:8px;+}+.hf-layers{flex:1;overflow:auto;padding:0 8px 12px;min-height:80px;}+.hf-layer{+ display:flex;align-items:center;gap:9px;padding:8px 10px;border-radius:6px;+ cursor:pointer;font-size:12.5px;color:#c3c9d1;+}+.hf-layer:hover{background:#282c33;}+.hf-layer.sel{background:#2f6f4f;color:#fff;}+.hf-layer .dot{width:7px;height:7px;border-radius:50%;background:#5c6470;flex:none;}+.hf-layer.sel .dot{background:#9fe3c0;}+.hf-layer .nm{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}+.hf-layer .pos{+ margin-left:auto;font-size:11px;color:#7d8792;font-variant-numeric:tabular-nums;flex:none;+}+.hf-layer.sel .pos{color:#c8ecd9;}++/* ---------- 属性区 ---------- */+.hf-props{border-top:1px solid #32363d;padding:4px 14px 12px;}+.hf-props[hidden]{display:none;}+.hf-field{display:flex;align-items:center;gap:8px;margin-bottom:9px;font-size:12px;color:#9aa2ad;}+.hf-field > label{width:38px;flex:none;}+.hf-field select{+ flex:1;appearance:none;background:#282c33;color:#e6e8ea;font-family:inherit;+ border:1px solid #3a3f47;border-radius:6px;padding:5px 8px;font-size:12px;cursor:pointer;+}+.hf-step{display:flex;align-items:center;gap:6px;}+.hf-step .hf-btn{padding:4px 10px;font-size:13px;line-height:1;}+.hf-step .val{+ min-width:52px;text-align:center;color:#e6e8ea;+ font-variant-numeric:tabular-nums;font-size:12px;+}+.hf-props .hf-btn.danger{width:100%;margin-top:2px;}++.hf-hint{+ padding:12px 14px;border-top:1px solid #32363d;font-size:11.5px;+ line-height:1.85;color:#7d8792;+}+.hf-hint kbd{+ background:#282c33;border:1px solid #3a3f47;border-radius:4px;+ padding:1px 5px;font-size:10.5px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;+ color:#c3c9d1;+}+.hf-hint b{color:#c3c9d1;font-weight:600;}++/* ---------- 草稿条 ---------- */+.hf-draft{+ display:flex;align-items:center;gap:8px;padding:9px 14px;+ background:#2a2f2a;border-bottom:1px solid #3a4a3a;+ font-size:11.5px;color:#9fe3c0;+}+.hf-draft[hidden]{display:none;}+.hf-draft .hf-btn{padding:3px 8px;font-size:11px;margin-left:auto;}++/* ---------- 图层的可拖拽 / 选中态 ---------- */+.hf-draggable{cursor:grab;}+.hf-draggable:hover{outline:1px dashed rgba(159,227,192,.55);outline-offset:3px;}+.hf-draggable.hf-sel{+ outline:none;cursor:grab;+}+.hf-resize-overlay{+ position:absolute;z-index:9999;border:1px dashed #38bdf8;+ pointer-events:none;+}+.hf-resize-overlay[hidden]{display:none;}+.hf-resize-handle{+ position:absolute;width:32px;height:32px;border:0;background:transparent;+ pointer-events:auto;touch-action:none;+}+.hf-resize-handle::after{+ content:"";position:absolute;left:50%;top:50%;width:12px;height:12px;+ transform:translate(-50%,-50%);border:1px solid #11633d;border-radius:2px;+ background:#4ade80;box-shadow:0 0 0 1px rgba(255,255,255,.8),0 1px 5px rgba(17,24,39,.24);+}+.hf-resize-handle:hover::after{width:14px;height:14px;background:#86efac;}+.hf-resize-handle.active::after{width:14px;height:14px;background:#bbf7d0;}+.hf-resize-handle.nw{left:0;top:0;transform:translate(-50%,-50%);cursor:nwse-resize;}+.hf-resize-handle.n{left:50%;top:0;transform:translate(-50%,-50%);cursor:ns-resize;}+.hf-resize-handle.ne{right:0;top:0;transform:translate(50%,-50%);cursor:nesw-resize;}+.hf-resize-handle.e{right:0;top:50%;transform:translate(50%,-50%);cursor:ew-resize;}+.hf-resize-handle.se{right:0;bottom:0;transform:translate(50%,50%);cursor:nwse-resize;}+.hf-resize-handle.s{left:50%;bottom:0;transform:translate(-50%,50%);cursor:ns-resize;}+.hf-resize-handle.sw{left:0;bottom:0;transform:translate(-50%,50%);cursor:nesw-resize;}+.hf-resize-handle.w{left:0;top:50%;transform:translate(-50%,-50%);cursor:ew-resize;}+.hf-resize-handle:is(.n,.e,.s,.w){z-index:2;}+.hf-size-val{color:#e6e8ea;font-variant-numeric:tabular-nums;}++/* ---------- 文本编辑态 ---------- */+/* 选中图层后才提示哪些文字可编辑;否则整张海报都是文本光标,反而看不出能拖 */+.hf-sel .hf-slot:hover,+.hf-sel.hf-slot:hover{+ outline:1px dashed #38bdf8;outline-offset:2px;cursor:text;+}+.hf-editing{+ outline:2px solid #38bdf8;outline-offset:2px;+ background:rgba(56,189,248,.10);+ cursor:text;caret-color:#38bdf8;+ -webkit-user-modify:read-write-plaintext-only;+}+/* 编辑中的图层让位给文本框,不再显示拖拽提示 */+.hf-draggable:has(.hf-editing){outline:none !important;cursor:text;}++/* ---------- 吸附辅助线 ---------- */+.hf-guides{position:absolute;inset:0;pointer-events:none;z-index:9998;}+.hf-guide{position:absolute;background:#ff2d8a;}+.hf-guide.v{width:1px;top:0;bottom:0;}+.hf-guide.h{height:1px;left:0;right:0;}++/* ---------- 弹窗 ---------- */+.hf-modal{+ position:fixed;inset:0;z-index:9500;background:rgba(8,10,12,.72);+ display:flex;align-items:center;justify-content:center;padding:40px;+}+.hf-modal[hidden]{display:none;}+.hf-modal .box{+ width:min(760px,100%);max-height:100%;background:#1e2126;border:1px solid #3a3f47;+ border-radius:10px;display:flex;flex-direction:column;overflow:hidden;+}+.hf-modal .box header{+ padding:14px 16px;border-bottom:1px solid #32363d;color:#e6e8ea;+ font-size:13px;font-weight:600;display:flex;align-items:center;gap:8px;+}+.hf-modal .box header .hf-spacer{margin-left:auto;}+.hf-modal textarea{+ flex:1;min-height:340px;border:0;outline:0;resize:none;padding:14px 16px;+ background:#15171a;color:#c3c9d1;line-height:1.65;+ font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;+}++.hf-toast{+ position:fixed;left:50%;bottom:32px;transform:translateX(-50%);z-index:9600;+ background:#2f6f4f;color:#fff;padding:10px 20px;border-radius:8px;font-size:13px;+ box-shadow:0 8px 24px rgba(0,0,0,.4);+}+.hf-toast[hidden]{display:none;}diff --git a/skills/editable-design/assets/editor/layer-editor.js b/skills/editable-design/assets/editor/layer-editor.jsnew file mode 100755index 0000000..b1a2c6b--- /dev/null+++ b/skills/editable-design/assets/editor/layer-editor.js@@ -0,0 +1,1929 @@+/* ============================================================+ layer-editor —— 海报图层微调编辑器+ 与 layer-editor.css 配套。接入方式:在海报 HTML 的 </head> 前加两行+ <link rel="stylesheet" href="layer-editor.css">+ <script src="layer-editor.js" defer></script>+ 海报本体无需任何改动,移除这两行即还原为纯海报。++ 定位:微调工具,不是设计工具。只做「改位置 / 改尺寸 / 改文字 / 改字号字体 / 删图层」。+ 前置契约:画布为固定 px 尺寸并声明 data-canvas-width/height;+ 可编辑单元带 data-layer-id。详见 SKILL.md。+ ============================================================ */+(() => {+ 'use strict';++ const canvas = document.querySelector('[data-canvas-width]') || document.querySelector('.poster-canvas');+ if (!canvas) {+ console.error('[layer-editor] 找不到画布:需要一个带 data-canvas-width 的根节点');+ return;+ }+ canvas.classList.add('hf-canvas');++ const CW = +canvas.dataset.canvasWidth || canvas.offsetWidth;+ const CH = +canvas.dataset.canvasHeight || canvas.offsetHeight;+ const SNAP = 8; // 吸附阈值,画布坐标系下的像素+ const FS_STEP = 1.08; // 字号每次缩放比例+ const MIN_W = 24; // 手动缩放的最小图层宽度+ const MIN_H = 16; // 手动缩放的最小图层高度+ const sourceSignature = (() => {+ let hash = 2166136261;+ const source = canvas.outerHTML;+ for (let i = 0; i < source.length; i++) {+ hash ^= source.charCodeAt(i);+ hash = Math.imul(hash, 16777619);+ }+ return (hash >>> 0).toString(36);+ })();+ const sourceRevision = document.documentElement.dataset.hfSourceRevision || sourceSignature;+ const runtimeRevision = document.documentElement.dataset.hfRuntimeRevision || 'runtime-v1';+ const DRAFT_KEY = `hf-draft:${location.pathname}:${sourceRevision}:${runtimeRevision}`;+ const MOTION = {+ scan: 760, scanOverlap: 0.78,+ duration: 780, reverse: 620, stagger: 58,+ ease: 'cubic-bezier(.22,1,.36,1)',+ };+ const motionOff = () => matchMedia('(prefers-reduced-motion: reduce)').matches+ || new URLSearchParams(location.search).get('motion') === '0';++ const state = {+ scale: 1, sel: null, layers: [], undo: [],+ initial: new Map(), removed: [], ui: {},+ exploded: false, spread: null, spreadGeometry: new Map(),+ groups: new Map(),+ sourceCanvas: null,+ motion: [], motionToken: null, transitioning: false,+ };++ const round = (n) => Math.round(n * 10) / 10;+ const px = (n) => round(n) + 'px';+ const h = (html) => {+ const t = document.createElement('template');+ t.innerHTML = html.trim();+ return t.content.firstElementChild;+ };++ const CONTEXT_PROPS = [+ 'display', 'box-sizing', 'overflow', 'overflow-x', 'overflow-y', 'opacity',+ 'color', 'background-color', 'background-image', 'background-size',+ 'background-position', 'background-repeat', 'background-clip',+ 'border-top-width', 'border-top-style', 'border-top-color',+ 'border-right-width', 'border-right-style', 'border-right-color',+ 'border-bottom-width', 'border-bottom-style', 'border-bottom-color',+ 'border-left-width', 'border-left-style', 'border-left-color',+ 'border-top-left-radius', 'border-top-right-radius',+ 'border-bottom-right-radius', 'border-bottom-left-radius',+ 'box-shadow', 'filter', 'clip-path', 'mix-blend-mode',+ 'font-family', 'font-size', 'font-style', 'font-weight', 'font-stretch',+ 'font-variant', 'line-height', 'letter-spacing', 'word-spacing',+ 'text-align', 'text-transform', 'text-decoration-line',+ 'text-decoration-color', 'text-decoration-style', 'text-shadow',+ 'white-space', 'writing-mode',+ 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',+ 'align-items', 'align-content', 'justify-items', 'justify-content',+ 'row-gap', 'column-gap', 'grid-template-columns', 'grid-template-rows',+ 'grid-auto-flow', 'flex-direction', 'flex-wrap', 'flex-grow', 'flex-shrink',+ 'object-fit', 'object-position', 'fill', 'stroke', 'stroke-width',+ ];+ const PSEUDO_PROPS = [+ 'content', 'display', 'position', 'left', 'top', 'right', 'bottom',+ 'width', 'height', 'box-sizing', 'opacity', 'color',+ 'background-color', 'background-image', 'background-size', 'background-position',+ 'border-top-width', 'border-top-style', 'border-top-color',+ 'border-right-width', 'border-right-style', 'border-right-color',+ 'border-bottom-width', 'border-bottom-style', 'border-bottom-color',+ 'border-left-width', 'border-left-style', 'border-left-color',+ 'border-top-left-radius', 'border-top-right-radius',+ 'border-bottom-right-radius', 'border-bottom-left-radius',+ 'transform', 'transform-origin', 'box-shadow', 'filter',+ ];++ const styleSnapshot = (el, pseudo, props) => {+ const cs = getComputedStyle(el, pseudo);+ return Object.fromEntries(props.map((prop) => [prop, cs.getPropertyValue(prop)]));+ };+ const changedDeclarations = (el, pseudo, before, props) => {+ const after = getComputedStyle(el, pseudo);+ return props.filter((prop) => after.getPropertyValue(prop) !== before[prop])+ .map((prop) => `${prop}:${before[prop]};`).join('');+ };++ /* ---------------------------------------------------------------+ * 1. 布局固化+ *+ * 海报里通常只有少数图层是绝对定位的,其余活在文档流(margin 流、+ * flex)里 —— 没有 left/top 就无从拖起。这里把每个图层此刻的实际+ * 位置量出来,统一改写成相对画布的绝对坐标。+ *+ * 必须严格分成「先全部量完,再全部改写」两趟:一旦边量边改,前面的+ * 元素脱离文档流会让后面的元素往上跳,量到的就全是错的。+ * ------------------------------------------------------------- */+ function bake() {+ state.sourceCanvas = canvas.cloneNode(true);+ const layers = [...canvas.querySelectorAll('[data-layer-id]')];+ const cRect = canvas.getBoundingClientRect();+ const rel = (el) => {+ const r = el.getBoundingClientRect();+ return { left: r.left - cRect.left, top: r.top - cRect.top, width: r.width, height: r.height };+ };++ // 可选的一级内容模块契约:未标组时保持扁平内容拆解;标组时把完整+ // 模块作为一个画廊单元,不再继续钻取内部叶子。叶子提升到画布前+ // 仍要固化归属,确保下载后的 baked HTML 再接线时能恢复模块组合,+ // 而不依赖原来的 DOM 嵌套关系。+ const groupNodes = [...canvas.querySelectorAll('[data-explode-group]')];+ const groupDefs = groupNodes.map((el) => {+ const id = (el.dataset.explodeGroup || '').trim();+ const nested = layers.filter((layer) => layer.closest('[data-explode-group]') === el);+ const explicit = layers.filter((layer) => (layer.dataset.explodeParent || '').trim() === id);+ const members = [...new Set([...nested, ...explicit])];+ return {+ id, el,+ label: (el.dataset.explodeLabel || id).trim() || id,+ members,+ memberIds: members.map((layer) => layer.dataset.layerId),+ box: rel(el),+ };+ }).filter((group) => group.id && group.members.length >= 2);+ state.groups = new Map(groupDefs.map((group) => [group.id, group]));+ for (const group of groupDefs) {+ for (const member of group.members) member.dataset.explodeParent = group.id;+ }++ // 提升叶子后仍要复刻原来的组内绘制顺序:surface/image 在底层,+ // 留在组容器里的分隔线、遮罩和轨道居中,copy/icon/decoration 在上层。+ // 每个顶层模块占用独立的 z 段,模块之间继续遵循原 DOM 顺序。+ const topChildren = [...canvas.children];+ const topOf = (el) => {+ let top = el;+ while (top.parentElement && top.parentElement !== canvas) top = top.parentElement;+ return top;+ };+ // 顶层绘制顺序不能只看 DOM 顺序:显式 z-index 会让较早出现的装饰+ // 盖到较晚元素之上。先按浏览器的粗粒度 stacking 顺序排一次,+ // 再给每个顶层模块分配独立 z 段。+ const topPaintOrder = [...topChildren].sort((a, b) => {+ const za = getComputedStyle(a).zIndex;+ const zb = getComputedStyle(b).zIndex;+ const na = za === 'auto' || !Number.isFinite(+za) ? 0 : +za;+ const nb = zb === 'auto' || !Number.isFinite(+zb) ? 0 : +zb;+ return na - nb || topChildren.indexOf(a) - topChildren.indexOf(b);+ });+ const topRank = new Map(topPaintOrder.map((el, index) => [el, (index + 1) * 100]));+ const stackBase = (el) => topRank.get(topOf(el)) || 100;+ for (const top of topChildren) {+ // 未被标成叶子图层的顶层视觉(背景图、scrim、路线装饰)也要进入+ // 同一套绘制顺序,否则提升后的图层会无条件盖过它们。+ top.style.zIndex = String(stackBase(top) + 30);+ }+ const memberGroup = new Map();+ for (const group of groupDefs) {+ group.stackBase = stackBase(group.el);+ // 有独立 surface 叶子的模块通常把容器留给分隔线/遮罩,容器应位于+ // surface/image 与 copy 之间;若没有 surface 叶子,容器自身往往+ // 就是卡片底色,必须放在 image 之下,不能把照片盖住。+ const hasSurface = group.members.some((member) => member.dataset.explodeRole === 'surface');+ group.el.style.zIndex = String(group.stackBase + (hasSurface ? 30 : 10));+ for (const member of group.members) memberGroup.set(member, group);+ }+ const stackZ = (el) => {+ const group = memberGroup.get(el);+ if (!group) return String(stackBase(el) + 50);+ const role = (el.dataset.explodeRole || 'copy').trim();+ const rank = { surface: 10, image: 20, copy: 40, icon: 45, decoration: 46 }[role] || 40;+ return String(group.stackBase + rank);+ };++ // 图层被抽走后,原先靠内容撑开的容器会塌陷;用 bottom 定位的容器+ // 一塌陷,容器内未被抽走的元素(如分隔线)就会整体位移。先钉死尺寸。+ const holders = new Set();+ for (const el of layers) {+ for (let p = el.parentElement; p && p !== canvas; p = p.parentElement) holders.add(p);+ }++ const layerBox = layers.map((el) => {+ const computed = getComputedStyle(el);+ return {+ el, id: el.dataset.layerId, box: rel(el), z: stackZ(el),+ // getBoundingClientRect() 是 transform 之后的可见包围盒,不能把它+ // 直接写回 width/height 再重新施加 transform。保存布局尺寸与矩阵,+ // 提升到画布后再用包围盒差值校准 left/top。+ layoutWidth: parseFloat(computed.width) || el.offsetWidth,+ layoutHeight: parseFloat(computed.height) || el.offsetHeight,+ transform: computed.transform,+ transformOrigin: computed.transformOrigin,+ scrollWidth: el.scrollWidth, scrollHeight: el.scrollHeight,+ context: styleSnapshot(el, null, CONTEXT_PROPS),+ before: styleSnapshot(el, '::before', PSEUDO_PROPS),+ after: styleSnapshot(el, '::after', PSEUDO_PROPS),+ };+ });+ const holderBox = [...holders].map((el) => ({+ el, box: rel(el),+ local: { left: el.offsetLeft, top: el.offsetTop },+ }));++ for (const { el, box, local } of holderBox) {+ if (getComputedStyle(el).position === 'absolute') {+ // holder 仍留在原父级,left/top 必须使用父级坐标。旧实现写入+ // 画布坐标,会让嵌套容器把父级偏移再加一次,产生大面积漂移。+ Object.assign(el.style, { left: px(local.left), top: px(local.top), right: 'auto', bottom: 'auto' });+ }+ Object.assign(el.style, { width: px(box.width), height: px(box.height), pointerEvents: 'none' });+ }++ // 提升到画布直属子节点,让所有图层共用同一个坐标系。+ // 插入位置紧跟原来的顶层祖先,以维持原有的绘制顺序。+ const anchors = new Map();+ for (const { el, box, z, layoutWidth, layoutHeight, transform, transformOrigin } of layerBox) {+ let top = el;+ while (top.parentElement !== canvas) top = top.parentElement;+ if (top !== el) {+ (anchors.get(top) || top).insertAdjacentElement('afterend', el);+ anchors.set(top, el);+ }+ Object.assign(el.style, {+ position: 'absolute',+ left: px(box.left), top: px(box.top), width: px(layoutWidth), height: px(layoutHeight),+ right: 'auto', bottom: 'auto',+ margin: '0',+ transform, transformOrigin,+ pointerEvents: 'auto',+ });+ if (z) el.style.zIndex = z;+ el.classList.add('hf-draggable');+ }++ // 旋转/位移后的 bounding box 左上角通常不等于 CSS left/top;第一次+ // 写入只是临时锚点。按原始可见包围盒反算一次锚点,保持旋转的回形针、+ // 邮戳、手写贴纸等逐像素落在原处。+ for (const rec of layerBox) {+ const visible = rel(rec.el);+ rec.el.style.left = px(parseFloat(rec.el.style.left) + rec.box.left - visible.left);+ rec.el.style.top = px(parseFloat(rec.el.style.top) + rec.box.top - visible.top);+ }++ // 图层离开语义容器后,`.dark-card .label` 这类上下文选择器不再+ // 命中。只把确实发生变化的视觉属性固化为内联值;同时为伪元素+ // 生成最小覆盖规则。这样既保留原稿,又不把整份 computed style+ // 粗暴复制进导出物。+ const pseudoRules = [];+ for (const rec of layerBox) {+ const current = getComputedStyle(rec.el);+ for (const prop of CONTEXT_PROPS) {+ if (current.getPropertyValue(prop) !== rec.context[prop]) {+ rec.el.style.setProperty(prop, rec.context[prop]);+ }+ }+ // shrink-to-fit 文本的测量值带小数;写回到 0.1px 后偶尔会少掉+ // 几百分之一像素,恰好触发多一行换行。只在真实 scroll 尺寸+ // 超过原稿时逐像素补宽,最多 8px,不碰正常固定宽度图层。+ for (let extra = 0; extra < 8 && (+ rec.el.scrollHeight > rec.scrollHeight + .5+ || rec.el.scrollWidth > rec.scrollWidth + .5+ ); extra++) {+ rec.el.style.width = px(parseFloat(rec.el.style.width) + 1);+ }+ const escaped = rec.id.replace(/\\/g, '\\\\').replace(/"/g, '\\"');+ const beforeDecl = changedDeclarations(rec.el, '::before', rec.before, PSEUDO_PROPS);+ const afterDecl = changedDeclarations(rec.el, '::after', rec.after, PSEUDO_PROPS);+ if (beforeDecl) pseudoRules.push(`[data-layer-id="${escaped}"]::before{${beforeDecl}}`);+ if (afterDecl) pseudoRules.push(`[data-layer-id="${escaped}"]::after{${afterDecl}}`);+ }+ if (pseudoRules.length) {+ const style = document.createElement('style');+ style.dataset.hfRuntimeContext = '1';+ style.textContent = pseudoRules.join('\n');+ document.head.appendChild(style);+ }++ state.layers = layerBox.map(({ el, id }) => ({ el, id }));+ for (const { el, id } of state.layers) {+ state.initial.set(id, {+ left: parseFloat(el.style.left), top: parseFloat(el.style.top),+ width: parseFloat(el.style.width), height: parseFloat(el.style.height),+ });+ }+ }++ // 元素移出原容器后会丢掉继承来的层级,先把最近一个显式 z-index 记下来+ function inheritedZ(el) {+ for (let n = el; n && n !== canvas; n = n.parentElement) {+ const z = getComputedStyle(n).zIndex;+ if (z !== 'auto') return z;+ }+ return '';+ }++ /* ---------------------------------------------------------------+ * 2. 文本槽+ *+ * 可编辑单元是「文本槽」而非整个图层:价格这类图层内部靠多个不同+ * 字号的 span 拼出排版,整块设成 contenteditable 的话,一个退格就+ * 能删掉 span,样式随之崩掉。所以只把承载文字的叶子节点标为可编辑。+ * ------------------------------------------------------------- */+ function markSlots() {+ for (const { el } of state.layers) {+ for (const slot of findSlots(el)) slot.classList.add('hf-slot');+ }+ }++ function findSlots(root) {+ const out = [];+ (function walk(n) {+ if (n instanceof SVGElement) return; // 二维码、装饰图形不参与文本编辑+ // 叶子节点,或「加 <b>3</b> 元升级」这种图文混排,都作为一个整体编辑+ const ownText = [...n.childNodes].some((c) => c.nodeType === 3 && c.textContent.trim());+ if (!n.children.length || ownText) {+ if (n.textContent.trim()) out.push(n);+ return;+ }+ for (const c of n.children) walk(c);+ })(root);+ return out;+ }++ // 图层自身可能就是一个槽(此时它内部不会再有子槽)+ const slotsOf = (layer) => {+ const out = layer.classList.contains('hf-slot') ? [layer] : [];+ out.push(...layer.querySelectorAll('.hf-slot'));+ return out;+ };++ /* ---------------------------------------------------------------+ * 3. 编辑器 UI(全部动态创建,海报 HTML 里不留痕迹)+ * ------------------------------------------------------------- */+ function buildUI() {+ const title = (document.title || '海报').slice(0, 40);+ const bar = h(`+ <div class="hf-bar">+ <span class="hf-title">${title}</span>+ <span class="hf-sep"></span>+ <button class="hf-btn" id="hf-undo" disabled>撤销</button>+ <button class="hf-btn" id="hf-reset">还原初始布局</button>+ <button class="hf-btn" id="hf-explode">拆解视图</button>+ <span class="hf-sep"></span>+ <button class="hf-btn primary" id="hf-save">下载 HTML</button>+ <button class="hf-btn" id="hf-explode-save">下载拆解稿</button>+ <button class="hf-btn" id="hf-css">复制定位 CSS</button>+ <label class="hf-zoom">缩放+ <input type="range" id="hf-scale" min="10" max="100" step="1">+ <output id="hf-scale-out">—</output>+ </label>+ </div>`);++ const panel = h(`+ <div class="hf-panel">+ <div class="hf-draft" id="hf-draft" hidden>+ <span id="hf-draft-msg"></span>+ <button class="hf-btn" id="hf-draft-drop">丢弃草稿</button>+ </div>+ <h4>图层</h4>+ <div class="hf-layers" id="hf-layers"></div>+ <div class="hf-props" id="hf-props" hidden>+ <h4 style="padding-left:0">属性</h4>+ <div class="hf-field">+ <label>字号</label>+ <div class="hf-step">+ <button class="hf-btn" id="hf-fs-down">A−</button>+ <span class="val" id="hf-fs-val">—</span>+ <button class="hf-btn" id="hf-fs-up">A+</button>+ </div>+ </div>+ <div class="hf-field">+ <label>尺寸</label>+ <span class="hf-size-val" id="hf-size-val">—</span>+ </div>+ <div class="hf-field" id="hf-ff-field">+ <label>字体</label>+ <select id="hf-ff"></select>+ </div>+ <button class="hf-btn danger" id="hf-del">删除此图层</button>+ </div>+ <div class="hf-hint">+ <b>单击</b>选中并拖动 <b>绿色手柄</b>改宽高<br>+ <b>双击</b>改文字 <b>角点</b>同时改宽高<br>+ <kbd>方向键</kbd> 微调 1px <kbd>Shift</kbd>+<kbd>方向键</kbd> 10px<br>+ <kbd>Alt</kbd> 临时关闭吸附 <kbd>Delete</kbd> 删除图层<br>+ <kbd>Enter</kbd> 提交文字 <kbd>Esc</kbd> 放弃本次修改<br>+ <kbd>⌘Z</kbd> 撤销 <kbd>⌘S</kbd> 下载+ </div>+ </div>`);++ const modal = h(`+ <div class="hf-modal" id="hf-modal" hidden>+ <div class="box">+ <header>+ <span id="hf-modal-title">导出</span>+ <button class="hf-btn hf-spacer" id="hf-modal-copy">复制</button>+ <button class="hf-btn" id="hf-modal-close">关闭</button>+ </header>+ <textarea id="hf-modal-text" spellcheck="false" readonly></textarea>+ </div>+ </div>`);++ const toast = h('<div class="hf-toast" id="hf-toast" hidden></div>');+ document.body.append(bar, panel, modal, toast);+ for (const id of ['undo', 'reset', 'explode', 'save', 'explode-save', 'css', 'scale', 'scale-out', 'layers', 'props',+ 'fs-down', 'fs-up', 'fs-val', 'size-val', 'ff', 'ff-field', 'del', 'modal', 'modal-title',+ 'modal-text', 'modal-copy', 'modal-close', 'toast', 'draft', 'draft-msg', 'draft-drop']) {+ state.ui[id] = document.getElementById('hf-' + id);+ }+ }++ const $ = (id) => state.ui[id];++ /* ---------------------------------------------------------------+ * 4. 舞台与缩放:画布通常放不进屏幕,整体 scale 显示+ * ------------------------------------------------------------- */+ const guides = Object.assign(document.createElement('div'), { className: 'hf-guides' });+ const resizeOverlay = h(`+ <div class="hf-resize-overlay" hidden>+ <i class="hf-resize-handle nw" data-hf-resize-dir="nw"></i>+ <i class="hf-resize-handle n" data-hf-resize-dir="n"></i>+ <i class="hf-resize-handle ne" data-hf-resize-dir="ne"></i>+ <i class="hf-resize-handle e" data-hf-resize-dir="e"></i>+ <i class="hf-resize-handle se" data-hf-resize-dir="se"></i>+ <i class="hf-resize-handle s" data-hf-resize-dir="s"></i>+ <i class="hf-resize-handle sw" data-hf-resize-dir="sw"></i>+ <i class="hf-resize-handle w" data-hf-resize-dir="w"></i>+ </div>`);+ let stage;++ function buildStage() {+ document.body.classList.add('hf-on');+ const wrap = Object.assign(document.createElement('div'), { className: 'hf-stage-wrap' });+ stage = Object.assign(document.createElement('div'), { className: 'hf-stage' });+ document.body.insertBefore(wrap, document.body.firstChild);+ wrap.appendChild(stage);+ stage.appendChild(canvas);+ stage.appendChild(guides);+ stage.appendChild(resizeOverlay);+ setScale(fitScale());+ }++ const fitScale = () => {+ const w = state.exploded && state.spread ? state.spread.width : CW;+ const h = state.exploded && state.spread ? state.spread.height : CH;+ return Math.min((window.innerWidth - 300 - 96) / w, (window.innerHeight - 52 - 72) / h);+ };++ function setScale(s) {+ state.scale = Math.max(0.1, Math.min(1, s));+ if (state.exploded && state.spread) {+ state.spread.board.style.transform = `scale(${state.scale})`;+ stage.style.width = state.spread.width * state.scale + 'px';+ stage.style.height = state.spread.height * state.scale + 'px';+ } else {+ canvas.style.transform = `scale(${state.scale})`;+ stage.style.width = CW * state.scale + 'px';+ stage.style.height = CH * state.scale + 'px';+ }+ $('scale').value = Math.round(state.scale * 100);+ $('scale-out').textContent = Math.round(state.scale * 100) + '%';+ updateResizeOverlay();+ }++ /* ---------------------------------------------------------------+ * 5. 拆解视图+ *+ * 把当前已经固化的成稿拆成完整总览、背景基底与一级内容模块,+ * 再铺成横向组件画廊;内容仍保留原 DOM / CSS,不改编辑状态。+ * ------------------------------------------------------------- */+ const cleanClone = (root) => {+ for (const n of [root, ...root.querySelectorAll('*')]) {+ if (n.classList) {+ for (const c of [...n.classList]) if (c.startsWith('hf-')) n.classList.remove(c);+ if (!n.getAttribute('class')) n.removeAttribute('class');+ }+ n.removeAttribute('contenteditable');+ for (const a of [...n.attributes]) if (a.name.startsWith('data-hf-')) n.removeAttribute(a.name);+ }+ root.style.transform = '';+ return root;+ };++ const finishExplodedSource = (copy, transparent = false, marker = 'layer') => {+ for (const n of copy.querySelectorAll('[data-layer-id]')) {+ if (marker === 'layer') {+ n.dataset.explodedLayer = n.dataset.layerId;+ const live = state.layers.find((layer) => layer.id === n.dataset.layerId)?.el;+ const opacity = live ? Number.parseFloat(getComputedStyle(live).opacity) : 1;+ if (Number.isFinite(opacity) && opacity < .55) {+ n.style.opacity = String(Math.max(.46, Math.min(.68, opacity * 1.8)));+ n.dataset.explodedVisibilityBoosted = '1';+ }+ }+ if (marker === 'reference') n.dataset.explodedReferenceLayer = n.dataset.layerId;+ n.removeAttribute('data-layer-id');+ }+ copy.classList.add('hf-exploded-source');+ Object.assign(copy.style, {+ position: 'absolute', left: '0', top: '0',+ transform: 'none', transformOrigin: 'top left',+ });+ if (transparent) Object.assign(copy.style, { background: 'transparent', boxShadow: 'none' });+ return copy;+ };++ const parseColor = (value) => {+ const raw = String(value);+ const rgb = raw.match(/rgba?\((\d+(?:\.\d+)?)[, ]+(\d+(?:\.\d+)?)[, ]+(\d+(?:\.\d+)?)(?:\s*[,/]\s*(\d*(?:\.\d+)?))?/i);+ if (rgb) return { rgb: rgb.slice(1, 4).map(Number), alpha: rgb[4] === undefined ? 1 : Number(rgb[4]) };+ const hex = raw.match(/#([0-9a-f]{6}|[0-9a-f]{3})(?![0-9a-f])/i);+ if (!hex) return null;+ const value6 = hex[1].length === 3 ? [...hex[1]].map((c) => c + c).join('') : hex[1];+ return {+ rgb: [0, 2, 4].map((i) => parseInt(value6.slice(i, i + 2), 16)), alpha: 1,+ };+ };++ function posterBackgroundRGB() {+ const cs = getComputedStyle(canvas);+ const solid = parseColor(cs.backgroundColor);+ if (solid && solid.alpha > .25) return solid.rgb;+ // 许多纸张海报用纯渐变覆盖整块画布,background-color 本身是+ // transparent。此时从 background-image 中选第一个近乎不透明的颜色;+ // 低透明度网点/纹理不应把暖白纸张误判成黑色舞台。+ const tokens = String(cs.backgroundImage).match(/#[0-9a-f]{3,8}|rgba?\([^)]*\)/ig) || [];+ for (const token of tokens) {+ const parsed = parseColor(token);+ if (parsed && parsed.alpha > .65) return parsed.rgb;+ }+ // 最后退到页面底色;仍透明时使用中性暖白。+ for (const el of [canvas.parentElement, document.body, document.documentElement]) {+ if (!el) continue;+ const parsed = parseColor(getComputedStyle(el).backgroundColor);+ if (parsed && parsed.alpha > .25) return parsed.rgb;+ }+ return [244, 241, 232];+ }++ function explodedTheme() {+ const rgb = posterBackgroundRGB();+ const linear = rgb.map((n) => {+ const c = n / 255;+ return c <= .03928 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4;+ });+ const light = linear[0] * .2126 + linear[1] * .7152 + linear[2] * .0722 > .52;+ const bg = `rgb(${rgb.map((n) => Math.round(n)).join(',')})`;+ const labelRGB = rgb.map((n) => Math.max(0, Math.min(255, Math.round(n * .42))));+ return light ? {+ kind: 'light', bg, fg: '#26313a',+ border: 'rgba(38,49,58,.28)', labelBg: 'rgba(255,255,255,.92)',+ labelFg: '#26313a', shadow: 'rgba(31,42,48,.18)',+ } : {+ kind: 'dark', bg, fg: '#f7fbff',+ border: 'rgba(247,251,255,.40)', labelBg: `rgba(${labelRGB.join(',')},.88)`,+ labelFg: '#f7fbff', shadow: 'rgba(0,0,0,.34)',+ };+ }++ function applyExplodedTheme(board) {+ const theme = explodedTheme();+ board.dataset.explodedTheme = theme.kind;+ board.style.setProperty('--hf-exploded-bg', theme.bg);+ board.style.setProperty('--hf-exploded-fg', theme.fg);+ board.style.setProperty('--hf-exploded-border', theme.border);+ board.style.setProperty('--hf-exploded-label-bg', theme.labelBg);+ board.style.setProperty('--hf-exploded-label-fg', theme.labelFg);+ board.style.setProperty('--hf-exploded-shadow', theme.shadow);+ return theme;+ }++ function isolatedCanvas(layerId = null) {+ const copy = cleanClone(canvas.cloneNode(true));+ copy.querySelectorAll('script').forEach((n) => n.remove());+ const layerNodes = [...copy.querySelectorAll('[data-layer-id]')];+ if (layerId) {+ const keep = layerNodes.find((n) => n.dataset.layerId === layerId);+ for (const child of [...copy.children]) if (child !== keep) child.remove();+ } else {+ for (const n of layerNodes) n.remove();+ // 背景组件不重复呈现已被抽成一级内容模块的表面。+ for (const n of [...copy.querySelectorAll('[data-explode-group]')]) {+ if (state.groups.has(n.dataset.explodeGroup)) n.remove();+ }+ }+ return finishExplodedSource(copy, !!layerId, 'layer');+ }++ function isolatedOverviewCanvas() {+ const copy = cleanClone(canvas.cloneNode(true));+ copy.querySelectorAll('script').forEach((n) => n.remove());+ return finishExplodedSource(copy, false, 'none');+ }++ const topChildOf = (root, node) => {+ let top = node;+ while (top && top.parentElement !== root) top = top.parentElement;+ return top;+ };++ function isolatedGroupCanvas(groupId) {+ const group = state.groups.get(groupId);+ const copy = cleanClone(canvas.cloneNode(true));+ copy.querySelectorAll('script').forEach((n) => n.remove());+ if (!group) return finishExplodedSource(copy, true, 'layer');++ const memberIds = new Set(group.memberIds);+ const target = [...copy.querySelectorAll('[data-explode-group]')]+ .find((n) => n.dataset.explodeGroup === groupId);+ const keepTop = target ? topChildOf(copy, target) : null;+ for (const child of [...copy.children]) {+ const member = child.dataset.layerId && memberIds.has(child.dataset.layerId);+ if (child !== keepTop && !member) child.remove();+ }+ if (keepTop) {+ for (const n of [...keepTop.querySelectorAll('[data-explode-group]')]) {+ if (n.dataset.explodeGroup !== groupId) {+ // Grid/Flex 模块不能直接删兄弟:目标卡会自动补到第一个槽位,+ // 原坐标裁切时便只剩提升后的文字,卡片底色已经跑走。隐藏但保留+ // 占位,既维持布局轨道,又不会把其他模块画进当前切片。+ n.style.visibility = 'hidden';+ n.setAttribute('aria-hidden', 'true');+ }+ }+ }+ for (const n of [...copy.querySelectorAll('[data-layer-id]')]) {+ if (!memberIds.has(n.dataset.layerId)) n.remove();+ }+ return finishExplodedSource(copy, true, 'layer');+ }++ const cropOf = (g) => {+ const pad = Math.min(84, Math.max(16, Math.max(CW, CH) * 0.035));+ const left = Math.max(0, g.left - pad);+ const top = Math.max(0, g.top - pad);+ const right = Math.min(CW, g.left + g.width + pad);+ const bottom = Math.min(CH, g.top + g.height + pad);+ return { left, top, width: Math.max(1, right - left), height: Math.max(1, bottom - top) };+ };++ function makeExplodedItem(rec, scale, interactive) {+ const tile = Object.assign(document.createElement('div'), { className: 'hf-exploded-item' });+ tile.dataset.layerName = rec.id;+ tile.dataset.explodedUnit = rec.kind;+ if (rec.supplementalText) tile.dataset.explodedTextSupplement = '1';+ if (rec.kind === 'group') tile.dataset.explodedGroup = rec.group.id;+ if (rec.kind === 'background') tile.dataset.explodedBackground = '1';+ if (rec.kind === 'overview') tile.dataset.explodedOverview = '1';+ tile.title = rec.label || rec.id;+ tile.style.width = px(rec.crop.width * scale);+ tile.style.height = px(rec.crop.height * scale);+ tile.style.zIndex = rec.kind === 'overview' ? '30' : rec.kind === 'background' ? '1' : '10';++ const crop = Object.assign(document.createElement('div'), { className: 'hf-exploded-crop' });+ Object.assign(crop.style, {+ width: px(rec.crop.width), height: px(rec.crop.height),+ transform: `scale(${scale})`, transformOrigin: 'top left',+ });+ const source = rec.kind === 'group' ? isolatedGroupCanvas(rec.group.id)+ : rec.kind === 'overview' ? isolatedOverviewCanvas()+ : rec.kind === 'background' ? isolatedCanvas()+ : isolatedCanvas(rec.id);+ source.style.left = px(-rec.crop.left);+ source.style.top = px(-rec.crop.top);+ crop.appendChild(source);+ tile.appendChild(crop);+ if (rec.kind !== 'layer') {+ const label = Object.assign(document.createElement('div'), {+ className: 'hf-exploded-label', textContent: rec.label,+ });+ label.setAttribute('aria-hidden', 'true');+ tile.appendChild(label);+ }+ if (interactive && rec.kind !== 'group') tile.addEventListener('click', async () => {+ await setExploded(false);+ const live = state.layers.find((l) => l.id === rec.id);+ if (live) select(live.el);+ });+ return tile;+ }++ function makeExplodedBoard(interactive = true) {+ // 舞台保持与海报高度相同,并给横向组件画廊足够宽度。终态没有+ // 永久中央基底:完整成稿、背景和内容都使用同一种 tile 排布。+ const width = Math.round(Math.max(CW * 1.7, CH * 1.275));+ const height = CH;+ const margin = height * 0.045;+ const board = Object.assign(document.createElement('div'), { className: 'hf-exploded-board' });+ const theme = applyExplodedTheme(board);+ board.dataset.explodedLevel = '1';+ board.dataset.width = width;+ board.dataset.height = height;+ Object.assign(board.style, { width: px(width), height: px(height) });++ const layerRecords = state.layers.map(({ el, id }, index) => {+ const g = state.exploded && state.spreadGeometry.has(id)+ ? state.spreadGeometry.get(id) : geom(el);+ return { kind: 'layer', el, id, index, g, crop: cropOf(g), area: g.width * g.height };+ }).filter((r) => r.g.width > 0 && r.g.height > 0);+ const grouped = new Set([...state.groups.values()].flatMap((group) => group.memberIds));+ const unionBox = (records) => {+ if (!records.length) return null;+ const left = Math.min(...records.map((rec) => rec.g.left));+ const top = Math.min(...records.map((rec) => rec.g.top));+ const right = Math.max(...records.map((rec) => rec.g.left + rec.g.width));+ const bottom = Math.max(...records.map((rec) => rec.g.top + rec.g.height));+ return { left, top, width: right - left, height: bottom - top };+ };+ const moduleRecords = [...state.groups.values()].map((group) => {+ const members = group.memberIds.map((id) => layerRecords.find((rec) => rec.id === id)).filter(Boolean);+ const index = Math.min(...group.memberIds.map((id) =>+ layerRecords.find((rec) => rec.id === id)?.index ?? Number.MAX_SAFE_INTEGER));+ const memberBox = unionBox(members);+ const declared = group.box;+ const declaredArea = Math.max(0, declared.width) * Math.max(0, declared.height);+ const memberArea = memberBox ? memberBox.width * memberBox.height : 0;+ const g = declared.width > 1 && declared.height > 1 && declaredArea >= memberArea * .2+ ? declared : memberBox;+ if (!g) return null;+ return {+ kind: 'group', id: `group:${group.id}`, label: group.label, group,+ index, g, crop: cropOf(g), area: g.width * g.height,+ };+ }).filter(Boolean);+ const primaryContentRecords = [...layerRecords.filter((rec) => !grouped.has(rec.id)), ...moduleRecords];+ const isTextLayer = (rec) => {+ const role = (rec.el.dataset.explodeRole || 'copy').trim();+ if (['surface', 'image', 'icon', 'decoration'].includes(role)) return false;+ return Boolean((rec.el.innerText || rec.el.textContent || '').replace(/\s+/g, ' ').trim());+ };+ const supplementalTextRecords = primaryContentRecords.length < 5+ ? layerRecords.filter((rec) => grouped.has(rec.id) && isTextLayer(rec))+ .map((rec) => ({ ...rec, supplementalText: true }))+ : [];+ const contentRecords = [...primaryContentRecords, ...supplementalTextRecords]+ .sort((a, b) => a.index - b.index)+ .map((rec) => ({ ...rec, motionOrder: Math.min(12, rec.index + 1) }));+ const full = { left: 0, top: 0, width: CW, height: CH };+ const overview = {+ kind: 'overview', id: '__overview__', label: '完整成稿总览', index: -2,+ motionOrder: 0, g: full, crop: full, area: CW * CH,+ };+ const background = {+ kind: 'background', id: '__background__', label: '背景基底', index: Number.MAX_SAFE_INTEGER,+ motionOrder: 13, g: full, crop: full, area: CW * CH,+ };+ const records = [overview, ...contentRecords, background];+ board.dataset.explodedPrimaryCount = primaryContentRecords.length;+ board.dataset.explodedTextSupplements = supplementalTextRecords.length;++ // 动画原点仍是一张可读的完整成稿。所有 tile 先叠回这个矩形,+ // 扫描结束后再散开;overview 在最上层保证起始画面像素完整。+ const originScale = Math.min((width * 0.52) / CW, (height * 0.86) / CH, 1);+ const originW = CW * originScale, originH = CH * originScale;+ const originLeft = (width - originW) / 2, originTop = (height - originH) / 2;++ // 扫描层覆盖“尚未拆开”的中央成稿。它只负责视觉提示,不参与+ // 几何和导出图层计数;扫描结束后保持透明,由同一 WAAPI 时间线驱动。+ const scan = Object.assign(document.createElement('div'), {+ className: 'hf-exploded-scan', ariaHidden: 'true',+ });+ Object.assign(scan.style, {+ left: px(originLeft), top: px(originTop), width: px(originW), height: px(originH),+ });+ scan.append(+ Object.assign(document.createElement('div'), { className: 'hf-exploded-scan-grid' }),+ Object.assign(document.createElement('div'), { className: 'hf-exploded-scan-beam' }),+ );+ board.appendChild(scan);++ // 组件数少时两列、常规三列、极多时最多五列。列数只由组件数决定,+ // 不依赖海报题材;原始横向位置仅作为轻量偏好,避免完全打乱拓扑。+ const laneCount = Math.max(2, Math.min(5, Math.ceil(records.length / 5)));+ const laneGap = width * 0.022;+ const laneWidth = (width - margin * 2 - laneGap * (laneCount - 1)) / laneCount;+ const lanes = Array.from({ length: laneCount }, () => []);+ const weights = Array(laneCount).fill(0);+ const addToLane = (rec, lane, weight = 1) => {+ lanes[lane].push(rec);+ weights[lane] += weight;+ };+ addToLane(overview, 0, .95);+ addToLane(background, laneCount - 1, .95);+ for (const rec of [...contentRecords].sort((a, b) => b.area - a.area)) {+ const desired = Math.round(((rec.g.left + rec.g.width / 2) / CW) * (laneCount - 1));+ let lane = 0, best = Infinity;+ for (let i = 0; i < laneCount; i++) {+ const score = weights[i] + Math.abs(i - desired) * .16;+ if (score < best) { best = score; lane = i; }+ }+ addToLane(rec, lane, Math.min(1.35, rec.g.height / CH * .72 + rec.g.width / CW * .28));+ }++ const place = (items, laneIndex) => {+ items.sort((a, b) => {+ const ar = a.kind === 'overview' || a.kind === 'background' ? -1 : a.g.top;+ const br = b.kind === 'overview' || b.kind === 'background' ? -1 : b.g.top;+ return ar - br || a.index - b.index;+ });+ if (!items.length) return;+ const usableH = height - margin * 2;+ const minGap = height * 0.022;+ const prepared = items.map((rec) => ({+ rec,+ scale: rec.kind === 'overview' || rec.kind === 'background'+ ? Math.min(.42, laneWidth / rec.crop.width, height * .34 / rec.crop.height)+ : Math.min(.86, laneWidth / rec.crop.width,+ height * (items.length <= 3 ? .30 : .24) / rec.crop.height),+ }));+ const rawH = prepared.reduce((sum, p) => sum + p.rec.crop.height * p.scale, 0);+ const roomForItems = Math.max(1, usableH - minGap * Math.max(0, items.length - 1));+ const shrink = rawH > roomForItems ? roomForItems / rawH : 1;+ for (const p of prepared) p.scale *= shrink;+ const usedH = prepared.reduce((sum, p) => sum + p.rec.crop.height * p.scale, 0);+ const gap = prepared.length > 1+ ? Math.max(minGap, Math.min(height * .055, (usableH - usedH) / (prepared.length - 1))) : 0;+ const blockH = usedH + gap * Math.max(0, prepared.length - 1);+ let y = margin + Math.max(0, (usableH - blockH) / 2);+ const laneX = margin + laneIndex * (laneWidth + laneGap);+ for (const p of prepared) {+ const tile = makeExplodedItem(p.rec, p.scale, interactive);+ const tw = p.rec.crop.width * p.scale;+ const left = laneX + (laneWidth - tw) / 2;+ Object.assign(tile.style, { left: px(left), top: px(y) });+ tile.dataset.motionFromLeft = round(originLeft + p.rec.crop.left * originScale);+ tile.dataset.motionFromTop = round(originTop + p.rec.crop.top * originScale);+ tile.dataset.motionFromScale = round(originScale / p.scale);+ tile.dataset.motionOrder = p.rec.motionOrder;+ const tiltIndex = Number.isFinite(p.rec.index) ? Math.abs(p.rec.index) : laneIndex;+ tile.dataset.motionTilt = round((tiltIndex % 2 ? 1 : -1) * (0.7 + tiltIndex % 3 * 0.35));+ y += p.rec.crop.height * p.scale + gap;+ board.appendChild(tile);+ }+ };+ lanes.forEach(place);+ board.addEventListener('pointermove', () => {+ if (board.classList.contains('hf-exploded-settled')) {+ board.classList.add('hf-exploded-interacted');+ }+ }, { passive: true });+ return {+ board, width, height, layerCount: layerRecords.length, level: 1,+ laneCount, laneWidth, originScale, theme,+ primaryContentCount: primaryContentRecords.length,+ supplementalTextCount: supplementalTextRecords.length,+ };+ }++ function stopExplodedMotion() {+ for (const a of state.motion) try { a.cancel(); } catch {}+ state.motion = [];+ state.motionToken = null;+ }++ async function animateExploded(board, reverse = false) {+ stopExplodedMotion();+ if (!board || motionOff() || !Element.prototype.animate) {+ board?.classList.toggle('hf-exploded-settled', !reverse);+ return;+ }+ const token = Symbol('explode-motion');+ state.motionToken = token;+ board.classList.add('hf-exploded-animating');+ board.classList.remove('hf-exploded-settled', 'hf-exploded-interacted');+ const items = [...board.querySelectorAll('.hf-exploded-item')];+ const maxOrder = Math.max(0, ...items.map((n) => +n.dataset.motionOrder || 0));+ const animations = [];++ if (!reverse) {+ const scan = board.querySelector('.hf-exploded-scan');+ const grid = board.querySelector('.hf-exploded-scan-grid');+ const beam = board.querySelector('.hf-exploded-scan-beam');+ const scanH = parseFloat(scan?.style.height) || 0;+ if (scan) animations.push(scan.animate([+ { opacity: 0 },+ { offset: .08, opacity: 1 },+ { offset: .86, opacity: 1 },+ { opacity: 0 },+ ], { duration: MOTION.scan, easing: 'linear', fill: 'both' }));+ if (grid) animations.push(grid.animate([+ { opacity: 0 },+ { offset: .16, opacity: .56 },+ { offset: .78, opacity: .28 },+ { opacity: 0 },+ ], { duration: MOTION.scan, easing: MOTION.ease, fill: 'both' }));+ if (beam) animations.push(beam.animate([+ { transform: `translateY(${round(-scanH * .2)}px)`, opacity: 0 },+ { offset: .08, opacity: 1 },+ { offset: .92, opacity: 1 },+ { transform: `translateY(${round(scanH * 1.02)}px)`, opacity: 0 },+ ], { duration: MOTION.scan, easing: 'cubic-bezier(.34,0,.25,1)', fill: 'both' }));+ }++ for (const item of items) {+ const left = parseFloat(item.style.left) || 0;+ const top = parseFloat(item.style.top) || 0;+ const dx = (+item.dataset.motionFromLeft || left) - left;+ const dy = (+item.dataset.motionFromTop || top) - top;+ const fromScale = +item.dataset.motionFromScale || 1;+ const order = Math.min(12, +item.dataset.motionOrder || 0);+ const tilt = +item.dataset.motionTilt || 0;+ const origin = `translate(${round(dx)}px,${round(dy)}px) scale(${round(fromScale)}) rotate(0deg)`;+ const overshoot = `translate(0,0) scale(1.018) rotate(${tilt}deg)`;+ const frames = reverse ? [+ { transform: 'translate(0,0) scale(1) rotate(0deg)', opacity: 1, filter: 'blur(0)' },+ { offset: .2, transform: overshoot, opacity: 1, filter: 'blur(0)' },+ { transform: origin, opacity: .56, filter: 'blur(1.5px)' },+ ] : [+ { transform: origin, opacity: 1, filter: 'blur(0)' },+ { offset: .12, transform: origin, opacity: 1, filter: 'blur(0)' },+ { offset: .74, transform: overshoot, opacity: 1, filter: 'blur(0)' },+ { transform: 'translate(0,0) scale(1) rotate(0deg)', opacity: 1, filter: 'blur(0)' },+ ];+ const delay = reverse ? (maxOrder - order) * 34+ : MOTION.scan * MOTION.scanOverlap + 70 + order * MOTION.stagger;+ animations.push(item.animate(frames, {+ duration: reverse ? MOTION.reverse : MOTION.duration,+ delay, easing: MOTION.ease, fill: 'both',+ }));+ }++ state.motion = animations;+ await Promise.allSettled(animations.map((a) => a.finished));+ if (state.motionToken !== token) return;+ for (const a of animations) a.cancel();+ state.motion = [];+ state.motionToken = null;+ board.classList.remove('hf-exploded-animating');+ board.classList.toggle('hf-exploded-settled', !reverse);+ }++ function syncExplodedUI(on) {+ document.body.classList.toggle('hf-exploded-on', on);+ $('explode').classList.toggle('active', on);+ $('explode').textContent = on ? '返回编辑' : '拆解视图';+ $('undo').disabled = on || !state.undo.length;+ $('reset').disabled = on;+ $('css').disabled = on;+ }++ async function setExploded(on = !state.exploded) {+ if (state.transitioning || on === state.exploded) return;+ state.transitioning = true;+ $('explode').disabled = true;+ endEdit(true);+ try {+ if (on) {+ state.spreadGeometry = new Map(state.layers.map(({ el, id }) => [id, geom(el)]));+ if (state.spread?.board) state.spread.board.remove();+ state.spread = makeExplodedBoard(true);+ state.exploded = true;+ syncExplodedUI(true);+ select(null);+ stage.appendChild(state.spread.board);+ stage.parentElement.style.setProperty('--hf-exploded-bg', state.spread.theme.bg);+ setScale(fitScale());+ await animateExploded(state.spread.board, false);+ } else {+ await animateExploded(state.spread?.board, true);+ state.spread?.board.remove();+ state.spread = null;+ state.exploded = false;+ syncExplodedUI(false);+ stage.parentElement.style.removeProperty('--hf-exploded-bg');+ setScale(fitScale());+ }+ } finally {+ state.transitioning = false;+ $('explode').disabled = false;+ }+ }++ /* ---------------------------------------------------------------+ * 5. 拖拽+ * ------------------------------------------------------------- */+ const geom = (el) => ({+ left: parseFloat(el.style.left) || 0,+ top: parseFloat(el.style.top) || 0,+ // 拆解视图会暂时 display:none 原画布;此时 offsetWidth/Height 为 0,+ // 仍要能从固化后的内联尺寸重建并下载拆解稿。+ width: el.offsetWidth || parseFloat(el.style.width) || parseFloat(getComputedStyle(el).width) || 0,+ height: el.offsetHeight || parseFloat(el.style.height) || parseFloat(getComputedStyle(el).height) || 0,+ });++ let drag = null;++ const releaseCapture = (el, pointerId) => {+ try {+ if (el?.hasPointerCapture?.(pointerId)) el.releasePointerCapture(pointerId);+ } catch { /* 指针可能已经被浏览器释放 */ }+ };++ const discardGestureUndo = (type, el) => {+ const last = state.undo[state.undo.length - 1];+ if (last?.type === type && last.el === el) state.undo.pop();+ $('undo').disabled = !state.undo.length;+ };++ canvas.addEventListener('pointerdown', (e) => {+ if (edit && edit.slot.contains(e.target)) return; // 编辑框内,光标定位交给浏览器+ const el = e.target.closest('[data-layer-id]');+ if (!el) { select(null); return; }+ // 这里刻意不调 preventDefault:在 pointerdown 上阻止默认行为会连带抑制+ // click / dblclick 兼容事件,双击进入文本编辑就失效了。防止拖拽误选+ // 文字改由下面「真正拖起来之后」再禁用 user-select。+ select(el);+ const g = geom(el);+ drag = { el, id: e.pointerId, sx: e.clientX, sy: e.clientY, ox: g.left, oy: g.top, w: g.width, h: g.height, moved: false };+ // 指针捕获推迟到确认拖拽之后:一旦在 pointerdown 阶段就捕获,后续+ // click / dblclick 的 target 会被重定向到捕获元素,双击时拿到的就是+ // 整个图层而不是被点的那个文本槽。+ });++ canvas.addEventListener('pointermove', (e) => {+ if (!drag) return;+ if (!(e.buttons & 1)) return finishDrag(true);+ // 画布被 scale 过,屏幕位移要换算回画布坐标才不会跟手偏移+ const dx = (e.clientX - drag.sx) / state.scale;+ const dy = (e.clientY - drag.sy) / state.scale;+ if (!drag.moved && Math.hypot(dx, dy) > 2) {+ drag.moved = true;+ drag.el.setPointerCapture(drag.id); // 捕获后指针滑出元素范围也不会「掉手」+ document.body.style.userSelect = 'none';+ getSelection().removeAllRanges();+ pushUndo({ type: 'move', el: drag.el, left: drag.ox, top: drag.oy });+ }+ const snapped = e.altKey+ ? { left: drag.ox + dx, top: drag.oy + dy, lines: [] }+ : snap(drag.el, drag.ox + dx, drag.oy + dy, drag.w, drag.h);+ move(drag.el, snapped.left, snapped.top);+ drawGuides(snapped.lines);+ });++ function finishDrag(commit = true) {+ if (!drag) return;+ const current = drag;+ drag = null;+ if (!commit && current.moved) {+ Object.assign(current.el.style, { left: px(current.ox), top: px(current.oy) });+ discardGestureUndo('move', current.el);+ syncPanel();+ } else if (current.moved) touch();+ releaseCapture(current.el, current.id);+ drawGuides([]);+ document.body.style.userSelect = '';+ }+ const endDrag = () => finishDrag(true);+ const cancelDrag = () => finishDrag(false);+ canvas.addEventListener('pointerup', endDrag);+ canvas.addEventListener('pointercancel', endDrag);+ canvas.addEventListener('lostpointercapture', endDrag);+ window.addEventListener('pointerup', endDrag, true);+ window.addEventListener('pointercancel', endDrag, true);++ // 图片图层不拦的话会走浏览器原生的「拖动图片」+ canvas.addEventListener('dragstart', (e) => e.preventDefault());++ function move(el, left, top) {+ el.style.left = px(left);+ el.style.top = px(top);+ syncPanel();+ }++ // 选框放在未缩放的舞台坐标系中,手柄始终保持可点击的屏幕尺寸;+ // 图层几何与指针位移则在画布坐标系内计算。+ function updateResizeOverlay() {+ if (!stage || !state.sel || state.exploded || edit) {+ resizeOverlay.hidden = true;+ return;+ }+ const g = geom(state.sel);+ Object.assign(resizeOverlay.style, {+ left: px(g.left * state.scale),+ top: px(g.top * state.scale),+ width: px(g.width * state.scale),+ height: px(g.height * state.scale),+ });+ resizeOverlay.hidden = false;+ }++ let resize = null;++ resizeOverlay.addEventListener('pointerdown', (e) => {+ const handle = e.target.closest('[data-hf-resize-dir]');+ if (!handle || !state.sel || edit) return;+ e.preventDefault();+ e.stopPropagation();+ const g = geom(state.sel);+ resize = {+ el: state.sel, handle, id: e.pointerId, dir: handle.dataset.hfResizeDir,+ sx: e.clientX, sy: e.clientY,+ left: g.left, top: g.top, width: g.width, height: g.height,+ widthLocked: state.sel.dataset.hfWidthLocked === '1',+ heightLocked: state.sel.dataset.hfHeightLocked === '1',+ moved: false,+ };+ handle.setPointerCapture(e.pointerId);+ handle.classList.add('active');+ });++ resizeOverlay.addEventListener('pointermove', (e) => {+ if (!resize || e.pointerId !== resize.id) return;+ if (!(e.buttons & 1)) return finishResize(true, e);+ const dx = (e.clientX - resize.sx) / state.scale;+ const dy = (e.clientY - resize.sy) / state.scale;+ if (!resize.moved && Math.hypot(dx, dy) > 1) {+ resize.moved = true;+ document.body.style.userSelect = 'none';+ getSelection().removeAllRanges();+ pushUndo({+ type: 'resize', el: resize.el,+ left: resize.left, top: resize.top,+ width: resize.width, height: resize.height,+ widthLocked: resize.widthLocked, heightLocked: resize.heightLocked,+ });+ }+ if (!resize.moved) return;++ const right = resize.left + resize.width;+ const bottom = resize.top + resize.height;+ let left = resize.left, top = resize.top;+ let width = resize.width, height = resize.height;++ if (resize.dir.includes('w')) {+ left = Math.max(0, Math.min(resize.left + dx, right - MIN_W));+ width = right - left;+ } else if (resize.dir.includes('e')) {+ width = Math.max(MIN_W, Math.min(CW - resize.left, resize.width + dx));+ }+ if (resize.dir.includes('n')) {+ top = Math.max(0, Math.min(resize.top + dy, bottom - MIN_H));+ height = bottom - top;+ } else if (resize.dir.includes('s')) {+ height = Math.max(MIN_H, Math.min(CH - resize.top, resize.height + dy));+ }++ Object.assign(resize.el.style, {+ left: px(left), top: px(top), width: px(width), height: px(height),+ });+ if (resize.dir.includes('w') || resize.dir.includes('e')) resize.el.dataset.hfWidthLocked = '1';+ if (resize.dir.includes('n') || resize.dir.includes('s')) resize.el.dataset.hfHeightLocked = '1';+ syncPanel();+ });++ function finishResize(commit = true, e) {+ if (!resize || (e && e.pointerId !== resize.id)) return;+ const current = resize;+ resize = null;+ current.handle.classList.remove('active');+ if (!commit && current.moved) {+ Object.assign(current.el.style, {+ left: px(current.left), top: px(current.top),+ width: px(current.width), height: px(current.height),+ });+ if (current.widthLocked) current.el.dataset.hfWidthLocked = '1';+ else delete current.el.dataset.hfWidthLocked;+ if (current.heightLocked) current.el.dataset.hfHeightLocked = '1';+ else delete current.el.dataset.hfHeightLocked;+ discardGestureUndo('resize', current.el);+ syncPanel();+ } else if (current.moved) touch();+ releaseCapture(current.handle, current.id);+ document.body.style.userSelect = '';+ updateResizeOverlay();+ }+ const endResize = (e) => finishResize(true, e);+ const cancelResize = () => finishResize(false);+ resizeOverlay.addEventListener('pointerup', endResize);+ resizeOverlay.addEventListener('pointercancel', endResize);+ resizeOverlay.addEventListener('lostpointercapture', endResize);+ window.addEventListener('pointerup', endResize, true);+ window.addEventListener('pointercancel', endResize, true);++ const finishPointerGestures = () => {+ finishDrag(true);+ finishResize(true);+ };+ document.addEventListener('pointerdown', finishPointerGestures, true);+ window.addEventListener('blur', finishPointerGestures);+ document.addEventListener('visibilitychange', () => {+ if (document.hidden) finishPointerGestures();+ });++ // 很矮或很窄的文字层中,边中点手柄可能覆盖文字的视觉中心。+ // 双击手柄时临时移开选框重新命中,让原本的双击编辑仍可用。+ resizeOverlay.addEventListener('dblclick', (e) => {+ if (!state.sel || resize?.moved) return;+ e.preventDefault();+ e.stopPropagation();+ resizeOverlay.hidden = true;+ const slot = document.elementFromPoint(e.clientX, e.clientY)?.closest('.hf-slot');+ resizeOverlay.hidden = false;+ if (slot && state.sel.contains(slot)) beginEdit(slot, state.sel);+ });++ /* ---------------------------------------------------------------+ * 6. 吸附:对齐画布中线/边缘,以及其它图层的边和中心+ * ------------------------------------------------------------- */+ function snap(el, left, top, w, h) {+ const vt = [0, CW / 2, CW], ht = [0, CH / 2, CH];+ for (const { el: o } of state.layers) {+ if (o === el) continue;+ const g = geom(o);+ vt.push(g.left, g.left + g.width / 2, g.left + g.width);+ ht.push(g.top, g.top + g.height / 2, g.top + g.height);+ }+ const axis = (edges, targets) => {+ let best = null;+ for (const edge of edges) {+ for (const t of targets) {+ const d = Math.abs(edge - t);+ if (d <= SNAP && (!best || d < best.d)) best = { d, delta: t - edge, at: t };+ }+ }+ return best;+ };+ const v = axis([left, left + w / 2, left + w], vt);+ const hh = axis([top, top + h / 2, top + h], ht);+ const lines = [];+ if (v) lines.push({ dir: 'v', at: v.at });+ if (hh) lines.push({ dir: 'h', at: hh.at });+ return { left: left + (v ? v.delta : 0), top: top + (hh ? hh.delta : 0), lines };+ }++ function drawGuides(lines) {+ guides.textContent = '';+ for (const l of lines) {+ const d = document.createElement('div');+ d.className = 'hf-guide ' + l.dir;+ d.style[l.dir === 'v' ? 'left' : 'top'] = l.at * state.scale + 'px';+ guides.appendChild(d);+ }+ }++ /* ---------------------------------------------------------------+ * 7. 选中、撤销、面板+ * ------------------------------------------------------------- */+ function select(el) {+ if (state.sel) state.sel.classList.remove('hf-sel');+ state.sel = el;+ if (el) el.classList.add('hf-sel');+ syncPanel();+ }++ // 位置 / 文字 / 样式 / 删除共用一个栈,保证 ⌘Z 的时间顺序符合直觉+ function pushUndo(entry) {+ state.undo.push(entry);+ $('undo').disabled = false;+ }++ function undo() {+ const last = state.undo.pop();+ if (last) {+ if (last.type === 'text') {+ last.slot.innerHTML = last.html;+ refit(last.layer);+ } else if (last.type === 'style') {+ last.slots.forEach((s, i) => { s.style[last.prop] = last.before[i]; });+ refit(last.layer);+ } else if (last.type === 'remove') {+ last.parent.insertBefore(last.el, last.next);+ state.layers.splice(last.idx, 0, { el: last.el, id: last.id });+ state.removed = state.removed.filter((id) => id !== last.id);+ rebuildPanel();+ } else if (last.type === 'resize') {+ Object.assign(last.el.style, {+ left: px(last.left), top: px(last.top),+ width: px(last.width), height: px(last.height),+ });+ if (last.widthLocked) last.el.dataset.hfWidthLocked = '1';+ else delete last.el.dataset.hfWidthLocked;+ if (last.heightLocked) last.el.dataset.hfHeightLocked = '1';+ else delete last.el.dataset.hfHeightLocked;+ syncPanel();+ } else {+ move(last.el, last.left, last.top);+ }+ }+ $('undo').disabled = !state.undo.length;+ touch();+ }++ function rebuildPanel() {+ const list = $('layers');+ list.textContent = '';+ for (const { el, id } of state.layers) {+ const row = h('<div class="hf-layer"><span class="dot"></span><span class="nm"></span><span class="pos"></span></div>');+ row.querySelector('.nm').textContent = id;+ row.addEventListener('click', async () => {+ if (state.exploded) await setExploded(false);+ select(el);+ });+ list.appendChild(row);+ }+ syncPanel();+ }++ function syncPanel() {+ const list = $('layers');+ if (list.children.length !== state.layers.length) return rebuildPanel();+ state.layers.forEach(({ el }, i) => {+ const row = list.children[i];+ const g = geom(el);+ row.classList.toggle('sel', el === state.sel);+ row.querySelector('.pos').textContent = `${Math.round(g.left)}, ${Math.round(g.top)} · ${Math.round(g.width)}×${Math.round(g.height)}`;+ });+ updateResizeOverlay();+ syncProps();+ }++ function syncProps() {+ const box = $('props');+ if (!state.sel) { box.hidden = true; return; }+ box.hidden = false;+ const g = geom(state.sel);+ $('size-val').textContent = `${Math.round(g.width)} × ${Math.round(g.height)} px`;+ const slots = slotsOf(state.sel);+ if (slots.length) {+ $('fs-val').textContent = Math.round(parseFloat(getComputedStyle(slots[0]).fontSize)) + 'px';+ $('fs-up').disabled = $('fs-down').disabled = false;+ } else {+ $('fs-val').textContent = '无文字';+ $('fs-up').disabled = $('fs-down').disabled = true;+ }+ $('ff').disabled = !slots.length;+ }++ /* ---------------------------------------------------------------+ * 8. 文本编辑+ * ------------------------------------------------------------- */+ let edit = null;++ function beginEdit(slot, layer) {+ if (edit) endEdit(true);+ edit = { slot, layer, html: slot.innerHTML };+ slot.setAttribute('contenteditable', 'plaintext-only');+ slot.classList.add('hf-editing');+ updateResizeOverlay();+ slot.focus();+ const range = document.createRange();+ range.selectNodeContents(slot);+ const sel = getSelection();+ sel.removeAllRanges();+ sel.addRange(range);+ }++ function endEdit(commit = true) {+ if (!edit) return;+ const { slot, layer, html } = edit;+ edit = null;+ slot.removeAttribute('contenteditable');+ slot.classList.remove('hf-editing');+ if (!commit) {+ slot.innerHTML = html;+ } else if (slot.innerHTML !== html) {+ pushUndo({ type: 'text', slot, layer, html });+ refit(layer);+ touch();+ }+ getSelection().removeAllRanges();+ syncPanel();+ }++ // 文字变长或字号变大后会被图层锁定的宽度挤到换行。这里按需扩宽,+ // 但不主动收窄,免得吃掉版式上刻意留白的宽度。用户用缩放手柄+ // 明确设过宽度后则保留该宽度,让文字按用户意图换行。+ function refit(layer) {+ if (layer.dataset.hfWidthLocked === '1') {+ syncPanel();+ return;+ }+ const cur = parseFloat(layer.style.width) || 0;+ const left = parseFloat(layer.style.left) || 0;+ layer.style.width = 'max-content';+ const natural = layer.getBoundingClientRect().width / state.scale;+ layer.style.width = px(Math.min(Math.max(cur, natural), CW - left));+ syncPanel();+ }++ canvas.addEventListener('dblclick', (e) => {+ // 按坐标重新做命中测试,而不是信任 e.target:指针一旦被捕获,+ // dblclick 的 target 会被重定向到捕获元素,拿不到真正被点的文本槽。+ const slot = document.elementFromPoint(e.clientX, e.clientY)?.closest('.hf-slot');+ const layer = slot?.closest('[data-layer-id]');+ if (slot && layer) beginEdit(slot, layer);+ });++ // 点到别处即提交。capture 阶段处理,抢在拖拽逻辑之前。+ document.addEventListener('pointerdown', (e) => {+ if (edit && !edit.slot.contains(e.target)) endEdit(true);+ }, true);++ document.addEventListener('keydown', (e) => {+ if (!edit) return;+ // 输入法组字期间按键一律归输入法,此时的 Esc 是取消组字而不是退出编辑+ if (e.isComposing || e.keyCode === 229) return;+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); endEdit(true); }+ else if (e.key === 'Escape') { e.preventDefault(); endEdit(false); }+ e.stopPropagation(); // 方向键交给光标,别拿去挪图层+ }, true);++ /* ---------------------------------------------------------------+ * 9. 字号与字体+ *+ * 作用对象是图层内的全部文本槽,不引入「选中子元素」这一层交互。+ * 字号按比例缩放而非绝对赋值,一对 A−/A+ 即可覆盖微调场景。+ * ------------------------------------------------------------- */+ function applyStyle(layer, prop, valueOf) {+ const slots = slotsOf(layer);+ if (!slots.length) return;+ const before = slots.map((s) => s.style[prop]);+ slots.forEach((s) => { s.style[prop] = valueOf(s); });+ pushUndo({ type: 'style', slots, layer, prop, before });+ refit(layer);+ touch();+ }++ const scaleFont = (layer, factor) => applyStyle(layer, 'fontSize',+ (s) => round(parseFloat(getComputedStyle(s).fontSize) * factor) + 'px');++ const setFont = (layer, value) => applyStyle(layer, 'fontFamily', () => value);++ /* 字体选项只从海报 :root 已声明的字体族变量里取。+ 不提供任意字体:那需要动态注入 @font-face,中文字体动辄数 MB,+ 且导出后若引用丢失会静默回落成系统字体。 */+ function fontOptions() {+ const out = [], seen = new Set();+ for (const sheet of document.styleSheets) {+ let rules;+ try { rules = sheet.cssRules; } catch { continue; } // 跨域样式表(如 Google Fonts)不可读+ for (const rule of rules) {+ if (!rule.style || !rule.selectorText) continue;+ if (!/(^|,)\s*(:root|html)\s*(,|$)/.test(rule.selectorText)) continue;+ for (const prop of rule.style) {+ if (!prop.startsWith('--') || seen.has(prop)) continue;+ const val = rule.style.getPropertyValue(prop).trim();+ if (!/serif|sans|mono|cursive|fantasy/i.test(val)) continue;+ seen.add(prop);+ out.push({ label: prop.slice(2), value: `var(${prop})` });+ }+ }+ }+ return out;+ }++ function buildFontSelect() {+ const opts = fontOptions();+ if (!opts.length) { $('ff-field').hidden = true; return; }+ const sel = $('ff');+ sel.append(h('<option value="">(保持原样)</option>'));+ for (const o of opts) {+ const el = h('<option></option>');+ el.value = o.value;+ el.textContent = o.label;+ sel.append(el);+ }+ sel.addEventListener('change', () => {+ if (state.sel && sel.value) setFont(state.sel, sel.value);+ sel.value = '';+ });+ }++ /* ---------------------------------------------------------------+ * 10. 删除图层+ * ------------------------------------------------------------- */+ function removeLayer(layer) {+ const idx = state.layers.findIndex((l) => l.el === layer);+ if (idx < 0) return;+ const { id } = state.layers[idx];+ pushUndo({ type: 'remove', el: layer, id, idx, parent: layer.parentNode, next: layer.nextSibling });+ layer.remove();+ state.layers.splice(idx, 1);+ state.removed.push(id);+ state.sel = null;+ rebuildPanel();+ touch();+ toast(`已删除 ${id}`);+ }++ /* ---------------------------------------------------------------+ * 11. 草稿:localStorage 自动保存,刷新与误关不丢+ * ------------------------------------------------------------- */+ let draftTimer;+ function touch() {+ clearTimeout(draftTimer);+ draftTimer = setTimeout(saveDraft, 500);+ }++ function snapshot() {+ return {+ at: Date.now(),+ removed: state.removed,+ layers: state.layers.map(({ el, id }) => ({+ id,+ left: parseFloat(el.style.left) || 0,+ top: parseFloat(el.style.top) || 0,+ width: el.style.width || '',+ height: el.style.height || '',+ manualWidth: el.dataset.hfWidthLocked === '1',+ manualHeight: el.dataset.hfHeightLocked === '1',+ slots: slotsOf(el).map((s) => ({+ html: s.innerHTML, fs: s.style.fontSize || '', ff: s.style.fontFamily || '',+ })),+ })),+ };+ }++ function saveDraft() {+ try {+ localStorage.setItem(DRAFT_KEY, JSON.stringify(snapshot()));+ } catch (err) {+ console.warn('[layer-editor] 草稿保存失败', err);+ }+ }++ function loadDraft() {+ try {+ const raw = localStorage.getItem(DRAFT_KEY);+ return raw ? JSON.parse(raw) : null;+ } catch { return null; }+ }++ // 自动恢复,同时给出「丢弃草稿」入口 —— 默认不丢失用户的改动+ function applyDraft(d) {+ const byId = new Map(state.layers.map((l) => [l.id, l.el]));+ for (const rec of d.layers || []) {+ const el = byId.get(rec.id);+ if (!el) continue;+ el.style.left = px(rec.left);+ el.style.top = px(rec.top);+ if (rec.width) el.style.width = rec.width;+ if (rec.height) el.style.height = rec.height;+ if (rec.manualWidth) el.dataset.hfWidthLocked = '1';+ if (rec.manualHeight) el.dataset.hfHeightLocked = '1';+ const slots = slotsOf(el);+ (rec.slots || []).forEach((s, i) => {+ if (!slots[i]) return;+ if (s.html !== undefined) slots[i].innerHTML = s.html;+ if (s.fs) slots[i].style.fontSize = s.fs;+ if (s.ff) slots[i].style.fontFamily = s.ff;+ });+ }+ for (const id of d.removed || []) {+ const idx = state.layers.findIndex((l) => l.id === id);+ if (idx < 0) continue;+ state.layers[idx].el.remove();+ state.layers.splice(idx, 1);+ state.removed.push(id);+ }+ }++ function showDraftBar(d) {+ const t = new Date(d.at);+ const pad = (n) => String(n).padStart(2, '0');+ $('draft-msg').textContent =+ `已恢复草稿(${pad(t.getMonth() + 1)}-${pad(t.getDate())} ${pad(t.getHours())}:${pad(t.getMinutes())})`;+ $('draft').hidden = false;+ }++ function dropDraft() {+ localStorage.removeItem(DRAFT_KEY);+ location.reload();+ }++ /* ---------------------------------------------------------------+ * 12. 导出+ * ------------------------------------------------------------- */+ function positionCSS() {+ const rules = state.layers.map(({ el, id }) => {+ const g = geom(el);+ return `[data-layer-id="${id}"]{ left:${round(g.left)}px; top:${round(g.top)}px; width:${round(g.width)}px; height:${round(g.height)}px; }`;+ });+ return '/* 图层定位(前提是各图层均为 position:absolute,父级为画布) */\n' + rules.join('\n');+ }++ function fullHTML() {+ endEdit(true);+ const doc = document.documentElement.cloneNode(true);+ doc.querySelectorAll('.hf-bar,.hf-panel,.hf-modal,.hf-toast,.hf-guides,.hf-resize-overlay').forEach((n) => n.remove());+ doc.querySelectorAll('link[href*="layer-editor"],script[src*="layer-editor"]').forEach((n) => n.remove());++ const cv = doc.querySelector('.hf-canvas');+ cv.style.transform = '';+ doc.querySelector('.hf-stage-wrap').replaceWith(cv);+ doc.querySelector('body').removeAttribute('class');+ doc.querySelectorAll('[contenteditable]').forEach((n) => n.removeAttribute('contenteditable'));+ doc.querySelectorAll('[class*="hf-"]').forEach((n) => {+ n.classList.remove('hf-canvas', 'hf-draggable', 'hf-sel', 'hf-slot', 'hf-editing');+ if (!n.getAttribute('class')) n.removeAttribute('class');+ });+ // data-hf-ready 挂在 <html> 上,会被 cloneNode 一起带走+ for (const n of [doc, ...doc.querySelectorAll('*')]) {+ for (const attr of [...n.attributes]) {+ if (attr.name.startsWith('data-hf-')) n.removeAttribute(attr.name);+ }+ }+ return '<!doctype html>\n' + doc.outerHTML;+ }++ const EXPLODED_EXPORT_CSS = `+ html,body{margin:0;width:100%;height:100%;overflow:hidden;background:var(--hf-exploded-bg,#0b0c0d)}+ body.hf-exploded-export{display:flex!important;align-items:center!important;justify-content:center!important;+ padding:0!important;min-height:100%!important;background:var(--hf-exploded-bg,#0b0c0d)!important}+ .hf-exploded-shell{position:relative;flex:none;overflow:visible}+ .hf-exploded-board{position:absolute;left:0;top:0;overflow:hidden;transform-origin:top left;+ background:var(--hf-exploded-bg,#0b0c0d);color:var(--hf-exploded-fg,#f4f1e8);isolation:isolate}+ .hf-exploded-item{position:absolute;overflow:hidden;transform-origin:top left;+ will-change:transform,opacity,filter}+ .hf-exploded-scan{position:absolute;z-index:40;overflow:hidden;pointer-events:none;opacity:0;+ border-radius:18px;mix-blend-mode:screen;+ box-shadow:inset 0 0 0 1px rgba(188,255,243,.36),inset 0 0 42px rgba(113,244,222,.09)}+ .hf-exploded-scan-grid{position:absolute;inset:0;opacity:0;+ background-image:linear-gradient(rgba(151,255,237,.16) 1px,transparent 1px),+ linear-gradient(90deg,rgba(151,255,237,.16) 1px,transparent 1px);+ background-size:48px 48px;+ mask-image:linear-gradient(180deg,transparent,black 12%,black 88%,transparent)}+ .hf-exploded-scan-beam{position:absolute;left:-3%;top:0;width:106%;height:18%;opacity:0;+ background:linear-gradient(180deg,transparent 0%,rgba(118,255,231,.08) 28%,+ rgba(185,255,244,.25) 50%,rgba(255,255,255,.96) 55%,+ rgba(104,255,230,.34) 58%,transparent 100%);+ filter:drop-shadow(0 0 18px rgba(152,255,237,.9))}+ .hf-exploded-item{filter:drop-shadow(0 16px 28px var(--hf-exploded-shadow,rgba(0,0,0,.28)));+ transition:transform .22s cubic-bezier(.22,1,.36,1),filter .18s}+ .hf-exploded-item:is([data-exploded-overview],[data-exploded-background]){+ border:1px solid var(--hf-exploded-border,rgba(244,241,232,.42));border-radius:16px;box-sizing:border-box}+ .hf-exploded-label{position:absolute;left:18px;top:18px;z-index:8;max-width:calc(100% - 36px);+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap;pointer-events:none;padding:12px 18px;+ border:1px solid var(--hf-exploded-border,rgba(255,255,255,.22));border-radius:999px;+ background:var(--hf-exploded-label-bg,rgba(11,12,13,.78));+ color:var(--hf-exploded-label-fg,#f4f1e8);font:650 28px/1 -apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif;+ opacity:0;transform:translateY(6px);transition:opacity .16s ease,transform .22s cubic-bezier(.22,1,.36,1)}+ .hf-exploded-settled.hf-exploded-interacted .hf-exploded-item:is(:hover,:focus-visible) .hf-exploded-label{+ opacity:1;transform:translateY(0)}+ .hf-exploded-settled .hf-exploded-item:hover{transform:translateY(-8px) scale(1.015);+ filter:drop-shadow(0 18px 34px rgba(0,0,0,.38)) brightness(1.08)}+ .hf-exploded-animating .hf-exploded-item{pointer-events:none}+ .hf-exploded-crop{position:absolute;left:0;top:0;overflow:hidden}+ .hf-exploded-source{max-width:none!important;max-height:none!important;transform:none!important}+ .hf-exploded-replay{position:fixed;right:22px;top:20px;z-index:20;appearance:none;+ border:1px solid rgba(255,255,255,.22);border-radius:999px;padding:8px 14px;+ color:#eee;background:rgba(20,22,24,.7);backdrop-filter:blur(12px);cursor:pointer;+ font:500 12px/1 -apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif}+ .hf-exploded-replay:hover{background:rgba(42,45,49,.88);border-color:rgba(255,255,255,.38)}+ .hf-exploded-replay:disabled{opacity:.45;cursor:default}+ @media(prefers-reduced-motion:reduce){.hf-exploded-item{transition:none}.hf-exploded-scan{display:none}}+ `;++ function explodedHTML() {+ endEdit(true);+ const spread = makeExplodedBoard(false);+ const doc = document.documentElement.cloneNode(true);+ doc.querySelectorAll('script').forEach((n) => n.remove());+ doc.querySelectorAll('link[href*="layer-editor"]').forEach((n) => n.remove());+ for (const n of [doc, ...doc.querySelectorAll('*')]) {+ for (const attr of [...n.attributes]) if (attr.name.startsWith('data-hf-')) n.removeAttribute(attr.name);+ }+ const head = doc.querySelector('head');+ const style = document.createElement('style');+ style.textContent = EXPLODED_EXPORT_CSS;+ head.appendChild(style);+ const title = head.querySelector('title');+ if (title) title.textContent += ' · 分层展示';++ const body = doc.querySelector('body');+ body.textContent = '';+ body.removeAttribute('style');+ body.className = 'hf-exploded-export';+ body.style.setProperty('--hf-exploded-bg', spread.theme.bg);+ body.style.setProperty('--hf-exploded-fg', spread.theme.fg);+ body.style.setProperty('--hf-exploded-border', spread.theme.border);+ body.style.setProperty('--hf-exploded-label-bg', spread.theme.labelBg);+ body.style.setProperty('--hf-exploded-label-fg', spread.theme.labelFg);+ body.style.setProperty('--hf-exploded-shadow', spread.theme.shadow);+ const shell = Object.assign(document.createElement('div'), { className: 'hf-exploded-shell' });+ shell.appendChild(spread.board);+ body.appendChild(shell);+ const replay = Object.assign(document.createElement('button'), {+ className: 'hf-exploded-replay', textContent: '↻ 再次播放分层动画', type: 'button',+ });+ body.appendChild(replay);++ const fit = document.createElement('script');+ fit.textContent = `(() => {+ const board = document.querySelector('.hf-exploded-board');+ const shell = document.querySelector('.hf-exploded-shell');+ const replay = document.querySelector('.hf-exploded-replay');+ const w = ${spread.width}, h = ${spread.height};+ const resize = () => {+ const s = Math.min(innerWidth / w, innerHeight / h);+ board.style.transform = 'scale(' + s + ')';+ shell.style.width = (w * s) + 'px';+ shell.style.height = (h * s) + 'px';+ };+ const reduced = matchMedia('(prefers-reduced-motion:reduce)').matches+ || new URLSearchParams(location.search).get('motion') === '0';+ board.addEventListener('pointermove', () => {+ if (board.classList.contains('hf-exploded-settled')) {+ board.classList.add('hf-exploded-interacted');+ }+ }, {passive:true});+ const scanDuration = 760, scanRelease = scanDuration * .78;+ let running = [];+ const play = async () => {+ for (const a of running) try { a.cancel(); } catch {}+ running = [];+ board.classList.remove('hf-exploded-settled','hf-exploded-interacted');+ if (reduced || !Element.prototype.animate) {+ replay.hidden = true;+ board.classList.add('hf-exploded-settled');+ document.documentElement.dataset.hfMotion = 'reduced';+ return;+ }+ board.classList.add('hf-exploded-animating');+ replay.disabled = true;+ const items = [...board.querySelectorAll('.hf-exploded-item')];+ const scan = board.querySelector('.hf-exploded-scan');+ const grid = board.querySelector('.hf-exploded-scan-grid');+ const beam = board.querySelector('.hf-exploded-scan-beam');+ const scanH = parseFloat(scan?.style.height)||0;+ if (scan) running.push(scan.animate([+ {opacity:0},{offset:.08,opacity:1},{offset:.86,opacity:1},{opacity:0}+ ],{duration:scanDuration,easing:'linear',fill:'both'}));+ if (grid) running.push(grid.animate([+ {opacity:0},{offset:.16,opacity:.56},{offset:.78,opacity:.28},{opacity:0}+ ],{duration:scanDuration,easing:'cubic-bezier(.22,1,.36,1)',fill:'both'}));+ if (beam) running.push(beam.animate([+ {transform:'translateY('+(-scanH*.2)+'px)',opacity:0},+ {offset:.08,opacity:1},{offset:.92,opacity:1},+ {transform:'translateY('+(scanH*1.02)+'px)',opacity:0}+ ],{duration:scanDuration,easing:'cubic-bezier(.34,0,.25,1)',fill:'both'}));+ for (const item of items) {+ const left = parseFloat(item.style.left)||0, top = parseFloat(item.style.top)||0;+ const dx = (+item.dataset.motionFromLeft||left)-left;+ const dy = (+item.dataset.motionFromTop||top)-top;+ const scale = +item.dataset.motionFromScale||1;+ const order = Math.min(12,+item.dataset.motionOrder||0);+ const tilt = +item.dataset.motionTilt||0;+ running.push(item.animate([+ {transform:'translate('+dx+'px,'+dy+'px) scale('+scale+') rotate(0deg)',opacity:1,filter:'blur(0)'},+ {offset:.12,transform:'translate('+dx+'px,'+dy+'px) scale('+scale+') rotate(0deg)',opacity:1,filter:'blur(0)'},+ {offset:.74,transform:'translate(0,0) scale(1.018) rotate('+tilt+'deg)',opacity:1,filter:'blur(0)'},+ {transform:'translate(0,0) scale(1) rotate(0deg)',opacity:1,filter:'blur(0)'}+ ],{duration:780,delay:scanRelease+70+order*58,easing:'cubic-bezier(.22,1,.36,1)',fill:'both'}));+ }+ await Promise.allSettled(running.map((a)=>a.finished));+ for (const a of running) a.cancel();+ running=[];+ board.classList.remove('hf-exploded-animating');+ board.classList.add('hf-exploded-settled');+ replay.disabled=false;+ document.documentElement.dataset.hfMotion='played';+ };+ replay.addEventListener('click',play);+ addEventListener('resize',resize); resize();+ play().finally(()=>{document.documentElement.dataset.hfExplodedReady='1';});+ })();`;+ body.appendChild(fit);+ return '<!doctype html>\n' + doc.outerHTML;+ }++ function downloadBlob(html, name) {+ const url = URL.createObjectURL(new Blob([html], { type: 'text/html;charset=utf-8' }));+ const a = Object.assign(document.createElement('a'), { href: url, download: name });+ document.body.appendChild(a);+ a.click();+ a.remove();+ URL.revokeObjectURL(url);+ toast('已下载 ' + name);+ }++ function download() {+ const html = fullHTML();+ const base = (location.pathname.split('/').pop() || 'poster').replace(/\.html?$/i, '');+ const name = (/^(editor|index)$/i.test(base) ? 'index' : base) + '.edited.html';+ downloadBlob(html, name);+ }++ function downloadExploded() {+ const base = (location.pathname.split('/').pop() || 'poster').replace(/\.html?$/i, '');+ const name = (/^(editor|index)$/i.test(base) ? 'index' : base) + '.layers.html';+ downloadBlob(explodedHTML(), name);+ }++ function openModal(title, text) {+ $('modal-title').textContent = title;+ $('modal-text').value = text;+ $('modal').hidden = false;+ $('modal-text').select();+ }++ let toastTimer;+ function toast(msg) {+ const t = $('toast');+ t.textContent = msg;+ t.hidden = false;+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => { t.hidden = true; }, 1800);+ }++ async function copy(text) {+ try {+ await navigator.clipboard.writeText(text);+ toast('已复制到剪贴板');+ } catch {+ toast('浏览器拒绝了剪贴板访问,请手动复制');+ }+ }++ /* ---------------------------------------------------------------+ * 13. 接线+ * ------------------------------------------------------------- */+ function wire() {+ $('undo').addEventListener('click', undo);++ $('reset').addEventListener('click', () => {+ endEdit(true);+ for (const { el, id } of state.layers) {+ const p = state.initial.get(id);+ if (p) {+ el.style.left = px(p.left); el.style.top = px(p.top);+ el.style.width = px(p.width); el.style.height = px(p.height);+ delete el.dataset.hfWidthLocked;+ delete el.dataset.hfHeightLocked;+ }+ }+ state.undo.length = 0;+ $('undo').disabled = true;+ syncPanel();+ touch();+ toast('已还原到固化后的初始布局');+ });++ $('save').addEventListener('click', download);+ $('explode').addEventListener('click', () => setExploded());+ $('explode-save').addEventListener('click', downloadExploded);+ $('css').addEventListener('click', () => openModal('图层定位 CSS', positionCSS()));+ $('modal-copy').addEventListener('click', () => copy($('modal-text').value));+ $('modal-close').addEventListener('click', () => { $('modal').hidden = true; });+ $('modal').addEventListener('click', (e) => { if (e.target === $('modal')) $('modal').hidden = true; });+ $('scale').addEventListener('input', (e) => setScale(e.target.value / 100));+ $('fs-up').addEventListener('click', () => state.sel && scaleFont(state.sel, FS_STEP));+ $('fs-down').addEventListener('click', () => state.sel && scaleFont(state.sel, 1 / FS_STEP));+ $('del').addEventListener('click', () => state.sel && removeLayer(state.sel));+ $('draft-drop').addEventListener('click', dropDraft);+ window.addEventListener('resize', () => setScale(fitScale()));++ document.addEventListener('keydown', (e) => {+ if (e.key === 'Escape' && (drag || resize)) {+ e.preventDefault();+ cancelDrag();+ cancelResize();+ return;+ }+ if (edit) return; // 编辑态的按键由 §8 的 capture 处理器负责+ const mod = e.metaKey || e.ctrlKey;+ if (mod && e.key.toLowerCase() === 'z') { e.preventDefault(); return undo(); }+ if (mod && e.key.toLowerCase() === 's') { e.preventDefault(); return download(); }+ if (e.key === 'Escape') return state.exploded ? setExploded(false) : select(null);+ if (!state.sel) return;+ if (e.key === 'Delete' || e.key === 'Backspace') {+ e.preventDefault();+ return removeLayer(state.sel);+ }+ if (!e.key.startsWith('Arrow')) return;+ e.preventDefault();+ const step = e.shiftKey ? 10 : 1;+ const g = geom(state.sel);+ pushUndo({ type: 'move', el: state.sel, left: g.left, top: g.top });+ const d = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key];+ move(state.sel, g.left + d[0], g.top + d[1]);+ touch();+ });+ }++ /* 字体决定文字块的实际尺寸,图片决定图层的实际高度 —— 两者都必须+ 落地后再测量,否则固化下来的是 fallback 字体或零高图片的坐标。+ 图片加载失败也要放行,否则一张坏图会卡死整个编辑器。 */+ function ready() {+ const imgs = [...document.images].filter((i) => !i.complete).map((i) => new Promise((r) => {+ i.addEventListener('load', r, { once: true });+ i.addEventListener('error', r, { once: true });+ }));+ return Promise.all([document.fonts.ready, ...imgs]);+ }++ ready().then(() => {+ bake();+ markSlots();+ buildUI();+ buildFontSelect();+ buildStage();+ wire();+ const draft = loadDraft();+ if (draft) { applyDraft(draft); showDraftBar(draft); }+ rebuildPanel();++ /* 供 scripts/ 下的离线固化与验证脚本驱动。编辑器不加载时不存在,+ 导出的 HTML 也不含此脚本,因此不会污染产物。 */+ window.__layerEditor = {+ fullHTML, explodedHTML, positionCSS, snapshot, download, downloadExploded, undo, toast,+ select, scaleFont, setFont, removeLayer, fontOptions,+ setExploded,+ layers: () => state.layers.map(({ el, id }) => ({ el, id })),+ state,+ };+ document.documentElement.dataset.hfReady = '1'; // 自动化脚本的等待锚点+ });+})();diff --git a/skills/editable-design/assets/poster-starter/.gitignore b/skills/editable-design/assets/poster-starter/.gitignorenew file mode 100755index 0000000..205db9e--- /dev/null+++ b/skills/editable-design/assets/poster-starter/.gitignore@@ -0,0 +1,3 @@+out/+.trace/+.DS_Storediff --git a/skills/editable-design/assets/poster-starter/README.md b/skills/editable-design/assets/poster-starter/README.mdnew file mode 100755index 0000000..bffe8f3--- /dev/null+++ b/skills/editable-design/assets/poster-starter/README.md@@ -0,0 +1,92 @@+# poster-starter++A fixed-canvas poster project. The visual system may combine generated artwork,+live typography, and HTML geometry, and the included scripts make the render+reproducible.++## Prerequisites++- A Chromium-based browser (Google Chrome, Chromium, Edge, Brave)+- Set `POSTER_BROWSER=<path to executable>` if it is somewhere unusual++## Quick start++```bash+scripts/check-poster.sh index.html+scripts/render-poster.sh index.html # defaults to out/poster.png+scripts/render-poster.sh index.html out/print.png --dpi 300+scripts/render-poster.sh --probe+```++`scripts/render-poster.sh` reads the PNG's real pixel dimensions back and compares them+with `poster.json`. A browser silently returns a different size when the window+and the content disagree, and the image looks perfectly normal, so this check is+not optional.++## What is here++- `index.html` — one file, CSS inline, zero external requests. Absolute+ positioning inside the canvas, fixed px for every layout dimension+- `poster.json` — canvas size, render scale, print DPI. The renderer takes its+ expected dimensions from here+- `assets/` — generated or provided visual assets, referenced by relative path+- `reference/` — optional non-shipping composition references+- `scripts/` — local validation, asset import, tracing, and PNG rendering tools+- `editor.html` — generated at delivery time; drag layers, resize width and+ height with eight handles, double-click text, adjust type, delete, undo, scan+ and dynamically spread/collapse the layers, and download clean edited or+ exploded HTML+- `layers.html` — standalone animated layer breakdown generated at delivery+- `brief.md` — written at the start of a real run from the active user request;+ the starter does not ship a placeholder because Replay evidence must be real+- `replay/` — generated after verification; a fixed offline viewer populated+ from the run's real prompts, plans, assets, code, review, and layer output++Import a selected generated image immediately rather than leaving the project+dependent on an image-generator cache path:++```bash+scripts/import-asset.sh /path/to/generated.png assets/visual-01.png+```++After the final render has passed visual review, create the editor companion:++```bash+node scripts/wire-editor.mjs index.html+```++The complete editor runtime is bundled with `poster-building` and copied into+the project during initialization, so no second skill is required and the+project remains usable offline. The original `index.html` is never modified by+editor wiring.++After verification, generate and check the Agent Design Replay:++```bash+node scripts/build-replay.mjs .+node scripts/verify-replay.mjs replay/index.html+```++## Contract++- The root element carries `data-canvas-width` / `data-canvas-height`, its+ `width`/`height` are the same px values, and it is `position: relative`+- Fixed px for every dimension, position, and gap that carries layout. No+ vw/vh/vmin/vmax/%. Decorative values (gradient stops, radii, shadow spread,+ texture sizes) are unrestricted+- No interactivity, no media queries, no CDN+- Nothing extends past the canvas edge++## The placeholder layout is temporary++`.preview-frame`, `.preview-status`, and the placeholder strings are scaffolding,+not product. Once the first real version replaces them, delete those blocks and+their CSS, delete `<meta name="poster-preview">`, replace `<title>` and the+placeholder strings with the poster's real title and live HTML text, and delete+every unreferenced file in `assets/`. Record the sweep in+`cleanup-checklist.json`.++The preview demonstrates the fixed canvas and safe area only. It is not a+recommendation for a full-bleed image, banded composition, asset count, text+placement, or final geometry. Build those decisions from the brief and visual+reference.diff --git a/skills/editable-design/assets/poster-starter/assets/.gitkeep b/skills/editable-design/assets/poster-starter/assets/.gitkeepnew file mode 100755index 0000000..e69de29diff --git a/skills/editable-design/assets/poster-starter/index.html b/skills/editable-design/assets/poster-starter/index.htmlnew file mode 100755index 0000000..4945024--- /dev/null+++ b/skills/editable-design/assets/poster-starter/index.html@@ -0,0 +1,91 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<title>Your poster is taking shape</title>+<meta name="poster-preview" content="placeholder">+<style>+ /* Palette and font stacks live here and are referenced throughout.+ Replace them with the poster's own values. */+ :root {+ --ink: #f2ede3;+ --ink-dim: #a9a196;+ --ground: #14171a;+ --accent: #b4472a;++ --font-display: "PingFang SC", "Hiragino Sans GB", Georgia, serif;+ --font-body: "PingFang SC", "Hiragino Sans GB", Helvetica, sans-serif;+ }++ /* border-box everywhere. A layer with padding measures wider than its `width`+ under content-box, and anything that writes the measured width back - an+ editor converting the layout to absolute positioning, for instance - adds+ the padding a second time. */+ * { box-sizing: border-box; }++ html, body { margin: 0; padding: 0; background: #0c0e10; }++ .poster {+ position: relative;+ width: 1200px;+ height: 1600px;+ overflow: hidden;+ background: var(--ground);+ font-family: var(--font-body);+ }++ /* Preview scaffolding only. Delete it before delivery and do not infer the+ final composition or asset topology from it. */+ .preview-frame {+ position: absolute;+ left: 72px;+ top: 72px;+ width: 1056px;+ height: 1456px;+ border: 2px dashed rgba(242, 237, 227, 0.22);+ }++ .preview-status {+ position: absolute;+ left: 300px;+ top: 650px;+ width: 600px;+ text-align: center;+ }++ .preview-status p {+ margin: 0 0 24px;+ color: var(--accent);+ font-size: 20px;+ font-weight: 700;+ letter-spacing: 0.12em;+ text-transform: uppercase;+ }++ .preview-status h1 {+ margin: 0 0 22px;+ color: var(--ink);+ font-family: var(--font-display);+ font-size: 58px;+ font-weight: 600;+ line-height: 1.12;+ }++ .preview-status span {+ color: var(--ink-dim);+ font-size: 25px;+ line-height: 1.45;+ }+</style>+</head>+<body>+ <div class="poster" data-canvas-width="1200" data-canvas-height="1600">+ <div class="preview-frame"></div>+ <div class="preview-status">+ <p>Fixed canvas · 1200 × 1600</p>+ <h1>Your poster is taking shape</h1>+ <span>Composition will follow the brief and visual reference</span>+ </div>+ </div>+</body>+</html>diff --git a/skills/editable-design/assets/poster-starter/poster.json b/skills/editable-design/assets/poster-starter/poster.jsonnew file mode 100755index 0000000..03fca1a--- /dev/null+++ b/skills/editable-design/assets/poster-starter/poster.json@@ -0,0 +1,6 @@+{+ "canvas": { "width": 1200, "height": 1600 },+ "scale": 2,+ "dpi": null,+ "zones": null+}diff --git a/skills/editable-design/assets/poster-starter/reference/.gitkeep b/skills/editable-design/assets/poster-starter/reference/.gitkeepnew file mode 100755index 0000000..8b13789--- /dev/null+++ b/skills/editable-design/assets/poster-starter/reference/.gitkeep@@ -0,0 +1 @@+diff --git a/skills/editable-design/assets/replay/icons/assets.png b/skills/editable-design/assets/replay/icons/assets.pngnew file mode 100644index 0000000..d9db480Binary files /dev/null and b/skills/editable-design/assets/replay/icons/assets.png differdiff --git a/skills/editable-design/assets/replay/icons/html.png b/skills/editable-design/assets/replay/icons/html.pngnew file mode 100644index 0000000..7815b6aBinary files /dev/null and b/skills/editable-design/assets/replay/icons/html.png differdiff --git a/skills/editable-design/assets/replay/icons/input.png b/skills/editable-design/assets/replay/icons/input.pngnew file mode 100644index 0000000..0119e75Binary files /dev/null and b/skills/editable-design/assets/replay/icons/input.png differdiff --git a/skills/editable-design/assets/replay/icons/layers.png b/skills/editable-design/assets/replay/icons/layers.pngnew file mode 100644index 0000000..3ca62a7Binary files /dev/null and b/skills/editable-design/assets/replay/icons/layers.png differdiff --git a/skills/editable-design/assets/replay/icons/plan.png b/skills/editable-design/assets/replay/icons/plan.pngnew file mode 100644index 0000000..144fdf1Binary files /dev/null and b/skills/editable-design/assets/replay/icons/plan.png differdiff --git a/skills/editable-design/assets/replay/icons/reference.png b/skills/editable-design/assets/replay/icons/reference.pngnew file mode 100644index 0000000..56277d1Binary files /dev/null and b/skills/editable-design/assets/replay/icons/reference.png differdiff --git a/skills/editable-design/assets/replay/icons/review.png b/skills/editable-design/assets/replay/icons/review.pngnew file mode 100644index 0000000..c643538Binary files /dev/null and b/skills/editable-design/assets/replay/icons/review.png differdiff --git a/skills/editable-design/assets/replay/index.html b/skills/editable-design/assets/replay/index.htmlnew file mode 100644index 0000000..b1a28ff--- /dev/null+++ b/skills/editable-design/assets/replay/index.html@@ -0,0 +1,59 @@+<!doctype html>+<html lang="zh-CN">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>Agent 创意轨迹</title>+ <link rel="stylesheet" href="replay.css">+</head>+<body>+ <header class="replay-header">+ <div class="brand-mark" aria-hidden="true"><span></span><span></span><span></span></div>+ <div class="replay-title">+ <strong id="project-title">Agent 创意轨迹</strong>+ <span id="project-status">已完成</span>+ </div>+ <div class="view-controls" aria-label="画布控制">+ <button type="button" class="play-replay" id="play-replay" aria-label="播放完整创意轨迹"><span aria-hidden="true">▶</span><b>播放轨迹</b></button>+ <button type="button" id="fit-view">全览</button>+ <button type="button" id="zoom-out" aria-label="缩小">−</button>+ <output id="zoom-label">100%</output>+ <button type="button" id="zoom-in" aria-label="放大">+</button>+ </div>+ </header>++ <main class="replay-shell">+ <section class="canvas-viewport" id="canvas-viewport" aria-label="Agent 创意流程画布">+ <div class="canvas-world" id="canvas-world">+ <nav class="phase-nav" id="phase-nav" aria-label="创意阶段">+ <button type="button" data-stage="input" data-phase="think">+ <img src="icons/plan.png" alt=""><span>01</span><strong>理解与规划</strong><small>01—03</small>+ </button>+ <button type="button" data-stage="assets" data-phase="make">+ <img src="icons/html.png" alt=""><span>02</span><strong>生成与构建</strong><small>04—05</small>+ </button>+ <button type="button" data-stage="review" data-phase="prove">+ <img src="icons/review.png" alt=""><span>03</span><strong>观察与修正</strong><small>06—07</small>+ </button>+ </nav>+ <svg class="flow-lines" id="flow-lines" viewBox="0 0 2540 1780" aria-hidden="true"></svg>+ <div id="stage-layer"></div>+ <div id="artifact-layer"></div>+ </div>+ </section>+ <aside class="detail-panel" id="detail-panel" aria-live="polite" aria-label="节点详情">+ <button type="button" class="detail-close" id="detail-close" aria-label="关闭详情">×</button>+ <div id="detail-content"></div>+ </aside>+ <div class="media-lightbox" id="media-lightbox" role="dialog" aria-modal="true" aria-hidden="true" aria-labelledby="media-lightbox-title">+ <button type="button" class="media-lightbox-close" id="media-lightbox-close" aria-label="关闭放大预览">×</button>+ <div class="media-lightbox-frame" id="media-lightbox-frame"></div>+ <div class="media-lightbox-caption"><strong id="media-lightbox-title"></strong><span id="media-lightbox-note"></span></div>+ </div>+ </main>++ <script src="data.js"></script>+ <script src="replay.js"></script>+ <script src="replay-motion.js"></script>+</body>+</html>diff --git a/skills/editable-design/assets/replay/replay-motion.js b/skills/editable-design/assets/replay/replay-motion.jsnew file mode 100644index 0000000..df577ad--- /dev/null+++ b/skills/editable-design/assets/replay/replay-motion.js@@ -0,0 +1,397 @@+(() => {+ const SVG_NS = 'http://www.w3.org/2000/svg';+ const INTRO_DURATION = 4700;+ const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ const wait = (duration) => new Promise((resolve) => setTimeout(resolve, duration));+ const randomBetween = (min, max) => Math.round(min + Math.random() * (max - min));++ function mount(viewer) {+ if (document.body.dataset.motionMounted === 'true') return;+ document.body.dataset.motionMounted = 'true';++ const { data, world, flowLines, detailPanel, selectStage, initialStage, getViewState } = viewer;+ const playButton = document.getElementById('play-replay');+ const playLabel = playButton?.querySelector('b');+ const playIcon = playButton?.querySelector('span');+ const status = document.getElementById('project-status');+ const stageNodes = new Map([...document.querySelectorAll('.stage-node')].map((node) => [node.dataset.stage, node]));+ const artifacts = [...document.querySelectorAll('.external-artifact')];+ const assetArtifacts = artifacts.filter((artifact) => artifact.classList.contains('asset')).slice(0, 4);+ const flowPaths = [...flowLines.querySelectorAll('.flow-path')];+ const introPaths = [...flowLines.querySelectorAll('.flow-path, .intro-path')];+ const pathById = new Map(flowPaths.map((path) => [path.id, path]));+ const mainAmbientPaths = flowPaths.filter((path) => !path.classList.contains('repair'));+ const repairAmbientPaths = flowPaths.filter((path) => path.classList.contains('repair'));+ let mode = 'intro';+ let ambientTimers = [];+ let activePulses = new Set();+ let showcaseAnimations = new Set();+ let showcaseCycle = 0;+ let mainAmbientIndex = 2;++ function animateElement(element, keyframes, options) {+ if (!element) return Promise.resolve();+ const animation = element.animate(keyframes, { fill: 'both', ...options });+ return animation.finished.catch(() => {}).finally(() => animation.cancel());+ }++ function setPlayState(playing, disabled = playing) {+ if (!playButton) return;+ playButton.disabled = disabled;+ playButton.classList.toggle('is-playing', playing);+ playButton.setAttribute('aria-pressed', String(playing));+ if (playLabel) playLabel.textContent = playing ? '播放中' : '播放轨迹';+ if (playIcon) playIcon.textContent = playing ? '●' : '▶';+ }++ function targetOpacity(path) {+ if (path.classList.contains('flow-artifact')) return .75;+ if (path.classList.contains('flow-main')) return .9;+ return 1;+ }++ async function runIntro() {+ const introStarted = performance.now();+ status?.classList.remove('is-lit');+ detailPanel.classList.remove('is-open');+ setPlayState(false, true);+ document.body.classList.add('is-intro');+ const { scale, tx, ty } = getViewState();+ const animations = [];++ animations.push(animateElement(world, [+ { opacity: 0, transform: `translate(${tx}px, ${ty}px) scale(${scale * .985})` },+ { opacity: 1, transform: `translate(${tx}px, ${ty}px) scale(${scale})` }+ ], { duration: 900, easing: 'cubic-bezier(.22,.72,.2,1)' }));++ [...document.querySelectorAll('.phase-nav button')].forEach((button, index) => {+ animations.push(animateElement(button, [+ { opacity: 0, transform: 'translateY(14px) scale(.985)' },+ { opacity: 1, transform: 'translateY(0) scale(1)' }+ ], { duration: 650, delay: 260 + index * 220, easing: 'cubic-bezier(.22,.72,.2,1)' }));+ });++ [...stageNodes.values()].forEach((node, index) => {+ animations.push(animateElement(node, [+ { opacity: 0, transform: 'translateY(18px) scale(.99)' },+ { opacity: 1, transform: 'translateY(0) scale(1)' }+ ], { duration: 720, delay: 420 + index * 90, easing: 'cubic-bezier(.22,.72,.2,1)' }));+ });++ artifacts.forEach((artifact, index) => {+ animations.push(animateElement(artifact, [+ { opacity: 0, transform: 'translateY(14px) scale(.98)' },+ { opacity: 1, transform: 'translateY(0) scale(1)' }+ ], { duration: 650, delay: 1150 + index * 95, easing: 'cubic-bezier(.22,.72,.2,1)' }));+ });++ introPaths.forEach((path, index) => {+ const length = Math.max(1, path.getTotalLength());+ const opacity = targetOpacity(path);+ animations.push(animateElement(path, [+ { strokeDasharray: `${length} ${length}`, strokeDashoffset: length, opacity: 0 },+ { opacity, offset: .18 },+ { strokeDasharray: `${length} ${length}`, strokeDashoffset: 0, opacity }+ ], { duration: 620, delay: 1600 + index * 260, easing: 'cubic-bezier(.3,.75,.2,1)' }));+ });++ [+ ['flow-reference-plan', 2300],+ ['flow-plan-assets', 2900],+ ['flow-html-review', 3500],+ ['flow-review-html-repair', 4100]+ ].forEach(([pathId, delay]) => {+ animations.push(wait(delay).then(() => launchEnergy(pathById.get(pathId), { strong: true, duration: 600, intensity: .52 })));+ });++ const finalArtifacts = artifacts.filter((artifact) => artifact.classList.contains('render') || artifact.classList.contains('layers'));+ finalArtifacts.forEach((artifact) => {+ animations.push(animateElement(artifact, [+ { transform: 'translateY(0) scale(1)' },+ { transform: 'translateY(-4px) scale(1.035)', offset: .45 },+ { transform: 'translateY(0) scale(1)' }+ ], { duration: 600, delay: 4000, easing: 'cubic-bezier(.22,.72,.2,1)' }));+ });++ animations.push(wait(4350).then(() => status?.classList.add('is-lit')));+ await Promise.allSettled(animations);+ const remaining = INTRO_DURATION - (performance.now() - introStarted);+ if (remaining > 0) await wait(remaining);+ document.body.classList.remove('is-intro');+ setPlayState(false, false);+ if (initialStage) selectStage(initialStage.id, false);+ startAmbient();+ }++ function ambientAllowed() {+ return mode === 'ambient' && !document.hidden && getViewState().scale >= .20;+ }++ function removeAmbientPulses() {+ [...activePulses].filter((pulse) => !pulse.strong).forEach((pulse) => pulse.cancel());+ }++ function launchEnergy(path, { strong = false, duration = strong ? 720 : 1150, intensity = strong ? .96 : .58 } = {}) {+ if (!path) return Promise.resolve();+ const ambientCount = [...activePulses].filter((pulse) => !pulse.strong).length;+ if (!strong && (!ambientAllowed() || ambientCount >= 2)) return Promise.resolve();++ return new Promise((resolve) => {+ const color = path.dataset.color || '#ffffff';+ const group = document.createElementNS(SVG_NS, 'g');+ group.classList.add('energy-pulse');+ group.style.filter = `drop-shadow(0 0 ${strong ? 8 : 10}px ${color})`;+ const circleSizes = strong ? [9, 6, 4] : [12, 7.5, 4.5];+ const circles = circleSizes.map((radius) => {+ const circle = document.createElementNS(SVG_NS, 'circle');+ circle.setAttribute('r', String(radius));+ circle.setAttribute('fill', color);+ group.appendChild(circle);+ return circle;+ });+ flowLines.appendChild(group);+ const length = Math.max(1, path.getTotalLength());+ const started = performance.now();+ let frame = 0;+ let finished = false;+ const pulse = {+ strong,+ cancel() {+ if (finished) return;+ finished = true;+ cancelAnimationFrame(frame);+ path.classList.remove('is-arrow-lit');+ group.remove();+ activePulses.delete(pulse);+ resolve();+ }+ };+ activePulses.add(pulse);++ const tick = (now) => {+ if (finished) return;+ if (!strong && !ambientAllowed()) {+ pulse.cancel();+ return;+ }+ const progress = Math.min(1, (now - started) / duration);+ const envelope = Math.sin(Math.PI * progress) * intensity;+ circles.forEach((circle, index) => {+ const local = Math.max(0, progress - index * .028);+ const point = path.getPointAtLength(local * length);+ circle.setAttribute('cx', point.x.toFixed(2));+ circle.setAttribute('cy', point.y.toFixed(2));+ circle.setAttribute('opacity', String(envelope * (1 - index * .28)));+ });+ path.classList.toggle('is-arrow-lit', progress > .82);+ if (progress >= 1) pulse.cancel();+ else frame = requestAnimationFrame(tick);+ };+ frame = requestAnimationFrame(tick);+ });+ }++ function clearAmbientTimers() {+ ambientTimers.forEach(clearTimeout);+ ambientTimers = [];+ }++ function cancelShowcaseAnimations() {+ showcaseCycle += 1;+ [...showcaseAnimations].forEach((animation) => animation.cancel());+ showcaseAnimations.clear();+ }++ function showcaseAnimation(target, keyframes, options) {+ if (!target) return Promise.resolve();+ const animation = target.animate(keyframes, { fill: 'both', ...options });+ showcaseAnimations.add(animation);+ return animation.finished.catch(() => {}).finally(() => {+ showcaseAnimations.delete(animation);+ animation.cancel();+ });+ }++ async function emphasizeAsset(artifact, cycle) {+ if (!artifact || cycle !== showcaseCycle || !ambientAllowed()) return;+ const image = artifact.querySelector('img');+ await Promise.allSettled([+ showcaseAnimation(artifact, [+ { transform: 'translateY(0)', borderColor: '#e8b783', boxShadow: '0 15px 36px rgba(66,57,44,.13)' },+ { transform: 'translateY(-3px)', borderColor: '#e88731', boxShadow: '0 21px 44px rgba(121,72,30,.20)', offset: .34 },+ { transform: 'translateY(-3px)', borderColor: '#e88731', boxShadow: '0 21px 44px rgba(121,72,30,.20)', offset: .72 },+ { transform: 'translateY(0)', borderColor: '#e8b783', boxShadow: '0 15px 36px rgba(66,57,44,.13)' }+ ], { duration: 700, easing: 'cubic-bezier(.22,.72,.2,1)' }),+ showcaseAnimation(image, [+ { transform: 'scale(1)' },+ { transform: 'scale(1.015)', offset: .34 },+ { transform: 'scale(1.015)', offset: .72 },+ { transform: 'scale(1)' }+ ], { duration: 700, easing: 'cubic-bezier(.22,.72,.2,1)' })+ ]);+ }++ function scheduleAssetShowcase(initial = false) {+ if (mode !== 'ambient' || !assetArtifacts.length) return;+ const delay = initial ? 1500 : randomBetween(4000, 6000);+ const timer = setTimeout(async () => {+ ambientTimers = ambientTimers.filter((item) => item !== timer);+ const cycle = ++showcaseCycle;+ for (const artifact of assetArtifacts) {+ if (mode !== 'ambient' || cycle !== showcaseCycle) break;+ if (ambientAllowed()) await emphasizeAsset(artifact, cycle);+ }+ if (mode === 'ambient' && cycle === showcaseCycle) scheduleAssetShowcase(false);+ }, delay);+ ambientTimers.push(timer);+ }++ function scheduleAmbient(kind, initial = false) {+ if (mode !== 'ambient') return;+ const isRepair = kind === 'repair';+ const delay = initial ? (isRepair ? 1100 : 400) : (isRepair ? randomBetween(2600, 4000) : randomBetween(1800, 3000));+ const timer = setTimeout(async () => {+ ambientTimers = ambientTimers.filter((item) => item !== timer);+ const pool = isRepair ? repairAmbientPaths : mainAmbientPaths;+ if (ambientAllowed() && pool.length) {+ const path = isRepair ? pool[0] : pool[mainAmbientIndex++ % pool.length];+ await launchEnergy(path);+ }+ scheduleAmbient(kind, false);+ }, delay);+ ambientTimers.push(timer);+ }++ function startAmbient() {+ if (reducedMotion) return;+ clearAmbientTimers();+ mode = 'ambient';+ scheduleAmbient('main', true);+ scheduleAmbient('repair', true);+ scheduleAssetShowcase(true);+ }++ function stopAmbient() {+ clearAmbientTimers();+ removeAmbientPulses();+ cancelShowcaseAnimations();+ }++ function updatePlaybackFocus(stageId, visitedStages) {+ stageNodes.forEach((node, id) => {+ node.classList.toggle('is-current', id === stageId);+ node.classList.toggle('is-past', id !== stageId && visitedStages.has(id));+ node.classList.toggle('is-future', id !== stageId && !visitedStages.has(id));+ });+ artifacts.forEach((artifact) => {+ const current = artifact.dataset.stage === stageId;+ artifact.classList.toggle('is-current', current);+ artifact.classList.toggle('is-future', !current && !visitedStages.has(artifact.dataset.stage));+ });+ selectStage(stageId, false);+ const node = stageNodes.get(stageId);+ animateElement(node, [+ { filter: 'brightness(.96)', transform: 'translateY(0) scale(.995)' },+ { filter: 'brightness(1)', transform: 'translateY(-3px) scale(1.008)' }+ ], { duration: 360, easing: 'cubic-bezier(.22,.72,.2,1)' });+ animateElement(detailPanel, [{ opacity: .78 }, { opacity: 1 }], { duration: 220, easing: 'ease-out' });+ }++ async function runStrongFlow(path) {+ if (!path) return;+ path.classList.remove('is-future');+ path.classList.add('is-current');+ const overlay = document.createElementNS(SVG_NS, 'path');+ const color = path.dataset.color || '#ffffff';+ const length = Math.max(1, path.getTotalLength());+ const segment = Math.max(42, length * .18);+ overlay.setAttribute('d', path.getAttribute('d'));+ overlay.setAttribute('class', 'event-flow-pulse');+ overlay.setAttribute('stroke', color);+ overlay.setAttribute('stroke-width', path.classList.contains('repair') ? '11' : '14');+ overlay.style.strokeDasharray = `${segment} ${length}`;+ overlay.style.strokeDashoffset = String(length);+ overlay.style.filter = `drop-shadow(0 0 8px ${color})`;+ flowLines.appendChild(overlay);+ const sweep = animateElement(overlay, [+ { strokeDashoffset: length, opacity: 0 },+ { opacity: .96, offset: .12 },+ { strokeDashoffset: -segment, opacity: .92, offset: .88 },+ { strokeDashoffset: -segment, opacity: 0 }+ ], { duration: 720, easing: 'cubic-bezier(.35,.02,.22,1)' });+ await Promise.allSettled([sweep, launchEnergy(path, { strong: true, duration: 720 })]);+ overlay.remove();+ path.classList.remove('is-current');+ path.classList.add('is-past');+ }++ function clearPlaybackClasses() {+ document.body.classList.remove('is-playing');+ stageNodes.forEach((node) => node.classList.remove('is-current', 'is-past', 'is-future'));+ artifacts.forEach((artifact) => artifact.classList.remove('is-current', 'is-future'));+ flowPaths.forEach((path) => path.classList.remove('is-current', 'is-past', 'is-future', 'is-arrow-lit'));+ }++ async function playReplay() {+ if (reducedMotion || mode === 'intro' || mode === 'playing') return;+ stopAmbient();+ mode = 'playing';+ setPlayState(true, true);+ document.body.classList.add('is-playing');+ const visitedStages = new Set();+ flowPaths.forEach((path) => path.classList.add('is-future'));+ const execution = [+ { stage: 'input' },+ { path: 'flow-input-reference', stage: 'reference' },+ { path: 'flow-reference-plan', stage: 'plan' },+ { path: 'flow-plan-assets', stage: 'assets' },+ { path: 'flow-assets-html', stage: 'html' },+ { path: 'flow-html-review', stage: 'review' },+ { path: 'flow-review-html-repair', stage: 'html' },+ { path: 'flow-review-layers', stage: 'layers' }+ ];++ visitedStages.add(execution[0].stage);+ updatePlaybackFocus(execution[0].stage, visitedStages);+ await wait(420);+ for (const event of execution.slice(1)) {+ await runStrongFlow(pathById.get(event.path));+ visitedStages.add(event.stage);+ updatePlaybackFocus(event.stage, visitedStages);+ await wait(320);+ }+ await wait(520);+ clearPlaybackClasses();+ setPlayState(false, false);+ mode = 'ambient';+ await wait(900);+ startAmbient();+ }++ playButton?.addEventListener('click', playReplay);+ window.addEventListener('poster-replay-viewchange', (event) => {+ if (event.detail?.scale < .20) {+ removeAmbientPulses();+ cancelShowcaseAnimations();+ }+ });+ document.addEventListener('visibilitychange', () => {+ if (document.hidden) {+ removeAmbientPulses();+ cancelShowcaseAnimations();+ }+ });++ if (reducedMotion) {+ mode = 'reduced';+ status?.classList.add('is-lit');+ setPlayState(false, true);+ if (playButton) playButton.title = '已按系统设置关闭动画';+ if (initialStage) selectStage(initialStage.id, false);+ } else {+ runIntro();+ }+ }++ window.__POSTER_REPLAY_MOTION__ = { mount };+})();diff --git a/skills/editable-design/assets/replay/replay.css b/skills/editable-design/assets/replay/replay.cssnew file mode 100644index 0000000..d9dfdf3--- /dev/null+++ b/skills/editable-design/assets/replay/replay.css@@ -0,0 +1,374 @@+:root {+ color-scheme: light;+ --paper: #f7f6f2;+ --surface: #ffffff;+ --ink: #25231f;+ --muted: #77736a;+ --line: #dedbd3;+ --think: #567bc9;+ --think-soft: #eef3ff;+ --make: #cf7626;+ --make-soft: #fff3e6;+ --prove: #53856b;+ --prove-soft: #edf7f1;+ --repair: #df7058;+}++* { box-sizing: border-box; }++html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; }++body {+ background: var(--paper);+ color: var(--ink);+ font-family: Inter, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", system-ui, sans-serif;+}++button { font: inherit; }++.replay-header {+ position: relative;+ z-index: 20;+ display: flex;+ align-items: center;+ height: 74px;+ padding: 0 24px;+ border-bottom: 1px solid #ddd9d0;+ background: rgba(255,255,255,.96);+ box-shadow: 0 2px 18px rgba(55,48,37,.05);+}++.brand-mark { position: relative; width: 38px; height: 38px; margin-right: 14px; }+.brand-mark span { position: absolute; width: 14px; height: 14px; border: 3px solid var(--think); border-radius: 50%; }+.brand-mark span:nth-child(1) { left: 1px; top: 11px; }+.brand-mark span:nth-child(2) { right: 1px; top: 2px; }+.brand-mark span:nth-child(3) { right: 2px; bottom: 1px; border-color: var(--make); }++.replay-title { display: flex; align-items: center; gap: 12px; min-width: 0; }+.replay-title strong { overflow: hidden; font-size: 20px; font-weight: 700; text-overflow: ellipsis; white-space: nowrap; }+.replay-title span { display: inline-flex; align-items: center; gap: 6px; padding: 5px 9px; border-radius: 999px; background: #eaf4ee; color: var(--prove); font-size: 11px; font-weight: 700; }+.replay-title span::before { width: 7px; height: 7px; border-radius: 50%; background: #b8b9b5; box-shadow: 0 0 0 0 rgba(83,133,107,0); content: ""; transition: background .24s ease, box-shadow .4s ease; }+.replay-title span.is-lit::before { background: var(--prove); box-shadow: 0 0 0 5px rgba(83,133,107,.13), 0 0 14px rgba(83,133,107,.46); }++.view-controls { display: flex; align-items: center; gap: 6px; margin-left: auto; }+.view-controls button, .view-controls output {+ display: grid;+ place-items: center;+ min-width: 42px;+ height: 38px;+ padding: 0 12px;+ border: 1px solid #d9d5cd;+ border-radius: 10px;+ background: #fff;+ color: #625e56;+ font-size: 13px;+ font-weight: 650;+}+.view-controls button { cursor: pointer; }+.view-controls button:hover { border-color: #b7b0a5; background: #faf9f6; }+.view-controls button:disabled { cursor: default; opacity: .5; }+.view-controls output { min-width: 64px; border-color: transparent; background: transparent; }+.view-controls .play-replay { display: flex; gap: 7px; min-width: 108px; border-color: #c9d7cd; color: var(--prove); }+.play-replay span { font-size: 10px; }+.play-replay b { font-size: 12px; font-weight: 750; }+.play-replay.is-playing { border-color: #92b29f; background: var(--prove-soft); }++.replay-shell { position: relative; height: calc(100% - 74px); }+.phase-nav {+ position: absolute;+ z-index: 24;+ top: 28px;+ bottom: 28px;+ left: 18px;+ display: grid;+ grid-template-rows: repeat(3, 1fr);+ align-items: center;+ width: 220px;+ pointer-events: none;+}+.phase-nav::before { position: absolute; z-index: -1; top: 10%; bottom: 10%; left: 104px; width: 2px; background: #d1cec7; content: ""; }+.phase-nav button {+ position: relative;+ display: grid;+ justify-items: center;+ width: 210px;+ min-height: 210px;+ padding: 18px 16px 20px;+ overflow: hidden;+ border: 1px solid #d8d4cc;+ border-radius: 18px;+ background: rgba(255,255,255,.94);+ box-shadow: 0 12px 30px rgba(61,53,41,.10);+ color: var(--phase-color);+ cursor: pointer;+ pointer-events: auto;+ transition: border-color .18s ease, box-shadow .18s ease, transform .18s ease;+}+.phase-nav button::before { position: absolute; top: 0; right: 34px; left: 34px; height: 5px; border-radius: 0 0 99px 99px; background: var(--phase-color); content: ""; }+.phase-nav button[data-phase="think"] { --phase-color: var(--think); --phase-soft: var(--think-soft); }+.phase-nav button[data-phase="make"] { --phase-color: var(--make); --phase-soft: var(--make-soft); }+.phase-nav button[data-phase="prove"] { --phase-color: var(--prove); --phase-soft: var(--prove-soft); }+.phase-nav button:hover { border-color: var(--phase-color); transform: translateY(-2px); }+.phase-nav button.is-active { border-color: var(--phase-color); background: var(--phase-soft); box-shadow: 0 14px 34px color-mix(in srgb, var(--phase-color) 18%, transparent); }+.phase-nav img { width: 56px; height: 56px; object-fit: contain; filter: drop-shadow(0 5px 7px rgba(45,49,54,.14)); transition: transform .18s ease; }+.phase-nav button.is-active img { transform: scale(1.06); }+.phase-nav span { font: 800 14px/1 ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: .12em; }+.phase-nav strong { align-self: center; max-width: 160px; font-size: 19px; line-height: 1.28; text-align: center; }+.phase-nav small { align-self: end; font: 800 13px/1 ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: .08em; }+.canvas-viewport {+ position: absolute;+ inset: 0;+ overflow: hidden;+ cursor: grab;+ background-color: #faf9f6;+ background-image: radial-gradient(circle, rgba(99,93,82,.20) 1.4px, transparent 1.6px), linear-gradient(rgba(110,104,93,.055) 1px, transparent 1px), linear-gradient(90deg, rgba(110,104,93,.055) 1px, transparent 1px);+ background-position: 0 0;+ background-size: 28px 28px, 140px 140px, 140px 140px;+}+.canvas-viewport.is-panning { cursor: grabbing; }+.canvas-world { position: absolute; left: 0; top: 0; width: 2540px; height: 1780px; transform-origin: 0 0; will-change: transform, opacity; }+.flow-lines { position: absolute; inset: 0; width: 2540px; height: 1780px; overflow: visible; pointer-events: none; }++.flow-main { fill: none; stroke-width: 7.5; stroke-linecap: round; stroke-linejoin: round; opacity: .9; }+.flow-main.think { stroke: var(--think); }+.flow-main.make { stroke: var(--make); }+.flow-main.prove { stroke: var(--prove); }+.flow-artifact { fill: none; stroke: #8aa1cf; stroke-width: 3; stroke-linecap: round; stroke-dasharray: 9 9; opacity: .75; }+.flow-artifact.make { stroke: #d7a16c; }+.flow-repair { fill: none; stroke: var(--repair); stroke-width: 5.5; stroke-linecap: round; stroke-linejoin: round; }+.flow-path { transition: opacity .2s ease, filter .2s ease; }+.flow-path.think { --flow-color: var(--think); }+.flow-path.make { --flow-color: var(--make); }+.flow-path.prove { --flow-color: var(--prove); }+.flow-path.repair { --flow-color: var(--repair); }+.flow-path.is-arrow-lit { filter: drop-shadow(0 0 10px var(--flow-color)); }+.energy-pulse, .event-flow-pulse { pointer-events: none; }+.event-flow-pulse { fill: none; stroke-linecap: round; stroke-linejoin: round; }+.flow-label rect { fill: #edf7f1; stroke: #8eb29c; }+.flow-label text { fill: #47765c; font-size: 18px; font-weight: 750; }++.stage-node {+ position: absolute;+ display: grid;+ grid-template-rows: auto minmax(0,1fr) auto;+ overflow: hidden;+ border: 2px solid var(--stage-color);+ border-radius: 20px;+ background: rgba(255,255,255,.98);+ box-shadow: 0 18px 44px rgba(66,57,44,.11);+ cursor: pointer;+ transition: box-shadow .18s ease, transform .18s ease, opacity .2s ease, filter .2s ease;+}+.stage-node:hover { transform: translateY(-3px); box-shadow: 0 24px 55px rgba(66,57,44,.15); }+.stage-node.is-selected { box-shadow: 0 24px 58px rgba(66,57,44,.16), 0 0 0 5px color-mix(in srgb, var(--stage-color) 16%, transparent); }+.is-playing .stage-node { pointer-events: none; }+.is-playing .stage-node.is-future { opacity: .46; filter: saturate(.66); }+.stage-node.is-current { z-index: 4; animation: node-breathe 1.05s ease-in-out infinite; box-shadow: 0 25px 62px rgba(66,57,44,.18), 0 0 0 7px color-mix(in srgb, var(--stage-color) 24%, transparent); }+.is-playing .flow-path.is-future { opacity: .44; }+.is-playing .flow-path.is-current { opacity: 1; filter: drop-shadow(0 0 7px var(--flow-color)); }+.stage-node[data-phase="think"] { --stage-color: var(--think); --stage-soft: var(--think-soft); }+.stage-node[data-phase="make"] { --stage-color: var(--make); --stage-soft: var(--make-soft); }+.stage-node[data-phase="prove"] { --stage-color: var(--prove); --stage-soft: var(--prove-soft); }++.stage-head { display: grid; grid-template-columns: 54px minmax(0,1fr) auto; gap: 13px; align-items: center; padding: 18px 20px 15px; }+.stage-icon { width: 54px; height: 54px; object-fit: contain; filter: drop-shadow(0 6px 8px rgba(45,49,54,.12)); }+.stage-heading small { display: block; margin-bottom: 3px; color: var(--stage-color); font-size: 11px; font-weight: 800; letter-spacing: .14em; text-transform: uppercase; }+.stage-heading strong { display: block; font-size: 24px; line-height: 1.12; }+.stage-status { align-self: start; padding: 6px 9px; border-radius: 999px; background: var(--stage-soft); color: var(--stage-color); font-size: 10px; font-weight: 800; }+.stage-body { min-height: 0; margin: 0 18px; overflow: hidden; border-radius: 13px; background: var(--stage-soft); }+.stage-meta { display: flex; justify-content: space-between; gap: 14px; padding: 12px 20px 15px; color: var(--muted); font: 12px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace; }++.input-body { display: grid; grid-template-columns: 52px minmax(0,1fr); gap: 14px; height: 100%; padding: 18px; }+.input-body img { width: 48px; height: 48px; object-fit: contain; }+.input-body p { max-height: 150px; margin: 0; overflow: hidden; color: #3c3933; font: 16px/1.52 Georgia, "Songti SC", serif; white-space: pre-wrap; }+.input-body .missing { color: #9b6659; font-family: inherit; }++.text-evidence { display: grid; grid-template-rows: auto minmax(0,1fr) auto; height: 100%; padding: 17px 18px; }+.text-evidence > small { color: var(--stage-color); font: 800 10px/1.2 ui-monospace, monospace; letter-spacing: .1em; text-transform: uppercase; }+.text-evidence pre { margin: 10px 0; overflow: hidden; color: #3c4964; font: 12px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; }+.text-evidence .evidence-file { overflow: hidden; color: #7e7a71; font: 10px/1.2 ui-monospace, monospace; text-overflow: ellipsis; white-space: nowrap; }++.plan-body { display: grid; grid-template-columns: minmax(0,1.5fr) minmax(140px,.7fr); gap: 12px; height: 100%; padding: 13px; }+.plan-canvas { position: relative; min-width: 0; overflow: hidden; border: 1px solid #91a7d4; border-radius: 10px; background: rgba(255,255,255,.82); }+.plan-canvas::after { position: absolute; inset: 0; background-image: linear-gradient(rgba(85,123,201,.07) 1px, transparent 1px), linear-gradient(90deg, rgba(85,123,201,.07) 1px, transparent 1px); background-size: 18px 18px; content: ""; pointer-events: none; }+.plan-slot { position: absolute; z-index: 1; display: flex; flex-direction: column; justify-content: center; overflow: hidden; padding: 5px 7px; border: 1px solid #6d8dcf; border-radius: 6px; background: rgba(218,229,250,.92); color: #3f5e9b; }+.plan-slot:nth-child(even) { border-color: #d1904a; background: rgba(255,235,207,.92); color: #925e28; }+.plan-slot strong { overflow: hidden; font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }+.plan-slot span { margin-top: 3px; overflow: hidden; font-size: 7px; text-overflow: ellipsis; white-space: nowrap; opacity: .8; }+.plan-slot.is-auto { align-items: flex-start; padding: 8px; }+.plan-slot.is-auto span { display: -webkit-box; line-height: 1.25; white-space: normal; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }+.plan-empty { position: absolute; inset: 10%; display: grid; place-content: center; gap: 7px; border: 1px dashed #9fb1d5; border-radius: 9px; color: #6078a6; text-align: center; }+.plan-empty strong { font-size: 11px; }+.plan-empty span { font-size: 8px; opacity: .75; }+.plan-copy { display: flex; flex-direction: column; justify-content: center; min-width: 0; color: #4d638e; }+.plan-copy small { color: var(--think); font: 800 9px/1.2 ui-monospace, monospace; letter-spacing: .1em; }+.plan-copy strong { margin: 8px 0; font-size: 14px; line-height: 1.3; }+.plan-copy p { max-height: 92px; margin: 0; overflow: hidden; font-size: 10px; line-height: 1.5; }++.asset-body { display: grid; grid-template-rows: auto minmax(0,1fr) auto; height: 100%; padding: 18px; }+.asset-body header { display: flex; justify-content: space-between; gap: 16px; color: #774c28; }+.asset-body header strong { overflow: hidden; font-size: 14px; text-overflow: ellipsis; white-space: nowrap; }+.asset-body header span { color: var(--make); font: 800 11px/1.2 ui-monospace, monospace; }+.asset-body pre { display: -webkit-box; margin: 13px 0; overflow: hidden; color: #654d38; font: 11px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; -webkit-box-orient: vertical; -webkit-line-clamp: 7; }+.asset-tabs { display: flex; gap: 7px; }+.asset-tabs span { display: grid; place-items: center; min-width: 34px; height: 25px; padding: 0 8px; border: 1px solid #dfb98e; border-radius: 7px; background: rgba(255,255,255,.7); color: #b86c2a; font: 800 9px/1 ui-monospace, monospace; }+.asset-tabs span:first-child { background: var(--make); color: #fff; }++.code-body { display: grid; grid-template-columns: minmax(0,1.45fr) minmax(150px,.55fr); gap: 10px; height: 100%; padding: 10px; background: #f5eee7; }+.code-window { display: grid; grid-template-rows: 32px minmax(0,1fr); min-width: 0; overflow: hidden; border-radius: 9px; background: #252a30; }+.code-window > span { display: flex; align-items: center; padding: 0 13px; border-bottom: 1px solid rgba(255,255,255,.09); color: #aeb6bd; font: 10px/1 ui-monospace, monospace; }+.code-window > span::before { width: 7px; height: 7px; margin-right: 26px; border-radius: 50%; background: #e17b2c; box-shadow: 11px 0 #d9b552, 22px 0 #75a281; content: ""; }+.code-window pre { margin: 0; padding: 15px; overflow: hidden; color: #d4d9de; font: 10px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; }+.code-facts { display: flex; flex-direction: column; justify-content: center; gap: 8px; padding: 12px; border: 1px solid #e0cdbb; border-radius: 9px; background: rgba(255,255,255,.78); }+.code-facts small { color: var(--make); font-size: 9px; font-weight: 800; letter-spacing: .1em; }+.code-facts span { padding: 7px 8px; border-radius: 6px; background: #f5e6d6; color: #735337; font: 9px/1.35 ui-monospace, monospace; }++.review-body { display: grid; grid-template-columns: 90px minmax(0,1fr); gap: 12px; height: 100%; padding: 12px; }+.review-count { display: flex; flex-direction: column; align-items: center; justify-content: center; border-radius: 9px; background: rgba(255,255,255,.72); color: var(--prove); text-align: center; }+.review-count strong { font: 42px/1 Georgia, serif; }+.review-count span { margin-top: 6px; font-size: 9px; font-weight: 700; }+.review-list { display: grid; align-content: center; gap: 7px; min-width: 0; }+.review-list div { overflow: hidden; padding: 8px 10px; border-left: 3px solid #6f9a81; border-radius: 0 7px 7px 0; background: rgba(255,255,255,.75); color: #4d6556; font-size: 10px; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; }++.layers-body { display: grid; grid-template-columns: repeat(3,1fr); gap: 10px; height: 100%; padding: 12px; }+.layer-stat { display: flex; flex-direction: column; justify-content: center; min-width: 0; padding: 13px; border: 1px solid #c5d8cd; border-radius: 9px; background: rgba(255,255,255,.78); color: #52725f; }+.layer-stat::before { width: 30px; height: 5px; margin-bottom: 10px; border-radius: 99px; background: #6f9a81; content: ""; }+.layer-stat:nth-child(2)::before { background: #5e83c4; }+.layer-stat:nth-child(3)::before { background: #d1904a; }+.layer-stat small { font-size: 9px; font-weight: 800; letter-spacing: .08em; }+.layer-stat strong { margin: 5px 0 2px; font: 28px/1.1 Georgia, serif; }+.layer-stat span { overflow: hidden; color: #748278; font-size: 8px; line-height: 1.35; text-overflow: ellipsis; }++.external-artifact {+ position: absolute;+ margin: 0;+ overflow: hidden;+ border: 2px solid var(--artifact-color, #9eb1d6);+ border-radius: 14px;+ background: #fff;+ box-shadow: 0 15px 36px rgba(66,57,44,.13);+ cursor: pointer;+ transition: transform .16s ease, box-shadow .16s ease, opacity .2s ease, filter .2s ease;+}+.external-artifact:hover { transform: translateY(-3px); box-shadow: 0 21px 46px rgba(66,57,44,.17); }+.external-artifact img, .external-artifact iframe { display: block; width: 100%; height: 100%; border: 0; object-fit: cover; background: #f0eee8; pointer-events: none; }+.external-artifact[data-contain="true"] img { object-fit: contain; }+.external-artifact figcaption { position: absolute; left: 7px; right: 7px; bottom: 7px; display: flex; justify-content: space-between; gap: 6px; padding: 6px 8px; border-radius: 7px; background: rgba(255,255,255,.94); color: #555149; font-size: 8px; font-weight: 800; }+.external-artifact figcaption span:last-child { color: #99938a; font-family: ui-monospace, monospace; }+.external-artifact.reference { --artifact-color: #89a3d6; }+.external-artifact.asset { --artifact-color: #e8b783; }+.external-artifact.render { --artifact-color: #d8883e; }+.external-artifact.layers { --artifact-color: #78a087; }+.external-artifact.featured-output { border-width: 3px; box-shadow: 0 22px 54px rgba(105,65,29,.19); }+.external-artifact.featured-output figcaption { right: 10px; bottom: 10px; left: 10px; padding: 8px 10px; font-size: 10px; }+.external-artifact.reference figcaption { font-size: 9px; }+.external-artifact.asset figcaption { right: 10px; bottom: 10px; left: 10px; padding: 8px 10px; font-size: 10px; }+.external-artifact.asset img { transform-origin: center; }+.is-playing .external-artifact.is-future { opacity: .45; filter: saturate(.65); }+.is-playing .external-artifact { pointer-events: none; }+.external-artifact.is-current { z-index: 5; transform: translateY(-5px) scale(1.025); box-shadow: 0 24px 54px rgba(66,57,44,.20), 0 0 0 5px color-mix(in srgb, var(--artifact-color) 18%, transparent); }+.is-playing .phase-nav button { pointer-events: none; }++.detail-panel {+ position: absolute;+ z-index: 30;+ top: 18px;+ right: 18px;+ bottom: 18px;+ width: min(620px, calc(100vw - 36px));+ overflow: hidden;+ border: 1px solid #d8d4cc;+ border-radius: 20px;+ background: rgba(255,255,255,.98);+ box-shadow: 0 24px 70px rgba(61,53,41,.18);+ transform: translateX(calc(100% + 30px));+ transition: transform .22s ease;+}+.detail-panel.is-open { transform: translateX(0); }+.is-intro .detail-panel { visibility: hidden; opacity: 0; pointer-events: none; transition: none; }+#detail-content { display: flex; flex-direction: column; width: 100%; height: 100%; min-height: 0; }+.detail-close { position: absolute; z-index: 2; top: 14px; right: 15px; width: 34px; height: 34px; border: 0; border-radius: 9px; background: #f4f2ed; color: #69645b; font-size: 24px; cursor: pointer; }+.detail-head { display: grid; flex: 0 0 auto; grid-template-columns: 56px minmax(0,1fr); gap: 14px; align-items: center; padding: 22px 58px 18px 20px; border-bottom: 1px solid #e3e0d9; }+.detail-head img { width: 54px; height: 54px; object-fit: contain; }+.detail-head small { display: block; margin-bottom: 4px; color: var(--detail-color); font-size: 10px; font-weight: 800; letter-spacing: .12em; text-transform: uppercase; }+.detail-head strong { display: block; font-size: 22px; }+.detail-body { flex: 1 1 auto; min-height: 0; overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; padding: 0 20px 28px; scrollbar-gutter: stable; touch-action: pan-y; }+.detail-section { padding: 18px 0; border-bottom: 1px solid #e6e2db; }+.detail-section:last-child { border-bottom: 0; }+.detail-section h3 { margin: 0 0 10px; color: #777269; font-size: 10px; letter-spacing: .12em; text-transform: uppercase; }+.detail-section-title { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 11px; }+.detail-section-title h3 { margin: 0; }+.detail-section-title span { color: var(--make); font: 800 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: .08em; }+.detail-section p { margin: 0; color: #3e3a34; font-size: 13px; line-height: 1.65; white-space: pre-wrap; }+.detail-section pre { max-height: 440px; margin: 0; padding: 13px; overflow: auto; border-radius: 10px; background: #f5f3ee; color: #403c36; font: 10px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; }+.detail-section pre.code { background: #252a30; color: #d6dbe0; }+.detail-media { overflow: hidden; border: 1px solid #ddd9d1; border-radius: 11px; background: #f2f0eb; }+.detail-media img { display: block; width: 100%; max-height: 420px; object-fit: contain; }+.detail-media iframe { display: block; width: 100%; height: 360px; border: 0; background: #f2f0eb; }+.prompt-list { display: grid; gap: 10px; }+.asset-overview-section { padding-top: 20px; }+.asset-overview-grid { display: grid; grid-template-columns: repeat(3, minmax(0,1fr)); gap: 8px; }+.asset-overview-grid figure { min-width: 0; margin: 0; overflow: hidden; border: 1px solid #ded9d0; border-radius: 10px; background: #f7f5f0; }+.asset-overview-grid img { display: block; width: 100%; aspect-ratio: 1; padding: 5px; object-fit: contain; background: #fff; }+.asset-overview-grid figcaption { display: grid; grid-template-columns: auto minmax(0,1fr); gap: 6px; align-items: center; padding: 7px; border-top: 1px solid #e5e0d7; }+.asset-overview-grid figcaption span { color: var(--make); font: 800 8px/1 ui-monospace, SFMono-Regular, Menlo, monospace; }+.asset-overview-grid figcaption strong { overflow: hidden; color: #514c44; font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }+.prompt-item { overflow: hidden; border: 1px solid #dfdbd3; border-radius: 10px; background: #fbfaf7; }+.prompt-item summary { display: grid; grid-template-columns: 34px minmax(0,1fr); gap: 9px; align-items: center; padding: 10px; cursor: pointer; list-style: none; }+.prompt-item summary::-webkit-details-marker { display: none; }+.prompt-item summary span { display: grid; place-items: center; width: 34px; height: 30px; border-radius: 7px; background: #f6e5d3; color: #ba6823; font: 800 9px/1 ui-monospace, monospace; }+.prompt-item summary strong { overflow: hidden; color: #4a453e; font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }+.prompt-result { display: grid; grid-template-columns: 100px minmax(0,1fr); gap: 10px; padding: 10px; border-top: 1px solid #e6e1d9; }+.prompt-result img { width: 100px; height: 100px; object-fit: cover; border-radius: 8px; background: #eeeae3; }+.prompt-result pre { max-height: 220px; padding: 0; background: transparent; }+.source-note { margin-top: 8px; color: #8b857b; font: 9px/1.45 ui-monospace, monospace; }++.media-lightbox {+ position: absolute;+ z-index: 80;+ inset: 16px;+ display: grid;+ grid-template-rows: minmax(0,1fr) auto;+ gap: 12px;+ padding: 24px;+ visibility: hidden;+ border: 1px solid rgba(255,255,255,.34);+ border-radius: 22px;+ background: rgba(31,32,33,.88);+ box-shadow: 0 30px 90px rgba(28,25,20,.32);+ opacity: 0;+ pointer-events: none;+ backdrop-filter: blur(18px);+ transition: opacity .2s ease, visibility .2s ease;+}+.media-lightbox.is-open { visibility: visible; opacity: 1; pointer-events: auto; }+.media-lightbox-frame { display: grid; min-width: 0; min-height: 0; place-items: center; overflow: hidden; border: 1px solid rgba(255,255,255,.26); border-radius: 16px; background: #f7f5f0; }+.media-lightbox-frame img { display: block; width: auto; height: auto; max-width: 100%; max-height: 100%; min-width: 0; min-height: 0; object-fit: contain; }+.media-lightbox-frame iframe { display: block; width: 100%; height: 100%; border: 0; background: #f7f5f0; }+.media-lightbox-caption { display: flex; align-items: center; justify-content: space-between; gap: 18px; min-width: 0; color: #fff; }+.media-lightbox-caption strong { overflow: hidden; font-size: 16px; text-overflow: ellipsis; white-space: nowrap; }+.media-lightbox-caption span { color: rgba(255,255,255,.65); font-size: 11px; }+.media-lightbox-close { position: absolute; z-index: 2; top: 34px; right: 34px; width: 42px; height: 42px; border: 1px solid rgba(255,255,255,.32); border-radius: 12px; background: rgba(25,26,27,.72); color: #fff; font-size: 29px; line-height: 1; cursor: pointer; backdrop-filter: blur(10px); }++@keyframes node-breathe {+ 0%, 100% { transform: translateY(-2px) scale(1); }+ 50% { transform: translateY(-4px) scale(1.008); }+}++@media (max-width: 760px) {+ .replay-header { height: 64px; padding: 0 12px; }+ .replay-shell { height: calc(100% - 64px); }+ .replay-title strong { font-size: 16px; }+ .replay-title span, #fit-view, #zoom-label, .play-replay b { display: none; }+ .view-controls button { min-width: 36px; height: 36px; padding: 0; }+ .view-controls .play-replay { min-width: 36px; }+ .phase-nav { display: none; }+ .detail-panel { top: 8px; right: 8px; bottom: 8px; width: calc(100vw - 16px); }+ .media-lightbox { inset: 8px; padding: 12px; border-radius: 16px; }+ .media-lightbox-close { top: 20px; right: 20px; }+ .media-lightbox-caption { align-items: flex-start; flex-direction: column; gap: 4px; }+}++@media (prefers-reduced-motion: reduce) {+ .stage-node, .external-artifact, .detail-panel, .media-lightbox, .flow-path, .phase-nav button, .phase-nav img, .replay-title span::before { transition: none; animation: none; }+}diff --git a/skills/editable-design/assets/replay/replay.js b/skills/editable-design/assets/replay/replay.jsnew file mode 100644index 0000000..04640f1--- /dev/null+++ b/skills/editable-design/assets/replay/replay.js@@ -0,0 +1,354 @@+(() => {+ const data = window.__POSTER_REPLAY__;+ if (!data) {+ document.getElementById('stage-layer').innerHTML = '<p style="padding:40px">Replay data is missing.</p>';+ return;+ }++ const viewport = document.getElementById('canvas-viewport');+ const world = document.getElementById('canvas-world');+ const stageLayer = document.getElementById('stage-layer');+ const artifactLayer = document.getElementById('artifact-layer');+ const flowLines = document.getElementById('flow-lines');+ const detailPanel = document.getElementById('detail-panel');+ const detailContent = document.getElementById('detail-content');+ const mediaLightbox = document.getElementById('media-lightbox');+ const mediaLightboxFrame = document.getElementById('media-lightbox-frame');+ const mediaLightboxTitle = document.getElementById('media-lightbox-title');+ const mediaLightboxNote = document.getElementById('media-lightbox-note');+ const zoomLabel = document.getElementById('zoom-label');+ const phaseNav = document.getElementById('phase-nav');+ const WORLD_WIDTH = 2540;+ const WORLD_HEIGHT = 1780;+ const stageById = new Map(data.stages.map((stage) => [stage.id, stage]));+ const layout = {+ input: { x: 260, y: 110, w: 490, h: 310 },+ reference: { x: 820, y: 110, w: 450, h: 330 },+ plan: { x: 2075, y: 110, w: 420, h: 360 },+ assets: { x: 800, y: 640, w: 480, h: 390 },+ html: { x: 1330, y: 640, w: 690, h: 390 },+ review: { x: 300, y: 1240, w: 690, h: 380 },+ layers: { x: 1330, y: 1240, w: 690, h: 380 }+ };+ const phaseColor = { think: '#567bc9', make: '#cf7626', prove: '#53856b' };+ let scale = 1;+ let tx = 0;+ let ty = 0;+ let selected = null;+ let dragging = false;+ let dragOrigin = null;++ document.title = `${data.project.title} · Agent 创意轨迹`;+ document.getElementById('project-title').textContent = data.project.title;+ document.getElementById('project-status').textContent = data.project.status === 'ok' ? '已完成' : data.project.status;++ const esc = (value = '') => String(value).replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[char]));+ const shorten = (value = '', max = 620) => value.length > max ? `${value.slice(0, max).trim()}…` : value;++ function stageIcon(stage) {+ return `<img class="stage-icon" src="icons/${esc(stage.kind)}.png" alt="">`;+ }++ function inputVisual(stage) {+ const text = stage.raw || '未记录原始用户 Prompt。';+ return `<div class="input-body"><img src="icons/input.png" alt=""><p class="${stage.raw ? '' : 'missing'}">${esc(shorten(text, 520))}</p></div>`;+ }++ function referenceVisual(stage) {+ return `<div class="text-evidence"><small>Art-direction prompt</small><pre>${esc(shorten(stage.prompt || '未记录增强 Prompt。', 880))}</pre><div class="evidence-file">${esc(stage.promptSource || 'missing')}</div></div>`;+ }++ function planVisual(stage) {+ const slots = (stage.slots || []).slice(0, 8);+ const hasRecordedRects = slots.length > 0 && slots.every((slot) => {+ const rect = slot.rect || {};+ return ['x', 'y', 'width', 'height'].every((key) => Number.isFinite(Number(rect[key]))) && Number(rect.width) > 0 && Number(rect.height) > 0;+ });+ let positionedSlots = [];+ if (hasRecordedRects) {+ const maxX = Math.max(1, ...slots.map((slot) => Number(slot.rect.x) + Number(slot.rect.width)));+ const maxY = Math.max(1, ...slots.map((slot) => Number(slot.rect.y) + Number(slot.rect.height)));+ positionedSlots = slots.map((slot) => ({+ slot,+ left: Math.max(1, Number(slot.rect.x) / maxX * 94),+ top: Math.max(1, Number(slot.rect.y) / maxY * 94),+ width: Math.max(12, Number(slot.rect.width) / maxX * 94),+ height: Math.max(12, Number(slot.rect.height) / maxY * 94)+ }));+ } else if (slots.length) {+ const columns = slots.length >= 5 ? 3 : slots.length >= 3 ? 2 : 1;+ const rows = Math.ceil(slots.length / columns);+ const gap = 3;+ const width = (92 - gap * (columns - 1)) / columns;+ const height = (88 - gap * (rows - 1)) / rows;+ positionedSlots = slots.map((slot, index) => ({+ slot,+ left: 4 + (index % columns) * (width + gap),+ top: 6 + Math.floor(index / columns) * (height + gap),+ width,+ height+ }));+ }+ const slotHTML = positionedSlots.length ? positionedSlots.map(({ slot, left, top, width, height }, index) => `<div class="plan-slot${hasRecordedRects ? '' : ' is-auto'}" style="left:${left}%;top:${top}%;width:${Math.min(width, 98-left)}%;height:${Math.min(height, 98-top)}%"><strong>${String(index + 1).padStart(2, '0')} · ${esc(slot.id || slot.label || 'slot')}</strong><span>${esc(slot.role || slot.form || slot.aspect || slot.prompt || '')}</span></div>`).join('') : '<div class="plan-empty"><strong>未记录可视化槽位</strong><span>右侧保留原始设计规划</span></div>';+ return `<div class="plan-body"><div class="plan-canvas">${slotHTML}</div><div class="plan-copy"><small>${esc(stage.architecture || 'DESIGN PLAN')}</small><strong>${esc(stage.planTitle || '版式与信息层级')}</strong><p>${esc(shorten(stage.raw || '', 300))}</p></div></div>`;+ }++ function assetsVisual(stage) {+ const first = stage.items?.[0] || {};+ const tabs = (stage.items || []).slice(0, 6).map((_, index) => `<span>${String(index + 1).padStart(2, '0')}</span>`).join('');+ return `<div class="asset-body"><header><strong>${esc(first.title || '生成 Prompt')}</strong><span>PROMPT 摘要 · ${stage.items?.length || 0}</span></header><pre>${esc(shorten(first.prompt || '未记录素材 Prompt。', 320))}</pre><div class="asset-tabs">${tabs}</div></div>`;+ }++ function htmlVisual(stage) {+ return `<div class="code-body"><div class="code-window"><span>index.html · live layers</span><pre>${esc(shorten(stage.code || '', 1700))}</pre></div><div class="code-facts"><small>RENDER CONTRACT</small><span>${esc(stage.canvas || 'fixed canvas')}</span><span>${stage.layerCount || 0} editable layers</span><span>${stage.groupCount || 0} explode groups</span></div></div>`;+ }++ function reviewVisual(stage) {+ const bullets = (stage.bullets || []).slice(0, 4);+ return `<div class="review-body"><div class="review-count"><strong>${stage.passCount || 1}</strong><span>REVIEW PASSES</span></div><div class="review-list">${bullets.map((line, index) => `<div>${String(index + 1).padStart(2, '0')} · ${esc(shorten(line, 96))}</div>`).join('') || '<div>未记录 Review 内容</div>'}</div></div>`;+ }++ function layersVisual(stage) {+ return `<div class="layers-body"><div class="layer-stat"><small>EDITABLE LAYERS</small><strong>${stage.layerCount || 0}</strong><span>data-layer-id</span></div><div class="layer-stat"><small>CONTENT GROUPS</small><strong>${stage.groupCount || 0}</strong><span>data-explode-group</span></div><div class="layer-stat"><small>OUTPUT</small><strong>${stage.preview ? 'LIVE' : '—'}</strong><span>${esc(stage.previewSource || '未生成分层展示')}</span></div></div>`;+ }++ const visualFor = { input: inputVisual, reference: referenceVisual, plan: planVisual, assets: assetsVisual, html: htmlVisual, review: reviewVisual, layers: layersVisual };++ function renderStage(stage) {+ const box = layout[stage.id];+ const article = document.createElement('article');+ article.className = 'stage-node';+ article.dataset.stage = stage.id;+ article.dataset.phase = stage.phase;+ article.style.cssText = `left:${box.x}px;top:${box.y}px;width:${box.w}px;height:${box.h}px`;+ article.innerHTML = `<header class="stage-head">${stageIcon(stage)}<div class="stage-heading"><small>${esc(stage.order)} · ${esc(stage.kind)}</small><strong>${esc(stage.title)}</strong></div><span class="stage-status">${esc(stage.statusLabel || '已记录')}</span></header><div class="stage-body">${visualFor[stage.kind](stage)}</div><footer class="stage-meta"><span>${esc(stage.timeLabel || '')}</span><span>${esc(stage.artifactLabel || '')}</span></footer>`;+ article.addEventListener('click', (event) => { event.stopPropagation(); selectStage(stage.id); });+ stageLayer.appendChild(article);+ }++ function closeDetail(updateUrl = true) {+ detailPanel.classList.remove('is-open');+ selected = null;+ document.querySelectorAll('.stage-node').forEach((node) => node.classList.remove('is-selected'));+ phaseNav?.querySelectorAll('button').forEach((button) => button.classList.remove('is-active'));+ if (updateUrl) {+ const url = new URL(location.href);+ url.searchParams.delete('stage');+ history.replaceState(null, '', url);+ }+ }++ function closeMedia() {+ mediaLightbox.classList.remove('is-open');+ mediaLightbox.setAttribute('aria-hidden', 'true');+ mediaLightboxFrame.replaceChildren();+ }++ function openMedia(src, label, kind) {+ if (!src) return;+ closeDetail();+ mediaLightbox.dataset.kind = kind;+ mediaLightboxTitle.textContent = label;+ mediaLightboxNote.textContent = kind === 'animation' ? '交互式 HTML · 自动播放分层动画' : '高清图像预览';+ const media = document.createElement(kind === 'animation' ? 'iframe' : 'img');+ if (kind === 'animation') {+ const url = new URL(src, location.href);+ url.searchParams.delete('motion');+ url.searchParams.set('replay', String(Date.now()));+ media.src = url.href;+ media.title = label;+ } else {+ media.src = src;+ media.alt = label;+ }+ mediaLightboxFrame.replaceChildren(media);+ mediaLightbox.classList.add('is-open');+ mediaLightbox.setAttribute('aria-hidden', 'false');+ document.getElementById('media-lightbox-close')?.focus({ preventScroll: true });+ }++ function artifactCard({ className, x, y, w, h, src, label, code, contain = false, iframe = false, stage, openMode = 'detail' }) {+ if (!src) return;+ const figure = document.createElement('figure');+ figure.className = `external-artifact ${className}`;+ figure.dataset.stage = stage;+ figure.dataset.contain = contain ? 'true' : 'false';+ figure.style.cssText = `left:${x}px;top:${y}px;width:${w}px;height:${h}px`;+ figure.innerHTML = `${iframe ? `<iframe src="${esc(src)}" title="${esc(label)}"></iframe>` : `<img src="${esc(src)}" alt="${esc(label)}">`}<figcaption><span>${esc(label)}</span><span>${esc(code)}</span></figcaption>`;+ figure.addEventListener('click', (event) => {+ event.stopPropagation();+ if (openMode === 'image') openMedia(src, label, 'image');+ else if (openMode === 'animation') openMedia(src, label, 'animation');+ else selectStage(stage);+ });+ artifactLayer.appendChild(figure);+ }++ function renderArtifacts() {+ const reference = stageById.get('reference');+ artifactCard({ className: 'reference', x: 1538, y: 110, w: 270, h: 360, src: reference?.preview, label: '视觉参考', code: 'OUT 02', contain: true, stage: 'reference', openMode: 'image' });++ const assets = stageById.get('assets');+ const assetItems = (assets?.items || []).filter((item) => item.src).slice(0, 4);+ if (assetItems.length === 1) {+ const item = assetItems[0];+ artifactCard({ className: 'asset single-asset', x: 260, y: 610, w: 500, h: 440, src: item.src, label: item.title || 'Asset 1', code: 'OUT 04.1', contain: item.contain, stage: 'assets' });+ } else {+ assetItems.forEach((item, index) => artifactCard({ className: 'asset', x: 260 + (index % 2) * 260, y: 610 + Math.floor(index / 2) * 230, w: 240, h: 210, src: item.src, label: item.title || `Asset ${index + 1}`, code: `OUT 04.${index + 1}`, contain: item.contain, stage: 'assets' }));+ }++ const html = stageById.get('html');+ artifactCard({ className: 'render featured-output', x: 2075, y: 670, w: 420, h: 560, src: html?.render, label: '最终渲染结果', code: 'OUT 05', contain: true, stage: 'html', openMode: 'image' });++ const layers = stageById.get('layers');+ artifactCard({ className: 'layers', x: 2075, y: 1320, w: 420, h: 360, src: layers?.preview, label: '可编辑分层动画', code: 'OUT 07', contain: true, iframe: layers?.preview?.endsWith('.html') || layers?.preview?.includes('.html?'), stage: 'layers', openMode: 'animation' });+ }++ function renderLines() {+ const assetCount = (stageById.get('assets')?.items || []).filter((item) => item.src).slice(0, 4).length;+ const assetConnectorPaths = assetCount === 1+ ? ['M760 830 C775 830 790 830 800 830']+ : [+ 'M500 715 C605 715 720 735 800 760',+ 'M760 715 C775 715 790 730 800 760',+ 'M500 945 C605 945 720 920 800 900',+ 'M760 945 C775 945 790 920 800 900',+ ].slice(0, assetCount);+ const assetConnectors = assetConnectorPaths.map((d) => `<path class="flow-artifact make intro-path" d="${d}"/>`).join('');+ flowLines.innerHTML = `+ <defs>+ <marker id="arrow-blue" markerUnits="userSpaceOnUse" markerWidth="18" markerHeight="18" refX="16" refY="9" viewBox="0 0 18 18" orient="auto"><path d="M1,1 L17,9 L1,17 Z" fill="#567bc9"/></marker>+ <marker id="arrow-orange" markerUnits="userSpaceOnUse" markerWidth="18" markerHeight="18" refX="16" refY="9" viewBox="0 0 18 18" orient="auto"><path d="M1,1 L17,9 L1,17 Z" fill="#cf7626"/></marker>+ <marker id="arrow-green" markerUnits="userSpaceOnUse" markerWidth="18" markerHeight="18" refX="16" refY="9" viewBox="0 0 18 18" orient="auto"><path d="M1,1 L17,9 L1,17 Z" fill="#53856b"/></marker>+ <marker id="arrow-red" markerUnits="userSpaceOnUse" markerWidth="18" markerHeight="18" refX="16" refY="9" viewBox="0 0 18 18" orient="auto"><path d="M1,1 L17,9 L1,17 Z" fill="#df7058"/></marker>+ </defs>+ <path id="flow-input-reference" class="flow-main flow-path think" data-from="input" data-to="reference" data-color="#567bc9" marker-end="url(#arrow-blue)" d="M750 265 C770 265 790 265 820 265"/>+ <path id="flow-reference-plan" class="flow-artifact flow-path think" data-from="reference" data-to="plan" data-color="#567bc9" marker-end="url(#arrow-blue)" d="M1270 290 L2075 290"/>+ <path id="flow-plan-assets" class="flow-main flow-path make" data-from="plan" data-to="assets" data-color="#cf7626" marker-end="url(#arrow-orange)" d="M2285 470 C2285 570 1500 500 1040 640"/>+ ${assetConnectors}+ <path id="flow-assets-html" class="flow-main flow-path make" data-from="assets" data-to="html" data-color="#cf7626" marker-end="url(#arrow-orange)" d="M1280 835 C1295 835 1310 835 1330 835"/>+ <path id="flow-html-review" class="flow-main flow-path prove" data-from="html" data-to="review" data-color="#53856b" marker-end="url(#arrow-green)" d="M1675 1030 C1675 1150 1015 1140 890 1240"/>+ <path id="flow-review-layers" class="flow-main flow-path prove" data-from="review" data-to="layers" data-color="#53856b" marker-end="url(#arrow-green)" d="M990 1430 C1100 1430 1210 1430 1330 1430"/>+ <path id="flow-review-html-repair" class="flow-repair flow-path repair" data-from="review" data-to="html" data-color="#df7058" marker-end="url(#arrow-red)" d="M610 1240 C610 1130 1220 1170 1470 1030"/>+ <g class="flow-label prove-label" transform="translate(1010 1150)"><rect width="134" height="34" rx="9"/><text x="67" y="23" text-anchor="middle">反馈修正</text></g>`;+ }++ function mediaSection(src, title, iframe = false) {+ if (!src) return '';+ return `<section class="detail-section"><h3>${esc(title)}</h3><div class="detail-media">${iframe ? `<iframe src="${esc(src)}" title="${esc(title)}"></iframe>` : `<img src="${esc(src)}" alt="${esc(title)}">`}</div></section>`;+ }++ function textSection(title, text, code = false) {+ if (!text) return '';+ return `<section class="detail-section"><h3>${esc(title)}</h3><pre class="${code ? 'code' : ''}">${esc(text)}</pre></section>`;+ }++ function detailFor(stage) {+ let body = '';+ if (stage.kind === 'input') {+ body += textSection('原始用户 Prompt', stage.raw || '未记录原始用户 Prompt。');+ if (stage.attachments?.length) body += `<section class="detail-section"><h3>输入附件</h3><p>${stage.attachments.map(esc).join('\n')}</p></section>`;+ }+ if (stage.kind === 'reference') {+ body += textSection('增强后的视觉 Prompt', stage.prompt || '未记录。');+ body += mediaSection(stage.preview, '生成的视觉参考');+ }+ if (stage.kind === 'plan') {+ body += textSection('设计规划', stage.raw || '未记录。');+ if (stage.assetPlanRaw) body += textSection('asset-plan.json', stage.assetPlanRaw);+ }+ if (stage.kind === 'assets') {+ const overviewItems = (stage.items || []).filter((item) => item.src);+ if (overviewItems.length) {+ body += `<section class="detail-section asset-overview-section"><div class="detail-section-title"><h3>素材全览</h3><span>${overviewItems.length} ASSETS</span></div><div class="asset-overview-grid">${overviewItems.map((item, index) => `<figure><img src="${esc(item.src)}" alt="${esc(item.title || item.id || '')}" loading="lazy"><figcaption><span>${String(index + 1).padStart(2, '0')}</span><strong>${esc(item.title || item.id || `Asset ${index + 1}`)}</strong></figcaption></figure>`).join('')}</div></section>`;+ }+ body += `<section class="detail-section"><h3>Prompt + 结果</h3><div class="prompt-list">${(stage.items || []).map((item, index) => `<details class="prompt-item" ${index === 0 ? 'open' : ''}><summary><span>${String(index + 1).padStart(2, '0')}</span><strong>${esc(item.title || item.id || `Asset ${index + 1}`)}</strong></summary><div class="prompt-result">${item.src ? `<img src="${esc(item.src)}" alt="${esc(item.title || '')}">` : '<div></div>'}<pre>${esc(item.prompt || '未记录 Prompt。')}</pre></div></details>`).join('')}</div></section>`;+ body += textSection('prompts.md', stage.raw);+ }+ if (stage.kind === 'html') {+ body += textSection('index.html', stage.fullCode || stage.code, true);+ body += mediaSection(stage.render, '渲染结果');+ }+ if (stage.kind === 'review') {+ body += textSection('render-review.md', stage.raw || '未记录。');+ }+ if (stage.kind === 'layers') {+ body += `<section class="detail-section"><h3>分层契约</h3><p>${stage.layerCount || 0} editable layers\n${stage.groupCount || 0} explode groups\n${stage.componentCount || 0} gallery components</p></section>`;+ body += mediaSection(stage.preview, '可编辑分层动画(HTML)', stage.preview?.includes('.html'));+ }+ return `<div class="detail-head" style="--detail-color:${phaseColor[stage.phase]}"><img src="icons/${esc(stage.kind)}.png" alt=""><div><small>${esc(stage.order)} · ${esc(stage.kind)}</small><strong>${esc(stage.title)}</strong></div></div><div class="detail-body">${body}<section class="detail-section"><h3>真实来源</h3><p>${esc(stage.sources?.join('\n') || '无')}</p></section></div>`;+ }++ function selectStage(id, updateUrl = true) {+ const stage = stageById.get(id);+ if (!stage) return;+ selected = id;+ document.querySelectorAll('.stage-node').forEach((node) => node.classList.toggle('is-selected', node.dataset.stage === id));+ phaseNav?.querySelectorAll('button').forEach((button) => button.classList.toggle('is-active', button.dataset.phase === stage.phase));+ detailContent.innerHTML = detailFor(stage);+ detailPanel.classList.add('is-open');+ if (updateUrl) {+ const url = new URL(location.href);+ url.searchParams.set('stage', stage.order.replace(/^0/, ''));+ history.replaceState(null, '', url);+ }+ }++ function applyTransform() {+ world.style.transform = `translate(${tx}px, ${ty}px) scale(${scale})`;+ zoomLabel.value = `${Math.round(scale * 100)}%`;+ zoomLabel.textContent = zoomLabel.value;+ window.dispatchEvent(new CustomEvent('poster-replay-viewchange', { detail: { scale } }));+ }++ function fitView() {+ const pad = 34;+ const availableW = viewport.clientWidth - pad * 2;+ const availableH = viewport.clientHeight - pad * 2;+ scale = Math.min(1, availableW / WORLD_WIDTH, availableH / WORLD_HEIGHT);+ tx = (viewport.clientWidth - WORLD_WIDTH * scale) / 2;+ ty = (viewport.clientHeight - WORLD_HEIGHT * scale) / 2;+ applyTransform();+ }++ function zoomBy(factor, centerX = viewport.clientWidth / 2, centerY = viewport.clientHeight / 2) {+ const next = Math.max(.18, Math.min(1.65, scale * factor));+ const worldX = (centerX - tx) / scale;+ const worldY = (centerY - ty) / scale;+ scale = next;+ tx = centerX - worldX * scale;+ ty = centerY - worldY * scale;+ applyTransform();+ }++ data.stages.forEach(renderStage);+ renderArtifacts();+ renderLines();++ document.getElementById('fit-view').addEventListener('click', fitView);+ document.getElementById('zoom-out').addEventListener('click', () => zoomBy(.86));+ document.getElementById('zoom-in').addEventListener('click', () => zoomBy(1.16));+ document.getElementById('detail-close').addEventListener('click', closeDetail);+ document.getElementById('media-lightbox-close').addEventListener('click', closeMedia);+ mediaLightbox.addEventListener('click', (event) => { if (event.target === mediaLightbox) closeMedia(); });+ document.addEventListener('keydown', (event) => { if (event.key === 'Escape' && mediaLightbox.classList.contains('is-open')) closeMedia(); });+ phaseNav?.querySelectorAll('button').forEach((button) => button.addEventListener('click', () => selectStage(button.dataset.stage)));+ viewport.addEventListener('wheel', (event) => { if (event.target.closest('.detail-panel,.media-lightbox')) return; event.preventDefault(); const rect = viewport.getBoundingClientRect(); zoomBy(event.deltaY < 0 ? 1.08 : .92, event.clientX - rect.left, event.clientY - rect.top); }, { passive: false });+ viewport.addEventListener('pointerdown', (event) => { if (event.target.closest('.stage-node,.external-artifact,.phase-nav,.detail-panel,.view-controls')) return; dragging = true; dragOrigin = { x: event.clientX, y: event.clientY, tx, ty }; viewport.classList.add('is-panning'); viewport.setPointerCapture(event.pointerId); });+ viewport.addEventListener('pointermove', (event) => { if (!dragging) return; tx = dragOrigin.tx + event.clientX - dragOrigin.x; ty = dragOrigin.ty + event.clientY - dragOrigin.y; applyTransform(); });+ viewport.addEventListener('pointerup', () => { dragging = false; viewport.classList.remove('is-panning'); });+ window.addEventListener('resize', fitView);++ requestAnimationFrame(() => {+ fitView();+ const requested = new URLSearchParams(location.search).get('stage');+ const requestedStage = requested ? data.stages.find((item) => item.order.replace(/^0/, '') === requested || item.id === requested) : null;+ const defaultStage = document.body.dataset.defaultStage ? stageById.get(document.body.dataset.defaultStage) : null;+ const initialStage = requestedStage || defaultStage;+ if (window.__POSTER_REPLAY_MOTION__?.mount) {+ window.__POSTER_REPLAY_MOTION__.mount({ data, viewport, world, flowLines, phaseNav, detailPanel, selectStage, initialStage, getViewState: () => ({ scale, tx, ty }) });+ } else if (initialStage) {+ selectStage(initialStage.id, false);+ }+ });+})();diff --git a/skills/editable-design/pack.sh b/skills/editable-design/pack.shnew file mode 100755index 0000000..bd3c26d--- /dev/null+++ b/skills/editable-design/pack.sh@@ -0,0 +1,19 @@+#!/usr/bin/env bash+set -euo pipefail++skill_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+parent_dir="$(cd "$skill_dir/.." && pwd)"+out="${1:-${TMPDIR:-/tmp}/editable-design-skill.tar.gz}"++mkdir -p "$(dirname "$out")"+tar \+ --exclude='editable-design/scripts/node_modules' \+ --exclude='editable-design/._*' \+ --exclude='editable-design/*/._*' \+ --exclude='editable-design/*/*/._*' \+ --exclude='editable-design/.DS_Store' \+ -czf "$out" \+ -C "$parent_dir" \+ editable-design++echo "$out"diff --git a/skills/editable-design/references/asset-architecture.md b/skills/editable-design/references/asset-architecture.mdnew file mode 100755index 0000000..38e32b3--- /dev/null+++ b/skills/editable-design/references/asset-architecture.md@@ -0,0 +1,72 @@+# Asset architecture++Read this only after [SKILL.md](../SKILL.md) selects a slot matrix, cutout stack,+or layered collage. `SKILL.md` owns topology and asset count; this reference+owns multi-asset cohesion and the `asset-plan.json` schema. [Imagery](imagery.md)+controls how each asset is prompted and validated.++## Multi-asset cohesion++### Slot matrix++Use for product families, catalog grids, comparisons, specimens, menus, and+timelines. Give every bounded cell its own asset and let HTML define identical+cell geometry, gutters, labels, and alignment.++Freeze one shared art-direction block for all prompts: camera, lens or rendering+style, viewpoint, lighting, background treatment, scale, palette, and crop. Add+only the subject-specific difference to each prompt. Prose alone does not lock a+series: when material, camera, and set continuity matter, give every slot the+same visual style anchor. Prefer the non-shipping art-directed reference when it+already defines the set; otherwise generate and approve one canonical slot,+then use it as the style reference for the remaining slots. Record the anchor in+`asset-plan.json`. If exact branded products are required, use supplied+packshots; do not invent packaging, labels, or product variants.++### Cutout stack++Use when subjects float over a field, overlap one another, or cross typography.+Plan the order explicitly, for example: backdrop, rear decoration, headline,+main subject, foreground detail, metadata. Put exact text in HTML at the correct+position in that order; never bake it into a cutout.++Use one transparent file per independently movable subject. Follow the+transparency workflow in [Imagery](imagery.md), and keep enough clean padding+around each subject for reliable extraction and cropping.++### Layered collage++Use a restrained base field plus a purposeful set of fragments. Split only+pieces whose overlap, angle, crop, or replacement matters. Generate photographic+or materially complex fragments; make simple tape, rules, flat paper polygons,+and frames in HTML/CSS. Reuse a fragment only when repetition is visibly part of+the design language.++Vary scale, angle, edge treatment, and depth, but preserve one palette and one+material logic. Avoid filling every gap: collage still needs hierarchy and+negative space.++## `asset-plan.json`++Create this only when two or more shipping assets are required. Keep it small.+For every asset record:++- `id` and `form`: `backdrop`, `slot`, `cutout`, or `fragment`;+- `rect`: intended `x`, `y`, `width`, and `height` on the poster canvas;+- `layer`: its named position in the back-to-front order;+- `prompt`: the prompt identifier stored in `prompts.md`;+- `style_reference`: the common visual anchor path or `null`;+- `depends_on`: the prerequisite asset only when returned pixels from it are+ required, otherwise empty;+- `source`: `generated`, `user`, or `provided-reference`.++List HTML text and geometry layers separately so the overlap order is explicit.++## Assembly checks++- Inspect every asset alone before assembly, especially alpha edges and unwanted+ generated lettering.+- Inspect the final render for rectangular seams, inconsistent light direction,+ mismatched scale, accidental tangencies, and text trapped between busy layers.+- If the composition only works after hiding seams with gradients and shadows,+ the split was wrong. Regenerate a continuous scene or change the architecture.diff --git a/skills/editable-design/references/editor-pitfalls.md b/skills/editable-design/references/editor-pitfalls.mdnew file mode 100755index 0000000..75c3198--- /dev/null+++ b/skills/editable-design/references/editor-pitfalls.md@@ -0,0 +1,70 @@+# 已知陷阱清单++全部为实际踩到并修复的问题,编辑器外壳里已处理。**遇到偏差不为 0 或功能异常时+先查这里**,不要重写外壳。++## 固化阶段++| # | 陷阱 | 处理 |+|---|---|---|+| T1 | 边量边改导致后续元素上跳 | 严格两趟:先全量测量并缓存,再统一写入 |+| T2 | 图层抽走后容器塌陷。尤以 `bottom` 定位的容器为害:高度一塌,容器整体下移,容器内**未被抽走的**元素(如分隔线)跟着跑位 | 测量阶段一并记录所有「含图层的祖先容器」,在抽离前把 `width/height` 钉死 |+| T3 | `margin` 残留。文档流元素靠 `margin-top` 排版,转 absolute 后 margin 仍生效,元素在新坐标基础上再偏移 | 写入时统一 `margin:0` |+| T4 | 把 `transform` 一律清空虽能解决 `translateX(-50%)` 的重复偏移,却会抹掉邮戳、回形针、手写贴纸等设计旋转 | 分别保存未变换布局尺寸、computed transform 与 transform-origin;提升后重施矩阵,再用可见包围盒差值反算 `left/top` |+| T5 | `right` / `bottom` 定位的元素改 `left/top` 无效 | 写入 `left/top` 的同时把 `right/bottom` 置 `auto` |+| T6 | z-index 与上下文样式丢失。元素移出原容器后,`.dark-card .label` 等祖先选择器不再命中;模块底色、图片、未标分隔线和 copy 的绘制次序也可能翻转 | 提升前保存发生变化的 computed/pseudo 样式并最小化内联;按顶层 stacking 顺序分配 z 段,区分“容器自身是 surface”与“独立 surface 叶子”两种模块 |+| T7 | 宽度塌缩。文档流元素宽度由父容器给定,转 absolute 后塌成 `fit-content`,文字重新换行 | 写入测得的 `width` |+| T8 | 字体未加载完就测量,量到的是 fallback 字体的坐标,落盘后整个版面偏移 | 固化前 `await document.fonts.ready` |+| T9 | 图片未加载完就测量(高度为 0)。**加载失败也必须放行**,否则一张坏图卡死整个编辑器 | 等待所有 `img` 的 `load` 与 `error` |+| T10 | DOM 提升顺序反转。多个图层依次插入同一锚点后顺序会颠倒,绘制次序随之改变 | 每组维护滚动锚点,插入后把锚点更新为刚插入的元素 |+| T11 | 被抽空的容器仍会捕获 pointer 事件,挡住下方图层 | 锁尺寸时一并设 `pointer-events:none` |++## 交互阶段++| # | 陷阱 | 处理 |+|---|---|---|+| T12 | **`pointerdown` 里调 `preventDefault()` 会抑制后续 `click` / `dblclick`**(Pointer Events 规范:阻止默认行为会连带抑制兼容鼠标事件)。表现为双击完全无法进入文本编辑 | 不在 `pointerdown` 阻止默认行为;防止拖拽误选文字改为「移动超过阈值后再设 `user-select:none`」 |+| T13 | **`setPointerCapture` 会把后续 `click` / `dblclick` 的 `target` 重定向到捕获元素**。表现为双击图层内的子元素时 `e.target` 变成整个图层,找不到文本槽。若图层自身恰好就是文本槽则「碰巧能用」,极具误导性 | ① 指针捕获推迟到确认拖拽之后;② `dblclick` 不信任 `e.target`,改用 `document.elementFromPoint()` 重新命中 |+| T14 | 画布整体 `scale` 后屏幕位移与画布位移不等,不换算则拖拽明显不跟手 | `dx = (e.clientX - startX) / scale` |+| T15 | 文本编辑态下方向键同时移动光标和图层 | 编辑态的 keydown 在 capture 阶段 `stopPropagation()` |+| T16 | **中文输入法**:组字期间 Esc 是「取消候选词」、Enter 是「上屏」。不区分则用户打字打到一半就被踢出编辑态 | 按键处理第一行即 `if (e.isComposing \|\| e.keyCode === 229) return;` |+| T17 | 文本编辑粒度若取整个图层,多字号拼排结构会被破坏(如价格由 `.cup`/`.num`/`.yuan` 三个不同字号字色的 span 拼成,整块 `contenteditable` 时一个退格即崩) | 编辑单元下沉到**文本槽**:图层内部只承载文字的叶子节点;图文混排节点整体算一个槽;SVG 子树排除 |+| T18 | 从外部粘贴带格式内容会把 HTML 污染进海报 | `contenteditable="plaintext-only"` |+| T19 | 文字改长或字号变大后被固化宽度挤到换行;但用户手动缩窄文本框时又确实需要换行 | 默认提交时按需扩宽且**不主动收窄**;一旦用户使用宽度手柄,就标记为手动宽度,后续文字与字号编辑保留该宽度 |+| T23 | `documentElement` 上的 `data-hf-ready` 标记会被 `cloneNode` 带进导出物 | 导出时移除所有 `data-hf-*` 属性(含 `<html>` 自身) |++## 测试与环境++| # | 陷阱 | 处理 |+|---|---|---|+| T20 | **Puppeteer 的 `clickCount: 2` 不产生 `dblclick`**。它只设置参数、不真的按两次,`detail` 恒为 1,浏览器不合成双击。会误判成功能 bug | 手动发两轮 down/up,第二轮传 `clickCount: 2`,此时 `detail=2`、`dblclick` 正常派发 |+| T21 | headless Chrome 启动被用户已开着的实例干扰,报 `Timed out waiting for the WS endpoint URL` | 每次用全新的临时 `--user-data-dir`(顺带保证 localStorage 干净,草稿不干扰固化) |+| T22 | 断言「导出物无编辑器残留」时,注入的 **HTML 注释节点**不会被 `querySelectorAll` 删除 | 用 `TreeWalker(SHOW_COMMENT)` 一并清理(当前外壳改为动态创建 DOM,已不注入注释) |+| T24 | `document.fonts` 含**所有**声明的 `@font-face`,未被使用的(如仅作 fallback 列出的字体)一直是 `unloaded`,这是按需加载的正常行为 | 断言只用 `document.fonts.status === 'loaded'`,不要求每个 FontFace 都 loaded |+| T25 | Google Fonts 把中文字体切成上百个 `unicode-range` 分片,同一 family 下必然部分 loaded 部分 unloaded | 判断一个 family 是否真的没用上,要看「是否**没有任何**分片被加载」 |+| T26 | 契约检查里把图层的祖先容器误报成「漏标 `data-layer-id`」——容器本身没有 layer-id,但它只是包装 | 候选块需额外排除「内部含 `[data-layer-id]`」的元素 |+| T27 | 拆解视图开启后原画布被 `display:none`,此时再次下载拆解稿若现场读 `offsetWidth/Height` 会全部得到 0,导出空稿 | 进入拆解态前缓存每层几何;隐藏后导出使用缓存,不重新测量不可见画布 |+| T28 | 用随机数或直接动画 `left/top` 做拆解,会让每次录制位置不同、截图中途态漂移,并破坏确定性验收;系统“减少动态效果”下还可能卡在初始态 | 终态只由确定性 `left/top` 决定;动画仅叠加 Web Animations 的 `transform/opacity/filter`,结束后取消动画回到 CSS 终态;支持 `prefers-reduced-motion` 与 `?motion=0`,独立稿动画完成后才设置 ready 锚点 |+| T29 | 拆解舞台过宽会让扫描原稿骤缩;列数太少又会把组件挤成细小侧注 | 使用平衡舞台 `max(1.7×画布宽, 1.275×画布高)`;扫描原点保留编辑态高度至少约 68%,终态按组件数自动使用 2–5 列,并分别约束总览、背景和内容组件的缩放 |+| T30 | 先播放扫描、之后才创建拆解动画,会让图层在扫描期间提前闪到最终位置;扫描层若未纳入统一结束处理,也会残留遮罩或卡住 ready | 首帧即创建全部 WAAPI:利用 `delay + fill:both` 把图层钉在成稿位置,扫描尾段与散开重叠;扫描层置于独立高层且终帧透明,统一等待和取消;reduced-motion / `?motion=0` 直接跳到终态 |+| T31 | 只比较 `getBoundingClientRect()` 会把“坐标没变、底色/伪元素/图片/层级已丢”的稿件误判为零偏差 | A 类验收同时截取原稿与 baked 稿做像素比较;几何比较负责定位,像素比较负责视觉真值 |+| T32 | 海报画布用渐变纸张而 `background-color:transparent` 时,直接读 backgroundColor 会得到透明黑并把拆解舞台误判成黑色 | 优先读取不透明背景色;透明时解析 background-image 中的近不透明颜色,再回退页面底色/暖白 |+| T33 | 中央常驻完整成稿或大幅空背景,会让终态看起来没有真正拆开并制造无意义留白;继续钻取第二层又会产生过细采集 | 动画起点把组件叠回完整成稿;终态把完整总览、未标记背景和一级内容全部缩成画廊组件,中央不留固定基底,也不提供第二级叶子钻取 |+| T34 | 从 Grid/Flex 模块容器中直接删除非目标兄弟,会让目标卡自动补位;按原坐标裁切时卡片底色消失,只剩已提升的文字/图标 | 非目标模块改用 `visibility:hidden` 保留布局占位,随后再移除其叶子;不要删除决定轨道位置的兄弟包装 |+| T35 | FLIP 散开动画把整个模块从扫描原点移动到画廊时,模块说明标签也会随父项同步缩放,运动中变成遮住海报的巨型省略文字;即使停稳后全部常驻,也会重复模块内已有标题 | 模块标签默认隐藏;仅在舞台停稳且用户悬停/聚焦具体模块时淡入,离开即隐藏。名称仍保存在 `title` 中供发现,但不污染扫描动画或静止拆解稿 |+| T36 | 分组容器只包绝对定位叶子时自身宽高可能为 0,按容器盒裁切会把模块压成不可见细条;一级有效组件过少时画廊也显得空 | 分组盒无效或远小于成员联合边界时回退到成员几何并集;一级内容组件少于 5 个时,把分组内有文字且非 surface/image/icon/decoration 的叶子作为同级补充 tile,保持一级结构不增加钻取层级 |+| T37 | 把缩放手柄画在已整体 `scale()` 的画布内,会让点击区域随缩放变小;用图层伪元素又无法可靠接收独立的八向拖拽;可见角点若同时就是命中区,在高密度海报上仍很难点中 | 在未缩放舞台中维护独立选框:显示坐标乘 `scale`,指针位移除以 `scale`;手柄使用约 32px 的透明命中区包住 12px 可见标记;进入文字编辑或拆解视图时隐藏,导出时彻底移除 |+| T38 | 在真正拖动前尚未建立 pointer capture;此时若指针在画布外松开、窗口失焦或浏览器取消手势,`pointerup` 可能不到达画布,旧手势会保持 armed,鼠标回来后图层继续跟随 | 在 window capture 阶段兜底处理 `pointerup/pointercancel`,监听 `lostpointercapture`、窗口失焦和页面隐藏;`pointermove` 发现主键已松开就立即结束;`Esc` 取消并恢复本次手势,下一次 pointerdown 先终止任何残留手势 |++## 诊断偏差不为 0++`bake.mjs` 报偏差时,按可能性排序检查:++1. 契约未满足 —— 先跑 `check-contract.mjs`,十有八九是 `vw/vh/%` 或字体没等到+2. 上表 T1–T11 未覆盖的布局:`float`、`position:sticky`、伪元素撑开高度、+ `writing-mode`、CSS `columns`、`subgrid`+3. 图层之间有重叠依赖(一个图层的位置由另一个图层的内容高度决定)++定位方法:`bake.mjs` 的输出逐图层列出了原始与固化后坐标,先看**哪些图层偏了、+偏移量是否相同**。同一容器内的图层偏移量一致,通常是 T2 容器塌陷;单个图层偏移+等于某个 margin 值,是 T3;旋转饰物的包围盒与角度不一致,是 T4。diff --git a/skills/editable-design/references/editor-runtime.md b/skills/editable-design/references/editor-runtime.mdnew file mode 100644index 0000000..695b4b3--- /dev/null+++ b/skills/editable-design/references/editor-runtime.md@@ -0,0 +1,131 @@+# Editor and exploded views++Read this when wiring, validating, baking, or diagnosing the bundled poster+editor. `poster-building` is the only required skill; no separate editor skill+or runtime is needed.++## Ownership and delivery++- `assets/editor/layer-editor.css` and `layer-editor.js` are the canonical+ runtime. Do not rewrite them per poster.+- `scripts/init-poster.sh` copies that runtime into+ `PROJECT/scripts/editor-assets/`.+- `PROJECT/scripts/wire-editor.mjs` copies the runtime beside `index.html` and+ creates `editor.html` without modifying `index.html`.+- The finished project remains offline and self-contained. Editor controls never+ enter the PNG because rendering always targets `index.html`.++## First use of validation tools++The browser-driven validation tools need `puppeteer-core`. Install it once in+the skill's `scripts/` directory:++```bash+npm ci --prefix <poster-building-skill>/scripts+```++The interactive `editor.html` itself needs no installation and no local server.++## Contract and wiring++Run the poster's normal static check first. For a browser-measured compatibility+preflight before the first render, then wire and verify from any directory with+absolute paths:++```bash+node <poster-building-skill>/scripts/check-contract.mjs PROJECT/index.html+node PROJECT/scripts/wire-editor.mjs PROJECT/index.html+node <poster-building-skill>/scripts/verify.mjs PROJECT/index.html+```++Fix every contract or verification failure before delivery. Do not patch the+editor runtime around a poster-specific violation. Verification compares both+layer geometry and rendered pixels: matching rectangles alone cannot detect a+lost card surface, contextual style, pseudo-element, blend, or paint order.++The poster authoring contract is defined in `SKILL.md`; this reference owns only+runtime wiring, verification, baking, and diagnosis.++## Standalone exploded view++`editor.html` already provides scan, one-level content spreading,+reverse-collapse, and download controls. Every poster also ships a standalone+`layers.html`. Groups appear as whole modules; ungrouped content appears as+individual units. If that produces fewer than five primary content units, the+gallery keeps those modules and additionally promotes their grouped text leaves+to companion units. This is a one-level density fallback, not a second-level+drilldown. The normal+`verify.mjs` run writes the verified file without another browser launch.+Use `explode.mjs` only to regenerate it separately while diagnosing a failure:++```bash+node <poster-building-skill>/scripts/explode.mjs PROJECT/index.html+node <poster-building-skill>/scripts/explode.mjs PROJECT/index.html PROJECT/layers.html+```++The exported view contains a small complete-composition overview, a small tile+for the unmarked paper/texture/fixed frame, whole content modules, and ungrouped+units. They spread into a 2–5 column component gallery with no+permanent central base. At the animation origin all tiles overlap at their+original coordinates, so the complete poster is reconstructed before it+separates. Text, images, and SVG remain DOM clones. The stage follows the+poster's actual paper or background tone, including dark hues, instead of+collapsing every dark poster to generic black. This preserves the intended+contrast of thin and low-opacity layers. In isolated content tiles only,+computed opacity below 0.55 receives a bounded presentation boost; the complete+overview remains visually faithful to the poster. It is a presentation artifact,+not a second editor.+Continue editing in `editor.html`.++The transition uses a scan beam followed by deterministic FLIP-style spreading.+Only `transform`, `opacity`, and `filter` animate; final `left` and `top` remain+deterministic. `prefers-reduced-motion` is respected, and `?motion=0` opens at a+stable end state for screenshots and automated review, with the replay-animation+control hidden because there is no motion to replay.++The settled view uses the center as part of the gallery. Column count depends+only on the effective component count after the small-gallery text fallback;+original horizontal position is a light placement preference, and visual weight+balances the columns. There is no second detailed collection pass.++## Optional offline bake++Use baking only when a stable, absolute-positioned source is useful for CI or+future editing:++```bash+node <poster-building-skill>/scripts/bake.mjs PROJECT/index.html+node <poster-building-skill>/scripts/bake.mjs PROJECT/index.html --in-place+```++The in-place form overwrites the source, so use it only when that exact target+is intended and recoverable. Baking must not land when any layer drifts by more+than 1px.++## Editor scope++The editor supports dragging, alignment snapping, arrow-key nudging, eight-handle+resizing, plain-text editing, proportional font scaling, switching among+declared font stacks, delete, undo, local drafts, scan/explode/collapse, and+clean normal or exploded HTML downloads. Left and right handles change width,+top and bottom handles change height, and corners change both. A width set by a+handle remains fixed during later text or font-size edits so wrapping follows+the user's chosen box; resize state participates in undo, draft restore, reset,+position-CSS export, and clean HTML export.++Pointer gestures must always have an exit path. Releasing anywhere, pointer+cancellation, capture loss, window blur, or hiding the page ends the active+gesture. Pressing Escape during a drag or resize cancels that gesture and+restores its starting geometry; pressing Escape afterward clears selection.++It intentionally does not add arbitrary layers, import images, reorder the+stack, rotate, recolor, or expose full typography controls. It is for human+micro-adjustments after design, not for redesigning the poster.++The automation anchor is `html[data-hf-ready]`. The public API is+`window.__layerEditor`, including `fullHTML()`, `explodedHTML()`, `download()`,+`downloadExploded()`, `undo()`, `select()`, `scaleFont()`, `setFont()`,+`removeLayer()`, `setExploded()`, `layers()`, and `state`.++When validation reports drift or an interaction fails, read+[Editor pitfalls](editor-pitfalls.md) before changing the runtime.diff --git a/skills/editable-design/references/imagery.md b/skills/editable-design/references/imagery.mdnew file mode 100755index 0000000..b27ccfb--- /dev/null+++ b/skills/editable-design/references/imagery.md@@ -0,0 +1,145 @@+# Imagery++Read this before writing any shipping-asset prompt, and again when generated+artwork comes back wrong: lettering appeared in the image, the composition does+not match its slot, a band that should be empty has objects in it, a cutout has+a dirty matte, or the crop does not fit its planned region. [SKILL.md](../SKILL.md)+owns asset topology, count, batching, and import policy; this reference owns+prompt construction and returned-image diagnostics.++## Reserved space: describe appearance only++Work out which regions text will cover, then **describe those regions purely by+their physical properties**:++```+WRONG: "leave clean dark negative space at the top for the headline"+RIGHT: "the top third is a continuous, low-detail, darker sky with no objects,+ symbols, borders, or high-contrast marks in it"+```++**Measured: naming the occupant produced an artefact 10 times out of 10;+describing appearance only, 0 times out of 13.** Holds across two scenes and two+framing nouns.++The trigger phrases are "for the headline", "space for the logo", "room for the+price", "space for copy". Tell the model something goes there and it draws+something — sometimes real lettering, sometimes an empty oval or bar. The second+is just as harmful: your HTML text lands on it and both become unreadable.++Say what the region **is**: sky, a wall, blurred foliage, flat shadow, an even+wash of paper — and that it is empty and uniform.++## A stated proportion is an intent, not a contract++Naming a share of the frame gets you a region of roughly that kind, not a region+of that size. Measured across two backdrops from the same model: one asked for a+clean right-hand 16 percent and got 22 percent; the other asked for 34 percent and+got **11**. Over-delivery and under-delivery, same wording pattern, same backend.++So never lay out against the number you asked for. Either measure the generated+backdrop before writing any coordinates — scan it in horizontal or vertical strips+and find where the ink actually starts — or leave far more margin than the layout+needs and accept the wasted space. A layout that survives only because the margin+happened to be generous was saved by luck, not by planning.++## Band phrasing++Describe a full-bleed backdrop as horizontal bands, one sentence each, giving+four things: position and share of the height, the material, the brightness, and+the detail density.++```+The composition reads as three horizontal bands.+Top 35 percent: an unbroken, even, pale grey-white fog sky, completely smooth+and uniform, no clouds, no birds, no sun disc, no objects, no marks, and no+high-contrast detail anywhere in it.+Middle band, about 37 percent of the height: layered ridgelines of tea terraces+receding into mist, dark blue-green silhouettes, soft atmospheric perspective,+the strongest detail of the whole frame concentrated here.+Bottom 28 percent: a flat, even wash of low-lying pale mist, extremely low+texture, uniform brightness, empty.+```++Two to four bands are both reasonable; let the layout decide. Bands that will+carry text need brightness well separated from the text colour. Bands that carry+no text are where the subject and the detail belong.++**Write the prompt in English even when the poster is in another language.**+Image models follow English more reliably and the prompt never appears in the+poster.++Note the difference between the "no clouds, no birds, no objects" above and a+negative instruction. Those clauses modify something already described+positively — they say how clean that fog sky is. "no text" modifies nothing.++## Negative instructions do not work++"no text, no lettering" has been measured to have no effect. Most current+image backends are not diffusion models: a diffusion model's negative prompt+genuinely subtracts a negative embedding inside CFG, whereas a multimodal model+generating an image has no such channel — the negation is just a few more tokens,+and models handle negation poorly to begin with.++Describing appearance is the mechanism that actually works.++## Size++**Use the size parameter when the tool has one; do not describe the frame in+prose.** A parameter is deterministic, prose is probabilistic.++- A full-bleed image gets the canvas proportions+- Slot artwork gets the slot's own dimensions+- If the tool only accepts an aspect ratio, give the ratio+- With no size control at all, the frame can only be implied in prose ("tall+ vertical portrait composition"), and the same prompt may return 1408x768 one+ time and 896x1200 the next. Expect to retry++When the returned image has the wrong proportions, crop it deliberately with+`object-fit` and `object-position`; never let it stretch. **Crop toward the bands+that carry no text** — keep the flat band the headline sits on and give up the+one nothing lands on.++## Transparent assets++Native transparency is an output control, not a visual prompt style. Follow the+active image-generation capability's transparency workflow. When the active+surface exposes a background parameter, pass `transparent` explicitly and use+PNG or WebP; do not rely on prompt wording alone. In the default Codex ImageGen+path, if no background parameter is exposed, ask for a genuinely transparent+background, never describe a checkerboard, preserve any returned alpha channel,+and treat the result as provisional until inspected.++Before importing a transparent asset, confirm that the file has an alpha channel+and that its empty corners are transparent. An RGB file that visibly contains a+checkerboard has baked pixels, not transparency. If the subject is correct but+the alpha check fails, do not spend another generation retry on the same subject:+use deterministic local alpha extraction when the edges permit it, or switch to+an explicitly authorized API/CLI path that can pass `background=transparent`.++Generate each independently movable cutout as its own file. One call containing+several separated subjects still returns one bitmap and does not create several+transparent assets.++Ask for a compact subject with room around it so it can be positioned and+cropped cleanly.++## Contrast where text sits over artwork++Use an explicit treatment sized to the text block: a solid panel, a scrim, or a+directional gradient. Do not count on the image being dark enough exactly where+you need it — change the scale and it no longer is.++Watch the edges of a scrim: the hard edge of a semi-transparent rectangle is+visible in the render. Either run it to the canvas edge or fade it out.++## Controllable and not++**Controllable**: the prose description, reference images (image-to-image and+local edits), cutouts, output size or ratio.++**Not controllable**: seed and reproducibility (the same prompt differs every+time; retrying is the only lever), negative prompts, or several independently+editable files from one built-in call.++Neither column depends on which image tool is behind it.diff --git a/skills/editable-design/references/layout-typography.md b/skills/editable-design/references/layout-typography.mdnew file mode 100755index 0000000..065f94b--- /dev/null+++ b/skills/editable-design/references/layout-typography.md@@ -0,0 +1,110 @@+# Layout and typography++Read this before writing HTML when the layout is unclear, and again when the+render is "correct everywhere but does not look designed". The "Shape the poster"+section of [SKILL.md](../SKILL.md) is the entry point.++A poster is read from a distance, scanned once, and taken in a fixed order.+Everything below serves that.++## Layout++**Hierarchy is the whole job.** A viewer should absorb a poster in three passes:+the hook, then the claim, then the detail. Build that staircase with size,+weight, colour, and white space, and make the steps genuinely different. Two+elements of similar visual weight compete and both lose. Emphasising everything+emphasises nothing.++**White space is structure, not what is left over.** Generous, deliberate margins+and gutters are the line between a designed poster and a filled one.++**Align to a grid.** Fix the margins and columns first, then place everything on+them. Optical alignment beats an offset you typed from memory; an edge that is+almost aligned reads as a mistake.++**Control the palette by role, not count.** Define the field, text, accent, and+semantic roles first. A restrained poster may need very few colours; a brand,+reference-led, or information-dense poster may need more. Every colour must+have a compositional or semantic job.++**Commit to one direction** — editorial, luxury, brutalist, playful, technical.+Pick one and let it drive every decision. A poster hedging between two reads as+neither.++**Anti-patterns:**++- Centring everything by default+- Equal spacing between unrelated blocks, flattening the hierarchy+- Text straight over busy artwork with no contrast treatment+- Borders, badges, and rules filling space in place of real structure+- Drop shadows and gradients patching a weak layout+- Marketplace styling: starbursts, unmotivated diagonal ribbons, clip art++A poster should look considered at full size and still read structurally as a+thumbnail.++## Working with the backdrop++Once the full-bleed backdrop exists, you are not laying out on white paper — you+are laying out on that image's bands.++- Text blocks land on the **flat** bands; the subject and the detail keep their own+- Let the text margins breathe with the image's composition; do not run type+ along the edge of the subject+- More than two levels of hierarchy inside one band wastes the flatness you+ asked the band for+- If the backdrop changes, revisit the layout. The same coordinates rarely hold+ on a different image++## Typography++Declare font stacks as custom properties on `:root` and reference them+throughout. Give every family a distinct job and valid script coverage. Add a+family when the brand, reference, script, or typographic contrast requires it,+not as decoration.++**Build a real size ramp.** display, headline, subhead, body, caption, each+clearly different from the last. A ramp with 10 percent steps reads as an error.++- Tighten tracking on large display type; open it slightly on small caps+- **A single-line block with `letter-spacing` needs `white-space: nowrap` or an+ explicit width.** CSS adds the tracking after the last character too, so the+ measured content width is a fraction wider than the glyphs need. Anything that+ later writes that measured width back — an editor converting the layout to+ absolute positioning, for instance — pushes the last character onto a second+ line. The block's height doubles and nothing reports an error+- Line height: 1.1–1.2 for display, 1.5–1.7 for body+- Keep poster body copy to 20–40 characters per line+- Do not run text to the edge; respect the margins you set+- Nothing below 9px after rendering. Small type is still meant to be read++## CJK typography++- **Choose a family that genuinely covers the script.** A Latin-only family must+ not set CJK text; use a CJK-capable family in that stack+- **No synthetic italics or synthetic bold.** Use a real weight, or another family+- **Weight is a choice of family, not only of `font-weight`.** Kai, running-script,+ and handwriting faces are structurally thin and stay thin at any size, so a+ headline set in one looks weightless however large. When a headline has to hold+ the page, take the weight from the family itself+- **CJK display type tolerates tight tracking; body copy does not**+- **In mixed settings put the Latin family first in the stack**, otherwise digits+ and roman characters inherit the CJK face's proportions++## Markup and CSS conventions++- **`* { box-sizing: border-box; }`**, always. `getBoundingClientRect()` reports+ the visual width including padding; under content-box, anything that writes that+ measured width back into `width` adds the padding a second time. A pill-shaped+ tag with `padding: 20px 44px` grows 88px wider every round trip, and nothing+ reports an error+- One file. CSS in a single `<style>` in the head. Zero external requests+- Palette and font stacks as `:root` custom properties, referenced throughout+- Layers absolutely positioned inside the canvas, so every coordinate is explicit+- Fixed px for every dimension, position, and gap that carries layout. No+ vw/vh/vmin/vmax/%. Decorative values — gradient stops, radii, shadow spread,+ texture `background-size` — are unrestricted+- Semantic class names describing the block's role on the poster+- Image paths relative to the poster file+- Never embed, print, or commit a key or credential+- **Do not write comments**diff --git a/skills/editable-design/references/replay-contract.md b/skills/editable-design/references/replay-contract.mdnew file mode 100644index 0000000..76dcc70--- /dev/null+++ b/skills/editable-design/references/replay-contract.md@@ -0,0 +1,166 @@+# Agent design replay contract++Read this only when recording, generating, or diagnosing a poster Replay.+The Replay is a deterministic view of the actual run, not a second design task.++## Seven story stages++Production may use more steps, but the viewer always groups evidence into:++1. Input — the user's original request and supplied attachments.+2. Reference — the exact enhanced art-direction prompt and its generated image.+3. Plan — composition notes, zones, asset topology, and slot geometry.+4. Assets — each shipping prompt paired with its imported result.+5. HTML — real source code and the rendered poster.+6. Review — concrete findings, changes, and rerender outcomes.+7. Layers — the verified editor or standalone exploded view and contract counts.++Canvas choice, font checks, cleanup, imports, and command logs remain in+`.trace`; they are metadata inside these stages rather than separate story nodes.++## Evidence files++- `brief.md` — the original user request verbatim. Include attachment paths, but+ do not copy ambient UI state, system instructions, or hidden context into it.+- `reference/composition-prompt.md` — the exact prompt sent to the image model+ for the non-shipping art-direction reference.+- `reference/composition-reference.png` — the generated reference image.+- `design-plan.md` — the single integrated decision for live wording,+ hierarchy, asset topology, regions, layer order, palette, typography, and+ geometry.+- `asset-plan.json` — asset IDs, target rectangles, topology, prompt IDs, and+ dependencies when more than one shipping asset is used.+- `prompts.md` — exact shipping prompts. Every `##` heading used by an asset+ must equal that asset's `prompt` value in `asset-plan.json`.+- `assets/*` — imported shipping results. Prefer an asset filename stem equal to+ its `id` in `asset-plan.json`.+- `index.html` and `out/poster.png` — source and current render.+- `render-review.md` — the agent's real visual review, not a retrospective+ marketing explanation.+- `editor.html` and `layers.html` — editable and standalone exploded results.++Record each file under its existing trace step as soon as it becomes stable.+Do not write generic sections such as “why this was done” or “what this node is+doing”. The viewer exposes the agent's actual prompt, plan, code, findings,+changes, and outputs.++## Review format++Use one section per real review pass when more than one pass occurs:++```markdown+# Render review++## Pass 01++### Findings+- Concrete visible defect.++### Changes+- Concrete edit applied to address it.++### Result+- What the rerender confirmed.++### Optimization+- The one highest-impact enhancement applied, or `none` when the approved+ render already preserves scanning, recall, and reference fidelity.+```++Do not invent a pass merely to make the Replay look active. A clean first render+may have one review section with no defects and `Optimization: none`. Keep all+real review and optimization activity in this one file, then record the+consolidated `render-review.md` once under `P16_read_render` after the final+render.++## Generation++After the poster, editor, and exploded behavior pass verification:++```bash+node scripts/build-replay.mjs .+node scripts/verify-replay.mjs replay/index.html+```++For a project created before the Replay runtime was added, call the equivalent+scripts from the installed `poster-building` skill and pass the project path.+Do not rerun the project initializer over an existing poster.++The builder emits `replay/index.html`, `data.js`, CSS, JS, and local icons. It+embeds text evidence in `data.js`, so opening the result over `file://` does not+depend on `fetch`. Media paths remain relative to the poster project.++The fixed viewer keeps three persistent phase controls visible: 理解与规划+(01—03), 生成与构建 (04—05), and 观察与修正 (06—07). Those controls live in+the scalable canvas world rather than in a fixed screen-space overlay, so fit+view cannot stack them over evidence nodes. Each phase card uses a 210 × 210px+world-space footprint with a 56px icon and a 19px label, so the controls remain+legible after fit-view scaling. A plain open finishes on the clean+overview with no stage detail expanded. An explicit `?stage=` query remains a+supported deep link, and closing a detail removes that query. Flow-arrow markers+use user-space sizing so their heads remain visually bounded when stroke widths+change.++The Design Plan, final rendered PNG, and editable layer animation share the same+right-column x-position. The generated reference is centered in the open space+between the Visual Reference and Design Plan stages. A single straight dashed+blue connector runs from stage 02, behind the centered reference, and into stage+03; no solid blue route loops above the image. The render lightbox loads the+original PNG directly and aspect-fits it within the available viewport; it must+show the full image without cropping or substituting a partial viewport capture.++The viewer has three motion states. On load it reconstructs the complete path+in 4.7 seconds: canvas settle, rapid node placement, ordered line drawing,+one phase pulse, final-output settle, and completion-light activation. The+detail panel stays fully hidden until this reconstruction completes. The+finished overview then uses no moving dashes; its first main pulse appears after+about 0.4 seconds and its first repair pulse after about 1.1 seconds, followed by+clearly visible energy packets on main paths every 1.8–3 seconds and repair paths+every 2.6–4 seconds, with at most two packets alive at once. Ambient packets+cross their paths in about 1.15 seconds. The playback control pauses ambient+motion and runs stronger+600–800ms causal pulses while synchronizing node focus, artifacts, and the+detail panel. Ambient motion pauses when the document is hidden or the canvas is+zoomed below 0.20 scale. `prefers-reduced-motion` disables all three motion+layers without hiding evidence.++The main-canvas Assets previews also use a quiet gallery cycle only in the+finished overview: each visible card brightens, rises 2–3px, gains a slightly+stronger shadow, and scales its image to 1.015 for about 700ms. After all visible+cards have been featured once, the gallery rests for a random 4–6 seconds. This+cycle pauses with ambient motion and never competes with formal playback.++The Assets detail begins with a compact visual overview of every recorded+shipping result before its Prompt/result accordions. The main canvas uses a+2540×1780 world: the Assets node shows only a short Prompt summary and balances+with the surrounding stage cards. Up to four shipping results appear beside it.+Exactly one result expands across the entire former 2×2 footprint and uses one+short dashed connector. Two to four results use the 2×2 matrix, with one+connector per visible result and no connector branches for empty slots. Every+result remains available in the detail overview.+Design Plan uses recorded rectangles when all slots provide valid geometry. If+the plan records semantic asset slots but no rectangles, the viewer lays those+real slots out as a compact matrix with their IDs and recorded roles; it never+stacks them into an apparently blank placeholder. If no slots were recorded at+all, it states that evidence is missing rather than inventing a composition.+The generated reference sits centered between the Visual Reference and Design+Plan stages at a slightly smaller scale, with their dashed connector visually+entering and leaving the image. The final render and layer output use large cards+in the right output column.+The 反馈修正 label sits on the green observation path, while the red return+path remains the visible repair loop. This keeps evidence readable without+placing an artifact between flow nodes or over their connectors.++When the layer output is `layers.html`, Replay embeds its live HTML animation,+not a GIF and not its `?motion=0` screenshot state. It auto-plays when loaded and+offers a clearly named control to play the layer animation again.++The stage detail panel is a wide, independently scrolling surface; wheel input+inside it never changes canvas zoom. Clicking the reference or final-render+artifact opens an image lightbox instead of stage details. Clicking the layer+artifact opens a large live-HTML lightbox and reloads it so its animation starts+from the beginning on every open.++The builder may derive ordering, time, canvas size, layer counts, and asset+pairings from recorded files. It must never reconstruct a missing prompt or+decision from memory. Missing evidence stays visibly missing.diff --git a/skills/editable-design/scripts/.gitignore b/skills/editable-design/scripts/.gitignorenew file mode 100644index 0000000..c2658d7--- /dev/null+++ b/skills/editable-design/scripts/.gitignore@@ -0,0 +1 @@+node_modules/diff --git a/skills/editable-design/scripts/_browser.mjs b/skills/editable-design/scripts/_browser.mjsnew file mode 100755index 0000000..f09e502--- /dev/null+++ b/skills/editable-design/scripts/_browser.mjs@@ -0,0 +1,247 @@+/**+ * _browser.mjs —— 编辑、固化、拆解与验收脚本共用的 headless 浏览器封装+ *+ * 为什么必须用真浏览器:图层坐标只能由布局引擎算出。jsdom / cheerio+ * 没有布局引擎,getBoundingClientRect() 恒返回 0,纯文本方案不可行。+ */+import { existsSync, mkdtempSync, rmSync, readFileSync, writeFileSync, copyFileSync, unlinkSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';++const ASSETS = resolve(dirname(fileURLToPath(import.meta.url)), '../assets/editor');+const ASSET_FILES = ['layer-editor.css', 'layer-editor.js'];+const TAGS = ' <link rel="stylesheet" href="layer-editor.css">\n'+ + ' <script src="layer-editor.js" defer></script>\n';++/**+ * 临时把编辑器接到一张海报上,用于离线驱动。+ * 临时 HTML 必须放在海报同目录,否则 assets/ 之类的相对路径会失效。+ * cleanup() 会移除临时文件,并将项目原有的编辑器资产逐字节还原。+ * 验收不得把技能内置运行时永久覆盖到已经完成的项目里。+ */+export function wireTemp(src, name = '_hf_tmp.html') {+ const dir = dirname(src);+ const tmp = join(dir, name);+ const originalAssets = new Map(ASSET_FILES.map((f) => {+ const target = join(dir, f);+ return [f, existsSync(target) ? readFileSync(target) : null];+ }));+ const html = readFileSync(src, 'utf8');+ if (!/<\/head>/i.test(html)) throw new Error('这份 HTML 没有 </head>,无法注入编辑器');++ for (const f of ASSET_FILES) copyFileSync(join(ASSETS, f), join(dir, f));+ writeFileSync(tmp, html.includes('layer-editor.js') ? html : html.replace(/<\/head>/i, TAGS + '</head>'));++ return {+ file: tmp,+ cleanup() {+ try { unlinkSync(tmp); } catch { /* 已不存在 */ }+ for (const f of ASSET_FILES) {+ const target = join(dir, f);+ const original = originalAssets.get(f);+ if (original) writeFileSync(target, original);+ else { try { unlinkSync(target); } catch { /* 已不存在 */ } }+ }+ },+ };+}++let puppeteer;+try {+ puppeteer = (await import('puppeteer-core')).default;+} catch {+ console.error('缺少依赖 puppeteer-core。请先执行:');+ console.error(' cd "' + dirname(fileURLToPath(import.meta.url)) + '" && npm install');+ process.exit(2);+}++const CHROME_CANDIDATES = [+ process.env.EDITABLE_DESIGN_BROWSER,+ process.env.PUPPETEER_EXECUTABLE_PATH,+ process.env.POSTER_BROWSER,+ process.env.CHROME_PATH,+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ '/Applications/Chromium.app/Contents/MacOS/Chromium',+ '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',+ '/usr/bin/google-chrome',+ '/usr/bin/chromium-browser',+ '/usr/bin/chromium',+].filter(Boolean);++function findChrome() {+ let hit = CHROME_CANDIDATES.find((p) => existsSync(p));+ if (!hit) {+ for (const name of ['chromium', 'google-chrome', 'chrome']) {+ try {+ const found = execFileSync('which', [name], { encoding: 'utf8' }).trim();+ if (found && existsSync(found)) { hit = found; break; }+ } catch { /* try the next name */ }+ }+ }+ if (!hit) {+ console.error('找不到 Chrome。请设置 EDITABLE_DESIGN_BROWSER 指向浏览器可执行文件。');+ process.exit(2);+ }+ return hit;+}++export async function launch() {+ // 每次用全新的临时 profile:既避开用户已开着的 Chrome 实例+ // (否则会卡在 "Timed out waiting for the WS endpoint URL"),+ // 也保证 localStorage 干净,草稿不会干扰固化结果。+ const profile = mkdtempSync(join(tmpdir(), 'layer-editor-'));+ const args = [+ '--allow-file-access-from-files',+ '--font-render-hinting=none',+ '--disable-gpu',+ `--user-data-dir=${profile}`,+ ];+ if (process.env.EDITABLE_DESIGN_NO_SANDBOX === '1') args.push('--no-sandbox');+ const browser = await puppeteer.launch({+ executablePath: findChrome(),+ headless: true,+ args,+ });+ const origClose = browser.close.bind(browser);+ browser.close = async () => {+ await origClose();+ try { rmSync(profile, { recursive: true, force: true }); } catch { /* 清理失败无妨 */ }+ };+ return browser;+}++/**+ * 加载一个本地 HTML 文件并等到可以安全测量为止。+ * waitEditor=true 时额外等编辑器初始化完成(data-hf-ready)。+ */+export async function open(browser, file, { width = 1600, height = 1200, waitEditor = false } = {}) {+ const page = await browser.newPage();+ await page.setViewport({ width, height, deviceScaleFactor: 1 });+ const errors = [];+ page.on('pageerror', (e) => errors.push(String(e)));+ page.on('console', (m) => { if (m.type() === 'error') errors.push('console: ' + m.text()); });++ await page.goto('file://' + resolve(file), { waitUntil: 'networkidle0' });+ if (waitEditor) await page.waitForSelector('html[data-hf-ready]', { timeout: 20000 });+ // 字体与图片决定文字块尺寸和图层高度,量之前必须落地+ await page.evaluate(() => document.fonts.ready);+ await page.evaluate(() => Promise.all(+ [...document.images].filter((i) => !i.complete).map((i) => new Promise((r) => {+ i.addEventListener('load', r, { once: true });+ i.addEventListener('error', r, { once: true });+ })),+ ));+ await new Promise((r) => setTimeout(r, 350));+ return { page, errors };+}++/** 读出每个 data-layer-id 图层相对画布的位置与尺寸(换算掉画布缩放) */+export function probe(page) {+ return page.evaluate(() => {+ const cv = document.querySelector('[data-canvas-width]') || document.querySelector('.poster-canvas');+ if (!cv) return null;+ const c = cv.getBoundingClientRect();+ const scale = c.width / (+cv.dataset.canvasWidth || cv.offsetWidth);+ const out = {};+ for (const el of cv.querySelectorAll('[data-layer-id]')) {+ const r = el.getBoundingClientRect();+ out[el.dataset.layerId] = {+ left: +((r.left - c.left) / scale).toFixed(1),+ top: +((r.top - c.top) / scale).toFixed(1),+ width: +(r.width / scale).toFixed(1),+ height: +(r.height / scale).toFixed(1),+ };+ }+ return out;+ });+}++/** 逐图层比对两次测量,返回最大偏差与超差清单 */+export function diff(a, b, tol = 1) {+ const ids = [...new Set([...Object.keys(a || {}), ...Object.keys(b || {})])];+ const rows = [];+ let worst = 0;+ for (const id of ids) {+ if (!a?.[id] || !b?.[id]) { rows.push({ id, missing: true }); continue; }+ const d = Math.max(Math.abs(a[id].left - b[id].left), Math.abs(a[id].top - b[id].top));+ worst = Math.max(worst, d);+ rows.push({ id, a: a[id], b: b[id], d: +d.toFixed(2), fail: d > tol });+ }+ return { worst: +worst.toFixed(2), rows, ok: rows.every((r) => !r.fail && !r.missing) };+}++/**+ * 对两个页面中的画布做真实像素比对。+ *+ * 几何一致只能证明图层框没有移动,无法发现上下文选择器失效、背景消失、+ * 伪元素丢失或绘制顺序改变。这里直接截取元素并交给浏览器解码 PNG,避免+ * 再引入 sharp/pngjs 等依赖。perChannelTolerance 用于忽略极轻微的抗锯齿噪声。+ */+export async function pixelDiff(pageA, selectorA, pageB, selectorB, { perChannelTolerance = 2 } = {}) {+ const elA = await pageA.$(selectorA);+ const elB = await pageB.$(selectorB);+ if (!elA || !elB) return { ok: false, reason: '找不到待比较画布' };+ const capture = async (page, el) => {+ const box = await el.boundingBox();+ if (!box) throw new Error('待比较画布不可见');+ // ElementHandle.screenshot() 会先尝试滚动元素到可见区。对于高于+ // 普通视口的竖版海报,某些 Chrome 版本会在这一步长时间等待。+ // 画布已被安置在足够大的视口中,直接按 bounding box 裁剪更稳定。+ return page.screenshot({+ type: 'png', omitBackground: true, captureBeyondViewport: true,+ clip: { x: box.x, y: box.y, width: box.width, height: box.height },+ });+ };+ // Puppeteer 会用同一把截图锁保护 BrowserContext,必须顺序执行。+ const pngA = await capture(pageA, elA);+ const pngB = await capture(pageB, elB);+ if (Buffer.compare(pngA, pngB) === 0) {+ return { ok: true, width: 0, height: 0, changed: 0, changedRatio: 0, meanAbs: 0, exact: true };+ }+ return pageA.evaluate(async ({ a, b, tolerance }) => {+ const load = (base64) => new Promise((resolve, reject) => {+ const img = new Image();+ img.onload = () => resolve(img);+ img.onerror = () => reject(new Error('PNG 解码失败'));+ img.src = `data:image/png;base64,${base64}`;+ });+ const [imgA, imgB] = await Promise.all([load(a), load(b)]);+ if (imgA.naturalWidth !== imgB.naturalWidth || imgA.naturalHeight !== imgB.naturalHeight) {+ return {+ ok: false, reason: '尺寸不一致',+ a: [imgA.naturalWidth, imgA.naturalHeight], b: [imgB.naturalWidth, imgB.naturalHeight],+ };+ }+ const width = imgA.naturalWidth, height = imgA.naturalHeight;+ const cv = document.createElement('canvas');+ cv.width = width; cv.height = height;+ const ctx = cv.getContext('2d', { willReadFrequently: true });+ ctx.clearRect(0, 0, width, height); ctx.drawImage(imgA, 0, 0);+ const aData = ctx.getImageData(0, 0, width, height).data;+ ctx.clearRect(0, 0, width, height); ctx.drawImage(imgB, 0, 0);+ const bData = ctx.getImageData(0, 0, width, height).data;+ let changed = 0, totalAbs = 0, worst = 0;+ for (let i = 0; i < aData.length; i += 4) {+ const dr = Math.abs(aData[i] - bData[i]);+ const dg = Math.abs(aData[i + 1] - bData[i + 1]);+ const db = Math.abs(aData[i + 2] - bData[i + 2]);+ const da = Math.abs(aData[i + 3] - bData[i + 3]);+ const local = Math.max(dr, dg, db, da);+ if (local > tolerance) changed++;+ totalAbs += dr + dg + db + da;+ if (local > worst) worst = local;+ }+ const pixels = width * height;+ return {+ ok: true, width, height, changed,+ changedRatio: changed / pixels,+ meanAbs: totalAbs / (pixels * 4), worst, exact: false,+ };+ }, {+ a: Buffer.from(pngA).toString('base64'),+ b: Buffer.from(pngB).toString('base64'),+ tolerance: perChannelTolerance,+ });+}diff --git a/skills/editable-design/scripts/bake.mjs b/skills/editable-design/scripts/bake.mjsnew file mode 100755index 0000000..3b6161a--- /dev/null+++ b/skills/editable-design/scripts/bake.mjs@@ -0,0 +1,87 @@+#!/usr/bin/env node+/**+ * bake.mjs —— 离线布局固化+ *+ * node bake.mjs <海报 index.html> [--in-place]+ *+ * 把文档流布局改写成纯绝对定位,视觉零变化。产物此后天然可拖,+ * 打开编辑器时不再需要现场固化(也就不再依赖字体每次都加载成功)。+ *+ * 默认输出 <base>.absolute.html;--in-place 直接覆盖原文件。+ * 验收:所有图层坐标偏差必须 ≤1px,否则不落盘并退出 1。+ */+import { writeFileSync, existsSync, unlinkSync } from 'node:fs';+import { dirname, join, resolve, basename, extname } from 'node:path';+import { launch, open, probe, diff, wireTemp } from './_browser.mjs';++const file = process.argv[2];+const inPlace = process.argv.includes('--in-place');+if (!file || !existsSync(resolve(file))) {+ console.error('用法: node bake.mjs <海报 index.html> [--in-place]');+ process.exit(2);+}++const src = resolve(file);+const dir = dirname(src);+const out = inPlace ? src : join(dir, `${basename(src, extname(src))}.absolute.html`);++let wired;+try {+ wired = wireTemp(src, '_hf_bake.html');+} catch (err) {+ console.error('❌ ' + err.message);+ process.exit(1);+}++const browser = await launch();+let code = 0;+try {+ // 1. 原始海报作为基准+ const { page: p0, errors: e0 } = await open(browser, src);+ const before = await probe(p0);+ if (!before || !Object.keys(before).length) {+ console.error('❌ 原始海报里没有 data-layer-id 图层,先跑 check-contract.mjs');+ code = 1;+ } else {+ if (e0.length) console.warn('⚠️ 原始海报有报错:', e0.join('; '));++ // 2. 挂上编辑器跑固化,取导出结果+ const { page: p1, errors: e1 } = await open(browser, wired.file, { waitEditor: true });+ const baked = await p1.evaluate(() => window.__layerEditor.fullHTML());+ if (e1.length) console.warn('⚠️ 固化过程有报错:', e1.join('; '));++ // 3. 先写到临时位置验证,通过了才落到最终路径+ const probeFile = join(dir, '_hf_bake_out.html');+ writeFileSync(probeFile, baked);+ const { page: p2, errors: e2 } = await open(browser, probeFile);+ const after = await probe(p2);+ const d = diff(before, after, 1);+ try { unlinkSync(probeFile); } catch {}++ console.log(`\n固化 · ${basename(src)}\n`);+ console.log(' 图层'.padEnd(24) + '原始 left,top'.padEnd(20) + '固化后 left,top'.padEnd(20) + '偏差');+ for (const r of d.rows) {+ if (r.missing) { console.log(` ${r.id.padEnd(23)}缺失`); continue; }+ console.log(` ${r.id.padEnd(23)}${`${r.a.left}, ${r.a.top}`.padEnd(20)}${`${r.b.left}, ${r.b.top}`.padEnd(20)}${r.d}${r.fail ? ' ❌' : ''}`);+ }+ console.log(`\n 最大偏差 ${d.worst}px 图层 ${d.rows.length} 个 产物 ${(baked.length / 1024).toFixed(1)}KB`);++ const clean = !/hf-|layer-editor/.test(baked);+ if (!clean) console.log(' ⚠️ 产物中检测到编辑器残留');+ if (e2.length) console.log(' ⚠️ 产物加载有报错:', e2.join('; '));++ if (d.ok && clean) {+ writeFileSync(out, baked);+ console.log(`\n✅ 视觉零偏差,已写入 ${out}\n`);+ } else {+ console.log('\n❌ 未通过验收,产物已丢弃。');+ console.log(' 偏差不为 0 通常意味着:契约未满足(先跑 check-contract.mjs),');+ console.log(' 或存在固化规则未覆盖的布局(float / sticky / 伪元素撑高 / writing-mode)。\n');+ code = 1;+ }+ }+} finally {+ wired.cleanup();+ await browser.close();+}+process.exit(code);diff --git a/skills/editable-design/scripts/build-replay.mjs b/skills/editable-design/scripts/build-replay.mjsnew file mode 100644index 0000000..99c82a6--- /dev/null+++ b/skills/editable-design/scripts/build-replay.mjs@@ -0,0 +1,316 @@+#!/usr/bin/env node+import {+ copyFileSync,+ cpSync,+ existsSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ statSync,+ writeFileSync,+} from 'node:fs';+import { dirname, extname, join, relative, resolve, sep } from 'node:path';+import { fileURLToPath } from 'node:url';++const scriptDir = dirname(fileURLToPath(import.meta.url));+const args = process.argv.slice(2);+const projectArg = args.find((arg) => !arg.startsWith('--')) || process.cwd();+const outIndex = args.indexOf('--out');+const projectRoot = resolve(projectArg);+const outDir = resolve(outIndex >= 0 && args[outIndex + 1] ? args[outIndex + 1] : join(projectRoot, 'replay'));+const templateCandidates = [+ join(scriptDir, 'replay-assets'),+ resolve(scriptDir, '../assets/replay'),+];+const templateDir = templateCandidates.find((path) => existsSync(join(path, 'index.html')));++if (!templateDir) {+ console.error('Replay template is unavailable. Re-run poster initialization or use the skill-local builder.');+ process.exit(2);+}+if (!existsSync(join(projectRoot, 'index.html'))) {+ console.error(`No poster index.html found in ${projectRoot}`);+ process.exit(2);+}++const posix = (value) => value.split(sep).join('/');+const read = (path, fallback = '') => existsSync(path) ? readFileSync(path, 'utf8') : fallback;+const readJSON = (path, fallback = {}) => {+ try { return JSON.parse(read(path)); } catch { return fallback; }+};+const firstExisting = (paths) => paths.find((path) => existsSync(path));+const projectPath = (...parts) => join(projectRoot, ...parts);+const browserPath = (path, query = '') => path ? `../${posix(relative(projectRoot, path))}${query}` : '';++function filesIn(path, extensions = []) {+ if (!existsSync(path)) return [];+ return readdirSync(path)+ .filter((name) => !name.startsWith('.') && (!extensions.length || extensions.includes(extname(name).toLowerCase())))+ .map((name) => join(path, name))+ .filter((file) => statSync(file).isFile())+ .sort();+}++function markdownSections(markdown) {+ const sections = [];+ const lines = markdown.split(/\r?\n/);+ let current = null;+ for (const line of lines) {+ const match = line.match(/^##\s+(.+?)\s*$/);+ if (match) {+ if (current) sections.push({ ...current, body: current.lines.join('\n').trim() });+ current = { title: match[1].trim(), lines: [] };+ } else if (current) {+ current.lines.push(line);+ }+ }+ if (current) sections.push({ ...current, body: current.lines.join('\n').trim() });+ return sections;+}++function findSection(sections, key) {+ if (!key) return null;+ const exact = sections.find((section) => section.title.toLowerCase() === String(key).toLowerCase());+ if (exact) return exact;+ const normalized = String(key).toLowerCase().replace(/[^a-z0-9]+/g, '');+ return sections.find((section) => section.title.toLowerCase().replace(/[^a-z0-9]+/g, '') === normalized)+ || sections.find((section) => section.title.toLowerCase().includes(String(key).toLowerCase()));+}++function traceEvents() {+ return read(projectPath('.trace', 'events.jsonl'))+ .split(/\r?\n/)+ .filter(Boolean)+ .flatMap((line) => { try { return [JSON.parse(line)]; } catch { return []; } });+}++const manifest = readJSON(projectPath('.trace', 'manifest.json'));+const poster = readJSON(projectPath('poster.json'));+const assetPlanPath = firstExisting([+ projectPath('asset-plan.json'),+ projectPath('.trace', 'artifacts', 'P11_asset_plan', 'asset-plan.json'),+]);+const assetPlanRaw = assetPlanPath ? read(assetPlanPath) : '';+const assetPlan = assetPlanPath ? readJSON(assetPlanPath) : {};+const promptPath = firstExisting([+ projectPath('prompts.md'),+ projectPath('.trace', 'artifacts', 'P12_generate_imagery', 'prompts.md'),+]);+const promptsRaw = promptPath ? read(promptPath) : '';+const promptSections = markdownSections(promptsRaw);+const briefPath = firstExisting([+ projectPath('brief.md'),+ projectPath('.trace', 'artifacts', 'P01_input', 'brief.md'),+]);+const briefRaw = briefPath ? read(briefPath).trim() : '';+const compositionPromptPath = firstExisting([+ projectPath('reference', 'composition-prompt.md'),+ projectPath('reference', 'reference-prompt.md'),+ projectPath('.trace', 'artifacts', 'P02_reference', 'composition-prompt.md'),+]);+const compositionSection = promptSections.find((section) => /composition reference|art-directed composition/i.test(section.title));+const compositionPrompt = compositionPromptPath ? read(compositionPromptPath).trim() : (compositionSection?.body || '');+const referenceImage = firstExisting([+ projectPath('reference', 'composition-reference.png'),+ projectPath('reference', 'art-direction.png'),+ ...filesIn(projectPath('reference'), ['.png', '.jpg', '.jpeg', '.webp']),+]);+const notesPath = firstExisting([+ projectPath('design-plan.md'),+ projectPath('reference', 'composition-notes.md'),+ projectPath('zones-plan.md'),+ projectPath('.trace', 'artifacts', 'P11_asset_plan', 'design-plan.md'),+ projectPath('.trace', 'artifacts', 'P11_asset_plan', 'zones-plan.md'),+]);+const notesRaw = notesPath ? read(notesPath).trim() : '';+const reviewPath = firstExisting([+ projectPath('render-review.md'),+ projectPath('.trace', 'artifacts', 'P16_read_render', 'render-review.md'),+]);+const reviewRaw = reviewPath ? read(reviewPath).trim() : '';+const indexRaw = read(projectPath('index.html'));+const renderPath = firstExisting([+ projectPath('out', 'poster.png'),+ ...filesIn(projectPath('out'), ['.png', '.jpg', '.jpeg', '.webp']),+]);+const layersPath = firstExisting([+ projectPath('layers.html'),+ projectPath('editor.html'),+]);+const events = traceEvents();+const assetFiles = filesIn(projectPath('assets'), ['.png', '.jpg', '.jpeg', '.webp']);++function eventTime(match) {+ return events.find(match)?.ts || '';+}++const startedAt = events.find((event) => event.type === 'run_start')?.ts || manifest.created_at || '';+function timeLabel(match) {+ const stamp = eventTime(match);+ if (!startedAt || !stamp) return '';+ const seconds = Math.max(0, Math.round((new Date(stamp) - new Date(startedAt)) / 1000));+ const minutes = Math.floor(seconds / 60);+ return `T+${String(minutes).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`;+}++function findAssetFile(id, index) {+ if (id) {+ const exact = assetFiles.find((path) => {+ const stem = path.slice(0, -extname(path).length).split(sep).pop();+ return stem.toLowerCase() === String(id).toLowerCase();+ });+ if (exact) return exact;+ const loose = assetFiles.find((path) => path.toLowerCase().includes(String(id).toLowerCase()));+ if (loose) return loose;+ }+ return assetFiles[index] || null;+}++let assetItems = [];+if (Array.isArray(assetPlan.assets) && assetPlan.assets.length) {+ assetItems = assetPlan.assets.map((asset, index) => {+ const promptKey = asset.prompt || asset.prompt_id || asset.id;+ const section = findSection(promptSections, promptKey) || findSection(promptSections, asset.id);+ const file = findAssetFile(asset.id, index);+ return {+ id: asset.id || `asset-${index + 1}`,+ title: asset.label || asset.id || section?.title || `Asset ${index + 1}`,+ promptId: promptKey || '',+ prompt: section?.body || '',+ src: browserPath(file),+ source: file ? posix(relative(projectRoot, file)) : '',+ contain: /cutout|relief|map|diagram|logo/i.test(`${asset.form || ''} ${asset.id || ''}`),+ };+ });+} else {+ const shippingSections = promptSections.filter((section) => !/composition reference|art-directed composition/i.test(section.title));+ assetItems = assetFiles.map((file, index) => ({+ id: file.slice(0, -extname(file).length).split(sep).pop(),+ title: shippingSections[index]?.title || file.split(sep).pop(),+ promptId: shippingSections[index]?.title || '',+ prompt: shippingSections[index]?.body || '',+ src: browserPath(file),+ source: posix(relative(projectRoot, file)),+ contain: /cutout|relief|map|diagram|logo/i.test(file),+ }));+}++const layerIds = [...indexRaw.matchAll(/data-layer-id\s*=\s*["']([^"']+)["']/g)].map((match) => match[1]);+const groupIds = [...indexRaw.matchAll(/data-explode-group\s*=\s*["']([^"']+)["']/g)].map((match) => match[1]);+const uniqueLayers = new Set(layerIds);+const uniqueGroups = new Set(groupIds);+const layersRaw = layersPath && layersPath.endsWith('layers.html') ? read(layersPath) : '';+const componentCount = layersRaw ? (layersRaw.match(/class=["'][^"']*hf-exploded-item\b/g) || []).length : 0;+const mainMatch = indexRaw.match(/<main\b[\s\S]*?<\/main>/i);+const codeExcerpt = (mainMatch?.[0] || indexRaw).slice(0, 5200).trim();+const reviewBullets = [...reviewRaw.matchAll(/^\s*-\s+(.+)$/gm)].map((match) => match[1].trim());+const explicitPasses = (reviewRaw.match(/^##\s+Pass\b/gmi) || []).length;+const renderPasses = events.filter((event) => event.type === 'exec_done' && /^P15_render/.test(event.step || '')).length;+const passCount = explicitPasses || Math.max(1, renderPasses);+const canvas = poster.canvas?.width && poster.canvas?.height ? `${poster.canvas.width} × ${poster.canvas.height}` : 'fixed canvas';+const documentTitle = (indexRaw.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1] || '').replace(/<[^>]+>/g, '').trim();+const title = manifest.label || documentTitle || projectRoot.split(sep).pop();++const stages = [+ {+ id: 'input', order: '01', kind: 'input', phase: 'think', title: '需求输入',+ statusLabel: briefRaw ? '原始记录' : '记录缺失',+ raw: briefRaw,+ fallbackLabel: briefRaw ? '' : manifest.label || '',+ attachments: filesIn(projectPath('input')).map((path) => posix(relative(projectRoot, path))),+ timeLabel: timeLabel((event) => event.type === 'run_start'),+ artifactLabel: briefRaw ? '1 个原始 Prompt' : '仅 trace label',+ sources: briefPath ? [posix(relative(projectRoot, briefPath))] : ['missing: brief.md'],+ },+ {+ id: 'reference', order: '02', kind: 'reference', phase: 'think', title: '视觉参考',+ statusLabel: compositionPrompt && referenceImage ? '已确定' : '证据不完整',+ prompt: compositionPrompt,+ promptSource: compositionPromptPath ? posix(relative(projectRoot, compositionPromptPath)) : (compositionSection ? 'prompts.md / composition reference' : ''),+ preview: browserPath(referenceImage),+ timeLabel: timeLabel((event) => /P11_reference|P02_reference/.test(event.step || '')),+ artifactLabel: referenceImage ? '1 个参考结果' : '无参考图',+ sources: [compositionPromptPath, referenceImage].filter(Boolean).map((path) => posix(relative(projectRoot, path))).concat(compositionSection && !compositionPromptPath ? ['prompts.md / composition reference'] : []),+ },+ {+ id: 'plan', order: '03', kind: 'plan', phase: 'think', title: '设计规划',+ statusLabel: notesRaw || assetPlanRaw ? '已决策' : '记录缺失',+ raw: notesRaw || assetPlanRaw,+ assetPlanRaw,+ architecture: assetPlan.architecture || assetPlan.type || '',+ planTitle: assetPlan.architecture || (notesPath ? notesPath.split(sep).pop() : '版式与信息层级'),+ slots: Array.isArray(assetPlan.assets) ? assetPlan.assets : [],+ timeLabel: timeLabel((event) => /P09_canvas|P11_asset_plan/.test(event.step || '')),+ artifactLabel: `${Array.isArray(assetPlan.assets) ? assetPlan.assets.length : 0} 个视觉槽位`,+ sources: [notesPath, assetPlanPath].filter(Boolean).map((path) => posix(relative(projectRoot, path))),+ },+ {+ id: 'assets', order: '04', kind: 'assets', phase: 'make', title: '素材生成',+ statusLabel: assetItems.length ? '已生成' : '无生成素材',+ items: assetItems,+ raw: promptsRaw,+ timeLabel: timeLabel((event) => /P12_generate_imagery|P21_bottom_scene/.test(event.step || '')),+ artifactLabel: `${assetItems.length} 个素材`,+ sources: [promptPath, ...assetFiles].filter(Boolean).map((path) => posix(relative(projectRoot, path))),+ },+ {+ id: 'html', order: '05', kind: 'html', phase: 'make', title: 'HTML 构建',+ statusLabel: renderPath ? '已渲染' : '已编码',+ code: codeExcerpt,+ fullCode: indexRaw.slice(0, 80000),+ render: browserPath(renderPath),+ canvas,+ layerCount: uniqueLayers.size,+ groupCount: uniqueGroups.size,+ timeLabel: timeLabel((event) => /P14_cleanup|P15_render/.test(event.step || '')),+ artifactLabel: renderPath ? 'HTML + PNG' : 'HTML',+ sources: ['index.html'].concat(renderPath ? [posix(relative(projectRoot, renderPath))] : []),+ },+ {+ id: 'review', order: '06', kind: 'review', phase: 'prove', title: 'Review 反馈',+ statusLabel: reviewRaw ? '已修正' : '记录缺失',+ raw: reviewRaw,+ bullets: reviewBullets,+ passCount,+ timeLabel: timeLabel((event) => /P16_read_render|P16_optimization|P25_read_render/.test(event.step || '')),+ artifactLabel: `${passCount} 轮 Review`,+ sources: reviewPath ? [posix(relative(projectRoot, reviewPath)), '.trace/events.jsonl'] : ['missing: render-review.md', '.trace/events.jsonl'],+ },+ {+ id: 'layers', order: '07', kind: 'layers', phase: 'prove', title: '分层展示',+ statusLabel: layersPath ? '已验证' : '未生成',+ layerCount: uniqueLayers.size,+ groupCount: uniqueGroups.size,+ componentCount,+ preview: browserPath(layersPath),+ previewSource: layersPath ? posix(relative(projectRoot, layersPath)) : '',+ timeLabel: timeLabel((event) => /P17_editor|P20_editor|P26_editor/.test(event.step || '')),+ artifactLabel: `${uniqueLayers.size} 图层 · ${uniqueGroups.size} 组`,+ sources: layersPath ? [posix(relative(projectRoot, layersPath)), 'index.html / data-layer-id'] : ['missing: editor.html or layers.html'],+ },+];++const replay = {+ schema: 'poster-replay/v1',+ generatedAt: new Date().toISOString(),+ project: {+ title,+ slug: projectRoot.split(sep).pop(),+ status: manifest.status || 'ok',+ canvas,+ },+ stages,+};++mkdirSync(outDir, { recursive: true });+for (const file of ['index.html', 'replay.css', 'replay.js', 'replay-motion.js']) {+ copyFileSync(join(templateDir, file), join(outDir, file));+}+cpSync(join(templateDir, 'icons'), join(outDir, 'icons'), { recursive: true });+writeFileSync(join(outDir, 'data.js'), `window.__POSTER_REPLAY__ = ${JSON.stringify(replay, null, 2)};\n`);++const missing = stages.filter((stage) => /缺失|不完整|未生成/.test(stage.statusLabel));+console.log(`replay ${join(outDir, 'index.html')}`);+console.log(`stages ${stages.length}`);+console.log(`assets ${assetItems.length}`);+if (missing.length) console.log(`evidence missing or partial: ${missing.map((stage) => stage.id).join(', ')}`);diff --git a/skills/editable-design/scripts/check-contract.mjs b/skills/editable-design/scripts/check-contract.mjsnew file mode 100755index 0000000..c1fa70b--- /dev/null+++ b/skills/editable-design/scripts/check-contract.mjs@@ -0,0 +1,293 @@+#!/usr/bin/env node+/**+ * check-contract.mjs —— 检查一张海报是否满足可编辑性契约+ *+ * node check-contract.mjs <海报 index.html> [--json]+ *+ * 退出码 0 = 通过,1 = 有违规,2 = 用法/环境错误。+ * 违规项交给 agent 修(改成什么值取决于设计意图),修完重跑。+ */+import { existsSync } from 'node:fs';+import { resolve } from 'node:path';+import { launch, open, probe, diff } from './_browser.mjs';++const file = process.argv[2];+const asJson = process.argv.includes('--json');+if (!file || !existsSync(resolve(file))) {+ console.error('用法: node check-contract.mjs <海报 index.html> [--json]');+ process.exit(2);+}++const report = { file: resolve(file), pass: true, checks: [], hints: {} };+const add = (id, ok, msg, fix) => {+ report.checks.push({ id, ok, msg, fix });+ if (!ok) report.pass = false;+};++const browser = await launch();+try {+ const { page, errors } = await open(browser, file, { width: 1400, height: 1000 });++ const info = await page.evaluate(() => {+ const cv = document.querySelector('[data-canvas-width]') || document.querySelector('.poster-canvas');+ if (!cv) return { canvas: false };+ const cs = getComputedStyle(cv);+ const layers = [...cv.querySelectorAll('[data-layer-id]')];+ const ids = layers.map((l) => l.dataset.layerId);+ const groupNodes = [...cv.querySelectorAll('[data-explode-group]')];+ const groupIds = groupNodes.map((n) => (n.dataset.explodeGroup || '').trim());+ const groupSet = new Set(groupIds.filter(Boolean));+ const allowedRoles = new Set(['surface', 'image', 'copy', 'icon', 'decoration']);+ const groups = groupNodes.map((node) => {+ const id = (node.dataset.explodeGroup || '').trim();+ const members = layers.filter((layer) =>+ layer.closest('[data-explode-group]') === node+ || (layer.dataset.explodeParent || '').trim() === id);+ return {+ id,+ label: (node.dataset.explodeLabel || '').trim(),+ members: [...new Set(members)].map((layer) => layer.dataset.layerId),+ };+ });++ // 编辑器会把每个文字叶子自动标成 hf-slot,并用命中位置进入编辑。+ // 像素没有重叠不代表交互框没有重叠;若 slot 中心被另一个图层截获,+ // 双击看似点中文字,实际却永远进不了编辑态。+ const blockedTextTargets = [];+ const textSlots = (root) => {+ const out = [];+ (function walk(node) {+ if (node instanceof SVGElement) return;+ const ownText = [...node.childNodes]+ .some((child) => child.nodeType === 3 && child.textContent.trim());+ if (!node.children.length || ownText) {+ if (node.textContent.trim()) out.push(node);+ return;+ }+ for (const child of node.children) walk(child);+ })(root);+ return out;+ };+ for (const layer of layers) {+ for (const slot of textSlots(layer)) {+ slot.scrollIntoView({ block: 'center', inline: 'center' });+ const rect = slot.getBoundingClientRect();+ if (rect.width < 1 || rect.height < 1) continue;+ const top = document.elementFromPoint(+ rect.left + rect.width / 2,+ rect.top + rect.height / 2,+ );+ const owner = top?.closest('[data-layer-id]');+ if (owner !== layer) {+ blockedTextTargets.push({+ layer: layer.dataset.layerId,+ text: slot.textContent.trim().replace(/\s+/g, ' ').slice(0, 24),+ blocker: owner?.dataset.layerId || top?.tagName?.toLowerCase() || '(none)',+ });+ }+ }+ }+ window.scrollTo(0, 0);++ // 候选漏标块:有文字、不属于任何图层、且内部也不含图层。+ // 最后一条很关键 —— 图层的祖先容器(如 .content / .footer)本身+ // 没有 data-layer-id,但它不是漏标,只是包装。+ const unlabeled = [];+ for (const el of cv.querySelectorAll('*')) {+ if (el.closest('[data-layer-id]') || el instanceof SVGElement) continue;+ if (el.querySelector('[data-layer-id]')) continue;+ if (!el.textContent.trim()) continue;+ if (unlabeled.some((o) => o.node.contains(el))) continue;+ unlabeled.push({ node: el });+ }++ // 静态定位 vw/vh 的出现处,便于修复时直接跳到那一行+ const viewportUnits = [];+ for (const sheet of document.styleSheets) {+ let rules;+ try { rules = sheet.cssRules; } catch { continue; }+ for (const r of rules) {+ if (!r.cssText) continue;+ for (const m of r.cssText.matchAll(/[^;{}]*\b\d*\.?\d+v(?:w|h|min|max)\b[^;{}]*/g)) {+ const frag = m[0].trim();+ const sel = r.selectorText || r.conditionText || '@rule';+ if (viewportUnits.length < 25) viewportUnits.push(`${sel} { ${frag} }`);+ }+ }+ }++ return {+ canvas: true,+ declaredW: +cv.dataset.canvasWidth || null,+ declaredH: +cv.dataset.canvasHeight || null,+ actualW: Math.round(cv.getBoundingClientRect().width),+ actualH: Math.round(cv.getBoundingClientRect().height),+ position: cs.position,+ layerCount: layers.length,+ duplicateIds: ids.filter((v, i) => ids.indexOf(v) !== i),+ emptyIds: ids.filter((v) => !v || !v.trim()).length,+ nestedLayers: layers.filter((layer) => layer.querySelector('[data-layer-id]'))+ .map((layer) => layer.dataset.layerId),+ groups,+ duplicateGroups: groupIds.filter((v, i) => groupIds.indexOf(v) !== i),+ emptyGroups: groupIds.filter((v) => !v).length,+ groupsAlsoLayers: groupNodes.filter((node) => node.hasAttribute('data-layer-id'))+ .map((node) => node.dataset.explodeGroup || '(empty)'),+ nestedGroups: groupNodes.filter((node) => node.parentElement?.closest('[data-explode-group]'))+ .map((node) => node.dataset.explodeGroup || '(empty)'),+ orphanParents: layers.filter((layer) => {+ const parent = (layer.dataset.explodeParent || '').trim();+ return parent && !groupSet.has(parent);+ }).map((layer) => `${layer.dataset.layerId}→${layer.dataset.explodeParent}`),+ invalidRoles: layers.filter((layer) => {+ const role = (layer.dataset.explodeRole || '').trim();+ return role && !allowedRoles.has(role);+ }).map((layer) => `${layer.dataset.layerId}:${layer.dataset.explodeRole}`),+ blockedTextTargets,+ unlabeled: unlabeled.map((o) => ({+ tag: o.node.tagName.toLowerCase(),+ cls: (typeof o.node.className === 'string' ? o.node.className : '') || '-',+ text: o.node.textContent.trim().replace(/\s+/g, ' ').slice(0, 34),+ })),+ viewportUnits,+ fontStatus: document.fonts.status,+ /* 声明了但没被用到的 @font-face 会一直是 unloaded,这是浏览器按需加载的+ 正常行为,仅作提示。注意 Google Fonts 把中文字体切成上百个+ unicode-range 分片,同一 family 下必然部分 loaded 部分 unloaded,+ 所以只有「没有任何分片被加载」才算这个 family 真的没用上。 */+ idleFonts: (() => {+ const tally = new Map();+ for (const f of document.fonts) {+ const cur = tally.get(f.family) || { loaded: 0 };+ if (f.status === 'loaded') cur.loaded++;+ tally.set(f.family, cur);+ }+ return [...tally].filter(([, v]) => v.loaded === 0).map(([k]) => k).slice(0, 10);+ })(),+ };+ });++ if (!info.canvas) {+ add('C1-canvas', false, '找不到画布根节点',+ '给海报根节点加 data-canvas-width / data-canvas-height(或使用 class="poster-canvas")');+ } else {+ add('C1-canvas', true, `画布 ${info.actualW}×${info.actualH}`);++ const declared = info.declaredW && info.declaredH;+ add('C1-declared', !!declared,+ declared ? `已声明 data-canvas-width/height = ${info.declaredW}×${info.declaredH}` : '缺少 data-canvas-width / data-canvas-height',+ '在画布根节点上声明 data-canvas-width="<宽>" data-canvas-height="<高>"');++ if (declared) {+ const match = Math.abs(info.declaredW - info.actualW) <= 1 && Math.abs(info.declaredH - info.actualH) <= 1;+ add('C1-match', match,+ match ? '声明尺寸与实际渲染尺寸一致' : `声明 ${info.declaredW}×${info.declaredH} 与实际 ${info.actualW}×${info.actualH} 不一致`,+ '把画布宽高改成 px 写死,并与 data-canvas-* 的声明保持一致');+ }++ add('C1-position', ['relative', 'absolute', 'fixed'].includes(info.position),+ `画布 position: ${info.position}`,+ '画布需要 position:relative,否则图层没有确定的包含块');++ add('C3-layers', info.layerCount > 0,+ `找到 ${info.layerCount} 个 data-layer-id 图层`,+ '给每个语义模块加 data-layer-id(判据:使用者是否会想单独移动它)');++ add('C3-unique', info.duplicateIds.length === 0 && info.emptyIds === 0,+ info.duplicateIds.length ? `data-layer-id 重复: ${[...new Set(info.duplicateIds)].join(', ')}` : 'data-layer-id 无重复无空值',+ 'data-layer-id 必须唯一且非空');++ add('C3-flat', info.nestedLayers.length === 0,+ info.nestedLayers.length ? `data-layer-id 不可嵌套: ${info.nestedLayers.join(', ')}` : 'data-layer-id 叶子图层无嵌套',+ '把共同容器改为不带 data-layer-id 的 data-explode-group,实际可编辑单元保留为叶子图层');++ const groupIdsOk = info.duplicateGroups.length === 0 && info.emptyGroups === 0;+ add('C4-group-ids', groupIdsOk,+ !info.groups.length ? '未声明一级内容分组(使用扁平组件模式)'+ : groupIdsOk ? `找到 ${info.groups.length} 个唯一分组` : `分组 id 重复或为空: ${[...new Set(info.duplicateGroups)].join(', ') || '(empty)'}`,+ 'data-explode-group 必须唯一且非空');++ const groupShapeOk = info.groupsAlsoLayers.length === 0 && info.nestedGroups.length === 0;+ add('C4-group-shape', groupShapeOk,+ groupShapeOk ? '分组容器不参与拖拽且不互相嵌套'+ : `无效分组容器: ${[...info.groupsAlsoLayers, ...info.nestedGroups].join(', ')}`,+ '分组容器只加 data-explode-group,不加 data-layer-id,也不要嵌套另一个分组容器');++ const usefulGroups = info.groups.filter((group) => group.members.length >= 2).length;+ const membersOk = info.groups.every((group) => group.members.length >= 2)+ && info.orphanParents.length === 0 && info.invalidRoles.length === 0;+ add('C4-group-members', membersOk,+ !info.groups.length ? '无需分组成员检查'+ : membersOk ? `${usefulGroups} 个分组均含至少 2 个叶子图层`+ : `分组成员/角色无效${info.orphanParents.length ? `;孤立归属 ${info.orphanParents.join(', ')}` : ''}${info.invalidRoles.length ? `;未知角色 ${info.invalidRoles.join(', ')}` : ''}`,+ '每个分组至少包含 2 个叶子 data-layer-id;角色仅用 surface/image/copy/icon/decoration');++ add('C5-text-hit', info.blockedTextTargets.length === 0,+ info.blockedTextTargets.length+ ? `文字编辑命中区被遮挡: ${info.blockedTextTargets.slice(0, 8)+ .map((item) => `${item.layer}→${item.blocker} (${item.text})`).join(', ')}`+ : '所有文字编辑命中区均可到达',+ '调整重叠图层的位置、pointer-events 或 DOM/z-index 顺序,使文字槽中心能命中所属 data-layer-id');+ }++ /* C2 的实质检测:调整同一真实浏览器页面的视口,图层坐标不应变化。+ 这比正则查 vh 精确得多 —— 百分比、vmin、calc() 混用都能抓到。 */+ const m1 = await probe(page);+ await page.setViewport({ width: 1000, height: 1500, deviceScaleFactor: 1 });+ await page.evaluate(() => new Promise((resolveFrame) => {+ requestAnimationFrame(() => requestAnimationFrame(resolveFrame));+ }));+ const m2 = await probe(page);+ const d = diff(m1, m2, 0.5);+ add('C2-viewport', d.ok,+ d.ok ? '调整视口后坐标不变(布局不依赖视口)'+ : `调整视口后坐标发生变化,最大 ${d.worst}px:${d.rows.filter((r) => r.fail).map((r) => r.id).join(', ')}`,+ '布局尺寸不能用 vw / vh / 百分比承担,改为 px 固定值(渐变、纹理等装饰不限)');++ add('fonts', info.fontStatus === 'loaded',+ info.fontStatus === 'loaded' ? '字体加载已完成(document.fonts.status = loaded)' : `字体仍在加载: ${info.fontStatus}`,+ '字体未落地会导致测量到 fallback 字体的坐标;检查网络或字体引用');++ add('runtime', errors.length === 0,+ errors.length ? `页面有 ${errors.length} 处报错` : '页面无控制台报错');++ report.hints = {+ unlabeled: info.unlabeled || [],+ viewportUnits: info.viewportUnits || [],+ idleFonts: info.idleFonts || [],+ pageErrors: errors,+ };+} finally {+ await browser.close();+}++if (asJson) {+ console.log(JSON.stringify(report, null, 2));+ process.exit(report.pass ? 0 : 1);+}++console.log(`\n契约检查 · ${report.file}\n`);+for (const c of report.checks) {+ console.log(` ${c.ok ? '✅' : '❌'} [${c.id}] ${c.msg}`);+ if (!c.ok && c.fix) console.log(` 修法: ${c.fix}`);+}++const { unlabeled, viewportUnits, idleFonts, pageErrors } = report.hints;+if (idleFonts.length) {+ console.log(`\n声明但未被使用的字体(按需加载,正常现象): ${idleFonts.join(', ')}`);+}+if (viewportUnits.length) {+ console.log(`\n视口单位出现处(供定位,装饰性用途可忽略):`);+ for (const v of viewportUnits) console.log(' ' + v);+}+if (unlabeled.length) {+ console.log(`\n可能漏标 data-layer-id 的候选块(${unlabeled.length} 个,需人工判断):`);+ for (const u of unlabeled) console.log(` <${u.tag} class="${u.cls}"> ${u.text}`);+}+if (pageErrors.length) {+ console.log(`\n页面报错:`);+ for (const e of pageErrors) console.log(' ' + e);+}++console.log(report.pass ? '\n契约通过 ✅ 可以执行 bake.mjs\n' : '\n契约未通过 ❌ 修复后重跑\n');+process.exit(report.pass ? 0 : 1);diff --git a/skills/editable-design/scripts/check-fonts.sh b/skills/editable-design/scripts/check-fonts.shnew file mode 100755index 0000000..b4a4fe3--- /dev/null+++ b/skills/editable-design/scripts/check-fonts.sh@@ -0,0 +1,204 @@+#!/usr/bin/env bash+# Verify that every font family the poster asks for actually resolves.+#+# A missing family raises no error anywhere: the browser silently falls back to+# a default face, the render succeeds, the pixel dimensions check out, and the+# poster ships with the wrong typography. Nothing else in this plugin can catch+# that, which is why it gets its own command.+#+# Detection compares a full metric signature against a sentinel family that+# cannot exist. Width alone is not enough — many CJK faces share an advance+# width — so the signature also covers the actual bounding box at two sizes,+# measured for a Latin sample and a CJK sample separately.+set -euo pipefail++here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+html=""+requested=""+while [[ $# -gt 0 ]]; do+ case "$1" in+ --family)+ [[ $# -ge 2 ]] || { echo "--family requires a font family name" >&2; exit 2; }+ requested="${requested}${2}"$'\n'+ shift 2+ ;;+ --help|-h)+ echo "usage: check-fonts.sh HTML"+ echo " check-fonts.sh --family FAMILY [--family FAMILY...]"+ exit 0+ ;;+ --*) echo "unknown argument: $1" >&2; exit 2 ;;+ *)+ [[ -z "$html" ]] || { echo "only one HTML file may be checked" >&2; exit 2; }+ html="$1"+ shift+ ;;+ esac+done++if [[ -z "$requested" ]]; then+ [[ -n "$html" ]] || { echo "usage: check-fonts.sh HTML or --family FAMILY" >&2; exit 2; }+ test -f "$html" || { echo "no such file: $html" >&2; exit 2; }+fi++# Collect every named family out of font-family declarations and --font-* custom+# properties, dropping generic keywords and var() references.+if [[ -n "$requested" ]]; then+ families="$(printf '%s' "$requested" | sed '/^[[:space:]]*$/d' | sort -u)"+else+ families=$(+ grep -o -E '(font-family|--font-[a-zA-Z-]+)[[:space:]]*:[^;}]*' "$html" \+ | sed 's/^[^:]*:[[:space:]]*//' \+ | tr ',' '\n' \+ | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' \+ -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'\$//" \+ | grep -v -E '^(serif|sans-serif|monospace|cursive|fantasy|system-ui|math|emoji|fangsong|ui-[a-z-]+|inherit|initial|unset|revert)$' \+ | grep -v -E '^(var\(|$)' \+ | sort -u+ )+fi++[[ -n "$families" ]] || { echo "no named font families found in $html"; exit 0; }++browser="$("$here/render-poster.sh" --probe | awk '{ $1 = ""; sub(/^ +/, ""); print }')"+[[ -n "$browser" && -x "$browser" ]] || {+ echo "no Chromium-based browser found, font check unavailable. Set EDITABLE_DESIGN_BROWSER=<executable>" >&2+ exit 1+}++families_json=$(+ printf '%s\n' "$families" \+ | sed 's/\\/\\\\/g; s/"/\\"/g' \+ | awk '{ printf "%s\"%s\"", (NR > 1 ? "," : ""), $0 }'+)++probe="$(mktemp -d "${TMPDIR:-/tmp}/poster-font-probe.XXXXXX")"+profile="$(mktemp -d "${TMPDIR:-/tmp}/poster-font-profile.XXXXXX")"+probe_pid=""++profile_pids() {+ ps -axo pid=,command= \+ | awk -v marker="--user-data-dir=$profile" \+ 'index($0, marker) && index($0, "awk -v marker=") == 0 { print $1 }'+}++stop_browser() {+ local pids=""+ local _+ pids="$(profile_pids)"+ [[ -n "$pids" ]] && kill $pids 2>/dev/null || true+ for _ in $(seq 1 10); do+ pids="$(profile_pids)"+ [[ -z "$pids" ]] && break+ sleep 0.1+ done+ pids="$(profile_pids)"+ [[ -n "$pids" ]] && kill -KILL $pids 2>/dev/null || true+ [[ -n "$probe_pid" ]] && wait "$probe_pid" 2>/dev/null || true+}++cleanup() {+ stop_browser+ [[ "$probe" == *"/poster-font-probe."* ]] && rm -rf -- "$probe"+ [[ "$profile" == *"/poster-font-profile."* ]] && rm -rf -- "$profile"+}+trap cleanup EXIT INT TERM++cat >"$probe/probe.html" <<PROBE+<!doctype html><html><head><meta charset="utf-8"></head><body><script>+const FAMILIES = [${families_json}];+// Three generic bases rather than one nonexistent sentinel. A single sentinel+// cannot see a family that happens to BE the platform default for that script+// — PingFang SC is macOS's default CJK sans, so stacking it over a sentinel+// produces byte-identical metrics and reads as missing. Comparing against+// serif, sans-serif and monospace fixes that: a real family overrides at least+// one of them.+const BASES = ['serif', 'sans-serif', 'monospace'];+const SAMPLES = { latin: 'AWmgQ019jil', cjk: '晨雾高山茶永' };++function signature(text, stack) {+ const ctx = document.createElement('canvas').getContext('2d');+ const parts = [];+ for (const size of [48, 73]) {+ ctx.font = size + 'px ' + stack;+ const m = ctx.measureText(text);+ parts.push(+ m.width.toFixed(3),+ (m.actualBoundingBoxAscent || 0).toFixed(3),+ (m.actualBoundingBoxDescent || 0).toFixed(3),+ (m.actualBoundingBoxLeft || 0).toFixed(3),+ (m.actualBoundingBoxRight || 0).toFixed(3)+ );+ }+ return parts.join('|');+}++const lines = FAMILIES.map((family) => {+ const quoted = JSON.stringify(family);+ const covers = {};+ for (const [name, text] of Object.entries(SAMPLES)) {+ covers[name] = BASES.some(+ (base) => signature(text, quoted + ', ' + base) !== signature(text, base)+ );+ }+ const verdict = covers.latin || covers.cjk+ ? (covers.cjk ? 'ok\tcjk + latin' : 'ok\tlatin only')+ : 'MISSING\t-';+ return 'FONTPROBE\t' + family + '\t' + verdict;+});++// Leading newline matters: --dump-dom emits "<body>" immediately before the+// first line, so without it the first family never matches a line-anchored grep.+document.body.textContent = '\n' + lines.join('\n') + '\n';+</script></body></html>+PROBE++"$browser" \+ --headless --disable-gpu --no-first-run --no-default-browser-check \+ --disable-extensions --disable-background-networking --disable-sync \+ --disable-default-apps --mute-audio \+ --user-data-dir="$profile" \+ --dump-dom "file://$probe/probe.html" \+ >"$probe/dom.html" 2>/dev/null &+probe_pid=$!++# --dump-dom writes to stdout and Chrome buffers it until exit, so polling the+# file for content never succeeds early. Wait for the process itself instead.+for _ in $(seq 1 20); do+ kill -0 "$probe_pid" 2>/dev/null || break+ sleep 0.25+done+if kill -0 "$probe_pid" 2>/dev/null; then+ stop_browser+else+ wait "$probe_pid" 2>/dev/null || true+fi+probe_pid=""++grep -q 'FONTPROBE' "$probe/dom.html" 2>/dev/null || {+ echo "the font probe returned nothing - the browser probably failed to start" >&2+ exit 3+}++missing=0+while IFS=$'\t' read -r _ family verdict coverage; do+ [[ -n "$family" ]] || continue+ if [[ "$verdict" == "MISSING" ]]; then+ printf 'FAIL %-28s not installed - the browser will silently fall back\n' "$family"+ missing=$(( missing + 1 ))+ else+ printf 'ok %-28s %s\n' "$family" "$coverage"+ fi+done < <(grep '^FONTPROBE' "$probe/dom.html" | sed 's/&/\&/g; s/</</g; s/>/>/g; s/"/"/g')++if [[ "$missing" -gt 0 ]]; then+ echo+ echo "Replace these $missing families, or use ones confirmed present. A missing font" >&2+ echo "raises no error: the render succeeds, the dimensions check out, and only the" >&2+ echo "type on the finished poster looks subtly wrong." >&2+ exit 1+fi++echo+echo "Families marked \"latin only\" must not set CJK text: every character would come"+echo "from a fallback face."diff --git a/skills/editable-design/scripts/check-poster.sh b/skills/editable-design/scripts/check-poster.shnew file mode 100755index 0000000..2c11643--- /dev/null+++ b/skills/editable-design/scripts/check-poster.sh@@ -0,0 +1,70 @@+#!/usr/bin/env bash+# Fast, self-contained checks for the poster contract. Visual quality still+# requires reading the rendered PNG; this catches deterministic packaging and+# markup failures before Chrome starts.+set -euo pipefail++html="${1:?usage: check-poster.sh HTML}"+test -f "$html" || { echo "no such file: $html" >&2; exit 2; }++project="$(cd "$(dirname "$html")" && pwd)"+html="$project/$(basename "$html")"+config="$project/poster.json"+failures=0++fail() {+ echo "FAIL $*" >&2+ failures=$(( failures + 1 ))+}++read_num() {+ sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p" "$2" | head -1+}++test -f "$config" || fail "missing poster.json"++if [[ -f "$config" ]]; then+ width="$(read_num width "$config")"+ height="$(read_num height "$config")"+ [[ -n "$width" && -n "$height" ]] || fail "cannot read canvas width and height from poster.json"+ if [[ -n "$width" && -n "$height" ]]; then+ grep -q "data-canvas-width=\"$width\"" "$html" || fail "HTML canvas width does not match poster.json ($width)"+ grep -q "data-canvas-height=\"$height\"" "$html" || fail "HTML canvas height does not match poster.json ($height)"+ fi+fi++grep -q 'position:[[:space:]]*relative' "$html" || fail "canvas must be position: relative"+grep -q 'overflow:[[:space:]]*hidden' "$html" || fail "canvas must hide overflow"++if grep -Eq 'poster-preview|Your poster is taking shape|The first version will appear here automatically' "$html" 2>/dev/null; then+ fail "starter placeholder content remains"+fi++grep -Eiq '<script([[:space:]>])' "$html" && fail "scripts are not allowed in the shipping poster"+grep -Eiq '@media([[:space:](])' "$html" && fail "media queries are not allowed on a fixed canvas"+grep -Eiq '[0-9.]([[:space:]]*)(vw|vh|vmin|vmax)([^a-zA-Z]|$)' "$html" && fail "viewport units are not allowed for poster layout"+grep -Eiq "(src|href)[[:space:]]*=[[:space:]]*['\"](https?:)?//" "$html" && fail "external asset requests are not allowed"+grep -Eiq "src[[:space:]]*=[[:space:]]*['\"]data:" "$html" && fail "embed generated assets as project files, not data URLs"++tmp="$(mktemp -d "${TMPDIR:-/tmp}/poster-contract.XXXXXX")"+trap 'rm -rf -- "$tmp"' EXIT INT TERM++grep -o 'data-layer-id="[^"]*"' "$html" | sed 's/.*="//; s/"$//' | sort >"$tmp/layers" || true+duplicates="$(uniq -d "$tmp/layers")"+[[ -z "$duplicates" ]] || fail "duplicate data-layer-id values: $(printf '%s' "$duplicates" | tr '\n' ' ')"++grep -o 'src="[^"]*"' "$html" | sed 's/^src="//; s/"$//' >"$tmp/assets" || true+while IFS= read -r asset; do+ [[ -n "$asset" ]] || continue+ case "$asset" in+ /*|*://*|data:*) fail "asset path must be project-relative: $asset" ;;+ *) [[ -f "$project/$asset" ]] || fail "missing referenced asset: $asset" ;;+ esac+done <"$tmp/assets"++if [[ "$failures" -gt 0 ]]; then+ echo "$failures poster contract check(s) failed" >&2+ exit 1+fi++echo "ok poster contract and local assets"diff --git a/skills/editable-design/scripts/doctor.sh b/skills/editable-design/scripts/doctor.shnew file mode 100755index 0000000..a8e4e36--- /dev/null+++ b/skills/editable-design/scripts/doctor.sh@@ -0,0 +1,70 @@+#!/usr/bin/env bash+set -u++here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+failures=0++ok() { printf '%-22s %s\n' "$1" "OK $2"; }+warn() { printf '%-22s %s\n' "$1" "OPTIONAL $2"; }+bad() { printf '%-22s %s\n' "$1" "MISSING $2"; failures=$((failures + 1)); }++printf '%s\n\n' "Editable Design doctor"++if command -v node >/dev/null 2>&1; then+ node_version="$(node -p 'process.versions.node')"+ node_major="${node_version%%.*}"+ node_minor="$(printf '%s' "$node_version" | cut -d. -f2)"+ if [[ "$node_major" -gt 22 || ( "$node_major" -eq 22 && "$node_minor" -ge 12 ) ]]; then ok "Node.js" "$node_version"; else bad "Node.js" "$node_version; requires >=22.12"; fi+else+ bad "Node.js" "requires >=22.12"+fi++if command -v npm >/dev/null 2>&1; then ok "npm" "$(npm --version)"; else bad "npm" "required for npm ci --prefix scripts"; fi++if [[ -f "$here/node_modules/puppeteer-core/package.json" ]]; then+ version="$(node -p "require('$here/node_modules/puppeteer-core/package.json').version" 2>/dev/null || true)"+ ok "puppeteer-core" "${version:-installed}"+else+ bad "puppeteer-core" "run npm ci --prefix scripts"+fi++browser=""+for candidate in "${EDITABLE_DESIGN_BROWSER:-}" "${PUPPETEER_EXECUTABLE_PATH:-}" "${POSTER_BROWSER:-}" "${CHROME_PATH:-}"; do+ if [[ -n "$candidate" && -x "$candidate" ]]; then browser="$candidate"; break; fi+done+if [[ -z "$browser" ]]; then+ for candidate in chromium google-chrome chrome; do+ browser="$(command -v "$candidate" 2>/dev/null || true)"+ [[ -n "$browser" ]] && break+ done+fi+if [[ -z "$browser" ]]; then+ for candidate in \+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" \+ "/Applications/Chromium.app/Contents/MacOS/Chromium" \+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge" \+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser" \+ "/usr/bin/google-chrome" "/usr/bin/chromium" "/usr/bin/chromium-browser"; do+ if [[ -x "$candidate" ]]; then browser="$candidate"; break; fi+ done+fi+if [[ -n "$browser" ]]; then ok "Chromium browser" "$browser"; else bad "Chromium browser" "set EDITABLE_DESIGN_BROWSER"; fi++if command -v python3 >/dev/null 2>&1; then+ python_version="$(python3 -c 'import sys; print(".".join(map(str, sys.version_info[:3])))')"+ warn "Python" "$python_version; optional cutout processing only"+ if python3 -c 'import PIL' >/dev/null 2>&1; then warn "Pillow" "installed"; else warn "Pillow" "needed only for cutout processing"; fi+else+ warn "Python" "needed only for cutout processing"+fi++warn "Image generation" "host-dependent; auto mode can fall back to off"+if [[ "${EDITABLE_DESIGN_NO_SANDBOX:-0}" == "1" ]]; then warn "Browser sandbox" "disabled by explicit environment setting"; else ok "Browser sandbox" "enabled"; fi++printf '\n'+if [[ "$failures" -eq 0 ]]; then+ printf '%s\n' "Core workflow ready."+ exit 0+fi+printf '%s\n' "Core workflow has $failures missing requirement(s)."+exit 1diff --git a/skills/editable-design/scripts/explode.mjs b/skills/editable-design/scripts/explode.mjsnew file mode 100644index 0000000..fe3844c--- /dev/null+++ b/skills/editable-design/scripts/explode.mjs@@ -0,0 +1,115 @@+#!/usr/bin/env node+/**+ * explode.mjs —— 把已标注图层的海报生成横向拆解展示稿+ *+ * node explode.mjs <海报 index.html> [输出 HTML]+ *+ * 默认产出同目录 layers.html。完整成稿总览、未标记背景和一级内容模块+ * 从原稿位置动态散开成组件画廊。每个内容叶子仍是独立 DOM,不把整稿压成图片。+ */+import { writeFileSync, existsSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { launch, open, wireTemp } from './_browser.mjs';++const file = process.argv[2];+if (!file || !existsSync(resolve(file))) {+ console.error('用法: node explode.mjs <海报 index.html> [输出 HTML]');+ process.exit(2);+}++const src = resolve(file);+const out = process.argv[3] ? resolve(process.argv[3]) : join(dirname(src), 'layers.html');+if (out === src) {+ console.error('❌ 输出路径不能覆盖源 HTML');+ process.exit(2);+}++const wired = wireTemp(src, '_hf_explode.html');+const browser = await launch();+let code = 0;+try {+ const { page, errors } = await open(browser, wired.file, { waitEditor: true });+ const expected = await page.evaluate(() => {+ const layers = window.__layerEditor.layers();+ const groups = [...window.__layerEditor.state.groups.values()];+ const grouped = new Set(groups.flatMap((group) => group.memberIds));+ const primary = groups.length + layers.filter((layer) => !grouped.has(layer.id)).length;+ const textSupplements = primary < 5 ? layers.filter(({ id, el }) => {+ if (!grouped.has(id)) return false;+ const role = (el.dataset.explodeRole || 'copy').trim();+ if (['surface', 'image', 'icon', 'decoration'].includes(role)) return false;+ return Boolean((el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim());+ }).length : 0;+ return { layers: layers.length, groups: groups.length, primary, textSupplements, units: primary + textSupplements + 2 };+ });+ const html = await page.evaluate(() => window.__layerEditor.explodedHTML());+ writeFileSync(out, html);++ const { page: result, errors: resultErrors } = await open(browser, out, { width: 1600, height: 1000 });+ await result.waitForSelector('html[data-hf-exploded-ready]', { timeout: 20000 });+ const audit = await result.evaluate(() => ({+ board: !!document.querySelector('.hf-exploded-board'),+ units: document.querySelectorAll('.hf-exploded-item').length,+ layers: document.querySelectorAll('[data-exploded-layer]').length,+ uniqueLayers: new Set([...document.querySelectorAll('[data-exploded-layer]')]+ .map((node) => node.dataset.explodedLayer)).size,+ primary: Number(document.querySelector('.hf-exploded-board')?.dataset.explodedPrimaryCount || 0),+ textSupplements: document.querySelectorAll('.hf-exploded-item[data-exploded-text-supplement]').length,+ bases: document.querySelectorAll('.hf-exploded-base').length,+ overviews: document.querySelectorAll('[data-exploded-overview]').length,+ backgrounds: document.querySelectorAll('[data-exploded-background]').length,+ groups: document.querySelectorAll('.hf-exploded-item[data-exploded-group]').length,+ level: document.querySelector('.hf-exploded-board')?.dataset.explodedLevel,+ drilldownUI: !!document.querySelector('.hf-exploded-nav'),+ theme: document.querySelector('.hf-exploded-board')?.dataset.explodedTheme,+ replay: !!document.querySelector('.hf-exploded-replay'),+ motion: document.documentElement.dataset.hfMotion,+ editorUI: !!document.querySelector('.hf-bar,.hf-panel'),+ centerOccupied: (() => {+ const board = document.querySelector('.hf-exploded-board');+ const width = parseFloat(board?.style.width) || 1;+ return [...document.querySelectorAll('.hf-exploded-item')].some((item) => {+ const left = parseFloat(item.style.left) || 0;+ const itemWidth = parseFloat(item.style.width) || 0;+ return left < width * .58 && left + itemWidth > width * .42;+ });+ })(),+ overflow: document.documentElement.scrollWidth > innerWidth + 1+ || document.documentElement.scrollHeight > innerHeight + 1,+ }));++ console.log(`\n拆解展示 · ${src}\n`);+ console.log(` ${audit.board ? '✅' : '❌'} 横向拆解画布`);+ console.log(` ${audit.uniqueLayers === expected.layers ? '✅' : '❌'} 内容叶子 ${audit.uniqueLayers}/${expected.layers}(${audit.layers} 次呈现)`);+ console.log(` ${audit.units === expected.units ? '✅' : '❌'} 组件总数 ${audit.units}/${expected.units}`);+ console.log(` ${audit.primary === expected.primary && audit.textSupplements === expected.textSupplements ? '✅' : '❌'} 少组件文字补充 一级 ${audit.primary},文字 ${audit.textSupplements}`);+ console.log(` ${audit.bases === 0 && audit.centerOccupied ? '✅' : '❌'} 无中央大基底`);+ console.log(` ${audit.overviews === 1 && audit.backgrounds === 1 ? '✅' : '❌'} 总览与背景组件 ${audit.overviews}/${audit.backgrounds}`);+ console.log(` ${audit.groups === expected.groups ? '✅' : '❌'} 一级模块 ${audit.groups}/${expected.groups}`);+ console.log(` ${audit.level === '1' && !audit.drilldownUI ? '✅' : '❌'} 仅一级内容拆解`);+ console.log(` ${['light', 'dark'].includes(audit.theme) ? '✅' : '❌'} 明暗主题 ${audit.theme || '未识别'}`);+ console.log(` ${audit.replay && ['played', 'reduced'].includes(audit.motion) ? '✅' : '❌'} 自动播放与重播 ${audit.motion || '未播放'}`);+ console.log(` ${!audit.editorUI ? '✅' : '❌'} 不含编辑器界面`);+ console.log(` ${!audit.overflow ? '✅' : '❌'} 自适应窗口无滚动溢出`);+ const allErrors = [...errors, ...resultErrors];+ if (allErrors.length) console.log(` ❌ 页面报错 ${allErrors.join('; ')}`);++ if (!audit.board || audit.uniqueLayers !== expected.layers || audit.units !== expected.units+ || audit.primary !== expected.primary || audit.textSupplements !== expected.textSupplements+ || audit.bases !== 0 || !audit.centerOccupied || audit.overviews !== 1 || audit.backgrounds !== 1+ || audit.groups !== expected.groups+ || audit.level !== '1' || audit.drilldownUI+ || !['light', 'dark'].includes(audit.theme) || !audit.replay+ || !['played', 'reduced'].includes(audit.motion)+ || audit.editorUI || audit.overflow || allErrors.length) {+ code = 1;+ console.log('\n❌ 拆解稿未通过验收。');+ } else {+ console.log(`\n✅ 已写入 ${out}\n`);+ }+} finally {+ wired.cleanup();+ await browser.close();+}++process.exit(code);diff --git a/skills/editable-design/scripts/import-asset.sh b/skills/editable-design/scripts/import-asset.shnew file mode 100755index 0000000..50f3f76--- /dev/null+++ b/skills/editable-design/scripts/import-asset.sh@@ -0,0 +1,23 @@+#!/usr/bin/env bash+# Copy one selected ImageGen output into the poster project without guessing the+# newest generated file or silently overwriting an approved asset.+set -euo pipefail++source_file="${1:?usage: import-asset.sh SOURCE DEST [--replace]}"+destination="${2:?usage: import-asset.sh SOURCE DEST [--replace]}"+replace="${3:-}"++test -f "$source_file" || { echo "no such generated asset: $source_file" >&2; exit 2; }+[[ "$destination" != */ ]] || { echo "destination must include a filename" >&2; exit 2; }++if [[ -e "$destination" && "$replace" != "--replace" ]]; then+ echo "destination already exists: $destination" >&2+ echo "use a versioned filename, or pass --replace only when replacement is intentional" >&2+ exit 2+fi++mkdir -p "$(dirname "$destination")"+cp -p "$source_file" "$destination"++test -s "$destination" || { echo "asset copy produced an empty file: $destination" >&2; exit 3; }+echo "asset $(cd "$(dirname "$destination")" && pwd)/$(basename "$destination")"diff --git a/skills/editable-design/scripts/init-poster.sh b/skills/editable-design/scripts/init-poster.shnew file mode 100755index 0000000..aaeb470--- /dev/null+++ b/skills/editable-design/scripts/init-poster.sh@@ -0,0 +1,64 @@+#!/usr/bin/env bash+set -euo pipefail++target="${1:-$PWD}"+script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+starter="$(cd "$script_dir/../assets/poster-starter" && pwd)"+editor_source="$(cd "$script_dir/../assets/editor" && pwd)"+replay_source="$(cd "$script_dir/../assets/replay" && pwd)"++if [[ ! -f "$editor_source/layer-editor.css" \+ || ! -f "$editor_source/layer-editor.js" ]] \+ || ! grep -q '\.hf-exploded-board' "$editor_source/layer-editor.css" \+ || ! grep -q '\.hf-resize-overlay' "$editor_source/layer-editor.css" \+ || ! grep -q 'setExploded' "$editor_source/layer-editor.js" \+ || ! grep -q 'data-hf-resize-dir' "$editor_source/layer-editor.js" \+ || ! grep -q 'downloadExploded' "$editor_source/layer-editor.js"; then+ echo "Bundled poster editor runtime is missing or incomplete." >&2+ exit 2+fi++mkdir -p "$target"+if find "$target" -mindepth 1 -maxdepth 1 \+ ! -name '.git' ! -name '.DS_Store' ! -name 'work' ! -name 'outputs' \+ -print -quit | grep -q .; then+ echo "Target is not empty: $target" >&2+ exit 2+fi++cp -R "$starter"/. "$target"/++# Put the reproducible runtime beside the generated project. Skill installation+# paths vary by host, so a project must never depend on the path it was created+# from.+mkdir -p "$target/scripts/editor-assets" "$target/scripts/replay-assets" "$target/assets" "$target/reference" "$target/out" "$target/licenses"+for tool in build-replay.mjs check-fonts.sh check-poster.sh import-asset.sh remove-chroma-key.py render-poster.sh trace.sh verify-replay.mjs wire-editor.mjs; do+ cp -p "$script_dir/$tool" "$target/scripts/$tool"+done++for editor_asset in layer-editor.css layer-editor.js; do+ cp -p "$editor_source/$editor_asset" "$target/scripts/editor-assets/$editor_asset"+done++cp -R "$replay_source"/. "$target/scripts/replay-assets"/+if [[ -f "$script_dir/../LICENSE" ]]; then+ cp -p "$script_dir/../LICENSE" "$target/licenses/editable-design-runtime-Apache-2.0.txt"+fi++# Source control is useful but not part of poster generation. Make it opt-in so+# initialization does not silently create repository state in a user's folder.+if [[ "${POSTER_INIT_GIT:-0}" == "1" && ! -d "$target/.git" ]]; then+ if command -v git >/dev/null 2>&1; then+ git -C "$target" init -b main >/dev/null+ else+ echo "git requested but unavailable - continuing without it" >&2+ fi+fi++# Nothing to install, but the renderer must be confirmed before any layout is+# written - otherwise you find out it is missing only after the poster is done.+"$script_dir/render-poster.sh" --probe || true+echo "starter $(cd "$target" && pwd)"+echo "tools $(cd "$target/scripts" && pwd)"+echo "editor bundled move/resize/edit/scan/explode runtime"+echo "replay bundled evidence viewer"diff --git a/skills/editable-design/scripts/package-lock.json b/skills/editable-design/scripts/package-lock.jsonnew file mode 100755index 0000000..7584fb2--- /dev/null+++ b/skills/editable-design/scripts/package-lock.json@@ -0,0 +1,334 @@+{+ "name": "editable-design-tools",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "editable-design-tools",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "puppeteer-core": "25.9.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@puppeteer/browsers": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.1.tgz",+ "integrity": "sha512-KDz+3qDRdBAlRlMjmKyj6dEs33YHTk/xRHEENSXq6TNnhgoU15ruSHtEBeVF6OZ9tBDY55Se4P0nFMNsipzU9A==",+ "license": "Apache-2.0",+ "dependencies": {+ "modern-tar": "^0.8.0",+ "yargs": "^18.0.0"+ },+ "bin": {+ "browsers": "lib/main-cli.js"+ },+ "engines": {+ "node": ">=22.12.0"+ },+ "peerDependencies": {+ "proxy-agent": ">=8.0.1",+ "yauzl": "^2.10.0 || ^3.4.0"+ },+ "peerDependenciesMeta": {+ "proxy-agent": {+ "optional": true+ },+ "yauzl": {+ "optional": true+ }+ }+ },+ "node_modules/ansi-regex": {+ "version": "6.3.0",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.3.0.tgz",+ "integrity": "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"+ }+ },+ "node_modules/ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/chromium-bidi": {+ "version": "17.0.2",+ "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-17.0.2.tgz",+ "integrity": "sha512-5v9GQFhTktFvotn/OFNJBmKLKRAb6n9r0bVCwf7sHgWc3/JryK0bj1nn93L3pHFrfgcsu6Be6EWsDi+1XHTGDg==",+ "license": "Apache-2.0",+ "dependencies": {+ "mitt": "^3.0.1",+ "zod": "^3.24.1"+ },+ "engines": {+ "node": ">=20.19.0 <22.0.0 || >=22.12.0"+ },+ "peerDependencies": {+ "devtools-protocol": "*"+ }+ },+ "node_modules/cliui": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",+ "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^7.2.0",+ "strip-ansi": "^7.1.0",+ "wrap-ansi": "^9.0.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/cliui/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/devtools-protocol": {+ "version": "0.0.1666840",+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1666840.tgz",+ "integrity": "sha512-gCcO42XCHKEs7Ag0S7aGYsnJ7hlgrO3qderYqeiY0Eqk+0GFfuvT13IA0hHreJTa2KCdDVyGMeOhdMNmrrTjVg==",+ "license": "BSD-3-Clause"+ },+ "node_modules/emoji-regex": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",+ "license": "MIT"+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/get-east-asian-width": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz",+ "integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/mitt": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",+ "license": "MIT"+ },+ "node_modules/modern-tar": {+ "version": "0.8.4",+ "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.8.4.tgz",+ "integrity": "sha512-gN54ddmyzEg10orwZ2u4OOv+bjpMWdIl5jIkodK97bMq8QBSL5c0D7YX0lT1Ooz+99S7+PvFbnxzdjgHo1r41g==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/puppeteer-core": {+ "version": "25.9.0",+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.9.0.tgz",+ "integrity": "sha512-U61rCwSMha62CA/Opy6tCx2Fx+ck7ouiKnbpEApzSoLYMoEu9F71nuFpHL55vmIt33/GYm6eKZVhH2ev0nAIeg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@puppeteer/browsers": "3.2.1",+ "chromium-bidi": "17.0.2",+ "devtools-protocol": "0.0.1666840",+ "typed-query-selector": "^2.12.2",+ "webdriver-bidi-protocol": "0.4.2",+ "ws": "^8.21.3"+ },+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/string-width": {+ "version": "8.2.2",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.2.2.tgz",+ "integrity": "sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg==",+ "license": "MIT",+ "dependencies": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ },+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/strip-ansi": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",+ "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^6.2.2"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"+ }+ },+ "node_modules/typed-query-selector": {+ "version": "2.12.2",+ "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.2.tgz",+ "integrity": "sha512-EOPFbyIub4ngnEdqi2yOcNeDLaX/0jcE1JoAXQDDMIthap7FoN795lc/SHfIq2d416VufXpM8z/lD+WRm2gfOQ==",+ "license": "MIT"+ },+ "node_modules/webdriver-bidi-protocol": {+ "version": "0.4.2",+ "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.2.tgz",+ "integrity": "sha512-VSV+fzfChirL3e7jay2yUC7B4HQCGtEWEg/MSSQbK+qWbqeGlRLlXTzPpYr3XGUvbpDHumWZBJxgesg4N7dbtA==",+ "license": "Apache-2.0"+ },+ "node_modules/wrap-ansi": {+ "version": "9.0.2",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",+ "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^6.2.1",+ "string-width": "^7.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/wrap-ansi/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/ws": {+ "version": "8.21.3",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",+ "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yargs": {+ "version": "18.1.0",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.1.0.tgz",+ "integrity": "sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg==",+ "license": "MIT",+ "dependencies": {+ "cliui": "^9.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "string-width": "^8.2.1",+ "y18n": "^5.0.5",+ "yargs-parser": "^22.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/yargs-parser": {+ "version": "22.0.0",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",+ "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",+ "license": "ISC",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/skills/editable-design/scripts/package.json b/skills/editable-design/scripts/package.jsonnew file mode 100755index 0000000..993b455--- /dev/null+++ b/skills/editable-design/scripts/package.json@@ -0,0 +1,14 @@+{+ "name": "editable-design-tools",+ "version": "0.1.0",+ "private": true,+ "type": "module",+ "description": "Editable Design browser validation, editing, layer breakdown, and replay tools",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=22.12.0"+ },+ "dependencies": {+ "puppeteer-core": "25.9.0"+ }+}diff --git a/skills/editable-design/scripts/remove-chroma-key.py b/skills/editable-design/scripts/remove-chroma-key.pynew file mode 100755index 0000000..e01f473--- /dev/null+++ b/skills/editable-design/scripts/remove-chroma-key.py@@ -0,0 +1,201 @@+#!/usr/bin/env python3+"""Turn a flat chroma-key image into a PNG or WebP with alpha."""++from __future__ import annotations++import argparse+from pathlib import Path+import re+from statistics import median+import sys+++def fail(message: str) -> None:+ print(f"remove-chroma-key: {message}", file=sys.stderr)+ raise SystemExit(2)+++def load_pillow():+ try:+ from PIL import Image, ImageFilter+ except ImportError:+ fail("Pillow is required; install it with `python3 -m pip install pillow`.")+ return Image, ImageFilter+++def parse_color(value: str) -> tuple[int, int, int]:+ match = re.fullmatch(r"#?([0-9a-fA-F]{6})", value.strip())+ if not match:+ fail("--key-color must be a six-digit RGB hex value such as #00ff00")+ raw = match.group(1)+ return tuple(int(raw[index : index + 2], 16) for index in (0, 2, 4))+++def sample_key(image, mode: str) -> tuple[int, int, int]:+ width, height = image.size+ pixels = image.load()+ samples: list[tuple[int, int, int]] = []+ band = max(1, min(width, height, 6))++ if mode == "corners":+ patch = max(1, min(width, height, 12))+ boxes = (+ (0, 0, patch, patch),+ (width - patch, 0, width, patch),+ (0, height - patch, patch, height),+ (width - patch, height - patch, width, height),+ )+ for left, top, right, bottom in boxes:+ for y in range(top, bottom):+ for x in range(left, right):+ samples.append(tuple(pixels[x, y][:3]))+ else:+ step = max(1, min(width, height) // 256)+ for x in range(0, width, step):+ for offset in range(band):+ samples.append(tuple(pixels[x, offset][:3]))+ samples.append(tuple(pixels[x, height - 1 - offset][:3]))+ for y in range(0, height, step):+ for offset in range(band):+ samples.append(tuple(pixels[offset, y][:3]))+ samples.append(tuple(pixels[width - 1 - offset, y][:3]))++ if not samples:+ fail("could not sample a key color from the image border")+ return tuple(int(round(median(pixel[channel] for pixel in samples))) for channel in range(3))+++def smoothstep(value: float) -> float:+ value = max(0.0, min(1.0, value))+ return value * value * (3.0 - 2.0 * value)+++def matte_alpha(distance: int, transparent: float, opaque: float) -> int:+ if distance <= transparent:+ return 0+ if distance >= opaque:+ return 255+ return round(255 * smoothstep((distance - transparent) / (opaque - transparent)))+++def spill_channels(key: tuple[int, int, int]) -> list[int]:+ maximum = max(key)+ if maximum < 128:+ return []+ return [index for index, value in enumerate(key) if value >= maximum - 16 and value >= 128]+++def dominance(rgb: tuple[int, int, int], key: tuple[int, int, int]) -> float:+ spills = spill_channels(key)+ if not spills:+ return 0.0+ others = [index for index in range(3) if index not in spills]+ key_strength = min(rgb[index] for index in spills)+ other_strength = max((rgb[index] for index in others), default=0)+ return float(key_strength - other_strength)+++def dominance_alpha(rgb: tuple[int, int, int], key: tuple[int, int, int]) -> int:+ amount = dominance(rgb, key)+ if amount <= 0:+ return 255+ spills = spill_channels(key)+ others = [index for index in range(3) if index not in spills]+ other_strength = max((rgb[index] for index in others), default=0)+ denominator = max(1.0, max(key) - other_strength)+ return round(255 * (1.0 - min(1.0, amount / denominator)))+++def despill(rgb: tuple[int, int, int], key: tuple[int, int, int], alpha: int) -> tuple[int, int, int]:+ if alpha >= 252:+ return rgb+ spills = spill_channels(key)+ others = [index for index in range(3) if index not in spills]+ if not spills or not others:+ return rgb+ values = list(rgb)+ cap = max(0, max(values[index] for index in others) - 1)+ for index in spills:+ values[index] = min(values[index], cap)+ return tuple(values)+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--input", required=True)+ parser.add_argument("--out", required=True)+ parser.add_argument("--key-color", default="#00ff00")+ parser.add_argument("--auto-key", choices=("none", "corners", "border"), default="border")+ parser.add_argument("--soft-matte", action="store_true")+ parser.add_argument("--transparent-threshold", type=float, default=12.0)+ parser.add_argument("--opaque-threshold", type=float, default=220.0)+ parser.add_argument("--despill", action="store_true")+ parser.add_argument("--edge-contract", type=int, default=0)+ parser.add_argument("--edge-feather", type=float, default=0.0)+ parser.add_argument("--force", action="store_true")+ return parser+++def main() -> None:+ args = build_parser().parse_args()+ source = Path(args.input)+ output = Path(args.out)+ if not source.is_file():+ fail(f"input image not found: {source}")+ if output.exists() and not args.force:+ fail(f"output already exists: {output}; pass --force to replace it")+ if output.suffix.lower() not in {".png", ".webp"}:+ fail("--out must end in .png or .webp")+ if not 0 <= args.transparent_threshold < args.opaque_threshold <= 255:+ fail("matte thresholds must satisfy 0 <= transparent < opaque <= 255")+ if not 0 <= args.edge_contract <= 16 or not 0 <= args.edge_feather <= 64:+ fail("edge contract must be 0..16 and edge feather must be 0..64")++ Image, ImageFilter = load_pillow()+ with Image.open(source) as opened:+ image = opened.convert("RGBA")+ key = sample_key(image, args.auto_key) if args.auto_key != "none" else parse_color(args.key_color)+ pixels = image.load()+ width, height = image.size++ for y in range(height):+ for x in range(width):+ red, green, blue, original_alpha = pixels[x, y]+ rgb = (red, green, blue)+ distance = max(abs(rgb[index] - key[index]) for index in range(3))+ key_like = distance <= 32 or dominance(rgb, key) >= 16+ alpha = 255+ if key_like:+ alpha = min(+ matte_alpha(distance, args.transparent_threshold, args.opaque_threshold),+ dominance_alpha(rgb, key),+ )+ alpha = round(alpha * original_alpha / 255)+ if alpha <= 8:+ pixels[x, y] = (0, 0, 0, 0)+ continue+ if args.despill and key_like:+ red, green, blue = despill(rgb, key, alpha)+ pixels[x, y] = (red, green, blue, alpha)++ alpha_channel = image.getchannel("A")+ for _ in range(args.edge_contract):+ alpha_channel = alpha_channel.filter(ImageFilter.MinFilter(3))+ if args.edge_feather:+ alpha_channel = alpha_channel.filter(ImageFilter.GaussianBlur(args.edge_feather))+ image.putalpha(alpha_channel)++ histogram = alpha_channel.histogram()+ total = width * height+ transparent = sum(histogram[:13])+ partial = sum(histogram[13:255])+ output.parent.mkdir(parents=True, exist_ok=True)+ image.save(output)+ print(f"wrote {output}")+ print(f"key color: #{key[0]:02x}{key[1]:02x}{key[2]:02x}")+ print(f"transparent pixels: {transparent}/{total}")+ print(f"partially transparent pixels: {partial}/{total}")+++if __name__ == "__main__":+ main()diff --git a/skills/editable-design/scripts/render-poster.sh b/skills/editable-design/scripts/render-poster.shnew file mode 100755index 0000000..5ecb2b9--- /dev/null+++ b/skills/editable-design/scripts/render-poster.sh@@ -0,0 +1,202 @@+#!/usr/bin/env bash+# Render the poster with the host browser, then read the real pixel dimensions+# back and compare them with the declared canvas.+#+# The read-back is not redundant: a browser silently produces a different size+# when the window and the content disagree, and the resulting image looks+# perfectly normal. Trust the artefact, not the renderer's exit code.+set -euo pipefail++find_browser() {+ local candidates=(+ "${EDITABLE_DESIGN_BROWSER:-}"+ "${PUPPETEER_EXECUTABLE_PATH:-}"+ "${POSTER_BROWSER:-}"+ "${CHROME_PATH:-}"+ )+ local candidate+ for candidate in "${candidates[@]}"; do+ [[ -n "$candidate" && -x "$candidate" ]] && { printf '%s' "$candidate"; return 0; }+ done+ for candidate in chromium google-chrome chrome; do+ local found+ found="$(command -v "$candidate" 2>/dev/null || true)"+ [[ -n "$found" ]] && { printf '%s' "$found"; return 0; }+ done+ candidates=(+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"+ "/Applications/Chromium.app/Contents/MacOS/Chromium"+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"+ )+ for candidate in "${candidates[@]}"; do+ [[ -x "$candidate" ]] && { printf '%s' "$candidate"; return 0; }+ done+ return 1+}++if [[ "${1:-}" == "--probe" ]]; then+ if browser="$(find_browser)"; then+ echo "renderer $browser"+ exit 0+ fi+ echo "renderer no Chromium-based browser found - rendering unavailable" >&2+ echo " install Google Chrome, or set EDITABLE_DESIGN_BROWSER=<executable>" >&2+ exit 1+fi++html="${1:?usage: render-poster.sh HTML [OUT_PNG] [--scale N | --dpi N]}"+shift+if [[ $# -gt 0 && "$1" != --* ]]; then+ out="$1"+ shift+else+ out="$(cd "$(dirname "$html")" 2>/dev/null && pwd)/out/poster.png"+fi++scale=""+dpi=""+while [[ $# -gt 0 ]]; do+ case "$1" in+ --scale) scale="$2"; shift 2 ;;+ --dpi) dpi="$2"; shift 2 ;;+ *) echo "unknown argument: $1" >&2; exit 2 ;;+ esac+done++test -f "$html" || { echo "no such file: $html" >&2; exit 2; }+project="$(cd "$(dirname "$html")" && pwd)"+config="$project/poster.json"++# poster.json's shape is fixed by the starter, so sed is enough and this script+# stays free of a JSON dependency.+read_num() {+ sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p" "$2" | head -1+}++if [[ -f "$config" ]]; then+ width="$(read_num width "$config")"+ height="$(read_num height "$config")"+ [[ -z "$scale" ]] && scale="$(read_num scale "$config")"+ [[ -z "$dpi" ]] && dpi="$(read_num dpi "$config")"+fi++[[ -n "${width:-}" && -n "${height:-}" ]] || {+ echo "cannot read canvas.width / canvas.height from poster.json" >&2+ exit 2+}++# Print path converts at 96 px/inch, so a given dpi decides the scale factor.+if [[ -n "$dpi" && "$dpi" != "0" ]]; then+ scale="$(awk -v d="$dpi" 'BEGIN { printf "%.4g", d / 96 }')"+fi+[[ -n "$scale" && "$scale" != "0" ]] || scale=2++browser="$(find_browser)" || {+ echo "no Chromium-based browser found. Set EDITABLE_DESIGN_BROWSER=<executable>" >&2+ exit 1+}++mkdir -p "$(dirname "$out")"+rm -f "$out"++# Never attach to the user's running browser, and never share a profile between+# poster renders. A shared profile makes concurrent jobs fight over its lock and+# lets a stale Chrome child poison the next run.+profile="$(mktemp -d "${TMPDIR:-/tmp}/poster-render-profile.XXXXXX")"+renderer_pid=""++profile_pids() {+ ps -axo pid=,command= \+ | awk -v marker="--user-data-dir=$profile" \+ 'index($0, marker) && index($0, "awk -v marker=") == 0 { print $1 }'+}++stop_renderer() {+ local pids=""+ local _++ pids="$(profile_pids)"+ [[ -n "$pids" ]] && kill $pids 2>/dev/null || true++ for _ in $(seq 1 20); do+ pids="$(profile_pids)"+ [[ -z "$pids" ]] && break+ sleep 0.1+ done++ pids="$(profile_pids)"+ [[ -n "$pids" ]] && kill -KILL $pids 2>/dev/null || true++ if [[ -n "$renderer_pid" ]]; then+ wait "$renderer_pid" 2>/dev/null || true+ fi+}++cleanup() {+ stop_renderer+ if [[ -n "$profile" && -d "$profile" && "$profile" == *"/poster-render-profile."* ]]; then+ rm -rf -- "$profile"+ fi+}++trap cleanup EXIT INT TERM++"$browser" \+ --headless \+ --disable-gpu \+ --hide-scrollbars \+ --no-first-run \+ --no-default-browser-check \+ --disable-extensions \+ --disable-background-networking \+ --disable-sync \+ --disable-default-apps \+ --mute-audio \+ --user-data-dir="$profile" \+ --force-device-scale-factor="$scale" \+ --window-size="${width},${height}" \+ --screenshot="$out" \+ "file://$(cd "$(dirname "$html")" && pwd)/$(basename "$html")" \+ >/dev/null 2>&1 &+renderer_pid=$!++# headless occasionally does not exit on its own, so wait for the artefact+# rather than for the process.+for _ in $(seq 1 120); do+ kill -0 "$renderer_pid" 2>/dev/null || break+ [[ -s "$out" ]] && { sleep 0.4; break; }+ sleep 0.5+done+stop_renderer+renderer_pid=""++test -s "$out" || { echo "render produced no $out" >&2; exit 3; }++# A PNG's IHDR carries width and height at bytes 16..23, big-endian. Reading+# them this way needs neither sips nor Pillow. macOS od emits a trailing blank+# line, so split on words instead of processing line by line.+png_dimensions() {+ local file="$1"+ # shellcheck disable=SC2046+ set -- $(od -An -tu1 -j16 -N8 "$file")+ printf '%d %d' \+ "$(( $1 * 16777216 + $2 * 65536 + $3 * 256 + $4 ))" \+ "$(( $5 * 16777216 + $6 * 65536 + $7 * 256 + $8 ))"+}++read -r actual_w actual_h <<<"$(png_dimensions "$out")"+expect_w="$(awk -v w="$width" -v s="$scale" 'BEGIN { printf "%d", w * s + 0.5 }')"+expect_h="$(awk -v h="$height" -v s="$scale" 'BEGIN { printf "%d", h * s + 0.5 }')"++if [[ "$actual_w" != "$expect_w" || "$actual_h" != "$expect_h" ]]; then+ echo "render does not match the declared canvas: got ${actual_w}x${actual_h}, expected ${expect_w}x${expect_h}" >&2+ echo "canvas ${width}x${height} @${scale}x. Check that the root element's width/height equal its data-canvas-* values." >&2+ exit 3+fi++echo "$out ${actual_w}x${actual_h} (canvas ${width}x${height} @${scale}x)"+echo+echo "Next: read this image and say every piece of text on it out loud, line by line."+echo "Confirm nothing is clipped, covered, or carried in from the generated artwork."+echo "A DOM check cannot see any of that."diff --git a/skills/editable-design/scripts/trace.sh b/skills/editable-design/scripts/trace.shnew file mode 100755index 0000000..ae210e8--- /dev/null+++ b/skills/editable-design/scripts/trace.sh@@ -0,0 +1,159 @@+#!/usr/bin/env bash+# Append-only execution trace for one poster build.+#+# Writes into `.trace/` inside the poster project: a manifest, one JSONL event+# stream, per-step command output, and copies of intermediate artefacts. The+# point is that "what was decided, and why" survives after the conversation is+# gone — a rendered poster on its own cannot tell you which prompt produced its+# backdrop or why a canvas size was chosen.+#+# Pure bash on purpose: this plugin has no runtime dependencies, and adding one+# just to keep a log would be a bad trade.+set -euo pipefail++script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+project_root="$(cd "$script_dir/.." && pwd)"+cd "$project_root"++trace_dir="${POSTER_TRACE_DIR:-$project_root/.trace}"+events="$trace_dir/events.jsonl"++now() { date +"%Y-%m-%dT%H:%M:%S%z" | sed 's/\(..\)$/:\1/'; }++# Minimal JSON string escaping: backslash, quote, then control characters.+esc() {+ printf '%s' "$1" \+ | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' \+ | awk 'BEGIN { ORS = "" } { if (NR > 1) print "\\n"; print }'+}++require_trace() {+ test -f "$events" || {+ echo "trace: no active trace. Run trace.sh init first" >&2+ exit 2+ }+}++append() {+ require_trace+ local seq+ seq=$(( $(wc -l <"$events") + 1 ))+ printf '{"seq":%d,"ts":"%s",%s}\n' "$seq" "$(now)" "$1" >>"$events"+}++cmd="${1:-}"+shift || true++case "$cmd" in+ init)+ label="${1:-}"+ mkdir -p "$trace_dir/steps" "$trace_dir/artifacts"+ : >"$events"+ printf '{\n "schema": "runlog/v1",\n "run_id": "%s",\n "created_at": "%s",\n "skill": "poster-building",\n "workspace": "%s",\n "label": "%s",\n "status": "running"\n}\n' \+ "$(date +%Y%m%d-%H%M%S)" "$(now)" "$(esc "$PWD")" "$(esc "$label")" \+ >"$trace_dir/manifest.json"+ append "\"type\":\"run_start\",\"label\":\"$(esc "$label")\""+ echo "$trace_dir"+ ;;++ start)+ step="${1:?usage: trace.sh start STEP [TITLE]}"+ append "\"type\":\"step_start\",\"step\":\"$(esc "$step")\",\"title\":\"$(esc "${2:-}")\""+ ;;++ done)+ step="${1:?usage: trace.sh done STEP [STATUS] [NOTE]}"+ append "\"type\":\"step_done\",\"step\":\"$(esc "$step")\",\"status\":\"${2:-ok}\",\"note\":\"$(esc "${3:-}")\""+ ;;++ decision)+ key="${1:?usage: trace.sh decision KEY VALUE WHY [STEP]}"+ value="${2:?}"+ why="${3:?why is required — a decision without a reason is not worth recording}"+ append "\"type\":\"decision\",\"step\":\"$(esc "${4:-}")\",\"key\":\"$(esc "$key")\",\"value\":\"$(esc "$value")\",\"why\":\"$(esc "$why")\""+ ;;++ note)+ append "\"type\":\"note\",\"step\":\"$(esc "${2:-}")\",\"text\":\"$(esc "${1:?usage: trace.sh note TEXT [STEP]}")\""+ ;;++ artifact)+ src="${1:?usage: trace.sh artifact PATH [STEP]}"+ step="${2:-_unassigned}"+ test -e "$src" || { echo "trace: no such path: $src" >&2; exit 2; }+ dest="$trace_dir/artifacts/$step"+ mkdir -p "$dest"+ # -X drops extended attributes on macOS; GNU cp does not accept the same+ # option, so keep the portable path everywhere else.+ if [[ "$(uname -s)" == "Darwin" ]]; then+ cp -RX "$src" "$dest/"+ else+ cp -R "$src" "$dest/"+ fi+ copied="$dest/$(basename "$src")"+ find "$dest" -name '._*' -delete 2>/dev/null || true+ if [[ -d "$copied" ]]; then+ size=$(find "$copied" -type f -exec wc -c {} + | tail -1 | awk '{print $1}')+ else+ size=$(wc -c <"$copied" | tr -d ' ')+ fi+ append "\"type\":\"artifact\",\"step\":\"$(esc "$step")\",\"name\":\"$(esc "$(basename "$src")")\",\"path\":\"artifacts/$(esc "$step")/$(esc "$(basename "$src")")\",\"bytes\":$size"+ ;;++ run)+ step="${1:?usage: trace.sh run STEP -- COMMAND...}"+ shift+ [[ "${1:-}" == "--" ]] && shift+ [[ $# -gt 0 ]] || { echo "trace: no command given" >&2; exit 2; }++ step_dir="$trace_dir/steps/$step"+ mkdir -p "$step_dir"+ index=$(( $(find "$step_dir" -name 'exec-*.json' | wc -l) + 1 ))+ stem=$(printf 'exec-%02d' "$index")++ append "\"type\":\"exec_start\",\"step\":\"$(esc "$step")\",\"label\":\"$stem\",\"command\":\"$(esc "$*")\""++ started=$(date +%s)+ set +e+ "$@" >"$step_dir/$stem.stdout" 2>"$step_dir/$stem.stderr"+ code=$?+ set -e+ elapsed=$(( $(date +%s) - started ))++ printf '{\n "label": "%s",\n "command": "%s",\n "exit_code": %d,\n "duration_s": %d,\n "stdout": "%s.stdout",\n "stderr": "%s.stderr"\n}\n' \+ "$stem" "$(esc "$*")" "$code" "$elapsed" "$stem" "$stem" >"$step_dir/$stem.json"++ append "\"type\":\"exec_done\",\"step\":\"$(esc "$step")\",\"label\":\"$stem\",\"exit_code\":$code,\"duration_s\":$elapsed"++ cat "$step_dir/$stem.stdout"+ cat "$step_dir/$stem.stderr" >&2+ exit $code+ ;;++ finish)+ require_trace+ status="${1:-ok}"+ append "\"type\":\"run_finish\",\"status\":\"$status\""+ sed -i.bak "s/\"status\": \"running\"/\"status\": \"$status\"/" "$trace_dir/manifest.json"+ rm -f "$trace_dir/manifest.json.bak"+ printf '{\n "status": "%s",\n "finished_at": "%s",\n "events": %d\n}\n' \+ "$status" "$(now)" "$(wc -l <"$events")" >"$trace_dir/result.json"+ echo "$trace_dir"+ ;;++ *)+ cat >&2 <<'USAGE'+usage: trace.sh <command>++ init [LABEL] start a trace in ./.trace/+ start STEP [TITLE] mark a step as started+ done STEP [ok|skip|fail] [NOTE] mark a step as finished+ decision KEY VALUE WHY [STEP] record a choice and its reason (why is required)+ note TEXT [STEP] record an observation+ artifact PATH [STEP] copy an intermediate artefact into the trace+ run STEP -- COMMAND... run a command, capturing output and exit code+ finish [ok|fail] close the trace+USAGE+ exit 2+ ;;+esacdiff --git a/skills/editable-design/scripts/verify-replay.mjs b/skills/editable-design/scripts/verify-replay.mjsnew file mode 100644index 0000000..b6107f5--- /dev/null+++ b/skills/editable-design/scripts/verify-replay.mjs@@ -0,0 +1,93 @@+#!/usr/bin/env node+import { existsSync, readFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import vm from 'node:vm';++const input = resolve(process.argv[2] || join(process.cwd(), 'replay', 'index.html'));+const replayDir = dirname(input);+const required = ['index.html', 'replay.css', 'replay.js', 'replay-motion.js', 'data.js'];+let failed = false;++for (const file of required) {+ const ok = existsSync(join(replayDir, file));+ console.log(` ${ok ? '✅' : '❌'} ${file}`);+ failed ||= !ok;+}++if (!failed) {+ const html = readFileSync(input, 'utf8');+ const replayCSS = readFileSync(join(replayDir, 'replay.css'), 'utf8');+ const replayJS = readFileSync(join(replayDir, 'replay.js'), 'utf8');+ const motionJS = readFileSync(join(replayDir, 'replay-motion.js'), 'utf8');+ const script = readFileSync(join(replayDir, 'data.js'), 'utf8');+ const sandbox = { window: {} };+ vm.runInNewContext(script, sandbox, { timeout: 1000 });+ const data = sandbox.window.__POSTER_REPLAY__;+ const ids = data?.stages?.map((stage) => stage.id) || [];+ const expected = ['input', 'reference', 'plan', 'assets', 'html', 'review', 'layers'];+ const schemaOK = data?.schema === 'poster-replay/v1';+ const stagesOK = expected.every((id, index) => ids[index] === id);+ const offlineOK = !/https?:\/\//i.test(html) && !/\bfetch\s*\(/.test(replayJS) && !/\bfetch\s*\(/.test(motionJS);+ const sourceOK = data.stages.every((stage) => Array.isArray(stage.sources));+ const phaseNavOK = html.includes('id="phase-nav"') && ['理解与规划', '生成与构建', '观察与修正'].every((label) => html.includes(label));+ const phaseIconsOK = ['icons/plan.png', 'icons/html.png', 'icons/review.png'].every((source) => html.includes(source));+ const noDefaultDetailOK = !html.includes('data-default-stage') && replayJS.includes('document.body.dataset.defaultStage ? stageById.get(document.body.dataset.defaultStage) : null');+ const arrowSizingOK = /markerUnits=["']userSpaceOnUse["']/.test(replayJS);+ const motionOK = html.includes('id="play-replay"') && ['runIntro', 'startAmbient', 'playReplay'].every((name) => motionJS.includes(name));+ const reducedMotionOK = motionJS.includes('prefers-reduced-motion');+ const flowIds = ['flow-input-reference', 'flow-reference-plan', 'flow-plan-assets', 'flow-assets-html', 'flow-html-review', 'flow-review-html-repair', 'flow-review-layers'];+ const playbackPathOK = flowIds.every((id) => replayJS.includes(`id="${id}"`) && motionJS.includes(id));+ const ambientCadenceOK = motionJS.includes('randomBetween(1800, 3000)') && motionJS.includes('randomBetween(2600, 4000)') && motionJS.includes('isRepair ? 1100 : 400') && motionJS.includes('strong ? 720 : 1150') && motionJS.includes('scale >= .20');+ const introTimingOK = motionJS.includes('INTRO_DURATION = 4700') && replayCSS.includes('.is-intro .detail-panel');+ const assetOverviewOK = replayJS.includes('asset-overview-grid') && replayCSS.includes('.asset-overview-grid');+ const planMatrixOK = replayJS.includes('hasRecordedRects') && replayJS.includes('slots.length >= 5 ? 3') && replayJS.includes('slot.role || slot.form || slot.aspect || slot.prompt') && replayJS.includes('plan-empty');+ const scaledPhaseNavOK = html.indexOf('id="canvas-world"') < html.indexOf('id="phase-nav"') && html.indexOf('id="phase-nav"') < html.indexOf('id="flow-lines"') && replayCSS.includes('width: 2540px');+ const largePhaseNavOK = replayCSS.includes('width: 210px') && replayCSS.includes('min-height: 210px') && replayCSS.includes('width: 56px; height: 56px') && replayCSS.includes('font-size: 19px');+ const assetStageOK = replayJS.includes("assets: { x: 800, y: 640, w: 480, h: 390 }") && replayJS.includes("shorten(first.prompt || '未记录素材 Prompt。', 320)");+ const adaptiveAssetsOK = replayJS.includes('assetItems.length === 1') && replayJS.includes("className: 'asset single-asset'") && replayJS.includes('x: 260, y: 610, w: 500, h: 440') && replayJS.includes('x: 260 + (index % 2) * 260') && replayJS.includes('y: 610 + Math.floor(index / 2) * 230') && replayJS.includes('assetCount === 1') && replayJS.includes('.slice(0, assetCount)');+ const assetShowcaseOK = motionJS.includes('scheduleAssetShowcase') && motionJS.includes('duration: 700') && motionJS.includes('randomBetween(4000, 6000)') && motionJS.includes("transform: 'scale(1.015)'");+ const feedbackLabelOK = replayJS.includes('class="flow-label prove-label"') && replayCSS.includes('.flow-label text { fill: #47765c');+ const layersStage = data.stages.find((stage) => stage.id === 'layers');+ const liveLayerAnimationOK = !layersStage?.preview?.includes('motion=0') && replayJS.includes('可编辑分层动画(HTML)');+ const referencePlacementOK = replayJS.includes("reference: { x: 820, y: 110, w: 450, h: 330 }") && replayJS.includes("x: 1538, y: 110, w: 270, h: 360") && replayJS.includes('class="flow-artifact flow-path think"') && replayJS.includes('d="M1270 290 L2075 290"') && !replayJS.includes('L1900 70 C2030 70 2010 275 2075 275');+ const rightColumnPlanOK = replayJS.includes("plan: { x: 2075, y: 110, w: 420, h: 360 }") && replayJS.includes("x: 2075, y: 670, w: 420, h: 560") && replayJS.includes("x: 2075, y: 1320, w: 420, h: 360");+ const featuredMediaOK = replayJS.includes("x: 2075, y: 670, w: 420, h: 560") && replayJS.includes("x: 2075, y: 1320, w: 420, h: 360");+ const detailPanelOK = replayCSS.includes('width: min(620px, calc(100vw - 36px))') && replayCSS.includes('#detail-content { display: flex') && replayCSS.includes('overflow-y: auto') && replayJS.includes("event.target.closest('.detail-panel,.media-lightbox')");+ const mediaLightboxOK = html.includes('id="media-lightbox"') && ['openMode: \'image\'', "openMode: 'animation'", 'url.searchParams.delete(\'motion\')'].every((token) => replayJS.includes(token)) && replayCSS.includes('.media-lightbox.is-open');+ const fullPngContainOK = replayCSS.includes('.media-lightbox-frame img { display: block; width: auto; height: auto; max-width: 100%; max-height: 100%; min-width: 0; min-height: 0; object-fit: contain; }');+ console.log(` ${schemaOK ? '✅' : '❌'} poster-replay/v1 schema`);+ console.log(` ${stagesOK ? '✅' : '❌'} seven ordered creative stages`);+ console.log(` ${offlineOK ? '✅' : '❌'} offline file:// runtime`);+ console.log(` ${sourceOK ? '✅' : '❌'} source provenance on every stage`);+ console.log(` ${phaseNavOK ? '✅' : '❌'} three persistent phase controls`);+ console.log(` ${phaseIconsOK ? '✅' : '❌'} phase control icons`);+ console.log(` ${noDefaultDetailOK ? '✅' : '❌'} clean overview with no default detail`);+ console.log(` ${arrowSizingOK ? '✅' : '❌'} bounded flow-arrow markers`);+ console.log(` ${motionOK ? '✅' : '❌'} intro, ambient, and playback motion states`);+ console.log(` ${reducedMotionOK ? '✅' : '❌'} reduced-motion fallback`);+ console.log(` ${playbackPathOK ? '✅' : '❌'} playback path-to-stage mapping`);+ console.log(` ${ambientCadenceOK ? '✅' : '❌'} faster ambient and repair cadence`);+ console.log(` ${introTimingOK ? '✅' : '❌'} 4.7s intro with hidden detail panel`);+ console.log(` ${assetOverviewOK ? '✅' : '❌'} all-assets visual overview`);+ console.log(` ${planMatrixOK ? '✅' : '❌'} recorded-plan slot matrix fallback`);+ console.log(` ${scaledPhaseNavOK ? '✅' : '❌'} phase controls scale with the canvas world`);+ console.log(` ${largePhaseNavOK ? '✅' : '❌'} enlarged readable phase controls`);+ console.log(` ${assetStageOK ? '✅' : '❌'} compact Assets stage with Prompt summary`);+ console.log(` ${adaptiveAssetsOK ? '✅' : '❌'} adaptive single/full and multi 2x2 Assets previews`);+ console.log(` ${assetShowcaseOK ? '✅' : '❌'} 700ms Assets gallery showcase with 4-6s rest`);+ console.log(` ${feedbackLabelOK ? '✅' : '❌'} feedback label on green observation path`);+ console.log(` ${liveLayerAnimationOK ? '✅' : '❌'} live HTML layer animation`);+ console.log(` ${referencePlacementOK ? '✅' : '❌'} centered reference on a straight dashed connector`);+ console.log(` ${rightColumnPlanOK ? '✅' : '❌'} Design Plan aligned with the right output column`);+ console.log(` ${featuredMediaOK ? '✅' : '❌'} enlarged right-side output column`);+ console.log(` ${detailPanelOK ? '✅' : '❌'} wide independently scrolling detail panel`);+ console.log(` ${mediaLightboxOK ? '✅' : '❌'} image and animation lightbox behaviors`);+ console.log(` ${fullPngContainOK ? '✅' : '❌'} full uncropped PNG in image lightbox`);+ failed ||= !schemaOK || !stagesOK || !offlineOK || !sourceOK || !phaseNavOK || !phaseIconsOK || !noDefaultDetailOK || !arrowSizingOK || !motionOK || !reducedMotionOK || !playbackPathOK || !ambientCadenceOK || !introTimingOK || !assetOverviewOK || !planMatrixOK || !scaledPhaseNavOK || !largePhaseNavOK || !assetStageOK || !adaptiveAssetsOK || !assetShowcaseOK || !feedbackLabelOK || !liveLayerAnimationOK || !referencePlacementOK || !rightColumnPlanOK || !featuredMediaOK || !detailPanelOK || !mediaLightboxOK || !fullPngContainOK;++ const missing = data.stages.filter((stage) => /缺失|不完整|未生成/.test(stage.statusLabel));+ if (missing.length) console.log(` ⚠️ missing evidence is shown, not reconstructed: ${missing.map((stage) => stage.id).join(', ')}`);+}++if (failed) process.exit(1);+console.log(`\n✅ Replay contract passed: ${input}\n`);diff --git a/skills/editable-design/scripts/verify.mjs b/skills/editable-design/scripts/verify.mjsnew file mode 100755index 0000000..cd1f80b--- /dev/null+++ b/skills/editable-design/scripts/verify.mjs@@ -0,0 +1,782 @@+#!/usr/bin/env node+/**+ * verify.mjs —— 编辑器功能验证+ *+ * node verify.mjs <海报 index.html> [--timings]+ *+ * A 类断言(转换类):固化视觉零偏差。+ * B 类断言(编辑类):改完导出、重新加载后 computed style 与几何一致。+ * —— 编辑功能是「故意改变视觉」的,A 类断言对它们不适用。+ * B 类要防的是「改得动但导不出去」,尤其字体静默回落成系统字体。+ *+ * 退出码 0 = 全绿,1 = 有失败。+ */+import { writeFileSync, existsSync, unlinkSync } from 'node:fs';+import { dirname, join, resolve, basename } from 'node:path';+import { launch, open, probe, diff, pixelDiff, wireTemp } from './_browser.mjs';++const file = process.argv[2];+if (!file || !existsSync(resolve(file))) {+ console.error('用法: node verify.mjs <海报 index.html>');+ process.exit(2);+}+const src = resolve(file);+const dir = dirname(src);+const layersOutput = join(dir, 'layers.html');+const showTimings = process.argv.includes('--timings');+const timingStartedAt = Date.now();+let timingMarkedAt = timingStartedAt;+let timingPhase = '启动浏览器';+const timingRows = [];++const markTiming = (nextPhase) => {+ const now = Date.now();+ if (showTimings) timingRows.push({ phase: timingPhase, ms: now - timingMarkedAt });+ timingPhase = nextPhase;+ timingMarkedAt = now;+};++let fails = 0;+let verifiedLayersHTML = '';+const check = (name, ok, extra = '') => {+ if (!ok) fails++;+ console.log(` ${ok ? '✅' : '❌'} ${name}${extra ? ' ' + extra : ''}`);+};+const group = (t) => {+ markTiming(t);+ console.log(`\n【${t}】`);+};++/** 采集每个图层的 computed style 与几何,用于 B 类往返比对。+ * 不依赖编辑器注入的 class,因此导出物上同样可用。 */+const COLLECT = () => {+ const cv = document.querySelector('[data-canvas-width]') || document.querySelector('.poster-canvas');+ const c = cv.getBoundingClientRect();+ const scale = c.width / (+cv.dataset.canvasWidth || cv.offsetWidth);+ const out = {};+ for (const el of cv.querySelectorAll('[data-layer-id]')) {+ const nodes = [el, ...el.querySelectorAll('*')].filter((n) => !(n instanceof SVGElement));+ const r = el.getBoundingClientRect();+ out[el.dataset.layerId] = {+ left: +((r.left - c.left) / scale).toFixed(1),+ top: +((r.top - c.top) / scale).toFixed(1),+ width: +(r.width / scale).toFixed(1),+ height: +(r.height / scale).toFixed(1),+ fonts: nodes.map((n) => {+ const cs = getComputedStyle(n);+ return `${cs.fontSize}|${cs.fontFamily}`;+ }),+ widths: nodes.map((n) => +(n.getBoundingClientRect().width / scale).toFixed(1)),+ text: el.textContent.replace(/\s+/g, ' ').trim(),+ };+ }+ return out;+};++function compare(a, b) {+ const issues = [];+ for (const id of Object.keys(a)) {+ if (!b[id]) { issues.push(`${id} 在导出物中缺失`); continue; }+ const x = a[id], y = b[id];+ if (Math.abs(x.left - y.left) > 1 || Math.abs(x.top - y.top) > 1) {+ issues.push(`${id} 坐标漂移 ${x.left},${x.top} → ${y.left},${y.top}`);+ }+ if (Math.abs(x.width - y.width) > 1 || Math.abs(x.height - y.height) > 1) {+ issues.push(`${id} 尺寸漂移 ${x.width}×${x.height} → ${y.width}×${y.height}`);+ }+ if (x.text !== y.text) issues.push(`${id} 文本不一致`);+ if (x.fonts.join('#') !== y.fonts.join('#')) {+ const i = x.fonts.findIndex((v, k) => v !== y.fonts[k]);+ issues.push(`${id} 字体/字号不一致: "${x.fonts[i]}" → "${y.fonts[i] ?? '(缺)'}"`);+ }+ // 字体若静默回落成系统字体,computed family 可能不变但渲染宽度会变+ const wBad = x.widths.findIndex((v, k) => Math.abs(v - (y.widths[k] ?? 0)) > 1);+ if (wBad >= 0) issues.push(`${id} 渲染宽度不一致 ${x.widths[wBad]} → ${y.widths[wBad] ?? '(缺)'}(字体可能回落)`);+ }+ for (const id of Object.keys(b)) if (!a[id]) issues.push(`${id} 多出于导出物`);+ return issues;+}++const wired = wireTemp(src, '_hf_verify.html');+const browser = await launch();+try {+ /* ---------- A 类:固化零偏差 ---------- */+ group('A 类 · 固化视觉零偏差');+ const { page: p0 } = await open(browser, src);+ const before = await probe(p0);+ const { page, errors } = await open(browser, wired.file, { waitEditor: true });+ const afterBake = await probe(page);+ const dA = diff(before, afterBake, 1);+ check(`${dA.rows.length} 个图层坐标不变`, dA.ok, `最大偏差 ${dA.worst}px`);++ // 几何一致不等于视觉一致:上下文样式、背景、伪元素和绘制顺序+ // 发生变化时,图层框仍可能完全不动。所以固化类验收必须再过一道像素门。+ // 编辑器里的画布放在固定、可滚动的舞台中,直接截取超出视口的+ // DOM 可能被父层 overflow 裁掉。先导出一份未修改的 baked HTML,+ // 再在同尺寸视口中与原稿比像素,比对的仍然是 bake 结果。+ const bakedFile = join(dir, '_hf_verify_baked.html');+ writeFileSync(bakedFile, await page.evaluate(() => window.__layerEditor.fullHTML()));+ const canvasSize = await p0.evaluate(() => {+ const cv = document.querySelector('[data-canvas-width]') || document.querySelector('.poster-canvas');+ return {+ width: Math.ceil(+cv.dataset.canvasWidth || cv.offsetWidth),+ height: Math.ceil(+cv.dataset.canvasHeight || cv.offsetHeight),+ };+ });+ const pixelViewport = {+ width: Math.max(1600, Math.min(8192, canvasSize.width + 20)),+ height: Math.max(1200, Math.min(8192, canvasSize.height + 20)),+ deviceScaleFactor: 1,+ };+ await p0.setViewport(pixelViewport);+ const { page: pBaked, errors: eBaked } = await open(browser, bakedFile, pixelViewport);+ const pixels = await pixelDiff(+ p0, '[data-canvas-width],.poster-canvas',+ pBaked, '[data-canvas-width],.poster-canvas',+ );+ // 少量 mix-blend-mode / 阴影在被提升进新的 stacking context 后会产生+ // 亚像素级合成差异;同时约束“变化像素比例”和“平均通道差”,可容纳+ // 这种不可见噪声,又会拦住丢背景、错层、去旋转等真实视觉漂移。+ const pixelOK = eBaked.length === 0 && pixels.ok+ && pixels.changedRatio <= 0.005 && pixels.meanAbs <= 0.05;+ check('画布像素级无可见漂移', pixelOK, pixels.reason+ || `变化 ${(pixels.changedRatio * 100).toFixed(3)}%,平均通道差 ${pixels.meanAbs.toFixed(4)}`);+ await pBaked.close();+ try { unlinkSync(bakedFile); } catch {}++ const scale = await page.evaluate(() => window.__layerEditor.state.scale);+ const at = (sel) => page.evaluate((s) => {+ const r = document.querySelector(s).getBoundingClientRect();+ return { x: r.left + r.width / 2, y: r.top + r.height / 2 };+ }, sel);+ // puppeteer 的 clickCount:2 只改参数、不真的按两次,detail 恒为 1,+ // 浏览器不会合成 dblclick。必须手动发两轮 down/up。+ const dbl = async (sel) => {+ const { x, y } = await at(sel);+ await page.mouse.move(x, y);+ await page.mouse.down(); await page.mouse.up();+ await page.mouse.down({ clickCount: 2 }); await page.mouse.up({ clickCount: 2 });+ await new Promise((r) => setTimeout(r, 180));+ };+ const layerIds = await page.evaluate(() => window.__layerEditor.layers().map((l) => l.id));+ const groupInfo = await page.evaluate(() => [...window.__layerEditor.state.groups.values()].map((group) => ({+ id: group.id,+ label: group.label,+ members: group.memberIds,+ })));+ const explodeExpectation = await page.evaluate(() => {+ const layers = window.__layerEditor.layers();+ const groups = [...window.__layerEditor.state.groups.values()];+ const grouped = new Set(groups.flatMap((group) => group.memberIds));+ const primary = groups.length + layers.filter((layer) => !grouped.has(layer.id)).length;+ const textSupplements = primary < 5 ? layers.filter(({ id, el }) => {+ if (!grouped.has(id)) return false;+ const role = (el.dataset.explodeRole || 'copy').trim();+ if (['surface', 'image', 'icon', 'decoration'].includes(role)) return false;+ return Boolean((el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim());+ }).length : 0;+ return { primary, textSupplements, units: primary + textSupplements + 2 };+ });+ const expectedExplodedUnits = explodeExpectation.units;+ const first = await page.evaluate(() => {+ const layers = window.__layerEditor.layers();+ return layers.find(({ el }) =>+ el.classList.contains('hf-slot') || el.querySelector('.hf-slot'))?.id+ || layers[0]?.id;+ });+ const sel1 = `[data-layer-id="${first}"]`;+ const geomOf = (id) => page.evaluate((i) => {+ const el = document.querySelector(`[data-layer-id="${i}"]`);+ return el ? { left: parseFloat(el.style.left), top: parseFloat(el.style.top) } : null;+ }, id);+ const boxOf = (id) => page.evaluate((i) => {+ const el = document.querySelector(`[data-layer-id="${i}"]`);+ if (!el) return null;+ const r = el.getBoundingClientRect();+ const scale = window.__layerEditor.state.scale;+ return {+ left: parseFloat(el.style.left), top: parseFloat(el.style.top),+ width: r.width / scale, height: r.height / scale,+ widthLocked: el.dataset.hfWidthLocked === '1',+ heightLocked: el.dataset.hfHeightLocked === '1',+ };+ }, id);++ /* ---------- 拖拽 ---------- */+ group('拖拽');+ const g0 = await geomOf(first);+ const pt = await at(sel1);+ await page.mouse.move(pt.x, pt.y);+ await page.mouse.down();+ await page.mouse.move(pt.x + 60, pt.y + 40, { steps: 12 });+ await page.mouse.up();+ const g1 = await geomOf(first);+ const moved = Math.abs(g1.left - g0.left) > 20 && Math.abs(g1.top - g0.top) > 10;+ check('位移按画布缩放换算', moved,+ `屏幕 +60,+40 → 画布 +${(g1.left - g0.left).toFixed(1)},+${(g1.top - g0.top).toFixed(1)}(缩放 ${Math.round(scale * 100)}%,含吸附修正)`);+ check('拖拽未误选文字', await page.evaluate(() => getSelection().toString() === ''));+ await page.evaluate(() => window.__layerEditor.undo());+ const g2 = await geomOf(first);+ check('撤销精确复位', Math.abs(g2.left - g0.left) < 0.5 && Math.abs(g2.top - g0.top) < 0.5);+ const release0 = await geomOf(first);+ await page.evaluate((id) => {+ const el = window.__layerEditor.layers().find((item) => item.id === id).el;+ const rect = el.getBoundingClientRect();+ const init = { bubbles: true, pointerId: 97, pointerType: 'mouse', isPrimary: true };+ el.dispatchEvent(new PointerEvent('pointerdown', {+ ...init, button: 0, buttons: 1, clientX: rect.left + 4, clientY: rect.top + 4,+ }));+ el.dispatchEvent(new PointerEvent('pointermove', {+ ...init, button: -1, buttons: 0, clientX: rect.left + 90, clientY: rect.top + 60,+ }));+ window.dispatchEvent(new PointerEvent('pointerup', {+ ...init, button: 0, buttons: 0, clientX: rect.left + 90, clientY: rect.top + 60,+ }));+ }, first);+ const release1 = await geomOf(first);+ check('鼠标已松开时不会残留拖拽', Math.abs(release1.left - release0.left) < 0.5+ && Math.abs(release1.top - release0.top) < 0.5);+ const escape0 = await geomOf(first);+ const escapeAt = await at(`[data-layer-id="${first}"]`);+ await page.mouse.move(escapeAt.x, escapeAt.y);+ await page.mouse.down();+ await page.mouse.move(escapeAt.x + 42, escapeAt.y + 24, { steps: 3 });+ const escapeMoved = await geomOf(first);+ await page.keyboard.press('Escape');+ await page.mouse.up();+ const escape1 = await geomOf(first);+ check('Esc 可取消进行中的拖拽', Math.abs(escapeMoved.left - escape0.left) > 5+ && Math.abs(escape1.left - escape0.left) < 0.5+ && Math.abs(escape1.top - escape0.top) < 0.5);++ /* ---------- 宽高缩放 ---------- */+ group('宽高缩放');+ await page.evaluate((id) => {+ const layer = window.__layerEditor.layers().find((item) => item.id === id);+ window.__layerEditor.select(layer.el);+ }, first);+ check('选中后显示八个缩放手柄', await page.evaluate(() =>+ document.querySelectorAll('.hf-resize-handle').length === 8+ && !document.querySelector('.hf-resize-overlay').hidden));+ check('缩放手柄具有宽松点击热区', await page.evaluate(() =>+ [...document.querySelectorAll('.hf-resize-handle')].every((handle) => {+ const rect = handle.getBoundingClientRect();+ return rect.width >= 28 && rect.height >= 28;+ })));+ const size0 = await boxOf(first);+ const dragHandle = async (selector, dx, dy) => {+ const handle = await page.$(selector);+ const box = await handle?.boundingBox();+ if (!box) return false;+ const x = box.x + box.width / 2;+ const y = box.y + box.height / 2;+ await page.mouse.move(x, y);+ await page.mouse.down();+ await page.mouse.move(x + dx, y + dy, { steps: 10 });+ await page.mouse.up();+ return true;+ };+ const eastReady = await dragHandle('.hf-resize-handle.e', 52, 0);+ const sizeW = await boxOf(first);+ check('左右手柄只改变宽度', eastReady+ && sizeW.width > size0.width + 20+ && Math.abs(sizeW.height - size0.height) < 0.5+ && sizeW.widthLocked && !sizeW.heightLocked,+ `${size0.width.toFixed(1)}×${size0.height.toFixed(1)} → ${sizeW.width.toFixed(1)}×${sizeW.height.toFixed(1)}`);+ const southReady = await dragHandle('.hf-resize-handle.s', 0, 38);+ const sizeWH = await boxOf(first);+ check('上下手柄只改变高度', southReady+ && sizeWH.height > sizeW.height + 15+ && Math.abs(sizeWH.width - sizeW.width) < 0.5+ && sizeWH.widthLocked && sizeWH.heightLocked,+ `${sizeW.width.toFixed(1)}×${sizeW.height.toFixed(1)} → ${sizeWH.width.toFixed(1)}×${sizeWH.height.toFixed(1)}`);+ const resizedSnapshot = await page.evaluate((id) =>+ window.__layerEditor.snapshot().layers.find((layer) => layer.id === id), first);+ check('草稿快照保留手动宽高', resizedSnapshot?.manualWidth === true+ && resizedSnapshot?.manualHeight === true && !!resizedSnapshot?.height);+ const lockedWidth = sizeWH.width;+ await page.evaluate((id) => {+ const layer = window.__layerEditor.layers().find((item) => item.id === id);+ window.__layerEditor.scaleFont(layer.el, 1.08);+ }, first);+ const sizeAfterFont = await boxOf(first);+ check('手动宽度不被文字或字号自动撑回', Math.abs(sizeAfterFont.width - lockedWidth) < 0.5,+ `${lockedWidth.toFixed(1)} → ${sizeAfterFont.width.toFixed(1)}`);+ await page.evaluate(() => {+ window.__layerEditor.undo();+ window.__layerEditor.undo();+ window.__layerEditor.undo();+ });+ const sizeBack = await boxOf(first);+ check('撤销恢复原始宽高与自动适配状态', Math.abs(sizeBack.width - size0.width) < 0.5+ && Math.abs(sizeBack.height - size0.height) < 0.5+ && !sizeBack.widthLocked && !sizeBack.heightLocked,+ `${sizeBack.width.toFixed(1)}×${sizeBack.height.toFixed(1)}`);+ const resizeEscape0 = await boxOf(first);+ const seHandle = await page.$('.hf-resize-handle.se');+ const seBox = await seHandle?.boundingBox();+ if (seBox) {+ const x = seBox.x + seBox.width / 2;+ const y = seBox.y + seBox.height / 2;+ await page.mouse.move(x, y);+ await page.mouse.down();+ await page.mouse.move(x + 44, y + 32, { steps: 3 });+ const resizeEscapeMoved = await boxOf(first);+ await page.keyboard.press('Escape');+ await page.mouse.up();+ const resizeEscape1 = await boxOf(first);+ check('Esc 可取消进行中的缩放', Math.abs(resizeEscapeMoved.width - resizeEscape0.width) > 5+ && Math.abs(resizeEscape1.width - resizeEscape0.width) < 1+ && Math.abs(resizeEscape1.height - resizeEscape0.height) < 1);+ } else {+ check('Esc 可取消进行中的缩放', false, '未找到右下角手柄');+ }++ /* ---------- 文本编辑 ---------- */+ group('文本编辑');+ const slotSel = await page.evaluate((id) => {+ const layer = document.querySelector(`[data-layer-id="${id}"]`);+ const slot = layer.classList.contains('hf-slot') ? layer : layer.querySelector('.hf-slot');+ if (!slot) return null;+ slot.setAttribute('data-hf-probe', '1');+ return '[data-hf-probe]';+ }, first);+ if (!slotSel) {+ check('图层内找到文本槽', false, `${first} 无文本槽`);+ } else {+ const origText = await page.evaluate((s) => document.querySelector(s).textContent, slotSel);+ await dbl(slotSel);+ check('双击进入编辑态', await page.evaluate(() => !!document.querySelector('.hf-editing')));+ check('已设为 plaintext-only',+ await page.evaluate(() => document.querySelector('.hf-editing')?.getAttribute('contenteditable') === 'plaintext-only'));+ check('内容已全选', await page.evaluate((t) => getSelection().toString().trim() === t.trim(), origText));++ const posBefore = await geomOf(first);+ await page.keyboard.press('ArrowRight');+ await page.keyboard.press('ArrowDown');+ const posAfter = await geomOf(first);+ check('编辑态方向键不挪图层', posBefore.left === posAfter.left && posBefore.top === posAfter.top);++ await page.keyboard.press('Escape');+ await new Promise((r) => setTimeout(r, 120));+ check('Esc 回滚原文', await page.evaluate((s, t) => document.querySelector(s).textContent === t, slotSel, origText));++ await dbl(slotSel);+ await page.evaluate((s) => {+ const r = document.createRange();+ r.selectNodeContents(document.querySelector(s));+ const g = getSelection(); g.removeAllRanges(); g.addRange(r);+ }, slotSel);+ await page.keyboard.type('验证文本ABC');+ await page.keyboard.press('Enter');+ await new Promise((r) => setTimeout(r, 200));+ check('Enter 提交改动', await page.evaluate((s) => document.querySelector(s).textContent === '验证文本ABC', slotSel));+ await page.evaluate(() => window.__layerEditor.undo());+ check('⌘Z 还原文字', await page.evaluate((s, t) => document.querySelector(s).textContent === t, slotSel, origText));+ }++ /* ---------- 多字号结构安全 ---------- */+ const multi = await page.evaluate(() => {+ for (const l of window.__layerEditor.layers()) {+ const slots = [...l.el.querySelectorAll('.hf-slot')];+ if (slots.length >= 2) {+ const sizes = new Set(slots.map((s) => getComputedStyle(s).fontSize));+ if (sizes.size >= 2) {+ slots[0].parentElement.setAttribute('data-hf-multi', '1');+ return { id: l.id, n: slots.length };+ }+ }+ }+ return null;+ });+ if (multi) {+ group(`结构安全 · ${multi.id}(多字号拼排)`);+ const structBefore = await page.evaluate(() => {+ const box = document.querySelector('[data-hf-multi]');+ return [...box.children].map((c) => `${c.tagName}.${(c.className || '').replace(/hf-\S+/g, '').trim()}`).join(',');+ });+ const target = await page.evaluate(() => {+ const box = document.querySelector('[data-hf-multi]');+ const slot = box.querySelector('.hf-slot');+ slot.setAttribute('data-hf-probe2', '1');+ return { fs: getComputedStyle(slot).fontSize, color: getComputedStyle(slot).color };+ });+ await dbl('[data-hf-probe2]');+ await page.keyboard.type('99');+ await page.keyboard.press('Enter');+ await new Promise((r) => setTimeout(r, 200));+ const structAfter = await page.evaluate(() => {+ const box = document.querySelector('[data-hf-multi]');+ const slot = box.querySelector('[data-hf-probe2]');+ return {+ children: [...box.children].map((c) => `${c.tagName}.${(c.className || '').replace(/hf-\S+/g, '').trim()}`).join(','),+ text: slot.textContent,+ fs: getComputedStyle(slot).fontSize,+ color: getComputedStyle(slot).color,+ };+ });+ check('兄弟 span 结构未被破坏', structBefore === structAfter.children, structAfter.children);+ check('文字已改', structAfter.text === '99');+ check('字号未变', structAfter.fs === target.fs, structAfter.fs);+ check('颜色未变', structAfter.color === target.color);+ await page.evaluate(() => window.__layerEditor.undo());+ }++ /* ---------- 字号 ---------- */+ group('字号');+ const fsBefore = await page.evaluate((s) => getComputedStyle(document.querySelector(s)).fontSize, slotSel || sel1);+ await page.evaluate((id) => {+ const l = window.__layerEditor.layers().find((x) => x.id === id);+ window.__layerEditor.select(l.el);+ window.__layerEditor.scaleFont(l.el, 1.08);+ }, first);+ await new Promise((r) => setTimeout(r, 120));+ const fsAfter = await page.evaluate((s) => getComputedStyle(document.querySelector(s)).fontSize, slotSel || sel1);+ check('A+ 放大字号', parseFloat(fsAfter) > parseFloat(fsBefore), `${fsBefore} → ${fsAfter}`);+ await page.evaluate(() => window.__layerEditor.undo());+ const fsBack = await page.evaluate((s) => getComputedStyle(document.querySelector(s)).fontSize, slotSel || sel1);+ check('撤销恢复字号', fsBack === fsBefore, fsBack);++ /* ---------- 字体 ---------- */+ group('字体');+ const opts = await page.evaluate(() => window.__layerEditor.fontOptions());+ check('从 :root 解析出字体族', opts.length > 0, opts.map((o) => o.label).join(' / ') || '(无)');+ let fontChanged = false;+ if (opts.length > 1) {+ const ffBefore = await page.evaluate((s) => getComputedStyle(document.querySelector(s)).fontFamily, slotSel || sel1);+ // 选一个与当前不同的字体族+ for (const o of opts) {+ await page.evaluate((id, v) => {+ const l = window.__layerEditor.layers().find((x) => x.id === id);+ window.__layerEditor.setFont(l.el, v);+ }, first, o.value);+ await new Promise((r) => setTimeout(r, 120));+ const now = await page.evaluate((s) => getComputedStyle(document.querySelector(s)).fontFamily, slotSel || sel1);+ if (now !== ffBefore) { fontChanged = true; break; }+ await page.evaluate(() => window.__layerEditor.undo());+ }+ check('切换字体生效', fontChanged);+ } else if (opts.length === 1) {+ check('单一字体栈无需切换', true, opts[0].label);+ }++ /* ---------- 删除图层 ---------- */+ group('删除图层');+ const victim = layerIds.find((id) => id !== first && id !== 'hero_photo') || layerIds[layerIds.length - 1];+ const othersBefore = await page.evaluate(COLLECT);+ await page.evaluate((id) => {+ const l = window.__layerEditor.layers().find((x) => x.id === id);+ window.__layerEditor.removeLayer(l.el);+ }, victim);+ await new Promise((r) => setTimeout(r, 120));+ check(`${victim} 已从 DOM 移除`, await page.evaluate((id) => !document.querySelector(`[data-layer-id="${id}"]`), victim));+ const othersAfter = await page.evaluate(COLLECT);+ const untouched = Object.keys(othersAfter).every((id) =>+ Math.abs(othersAfter[id].left - othersBefore[id].left) < 0.5+ && Math.abs(othersAfter[id].top - othersBefore[id].top) < 0.5);+ check('其他图层坐标不受影响', untouched);+ await page.evaluate(() => window.__layerEditor.undo());+ await new Promise((r) => setTimeout(r, 120));+ check('撤销恢复图层', await page.evaluate((id) => !!document.querySelector(`[data-layer-id="${id}"]`), victim));+ const restored = await page.evaluate(COLLECT);+ check('恢复后位置正确', Object.keys(othersBefore).every((id) =>+ restored[id] && Math.abs(restored[id].left - othersBefore[id].left) < 0.5));++ /* ---------- 拆解视图 ---------- */+ group('拆解视图');+ const composedBeforeSpread = await page.evaluate(COLLECT);+ const composedScreenHeight = await page.evaluate(() =>+ document.querySelector('.hf-canvas').getBoundingClientRect().height);+ const enterMotion = await page.evaluate(async () => {+ void window.__layerEditor.setExploded(true);+ await new Promise((r) => setTimeout(r, 180));+ return {+ running: document.getAnimations().filter((a) => a.playState === 'running').length,+ scanning: document.querySelector('.hf-exploded-scan-beam')?.getAnimations()+ .some((a) => a.playState === 'running') || false,+ labelsVisible: [...document.querySelectorAll('.hf-exploded-label')].some((label) =>+ Number.parseFloat(getComputedStyle(label).opacity) > .05),+ reduced: matchMedia('(prefers-reduced-motion: reduce)').matches+ || new URLSearchParams(location.search).get('motion') === '0',+ };+ });+ check('拆解前先执行扫描特效', enterMotion.reduced || enterMotion.scanning,+ enterMotion.reduced ? '已遵循 reduced-motion' : '扫描束运行中');+ check('进入时执行分层散开动画', enterMotion.reduced || enterMotion.running > 0,+ enterMotion.reduced ? '已遵循 reduced-motion' : `${enterMotion.running} 个动画运行中`);+ check('扫描与散开期间不放大模块标签', enterMotion.reduced || !enterMotion.labelsVisible,+ enterMotion.reduced ? '已遵循 reduced-motion' : '运动阶段标签保持隐藏');+ await page.waitForFunction(() => !window.__layerEditor.state.transitioning, { timeout: 20000 });+ await new Promise((r) => setTimeout(r, 220));+ const liveSpread = await page.evaluate(() => ({+ active: document.body.classList.contains('hf-exploded-on'),+ board: !!document.querySelector('.hf-exploded-board'),+ scanHeight: document.querySelector('.hf-exploded-scan')?.getBoundingClientRect().height || 0,+ boardHeight: document.querySelector('.hf-exploded-board')?.getBoundingClientRect().height || 0,+ laneCount: window.__layerEditor.state.spread?.laneCount || 0,+ units: document.querySelectorAll('.hf-exploded-board .hf-exploded-item').length,+ layers: document.querySelectorAll('.hf-exploded-board [data-exploded-layer]').length,+ uniqueLayers: new Set([...document.querySelectorAll('.hf-exploded-board [data-exploded-layer]')]+ .map((node) => node.dataset.explodedLayer)).size,+ primaryContent: Number(document.querySelector('.hf-exploded-board')?.dataset.explodedPrimaryCount || 0),+ textSupplements: document.querySelectorAll('.hf-exploded-item[data-exploded-text-supplement]').length,+ bases: document.querySelectorAll('.hf-exploded-base').length,+ overviews: document.querySelectorAll('.hf-exploded-item[data-exploded-overview]').length,+ backgrounds: document.querySelectorAll('.hf-exploded-item[data-exploded-background]').length,+ groups: document.querySelectorAll('.hf-exploded-item[data-exploded-group]').length,+ gallery: (() => {+ const board = document.querySelector('.hf-exploded-board');+ const width = parseFloat(board?.style.width) || 1;+ const height = parseFloat(board?.style.height) || 1;+ const items = [...document.querySelectorAll('.hf-exploded-item')].map((item) => ({+ left: parseFloat(item.style.left) || 0,+ top: parseFloat(item.style.top) || 0,+ width: parseFloat(item.style.width) || 0,+ height: parseFloat(item.style.height) || 0,+ }));+ const minX = Math.min(...items.map((item) => item.left));+ const maxX = Math.max(...items.map((item) => item.left + item.width));+ const special = [...document.querySelectorAll('[data-exploded-overview],[data-exploded-background]')]+ .map((item) => (parseFloat(item.style.height) || 0) / height);+ return {+ span: (maxX - minX) / width,+ centerOccupied: items.some((item) => item.left < width * .58 && item.left + item.width > width * .42),+ specialMin: Math.min(...special), specialMax: Math.max(...special),+ };+ })(),+ labelsVisible: [...document.querySelectorAll('.hf-exploded-label')].some((label) =>+ Number.parseFloat(getComputedStyle(label).opacity) > .05),+ labelsNamed: [...document.querySelectorAll('.hf-exploded-item[data-exploded-group]')].every((item) =>+ Boolean(item.title?.trim())),+ hasDrilldownAPI: typeof window.__layerEditor.openExplodedGroup === 'function',+ level: document.querySelector('.hf-exploded-board')?.dataset.explodedLevel,+ theme: document.querySelector('.hf-exploded-board')?.dataset.explodedTheme,+ expectedTheme: (() => {+ const cs = getComputedStyle(document.querySelector('.hf-canvas'));+ const parse = (raw) => {+ const rgba = String(raw).match(/rgba?\((\d+(?:\.\d+)?)[, ]+(\d+(?:\.\d+)?)[, ]+(\d+(?:\.\d+)?)(?:\s*[,/]\s*(\d*(?:\.\d+)?))?/i);+ if (rgba) return { rgb: rgba.slice(1, 4).map(Number), alpha: rgba[4] === undefined ? 1 : Number(rgba[4]) };+ const hex = String(raw).match(/#([0-9a-f]{6}|[0-9a-f]{3})(?![0-9a-f])/i);+ if (!hex) return null;+ const v = hex[1].length === 3 ? [...hex[1]].map((c) => c + c).join('') : hex[1];+ return { rgb: [0, 2, 4].map((i) => parseInt(v.slice(i, i + 2), 16)), alpha: 1 };+ };+ let color = parse(cs.backgroundColor);+ if (!color || color.alpha <= .25) {+ const tokens = String(cs.backgroundImage).match(/#[0-9a-f]{3,8}|rgba?\([^)]*\)/ig) || [];+ color = tokens.map(parse).find((entry) => entry && entry.alpha > .65) || null;+ }+ const rgb = color?.rgb || [244, 241, 232];+ const linear = rgb.map((n) => {+ const c = n / 255;+ return c <= .03928 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4;+ });+ return linear[0] * .2126 + linear[1] * .7152 + linear[2] * .0722 > .52 ? 'light' : 'dark';+ })(),+ sourceVisible: getComputedStyle(document.querySelector('.hf-stage > .hf-canvas')).display !== 'none',+ }));+ check('可切换到横向拆解画布', liveSpread.active && liveSpread.board && !liveSpread.sourceVisible);+ check('全部内容叶子均归入一级拆解', liveSpread.uniqueLayers === layerIds.length,+ `${liveSpread.uniqueLayers}/${layerIds.length} 个唯一叶子,${liveSpread.layers} 次呈现`);+ check('完整总览与背景均作为普通组件', liveSpread.overviews === 1+ && liveSpread.backgrounds === 1 && liveSpread.bases === 0,+ `总览 ${liveSpread.overviews}、背景 ${liveSpread.backgrounds}、固定基底 ${liveSpread.bases}`);+ check('组件画廊数量完整', liveSpread.units === expectedExplodedUnits,+ `${liveSpread.units}/${expectedExplodedUnits}`);+ check('少组件时补入分组文字叶子', liveSpread.primaryContent === explodeExpectation.primary+ && liveSpread.textSupplements === explodeExpectation.textSupplements,+ `一级组件 ${liveSpread.primaryContent},文字补充 ${liveSpread.textSupplements}`);+ check('拆解舞台跟随海报明暗主题', liveSpread.theme === liveSpread.expectedTheme,+ `${liveSpread.theme}/${liveSpread.expectedTheme}`);+ check('一级拆解保持分组兼容', liveSpread.level === '1' && liveSpread.groups === groupInfo.length,+ `${liveSpread.groups}/${groupInfo.length} 个模块`);+ check('拆解视图不提供第二级叶子钻取', !liveSpread.hasDrilldownAPI,+ '仅保留一级内容模块');+ check('静止拆解稿不叠加冗余模块标签', !liveSpread.labelsVisible,+ '名称仅在明确交互时提示');+ check('模块仍保留可发现的语义名称', !groupInfo.length || liveSpread.labelsNamed,+ groupInfo.length ? `${liveSpread.groups} 个模块均有名称` : '无一级模块标签');+ const originRatio = liveSpread.scanHeight / composedScreenHeight;+ check('扫描原点保持完整成稿的可读尺度', originRatio >= 0.68,+ `扫描态为编辑态高度的 ${(originRatio * 100).toFixed(1)}%`);+ check('终态铺满舞台且中央无大块保留区', liveSpread.laneCount >= 2+ && liveSpread.gallery.centerOccupied && liveSpread.gallery.span >= .72,+ `${liveSpread.laneCount} 列,横向覆盖 ${(liveSpread.gallery.span * 100).toFixed(1)}%`);+ check('总览与背景均为小型组件', liveSpread.gallery.specialMin >= .08+ && liveSpread.gallery.specialMax <= .38,+ `高度占舞台 ${(liveSpread.gallery.specialMin * 100).toFixed(1)}%–${(liveSpread.gallery.specialMax * 100).toFixed(1)}%`);++ if (groupInfo.length) {+ await page.hover('.hf-exploded-item[data-exploded-group]');+ await new Promise((r) => setTimeout(r, 220));+ check('悬停模块时才显示名称提示', await page.evaluate(() =>+ Number.parseFloat(getComputedStyle(document.querySelector('.hf-exploded-item[data-exploded-group] .hf-exploded-label')).opacity) > .9));+ await page.mouse.move(0, 0);+ await page.click('.hf-exploded-item[data-exploded-group]');+ await new Promise((r) => setTimeout(r, 120));+ check('点击内容模块不会进入细粒度第二层', await page.evaluate(() =>+ document.querySelector('.hf-exploded-board')?.dataset.explodedLevel === '1'+ && !document.querySelector('.hf-exploded-nav')));+ }++ const spreadHTML = await page.evaluate(() => window.__layerEditor.explodedHTML());+ verifiedLayersHTML = spreadHTML;+ check('拆解导出物无编辑器依赖', !/layer-editor|class="hf-(bar|panel|modal|toast)/.test(spreadHTML));+ const spreadFile = join(dir, '_hf_verify_layers.html');+ writeFileSync(spreadFile, spreadHTML);+ const { page: pSpread, errors: eSpread } = await open(browser, spreadFile, { width: 1600, height: 1000 });+ await pSpread.waitForSelector('html[data-hf-exploded-ready]', { timeout: 20000 });+ const spreadAudit = await pSpread.evaluate(() => ({+ units: document.querySelectorAll('.hf-exploded-board .hf-exploded-item').length,+ layers: document.querySelectorAll('[data-exploded-layer]').length,+ uniqueLayers: new Set([...document.querySelectorAll('[data-exploded-layer]')]+ .map((node) => node.dataset.explodedLayer)).size,+ primaryContent: Number(document.querySelector('.hf-exploded-board')?.dataset.explodedPrimaryCount || 0),+ textSupplements: document.querySelectorAll('.hf-exploded-item[data-exploded-text-supplement]').length,+ bases: document.querySelectorAll('.hf-exploded-base').length,+ overviews: document.querySelectorAll('[data-exploded-overview]').length,+ backgrounds: document.querySelectorAll('[data-exploded-background]').length,+ groups: document.querySelectorAll('.hf-exploded-item[data-exploded-group]').length,+ level: document.querySelector('.hf-exploded-board')?.dataset.explodedLevel,+ drilldownUI: !!document.querySelector('.hf-exploded-nav'),+ centerOccupied: (() => {+ const board = document.querySelector('.hf-exploded-board');+ const width = parseFloat(board?.style.width) || 1;+ return [...document.querySelectorAll('.hf-exploded-item')].some((item) => {+ const left = parseFloat(item.style.left) || 0;+ const itemWidth = parseFloat(item.style.width) || 0;+ return left < width * .58 && left + itemWidth > width * .42;+ });+ })(),+ replay: !!document.querySelector('.hf-exploded-replay'),+ motion: document.documentElement.dataset.hfMotion,+ overflow: document.documentElement.scrollWidth > innerWidth + 1+ || document.documentElement.scrollHeight > innerHeight + 1,+ }));+ check('拆解稿可独立渲染无报错', eSpread.length === 0, eSpread.join('; '));+ check('拆解稿自适应且图层齐全', spreadAudit.uniqueLayers === layerIds.length && !spreadAudit.overflow,+ `${spreadAudit.uniqueLayers}/${layerIds.length} 个唯一叶子,${spreadAudit.layers} 次呈现`);+ check('独立拆解稿不保留中央大基底', spreadAudit.bases === 0+ && spreadAudit.centerOccupied, `${spreadAudit.bases} 个固定基底`);+ check('独立稿含完整总览与背景组件', spreadAudit.overviews === 1+ && spreadAudit.backgrounds === 1 && spreadAudit.units === expectedExplodedUnits,+ `${spreadAudit.units}/${expectedExplodedUnits} 个组件`);+ check('独立稿保留少组件文字补充', spreadAudit.primaryContent === explodeExpectation.primary+ && spreadAudit.textSupplements === explodeExpectation.textSupplements,+ `一级组件 ${spreadAudit.primaryContent},文字补充 ${spreadAudit.textSupplements}`);+ check('拆解稿保留一级模块语义', spreadAudit.groups === groupInfo.length,+ `${spreadAudit.groups}/${groupInfo.length} 个模块`);+ check('独立拆解稿只有一级内容层', spreadAudit.level === '1' && !spreadAudit.drilldownUI,+ `level ${spreadAudit.level}`);+ check('拆解稿带自动播放与重播入口', spreadAudit.replay+ && ['played', 'reduced'].includes(spreadAudit.motion), spreadAudit.motion || '未播放');+ const replayMotion = await pSpread.evaluate(async () => {+ if (document.documentElement.dataset.hfMotion === 'reduced') return { any: true, scan: true };+ document.querySelector('.hf-exploded-replay').click();+ await new Promise((r) => setTimeout(r, 160));+ return {+ any: document.getAnimations().some((a) => a.playState === 'running'),+ scan: document.querySelector('.hf-exploded-scan-beam')?.getAnimations()+ .some((a) => a.playState === 'running') || false,+ };+ });+ check('重播按钮可重新触发扫描与拆解', replayMotion.any && replayMotion.scan);+ await pSpread.close();+ try { unlinkSync(spreadFile); } catch {}++ const exitMotion = await page.evaluate(async () => {+ void window.__layerEditor.setExploded(false);+ await new Promise((r) => setTimeout(r, 150));+ return {+ running: document.getAnimations().filter((a) => a.playState === 'running').length,+ reduced: matchMedia('(prefers-reduced-motion: reduce)').matches,+ };+ });+ check('返回时执行反向合拢动画', exitMotion.reduced || exitMotion.running > 0,+ exitMotion.reduced ? '已遵循 reduced-motion' : `${exitMotion.running} 个动画运行中`);+ await page.waitForFunction(() => !window.__layerEditor.state.transitioning, { timeout: 20000 });+ const composedAfterSpread = await page.evaluate(COLLECT);+ check('返回编辑后原布局不变', compare(composedBeforeSpread, composedAfterSpread).length === 0);++ /* ---------- B 类:导出往返一致 ---------- */+ group('B 类 · 导出往返一致');+ const stateBefore = await page.evaluate(COLLECT);+ const html = await page.evaluate(() => window.__layerEditor.fullHTML());+ check('导出物无编辑器残留', !/hf-|layer-editor/.test(html));+ const outFile = join(dir, '_hf_verify_out.html');+ writeFileSync(outFile, html);+ const { page: pOut, errors: eOut } = await open(browser, outFile);+ const stateAfter = await pOut.evaluate(COLLECT);+ const issues = compare(stateBefore, stateAfter);+ check('导出物可独立渲染无报错', eOut.length === 0, eOut.join('; '));+ check('坐标 / 字号 / 字体 / 渲染宽度全部一致', issues.length === 0, issues.slice(0, 4).join(' | '));+ try { unlinkSync(outFile); } catch {}++ /* ---------- 草稿 ---------- */+ group('草稿(localStorage)');+ await page.evaluate((id) => {+ const l = window.__layerEditor.layers().find((x) => x.id === id);+ l.el.style.left = '777px';+ l.el.style.top = '333px';+ l.el.style.width = `${parseFloat(l.el.style.width) + 33}px`;+ l.el.style.height = `${parseFloat(l.el.style.height) + 17}px`;+ l.el.dataset.hfWidthLocked = '1';+ l.el.dataset.hfHeightLocked = '1';+ window.__layerEditor.state.removed.length = 0;+ }, first);+ await page.evaluate(() => window.__layerEditor.snapshot());+ await page.evaluate((id) => {+ // 走真实路径:模拟一次方向键触发 touch() 的草稿保存+ const l = window.__layerEditor.layers().find((x) => x.id === id);+ window.__layerEditor.select(l.el);+ }, first);+ await page.keyboard.press('ArrowRight');+ await new Promise((r) => setTimeout(r, 800));+ const draftRaw = await page.evaluate(() => {+ const prefix = 'hf-draft:' + location.pathname;+ const key = Object.keys(localStorage).find((candidate) =>+ candidate === prefix || candidate.startsWith(prefix + ':'));+ return key ? localStorage.getItem(key) : null;+ });+ check('草稿已写入 localStorage', !!draftRaw, draftRaw ? `${(draftRaw.length / 1024).toFixed(1)}KB` : '');++ const expect = await boxOf(first);+ await page.reload({ waitUntil: 'networkidle0' });+ await page.waitForSelector('html[data-hf-ready]', { timeout: 20000 });+ await new Promise((r) => setTimeout(r, 400));+ const afterReload = await boxOf(first);+ check('刷新后自动恢复草稿', afterReload && Math.abs(afterReload.left - expect.left) < 0.5,+ `期望 ${expect.left},${expect.top} 实得 ${afterReload?.left},${afterReload?.top}`);+ check('刷新后恢复手动宽高状态', afterReload+ && Math.abs(afterReload.width - expect.width) < 0.5+ && Math.abs(afterReload.height - expect.height) < 0.5+ && afterReload.widthLocked && afterReload.heightLocked,+ `期望 ${expect.width.toFixed(1)}×${expect.height.toFixed(1)} 实得 ${afterReload?.width.toFixed(1)}×${afterReload?.height.toFixed(1)}`);+ check('草稿提示条可见', await page.evaluate(() => !document.getElementById('hf-draft').hidden));++ if (!fails && verifiedLayersHTML) {+ try {+ writeFileSync(layersOutput, verifiedLayersHTML);+ check('已生成默认 layers.html', true, layersOutput);+ } catch (error) {+ check('已生成默认 layers.html', false, String(error));+ }+ }++ if (errors.length) console.log('\n编辑器页面报错:', errors.join('; '));+} finally {+ wired.cleanup();+ await browser.close();+}++markTiming('完成');+if (showTimings) {+ console.log('\n【分阶段计时】');+ for (const row of timingRows) {+ console.log(` TIMING\t${row.phase}\t${(row.ms / 1000).toFixed(3)}s`);+ }+ console.log(` TIMING\t总计\t${((Date.now() - timingStartedAt) / 1000).toFixed(3)}s`);+}++console.log(fails === 0 ? '\n全部通过 ✅\n' : `\n${fails} 项失败 ❌\n`);+process.exit(fails ? 1 : 0);diff --git a/skills/editable-design/scripts/wire-editor.mjs b/skills/editable-design/scripts/wire-editor.mjsnew file mode 100755index 0000000..48ed095--- /dev/null+++ b/skills/editable-design/scripts/wire-editor.mjs@@ -0,0 +1,104 @@+#!/usr/bin/env node++import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { createHash } from 'node:crypto';+import { basename, dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const target = process.argv[2];+if (!target) {+ console.error('usage: node scripts/wire-editor.mjs index.html');+ process.exit(2);+}++const source = resolve(target);+if (!existsSync(source) || !statSync(source).isFile()) {+ console.error(`wire-editor: no such HTML file: ${source}`);+ process.exit(2);+}++const project = dirname(source);+const scriptDir = dirname(fileURLToPath(import.meta.url));+const runtimeCandidates = [+ join(scriptDir, 'editor-assets'),+ resolve(scriptDir, '../assets/editor'),+];+const bundledAssets = runtimeCandidates.find((candidate) => {+ const css = join(candidate, 'layer-editor.css');+ const js = join(candidate, 'layer-editor.js');+ return existsSync(css) && existsSync(js)+ && readFileSync(css, 'utf8').includes('.hf-exploded-board')+ && readFileSync(js, 'utf8').includes('setExploded')+ && readFileSync(js, 'utf8').includes('downloadExploded');+});++if (!bundledAssets) {+ console.error('wire-editor: bundled poster editor runtime is unavailable or incomplete');+ process.exit(1);+}+let html = readFileSync(source, 'utf8');+const sourceRevision = createHash('sha256').update(html).digest('hex').slice(0, 12);+const runtimeRevision = createHash('sha256')+ .update(readFileSync(join(bundledAssets, 'layer-editor.css')))+ .update(readFileSync(join(bundledAssets, 'layer-editor.js')))+ .digest('hex').slice(0, 10);+const assetRevision = `${sourceRevision}-${runtimeRevision}`;+const tags = ' <meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate">\n'+ + ' <meta http-equiv="Pragma" content="no-cache">\n'+ + ` <link rel="stylesheet" href="layer-editor.css?v=${assetRevision}">\n`+ + ` <script src="layer-editor.js?v=${assetRevision}" defer></script>\n`;++if (!/<\/head>/i.test(html)) {+ console.error('wire-editor: HTML has no closing head tag');+ process.exit(1);+}+if (!/data-canvas-width="[0-9]+"/.test(html) || !/data-canvas-height="[0-9]+"/.test(html)) {+ console.error('wire-editor: canvas is missing data-canvas-width or data-canvas-height');+ process.exit(1);+}++const ids = [...html.matchAll(/data-layer-id="([^"]*)"/g)].map((match) => match[1]);+const duplicates = [...new Set(ids.filter((id, index) => !id || ids.indexOf(id) !== index))];+if (!ids.length || duplicates.length) {+ console.error(`wire-editor: invalid layer ids${duplicates.length ? `: ${duplicates.join(', ')}` : ''}`);+ process.exit(1);+}++html = html.replace(/<html([^>]*)>/i, (match, attrs) => {+ const cleanAttrs = attrs+ .replace(/\sdata-hf-source-revision="[^"]*"/i, '')+ .replace(/\sdata-hf-runtime-revision="[^"]*"/i, '');+ return `<html${cleanAttrs} data-hf-source-revision="${sourceRevision}" data-hf-runtime-revision="${runtimeRevision}">`;+});++for (const filename of ['layer-editor.css', 'layer-editor.js']) {+ const bundled = join(bundledAssets, filename);+ if (!existsSync(bundled)) {+ console.error(`wire-editor: bundled asset is missing: ${bundled}`);+ process.exit(1);+ }+ copyFileSync(bundled, join(project, filename));+}++const projectRuntime = join(project, 'scripts', 'editor-assets');+if (existsSync(join(project, 'poster.json'))) {+ mkdirSync(projectRuntime, { recursive: true });+ for (const filename of ['layer-editor.css', 'layer-editor.js']) {+ const bundled = join(bundledAssets, filename);+ const vendored = join(projectRuntime, filename);+ if (resolve(bundled) !== resolve(vendored)) copyFileSync(bundled, vendored);+ }+}++if (!html.includes('layer-editor.js')) {+ html = html.replace(/<\/head>/i, tags + '</head>');+}++const output = join(project, 'editor.html');+writeFileSync(output, html);+console.log(`editor ${output}`);+console.log(`source ${basename(source)} unchanged`);+console.log(`layers ${ids.length}`);+console.log(`runtime ${bundledAssets}`);+console.log(`revision ${sourceRevision}`);+console.log(`assets-rev ${runtimeRevision}`);diff --git a/skills/editable-design/tests/fixtures/small-explode/index.html b/skills/editable-design/tests/fixtures/small-explode/index.htmlnew file mode 100644index 0000000..f977e66--- /dev/null+++ b/skills/editable-design/tests/fixtures/small-explode/index.html@@ -0,0 +1,86 @@+<!doctype html>+<html lang="zh-CN">+<head>+<meta charset="utf-8">+<title>少组件拆解回归测试</title>+<style>+:root {+ --paper: #12382f;+ --ink: #f4eddf;+ --gold: #c6a45d;+ --font-display: "Songti SC", "STSong", serif;+ --font-body: "PingFang SC", "Hiragino Sans GB", sans-serif;+}+* { box-sizing: border-box; }+html, body { margin: 0; padding: 0; background: #12382f; }+.poster {+ position: relative;+ width: 800px;+ height: 1000px;+ overflow: hidden;+ background: linear-gradient(155deg, #173f35 0%, #0b2a23 100%);+ color: var(--ink);+ font-family: var(--font-body);+}+.wash {+ position: absolute;+ left: 0;+ top: 620px;+ width: 800px;+ height: 380px;+ background: linear-gradient(180deg, rgba(244,237,223,0) 0%, rgba(244,237,223,0.18) 100%);+}+[data-layer-id] { position: absolute; margin: 0; }+.headline {+ left: 80px;+ top: 130px;+ width: 500px;+ height: 100px;+ font-family: var(--font-display);+ font-size: 76px;+ line-height: 100px;+}+.subhead {+ left: 84px;+ top: 260px;+ width: 420px;+ height: 50px;+ color: var(--gold);+ font-size: 30px;+ line-height: 50px;+}+.caption {+ left: 84px;+ top: 340px;+ width: 560px;+ height: 42px;+ font-size: 24px;+ line-height: 42px;+}+.badge {+ left: 84px;+ top: 810px;+ width: 210px;+ height: 58px;+ border: 1px solid var(--gold);+ color: var(--gold);+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 22px;+ letter-spacing: 4px;+}+</style>+</head>+<body>+<div class="poster" data-canvas-width="800" data-canvas-height="1000">+ <div class="wash"></div>+ <div data-explode-group="hero" data-explode-label="标题模块">+ <div class="headline" data-layer-id="headline">山川入画</div>+ <div class="subhead" data-layer-id="subhead">少组件拆解</div>+ <div class="caption" data-layer-id="caption">文字叶子应作为同级补充组件出现</div>+ </div>+ <div class="badge" data-layer-id="badge">回归测试</div>+</div>+</body>+</html>diff --git a/skills/html-to-pptx/LICENSE b/skills/html-to-pptx/LICENSEnew file mode 100644index 0000000..d645695--- /dev/null+++ b/skills/html-to-pptx/LICENSE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/skills/html-to-pptx/README.md b/skills/html-to-pptx/README.mdnew file mode 100644index 0000000..09d6d7c--- /dev/null+++ b/skills/html-to-pptx/README.md@@ -0,0 +1,37 @@+# HTML to Editable PPTX++`html-to-pptx` is an independent Codex skill that deterministically converts compatible slide, poster, and fixed-canvas HTML into an editable PowerPoint file. It also supports `layers.html` exploded-layer boards and an optional visual comparison workflow.++## Requirements++- Python 3.10 or newer+- Playwright Chromium+- `python-pptx`, Pillow, and NumPy++```bash+python3 -m pip install -r requirements.txt+python3 -m playwright install chromium+scripts/doctor.sh+```++Chromium sandboxing stays enabled by default. Set `HTML_TO_PPTX_NO_SANDBOX=1` only when the host cannot launch Chromium with its sandbox.++Optional visual comparison additionally requires LibreOffice and PyMuPDF:++```bash+python3 -m pip install -r requirements-check.txt+```++## Usage++```bash+python3 scripts/to_pptx.py /path/to/index.html -o /path/to/design.pptx+python3 scripts/exploded_to_pptx.py /path/to/layers.html+python3 scripts/render_check.py /path/to/index.html /path/to/design.pptx+```++Use the original `index.html` or an editor-downloaded `*.edited.html` beside its assets. Do not pass an editor shell such as `editor.html`.++Editable Design is a supported source of HTML, but it is not required. This skill runs only when PPTX conversion is requested.++This community project is provided under the Apache License 2.0 and is not an official OpenAI project.diff --git a/skills/html-to-pptx/SKILL.md b/skills/html-to-pptx/SKILL.mdnew file mode 100644index 0000000..7badb0a--- /dev/null+++ b/skills/html-to-pptx/SKILL.md@@ -0,0 +1,220 @@+---+name: html-to-pptx+description: 把 slide/poster 的 HTML 确定性地转成可编辑 PPTX——每个视觉元素(插画、图标、箭头、装饰线、文字)都是能单独选中拖动的对象,而不是压成一张背景图;也能把 case 的图层展开图 layers.html 转成一页可编辑 PPTX;并可把产物渲回图片做保真度比对。当用户要导出 pptx/ppt、问「HTML 怎么转 PowerPoint」、想让生成的海报或幻灯片能在 PowerPoint 里继续改、要把图层展开图/拆解图变成 ppt、或需要检查转换后元素是否独立可编辑时使用。+---++# HTML → 可编辑 PPTX++**纯确定性转换:无 LLM、无常驻服务、离线单命令。**++目标不是「截个图塞进 ppt」,而是让 PowerPoint 里每个元素都能单独选中、拖动、改字、改色。++## 前置依赖++```bash+python3 -m pip install -r requirements.txt+python3 -m playwright install chromium+./scripts/doctor.sh+```++确定性转换核心已经随 Skill 固定在 `scripts/_html_to_pptx.py`,不依赖其他私有仓库。+浏览器默认保留 Chromium 沙箱;只有运行环境明确不支持沙箱时,才设置+`HTML_TO_PPTX_NO_SANDBOX=1`。++`render_check.py` 额外需要 LibreOffice(渲染 pptx)和 PyMuPDF:+`brew install --cask libreoffice && python3 -m pip install -r requirements-check.txt`。+这两项只用于视觉比对,不影响核心转换。++## 转换++```bash+python3 scripts/to_pptx.py <index.html> # → 同目录同名 .pptx+python3 scripts/to_pptx.py <index.html> -o deck.pptx+python3 scripts/to_pptx.py <index.html> --selector '#hero' # 画布识别失败时手动指定+```++输出示例,**先看这行确认画布和元素分布是否合理**:++```+✅ /path/dragon_poster.pptx+ 画布 1067x1600 ([data-canvas-width]) · 形状 4 · 文本框 10 · 独立图片 13 · 元素 28+```++## 图层展开图(case 的 `layers.html`)++`outputs/cases/*/*/layers.html` 是一张**图层展开图**:`.hf-exploded-board` 上摊开若干+`.hf-exploded-item`——整图缩略(overview)、背景底、以及各图层/分组。转成**一页**+PPTX,默认丢掉 overview 那一项:++```bash+python3 scripts/exploded_to_pptx.py <case>/layers.html # → 同目录 layers.pptx+python3 scripts/exploded_to_pptx.py <case>/layers.html --keep-overview+```++```+board 3060x2400 · 分块 26 (跳过 overview 1)· {'layer': 12, 'group': 13, 'background': 1}+✅ .../layers.pptx+ 形状 45 · 文本框 93 · 独立图片 51 · 元素 265+```++粒度是**元素级**而非分块级:每块内部的每行字、每张照片、每张卡片都是独立对象。++这类页面有三个特性会干扰通用转换,`exploded_to_pptx.py` 在量画布之前一次性抹平,+所以**不要直接用 `to_pptx.py` 指向 board**:++1. board 会按窗口自适应缩放,而转换器又要把视口调成画布大小,两者互相触发、越缩越小。+ 用 `!important` 规则钉死 `transform`,压过页面脚本写的 inline style。+2. 有入场动画,要等 `[data-hf-exploded-ready='1']` 再量。+3. overview 缩略图、扫描光效、replay 按钮属于页面外壳,不是内容。++## 验收(建议每次都跑)++```bash+python3 scripts/render_check.py <index.html> <out.pptx> # → <out>.compare.png+python3 scripts/render_check.py <layers.html> <layers.pptx> --exploded+```++四联图:源 HTML / PPTX 渲回 / 每个独立对象的边界框 / 误差热力图。**第三联是关键**+——框住的每一块在 PowerPoint 里都能单独选中。若某个视觉元素没有自己的框,说明它掉进+了兜底背景,按下方「排错」处理。++终端同时给出平均像素差、超阈值占比,以及误差最大的几块区域的坐标和两侧色值。+**别只看聚合数字**:整页平均差很容易被大面积正确的背景稀释,一整张卡片的内容糊掉在+均值上可能只体现为零点几的波动,一定要顺着列出的区域坐标去看具体是哪里错了。++展开图必须加 `--exploded`,它会套用与转换器完全相同的页面预处理;否则基准图里会多出+总览图和没跑完的入场动画,比对的是两张不同的画。++**注意 LibreOffice 的渲染不等于 PowerPoint**,竖排 CJK 尤其如此:同一份 pptx,+PowerPoint 排成正确的单列,LibreOffice 会把它拆成两列。已实测确认这是 LibreOffice 的+问题,不是产物的问题——别为了迁就它去改字族,那只会让 PowerPoint 里变差。++macOS 上可以让 PowerPoint 自己导 PDF 来做权威比对:++```applescript+tell application "Microsoft PowerPoint"+ open POSIX file "/abs/path/deck.pptx"+ save presentation 1 in "/abs/path/out.pdf" as save as PDF+end tell+```++PowerPoint 是沙箱应用,输出路径要挑它有权限写的位置;若长时间无输出,多半是它弹了+模态框,切过去点掉即可。++### 无法严格复刻的部分++- **字重只有两档**。OOXML 的 `b` 是布尔量,CSS 的 400/500/600/650 会被压成常规或加粗。+ 实测「PingFang SC Semibold」这类带字重的字族名解析不出来,这条路走不通。+- **对方机器缺字体就会被替换**。我们写的是正确的字族名,但装没装不由我们决定;+ OOXML 的字体内嵌 python-pptx 不支持,Mac 版 PowerPoint 也不认。+- **纵向基线有零点几个百分点的偏移**。PPTX 按文本框锚定,CSS 按行盒基线,结构不同。+- **径向/conic/多层叠加渐变画不成原生填充**。没有子元素时会栅格化,仍是独立可拖动+ 的对象、像素精确;带子元素的容器不能栅格化(会把子元素一起吞掉),它的底色就留在+ 兜底背景里,视觉正确但那层底色本身不可单独选中。单层线性渐变则输出成真正的+ `gradFill`,双色标带 alpha 和角度。++## 转换规则++四分类,决定每个 DOM 元素在 pptx 里变成什么:++| 角色 | 产物 | 典型对象 |+| --- | --- | --- |+| `text` | 可编辑文本框(含自己的底色形状、旋转角度) | 标题、标签、斜排文字 |+| `shape` | 原生(圆角)矩形,子元素叠在上面 | 卡片、胶囊、空心圆圈 |+| `picture` | **单独隔离截图(透明底)**,各自成一张图 | 插画、内联 SVG 图标、箭头、装饰线 |+| `image` | 不重建,留在兜底背景 | 满画布渐变底、纯装饰纹理 |++关键设计:**兜底背景只装没能重建的部分**,所以永远不丢像素;重建充分时它就只剩纸张底色。++画布自动识别 `.slide-canvas` / `.poster-canvas` / `[data-canvas-width]` / `#poster`;+幻灯片尺寸按**真实宽高比**推导(长边 13.333in),1920×1080 仍是 16:9,1067×1600 保持竖版,+两轴等比例不拉伸。++已覆盖:非均匀边框(顶边强调条拆成独立细条)、只有描边的空心盒子不被填实、+`writing-mode` 竖排、字体替换后自动缩字号以免溢出。++**旋转会累积祖先的 transform**,和缩放同理。被外层 wrapper 转了角度的按钮,自身+computed `transform` 是 `none`,只读它自己会把整块导成水平的。旋转元素按「未旋转的+布局尺寸、居中于实测包围盒」放置——包围盒是斜矩形的轴对齐外接框,直接拿它当宽高会偏大。++**水平对齐取实际渲染结果,不只看 `text-align`**。用 flex `justify-content: center` 居中+的胶囊按钮从不设置 `text-align`,它继承来的值是 `start`;只读这一个属性会把文字钉在+按钮左边缘。现在 flex 行方向读 `justify-content`、列方向读 `align-items`(列布局里水平+是交叉轴),grid 优先 `justify-items` 再退回 `justify-content`;`space-between` 这类分布+关键字仍沿用 `text-align`,因为只有一段文字时它们本来就贴起始边。++**`mix-blend-mode: multiply` 的白底会烘进 alpha**。白底无 alpha 的线稿 PNG 靠 multiply+消掉自己的白(白 × 纸色 = 纸色)。PowerPoint 的图片没有混合模式,而隔离截图又是透明底,+multiply 和「什么都没有」混合等于不混合,白底会原样进 pptx,成为一块白板。+灰度墨的 multiply 与「黑墨按 alpha 叠加」在数学上等价:`src*d == a*C + (1-a)*d`+取 `C=0, a=1-src`。取 `m = min(r,g,b)` 作为要抠掉的白量即可推广到彩色墨——+压在白底上时精确,墨是灰的时候处处精确,而 `grayscale()` 滤镜留下的正是灰墨。+`darken` 同样处理,`soft-light` 之类没有等价 alpha 形式,不处理。++这条规则会让产物**偏离展开图页面、但对齐真实海报**。展开图里每个分块只含自己那一层,+纸色是另一个独立分块,所以线稿底下压根没有可乘的东西,multiply 在展开图里是失效的,+白板照样显示(实测:真海报把 multiply 强制成 normal 采样点变化 +11,展开图变化 0)。+如实复刻这种页面等于把白板抄进 pptx,所以这里选择按图层的**语义**导出。++**叠放次序**按每个元素在页面里实测的「绘制路径」排:从画布往下逐层记录+`[有效 z-index, 兄弟序号]`,字典序比较即可在最近公共祖先处分出胜负。不能把 z-index 当+成全局排序键——它只在同一个层叠上下文内给兄弟排序,拍平之后 `position:relative;+z-index:1` 的卡片会排到自己子元素后面,用底色盖住自己的图标和文字。++**排版保真**:字族取 CSS 字体链里**本机真实装有**的那一个(用字形宽度探测,+`document.fonts.check` 恒返回 true、不能用),字号按实测值 1:1 换算,`letter-spacing`+写成 OOXML `spc`、`line-height` 写成精确行距、斜体写成 `i`。字号只在字体确实需要替换+时才收缩,字体对得上时不打折。++**文字块拆分**:一行文字若靠 flex `gap` 或内联分隔符的 margin 撑开,合成一个文本框会+塌掉近一半宽度。这类容器里的每段裸文本会被包进 span,各自成为独立文本框,落在自己+实测的位置上。++另外三项针对「元素被祖先加工过」的补偿,缺了任何一项展开图都会明显走样:++- **累积缩放**:盒子量的是变换后的尺寸,字号/边框/圆角量的却是变换前的值。二者都乘上+ 祖先 `transform` 的累积缩放,否则 0.5 倍裁剪窗里的 24px 标题会撑爆自己的框。+- **累积不透明度**:元素被逐个拆出来,祖先的 `opacity` 和颜色自身的 alpha 都要折进+ 每个对象。漏掉的话,12% 透明度的水印大字会导出成实心亮字。+- **裁剪**:伸出 `overflow:hidden` 祖先的部分要按可见切片摆放,图片按可见区截图;+ 完全不可见的元素直接跳过。++## 排错++**某个元素没有独立边界框(掉进兜底背景)**+到 `outputs/.../scene.json` 查它的 `roles`。判成 `image` 通常是两种情况:面积占比 ≥ 0.9+(被当成满画布背景),或者它确实没有自己的墨迹(纯布局容器)。前者属误判,+需要调 `MAX_SHAPE_AREA_FRACTION` 或在 `classify_elements` 里加规则。++**整页只有一个对象**+源 HTML 整页画在**一个大 `<svg>`** 里。SVG 内部节点不拆——这类页面没有可分的顶层结构,+是转换器的已知限制,不是 bug。要拆得改 HTML 生成侧,让结构落在 DOM 元素上。++**传错文件**+别传编辑器外壳 `editor.html`(编辑器 UI 会被一起拍进去)。传原始 `index.html`,+或 Editable Design 编辑器「下载 HTML」导出的 `*.edited.html`。++**相对资源(css/字体/图片)丢失**+按 HTML 所在目录解析,所以在原目录里跑最稳。++## 分发给别人++```bash+./pack.sh # → ~/Desktop/html-to-pptx-skill.tar.gz+```++`pack.sh` 会把完整 Skill(含固定的 `scripts/_html_to_pptx.py`、依赖清单、许可和诊断脚本)+一起打包,解压后不依赖本仓库其他文件。++对方:`tar -xzf html-to-pptx-skill.tar.gz -C ~/.codex/skills/`,装好 Python 依赖即可用。+包里带着 `pack.sh` 自己,可继续二次分发。++## 与 Editable Design 的关系++两者是可独立安装的同级 Skill,不是主 Skill 与内部子 Skill。Editable Design 负责完成并交付+HTML、PNG、浏览器编辑器和设计回放;本 Skill 只负责把用户指定的 HTML 转成 PowerPoint 中+可编辑的 PPTX。++当 Editable Design 已完成核心设计,如果本 Skill 可用,可以向用户简短说明“还可以导出为+可编辑 PPTX”。**只有用户明确说需要时才运行转换**,不能让 PPTX 导出阻塞或延迟核心设计交付。+转换时使用原始 `index.html` 或编辑器下载的 `*.edited.html`,绝不使用 `editor.html`。diff --git a/skills/html-to-pptx/THIRD_PARTY_NOTICES.md b/skills/html-to-pptx/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..ce623eb--- /dev/null+++ b/skills/html-to-pptx/THIRD_PARTY_NOTICES.md@@ -0,0 +1,12 @@+# Third-party notices++Dependencies are installed separately and are not included in the release archive.++- Playwright for Python — Apache License 2.0.+- python-pptx — MIT License.+- Pillow — HPND License.+- NumPy — BSD-3-Clause License.+- PyMuPDF — optional comparison dependency, available under AGPL or a commercial license; users are responsible for choosing and complying with the applicable terms.+- LibreOffice — optional external application used to render PPTX files for comparison; it is not redistributed here.++Generated presentations and user-provided HTML or artwork are not included in this repository's license merely because they are processed by the skill.diff --git a/skills/html-to-pptx/agents/openai.yaml b/skills/html-to-pptx/agents/openai.yamlnew file mode 100644index 0000000..53b65fd--- /dev/null+++ b/skills/html-to-pptx/agents/openai.yaml@@ -0,0 +1,4 @@+interface:+ display_name: "HTML to Editable PPTX"+ short_description: "Convert compatible HTML into editable PowerPoint"+ default_prompt: "Use $html-to-pptx to convert this HTML design into an editable PowerPoint file."diff --git a/skills/html-to-pptx/pack.sh b/skills/html-to-pptx/pack.shnew file mode 100755index 0000000..b0d79d8--- /dev/null+++ b/skills/html-to-pptx/pack.sh@@ -0,0 +1,47 @@+#!/usr/bin/env bash+# 把 skill 打包成可分发的压缩包(按输出扩展名选 .zip 或 .tar.gz)+#+# ./pack.sh 默认 ~/Desktop/html-to-pptx-skill.tar.gz+# ./pack.sh ~/Desktop/xxx.zip 后缀写 .zip 就出 zip+#+# 完整复制当前 Skill;转换核心已经固定在 scripts/_html_to_pptx.py。+set -euo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+NAME="html-to-pptx"+OUT="${1:-$HOME/Desktop/${NAME}-skill.tar.gz}"++STAGE="$(mktemp -d)"+trap 'rm -rf "$STAGE"' EXIT+if [ ! -f "$HERE/scripts/_html_to_pptx.py" ]; then+ echo "❌ 缺少 scripts/_html_to_pptx.py,已中止。" >&2+ exit 1+fi+cp -R "$HERE" "$STAGE/$NAME"+find "$STAGE/$NAME" -name '.DS_Store' -delete+find "$STAGE/$NAME" -name '._*' -delete+find "$STAGE/$NAME" -type d -name '__pycache__' -prune -exec rm -rf {} +++mkdir -p "$(dirname "$OUT")"+rm -f "$OUT"+if [[ "$OUT" == *.zip ]]; then+ # -X 不写 macOS 的资源分支,免得对方解出一堆 __MACOSX/._ 垃圾文件+ ( cd "$STAGE" && zip -q -r -X "$OUT" "$NAME" -x '*.DS_Store' )+ COUNT=$(unzip -Z1 "$OUT" | grep -vc '/$')+ UNPACK="unzip $(basename "$OUT") -d ~/.codex/skills/"+else+ tar -czf "$OUT" -C "$STAGE" "$NAME"+ COUNT=$(tar -tzf "$OUT" | grep -vc '/$')+ UNPACK="tar -xzf $(basename "$OUT") -C ~/.codex/skills/"+fi++echo ""+echo "✅ 已打包 $OUT"+echo " 体积 $(du -h "$OUT" | cut -f1) 文件 $COUNT 个"+echo ""+echo "对方使用方式:"+echo " $UNPACK"+echo " cd ~/.codex/skills/$NAME && python3 -m pip install -r requirements.txt"+echo " python3 -m playwright install chromium && ./scripts/doctor.sh"+echo ""+echo "前置要求:Python 3.10+。跑 render_check.py 还需 LibreOffice 与 PyMuPDF。"diff --git a/skills/html-to-pptx/requirements-check.txt b/skills/html-to-pptx/requirements-check.txtnew file mode 100644index 0000000..4f365fd--- /dev/null+++ b/skills/html-to-pptx/requirements-check.txt@@ -0,0 +1,2 @@+-r requirements.txt+PyMuPDFdiff --git a/skills/html-to-pptx/requirements.txt b/skills/html-to-pptx/requirements.txtnew file mode 100644index 0000000..44c40b9--- /dev/null+++ b/skills/html-to-pptx/requirements.txt@@ -0,0 +1,4 @@+playwright+python-pptx+Pillow+numpydiff --git a/skills/html-to-pptx/scripts/_html_to_pptx.py b/skills/html-to-pptx/scripts/_html_to_pptx.pynew file mode 100644index 0000000..7660027--- /dev/null+++ b/skills/html-to-pptx/scripts/_html_to_pptx.py@@ -0,0 +1,1669 @@+"""HTML slide / poster -> editable PPTX (semantic reconstruction).++Design goal: **every visual element becomes its own PPTX object.** A deck that+opens in PowerPoint should let you grab the arrow, the dragon and the icon+independently — not find them fused into one flat backdrop picture.++Pipeline (deterministic; a single optional LLM call may only re-label roles):++ 1. extract Playwright renders the canvas (``.slide-canvas`` / ``.poster-canvas``+ / ``[data-canvas-width]``, auto-detected) and walks the DOM,+ collecting each element's canvas-relative box, computed style,+ rotation, stacking order and whether it owns renderable content.+ Coordinates come from ``getBoundingClientRect`` so grid/flex+ layouts are captured precisely.+ 2. classify A deterministic four-way rule assigns a role:+ text editable text box (plus its own fill, if painted)+ shape native (rounded) rectangle; children render on top+ picture rasterized **on its own transparent canvas** — images,+ inline SVG, and painted leaves too complex for a+ native shape (partial borders, gradients, rotation)+ image not reconstructed; stays in the residual backdrop+ 3. rasterize Each ``picture`` is screenshotted in isolation (every other+ element hidden, transparent background) so it lands in the deck+ as a standalone, movable picture shape.+ 4. backdrop Everything reconstructed is neutralized and the canvas is+ re-shot. Only what we failed to rebuild survives, so the deck is+ never missing pixels — usually just the page background.+ 5. build python-pptx renders backdrop first, then every element in+ stacking order (z-index, then document order).+ 6. verify The saved file is re-opened to confirm shape/text/picture counts.++Slide dimensions follow the canvas aspect ratio (long side 13.333in), so a+1920x1080 slide stays 16:9 and a 1067x1600 poster stays portrait. The scale is+uniform on both axes, so nothing is ever stretched.+"""++from __future__ import annotations++import json+import math+import os+import re+import threading+from contextlib import contextmanager+from functools import partial+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from typing import Any, Dict, Iterator, List, Optional, Tuple+from urllib.parse import quote++# Long edge of the generated slide. 1920x1080 -> 13.333in x 7.5in (the classic+# 16:9 deck); a portrait poster keeps its own ratio against the same long edge.+LONG_SIDE_IN = 13.3333333+EMU_PER_INCH = 914400+EMU_PER_PT = 12700+BOLD_WEIGHT_THRESHOLD = 600+# An element covering most of the canvas is treated as backdrop, never a shape.+MAX_SHAPE_AREA_FRACTION = 0.9+# Minimum opaque alpha for a color to count as "painted".+MIN_VISIBLE_ALPHA = 0.02+# Below this angle a rotation is noise from sub-pixel layout, not design intent.+MIN_ROTATION_DEG = 0.5++# Kept for backwards compatibility with callers that imported the 16:9 defaults.+DEFAULT_SLIDE_WIDTH_EMU = 12192000+DEFAULT_SLIDE_HEIGHT_EMU = 6858000++CANVAS_SELECTORS = (".slide-canvas", ".poster-canvas", "[data-canvas-width]", "#poster")++_CJK_RE = re.compile(r"[\u3400-\u9fff\uf900-\ufaff\uff00-\uffef]")+_RGBA_RE = re.compile(+ r"rgba?\(\s*([0-9.]+)[,\s]+([0-9.]+)[,\s]+([0-9.]+)(?:[,\s/]+([0-9.]+%?))?\s*\)"+)++# Collected once in the page. ``data-wca-id`` is stamped on every element so the+# rasterize and neutralize passes can re-select the exact same nodes.+_EXTRACT_JS = r"""+(canvasSel) => {+ const canvas = document.querySelector(canvasSel);+ if (!canvas) return null;+ const cb = canvas.getBoundingClientRect();+ const SKIP = new Set(['script','style','defs','clippath','marker','filter','lineargradient','radialgradient','mask','symbol','title','metadata']);+ const hasDirectText = (node) => {+ for (const n of node.childNodes) if (n.nodeType === 3 && n.textContent.trim()) return true;+ return false;+ };+ const parseAlpha = (c) => {+ const m = c && c.match(/rgba?\(\s*[\d.]+[,\s]+[\d.]+[,\s]+[\d.]+(?:[,\s\/]+([\d.]+%?))?/);+ if (!m || m[1] == null) return c && c !== 'transparent' ? 1 : 0;+ return m[1].endsWith('%') ? parseFloat(m[1]) / 100 : parseFloat(m[1]);+ };+ const sides = ['Top','Right','Bottom','Left'];+ // "Painted" = contributes ink of its own (fill, border, gradient or shadow).+ const painted = (st) => {+ if (parseAlpha(st.backgroundColor) > 0.02) return true;+ if ((st.backgroundImage || 'none') !== 'none') return true;+ if ((st.boxShadow || 'none') !== 'none') return true;+ for (const s of sides) {+ if (parseFloat(st['border' + s + 'Width']) > 0+ && st['border' + s + 'Style'] !== 'none'+ && parseAlpha(st['border' + s + 'Color']) > 0.02) return true;+ }+ return false;+ };+ const insideSvg = (el) => { const a = el.closest('svg'); return !!a && a !== el; };+ const visible = (el) => {+ const st = getComputedStyle(el);+ if (st.display === 'none' || st.visibility === 'hidden') return false;+ if (parseFloat(st.opacity || '1') <= 0.01) return false;+ return true;+ };+ // Does this node put anything on screen by itself?+ const renderable = (el) => {+ const t = el.tagName.toLowerCase();+ if (t === 'img' || t === 'svg' || t === 'canvas' || t === 'video') return true;+ if (hasDirectText(el)) return true;+ return painted(getComputedStyle(el));+ };+ const rotationOf = (st) => {+ const tr = st.transform;+ if (!tr || tr === 'none') return 0;+ const m = tr.match(/matrix\(([^)]+)\)/);+ if (!m) return 0;+ const p = m[1].split(',').map(Number);+ return Math.atan2(p[1], p[0]) * 180 / Math.PI;+ };+ // Rotation is inherited through ancestor transforms exactly as scale is. A pill+ // tilted by a wrapper reports `transform: none` on itself, so reading only its+ // own style exports it bolt upright.+ const contentRotationOf = (el) => {+ let deg = 0;+ for (let n = el; n && n !== canvas.parentElement; n = n.parentElement) {+ deg += rotationOf(getComputedStyle(n));+ }+ return deg;+ };+ // Cumulative scale from every transform between the element and the canvas,+ // its own included. Boxes come from getBoundingClientRect (already scaled) but+ // font size and border width come from computed style (not scaled), so without+ // this factor text inside a scaled wrapper renders 1/scale too large.+ const contentScaleOf = (el) => {+ let s = 1;+ for (let n = el; n && n !== canvas.parentElement; n = n.parentElement) {+ const t = getComputedStyle(n).transform;+ if (!t || t === 'none') continue;+ const m = t.match(/matrix\(([^)]+)\)/);+ if (!m) continue;+ const p = m[1].split(',').map(Number);+ s *= (Math.hypot(p[0], p[1]) + Math.hypot(p[2], p[3])) / 2;+ }+ return s > 0 ? s : 1;+ };+ // Cumulative CSS opacity, own included. Elements are extracted individually, so+ // a faded ancestor has to be folded into each descendant's own alpha.+ const contentOpacityOf = (el) => {+ let o = 1;+ for (let n = el; n && n !== canvas.parentElement; n = n.parentElement) {+ const v = parseFloat(getComputedStyle(n).opacity || '1');+ if (!isNaN(v)) o *= v;+ }+ return o;+ };+ // Visible slice after every clipping ancestor. An element sticking out of an+ // overflow:hidden crop must not be drawn full-size in the deck.+ const clipRectOf = (el, r) => {+ let x0 = r.left, y0 = r.top, x1 = r.right, y1 = r.bottom;+ for (let n = el.parentElement; n && n !== canvas.parentElement; n = n.parentElement) {+ const st = getComputedStyle(n);+ const hides = [st.overflow, st.overflowX, st.overflowY].some(+ (v) => v === 'hidden' || v === 'clip' || v === 'auto' || v === 'scroll');+ if (!hides) continue;+ const nr = n.getBoundingClientRect();+ x0 = Math.max(x0, nr.left); y0 = Math.max(y0, nr.top);+ x1 = Math.min(x1, nr.right); y1 = Math.min(y1, nr.bottom);+ }+ return { left: x0, top: y0, width: Math.max(0, x1 - x0), height: Math.max(0, y1 - y0) };+ };+ // z-index only orders siblings inside one stacking context, and it is ignored+ // on a static element that is not a flex/grid item. Reading it as a global key+ // lets a card with `z-index:1` sort above the text it contains.+ const stackZ = (el) => {+ const st = getComputedStyle(el);+ const z = parseInt(st.zIndex, 10);+ if (isNaN(z)) return 0;+ if (st.position !== 'static') return z;+ const par = el.parentElement;+ if (par && /(flex|grid)$/.test(getComputedStyle(par).display)) return z;+ return 0;+ };+ const sibIdx = new WeakMap();+ const siblingIndex = (el) => {+ if (sibIdx.has(el)) return sibIdx.get(el);+ const par = el.parentElement;+ if (!par) return 0;+ let i = 0;+ for (const kid of par.children) sibIdx.set(kid, i++);+ return sibIdx.get(el) ?? 0;+ };+ // Paint order as a path from the canvas down: each step contributes the node's+ // effective z-index then its position among siblings. Comparing two paths+ // lexicographically resolves them at their lowest common ancestor, and an+ // ancestor's path is a prefix of its descendant's, so a parent always paints+ // first — which is exactly the rule a flat z-index sort was breaking.+ const paintPathOf = (el) => {+ const chain = [];+ for (let n = el; n && n !== canvas; n = n.parentElement) chain.push(n);+ const out = [];+ for (let i = chain.length - 1; i >= 0; i--) {+ out.push(stackZ(chain[i]), siblingIndex(chain[i]));+ }+ return out;+ };+ const hasPseudo = (el) => {+ for (const p of ['::before', '::after']) {+ const cs = getComputedStyle(el, p);+ if (!cs) continue;+ const c = cs.content;+ if (c && c !== 'none' && c !== 'normal' && parseFloat(cs.width || '0') >= 0 && painted(cs)) return true;+ if (c && c !== 'none' && c !== 'normal' && c !== '""') return true;+ }+ return false;+ };+ const resolveColor = (node) => {+ const s = getComputedStyle(node);+ let c = (s.webkitTextFillColor && s.webkitTextFillColor !== 'currentcolor')+ ? s.webkitTextFillColor : s.color;+ if (parseAlpha(c) < 0.1) {+ const g = (s.backgroundImage || '').match(/rgba?\([^)]*\)/);+ if (g) return g[0];+ if (parseAlpha(s.color) >= 0.1) return s.color;+ }+ return c;+ };+ const isInline = (node) => {+ const d = getComputedStyle(node).display;+ return d.startsWith('inline') || d === 'contents';+ };+ // OOXML names exactly one typeface, so the CSS chain has to collapse to the+ // family the browser actually painted with. Generic keywords are skipped: they+ // resolve per-platform and carry no name PowerPoint could look up.+ const GENERIC = /^(sans-serif|serif|monospace|cursive|fantasy|system-ui|ui-sans-serif|ui-serif|ui-monospace|ui-rounded|math|emoji|fangsong|-apple-system|blinkmacsystemfont)$/i;+ // document.fonts.check() answers "can this string be rendered", which is always+ // true once fallback kicks in, so it cannot tell an installed family from a+ // missing one. Measuring glyph widths against baseline families can.+ const PROBE = 'mmmmmmmmmmlliWWWW@@@@国永';+ const measureCtx = document.createElement('canvas').getContext('2d');+ const baseWidths = {};+ for (const b of ['monospace', 'serif', 'sans-serif']) {+ measureCtx.font = '72px ' + b;+ baseWidths[b] = measureCtx.measureText(PROBE).width;+ }+ const installed = (name) => {+ for (const b of ['monospace', 'serif', 'sans-serif']) {+ measureCtx.font = '72px "' + name + '", ' + b;+ if (measureCtx.measureText(PROBE).width !== baseWidths[b]) return true;+ }+ return false;+ };+ const familyCache = new Map();+ const resolveFamily = (chain) => {+ if (familyCache.has(chain)) return familyCache.get(chain);+ let picked = '';+ for (const raw of (chain || '').split(',')) {+ const name = raw.trim().replace(/^["']|["']$/g, '');+ if (!name || GENERIC.test(name)) continue;+ if (!picked) picked = name; // keep the first concrete name as a fallback+ let ok = false;+ try { ok = installed(name); } catch (e) { /* malformed family name */ }+ if (ok) { picked = name; break; } // this is the one actually painted+ }+ familyCache.set(chain, picked);+ return picked;+ };+ const spacingOf = (cs) => {+ const v = parseFloat(cs.letterSpacing);+ return isNaN(v) ? 0 : v; // 'normal' -> 0+ };+ // Flatten a text element into lines of styled runs so multi-color titles and+ // muted suffixes keep their per-span color / weight / size.+ const buildRich = (root) => {+ const lines = [[]];+ const cur = () => lines[lines.length - 1];+ const walk = (node) => {+ for (const ch of node.childNodes) {+ if (ch.nodeType === 3) {+ const t = ch.textContent.replace(/\s+/g, ' ');+ if (t) {+ const cs = getComputedStyle(node);+ cur().push({ text: t, color: resolveColor(node), weight: cs.fontWeight || '400',+ size: parseFloat(cs.fontSize) || 0, family: resolveFamily(cs.fontFamily),+ italic: cs.fontStyle === 'italic' || cs.fontStyle === 'oblique',+ spacing: spacingOf(cs) });+ }+ } else if (ch.nodeType === 1) {+ const t = ch.tagName.toLowerCase();+ if (SKIP.has(t)) continue;+ if (t === 'br') { lines.push([]); continue; }+ const cs = getComputedStyle(ch);+ if (cs.display === 'none' || cs.visibility === 'hidden') continue;+ const block = !isInline(ch);+ if (block && cur().length) lines.push([]);+ walk(ch);+ if (block && cur().length) lines.push([]);+ }+ }+ };+ walk(root);+ const cleaned = [];+ for (const line of lines) {+ const runs = line.filter((r) => r.text !== '');+ if (runs.length && runs.some((r) => r.text.trim() !== '')) {+ runs[0].text = runs[0].text.replace(/^\s+/, '');+ runs[runs.length - 1].text = runs[runs.length - 1].text.replace(/\s+$/, '');+ cleaned.push(runs.filter((r) => r.text !== ''));+ }+ }+ return cleaned;+ };++ // A run of text carries no geometry of its own, so a row whose chunks are+ // pushed apart by flex `gap` or by margins on inline separators collapses to a+ // fraction of its width once merged into one paragraph. Wrapping each bare+ // text run in a span makes every chunk a measurable element that lands at its+ // own position instead. Layout is unaffected: an inline span around a text run+ // occupies exactly the box the anonymous run already did.+ const spacedRow = (box) => {+ const disp = getComputedStyle(box).display;+ if (/^(inline-)?(flex|grid)$/.test(disp)) {+ const gap = parseFloat(getComputedStyle(box).gap);+ if (!isNaN(gap) && gap > 0.5) return true;+ }+ for (const kid of box.children) {+ const ks = getComputedStyle(kid);+ for (const prop of ['marginLeft', 'marginRight', 'paddingLeft', 'paddingRight']) {+ if (Math.abs(parseFloat(ks[prop]) || 0) > 0.5) return true;+ }+ }+ return false;+ };+ for (const box of canvas.querySelectorAll('*')) {+ if (!box.children.length || !hasDirectText(box) || !spacedRow(box)) continue;+ for (const node of [...box.childNodes]) {+ if (node.nodeType !== 3 || !node.textContent.trim()) continue;+ const span = document.createElement('span');+ span.setAttribute('data-wca-anon', '1');+ node.parentNode.replaceChild(span, node);+ span.appendChild(node);+ }+ }++ const out = [];+ let idx = 0;+ for (const el of canvas.querySelectorAll('*')) {+ const tag = el.tagName.toLowerCase();+ if (SKIP.has(tag)) continue;+ if (insideSvg(el)) continue; // svg internals ride along with their root+ if (!visible(el)) continue;+ const r = el.getBoundingClientRect();+ if (r.width <= 0.5 || r.height <= 0.5) continue;+ const vis = clipRectOf(el, r);+ if (vis.width <= 0.5 || vis.height <= 0.5) continue; // clipped away entirely++ const st = getComputedStyle(el);+ let textAncestor = false;+ for (let a = el.parentElement; a && a !== canvas; a = a.parentElement) {+ if (hasDirectText(a)) { textAncestor = true; break; }+ }+ let renderableDescendant = false;+ for (const d of el.querySelectorAll('*')) {+ if (SKIP.has(d.tagName.toLowerCase())) continue;+ if (insideSvg(d) || !visible(d)) continue;+ const dr = d.getBoundingClientRect();+ if (dr.width <= 0.5 || dr.height <= 0.5) continue;+ if (renderable(d)) { renderableDescendant = true; break; }+ }+ const bw = sides.map((s) => parseFloat(st['border' + s + 'Width']) || 0);+ const bc = sides.map((s) => st['border' + s + 'Color']);+ const uniformBorder = bw.every((v) => Math.abs(v - bw[0]) < 0.01)+ && bc.every((v) => v === bc[0]);+ const radii = ['TopLeft','TopRight','BottomLeft','BottomRight']+ .map((c) => parseFloat(st['border' + c + 'Radius']) || 0);+ const zi = st.zIndex;++ el.setAttribute('data-wca-id', String(idx));+ const direct = hasDirectText(el);+ out.push({+ id: idx,+ tag,+ className: (el.getAttribute('class') || '').slice(0, 140),+ x: r.left - cb.left, y: r.top - cb.top, w: r.width, h: r.height,+ vx: r.left, vy: r.top, // viewport coords, for screenshot clips+ visX: vis.left - cb.left, visY: vis.top - cb.top,+ visW: vis.width, visH: vis.height,+ visVX: vis.left, visVY: vis.top,+ clipped: (vis.width < r.width - 0.5) || (vis.height < r.height - 0.5),+ contentScale: contentScaleOf(el),+ contentOpacity: contentOpacityOf(el),+ layoutW: el.offsetWidth || r.width, // pre-transform size (rotation aside)+ layoutH: el.offsetHeight || r.height,+ areaFrac: (r.width * r.height) / Math.max(1, cb.width * cb.height),+ isSvg: tag === 'svg',+ isImg: tag === 'img' || tag === 'canvas' || tag === 'video',+ hasDirectText: direct,+ hasTextAncestor: textAncestor,+ hasRenderableDescendant: renderableDescendant,+ hasPseudo: hasPseudo(el),+ rotation: contentRotationOf(el),+ zIndex: (zi === 'auto' || zi === '' || zi == null) ? 0 : (parseInt(zi, 10) || 0),+ paintPath: paintPathOf(el),+ innerText: direct ? el.innerText : '',+ richText: direct ? buildRich(el) : [],+ fontSize: parseFloat(st.fontSize) || 0,+ fontWeight: st.fontWeight || '400',+ color: st.color,+ textAlign: st.textAlign || 'start',+ mixBlendMode: st.mixBlendMode || 'normal',+ display: st.display || 'block',+ flexDirection: st.flexDirection || 'row',+ justifyContent: st.justifyContent || 'normal',+ justifyItems: st.justifyItems || 'normal',+ alignItems: st.alignItems || 'normal',+ writingMode: st.writingMode || 'horizontal-tb',+ fontFamily: resolveFamily(st.fontFamily),+ fontStyle: st.fontStyle || 'normal',+ letterSpacing: spacingOf(st),+ lineHeight: parseFloat(st.lineHeight) || 0, // 'normal' -> 0, meaning auto+ opacity: parseFloat(st.opacity || '1'),+ bgColor: st.backgroundColor,+ bgImage: st.backgroundImage || 'none',+ borderRadius: Math.max.apply(null, radii),+ uniformRadius: radii.every((v) => Math.abs(v - radii[0]) < 0.01),+ borderWidth: bw[0],+ borderColor: bc[0],+ borderWidths: bw, // Top, Right, Bottom, Left+ borderColors: bc,+ uniformBorder: uniformBorder,+ boxShadow: st.boxShadow || 'none',+ });+ idx++;+ }+ return { canvas: { width: cb.width, height: cb.height }, elements: out };+}+"""++# Re-measure text under a neutral fallback font (Arial + PingFang/YaHei, present+# on typical macOS/Windows PowerPoint installs) to learn how much each text box+# must shrink to fit its ORIGINAL box when the design fonts are unavailable. The+# shrink is baked into the font size so it never depends on the opening app+# recomputing "shrink text on overflow" (PowerPoint does not, on open).+# Safety net for font substitution: re-measure each text box in the family that+# will actually be written to the pptx. When that family is the one the page+# already painted with, the ratio is 1 and nothing shrinks; it only bites when we+# had to fall back, where the substitute is wider and would overlap neighbours.+_MEASURE_FIT_JS = r"""+(items) => {+ const scales = {};+ const patched = [];+ for (const it of items) {+ const el = document.querySelector(`[data-wca-id="${it.id}"]`);+ if (!el) { scales[it.id] = 1; continue; }+ if (it.family) {+ patched.push([el, el.style.getPropertyValue('font-family'),+ el.style.getPropertyPriority('font-family')]);+ el.style.setProperty('font-family', '"' + it.family + '"', 'important');+ }+ }+ void document.body.offsetHeight; // force reflow+ for (const it of items) {+ const el = document.querySelector(`[data-wca-id="${it.id}"]`);+ if (!el) continue;+ const r = el.getBoundingClientRect();+ const wr = it.w > 0 && r.width > 0 ? it.w / r.width : 1;+ const hr = it.h > 0 && r.height > 0 ? it.h / r.height : 1;+ scales[it.id] = Math.max(0.3, Math.min(1, wr, hr));+ }+ for (const [el, value, prio] of patched) {+ if (value) el.style.setProperty('font-family', value, prio);+ else el.style.removeProperty('font-family');+ }+ return scales;+}+"""++# Isolation for per-element rasterization: strip page/canvas paint, hide every+# element, then re-show the target *and all of its descendants* (a parent set to+# `visible` cannot un-hide children that carry their own !important hidden).+_ISOLATE_JS = r"""+(payload) => {+ const canvas = document.querySelector(payload.canvasSel);+ if (!canvas) return;+ for (const node of [document.documentElement, document.body, canvas]) {+ node.style.setProperty('background', 'transparent', 'important');+ node.style.setProperty('background-image', 'none', 'important');+ }+ for (const el of canvas.querySelectorAll('*')) {+ el.style.setProperty('visibility', 'hidden', 'important');+ }+ const target = canvas.querySelector(`[data-wca-id="${payload.id}"]`);+ if (!target) return;+ target.style.setProperty('visibility', 'visible', 'important');+ for (const d of target.querySelectorAll('*')) {+ d.style.setProperty('visibility', 'visible', 'important');+ }+}+"""++_RESET_ISOLATION_JS = r"""+(canvasSel) => {+ const canvas = document.querySelector(canvasSel);+ if (!canvas) return;+ for (const node of [document.documentElement, document.body, canvas]) {+ node.style.removeProperty('background');+ node.style.removeProperty('background-image');+ }+ for (const el of canvas.querySelectorAll('*')) el.style.removeProperty('visibility');+}+"""++# Applied before the residual-backdrop shot. Each role gives up exactly the ink+# it contributes to the rebuilt deck, so whatever is left over is what we failed+# to reconstruct — and it still ships, inside the backdrop.+_NEUTRALIZE_JS = r"""+(payload) => {+ const strip = (el) => {+ el.style.setProperty('background', 'transparent', 'important');+ el.style.setProperty('background-image', 'none', 'important');+ el.style.setProperty('border', 'none', 'important');+ el.style.setProperty('box-shadow', 'none', 'important');+ el.style.setProperty('backdrop-filter', 'none', 'important');+ el.style.setProperty('-webkit-backdrop-filter', 'none', 'important');+ };+ for (const id of payload.shapeIds) {+ const el = document.querySelector(`[data-wca-id="${id}"]`);+ if (el) strip(el); // keep children: they render on top+ }+ for (const id of payload.textIds) {+ const el = document.querySelector(`[data-wca-id="${id}"]`);+ if (!el) continue;+ strip(el);+ el.style.setProperty('color', 'transparent', 'important');+ el.style.setProperty('-webkit-text-fill-color', 'transparent', 'important');+ }+ for (const id of payload.pictureIds) {+ const el = document.querySelector(`[data-wca-id="${id}"]`);+ if (!el) continue; // rasterized whole: hide the subtree+ el.style.setProperty('visibility', 'hidden', 'important');+ for (const d of el.querySelectorAll('*')) {+ d.style.setProperty('visibility', 'hidden', 'important');+ }+ }+}+"""+++class _QuietHandler(SimpleHTTPRequestHandler):+ def log_message(self, _format: str, *args: Any) -> None: # noqa: A003+ del args+++@contextmanager+def _serve_preview(index: Path) -> Iterator[str]:+ """Serve ``index``'s directory on a random loopback port.++ Self-contained (mirrors quality.screenshots._serve_preview) so this export+ module does not boot the whole quality-gate/providers stack just to render.+ """+ root = index.parent+ handler = partial(_QuietHandler, directory=str(root))+ server = ThreadingHTTPServer(("127.0.0.1", 0), handler)+ server.daemon_threads = True+ thread = threading.Thread(+ target=server.serve_forever, name="pptx-preview-http", daemon=True+ )+ thread.start()+ relative_index = index.relative_to(root).as_posix()+ host, port = server.server_address[:2]+ url = f"http://{host}:{port}/{quote(relative_index)}"+ try:+ yield url+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=3)+++def _parse_rgba(value: Optional[str]) -> Optional[Tuple[int, int, int, float]]:+ if not value:+ return None+ match = _RGBA_RE.search(value)+ if not match:+ return None+ r, g, b, a = match.groups()+ alpha = 1.0+ if a is not None:+ alpha = float(a[:-1]) / 100.0 if a.endswith("%") else float(a)+ return int(float(r)), int(float(g)), int(float(b)), alpha+++def _alpha(value: Optional[str]) -> float:+ parsed = _parse_rgba(value)+ return parsed[3] if parsed else 0.0+++def _gradient_first_color(bg_image: Optional[str]) -> Optional[Tuple[int, int, int]]:+ """First color stop of a CSS gradient (computed style is normalized to rgb()).++ Used to recover the intended color of gradient-clipped ("transparent") text,+ which a single-pixel sample would miss when it lands between glyphs.+ """+ if not bg_image or "gradient" not in bg_image:+ return None+ parsed = _parse_rgba(bg_image)+ return parsed[:3] if parsed else None+++def _has_gradient(el: Dict[str, Any]) -> bool:+ return "gradient" in (el.get("bgImage") or "")+++# CSS keyword directions, as the angle convention used by `linear-gradient`:+# 0deg points up and angles grow clockwise.+_GRADIENT_KEYWORD_DEG = {+ "to top": 0.0,+ "to right": 90.0,+ "to bottom": 180.0,+ "to left": 270.0,+ "to top right": 45.0,+ "to right top": 45.0,+ "to bottom right": 135.0,+ "to right bottom": 135.0,+ "to bottom left": 225.0,+ "to left bottom": 225.0,+ "to top left": 315.0,+ "to left top": 315.0,+}+++def _split_top_level(text: str) -> List[str]:+ """Split on commas that are not inside parentheses (rgb(...) holds its own)."""+ parts: List[str] = []+ depth = 0+ start = 0+ for i, ch in enumerate(text):+ if ch == "(":+ depth += 1+ elif ch == ")":+ depth -= 1+ elif ch == "," and depth == 0:+ parts.append(text[start:i])+ start = i + 1+ parts.append(text[start:])+ return [p.strip() for p in parts if p.strip()]+++def _linear_gradient(+ bg_image: Optional[str],+) -> Optional[Tuple[float, List[Tuple[int, int, int, float]]]]:+ """``(css_angle_deg, stops)`` for a lone CSS ``linear-gradient``, else None.++ Returns None for radial/conic gradients and for stacked multi-layer+ backgrounds — shapes PowerPoint cannot express, whose ink is better left in+ the backdrop than approximated by one flat color.+ """+ value = (bg_image or "").strip()+ if not value.startswith("linear-gradient(") or not value.endswith(")"):+ return None+ inner = value[len("linear-gradient(") : -1]+ tokens = _split_top_level(inner)+ if len(tokens) < 2:+ return None++ angle = 180.0 # CSS default is `to bottom`+ head = tokens[0].lower()+ if not _RGBA_RE.search(tokens[0]) and not tokens[0].startswith("#"):+ if head.endswith("deg"):+ try:+ angle = float(head[:-3])+ except ValueError:+ return None+ elif head in _GRADIENT_KEYWORD_DEG:+ angle = _GRADIENT_KEYWORD_DEG[head]+ else:+ return None # turn/rad units, interpolation hints: not worth guessing+ tokens = tokens[1:]++ stops: List[Tuple[int, int, int, float]] = []+ for token in tokens:+ parsed = _parse_rgba(token)+ if parsed is None:+ return None+ stops.append(parsed)+ if len(stops) < 2:+ return None+ return angle, stops+++_FLEX_DISPLAY_RE = re.compile(r"^(inline-)?(flex|grid)$")+# CSS box-alignment keywords, as the `text-align` value that looks the same.+_ALIGN_KEYWORDS = {+ "center": "center",+ "flex-end": "right",+ "end": "right",+ "right": "right",+ "flex-start": "left",+ "start": "left",+ "left": "left",+}+++def _effective_align(el: Dict[str, Any]) -> str:+ """Horizontal alignment as rendered, not merely as ``text-align`` says.++ A pill that centers its label with ``justify-content`` leaves ``text-align``+ at the inherited ``start``, so reading that alone pins the words to the left+ edge of a box the browser draws them centered in.++ Distribution keywords (``space-between`` and friends) and ``normal`` fall+ through to ``text-align``: with a single run of text they put it at the+ start anyway, which is what the inherited value already says.+ """+ fallback = str(el.get("textAlign") or "start").lower()+ if not _FLEX_DISPLAY_RE.match(str(el.get("display") or "")):+ return fallback+ if "grid" in str(el.get("display") or ""):+ source = el.get("justifyItems") or "normal"+ if str(source).lower() in ("normal", "legacy", "stretch"):+ source = el.get("justifyContent") or "normal"+ elif "column" in str(el.get("flexDirection") or ""):+ # In a column the cross axis is the horizontal one.+ source = el.get("alignItems") or "normal"+ else:+ source = el.get("justifyContent") or "normal"+ return _ALIGN_KEYWORDS.get(str(source).lower(), fallback)+++def _fill_representable(el: Dict[str, Any]) -> bool:+ """Can the element's own background be drawn as a native PowerPoint fill?"""+ if not _has_gradient(el):+ return True+ return _linear_gradient(el.get("bgImage")) is not None+++def _border_sides(el: Dict[str, Any]) -> List[Tuple[float, str]]:+ """Per-side (width, color), in Top/Right/Bottom/Left order.++ Falls back to the scalar top-side pair when the array is absent, so a box+ styled only on, say, its left and bottom edges (an L-shaped corner mark) is+ still recognized as painted instead of being written off as a bare container.+ """+ widths = el.get("borderWidths")+ colors = el.get("borderColors")+ if isinstance(widths, list) and isinstance(colors, list) and len(widths) == len(colors) == 4:+ return list(zip((float(w or 0) for w in widths), colors))+ return [(float(el.get("borderWidth", 0) or 0), el.get("borderColor") or "")] * 4+++def _has_visible_border(el: Dict[str, Any]) -> bool:+ return any(+ w > 0 and _alpha(c) > MIN_VISIBLE_ALPHA for w, c in _border_sides(el)+ )+++def _is_panel(el: Dict[str, Any]) -> bool:+ """A styled box worth reconstructing (native shape or its own picture)."""+ if _alpha(el.get("bgColor")) > MIN_VISIBLE_ALPHA:+ return True+ if (el.get("bgImage") or "none") != "none":+ return True+ if _has_visible_border(el):+ return True+ if (el.get("boxShadow") or "none") != "none":+ return True+ return False+++def _shape_representable(el: Dict[str, Any]) -> bool:+ """Can python-pptx draw this box faithfully as a native rectangle?++ Uniform border, uniform corner radius, no rotation, no gradient fill and no+ pseudo-element decoration. Anything else keeps more fidelity as its own+ picture — still an independent, movable object in the deck. Gradients are+ excluded even when PowerPoint could express them: a two-stop approximation+ of a multi-stop CSS ramp loses to a pixel-exact raster, and an element that+ reaches here has no children to swallow.+ """+ if not el.get("uniformBorder", True):+ return False+ if not el.get("uniformRadius", True):+ return False+ if abs(el.get("rotation", 0.0)) >= MIN_ROTATION_DEG:+ return False+ if _has_gradient(el):+ return False+ if el.get("hasPseudo"):+ return False+ return True+++def classify_elements(elements: List[Dict[str, Any]]) -> Dict[int, str]:+ """Deterministic four-way role assignment.++ ``text`` editable text box (its own fill is emitted as a shape behind it)+ ``shape`` native (rounded) rectangle, children drawn on top+ ``picture`` rasterized on its own transparent canvas -> standalone picture+ ``image`` not reconstructed; whatever ink it has stays in the backdrop+ """+ roles: Dict[int, str] = {}+ for el in elements:+ eid = int(el["id"])+ big = el.get("areaFrac", 1.0) >= MAX_SHAPE_AREA_FRACTION+ if el.get("hasDirectText") and not el.get("hasTextAncestor"):+ roles[eid] = "text"+ elif el.get("isSvg") or el.get("isImg"):+ # Images and inline SVG become their own picture, never a shared backdrop.+ roles[eid] = "image" if big else "picture"+ elif el.get("hasTextAncestor"):+ roles[eid] = "image" # part of an ancestor's text box+ elif _is_panel(el) and not big:+ if el.get("hasRenderableDescendant"):+ # A card stays native so its children draw on top — but only if we+ # can actually paint its own fill. Rasterizing is not an option+ # (it would swallow the children), and flattening an unexpressible+ # gradient to one color turns a faint radial glow into a solid+ # slab, so that ink is left in the backdrop instead.+ roles[eid] = "shape" if _fill_representable(el) else "image"+ else:+ roles[eid] = "shape" if _shape_representable(el) else "picture"+ elif el.get("hasPseudo") and not el.get("hasRenderableDescendant") and not big:+ roles[eid] = "picture" # decoration drawn purely via ::before/::after+ else:+ roles[eid] = "image"+ return roles+++def llm_classify(+ elements: List[Dict[str, Any]],+ full_png: Path,+ fallback: Dict[int, str],+) -> Dict[int, str]:+ """Single LLM(F2) call that may only override the role per element id.++ Coordinates/styles are never sourced from the model. Any missing or invalid+ id falls back to the deterministic decision. Returns ``fallback`` unchanged if+ credentials are absent or the call fails.+ """+ try:+ from ..prompts.loaders import load_prompt+ from ..providers.llm import get_llm++ system = load_prompt("tools/html_to_pptx.md")+ if not system.strip():+ return fallback+ table = [+ {+ "id": el["id"],+ "tag": el["tag"],+ "class": el["className"],+ "w": round(el["w"], 1),+ "h": round(el["h"], 1),+ "hasDirectText": el["hasDirectText"],+ "hasTextAncestor": el["hasTextAncestor"],+ "isSvg": el["isSvg"],+ "text": (el["innerText"] or "")[:60],+ "bgColor": el["bgColor"],+ "bgImage": "gradient" if _has_gradient(el) else "none",+ "borderRadius": round(el["borderRadius"], 1),+ "borderWidth": round(el["borderWidth"], 1),+ "default": fallback.get(int(el["id"])),+ }+ for el in elements+ ]+ user = (+ "Assign a PPTX role to every element id using the attached rendering "+ "as visual context. Roles: 'text' (editable text box), 'shape' (native "+ "rectangle), 'picture' (standalone rasterized image) or 'image' (leave "+ "in the backdrop). Reply with ONLY a JSON object mapping id (string) "+ "-> role.\n\nELEMENTS:\n" + json.dumps(table, ensure_ascii=False)+ )+ content = get_llm().vision(system, user, [str(full_png)])+ parsed = _extract_json_object(content)+ if not isinstance(parsed, dict):+ return fallback+ merged = dict(fallback)+ for key, role in parsed.items():+ try:+ eid = int(key)+ except (TypeError, ValueError):+ continue+ if role in {"text", "shape", "picture", "image"} and eid in merged:+ merged[eid] = role+ return merged+ except Exception:+ return fallback+++def _extract_json_object(text: str) -> Any:+ if not text:+ return None+ stripped = text.strip()+ if stripped.startswith("```"):+ stripped = stripped.strip("`")+ stripped = re.sub(r"^json\s*", "", stripped, flags=re.IGNORECASE).strip()+ start = stripped.find("{")+ end = stripped.rfind("}")+ if start == -1 or end == -1 or end <= start:+ return None+ try:+ return json.loads(stripped[start : end + 1])+ except json.JSONDecodeError:+ return None+++# Blend modes whose purpose is to make the white a raster sits on disappear.+MULTIPLY_BLEND_MODES = {"multiply", "darken"}+++def bake_multiply_to_alpha(png_path: Path) -> bool:+ """Turn a ``mix-blend-mode: multiply`` raster into a plain transparent one.++ White-backed linework relies on multiply to make its background vanish+ against the paper. PowerPoint has no multiply for pictures, and an isolated+ shot blends against nothing, so the white would simply show.++ Multiply and alpha compositing agree when the ink is neutral: for backdrop+ ``d``, ``src*d`` equals ``a*C + (1-a)*d`` with ``C = 0`` and ``a = 1-src``.+ Taking ``m = min(r,g,b)`` as the amount of white to remove generalizes that+ to colored ink — exact over a white backdrop, and exact everywhere once the+ ink is gray, which is what a ``grayscale()`` filter leaves behind.++ Returns whether anything was written.+ """+ try:+ import numpy as np+ from PIL import Image+ except ImportError:+ return False++ with Image.open(png_path) as handle:+ image = handle.convert("RGBA")+ data = np.asarray(image).astype(np.float32) / 255.0+ rgb, alpha = data[:, :, :3], data[:, :, 3]++ white = rgb.min(axis=2) # the neutral part to knock out+ keep = 1.0 - white+ # Un-premultiply the ink against the white it sat on; where there is no ink+ # left the color is irrelevant because the alpha below is zero.+ safe = np.where(keep > 1e-4, keep, 1.0)[:, :, None]+ ink = np.clip((rgb - white[:, :, None]) / safe, 0.0, 1.0)++ out = np.empty_like(data)+ out[:, :, :3] = ink+ out[:, :, 3] = alpha * keep+ Image.fromarray((out * 255.0 + 0.5).astype(np.uint8), "RGBA").save(png_path)+ return True+++def _resolve_canvas(page, canvas_selector: Optional[str]) -> str:+ """Pick the canvas selector: explicit wins, else first that matches exactly once."""+ if canvas_selector:+ count = page.locator(canvas_selector).count()+ if count != 1:+ raise RuntimeError(+ f"expected exactly one {canvas_selector}, found {count}"+ )+ return canvas_selector+ for selector in CANVAS_SELECTORS:+ if page.locator(selector).count() == 1:+ return selector+ raise RuntimeError(+ "no canvas found; pass canvas_selector explicitly "+ f"(tried {', '.join(CANVAS_SELECTORS)})"+ )+++def capture_scene(+ index_path: Path,+ out_dir: Path,+ *,+ canvas_selector: Optional[str] = None,+ use_llm: bool = False,+ scale: int = 2,+ ready_selector: Optional[str] = None,+ prepare_js: Optional[str] = None,+ viewport: Optional[Tuple[int, int]] = None,+) -> Dict[str, Any]:+ """Render, extract, classify, rasterize every picture, and shoot the backdrop.++ ``ready_selector`` waits for a page that signals when it has settled (an+ intro animation, say) before anything is measured. ``prepare_js`` then runs+ in the page just before the canvas is resolved, so a caller can strip page+ chrome or defeat responsive scaling without this module knowing about any+ particular page. ``viewport`` pins the window size for pages that lay+ themselves out against it.+ """+ from playwright.sync_api import sync_playwright++ out_dir.mkdir(parents=True, exist_ok=True)+ parts_dir = out_dir / "parts"+ parts_dir.mkdir(parents=True, exist_ok=True)+ full_png = out_dir / "full.png"+ background_png = out_dir / "background.png"++ with _serve_preview(index_path) as url, sync_playwright() as playwright:+ browser_args = ["--no-sandbox"] if os.environ.get("HTML_TO_PPTX_NO_SANDBOX") == "1" else []+ browser = playwright.chromium.launch(args=browser_args)+ try:+ vw, vh = viewport or (1920, 1080)+ page = browser.new_page(+ viewport={"width": vw, "height": vh},+ device_scale_factor=scale,+ )+ page.goto(url, wait_until="load", timeout=30000)+ try:+ page.evaluate(+ "async () => { if (document.fonts && document.fonts.ready)"+ " { await document.fonts.ready; } }"+ )+ except Exception:+ pass+ if ready_selector:+ page.wait_for_selector(ready_selector, timeout=30000)+ page.wait_for_timeout(400)+ if prepare_js:+ page.evaluate(prepare_js)+ page.wait_for_timeout(200)++ selector = _resolve_canvas(page, canvas_selector)+ canvas = page.locator(selector)+ box = canvas.bounding_box() or {}+ cw = int(math.ceil(box.get("width") or 1920))+ ch = int(math.ceil(box.get("height") or 1080))+ if viewport is None:+ # Size the viewport to the canvas so nothing is clipped or scrolled.+ # Skipped when the caller pinned one: a page that scales itself to+ # fit the window would just shrink again in response.+ page.set_viewport_size({"width": cw, "height": ch})+ page.wait_for_timeout(150)++ extracted = page.evaluate(_EXTRACT_JS, selector)+ if not extracted:+ raise RuntimeError(f"{selector} not found during extraction")+ elements: List[Dict[str, Any]] = extracted["elements"]+ canvas_dims = extracted["canvas"]++ # Crisp full-canvas render used for color sampling.+ canvas.screenshot(path=str(full_png))++ roles = classify_elements(elements)+ if use_llm:+ roles = llm_classify(elements, full_png, roles)++ by_id = {int(el["id"]): el for el in elements}+ shape_ids = [i for i, r in roles.items() if r == "shape"]+ text_ids = [i for i, r in roles.items() if r == "text"]+ picture_ids = [i for i, r in roles.items() if r == "picture"]++ # Deterministic per-textbox shrink so text fits its box under font+ # substitution, independent of the opening app's autofit behavior.+ fit_items = [+ {"id": el["id"], "w": el["w"], "h": el["h"],+ "family": el.get("fontFamily") or ""}+ for el in elements+ if int(el["id"]) in set(text_ids)+ ]+ fit_scales = page.evaluate(_MEASURE_FIT_JS, fit_items) if fit_items else {}+ for el in elements:+ el["fitScale"] = float(fit_scales.get(str(el["id"]), 1.0))++ # --- each picture on its own transparent canvas -------------------+ shot = page.viewport_size or {"width": cw, "height": ch}+ vw, vh = shot["width"], shot["height"]+ rasterized: Dict[int, str] = {}+ for eid in sorted(picture_ids):+ el = by_id[eid]+ # Shoot only the visible slice, so a picture hanging out of a crop+ # is cropped in the deck exactly as the page crops it.+ ox = _clamp(el.get("visVX", el["vx"]), 0.0, float(vw))+ oy = _clamp(el.get("visVY", el["vy"]), 0.0, float(vh))+ clip = {+ "x": ox,+ "y": oy,+ "width": min(el.get("visW", el["w"]), vw - ox),+ "height": min(el.get("visH", el["h"]), vh - oy),+ }+ # Chromium refuses sub-pixel clips; such a sliver is invisible anyway.+ if clip["width"] < 1.0 or clip["height"] < 1.0:+ continue+ page.evaluate(_ISOLATE_JS, {"canvasSel": selector, "id": eid})+ part = parts_dir / f"el_{eid}.png"+ page.screenshot(path=str(part), clip=clip, omit_background=True)+ if str(el.get("mixBlendMode", "normal")).lower() in MULTIPLY_BLEND_MODES:+ bake_multiply_to_alpha(part)+ rasterized[eid] = str(part)+ if picture_ids:+ page.evaluate(_RESET_ISOLATION_JS, selector)+ page.wait_for_timeout(80)++ # --- residual backdrop: only what we could not rebuild -------------+ page.evaluate(+ _NEUTRALIZE_JS,+ {+ "shapeIds": shape_ids,+ "textIds": text_ids,+ "pictureIds": list(rasterized.keys()),+ },+ )+ page.wait_for_timeout(120)+ canvas.screenshot(path=str(background_png))+ finally:+ browser.close()++ for el in elements:+ el["partPng"] = rasterized.get(int(el["id"]), "")++ scene = {+ "canvas": canvas_dims,+ "scale": scale,+ "selector": selector,+ "background_png": str(background_png),+ "full_png": str(full_png),+ "elements": elements,+ "roles": {str(k): v for k, v in roles.items()},+ }+ (out_dir / "scene.json").write_text(+ json.dumps(scene, ensure_ascii=False, indent=2), encoding="utf-8"+ )+ return scene+++# --------------------------------------------------------------------------- #+# PPTX builder+# --------------------------------------------------------------------------- #+++def slide_size_emu(canvas_width: float, canvas_height: float) -> Tuple[int, int]:+ """Slide size preserving the canvas aspect ratio, long edge = LONG_SIDE_IN.++ 1920x1080 -> the familiar 13.333x7.5in 16:9 deck; 1067x1600 -> portrait. The+ scale stays uniform on both axes, so artwork is never stretched.+ """+ cw = max(1.0, float(canvas_width))+ ch = max(1.0, float(canvas_height))+ if cw >= ch:+ win, hin = LONG_SIDE_IN, LONG_SIDE_IN * ch / cw+ else:+ hin, win = LONG_SIDE_IN, LONG_SIDE_IN * cw / ch+ return int(round(win * EMU_PER_INCH)), int(round(hin * EMU_PER_INCH))+++def _sample_box_color(img: Any, el: Dict[str, Any], scale: int) -> Tuple[int, int, int]:+ """Median color of a ring just inside the element's edges.++ Sampling the exact center lands on a glyph whenever the box holds text,+ which used to paint whole pills the color of their own lettering.+ """+ if el.get("clipped"):+ bx, by, bw, bh = el["visX"], el["visY"], el["visW"], el["visH"]+ else:+ bx, by, bw, bh = el["x"], el["y"], el["w"], el["h"]+ x0 = int(bx * scale)+ y0 = int(by * scale)+ x1 = int((bx + bw) * scale)+ y1 = int((by + bh) * scale)+ x0, y0 = max(0, x0), max(0, y0)+ x1, y1 = min(img.width, x1), min(img.height, y1)+ if x1 - x0 < 3 or y1 - y0 < 3:+ px = max(0, min(img.width - 1, (x0 + x1) // 2))+ py = max(0, min(img.height - 1, (y0 + y1) // 2))+ pixel = img.getpixel((px, py))+ return (pixel, pixel, pixel) if isinstance(pixel, int) else tuple(pixel[:3])++ inset_x = max(1, (x1 - x0) // 10)+ inset_y = max(1, (y1 - y0) // 10)+ xs = range(x0 + inset_x, x1 - inset_x, max(1, (x1 - x0) // 24))+ ys = range(y0 + inset_y, y1 - inset_y, max(1, (y1 - y0) // 24))+ samples: List[Tuple[int, int, int]] = []+ for x in xs:+ for y in (y0 + inset_y, y1 - inset_y - 1):+ samples.append(_pixel_rgb(img, x, y))+ for y in ys:+ for x in (x0 + inset_x, x1 - inset_x - 1):+ samples.append(_pixel_rgb(img, x, y))+ if not samples:+ return _pixel_rgb(img, (x0 + x1) // 2, (y0 + y1) // 2)+ samples.sort(key=lambda c: c[0] + c[1] + c[2])+ return samples[len(samples) // 2]+++def _pixel_rgb(img: Any, x: int, y: int) -> Tuple[int, int, int]:+ x = max(0, min(img.width - 1, x))+ y = max(0, min(img.height - 1, y))+ pixel = img.getpixel((x, y))+ if isinstance(pixel, int):+ return pixel, pixel, pixel+ return int(pixel[0]), int(pixel[1]), int(pixel[2])+++def _clamp(value: float, low: float, high: float) -> float:+ return max(low, min(high, value))+++def build_pptx(scene: Dict[str, Any], out_path: Path) -> Dict[str, Any]:+ from PIL import Image+ from pptx import Presentation+ from pptx.dml.color import RGBColor+ from pptx.enum.shapes import MSO_SHAPE+ from pptx.enum.text import MSO_ANCHOR, MSO_AUTO_SIZE, PP_ALIGN+ from pptx.oxml.ns import qn+ from pptx.util import Emu, Pt++ canvas = scene["canvas"]+ scale = int(scene.get("scale", 1))+ roles: Dict[int, str] = {int(k): v for k, v in scene["roles"].items()}+ by_id = {int(el["id"]): el for el in scene["elements"]}++ cw = float(canvas["width"])+ ch = float(canvas["height"])+ slide_w, slide_h = slide_size_emu(cw, ch)+ emu_x = slide_w / cw+ emu_y = slide_h / ch+ # Font/line sizes MUST scale by the same canvas->slide factor as positions.+ # The canvas (e.g. 1920px) is mapped onto 13.333in, so a CSS px is smaller+ # than 1/96in on the slide; using the naive 96dpi px->pt (0.75) makes every+ # font ~1.5x too big for its box. pt = px * EMU_per_px / EMU_per_pt.+ px_to_pt = emu_x / EMU_PER_PT++ def _ex(px: float) -> int:+ return int(round(_clamp(px, 0, cw) * emu_x))++ def _ey(px: float) -> int:+ return int(round(_clamp(px, 0, ch) * emu_y))++ def _ew(px: float) -> int:+ return max(1, int(round(px * emu_x)))++ def _eh(px: float) -> int:+ return max(1, int(round(px * emu_y)))++ align_map = {+ "left": PP_ALIGN.LEFT,+ "start": PP_ALIGN.LEFT,+ "center": PP_ALIGN.CENTER,+ "right": PP_ALIGN.RIGHT,+ "end": PP_ALIGN.RIGHT,+ "justify": PP_ALIGN.JUSTIFY,+ }++ def _set_alpha(fill: Any, rgb: Tuple[int, int, int], alpha: float) -> None:+ fill.solid()+ fill.fore_color.rgb = RGBColor(*rgb)+ if alpha < 1.0:+ solid = fill._xPr.find(qn("a:solidFill"))+ srgb = solid.find(qn("a:srgbClr")) if solid is not None else None+ if srgb is not None:+ node = srgb.makeelement(+ qn("a:alpha"),+ {"val": str(int(_clamp(alpha, 0, 1) * 100000))},+ )+ srgb.append(node)++ def _set_gradient(+ fill: Any,+ angle: float,+ stops: List[Tuple[int, int, int, float]],+ opacity: float,+ ) -> None:+ """Two-stop linear gradient matching the CSS one end to end.++ PowerPoint's UI angle runs counter-clockwise from pointing right, while+ CSS measures clockwise from pointing up.+ """+ fill.gradient()+ slots = fill.gradient_stops+ for slot, rgba, position in (+ (slots[0], stops[0], 0.0),+ (slots[-1], stops[-1], 1.0),+ ):+ slot.color.rgb = RGBColor(*rgba[:3])+ slot.position = position+ alpha = rgba[3] * opacity+ if alpha < 1.0:+ srgb = slot._gs.find(qn("a:srgbClr"))+ if srgb is not None:+ srgb.append(+ srgb.makeelement(+ qn("a:alpha"),+ {"val": str(int(_clamp(alpha, 0, 1) * 100000))},+ )+ )+ fill.gradient_angle = (450.0 - angle) % 360.0++ def _set_run_color(run: Any, rgb: Tuple[int, int, int], alpha: float) -> None:+ """Run color with alpha. python-pptx exposes only opaque RGB, but a faded+ watermark word set fully opaque reads as a solid headline."""+ run.font.color.rgb = RGBColor(*rgb)+ if alpha >= 1.0:+ return+ rpr = run._r.get_or_add_rPr()+ solid = rpr.find(qn("a:solidFill"))+ srgb = solid.find(qn("a:srgbClr")) if solid is not None else None+ if srgb is not None:+ srgb.append(+ srgb.makeelement(+ qn("a:alpha"), {"val": str(int(_clamp(alpha, 0, 1) * 100000))}+ )+ )++ def _set_font(run: Any, name: str) -> None:+ run.font.name = name+ rpr = run._r.get_or_add_rPr()+ for tag in ("a:latin", "a:ea", "a:cs"):+ node = rpr.find(qn(tag))+ if node is None:+ node = rpr.makeelement(qn(tag), {})+ rpr.append(node)+ node.set("typeface", name)++ def _set_tracking(run: Any, points: float) -> None:+ """Letter spacing, in OOXML's hundredths of a point.++ Wide tracking is load-bearing in poster typography — a 29px word set at+ 19px tracking collapses into a different design without it.+ """+ if abs(points) < 0.01:+ return+ run._r.get_or_add_rPr().set("spc", str(int(round(points * 100))))++ prs = Presentation()+ prs.slide_width = Emu(slide_w)+ prs.slide_height = Emu(slide_h)+ slide = prs.slides.add_slide(prs.slide_layouts[6])++ # Bottom layer: only what could not be reconstructed (usually page background).+ slide.shapes.add_picture(+ scene["background_png"], Emu(0), Emu(0), width=Emu(slide_w), height=Emu(slide_h)+ )++ full = Image.open(scene["full_png"]).convert("RGB")++ def _box(el: Dict[str, Any]) -> Tuple[float, float, float, float]:+ """Placement box: the visible slice once clipping ancestors are applied."""+ if el.get("clipped"):+ return el["visX"], el["visY"], el["visW"], el["visH"]+ return el["x"], el["y"], el["w"], el["h"]++ def _copacity(el: Dict[str, Any]) -> float:+ try:+ return _clamp(float(el.get("contentOpacity", 1.0) or 1.0), 0.0, 1.0)+ except (TypeError, ValueError):+ return 1.0++ def _cscale(el: Dict[str, Any]) -> float:+ """Scale that ancestor transforms already applied to the rendered box.++ Boxes are measured post-transform but font/border sizes are not, so both+ have to be multiplied through to stay in proportion.+ """+ try:+ value = float(el.get("contentScale", 1.0) or 1.0)+ except (TypeError, ValueError):+ return 1.0+ return value if value > 0 else 1.0++ def _add_box(el: Dict[str, Any]) -> Any:+ """Native (rounded) rectangle honoring the element's rotation."""+ bx, by, bw, bh = _box(el)+ rot = float(el.get("rotation", 0.0))+ if abs(rot) >= MIN_ROTATION_DEG:+ # The measured box is the axis-aligned bounds of a tilted rectangle,+ # so it is wider and taller than the rectangle itself. PowerPoint+ # rotates about the center: place the unrotated layout box there.+ cs_ = _cscale(el)+ bw, bh = (+ float(el.get("layoutW") or bw) * cs_,+ float(el.get("layoutH") or bh) * cs_,+ )+ bx, by = bx + (_box(el)[2] - bw) / 2.0, by + (_box(el)[3] - bh) / 2.0+ radius = el.get("borderRadius", 0) * _cscale(el)+ auto = MSO_SHAPE.ROUNDED_RECTANGLE if radius > 1 else MSO_SHAPE.RECTANGLE+ shape = slide.shapes.add_shape(auto, _ex(bx), _ey(by), _ew(bw), _eh(bh))+ if radius > 1:+ short_side = max(1.0, min(bw, bh))+ shape.adjustments[0] = _clamp(radius / short_side, 0, 0.5)+ bg = _parse_rgba(el.get("bgColor"))+ border = _parse_rgba(el.get("borderColor"))+ outlined = _has_visible_border(el)+ op = _copacity(el)+ if bg and bg[3] > MIN_VISIBLE_ALPHA:+ _set_alpha(shape.fill, bg[:3], bg[3] * op)+ elif _has_gradient(el):+ gradient = _linear_gradient(el.get("bgImage"))+ if gradient:+ _set_gradient(shape.fill, gradient[0], gradient[1], op)+ else:+ _set_alpha(shape.fill, _sample_box_color(full, el, scale), op)+ elif outlined:+ # Outline-only box (hollow circle, hairline frame): filling it with a+ # sampled color turns a ring into a disc.+ shape.fill.background()+ else:+ _set_alpha(shape.fill, _sample_box_color(full, el, scale), 0.9 * op)+ if outlined and el.get("uniformBorder", True):+ shape.line.color.rgb = RGBColor(*border[:3])+ shape.line.width = Pt(max(0.5, el["borderWidth"] * _cscale(el) * px_to_pt))+ else:+ # Non-uniform borders (a colored top accent over gray sides) cannot be+ # one PPTX outline; each visible edge is drawn separately below.+ shape.line.fill.background()+ shape.shadow.inherit = False+ shape.text_frame.text = ""+ rot = float(el.get("rotation", 0.0))+ if abs(rot) >= MIN_ROTATION_DEG:+ shape.rotation = rot+ return shape++ def _add_border_sides(el: Dict[str, Any]) -> int:+ """Draw each visible edge of a non-uniform border as its own thin bar."""+ widths = el.get("borderWidths") or []+ colors = el.get("borderColors") or []+ if len(widths) != 4 or len(colors) != 4:+ return 0+ cs = _cscale(el)+ widths = [w * cs for w in widths]+ x, y, w, h = _box(el)+ geometry = (+ (x, y, w, widths[0]), # top+ (x + w - widths[1], y, widths[1], h), # right+ (x, y + h - widths[2], w, widths[2]), # bottom+ (x, y, widths[3], h), # left+ )+ made = 0+ for (bx, by, bw_, bh_), width, color in zip(geometry, widths, colors):+ rgba = _parse_rgba(color)+ if width <= 0 or not rgba or rgba[3] <= MIN_VISIBLE_ALPHA:+ continue+ bar = slide.shapes.add_shape(+ MSO_SHAPE.RECTANGLE, _ex(bx), _ey(by), _ew(bw_), _eh(bh_)+ )+ _set_alpha(bar.fill, rgba[:3], rgba[3] * _copacity(el))+ bar.line.fill.background()+ bar.shadow.inherit = False+ bar.text_frame.text = ""+ made += 1+ return made++ shape_count = text_count = picture_count = 0+ # Stacking order: the per-element paint path measured in the page, which+ # nests z-index inside its own stacking context. Falling back to a flat+ # z-index would let a positioned container's fill bury its own children.+ ordered = sorted(+ by_id.values(),+ key=lambda e: (+ list(e.get("paintPath") or [int(e.get("zIndex", 0) or 0)]),+ int(e["id"]),+ ),+ )++ for el in ordered:+ eid = int(el["id"])+ role = roles.get(eid)++ if role == "shape":+ _add_box(el)+ shape_count += 1+ if not el.get("uniformBorder", True):+ shape_count += _add_border_sides(el)++ elif role == "picture":+ part = el.get("partPng")+ if not part or not Path(part).exists():+ continue+ bx, by, bw, bh = _box(el)+ slide.shapes.add_picture(+ part, _ex(bx), _ey(by), width=_ew(bw), height=_eh(bh)+ )+ picture_count += 1++ elif role == "text":+ text = (el.get("innerText") or "").strip()+ if not text:+ continue+ # A badge/pill owns a fill *and* copy: emit the fill, then the words.+ if _is_panel(el):+ _add_box(el)+ shape_count += 1+ if not el.get("uniformBorder", True):+ shape_count += _add_border_sides(el)++ cs = _cscale(el)+ tx, ty, tw, th = _box(el)+ rot = float(el.get("rotation", 0.0))+ if abs(rot) >= MIN_ROTATION_DEG:+ # PowerPoint rotates about the center, so place the *unrotated*+ # box centered on the measured (rotated) bounding box.+ lw = float(el.get("layoutW") or el["w"]) * cs+ lh = float(el.get("layoutH") or el["h"]) * cs+ cx = tx + tw / 2.0+ cy = ty + th / 2.0+ box = slide.shapes.add_textbox(+ _ex(cx - lw / 2.0), _ey(cy - lh / 2.0), _ew(lw), _eh(lh)+ )+ box.rotation = rot+ else:+ box = slide.shapes.add_textbox(_ex(tx), _ey(ty), _ew(tw), _eh(th))++ tf = box.text_frame+ tf.word_wrap = True+ # CSS vertical writing-mode has a direct OOXML counterpart; without it+ # a vertical column of CJK glyphs reflows into horizontal lines.+ vertical = str(el.get("writingMode", "")).startswith("vertical")+ if vertical:+ tf._bodyPr.set("vert", "eaVert")+ # Shrink font to fit the original box so foreign-font substitution+ # cannot wrap text into extra lines that overlap neighbors.+ tf.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE+ tf.margin_left = tf.margin_right = Emu(0)+ tf.margin_top = tf.margin_bottom = Emu(0)+ tf.vertical_anchor = MSO_ANCHOR.MIDDLE++ base = _parse_rgba(el.get("color"))+ if not base or base[3] < 0.1:+ fallback_rgb = _gradient_first_color(el.get("bgImage")) or _sample_box_color(+ full, el, scale+ )+ fallback_alpha = 1.0+ else:+ fallback_rgb = base[:3]+ fallback_alpha = base[3]++ # Only pay the anti-overflow margin when the text actually had to be+ # shrunk; when the real family is available the size stays exact.+ fit_scale = float(el.get("fitScale", 1.0))+ if fit_scale < 1.0:+ fit_scale *= 0.98+ el_size = el.get("fontSize", 16)+ align = align_map.get(_effective_align(el), PP_ALIGN.LEFT)+ # Everything measured in CSS px shares one conversion to points.+ type_scale = cs * px_to_pt * fit_scale+ el_family = str(el.get("fontFamily") or "")+ el_italic = str(el.get("fontStyle", "")) in ("italic", "oblique")+ el_tracking = float(el.get("letterSpacing", 0) or 0)+ line_height = float(el.get("lineHeight", 0) or 0)++ text_opacity = _copacity(el)++ def _run_color(value: Optional[str]) -> Tuple[Tuple[int, int, int], float]:+ parsed = _parse_rgba(value)+ if parsed and parsed[3] >= 0.1:+ return parsed[:3], parsed[3] * text_opacity+ return fallback_rgb, fallback_alpha * text_opacity++ rich = el.get("richText") or []+ if not rich:+ rich = [[{"text": ln}] for ln in text.split("\n")]++ for i, line in enumerate(rich):+ para = tf.paragraphs[0] if i == 0 else tf.add_paragraph()+ para.alignment = align+ # In vertical writing-mode CSS line-height sizes the *column*, not+ # the advance between glyphs; mapping it to OOXML line spacing+ # pushes a single column of CJK into two.+ if line_height > 0 and not vertical:+ para.line_spacing = Pt(line_height * type_scale)+ for seg in line:+ seg_text = seg.get("text", "")+ if seg_text == "":+ continue+ run = para.add_run()+ run.text = seg_text+ seg_size = float(seg.get("size") or el_size)+ run.font.size = Pt(max(1.0, seg_size * type_scale))+ try:+ weight = int(float(seg.get("weight", el.get("fontWeight", 400))))+ except (TypeError, ValueError):+ weight = 700 if str(seg.get("weight")) == "bold" else 400+ run.font.bold = weight >= BOLD_WEIGHT_THRESHOLD+ run.font.italic = bool(seg.get("italic", el_italic))+ _set_run_color(run, *_run_color(seg.get("color")))+ tracking = seg.get("spacing")+ _set_tracking(+ run,+ (el_tracking if tracking is None else float(tracking)) * type_scale,+ )+ family = str(seg.get("family") or el_family)+ if not family:+ # No concrete family survived the CSS chain; keep the old+ # two-font guess so CJK does not land in a Latin face.+ family = "Microsoft YaHei" if _CJK_RE.search(seg_text) else "Arial"+ _set_font(run, family)+ text_count += 1++ out_path.parent.mkdir(parents=True, exist_ok=True)+ prs.save(str(out_path))+ return {+ "shape_count": shape_count,+ "text_count": text_count,+ "picture_count": picture_count,+ }+++def verify_pptx(out_path: Path, expected: Dict[str, Any]) -> Dict[str, Any]:+ """Deterministic sanity check (replaces a repair loop)."""+ from pptx import Presentation+ from pptx.enum.shapes import MSO_SHAPE_TYPE++ prs = Presentation(str(out_path))+ slide = prs.slides[0]+ pictures = text_boxes = shapes = 0+ for shp in slide.shapes:+ if shp.shape_type == MSO_SHAPE_TYPE.PICTURE:+ pictures += 1+ elif shp.has_text_frame and shp.shape_type == MSO_SHAPE_TYPE.TEXT_BOX:+ text_boxes += 1+ else:+ shapes += 1+ report = {+ "pictures": pictures,+ "text_boxes": text_boxes,+ "shapes": shapes,+ "expected_shapes": expected.get("shape_count", 0),+ "expected_text": expected.get("text_count", 0),+ "expected_pictures": expected.get("picture_count", 0) + 1, # + backdrop+ }+ report["ok"] = (+ pictures >= expected.get("picture_count", 0) + 1+ and text_boxes >= expected.get("text_count", 0)+ and shapes >= expected.get("shape_count", 0)+ )+ return report+++def build_editable_pptx(+ index_path: Path,+ out_dir: Path,+ *,+ out_name: str = "slide.pptx",+ canvas_selector: Optional[str] = None,+ use_llm: bool = False,+ scale: int = 2,+ ready_selector: Optional[str] = None,+ prepare_js: Optional[str] = None,+ viewport: Optional[Tuple[int, int]] = None,+) -> Dict[str, Any]:+ """Full pipeline entrypoint. Returns a manifest dict with the pptx path."""+ index_path = Path(index_path)+ out_dir = Path(out_dir)+ scene = capture_scene(+ index_path,+ out_dir,+ canvas_selector=canvas_selector,+ use_llm=use_llm,+ scale=scale,+ ready_selector=ready_selector,+ prepare_js=prepare_js,+ viewport=viewport,+ )+ pptx_path = out_dir / out_name+ counts = build_pptx(scene, pptx_path)+ verification = verify_pptx(pptx_path, counts)+ return {+ "pptx_path": str(pptx_path),+ "background_png": scene["background_png"],+ "scene_json": str(out_dir / "scene.json"),+ "canvas": scene["canvas"],+ "selector": scene["selector"],+ "element_count": len(scene["elements"]),+ **counts,+ "verification": verification,+ }diff --git a/skills/html-to-pptx/scripts/doctor.sh b/skills/html-to-pptx/scripts/doctor.shnew file mode 100755index 0000000..e1c8228--- /dev/null+++ b/skills/html-to-pptx/scripts/doctor.sh@@ -0,0 +1,48 @@+#!/usr/bin/env bash+set -u++failures=0++ok() { printf '%-22s %s\n' "$1" "OK $2"; }+warn() { printf '%-22s %s\n' "$1" "OPTIONAL $2"; }+bad() { printf '%-22s %s\n' "$1" "MISSING $2"; failures=$((failures + 1)); }++printf '%s\n\n' "HTML to PPTX doctor"++if command -v python3 >/dev/null 2>&1; then+ version="$(python3 -c 'import sys; print(".".join(map(str, sys.version_info[:3])))')"+ major="${version%%.*}"+ minor="$(printf '%s' "$version" | cut -d. -f2)"+ if [[ "$major" -gt 3 || ( "$major" -eq 3 && "$minor" -ge 10 ) ]]; then ok "Python" "$version"; else bad "Python" "$version; requires >=3.10"; fi+else+ bad "Python" "requires >=3.10"+fi++for module in playwright pptx PIL numpy; do+ if python3 -c "import $module" >/dev/null 2>&1; then ok "$module" "installed"; else bad "$module" "install requirements.txt"; fi+done++if python3 -c 'import fitz' >/dev/null 2>&1; then warn "PyMuPDF" "installed for comparison"; else warn "PyMuPDF" "install requirements-check.txt for comparison"; fi++soffice="${SOFFICE_PATH:-}"+if [[ -n "$soffice" && -x "$soffice" ]]; then+ warn "LibreOffice" "$soffice"+elif command -v soffice >/dev/null 2>&1; then+ warn "LibreOffice" "$(command -v soffice)"+elif command -v libreoffice >/dev/null 2>&1; then+ warn "LibreOffice" "$(command -v libreoffice)"+elif [[ -x "/Applications/LibreOffice.app/Contents/MacOS/soffice" ]]; then+ warn "LibreOffice" "/Applications/LibreOffice.app/Contents/MacOS/soffice"+else+ warn "LibreOffice" "needed only for visual comparison"+fi++if [[ "${HTML_TO_PPTX_NO_SANDBOX:-0}" == "1" ]]; then warn "Browser sandbox" "disabled by explicit environment setting"; else ok "Browser sandbox" "enabled"; fi++printf '\n'+if [[ "$failures" -eq 0 ]]; then+ printf '%s\n' "Core conversion workflow ready."+ exit 0+fi+printf '%s\n' "Core workflow has $failures missing requirement(s)."+exit 1diff --git a/skills/html-to-pptx/scripts/exploded_to_pptx.py b/skills/html-to-pptx/scripts/exploded_to_pptx.pynew file mode 100755index 0000000..64b0fc2--- /dev/null+++ b/skills/html-to-pptx/scripts/exploded_to_pptx.py@@ -0,0 +1,186 @@+#!/usr/bin/env python3+"""exploded_to_pptx —— case 的 layers.html(图层展开图)→ 一页可编辑 PPTX。++一页幻灯片复刻整张展开图的排布,**去掉 Full overview 那一项**,其余每块(各图层/+分组/背景底)里的元素都重建成独立可拖对象。++用法:+ python3 exploded_to_pptx.py <layers.html> [-o out.pptx] [--keep-overview]++页面自身的三个特性会干扰通用转换器,这里在量画布之前一次性抹平:+ 1. board 会按窗口大小自适应缩放,而转换器又要把视口调成画布大小 —— 两者互相触发,+ 越缩越小。用 !important 规则钉死 transform,压过页面脚本写的 inline style。+ 2. 入场动画期间各块带临时 transform,等 data-hf-exploded-ready 再落位。+ 3. overview 缩略图、扫描光效、replay 按钮属于页面外壳,不是内容。++依赖:playwright(Python) + python-pptx + Pillow。+"""+from __future__ import annotations++import argparse+import importlib.util+import json+import os+import sys+import tempfile+from pathlib import Path++BOARD = ".hf-exploded-board"+READY = "[data-hf-exploded-ready='1']"++# 在页面里跑:抹平自适应缩放、落位、清外壳。+PREPARE_JS = r"""+(opts) => {+ const board = document.querySelector('.hf-exploded-board');+ if (!board) return null;++ // 动画收尾:脚本正常会加这两个 class,这里兜底,避免半路截图+ board.classList.remove('hf-exploded-animating');+ board.classList.add('hf-exploded-settled');+ for (const a of (document.getAnimations ? document.getAnimations() : [])) {+ try { a.finish(); } catch (e) { try { a.cancel(); } catch (e2) {} }+ }+ for (const it of board.querySelectorAll('.hf-exploded-item')) {+ it.style.removeProperty('transform');+ it.style.removeProperty('opacity');+ }++ // 页面外壳:overview 缩略图、扫描光效、replay 按钮+ if (!opts.keepOverview) {+ board.querySelectorAll('[data-exploded-overview]').forEach((n) => n.remove());+ }+ board.querySelectorAll('.hf-exploded-scan').forEach((n) => n.remove());+ document.querySelectorAll('.hf-exploded-replay').forEach((n) => n.remove());++ const w = parseFloat(board.dataset.width) || board.getBoundingClientRect().width;+ const h = parseFloat(board.dataset.height) || board.getBoundingClientRect().height;++ // !important 压过页面 resize() 写的 inline transform(作者 !important 在层叠里+ // 高于 animation,也高于普通 inline),从此 board 恒为 1:1 且贴在原点。+ const css = document.createElement('style');+ css.textContent = `+ html,body{margin:0!important;padding:0!important;display:block!important;+ min-height:0!important;background:transparent!important}+ .hf-exploded-shell{position:static!important;width:${w}px!important;height:${h}px!important;+ transform:none!important;margin:0!important}+ .hf-exploded-board{position:absolute!important;left:0!important;top:0!important;+ transform:none!important;width:${w}px!important;height:${h}px!important}+ .hf-exploded-item{filter:none!important}`;+ document.head.appendChild(css);+ return { width: Math.round(w), height: Math.round(h) };+}+"""++# 只读 board 尺寸和分块清单,不改页面。+PROBE_JS = r"""+() => {+ const board = document.querySelector('.hf-exploded-board');+ if (!board) return null;+ const items = [...board.querySelectorAll('.hf-exploded-item')].map((el) => ({+ name: el.dataset.layerName || '',+ unit: el.dataset.explodedUnit || '',+ overview: !!el.dataset.explodedOverview,+ title: el.getAttribute('title') || '',+ }));+ return {+ width: parseFloat(board.dataset.width) || 0,+ height: parseFloat(board.dataset.height) || 0,+ items,+ };+}+"""+++def _locate_converter():+ """从本 Skill 自带的确定性转换核心加载模块。"""+ vendored = Path(__file__).resolve().with_name("_html_to_pptx.py")+ if vendored.is_file():+ spec = importlib.util.spec_from_file_location("_wca_html_to_pptx", vendored)+ if spec is None or spec.loader is None:+ raise ImportError(f"无法创建转换器加载器: {vendored}")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module++ raise ModuleNotFoundError("缺少本 Skill 的 scripts/_html_to_pptx.py")+++def _browser_args() -> list[str]:+ return ["--no-sandbox"] if os.environ.get("HTML_TO_PPTX_NO_SANDBOX") == "1" else []+++def _probe(src: Path) -> dict:+ """先量一遍 board:拿自然尺寸定视口,顺便报告分块构成。"""+ from playwright.sync_api import sync_playwright++ with sync_playwright() as playwright:+ browser = playwright.chromium.launch(args=_browser_args())+ try:+ page = browser.new_page(viewport={"width": 1600, "height": 1000})+ page.goto(src.resolve().as_uri(), wait_until="load", timeout=30000)+ try:+ page.wait_for_selector(READY, timeout=30000)+ except Exception: # noqa: BLE001+ pass+ return page.evaluate(PROBE_JS)+ finally:+ browser.close()+++def main() -> None:+ ap = argparse.ArgumentParser(description="layers.html 图层展开图 -> 一页可编辑 PPTX")+ ap.add_argument("html", help="case 的 layers.html")+ ap.add_argument("-o", "--out", help="输出 .pptx(默认与输入同目录 layers.pptx)")+ ap.add_argument("--keep-overview", action="store_true", help="保留 Full overview 缩略图")+ args = ap.parse_args()++ src = Path(args.html).resolve()+ if not src.is_file():+ sys.stderr.write(f"找不到文件: {src}\n")+ sys.exit(2)+ out = Path(args.out).resolve() if args.out else src.with_suffix(".pptx")++ try:+ converter = _locate_converter()+ except Exception as exc: # noqa: BLE001+ sys.stderr.write(f"无法加载转换器: {exc}\n")+ sys.exit(1)++ info = _probe(src)+ if not info:+ sys.stderr.write(f"页面里没有 {BOARD},这不是一张图层展开图。\n")+ sys.exit(2)+ kept = [i for i in info["items"] if args.keep_overview or not i["overview"]]+ dropped = len(info["items"]) - len(kept)+ units: dict[str, int] = {}+ for item in kept:+ units[item["unit"]] = units.get(item["unit"], 0) + 1+ print(+ f"board {info['width']:.0f}x{info['height']:.0f} · 分块 {len(kept)} "+ f"(跳过 overview {dropped})· {units}"+ )++ prepare = f"() => ({PREPARE_JS})({json.dumps({'keepOverview': args.keep_overview})})"+ work = Path(tempfile.mkdtemp(prefix="exploded_pptx_"))+ manifest = converter.build_editable_pptx(+ src,+ work,+ out_name=out.name,+ canvas_selector=BOARD,+ use_llm=False,+ ready_selector=READY,+ prepare_js=prepare,+ viewport=(int(info["width"]), int(info["height"])),+ )++ produced = Path(manifest["pptx_path"])+ out.parent.mkdir(parents=True, exist_ok=True)+ out.write_bytes(produced.read_bytes())+ print(+ f"✅ {out}\n 形状 {manifest['shape_count']} · 文本框 {manifest['text_count']} · "+ f"独立图片 {manifest['picture_count']} · 元素 {manifest['element_count']}"+ )+++if __name__ == "__main__":+ main()diff --git a/skills/html-to-pptx/scripts/render_check.py b/skills/html-to-pptx/scripts/render_check.pynew file mode 100755index 0000000..3b1c47e--- /dev/null+++ b/skills/html-to-pptx/scripts/render_check.py@@ -0,0 +1,333 @@+#!/usr/bin/env python3+"""render_check —— 把生成的 PPTX 渲回图片,和源 HTML 比对并给出数值。++产出一张四联图:源 HTML / PPTX 渲回 / 每个独立对象的边界框 / 误差热力图。+第三联验证「元素是否真的各自独立」——框住的每一块在 PowerPoint 里都能单独选中。+第四联把误差最大的几块框出来,并在终端列出坐标与两侧色值,不用靠肉眼找问题在哪。++用法:+ python3 render_check.py <source.html> <out.pptx> [-o compare.png] [--selector .slide-canvas]+ python3 render_check.py <layers.html> <layers.pptx> --exploded++`--exploded` 用于 case 的图层展开图:截图前套用与转换器完全相同的页面预处理+(等动画就绪、删 overview、关响应式缩放),否则基准图里会多出总览图,比对没有意义。++依赖:LibreOffice(渲染 pptx)、PyMuPDF、Pillow、numpy、playwright(Python)、python-pptx。+"""+from __future__ import annotations++import argparse+import os+import shutil+import subprocess+import sys+import tempfile+from pathlib import Path++CANVAS_SELECTORS = (".slide-canvas", ".poster-canvas", "[data-canvas-width]", "#poster")+SOFFICE_CANDIDATES = (+ "/Applications/LibreOffice.app/Contents/MacOS/soffice",+ "/usr/bin/soffice",+ "/usr/bin/libreoffice",+)+OUTLINE_COLORS = {"picture": (232, 62, 62), "text": (32, 120, 235), "shape": (28, 168, 92)}+# Mean channel distance above which a pixel counts as visibly wrong rather than+# as antialiasing or a font-hinting difference.+DIFF_THRESHOLD = 28+# Side of the coarse cell the diff is pooled into before regions are grown. Small+# enough to separate two neighbouring cards, large enough to bridge glyph gaps.+DIFF_CELL = 24+++def _browser_args() -> list[str]:+ return ["--no-sandbox"] if os.environ.get("HTML_TO_PPTX_NO_SANDBOX") == "1" else []+++def _find_soffice() -> str:+ for candidate in (os.environ.get("SOFFICE_PATH"), *SOFFICE_CANDIDATES):+ if candidate and Path(candidate).is_file():+ return candidate+ found = shutil.which("soffice") or shutil.which("libreoffice")+ if found:+ return found+ sys.stderr.write(+ "找不到 LibreOffice(用于把 pptx 渲成图片)。\n"+ " macOS: brew install --cask libreoffice\n"+ " 或用 SOFFICE_PATH 环境变量指定可执行文件路径。\n"+ )+ sys.exit(1)+++def _load_exploded():+ """The展开图 entry point, for its page-prep contract."""+ import importlib.util++ path = Path(__file__).with_name("exploded_to_pptx.py")+ spec = importlib.util.spec_from_file_location("_exploded", path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _shoot_exploded(html: Path, out_png: Path) -> None:+ """Baseline shot of a layers board under the converter's own page prep.++ Shooting the page as it loads would capture the overview tile and a+ half-finished reveal animation, so the comparison would measure the+ difference between two different pictures.+ """+ from playwright.sync_api import sync_playwright++ exploded = _load_exploded()+ with sync_playwright() as playwright:+ browser = playwright.chromium.launch(args=_browser_args())+ page = browser.new_page(viewport={"width": 1600, "height": 1000})+ page.goto(html.resolve().as_uri(), wait_until="load", timeout=30000)+ try:+ page.wait_for_selector(exploded.READY, timeout=30000)+ except Exception: # noqa: BLE001+ pass+ info = page.evaluate(exploded.PROBE_JS)+ page.set_viewport_size(+ {"width": max(1, int(info["width"])), "height": max(1, int(info["height"]))}+ )+ page.wait_for_timeout(400)+ page.evaluate(f"() => ({exploded.PREPARE_JS})({{'keepOverview': false}})")+ page.wait_for_timeout(300)+ page.locator(exploded.BOARD).screenshot(path=str(out_png))+ browser.close()+++def _shoot_html(html: Path, selector: str | None, out_png: Path) -> None:+ from playwright.sync_api import sync_playwright++ with sync_playwright() as playwright:+ browser = playwright.chromium.launch(args=_browser_args())+ page = browser.new_page(viewport={"width": 1920, "height": 1080})+ page.goto(html.resolve().as_uri(), wait_until="load", timeout=30000)+ try:+ page.evaluate(+ "async () => { if (document.fonts && document.fonts.ready)"+ " { await document.fonts.ready; } }"+ )+ except Exception: # noqa: BLE001+ pass+ page.wait_for_timeout(400)+ picked = selector+ if not picked:+ for candidate in CANVAS_SELECTORS:+ if page.locator(candidate).count() == 1:+ picked = candidate+ break+ target = page.locator(picked) if picked else page+ box = target.bounding_box() if picked else None+ if box:+ page.set_viewport_size(+ {"width": max(1, int(box["width"])), "height": max(1, int(box["height"]))}+ )+ page.wait_for_timeout(150)+ target.screenshot(path=str(out_png))+ browser.close()+++def _render_pptx(pptx: Path, work: Path) -> Path:+ soffice = _find_soffice()+ subprocess.run(+ [soffice, "--headless", "--convert-to", "pdf", "--outdir", str(work), str(pptx)],+ check=True,+ capture_output=True,+ timeout=300,+ )+ pdf = work / f"{pptx.stem}.pdf"+ if not pdf.is_file():+ sys.stderr.write(f"LibreOffice 未能生成 PDF: {pdf}\n")+ sys.exit(1)+ import fitz++ doc = fitz.open(pdf)+ png = work / "render.png"+ doc[0].get_pixmap(dpi=150).save(png)+ doc.close()+ return png+++def _outline_objects(render_png: Path, pptx: Path, out_png: Path) -> int:+ from PIL import Image, ImageDraw+ from pptx import Presentation+ from pptx.enum.shapes import MSO_SHAPE_TYPE++ image = Image.open(render_png).convert("RGB")+ prs = Presentation(str(pptx))+ slide = prs.slides[0]+ sx = image.width / prs.slide_width+ sy = image.height / prs.slide_height+ draw = ImageDraw.Draw(image)+ count = 0+ for shape in slide.shapes:+ # The full-bleed fallback backdrop is not an independently editable object.+ if shape.width / prs.slide_width > 0.97 and shape.height / prs.slide_height > 0.97:+ continue+ if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:+ kind = "picture"+ elif shape.shape_type == MSO_SHAPE_TYPE.TEXT_BOX:+ kind = "text"+ else:+ kind = "shape"+ draw.rectangle(+ [+ shape.left * sx,+ shape.top * sy,+ (shape.left + shape.width) * sx,+ (shape.top + shape.height) * sy,+ ],+ outline=OUTLINE_COLORS[kind],+ width=3,+ )+ count += 1+ image.save(out_png)+ return count+++def _worst_regions(bad, top: int):+ """Group flagged cells into regions, largest first.++ A plain breadth-first merge over the coarse grid; connected-component+ labelling would pull in SciPy for a few hundred cells.+ """+ rows, cols = bad.shape+ seen = [[False] * cols for _ in range(rows)]+ regions = []+ for r0 in range(rows):+ for c0 in range(cols):+ if not bad[r0][c0] or seen[r0][c0]:+ continue+ seen[r0][c0] = True+ queue = [(r0, c0)]+ cells = []+ while queue:+ r, c = queue.pop()+ cells.append((r, c))+ for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):+ nr, nc = r + dr, c + dc+ if 0 <= nr < rows and 0 <= nc < cols and bad[nr][nc] and not seen[nr][nc]:+ seen[nr][nc] = True+ queue.append((nr, nc))+ rs = [c[0] for c in cells]+ cs = [c[1] for c in cells]+ regions.append((len(cells), min(cs), min(rs), max(cs) + 1, max(rs) + 1))+ regions.sort(reverse=True)+ return regions[:top]+++def _diff_report(gt_png: Path, render_png: Path, out_png: Path, top: int = 5):+ """Pixel distance between the two panels, plus where the worst of it sits."""+ import numpy as np+ from PIL import Image, ImageDraw++ gt = Image.open(gt_png).convert("RGB")+ rendered = Image.open(render_png).convert("RGB").resize(gt.size, Image.LANCZOS)+ gt_a = np.asarray(gt, dtype=float)+ rd_a = np.asarray(rendered, dtype=float)+ delta = np.abs(gt_a - rd_a).mean(axis=2)++ heat = Image.fromarray(+ np.uint8(np.clip(delta * 3, 0, 255))+ ).convert("RGB")+ draw = ImageDraw.Draw(heat)++ rows = max(1, delta.shape[0] // DIFF_CELL)+ cols = max(1, delta.shape[1] // DIFF_CELL)+ pooled = delta[: rows * DIFF_CELL, : cols * DIFF_CELL]+ pooled = pooled.reshape(rows, DIFF_CELL, cols, DIFF_CELL).mean(axis=(1, 3))+ bad = pooled > DIFF_THRESHOLD++ found = []+ for _, c0, r0, c1, r1 in _worst_regions(bad, top):+ x0, y0, x1, y1 = c0 * DIFF_CELL, r0 * DIFF_CELL, c1 * DIFF_CELL, r1 * DIFF_CELL+ draw.rectangle([x0, y0, x1, y1], outline=(255, 90, 40), width=3)+ found.append(+ (+ (x0, y0, x1 - x0, y1 - y0),+ tuple(int(v) for v in gt_a[y0:y1, x0:x1].mean(axis=(0, 1))),+ tuple(int(v) for v in rd_a[y0:y1, x0:x1].mean(axis=(0, 1))),+ )+ )+ heat.save(out_png)+ return float(delta.mean()), float((delta > DIFF_THRESHOLD).mean() * 100), found+++def _compose(panels: list[tuple[str, Path]], out_png: Path) -> None:+ from PIL import Image, ImageDraw++ height = 860+ images = []+ for label, path in panels:+ img = Image.open(path).convert("RGB")+ images.append((label, img.resize((round(img.width * height / img.height), height))))+ pad, bar = 14, 28+ total = sum(i.width for _, i in images) + pad * (len(images) + 1)+ canvas = Image.new("RGB", (total, height + bar + pad * 2), (28, 30, 34))+ draw = ImageDraw.Draw(canvas)+ x = pad+ for label, img in images:+ draw.text((x, 8), label, fill=(240, 240, 240))+ canvas.paste(img, (x, bar))+ x += img.width + pad+ canvas.save(out_png)+++def main() -> None:+ ap = argparse.ArgumentParser(description="PPTX 渲回图片,与源 HTML 三联比对")+ ap.add_argument("html", help="源 slide/poster HTML")+ ap.add_argument("pptx", help="to_pptx.py 产出的 .pptx")+ ap.add_argument("-o", "--out", help="输出对比图(默认 pptx 同目录 <name>.compare.png)")+ ap.add_argument("--selector", default=None, help="画布选择器(默认自动识别)")+ ap.add_argument(+ "--exploded",+ action="store_true",+ help="源文件是 case 的图层展开图 layers.html,截图前套用转换器同款页面预处理",+ )+ args = ap.parse_args()++ html = Path(args.html).resolve()+ pptx = Path(args.pptx).resolve()+ for path in (html, pptx):+ if not path.is_file():+ sys.stderr.write(f"找不到文件: {path}\n")+ sys.exit(2)+ out = Path(args.out).resolve() if args.out else pptx.with_suffix(".compare.png")++ work = Path(tempfile.mkdtemp(prefix="render_check_"))+ gt = work / "gt.png"+ if args.exploded:+ _shoot_exploded(html, gt)+ else:+ _shoot_html(html, args.selector, gt)+ render = _render_pptx(pptx, work)+ outlined = work / "outlined.png"+ count = _outline_objects(render, pptx, outlined)+ heat = work / "heat.png"+ mean, over, regions = _diff_report(gt, render, heat)++ _compose(+ [+ ("源 HTML", gt),+ ("PPTX 渲回", render),+ (f"{count} 个独立可编辑对象(红=图片 蓝=文本框 绿=形状)", outlined),+ (f"误差热力图 平均 {mean:.2f} 超阈值 {over:.2f}%", heat),+ ],+ out,+ )+ print(f"✅ {out}")+ print(f" 独立对象 {count} 个(不含整页兜底背景)")+ print(f" 平均像素差 {mean:.2f} 超阈值占比 {over:.2f}%")+ if regions:+ print(" 误差最大的区域(源图坐标 x,y,w,h):")+ for (x, y, w, h), gt_rgb, rd_rgb in regions:+ print(f" ({x},{y},{w},{h}) 源 rgb{gt_rgb} → pptx rgb{rd_rgb}")+ else:+ print(" 没有超出阈值的区域")+++if __name__ == "__main__":+ main()diff --git a/skills/html-to-pptx/scripts/to_pptx.py b/skills/html-to-pptx/scripts/to_pptx.pynew file mode 100755index 0000000..9f453b0--- /dev/null+++ b/skills/html-to-pptx/scripts/to_pptx.py@@ -0,0 +1,85 @@+#!/usr/bin/env python3+"""to_pptx —— slide / poster HTML → 可编辑 PPTX(离线、纯确定性、无服务、无 LLM)。++复用仓库现成的 ``build_editable_pptx(use_llm=False)``:自动识别画布(``.slide-canvas``+/ ``.poster-canvas`` / ``[data-canvas-width]`` / ``#poster``)、按真实宽高比定幻灯片+尺寸 → 量每个元素盒子/样式 → 四分类(text/shape/picture/image) → python-pptx 生成。+每个视觉元素(图标、箭头、插画)都是独立可拖动对象,而不是压成一张背景图。++用法:+ python3 to_pptx.py <slide-or-poster.html> [-o out.pptx] [--selector .slide-canvas]++约定:+ · 传编辑器「下载 HTML」导出的 slide.edited.html,或原始 index.html。+ **不要**传 editor.html(那里含编辑器外壳,会被一起拍进去)。+ · 相对资源(css/字体/图片)按 HTML 所在目录解析,所以在原目录里跑最稳。++依赖(与 harness 一致):playwright(Python) + python-pptx + Pillow。+"""+from __future__ import annotations++import argparse+import importlib.util+import sys+import tempfile+from pathlib import Path+++def _locate_converter():+ """从本 Skill 自带的确定性转换核心加载 ``build_editable_pptx``。"""+ vendored = Path(__file__).resolve().with_name("_html_to_pptx.py")+ if vendored.is_file():+ spec = importlib.util.spec_from_file_location("_wca_html_to_pptx", vendored)+ if spec is None or spec.loader is None:+ raise ImportError(f"无法创建转换器加载器: {vendored}")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module.build_editable_pptx++ raise ModuleNotFoundError("缺少本 Skill 的 scripts/_html_to_pptx.py")+++def main() -> None:+ ap = argparse.ArgumentParser(description="slide / poster HTML -> 可编辑 PPTX(离线确定性)")+ ap.add_argument("html", help="slide/poster HTML(*.edited.html 或 index.html,勿传 editor.html)")+ ap.add_argument("-o", "--out", help="输出 .pptx(默认与输入同目录同名)")+ ap.add_argument("--selector", default=None, help="画布选择器(默认自动识别)")+ args = ap.parse_args()++ src = Path(args.html).resolve()+ if not src.is_file():+ sys.stderr.write(f"找不到文件: {src}\n")+ sys.exit(2)++ out = Path(args.out).resolve() if args.out else src.with_suffix(".pptx")++ try:+ build_editable_pptx = _locate_converter()+ except Exception as exc: # noqa: BLE001+ sys.stderr.write(+ "无法加载转换器 build_editable_pptx。\n"+ f" 原因: {exc}\n"+ " 请确认 Skill 文件完整,并安装 requirements.txt。\n"+ )+ sys.exit(1)++ work = Path(tempfile.mkdtemp(prefix="to_pptx_"))+ manifest = build_editable_pptx(+ src, work, out_name=out.name, canvas_selector=args.selector, use_llm=False+ )+ produced = Path(manifest["pptx_path"])+ out.parent.mkdir(parents=True, exist_ok=True)+ out.write_bytes(produced.read_bytes())+ canvas = manifest.get("canvas") or {}+ print(+ f"✅ {out}\n 画布 {canvas.get('width', 0):.0f}x{canvas.get('height', 0):.0f}"+ f" ({manifest.get('selector')}) · 形状 {manifest.get('shape_count')} · "+ f"文本框 {manifest.get('text_count')} · 独立图片 {manifest.get('picture_count')} · "+ f"元素 {manifest.get('element_count')}"+ )+ if not manifest.get("shape_count") and not manifest.get("text_count"):+ print(" ⚠️ 未重建出可编辑形状/文本(多为纯 SVG slide,整页折成背景图,仍是合法 pptx)")+++if __name__ == "__main__":+ main()