12 个视觉参考图库与浏览器无限画布 AI 创作台(5,700+ 素材、中英提示词、多图对比、ComfyUI & MCP)· Visual reference library & infinite-canvas AI studio in the browser
JavaScript ai-artai-try-onchinesecloudflare-pagescomfyuidrawing-referencefashiongeminigpt-imageimage-generationinfinite-canvasmcpmoodboardoutfit-referencepose-referencepromptpwareference-boardseedreamvirtual-try-on
Release v1.3.0: paired pose views, creative studio and local generation
atuizzcbe532b75c27
diff --git a/.agents/skills/posewear/SKILL.md b/.agents/skills/posewear/SKILL.mdnew file mode 100644index 0000000..09944d8--- /dev/null+++ b/.agents/skills/posewear/SKILL.md@@ -0,0 +1,11 @@+---+name: posewear+description: Use PoseWear to find pose, outfit, portrait, expression, hairstyle, setting or lighting references and assemble an image-generation prompt with the exact reference image URLs. Use when someone wants to pick, combine or hand off visual references from 衣姿.+---++1. For a request without a specific item ID, call `posewear_search_references` with the user's search terms. Scope a query with the `collection` field. Call `posewear_list_collections` to discover the available libraries.+2. Call `posewear_get_reference` for promising items. Look at `angles` when a viewpoint or hair color matters. Pass its zero-based `angle` to select the view. Single-view items use angle 0.+3. Call `posewear_compose_brief` with the chosen `{collection, id, angle}` records in the user's order. Set `language` to `zh` or `en`. Supply `prompt` to keep the user's wording or omit it to combine the catalog descriptions.+4. The returned `brief` is ready to share. To use an image model that accepts references, pass the ordered `references[].url` values to its image-input field. Follow the user's choice of model and ordinary approval for a paid generation. PoseWear's four tools read catalog data and URLs; the generation service handles rendering.++CharaDB hairstyles and some anime outfits are hotlinked. Keep those image URLs at their original host. Uploaded personal photos stay in the browser. Ask for a separate attachment if a user’s brief mentions a local photo.diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlnew file mode 100644index 0000000..26c0365--- /dev/null+++ b/.github/workflows/test.yml@@ -0,0 +1,16 @@+name: Tests+on: [push, pull_request]+permissions:+ contents: read+jobs:+ offline:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 24+ cache: npm+ - run: npm ci+ - run: npx playwright install --with-deps chromium+ - run: npm run test:offlinediff --git a/AGENTS.md b/AGENTS.mdindex 62db7a0..0783f54 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -18,26 +18,39 @@| `seo.py` | 每库/每条目的静态 SEO 落地页 || `src/index.html` | 单页骨架(所有栏目、试穿台、托盘、弹窗的 DOM 都在这里) || `src/app.js` | 图库 SPA:栏目切换、筛选、卡片、灯箱、收藏、组合与**悬浮生图工作台**(托盘) |-| `src/studio.js` | 试穿/生图核心:服务商协议(OpenAI/Gemini/Seedream/xAI/自定义中转)、生成管线、素材选择器(picker)、配置弹窗;对外接口是 `window.WB` |+| `src/references.js` | 浏览器与 MCP 共用选定视角、公开图片地址与复制文本的格式 |+| `src/i18n.js` | 中英日界面词条与语言切换,`pwUiLocale` 独立于提示词设置 |+| `src/studio.js` | 工作台选材、提示词、生成与结果;对外接口是 `window.WB` |+| `src/image-providers.js` | 悬浮及完整工作台共用的生图服务商协议、连接测试和错误解析 |+| `src/theme.js` | 首屏外观、系统主题与用户选择的同步 || `src/history.js` | 生成记录页(数据在浏览器 IndexedDB `lk-studio` 的 `h` 表,上限 200 条) || `src/extras.js` | `window.X` 工具(下载、ZIP 等);`src/zip.js` 打包 |-| `functions/api/proxy.js` | Pages Function:CORS 转发代理(只许本站来源、官方域名限标准 https、自定义中转放行任意端口、内网地址黑名单) |+| `functions/api/proxy.js` | Pages Function:CORS 转发代理(只许本站来源、官方域名限标准 https、自定义 HTTPS 中转按部署变量 POSEWEAR_PROXY_ORIGINS 精确匹配来源和端口) || `scripts/fetch-assets.py` | 从上游站抓素材到 `assets-raw/`(低并发,勿反复全量抓) || `scripts/prep-modules.py` | 新模块(表情/发型等)素材预处理 || `scripts/sync-r2.py` | 把图片目录同步到 R2(断点续传,见下) |-| `tests/` | Playwright 回归(见「测试」) |+| `scripts/catalog-source.mjs` | 本地预览与 MCP 共用的公开目录发现、指纹校验与读取 |+| `mcp/server.mjs` · `.agents/skills/posewear/` | 只读 stdio MCP 与项目选图 Skill。[接入与工具](mcp/README.md) |+| `scripts/local-engine.mjs` | 本地预览的 ComfyUI / stable-diffusion.cpp 适配。[引擎设置与工作流](docs/local-engines.md) |+| `tests/` | 浏览器、协议与构建回归(见「测试」) |## 构建与部署(标准流程,勿改顺序)```bash-python3 scripts/fetch-assets.py # 首次或素材更新时-POSEWEAR_ASSET_HOST=https://pwimg.0vo.pro python3 build.py # 约 7–16 分钟,产物 dist/(约 15,498 文件)-cp -r dist /tmp/staging # 关键:从副本测试与部署,别直接动 dist-python3 tests/check_csp.py /tmp/staging # CSP 守卫,必须 PASS-# 起本地服务跑回归(见下),全绿后:-npx wrangler pages deploy /tmp/staging --project-name posewear --branch main+# 日常开发可直接 npm ci && npm start,预览会联网加载已发布的 12 份目录。+# 从原始素材构建时,先在独立 Python 环境安装 Pillow,再准备素材:+python3 -m pip install Pillow+python3 scripts/fetch-assets.py+python3 scripts/prep-modules.py --archive /path/to/posewear-assets-archive --snapshots /path/to/pw-modules+POSEWEAR_ASSET_HOST=https://pwimg.0vo.pro python3 build.py+export POSEWEAR_STAGING="$(mktemp -d "${TMPDIR:-/tmp}/posewear-staging.XXXXXXXX")"+cp -R dist/. "$POSEWEAR_STAGING/"+python3 tests/check_csp.py "$POSEWEAR_STAGING"+# 在此副本完成下方回归后,从项目根目录发布同一副本:+npm run deploy```+- 缺扩展档案时可用 `python3 build.py --allow-partial` 本地开发;带缺库标记的产物不能通过发布检查。- **`--branch main` 不可省**:wrangler 按本地 git 分支决定部署目标,漏了会静默发到分支预览、生产不变。部署后必须线上验活(见清单),不能只看 deploy 成功。- Pages 单站上限 20,000 文件;`POSEWEAR_ASSET_HOST` 让缩略图/原图走 R2,主站文件数才压得住。- wrangler 用 OAuth 登录态(约 1 小时过期):过期时 whoami 报未登录是假象,用 refresh_token 向 `https://dash.cloudflare.com/oauth2/token` 刷新(client_id `54d11594-84e4-41aa-b438-e81b8fa78ee7`,**必须带浏览器 UA**,否则 403/1010),或给 wrangler 传 `CLOUDFLARE_API_TOKEN` 环境变量。@@ -46,27 +59,34 @@ npx wrangler pages deploy /tmp/staging --project-name posewear --branch main### 部署后线上验活清单-1. 首页 200,公告/统计数字与本次改动一致;+1. 首页 200,铃铛内的公告及素材库菜单中的统计数字与本次改动一致;2. 线上 `/assets/*.js` 哈希与 staging 一致,关键新代码字符串能 grep 到;3. 响应头 CSP 的 img-src 覆盖全部图片源站(含热链站);4. 任选一库 JSON 条数正确;样本图各一张:pwimg 的 t/o 各 200、同源 m 200、热链图 200;5. `curl -X OPTIONS https://posewear.pages.dev/api/proxy` 返回 204;6. 本次改动的功能点在生产页面实际点一遍(或用线上地址跑对应测试套件)。+开发预览的静态 SEO 路由优先读本地 `dist/`,可用 `POSEWEAR_STAGING=/absolute/path npm start` 指向构建副本。没有对应本地页时会读取发布站版本。+## 数据与素材- 上游五站同作者 @giaaibusi(人像 @agi_aibusi,CC0);深度姿势数据在 `depth/packs/`(已入库);新模块素材档案在维护者本地 `posewear-assets-archive/`(不在仓库)。- 发型与部分动画服装来自 CharaDB:**图片只能热链**(`charadb-2fi.pages.dev`),禁止再分发、不要下载进 R2/dist。-- 新增热链数据源时必须同步 CSP:`build.py` 会从 CharaDB 数据自动收集源站写入 img-src/connect-src,新数据源要照此处理,并跑 `tests/check_csp.py` 守卫(2026-11-23 发型库全灭就是漏了这一步)。+- 新增热链数据源时必须同步 CSP:`build.py` 会从 CharaDB 数据自动收集源站写入 img-src,connect-src 允许 HTTPS 以支持自定义直连,图片展示仍限指定来源。新数据源要照此处理,并跑 `tests/check_csp.py` 守卫(2026-11-23 发型库全灭就是漏了这一步)。- 条目数据字段:`t/m/i/o` 是四档图片路径,`ext=1` 表示热链外站图,`ref` 为 referrerpolicy。## 测试```bash-npm i # 装 playwright + wrangler(devDependencies)-python3 -m http.server 8902 -d <staging目录> &-CHROME_PATH=<playwright chromium 路径> NODE_PATH=$PWD/node_modules U=http://localhost:8902 \- node tests/v13.js # 其余套件同理+npm ci+npx playwright install chromium+# 在没有素材档案和 staging 的源码目录也可执行+npm run test:offline+# 完整站点回归请使用上面准备的 staging+# 终端一,从 staging 加载 Pages 响应头和 Functions+npx wrangler pages dev "$POSEWEAR_STAGING" --cwd "$POSEWEAR_STAGING" --ip 127.0.0.1 --port 8902 --compatibility-date 2026-11-19+# 终端二,从项目根目录运行(使用已有浏览器时可设置 CHROME_PATH)+U=http://127.0.0.1:8902 npm test```| 套件 | 覆盖 |@@ -78,21 +98,25 @@ CHROME_PATH=<playwright chromium 路径> NODE_PATH=$PWD/node_modules U=http://lo| v16-proxy | 代理函数单元测试(node 直跑 `.mjs`,不起浏览器) || v17-history | 生成记录页冒烟 || v18-quick | 悬浮工作台:常驻入口、面板内加素材、托盘内生图全流程 |+| mcp-regressions / reference-regressions | stdio 握手与真实工具调用、指定角度、单条及组合提示词的参考图地址 |+| local-engine-regressions | 本机引擎状态、ComfyUI 工作流、sd.cpp 协议与请求边界 |+- `tests/run.mjs` 按顺序执行 v12–v18 和专项回归(图库、工作台、界面语言等),任一失败会返回非零退出码。- 测试用 route 拦截把服务商 API 全部 mock 掉(fixtures 是本地假图),不消耗真实额度;**不要**改成真调。- 已知环境坑:受限沙箱里 Chromium 经代理加载外站图片会 `ERR_TUNNEL_CONNECTION_FAILED`,v15 有 9 项这类基线失败(卡片渲染/页面错误断言),与改动无关;判断回归要和改版前基线逐项对比,新增失败才算回归。- 改 studio 生成管线必须保 v13 全绿;改托盘/工作台保 v18 全绿。## 关键机制速记-- **悬浮生图工作台**(app.js 托盘 + studio.js):右下角常驻按钮 `#trayFab` 打开面板;面板内「添加素材」经 `WB.openPicker(type, sink)` 复用 studio 的选择器往组合里加;组合经 `WB.setSel` 同步进试穿台槽位(服装/动画/历代→服装≤2,姿势/深度→姿势≤6,人像→人物≤1,表情≤1,其余类型只进提示词补充段);生成走 `WB.quick(opts)` = studio `run()` 的 quick 模式(跳过试穿台 UI、结果回托盘并存入生成记录)。试穿台本体是「完整工作台」,两者共用一套生成核心,不要另起炉灶。-- 服务商配置存 localStorage `wbCfg`;Key 只在浏览器,永不入库、永不上传本站。-- 公告条关闭键带版本号(当前 `annV2`):换公告内容时记得 bump 键名,否则关过旧公告的用户看不到新公告。+- **悬浮生图工作台**(app.js 托盘 + studio.js):点击 `#trayFab` 展开工作台,浏览、切换素材库时面板保持打开。收起后,创作条保留已选素材缩略图。面板内「添加素材」经 `WB.openPicker(type, sink)` 复用 studio 的选择器往组合里加;仅在转入完整工作台时由 `WB.setSel` 同步槽位(服装/动画/历代→服装≤2,姿势/深度→姿势≤6,人像→人物≤1。表情≤1,发型、场景、光影、道具和家具归入「其他素材」,均以参考图随生成请求发送);生成走 `WB.quick(opts)` = studio `run()` 的 quick 模式(跳过试穿台 UI、结果回托盘并存入生成记录)。试穿台本体是「完整工作台」,两者共用一套生成核心,不要另起炉灶。+- 需要代理自定义 HTTPS 服务时,通过部署变量 `POSEWEAR_PROXY_ORIGINS` 登记其完整来源(含端口),多个来源以空格或逗号分隔。服务商配置存 localStorage `wbCfg`;配置只持久化在浏览器。直连时密钥与图片发往所选服务,启用代理时本站 Function 经手并转发请求,不保存请求内容。+- 公告、应用更新和最近操作由 `#noticeMenu` 集中展示。素材来源与许可位于页脚 `#credits`。+- `copyRefs` 默认开启。卡片、灯箱、悬浮及完整工作台复用同一参考图格式。保留选定的 `angles` 视角和原站热链,本地上传图在复制文本中提示用户另附。- localStorage 键:`wbCfg`、`wbSel`(试穿台选材)、`sel`(组合)、`fav`、`theme`、`lang` 等,改名即丢用户数据,慎改。## 约定-- UI 文案简体中文;品牌红 `#ff2442` 点缀、白底干净、**不用黄色/金色**;页面忌文字堆砌。+- 默认 UI 文案简体中文,同时维护英文、日文词条;品牌红 `#ff2442` 点缀、白底干净、**不用黄色/金色**;页面忌文字堆砌。- 提交:显式列文件路径提交,**不要 `git add -A`**(工作区常有 dist-assets 等大目录未跟踪)。- 发版:三语 README 更新日志各加一条(中/英/日),GitHub Release 用 API 建,tag 形如 `v1.2.1`。- 生产红线:部署、合并 PR、回议题已获维护者长期授权(2026-11-22);新功能/动架构/花钱的事先问维护者。diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..88bd565--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,159 @@+# PoseWear · 版本记录 · Release notes · 更新履歴++[简体中文](#zh) · [English](#en) · [日本語](#ja)++<a id="zh"></a>++## 简体中文++### 2026-11-24 · v1.3.0++- 在姿势卡片上点编号,可在同一机位的线稿和深度图之间翻面。复制单条或组合提示词会附上所选角度的参考图链接。+- 展开悬浮工作台后仍可浏览图库、切换分类、继续选图。完整工作台默认展示人物、服装和姿势,其余参考图集中在「其他素材」。刷新后可恢复手改提示词、张数和比例。+- 界面支持简体中文、英文和日文。手机支持触屏选材,外观可设为跟随系统、浅色或深色。+- 本地工作台可连接 ComfyUI 或 stable-diffusion.cpp。ComfyUI 内置工作流接受一张参考图,多图可使用自定义工作流。智能体可通过只读 MCP 和选图 Skill 搜索图库、选取机位并组合提示词。++### 2026-11-23 · v1.2.1++- 组合托盘升级为常驻「生图工作台」:常驻悬浮按钮(带已选数量徽章),随时打开拼装;面板内可直接「添加素材」(服装、动画服装、姿势、人像、表情),不必先回图库点选;空组合时有明确的空状态引导。+- 新增 `AGENTS.md` 开发交接手册与 `scripts/sync-r2.py`(R2 图片同步脚本),仓库可完整交付他人接手开发。++### 2026-11-23 · v1.2.0++- 组合托盘新增「简易生图」:在图库里选好服装、姿势、人像、表情,托盘里直接生成图片(可改提示词、选张数和比例),结果可看大图、下载,并自动存入生成记录,不必先进试穿工作台。+- 试穿台打磨:去掉右栏中部的空白占位,生成结果自动滚入视野。+- 全站文案与数据校正:动画服装数量 1320 → 1760(首页统计、meta、公告、页脚统一),页脚补 CharaDB 致谢,隐私说明改正深度姿势分发方式;托盘加高度上限、手机端公告限两行。+- 新增 `tests/v18-quick.js` 覆盖托盘生图全流程。++### 2026-11-23 · v1.1.0++- 修复发型库与动画服装中 CharaDB 部分的图片全部加载失败:本站 CSP 的 `img-src` 白名单漏了热链源站,浏览器直接拦截。构建时改为自动收集数据里的热链源站写入白名单,并新增 `tests/check_csp.py` 守卫,构建后校验全部图片源站。+- 本页 README 同步到当前功能(英文、日文版同步更新)。++### 2026-11-22 · 生成记录页、代理与 Gemini 协议++- 新增「生成记录」页(@OrangeSAM 贡献):全选批量打包、导出 ZIP(含提示词与参数元数据)、单张重新生成、大图与原图前后对比;记录上限 200 条。+- 修复代理开关对自定义中转不生效:未勾选代理时中转请求直连;代理放行自定义中转的任意端口(官方域名仍限标准 HTTPS,内网地址仍拒绝)。+- 自定义中转新增 Gemini 协议:可选 `models/:generateContent` 调用,鉴权头按协议自动切换。+- 页头宽屏遮挡修复(@yansiao1227 贡献)。++### 2026-11-21 · 七个扩展库上线、图片迁入 R2++- 新增七个栏目:表情 95、发型 122(CharaDB,图片热链原站)、历代服装 57、场景 64、光影 50、道具 32、家具 41;动画服装并入 CharaDB 的 440 套,总数增至 **1760 套**。+- 全站图片改由 Cloudflare R2(`pwimg.0vo.pro`)分发;深度姿势图片改为本站自存,不再热链原站,加载更稳定。+- 修复 Seedream 5.x 参数错误导致生图失败(@COBEZE 贡献):参数改为仅对 4.x 模型发送。++### 2026-11-19 · 动画服装库上线++- 新增「动画服装」栏目:接入上游 COSTUME-ANIME-DB([@giaaibusi](https://x.com/giaaibusi))的 **1320 套**动画风穿搭,与写实服装同为 8 个分类(春 197 / 夏 237 / 秋 230 / 冬 232 / 内衣 197 / 派对礼服 36 / 泳装 52 / 性感 139),每套附中英文提示词。+- 内衣、性感类共 336 套按成人内容处理:默认隐藏,打开顶部「18+」开关后显示(默认公开 984 套)。+- 动画服装支持服装库的全部功能:分类 / 颜色 / 单品筛选、搜索建议、收藏、最近浏览、组合提示词、中英双语详情页与 sitemap;试穿工作台的服装步骤可直接「从动画服装选」。+- 首页新增上线公告条与动画服装计数,页脚与隐私说明补齐来源致谢;`scripts/fetch-assets.py` 新增 `anime` 数据源(顺带修复写实服装漏抓缩略图的问题)。++### 2026-10-31 · 深度姿势++- 新增「深度姿势」栏目:热链上游深度姿势图 288 组 / 1439 张,双人图走 18+ 开关。++<a id="en"></a>++## English++### 2026-11-24 · v1.3.0++- Click a pose card’s ID to flip between its line drawing and depth map at the same camera angle. Copying a single or mixed prompt includes image links for the selected views.+- Keep the floating studio open while browsing, switching collections and adding references. The full studio groups portraits, outfits and poses first, with other materials in one section. Edited prompts, image count and aspect ratio survive a refresh.+- Choose Simplified Chinese, English or Japanese, and use the touch controls to pick references on a phone. Appearance can follow the system or use light or dark mode.+- Connect the local studio to ComfyUI or stable-diffusion.cpp. The included ComfyUI workflow accepts one reference image. Custom workflows can use multiple images. The read-only MCP server and reference selection skill let agents search the gallery, choose views and assemble prompts.++### 2026-11-23 · v1.2.1++- The combo tray is now a persistent floating "Image Workbench": a floating button (with a selected-count badge) opens it from anywhere; you can add materials (outfits, anime outfits, poses, portraits, expressions) right inside the panel via the picker, with a clear empty state to get started.+- Added `AGENTS.md` (developer handover manual) and `scripts/sync-r2.py` (R2 image sync) so the repo can be handed over wholesale.++### 2026-11-23 · v1.2.0++- The combo tray now generates images directly: pick outfits, poses, portraits and expressions in the galleries, then generate right inside the tray (editable prompt, count and aspect ratio). Results open full-size, download, and are saved to the generation history automatically — no trip to the studio required.+- Studio polish: removed the empty spacer in the right column; results scroll into view when ready.+- Site-wide copy and data corrections: anime outfits 1320 → 1760 (hero stats, meta, announcement, footer), CharaDB credited in the footer, privacy note corrected for depth-pose delivery; tray height capped with internal scrolling, announcement clamped to two lines on mobile.+- New `tests/v18-quick.js` covers the full tray generation flow.++### 2026-11-23 · v1.1.0++- Fixed every hairstyle image (and the CharaDB part of anime outfits) failing to load: the site's CSP `img-src` allowlist was missing the hotlinked origin, so browsers blocked them all. The build now collects hotlink origins from the data automatically, and `tests/check_csp.py` guards the allowlist after each build.+- READMEs (Chinese / English / Japanese) brought up to date with the current feature set.++### 2026-11-22 · History page, proxy fix, Gemini protocol for relays++- New **Generation history** page (contributed by @OrangeSAM): select-all batch download, ZIP export with prompt/parameter metadata, single-item regeneration, before/after comparison; capped at 200 entries.+- Fixed the proxy toggle being ignored for custom relays: unticked now means direct connections; the proxy allows any port for custom relays (official domains stay HTTPS-only, private addresses stay blocked).+- Custom relays gain the Gemini protocol (`models/:generateContent`, auth header switches automatically).+- Wide-screen header overlap fix (contributed by @yansiao1227).++### 2026-11-21 · Seven extension libraries, images move to R2++- Seven new tabs: expressions (95), hairstyles (122, from CharaDB, images hotlinked), historical outfits (57), scenes (64), lighting (50), props (32), furniture (41). Anime outfits absorb 440 CharaDB sets, growing to **1,760**.+- All images are now served from Cloudflare R2 (`pwimg.0vo.pro`); depth-pose images are self-hosted instead of hotlinked, which loads more reliably.+- Fixed Seedream 5.x generation failures (contributed by @COBEZE): 5.x-only parameters are now sent to 4.x models only.++### 2026-11-19 · Anime outfits library++- New **Anime outfits** tab: 1,320 anime-style outfits from COSTUME-ANIME-DB by [@giaaibusi](https://x.com/giaaibusi), in the same 8 categories as the outfit library (spring 197 / summer 237 / autumn 230 / winter 232 / lingerie 197 / party 36 / swimwear 52 / sexy 139), each with Chinese and English prompts.+- Lingerie and sexy categories (336 items) are treated as adult content: hidden by default behind the 18+ toggle (984 public items).+- Anime outfits support the full outfit feature set: category / colour / item filters, search suggestions, favourites, recent views, prompt combos, bilingual detail pages and sitemap; the try-on studio can pick anime outfits directly from the garment step.+- Homepage announcement bar and anime counts added; `scripts/fetch-assets.py` gains an `anime` source (and now also fetches the outfit thumbnails it used to miss).++### 2026-10-31 · Depth poses++- New **Depth poses** tab: 288 sets / 1,439 hotlinked depth-pose images; two-person images sit behind the 18+ toggle.++<a id="ja"></a>++## 日本語++### 2026-11-24 · v1.3.0++- ポーズカードの番号を押すと、同じアングルの線画と深度画像を切り替えられます。単体または組み合わせたプロンプトをコピーすると、選んだアングルの参考画像リンクも付きます。+- フローティングスタジオを開いたまま、ライブラリを切り替えて素材を追加できます。スタジオでは人物・衣装・ポーズを先頭に置き、それ以外の参考画像を「その他の素材」にまとめました。再読み込み後も編集したプロンプト、枚数、縦横比を復元できます。+- 表示言語を簡体字中国語・英語・日本語から選べます。スマートフォンではタッチ操作で素材を選択でき、外観はシステム設定・ライト・ダークから選べます。+- ローカルスタジオから ComfyUI または stable-diffusion.cpp に接続できます。付属の ComfyUI ワークフローは参考画像 1 枚用です。複数枚を使う場合はカスタムワークフローを指定できます。読み取り専用 MCP と素材選択用スキルを使うと、エージェントから素材の検索、アングルの選択、プロンプトの組み合わせができます。++### 2026-11-23 · v1.2.1++- コンボトレイが常駐の「画像生成ワークベンチ」に:フローティングボタン(選択数のバッジ付き)からいつでも開け、パネル内で素材(衣装・アニメ衣装・ポーズ・ポートレート・表情)を直接追加できます。空のときは空状態の案内が表示されます。+- 開発引き継ぎマニュアル `AGENTS.md` と R2 画像同期スクリプト `scripts/sync-r2.py` を追加し、リポジトリ全体を引き継げるようにしました。++### 2026-11-23 · v1.2.0++- コンボトレイで直接画像生成が可能に:ギャラリーで服・ポーズ・ポートレート・表情を選ぶと、トレイの中でそのまま生成できます(プロンプト編集、枚数と比率の選択に対応)。結果は拡大表示とダウンロードができ、生成履歴にも自動保存されます。+- 試着台の調整:右カラムの空白スペーサーを除去し、生成結果が自動で表示位置までスクロールするようになりました。+- サイト全体の文案とデータを修正:アニメ服の点数を 1320 → 1760 に統一(統計・meta・お知らせ・フッター)、フッターに CharaDB のクレジットを追加、プライバシー説明の深度ポーズ配信方式を修正。トレイに高さ上限を追加し、モバイルのお知らせを 2 行に制限。+- トレイ生成フロー全体をカバーする `tests/v18-quick.js` を追加。++### 2026-11-23 · v1.1.0++- ヘアスタイルの全画像(およびアニメ服の CharaDB 分)が読み込めなかった問題を修正:サイトの CSP の `img-src` 許可リストにホットリンク先のオリジンが欠けており、ブラウザがすべてブロックしていました。ビルド時にデータからホットリンクのオリジンを自動収集して許可リストへ書き込むようになり、`tests/check_csp.py` がビルド後に検証します。+- README(中国語/英語/日本語)を現在の機能に合わせて更新。++### 2026-11-22 · 生成履歴ページ、プロキシ修正、リレーの Gemini プロトコル++- 新しい **生成履歴** ページ(@OrangeSAM によるコントリビュート):全選択の一括ダウンロード、プロンプト/パラメータのメタデータ付き ZIP エクスポート、1 件ごとの再生成、元写真とのビフォーアフター比較。上限 200 件。+- カスタムリレーでプロキシのトグルが効かなかった問題を修正:オフの場合は直接接続に。プロキシはリレーの任意ポートを許可(公式ドメインは HTTPS のみ、プライベートアドレスは引き続きブロック)。+- カスタムリレーに Gemini プロトコル(`models/:generateContent`、認証ヘッダーは自動切替)を追加。+- ワイド画面でヘッダーが重なる問題を修正(@yansiao1227 によるコントリビュート)。++### 2026-11-21 · 7 つの拡張ライブラリ、画像を R2 へ移行++- 新しいタブ 7 つ:表情 95、ヘアスタイル 122(CharaDB、画像はホットリンク)、歴史服装 57、シーン 64、ライティング 50、小道具 32、家具 41。アニメ服に CharaDB の 440 点が加わり、合計 **1,760 点**に。+- 全画像の配信を Cloudflare R2(`pwimg.0vo.pro`)に移行。深度ポーズ画像はホットリンクをやめて自前ホスティングにし、読み込みが安定しました。+- Seedream 5.x で生成が失敗する問題を修正(@COBEZE によるコントリビュート):5.x 向けパラメータは 4.x モデルにのみ送るようになりました。++### 2026-11-19 · アニメ服ライブラリ++- 新しい **アニメ服** タブ:[@giaaibusi](https://x.com/giaaibusi) による COSTUME-ANIME-DB から 1,320 点のアニメ風の服装を、服装ライブラリと同じ 8 カテゴリー(春 197 / 夏 237 / 秋 230 / 冬 232 / ランジェリー 197 / パーティー 36 / 水着 52 / セクシー 139)で収録。それぞれ中国語と英語のプロンプト付き。+- ランジェリーとセクシーのカテゴリー(336 点)はアダルトコンテンツとして扱われ、既定では 18+ トグルの背後に隠されています(公開アイテムは 984 点)。+- アニメ服は服装の全機能に対応:カテゴリー/色/アイテムのフィルター、検索候補、お気に入り、最近の閲覧、プロンプトの組み合わせ、バイリンガルの詳細ページとサイトマップ。試着スタジオでは、衣装のステップからアニメ服を直接選べます。+- ホームページのお知らせバーとアニメの点数を追加。`scripts/fetch-assets.py` に `anime` ソースを追加(これまで取得できていなかった服装のサムネイルも取得するようになりました)。++### 2026-10-31 · 深度ポーズ++- 新しい **深度ポーズ** タブ:288 セット / 1,439 点のホットリンクされた深度ポーズ画像。2 人の画像は 18+ トグルの背後にあります。diff --git a/README.en.md b/README.en.mdindex 0c554ef..ae8faaa 100644--- a/README.en.md+++ b/README.en.md@@ -1,161 +1,69 @@-<div align="center">+# PoseWear-<img src="docs/banner.jpg" alt="Portrait + pose + outfit = result" width="900">+[简体中文](README.md) · [English](README.en.md) · [日本語](README.ja.md)-<sub>The result is an AI-generated example using a portrait, pose and outfit from the galleries as references. Source images belong to their authors; see Acknowledgements.</sub>+Find visual references for drawing, photography and AI try-on. Pick a pose, flip it to the matching depth view and pair it with a portrait or outfit. Copy the prompt and image links into an agent, or generate an image in the studio.-<img src="docs/logo.svg" width="72" alt="PoseWear">+[Open the gallery](https://posewear.pages.dev/) · [Run locally](#run-locally) · [Connect an agent](mcp/README.md) · [Release notes](CHANGELOG.md#en)-# PoseWear 衣姿+-Pose, outfit and portrait reference galleries with bilingual prompts, plus a bring-your-own-key AI try-on studio that runs in your browser.+## Run locally-[](LICENSE)-[](https://pages.cloudflare.com/)-[](https://posewear.pages.dev)-[](https://github.com/atuizz/posewear/stargazers)+Use Node.js 22.12 or later. The preview fetches the 12 public catalogs on first visit and loads images as you browse. If you downloaded the source ZIP, open the extracted project directory and start at `npm ci`.-[Live demo](https://posewear.pages.dev) · [Features](#features) · [Quick start](#quick-start) · [Deploy](#deploy) · [FAQ](#faq) · [中文](README.md) · [日本語](README.ja.md)--<img src="docs/home.jpg" alt="Home" width="900">--</div>--## Features--- **Twelve galleries**: poses (multi-angle line sketches), depth poses, outfits (by season and type), anime outfits (anime-style looks, including the CharaDB merge), portraits (face references, CC0), plus seven extension libraries: expressions, hairstyles, historical outfits, scenes, lighting, props and furniture. Every image has a Chinese description and an English prompt you can copy.-- **Search and filters**: search in Chinese or English, filter by category, sort, or pick a random image. Each item has its own static page for sharing.-- **Try-on studio**: upload a photo, pick an outfit and a pose, then generate. You can also generate without a photo. It supports several outputs per run, a before/after slider, and single or zip download.-- **Generation history**: a dedicated page backed by IndexedDB (up to 200 entries): select-all batch zip download, export with prompt and parameter metadata, regenerate a single result, and a before/after comparison against the source photo.-- **Clear errors**: an invalid key, a rate limit, a timeout or a safety block each get their own message and a suggested next step.-- **Reduce false safety blocks**: on by default. The studio rewrites its prompt into a neutral e-commerce try-on description without changing the outfit or pose. Turn it off to send the prompt as is.-- Favorites, recent items and prompt combos, all stored locally; an 18+ toggle with age confirmation; PWA and offline support; dark mode; a Chinese/English UI.--### Providers--| Provider | You need | Default model | Notes |-|---|---|---|---|-| OpenAI | API key (gpt-image requires a verified org) | gpt-image-1 | images/edits with multiple references; strictest moderation |-| Gemini | Google AI Studio key | gemini-2.5-flash-image | a.k.a. Nano Banana |-| Doubao Seedream | Volcengine Ark key | doubao-seedream-4-0-250828 | routed through the site proxy by default for CORS |-| Custom relay | Base URL, key and model | any | OpenAI-compatible (edits / generations) or the Gemini protocol (`models/:generateContent`); the proxy toggle applies to relays too — unticked means direct connections, and relay endpoints may use any port |--## Changelog--### 2026-11-23 · v1.2.1--- The combo tray is now a persistent floating "Image Workbench": a bottom-right button (with a selected-count badge) opens it from anywhere; you can add materials (outfits, anime outfits, poses, portraits, expressions) right inside the panel via the picker, with a clear empty state to get started.-- Added `AGENTS.md` (developer handover manual) and `scripts/sync-r2.py` (R2 image sync) so the repo can be handed over wholesale.--### 2026-11-23 · v1.2.0--- The combo tray now generates images directly: pick outfits, poses, portraits and expressions in the galleries, then generate right inside the tray (editable prompt, count and aspect ratio). Results open full-size, download, and are saved to the generation history automatically — no trip to the studio required.-- Studio polish: removed the empty spacer in the right column; results scroll into view when ready.-- Site-wide copy and data corrections: anime outfits 1320 → 1760 (hero stats, meta, announcement, footer), CharaDB credited in the footer, privacy note corrected for depth-pose delivery; tray height capped with internal scrolling, announcement clamped to two lines on mobile.-- New `tests/v18-quick.js` covers the full tray generation flow.--### 2026-11-23 · v1.1.0--- Fixed every hairstyle image (and the CharaDB part of anime outfits) failing to load: the site's CSP `img-src` allowlist was missing the hotlinked origin, so browsers blocked them all. The build now collects hotlink origins from the data automatically, and `tests/check_csp.py` guards the allowlist after each build.-- READMEs (Chinese / English / Japanese) brought up to date with the current feature set.--### 2026-11-22 · History page, proxy fix, Gemini protocol for relays--- New **Generation history** page (contributed by @OrangeSAM): select-all batch download, ZIP export with prompt/parameter metadata, single-item regeneration, before/after comparison; capped at 200 entries.-- Fixed the proxy toggle being ignored for custom relays: unticked now means direct connections; the proxy allows any port for custom relays (official domains stay HTTPS-only, private addresses stay blocked).-- Custom relays gain the Gemini protocol (`models/:generateContent`, auth header switches automatically).-- Wide-screen header overlap fix (contributed by @yansiao1227).--### 2026-11-21 · Seven extension libraries, images move to R2--- Seven new tabs: expressions (95), hairstyles (122, from CharaDB, images hotlinked), historical outfits (57), scenes (64), lighting (50), props (32), furniture (41). Anime outfits absorb 440 CharaDB sets, growing to **1,760**.-- All images are now served from Cloudflare R2 (`pwimg.0vo.pro`); depth-pose images are self-hosted instead of hotlinked, which loads more reliably.-- Fixed Seedream 5.x generation failures (contributed by @COBEZE): 5.x-only parameters are now sent to 4.x models only.--### 2026-11-19 · Anime outfits library--- New **Anime outfits** tab: 1,320 anime-style outfits from COSTUME-ANIME-DB by [@giaaibusi](https://x.com/giaaibusi), in the same 8 categories as the outfit library (spring 197 / summer 237 / autumn 230 / winter 232 / lingerie 197 / party 36 / swimwear 52 / sexy 139), each with Chinese and English prompts.-- Lingerie and sexy categories (336 items) are treated as adult content: hidden by default behind the 18+ toggle (984 public items).-- Anime outfits support the full outfit feature set: category / colour / item filters, search suggestions, favourites, recent views, prompt combos, bilingual detail pages and sitemap; the try-on studio can pick anime outfits directly from the garment step.-- Homepage announcement bar and anime counts added; `scripts/fetch-assets.py` gains an `anime` source (and now also fetches the outfit thumbnails it used to miss).--### 2026-10-31 · Depth poses--- New **Depth poses** tab: 288 sets / 1,439 hotlinked depth-pose images; two-person images sit behind the 18+ toggle.--## Screenshots--| Studio | Dark mode | Mobile |-|:---:|:---:|:---:|-| <img src="docs/studio.jpg" width="420" alt="Studio"> | <img src="docs/dark.jpg" width="420" alt="Dark mode"> | <img src="docs/mobile.jpg" width="180" alt="Mobile"> |--## Quick start--You need Python 3.9+ with Pillow. Tests and deploys also need Node.js 18+.--```bash-git clone https://github.com/atuizz/posewear.git && cd posewear-pip install pillow-python3 scripts/fetch-assets.py # downloads data and images from the original galleries (several GB)-python3 build.py # outputs dist/-python3 -m http.server 8787 -d dist+```sh+git clone https://github.com/atuizz/posewear.git+cd posewear+npm ci+npm start```-Set `POSEWEAR_RAW` to use a different asset folder, and `POSEWEAR_SITE` to set your own site URL for the sitemap and share links. Set `POSEWEAR_ASSET_HOST` to emit thumbnails and full images into a separate `dist-assets/` folder (deploy it on its own or upload it to R2) while the main site ships pages and data only.+Open the [local gallery](http://127.0.0.1:8787/). Browsing, saving favorites and copying references all work without an account or API key.-## Deploy+## From reference to image-The repository ships without assets, so build locally first, then upload `dist/` to Cloudflare Pages:+| Where | What you can do |+| --- | --- |+| Gallery | Pick a camera angle at the foot of a pose card. Click the ID in the top left to flip to the corresponding depth map and back. Both sides of the same pose and angle can guide one generation. |+| Floating studio | Use the plus on a card to collect references. Keep the studio open as you browse or switch collections. Copying a single or combined prompt includes public image links for your selected views by default. Attach any locally uploaded photos separately when sharing. |+| Full studio | Pick any combination of person, outfit and pose. Open **Other references** for expressions, hairstyles, scenes, lighting, props or furniture. Use a single prop, start with text alone, or upload your photo for a before-and-after try-on. The studio remembers your edited prompt, image count and aspect ratio. |+| Generation history | Revisit a result, download it or export the images, prompts and settings as a ZIP. Each browser keeps up to 200 records. |-```bash-npm install && npx wrangler login-POSEWEAR_SITE=https://<project>.pages.dev python3 build.py-npx wrangler pages deploy dist --project-name <project>-```--`functions/api/proxy.js` is deployed as a Pages Function that only forwards API requests. Adding a rate-limit rule for `/api/proxy` is recommended.+-## Tests+[See a try-on made from a portrait, outfit and pose](docs/banner.jpg)-The Playwright tests mock every provider endpoint, so no real key is needed. They cover success, a bad key, rate limits, 5xx errors, timeouts, cancel, safety blocks and multiple outputs.+The collection menu groups all 12 libraries into **Movement**, **People**, **Wardrobe** and **Setting**. You can pick references on mobile, too. The globe menu controls the interface language (Chinese, English or Japanese), description language (Chinese or English) and whether to include reference links when copying. Appearance follows your system by default. Choose light or dark mode in the header, and open the bell for updates and recent actions.-```bash-npm install && npx playwright install chromium-python3 -m http.server 8787 -d dist &-node tests/v12.js && node tests/v13.js-node tests/v16-proxy.mjs && node tests/v17-history.js # proxy rules / history page-python3 tests/check_csp.py dist # every image origin must be in the CSP allowlist-```+<table><tr><td width="28%" valign="top"><img src="docs/mobile-en.jpg" alt="PoseWear on a phone" width="100%"></td><td valign="top"><img src="docs/dark-en.jpg" alt="PoseWear in dark mode" width="100%"></td></tr></table>-## FAQ+## Choose how to generate-**Is my API key safe?** It stays in your browser's localStorage. Requests go straight to the provider. They only go through `/api/proxy` if you turn on proxy forwarding or use a custom relay; the proxy forwards requests as they are and never stores keys or images.+- **Cloud provider.** Enter your API key in the studio's provider settings. Use OpenAI, Gemini, Seedream or an HTTPS service compatible with the OpenAI, Gemini or xAI image protocol. Direct requests send the key, prompt and images to your provider. Enabling the proxy routes the same request through a Pages Function. Your provider sets pricing and quotas.+- **Local model.** Start ComfyUI, select it in the local studio, test the connection and choose an installed checkpoint. The built-in workflow takes one reference image. Supply your own workflow for multiple images, or start the preview with `POSEWEAR_LOCAL_ENGINE=sd-cpp npm start` to connect a stable-diffusion.cpp `sd-server`. [Local engine setup (Chinese)](docs/local-engines.md)+- **Agent.** From the repository root, run `codex mcp add posewear -- node "$PWD/mcp/server.mjs"` and start a new Codex session. Try “Find a side view of a seated pose, pair it with a spring outfit, and give me the prompt and both image links.” For another stdio client, use `node` as the command and the absolute path to `mcp/server.mjs` as its argument. [MCP configuration and tool examples (Chinese)](mcp/README.md) · [Reference selection skill](.agents/skills/posewear/SKILL.md)-**Why was my image blocked?** Providers moderate both the input photos and the output. Real photos with revealing outfits are the most likely to be blocked, and OpenAI is the strictest. The rewrite option reduces false positives on normal outfits. It does not bypass moderation of prohibited content.+Favorites, studio drafts and API keys live in your browser's localStorage. Generated images and their settings live in IndexedDB. Clearing the site's browser data removes both.-**Can I use the images?** No images are included in this repo. All assets belong to their original authors, so check each source site's terms. The portrait gallery is CC0.+## Development and tests-## Contributing+The frontend uses plain JS, HTML and CSS. Python builds the static site. A Cloudflare Pages Function serves as an optional generation proxy. Use `npm start` to develop the interface. A full build from the original assets also requires Python 3.9+, Pillow, the source images and the extension archives.-Issues and PRs are welcome. Run `python3 build.py` and both test files before you open a PR, and add screenshots for UI changes. Please don't commit any assets or keys.+Install the test browser with `npx playwright install chromium`, then run `npm run test:offline` for the fixture-based checks. For the full regression suite, start the staged Pages server as described in the handbook and run `U=http://127.0.0.1:8902 npm test` in the repository root. The browser tests mock image generation. [Asset preparation, builds and testing (Chinese)](AGENTS.md)-## Acknowledgements+**v1.3.0 (2026-11-24)** Flip between matched line and depth views, keep selecting references in the open studio, and generate from a single material or just a prompt. This update also adds copyable reference links, three UI languages, local engines and MCP support. [Release notes](https://github.com/atuizz/posewear/releases/tag/v1.3.0) · [Changelog](CHANGELOG.md#en)-[AI Pose Gallery](https://ai-pose-gallery.pages.dev/) · [AI Costume Gallery](https://ai-costume-gallery.pages.dev/) · [AI Costume Anime Gallery](https://ai-costume-anime-gallery.pages.dev/) by [@giaaibusi](https://x.com/giaaibusi) · [AI Pose Depth Gallery](https://ai-pose-depth-gallery.pages.dev/) by [ギア / @giaaibusi](https://x.com/giaaibusi) (unofficial Chinese index; images are self-hosted by this site, © the author) · CharaDB by たき AI (hairstyles and part of the anime outfits; tag data CC0, images hotlinked from the source site, not stored here) · [AI Portrait Gallery](https://ai-portrait-gallery.pages.dev/) by [@agi_aibusi](https://x.com/agi_aibusi) (CC0) · [wzc520pyfm/gen-ai-pose-image](https://github.com/wzc520pyfm/gen-ai-pose-image) · [paipiange/nvzhuang](https://github.com/paipiange/nvzhuang)+## License and credits-## License and asset boundaries+The code, UI copy and build scripts are available under the [MIT License](LICENSE). Each reference image, including images visible in the screenshots, retains its source terms. Keep source and author credits on self-hosted copies.-| What | In this repo? | License |-|---|---|---|-| Code, UI copy, build scripts | Yes | [MIT](LICENSE) |-| Pose and outfit images and data | No — downloaded by `fetch-assets.py` | Owned by [@giaaibusi](https://x.com/giaaibusi) ([AI Pose Gallery](https://ai-pose-gallery.pages.dev/) / [AI Costume Gallery](https://ai-costume-gallery.pages.dev/) / [AI Costume Anime Gallery](https://ai-costume-anime-gallery.pages.dev/)); no open license is stated |-| Portrait images | No — same as above | [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/) by [@agi_aibusi](https://x.com/agi_aibusi) ([AI Portrait Gallery](https://ai-portrait-gallery.pages.dev/)) |-| Depth-pose images | No — self-hosted on this site's CDN (sourced from [AI Pose Depth Gallery](https://ai-pose-depth-gallery.pages.dev/)) | Owned by [ギア / @giaaibusi](https://x.com/giaaibusi). This repo only has the text metadata and Chinese names |-| Hairstyle and CharaDB anime-outfit images | No — hotlinked with `<img>` from CharaDB | Tag data CC0; images © CharaDB author たき AI, not stored or redistributed here |-| Depth-pose text metadata | Yes, `depth/packs/` | Japanese text belongs to the original author; Chinese names are ours |-| README screenshots | Yes | The pictures shown belong to their authors as above |+| Material | Source and terms |+| --- | --- |+| Poses, depth maps, outfits and anime outfits | By ギア / @giaaibusi. Contact the author about commercial use, reposting or redistribution. The repository includes Japanese depth metadata and PoseWear's Chinese names. Images are served by the asset CDN. [Line art](https://ai-pose-gallery.pages.dev/) · [Depth](https://ai-pose-depth-gallery.pages.dev/) · [Outfits](https://ai-costume-gallery.pages.dev/) · [Anime outfits](https://ai-costume-anime-gallery.pages.dev/) |+| Portraits | Fictional AI portraits by @agi_aibusi, released under CC0. The author asks users to avoid bulk reposting the originals. [AI Portrait Gallery](https://ai-portrait-gallery.pages.dev/) |+| Hairstyles and selected anime outfits | たき AI / CharaDB. Tags are CC0. Images belong to the author and are loaded directly from the original host. [CharaDB](https://charadb-2fi.pages.dev/) |+| Expressions | WaveSpeed AI Emotion Gallery, using ICT Face Model Light (© USC Institute for Creative Technologies, MIT). |+| Historical dress, scenes, lighting, props and furniture | Shisei / wquguru, CC0 1.0. |-- MIT covers the code only, not any image or data.-- To repost, use commercially or redistribute pose/outfit images, ask the author @giaaibusi first and follow the source site's terms.-- Portraits are CC0: free to use, modify and sell without credit. They are AI-generated fictional people — don't use them to impersonate real people. The author asks that they not be bulk-reposted as-is.-- If you deploy your own copy, keep the source and author credits on the pages.+Thanks to two open-source projects that inspired this work. [gen-ai-pose-image](https://github.com/wzc520pyfm/gen-ai-pose-image) · [nvzhuang](https://github.com/paipiange/nvzhuang)diff --git a/README.ja.md b/README.ja.mdindex 4d345ab..85f8c96 100644--- a/README.ja.md+++ b/README.ja.md@@ -1,161 +1,69 @@-<div align="center">+# 衣姿 PoseWear-<img src="docs/banner.jpg" alt="人物 + ポーズ + 服装 = 成果物" width="900">+[简体中文](README.md) · [English](README.en.md) · [日本語](README.ja.md)-<sub>成果物は、ギャラリーの人物・ポーズ・服装を参考に AI が生成した例です。素材画像の著作権は各作者に帰属します。謝辞を参照してください。</sub>+作画、撮影、AI 試着のための参考画像を探せるギャラリーです。ポーズを選んで同じアングルの深度画像に切り替え、人物や衣装と組み合わせます。プロンプトと画像リンクをエージェントに渡したり、そのままスタジオで画像を生成したりできます。-<img src="docs/logo.svg" width="72" alt="PoseWear">+[ギャラリーを開く](https://posewear.pages.dev/) · [ローカルで起動](#ローカルで起動) · [エージェントと接続](mcp/README.md) · [更新履歴](CHANGELOG.md#ja)-# PoseWear 衣姿+-バイリンガルのプロンプト付きのポーズ・服装・人物の参考ギャラリーと、ブラウザ上で動作する BYOK(自分の API キーを使う)AI 試着スタジオ。+## ローカルで起動-[](LICENSE)-[](https://pages.cloudflare.com/)-[](https://posewear.pages.dev)-[](https://github.com/atuizz/posewear/stargazers)+Node.js 22.12 以降を使用します。プレビューの初回アクセス時に公開カタログ 12 件を取得し、画像は閲覧に合わせて読み込みます。ソースの ZIP を入手した場合は、展開したプロジェクトのディレクトリで `npm ci` から実行してください。-[ライブデモ](https://posewear.pages.dev) · [機能](#機能) · [クイックスタート](#クイックスタート) · [デプロイ](#デプロイ) · [FAQ](#faq) · [中文](README.md) · [English](README.en.md)--<img src="docs/home.jpg" alt="ホーム" width="900">--</div>--## 機能--- **12 のギャラリー**:ポーズ(多角度の線画)、深度ポーズ、服装(季節と種類で分類)、アニメ服(アニメ風の着こなし、CharaDB 統合分を含む)、人物(顔のリファレンス、CC0)に加え、表情・ヘアスタイル・歴史服装・シーン・ライティング・小道具・家具の 7 つの拡張ライブラリ。すべての画像に中国語の説明と、コピーできる英語のプロンプトが付いています。-- **検索とフィルター**:中国語または英語で検索、カテゴリーで絞り込み、並べ替え、ランダムな画像の選択ができます。各アイテムには共有用の静的ページがあります。-- **試着スタジオ**:写真をアップロードし、服装とポーズを選んで生成します。写真なしで生成することもできます。1 回の実行で複数の出力、ビフォーアフターのスライダー、単体または zip でのダウンロードに対応しています。-- **生成履歴**:IndexedDB に保存される専用ページ(上限 200 件)。全選択して一括 zip ダウンロード、プロンプトとパラメータのメタデータ付きエクスポート、1 件ごとの再生成、元写真とのビフォーアフター比較ができます。-- **わかりやすいエラー**:無効なキー、レート制限、タイムアウト、セーフティブロックのそれぞれに専用のメッセージと、次に取るべき手順の提案が表示されます。-- **誤ったセーフティブロックの低減**:既定でオン。スタジオは、服装やポーズを変えずに、プロンプトを中立的な EC 試着の説明に書き換えます。オフにすると、プロンプトをそのまま送信します。-- お気に入り、最近のアイテム、プロンプトの組み合わせはすべてローカルに保存。年齢確認付きの 18+ トグル、PWA とオフライン対応、ダークモード、中国語/英語の UI。--### プロバイダー--| プロバイダー | 必要なもの | 既定のモデル | 備考 |-|---|---|---|---|-| OpenAI | API キー(gpt-image には認証済みの組織が必要) | gpt-image-1 | 複数のリファレンスを使う images/edits。モデレーションが最も厳格 |-| Gemini | Google AI Studio のキー | gemini-2.5-flash-image | 別名 Nano Banana |-| Doubao Seedream | Volcengine Ark のキー | doubao-seedream-4-0-250828 | CORS のため既定でサイトのプロキシ経由 |-| Custom relay | ベース URL、キー、モデル | 任意 | OpenAI 互換(edits / generations)または Gemini プロトコル(`models/:generateContent`)。プロキシのトグルはリレーにも適用され、オフの場合は直接接続、リレーのエンドポイントは任意のポートを使用可能 |--## 変更履歴--### 2026-11-23 · v1.2.1--- コンボトレイが常駐の「画像生成ワークベンチ」に:右下のフローティングボタン(選択数のバッジ付き)からいつでも開け、パネル内で素材(衣装・アニメ衣装・ポーズ・ポートレート・表情)を直接追加できます。空のときは空状態の案内が表示されます。-- 開発引き継ぎマニュアル `AGENTS.md` と R2 画像同期スクリプト `scripts/sync-r2.py` を追加し、リポジトリ全体を引き継げるようにしました。--### 2026-11-23 · v1.2.0--- コンボトレイで直接画像生成が可能に:ギャラリーで服・ポーズ・ポートレート・表情を選ぶと、トレイの中でそのまま生成できます(プロンプト編集、枚数と比率の選択に対応)。結果は拡大表示とダウンロードができ、生成履歴にも自動保存されます。-- 試着台の調整:右カラムの空白スペーサーを除去し、生成結果が自動で表示位置までスクロールするようになりました。-- サイト全体の文案とデータを修正:アニメ服の点数を 1320 → 1760 に統一(統計・meta・お知らせ・フッター)、フッターに CharaDB のクレジットを追加、プライバシー説明の深度ポーズ配信方式を修正。トレイに高さ上限を追加し、モバイルのお知らせを 2 行に制限。-- トレイ生成フロー全体をカバーする `tests/v18-quick.js` を追加。--### 2026-11-23 · v1.1.0--- ヘアスタイルの全画像(およびアニメ服の CharaDB 分)が読み込めなかった問題を修正:サイトの CSP の `img-src` 許可リストにホットリンク先のオリジンが欠けており、ブラウザがすべてブロックしていました。ビルド時にデータからホットリンクのオリジンを自動収集して許可リストへ書き込むようになり、`tests/check_csp.py` がビルド後に検証します。-- README(中国語/英語/日本語)を現在の機能に合わせて更新。--### 2026-11-22 · 生成履歴ページ、プロキシ修正、リレーの Gemini プロトコル--- 新しい **生成履歴** ページ(@OrangeSAM によるコントリビュート):全選択の一括ダウンロード、プロンプト/パラメータのメタデータ付き ZIP エクスポート、1 件ごとの再生成、元写真とのビフォーアフター比較。上限 200 件。-- カスタムリレーでプロキシのトグルが効かなかった問題を修正:オフの場合は直接接続に。プロキシはリレーの任意ポートを許可(公式ドメインは HTTPS のみ、プライベートアドレスは引き続きブロック)。-- カスタムリレーに Gemini プロトコル(`models/:generateContent`、認証ヘッダーは自動切替)を追加。-- ワイド画面でヘッダーが重なる問題を修正(@yansiao1227 によるコントリビュート)。--### 2026-11-21 · 7 つの拡張ライブラリ、画像を R2 へ移行--- 新しいタブ 7 つ:表情 95、ヘアスタイル 122(CharaDB、画像はホットリンク)、歴史服装 57、シーン 64、ライティング 50、小道具 32、家具 41。アニメ服に CharaDB の 440 点が加わり、合計 **1,760 点**に。-- 全画像の配信を Cloudflare R2(`pwimg.0vo.pro`)に移行。深度ポーズ画像はホットリンクをやめて自前ホスティングにし、読み込みが安定しました。-- Seedream 5.x で生成が失敗する問題を修正(@COBEZE によるコントリビュート):5.x 向けパラメータは 4.x モデルにのみ送るようになりました。--### 2026-11-19 · アニメ服ライブラリ--- 新しい **アニメ服** タブ:[@giaaibusi](https://x.com/giaaibusi) による COSTUME-ANIME-DB から 1,320 点のアニメ風の服装を、服装ライブラリと同じ 8 カテゴリー(春 197 / 夏 237 / 秋 230 / 冬 232 / ランジェリー 197 / パーティー 36 / 水着 52 / セクシー 139)で収録。それぞれ中国語と英語のプロンプト付き。-- ランジェリーとセクシーのカテゴリー(336 点)はアダルトコンテンツとして扱われ、既定では 18+ トグルの背後に隠されています(公開アイテムは 984 点)。-- アニメ服は服装の全機能に対応:カテゴリー/色/アイテムのフィルター、検索候補、お気に入り、最近の閲覧、プロンプトの組み合わせ、バイリンガルの詳細ページとサイトマップ。試着スタジオでは、衣装のステップからアニメ服を直接選べます。-- ホームページのお知らせバーとアニメの点数を追加。`scripts/fetch-assets.py` に `anime` ソースを追加(これまで取得できていなかった服装のサムネイルも取得するようになりました)。--### 2026-10-31 · 深度ポーズ--- 新しい **深度ポーズ** タブ:288 セット / 1,439 点のホットリンクされた深度ポーズ画像。2 人の画像は 18+ トグルの背後にあります。--## スクリーンショット--| スタジオ | ダークモード | モバイル |-|:---:|:---:|:---:|-| <img src="docs/studio.jpg" width="420" alt="スタジオ"> | <img src="docs/dark.jpg" width="420" alt="ダークモード"> | <img src="docs/mobile.jpg" width="180" alt="モバイル"> |--## クイックスタート--Pillow を備えた Python 3.9+ が必要です。テストとデプロイには Node.js 18+ も必要です。--```bash-git clone https://github.com/atuizz/posewear.git && cd posewear-pip install pillow-python3 scripts/fetch-assets.py # downloads data and images from the original galleries (several GB)-python3 build.py # outputs dist/-python3 -m http.server 8787 -d dist+```sh+git clone https://github.com/atuizz/posewear.git+cd posewear+npm ci+npm start```-別の素材フォルダを使うには `POSEWEAR_RAW` を、サイトマップや共有リンク用に独自のサイト URL を設定するには `POSEWEAR_SITE` を設定します。`POSEWEAR_ASSET_HOST` を設定すると、サムネイルと原画像は別の `dist-assets/` フォルダーに出力されます(単独でデプロイするか R2 にアップロード可能)。メインサイトにはページとデータだけが残ります。+[ローカルのギャラリー](http://127.0.0.1:8787/)を開きます。閲覧、お気に入り登録、参考画像リンクのコピーにはアカウントも API キーも不要です。-## デプロイ+## 素材を選んで画像を作る-このリポジトリは素材を含まずに配布されるため、まずローカルでビルドし、`dist/` を Cloudflare Pages にアップロードします:+| 場所 | できること |+| --- | --- |+| 素材ライブラリ | ポーズカードの下部でアングルを選択。左上の番号を押すと、同じアングルの線画と深度画像を切り替えられます。同じポーズ・アングルの両方を生成時に使えます。 |+| フローティングスタジオ | カードの「+」で素材を追加します。スタジオを開いたまま別の素材やライブラリを選べます。単体・組み合わせのどちらも、プロンプトをコピーすると選択したアングルの画像 URL が付きます。アップロードした手元の写真は別途添付してください。 |+| スタジオ | 人物・衣装・ポーズを自由に組み合わせられます。表情、髪型、背景、照明、小物、家具は「その他の素材」から選択。小物一つ、あるいは文章だけでも生成できます。編集したプロンプト、枚数、縦横比は次回も引き継がれます。試着では、自分の写真と生成結果を見比べられます。 |+| 生成履歴 | 結果を見直して保存したり、画像・プロンプト・設定をまとめて ZIP で書き出したりできます。保存件数はブラウザーごとに最大 200 件です。 |-```bash-npm install && npx wrangler login-POSEWEAR_SITE=https://<project>.pages.dev python3 build.py-npx wrangler pages deploy dist --project-name <project>-```--`functions/api/proxy.js` は、API リクエストを転送するだけの Pages Function としてデプロイされます。`/api/proxy` にレート制限ルールを追加することを推奨します。+-## テスト+[人物・衣装・ポーズを組み合わせた試着例](docs/banner.jpg)-Playwright のテストはすべてのプロバイダーのエンドポイントをモックするため、実際のキーは不要です。成功、不正なキー、レート制限、5xx エラー、タイムアウト、キャンセル、セーフティブロック、複数出力をカバーします。+素材メニューでは 12 のライブラリを「動作」「人物・髪型」「衣類」「空間・小物」の四つに分類しています。スマートフォンからも素材を選べます。地球のアイコンから表示言語(中・英・日)、素材の説明言語(中・英)、コピー時の画像リンクの有無を設定できます。外観は初期設定でシステムに合わせます。ヘッダーではライト・ダークを指定でき、ベルから更新や直近の操作を確認できます。-```bash-npm install && npx playwright install chromium-python3 -m http.server 8787 -d dist &-node tests/v12.js && node tests/v13.js-node tests/v16-proxy.mjs && node tests/v17-history.js # プロキシ規則 / 履歴ページ-python3 tests/check_csp.py dist # すべての画像オリジンが CSP の許可リストにあるか検証-```+<table><tr><td width="28%" valign="top"><img src="docs/mobile-ja.jpg" alt="スマートフォンでの表示" width="100%"></td><td valign="top"><img src="docs/dark-ja.jpg" alt="ダークモードの PoseWear" width="100%"></td></tr></table>-## FAQ+## 生成方法を選ぶ-**API キーは安全ですか?** キーはブラウザの localStorage に保存されます。リクエストはプロバイダーへ直接送られます。プロキシ転送をオンにするか、カスタムリレーを使う場合にのみ `/api/proxy` を経由します。プロキシはリクエストをそのまま転送し、キーや画像を保存することはありません。+- **クラウドサービス。** スタジオのプロバイダー設定に自身の API キーを入力します。OpenAI、Gemini、Seedream のほか、OpenAI・Gemini・xAI の画像 API と互換性のある HTTPS サービスを利用できます。直接接続ではキー、プロンプト、画像が選択したサービスに送られます。プロキシを有効にすると Pages Function が同じ内容を転送します。料金と利用上限は各サービスの規定に従います。+- **ローカルモデル。** ComfyUI を起動してローカルのスタジオで選択し、接続テスト後にインストール済みのチェックポイントを指定します。付属ワークフローは参考画像 1 枚に対応します。複数枚には独自のワークフローを使用できます。stable-diffusion.cpp の `sd-server` を使う場合は `POSEWEAR_LOCAL_ENGINE=sd-cpp npm start` でプレビューを起動します。[ローカルエンジンの設定(中国語)](docs/local-engines.md)+- **エージェント。** リポジトリのルートで `codex mcp add posewear -- node "$PWD/mcp/server.mjs"` を実行して、新しい Codex セッションを開きます。例えば「横から見た座りポーズと春服を探して、プロンプトと参考画像 2 枚のリンクをください」と依頼できます。ほかの stdio クライアントでは、コマンドに `node`、引数に `mcp/server.mjs` の絶対パスを指定します。[MCP の設定とツール例(中国語)](mcp/README.md) · [素材選択の Skill](.agents/skills/posewear/SKILL.md)-**なぜ画像がブロックされたのですか?** プロバイダーは入力写真と出力の両方をモデレーションします。露出の多い服装の実写は最もブロックされやすく、OpenAI が最も厳格です。書き換えオプションは通常の服装での誤検出を減らします。禁止コンテンツのモデレーションを回避するものではありません。+お気に入り、スタジオの下書き、API キーはブラウザーの localStorage、生成履歴は IndexedDB に保存されます。サイトのブラウザーデータを消去すると、これらの内容も削除されます。-**画像を使えますか?** このリポジトリには画像は含まれていません。すべての素材は各作者に帰属するため、各ソースサイトの規約を確認してください。人物ギャラリーは CC0 です。+## 開発とテスト-## コントリビュート+フロントエンドは素の JS、HTML、CSS で、Python が静的サイトをビルドします。生成用のプロキシには Cloudflare Pages Function を使えます。画面の開発には `npm start` を使用します。原画からの完全なビルドには Python 3.9 以降、Pillow、元画像、拡張素材アーカイブが必要です。-Issue と PR を歓迎します。PR を出す前に `python3 build.py` と両方のテストファイルを実行し、UI の変更にはスクリーンショットを添えてください。素材やキーはコミットしないでください。+`npx playwright install chromium` でテスト用ブラウザーをインストールし、`npm run test:offline` でフィクスチャを使うテストを実行できます。全回帰テストを実行する場合は、開発手順に従ってステージングの Pages サーバーを起動し、リポジトリのルートで `U=http://127.0.0.1:8902 npm test` を実行します。ブラウザーテストは画像生成サービスの応答を模擬します。[素材準備、ビルドとテスト手順(中国語)](AGENTS.md)-## 謝辞+**v1.3.0(2026-11-24)** 対応する線画と深度画像の切り替え、スタジオを開いたままの素材選択、素材単体またはプロンプトだけでの生成に対応しました。参考画像リンク付きコピー、3 言語の UI、ローカルエンジン、MCP も利用できます。[リリースノート](https://github.com/atuizz/posewear/releases/tag/v1.3.0) · [更新履歴](CHANGELOG.md#ja)-[AI Pose Gallery](https://ai-pose-gallery.pages.dev/) · [AI Costume Gallery](https://ai-costume-gallery.pages.dev/) · [AI Costume Anime Gallery](https://ai-costume-anime-gallery.pages.dev/) by [@giaaibusi](https://x.com/giaaibusi) · [AI Pose Depth Gallery](https://ai-pose-depth-gallery.pages.dev/) by [ギア / @giaaibusi](https://x.com/giaaibusi)(非公式の中国語インデックス。画像は本サイトで自前ホスティング、著作権は作者に帰属) · CharaDB by たき AI(ヘアスタイルとアニメ服の一部。タグデータは CC0、画像は元のサイトからホットリンクし、ここには保存しません) · [AI Portrait Gallery](https://ai-portrait-gallery.pages.dev/) by [@agi_aibusi](https://x.com/agi_aibusi)(CC0) · [wzc520pyfm/gen-ai-pose-image](https://github.com/wzc520pyfm/gen-ai-pose-image) · [paipiange/nvzhuang](https://github.com/paipiange/nvzhuang)+## ライセンスと謝辞-## ライセンスと素材の扱い+コード、画面の文言、ビルドスクリプトには [MIT ライセンス](LICENSE) が適用されます。スクリーンショット内の画像を含め、素材にはそれぞれの提供元の利用条件が適用されます。セルフホストの際は出典と作者名を残してください。-| 対象 | このリポジトリに含まれる? | ライセンス |-|---|---|---|-| コード、UI コピー、ビルドスクリプト | はい | [MIT](LICENSE) |-| ポーズと服装の画像・データ | いいえ — `fetch-assets.py` でダウンロード | [@giaaibusi](https://x.com/giaaibusi)([AI Pose Gallery](https://ai-pose-gallery.pages.dev/) / [AI Costume Gallery](https://ai-costume-gallery.pages.dev/) / [AI Costume Anime Gallery](https://ai-costume-anime-gallery.pages.dev/))に帰属。オープンライセンスの明示はなし |-| 人物画像 | いいえ — 上と同じ | [@agi_aibusi](https://x.com/agi_aibusi)([AI Portrait Gallery](https://ai-portrait-gallery.pages.dev/))による [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/) |-| 深度ポーズ画像 | いいえ — 本サイトの CDN で自前ホスティング(出典は [AI Pose Depth Gallery](https://ai-pose-depth-gallery.pages.dev/)) | [ギア / @giaaibusi](https://x.com/giaaibusi) に帰属。このリポジトリにはテキストのメタデータと中国語名のみ |-| ヘアスタイルと CharaDB のアニメ服画像 | いいえ — CharaDB から `<img>` でホットリンク | タグデータは CC0。画像の著作権は CharaDB の作者 たき AI に帰属し、ここでは保存も再配布もしない |-| 深度ポーズのテキストメタデータ | はい、`depth/packs/` | 日本語テキストは原作者に帰属。中国語名は本プロジェクトのもの |-| README のスクリーンショット | はい | 表示されている画像は上記のとおり各作者に帰属 |+| 素材 | 出典と利用条件 |+| --- | --- |+| ポーズ、深度画像、衣装、アニメ衣装 | ギア / @giaaibusi。商用利用、転載、再配布については作者にご確認ください。リポジトリには深度画像の日本語メタデータと本サイトの中国語訳を収録し、画像は素材 CDN から配信しています。[線画](https://ai-pose-gallery.pages.dev/) · [深度画像](https://ai-pose-depth-gallery.pages.dev/) · [衣装](https://ai-costume-gallery.pages.dev/) · [アニメ衣装](https://ai-costume-anime-gallery.pages.dev/) |+| 人物 | @agi_aibusi による架空の AI ポートレート、CC0。作者は原画の一括転載を控えるよう希望しています。[AI Portrait Gallery](https://ai-portrait-gallery.pages.dev/) |+| 髪型・一部のアニメ衣装 | たき AI / CharaDB。タグは CC0。画像の権利は作者に帰属し、提供元から直接読み込みます。[CharaDB](https://charadb-2fi.pages.dev/) |+| 表情 | WaveSpeed AI Emotion Gallery。ICT Face Model Light を使用(© USC Institute for Creative Technologies、MIT)。 |+| 歴代衣装、背景、照明、小物、家具 | Shisei / wquguru、CC0 1.0。 |-- MIT が対象とするのはコードのみで、画像やデータは対象外です。-- ポーズ/服装の画像を転載、商用利用、再配布する場合は、まず作者 @giaaibusi に確認し、ソースサイトの規約に従ってください。-- 人物画像は CC0 です:クレジット表示なしで自由に使用、改変、販売できます。これらは AI が生成した架空の人物です。実在の人物になりすますために使わないでください。作者は、これらをそのまま大量に転載しないよう求めています。-- 自分でコピーをデプロイする場合は、ページ上のソースと作者のクレジットを残してください。+着想をいただいた二つのオープンソースプロジェクトに感謝します。[gen-ai-pose-image](https://github.com/wzc520pyfm/gen-ai-pose-image) · [nvzhuang](https://github.com/paipiange/nvzhuang)diff --git a/README.md b/README.mdindex bc0cf5b..889f167 100644--- a/README.md+++ b/README.md@@ -1,251 +1,69 @@-<div align="center">--<img src="docs/banner.jpg" alt="人像 + 姿势 + 服饰 = 成品" width="900">--<sub>成品为用站内人像、姿势、服装作参考的 AI 生成示例;素材版权归原作者,见<a href="#致谢">致谢</a>。</sub>--<img src="docs/logo.svg" width="72" alt="衣姿 PoseWear">-# 衣姿 PoseWear-姿势、服装、人像参考图库,附中英文提示词;用自己的 API Key,在浏览器里直接 AI 试穿。--[](LICENSE)-[](https://pages.cloudflare.com/)-[](https://posewear.pages.dev)-[](https://github.com/atuizz/posewear/stargazers)--[在线体验](https://posewear.pages.dev) · [功能](#功能) · [快速开始](#快速开始) · [部署](#部署) · [常见问题](#常见问题) · [English](README.en.md) · [日本語](README.ja.md)--<img src="docs/home.jpg" alt="首页截图" width="900">--</div>--## 简介--衣姿是一个纯静态的参考图站点:十二套素材库都能直接浏览、搜索和复制提示词。挑中的服装和姿势可以带到试穿工作台,配上你自己的照片和模型 API,生成试穿图。--不需要注册,也没有后端数据库。密钥、收藏和生成记录都只保存在你的浏览器里。--## 功能--| | |-|---|---|-| **素材库** | 姿势(多角度线稿)、深度姿势、服装(按季节和类型分类)、动画服装(动画风穿搭,含 CharaDB 并入部分)、人像(脸模参考,CC0),以及表情、发型、历代服装、场景、光影、道具、家具七个扩展库。每张图都有中文描述;深度姿势另附日文原名 |-| **搜索与筛选** | 中英文关键词、分类、排序、随机一张;每个素材有独立详情页,方便分享 |-| **试穿工作台** | 上传人物照,选服装和姿势,生成试穿图,或不用照片直接出图;一次可出多张,有前后对比、单张下载和打包下载 |-| **多家服务商** | OpenAI、Gemini、豆包 Seedream、OpenAI 兼容的自定义中转,见下表 |-| **生成记录** | 独立记录页:保存在本机 IndexedDB(上限 200 条),可全选批量打包下载、导出 ZIP(含每张图的提示词与参数)、单张重新生成,大图模式可与原图前后对比 |-| **清楚的报错** | 密钥无效、限流、超时、被安全审核拦截等情况会分别说明,并给出下一步可以怎么做 |-| **减少误拦截** | 默认开启。发送前把提示词改写成中性的电商试穿描述,不改变服装和姿势;关闭后按原样发送 |-| **收藏 / 最近 / 组合** | 本机保存,可导入导出,删除可撤销;可以把多个素材拼成一段提示词 |-| **18+ 开关** | 成人向分类默认隐藏,打开前需要确认年龄 |-| **PWA 与深色模式** | 可安装,看过的内容离线也能打开;深色模式跟随系统,也可手动切换 |-| **中文 / English 界面** | 默认中文,右上角切换 |--### 支持的服务商--| 服务商 | 需要准备 | 默认模型 | 说明 |-|---|---|---|---|-| OpenAI | API Key(gpt-image 需已验证组织) | gpt-image-1 | 走 images/edits,多张参考图;安全审核最严 |-| Gemini | Google AI Studio 的 API Key | gemini-2.5-flash-image | 即 Nano Banana |-| 豆包 Seedream | 火山方舟 API Key | doubao-seedream-4-0-250828 | 国内直连,默认经本站代理以解决跨域 |-| 自定义中转 | Base URL + Key + 模型名 | 自填 | OpenAI 兼容(edits / generations)或 Gemini 协议(`models/:generateContent`);代理开关对中转同样生效,未勾选时代理直连,中转地址可用任意端口 |--## 更新日志--### 2026-11-23 · v1.2.1--- 组合托盘升级为常驻「生图工作台」:右下角常驻悬浮按钮(带已选数量徽章),随时打开拼装;面板内可直接「添加素材」(服装、动画服装、姿势、人像、表情),不必先回图库点选;空组合时有明确的空状态引导。-- 新增 `AGENTS.md` 开发交接手册与 `scripts/sync-r2.py`(R2 图片同步脚本),仓库可完整交付他人接手开发。--### 2026-11-23 · v1.2.0--- 组合托盘新增「简易生图」:在图库里选好服装、姿势、人像、表情,托盘里直接生成图片(可改提示词、选张数和比例),结果可看大图、下载,并自动存入生成记录,不必先进试穿工作台。-- 试穿台打磨:去掉右栏中部的空白占位,生成结果自动滚入视野。-- 全站文案与数据校正:动画服装数量 1320 → 1760(首页统计、meta、公告、页脚统一),页脚补 CharaDB 致谢,隐私说明改正深度姿势分发方式;托盘加高度上限、手机端公告限两行。-- 新增 `tests/v18-quick.js` 覆盖托盘生图全流程。--### 2026-11-23 · v1.1.0--- 修复发型库与动画服装中 CharaDB 部分的图片全部加载失败:本站 CSP 的 `img-src` 白名单漏了热链源站,浏览器直接拦截。构建时改为自动收集数据里的热链源站写入白名单,并新增 `tests/check_csp.py` 守卫,构建后校验全部图片源站。-- 本页 README 同步到当前功能(英文、日文版同步更新)。--### 2026-11-22 · 生成记录页、代理与 Gemini 协议--- 新增「生成记录」页(@OrangeSAM 贡献):全选批量打包、导出 ZIP(含提示词与参数元数据)、单张重新生成、大图与原图前后对比;记录上限 200 条。-- 修复代理开关对自定义中转不生效:未勾选代理时中转请求直连;代理放行自定义中转的任意端口(官方域名仍限标准 HTTPS,内网地址仍拒绝)。-- 自定义中转新增 Gemini 协议:可选 `models/:generateContent` 调用,鉴权头按协议自动切换。-- 页头宽屏遮挡修复(@yansiao1227 贡献)。--### 2026-11-21 · 七个扩展库上线、图片迁入 R2+[简体中文](README.md) · [English](README.en.md) · [日本語](README.ja.md)-- 新增七个栏目:表情 95、发型 122(CharaDB,图片热链原站)、历代服装 57、场景 64、光影 50、道具 32、家具 41;动画服装并入 CharaDB 的 440 套,总数增至 **1760 套**。-- 全站图片改由 Cloudflare R2(`pwimg.0vo.pro`)分发;深度姿势图片改为本站自存,不再热链原站,加载更稳定。-- 修复 Seedream 5.x 参数错误导致生图失败(@COBEZE 贡献):参数改为仅对 4.x 模型发送。+给绘画、摄影和 AI 试穿挑参考图。从一个动作开始,翻到同机位的深度图,搭配人物与服装,再把提示词和参考图链接一起交给智能体,或直接在工作台生成图片。-### 2026-11-19 · 动画服装库上线+[打开在线图库](https://posewear.pages.dev/) · [本地启动](#本地启动) · [接入智能体](mcp/README.md) · [版本记录](CHANGELOG.md#zh)-- 新增「动画服装」栏目:接入上游 COSTUME-ANIME-DB([@giaaibusi](https://x.com/giaaibusi))的 **1320 套**动画风穿搭,与写实服装同为 8 个分类(春 197 / 夏 237 / 秋 230 / 冬 232 / 内衣 197 / 派对礼服 36 / 泳装 52 / 性感 139),每套附中英文提示词。-- 内衣、性感类共 336 套按成人内容处理:默认隐藏,打开顶部「18+」开关后显示(默认公开 984 套)。-- 动画服装支持服装库的全部功能:分类 / 颜色 / 单品筛选、搜索建议、收藏、最近浏览、组合提示词、中英双语详情页与 sitemap;试穿工作台的服装步骤可直接「从动画服装选」。-- 首页新增上线公告条与动画服装计数,页脚与隐私说明补齐来源致谢;`scripts/fetch-assets.py` 新增 `anime` 数据源(顺带修复写实服装漏抓缩略图的问题)。+-### 2026-10-31 · 深度姿势+## 本地启动-- 新增「深度姿势」栏目:热链上游深度姿势图 288 组 / 1439 张,双人图走 18+ 开关。+需要 Node.js 22.12 或以上版本。首次访问会联网载入 12 份公开素材目录,图片按需加载。已下载源码 ZIP 时,进入解压后的项目目录,从 `npm ci` 开始。-## 截图--| 试穿工作台 | 深色模式 | 手机 |-|:---:|:---:|:---:|-| <img src="docs/studio.jpg" alt="试穿工作台" width="420"> | <img src="docs/dark.jpg" alt="深色模式" width="420"> | <img src="docs/mobile.jpg" alt="手机" width="180"> |--## 快速开始--需要 Python 3.9+ 和 Pillow;测试与部署另外需要 Node.js 18+。--```bash-git clone https://github.com/atuizz/posewear.git && cd posewear-pip install pillow--# 1. 从原作者的图库下载数据和图片到 ./assets-raw(数 GB,耗时较长)-python3 scripts/fetch-assets.py # 也可只下部分:pose costume portrait--# 2. 构建到 dist/-python3 build.py--# 3. 本地预览 http://localhost:8787-python3 -m http.server 8787 -d dist-```--| 环境变量 | 作用 | 默认 |-|---|---|---|-| `POSEWEAR_RAW` | 原始素材目录 | `assets-raw` |-| `POSEWEAR_SITE` | 站点地址,用于 sitemap 和分享链接 | `https://posewear.pages.dev` |-| `POSEWEAR_ASSET_HOST` | 图片资源域名;设置后缩略图与原图输出到独立的 `dist-assets/`(可单独部署或上传 R2),主站只留页面与数据 | 不设置(图片进主站) |-| `POSEWEAR_WA_TOKEN` | Cloudflare Web Analytics 站点令牌;设置后构建注入统计脚本 | 不设置 |--## 部署--仓库不带素材,所以需要先在本地构建,再上传 `dist/` 到 Cloudflare Pages:--```bash-npm install-npx wrangler login-POSEWEAR_SITE=https://<你的项目名>.pages.dev python3 build.py-npx wrangler pages deploy dist --project-name <你的项目名>+```sh+git clone https://github.com/atuizz/posewear.git+cd posewear+npm ci+npm start```-- 第一次运行时,wrangler 会提示创建项目;之后同一条命令就是更新。-- `functions/api/proxy.js` 会作为 Pages Function 一起部署,只用于转发 API 请求。建议在 Cloudflare 控制台给 `/api/proxy` 加一条限流规则。-- CSP 等响应头由 `post.py` 生成在 `dist/_headers` 里。--## 测试--测试用 Playwright 拦截各服务商的接口,模拟成功、密钥错误、限流、5xx、超时、取消、安全拦截、多张输出等情况,不需要真实的 Key。--```bash-npm install && npx playwright install chromium-python3 -m http.server 8787 -d dist &-node tests/v12.js # 图库、收藏、灯箱、路由、移动端-node tests/v13.js # 试穿工作台全流程、深色模式、长文本-node tests/v14-xai.js # xAI / Grok 服务商-node tests/v16-proxy.mjs # /api/proxy 转发规则单元测试-node tests/v17-history.js # 生成记录页冒烟-python3 tests/check_csp.py dist # 校验全部图片源站都在 CSP 白名单内-U=https://posewear.pages.dev node tests/v12.js # 直接测线上-```--## 目录结构--```-src/ 前端源码,无框架- app.js 图库、搜索筛选、收藏最近、灯箱、路由- studio.js 试穿工作台:服务商适配、进度、结果、历史、减少误拦截- history.js 生成记录页:批量打包、导出、重新生成、前后对比- extras.js 批量操作、导入导出- style.css 样式(含深色模式)- sw.js / zip.js 离线缓存 / 打包下载-functions/api/proxy.js Pages Function,转发 API 请求-build.py / post.py 生成缩略图、数据、详情页、sitemap、_headers-costume_text.py 服装中英文描述-words.txt, tr_*.txt 词表与中英文翻译-depth/ 深度姿势素材包(只有文本,图片热链原站)-depthpack.py 把素材包编成可替换的 depths.json-scripts/ fetch-assets.py 下载素材,make-icons.js 生成图标-tests/ Playwright 测试-docs/ README 用图-```--## 常见问题--<details>-<summary><b>API Key 安全吗?</b></summary>--Key 只存在你浏览器的 localStorage 里,可在设置里清除。默认由浏览器直接请求服务商的官方接口。只有两种情况会经过本站的 `/api/proxy`:开启了「通过本站代理转发」,或使用自定义中转。这时它只按原样转发,不记录、不保存密钥和图片,并拒绝转发到内网地址。在公共电脑上用完记得清除。如果不放心,可以自己部署一份。-</details>--<details>-<summary><b>为什么会被「安全审核」拦下?</b></summary>+打开[本地图库](http://127.0.0.1:8787/)。浏览、收藏和复制参考图均无需账号或 API 密钥。-各家服务商都会审核输入的照片和生成的结果。真人照片配上泳装、内衣、露背等比较暴露的服装,最容易被拦,OpenAI 最严,Gemini 和 Seedream 相对宽松。「减少误拦截」可以降低正常穿搭被误判的概率,但不会、也不应该绕过对违规内容的审核。被拦时可以换一家服务商,或换一套服装。-</details>+## 从选图到出图-<details>-<summary><b>素材可以商用吗?</b></summary>+| 在哪里 | 可以做什么 |+| --- | --- |+| 素材库 | 在姿势卡片底部选择机位,点左上角编号可翻到对应深度图,再点一次回到线稿。同一动作、同一角度的两面可一起用于生成。 |+| 悬浮工作台 | 点卡片上的加号收集素材。展开底部创作条后也能继续浏览和换库。复制单条或组合提示词时,默认附上所选视角的公开图片直链;转发时请另附本地上传的照片。 |+| 完整工作台 | 人物、服装、姿势可以自由组合;表情、发型、场景、光影、道具和家具集中在「其他素材」。可以只用一个道具,也可以只写提示词。工作台会记住手改的提示词、张数和比例。试穿时可上传自己的照片对比成品。 |+| 我的 → 生成记录 | 查看成品、下载图片,或将图片、提示词与参数打成 ZIP。当前浏览器最多保存 200 条记录。 |-本仓库不包含任何图片,素材版权归原作者所有,请以各原站的说明为准。人像库作者声明为 CC0。本仓库的 MIT 许可只覆盖代码和文案。-</details>+-<details>-<summary><b>生成要多久、花多少钱?</b></summary>+[查看人物、服装和姿势组合后的试穿示例](docs/banner.jpg)-通常每张半分钟左右,费用按你所用服务商的价格从你的账户扣除,本站不收费。-</details>+图库将 12 个库按姿态、人物造型、服饰、环境与物件归为四组。手机也可直接选图。地球图标可分别设置界面语言(中、英、日)与素材描述语言(中、英),以及复制时是否附图链。外观默认跟随系统,可在页头切换浅色或深色;铃铛集中显示更新和操作提示。-## 路线图+<table><tr><td width="28%" valign="top"><img src="docs/mobile.jpg" alt="手机上的 PoseWear" width="100%"></td><td valign="top"><img src="docs/dark.jpg" alt="深色模式下的 PoseWear" width="100%"></td></tr></table>-- [ ] 更多服务商与模型预设-- [x] 生成记录导出(v1.1.0 已上线:ZIP 含提示词与参数)-- [ ] 增量更新素材(只下载新增内容)-- [ ] 更完整的英文界面文案+## 选择生成方式-欢迎在 [Issues](https://github.com/atuizz/posewear/issues) 里提建议。+- **云端服务。** 在工作台的服务商设置中填写自己的密钥。支持 OpenAI、Gemini、豆包 Seedream 及兼容 OpenAI、Gemini、xAI 图片协议的 HTTPS 服务。直连会将密钥、提示词和图片送往所选服务;启用代理时由本站 Pages Function 转发。费用和配额由服务商决定。+- **本机模型。** 启动 ComfyUI,在本地工作台选择「ComfyUI」,测试连接并选取已安装的 checkpoint。内置工作流接受一张参考图;多图可以接入自定义工作流。使用 stable-diffusion.cpp 的 `sd-server` 时,以 `POSEWEAR_LOCAL_ENGINE=sd-cpp npm start` 启动预览。[本机引擎配置](docs/local-engines.md)+- **交给智能体。** 在仓库根目录运行 `codex mcp add posewear -- node "$PWD/mcp/server.mjs"`,新开会话即可让智能体搜索素材、按角度取图和组合提示词。例如「找一个侧面的坐姿,配一套春装,给我提示词和两张参考图的链接」。其他 stdio 客户端可用 `node` 启动仓库中的 `mcp/server.mjs`(填写绝对路径)。[MCP 设置与示例](mcp/README.md) · [选图 Skill](.agents/skills/posewear/SKILL.md)-## 参与贡献+收藏、工作台草稿与 API 密钥保存在当前浏览器的 localStorage,生成记录保存在 IndexedDB。清除站点数据会一并删除这些内容。-欢迎提 Issue 和 PR:+## 开发与测试-1. Fork 后新建分支;-2. 改动前端后运行 `python3 build.py` 和 `node tests/v12.js && node tests/v13.js`;-3. PR 里说明改了什么,界面改动附截图。+界面使用原生 JS、HTML 和 CSS,Python 负责构建静态站,Cloudflare Pages Function 提供可选的生成代理。开发界面直接使用 `npm start`。从原图构建完整站点还需要 Python 3.9+、Pillow、原始素材及扩展库档案。-文案请保持口语、简洁;不提交任何素材图片或密钥。+运行 `npx playwright install chromium` 安装测试浏览器。运行 `npm run test:offline` 可用本地测试素材执行回归。完整测试需按开发手册启动 staging 服务,再在仓库根目录执行 `U=http://127.0.0.1:8902 npm test`。浏览器回归使用模拟的生图服务响应。[构建、素材准备与测试步骤](AGENTS.md)-## 致谢+**v1.3.0(2026-11-24)** 姿势与深度图可在原位翻面,悬浮工作台支持连续选材,完整工作台支持单素材与纯提示词生图。新增携图复制、三语界面、本机引擎与 MCP。[发布说明](https://github.com/atuizz/posewear/releases/tag/v1.3.0) · [历史版本](CHANGELOG.md#zh)-- [AI Pose Gallery](https://ai-pose-gallery.pages.dev/):姿势线稿-- [AI Pose Depth Gallery](https://ai-pose-depth-gallery.pages.dev/):深度姿势,作者 [ギア / @giaaibusi](https://x.com/giaaibusi)。非官方汉化;图片由本站自存分发,版权归原作者-- CharaDB(作者 たき AI):发型库与动画服装并入部分的数据来源,标签数据 CC0;图片热链原站托管,本站不保存-- [AI Costume Gallery](https://ai-costume-gallery.pages.dev/):服装图,作者 [@giaaibusi](https://x.com/giaaibusi)-- [AI Costume Anime Gallery](https://ai-costume-anime-gallery.pages.dev/):动画服装图,作者 [@giaaibusi](https://x.com/giaaibusi)-- [AI Portrait Gallery](https://ai-portrait-gallery.pages.dev/):人像,作者 [@agi_aibusi](https://x.com/agi_aibusi),CC0-- [wzc520pyfm/gen-ai-pose-image](https://github.com/wzc520pyfm/gen-ai-pose-image)、[paipiange/nvzhuang](https://github.com/paipiange/nvzhuang):给了很多思路的同类项目+## 许可与致谢-## 许可与素材边界+代码、界面文案和构建脚本采用 [MIT](LICENSE)。素材及截图中的图片各有其来源与使用条件。自建站请保留来源与作者说明。-| 内容 | 是否在本仓库 | 许可 |-|---|---|---|-| 代码、页面文案、构建脚本 | 是 | [MIT](LICENSE) |-| 姿势、服装图片和原始数据 | 否,由 `fetch-assets.py` 从原站下载 | 归原作者 [@giaaibusi](https://x.com/giaaibusi) 所有([AI Pose Gallery](https://ai-pose-gallery.pages.dev/) / [AI Costume Gallery](https://ai-costume-gallery.pages.dev/) / [AI Costume Anime Gallery](https://ai-costume-anime-gallery.pages.dev/)),原站未标明开放许可 |-| 人像图片 | 否,同上 | [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/deed.zh-hans),作者 [@agi_aibusi](https://x.com/agi_aibusi)([AI Portrait Gallery](https://ai-portrait-gallery.pages.dev/)) |-| 深度姿势图片 | 否,本站自存于 CDN 分发(源自 [AI Pose Depth Gallery](https://ai-pose-depth-gallery.pages.dev/)) | 归作者 [ギア / @giaaibusi](https://x.com/giaaibusi)。本仓库只有文本元数据和译名 |-| 发型与 CharaDB 动画服装图片 | 否,页面 `<img>` 热链 CharaDB 原站 | 标签数据 CC0;图片版权归 CharaDB 作者 たき AI,本站不保存、不再分发 |-| 深度姿势文本元数据 | 是,`depth/packs/` | 日文原文归原作者,中文译名为本站 |-| README 截图 | 是 | 截图里的图片素材同上,归各自作者 |+| 素材 | 来源与使用条件 |+| --- | --- |+| 姿势、深度姿势、服装、动画服装 | ギア / @giaaibusi。商用、转载、二次分发请向作者确认。仓库收录深度姿势日文文本及本站中文译名,图片由素材 CDN 分发。[线稿](https://ai-pose-gallery.pages.dev/) · [深度图](https://ai-pose-depth-gallery.pages.dev/) · [服装](https://ai-costume-gallery.pages.dev/) · [动画服装](https://ai-costume-anime-gallery.pages.dev/) |+| 人像 | @agi_aibusi 的虚构 AI 人像,CC0。作者希望避免原样批量转载。[AI Portrait Gallery](https://ai-portrait-gallery.pages.dev/) |+| 发型与部分动画服装 | たき AI / CharaDB,标签为 CC0。图片归作者所有,直接从原站加载。[CharaDB](https://charadb-2fi.pages.dev/) |+| 表情 | WaveSpeed AI Emotion Gallery;使用 ICT Face Model Light 头模(© USC Institute for Creative Technologies,MIT)。 |+| 历代服饰、场景、光影、道具、家具 | Shisei / wquguru,CC0 1.0。 |-- MIT 只覆盖代码,不覆盖任何图片和数据。-- 想转载、商用或二次分发姿势、服装图片,请先联系原作者 @giaaibusi,以原站说明为准。-- 人像为 CC0,可商用、可修改、无需署名;均为 AI 生成的虚构人物,不要用来冒充真人。原作者希望不要原样批量转载。-- 自己部署时,请保留页面里的来源与作者说明。+感谢两个开源项目带来的灵感。[gen-ai-pose-image](https://github.com/wzc520pyfm/gen-ai-pose-image) · [nvzhuang](https://github.com/paipiange/nvzhuang)diff --git a/build.py b/build.pyindex c77c158..1fd8407 100644--- a/build.py+++ b/build.py@@ -1,12 +1,28 @@-import json,os,shutil,subprocess,depthpack+import argparse,json,os,shutil,subprocess,depthpackfrom costume_text import gen2import hashlib,re,html as H-from concurrent.futures import ProcessPoolExecutor+from concurrent.futures import ThreadPoolExecutorfrom PIL import Image# 素材目录:默认 ./assets-raw,可用环境变量 POSEWEAR_RAW 指定(见 scripts/fetch-assets.py)R=os.environ.get('POSEWEAR_RAW','assets-raw'); D='dist'# 分离部署:设 POSEWEAR_ASSET_HOST 后,缩略图与原图输出到 dist-assets(独立 Pages 站),主站文件数压回免费版上限内;不设则单站构建,行为不变AHOST=os.environ.get('POSEWEAR_ASSET_HOST','').rstrip('/'); AD='dist-assets'; AROOT=AD if AHOST else D+args = argparse.ArgumentParser(description="Build the PoseWear static site")+args.add_argument('--allow-partial', action='store_true', help="allow missing extension archives for local development")+options = args.parse_args()+ARCHIVES = [f'{kind}/data.json' for kind in ('expression','dynasty','scene','light','prop','furn')] + ['charadb/hair.json','charadb/outfits.json']+missing = []+for archive in ARCHIVES:+ path = os.path.join(R, archive)+ if not os.path.isfile(path):+ missing.append(archive)+ continue+ with open(path) as source:+ items = json.load(source)+ if not isinstance(items, list) or not items:+ missing.append(archive)+if missing and not options.allow_partial:+ args.error("Missing or empty extension archives: " + ", ".join(missing) + ". See AGENTS.md or use --allow-partial for local development.")if AHOST: os.makedirs(AD,exist_ok=True)LINE={'全身1人・セクシー系':('全身·性感','full body, solo, sexy'),'全身1人・標準系':('全身·标准','full body, solo'),'上半身1人':('上半身','upper body, solo'),'2人絡み':('双人互动','two people, couple')}CAT={'寝そべり':'躺卧','セクシー・露骨寄り系':'性感·大胆','立ち':'站姿','座り':'坐姿','かわいい系':'可爱','胸寄せ・谷間強調系':'挤胸·乳沟','膝立ち・四つん這い':'跪立·趴姿','特殊':'特殊','正常位':'正面位','膝立ち':'跪立','横座り・女の子座り':'侧坐·鸭子坐','後背位':'后入位','背面座位':'背面坐位','しゃがみ':'蹲姿','前かがみ':'前倾','顔寄せ系':'贴脸','騎乗位':'骑乘位','立位':'立位','立位密着':'立位贴身','のけぞり・反り':'后仰','ひねり':'扭身','側位':'侧位','座位':'坐位','対面座位':'对面坐位','座位密着':'坐位贴身','密着':'贴身'}@@ -24,7 +40,8 @@ cos=[{'id':d['id'],'cat':CC[d['カテゴリ']][0],'catEn':CC[d['カテゴリ']][acs=[{'id':d['id'],'cat':CC[d['カテゴリ']][0],'catEn':CC[d['カテゴリ']][1],'kw':d['キーワード'],**dict(zip(('zh','en','ti'),gen2(d['キーワード'],CC[d['カテゴリ']][1],d['id']))),'t':'a/t/'+os.path.basename(d['サムネ']),'m':'a/m/'+d['id']+'.webp','i':'a/i/'+os.path.basename(d['画像']),'o':'o/a/'+d['id']+'.png','_src':d} for d in ad]# 双人 分类人工复核(看图)FIX={'pair60_P031':'坐位','pair60_P053':'立位贴身','pair60_P055':'侧位','pair60_P058':'贴脸'}-for k,v in FIX.items(): poses[k]['cat']=v+for k,v in FIX.items():+ if k in poses: poses[k]['cat']=vADULT_LINES={'双人互动','全身·性感'};ADULT_CATS={'挤胸·乳沟','性感·大胆'};ADULT_COS={'内衣','性感'}for p in poses.values():if p['line'] in ADULT_LINES or p['cat'] in ADULT_CATS: p['a']=1@@ -33,6 +50,11 @@ for c in cos:for c in acs:if c['cat'] in ADULT_COS: c['a']=1os.makedirs(D,exist_ok=True)+partial_marker = os.path.join(D, '.posewear-partial')+if missing:+ with open(partial_marker, 'w') as marker: marker.write('\n'.join(missing))+elif os.path.exists(partial_marker):+ os.remove(partial_marker)for f in os.listdir('src'): shutil.copy('src/'+f,D)J=lambda o:json.dumps(o,ensure_ascii=False,separators=(',',':'))SRC={}@@ -156,8 +178,10 @@ if os.path.exists(f'{AROOT}/p/t'):for f in os.listdir(f'{AROOT}/p/t'):if f.endswith('.jpg'): os.remove(f'{AROOT}/p/t/{f}')if AHOST:- open(f'{AD}/_headers','w').write('/*\n Cache-Control: public, max-age=31536000, immutable\n Access-Control-Allow-Origin: *\n/o/*\n Content-Disposition: attachment\n')-with ProcessPoolExecutor() as ex: list(ex.map(cv,pd)); list(ex.map(cm,cd)); list(ex.map(ca,ad)); list(ex.map(cr,rd))+ open(f'{AD}/_headers','w').write('/*\n Cache-Control: public, max-age=0, must-revalidate\n Access-Control-Allow-Origin: *\n/o/*\n Content-Disposition: attachment\n')+with ThreadPoolExecutor(max_workers=min(os.cpu_count() or 1, 8)) as ex:+ for convert, records in ((cv,pd),(cm,cd),(ca,ad),(cr,rd)):+ list(ex.map(convert,records))for _sub,_items in NEWMODS: _cnew(_sub,_items)# 深度姿势:只解析素材包里的文本,热链包不复制图片(见 depthpack.py)_dc=depthpack.catalog(); DJ=J(_dc['payload']); DEPTH_ORIGINS=_dc['origins']diff --git a/depth/packs/gia-depth/manifest.json b/depth/packs/gia-depth/manifest.jsonindex 162eba7..9d105dc 100644--- a/depth/packs/gia-depth/manifest.json+++ b/depth/packs/gia-depth/manifest.json@@ -12,7 +12,7 @@"credit": "素材来自 ai-pose-depth-gallery,作者ギア(https://x.com/giaaibusi)","unofficial": "非官方汉化","referrerPolicy": "no-referrer",- "note": "图片由原站托管,本站不保存。双人互动默认隐藏,需打开右上角「18+」并确认已满 18 岁。",+ "note": "双人互动默认隐藏,需打开右上角「18+」并确认已满 18 岁。","items": "items.json","gatedLines": ["2人絡み"],"fields": {diff --git a/docs/comfyui/img2img-api.json b/docs/comfyui/img2img-api.jsonnew file mode 100644index 0000000..c35abee--- /dev/null+++ b/docs/comfyui/img2img-api.json@@ -0,0 +1,10 @@+{+ "1": {"class_type":"CheckpointLoaderSimple","inputs":{"ckpt_name":"YOUR_CHECKPOINT.safetensors"}},+ "2": {"class_type":"LoadImage","_meta":{"title":"PoseWear Image 1"},"inputs":{"image":"reference.jpg"}},+ "3": {"class_type":"CLIPTextEncode","_meta":{"title":"PoseWear Prompt"},"inputs":{"text":"","clip":["1",1]}},+ "4": {"class_type":"CLIPTextEncode","inputs":{"text":"","clip":["1",1]}},+ "5": {"class_type":"VAEEncode","inputs":{"pixels":["2",0],"vae":["1",2]}},+ "6": {"class_type":"KSampler","_meta":{"title":"PoseWear Seed"},"inputs":{"seed":1,"steps":20,"cfg":7,"sampler_name":"euler","scheduler":"normal","denoise":0.6,"model":["1",0],"positive":["3",0],"negative":["4",0],"latent_image":["5",0]}},+ "7": {"class_type":"VAEDecode","inputs":{"samples":["6",0],"vae":["1",2]}},+ "8": {"class_type":"SaveImage","_meta":{"title":"PoseWear Output"},"inputs":{"filename_prefix":"PoseWear","images":["7",0]}}+}diff --git a/docs/dark-en.jpg b/docs/dark-en.jpgnew file mode 100644index 0000000..3a3cdefBinary files /dev/null and b/docs/dark-en.jpg differdiff --git a/docs/dark-ja.jpg b/docs/dark-ja.jpgnew file mode 100644index 0000000..2d21019Binary files /dev/null and b/docs/dark-ja.jpg differdiff --git a/docs/dark.jpg b/docs/dark.jpgindex b67be05..71addd9 100644Binary files a/docs/dark.jpg and b/docs/dark.jpg differdiff --git a/docs/home-en.jpg b/docs/home-en.jpgnew file mode 100644index 0000000..243870bBinary files /dev/null and b/docs/home-en.jpg differdiff --git a/docs/home-ja.jpg b/docs/home-ja.jpgnew file mode 100644index 0000000..eb63811Binary files /dev/null and b/docs/home-ja.jpg differdiff --git a/docs/home.jpg b/docs/home.jpgindex bd86c4d..8c966dd 100644Binary files a/docs/home.jpg and b/docs/home.jpg differdiff --git a/docs/local-engines.md b/docs/local-engines.mdnew file mode 100644index 0000000..5bf68bf--- /dev/null+++ b/docs/local-engines.md@@ -0,0 +1,44 @@+# 在本机工作台生图++本地预览默认使用云端服务商,也可以连接本机的 ComfyUI 或 stable-diffusion.cpp。两种工作台共用同一份服务商设置。++## 用 ComfyUI 和一张参考图开始++1. 启动 ComfyUI,默认地址为 `http://127.0.0.1:8188`。从 PoseWear 仓库根目录运行 `npm ci` 和 `npm start`。+2. 打开[本地工作台](http://127.0.0.1:8787/#studio),进入服务商设置,选择「ComfyUI」,点「测试连接」。从返回的列表中选一个已安装、兼容的 checkpoint,点击保存。+3. 在「生图」模式选一套服装,将画幅设为「自动」或选择所需比例,即可用这张图生成。也可以从悬浮工作台选择一件服装生成。++自带工作流加载你在界面上选定的 checkpoint,使用一张参考图。画幅选「自动」会沿用参考图比例,手动选比例会居中裁切到对应画幅。[查看工作流](comfyui/img2img-api.json)++### 自定义多参考图工作流++若要同时使用人物、服装与姿势,请在 ComfyUI 中连接自己的多图工作流,按下表设置节点标题,导出为 API 格式的 JSON,再重新启动 PoseWear。++```sh+POSEWEAR_LOCAL_ENGINE=comfyui \+POSEWEAR_COMFY_WORKFLOW=/absolute/path/to/workflow-api.json \+npm start+```++| 节点标题 | 工作台如何使用 |+| --- | --- |+| `PoseWear Prompt` | 把最终提示词写入该节点的 `text` 输入。 |+| `PoseWear Image 1`、`PoseWear Image 2` … | 按顺序绑定到 `LoadImage` 节点。输入顺序为人物、服装、姿势、表情、其他素材。节点数量须匹配本次生成实际传入的图片数量。 |+| `PoseWear Output` | 从这个输出节点读取一张生成图片。 |+| `PoseWear Size`(可选) | 选择指定画幅时写入 `width` 和 `height`。自动画幅使用工作流本身的尺寸设置。 |+| `PoseWear Seed`(可选) | 为该节点的 `seed` 输入写入新的随机种子。 |++取消生成会停止工作台等待,并尝试删除本次尚在队列中的任务。正在 GPU 上执行的任务可能继续完成。上传的输入和生成的文件按自己的 ComfyUI 存储策略保留。[ComfyUI 服务端路由](https://docs.comfy.org/development/comfyui-server/comms_routes)++## stable-diffusion.cpp++使用提供图片编辑接口的 `sd-server`,加载支持参考图的模型。服务默认位于 `127.0.0.1:1234`。++```sh+npm ci+POSEWEAR_LOCAL_ENGINE=sd-cpp npm start+```++工作台通过 `/v1/models` 检查连接,有参考图时把每张图作为一个 `image[]` 字段交给 `/v1/images/edits`,纯提示词则使用 `/v1/images/generations`。模型和构建版本决定可以使用的参考图数量与出图效果。[sd-server 接口文档](https://github.com/leejet/stable-diffusion.cpp/blob/master/examples/server/api.md)++两个引擎都可以通过 `POSEWEAR_LOCAL_URL` 指定其他回环端口。工作台通过本机预览进程把提示词和选中图片送给本机服务。首次载入公开图库仍需联网。[GitHub 议题 #23](https://github.com/atuizz/posewear/issues/23)diff --git a/docs/mobile-en.jpg b/docs/mobile-en.jpgnew file mode 100644index 0000000..0471327Binary files /dev/null and b/docs/mobile-en.jpg differdiff --git a/docs/mobile-ja.jpg b/docs/mobile-ja.jpgnew file mode 100644index 0000000..bf76e42Binary files /dev/null and b/docs/mobile-ja.jpg differdiff --git a/docs/mobile.jpg b/docs/mobile.jpgindex b68b3bc..21b250a 100644Binary files a/docs/mobile.jpg and b/docs/mobile.jpg differdiff --git a/docs/studio-en.jpg b/docs/studio-en.jpgnew file mode 100644index 0000000..758caa7Binary files /dev/null and b/docs/studio-en.jpg differdiff --git a/docs/studio-ja.jpg b/docs/studio-ja.jpgnew file mode 100644index 0000000..5a199b8Binary files /dev/null and b/docs/studio-ja.jpg differdiff --git a/docs/studio.jpg b/docs/studio.jpgindex c3fed17..32b86a6 100644Binary files a/docs/studio.jpg and b/docs/studio.jpg differdiff --git a/functions/api/proxy.js b/functions/api/proxy.jsindex 2a6e8a1..2cb91f0 100644--- a/functions/api/proxy.js+++ b/functions/api/proxy.js@@ -1,11 +1,7 @@-// 衣姿 PoseWear 转发代理(v10):只转发、不记录、不存储任何请求内容或密钥。-// 限制:① 只接受本站页面发起的请求(Origin / Referer 同源);② 官方接口只走标准 https;-// 自定义中转必须带 x-proxy-custom: 1 且路径符合图片接口格式,可用 http/https 任意端口(内网地址除外);-// ③ 结果图片只从官方结果 CDN 下载;④ 每 IP 频率限制。const API_PATH=/^\/(api\/v3|v\d+(beta|alpha)?)\/(images\/(edits|generations)|models(\/[^/]+(:generateContent)?)?)$/;-const OFFICIAL=[/^api\.openai\.com$/,/^generativelanguage\.googleapis\.com$/,/^ark\.[a-z0-9-]+\.volces\.com$/,/^ark\.[a-z0-9-]+\.bytepluses\.com$/];+const OFFICIAL=[/^api\.x\.ai$/,/^api\.openai\.com$/,/^generativelanguage\.googleapis\.com$/,/^ark\.[a-z0-9-]+\.volces\.com$/,/^ark\.[a-z0-9-]+\.bytepluses\.com$/];const IMG_HOSTS=[/^oaidalleapiprodscus\.blob\.core\.windows\.net$/,/(^|\.)volces\.com$/,/(^|\.)bytepluses\.com$/,/(^|\.)googleusercontent\.com$/];-const DROP=['host','x-target-url','x-proxy-kind','x-proxy-custom','cookie','origin','referer','x-forwarded-for','x-forwarded-proto','x-real-ip','content-length','sec-fetch-site','sec-fetch-mode','sec-fetch-dest'];+const FORWARD = ['accept', 'content-type', 'authorization', 'x-goog-api-key'];// 每个 isolate 的内存限流(尽力而为);正式防护建议在 Cloudflare 控制台为 /api/proxy 加速率限制规则。const RL=new Map(),WIN=60e3,MAX_API=20,MAX_IMG=40;function limited(ip,kind){const now=Date.now(),k=kind+'|'+ip;let e=RL.get(k);if(!e||now-e.t>WIN){e={t:now,n:0};RL.set(k,e)}e.n++;@@ -14,7 +10,7 @@ function limited(ip,kind){const now=Date.now(),k=kind+'|'+ip;let e=RL.get(k);if(async function cacheCount(ip,kind,ctx){try{const c=caches.default,m=Math.floor(Date.now()/WIN),key=new Request(`https://rl.invalid/${kind}/${encodeURIComponent(ip)}/${m}`);const r=await c.match(key),n=(r?+(await r.text())||0:0)+1;const p=c.put(key,new Response(String(n),{headers:{'cache-control':'max-age=120'}}));await p;return n}catch(e){return 0}}async function over(ip,kind,ctx){const mem=limited(ip,kind);const n=await cacheCount(ip,kind,ctx);return mem||n>(kind==='img'?MAX_IMG:MAX_API)}-function sameSite(req){const self=new URL(req.url).host;for(const h of['origin','referer']){const v=req.headers.get(h);if(v){try{return new URL(v).host===self}catch(e){return false}}}return false}+function sameSite(req){const self=new URL(req.url).origin;for(const h of['origin','referer']){const v=req.headers.get(h);if(v){try{return new URL(v).origin===self}catch(e){return false}}}return false}export async function onRequest(ctx){const {request}=ctx;if(request.method==='OPTIONS')return new Response(null,{status:204});if(!['GET','POST'].includes(request.method))return j(405,'只支持 GET / POST');@@ -22,11 +18,11 @@ export async function onRequest(ctx){const {request}=ctx;let t;try{t=new URL(request.headers.get('x-target-url')||'')}catch(e){return j(400,'缺少或无效的 x-target-url')}if(t.username||t.password)return j(400,'目标地址不能带账号密码');const official0=OFFICIAL.some(r=>r.test(t.hostname));- if(official0?(t.protocol!=='https:'||(t.port&&t.port!=='443')):!/^https?:$/.test(t.protocol))return j(400,official0?'官方接口地址必须是标准 https 地址':'目标地址必须是 http/https 地址');+ if(t.protocol!=='https:' || (official0 && t.port))return j(400,'目标必须使用 HTTPS;官方接口只支持标准端口');const ip=request.headers.get('cf-connecting-ip')||'0';const img=request.headers.get('x-proxy-kind')==='image';if(img){if(request.method!=='GET')return j(405,'图片下载只支持 GET');- if(!IMG_HOSTS.some(r=>r.test(t.hostname)))return j(403,'该图片地址不在允许范围内');+ if(t.port||!IMG_HOSTS.some(r=>r.test(t.hostname)))return j(403,'该图片地址不在允许范围内');if(await over(ip,'img',ctx))return j(429,'请求过于频繁,请稍后再试');const r=await fetch(t.toString(),{redirect:'manual'}).catch(()=>null);const ct=r&&r.headers.get('content-type')||'';if(!r||!r.ok||!/^image\//.test(ct))return j(502,'结果图片下载失败');return new Response(r.body,{headers:{'content-type':ct,'cache-control':'no-store','x-content-type-options':'nosniff'}})}@@ -34,10 +30,13 @@ export async function onRequest(ctx){const {request}=ctx;if(!official&&!custom)return j(403,'该地址不是官方接口;自定义中转需在设置中选择「自定义」');const path=t.pathname.replace(/\/+$/,'');if(official?!API_PATH.test(path):!/\/(images\/(edits|generations)|models(\/[^/]+(:generateContent)?)?)$/.test(path))return j(403,'该路径不允许通过代理转发');- if(custom&&/^(localhost|127\.|10\.|192\.168\.|169\.254\.|\[)/.test(t.hostname))return j(403,'不能转发到内网地址');+ // Administrators opt in each relay by exact HTTPS origin, including any nonstandard port.+ // Browser direct mode is available for arbitrary HTTPS relays that support CORS.+ const relays = (ctx.env?.POSEWEAR_PROXY_ORIGINS || '').split(/[\s,]+/).filter(Boolean);+ if(!official && !relays.includes(t.origin))return j(403,'本站代理未登记此中转。请关闭代理直连,或联系部署者登记 HTTPS 来源。');if(await over(ip,'api',ctx))return j(429,'请求过于频繁,请稍后再试');- const h=new Headers();for(const[k,v]of request.headers){const l=k.toLowerCase();if(!DROP.includes(l)&&!l.startsWith('cf-'))h.set(k,v)}- try{const r=await fetch(t.toString(),{method:request.method,headers:h,body:request.method==='POST'?request.body:undefined,redirect:'manual'});+ const h=new Headers();for(const name of FORWARD)if(request.headers.has(name))h.set(name,request.headers.get(name));+ try{const r=await fetch(t.toString(),{method:request.method,headers:h,...(request.method==='POST'?{body:request.body,duplex:'half'}:{}),redirect:'manual'});const oh=new Headers();['content-type'].forEach(k=>r.headers.get(k)&&oh.set(k,r.headers.get(k)));oh.set('cache-control','no-store');return new Response(r.body,{status:r.status,headers:oh})}catch(e){return j(502,'代理无法连接目标服务')}diff --git a/functions/package.json b/functions/package.jsonnew file mode 100644index 0000000..3dbc1ca--- /dev/null+++ b/functions/package.json@@ -0,0 +1,3 @@+{+ "type": "module"+}diff --git a/mcp/README.md b/mcp/README.mdnew file mode 100644index 0000000..31bad26--- /dev/null+++ b/mcp/README.md@@ -0,0 +1,53 @@+# PoseWear MCP++Agent 可以从图库中选人物、姿势、服装与环境,取得指定视角的图片直链,再把它们组合成一段可转发的生图提示词。++## 接入++在仓库根目录执行:++```sh+npm ci+codex mcp add posewear -- node "$PWD/mcp/server.mjs"+```++新启的 Codex 会话可以发现这四个工具。项目中的 [PoseWear skill](../.agents/skills/posewear/SKILL.md) 提供选图工作流。++其他支持 stdio 的 MCP 客户端可以使用以下配置。将路径替换为实际仓库的绝对路径:++```json+{+ "mcpServers": {+ "posewear": {+ "command": "node",+ "args": ["/absolute/path/to/posewear/mcp/server.mjs"]+ }+ }+}+```++默认使用 PoseWear 已发布的公开目录,安装后可直接启用。本地开发时,在客户端环境中设置 `POSEWEAR_CATALOG_URL=http://127.0.0.1:8787/` 即可读取 `npm start` 的预览,也可填写自托管站点。分享的图片地址使用该站声明的 canonical URL 与素材域名;自托管时应正确设置构建参数 `POSEWEAR_SITE` 和 `POSEWEAR_ASSET_HOST`。目录在进程内缓存,重启 MCP 服务即可重新读取发布版本。默认隐藏标为成人向的素材;部署者可主动设置 `POSEWEAR_ALLOW_ADULT=1` 以包含这些条目。++## 从搜索到参考图++| 工具 | 用法 |+| --- | --- |+| `posewear_list_collections` | 返回十二个库的 ID、中英日名称和可见条数。 |+| `posewear_search_references` | 按库、关键词检索。返回条目 ID、可用角度数及分页位置 `nextOffset`。 |+| `posewear_get_reference` | 按库、条目 ID 和角度返回直链、提示词和图库详情页。 |+| `posewear_compose_brief` | 按传入顺序生成提示词与参考图清单,`prompt` 可指定自己的文案。 |++例如,先查找 `collection="pose"` 下的站姿并获取所有角度,再将其中一个角度与选好的服装一起传给 `posewear_compose_brief`:++```json+{+ "references": [+ {"collection":"pose","id":"full_single_P001","angle":1},+ {"collection":"costume","id":"SPR-0001"}+ ],+ "language":"zh",+ "prompt":"按第一张图的姿势与机位,穿第二张图的服装。"+}+```++取 `brief` 即可转发。具有生图能力的 Agent 可将 `references[].url` 依次传入模型的参考图输入。MCP 工具只读取目录并返回链接,个人密钥、上传照片和生成记录保留在浏览器;CharaDB 素材继续使用原站热链。diff --git a/mcp/server.mjs b/mcp/server.mjsnew file mode 100644index 0000000..5802e34--- /dev/null+++ b/mcp/server.mjs@@ -0,0 +1,135 @@+import { McpServer } from '@modelcontextprotocol/server';+import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';+import { z } from 'zod';+import { catalogIndex, collections, publishedSite, readCatalog } from '../scripts/catalog-source.mjs';+import { reference, formatBrief } from '../src/references.js';++const server = new McpServer({ name:'posewear', version:'1.0.0' }, {+ instructions:'Find references by collection and ID. Use get_reference for available angles. The URL in a reference is a directly usable image.',+});+const source = process.env.POSEWEAR_CATALOG_URL || publishedSite;+const showAdult = process.env.POSEWEAR_ALLOW_ADULT === '1';+const collectionIds = Object.keys(collections);+const collection = z.enum(collectionIds);+const language = z.enum(['zh','en']).default('zh').describe('Prompt and reference-label language.');+const pick = z.object({+ collection,+ id:z.string().min(1).describe('Exact catalog item ID returned by search. IDs are scoped to their collection.'),+ angle:z.number().int().min(0).default(0).describe('Zero-based view or color-variant index returned by get_reference.'),+});+const image = z.object({label:z.string(),url:z.url()});+const summary = z.object({+ collection, id:z.string(), title:z.string(), category:z.string(), angleCount:z.number().int(),+});+const annotations = { readOnlyHint:true, destructiveHint:false, idempotentHint:true, openWorldHint:true };+let indexPromise;+const records = new Map();++function index() {+ indexPromise ??= catalogIndex(source).catch(error => {indexPromise = undefined; throw error;});+ return indexPromise;+}+function items(type) {+ if (!records.has(type)) {+ const loading = index().then(meta => readCatalog(meta,collections[type].file))+ .then(catalog => catalog.items.filter(item => showAdult || !item.a))+ .catch(error => { records.delete(type); throw error; });+ records.set(type,loading);+ }+ return records.get(type);+}+function summarize(type,item) {+ return {collection:type, id:item.id, title:item.ti || item.zh || item.id,+ category:item.cat || item.sec || '', angleCount:item.angles?.length || 1};+}+function result(value,text = JSON.stringify(value)) {+ return {content:[{type:'text',text}],structuredContent:value};+}+async function resolvePick({collection:type,id,angle},lang) {+ const item = (await items(type)).find(record => record.id === id);+ if (!item) throw new Error(`Reference unavailable: ${type}/${id}. Use posewear_search_references to choose a visible item.`);+ const count = item.angles?.length || 1;+ if (angle >= count) throw new Error(`View ${angle} is unavailable for ${type}/${id}. Choose an index from 0 to ${count-1}.`);+ const view = item.angles?.[angle];+ const {site,assetHost} = await index();+ const ref = reference({...item,type},angle,site,lang,assetHost);+ const prompt = [item[lang], view && (lang === 'en' ? item.lineEn : item.line), view?.[lang]]+ .filter(Boolean).join(lang === 'en' ? ', ' : ',');+ return {item,angle,prompt,ref,page:new URL('#'+type+'/'+encodeURIComponent(id),site).href};+}++server.registerTool('posewear_list_collections',{+ title:'List PoseWear collections',+ description:'Discover all libraries with Chinese, English and Japanese names and visible item counts.',+ inputSchema:z.object({}),+ outputSchema:z.object({collections:z.array(z.object({collection,zh:z.string(),en:z.string(),ja:z.string(),count:z.number()}))}),+ annotations,+}, async () => {+ const list = [];+ for (const type of collectionIds) {+ const [zh,en,ja] = collections[type].names;+ list.push({collection:type,zh,en,ja,count:(await items(type)).length});+ }+ return result({collections:list});+});++server.registerTool('posewear_search_references',{+ title:'Find visual references',+ description:'Search catalog names, descriptions, categories, IDs and view names. Space-separated terms all match. Browse one library with an empty query.',+ inputSchema:z.object({query:z.string().default(''),collection:collection.optional(),+ offset:z.number().int().nonnegative().default(0),limit:z.number().int().min(1).max(40).default(8)}),+ outputSchema:z.object({items:z.array(summary),total:z.number(),nextOffset:z.number().nullable()}),+ annotations,+}, async ({query,collection,offset,limit}) => {+ const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);+ const matches = [];+ for (const type of collection ? [collection] : collectionIds) {+ for (const item of await items(type)) {+ const names = [item.id,item.ti,item.zh,item.en,item.ja].filter(Boolean).map(value => value.toLowerCase());+ const searchText = [...names,item.kw,item.cat,item.catEn,item.catJa,item.line,item.lineEn,item.lineJa,item.no,+ item.sec,item.len,item.st,item.era,item.emo,item.int,...collections[type].names,+ ...(item.angles || []).flatMap(view => [view.zh,view.en,view.ja])].join(' ').toLowerCase();+ if (!terms.every(term => searchText.includes(term))) continue;+ const words = names.join(' ').split(/[^\p{L}\p{N}]+/u);+ let score = 0;+ for (const term of terms) {+ if (names.includes(term)) score += 4;+ else if (words.includes(term)) score += 2;+ else if (names.some(name => name.includes(term))) score += 1;+ }+ matches.push({type,item,score});+ }+ }+ matches.sort((a,b) => b.score-a.score);+ const page = matches.slice(offset,offset+limit).map(({type,item}) => summarize(type,item));+ return result({items:page,total:matches.length,nextOffset:offset+limit < matches.length ? offset+limit : null});+});++server.registerTool('posewear_get_reference',{+ title:'Get an image and its available views',+ description:'Resolve an exact reference to its selected image URL, prompt, entry page and available camera angles or color variants.',+ inputSchema:pick.extend({language}),+ outputSchema:summary.extend({angle:z.number(),angles:z.array(z.object({angle:z.number(),zh:z.string(),en:z.string()})),+ prompt:z.string(),image,page:z.url()}),+ annotations,+}, async input => {+ const {item,angle,prompt,ref,page} = await resolvePick(input,input.language);+ const angles = (item.angles || []).map((view,angle) => ({angle,zh:view.zh || '',en:view.en || ''}));+ return result({...summarize(input.collection,item),angle,angles,prompt,image:ref,page});+});++server.registerTool('posewear_compose_brief',{+ title:'Compose a prompt with reference images',+ description:'Assemble selected references in order into a copy-ready generation brief. Supply prompt to preserve your own wording, or omit it to combine catalog descriptions.',+ inputSchema:z.object({references:z.array(pick).min(1),prompt:z.string().min(1).optional(),language}),+ outputSchema:z.object({brief:z.string(),references:z.array(image)}),+ annotations,+}, async ({references,prompt,language}) => {+ const resolved = await Promise.all(references.map(selection => resolvePick(selection,language)));+ const images = resolved.map(selection => selection.ref);+ const description = prompt ?? resolved.map(({ref,prompt}) => ref.label+' — '+prompt).join('\n');+ const brief = formatBrief(description,images,language);+ return result({brief,references:images},brief);+});++await server.connect(new StdioServerTransport());diff --git a/package-lock.json b/package-lock.jsonnew file mode 100644index 0000000..69a8075--- /dev/null+++ b/package-lock.json@@ -0,0 +1,2330 @@+{+ "name": "posewear",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "posewear",+ "license": "MIT",+ "dependencies": {+ "@modelcontextprotocol/server": "^2.4.0",+ "zod": "^4.6.7"+ },+ "devDependencies": {+ "@modelcontextprotocol/client": "^2.4.0",+ "playwright": "^1.48.0",+ "wrangler": "^4.0.0"+ },+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/@cloudflare/kv-asset-handler": {+ "version": "0.5.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.1.tgz",+ "integrity": "sha512-48OysfSW3MkQY1XjkhkpPkgrEkOvgfoyHzA2eyX5wpzFpijC02uWigv3hkNdJdT3C7ybW/U17yYHXeR68pLeww==",+ "dev": true,+ "license": "MIT OR Apache-2.0",+ "engines": {+ "node": ">=22.0.0"+ }+ },+ "node_modules/@cloudflare/unenv-preset": {+ "version": "2.16.2",+ "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.2.tgz",+ "integrity": "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ==",+ "dev": true,+ "license": "MIT OR Apache-2.0",+ "peerDependencies": {+ "unenv": "2.0.0-rc.24",+ "workerd": ">1.20260305.0 <2.0.0-0"+ },+ "peerDependenciesMeta": {+ "workerd": {+ "optional": true+ }+ }+ },+ "node_modules/@cloudflare/workerd-darwin-64": {+ "version": "1.20261119.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261119.1.tgz",+ "integrity": "sha512-yotoiTGXCl1gTRX+y5ZWSAmzAg6CcBJXhJL6C1DGWUhsjjezNe8FdzraNsefVTOeKsOid2EC+hqOzewczKLvmQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workerd-darwin-arm64": {+ "version": "1.20261119.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261119.1.tgz",+ "integrity": "sha512-VPOmfEmMubvw4SPcg/yDgamQXsiVAENgxeCJO8pDggRJFaF93SP0g/hktD8sbfmWBS19BO1kX1EsdgHSgRL9jA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workerd-linux-64": {+ "version": "1.20261119.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261119.1.tgz",+ "integrity": "sha512-aaDf78smiN12Uuwtg6TG6iLVS61sLpy/7DC5PYORf2+TCYw/bygcaqqb8zQJ+XwZ3xYhm/Ws80c/yMMhCMTFYA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workerd-linux-arm64": {+ "version": "1.20261119.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261119.1.tgz",+ "integrity": "sha512-LkyAvTMcKqRUP73HRScWWwTSz3pw09um1hxR+rcGdvsGzao8IR59XXTp/tul6kFdVBL2mD8U3X6j2O8t7I4viw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workerd-windows-64": {+ "version": "1.20261119.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261119.1.tgz",+ "integrity": "sha512-y4RO3QFNWt4j4uq2kmP5tklTvdA3qOA0PXuA66vsCmEtZYYb71ldefJcq5Dt0jrexKf/i4BBaLXZMVYLnohb0g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workers-utils": {+ "version": "0.56.0",+ "resolved": "https://registry.npmjs.org/@cloudflare/workers-utils/-/workers-utils-0.56.0.tgz",+ "integrity": "sha512-Fw3/zR+pQp+5hKn1CHIRkCYz49fyAb2qRqCq01jBGqlKL0rRnZyXYD4j0h9cjaWPYYQUOe5y6L7BNp2ZwsHg5A==",+ "dev": true,+ "license": "MIT OR Apache-2.0",+ "dependencies": {+ "@cspotcode/source-map-support": "0.8.1",+ "chalk": "5.3.0",+ "dotenv": "16.3.1",+ "undici": "7.30.2"+ },+ "peerDependencies": {+ "vitest": "^4.1.0 || ^5.0.0"+ },+ "peerDependenciesMeta": {+ "vitest": {+ "optional": true+ }+ }+ },+ "node_modules/@cspotcode/source-map-support": {+ "version": "0.8.1",+ "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",+ "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/trace-mapping": "0.3.9"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@emnapi/runtime": {+ "version": "1.11.3",+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",+ "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",+ "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",+ "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",+ "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",+ "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",+ "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",+ "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",+ "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",+ "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",+ "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",+ "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",+ "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",+ "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",+ "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",+ "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",+ "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",+ "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",+ "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",+ "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",+ "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",+ "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",+ "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",+ "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",+ "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",+ "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",+ "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@img/colour": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@img/sharp-darwin-arm64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz",+ "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-arm64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-darwin-x64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz",+ "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-x64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-freebsd-wasm32": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz",+ "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==",+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "dependencies": {+ "@img/sharp-wasm32": "0.35.5"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-arm64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz",+ "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-x64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz",+ "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz",+ "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz",+ "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-ppc64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz",+ "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-riscv64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz",+ "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-s390x": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz",+ "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-x64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz",+ "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz",+ "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {+ "version": "1.3.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz",+ "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-linux-arm": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz",+ "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linux-arm64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz",+ "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linux-ppc64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz",+ "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-ppc64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linux-riscv64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz",+ "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-riscv64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linux-s390x": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz",+ "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-s390x": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linux-x64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz",+ "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-x64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-arm64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz",+ "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-x64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz",+ "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4"+ }+ },+ "node_modules/@img/sharp-wasm32": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz",+ "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==",+ "dev": true,+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/runtime": "^1.11.3"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-webcontainers-wasm32": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz",+ "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==",+ "cpu": [+ "wasm32"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "dependencies": {+ "@img/sharp-wasm32": "0.35.5"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-arm64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz",+ "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-ia32": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz",+ "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-x64": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz",+ "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@jridgewell/resolve-uri": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz",+ "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@jridgewell/trace-mapping": {+ "version": "0.3.9",+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",+ "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/resolve-uri": "^3.0.3",+ "@jridgewell/sourcemap-codec": "^1.4.10"+ }+ },+ "node_modules/@modelcontextprotocol/client": {+ "version": "2.4.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.4.0.tgz",+ "integrity": "sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/core": "2.4.0",+ "cross-spawn": "^7.0.5",+ "eventsource": "^3.0.2",+ "eventsource-parser": "^3.0.8",+ "jose": "^6.1.3",+ "pkce-challenge": "^5.0.0",+ "zod": "^4.2.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@modelcontextprotocol/core": {+ "version": "2.4.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.4.0.tgz",+ "integrity": "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "zod": "^4.2.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@modelcontextprotocol/server": {+ "version": "2.4.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.4.0.tgz",+ "integrity": "sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@modelcontextprotocol/core": "2.4.0",+ "zod": "^4.2.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@poppinss/colors": {+ "version": "4.1.6",+ "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz",+ "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "kleur": "^4.1.5"+ }+ },+ "node_modules/@poppinss/dumper": {+ "version": "0.6.5",+ "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz",+ "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@poppinss/colors": "^4.1.5",+ "@sindresorhus/is": "^7.0.2",+ "supports-color": "^10.0.0"+ }+ },+ "node_modules/@poppinss/exception": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz",+ "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@sindresorhus/is": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz",+ "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/is?sponsor=1"+ }+ },+ "node_modules/@speed-highlight/core": {+ "version": "1.2.24",+ "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz",+ "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==",+ "dev": true,+ "license": "CC0-1.0"+ },+ "node_modules/@types/node": {+ "version": "18.19.130",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz",+ "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~5.26.4"+ }+ },+ "node_modules/@types/node-fetch": {+ "version": "2.6.13",+ "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz",+ "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*",+ "form-data": "^4.0.4"+ }+ },+ "node_modules/@types/yargs": {+ "version": "17.0.24",+ "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.24.tgz",+ "integrity": "sha512-6i0aC7jV6QzQB8ne1joVZ0eSFIstHsCrobmOtghM11yGlH0j43FKL2UhWdELkyps0zuf7qVTUVCCR+tgSlyLLw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/yargs-parser": "*"+ }+ },+ "node_modules/@types/yargs-parser": {+ "version": "21.0.3",+ "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz",+ "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/abort-controller": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",+ "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "event-target-shim": "^5.0.0"+ },+ "engines": {+ "node": ">=6.5"+ }+ },+ "node_modules/agentkeepalive": {+ "version": "4.6.0",+ "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz",+ "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "humanize-ms": "^1.2.1"+ },+ "engines": {+ "node": ">= 8.0.0"+ }+ },+ "node_modules/asynckit": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/chalk": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz",+ "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^12.17.0 || ^14.13 || >=16.0.0"+ },+ "funding": {+ "url": "https://github.com/chalk/chalk?sponsor=1"+ }+ },+ "node_modules/cloudflare": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/cloudflare/-/cloudflare-5.2.0.tgz",+ "integrity": "sha512-dVzqDpPFYR9ApEC9e+JJshFJZXcw4HzM8W+3DHzO5oy9+8rLC53G7x6fEf9A7/gSuSCxuvndzui5qJKftfIM9A==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@types/node": "^18.11.18",+ "@types/node-fetch": "^2.6.4",+ "abort-controller": "^3.0.0",+ "agentkeepalive": "^4.2.1",+ "form-data-encoder": "1.7.2",+ "formdata-node": "^4.3.2",+ "node-fetch": "^2.6.7"+ }+ },+ "node_modules/combined-stream": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "delayed-stream": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/cookie": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",+ "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/delayed-stream": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/devtools-protocol": {+ "version": "0.0.1182435",+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1182435.tgz",+ "integrity": "sha512-EmlkWb62wSbQNE1gRZZsi4KZYRaF5Skpp183LhRU7+sadKR06O1dHCjZmFSEG6Kv7P6S/UYLxcY3NlYwqKM99w==",+ "dev": true,+ "license": "BSD-3-Clause"+ },+ "node_modules/dotenv": {+ "version": "16.3.1",+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz",+ "integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/motdotla/dotenv?sponsor=1"+ }+ },+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/error-stack-parser-es": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz",+ "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/antfu"+ }+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",+ "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-set-tostringtag": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6",+ "has-tostringtag": "^1.0.2",+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/esbuild": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",+ "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.28.2",+ "@esbuild/android-arm": "0.28.2",+ "@esbuild/android-arm64": "0.28.2",+ "@esbuild/android-x64": "0.28.2",+ "@esbuild/darwin-arm64": "0.28.2",+ "@esbuild/darwin-x64": "0.28.2",+ "@esbuild/freebsd-arm64": "0.28.2",+ "@esbuild/freebsd-x64": "0.28.2",+ "@esbuild/linux-arm": "0.28.2",+ "@esbuild/linux-arm64": "0.28.2",+ "@esbuild/linux-ia32": "0.28.2",+ "@esbuild/linux-loong64": "0.28.2",+ "@esbuild/linux-mips64el": "0.28.2",+ "@esbuild/linux-ppc64": "0.28.2",+ "@esbuild/linux-riscv64": "0.28.2",+ "@esbuild/linux-s390x": "0.28.2",+ "@esbuild/linux-x64": "0.28.2",+ "@esbuild/netbsd-arm64": "0.28.2",+ "@esbuild/netbsd-x64": "0.28.2",+ "@esbuild/openbsd-arm64": "0.28.2",+ "@esbuild/openbsd-x64": "0.28.2",+ "@esbuild/openharmony-arm64": "0.28.2",+ "@esbuild/sunos-x64": "0.28.2",+ "@esbuild/win32-arm64": "0.28.2",+ "@esbuild/win32-ia32": "0.28.2",+ "@esbuild/win32-x64": "0.28.2"+ }+ },+ "node_modules/event-target-shim": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",+ "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/eventsource": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "eventsource-parser": "^3.0.1"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/eventsource-parser": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",+ "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/form-data": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",+ "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "asynckit": "^0.4.0",+ "combined-stream": "^1.0.8",+ "es-set-tostringtag": "^2.1.0",+ "hasown": "^2.0.4",+ "mime-types": "^2.1.35"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/form-data-encoder": {+ "version": "1.7.2",+ "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz",+ "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/formdata-node": {+ "version": "4.4.1",+ "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz",+ "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "node-domexception": "1.0.0",+ "web-streams-polyfill": "4.0.0-beta.3"+ },+ "engines": {+ "node": ">= 12.20"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-tostringtag": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "has-symbols": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/humanize-ms": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz",+ "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ms": "^2.0.0"+ }+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/jose": {+ "version": "6.2.18",+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.18.tgz",+ "integrity": "sha512-doV4thUwgkrycJH4yLeqwTGIIZphHl+pk7CPReuMIhYhncmgzdko85MaCG4YQFTxqMFr1/oEH32tZuKKovcDEg==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },+ "node_modules/kleur": {+ "version": "4.1.5",+ "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",+ "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "mime-db": "1.52.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/miniflare": {+ "version": "5.20261119.0-beta",+ "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261119.0-beta.tgz",+ "integrity": "sha512-HdNQIUPgde5Yg0qFaI6iiYd0aOxAgKQTXDstkBN2G1tPBdslNrUKdySwaGdBix0IFd+yh8M0gkqzw68dIZ2Ugw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@cspotcode/source-map-support": "0.8.1",+ "sharp": "0.35.5",+ "undici": "7.30.2",+ "workerd": "1.20261119.1",+ "ws": "8.21.0",+ "youch": "4.1.0-beta.10"+ },+ "engines": {+ "node": ">=22.12.0"+ },+ "peerDependencies": {+ "kerberos": "^2.0.0"+ },+ "peerDependenciesMeta": {+ "kerberos": {+ "optional": true+ }+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/node-domexception": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",+ "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",+ "deprecated": "Use your platform's native DOMException instead",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/jimmywarting"+ },+ {+ "type": "github",+ "url": "https://paypal.me/jimmywarting"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=10.5.0"+ }+ },+ "node_modules/node-fetch": {+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",+ "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "whatwg-url": "^5.0.0"+ },+ "engines": {+ "node": "4.x || >=6.0.0"+ },+ "peerDependencies": {+ "encoding": "^0.1.0"+ },+ "peerDependenciesMeta": {+ "encoding": {+ "optional": true+ }+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-to-regexp": {+ "version": "6.3.0",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz",+ "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/pkce-challenge": {+ "version": "5.0.2",+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.2.tgz",+ "integrity": "sha512-vCc54+qyIfKC5e2UN28AZKElwqjLINgiIV3RKI8pDu93TjaAJoB3QrgMzEBouy8yOKsXVXdAinO1QArJf9x5WA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/playwright": {+ "version": "1.65.1",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz",+ "integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.65.1"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.65.1",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz",+ "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/semver": {+ "version": "7.8.6",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",+ "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/sharp": {+ "version": "0.35.5",+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",+ "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@img/colour": "^1.1.0",+ "detect-libc": "^2.1.2",+ "semver": "^7.8.5"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-darwin-arm64": "0.35.5",+ "@img/sharp-darwin-x64": "0.35.5",+ "@img/sharp-freebsd-wasm32": "0.35.5",+ "@img/sharp-libvips-darwin-arm64": "1.3.4",+ "@img/sharp-libvips-darwin-x64": "1.3.4",+ "@img/sharp-libvips-linux-arm": "1.3.4",+ "@img/sharp-libvips-linux-arm64": "1.3.4",+ "@img/sharp-libvips-linux-ppc64": "1.3.4",+ "@img/sharp-libvips-linux-riscv64": "1.3.4",+ "@img/sharp-libvips-linux-s390x": "1.3.4",+ "@img/sharp-libvips-linux-x64": "1.3.4",+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4",+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4",+ "@img/sharp-linux-arm": "0.35.5",+ "@img/sharp-linux-arm64": "0.35.5",+ "@img/sharp-linux-ppc64": "0.35.5",+ "@img/sharp-linux-riscv64": "0.35.5",+ "@img/sharp-linux-s390x": "0.35.5",+ "@img/sharp-linux-x64": "0.35.5",+ "@img/sharp-linuxmusl-arm64": "0.35.5",+ "@img/sharp-linuxmusl-x64": "0.35.5",+ "@img/sharp-webcontainers-wasm32": "0.35.5",+ "@img/sharp-win32-arm64": "0.35.5",+ "@img/sharp-win32-ia32": "0.35.5",+ "@img/sharp-win32-x64": "0.35.5"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ }+ }+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/supports-color": {+ "version": "10.2.2",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz",+ "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/chalk/supports-color?sponsor=1"+ }+ },+ "node_modules/tr46": {+ "version": "0.0.3",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tslib": {+ "version": "2.9.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",+ "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",+ "dev": true,+ "license": "0BSD",+ "optional": true+ },+ "node_modules/undici": {+ "version": "7.30.2",+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz",+ "integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20.18.1"+ }+ },+ "node_modules/undici-types": {+ "version": "5.26.5",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",+ "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/unenv": {+ "version": "2.0.0-rc.24",+ "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz",+ "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "pathe": "^2.0.3"+ }+ },+ "node_modules/web-streams-polyfill": {+ "version": "4.0.0-beta.3",+ "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz",+ "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 14"+ }+ },+ "node_modules/webidl-conversions": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",+ "dev": true,+ "license": "BSD-2-Clause"+ },+ "node_modules/whatwg-url": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tr46": "~0.0.3",+ "webidl-conversions": "^3.0.0"+ }+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/workerd": {+ "version": "1.20261119.1",+ "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261119.1.tgz",+ "integrity": "sha512-lalSvY+ad5asqMgzA/DfrZo7wvuvOHJc/aS1UctUrwu76fJE/LkSKJlprfBu0LeU79Qai5d+xFooQA9CIfj+dQ==",+ "dev": true,+ "hasInstallScript": true,+ "license": "Apache-2.0",+ "bin": {+ "workerd": "bin/workerd"+ },+ "engines": {+ "node": ">=16"+ },+ "optionalDependencies": {+ "@cloudflare/workerd-darwin-64": "1.20261119.1",+ "@cloudflare/workerd-darwin-arm64": "1.20261119.1",+ "@cloudflare/workerd-linux-64": "1.20261119.1",+ "@cloudflare/workerd-linux-arm64": "1.20261119.1",+ "@cloudflare/workerd-windows-64": "1.20261119.1"+ }+ },+ "node_modules/wrangler": {+ "version": "4.166.0",+ "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.166.0.tgz",+ "integrity": "sha512-qMz0sHGXqEC0Va8T6dAaG0ggp9tCcuHHYMUQzRKbtZg6+MPAPb6oBu1757IaeugNJHPAz+twHiA+zDyXWQLsLw==",+ "dev": true,+ "license": "MIT OR Apache-2.0",+ "dependencies": {+ "@cloudflare/kv-asset-handler": "0.5.1",+ "@cloudflare/unenv-preset": "2.16.2",+ "@cloudflare/workers-utils": "0.56.0",+ "@cspotcode/source-map-support": "0.8.1",+ "@types/yargs": "17.0.24",+ "cloudflare": "5.2.0",+ "devtools-protocol": "0.0.1182435",+ "esbuild": "0.28.2",+ "miniflare": "5.20261119.0-beta",+ "path-to-regexp": "6.3.0",+ "undici": "7.30.2",+ "unenv": "2.0.0-rc.24",+ "workerd": "1.20261119.1"+ },+ "bin": {+ "cf-wrangler": "bin/cf-wrangler.js",+ "wrangler": "bin/wrangler.js",+ "wrangler2": "bin/wrangler.js"+ },+ "engines": {+ "node": ">=22.12.0"+ },+ "optionalDependencies": {+ "fsevents": "2.3.3"+ },+ "peerDependencies": {+ "@cloudflare/workers-types": "^5.20261119.1"+ },+ "peerDependenciesMeta": {+ "@cloudflare/workers-types": {+ "optional": true+ }+ }+ },+ "node_modules/ws": {+ "version": "8.21.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",+ "dev": true,+ "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/youch": {+ "version": "4.1.0-beta.10",+ "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz",+ "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@poppinss/colors": "^4.1.5",+ "@poppinss/dumper": "^0.6.4",+ "@speed-highlight/core": "^1.2.7",+ "cookie": "^1.0.2",+ "youch-core": "^0.3.3"+ }+ },+ "node_modules/youch-core": {+ "version": "0.3.3",+ "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz",+ "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@poppinss/exception": "^1.2.2",+ "error-stack-parser-es": "^1.0.5"+ }+ },+ "node_modules/zod": {+ "version": "4.6.7",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",+ "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/package.json b/package.jsonindex 7f3de46..0f27608 100644--- a/package.json+++ b/package.json@@ -6,11 +6,22 @@"scripts": {"build": "python3 build.py","serve": "python3 -m http.server 8787 -d dist",- "test": "node tests/v12.js && node tests/v13.js",- "deploy": "wrangler pages deploy dist --project-name posewear --branch main"+ "test": "node tests/run.mjs",+ "deploy": "python3 tests/check_csp.py \"${POSEWEAR_STAGING:?Set POSEWEAR_STAGING to a fresh staging copy}\" && cd \"$POSEWEAR_STAGING\" && wrangler pages deploy . --project-name posewear --branch main",+ "start": "node scripts/preview.mjs",+ "mcp": "node mcp/server.mjs",+ "test:offline": "node tests/run.mjs --offline"},"devDependencies": {+ "@modelcontextprotocol/client": "^2.4.0","playwright": "^1.48.0","wrangler": "^4.0.0"+ },+ "dependencies": {+ "@modelcontextprotocol/server": "^2.4.0",+ "zod": "^4.6.7"+ },+ "engines": {+ "node": ">=22.12.0"}}diff --git a/post.py b/post.pyindex 3f23271..6e00787 100644--- a/post.py+++ b/post.py@@ -13,22 +13,27 @@ def put(name,data):base,ext=name.rsplit('.',1);n=f'assets/{base}.{h8(b)}.{ext}';open(f'{D}/{n}','wb').write(b);A[name]=n;return nput('poses.json',PJ);put('costumes.json',CJ);put('anime.json',AJ);put('portraits.json',RJ);put('depths.json',DJ)put('expressions.json',EXJ);put('hair.json',HAJ);put('dynasties.json',DYJ);put('scenes.json',SCJ);put('lights.json',LIJ);put('props.json',PRJ);put('furniture.json',FUJ)-for f in ['style.css','zip.js','extras.js','studio.js','history.js']: put(f,open(f'src/{f}','rb').read())+CLIENT_FILES = ['theme.js','style.css','app.js','zip.js','extras.js','image-providers.js','studio.js','history.js','i18n.js','references.js']+for f in CLIENT_FILES:+ if f != 'app.js': put(f,open(f'src/{f}','rb').read())app=open('src/app.js').read()-if AH: app=app.replace("const AH='';",f"const AH='{AH}/';")-app=app.replace("'poses.json'","'/"+A['poses.json']+"'").replace("'costumes.json'","'/"+A['costumes.json']+"'").replace("'anime.json'","'/"+A['anime.json']+"'").replace("'portraits.json'","'/"+A['portraits.json']+"'").replace("'depths.json'","'/"+A['depths.json']+"'").replace("'expressions.json'","'/"+A['expressions.json']+"'").replace("'hair.json'","'/"+A['hair.json']+"'").replace("'dynasties.json'","'/"+A['dynasties.json']+"'").replace("'scenes.json'","'/"+A['scenes.json']+"'").replace("'lights.json'","'/"+A['lights.json']+"'").replace("'props.json'","'/"+A['props.json']+"'").replace("'furniture.json'","'/"+A['furniture.json']+"'")+if AH: app=app.replace("const AH='';","const AH="+repr(AH+'/')+";")+for name, asset in A.items():+ if name.endswith('.json'): app=app.replace(repr(name),repr('/'+asset))put('app.js',app)-VER='posewear-v10-'+h8(''.join(A.values()))idx=open('src/index.html').read()-for f in ['style.css','app.js','zip.js','extras.js','studio.js','history.js']:+for f in CLIENT_FILES:idx=idx.replace(f'"{f}"',f'"/{A[f]}"')idx=idx.replace('href="poses.json"',f'href="/{A["poses.json"]}"')if WAT: idx=idx.replace('</body>',f'<script defer src="https://static.cloudflareinsights.com/beacon.min.js" data-cf-beacon=\'{{"token": "{WAT}"}}\'></script></body>')open(f'{D}/index.html','w').write(idx)-for f in ['style.css','app.js','zip.js','extras.js','studio.js','history.js']:+for f in CLIENT_FILES:if os.path.exists(f'{D}/{f}'): os.remove(f'{D}/{f}')-sw=open('src/sw.js').read().replace("const V='posewear-v9'",f"const V='{VER}'")-sw=sw.replace("['./','index.html','style.css','app.js','studio.js','extras.js','zip.js','history.js','favicon.svg']",json.dumps(['/','/favicon.svg']+['/'+A[f] for f in ['style.css','app.js','studio.js','extras.js','zip.js','history.js','poses.json','depths.json']]))+sw=open('src/sw.js').read()+version = 'posewear-' + h8(sw + idx + ''.join(A.values()))+sw=sw.replace("'posewear-development'",repr(version))+precache = ['/','/favicon.svg']+['/'+A[f] for f in CLIENT_FILES+['poses.json','depths.json']]+sw=re.sub(r'const PRECACHE = .*?;', 'const PRECACHE = '+json.dumps(precache)+';', sw, count=1)open(f'{D}/sw.js','w').write(sw)import base64inl=re.findall(r'<script>(.*?)</script>',idx,re.S)@@ -36,20 +41,23 @@ SH=' '.join("'sha256-"+base64.b64encode(hashlib.sha256(x.encode()).digest()).dec# ---------- 静态详情页 ----------for d in ['pose','costume','anime','portrait']:if os.path.exists(f'{D}/{d}'): shutil.rmtree(f'{D}/{d}')-CSS='''body{margin:0;font:15px/1.7 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;color:#111;background:#fff}a{color:inherit}-header{display:flex;align-items:center;gap:10px;padding:14px 20px;border-bottom:1px solid #f0f0f0}header a{text-decoration:none;font-weight:700;display:flex;align-items:center;gap:8px}+THEME_HEAD = f'<meta name="theme-color" content="#ffffff"><script src="/{A["theme.js"]}"></script>'+DARK_TOKENS = 'color-scheme:dark;--paper:#111;--ink:#eee;--muted:#aaa;--surface:#1d1d1d;--surface-hover:#292929;--edge:#333'+CSS = (':root{color-scheme:light;--paper:#fff;--ink:#111;--muted:#606060;--surface:#f5f5f5;--surface-hover:#ececec;--edge:#ededed}'+ ':root[data-theme="dark"]{' + DARK_TOKENS + '}'+ '@media(prefers-color-scheme:dark){:root:not([data-theme]){' + DARK_TOKENS + '}}') + '''body{margin:0;font:15px/1.7 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;color:var(--ink);background:var(--paper)}a{color:inherit}+header{display:flex;align-items:center;gap:10px;padding:14px 20px;border-bottom:1px solid var(--edge)}header a{text-decoration:none;font-weight:700;display:flex;align-items:center;gap:8px}.mk{width:26px;height:26px;color:#ff2442;display:grid;place-items:center}.mk svg{width:26px;height:26px}main{max-width:1040px;margin:0 auto;padding:24px 20px;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:32px}@media(max-width:760px){main{grid-template-columns:1fr}}-.im img{width:100%;height:auto;border-radius:16px;background:#f5f5f5;display:block}-h1{font-size:24px;margin:0 0 6px}.mu{color:#666;font-size:13px}.bc{font-size:13px;color:#666;margin-bottom:12px}-.box{background:#f5f5f5;border-radius:14px;padding:14px 16px;margin:14px 0}.box small{color:#666}-.go{display:inline-block;background:#d81b3a;color:#fff;border-radius:999px;padding:10px 22px;text-decoration:none;font-weight:600;margin:6px 8px 6px 0}-.rel{grid-column:1/-1}.rel ul{list-style:none;padding:0;display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:12px}.rel img{width:100%;height:auto;border-radius:10px;background:#f5f5f5;display:block}.rel a{text-decoration:none;font-size:13px}-footer{text-align:center;color:#666;font-size:12px;padding:30px 20px;border-top:1px solid #f0f0f0}+.im img{width:100%;height:auto;border-radius:16px;background:var(--surface);display:block}+h1{font-size:24px;margin:0 0 6px}.mu{color:var(--muted);font-size:13px}.bc{font-size:13px;color:var(--muted);margin-bottom:12px}+.box{background:var(--surface);border-radius:14px;padding:14px 16px;margin:14px 0}.box small{color:var(--muted)}+.go{display:inline-block;background:#d81b3a;color:white;border-radius:999px;padding:10px 22px;text-decoration:none;font-weight:600;margin:6px 8px 6px 0}+.rel{grid-column:1/-1}.rel ul{list-style:none;padding:0;display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:12px}.rel img{width:100%;height:auto;border-radius:10px;background:var(--surface);display:block}.rel a{text-decoration:none;font-size:13px}+footer{text-align:center;color:var(--muted);font-size:12px;padding:30px 20px;border-top:1px solid var(--edge)}h1{overflow-wrap:anywhere}-@media(prefers-color-scheme:dark){body{color:#eee;background:#111}header,footer{border-color:#262626}.mu,.bc,.box small,footer{color:#9a9a9a}.box{background:#1d1d1d}.im img,.rel img{background:#1d1d1d}.go[style]{background:#eee!important;color:#111!important}}-:root{color-scheme:light dark}'''+.go.secondary{background:var(--ink);color:var(--paper)}'''LOGO='<span class="mk"><svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="6.6" r="4" fill="currentColor"/><path d="M16 13.4 3.4 25.6h25.2z" fill="none" stroke="currentColor" stroke-width="3.4" stroke-linejoin="round"/></svg></span>'E=lambda s:H.escape(str(s),quote=True)def page(kind,it,rel):@@ -71,22 +79,23 @@ def page(kind,it,rel):return f'''<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{E(ttl)} | 衣姿 PoseWear</title><meta name="description" content="{E(desc[:150])}"><link rel="canonical" href="{url}"><meta property="og:type" content="article"><meta property="og:title" content="{E(ttl)}"><meta property="og:description" content="{E(desc[:150])}"><meta property="og:image" content="{SITE}/{img}"><meta property="og:url" content="{url}"><meta name="twitter:card" content="summary_large_image">-<link rel="icon" href="/favicon.svg" type="image/svg+xml"><style>{CSS}</style>+<link rel="icon" href="/favicon.svg" type="image/svg+xml">{THEME_HEAD}<style>{CSS}</style><script type="application/ld+json">{json.dumps(ld,ensure_ascii=False)}</script></head><body><header><a href="/">{LOGO}衣姿 PoseWear</a></header><main><div class="im"><img src="/{img}" alt="{E(ttl)}" width="{w}" height="{h}"></div><div><div class="bc"><a href="/">首页</a> › <a href="/#{kind}">{lab}</a> › {E(it.get('cat') or it.get('len'))}</div><h1>{E(it['zh'] if P else it['ti'])}</h1><div class="mu">{E(meta)}</div><div class="box"><small>中文描述</small><p>{E(desc)}</p></div><div class="box"><small>英文提示词 · PROMPT</small><p>{E(en)}</p></div>-<a class="go" href="/#{kind}/{it['id']}">在衣姿中打开</a><a class="go" style="background:#111" href="/#studio">去试穿</a></div>+<a class="go" href="/#{kind}/{it['id']}">在衣姿中打开</a><a class="go secondary" href="/#studio">去试穿</a></div><section class="rel"><h2>同类{'姿势' if P else '穿搭' if kind=='costume' else '人像'}</h2><ul>{rl}</ul></section></main><footer>{'图片来自 AI Portrait Gallery(作者 @agi_aibusi,CC0 1.0),AI 生成的虚构人物。' if kind=='portrait' else '图片来自 AI Pose Gallery / AI Costume Gallery(原作者 @giaaibusi)'},中文描述由本站整理。<a href="/">返回首页</a></footer></body></html>'''-open(f'{D}/404.html','w').write(f'''<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>页面不存在 | 衣姿 PoseWear</title><meta name="robots" content="noindex"><link rel="icon" href="/favicon.svg" type="image/svg+xml"><style>{CSS}+open(f'{D}/404.html','w').write(f'''<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>页面不存在 | 衣姿 PoseWear</title><meta name="robots" content="noindex"><link rel="icon" href="/favicon.svg" type="image/svg+xml">{THEME_HEAD}<style>{CSS}.nf{{max-width:480px;margin:12vh auto;text-align:center;padding:0 20px}}.nf b{{font-size:64px;color:#d81b3a;display:block;line-height:1}}</style></head><body><header><a href="/">{LOGO}衣姿 PoseWear</a></header>-<div class="nf"><b>404</b><h1>这个页面不存在</h1><p class="mu">链接可能写错了,或者内容已经调整。</p><a class="go" href="/">回到首页</a><a class="go" style="background:#111" href="/#costume">看看服装库</a></div></body></html>''')+<div class="nf"><b>404</b><h1>这个页面不存在</h1><p class="mu">链接可能写错了,或者内容已经调整。</p><a class="go" href="/">回到首页</a><a class="go secondary" href="/#costume">看看服装库</a></div></body></html>''')_IMG=" ".join(["'self'","data:","blob:"]+list(DEPTH_ORIGINS)+list(HOTLINK_ORIGINS)+([AH] if AH else []))CSP=("default-src 'self'; script-src 'self' "+SH+(" https://static.cloudflareinsights.com" if WAT else "")+"; style-src 'self' 'unsafe-inline'; img-src "+_IMG+"; font-src 'self' data:; "- "connect-src 'self' data: blob: https://api.openai.com https://generativelanguage.googleapis.com https://*.volces.com https://*.bytepluses.com https://oaidalleapiprodscus.blob.core.windows.net https://*.googleusercontent.com"+(" "+" ".join(HOTLINK_ORIGINS) if HOTLINK_ORIGINS else "")+(" https://cloudflareinsights.com" if WAT else "")+"; "+ "connect-src 'self' data: blob: https:; ""worker-src 'self'; manifest-src 'self'; media-src 'self' blob:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests")+REVALIDATE=' Cache-Control: public, max-age=0, must-revalidate\n'IMM=' Cache-Control: public, max-age=31536000, immutable\n'# Pages Functions 必须位于部署目录内才会随 wrangler pages deploy 一起发布(曾因只传静态产物导致 /api/proxy 丢失,见 issue #7)if os.path.isdir('functions'):@@ -101,17 +110,17 @@ open(f'{D}/_headers','w').write(f'''/*Cross-Origin-Opener-Policy: same-origin/assets/*{IMM}/p/*-{IMM}/c/*-{IMM}/a/*-{IMM}/r/*-{IMM}/e/*-{IMM}/y/*-{IMM}/s/*-{IMM}/l/*-{IMM}/t/*-{IMM}/f/*-{IMM}/o/*-{IMM}/icon-*+{REVALIDATE}/c/*+{REVALIDATE}/a/*+{REVALIDATE}/r/*+{REVALIDATE}/e/*+{REVALIDATE}/y/*+{REVALIDATE}/s/*+{REVALIDATE}/l/*+{REVALIDATE}/t/*+{REVALIDATE}/f/*+{REVALIDATE}/o/*+{REVALIDATE}/icon-*Cache-Control: public, max-age=86400/og.pngCache-Control: public, max-age=86400diff --git a/scripts/catalog-source.mjs b/scripts/catalog-source.mjsnew file mode 100644index 0000000..de56cbe--- /dev/null+++ b/scripts/catalog-source.mjs@@ -0,0 +1,56 @@+import { createHash } from 'node:crypto';++export const publishedSite = 'https://posewear.pages.dev/';+export const collections = {+ pose: { file:'poses', names:['姿势','Poses','ポーズ'] },+ depth: { file:'depths', names:['深度姿势','Depth poses','深度ポーズ'] },+ costume: { file:'costumes', names:['服装','Outfits','衣装'] },+ anime: { file:'anime', names:['动画服装','Anime outfits','アニメ衣装'] },+ portrait: { file:'portraits', names:['人像','Portraits','人物'] },+ expr: { file:'expressions', names:['表情','Expressions','表情'] },+ hair: { file:'hair', names:['发型','Hairstyles','髪型'] },+ dyn: { file:'dynasties', names:['历代服饰','Historical dress','歴代衣装'] },+ scene: { file:'scenes', names:['场景','Scenes','背景'] },+ light: { file:'lights', names:['光影','Lighting','照明'] },+ prop: { file:'props', names:['道具','Props','小物'] },+ furn: { file:'furniture', names:['家具','Furniture','家具'] },+};+export const catalogNames = Object.values(collections).map(collection => collection.file);++async function checkedText(url) {+ const response = await fetch(url, { signal:AbortSignal.timeout(20000) });+ if (!response.ok) throw new Error(`Could not load ${url.pathname} (HTTP ${response.status})`);+ return response.text();+}++// Read the filenames that the actual SPA loads. Published builds carry a content hash;+// the source preview serves the same catalogs without a hash.+export async function catalogIndex(base) {+ const home = new URL(base);+ const html = await checkedText(home);+ const app = html.match(/<script\b[^>]*\bsrc=["']((?:\/assets\/app\.[a-f0-9]+|\/?app)\.js)["']/);+ if (!app) throw new Error('The site does not contain the PoseWear gallery script');+ const script = await checkedText(new URL(app[1],home));+ const files = new Map();+ for (const match of script.matchAll(/["']((?:\/assets\/)?([a-z]+)(?:\.([a-f0-9]+))?\.json)["']/g)) {+ files.set(match[2], { url:new URL(match[1],home), digest:match[3] });+ }+ const missing = catalogNames.filter(name => !files.has(name));+ if (missing.length) throw new Error('Missing catalog filenames: '+missing.join(', '));+ const canonical = html.match(/<link\b[^>]*rel="canonical"[^>]*href="([^"]+)"/);+ const site = new URL(canonical?.[1] || home,home).href;+ const assetPath = script.match(/\bconst AH=['"]([^'"]*)['"]/);+ return { files, site, assetHost:new URL(assetPath?.[1] || site,site).href };+}++export async function readCatalog(index,name) {+ const {url,digest} = index.files.get(name);+ const text = await checkedText(url);+ if (digest && createHash('sha256').update(text).digest('hex').slice(0,digest.length) !== digest) {+ throw new Error('Catalog fingerprint mismatch: '+name);+ }+ const payload = JSON.parse(text);+ const items = Array.isArray(payload) ? payload : payload.items;+ if (!Array.isArray(items)) throw new Error('Invalid catalog records: '+name);+ return {text,items};+}diff --git a/scripts/fetch-assets.py b/scripts/fetch-assets.pyindex 988ac4a..60da733 100644--- a/scripts/fetch-assets.py+++ b/scripts/fetch-assets.py@@ -44,6 +44,7 @@ def get(url, path=None, tries=4):for i in range(tries):try:b = urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=60).read()+ if not b: raise ValueError('empty response')if path is None:return bos.makedirs(os.path.dirname(path), exist_ok=True)@@ -56,8 +57,7 @@ def get(url, path=None, tries=4):r = _curl(url, path)if r:return r- print('失败', url, err, flush=True)- return None if path is None else 0+ raise RuntimeError(f'下载失败: {url}') from errdef inline_data(html):@@ -87,7 +87,8 @@ def meta(lib):keys = {'pose': ['サムネ', '原寸'], 'costume': ['サムネ', '画像', '原寸'], 'anime': ['サムネ', '画像', '原寸']}[lib]return [x[k] for x in data['D'] for k in keys if x.get(k)]for f in ('images.js', 'ranking.js'):- open(os.path.join(d, f), 'wb').write(get(base + 'data/' + f))+ content = get(base + 'data/' + f)+ open(os.path.join(d, f), 'wb').write(content)t = open(os.path.join(d, 'images.js')).read()items = json.loads(t[t.index('['):t.rindex(']') + 1])return [x[k] for x in items for k in ('thumb', 'full') if x.get(k)]@@ -101,7 +102,7 @@ def main():print(f'{lib}: {len(files)} 个文件', flush=True)if only_meta:continue- jobs = [(SRC[lib] + f, os.path.join(OUT, lib, f)) for f in files]+ jobs = [(SRC[lib] + f, os.path.join(OUT, lib, f)) for f in dict.fromkeys(files)]n = 0with cf.ThreadPoolExecutor(WORKERS) as ex:for i, s in enumerate(ex.map(lambda j: get(*j), jobs)):diff --git a/scripts/local-engine.mjs b/scripts/local-engine.mjsnew file mode 100644index 0000000..b134c25--- /dev/null+++ b/scripts/local-engine.mjs@@ -0,0 +1,132 @@+import { readFile } from 'node:fs/promises';+import { setTimeout as delay } from 'node:timers/promises';+import { randomUUID, randomInt } from 'node:crypto';++// This adapter runs in the loopback preview process. Only its operator chooses the backend and workflow.+export function localEngine(env) {+ const name = env.POSEWEAR_LOCAL_ENGINE || 'comfyui';+ if (name === 'off') return null;+ if (!['comfyui','sd-cpp'].includes(name)) throw Error('POSEWEAR_LOCAL_ENGINE must be comfyui, sd-cpp or off');+ const origin = new URL(env.POSEWEAR_LOCAL_URL || (name === 'comfyui' ? 'http://127.0.0.1:8188' : 'http://127.0.0.1:1234'));+ if (!['127.0.0.1','localhost','[::1]'].includes(origin.hostname) || !['http:','https:'].includes(origin.protocol) ||+ origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash) throw Error('POSEWEAR_LOCAL_URL must be a loopback origin');+ const preset = name === 'comfyui' && !env.POSEWEAR_COMFY_WORKFLOW;+ const workflow = preset ? new URL('../docs/comfyui/img2img-api.json',import.meta.url) : env.POSEWEAR_COMFY_WORKFLOW;+ return {name,origin:origin.origin,workflow,preset};+}++async function upstream(engine, path, signal, init = {}) {+ const res = await fetch(engine.origin+path,{...init,signal,redirect:'error'});+ if (!res.ok) throw Error('Local engine HTTP '+res.status+' · '+(await res.text()).slice(0,600));+ return res;+}+function workflowSlots(graph, count) {+ const nodes = Object.entries(graph);+ const prompts = nodes.filter(([,n]) => n._meta?.title === 'PoseWear Prompt').map(([,n]) => n);+ const images = nodes.filter(([,n]) => /^PoseWear Image \d+$/.test(n._meta?.title))+ .map(([,n]) => ({node:n,index:Number(n._meta.title.split(' ').at(-1))})).sort((a,b)=>a.index-b.index);+ const outputs = nodes.filter(([,n])=>n._meta?.title==='PoseWear Output');+ if (!prompts.length || prompts.some(n=>typeof n.inputs?.text!=='string') || outputs.length!==1)+ throw Error('The workflow needs a text node named PoseWear Prompt and one image output named PoseWear Output.');+ if (images.length!==count || images.some((it,i)=>it.index!==i+1 || it.node.class_type!=='LoadImage'))+ throw Error(`Workflow expects ${images.length} numbered LoadImage reference(s); selection has ${count}.`);+ return {prompts, images, output:outputs[0][0]};+}+async function comfyImage(engine, form, signal) {+ const graph = JSON.parse(await readFile(engine.workflow,'utf8'));+ const refs = form.getAll('image[]'), slots = workflowSlots(graph,refs.length);+ if (engine.preset) graph['1'].inputs.ckpt_name = form.get('checkpoint');+ for (const node of slots.prompts) node.inputs.text=form.get('prompt');+ if (form.has('size')) {+ const [width,height]=form.get('size').split('x').map(Number);+ if (engine.preset) {+ // The bundled graph connects LoadImage (2) directly to VAEEncode (5) in Auto mode.+ graph['9'] = {class_type:'ImageScale',inputs:{image:['2',0],upscale_method:'lanczos',width,height,crop:'center'}};+ graph['5'].inputs.pixels = ['9',0];+ } else {+ const sizes=Object.values(graph).filter(n=>n._meta?.title==='PoseWear Size');+ if (!sizes.length) throw Error('Use Auto aspect ratio, or name a width/height node PoseWear Size.');+ for (const node of sizes) Object.assign(node.inputs,{width,height});+ }+ }+ for (const n of Object.values(graph)) if(n._meta?.title==='PoseWear Seed') n.inputs.seed=randomInt(0,2**32);+ const id = randomUUID();+ for (const {node,index} of slots.images) {+ const upload = new FormData();+ upload.set('image',refs[index-1],`posewear-${id}-${index}.jpg`);+ const saved = await (await upstream(engine,'/upload/image',signal,{method:'POST',body:upload})).json();+ if (!saved.name) throw Error('ComfyUI did not return an input filename.');+ node.inputs.image=[saved.subfolder,saved.name].filter(Boolean).join('/');+ }+ const job=await (await upstream(engine,'/prompt',signal,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({prompt:graph,client_id:id})})).json();+ if(!job.prompt_id) throw Error('ComfyUI did not accept the workflow.');+ const path='/history/'+encodeURIComponent(job.prompt_id);+ try {+ for (;;) {+ const record=(await (await upstream(engine,path,signal)).json())[job.prompt_id];+ if (record) {+ if(record.status?.status_str==='error') throw Error('ComfyUI workflow failed. '+(record.status.messages?.find(([kind])=>kind==='execution_error')?.[1]?.exception_message||''));+ const result=record.outputs?.[slots.output]?.images;+ if(result?.length!==1) throw Error('PoseWear Output must return one image per request.');+ const {filename,subfolder='',type='output'}=result[0];+ return await upstream(engine,'/view?'+new URLSearchParams({filename,subfolder,type}),signal);+ }+ await delay(500,undefined,{signal});+ }+ } finally {+ // Delete only this pending job. An already executing job may finish on the local engine.+ if (signal.aborted) await upstream(engine,'/queue',AbortSignal.timeout(1500),{method:'POST',+ headers:{'content-type':'application/json'},body:JSON.stringify({delete:[job.prompt_id]})}).catch(()=>{});+ }+}+export async function localRequest(engine,request) {+ if (!engine) return new Response(null,{status:404});+ const url=new URL(request.url);+ if (request.headers.get('x-posewear-local')!=='1' || (request.method==='POST' && request.headers.get('origin')!==url.origin))+ return new Response(null,{status:403});+ const signal=AbortSignal.any([request.signal,AbortSignal.timeout(180000)]);+ try {+ if(url.pathname==='/api/local/status' && request.method==='GET') {+ const path=engine.name==='comfyui'?'/system_stats':'/v1/models';+ const status=await (await upstream(engine,path,signal)).json();+ if (engine.name==='comfyui'? !status.system : !Array.isArray(status.data)) throw Error('Unexpected local engine response.');+ const result = {engine:engine.name};+ if (engine.preset) {+ const info = await (await upstream(engine,'/object_info/CheckpointLoaderSimple',signal)).json();+ const checkpoints = info.CheckpointLoaderSimple?.input?.required?.ckpt_name?.[0];+ if (!Array.isArray(checkpoints) || !checkpoints.every(name => typeof name === 'string'))+ throw Error('ComfyUI did not return its checkpoint list.');+ result.checkpoints = checkpoints;+ }+ return Response.json(result,{headers:{'cache-control':'no-store'}});+ }+ if (url.pathname!=='/api/local/generate' || request.method!=='POST') return new Response(null,{status:404});+ const form=await request.formData();+ if(!form.get('prompt') || form.getAll('image[]').some(i=>typeof i==='string')) return new Response('Invalid image request',{status:400});+ if (engine.preset) {+ const checkpoint = form.get('checkpoint');+ if (typeof checkpoint !== 'string' || !checkpoint.trim()) return new Response('Select a ComfyUI checkpoint.',{status:400});+ if (form.getAll('image[]').length !== 1) return new Response('The ComfyUI preset needs one reference image.',{status:400});+ if (form.has('size') && !/^[1-9]\d*x[1-9]\d*$/.test(form.get('size'))) return new Response('Invalid image size.',{status:400});+ }+ let image;+ if(engine.name==='comfyui') image=await comfyImage(engine,form,signal);+ else {+ const imgs=form.getAll('image[]');+ const result=imgs.length ? await upstream(engine,'/v1/images/edits',signal,{method:'POST',body:form}) :+ await upstream(engine,'/v1/images/generations',signal,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(Object.fromEntries(form))});+ const data=(await result.json()).data?.[0]?.b64_json;+ if(!data) throw Error('sd-server did not return image data.');+ image=new Response(Buffer.from(data,'base64'),{headers:{'content-type':'image/png'}});+ }+ const contentType=image.headers.get('content-type')||'';+ if(!contentType.startsWith('image/')) throw Error('The local engine did not return an image.');+ return new Response(image.body,{headers:{'content-type':contentType,'cache-control':'no-store'}});+ } catch(e) {+ if (['ECONNREFUSED','ECONNRESET','UND_ERR_SOCKET'].includes(e.cause?.code)) {+ const name = engine.name === 'comfyui' ? 'ComfyUI' : 'sd-server';+ return new Response(`Start ${name} at ${engine.origin}, then reconnect.`,{status:503,headers:{'cache-control':'no-store'}});+ }+ return new Response(e.message,{status:502,headers:{'cache-control':'no-store'}});+ }+}diff --git a/scripts/preview.mjs b/scripts/preview.mjsindex 7643432..a27cb63 100644--- a/scripts/preview.mjs+++ b/scripts/preview.mjs@@ -3,136 +3,138 @@ import fs from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';import { Readable } from 'node:stream';+import { catalogIndex, catalogNames, publishedSite, readCatalog } from './catalog-source.mjs';import { onRequest } from '../functions/api/proxy.js';+import { localEngine, localRequest } from './local-engine.mjs';+const engine = localEngine(process.env);-const __dirname = path.dirname(fileURLToPath(import.meta.url));-const root = path.resolve(__dirname, '../src');--const nativeFetch = globalThis.fetch;-globalThis.fetch = async (url, init = {}) =>- nativeFetch(- url,- init.body instanceof ReadableStream- ? { ...init, body: await new Response(init.body).arrayBuffer() }- : init- );--const mime = {- '.html': 'text/html; charset=utf-8',- '.js': 'text/javascript; charset=utf-8',- '.css': 'text/css; charset=utf-8',- '.svg': 'image/svg+xml',- '.png': 'image/png',- '.jpg': 'image/jpeg',- '.jpeg': 'image/jpeg',- '.webp': 'image/webp',- '.json': 'application/json',- '.webmanifest': 'application/manifest+json',- '.ico': 'image/x-icon'-};--const JSON_MAP = {- '/poses.json': 'https://posewear.pages.dev/assets/poses.2383bf449f.json',- '/depths.json': 'https://posewear.pages.dev/assets/depths.264ea86381.json',- '/costumes.json': 'https://posewear.pages.dev/assets/costumes.2cee954fb7.json',- '/anime.json': 'https://posewear.pages.dev/assets/anime.5b38cbc858.json',- '/portraits.json': 'https://posewear.pages.dev/assets/portraits.0b8834f90f.json'-};--const server = http.createServer(async (req, res) => {+const root = fileURLToPath(new URL('../src/', import.meta.url));+const stagedPages = process.env.POSEWEAR_STAGING || fileURLToPath(new URL('../dist/', import.meta.url));+const release = new URL(publishedSite).origin;+const media = 'https://pwimg.0vo.pro';+const port = Number(process.env.PORT || 8787);+const mime = {'.html':'text/html; charset=utf-8','.js':'text/javascript','.css':'text/css','.svg':'image/svg+xml',+ '.png':'image/png','.webmanifest':'application/manifest+json','.json':'application/json'};+const catalogs = catalogNames;+let snapshot;+const statNames = {poses:'pose',depths:'depth',costumes:'cos',anime:'ani',portraits:'por',expressions:'exp',+ hair:'hair',dynasties:'dyn',scenes:'scene',lights:'light',props:'prop',furniture:'furn'};+async function discover() {+ const index = await catalogIndex(process.env.POSEWEAR_CATALOG_URL || publishedSite);+ const data = new Map(), counts = {};+ for (let i = 0; i < catalogs.length; i += 4) {+ await Promise.all(catalogs.slice(i,i+4).map(async name => {+ const {text,items} = await readCatalog(index,name);+ if (!items.length) throw new Error('Empty catalog: '+name);+ const publicItems = items.filter(item => !item.a);+ const key = statNames[name];+ if (key) counts[key] = [publicItems.length, items.length];+ data.set(name,text);+ }));+ }+ return {data,counts};+}+function publishedSnapshot() {+ snapshot ??= discover().catch(error => { snapshot = undefined; throw error; });+ return snapshot;+}+async function remote(res, url, method, successStatus) {+ const r = await fetch(url, { method });+ const headers = {};+ for (const key of ['content-type','cache-control']) if (r.headers.has(key)) headers[key] = r.headers.get(key);+ res.writeHead(r.ok && successStatus ? successStatus : r.status, headers);+ if (r.body) Readable.fromWeb(r.body).pipe(res); else res.end();+ return r.status;+}+const server = http.createServer(async (req,res) => {try {- const u = new URL(req.url, 'http://127.0.0.1:8787');-- // 1. API proxy route- if (u.pathname === '/api/proxy') {- const h = new Headers();- for (const [k, v] of Object.entries(req.headers)) {- if (v) h.set(k, Array.isArray(v) ? v.join(', ') : v);- }- const request = new Request(u, {- method: req.method,- headers: h,- ...(req.method === 'POST' ? { body: Readable.toWeb(req), duplex: 'half' } : {})- });- const result = await onRequest({ request });- res.writeHead(result.status, Object.fromEntries(result.headers));- if (result.body) Readable.fromWeb(result.body).pipe(res);- else res.end();+ const currentPort = server.address().port;+ if (!['127.0.0.1:'+currentPort,'localhost:'+currentPort].includes(req.headers.host)) return res.writeHead(400).end();+ const u = new URL(req.url, 'http://'+req.headers.host);+ if (u.pathname.startsWith('/api/local/')) {+ const controller = new AbortController();+ res.once('close',()=>{ if(!res.writableEnded) controller.abort(); });+ const request = new Request(u,{method:req.method,headers:req.headers,signal:controller.signal,+ ...(req.method==='POST'?{body:Readable.toWeb(req),duplex:'half'}:{})});+ const reply = await localRequest(engine,request);+ res.writeHead(reply.status,Object.fromEntries(reply.headers));+ if(reply.body) Readable.fromWeb(reply.body).pipe(res); else res.end();return;}-- if (req.method !== 'GET' && req.method !== 'HEAD') {- res.writeHead(405).end();+ if (u.pathname === '/api/proxy') {+ const request = new Request(u,{method:req.method,headers:req.headers,+ ...(req.method === 'POST' ? {body:Readable.toWeb(req),duplex:'half'} : {})});+ const response = await onRequest({request,env:process.env});+ res.writeHead(response.status,Object.fromEntries(response.headers));+ if (response.body) Readable.fromWeb(response.body).pipe(res); else res.end();return;}-- // 2. Map known data JSON endpoints- if (JSON_MAP[u.pathname]) {- const remote = await fetch(JSON_MAP[u.pathname]);- res.writeHead(remote.status, {- 'content-type': 'application/json; charset=utf-8',- 'cache-control': 'no-cache'- });- if (remote.body) Readable.fromWeb(remote.body).pipe(res);- else res.end();+ if (!['GET','HEAD'].includes(req.method)) return res.writeHead(405).end();+ const name = u.pathname.slice(1).replace(/\.json$/,'');+ if (u.pathname === '/'+name+'.json' && catalogs.includes(name)) {+ const {data} = await publishedSnapshot();+ res.writeHead(200,{'content-type':mime['.json'],'cache-control':'no-cache'}).end(data.get(name));return;}-- // 3. Check local files in src/- let relPath = u.pathname.replace(/^\/+/, '');- if (!relPath || relPath === 'index.html') relPath = 'index.html';-- // Map hashed /assets/* requests to unhashed local files if needed- if (relPath.startsWith('assets/')) {- const base = path.basename(relPath);- if (/^studio(\.[a-f0-9]+)?\.js$/.test(base)) relPath = 'studio.js';- else if (/^history(\.[a-f0-9]+)?\.js$/.test(base)) relPath = 'history.js';- else if (/^app(\.[a-f0-9]+)?\.js$/.test(base)) relPath = 'app.js';- else if (/^extras(\.[a-f0-9]+)?\.js$/.test(base)) relPath = 'extras.js';- else if (/^zip(\.[a-f0-9]+)?\.js$/.test(base)) relPath = 'zip.js';- else if (/^style(\.[a-f0-9]+)?\.css$/.test(base)) relPath = 'style.css';- }-- const localFile = path.resolve(root, relPath);- if (localFile.startsWith(root + '/')) {+ const rel = u.pathname === '/' ? 'index.html' : u.pathname.slice(1);+ if (/^[a-zA-Z0-9.-]+$/.test(rel) && rel !== '.' && rel !== '..') {try {- const data = await fs.readFile(localFile);- res.writeHead(200, {- 'content-type': mime[path.extname(localFile)] || 'application/octet-stream',- 'cache-control': 'no-cache'- });- res.end(data);+ let content = await fs.readFile(path.join(root,rel));+ if (rel === 'index.html') {+ const {counts} = await publishedSnapshot();+ content = content.toString().replace(/<b data-stat="(\w+)"[^>]*>[^<]*<\/b>/g, (_,key) => {+ const [visible,total] = counts[key];+ return `<b data-stat="${key}" data-n="${visible}" data-na="${total}">${visible.toLocaleString('en-US')}</b>`;+ });+ }+ if (rel === 'index.html' && engine) {+ const preset = engine.preset ? ' data-local-preset="1"' : '';+ content = content.toString().replace('<html ',`<html data-local-engine="${engine.name}"${preset} `);+ }+ if (rel === 'app.js') content = content.toString().replace("const AH='';","const AH='"+media+"/';");+ res.writeHead(200,{'content-type':mime[path.extname(rel)] || 'application/octet-stream','cache-control':'no-store'}).end(content);return;- } catch (err) {- // Not found locally, proceed to remote proxy+ } catch (e) { if (e.code !== 'ENOENT') throw e; }+ }+ // Static pages use the theme asset from the same build as their HTML.+ if (/^\/assets\/theme\.[0-9a-f]{10}\.js$/.test(u.pathname)) {+ try {+ const script = await fs.readFile(path.join(stagedPages,u.pathname));+ return res.writeHead(200,{'content-type':mime['.js']}).end(script);+ } catch (error) {+ if (error.code !== 'ENOENT') throw error;}+ await remote(res,release+u.pathname,req.method);+ return;}-- // 4. Remote asset proxy (fallback to asset host or main host)- let remoteUrl = 'https://posewear.pages.dev' + u.pathname + u.search;- if (/^\/(p|c|a|o|r)\//.test(u.pathname)) {- remoteUrl = 'https://posewear-assets-96b.pages.dev' + u.pathname + u.search;+ const seoRoute = /^\/(?:en|pose|costume|anime|portrait|tag)\/[\w/-]*$/.test(u.pathname);+ if (seoRoute) {+ try {+ const html = await fs.readFile(path.join(stagedPages,u.pathname,'index.html'));+ return res.writeHead(200,{'content-type':mime['.html'],'cache-control':'no-cache'}).end(html);+ } catch (error) {+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error;+ }}-- let remote = await fetch(remoteUrl);- if (!remote.ok && remoteUrl.includes('posewear-assets-96b')) {- // Try fallback to main site- const fallback = await fetch('https://posewear.pages.dev' + u.pathname + u.search);- if (fallback.ok) remote = fallback;+ if (seoRoute || /^\/[pcareysltf]\/(?:m|i)\/[\w.%-]+\.webp$/.test(u.pathname)) {+ await remote(res,release+u.pathname,req.method);+ return;}-- const h = {};- for (const key of ['content-type', 'cache-control']) {- if (remote.headers.has(key)) h[key] = remote.headers.get(key);+ if ((req.headers.accept || '').includes('text/html')) {+ try {+ const html = await fs.readFile(path.join(stagedPages,'404.html'));+ return res.writeHead(404,{'content-type':mime['.html']}).end(html);+ } catch (error) {+ if (error.code !== 'ENOENT') throw error;+ }+ // The published 404 document itself returns 200. Keep the unknown route a 404.+ await remote(res,release+'/404.html',req.method,404);+ return;}- res.writeHead(remote.status, h);- if (remote.body) Readable.fromWeb(remote.body).pipe(res);- else res.end();- } catch (e) {- res.writeHead(502, { 'content-type': 'text/plain' }).end('Local preview error: ' + e.message);+ res.writeHead(404).end();+ } catch (error) {+ if (!res.headersSent) res.writeHead(502,{'content-type':'text/plain; charset=utf-8'});+ res.end('Preview unavailable: '+error.message);}});--server.listen(8787, '127.0.0.1', () => {- console.log('PoseWear local preview running at http://127.0.0.1:8787/');-});+server.listen(port,'127.0.0.1',() => console.log('PoseWear: http://127.0.0.1:'+server.address().port+'/'));diff --git a/scripts/sync-r2.py b/scripts/sync-r2.pyindex b7fca8d..7209f2d 100644--- a/scripts/sync-r2.py+++ b/scripts/sync-r2.py@@ -4,8 +4,8 @@用法:python3 scripts/sync-r2.py <本地目录> [--workers 8] [--journal 路径]-- 对象键 = 相对目录路径;带一年 immutable 缓存头上传。-- 断点续传:journal 记录已完成的对象键,重跑自动跳过;失败键记到 <journal>.fail。+- 对象键 = 相对目录路径;同名对象会更新,客户端通过 ETag 重新验证。+- 断点续传:journal 记录目标账号、桶、对象键与内容摘要,重跑自动跳过;失败键记到 <journal>.fail。- 凭据:环境变量 CLOUDFLARE_API_TOKEN(需 R2 编辑权限),或本机 wrangler 登录态(自动读 ~/.config/.wrangler/config/default.toml 的 oauth_token,约 1 小时过期需刷新)。- 账号:环境变量 CLOUDFLARE_ACCOUNT_ID,缺省用本项目账号。@@ -13,7 +13,8 @@缩略图(t/)与原图(o/)走 R2;中图(m/、i/)是主站同源文件,不进 R2。"""-import os, re, sys, time, threading, concurrent.futures as cf+import argparse, hashlib, json, os, re, sys, time, threading, concurrent.futures as cf+from urllib.parse import quotetry:import requests@@ -26,7 +27,7 @@ TOML = os.path.expanduser("~/.config/.wrangler/config/default.toml")CT = {".webp": "image/webp", ".png": "image/png", ".jpg": "image/jpeg",".jpeg": "image/jpeg", ".gif": "image/gif", ".svg": "image/svg+xml",".json": "application/json", ".txt": "text/plain"}-CC = "public, max-age=31536000, immutable"+CC = "public, max-age=0, must-revalidate"def get_token():@@ -38,35 +39,38 @@ def get_token():def main():- args = [a for a in sys.argv[1:] if not a.startswith("--")]- opts = dict(zip([a for a in sys.argv[1:] if a.startswith("--")][::1],- [sys.argv[i + 1] for i, a in enumerate(sys.argv) if a.startswith("--")]))- if not args:- sys.exit(__doc__)- root = args[0]- workers = int(opts.get("--workers", 8))- journal_path = opts.get("--journal", os.path.join(root, ".r2-journal"))+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('root')+ parser.add_argument('--workers', type=int, choices=range(1, 9), default=8)+ parser.add_argument('--journal')+ args = parser.parse_args()+ root, workers = args.root, args.workers+ if not os.path.isdir(root): parser.error('Directory does not exist')+ journal_path = os.path.abspath(args.journal or os.path.join(root, ".r2-journal"))fail_path = journal_path + ".fail"-- done = set()- if os.path.exists(journal_path):- done = set(l.strip() for l in open(journal_path) if l.strip())+ done = {}+ if os.path.isfile(journal_path):+ with open(journal_path) as rows:+ for row in rows:+ try:+ account, bucket, key, digest = json.loads(row)+ except (ValueError, TypeError):+ continue # Legacy journals do not identify the bucket or content.+ if account == ACCT and bucket == BUCKET: done[key] = digestkeys = []for dp, _, fns in os.walk(root):for fn in fns:- rel = os.path.relpath(os.path.join(dp, fn), root).replace(os.sep, "/")- if rel != os.path.basename(journal_path) and rel not in done:- keys.append(rel)- print(f"待上传 {len(keys)} 个(已完成 {len(done)} 跳过),并发 {workers}")- if not keys:- return- token = [get_token(), time.time()]+ file = os.path.join(dp, fn)+ if os.path.abspath(file) not in (journal_path, fail_path) and not fn.startswith('.r2-journal'):+ keys.append(os.path.relpath(file, root).replace(os.sep, "/"))+ if not keys: return+ token = [None, 0]tlock = threading.Lock()tls = threading.local()def tok():with tlock:- if time.time() - token[1] > 600 and not os.environ.get("CLOUDFLARE_API_TOKEN"):+ if token[0] is None or (time.time() - token[1] > 600 and not os.environ.get("CLOUDFLARE_API_TOKEN")):token[0], token[1] = get_token(), time.time()return token[0]@@ -78,21 +82,25 @@ def main():jf = open(journal_path, "a")ff = open(fail_path, "a")jlock = threading.Lock()- stats = {"ok": 0, "fail": 0}+ stats = {"ok": 0, "fail": 0, "skipped": 0}def put_one(rel):- url = f"https://api.cloudflare.com/client/v4/accounts/{ACCT}/r2/buckets/{BUCKET}/objects/{rel}"+ with open(os.path.join(root, rel), "rb") as source: data = source.read()+ digest = hashlib.sha256(data).hexdigest()+ if done.get(rel) == digest:+ with jlock: stats["skipped"] += 1+ return+ url = f"https://api.cloudflare.com/client/v4/accounts/{ACCT}/r2/buckets/{BUCKET}/objects/{quote(rel)}"ext = os.path.splitext(rel)[1].lower()headers = {"Content-Type": CT.get(ext, "application/octet-stream"),"Cache-Control": CC, "Authorization": "Bearer " + tok()}- data = open(os.path.join(root, rel), "rb").read()delay, last = 1.0, Nonefor _ in range(7):try:r = sess().put(url, data=data, headers=headers, timeout=120)if r.status_code == 200:with jlock:- jf.write(rel + "\n"); jf.flush(); stats["ok"] += 1+ jf.write(json.dumps([ACCT, BUCKET, rel, digest]) + "\n"); jf.flush(); stats["ok"] += 1returnlast = f"{r.status_code} {r.text[:120]}"if r.status_code == 429:@@ -106,7 +114,9 @@ def main():t0 = time.time()with cf.ThreadPoolExecutor(max_workers=workers) as ex:list(ex.map(put_one, keys))- print(f"完成:ok {stats['ok']},fail {stats['fail']},用时 {time.time() - t0:.0f}s")+ jf.close()+ ff.close()+ print(f"完成:跳过 {stats['skipped']},ok {stats['ok']},fail {stats['fail']},用时 {time.time() - t0:.0f}s")if stats["fail"]:sys.exit(1)diff --git a/seo.py b/seo.pyindex c550caf..a51a594 100644--- a/seo.py+++ b/seo.py@@ -48,33 +48,40 @@ HAS_EN={'pose','costume','anime'} # 人像详情页数量太大,英文版只LAB={'zh':{'pose':'姿势','costume':'服装','anime':'动画服装','portrait':'人像','tag':'标签','home':'首页'},'en':{'pose':'Poses','costume':'Outfits','anime':'Anime outfits','portrait':'Portraits','tag':'Tags','home':'Home'}}CSS2=CSS+'''.bc ol{list-style:none;margin:0;padding:0;display:flex;flex-wrap:wrap;gap:4px}.bc li+li:before{content:"›";margin-right:4px;color:#aaa}.bc a{text-decoration:none}.bc a:hover{text-decoration:underline}-.tg{list-style:none;padding:0;display:flex;flex-wrap:wrap;gap:8px;margin:10px 0}.tg a{font-size:13px;background:#f5f5f5;border-radius:999px;padding:4px 12px;text-decoration:none}.tg a:hover{background:#ececec}-header nav{margin-left:auto;display:flex;gap:16px;font-size:14px}header nav a{font-weight:500;color:#555}-.wrap{max-width:1180px;margin:0 auto;padding:24px 20px}.wrap h1{font-size:28px}.lead{color:#555;max-width:720px;margin:6px 0 18px}-.cg{list-style:none;padding:0;display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:20px 14px}.cg a{text-decoration:none;font-size:13px;display:block}.cg img{width:100%;height:auto;border-radius:12px;background:#f5f5f5;display:block;margin-bottom:6px}.cg span{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}-.pg{display:flex;gap:8px;justify-content:center;margin:28px 0}.pg a,.pg b{padding:6px 14px;border-radius:999px;background:#f5f5f5;text-decoration:none;font-size:14px}.pg b{background:#111;color:#fff}+.tg{list-style:none;padding:0;display:flex;flex-wrap:wrap;gap:8px;margin:10px 0}.tg a{font-size:13px;background:var(--surface);border-radius:999px;padding:4px 12px;text-decoration:none}.tg a:hover{background:var(--surface-hover)}+header nav{margin-left:auto;display:flex;gap:16px;font-size:14px}header nav a{font-weight:500;color:var(--muted)}+.wrap{max-width:1180px;margin:0 auto;padding:24px 20px}.wrap h1{font-size:28px}.lead{color:var(--muted);max-width:720px;margin:6px 0 18px}+.cg{list-style:none;padding:0;display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:20px 14px}.cg a{text-decoration:none;font-size:13px;display:block}.cg img{width:100%;height:auto;border-radius:12px;background:var(--surface);display:block;margin-bottom:6px}.cg span{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.pg{display:flex;gap:8px;justify-content:center;margin:28px 0}.pg a,.pg b{padding:6px 14px;border-radius:999px;background:var(--surface);text-decoration:none;font-size:14px}.pg b{background:var(--ink);color:var(--paper)}.sec h2{font-size:18px;margin:28px 0 10px}pre{white-space:pre-wrap;margin:0;font:inherit}-@media(prefers-color-scheme:dark){.tg a,.pg a,.cg img{background:#1d1d1d}header nav a{color:#bbb}.lead{color:#aaa}.pg b{background:#eee;color:#111}}'''+.static-dock{position:fixed;right:max(16px,env(safe-area-inset-right));bottom:max(16px,env(safe-area-inset-bottom));width:48px;height:48px;z-index:3;display:grid;place-items:center;background:var(--ink);color:var(--paper);border:1px solid #ffffff36;border-radius:16px;box-shadow:0 5px 16px #0002;text-decoration:none}+.static-dock svg{width:23px;height:23px;fill:none;stroke:currentColor;stroke-width:1.65;stroke-linecap:round;stroke-linejoin:round}.static-dock:focus-visible{outline:3px solid #ff2442;outline-offset:3px}+@media(max-width:760px){header{flex-wrap:wrap;padding:10px 14px}header nav{margin:0;width:100%;flex-wrap:wrap;gap:4px 14px}header nav a{min-height:32px}main{grid-template-columns:minmax(0,1fr);padding:16px 14px;gap:20px}main>div{min-width:0;overflow-wrap:anywhere}.cg{grid-template-columns:repeat(2,minmax(0,1fr))}footer{padding-bottom:76px}}'''def url(lang,path): return SITE+('/en' if lang=='en' else '')+pathdef alts(path,en=True):if not en: return f'<link rel="canonical" href="{url("zh",path)}">'return f'<link rel="alternate" hreflang="zh-CN" href="{url("zh",path)}"><link rel="alternate" hreflang="en" href="{url("en",path)}"><link rel="alternate" hreflang="x-default" href="{url("zh",path)}">'def crumbs_ld(lang,cr,bid=None): return {"@type":"BreadcrumbList",**({"@id":bid} if bid else {}),"itemListElement":[{"@type":"ListItem","position":i+1,"name":n,**({"item":SITE+u} if u else {})} for i,(n,u) in enumerate(cr)]}-def crumbs_html(cr): return '<nav class="bc" aria-label="breadcrumb"><ol>'+''.join(f'<li>{"<a href=\""+u+"\">"+E(n)+"</a>" if u else "<span aria-current=\"page\">"+E(n)+"</span>"}</li>' for n,u in cr)+'</ol></nav>'-def shell(lang,path,title,desc,body,ld,en=True,og=None,ogt='website'):+def crumbs_html(cr):+ parts = [f'<a href="{E(u)}">{E(n)}</a>' if u else f'<span aria-current="page">{E(n)}</span>' for n,u in cr]+ return '<nav class="bc" aria-label="breadcrumb"><ol>'+''.join(f'<li>{part}</li>' for part in parts)+'</ol></nav>'++def shell(lang,path,title,desc,body,ld,en=True,og=None,ogt='website',credit='',workbench='/#workbench'):+ dock_label='Open image studio' if lang=='en' else '打开生图工作台'P='/en' if lang=='en' else ''nav=(f'<nav><a href="{P}/pose/">{LAB[lang]["pose"]}</a><a href="{P}/costume/">{LAB[lang]["costume"]}</a><a href="{P}/anime/">{LAB[lang]["anime"]}</a><a href="{P}/portrait/">{LAB[lang]["portrait"]}</a><a href="https://github.com/atuizz/posewear" target="_blank" rel="noopener">GitHub</a>'+(f'<a href="/en{path}" hreflang="en" lang="en">EN</a>' if lang=='zh' and en else f'<a href="{path}" hreflang="zh-CN" lang="zh-CN">中文</a>' if lang=='en' else '')+'</nav>')- foot=('Images from AI Pose Gallery / AI Costume Gallery (by @giaaibusi) and AI Portrait Gallery (by @agi_aibusi, CC0 1.0). All AI-generated. <a href="/en/">PoseWear home</a>' if lang=='en' else- '图片来自 AI Pose Gallery / AI Costume Gallery(原作者 @giaaibusi)与 AI Portrait Gallery(@agi_aibusi,CC0 1.0),均为 AI 生成图,中文描述由本站整理。<a href="/">返回首页</a>')+ foot=('Images from AI Pose Gallery / AI Costume Gallery (by @giaaibusi) and AI Portrait Gallery (by @agi_aibusi, CC0 1.0). All AI-generated.' if lang=='en' else+ '图片来自 AI Pose Gallery / AI Costume Gallery(原作者 @giaaibusi)与 AI Portrait Gallery(@agi_aibusi,CC0 1.0),均为 AI 生成图,中文描述由本站整理。')return f'''<!doctype html><html lang="{'en' if lang=='en' else 'zh-CN'}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{E(title)}</title><meta name="description" content="{E(desc[:160])}"><link rel="canonical" href="{url(lang,path)}">{alts(path) if en else ''}<meta property="og:type" content="{ogt}"><meta property="og:site_name" content="衣姿 PoseWear"><meta property="og:title" content="{E(title)}"><meta property="og:description" content="{E(desc[:160])}"><meta property="og:image" content="{SITE}/{og or 'og.png'}"><meta property="og:url" content="{url(lang,path)}"><meta property="og:locale" content="{'en_US' if lang=='en' else 'zh_CN'}"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:description" content="{E(desc[:160])}">-<link rel="icon" href="/favicon.svg" type="image/svg+xml"><style>{CSS2}</style>+<link rel="icon" href="/favicon.svg" type="image/svg+xml">{THEME_HEAD}<style>{CSS2}</style><script type="application/ld+json">{json.dumps({"@context":"https://schema.org","@graph":ld},ensure_ascii=False,separators=(',',':'))}</script></head><body><header><a href="{P}/">{LOGO}衣姿 PoseWear</a>{nav}</header>{body}-<footer>{foot}</footer></body></html>'''+<a class="static-dock" href="{E(workbench)}" aria-label="{dock_label}" title="{dock_label}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3.5 10V7.8a2 2 0 0 1 2-2H9M19.8 12.7v5.5a2 2 0 0 1-2 2H5.5a2 2 0 0 1-2-2V10m3.3 6.4 3.4-3.6 2.2 2.3 1.2-1.2 2.5 2.5"/><path d="m16.4 2.7.9 3.1 3.1.9-3.1.9-.9 3.1-.9-3.1-3.1-.9 3.1-.9z"/></svg></a>+<footer>{credit or foot} <a href="{P}/">{'PoseWear home' if lang=='en' else '返回首页'}</a></footer></body></html>'''def W(path,html):os.makedirs(f'{D}{path}',exist_ok=True);open(f'{D}{path}index.html','w').write(html)SM={'pose':[],'costume':[],'anime':[],'portrait':[],'pages':[]}@@ -127,14 +134,15 @@ def detail(lang,kind,it,rel):f'Source: <a href="{src[1]}" rel="noopener">{src[0]}</a> by <a href="{src[3]}" rel="noopener">{src[2]}</a>. No license is stated by the source; ask the author before reuse.'))+'</p>')boxes=(f'<div class="box"><small>中文描述</small><p>{E(prz)}</p></div><div class="box"><small>中文提示词</small><p>{E(pzh)}</p></div><div class="box"><small>英文提示词 · PROMPT</small><p>{E(pre)}</p></div>' if zh elsef'<div class="box"><small>PROMPT</small><p>{E(pre)}</p></div><div class="box" lang="zh-CN"><small>中文提示词 · Chinese prompt</small><p>{E(pzh)}</p></div>')+ workbench=f'/#workbench/{kind}/{it["id"]}'rl=''.join(cardli(lang,kind,r) for r in rel)body=f'''<main><div class="im"><img src="/{img}" alt="{E(t)}" width="{w}" height="{h}" fetchpriority="high"></div><div>{crumbs_html(cr)}<h1>{E(t)}</h1><div class="mu">{E((it['line']+' · '+it['cat'] if zh else it['lineEn']+' · '+cen) if kind=='pose' else (cz_ if zh else cen))} · {'编号' if zh else 'No.'} {E(it.get('no') or it['id'])}</div>{tg}{boxes}{ang}-<a class="go" href="/#{kind}/{it['id']}">{'在衣姿中打开' if zh else 'Open in PoseWear'}</a><a class="go" style="background:#111" href="/#studio">{'去试穿' if zh else 'Try on'}</a>{lic}</div>+<a class="go" href="/#{kind}/{it['id']}">{'在衣姿中打开' if zh else 'Open in PoseWear'}</a><a class="go secondary" href="{E(workbench)}">{'用作参考图' if zh else 'Use as reference'}</a></div><section class="rel"><h2>{('同类'+('姿势' if kind=='pose' else '穿搭' if kind in ('costume','anime') else '人像')) if zh else 'More like this'}</h2><ul>{rl}</ul></section></main>'''BID=url(lang,path)+'#breadcrumb';ld=[io,crumbs_ld(lang,cr,BID),{"@type":"WebPage","@id":url(lang,path),"url":url(lang,path),"name":ttl,"inLanguage":'zh-CN' if zh else 'en',"primaryImageOfPage":{"@id":url(lang,path)+'#image'},"breadcrumb":{"@id":BID}}]- return shell(lang,path,ttl,desc,body,ld,en=kind in HAS_EN,og=img,ogt='article')+ return shell(lang,path,ttl,desc,body,ld,en=kind in HAS_EN,og=img,ogt='article',credit=lic,workbench=workbench)for kind,L in [('pose',SP),('costume',SC),('anime',SA),('portrait',SR)]:ck=lambda x:catof(kind,x)[1]for i,it in enumerate(L):@@ -200,14 +208,14 @@ def featured(lang,n=12):return ''.join(cardli(lang,'costume',c) for c in SC[:n])catlinks=lambda lang:''.join(f'<li><a href="{"/en" if lang=="en" else ""}/{k}/{s}/">{E(z if lang=="zh" else e)}</a></li>' for k in ['pose','costume'] for s,z,e,L in CATS[k])en_desc=f"PoseWear: {len(SP)} pose sets ({NA_PUB} angle images), {len(SC):,} outfits, {len(SA):,} anime outfits and {len(SR):,} CC0 portraits, all with English and Chinese prompts — plus online AI try-on."ENLD=[{"@type":"WebSite","@id":SITE+'/en/#website',"url":SITE+'/en/',"name":"PoseWear","alternateName":"衣姿 PoseWear","inLanguage":"en","description":en_desc,"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":SITE+'/?t=costume&q={search_term_string}'},"query-input":"required name=search_term_string"}},- {"@type":"WebApplication","name":"PoseWear","url":SITE+'/en/',"applicationCategory":"DesignApplication","operatingSystem":"Any (web browser)","browserRequirements":"Requires JavaScript","inLanguage":["zh-CN","en"],"offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"description":en_desc}]+ {"@type":"WebApplication","name":"PoseWear","url":SITE+'/en/',"applicationCategory":"DesignApplication","operatingSystem":"Any (web browser)","browserRequirements":"Requires JavaScript","inLanguage":["zh-CN","en","ja"],"offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"description":en_desc}]body=f'''<div class="wrap"><h1>Pose, outfit and portrait references with prompts</h1><p class="lead">{E(en_desc)} Favourite and combine references, copy prompts for Stable Diffusion or Midjourney, or upload your own photo to try an outfit on.</p>-<p><a class="go" href="/#costume">Open the gallery</a><a class="go" style="background:#111" href="/#studio">Try on online</a></p>+<p><a class="go" href="/#costume">Open the gallery</a><a class="go secondary" href="/#studio">Try on online</a></p><section class="sec"><h2>Browse by category</h2><ul class="tg">{catlinks("en")}<li><a href="/en/portrait/">Portraits</a></li><li><a href="/en/anime/">Anime outfits</a></li><li><a href="/en/tag/">Outfit tags</a></li></ul></section><section class="sec"><h2>Outfits</h2><ul class="cg">{featured("en")}</ul></section><section class="sec"><h2>Poses</h2><ul class="cg">{"".join(cardli("en","pose",p) for p in SP[:12])}</ul></section>-<section class="sec"><h2>About the images</h2><p class="lead">The code is open source (MIT, <a href="https://github.com/atuizz/posewear">GitHub</a>). Pose and outfit images come from AI Pose Gallery / AI Costume Gallery by <a href="https://x.com/giaaibusi">@giaaibusi</a> — no license is stated, so ask the author before reuse. Portraits come from AI Portrait Gallery by <a href="https://x.com/agi_aibusi">@agi_aibusi</a> under <a href="{CC0}" rel="license">CC0 1.0</a>. The app interface is in Chinese, with prompts available in English.</p></section></div>'''-W('/en/',shell('en','/','PoseWear – Pose & Outfit Reference Library with AI Prompts and Online Try-On',en_desc,body,ENLD))+</div>'''+W('/en/',shell('en','/','PoseWear – Pose & Outfit Reference Library with AI Prompts and Online Try-On',en_desc,body,ENLD,credit=f'''The code is open source (MIT, <a href="https://github.com/atuizz/posewear">GitHub</a>). Pose and outfit images come from AI Pose Gallery / AI Costume Gallery by <a href="https://x.com/giaaibusi">@giaaibusi</a> — no license is stated, so ask the author before reuse. Portraits come from AI Portrait Gallery by <a href="https://x.com/agi_aibusi">@agi_aibusi</a> under <a href="{CC0}" rel="license">CC0 1.0</a>.'''))add('pages','/',TODAY)# ---- 中文首页:标题、描述、真实数字、前 N 项静态卡片、JSON-LD、hreflang ----HC=dict(pose=len(SP),ang=NA_PUB,cos=len(SC),ani=ANI_PUB,por=len(SR));HA=dict(pose=len(poses),ang=NA,cos=len(cos),ani=len(acs),por=len(pors)) # 首页计数唯一来源;改公开数:HC=dict(pose=len(SP),ang=NA_PUB,cos=len(SC),por=len(SR))@@ -219,22 +227,28 @@ idx=re.sub(r'<meta name="description" content="[^"]*">',f'<meta name="descriptioidx=re.sub(r'<meta property="og:title" content="[^"]*">','<meta property="og:title" content="衣姿 PoseWear:姿势、服装、人像参考图库">',idx,1)idx=re.sub(r'<meta property="og:description" content="[^"]*">',f'<meta property="og:description" content="{E(zh_desc)}">',idx,1)idx=idx.replace('<meta name="twitter:card" content="summary_large_image">',f'<meta name="twitter:card" content="summary_large_image"><meta name="twitter:description" content="{E(zh_desc)}">',1)-idx=idx.replace('<link rel="canonical" href="https://posewear.pages.dev/">','<link rel="canonical" href="https://posewear.pages.dev/">'+alts('/'))+idx=idx.replace('https://posewear.pages.dev/',SITE+'/')+idx=idx.replace(f'<link rel="canonical" href="{SITE}/">',f'<link rel="canonical" href="{SITE}/">'+alts('/'))LD=[{"@type":"WebSite","@id":SITE+'/#website',"url":SITE+'/',"name":"衣姿 PoseWear","alternateName":["PoseWear","衣姿"],"inLanguage":"zh-CN","description":zh_desc,"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":SITE+'/?t=costume&q={search_term_string}'},"query-input":"required name=search_term_string"}},- {"@type":"WebApplication","name":"衣姿 PoseWear","url":SITE+'/',"applicationCategory":"DesignApplication","operatingSystem":"Any (web browser)","browserRequirements":"Requires JavaScript","inLanguage":["zh-CN","en"],+ {"@type":"WebApplication","name":"衣姿 PoseWear","url":SITE+'/',"applicationCategory":"DesignApplication","operatingSystem":"Any (web browser)","browserRequirements":"Requires JavaScript","inLanguage":["zh-CN","en","ja"],"offers":{"@type":"Offer","price":"0","priceCurrency":"CNY"},"description":zh_desc,"image":SITE+'/og.png',"isAccessibleForFree":True,"featureList":["姿势参考图(多角度)","服装穿搭参考图","人像脸模参考(CC0)","中英文提示词","在线 AI 试穿"]}]idx=idx.replace('</head>',f'<script type="application/ld+json">{json.dumps({"@context":"https://schema.org","@graph":LD},ensure_ascii=False,separators=(",",":"))}</script></head>',1)-HOME_COUNTS=[('288','pose'),('1439','ang'),('1407','cos'),('1320','ani'),('1499','por')]-for a,k in HOME_COUNTS:- idx=idx.replace(f'<b data-n="{a}">0</b>',f'<b data-n="{HC[k]}" data-na="{HA[k]}">{HC[k]:,}</b>')+for key, catalog in [('depth',DJ),('exp',EXJ),('hair',HAJ),('dyn',DYJ),('scene',SCJ),('light',LIJ),('prop',PRJ),('furn',FUJ)]:+ items=json.loads(catalog)+ if isinstance(items,dict): items=items['items']+ HC[key]=sum(1 for item in items if not item.get('a'))+ HA[key]=len(items)+for k in HC:+ idx=re.sub(r'<b (?=[^>]*data-stat="'+k+r'")[^>]*>[^<]*</b>',f'<b data-stat="{k}" data-n="{HC[k]}" data-na="{HA[k]}">{HC[k]:,}</b>',idx,count=1)def ssr(p):- t=p['zh'];a=p['angles'];return (f'<article class="card ssr"><div class="ph pose done"><a href="/pose/{p["id"]}/" class="ssl"><img class="ld" src="{TU(a[0]["t"])}" alt="{E(t)}" width="300" height="400" decoding="async"{"" if SP.index(p)<4 else " loading=\"lazy\""}></a><span class="badge">{p["no"]}</span></div>'+ loading = '' if SP.index(p)<4 else ' loading="lazy"'+ t=p['zh'];a=p['angles'];return (f'<article class="card ssr"><div class="ph pose done"><a href="/pose/{p["id"]}/" class="ssl"><img class="ld" src="{TU(a[0]["t"])}" alt="{E(t)}" width="300" height="400" decoding="async"{loading}></a><span class="badge">{p["no"]}</span></div>'f'<div class="info"><h3><a href="/pose/{p["id"]}/">{E(t)}</a></h3><div class="sub">{E(p["cat"])} · {len(a)} 个角度</div><div class="tags"><span class="tag">{E(p["line"])}</span><span class="tag c">{E(p["cat"])}</span></div></div></article>')g=re.search(r'(<main id="grid"[^>]*>)(.*?)(</main>)',idx,re.S)idx=idx[:g.start(2)]+''.join(ssr(p) for p in SP[:12])+idx[g.end(2):]nav='<nav class="seoc" aria-label="分类浏览"><div><h4>姿势分类</h4>'+''.join(f'<a href="/pose/{s}/">{z}</a>' for s,z,e,L in CATS['pose'])+'</div><div><h4>服装分类</h4>'+''.join(f'<a href="/costume/{s}/">{z}</a>' for s,z,e,L in CATS['costume'])+'<a href="/tag/">按单品和颜色</a></div><div><h4>人像</h4>'+''.join(f'<a href="/portrait/{s}/">{z}</a>' for s,z,e,L in CATS['portrait'])+'</div><div><h4>其他</h4><a href="/pose/">姿势图库</a><a href="/costume/">服装图库</a><a href="/anime/">动画服装图库</a><a href="/portrait/">人像图库</a><a href="/en/" hreflang="en" lang="en">English</a></div></nav>'-idx=idx.replace('<footer class="foot">',nav+'<footer class="foot">',1)+idx=idx.replace('<!-- category-index -->','<details class="footer-index"><summary>分类索引</summary>'+nav+'</details>')open(f'{D}/index.html','w').write(idx)# ---- 站点地图 ----def smx(L,img=True):diff --git a/src/app.js b/src/app.jsindex 043cff5..a31ceb0 100644--- a/src/app.js+++ b/src/app.js@@ -2,25 +2,77 @@let Q0='',QT='';try{const u=new URLSearchParams(location.search);Q0=(u.get('q')||'').slice(0,60);QT=u.get('t')||''}catch(e){}const $=s=>document.querySelector(s),$$=s=>document.querySelectorAll(s),LS=k=>{try{return JSON.parse(localStorage[k]||'null')}catch(e){return null}},SV=(k,v)=>{try{localStorage[k]=JSON.stringify(v)}catch(e){}};const esc=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));-const RM=matchMedia('(prefers-reduced-motion: reduce)').matches,HOVER=matchMedia('(hover:hover) and (pointer:fine)').matches;-const ITEMS={},DATA={},LOAD={},TABS=['pose','depth','costume','anime','portrait','expr','hair','dyn','scene','light','prop','furn','studio','fav','recent','history'],TNAME={pose:'姿势库',depth:'深度姿势',costume:'服装库',anime:'动画服装库',portrait:'人像库',expr:'表情库',hair:'发型库',dyn:'历代服饰',scene:'场景库',light:'光影库',prop:'道具库',furn:'家具库',studio:'试穿',fav:'我的收藏',recent:'最近浏览',history:'生成记录'};+const motionPreference=matchMedia('(prefers-reduced-motion: reduce)'),HOVER=matchMedia('(hover:hover) and (pointer:fine)').matches;+const ITEMS={},DATA={},LOAD={},TABS=['pose','depth','costume','anime','portrait','expr','hair','dyn','scene','light','prop','furn','studio','fav','recent','history'],TNAME={pose:'姿势库',depth:'深度姿势',costume:'服装库',anime:'动画服装库',portrait:'人像库',expr:'表情库',hair:'发型库',dyn:'历代服饰',scene:'场景库',light:'光影库',prop:'道具库',furn:'家具库',studio:'工作台',fav:'我的收藏',recent:'最近浏览',history:'生成记录'};const PFX={pose:'p:',depth:'d:',costume:'c:',anime:'a:',portrait:'r:',expr:'e:',hair:'h:',dyn:'y:',scene:'s:',light:'l:',prop:'t:',furn:'f:'},KT={p:'pose',d:'depth',c:'costume',a:'anime',r:'portrait',e:'expr',h:'hair',y:'dyn',s:'scene',l:'light',t:'prop',f:'furn'},TL=it=>({pose:'姿势',depth:'深度姿势',costume:'服装',anime:'动画服装',portrait:'人像',expr:'表情',hair:'发型',dyn:'历代服饰',scene:'场景',light:'光影',prop:'道具',furn:'家具'})[it.type];const st={tab:'pose',q:'',f:{},sort:'def',lang:LS('lang')||'zh',tl:LS('tl')||'zh',fav:new Set(LS('fav')||[]),sel:LS('sel')||[],rec:LS('rec')||[],recT:LS('recT')||{},ang:LS('ang')||{},list:[],n:0,adult:LS('adult')===true};const ok=it=>it&&(st.adult||!it.a);-function load(t){return LOAD[t]||(LOAD[t]=fetch({pose:'poses.json',depth:'depths.json',costume:'costumes.json',anime:'anime.json',portrait:'portraits.json',expr:'expressions.json',hair:'hair.json',dyn:'dynasties.json',scene:'scenes.json',light:'lights.json',prop:'props.json',furn:'furniture.json'}[t]).then(r=>{if(!r.ok)throw Error(r.status);return r.json()}).then(raw=>{const a=Array.isArray(raw)?raw:(raw.items||[]);if(t=='depth')DATA.depthMeta=raw.pack||null;a.forEach((it,i)=>{it.type=t;it.k=PFX[t]+it.id;it.ord=i;if(it.angles)it.ai=st.ang[it.k]||0;ITEMS[it.k]=it});DATA[t]=a;if(t=='depth')paintDepth();counts();return a}).catch(e=>{delete LOAD[t];throw e}))}+function load(t){return LOAD[t]||(LOAD[t]=fetch({pose:'poses.json',depth:'depths.json',costume:'costumes.json',anime:'anime.json',portrait:'portraits.json',expr:'expressions.json',hair:'hair.json',dyn:'dynasties.json',scene:'scenes.json',light:'lights.json',prop:'props.json',furn:'furniture.json'}[t]).then(r=>{if(!r.ok)throw Error(r.status);return r.json()}).then(raw=>{const a=Array.isArray(raw)?raw:(raw.items||[]);if(t=='depth')DATA.depthMeta=raw.pack||null;a.forEach((it,i)=>{it.type=t;it.k=PFX[t]+it.id;it.ord=i;if(it.angles)it.ai=st.ang[it.k]||0;ITEMS[it.k]=it});DATA[t]=a;counts();return a}).catch(e=>{delete LOAD[t];throw e}))}+function counterpartType(item){+ if(item.type==='pose')return 'depth';+ if(item.type==='depth'&&item.pack==='gia-depth')return 'pose';+ return null;+}+function poseCounterpart(item,index=item.ai){+ const type=counterpartType(item);+ if(!type||!ok(item))return null;+ const other=ITEMS[PFX[type]+item.id];+ if(!ok(other)||!counterpartType(other))return null;+ const angle=other.angles.findIndex(a=>a.zh===item.angles[index]?.zh);+ return angle<0?null:{item:other,angle};+}+const flippedCards=new Map();+function cardFace(origin){+ const face=flippedCards.get(origin.k);+ return ok(face)?face:origin;+}const needKeys=ks=>Promise.all([...new Set(ks.map(k=>KT[k[0]]).filter(Boolean))].map(load));const AH='';const ath=u=>u.startsWith('http')?u:AH+u;const thumb=it=>ath(it.angles?it.angles[it.ai].t:it.t),big=it=>it.angles?it.angles[it.ai].i:(innerWidth*(devicePixelRatio||1)>1500?it.i:it.m);const orig=it=>it.ext?'':((AH||'/')+(it.angles?it.angles[it.ai].o:it.o));-function prompt(it,lang){if(it.angles){const a=it.angles[it.ai];return lang=='en'?`${it.en}, ${it.lineEn}, ${a.en}`:`${it.zh},${it.line},${a.zh}`}return lang=='en'?it.en:it.zh}+function prompt(it,lang){const angle=it.angles?.[it.ai];return [it[lang],angle&&(lang==='en'?it.lineEn:it.line),angle?.[lang]].filter(Boolean).join(lang==='en'?', ':',')}const title=it=>it.type=='pose'||it.type=='depth'?it.zh:it.ti;-const subtitle=it=>it.type=='depth'?it.ja:st.lang=='en'?prompt(it,'en'):it.type=='pose'?`${it.cat} · ${it.angles.length} 个角度`:it.type=='portrait'?`${it.sec} · ${it.len}${it.rk?' · 人气第 '+it.rk:''}`:it.zh;-const NOTES={expr:'<div class="dnote-in"><p><span class="dtag">来源</span>表情图来自 WaveSpeed AI Emotion Gallery,底层头模为 ICT Face Model Light(ICT-FaceKit,© USC Institute for Creative Technologies,MIT)。无身份灰模头,只传神态、不传长相。</p></div>',hair:'<div class="dnote-in"><p><span class="dtag">来源</span>数据来自 CharaDB(作者 たき AI),标签数据 CC0;图片由原站托管、本站不保存,版权归原作者。</p></div>',dyn:'<div class="dnote-in"><p><span class="dtag">来源</span>中国历代服饰来自 Shisei(作者 wquguru),图片与数据 CC0 1.0,可自由使用。</p></div>',scene:'<div class="dnote-in"><p><span class="dtag">来源</span>场景来自 Shisei(作者 wquguru),图片与数据 CC0 1.0,可自由使用。空景中央留空,方便把人物放进去。</p></div>',light:'<div class="dnote-in"><p><span class="dtag">来源</span>光影来自 Shisei(作者 wquguru),图片与数据 CC0 1.0。同一个人台、同样的灰球,只有光在变——照着挑光型、抄英文描述即可。</p></div>',prop:'<div class="dnote-in"><p><span class="dtag">来源</span>道具来自 Shisei(作者 wquguru),图片与数据 CC0 1.0,可自由使用。</p></div>',furn:'<div class="dnote-in"><p><span class="dtag">来源</span>家具来自 Shisei(作者 wquguru),图片与数据 CC0 1.0;尺寸为真实厘米数,与人台同比例。</p></div>'};-function paintDepth(){const m=DATA.depthMeta,el=$('#depthNote');if(!m||!el)return;const site=m.site||'https://ai-pose-depth-gallery.pages.dev/',author=m.authorUrl||'https://x.com/giaaibusi';el.innerHTML=`<div class="dnote-in"><p><span class="dtag">${esc(m.unofficial||'非官方汉化')}</span>素材来自 <a href="${esc(site)}" target="_blank" rel="noopener">${esc(m.siteName||'ai-pose-depth-gallery')}</a>,作者<a href="${esc(author)}" target="_blank" rel="noopener">${esc(m.author||'ギア')}</a>(<a href="${esc(author)}" target="_blank" rel="noopener">${esc(author)}</a>)。</p><p class="dsub">${esc(m.note||'')}</p></div>`}-function toast(t,undo){const e=$('#toast');e.textContent=t;if(undo){const b=document.createElement('button');b.textContent='撤销';b.onclick=()=>{e.classList.remove('on','act');undo()};e.append(b)}e.classList.toggle('act',!!undo);e.classList.remove('on');void e.offsetWidth;e.classList.add('on');clearTimeout(e._t);e._t=setTimeout(()=>e.classList.remove('on','act'),undo?4500:1800)}+const subtitle=(it,layout=it.type)=>layout=='depth'?it.ja:st.lang=='en'?prompt(it,'en'):layout=='pose'?`${it.cat} · ${it.angles.length} 个角度`:layout=='portrait'?`${it.sec} · ${it.len}${it.rk?' · 人气第 '+it.rk:''}`:it.zh;+function recordNotice(text){const last=$('#noticeAction');last.textContent=text;last.hidden=false}+function toast(t,undo){recordNotice(t);const e=$('#toast');e.textContent=t;if(undo){const b=document.createElement('button');b.textContent='撤销';b.onclick=()=>{e.classList.remove('on','act');undo()};e.append(b)}e.classList.toggle('act',!!undo);e.classList.remove('on');void e.offsetWidth;e.classList.add('on');clearTimeout(e._t);e._t=setTimeout(()=>e.classList.remove('on','act'),undo?4500:1800)}const EI={'fav': '<svg viewBox="0 0 24 24"><path d="M12 20s-7-4.4-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 10c0 5.6-7 10-7 10z"/></svg>', 'rec': '<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8"/><path d="M12 8v4l3 2"/></svg>', 'q': '<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>'};-async function copy(t,label){try{await navigator.clipboard.writeText(t)}catch(e){const a=document.createElement('textarea');a.value=t;a.style.cssText='position:fixed;opacity:0';document.body.append(a);a.select();document.execCommand('copy');a.remove()}toast('已复制'+(label?'「'+label+'」':''))}-function counts(){if(DATA.pose)$('#nPose').textContent=DATA.pose.filter(ok).length;if(DATA.depth)$('#nDepth').textContent=DATA.depth.filter(ok).length;if(DATA.costume)$('#nCos').textContent=DATA.costume.filter(ok).length;if(DATA.anime)$('#nAni').textContent=DATA.anime.filter(ok).length;if(DATA.portrait)$('#nPor').textContent=DATA.portrait.length;if(DATA.expr)$('#nExp').textContent=DATA.expr.length;if(DATA.hair)$('#nHair').textContent=DATA.hair.length;if(DATA.dyn)$('#nDyn').textContent=DATA.dyn.length;if(DATA.scene)$('#nSce').textContent=DATA.scene.length;if(DATA.light)$('#nLig').textContent=DATA.light.length;if(DATA.prop)$('#nPro').textContent=DATA.prop.length;if(DATA.furn)$('#nFur').textContent=DATA.furn.length;const nf=[...st.fav].filter(k=>!ITEMS[k]||ok(ITEMS[k])).length;$('#nFav').textContent=nf||'';$('#nRec').textContent=st.rec.filter(k=>!ITEMS[k]||ok(ITEMS[k])).length||'';requestAnimationFrame(moveInd)}+async function copy(text,label){+ try {await navigator.clipboard.writeText(text)}+ catch {+ const field=document.createElement('textarea'),opener=document.activeElement;+ field.value=text;field.style.cssText='position:fixed;opacity:0';document.body.append(field);field.select();+ const copied=document.execCommand('copy');field.remove();opener?.focus({preventScroll:true});+ if(!copied)return toast('复制失败,请检查剪贴板权限');+ }+ toast('已复制'+(label?'「'+label+'」':''));+}+// Copied references use the public deployment origin, including when previewing locally.+const publicSite=document.querySelector('link[rel=canonical]').href;+const copyRefs=$('#copyRefs');+copyRefs.checked=LS('copyRefs')!==false;+copyRefs.onchange=()=>SV('copyRefs',copyRefs.checked);+function copyBrief(text, items, lang, label){+ if(!copyRefs.checked)return copy(text,label);+ const refs=items.map(it=>it && PoseWearReferences.reference(it,it.ai??0,publicSite,lang,AH||publicSite));+ return copy(PoseWearReferences.formatBrief(text,refs,lang),label);+}+function counts(){+ const bars=$$('#libraryMenu [data-tab]');+ const quantities=[];+ for(const button of bars){+ const n=button.querySelector('[data-stat]'),items=DATA[button.dataset.tab];+ if(items){+ n.dataset.n=items.filter(it=>!it.a).length;+ n.dataset.na=items.length;+ }+ const count=Number((st.adult&&n.dataset.na)||n.dataset.n);+ n.textContent=String(count);quantities.push(count);+ }+ const maximum=Math.max(1,...quantities);+ bars.forEach((button,index)=>button.style.setProperty('--share',quantities[index]/maximum));+ const nf=[...st.fav].filter(k=>!ITEMS[k]||ok(ITEMS[k])).length;+ $('#nFav').textContent=nf||'';$('#nRec').textContent=st.rec.filter(k=>!ITEMS[k]||ok(ITEMS[k])).length||'';+}const FDEF={pose:[['line','系列'],['cat','分类'],['ang','角度']],depth:[['line','系列'],['cat','分类'],['ang','角度']],costume:[['cat','分类'],['col','颜色'],['item','单品']],anime:[['cat','分类'],['col','颜色'],['item','单品']],portrait:[['sec','类型'],['len','发长'],['st','发型']],expr:[['emo','情绪'],['int','强度']],hair:[['cat','分类']],dyn:[['era','朝代'],['ang','角度']],scene:[['cat','分类'],['ang','机位']],light:[['cat','分类'],['ang','机位']],prop:[['cat','分类'],['ang','视角']],furn:[['cat','分类'],['ang','视角']],fav:[['type','类型']],recent:[['type','类型']]};const FLAB={sec:'类型',len:'发长',st:'发型',line:'系列',cat:'分类',ang:'角度',col:'颜色',item:'单品',type:'类型',emo:'情绪',int:'强度',era:'朝代'};const COLS={'黑':'black','白':'white','红':'red','粉':'pink','蓝':'blue','藏青':'navy','棕':'brown','米':'beige','象牙白':'ivory','灰':'grey','绿':'green','黄':'yellow','紫':'purple','金':'gold','银':'silver','卡其':'khaki','酒红':'burgundy','橙':'orange','奶油':'cream','薄荷':'mint','薰衣草':'lavender','橄榄':'olive'};@@ -34,19 +86,19 @@ function drawFilters(){const filters = $('#filters');const positions = new Map();let focusedChip;- if (filters.dataset.tab === st.tab) {+ if (filters.dataset.filterTab === st.tab) {for (const row of filters.querySelectorAll('.frow')) {- positions.set(row.getAttribute('aria-label'), row.scrollLeft);+ positions.set(row.dataset.filter, row.scrollLeft);}const active = document.activeElement;if (filters.contains(active) && active.matches('.chip')) focusedChip = active.dataset;}const b=base();const rows=FDEF[st.tab].map(([key,lab])=>{const c={};b.forEach(it=>val(it,key).forEach(v=>c[v]=(c[v]||0)+1));const ent=Object.entries(c).sort((a,b)=>b[1]-a[1]);if(ent.length<2&&!st.f[key])return'';- return `<div class="frow" role="group" aria-label="${lab}"><label>${lab}</label><button class="chip ${!st.f[key]?'on':''}" data-k="${key}" data-v="" aria-pressed="${!st.f[key]}">全部</button>${ent.map(([v,n])=>`<button class="chip ${st.f[key]==v?'on':''}" data-k="${key}" data-v="${esc(v)}" aria-pressed="${st.f[key]==v}">${esc(v)}<i>${n}</i></button>`).join('')}</div>`}).join('');+ return `<div class="frow" role="group" data-filter="${key}" aria-label="${lab}"><label>${lab}</label><button class="chip ${!st.f[key]?'on':''}" data-k="${key}" data-v="" aria-pressed="${!st.f[key]}">全部</button>${ent.map(([v,n])=>`<button class="chip ${st.f[key]==v?'on':''}" data-k="${key}" data-v="${esc(v)}" aria-pressed="${st.f[key]==v}">${esc(v)}<i>${n}</i></button>`).join('')}</div>`}).join('');filters.innerHTML=`<div class="dh"><b>筛选</b><button class="sm pri" data-done>完成</button></div>`+rows;- filters.dataset.tab = st.tab;+ filters.dataset.filterTab = st.tab;for (const row of filters.querySelectorAll('.frow')) {- row.scrollLeft = positions.get(row.getAttribute('aria-label')) ?? 0;+ row.scrollLeft = positions.get(row.dataset.filter) ?? 0;}if (focusedChip) {const replacement = [...filters.querySelectorAll('.chip')].find(chip =>@@ -55,78 +107,358 @@ function drawFilters(){}const act=Object.entries(st.f).filter(e=>e[1]);$('#active').innerHTML=act.map(([k,v])=>`<button data-k="${k}" title="移除此条件">${FLAB[k]}:${esc(v)} ✕</button>`).join('');$('#fN').textContent=act.length||'';$('#clearAll').hidden=!(act.length||st.q)}function shuffle(a){for(let i=a.length-1;i>0;i--){const j=Math.random()*(i+1)|0;[a[i],a[j]]=[a[j],a[i]]}return a}-function apply(){const q=st.q.toLowerCase().trim().split(/\s+/).filter(Boolean);+function apply(previousView){const q=st.q.toLowerCase().trim().split(/\s+/).filter(Boolean);let L=base().filter(it=>Object.entries(st.f).every(([k,v])=>!v||val(it,k).includes(v))&&q.every(w=>(it._s||(it._s=[it.id,it.ti,it.zh,it.en,it.ja,it.kw,it.cat,it.catEn,it.catJa,it.line,it.lineJa,it.no,it.sec,it.len,it.st,...(it.angles||[]).flatMap(a=>[a.zh,a.en,a.ja])].join(' ').toLowerCase())).includes(w)));- if(st.f.ang)L.forEach(it=>{const i=it.angles.findIndex(a=>a.zh==st.f.ang);if(i>=0)it.ai=i});- if(st.sort=='id')L=L.slice().reverse();else if(st.sort=='shuf')L=shuffle(L.slice());else if(st.sort=='rank')L=L.slice().sort((a,b)=>(a.rk||a.rc&&a.rc+10||999)-(b.rk||b.rc&&b.rc+10||999));else if(st.sort=='fav')L=L.slice().sort((a,b)=>st.fav.has(b.k)-st.fav.has(a.k));- st.list=L;const tot=base().length;const imgs=a=>a.reduce((n,it)=>n+(it.angles?it.angles.length:1),0);+ if(st.f.ang){+ for(const it of L){+ const index=it.angles.findIndex(a=>a.zh===st.f.ang);+ if(index<0)continue;+ it.ai=index;+ if(flippedCards.has(it.k)){+ const mate=poseCounterpart(it,index);+ if(mate)mate.item.ai=mate.angle;else flippedCards.delete(it.k);+ }+ }+ tray();+ }+ if(st.sort=='id')L=L.slice().reverse();else if(st.sort=='shuf'){+ const order=previousView?.order;+ L=order?L.sort((a,b)=>(order.get(a.k)??Infinity)-(order.get(b.k)??Infinity)):shuffle(L);+ }else if(st.sort=='rank')L=L.slice().sort((a,b)=>(a.rk||a.rc&&a.rc+10||999)-(b.rk||b.rc&&b.rc+10||999));else if(st.sort=='fav')L=L.slice().sort((a,b)=>st.fav.has(b.k)-st.fav.has(a.k));+ st.list=L;window.X?.filterBatch?.(L.map(cardFace));const tot=base().length;const imgs=a=>a.reduce((n,it)=>n+(it.angles?it.angles.length:1),0);$('#count').innerHTML=st.tab=='depth'?(L.length==tot?`共 <b>${tot}</b> 组 · ${imgs(base())} 张`:`<b>${L.length}</b> / ${tot} 组 · ${imgs(L)} 张`):(L.length==tot?`共 <b>${tot}</b> 项`:`<b>${L.length}</b> / ${tot} 项`);$('#grid').innerHTML='';st.n=0;const em=!L.length;$('#empty').hidden=!em;$('#clearAll').hidden=!(Object.values(st.f).some(Boolean)||st.q);document.body.classList.toggle('none0',(st.tab=='fav'||st.tab=='recent')&&!tot);if(em){const none=(st.tab=='fav'||st.tab=='recent')&&!tot;$('#emptyT').textContent=none?(st.tab=='fav'?'还没有收藏':'还没有浏览记录'):'没有找到匹配的内容';$('#emptyP').textContent=none?(st.tab=='fav'?'看到喜欢的,点卡片右上角的 ♡。收藏只存在这台设备的浏览器里,可以导出备份。':'打开过的大图会按时间排在这里,最多保留 100 条。'):'换个关键词试试,或者看看这些热门搜索:';$('#sugg').innerHTML=none?'':(SUGG[st.tab]||[]).map(s=>`<button class="chip" data-s="${s}">${s}</button>`).join('');$('#reset').hidden=none;$('#empty .emo').innerHTML=none?(st.tab=='fav'?EI.fav:EI.rec):EI.q;$('#emptyGo').innerHTML=none?'<button class="sm" data-go="pose">逛姿势库</button><button class="sm" data-go="depth">逛深度姿势</button><button class="sm" data-go="costume">逛服装库</button><button class="sm" data-go="anime">逛动画服装</button><button class="sm" data-go="portrait">逛人像库</button><button class="sm" data-go="expr">逛表情库</button><button class="sm" data-go="dyn">逛历代服饰</button><button class="sm" data-go="scene">逛场景库</button>':''}- more()}-function card(it,d){const isS=st.sel.includes(it.k),isF=st.fav.has(it.k),P=it.type=='pose',D=it.type=='depth',A2=P||D||!!it.angles,t=title(it);+ more(previousView?.count||30)}+const STUDIO_SLOT = {portrait:'portrait',costume:'garment',anime:'garment',dyn:'garment',pose:'pose',depth:'pose',expr:'expr'};+const studioSlot=type=>STUDIO_SLOT[type]||'extra';+function tryLabel(it, selecting=false) {+ if(selecting)return st.sel.includes(it.k)?'移出工作台':'加入工作台';+ const slot=STUDIO_SLOT[it.type];+ return {portrait:'用作人物参考',garment:'试穿这套',pose:'用作姿势参考',expr:'用作表情参考'}[slot] || '加入生图组合';+}+function useReference(it) {+ if (STUDIO_SLOT[it.type]) return window.WB?.pick(it);+ if (!st.sel.includes(it.k)) toggleSel(it.k);+ openTray();+}+function cardBadges(it){+ const mate=poseCounterpart(it),label=it.type==='pose'?'切换到深度图':'切换到线稿';+ const number=mate?`<button class="badge card-flip" type="button" data-a="flip" title="${label}" aria-label="${label}"><span>${esc(it.no)}</span><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 12a9 9 0 0 1 15-6l2 2m0-5v5h-5M21 12a9 9 0 0 1-15 6l-2-2m0 5v-5h5"/></svg></button>`:`<span class="badge">${esc(it.no)}</span>`;+ return `<div class="card-badges">${number}${it.a?'<span class="badge age">18+</span>':''}</div>`;+}+function loadCardPairs(){+ if(!['pose','depth','fav','recent'].includes(st.tab))return;+ const missing=new Set(base().map(counterpartType).filter(type=>type&&!DATA[type]));+ for(const type of missing)load(type).then(()=>{+ for(const badges of grid.querySelectorAll('.card-badges')){+ const it=cardFace(ITEMS[badges.closest('.card').dataset.k]);+ if(counterpartType(it)===type&&poseCounterpart(it))badges.outerHTML=cardBadges(it);+ }+ },()=>{});+}+function cardAngles(origin,it){+ const angles=it.angles.map((angle,index)=>({name:angle.zh,index}));+ if(it!==origin){+ const order=new Map(origin.angles.map((angle,index)=>[angle.zh,index]));+ angles.sort((a,b)=>(order.get(a.name)??order.size)-(order.get(b.name)??order.size));+ }+ return angles.map(({name,index})=>`<button type="button" data-a="ang" data-i="${index}" aria-pressed="${index===it.ai}" class="${index===it.ai?'on':''}">${esc(name)}</button>`).join('');+}+function card(origin,d){const it=cardFace(origin),isS=st.sel.includes(it.k),isF=st.fav.has(it.k),P=it.type=='pose',D=it.type=='depth',A2=P||D||!!it.angles,t=title(it);const tags=P||D?[[it.line,''],[it.cat,'c']]:it.type=='portrait'?[[it.sec,'c'],[it.len,'']]:[[it.cat,'c'],...val(it,'item').slice(0,3).map(x=>[x,''])];const miss=D?`<a class="miss" href="${esc(it.site)}" target="_blank" rel="noopener">请前往原站查看</a>`:'';- return `<article class="card ${isS?'sel':''}" data-k="${it.k}" style="animation-delay:${d||0}ms"><div class="ph ${D?'depth':P?'pose':'cos'}" data-a="open"><img loading="lazy" decoding="async"${D?` referrerpolicy="${esc(it.ref||'no-referrer')}"`:''} src="${esc(thumb(it))}" alt="${esc(t)}" width="${A2?300:it.type=='portrait'?400:360}" height="${A2?400:it.type=='portrait'?500:540}" draggable="false">${miss}<button class="phk" data-a="open" aria-label="${esc(t)}"></button>- ${it.rk?`<span class="badge rk">TOP ${it.rk}</span>`:''}${A2?`<span class="badge">${esc(it.no)}</span>${it.a?'<span class="badge age">18+</span>':''}<div class="angs">${it.angles.map((a,i)=>`<span data-a="ang" data-i="${i}" class="${i==it.ai?'on':''}">${esc(a.zh)}</span>`).join('')}</div>`:''}- ${st.tab=='recent'?'<button data-a="unrec" class="unrec" title="从记录中移除" aria-label="从记录中移除">✕</button>':''}<div class="cbtns"><button data-a="fav" class="${isF?'on':''}" title="${isF?'取消收藏':'收藏'}" aria-label="收藏" aria-pressed="${isF}">${isF?'♥':'♡'}</button><button data-a="sel" class="${isS?'on':''}" title="${isS?'移出组合':'加入组合'}" aria-label="加入组合" aria-pressed="${isS}">${isS?'✓':'+'}</button></div>${D?'':`<button class="try" data-a="try">${P?'用作姿势参考':it.type=='portrait'?'用作人物参考':it.type=='expr'?'用作表情参考':'试穿这套'}</button>`}</div>- <div class="info"><h3 title="${esc(t)}">${esc(t)}</h3><div class="sub">${esc(subtitle(it))}</div>${D?`<div class="sub dim">${esc(it.line)} · ${esc(it.cat)}</div>`:''}<div class="tags">${tags.map(([x,c])=>`<span class="tag ${c}">${esc(x)}</span>`).join('')}</div>- <div class="copy"><button data-a="cpzh">复制中文</button><button data-a="cpen">复制英文</button></div></div></article>`}+ return `<article class="card ${window.X?.batchPicked?.(it.k)?'picked':''} ${isS?'sel':''}" data-k="${origin.k}"${origin!==it?` data-show="${it.k}"`:''} style="animation-delay:${d||0}ms"><div class="ph ${D?'depth':P?'pose':'cos'}" data-a="open"><img loading="lazy" decoding="async"${D?` referrerpolicy="${esc(it.ref||'no-referrer')}"`:''} src="${esc(thumb(it))}" alt="${esc(t)}" width="${A2?300:it.type=='portrait'?400:360}" height="${A2?400:it.type=='portrait'?500:540}" draggable="false">${miss}<button class="phk" data-a="open" aria-label="${esc(t)}"></button>+ ${it.rk?`<span class="badge rk">TOP ${it.rk}</span>`:''}${A2?`${P||D?cardBadges(it):`<span class="badge">${esc(it.no)}</span>${it.a?'<span class="badge age">18+</span>':''}`}<div class="angs">${cardAngles(origin,it)}</div>`:''}+ ${st.tab=='recent'?'<button data-a="unrec" class="unrec" title="从记录中移除" aria-label="从记录中移除">✕</button>':''}<div class="cbtns"><button data-a="fav" class="${isF?'on':''}" title="${isF?'取消收藏':'收藏'}" aria-label="收藏" aria-pressed="${isF}">${isF?'♥':'♡'}</button><button data-a="sel" class="${isS?'on':''}" title="${isS?'移出组合':'加入组合'}" aria-label="加入组合" aria-pressed="${isS}">${isS?'✓':'+'}</button></div>${D?'':`<button class="try" data-a="try">${tryLabel(it,trayOpen)}</button>`}</div>+ <div class="info"><div class="card-heading"><h3 title="${esc(t)}">${esc(t)}</h3><button class="card-copy" data-a="copy" title="复制提示词" aria-label="复制提示词"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M15 5V4H5v11h1"/></svg></button></div><div class="sub">${esc(subtitle(it,origin.type))}</div>${origin.type==='depth'?`<div class="sub dim">${esc(it.line)} · ${esc(it.cat)}</div>`:''}<div class="tags">${tags.map(([x,c])=>`<span class="tag ${c}">${esc(x)}</span>`).join('')}</div>+ </div></article>`}function grp(k){const t=st.recT[k];if(!t)return'更早';const d=new Date();d.setHours(0,0,0,0);return t>=d?'今天':t>=d-864e5?'昨天':t>=d-6*864e5?'近 7 天':'更早'}-function more(){if(st.n>=st.list.length)return;const G=st.tab=='recent'&&!st.q&&!Object.values(st.f).some(Boolean);let pg=G&&st.n?grp(st.list[st.n-1].k):'';const h=st.list.slice(st.n,st.n+30).map((it,i)=>{let x='';if(G){const g=grp(it.k);if(g!=pg){x=`<h4 class="grp">${g}</h4>`;pg=g}}return x+card(it,RM?0:Math.min(i,14)*35)}).join('');st.n+=30;$('#grid').insertAdjacentHTML('beforeend',h)}+function more(count=30){if(st.n>=st.list.length)return;const G=st.tab=='recent'&&!st.q&&!Object.values(st.f).some(Boolean);let pg=G&&st.n?grp(st.list[st.n-1].k):'';const h=st.list.slice(st.n,st.n+count).map((it,i)=>{let x='';if(G){const g=grp(it.k);if(g!=pg){x=`<h4 class="grp">${g}</h4>`;pg=g}}return x+card(it,motionPreference.matches?0:Math.min(i,14)*35)}).join('');st.n+=count;$('#grid').insertAdjacentHTML('beforeend',h)}const grid=$('#grid');-grid.addEventListener('load',e=>{if(e.target.tagName=='IMG'){e.target.classList.add('ld');e.target.parentNode.classList.add('done')}},true);+grid.addEventListener('load',e=>{if(e.target.tagName=='IMG'){e.target.classList.add('ld');e.target.parentNode.classList.remove('err');e.target.parentNode.classList.add('done')}},true);grid.addEventListener('error',e=>{if(e.target.tagName=='IMG'){e.target.parentNode.classList.add('err','done')}},true);new IntersectionObserver(e=>e[0].isIntersecting&&more(),{rootMargin:'1400px'}).observe($('#sentinel'));-function refreshCard(k){const el=grid.querySelector(`.card[data-k="${CSS.escape(k)}"]`);if(!el)return;const t=document.createElement('div');t.innerHTML=card(ITEMS[k]);const n=t.firstElementChild;n.style.animation='none';n.querySelector('img').classList.add('ld');n.querySelector('.ph').classList.add('done');el.replaceWith(n)}-function setAng(it,i){it.ai=i;st.ang[it.k]=i;SV('ang',st.ang);refreshCard(it.k)}-function dropCard(k){const el=grid.querySelector(`.card[data-k="${CSS.escape(k)}"]`);const i=st.list.findIndex(x=>x.k==k);if(i>=0){st.list.splice(i,1);st.n=Math.max(0,st.n-1)}const fin=()=>{el&&el.remove();if(!st.list.length)apply();else{const tot=base().length;$('#count').innerHTML=st.list.length==tot?`共 <b>${tot}</b> 项`:`<b>${st.list.length}</b> / ${tot} 项`;grid.querySelectorAll('.rgrp').forEach(g=>{const n=g.nextElementSibling;if(!n||n.classList.contains('rgrp'))g.remove()})}};if(el&&!RM)el.animate([{opacity:1,transform:'none'},{opacity:0,transform:'scale(.92)'}],{duration:220,easing:'cubic-bezier(.4,0,.2,1)'}).finished.then(fin);else fin()}-function toggleFav(k,quiet){const on=!st.fav.has(k);on?st.fav.add(k):st.fav.delete(k);SV('fav',[...st.fav]);counts();if(!quiet)toast(on?'已加入收藏':'已取消收藏',on?null:()=>{toggleFav(k,1);if(st.tab=='fav')apply()});if(!on&&st.tab=='fav'&&$('#lb').hidden)dropCard(k);else{refreshCard(k);if(st.tab=='fav')pend.add(k)}if(!$('#lb').hidden)lbDraw()}+function replaceCard(el,prepared){+ const origin=ITEMS[el.dataset.k],oldImage=el.querySelector('img'),wrapper=document.createElement('div');+ wrapper.innerHTML=card(origin);+ const n=wrapper.firstElementChild,ph=n.querySelector('.ph'),img=ph.querySelector('img');+ n.style.animation='none';+ const active=document.activeElement;+ const action=el.contains(active)&&active.dataset.a;+ if(prepared){+ for(const name of ['alt','width','height','draggable'])prepared.setAttribute(name,img.getAttribute(name));+ prepared.classList.add('ld');img.replaceWith(prepared);ph.classList.add('done');+ if(!motionPreference.matches&&oldImage.complete&&oldImage.naturalWidth){+ const outgoing=oldImage.cloneNode();+ outgoing.className='ld flip-previous';+ outgoing.alt='';outgoing.setAttribute('aria-hidden','true');+ ph.classList.add('pair-turn');prepared.after(outgoing);+ outgoing.addEventListener('animationend',()=>{outgoing.remove();ph.classList.remove('pair-turn')},{once:true});+ }+ }else if(img.getAttribute('src')===oldImage.getAttribute('src')){+ const oldFace=oldImage.parentElement;+ ph.classList.toggle('done',oldFace.classList.contains('done'));+ ph.classList.toggle('err',oldFace.classList.contains('err'));+ img.replaceWith(oldImage);+ }+ el.replaceWith(n);+ if(action) n.querySelector(`button[data-a="${CSS.escape(action)}"]`+(active.dataset.i!=null?`[data-i="${CSS.escape(active.dataset.i)}"]`:''))?.focus({preventScroll:true});+}+function refreshCard(k){+ const key=CSS.escape(k);+ grid.querySelectorAll(`.card[data-show="${key}"],.card[data-k="${key}"]:not([data-show])`).forEach(el=>replaceCard(el));+}+async function flipCard(el,button,it){+ const mate=poseCounterpart(it);+ if(!mate||button.hasAttribute('aria-busy'))return;+ button.setAttribute('aria-busy','true');+ const image=new Image(),view=mate.item.angles[mate.angle];+ if(mate.item.type==='depth')image.referrerPolicy=mate.item.ref||'no-referrer';+ image.src=ath(view.t);+ try{await image.decode()}catch{+ if(button.isConnected){button.removeAttribute('aria-busy');toast('图片加载失败,请重试')}+ return;+ }+ if(!button.isConnected||!ok(mate.item)||document.body.classList.contains('batch')){+ button.removeAttribute('aria-busy');return;+ }+ if(mate.item.ai!==mate.angle)setAng(mate.item,mate.angle);+ if(mate.item.k===el.dataset.k)flippedCards.delete(el.dataset.k);+ else flippedCards.set(el.dataset.k,mate.item);+ replaceCard(el,image);+}+function setAng(it,i){it.ai=i;st.ang[it.k]=i;SV('ang',st.ang);refreshCard(it.k);if(st.sel.includes(it.k))tray()}+function dropCard(k){const el=grid.querySelector(`.card[data-k="${CSS.escape(k)}"]`);const i=st.list.findIndex(x=>x.k==k);if(i>=0){st.list.splice(i,1);st.n=Math.max(0,st.n-1)}const fin=()=>{el&&el.remove();if(!st.list.length)apply();else{const tot=base().length;$('#count').innerHTML=st.list.length==tot?`共 <b>${tot}</b> 项`:`<b>${st.list.length}</b> / ${tot} 项`;grid.querySelectorAll('.grp').forEach(g=>{const n=g.nextElementSibling;if(!n||n.classList.contains('grp'))g.remove()})}};if(el&&!motionPreference.matches)el.animate([{opacity:1,transform:'none'},{opacity:0,transform:'scale(.92)'}],{duration:220,easing:'cubic-bezier(.4,0,.2,1)'}).finished.then(fin);else fin()}+function toggleFav(k,quiet){const on=!st.fav.has(k);on?st.fav.add(k):st.fav.delete(k);SV('fav',[...st.fav]);counts();if(!quiet)toast(on?'已加入收藏':'已取消收藏',on?null:()=>{toggleFav(k,1);if(st.tab=='fav')apply()});refreshCard(k);+ if(st.tab==='fav'){+ if(!$('#lb').hidden)pend.add(k);+ else if(on)apply();else dropCard(k);+ }+ if(!$('#lb').hidden)lbDraw()}function unRec(k){const old=st.rec.slice();st.rec=st.rec.filter(x=>x!=k);SV('rec',st.rec);counts();dropCard(k);toast('已从记录中移除',()=>{st.rec=old;SV('rec',old);counts();apply()})}-function toggleSel(k){const i=st.sel.indexOf(k);i>=0?st.sel.splice(i,1):st.sel.push(k);SV('sel',st.sel);refreshCard(k);tray(i<0);toast(i<0?'已加入组合':'已移出组合');if(!$('#lb').hidden)lbDraw()}-function combo(lang){const its=st.sel.map(k=>ITEMS[k]).filter(Boolean),p=its.filter(i=>i.type=='pose'),d=its.filter(i=>i.type=='depth'),c=its.filter(i=>i.type=='costume'||i.type=='anime'||i.type=='dyn'),r=its.filter(i=>i.type=='portrait'),e=its.filter(i=>i.type=='expr'),h=its.filter(i=>i.type=='hair'),s=its.filter(i=>i.type=='scene'),l=its.filter(i=>i.type=='light');- if(lang=='en')return['masterpiece, best quality, 1girl',...r.map(i=>i.en.replace(/, consistent facial features, face reference$/,'')),...c.map(i=>i.en.replace(/^\w+ outfit, /,'')),...h.map(i=>'hairstyle: '+i.en),...e.map(i=>'expression: '+i.en),...p.map(i=>prompt(i,'en')),...d.map(i=>'depth reference, '+prompt(i,'en')),...s.map(i=>'scene: '+prompt(i,'en')),...l.map(i=>'lighting: '+prompt(i,'en'))].join(', ');- return['杰作,最佳画质,一位女性',...r.map(i=>'人物:'+i.len+(i.st?','+i.st:'')),...c.map(i=>i.zh.replace(/。$/,'')),...h.map(i=>'发型:'+i.ti),...e.map(i=>'神态:'+i.zh),...p.map(i=>'摆出「'+prompt(i,'zh')+'」的姿势'),...d.map(i=>'深度姿势参考:'+prompt(i,'zh')),...s.map(i=>'场景:'+prompt(i,'zh')),...l.map(i=>'光线:'+prompt(i,'zh'))].join(';')+'。'}+function toggleSel(k){+ const index=st.sel.indexOf(k),added=index<0;+ if(added)st.sel.push(k);else st.sel.splice(index,1);+ SV('sel',st.sel);refreshCard(k);tray(added?k:null);+ const message=added?'已加入组合':'已移出组合';+ if(trayOpen)recordNotice(message);else toast(message);+ if(!$('#lb').hidden)lbDraw();+}+function visibleSelection(){+ const items=st.sel.map(k=>ITEMS[k]).filter(ok);+ const poses=items.filter(counterpartType);+ if(!poses.some(it=>it.type==='pose')||!poses.some(it=>it.type==='depth'))return items;+ const groups=new Map();+ for(const it of poses){+ if(!groups.has(it.id))groups.set(it.id,{});+ groups.get(it.id)[it.type]=it;+ }+ const ordered=[...groups.values()].flatMap(({pose,depth})=>[pose,depth].filter(Boolean));+ const rest=items.filter(it=>!counterpartType(it));+ rest.splice(items.indexOf(poses[0]),0,...ordered);+ return rest;+}+function compactSelection(selected){+ if(selected.length<=3)return selected;+ const recent=new Set();+ for(let i=st.sel.length-1;i>=0&&recent.size<3;i--){+ const it=ITEMS[st.sel[i]];+ if(!ok(it)||recent.has(it))continue;+ recent.add(it);+ const type=counterpartType(it);+ const other=type&&ITEMS[PFX[type]+it.id];+ if(recent.size<3&&other&&counterpartType(other)&&selected.includes(other))recent.add(other);+ }+ return selected.filter(it=>recent.has(it));+}++function combo(lang){+ return visibleSelection().map(it=>{+ const {label}=PoseWearReferences.reference(it,it.ai??0,publicSite,lang,AH||publicSite);+ return label+' — '+prompt(it,lang);+ }).join('\n');+}let trayOpen=false;-function tray(added){const n=st.sel.length,fab=$('#trayFab');if(st.tab=='studio'||st.tab=='history'){$('#tray').hidden=true;if(fab)fab.hidden=true;document.body.classList.remove('tray');return}- if(added)trayOpen=true;const open=trayOpen;$('#tray').hidden=!open;if(fab){fab.hidden=open;const bd=$('#trayFabN');bd.textContent=n;bd.hidden=!n}document.body.classList.toggle('tray',open);if(!open)return;$('#tgEmpty').hidden=n>0;$('#trayComboBox').hidden=!n;- const UN={pose:'个姿势',depth:'个深度姿势',costume:'套服装',anime:'套服装',portrait:'个人像',expr:'个表情',hair:'款发型',dyn:'套历代服饰',scene:'个场景',light:'种光影',prop:'件道具',furn:'件家具'},tc={};st.sel.forEach(k=>{const it=ITEMS[k];if(it)tc[it.type]=(tc[it.type]||0)+1});$('#trayN').textContent=Object.entries(tc).map(([t,m])=>`${m} ${UN[t]||'项'}`).join(' · ');+function trayThumbnail(item){+ return `<img data-type="${item.type}" src="${esc(thumb(item))}"${item.ref?` referrerpolicy="${esc(item.ref)}"`:''} alt="">`;+}+function trayItem(it){+ const type=counterpartType(it);+ const name=type?[it.no,title(it),it.angles[it.ai].zh].join(' · '):title(it);+ const action=type==='depth'?'添加同视角深度姿势':'添加同视角姿势';+ const pairButton=type?`<button class="tray-pair" data-pair="${esc(it.k)}" title="${action}" aria-label="${action}" hidden>+</button>`:'';+ return `<div title="${esc(name)}">${trayThumbnail(it)}<em>${TL(it)}</em>${pairButton}<button data-k="${esc(it.k)}" type="button" title="移除" aria-label="移除 ${esc(type?TL(it)+' · '+name:name)}">×</button></div>`;+}+function showTrayPairs(){+ for(const button of $$('#trayItems [data-pair]')){+ const mate=poseCounterpart(ITEMS[button.dataset.pair]);+ button.hidden=!mate||st.sel.includes(mate.item.k);+ }+}+function tray(addedKey){+ const selected=visibleSelection(),n=selected.length,fab=$('#trayFab'),badge=$('#trayFabN');+ fab.hidden=trayOpen;fab.setAttribute('aria-expanded',String(trayOpen));+ badge.textContent=n;badge.hidden=!n;+ $('#trayFilm').innerHTML=compactSelection(selected).map(trayThumbnail).join('');+ if(addedKey&&!trayOpen&&!motionPreference.matches)fab.animate([{transform:'scale(1)'},{transform:'scale(1.12)'},{transform:'scale(1)'}],{duration:300});+ $('#tray').hidden=!trayOpen;+ document.body.classList.toggle('tray',trayOpen);+ if(!trayOpen)return;+ $('#tgEmpty').hidden=n>0;$('#trayClear').hidden=!n;$('#trayComboBox').hidden=!n;+ $('#trayN').textContent=n ? String(n) : '';$$('[data-tl]').forEach(b=>b.classList.toggle('on',b.dataset.tl==st.tl));- $('#trayItems').innerHTML=st.sel.map(k=>ITEMS[k]?`<div><img src="${esc(thumb(ITEMS[k]))}"${ITEMS[k].ref?` referrerpolicy="${esc(ITEMS[k].ref)}"`:''} alt=""><em>${TL(ITEMS[k])}</em><b data-k="${k}" title="移除" role="button" aria-label="移除">×</b></div>`:'').join('');$('#trayText').textContent=combo(st.tl);tgSync()}-$('#trayItems').onclick=e=>{const k=e.target.dataset.k;k&&toggleSel(k)};$('#trayCopyEn').onclick=()=>copy(combo('en'),'组合英文提示词');$('#trayCopyZh').onclick=()=>copy(combo('zh'),'组合中文描述');+ const strip=$('#trayItems');+ strip.innerHTML=selected.map(trayItem).join('');+ showTrayPairs();+ const missing=new Set(selected.map(counterpartType).filter(t=>t&&!DATA[t]));+ if(missing.size)Promise.all([...missing].map(load)).then(showTrayPairs,()=>{});+ if(addedKey){+ const added=strip.querySelector(`[data-k="${CSS.escape(addedKey)}"]`)?.parentElement;+ if(added){+ const bounds=strip.getBoundingClientRect(),item=added.getBoundingClientRect();+ const shift=item.left<bounds.left?item.left-bounds.left:Math.max(0,item.right-bounds.right);+ if(shift)strip.scrollBy({left:shift,behavior:motionPreference.matches?'instant':'smooth'});+ if(!motionPreference.matches)added.animate([{opacity:.35,transform:'translateY(6px)'},{opacity:1,transform:'none'}],{duration:220});+ }+ }+ $('#trayText').textContent=combo(st.tl);tgSync()+}+$('#trayItems').onclick=e=>{+ const source=e.target.closest('button[data-pair]');+ if(source){+ const mate=poseCounterpart(ITEMS[source.dataset.pair]);+ if(!mate||st.sel.includes(mate.item.k))return;+ setAng(mate.item,mate.angle);toggleSel(mate.item.k);+ $('#trayItems').querySelector(`[data-k="${CSS.escape(mate.item.k)}"]`).focus({preventScroll:true});+ return;+ }+ const button=e.target.closest('button[data-k]');if(!button)return;+ const pos=[...$$('#trayItems [data-k]')].indexOf(button);toggleSel(button.dataset.k);+ const buttons=$$('#trayItems [data-k]');+ (buttons[Math.min(pos,buttons.length-1)]||$('#tgAddRow button')).focus({preventScroll:true});+};$('#trayCopyEn').onclick=()=>copyBrief(combo('en'),visibleSelection(),'en','组合英文提示词');$('#trayCopyZh').onclick=()=>copyBrief(combo('zh'),visibleSelection(),'zh','组合中文描述');$$('[data-tl]').forEach(b=>b.onclick=()=>{st.tl=b.dataset.tl;SV('tl',st.tl);tray()});-$('#trayMin').onclick=()=>{trayOpen=false;tray()};-$('#trayFab').onclick=()=>{trayOpen=true;tray()};-$('#tgAddRow').onclick=e=>{const b=e.target.closest('[data-add]');if(!b||!window.WB)return;WB.openPicker(b.dataset.add,{keys:()=>st.sel.slice(),toggle:k=>{toggleSel(k);return st.sel.includes(k)}})};-$('#trayClear').onclick=()=>{const s=st.sel;st.sel=[];SV('sel',[]);s.forEach(refreshCard);tray();toast('已清空组合')};+function setTrayOpen(open){+ trayOpen=open;+ tray();+ for(const button of grid.querySelectorAll('[data-a="try"]')){+ const item=cardFace(ITEMS[button.closest('.card').dataset.k]);+ button.textContent=tryLabel(item,open);+ }+}+function openTray(){setTrayOpen(true);$('#tray').focus({preventScroll:true})}+function closeTray(restore=true){setTrayOpen(false);if(restore)$('#trayFab').focus({preventScroll:true})}+$('#trayMin').onclick=()=>closeTray();+$('#trayFab').onclick=openTray;+$('#tgAddRow').onclick=e=>{+ const button=e.target.closest('[data-add]');if(!button||!window.WB)return;+ const menu=button.closest('details');+ if(menu){menu.open=false;menu.querySelector('summary').focus({preventScroll:true})}+ WB.openPicker(button.dataset.add,{+ keys:()=>st.sel.slice(),+ toggle:(k,ai)=>{+ const item=ITEMS[k];+ if(ai!=null&&item.ai!==ai&&!st.sel.includes(k))setAng(item,ai);+ toggleSel(k);+ return st.sel.includes(k);+ }+ });+};+$('#trayClear').onclick=()=>{const s=st.sel;st.sel=[];SV('sel',[]);s.forEach(refreshCard);tray();$('#tgAddRow button').focus({preventScroll:true});toast('已清空组合')};// —— 托盘简易生图:组合直接同步到试穿台选材,在托盘内生成-const TG_SLOT={portrait:'portrait',costume:'garment',anime:'garment',dyn:'garment',pose:'pose',depth:'pose',expr:'expr'};-let tgSig='',tgBusy=false,tgRecs=[],tgUrls=[],tgCur=0;-function tgGroups(){const g={portrait:[],garment:[],pose:[],expr:[]},extra=[];st.sel.forEach(k=>{const it=ITEMS[k];if(!it)return;const s=TG_SLOT[it.type];if(s)g[s].push(it);else extra.push(it)});return{g,extra}}-async function tgSync(){const pv=$('#tgProv');if(pv)pv.textContent=window.WB&&WB._cfg.key?WB.provLabel():'未配置 API';if(!st.sel.length)tgSig='';if(!st.sel.length||!window.WB)return;const sig=st.sel.join(',');if(sig==tgSig)return;tgSig=sig;const{g,extra}=tgGroups();try{const base=await WB.setSel(g);const ex=extra.map(it=>prompt(it,st.tl)).join(st.tl=='en'?', ':';');$('#tgPrompt').value=base+(ex?'\n'+(st.tl=='en'?'Additional: ':'补充:')+ex:'')}catch(e){}}+const trayDraft=LS('trayDraft');+let tgAutoPrompt='',tgEdited=trayDraft?.prompt!=null,tgBusy=false,tgRecs=[],tgUrls=[],tgCur=0;+if(trayDraft){+ $('#tgPrompt').value=trayDraft.prompt??'';+ $('#tgN').value=trayDraft.count;+ $('#tgAR').value=trayDraft.ratio;+}+function saveTrayDraft(){+ SV('trayDraft',{prompt:tgEdited?$('#tgPrompt').value:null,count:$('#tgN').value,ratio:$('#tgAR').value});+}+function groupSelection(items) {+ const groups={portrait:[],garment:[],pose:[],expr:[],extra:[]};+ for(const it of items)groups[studioSlot(it.type)].push(it);+ return groups;+}+const traySelection=()=>groupSelection(visibleSelection());+function tgSync(){+ const editor=$('#tgPrompt');+ $('#tgProv').textContent=window.WB&&WB.configured()?WB.provLabel():'未配置 API';+ $('#tgCfg .dot').classList.toggle('on',!!window.WB?.configured());+ if(!visibleSelection().length){tgAutoPrompt='';if(!tgEdited)editor.value='';return}+ if(!window.WB)return;+ tgAutoPrompt=WB.selectionPrompt(traySelection(),st.tl);+ if(!tgEdited)editor.value=tgAutoPrompt;+}+$('#tgCopyDraft').onclick=()=>{+ const g=traySelection();+ const inputs=[...g.portrait.slice(0,1),...g.garment.slice(0,2),...g.pose.slice(0,6),...g.expr.slice(0,1)];+ const other=visibleSelection().filter(it=>!inputs.includes(it));+ copyBrief($('#tgPrompt').value,[...inputs,...other],st.tl,'提示词');+};+$('#tgPrompt').oninput=e=>{tgEdited=e.target.value!==tgAutoPrompt;saveTrayDraft()};+$('#tgN').onchange=$('#tgAR').onchange=saveTrayDraft;function tgStat(t){const s=$('#tgStat');if(!s)return;s.hidden=!t;if(t)s.textContent=t}function tgRender(){tgUrls.forEach(u=>URL.revokeObjectURL(u));tgUrls=tgRecs.map(r=>URL.createObjectURL(r.after));$('#tgRes').innerHTML=tgUrls.map((u,i)=>`<button data-tg="${i}" title="查看大图"><img src="${u}" alt="生成结果 ${i+1}"></button>`).join('')}-$('#tgRes').onclick=e=>{const b=e.target.closest('[data-tg]');if(!b)return;tgCur=+b.dataset.tg;$('#tgViewImg').src=tgUrls[tgCur];$('#tgView').hidden=false};-const tgClose=()=>{$('#tgView').hidden=true};+$('#tgRes').onclick=e=>{const b=e.target.closest('[data-tg]');if(!b)return;tgCur=+b.dataset.tg;$('#tgViewImg').src=tgUrls[tgCur];openDialog($('#tgView'),$('#tgViewX'),b)};+const tgClose=()=>closeDialog($('#tgView'));$('#tgViewX').onclick=tgClose;$('#tgView').addEventListener('click',e=>{if(e.target.classList.contains('tgv-bg'))tgClose()});$('#tgDl').onclick=()=>{const r=tgRecs[tgCur];if(r&&window.X)window.X.dl(r.after,`posewear-gen-${tgCur+1}.png`)};-$('#tgHist').onclick=()=>{tgClose();setTab('history')};+$('#tgHist').onclick=()=>{tgClose();closeTray(false);navigate('history')};$('#tgCfg').onclick=()=>window.WB&&WB.cfgOpen();-$('#tgStudio').onclick=()=>setTab('studio');+$('#cfg').addEventListener('click',e=>{+ if(trayOpen&&e.target.closest('#cfSave,#cfClr'))tgSync();+});+async function sendToStudio(items,append=false,draft) {+ const groups=groupSelection(items);+ try {+ if(items.length||draft)await (append?WB.addSelection:WB.setSel)(groups,'',draft);+ await navigate('studio');+ return true;+ } catch {toast('素材未能载入,请重试');return false}+}+$('#tgStudio').onclick=async()=>{+ const items=visibleSelection(),prompt=$('#tgPrompt').value.trim();+ const draft=items.length||prompt?{prompt:tgEdited?prompt:'',lang:st.tl,count:$('#tgN').value,ratio:$('#tgAR').value}:null;+ if(await sendToStudio(items,false,draft)){closeTray(false);$('#stT').focus({preventScroll:true})}+};$('#tgStop').onclick=()=>window.WB&&WB.stop();-$('#tgGo').onclick=async()=>{if(tgBusy)return;if(!window.WB)return;if(!WB._cfg.key){WB.cfgOpen();return}- if(!st.sel.length)return toast('先从图库里选几项加入组合');await tgSync();tgBusy=true;const go=$('#tgGo');go.disabled=true;go.textContent='生成中…';$('#tgStop').hidden=false;tgStat('正在准备素材…');- const pv=$('#tgPrompt').value.trim(),o={n:+$('#tgN').value||1,ar:$('#tgAR').value,onTick:(d,t)=>tgStat(`生成中… 已完成 ${d} / ${t}`)};if(pv)o.prompt=pv;- try{const r=await WB.quick(o);if(r.got&&r.got.length){tgRecs=r.got;tgRender()}if(r.errs&&r.errs.length){const e=r.errs.find(x=>x.safe)||r.errs[0];tgStat(e.name=='AbortError'?'已取消':(e.safe?'被服务商的安全审核拦下了,换个服务商或服装再试':'生成失败:'+WB.nice(e).split('\n')[0]))}else if(r.got&&r.got.length)tgStat(`完成 ${r.got.length} 张,已存入生成记录`);else if(r.nokey)tgStat('请先配置 API')}- catch(e){tgStat('生成失败:'+(e.message||e))}finally{tgBusy=false;go.disabled=false;go.textContent='生成图片';$('#tgStop').hidden=true}};-grid.onclick=e=>{if(e.target.closest('a.miss'))return;const a=e.target.closest('[data-a]');if(!a)return;const c=e.target.closest('.card'),k=c.dataset.k,it=ITEMS[k];e.stopPropagation();+$('#tgGo').onclick=async()=>{if(tgBusy)return;if(!window.WB)return;if(!WB.configured()){WB.cfgOpen();return}+ if(!visibleSelection().length&&!$('#tgPrompt').value.trim())return $('#tgPrompt').focus();tgSync();tgBusy=true;const go=$('#tgGo');go.disabled=true;go.textContent='生成中…';$('#tgStop').hidden=false;tgStat('正在准备素材…');+ const pv=$('#tgPrompt').value.trim(),o={selection:traySelection(),lang:st.tl,n:+$('#tgN').value||1,ar:$('#tgAR').value,onTick:(d,t)=>tgStat(`生成中… 已完成 ${d} / ${t}`)};if(pv)o.prompt=pv;+ try{+ const r=await WB.quick(o);+ if(r.got.length){tgRecs=r.got;tgRender()}+ const messages=[];+ if(r.got.length)messages.push(r.unsaved?`完成 ${r.got.length} 张,其中 ${r.unsaved} 张未存入生成记录,请立即下载`:`完成 ${r.got.length} 张,已存入生成记录`);+ if(r.cancelled)messages.push('已取消');+ else if(r.errs.length){const err=r.errs.find(x=>x.safe)||r.errs[0];messages.push(err.safe?'被服务商的安全审核拦下了':'生成失败:'+WB.nice(err).split('\n')[0])}+ if(r.warns?.length)messages.push(...r.warns);+ if(r.nokey)messages.push('请先配置 API');+ tgStat(messages.join(';'));+ }catch(e){tgStat('生成失败:'+(e.message||e))}finally{tgBusy=false;go.disabled=false;go.textContent='生成图片';$('#tgStop').hidden=true}};++grid.onclick=e=>{if(e.target.closest('a.miss'))return;const a=e.target.closest('[data-a]');if(!a)return;const c=e.target.closest('.card'),origin=ITEMS[c.dataset.k],it=cardFace(origin),k=it.k;e.stopPropagation();const ph=c.querySelector('.ph');if(a.dataset.a=='open'&&ph.classList.contains('err')){const im=ph.querySelector('img');ph.classList.remove('err','done');im.src=thumb(it)+'?r='+Date.now();return}- ({open:()=>lbOpen(st.list.indexOf(it),c),fav:()=>toggleFav(k),unrec:()=>unRec(k),sel:()=>toggleSel(k),cpen:()=>copy(prompt(it,'en'),'英文提示词'),cpzh:()=>copy(prompt(it,'zh'),'中文描述'),try:()=>window.WB&&WB.pick(it),ang:()=>setAng(it,+a.dataset.i)})[a.dataset.a]()};-function viewT(fn){if(document.startViewTransition&&!RM){try{const v=document.startViewTransition(fn);v.ready.catch(()=>{});v.finished.catch(()=>{});return v.updateCallbackDone.catch(()=>{})}catch(e){}}fn();grid.classList.add('fade');requestAnimationFrame(()=>requestAnimationFrame(()=>grid.classList.remove('fade')));return Promise.resolve()}-function drawer(o){$('#filters').classList.toggle('open',o);$('#fBtn').classList.toggle('on',o)}+ ({open:()=>lbOpen(st.list.indexOf(origin),c),flip:()=>flipCard(c,a,it),fav:()=>toggleFav(k),unrec:()=>unRec(origin.k),sel:()=>toggleSel(k),copy:()=>copyBrief(prompt(it,st.lang),[it],st.lang,'提示词'),try:()=>trayOpen?toggleSel(it.k):useReference(it),ang:()=>setAng(it,+a.dataset.i)})[a.dataset.a]()};+function viewT(fn){+ if(motionPreference.matches){fn();return Promise.resolve()}+ if(document.startViewTransition){+ const transition=document.startViewTransition(fn);+ transition.ready.catch(()=>{}); // Transitions may be skipped while navigating quickly.+ return transition.updateCallbackDone;+ }+ fn();+ grid.classList.add('fade');+ requestAnimationFrame(()=>requestAnimationFrame(()=>grid.classList.remove('fade')));+ return Promise.resolve();+}+function drawer(o){$('#filters').classList.toggle('open',o);$('#fBtn').classList.toggle('on',o);$('#fBtn').setAttribute('aria-expanded',String(o))}function scrollHorizontal(event) {const mode = event.deltaMode;if (!event.cancelable || event.ctrlKey || event.shiftKey || event.deltaX || !event.deltaY) return;@@ -148,54 +480,157 @@ $('#active').onclick=e=>{const b=e.target.closest('button');if(b){st.f[b.datasetconst clearAll=()=>{st.f={};st.q='';$('#q').value='';$('#qx').hidden=true;viewT(()=>{drawFilters();apply()})};$('#reset').onclick=clearAll;$('#clearAll').onclick=clearAll;$('#sugg').onclick=e=>{const s=e.target.closest('[data-s]');if(s){st.f={};$('#q').value=st.q=s.dataset.s;$('#qx').hidden=false;drawFilters();apply()}};$('#sort').onchange=e=>{st.sort=e.target.value;viewT(apply)};+$('#qDone').onclick=()=>$('#libraryMenu summary').focus({preventScroll:true});let qt;$('#q').oninput=e=>{$('#qx').hidden=!e.target.value;clearTimeout(qt);qt=setTimeout(()=>{st.q=e.target.value;apply()},160)};$('#qx').onclick=()=>{$('#q').value='';st.q='';$('#qx').hidden=true;apply();$('#q').focus()};function randPick(){if(!st.list.length)return toast('当前没有可选的内容');const i=Math.random()*st.list.length|0;lbOpen(i);0}$('#rand').onclick=randPick;// 语言-function setLang(l,quiet){st.lang=l;SV('lang',l);document.documentElement.dataset.lang=l;$$('button[data-lang]').forEach(b=>b.classList.toggle('on',b.dataset.lang==l));grid.querySelectorAll('.card').forEach(c=>{const it=ITEMS[c.dataset.k];if(it)c.querySelector('.sub').textContent=subtitle(it)});if(!quiet)toast(l=='zh'?'描述语言:中文':'描述语言:英文提示词')}+function setLang(l,quiet){st.lang=l;SV('lang',l);document.documentElement.dataset.lang=l;$$('button[data-lang]').forEach(b=>b.classList.toggle('on',b.dataset.lang==l));grid.querySelectorAll('.card').forEach(c=>{const origin=ITEMS[c.dataset.k];if(origin)c.querySelector('.sub').textContent=subtitle(cardFace(origin),origin.type)});if(!quiet)toast(l=='zh'?'描述语言:中文':'描述语言:英文提示词')}$$('button[data-lang]').forEach(b=>b.onclick=()=>setLang(b.dataset.lang));// 标签页-function moveInd(){const b=$('.tabs button.on'),ind=$('.ind');if(!b)return;ind.style.width=b.offsetWidth+'px';ind.style.transform=`translateX(${b.offsetLeft}px)`}-function selectTab(tab) {- for (const button of $$('.tabs button')) {- const selected = button.dataset.tab === tab;- button.classList.toggle('on', selected);- button.setAttribute('aria-selected', selected);+function selectTab(tab){+ const active=$(`.tabs [data-tab="${tab}"]`);+ const library=active.closest('#libraryMenu'),personal=active.closest('#personalMenu');+ $('#libraryLabel').textContent=library?TNAME[tab]:'素材库';+ $('#personalLabel').textContent=personal?TNAME[tab]:'我的';+ $('#collectionTitle').textContent=TNAME[tab];+ for(const button of $$('.tabs [data-tab]')){+ button.classList.toggle('on',button===active);+ if(button===active)button.setAttribute('aria-current','page');+ else button.removeAttribute('aria-current');+ }+ for(const menu of $$('.tabs details')){+ menu.classList.toggle('current',menu===library||menu===personal);+ menu.open=false;+ }+}+document.addEventListener('pointerdown',event=>{+ for(const menu of $$('.shell-menu[open]'))if(!menu.contains(event.target))menu.open=false;+});+for(const menu of $$('.shell-menu')){+ menu.addEventListener('focusout',event=>{+ if(event.relatedTarget&&!menu.contains(event.relatedTarget))menu.open=false;+ });+ menu.addEventListener('keydown',event=>{+ if(event.key==='Escape'&&menu.open){+ event.preventDefault();event.stopPropagation();menu.open=false;+ menu.querySelector('summary').focus();+ }+ const items=[...menu.querySelectorAll('[data-tab],[data-theme-choice]')];+ if(!items.length)return;+ const index=items.indexOf(event.target);+ let next;+ switch(event.key){+ case 'ArrowDown':next=(index+1)%items.length;break;+ case 'ArrowUp':next=index<=0?items.length-1:index-1;break;+ case 'Home':next=0;break;+ case 'End':next=items.length-1;break;+ default:return;+ }+ event.preventDefault();event.stopPropagation();menu.open=true;items[next].focus();+ });+}+// Keep the gallery position while the user works in the studio or checks a result.+let galleryReturn=null,tabRequest=0;+const isWorkspace=tab=>tab==='studio'||tab==='history';+function navigate(tab){+ const hash='#'+tab;+ if(location.hash!==hash){+ if(history.state?.galleryItem)history.replaceState(null,'',hash);+ else history.pushState(null,'',hash);+ }+ const openingStudio=tab==='studio'&&st.tab!=='studio';+ const ready=setTab(tab);+ if(openingStudio)$('#stT').focus({preventScroll:true});+ return ready;+}+async function setTab(t,openId,workbenchId){+ const request=++tabRequest,changed=st.tab!==t;+ clearTimeout(qt);+ if(changed&&st.tab&&!isWorkspace(st.tab)&&isWorkspace(t)){+ galleryReturn={tab:st.tab,query:$('#q').value,filters:{...st.f},count:st.n,scroll:scrollY,+ cardKey:document.activeElement.closest('.card')?.dataset.k,+ order:st.sort==='shuf'?new Map(st.list.map((item,i)=>[item.k,i])):null};}- moveInd();- $('.tabs button.on')?.scrollIntoView({block:'nearest',inline:'nearest'});-}-async function setTab(t,openId){$('#porNote').hidden=t!='portrait';$('#depthNote').hidden=t!='depth';const sn=$('#srcNote');if(sn){sn.hidden=!NOTES[t];if(NOTES[t])sn.innerHTML=NOTES[t]}document.body.classList.toggle('depth',t=='depth');if(t=='studio'){st.tab=t;selectTab(t);document.title='试穿 · 衣姿 PoseWear';history.replaceState(null,'','#studio');document.body.classList.add('studio');document.body.classList.remove('histview');$('#studio').hidden=false;$('#histSec').hidden=true;$('#tray').hidden=true;scrollTo({top:0});window.WB&&WB.show();return}- if(t=='history'){st.tab=t;selectTab(t);document.title='生成记录 · 衣姿 PoseWear';history.replaceState(null,'','#history');document.body.classList.remove('studio');document.body.classList.add('histview');$('#studio').hidden=true;$('#histSec').hidden=false;$('#tray').hidden=true;scrollTo({top:0});window.HIS&&HIS.show();return}- if(document.body.classList.contains('studio')){document.body.classList.remove('studio');$('#studio').hidden=true;tray()}- if(document.body.classList.contains('histview')){document.body.classList.remove('histview');$('#histSec').hidden=true;tray()}- const changed=st.tab!=t;st.tab=t;if(changed)grid.classList.add('gbusy');st.f={};st.q='';$('#q').value='';$('#qx').hidden=true;+ const previous=isWorkspace(st.tab)&&!openId&&workbenchId===undefined&&galleryReturn?.tab===t?galleryReturn:null;+ if(changed&&!isWorkspace(t))galleryReturn=null;+ if(changed){window.X?.closeBatch?.();flippedCards.clear()}+ st.tab=t;tray();+document.body.classList.toggle('depth',t=='depth');if(t=='studio'){selectTab(t);document.title='工作台 · 衣姿 PoseWear';history.replaceState(null,'','#studio');document.body.classList.add('studio');document.body.classList.remove('histview');$('#studio').hidden=false;$('#histSec').hidden=true;scrollTo({top:0});window.WB&&WB.show();return}+ if(t=='history'){selectTab(t);document.title='生成记录 · 衣姿 PoseWear';history.replaceState(null,'','#history');document.body.classList.remove('studio');document.body.classList.add('histview');$('#studio').hidden=true;$('#histSec').hidden=false;scrollTo({top:0});window.HIS&&HIS.show();return}+ if(document.body.classList.contains('studio')){document.body.classList.remove('studio');$('#studio').hidden=true}+ if(document.body.classList.contains('histview')){document.body.classList.remove('histview');$('#histSec').hidden=true}+ if(changed)grid.classList.add('gbusy');+ st.f=previous?.filters||{};st.q=previous?.query||'';+ $('#q').value=st.q;$('#qx').hidden=!st.q;selectTab(t);document.title=TNAME[t]+' · 衣姿 PoseWear';if(!openId)history.replaceState(null,'','#'+t);- $('#rand').hidden=t=='fav'||t=='recent';$('#favTools').hidden=t!='fav';$('#clrRec').hidden=t!='recent';$('#sort').hidden=t=='recent';$('#porNote').hidden=t!='portrait';$('#depthNote').hidden=t!='depth';$('#q').placeholder=t=='depth'?'搜姿势名、系列、分类':(innerWidth<=760?'搜索':'搜姿势、颜色、单品');$('#sort option[value=rank]').hidden=t!='portrait';if(t!='portrait'&&st.sort=='rank'){st.sort='def';$('#sort').value='def'}+ $('#rand').hidden=t=='fav'||t=='recent';$('#favTools').hidden=t!='fav';$('#clrRec').hidden=t!='recent';$('#sort').hidden=t=='recent';$('#q').placeholder=t=='depth'?'搜姿势名、系列、分类':(innerWidth<=760?'搜索':'搜姿势、颜色、单品');$('#sort option[value=rank]').hidden=t!='portrait';if(t!='portrait'&&st.sort=='rank'){st.sort='def';$('#sort').value='def'}document.body.classList.toggle('compact',t=='fav'||t=='recent');if((!DATA[t]&&!(t=='pose'&&grid.querySelector('.ssr')))||t=='fav'||t=='recent'){grid.innerHTML='<div class="skel"></div>'.repeat(10);$('#empty').hidden=true}- try{if(t=='fav')await needKeys([...st.fav]);else if(t=='recent')await needKeys(st.rec);else await load(t)}catch(e){grid.innerHTML='';$('#empty').hidden=false;$('#emptyT').textContent='数据加载失败';$('#emptyP').textContent='请检查网络后刷新页面重试';$('#sugg').innerHTML='';$('#reset').hidden=true;$('#empty .emo').innerHTML=EI.q;delete LOAD[t];grid.classList.remove('gbusy');$('#emptyGo').innerHTML='<button class="sm pri" id="retry">重新加载</button>';$('#retry').onclick=()=>{st.tab='';setTab(t)};return}- if(st.tab!=t)return;if(Q0){st.q=Q0;$('#q').value=Q0;$('#qx').hidden=false;Q0=''}const go=()=>{drawFilters();apply()};if(changed)await viewT(go);else go();grid.classList.remove('gbusy');- if(openId)openById(openId)- else if(changed&&scrollY>$('#bar').offsetTop)scrollTo({top:$('#hero').offsetHeight&&t!='fav'&&t!='recent'?$('#bar').offsetTop-60:0})}-$('.tabs').onclick=e=>{const b=e.target.closest('button');if(!b)return;const t=b.dataset.tab;if(t==st.tab&&!document.body.classList.contains('studio')){scrollTo({top:0,behavior:RM?'auto':'smooth'});return}if(location.hash!='#'+t)history.pushState(null,'','#'+t);setTab(t)};addEventListener('resize',()=>{moveInd();hdr()});-function theme(){const go=()=>{const t=document.documentElement.dataset.theme=document.documentElement.dataset.theme=='dark'?'light':'dark';SV('theme',t);localStorage.theme=t;$('meta[name=theme-color]').content=t=='dark'?'#111111':'#ffffff'};if(document.startViewTransition&&!RM){const v=document.startViewTransition(go);v.ready.catch(()=>{});v.finished.catch(()=>{})}else go()}-$('#theme').onclick=theme;$('#help').onclick=()=>$('#helpBox').hidden=false;$('#helpBox').onclick=e=>{if(e.target.id=='helpBox'||e.target.dataset.close!=null)$('#helpBox').hidden=true};+ try{if(t=='fav')await needKeys([...st.fav]);else if(t=='recent')await needKeys(st.rec);else await load(t)}catch(e){if(request!==tabRequest)return;grid.innerHTML='';$('#empty').hidden=false;$('#emptyT').textContent='数据加载失败';$('#emptyP').textContent='请检查网络后刷新页面重试';$('#sugg').innerHTML='';$('#reset').hidden=true;$('#empty .emo').innerHTML=EI.q;grid.classList.remove('gbusy');$('#emptyGo').innerHTML='<button class="sm pri" id="retry">重新加载</button>';$('#retry').onclick=()=>setTab(t,openId,workbenchId);return}+ if(request!==tabRequest)return;if(Q0){st.q=Q0;$('#q').value=Q0;$('#qx').hidden=false;Q0=''}const go=()=>{if(request===tabRequest){drawFilters();apply(previous);loadCardPairs()}};if(changed)await viewT(go);else go();if(request!==tabRequest)return;grid.classList.remove('gbusy');+ if(workbenchId!==undefined){+ const it=ITEMS[PFX[t]+workbenchId];+ if(it&&!it.a&&!st.sel.includes(it.k))toggleSel(it.k);+ openTray();+ }else if(openId)openById(openId)+ else if(previous){+ scrollTo({top:previous.scroll,behavior:'instant'});+ if(previous.cardKey)grid.querySelector('.card[data-k="'+CSS.escape(previous.cardKey)+'"] .phk')?.focus({preventScroll:true});+ }+ else if(changed&&scrollY>$('#bar').offsetTop)scrollTo({top:0})}+$('.tabs').onclick=e=>{+ const button=e.target.closest('[data-tab]');if(!button)return;+ const tab=button.dataset.tab,menu=button.closest('details');+ if(menu){menu.open=false;menu.querySelector('summary').focus({preventScroll:true})}+ if(tab===st.tab){scrollTo({top:0,behavior:motionPreference.matches?'auto':'smooth'});return}+ navigate(tab);+};+addEventListener('resize',()=>hdr());+const dialogOpeners=new WeakMap();+function openDialog(dialog,initial,opener=document.activeElement){+ dialogOpeners.set(dialog,opener);dialog.hidden=false;+ (initial||dialog.querySelector('button')).focus({preventScroll:true});+}+function closeDialog(dialog){+ dialog.hidden=true;dialogOpeners.get(dialog)?.focus({preventScroll:true});+ dialogOpeners.delete(dialog);+}+function trapTab(e,dialog) {+ const focusable=[...dialog.querySelectorAll('button:not(:disabled),a[href],input:not(:disabled),select:not(:disabled),textarea:not(:disabled),summary,[tabindex="0"]')].filter(el=>el.tabIndex>=0&&el.getClientRects().length);+ if(!focusable.length)return;+ const first=focusable[0],last=focusable[focusable.length-1],active=document.activeElement;+ if(!dialog.contains(active)||(e.shiftKey?active===first:active===last)){+ e.preventDefault();(e.shiftKey?last:first).focus();+ }+}+$('#themeMenu').addEventListener('click',event=>{+ const option=event.target.closest('[data-theme-choice]');+ if(!option)return;+ window.PoseWearTheme.select(option.dataset.themeChoice);+ $('#themeMenu').open=false;+ $('#theme').focus({preventScroll:true});+});+$('#help').onclick=()=>{const menu=$('#noticeMenu');menu.open=false;openDialog($('#helpBox'),null,menu.querySelector('summary'))};+$('#helpBox').onclick=e=>{if(e.target.id==='helpBox'||e.target.closest('[data-close]'))closeDialog($('#helpBox'))};+$('.skip').onclick=e=>{+ e.preventDefault();+ const target=$(st.tab==='studio'?'#studio':st.tab==='history'?'#histSec':'#grid');+ target.tabIndex=-1;target.focus({preventScroll:true});target.scrollIntoView({block:'start'});+};// 滚动const hdr=()=>document.documentElement.style.setProperty('--hdr',$('#top').offsetHeight+'px');new ResizeObserver(hdr).observe($('#top'));let sc=false;addEventListener('scroll',()=>{const s=scrollY>24;if(s!=sc){sc=s;document.body.classList.toggle('scrolled',s);setTimeout(hdr,420)}$('#toTop').classList.toggle('on',scrollY>900)},{passive:true});-$('#toTop').onclick=()=>scrollTo({top:0,behavior:RM?'auto':'smooth'});+$('#toTop').onclick=()=>scrollTo({top:0,behavior:motionPreference.matches?'auto':'smooth'});// 收藏导入导出 / 最近$('#exp').onclick=()=>{if(!st.fav.size)return toast('还没有收藏可导出');const items=[...st.fav].map(k=>ITEMS[k]).filter(Boolean).map(it=>({类型:TL(it),编号:it.id,名称:title(it),中文:prompt(it,'zh'),英文:prompt(it,'en'),key:it.k}));const b=new Blob([JSON.stringify({app:'衣姿 PoseWear',导出时间:new Date().toLocaleString('zh-CN'),收藏:items},null,2)],{type:'application/json'}),a=document.createElement('a');a.href=URL.createObjectURL(b);a.download='衣姿-收藏-'+new Date().toISOString().slice(0,10)+'.json';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),2000);toast('已导出 '+items.length+' 条收藏')};$('#imp').onclick=()=>$('#impF').click();$('#impF').onchange=async e=>{try{const j=JSON.parse(await e.target.files[0].text());const ks=(j.收藏||[]).map(x=>x.key).filter(k=>/^[pcradehysltf]:/.test(k));await needKeys(ks);let n=0;ks.forEach(k=>{if(ITEMS[k]&&!st.fav.has(k)){st.fav.add(k);n++}});SV('fav',[...st.fav]);counts();setTab('fav');toast('已导入 '+n+' 条收藏')}catch(err){toast('导入失败:文件格式不正确')}e.target.value=''};$('#clrRec').onclick=()=>{if(!st.rec.length)return;const old=st.rec.slice();st.rec=[];SV('rec',[]);counts();viewT(apply);toast(`已清空 ${old.length} 条记录`,()=>{st.rec=old;SV('rec',old);counts();viewT(apply)})};$('#clrFav').onclick=()=>{if(!st.fav.size)return toast('还没有收藏');const old=[...st.fav];st.fav=new Set();SV('fav',[]);counts();viewT(apply);toast(`已清空 ${old.length} 条收藏`,()=>{st.fav=new Set(old);SV('fav',old);counts();viewT(apply)})};-document.addEventListener('click',e=>{const b=e.target.closest('[data-go]');if(b){history.pushState(null,'','#'+b.dataset.go);setTab(b.dataset.go)}});-$('#introX').onclick=()=>{localStorage.introX=1;const el=$('#intro');RM?document.documentElement.classList.add('nointro'):el.animate([{opacity:1,height:el.offsetHeight+'px'},{opacity:0,height:0,paddingTop:0,paddingBottom:0,marginBottom:0}],{duration:220,easing:'cubic-bezier(.2,.7,.2,1)'}).finished.then(()=>document.documentElement.classList.add('nointro'))};-$('#annX').onclick=()=>{localStorage.annV2=1;document.documentElement.classList.add('noann')};+document.addEventListener('click',e=>{const b=e.target.closest('[data-go]');if(b)navigate(b.dataset.go)});addEventListener('offline',()=>toast('网络已断开,看过的图片还能继续浏览'));addEventListener('online',()=>toast('网络已恢复'));function addRec(k){st.rec=[k,...st.rec.filter(x=>x!=k)].slice(0,100);st.recT[k]=Date.now();const r={};st.rec.forEach(x=>st.recT[x]&&(r[x]=st.recT[x]));st.recT=r;SV('rec',st.rec);SV('recT',r);counts()}addEventListener('storage',e=>{if(!['fav','rec','recT','adult','sel'].includes(e.key))return;st.fav=new Set(LS('fav')||[]);st.rec=LS('rec')||[];st.recT=LS('recT')||{};st.sel=LS('sel')||[];if(e.key=='adult'&&st.adult!=(LS('adult')===true))ageSet(LS('adult')===true);counts();needKeys([...st.fav,...st.rec,...st.sel]).then(()=>{tray();if((st.tab=='fav'||st.tab=='recent')&&$('#lb').hidden)apply()}).catch(()=>{})});@@ -204,57 +639,126 @@ let li=0,srcCard=null;const pre=new Map();function preload(src){if(pre.has(src))function rectAnim(el,from,rev){const to=el.getBoundingClientRect();if(!from||!to.width)return el.animate([{opacity:0,transform:'scale(.94)'},{opacity:1,transform:'none'}],{duration:rev?220:380,easing:'cubic-bezier(.16,1,.3,1)',direction:rev?'reverse':'normal',fill:'both'});const dx=from.left+from.width/2-(to.left+to.width/2),dy=from.top+from.height/2-(to.top+to.height/2),s=Math.max(from.width/to.width,.08);return el.animate([{transform:`translate(${dx}px,${dy}px) scale(${s})`,opacity:.2,borderRadius:'40px'},{transform:'none',opacity:1,borderRadius:'20px'}],{duration:rev?320:520,easing:rev?'cubic-bezier(.4,0,.2,1)':'cubic-bezier(.16,1,.3,1)',direction:rev?'reverse':'normal',fill:'both'})}-let lbPushed=false;const pend=new Set();function lbOpen(i,c){if(i<0||!st.list[i])return;li=i;{const it=st.list[i],h='#'+it.type+'/'+it.id;if(location.hash!=h&&!location.hash.includes('/')){history.pushState(null,'',h);lbPushed=true}}srcCard=c||null;const lb=$('#lb');lb.hidden=false;document.body.style.overflow='hidden';lbDraw();- if(!RM){$('.lb-bg').animate([{opacity:0},{opacity:1}],{duration:300});rectAnim($('.lb-box'),c&&c.querySelector('.ph').getBoundingClientRect())}setTimeout(()=>$('.lb-x').focus({preventScroll:true}),60)}-let closing=false;function lbClose(){if($('#lb').hidden||closing)return;if(lbPushed){lbPushed=false;history.back()}const it=st.list[li],c=it&&grid.querySelector(`.card[data-k="${CSS.escape(it.k)}"]`),r=c&&c.querySelector('.ph').getBoundingClientRect();- const vis=r&&r.bottom>0&&r.top<innerHeight;const done=()=>{closing=false;$('#lb').hidden=true;document.body.style.overflow='';$('.lb-box').getAnimations().forEach(a=>a.cancel());if(location.hash.includes('/'))history.replaceState(null,'','#'+st.tab);c&&c.querySelector('.phk').focus({preventScroll:true});if(st.tab=='fav'){pend.forEach(k=>!st.fav.has(k)&&dropCard(k))}pend.clear()};- if(RM)return done();closing=true;$('.lb-bg').animate([{opacity:1},{opacity:0}],{duration:220,fill:'both'}).finished.then(a=>a.cancel());rectAnim($('.lb-box'),vis?r:null,true).finished.then(done)}-function lbDraw(){const it=st.list[li];if(!it)return;const img=$('#lbImg'),box=$('.lb-img'),src=big(it),D=it.type=='depth';addRec(it.k);- history.replaceState(null,'','#'+it.type+'/'+it.id);+// li always indexes the gallery the user entered from, even while its paired image is on screen.+let lbVariant=null,lbVisitedPair=false;+const previewItem=()=>lbVariant||st.list[li];+function drawPosePair(it,slot){+ const type=counterpartType(it);+ if(!type||!ok(it))return;+ const show=()=>{+ if(!slot.isConnected||$('#lb').hidden||closing||previewItem()!==it||!poseCounterpart(it))return;+ slot.innerHTML='<div class="seg" role="group" aria-label="姿势图类型">'++ [['pose','线稿'],['depth','深度图']].map(([kind,label])=>+ `<button data-variant="${kind}" class="${kind===it.type?'on':''}" aria-pressed="${kind===it.type}">${label}</button>`+ ).join('')+'</div>';+ };+ if(DATA[type])show();+ else load(type).then(show,()=>{});+}+let lbPushed=false;const pend=new Set();function lbOpen(i,c){if(!ok(st.list[i]))return;li=i;lbVariant=c?.dataset.show?ITEMS[c.dataset.show]:null;lbVisitedPair=!!lbVariant;{const it=previewItem(),h='#'+it.type+'/'+it.id;if(location.hash!=h&&!location.hash.includes('/')){history.pushState({galleryItem:true},'',h);lbPushed=true}}const lb=$('#lb');if(lb.hidden)srcCard=document.activeElement;lb.hidden=false;document.body.style.overflow='hidden';lbDraw();+ if(!motionPreference.matches){$('.lb-bg').animate([{opacity:0},{opacity:1}],{duration:300});rectAnim($('.lb-box'),c&&c.querySelector('.ph').getBoundingClientRect())}$('.lb-x').focus({preventScroll:true})}+let closing=false;function lbClose(navigate=false,immediate=false){if($('#lb').hidden||closing)return;+ const leaving=navigate===true,fromHistory=st.tab==='history';+ if(lbPushed){lbPushed=false;if(!leaving)history.back()}+ const it=st.list[li],c=it&&grid.querySelector(`.card[data-k="${CSS.escape(it.k)}"]`),r=c&&c.querySelector('.ph').getBoundingClientRect();+ const vis=r&&r.bottom>0&&r.top<innerHeight;const done=()=>{closing=false;lbVariant=null;$('#lb').hidden=true;document.body.style.overflow='';$('.lb-box').getAnimations().forEach(a=>a.cancel());if(!leaving&&location.hash.includes('/'))history.replaceState(null,'','#'+st.tab);+ if(!leaving&&lbVisitedPair&&(st.tab==='recent'||st.tab==='fav'&&pend.size))apply();+ else if(st.tab==='fav')pend.forEach(k=>!st.fav.has(k)&&dropCard(k));+ lbVisitedPair=false;pend.clear();+ if(fromHistory)window.HIS?.closed?.(!leaving);+ else {+ const img=$('#lbImg');delete img.dataset.src;img.removeAttribute('srcset');img.removeAttribute('src');$('#lbSide').replaceChildren();+ if(!leaving){+ const back=srcCard?.isConnected&&srcCard!==document.body?srcCard:it&&grid.querySelector(`.card[data-k="${CSS.escape(it.k)}"] .phk`);+ back?.focus({preventScroll:true});+ }+ }};+ if(motionPreference.matches||leaving||immediate)return done();closing=true;$('.lb-bg').animate([{opacity:1},{opacity:0}],{duration:220,fill:'both'}).finished.then(a=>a.cancel());rectAnim($('.lb-box'),vis?r:null,true).finished.then(done)}+function lbDraw(){const it=previewItem();if(!ok(it)||st.tab==='history')return;const img=$('#lbImg'),box=$('.lb-img'),src=big(it),D=it.type=='depth';addRec(it.k);+ history.replaceState(history.state,'','#'+it.type+'/'+it.id);box.classList.toggle('ext',!!it.ext);box.classList.remove('fail');const miss=$('#lbMiss');if(it.site)miss.href=it.site;img.referrerPolicy=it.ref||'';img.onerror=()=>{if(D&&img.dataset.src==src){box.classList.add('fail');box.classList.remove('loading')}};- if(img.dataset.src!=src){img.dataset.src=src;img.removeAttribute('srcset');img.src=thumb(it);img.classList.add('lo');box.classList.add('loading');preload(src).then(s=>{if(img.dataset.src!=src)return;if(s){img.src=s;if(it.type=='costume'||it.type=='anime'){img.sizes='(max-width:760px) 100vw, 60vw';img.srcset=`${it.m} 1080w, ${it.i} 1366w`}img.classList.remove('lo');box.classList.remove('loading');box.classList.remove('fail')}else if(D){box.classList.add('fail');box.classList.remove('loading');img.classList.remove('lo')}})}- [1,-1,2].forEach(d=>{const n=st.list[(li+d+st.list.length)%st.list.length];n&&preload(big(n))});if(it.angles)it.angles.forEach(a=>preload(a.i));+ if(img.dataset.src!=src){img.dataset.src=src;img.removeAttribute('srcset');img.src=thumb(it);img.classList.add('lo');box.classList.add('loading');preload(src).then(s=>{if(img.dataset.src!=src)return;if(s){img.src=s;if(it.type=='costume'||it.type=='anime'){img.sizes='(max-width:760px) 100vw, 60vw';img.srcset=`${it.m} 1080w, ${it.i} 1366w`}img.classList.remove('lo');box.classList.remove('loading');box.classList.remove('fail')}else{box.classList.toggle('fail',D);box.classList.remove('loading');img.classList.remove('lo')}})}+ [1,-1,2].forEach(d=>{const n=st.list[(li+d+st.list.length)%st.list.length];if(ok(n))preload(big(n))});if(it.angles)it.angles.forEach(a=>preload(a.i));const P=it.type=='pose',isF=st.fav.has(it.k),isS=st.sel.includes(it.k);img.alt=title(it);const zh=`<div class="pbox"><small>中文描述</small><p>${esc(prompt(it,'zh'))}</p><button class="sm pri" data-c="zh">复制中文</button></div>`,en=`<div class="pbox en"><small>英文提示词 · PROMPT</small><p>${esc(prompt(it,'en'))}</p><button class="sm" data-c="en">复制英文</button></div>`;const ang=!!it.angles, meta=ang?it.line+' · '+it.cat+(D?' · '+it.angles[it.ai].zh:'')+' · 编号 '+it.no:it.type=='portrait'?it.sec+' · '+it.len+' · 编号 '+it.no+(it.rk?' · 人气第 '+it.rk+' 名':''):it.cat+' · 编号 '+it.id;const jaLine=D?`<div class="jp">日文原名:${esc(it.ja)}</div><div class="jp">${esc(it.lineJa)} · ${esc(it.catJa)} · ${esc(it.angles[it.ai].ja)}</div>`:(P?`<div class="jp">日文原名:${esc(it.ja)}</div>`:'');- const srcLink=D?`<p class="creditln"><b>${esc(it.unofficial||'非官方汉化')}</b> ${esc(it.credit||'')}</p><a class="goext" href="${esc(it.site)}" target="_blank" rel="noopener">在原站查看</a>`:'';- $('#lbSide').innerHTML=`<div class="mu">${TNAME[['fav','recent'].includes(st.tab)?st.tab:it.type]} · 第 ${li+1} / ${st.list.length} 项</div><h2>${esc(title(it))}</h2><div class="mu">${esc(meta)}</div>- ${jaLine}${ang?`<div class="angsel" role="group" aria-label="拍摄角度">${it.angles.map((a,i)=>`<button class="chip ${i==it.ai?'on':''}" data-ai="${i}">${esc(a.zh)}</button>`).join('')}</div>`:''}- ${st.lang=='en'?en+zh:zh+en}${ang?'':it.type=='portrait'?`<div class="jp">日文原名:${esc(it.ja)} · CC0 1.0,AI 生成的虚构人物,请勿用于冒充真人</div>`:`<div class="jp">原始关键词:${esc(it.kw)}</div>`}- ${srcLink}- <div class="mact"><button data-x="fav" class="${isF?'on':''}" aria-label="${isF?'取消收藏':'收藏'}">${isF?'♥':'♡'}</button><button data-x="share">分享</button>${D?'':`<button data-x="try" class="pri">${P?'用作姿势参考':it.type=='portrait'?'用作人物参考':it.type=='expr'?'用作表情参考':'试穿这套'}</button>`}</div> <div class="acts"><button data-x="fav">${isF?'♥ 已收藏':'♡ 收藏'}</button><button data-x="sel" class="${isS?'':'pri'}">${isS?'✓ 已在组合中':'+ 加入组合'}</button>${D?'':`<button data-x="try">${P?'用作姿势参考':it.type=='portrait'?'用作人物参考':it.type=='expr'?'用作表情参考':'试穿这套'}</button>`}<button data-x="share">分享链接</button>${D?'':`<button data-x="dlx">下载图片</button><button data-x="cpimg">复制图片</button>${it.ext?'':`<a href="${orig(it)}" download="posewear-${it.type}-${it.id}${P?'-'+it.ai:''}.png" class="dl"><button tabindex="-1">下载原图 PNG</button></a>`}${P||it.type=='portrait'?'':`<a href="https://s.taobao.com/search?q=${encodeURIComponent([...val(it,'col').slice(0,1),...val(it,'item').slice(0,2)].join(' ')||'女装 '+it.cat)}" target="_blank" rel="noopener" class="dl"><button tabindex="-1">淘宝搜同款 ↗</button></a>`}`}</div>-<div id="lbSim"></div><p class="mu" style="margin-top:22px;line-height:2.1"><kbd>←</kbd><kbd>→</kbd>切换 ${ang?'<kbd>↑</kbd><kbd>↓</kbd>角度 ':''}<kbd>F</kbd>收藏 <kbd>A</kbd>组合 <kbd>C</kbd>复制 <kbd>S</kbd>分享</p>`;window.X&&X.lb(it)}-const share=()=>copy(location.href,'分享链接');-$('#lbSide').onclick=e=>{const it=st.list[li],t=e.target.closest('button');if(!t)return;if(t.dataset.ai){setAng(it,+t.dataset.ai);lbDraw()}if(t.dataset.c)copy(prompt(it,t.dataset.c),t.dataset.c=='en'?'英文提示词':'中文描述');if(t.dataset.x=='fav')toggleFav(it.k);if(t.dataset.x=='sel')toggleSel(it.k);if(t.dataset.x=='share')share();if(t.dataset.x=='try'){lbClose();window.WB&&WB.pick(it)}};-const step=d=>{li=(li+d+st.list.length)%st.list.length;lbDraw();if(!RM)$('#lbImg').animate([{opacity:.3,transform:`translateX(${d*30}px)`},{opacity:1,transform:'none'}],{duration:320,easing:'cubic-bezier(.16,1,.3,1)'})};+ const sourceCredit=D?`<p class="creditln">${esc(it.unofficial||'非官方汉化')} · ${esc(it.credit||'')} <a href="${esc(it.site)}" target="_blank" rel="noopener">在原站查看</a></p>`:it.type==='portrait'?'<p class="creditln">CC0 1.0,AI 生成的虚构人物,请勿用于冒充真人</p>':'';+ $('#lbSide').innerHTML=`<div class="mu">${TNAME[st.tab]} · 第 ${li+1} / ${st.list.length} 项</div><h2>${esc(title(it))}</h2><div class="mu">${esc(meta)}</div>+ ${jaLine}${P||D?'<div id="lbPair"></div>':''}${ang?`<div class="angsel" role="group" aria-label="拍摄角度">${it.angles.map((a,i)=>`<button class="chip ${i==it.ai?'on':''}" data-ai="${i}" aria-pressed="${i==it.ai}">${esc(a.zh)}</button>`).join('')}</div>`:''}+ ${st.lang=='en'?en+zh:zh+en}${ang?'':it.type=='portrait'?`<div class="jp">日文原名:${esc(it.ja)}</div>`:`<div class="jp">原始关键词:${esc(it.kw)}</div>`}+ <div class="mact"><button data-x="fav" class="${isF?'on':''}" aria-label="${isF?'取消收藏':'收藏'}">${isF?'♥':'♡'}</button><button data-x="share">分享</button>${D?'':`<button data-x="try" class="pri">${tryLabel(it)}</button>`}</div> <div class="acts"><button data-x="fav">${isF?'♥ 已收藏':'♡ 收藏'}</button><button data-x="sel" class="${isS?'':'pri'}">${isS?'✓ 已在组合中':'+ 加入组合'}</button>${D?'':`<button data-x="try">${tryLabel(it)}</button>`}<button data-x="share">分享链接</button>${D?'':`${it.ext?'':`<button data-x="dlx">下载图片</button><button data-x="cpimg">复制图片</button><a href="${orig(it)}" download="posewear-${it.type}-${it.id}${P?'-'+it.ai:''}.png" class="dl"><button tabindex="-1">下载原图 PNG</button></a>`}${P||it.type=='portrait'?'':`<a href="https://s.taobao.com/search?q=${encodeURIComponent([...val(it,'col').slice(0,1),...val(it,'item').slice(0,2)].join(' ')||'女装 '+it.cat)}" target="_blank" rel="noopener" class="dl"><button tabindex="-1">淘宝搜同款 ↗</button></a>`}`}</div>+<div id="lbSim"></div><p class="mu" style="margin-top:22px;line-height:2.1"><kbd>←</kbd><kbd>→</kbd>切换 ${ang?'<kbd>↑</kbd><kbd>↓</kbd>角度 ':''}<kbd>F</kbd>收藏 <kbd>A</kbd>组合 <kbd>C</kbd>复制 <kbd>S</kbd>分享</p>${sourceCredit}`;if(P||D)drawPosePair(it,$('#lbPair'));window.X&&X.lb(it)}+function share(){+ const it=previewItem(),url=new URL(location.href);+ if(counterpartType(it))url.hash=it.type+'/'+it.id+'/'+encodeURIComponent(it.angles[it.ai].zh);+ copy(url.href,'分享链接');+}+$('#lbSide').onclick=e=>{const it=previewItem(),t=e.target.closest('button');if(!t||!ok(it)||st.tab==='history')return;+ if(t.dataset.variant){+ const pair=poseCounterpart(it);+ if(!pair||pair.item.type!==t.dataset.variant)return;+ lbVisitedPair=true;lbVariant=pair.item;setAng(pair.item,pair.angle);lbDraw();+ $('#lbPair [aria-pressed="true"]')?.focus({preventScroll:true});return;+ }+ if(t.dataset.ai){setAng(it,+t.dataset.ai);lbDraw();$('#lbSide [data-ai="'+it.ai+'"]').focus({preventScroll:true})}if(t.dataset.c)copyBrief(prompt(it,t.dataset.c),[it],t.dataset.c,t.dataset.c=='en'?'英文提示词':'中文描述');if(t.dataset.x=='fav')toggleFav(it.k);if(t.dataset.x=='sel')toggleSel(it.k);if(t.dataset.x=='share')share();if(t.dataset.x=='try'){lbClose(!!STUDIO_SLOT[it.type]);useReference(it)}};+const step=d=>{li=(li+d+st.list.length)%st.list.length;lbVariant=null;lbDraw();if(!motionPreference.matches)$('#lbImg').animate([{opacity:.3,transform:`translateX(${d*30}px)`},{opacity:1,transform:'none'}],{duration:320,easing:'cubic-bezier(.16,1,.3,1)'})};$('.lb-bg').onclick=lbClose;$('.lb-x').onclick=lbClose;$('.prev').onclick=()=>step(-1);$('.next').onclick=()=>step(1);-addEventListener('keydown',e=>{if(e.ctrlKey||e.metaKey||e.altKey)return;const ae=document.activeElement,inp=ae&&/^(INPUT|SELECT|TEXTAREA)$/.test(ae.tagName);- if(e.key=='Escape'){if(!$('#ageBox').hidden)return $('#ageBox').hidden=true;if(!$('#privBox').hidden)return $('#privBox').hidden=true;if(!$('#helpBox').hidden)return $('#helpBox').hidden=true;if(!$('#lb').hidden)return lbClose();drawer(false);if(inp)ae.blur();return}if(inp)return;- if(e.key=='?'){$('#helpBox').hidden=!$('#helpBox').hidden;return}const k=(e.key||'').toLowerCase();- if($('#lb').hidden){if(e.key=='/'){e.preventDefault();$('#q').focus()}else if(k=='r'&&st.tab!='studio'&&!$('#rand').hidden)randPick();else if(k=='t')theme();else if(k=='l')setLang(st.lang=='zh'?'en':'zh');else if('123456789'.includes(e.key)&&TABS[e.key-1])setTab(TABS[e.key-1]);return}- const it=st.list[li];if(e.key=='ArrowLeft')step(-1);else if(e.key=='ArrowRight')step(1);+addEventListener('keydown',e=>{if(e.ctrlKey||e.metaKey||e.altKey||e.target.closest?.('.shell-menu[open]'))return;const ae=document.activeElement,inp=ae&&/^(INPUT|SELECT|TEXTAREA)$/.test(ae.tagName);+ if(!$('#cfg').hidden||!$('#pk').hidden)return;+ const modal=$('#ageBox:not([hidden]),#privBox:not([hidden]),#helpBox:not([hidden]),#tgView:not([hidden])');+ if(modal){+ if(e.key==='Escape'||(modal.id==='helpBox'&&e.key==='?')){e.preventDefault();closeDialog(modal);if(modal.id==='ageBox')ageCb=null}+ else if(e.key==='Tab')trapTab(e,modal);+ return;+ }+ if(trayOpen&&$('#lb').hidden&&$('#tray').contains(ae)&&e.key==='Escape'){+ e.preventDefault();closeTray();+ return;+ }+ if(!$('#lb').hidden&&e.key==='Tab'){trapTab(e,$('#lb'));return}+ if(e.key==='Escape'){if(!$('#lb').hidden)return lbClose();drawer(false);if(inp)ae.blur();return}if(inp)return;+ if(e.key==='?'){openDialog($('#helpBox'));return}const k=(e.key||'').toLowerCase();+ if($('#lb').hidden){if(e.key==='/'&&FDEF[st.tab]){e.preventDefault();$('#q').focus()}else if(k==='r'&&FDEF[st.tab]&&!$('#rand').hidden)randPick();else if(k==='t')window.PoseWearTheme.toggle();else if(k==='l')setLang(st.lang==='zh'?'en':'zh');else if('123456789'.includes(e.key)&&TABS[e.key-1])navigate(TABS[e.key-1]);return}+ if(st.tab==='history')return;+ const it=previewItem();if(!ok(it))return;if(e.key=='ArrowLeft')step(-1);else if(e.key=='ArrowRight')step(1);else if(/Arrow(Up|Down)/.test(e.key)&&it.angles){e.preventDefault();setAng(it,(it.ai+(e.key=='ArrowUp'?-1:1)+it.angles.length)%it.angles.length);lbDraw()}- else if(k=='f')toggleFav(it.k);else if(k=='a')toggleSel(it.k);else if(k=='c')copy(prompt(it,'zh'),'中文描述');else if(k=='s')share();- else if(e.key=='Tab'){const f=[...$('#lb').querySelectorAll('button,a[href]')].filter(x=>x.offsetParent);if(!f.length)return;const a=f[0],z=f[f.length-1];if(e.shiftKey&&ae==a){e.preventDefault();z.focus()}else if(!e.shiftKey&&ae==z){e.preventDefault();a.focus()}}});-let tx,ty;$('.lb-img').addEventListener('touchstart',e=>{tx=e.touches[0].clientX;ty=e.touches[0].clientY},{passive:true});$('.lb-img').addEventListener('touchend',e=>{const d=e.changedTouches[0].clientX-tx,dy=e.changedTouches[0].clientY-ty;if(Math.abs(d)>50&&Math.abs(d)>Math.abs(dy))step(d<0?1:-1);else if(dy>90)lbClose()});+ else if(k=='f')toggleFav(it.k);else if(k=='a')toggleSel(it.k);else if(k=='c')copyBrief(prompt(it,'zh'),[it],'zh','中文描述');else if(k=='s')share();+});+let tx,ty;$('.lb-img').addEventListener('touchstart',e=>{tx=e.touches[0].clientX;ty=e.touches[0].clientY},{passive:true});$('.lb-img').addEventListener('touchend',e=>{const d=e.changedTouches[0].clientX-tx,dy=e.changedTouches[0].clientY-ty;if(Math.abs(d)>50&&Math.abs(d)>Math.abs(dy))(d<0?$('.next'):$('.prev')).click();else if(dy>90)lbClose()});// 数字滚动-function countUp(){$$('.stats b').forEach(b=>{const n=+(st.adult&&b.dataset.na||b.dataset.n);if(RM||b.textContent.trim()!='0'){b.textContent=n.toLocaleString('zh-CN');return}const t0=performance.now();const f=t=>{const p=Math.min((t-t0)/1400,1);b.textContent=Math.round(n*(1-Math.pow(1-p,4))).toLocaleString('zh-CN');p<1&&requestAnimationFrame(f)};requestAnimationFrame(f)})}// 路由-function openById(id){let i=st.list.findIndex(x=>x.id==id);if(i>=0)return lbOpen(i);const it=(DATA[st.tab]||[]).find(x=>x.id==id);if(!it)return toast('未找到该条目');- if(!ok(it))return ageAsk(()=>openById(id));st.f={};st.q='';$('#q').value='';drawFilters();apply();i=st.list.findIndex(x=>x.id==id);if(i>=0)lbOpen(i)}-function route(){const [t,id]=location.hash.slice(1).split('/');const tab=TABS.includes(t)?t:'pose';if(!id&&tab==st.tab&&st.list.length)return;if(tab!=st.tab||!st.list.length||!id)setTab(tab,id&&decodeURIComponent(id));else openById(decodeURIComponent(id))}+function openById(id){+ const it=st.list.find(x=>x.id===id)||(DATA[st.tab]||[]).find(x=>x.id===id);+ if(!it)return toast('未找到该条目');+ if(!ok(it))return ageAsk(()=>openById(id));+ const sharedAngle=location.hash.split('/')[2];+ if(sharedAngle&&counterpartType(it)){+ const angle=it.angles.findIndex(a=>encodeURIComponent(a.zh)===sharedAngle);+ if(angle>=0)setAng(it,angle);+ }+ if(!st.list.includes(it)){st.f={};st.q='';$('#q').value='';drawFilters();apply()}+ lbOpen(st.list.indexOf(it));+}+function route(){const [t,id,ref]=location.hash.slice(1).split('/');+ if(t==='workbench')return setTab(Object.hasOwn(PFX,id)?id:'pose',null,ref||'');+ const tab=TABS.includes(t)?t:'pose';if(!id&&tab==st.tab&&st.list.length)return;if(tab!=st.tab||!st.list.length||!id)setTab(tab,id&&decodeURIComponent(id));else openById(decodeURIComponent(id))}// 成人内容开关-function ageSet(on,anim){st.adult=on;SV('adult',on);if(on)SV('ageOk',true);document.body.classList.toggle('adult',on);$('#adultSw').setAttribute('aria-checked',on);$('#adultSw').title=on?'成人向内容已显示,点击关闭':'成人向内容已隐藏,点击打开';counts();countUp();if(st.tab&&st.tab!='studio'&&st.tab!=''){const f=()=>{drawFilters();apply()};anim?viewT(f):f()}window.WB&&WB.show&&st.tab=='studio'&&WB.show()}-let ageCb=null;function ageAsk(cb){ageCb=cb||null;const seen=LS('ageOk');$('#ageT').textContent=cb?'这是成人向内容':'显示成人向内容?';$('#ageP').textContent=(cb?'要查看它,需要打开顶部的「18+」开关。':'包括双人互动、性感类姿势、深度姿势里的双人图,以及内衣、性感类服装。')+(seen?'打开后随时可以再关上。':'仅适合已满 18 岁的用户。只需确认一次,之后用顶部开关随时打开或关闭。');$('#ageY').textContent=seen?'打开 18+ 开关':'我已满 18 岁,打开';$('#ageBox').hidden=false;setTimeout(()=>$('#ageY').focus(),30)}+function ageSet(on,anim){st.adult=on;SV('adult',on);if(on)SV('ageOk',true);document.body.classList.toggle('adult',on);$('#adultSw').setAttribute('aria-checked',on);$('#adultSw').title=on?'成人向内容已显示,点击关闭':'成人向内容已隐藏,点击打开';counts();+ const origin=!$('#lb').hidden&&st.tab!=='history'&&st.list[li];+ if(origin&&(!ok(origin)||!ok(previewItem())))lbClose(false,true);+ if(FDEF[st.tab]){const f=()=>{if(FDEF[st.tab]){drawFilters();apply();tray();+ if(origin&&!$('#lb').hidden&&!closing){li=st.list.indexOf(origin);if(li<0)lbClose(false,true);else lbDraw()}+ }};anim?viewT(f):f()}window.WB&&WB.show&&st.tab=='studio'&&WB.show()}+let ageCb=null;function ageAsk(cb){ageCb=cb||null;const seen=LS('ageOk');$('#ageT').textContent=cb?'这是成人向内容':'显示成人向内容?';$('#ageP').textContent=(cb?'要查看它,需要打开顶部的「18+」开关。':'包括双人互动、性感类姿势、深度姿势里的双人图,以及内衣、性感类服装。')+(seen?'打开后随时可以再关上。':'仅适合已满 18 岁的用户。只需确认一次,之后用顶部开关随时打开或关闭。');$('#ageY').textContent=seen?'打开 18+ 开关':'我已满 18 岁,打开';openDialog($('#ageBox'),$('#ageY'))}$('#adultSw').onclick=()=>{if(st.adult){ageSet(false,1);toast('已关闭成人向内容')}else if(LS('ageOk')){ageSet(true,1);toast('已显示成人向内容')}else ageAsk()};-$('#ageY').onclick=()=>{$('#ageBox').hidden=true;ageSet(true,!ageCb);toast('已显示成人向内容,可用顶部开关关闭');const c=ageCb;ageCb=null;c&&c()};-$('#ageN').onclick=$('#ageBox').onclick=e=>{if(e.target.id!='ageN'&&e.target.id!='ageBox')return;$('#ageBox').hidden=true;ageCb=null};+$('#ageY').onclick=()=>{closeDialog($('#ageBox'));ageSet(true,!ageCb);toast('已显示成人向内容,可用顶部开关关闭');const c=ageCb;ageCb=null;c&&c()};+$('#ageN').onclick=$('#ageBox').onclick=e=>{if(e.target.id!='ageN'&&e.target.id!='ageBox')return;closeDialog($('#ageBox'));ageCb=null};document.addEventListener('click',e=>{const b=e.target.closest('[data-age]');if(!b)return;st.adult?(ageSet(false),toast('已隐藏成人内容')):ageAsk()});-$('#privO').onclick=e=>{e.preventDefault();$('#privBox').hidden=false};$('#privBox').onclick=e=>{if(e.target.id=='privBox'||e.target.dataset.close!=null)$('#privBox').hidden=true};+$('#privO').onclick=e=>{e.preventDefault();openDialog($('#privBox'))};$('#privBox').onclick=e=>{if(e.target.id=='privBox'||e.target.closest('[data-close]'))closeDialog($('#privBox'))};addEventListener('hashchange',()=>{const id=location.hash.split('/')[1];if(!$('#lb').hidden){if(id)return;lbPushed=false;lbClose();setTimeout(route,closing?280:0);return}route()});-if(innerWidth<=760)$('#q').placeholder='搜索';setLang(st.lang,true);ageSet(st.adult);hdr();countUp();needKeys([...st.sel]).then(()=>tray()).catch(()=>{});st.tab='';if(Q0&&!location.hash)history.replaceState(null,'','?q='+encodeURIComponent(Q0)+'#'+(TABS.includes(QT)?QT:'costume'));route();+if(innerWidth<=760)$('#q').placeholder='搜索';setLang(st.lang,true);ageSet(st.adult);hdr();needKeys([...st.sel]).then(()=>tray()).catch(()=>{});st.tab='';if(Q0&&!location.hash)history.replaceState(null,'','?q='+encodeURIComponent(Q0)+'#'+(TABS.includes(QT)?QT:'costume'));route();if('serviceWorker'in navigator&&location.protocol!='file:')addEventListener('load',()=>navigator.serviceWorker.register('/sw.js').catch(()=>{}));-window.APP={ok,ageAsk,toggleFav,toggleSel,lbOpen,lbClose,apply,li:()=>li,load,ITEMS,DATA,thumb,big,ath,title,prompt,toast,esc,setTab,st,copy};+window.APP={ok,counterpartType,poseCounterpart,cardFace,studioSlot,suggestions:SUGG,sendToStudio,ageAsk,toggleFav,toggleSel,lbOpen,lbClose,previewItem,apply,li:()=>li,load,ITEMS,DATA,thumb,big,ath,title,prompt,toast,esc,setTab:navigate,st,copy,copyBrief,needKeys};diff --git a/src/extras.js b/src/extras.jsindex 8272edc..9791f84 100644--- a/src/extras.js+++ b/src/extras.js@@ -1,59 +1,69 @@// 衣姿 v8:动效与小功能-(()=>{const A=window.APP,$=s=>document.querySelector(s),$$=s=>document.querySelectorAll(s),RM=matchMedia('(prefers-reduced-motion: reduce)').matches,EZ='cubic-bezier(.16,1,.3,1)',grid=$('#grid');+(()=>{const A=window.APP,$=s=>document.querySelector(s),$$=s=>document.querySelectorAll(s),motionPreference = matchMedia('(prefers-reduced-motion: reduce)'),EZ='cubic-bezier(.16,1,.3,1)',grid=$('#grid');const LS=k=>{try{return JSON.parse(localStorage[k]||'null')}catch(e){return null}},SV=(k,v)=>{try{localStorage[k]=JSON.stringify(v)}catch(e){}};const dl=(blob,name)=>{const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(a.href),3000)};const X=window.X={dl};// —— 爱心 pop + 粒子-function burst(el){if(RM||!el)return;const r=el.getBoundingClientRect(),cx=r.left+r.width/2,cy=r.top+r.height/2;for(let i=0;i<8;i++){const p=document.createElement('i');p.className='pt';p.style.cssText=`left:${cx}px;top:${cy}px;background:${i%2?'#ff2442':'#ff8fa3'}`;document.body.append(p);const a=i/8*Math.PI*2,d=18+Math.random()*10;p.animate([{transform:'translate(-50%,-50%) scale(1)',opacity:1},{transform:`translate(calc(-50% + ${Math.cos(a)*d}px),calc(-50% + ${Math.sin(a)*d}px)) scale(.2)`,opacity:0}],{duration:520,easing:EZ}).finished.then(()=>p.remove())}}-function pop(el){if(!RM&&el)el.animate([{transform:'scale(1)'},{transform:'scale(1.32)'},{transform:'scale(.92)'},{transform:'scale(1)'}],{duration:460,easing:EZ})}-function fly(img,target){if(RM||!img||!target)return;const a=img.getBoundingClientRect(),b=target.getBoundingClientRect();if(!a.width)return;const c=img.cloneNode();c.className='flyimg';c.style.cssText=`left:${a.left}px;top:${a.top}px;width:${a.width}px;height:${a.height}px`;document.body.append(c);+function burst(el){if(motionPreference.matches||!el)return;const r=el.getBoundingClientRect(),cx=r.left+r.width/2,cy=r.top+r.height/2;for(let i=0;i<8;i++){const p=document.createElement('i');p.className='pt';p.style.cssText=`left:${cx}px;top:${cy}px;background:${i%2?'#ff2442':'#ff8fa3'}`;document.body.append(p);const a=i/8*Math.PI*2,d=18+Math.random()*10;p.animate([{transform:'translate(-50%,-50%) scale(1)',opacity:1},{transform:`translate(calc(-50% + ${Math.cos(a)*d}px),calc(-50% + ${Math.sin(a)*d}px)) scale(.2)`,opacity:0}],{duration:520,easing:EZ}).finished.then(()=>p.remove())}}+function pop(el){if(!motionPreference.matches&&el)el.animate([{transform:'scale(1)'},{transform:'scale(1.32)'},{transform:'scale(.92)'},{transform:'scale(1)'}],{duration:460,easing:EZ})}+function fly(img,target){if(motionPreference.matches||!img||!target)return;const a=img.getBoundingClientRect(),b=target.getBoundingClientRect();if(!a.width)return;const c=img.cloneNode();c.className='flyimg';c.style.cssText=`left:${a.left}px;top:${a.top}px;width:${a.width}px;height:${a.height}px`;document.body.append(c);const dx=b.left+b.width/2-(a.left+a.width/2),dy=b.top+b.height/2-(a.top+a.height/2);c.animate([{transform:'none',opacity:1,borderRadius:'14px'},{transform:`translate(${dx*.6}px,${dy*.6-40}px) scale(.35)`,opacity:.9,offset:.6},{transform:`translate(${dx}px,${dy}px) scale(.06)`,opacity:.2,borderRadius:'50%'}],{duration:640,easing:'cubic-bezier(.5,0,.2,1)'}).finished.then(()=>{c.remove();pop(target)})}X.fly=fly;X.pop=pop;-const favTab=()=>$('.tabs button[data-tab=fav]'),stuTab=()=>$('.tabs button[data-tab=studio]');+const favTab=()=>$('#personalMenu summary');grid.addEventListener('click',e=>{const b=e.target.closest('[data-a]');const card=e.target.closest('.card');if(!card)return;- if(document.body.classList.contains('batch')){e.preventDefault();e.stopPropagation();card.classList.toggle('picked');pick(card.dataset.k);return}- if(b&&b.dataset.a=='fav'){const k=card.dataset.k,on=!A.st.fav.has(k),img=card.querySelector('img');requestAnimationFrame(()=>{const nb=grid.querySelector(`.card[data-k="${CSS.escape(k)}"] [data-a=fav]`);if(on){pop(nb);burst(nb);fly(img,favTab())}})}- if(b&&b.dataset.a=='sel'){const k=card.dataset.k;if(!A.st.sel.includes(k))fly(card.querySelector('img'),$('#tray:not([hidden])')||stuTab())}},true);+ const key=card.dataset.show||card.dataset.k;+ if(document.body.classList.contains('batch')){e.preventDefault();e.stopPropagation();pick(key);grid.querySelectorAll('.card').forEach(c=>c.classList.toggle('picked',B.has(c.dataset.show||c.dataset.k)));return}+ if(b&&b.dataset.a=='fav'){const on=!A.st.fav.has(key),img=card.querySelector('img');requestAnimationFrame(()=>{const nb=grid.querySelector(`.card[data-k="${CSS.escape(card.dataset.k)}"] [data-a=fav]`);if(on){pop(nb);burst(nb);fly(img,favTab())}})}+ if(b&&b.dataset.a=='sel'&&!$('#trayFab').hidden&&!A.st.sel.includes(key))fly(card.querySelector('img'),$('#trayFab'))},true);// —— 批量模式-const B=new Set();function pick(k){B.has(k)?B.delete(k):B.add(k);bbar()}+const B=new Set();+X.batchPicked=k=>B.has(k);+X.filterBatch=items=>{if(!B.size)return;const keys=new Set(items.map(it=>it.k));for(const k of B)if(!keys.has(k))B.delete(k);bbar()};+function pick(k){B.has(k)?B.delete(k):B.add(k);bbar()}const tb=$('.tbar'),bt=document.createElement('button');bt.className='fbtn';bt.id='batchBtn';bt.innerHTML='<svg viewBox="0 0 24 24"><rect x="4" y="4" width="7" height="7" rx="2"/><rect x="13" y="4" width="7" height="7" rx="2"/><rect x="4" y="13" width="7" height="7" rx="2"/><path d="m14 16.5 2 2 4-4"/></svg>批量';tb.querySelector('.sp').after(bt);const bb=document.createElement('div');bb.id='bbar';bb.hidden=true;bb.innerHTML='<b id="bbN">已选 0</b><button data-b="all">全选</button><button data-b="fav">收藏</button><button data-b="unfav">取消收藏</button><button data-b="zip">打包下载</button><button data-b="stu">去试穿</button><button data-b="cp">复制</button><button data-b="x" class="pri">完成</button>';document.body.append(bb);-function batch(on){document.body.classList.toggle('batch',on);bb.querySelector('[data-b=fav]').hidden=A.st.tab=='fav';bb.querySelector('[data-b=unfav]').hidden=A.st.tab!='fav';bb.hidden=!on;bt.classList.toggle('on',on);if(!on){B.clear();$$('.card.picked').forEach(c=>c.classList.remove('picked'))}bbar()}+function batch(on){document.body.classList.toggle('batch',on);bb.querySelector('[data-b=fav]').hidden=A.st.tab=='fav';bb.querySelector('[data-b=unfav]').hidden=A.st.tab!='fav';bb.hidden=!on;bt.classList.toggle('on',on);bt.setAttribute('aria-pressed',String(on));if(!on){B.clear();$$('.card.picked').forEach(c=>c.classList.remove('picked'))}bbar()}function bbar(){$('#bbN').textContent='已选 '+B.size;bb.querySelectorAll('[data-b]:not([data-b=x]):not([data-b=all])').forEach(b=>b.disabled=!B.size)}bt.onclick=()=>batch(!document.body.classList.contains('batch'));bb.onclick=async e=>{const t=e.target.closest('[data-b]');if(!t)return;const its=[...B].map(k=>A.ITEMS[k]).filter(Boolean),m=t.dataset.b;- if(m=='x')return batch(false);if(m=='all'){$$('#grid .card').forEach(c=>{c.classList.add('picked');B.add(c.dataset.k)});return bbar()}+ if(m=='x')return batch(false);if(m=='all'){A.st.list.forEach(it=>B.add(A.cardFace(it).k));$$('#grid .card').forEach(c=>c.classList.add('picked'));return bbar()}if(m=='fav'){let n=0;its.forEach(it=>{if(!A.st.fav.has(it.k)){A.st.fav.add(it.k);n++}});SV('fav',[...A.st.fav]);$('#nFav').textContent=A.st.fav.size;pop(favTab());A.toast(`已收藏 ${n} 项`);batch(false);A.apply()}if(m=='unfav'){its.forEach(it=>A.st.fav.delete(it.k));SV('fav',[...A.st.fav]);const n=its.length,ks=its.map(i=>i.k);batch(false);A.apply();$('#nFav').textContent=A.st.fav.size||'';A.toast(`已取消 ${n} 项收藏`,()=>{ks.forEach(k=>A.st.fav.add(k));SV('fav',[...A.st.fav]);$('#nFav').textContent=A.st.fav.size;A.apply()})}- if(m=='zip'){const local=its.filter(it=>!it.ext);if(!local.length)return A.toast(its.length?'这些图片在原站,请前往原站查看':'先选几张');if(!window.makeZip)return;t.disabled=true;t.textContent='打包中…';try{const fs=[];for(const it of local.slice(0,60)){const u=A.big(it);const r=await fetch(u);if(r.ok)fs.push({name:`posewear-${it.type}-${it.id}.webp`,blob:await r.blob()})}window.X.dl(await makeZip(fs),`posewear-${A.st.tab}-${fs.length}.zip`);A.toast(`已打包 ${fs.length} 张`+(local.length>60?'(单次最多 60 张)':'')+(local.length<its.length?',深度姿势请到原站查看':''))}catch(err){A.toast('打包失败,请重试')}t.disabled=false;t.textContent='打包下载'}- if(m=='cp'){A.copy(its.map(it=>A.prompt(it,A.st.lang=='en'?'en':'zh')).join('\n'),`${its.length} 条提示词`)}- if(m=='stu'){const p=its.filter(i=>i.type=='pose'),c=its.filter(i=>i.type=='costume'||i.type=='anime'),r=its.filter(i=>i.type=='portrait');batch(false);for(const it of [...r.slice(0,3),...c.slice(0,1),...p.slice(0,6)])await window.WB.pick(it);if(!its.length)A.setTab('studio')}};+ if(m=='zip'){const local=its.filter(it=>!it.ext);if(!local.length)return A.toast(its.length?'这些图片在原站,请前往原站查看':'先选几张');if(!window.makeZip)return;t.disabled=true;t.textContent='打包中…';try{const fs=[];for(const it of local.slice(0,60)){const u=A.big(it);const r=await fetch(u);if(!r.ok)throw Error(r.status);fs.push({name:`posewear-${it.type}-${it.id}.webp`,blob:await r.blob()})}window.X.dl(await makeZip(fs),`posewear-${A.st.tab}-${fs.length}.zip`);A.toast(`已打包 ${fs.length} 张`+(local.length>60?'(单次最多 60 张)':'')+(local.length<its.length?',外链图片请到原站查看':''))}catch(err){A.toast('打包失败,请重试')}t.disabled=false;t.textContent='打包下载'}+ if(m=='cp'){A.copyBrief(its.map(it=>A.prompt(it,A.st.lang)).join('\n'),its,A.st.lang,`${its.length} 条提示词`)}+ if(m=='stu'){+ if(await A.sendToStudio(its,true))batch(false);+ }};addEventListener('keydown',e=>{if(e.key=='Escape'&&document.body.classList.contains('batch'))batch(false)});-const _st=A.setTab;A.setTab=(...a)=>{if(document.body.classList.contains('batch'))batch(false);return _st(...a)};-$('.tabs').addEventListener('click',()=>document.body.classList.contains('batch')&&batch(false),true);-// —— 搜索建议-const HOT={pose:['站姿','坐姿','回头','可爱','躺卧','跪立','俯拍','蹲姿'],depth:['站姿','坐姿','上半身','全身','俯拍','侧面','可爱','跪立'],costume:['连衣裙','黑色','泳装','针织','蕾丝','冬季','牛仔','高跟鞋'],anime:['连衣裙','黑色','泳装','针织','蕾丝','冬季','牛仔','制服'],portrait:['短发','波波','狼尾','刘海','卷','奶茶色','黑发','生活照']};+X.closeBatch=()=>{if(document.body.classList.contains('batch'))batch(false)};+ // —— 搜索建议const q=$('#q'),sg=document.createElement('div');sg.id='qsug';sg.hidden=true;q.parentNode.append(sg);-function sgDraw(){const h=LS('qh')||[],v=q.value.trim(),tab=['costume','anime','portrait','depth'].includes(A.st.tab)?A.st.tab:'pose',hot=(HOT[tab]||[]).filter(x=>!v||x.includes(v));+function sgDraw(){const h=LS('qh')||[],v=q.value.trim(),hot=(A.suggestions[A.st.tab]||[]).filter(x=>!v||x.includes(v));sg.innerHTML=(h.length&&!v?`<div class="sgh"><small>最近搜索</small><button data-clr>清除</button></div><div class="sgc">${h.map(x=>`<button data-q="${A.esc(x)}">${A.esc(x)}</button>`).join('')}</div>`:'')+(hot.length?`<div class="sgh"><small>热门</small></div><div class="sgc">${hot.map((x,i)=>`<button data-q="${x}"><em>${i+1}</em>${x}</button>`).join('')}</div>`:'');sg.hidden=!sg.innerHTML}const saveQ=()=>{const v=q.value.trim();if(v.length<1)return;SV('qh',[v,...(LS('qh')||[]).filter(x=>x!=v)].slice(0,8))};q.addEventListener('focus',sgDraw);q.addEventListener('input',()=>{sgDraw();clearTimeout(q._h);q._h=setTimeout(saveQ,1500)});q.addEventListener('keydown',e=>{if(e.key=='Enter'){saveQ();sg.hidden=true;q.blur()}});-q.addEventListener('blur',()=>setTimeout(()=>{sg.hidden=true},150));-sg.addEventListener('mousedown',e=>e.preventDefault());sg.onclick=e=>{const b=e.target.closest('button');if(!b)return;if(b.dataset.clr!=null){SV('qh',[]);return sgDraw()}if(!['pose','costume','anime','portrait','depth'].includes(A.st.tab)&&b.dataset.q)A.setTab('pose');q.value=b.dataset.q;q.dispatchEvent(new Event('input'));saveQ();sg.hidden=true;q.blur()};+q.parentNode.addEventListener('focusout',e=>{if(!q.parentNode.contains(e.relatedTarget))sg.hidden=true});+q.parentNode.addEventListener('keydown',e=>{+ if(e.key==='Escape'&&!sg.hidden){e.stopPropagation();q.focus();sg.hidden=true}+});+sg.addEventListener('mousedown',e=>e.preventDefault());sg.onclick=e=>{const b=e.target.closest('button');if(!b)return;if(b.dataset.clr!=null){SV('qh',[]);return sgDraw()}q.focus();q.value=b.dataset.q;q.dispatchEvent(new Event('input'));saveQ();sg.hidden=true};// —— 计数动画-const cnt=$('#count');new MutationObserver(()=>{if(!RM)cnt.animate([{opacity:.2,transform:'translateY(4px)'},{opacity:1,transform:'none'}],{duration:360,easing:EZ})}).observe(cnt,{childList:true,characterData:true,subtree:true});+const cnt=$('#count');new MutationObserver(()=>{if(!motionPreference.matches)cnt.animate([{opacity:.2,transform:'translateY(4px)'},{opacity:1,transform:'none'}],{duration:360,easing:EZ})}).observe(cnt,{childList:true,characterData:true,subtree:true});// —— 大图:相似推荐 / 下载 / 复制图片X.lb=it=>{const L=A.st.list,cols=new Set((it.zh||'').match(/[黑白红粉蓝灰绿黄紫金银棕米]/g)||[]);const sc=x=>it.type=='portrait'?(x.len==it.len?2:0)+(x.st&&x.st==it.st?4:0)+(x.sec==it.sec?1:0):(x.cat==it.cat?3:0)+(x.line&&x.line==it.line?1:0)+((x.zh||'').match(/[黑白红粉蓝灰绿黄紫金银棕米]/g)||[]).filter(c=>cols.has(c)).length;const s=L.map((x,i)=>[x,i]).filter(([x])=>x.k!=it.k&&x.type==it.type).map(([x,i])=>[x,i,sc(x)+Math.random()*.5]).sort((a,b)=>b[2]-a[2]).slice(0,8);const el=$('#lbSim');if(!el)return;el.innerHTML=s.length?`<small class="simh">相似推荐</small><div class="sim">${s.map(([x,i])=>`<button data-si="${i}" title="${A.esc(A.title(x))}"><img src="${A.esc(A.thumb(x))}" alt="${A.esc(A.title(x))}" loading="lazy"${x.ref?` referrerpolicy="${A.esc(x.ref)}"`:''}></button>`).join('')}</div>`:''};-async function curBlob(){const it=A.st.list[A.li()];const r=await fetch(A.big(it));return[await r.blob(),it]}+async function curBlob(){const it=A.previewItem();const r=await fetch(A.big(it));if(!r.ok)throw Error(r.status);return[await r.blob(),it]}$('#lbSide').addEventListener('click',async e=>{const b=e.target.closest('button');if(!b)return;- if(b.dataset.si){const i=+b.dataset.si;A.lbOpen(i);if(!RM)$('#lbImg').animate([{opacity:0,transform:'scale(.97)'},{opacity:1,transform:'none'}],{duration:340,easing:EZ});return}+ if(b.dataset.si){const i=+b.dataset.si;A.lbOpen(i);if(!motionPreference.matches)$('#lbImg').animate([{opacity:0,transform:'scale(.97)'},{opacity:1,transform:'none'}],{duration:340,easing:EZ});return}if(b.dataset.x=='dlx'){try{const[bl,it]=await curBlob();dl(bl,`posewear-${it.type}-${it.id}.webp`);A.toast('已开始下载')}catch(err){A.toast('下载失败')}}if(b.dataset.x=='cpimg'){try{const[bl]=await curBlob();const im=await createImageBitmap(bl),c=document.createElement('canvas');c.width=im.width;c.height=im.height;c.getContext('2d').drawImage(im,0,0);const png=await new Promise(r=>c.toBlob(r,'image/png'));await navigator.clipboard.write([new ClipboardItem({'image/png':png})]);A.toast('图片已复制到剪贴板')}catch(err){A.toast('当前浏览器不支持复制图片')}}});// —— 随机:洗牌动画-const rb=$('#rand');if(rb)rb.addEventListener('click',()=>{if(RM)return;const cs=[...$$('#grid .card')].filter(c=>{const r=c.getBoundingClientRect();return r.top<innerHeight&&r.bottom>0}).slice(0,12);cs.forEach((c,i)=>c.animate([{transform:'none'},{transform:`translateY(-6px) rotate(${(i%2?1:-1)*1.2}deg)`},{transform:'none'}],{duration:420,delay:i*22,easing:EZ}))},true);+const rb=$('#rand');if(rb)rb.addEventListener('click',()=>{if(motionPreference.matches)return;const cs=[...$$('#grid .card')].filter(c=>{const r=c.getBoundingClientRect();return r.top<innerHeight&&r.bottom>0}).slice(0,12);cs.forEach((c,i)=>c.animate([{transform:'none'},{transform:`translateY(-6px) rotate(${(i%2?1:-1)*1.2}deg)`},{transform:'none'}],{duration:420,delay:i*22,easing:EZ}))},true);// —— 收藏/最近为空的 CTA// —— PWA 更新提示-if('serviceWorker'in navigator&&navigator.serviceWorker.controller){navigator.serviceWorker.addEventListener('controllerchange',()=>{const u=document.createElement('button');u.id='upd';u.innerHTML='<b>●</b> 有新版本,点击刷新';u.onclick=()=>location.reload();document.body.append(u)})}+if('serviceWorker'in navigator&&navigator.serviceWorker.controller){+ navigator.serviceWorker.addEventListener('controllerchange',()=>{$('#noticeReload').hidden=false});+ $('#noticeReload').onclick=()=>location.reload();+}})();diff --git a/src/history.js b/src/history.jsindex 2d7709d..4df3b11 100644--- a/src/history.js+++ b/src/history.js@@ -3,16 +3,18 @@const A = window.APP;if (!A) return;const $ = s => document.querySelector(s), $$ = s => document.querySelectorAll(s), esc = A.esc, toast = A.toast;- const RM = matchMedia('(prefers-reduced-motion: reduce)').matches;+ const motionPreference = matchMedia('(prefers-reduced-motion: reduce)');const p2 = n => String(n).padStart(2, '0');const stamp = d => `${d.getFullYear()}${p2(d.getMonth() + 1)}${p2(d.getDate())}-${p2(d.getHours())}${p2(d.getMinutes())}`;const PROV_NAME = { openai: 'OpenAI', gemini: 'Gemini', seedream: '豆包', custom: '自定义' };+ const providerName = r => (r.prov === 'local' && r.model) || PROV_NAME[r.prov] || r.prov || 'AI';let L = [];const sel = new Set();let curIndex = -1;let blobUrls = [];let lbUrls = [];+ let opener = null;const U = b => {if (!b) return '';@@ -20,6 +22,10 @@blobUrls.push(u);return u;};+ function copyRecord(r,text){+ if(r.inputs)return window.WB.copyStudioBrief(text,r.inputs,r.inputs.lang||'zh');+ return A.copy(text,'提示词');+ }const cleanupUrls = () => {blobUrls.forEach(u => URL.revokeObjectURL(u));blobUrls = [];@@ -49,12 +55,8 @@};const getRecords = async () => {- try {- const all = await tx('readonly', s => s.getAll());- return (all || []).sort((a, b) => b.t - a.t);- } catch (e) {- return [];- }+ const all = await tx('readonly', s => s.getAll());+ return all.sort((a, b) => b.t - a.t);};const delRecord = async t => {@@ -122,14 +124,17 @@return;}const tryon = L.filter(r => r.mode != 'gen').length;- const gen = L.filter(r => r.mode == 'gen').length;+ const gen = L.length - tryon;const provCount = {};L.forEach(r => {- const p = PROV_NAME[r.prov] || r.prov || '其他';+ const p = providerName(r);provCount[p] = (provCount[p] || 0) + 1;});const provStr = Object.entries(provCount).map(([k, v]) => `${esc(k)} ${v}`).join(' / ');- el.innerHTML = `共 <b>${L.length}</b> 张 · 试穿 <b>${tryon}</b> / 生图 <b>${gen}</b>${provStr ? ' · ' + provStr : ''}`;+ el.innerHTML = `<span class="hist-ratio" aria-hidden="true"><i style="width:${100*tryon/L.length}%"></i></span>+ <span class="hist-key"><i></i><span>试穿</span> <b>${tryon}</b></span>+ <span class="hist-key gen"><i></i><span>生图</span> <b>${gen}</b></span>+ <span class="hist-providers">${provStr}</span>`;}function renderGrid() {@@ -158,13 +163,14 @@const isSel = sel.has(r.t);const d = new Date(r.t);const timeStr = `${d.getMonth() + 1}/${d.getDate()} ${p2(d.getHours())}:${p2(d.getMinutes())}`;- const prov = PROV_NAME[r.prov] || r.prov || 'AI';+ const prov = providerName(r);const label = r.label || (r.prompt ? r.prompt.slice(0, 40) : (r.mode == 'gen' ? '自由生图' : '虚拟试穿'));- const sub = `${timeStr} · ${prov} · ${r.model || ''}`;+ const sub = [timeStr, prov, r.model !== prov && r.model].filter(Boolean).join(' · ');return `<article class="hist-card${isSel ? ' selected' : ''}" data-t="${r.t}" data-i="${i}">- <div class="hph" role="button" tabindex="0" aria-label="查看大图:${esc(label)}">+ <div class="hph"><img src="${u}" alt="${esc(label)}" loading="lazy">+ <button class="hopen" type="button" aria-label="查看大图:${esc(label)}"></button><input type="checkbox" class="hsel" data-t="${r.t}" aria-label="选择此记录" ${isSel ? 'checked' : ''}><div class="hcbtns"><button class="icon" data-act="dl" title="下载图片" aria-label="下载图片">@@ -210,24 +216,14 @@}async function regen(r) {- if (!r) return;- if (window.WB) {- await WB.show();- const W = WB._W;- if (W) {- W.mode = r.mode || 'tryon';- if (r.before) {- W.persons = [{- blob: r.before,- url: URL.createObjectURL(r.before),- w: 1024,- h: 1024- }];- }- }+ if (!r || !window.WB) return;+ try {+ const missing = await WB.restoreRecord(r);A.lbClose();- A.setTab('studio');- toast('已载入照片,可在工作台调整或直接生成');+ await A.setTab('studio');+ toast(['已载入历史提示词和可用参考图', ...missing].join(';'));+ } catch {+ toast('历史选材未能载入,请重试');}}@@ -244,7 +240,7 @@h: 1024}];}- A.lbClose();+ A.lbClose(true);A.setTab('studio');toast('已将结果设为新的人物照片');}@@ -257,12 +253,13 @@const lb = $('#lb');if (!lb) return;+ opener = srcCard?.querySelector('.hopen');lb.hidden = false;document.body.style.overflow = 'hidden';drawLb();- if (!RM && srcCard) {+ if (!motionPreference.matches && srcCard) {const ph = srcCard.querySelector('.hph');if (ph) {const rect = ph.getBoundingClientRect();@@ -292,6 +289,9 @@lbUrls.push(afterUrl);if (img) {+ delete img.dataset.src;+ img.onerror = null;+ img.classList.remove('lo');img.removeAttribute('srcset');img.src = afterUrl;img.alt = r.label || (r.mode == 'gen' ? '自由生图' : '虚拟试穿');@@ -313,7 +313,7 @@const d = new Date(r.t);const dateStr = `${d.getFullYear()}/${p2(d.getMonth() + 1)}/${p2(d.getDate())} ${p2(d.getHours())}:${p2(d.getMinutes())}`;- const prov = PROV_NAME[r.prov] || r.prov || 'AI 服务商';+ const prov = providerName(r);const side = $('#lbSide');if (!side) return;@@ -350,7 +350,7 @@if (!L.length) return;curIndex = (curIndex + delta + L.length) % L.length;drawLb();- if (!RM) {+ if (!motionPreference.matches) {const img = $('#lbImg');if (img) {img.animate([@@ -379,6 +379,7 @@// Intercept keyboard shortcuts when in history lightbox viewaddEventListener('keydown', e => {if (A.st.tab == 'history' && !$('#lb')?.hidden) {+ if ($('#helpBox:not([hidden]),#ageBox:not([hidden]),#privBox:not([hidden])')) return;if (e.ctrlKey || e.metaKey || e.altKey) return;const ae = document.activeElement;if (ae && /^(INPUT|SELECT|TEXTAREA)$/.test(ae.tagName)) return;@@ -398,7 +399,7 @@e.preventDefault();e.stopImmediatePropagation();const r = L[curIndex];- if (r?.prompt) A.copy(r.prompt, '提示词');+ if (r?.prompt) copyRecord(r,r.prompt);} else if (k == 'f' || k == 'a' || k == 's') {e.preventDefault();e.stopImmediatePropagation();@@ -415,11 +416,11 @@const r = L[curIndex];if (!r) return;- if (act == 'cp') A.copy(r.prompt, '提示词');- if (act == 'cporig') A.copy(r.orig, '原始提示词');+ if (act == 'cp') copyRecord(r,r.prompt);+ if (act == 'cporig') copyRecord(r,r.orig);if (act == 'dl') dlOne(r);if (act == 'regen') {- A.lbClose();+ A.lbClose(true);await regen(r);}if (act == 'person') {@@ -468,18 +469,6 @@}});- $('#histGrid')?.addEventListener('keydown', e => {- if (e.key == 'Enter' || e.key == ' ') {- const ph = e.target.closest('.hph');- if (ph && !e.target.classList.contains('hsel')) {- e.preventDefault();- const card = ph.closest('.hist-card');- const i = +card?.dataset.i;- if (i >= 0) openLb(i, card);- }- }- });-// Toolbar events$('#histSelAll')?.addEventListener('change', e => {if (e.target.checked) {@@ -584,7 +573,17 @@});async function refresh() {- L = await getRecords();+ try {+ L = await getRecords();+ } catch {+ $('#histEmpty').hidden = true;+ $('#histBar').hidden = true;+ $('#histStats').hidden = true;+ const grid = $('#histGrid');+ grid.innerHTML = '<p>生成记录读取失败。<button type="button" class="sm">重新加载</button></p>';+ grid.querySelector('button').onclick = refresh;+ return;+ }const currentKeys = new Set(L.map(r => r.t));for (const k of sel) {if (!currentKeys.has(k)) sel.delete(k);@@ -596,7 +595,15 @@await refresh();}- window.HIS = { show, refresh, getList: () => L };+ function closed(restoreFocus) {+ cleanupLbUrls();+ if (restoreFocus) {+ const target = opener?.isConnected ? opener : $('#histGrid .hopen, #histEmpty button');+ target?.focus({preventScroll:true});+ }+ opener = null;+ }+ window.HIS = { show, refresh, closed, getList: () => L };// Init badge count on loadgetRecords().then(list => {diff --git a/src/i18n.js b/src/i18n.jsnew file mode 100644index 0000000..6b905fb--- /dev/null+++ b/src/i18n.js@@ -0,0 +1,549 @@+'use strict';+(() => {+ const languages = {zh: 'zh-CN', en: 'en', ja: 'ja'};+ const translations = {+ '添加同视角深度姿势':['Add the matching depth view','同じアングルの深度画像を追加'],+ '添加同视角姿势':['Add the matching pose sketch','同じアングルの線画を追加'],+ '切换到深度图':['Flip to depth map','深度画像に切り替え'],+ '切换到线稿':['Flip to line art','線画に切り替え'],+ '图片加载失败,请重试':['Image could not load. Try again.','画像を読み込めませんでした。もう一度お試しください。'],+ '复制时附参考图':['Include image links when copying','コピー時に参照画像のリンクを含める'],+ '复制失败,请检查剪贴板权限':['Could not copy. Check clipboard permissions.','コピーできませんでした。クリップボードの権限をご確認ください。'],+ '本机引擎':['Local engine','ローカルエンジン'], '本机引擎已连接':['Local engine connected','ローカルエンジンに接続しました'],+ '使用本机已启动的引擎。':['Uses the engine running on this computer.','この端末で起動したエンジンを使います。'],++ '在本机使用 ComfyUI':['Use ComfyUI locally','ローカルで ComfyUI を使う'],+ '在项目目录运行':['In the project folder, run','プロジェクトフォルダで'], ',然后':[', then',' を実行し、'], '打开本机工作台':['open the local studio','ローカルスタジオを開く'],+ '本机模型':['Local checkpoint','ローカルモデル'], '选择模型':['Choose a checkpoint','モデルを選択'],+ '请先测试连接并选择本机模型':['Test the connection and choose a local checkpoint.','接続をテストしてローカルモデルを選択してください。'],+ '使用一张参考图。测试连接后选择模型。':['Use one reference image. Test the connection to list checkpoints.','参照画像は1枚。接続をテストしてモデルを選択してください。'],+ '无法连接本机 ComfyUI。请先启动服务,再测试连接。':['Could not reach ComfyUI on this computer. Start the service, then test again.','ローカルの ComfyUI に接続できません。起動してから接続を再テストしてください。'],+ 'ComfyUI 中还没有可用的 checkpoint':['No checkpoints are available in ComfyUI yet.','ComfyUI に利用可能なモデルがありません。'],+ '通知': ['Notifications','お知らせ'], '姿态': ['Movement','動作'], '人物造型': ['People','人物・髪型'],+ '服饰': ['Wardrobe','衣類'], '环境与物件': ['Setting','空間・小物'], '素材库': ['Libraries','素材集'], '我的': ['Saved','マイページ'],+ '工作台': ['Studio','スタジオ'],+ '深度图': ['Depth map','深度画像'],+ '分类索引': ['Category index','分類索引'], '在原站查看': ['View source','提供元で見る'],+ 'CC0 1.0,AI 生成的虚构人物,请勿用于冒充真人': ['CC0 1.0. Fictional AI-generated portrait. Please do not impersonate real people.','CC0 1.0。AI が生成した架空の人物です。実在の人物へのなりすましには使用しないでください。'],+ '素材来源与许可': ['Sources and licenses','出典・ライセンス'], '更新已就绪,刷新页面': ['Update ready · Reload','更新を適用して再読み込み'],+ '复制提示词可附参考图链接。': ['Prompts can include links to your reference images.','プロンプトに参照画像へのリンクを含められます。'],+ '。非官方整理。图片权利归原作者,转载或商用前请联系原作者。': ['. Unofficial collection. Images belong to their creators. Contact them before redistribution or commercial use.','。非公式の素材集です。画像の権利は原作者に帰属します。転載・商用利用の前に原作者へお問い合わせください。'],+ '。人像为虚构人物。原作者希望避免原样批量转载。': ['. Portraits depict fictional people. The creator asks that the unmodified collection not be reposted in bulk.','。架空の人物です。原作者はそのままの一括転載を控えるよう求めています。'],+ '。发型与部分动画服装使用原站图片,标签为 CC0,图片版权归原作者。': ['. Hairstyles and selected anime outfits use images hosted by the source. Tags are CC0. Image rights belong to the creator.','。髪型と一部のアニメ衣装は元サイトの画像を表示しています。タグは CC0、画像の権利は原作者に帰属します。'],+ '。表情参考使用 ICT-FaceKit 头模,© USC Institute for Creative Technologies,MIT。': ['. Expression references use the ICT-FaceKit head model, © USC Institute for Creative Technologies, MIT.','。表情資料は ICT-FaceKit の頭部モデルを使用しています(© USC Institute for Creative Technologies、MIT)。'],+ '。历代服饰、场景、光影、道具与家具采用 CC0 1.0。': ['. Historical dress, scenes, lighting, props and furniture are CC0 1.0.','。時代衣装・背景・照明・小道具・家具は CC0 1.0 です。'],+ '加入工作台':['Add to workspace','創作パネルに追加'], '移出工作台':['Remove from workspace','創作パネルから外す'],+ '创作台':['Workspace','創作パネル'], '收起工作台':['Collapse workspace','パネルをたたむ'],+ '参考素材或提示词':['references or a prompt','素材またはプロンプト'],+ '选择素材或输入提示词':['Choose references or enter a prompt','素材を選ぶかプロンプトを入力'],+ '试穿工作台':['Try-on studio','試着スタジオ'], '参考画板':['Reference board','リファレンスボード'],+ '创作工作台':['Creative studio','制作スタジオ'], '其他素材':['Other references','その他の素材'],+ '选择人物':['Choose a person','人物を選ぶ'], '素材分类':['Reference categories','素材の種類'],+ '服装类型':['Outfit collections','衣装の種類'], '上传服装图':['Upload an outfit photo','衣装の画像を追加'],+ '描述你想生成的画面':['Describe the image you want to create','作りたい画像を入力'], '上传':['Upload','アップロード'],+ '最多 2 张服装参考图':['Choose up to 2 outfit reference images','衣装の参考画像は最大2枚です'],+ '已加入工作台':['Added to the studio','スタジオに追加しました'],+ '请先选择素材或输入提示词':['Choose a reference or enter a prompt','素材を選ぶかプロンプトを入力してください'],+ '编辑提示词':['Edit prompt','プロンプトを編集'], '本次请求':['Request','リクエスト'], '提交的参考图':['Input references','送信した参照画像'],+ '被服务商的安全审核拦下了':['Blocked by the provider’s safety review','プロバイダーの安全審査によりブロックされました'],+ '实际发送的提示词':['Submitted prompt','送信したプロンプト'],+ '当前模型未接收参考图,本次仅按提示词生成。':['The model did not accept the references. This image was generated from the prompt alone.','モデルが参照画像を受け付けなかったため、今回はプロンプトのみで生成しました。'],+ '涉及未成年人':['Content involving minors','未成年者に関連する内容'], '性感/暴露内容':['Sexual or explicit content','性的な内容・露出'],+ '暴力或血腥':['Violence or gore','暴力・流血表現'], '自残':['Self-harm','自傷行為'], '仇恨':['Hate','ヘイト表現'],+ '骚扰':['Harassment','嫌がらせ'], '危险或违法内容':['Dangerous or illegal content','危険または違法な内容'],+ '个人隐私信息':['Personal information','個人情報'], '版权内容':['Copyrighted content','著作権に関わる内容'],+ '搭配示例':['Sample look','コーデ例'], '使用这组参考':['Use these references','この組み合わせを使う'],+ '生成进度':['Generation progress','生成の進捗'], '参考素材':['References','参照素材'],+ '尚未选材':['No references selected','素材未選択'], '组合描述':['Combined description','組み合わせの説明'],+ '更多素材':['More materials','その他の素材'], '输入或编辑提示词':['Enter or edit a prompt','プロンプトを入力・編集'],+ '选择姿势':['Choose a pose','ポーズを選択'], '选择表情':['Choose an expression','表情を選択'],+ '语言设置': ['Language preferences','言語設定'],+ '界面语言': ['Interface language','表示言語'],+ '素材描述语言': ['Reference descriptions','素材の説明言語'],+ '描述语言': ['Description language','説明の言語'],+ '跳到内容': ['Skip to content','コンテンツへ移動'],+ '衣姿 PoseWear 首页': ['PoseWear home','PoseWear ホーム'],+ '搜姿势、颜色、单品': ['Search poses, colors, or clothing','ポーズ、色、アイテムを検索'],+ '搜姿势名、系列、分类': ['Search by pose, series, or category','ポーズ名、シリーズ、分類を検索'],+ '搜索': ['Search','検索'], '搜索…': ['Search…','検索…'], '清除搜索': ['Clear search','検索をクリア'],+ '显示成人向内容(18+)': ['Show adult content (18+)','成人向けコンテンツを表示(18+)'],+ '成人向内容,默认关闭': ['Adult content is hidden by default','成人向けコンテンツは初期設定で非表示'],+ '成人向内容已隐藏,点击打开': ['Adult content hidden. Show it','成人向けコンテンツは非表示。押して表示'],+ '成人向内容已显示,点击关闭': ['Adult content visible. Hide it','成人向けコンテンツを表示中。押して非表示'],+ '快捷键(?)': ['Keyboard shortcuts (?)','キーボードショートカット(?)'],+ '快捷键帮助': ['Keyboard shortcuts','ショートカットのヘルプ'], '快捷键': ['Keyboard shortcuts','キーボードショートカット'],+ '外观': ['Appearance','外観'], '外观(T)': ['Appearance (T)','外観(T)'],+ '跟随系统': ['Use system setting','システムに合わせる'], '浅色': ['Light','ライト'], '深色': ['Dark','ダーク'],+ '切换深浅色(T)': ['Switch theme (T)','テーマを切り替え(T)'],+ '切换深浅色': ['Switch theme','テーマを切り替え'], 'GitHub 开源仓库': ['GitHub repository','GitHub リポジトリ'],+ '栏目': ['Sections','セクション'], '姿势': ['Poses','ポーズ'], '深度姿势': ['Depth poses','深度ポーズ'],+ '服装': ['Outfits','衣装'], '动画服装': ['Anime outfits','アニメ衣装'], '人像': ['Portraits','人物'],+ '表情': ['Expressions','表情'], '发型': ['Hair','髪型'], '历代': ['Historical dress','時代衣装'],+ '历代服饰': ['Historical dress','時代衣装'], '场景': ['Scenes','背景'], '光影': ['Lighting','照明'],+ '道具': ['Props','小道具'], '家具': ['Furniture','家具'], '试穿': ['Try-on','試着'],+ '收藏': ['Favorites','お気に入り'], '最近': ['Recent','最近'], '生成记录': ['History','生成履歴'],+ '姿势库': ['Pose library','ポーズ集'], '深度姿势库': ['Depth pose library','深度ポーズ集'],+ '服装库': ['Outfit library','衣装集'], '动画服装库': ['Anime outfit library','アニメ衣装集'],+ '人像库': ['Portrait library','人物集'], '表情库': ['Expression library','表情集'], '发型库': ['Hair library','髪型集'],+ '历代服饰库': ['Historical dress library','時代衣装集'], '场景库': ['Scene library','背景集'],+ '光影库': ['Lighting library','照明集'], '道具库': ['Prop library','小道具集'], '家具库': ['Furniture library','家具集'],+ '我的收藏': ['My favorites','お気に入り'], '最近浏览': ['Recently viewed','閲覧履歴'],+ '参考图库': ['Reference library','参考素材集'],+ '点开素材查看大图和提示词,加入组合即可生图。': ['Open a reference for the full image and prompts, or add it to a set to generate an image.','素材を開くと大きな画像とプロンプトを確認できます。組み合わせて画像を生成できます。'],+ '去试穿': ['Open studio','試着室へ'], '不再显示这条说明': ['Dismiss introduction','説明を閉じる'],+ '图库更新': ['Library update','素材集の更新'], '新增表情、发型等七个参考库。': ['Seven new collections, including expressions and hairstyles.','表情や髪型など、7つの素材集を追加しました。'],+ '浏览发型': ['Explore hair','髪型を見る'], '关闭公告': ['Dismiss announcement','お知らせを閉じる'],+ '更多筛选': ['Filters','絞り込み'], '清空全部': ['Clear all','すべて解除'], '清空筛选': ['Clear filters','絞り込みを解除'],+ '导出收藏': ['Export favorites','お気に入りをエクスポート'], '导入': ['Import','読み込み'],+ '清空': ['Clear','クリア'], '清空记录': ['Clear history','履歴を消去'], '排序': ['Sort','並べ替え'],+ '默认排序': ['Default order','標準順'], '编号倒序': ['ID descending','ID 降順'], '随机打乱': ['Shuffle','シャッフル'],+ '收藏优先': ['Favorites first','お気に入り優先'], '人气榜': ['Popular','人気順'], '随机一个': ['Random pick','ランダム'],+ '没有找到匹配的内容': ['No matches','一致する素材がありません'], '换个关键词,或清空筛选条件试试': ['Try a different keyword or clear the filters.','別のキーワードを試すか、絞り込みを解除してください。'],+ '系列': ['Series','シリーズ'], '分类': ['Category','分類'], '角度': ['Angle','アングル'], '颜色': ['Color','色'], '单品': ['Item','アイテム'],+ '类型': ['Type','種類'], '发长': ['Hair length','髪の長さ'], '情绪': ['Emotion','感情'], '强度': ['Intensity','強さ'],+ '朝代': ['Era','時代'], '机位': ['Camera angle','カメラ位置'], '视角': ['View','視点'], '全部': ['All','すべて'],+ '更多': ['More','もっと見る'], '收起': ['Collapse','折りたたむ'], '全部筛选': ['All filters','すべての絞り込み'],+ '工作模式': ['Studio mode','作成モード'], '用我的照片': ['Use my photo','自分の写真を使う'],+ '没有照片': ['Without a photo','写真を使わない'], '上传照片,选一套衣服,换上看看。': ['Upload a photo and select an outfit to try on.','写真をアップロードし、試着したい衣装を選びます。'],+ '选模特类型和服装,直接出一张上身图。': ['Choose a model and an outfit to create an image.','モデルと衣装を選んで着用画像を生成します。'],+ '人物照片': ['Portrait photo','人物写真'], '人物': ['Person','人物'], '模特': ['Model','モデル'],+ '必选': ['Required','必須'], '可选': ['Optional','任意'], '可传脸部参考': ['Face reference optional','顔の参考写真は任意'],+ '从人像库选': ['Browse portraits','人物集から選ぶ'], '上传人物照': ['Upload a portrait','人物写真を追加'],+ '点击、拖入或粘贴': ['Choose, drop, or paste','選択・ドロップ・貼り付け'],+ '模特类型': ['Model type','モデルの種類'], '上传图': ['Upload','画像を追加'],+ '从库中选': ['Browse library','素材集から選ぶ'], '从动画服装选': ['Anime outfits','アニメ衣装から選ぶ'],+ '全部角度': ['All angles','全アングル'], '多姿势出图方式': ['Multiple-pose output','複数ポーズの生成方法'],+ '分开出': ['Separate images','個別に生成'], '拼一张': ['One sheet','1枚にまとめる'], '从表情库选': ['Browse expressions','表情集から選ぶ'],+ '需要一个图像模型的 API Key': ['Add an image model API key','画像モデルの API キーを設定'],+ '选择服务商并配置自己的 API Key。': ['Choose your provider and enter your own API key.','プロバイダーを選び、ご自身の API キーを設定してください。'],+ '去设置': ['Set up','設定する'], '结果': ['Result','結果'], '结果会显示在这里': ['Your result will appear here','生成した画像がここに表示されます'],+ '选好人物和服装后点「生成」': ['Select a person and an outfit, then choose Generate.','人物と衣装を選び、「生成」を押してください。'],+ '生成结果': ['Generated image','生成結果'], '原始照片': ['Original photo','元の写真'], '前后对比': ['Before and after','生成前後の比較'], '原图': ['Original','元画像'],+ '正在上传素材…': ['Uploading references…','素材をアップロード中…'], '正在准备素材…': ['Preparing references…','素材を準備中…'],+ '取消': ['Cancel','キャンセル'], '下载': ['Download','ダウンロード'], '全部打包': ['Download all as ZIP','すべて ZIP に保存'],+ '重来': ['Start again','やり直す'], '当原图': ['Use as original','元画像として使う'], '对比': ['Compare','比較'],+ '未配置 API': ['API not set up','API 未設定'], '设置': ['Settings','設定'], '生成': ['Generate','生成'],+ '风格': ['Style','スタイル'], '画幅': ['Aspect ratio','縦横比'], '自动': ['Auto','自動'],+ '数量': ['Count','枚数'], '高级设置': ['Advanced settings','詳細設定'],+ '保留原照片背景与光线': ['Keep the original background and lighting','元の背景と照明を保持'],+ '减少误拦截': ['Use neutral wording','中立的な表現を使う'],+ '用更中性的描述发送,减少正常穿搭被误判,不改变服装和姿势': ['Use neutral descriptions to reduce false flags while preserving the outfit and pose.','衣装やポーズは変えず、誤判定を減らすために説明を中立的な表現にします。'],+ '补充要求(可选),例如:海边日落、半身构图、手拿咖啡…': ['Additional details (optional), e.g. a beach sunset or a waist-up shot…','追加の指定(任意)。例:海辺の夕日、上半身の構図、手にコーヒー…'],+ '自定义模特描述,例如:25 岁成年女性,黑色长直发,清淡妆容,身材纤细': ['Describe the model, e.g. an adult with long black hair and natural makeup.','モデルの特徴を入力。例:黒いロングヘア、ナチュラルメイクの成人女性'],+ '提示词语言': ['Prompt language','プロンプトの言語'], '英文': ['English','英語'], '中文': ['Chinese','中国語'],+ '复制': ['Copy','コピー'], '重置': ['Reset','リセット'], '最终提示词': ['Final prompt','最終プロンプト'],+ '未配置': ['Not configured','未設定'], '选择素材': ['Select references','素材を選択'],+ '选择服装': ['Choose an outfit','衣装を選択'], '选择动画服装': ['Choose an anime outfit','アニメ衣装を選択'],+ '选择姿势参考图(最多 6 张)': ['Choose up to 6 pose reference images','ポーズ参考画像を選択(最大6枚)'],+ '姿势图类型':['Pose reference type','ポーズ画像の種類'], '姿势线稿与深度图':['Pose sketches and depth maps','ポーズの線画と深度マップ'],+ '线稿':['Line art','線画'], '没有匹配的结果':['No matching references','該当する素材がありません'],+ '选择人像(作为人物 / 脸部参考)': ['Choose a portrait or face reference','人物・顔の参考写真を選択'],+ '选择表情(只迁移神态,不换脸)': ['Choose an expression (keep the face)','表情を選択(顔は変更しません)'],+ '选择姿势(可选)': ['Choose poses (optional)','ポーズを選択(任意)'],+ '选择表情(可选)': ['Choose an expression (optional)','表情を選択(任意)'],+ '从库里选,或上传图片': ['Browse the library or upload an image','素材集から選択、または画像を追加'],+ '不选就随机': ['Leave empty for a random pose','選ばない場合はランダム'],+ '不选就保持原姿势': ['Leave empty to keep the original pose','選ばない場合は元のポーズを保持'],+ '只取神态,不换脸': ['Keep the face; transfer the expression','顔を保ったまま表情を反映'],+ '完成': ['Done','完了'], '关闭': ['Close','閉じる'], 'API 设置': ['API settings','API 設定'],+ '服务商': ['Provider','プロバイダー'], '豆包 Seedream': ['Seedream','Seedream'],+ '火山方舟 · 国内直连': ['Volcengine Ark','Volcengine Ark'], '自定义中转': ['Custom endpoint','カスタム接続先'],+ 'OpenAI 兼容': ['OpenAI compatible','OpenAI 互換'], '连接': ['Connection','接続'], '显示': ['Show','表示'], '隐藏': ['Hide','非表示'],+ '模型': ['Model','モデル'], '高级': ['Advanced','詳細'], '接口协议': ['API protocol','API 形式'],+ 'images/edits · multipart(OpenAI 官方格式)': ['images/edits · multipart (OpenAI)','images/edits · multipart(OpenAI)'],+ 'images/generations · JSON 多图(多数中转 / gpt-image-2)': ['images/generations · JSON (multiple images)','images/generations · JSON(複数画像)'],+ 'Gemini · models/:generateContent(Nano Banana 等)': ['Gemini · models/:generateContent (Nano Banana)','Gemini · models/:generateContent(Nano Banana など)'],+ '图片字段名': ['Image field name','画像フィールド名'], 'image[](官方,多图)': ['image[] (official, multiple images)','image[](公式、複数画像)'],+ 'image(部分中转)': ['image (some endpoints)','image(一部の接続先)'],+ '通过本站代理转发': ['Route through the site proxy','サイトのプロキシを経由'],+ '开启后,本站代理会转发请求内容和凭据。': ['When enabled, the site proxy forwards your request and credentials.','有効にすると、このサイトのプロキシがリクエストと認証情報を転送します。'],+ 'API Key 保存在此浏览器。使用公共设备后,请清除密钥。': ['Your key is stored in this browser. Clear it after using a shared device.','キーはこのブラウザに保存されます。共有端末の利用後はキーを削除してください。'],+ '清除密钥': ['Clear key','キーを削除'], '导出': ['Export','書き出し'], '测试连接': ['Test connection','接続テスト'], '保存': ['Save','保存'],+ '生图工作台': ['Image workspace','画像作成'], '添加素材': ['Add references','素材を追加'],+ '工作台还是空的。用上面的按钮直接选素材,或者在图库里点卡片上的 + 加入——拼好素材就能在这里生图。': ['Choose a reference above or add one from the library with +.','上のボタンから素材を選ぶか、素材集の + で追加できます。'],+ '复制中文描述': ['Copy Chinese description','中国語の説明をコピー'], '复制英文提示词': ['Copy English prompt','英語プロンプトをコピー'],+ '完整工作台': ['Full studio','試着室を開く'], '生图提示词': ['Image prompt','画像プロンプト'],+ '选好素材后这里会自动填好提示词,也可以自己改': ['A prompt appears when you add references. You can edit it here.','素材を追加するとプロンプトが表示されます。ここで編集できます。'],+ '张数': ['Images','枚数'], '比例': ['Ratio','比率'], '生成图片': ['Generate image','画像を生成'], '停止': ['Stop','停止'],+ '打开生图工作台': ['Open image workspace','画像作成パネルを開く'], '在生成记录中查看': ['View in history','生成履歴で見る'],+ '大图预览': ['Image preview','画像プレビュー'], '关闭(Esc)': ['Close (Esc)','閉じる(Esc)'], '上一张': ['Previous','前へ'], '下一张': ['Next','次へ'],+ '请前往原站查看': ['View on the source site','提供元で見る'], '聚焦搜索': ['Focus search','検索に移動'],+ '切换描述语言(中 / 英)': ['Switch description language','説明の言語を切り替え'], '切换栏目': ['Switch section','セクションを切り替え'],+ '大图:上一张 / 下一张': ['Preview: previous / next','プレビュー:前 / 次'], '大图:切换拍摄角度': ['Preview: change angle','プレビュー:アングルを変更'],+ '大图:收藏': ['Preview: favorite','プレビュー:お気に入り'], '大图:加入 / 移出组合': ['Preview: add to / remove from set','プレビュー:組合せに追加・削除'],+ '大图:复制中文描述': ['Preview: copy Chinese description','プレビュー:中国語の説明をコピー'], '大图:复制分享链接': ['Preview: copy link','プレビュー:共有リンクをコピー'],+ '知道了': ['Got it','閉じる'], '回到顶部': ['Back to top','先頭へ戻る'], '全选': ['Select all','すべて選択'],+ '已选': ['Selected','選択中'], '张': ['images','枚'], '打包下载': ['Download ZIP','ZIP で保存'], '导出 ZIP': ['Export ZIP','ZIP を書き出し'],+ '还没有生成记录': ['No images yet','生成履歴はまだありません'], '在试穿工作台生成的图片会保存在这里': ['Images you generate in the studio appear here.','試着室で生成した画像がここに保存されます。'],+ '使用提示': ['Tips','使い方'], '来源与致谢': ['Sources and credits','出典・クレジット'],+ '隐私说明': ['Privacy','プライバシー'], '开源地址': ['Source code','ソースコード'],+ '显示成人向内容?': ['Show adult content?','成人向けコンテンツを表示しますか?'],+ '包括双人互动、性感类姿势、深度姿势里的双人图,以及内衣、性感类服装。仅适合已满 18 岁的用户。只需确认一次,之后用顶部的「18+」开关随时打开或关闭。': ['Includes intimate poses, adult depth references, lingerie, and revealing outfits. For ages 18+ only. Once confirmed, use the 18+ switch to show or hide them.','親密なポーズ、成人向けの深度素材、ランジェリーなどを含みます。18歳以上の方のみ利用できます。確認後は「18+」で表示を切り替えられます。'],+ '暂不': ['Not now','今はしない'], '我已满 18 岁,打开': ['I am 18 or older. Show content','18歳以上です。表示する'],+ '本机存储': ['Local storage','端末内の保存'], 'API 密钥': ['API key','API キー'], '代理限制': ['Proxy rules','プロキシの制限'], '统计': ['Analytics','アクセス解析'], '图片': ['Images','画像'],+ ':收藏、浏览记录、筛选偏好、成人内容开关和试穿记录只保存在你的浏览器(localStorage / IndexedDB),不上传。清除浏览器数据即可删除。': [': Favorites, browsing history, filters, the adult-content setting and try-on history are saved in this browser. Clear browser data to remove them.',':お気に入り、閲覧・試着履歴、絞り込み、成人向け設定はブラウザ内に保存されます。ブラウザのデータを消去すると削除できます。'],+ ':密钥保存在此浏览器。直连时,请求发往所选服务商;使用本站代理时,代理会经手凭据和图片。': [': Your key is stored in this browser. Direct requests go to your provider. When you use the site proxy, it receives credentials and images to forward them.',':キーはこのブラウザに保存されます。直接接続では選択したプロバイダーへ送信し、サイトのプロキシを使う場合はプロキシが認証情報と画像を中継します。'],+ ':代理接受本站页面发起的接口请求。自定义中转的运营者也能收到请求内容,请选择可信服务。': [': The proxy accepts requests from this site. A custom endpoint also receives the request content. Choose a service you trust.',':このサイトのページからのリクエストを受け付けます。カスタム接続先にもリクエストの内容が届くため、信頼できるサービスを選んでください。'],+ ':站点部署者可以开启 Cloudflare Web Analytics。': [': The site operator can enable Cloudflare Web Analytics.',':サイトの運営者は Cloudflare Web Analytics を有効にできます。'],+ ':姿势、服装、人像和深度姿势由本站托管分发,来自 AI Pose Gallery、AI Costume Gallery、AI Costume Anime Gallery、AI Pose Depth Gallery(@giaaibusi)与 AI Portrait Gallery(@agi_aibusi)。发型与部分动画服装的图片由 CharaDB 原站托管、页面直接加载,对方能看到请求的 IP。': [': PoseWear serves poses, outfits, portraits and depth references from the credited galleries. Hair and some anime outfits load directly from CharaDB, which receives your IP address.',':ポーズ、衣装、人物、深度素材は各提供元からの素材を当サイトが配信しています。髪型と一部のアニメ衣装は CharaDB から直接読み込むため、接続元 IP が提供元に伝わります。'],+ '参考图':['Reference images','参考画像'], '来源':['Source','出典'], '非官方汉化':['Unofficial translation','非公式翻訳'],+ '人像使用提示与规则':['Portrait usage notes','人物素材の利用について'],+ '在 AI 工具的「角色参考 / 脸部参考」里载入这张图即可。':['Load the image in your AI tool’s character or face reference field.','AI ツールのキャラクター・顔の参照欄に画像を読み込みます。'],+ '想统一长相用「正脸」;参考服装、发质和整体氛围用「生活照」。':['Choose a front-facing portrait for facial consistency, or a lifestyle photo for clothing and hair reference.','顔を揃えるには正面の写真を、衣装・髪・雰囲気には日常写真を使います。'],+ '一直用同一张图,生成的脸会更稳定。下载原图 PNG 能保留更多细节。':['Reuse the same reference for a consistent face. The original PNG has more detail.','同じ画像を使うと顔が安定します。元の PNG には細部が残っています。'],+ 'CC0 1.0:可商用、可修改,无需署名。均为 AI 生成的虚构人物,不得用来冒充真人或用于违背公序良俗的用途。原作者希望不要把图片原样批量转载。':['CC0 1.0 permits commercial use and edits without attribution. The people are fictional and AI-generated. Do not use them to impersonate real people or for inappropriate purposes. The creator asks that the images not be reposted unchanged in bulk.','CC0 1.0。商用利用・改変可能で、表示義務はありません。AI 生成の架空の人物です。なりすましや公序良俗に反する利用はお控えください。作者はそのままの一括転載を希望していません。'],+ '添加到组合':['Add to set','組合せに追加'], '加入组合':['Add to set','組合せに追加'], '移出组合':['Remove from set','組合せから削除'],+ '取消收藏':['Remove favorite','お気に入りを解除'], '已收藏':['Favorited','お気に入り済み'], '撤销':['Undo','元に戻す'], '移除':['Remove','削除'],+ '从记录中移除':['Remove from history','履歴から削除'], '查看大图':['Open preview','拡大表示'], '复制中文':['Copy Chinese','中国語をコピー'],+ '复制英文':['Copy English','英語をコピー'], '分享':['Share','共有'], '分享链接':['Share link','リンクを共有'], '中文描述':['Chinese description','中国語の説明'],+ '英文提示词 · PROMPT':['English prompt','英語プロンプト'], '英文提示词':['English prompt','英語プロンプト'], '提示词':['Prompt','プロンプト'],+ '下载图片':['Download image','画像を保存'], '复制图片':['Copy image','画像をコピー'], '下载原图 PNG':['Download original PNG','元の PNG を保存'],+ '下载原图 WebP':['Download original WebP','元の WebP を保存'], '下载原图':['Download original','元画像を保存'], '淘宝搜同款 ↗':['Find similar on Taobao ↗','淘宝で類似商品を検索 ↗'],+ '拍摄角度':['Camera angles','撮影アングル'], '试穿这套':['Try on this outfit','この衣装を試す'], '用作姿势参考':['Use as pose reference','ポーズに使う'],+ '用作人物参考':['Use as portrait reference','人物の参考に使う'], '用作表情参考':['Use as expression reference','表情に使う'],+ '+ 加入组合':['+ Add to set','+ 組合せに追加'], '✓ 已在组合中':['✓ In set','✓ 追加済み'], '♡ 收藏':['♡ Favorite','♡ お気に入り'],+ '♥ 已收藏':['♥ Favorited','♥ お気に入り済み'], '打开大图':['Open image','拡大表示'],+ '共':['Total','全'], '项':['items','件'], '个角度':['angles','アングル'], '张图片':['images','枚'], '条记录':['records','件'],+ '张 · 试穿':['images · Try-on','枚 · 試着'], '/ 生图':['/ Generate','/ 生成'], '最近搜索':['Recent searches','最近の検索'],+ '热门搜索':['Popular searches','人気の検索'], '热门':['Popular','人気'], '批量':['Select','複数選択'], '批量选择':['Select multiple','複数選択'],+ '取消全选':['Deselect all','すべて解除'], '已从记录中移除':['Removed from history','履歴から削除しました'], '已清空组合':['Set cleared','組合せをクリアしました'],+ '先从图库里选几项加入组合':['Add references from the library first','先に素材を組合せに追加してください'],+ '当前没有可选的内容':['No items to select','選択できる項目がありません'], '还没有收藏可导出':['No favorites to export','書き出すお気に入りがありません'],+ '还没有收藏':['No favorites yet','お気に入りはまだありません'], '还没有浏览记录':['No recent views','閲覧履歴はまだありません'],+ '看到喜欢的,点卡片右上角的 ♡。收藏只存在这台设备的浏览器里,可以导出备份。':['Tap ♡ on a card to save it. Favorites stay in this browser and can be exported.','カード右上の ♡ を押すと追加できます。お気に入りはこの端末に保存され、書き出しもできます。'],+ '打开过的大图会按时间排在这里,最多保留 100 条。':['Images you have opened appear here, up to the last 100.','開いた画像が新しい順に最大100件表示されます。'],+ '换个关键词试试,或者看看这些热门搜索:':['Try another keyword or one of these popular searches.','別のキーワードや、こちらの人気の検索もお試しください。'],+ '未找到该条目':['Reference not found','素材が見つかりません'], '数据加载失败':['Could not load references','素材を読み込めません'],+ '请检查网络后刷新页面重试':['Check your connection, then try again.','接続を確認して再読み込みしてください。'], '重新加载':['Reload','再読み込み'],+ '正面':['Front','正面'], '俯拍':['High angle','ハイアングル'], '仰拍':['Low angle','ローアングル'], '侧面':['Side','側面'], '斜侧':['Three-quarter','斜め'],+ '斜侧面':['Three-quarter','斜め'], '上半身':['Upper body','上半身'], '全身·标准':['Full body','全身・標準'],+ '全身·性感':['Full body · mature','全身・成人向け'], '双人互动':['Two people','2人'], '躺卧':['Lying down','横たわり'], '站姿':['Standing','立ち'], '坐姿':['Sitting','座り'],+ '跪立·趴姿':['Kneeling / prone','膝立ち・うつ伏せ'], '可爱':['Cute','かわいい'], '正脸':['Front-facing','正面'], '生活照':['Lifestyle','日常写真'],+ '短发':['Short','ショート'], '中长发':['Medium','ミディアム'], '半长发':['Shoulder length','セミロング'], '长发':['Long','ロング'],+ '春季':['Spring','春'], '夏季':['Summer','夏'], '秋季':['Autumn','秋'], '冬季':['Winter','冬'], '派对礼服':['Partywear','パーティー'], '泳装':['Swimwear','水着'],+ '内衣':['Lingerie','ランジェリー'], '性感':['Mature','セクシー'], '黑':['Black','黒'], '白':['White','白'], '红':['Red','赤'], '蓝':['Blue','青'],+ '粉':['Pink','ピンク'], '绿':['Green','緑'], '灰':['Gray','灰色'], '银白':['Silver','銀白'], '棕':['Brown','茶'], '银':['Silver','銀'],+ '紫':['Purple','紫'], '黄':['Yellow','黄'], '金':['Gold','金'], '米':['Beige','ベージュ'], '橙':['Orange','オレンジ'], '藏青':['Navy','紺'],+ '粉色':['Pink','ピンク'], '刘海':['Bangs','前髪'], '发色':['Hair color','髪色'], '发饰':['Hair accessories','髪飾り'], '瞳色':['Eye color','瞳の色'], '瞳型':['Eye shape','目の形'],+ '强烈':['Strong','強い'], '中等':['Medium','中程度'], '轻微':['Subtle','弱い'], '愤怒':['Anger','怒り'], '困惑':['Confusion','困惑'], '惊讶':['Surprise','驚き'],+ '背面':['Back','背面'], '俯视':['From above','俯瞰'], '仰视':['From below','あおり'], '平视':['Eye level','目線の高さ'],+ '室内':['Interior','室内'], '城市':['Urban','市街'], '自然':['Nature','自然'], '影棚':['Studio','スタジオ'], '时段':['Time of day','時間帯'],+ '空间':['Space','空間'], '艺术':['Artistic','アート'], '特效':['Effects','特殊効果'], '乐器':['Instruments','楽器'],+ '东亚女性':['East Asian woman','東アジア系女性'], '欧美女性':['Western woman','欧米系女性'], '男性模特':['Male model','男性モデル'],+ '动漫角色':['Anime character','アニメキャラクター'], '自定义':['Custom','カスタム'], '照片质感':['Photorealistic','写真風'],+ '影棚大片':['Editorial','スタジオ撮影'], '城市街拍':['Street style','ストリート'], '电商白底':['White backdrop','白背景の商品写真'],+ '胶片氛围':['Film','フィルム風'], '动漫插画':['Anime illustration','アニメイラスト'],+ '每张约半分钟':['About half a minute per image','1枚につき約30秒'], '上传人物照片':['Upload a portrait','人物写真を追加'],+ '请先上传人物照片':['Upload a portrait first','先に人物写真を追加してください'], '请先选择服装':['Choose an outfit first','先に衣装を選んでください'],+ '请先配置你的 API':['Set up your API first','先に API を設定してください'], '请先填写 API Key':['Enter an API key first','先に API キーを入力してください'],+ 'API 设置已保存在本机':['API settings saved on this device','API 設定をこの端末に保存しました'],+ '地址可达,方舟未提供模型列表。请通过生成验证密钥与模型。':['Endpoint reachable. Ark did not return a model list. Generate an image to verify your key and model.','接続先に到達しました。方舟のモデル一覧は取得できません。画像を生成してキーとモデルを確認してください。'],+ '接口未返回模型信息,请检查 Base URL 与接口协议。':['The endpoint did not return model information. Check the base URL and protocol.','モデル情報を取得できません。ベース URL と接続方式を確認してください。'],+ '本站代理未生效:/api/proxy 返回的是网站静态页面而不是接口响应,Seedream 暂时连不上,请稍后再试或联系站长':['The site proxy returned a web page. Try again later or contact the site administrator.','サイトのプロキシが Web ページを返しました。後ほど再試行するか管理者にお問い合わせください。'],+ '已从本机清除密钥':['Key cleared from this device','この端末からキーを削除しました'], '正在连接…':['Connecting…','接続中…'],+ '生成中…':['Generating…','生成中…'], '模型正在绘制…':['Generating the image…','画像を生成中…'],+ '生成完成':['Image generated','生成しました'], '已取消生成':['Generation canceled','生成をキャンセルしました'], '已取消':['Canceled','キャンセルしました'],+ '已加入表情参考(只取神态)':['Expression added as a reference','表情の参考に追加しました'], '已选为试穿服装':['Outfit selected for try-on','試着する衣装に設定しました'],+ '已加入补充要求':['Added to additional instructions','追加の指定に反映しました'], '已读入设置,点击保存后生效':['Settings imported. Save to apply.','設定を読み込みました。保存すると反映されます。'],+ 'Base URL 需填写有效的 HTTPS 地址,请勿在地址中包含账号或密码。':['Enter a valid HTTPS base URL without a username or password.','ユーザー名・パスワードを含まない HTTPS の URL を入力してください。'],+ '直连时,浏览器将密钥和图片发给填写的 HTTPS 地址。启用本站代理后会经本站转发,仅支持管理员登记的中转地址(含端口)。':['Direct requests send your key and images to the HTTPS endpoint you enter. The site proxy forwards them only to endpoints and ports registered by the administrator.','直接接続では入力した HTTPS の接続先にキーと画像を送信します。サイトのプロキシは、管理者が登録した接続先とポートにのみ転送します。'],+ ':本站仅向官方服务或管理员登记的 HTTPS 地址转发。接收方会收到凭据和图片,请选择可信服务。':[': The proxy forwards only to official services or registered HTTPS endpoints. The recipient receives your credentials and images. Choose a service you trust.',':公式サービスまたは管理者が登録した HTTPS 接続先にのみ転送します。認証情報と画像は相手に届くため、信頼できるサービスを選んでください。'],+ '记录保存失败,请先下载':['Could not save to history. Download your image.','履歴に保存できません。先に画像をダウンロードしてください。'],+ '已有生成任务正在进行':['A generation is already running','すでに生成中です'], '生成完成,部分图片未能存入生成记录,请先下载。':['Generation finished. Some images could not be saved to history. Download them now.','生成が完了しました。一部を履歴に保存できなかったため、ダウンロードしてください。'],+ '已载入历史提示词和可用参考图':['Restored the prompt and available references','履歴のプロンプトと利用可能な参考画像を読み込みました'],+ '旧记录的服装和姿势需重选':['Select the outfit and poses again for this older record','以前の記録の衣装とポーズを選び直してください'],+ '请核对当前服务商及模型':['Check the current provider and model','現在のプロバイダーとモデルを確認してください'],+ '部分参考图需重选':['Select unavailable references again','一部の参考画像を選び直してください'], '部分素材库未能加载':['Some libraries could not be loaded','一部の素材集を読み込めませんでした'],+ '部分人物照片需重选':['Select the unavailable portraits again','一部の人物写真を選び直してください'],+ '历史选材未能载入,请重试':['Could not restore references. Please retry.','履歴の素材を読み込めません。再試行してください。'],+ '素材加载失败,请关闭后重试':['Could not load references. Close and try again.','素材を読み込めません。閉じてから再試行してください。'],+ '试穿台选材加载失败,请重新打开后再试':['Could not load the selection. Reopen the studio to retry.','選択した素材を読み込めません。試着室を開き直してください。'],+ '素材未能载入,请重试':['Could not load the selection. Please retry.','素材を読み込めません。再試行してください。'],+ '最多 3 张人物照片':['Up to 3 portraits','人物写真は最大3枚'], '最多选择 6 张姿势参考图':['Choose up to 6 pose reference images','ポーズ参考画像は最大6枚です'],+ '人像加载失败':['Could not load portrait','人物写真を読み込めません'], '请选择图片文件':['Choose an image file','画像ファイルを選んでください'],+ '无法读取这张图片':['Could not read this image','この画像を読み込めません'], '无法读取服装图':['Could not read the outfit image','衣装画像を読み込めません'],+ '最多上传 2 张服装图(上装 + 下装)':['Upload up to 2 outfit images (top and bottom)','衣装画像は最大2枚(トップスとボトムス)'],+ '已复制':['Copied','コピーしました'], '已将结果设为新的人物照片':['Result set as the new portrait','生成結果を新しい人物写真に設定しました'],+ '已按当前选择重新生成提示词':['Prompt rebuilt from your selection','選択中の素材からプロンプトを作成しました'],+ '已开始下载图片':['Image download started','画像のダウンロードを開始しました'], '已开始下载':['Download started','ダウンロードを開始しました'],+ '下载失败':['Download failed','ダウンロードできませんでした'], '打包失败,请重试':['Could not create the ZIP. Try again.','ZIP を作成できません。再試行してください。'],+ '导入失败:文件格式不正确':['Import failed. Check the file format.','読み込みに失敗しました。形式を確認してください。'],+ '图片已复制到剪贴板':['Image copied to clipboard','画像をクリップボードにコピーしました'], '当前浏览器不支持复制图片':['This browser cannot copy images','このブラウザは画像のコピーに対応していません'],+ '生成失败':['Generation failed','生成に失敗しました'], '重试':['Retry','再試行'], '检查 API 设置':['Check API settings','API 設定を確認'],+ '换服务商重试':['Try another provider','別のプロバイダーで再試行'], '换一套服装':['Choose another outfit','別の衣装を選ぶ'],+ '密钥无效或已过期,请检查 API Key':['Invalid or expired API key. Check your key.','API キーが無効または期限切れです。キーを確認してください。'],+ '图片太大,请换一张更小的照片':['Image too large. Choose a smaller photo.','画像が大きすぎます。小さい写真を選んでください。'],+ '请求过于频繁或额度已用完,请稍后再试或检查账户余额':['Too many requests or insufficient credits. Try again later or check your balance.','リクエストが多すぎるか、残高が不足しています。時間を置くか残高を確認してください。'],+ '服务商内部错误,请稍后重试':['Provider error. Try again later.','プロバイダーでエラーが発生しました。しばらくしてから再試行してください。'],+ '网关错误(中转服务不可用)':['Gateway error (endpoint unavailable)','ゲートウェイエラー(接続先を利用できません)'],+ '服务暂时不可用,请稍后重试':['Service unavailable. Try again later.','一時的に利用できません。しばらくしてから再試行してください。'],+ '服务商响应超时,请重试':['Provider timed out. Try again.','プロバイダーがタイムアウトしました。再試行してください。'],+ '自由生图':['Image generation','画像生成'], '虚拟试穿':['Virtual try-on','バーチャル試着'], '生图':['Generate','生成'],+ '提示词 · PROMPT':['Prompt','プロンプト'], '复制提示词':['Copy prompt','プロンプトをコピー'], '原始提示词':['Original prompt','元のプロンプト'],+ '用此设置重新生成':['Generate with these settings','この設定で再生成'], '用相同设置重新生成':['Generate with these settings','この設定で再生成'],+ '用作人物照片':['Use as a portrait','人物写真に使う'], '删除此记录':['Delete this record','この履歴を削除'],+ '删除记录':['Delete record','履歴を削除'], '重新生成':['Regenerate','再生成'], '切换记录':['Change record','履歴を切り替え'],+ '打包中…':['Creating ZIP…','ZIP を作成中…'], '导出中…':['Exporting…','書き出し中…'],+ '请先勾选要下载的记录':['Select records to download','保存する履歴を選択してください'], '请先勾选要导出的记录':['Select records to export','書き出す履歴を選択してください'],+ '新建':['New','新規'], '删除':['Delete','削除'], '清除':['Clear','消去'], '今天':['Today','今日'], '昨天':['Yesterday','昨日'],+ '网络已断开,看过的图片还能继续浏览':['Offline. Previously viewed images may still be available.','オフラインです。閲覧済みの画像は引き続き利用できます。'],+ '网络已恢复':['Back online','接続が復旧しました'],+ '导出时包含 API Key 吗?\n确定 = 包含,取消 = 不含密钥':['Include the API key in the export?\nOK includes it. Cancel exports without the key.','書き出しに API キーを含めますか?\nOK はキーを含め、キャンセルはキーを含めずに書き出します。'],+ "加入生图组合": ["Add to generation set", "生成用の組合せに追加"],+ "生成记录读取失败。": ["Could not read generation history.", "生成履歴を読み込めません。"],+ "外链图片请到原站查看": ["View externally hosted images on the source site", "外部配信の画像は提供元でご覧ください"],+ "在": ["Visit", "アクセス先:"],+ "创建密钥;gpt-image-1 需要已验证的组织。": ["to create a key. An organization verified by OpenAI is required for gpt-image-1.", "でキーを作成します。gpt-image-1 には認証済みの組織が必要です。"],+ "免费获取 API Key(AIza 开头)。": ["to get an API key starting with AIza.", "で AIza から始まる API キーを取得できます。"],+ "火山方舟控制台": ["Volcengine Ark Console", "Volcengine Ark コンソール"],+ "开通 Seedream 模型并创建 API Key;会自动走本站代理。": ["to enable Seedream and create an API key. Requests use the site proxy.", "で Seedream を有効にして API キーを作成します。サイトのプロキシ経由で接続します。"],+ "SD 类模型用英文提示词更准": ["Use English prompts for Stable Diffusion models.", "Stable Diffusion 系モデルには英語プロンプトがおすすめです。"],+ "与": ["and", "と"],+ "中文名称和描述由本站翻译": ["PoseWear provides the Chinese titles and descriptions.", "中国語の名称と説明は当サイトの翻訳です。"],+ "人像来自": ["Portraits from", "人物素材:"],+ "原作者": ["Original creator", "原作者"],+ "发型与部分动画服装来自 CharaDB(作者 たき AI,标签 CC0),图片热链原站": ["Hair and some anime outfits come from CharaDB by たき AI. Tags are CC0, and images load from CharaDB.", "髪型と一部のアニメ衣装は CharaDB(作者 たき AI)の提供です。タグは CC0 で、画像は提供元から表示します。"],+ "双人互动默认隐藏,需打开右上角「18+」并确认已满 18 岁。": ["Two-person references are hidden by default. Use the 18+ switch and confirm your age to see them.", "二人用の参考素材は初期状態では非表示です。18+ スイッチで年齢を確認すると表示できます。"],+ "图片由原站托管,本站不保存。双人互动默认隐藏,需打开右上角「18+」并确认已满 18 岁。": ["Images are hosted by the source. Two-person references are hidden by default. Use the 18+ switch and confirm your age to see them.", "画像は提供元から配信されます。二人用の参考素材を見るには、18+ スイッチで年齢を確認してください。"],+ "姿势和服装": ["Pose and outfit", "ポーズと衣装"],+ "姿势和服装参考图。图片来自下方原图库,均为生成图。": ["AI-generated pose and outfit references from the galleries credited below.", "以下の素材集に掲載された、AI 生成のポーズ・衣装参考画像です。"],+ "把姿势和服装放进组合": ["to add poses and outfits to your set.", "でポーズや衣装を組合せに追加します。"],+ "收藏和设置保存在本机": ["Favorites and settings are saved on this device.", "お気に入りと設定はこの端末に保存されます。"],+ "每个姿势有多个角度,每套服装都附中英文描述。可以收藏、组合,也能上传自己的照片试穿。": ["Explore multiple angles for each pose and bilingual outfit prompts. Save favorites, build a set, or upload a photo to try on an outfit.", "各ポーズを複数の角度で確認し、衣装の中英プロンプトを読めます。お気に入りや組合せに追加し、自分の写真で試着できます。"],+ "深度姿势来自": ["Depth poses from", "深度ポーズの提供元:"],+ "点": ["Select", "選択:"],+ "画画、拍照、出图时用的参考": ["References for illustration, photography and image generation", "イラスト、撮影、画像生成のための参考素材"],+ "素材整理自公开图库": ["References from public galleries", "参考素材の提供元:"],+ "素材来自": ["References from", "素材提供:"],+ "部分姿势和内衣、性感类服装属于成人向参考,默认不显示,可以用顶部的「18+」开关打开或关闭。": ["Some poses, lingerie and mature outfits are hidden by default. Use the 18+ switch to show or hide them.", "一部のポーズ、ランジェリー、成人向け衣装は初期状態では非表示です。上部の 18+ スイッチで表示を切り替えられます。"],+ "(非官方汉化),图片由本站自存分发": ["(unofficial Chinese translation). Images are distributed by PoseWear.", "(非公式の中国語訳)。画像は当サイトが配信します。"],+ ",作者": [", by ", "、作者:"],+ "组姿势": ["pose sets", "組のポーズ"],+ "张角度图": ["angle views", "枚のアングル画像"],+ "套服装": ["outfits", "点の衣装"],+ "套动画服装": ["anime outfits", "点のアニメ衣装"],+ "张人像": ["portraits", "枚の人物画像"],+ "条表情": ["expressions", "種類の表情"],+ "款发型": ["hairstyles", "種類の髪型"],+ "套历代服饰": ["historical outfits", "点の時代衣装"],+ "个场景": ["scenes", "種類の背景"],+ "种光影": ["lighting setups", "種類の照明"],+ "件道具": ["props", "点の小道具"],+ "件家具": ["furniture pieces", "点の家具"],+ "表情图来自 WaveSpeed AI Emotion Gallery,底层头模为 ICT Face Model Light(ICT-FaceKit,© USC Institute for Creative Technologies,MIT)。无身份灰模头,只传神态、不传长相。": ["Expressions from WaveSpeed AI Emotion Gallery use the ICT Face Model Light (ICT-FaceKit, © USC Institute for Creative Technologies, MIT). The neutral head conveys expression without transferring identity.", "表情の提供元は WaveSpeed AI Emotion Gallery です。ICT Face Model Light(ICT-FaceKit、© USC Institute for Creative Technologies、MIT)の無彩色ヘッドで、顔立ちを変えずに表情を参照できます。"],+ "数据来自 CharaDB(作者 たき AI),标签数据 CC0;图片由原站托管、本站不保存,版权归原作者。": ["Data from CharaDB by たき AI. Tags are CC0. Images are hosted by CharaDB and belong to their creators.", "データ提供は CharaDB(作者 たき AI)、タグは CC0 です。画像は提供元から配信され、著作権は原作者に帰属します。"],+ "中国历代服饰来自 Shisei(作者 wquguru),图片与数据 CC0 1.0,可自由使用。": ["Chinese historical dress from Shisei by wquguru. Images and data are CC0 1.0.", "中国の時代衣装は Shisei(作者 wquguru)から。画像とデータは CC0 1.0 です。"],+ "场景来自 Shisei(作者 wquguru),图片与数据 CC0 1.0,可自由使用。空景中央留空,方便把人物放进去。": ["Scenes from Shisei by wquguru. Images and data are CC0 1.0. The center is left open to place a subject.", "背景は Shisei(作者 wquguru)から。画像とデータは CC0 1.0 で、中央の空間に人物を配置できます。"],+ "光影来自 Shisei(作者 wquguru),图片与数据 CC0 1.0。同一个人台、同样的灰球,只有光在变——照着挑光型、抄英文描述即可。": ["Lighting from Shisei by wquguru (CC0 1.0). Each reference uses the same mannequin and gray sphere to compare the light. Copy the English prompt to use it.", "照明の提供元は Shisei(作者 wquguru、CC0 1.0)です。同じマネキンと灰色の球を使って光の違いを比較し、英語の説明をコピーできます。"],+ "道具来自 Shisei(作者 wquguru),图片与数据 CC0 1.0,可自由使用。": ["Props from Shisei by wquguru. Images and data are CC0 1.0.", "小道具は Shisei(作者 wquguru)から。画像とデータは CC0 1.0 です。"],+ "家具来自 Shisei(作者 wquguru),图片与数据 CC0 1.0;尺寸为真实厘米数,与人台同比例。": ["Furniture from Shisei by wquguru (CC0 1.0). Dimensions are in centimeters, to the same scale as the mannequin.", "家具は Shisei(作者 wquguru、CC0 1.0)から。寸法は実寸の cm で、マネキンと同じ縮尺です。"],+ "偶像与舞台": ["Idols & stage", "アイドル・ステージ"],+ "军事与科幻": ["Military & sci-fi", "ミリタリー・SF"],+ "制服与校园风": ["Uniforms & schoolwear", "制服・スクール"],+ "和服": ["Kimono", "和服"],+ "奇幻": ["Fantasy", "ファンタジー"],+ "居家与睡衣": ["Loungewear & sleepwear", "部屋着・パジャマ"],+ "春夏休闲": ["Spring & summer casual", "春夏のカジュアル"],+ "洛丽塔与地雷系": ["Lolita & jirai-kei", "ロリータ・地雷系"],+ "礼服与派对": ["Evening & partywear", "ドレス・パーティー"],+ "秋冬休闲": ["Autumn & winter casual", "秋冬のカジュアル"],+ "职业与角色扮演": ["Workwear & cosplay", "職業・コスプレ"],+ "节庆与季节": ["Festive & seasonal", "祭事・季節"],+ "运动": ["Sportswear", "スポーツ"],+ "通勤与职场": ["Commuting & office", "通勤・オフィス"],+ "侧位": ["Side position", "側位"],+ "侧坐·鸭子坐": ["Side-sitting & W-sitting", "横座り・ぺたん座り"],+ "前倾": ["Leaning forward", "前かがみ"],+ "后仰": ["Leaning back", "のけぞり"],+ "后入位": ["Rear-facing position", "後背位"],+ "坐位": ["Seated position", "座位"],+ "坐位贴身": ["Seated close together", "座った密着"],+ "对面坐位": ["Face-to-face sitting", "対面座位"],+ "性感·大胆": ["Sensual & bold", "セクシー・大胆"],+ "扭身": ["Twisting", "ひねり"],+ "挤胸·乳沟": ["Cleavage poses", "胸寄せ・谷間"],+ "正面位": ["Face-to-face position", "対面"],+ "特殊": ["Other", "特殊"],+ "立位": ["Standing position", "立位"],+ "立位贴身": ["Standing close together", "立った密着"],+ "背面坐位": ["Rear-facing sitting", "背面座位"],+ "贴脸": ["Faces together", "顔を寄せる"],+ "贴身": ["Close contact", "密着"],+ "跪立": ["Upright kneeling", "膝立ち"],+ "蹲姿": ["Squatting", "しゃがみ"],+ "骑乘位": ["Straddling", "騎乗位"],+ "元": ["Yuan", "元"],+ "唐": ["Tang", "唐"],+ "商": ["Shang", "殷"],+ "婚服": ["Wedding attire", "婚礼衣装"],+ "宋": ["Song", "宋"],+ "明": ["Ming", "明"],+ "民国": ["Republican era", "民国時代"],+ "汉": ["Han", "漢"],+ "清": ["Qing", "清"],+ "魏晋": ["Wei–Jin", "魏晋"],+ "严肃": ["Serious", "真剣"],+ "厌恶": ["Disgust", "嫌悪"],+ "大笑": ["Laughter", "大笑い"],+ "害羞": ["Shy", "恥じらい"],+ "开心": ["Happy", "喜び"],+ "得意": ["Proud", "得意"],+ "恐惧": ["Fear", "恐怖"],+ "悲伤": ["Sadness", "悲しみ"],+ "搞怪": ["Playful", "おどけ"],+ "撩人": ["Flirtatious", "誘惑"],+ "疲惫": ["Tired", "疲労"],+ "含蓄": ["Restrained", "控えめ"],+ "中式": ["Chinese style", "中国風"],+ "坐具": ["Seating", "椅子・腰掛け"],+ "影棚结构": ["Studio structures", "スタジオ用構造物"],+ "桌案": ["Tables & desks", "テーブル・机"],+ "人像光位": ["Portrait light positions", "人物照明の位置"],+ "手持日用": ["Everyday handheld items", "手持ちの日用品"],+ "民族器物": ["Traditional objects", "伝統の道具"],+ "历史奇幻": ["Historical fantasy", "歴史・ファンタジー"],+ };++ const formats = [+ [/^连接成功:模型 (.+) 可用$/, (m,t,en) => en ? 'Connected. '+m[1]+' is available.' : '接続しました。'+m[1]+' を利用できます。'],+ [/^连接成功:共 (\d+) 个模型(?:,包含 (.+)|,但未找到 (.+)(中转可能不列出,可直接尝试))?$/, (m,t,en) => {+ const count=en?'Connected. Models: '+m[1]+'.':'接続しました。モデル数:'+m[1]+'。';+ if(m[2])return count+(en?' Includes '+m[2]+'.':m[2]+' を含みます。');+ if(m[3])return count+(en?' '+m[3]+' is unlisted. You can still try generating.':m[3]+' は一覧にありません。画像生成で確認できます。');+ return count;+ }],+ [/^姿势参考图((\d+)\/6 张)$/, (m,t,en) => en?'Pose reference images ('+m[1]+'/6)':'ポーズ参考画像('+m[1]+'/6枚)'],+ [/^完成 (\d+) 张,其中 (\d+) 张未存入生成记录,请立即下载$/, (m,t,en) => en ? m[1]+' images finished. '+m[2]+' could not be saved to history. Download them now.' : m[1]+'枚を生成しました。'+m[2]+'枚を履歴に保存できなかったため、今すぐダウンロードしてください。'],+ [/^(.+) · 衣姿 PoseWear$/, (m,t) => t(m[1]) + ' · PoseWear'],+ [/^将生成 (\d+) 张$/, (m,t,en) => en ? 'Images to generate: ' + m[1] : '生成予定:' + m[1] + '枚'],+ [/^还缺:(.+)$/, (m,t,en) => (en ? 'Still needed: ' : '必要な項目:') + m[1].split('、').map(t).join(en ? ', ' : '、')],+ [/^请先(.+)$/, (m,t,en) => (en ? 'First: ' : '先に設定:') + m[1].split('、').map(t).join(en ? ', ' : '、')],+ [/^(竖|横|方) (\d+:\d+)$/, (m,t,en) => ({竖:en?'Portrait':'縦',横:en?'Landscape':'横',方:en?'Square':'正方形'})[m[1]]+' '+m[2]],+ [/^(\d+) 秒(?: · 已完成 (\d+) \/ (\d+))?$/, (m,t,en) => m[1]+(en?' s':'秒')+(m[2]?' · '+m[2]+'/'+m[3]:'')],+ [/^逛(.+)$/, (m,t,en) => en?'Browse '+t(m[1]):t(m[1])+'を見る'],+ [/^已选\s*(\d+)\s*(?:项|张)?$/, (m,t,en) => en?m[1]+' selected':m[1]+'件選択中'],+ [/^已收藏 (\d+) 项$/, (m,t,en) => en?m[1]+' added to favorites':m[1]+'件をお気に入りに追加しました'],+ [/^已取消 (\d+) 项收藏$/, (m,t,en) => en?m[1]+' removed from favorites':m[1]+'件のお気に入りを解除しました'],+ [/^已(?:清空|删除) (\d+) 条(记录|收藏)$/, (m,t,en) => en?'Removed '+m[1]+' '+(m[2]==='记录'?'records':'favorites'):m[1]+'件削除しました'],+ [/^生成记录 · 第 (\d+) \/ (\d+) 项$/, (m,t,en) => (en?'History':'生成履歴')+' · '+m[1]+' / '+m[2]],+ [/^已复制「(.+)」$/, (m,t,en) => en?'Copied: '+t(m[1]):t(m[1])+'をコピーしました'],+ [/^打开大图[::]\s*(.+)$/, (m,t,en) => (en?'Open preview: ':'拡大表示:')+m[1]],+ [/^查看大图[::]\s*(.+)$/, (m,t,en) => (en?'Open image: ':'画像を開く:')+m[1]],+ [/^(移除|人物照片|生成结果)\s*[::]?\s+(.+)$/, (m,t) => t(m[1])+' '+m[2]],+ [/^完成 (\d+) 张[,,]已存入生成记录$/, (m,t,en) => en?m[1]+' saved to history':m[1]+'枚を履歴に保存しました'],+ [/^已加入姿势参考((\d+) 个)$/, (m,t,en) => en?'Pose added ('+m[1]+')':'参考ポーズに追加('+m[1]+'件)'],+ [/^已展开 (\d+) 个角度$/, (m,t,en) => en?m[1]+' angles selected':m[1]+'アングルを選択しました'],+ [/^组 · ([\d,]+) 张$/, (m,t,en) => en?'groups · '+m[1]+' images':'組 · '+m[1]+'枚'],+ [/^\/ ([\d,]+) 项$/, (m,t,en) => '/ '+m[1]+(en?' items':'件')],+ [/^\/ ([\d,]+) 组 · ([\d,]+) 张$/, (m,t,en) => '/ '+m[1]+(en?' groups · ':'組 · ')+m[2]+(en?' images':'枚')],+ [/^(\d+) (套服装|套动画服装|个姿势|个深度姿势|个人像|个表情|款发型|套历代服饰|个场景|种光影|件道具|件家具)$/, (m,t) => m[1]+' '+t(m[2].slice(1))],+ [/^(自由生图|虚拟试穿|试穿|生图|豆包 Seedream) · (.+)$/, (m,t) => t(m[1])+' · '+m[2]],+ ];++ const textState = new WeakMap();+ const attributeState = new WeakMap();+ const attributes = ['aria-label','placeholder','title','alt'];+ // Gallery titles, prompts, search history and filenames are data, even when they match a UI label.+ const preserve = 'script,style,pre,textarea,[translate=no],[contenteditable=true],.pbox p,.card h3,.card .sub,.hinfo,.pick b,#pkG span,#lbSim a,#lbSim b,#lbSide h2,#trayText,.sgc [data-q],.seoc a[href*="/tag/"]';+ let locale = 'zh';+ try {+ const saved = localStorage.getItem('pwUiLocale');+ if (Object.hasOwn(languages, saved)) locale = saved;+ } catch {}++ function translate(raw) {+ if (locale === 'zh' || typeof raw !== 'string') return raw;+ const key = raw.trim();+ if (!/[\u3400-\u9fff]/u.test(key)) return raw;+ const english = locale === 'en';+ let result = Object.hasOwn(translations,key) ? translations[key][english ? 0 : 1] : undefined;+ if (result === undefined) {+ for (const [pattern, render] of formats) {+ const match = key.match(pattern);+ if (match) { result = render(match,translate,english); break; }+ }+ }+ return result === undefined ? raw : raw.replace(key, () => result);+ }++ function localizeText(node) {+ const previous = textState.get(node);+ const original = previous && previous.shown === node.data ? previous.original : node.data;+ const shown = translate(original);+ if (node.data === shown) return;+ node.data = shown;+ textState.set(node,{original,shown});+ }++ function localizeAttributes(el) {+ let state = attributeState.get(el);+ for (const attr of attributes) {+ // Reference images can have filenames and user-authored labels as their alternative text.+ if (attr === 'alt' && !['wbAfter','wbBefore','tgViewImg'].includes(el.id)) continue;+ if (attr === 'title' && el.matches('.card h3,#pkG button,.pick b')) continue;+ if (attr === 'aria-label' && el.matches('.card .phk')) continue;+ const current = el.getAttribute(attr);+ if (current === null) continue;+ const previous = state?.[attr];+ const original = previous && previous.shown === current ? previous.original : current;+ const shown = translate(original);+ if (current === shown) continue;+ state ||= {};+ state[attr] = {original,shown};+ attributeState.set(el,state);+ el.setAttribute(attr,shown);+ }+ }++ function visit(node) {+ if (node.nodeType === Node.TEXT_NODE) { localizeText(node); return; }+ if (node.nodeType !== Node.ELEMENT_NODE || node.matches('[translate=no],script,style')) return;+ localizeAttributes(node);+ if (node.matches(preserve)) return;+ for (const child of node.childNodes) visit(child);+ }++ const observer = new MutationObserver(mutations => {+ for (const mutation of mutations) {+ const el = mutation.target.nodeType === Node.ELEMENT_NODE ? mutation.target : mutation.target.parentElement;+ if (!el || !el.isConnected) continue;+ if (mutation.type === 'attributes') {+ if (!el.closest('[translate=no]')) localizeAttributes(el);+ } else if (!el.closest(preserve)) {+ if (mutation.type === 'characterData') localizeText(mutation.target);+ else for (const child of mutation.addedNodes) visit(child);+ }+ }+ });++ const selector = document.getElementById('uiLocale');+ const menu = document.getElementById('languageMenu');+ function applyLocale() {+ observer.disconnect();+ document.documentElement.lang = languages[locale];+ selector.value = locale;+ visit(document.body);+ visit(document.querySelector('title'));+ if (locale !== 'zh') {+ const options = {subtree:true,childList:true,characterData:true,attributes:true,attributeFilter:attributes};+ observer.observe(document.body,options);+ observer.observe(document.querySelector('title'),{subtree:true,childList:true,characterData:true});+ }+ }+ selector.addEventListener('change', () => {+ if (!Object.hasOwn(languages,selector.value)) return;+ locale = selector.value;+ try {localStorage.setItem('pwUiLocale',locale);} catch {}+ applyLocale();+ });+ document.addEventListener('pointerdown', event => {if (!menu.contains(event.target)) menu.open=false;});+ menu.addEventListener('keydown', event => {+ if (event.key === 'Escape' && menu.open) {+ event.stopPropagation();+ menu.open = false;+ menu.querySelector('summary').focus();+ }+ });+ window.PWLocale = {t:translate};+ applyLocale();+})();diff --git a/src/image-providers.js b/src/image-providers.jsnew file mode 100644index 0000000..567ba86--- /dev/null+++ b/src/image-providers.js@@ -0,0 +1,309 @@+'use strict';++// Browser transports shared by the full studio and the floating workbench.+window.PoseWearImageProviders = (() => {+ const providers = {+ openai: {+ name: 'OpenAI', base: 'https://api.openai.com/v1', model: 'gpt-image-1',+ models: ['gpt-image-1', 'gpt-image-1-mini', 'gpt-image-2', 'dall-e-2']+ },+ gemini: {+ name: 'Gemini', base: 'https://generativelanguage.googleapis.com/v1beta', model: 'gemini-2.5-flash-image',+ models: ['gemini-2.5-flash-image', 'gemini-3-pro-image-preview', 'gemini-3.1-flash-image']+ },+ seedream: {+ name: '豆包 Seedream', base: 'https://ark.cn-beijing.volces.com/api/v3', model: 'doubao-seedream-5-5-261028',+ models: ['doubao-seedream-5-5-261028', 'doubao-seedream-5-0-flash-260915', 'doubao-seedream-4-5-251128', 'doubao-seedream-4-0-250828']+ },+ custom: {+ name: '自定义中转', base: '', model: 'gpt-image-1',+ models: ['gpt-image-1', 'gpt-image-2', 'grok-imagine-image-2.0', 'gemini-2.5-flash-image', 'flux-kontext-pro', 'qwen-image-edit', 'doubao-seedream-4-0-250828']+ }+ };++ const officialHost = /^(api\.openai\.com|generativelanguage\.googleapis\.com|ark\.[a-z0-9-]+\.(volces|bytepluses)\.com)$/;+ const imageSizes = { '2:3': '1024x1536', '3:4': '1024x1536', '9:16': '1024x1536', '1:1': '1024x1024', '4:3': '1536x1024', '16:9': '1536x1024' };+ const seedreamSizes = { auto: '1728x2304', '2:3': '1664x2496', '3:4': '1728x2304', '9:16': '1440x2560', '1:1': '2048x2048', '4:3': '2304x1728', '16:9': '2560x1440' };+ const textOnlyWarning = '当前模型未接收参考图,本次仅按提示词生成。';++ function protocol(settings) {+ if (settings.prov === 'openai') return 'edits';+ if (settings.prov === 'custom') return settings.proto;+ return settings.prov;+ }++ function apiBase(settings) {+ const base = (settings.base || providers[settings.prov].base).trim().replace(/\/+$/, '');+ if (protocol(settings) === 'gemini' && /\/v1(beta|alpha)?$/.test(base)) return base;+ if (settings.prov === 'gemini') return base + '/v1beta';+ if (settings.prov === 'seedream') return base;+ return /\/v\d+$/.test(base) ? base : base + '/v1';+ }++ function request(settings, path, options) {+ const url = apiBase(settings) + path;+ const headers = new Headers(options.headers);+ if (protocol(settings) === 'gemini') headers.set('x-goog-api-key', settings.key);+ else headers.set('Authorization', 'Bearer ' + settings.key);+ if (!settings.proxy) return fetch(url, { ...options, headers });+ headers.set('x-target-url', url);+ if (settings.prov === 'custom' || !officialHost.test(new URL(url).hostname)) headers.set('x-proxy-custom', '1');+ return fetch('/api/proxy', { ...options, headers });+ }++ function redact(text, key) {+ const value = String(text);+ return key ? value.split(key).join('***') : value;+ }++ const safetyReason = /safety system|safety_violations|moderation_blocked|content_policy_violation|content policy|SensitiveContent|sensitive content|PROHIBITED_CONTENT|IMAGE_SAFETY|\bSAFETY\b|BLOCKLIST|SPII|blocked by|内容安全|敏感/i;+ const categories = [+ [/minor|child|CSAM/i, '涉及未成年人'], [/sexual|SEXUALLY_EXPLICIT|nudity|porn|色情/i, '性感/暴露内容'],+ [/violen|gore|血腥|暴力/i, '暴力或血腥'], [/self-?harm/i, '自残'], [/hate|HATE_SPEECH/i, '仇恨'],+ [/harass/i, '骚扰'], [/illicit|DANGEROUS/i, '危险或违法内容'], [/SPII|personal/i, '个人隐私信息'],+ [/copyright|RECITATION|trademark/i, '版权内容']+ ];++ function safetyError(message, data, requestId, key) {+ const text = message + ' ' + JSON.stringify(data || '');+ if (!safetyReason.test(text)) return null;+ const error = Error(redact(message || 'safety', key));+ error.safe = {+ cats: categories.filter(([match]) => match.test(text)).map(([, label]) => label),+ where: /InputImage|input image/i.test(text) ? 'in' : /OutputImage|output/i.test(text) ? 'out' : '',+ rid: redact(requestId || text.match(/req_[A-Za-z0-9]+/)?.[0] || '', key)+ };+ error.raw = redact(message.trim(), key) || redact(text, key).slice(0, 600);+ error.zh = '被服务商的安全审核拦下了';+ return error;+ }++ const statusMessages = {+ 400: '请求参数有误:常见原因是模型不支持参考图、画幅尺寸不对或图片格式不支持,可换个模型或画幅再试',+ 401: '密钥无效或已过期,请检查 API Key',+ 403: '没有权限:密钥无此模型权限、账户未验证,或所在地区不受支持',+ 404: '地址或模型不存在:请检查 Base URL 和模型名',+ 413: '图片太大,请换一张更小的照片',+ 429: '请求过于频繁或额度已用完,请稍后再试或检查账户余额',+ 500: '服务商内部错误,请稍后重试', 502: '网关错误(中转服务不可用)',+ 503: '服务暂时不可用,请稍后重试', 504: '服务商响应超时,请重试'+ };++ function apiError(reply, data, settings) {+ const detail = data?.error?.message || data?.error?.status || data?.error || data?.message || reply.statusText;+ const message = redact(typeof detail === 'string' ? detail : JSON.stringify(detail), settings.key);+ const requestId = data?.error?.request_id || reply.headers.get('x-request-id');+ const blocked = safetyError(message, data, requestId, settings.key);+ if (blocked) {+ blocked.status = reply.status;+ return blocked;+ }+ let reason = statusMessages[reply.status] || '请求失败(HTTP ' + reply.status + ')';+ const unsupported = message.match(/Argument not supported:\s*(\w+)/i);+ if (/API_KEY_INVALID|API key not valid|invalid api key|Incorrect API key|AuthenticationError|InvalidApiKey/i.test(message + ' ' + JSON.stringify(data))) {+ reason = statusMessages[401];+ } else if (unsupported) {+ reason = '该服务商不支持 ' + unsupported[1] + ' 参数:当前接口协议与它的规格对不上,请检查「接口协议」设置(xAI 请改选 xAI 协议)';+ }+ const error = Error(message);+ error.status = reply.status;+ error.zh = reason + (message ? '\n服务商返回:' + message.slice(0, 300) : '');+ return error;+ }++ function nice(error) {+ if (error.name === 'AbortError') return '已取消';+ if (error instanceof TypeError) return '无法连接到服务商:网络不通,或该地址不允许浏览器跨域访问(CORS)。\n可在 API 设置中开启「通过本站代理转发」。';+ return error.zh || error.message || String(error);+ }++ async function testConnection(settings, model, signal) {+ const gemini = protocol(settings) === 'gemini';+ const path = gemini ? '/models/' + encodeURIComponent(model) : '/models';+ const reply = await request(settings, path, { method: 'GET', signal });+ const data = await reply.json().catch(() => null);+ if (!reply.ok) {+ if (settings.prov === 'seedream' && reply.status === 404) {+ if (reply.headers.get('content-type')?.includes('text/html')) {+ throw Error('本站代理未生效:/api/proxy 返回的是网站静态页面而不是接口响应,Seedream 暂时连不上,请稍后再试或联系站长');+ }+ return '地址可达,方舟未提供模型列表。请通过生成验证密钥与模型。';+ }+ throw apiError(reply, data, settings);+ }+ if (gemini && (data?.name || data?.displayName)) return '连接成功:模型 ' + (data.displayName || model) + ' 可用';+ if (gemini || !Array.isArray(data?.data) || data.data.some(entry => typeof entry?.id !== 'string')) {+ throw Error('接口未返回模型信息,请检查 Base URL 与接口协议。');+ }+ const ids = data.data.map(entry => entry.id);+ let message = '连接成功:共 ' + ids.length + ' 个模型';+ if (ids.length) message += ids.includes(model) ? ',包含 ' + model : ',但未找到 ' + model + '(中转可能不列出,可直接尝试)';+ return message;+ }++ async function readResponse(job, path, body) {+ const options = { method: 'POST', body, signal: job.signal };+ if (!(body instanceof FormData)) {+ options.headers = { 'Content-Type': 'application/json' };+ options.body = JSON.stringify(body);+ }+ const reply = await request(job.settings, path, options);+ const data = await reply.json().catch(() => null);+ job.signal.throwIfAborted();+ if (!reply.ok) throw apiError(reply, data, job.settings);+ return data;+ }++ function base64(blob) {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result.slice(reader.result.indexOf(',') + 1));+ reader.onerror = () => reject(reader.error);+ reader.readAsDataURL(blob);+ });+ }++ async function dataURL(blob) {+ return 'data:' + (blob.type || 'image/jpeg') + ';base64,' + await base64(blob);+ }++ async function resultBlob(data, job) {+ const image = data?.data?.[0];+ if (image?.b64_json) return (await fetch('data:image/png;base64,' + image.b64_json)).blob();+ if (!image?.url) throw Error('服务商没有返回图片数据' + (data?.error?.message ? ':' + redact(data.error.message, job.settings.key) : ''));+ const { url } = image;+ let reply = await fetch(url, { signal: job.signal }).catch(() => null);+ if (!reply?.ok) {+ job.signal.throwIfAborted();+ reply = await fetch('/api/proxy', {+ signal: job.signal, headers: { 'x-target-url': url, 'x-proxy-kind': 'image' }+ }).catch(() => null);+ }+ job.signal.throwIfAborted();+ if (!reply?.ok) throw Error('结果图片无法在浏览器中下载,请直接打开:' + redact(url, job.settings.key));+ return reply.blob();+ }++ async function generateLocal({ images, prompt, ratio, checkpoint, signal }) {+ const form = new FormData();+ form.set('prompt', prompt);+ if (checkpoint) form.set('checkpoint', checkpoint);+ if (ratio !== 'auto') {+ const [width, height] = ratio.split(':').map(Number);+ const unit = 1024 / Math.max(width, height);+ const pixels = n => Math.round(n * unit / 8) * 8;+ form.set('size', pixels(width) + 'x' + pixels(height));+ }+ images.forEach((image, i) => form.append('image[]', image, 'reference-' + (i + 1) + '.jpg'));+ const reply = await fetch('/api/local/generate', { method: 'POST', headers: { 'x-posewear-local': '1' }, body: form, signal });+ if (!reply.ok) throw Error(await reply.text());+ return { blob: await reply.blob() };+ }++ async function generateGemini(job) {+ const parts = [{ text: job.prompt }];+ for (const image of job.images) {+ parts.push({ inline_data: { mime_type: image.type || 'image/jpeg', data: await base64(image) } });+ }+ const generationConfig = { responseModalities: ['TEXT', 'IMAGE'] };+ if (job.ratio !== 'auto') generationConfig.imageConfig = { aspectRatio: job.ratio };+ const data = await readResponse(job, '/models/' + encodeURIComponent(job.model) + ':generateContent', {+ contents: [{ role: 'user', parts }], generationConfig+ });+ const candidates = data?.candidates || [];+ const output = candidates.flatMap(candidate => candidate.content?.parts || []);+ const image = output.map(part => part.inlineData || part.inline_data).find(part => part?.data);+ if (image) return { blob: await (await fetch('data:' + (image.mimeType || image.mime_type || 'image/png') + ';base64,' + image.data)).blob() };++ const candidate = candidates[0];+ const reason = data?.promptFeedback?.blockReason || candidate?.finishReason;+ if (reason && /SAFETY|PROHIBITED|BLOCKLIST|SPII|OTHER/i.test(reason)) {+ const ratings = (candidate?.safetyRatings || []).filter(rating => rating.blocked || /HIGH|MEDIUM/.test(rating.probability));+ const detail = [reason, ...ratings.map(rating => rating.category), candidate?.finishMessage].filter(Boolean).join(' ');+ const blocked = safetyError(detail, null, data?.responseId, job.settings.key);+ if (blocked) throw blocked;+ }+ const text = redact(output.map(part => part.text).filter(Boolean).join(' '), job.settings.key);+ throw Error('模型没有返回图片' + (reason ? '(' + reason + ',可能触发了安全策略)' : '') + (text ? '\n模型回复:' + text.slice(0, 300) : ''));+ }++ async function generations(job, params, images = job.images) {+ const body = { model: job.model, prompt: job.prompt, n: 1, ...params };+ if (images.length) body.image = await Promise.all(images.map(dataURL));+ return resultBlob(await readResponse(job, '/images/generations', body), job);+ }++ async function generateSeedream(job) {+ const params = { size: seedreamSizes[job.ratio] || seedreamSizes.auto, response_format: 'b64_json', watermark: false };+ if (/seedream-4/.test(job.model)) params.sequential_image_generation = 'disabled';+ try {+ return { blob: await generations(job, params) };+ } catch (error) {+ if (!job.images.length || error.safe || error.status !== 400 || !/image|参考/i.test(error.message)) throw error;+ return { blob: await generations(job, params, []), warn: textOnlyWarning };+ }+ }++ async function generateXai(job) {+ const body = { model: job.model, prompt: job.prompt, n: 1, response_format: 'b64_json' };+ if (job.ratio !== 'auto') body.aspect_ratio = job.ratio;+ const urls = await Promise.all(job.images.slice(0, 5).map(dataURL));+ if (urls.length === 1) body.image = { url: urls[0] };+ if (urls.length > 1) body.images = urls.map(url => ({ url }));+ const path = urls.length ? '/images/edits' : '/images/generations';+ return {+ blob: await resultBlob(await readResponse(job, path, body), job),+ warn: job.images.length > 5 ? 'xAI 参考图最多 5 张,已只发送前 5 张。' : ''+ };+ }++ async function edits(job, size, field) {+ const form = new FormData();+ const single = job.model === 'dall-e-2';+ form.set('model', job.model);+ form.set('prompt', job.prompt);+ const images = single ? job.images.slice(0, 1) : job.images;+ images.forEach((image, i) => form.append(field, image, 'ref-' + (i + 1) + '.jpg'));+ form.set('n', '1');+ form.set('size', single && size === 'auto' ? '1024x1024' : size);+ return resultBlob(await readResponse(job, '/images/edits', form), job);+ }++ async function generateOpenAI(job) {+ const size = imageSizes[job.ratio] || (/^gpt-image/.test(job.model) ? 'auto' : '1024x1024');+ if (protocol(job.settings) === 'json' || !job.images.length) return { blob: await generations(job, { size }) };+ const field = job.settings.prov === 'custom' ? job.settings.field : 'image[]';+ try {+ return { blob: await edits(job, size, field) };+ } catch (error) {+ if (error.name === 'AbortError' || error.safe || /Argument not supported/i.test(error.message)) throw error;+ if (error.status === 400 && /image/i.test(error.message) && !/safety|moderation|reject/i.test(error.message)) {+ const alternate = field === 'image[]' ? 'image' : 'image[]';+ try {+ return { blob: await edits(job, size, alternate), warn: '已自动改用另一种图片字段名重试成功。' };+ } catch (retryError) {+ if (retryError.name === 'AbortError' || retryError.safe || retryError.status !== 400) throw retryError;+ }+ }+ if (![404, 405, 415, 501].includes(error.status) && !/edits|not supported|unsupported|no such|invalid url/i.test(error.message)) throw error;+ }+ try {+ return { blob: await generations(job, { size }), warn: '该接口不支持 images/edits,已自动改用 images/generations(JSON 多图)。' };+ } catch (error) {+ if (error.safe || error.status !== 400) throw error;+ return { blob: await generations(job, { size }, []), warn: textOnlyWarning };+ }+ }++ function generateImage(job) {+ switch (protocol(job.settings)) {+ case 'local': return generateLocal(job);+ case 'gemini': return generateGemini(job);+ case 'seedream': return generateSeedream(job);+ case 'xai': return generateXai(job);+ default: return generateOpenAI(job);+ }+ }++ return { providers, generateImage, testConnection, nice };+})();diff --git a/src/index.html b/src/index.htmlindex 3e9fbd6..7992e4f 100644--- a/src/index.html+++ b/src/index.html@@ -1,44 +1,67 @@-<!doctype html><html lang="zh-CN" data-theme="light"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">+<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><title>姿势库 · 衣姿 PoseWear</title><meta name="description" content="288 个人体姿势(1439 张多角度图)、1407 套服装、1760 套动画服装和 1499 张人像参考图,另有表情、发型、历代、场景、光影、道具、家具扩展库,附中英文提示词,可上传照片试穿,也可在图库里直接生图。"><meta name="keywords" content="绘画参考,姿势参考,服装参考,提示词,Stable Diffusion,Midjourney,姿势库,服装库"><meta name="theme-color" content="#ffffff"><meta property="og:title" content="衣姿 PoseWear:姿势和服装参考图"><meta property="og:description" content="288 个姿势、1407 套服装、1760 套动画服装、1499 张人像,附中英文提示词,可上传照片试穿。"><meta property="og:type" content="website"><meta property="og:image" content="https://posewear.pages.dev/og.png"><meta property="og:url" content="https://posewear.pages.dev/"><link rel="canonical" href="https://posewear.pages.dev/"><meta name="twitter:card" content="summary_large_image"><link rel="icon" href="favicon.svg" type="image/svg+xml"><link rel="apple-touch-icon" href="apple-touch-icon.png"><link rel="manifest" href="manifest.webmanifest">+<script src="theme.js"></script><link rel="preload" href="poses.json" as="fetch" crossorigin><link rel="stylesheet" href="style.css">-<script>try{var d=document.documentElement;d.dataset.theme=localStorage.theme||'light';d.dataset.lang=JSON.parse(localStorage.lang||'"zh"');if(localStorage.introX)d.classList.add('nointro');if(localStorage.annV2)d.classList.add('noann')}catch(e){}</script></head><body>+<script>try{document.documentElement.dataset.lang=JSON.parse(localStorage.lang||'"zh"');}catch(e){}</script></head><body><a class="skip" href="#grid">跳到内容</a><header class="top" id="top"><a class="brand" href="#pose" aria-label="衣姿 PoseWear 首页"><span class="mark" aria-hidden="true"><svg viewBox="0 0 32 32"><circle cx="16" cy="6.6" r="4" fill="currentColor"/><path d="M16 13.4 3.4 25.6h25.2z" fill="none" stroke="currentColor" stroke-width="3.4" stroke-linejoin="round"/></svg></span><span class="wm"><b>衣姿</b><small>PoseWear</small></span></a>-<div class="search"><svg class="sic" viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg><input id="q" type="search" placeholder="搜姿势、颜色、单品" autocomplete="off" aria-label="搜索"><button id="qx" class="qx" aria-label="清除搜索" hidden>✕</button></div><div class="tools"><button id="adultSw" class="asw" role="switch" aria-checked="false" aria-label="显示成人向内容(18+)" title="成人向内容,默认关闭"><span class="trk" aria-hidden="true"><span class="kn"></span></span><b>18+</b></button><div class="seg" role="group" aria-label="描述语言"><button data-lang="zh">中</button><button data-lang="en">EN</button></div><button id="help" class="icon" title="快捷键(?)" aria-label="快捷键帮助"><svg viewBox="0 0 24 24"><rect x="3" y="6" width="18" height="12" rx="2"/><path d="M7 10h.01M11 10h.01M15 10h.01M7 14h10"/></svg></button><button id="theme" class="icon" title="切换深浅色(T)" aria-label="切换深浅色"><svg class="sun" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg><svg class="moon" viewBox="0 0 24 24"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg></button><a class="icon" href="https://github.com/atuizz/posewear" target="_blank" rel="noopener" title="GitHub 开源仓库" aria-label="GitHub 开源仓库"><svg class="gh" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg></a></div>-<nav class="tabs" role="tablist" aria-label="栏目"><span class="ind" aria-hidden="true"></span><button role="tab" data-tab="pose">姿势<i id="nPose"></i></button><button role="tab" data-tab="depth">深度姿势<i id="nDepth"></i></button><button role="tab" data-tab="costume">服装<i id="nCos"></i></button><button role="tab" data-tab="anime">动画服装<i id="nAni"></i></button><button role="tab" data-tab="portrait">人像<i id="nPor"></i></button><button role="tab" data-tab="expr">表情<i id="nExp"></i></button><button role="tab" data-tab="hair">发型<i id="nHair"></i></button><button role="tab" data-tab="dyn">历代<i id="nDyn"></i></button><button role="tab" data-tab="scene">场景<i id="nSce"></i></button><button role="tab" data-tab="light">光影<i id="nLig"></i></button><button role="tab" data-tab="prop">道具<i id="nPro"></i></button><button role="tab" data-tab="furn">家具<i id="nFur"></i></button><button role="tab" data-tab="studio" class="st">试穿</button><button role="tab" data-tab="fav">收藏<i id="nFav"></i></button><button role="tab" data-tab="recent">最近<i id="nRec"></i></button><button role="tab" data-tab="history">生成记录<i id="nHist"></i></button></nav></header>-<section class="hero" id="hero"><div class="hero-in"><p class="eyebrow">画画、拍照、出图时用的参考</p><h1 id="heroT">姿势和服装<br>参考图</h1>-<div class="hero-r"><p class="lead" id="heroP">每个姿势有多个角度,每套服装都附中英文描述。可以收藏、组合,也能上传自己的照片试穿。</p>-<div class="stats"><div><b data-n="288">0</b><span>组姿势</span></div><div><b data-n="1439">0</b><span>张角度图</span></div><div><b data-n="1407">0</b><span>套服装</span></div><div><b data-n="1760">0</b><span>套动画服装</span></div><div><b data-n="1499">0</b><span>张人像</span></div><div><b data-n="95">0</b><span>条表情</span></div><div><b data-n="122">0</b><span>款发型</span></div><div><b data-n="57">0</b><span>套历代服饰</span></div><div><b data-n="64">0</b><span>个场景</span></div><div><b data-n="50">0</b><span>种光影</span></div><div><b data-n="32">0</b><span>件道具</span></div><div><b data-n="41">0</b><span>件家具</span></div></div></div></div></section>-<aside id="depthNote" class="dnote" hidden><div class="dnote-in"><p><span class="dtag">非官方汉化</span>素材来自 <a href="https://ai-pose-depth-gallery.pages.dev/" target="_blank" rel="noopener">ai-pose-depth-gallery</a>,作者<a href="https://x.com/giaaibusi" target="_blank" rel="noopener">ギア</a>(<a href="https://x.com/giaaibusi" target="_blank" rel="noopener">https://x.com/giaaibusi</a>)。</p><p class="dsub">图片由原站托管,本站不保存。双人互动默认隐藏,需打开右上角「18+」并确认已满 18 岁。</p></div></aside>-<aside id="srcNote" class="dnote" hidden></aside>-<div id="intro" class="intro"><p><b>姿势、服装、动画服装、人像参考图</b><span>画画、拍照、AI 出图时用。点开看大图和中英文描述,喜欢就收藏;也可以上传自己的照片试穿。</span></p><button class="sm" data-go="studio">去试穿</button><button id="introX" class="ix" aria-label="不再显示这条说明">✕</button></div>-<div id="ann" class="annbar"><p><b>更新 · 七个新栏目与悬浮生图</b><span>新增表情、发型、历代、场景、光影、道具、家具七个栏目,动画服装扩充至 1760 套,试穿台新增「生成记录」页。右下角有常驻的悬浮生图工作台,随时添加素材、拼装生图。</span></p><button class="sm" data-go="hair">去看看</button><button id="annX" class="ix" aria-label="关闭公告">✕</button></div>+<nav class="tabs" aria-label="栏目">+<details class="shell-menu" name="header-popover" id="libraryMenu"><summary class="nav-trigger"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round"><rect x="3.5" y="3.5" width="6.5" height="6.5" rx="1.6"/><rect x="14" y="3.5" width="6.5" height="6.5" rx="1.6"/><rect x="3.5" y="14" width="6.5" height="6.5" rx="1.6"/><rect x="14" y="14" width="6.5" height="6.5" rx="1.6"/></svg><span id="libraryLabel">姿势库</span><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round"><path d="m8 10 4 4 4-4"/></svg></summary>+<div class="shell-pop library-menu stats"><section><h2>姿态</h2><button type="button" data-tab="pose"><span>姿势</span><i class="nav-count" id="nPose"><b data-stat="pose" data-n="288">0</b></i></button><button type="button" data-tab="depth"><span>深度姿势</span><i class="nav-count" id="nDepth"><b data-stat="depth" data-n="288">0</b></i></button></section>+<section><h2>人物造型</h2><button type="button" data-tab="portrait"><span>人像</span><i class="nav-count" id="nPor"><b data-stat="por" data-n="1499">0</b></i></button><button type="button" data-tab="expr"><span>表情</span><i class="nav-count" id="nExp"><b data-stat="exp" data-n="95">0</b></i></button><button type="button" data-tab="hair"><span>发型</span><i class="nav-count" id="nHair"><b data-stat="hair" data-n="122">0</b></i></button></section>+<section><h2>服饰</h2><button type="button" data-tab="costume"><span>服装</span><i class="nav-count" id="nCos"><b data-stat="cos" data-n="1407">0</b></i></button><button type="button" data-tab="anime"><span>动画服装</span><i class="nav-count" id="nAni"><b data-stat="ani" data-n="1760">0</b></i></button><button type="button" data-tab="dyn"><span>历代服饰</span><i class="nav-count" id="nDyn"><b data-stat="dyn" data-n="57">0</b></i></button></section>+<section><h2>环境与物件</h2><button type="button" data-tab="scene"><span>场景</span><i class="nav-count" id="nSce"><b data-stat="scene" data-n="64">0</b></i></button><button type="button" data-tab="light"><span>光影</span><i class="nav-count" id="nLig"><b data-stat="light" data-n="50">0</b></i></button><button type="button" data-tab="prop"><span>道具</span><i class="nav-count" id="nPro"><b data-stat="prop" data-n="32">0</b></i></button><button type="button" data-tab="furn"><span>家具</span><i class="nav-count" id="nFur"><b data-stat="furn" data-n="41">0</b></i></button></section>+</div></details>+<button type="button" class="nav-trigger" data-tab="studio"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round"><path d="m12 3 1.7 5.3L19 10l-5.3 1.7L12 17l-1.7-5.3L5 10l5.3-1.7zM19 15v5m-2.5-2.5h5"/></svg><span>工作台</span></button>+<details class="shell-menu" name="header-popover" id="personalMenu"><summary class="nav-trigger"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round"><path d="M6.5 4.5a1 1 0 0 1 1-1h9a1 1 0 0 1 1 1v16L12 17l-5.5 3.5z"/></svg><span id="personalLabel">我的</span><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round"><path d="m8 10 4 4 4-4"/></svg></summary>+<div class="shell-pop personal-menu"><button type="button" data-tab="fav">收藏<i id="nFav"></i></button><button type="button" data-tab="recent">最近<i id="nRec"></i></button><button type="button" data-tab="history">生成记录<i id="nHist"></i></button></div></details>+</nav>+<div class="search"><svg class="sic" viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg><input id="q" type="search" placeholder="搜姿势、颜色、单品" autocomplete="off" aria-label="搜索"><button id="qx" class="qx" aria-label="清除搜索" hidden>✕</button><button id="qDone" type="button">完成</button></div><div class="tools"><button id="adultSw" class="asw" role="switch" aria-checked="false" aria-label="显示成人向内容(18+)" title="成人向内容,默认关闭"><span class="trk" aria-hidden="true"><span class="kn"></span></span><b>18+</b></button><details name="header-popover" id="languageMenu" class="lang-menu"><summary class="icon" aria-label="语言设置" title="语言设置"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"/><ellipse cx="12" cy="12" rx="4" ry="9"/><path d="M3 12h18"/></svg></summary><div class="lang-panel"><label for="uiLocale">界面语言</label><select id="uiLocale" translate="no"><option value="zh">简体中文</option><option value="en">English</option><option value="ja">日本語</option></select><span>素材描述语言</span><div class="seg" role="group" aria-label="描述语言"><button data-lang="zh" lang="zh" translate="no">中文</button><button data-lang="en" lang="en" translate="no">English</button></div><label class="copy-pref"><input type="checkbox" id="copyRefs" checked><span>复制时附参考图</span></label></div></details><details id="themeMenu" class="shell-menu" name="header-popover"><summary id="theme" class="icon" title="外观(T)" aria-label="外观"><svg aria-hidden="true" class="sun" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg><svg aria-hidden="true" class="moon" viewBox="0 0 24 24"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg></summary>+<div class="shell-pop theme-pop" role="group" aria-label="外观">+<button type="button" data-theme-choice="system" aria-pressed="false"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="18" height="13" rx="2.5"/><path d="M8 21h8m-4-4v4"/></svg><span>跟随系统</span></button>+<button type="button" data-theme-choice="light" aria-pressed="false"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg><span>浅色</span></button>+<button type="button" data-theme-choice="dark" aria-pressed="false"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg><span>深色</span></button>+</div></details><details id="noticeMenu" class="shell-menu" name="header-popover"><summary class="icon" aria-label="通知" title="通知"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round"><path d="M5 16c1.4-1.4 1.8-3.4 1.8-6a5.2 5.2 0 0 1 10.4 0c0 2.6.4 4.6 1.8 6l.6 1H4.4zM10 20a2.5 2.5 0 0 0 4 0"/></svg></summary>+<section class="shell-pop notice-pop" aria-label="通知"><h2>通知</h2><button id="noticeReload" class="sm" hidden>更新已就绪,刷新页面</button>+<p id="noticeAction" hidden></p><article id="releaseNotice"><strong>图库更新</strong><p>复制提示词可附参考图链接。</p></article>+<button id="help" class="notice-help" type="button">快捷键</button></section></details></div>+</header>+<h1 class="vh" id="collectionTitle">姿势库</h1><section class="bar" id="bar">-<div class="tbar"><span id="count" aria-live="polite"></span><button id="fBtn" class="fbtn"><svg viewBox="0 0 24 24"><path d="M4 6h16M7 12h10M10 18h4"/></svg>更多筛选<b id="fN"></b></button><div id="active"></div><button id="clearAll" class="ghost sm" hidden>清空全部</button><span class="sp"></span>+<div class="tbar"><span id="count" aria-live="polite"></span><button id="fBtn" class="fbtn" aria-label="更多筛选" title="更多筛选" aria-controls="filters" aria-expanded="false"><svg viewBox="0 0 24 24"><path d="M4 6h16M7 12h10M10 18h4"/></svg><span>更多筛选</span><b id="fN"></b></button><div id="active"></div><button id="clearAll" class="ghost sm" hidden>清空全部</button><span class="sp"></span><span id="favTools" hidden><button id="exp" class="sm">导出收藏</button><button id="imp" class="sm">导入</button><button id="clrFav" class="sm">清空</button><input id="impF" type="file" accept=".json" hidden></span><button id="clrRec" class="sm" hidden>清空记录</button><select id="sort" aria-label="排序"><option value="def">默认排序</option><option value="id">编号倒序</option><option value="shuf">随机打乱</option><option value="fav">收藏优先</option><option value="rank" hidden>人气榜</option></select>-<button id="rand" class="pri">随机一个</button></div></section>+<button id="rand" class="pri" aria-label="随机一个" title="随机一个"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 6h3c4 0 7 12 11 12h4m-4-4 4 4-4 4M3 18h3c1.6 0 3.1-1.8 4.6-4.2M13.3 9.9C14.7 7.6 16 6 17.5 6H21m-4-4 4 4-4 4"/></svg><span>随机一个</span></button></div></section><div id="filters" class="filters"></div>-<details id="porNote" class="pnote" hidden><summary>人像使用提示与规则</summary><ul><li>在 AI 工具的「角色参考 / 脸部参考」里载入这张图即可。</li><li>想统一长相用「正脸」;参考服装、发质和整体氛围用「生活照」。</li><li>一直用同一张图,生成的脸会更稳定。下载原图 PNG 能保留更多细节。</li><li>CC0 1.0:可商用、可修改,无需署名。均为 AI 生成的虚构人物,不得用来冒充真人或用于违背公序良俗的用途。原作者希望不要把图片原样批量转载。</li></ul></details><main id="grid" class="grid" aria-live="polite"><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div></main><div id="sentinel"></div>+<main id="grid" class="grid" aria-live="polite"><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div><div class="skel"></div></main><div id="sentinel"></div><div id="empty" hidden><div class="emo">🔍</div><h3 id="emptyT">没有找到匹配的内容</h3><p id="emptyP">换个关键词,或清空筛选条件试试</p><div id="sugg"></div><div id="emptyGo" class="ego"></div><button id="reset" class="pri">清空筛选</button></div>-<section id="studio" hidden aria-labelledby="stT"><h2 id="stT" class="vh">试穿</h2>+<section id="studio" hidden aria-labelledby="stT">+<header class="studio-head"><h1 id="stT" tabindex="-1">创作工作台</h1><div class="seg modes" role="group" aria-label="工作模式"><button data-mode="tryon">试穿</button><button data-mode="gen">生图</button></div></header><div class="st-app">-<aside class="st-l">-<div class="seg modes" role="group" aria-label="工作模式"><button data-mode="tryon">用我的照片</button><button data-mode="gen">没有照片</button></div>-<p class="lead" id="stLead"></p>-<div class="step" data-s="1"><div class="sh"><i>1</i><b id="s1T">人物照片</b><small id="s1R"></small><span class="sp"></span><button class="lnk" data-pick="portrait">从人像库选</button></div><div class="persons" id="wbPersons"></div><label class="drop" id="wbDrop" tabindex="0"><input type="file" id="wbFile" accept="image/*" multiple hidden><span class="dz"><svg viewBox="0 0 24 24"><path d="M12 16V4m0 0-4 4m4-4 4 4M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3"/></svg><b>上传人物照</b><small>点击、拖入或粘贴</small></span></label><div id="wbChar"><div class="sub0">模特类型</div><div class="chips" id="wbChars"></div><textarea id="wbCharTxt" rows="2" placeholder="自定义模特描述,例如:25 岁成年女性,黑色长直发,清淡妆容,身材纤细"></textarea></div></div>-<div class="step" data-s="2"><div class="sh"><i>2</i><b>服装</b><small id="s2R">必选</small><span class="sp"></span><label class="lnk btn">上传图<input type="file" id="wbGFile" accept="image/*" multiple hidden></label><button class="lnk" data-pick="costume">从库中选</button><button class="lnk" data-pick="anime">从动画服装选</button></div><div class="slot" id="wbG"></div></div>-<div class="step" data-s="3"><div class="sh"><i>3</i><b>姿势</b><small id="s3R">可选</small><span class="sp"></span><button class="lnk" data-pick="pose">从库中选</button></div><div class="slot" id="wbPo"></div><div class="row r3"><button class="sm ghost" id="wbAllAng" hidden>全部角度</button><span class="sp"></span><div class="seg sm" id="wbBatch" role="group" aria-label="多姿势出图方式" hidden><button data-bm="each">分开出</button><button data-bm="sheet">拼一张</button></div></div></div>-<div class="step"><div class="sh"><i>4</i><b>表情</b><small>可选</small><span class="sp"></span><button class="lnk" data-pick="expr">从表情库选</button></div><div class="slot" id="wbEx"></div></div>+<aside class="st-l" aria-label="参考素材">+<div class="primary-materials">+<section class="step person-step" data-s="1" aria-labelledby="s1T">+<div class="sh"><svg class="material-icon" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="8" r="3.5"/><path d="M5 21v-2a7 7 0 0 1 14 0v2"/></svg><b id="s1T">人物</b><span class="sp"></span><button class="lnk pick-more" data-pick="portrait" hidden>从人像库选</button><label class="lnk upload-link" id="wbDrop" tabindex="0" role="button" title="上传人物照" aria-label="上传人物照">上传<input type="file" id="wbFile" accept="image/*" multiple hidden></label></div>+<div class="persons" id="wbPersons"></div><button class="empty0" id="wbPortraitPick" data-pick="portrait"><span><b>选择人物</b></span></button>+<details id="wbChar"><summary>模特类型</summary><div class="chips" id="wbChars"></div><textarea id="wbCharTxt" rows="2" placeholder="自定义模特描述,例如:25 岁成年女性,黑色长直发,清淡妆容,身材纤细"></textarea></details></section>+<section class="step" data-s="2" aria-labelledby="s2T">+<div class="sh"><svg class="material-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M9.5 6a2.5 2.5 0 1 1 4.6 1.4C13.4 8.5 12 8.9 12 10v1l8.5 5.4a1.3 1.3 0 0 1-.7 2.4H4.2a1.3 1.3 0 0 1-.7-2.4L12 11"/></svg><b id="s2T">服装</b><span class="sp"></span><button class="lnk pick-more" data-pick="costume" hidden>从库中选</button><label class="lnk upload-link" tabindex="0" role="button" title="上传服装图" aria-label="上传服装图">上传<input type="file" id="wbGFile" accept="image/*" multiple hidden></label></div>+<div class="slot" id="wbG"></div></section>+<section class="step" data-s="3" aria-labelledby="s3T">+<div class="sh"><svg class="material-icon" viewBox="0 0 24 24" aria-hidden="true"><circle cx="13" cy="4" r="2"/><path d="m5 11 5-3 4 1 5-2M12 9l-1 6-5 5m5-5 4 1 2 5"/></svg><b id="s3T">姿势</b><span class="sp"></span><button class="lnk pick-more" data-pick="pose" hidden>从库中选</button></div>+<div class="slot" id="wbPo"></div><div class="row r3"><button class="sm ghost" id="wbAllAng" hidden>全部角度</button><span class="sp"></span><div class="seg sm" id="wbBatch" role="group" aria-label="多姿势出图方式" hidden><button data-bm="each">分开出</button><button data-bm="sheet">拼一张</button></div></div></section>+</div>+<details class="material-extras" id="wbOther"><summary><svg class="material-icon" viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="3" width="7" height="7" rx="2"/><rect x="14" y="3" width="7" height="7" rx="2"/><rect x="3" y="14" width="7" height="7" rx="2"/><path d="M14 17.5h7M17.5 14v7"/></svg><b>其他素材</b><span class="sp"></span><span class="other-preview" id="wbOtherPreview"></span><b id="wbOtherCount" hidden></b><svg class="chevron" viewBox="0 0 24 24" aria-hidden="true"><path d="m7 10 5 5 5-5"/></svg></summary>+<div class="other-types" id="wbOtherTypes" role="group" aria-label="素材分类"></div><div class="slot" id="wbEx"></div><div class="slot" id="wbOtherRefs"></div></details></aside>-<main class="st-c"><div class="onb" id="wbOnb" hidden><div class="onb-i"><svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="15" r="4"/><path d="m11 12 9-9m-3 3 3 3m-6 0 2 2"/></svg></div><div><b>需要一个图像模型的 API Key</b><p>支持 OpenAI、Gemini、豆包或中转。Key 只存在你的浏览器里。</p></div><button class="pri sm" id="wbOnbGo">去设置</button></div>-<div class="stage" id="wbStage"><div class="ph0" id="wbPh0"><div class="ill"><i class="c1">人物</i><em>+</em><i class="c2">服装</i><em>→</em><i class="c3">结果</i></div><span>结果会显示在这里</span><p>选好人物和服装后点「生成」</p></div>+<main class="st-c" aria-labelledby="wbCanvasTitle"><header class="canvas-head"><h2 id="wbCanvasTitle">参考画板</h2><span id="wbCanvasRatio"></span></header>+<div class="stage" id="wbStage"><div class="reference-board" id="wbPh0"><div class="board-cards" id="wbBoardCards"></div><button id="wbExample" type="button" class="board-use" hidden>使用这组参考</button></div><div class="cmp" id="wbCmp" hidden><img id="wbAfter" alt="生成结果"><div class="bef" id="wbBefW"><img id="wbBefore" alt="原始照片"></div><div class="hdl" id="wbHdl"><span></span></div><input type="range" id="wbRange" min="0" max="100" value="50" aria-label="前后对比"><em class="l">原图</em><em class="r">结果</em></div>-<div class="busy" id="wbBusy" hidden><div class="skel0"></div><div class="bar0"><i id="wbProg"></i></div><b id="wbStage1">正在上传素材…</b><small id="wbTime">0 秒</small><button class="sm ghost" id="wbStop">取消</button></div>+<div class="busy" id="wbBusy" hidden><div class="skel0"></div><progress id="wbProg" aria-label="生成进度"></progress><b id="wbStage1">正在上传素材…</b><small id="wbTime">0 秒</small><button class="sm ghost" id="wbStop">取消</button></div><div class="err" id="wbErr" hidden></div></div><div class="warn" id="wbWarn" hidden></div><div class="res" id="wbRes" hidden></div>@@ -46,40 +69,49 @@</main><aside class="st-r"><button id="wbCfg" class="cfg"><span class="dot" id="wbDot"></span><span id="wbProv">未配置 API</span><b>设置</b></button>-<div class="flow"><span data-f="1">人物</span><i>›</i><span data-f="2">服装</span><i>›</i><span data-f="3">姿势</span><i>›</i><span data-f="4">生成</span></div>+<div class="quick"><div class="lab0">风格</div><div class="chips" id="wbStyles"></div><div class="row q2"><div class="row"><label class="lab">画幅<select id="wbAR"><option value="auto">自动</option><option value="2:3">竖 2:3</option><option value="3:4">竖 3:4</option><option value="9:16">竖 9:16</option><option value="1:1">方 1:1</option><option value="4:3">横 4:3</option><option value="16:9">横 16:9</option></select></label><label class="lab">数量<select id="wbN"><option>1</option><option>2</option><option>3</option><option>4</option></select></label></div></div></div>-<details class="adv"><summary>高级设置</summary><div class="adv-b"><label class="tg mt"><input type="checkbox" id="wbKeepBg"><span><b>保留原照片背景与光线</b></span></label><label class="tg mt"><input type="checkbox" id="wbNeutral"><span><b>减少误拦截</b><small>用更中性的描述发送,减少正常穿搭被误判,不改变服装和姿势</small></span></label><textarea id="wbExtra" rows="2" placeholder="补充要求(可选),例如:海边日落、半身构图、手拿咖啡…"></textarea><div class="row"><div class="seg sm" role="group" aria-label="提示词语言"><button data-pl="en">英文</button><button data-pl="zh">中文</button></div><span class="sp"></span><button class="sm ghost" id="wbCopyP">复制</button><button class="sm ghost" id="wbReP">重置</button></div><textarea id="wbPrompt" rows="8" aria-label="最终提示词"></textarea></div></details>+<section class="prompt-panel" aria-labelledby="wbPromptTitle"><div class="sh"><b id="wbPromptTitle">生图提示词</b></div><textarea id="wbPrompt" rows="4" aria-labelledby="wbPromptTitle" placeholder="描述你想生成的画面"></textarea><div class="prompt-tools"><div class="seg sm" role="group" aria-label="提示词语言"><button data-pl="en">英文</button><button data-pl="zh">中文</button></div><span class="sp"></span><button class="sm ghost" id="wbCopyP" type="button">复制</button><button class="sm ghost" id="wbReP" type="button">重置</button></div></section>+<details class="adv"><summary>高级设置</summary><div class="adv-b"><label class="tg mt"><input type="checkbox" id="wbKeepBg"><span><b>保留原照片背景与光线</b></span></label><label class="tg mt"><input type="checkbox" id="wbNeutral"><span><b>减少误拦截</b><small>用更中性的描述发送,减少正常穿搭被误判,不改变服装和姿势</small></span></label><textarea id="wbExtra" rows="2" placeholder="补充要求(可选),例如:海边日落、半身构图、手拿咖啡…"></textarea></div></details><div class="hist"><div class="sh"><b>生成记录</b><span class="sp"></span><button class="sm ghost" data-go="history">全部</button><button class="sm ghost" id="wbHClr">清空</button></div><div class="hl" id="wbHist"></div></div>-<div class="gobar"><div class="gb-i"><span><b id="wbEst">将生成 1 张</b><small id="wbHint"></small></span><button class="cfgchip" id="wbCfg2" type="button"><span class="dot" id="wbDot2"></span><span id="wbProv2">未配置</span></button></div><button id="wbGo" class="pri big">生成</button></div>+<div class="gobar"><div class="gb-i"><span><b id="wbEst">将生成 1 张</b></span><button class="cfgchip" id="wbCfg2" type="button"><span class="dot" id="wbDot2"></span><span id="wbProv2">未配置</span></button></div><button id="wbGo" class="pri big">生成</button></div></aside></div></section>-<div id="pk" hidden role="dialog" aria-modal="true" aria-label="选择素材"><div class="pk-box"><div class="pk-h"><b id="pkT">选择服装</b><input id="pkQ" type="search" placeholder="搜索…" autocomplete="off"><button class="sm pri" id="pkDone" hidden>完成</button><button class="icon" id="pkX" aria-label="关闭">✕</button></div><div class="pk-g" id="pkG"></div></div></div>+<div id="pk" hidden role="dialog" aria-modal="true" aria-label="选择素材"><div class="pk-box"><div class="pk-h"><b id="pkT">选择服装</b><input id="pkQ" type="search" placeholder="搜索…" autocomplete="off"><button class="sm pri" id="pkDone" hidden>完成</button><button class="icon" id="pkX" aria-label="关闭">✕</button></div><div id="pkPoseTypes" class="seg sm" role="group" aria-label="姿势图类型" hidden><button type="button" data-pk-type="pose" aria-pressed="true" class="on">线稿</button><button type="button" data-pk-type="depth" aria-pressed="false">深度图</button></div><div class="pk-types" id="pkMaterialTypes" role="group" aria-label="素材分类" hidden></div><div class="pk-g" id="pkG"></div></div></div><div id="cfg" hidden role="dialog" aria-modal="true" aria-labelledby="cfgT"><div class="cfg-box"><div class="pk-h"><b id="cfgT">API 设置</b><button class="icon" id="cfgX" aria-label="关闭">✕</button></div><div class="cfg-b"><div class="grp">服务商</div><div class="prov" role="radiogroup" aria-label="服务商"><label><input type="radio" name="prov" value="openai"><span><i class="lg" style="background:#111">O</i><b>OpenAI</b><small>gpt-image-1 · edits</small></span></label><label><input type="radio" name="prov" value="gemini"><span><i class="lg" style="background:#4f7cff">G</i><b>Gemini</b><small>Nano Banana</small></span></label><label><input type="radio" name="prov" value="seedream"><span><i class="lg" style="background:#ff6a00">豆</i><b>豆包 Seedream</b><small>火山方舟 · 国内直连</small></span></label><label><input type="radio" name="prov" value="custom"><span><i class="lg" style="background:#7a7a7a">中</i><b>自定义中转</b><small>OpenAI 兼容</small></span></label></div>-<p class="fine" id="cfHelp"></p><div class="grp">连接</div><label class="fld">Base URL<input id="cfBase" placeholder="https://api.openai.com" spellcheck="false"></label>+<details class="fine" id="cfLocalSetup"><summary>在本机使用 ComfyUI</summary><p>在项目目录运行 <code>npm start</code>,然后 <a href="http://127.0.0.1:8787/#studio" target="_blank" rel="noopener">打开本机工作台</a></p></details>+<p class="fine" id="cfHelp"></p><label class="fld" id="cfCheckpointW" hidden>本机模型<select id="cfCheckpoint"></select></label><div class="grp">连接</div><label class="fld">Base URL<input id="cfBase" placeholder="https://api.openai.com" spellcheck="false"></label><label class="fld">API Key<span class="kw"><input id="cfKey" type="password" placeholder="sk-…" autocomplete="off" spellcheck="false"><button class="sm ghost" id="cfEye" type="button">显示</button></span></label><label class="fld">模型<input id="cfModel" list="cfModels" spellcheck="false"><datalist id="cfModels"></datalist></label><div class="grp">高级</div><label class="fld" id="cfProtoW">接口协议<select id="cfProto"><option value="edits">images/edits · multipart(OpenAI 官方格式)</option><option value="json">images/generations · JSON 多图(多数中转 / gpt-image-2)</option><option value="xai">xAI · images/edits JSON(Grok Imagine)</option><option value="gemini">Gemini · models/:generateContent(Nano Banana 等)</option></select></label><label class="fld" id="cfFieldW">图片字段名<select id="cfField"><option value="image[]">image[](官方,多图)</option><option value="image">image(部分中转)</option></select></label>-<label class="tg"><input type="checkbox" id="cfProxy"><span><b>通过本站代理转发</b><small>中转不支持跨域(CORS)时再打开。只转发,不保存。不勾选时由浏览器直连中转地址(含非 443 端口)。</small></span></label>-<div class="note"><b>密钥</b>只存在这个浏览器里,请求直接发给你填的地址。用公共电脑记得清除。</div>+<label class="tg"><input type="checkbox" id="cfProxy"><span><b>通过本站代理转发</b><small>直连时,浏览器将密钥和图片发给填写的 HTTPS 地址。启用本站代理后会经本站转发,仅支持管理员登记的中转地址(含端口)。</small></span></label>+<div class="note">API Key 保存在此浏览器。使用公共设备后,请清除密钥。</div><p class="fine" id="cfMsg" aria-live="polite"></p></div><div class="cfg-f"><button class="ghost sm" id="cfClr">清除密钥</button><button class="ghost sm" id="cfExp">导出</button><button class="ghost sm" id="cfImp">导入</button><input type="file" id="cfImpF" accept=".json" hidden><span class="sp"></span><button class="sm" id="cfTest">测试连接</button><button class="pri sm" id="cfSave">保存</button></div></div></div>-<aside id="tray" hidden aria-label="生图工作台"><div class="tray-h"><b>生图工作台</b><small id="trayN"></small><span class="sp"></span><div class="seg sm"><button data-tl="zh">中文</button><button data-tl="en">英文</button></div><button id="trayMin" class="ghost sm">收起</button></div><div class="tray-b"><div class="tg-add" id="tgAddRow"><span>添加素材</span><button data-add="costume">服装</button><button data-add="anime">动画服装</button><button data-add="pose">姿势</button><button data-add="portrait">人像</button><button data-add="expr">表情</button></div><p class="tg-empty" id="tgEmpty" hidden>工作台还是空的。用上面的按钮直接选素材,或者在图库里点卡片上的 + 加入——拼好素材就能在这里生图。</p><div class="tray-items" id="trayItems"></div><div id="trayComboBox"><pre id="trayText"></pre>-<div class="tray-act"><button id="trayCopyZh" class="pri">复制中文描述</button><button id="trayCopyEn">复制英文提示词</button><button id="trayClear" class="ghost">清空</button></div></div>-<div class="tgen"><div class="tgen-h"><b>生成</b><small id="tgProv">未配置 API</small><span class="sp"></span><button id="tgCfg" class="sm ghost">API 设置</button><button id="tgStudio" class="sm ghost">完整工作台</button></div>-<textarea id="tgPrompt" rows="4" aria-label="生图提示词" placeholder="选好素材后这里会自动填好提示词,也可以自己改"></textarea>-<div class="tgen-row"><label>张数<select id="tgN"><option>1</option><option>2</option><option>3</option><option>4</option></select></label><label>比例<select id="tgAR"><option value="auto">自动</option><option value="2:3">竖 2:3</option><option value="3:4">竖 3:4</option><option value="9:16">竖 9:16</option><option value="1:1">方 1:1</option><option value="4:3">横 4:3</option><option value="16:9">横 16:9</option></select></label><button id="tgGo" class="pri">生成图片</button><button id="tgStop" class="ghost" hidden>停止</button></div>-<p class="tgen-stat" id="tgStat" hidden></p><div class="tgen-res" id="tgRes"></div></div></div></aside>-<button id="trayFab" hidden aria-label="打开生图工作台"><svg viewBox="0 0 24 24" width="19" height="19" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="4"/><circle cx="9" cy="9" r="2"/><path d="m21 15-4.3-4.3a1.5 1.5 0 0 0-2.1 0L6 19"/></svg><span>生图工作台</span><em id="trayFabN" hidden>0</em></button>+<div id="workspaceDock">+<button id="trayFab" class="dock-launch" type="button" hidden aria-controls="tray" aria-expanded="false" title="打开生图工作台" aria-label="打开生图工作台">+ <span class="dock-mark"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3.5" y="6" width="15" height="14" rx="3"/><path d="m6.5 16 3.4-3.6 2.5 2.5 1.8-1.8 1.8 2"/><path class="dock-spark" d="m18 2 .9 2.8 2.8.9-2.8.9L18 9.4l-.9-2.8-2.8-.9 2.8-.9z"/></svg></span><span class="dock-launch-name">创作台</span><span id="trayFilm" aria-hidden="true"></span><em id="trayFabN" hidden>0</em><svg class="dock-chevron" viewBox="0 0 24 24" aria-hidden="true"><path d="m7 14 5-5 5 5"/></svg>+</button>+<aside id="tray" hidden tabindex="-1" aria-labelledby="trayTitle">+ <div class="tray-b"><div class="dock-materials"><section class="dock-block"><div class="dock-heading"><h3>参考素材</h3><small class="tg-empty" id="tgEmpty" hidden>尚未选材</small><button id="trayClear" class="sm ghost">清空</button></div><div class="tray-items" id="trayItems"></div><div class="tg-add" id="tgAddRow"><button data-add="portrait"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="8" r="3"/><path d="M5 20v-2a7 7 0 0 1 14 0v2"/></svg>人像</button><button data-add="costume"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m8 4-5 3 2.5 4 2-1v10h9V10l2 1L21 7l-5-3c-.8 1.3-2.1 2-4 2s-3.2-.7-4-2z"/></svg>服装</button><button data-add="pose" title="姿势线稿与深度图" aria-label="姿势线稿与深度图"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="14" cy="4.5" r="1.5"/><path d="m5 10 6-2 4 4 4-1m-7-3-2 6 5 2 2 5m-7-7-1 4-4 3"/></svg>姿势</button><details id="tgMore"><summary title="其他素材" aria-label="其他素材"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="5" cy="12" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/></svg></summary><div><button data-add="expr">表情</button><button data-add="hair">发型</button><button data-add="scene">场景</button><button data-add="light">光影</button><button data-add="prop">道具</button><button data-add="furn">家具</button></div></details></div></section>+<details id="trayComboBox" class="dock-combo"><summary>组合描述</summary><div class="seg sm"><button data-tl="zh">中文</button><button data-tl="en">英文</button></div><pre id="trayText"></pre><div class="tray-act"><button id="trayCopyZh" class="sm">复制中文描述</button><button id="trayCopyEn" class="sm">复制英文提示词</button></div></details>+</div><div class="tgen"><div class="dock-heading"><label for="tgPrompt">生图提示词</label><button id="tgCopyDraft" class="dock-icon" title="复制提示词" aria-label="复制提示词"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M15 5V4H5v11h1"/></svg></button></div><textarea id="tgPrompt" rows="3" aria-label="生图提示词" placeholder="输入或编辑提示词"></textarea>+<div class="tgen-row"><label>张数<select id="tgN"><option>1</option><option>2</option><option>3</option><option>4</option></select></label><label>比例<select id="tgAR"><option value="auto">自动</option><option value="2:3">竖 2:3</option><option value="3:4">竖 3:4</option><option value="9:16">竖 9:16</option><option value="1:1">方 1:1</option><option value="4:3">横 4:3</option><option value="16:9">横 16:9</option></select></label></div>+<p class="tgen-stat" id="tgStat" role="status" hidden></p><div class="tgen-res" id="tgRes"></div></div></div>+ <footer class="dock-foot"><h2 class="dock-title"><button id="trayMin" type="button" aria-controls="tray" aria-expanded="true" title="收起工作台" aria-label="收起工作台"><span class="dock-mark"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3.5" y="6" width="15" height="14" rx="3"/><path d="m6.5 16 3.4-3.6 2.5 2.5 1.8-1.8 1.8 2"/><path class="dock-spark" d="m18 2 .9 2.8 2.8.9-2.8.9L18 9.4l-.9-2.8-2.8-.9 2.8-.9z"/></svg></span><span id="trayTitle">创作台</span><small id="trayN" role="status" aria-atomic="true"></small><svg class="dock-chevron" viewBox="0 0 24 24" aria-hidden="true"><path d="m7 14 5-5 5 5"/></svg></button></h2>+ <div class="dock-actions"><button id="tgStudio" class="dock-icon" title="完整工作台" aria-label="完整工作台"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M13 4h7v7M20 4l-9 9"/><path d="M9 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-3"/></svg></button><button id="tgCfg" class="sm ghost" aria-label="API 设置" title="API 设置"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 7h5m4 0h5M5 17h8m4 0h2"/><circle cx="12" cy="7" r="2"/><circle cx="15" cy="17" r="2"/></svg><i class="dot" aria-hidden="true"></i><span id="tgProv">未配置 API</span></button><button id="tgGo" class="pri">生成图片</button><button id="tgStop" class="ghost" hidden>停止</button></div></footer>+</aside>+</div><div id="tgView" hidden role="dialog" aria-modal="true" aria-label="生成结果"><div class="tgv-bg"></div><figure><img id="tgViewImg" alt="生成结果"><figcaption><button id="tgDl" class="pri sm">下载</button><button id="tgHist" class="sm">在生成记录中查看</button><button id="tgViewX" class="sm ghost">关闭</button></figcaption></figure></div><div id="lb" hidden role="dialog" aria-modal="true" aria-label="大图预览"><div class="lb-bg"></div><div class="lb-box"><button class="lb-x icon" title="关闭(Esc)" aria-label="关闭">✕</button><button class="lb-nav prev icon" aria-label="上一张">‹</button><button class="lb-nav next icon" aria-label="下一张">›</button><div class="lb-img"><img id="lbImg" alt="" referrerpolicy="no-referrer"><a id="lbMiss" class="lb-miss" href="https://ai-pose-depth-gallery.pages.dev/" target="_blank" rel="noopener">请前往原站查看</a><div class="spin"></div></div><div class="lb-side" id="lbSide"></div></div></div><div id="drawerBg" hidden></div>-<div id="helpBox" hidden role="dialog" aria-label="快捷键"><div class="hb"><h3>快捷键</h3><dl><dt><kbd>/</kbd></dt><dd>聚焦搜索</dd><dt><kbd>R</kbd></dt><dd>随机一个</dd><dt><kbd>T</kbd></dt><dd>切换深浅色</dd><dt><kbd>L</kbd></dt><dd>切换描述语言(中 / 英)</dd><dt><kbd>1</kbd>–<kbd>9</kbd></dt><dd>切换栏目</dd><dt><kbd>←</kbd><kbd>→</kbd></dt><dd>大图:上一张 / 下一张</dd><dt><kbd>↑</kbd><kbd>↓</kbd></dt><dd>大图:切换拍摄角度</dd><dt><kbd>F</kbd></dt><dd>大图:收藏</dd><dt><kbd>A</kbd></dt><dd>大图:加入 / 移出组合</dd><dt><kbd>C</kbd></dt><dd>大图:复制中文描述</dd><dt><kbd>S</kbd></dt><dd>大图:复制分享链接</dd><dt><kbd>Esc</kbd></dt><dd>关闭</dd></dl><button class="pri" data-close>知道了</button></div></div>+<div id="helpBox" hidden role="dialog" aria-modal="true" aria-label="快捷键"><div class="hb"><h3>快捷键</h3><dl><dt><kbd>/</kbd></dt><dd>聚焦搜索</dd><dt><kbd>R</kbd></dt><dd>随机一个</dd><dt><kbd>T</kbd></dt><dd>切换深浅色</dd><dt><kbd>L</kbd></dt><dd>切换描述语言(中 / 英)</dd><dt><kbd>1</kbd>–<kbd>9</kbd></dt><dd>切换栏目</dd><dt><kbd>←</kbd><kbd>→</kbd></dt><dd>大图:上一张 / 下一张</dd><dt><kbd>↑</kbd><kbd>↓</kbd></dt><dd>大图:切换拍摄角度</dd><dt><kbd>F</kbd></dt><dd>大图:收藏</dd><dt><kbd>A</kbd></dt><dd>大图:加入 / 移出组合</dd><dt><kbd>C</kbd></dt><dd>大图:复制中文描述</dd><dt><kbd>S</kbd></dt><dd>大图:复制分享链接</dd><dt><kbd>Esc</kbd></dt><dd>关闭</dd></dl><button class="pri" data-close>知道了</button></div></div><button id="toTop" class="icon" title="回到顶部" aria-label="回到顶部">↑</button><div id="toast" role="status"></div><section id="histSec" hidden aria-labelledby="histSecT"><h2 id="histSecT" class="vh">生成记录</h2>@@ -96,7 +128,11 @@<main id="histGrid" class="grid hist-grid" aria-live="polite"></main><div id="histEmpty" hidden><div class="emo">🎨</div><h3>还没有生成记录</h3><p>在试穿工作台生成的图片会保存在这里</p><button class="pri sm" data-go="studio">去试穿</button></div></section>-<footer class="foot"><div class="fi"><div><b class="fwm">衣姿 PoseWear</b><p>姿势和服装参考图。图片来自下方原图库,均为生成图。</p></div>-<div><h4>使用提示</h4><ul><li>点 <b>+</b> 把姿势和服装放进组合</li><li>SD 类模型用英文提示词更准</li><li>收藏和密钥只存在本机</li></ul></div>-<div><h4>来源与致谢</h4><ul><li>素材整理自公开图库 <a href="https://ai-pose-gallery.pages.dev" target="_blank" rel="noopener">AI Pose Gallery</a>、<a href="https://ai-costume-gallery.pages.dev" target="_blank" rel="noopener">AI Costume Gallery</a> 与 <a href="https://ai-costume-anime-gallery.pages.dev" target="_blank" rel="noopener">AI Costume Anime Gallery</a></li><li>深度姿势来自 <a href="https://ai-pose-depth-gallery.pages.dev/" target="_blank" rel="noopener">ai-pose-depth-gallery</a>(非官方汉化),图片由本站自存分发</li><li>发型与部分动画服装来自 CharaDB(作者 たき AI,标签 CC0),图片热链原站</li><li>原作者 <a href="https://x.com/giaaibusi" target="_blank" rel="noopener">@giaaibusi</a></li><li>人像来自 <a href="https://ai-portrait-gallery.pages.dev" target="_blank" rel="noopener">AI Portrait Gallery</a>(<a href="https://x.com/agi_aibusi" target="_blank" rel="noopener">@agi_aibusi</a>,<a href="https://creativecommons.org/publicdomain/zero/1.0/deed.zh-hans" target="_blank" rel="noopener">CC0 1.0</a>)</li><li>中文名称和描述由本站翻译</li></ul></div></div><p class="cnote">部分姿势和内衣、性感类服装属于成人向参考,默认不显示,可以用顶部的「18+」开关打开或关闭。</p><p class="copy-r">© 衣姿 PoseWear · <a href="#" id="privO">隐私说明</a> · <a href="https://github.com/atuizz/posewear" target="_blank" rel="noopener">开源地址</a></p></footer><div id="ageBox" class="mdl" hidden role="dialog" aria-modal="true" aria-labelledby="ageT"><div class="hb"><h3 id="ageT">显示成人向内容?</h3><p id="ageP">包括双人互动、性感类姿势、深度姿势里的双人图,以及内衣、性感类服装。仅适合已满 18 岁的用户。只需确认一次,之后用顶部的「18+」开关随时打开或关闭。</p><div class="row"><button class="sm ghost" id="ageN">暂不</button><button class="sm pri" id="ageY">我已满 18 岁,打开</button></div></div></div><div id="privBox" class="mdl" hidden role="dialog" aria-modal="true" aria-labelledby="privT"><div class="hb"><h3 id="privT">隐私说明</h3><ul class="pl"><li><b>本机存储</b>:收藏、浏览记录、筛选偏好、成人内容开关和试穿记录只保存在你的浏览器(localStorage / IndexedDB),不上传。清除浏览器数据即可删除。</li><li><b>API 密钥</b>:只保存在本机。生成时由浏览器直接发给你选择的服务商;开启「通过本站代理转发」或使用自定义中转时,请求会经过本站的转发接口,只转发、不记录、不保存。</li><li><b>代理限制</b>:转发接口只接受本站页面发起的请求,只能访问官方接口地址。</li><li><b>统计</b>:本站不使用统计、广告或第三方追踪脚本,不设置 Cookie。</li><li><b>图片</b>:姿势、服装、人像和深度姿势由本站托管分发,来自 AI Pose Gallery、AI Costume Gallery、AI Costume Anime Gallery、AI Pose Depth Gallery(@giaaibusi)与 AI Portrait Gallery(@agi_aibusi)。发型与部分动画服装的图片由 CharaDB 原站托管、页面直接加载,对方能看到请求的 IP。</li></ul><div class="row"><button class="sm pri" data-close>知道了</button></div></div></div>-<script src="app.js" defer></script><script src="zip.js" defer></script><script src="extras.js" defer></script><script src="studio.js" defer></script><script src="history.js" defer></script></body></html>+<footer class="foot"><div class="foot-line"><small>© 衣姿 PoseWear</small><a href="#" id="privO">隐私说明</a><a href="https://github.com/atuizz/posewear" target="_blank" rel="noopener">GitHub</a></div><details id="credits"><summary>素材来源与许可</summary><div class="credit-list">+<p><a href="https://ai-pose-gallery.pages.dev/" target="_blank" rel="noopener">AI Pose Gallery</a> · <a href="https://ai-pose-depth-gallery.pages.dev/" target="_blank" rel="noopener">AI Pose Depth Gallery</a> · <a href="https://ai-costume-gallery.pages.dev/" target="_blank" rel="noopener">AI Costume Gallery</a> · <a href="https://ai-costume-anime-gallery.pages.dev/" target="_blank" rel="noopener">AI Costume Anime Gallery</a> · <a href="https://x.com/giaaibusi" target="_blank" rel="noopener">@giaaibusi</a><span>。非官方整理。图片权利归原作者,转载或商用前请联系原作者。</span></p>+<p><a href="https://ai-portrait-gallery.pages.dev/" target="_blank" rel="noopener">AI Portrait Gallery</a> · <a href="https://x.com/agi_aibusi" target="_blank" rel="noopener">@agi_aibusi</a> · <a href="https://creativecommons.org/publicdomain/zero/1.0/" rel="license">CC0 1.0</a><span>。人像为虚构人物。原作者希望避免原样批量转载。</span></p>+<p><a href="https://charadb-2fi.pages.dev/" target="_blank" rel="noopener">CharaDB</a> · たき AI<span>。发型与部分动画服装使用原站图片,标签为 CC0,图片版权归原作者。</span></p>+<p>WaveSpeed AI Emotion Gallery · ICT Face Model Light<span>。表情参考使用 ICT-FaceKit 头模,© USC Institute for Creative Technologies,MIT。</span></p>+<p>Shisei · wquguru<span>。历代服饰、场景、光影、道具与家具采用 CC0 1.0。</span></p>+</div></details><!-- category-index --></footer><div id="ageBox" class="mdl" hidden role="dialog" aria-modal="true" aria-labelledby="ageT"><div class="hb"><h3 id="ageT">显示成人向内容?</h3><p id="ageP">包括双人互动、性感类姿势、深度姿势里的双人图,以及内衣、性感类服装。仅适合已满 18 岁的用户。只需确认一次,之后用顶部的「18+」开关随时打开或关闭。</p><div class="row"><button class="sm ghost" id="ageN">暂不</button><button class="sm pri" id="ageY">我已满 18 岁,打开</button></div></div></div><div id="privBox" class="mdl" hidden role="dialog" aria-modal="true" aria-labelledby="privT"><div class="hb"><h3 id="privT">隐私说明</h3><ul class="pl"><li><b>本机存储</b>:收藏、浏览记录、筛选偏好、成人内容开关和试穿记录只保存在你的浏览器(localStorage / IndexedDB),不上传。清除浏览器数据即可删除。</li><li><b>API 密钥</b>:密钥保存在此浏览器。直连时,请求发往所选服务商;使用本站代理时,代理会经手凭据和图片。</li><li><b>代理限制</b>:本站仅向官方服务或管理员登记的 HTTPS 地址转发。接收方会收到凭据和图片,请选择可信服务。</li><li><b>统计</b>:站点部署者可以开启 Cloudflare Web Analytics。</li><li><b>图片</b>:姿势、服装、人像和深度姿势由本站托管分发,来自 AI Pose Gallery、AI Costume Gallery、AI Costume Anime Gallery、AI Pose Depth Gallery(@giaaibusi)与 AI Portrait Gallery(@agi_aibusi)。发型与部分动画服装的图片由 CharaDB 原站托管、页面直接加载,对方能看到请求的 IP。</li></ul><div class="row"><button class="sm pri" data-close>知道了</button></div></div></div>+<script src="i18n.js" defer></script><script src="references.js" defer></script><script src="app.js" defer></script><script src="zip.js" defer></script><script src="extras.js" defer></script><script src="image-providers.js" defer></script><script src="studio.js" defer></script><script src="history.js" defer></script></body></html>diff --git a/src/references.js b/src/references.jsnew file mode 100644index 0000000..77ad211--- /dev/null+++ b/src/references.js@@ -0,0 +1,39 @@+// Also imported by the local MCP server. Media origins follow the same split as the site build.+(function () {+ const libraries = {+ pose:['姿势','Pose'], depth:['深度姿势','Depth pose'], costume:['服装','Outfit'],+ anime:['动画服装','Anime outfit'], portrait:['人像','Portrait'], expr:['表情','Expression'],+ hair:['发型','Hairstyle'], dyn:['历代服饰','Historical dress'], scene:['场景','Scene'],+ light:['光影','Lighting'], prop:['道具','Prop'], furn:['家具','Furniture']+ };+ function reference(item, angle = 0, site, language = 'zh', assetHost = site) {+ const view = item.angles?.[angle];+ const image = view || item;+ const display = view ? image.i || image.m : image.m || image.i;+ const path = display || image.o || image.t;+ const url = new URL(path, (display ? site : assetHost).replace(/\/$/,'')+'/').href;+ const en = language === 'en';+ const label = [libraries[item.type][en ? 1 : 0], en ? item.id : item.ti || item.zh || item.id,+ view && (en ? view.en : view.zh)].filter(Boolean).join(' · ');+ return {label,url};+ }+ function formatBrief(prompt, references, language = 'zh') {+ const en = language === 'en';+ const lines = [];+ if (references.length) {+ lines.push(en ? 'Reference images' : '参考图');+ references.forEach((ref,index) => {+ const slot = (en ? 'Image ' : '图 ') + (index+1);+ const value = ref ? ref.label+' — '+ref.url : (en ? 'Attach this local image separately.' : '请另附这张本地参考图。');+ lines.push('- '+slot+' · '+value);+ });+ }+ return [prompt,lines.join('\n')].filter(Boolean).join('\n\n');+ }+ if (typeof module !== 'undefined' && module.exports) {+ module.exports.reference = reference;+ module.exports.formatBrief = formatBrief;+ } else {+ window.PoseWearReferences = {reference,formatBrief};+ }+})();diff --git a/src/studio.js b/src/studio.jsindex 492549b..2ebbf03 100644--- a/src/studio.js+++ b/src/studio.js@@ -2,11 +2,22 @@(()=>{const A=window.APP;if(!A)return;const $=s=>document.querySelector(s),$$=s=>document.querySelectorAll(s),esc=A.esc,toast=A.toast;const LS=k=>{try{return JSON.parse(localStorage[k]||'null')}catch(e){return null}},SV=(k,v)=>{try{localStorage[k]=JSON.stringify(v)}catch(e){}};// ---------- 服务商 -----------const PROV={openai:{name:'OpenAI',base:'https://api.openai.com/v1',model:'gpt-image-1',models:['gpt-image-1','gpt-image-1-mini','gpt-image-2','dall-e-2']},- gemini:{name:'Gemini',base:'https://generativelanguage.googleapis.com/v1beta',model:'gemini-2.5-flash-image',models:['gemini-2.5-flash-image','gemini-3-pro-image-preview','gemini-3.1-flash-image']},- seedream:{name:'豆包 Seedream',base:'https://ark.cn-beijing.volces.com/api/v3',model:'doubao-seedream-5-5-261028',models:['doubao-seedream-5-5-261028','doubao-seedream-5-0-flash-260915','doubao-seedream-4-5-251128','doubao-seedream-4-0-250828']},- custom:{name:'自定义中转',base:'',model:'gpt-image-1',models:['gpt-image-1','gpt-image-2','grok-imagine-image-2.0','gemini-2.5-flash-image','flux-kontext-pro','qwen-image-edit','doubao-seedream-4-0-250828']}};-const cfg=Object.assign({prov:'openai',base:'',key:'',model:'',field:'image[]',proto:'edits',proxy:false},LS('wbCfg')||{});+const {providers, generateImage, testConnection, nice}=window.PoseWearImageProviders;+const PROV={...providers};+const localEngine=document.documentElement.dataset.localEngine;+const localPreset=document.documentElement.dataset.localPreset==='1';+$('#cfLocalSetup').hidden=!!localEngine;+if(localEngine){+ const name=localEngine==='comfyui'?'ComfyUI':'sd.cpp';+ PROV.local={name,base:'',model:name,models:[]};+ const label=document.createElement('label');+ label.innerHTML='<input type="radio" name="prov" value="local"><span><i class="lg">⌂</i><b>'+name+'</b><small>本机引擎</small></span>';+ $('#cfg .prov').append(label);+}+const configured=(settings=cfg)=>settings.prov==='local'?!!localEngine&&(!localPreset||!!settings.checkpoint):!!settings.key;+const defaultConfig={prov:localEngine&&!localPreset?'local':'openai',base:'',key:'',model:'',field:'image[]',proto:'edits',proxy:false};+const storedConfig=LS('wbCfg');+const cfg={...defaultConfig,...(Object.hasOwn(PROV,storedConfig?.prov)?storedConfig:{})};// ---------- 预设 ----------const CHARS=[['asia','东亚女性','an adult East Asian woman in her mid-20s, long black hair, natural makeup, slim build','一位二十多岁的成年东亚女性,黑色长发,自然淡妆,身材纤细'],['west','欧美女性','an adult Caucasian woman in her late 20s, wavy light-brown hair, natural makeup, athletic build','一位二十多岁的成年欧美女性,浅棕色波浪长发,自然妆容,匀称身材'],@@ -17,100 +28,457 @@ const STYLES=[['keep','照片质感','photorealistic, matching the original phot['street','城市街拍','candid city street-style photo, natural daylight, shallow depth of field','城市街拍抓拍,自然日光,浅景深'],['ecom','电商白底','e-commerce product-model photo, pure white background, even lighting, full body','电商模特图,纯白背景,均匀布光,全身构图'],['film','胶片氛围','35mm film photograph, warm tones, subtle grain, golden hour light','35mm 胶片摄影,暖色调,轻微颗粒,黄金时刻光线'],['anime','动漫插画','high-quality anime illustration, clean line art, soft cel shading','高质量动漫插画,干净线稿,柔和赛璐璐上色']];const ANG_EN={'正面':'front view','斜侧':'three-quarter view','侧面':'side profile','俯拍':'high-angle shot looking down','仰拍':'low-angle shot looking up','背面':'back view','下から':'low angle'};-const W={mode:LS('wbMode')||'tryon',persons:[],garments:[],poses:[],exprs:[],char:LS('wbChar')||'asia',charTxt:LS('wbCharTxt')||'',style:LS('wbStyle')||'keep',bm:LS('wbBm')||'each',pl:LS('wbPl')||'en',keepBg:LS('wbKeepBg')??true,busy:null,dirty:false,results:[],ri:0,cmp:true};+const MATERIAL_ROLES={hair:['发型','Hairstyle'],scene:['场景','Scene'],light:['光影','Lighting'],prop:['道具','Prop'],furn:['家具','Furniture']};+const preferredMode=LS('wbMode');+let autoMode=!preferredMode;+const W={mode:preferredMode||'gen',persons:[],garments:[],poses:[],exprs:[],extraRefs:[],char:LS('wbChar')||'asia',charTxt:LS('wbCharTxt')||'',style:LS('wbStyle')||'keep',bm:LS('wbBm')||'each',pl:LS('wbPl')||'en',keepBg:LS('wbKeepBg')??true,busy:null,dirty:false,results:[],ri:0,cmp:true};// item: {kind:'lib',k,ai?} | {kind:'file',blob,url,name}const g0=LS('wbSel')||{};+const savedDraft=LS('wbDraft');+if(savedDraft){+ $('#wbExtra').value=savedDraft.extra;+ $('#wbN').value=savedDraft.count;+ $('#wbAR').value=savedDraft.ratio;+ W.dirty=savedDraft.prompt!=null;+ if(W.dirty)$('#wbPrompt').value=savedDraft.prompt;+}+function saveDraft(){+ SV('wbDraft',{prompt:W.dirty?$('#wbPrompt').value:null,extra:$('#wbExtra').value,+ count:$('#wbN').value,ratio:$('#wbAR').value});+}// ---------- 工具 -----------const normBase=b=>(b||'').trim().replace(/\/+$/,'');-function root(){let b=normBase(cfg.base)||PROV[cfg.prov].base;if(cfg.prov=='gemini')return/\/v1(beta|alpha)?$/.test(b)?b:b+'/v1beta';if(cfg.prov=='seedream')return b;return/\/v\d+$/.test(b)?b:b+'/v1'}-const modelOf=()=>(cfg.model||'').trim()||PROV[cfg.prov].model;-const proto=()=>cfg.prov=='openai'?'edits':cfg.prov=='custom'?cfg.proto:cfg.prov;+const modelOf=(settings=cfg)=>settings.prov==='local'&&localPreset?settings.checkpoint:(settings.model||'').trim()||PROV[settings.prov].model;+const provLabel=()=>configured()?[PROV[cfg.prov].name,cfg.prov!=='local'&&modelOf()].filter(Boolean).join(' · '):'';+function configError(settings){+ if(settings.prov==='local')return localPreset&&!settings.checkpoint?'请先测试连接并选择本机模型':'';+ if(settings.prov=='custom'&&!settings.base)return '自定义中转需要填写 Base URL';+ if(!settings.base)return '';+ try{const u=new URL(settings.base);if(u.protocol=='https:'&&!u.username&&!u.password)return ''}catch{}+ return 'Base URL 需填写有效的 HTTPS 地址,请勿在地址中包含账号或密码。';+}function loadImg(src){return new Promise((r,j)=>{const i=new Image();i.onload=()=>r(i);i.onerror=()=>j(Error('图片读取失败'));i.src=src})}async function toJpeg(src,max=1536){const i=await loadImg(src);let w=i.naturalWidth,h=i.naturalHeight,s=Math.min(1,max/Math.max(w,h));w=Math.round(w*s);h=Math.round(h*s);const c=document.createElement('canvas');c.width=w;c.height=h;const x=c.getContext('2d');x.fillStyle='#fff';x.fillRect(0,0,w,h);x.drawImage(i,0,0,w,h);return new Promise(r=>c.toBlob(b=>r({blob:b,w,h}),'image/jpeg',.92))}const libSrc=a=>{const it=A.ITEMS[a.k];return it.angles?it.angles[a.ai??it.ai].i:it.i};-async function assetBlob(a){if(a.kind=='file')return a.blob;const src=libSrc(a);const r=await fetch(src);if(!r.ok)throw Error('素材下载失败('+r.status+')');const u=URL.createObjectURL(await r.blob());try{return(await toJpeg(u,1280)).blob}finally{URL.revokeObjectURL(u)}}-const b64=b=>new Promise(r=>{const f=new FileReader();f.onload=()=>r(f.result.split(',')[1]);f.readAsDataURL(b)});-const dataURL=async b=>'data:'+(b.type||'image/jpeg')+';base64,'+await b64(b);+async function assetBlob(a,signal){+ if(a.blob)return a.blob;+ const src=a.kind=='portrait'?A.ITEMS[a.k].m:libSrc(a);+ const r=await fetch(src,{signal,referrerPolicy:A.ITEMS[a.k].ref||''});if(!r.ok)throw Error('素材下载失败('+r.status+')');const u=URL.createObjectURL(await r.blob());try{return(await toJpeg(u,a.kind=='portrait'?1536:1280)).blob}finally{URL.revokeObjectURL(u)}}const isGen=()=>W.mode=='gen';const hasPerson=()=>W.persons.length>0;// ---------- 提示词 -----------function poseDesc(p,en){const it=A.ITEMS[p.k];if(!it)return'';const a=it.angles[p.ai??it.ai];return en?`${it.en} (${it.lineEn}, ${ANG_EN[a.zh]||a.en||a.zh})${/2人|双人/.test(it.line)?' — a two-person pose: match the number of people and their relative positions':''}`:`${it.zh}(${it.line},${a.zh})${/2人|双人/.test(it.line)?'——双人姿势,人数与相对位置需与线稿一致':''}`}-function compose(poseSet){const en=W.pl=='en',P=W.persons.length,G=W.garments.length,ps=poseSet||W.poses,np=ps.length,sheet=np>1;const style=STYLES.find(s=>s[0]==W.style)||STYLES[0],ch=CHARS.find(c=>c[0]==W.char)||CHARS[0],ex=$('#wbExtra').value.trim();- const gi=W.garments.map(g=>g.kind=='lib'&&A.ITEMS[g.k]).filter(Boolean);let n=0;const rng=(c)=>{if(!c)return null;const a=n+1,b=n+c;n=b;return a==b?(en?`image ${a}`:`第 ${a} 张`):(en?`images ${a}–${b}`:`第 ${a}–${b} 张`)};- const E=W.exprs.length,ei=E?A.ITEMS[W.exprs[0].k]:null;const rP=rng(P),rG=rng(G),rS=rng(np),rE=rng(E);const L=[];- if(en){L.push(P?`Fashion ${isGen()?'image generation':'virtual try-on'} using reference images. ${rP} ${P>1?'show':'shows'} the person (same individual)${G?`; ${rG} ${G>1?'show':'shows'} the outfit${G>1?' pieces (top and bottom)':''} on an invisible mannequin`:''}${np?`; ${rS} ${np>1?'are':'is'} pose sketch${np>1?'es':''}`:''}.`:`Fashion image generation from reference images. ${G?`${rG} ${G>1?'show':'shows'} the outfit on an invisible mannequin`:''}${np?`; ${rS} ${np>1?'are':'is'} pose sketch${np>1?'es':''}`:''}.`);- L.push(P?"Subject: the person from the photo. Preserve their face, identity, hairstyle, skin tone and body proportions exactly; they must stay recognisably the same adult.":`Subject: ${(W.char=='custom'?W.charTxt:ch[2])||ch[2]||'an adult model'}. Always an adult with adult proportions.`);+// Only the matching view of a pose sketch and its paired depth map describe one action.+function poseGroups(poses){+ const groups=[];+ for(const ref of poses){+ const item=A.ITEMS[ref.k],mate=A.poseCounterpart(item,ref.ai??item.ai);+ const partner=mate&&groups.find(group=>{+ const first=group[0];+ return group.length===1&&first.k===mate.item.k&&(first.ai??mate.item.ai)===mate.angle;+ });+ if(partner)partner.push(ref);else groups.push([ref]);+ }+ return groups;+}+function poseInstructions(groups,poseNumbers,en,sheet){+ const roles=ref=>{+ const depth=A.ITEMS[ref.k].type==='depth';+ const type=en?(depth?'depth map':'pose sketch'):(depth?'深度图':'姿势线稿');+ return en?poseNumbers.get(ref)+' ('+type+')':poseNumbers.get(ref)+'('+type+')';+ };+ const details=groups.map((group,i)=>{+ const refs=group.map(roles).join(en?' + ':'+');+ const description=poseDesc(group[0],en);+ const pairing=group.length===2?(en?' together show the same pose and camera angle: ':'对应同一动作和机位:'):(en?': ':':');+ return (sheet?'('+ (i+1) +') ':'')+refs+pairing+description;+ });+ const prefix=en?(sheet?`Pose: draw ${groups.length} panels in one image, one per pose, with the same subject and outfit, even spacing and no text. `:'Pose: '):+ (sheet?`姿势:在同一张图中画 ${groups.length} 格,每格对应一个姿势,人物与服装保持一致,均匀留白,不写文字。`:'姿势:');+ const types=new Set(groups.flat().map(ref=>A.ITEMS[ref.k].type));+ const guides=[];+ if(types.has('pose'))guides.push(en?'Use the sketch for body posture, weight and limb placement. Omit its guide lines.':+ '按线稿还原身体姿态、重心和四肢位置,省略辅助线。');+ if(types.has('depth'))guides.push(en?'Use the depth map for near/far relationships and occlusion. Render natural colors and lighting.':+ '按深度图还原肢体前后关系和遮挡,成图使用自然色彩与光照。');+ return prefix+details.join(en?'; ':';')+(en?'. ':'。')+guides.join(en?' ':'');+}+function poseDesc(p,en){const it=A.ITEMS[p.k];if(!it)return'';const a=it.angles[p.ai??it.ai];return en?`${it.en} (${it.lineEn}, ${ANG_EN[a.zh]||a.en||a.zh})${/2人|双人/.test(it.line)?' — a two-person pose: match the number of people and their relative positions':''}`:`${it.zh}(${it.line},${a.zh})${/2人|双人/.test(it.line)?'——双人姿势,人数与相对位置需与参考图一致':''}`}+function compose(poseSet,state=W){const en=state.pl=='en',P=state.persons.length,G=state.garments.length,ps=poseSet||state.poses,groups=poseGroups(ps),np=groups.length,sheet=np>1&&state.bm=='sheet';const style=STYLES.find(s=>s[0]==state.style)||STYLES[0],ch=CHARS.find(c=>c[0]==state.char)||CHARS[0],ex=state.extra??$('#wbExtra').value.trim();+ const gi=state.garments.map(g=>g.kind=='lib'&&A.ITEMS[g.k]).filter(Boolean);let n=0;const rng=(c)=>{if(!c)return null;const a=n+1,b=n+c;n=b;return a==b?(en?`image ${a}`:`第 ${a} 张`):(en?`images ${a}–${b}`:`第 ${a}–${b} 张`)};+ const E=state.exprs.length,ei=E?A.ITEMS[state.exprs[0].k]:null;const rP=rng(P),rG=rng(G),poseNumbers=new Map(ps.map(ref=>[ref,rng(1)])),rE=rng(E);const L=[];+ const materials=state.extraRefs.map(ref=>{+ const it=A.ITEMS[ref.k],role=MATERIAL_ROLES[it.type][en?1:0];+ const description=A.prompt({...it,ai:ref.ai??it.ai},state.pl);+ return en?`${role} (${rng(1)}): ${description}`:`${role}(${rng(1)}):${description}`;+ });+ if(!(P||G||np||E)){+ if(state.mode==='gen'&&state.char==='custom'&&state.charTxt.trim())materials.unshift(state.charTxt.trim());+ if(!materials.length)return ex;+ if(state.dirtyStyle)materials.push(style[en?2:3]);+ if(ex)materials.push(ex);+ return materials.join('\n');+ }+ const tryon=P&&G&&state.mode==='tryon';+ const keepBackground=tryon&&state.keepBg&&!state.extraRefs.some(ref=>['scene','light'].includes(A.ITEMS[ref.k].type));+ const hairRef=state.extraRefs.some(ref=>A.ITEMS[ref.k].type==='hair');+ if(en){L.push(P?`Fashion ${tryon?'virtual try-on':'image generation'} using reference images. ${rP} ${P>1?'show':'shows'} the person (same individual)${G?`; ${rG} ${G>1?'show':'shows'} the outfit${G>1?' pieces (top and bottom)':''} on an invisible mannequin`:''}.`:`Fashion image generation from reference images.${G?` ${rG} ${G>1?'show':'shows'} the outfit on an invisible mannequin.`:''}`);+ L.push(P?`Subject: the person from the photo. Preserve their face, identity, ${hairRef?'':'hairstyle, '}skin tone and body proportions exactly; they must stay recognisably the same adult.`:`Subject: ${(state.char=='custom'?state.charTxt:ch[2])||ch[2]||'an adult model'}. Always an adult with adult proportions.`);if(G)L.push(`Outfit: dress the subject in the complete outfit from ${rG}, reproducing every garment faithfully — cut, color, fabric, pattern, layering, shoes and accessories${gi.length?': '+gi.map(x=>x.en.replace(/^[^,]*outfit,\s*/,'')).join('; '):''}. Replace the original clothing entirely. Never draw the mannequin or a blank body.`);- if(np)L.push((sheet&&W.bm=='sheet'?`Pose: draw ${np} panels in one image, one per pose sketch, same subject and outfit in every panel, with even spacing and no text: `:'Pose: ')+ps.map((p,i)=>(sheet&&W.bm=='sheet'?`(${i+1}) `:'')+poseDesc(p,true)).join('; ')+'. Use the sketch only for body posture, weight, limb placement and camera angle; never draw sketch lines, joint circles or guide marks.');+ if(np)L.push(poseInstructions(groups,poseNumbers,true,sheet));else if(P)L.push('Pose: keep the original pose, framing and camera angle.');- if(E&&ei)L.push(`Expression: ${rE} is a faceless neutral head model showing the target expression (${ei.en}). Give the subject exactly this facial expression. Transfer ONLY the expression — the subject's own facial features, face shape and identity must remain exactly as in the person photo; never copy the reference head's face.`);- L.push(`Look: ${P&&W.keepBg&&!isGen()?'keep the original background and lighting of the photo; ':''}${style[2]}. Natural fabric drape with realistic folds and shadows, high detail. No text, no watermark, no borders.`);+ if(E&&ei)L.push(`Expression: ${rE} shows the target expression (${ei.en}). Transfer the expression only.${P?" Preserve the facial features and identity from the person photo.":''}`);+ L.push(...materials);+ L.push(`Look: ${keepBackground?'keep the original background and lighting of the photo; ':''}${style[2]}.${G?' Natural fabric drape with realistic folds and shadows.':''} High detail. No text, no watermark, no borders.`);if(ex)L.push('Additional: '+ex)}- else{L.push(P?`时尚${isGen()?'生图':'虚拟试穿'},使用参考图。${rP}是人物照片(同一人)${G?`;${rG}是放在隐形人台上的服装${G>1?'(上装与下装)':''}`:''}${np?`;${rS}是姿势线稿`:''}。`:`根据参考图进行时尚生图。${G?`${rG}是放在隐形人台上的服装`:''}${np?`;${rS}是姿势线稿`:''}。`);- L.push(P?'人物:照片中的人。严格保留其面部、身份特征、发型、肤色与身材比例,必须一眼认出是同一位成年人。':`人物:${(W.char=='custom'?W.charTxt:ch[3])||ch[3]||'一位成年模特'}。始终为成年人比例。`);+ else{L.push(P?`时尚${tryon?'虚拟试穿':'生图'},使用参考图。${rP}是人物照片(同一人)${G?`;${rG}是放在隐形人台上的服装${G>1?'(上装与下装)':''}`:''}。`:`根据参考图进行时尚生图。${G?`${rG}是放在隐形人台上的服装。`:''}`);+ L.push(P?`人物:照片中的人。严格保留其面部、身份特征、${hairRef?'':'发型、'}肤色与身材比例,必须一眼认出是同一位成年人。`:`人物:${(state.char=='custom'?state.charTxt:ch[3])||ch[3]||'一位成年模特'}。始终为成年人比例。`);if(G)L.push(`服装:为人物换上${rG}中的整套服装,准确还原版型、颜色、面料、图案、叠穿、鞋袜与配饰${gi.length?':'+gi.map(x=>x.zh.replace(/[。.]$/,'')).join(';'):''}。完全替换原有衣物,不要画出人台或空白身体。`);- if(np)L.push((sheet&&W.bm=='sheet'?`姿势:在同一张图中画 ${np} 格,每格对应一张线稿,人物与服装保持一致,均匀留白,不写文字:`:'姿势:')+ps.map((p,i)=>(sheet&&W.bm=='sheet'?`(${i+1})`:'')+poseDesc(p,false)).join(';')+'。线稿只用于提取身体姿态、重心、四肢位置和镜头角度,不要画出线条、关节圆或辅助线。');+ if(np)L.push(poseInstructions(groups,poseNumbers,false,sheet));else if(P)L.push('姿势:保持原照片的姿势、构图和拍摄角度。');- if(E&&ei)L.push(`表情:${rE} 是一张无身份头模的表情参考(${ei.zh})。让人物做出完全一致的表情。只迁移神态——人物本人的五官、脸型和身份必须与照片完全一致,不要照搬参考头的脸。`);- L.push(`画面:${P&&W.keepBg&&!isGen()?'保留原照片的背景与光线;':''}${style[3]}。衣物垂坠自然,褶皱阴影真实,高细节。不要文字、水印或边框。`);+ if(E&&ei)L.push(`表情:${rE} 展示目标表情(${ei.zh})。只迁移神态。${P?'保留人物照片中的五官、脸型和身份。':''}`);+ L.push(...materials);+ L.push(`画面:${keepBackground?'保留原照片的背景与光线;':''}${style[3]}。${G?'衣物垂坠自然,褶皱阴影真实。':''}高细节。不要文字、水印或边框。`);if(ex)L.push('补充:'+ex)}return L.join('\n')}function reprompt(force){if(force||!W.dirty){$('#wbPrompt').value=compose();W.dirty=false}}// ---------- 渲染 -----------function pickRow(a,type,i){const it=a.kind=='lib'&&A.ITEMS[a.k];if(a.kind=='lib'&&!it)return'<div class="empty0">加载中…</div>';- const src=it?(type=='pose'?A.ath(it.angles[a.ai??it.ai].t):A.thumb(it)):a.url,t=it?A.title(it):(a.name||'自定义图片'),sub=it?(it.type=='pose'?it.line+' · '+it.angles[a.ai??it.ai].zh:it.cat+' · '+it.id):(type=='costume'?(W.garments.length>1?(i==0?'上装':'下装'):'本地上传'):'本地上传');- return`<div class="pick ${type}"><img src="${src}" alt="${esc(t)}"><div><b>${esc(t)}</b><small>${esc(sub)}</small></div>${(type=='pose'||type=='expr')&&it?`<select data-ang="${i}" aria-label="角度">${it.angles.map((x,j)=>`<option value="${j}" ${j==(a.ai??it.ai)?'selected':''}>${x.zh}</option>`).join('')}</select>`:''}<button class="rmx" data-rm="${type}" data-i="${i}" aria-label="移除" title="移除">×</button></div>`}-function render(){const G=isGen();$$('[data-mode]').forEach(b=>b.classList.toggle('on',b.dataset.mode==W.mode));- $('#stLead').textContent=G?'选模特类型和服装,直接出一张上身图。':'上传照片,选一套衣服,换上看看。';- $('#s1T').textContent=G?'模特':'人物照片';$('#s1R').textContent=G?'可传脸部参考':'必选';$('#s1T').textContent=G?'模特':'人物';- $('#wbPersons').innerHTML=W.persons.map((p,i)=>`<div class="pp"><img src="${p.url}" alt="人物照片 ${i+1}"><small>${p.w}×${p.h}</small><button class="x" data-rmp="${i}" aria-label="移除">×</button></div>`).join('');- $('#wbDrop').classList.toggle('mini',W.persons.length>0);$('#wbDrop').hidden=W.persons.length>=3;$('#wbChar').hidden=!G||hasPerson();+const boardLabels={portrait:'人物',costume:'服装',anime:'动画服装',dyn:'历代服饰',pose:'姿势',depth:'深度姿势',expr:'表情',hair:'发型',scene:'场景',light:'光影',prop:'道具',furn:'家具'};+const garmentTypes=['costume','anime','dyn'],otherTypes=['expr','hair','scene','light','prop','furn'];+const typeButton=(type,attr)=>`<button type="button" ${attr}="${type}">${boardLabels[type]}</button>`;+$('#wbOtherTypes').innerHTML=otherTypes.map(type=>typeButton(type,'data-pick')).join('');+const thumbnail=(ref,it)=>ref.url||(it.angles?A.ath(it.angles[ref.ai??it.ai].t):A.thumb(it));+function pickRow(ref,slot,index){+ const it=A.ITEMS[ref.k],type=it?.type||slot,name=it?A.title(it):ref.name||'自定义图片';+ const angle=it?.angles?.[ref.ai??it.ai],sub=it?`<span>${boardLabels[type]}</span> · ${esc(it.no||it.id)}`:'本地上传';+ const views=angle?`<select data-ang="${index}" data-slot="${slot}" aria-label="角度">${it.angles.map((a,i)=>`<option value="${i}" ${a===angle?'selected':''}>${esc(a.zh)}</option>`).join('')}</select>`:'';+ return `<div class="pick ${slot}" data-type="${type}"><img src="${esc(thumbnail(ref,it))}" alt=""${it?.ref?` referrerpolicy="${esc(it.ref)}"`:''}><div><b>${esc(name)}</b><small>${sub}</small></div>${views}<button type="button" class="rmx" data-rm="${slot}" data-i="${index}" aria-label="移除" title="移除">×</button></div>`;+}+function renderOther(){+ const refs=[...W.exprs,...W.extraRefs];+ const preview=$('#wbOtherPreview');+ preview.innerHTML=refs.slice(0,3).map(ref=>{+ const it=A.ITEMS[ref.k];+ return `<img data-type="${it.type}" src="${esc(thumbnail(ref,it))}" alt="" title="${esc(A.title(it))}"${it.ref?` referrerpolicy="${esc(it.ref)}"`:''}>`;+ }).join('');+ const count=$('#wbOtherCount');count.hidden=!refs.length;count.textContent=refs.length||'';+ $('#wbEx').innerHTML=W.exprs.map((ref,i)=>pickRow(ref,'expr',i)).join('');+ $('#wbOtherRefs').innerHTML=W.extraRefs.map((ref,i)=>pickRow(ref,'other',i)).join('');+}+let exampleRefs=[];+function paintBoard(){+ const output=W.results.length>0;+ const chosen=[...W.persons.map(ref=>['portrait',ref]),...W.garments.map(ref=>['costume',ref]),+ ...W.poses.map(ref=>['pose',ref]),...W.exprs.map(ref=>['expr',ref]),...W.extraRefs.map(ref=>[A.ITEMS[ref.k].type,ref])];+ const example=!chosen.length;+ $('#wbCanvasTitle').textContent=output?'生成结果':example&&exampleRefs.length?'搭配示例':'参考画板';+ const ratio=$('#wbAR').value;+ $('#wbCanvasRatio').textContent=!output&&ratio!=='auto'?ratio:'';+ if(output)return;+ const refs=example?exampleRefs.map(it=>[it.type,libItem(it)]):chosen;+ const cards=$('#wbBoardCards');+ cards.classList.toggle('sample',example);+ cards.classList.toggle('many',refs.length>3);+ cards.innerHTML=refs.map(([type,ref])=>{+ const item=A.ITEMS[ref.k];+ const source=thumbnail(ref,item),material=item?.type||type;+ const label=item?A.title(item):ref.name||boardLabels[type];+ return `<button class="board-card" data-pick="${material}" data-type="${material}"${item?` data-pk-key="${esc(item.k)}"`:''} title="${esc(label)}"><img src="${esc(source)}" alt="${esc(label)}"${item?.ref?` referrerpolicy="${esc(item.ref)}"`:''}><span>${boardLabels[material]}</span></button>`;+ }).join('');+ $('#wbExample').hidden=!example||!refs.length;+}+async function loadExample(){+ if(exampleRefs.length)return;+ const types=['portrait','costume','pose'];+ const groups=await Promise.allSettled(types.map(A.load));+ exampleRefs=groups.flatMap(result=>result.status==='fulfilled'?[result.value.find(it=>!it.a)].filter(Boolean):[]);+ paintBoard();+}+$('#wbExample').onclick=async()=>{+ const button=$('#wbExample');button.disabled=true;+ try{+ await setSel({portrait:exampleRefs.filter(it=>it.type==='portrait'),garment:exampleRefs.filter(it=>it.type==='costume'),pose:exampleRefs.filter(it=>it.type==='pose')});+ }catch{toast('素材未能载入,请重试')}finally{button.disabled=false}+};+function updateStart(){+ const ready=W.persons.length||W.garments.length||W.poses.length||W.exprs.length||W.extraRefs.length||+ $('#wbExtra').value.trim()||(W.dirty&&$('#wbPrompt').value.trim())||(isGen()&&W.char==='custom'&&W.charTxt.trim());+ const need=ready?[]:['选择素材或输入提示词'];+ const button=$('#wbGo');+ if(!W.busy){button.disabled=!!need.length;button.title=need.length?'请先'+need.join('、'):''}+ return need;+}+function setMode(mode){+ autoMode=false;W.mode=mode;SV('wbMode',mode);+ if(mode==='gen'&&W.style==='keep')W.style='studio';+ if(mode==='tryon'&&W.style==='studio'&&!W.dirtyStyle)W.style='keep';+}+function render(){+ if(autoMode)W.mode=hasPerson()&&W.garments.length?'tryon':'gen';+ const G=isGen();$$('[data-mode]').forEach(b=>{b.classList.toggle('on',b.dataset.mode==W.mode);b.setAttribute('aria-pressed',String(b.dataset.mode==W.mode))});+ $('#wbPersons').innerHTML=W.persons.map((p,i)=>`<div class="pp"><img src="${esc(p.url)}" alt="人物照片 ${i+1}">${p.w&&p.h?`<small>${p.w}×${p.h}</small>`: ''}<button class="x" data-rmp="${i}" aria-label="移除">×</button></div>`).join('');+ $('#wbPortraitPick').hidden=!!W.persons.length;$('#wbDrop').hidden=W.persons.length>=3;$('#wbChar').hidden=!G||hasPerson();$('#wbChars').innerHTML=CHARS.map(c=>`<button class="chip ${W.char==c[0]?'on':''}" data-char="${c[0]}">${c[1]}</button>`).join('');$('#wbCharTxt').hidden=W.char!='custom';$('#wbCharTxt').value=W.charTxt;- $('#wbG').innerHTML=W.garments.length?W.garments.map((g,i)=>pickRow(g,'costume',i)).join(''):'<button class="empty0" data-pick="costume"><span><b>选择服装</b><small>从库里选,或上传图片</small></span></button>';- $('#wbPo').innerHTML=W.poses.length?W.poses.map((p,i)=>pickRow(p,'pose',i)).join(''):`<button class="empty0" data-pick="pose"><span><b>选择姿势(可选)</b><small>${G?'不选就随机':'不选就保持原姿势'}</small></span></button>`;- $('#wbEx').innerHTML=W.exprs.length?W.exprs.map((g,i)=>pickRow(g,'expr',i)).join(''):'<button class="empty0" data-pick="expr"><span><b>选择表情(可选)</b><small>只取神态,不换脸</small></span></button>';- $('#wbBatch').hidden=W.poses.length<2;$$('[data-bm]').forEach(b=>b.classList.toggle('on',b.dataset.bm==W.bm));$('#wbAllAng').hidden=W.poses.length!=1||!A.ITEMS[(W.poses[0]||{}).k];+ $('#wbG').innerHTML=W.garments.length?W.garments.map((g,i)=>pickRow(g,'costume',i)).join(''):'<button class="empty0" data-pick="costume"><span><b>选择服装</b></span></button>';+ $('#wbPo').innerHTML=W.poses.length?W.poses.map((p,i)=>pickRow(p,'pose',i)).join(''):`<button class="empty0" data-pick="pose"><span><b>选择姿势</b></span></button>`;+ renderOther();+ $('#wbBatch').hidden=poseGroups(W.poses).length<2;$$('[data-bm]').forEach(b=>b.classList.toggle('on',b.dataset.bm==W.bm));$('#wbAllAng').hidden=W.poses.length!=1||!A.ITEMS[(W.poses[0]||{}).k];$('#wbStyles').innerHTML=STYLES.map(s=>`<button class="chip ${W.style==s[0]?'on':''}" data-style="${s[0]}">${s[1]}</button>`).join('');$('#wbKeepBg').checked=W.keepBg;$('#wbKeepBg').closest('label').hidden=G||!hasPerson();$$('[data-pl]').forEach(b=>b.classList.toggle('on',b.dataset.pl==W.pl));- const ok=!!cfg.key;$('#wbDot').className='dot'+(ok?' on':'');$('#wbProv').textContent=ok?PROV[cfg.prov].name+' · '+modelOf():'未配置 API';$('#wbDot2').className='dot'+(ok?' on':'');$('#wbProv2').textContent=ok?PROV[cfg.prov].name:'未配置 API';$('#wbOnb').hidden=ok;- const dn=[G?true:hasPerson(),W.garments.length>0,W.poses.length>0,!!(W.style||$('#wbExtra').value)];$$('.step[data-s]').forEach(e=>e.classList.toggle('done',dn[e.dataset.s-1]));- const jobs=nJobs();$('#wbGo').textContent='生成';$('#wbEst').textContent=`将生成 ${jobs} 张`;- const miss=[!G&&!hasPerson()&&'人物照片',!W.garments.length&&'服装',!ok&&'API 密钥'].filter(Boolean);$('#wbHint').textContent=miss.length?'还缺:'+miss.join('、'):'每张约半分钟';$('#wbHint').classList.toggle('miss',!!miss.length);const need=[!G&&!hasPerson()&&'上传人物照片',!W.garments.length&&'选择服装'].filter(Boolean);if(!W.busy){$('#wbGo').disabled=!!need.length;$('#wbGo').title=need.length?'请先'+need.join('、'):'';if(need.length)$('#wbGo').textContent='请先'+need[0]}$$('.flow [data-f]').forEach(e=>e.classList.toggle('on',e.dataset.f<4?dn[e.dataset.f-1]&&(e.dataset.f!=3||W.poses.length>0):!need.length));- SV('wbSel',{g:W.garments.filter(g=>g.kind=='lib').map(g=>g.k),p:W.poses.filter(p=>p.kind=='lib').map(p=>[p.k,p.ai]),e:W.exprs.filter(g=>g.kind=='lib').map(g=>[g.k,g.ai])});reprompt()}-const nJobs=()=>(W.poses.length>1&&W.bm=='each'?W.poses.length:1)*(+$('#wbN').value||1);+ const ok=configured();$('#wbDot').className='dot'+(ok?' on':'');$('#wbProv').textContent=provLabel()||'未配置 API';$('#wbDot2').className='dot'+(ok?' on':'');$('#wbProv2').textContent=ok?PROV[cfg.prov].name:'未配置 API';+ const sizes=[W.persons.length,W.garments.length,W.poses.length];+ for(const step of $$('.primary-materials .step')){+ const size=sizes[Number(step.dataset.s)-1];+ step.classList.toggle('done',size>0);+ step.querySelector('.pick-more').hidden=!size||(step.dataset.s==='1'&&size>=3);+ }+ const jobs=nJobs();if(!W.busy)$('#wbGo').textContent='生成';$('#wbEst').textContent=`将生成 ${jobs} 张`;+ updateStart();paintBoard();+ SV('wbSel',{r:W.persons.filter(p=>p.k).map(p=>p.k),g:W.garments.filter(g=>g.kind=='lib').map(g=>g.ai==null?g.k:[g.k,g.ai]),p:W.poses.map(p=>[p.k,p.ai]),e:W.exprs.map(e=>[e.k,e.ai]),x:W.extraRefs.map(x=>[x.k,x.ai])});reprompt()}+const nJobs=()=>(W.bm=='each'?Math.max(1,poseGroups(W.poses).length):1)*(+$('#wbN').value||1);// ---------- 上传 -----------async function addPortrait(it){if(W.persons.length>=3)return toast('最多 3 张人物照片');try{const x=await toJpeg(it.m,1536);W.persons.push({blob:x.blob,url:URL.createObjectURL(x.blob),w:x.w,h:x.h,k:it.k});render();toast(W.mode=='gen'?'已设为脸部参考(生成时保持这张脸)':'已设为人物照片')}catch(e){toast('人像加载失败')}}+function libPortrait(ref){return {kind:'portrait',k:ref.k,url:A.ITEMS[ref.k].m}}+function addPortrait(it){if(W.persons.length>=3)return toast('最多 3 张人物照片');W.persons.push(libPortrait(it));render();toast(W.mode=='gen'?'已设为脸部参考(生成时保持这张脸)':'已设为人物照片')}async function addPersons(files){files=[...files].filter(f=>/^image\//.test(f.type));if(!files.length)return toast('请选择图片文件');for(const f of files){if(W.persons.length>=3){toast('最多 3 张人物照片');break}const u=URL.createObjectURL(f);try{const r=await toJpeg(u,1536);W.persons.push({blob:r.blob,url:URL.createObjectURL(r.blob),w:r.w,h:r.h})}catch(e){toast('无法读取这张图片')}finally{URL.revokeObjectURL(u)}}render()}-const drop=$('#wbDrop');$('#wbFile').onchange=e=>{addPersons(e.target.files);e.target.value=''};+const drop=$('.person-step');$('#wbFile').onchange=e=>{addPersons(e.target.files);e.target.value=''};['dragenter','dragover'].forEach(t=>drop.addEventListener(t,e=>{e.preventDefault();drop.classList.add('over')}));['dragleave','drop'].forEach(t=>drop.addEventListener(t,e=>{e.preventDefault();drop.classList.remove('over')}));-drop.addEventListener('drop',e=>addPersons(e.dataTransfer.files));drop.addEventListener('keydown',e=>{if(e.key=='Enter'||e.key==' '){e.preventDefault();$('#wbFile').click()}});-$('#wbGFile').onchange=async e=>{const fs=[...e.target.files];e.target.value='';W.garments=W.garments.filter(g=>g.kind=='file');for(const f of fs){if(W.garments.length>=2){toast('最多上传 2 张服装图(上装 + 下装)');break}const u=URL.createObjectURL(f);try{const r=await toJpeg(u,1280);URL.revokeObjectURL(u);W.garments.push({kind:'file',blob:r.blob,url:URL.createObjectURL(r.blob),name:f.name})}catch(x){toast('无法读取服装图')}}render()};+drop.addEventListener('drop',e=>addPersons(e.dataTransfer.files));for(const label of $$('.upload-link'))label.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();label.querySelector('input').click()}});+$('#wbGFile').onchange=async e=>{+ const files=[...e.target.files];e.target.value='';+ for(const file of files){+ if(W.garments.length>=2){toast('最多 2 张服装参考图');break}+ const url=URL.createObjectURL(file);+ try{const result=await toJpeg(url,1280);W.garments.push(fileItem(result.blob,file.name))}+ catch{toast('无法读取服装图')}finally{URL.revokeObjectURL(url)}+ }+ render();+};document.addEventListener('paste',e=>{if(document.body.classList.contains('studio')&&!/INPUT|TEXTAREA/.test(document.activeElement.tagName)){const f=[...e.clipboardData.files].filter(f=>/^image/.test(f.type));if(f.length)addPersons(f)}});$('#studio').addEventListener('click',e=>{const t=e.target;let b;- if(b=t.closest('[data-rm]')){const i=+b.dataset.i;b.dataset.rm=='pose'?W.poses.splice(i,1):b.dataset.rm=='expr'?W.exprs.splice(i,1):W.garments.splice(i,1);render()}- if(b=t.closest('[data-rmp]')){W.persons.splice(+b.dataset.rmp,1);render()}- if(b=t.closest('[data-pick]'))picker(b.dataset.pick);- if(b=t.closest('[data-pl]')){W.pl=b.dataset.pl;SV('wbPl',W.pl);reprompt(true);render()}- if(b=t.closest('[data-mode]')){W.mode=b.dataset.mode;SV('wbMode',W.mode);if(W.mode=='gen'&&W.style=='keep'){W.style='studio'}if(W.mode=='tryon'&&W.style=='studio'&&!W.dirtyStyle)W.style='keep';W.dirty=false;render()}+ if(b=t.closest('[data-rm]')){+ const refs={pose:W.poses,expr:W.exprs,costume:W.garments,other:W.extraRefs}[b.dataset.rm];+ const index=Number(b.dataset.i),group=b.closest('.step,.material-extras'),type=b.closest('.pick').dataset.type;+ const [ref]=refs.splice(index,1);if(ref.blob)URL.revokeObjectURL(ref.url);+ render();+ const remaining=group.querySelectorAll('[data-rm="'+b.dataset.rm+'"]');+ const next=remaining[Math.min(index,remaining.length-1)]||group.querySelector('[data-pick="'+type+'"]:not([hidden])')||group.querySelector('.empty0');+ next?.focus({preventScroll:true});+ }+ if(b=t.closest('[data-rmp]')){+ const i=Number(b.dataset.rmp),[person]=W.persons.splice(i,1);+ if(person.blob)URL.revokeObjectURL(person.url);+ render();($('#wbPersons [data-rmp="'+Math.min(i,W.persons.length-1)+'"]')||$('#wbPortraitPick')).focus({preventScroll:true});+ }+ if(b=t.closest('[data-pick]'))picker(b.dataset.pick,b);+ if(b=t.closest('[data-pl]')){W.pl=b.dataset.pl;SV('wbPl',W.pl);reprompt(true);saveDraft();render()}+ if(b=t.closest('[data-mode]')){setMode(b.dataset.mode);render()}if(b=t.closest('[data-char]')){W.char=b.dataset.char;SV('wbChar',W.char);render()}if(b=t.closest('[data-style]')){W.style=b.dataset.style;W.dirtyStyle=1;SV('wbStyle',W.style);render()}if(b=t.closest('[data-bm]')){W.bm=b.dataset.bm;SV('wbBm',W.bm);render()}});-$('#studio').addEventListener('change',e=>{const s=e.target.closest('[data-ang]');if(s){const row=s.closest('.pick');if(row&&row.classList.contains('expr'))W.exprs[+s.dataset.ang].ai=+s.value;else W.poses[+s.dataset.ang].ai=+s.value;render()}if(e.target.id=='wbN')render();if(e.target.id=='wbKeepBg'){W.keepBg=e.target.checked;SV('wbKeepBg',W.keepBg);render()}});-$('#wbCharTxt').oninput=e=>{W.charTxt=e.target.value;SV('wbCharTxt',W.charTxt);reprompt()};+$('#studio').addEventListener('change',e=>{+ const s=e.target.closest('[data-ang]');+ if(s){+ const slot=s.dataset.slot,index=s.dataset.ang;+ const refs={pose:W.poses,expr:W.exprs,costume:W.garments,other:W.extraRefs}[slot];+ refs[Number(index)].ai=Number(s.value);+ render();$('#studio [data-slot="'+slot+'"][data-ang="'+index+'"]').focus({preventScroll:true});+ }else if(e.target.id==='wbN'||e.target.id==='wbAR'){saveDraft();render()}+ else if(e.target.id==='wbKeepBg'){W.keepBg=e.target.checked;SV('wbKeepBg',W.keepBg);render()}+});+$('#wbCharTxt').oninput=e=>{W.charTxt=e.target.value;SV('wbCharTxt',W.charTxt);reprompt();updateStart()};$('#wbAllAng').onclick=()=>{const p=W.poses[0],it=A.ITEMS[p.k];W.poses=it.angles.slice(0,6).map((a,i)=>({kind:'lib',k:p.k,ai:i}));toast(`已展开 ${W.poses.length} 个角度`);render()};-$('#wbPrompt').oninput=()=>W.dirty=true;$('#wbExtra').oninput=()=>reprompt();$('#wbReP').onclick=()=>{reprompt(true);toast('已按当前选择重新生成提示词')};-$('#wbCopyP').onclick=()=>A.copy($('#wbPrompt').value,'提示词');+$('#wbPrompt').oninput=()=>{W.dirty=true;saveDraft();updateStart()};+$('#wbExtra').oninput=()=>{reprompt();saveDraft();updateStart()};+$('#wbReP').onclick=()=>{reprompt(true);saveDraft();updateStart();toast('已按当前选择重新生成提示词')};+function copyStudioBrief(text, inputs, lang) {+ if(!$('#copyRefs').checked)return A.copy(text,'提示词');+ const selected=[...(inputs.persons||[]),...(inputs.garments||[]),...(inputs.poses||[]),...(inputs.exprs||[]),...(inputs.extraRefs||[])];+ const known=selected.filter(r=>r.k);+ function copyCurrent(){+ const items=selected.flatMap(r=>r.k ? (A.ITEMS[r.k]?[{...A.ITEMS[r.k],ai:r.ai??0}]:[]) : [null]);+ return A.copyBrief(text,items,lang,'提示词');+ }+ if(known.every(r=>A.ITEMS[r.k]))return copyCurrent();+ return A.needKeys(known.map(r=>r.k)).then(copyCurrent).catch(()=>toast('素材未能载入,请重试'));+}+$('#wbCopyP').onclick=()=>copyStudioBrief($('#wbPrompt').value,W,W.pl);// ---------- 选择器 -----------let pkType='costume',pkSink=null;async function picker(t){pkType=t;$('#pkT').textContent=t=='pose'?'选择姿势(可多选,最多 6 个)':t=='portrait'?'选择人像(作为人物 / 脸部参考)':t=='expr'?'选择表情(只迁移神态,不换脸)':t=='anime'?'选择动画服装':'选择服装';$('#pkDone').hidden=!pkSink&&t!='pose';$('#pk').hidden=false;document.body.style.overflow='hidden';$('#pkQ').value='';$('#pkG').innerHTML='<div class="skel"></div>'.repeat(12);await A.load(t);drawPk();setTimeout(()=>$('#pkQ').focus(),50)}-function drawPk(){const q=$('#pkQ').value.toLowerCase().trim().split(/\s+/).filter(Boolean),L=A.DATA[pkType].filter(A.ok).filter(it=>q.every(w=>(it._s||[it.id,it.zh,it.en,it.cat,it.line||''].join(' ').toLowerCase()).includes(w))).slice(0,150),sel=pkSink?new Set(pkSink.keys()):new Set(W.poses.map(p=>p.k));- $('#pkG').innerHTML=L.length?L.map(it=>`<button data-k="${it.k}" class="${pkType} ${sel.has(it.k)?'on':''}" title="${esc(A.title(it))}"><img loading="lazy" src="${A.thumb(it)}" alt="${esc(A.title(it))}"><span>${esc(A.title(it))}</span></button>`).join(''):'<p class="fine">没有匹配的结果</p>'}-let pq;$('#pkQ').oninput=()=>{clearTimeout(pq);pq=setTimeout(drawPk,150)};const pkClose=()=>{$('#pk').hidden=true;document.body.style.overflow='';pkSink=null;render()};$('#pkX').onclick=pkClose;$('#pkDone').onclick=pkClose;-$('#pk').onclick=e=>{if(e.target.id=='pk')return pkClose();const b=e.target.closest('[data-k]');if(!b)return;const k=b.dataset.k;- if(pkSink){b.classList.toggle('on',pkSink.toggle(k));return}- if(pkType=='pose'){const i=W.poses.findIndex(p=>p.k==k);if(i>=0)W.poses.splice(i,1);else if(W.poses.length>=6)return toast('最多选择 6 个姿势');else W.poses.push({kind:'lib',k,ai:A.ITEMS[k].ai});b.classList.toggle('on',i<0);$('#pkT').textContent=`选姿势(${W.poses.length}/6)`}- else if(pkType=='portrait'){pkClose();addPortrait(A.ITEMS[k])}- else if(pkType=='expr'){W.exprs=[{kind:'lib',k,ai:A.ITEMS[k].ai}];pkClose()}- else{W.garments=[{kind:'lib',k}];pkClose()}};+let pkType='costume',pkSink=null,pkItems=null,pkLastId='',pkTimer;+const poseType=type=>type==='pose'||type==='depth';+function pickerRefs(){+ if(pkSink)return pkSink.keys().map(k=>A.ITEMS[k]).filter(A.ok);+ if(poseType(pkType))return W.poses;+ if(garmentTypes.includes(pkType))return W.garments;+ if(pkType==='portrait')return W.persons;+ return pkType==='expr'?W.exprs:W.extraRefs;+}+function picker(type,opener=document.activeElement){+ const initialKey=opener?.dataset.pkKey;+ pkLastId=A.ITEMS[initialKey]?.id||'';$('#pkQ').value='';+ openDialog($('#pk'),$('#pkQ'),opener);+ showPickerType(type,null,initialKey);+}+function pickerPoseTitle(){+ if(pkSink)return '选择姿势';+ return W.poses.length?`姿势参考图(${W.poses.length}/6 张)`:'选择姿势参考图(最多 6 张)';+}+function pickerAnchor(){+ const grid=$('#pkG'),view=grid.getBoundingClientRect(),visible=[];+ for(const card of grid.querySelectorAll('button[data-k]')){+ const rect=card.getBoundingClientRect();+ if(rect.top>=view.bottom)break;+ if(rect.bottom<=view.top)continue;+ const anchor={item:A.ITEMS[card.dataset.k],angle:+card.dataset.ai,offset:rect.top-view.top};+ if(anchor.item.id===pkLastId)visible.unshift(anchor);else visible.push(anchor);+ }+ return {visible,scroll:grid.scrollTop};+}+async function showPickerType(type,anchor,initialKey){+ clearTimeout(pkTimer);pkType=type;pkItems=null;+ const poses=poseType(type);+ $('#pkPoseTypes').hidden=!poses;+ for(const tab of $$('#pkPoseTypes button')){+ const on=tab.dataset.pkType===type;tab.classList.toggle('on',on);tab.setAttribute('aria-pressed',on);+ }+ const group=garmentTypes.includes(type)?garmentTypes:otherTypes.includes(type)?otherTypes:null;+ const tabs=$('#pkMaterialTypes');+ tabs.hidden=!group;+ if(group){+ if(tabs.dataset.group!==group[0]){+ tabs.innerHTML=group.map(kind=>typeButton(kind,'data-pk-material')).join('');+ tabs.dataset.group=group[0];+ }+ for(const tab of tabs.children){+ const active=tab.dataset.pkMaterial===type;+ tab.classList.toggle('on',active);tab.setAttribute('aria-pressed',String(active));+ }+ }+ $('#pkDone').hidden=false;+ $('#pkT').textContent=poses?pickerPoseTitle():group===otherTypes?'其他素材':group===garmentTypes?'选择服装':'选择人物';+ const grid=$('#pkG');+ if(!A.DATA[type])grid.innerHTML='<div class="skel"></div>'.repeat(12);+ try{+ const items=await A.load(type);+ if(pkType!==type||$('#pk').hidden)return;+ pkItems=items;+ if(type==='depth'&&A.DATA.pose){+ const end=A.DATA.pose.length;+ const rank=it=>A.counterpartType(it)?(A.ITEMS['p:'+it.id]?.ord??end):end;+ pkItems=[...items].sort((a,b)=>rank(a)-rank(b));+ }+ drawPk(initialKey);+ if(initialKey)grid.querySelector(`[data-k="${CSS.escape(initialKey)}"]`)?.scrollIntoView({block:'nearest'});+ if(anchor){+ for(const {item,angle,offset} of anchor.visible){+ const mate=A.poseCounterpart(item,angle);+ const card=mate&&grid.querySelector(`[data-k="${CSS.escape(mate.item.k)}"]`);+ if(!card)continue;+ grid.scrollTop+=card.getBoundingClientRect().top-grid.getBoundingClientRect().top-offset;+ return;+ }+ grid.scrollTop=anchor.scroll;+ }+ }catch{+ if(pkType===type&&!$('#pk').hidden)grid.textContent='素材加载失败,请关闭后重试';+ }+}+function pickerPoseAngles(refs){+ const angles=new Map();+ for(const ref of refs){+ const item=A.ITEMS[ref.k];+ if(!A.ok(item))continue;+ const index=ref.ai??item.ai;+ if(item.type===pkType){angles.set(item.k,index);continue}+ const mate=A.poseCounterpart(item,index);+ if(mate&&!angles.has(mate.item.k))angles.set(mate.item.k,mate.angle);+ }+ return angles;+}+let pkMatches=[],pkRendered=0;+function drawPk(initialKey){+ if(!pkItems)return;+ const words=$('#pkQ').value.trim().toLowerCase().split(/\s+/).filter(Boolean);+ pkMatches=pkItems.filter(it=>{+ if(!A.ok(it))return false;+ if(!words.length)return true;+ const text=[it.id,it.no,it.ti,it.zh,it.en,it.ja,it.line,it.lineEn,it.lineJa,it.cat,it.catEn,it.catJa,it.kw,it.sec,it.len,it.st,...(it.angles||[]).flatMap(a=>[a.zh,a.en,a.ja])].join(' ').toLowerCase();+ return words.every(word=>text.includes(word));+ });+ const grid=$('#pkG');grid.replaceChildren();pkRendered=0;+ if(pkMatches.length){+ const count=poseType(pkType)?pkMatches.length:Math.max(150,initialKey?1+pkMatches.findIndex(it=>it.k===initialKey):0);+ appendPickerItems(count);+ }else grid.innerHTML='<p class="fine">没有匹配的结果</p>';+ grid.scrollTop=0;+}+function appendPickerItems(count){+ const refs=pickerRefs(),selected=new Set(refs.map(ref=>ref.k)),poses=poseType(pkType);+ const angles=poses?pickerPoseAngles(refs):null,items=pkMatches.slice(pkRendered,pkRendered+count);+ const markup=items.map(it=>{+ const on=selected.has(it.k),title=esc(A.title(it)),angle=poses?(angles.get(it.k)??it.ai):null;+ const src=poses?A.ath(it.angles[angle].t):A.thumb(it);+ return `<button type="button" data-k="${esc(it.k)}"${poses?` data-ai="${angle}"`:''} aria-pressed="${on}" class="${pkType} ${on?'on':''}" title="${title}"><img loading="lazy" src="${esc(src)}"${it.ref?` referrerpolicy="${esc(it.ref)}"`:''} alt=""><span>${title}</span></button>`;+ }).join('');+ $('#pkG').insertAdjacentHTML('beforeend',markup);+ pkRendered+=items.length;+}+$('#pkG').addEventListener('scroll',e=>{+ const grid=e.currentTarget;+ if(pkItems&&pkRendered<pkMatches.length&&grid.scrollHeight-grid.scrollTop-grid.clientHeight<grid.clientHeight)appendPickerItems(150);+},{passive:true});+$('#pkQ').oninput=()=>{+ pkLastId='';clearTimeout(pkTimer);pkTimer=setTimeout(drawPk,150);+};+function pkClose(){+ clearTimeout(pkTimer);pkItems=null;+ const dialog=$('#pk'),opener=dialogOpeners.get(dialog);+ if(!pkSink)render();+ pkSink=null;closeDialog(dialog);+ if(opener?.dataset.pick&&!opener.isConnected){+ const type=opener.dataset.pick==='depth'?'pose':opener.dataset.pick;+ const key=opener.dataset.pkKey,board=key&&$('#wbBoardCards').querySelector(`[data-pk-key="${CSS.escape(key)}"]`);+ const slot=[...$$(`#studio .step [data-pick="${CSS.escape(type)}"]`)].find(el=>el.getClientRects().length);+ (board||slot||$('#wbOther summary')).focus({preventScroll:true});+ }+}+$('#pkX').onclick=pkClose;$('#pkDone').onclick=pkClose;+$('#pk').onclick=e=>{+ if(e.target.id==='pk')return pkClose();+ const tab=e.target.closest('[data-pk-type]');+ if(tab){+ if(tab.dataset.pkType!==pkType)showPickerType(tab.dataset.pkType,pickerAnchor());+ return;+ }+ const material=e.target.closest('[data-pk-material]');+ if(material){if(material.dataset.pkMaterial!==pkType)showPickerType(material.dataset.pkMaterial);return}+ const card=e.target.closest('#pkG [data-k]');if(!card)return;+ const key=card.dataset.k,item=A.ITEMS[key],angle=poseType(pkType)?+card.dataset.ai:undefined;+ let on;+ if(pkSink)on=pkSink.toggle(key,angle);+ else if(poseType(pkType)){+ on=!W.poses.some(ref=>ref.k===key);+ if(!on)W.poses=W.poses.filter(ref=>ref.k!==key);+ else if(W.poses.length>=6)return toast('最多选择 6 张姿势参考图');+ else W.poses.push({kind:'lib',k:key,ai:angle});+ $('#pkT').textContent=pickerPoseTitle();+ }else if(pkType==='portrait'){+ const index=W.persons.findIndex(ref=>ref.k===key);+ on=index<0;+ if(!on)W.persons.splice(index,1);+ else if(W.persons.length<3)W.persons.push(libPortrait(item));+ else return toast('最多 3 张人物照片');+ }else{+ const refs=pickerRefs(),index=refs.findIndex(ref=>ref.k===key);+ on=index<0;+ if(!on)refs.splice(index,1);+ else if(pkType==='expr'){+ refs.splice(0,refs.length,libItem(item));+ for(const prior of $('#pkG').querySelectorAll('[aria-pressed="true"]')){+ prior.classList.remove('on');prior.setAttribute('aria-pressed','false');+ }+ }else if(garmentTypes.includes(pkType)&&refs.length>=2)return toast('最多 2 张服装参考图');+ else refs.push(libItem(item));+ }+ card.classList.toggle('on',on);card.setAttribute('aria-pressed',on);pkLastId=item.id;+};// ---------- 设置 ----------// ---------- 减少误拦截:只改发送给服务商的措辞,不改服装、姿势 ----------@@ -128,123 +496,404 @@ const NEUTRAL=[const FRAME={en:'Professional e-commerce fashion try-on photo for a clothing catalog. The subject is an adult, fully clothed in exactly the reference garments (same design, color and cut, nothing added or removed), keeping the same identity, in a natural, relaxed, non-suggestive pose, in a tasteful studio or lifestyle setting.',zh:'服装电商的专业试穿照片,用于商品目录。人物是成年人,完整穿着参考图中的服装(款式、颜色、剪裁完全一致,不增不减),保持同一人的长相,姿势自然放松,场景为简洁的影棚或生活场景。'};const neutralOn=()=>LS('wbNeutral')!==false;$('#wbNeutral').checked=neutralOn();$('#wbNeutral').onchange=e=>{SV('wbNeutral',e.target.checked);toast(e.target.checked?'已开启减少误拦截':'已关闭减少误拦截,将按原提示词发送')};-const isAdultJob=set=>[...W.garments,...(set||[])].some(g=>g.kind=='lib'&&A.ITEMS[g.k]&&A.ITEMS[g.k].a);-function neutralize(p){let t=p;for(const [a,b] of NEUTRAL)t=t.replace(a,b?'\x01'+b+'\x01':'\x02');+const isAdultJob=(garments,set)=>[...garments,...set].some(g=>g.kind=='lib'&&A.ITEMS[g.k]&&A.ITEMS[g.k].a);+function neutralize(p,lang){let t=p;for(const [a,b] of NEUTRAL)t=t.replace(a,b?'\x01'+b+'\x01':'\x02');t=t.replace(/\b(with|and|in)\s+\x02\s+(?:and|with)\b/gi,'$1').replace(/\x01\x02*\x01/g,'、').replace(/\x01\s+\x01/g,' ').replace(/[\x01]/g,'').replace(/\s*\x02\s*/g,' ').replace(/(^|[,,、;;::。.\n])\s*(?:and|with|,)?\s*(?=[,,、;;。.\n]|$)/g,'$1').replace(/([,、;])[,、;]+/g,'$1').replace(/([,;])\s*[,;]+/g,'$1').replace(/[ \t]{2,}/g,' ').replace(/\s+([,.;,。;、])/g,'$1').replace(/^[,,、]\s*|[,,、]\s*$/gm,'').replace(/[,,、]\s*([.。;;])/g,'$1');- const zh=/[\u4e00-\u9fa5]/.test(t.slice(0,40))&&W.pl!='en';return FRAME[zh?'zh':'en']+'\n'+t}-function cfgFill(){$$('[name=prov]').forEach(r=>r.checked=r.value==cfg.prov);const P=PROV[cfg.prov];$('#cfBase').value=cfg.base;$('#cfBase').placeholder=P.base||'https://你的中转地址/v1';$('#cfKey').value=cfg.key;$('#cfKey').placeholder=cfg.prov=='gemini'?'AIza…':'sk-… / 方舟 API Key';- $('#cfModel').value=cfg.model;$('#cfModel').placeholder=P.model;$('#cfModels').innerHTML=P.models.map(m=>`<option value="${m}">`).join('');$('#cfField').value=cfg.field;$('#cfProto').value=cfg.proto;$('#cfProtoW').hidden=cfg.prov!='custom';$('#cfFieldW').hidden=!(cfg.prov=='custom'&&cfg.proto=='edits');$('#cfProxy').checked=cfg.proxy;$('#cfHelp').innerHTML=({openai:'在 <a href="https://platform.openai.com/api-keys" target="_blank" rel="noopener">platform.openai.com/api-keys</a> 创建密钥;gpt-image-1 需要已验证的组织。',gemini:'在 <a href="https://aistudio.google.com/apikey" target="_blank" rel="noopener">Google AI Studio</a> 免费获取 API Key(AIza 开头)。',seedream:'在 <a href="https://console.volcengine.com/ark" target="_blank" rel="noopener">火山方舟控制台</a> 开通 Seedream 模型并创建 API Key;会自动走本站代理。',custom:'填写中转商提供的 Base URL(通常以 /v1 结尾)与密钥,并按中转文档选择接口协议。'})[cfg.prov]||'';$('#cfMsg').textContent='';$('#cfMsg').className='fine'}-function cfgRead(){return{prov:($('[name=prov]:checked')||{}).value||'openai',base:$('#cfBase').value.trim(),key:$('#cfKey').value.trim(),model:$('#cfModel').value.trim(),field:$('#cfField').value,proto:$('#cfProto').value,proxy:$('#cfProxy').checked}}-const cfgOpen=()=>{cfgFill();$('#cfg').hidden=false;document.body.style.overflow='hidden'},cfgClose=()=>{$('#cfg').hidden=true;document.body.style.overflow=''};-$('#wbCfg').onclick=cfgOpen;$('#wbCfg2').onclick=cfgOpen;$('#wbOnbGo').onclick=cfgOpen;$('#cfgX').onclick=cfgClose;$('#cfg').addEventListener('click',e=>{if(e.target.id=='cfg')cfgClose()});-$$('[name=prov]').forEach(r=>r.onchange=()=>{const o=cfgRead();Object.assign(cfg,o,{base:'',model:''});if(o.prov=='seedream')cfg.proxy=true;cfgFill();if(o.prov=='seedream')msg('火山方舟接口不允许浏览器跨域,已开启本站代理')});-$('#cfProto').onchange=()=>{cfg.proto=$('#cfProto').value;$('#cfFieldW').hidden=cfg.proto!='edits'};+ const zh=/[\u4e00-\u9fa5]/.test(t.slice(0,40))&&lang!='en';return FRAME[zh?'zh':'en']+'\n'+t}+let checkpoints=[];+let connectionCheck;+function cancelConnectionCheck(){+ if(connectionCheck)connectionCheck.abort();+ connectionCheck=null;+}+function showCheckpoints(selected,files){+ const field=$('#cfCheckpoint');+ field.replaceChildren(new Option('选择模型',''),...files.map(file=>new Option(file,file)));+ field.value=files.includes(selected)?selected:'';+}+function cfgFill(cfg){+ cancelConnectionCheck();+ const preset=cfg.prov==='local'&&localPreset;+ $('#cfCheckpointW').hidden=!preset;+ if(preset){+ const files=cfg.checkpoint&&!checkpoints.includes(cfg.checkpoint)?[cfg.checkpoint,...checkpoints]:checkpoints;+ showCheckpoints(cfg.checkpoint,files);+ }+ $('#cfg').classList.toggle('local-engine',cfg.prov==='local');+$$('[name=prov]').forEach(r=>r.checked=r.value==cfg.prov);const P=PROV[cfg.prov];$('#cfBase').value=cfg.base;$('#cfBase').placeholder=P.base||'https://你的中转地址/v1';$('#cfKey').value=cfg.key;$('#cfKey').placeholder=cfg.prov=='gemini'?'AIza…':'sk-… / 方舟 API Key';+ $('#cfModel').value=cfg.model;$('#cfModel').placeholder=P.model;$('#cfModels').innerHTML=P.models.map(m=>`<option value="${m}">`).join('');$('#cfField').value=cfg.field;$('#cfProto').value=cfg.proto;$('#cfProtoW').hidden=cfg.prov!='custom';$('#cfFieldW').hidden=!(cfg.prov=='custom'&&cfg.proto=='edits');$('#cfProxy').checked=cfg.proxy;$('#cfHelp').innerHTML=({local:preset?'使用一张参考图。测试连接后选择模型。':'使用本机已启动的引擎。',openai:'在 <a href="https://platform.openai.com/api-keys" target="_blank" rel="noopener">platform.openai.com/api-keys</a> 创建密钥;gpt-image-1 需要已验证的组织。',gemini:'在 <a href="https://aistudio.google.com/apikey" target="_blank" rel="noopener">Google AI Studio</a> 免费获取 API Key(AIza 开头)。',seedream:'在 <a href="https://console.volcengine.com/ark" target="_blank" rel="noopener">火山方舟控制台</a> 开通 Seedream 模型并创建 API Key;会自动走本站代理。',custom:'直连时,浏览器将密钥和图片发给填写的 HTTPS 地址。启用本站代理后会经本站转发,仅支持管理员登记的中转地址(含端口)。'})[cfg.prov]||'';$('#cfMsg').textContent='';$('#cfMsg').className='fine'}+function cfgRead(){+ const prov=$('[name=prov]:checked').value;+ const settings={prov,base:$('#cfBase').value.trim(),key:$('#cfKey').value.trim(),model:$('#cfModel').value.trim(),field:$('#cfField').value,proto:$('#cfProto').value,proxy:$('#cfProxy').checked};+ if(prov==='local'&&localPreset)settings.checkpoint=$('#cfCheckpoint').value;+ return settings;+}+const dialogOpeners=new Map();+function openDialog(dialog,focus){+ dialogOpeners.set(dialog,document.activeElement);+ dialog.hidden=false;document.body.style.overflow='hidden';focus.focus({preventScroll:true});+}+function closeDialog(dialog){+ dialog.hidden=true;document.body.style.overflow='';+ const opener=dialogOpeners.get(dialog);dialogOpeners.delete(dialog);+ if(opener?.isConnected)opener.focus({preventScroll:true});+}+function cfgOpen(){$('#cfKey').type='password';$('#cfEye').textContent='显示';cfgFill(cfg);openDialog($('#cfg'),$('[name=prov]:checked'))}+const cfgClose=()=>{cancelConnectionCheck();closeDialog($('#cfg'))};+$('#wbCfg').onclick=cfgOpen;$('#wbCfg2').onclick=cfgOpen;$('#cfgX').onclick=cfgClose;$('#cfg').addEventListener('click',e=>{if(e.target.id=='cfg')cfgClose()});+$$('[name=prov]').forEach(r=>r.onchange=()=>{+ const draft=cfgRead();+ if(draft.prov==cfg.prov)cfgFill(cfg);+ else cfgFill({...draft,base:'',key:'',model:'',proxy:draft.prov=='seedream'});+ if(draft.prov=='seedream')msg('火山方舟接口不允许浏览器跨域,已开启本站代理');+});+$('#cfProto').onchange=()=>{$('#cfFieldW').hidden=$('#cfProto').value!='edits'};$('#cfEye').onclick=()=>{const k=$('#cfKey');k.type=k.type=='password'?'text':'password';$('#cfEye').textContent=k.type=='password'?'显示':'隐藏'};-$('#cfSave').onclick=()=>{const o=cfgRead();if(o.prov=='custom'&&!o.base)return msg('自定义中转需要填写 Base URL',1);Object.assign(cfg,o);SV('wbCfg',cfg);render();cfgClose();toast('API 设置已保存在本机')};-$('#cfClr').onclick=()=>{cfg.key='';$('#cfKey').value='';SV('wbCfg',cfg);render();msg('已从本机清除密钥')};+$('#cfSave').onclick=()=>{const o=cfgRead();const error=configError(o);if(error)return msg(error,1);try{localStorage.setItem('wbCfg',JSON.stringify(o))}catch{return msg('无法保存设置,请检查浏览器存储权限',1)}Object.assign(cfg,o);render();cfgClose();toast('API 设置已保存在本机')};+$('#cfClr').onclick=()=>{+ cancelConnectionCheck();+ cfg.key='';$('#cfKey').value='';render();+ try{localStorage.setItem('wbCfg',JSON.stringify(cfg));msg('已从本机清除密钥')}+ catch{msg('当前页面已清除密钥,浏览器存储未能更新',1)}+};function msg(t,bad){const m=$('#cfMsg');m.textContent=t;m.className='fine '+(bad?'bad':'good')}-$('#cfTest').onclick=async()=>{const o=cfgRead();if(!o.key)return msg('请先填写 API Key',1);if(o.prov=='custom'&&!o.base)return msg('请填写 Base URL',1);const old=Object.assign({},cfg);Object.assign(cfg,o);msg('正在连接…');- try{const g=proto()=='gemini',url=g?`${root()}/models/${encodeURIComponent(modelOf())}`:`${root()}/models`;const r=await call(url,{method:'GET',headers:auth()});const j=await r.json().catch(()=>null);- if(!r.ok){if(cfg.prov=='seedream'&&r.status==404){if((r.headers.get('content-type')||'').includes('text/html')){const e=Error('');e.zh='本站代理未生效:/api/proxy 返回的是网站静态页面而不是接口响应,Seedream 暂时连不上,请稍后再试或联系站长';throw e}return msg('地址可达、密钥已被接受(方舟不提供模型列表接口,可直接生成测试)')}throw await apiErr(r,j)}- if(g)msg(`连接成功:模型 ${j&&j.displayName||modelOf()} 可用`);else{const ids=(j&&j.data||[]).map(m=>m.id),has=ids.includes(modelOf());msg(`连接成功:共 ${ids.length} 个模型`+(ids.length?(has?`,包含 ${modelOf()}`:`,但未找到 ${modelOf()}(中转可能不列出,可直接尝试)`):''))}}- catch(e){msg(nice(e),1)}finally{Object.assign(cfg,old)}};-// ---------- 请求 -----------function auth(){return proto()=='gemini'?{'x-goog-api-key':cfg.key}:{Authorization:'Bearer '+cfg.key}}+$('#cfg').addEventListener('input',()=>{+ cancelConnectionCheck();+ $('#cfMsg').textContent='';+});+$('#cfTest').onclick=async()=>{+ const settings=cfgRead();+ cancelConnectionCheck();+ if(settings.prov!=='local'){+ if(!settings.key)return msg('请先填写 API Key',1);+ const invalid=configError(settings);+ if(invalid)return msg(invalid,1);+ }+ const check=new AbortController();+ connectionCheck=check;+ msg('正在连接…');+ try{+ if(settings.prov!=='local'){+ const result=await testConnection(settings,modelOf(settings),check.signal);+ if(!check.signal.aborted)msg(result);+ return;+ }+ const reply=await fetch('/api/local/status',{headers:{'x-posewear-local':'1'},signal:check.signal});+ if(localPreset&&reply.status===503)throw Error('无法连接本机 ComfyUI。请先启动服务,再测试连接。');+ if(!reply.ok)throw Error(await reply.text());+ const status=await reply.json();+ if(check.signal.aborted)return;+ if(localPreset){+ checkpoints=status.checkpoints;+ showCheckpoints($('#cfCheckpoint').value,checkpoints);+ if(!checkpoints.length)return msg('ComfyUI 中还没有可用的 checkpoint',1);+ }+ msg('本机引擎已连接');+ }catch(error){+ if(!check.signal.aborted)msg(settings.prov==='local'?error.message:nice(error),1);+ }finally{+ if(connectionCheck===check)connectionCheck=null;+ }+};const p2=n=>String(n).padStart(2,'0'),stamp=d=>`${d.getFullYear()}${p2(d.getMonth()+1)}${p2(d.getDate())}-${p2(d.getHours())}${p2(d.getMinutes())}`;-const OFF=/^(api\.openai\.com|generativelanguage\.googleapis\.com|ark\.[a-z0-9-]+\.(volces|bytepluses)\.com)$/;-function call(url,o){let hn='';try{hn=new URL(url).hostname}catch(e){}const cu=cfg.prov=='custom'||!OFF.test(hn);if(!cfg.proxy)return fetch(url,o);const h=new Headers(o.headers||{});h.set('x-target-url',url);if(cu)h.set('x-proxy-custom','1');return fetch('/api/proxy',Object.assign({},o,{headers:h}))}-async function fetchResult(url){let r=await fetch(url).catch(()=>null);if(!r||!r.ok)r=await fetch('/api/proxy',{headers:{'x-target-url':url,'x-proxy-kind':'image'}}).catch(()=>null);if(r&&r.ok)return r.blob();const e=Error('');e.zh='结果图片无法在浏览器中下载,请直接打开:'+url;throw e}--const SAFE_RE=/safety system|safety_violations|moderation_blocked|content_policy_violation|content policy|SensitiveContent|sensitive content|PROHIBITED_CONTENT|IMAGE_SAFETY|\bSAFETY\b|BLOCKLIST|SPII|blocked by|内容安全|敏感/i;-const CAT=[[/minor|child|CSAM/i,'涉及未成年人'],[/sexual|SEXUALLY_EXPLICIT|nudity|porn|色情/i,'性感/暴露内容'],[/violen|gore|血腥|暴力/i,'暴力或血腥'],[/self-?harm/i,'自残'],[/hate|HATE_SPEECH/i,'仇恨'],[/harass/i,'骚扰'],[/illicit|DANGEROUS/i,'危险或违法内容'],[/SPII|personal/i,'个人隐私信息'],[/copyright|RECITATION|trademark/i,'版权内容']];-function safeErr(raw,j,rid){const t=String(raw||'')+' '+JSON.stringify(j||'');if(!SAFE_RE.test(t))return null;const e=Error(String(raw||'safety'));const c=CAT.filter(x=>x[0].test(t)).map(x=>x[1]);- e.safe={cats:[...new Set(c)],where:/InputImage|input image/i.test(t)?'in':/OutputImage|output/i.test(t)?'out':'',rid:rid||(t.match(/req_[A-Za-z0-9]+/)||[])[0]||''};- let r=String(raw||'').trim();if(cfg.key)r=r.split(cfg.key).join('***');e.raw=r||t.slice(0,600);e.zh='被服务商的安全审核拦下了';return e}-async function apiErr(r,j){if(j===undefined)j=await r.json().catch(()=>null);const raw=(j&&(j.error&&(j.error.message||j.error.status||j.error)||j.message))||r.statusText||'';{const se=safeErr(typeof raw=='string'?raw:JSON.stringify(raw),j,(j&&j.error&&j.error.request_id)||r.headers.get('x-request-id'));if(se){se.status=r.status;return se}}- const m={400:'请求参数有误:常见原因是模型不支持参考图、画幅尺寸不对或图片格式不支持,可换个模型或画幅再试',401:'密钥无效或已过期,请检查 API Key',403:'没有权限:密钥无此模型权限、账户未验证,或所在地区不受支持',404:'地址或模型不存在:请检查 Base URL 和模型名',413:'图片太大,请换一张更小的照片',429:'请求过于频繁或额度已用完,请稍后再试或检查账户余额',500:'服务商内部错误,请稍后重试',502:'网关错误(中转服务不可用)',503:'服务暂时不可用,请稍后重试',504:'服务商响应超时,请重试'}[r.status]||('请求失败(HTTP '+r.status+')');- let t=String(typeof raw=='string'?raw:JSON.stringify(raw));if(cfg.key)t=t.split(cfg.key).join('***');const bad=/API_KEY_INVALID|API key not valid|invalid api key|Incorrect API key|AuthenticationError|InvalidApiKey/i.test(t+' '+JSON.stringify(j||''));const ans=!bad&&t.match(/Argument not supported:\s*(\w+)/i);const e=Error(t);e.status=r.status;e.zh=(bad?'密钥无效或已过期,请检查 API Key':ans?`该服务商不支持 ${ans[1]} 参数:当前接口协议与它的规格对不上,请检查「接口协议」设置(xAI 请改选 xAI 协议)`:m)+(t?`\n服务商返回:${t.slice(0,300)}`:'');return e}-function nice(e){if(e.name=='AbortError')return'已取消';if(e instanceof TypeError)return'无法连接到服务商:网络不通,或该地址不允许浏览器跨域访问(CORS)。\n可在 API 设置中开启「通过本站代理转发」。';return e.zh||e.message||String(e)}-const AR={auto:null,'2:3':'1024x1536','3:4':'1024x1536','9:16':'1024x1536','1:1':'1024x1024','4:3':'1536x1024','16:9':'1536x1024'};-const SD={auto:'1728x2304','2:3':'1664x2496','3:4':'1728x2304','9:16':'1440x2560','1:1':'2048x2048','4:3':'2304x1728','16:9':'2560x1440'};-const toB=async d=>(await fetch('data:image/png;base64,'+d)).blob();-async function openaiData(j){const d=j&&j.data&&j.data[0];if(!d){const e=Error('');e.zh='服务商没有返回图片数据'+(j&&j.error?':'+(j.error.message||''):'');throw e}return d.b64_json?toB(d.b64_json):fetchResult(d.url)}-async function genOnce(imgs,prompt,sig,arO){const ar=arO||$('#wbAR').value,m=modelOf(),P=proto();let warn='';- if(P=='gemini'){const parts=[{text:prompt}];for(const b of imgs)parts.push({inline_data:{mime_type:b.type||'image/jpeg',data:await b64(b)}});const gc={responseModalities:['TEXT','IMAGE']};if(ar!='auto')gc.imageConfig={aspectRatio:ar};- const r=await call(`${root()}/models/${encodeURIComponent(m)}:generateContent`,{method:'POST',signal:sig,headers:Object.assign({'Content-Type':'application/json'},auth()),body:JSON.stringify({contents:[{role:'user',parts}],generationConfig:gc})});- const j=await r.json().catch(()=>null);if(!r.ok)throw await apiErr(r,j);const c=j&&j.candidates&&j.candidates[0],ps=((j&&j.candidates)||[]).flatMap(c=>(c.content&&c.content.parts)||[]),im=ps.find(p=>(p.inlineData||p.inline_data||{}).data);- if(!im){const why=(j&&j.promptFeedback&&j.promptFeedback.blockReason)||(c&&c.finishReason);{const rs=(c&&c.safetyRatings||[]).filter(x=>x.blocked||/HIGH|MEDIUM/.test(x.probability||'')).map(x=>x.category).join(' ');const se=why&&/SAFETY|PROHIBITED|BLOCKLIST|SPII|OTHER/i.test(why)?safeErr(why+' '+rs+' '+((c&&c.finishMessage)||''),null,j&&j.responseId):null;if(se)throw se}const t=ps.map(p=>p.text).filter(Boolean).join(' ');const e=Error(t);e.zh='模型没有返回图片'+(why?`(${why},可能触发了安全策略)`:'')+(t?'\n模型回复:'+t.slice(0,300):'');throw e}- const d=im.inlineData||im.inline_data;return{blob:await(await fetch(`data:${d.mimeType||d.mime_type||'image/png'};base64,${d.data}`)).blob()}}- const json=async(withImgs,extra)=>{const body=Object.assign({model:m,prompt,n:1},extra);if(withImgs&&imgs.length)body.image=await Promise.all(imgs.map(dataURL));- const r=await call(`${root()}/images/generations`,{method:'POST',signal:sig,headers:Object.assign({'Content-Type':'application/json'},auth()),body:JSON.stringify(body)});const j=await r.json().catch(()=>null);if(!r.ok)throw await apiErr(r,j);return openaiData(j)};- if(P=='seedream'){const ex={size:SD[ar]||SD.auto,response_format:'b64_json',watermark:false};if(/seedream-4/.test(m))ex.sequential_image_generation='disabled';try{return{blob:await json(true,ex)}}catch(e){if(!e.safe&&e.status==400&&/image|参考/i.test(e.message)){warn='该模型没有接收参考图,结果只按文字生成,人物与服装可能对不齐。';return{blob:await json(false,ex),warn}}throw e}}- if(P=='xai'){const body={model:m,prompt,n:1,response_format:'b64_json'};if(ar!='auto')body.aspect_ratio=ar;let used=imgs;- if(imgs.length>5){used=imgs.slice(0,5);warn='xAI 参考图最多 5 张,已只发送前 5 张。'}- if(used.length){const us=await Promise.all(used.map(dataURL));if(us.length==1)body.image={url:us[0]};else body.images=us.map(u=>({url:u}))}- const r=await call(`${root()}/images/${used.length?'edits':'generations'}`,{method:'POST',signal:sig,headers:Object.assign({'Content-Type':'application/json'},auth()),body:JSON.stringify(body)});const j=await r.json().catch(()=>null);if(!r.ok)throw await apiErr(r,j);return{blob:await openaiData(j),warn}}- const sz=AR[ar]||(/^gpt-image/.test(m)?'auto':'1024x1024');- if(P=='json')return{blob:await json(true,{size:sz})};- const edits=async field=>{const fd=new FormData();fd.append('model',m);fd.append('prompt',prompt);const one=/^dall-e-2$/.test(m);(one?imgs.slice(0,1):imgs).forEach((b,i)=>fd.append(field,b,`ref-${i+1}.jpg`));fd.append('n','1');fd.append('size',one&&sz=='auto'?'1024x1024':sz);- const r=await call(`${root()}/images/edits`,{method:'POST',signal:sig,headers:auth(),body:fd});const j=await r.json().catch(()=>null);if(!r.ok)throw await apiErr(r,j);return openaiData(j)};- const f0=cfg.prov=='custom'?cfg.field:'image[]';- try{return{blob:await edits(f0)}}catch(e){if(e.name=='AbortError'||e.safe)throw e;if(/Argument not supported/i.test(e.message))throw e;- if(e.status==400&&/image/i.test(e.message)&&!/safety|moderation|reject/i.test(e.message)){try{return{blob:await edits(f0=='image[]'?'image':'image[]'),warn:'已自动改用另一种图片字段名重试成功。'}}catch(x){}}- if([404,405,415,501].includes(e.status)||/edits|not supported|unsupported|no such|invalid url/i.test(e.message)){try{return{blob:await json(true,{size:sz}),warn:'该接口不支持 images/edits,已自动改用 images/generations(JSON 多图)。'}}catch(x){if(x.name=='AbortError')throw x;return{blob:await json(false,{size:sz}),warn:'该接口不支持参考图,结果只按文字生成,人物与服装可能对不齐。'}}}- throw e}}// ---------- 进度 -----------let T0,tick,PR=0,done=0,total=1;function stage(t){$('#wbStage1').textContent=t}-function busy(on){$('#wbBusy').hidden=!on;$('#wbGo').classList.toggle('run',on);if(on)$('#wbGo').innerHTML='<i class="ring"></i>生成中…';$('#wbGo').disabled=on;clearInterval(tick);if(on){T0=Date.now();PR=.03;tick=setInterval(()=>{const s=(Date.now()-T0)/1e3,cap=(done+.95)/total;PR=Math.max(done/total,Math.min(cap,PR+(cap-PR)*.03));$('#wbProg').style.transform=`scaleX(${PR})`;$('#wbTime').textContent=`${Math.round(s)} 秒`+(total>1?` · 已完成 ${done} / ${total}`:'');},250)}else render()}-async function run(opts={}){if(!cfg.key){toast('请先配置你的 API');cfgOpen();return{got:[],errs:[],warns:[],nokey:true}}if(!opts.quick){if(!isGen()&&!hasPerson())return toast('请先上传人物照片');if(!W.garments.length)return toast('请先选择服装')}- let modeBak=null;if(opts.quick&&!hasPerson()&&W.mode!='gen'){modeBak=W.mode;W.mode='gen'}- const ac=new AbortController();W.busy=ac;$('#wbErr').hidden=true;$('#wbWarn').hidden=true;- const n=opts.n||(+$('#wbN').value||1),sets=W.poses.length>1&&W.bm=='each'?W.poses.map(p=>[p]):[W.poses];const jobs=[];sets.forEach(s=>{for(let i=0;i<n;i++)jobs.push(s)});- done=0;total=jobs.length;if(!opts.quick)busy(true);stage('正在准备素材…');const errs=[],warns=new Set(),got=[];- try{const pb=W.persons.map(p=>p.blob),gb=await Promise.all(W.garments.map(assetBlob)),eb=await Promise.all(W.exprs.map(assetBlob)),cache=new Map();const poseB=async p=>{const key=p.k+':'+p.ai;if(!cache.has(key))cache.set(key,assetBlob(p));return cache.get(key)};- const custom=opts.prompt!=null?opts.prompt:(W.dirty?$('#wbPrompt').value.trim():null);stage(total>1?`模型正在绘制… 共 ${total} 张`:'模型正在绘制…');- let q=0;const worker=async()=>{while(q<jobs.length&&!ac.signal.aborted){const set=jobs[q++];try{const imgs=[...pb,...gb,...await Promise.all(set.map(poseB)),...eb];const prompt0=custom&&(sets.length==1||opts.quick)?custom:compose(set),soft=neutralOn()&&!isAdultJob(set),prompt=soft?neutralize(prompt0):prompt0;W.lastSent=prompt;- const jc=new AbortController(),onA=()=>jc.abort();ac.signal.addEventListener('abort',onA);let tmo=false;const tm=setTimeout(()=>{tmo=true;jc.abort()},window.__TMO||180000);let r;try{r=await genOnce(imgs,prompt,jc.signal,opts.ar)}catch(x){x.sent=prompt;if(tmo&&!ac.signal.aborted){const y=Error('timeout');y.zh='等了 3 分钟还没有返回。服务商可能正忙,稍后点「重试」。';throw y}throw x}finally{clearTimeout(tm);ac.signal.removeEventListener('abort',onA)}if(r.warn)warns.add(r.warn);const rec={t:Date.now()+Math.random(),prov:cfg.prov,model:modelOf(),prompt,orig:soft?prompt0:null,neutral:soft,mode:W.mode,label:set.map(p=>poseDesc(p,false).split('(')[0]).join(' / ')||'',before:pb[0]||null,after:r.blob};got.push(rec);await save(rec);W.results=got.slice();if(!opts.quick)show(got.length-1)}- catch(e){if(e.name=='AbortError')throw e;errs.push(e)}finally{done++;if(opts.onTick)opts.onTick(done,total)}}};- await Promise.all(Array.from({length:Math.min(2,jobs.length)},worker));- if(got.length){toast(got.length>1?`完成 ${got.length} 张`:'生成完成');hist();window.HIS&&HIS.refresh()}if(errs.length&&!opts.quick){const e=errs.find(x=>x.safe)||errs[0];errBox(e,got.length?`${errs.length} 张生成失败`:'')}- if(warns.size&&!opts.quick){$('#wbWarn').hidden=false;$('#wbWarn').textContent=[...warns].join(' ')}}- catch(e){if(e.name=='AbortError'){toast('已取消生成');if(got.length)hist()}else if(!opts.quick)errBox(e);else errs.push(e)}- finally{if(!opts.quick)busy(false);else render();W.busy=null;if(modeBak)W.mode=modeBak}- return{got,errs,warns:[...warns]}}-function errBox(e,head){const el=$('#wbErr');el.hidden=false;el.classList.toggle('safe',!!e.safe);- if(e.safe){const S=e.safe,c=S.cats.length?`,原因是<b>${S.cats.join('、')}</b>`:'';const w=S.where=='in'?'上传的照片或服装图':S.where=='out'?'生成出来的图片':'这次请求';- el.innerHTML=`<b>${head?head+' · ':''}被服务商的安全审核拦下了</b><p>${(PROV[cfg.prov]||{}).name||'服务商'} 判断${w}不合规${c}。真人照片配上比较暴露的服装(泳装、内衣、露背等)很容易被拦,OpenAI 审核最严,Gemini 和豆包 Seedream 相对宽松一些。</p><p class="fine">可以换一家服务商,或换一套遮挡多一点的服装。原样重试大多还会被拦。</p><div class="row"><button class="sm" data-ef="prov">换服务商重试</button><button class="sm ghost" data-ef="cos">换一套服装</button><button class="sm ghost" id="wbRetry">重试</button></div>${neutralOn()?'':'<div class="row"><button class="sm" data-ef="neutral">打开减少误拦截后重试</button></div>'}<details class="raw"><summary>查看原始信息</summary><pre>${esc(e.raw+(S.rid&&!e.raw.includes(S.rid)?'\nrequest id: '+S.rid:'')+(e.sent?'\n\n实际发送的提示词'+(neutralOn()?'(已开启减少误拦截)':'')+':\n'+e.sent:''))}</pre><button class="sm ghost" data-ef="copy">复制</button></details>`;return}+let tick,done=0,total=1;+function stage(t){$('#wbStage1').textContent=t}+function busy(on){+ const panel=$('#wbBusy'),go=$('#wbGo'),progress=$('#wbProg');+ panel.hidden=!on;go.classList.toggle('run',on);go.disabled=on;clearInterval(tick);+ if(!on){render();return}+ go.textContent='生成中…';const started=Date.now();+ const update=()=>{+ progress.max=total;+ if(total>1)progress.value=done;else progress.removeAttribute('value');+ $('#wbTime').textContent=Math.floor((Date.now()-started)/1000)+' 秒'+(total>1?` · 已完成 ${done} / ${total}`:'');+ };+ update();tick=setInterval(update,1000);+}+let retryBatch=null;+function jobBatch(opts){+ const state=opts.selection?selectionState(opts.selection,opts.lang):{...W};+ const mode=state.persons.length&&state.garments.length?state.mode:'gen';+ const persons=state.persons.map(p=>({...p})),garments=state.garments.map(g=>({...g})),exprs=state.exprs.map(e=>({...e}));+ const poses=state.poses.map(p=>({...p}));+ const groups=poseGroups(poses);+ const split=!opts.quick&&groups.length>1&&state.bm=='each';+ const sets=split?groups:[poses];+ const count=Number(opts.n||$('#wbN').value)||1;+ const custom=opts.prompt??(!opts.selection&&W.dirty?$('#wbPrompt').value.trim():null);+ const ar=opts.ar||$('#wbAR').value;+ const jobs=[];+ for(const set of sets){+ const original=custom||compose(set,state);+ const soft=garments.length>0&&$('#wbNeutral').checked&&!isAdultJob(garments,[...set,...exprs,...state.extraRefs]);+ const prompt=soft?neutralize(original,state.pl):original;+ const label=poseGroups(set).map(([ref])=>{+ const item=A.ITEMS[ref.k],view=item.angles[ref.ai??item.ai];+ return item.zh+' · '+view.zh;+ }).join(' / ');+ for(let i=0;i<count;i++)jobs.push({set,prompt,original,soft,label});+ }+ return {jobs,persons,garments,exprs,extraRefs:state.extraRefs.map(ref=>({...ref})),mode,ar,lang:state.pl,bm:state.bm};+}+function recordInputs(batch,job,imgs){+ const ref=item=>({k:item.k,ai:item.ai});+ return {persons:batch.persons.map((p,i)=>({k:p.k,w:p.w,h:p.h,...(i?{blob:imgs[i]}:{})})),+ garments:batch.garments.map(g=>g.kind=='file'?{name:g.name,blob:g.blob}:ref(g)),+ poses:job.set.map(ref),exprs:batch.exprs.map(ref),extraRefs:batch.extraRefs.map(ref),ar:batch.ar,lang:batch.lang,bm:batch.bm};+}+async function run(opts={}){+ const outcome={got:[],errs:[],warns:[],unsaved:0,cancelled:false};+ if(W.busy){outcome.errs.push(Error('已有生成任务正在进行'));return outcome}+ if(!opts.quick&&!opts.retry){+ const need=updateStart();if(need.length)return toast('请先'+need.join('、'));+ }+ const batch=opts.retry||jobBatch(opts);+ if(!batch.jobs[0].original.trim()){outcome.errs.push(Error('选择素材或输入提示词'));return outcome}+ if(!configured()){toast('请先配置你的 API');cfgOpen();outcome.nokey=true;return outcome}+ const invalid=configError(cfg);if(invalid){outcome.errs.push(Error(invalid));cfgOpen();msg(invalid,1);return outcome}+ const settings={...cfg},controller=new AbortController();+ const signal=controller.signal;+ W.busy=controller;+ if(!opts.quick)retryBatch=null;+ $('#wbErr').hidden=true;$('#wbWarn').hidden=true;+ done=0;total=batch.jobs.length;+ if(!opts.quick)busy(true);+ stage('正在准备素材…');+ const warnings=new Set(),failed=[],retained=opts.retry?.retained||[];+ const blobs=new Map();+ const imageFor=item=>{+ if(!blobs.has(item))blobs.set(item,assetBlob(item,signal));+ return blobs.get(item);+ };+ let next=0;+ const worker=async()=>{+ while(next<batch.jobs.length&&!signal.aborted){+ const job=batch.jobs[next++];+ try{+ const items=[...batch.persons,...batch.garments,...job.set,...batch.exprs,...batch.extraRefs];+ const imgs=await Promise.all(items.map(imageFor));+ signal.throwIfAborted();+ stage(total>1?`模型正在绘制… 共 ${total} 张`:'模型正在绘制…');+ W.lastSent=job.prompt;+ const request=new AbortController(),cancel=()=>request.abort();+ signal.addEventListener('abort',cancel,{once:true});+ let timeout=false,result;+ const timer=setTimeout(()=>{timeout=true;request.abort()},window.__TMO||180000);+ try{+ result=await generateImage({+ images:imgs,prompt:job.prompt,signal:request.signal,ratio:batch.ar,+ settings,model:modelOf(settings),checkpoint:localPreset?settings.checkpoint:null+ });+ request.signal.throwIfAborted();+ }catch(error){+ if(timeout&&!signal.aborted){const e=Error('timeout');e.zh='等了 3 分钟还没有返回。服务商可能正忙,稍后点「重试」。';throw e}+ throw error;+ }finally{clearTimeout(timer);signal.removeEventListener('abort',cancel)}+ if(result.warn)warnings.add(result.warn);+ const rec={t:Date.now()+Math.random(),prov:settings.prov,model:modelOf(settings),prompt:job.prompt,orig:job.soft?job.original:null,+ neutral:job.soft,mode:batch.mode,label:job.label,before:batch.persons.length?imgs[0]:null,after:result.blob,inputs:recordInputs(batch,job,imgs)};+ outcome.got.push(rec);+ try{await save(rec)}catch{outcome.unsaved++}+ if(!opts.quick){W.results=[...retained,...outcome.got];show(W.results.length-1)}+ }catch(error){+ if(signal.aborted)break;+ error.sent=job.prompt;outcome.errs.push(error);failed.push(job);+ }finally{done++;if(opts.onTick)opts.onTick(done,total)}+ }+ };+ try{+ await Promise.all(Array.from({length:Math.min(2,batch.jobs.length)},worker));+ outcome.cancelled=signal.aborted;+ if(outcome.unsaved)warnings.add('生成完成,部分图片未能存入生成记录,请先下载。');+ if(outcome.got.length){hist();window.HIS?.refresh()}+ if(signal.aborted)toast('已取消生成');+ else if(outcome.got.length)toast(outcome.unsaved?'记录保存失败,请先下载':outcome.got.length>1?`完成 ${outcome.got.length} 张`:'生成完成');+ if(!opts.quick&&failed.length){+ retryBatch={...batch,jobs:failed,retained:[...retained,...outcome.got]};+ const error=outcome.errs.find(e=>e.safe)||outcome.errs[0];+ errBox(error,retained.length||outcome.got.length?`${failed.length} 张生成失败`:'',batch.garments.length>0);+ }+ outcome.warns=[...warnings];+ if(!opts.quick&&warnings.size){$('#wbWarn').hidden=false;$('#wbWarn').textContent=outcome.warns.join(' ')}+ }finally{+ W.busy=null;+ if(!opts.quick)busy(false);+ }+ return outcome;+}+function errBox(e,head,hasGarment){const el=$('#wbErr');el.hidden=false;el.classList.toggle('safe',!!e.safe);+ if(e.safe){+ const safety=e.safe,where=safety.where==='in'?'提交的参考图':safety.where==='out'?'生成结果':'本次请求';+ const reason=safety.cats.map(cat=>esc(window.PWLocale.t(cat))).join(' · ');+ const edit=hasGarment?'<button class="sm ghost" data-ef="cos">换一套服装</button>':'<button class="sm ghost" data-ef="prompt">编辑提示词</button>';+ const detail=e.raw+(safety.rid&&!e.raw.includes(safety.rid)?'\nrequest id: '+safety.rid:'')+(e.sent?'\n\n'+window.PWLocale.t('实际发送的提示词')+'\n'+e.sent:'');+ el.innerHTML=`<b>${head?esc(head)+' · ':''}<span>被服务商的安全审核拦下了</span></b><p>${esc(PROV[cfg.prov].name)} · <span>${where}</span>${reason?' · '+reason:''}</p><div class="row"><button class="sm" data-ef="prov">换服务商重试</button>${edit}<button class="sm ghost" id="wbRetry">重试</button></div>${hasGarment&&!neutralOn()?'<button class="sm" data-ef="neutral">打开减少误拦截后重试</button>':''}<details class="raw"><summary>查看原始信息</summary><pre>${esc(detail)}</pre><button class="sm ghost" data-ef="copy">复制</button></details>`;return}el.innerHTML=`<b>${head||'生成失败'}</b><p>${esc(nice(e)).replace(/\n/g,'<br>')}</p><div class="row"><button class="sm" id="wbRetry">重试</button><button class="sm ghost" data-open-cfg>检查 API 设置</button></div>`}-$('#wbStage').addEventListener('click',e=>{const f=e.target.closest('[data-ef]');if(f){const k=f.dataset.ef;if(k=='prov'){cfgOpen();const p=$('#cfg .prov');p.scrollIntoView({block:'start'});p.classList.remove('hl');void p.offsetWidth;p.classList.add('hl');const o=$('[name=prov]:not(:checked)');o&&o.focus()}if(k=='cos')picker('costume');if(k=='neutral'){SV('wbNeutral',true);$('#wbNeutral').checked=true;run()}if(k=='copy')A.copy?A.copy(f.previousElementSibling.textContent):navigator.clipboard.writeText(f.previousElementSibling.textContent).then(()=>toast('已复制'));return}if(e.target.id=='wbRetry')run();if(e.target.closest('[data-open-cfg]'))cfgOpen()});-$('#wbGo').onclick=run;$('#wbAgain').onclick=run;$('#wbStop').onclick=()=>W.busy&&W.busy.abort();+$('#wbStage').addEventListener('click',e=>{const f=e.target.closest('[data-ef]');if(f){const k=f.dataset.ef;if(k=='prov'){cfgOpen();const p=$('#cfg .prov');p.scrollIntoView({block:'start'});p.classList.remove('hl');void p.offsetWidth;p.classList.add('hl');const o=$('[name=prov]:not(:checked)');o&&o.focus()}if(k=='cos')picker('costume');if(k=='prompt')$('#wbPrompt').focus();if(k=='neutral'){SV('wbNeutral',true);$('#wbNeutral').checked=true;run()}if(k=='copy')A.copy?A.copy(f.previousElementSibling.textContent):navigator.clipboard.writeText(f.previousElementSibling.textContent).then(()=>toast('已复制'));return}if(e.target.id=='wbRetry'&&retryBatch)run({retry:retryBatch});if(e.target.closest('[data-open-cfg]'))cfgOpen()});+$('#wbGo').onclick=()=>run();$('#wbAgain').onclick=()=>run();$('#wbStop').onclick=()=>W.busy&&W.busy.abort();// ---------- 结果 ----------let urls=[];const ru=new Map();const U=b=>{if(!ru.has(b))ru.set(b,URL.createObjectURL(b));return ru.get(b)};function show(i,meta){const r=W.results[i];if(!r)return;{let d=$('#wbSentD');if(!d){d=document.createElement('details');d.id='wbSentD';d.className='raw sent';$('#wbOutAct').after(d)}d.hidden=!r.prompt;d.innerHTML=r.prompt?`<summary>查看原始信息${r.neutral?' · 已减少误拦截':''}</summary><pre>${esc((r.orig?'原提示词:\n'+r.orig+'\n\n实际发送:\n':'实际发送:\n')+r.prompt)}</pre>`:''}W.ri=i;const a=U(r.after),hasB=!!r.before;$('#wbAfter').src=a;if(hasB)$('#wbBefore').src=U(r.before);$('#wbCmp').hidden=false;$('#wbCmp').classList.toggle('solo',!hasB||!W.cmp);$('#wbCmpT').hidden=!hasB;$('#wbCmpT').textContent=W.cmp?'关闭对比':'前后对比';- $('#wbPh0').hidden=true;$('#wbErr').hidden=true;$('#wbOutAct').hidden=false;setX(50);$('#wbZip').hidden=W.results.length<2;if(!matchMedia('(prefers-reduced-motion: reduce)').matches){$('#wbAfter').animate([{opacity:0,transform:'scale(1.03)',filter:'blur(8px)'},{opacity:1,transform:'none',filter:'none'}],{duration:620,easing:'cubic-bezier(.16,1,.3,1)'});if(hasB&&W.cmp&&!W._wig){W._wig=1;const t0=performance.now();const f=t=>{const p=(t-t0)/1400;if(p>=1)return setX(50);setX(50+Math.sin(p*Math.PI*2)*12*(1-p));requestAnimationFrame(f)};setTimeout(()=>requestAnimationFrame(f),500)}}$('#wbMeta').textContent=meta||((PROV[r.prov]||{name:r.prov}).name+' · '+r.model+(r.label?' · '+r.label:''));- const R=$('#wbRes');R.hidden=W.results.length<2;R.innerHTML=W.results.map((x,j)=>`<button data-ri="${j}" class="${j==i?'on':''}"><img src="${U(x.after)}" alt="结果 ${j+1}"></button>`).join('');const rct=$('#wbStage').getBoundingClientRect();if(rct.bottom<0||rct.top>innerHeight)$('#wbStage').scrollIntoView({behavior:'smooth',block:'nearest'})}+ $('#wbPh0').hidden=true;$('#wbCanvasTitle').textContent='生成结果';$('#wbCanvasRatio').textContent='';$('#wbErr').hidden=true;$('#wbOutAct').hidden=false;setX(50);$('#wbZip').hidden=W.results.length<2;if(!matchMedia('(prefers-reduced-motion: reduce)').matches){$('#wbAfter').animate([{opacity:0,transform:'scale(1.03)',filter:'blur(8px)'},{opacity:1,transform:'none',filter:'none'}],{duration:620,easing:'cubic-bezier(.16,1,.3,1)'});if(hasB&&W.cmp&&!W._wig){W._wig=1;const t0=performance.now();const f=t=>{const p=(t-t0)/1400;if(p>=1)return setX(50);setX(50+Math.sin(p*Math.PI*2)*12*(1-p));requestAnimationFrame(f)};setTimeout(()=>requestAnimationFrame(f),500)}}$('#wbMeta').textContent=meta||((PROV[r.prov]||{name:r.prov}).name+' · '+r.model+(r.label?' · '+r.label:''));+ const R=$('#wbRes');R.hidden=W.results.length<2;R.innerHTML=W.results.map((x,j)=>`<button data-ri="${j}" class="${j==i?'on':''}"><img src="${U(x.after)}" alt="结果 ${j+1}"></button>`).join('');const rct=$('#wbStage').getBoundingClientRect();if(rct.bottom<0||rct.top>innerHeight)$('#wbStage').scrollIntoView({behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'instant':'smooth',block:'nearest'})}$('#wbRes').onclick=e=>{const b=e.target.closest('[data-ri]');b&&show(+b.dataset.ri)};$('#wbCmpT').onclick=()=>{W.cmp=!W.cmp;show(W.ri)};$('#wbZip').onclick=async()=>{if(!window.makeZip)return;const ts=stamp(new Date());const fs=W.results.map((r,i)=>({name:`posewear-${r.mode=='gen'?'gen':'tryon'}-${ts}-${String(i+1).padStart(2,'0')}.png`,blob:r.after}));window.X.dl(await makeZip(fs),`posewear-tryon-${ts}.zip`);toast(`已打包 ${fs.length} 张`)};-$('#cfExp').onclick=()=>{const withKey=confirm('导出时包含 API Key 吗?\n确定 = 包含,取消 = 不含密钥');const o={...cfg};if(!withKey)delete o.key;window.X.dl(new Blob([JSON.stringify({app:'衣姿 PoseWear',type:'api-config',cfg:o},null,2)],{type:'application/json'}),'衣姿-API设置.json');msg('已导出设置'+(withKey?'(含密钥,请妥善保管)':'(不含密钥)'))};-$('#cfImp').onclick=()=>$('#cfImpF').click();$('#cfImpF').onchange=async e=>{try{const j=JSON.parse(await e.target.files[0].text());const o=j.cfg||j;if(!o.prov)throw 0;Object.assign(cfg,o);SV('wbCfg',cfg);cfgFill();render();msg('已导入设置')}catch(err){msg('导入失败:文件格式不正确',1)}e.target.value=''};+$('#cfExp').onclick=()=>{const notice='导出时包含 API Key 吗?\n确定 = 包含,取消 = 不含密钥';const withKey=confirm(window.PWLocale?.t(notice)||notice);const o=cfgRead();if(!withKey)delete o.key;window.X.dl(new Blob([JSON.stringify({app:'衣姿 PoseWear',type:'api-config',cfg:o},null,2)],{type:'application/json'}),'衣姿-API设置.json');msg('已导出设置'+(withKey?'(含密钥,请妥善保管)':'(不含密钥)'))};+$('#cfImp').onclick=()=>$('#cfImpF').click();$('#cfImpF').onchange=async e=>{try{const j=JSON.parse(await e.target.files[0].text());const o=j.cfg||j;if(!Object.hasOwn(PROV,o.prov)||['base','key','model','checkpoint'].some(k=>o[k]!=null&&typeof o[k]!='string'))throw Error();cfgFill({...cfg,...o,key:o.key||''});msg('已读入设置,点击保存后生效')}catch(err){msg('导入失败:文件格式不正确',1)}e.target.value=''};$('#wbDl').onclick=()=>{const r=W.results[W.ri];if(!r)return;const l=document.createElement('a');l.href=U(r.after);l.download=`posewear-${r.mode=='gen'?'gen':'tryon'}-${stamp(new Date(r.t))}-${String(W.ri+1).padStart(2,'0')}.png`;l.click()};-$('#wbUse').onclick=async()=>{const r=W.results[W.ri];if(!r)return;const x=await toJpeg(U(r.after),1536);W.persons=[{blob:x.blob,url:URL.createObjectURL(x.blob),w:x.w,h:x.h}];W.mode='tryon';render();toast('已将结果设为新的人物照片')};+$('#wbUse').onclick=async()=>{const r=W.results[W.ri];if(!r)return;const x=await toJpeg(U(r.after),1536);W.persons=[{blob:x.blob,url:URL.createObjectURL(x.blob),w:x.w,h:x.h}];render();toast('已将结果设为新的人物照片')};function setX(x){$('#wbCmp').style.setProperty('--x',x+'%');$('#wbRange').value=x}$('#wbRange').oninput=e=>setX(e.target.value);// ---------- IndexedDB ----------let dbp;const db=()=>dbp||(dbp=new Promise((r,j)=>{const q=indexedDB.open('lk-studio',1);q.onupgradeneeded=()=>q.result.createObjectStore('h',{keyPath:'t'});q.onsuccess=()=>r(q.result);q.onerror=()=>j(q.error)}));const tx=async(m,f)=>{const d=await db();return new Promise((r,j)=>{const t=d.transaction('h',m),s=t.objectStore('h'),q=f(s);t.oncomplete=()=>r(q&&q.result);t.onerror=()=>j(t.error)})};-async function save(rec){try{await tx('readwrite',s=>s.put(rec));const all=await tx('readonly',s=>s.getAllKeys());if(all.length>200)await tx('readwrite',s=>{all.slice(0,all.length-200).forEach(k=>s.delete(k))})}catch(e){}}-let hu=[];async function hist(){let L=[];try{L=(await tx('readonly',s=>s.getAll()))||[]}catch(e){}L.sort((a,b)=>b.t-a.t);hu.forEach(URL.revokeObjectURL);hu=[];+async function save(rec){+ await tx('readwrite',store=>{+ store.put(rec);+ const keys=store.getAllKeys();+ keys.onsuccess=()=>keys.result.slice(0,-200).forEach(key=>store.delete(key));+ });+}+let hu=[];async function hist(){let L;+ try{L=await tx('readonly',s=>s.getAll())}catch{$('#wbHist').textContent='无法读取生成记录,请检查浏览器存储权限';return}+ L.sort((a,b)=>b.t-a.t);hu.forEach(URL.revokeObjectURL);hu=[];const list=L.slice(0,30);- $('#wbHist').innerHTML=list.length?(list.map(r=>{const u=URL.createObjectURL(r.after);hu.push(u);return`<button data-t="${r.t}" title="${esc(new Date(r.t).toLocaleString('zh-CN')+(r.label?' · '+r.label:''))}"><img src="${u}" alt="历史结果"><span>${r.mode=='gen'?'生图':'试穿'} · ${esc(new Date(r.t).toLocaleTimeString('zh-CN',{hour:'2-digit',minute:'2-digit'}))}</span><i data-del="${r.t}" aria-label="删除">×</i></button>`}).join('')+(L.length>30?`<button class="hist-more" data-go="history" title="查看全部 ${L.length} 条记录"><b>全部</b><small>${L.length}条 ↗</small></button>`:'')):'<p class="fine">还没有生成记录</p>';W.hist=L}-$('#wbHist').onclick=async e=>{const d=e.target.closest('[data-del]');if(d){e.stopPropagation();const rec=(W.hist||[]).find(x=>x.t==d.dataset.del);await tx('readwrite',s=>s.delete(+d.dataset.del));await hist();if(rec)toast('已删除 1 条记录',async()=>{await tx('readwrite',s=>s.put(rec));hist()});return}const b=e.target.closest('[data-t]');if(!b)return;const r=W.hist.find(x=>x.t==b.dataset.t);if(r){W.results=[r];show(0,(PROV[r.prov]||{name:r.prov}).name+' · '+r.model+' · '+new Date(r.t).toLocaleString('zh-CN'));$('#wbStage').scrollIntoView({behavior:'smooth',block:'nearest'})}};+ $('#wbHist').innerHTML=list.length?(list.map(r=>{const u=URL.createObjectURL(r.after);hu.push(u);return`<button data-t="${r.t}" title="${esc(new Date(r.t).toLocaleString('zh-CN')+(r.label?' · '+r.label:''))}"><img src="${u}" alt="历史结果"><span>${r.mode=='gen'?'生图':'试穿'} · ${esc(new Date(r.t).toLocaleTimeString('zh-CN',{hour:'2-digit',minute:'2-digit'}))}</span><i data-del="${r.t}" aria-label="删除">×</i></button>`}).join('')+(L.length>30?`<button class="hist-more" data-go="history" title="查看全部 ${L.length} 条记录"><b>全部</b><small>${L.length}条 ↗</small></button>`:'')):'';W.hist=L}+$('#wbHist').onclick=async e=>{const d=e.target.closest('[data-del]');if(d){e.stopPropagation();const rec=(W.hist||[]).find(x=>x.t==d.dataset.del);await tx('readwrite',s=>s.delete(+d.dataset.del));await hist();if(rec)toast('已删除 1 条记录',async()=>{await tx('readwrite',s=>s.put(rec));hist()});return}const b=e.target.closest('[data-t]');if(!b)return;const r=W.hist.find(x=>x.t==b.dataset.t);if(r){W.results=[r];show(0,(PROV[r.prov]||{name:r.prov}).name+' · '+r.model+' · '+new Date(r.t).toLocaleString('zh-CN'));$('#wbStage').scrollIntoView({behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'instant':'smooth',block:'nearest'})}};$('#wbHClr').onclick=async()=>{const all=W.hist||[];if(!all.length)return toast('还没有生成记录');await tx('readwrite',s=>s.clear());await hist();toast(`已清空 ${all.length} 条记录`,async()=>{await tx('readwrite',s=>{all.forEach(r=>s.put(r))});hist()})};// ---------- 对外 -----------let inited=false;async function init(){if(inited)return;inited=true;const gk=[].concat(g0.g||[]),pk=(g0.p||[]).filter(x=>Array.isArray(x)),ek=(g0.e||[]).filter(x=>Array.isArray(x));const need=[gk.length&&'costume',gk.some(k=>k[0]=='a')&&'anime',pk.length&&'pose',ek.length&&'expr'].filter(Boolean);if(need.length)await Promise.all(need.map(A.load)).catch(()=>{});- if(!W.garments.length)W.garments=gk.filter(k=>A.ITEMS[k]).slice(0,1).map(k=>({kind:'lib',k}));if(!W.poses.length)W.poses=pk.filter(x=>A.ITEMS[x[0]]).slice(0,6).map(x=>({kind:'lib',k:x[0],ai:x[1]??A.ITEMS[x[0]].ai}));if(!W.exprs.length)W.exprs=ek.filter(x=>A.ITEMS[x[0]]).slice(0,1).map(x=>({kind:'lib',k:x[0],ai:x[1]??A.ITEMS[x[0]].ai}));hist()}-async function setSel(sel){await init();W.garments=(sel.garment||[]).slice(0,2).map(it=>({kind:'lib',k:it.k}));W.poses=(sel.pose||[]).slice(0,6).map(it=>({kind:'lib',k:it.k,ai:it.ai}));W.exprs=(sel.expr||[]).slice(0,1).map(it=>({kind:'lib',k:it.k,ai:it.ai}));const pk=(sel.portrait||[])[0];if(pk){if(!(W.persons.length&&W.persons[0].k==pk.k)){W.persons=[];await addPortrait(pk)}}else W.persons=[];reprompt(true);render();return $('#wbPrompt').value}-window.WB={async show(){await init();render()},async pick(it){await init();if(it.type=='pose'){if(!W.poses.some(p=>p.k==it.k)){if(W.poses.length>=6)W.poses.shift();W.poses.push({kind:'lib',k:it.k,ai:it.ai})}toast(`已加入姿势参考(${W.poses.length} 个)`)}else if(it.type=='portrait'){await addPortrait(it)}else if(it.type=='expr'){W.exprs=[{kind:'lib',k:it.k,ai:it.ai}];toast('已加入表情参考(只取神态)')}else{W.garments=[{kind:'lib',k:it.k}];toast('已选为试穿服装')}A.setTab('studio')},_W:W,_cfg:cfg,db:{tx,save,hist:()=>tx('readonly',s=>s.getAll()),del:t=>tx('readwrite',s=>s.delete(t)),clear:()=>tx('readwrite',s=>s.clear()),put:r=>tx('readwrite',s=>s.put(r)),refreshHist:hist},quick:o=>run(Object.assign({},o||{},{quick:true})),cfgOpen,nice,busy:()=>!!W.busy,stop:()=>{if(W.busy)W.busy.abort()},provLabel:()=>cfg.key?PROV[cfg.prov].name+' · '+modelOf():'',setSel,openPicker:(t,sink)=>{pkSink=sink;picker(t)}};+function libItem(ref){return {kind:'lib',k:ref.k,ai:ref.ai??A.ITEMS[ref.k]?.ai}}+function fileItem(blob,name){return {kind:'file',blob,name,url:URL.createObjectURL(blob)}}+function groupLibraryRefs(refs){+ const groups={portrait:[],garment:[],pose:[],expr:[],extra:[]};+ for(const ref of refs){+ const item=A.ITEMS[ref.k];+ if(item)groups[A.studioSlot(item.type)].push(libItem(ref));+ }+ return groups;+}+let initPromise;+function init(){+ if(!initPromise)initPromise=(async()=>{+ const refs=[...(g0.r||[]),...(g0.g||[]),...(g0.p||[]),...(g0.e||[]),...(g0.x||[])]+ .map(saved=>Array.isArray(saved)?{k:saved[0],ai:saved[1]}:{k:saved});+ await A.needKeys(refs.map(ref=>ref.k));+ const groups=groupLibraryRefs(refs);+ if(!W.persons.length)W.persons=groups.portrait.slice(0,3).map(libPortrait);+ if(!W.garments.length)W.garments=groups.garment.slice(0,2);+ if(!W.poses.length)W.poses=groups.pose.slice(0,6);+ if(!W.exprs.length)W.exprs=groups.expr.slice(0,1);+ if(!W.extraRefs.length)W.extraRefs=groups.extra;+ hist();+ })().catch(error=>{initPromise=null;throw error});+ return initPromise;+}+function selectionState(sel,lang){+ const groups=groupLibraryRefs([...(sel.portrait||[]),...(sel.garment||[]),...(sel.pose||[]),...(sel.expr||[]),...(sel.extra||[])]);+ const persons=groups.portrait.slice(0,1).map(libPortrait),garments=groups.garment.slice(0,2);+ return {...W,extra:'',charTxt:Object.values(groups).some(items=>items.length)?W.charTxt:'',pl:lang?(lang=='zh'?'zh':'en'):W.pl,persons,garments,poses:groups.pose.slice(0,6),+ exprs:groups.expr.slice(0,1),extraRefs:groups.extra,mode:persons.length&&garments.length?'tryon':'gen',bm:'sheet'};+}+let importVersion=0;+async function setSel(sel,extraText,draft){+ const version=++importVersion;+ await init();+ if(version!==importVersion)return;+ const state=selectionState(sel);+ W.extraRefs=state.extraRefs;W.garments=state.garments;W.poses=state.poses;W.exprs=state.exprs;+ if(state.persons.length||draft)W.persons=state.persons;+ else W.persons=W.persons.filter(p=>!p.k);+ if(draft){+ setMode(state.mode);W.pl=draft.lang;W.bm=state.bm;SV('wbPl',W.pl);SV('wbBm',W.bm);+ $('#wbN').value=draft.count;$('#wbAR').value=draft.ratio;$('#wbExtra').value=extraText||'';+ }else appendExtra(extraText);+ reprompt(true);+ if(draft?.prompt){$('#wbPrompt').value=draft.prompt;W.dirty=true}+ saveDraft();+ render();+ return $('#wbPrompt').value;+}+function appendExtra(text){+ if(!text)return;+ const input=$('#wbExtra');+ if(!input.value.split('\n').includes(text)){+ input.value=[input.value.trim(),text].filter(Boolean).join('\n');+ saveDraft();+ }+}+async function addSelection(sel,extraText){+ await init();+ const refs=groupLibraryRefs([...(sel.portrait||[]),...(sel.garment||[]),...(sel.pose||[]),...(sel.expr||[]),...(sel.extra||[])]);+ if(refs.garment.length)W.garments=refs.garment.slice(0,2);+ if(refs.expr.length)W.exprs=refs.expr.slice(0,1);+ for(const it of refs.pose){+ if(W.poses.some(p=>p.k==it.k))continue;+ if(W.poses.length>=6)W.poses.shift();+ W.poses.push(libItem(it));+ }+ for(const it of refs.portrait){+ if(W.persons.length>=3)break;+ if(!W.persons.some(p=>p.k==it.k))await addPortrait(it);+ }+ for(const it of refs.extra)if(!W.extraRefs.some(r=>r.k===it.k&&r.ai===it.ai))W.extraRefs.push(it);+ appendExtra(extraText);render();+}+async function pick(it){+ await init();+ if(it.type=='pose'||it.type=='depth'){+ if(!W.poses.some(p=>p.k==it.k)){if(W.poses.length>=6)W.poses.shift();W.poses.push(libItem(it))}+ toast(`已加入姿势参考(${W.poses.length} 个)`);+ }else if(it.type=='portrait'){await addPortrait(it)}+ else if(it.type=='expr'){W.exprs=[libItem(it)];toast('已加入表情参考(只取神态)')}+ else if(['costume','anime','dyn'].includes(it.type)){W.garments=[libItem(it)];toast('已选为试穿服装')}+ else{if(!W.extraRefs.some(r=>r.k===it.k&&r.ai===it.ai))W.extraRefs.push(libItem(it));toast('已加入工作台')}+ A.setTab('studio');+}+async function restoreRecord(r){+ await init();+ const inputs=r.inputs,problems=[];+ const garments=inputs?.garments||[];+ const savedRefs=[...garments,...(inputs?.poses||[]),...(inputs?.exprs||[]),...(inputs?.extraRefs||[])].filter(ref=>ref.k);+ const personKeys=(inputs?.persons||[]).filter(ref=>ref.k).map(ref=>ref.k);+ try{await A.needKeys([...personKeys,...savedRefs.map(ref=>ref.k)])}catch{problems.push('部分素材库未能加载')}+ if(savedRefs.some(ref=>!A.ITEMS[ref.k]))problems.push('部分参考图需重选');+ const groups=groupLibraryRefs(savedRefs);+ W.garments=garments.flatMap(g=>g.blob?[fileItem(g.blob,g.name)]:A.ITEMS[g.k]&&A.studioSlot(A.ITEMS[g.k].type)==='garment'?[libItem(g)]:[]);+ W.poses=groups.pose;W.exprs=groups.expr;W.extraRefs=groups.extra;+ W.persons=groups.portrait.map(libPortrait);+ const savedPeople=inputs?.persons||(r.before?[{}]:[]);+ for(const [i,p] of savedPeople.entries()){+ const blob=i?p.blob:r.before;+ if(!blob){problems.push('部分人物照片需重选');continue}+ let w=p.w,h=p.h;+ if(!w||!h){const image=await createImageBitmap(blob).catch(()=>null);if(image){w=image.width;h=image.height;image.close()}}+ W.persons.push({blob,k:p.k,w:w||'?',h:h||'?',url:URL.createObjectURL(blob)});+ }+ autoMode=false;W.mode=r.mode||'tryon';W.pl=inputs?.lang||W.pl;W.bm=inputs?.bm||'each';+ $('#wbAR').value=inputs?.ar||'auto';$('#wbN').value='1';$('#wbExtra').value='';+ $('#wbNeutral').checked=!!r.neutral;+ $('#wbPrompt').value=r.orig||r.prompt||'';W.dirty=!!$('#wbPrompt').value;+ SV('wbMode',W.mode);SV('wbPl',W.pl);SV('wbBm',W.bm);saveDraft();+ if(!inputs)problems.push('旧记录的服装和姿势需重选');+ if(cfg.prov!==r.prov||modelOf()!==r.model)problems.push('请核对当前服务商及模型');+ render();+ return problems;+}+window.WB={copyStudioBrief,async show(){try{await init();render();if(!W.results.length)loadExample()}catch{toast('试穿台选材加载失败,请重新打开后再试')}},pick,restoreRecord,+ _W:W,_cfg:cfg,db:{tx,save,hist:()=>tx('readonly',s=>s.getAll()),del:t=>tx('readwrite',s=>s.delete(t)),clear:()=>tx('readwrite',s=>s.clear()),put:r=>tx('readwrite',s=>s.put(r)),refreshHist:hist},+ quick:o=>run({...o,quick:true}),cfgOpen,nice,busy:()=>!!W.busy,stop:()=>W.busy?.abort(),configured,provLabel,+ setSel,addSelection,selectionPrompt:(sel,lang)=>compose(undefined,selectionState(sel,lang)),openPicker:(t,sink)=>{pkSink=sink;picker(t)}};if(document.body.classList.contains('studio'))WB.show();if(location.hash=='#studio'){const t0=()=>scrollTo(0,0);requestAnimationFrame(t0);addEventListener('load',()=>setTimeout(t0,0),{once:true})}-addEventListener('keydown',e=>{if(e.key=='Escape'){if(!$('#pk').hidden)pkClose();else if(!$('#cfg').hidden)cfgClose()}});+addEventListener('keydown',e=>{+ const dialog=!$('#pk').hidden?$('#pk'):!$('#cfg').hidden?$('#cfg'):null;+ if(!dialog)return;+ if(e.key=='Escape'){e.preventDefault();e.stopImmediatePropagation();dialog.id=='pk'?pkClose():cfgClose();return}+ if(e.key!='Tab')return;+ const nodes=[...dialog.querySelectorAll('button,input,select,textarea,a[href]')].filter(el=>!el.disabled&&el.getClientRects().length);+ const first=nodes[0],last=nodes[nodes.length-1];+ if(e.shiftKey&&document.activeElement===first){e.preventDefault();last?.focus()}+ else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first?.focus()}+},true);})();-// v10:手机端把密钥引导卡放到第 1 步之前-(()=>{const mq=matchMedia('(max-width:760px)'),o=document.getElementById('wbOnb');if(!o)return;const place=()=>{if(mq.matches){const s1=document.querySelector('.st-l [data-s="1"]');s1&&s1.parentNode.insertBefore(o,s1)}else document.querySelector('.st-c').prepend(o)};place();mq.addEventListener('change',place)})();diff --git a/src/style.css b/src/style.cssindex f7d0e67..acd93aa 100644--- a/src/style.css+++ b/src/style.css@@ -28,13 +28,13 @@ body.scrolled .top{box-shadow:0 1px 0 var(--line)}.brand{display:flex;align-items:center;gap:10px;text-decoration:none;flex:none}.mark{width:34px;height:34px;display:grid;place-items:center;background:var(--ac);color:#fff;font:700 17px/1 var(--sans);border-radius:10px}.wm b{font-size:18px;font-weight:700;letter-spacing:.02em}-.tabs,.frow{overflow-x:auto;scrollbar-width:none}-.tabs::-webkit-scrollbar,.frow::-webkit-scrollbar{display:none}+.frow{overflow-x:auto;scrollbar-width:none}+.frow::-webkit-scrollbar{display:none}.tabs{position:relative;display:flex;gap:2px;flex:0 0 100%;min-width:0;padding:3px 4px}.tabs button{background:transparent;padding:10px 16px;font-size:15px;font-weight:600;color:var(--tx2);position:relative;flex:none}.tabs button:hover{color:var(--tx);background:var(--sf)}.tabs button.on{background:var(--tx);color:var(--bg)}.tabs button i{font-style:normal;font-weight:400;font-size:12px;opacity:.55;margin-left:4px}-.ind{display:none}+.top .search{position:relative;flex:1;max-width:40rem;min-width:0;margin-left:auto}.sic{position:absolute;left:18px;top:50%;width:18px;height:18px;transform:translateY(-50%);fill:none;stroke:var(--mu);stroke-width:2;stroke-linecap:round;pointer-events:none}#q{width:100%;font:inherit;font-size:15px;background:var(--sf);color:var(--tx);border:2px solid transparent;padding:11px 44px 11px 46px;border-radius:99px;outline:0;transition:border-color .2s,background .2s}@@ -42,9 +42,9 @@ body.scrolled .top{box-shadow:0 1px 0 var(--line)}.qx{position:absolute;right:8px;top:50%;transform:translateY(-50%);width:30px;height:30px;padding:0;background:var(--sf2);color:var(--tx2);font-size:12px}.tools{display:flex;align-items:center;gap:4px;flex:none}#theme .moon{display:none}[data-theme=dark] #theme .sun{display:none}[data-theme=dark] #theme .moon{display:block}-.hero{display:none}+body.studio .bar,body.studio .filters,body.studio #grid,body.studio #empty,body.studio #sentinel,body.studio .top .search{display:none!important}-body.histview .bar,body.histview .filters,body.histview #grid,body.histview #empty,body.histview #sentinel,body.histview .top .search,body.histview .hero,body.histview .intro,body.histview .annbar,body.histview #toTop{display:none!important}+body.histview .bar,body.histview .filters,body.histview #grid,body.histview #empty,body.histview #sentinel,body.histview .top .search,body.histview #toTop{display:none!important}/* toolbar + filters */.bar{position:sticky;top:calc(var(--hdr,72px) - 1px);z-index:20;max-width:var(--w);margin:0 auto;padding:6px 24px 10px;display:flex;align-items:center;gap:12px;background:var(--bg)}.tbar{display:flex;align-items:center;gap:8px;flex:1;min-width:0}@@ -85,11 +85,11 @@ body.histview .bar,body.histview .filters,body.histview #grid,body.histview #emp.try:hover{background:var(--ac2)}.card:hover .try,.try:focus-visible{opacity:1;transform:none}.ph.pose .try{bottom:42px}.angs{position:absolute;left:0;right:0;bottom:0;display:flex;justify-content:center;gap:2px;padding:8px}-.angs span{font-size:11.5px;padding:3px 9px;color:#888;cursor:pointer;border-radius:99px;background:rgba(255,255,255,.7)}.angs span:hover{color:#111}.angs span.on{color:#fff;background:#111}+.angs :is(span,button){font-size:11.5px;padding:3px 9px;color:#4b4b4b;cursor:pointer;border-radius:99px;background:rgba(255,255,255,.92)}.angs :is(span,button):hover{color:#111}.angs :is(span,button).on{color:#fff;background:#111}.info{padding:10px 4px 0;min-width:0}.info h3{font-size:14.5px;font-weight:600;line-height:1.4;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.info .sub{font-size:12.5px;color:var(--mu);margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}-.tags,.copy{display:none}+.tags{display:none}.card.sel .ph{box-shadow:0 0 0 3px var(--ac)}.skel{aspect-ratio:3/4.4;border-radius:16px;background:linear-gradient(100deg,var(--sf) 30%,var(--bg) 50%,var(--sf) 70%);background-size:250% 100%;animation:sh 1.5s infinite linear}/* empty */@@ -103,10 +103,9 @@ body.histview .bar,body.histview .filters,body.histview #grid,body.histview #emp.tray-b{padding:0 20px 18px}.tray-items{display:flex;gap:8px;overflow-x:auto;padding:6px 6px 4px 0}.tray-items div{position:relative;flex:none}.tray-items img{width:52px;height:68px;object-fit:cover;border-radius:10px;background:var(--ph);display:block}.tray-items em{position:absolute;left:0;right:0;bottom:0;font-size:10px;font-style:normal;text-align:center;background:rgba(0,0,0,.5);color:#fff;border-radius:0 0 10px 10px}-.tray-items b{position:absolute;right:-5px;top:-5px;width:18px;height:18px;border-radius:50%;background:var(--tx);color:var(--bg);font-size:12px;display:grid;place-items:center;cursor:pointer}+.tray-items [data-k]{position:absolute;right:-5px;top:-5px;width:18px;height:18px;border-radius:50%;background:var(--tx);color:var(--bg);font-size:12px;display:grid;place-items:center;cursor:pointer}#trayText{white-space:pre-wrap;font:13px/1.7 var(--sans);color:var(--tx2);max-height:130px;overflow:auto;margin:12px 0;padding:12px 14px;background:var(--sf);border-radius:12px}.tray-act{display:flex;gap:8px}.tray-act .pri{flex:1}-body.tray .foot{padding-bottom:300px}/* lightbox */#lb{position:fixed;inset:0;z-index:60}.lb-bg{position:absolute;inset:0;background:rgba(0,0,0,.55);animation:fade .25s both}@keyframes fade{from{opacity:0}}@@ -120,6 +119,10 @@ body.tray .foot{padding-bottom:300px}.lb-side h2{font-size:24px;line-height:1.35;margin:6px 0 4px;font-weight:700}.mu{font-size:12.5px;color:var(--mu)}.jp{font-size:12px;color:var(--mu);margin-top:8px}.angsel{display:flex;flex-wrap:wrap;gap:6px;margin:18px 0 4px}+#lbPair:not(:empty){margin-top:16px}+#lbPair:not(:empty)+.angsel{margin-top:10px}+#lbPair button{min-height:32px}+@media(pointer:coarse){#lbPair button{min-height:44px}}.pbox{margin-top:16px;padding:14px 16px;background:var(--sf);border-radius:14px}.pbox small{display:block;font-size:12px;font-weight:600;color:var(--tx2);margin-bottom:6px}.pbox p{margin:0 0 12px;font-size:13.5px;line-height:1.8;color:var(--tx)}.pbox.en p{font:12.5px/1.7 ui-monospace,Menlo,monospace;color:var(--tx2)}.pbox button{background:var(--bg2)}.pbox button.pri{background:var(--tx);color:var(--bg)}@@ -202,8 +205,11 @@ textarea{width:100%;font:13.5px/1.7 var(--sans);color:var(--tx);background:var(-.cfg-box{width:min(580px,100%);max-height:94vh}.pk-h{display:flex;align-items:center;gap:14px;padding:16px 16px 16px 24px}.pk-h b{font-size:18px;font-weight:700;flex:none}#pkQ{flex:1;font:inherit;background:var(--sf);color:var(--tx);border:0;border-radius:99px;padding:9px 16px;outline:0}+#pkPoseTypes{align-self:flex-start;flex:none;margin:0 24px 10px}+#pkPoseTypes button{min-height:30px;padding-inline:14px}+.pk-g button.depth img{object-fit:contain}.pk-g{overflow:auto;padding:6px 24px 24px;display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:18px 12px}.pk-g .skel{aspect-ratio:3/4}-.pk-g button{flex-direction:column;align-items:stretch;padding:0;background:transparent;gap:6px;text-align:left;border-radius:0}.pk-g img{aspect-ratio:3/4;object-fit:cover;background:var(--ph);width:100%;border-radius:12px;transition:box-shadow .15s}.pk-g button.pose img{object-fit:contain;background:var(--phw);mix-blend-mode:multiply}+.pk-g button{flex-direction:column;align-items:stretch;padding:0;background:transparent;gap:6px;text-align:left;border-radius:0}.pk-g img{aspect-ratio:3/4;object-fit:cover;background:var(--ph);width:100%;border-radius:12px;transition:box-shadow .15s}.pk-g button.pose img{object-fit:contain;background:var(--phw)}.pk-g button:hover img{box-shadow:0 0 0 2px var(--line2)}.pk-g button.on img{box-shadow:0 0 0 3px var(--ac)}.pk-g span{font-size:12px;font-weight:400;color:var(--tx2);overflow:hidden;text-overflow:ellipsis}.pk-g button.on span{color:var(--ac);font-weight:600}.cfg-b{padding:4px 24px 20px;overflow:auto;display:flex;flex-direction:column;gap:14px}.prov{display:grid;grid-template-columns:repeat(4,1fr);gap:8px}.prov label{cursor:pointer}.prov input{position:absolute;opacity:0}@@ -219,7 +225,7 @@ textarea{width:100%;font:13.5px/1.7 var(--sans);color:var(--tx);background:var(-@media(min-width:1500px){.grid{grid-template-columns:repeat(6,minmax(0,1fr))}}@media(max-width:1180px){.tabs button{padding:9px 12px;font-size:14px}.tabs button i{display:none}.st-grid{grid-template-columns:1fr}.st-out{position:static}.lb-side{width:360px}.next{right:386px}}@media(max-width:860px){- .top{padding:10px 12px 8px;gap:8px 10px}.wm{display:none}#help{display:none}+ .top{padding:10px 12px 8px;gap:8px 10px}.wm{display:none}.top .search{max-width:none}.tools .seg{display:none}.tabs button{padding:7px 13px;font-size:14px}#q{padding:9px 38px 9px 40px;font-size:14px}.sic{left:14px;width:16px;height:16px}@@ -227,8 +233,8 @@ textarea{width:100%;font:13.5px/1.7 var(--sans);color:var(--tx);background:var(-.filters{padding:0 12px 10px}.chip{font-size:13px;padding:7px 13px}.frow label{display:none}.grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:16px 8px;padding:4px 8px 30px}.ph{border-radius:12px}.info{padding:7px 4px 0}.info h3{font-size:13.5px}.info .sub{font-size:11.5px}- .cbtns{opacity:1;transform:none;right:6px;top:6px;gap:6px}.cbtns button{width:28px;height:28px;font-size:13px}.cbtns button[data-a=sel]{display:none}.card.sel .cbtns button[data-a=sel]{display:inline-flex}- .try{display:none}.angs{padding:6px 4px}.angs span{padding:2px 6px;font-size:10.5px}.badge{left:6px;top:6px;font-size:10.5px}+ .cbtns{opacity:1;transform:none;right:6px;top:6px;gap:6px}.cbtns button{width:28px;height:28px;font-size:13px}.cbtns button[data-a=sel]{display:inline-flex}+ .try{display:none}.angs{padding:6px 4px}.angs :is(span,button){padding:2px 6px;font-size:10.5px}.badge{left:6px;top:6px;font-size:10.5px}#tray{left:8px;right:8px;bottom:8px;width:auto}.tray-act button{font-size:12.5px;padding:8px 10px}.tray-h small{display:none}.lb-box{inset:0;flex-direction:column;border-radius:0;overflow:auto}.lb-img{flex:none;height:56vh;margin:0;border-radius:0}.lb-img img{max-height:56vh}.lb-side{width:auto;padding:20px 18px 30px;overflow:visible}.lb-side h2{font-size:20px}.lb-nav{top:28vh;width:36px;height:36px}.next{right:12px}.prev{left:12px}#toast{bottom:calc(24px + env(safe-area-inset-bottom))}body.tray:not(.studio) #toast{top:auto;bottom:96px}@@ -275,7 +281,6 @@ body.studio .top{background:#fafafa}[data-theme=dark] body.studio .top{backgroun/* sticky generate bar */.gobar{position:sticky;bottom:12px;z-index:5;background:color-mix(in srgb,var(--bg2) 92%,transparent);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border-radius:20px;padding:12px;box-shadow:0 8px 30px rgba(0,0,0,.1),0 0 0 1px rgba(0,0,0,.04)}.gb-i{display:flex;align-items:center;gap:10px;padding:0 4px 10px}.gb-i>span{flex:1;min-width:0;display:flex;flex-direction:column}.gb-i b{font-size:14px}-#wbHint{font-size:12px;color:var(--mu);margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}#wbHint.miss{color:#d9822b}.cfgchip{font-size:12px;padding:6px 12px;gap:7px;background:var(--sf)}.gobar .big{margin:0;border-radius:14px;padding:15px}/* output */@@ -382,7 +387,7 @@ button:active:not(:disabled){transform:scale(.96)}body.batch .card .ph{cursor:copy}body.batch .card .ph::after{content:"";position:absolute;top:10px;left:10px;width:22px;height:22px;border-radius:50%;border:2px solid #fff;background:rgba(0,0,0,.18);box-shadow:0 1px 4px rgba(0,0,0,.2);transition:transform .25s cubic-bezier(.16,1,.3,1),background .2s;z-index:3}body.batch .card.picked .ph::after{background:var(--ac) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='3.4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 12 4 4 8-8'/%3E%3C/svg%3E") center/14px no-repeat;border-color:var(--ac);transform:scale(1.1)}body.batch .card .ph img{transition:transform .3s cubic-bezier(.16,1,.3,1)}body.batch .card.picked .ph img{transform:scale(.94)}body.batch .card.picked .ph{box-shadow:0 0 0 3px var(--ac)}-body.batch .cbtns,body.batch .try,body.batch #tray{display:none!important}+body.batch .cbtns,body.batch .try{display:none!important}#bbar{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);z-index:60;display:flex;gap:6px;align-items:center;background:#111;color:#fff;padding:8px 8px 8px 18px;border-radius:999px;box-shadow:0 12px 40px rgba(0,0,0,.25);animation:bup .45s cubic-bezier(.16,1,.3,1)}#bbar b{font-size:13.5px;margin-right:8px;font-variant-numeric:tabular-nums;white-space:nowrap}#bbar button{background:rgba(255,255,255,.1);color:#fff;border:0;border-radius:999px;padding:8px 14px;font-size:13px;white-space:nowrap}#bbar button:hover:not(:disabled){background:rgba(255,255,255,.2)}#bbar button:disabled{opacity:.4}#bbar button.pri{background:var(--ac)}@keyframes bup{from{opacity:0;transform:translate(-50%,24px)}}@@ -390,11 +395,10 @@ body.batch .cbtns,body.batch .try,body.batch #tray{display:none!important}/* search suggest */.search{position:relative}#qsug{position:absolute;left:0;right:0;top:calc(100% + 8px);background:var(--bg2,#fff);border-radius:16px;box-shadow:0 16px 48px rgba(0,0,0,.14),0 0 0 1px rgba(0,0,0,.04);padding:12px 14px 14px;z-index:80;animation:sgin .28s cubic-bezier(.16,1,.3,1);transform-origin:top}@keyframes sgin{from{opacity:0;transform:translateY(-6px) scale(.98)}}-.sgh{display:flex;justify-content:space-between;align-items:center;margin:2px 0 8px}.sgh small{color:#999;font-size:12px}.sgh button{border:0;background:none;color:#999;font-size:12px;padding:0}.sgc{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:8px}.sgc button{border:0;background:#f5f5f5;border-radius:999px;padding:6px 12px;font-size:13px;color:#333}.sgc button:hover{background:#ffeef0;color:var(--ac)}.sgc em{font-style:normal;color:var(--ac);font-weight:700;margin-right:5px;font-size:12px}+.sgh{display:flex;justify-content:space-between;align-items:center;margin:2px 0 8px}.sgh small{color:var(--mu);font-size:12px}.sgh button{border:0;background:none;color:var(--mu);font-size:12px;padding:0}.sgc{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:8px}.sgc button{border:0;background:var(--sf);border-radius:999px;padding:6px 12px;font-size:13px;color:var(--tx2)}.sgc button:hover{background:var(--sf2);color:var(--tx)}.sgc em{font-style:normal;color:var(--ac);font-weight:700;margin-right:5px;font-size:12px}/* lightbox similar */-.simh{display:block;color:#999;font-size:12px;margin:22px 0 8px}.sim{display:grid;grid-template-columns:repeat(4,1fr);gap:8px}.sim button{padding:0;border:0;border-radius:10px;overflow:hidden;aspect-ratio:3/4;background:#f3f3f3}.sim img{width:100%;height:100%;object-fit:cover;transition:transform .4s cubic-bezier(.16,1,.3,1)}.sim button:hover img{transform:scale(1.06)}+.simh{display:block;color:var(--mu);font-size:12px;margin:22px 0 8px}.sim{display:grid;grid-template-columns:repeat(4,1fr);gap:8px}.sim button{padding:0;border:0;border-radius:10px;overflow:hidden;aspect-ratio:3/4;background:#f3f3f3}.sim img{width:100%;height:100%;object-fit:cover;transition:transform .4s cubic-bezier(.16,1,.3,1)}.sim button:hover img{transform:scale(1.06)}.cta{display:flex;gap:10px;justify-content:center;margin-top:18px}-#upd{position:fixed;left:50%;top:76px;transform:translateX(-50%);z-index:90;background:#111;color:#fff;border:0;border-radius:999px;padding:10px 18px;font-size:13px;box-shadow:0 10px 30px rgba(0,0,0,.2);animation:sgin .4s cubic-bezier(.16,1,.3,1)}#upd b{color:var(--ac)}/* toast spring */#toast.on{animation:tspr .5s cubic-bezier(.34,1.56,.64,1)}@keyframes tspr{from{opacity:0;transform:translate(-50%,14px) scale(.96)}}/* studio */@@ -411,12 +415,12 @@ body.batch .card .badge,body.batch .card .angs{display:none}.ill .c3{background:#fff;color:#999;font-size:13px;box-shadow:none;border:1.5px dashed #d6d6d6}#wbGo::after{display:none!important;animation:none!important}@media(max-width:760px){.tbar{flex-wrap:wrap;row-gap:8px}.tbar .sp{flex-basis:100%;height:0}}-@media(max-width:760px){.angs{flex-wrap:nowrap;overflow:hidden}.angs span{white-space:nowrap;flex:none;padding:3px 7px;font-size:11px}#batchBtn{width:38px;height:34px;justify-content:center;background:var(--sf,#f5f5f5)}#batchBtn svg{width:18px;height:18px}}+@media(max-width:760px){.angs{flex-wrap:nowrap;overflow:hidden}.angs :is(span,button){white-space:nowrap;flex:none;padding:3px 7px;font-size:11px}#batchBtn{width:38px;height:34px;justify-content:center;background:var(--sf,#f5f5f5)}#batchBtn svg{width:18px;height:18px}}/* ===== v10 ===== */:root{--mu:#6e6e6e}[data-theme=dark]{--mu:#9a9a9a}#rand{background:#d81b3a}#rand:hover{background:#c0142f}.chip i{opacity:.75!important;color:inherit!important}-.phk{position:absolute;inset:0;width:100%;height:100%;background:none;border:0;padding:0;margin:0;cursor:zoom-in;border-radius:inherit;z-index:0}+.ph .phk{position:absolute;inset:0;width:100%;height:100%;background:none;border:0;padding:0;margin:0;cursor:zoom-in;border-radius:inherit;z-index:0}.phk:focus-visible{outline:2px solid var(--ac);outline-offset:-3px}.ph .badge,.ph .angs,.ph .cbtns,.ph .try{z-index:1}.grid{min-height:calc(100vh - 120px)}@@ -439,13 +443,7 @@ body.none0 #favTools,body.none0 #fBtn,body.none0 #sort,body.none0 #batchBtn,body.badge.rk{background:#111;color:#fff}.badge.age{left:58px;background:var(--ac);color:#fff}.sub.dim{margin-top:1px}-.dnote{max-width:var(--w);margin:0 auto;padding:0 24px 10px}-.dnote-in{padding:14px 18px;border-radius:16px;background:var(--acs);border:1px solid rgba(255,36,66,.22)}-.dnote p{margin:0;font-size:15px;line-height:1.65;color:var(--tx)}-.dnote .dsub{margin-top:4px;font-size:13px;color:var(--tx2)}-.dnote a{color:var(--ac);font-weight:650}-.dtag{display:inline-block;margin-right:8px;padding:2px 8px;border-radius:99px;background:var(--ac);color:#fff;font-size:12px;font-weight:700;letter-spacing:.02em}-body.depth .intro{display:none}+.ph.depth{background:#141414}.ph.depth img{object-fit:contain;mix-blend-mode:normal;padding:0;background:#141414}.ph .miss{display:none}@@ -455,16 +453,47 @@ body.depth .intro{display:none}.ph.depth.err img{position:absolute;width:1px;height:1px;opacity:0;pointer-events:none}.ph.depth.err .phk{display:none}.ph.depth.err .miss{display:grid;place-items:center;position:absolute;inset:0;z-index:3;padding:18px;background:var(--ph);color:var(--ac);font-size:15px;font-weight:700;line-height:1.6;text-align:center;text-decoration:none}+.card-badges{position:absolute;z-index:4;top:8px;left:8px;display:flex;align-items:center;gap:4px;pointer-events:none}+.card-badges .badge{position:static}+.card-badges .card-flip{pointer-events:auto;gap:5px;min-height:28px;padding:2px 8px;color:#48484c;background:rgba(255,255,255,.94);font-variant-numeric:tabular-nums}+.card-flip svg{width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}+.ph.depth .card-flip{background:rgba(43,43,47,.95);color:#f2f2f3}+.card-flip:is(:hover,:focus-visible){background-color:#fff;color:#b61538}+.ph.depth .card-flip:is(:hover,:focus-visible){background-color:#37373c;color:#ff9bac}+.card-flip[aria-busy=true]{cursor:progress}+.card-flip[aria-busy=true] svg{opacity:.55}+.ph:has(.card-badges) .unrec{top:47px}+body.batch .card-badges{display:none}+@media(pointer:coarse){+ .card-badges{top:0;left:6px}+ .card-flip.badge{min-height:44px;border-block:8px solid transparent}+ .card-badges .card-flip,.ph.depth .card-flip{background-clip:padding-box}+}+@media(max-width:480px){+ .card-badges{flex-direction:column;align-items:flex-start;gap:0}+ .ph:has(.card-badges .age) .unrec{top:69px}+}+.ph .flip-previous{display:none}+@media(prefers-reduced-motion:no-preference){+ .ph.pair-turn{--turn-from:-180deg;--turn-to:180deg;--sketch-brightness:.957}+ [data-theme=dark] .ph.pair-turn{--sketch-brightness:.925}+ .ph.pair-turn.pose{--turn-from:180deg;--turn-to:-180deg}+ .ph.pair-turn>img{backface-visibility:hidden;transition:none}+ .ph.pair-turn>img:first-child{animation:pose-face-in .38s ease-in-out both}+ .ph.pair-turn.pose>img:first-child,.ph.pair-turn.depth>.flip-previous{background:#fff;mix-blend-mode:normal;filter:brightness(var(--sketch-brightness))}+ .ph.pair-turn>.flip-previous{display:block;position:absolute;inset:0;width:100%;height:100%;pointer-events:none;object-fit:contain;animation:pose-face-out .38s ease-in-out both}+ .ph.pair-turn.depth>.flip-previous{padding:5% 4% 13%}+ .ph.pair-turn.pose>.flip-previous{padding:0;background:#141414;mix-blend-mode:normal}+ @keyframes pose-face-in{from{transform:perspective(850px) rotateY(var(--turn-from))}to{transform:perspective(850px) rotateY(0deg)}}+ @keyframes pose-face-out{from{transform:perspective(850px) rotateY(0deg)}to{transform:perspective(850px) rotateY(var(--turn-to))}}+}.lb-miss{display:none;position:absolute;inset:0;z-index:2;place-items:center;background:var(--sf);color:var(--ac);font-size:18px;font-weight:700;text-decoration:none}.lb-img.fail .lb-miss{display:grid}.lb-img.fail img,.lb-img.fail .spin{opacity:0}[data-theme=light] .lb-img.ext img,:root:not([data-theme=dark]) .lb-img.ext img,.lb-img.ext img{mix-blend-mode:normal}-.creditln{margin:14px 0 0;font-size:13px;line-height:1.7;color:var(--tx2)}-.creditln b{display:inline-block;margin-right:6px;padding:1px 7px;border-radius:99px;background:var(--ac);color:#fff;font-size:12px}-.goext{display:inline-flex;margin-top:10px;padding:8px 16px;border-radius:99px;background:var(--tx);color:var(--bg);font-weight:650;text-decoration:none}-@media(max-width:860px){.dnote{padding:0 12px 8px}.badge.age{left:46px}.dnote p{font-size:13.5px}}-.pnote{max-width:var(--w);margin:0 auto 10px;padding:0 24px;font-size:13px;color:var(--tx2)}.pnote summary{cursor:pointer;color:var(--tx);font-weight:500}.pnote ul{margin:8px 0 0;padding-left:18px;line-height:1.8}-@media(max-width:760px){.pnote{padding:0 12px}}+.creditln{margin:14px 0 0;font-size:12px;line-height:1.7;color:var(--tx2)}+.creditln a{color:inherit;text-decoration:underline;text-underline-offset:2px}+@media(max-width:860px){.badge.age{left:46px}}/* v11: 18+ switch */.asw{display:inline-flex;align-items:center;gap:7px;height:34px;padding:0 10px 0 6px;margin-right:6px;border-radius:99px;background:transparent;color:var(--tx2);font-size:12.5px;font-weight:600;border:1px solid var(--line2,#e5e5e5);transition:color .2s,border-color .2s,background .2s}.asw:hover{color:var(--tx);border-color:var(--mu)}@@ -493,20 +522,20 @@ button:active:not(:disabled){transform:scale(.97)}.tabs button:active,.chip:acti@media(prefers-reduced-motion:reduce){.asw .kn,.asw .trk{transition:none}}@media(max-width:760px){.tabs button i#nFav,.tabs button i#nRec{display:inline;margin-left:3px;font-size:11px;opacity:.7}}/* v12 */-.intro{max-width:var(--w);margin:2px auto 4px;padding:0 24px;display:flex;align-items:center;gap:10px;box-sizing:border-box}-.intro p{flex:1;margin:0;display:flex;align-items:baseline;gap:10px;flex-wrap:wrap;font-size:13.5px;color:var(--tx2);line-height:1.6;min-width:0}.intro p b{font-size:15px;color:var(--tx);font-weight:600}-.intro .ix{width:32px;height:32px;padding:0;border-radius:50%;background:transparent;color:var(--mu);font-size:12px}.intro .ix:hover{background:var(--line);color:var(--tx)}-.nointro .intro,body.studio .intro,body.compact .intro{display:none}-.annbar{max-width:var(--w);margin:8px auto 4px;padding:10px 14px;display:flex;align-items:center;gap:10px;box-sizing:border-box;background:var(--acs);border:1px solid var(--line2);border-radius:12px}-.annbar p{flex:1;margin:0;display:flex;align-items:baseline;gap:10px;flex-wrap:wrap;font-size:13.5px;color:var(--tx2);line-height:1.6;min-width:0}.annbar p b{font-size:14.5px;color:var(--tx);font-weight:600;white-space:nowrap}-.annbar .ix{width:32px;height:32px;padding:0;border-radius:50%;background:transparent;color:var(--mu);font-size:12px;flex:none}.annbar .ix:hover{background:var(--line);color:var(--tx)}-.annbar .sm{flex:none}-.noann .annbar,body.studio .annbar,body.depth .annbar,body.compact .annbar{display:none}+++++++++::view-transition-old(root),::view-transition-new(root){animation-duration:.16s!important;animation-timing-function:cubic-bezier(.2,.7,.2,1)}.grid{transition:opacity .16s}#toast{bottom:calc(32px + env(safe-area-inset-bottom))}#tray{bottom:calc(24px + env(safe-area-inset-bottom))}@media(max-width:760px){- .intro{padding:0 12px;margin:0 auto 2px}.intro p{font-size:12.5px;gap:2px 8px}.intro p span{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.intro p b{font-size:14px}.intro .ix{width:44px;height:44px;margin-right:-8px}.intro .sm{min-height:36px;flex:none}+.tabs button{min-height:44px}.cbtns button{position:relative;width:34px;height:34px}.cbtns button::after{content:'';position:absolute;inset:-5px}.unrec{width:34px;height:34px}.unrec::after{content:'';position:absolute;inset:-5px}@@ -516,7 +545,7 @@ button:active:not(:disabled){transform:scale(.97)}.tabs button:active,.chip:acti}.mact{display:none}@media(max-width:760px){- .intro .sm{display:none}+.mact{display:flex;position:sticky;bottom:0;z-index:3;gap:8px;margin:12px -18px 0;padding:10px 18px calc(10px + env(safe-area-inset-bottom));background:var(--bg2);border-top:1px solid var(--line)}.mact button{min-height:44px;border-radius:99px;padding:0 16px}.mact button:first-child{width:44px;padding:0;font-size:18px;flex:none}.mact button.on{color:var(--ac)}.mact .pri{flex:1}.lb-side .acts button{min-height:40px}@@ -614,7 +643,7 @@ button:active:not(:disabled){transform:scale(.97)}.tabs button:active,.chip:acti#tgView figure{position:relative;margin:0;max-width:min(92vw,560px);text-align:center}#tgView img{max-width:100%;max-height:78vh;border-radius:16px;box-shadow:var(--sh3);background:var(--ph)}#tgView figcaption{display:flex;gap:8px;justify-content:center;margin-top:12px}-@media(max-width:760px){.annbar p span{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}}+@media(min-width:761px){.frow{-webkit-mask-image:linear-gradient(90deg,#000 93%,transparent 99%);mask-image:linear-gradient(90deg,#000 93%,transparent 99%)}}/* v1.2.1:悬浮工作台常驻入口 + 面板内添加素材 */@@ -628,3 +657,608 @@ button:active:not(:disabled){transform:scale(.97)}.tabs button:active,.chip:acti.tg-add button{font:12.5px var(--sans);color:var(--tx);background:var(--sf);border:1px solid var(--bd);border-radius:999px;padding:6px 11px;cursor:pointer}.tg-add button:hover{border-color:var(--ac);color:var(--ac)}.tg-empty{font-size:13px;line-height:1.7;color:var(--tx2);background:var(--sf);border-radius:12px;padding:12px 14px;margin:0 0 12px}++/* Gallery navigation and language preferences */+.lang-menu{position:relative}+.lang-menu>summary{display:grid;place-items:center;cursor:pointer;list-style:none}+.lang-menu>summary::-webkit-details-marker{display:none}+.lang-menu[open]>summary,.lang-menu>summary:hover{background:var(--sf)}+.lang-panel{position:absolute;z-index:45;right:0;top:calc(100% + 6px);width:218px;max-width:calc(100vw - 24px);padding:16px;display:grid;gap:8px;border:1px solid var(--line);border-radius:14px;background:var(--bg2);box-shadow:var(--sh3)}+.lang-panel label,.lang-panel>span{font-size:12px;font-weight:650;color:var(--tx2)}+.lang-panel>span{margin-top:6px}+.lang-panel select{width:100%}+.tools .lang-panel .seg{display:flex}+.lang-panel button{flex:1;min-height:34px}+[data-lang].on{font-weight:700}+.acts [data-x=try],.mact .pri,#wbGo:not(:disabled),#tgGo,#cfSave,#pkDone{background:#c71939;color:#fff}+.acts [data-x=try]:hover,.mact .pri:hover,#wbGo:hover:not(:disabled),#tgGo:hover,#cfSave:hover,#pkDone:hover{background:#a81430}+.angs button{min-width:0;min-height:0;font:inherit;border:0;line-height:1.5}+.angs button:focus-visible{outline-offset:-2px}+.tray-items [data-k]{padding:0;border:0}+#cfg .pk-h{justify-content:space-between}+#pkQ{min-width:0}+#pkDone,#pkX,#cfgX{flex:none}+:is(#q,#pkQ,#tgPrompt,.fld input,.fld select,.phk,summary):focus-visible{outline:2px solid var(--tx);outline-offset:2px}+.phk:focus-visible{outline-offset:-3px}+button:focus-visible,a:focus-visible,select:focus-visible{outline:2px solid var(--tx);outline-offset:2px}++@media(max-width:860px){+ .top:has(details[open]){z-index:42}+ .st-app{grid-template-columns:minmax(0,1fr)}+ .st-l,.st-r,.st-c,.sh{min-width:0}+ .sh{flex-wrap:wrap;row-gap:4px}+ .st-r{order:0}+ .st-c:has(#wbCmp:not([hidden])){order:-3}+ .st-c:has(#wbPh0:not([hidden])) .stage{min-height:160px}+ .st-c:has(#wbPh0:not([hidden])){min-height:0}+ .st-c .onb{margin-bottom:10px}+ #studio{padding-bottom:calc(155px + env(safe-area-inset-bottom))}+ .cfg-f{flex-wrap:wrap;padding:10px 14px calc(10px + env(safe-area-inset-bottom));gap:5px}+ .cfg-f button{white-space:normal;min-height:38px;padding:6px 10px}+ .cfg-f #cfSave{margin-left:auto}+ #cfg .cfg-b{min-height:0}+ #pk .pk-h{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:8px;padding:12px 14px}+ #pkT{font-size:15px;line-height:1.4}+ #pkDone{grid-row:1;grid-column:2;min-height:38px}+ #pkX{grid-row:1;grid-column:3;width:38px;height:38px}+ #pkQ{grid-row:2;grid-column:1/-1;width:100%;min-width:0;font-size:16px}+ #pkPoseTypes{margin:0 14px 8px}+ #pkPoseTypes button{min-height:36px}+ .cfg-box,.pk-box{width:100%;max-height:92dvh}++++ .pk-box .pk-g{min-width:0;grid-template-columns:repeat(3,minmax(0,1fr))}+ .pk-g button{min-width:0}+ #bbar{overflow-x:auto;max-width:100%}+}+@media(max-width:760px){+ .angs{justify-content:flex-start;overflow-x:auto;scrollbar-width:none;overscroll-behavior-x:contain}+ .angs::-webkit-scrollbar{display:none}+ .angs :is(span,button){flex:none;min-height:26px}+ .angs :is(span,button):first-child{margin-inline-start:auto}+ .angs :is(span,button):last-child{margin-inline-end:auto}+ #bbar{overflow-x:auto}+ .mdl .hb,#helpBox .hb{max-height:calc(100dvh - 32px);overflow:auto}+ #toast{white-space:normal;width:max-content}+ .mact button,.cfg-f button,.tgen-h button,.tgen-row button{white-space:normal}+ .hist-bar .tbar{flex-wrap:wrap}+}+@media(max-width:420px){+ .cfg-f{display:grid;grid-template-columns:repeat(6,minmax(0,1fr))}+ .cfg-f .sp{display:none}+ .cfg-f button{grid-column:span 2}+ .cfg-f #cfTest,.cfg-f #cfSave{grid-column:span 3}+ .cfg-f #cfSave{margin:0}+ .top .wm{display:none}+ .lang-panel{right:-40px}+ .tgen-row{flex-wrap:wrap}+}+@media(max-height:530px) and (orientation:landscape){+ .mdl .hb,#helpBox .hb{max-height:calc(100dvh - 24px);overflow:auto}+ .st-c .stage,.st-c:has(#wbPh0:not([hidden])) .stage{min-height:120px}+ #pk .pk-h{padding-block:6px}+}+.hist-card .hopen{position:absolute;inset:0;width:100%;height:100%;border:0;background:transparent;border-radius:inherit;padding:0}+.hist-card .hopen:focus-visible{outline-offset:-3px}+.hist-card .hmode{pointer-events:none}+html:lang(en) .ph.err::after{content:"Image unavailable · Retry"}+html:lang(ja) .ph.err::after{content:"画像を読み込めません · 再試行"}+html:lang(en) .st-r .hl:empty::before{content:"Generated images are saved here on this device."}+html:lang(ja) .st-r .hl:empty::before{content:"生成した画像はこの端末に保存されます。"}+@media(min-width:640px) and (max-width:1024px) and (max-height:530px) and (orientation:landscape){+ body.studio{overflow:auto}+ #studio{height:auto;padding:6px 12px calc(85px + env(safe-area-inset-bottom))}+ .st-app{height:auto;align-items:start;grid-template-columns:repeat(2,minmax(0,1fr))}+ .st-l{grid-column:1;grid-row:1 / span 2}+ .st-c{grid-column:2;grid-row:1;min-height:0}+ .st-r{grid-column:2;grid-row:2}+ .st-l,.st-r{overflow:visible}+ .st-r .gobar{position:fixed;inset:auto 12px 0 auto;z-index:30;width:calc(50% - 19px);display:flex;align-items:center;gap:12px;padding:7px 10px calc(7px + env(safe-area-inset-bottom));border-radius:14px 14px 0 0}+ .st-r .gobar .gb-i{flex:1;min-width:0;margin:0}+ .st-r .gobar .big{flex:0 1 auto;width:auto;min-width:82px;padding:10px}+ .cfgchip{display:inline-flex}+ .st-r .cfg{display:none}+}++#cfLocalSetup summary{width:fit-content;cursor:pointer}+#cfLocalSetup p{margin:6px 0 0}#cfLocalSetup a{color:var(--tx);text-underline-offset:3px}+#cfg.local-engine .cfg-b :is(.fld:not(#cfCheckpointW),.tg,.note),+#cfg.local-engine .cfg-b .grp:not(:first-child),+#cfg.local-engine #cfClr{display:none}++/* Header disclosures share one row; only the current collection is named there. */+.top{display:grid;grid-template-columns:auto auto minmax(9rem,1fr) auto;grid-template-areas:"brand nav search tools";align-items:center;column-gap:clamp(12px,2.4vw,40px);padding-block:12px}+.top .brand{grid-area:brand}+.top .search{grid-area:search;width:100%;max-width:32rem}+.top .tools{grid-area:tools;justify-self:end}+.tabs{grid-area:nav;align-items:center;gap:4px;overflow:visible;padding:0;min-width:0}+.shell-menu{position:relative}+.shell-menu summary{cursor:pointer;list-style:none}+.shell-menu summary::-webkit-details-marker,.foot summary::-webkit-details-marker{display:none}+.tabs .nav-trigger{display:inline-flex;align-items:center;justify-content:center;gap:6px;padding:7px 12px;border-radius:99px;min-height:38px;background:transparent;color:var(--tx2);font-size:14px;font-weight:600;white-space:nowrap;transition:background-color .18s,color .18s}+.tabs .nav-trigger>svg{width:17px;height:17px;flex:none}+.tabs summary.nav-trigger>svg:last-child{width:13px;height:13px;transition:transform .18s}+.tabs details[open]>summary.nav-trigger>svg:last-child{transform:rotate(180deg)}+.tabs .current>.nav-trigger,.tabs .nav-trigger.on{background:var(--tx);color:var(--bg)}+.tabs .nav-trigger:hover,.shell-menu[open]>.icon{background:var(--sf);color:var(--tx)}+.tabs .current>.nav-trigger:hover,.tabs .nav-trigger.on:hover{background:var(--tx);color:var(--bg)}+.shell-menu>.icon{display:grid;place-items:center}+.shell-pop{position:absolute;z-index:48;top:calc(100% + 8px);left:0;border:1px solid var(--line);border-radius:18px;background:var(--bg2);color:var(--tx);box-shadow:var(--sh3);max-height:calc(100dvh - var(--hdr,72px) - 16px);overflow-y:auto;overscroll-behavior:contain}+@media(prefers-reduced-motion:no-preference){+ .shell-menu[open]>.shell-pop{animation:shellReveal .18s var(--out)}+ @keyframes shellReveal{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}+}+.library-menu{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px 18px;width:25rem;padding:18px}+.library-menu h2,.notice-pop h2{font:600 12px/1.4 var(--sans);color:var(--tx2);margin:0 8px 5px}+.library-menu button,.personal-menu button{display:flex;align-items:center;justify-content:space-between;gap:10px;min-height:38px;width:100%;border-radius:9px;padding:7px 9px;text-align:left;font-size:14px;font-weight:500;color:var(--tx)}+.tabs .shell-pop button i{display:inline-block;color:var(--mu);font-size:11px;font-style:normal;font-variant-numeric:tabular-nums;opacity:1}+.tabs .shell-pop button.on{background:var(--acs);color:var(--tx)}+.nav-count{width:32px;text-align:right;line-height:1.1}+.nav-count b{font-weight:500}+.nav-count::after{content:"";display:block;width:100%;height:2px;margin-top:4px;border-radius:2px;background:currentColor;opacity:.5;transform:scaleX(var(--share,0));transform-origin:right}+.tabs .shell-pop button.on .nav-count{color:var(--ac)}+.personal-menu{width:12rem;padding:6px}+.theme-pop{right:0;left:auto;width:max-content;min-width:10rem;padding:5px;border-radius:16px}+.theme-pop button{display:flex;align-items:center;justify-content:flex-start;background:transparent;gap:9px;width:100%;min-height:38px;padding:7px 10px;border-radius:10px;color:var(--tx2);font:500 13px/1.4 var(--sans);text-align:start}+.theme-pop button svg{width:17px;height:17px;fill:none;stroke:currentColor;stroke-width:1.65;stroke-linecap:round;stroke-linejoin:round}+.theme-pop button[aria-pressed=true]{background:var(--sf);color:var(--tx)}+.theme-pop button[aria-pressed=true]::after{content:"";width:5px;height:9px;margin-inline-start:auto;border:solid var(--tx);border-width:0 1.6px 1.6px 0;transform:rotate(45deg)}+@media(hover:hover){.theme-pop button:hover{background:var(--sf);color:var(--tx)}}+@media(pointer:coarse){.theme-pop button{min-height:44px}}+@media(prefers-reduced-motion:no-preference){+ #themeMenu:focus-within #theme svg{animation:themeIconIn .22s var(--out)}+ @keyframes themeIconIn{from{opacity:.5;transform:rotate(-16deg) scale(.84)}}+}+.notice-pop{right:0;left:auto;min-width:234px;width:17rem;padding:16px}+.notice-pop h2{font-size:15px;color:var(--tx);margin:0 0 12px}+.notice-pop p{margin:4px 0;font-size:13px;line-height:1.55;color:var(--tx2)}+.notice-pop strong{font-size:12px;font-weight:600}+#noticeAction:not([hidden]),#noticeReload:not([hidden]){margin-bottom:12px}+#noticeMenu:has(#noticeReload:not([hidden]))>summary::after{content:"";position:absolute;top:7px;right:7px;width:6px;height:6px;border-radius:50%;background:var(--ac)}+#help.notice-help{display:block;background:transparent;padding:8px 0 0;margin-top:10px;border-top:1px solid var(--line);width:100%;border-radius:0;text-align:left;font-size:12px;color:var(--tx2)}+.foot{padding:18px max(24px,calc((100vw - var(--w))/2 + 24px)) 32px;border-top:1px solid var(--line);background:var(--bg)}+.foot-line{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap}+.foot-line small,.foot-line a,.foot summary{font-size:12px;font-weight:400;color:var(--tx2)}+.foot-line small{margin-right:auto}+.foot details{margin-top:6px}+.foot summary{width:fit-content;list-style:none;cursor:pointer}+.foot summary::after{content:"⌄";display:inline-block;margin-inline-start:5px}+.foot details[open]>summary::after{transform:rotate(180deg)}+.credit-list{margin-top:8px;max-width:80rem}+.credit-list p{font-size:12px;line-height:1.65;margin:4px 0}+@media(max-width:1020px){+ .top{grid-template-columns:auto minmax(4.5rem,1fr) auto;grid-template-areas:"brand search tools" "nav nav nav";gap:6px 10px;padding-block:7px 4px}+ .top .search{max-width:none}+ .top .tools{gap:2px}+ .tabs .nav-trigger{min-height:40px;padding:6px 11px}+}+@media(max-width:760px){+ .top{padding-inline:max(10px,env(safe-area-inset-left)) max(10px,env(safe-area-inset-right))}+ .tabs{gap:2px}+ .tabs .nav-trigger{font-size:13px;padding-inline:9px}+ .tabs .nav-trigger>svg{width:15px;height:15px}+ .tabs .nav-trigger>span{overflow:hidden;text-overflow:ellipsis}+ .tabs .shell-menu{min-width:0}+ .tabs summary.nav-trigger{max-width:100%}+ .tabs .shell-pop{position:fixed;left:max(8px,env(safe-area-inset-left));right:max(8px,env(safe-area-inset-right));width:auto;top:var(--hdr);padding:12px}+ .library-menu{gap:10px 8px}+ .library-menu button,.personal-menu button{min-height:44px}+ .personal-menu{max-width:23rem;margin:auto}+ .foot{padding:16px 12px 24px}+ .notice-pop{max-width:calc(100vw - 20px)}+}+@media(max-width:390px){+ .top .tools .icon{width:32px}+ .asw{margin-right:0}+ .tabs .nav-trigger{gap:4px;padding-inline:7px}+ .library-menu button{font-size:13px;padding-inline:6px}+ .tabs .shell-pop{padding:10px}+}++#qDone{display:none}+#rand svg{display:none;width:17px;height:17px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}+.footer-index .seoc{border:0;padding:12px 0}+@media(max-width:760px){+ .top{grid-template-rows:minmax(44px,auto) auto}+ .top .search:focus-within{position:absolute;display:flex;align-items:center;gap:6px;background:var(--bg);grid-area:auto;inset:7px max(10px,env(safe-area-inset-right)) auto max(10px,env(safe-area-inset-left));width:auto;z-index:51}+ .top .search:focus-within #q{width:0;flex:1}+ .top .search:focus-within #qDone{display:inline-flex;width:54px;min-height:44px;padding:0;justify-content:center;background:var(--bg);color:var(--tx);font-size:13px}+ .top .search:focus-within #qx{right:66px}+ #q:placeholder-shown{padding-inline-end:8px}+ #bar .tbar{column-gap:5px;row-gap:4px}+ #bar .tbar .sp{flex:1 0 0}+ #active:empty{display:none}+ #active:not(:empty){order:1;flex:1 0 55%}+ #clearAll{order:2}+ #fBtn{min-width:38px;min-height:38px;padding:6px;gap:2px}+ #fBtn span{display:none}+ #sort{max-width:126px;min-height:38px}+ #rand{min-height:38px}+}+@media(max-width:365px){+ #rand{width:38px;padding:0;justify-content:center}+ #rand svg{display:block}+ #rand span{display:none}+}++/* Reference board and generation workspace */+#studio{display:flex;flex-direction:column;padding:0 clamp(12px,2.2vw,36px) 20px}+.studio-head{display:flex;align-items:center;justify-content:space-between;gap:16px;max-width:1660px;width:100%;margin:0 auto;padding:16px 2px 14px}+.studio-head h1{font-size:clamp(23px,2.1vw,33px);font-weight:650;letter-spacing:-.045em;line-height:1.12}+.studio-head h1:focus{outline:none}+.studio-head .modes{width:auto;max-width:55%;background:var(--sf);border-radius:12px}+.studio-head .modes button{flex:auto;border-radius:9px;padding:8px 14px;white-space:nowrap}+@media(max-width:420px){html:lang(en) .studio-head .modes button,html:lang(ja) .studio-head .modes button{white-space:normal}}+.st-app{width:100%;flex:1;min-height:0;height:auto;gap:clamp(12px,1.4vw,24px);grid-template-columns:minmax(250px,.91fr) minmax(0,1.82fr) clamp(230px,20vw,340px)}+.st-l,.st-r{gap:12px}+.st-l .step,.st-r .quick,.st-r .adv,.st-r .hist,.st-r .cfg,.st-c,.st-r .gobar{box-shadow:none;border:1px solid var(--line2)}+.st-l .step,.st-r .quick,.st-r .adv,.st-r .hist,.st-c{border-radius:18px}+.primary-materials,.material-extras,.prompt-panel{background:var(--bg2);border:1px solid var(--line2);border-radius:18px}+.primary-materials{padding-inline:15px}+.primary-materials .step{padding:13px 0 15px;border:0;border-radius:0;box-shadow:none;background:transparent}+.primary-materials .step+.step{border-top:1px solid var(--line)}+.st-l .sh{flex-wrap:wrap;gap:4px 8px;margin-bottom:7px;min-height:28px}+.st-l .sh b,.material-extras>summary>b{font-size:14px;font-weight:650}+.material-icon,.material-extras .chevron,.primary-materials .lnk svg{flex:none;width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.65;stroke-linecap:round;stroke-linejoin:round}+.material-icon{color:var(--tx2)}+.st-l .lnk{min-height:28px;padding:3px 5px;border-radius:7px;font-size:12px;font-weight:500;color:var(--tx2);text-decoration:none;background:transparent}+.st-l .lnk:is(:hover,:focus-visible){color:var(--tx);background:var(--sf)}+.st-l .lnk svg{width:14px;height:14px}+.st-l .upload-link{display:inline-flex;align-items:center;padding-inline:8px;cursor:pointer}+.person-step.over{background:var(--acs)}+.primary-materials .empty0{display:flex;align-items:center;gap:8px;min-height:43px;padding:8px 11px;border:1px solid transparent;border-radius:10px;background:var(--sf);color:var(--tx2);text-align:left}+.primary-materials .empty0 b{font-size:13px;font-weight:500;color:inherit}+.primary-materials .empty0::before{content:none}+.primary-materials .empty0::after{content:"+";flex:none;display:grid;place-items:center;width:23px;height:23px;border-radius:50%;background:var(--bg2);color:var(--tx2);font-size:16px;font-weight:400;line-height:1}+.primary-materials .empty0:is(:hover,:focus-visible){border-color:var(--line2);background:var(--sf2);color:var(--tx)}+.primary-materials .empty0:hover::after{color:var(--ac2)}+.primary-materials .r3:not(:has(> button:not([hidden]),> .seg:not([hidden]))){display:none}+.primary-materials #wbChar{margin-top:8px}+.primary-materials #wbChar summary{width:fit-content;min-height:26px;display:flex;align-items:center;gap:6px;cursor:pointer;list-style:none;font-size:12px;font-weight:500;color:var(--tx2)}+.primary-materials #wbChar summary::-webkit-details-marker,.material-extras>summary::-webkit-details-marker{display:none}+.primary-materials #wbChar summary::after{content:"";width:6px;height:6px;border:solid currentColor;border-width:0 1px 1px 0;transform:rotate(45deg) translateY(-2px)}+.primary-materials #wbChar[open] summary::after{transform:rotate(225deg) translate(-1px,-1px)}+.primary-materials #wbChar[open] .chips{padding:4px 0}+.st-l .pick{min-width:0;padding:5px 7px 5px 5px;gap:8px;border-radius:10px}+.st-l .pick img,.other-preview img{border:1px solid var(--ref-edge,var(--line2));border-radius:7px;box-shadow:none}+.st-l .pick img{width:39px;height:48px}+.st-l .pick small{display:block;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}+.st-l .pick select{min-width:0;max-width:35%;min-height:30px;padding:4px 20px 4px 7px;background-position:right 7px center}+.st-l .pick .rmx{flex:none;width:26px;height:26px;opacity:1;box-shadow:none}+.material-extras{flex:none;padding:0 15px}+.material-extras>summary{display:flex;align-items:center;gap:8px;min-height:50px;list-style:none;color:var(--tx);cursor:pointer}+.material-extras .chevron{width:14px;height:14px;color:var(--mu);transition:transform .18s var(--out)}+.material-extras[open] .chevron{transform:rotate(180deg)}+.other-preview{display:inline-flex;align-items:center}+.other-preview img{display:block;width:23px;height:27px;object-fit:cover;background:var(--sf)}+.other-preview img+img{margin-left:-5px}+#wbOtherCount:not(:empty){min-width:21px;padding:2px 5px;border-radius:6px;font-size:11px;text-align:center;color:var(--tx2);background:var(--sf);font-variant-numeric:tabular-nums}+.other-types{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px}+.other-types button{min-width:0;min-height:33px;padding:5px;border:1px solid var(--line);border-radius:8px;font-size:12px;color:var(--tx2);background:var(--bg2);white-space:normal}+.other-types button:is(:hover,:focus-visible){background:var(--sf);color:var(--tx)}+.material-extras[open]{padding-bottom:13px}+.material-extras .slot:not(:empty){margin-top:8px}+.prompt-panel{padding:13px 14px}+.prompt-panel .sh{margin:0 0 8px}+.prompt-panel .sh b{font-size:14px}+.prompt-panel #wbPrompt{display:block;margin:0;padding:9px 10px;min-height:88px;max-height:28vh;font-size:13px;line-height:1.55;color:var(--tx);border:1px solid transparent;border-radius:9px}+.prompt-panel #wbPrompt:focus{border-color:var(--tx2);background:var(--bg2)}+.prompt-tools{display:flex;align-items:center;flex-wrap:wrap;gap:4px;margin-top:8px}+.prompt-tools .sm.ghost{padding:5px 7px;font-size:12px}+.pk-types{display:flex;flex:none;align-items:center;flex-wrap:wrap;gap:5px;margin:0 24px 10px}+.pk-types button{min-height:32px;padding:6px 12px;font-size:12.5px;color:var(--tx2)}+.pk-types button:is(.on,[aria-pressed=true]){background:var(--tx);color:var(--bg)}++.st-c{padding:0;overflow:auto;scrollbar-width:thin}+.canvas-head{display:flex;align-items:center;justify-content:space-between;padding:13px 16px;border-bottom:1px solid var(--line);gap:12px}+.canvas-head h2,.dock-heading h3{font-size:14px;font-weight:650}+.canvas-head span{font-size:12px;color:var(--mu);font-variant-numeric:tabular-nums}+.st-c #wbStage{border-radius:0;flex:1;min-height:180px;background-color:var(--sf);background-image:radial-gradient(var(--line2) .85px,transparent .85px);background-size:13px 13px}+.reference-board{display:grid;place-items:center;align-content:center;gap:36px;width:100%;min-width:0;padding:clamp(18px,4%,48px);max-height:100%;overflow:auto}+.board-cards{display:flex;justify-content:center;align-items:center;flex-wrap:wrap;gap:12px;width:100%;min-width:0;padding:10px 3px}+.board-card{display:flex;flex-direction:column;align-items:stretch;gap:0;text-align:start;max-width:215px;width:clamp(64px,38%,215px);padding:5px;border-radius:13px;background:var(--bg2);border:1px solid var(--line2);box-shadow:0 8px 22px rgba(0,0,0,.08);white-space:normal}+.board-card img{display:block;width:100%;aspect-ratio:3/4;object-fit:cover;border-radius:8px;background:var(--sf)}+.board-card:is([data-pick=costume],[data-pick=pose]) img{object-fit:contain}+.board-card span{align-self:center;padding:6px 3px 1px;color:var(--tx2);font-size:12px;font-weight:580}+.board-cards:not(.many){flex-wrap:nowrap}+.board-cards.sample:not(.many){gap:0}+.board-cards.sample:not(.many) .board-card{width:36%}+.board-cards.sample:not(.many) .board-card:first-child:not(:last-child){transform:rotate(-6deg) translateY(5%);margin-right:-7%}+.board-cards.sample:not(.many) .board-card:nth-child(2){transform:translateY(-5%);z-index:1}+.board-cards.sample:not(.many) .board-card:nth-child(3){transform:rotate(6deg) translateY(8%);margin-left:-7%}+.board-cards:not(.sample) .board-card{min-width:0;border-color:var(--ref-edge,var(--line2))}+.board-cards:not(.sample) .board-card img{object-fit:contain}+.board-card[data-type=depth] img{background:#141414}+.board-cards.many .board-card{width:clamp(62px,24%,135px)}+.board-cards .board-card:is(:hover,:focus-visible){z-index:2;border-color:var(--tx2)}+.board-use{min-height:38px;padding:8px 16px;background:var(--bg2);border:1px solid var(--line2);font-size:13px}+.board-use::after{content:"↗";font-size:15px}+.st-c .out-act,.st-c .warn,.st-c .res,.st-c .sent{margin:8px 12px}+.st-c .cmp{background:var(--sf)}+.st-c:has(#wbCmp:not([hidden])) #wbStage{min-height:240px}+.st-c #wbBusy{background:color-mix(in srgb,var(--bg2) 88%,transparent)}+#wbProg{appearance:none;width:min(220px,65%);height:5px;border:0;border-radius:8px;overflow:hidden;background:var(--sf2);accent-color:var(--ac)}+#wbProg::-webkit-progress-bar{background:var(--sf2);border-radius:8px}+#wbProg::-webkit-progress-value{background:var(--ac);border-radius:8px}+#wbProg:indeterminate{background:var(--sf2) linear-gradient(90deg,transparent,var(--ac),transparent) no-repeat;background-size:48% 100%;animation:rendering 1.5s ease-in-out infinite alternate}+#wbProg:indeterminate::-webkit-progress-inner-element{display:none}+@keyframes rendering{from{background-position:-40% 0}to{background-position:140% 0}}+.st-r .hist:has(.hl:empty){display:none}+.st-r .gobar{margin-top:auto;position:sticky;bottom:0;box-shadow:0 -5px 14px color-mix(in srgb,var(--bg) 75%,transparent)}+.st-r .big{box-shadow:none}+.out-act{flex-wrap:wrap}+.out-act small{overflow-wrap:anywhere}+#wbRange:focus-visible + em{outline:2px solid var(--ac)}+/* The compact strip and its editor share one bottom anchor. */+body{--dock-base:18px;--dock-edge:calc(var(--dock-base) + env(safe-area-inset-bottom));--dock-limit:min(49dvh,430px)}+body.batch{--dock-base:82px}+#workspaceDock{+ position:fixed;z-index:34;bottom:var(--dock-edge);left:50%;transform:translateX(-50%);width:max-content;+ max-width:calc(100% - 24px);display:grid;justify-items:center;pointer-events:none;+ --rail-bg:#242429;--rail-text:#f8f8fa;--rail-muted:#cacacf;--rail-hover:#36363d;--rail-line:rgba(255,255,255,.15);+}+#workspaceDock svg{width:18px;height:18px;flex:none;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round}+#workspaceDock .dock-mark{+ flex:none;display:grid;place-items:center;width:34px;height:34px;border-radius:50%;background:var(--rail-hover);color:var(--rail-text);+}+#workspaceDock .dock-mark svg{width:23px;height:23px}+#workspaceDock .dock-mark .dock-spark{stroke:var(--rail-hover);stroke-width:1.2;fill:#ff4964}+#workspaceDock .dock-chevron{width:15px;height:15px;color:var(--rail-muted);stroke-width:1.8}+#trayFab{+ position:static;display:flex;align-items:center;gap:9px;width:auto;height:48px;padding:5px 12px 5px 6px;+ border:1px solid var(--rail-line);border-radius:99px;color:var(--rail-text);background:var(--rail-bg);pointer-events:auto;+ font-size:13px;font-weight:620;box-shadow:0 6px 20px rgba(0,0,0,.2),0 1px 4px rgba(0,0,0,.11);+}+#trayFab:hover{border-color:#68686c;color:var(--rail-text);background:var(--rail-bg)}+#trayFilm{display:flex;align-items:center;padding:1px 2px 1px 3px}+#trayFilm:empty{display:none}+#trayFilm img{width:26px;height:34px;object-fit:cover;background:var(--rail-hover);border:1px solid var(--ref-edge);border-radius:5px}+#trayFilm img:not(:first-child){margin-left:-9px}+#trayFilm img:first-child:not(:last-child){transform:rotate(-7deg)}+#trayFilm img:last-child:not(:first-child){transform:rotate(7deg)}+#trayFab #trayFabN,#trayN:not(:empty){display:grid;place-items:center;min-width:21px;height:21px;padding:0 5px;border:0;border-radius:7px;background:var(--rail-hover);color:var(--rail-text);font:650 11px/1 var(--sans);font-variant-numeric:tabular-nums}+#tray{+ position:static;display:flex;flex-direction:column;align-items:center;gap:7px;width:min(780px,calc(100vw - 24px));max-width:100%;+ max-height:var(--dock-limit);padding:0;overflow:visible;background:transparent;border:0;border-radius:0;+ box-shadow:none;pointer-events:none;transform-origin:center bottom;+}+#tray:focus{outline:none}+#workspaceDock [hidden]{display:none!important}+#tray .tray-b{+ min-height:0;align-self:stretch;overflow-y:auto;overscroll-behavior:contain;scrollbar-width:thin;pointer-events:auto;+ border:1px solid var(--line2);border-radius:20px;background:var(--bg2);box-shadow:0 10px 36px rgba(0,0,0,.13),0 2px 6px rgba(0,0,0,.06);+ display:grid;grid-template-columns:minmax(0,.94fr) minmax(0,1.13fr);padding:16px 19px 14px;gap:18px;+}+.dock-materials{container-type:inline-size;min-width:0;border-right:1px solid var(--line);padding-right:18px}+.dock-heading{display:flex;align-items:center;justify-content:space-between;gap:8px;min-height:30px}+.dock-heading h3,.dock-heading label{font-size:13px;font-weight:650;line-height:1.3}+.dock-heading .tg-empty{margin:0;padding:0;border:0;background:none;font-size:12px;font-weight:400;color:var(--tx2)}+#trayClear{font-size:12px;color:var(--tx2);padding:5px}+.tray-items:empty{display:none}+.tray-items{flex-wrap:nowrap;align-items:center;gap:7px;max-width:100%;padding:8px 6px 6px 1px;overflow-x:auto;overflow-y:hidden;scroll-snap-type:x proximity;scrollbar-width:thin}+.tray-items>div{scroll-snap-align:start}+.tray-items img{width:68px;height:86px;border:1px solid var(--ref-edge);border-radius:9px}+:is(#workspaceDock,#studio) [data-type=pose]{--ref-edge:#849dbb;object-fit:contain}+:is(#workspaceDock,#studio) [data-type=depth]{--ref-edge:#9689ae;object-fit:contain}+:is(#workspaceDock,#studio) [data-type=costume]{--ref-edge:#be929a}+:is(#workspaceDock,#studio) [data-type=anime]{--ref-edge:#b08fad}+:is(#workspaceDock,#studio) [data-type=portrait]{--ref-edge:#c49a82}+:is(#workspaceDock,#studio) [data-type=expr]{--ref-edge:#a2778b}+:is(#workspaceDock,#studio) [data-type=hair]{--ref-edge:#968071}+:is(#workspaceDock,#studio) [data-type=dyn]{--ref-edge:#ab7870}+:is(#workspaceDock,#studio) [data-type=scene]{--ref-edge:#88a48a}+:is(#workspaceDock,#studio) [data-type=light]{--ref-edge:#a2b6bf}+:is(#workspaceDock,#studio) [data-type=prop]{--ref-edge:#739e9c}+:is(#workspaceDock,#studio) [data-type=furn]{--ref-edge:#95928e}+.tray-items em{bottom:1px;left:1px;right:1px;padding:8px 5px 3px;border-radius:0 0 8px 8px;background:linear-gradient(transparent,rgba(0,0,0,.6));text-align:left;line-height:1.2;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}+.tray-items [data-k]{width:25px;height:25px;right:-4px;top:-5px;border:2px solid var(--bg2)}+.tray-pair{position:absolute;top:2px;left:2px;width:24px;height:24px;padding:0;border-radius:50%;background:var(--bg2);color:var(--tx);font-size:14px;line-height:1;box-shadow:var(--sh1)}+@media(hover:hover) and (pointer:fine){+ .tray-items :is([data-k],.tray-pair){opacity:0}+ .tray-items>div:hover :is([data-k],.tray-pair),.tray-items>div:focus-within :is([data-k],.tray-pair){opacity:1}+}+.tg-add{align-items:center;gap:5px;margin:6px 0 0}+.tg-add button,.tg-add summary{+ display:inline-flex;align-items:center;justify-content:center;gap:4px;min-height:32px;padding:5px 9px;margin:0;+ border:1px solid transparent;border-radius:9px;background:var(--sf);color:var(--tx2);font-size:12px;line-height:1.2;cursor:pointer;+}+.tg-add button:hover,.tg-add summary:hover{color:var(--tx);border-color:var(--line2);background:var(--sf2)}+#tgAddRow svg{width:15px;height:15px}+.tg-add summary::after,.dock-combo>summary::after{content:"";width:6px;height:6px;flex:none;border:solid currentColor;border-width:0 1.5px 1.5px 0;transform:translateY(-1px) rotate(45deg)}+#tgMore summary{width:34px;padding:0}+#tgMore summary svg{display:block;width:18px;height:18px;fill:currentColor}+#tgMore summary::after{display:none}+@container(max-width:350px){+ #tgAddRow>button{padding-inline:8px}+ #tgAddRow>button svg{display:none}+}+.tg-add details[open]{width:100%}+.tg-add details[open] summary::after,.dock-combo[open]>summary::after{transform:translateY(1px) rotate(225deg)}+.tg-add details>div{display:flex;flex-wrap:wrap;gap:5px;margin-top:6px}+.dock-combo{margin-top:8px;border-top:1px solid var(--line)}+.dock-combo>summary{display:flex;align-items:center;gap:8px;width:max-content;min-height:34px;color:var(--tx2);font-size:12px;cursor:pointer}+.dock-combo>summary::-webkit-details-marker,.tg-add summary::-webkit-details-marker{display:none}+#trayText{max-height:90px;margin:6px 0}+.tray-act{padding-bottom:4px}+#tray .tgen{min-width:0;margin:0;padding:0;border:0}+.dock-icon{display:grid;place-items:center;flex:none;width:38px;height:38px;padding:0;border-radius:11px;color:var(--tx2);background:transparent}+.dock-icon:hover{background:var(--sf);color:var(--tx)}+#tgCopyDraft{width:32px;height:32px}+#tgPrompt{display:block;margin:3px 0 0;min-height:62px;max-height:200px;border:1px solid var(--line2);background:var(--sf);resize:vertical}+#tgPrompt:focus{border-color:var(--tx2);background:var(--bg2);outline:none}+.tgen-row{justify-content:flex-start;gap:12px;margin-top:8px}+.tgen-row select{min-height:30px}+#tgRes{flex-wrap:nowrap;overflow-x:auto}+#tgRes button{flex:none}+#tgRes img{width:52px;height:64px}+@media(min-width:641px){+ #tray .tgen{display:flex;flex-direction:column}+ #tray .tgen>:not(#tgPrompt){flex:none}+ #tray #tgPrompt{flex:1 0 auto;max-height:none}+ #tray .tgen-row{justify-content:space-between}+ #tray #tgRes:empty{display:none}+}+.dock-foot{+ flex:none;display:flex;align-items:center;justify-content:space-between;gap:9px;max-width:100%;padding:4px 5px;pointer-events:auto;+ border:1px solid var(--rail-line);border-radius:99px;background:var(--rail-bg);color:var(--rail-text);box-shadow:0 6px 22px rgba(0,0,0,.2),0 1px 4px rgba(0,0,0,.12);+}+.dock-title,.dock-actions,#trayMin{display:flex;align-items:center;min-width:0;margin:0}+.dock-actions{gap:3px;border-left:1px solid var(--rail-line);padding-left:7px}+.dock-actions .dock-icon{color:var(--rail-muted);border-radius:50%}+.dock-actions .dock-icon:hover,.dock-actions #tgCfg:hover{background:var(--rail-hover);color:var(--rail-text)}+#workspaceDock :is(#trayFab,.dock-foot button):focus-visible{outline:2px solid #ff526e;outline-offset:2px}+#trayMin{gap:7px;min-height:40px;background:transparent;padding:3px 7px 3px 2px;color:var(--rail-text);font-size:13px;font-weight:620;border-radius:99px}+#trayMin:hover{background:var(--rail-hover)}+#trayMin .dock-chevron{transform:rotate(180deg)}+.dock-foot #tgCfg{display:flex;align-items:center;gap:5px;min-width:0;min-height:38px;padding:5px 9px;color:var(--rail-muted);background:transparent;font-size:12px}+.dock-foot #tgCfg svg{display:none}+.dock-foot #tgProv{display:block;max-width:165px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.dock-foot #tgGo,.dock-foot #tgStop{flex:none;min-height:40px;padding:8px 16px}+.dock-foot #tgGo{background:#d91f43}+.dock-foot #tgGo:hover{background:#c5183a}+.dock-foot #tgStop{background:var(--rail-hover);color:var(--rail-text)}+.dock-foot:has(#tgStop:not([hidden])) #tgGo{display:none}+body:has(#tray:not([hidden])) .foot{padding-bottom:calc(var(--dock-edge) + var(--dock-limit) + 18px)}+body:has(#trayFab:not([hidden])) .foot{padding-bottom:calc(var(--dock-edge) + 58px)}+body:has(#trayFab:not([hidden])) #toast{bottom:calc(var(--dock-edge) + 60px)}+body:has(#tray:not([hidden])) #toast{bottom:auto;top:calc(var(--hdr,72px) + 8px)}+@media(min-width:861px){+ body.studio #workspaceDock{--studio-controls:clamp(230px,20vw,340px);left:calc((100% - var(--studio-controls))/2)}+ body.studio #tray{width:min(780px,calc(100vw - var(--studio-controls) - 84px))}+}+@media(max-width:860px){+ body{--dock-base:10px}+ body.studio{--dock-base:84px}+ body.batch{--dock-base:65px}+}+@media(max-width:640px){+ body{--dock-limit:min(48dvh,370px)}+ #workspaceDock{max-width:calc(100% - 16px)}+ #tray{width:min(470px,calc(100vw - 16px));border-radius:19px}+ #tray .tray-b{grid-template-columns:minmax(0,1fr);padding:10px 13px;gap:9px}+ .dock-materials{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:2px 10px;border:0;padding:0}+ .dock-block{display:contents}+ .dock-block>.dock-heading{grid-area:1 / 1}+ .dock-combo{grid-area:1 / 2;margin:0;border:0}+ .dock-combo>summary{min-height:30px}+ .dock-combo[open]{grid-area:auto / 1 / auto / -1}+ .tray-items,.tg-add{grid-column:1 / -1}+ .dock-heading{min-height:24px}+ .tg-add{margin-top:4px;gap:4px}+ .tg-add button,.tg-add summary{min-height:34px;padding:5px 8px}+ #tgAddRow svg{display:none}+ .tray-items img{width:51px;height:64px}+ #tgPrompt{max-height:128px;min-height:55px;height:64px}+ .tgen-row{margin-top:5px}+ @container(max-width:310px){#tgAddRow>button{padding-inline:6px}}+ .dock-foot{gap:4px;padding:3px 4px}+ .dock-actions{gap:1px;padding-left:3px}+ .dock-foot #tgCfg{position:relative;justify-content:center;width:38px;height:38px;padding:0}+ .dock-foot #tgCfg svg{display:block}+ .dock-foot #tgCfg .dot{position:absolute;top:5px;right:4px;width:6px;height:6px;border:1px solid var(--rail-bg)}+ .dock-foot #tgProv{position:absolute;clip-path:inset(50%);width:1px;height:1px}+ .dock-foot #tgGo,.dock-foot #tgStop{padding:8px 12px}+}+@media(max-width:360px){+ #trayMin{gap:5px}+ #trayTitle{position:absolute;width:1px;height:1px;clip-path:inset(50%);overflow:hidden}+}+@media(min-width:640px) and (max-width:1024px) and (max-height:530px) and (orientation:landscape){+ body{--dock-limit:48dvh}+ body.studio{--dock-base:9px}+ body.studio #workspaceDock{left:10px;transform:none;max-width:calc(50% - 16px)}+ body.studio #tray{width:calc(50vw - 16px)}+ body.studio #tray .tray-b{grid-template-columns:minmax(0,1fr);gap:8px}+ body.studio #tray .tgen{display:block}+ body.studio #tray #tgPrompt{max-height:200px}+ body.studio #tray .tgen-row{justify-content:flex-start}+ body.studio .dock-materials{border:0;padding:0}+ body.studio .dock-foot #tgProv{max-width:65px}+ body.studio #trayTitle{position:absolute;width:1px;height:1px;clip-path:inset(50%);overflow:hidden}+}+@media(prefers-reduced-motion:no-preference){+ #tray{animation:dock-open .27s cubic-bezier(.16,1,.3,1)}+ #trayFilm img{transition:transform .22s var(--out),margin .22s var(--out)}+ #trayFab:hover #trayFilm img:not(:first-child){margin-left:-6px}+ #trayFab:hover .dock-chevron{transform:translateY(-2px)}+ @keyframes dock-open{from{opacity:0;transform:translateY(12px) scale(.975)}to{opacity:1;transform:none}}+}+@media(prefers-reduced-motion:reduce){#tray,#wbProg:indeterminate{animation:none}}+@media(max-width:860px){+ #studio{padding:0 12px calc(128px + env(safe-area-inset-bottom))}+ .studio-head{padding:12px 0;gap:8px}+ .studio-head .modes{max-width:62%}+ .studio-head .modes button{padding:7px 10px;font-size:12px}+ .st-app{display:flex;flex-direction:column;gap:12px}+ .st-l,.st-r{display:flex;flex-direction:column;overflow:visible}+ .st-c{order:-1;min-height:0}+ .st-c:has(#wbCmp:not([hidden]),#wbBusy:not([hidden]),#wbErr:not([hidden])){order:-3;min-height:0}+ .primary-materials{padding-inline:13px}+ .primary-materials .step{padding-block:9px 12px}+ .material-extras{padding-inline:13px}+ .pk-types{margin:0 14px 8px}+ .st-l .lnk,.other-types button,.pk-types button{min-height:40px}+ .st-l .pick .rmx{width:36px;height:36px}+ .st-l .pick select{min-height:36px}+ .prompt-panel #wbPrompt,.primary-materials #wbCharTxt{font-size:16px}+ .st-c #wbStage,.st-c:has(#wbPh0:not([hidden])) #wbStage{min-height:0}+ .reference-board{padding:16px 12px;gap:13px}+ .board-cards{max-width:370px}+ .board-cards:not(.many) .board-card{width:26%;padding:3px;border-radius:9px}+ .board-card img{border-radius:6px}+ .board-card span{font-size:11px;padding:3px}+ .board-use{min-height:34px;padding:6px 12px}+ .st-c:has(#wbCmp:not([hidden])) #wbStage,.st-c:has(#wbBusy:not([hidden])) #wbStage,.st-c:has(#wbErr:not([hidden])) #wbStage{min-height:min(450px,60dvh)}+ .st-r .gobar{position:fixed;bottom:0;margin:0;display:flex;align-items:center;gap:12px;border-radius:16px 16px 0 0}+ .gobar .gb-i{flex:1;display:flex;align-items:flex-start;flex-direction:column;gap:2px;min-width:0;padding:0}+ .gobar .gb-i b{font-size:12px}+ .gobar .cfgchip{background:none;min-height:30px;padding:2px 4px}+ .gobar .big{width:auto;min-width:100px;min-height:44px;padding:10px 16px}++}+@media(max-width:860px) and (orientation:portrait){+ .st-app .st-r{display:contents}+ .st-app .st-l{order:-3}+ .st-app .prompt-panel{order:-2}+ .st-c:has(#wbCmp:not([hidden]),#wbBusy:not([hidden]),#wbErr:not([hidden])){order:-4}+ body.studio:not(.tray) #workspaceDock{bottom:calc(14px + env(safe-area-inset-bottom))}+ body.studio #trayFab{position:relative;min-width:44px;height:44px;padding:4px 7px;border-radius:12px;box-shadow:none}+ body.studio #trayFab :is(.dock-launch-name,.dock-chevron){display:none}+ body.studio #trayFab .dock-mark{width:28px;height:28px;background:transparent}+ body.studio #trayFab:has(#trayFilm:not(:empty)) .dock-mark{display:none}+ body.studio #trayFilm{padding:0}+ body.studio #trayFilm img{width:20px;height:28px}+ body.studio #trayFilm img:not(:first-child){margin-left:-10px}+ body.studio #trayFabN{position:absolute;top:-5px;right:-6px;height:16px;min-width:16px;padding:0 4px;font-size:10px;border:1px solid var(--bg2)}+ .st-r .gobar{justify-content:space-between}+ .gobar .gb-i{max-width:calc(50% - 30px)}+ .gobar .gb-i>span,.gobar .cfgchip{max-width:100%}+ .gobar .gb-i b,#wbProv2{overflow:hidden;white-space:nowrap;text-overflow:ellipsis}+}+@media(min-width:640px) and (max-width:1024px) and (max-height:530px) and (orientation:landscape){+ #studio{height:auto;padding-bottom:70px}+ .st-app{display:grid;grid-template-columns:repeat(2,minmax(0,1fr))}+ .st-r .gobar{position:fixed;bottom:0;right:12px;margin:0}+ .studio-head h1{font-size:22px}+ .reference-board{padding:16px;gap:8px}+ .board-cards:not(.many) .board-card{width:23%}+}+++.lang-panel .copy-pref{display:flex;align-items:center;gap:8px;margin-top:4px;padding-top:10px;border-top:1px solid var(--line);cursor:pointer}+.copy-pref input{width:16px;height:16px;margin:0;accent-color:var(--ac)}++.card-heading{display:flex;align-items:center;gap:5px}+.card-heading h3{flex:1;min-width:0}+.card-copy{display:grid;place-items:center;flex:none;width:32px;height:32px;background:transparent;color:var(--tx2);padding:5px;border:0;border-radius:8px;cursor:pointer}+.card-copy svg{width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}+.card-copy:hover,.card-copy:focus-visible{background:var(--bg);color:var(--ac)}+@media(hover:hover) and (pointer:fine){.card-copy{opacity:0}.card:hover .card-copy,.card:focus-within .card-copy{opacity:1}}+@media(pointer:coarse){.card-copy{width:40px;height:40px}}++.hist-stats{display:flex;flex-wrap:wrap;align-items:center;gap:6px 14px;color:var(--tx2);font-variant-numeric:tabular-nums}+.hist-ratio{display:flex;overflow:hidden;flex:none;width:84px;height:5px;border-radius:3px;background:var(--mu)}+.hist-ratio i,.hist-key i{background:var(--ac)}.hist-key.gen i{background:var(--mu)}+.hist-key{display:inline-flex;align-items:center;gap:4px}.hist-key i{width:6px;height:6px;border-radius:50%}+.hist-key b{color:var(--tx)}.hist-providers{font-size:12px}diff --git a/src/sw.js b/src/sw.jsindex 3232dcb..3c28888 100644--- a/src/sw.js+++ b/src/sw.js@@ -1,5 +1,25 @@-const V='posewear-v9';self.addEventListener('install',e=>{self.skipWaiting();e.waitUntil(caches.open(V).then(c=>c.addAll(['./','index.html','style.css','app.js','studio.js','extras.js','zip.js','history.js','favicon.svg'])))});-self.addEventListener('activate',e=>e.waitUntil(caches.keys().then(ks=>Promise.all(ks.filter(k=>k!=V).map(k=>caches.delete(k))))));-self.addEventListener('fetch',e=>{const u=new URL(e.request.url);if(u.origin!=location.origin||u.pathname.startsWith('/api/')||e.request.method!='GET')return;- const img=/\/(p|c)\/(t|i|m)\//.test(u.pathname);e.respondWith(img?caches.match(e.request).then(r=>r||fetch(e.request).then(res=>{const cl=res.clone();caches.open(V+'-img').then(c=>c.put(e.request,cl));return res}))- :fetch(e.request).then(res=>{const cl=res.clone();caches.open(V).then(c=>c.put(e.request,cl));return res}).catch(()=>caches.match(e.request)))});+const VERSION = 'posewear-development';+const PRECACHE = ['./','index.html','theme.js','style.css','app.js','image-providers.js','studio.js','extras.js','zip.js','history.js','i18n.js','references.js','favicon.svg'];+self.addEventListener('install', event => {+ event.waitUntil(caches.open(VERSION).then(cache => cache.addAll(PRECACHE)).then(() => self.skipWaiting()));+});+self.addEventListener('activate', event => {+ event.waitUntil(caches.keys().then(keys => Promise.all(+ keys.filter(key => key.startsWith('posewear-') && key !== VERSION).map(key => caches.delete(key))+ )));+});+self.addEventListener('fetch', event => {+ const request = event.request;+ const url = new URL(request.url);+ if (request.method !== 'GET' || url.origin !== location.origin || url.pathname.startsWith('/api/')) return;+ event.respondWith((async () => {+ const cache = await caches.open(VERSION);+ let response;+ try { response = await fetch(request); }+ catch (error) { return await cache.match(request) || Promise.reject(error); }+ if (response.ok && response.status === 200 && !response.redirected) {+ event.waitUntil(cache.put(request, response.clone()).catch(() => {}));+ }+ return response;+ })());+});diff --git a/src/theme.js b/src/theme.jsnew file mode 100644index 0000000..4b731b8--- /dev/null+++ b/src/theme.js@@ -0,0 +1,33 @@+// Run in the document head so the first paint uses the saved appearance.+(() => {+ const root = document.documentElement;+ const system = matchMedia('(prefers-color-scheme: dark)');+ const tint = document.querySelector('meta[name="theme-color"]');+ const preference = value => value === 'dark' || value === 'light' ? value : 'system';+ let selected = 'system';+ try { selected = preference(localStorage.getItem('theme')); } catch { /* Storage can be disabled. */ }++ function apply() {+ const resolved = selected === 'system' ? (system.matches ? 'dark' : 'light') : selected;+ root.dataset.theme = resolved;+ if (tint) tint.content = resolved === 'dark' ? '#111111' : '#ffffff';+ for (const button of document.querySelectorAll('[data-theme-choice]')) {+ button.setAttribute('aria-pressed', String(button.dataset.themeChoice === selected));+ }+ }+ function select(value) {+ selected = preference(value);+ apply();+ try { localStorage.setItem('theme', selected); } catch { /* Keep the choice for this visit. */ }+ }++ apply();+ document.addEventListener('DOMContentLoaded', apply, {once: true});+ system.addEventListener('change', () => { if (selected === 'system') apply(); });+ window.addEventListener('storage', event => {+ if (event.storageArea !== localStorage || (event.key !== 'theme' && event.key !== null)) return;+ selected = preference(event.newValue);+ apply();+ });+ window.PoseWearTheme = {select, toggle() { select(root.dataset.theme === 'dark' ? 'light' : 'dark'); }};+})();diff --git a/tests/check_csp.py b/tests/check_csp.pyindex 2cc0c1c..f593e7d 100644--- a/tests/check_csp.py+++ b/tests/check_csp.py@@ -1,47 +1,64 @@-# CSP 守卫:dist/assets/*.json 里所有图片字段引用的外部源站,必须出现在-# dist/_headers 的 img-src 里,否则浏览器会拦截(2026-11-23 发型库热链图全灭的教训)。-# 用法:python3 tests/check_csp.py [dist目录]-import json, glob, re, sys, os+"""Check the deployable catalog set and the CSP permissions needed to browse and fetch its images."""+import json+import re+import sys+from pathlib import Path+from urllib.parse import urlsplit-D = sys.argv[1] if len(sys.argv) > 1 else 'dist'-hdr = open(f'{D}/_headers').read()-m = re.search(r'img-src ([^;]+)', hdr)-img_src = set(m.group(1).split()) if m else set()-m2 = re.search(r'connect-src ([^;]+)', hdr)-conn_src = set(m2.group(1).split()) if m2 else set()+def check(root):+ headers = (root / '_headers').read_text()+ policy = re.search(r'Content-Security-Policy:\s*([^\n]+)', headers).group(1)+ directives = {words[0]: set(words[1:]) for part in policy.split(';') if (words := part.split())}+ names = 'poses depths costumes anime portraits expressions hair dynasties scenes lights props furniture'.split()+ origins = set()+ problems = []+ home = (root / 'index.html').read_text()+ footer = re.search(r'<footer class="foot">.*?</footer>', home, re.S)+ index_marker = '<details class="footer-index">'+ if home.count(index_marker) != 1 or not footer or index_marker not in footer[0]:+ problems.append('The category index must appear once in the site footer.')+ if (root / '.posewear-partial').exists():+ problems.append('Local partial build: ' + (root / '.posewear-partial').read_text().replace('\n', ', '))+ def images(node):+ if isinstance(node, list):+ for item in node: images(item)+ if isinstance(node, dict):+ for key, value in node.items():+ if key in {'t','m','i','o'} and isinstance(value, str) and '://' in value:+ url = urlsplit(value)+ origins.add(f'{url.scheme}://{url.netloc}')+ else: images(value)+ for name in names:+ files = list((root / 'assets').glob(name+'.*.json'))+ if len(files) != 1:+ problems.append(f'{name}: expected one manifest, found {len(files)}')+ continue+ try:+ data = json.loads(files[0].read_text())+ items = data.get('items') if isinstance(data, dict) else data+ if not isinstance(items, list) or not items: raise ValueError('missing items')+ images(items)+ except (ValueError, OSError) as error:+ problems.append(f'{name}: {error}')+ apps = list((root/'assets').glob('app.*.js'))+ if len(apps) != 1:+ problems.append('Expected one compiled app.js')+ else:+ host = re.search(r"""const AH=['"](https?://[^'"]+)['"]""", apps[0].read_text())+ if host: origins.add(host[1].rstrip('/'))+ for directive in ['img-src','connect-src']:+ allowed = directives.get(directive, set())+ if "'self'" not in allowed: problems.append(f"{directive}: missing 'self'")+ for origin in sorted(origins):+ if origin not in allowed and origin.split(':')[0]+':' not in allowed:+ problems.append(f'{directive}: missing {origin}')+ return problems-IMG_KEYS = {'t', 'i', 'o', 'm'}-origins = {}--def walk(o):- if isinstance(o, dict):- for k, v in o.items():- if k in IMG_KEYS and isinstance(v, str) and v.startswith('https://'):- org = '/'.join(v.split('/')[:3])- origins[org] = origins.get(org, 0) + 1- else:- walk(v)- elif isinstance(o, list):- for v in o:- walk(v)--for f in glob.glob(f'{D}/assets/*.json'):+if __name__ == '__main__':try:- walk(json.load(open(f)))- except Exception:- pass--bad = []-for org, n in sorted(origins.items()):- if org not in img_src:- bad.append(f'{org}({n} 处图片引用不在 img-src)')- if org not in conn_src and org not in ("'self'",):- # connect-src 缺失只警告:试穿台 fetch 素材时才需要,图片展示不受影响- print(f'WARN {org} 不在 connect-src(试穿台取图可能被拦)')--if bad:- print('FAIL CSP img-src 缺失源站:')- for b in bad:- print(' -', b)- sys.exit(1)-print(f'PASS CSP img-src 覆盖全部 {len(origins)} 个图片源站:{sorted(origins)}')+ issues = check(Path(sys.argv[1] if len(sys.argv)>1 else 'dist'))+ except (OSError, AttributeError, ValueError) as error:+ issues = [str(error)]+ if issues:+ sys.exit('FAIL\n'+'\n'.join(issues))+ print('PASS: site footer, 12 populated catalogs and all image and fetch origins.')diff --git a/tests/dock-browsing-regressions.js b/tests/dock-browsing-regressions.jsnew file mode 100644index 0000000..7bae7c0--- /dev/null+++ b/tests/dock-browsing-regressions.js@@ -0,0 +1,192 @@+const assert = require('node:assert/strict');+const {chromium} = require('playwright');++async function scrollGallery(page, mobile) {+ const tray = await page.locator('#tray').boundingBox();+ const y = Math.min(360, tray.y - 12);+ await page.evaluate(() => window.scrollTo({top:0,behavior:'instant'}));+ if (mobile) {+ const cdp = await page.context().newCDPSession(page);+ const touch = (type, points) => cdp.send('Input.dispatchTouchEvent',{type,touchPoints:points});+ await touch('touchStart',[{x:24,y}]);+ for (let offset=20; offset<=100; offset+=20) await touch('touchMove',[{x:24,y:y-offset}]);+ await touch('touchEnd',[]);+ await cdp.detach();+ } else {+ await page.mouse.move(24,y);+ await page.mouse.wheel(0,170);+ }+ await page.waitForFunction(() => scrollY > 10, null, {timeout:4000});+}++// Put the target in the part of the gallery above or beside the dock. A normal+// click/tap still has to pass hit-testing, including for photo and angle buttons.+async function reveal(control) {+ await control.evaluate(el => {+ const r = el.getBoundingClientRect(), dock = document.querySelector('#tray').getBoundingClientRect();+ const x = r.left + r.width/2, y = r.top + r.height/2;+ const top = document.querySelector('#bar').getBoundingClientRect().bottom + 6;+ const bottom = (x > dock.left && x < dock.right ? dock.top : innerHeight) - 6;+ if (y < top || y > bottom) window.scrollBy({top:y-(top+bottom)/2,behavior:'instant'});+ });+}++async function checkTwoReferenceLayout(panel,mobile) {+ const layout = await panel.evaluate(el => {+ const rect = selector => el.querySelector(selector).getBoundingClientRect();+ const left = rect('.dock-materials'), prompt = rect('#tgPrompt'), row = rect('.tgen-row');+ return {+ sideBySide:left.right<=prompt.left, stacked:left.bottom<=prompt.top,+ belowRow:left.bottom-row.bottom, aboveRow:row.top-prompt.bottom,+ promptHeight:prompt.height, viewportFraction:el.getBoundingClientRect().height/innerHeight+ };+ });+ const measured = JSON.stringify(layout);+ if (mobile) {+ assert.ok(layout.stacked && layout.promptHeight<=96 && layout.viewportFraction<=0.5,measured);+ } else {+ assert.ok(layout.sideBySide && layout.belowRow<=16 && layout.aboveRow<=16,measured);+ }+}++async function check(browser, width, height, deviceScaleFactor) {+ const mobile = width < 800;+ const context = await browser.newContext({viewport:{width,height},+ deviceScaleFactor,isMobile:mobile,hasTouch:mobile,reducedMotion:'reduce',serviceWorkers:'block'});+ const page = await context.newPage();+ page.setDefaultTimeout(6000);+ const errors=[];+ page.on('pageerror',error => errors.push(error.message));+ const activate = el => mobile ? el.tap() : el.click();+ const panel = page.locator('#tray');+ const launcher = page.locator('#trayFab');+ try {+ await page.goto((process.env.U || 'http://127.0.0.1:8787')+'/#costume',{waitUntil:'domcontentloaded'});+ const outfits = page.locator('#grid .card[data-k^="c:"]');+ await outfits.first().waitFor();+ await launcher.waitFor();+ await activate(launcher);+ await panel.waitFor();+ assert.notEqual(await panel.getAttribute('aria-modal'),'true','the open dock hides the gallery from assistive technology');+ await scrollGallery(page,mobile);+ for (const index of [0,1,2]) {+ const primary = !mobile && index === 1;+ const pick = outfits.nth(index).locator(primary ? '[data-a=try]' : '[data-a=sel]');+ await reveal(pick);+ if (!mobile) await pick.hover();+ if (primary) assert.equal(await pick.innerText(),'加入工作台');+ await activate(pick);+ if (primary) {+ assert.equal(new URL(page.url()).hash,'#costume','the primary action left the current gallery');+ assert.equal(await pick.innerText(),'移出工作台');+ }+ if (index===1) await checkTwoReferenceLayout(panel,mobile);+ }+ assert.equal(await page.locator('#trayItems [data-k^="c:"]').count(),3);+ await page.locator('#tgPrompt').fill('Keep this edited studio draft.');+ await activate(page.locator('#libraryMenu summary'));+ await activate(page.locator('#libraryMenu [data-tab=pose]'));+ const pose = page.locator('#grid .card[data-k^="p:"]').first();+ await pose.waitFor();+ assert.ok(await panel.isVisible(),'switching collections closed the dock');+ const addPose = pose.locator('[data-a=sel]');+ await reveal(addPose);+ if (!mobile) await addPose.hover();+ await activate(addPose);+ const angle = pose.locator('[data-a=ang][data-i="1"]');+ await reveal(angle);+ await activate(angle);+ assert.equal(await angle.getAttribute('aria-pressed'),'true');+ const selected = await page.locator('#trayItems img').evaluateAll(imgs => imgs.map(img => img.src));+ assert.equal(selected.length,4);+ assert.equal(selected.at(-1),await pose.locator('img').evaluate(el => el.src),'the dock kept the previous angle');++ const photo = pose.locator('.phk');+ await reveal(photo);+ await activate(photo);+ await page.locator('#lb').waitFor();+ await page.waitForFunction(() => document.querySelector('#lb').contains(document.activeElement));+ if (mobile) await activate(page.locator('#lb .lb-x'));+ else await page.keyboard.press('Escape');+ await page.locator('#lb').waitFor({state:'hidden'});+ assert.ok(await photo.evaluate(el => el === document.activeElement),'lightbox did not return focus to the card');+ assert.ok(await panel.isVisible(),'closing the lightbox also closed the dock');+ assert.equal(await page.locator('#tgPrompt').inputValue(),'Keep this edited studio draft.');+ await page.keyboard.press('/');+ assert.equal(await page.evaluate(() => document.activeElement.id),'q');+ await page.keyboard.press('Escape');+ assert.ok(await panel.isVisible(),'a gallery keyboard shortcut closed the dock');+ await page.locator('#tgGo').focus();+ await page.keyboard.press('Tab');+ assert.ok(await panel.evaluate(el => !el.contains(document.activeElement)),'Tab stayed trapped in the dock');+ await page.locator('#trayMin').focus();+ await page.keyboard.press('Escape');+ assert.ok(await launcher.evaluate(el => el === document.activeElement));+ assert.deepEqual(await page.locator('#trayFilm img').evaluateAll(imgs => imgs.map(img => img.src)),selected.slice(-3));+ assert.equal(await page.locator('#trayFabN').innerText(),'4');+ await activate(launcher);+ await panel.waitFor();+ assert.deepEqual(await page.locator('#trayItems img').evaluateAll(imgs => imgs.map(img => img.src)),selected,+ 'reopening the panel lost selected references or their chosen angle');+ assert.equal(await page.locator('#tgPrompt').inputValue(),'Keep this edited studio draft.');+ assert.deepEqual(errors,[]);+ console.log('PASS '+width+'px @'+deviceScaleFactor+'x '+(mobile?'touch':'desktop')+' launcher, panel, browsing, angles, lightbox and keyboard');+ } finally { await context.close(); }+}++async function checkPosePair(browser) {+ const context = await browser.newContext({permissions:['clipboard-read','clipboard-write'],reducedMotion:'reduce',serviceWorkers:'block'});+ try {+ const page = await context.newPage();+ await page.goto((process.env.U || 'http://127.0.0.1:8787')+'/#pose',{waitUntil:'domcontentloaded'});+ await page.fill('#q','full_single_P052');+ const card = page.locator('#grid .card[data-k="p:full_single_P052"]');+ await card.locator('[data-a=ang]').filter({hasText:'侧面'}).click();+ await card.hover();+ await card.locator('[data-a=sel]').click();+ const other = await page.evaluate(async()=>{+ const keys=[];+ for(const type of ['costume','portrait']){+ const items=await APP.load(type), item=items.find(APP.ok);+ APP.toggleSel(item.k); keys.push(item.k);+ }+ return keys;+ });+ await page.click('#trayFab');+ const p='p:full_single_P052', d='d:full_single_P052';+ const addDepth=page.locator('#trayItems [data-pair="'+p+'"]');+ await addDepth.locator('..').hover();+ await addDepth.click();+ const keys=()=>page.locator('#trayItems [data-k]').evaluateAll(buttons=>buttons.map(b=>b.dataset.k));+ assert.deepEqual(await keys(),[p,d,...other]);+ assert.equal(await page.locator('#trayItems img[data-type=depth]').evaluate(i=>i.src.split('/').pop()),'full_single_P052_side.jpg');+ await page.click('#trayComboBox summary');+ await page.click('#trayCopyZh');+ const brief=await page.evaluate(()=>navigator.clipboard.readText());+ assert.ok(brief.includes('full_single_P052_side.webp')&&brief.includes('full_single_P052_side.png'));+ await page.click('#trayMin');+ assert.deepEqual(await page.locator('#trayFilm img').evaluateAll(imgs=>imgs.map(i=>i.dataset.type)),['pose','depth','portrait']);+ await page.reload({waitUntil:'domcontentloaded'});+ await page.click('#trayFab');+ await page.waitForFunction(()=>document.querySelectorAll('#trayItems [data-k]').length===4);+ assert.deepEqual(await keys(),[p,d,...other]);+ await page.locator('#trayItems [data-k="'+p+'"]').locator('..').hover();+ await page.locator('#trayItems [data-k="'+p+'"]').click();+ const addPose=page.locator('#trayItems [data-pair="'+d+'"]');+ await addPose.locator('..').hover(); await addPose.click();+ const restored = await keys();+ assert.equal(restored.indexOf(d),restored.indexOf(p)+1);+ assert.equal(await page.locator('#trayItems img[data-type=pose]').evaluate(i=>i.src.split('/').pop()),'full_single_P052_side.webp');+ console.log('PASS matching pose/depth references stay adjacent in the tray, filmstrip and clipboard, across reload and both add directions');+ } finally { await context.close(); }+}++(async () => {+ const browser = await chromium.launch({executablePath:process.env.CHROME_PATH});+ try {+ await checkPosePair(browser);+ for (const [width,height,scale] of [[1280,844,1],[1024,675,1.25],[390,844,3],[320,568,2]])+ await check(browser,width,height,scale);+ }+ finally { await browser.close(); }+})().catch(error => {console.error(error);process.exitCode=1;});diff --git a/tests/fixtures/site.js b/tests/fixtures/site.jsnew file mode 100644index 0000000..5870945--- /dev/null+++ b/tests/fixtures/site.js@@ -0,0 +1,19 @@+// Serve the real source UI with fixture catalogs. No preview process or network is needed.+const fs = require('node:fs');+const path = require('node:path');++const origin = 'http://posewear.test';+const source = path.resolve(__dirname, '../../src');++function serveSite(catalogs = {}) {+ return route => {+ const url = new URL(route.request().url());+ if (url.origin !== origin) return route.abort();+ const name = url.pathname.slice(1) || 'index.html';+ if (name.endsWith('.json')) return route.fulfill({json:catalogs[name] || []});+ const file = path.join(source,name);+ return fs.existsSync(file) ? route.fulfill({path:file}) : route.fulfill({status:404,body:''});+ };+}++module.exports = {origin, serveSite};diff --git a/tests/gallery-regressions.js b/tests/gallery-regressions.jsnew file mode 100644index 0000000..1749890--- /dev/null+++ b/tests/gallery-regressions.js@@ -0,0 +1,183 @@+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { chromium } = require('playwright');++const root = path.join(__dirname, '..', 'src');+const sample = { id:'sample', ti:'示例', zh:'示例', en:'sample', no:'1', cat:'示例分类',+ line:'全身', lineEn:'full body', t:'icon-192.png', m:'icon-192.png', i:'icon-192.png', o:'icon-192.png' };+const angles = ['正面', '侧面'].map((zh, i) => ({ ...sample, zh, en:['front view','side view'][i] }));+const data = {+ 'poses.json': [{ ...sample, angles }],+ 'costumes.json': Array.from({length:80}, (_, i) => ({...sample, id:'dress'+i})),+ 'props.json': [{ ...sample, ti:'木吉他', zh:'木吉他', en:'a wooden guitar', angles }],+ 'expressions.json': [{ ...sample, ti:'开心', emo:'开心', angles }]+};++async function run() {+ const browser = await chromium.launch({executablePath:process.env.CHROME_PATH});+ try {+ const ctx = await browser.newContext({reducedMotion:'reduce', serviceWorkers:'block', locale:'zh-CN'});+ const page = await ctx.newPage();+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ let failDepth;+ await page.route('**/*', route => {+ const url = new URL(route.request().url());+ if (url.hostname !== 'posewear.test') return route.abort();+ const file = url.pathname.slice(1) || 'index.html';+ if (file === 'depths.json') {+ failDepth = () => route.fulfill({status:503, body:''});+ return;+ }+ if (file.endsWith('.json')) return route.fulfill({json:data[file] || []});+ const source = path.join(root, file);+ if (fs.existsSync(source)) return route.fulfill({path:source});+ return route.fulfill({status:404, body:''});+ });+ await page.goto('http://posewear.test/#costume');+ const card = page.locator('#grid .card').first();+ await card.waitFor();+ const openImage = card.locator('.phk');+ await openImage.hover();+ assert.equal(await openImage.evaluate(el => getComputedStyle(el).backgroundColor), 'rgba(0, 0, 0, 0)');+ const library = page.locator('#libraryMenu summary');+ await library.press('ArrowDown');+ assert.equal(await page.evaluate(() => document.activeElement.dataset.tab),'pose');+ await page.keyboard.press('End');+ assert.equal(await page.evaluate(() => document.activeElement.dataset.tab),'furn');+ await page.keyboard.press('Escape');+ assert.ok(await library.evaluate(el => el === document.activeElement && !el.parentElement.open));+ await page.locator('.skip').press('Enter');+ assert.equal(await page.evaluate(() => location.hash), '#costume');+ assert.equal(await page.evaluate(() => document.activeElement.id), 'grid');++ await card.locator('.phk').press('Enter');+ await page.locator('#lbSide .acts [data-x=try]').press('Enter');+ await page.waitForFunction(() => APP.st.tab === 'studio' && WB._W.garments.length === 1);+ await page.locator('#libraryMenu summary').click();+ await page.locator('.tabs [data-tab=costume]').click();+ assert.ok(await page.locator('#trayFab').isVisible());++ await page.locator('#batchBtn').click();+ await page.locator('#bbar [data-b=all]').click();+ assert.equal(await page.locator('#bbN').textContent(), '已选 80');+ await page.locator('#bbar [data-b=x]').click();++ await page.locator('#libraryMenu summary').click();+ await Promise.all([page.waitForRequest('**/depths.json'),page.locator('.tabs [data-tab=depth]').click()]);+ await page.locator('#libraryMenu summary').click();+ await page.locator('.tabs [data-tab=expr]').click();+ await card.waitFor();+ assert.equal(typeof failDepth, 'function');+ await failDepth();+ await page.waitForFunction(() => document.querySelector('#grid .card')?.dataset.k === 'e:sample');+ await page.locator('#q').focus();+ await page.keyboard.press('Tab');+ await page.waitForTimeout(200); // The former input blur timer fired after 150 ms.+ assert.ok(await page.locator('#qsug').isVisible());+ assert.equal(await page.evaluate(() => document.activeElement.dataset.q), '开心');+ await page.keyboard.press('Enter');+ assert.equal(await page.evaluate(() => APP.st.tab), 'expr');+ await page.locator('#batchBtn').click();+ await card.locator('.phk').press('Enter');+ await page.locator('#bbar [data-b=stu]').click();+ await page.waitForFunction(() => APP.st.tab === 'studio' && WB._W.exprs.length === 1);+ assert.equal(await page.evaluate(() => WB._W.garments[0].k), 'c:dress0');++ await page.locator('#libraryMenu summary').click();+ await page.locator('.tabs [data-tab=prop]').click();+ await card.locator('[data-a=try]').press('Enter');+ await page.locator('#trayComboBox summary').click();+ assert.match(await page.locator('#trayText').innerText(), /木吉他/);+ await page.locator('[data-tl=en]').click();+ assert.match(await page.locator('#trayText').innerText(), /wooden guitar/);+ assert.equal(await page.evaluate(() => WB._W.garments[0].k), 'c:dress0');+ await page.getByRole('button', {name:'移除 木吉他'}).press('Enter');+ assert.equal(await page.locator('#trayItems button').count(), 0);+ await page.locator('#trayMin').click();+ await page.locator('#libraryMenu summary').click();+ await page.locator('.tabs [data-tab=pose]').click();+ await card.locator('[data-a=sel]').press('Enter');+ await card.locator('[data-a=ang][data-i="1"]').press('Enter');+ await page.locator('#trayFab').click();+ assert.match(await page.locator('#tgPrompt').inputValue(), /side profile|side view/);+ await page.locator('#tgPrompt').fill('手写描述');+ await page.locator('#trayMin').click();+ await card.locator('[data-a=ang][data-i="0"]').press('Enter');+ await page.locator('#trayFab').click();+ assert.equal(await page.locator('#tgPrompt').inputValue(), '手写描述');+ await page.locator('#trayMin').click();+ await page.locator('#noticeMenu summary').click();+ await page.locator('#help').click();+ await page.keyboard.press('r');+ assert.ok(await page.locator('#lb').isHidden());+ await page.keyboard.press('Escape');+ assert.equal(await page.evaluate(() => document.activeElement.parentNode.id), 'noticeMenu');++ await page.evaluate(async () => {+ const pic = await (await fetch('icon-192.png')).blob();+ for (const t of [1,2]) await WB.db.put({t, after:pic, mode:'gen', prompt:'历史样例 '+t, prov:'openai'});+ });+ await page.locator('#personalMenu summary').click();+ await page.locator('.tabs [data-tab=history]').click();+ const row = page.locator('.hist-card').first();+ await row.waitFor();+ await Promise.all([page.waitForEvent('download'),row.locator('[data-act=dl]').press('Enter')]);+ assert.ok(await page.locator('#lb').isHidden());+ await row.locator('.hopen').press('Enter');+ await page.locator('.lb-img').evaluate(el => {+ for (const [name, key, x] of [['touchstart','touches',200],['touchend','changedTouches',100]]) {+ const e = new Event(name);+ Object.defineProperty(e, key, {value:[{clientX:x,clientY:100}]});+ el.dispatchEvent(e);+ }+ });+ assert.match(await page.locator('#lbSide .mu').first().innerText(), /第 2 \/ 2 项/);+ assert.equal(await page.evaluate(() => location.hash), '#history');+ await page.keyboard.press('Escape');+ await page.locator('#adultSw').click();+ await page.locator('#ageY').click();+ assert.equal(await page.locator('#adultSw').getAttribute('aria-checked'), 'true');++ await page.evaluate(() => {+ localStorage.sel = JSON.stringify(['c:dress3']);+ localStorage.fav = JSON.stringify(['e:sample']);+ });+ await page.goto('about:blank');+ for (const hash of ['workbench/pose/sample','workbench/pose/sample','workbench']) {+ await page.goto('http://posewear.test/#'+hash);+ await page.locator('#tray').waitFor();+ await page.locator('#trayItems [data-k="c:dress3"]').waitFor();+ assert.ok(await page.locator('#trayItems [data-k="p:sample"]').isVisible());+ assert.deepEqual(await page.evaluate(() => APP.st.sel),['c:dress3','p:sample']);+ assert.deepEqual(await page.evaluate(() => [...APP.st.fav]),['e:sample']);+ await page.locator('#trayMin').click();+ }+ await page.goto('http://posewear.test/#costume');+ await card.waitFor();+ await page.locator('#q').fill('dress');+ await page.waitForFunction(()=>APP.st.q==='dress');+ await page.locator('#sort').selectOption('shuf');+ const deepCard=page.locator('#grid .card').nth(26);+ await deepCard.scrollIntoViewIfNeeded();+ await deepCard.hover();+ const order=await page.locator('#grid .card').evaluateAll(cards=>cards.slice(0,30).map(c=>c.dataset.k));+ const scroll=await page.evaluate(()=>scrollY);+ await deepCard.locator('[data-a=try]').click();+ await page.waitForURL('**/#studio');+ await page.goBack();+ await page.waitForFunction(()=>APP.st.tab==='costume'&&!document.querySelector('#grid').classList.contains('gbusy'));+ assert.equal(await page.locator('#q').inputValue(),'dress');+ assert.deepEqual(await page.locator('#grid .card').evaluateAll(cards=>cards.slice(0,30).map(c=>c.dataset.k)),order);+ assert.ok(Math.abs(await page.evaluate(()=>scrollY)-scroll)<50,'return to the same gallery row');+ await page.locator('#qx').click();+ await page.locator('#sort').selectOption('def');++ assert.deepEqual(errors, []);+ console.log('PASS gallery navigation, selection, keyboard and history regressions');+ } finally {+ await browser.close();+ }+}+run().catch(error => { console.error(error); process.exitCode = 1; });diff --git a/tests/local-engine-regressions.mjs b/tests/local-engine-regressions.mjsnew file mode 100644index 0000000..a7b6a98--- /dev/null+++ b/tests/local-engine-regressions.mjs@@ -0,0 +1,118 @@+import assert from 'node:assert/strict';+import http from 'node:http';+import { readFile } from 'node:fs/promises';+import { Readable } from 'node:stream';+import { localEngine, localRequest } from '../scripts/local-engine.mjs';++const bytes=await readFile(new URL('./fixtures/mk1.png',import.meta.url));+const events=[];+const models = ['base.safetensors','服饰/portrait v2.safetensors'];+let listed = models, submittedGraph;+const server=http.createServer(async(req,res)=>{+ events.push(req.url);+ const json=value=>res.writeHead(200,{'content-type':'application/json'}).end(JSON.stringify(value));+ if(req.url==='/v1/models')return json({data:[{id:'local'}]});+ if(req.url==='/system_stats')return json({system:{os:'fixture'}});+ if(req.url==='/object_info/CheckpointLoaderSimple')+ return json({CheckpointLoaderSimple:{input:{required:{ckpt_name:[listed,{tooltip:'checkpoint'}]}}}});+ if(req.url==='/upload/image'||req.url==='/v1/images/edits'){+ const form=await new Response(Readable.toWeb(req),{headers:req.headers}).formData();+ if(req.url==='/upload/image'){+ assert.deepEqual(Buffer.from(await form.get('image').arrayBuffer()),bytes);+ return json({name:'loaded.jpg',subfolder:'input-folder'});+ }+ assert.equal(form.get('prompt'),'reference test');+ for (const file of form.getAll('image[]'))assert.deepEqual(Buffer.from(await file.arrayBuffer()),bytes);+ assert.equal(form.getAll('image[]').length,2);+ return json({data:[{b64_json:bytes.toString('base64')}]});+ }+ if(req.url==='/v1/images/generations'){+ const data=await new Response(Readable.toWeb(req)).json(); assert.equal(data.prompt,'reference test');+ return json({data:[{b64_json:bytes.toString('base64')}]});+ }+ if(req.url==='/prompt'){+ const {prompt}=await new Response(Readable.toWeb(req)).json();+ submittedGraph = prompt;+ assert.equal(prompt['2'].inputs.image,'input-folder/loaded.jpg');+ assert.equal(prompt['3'].inputs.text,'reference test');+ return json({prompt_id:'job-1'});+ }+ if(req.url==='/history/job-1')return json({'job-1':{outputs:{'8':{images:[{filename:'output.png',type:'output'}]}}}});+ if(req.url.startsWith('/view?'))return res.writeHead(200,{'content-type':'image/png'}).end(bytes);+ res.writeHead(404).end();+});+await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));+const origin='http://127.0.0.1:'+server.address().port;+const preview='http://127.0.0.1:8787';+const request=(engine,method,refs=0,checkpoint,size)=>{+ const form=new FormData();form.set('prompt','reference test');+ if(checkpoint!==undefined)form.set('checkpoint',checkpoint);+ if(size!==undefined)form.set('size',size);+ for(let i=0;i<refs;i++)form.append('image[]',new Blob([bytes],{type:'image/png'}),'reference.png');+ return localRequest(engine,new Request(preview+'/api/local/'+(method==='GET'?'status':'generate'),{+ method,headers:{origin:preview,'x-posewear-local':'1'},body:method==='POST'?form:undefined}));+};+const preset = localEngine({POSEWEAR_LOCAL_URL:origin});+try{+ const defaults=localEngine({});+ assert.equal(defaults.name,'comfyui');+ assert.equal(defaults.origin,'http://127.0.0.1:8188');+ assert.equal(defaults.preset,true);+ assert.equal(localEngine({POSEWEAR_LOCAL_ENGINE:'off'}),null);+ assert.throws(()=>localEngine({POSEWEAR_LOCAL_URL:'https://remote.example'}),/loopback/);+ assert.deepEqual(events,[],'configuring the optional preset contacted an engine');+ for(const [method,headers] of [+ ['GET',{}],['POST',{'x-posewear-local':'1',origin:'https://other.example'}]+ ]){+ const path=method==='GET'?'status':'generate';+ assert.equal((await localRequest(preset,new Request(preview+'/api/local/'+path,{method,headers}))).status,403);+ }+ assert.deepEqual(events,[]);+ assert.deepEqual(await (await request(preset,'GET')).json(),{engine:'comfyui',checkpoints:models});+ assert.deepEqual(events,['/system_stats','/object_info/CheckpointLoaderSimple']);+ listed=[];+ assert.deepEqual(await (await request(preset,'GET')).json(),{engine:'comfyui',checkpoints:[]});+ listed=null;+ assert.equal((await request(preset,'GET')).status,502);+ listed=models;+ const before=events.length;+ assert.equal((await request(preset,'POST',1)).status,400);+ assert.equal((await request(preset,'POST',0,models[1])).status,400);+ assert.equal((await request(preset,'POST',2,models[1])).status,400);+ assert.equal((await request(preset,'POST',1,models[1],'portrait')).status,400);+ assert.equal(events.length,before,'invalid preset input uploaded files');+ for(const [name,size] of [[models[1],'576x1024'],[models[0],undefined]]) {+ const image=await request(preset,'POST',1,name,size);+ assert.equal(image.status,200);+ assert.deepEqual(Buffer.from(await image.arrayBuffer()),bytes);+ assert.equal(submittedGraph['1'].inputs.ckpt_name,name);+ if (size) {+ assert.deepEqual(submittedGraph['5'].inputs.pixels,['9',0]);+ assert.deepEqual(submittedGraph['9'],{class_type:'ImageScale',inputs:{image:['2',0],upscale_method:'lanczos',width:576,height:1024,crop:'center'}});+ } else {+ assert.deepEqual(submittedGraph['5'].inputs.pixels,['2',0]);+ assert.ok(!submittedGraph['9']);+ }+ }+ console.log('PASS preview preset model discovery, explicit selection and reference validation');+ for(const name of ['sd-cpp','comfyui']){+ const engine=localEngine({POSEWEAR_LOCAL_ENGINE:name,POSEWEAR_LOCAL_URL:origin,+ POSEWEAR_COMFY_WORKFLOW:new URL('../docs/comfyui/img2img-api.json',import.meta.url)});+ assert.equal(engine.preset,false);+ assert.deepEqual(await (await request(engine,'GET')).json(),{engine:name});+ const image=await request(engine,'POST',name==='comfyui'?1:2,name==='comfyui'?models[1]:undefined);+ assert.equal(image.status,200);+ assert.deepEqual(Buffer.from(await image.arrayBuffer()),bytes);+ if(name==='comfyui'){+ assert.equal(submittedGraph['1'].inputs.ckpt_name,'YOUR_CHECKPOINT.safetensors','custom workflow model changed');+ assert.equal((await request(engine,'POST',1,models[1],'576x1024')).status,502,'custom workflow still needs a size node');+ const previous=events.length;assert.equal((await request(engine,'POST',2)).status,502);assert.equal(events.length,previous);+ }else assert.equal((await request(engine,'POST')).status,200);+ console.log('PASS local '+name+' connection, submission and result');+ }+ assert.equal((await request(null,'GET')).status,404);+}finally{server.closeAllConnections();await new Promise(resolve=>server.close(resolve));}+const unavailable=await request(preset,'GET');+assert.equal(unavailable.status,503);+assert.ok((await unavailable.text()).includes('Start ComfyUI at '+origin));+console.log('PASS unavailable engine and disabled bridge have distinct HTTP responses');diff --git a/tests/local-workspace-regressions.mjs b/tests/local-workspace-regressions.mjsnew file mode 100644index 0000000..660f351--- /dev/null+++ b/tests/local-workspace-regressions.mjs@@ -0,0 +1,219 @@+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { once } from 'node:events';+import { readFile } from 'node:fs/promises';+import { createHash } from 'node:crypto';+import http from 'node:http';+import { createInterface } from 'node:readline';+import { Readable } from 'node:stream';+import { fileURLToPath } from 'node:url';+import { chromium } from 'playwright';+import { catalogNames } from '../scripts/catalog-source.mjs';++const input = fileURLToPath(new URL('./fixtures/person.png', import.meta.url));+const output = await readFile(new URL('./fixtures/mk1.png', import.meta.url));+const workflow = fileURLToPath(new URL('../docs/comfyui/img2img-api.json', import.meta.url));+const previewScript = fileURLToPath(new URL('../scripts/preview.mjs', import.meta.url));++const checkpoints = ['fashion/base.safetensors','wardrobe-v2.safetensors'];++async function check(browser, profile) {+ const standard = profile === 'default';+ const comfy = profile !== 'sd-cpp';+ const name = comfy ? 'ComfyUI' : 'sd.cpp';+ const prompt = 'A blue linen outfit, photographed in soft light.';+ const requests = [];+ let reachable = true;+ let receivedPrompt, uploadedImage, receivedCheckpoint, outputNode;+ const upstream = http.createServer(async (req,res) => {+ const json = value => res.writeHead(200,{'content-type':'application/json'}).end(JSON.stringify(value));+ const url = new URL(req.url, 'http://'+req.headers.host);+ const imageURL = url.origin + '/sample.png';+ const route = url.pathname;+ if (route === '/') return res.end('<script src="/app.js"></script>');+ if (route === '/app.js') return res.end(JSON.stringify(catalogNames.map(n => n+'.json')));+ if (route.endsWith('.json')) {+ const item = {id:'fixture', cat:'春季', ti:'蓝色外套', zh:'蓝色外套', en:'blue coat',+ line:'单人', lineEn:'solo', t:imageURL, m:imageURL, i:imageURL, o:imageURL};+ item.angles = route === '/poses.json' ? [{...item, zh:'正面', en:'front'}] : undefined;+ return json([item]);+ }+ if (route === '/sample.png') return res.writeHead(200,{'content-type':'image/png','access-control-allow-origin':'*'}).end(output);++ requests.push(route);+ if (!reachable) return res.writeHead(503).end('fixture engine is offline');+ if (route === '/object_info/CheckpointLoaderSimple') return json({+ CheckpointLoaderSimple:{input:{required:{ckpt_name:[checkpoints,{}]}}}+ });+ if (route === '/system_stats') return json({system:{os:'fixture'}});+ if (route === '/v1/models') return json({data:[{id:'fixture'}]});+ if (route === '/upload/image' || route === '/v1/images/edits') {+ const form = await new Response(Readable.toWeb(req),{headers:req.headers}).formData();+ const image = form.get(route === '/upload/image' ? 'image' : 'image[]');+ uploadedImage = image && {type:image.type, bytes:Buffer.from(await image.arrayBuffer())};+ if (route === '/upload/image') return json({name:'fixture.jpg'});+ receivedPrompt = form.get('prompt');+ return json({data:[{b64_json:output.toString('base64')}]});+ }+ if (route === '/prompt') {+ const {prompt:graph} = await new Response(Readable.toWeb(req)).json();+ const nodes = Object.entries(graph);+ receivedPrompt = nodes.find(([,node])=>node._meta?.title==='PoseWear Prompt')?.[1].inputs.text;+ receivedCheckpoint = nodes.find(([,node])=>node.class_type==='CheckpointLoaderSimple')?.[1].inputs.ckpt_name;+ outputNode = nodes.find(([,node])=>node._meta?.title==='PoseWear Output')?.[0];+ return json({prompt_id:'demo-job'});+ }+ if (route === '/history/demo-job') return json({'demo-job':{outputs:{[outputNode]:{images:[{filename:'result.png',type:'output'}]}}}});+ if (route === '/view') return res.writeHead(200,{'content-type':'image/png'}).end(output);+ res.writeHead(404).end();+ });+ upstream.listen(0,'127.0.0.1');+ await once(upstream,'listening');+ const origin = 'http://127.0.0.1:'+upstream.address().port;+ const env = {...process.env, PORT:'0', POSEWEAR_CATALOG_URL:origin, POSEWEAR_LOCAL_URL:origin};+ delete env.POSEWEAR_LOCAL_ENGINE;+ delete env.POSEWEAR_COMFY_WORKFLOW;+ if (!standard) env.POSEWEAR_LOCAL_ENGINE = comfy ? 'comfyui' : 'sd-cpp';+ if (profile === 'workflow') env.POSEWEAR_COMFY_WORKFLOW = workflow;+ const preview = spawn(process.execPath,[previewScript],{stdio:['ignore','pipe','inherit'],env});+ const context = await browser.newContext({serviceWorkers:'block',reducedMotion:'reduce',locale:'zh-CN'});+ try {+ const lines = createInterface({input:preview.stdout});+ const {value} = await lines[Symbol.asyncIterator]().next();+ const url = value?.match(/http:\/\/127\.0\.0\.1:\d+\//)?.[0];+ assert.ok(url, 'local preview started');+ const page = await context.newPage();+ const errors = [];+ page.on('pageerror', e => errors.push(e.message));+ await page.route('https://**', route => route.abort());+ await page.goto(url+'#studio');+ await page.locator('#wbCfg').click();+ const save = page.locator('#cfSave');+ const checkpoint = page.locator('#cfCheckpoint');+ const testConnection = page.locator('#cfTest');+ const status = page.locator('#cfMsg');+ if (standard) {+ assert.equal(await page.locator('[name=prov]:checked').inputValue(),'openai');+ assert.ok(await page.locator('#cfKey').isVisible());+ await page.locator('[name=prov][value=local]').check();+ assert.ok(await checkpoint.isVisible());+ assert.equal(await checkpoint.inputValue(),'');+ if (await save.isEnabled()) await save.click();+ assert.ok(await page.locator('#cfg').isVisible());+ assert.equal(await page.evaluate(()=>WB._cfg.prov),'openai');++ // An older local preset can lack a checkpoint. It still needs a model before generating.+ await page.evaluate(()=>localStorage.setItem('wbCfg',JSON.stringify({prov:'local',model:'',key:''})));+ await page.reload();+ await page.locator('#trayFab').click();+ await page.locator('#tgPrompt').fill('Missing checkpoint');+ await page.locator('#tgGo').click();+ await checkpoint.waitFor();+ assert.equal(await page.evaluate(()=>WB.configured()),false);+ assert.equal(requests.filter(r=>r==='/prompt'||r==='/upload/image').length,0);+ reachable = false;+ const [failure] = await Promise.all([+ page.waitForResponse(r=>r.url().endsWith('/api/local/status')),+ testConnection.click()+ ]);+ assert.ok(!failure.ok());+ await page.locator('#cfMsg.bad').waitFor();+ assert.doesNotMatch(await status.innerText(),/已连接/);+ assert.equal(await checkpoint.inputValue(),'');+ reachable = true;+ } else {+ assert.equal(await page.locator('[name=prov]:checked').inputValue(),'local');+ assert.ok(await checkpoint.isHidden());+ }+ assert.ok(await page.locator('#cfKey').isHidden());+ const [connection] = await Promise.all([+ page.waitForResponse(r=>r.url().endsWith('/api/local/status')),+ testConnection.click()+ ]);+ assert.ok(connection.ok());+ await status.filter({hasText:'已连接'}).waitFor();+ if (standard) {+ assert.deepEqual((await connection.json()).checkpoints,checkpoints);+ await checkpoint.locator('option').filter({hasText:checkpoints[1]}).waitFor({state:'attached'});+ assert.deepEqual(await checkpoint.locator('option').evaluateAll(options=>options.map(o=>o.value).filter(Boolean)), checkpoints);+ assert.equal(await checkpoint.inputValue(),'');+ if (await save.isEnabled()) await save.click();+ assert.ok(await page.locator('#cfg').isVisible());+ await checkpoint.selectOption(checkpoints[1]);+ }+ await save.click();+ if (standard) {+ assert.equal(await page.evaluate(()=>JSON.parse(localStorage.getItem('wbCfg')).checkpoint),checkpoints[1]);+ await page.locator('#trayMin').click();+ }+ let expectedReference;+ if (comfy) {+ await page.locator('[data-mode=gen]').click();+ await page.locator('#wbGFile').setInputFiles(input);+ await page.locator('#wbG .pick').waitFor();+ expectedReference = await page.evaluate(async()=>{+ const bytes = await crypto.subtle.digest('SHA-256',await WB._W.garments[0].blob.arrayBuffer());+ return [...new Uint8Array(bytes)].map(b=>b.toString(16).padStart(2,'0')).join('');+ });+ await page.locator('details.adv summary').click();+ await page.locator('#wbNeutral').uncheck();+ await page.locator('#wbPrompt').fill(prompt);+ await page.locator('#wbGo').click();+ await page.locator('#wbAfter[src^=blob]').waitFor();+ await page.locator('#personalMenu summary').click();+ await page.locator('.tabs [data-tab=history]').click();+ } else {+ await page.locator('#trayFab').click();+ assert.equal(await page.locator('#tgProv').textContent(),name);+ await page.locator('#tray [data-add=costume]').click();+ await page.locator('#pkG [data-k]').click();+ await page.locator('#pkDone').click();+ await page.locator('#tgPrompt').fill(prompt);+ await page.locator('#tgGo').click();+ await page.locator('#tgRes button').click();+ await page.locator('#tgViewImg[src^=blob]').waitFor();+ await page.locator('#tgHist').click();+ }+ const card = page.locator('#histGrid .hist-card');+ await card.waitFor();+ const recordedModel = standard ? checkpoints[1] : name;+ assert.ok((await card.innerText()).includes(recordedModel));+ await page.reload();+ await card.waitFor();+ const record = await page.evaluate(async () => {+ const [r] = await WB.db.hist();+ return {model:r.model, provider:r.prov, bytes:[...new Uint8Array(await r.after.arrayBuffer())]};+ });+ assert.equal(record.model,recordedModel);+ assert.equal(record.provider,'local');+ assert.deepEqual(Buffer.from(record.bytes),output);+ assert.ok(receivedPrompt?.includes(prompt));+ assert.equal(uploadedImage.type,'image/jpeg');+ if (comfy) {+ assert.equal(createHash('sha256').update(uploadedImage.bytes).digest('hex'),expectedReference);+ assert.equal(receivedPrompt,prompt);+ assert.equal(receivedCheckpoint, standard ? checkpoints[1] : 'YOUR_CHECKPOINT.safetensors');+ }+ assert.deepEqual(requests.filter(r=>!['/system_stats','/object_info/CheckpointLoaderSimple','/v1/models'].includes(r)),+ comfy ? ['/upload/image','/prompt','/history/demo-job','/view'] : ['/v1/images/edits']);+ assert.deepEqual(errors,[]);+ if (standard) console.log('PASS cloud default, local model required, failed connection, live checkpoint selection');+ console.log('PASS '+profile+' local preview, browser generation, displayed result and persisted history');+ } finally {+ await context.close();+ if (preview.exitCode === null && preview.signalCode === null) {+ const stopped = once(preview,'exit');+ preview.kill();+ await stopped;+ }+ upstream.closeAllConnections();+ await new Promise(resolve=>upstream.close(resolve));+ }+}++const browser = await chromium.launch({executablePath:process.env.CHROME_PATH});+try {+ for (const profile of ['default','workflow','sd-cpp']) await check(browser,profile);+} finally {+ await browser.close();+}diff --git a/tests/locale-regressions.js b/tests/locale-regressions.jsnew file mode 100644index 0000000..fee222d--- /dev/null+++ b/tests/locale-regressions.js@@ -0,0 +1,109 @@+const assert = require('node:assert/strict');+const {serveSite} = require('./fixtures/site');+const { chromium } = require('playwright');++const sample = {+ id:'test', ti:'收藏', zh:'收藏', en:'The original English prompt',+ cat:'春季', t:'icon-192.png', m:'icon-192.png', i:'icon-192.png', o:'icon-192.png',+};+const pose = {...sample, line:'全身', no:'1', angles:[{...sample, zh:'正面', en:'front view'}]};++const serve = serveSite({'poses.json':[pose], 'costumes.json':[sample]});++// A Locator click may scroll clipped controls into view. Test the touch target at its original coordinates.+async function tapVisible(page, selector) {+ const button = page.locator(selector);+ await button.waitFor();+ const rect = await button.boundingBox();+ const {width, height} = page.viewportSize();+ assert.ok(rect && rect.x >= 0 && rect.y >= 0 && rect.x+rect.width <= width+1 && rect.y+rect.height <= height+1,+ selector+' outside viewport: '+JSON.stringify(rect));+ const x = rect.x+rect.width/2, y = rect.y+rect.height/2;+ assert.ok(await button.evaluate((el, [x,y]) => el.contains(document.elementFromPoint(x,y)), [x,y]), selector+' is covered');+ await page.touchscreen.tap(x,y);+}++async function chooseLocale(page, value) {+ await page.locator('#languageMenu summary').tap();+ await page.locator('#uiLocale').selectOption(value);+ await page.locator('#languageMenu summary').tap();+}++async function run() {+ const browser = await chromium.launch({executablePath:process.env.CHROME_PATH});+ try {+ for (const [width,height] of [[320,568],[390,844]]) {+ const ctx = await browser.newContext({viewport:{width,height}, isMobile:true, hasTouch:true,+ reducedMotion:'reduce', serviceWorkers:'block'});+ const page = await ctx.newPage();+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.route('**/*',serve);+ await page.goto('http://posewear.test/#costume');+ const description = page.locator('.card .sub').first();+ await description.waitFor();+ assert.equal(await description.textContent(),sample.zh);+ assert.equal(await page.locator('#libraryMenu section').count(),4);+ assert.equal(await page.locator('#libraryMenu button[data-tab]').count(),12);+ await tapVisible(page,'#libraryMenu summary');+ await tapVisible(page,'#libraryMenu [data-tab=furn]');+ assert.equal(await page.evaluate(() => location.hash),'#furn');+ assert.equal(await page.locator('#libraryLabel').textContent(),'家具库');+ await tapVisible(page,'#libraryMenu summary');+ await tapVisible(page,'#libraryMenu [data-tab=costume]');+ await description.waitFor();+ await tapVisible(page,'#q');+ assert.ok((await page.locator('.top .search').boundingBox()).width >= width - 24);+ await tapVisible(page,'#qDone');+ // Switch directly between the library and notifications.+ await page.locator('#libraryMenu summary').tap();+ await tapVisible(page,'#noticeMenu summary');+ assert.ok(await page.locator('#releaseNotice').isVisible());+ assert.ok(await page.locator('#libraryMenu [data-tab=pose]').isHidden());+ await tapVisible(page,'#noticeMenu summary');+ assert.ok(await page.locator('#releaseNotice').isHidden());+ assert.equal(await page.locator('footer #credits').count(),1);+ assert.ok(await page.locator('.credit-list').isHidden());+ const nav = page.locator('.tabs [data-tab=studio]');+ for (const [locale,lang,label] of [['en','en','Studio'],['ja','ja','スタジオ'],['zh','zh-CN','工作台']]) {+ await chooseLocale(page,locale);+ assert.equal(await nav.innerText(),label);+ assert.equal(await description.textContent(),sample.zh);+ await page.reload();+ await description.waitFor();+ assert.equal(await page.locator('html').getAttribute('lang'),lang);+ assert.equal(await nav.innerText(),label);+ assert.equal(await description.textContent(),sample.zh);+ }+ await page.locator('#languageMenu summary').tap();+ await page.locator('[data-lang=en]').tap();+ await page.locator('#languageMenu summary').tap();+ await chooseLocale(page,'ja');+ assert.equal(await description.textContent(),sample.en);+ assert.equal(await page.locator('.card h3').first().textContent(),sample.ti);+ assert.equal(await page.locator('.card h3').first().getAttribute('title'),sample.ti);++ await chooseLocale(page,'en');+ await page.locator('#trayFab').tap();+ await page.locator('#tgPrompt').fill('保存 / 自分のプロンプト');+ await page.locator('#tgCfg').tap();+ await tapVisible(page,'#cfSave');+ await page.locator('#cfg').waitFor({state:'hidden'});+ await page.locator('#tray [data-add=pose]').tap();+ await page.locator('#pkG button').first().waitFor();+ await tapVisible(page,'#pkDone');+ await page.locator('#pk').waitFor({state:'hidden'});+ assert.equal(await page.locator('#tgPrompt').inputValue(),'保存 / 自分のプロンプト');+ await page.locator('#trayMin').tap();+ await nav.tap();+ await page.locator('details.adv > summary').tap();+ await page.locator('#wbExtra').fill('衣装 / 保持原文');+ await chooseLocale(page,'ja');+ assert.equal(await page.locator('#wbExtra').inputValue(),'衣装 / 保持原文');+ assert.deepEqual(errors, []);+ await ctx.close();+ console.log('PASS '+width+'px touch targets, locale persistence and independent prompts');+ }+ } finally { await browser.close(); }+}+run().catch(error => {console.error(error);process.exitCode=1;});diff --git a/tests/mcp-regressions.mjs b/tests/mcp-regressions.mjsnew file mode 100644index 0000000..9f9eed4--- /dev/null+++ b/tests/mcp-regressions.mjs@@ -0,0 +1,78 @@+// Exercise the real stdio transport against a self-contained, fingerprinted gallery.+import assert from 'node:assert/strict';+import http from 'node:http';+import { createHash } from 'node:crypto';+import { fileURLToPath } from 'node:url';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';+import { collections } from '../scripts/catalog-source.mjs';++const media = 'https://cdn.example/';+const site = 'https://gallery.example/';+const files = new Map();+const sample = {id:'look-one', ti:'蓝外套', zh:'蓝色外套', en:'blue jacket', cat:'春季',+ t:'c/t/coat.webp', m:'c/m/coat.webp', i:'c/i/coat.webp'};+for (const [type,{file}] of Object.entries(collections)) {+ let items = [];+ if (type === 'costume') items = [{...sample,id:'skirt',en:'light petticoat'},sample,{...sample,id:'outerwear',en:'wool coat'},{...sample,id:'hidden-only',a:1}];+ if (type === 'pose') items = [{id:'standing',zh:'站立',en:'standing',line:'单人',lineEn:'solo',+ angles:[{zh:'正面',en:'front',i:'p/i/front.webp'},{zh:'侧面',en:'side',i:'p/i/side.webp'}]}];+ if (type === 'hair') items = [{...sample,id:'H001', ext:1,+ angles:[{zh:'棕发',en:'brown',i:'https://charadb-2fi.pages.dev/img/H001.jpg'}]}];+ if (type === 'prop') items = [{id:'lute',ti:'琵琶',zh:'琵琶',en:'lute',o:'o/t/lute.webp'}];+ const body = JSON.stringify(type === 'depth' ? {items} : items);+ const hash = createHash('sha256').update(body).digest('hex').slice(0,10);+ files.set('/assets/'+file+'.'+hash+'.json',body);+}+const app = "const AH='"+media+"';\nconst urls="+JSON.stringify([...files.keys()])+';';+files.set('/assets/app.1234567890.js',app);+files.set('/','<link rel="canonical" href="'+site+'"><script src="/assets/app.1234567890.js" defer></script>');++const web = http.createServer((req,res) => {+ const body = files.get(req.url);+ res.writeHead(body === undefined ? 404 : 200).end(body);+});+await new Promise(resolve => web.listen(0,'127.0.0.1',resolve));+const script = fileURLToPath(new URL('../mcp/server.mjs',import.meta.url));+const client = new Client({name:'posewear-smoke',version:'1'});+const transport = new StdioClientTransport({command:process.execPath,args:[script],+ env:{POSEWEAR_CATALOG_URL:'http://127.0.0.1:'+web.address().port+'/'}});+async function call(name,args) {+ const response = await client.callTool({name:'posewear_'+name,arguments:args});+ assert(!response.isError,JSON.stringify(response.content));+ return response.structuredContent;+}+try {+ await client.connect(transport);+ assert.equal((await client.listTools()).tools.length,4);+ const {collections:list} = await call('list_collections',{});+ assert.equal(list.length,12);+ assert.equal(list.find(item => item.collection === 'costume').count,3);+ assert.equal(list.find(item => item.collection === 'depth').count,0);+ const found = await call('search_references',{query:'blue jacket',collection:'costume',limit:1});+ assert.equal(found.items[0].id,'look-one');+ assert.equal((await call('search_references',{query:'coat',limit:1})).items[0].id,'outerwear');+ const page2 = await call('search_references',{query:'',limit:1,offset:1});+ assert.equal(page2.nextOffset,2);+ assert.equal((await call('search_references',{query:'hidden-only'})).total,0);+ const side = {collection:'pose',id:'standing',angle:1};+ const pose = await call('get_reference',{...side,language:'en'});+ assert.equal(pose.angles[1].en,'side');+ assert.equal(pose.image.url,site+'p/i/side.webp');+ assert.match(pose.prompt,/side/);+ assert.equal(pose.page,site+'#pose/standing');+ const input = [side,{collection:'costume',id:'look-one'},{collection:'hair',id:'H001'},{collection:'prop',id:'lute'}];+ const handoff = await call('compose_brief',{references:input,prompt:'Keep this composition.',language:'en'});+ assert.deepEqual(handoff.references.map(image => image.url),[+ site+'p/i/side.webp',site+'c/m/coat.webp','https://charadb-2fi.pages.dev/img/H001.jpg',media+'o/t/lute.webp']);+ assert.match(handoff.brief,/^Keep this composition\.\n\nReference images/);+ for (const image of handoff.references) assert(handoff.brief.includes(image.url));+ for (const input of [{...side,angle:8},{collection:'costume',id:'hidden-only'}]) {+ const response = await client.callTool({name:'posewear_get_reference',arguments:input});+ assert.equal(response.isError,true);+ }+ console.log('PASS MCP stdio discovery, scoped search, pagination, views, source links and mixed briefs');+} finally {+ await client.close();+ await new Promise(resolve => web.close(resolve));+}diff --git a/tests/paired-pose-generation-regressions.js b/tests/paired-pose-generation-regressions.jsnew file mode 100644index 0000000..ee312af--- /dev/null+++ b/tests/paired-pose-generation-regressions.js@@ -0,0 +1,120 @@+// Check the prompt, number of jobs and actual multipart uploads together.+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const {chromium} = require('playwright');++(async () => {+ const base = new URL(process.env.U || 'http://localhost:8787');+ const browser = await chromium.launch({executablePath:process.env.CHROME_PATH});+ try {+ const page = await browser.newPage({serviceWorkers:'block',reducedMotion:'reduce'});+ const errors = [], requests = [];+ page.on('pageerror',error => errors.push(error.message));+ await page.addInitScript(() => {+ localStorage.wbMode = JSON.stringify('gen');+ localStorage.wbCfg = JSON.stringify({prov:'openai',key:'fixture-only',proxy:false});+ localStorage.wbNeutral = 'false';+ });+ const fixture = fs.readFileSync(path.join(__dirname,'fixtures/mk1.png'));+ await page.route('**/*', async route => {+ const req = route.request(), url = new URL(req.url());+ if (req.method() === 'POST') {+ assert.equal(url.origin,'https://api.openai.com');+ const form = await new Response(req.postDataBuffer(),{headers:{'content-type':req.headers()['content-type']}}).formData();+ requests.push({prompt:form.get('prompt'),images:form.getAll('image[]').length});+ return route.fulfill({json:{data:[{b64_json:fixture.toString('base64')}]}});+ }+ if (/\.(?:png|jpg|webp)$/.test(url.pathname)) {+ return route.fulfill({body:fixture,contentType:'image/png',headers:{'access-control-allow-origin':'*'}});+ }+ if (url.origin === base.origin) return route.continue();+ return route.abort();+ });+ await page.goto(base.href+'#studio');+ const [paired, distinct] = await page.evaluate(async () => {+ await WB.show();+ await Promise.all(['pose','depth','costume'].map(APP.load));+ const sketch=APP.DATA.pose.find(it=>!it.a && it.id==='full_single_P001');+ const depth=APP.DATA.depth.find(it=>it.id===sketch.id);+ const side=sketch.angles.findIndex(a=>a.zh==='侧面');+ const dSide=depth.angles.findIndex(a=>a.zh==='侧面');+ const front=sketch.angles.findIndex(a=>a.zh==='正面');+ const pair=[{k:depth.k,ai:dSide},{k:sketch.k,ai:side}];+ return [pair,[pair[0],{k:sketch.k,ai:front},pair[1]]];+ });++ async function select(poses) {+ await page.evaluate(poses => WB.setSel({garment:[APP.DATA.costume[0]],pose:poses}),poses);+ }+ await select(paired);+ assert.equal(await page.locator('#wbBatch').isHidden(),true);+ assert.equal(await page.locator('#wbEst').innerText(),'将生成 1 张');+ const getPrompt=(p,lang)=>page.evaluate(([refs,lang])=>WB.selectionPrompt({pose:refs},lang),[p,lang]);+ const zh=await getPrompt(paired,'zh'), en=await getPrompt(paired,'en');+ assert.match(zh,/第 1 张(深度图)+第 2 张(姿势线稿)对应同一动作和机位/);+ assert.match(en,/image 1 \(depth map\) \+ image 2 \(pose sketch\) together show the same pose/);+ assert.match(en,/depth map for near\/far relationships and occlusion/);+ assert.doesNotMatch(en,/panels/);+ assert.doesNotMatch(await getPrompt([paired[0]],'en'),/pose sketch|panels/);+ assert.doesNotMatch(await getPrompt([paired[1]],'zh'),/深度图|画 \d+ 格/);++ // Interleave another view between the two matching references.+ await select(distinct);+ assert.equal(await page.locator('#wbBatch').isVisible(),true);+ assert.equal(await page.locator('#wbEst').innerText(),'将生成 2 张');+ const sheet=await getPrompt(distinct,'en');+ assert.match(sheet,/draw 2 panels/);+ assert.match(sheet,/image 1 \(depth map\) \+ image 3 \(pose sketch\) together show the same pose/);++ await page.click('#wbGo');+ await page.waitForFunction(()=> !WB.busy() && WB._W.results.length===2);+ assert.deepEqual(requests.map(x=>x.images).sort(),[2,3]);+ const pairJob=requests.find(x=>x.images===3);+ assert.match(pairJob.prompt,/image 2 \(depth map\) \+ image 3 \(pose sketch\) together show the same pose/);+ assert.doesNotMatch(pairJob.prompt,/panels/);+ assert.deepEqual(await page.evaluate(()=>WB._W.results.find(r=>r.inputs.poses.length===2).inputs.poses),paired);+ const quick = await page.evaluate(async refs=>{+ const result=await WB.quick({selection:{pose:refs},lang:'en',n:1});+ return result.got.map(item=>({pose:item.inputs.poses,label:item.label}));+ },distinct);+ assert.deepEqual(quick.map(record=>record.pose),[distinct]);+ assert.match(quick[0].label,/侧面.*正面/);+ assert.equal(requests[2].images,3);+ assert.match(requests[2].prompt,/draw 2 panels/);++ const independent=await page.evaluate(refs=>{+ const depth=APP.ITEMS[refs[0].k];+ const key='d:independent-test';+ APP.ITEMS[key]={...depth,k:key,pack:'another-pack'};+ const prompt=WB.selectionPrompt({pose:[{k:key,ai:refs[0].ai},refs[1]]},'en');+ delete APP.ITEMS[key];+ return prompt;+ },paired);+ assert.match(independent,/draw 2 panels/);+ assert.doesNotMatch(independent,/together show the same pose/);+ const visibility=await page.evaluate(refs=>{+ // A previously saved selection may omit its angle index.+ const [depth,sketch]=refs.map(ref=>APP.ITEMS[ref.k]);+ const id='pair-visibility-test';+ const d={...depth,k:'d:'+id,id,ai:refs[0].ai};+ const p={...sketch,k:'p:'+id,id,ai:refs[1].ai,a:1};+ const previous=APP.st.adult;+ Object.assign(APP.ITEMS,{[d.k]:d,[p.k]:p});+ const stored={pose:[{k:p.k},{k:d.k}]};+ APP.st.adult=false;+ const plain=WB.selectionPrompt({pose:[{k:d.k}]},'en');+ const hiddenMate=APP.poseCounterpart(d,d.ai);+ APP.st.adult=true;+ const optedIn=WB.selectionPrompt(stored,'en');+ APP.st.adult=previous;+ delete APP.ITEMS[d.k]; delete APP.ITEMS[p.k];+ return {plain,hiddenMate,optedIn};+ },paired);+ assert.equal(visibility.hiddenMate,null);+ assert.doesNotMatch(visibility.plain,/pose sketch|panels/);+ assert.match(visibility.optedIn,/image 1 \(pose sketch\) \+ image 2 \(depth map\) together show the same pose/);+ assert.deepEqual(errors,[]);+ console.log('PASS paired sketch/depth roles, angle identity, image order and job counts');+ } finally { await browser.close(); }+})().catch(err=>{console.error(err);process.exitCode=1});diff --git a/tests/pose-pair-regressions.js b/tests/pose-pair-regressions.jsnew file mode 100644index 0000000..24e6545--- /dev/null+++ b/tests/pose-pair-regressions.js@@ -0,0 +1,261 @@+// Reordered views, colliding display numbers, restricted pairs and independent packs.+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { chromium } = require('playwright');++const src = path.resolve(__dirname, '../src');+const directions = {front:'正面', side:'侧面', top:'俯拍'};+function entry(type, id, views, extra = {}) {+ return {+ id, no:'P001', line:'全身', lineEn:'full body', cat:'站姿',+ zh:type+' '+id, en:type+' reference '+id, ja:id,+ ...(type === 'depth' ? {pack:'gia-depth',site:'https://example.test/'} : {}),+ angles:views.map(view => {+ const image = 'media/'+type+'/'+id+'/'+view;+ return {zh:directions[view], en:view, ja:view, t:image+'-thumb.png', i:image+'.png', o:image+'.png'};+ }),+ ...extra+ };+}+const paired = 'full_stand_P001', unpaired = 'unpaired_P001', gated = 'full_sexy_P001';+const extension = 'ext_P001', partial = 'partial_P001';+const pose = [+ entry('pose',paired,['front','side']), entry('pose',unpaired,['front']),+ entry('pose',gated,['front'],{a:1}), entry('pose',extension,['front']),+ entry('pose',partial,['front','top'])+];+const depth = [+ entry('depth',paired,['side','front']), entry('depth',gated,['front']),+ entry('depth',extension,['front'],{pack:'community'}), entry('depth',partial,['front'])+];+const site = 'http://posewear.test/';+const variant = (page,type) => page.locator('#lbPair [data-variant="'+type+'"]');+const card = (page,key) => page.locator('#grid [data-k="'+key+'"] .phk');++async function checkGalleryFaces(browser, serve) {+ for (const mobile of [false,true]) {+ const context=await browser.newContext({serviceWorkers:'block',locale:'zh-CN',reducedMotion:'reduce',+ hasTouch:mobile,isMobile:mobile,viewport:mobile?{width:390,height:844}:{width:1200,height:850}});+ await context.route('**/*',serve);+ await context.addInitScript(dark=>{+ if(dark)localStorage.theme='dark';+ Object.defineProperty(navigator,'clipboard',{value:{writeText:async text=>{window.lastCopied=text}}});+ },mobile);+ const page=await context.newPage(),errors=[];+ page.setDefaultTimeout(6000);+ page.on('pageerror',err=>errors.push(err.message));+ const origin=mobile?'depth':'pose',other=mobile?'pose':'depth',key=origin[0]+':'+paired;+ const row=page.locator('#grid .card[data-k="'+key+'"]');+ const flip=row.locator('button[data-a=flip]');+ const image=(type,view)=>row.locator('.ph img[src$="media/'+type+'/'+paired+'/'+view+'-thumb.png"]');+ await page.goto(site+'#'+origin);+ await flip.waitFor();+ const missing=mobile?[gated,extension]:[unpaired,extension];+ for (const id of missing) {+ assert.ok(await page.locator('#grid .card[data-k="'+origin[0]+':'+id+'"] .phk').isVisible());+ assert.equal(await page.locator('#grid .card[data-k="'+origin[0]+':'+id+'"] [data-a=flip]:visible').count(),0);+ }+ if (!mobile) {+ const incomplete=page.locator('#grid .card[data-k="p:'+partial+'"]');+ await incomplete.getByRole('button',{name:'俯拍',exact:true}).click();+ assert.equal(await incomplete.locator('[data-a=flip]:visible').count(),0);+ }+ await row.getByRole('button',{name:'侧面',exact:true}).click();+ const angles=await row.locator('.angs button').allTextContents();+ await image(origin,'side').waitFor();+ if (mobile) {+ assert.equal(await page.locator('html').getAttribute('data-theme'),'dark');+ assert.ok(await flip.evaluate(el=>getComputedStyle(el).opacity!=='0'));+ await flip.tap();+ } else {+ const target='**/media/depth/'+paired+'/side-thumb.png';+ const failed=page.waitForResponse(response=>response.url().endsWith('/depth/'+paired+'/side-thumb.png')&&response.status()===503);+ await page.route(target,route=>route.fulfill({status:503,body:''}),{times:1});+ await flip.press('Enter');+ await failed;+ await row.locator('button[data-a=flip]:not([aria-busy=true])').waitFor();+ assert.ok(await image(origin,'side').isVisible());+ const pending=page.waitForRequest(target);+ let release;+ const gate=new Promise(resolve=>{release=resolve});+ await page.route(target,async route=>{await gate;await route.fallback()});+ await flip.press('Enter');+ await pending;+ assert.equal(await flip.getAttribute('aria-busy'),'true');+ assert.ok(await image(origin,'side').evaluate(el=>el.complete&&el.naturalWidth>0&&getComputedStyle(el).opacity!=='0'));+ release();+ }+ await image(other,'side').waitFor();+ assert.deepEqual(await row.locator('.angs button').allTextContents(),angles);+ assert.equal(await row.getAttribute('data-show'),other[0]+':'+paired);+ assert.equal(await row.locator('.angs [aria-pressed=true]').textContent(),'侧面');+ assert.equal(await page.evaluate(()=>location.hash),'#'+origin);+ assert.ok(await page.locator('#lb').isHidden());+ if (!mobile) {+ assert.equal(await page.evaluate(()=>document.activeElement.dataset.a),'flip');+ await row.locator('[data-a=fav]').press('Enter');+ await row.locator('[data-a=sel]').press('Enter');+ assert.deepEqual(await page.evaluate(()=>[[...APP.st.fav],APP.st.sel]),[['d:'+paired],['d:'+paired]]);+ assert.equal(await row.locator('[data-a=fav]').getAttribute('aria-pressed'),'true');+ assert.equal(await row.locator('[data-a=sel]').getAttribute('aria-pressed'),'true');+ await row.locator('[data-a=copy]').press('Enter');+ assert.ok((await page.evaluate(()=>lastCopied)).includes('media/depth/'+paired+'/side.png'));+ await row.locator('.phk').click();+ assert.equal(await page.locator('#lbImg').getAttribute('data-src'),'media/depth/'+paired+'/side.png');+ await page.keyboard.press('Escape');+ await page.waitForFunction(()=>location.hash==='#pose'&&document.querySelector('#lb').hidden);+ await page.locator('#batchBtn').click();+ await row.locator('.phk').click();+ await page.evaluate(()=>{window.lastCopied=''});+ await page.locator('#bbar [data-b=cp]').click();+ assert.ok((await page.evaluate(()=>lastCopied)).includes('media/depth/'+paired+'/side.png'));+ await page.locator('#bbar [data-b=x]').click();+ }+ await row.getByRole('button',{name:'正面',exact:true}).click();+ if(mobile)await flip.tap();else await flip.press('Space');+ await image(origin,'front').waitFor();+ assert.equal(await row.locator('.angs [aria-pressed=true]').textContent(),'正面');+ assert.equal(await row.locator('[data-a=fav]').getAttribute('aria-pressed'),'false');+ assert.equal(await row.locator('[data-a=sel]').getAttribute('aria-pressed'),'false');+ assert.deepEqual(errors,[]);+ await context.close();+ }+ console.log('PASS gallery pose/depth flips in place with the same view, visible-face actions, keyboard and dark touch controls');+}++async function run(){+ const browser=await chromium.launch({executablePath:process.env.CHROME_PATH});+ try {+ const ctx=await browser.newContext({serviceWorkers:'block',reducedMotion:'reduce',locale:'zh-CN'});+ const errors=[],images=[];+ let releaseDepth, releaseImage;+ const depthGate=new Promise(resolve=>{releaseDepth=resolve});+ const imageGate=new Promise(resolve=>{releaseImage=resolve});+ const serve=async route=>{+ const url=new URL(route.request().url());+ if(url.hostname!=='posewear.test')return route.abort();+ const file=url.pathname.slice(1)||'index.html';+ if(file==='poses.json')return route.fulfill({json:pose});+ if(file==='depths.json'){await depthGate;return route.fulfill({json:{items:depth}})}+ if(file.endsWith('.json'))return route.fulfill({json:[]});+ if(file.startsWith('media/')){+ images.push([file,route.request().resourceType()]);+ if(file==='media/depth/'+paired+'/side.png')await imageGate;+ return route.fulfill({path:path.join(__dirname,'fixtures/mk1.png')});+ }+ const local=path.join(src,file);+ return fs.existsSync(local)?route.fulfill({path:local}):route.fulfill({status:404,body:''});+ };+ await ctx.route('**/*',serve);+ await ctx.addInitScript(()=>{+ Object.defineProperty(navigator,'clipboard',{value:{+ writeText:async text=>{window.lastCopied=text}+ }});+ });+ ctx.on('page',p=>p.on('pageerror',err=>errors.push(err.message)));+ const page=await ctx.newPage();+ const side=page.locator('#lbSide');+ await page.goto(site+'#pose');+ await card(page,'p:'+paired).click();+ await page.keyboard.press('ArrowRight');+ releaseDepth();+ await page.waitForFunction(()=>!!APP.DATA.depth);+ assert.equal(await side.locator('h2').textContent(),'pose '+unpaired);+ assert.equal(await side.locator('[data-variant]').count(),0);+ assert.equal(images.some(([src])=>src.startsWith('media/depth/')),false);++ await page.keyboard.press('ArrowLeft');+ await side.locator('[data-ai="1"]').click();+ await variant(page,'depth').press('Enter');+ assert.equal(await page.locator('#lbImg').getAttribute('data-src'),'media/depth/'+paired+'/side.png');+ assert.equal(await page.evaluate(()=>location.hash),'#depth/'+paired);+ assert.equal(await page.evaluate(()=>document.activeElement.dataset.variant),'depth');+ assert.deepEqual(await page.evaluate(()=>[APP.st.tab,APP.previewItem().ai]),['pose',0]);+ await variant(page,'pose').click();+ const delayed=page.waitForResponse(response=>response.url().endsWith('media/depth/'+paired+'/side.png'));+ releaseImage();+ await (await delayed).finished();+ await page.waitForFunction(()=>document.querySelector('#lbImg').src.endsWith('/pose/full_stand_P001/side.png'));+ await variant(page,'depth').click();+ await side.locator('[data-c=en]').click();+ await page.waitForFunction(()=>window.lastCopied?.includes('Reference images'));+ assert.match(await page.evaluate(()=>lastCopied),new RegExp('media/depth/'+paired+'/side.png'));+ await side.locator('.acts [data-x=sel]').click();+ await page.keyboard.press('f');+ assert.deepEqual(await page.evaluate(()=>[...APP.st.fav,...APP.st.sel]),['d:'+paired,'d:'+paired]);+ await page.keyboard.press('ArrowDown');+ await page.keyboard.press('s');+ const link=await page.evaluate(()=>lastCopied);+ assert.equal(new URL(link).hash,'#depth/'+paired+'/'+encodeURIComponent('正面'));+ await page.keyboard.press('Escape');+ await page.waitForFunction(()=>location.hash==='#pose'&&document.querySelector('#lb').hidden);+ assert.equal(await page.evaluate(()=>document.activeElement.closest('.card')?.dataset.k),'p:'+paired);++ // A shared view overrides this recipient's saved selection and restores their library on close.+ await page.evaluate(key=>{localStorage.ang=JSON.stringify({...JSON.parse(localStorage.ang),[key]:0})},'d:'+paired);+ const recipient=await ctx.newPage();+ await recipient.goto(link);+ await variant(recipient,'depth').waitFor();+ assert.equal(await recipient.locator('#lbImg').getAttribute('data-src'),'media/depth/'+paired+'/front.png');+ assert.equal(await recipient.evaluate(()=>APP.st.tab),'depth');+ await variant(recipient,'pose').click();+ assert.equal(await recipient.locator('#lbImg').getAttribute('data-src'),'media/pose/'+paired+'/front.png');+ const download=recipient.waitForEvent('download');+ await recipient.locator('#lbSide [data-x=dlx]').click();+ assert.equal((await download).suggestedFilename(),'posewear-pose-'+paired+'.webp');+ assert.ok(images.some(([src,type])=>src==='media/pose/'+paired+'/front.png'&&type==='fetch'));+ await recipient.keyboard.press('Escape');+ await recipient.waitForFunction(()=>location.hash==='#depth'&&document.querySelector('#lb').hidden);+ await card(recipient,'d:'+gated).click();+ assert.equal(await variant(recipient,'pose').count(),0);+ assert.equal(images.some(([src])=>src.includes('media/pose/'+gated+'/')),false);+ await recipient.keyboard.press('Escape');+ await card(recipient,'d:'+extension).click();+ assert.equal(await variant(recipient,'pose').count(),0);+ await recipient.close();++ await page.locator('#personalMenu summary').click();+ await page.locator('.tabs [data-tab=fav]').click();+ await card(page,'d:'+paired).click();+ await variant(page,'pose').click();+ await side.locator('.acts [data-x=fav]').click();+ await page.keyboard.press('Escape');+ await card(page,'p:'+paired).waitFor();+ assert.equal(await page.evaluate(()=>document.activeElement.closest('.card')?.dataset.k),'d:'+paired);+ await page.locator('#libraryMenu summary').click();+ await page.locator('.tabs [data-tab=pose]').click();+ await card(page,'p:'+extension).click();+ assert.equal(await variant(page,'depth').count(),0);+ await page.keyboard.press('Escape');+ await card(page,'p:'+partial).click();+ await variant(page,'depth').waitFor();+ await side.locator('[data-ai="1"]').click();+ assert.equal(await variant(page,'depth').count(),0);+ await side.locator('[data-ai="0"]').click();+ await page.keyboard.press('Escape');+ await page.locator('#personalMenu summary').click();+ await page.locator('.tabs [data-tab=recent]').click();+ await card(page,'p:'+partial).click();+ await variant(page,'depth').click();+ await page.keyboard.press('Escape');+ await card(page,'d:'+partial).waitFor();+ assert.equal(await page.evaluate(()=>document.activeElement.closest('.card')?.dataset.k),'p:'+partial);+ await page.locator('#libraryMenu summary').click();+ await page.locator('.tabs [data-tab=pose]').click();+ await page.locator('#adultSw').click();+ await page.locator('#ageY').click();+ await card(page,'p:'+gated).click();+ await variant(page,'depth').click();+ const settings=await ctx.newPage();+ await settings.goto(site+'#depth');+ await settings.locator('#adultSw').click();+ await page.locator('#lb').waitFor({state:'hidden'});+ assert.equal(await card(page,'p:'+gated).count(),0);+ assert.equal(await page.locator('#lbImg').getAttribute('src'),null);+ assert.deepEqual(errors,[]);+ console.log('PASS lightbox pose/depth: angle matching, actions, shared view, restrictions, independent packs, late catalog and image');+ await checkGalleryFaces(browser,serve);+ } finally {await browser.close()}+}+run().catch(err=>{console.error(err);process.exitCode=1});diff --git a/tests/pose-picker-regressions.js b/tests/pose-picker-regressions.jsnew file mode 100644index 0000000..b655d74--- /dev/null+++ b/tests/pose-picker-regressions.js@@ -0,0 +1,146 @@+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const {chromium} = require('playwright');++const source = path.join(__dirname,'..','src');+const labels = {正面:'front',侧面:'side',背面:'back'};+function reference(id,depth=false,gated=false) {+ const pose = {id,no:id.split('_').at(-1),ti:id,zh:id,en:id,cat:'立姿',line:'全身',lineEn:'full body',a:gated};+ if (depth) pose.pack='gia-depth';+ const views = depth?['正面','背面','侧面']:['正面','侧面','背面'];+ pose.angles = views.map(zh => {+ const file = '/icon-192.png?view='+labels[zh];+ return {zh,en:labels[zh],t:file,i:file,o:file};+ });+ return pose;+}+const id = n => 'full_single_P'+String(n).padStart(3,'0');+const ordered = ['upper80v2_P052',...Array.from({length:174},(_,i)=>id(i+1))];+const poses = [...ordered.map(key=>reference(key)),reference('private_line',false,true),reference('private_depth'),reference('only_line')];+const depths = [...[...ordered].reverse().map(key=>reference(key,true)),reference('private_line',true),reference('private_depth',true,true),reference('only_depth',true)];+const outfit = {id:'outfit',ti:'服装',zh:'服装',en:'outfit',cat:'服装',t:'/icon-192.png',m:'/icon-192.png',i:'/icon-192.png',o:'/icon-192.png'};+const catalogs = {'poses.json':poses,'depths.json':{items:depths},'costumes.json':[outfit]};+const card = (page,k) => page.locator('#pkG [data-k="'+k+'"]');+const variant = (page,type) => page.locator('#pkPoseTypes [data-pk-type='+type+']');+const materialKeys = page => page.locator('#pkG [data-k]').evaluateAll(cards=>cards.map(el=>el.dataset.k));+async function search(page,query) {+ const old = await page.locator('#pkG').evaluate(grid=>grid.firstElementChild?.outerHTML);+ await page.locator('#pkQ').fill(query);+ await page.waitForFunction(previous=>document.querySelector('#pkG').firstElementChild?.outerHTML!==previous,old);+}+async function check(browser,width) {+ const mobile=width<600;+ const context=await browser.newContext({viewport:{width,height:mobile?780:820},hasTouch:mobile,isMobile:mobile,reducedMotion:'reduce',serviceWorkers:'block'});+ const page=await context.newPage();+ page.setDefaultTimeout(6000);+ const errors=[];+ page.on('pageerror',error=>errors.push(error.message));+ try {+ await page.route('**/*', route=>{+ const url=new URL(route.request().url());+ if(url.hostname!=='posewear.test')return route.abort();+ const file=url.pathname.slice(1)||'index.html';+ if(file.endsWith('.json'))return route.fulfill({json:catalogs[file]||[]});+ const location=path.join(source,file);+ return fs.existsSync(location)?route.fulfill({path:location}):route.fulfill({status:404,body:''});+ });+ await page.addInitScript(locale=>localStorage.setItem('pwUiLocale',locale),mobile?'ja':'en');+ await page.goto('http://posewear.test/#pose');+ const sketchKey='p:'+id(52),depthKey='d:'+id(52);+ // Select a side view via the gallery, before adding the same reference in the picker.+ await page.locator('#q').fill(id(52));+ const galleryCard=page.locator('#grid .card[data-k="'+sketchKey+'"]');+ await galleryCard.locator('[data-a=ang][data-i="1"]').click();+ await page.locator('#trayFab').click();+ await page.locator('#tgPrompt').fill('保留我的提示词');+ const opener=page.locator('#tgAddRow [data-add=pose]');+ await opener.click();+ await card(page,sketchKey).waitFor();+ assert.deepEqual(await page.locator('#pkPoseTypes button').allInnerTexts(),mobile?['線画','深度画像']:['Line art','Depth map']);+ assert.deepEqual((await materialKeys(page)).slice(0,ordered.length),ordered.map(key=>'p:'+key));+ const farKey=id(165);+ await card(page,'p:'+farKey).scrollIntoViewIfNeeded();+ await card(page,'p:'+farKey).click();+ const offset=element=>element.getBoundingClientRect().top-document.querySelector('#pkG').getBoundingClientRect().top;+ const originalOffset=await card(page,'p:'+farKey).evaluate(offset);+ await variant(page,'depth').click();+ await card(page,'d:'+farKey).waitFor();+ assert.deepEqual((await materialKeys(page)).slice(0,ordered.length),ordered.map(key=>'d:'+key));+ assert.ok(Math.abs(await card(page,'d:'+farKey).evaluate(offset)-originalOffset)<=2);+ assert.equal(await card(page,'d:private_depth').count(),0);+ assert.equal(await card(page,'d:private_line').count(),1);+ assert.equal(await card(page,'d:only_depth').count(),1);+ await variant(page,'pose').click();+ await card(page,'p:'+farKey).click();+ assert.equal(await card(page,'p:private_line').count(),0);+ assert.equal(await card(page,'p:private_depth').count(),1);+ assert.equal(await card(page,'p:only_line').count(),1);++ await page.locator('#pkQ').fill('P052');+ await page.waitForFunction(()=>document.querySelectorAll('#pkG [data-k]').length===2);+ await card(page,sketchKey).click();+ assert.match(await card(page,sketchKey).locator('img').getAttribute('src'),/side$/);+ await variant(page,'depth').click();+ assert.equal(await page.locator('#pkQ').inputValue(),'P052');+ assert.deepEqual(await materialKeys(page),['d:upper80v2_P052',depthKey]);+ assert.match(await card(page,depthKey).locator('img').getAttribute('src'),/side$/);+ assert.match(await card(page,'d:upper80v2_P052').locator('img').getAttribute('src'),/front$/);+ await card(page,depthKey).click();+ await variant(page,'pose').click();+ assert.equal(await card(page,sketchKey).getAttribute('aria-pressed'),'true');+ await page.locator('#pkDone').click();+ assert.ok(await opener.evaluate(el=>document.activeElement===el));+ assert.deepEqual(await page.locator('#trayItems img').evaluateAll(images=>images.map(img=>[img.dataset.type,new URL(img.src).search])),[['pose','?view=side'],['depth','?view=side']]);+ assert.equal(await page.locator('#tgPrompt').inputValue(),'保留我的提示词');+ await page.locator('#trayMin').click();+ await page.locator('.tabs [data-tab=studio]').click();++ const studioOpener=page.locator('#studio .sh [data-pick=pose]');+ await page.locator('#wbPo .empty0').click();+ assert.equal(await page.locator('#pkT').innerText(),mobile?'ポーズ参考画像を選択(最大6枚)':'Choose up to 6 pose reference images');+ await variant(page,'depth').click();+ await card(page,depthKey).click();+ await page.keyboard.press('Escape');+ assert.ok(await studioOpener.evaluate(el=>document.activeElement===el));+ const angleSelect=page.locator('#wbPo [data-ang]');+ await angleSelect.selectOption('1'); // depth "back" at 1, line-art "back" at 2.+ await studioOpener.click();+ assert.match(await card(page,sketchKey).locator('img').getAttribute('src'),/back$/);+ await card(page,sketchKey).click();+ await variant(page,'depth').click();+ assert.equal(await card(page,depthKey).getAttribute('aria-pressed'),'true');+ for(const n of [1,2,3,4])await card(page,'d:'+id(n)).click();+ await card(page,'d:'+id(5)).click();+ assert.equal(await card(page,'d:'+id(5)).getAttribute('aria-pressed'),'false');+ assert.equal(await page.locator('#pkT').innerText(),mobile?'ポーズ参考画像(6/6枚)':'Pose reference images (6/6)');+ assert.equal(await page.locator('#toast').innerText(),mobile?'ポーズ参考画像は最大6枚です':'Choose up to 6 pose reference images');+ await page.locator('#pkDone').click();+ const selection=await page.evaluate(()=>({poses:WB._W.poses.map(ref=>[ref.k,ref.ai]),garments:WB._W.garments}));+ assert.deepEqual(selection.poses,[[depthKey,1],[sketchKey,2],...[1,2,3,4].map(n=>['d:'+id(n),0])]);+ assert.deepEqual(selection.garments,[]);+ assert.equal(await page.locator('#wbPo .pick').count(),6);+ await page.locator('#wbBoardCards [data-pick=depth]').first().click();+ assert.equal(await variant(page,'depth').getAttribute('aria-pressed'),'true');+ await search(page,'unmatched term');+ assert.equal(await page.locator('#pkG [data-k]').count(),0);+ await variant(page,'pose').click();+ assert.equal(await page.locator('#pkG [data-k]').count(),0);+ await page.locator('#pkX').click();++ await page.locator('#wbG .empty0').click();+ assert.ok(await page.locator('#pkPoseTypes').isHidden());+ await card(page,'c:outfit').click();+ assert.equal(await card(page,'c:outfit').getAttribute('aria-pressed'),'true');+ await page.locator('#pkDone').click();+ await page.locator('#pk').waitFor({state:'hidden'});+ assert.equal(await page.evaluate(()=>WB._W.garments[0].k),'c:outfit');+ assert.deepEqual(errors,[]);+ console.log('PASS '+width+'px paired pose picker ordering, scroll, search, gating, camera angles, limits and drafts');+ } finally { await context.close(); }+}+(async()=>{+ const browser=await chromium.launch({executablePath:process.env.CHROME_PATH});+ try { for(const width of [1100,390])await check(browser,width); }+ finally { await browser.close(); }+})().catch(error=>{console.error(error);process.exitCode=1});diff --git a/tests/provider-connection-regressions.js b/tests/provider-connection-regressions.jsnew file mode 100644index 0000000..894aca3--- /dev/null+++ b/tests/provider-connection-regressions.js@@ -0,0 +1,63 @@+// The API settings dialog must report the active endpoint's response, including failures.+const assert = require('node:assert/strict');+const { chromium } = require('playwright');+const {origin, serveSite} = require('./fixtures/site');++(async () => {+ const browser = await chromium.launch({executablePath:process.env.CHROME_PATH});+ try {+ const page = await browser.newPage({serviceWorkers:'block', locale:'zh-CN', reducedMotion:'reduce'});+ await page.route('**/*',serveSite());+ const requests = [];+ let response, release;+ const held = new Promise(resolve => { release = resolve; });+ await page.route('https://relay.example/**', async route => {+ const req = route.request();+ const headers = {'access-control-allow-origin':'*','access-control-allow-headers':'*','access-control-allow-methods':'GET,OPTIONS'};+ if (req.method() === 'OPTIONS') return route.fulfill({status:204,headers});+ requests.push({path:new URL(req.url()).pathname, key:req.headers()['x-goog-api-key']});+ const current = response;+ if (req.url().endsWith('/older-model')) await held;+ await route.fulfill({...current, headers}).catch(() => {});+ });+ await page.goto(origin+'/#studio');+ await page.click('#wbCfg');+ await page.locator('[name=prov][value=custom]').check();+ await page.fill('#cfBase','https://relay.example/v1beta');+ await page.fill('#cfKey','fixture-only');+ await page.selectOption('#cfProto','gemini');+ await page.fill('#cfModel','older-model');++ response={json:{name:'models/older-model'}};+ await Promise.all([+ page.waitForRequest(req=>req.method()==='GET' && req.url().endsWith('/models/older-model')),+ page.click('#cfTest')+ ]);+ await page.fill('#cfModel','current-model');+ response={contentType:'text/html',body:'<!doctype html><title>Gallery</title>'};+ await page.click('#cfTest');+ const error=page.locator('#cfMsg.bad');+ await error.filter({hasText:'接口未返回模型信息'}).waitFor();+ release();++ response={json:{name:'models/current-model',displayName:'Current'}};+ await page.click('#cfTest');+ await page.locator('#cfMsg.good').filter({hasText:'Current'}).waitFor();+ assert.deepEqual(requests.map(r=>r.path),[+ '/v1beta/models/older-model','/v1beta/models/current-model','/v1beta/models/current-model'+ ]);+ assert.ok(requests.every(r=>r.key==='fixture-only'));++ response={json:{data:[]}};+ await page.selectOption('#cfProto','json');+ await page.fill('#cfBase','https://relay.example/v1');+ await page.click('#cfTest');+ await page.locator('#cfMsg.good').filter({hasText:'共 0 个模型'}).waitFor();+ response={json:{data:[{}]}};+ await page.click('#cfTest');+ await error.filter({hasText:'接口未返回模型信息'}).waitFor();+ console.log('PASS custom Gemini path and authentication, stale check cancellation, invalid and empty model lists');+ } finally {+ await browser.close();+ }+})().catch(error=>{console.error(error);process.exitCode=1;});diff --git a/tests/reference-regressions.js b/tests/reference-regressions.jsnew file mode 100644index 0000000..3f72d57--- /dev/null+++ b/tests/reference-regressions.js@@ -0,0 +1,165 @@+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const {chromium} = require('playwright');++const source = path.resolve(__dirname,'../src');+const photo = path.join(__dirname,'fixtures/mk1.png');+const site = 'https://posewear.pages.dev/';+const outfit = {id:'coat',ti:'大衣',zh:'灰色大衣',en:'grey coat',cat:'外套',m:'c/m/coat.webp',i:'c/i/coat.webp',t:'c/t/coat.webp'};+const pose = {id:'turn',zh:'转身',en:'turning',line:'全身',lineEn:'full body',angles:[+ {zh:'正面',en:'front view',t:'p/t/front.webp',i:'p/i/front.webp',o:'p/o/front.webp'},+ {zh:'侧面',en:'side view',t:'p/t/side.webp',i:'p/i/side.webp',o:'p/o/side.webp'}+]};+const guitar={...outfit,id:'T001',ti:'木吉他',zh:'木吉他',en:'wooden guitar',cat:'乐器',+ angles:pose.angles.map(a=>({...a,t:a.t.replace('p/','t/'),i:a.i.replace('p/','t/')}))};+const room={...outfit,id:'room',ti:'客厅',zh:'客厅',en:'living room',cat:'室内',m:'s/m/room.webp'};+const catalogs = {'poses.json':[pose],'costumes.json':[outfit],'props.json':[guitar],'scenes.json':[room]};++async function run() {+ const browser=await chromium.launch({executablePath:process.env.CHROME_PATH});+ try {+ const context=await browser.newContext({permissions:['clipboard-read','clipboard-write'],serviceWorkers:'block',reducedMotion:'reduce',locale:'zh-CN'});+ await context.addInitScript(()=>{localStorage.lang=JSON.stringify('en')});+ const page=await context.newPage();+ const errors=[];+ page.on('pageerror',error=>errors.push(error.message));+ await page.route('**/*',route=>{+ const url=new URL(route.request().url());+ if(url.hostname!=='posewear.test')return route.abort();+ const name=url.pathname.slice(1)||'index.html';+ if(name.endsWith('.json'))return route.fulfill({json:catalogs[name]||[]});+ if(name.endsWith('.webp'))return route.fulfill({path:photo,contentType:'image/png'});+ const local=path.join(source,name);+ return fs.existsSync(local)?route.fulfill({path:local}):route.fulfill({status:404});+ });+ await page.goto('https://posewear.test/#pose');+ const card=page.locator('#grid .card').first();+ const clipboard=()=>page.evaluate(()=>navigator.clipboard.readText());+ async function copied(button) {+ await page.evaluate(()=>navigator.clipboard.writeText(''));+ await button.click();+ await page.waitForFunction(async()=>!!(await navigator.clipboard.readText()));+ return clipboard();+ }+ const side=site+'p/i/side.webp';+ await card.locator('[data-a=ang][data-i="1"]').click();+ assert.match(await copied(card.locator('[data-a=copy]')),/turning, full body, side view/);+ assert.ok((await clipboard()).includes(side));+ await card.locator('.phk').click();+ await page.keyboard.press('c');+ await page.waitForFunction(async()=> (await navigator.clipboard.readText()).includes('侧面'));+ assert.ok((await clipboard()).includes(side));+ await page.keyboard.press('Escape');+ await card.locator('[data-a=sel]').click();+ await page.locator('#libraryMenu summary').click();+ await page.locator('#libraryMenu [data-tab=costume]').click();+ await card.locator('[data-a=sel]').click();+ await page.locator('#trayFab').click();+ await page.locator('#trayComboBox summary').click();+ const mixed=await copied(page.locator('#trayCopyEn'));+ assert.deepEqual(mixed.match(/https:\/\/\S+/g),[side,site+outfit.m]);+ await page.locator('#tgPrompt').fill('Keep this exact wording.');+ await page.locator('#tgN').selectOption('3');+ await page.locator('#tgAR').selectOption('16:9');+ await page.reload();+ await page.locator('#trayFab').click();+ assert.equal(await page.locator('#tgN').inputValue(),'3');+ assert.equal(await page.locator('#tgAR').inputValue(),'16:9');+ const edited=await copied(page.locator('#tgCopyDraft'));+ assert.ok(edited.startsWith('Keep this exact wording.\n\n'));+ assert.deepEqual(edited.match(/https:\/\/\S+/g),[site+outfit.m,side]);+ await page.locator('#trayMin').click();+ await page.locator('#batchBtn').click();+ await card.locator('.phk').click();+ assert.ok((await copied(page.locator('[data-b=cp]'))).includes(site+outfit.m));+ await page.locator('[data-b=x]').click();+ await card.locator('[data-a=try]').click();+ await page.locator('#wbFile').setInputFiles(photo);+ await page.waitForFunction(()=>WB._W.persons.length===1);+ await page.locator('.adv summary').click();+ await page.locator('#wbPrompt').fill('keep my edit');+ const studio=await copied(page.locator('#wbCopyP'));+ assert.ok(studio.startsWith('keep my edit\n\n'));+ assert.match(studio,/(Image|图) 1 · (Attach|请另附)/);+ assert.match(studio,/(Image|图) 2 · /);+ assert.ok(studio.includes(site+outfit.m));+ assert.doesNotMatch(studio,/blob:|data:image|mk1\.png/);+ await page.locator('#wbExtra').fill('Side lighting');+ await page.locator('#wbN').selectOption('2');+ await page.locator('#wbAR').selectOption('3:4');+ await page.reload();+ await page.locator('#wbG .pick').waitFor();+ assert.equal(await page.locator('#wbPrompt').inputValue(),'keep my edit');+ assert.equal(await page.locator('#wbN').inputValue(),'2');+ assert.equal(await page.locator('#wbAR').inputValue(),'3:4');+ assert.equal(await page.locator('#wbExtra').inputValue(),'Side lighting');+ await page.locator('#wbReP').click();+ await page.reload();+ await page.locator('#wbG .pick').waitFor();+ assert.match(await page.locator('#wbPrompt').inputValue(),/Side lighting/);+ assert.doesNotMatch(await page.locator('#wbPrompt').inputValue(),/keep my edit/);+ await page.evaluate(async()=>{+ const after=await (await fetch('icon-192.png')).blob();+ await WB.db.put({t:1234,after,mode:'gen',prov:'openai',prompt:'saved draft',orig:'original draft',+ inputs:{persons:[],garments:[],poses:[{k:'p:turn',ai:1}],exprs:[],lang:'en'}});+ });+ await page.goto('https://posewear.test/#history');+ await page.reload();+ await page.locator('.hist-card .hopen').click();+ const saved=await copied(page.locator('[data-hlb=cp]'));+ assert.ok(saved.startsWith('saved draft\n\n'));+ assert.ok(saved.includes(side));+ await page.locator('#lbSide .raw summary').click();+ const original=await copied(page.locator('[data-hlb=cporig]'));+ assert.ok(original.startsWith('original draft\n\n'));+ assert.ok(original.includes(side));+ await page.keyboard.press('Escape');+ await page.locator('#languageMenu summary').click();+ await page.locator('#copyRefs').uncheck();+ await page.reload();+ await page.goto('https://posewear.test/#costume');+ assert.equal(await copied(card.locator('[data-a=copy]')),'grey coat');++ // Earlier versions could save a prop in the garment slot.+ await page.evaluate(()=>{+ localStorage.wbSel=JSON.stringify({g:['t:T001'],p:[],e:[]});+ localStorage.copyRefs='true';localStorage.sel='[]';+ history.replaceState(null,'','#studio');+ });+ await page.reload();+ const other=page.locator('#wbOther');+ await page.locator('#wbOtherCount').filter({hasText:'1'}).waitFor();+ assert.equal(await other.getAttribute('open'),null);+ assert.deepEqual(await page.locator('.primary-materials .sh b').allTextContents(),['人物','服装','姿势']);+ assert.equal(await page.locator('#wbG .pick').count(),0);+ assert.ok(await page.locator('#wbPrompt').isVisible());+ assert.ok(await page.locator('#wbGo').isEnabled());+ await other.locator('summary').click();+ await other.locator('[data-type=prop] select').selectOption('1');+ assert.ok((await copied(page.locator('#wbCopyP'))).includes(site+'t/i/side.webp'));+ await other.locator('[data-pick=scene]').click();+ await page.locator('#pkG [data-k="s:room"]').click();+ await page.locator('#pkDone').click();+ assert.deepEqual(await page.locator('#wbBoardCards .board-card').evaluateAll(els=>els.map(el=>el.dataset.type)),['prop','scene']);+ await page.reload();+ await other.locator('summary').click();+ await other.locator('.pick[data-type=scene] [data-rm]').click();+ assert.ok((await copied(page.locator('#wbCopyP'))).includes(site+'t/i/side.webp'));+ assert.doesNotMatch(await clipboard(),/s\/m\/room\.webp/);++ await page.locator('#trayFab').click();+ assert.deepEqual(await page.locator('#tgAddRow > [data-add]').evaluateAll(els=>els.map(el=>el.dataset.add)),['portrait','costume','pose']);+ await page.locator('#tgMore summary').click();+ await page.locator('#tgMore [data-add=scene]').click();+ await page.locator('#pkG [data-k="s:room"]').click();+ await page.locator('#pkDone').click();+ await page.locator('#tgStudio').click();+ await page.locator('#wbBoardCards [data-pk-key="s:room"]').waitFor();+ assert.ok((await copied(page.locator('#wbCopyP'))).includes(site+room.m));+ assert.ok(await page.locator('#wbGo').isEnabled());+ assert.deepEqual(errors,[]);+ console.log('PASS real clipboard: card, angle, lightbox, batch, mixed and edited workspaces, private upload positions, saved history and text-only preference');+ } finally {await browser.close()}+}+run().catch(error=>{console.error(error);process.exitCode=1});diff --git a/tests/run.mjs b/tests/run.mjsnew file mode 100644index 0000000..75a1f27--- /dev/null+++ b/tests/run.mjs@@ -0,0 +1,32 @@+import { readdirSync } from 'node:fs';+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';++const directory = new URL('./', import.meta.url);+// These suites serve source files and fixtures directly or start their own loopback server.+const offlineSuites = [+ 'gallery-regressions.js',+ 'locale-regressions.js',+ 'local-engine-regressions.mjs',+ 'local-workspace-regressions.mjs',+ 'mcp-regressions.mjs',+ 'pose-pair-regressions.js',+ 'pose-picker-regressions.js',+ 'provider-connection-regressions.js',+ 'reference-regressions.js',+ 'theme-regressions.js',+ 'v16-proxy.mjs',+];+const suites = process.argv.includes('--offline') ? offlineSuites : readdirSync(directory)+ .filter(name => /^v\d+(?:-.*)?\.m?js$/.test(name) || /-regressions\.(?:m?js|cjs)$/.test(name)).sort();+const failed = [];+for (const suite of suites) {+ console.log('\n'+suite);+ const result = spawnSync(process.execPath, [fileURLToPath(new URL(suite, directory))], {stdio:'inherit'});+ if (result.status !== 0) failed.push(suite);+}+console.log(`\n${suites.length - failed.length} / ${suites.length} suites passed`);+if (failed.length) {+ console.error('Failed suites: '+failed.join(', '));+ process.exitCode = 1;+}diff --git a/tests/studio-materials-regressions.js b/tests/studio-materials-regressions.jsnew file mode 100644index 0000000..b227ce4--- /dev/null+++ b/tests/studio-materials-regressions.js@@ -0,0 +1,74 @@+// Selected library items keep their category in the picker, reference board and saved workspace.+const assert = require('node:assert/strict');+const {chromium} = require('playwright');+const base = process.env.U || 'http://127.0.0.1:8787';++async function check(browser, width) {+ const mobile = width < 700;+ const ctx = await browser.newContext({+ viewport:{width,height:880},hasTouch:mobile,isMobile:mobile,reducedMotion:'reduce',serviceWorkers:'block'+ });+ try {+ await ctx.addInitScript(()=>{+ if (!sessionStorage.seeded) {+ localStorage.wbSel=JSON.stringify({g:['t:T001']});+ sessionStorage.seeded='1';+ }+ });+ const page=await ctx.newPage(),errors=[];+ page.on('pageerror',error=>errors.push(error.message));+ await page.goto(base+'/#studio');+ const board=page.locator('#wbBoardCards'),extras=page.locator('#wbOther'),picker=page.locator('#pk');+ await board.locator('[data-pk-key="t:T001"]').waitFor();+ assert.deepEqual(await page.locator('.primary-materials .sh b').allTextContents(),['人物','服装','姿势']);+ assert.equal(await extras.getAttribute('open'),null);+ assert.equal(await page.locator('#wbOtherCount').textContent(),'1');+ assert.equal(await page.locator('#wbG .pick').count(),0);+ assert.equal(await board.locator('[data-pk-key="t:T001"] span').textContent(),'道具');+ assert.equal(await page.locator('#wbGo').isEnabled(),true);+ assert.equal(await page.locator('#wbPrompt').isVisible(),true);+ await extras.locator('summary').click();+ const guitar=extras.locator('.pick[data-type="prop"]');+ assert.match(await guitar.textContent(),/木吉他.*道具.*T001/);+ const angle=guitar.locator('select');+ await angle.selectOption({index:1});+ const changedSrc=await board.locator('[data-pk-key="t:T001"] img').getAttribute('src');+ assert.equal(await guitar.locator('img').getAttribute('src'),changedSrc);+ await extras.locator('[data-pick=expr]').click();+ const kinds=picker.locator('#pkMaterialTypes [data-pk-material]');+ assert.deepEqual(await kinds.evaluateAll(els=>els.map(el=>el.dataset.pkMaterial)),+ ['expr','hair','scene','light','prop','furn']);+ await picker.locator('#pkG button').first().click();+ await picker.locator('[data-pk-material=prop]').click();+ await picker.locator('#pkG [data-k="t:T001"][aria-pressed=true]').waitFor();+ await picker.locator('#pkG [data-k="t:T002"]').click();+ await picker.locator('#pkDone').click();+ assert.equal(await page.locator('#wbOtherCount').textContent(),'3');+ assert.equal(await board.locator('[data-type=prop]').count(),2);+ assert.equal(await board.locator('[data-type=expr]').count(),1);+ await page.reload();+ await board.locator('[data-pk-key="t:T002"]').waitFor();+ assert.equal(await board.locator('[data-pk-key="t:T001"] img').getAttribute('src'),changedSrc);+ await extras.locator('summary').click();+ await extras.locator('.pick[data-type=expr] [data-rm]').click();+ const open=page.locator('#wbG .empty0');+ await open.click();+ assert.deepEqual(await kinds.evaluateAll(els=>els.map(el=>el.dataset.pkMaterial)),['costume','anime','dyn']);+ await picker.locator('[data-pk-material=dyn]').click();+ await picker.locator('#pkG button.dyn').first().click();+ await picker.locator('#pkDone').click();+ await page.locator('#wbG .pick[data-type=dyn]').waitFor();+ assert.equal(await board.locator('[data-type=dyn] span').textContent(),'历代服饰');+ // A mode change cannot erase a manually edited brief.+ const prompt=page.locator('#wbPrompt');+ await prompt.fill('Draw the guitar under soft lighting.');+ await page.locator('[data-mode=gen]').click();+ assert.equal(await prompt.inputValue(),'Draw the guitar under soft lighting.');+ assert.deepEqual(errors,[]);+ console.log('PASS '+width+'px studio material groups, migrated guitar, saved angle, picker tabs, board and draft');+ } finally {await ctx.close()}+}+(async()=>{+ const browser=await chromium.launch({executablePath:process.env.CHROME_PATH});+ try {for(const width of [1280,390])await check(browser,width)} finally {await browser.close()}+})().catch(error=>{console.error(error);process.exitCode=1});diff --git a/tests/studio-regressions.js b/tests/studio-regressions.jsnew file mode 100644index 0000000..22c890c--- /dev/null+++ b/tests/studio-regressions.js@@ -0,0 +1,203 @@+// The browser drives the same workbench used in production. Every provider request is intercepted.+const assert = require('node:assert/strict');+const path = require('node:path');+const fs = require('node:fs');+const { chromium } = require('playwright');++(async () => {+ const base = process.env.U || 'http://localhost:8787';+ const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH });+ try {+ const context = await browser.newContext({ serviceWorkers: 'block', reducedMotion: 'reduce' });+ const page = await context.newPage();+ const fixture = fs.readFileSync(path.join(__dirname, 'fixtures', 'mk1.png'));+ const hits = [], errors = [], imageRequests = [];+ let failNext = false, rejectInput = false, heldImage;+ page.on('pageerror', error => errors.push(error.message));+ await page.addInitScript(() => {+ if (sessionStorage.studioTest) return;+ sessionStorage.studioTest = '1';+ localStorage.wbCfg = JSON.stringify({ prov: 'openai', key: 'fixture-only', proxy: false });+ localStorage.wbNeutral = 'false';+ localStorage.introX = '1';+ });+ await page.route('**/*', async route => {+ const request = route.request(), url = new URL(request.url());+ if (request.method() === 'POST') {+ assert.equal(url.hostname, 'api.openai.com');+ const type=request.headers()['content-type'];+ const form=type.includes('multipart')?await new Response(request.postDataBuffer(),{headers:{'content-type':type}}).formData():null;+ const refs=form?form.getAll('image[]'):[];+ const prompt=form?form.get('prompt'):request.postDataJSON().prompt;+ assert.ok(refs.every(file=>file.size>0&&file.type==='image/jpeg'));+ hits.push({refs:refs.length,edited:prompt.includes('EDITED_MARKER'),prompt,path:url.pathname});+ if (rejectInput) {+ rejectInput=false;+ return route.fulfill({status:400,json:{error:{code:'moderation_blocked',message:'Blocked by the safety system'}}});+ }+ if (failNext) {+ failNext = false;+ return route.fulfill({ status: 429, json: { error: { message: 'mock limit' } } });+ }+ return route.fulfill({ json: { data: [{ b64_json: fixture.toString('base64') }] } });+ }+ if (request.method() === 'OPTIONS') {+ return route.fulfill({ status: 204, headers: {+ 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET,POST',+ 'access-control-allow-headers': '*'+ } });+ }+ if (/\.webp$/.test(url.pathname)) {+ imageRequests.push(url.pathname);+ if (heldImage && url.pathname === heldImage.pathname) {+ heldImage.started();+ await heldImage.wait;+ }+ return route.fulfill({ body: fixture, contentType: 'image/png', headers: { 'access-control-allow-origin': '*' } }).catch(() => {});+ }+ if (url.origin === new URL(base).origin) return route.continue();+ return route.abort();+ });+ await page.goto(base + '/#studio');+ await page.waitForFunction(() => window.WB && window.APP);+ await page.evaluate(async () => {+ await Promise.all(['costume', 'pose', 'prop', 'portrait'].map(t => APP.load(t)));+ await WB.show();+ });++ assert.equal(await page.locator('[data-mode=gen]').getAttribute('aria-pressed'),'true');+ await page.click('#wbCfg');+ await page.locator('[name=prov][value=gemini]').check();+ assert.equal(await page.inputValue('#cfKey'), '');+ await page.fill('#cfBase', 'http://example.test');+ await page.click('#cfSave');+ assert.match(await page.locator('#cfMsg').textContent(), /HTTPS/);+ await page.click('#cfgX');+ assert.equal(await page.evaluate(() => WB._cfg.prov), 'openai');++ await page.setInputFiles('#wbFile', path.join(__dirname, 'fixtures', 'person.png'));+ await page.waitForFunction(() => WB._W.persons.length === 1);+ const firstQuick = await page.evaluate(async () => {+ const groups = { pose: APP.DATA.pose.slice(0, 2) };+ WB.selectionPrompt(groups);+ const r = await WB.quick({ selection: groups, n: 1 });+ return [WB._W.persons.length, r.got.length, r.got[0]?.before === null];+ });+ assert.deepEqual(firstQuick, [1, 1, true]);+ assert.equal(hits.length, 1);+ assert.equal(hits[0].refs, 2);++ const posePath = await page.evaluate(() => new URL(APP.DATA.pose[2].angles[0].i, location.href).pathname);+ let release, started;+ const reached = new Promise(resolve => { started = resolve; });+ heldImage = { pathname: posePath, started, wait: new Promise(resolve => { release = resolve; }) };+ const cancelled = page.evaluate(async () => {+ const r = await WB.quick({ selection: { pose: [APP.DATA.pose[2]] }, n: 1 });+ return r.cancelled && r.got.length === 0;+ });+ await Promise.race([reached, page.waitForTimeout(10000).then(() => { throw Error('Pose image request did not start'); })]);+ await page.evaluate(() => WB.stop());+ release();+ assert.equal(await cancelled, true);+ assert.equal(hits.length, 1);+ heldImage = null;++ await page.evaluate(async () => {+ await WB.setSel({ garment: APP.DATA.costume.slice(0, 2), pose: APP.DATA.pose.slice(0, 2) });+ const prompt = document.querySelector('#wbPrompt');+ prompt.value = 'Use EDITED_MARKER in every picture';+ prompt.dispatchEvent(new Event('input'));+ });+ assert.equal(await page.locator('[data-mode=tryon]').getAttribute('aria-pressed'),'true');+ failNext = true;+ await page.click('#wbGo');+ await page.waitForSelector('#wbRetry');+ assert.equal(hits.length, 3);+ assert.ok(hits.slice(1).every(x => x.edited && x.refs === 4));+ await page.click('#wbRetry');+ await page.waitForFunction(() => !WB.busy() && WB._W.results.length === 2);+ assert.equal(hits.length, 4);+ assert.ok(hits[3].edited);++ await page.reload();+ await page.waitForFunction(() => window.WB && WB._W.garments.length === 2);+ assert.equal(await page.locator('#wbPrompt').inputValue(),'Use EDITED_MARKER in every picture');+ const legacy = await page.evaluate(async () => {+ const fresh = (await WB.db.hist()).find(r => r.inputs.garments.length === 2);+ await WB.restoreRecord(fresh);+ const count = WB._W.garments.length;+ await WB.restoreRecord({ mode: 'gen', before: null, prompt: 'old prompt' });+ return { count, oldPersons: WB._W.persons.length, prompt: document.querySelector('#wbPrompt').value };+ });+ assert.deepEqual(legacy, { count: 2, oldPersons: 0, prompt: 'old prompt' });+ const unsaved = await page.evaluate(async () => {+ const before = (await WB.db.hist()).length;+ const original = IDBObjectStore.prototype.put;+ IDBObjectStore.prototype.put = () => { throw new DOMException('mock quota', 'QuotaExceededError'); };+ try {+ const r = await WB.quick({ selection: { garment: APP.DATA.costume.slice(0, 1) }, n: 1 });+ return [before === (await WB.db.hist()).length, r.got.length, r.unsaved, r.warns.length > 0];+ } finally { IDBObjectStore.prototype.put = original; }+ });+ assert.deepEqual(unsaved, [true, 1, 1, true]);++ // The default studio can start from a single prop with no implicit person or outfit.+ await page.evaluate(()=>{+ localStorage.removeItem('wbDraft'); // A legacy installation has selections, but no saved editor draft.+ localStorage.wbMode=JSON.stringify('tryon');+ localStorage.wbNeutral='true';+ localStorage.wbSel=JSON.stringify({g:['t:T001']});+ });+ await page.reload();+ await page.waitForFunction(()=>window.WB?._W.extraRefs[0]?.k==='t:T001');+ assert.deepEqual(await page.evaluate(()=>WB._W.garments),[]);+ assert.equal(await page.locator('[data-mode=tryon]').getAttribute('aria-pressed'),'true');+ assert.equal(await page.locator('#wbGo').isEnabled(),true);+ await page.click('#wbGo');+ await page.waitForFunction(()=>!WB.busy()&&WB._W.results.length===1);+ const prop=hits.at(-1);+ assert.equal(prop.path,'/v1/images/edits');+ assert.equal(prop.refs,1);+ assert.match(prop.prompt,/Prop \(image 1\):.*acoustic guitar/i);+ assert.doesNotMatch(prop.prompt,/fashion|mannequin|east asian|try-on/i);+ const stored=await page.evaluate(()=>WB._W.results[0].inputs.extraRefs);+ assert.deepEqual(stored,[{k:'t:T001',ai:0}]);+ rejectInput=true;+ await page.click('#wbGo');+ await page.locator('#wbErr [data-ef=prompt]').click();+ assert.equal(await page.evaluate(()=>document.activeElement.id),'wbPrompt');+ assert.equal(await page.locator('#wbErr [data-ef=cos]').count(),0);+ const mixed=await page.evaluate(async()=>{+ const prop=APP.ITEMS['t:T001'],pose=APP.DATA.pose[0];+ const result=await WB.quick({selection:{pose:[pose],extra:[{k:prop.k,ai:1}]},n:1,lang:'en'});+ return {ref:prop.angles[1].i,view:prop.angles[1].en,record:result.got[0].inputs.extraRefs};+ });+ assert.ok(imageRequests.includes(new URL(mixed.ref,base).pathname));+ assert.equal(hits.at(-1).refs,2);+ assert.match(hits.at(-1).prompt,/Prop \(image 2\)/);+ assert.ok(hits.at(-1).prompt.includes(mixed.view));+ assert.deepEqual(mixed.record,[{k:'t:T001',ai:1}]);++ await page.evaluate(()=>WB.setSel({}));+ assert.equal(await page.inputValue('#wbPrompt'),'');+ assert.ok(await page.locator('#wbGo').isDisabled());+ const total=hits.length;+ const empty=await page.evaluate(async()=>{const r=await WB.quick({selection:{},prompt:' '});return r.errs.length});+ assert.equal(empty,1);+ assert.equal(hits.length,total);+ const note='A single ceramic vase, white background.';+ await page.locator('#wbPrompt').fill(note);+ await page.click('#wbGo');+ await page.waitForFunction(note=>!WB.busy()&&WB._W.results[0]?.prompt===note,note);+ assert.deepEqual(hits.at(-1),{refs:0,edited:false,prompt:note,path:'/v1/images/generations'});+ await page.evaluate(()=>WB.setSel({}));+ await page.locator('[data-mode=gen]').click();+ await page.locator('#wbChar summary').click();+ await page.locator('[data-char=custom]').click();+ await page.locator('#wbCharTxt').fill('A silver-haired cellist.');+ assert.equal(await page.inputValue('#wbPrompt'),'A silver-haired cellist.');+ assert.ok(await page.locator('#wbGo').isEnabled());+ assert.deepEqual(errors, []);+ console.log('PASS studio config, isolated tray, cancellation, edited prompts, partial retry, draft restore, history, optional materials, selected image views and text-only generation');+ } finally { await browser.close(); }+})().catch(error => { console.error(error); process.exitCode = 1; });diff --git a/tests/theme-regressions.js b/tests/theme-regressions.jsnew file mode 100644index 0000000..25b6e9b--- /dev/null+++ b/tests/theme-regressions.js@@ -0,0 +1,81 @@+// First paint, live OS changes, explicit choices, and keyboard/touch interaction.+const assert = require('node:assert/strict');+const {origin, serveSite} = require('./fixtures/site');+const {chromium} = require('playwright');++async function expectTheme(page, palette) {+ await page.waitForFunction(expected => document.documentElement.dataset.theme === expected, palette);+ const colors = await page.evaluate(() => [+ getComputedStyle(document.documentElement).colorScheme,+ document.querySelector('meta[name="theme-color"]').content+ ]);+ assert.deepEqual(colors, [palette, palette === 'dark' ? '#111111' : '#ffffff']);+}++async function run() {+ const browser = await chromium.launch({executablePath:process.env.CHROME_PATH});+ try {+ const desktop = await browser.newContext({colorScheme:'dark',serviceWorkers:'block'});+ await desktop.route('**/*',serveSite());+ const first = await desktop.newPage();+ // Pause the deferred gallery boot to check appearance as soon as HTML is parsed.+ let allowApp;+ const gate = new Promise(resolve => { allowApp = resolve; });+ await first.route('**/app.js',async route => { await gate; await route.fallback(); });+ const navigation = first.goto(origin);+ await first.locator('#theme').waitFor();+ await expectTheme(first,'dark');+ assert.equal(await first.evaluate(() => window.APP), undefined);+ allowApp();+ await navigation;+ assert.equal(await first.locator('[data-theme-choice=system]').getAttribute('aria-pressed'),'true');+ await first.emulateMedia({colorScheme:'light'});+ await expectTheme(first,'light');++ const second = await desktop.newPage();+ await second.goto(origin+'/#studio');+ await first.locator('#theme').focus();+ await first.keyboard.press('ArrowDown');+ await first.keyboard.press('End');+ await first.keyboard.press('Enter');+ assert.equal(await first.locator('#themeMenu').getAttribute('open'),null);+ assert.equal(await first.locator('#theme').evaluate(el => el === document.activeElement),true);+ await expectTheme(first,'dark');+ await expectTheme(second,'dark');+ await first.reload();+ await expectTheme(first,'dark');+ await second.emulateMedia({colorScheme:'light'});+ await expectTheme(second,'dark');+ await second.keyboard.press('t');+ await expectTheme(first,'light');+ await first.locator('#theme').click();+ await first.locator('[data-theme-choice=system]').click();+ await second.emulateMedia({colorScheme:'dark'});+ await expectTheme(first,'light');+ await expectTheme(second,'dark');+ await desktop.close();++ const mobile = await browser.newContext({isMobile:true,hasTouch:true,viewport:{width:320,height:568},+ reducedMotion:'reduce',colorScheme:'dark',serviceWorkers:'block'});+ await mobile.route('**/*',serveSite());+ await mobile.addInitScript(() => { localStorage.theme='light'; localStorage.pwUiLocale='ja'; });+ const phone = await mobile.newPage();+ await phone.goto(origin);+ await expectTheme(phone,'light');+ await phone.getByLabel('外観',{exact:true}).filter({hasNot:phone.locator('button')}).tap();+ const dark = phone.getByRole('button',{name:'ダーク',exact:true});+ const rect = await dark.boundingBox();+ assert.ok(rect && rect.height >= 44 && rect.x >= 0 && rect.x + rect.width <= 320);+ assert.equal(await phone.locator('.theme-pop').evaluate(el=>getComputedStyle(el).animationName),'none');+ await dark.tap();+ await expectTheme(phone,'dark');+ await phone.locator('#theme').tap();+ await phone.keyboard.press('Escape');+ assert.equal(await phone.locator('#themeMenu').getAttribute('open'),null);+ await mobile.close();+ console.log('Theme: initial paint, system/explicit preferences, persistence, tab sync, keyboard, phone and reduced motion passed.');+ } finally {+ await browser.close();+ }+}+run().catch(error=>{console.error(error);process.exitCode=1;});diff --git a/tests/v12.js b/tests/v12.jsindex 7df4e46..8b1052d 100644--- a/tests/v12.js+++ b/tests/v12.js@@ -2,11 +2,11 @@ const {chromium}=require('playwright');const path=require('path'),FX=path.join(_const ok=(n,v)=>{R.push((v?'PASS ':'FAIL ')+n)};const W=(pg,f,a)=>pg.waitForFunction(f,a,{timeout:T}).then(()=>true).catch(()=>false);const ctx=await b.newContext({viewport:{width:1440,height:900}});const pg=await ctx.newPage();pg.on('pageerror',e=>errs.push(''+e));pg.on('console',m=>m.type()=='error'&&!/404/.test(m.text())&&errs.push(m.text()));-await pg.goto(U+'/');ok('home grid',await W(pg,()=>document.querySelectorAll('#grid .card img.ld').length>=5));ok('intro visible',await pg.isVisible('#intro'));await pg.screenshot({path:S+'d-home.png'});+await pg.goto(U+'/');ok('home grid',await W(pg,()=>document.querySelectorAll('#grid .card img.ld').length>=5));ok('one closed notice center',await pg.isVisible('#noticeMenu summary')&&!(await pg.isVisible('#releaseNotice')));await pg.screenshot({path:S+'d-home.png'});// tab switch timingconst tt=await pg.evaluate(async()=>{const o=[];for(const t of ['costume','portrait','pose']){const t0=performance.now();document.querySelector(`[data-tab=${t}]`).click();await new Promise(r=>{const f=()=>APP.st.tab==t&&document.querySelector('#grid .card')&&!document.querySelector('#grid .skel')?r():requestAnimationFrame(f);f()});o.push(Math.round(performance.now()-t0))}return o});ok('tab switch ms '+tt,Math.max(...tt)<400);// back behaviour-await pg.click('[data-tab=costume]');await W(pg,()=>APP.st.tab=='costume'&&document.querySelector('#grid .card'));+await pg.click('#libraryMenu summary');await pg.click('[data-tab=costume]');await W(pg,()=>APP.st.tab=='costume'&&document.querySelector('#grid .card'));await pg.evaluate(()=>document.querySelector('#grid .card .phk').click());ok('lb open',await W(pg,()=>!document.querySelector('#lb').hidden&&location.hash.includes('/')));await pg.waitForTimeout(600);await pg.screenshot({path:S+'d-lb.png'});await pg.goBack();ok('back closes lb',await W(pg,()=>document.querySelector('#lb').hidden&&location.hash=='#costume'));@@ -14,13 +14,14 @@ await pg.goBack();ok('back to previous tab',await W(pg,()=>APP.st.tab=='pose'));await pg.goForward();ok('forward',await W(pg,()=>APP.st.tab=='costume'));// fav in lightbox updates fav gridawait pg.evaluate(()=>{APP.st.list.slice(0,3).forEach(i=>APP.st.fav.has(i.k)||APP.toggleFav(i.k,1))});-await pg.click('[data-tab=fav]');ok('fav grid',await W(pg,()=>APP.st.tab=='fav'&&document.querySelectorAll('#grid .card').length>=3));const nf=await pg.$$eval('#grid .card',x=>x.length);+await pg.click('#personalMenu summary');await pg.click('[data-tab=fav]');ok('fav grid',await W(pg,()=>APP.st.tab=='fav'&&document.querySelectorAll('#grid .card').length>=3));const nf=await pg.$$eval('#grid .card',x=>x.length);await pg.evaluate(()=>document.querySelector('#grid .card .phk').click());await W(pg,()=>!document.querySelector('#lb').hidden);await pg.waitForTimeout(400);await pg.keyboard.press('f');await pg.waitForTimeout(200);await pg.keyboard.press('Escape');ok('unfav in lb removes card',await W(pg,n=>document.querySelector('#lb').hidden&&document.querySelectorAll('#grid .card').length==n-1,nf));// refresh restoreawait pg.goto(U+'/#portrait');ok('refresh restore portrait',await W(pg,()=>APP.st.tab=='portrait'&&document.querySelector('#grid .card img')));-// intro dismiss-await pg.click('#introX');await pg.waitForTimeout(400);await pg.reload();await W(pg,()=>document.querySelector('#grid .card'));ok('intro dismissed persists',!(await pg.isVisible('#intro')));+// Release notices stay behind the bell when switching or refreshing the gallery.+await pg.click('#noticeMenu summary');await pg.locator('#releaseNotice').waitFor();await pg.keyboard.press('Escape');+await pg.reload();await W(pg,()=>document.querySelector('#grid .card'));ok('notices stay closed on refresh',!(await pg.isVisible('#releaseNotice')));// studio + settingsawait pg.click('[data-tab=studio]');await W(pg,()=>APP.st.tab=='studio');await pg.waitForTimeout(800);await pg.screenshot({path:S+'d-studio.png'});ok('studio fits',(await pg.evaluate(()=>document.documentElement.scrollHeight))<=900);// dark lb@@ -34,4 +35,4 @@ await m.evaluate(()=>document.querySelector('#grid .card .phk').click());await Wawait m.goto(U+'/#studio');await W(m,()=>APP.st.tab=='studio');await m.waitForTimeout(700);await m.screenshot({path:S+'m-studio.png'});await m.goto(U+'/#fav');await W(m,()=>APP.st.tab=='fav');await m.waitForTimeout(800);await m.screenshot({path:S+'m-fav.png'});if(process.env.LIVE){for(const p of ['/pose/full_single_P001/','/costume/SPR-0001/','/nope-x']){await pg.goto(U+p);await pg.waitForTimeout(600);await pg.screenshot({path:S+'d'+p.replace(/\W+/g,'-')+'.png'})}}-console.log(R.join('\n'));console.log('errs',errs);await b.close()})()+console.log(R.join('\n'));console.log('errs',errs);process.exitCode=R.some(row=>row.startsWith('FAIL'))||errs.length?1:0;await b.close()})()diff --git a/tests/v13.js b/tests/v13.jsindex bc1b668..6d27914 100644--- a/tests/v13.js+++ b/tests/v13.js@@ -65,4 +65,4 @@ await p.evaluate(()=>{const ks=Object.keys(APP.ITEMS).slice(0,12);ks.forEach(k=>const ov=await p.evaluate(()=>[...document.querySelectorAll('.card,.tray-h,#tray,.tabs')].filter(e=>e.scrollWidth>e.clientWidth+2).map(e=>e.className||e.id).slice(0,5));R.push(['no overflow',!ov.length,JSON.stringify(ov)]);const cb=await p.$eval('.cbtns button',e=>e.getBoundingClientRect().width);R.push(['card btn size',cb>=40,cb]);await c.close();await b.close();-R.forEach(r=>console.log((r[1]?'PASS ':'FAIL ')+r[0]+' — '+r[2]));console.log('errors',errs);})();+R.forEach(r=>console.log((r[1]?'PASS ':'FAIL ')+r[0]+' — '+r[2]));console.log('errors',errs);process.exitCode=R.some(row=>!row[1])||errs.length?1:0;})();diff --git a/tests/v15-modules.js b/tests/v15-modules.jsindex 4b2a45a..b05ef9f 100644--- a/tests/v15-modules.js+++ b/tests/v15-modules.js@@ -5,10 +5,19 @@ const ok=(n,v,d)=>{R.push((v?'PASS ':'FAIL ')+n+(d?' :: '+d:''))};const W=(pg,f,a)=>pg.waitForFunction(f,a,{timeout:T}).then(()=>true).catch(()=>false);const ctx=await b.newContext({viewport:{width:1440,height:900}});const pg=await ctx.newPage();pg.on('pageerror',e=>errs.push(''+e));pg.on('console',m=>m.type()=='error'&&!/404/.test(m.text())&&errs.push(m.text()));await pg.goto(U+'/');ok('home grid',await W(pg,()=>document.querySelectorAll('#grid .card img.ld').length>=5));+// A tab can become active before its view-transition callback paints the new cards.+async function openLibrary(type) {+ await pg.click('#libraryMenu summary');+ await pg.click(`[data-tab=${type}]`);+ await pg.waitForFunction(t => {+ const card = document.querySelector('#grid:not(.gbusy) .card');+ return APP.st.tab === t && APP.ITEMS[card?.dataset.k]?.type === t;+ }, type, {timeout:T});+}// ---- 各新栏目:数据条数 + 卡片渲染 + 导航计数 ----const EXP={expr:95,hair:122,dyn:57,scene:64,light:50,prop:32,furn:41}; // 历代/四库已剔除上游零视角空壳条目(历代 60−3、场景 68−4、光影 55−5、道具 36−4、家具 48−7)for(const [t,n] of Object.entries(EXP)){- await pg.click(`[data-tab=${t}]`);+ await openLibrary(t);await pg.evaluate(t=>APP.load(t),t);const len=await pg.evaluate(t=>APP.DATA[t].length,t);ok(t+' 数据条数 '+len,len==n,'expect '+n);@@ -17,14 +26,14 @@ for(const [t,n] of Object.entries(EXP)){ok(t+' 导航计数',+nav==n,nav);}// ---- 表情:情绪 + 强度筛选 -----await pg.click('[data-tab=expr]');await W(pg,()=>APP.st.tab=='expr'&&document.querySelector('#grid .card'));+await openLibrary('expr');await pg.evaluate(()=>{APP.st.f={emo:'愤怒'};APP.apply()});ok('表情情绪筛选',await pg.evaluate(()=>APP.st.list.length==8&&APP.st.list.every(i=>i.emo=='愤怒')));await pg.evaluate(()=>{APP.st.f={emo:'愤怒',int:'强烈'};APP.apply()});ok('表情强度筛选',await pg.evaluate(()=>APP.st.list.length==4&&APP.st.list.every(i=>i.int=='强烈')));await pg.evaluate(()=>{APP.st.f={};APP.apply()});// ---- 历代:朝代筛选(唐 6 套,另 2 套为零视角空壳已剔除)+ 灯箱切视角 -----await pg.click('[data-tab=dyn]');await W(pg,()=>APP.st.tab=='dyn'&&document.querySelector('#grid .card'));+await openLibrary('dyn');await pg.evaluate(()=>{APP.st.f={era:'唐'};APP.apply()});ok('历代朝代筛选',await pg.evaluate(()=>APP.st.list.length==6&&APP.st.list.every(i=>i.era=='唐')));await pg.evaluate(()=>document.querySelector('#grid .card .phk').click());@@ -36,25 +45,25 @@ const src1=await pg.evaluate(()=>document.querySelector('#lbImg').dataset.src);ok('灯箱切视角换图',src0!=src1&&/_back\.webp/.test(src1||''),src1);await pg.keyboard.press('Escape');await pg.evaluate(()=>{APP.st.f={};APP.apply()});// ---- 发型:热链 + 发色变体 -----await pg.click('[data-tab=hair]');await W(pg,()=>APP.st.tab=='hair'&&document.querySelector('#grid .card'));+await openLibrary('hair');const hsrc=await pg.evaluate(()=>document.querySelector('#grid .card img').src);ok('发型图片热链原站',/^https:\/\/charadb-2fi\.pages\.dev\/thumb\//.test(hsrc),hsrc);ok('发型分组带 5 个发色变体',await pg.evaluate(()=>{const g=APP.DATA.hair.find(i=>i.angles);return g&&g.angles.length==5}));ok('发型单品条数',await pg.evaluate(()=>APP.DATA.hair.filter(i=>!i.angles).length==76));// ---- CharaDB 并入动画服装 -----await pg.click('[data-tab=anime]');await W(pg,()=>APP.st.tab=='anime'&&document.querySelector('#grid .card'));+await openLibrary('anime');ok('动画服装总数 1760',await pg.evaluate(()=>APP.DATA.anime.length==1760),await pg.evaluate(()=>''+APP.DATA.anime.length));ok('charadb 条目在位且标记 ext',await pg.evaluate(()=>{const it=APP.DATA.anime.find(i=>i.id=='charadb-O001');return !!it&&it.ext==1&&/^https:\/\/charadb/.test(it.t)}));ok('charadb 敏感条目默认隐藏',await pg.evaluate(()=>APP.DATA.anime.filter(i=>i.ext&&i.a).length==44&&APP.st.list.every(i=>!i.a)));// ---- 场景/光影抽查:机位筛选 -----await pg.click('[data-tab=scene]');await W(pg,()=>APP.st.tab=='scene'&&document.querySelector('#grid .card'));+await openLibrary('scene');await pg.evaluate(()=>{APP.st.f={ang:'俯视'};APP.apply()});ok('场景机位筛选',await pg.evaluate(()=>APP.st.list.length>0&&APP.st.list.every(i=>i.angles.some(a=>a.zh=='俯视'))));await pg.evaluate(()=>{APP.st.f={};APP.apply()});// ---- 收藏新模块条目(发型)→ 收藏页渲染 -----await pg.click('[data-tab=hair]');await W(pg,()=>APP.st.tab=='hair'&&document.querySelector('#grid .card'));+await openLibrary('hair');await pg.evaluate(()=>{const it=APP.DATA.hair[0];APP.toggleFav(it.k,1)});-await pg.click('[data-tab=fav]');+await pg.click('#personalMenu summary');await pg.click('[data-tab=fav]');ok('收藏页含发型条目',await W(pg,()=>document.querySelectorAll('#grid .card').length>=1));// ---- 试穿:表情槽位(占位 + 数据打通,不做真实生图) ----await pg.goto(U+'/#studio');await pg.waitForFunction(()=>window.WB&&window.APP,null,{timeout:15000});@@ -62,12 +71,19 @@ const slot=await pg.evaluate(async()=>{await APP.load('expr');const it=APP.DATA.ok('WB.pick 表情进槽位',slot==1);ok('表情槽位渲染',await W(pg,()=>document.querySelector('#wbEx .pick')!=null));await pg.screenshot({path:S+'studio-expr.png'});-await pg.evaluate(()=>{WB._W.pl='zh';document.querySelector('#wbPrompt').value='';WB._W.dirty=false;const ev=new Event('input',{bubbles:true});document.querySelector('#wbExtra').dispatchEvent(ev)});-const pr=await pg.evaluate(()=>document.querySelector('#wbPrompt').value);-ok('提示词含表情迁移句(中)',/只迁移神态/.test(pr)&&/五官、脸型和身份/.test(pr),pr.slice(0,60));-await pg.evaluate(()=>{WB._W.pl='en';document.querySelector('#wbPrompt').value='';WB._W.dirty=false;const ev=new Event('input',{bubbles:true});document.querySelector('#wbExtra').dispatchEvent(ev)});-const pre=await pg.evaluate(()=>document.querySelector('#wbPrompt').value);-ok('提示词含表情迁移句(英)',/Transfer ONLY the expression/.test(pre)&&/identity must remain/.test(pre),pre.slice(0,60));+await pg.locator('[data-pl=zh]').click();+const pr=await pg.inputValue('#wbPrompt');+ok('单张表情图(中)',/第 1 张/.test(pr)&&/只迁移神态/.test(pr)&&!/人物照片/.test(pr));+await pg.locator('[data-pl=en]').click();+const pre=await pg.inputValue('#wbPrompt');+ok('单张表情图(英)',/expression: image 1/i.test(pre)&&/transfer the expression only/i.test(pre)&&!/person photo/i.test(pre));+await pg.setInputFiles('#wbFile',path.join(__dirname,'fixtures','person.png'));+await pg.waitForFunction(()=>WB._W.persons.length===1);+const withPerson=await pg.inputValue('#wbPrompt');+ok('有人物照片时保留身份(英)',/expression: image 2/i.test(withPerson)&&/identity from the person photo/i.test(withPerson));+await pg.locator('[data-pl=zh]').click();+const withPersonZh=await pg.inputValue('#wbPrompt');+ok('有人物照片时保留身份(中)',/表情:第 2 张/.test(withPersonZh)&&/五官、脸型和身份/.test(withPersonZh));ok('无页面错误',errs.length==0,errs.slice(0,3).join(' | '));await b.close();const fail=R.filter(x=>x.startsWith('FAIL'));console.log(R.join('\n'));console.log(fail.length?('V15 FAIL '+fail.length):'V15 ALL PASS');process.exit(fail.length?1:0)})().catch(e=>{console.error(e);process.exit(1)});diff --git a/tests/v16-proxy.mjs b/tests/v16-proxy.mjsindex fb41c40..897777d 100644--- a/tests/v16-proxy.mjs+++ b/tests/v16-proxy.mjs@@ -9,17 +9,22 @@ async function call(target, headers = {}, withOrigin = true) {if (withOrigin) h.set('origin', SELF);if (target) h.set('x-target-url', target);const req = new Request(SELF + '/api/proxy', { method: 'POST', headers: h, body: '{}' });- const r = await onRequest({ request: req, waitUntil() {} });+ const r = await onRequest({ request: req, env: {POSEWEAR_PROXY_ORIGINS:'https://example.com:8443'} });const t = await r.text().catch(() => '');return { status: r.status, body: t.slice(0, 120) };}-let r = await call('https://example.com:8443/v1/images/generations', { 'x-proxy-custom': '1' });-ok('custom https 非443 端口放行', r.status !== 400 && !/标准 https|http\/https 地址/.test(r.body), r.status + ' ' + r.body);+let forwarded;+globalThis.fetch = async (url, init) => { forwarded = init.headers; return new Response('{}') };+let r = await call('https://example.com:8443/v1/images/generations', { 'x-proxy-custom': '1', 'cookie':'test-cookie', 'authorization':'Bearer test-only', 'x-unrelated':'test' });+ok('custom https 非443 端口放行', r.status === 200, r.status + ' ' + r.body);+ok('只转发上游必需的请求头', forwarded.get('authorization') === 'Bearer test-only' && !forwarded.has('cookie') && !forwarded.has('x-unrelated'));+r = await call('https://other.example/v1/models', { 'x-proxy-custom':'1' });+ok('未登记中转提示改用直连', r.status === 403 && r.body.includes('直连'));r = await call('http://example.com:8080/v1/images/edits', { 'x-proxy-custom': '1' });-ok('custom http 非443 端口放行', r.status !== 400 && !/标准 https|http\/https 地址/.test(r.body), r.status + ' ' + r.body);+ok('custom http 拒绝明文', r.status === 400, r.status + ' ' + r.body);r = await call('https://api.openai.com:8443/v1/images/generations', {});ok('官方域名带端口仍拒绝', r.status === 400, r.status + ' ' + r.body);-r = await call('http://192.168.1.5:8188/v1/images/generations', { 'x-proxy-custom': '1' });+r = await call('https://192.168.1.5:8188/v1/images/generations', { 'x-proxy-custom': '1' });ok('自定义内网地址仍拒绝', r.status === 403, r.status + ' ' + r.body);r = await call('https://example.com:8443/v1/chat/completions', { 'x-proxy-custom': '1' });ok('自定义非图片路径仍拒绝', r.status === 403, r.status + ' ' + r.body);diff --git a/tests/v17-history.js b/tests/v17-history.jsindex bf37e59..81f5b1f 100644--- a/tests/v17-history.js+++ b/tests/v17-history.js@@ -3,7 +3,7 @@ const { chromium } = require('playwright');const path = require('path'), FX = path.join(__dirname, 'fixtures') + '/';const fs = require('fs');(async () => {- const U = process.env.U || 'http://localhost:8794';+ const U = process.env.U || 'http://localhost:8787';const b = await chromium.launch({ executablePath: process.env.CHROME_PATH });const R = [], errs = [];const ok = (n, c, d) => R.push([n, !!c, d || '']);@@ -13,8 +13,9 @@ const fs = require('fs');await p.goto(U + '/');await p.waitForFunction(() => window.APP, null, { timeout: 15000 });// 种记录:2 条试穿(带 before)+ 1 条生图- await p.evaluate(async FXU => {- const blob = async n => (await (await fetch(FXU + n)).blob());+ const fixtures = Object.fromEntries(['person.png','mk1.png','mk2.png'].map(name => [name,fs.readFileSync(FX+name).toString('base64')]));+ await p.evaluate(async images => {+ const blob = n => new Blob([Uint8Array.from(atob(images[n]), c => c.charCodeAt(0))],{type:'image/png'});const b1 = await blob('person.png'), b2 = await blob('mk1.png'), b3 = await blob('mk2.png');const db = await new Promise((res, rej) => { const q = indexedDB.open('lk-studio', 1); q.onupgradeneeded = () => q.result.createObjectStore('h', { keyPath: 't' }); q.onsuccess = () => res(q.result); q.onerror = () => rej(q.error); });const put = r => new Promise((res, rej) => { const t = db.transaction('h', 'readwrite'); t.objectStore('h').put(r); t.oncomplete = res; t.onerror = () => rej(t.error); });@@ -22,27 +23,11 @@ const fs = require('fs');await put({ t: now - 3000, prov: 'openai', model: 'gpt-image-1', prompt: '测试提示词A', mode: 'tryon', label: '记录A', before: b1, after: b2 });await put({ t: now - 2000, prov: 'gemini', model: 'gemini-2.5-flash-image', prompt: '测试提示词B', mode: 'tryon', label: '记录B', before: b1, after: b3 });await put({ t: now - 1000, prov: 'seedream', model: 'doubao-seedream-5-5-261028', prompt: '测试提示词C', mode: 'gen', label: '记录C', before: null, after: b2 });- }, '/tests-fixtures/');- // fixtures 经测试服务器根路径不可达时改用文件协议注入+ db.close();+ }, fixtures);await p.goto(U + '/#history');- await p.waitForTimeout(1200);- let n = await p.evaluate(() => document.querySelectorAll('#histGrid .hist-card').length);- if (n === 0) {- // 直接用 dataURL 种 Blob 再试一次- await p.evaluate(async () => {- const px = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg==';- const blob = async () => (await (await fetch('data:image/png;base64,' + px)).blob());- const db = await new Promise((res, rej) => { const q = indexedDB.open('lk-studio', 1); q.onupgradeneeded = () => q.result.createObjectStore('h', { keyPath: 't' }); q.onsuccess = () => res(q.result); q.onerror = () => rej(q.error); });- const put = r => new Promise((res, rej) => { const t = db.transaction('h', 'readwrite'); t.objectStore('h').put(r); t.oncomplete = res; t.onerror = () => rej(t.error); });- const now = Date.now(), bb = await blob();- await put({ t: now - 3000, prov: 'openai', model: 'gpt-image-1', prompt: '测试提示词A', mode: 'tryon', label: '记录A', before: bb, after: bb });- await put({ t: now - 2000, prov: 'gemini', model: 'gemini-2.5-flash-image', prompt: '测试提示词B', mode: 'tryon', label: '记录B', before: bb, after: bb });- await put({ t: now - 1000, prov: 'seedream', model: 'doubao-seedream-5-5-261028', prompt: '测试提示词C', mode: 'gen', label: '记录C', before: null, after: bb });- });- await p.evaluate(() => window.HIS && HIS.refresh());- await p.waitForTimeout(800);- n = await p.evaluate(() => document.querySelectorAll('#histGrid .hist-card').length);- }+ await p.waitForFunction(() => document.querySelectorAll('#histGrid .hist-card').length === 3);+ const n = await p.locator('#histGrid .hist-card').count();ok('记录页渲染 3 条', n === 3, 'cards=' + n);ok('导航计数 3', await p.evaluate(() => document.querySelector('#nHist').textContent == '3'), await p.evaluate(() => document.querySelector('#nHist').textContent));ok('统计行含试穿/生图', await p.evaluate(() => /试穿/.test(document.querySelector('#histStats').textContent) && /生图/.test(document.querySelector('#histStats').textContent)), '');@@ -62,7 +47,7 @@ const fs = require('fs');ok('方向键切换记录', await p.evaluate(() => /第 2 \/ 3 项/.test(document.querySelector('#lbSide').textContent)), await p.evaluate(() => document.querySelector('#lbSide .mu').textContent));ok('试穿记录有对比滑杆', await p.evaluate(() => !!document.querySelector('#lbSide .hlb-cmp input[type=range]')), '');await p.keyboard.press('Escape');- await p.waitForTimeout(300);+ await p.locator('#lb').waitFor({state:'hidden'});ok('Esc 关闭灯箱', await p.evaluate(() => document.querySelector('#lb').hidden), '');// 删除一条await p.click('#histGrid .hist-card [data-act="del"]');@@ -74,5 +59,6 @@ const fs = require('fs');ok('切回图库 histSec 隐藏', await p.evaluate(() => document.querySelector('#histSec').hidden && !document.body.classList.contains('histview')), '');ok('无页面错误', errs.length === 0, errs.join(' | ').slice(0, 200));await b.close();+ process.exitCode = R.some(row => !row[1]) ? 1 : 0;R.forEach(r => console.log((r[1] ? 'PASS ' : 'FAIL ') + r[0] + (r[2] ? ' — ' + r[2] : '')));})();diff --git a/tests/v18-quick.js b/tests/v18-quick.jsindex 3f82ce4..bb8a08a 100644--- a/tests/v18-quick.js+++ b/tests/v18-quick.js@@ -16,6 +16,8 @@ const { chromium } = require('playwright'); const path = require('path'), FX = p// —— 主流程{ const { c, p } = await setup(true); hits = [];await sel(p, 'costume'); await sel(p, 'pose');+ R.push(['silent selection updates the launcher', await p.locator('#tray').isHidden() && await p.locator('#trayFabN').textContent() === '2', '']);+ await p.click('#trayFab');R.push(['tray visible', await p.$eval('#tray', e => !e.hidden), '']);await p.waitForFunction(() => document.querySelector('#tgPrompt').value.length > 30, null, { timeout: 15000 }).catch(() => {});const pv = await p.$eval('#tgPrompt', e => e.value);@@ -35,12 +37,24 @@ const { chromium } = require('playwright'); const path = require('path'), FX = p// —— 错误路径mode = '500'; await p.click('#tgGo'); await p.waitForFunction(() => /生成失败/.test(document.querySelector('#tgStat').textContent), null, { timeout: 20000 }).catch(() => {});R.push(['error shown', /生成失败/.test(await p.$eval('#tgStat', e => e.textContent)), await p.$eval('#tgStat', e => e.textContent)]);- mode = 'ok'; await c.close() }+ mode = 'ok';+ await p.locator('#tgPrompt').fill('Use this edited draft.');+ await p.selectOption('#tgN','2'); await p.selectOption('#tgAR','3:4');+ await p.click('#tgStudio'); await p.waitForSelector('#studio:not([hidden])');+ const draft=await p.evaluate(()=>[document.querySelector('#wbPrompt').value,document.querySelector('#wbN').value,+ document.querySelector('#wbAR').value,WB._W.mode,document.querySelector('#wbGo').disabled]);+ R.push(['expanded studio retains edited draft and settings', JSON.stringify(draft) === JSON.stringify(['Use this edited draft.','2','3:4','gen',false]), JSON.stringify(draft)]);+ await c.close() }// —— 未配置路径:点生成应打开 API 设置{ const { c, p } = await setup(false);await sel(p, 'costume');+ await p.click('#trayFab');await p.click('#tgGo'); await p.waitForTimeout(600);R.push(['nokey opens cfg', await p.$eval('#cfg', e => !e.hidden), '']);+ await p.locator('#cfKey').fill('sk-ui-test'); await p.locator('#cfSave').click();+ R.push(['saved provider updates in open tray', await p.locator('#tgProv').innerText() !== '未配置 API' && await p.locator('#tgCfg .dot.on').count() === 1, '']);+ await p.locator('#tgCfg').click(); await p.locator('#cfClr').click(); await p.locator('#cfgX').click();+ R.push(['cleared key updates in open tray', await p.locator('#tgProv').innerText() === '未配置 API' && await p.locator('#tgCfg .dot.on').count() === 0, '']);await c.close() }// —— 常驻工作台:空选时入口在位,开面板经选择器加素材{ const { c, p } = await setup(true);@@ -56,6 +70,29 @@ const { chromium } = require('playwright'); const path = require('path'), FX = pR.push(['picker adds to tray', n1 == 1, 'items ' + n1]);await p.waitForFunction(() => document.querySelector('#tgPrompt').value.length > 30, null, { timeout: 15000 }).catch(() => {});R.push(['prompt after picker add', (await p.$eval('#tgPrompt', e => e.value)).length > 30, '']);+ await p.locator('#tgMore summary').click(); await p.locator('[data-add=prop]').click();+ await p.locator('#pkG [data-k]').first().click(); await p.locator('#pkDone').click();+ R.push(['extended reference library', await p.locator('#trayItems [data-k]').count() === 2, '']);+ await p.keyboard.press('Escape');+ R.push(['closing restores launcher focus', await p.evaluate(()=>document.activeElement.id === 'trayFab'), '']);+ for(const tab of ['fav','history','studio']) {+ await p.evaluate(tab=>APP.setTab(tab),tab);+ await p.locator('#trayFab').click();+ R.push(['global workspace in '+tab, await p.locator('#tray').isVisible(), '']);+ await p.keyboard.press('Escape');+ }+ await p.locator('#wbExample').click();+ await p.waitForFunction(()=>WB._W.persons.length && WB._W.garments.length && WB._W.poses.length);+ R.push(['reference board applies real inputs', await p.locator('#wbBoardCards .board-card').count() === 3, '']);+ await c.close() }+ { const {c,p}=await setup(true); hits=[];+ await p.locator('#trayFab').click(); await p.locator('#tgPrompt').fill('Draw a blue linen scarf.');+ await p.locator('#tgStudio').click(); await p.locator('details.adv summary').click();+ await p.locator('#wbReP').click();+ R.push(['reset text-only draft updates generate state', await p.locator('#wbGo').isDisabled(), '']);+ await p.locator('#wbPrompt').fill('Draw a blue linen scarf.'); await p.locator('#wbGo').click();+ await p.locator('#wbAfter[src^=blob]').waitFor();+ R.push(['text-only draft generates in full studio', hits.some(url=>url.endsWith('/images/generations')), hits.join(', ')]);await c.close() }R.push(['no pageerror', !errs.length, errs.slice(0, 3).join(' | ')]);let f = 0; for (const [n, ok, d] of R) { console.log((ok ? 'PASS' : 'FAIL') + ' ' + n + (ok ? '' : ' :: ' + d)); if (!ok) f++ }