Skip to content

12 个视觉参考图库与浏览器无限画布 AI 创作台(5,700+ 素材、中英提示词、多图对比、ComfyUI & MCP)· Visual reference library & infinite-canvas AI studio in the browser

refactor: modularize frontend, flatten CSS, and replace Python exec() glue

atuizzcd7fd5fb22c3
diff --git a/AGENTS.md b/AGENTS.md
index e71bc65..c7b0bf3 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -13,11 +13,16 @@
| 路径 | 职责 |
|---|---|
-| `build.py` | 构建主入口:读 `assets-raw` 数据 → 生成每库 JSON、图片变体、SEO 页;内部依次 exec `post.py`、`seo.py` |
-| `post.py` | 后处理:资源指纹(`/assets/<name>.<hash>.js|json`)、`_headers`(含 CSP)、index.html 组装 |
-| `seo.py` | 每库/每条目的静态 SEO 落地页 |
+| `build.py` | 构建主入口:读 `assets-raw` 数据 → 生成每库 JSON、图片变体,显式调用 `post.run(ctx)` |
+| `post.py` | 后处理模块(`post.run(ctx)`):资源指纹(`/assets/<name>.<hash>.js|json`)、`sw.js` 预缓存、`_headers`(含 CSP)、`index.html` 组装,并调用 `seo.run(ctx)` |
+| `seo.py` | 静态 SEO 落地页模块(`seo.run(ctx)`):中英文首页/分类/标签/详情页与站点地图 |
| `src/index.html` | 单页骨架(所有栏目、试穿台、托盘、弹窗的 DOM 都在这里) |
+| `src/catalog.js` | `window.PoseWearCatalog` 单一数据源:12 库注册表、筛选与配色、槽位映射与通用 DOM/存储工具 |
| `src/app.js` | 图库 SPA:栏目切换、筛选、卡片、灯箱、收藏、组合与**悬浮生图工作台**(托盘) |
+| `src/palette.js` | 灯箱主色调提取与色卡渲染(`window.PoseWearPalette`) |
+| `src/sketch.js` | 全屏速写定时练习工作室(`window.PoseWearSketch`) |
+| `src/command-palette.js` | 全局 `⌘K` 命令面板(`window.PoseWearCommandPalette`) |
+| `src/board-export.js` | 参考画板高分 PNG 拼贴导出(`window.PoseWearBoardExport`) |
| `src/references.js` | 浏览器与 MCP 共用选定视角、公开图片地址与复制文本的格式 |
| `src/i18n.js` | 中英日界面词条与语言切换,`pwUiLocale` 独立于提示词设置 |
| `src/studio.js` | 工作台选材、提示词、生成与结果;对外接口是 `window.WB` |
diff --git a/build.py b/build.py
index efd7015..a9626c8 100644
--- a/build.py
+++ b/build.py
@@ -1,194 +1,535 @@
-import argparse,json,os,shutil,subprocess,depthpack
-from costume_text import gen2
-import hashlib,re,html as H
+"""Build entry point for PoseWear: converts raw assets, generates catalogs, and invokes post.run(ctx)."""
+
+import argparse
from concurrent.futures import ProcessPoolExecutor
+from functools import partial
+import json
+import os
+import shutil
+
from PIL import Image
+
+from costume_text import gen2
+import depthpack
+import post
+
+
# 素材目录:默认 ./assets-raw,可用环境变量 POSEWEAR_RAW 指定(见 scripts/fetch-assets.py)
-R=os.environ.get('POSEWEAR_RAW','assets-raw'); D='dist'
+RAW_DIR = os.environ.get('POSEWEAR_RAW', 'assets-raw')
+DIST_DIR = '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={'寝そべり':'躺卧','セクシー・露骨寄り系':'性感·大胆','立ち':'站姿','座り':'坐姿','かわいい系':'可爱','胸寄せ・谷間強調系':'挤胸·乳沟','膝立ち・四つん這い':'跪立·趴姿','特殊':'特殊','正常位':'正面位','膝立ち':'跪立','横座り・女の子座り':'侧坐·鸭子坐','後背位':'后入位','背面座位':'背面坐位','しゃがみ':'蹲姿','前かがみ':'前倾','顔寄せ系':'贴脸','騎乗位':'骑乘位','立位':'立位','立位密着':'立位贴身','のけぞり・反り':'后仰','ひねり':'扭身','側位':'侧位','座位':'坐位','対面座位':'对面坐位','座位密着':'坐位贴身','密着':'贴身'}
-ANG={'正面':('正面','front view'),'上から':('俯拍','high angle, from above'),'下から':('仰拍','low angle, from below'),'横':('侧面','side view'),'斜め':('斜侧','three-quarter view')}
-CC={'春':('春季','spring'),'夏':('夏季','summer'),'秋':('秋季','autumn'),'冬':('冬季','winter'),'ランジェリー':('内衣','lingerie'),'パーティ':('派对礼服','party'),'水着':('泳装','swimsuit'),'セクシー':('性感','sexy')}
-W=dict(l.split(':') for l in open('words.txt').read().split())
-TR={l.split('|')[0]:l.split('|')[1:] for l in open('tr_pose.txt').read().strip().split('\n')}
-pd=json.load(open(f'{R}/pose/data.json'))['D']; cd=json.load(open(f'{R}/costume/data.json'))['D']; ad=json.load(open(f'{R}/anime/data.json'))['D']
-poses={}
-for d in pd:
- k=d['id'].rsplit('_',1)[0]; zh,en=TR[d['ポーズ名']]
- p=poses.setdefault(k,{'id':k,'no':d['ポーズ番号'],'line':LINE[d['系統']][0],'cat':CAT[d['分類']],'ja':d['ポーズ名'],'zh':zh,'en':en,'lineEn':LINE[d['系統']][1],'angles':[]})
- a=ANG[d['アングル']]; p['angles'].append({'zh':a[0],'en':a[1],'t':'p/t/'+d['id']+'.webp','i':'p/i/'+d['id']+'.webp','o':'o/p/'+d['id']+'.png','_src':d})
-cos=[{'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':'c/t/'+os.path.basename(d['サムネ']),'m':'c/m/'+d['id']+'.webp','i':'c/i/'+os.path.basename(d['画像']),'o':'o/c/'+d['id']+'.png','_src':d} for d in cd]
-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]
+ASSET_HOST = os.environ.get('POSEWEAR_ASSET_HOST', '').rstrip('/')
+ASSETS_DIST_DIR = 'dist-assets'
+ASSET_ROOT = ASSETS_DIST_DIR if ASSET_HOST else DIST_DIR
+
+EXTENSION_ARCHIVES = (
+ [f'{kind}/data.json' for kind in ('expression', 'dynasty', 'scene', 'light', 'prop', 'furn')]
+ + ['charadb/hair.json', 'charadb/outfits.json']
+)
+
+LINE = {
+ '全身1人・セクシー系': ('全身·性感', 'full body, solo, sexy'),
+ '全身1人・標準系': ('全身·标准', 'full body, solo'),
+ '上半身1人': ('上半身', 'upper body, solo'),
+ '2人絡み': ('双人互动', 'two people, couple'),
+}
+
+CAT = {
+ '寝そべり': '躺卧', 'セクシー・露骨寄り系': '性感·大胆', '立ち': '站姿', '座り': '坐姿',
+ 'かわいい系': '可爱', '胸寄せ・谷間強調系': '挤胸·乳沟', '膝立ち・四つん這い': '跪立·趴姿',
+ '特殊': '特殊', '正常位': '正面位', '膝立ち': '跪立', '横座り・女の子座り': '侧坐·鸭子坐',
+ '後背位': '后入位', '背面座位': '背面坐位', 'しゃがみ': '蹲姿', '前かがみ': '前倾',
+ '顔寄せ系': '贴脸', '騎乗位': '骑乘位', '立位': '立位', '立位密着': '立位贴身',
+ 'のけぞり・反り': '后仰', 'ひねり': '扭身', '側位': '侧位', '座位': '坐位',
+ '対面座位': '对面坐位', '座位密着': '坐位贴身', '密着': '贴身',
+}
+
+ANG = {
+ '正面': ('正面', 'front view'),
+ '上から': ('俯拍', 'high angle, from above'),
+ '下から': ('仰拍', 'low angle, from below'),
+ '横': ('侧面', 'side view'),
+ '斜め': ('斜侧', 'three-quarter view'),
+}
+
+CC = {
+ '春': ('春季', 'spring'),
+ '夏': ('夏季', 'summer'),
+ '秋': ('秋季', 'autumn'),
+ '冬': ('冬季', 'winter'),
+ 'ランジェリー': ('内衣', 'lingerie'),
+ 'パーティ': ('派对礼服', 'party'),
+ '水着': ('泳装', 'swimsuit'),
+ 'セクシー': ('性感', 'sexy'),
+}
+
# 双人 分类人工复核(看图)
-FIX={'pair60_P031':'坐位','pair60_P053':'立位贴身','pair60_P055':'侧位','pair60_P058':'贴脸'}
-for k,v in FIX.items(): poses[k]['cat']=v
-ADULT_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
-for c in cos:
- if c['cat'] in ADULT_COS: c['a']=1
-for c in acs:
- if c['cat'] in ADULT_COS: c['a']=1
-os.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={}
-for p in poses.values():
- for a in p['angles']: SRC[a['i']]=a.pop('_src')
-for c in cos: SRC[c['id']]=c.pop('_src')
-for c in acs: SRC['anime:'+c['id']]=c.pop('_src')
-# 安全内容排在前面(默认落地页无露骨内容)
-PL=sorted(poses.values(),key=lambda p:p.get('a',0))
-# CharaDB 服装 440 条并入动画服装(元数据自存、图片热链原站,见 scripts/prep-modules.py)
-_cdb=f'{R}/charadb/outfits.json'
-if os.path.exists(_cdb):
- for d in json.load(open(_cdb)):
- it={'id':d['id'],'cat':d['cat'],'catEn':d['catEn'],'kw':d['kw'],'zh':d['name']+','+'、'.join(d['tagsZh'][1:])+'。','en':d['kw'],'ti':d['name'],'t':d['t'],'m':d['m'],'i':d['i'],'o':'','ext':1}
- if d.get('sens'): it['a']=1
- acs.append(it)
-PJ=J(PL);CJ=J(cos);AJ=J(acs)
-
-# ---------- 人像库(AI Portrait Gallery,CC0,@agi_aibusi)----------
-rt=open(f'{R}/portrait/images.js').read();rd=json.loads(rt[rt.index('['):rt.rindex(']')+1])
-rk=open(f'{R}/portrait/ranking.js').read();RK=json.loads(rk[rk.index('{'):rk.rindex('}')+1])
-TRP={l.split('|')[0]:l.split('|')[1:] for l in open('tr_portrait.txt').read().strip().split('\n')}
-LEN={'ショート':('短发','short hair'),'ミディアム':('中长发','medium-length hair'),'セミロング':('半长发','shoulder-length hair'),'ロング':('长发','long hair')}
-SEC={'face':('正脸','front-facing head-and-shoulders portrait, plain light grey background, soft even lighting'),'styling':('生活照','casual selfie-style lifestyle photo, indoor natural light')}
-RANK={x:i+1 for i,x in enumerate(RK['top']['総合'])}
-RANKC={}
-for c,L in RK['top'].items():
- if c!='総合':
- for i,x in enumerate(L):RANKC[x]=i+1
-pors=[];seq={}
-for d in rd:
- sec=SEC[d['section']];ln=LEN[d['hair']];sz,se=TRP.get(d['style'],['',''])
- seq[d['section']]=seq.get(d['section'],0)+1;no=('F' if d['section']=='face' else 'S')+str(seq[d['section']]).zfill(3)
- zh=f"一位亚洲年轻女性,{ln[0]}{','+sz if sz else ''},{'正面半身肖像,浅灰纯色背景,柔和均匀的光线' if d['section']=='face' else '自拍风生活照,室内自然光'}。作为人物面部参考,保持五官和脸型一致。"
- en=f"young Asian woman, {ln[1]}{', '+se if se else ''}, {sec[1]}, consistent facial features, face reference"
- it={'id':d['id'],'no':no,'sec':sec[0],'len':ln[0],'st':sz,'ti':sz or f"{ln[0]} · {sec[0]}",'zh':zh,'en':en,'ja':d['style'] or d['hair'],'t':'r/t/'+d['id']+'.webp','m':'r/m/'+d['id']+'.webp','i':'r/m/'+d['id']+'.webp','o':'o/r/'+d['id']+'.png','w':d['w'],'h':d['h']}
- if d['id'] in RANK: it['rk']=RANK[d['id']]
- if d['id'] in RANKC: it['rc']=RANKC[d['id']]
- pors.append(it)
-RJ=J(pors)
-
-# ---------- 新模块(数据由 scripts/prep-modules.py 从本地档案生成到 assets-raw,构建不访问外网)----------
-VM={'front':('正面','front view'),'diag':('斜侧','three-quarter view'),'side':('侧面','side view'),'back':('背面','back view'),'above':('俯视','high angle, from above'),'below':('仰视','low angle, from below'),'eye':('平视','eye-level view'),'tq':('3/4 侧','three-quarter view')}
-def _vmod(sub,pre):
- p=f'{R}/{sub}/data.json'
- if not os.path.exists(p): return []
- out=[]
- for it in json.load(open(p)):
- nit={'id':it['id'],'cat':it['cat'],'ti':it['ti'],'zh':it['zh'],'en':it['en'],'ja':it.get('ja',''),'line':it['line'],'lineEn':it['lineEn'],'no':it['id'],
- 'angles':[{'zh':VM[v][0],'en':VM[v][1],'t':f'{pre}/t/{it["id"]}_{v}.webp','i':f'{pre}/i/{it["id"]}_{v}.webp','o':f'o/{pre}/{it["id"]}_{v}.webp','_3':f,'_9':f} for v,f in it['views'].items()]}
- nit.update(it.get('extra') or {})
- out.append(nit)
- return out
-EXP=_vmod('expression','e'); DYN=_vmod('dynasty','y'); SCE=_vmod('scene','s'); LIG=_vmod('light','l'); PRO=_vmod('prop','t'); FUR=_vmod('furn','f')
-_hp=f'{R}/charadb/hair.json'; HAI=json.load(open(_hp)) if os.path.exists(_hp) else []
-# 热链图片的源站(CharaDB 等):post.py 据此放行 CSP 的 img-src/connect-src,
-# 否则浏览器会拦截全部热链图片(2026-11-23 发型库全图加载失败的根因)。
-def _origins(o):
- s=set()
- def w(x):
- if isinstance(x,dict):
- for v in x.values(): w(v)
- elif isinstance(x,list):
- for v in x: w(v)
- elif isinstance(x,str) and x.startswith('https://'): s.add('/'.join(x.split('/')[:3]))
- w(o); return s
-HOTLINK_ORIGINS=set()
-for _f in ['charadb/outfits.json','charadb/hair.json']:
- _p=f'{R}/{_f}'
- if os.path.exists(_p): HOTLINK_ORIGINS|=_origins(json.load(open(_p)))
-HOTLINK_ORIGINS=sorted(HOTLINK_ORIGINS)
-EXJ=J(EXP);DYJ=J(DYN);SCJ=J(SCE);LIJ=J(LIG);PRJ=J(PRO);FUJ=J(FUR);HAJ=J(HAI)
-NEWMODS=[('expression',EXP),('dynasty',DYN),('scene',SCE),('light',LIG),('prop',PRO),('furn',FUR)]
-def _cnew(sub,items):
- for it in items:
- for a in it['angles']:
- f3,f9=a.pop('_3'),a.pop('_9')
- for src,tier,dst in [(f3,'w300',f'{AROOT}/{a["t"]}'),(f9,'w900',f'{D}/{a["i"]}'),(f9,'w900',f'{AROOT}/{a["o"]}')]:
- if not os.path.exists(dst): shutil.copy(f'{R}/{sub}/files/{tier}/{src}',dst)
-if os.path.exists(f'{D}/data.js'): os.remove(f'{D}/data.js')
-for a,b in [('costume/thumbs','c/t'),('costume/img','c/i'),('anime/thumbs','a/t'),('anime/img','a/i')]:
- shutil.copytree(f'{R}/{a}',f'{AROOT if b.endswith("/t") else D}/{b}',dirs_exist_ok=True)
-os.makedirs(f'{D}/p/i',exist_ok=True)
-def cv(d):
- t=f"{AROOT}/p/t/{d['id']}.webp"
- if not os.path.exists(t):
- im=Image.open(f"{R}/pose/{d['サムネ']}").convert('RGB');im.save(t,'WEBP',quality=80,method=6)
- o=f"{AROOT}/o/p/{d['id']}.png"
- if not os.path.exists(o): os.link(f"{R}/pose/{d['原寸']}",o)
- o=f"{D}/p/i/{d['id']}.webp"
- if not os.path.exists(o):
- im=Image.open(f"{R}/pose/{d['原寸']}").convert('RGB'); im.thumbnail((1200,1200)); im.save(o,'WEBP',quality=82)
-
-def cm(d):
- o=f"{D}/c/m/{d['id']}.webp"
- if not os.path.exists(o):
- im=Image.open(f"{R}/costume/{d['画像']}").convert('RGB'); im.thumbnail((1080,1620)); im.save(o,'WEBP',quality=80)
- o=f"{AROOT}/o/c/{d['id']}.png"
- if not os.path.exists(o): os.link(f"{R}/costume/{d['原寸']}",o)
-def ca(d):
- o=f"{D}/a/m/{d['id']}.webp"
- if not os.path.exists(o):
- im=Image.open(f"{R}/anime/{d['画像']}").convert('RGB'); im.thumbnail((1080,1620)); im.save(o,'WEBP',quality=80)
- o=f"{AROOT}/o/a/{d['id']}.png"
- if not os.path.exists(o): os.link(f"{R}/anime/{d['原寸']}",o)
-def cr(d):
- t=f"{AROOT}/r/t/{d['id']}.webp"
- if not os.path.exists(t): shutil.copy(f"{R}/portrait/{d['thumb']}",t)
- o=f"{D}/r/m/{d['id']}.webp"
- if not os.path.exists(o):
- im=Image.open(f"{R}/portrait/{d['full']}").convert('RGB'); im.thumbnail((1080,1350)); im.save(o,'WEBP',quality=80)
- o=f"{AROOT}/o/r/{d['id']}.png"
- if not os.path.exists(o): os.link(f"{R}/portrait/{d['full']}",o)
-for x in ['p/t','c/m','o/p','o/c','a/m','o/a','r/t','r/m','o/r','e/t','e/i','o/e','y/t','y/i','o/y','s/t','s/i','o/s','l/t','l/i','o/l','t/t','t/i','o/t','f/t','f/i','o/f']: os.makedirs(f'{AROOT if x.endswith("/t") or x.startswith("o/") else D}/{x}',exist_ok=True)
-if AHOST:
- # 分离模式下缩略图/原图改写到 dist-assets,删掉 dist 里上一轮单站构建残留的旧文件,
- # 否则主站仍含这批文件、文件数压不回 2 万上限(Codex review on PR #4)
- for _d in ['p/t','c/t','a/t','r/t','e/t','y/t','s/t','l/t','t/t','f/t','o']:
- shutil.rmtree(f'{D}/{_d}',ignore_errors=True)
-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:
- 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']
-if AHOST:
- # 图片自存模式:深度图已全量存入图片域名下的 d/ 前缀(上游 /thumbs/→/d/thumbs/、/img/→/d/img/),
- # 条目地址改走自存,不再热链原站(原站不可用时前端会整批找不到图);署名用的裸域名链接不在替换范围内。
- DJ=DJ.replace('https://ai-pose-depth-gallery.pages.dev/thumbs/',AHOST+'/d/thumbs/').replace('https://ai-pose-depth-gallery.pages.dev/img/',AHOST+'/d/img/')
-for src,rel in _dc['copies']:
- dest=f'{D}/{rel}'; os.makedirs(os.path.dirname(dest),exist_ok=True); shutil.copyfile(src,dest)
-exec(open('post.py').read())
-print(len(poses),len(cos),len(acs),len(_dc['payload']['items']),'| new:',len(EXP),len(HAI),len(DYN),len(SCE),len(LIG),len(PRO),len(FUR))
+PAIR_CAT_FIXES = {
+ 'pair60_P031': '坐位',
+ 'pair60_P053': '立位贴身',
+ 'pair60_P055': '侧位',
+ 'pair60_P058': '贴脸',
+}
+
+ADULT_LINES = {'双人互动', '全身·性感'}
+ADULT_CATS = {'挤胸·乳沟', '性感·大胆'}
+ADULT_COS = {'内衣', '性感'}
+
+PORTRAIT_HAIR = {
+ 'ショート': ('短发', 'short hair'),
+ 'ミディアム': ('中长发', 'medium-length hair'),
+ 'セミロング': ('半长发', 'shoulder-length hair'),
+ 'ロング': ('长发', 'long hair'),
+}
+
+PORTRAIT_SECTION = {
+ 'face': ('正脸', 'front-facing head-and-shoulders portrait, plain light grey background, soft even lighting'),
+ 'styling': ('生活照', 'casual selfie-style lifestyle photo, indoor natural light'),
+}
+
+VIEW_MAP = {
+ 'front': ('正面', 'front view'),
+ 'diag': ('斜侧', 'three-quarter view'),
+ 'side': ('侧面', 'side view'),
+ 'back': ('背面', 'back view'),
+ 'above': ('俯视', 'high angle, from above'),
+ 'below': ('仰视', 'low angle, from below'),
+ 'eye': ('平视', 'eye-level view'),
+ 'tq': ('3/4 侧', 'three-quarter view'),
+}
+
+
+def _dump_json(obj):
+ return json.dumps(obj, ensure_ascii=False, separators=(',', ':'))
+
+
+def _collect_origins(obj):
+ origins = set()
+
+ def walk(node):
+ if isinstance(node, dict):
+ for value in node.values():
+ walk(value)
+ elif isinstance(node, list):
+ for value in node:
+ walk(value)
+ elif isinstance(node, str) and node.startswith('https://'):
+ origins.add('/'.join(node.split('/')[:3]))
+
+ walk(obj)
+ return origins
+
+
+def _load_view_module(raw_dir, sub, prefix):
+ path = f'{raw_dir}/{sub}/data.json'
+ if not os.path.exists(path):
+ return []
+ out = []
+ with open(path) as fh:
+ records = json.load(fh)
+ for it in records:
+ item = {
+ 'id': it['id'],
+ 'cat': it['cat'],
+ 'ti': it['ti'],
+ 'zh': it['zh'],
+ 'en': it['en'],
+ 'ja': it.get('ja', ''),
+ 'line': it['line'],
+ 'lineEn': it['lineEn'],
+ 'no': it['id'],
+ 'angles': [
+ {
+ 'zh': VIEW_MAP[view][0],
+ 'en': VIEW_MAP[view][1],
+ 't': f'{prefix}/t/{it["id"]}_{view}.webp',
+ 'i': f'{prefix}/i/{it["id"]}_{view}.webp',
+ 'o': f'o/{prefix}/{it["id"]}_{view}.webp',
+ '_3': filename,
+ '_9': filename,
+ }
+ for view, filename in it['views'].items()
+ ],
+ }
+ item.update(it.get('extra') or {})
+ out.append(item)
+ return out
+
+
+def _copy_new_module(raw_dir, dist_dir, asset_root, sub, items):
+ for it in items:
+ for angle in it['angles']:
+ f3, f9 = angle.pop('_3'), angle.pop('_9')
+ for src_file, tier, dest in (
+ (f3, 'w300', f'{asset_root}/{angle["t"]}'),
+ (f9, 'w900', f'{dist_dir}/{angle["i"]}'),
+ (f9, 'w900', f'{asset_root}/{angle["o"]}'),
+ ):
+ if not os.path.exists(dest):
+ shutil.copy(f'{raw_dir}/{sub}/files/{tier}/{src_file}', dest)
+
+
+def _convert_pose(raw_dir, dist_dir, asset_root, record):
+ thumb = f"{asset_root}/p/t/{record['id']}.webp"
+ if not os.path.exists(thumb):
+ im = Image.open(f"{raw_dir}/pose/{record['サムネ']}").convert('RGB')
+ im.save(thumb, 'WEBP', quality=80, method=6)
+ orig = f"{asset_root}/o/p/{record['id']}.png"
+ if not os.path.exists(orig):
+ os.link(f"{raw_dir}/pose/{record['原寸']}", orig)
+ mid = f"{dist_dir}/p/i/{record['id']}.webp"
+ if not os.path.exists(mid):
+ im = Image.open(f"{raw_dir}/pose/{record['原寸']}").convert('RGB')
+ im.thumbnail((1200, 1200))
+ im.save(mid, 'WEBP', quality=82)
+
+
+def _convert_costume(raw_dir, dist_dir, asset_root, folder, prefix, record):
+ mid = f"{dist_dir}/{prefix}/m/{record['id']}.webp"
+ if not os.path.exists(mid):
+ im = Image.open(f"{raw_dir}/{folder}/{record['画像']}").convert('RGB')
+ im.thumbnail((1080, 1620))
+ im.save(mid, 'WEBP', quality=80)
+ orig = f"{asset_root}/o/{prefix}/{record['id']}.png"
+ if not os.path.exists(orig):
+ os.link(f"{raw_dir}/{folder}/{record['原寸']}", orig)
+
+
+def _convert_portrait(raw_dir, dist_dir, asset_root, record):
+ thumb = f"{asset_root}/r/t/{record['id']}.webp"
+ if not os.path.exists(thumb):
+ shutil.copy(f"{raw_dir}/portrait/{record['thumb']}", thumb)
+ mid = f"{dist_dir}/r/m/{record['id']}.webp"
+ if not os.path.exists(mid):
+ im = Image.open(f"{raw_dir}/portrait/{record['full']}").convert('RGB')
+ im.thumbnail((1080, 1350))
+ im.save(mid, 'WEBP', quality=80)
+ orig = f"{asset_root}/o/r/{record['id']}.png"
+ if not os.path.exists(orig):
+ os.link(f"{raw_dir}/portrait/{record['full']}", orig)
+
+
+def _check_archives(raw_dir):
+ missing = []
+ for archive in EXTENSION_ARCHIVES:
+ path = os.path.join(raw_dir, 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)
+ return missing
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description='Build the PoseWear static site')
+ parser.add_argument('--allow-partial', action='store_true', help='allow missing extension archives for local development')
+ options = parser.parse_args(argv)
+
+ raw_dir = RAW_DIR
+ dist_dir = DIST_DIR
+ asset_host = ASSET_HOST
+ assets_dist_dir = ASSETS_DIST_DIR
+ asset_root = ASSET_ROOT
+
+ missing = _check_archives(raw_dir)
+ if missing and not options.allow_partial:
+ parser.error('Missing or empty extension archives: ' + ', '.join(missing) + '. See AGENTS.md or use --allow-partial for local development.')
+
+ if asset_host:
+ os.makedirs(assets_dist_dir, exist_ok=True)
+
+ with open('tr_pose.txt') as fh:
+ tr_pose = {line.split('|')[0]: line.split('|')[1:] for line in fh.read().strip().split('\n')}
+ with open(f'{raw_dir}/pose/data.json') as fh:
+ pd = json.load(fh)['D']
+ with open(f'{raw_dir}/costume/data.json') as fh:
+ cd = json.load(fh)['D']
+ with open(f'{raw_dir}/anime/data.json') as fh:
+ ad = json.load(fh)['D']
+
+ poses = {}
+ for d in pd:
+ key = d['id'].rsplit('_', 1)[0]
+ zh, en = tr_pose[d['ポーズ名']]
+ entry = poses.setdefault(key, {
+ 'id': key,
+ 'no': d['ポーズ番号'],
+ 'line': LINE[d['系統']][0],
+ 'cat': CAT[d['分類']],
+ 'ja': d['ポーズ名'],
+ 'zh': zh,
+ 'en': en,
+ 'lineEn': LINE[d['系統']][1],
+ 'angles': [],
+ })
+ ang = ANG[d['アングル']]
+ entry['angles'].append({
+ 'zh': ang[0],
+ 'en': ang[1],
+ 't': 'p/t/' + d['id'] + '.webp',
+ 'i': 'p/i/' + d['id'] + '.webp',
+ 'o': 'o/p/' + d['id'] + '.png',
+ })
+
+ cos = [
+ {
+ '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': 'c/t/' + os.path.basename(d['サムネ']),
+ 'm': 'c/m/' + d['id'] + '.webp',
+ 'i': 'c/i/' + os.path.basename(d['画像']),
+ 'o': 'o/c/' + d['id'] + '.png',
+ }
+ for d in cd
+ ]
+ 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',
+ }
+ for d in ad
+ ]
+
+ for key, cat_name in PAIR_CAT_FIXES.items():
+ poses[key]['cat'] = cat_name
+
+ for p in poses.values():
+ if p['line'] in ADULT_LINES or p['cat'] in ADULT_CATS:
+ p['a'] = 1
+ for c in cos:
+ if c['cat'] in ADULT_COS:
+ c['a'] = 1
+ for c in acs:
+ if c['cat'] in ADULT_COS:
+ c['a'] = 1
+
+ os.makedirs(dist_dir, exist_ok=True)
+ partial_marker = os.path.join(dist_dir, '.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 filename in os.listdir('src'):
+ shutil.copy('src/' + filename, dist_dir)
+
+ # 安全内容排在前面(默认落地页无露骨内容)
+ poses_list = sorted(poses.values(), key=lambda p: p.get('a', 0))
+
+ # CharaDB 服装 440 条并入动画服装(元数据自存、图片热链原站,见 scripts/prep-modules.py)
+ cdb_path = f'{raw_dir}/charadb/outfits.json'
+ if os.path.exists(cdb_path):
+ with open(cdb_path) as fh:
+ for d in json.load(fh):
+ item = {
+ 'id': d['id'],
+ 'cat': d['cat'],
+ 'catEn': d['catEn'],
+ 'kw': d['kw'],
+ 'zh': d['name'] + ',' + '、'.join(d['tagsZh'][1:]) + '。',
+ 'en': d['kw'],
+ 'ti': d['name'],
+ 't': d['t'],
+ 'm': d['m'],
+ 'i': d['i'],
+ 'o': '',
+ 'ext': 1,
+ }
+ if d.get('sens'):
+ item['a'] = 1
+ acs.append(item)
+
+ # ---------- 人像库(AI Portrait Gallery,CC0,@agi_aibusi)----------
+ with open(f'{raw_dir}/portrait/images.js') as fh:
+ rt = fh.read()
+ rd = json.loads(rt[rt.index('['):rt.rindex(']') + 1])
+ with open(f'{raw_dir}/portrait/ranking.js') as fh:
+ rk_text = fh.read()
+ rk = json.loads(rk_text[rk_text.index('{'):rk_text.rindex('}') + 1])
+ with open('tr_portrait.txt') as fh:
+ tr_portrait = {line.split('|')[0]: line.split('|')[1:] for line in fh.read().strip().split('\n')}
+
+ rank_all = {item_id: idx + 1 for idx, item_id in enumerate(rk['top']['総合'])}
+ rank_cat = {}
+ for cat_key, entries in rk['top'].items():
+ if cat_key != '総合':
+ for idx, item_id in enumerate(entries):
+ rank_cat[item_id] = idx + 1
+
+ portraits = []
+ seq = {}
+ for d in rd:
+ sec = PORTRAIT_SECTION[d['section']]
+ hair = PORTRAIT_HAIR[d['hair']]
+ sz, se = tr_portrait.get(d['style'], ['', ''])
+ seq[d['section']] = seq.get(d['section'], 0) + 1
+ no = ('F' if d['section'] == 'face' else 'S') + str(seq[d['section']]).zfill(3)
+ zh = f"一位亚洲年轻女性,{hair[0]}{',' + sz if sz else ''},{'正面半身肖像,浅灰纯色背景,柔和均匀的光线' if d['section'] == 'face' else '自拍风生活照,室内自然光'}。作为人物面部参考,保持五官和脸型一致。"
+ en = f"young Asian woman, {hair[1]}{', ' + se if se else ''}, {sec[1]}, consistent facial features, face reference"
+ item = {
+ 'id': d['id'],
+ 'no': no,
+ 'sec': sec[0],
+ 'len': hair[0],
+ 'st': sz,
+ 'ti': sz or f'{hair[0]} · {sec[0]}',
+ 'zh': zh,
+ 'en': en,
+ 'ja': d['style'] or d['hair'],
+ 't': 'r/t/' + d['id'] + '.webp',
+ 'm': 'r/m/' + d['id'] + '.webp',
+ 'i': 'r/m/' + d['id'] + '.webp',
+ 'o': 'o/r/' + d['id'] + '.png',
+ 'w': d['w'],
+ 'h': d['h'],
+ }
+ if d['id'] in rank_all:
+ item['rk'] = rank_all[d['id']]
+ if d['id'] in rank_cat:
+ item['rc'] = rank_cat[d['id']]
+ portraits.append(item)
+
+ # ---------- 新模块(数据由 scripts/prep-modules.py 从本地档案生成到 assets-raw,构建不访问外网)----------
+ exp_items = _load_view_module(raw_dir, 'expression', 'e')
+ dyn_items = _load_view_module(raw_dir, 'dynasty', 'y')
+ sce_items = _load_view_module(raw_dir, 'scene', 's')
+ lig_items = _load_view_module(raw_dir, 'light', 'l')
+ pro_items = _load_view_module(raw_dir, 'prop', 't')
+ fur_items = _load_view_module(raw_dir, 'furn', 'f')
+ hair_path = f'{raw_dir}/charadb/hair.json'
+ hair_items = json.load(open(hair_path)) if os.path.exists(hair_path) else []
+
+ # 热链图片的源站(CharaDB 等):post.py 据此放行 CSP 的 img-src/connect-src,
+ # 否则浏览器会拦截全部热链图片(2026-11-23 发型库全图加载失败的根因)。
+ hotlink_origins = set()
+ for rel in ('charadb/outfits.json', 'charadb/hair.json'):
+ full = f'{raw_dir}/{rel}'
+ if os.path.exists(full):
+ with open(full) as fh:
+ hotlink_origins |= _collect_origins(json.load(fh))
+ hotlink_origins = sorted(hotlink_origins)
+
+ new_modules = [
+ ('expression', exp_items),
+ ('dynasty', dyn_items),
+ ('scene', sce_items),
+ ('light', lig_items),
+ ('prop', pro_items),
+ ('furn', fur_items),
+ ]
+
+ if os.path.exists(f'{dist_dir}/data.js'):
+ os.remove(f'{dist_dir}/data.js')
+ for src_sub, dst_sub in (('costume/thumbs', 'c/t'), ('costume/img', 'c/i'), ('anime/thumbs', 'a/t'), ('anime/img', 'a/i')):
+ shutil.copytree(f'{raw_dir}/{src_sub}', f'{asset_root if dst_sub.endswith("/t") else dist_dir}/{dst_sub}', dirs_exist_ok=True)
+ os.makedirs(f'{dist_dir}/p/i', exist_ok=True)
+
+ dirs = [
+ 'p/t', 'c/m', 'o/p', 'o/c', 'a/m', 'o/a', 'r/t', 'r/m', 'o/r',
+ 'e/t', 'e/i', 'o/e', 'y/t', 'y/i', 'o/y', 's/t', 's/i', 'o/s',
+ 'l/t', 'l/i', 'o/l', 't/t', 't/i', 'o/t', 'f/t', 'f/i', 'o/f',
+ ]
+ for sub in dirs:
+ base = asset_root if sub.endswith('/t') or sub.startswith('o/') else dist_dir
+ os.makedirs(f'{base}/{sub}', exist_ok=True)
+
+ if asset_host:
+ # 分离模式下缩略图/原图改写到 dist-assets,删掉 dist 里上一轮单站构建残留的旧文件,
+ # 否则主站仍含这批文件、文件数压不回 2 万上限(Codex review on PR #4)
+ for stale in ('p/t', 'c/t', 'a/t', 'r/t', 'e/t', 'y/t', 's/t', 'l/t', 't/t', 'f/t', 'o'):
+ shutil.rmtree(f'{dist_dir}/{stale}', ignore_errors=True)
+
+ pose_thumbs = f'{asset_root}/p/t'
+ if os.path.exists(pose_thumbs):
+ for fname in os.listdir(pose_thumbs):
+ if fname.endswith('.jpg'):
+ os.remove(f'{pose_thumbs}/{fname}')
+
+ if asset_host:
+ with open(f'{assets_dist_dir}/_headers', 'w') as fh:
+ fh.write('/*\n Cache-Control: public, max-age=31536000, immutable\n Access-Control-Allow-Origin: *\n/o/*\n Content-Disposition: attachment\n')
+
+ with ProcessPoolExecutor() as pool:
+ for fn, records in (
+ (partial(_convert_pose, raw_dir, dist_dir, asset_root), pd),
+ (partial(_convert_costume, raw_dir, dist_dir, asset_root, 'costume', 'c'), cd),
+ (partial(_convert_costume, raw_dir, dist_dir, asset_root, 'anime', 'a'), ad),
+ (partial(_convert_portrait, raw_dir, dist_dir, asset_root), rd),
+ ):
+ list(pool.map(fn, records))
+
+ for sub, items in new_modules:
+ _copy_new_module(raw_dir, dist_dir, asset_root, sub, items)
+
+ # 深度姿势:只解析素材包里的文本,热链包不复制图片(见 depthpack.py)
+ depth_cat = depthpack.catalog()
+ dj = _dump_json(depth_cat['payload'])
+ depth_origins = depth_cat['origins']
+ if asset_host:
+ # 图片自存模式:深度图已全量存入图片域名下的 d/ 前缀(上游 /thumbs/→/d/thumbs/、/img/→/d/img/),
+ # 条目地址改走自存,不再热链原站(原站不可用时前端会整批找不到图);署名用的裸域名链接不在替换范围内。
+ dj = (
+ dj.replace('https://ai-pose-depth-gallery.pages.dev/thumbs/', asset_host + '/d/thumbs/')
+ .replace('https://ai-pose-depth-gallery.pages.dev/img/', asset_host + '/d/img/')
+ )
+ for src_file, rel in depth_cat['copies']:
+ dest = f'{dist_dir}/{rel}'
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
+ shutil.copyfile(src_file, dest)
+
+ # 重要:_copy_new_module 已 pop 掉 _3/_9 临时字段后再序列化新模块 JSON
+ catalogs = {
+ 'poses.json': _dump_json(poses_list),
+ 'costumes.json': _dump_json(cos),
+ 'anime.json': _dump_json(acs),
+ 'portraits.json': _dump_json(portraits),
+ 'depths.json': dj,
+ 'expressions.json': _dump_json(exp_items),
+ 'hair.json': _dump_json(hair_items),
+ 'dynasties.json': _dump_json(dyn_items),
+ 'scenes.json': _dump_json(sce_items),
+ 'lights.json': _dump_json(lig_items),
+ 'props.json': _dump_json(pro_items),
+ 'furniture.json': _dump_json(fur_items),
+ }
+
+ ctx = {
+ 'raw_dir': raw_dir,
+ 'dist_dir': dist_dir,
+ 'src_dir': 'src',
+ 'functions_dir': 'functions',
+ 'asset_host': asset_host,
+ 'catalogs': catalogs,
+ 'data': {
+ 'poses': poses,
+ 'poses_list': poses_list,
+ 'costumes': cos,
+ 'anime': acs,
+ 'portraits': portraits,
+ },
+ 'depth_origins': depth_origins,
+ 'hotlink_origins': hotlink_origins,
+ }
+ post.run(ctx)
+ print(
+ len(poses), len(cos), len(acs), len(depth_cat['payload']['items']),
+ '| new:', len(exp_items), len(hair_items), len(dyn_items), len(sce_items), len(lig_items), len(pro_items), len(fur_items),
+ )
+
+
+if __name__ == '__main__':
+ main()
diff --git a/post.py b/post.py
index fe0c7e1..ea7f4b5 100644
--- a/post.py
+++ b/post.py
@@ -1,144 +1,248 @@
-# v10 构建后处理:哈希资源、静态详情页、SEO 文件、_headers(由 build.py exec)
-SITE=os.environ.get('POSEWEAR_SITE','https://posewear.pages.dev').rstrip('/') # 部署到自己的域名时改这里
-AH=os.environ.get('POSEWEAR_ASSET_HOST','').rstrip('/') # 分离部署时缩略图/原图所在站(见 build.py 的 AHOST)
-WAT=os.environ.get('POSEWEAR_WA_TOKEN','').strip() # Cloudflare Web Analytics 站点令牌(公开值,随页面下发);设了才注入统计脚本并放行其 CSP 域名
-def TU(p): return p if p.startswith('http') else (AH+'/'+p if AH else '/'+p) # 缩略图相对引用
-def TS(p): return p if p.startswith('http') else (AH+'/'+p if AH else SITE+'/'+p) # 缩略图绝对引用(JSON-LD)
-h8=lambda b:hashlib.sha256(b if isinstance(b,bytes) else b.encode()).hexdigest()[:10]
-os.makedirs(f'{D}/assets',exist_ok=True)
-for f in os.listdir(f'{D}/assets'): os.remove(f'{D}/assets/{f}')
-A={}
-def put(name,data):
- b=data.encode() if isinstance(data,str) else data
- base,ext=name.rsplit('.',1);n=f'assets/{base}.{h8(b)}.{ext}';open(f'{D}/{n}','wb').write(b);A[name]=n;return n
-put('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)
-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='';","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)
-idx=open('src/index.html').read()
-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 CLIENT_FILES:
- if os.path.exists(f'{D}/{f}'): os.remove(f'{D}/{f}')
-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)
+"""Build post-processor: asset fingerprinting, index.html/sw.js assembly, 404, _headers/CSP, and SEO."""
+
import base64
-inl=re.findall(r'<script>(.*?)</script>',idx,re.S)
-SH=' '.join("'sha256-"+base64.b64encode(hashlib.sha256(x.encode()).digest()).decode()+"'" for x in inl)
-# ---------- 静态详情页 ----------
-for d in ['pose','costume','anime','portrait']:
- if os.path.exists(f'{D}/{d}'): shutil.rmtree(f'{D}/{d}')
-THEME_HEAD = f'<meta name="theme-color" content="#ffffff"><script src="/{A["theme.js"]}"></script>'
+import hashlib
+import json
+import os
+import re
+import shutil
+
+import seo
+
+
+CLIENT_FILES = [
+ 'theme.js',
+ 'style.css',
+ 'i18n.js',
+ 'catalog.js',
+ 'references.js',
+ 'palette.js',
+ 'app.js',
+ 'sketch.js',
+ 'command-palette.js',
+ 'zip.js',
+ 'extras.js',
+ 'image-providers.js',
+ 'board-export.js',
+ 'studio.js',
+ 'history.js',
+]
+
+CATALOG_FILES = (
+ 'poses.json',
+ 'costumes.json',
+ 'anime.json',
+ 'portraits.json',
+ 'depths.json',
+ 'expressions.json',
+ 'hair.json',
+ 'dynasties.json',
+ 'scenes.json',
+ 'lights.json',
+ 'props.json',
+ 'furniture.json',
+)
+
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: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}
-.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):
- P=kind=='pose'
- if kind=='portrait':
- ttl=f"{it['ti']} · 人像脸模参考";img=it['m'];w,h=1080,round(1080*it['h']/it['w']);th=it['t']
- desc=f"{it['sec']} · {it['len']}{','+it['st'] if it['st'] else ''}。AI 生成的虚构人物,可作 AI 绘图/视频的人物面部参考,CC0。";meta=f"{it['sec']} · {it['len']} · 编号 {it['no']}";en=it['en']
- elif P:
- ttl=f"{it['zh']} · {it['cat']}姿势参考";img=it['angles'][0]['i'];w,h=900,1200;th=it['angles'][0]['t']
- desc=f"{it['zh']}。{it['line']} · {it['cat']},共 {len(it['angles'])} 个拍摄角度({'、'.join(a['zh'] for a in it['angles'])})。附中英文提示词,可直接用于绘图或出图。"
- meta=f"{it['line']} · {it['cat']} · 编号 {it['no']}";en=f"{it['en']}, {it['lineEn']}"
- else:
- ttl=f"{it['ti']} · {it['cat']}穿搭参考";img=it['m'];w,h=1080,1620;th=it['t']
- desc=it['zh'];meta=f"{it['cat']} · 编号 {it['id']}";en=it['en']
- url=f"{SITE}/{kind}/{it['id']}/"
- ld={"@context":"https://schema.org","@type":"ImageObject","name":ttl,"description":desc,"contentUrl":f"{SITE}/{img}","thumbnailUrl":f"{TS(th)}","url":url,"width":w,"height":h,"isPartOf":{"@type":"WebSite","name":"衣姿 PoseWear","url":SITE+'/'},"creditText":"AI Pose Gallery / AI Costume Gallery (@giaaibusi)"}
- rl=''.join(f'<li><a href="/{kind}/{r["id"]}/"><img src="{TU(r["angles"][0]["t"] if P else r["t"])}" alt="{E(r["zh"] if P else r["ti"])}" width="{300 if P else 360 if kind=="costume" else 400}" height="{400 if P else 540 if kind=="costume" else 500}" loading="lazy">{E(r["zh"] if P else r["ti"])}</a></li>' for r in rel)
- lab={'pose':'姿势库','costume':'服装库','portrait':'人像库'}[kind]
- 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">{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 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">{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 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: http://localhost:* http://127.0.0.1:*; "
- # 本机回环 http:自定义服务商直连本机网关(如本地 ComfyUI/OpenAI 兼容网关)时,
- # 浏览器直接 fetch http://127.0.0.1:端口;此前 connect-src 只有 https: 会拦掉。
- # upgrade-insecure-requests 不升级回环地址(已是潜在可信源),故只需放行本机 http。
- "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")
-IMM=' Cache-Control: public, max-age=31536000, immutable\n'
-# Pages Functions 必须位于部署目录内才会随 wrangler pages deploy 一起发布(曾因只传静态产物导致 /api/proxy 丢失,见 issue #7)
-if os.path.isdir('functions'):
- shutil.rmtree(f'{D}/functions',ignore_errors=True); shutil.copytree('functions',f'{D}/functions')
-open(f'{D}/_headers','w').write(f'''/*
- Content-Security-Policy: {CSP}
- X-Content-Type-Options: nosniff
- Referrer-Policy: strict-origin-when-cross-origin
- X-Frame-Options: DENY
- Strict-Transport-Security: max-age=31536000; includeSubDomains
- Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), usb=(), interest-cohort=()
- 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-*
- Cache-Control: public, max-age=86400
-/og.png
- Cache-Control: public, max-age=86400
-/sw.js
- Cache-Control: no-cache
-/
- Cache-Control: public, max-age=0, must-revalidate
-/index.html
- Cache-Control: public, max-age=0, must-revalidate
-/pose/*
- Cache-Control: public, max-age=600
-/costume/*
- Cache-Control: public, max-age=600
-/anime/*
- Cache-Control: public, max-age=600
-/portrait/*
- Cache-Control: public, max-age=600
-''')
-exec(open('seo.py').read())
+
+BASE_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}\n'
+ '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}\n'
+ '.mk{width:26px;height:26px;color:#ff2442;display:grid;place-items:center}.mk svg{width:26px;height:26px}\n'
+ 'main{max-width:1040px;margin:0 auto;padding:24px 20px;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:32px}\n'
+ '@media(max-width:760px){main{grid-template-columns:1fr}}\n'
+ '.im img{width:100%;height:auto;border-radius:16px;background:var(--surface);display:block}\n'
+ '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}\n'
+ '.box{background:var(--surface);border-radius:14px;padding:14px 16px;margin:14px 0}.box small{color:var(--muted)}\n'
+ '.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}\n'
+ '.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}\n'
+ 'footer{text-align:center;color:var(--muted);font-size:12px;padding:30px 20px;border-top:1px solid var(--edge)}\n'
+ 'h1{overflow-wrap:anywhere}\n'
+ '.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>'
+)
+
+IMMUTABLE_PATHS = ('/assets/*', '/p/*', '/c/*', '/a/*', '/r/*', '/e/*', '/y/*', '/s/*', '/l/*', '/t/*', '/f/*', '/o/*')
+
+
+def _hash10(data):
+ raw = data if isinstance(data, bytes) else data.encode()
+ return hashlib.sha256(raw).hexdigest()[:10]
+
+
+def _build_csp(inline_hashes, img_origins, wa_token):
+ script_src = "'self' " + inline_hashes + (' https://static.cloudflareinsights.com' if wa_token else '')
+ img_src = ' '.join(img_origins)
+ # Local loopback http is allowed so custom/local engines (e.g. ComfyUI, sd.cpp, OpenAI-compatible
+ # gateways on 127.0.0.1/localhost) can be fetched directly from the browser without CSP blocking.
+ return (
+ f"default-src 'self'; script-src {script_src}; style-src 'self' 'unsafe-inline'; "
+ f"img-src {img_src}; font-src 'self' data:; "
+ "connect-src 'self' data: blob: https: http://localhost:* http://127.0.0.1:*; "
+ "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"
+ )
+
+
+def run(ctx):
+ """Fingerprint assets, rewrite index.html & sw.js, emit 404/_headers/functions, then run seo.run."""
+ dist_dir = ctx['dist_dir']
+ src_dir = ctx.get('src_dir', 'src')
+ functions_dir = ctx.get('functions_dir', 'functions')
+ site = ctx.get('site', os.environ.get('POSEWEAR_SITE', 'https://posewear.pages.dev')).rstrip('/')
+ asset_host = ctx.get('asset_host', os.environ.get('POSEWEAR_ASSET_HOST', '')).rstrip('/')
+ wa_token = ctx.get('wa_token', os.environ.get('POSEWEAR_WA_TOKEN', '')).strip()
+ catalogs = ctx['catalogs']
+ depth_origins = list(ctx.get('depth_origins', ()))
+ hotlink_origins = list(ctx.get('hotlink_origins', ()))
+
+ assets_dir = os.path.join(dist_dir, 'assets')
+ os.makedirs(assets_dir, exist_ok=True)
+ for name in os.listdir(assets_dir):
+ os.remove(os.path.join(assets_dir, name))
+
+ assets = {}
+
+ def put(name, data):
+ blob = data.encode() if isinstance(data, str) else data
+ base, ext = name.rsplit('.', 1)
+ rel = f'assets/{base}.{_hash10(blob)}.{ext}'
+ with open(os.path.join(dist_dir, rel), 'wb') as fh:
+ fh.write(blob)
+ assets[name] = rel
+ return rel
+
+ # 1. Write all 12 fingerprinted catalog JSON manifests
+ for filename in CATALOG_FILES:
+ payload = catalogs[filename]
+ if not isinstance(payload, (str, bytes)):
+ payload = json.dumps(payload, ensure_ascii=False, separators=(',', ':'))
+ put(filename, payload)
+
+ # 2. Fingerprint client scripts & styles (inject asset host & manifest hashes into app.js)
+ for filename in CLIENT_FILES:
+ if filename != 'app.js':
+ with open(os.path.join(src_dir, filename), 'rb') as fh:
+ put(filename, fh.read())
+
+ with open(os.path.join(src_dir, 'app.js')) as fh:
+ app_js = fh.read()
+ if asset_host:
+ app_js = app_js.replace("const AH='';", f"const AH={repr(asset_host + '/')};")
+ for name, rel in assets.items():
+ if name.endswith('.json'):
+ app_js = app_js.replace(repr(name), repr('/' + rel))
+ put('app.js', app_js)
+
+ # 3. Assemble index.html with hashed assets and remove unhashed duplicates from dist/
+ with open(os.path.join(src_dir, 'index.html')) as fh:
+ idx = fh.read()
+ for filename in CLIENT_FILES:
+ idx = idx.replace(f'"{filename}"', f'"/{assets[filename]}"')
+ idx = idx.replace('href="poses.json"', f'href="/{assets["poses.json"]}"')
+ if wa_token:
+ idx = idx.replace(
+ '</body>',
+ f'<script defer src="https://static.cloudflareinsights.com/beacon.min.js" data-cf-beacon=\'{{"token": "{wa_token}"}}\'></script></body>',
+ )
+ with open(os.path.join(dist_dir, 'index.html'), 'w') as fh:
+ fh.write(idx)
+
+ for filename in CLIENT_FILES:
+ unhashed = os.path.join(dist_dir, filename)
+ if os.path.exists(unhashed):
+ os.remove(unhashed)
+
+ # 4. Assemble Service Worker with version hash and fingerprinted precache list
+ with open(os.path.join(src_dir, 'sw.js')) as fh:
+ sw = fh.read()
+ version = 'posewear-' + _hash10(sw + idx + ''.join(assets.values()))
+ sw = sw.replace("'posewear-development'", repr(version))
+ precache = ['/', '/favicon.svg'] + ['/' + assets[f] for f in CLIENT_FILES + ['poses.json', 'depths.json']]
+ sw = re.sub(r'const PRECACHE = .*?;', 'const PRECACHE = ' + json.dumps(precache) + ';', sw, count=1)
+ with open(os.path.join(dist_dir, 'sw.js'), 'w') as fh:
+ fh.write(sw)
+
+ # 5. Compute inline script SHA-256 CSP hashes, clean old static dirs, write 404.html
+ inline_scripts = re.findall(r'<script>(.*?)</script>', idx, re.S)
+ inline_hashes = ' '.join(
+ "'sha256-" + base64.b64encode(hashlib.sha256(script.encode()).digest()).decode() + "'"
+ for script in inline_scripts
+ )
+
+ for sub in ('pose', 'costume', 'anime', 'portrait'):
+ target = os.path.join(dist_dir, sub)
+ if os.path.exists(target):
+ shutil.rmtree(target)
+
+ theme_head = f'<meta name="theme-color" content="#ffffff"><script src="/{assets["theme.js"]}"></script>'
+ not_found_html = (
+ '<!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">'
+ f'<link rel="icon" href="/favicon.svg" type="image/svg+xml">{theme_head}<style>{BASE_CSS}\n'
+ '.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>'
+ f'<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 secondary" href="/#costume">看看服装库</a></div></body></html>'
+ )
+ with open(os.path.join(dist_dir, '404.html'), 'w') as fh:
+ fh.write(not_found_html)
+
+ # 6. Copy Pages Functions into dist/ so wrangler pages deploy includes /api/proxy (issue #7)
+ if functions_dir and os.path.isdir(functions_dir):
+ dest_fn = os.path.join(dist_dir, 'functions')
+ shutil.rmtree(dest_fn, ignore_errors=True)
+ shutil.copytree(functions_dir, dest_fn)
+
+ # 7. Write _headers (security headers + CSP + cache lifetimes)
+ img_origins = ["'self'", 'data:', 'blob:'] + depth_origins + hotlink_origins + ([asset_host] if asset_host else [])
+ csp = _build_csp(inline_hashes, img_origins, wa_token)
+ imm_block = ''.join(f'{path}\n Cache-Control: public, max-age=31536000, immutable\n' for path in IMMUTABLE_PATHS)
+ headers = (
+ f'/*\n'
+ f' Content-Security-Policy: {csp}\n'
+ f' X-Content-Type-Options: nosniff\n'
+ f' Referrer-Policy: strict-origin-when-cross-origin\n'
+ f' X-Frame-Options: DENY\n'
+ f' Strict-Transport-Security: max-age=31536000; includeSubDomains\n'
+ f' Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), usb=(), interest-cohort=()\n'
+ f' Cross-Origin-Opener-Policy: same-origin\n'
+ f'{imm_block}'
+ '/icon-*\n Cache-Control: public, max-age=86400\n'
+ '/og.png\n Cache-Control: public, max-age=86400\n'
+ '/sw.js\n Cache-Control: no-cache\n'
+ '/\n Cache-Control: public, max-age=0, must-revalidate\n'
+ '/index.html\n Cache-Control: public, max-age=0, must-revalidate\n'
+ '/pose/*\n Cache-Control: public, max-age=600\n'
+ '/costume/*\n Cache-Control: public, max-age=600\n'
+ '/anime/*\n Cache-Control: public, max-age=600\n'
+ '/portrait/*\n Cache-Control: public, max-age=600\n'
+ )
+ with open(os.path.join(dist_dir, '_headers'), 'w') as fh:
+ fh.write(headers)
+
+ # 8. Delegate static SEO pages, sitemaps, robots.txt and SSR home fragment to seo.run
+ seo_ctx = {
+ **ctx,
+ 'site': site,
+ 'asset_host': asset_host,
+ 'assets': assets,
+ 'theme_head': theme_head,
+ 'base_css': BASE_CSS,
+ 'logo': LOGO,
+ }
+ seo_summary = seo.run(seo_ctx)
+ return {'assets': assets, 'csp': csp, 'seo': seo_summary}
diff --git a/seo.py b/seo.py
index a51a594..417928b 100644
--- a/seo.py
+++ b/seo.py
@@ -1,52 +1,143 @@
-# SEO:静态首页内容、分类/标签页、详情页、英文版、分站点地图、IndexNow 密钥(由 post.py exec)
-import datetime,time
-TODAY=datetime.date.today().isoformat()
-MT=lambda p:datetime.date.fromtimestamp(os.path.getmtime(p)).isoformat()
-LM={'pose':MT(f'{R}/pose/data.json'),'costume':MT(f'{R}/costume/data.json'),'anime':MT(f'{R}/anime/data.json'),'portrait':MT(f'{R}/portrait/images.js')}
-for d in ['en','tag']:
- if os.path.exists(f'{D}/{d}'): shutil.rmtree(f'{D}/{d}')
-if not os.path.exists('indexnow.key'):
- import secrets;open('indexnow.key','w').write(secrets.token_hex(16))
-INK=open('indexnow.key').read().strip();open(f'{D}/{INK}.txt','w').write(INK)
-SRCS={'pose':('AI Pose Gallery','https://ai-pose-gallery.pages.dev','@giaaibusi','https://x.com/giaaibusi'),
- 'costume':('AI Costume Gallery','https://ai-costume-gallery.pages.dev','@giaaibusi','https://x.com/giaaibusi'),
- 'anime':('AI Costume Anime Gallery','https://ai-costume-anime-gallery.pages.dev','@giaaibusi','https://x.com/giaaibusi'),
- 'portrait':('AI Portrait Gallery','https://ai-portrait-gallery.pages.dev','@agi_aibusi','https://x.com/agi_aibusi')}
-CC0='https://creativecommons.org/publicdomain/zero/1.0/'
-# ---- 分类定义 ----
-PCAT={'可爱':('cute','Cute'),'坐姿':('sitting','Sitting'),'站姿':('standing','Standing'),'跪立':('kneeling','Kneeling'),'躺卧':('lying','Lying down'),'侧坐·鸭子坐':('side-sitting','Side sitting'),'蹲姿':('squatting','Squatting'),'前倾':('leaning-forward','Leaning forward'),'后仰':('leaning-back','Leaning back'),'扭身':('twisting','Twisting')}
-CCAT={'春季':('spring','Spring'),'夏季':('summer','Summer'),'秋季':('autumn','Autumn'),'冬季':('winter','Winter'),'派对礼服':('party','Party dresses'),'泳装':('swimsuit','Swimwear')}
-RSEC={'正脸':('front-face','Front face'),'生活照':('lifestyle','Lifestyle')}
-RLEN={'短发':('short-hair','Short hair'),'中长发':('medium-hair','Medium hair'),'半长发':('shoulder-length-hair','Shoulder-length hair'),'长发':('long-hair','Long hair')}
-COLS={'黑':'black','白':'white','红':'red','粉':'pink','蓝':'blue','藏青':'navy','棕':'brown','米':'beige','象牙白':'ivory','灰':'grey','绿':'green','黄':'yellow','紫':'purple','金':'gold','银':'silver','卡其':'khaki','酒红':'burgundy','橙':'orange','奶油':'cream','薄荷':'mint','薰衣草':'lavender','橄榄':'olive'}
-ITEMK={'连衣裙':'dress','半身裙':'skirt','短裤':'shorts','长裤':'trousers','牛仔裤':'jeans','大衣':'coat','夹克':'jacket','开衫':'cardigan','衬衫':'blouse','毛衣':'sweater','吊带':'camisole','泳衣':'swimsuit','靴子':'boots','高跟鞋':'high heels','运动鞋':'sneakers','凉鞋':'sandals','连裤袜':'tights','长筒袜':'stockings'}
-cz=lambda k:k if k.endswith('白') else k+'色'
-NA=sum(len(p['angles']) for p in poses.values());SP=[p for p in PL if not p.get('a')];NA_PUB=sum(len(p['angles']) for p in SP);SC=[c for c in cos if not c.get('a')];SA=[c for c in acs if not c.get('a') and not c.get('ext')];ANI_PUB=sum(1 for c in acs if not c.get('a'));SR=pors
-def ctags(c):
- w=' '+c['kw']+' ';e=' '+c['en'].replace(',',' ')+' '
- return [('item',z,ITEMK[z]) for z in ITEMK if ' '+ITEMK[z]+' ' in e]+[('col',z,COLS[z]) for z in COLS if ' '+COLS[z]+' ' in w]
-TAGS={}
-for c in SC:
- for k,z,en in ctags(c): TAGS.setdefault(en.replace(' ','-'),{'k':k,'zh':z if k=='item' else cz(z),'en':en,'L':[]})['L'].append(c)
-TAGS={s:t for s,t in TAGS.items() if len(t['L'])>=4}
-cap=lambda s:s[:1].upper()+s[1:]
-def en_title(kind,it):
- if kind=='pose': return cap(it['en'])
- if kind in ('costume','anime'):
- ps=[x.strip() for x in it['en'].split(',')][1:3];return cap(' + '.join(ps)) if ps else cap(it['en'])
- return cap(it['en'].split(',')[1].strip())+' portrait'
-def zh_title(kind,it): return it['zh'] if kind=='pose' else it['ti']
-def thumb(kind,it): return it['angles'][0]['t'] if kind=='pose' else it['t']
-def big(kind,it): return it['angles'][0]['i'] if kind=='pose' else it['m']
-TW={'pose':(300,400),'costume':(360,540),'anime':(360,540),'portrait':(400,500)}
-def catof(kind,it):
- if kind=='pose': return ('pose',PCAT[it['cat']][0],it['cat'],PCAT[it['cat']][1])
- if kind=='costume': return ('costume',CCAT[it['cat']][0],it['cat'],CCAT[it['cat']][1])
- if kind=='anime': return ('anime',CCAT[it['cat']][0],it['cat'],CCAT[it['cat']][1])
- return ('portrait',RLEN[it['len']][0],it['len'],RLEN[it['len']][1])
-HAS_EN={'pose','costume','anime'} # 人像详情页数量太大,英文版只做分类页(Pages 文件数上限)
-LAB={'zh':{'pose':'姿势','costume':'服装','anime':'动画服装','portrait':'人像','tag':'标签','home':'首页'},'en':{'pose':'Poses','costume':'Outfits','anime':'Anime outfits','portrait':'Portraits','tag':'Tags','home':'Home'}}
-CSS2=CSS+'''
+"""SEO builder: static home SSR, category/tag/detail pages, /en/ site, sitemaps and IndexNow."""
+
+import datetime
+import html as html_lib
+import json
+import os
+import re
+import secrets
+import shutil
+
+
+CC0_URL = 'https://creativecommons.org/publicdomain/zero/1.0/'
+
+SOURCES = {
+ 'pose': ('AI Pose Gallery', 'https://ai-pose-gallery.pages.dev', '@giaaibusi', 'https://x.com/giaaibusi'),
+ 'costume': ('AI Costume Gallery', 'https://ai-costume-gallery.pages.dev', '@giaaibusi', 'https://x.com/giaaibusi'),
+ 'anime': ('AI Costume Anime Gallery', 'https://ai-costume-anime-gallery.pages.dev', '@giaaibusi', 'https://x.com/giaaibusi'),
+ 'portrait': ('AI Portrait Gallery', 'https://ai-portrait-gallery.pages.dev', '@agi_aibusi', 'https://x.com/agi_aibusi'),
+}
+
+POSE_CATEGORIES = {
+ '可爱': ('cute', 'Cute'),
+ '坐姿': ('sitting', 'Sitting'),
+ '站姿': ('standing', 'Standing'),
+ '跪立': ('kneeling', 'Kneeling'),
+ '躺卧': ('lying', 'Lying down'),
+ '侧坐·鸭子坐': ('side-sitting', 'Side sitting'),
+ '蹲姿': ('squatting', 'Squatting'),
+ '前倾': ('leaning-forward', 'Leaning forward'),
+ '后仰': ('leaning-back', 'Leaning back'),
+ '扭身': ('twisting', 'Twisting'),
+}
+
+COSTUME_CATEGORIES = {
+ '春季': ('spring', 'Spring'),
+ '夏季': ('summer', 'Summer'),
+ '秋季': ('autumn', 'Autumn'),
+ '冬季': ('winter', 'Winter'),
+ '派对礼服': ('party', 'Party dresses'),
+ '泳装': ('swimsuit', 'Swimwear'),
+}
+
+PORTRAIT_SECTIONS = {
+ '正脸': ('front-face', 'Front face'),
+ '生活照': ('lifestyle', 'Lifestyle'),
+}
+
+PORTRAIT_LENGTHS = {
+ '短发': ('short-hair', 'Short hair'),
+ '中长发': ('medium-hair', 'Medium hair'),
+ '半长发': ('shoulder-length-hair', 'Shoulder-length hair'),
+ '长发': ('long-hair', 'Long hair'),
+}
+
+COLORS = {
+ '黑': 'black', '白': 'white', '红': 'red', '粉': 'pink', '蓝': 'blue',
+ '藏青': 'navy', '棕': 'brown', '米': 'beige', '象牙白': 'ivory', '灰': 'grey',
+ '绿': 'green', '黄': 'yellow', '紫': 'purple', '金': 'gold', '银': 'silver',
+ '卡其': 'khaki', '酒红': 'burgundy', '橙': 'orange', '奶油': 'cream',
+ '薄荷': 'mint', '薰衣草': 'lavender', '橄榄': 'olive',
+}
+
+GARMENT_ITEMS = {
+ '连衣裙': 'dress', '半身裙': 'skirt', '短裤': 'shorts', '长裤': 'trousers',
+ '牛仔裤': 'jeans', '大衣': 'coat', '夹克': 'jacket', '开衫': 'cardigan',
+ '衬衫': 'blouse', '毛衣': 'sweater', '吊带': 'camisole', '泳衣': 'swimsuit',
+ '靴子': 'boots', '高跟鞋': 'high heels', '运动鞋': 'sneakers', '凉鞋': 'sandals',
+ '连裤袜': 'tights', '长筒袜': 'stockings',
+}
+
+THUMB_DIMENSIONS = {
+ 'pose': (300, 400),
+ 'costume': (360, 540),
+ 'anime': (360, 540),
+ 'portrait': (400, 500),
+}
+
+# Portrait detail count is large; English edition publishes category/hub pages only (Cloudflare Pages 20k file limit).
+HAS_EN = {'pose', 'costume', 'anime'}
+
+LABELS = {
+ 'zh': {'pose': '姿势', 'costume': '服装', 'anime': '动画服装', 'portrait': '人像', 'tag': '标签', 'home': '首页'},
+ 'en': {'pose': 'Poses', 'costume': 'Outfits', 'anime': 'Anime outfits', 'portrait': 'Portraits', 'tag': 'Tags', 'home': 'Home'},
+}
+
+HUB_NAMES = {
+ 'pose': ('姿势参考图库', 'Pose Reference Library'),
+ 'costume': ('服装穿搭参考图库', 'Outfit Reference Library'),
+ 'anime': ('动画服装参考图库', 'Anime Outfit Reference Library'),
+ 'portrait': ('人像脸模参考图库', 'Portrait Face References'),
+ 'tag': ('穿搭标签', 'Outfit Tags'),
+}
+
+LISTING_INTROS = {
+ 'pose': (
+ '{c}姿势参考图,共 {n} 个姿势,每个都有正面、俯拍、仰拍等多个角度,附中英文提示词,画画、拍照和 AI 出图都能用。',
+ '{c} pose references: {n} poses, each shot from several camera angles, with English prompts for drawing, photography and AI image generation.',
+ ),
+ 'costume': (
+ '{c}穿搭参考图,共 {n} 套,每套都有中文描述和英文提示词,可以在衣姿里上传照片在线试穿。',
+ '{c} outfit references: {n} looks, each with a description and an English prompt. Upload a photo to try them on in PoseWear.',
+ ),
+ 'anime': (
+ '{c}动画风穿搭参考图,共 {n} 套,每套都有中文描述和英文提示词,可以在衣姿里上传照片在线试穿。',
+ '{c} anime-style outfit references: {n} looks, each with a description and an English prompt. Upload a photo to try them on in PoseWear.',
+ ),
+ 'portrait': (
+ '{c}人像脸模参考,共 {n} 张,AI 生成的虚构人物,CC0 1.0,可作 AI 绘图和视频的人物面部参考。',
+ '{c} face references: {n} AI-generated fictional people, CC0 1.0, for consistent characters in AI images and video.',
+ ),
+ 'tag': (
+ '带「{c}」的穿搭参考图,共 {n} 套,附中英文提示词。',
+ 'Outfit references with {c}: {n} looks with English prompts.',
+ ),
+}
+
+HUB_INTROS = {
+ 'pose': (
+ '按分类浏览 {n} 个姿势参考,每个姿势都有多个拍摄角度和中英文提示词。',
+ 'Browse {n} pose references by category, each with several camera angles and prompts.',
+ ),
+ 'costume': (
+ '按季节和场合浏览 {n} 套服装穿搭参考,附中英文提示词,可在线 AI 试穿。',
+ 'Browse {n} outfit references by season and occasion, with prompts and online AI try-on.',
+ ),
+ 'anime': (
+ '按季节和场合浏览 {n} 套动画风服装穿搭参考,附中英文提示词,可在线 AI 试穿。',
+ 'Browse {n} anime-style outfit references by season and occasion, with prompts and online AI try-on.',
+ ),
+ 'portrait': (
+ '按类型和发长浏览 {n} 张人像脸模参考,CC0 1.0。',
+ 'Browse {n} CC0 portrait face references by type and hair length.',
+ ),
+ 'tag': (
+ '按单品和颜色浏览穿搭参考,共 {n} 个标签。',
+ 'Browse outfits by garment and colour: {n} tags.',
+ ),
+}
+
+SEO_EXTRA_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: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)}
@@ -57,210 +148,718 @@ header nav{margin-left:auto;display:flex;gap:16px;font-size:14px}header nav a{fo
.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 '')+path
-def 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):
- 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.' 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">{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}
-<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':[]}
-def add(sm,path,lm,imgs=(),en=True):
- SM[sm].append((url('zh',path),lm,imgs))
- if en: SM[sm].append((url('en',path),lm,imgs))
-def cardli(lang,kind,it,href=None):
- t=en_title(kind,it) if lang=='en' else zh_title(kind,it);w,h=TW[kind]
- href=href or (('/en' if lang=='en' and kind in HAS_EN else '')+f'/{kind}/{it["id"]}/')
- return f'<li><a href="{href}"><img src="{TU(thumb(kind,it))}" alt="{E(t)}" width="{w}" height="{h}" loading="lazy" decoding="async"><span>{E(t)}</span></a></li>'
-# ---- 详情页 ----
-def detail(lang,kind,it,rel):
- zh=lang=='zh';P='/en' if not zh else '';src=SRCS[kind];ck,slug,cz_,cen=catof(kind,it)
- tz=zh_title(kind,it);te=en_title(kind,it);t=tz if zh else te
- img=big(kind,it);th=thumb(kind,it)
- if kind=='portrait': w,h=1080,round(1080*it['h']/it['w'])
- elif kind=='pose': w,h=900,1200
- else: w,h=1080,1620
- angs=it.get('angles',[])
- if kind=='pose':
- prz=f"{it['zh']},{it['line']},{it['cat']}。";pzh=f"{it['zh']},{it['line']},{it['cat']}姿势";pre=f"{it['en']}, {it['lineEn']}"
- desc=(f"{it['zh']}:{it['line']} · {it['cat']}姿势参考,{len(angs)} 个拍摄角度({'、'.join(a['zh'] for a in angs)}),附中英文提示词。" if zh else
- f"{te} — {it['lineEn']} pose reference ({cen.lower()}), {len(angs)} camera angles ({', '.join(a['en'] for a in angs)}), with an English prompt.")
- ttl=f"{tz} · {it['cat']}姿势参考 | 衣姿 PoseWear" if zh else f"{te} – {cen} Pose Reference | PoseWear"
- elif kind in ('costume','anime'):
- prz=it['zh'];pre=it['en'];pzh=f"{it['cat']}穿搭,"+it['zh'].rstrip('。').replace('。',',')
- desc=(f"{it['ti']}:{it['cat']}穿搭参考图。{it['zh']}附英文提示词,可在线 AI 试穿。" if zh else f"{te} – {cen.lower()} outfit reference image with an AI prompt: {it['en']}. Try it on online.")
- ttl=f"{tz} · {it['cat']}穿搭参考 | 衣姿 PoseWear" if zh else f"{te} – {cen} Outfit Reference | PoseWear"
- else:
- prz=it['zh'];pre=it['en'];pzh=it['zh'].rstrip('。').replace('。',',')
- desc=f"{it['ti']}:{it['sec']}人像脸模参考({it['len']}{','+it['st'] if it['st'] else ''})。AI 生成的虚构人物,CC0 1.0,附中英文提示词。"
- ttl=f"{tz} · 人像脸模参考 {it['no']} | 衣姿 PoseWear"
- path=f'/{kind}/{it["id"]}/'
- cr=[(LAB[lang]['home'],P+'/'),(LAB[lang][kind],f'{P}/{kind}/'),(cz_ if zh else cen,f'{P}/{kind}/{slug}/'),(t,None)]
- kws=[cz_,cen]+([it['line'],it['lineEn']] if kind=='pose' else [])+([x[1] if x[0]=='item' else cz(x[1]) for x in ctags(it)] if kind in ('costume','anime') else [])+([it['sec'],it['st']] if kind=='portrait' else [])
- kws=[k for k in kws if k]
- creator={"@type":"Person","name":src[2],"url":src[3]}
- io={"@type":"ImageObject","@id":url(lang,path)+'#image',"name":t,"description":desc,"contentUrl":f"{SITE}/{img}","thumbnailUrl":f"{TS(th)}","url":url(lang,path),"width":w,"height":h,
- "encodingFormat":"image/webp","inLanguage":'en' if not zh else 'zh-CN',"keywords":', '.join(kws),"creator":creator,"creditText":f"{src[0]} ({src[2]})","acquireLicensePage":src[1],
- "isPartOf":{"@type":"WebSite","name":"衣姿 PoseWear","url":SITE+'/'},"dateModified":LM[kind]}
- if kind=='portrait': io.update({"license":CC0,"copyrightNotice":"CC0 1.0 (public domain dedication) by @agi_aibusi"})
- tags=[]
- if kind in ('costume','anime'): tags=[(x[1] if x[0]=='item' else cz(x[1]),x[2]) for x in ctags(it) if x[2].replace(' ','-') in TAGS]
- tg='<div class="tg">'+f'<a href="{P}/{kind}/{slug}/">{E(cz_ if zh else cen)}</a>'+''.join(f'<a href="{P}/tag/{en.replace(" ","-")}/">{E(z if zh else en)}</a>' for z,en in tags)+(f'<a href="/portrait/{RSEC[it["sec"]][0]}/">{E(it["sec"])}</a>' if kind=='portrait' else '')+'</div>'
- if kind=='pose':
- ang=('<div class="box"><small>'+('拍摄角度' if zh else 'Camera angles')+'</small><ul>'+''.join(f'<li><a href="/{a["i"]}">{E(a["zh"] if zh else a["en"])}</a> · <code>{E(a["en"])}</code></li>' for a in angs)+'</ul></div>')
- else: ang=''
- lic=('<p class="mu">'+(f'许可:<a href="{CC0}" rel="license">CC0 1.0</a>,可商用、可修改,无需署名;原作者希望不要原样批量转载。来源:<a href="{src[1]}" rel="noopener">{src[0]}</a>(<a href="{src[3]}" rel="noopener">{src[2]}</a>)。' if kind=='portrait' else
- (f'来源:<a href="{src[1]}" rel="noopener">{src[0]}</a>,原作者 <a href="{src[3]}" rel="noopener">{src[2]}</a>。原站未标明授权,转载或商用请先联系原作者。' if zh else
- 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 else
- f'<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 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',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):
- same=[x for x in L if ck(x)==ck(it) and x['id']!=it['id']];pos=sum(1 for x in L[:i] if ck(x)==ck(it));rel=(same[pos:]+same[:pos])[:8]
- imgs=[a['i'] for a in it['angles']] if kind=='pose' else [it['m']]
- for lang in (['zh','en'] if kind in HAS_EN else ['zh']):
- W(('/en' if lang=='en' else '')+f'/{kind}/{it["id"]}/',detail(lang,kind,it,rel))
- add(kind,f'/{kind}/{it["id"]}/',LM[kind],[(SITE+'/'+x,zh_title(kind,it)) for x in imgs],en=kind in HAS_EN)
-# ---- 分类 / 标签 / 栏目页 ----
-PER=96
-INTRO={'pose':('{c}姿势参考图,共 {n} 个姿势,每个都有正面、俯拍、仰拍等多个角度,附中英文提示词,画画、拍照和 AI 出图都能用。','{c} pose references: {n} poses, each shot from several camera angles, with English prompts for drawing, photography and AI image generation.'),
- 'costume':('{c}穿搭参考图,共 {n} 套,每套都有中文描述和英文提示词,可以在衣姿里上传照片在线试穿。','{c} outfit references: {n} looks, each with a description and an English prompt. Upload a photo to try them on in PoseWear.'),
- 'anime':('{c}动画风穿搭参考图,共 {n} 套,每套都有中文描述和英文提示词,可以在衣姿里上传照片在线试穿。','{c} anime-style outfit references: {n} looks, each with a description and an English prompt. Upload a photo to try them on in PoseWear.'),
- 'portrait':('{c}人像脸模参考,共 {n} 张,AI 生成的虚构人物,CC0 1.0,可作 AI 绘图和视频的人物面部参考。','{c} face references: {n} AI-generated fictional people, CC0 1.0, for consistent characters in AI images and video.'),
- 'tag':('带「{c}」的穿搭参考图,共 {n} 套,附中英文提示词。','Outfit references with {c}: {n} looks with English prompts.')}
-def listing(lang,kind,base,slug,cz_,cen,L,kindi=None,en=True,sm='pages'):
- zh=lang=='zh';P='/en' if not zh else '';kindi=kindi or kind;n=len(L);c=cz_ if zh else cen
- pages=max(1,-(-n//PER))
- for pg in range(1,pages+1):
- path=f'{base}{slug}/'+(f'{pg}/' if pg>1 else '')
- cr=[(LAB[lang]['home'],P+'/'),(LAB[lang][kind],f'{P}{base}'),(c,None if pg==1 else f'{P}{base}{slug}/')]+([(f'第 {pg} 页' if zh else f'Page {pg}',None)] if pg>1 else [])
- ttl=(f"{c}{'' if kind=='tag' else {'pose':'姿势','costume':'穿搭','anime':'动画穿搭','portrait':'人像'}[kind]}参考图{'' if pg==1 else f'(第 {pg} 页)'} | 衣姿 PoseWear" if zh else f"{c} {'Outfit' if kind in('costume','tag','anime') else {'pose':'Pose','portrait':'Portrait'}[kind]} References{'' if pg==1 else f' – Page {pg}'} | PoseWear")
- desc=INTRO[kind][0 if zh else 1].format(c=c,n=n)
- items=L[(pg-1)*PER:pg*PER]
- pgn=''
- if pages>1: pgn='<nav class="pg" aria-label="pagination">'+''.join(f'<b>{i}</b>' if i==pg else f'<a href="{P}{base}{slug}/{"" if i==1 else str(i)+"/"}">{i}</a>' for i in range(1,pages+1))+'</nav>'
- body=f'<div class="wrap">{crumbs_html(cr)}<h1>{E(ttl.split(" | ")[0])}</h1><p class="lead">{E(desc)}</p><ul class="cg">{"".join(cardli(lang,kindi,it) for it in items)}</ul>{pgn}</div>'
- ld=[{"@type":"CollectionPage","@id":url(lang,path),"url":url(lang,path),"name":ttl,"description":desc,"inLanguage":'zh-CN' if zh else 'en',"isPartOf":{"@type":"WebSite","name":"衣姿 PoseWear","url":SITE+'/'}},crumbs_ld(lang,cr),
- {"@type":"ItemList","numberOfItems":len(items),"itemListElement":[{"@type":"ListItem","position":i+1,"url":SITE+('/en' if not zh and kindi in HAS_EN else '')+f'/{kindi}/{it["id"]}/'} for i,it in enumerate(items)]}]
- W(P+path,shell(lang,path,ttl,desc,body,ld,en=en))
- if lang=='zh': add(sm,path,LM[kindi],en=en)
-CATS={'pose':[(PCAT[k][0],k,PCAT[k][1],[p for p in SP if p['cat']==k]) for k in PCAT],
- 'costume':[(CCAT[k][0],k,CCAT[k][1],[c for c in SC if c['cat']==k]) for k in CCAT],
- 'anime':[(CCAT[k][0],k,CCAT[k][1],[c for c in SA if c['cat']==k]) for k in CCAT],
- 'portrait':[(RSEC[k][0],k,RSEC[k][1],[r for r in SR if r['sec']==k]) for k in RSEC]+[(RLEN[k][0],k,RLEN[k][1],[r for r in SR if r['len']==k]) for k in RLEN]}
-for lang in ['zh','en']:
- for kind,cs in CATS.items():
- for slug,z,e,L in cs: listing(lang,kind,f'/{kind}/',slug,z,e,L)
- for slug,t in TAGS.items(): listing(lang,'tag','/tag/',slug,t['zh'],t['en'],t['L'],kindi='costume')
-NAMES={'pose':('姿势参考图库','Pose Reference Library'),'costume':('服装穿搭参考图库','Outfit Reference Library'),'anime':('动画服装参考图库','Anime Outfit Reference Library'),'portrait':('人像脸模参考图库','Portrait Face References'),'tag':('穿搭标签','Outfit Tags')}
-CNT={'pose':len(SP),'costume':len(SC),'anime':len(SA),'portrait':len(SR),'tag':len(TAGS)}
-def hub(lang,kind):
- zh=lang=='zh';P='/en' if not zh else '';path=f'/{kind}/';nm=NAMES[kind][0 if zh else 1]
- cs=[(s,z,e,len(L)) for s,z,e,L in CATS[kind]] if kind!='tag' else [(s,t['zh'],t['en'],len(t['L'])) for s,t in sorted(TAGS.items(),key=lambda x:-len(x[1]['L']))]
- desc={'pose':('按分类浏览 {n} 个姿势参考,每个姿势都有多个拍摄角度和中英文提示词。','Browse {n} pose references by category, each with several camera angles and prompts.'),
- 'costume':('按季节和场合浏览 {n} 套服装穿搭参考,附中英文提示词,可在线 AI 试穿。','Browse {n} outfit references by season and occasion, with prompts and online AI try-on.'),
- 'anime':('按季节和场合浏览 {n} 套动画风服装穿搭参考,附中英文提示词,可在线 AI 试穿。','Browse {n} anime-style outfit references by season and occasion, with prompts and online AI try-on.'),
- 'portrait':('按类型和发长浏览 {n} 张人像脸模参考,CC0 1.0。','Browse {n} CC0 portrait face references by type and hair length.'),
- 'tag':('按单品和颜色浏览穿搭参考,共 {n} 个标签。','Browse outfits by garment and colour: {n} tags.')}[kind][0 if zh else 1].format(n=CNT[kind])
- cr=[(LAB[lang]['home'],P+'/'),(LAB[lang][kind],None)]
- first={s:L[0] for s,z,e,L in CATS[kind]} if kind!='tag' else {s:t['L'][0] for s,t in TAGS.items()}
- ki='costume' if kind=='tag' else kind
- li=''.join(f'<li><a href="{P}/{kind}/{s}/"><img src="{TU(thumb(ki,first[s]))}" alt="{E(z if zh else e)}" width="{TW[ki][0]}" height="{TW[ki][1]}" loading="lazy" decoding="async"><span>{E(z if zh else e)} · {n}</span></a></li>' for s,z,e,n in cs)
- extra='' if kind!='costume' else f'<p><a href="{P}/tag/">{"按单品和颜色浏览 →" if zh else "Browse by garment and colour →"}</a></p>'
- body=f'<div class="wrap">{crumbs_html(cr)}<h1>{E(nm)}</h1><p class="lead">{E(desc)}</p><ul class="cg">{li}</ul>{extra}</div>'
- ld=[{"@type":"CollectionPage","url":url(lang,path),"name":nm,"description":desc,"inLanguage":'zh-CN' if zh else 'en'},crumbs_ld(lang,cr)]
- W(P+path,shell(lang,path,f'{nm} | 衣姿 PoseWear' if zh else f'{nm} | PoseWear',desc,body,ld))
- if zh: add('pages',path,TODAY)
-for lang in ['zh','en']:
- for k in NAMES: hub(lang,k)
-# ---- 英文首页 ----
-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","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 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>
-</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))
-zh_desc=f"衣姿 PoseWear:{HC['pose']} 组姿势({HC['ang']:,} 张角度图)、{HC['cos']:,} 套服装、{HC['ani']:,} 套动画服装、{HC['por']:,} 张人像参考图,附中英文提示词,可上传照片在线 AI 试穿。免费,无需注册。"
-zhttl='衣姿 PoseWear · 姿势、服装、人像参考图库 | 中英文提示词 + 在线 AI 试穿'
-idx=open(f'{D}/index.html').read()
-idx=re.sub(r'<title>.*?</title>',f'<title>{zhttl}</title>',idx,1)
-idx=re.sub(r'<meta name="description" content="[^"]*">',f'<meta name="description" content="{E(zh_desc)}">',idx,1)
-idx=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('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","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)
-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):
- 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('<!-- category-index -->','<details class="footer-index"><summary>分类索引</summary>'+nav+'</details>')
-open(f'{D}/index.html','w').write(idx)
-# ---- 站点地图 ----
-def smx(L,img=True):
- out=['<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">\n']
- for u,lm,ims in L:
- out.append(f'<url><loc>{u}</loc><lastmod>{lm}</lastmod>'+''.join(f'<image:image><image:loc>{E(i)}</image:loc></image:image>' for i,_ in ims)+'</url>\n')
- return ''.join(out)+'</urlset>\n'
-SM['pages'].insert(0,(SITE+'/',TODAY,[(SITE+'/og.png','')]))
-for k,L in SM.items(): open(f'{D}/sitemap-{k}.xml','w').write(smx(L))
-ix='<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'+''.join(f'<sitemap><loc>{SITE}/sitemap-{k}.xml</loc><lastmod>{max(x[1] for x in L)}</lastmod></sitemap>\n' for k,L in SM.items())+'</sitemapindex>\n'
-open(f'{D}/sitemap_index.xml','w').write(ix);open(f'{D}/sitemap.xml','w').write(ix)
-open(f'{D}/robots.txt','w').write(f'User-agent: *\nAllow: /\nDisallow: /api/\nDisallow: /o/\n\nSitemap: {SITE}/sitemap_index.xml\n')
-open('urls.txt','w').write('\n'.join(u for L in SM.values() for u,_,_ in L)+'\n')
-open(f'{D}/_headers','a').write('/en/*\n Cache-Control: public, max-age=600\n/tag/*\n Cache-Control: public, max-age=600\n/sitemap*\n Cache-Control: public, max-age=3600\n')
-print('NA_PUB',NA_PUB);print('seo',{k:len(v) for k,v in SM.items()},'tags',len(TAGS))
+
+EXTRA_CATALOG_STATS = (
+ ('depth', 'depths.json'),
+ ('exp', 'expressions.json'),
+ ('hair', 'hair.json'),
+ ('dyn', 'dynasties.json'),
+ ('scene', 'scenes.json'),
+ ('light', 'lights.json'),
+ ('prop', 'props.json'),
+ ('furn', 'furniture.json'),
+)
+
+
+def _esc(value):
+ return html_lib.escape(str(value), quote=True)
+
+
+def _cap(text):
+ return text[:1].upper() + text[1:]
+
+
+def _color_zh(name):
+ return name if name.endswith('白') else name + '色'
+
+
+def _costume_tags(item):
+ words = ' ' + item['kw'] + ' '
+ english = ' ' + item['en'].replace(',', ' ') + ' '
+ items = [('item', zh, en) for zh, en in GARMENT_ITEMS.items() if ' ' + en + ' ' in english]
+ colors = [('col', zh, en) for zh, en in COLORS.items() if ' ' + en + ' ' in words]
+ return items + colors
+
+
+def _en_title(kind, item):
+ if kind == 'pose':
+ return _cap(item['en'])
+ if kind in ('costume', 'anime'):
+ parts = [part.strip() for part in item['en'].split(',')][1:3]
+ return _cap(' + '.join(parts)) if parts else _cap(item['en'])
+ parts = item['en'].split(',')
+ return _cap((parts[1] if len(parts) > 1 else parts[0]).strip()) + ' portrait'
+
+
+def _zh_title(kind, item):
+ return item['zh'] if kind == 'pose' else item['ti']
+
+
+def _thumb(kind, item):
+ return item['angles'][0]['t'] if kind == 'pose' else item['t']
+
+
+def _big(kind, item):
+ return item['angles'][0]['i'] if kind == 'pose' else item['m']
+
+
+def _category_of(kind, item):
+ if kind == 'pose':
+ slug, en = POSE_CATEGORIES[item['cat']]
+ return ('pose', slug, item['cat'], en)
+ if kind in ('costume', 'anime'):
+ slug, en = COSTUME_CATEGORIES[item['cat']]
+ return (kind, slug, item['cat'], en)
+ slug, en = PORTRAIT_LENGTHS[item['len']]
+ return ('portrait', slug, item['len'], en)
+
+
+def _mtime_iso(path, fallback):
+ if path and os.path.exists(path):
+ return datetime.date.fromtimestamp(os.path.getmtime(path)).isoformat()
+ return fallback
+
+
+def run(ctx):
+ """Generate static SEO pages, English site, SSR home fragment, sitemaps, and robots.txt."""
+ raw_dir = ctx.get('raw_dir', 'assets-raw')
+ dist_dir = ctx['dist_dir']
+ site = ctx['site'].rstrip('/')
+ asset_host = ctx.get('asset_host', '').rstrip('/')
+ theme_head = ctx['theme_head']
+ css2 = ctx['base_css'] + SEO_EXTRA_CSS
+ logo = ctx['logo']
+ catalogs = ctx['catalogs']
+ data = ctx['data']
+ urls_path = ctx.get('urls_path', 'urls.txt')
+ indexnow_key_path = ctx.get('indexnow_key_path', 'indexnow.key')
+
+ today = datetime.date.today().isoformat()
+ explicit_lm = ctx.get('last_modified') or {}
+ last_mod = {
+ 'pose': explicit_lm.get('pose') or _mtime_iso(os.path.join(raw_dir, 'pose/data.json'), today),
+ 'costume': explicit_lm.get('costume') or _mtime_iso(os.path.join(raw_dir, 'costume/data.json'), today),
+ 'anime': explicit_lm.get('anime') or _mtime_iso(os.path.join(raw_dir, 'anime/data.json'), today),
+ 'portrait': explicit_lm.get('portrait') or _mtime_iso(os.path.join(raw_dir, 'portrait/images.js'), today),
+ }
+
+ def thumb_url(path):
+ if path.startswith('http'):
+ return path
+ return f'{asset_host}/{path}' if asset_host else f'/{path}'
+
+ def thumb_abs(path):
+ if path.startswith('http'):
+ return path
+ return f'{asset_host}/{path}' if asset_host else f'{site}/{path}'
+
+ for sub in ('en', 'tag'):
+ target = os.path.join(dist_dir, sub)
+ if os.path.exists(target):
+ shutil.rmtree(target)
+
+ if not os.path.exists(indexnow_key_path):
+ with open(indexnow_key_path, 'w') as fh:
+ fh.write(secrets.token_hex(16))
+ with open(indexnow_key_path) as fh:
+ indexnow_key = fh.read().strip()
+ with open(os.path.join(dist_dir, f'{indexnow_key}.txt'), 'w') as fh:
+ fh.write(indexnow_key)
+
+ poses = data['poses']
+ poses_list = data['poses_list']
+ costumes = data['costumes']
+ anime = data['anime']
+ portraits = data['portraits']
+
+ na_total = sum(len(p['angles']) for p in poses.values())
+ safe_poses = [p for p in poses_list if not p.get('a')]
+ na_pub = sum(len(p['angles']) for p in safe_poses)
+ safe_costumes = [c for c in costumes if not c.get('a')]
+ safe_anime = [c for c in anime if not c.get('a') and not c.get('ext')]
+ anime_pub = sum(1 for c in anime if not c.get('a'))
+ safe_portraits = portraits
+
+ tags_map = {}
+ for item in safe_costumes:
+ for kind_t, zh, en in _costume_tags(item):
+ slug = en.replace(' ', '-')
+ entry = tags_map.setdefault(slug, {'k': kind_t, 'zh': zh if kind_t == 'item' else _color_zh(zh), 'en': en, 'L': []})
+ entry['L'].append(item)
+ tags_map = {slug: entry for slug, entry in tags_map.items() if len(entry['L']) >= 4}
+
+ def page_url(lang, path):
+ return site + ('/en' if lang == 'en' else '') + path
+
+ def hreflang_tags(path, has_en=True):
+ if not has_en:
+ return f'<link rel="canonical" href="{page_url("zh", path)}">'
+ return (
+ f'<link rel="alternate" hreflang="zh-CN" href="{page_url("zh", path)}">'
+ f'<link rel="alternate" hreflang="en" href="{page_url("en", path)}">'
+ f'<link rel="alternate" hreflang="x-default" href="{page_url("zh", path)}">'
+ )
+
+ def crumbs_ld(cr, bid=None):
+ return {
+ '@type': 'BreadcrumbList',
+ **({'@id': bid} if bid else {}),
+ 'itemListElement': [
+ {'@type': 'ListItem', 'position': idx + 1, 'name': name, **({'item': site + href} if href else {})}
+ for idx, (name, href) in enumerate(cr)
+ ],
+ }
+
+ def crumbs_html(cr):
+ parts = [f'<a href="{_esc(href)}">{_esc(name)}</a>' if href else f'<span aria-current="page">{_esc(name)}</span>' for name, href in cr]
+ return '<nav class="bc" aria-label="breadcrumb"><ol>' + ''.join(f'<li>{p}</li>' for p in parts) + '</ol></nav>'
+
+ def shell(lang, path, title, desc, body, ld, has_en=True, og=None, ogt='website', credit='', workbench='/#workbench'):
+ dock_label = 'Open image studio' if lang == 'en' else '打开生图工作台'
+ prefix = '/en' if lang == 'en' else ''
+ switch = (
+ f'<a href="/en{path}" hreflang="en" lang="en">EN</a>'
+ if lang == 'zh' and has_en
+ else f'<a href="{path}" hreflang="zh-CN" lang="zh-CN">中文</a>'
+ if lang == 'en'
+ else ''
+ )
+ nav = (
+ f'<nav><a href="{prefix}/pose/">{LABELS[lang]["pose"]}</a>'
+ f'<a href="{prefix}/costume/">{LABELS[lang]["costume"]}</a>'
+ f'<a href="{prefix}/anime/">{LABELS[lang]["anime"]}</a>'
+ f'<a href="{prefix}/portrait/">{LABELS[lang]["portrait"]}</a>'
+ f'<a href="https://github.com/atuizz/posewear" target="_blank" rel="noopener">GitHub</a>'
+ f'{switch}</nav>'
+ )
+ default_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 生成图,中文描述由本站整理。'
+ )
+ ld_json = json.dumps({'@context': 'https://schema.org', '@graph': ld}, ensure_ascii=False, separators=(',', ':'))
+ return (
+ f'<!doctype html><html lang="{"en" if lang == "en" else "zh-CN"}"><head>'
+ f'<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
+ f'<title>{_esc(title)}</title><meta name="description" content="{_esc(desc[:160])}">'
+ f'<link rel="canonical" href="{page_url(lang, path)}">{hreflang_tags(path) if has_en else ""}'
+ f'<meta property="og:type" content="{ogt}"><meta property="og:site_name" content="衣姿 PoseWear">'
+ f'<meta property="og:title" content="{_esc(title)}"><meta property="og:description" content="{_esc(desc[:160])}">'
+ f'<meta property="og:image" content="{site}/{og or "og.png"}"><meta property="og:url" content="{page_url(lang, path)}">'
+ f'<meta property="og:locale" content="{"en_US" if lang == "en" else "zh_CN"}">'
+ f'<meta name="twitter:card" content="summary_large_image"><meta name="twitter:description" content="{_esc(desc[:160])}">'
+ f'<link rel="icon" href="/favicon.svg" type="image/svg+xml">{theme_head}<style>{css2}</style>'
+ f'<script type="application/ld+json">{ld_json}</script></head><body>'
+ f'<header><a href="{prefix}/">{logo}衣姿 PoseWear</a>{nav}</header>'
+ f'{body}'
+ f'<a class="static-dock" href="{_esc(workbench)}" aria-label="{dock_label}" title="{dock_label}">'
+ f'<svg viewBox="0 0 24 24" aria-hidden="true">'
+ f'<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"/>'
+ f'<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>'
+ f'<footer>{credit or default_foot} <a href="{prefix}/">{"PoseWear home" if lang == "en" else "返回首页"}</a></footer></body></html>'
+ )
+
+ def write_page(path, content):
+ out_dir = os.path.join(dist_dir, path.lstrip('/'))
+ os.makedirs(out_dir, exist_ok=True)
+ with open(os.path.join(out_dir, 'index.html'), 'w') as fh:
+ fh.write(content)
+
+ sitemaps = {'pose': [], 'costume': [], 'anime': [], 'portrait': [], 'pages': []}
+
+ def add_sitemap(sm, path, lm, imgs=(), has_en=True):
+ sitemaps[sm].append((page_url('zh', path), lm, imgs))
+ if has_en:
+ sitemaps[sm].append((page_url('en', path), lm, imgs))
+
+ def card_li(lang, kind, item, href=None):
+ title = _en_title(kind, item) if lang == 'en' else _zh_title(kind, item)
+ w, h = THUMB_DIMENSIONS[kind]
+ target = href or (('/en' if lang == 'en' and kind in HAS_EN else '') + f'/{kind}/{item["id"]}/')
+ return (
+ f'<li><a href="{target}">'
+ f'<img src="{thumb_url(_thumb(kind, item))}" alt="{_esc(title)}" width="{w}" height="{h}" loading="lazy" decoding="async">'
+ f'<span>{_esc(title)}</span></a></li>'
+ )
+
+ def detail_page(lang, kind, item, related):
+ is_zh = lang == 'zh'
+ prefix = '' if is_zh else '/en'
+ src = SOURCES[kind]
+ _, slug, cz_, cen = _category_of(kind, item)
+ tz, te = _zh_title(kind, item), _en_title(kind, item)
+ title = tz if is_zh else te
+ img = _big(kind, item)
+ th = _thumb(kind, item)
+ if kind == 'portrait':
+ w, h = 1080, round(1080 * item['h'] / item['w'])
+ elif kind == 'pose':
+ w, h = 900, 1200
+ else:
+ w, h = 1080, 1620
+ angles = item.get('angles', [])
+
+ if kind == 'pose':
+ prz = f"{item['zh']},{item['line']},{item['cat']}。"
+ pzh = f"{item['zh']},{item['line']},{item['cat']}姿势"
+ pre = f"{item['en']}, {item['lineEn']}"
+ desc = (
+ f"{item['zh']}:{item['line']} · {item['cat']}姿势参考,{len(angles)} 个拍摄角度({'、'.join(a['zh'] for a in angles)}),附中英文提示词。"
+ if is_zh
+ else f"{te} — {item['lineEn']} pose reference ({cen.lower()}), {len(angles)} camera angles ({', '.join(a['en'] for a in angles)}), with an English prompt."
+ )
+ ttl = f"{tz} · {item['cat']}姿势参考 | 衣姿 PoseWear" if is_zh else f"{te} – {cen} Pose Reference | PoseWear"
+ elif kind in ('costume', 'anime'):
+ prz = item['zh']
+ pre = item['en']
+ pzh = f"{item['cat']}穿搭," + item['zh'].rstrip('。').replace('。', ',')
+ desc = (
+ f"{item['ti']}:{item['cat']}穿搭参考图。{item['zh']}附英文提示词,可在线 AI 试穿。"
+ if is_zh
+ else f"{te} – {cen.lower()} outfit reference image with an AI prompt: {item['en']}. Try it on online."
+ )
+ ttl = f"{tz} · {item['cat']}穿搭参考 | 衣姿 PoseWear" if is_zh else f"{te} – {cen} Outfit Reference | PoseWear"
+ else:
+ prz = item['zh']
+ pre = item['en']
+ pzh = item['zh'].rstrip('。').replace('。', ',')
+ desc = f"{item['ti']}:{item['sec']}人像脸模参考({item['len']}{',' + item['st'] if item['st'] else ''})。AI 生成的虚构人物,CC0 1.0,附中英文提示词。"
+ ttl = f"{tz} · 人像脸模参考 {item['no']} | 衣姿 PoseWear"
+
+ path = f'/{kind}/{item["id"]}/'
+ crumbs = [
+ (LABELS[lang]['home'], prefix + '/'),
+ (LABELS[lang][kind], f'{prefix}/{kind}/'),
+ (cz_ if is_zh else cen, f'{prefix}/{kind}/{slug}/'),
+ (title, None),
+ ]
+ kws = (
+ [cz_, cen]
+ + ([item['line'], item['lineEn']] if kind == 'pose' else [])
+ + ([x[1] if x[0] == 'item' else _color_zh(x[1]) for x in _costume_tags(item)] if kind in ('costume', 'anime') else [])
+ + ([item['sec'], item['st']] if kind == 'portrait' else [])
+ )
+ kws = [kw for kw in kws if kw]
+ creator = {'@type': 'Person', 'name': src[2], 'url': src[3]}
+ image_obj = {
+ '@type': 'ImageObject',
+ '@id': page_url(lang, path) + '#image',
+ 'name': title,
+ 'description': desc,
+ 'contentUrl': f'{site}/{img}',
+ 'thumbnailUrl': thumb_abs(th),
+ 'url': page_url(lang, path),
+ 'width': w,
+ 'height': h,
+ 'encodingFormat': 'image/webp',
+ 'inLanguage': 'zh-CN' if is_zh else 'en',
+ 'keywords': ', '.join(kws),
+ 'creator': creator,
+ 'creditText': f'{src[0]} ({src[2]})',
+ 'acquireLicensePage': src[1],
+ 'isPartOf': {'@type': 'WebSite', 'name': '衣姿 PoseWear', 'url': site + '/'},
+ 'dateModified': last_mod[kind],
+ }
+ if kind == 'portrait':
+ image_obj.update({'license': CC0_URL, 'copyrightNotice': 'CC0 1.0 (public domain dedication) by @agi_aibusi'})
+
+ item_tags = []
+ if kind in ('costume', 'anime'):
+ item_tags = [
+ (x[1] if x[0] == 'item' else _color_zh(x[1]), x[2])
+ for x in _costume_tags(item)
+ if x[2].replace(' ', '-') in tags_map
+ ]
+ tag_html = (
+ '<div class="tg">'
+ + f'<a href="{prefix}/{kind}/{slug}/">{_esc(cz_ if is_zh else cen)}</a>'
+ + ''.join(f'<a href="{prefix}/tag/{en.replace(" ", "-")}/">{_esc(z if is_zh else en)}</a>' for z, en in item_tags)
+ + (f'<a href="/portrait/{PORTRAIT_SECTIONS[item["sec"]][0]}/">{_esc(item["sec"])}</a>' if kind == 'portrait' else '')
+ + '</div>'
+ )
+ angle_html = ''
+ if kind == 'pose':
+ angle_html = (
+ '<div class="box"><small>'
+ + ('拍摄角度' if is_zh else 'Camera angles')
+ + '</small><ul>'
+ + ''.join(
+ f'<li><a href="/{a["i"]}">{_esc(a["zh"] if is_zh else a["en"])}</a> · <code>{_esc(a["en"])}</code></li>'
+ for a in angles
+ )
+ + '</ul></div>'
+ )
+
+ if kind == 'portrait':
+ lic_inner = f'许可:<a href="{CC0_URL}" rel="license">CC0 1.0</a>,可商用、可修改,无需署名;原作者希望不要原样批量转载。来源:<a href="{src[1]}" rel="noopener">{src[0]}</a>(<a href="{src[3]}" rel="noopener">{src[2]}</a>)。'
+ elif is_zh:
+ lic_inner = f'来源:<a href="{src[1]}" rel="noopener">{src[0]}</a>,原作者 <a href="{src[3]}" rel="noopener">{src[2]}</a>。原站未标明授权,转载或商用请先联系原作者。'
+ else:
+ lic_inner = 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.'
+ lic = f'<p class="mu">{lic_inner}</p>'
+
+ if is_zh:
+ boxes = (
+ f'<div class="box"><small>中文描述</small><p>{_esc(prz)}</p></div>'
+ f'<div class="box"><small>中文提示词</small><p>{_esc(pzh)}</p></div>'
+ f'<div class="box"><small>英文提示词 · PROMPT</small><p>{_esc(pre)}</p></div>'
+ )
+ else:
+ boxes = (
+ f'<div class="box"><small>PROMPT</small><p>{_esc(pre)}</p></div>'
+ f'<div class="box" lang="zh-CN"><small>中文提示词 · Chinese prompt</small><p>{_esc(pzh)}</p></div>'
+ )
+
+ workbench = f'/#workbench/{kind}/{item["id"]}'
+ rel_html = ''.join(card_li(lang, kind, r) for r in related)
+ meta_line = (
+ (item['line'] + ' · ' + item['cat'] if is_zh else item['lineEn'] + ' · ' + cen)
+ if kind == 'pose'
+ else (cz_ if is_zh else cen)
+ )
+ more_heading = ('同类' + ('姿势' if kind == 'pose' else '穿搭' if kind in ('costume', 'anime') else '人像')) if is_zh else 'More like this'
+ body = (
+ f'<main><div class="im"><img src="/{img}" alt="{_esc(title)}" width="{w}" height="{h}" fetchpriority="high"></div>'
+ f'<div>{crumbs_html(crumbs)}<h1>{_esc(title)}</h1>'
+ f'<div class="mu">{_esc(meta_line)} · {"编号" if is_zh else "No."} {_esc(item.get("no") or item["id"])}</div>{tag_html}'
+ f'{boxes}{angle_html}'
+ f'<a class="go" href="/#{kind}/{item["id"]}">{"在衣姿中打开" if is_zh else "Open in PoseWear"}</a>'
+ f'<a class="go secondary" href="{_esc(workbench)}">{"用作参考图" if is_zh else "Use as reference"}</a></div>'
+ f'<section class="rel"><h2>{more_heading}</h2><ul>{rel_html}</ul></section></main>'
+ )
+ bid = page_url(lang, path) + '#breadcrumb'
+ ld = [
+ image_obj,
+ crumbs_ld(crumbs, bid),
+ {
+ '@type': 'WebPage',
+ '@id': page_url(lang, path),
+ 'url': page_url(lang, path),
+ 'name': ttl,
+ 'inLanguage': 'zh-CN' if is_zh else 'en',
+ 'primaryImageOfPage': {'@id': page_url(lang, path) + '#image'},
+ 'breadcrumb': {'@id': bid},
+ },
+ ]
+ return shell(lang, path, ttl, desc, body, ld, has_en=kind in HAS_EN, og=img, ogt='article', credit=lic, workbench=workbench)
+
+ # 1. Detail pages
+ for kind, items in (('pose', safe_poses), ('costume', safe_costumes), ('anime', safe_anime), ('portrait', safe_portraits)):
+ for i, item in enumerate(items):
+ cat_slug = _category_of(kind, item)[1]
+ same = [x for x in items if _category_of(kind, x)[1] == cat_slug and x['id'] != item['id']]
+ pos = sum(1 for x in items[:i] if _category_of(kind, x)[1] == cat_slug)
+ related = (same[pos:] + same[:pos])[:8]
+ imgs = [a['i'] for a in item['angles']] if kind == 'pose' else [item['m']]
+ for lang in (['zh', 'en'] if kind in HAS_EN else ['zh']):
+ prefix = '/en' if lang == 'en' else ''
+ write_page(f'{prefix}/{kind}/{item["id"]}/', detail_page(lang, kind, item, related))
+ add_sitemap(kind, f'/{kind}/{item["id"]}/', last_mod[kind], [(site + '/' + x, _zh_title(kind, item)) for x in imgs], has_en=kind in HAS_EN)
+
+ # 2. Category / tag / hub pages
+ per_page = 96
+
+ def listing_page(lang, kind, base, slug, cz_, cen, items, item_kind=None, has_en=True, sm='pages'):
+ is_zh = lang == 'zh'
+ prefix = '' if is_zh else '/en'
+ item_kind = item_kind or kind
+ total = len(items)
+ label = cz_ if is_zh else cen
+ pages = max(1, -(-total // per_page))
+ zh_suffix = '' if kind == 'tag' else {'pose': '姿势', 'costume': '穿搭', 'anime': '动画穿搭', 'portrait': '人像'}[kind]
+ en_suffix = 'Outfit' if kind in ('costume', 'tag', 'anime') else {'pose': 'Pose', 'portrait': 'Portrait'}[kind]
+ for pg in range(1, pages + 1):
+ path = f'{base}{slug}/' + (f'{pg}/' if pg > 1 else '')
+ crumbs = [
+ (LABELS[lang]['home'], prefix + '/'),
+ (LABELS[lang][kind], f'{prefix}{base}'),
+ (label, None if pg == 1 else f'{prefix}{base}{slug}/'),
+ ] + ([(f'第 {pg} 页' if is_zh else f'Page {pg}', None)] if pg > 1 else [])
+ ttl = (
+ f"{label}{zh_suffix}参考图{'' if pg == 1 else f'(第 {pg} 页)'} | 衣姿 PoseWear"
+ if is_zh
+ else f"{label} {en_suffix} References{'' if pg == 1 else f' – Page {pg}'} | PoseWear"
+ )
+ desc = LISTING_INTROS[kind][0 if is_zh else 1].format(c=label, n=total)
+ slice_items = items[(pg - 1) * per_page : pg * per_page]
+ pgn = ''
+ if pages > 1:
+ pgn = '<nav class="pg" aria-label="pagination">' + ''.join(
+ f'<b>{i}</b>' if i == pg else f'<a href="{prefix}{base}{slug}/{"" if i == 1 else str(i) + "/"}">{i}</a>'
+ for i in range(1, pages + 1)
+ ) + '</nav>'
+ body = (
+ f'<div class="wrap">{crumbs_html(crumbs)}<h1>{_esc(ttl.split(" | ")[0])}</h1>'
+ f'<p class="lead">{_esc(desc)}</p>'
+ f'<ul class="cg">{"".join(card_li(lang, item_kind, it) for it in slice_items)}</ul>{pgn}</div>'
+ )
+ ld = [
+ {
+ '@type': 'CollectionPage',
+ '@id': page_url(lang, path),
+ 'url': page_url(lang, path),
+ 'name': ttl,
+ 'description': desc,
+ 'inLanguage': 'zh-CN' if is_zh else 'en',
+ 'isPartOf': {'@type': 'WebSite', 'name': '衣姿 PoseWear', 'url': site + '/'},
+ },
+ crumbs_ld(crumbs),
+ {
+ '@type': 'ItemList',
+ 'numberOfItems': len(slice_items),
+ 'itemListElement': [
+ {
+ '@type': 'ListItem',
+ 'position': i + 1,
+ 'url': site + ('/en' if not is_zh and item_kind in HAS_EN else '') + f'/{item_kind}/{it["id"]}/',
+ }
+ for i, it in enumerate(slice_items)
+ ],
+ },
+ ]
+ write_page(prefix + path, shell(lang, path, ttl, desc, body, ld, has_en=has_en))
+ if is_zh:
+ add_sitemap(sm, path, last_mod[item_kind], has_en=has_en)
+
+ cats = {
+ 'pose': [(POSE_CATEGORIES[k][0], k, POSE_CATEGORIES[k][1], L) for k in POSE_CATEGORIES if (L := [p for p in safe_poses if p['cat'] == k])],
+ 'costume': [(COSTUME_CATEGORIES[k][0], k, COSTUME_CATEGORIES[k][1], L) for k in COSTUME_CATEGORIES if (L := [c for c in safe_costumes if c['cat'] == k])],
+ 'anime': [(COSTUME_CATEGORIES[k][0], k, COSTUME_CATEGORIES[k][1], L) for k in COSTUME_CATEGORIES if (L := [c for c in safe_anime if c['cat'] == k])],
+ 'portrait': (
+ [(PORTRAIT_SECTIONS[k][0], k, PORTRAIT_SECTIONS[k][1], L) for k in PORTRAIT_SECTIONS if (L := [r for r in safe_portraits if r['sec'] == k])]
+ + [(PORTRAIT_LENGTHS[k][0], k, PORTRAIT_LENGTHS[k][1], L) for k in PORTRAIT_LENGTHS if (L := [r for r in safe_portraits if r['len'] == k])]
+ ),
+ }
+
+ for lang in ('zh', 'en'):
+ for kind, cat_list in cats.items():
+ for slug, zh_name, en_name, items in cat_list:
+ listing_page(lang, kind, f'/{kind}/', slug, zh_name, en_name, items)
+ for slug, tag_entry in tags_map.items():
+ listing_page(lang, 'tag', '/tag/', slug, tag_entry['zh'], tag_entry['en'], tag_entry['L'], item_kind='costume')
+
+ counts = {
+ 'pose': len(safe_poses),
+ 'costume': len(safe_costumes),
+ 'anime': len(safe_anime),
+ 'portrait': len(safe_portraits),
+ 'tag': len(tags_map),
+ }
+
+ def hub_page(lang, kind):
+ is_zh = lang == 'zh'
+ prefix = '' if is_zh else '/en'
+ path = f'/{kind}/'
+ name = HUB_NAMES[kind][0 if is_zh else 1]
+ if kind != 'tag':
+ entries = [(s, z, e, len(items)) for s, z, e, items in cats[kind]]
+ first = {s: items[0] for s, _, _, items in cats[kind]}
+ else:
+ entries = [(s, t['zh'], t['en'], len(t['L'])) for s, t in sorted(tags_map.items(), key=lambda pair: -len(pair[1]['L']))]
+ first = {s: t['L'][0] for s, t in tags_map.items()}
+ desc = HUB_INTROS[kind][0 if is_zh else 1].format(n=counts[kind])
+ crumbs = [(LABELS[lang]['home'], prefix + '/'), (LABELS[lang][kind], None)]
+ item_kind = 'costume' if kind == 'tag' else kind
+ tw, th = THUMB_DIMENSIONS[item_kind]
+ li_html = ''.join(
+ f'<li><a href="{prefix}/{kind}/{slug}/">'
+ f'<img src="{thumb_url(_thumb(item_kind, first[slug]))}" alt="{_esc(zh if is_zh else en)}" width="{tw}" height="{th}" loading="lazy" decoding="async">'
+ f'<span>{_esc(zh if is_zh else en)} · {cnt}</span></a></li>'
+ for slug, zh, en, cnt in entries
+ )
+ extra = '' if kind != 'costume' else f'<p><a href="{prefix}/tag/">{"按单品和颜色浏览 →" if is_zh else "Browse by garment and colour →"}</a></p>'
+ body = f'<div class="wrap">{crumbs_html(crumbs)}<h1>{_esc(name)}</h1><p class="lead">{_esc(desc)}</p><ul class="cg">{li_html}</ul>{extra}</div>'
+ ld = [
+ {'@type': 'CollectionPage', 'url': page_url(lang, path), 'name': name, 'description': desc, 'inLanguage': 'zh-CN' if is_zh else 'en'},
+ crumbs_ld(crumbs),
+ ]
+ write_page(prefix + path, shell(lang, path, f'{name} | 衣姿 PoseWear' if is_zh else f'{name} | PoseWear', desc, body, ld))
+ if is_zh:
+ add_sitemap('pages', path, today)
+
+ for lang in ('zh', 'en'):
+ for kind in HUB_NAMES:
+ hub_page(lang, kind)
+
+ # 3. English home page
+ cat_links_en = ''.join(
+ f'<li><a href="/en/{k}/{s}/">{_esc(en)}</a></li>'
+ for k in ('pose', 'costume')
+ for s, _, en, _ in cats[k]
+ )
+ en_desc = f'PoseWear: {len(safe_poses)} pose sets ({na_pub} angle images), {len(safe_costumes):,} outfits, {len(safe_anime):,} anime outfits and {len(safe_portraits):,} CC0 portraits, all with English and Chinese prompts — plus online AI try-on.'
+ en_ld = [
+ {
+ '@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', 'ja'],
+ 'offers': {'@type': 'Offer', 'price': '0', 'priceCurrency': 'USD'},
+ 'description': en_desc,
+ },
+ ]
+ en_body = (
+ f'<div class="wrap"><h1>Pose, outfit and portrait references with prompts</h1>'
+ f'<p class="lead">{_esc(en_desc)} Favourite and combine references, copy prompts for Stable Diffusion or Midjourney, or upload your own photo to try an outfit on.</p>'
+ f'<p><a class="go" href="/#costume">Open the gallery</a><a class="go secondary" href="/#studio">Try on online</a></p>'
+ f'<section class="sec"><h2>Browse by category</h2><ul class="tg">{cat_links_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>'
+ f'<section class="sec"><h2>Outfits</h2><ul class="cg">{"".join(card_li("en", "costume", c) for c in safe_costumes[:12])}</ul></section>'
+ f'<section class="sec"><h2>Poses</h2><ul class="cg">{"".join(card_li("en", "pose", p) for p in safe_poses[:12])}</ul></section>'
+ f'</div>'
+ )
+ en_credit = (
+ '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 '
+ f'<a href="https://x.com/agi_aibusi">@agi_aibusi</a> under <a href="{CC0_URL}" rel="license">CC0 1.0</a>.'
+ )
+ write_page('/en/', shell('en', '/', 'PoseWear – Pose & Outfit Reference Library with AI Prompts and Online Try-On', en_desc, en_body, en_ld, credit=en_credit))
+ add_sitemap('pages', '/', today)
+
+ # 4. Chinese home page: meta, JSON-LD, live stats, SSR first 12 poses, footer category index
+ home_pub = {'pose': len(safe_poses), 'ang': na_pub, 'cos': len(safe_costumes), 'ani': anime_pub, 'por': len(safe_portraits)}
+ home_all = {'pose': len(poses), 'ang': na_total, 'cos': len(costumes), 'ani': len(anime), 'por': len(portraits)}
+ for stat_key, filename in EXTRA_CATALOG_STATS:
+ raw_payload = catalogs[filename]
+ parsed = json.loads(raw_payload) if isinstance(raw_payload, str) else raw_payload
+ items = parsed['items'] if isinstance(parsed, dict) else parsed
+ home_pub[stat_key] = sum(1 for item in items if not item.get('a'))
+ home_all[stat_key] = len(items)
+
+ zh_desc = f"衣姿 PoseWear:{home_pub['pose']} 组姿势({home_pub['ang']:,} 张角度图)、{home_pub['cos']:,} 套服装、{home_pub['ani']:,} 套动画服装、{home_pub['por']:,} 张人像参考图,附中英文提示词,可上传照片在线 AI 试穿。免费,无需注册。"
+ zh_title = '衣姿 PoseWear · 姿势、服装、人像参考图库 | 中英文提示词 + 在线 AI 试穿'
+
+ index_path = os.path.join(dist_dir, 'index.html')
+ with open(index_path) as fh:
+ idx = fh.read()
+ idx = re.sub(r'<title>.*?</title>', f'<title>{zh_title}</title>', idx, count=1)
+ idx = re.sub(r'<meta name="description" content="[^"]*">', f'<meta name="description" content="{_esc(zh_desc)}">', idx, count=1)
+ idx = re.sub(r'<meta property="og:title" content="[^"]*">', '<meta property="og:title" content="衣姿 PoseWear:姿势、服装、人像参考图库">', idx, count=1)
+ idx = re.sub(r'<meta property="og:description" content="[^"]*">', f'<meta property="og:description" content="{_esc(zh_desc)}">', idx, count=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="{_esc(zh_desc)}">', 1)
+ idx = idx.replace('https://posewear.pages.dev/', site + '/')
+ idx = idx.replace(f'<link rel="canonical" href="{site}/">', f'<link rel="canonical" href="{site}/">' + hreflang_tags('/'))
+ home_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', 'ja'],
+ 'offers': {'@type': 'Offer', 'price': '0', 'priceCurrency': 'CNY'},
+ 'description': zh_desc,
+ 'image': site + '/og.png',
+ 'isAccessibleForFree': True,
+ 'featureList': ['姿势参考图(多角度)', '服装穿搭参考图', '人像脸模参考(CC0)', '中英文提示词', '在线 AI 试穿'],
+ },
+ ]
+ home_ld_json = json.dumps({'@context': 'https://schema.org', '@graph': home_ld}, ensure_ascii=False, separators=(',', ':'))
+ idx = idx.replace('</head>', f'<script type="application/ld+json">{home_ld_json}</script></head>', 1)
+
+ for key in home_pub:
+ idx = re.sub(
+ r'<b (?=[^>]*data-stat="' + key + r'")[^>]*>[^<]*</b>',
+ f'<b data-stat="{key}" data-n="{home_pub[key]}" data-na="{home_all[key]}">{home_pub[key]:,}</b>',
+ idx,
+ count=1,
+ )
+
+ def ssr_pose(pos_idx, pose):
+ loading = '' if pos_idx < 4 else ' loading="lazy"'
+ title = pose['zh']
+ angles = pose['angles']
+ return (
+ f'<article class="card ssr"><div class="ph pose done">'
+ f'<a href="/pose/{pose["id"]}/" class="ssl">'
+ f'<img class="ld" src="{thumb_url(angles[0]["t"])}" alt="{_esc(title)}" width="300" height="400" decoding="async"{loading}></a>'
+ f'<span class="badge">{pose["no"]}</span></div>'
+ f'<div class="info"><h3><a href="/pose/{pose["id"]}/">{_esc(title)}</a></h3>'
+ f'<div class="sub">{_esc(pose["cat"])} · {len(angles)} 个角度</div>'
+ f'<div class="tags"><span class="tag">{_esc(pose["line"])}</span><span class="tag c">{_esc(pose["cat"])}</span></div></div></article>'
+ )
+
+ grid_match = re.search(r'(<main id="grid"[^>]*>)(.*?)(</main>)', idx, re.S)
+ idx = idx[:grid_match.start(2)] + ''.join(ssr_pose(i, p) for i, p in enumerate(safe_poses[:12])) + idx[grid_match.end(2):]
+ cat_nav = (
+ '<nav class="seoc" aria-label="分类浏览">'
+ '<div><h4>姿势分类</h4>' + ''.join(f'<a href="/pose/{s}/">{z}</a>' for s, z, _, _ in cats['pose']) + '</div>'
+ '<div><h4>服装分类</h4>' + ''.join(f'<a href="/costume/{s}/">{z}</a>' for s, z, _, _ in cats['costume']) + '<a href="/tag/">按单品和颜色</a></div>'
+ '<div><h4>人像</h4>' + ''.join(f'<a href="/portrait/{s}/">{z}</a>' for s, z, _, _ 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('<!-- category-index -->', '<details class="footer-index"><summary>分类索引</summary>' + cat_nav + '</details>')
+ with open(index_path, 'w') as fh:
+ fh.write(idx)
+
+ # 5. Sitemaps, robots.txt, URL list and extra cache headers
+ def sitemap_xml(entries):
+ out = ['<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">\n']
+ for loc, lm, imgs in entries:
+ img_tags = ''.join(f'<image:image><image:loc>{_esc(u)}</image:loc></image:image>' for u, _ in imgs)
+ out.append(f'<url><loc>{loc}</loc><lastmod>{lm}</lastmod>{img_tags}</url>\n')
+ return ''.join(out) + '</urlset>\n'
+
+ sitemaps['pages'].insert(0, (site + '/', today, [(site + '/og.png', '')]))
+ for sm_key, entries in sitemaps.items():
+ with open(os.path.join(dist_dir, f'sitemap-{sm_key}.xml'), 'w') as fh:
+ fh.write(sitemap_xml(entries))
+
+ sitemap_index = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
+ + ''.join(
+ f'<sitemap><loc>{site}/sitemap-{sm_key}.xml</loc><lastmod>{max((x[1] for x in entries), default=today)}</lastmod></sitemap>\n'
+ for sm_key, entries in sitemaps.items()
+ )
+ + '</sitemapindex>\n'
+ )
+ for name in ('sitemap_index.xml', 'sitemap.xml'):
+ with open(os.path.join(dist_dir, name), 'w') as fh:
+ fh.write(sitemap_index)
+
+ with open(os.path.join(dist_dir, 'robots.txt'), 'w') as fh:
+ fh.write(f'User-agent: *\nAllow: /\nDisallow: /api/\nDisallow: /o/\n\nSitemap: {site}/sitemap_index.xml\n')
+
+ with open(urls_path, 'w') as fh:
+ fh.write('\n'.join(loc for entries in sitemaps.values() for loc, _, _ in entries) + '\n')
+
+ with open(os.path.join(dist_dir, '_headers'), 'a') as fh:
+ fh.write('/en/*\n Cache-Control: public, max-age=600\n/tag/*\n Cache-Control: public, max-age=600\n/sitemap*\n Cache-Control: public, max-age=3600\n')
+
+ summary = {'na_pub': na_pub, 'sitemaps': {k: len(v) for k, v in sitemaps.items()}, 'tags': len(tags_map)}
+ print('NA_PUB', na_pub)
+ print('seo', summary['sitemaps'], 'tags', summary['tags'])
+ return summary
diff --git a/src/app.js b/src/app.js
index 95fe745..8740ce4 100644
--- a/src/app.js
+++ b/src/app.js
@@ -1,1198 +1,2368 @@
'use strict';
-const _u=new URLSearchParams(location.search);let Q0=(_u.get('q')||'').slice(0,60),QT=_u.get('t')||'';
-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=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
-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;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){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,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(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'};
-const COL_SWATCH={'黑':'#1c1c1e','白':'#ffffff','红':'#d92d46','粉':'#f2a5b8','蓝':'#3b7dd8','藏青':'#223354','棕':'#80553a','米':'#d8cab6','象牙白':'#f5f1e6','灰':'#8e8e93','绿':'#478a5d','黄':'#d8be6b','紫':'#8664b8','金':'#b89e68','银':'#c0c4ca','卡其':'#b5a27e','酒红':'#7c2237','橙':'#df7a42','奶油':'#f3ebd8','薄荷':'#8fd3be','薰衣草':'#b8a5d6','橄榄':'#687444'};
-const ITEMK={'连衣裙':'dress','半身裙':'skirt','短裤':'shorts','长裤':'trousers','牛仔裤':'jeans','大衣':'coat','夹克':'jacket','开衫':'cardigan','衬衫':'blouse','毛衣':'sweater','吊带':'camisole','文胸':'bra','泳衣':'swimsuit','靴子':'boots','高跟鞋':'high heels','运动鞋':'sneakers','凉鞋':'sandals','连裤袜':'tights','长筒袜':'stockings'};
-const SUGG={pose:['站姿','坐姿','回头','双手抱头','可爱','躺卧','比心','跪立'],depth:['站姿','坐姿','上半身','全身','俯拍','侧面','可爱','跪立'],costume:['连衣裙','黑色','泳装','针织','蕾丝','冬季','牛仔','高跟鞋'],anime:['连衣裙','黑色','泳装','针织','蕾丝','冬季','牛仔','制服'],portrait:['短发','波波','狼尾','刘海','卷','奶茶','黑发','正脸'],expr:['开心','大笑','愤怒','害羞','搞怪','严肃'],hair:['长发','双马尾','刘海','发饰','瞳色'],dyn:['唐','宋','明','曲裾','齐胸'],scene:['客厅','庭院','街道','海岸'],light:['伦勃朗','窗光','黄昏','夜景'],prop:['吉他','油纸伞','灯笼','相机'],furn:['餐椅','沙发','造型台','床榻'],fav:[],recent:[]};
-function base(){return(st.tab=='fav'?[...st.fav].reverse().map(k=>ITEMS[k]):st.tab=='recent'?st.rec.map(k=>ITEMS[k]):DATA[st.tab]||[]).filter(ok)}
-function val(it,key){if(key=='ang')return it.angles.map(a=>a.zh);if(key=='type')return[TL(it)];
- if(key=='col'){if(!it.kw)return[];if(!it._c){const w=' '+it.kw+' ';it._c=Object.keys(COLS).filter(c=>w.includes(' '+COLS[c]+' '))}return it._c}
- if(key=='item'){if(!it.kw)return[];if(!it._i){const e=' '+it.en.replace(/,/g,' ')+' ';it._i=Object.keys(ITEMK).filter(z=>e.includes(' '+ITEMK[z]+' '))}return it._i}return it[key]?[it[key]]:[]}
-function drawFilters(){
- const filters = $('#filters');
- const positions = new Map();
- let focusedChip;
- if (filters.dataset.filterTab === st.tab) {
- for (const row of filters.querySelectorAll('.frow')) {
- 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 rowList=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" 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])=>{const sw=key==='col'&&COL_SWATCH[v]?`<span class="csw" style="--sw:${COL_SWATCH[v]}" aria-hidden="true"></span>`:'';return `<button class="chip ${st.f[key]==v?'on':''}" data-k="${key}" data-v="${esc(v)}" aria-pressed="${st.f[key]==v}">${sw}${esc(v)}<i>${n}</i></button>`}).join('')}</div>`}).filter(Boolean);
- filters.innerHTML=`<div class="dh"><b>筛选</b><button class="sm pri" data-done>完成</button></div>`+rowList.join('');
- filters.dataset.filterTab = st.tab;
- const hasMoreRows=rowList.length>1;
- $('#fBtn').hidden=!hasMoreRows;
- if(!hasMoreRows)drawer(false);
- for (const row of filters.querySelectorAll('.frow')) {
- row.scrollLeft = positions.get(row.dataset.filter) ?? 0;
- }
- if (focusedChip) {
- const replacement = [...filters.querySelectorAll('.chip')].find(chip =>
- chip.dataset.k === focusedChip.k && chip.dataset.v === focusedChip.v);
- replacement?.focus({preventScroll:true});
- }
- 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 countMarkup(list,all){
- const imgs=a=>a.reduce((n,it)=>n+(it.angles?it.angles.length:1),0);
- return st.tab=='depth'?(list.length==all.length?`共 <b>${all.length}</b> 组 · ${imgs(all)} 张`:`<b>${list.length}</b> / ${all.length} 组 · ${imgs(list)} 张`):(list.length==all.length?`共 <b>${all.length}</b> 项`:`<b>${list.length}</b> / ${all.length} 项`);
-}
-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){
- 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 all=base(),tot=all.length;
- $('#count').innerHTML=countMarkup(L,all);$('#grid').innerHTML='';st.n=0;
- const em=!L.length;$('#empty').hidden=!em;$('#clearAll').hidden=!(Object.values(st.f).some(Boolean)||st.q);
- if($('#sketchBtn'))$('#sketchBtn').hidden=L.length<2;
- 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(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'?'切换到深度图':'切换到线稿',hint=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><em class="flip-hint" aria-hidden="true">${hint}</em></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 miss=D?`<a class="miss" href="${esc(it.site)}" target="_blank" rel="noopener">请前往原站查看</a>`:'';
- 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></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(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="rgrp">${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.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 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));
-}
-function updateCardAngle(it){
- const key=CSS.escape(it.k),nextSrc=thumb(it);
- grid.querySelectorAll(`.card[data-show="${key}"],.card[data-k="${key}"]:not([data-show])`).forEach(el=>{
- const origin=ITEMS[el.dataset.k],ph=el.querySelector('.ph'),img=ph.querySelector('img');
- if(img&&img.getAttribute('src')!==nextSrc){ph.classList.remove('err');img.src=nextSrc}
- el.querySelectorAll('.angs [data-a="ang"]').forEach(btn=>{
- const on=+btn.dataset.i===it.ai;btn.classList.toggle('on',on);btn.setAttribute('aria-pressed',String(on));
+(() => {
+ const C = window.PoseWearCatalog;
+ if (!C) return;
+ const {
+ $, $$, esc, readLS: LS, writeLS: SV, shuffle,
+ TABS, TNAME, PFX, KT, TL, FDEF, FLAB, COLS, COL_SWATCH, ITEMK, SUGG, STUDIO_SLOT, studioSlot,
+ } = C;
+
+ // Build-injected asset host & catalog manifest filenames.
+ // Kept verbatim so post.py, scripts/preview.mjs, scripts/catalog-source.mjs,
+ // and tests/check_csp.py can discover the asset host and all 12 catalog manifests.
+ const AH='';
+ const CATALOG_FILES = {
+ 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',
+ };
+
+ const params = new URLSearchParams(location.search);
+ let Q0 = (params.get('q') || '').slice(0, 60);
+ const QT = params.get('t') || '';
+
+ const motionPreference = matchMedia('(prefers-reduced-motion: reduce)');
+ const ITEMS = {};
+ const DATA = {};
+ const LOAD = {};
+
+ 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(type) {
+ if (LOAD[type]) return LOAD[type];
+ LOAD[type] = fetch(CATALOG_FILES[type])
+ .then(res => {
+ if (!res.ok) throw Error(res.status);
+ return res.json();
+ })
+ .then(raw => {
+ const list = Array.isArray(raw) ? raw : (raw.items || []);
+ if (type === 'depth') DATA.depthMeta = raw.pack || null;
+ list.forEach((it, index) => {
+ it.type = type;
+ it.k = PFX[type] + it.id;
+ it.ord = index;
+ if (it.angles) it.ai = st.ang[it.k] || 0;
+ ITEMS[it.k] = it;
+ });
+ DATA[type] = list;
+ counts();
+ return list;
+ })
+ .catch(err => {
+ delete LOAD[type];
+ throw err;
+ });
+ return LOAD[type];
+ }
+
+ 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 = keys => Promise.all([...new Set(keys.map(k => KT[k[0]]).filter(Boolean))].map(load));
+ const ath = url => (url.startsWith('http') ? url : AH + url);
+ const thumb = it => ath(it.angles ? it.angles[it.ai].t : it.t);
+ const 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) {
+ 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, layout = it.type) => {
+ if (layout === 'depth') return it.ja;
+ if (st.lang === 'en') return prompt(it, 'en');
+ if (layout === 'pose') return `${it.cat} · ${it.angles.length} 个角度`;
+ if (layout === 'portrait') return `${it.sec} · ${it.len}${it.rk ? ' · 人气第 ' + it.rk : ''}`;
+ return it.zh;
+ };
+
+ function recordNotice(text) {
+ const last = $('#noticeAction');
+ last.textContent = text;
+ last.hidden = false;
+ }
+
+ function toast(text, undo) {
+ recordNotice(text);
+ const el = $('#toast');
+ el.textContent = text;
+ if (undo) {
+ const btn = document.createElement('button');
+ btn.textContent = '撤销';
+ btn.onclick = () => {
+ el.classList.remove('on', 'act');
+ undo();
+ };
+ el.append(btn);
+ }
+ el.classList.toggle('act', !!undo);
+ el.classList.remove('on');
+ void el.offsetWidth;
+ el.classList.add('on');
+ clearTimeout(el._t);
+ el._t = setTimeout(() => el.classList.remove('on', 'act'), undo ? 4500 : 1800);
+ }
+
+ const EMPTY_ICONS = {
+ 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(text, label) {
+ try {
+ await navigator.clipboard.writeText(text);
+ } catch {
+ const field = document.createElement('textarea');
+ const 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 stat = button.querySelector('[data-stat]');
+ const items = DATA[button.dataset.tab];
+ if (items) {
+ stat.dataset.n = items.filter(it => !it.a).length;
+ stat.dataset.na = items.length;
+ }
+ const count = Number((st.adult && stat.dataset.na) || stat.dataset.n);
+ stat.textContent = String(count);
+ quantities.push(count);
+ }
+ const maximum = Math.max(1, ...quantities);
+ bars.forEach((button, index) => button.style.setProperty('--share', quantities[index] / maximum));
+ const favCount = [...st.fav].filter(k => !ITEMS[k] || ok(ITEMS[k])).length;
+ $('#nFav').textContent = favCount || '';
+ $('#nRec').textContent = st.rec.filter(k => !ITEMS[k] || ok(ITEMS[k])).length || '';
+ }
+
+ function base() {
+ const list =
+ st.tab === 'fav'
+ ? [...st.fav].reverse().map(k => ITEMS[k])
+ : st.tab === 'recent'
+ ? st.rec.map(k => ITEMS[k])
+ : DATA[st.tab] || [];
+ return list.filter(ok);
+ }
+
+ function val(it, key) {
+ if (key === 'ang') return it.angles.map(a => a.zh);
+ if (key === 'type') return [TL(it)];
+ if (key === 'col') {
+ if (!it.kw) return [];
+ if (!it._c) {
+ const padded = ` ${it.kw} `;
+ it._c = Object.keys(COLS).filter(c => padded.includes(` ${COLS[c]} `));
+ }
+ return it._c;
+ }
+ if (key === 'item') {
+ if (!it.kw) return [];
+ if (!it._i) {
+ const padded = ` ${it.en.replace(/,/g, ' ')} `;
+ it._i = Object.keys(ITEMK).filter(z => padded.includes(` ${ITEMK[z]} `));
+ }
+ return it._i;
+ }
+ return it[key] ? [it[key]] : [];
+ }
+
+ function drawFilters() {
+ const filters = $('#filters');
+ const positions = new Map();
+ let focusedChip;
+ if (filters.dataset.filterTab === st.tab) {
+ for (const row of filters.querySelectorAll('.frow')) {
+ positions.set(row.dataset.filter, row.scrollLeft);
+ }
+ const active = document.activeElement;
+ if (filters.contains(active) && active.matches('.chip')) focusedChip = active.dataset;
+ }
+
+ const items = base();
+ const rowList = FDEF[st.tab]
+ .map(([key, label]) => {
+ const freq = {};
+ items.forEach(it => val(it, key).forEach(v => { freq[v] = (freq[v] || 0) + 1; }));
+ const entries = Object.entries(freq).sort((a, b) => b[1] - a[1]);
+ if (entries.length < 2 && !st.f[key]) return '';
+ const chips = entries
+ .map(([v, n]) => {
+ const swatch = key === 'col' && COL_SWATCH[v]
+ ? `<span class="csw" style="--sw:${COL_SWATCH[v]}" aria-hidden="true"></span>`
+ : '';
+ const active = st.f[key] === v;
+ return `<button class="chip ${active ? 'on' : ''}" data-k="${key}" data-v="${esc(v)}" aria-pressed="${active}">${swatch}${esc(v)}<i>${n}</i></button>`;
+ })
+ .join('');
+ return `<div class="frow" role="group" data-filter="${key}" aria-label="${label}"><label>${label}</label><button class="chip ${!st.f[key] ? 'on' : ''}" data-k="${key}" data-v="" aria-pressed="${!st.f[key]}">全部</button>${chips}</div>`;
+ })
+ .filter(Boolean);
+
+ filters.innerHTML = '<div class="dh"><b>筛选</b><button class="sm pri" data-done>完成</button></div>' + rowList.join('');
+ filters.dataset.filterTab = st.tab;
+
+ const hasMoreRows = rowList.length > 1;
+ $('#fBtn').hidden = !hasMoreRows;
+ if (!hasMoreRows) drawer(false);
+
+ for (const row of filters.querySelectorAll('.frow')) {
+ row.scrollLeft = positions.get(row.dataset.filter) ?? 0;
+ }
+ if (focusedChip) {
+ const replacement = [...filters.querySelectorAll('.chip')].find(
+ chip => chip.dataset.k === focusedChip.k && chip.dataset.v === focusedChip.v
+ );
+ replacement?.focus({ preventScroll: true });
+ }
+
+ const activeFilters = Object.entries(st.f).filter(([, v]) => v);
+ $('#active').innerHTML = activeFilters
+ .map(([k, v]) => `<button data-k="${k}" title="移除此条件">${FLAB[k]}:${esc(v)} ✕</button>`)
+ .join('');
+ $('#fN').textContent = activeFilters.length || '';
+ $('#clearAll').hidden = !(activeFilters.length || st.q);
+ }
+
+ function countMarkup(list, all) {
+ const imageCount = arr => arr.reduce((n, it) => n + (it.angles ? it.angles.length : 1), 0);
+ if (st.tab === 'depth') {
+ return list.length === all.length
+ ? `共 <b>${all.length}</b> 组 · ${imageCount(all)} 张`
+ : `<b>${list.length}</b> / ${all.length} 组 · ${imageCount(list)} 张`;
+ }
+ return list.length === all.length
+ ? `共 <b>${all.length}</b> 项`
+ : `<b>${list.length}</b> / ${all.length} 项`;
+ }
+
+ function searchHaystack(it) {
+ if (!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();
+ }
+ return it._s;
+ }
+
+ function apply(previousView) {
+ const words = st.q.toLowerCase().trim().split(/\s+/).filter(Boolean);
+ let list = base().filter(
+ it =>
+ Object.entries(st.f).every(([k, v]) => !v || val(it, k).includes(v)) &&
+ words.every(w => searchHaystack(it).includes(w))
+ );
+
+ if (st.f.ang) {
+ for (const it of list) {
+ 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') {
+ list = list.slice().reverse();
+ } else if (st.sort === 'shuf') {
+ const order = previousView?.order;
+ list = order
+ ? list.sort((a, b) => (order.get(a.k) ?? Infinity) - (order.get(b.k) ?? Infinity))
+ : shuffle(list);
+ } else if (st.sort === 'rank') {
+ list = list.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') {
+ list = list.slice().sort((a, b) => st.fav.has(b.k) - st.fav.has(a.k));
+ }
+
+ st.list = list;
+ window.X?.filterBatch?.(list.map(cardFace));
+
+ const all = base();
+ const total = all.length;
+ $('#count').innerHTML = countMarkup(list, all);
+ $('#grid').innerHTML = '';
+ st.n = 0;
+
+ const empty = !list.length;
+ $('#empty').hidden = !empty;
+ $('#clearAll').hidden = !(Object.values(st.f).some(Boolean) || st.q);
+ if ($('#sketchBtn')) $('#sketchBtn').hidden = list.length < 2;
+ document.body.classList.toggle('none0', (st.tab === 'fav' || st.tab === 'recent') && !total);
+
+ if (empty) {
+ const none = (st.tab === 'fav' || st.tab === 'recent') && !total;
+ $('#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' ? EMPTY_ICONS.fav : EMPTY_ICONS.rec) : EMPTY_ICONS.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(previousView?.count || 30);
+ }
+
+ 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);
+ const label = it.type === 'pose' ? '切换到深度图' : '切换到线稿';
+ const hint = 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>` +
+ `<em class="flip-hint" aria-hidden="true">${hint}</em></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, delay) {
+ const it = cardFace(origin);
+ const isSel = st.sel.includes(it.k);
+ const isFav = st.fav.has(it.k);
+ const isPose = it.type === 'pose';
+ const isDepth = it.type === 'depth';
+ const hasAngles = isPose || isDepth || !!it.angles;
+ const label = title(it);
+ const miss = isDepth ? `<a class="miss" href="${esc(it.site)}" target="_blank" rel="noopener">请前往原站查看</a>` : '';
+ const w = hasAngles ? 300 : it.type === 'portrait' ? 400 : 360;
+ const h = hasAngles ? 400 : it.type === 'portrait' ? 500 : 540;
+ const topBadge = hasAngles
+ ? (isPose || isDepth ? cardBadges(it) : `<span class="badge">${esc(it.no)}</span>${it.a ? '<span class="badge age">18+</span>' : ''}`) +
+ `<div class="angs">${cardAngles(origin, it)}</div>`
+ : '';
+
+ return (
+ `<article class="card ${window.X?.batchPicked?.(it.k) ? 'picked' : ''} ${isSel ? 'sel' : ''}" data-k="${origin.k}"${origin !== it ? ` data-show="${it.k}"` : ''} style="animation-delay:${delay || 0}ms">` +
+ `<div class="ph ${isDepth ? 'depth' : isPose ? 'pose' : 'cos'}" data-a="open">` +
+ `<img loading="lazy" decoding="async"${isDepth ? ` referrerpolicy="${esc(it.ref || 'no-referrer')}"` : ''} src="${esc(thumb(it))}" alt="${esc(label)}" width="${w}" height="${h}" draggable="false">` +
+ `${miss}<button class="phk" data-a="open" aria-label="${esc(label)}"></button>` +
+ `${it.rk ? `<span class="badge rk">TOP ${it.rk}</span>` : ''}${topBadge}` +
+ `${st.tab === 'recent' ? '<button data-a="unrec" class="unrec" title="从记录中移除" aria-label="从记录中移除">✕</button>' : ''}` +
+ `<div class="cbtns">` +
+ `<button data-a="fav" class="${isFav ? 'on' : ''}" title="${isFav ? '取消收藏' : '收藏'}" aria-label="收藏" aria-pressed="${isFav}">${isFav ? '♥' : '♡'}</button>` +
+ `<button data-a="sel" class="${isSel ? 'on' : ''}" title="${isSel ? '移出组合' : '加入组合'}" aria-label="加入组合" aria-pressed="${isSel}">${isSel ? '✓' : '+'}</button>` +
+ `</div>${isDepth ? '' : `<button class="try" data-a="try">${tryLabel(it, trayOpen)}</button>`}</div>` +
+ `<div class="info"><div class="card-heading"><h3 title="${esc(label)}">${esc(label)}</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></article>`
+ );
+ }
+
+ function recentGroup(key) {
+ const ts = st.recT[key];
+ if (!ts) return '更早';
+ const dayStart = new Date();
+ dayStart.setHours(0, 0, 0, 0);
+ if (ts >= dayStart) return '今天';
+ if (ts >= dayStart - 864e5) return '昨天';
+ if (ts >= dayStart - 6 * 864e5) return '近 7 天';
+ return '更早';
+ }
+
+ function more(count = 30) {
+ if (st.n >= st.list.length) return;
+ const grouped = st.tab === 'recent' && !st.q && !Object.values(st.f).some(Boolean);
+ let prevGroup = grouped && st.n ? recentGroup(st.list[st.n - 1].k) : '';
+ const html = st.list
+ .slice(st.n, st.n + count)
+ .map((it, i) => {
+ let heading = '';
+ if (grouped) {
+ const g = recentGroup(it.k);
+ if (g !== prevGroup) {
+ heading = `<h4 class="rgrp">${g}</h4>`;
+ prevGroup = g;
+ }
+ }
+ return heading + card(it, motionPreference.matches ? 0 : Math.min(i, 14) * 35);
+ })
+ .join('');
+ st.n += count;
+ $('#grid').insertAdjacentHTML('beforeend', html);
+ }
+
+ const grid = $('#grid');
+ grid.addEventListener('load', e => {
+ if (e.target.tagName !== 'IMG') return;
+ 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(entries => entries[0].isIntersecting && more(), { rootMargin: '1400px' }).observe($('#sentinel'));
+
+ function replaceCard(el, prepared) {
+ const origin = ITEMS[el.dataset.k];
+ const oldImage = el.querySelector('img');
+ const wrapper = document.createElement('div');
+ wrapper.innerHTML = card(origin);
+ const nextCard = wrapper.firstElementChild;
+ const ph = nextCard.querySelector('.ph');
+ const img = ph.querySelector('img');
+ nextCard.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(nextCard);
+ if (action) {
+ const sel = `button[data-a="${CSS.escape(action)}"]` + (active.dataset.i != null ? `[data-i="${CSS.escape(active.dataset.i)}"]` : '');
+ nextCard.querySelector(sel)?.focus({ preventScroll: true });
+ }
+ }
+
+ function refreshCard(key) {
+ const escaped = CSS.escape(key);
+ grid.querySelectorAll(`.card[data-show="${escaped}"],.card[data-k="${escaped}"]:not([data-show])`).forEach(el => replaceCard(el));
+ }
+
+ function updateCardAngle(it) {
+ const escaped = CSS.escape(it.k);
+ const nextSrc = thumb(it);
+ grid.querySelectorAll(`.card[data-show="${escaped}"],.card[data-k="${escaped}"]:not([data-show])`).forEach(el => {
+ const origin = ITEMS[el.dataset.k];
+ const ph = el.querySelector('.ph');
+ const img = ph.querySelector('img');
+ if (img && img.getAttribute('src') !== nextSrc) {
+ ph.classList.remove('err');
+ img.src = nextSrc;
+ }
+ el.querySelectorAll('.angs [data-a="ang"]').forEach(btn => {
+ const on = +btn.dataset.i === it.ai;
+ btn.classList.toggle('on', on);
+ btn.setAttribute('aria-pressed', String(on));
+ });
+ const badges = el.querySelector('.card-badges');
+ if (badges && (it.type === 'pose' || it.type === 'depth')) badges.outerHTML = cardBadges(it);
+ const sub = el.querySelector('.info .sub');
+ if (sub && origin) sub.textContent = subtitle(it, origin.type);
+ });
+ }
+
+ 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();
+ const 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);
+ updateCardAngle(it);
+ if (st.sel.includes(it.k)) tray();
+ }
+
+ function dropCard(k) {
+ const el = grid.querySelector(`.card[data-k="${CSS.escape(k)}"]`);
+ const idx = st.list.findIndex(x => x.k === k);
+ if (idx >= 0) {
+ st.list.splice(idx, 1);
+ st.n = Math.max(0, st.n - 1);
+ }
+ const finalize = () => {
+ el?.remove();
+ if (!st.list.length) {
+ apply();
+ } else {
+ $('#count').innerHTML = countMarkup(st.list, base());
+ grid.querySelectorAll('.rgrp').forEach(heading => {
+ const next = heading.nextElementSibling;
+ if (!next || next.classList.contains('rgrp')) heading.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(finalize);
+ } else {
+ finalize();
+ }
+ }
+
+ function toggleFav(k, quiet) {
+ const on = !st.fav.has(k);
+ if (on) st.fav.add(k);
+ else 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 index = st.sel.indexOf(k);
+ const 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();
+ }
+
+ // ---------- Floating Workspace Dock ----------
+ 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;
+ const trayThumbnail = item =>
+ `<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>`
+ : '';
+ const removeLabel = esc(type ? `${TL(it)} · ${name}` : name);
+ return `<div title="${esc(name)}">${trayThumbnail(it)}<em>${TL(it)}</em>${pairButton}<button data-k="${esc(it.k)}" type="button" title="移除" aria-label="移除 ${removeLabel}">×</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();
+ const n = selected.length;
+ const fab = $('#trayFab');
+ const 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));
+
+ 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();
+ const rect = added.getBoundingClientRect();
+ const shift = rect.left < bounds.left ? rect.left - bounds.left : Math.max(0, rect.right - bounds.right);
+ if (shift) strip.scrollBy({ left: shift, behavior: motionPreference.matches ? 'instant' : 'smooth' });
+ if (!motionPreference.matches) {
+ added.animate([{ opacity: 0.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();
+ };
+ });
+
+ 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 prev = st.sel;
+ st.sel = [];
+ SV('sel', []);
+ prev.forEach(refreshCard);
+ tray();
+ $('#tgAddRow button').focus({ preventScroll: true });
+ toast('已清空组合');
+ };
+
+ // Floating dock quick generation
+ const trayDraft = LS('trayDraft');
+ let tgAutoPrompt = '';
+ let tgEdited = trayDraft?.prompt != null;
+ let tgBusy = false;
+ let tgRecs = [];
+ let tgUrls = [];
+ let 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');
+ const reset = $('#tgResetPrompt');
+ $('#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 = '';
+ if (reset) reset.hidden = true;
+ return;
+ }
+ if (!window.WB) return;
+ tgAutoPrompt = WB.selectionPrompt(traySelection(), st.tl);
+ if (!tgEdited) editor.value = tgAutoPrompt;
+ if (reset) reset.hidden = !tgEdited;
+ }
+
+ $('#tgResetPrompt').onclick = () => {
+ tgEdited = false;
+ $('#tgPrompt').value = tgAutoPrompt;
+ saveTrayDraft();
+ $('#tgResetPrompt').hidden = true;
+ toast('已按当前选择重新生成提示词');
+ };
+ $('#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;
+ if ($('#tgResetPrompt')) $('#tgResetPrompt').hidden = !tgEdited || !visibleSelection().length;
+ saveTrayDraft();
+ };
+ $('#tgN').onchange = $('#tgAR').onchange = saveTrayDraft;
+
+ function tgStat(text) {
+ const el = $('#tgStat');
+ if (!el) return;
+ el.hidden = !text;
+ if (text) el.textContent = text;
+ }
+
+ 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];
+ 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(); closeTray(false); navigate('history'); };
+ $('#tgCfg').onclick = () => window.WB?.cfgOpen();
+ $('#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();
+ const promptVal = $('#tgPrompt').value.trim();
+ const draft = items.length || promptVal
+ ? { prompt: tgEdited ? promptVal : '', 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?.stop();
+ $('#tgGo').onclick = async () => {
+ if (tgBusy || !window.WB) return;
+ if (!WB.configured()) return WB.cfgOpen();
+ 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();
+ const opts = {
+ selection: traySelection(),
+ lang: st.tl,
+ n: +$('#tgN').value || 1,
+ ar: $('#tgAR').value,
+ onTick: (d, t) => tgStat(`生成中… 已完成 ${d} / ${t}`),
+ };
+ if (pv) opts.prompt = pv;
+ try {
+ const r = await WB.quick(opts);
+ 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 (err) {
+ tgStat('生成失败:' + (err.message || err));
+ } finally {
+ tgBusy = false;
+ go.disabled = false;
+ go.textContent = '生成图片';
+ $('#tgStop').hidden = true;
+ }
+ };
+
+ // ---------- Grid Interactions & Navigation ----------
+ grid.onclick = e => {
+ if (e.target.closest('a.miss')) return;
+ const actEl = e.target.closest('[data-a]');
+ if (!actEl) return;
+ const cardEl = e.target.closest('.card');
+ const origin = ITEMS[cardEl.dataset.k];
+ const it = cardFace(origin);
+ e.stopPropagation();
+
+ const ph = cardEl.querySelector('.ph');
+ if (actEl.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;
+ }
+
+ const actions = {
+ open: () => lbOpen(st.list.indexOf(origin), cardEl),
+ flip: () => flipCard(cardEl, actEl, it),
+ fav: () => toggleFav(it.k),
+ unrec: () => unRec(origin.k),
+ sel: () => toggleSel(it.k),
+ copy: () => copyBrief(prompt(it, st.lang), [it], st.lang, '提示词'),
+ try: () => (trayOpen ? toggleSel(it.k) : useReference(it)),
+ ang: () => setAng(it, +actEl.dataset.i),
+ };
+ actions[actEl.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(open) {
+ $('#filters').classList.toggle('open', open);
+ $('#fBtn').classList.toggle('on', open);
+ $('#fBtn').setAttribute('aria-expanded', String(open));
+ }
+
+ function scrollHorizontal(event) {
+ const mode = event.deltaMode;
+ if (!event.cancelable || event.ctrlKey || event.shiftKey || event.deltaX || !event.deltaY) return;
+ const row = event.target.closest('.tabs, .frow');
+ if (!row || row.scrollWidth <= row.clientWidth) return;
+ const start = row.scrollLeft;
+ const unit = mode === WheelEvent.DOM_DELTA_LINE ? 16 : mode === WheelEvent.DOM_DELTA_PAGE ? row.clientWidth : 1;
+ row.scrollLeft += event.deltaY * unit;
+ if (row.scrollLeft !== start) event.preventDefault();
+ }
+
+ $('.tabs').addEventListener('wheel', scrollHorizontal, { passive: false });
+ $('#filters').addEventListener('wheel', scrollHorizontal, { passive: false });
+ $('#fBtn').onclick = () => drawer(!$('#filters').classList.contains('open'));
+ $('#drawerBg').onclick = () => drawer(false);
+ $('#filters').onclick = e => {
+ if (e.target.closest('[data-done]')) return drawer(false);
+ const chip = e.target.closest('.chip');
+ if (!chip) return;
+ st.f[chip.dataset.k] = chip.dataset.v;
+ viewT(() => { drawFilters(); apply(); });
+ };
+ $('#active').onclick = e => {
+ const btn = e.target.closest('button');
+ if (!btn) return;
+ st.f[btn.dataset.k] = '';
+ viewT(() => { drawFilters(); apply(); });
+ };
+
+ const 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) return;
+ 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 applySearch(query) {
+ $('#q').value = query;
+ st.q = query;
+ $('#qx').hidden = !query;
+ apply();
+ }
+
+ function randPick() {
+ if (!st.list.length) return toast('当前没有可选的内容');
+ lbOpen((Math.random() * st.list.length) | 0);
+ }
+ $('#rand').onclick = randPick;
+
+ // Description language toggle
+ function setLang(lang, quiet) {
+ st.lang = lang;
+ SV('lang', lang);
+ document.documentElement.dataset.lang = lang;
+ $$('button[data-lang]').forEach(b => b.classList.toggle('on', b.dataset.lang === lang));
+ 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(lang === 'zh' ? '描述语言:中文' : '描述语言:英文提示词');
+ }
+ $$('button[data-lang]').forEach(b => { b.onclick = () => setLang(b.dataset.lang); });
+
+ // Tabs & shell menus
+ function selectTab(tab) {
+ const active = $(`.tabs [data-tab="${tab}"]`);
+ const library = active.closest('#libraryMenu');
+ const 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;
+ if (event.key === 'ArrowDown') next = (index + 1) % items.length;
+ else if (event.key === 'ArrowUp') next = index <= 0 ? items.length - 1 : index - 1;
+ else if (event.key === 'Home') next = 0;
+ else if (event.key === 'End') next = items.length - 1;
+ else 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;
+ let 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;
+ const 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,
+ };
+ }
+ 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?.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?.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';
+ $('#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 {
+ if (request !== tabRequest) return;
+ grid.innerHTML = '';
+ $('#empty').hidden = false;
+ $('#emptyT').textContent = '数据加载失败';
+ $('#emptyP').textContent = '请检查网络后刷新页面重试';
+ $('#sugg').innerHTML = '';
+ $('#reset').hidden = true;
+ $('#empty .emo').innerHTML = EMPTY_ICONS.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) return;
+ 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 > 0) {
+ scrollTo({ top: 0, behavior: 'instant' });
+ }
+ }
+
+ $('.tabs').onclick = e => {
+ const button = e.target.closest('[data-tab]');
+ if (!button) return;
+ const tab = button.dataset.tab;
+ const 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);
+ };
+
+ // Dialog & scroll utilities
+ const hdr = () => document.documentElement.style.setProperty('--hdr', $('#top').offsetHeight + 'px');
+ addEventListener('resize', () => hdr());
+ new ResizeObserver(hdr).observe($('#top'));
+
+ let scrolled = false;
+ addEventListener('scroll', () => {
+ const s = scrollY > 24;
+ if (s !== scrolled) {
+ scrolled = s;
+ document.body.classList.toggle('scrolled', s);
+ setTimeout(hdr, 420);
+ }
+ $('#toTop').classList.toggle('on', scrollY > 900);
+ }, { passive: true });
+ $('#toTop').onclick = () => scrollTo({ top: 0, behavior: motionPreference.matches ? 'auto' : 'smooth' });
+
+ 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];
+ const last = focusable[focusable.length - 1];
+ const 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' });
+ };
+
+ // Favorites import/export & recent storage sync
+ $('#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 blob = new Blob(
+ [JSON.stringify({ app: '衣姿 PoseWear', 导出时间: new Date().toLocaleString('zh-CN'), 收藏: items }, null, 2)],
+ { type: 'application/json' }
+ );
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(blob);
+ 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 json = JSON.parse(await e.target.files[0].text());
+ const keys = (json.收藏 || []).map(x => x.key).filter(k => /^[pcradehysltf]:/.test(k));
+ await needKeys(keys);
+ let added = 0;
+ keys.forEach(k => {
+ if (ITEMS[k] && !st.fav.has(k)) {
+ st.fav.add(k);
+ added++;
+ }
+ });
+ SV('fav', [...st.fav]);
+ counts();
+ setTab('fav');
+ toast(`已导入 ${added} 条收藏`);
+ } catch {
+ 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) 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 nextTimes = {};
+ st.rec.forEach(x => { if (st.recT[x]) nextTimes[x] = st.recT[x]; });
+ st.recT = nextTimes;
+ SV('rec', st.rec);
+ SV('recT', nextTimes);
+ 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(() => {});
+ });
+
+ // ---------- Lightbox & Artist Inspection Studio ----------
+ let li = 0;
+ let srcCard = null;
+ const preCache = new Map();
+
+ function preload(src) {
+ if (preCache.has(src)) return preCache.get(src);
+ const promise = new Promise(resolve => {
+ const img = new Image();
+ if (/^https?:/i.test(src)) img.referrerPolicy = 'no-referrer';
+ img.onload = () => resolve(src);
+ img.onerror = () => resolve(null);
+ img.src = src;
+ });
+ preCache.set(src, promise);
+ if (preCache.size > 80) preCache.delete(preCache.keys().next().value);
+ return promise;
+ }
+
+ function rectAnim(el, from, reverse) {
+ const to = el.getBoundingClientRect();
+ if (!from || !to.width) {
+ return el.animate(
+ [{ opacity: 0, transform: 'scale(.94)' }, { opacity: 1, transform: 'none' }],
+ { duration: reverse ? 220 : 380, easing: 'cubic-bezier(.16,1,.3,1)', direction: reverse ? 'reverse' : 'normal', fill: 'both' }
+ );
+ }
+ const dx = from.left + from.width / 2 - (to.left + to.width / 2);
+ const dy = from.top + from.height / 2 - (to.top + to.height / 2);
+ const scale = Math.max(from.width / to.width, 0.08);
+ return el.animate(
+ [
+ { transform: `translate(${dx}px,${dy}px) scale(${scale})`, opacity: 0.2, borderRadius: '40px' },
+ { transform: 'none', opacity: 1, borderRadius: '20px' },
+ ],
+ {
+ duration: reverse ? 320 : 520,
+ easing: reverse ? 'cubic-bezier(.4,0,.2,1)' : 'cubic-bezier(.16,1,.3,1)',
+ direction: reverse ? 'reverse' : 'normal',
+ fill: 'both',
+ }
+ );
+ }
+
+ // li always indexes the gallery the user entered from, even while its paired image is on screen.
+ let lbVariant = null;
+ let lbVisitedPair = false;
+ const previewItem = () => lbVariant || st.list[li];
+ const lbV = { zoom: 1, x: 0, y: 0, flip: false, grid: 0, gray: false, cmp: false };
+
+ function lbApplyView() {
+ const stage = $('#lbStage');
+ const pImg = $('#lbPairImg');
+ const gridEl = $('#lbGrid');
+ const tools = $('#lbTools');
+ if (!stage) return;
+
+ const zoomed = lbV.zoom > 1;
+ stage.classList.toggle('zoomed', zoomed);
+ stage.classList.toggle('flipped', lbV.flip);
+ stage.classList.toggle('gray', lbV.gray);
+ stage.classList.toggle('comparing', lbV.cmp);
+ stage.style.setProperty('--lb-tx', zoomed ? lbV.x + 'px' : '0px');
+ stage.style.setProperty('--lb-ty', zoomed ? lbV.y + 'px' : '0px');
+ stage.style.setProperty('--lb-z', String(lbV.zoom));
+ if (gridEl) gridEl.dataset.mode = ['', 'thirds', 'cross'][lbV.grid] || '';
+
+ const cmpWrap = $('#lbPairCmp');
+ const hdl = $('#lbPairHdl');
+ const rng = $('#lbPairRange');
+ if (cmpWrap) cmpWrap.hidden = !lbV.cmp;
+ if (hdl) hdl.hidden = !lbV.cmp;
+ if (rng) rng.hidden = !lbV.cmp;
+ if (!lbV.cmp && pImg) pImg.removeAttribute('src');
+
+ if (tools) {
+ const setBtn = (k, on) => {
+ const b = tools.querySelector(`[data-lt="${k}"]`);
+ if (!b) return;
+ b.classList.toggle('on', !!on);
+ b.setAttribute('aria-pressed', String(!!on));
+ };
+ setBtn('zoom', zoomed);
+ setBtn('flip', lbV.flip);
+ setBtn('grid', lbV.grid > 0);
+ setBtn('gray', lbV.gray);
+ setBtn('cmp', lbV.cmp);
+ }
+ }
+
+ function lbResetView(hideTools = false) {
+ lbV.zoom = 1;
+ lbV.x = 0;
+ lbV.y = 0;
+ lbV.flip = false;
+ lbV.grid = 0;
+ lbV.gray = false;
+ lbV.cmp = false;
+ const stage = $('#lbStage');
+ const rng = $('#lbPairRange');
+ const tools = $('#lbTools');
+ const box = $('.lb-img');
+ if (stage) stage.style.setProperty('--x', '50%');
+ if (rng) rng.value = '50';
+ if (hideTools && tools) tools.hidden = true;
+ if (hideTools && box) box.removeAttribute('data-img-type');
+ lbApplyView();
+ }
+
+ function lbDrawPalette(it) {
+ window.PoseWearPalette?.render($('#lbPal'), $('#lbImg'), it, () => !$('#lb').hidden && previewItem() === it);
+ }
+
+ function lbSyncCompare(it) {
+ const cmpBtn = $('#lbTools [data-lt="cmp"]');
+ const grayBtn = $('#lbTools [data-lt="gray"]');
+ const mate = it && poseCounterpart(it);
+ const mono = it && (it.type === 'pose' || it.type === 'depth');
+ if (grayBtn) grayBtn.hidden = !!mono;
+ if (mono && lbV.gray) {
+ lbV.gray = false;
+ lbApplyView();
+ }
+ if (cmpBtn) cmpBtn.hidden = !mate;
+ if (!mate) {
+ if (lbV.cmp) {
+ lbV.cmp = false;
+ lbApplyView();
+ }
+ return;
+ }
+ if (lbV.cmp) {
+ const pImg = $('#lbPairImg');
+ const view = mate.item.angles[mate.angle];
+ pImg.referrerPolicy = mate.item.ref || '';
+ pImg.src = view.i || view.t;
+ $('#lbPairCmp').dataset.pairType = mate.item.type;
+ }
+ }
+
+ function lbToggleTool(action) {
+ if (st.tab === 'history' || $('#lb').hidden) return;
+ const it = previewItem();
+ if (!ok(it)) return;
+ if (action === 'zoom') {
+ if (lbV.cmp) lbV.cmp = false;
+ lbV.zoom = lbV.zoom > 1 ? 1 : 2;
+ lbV.x = 0;
+ lbV.y = 0;
+ } else if (action === 'flip') {
+ lbV.flip = !lbV.flip;
+ } else if (action === 'grid') {
+ lbV.grid = (lbV.grid + 1) % 3;
+ } else if (action === 'gray') {
+ if (it.type === 'pose' || it.type === 'depth') return;
+ lbV.gray = !lbV.gray;
+ } else if (action === 'cmp') {
+ const mate = poseCounterpart(it);
+ if (!mate) return;
+ lbV.cmp = !lbV.cmp;
+ if (lbV.cmp) {
+ lbV.zoom = 1;
+ lbV.x = 0;
+ lbV.y = 0;
+ $('#lbStage').style.setProperty('--x', '50%');
+ $('#lbPairRange').value = '50';
+ lbSyncCompare(it);
+ }
+ }
+ lbApplyView();
+ }
+
+ $('#lbTools')?.addEventListener('click', e => {
+ const b = e.target.closest('[data-lt]');
+ if (b) lbToggleTool(b.dataset.lt);
+ });
+ $('#lbPairRange')?.addEventListener('input', e => {
+ $('#lbStage').style.setProperty('--x', e.target.value + '%');
+ });
+
+ {
+ const stage = $('#lbStage');
+ let drag = null;
+ stage?.addEventListener('dblclick', e => {
+ if (st.tab === 'history' || lbV.cmp || e.target.closest('#lbPairRange')) return;
+ lbToggleTool('zoom');
+ });
+ stage?.addEventListener('pointerdown', e => {
+ if (lbV.zoom <= 1 || e.button !== 0 || e.target.closest('#lbPairRange')) return;
+ drag = { id: e.pointerId, sx: e.clientX, sy: e.clientY, ox: lbV.x, oy: lbV.y };
+ stage.setPointerCapture(e.pointerId);
+ stage.classList.add('panning');
+ });
+ stage?.addEventListener('pointermove', e => {
+ if (!drag || e.pointerId !== drag.id) return;
+ const r = stage.getBoundingClientRect();
+ const limX = r.width * 0.42;
+ const limY = r.height * 0.42;
+ lbV.x = Math.max(-limX, Math.min(limX, drag.ox + (e.clientX - drag.sx)));
+ lbV.y = Math.max(-limY, Math.min(limY, drag.oy + (e.clientY - drag.sy)));
+ stage.style.setProperty('--lb-tx', lbV.x + 'px');
+ stage.style.setProperty('--lb-ty', lbV.y + 'px');
+ });
+ const endDrag = e => {
+ if (drag && e.pointerId === drag.id) {
+ drag = null;
+ stage.classList.remove('panning');
+ }
+ };
+ stage?.addEventListener('pointerup', endDrag);
+ stage?.addEventListener('pointercancel', endDrag);
+ }
+
+ 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>';
+ lbSyncCompare(it);
+ };
+ if (DATA[type]) show();
+ else load(type).then(show, () => {});
+ }
+
+ let lbPushed = false;
+ const pend = new Set();
+
+ function lbOpen(i, cardEl) {
+ if (!ok(st.list[i])) return;
+ li = i;
+ lbVariant = cardEl?.dataset.show ? ITEMS[cardEl.dataset.show] : null;
+ lbVisitedPair = !!lbVariant;
+ const it = previewItem();
+ const 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;
+ lbResetView();
+ lb.hidden = false;
+ document.body.style.overflow = 'hidden';
+ lbDraw();
+ if (!motionPreference.matches) {
+ $('.lb-bg').animate([{ opacity: 0 }, { opacity: 1 }], { duration: 300 });
+ rectAnim($('.lb-box'), cardEl && cardEl.querySelector('.ph').getBoundingClientRect());
+ }
+ $('.lb-x').focus({ preventScroll: true });
+ }
+
+ let closing = false;
+ function lbClose(navigateOut = false, immediate = false) {
+ if ($('#lb').hidden || closing) return;
+ const leaving = navigateOut === true;
+ const fromHistory = st.tab === 'history';
+ if (lbPushed) {
+ lbPushed = false;
+ if (!leaving) history.back();
+ }
+ const it = st.list[li];
+ const cardEl = it && grid.querySelector(`.card[data-k="${CSS.escape(it.k)}"]`);
+ const rect = cardEl && cardEl.querySelector('.ph').getBoundingClientRect();
+ const visible = rect && rect.bottom > 0 && rect.top < innerHeight;
+
+ const done = () => {
+ closing = false;
+ lbVariant = null;
+ lbResetView(true);
+ $('#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'), visible ? rect : null, true).finished.then(done);
+ }
+
+ function lbDraw() {
+ const it = previewItem();
+ if (!ok(it) || st.tab === 'history') return;
+ const img = $('#lbImg');
+ const box = $('.lb-img');
+ const src = big(it);
+ const isDepth = it.type === 'depth';
+ addRec(it.k);
+ history.replaceState(history.state, '', `#${it.type}/${it.id}`);
+
+ box.dataset.imgType = it.type;
+ box.classList.toggle('ext', !!it.ext);
+ box.classList.remove('fail');
+ if (it.site) $('#lbMiss').href = it.site;
+ if ($('#lbTools')) $('#lbTools').hidden = false;
+ lbSyncCompare(it);
+ lbApplyView();
+
+ img.referrerPolicy = it.ref || '';
+ img.onerror = () => {
+ if (isDepth && 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(loaded => {
+ if (img.dataset.src !== src) return;
+ if (loaded) {
+ img.src = loaded;
+ 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', 'fail');
+ lbDrawPalette(it);
+ } else {
+ box.classList.toggle('fail', isDepth);
+ box.classList.remove('loading');
+ img.classList.remove('lo');
+ }
+ });
+ }
+
+ [1, -1, 2].forEach(d => {
+ const next = st.list[(li + d + st.list.length) % st.list.length];
+ if (ok(next)) preload(big(next));
+ });
+ if (it.angles) it.angles.forEach(a => preload(a.i));
+
+ const isPose = it.type === 'pose';
+ const isFav = st.fav.has(it.k);
+ const isSel = st.sel.includes(it.k);
+ img.alt = title(it);
+
+ const cpSvg = '<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>';
+ const zhBox = `<div class="pbox"><div class="pbox-h"><small>中文描述</small><button class="sm pbox-cp pri" data-c="zh">${cpSvg}<span>复制中文</span></button></div><p>${esc(prompt(it, 'zh'))}</p></div>`;
+ const enBox = `<div class="pbox en"><div class="pbox-h"><small>英文提示词 · PROMPT</small><button class="sm pbox-cp" data-c="en">${cpSvg}<span>复制英文</span></button></div><p>${esc(prompt(it, 'en'))}</p></div>`;
+
+ const hasAng = !!it.angles;
+ const meta = hasAng
+ ? `${it.line} · ${it.cat}${isDepth ? ' · ' + 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 = isDepth
+ ? `<div class="jp">日文原名:${esc(it.ja)}</div><div class="jp">${esc(it.lineJa)} · ${esc(it.catJa)} · ${esc(it.angles[it.ai].ja)}</div>`
+ : (isPose ? `<div class="jp">日文原名:${esc(it.ja)}</div>` : '');
+
+ const sourceCredit = isDepth
+ ? `<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>'
+ : '';
+
+ const angHtml = hasAng
+ ? `<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>`
+ : '';
+
+ const taobaoQuery = encodeURIComponent([...val(it, 'col').slice(0, 1), ...val(it, 'item').slice(0, 2)].join(' ') || `女装 ${it.cat}`);
+ const downloadActs = isDepth
+ ? ''
+ : (it.ext
+ ? ''
+ : `<button data-x="dlx">下载图片</button><button data-x="cpimg">复制图片</button>` +
+ `<a href="${orig(it)}" download="posewear-${it.type}-${it.id}${isPose ? '-' + it.ai : ''}.png" class="dl"><button tabindex="-1">下载原图 PNG</button></a>`) +
+ (isPose || it.type === 'portrait'
+ ? ''
+ : `<a href="https://s.taobao.com/search?q=${taobaoQuery}" target="_blank" rel="noopener" class="dl"><button tabindex="-1">淘宝搜同款 ↗</button></a>`);
+
+ $('#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}` +
+ `<div id="lbPal" class="lb-pal" hidden></div>` +
+ `${isPose || isDepth ? '<div id="lbPair"></div>' : ''}${angHtml}` +
+ `${st.lang === 'en' ? enBox + zhBox : zhBox + enBox}` +
+ `${hasAng ? '' : 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="${isFav ? 'on' : ''}" aria-label="${isFav ? '取消收藏' : '收藏'}">${isFav ? '♥' : '♡'}</button><button data-x="share">分享</button>${isDepth ? '' : `<button data-x="try" class="pri">${tryLabel(it)}</button>`}</div>` +
+ `<div class="acts"><button data-x="fav">${isFav ? '♥ 已收藏' : '♡ 收藏'}</button><button data-x="sel" class="${isSel ? '' : 'pri'}">${isSel ? '✓ 已在组合中' : '+ 加入组合'}</button>${isDepth ? '' : `<button data-x="try">${tryLabel(it)}</button>`}<button data-x="share">分享链接</button>${downloadActs}</div>` +
+ `<div id="lbSim"></div>` +
+ `<p class="mu lb-keys"><kbd>←</kbd><kbd>→</kbd>切换 ${hasAng ? '<kbd>↑</kbd><kbd>↓</kbd>角度 ' : ''}<kbd>Z</kbd>缩放 <kbd>H</kbd>镜像 <kbd>G</kbd>参考线 ${isPose || isDepth ? '<kbd>V</kbd>对比 ' : '<kbd>B</kbd>灰度 '}<kbd>F</kbd>收藏 <kbd>A</kbd>组合 <kbd>C</kbd>复制 <kbd>S</kbd>分享</p>` +
+ sourceCredit;
+
+ if (isPose || isDepth) drawPosePair(it, $('#lbPair'));
+ else lbDrawPalette(it);
+ window.X?.lb?.(it);
+ }
+
+ function share() {
+ const it = previewItem();
+ const 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();
+ const btn = e.target.closest('button');
+ if (!btn || !ok(it) || st.tab === 'history') return;
+ if (btn.dataset.hex) {
+ copy(btn.dataset.hex, btn.dataset.hex);
+ btn.classList.add('copied');
+ clearTimeout(btn._ct);
+ btn._ct = setTimeout(() => btn.classList.remove('copied'), 1000);
+ return;
+ }
+ if (btn.dataset.variant) {
+ const pair = poseCounterpart(it);
+ if (!pair || pair.item.type !== btn.dataset.variant) return;
+ lbVisitedPair = true;
+ lbVariant = pair.item;
+ setAng(pair.item, pair.angle);
+ lbDraw();
+ $('#lbPair [aria-pressed="true"]')?.focus({ preventScroll: true });
+ return;
+ }
+ if (btn.dataset.ai) {
+ setAng(it, +btn.dataset.ai);
+ lbDraw();
+ $(`#lbSide [data-ai="${it.ai}"]`).focus({ preventScroll: true });
+ }
+ if (btn.dataset.c) {
+ copyBrief(prompt(it, btn.dataset.c), [it], btn.dataset.c, btn.dataset.c === 'en' ? '英文提示词' : '中文描述');
+ btn.classList.add('copied');
+ clearTimeout(btn._ct);
+ btn._ct = setTimeout(() => btn.classList.remove('copied'), 1200);
+ }
+ if (btn.dataset.x === 'fav') toggleFav(it.k);
+ if (btn.dataset.x === 'sel') toggleSel(it.k);
+ if (btn.dataset.x === 'share') share();
+ if (btn.dataset.x === 'try') {
+ lbClose(!!STUDIO_SLOT[it.type]);
+ useReference(it);
+ }
+ };
+
+ const step = delta => {
+ li = (li + delta + st.list.length) % st.list.length;
+ lbVariant = null;
+ lbResetView();
+ lbDraw();
+ if (!motionPreference.matches) {
+ $('#lbImg').animate(
+ [{ opacity: 0.3, transform: `translateX(${delta * 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);
+
+ // ---------- Global Keyboard Shortcuts ----------
+ addEventListener('keydown', e => {
+ const k = (e.key || '').toLowerCase();
+ if ((e.ctrlKey || e.metaKey) && !e.altKey && k === 'k') {
+ e.preventDefault();
+ window.PoseWearCommandPalette?.isOpen()
+ ? window.PoseWearCommandPalette.close()
+ : window.PoseWearCommandPalette?.open();
+ return;
+ }
+ if (window.PoseWearCommandPalette?.handleKey(e)) return;
+ if (window.PoseWearSketch?.handleKey(e)) return;
+
+ if (e.ctrlKey || e.metaKey || e.altKey || e.target.closest?.('.shell-menu[open]')) return;
+ const ae = document.activeElement;
+ const inInput = 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 (inInput) ae.blur();
+ return;
+ }
+ if (inInput) return;
+ if (e.key === '?') {
+ openDialog($('#helpBox'));
+ return;
+ }
+
+ 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 === 'z') lbToggleTool('zoom');
+ else if (k === 'h') lbToggleTool('flip');
+ else if (k === 'g') lbToggleTool('grid');
+ else if (k === 'b') lbToggleTool('gray');
+ else if (k === 'v') lbToggleTool('cmp');
+ else if (k === 't') window.PoseWearTheme.toggle();
+ 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();
+ });
+
+ // Touch swipe inside lightbox
+ let tx = 0;
+ let ty = 0;
+ let tSkip = false;
+ $('.lb-img').addEventListener('touchstart', e => {
+ tSkip = lbV.zoom > 1 || !!e.target.closest('#lbPairRange,#lbTools');
+ tx = e.touches[0].clientX;
+ ty = e.touches[0].clientY;
+ }, { passive: true });
+ $('.lb-img').addEventListener('touchend', e => {
+ if (tSkip) return;
+ const dx = e.changedTouches[0].clientX - tx;
+ const dy = e.changedTouches[0].clientY - ty;
+ if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(dy)) (dx < 0 ? $('.next') : $('.prev')).click();
+ else if (dy > 90) lbClose();
});
- const badges=el.querySelector('.card-badges');
- if(badges&&(it.type==='pose'||it.type==='depth'))badges.outerHTML=cardBadges(it);
- const sub=el.querySelector('.info .sub');
- if(sub&&origin)sub.textContent=subtitle(it,origin.type);
- });
-}
-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);updateCardAngle(it);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{$('#count').innerHTML=countMarkup(st.list,base());grid.querySelectorAll('.rgrp').forEach(g=>{const n=g.nextElementSibling;if(!n||n.classList.contains('rgrp'))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 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 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));
- 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()});
-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 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'),reset=$('#tgResetPrompt');
- $('#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='';if(reset)reset.hidden=true;return}
- if(!window.WB)return;
- tgAutoPrompt=WB.selectionPrompt(traySelection(),st.tl);
- if(!tgEdited)editor.value=tgAutoPrompt;
- if(reset)reset.hidden=!tgEdited;
-}
-$('#tgResetPrompt').onclick=()=>{
- tgEdited=false;$('#tgPrompt').value=tgAutoPrompt;saveTrayDraft();
- $('#tgResetPrompt').hidden=true;toast('已按当前选择重新生成提示词');
-};
-$('#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;if($('#tgResetPrompt'))$('#tgResetPrompt').hidden=!tgEdited||!visibleSelection().length;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];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();closeTray(false);navigate('history')};
-$('#tgCfg').onclick=()=>window.WB&&WB.cfgOpen();
-$('#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.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(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;
-
- const row = event.target.closest('.tabs, .frow');
- if (!row || row.scrollWidth <= row.clientWidth) return;
-
- const start = row.scrollLeft;
- const unit = mode === WheelEvent.DOM_DELTA_LINE ? 16
- : mode === WheelEvent.DOM_DELTA_PAGE ? row.clientWidth : 1;
- row.scrollLeft += event.deltaY * unit;
- if (row.scrollLeft !== start) event.preventDefault();
-}
-$('.tabs').addEventListener('wheel', scrollHorizontal, {passive:false});
-$('#filters').addEventListener('wheel', scrollHorizontal, {passive:false});
-$('#fBtn').onclick=()=>drawer(!$('#filters').classList.contains('open'));$('#drawerBg').onclick=()=>drawer(false);
-$('#filters').onclick=e=>{if(e.target.closest('[data-done]'))return drawer(false);const b=e.target.closest('.chip');if(!b)return;st.f[b.dataset.k]=b.dataset.v;viewT(()=>{drawFilters();apply()})};
-$('#active').onclick=e=>{const b=e.target.closest('button');if(b){st.f[b.dataset.k]='';viewT(()=>{drawFilters();apply()})}};
-const 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)}
-$('#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 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 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};
- }
- 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';$('#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){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>0)scrollTo({top:0,behavior:'instant'})}
-$('.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: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)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(()=>{})});
-// 大图
-let li=0,srcCard=null;const pre=new Map();function preload(src){if(pre.has(src))return pre.get(src);const p=new Promise(r=>{const i=new Image();if(/^https?:/i.test(src))i.referrerPolicy='no-referrer';i.onload=()=>r(src);i.onerror=()=>r(null);i.src=src});pre.set(src,p);if(pre.size>80)pre.delete(pre.keys().next().value);return p}
-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'})}
-// 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];
-const lbV={zoom:1,x:0,y:0,flip:false,grid:0,gray:false,cmp:false};
-function lbApplyView(){
- const stage=$('#lbStage'),img=$('#lbImg'),pImg=$('#lbPairImg'),gridEl=$('#lbGrid'),tools=$('#lbTools');
- if(!stage)return;
- const z=lbV.zoom>1;
- stage.classList.toggle('zoomed',z);
- stage.classList.toggle('flipped',lbV.flip);
- stage.classList.toggle('gray',lbV.gray);
- stage.classList.toggle('comparing',lbV.cmp);
- stage.style.setProperty('--lb-tx',z?lbV.x+'px':'0px');
- stage.style.setProperty('--lb-ty',z?lbV.y+'px':'0px');
- stage.style.setProperty('--lb-z',String(lbV.zoom));
- if(gridEl)gridEl.dataset.mode=['','thirds','cross'][lbV.grid]||'';
- const cmpWrap=$('#lbPairCmp'),hdl=$('#lbPairHdl'),rng=$('#lbPairRange');
- if(cmpWrap)cmpWrap.hidden=!lbV.cmp;
- if(hdl)hdl.hidden=!lbV.cmp;
- if(rng)rng.hidden=!lbV.cmp;
- if(!lbV.cmp&&pImg)pImg.removeAttribute('src');
- if(tools){
- const setBtn=(k,on)=>{const b=tools.querySelector(`[data-lt="${k}"]`);if(b){b.classList.toggle('on',!!on);b.setAttribute('aria-pressed',String(!!on))}};
- setBtn('zoom',z);setBtn('flip',lbV.flip);setBtn('grid',lbV.grid>0);setBtn('gray',lbV.gray);setBtn('cmp',lbV.cmp);
- }
-}
-function lbResetView(hideTools=false){
- lbV.zoom=1;lbV.x=0;lbV.y=0;lbV.flip=false;lbV.grid=0;lbV.gray=false;lbV.cmp=false;
- const stage=$('#lbStage'),rng=$('#lbPairRange'),tools=$('#lbTools'),box=$('.lb-img');
- if(stage)stage.style.setProperty('--x','50%');
- if(rng)rng.value='50';
- if(hideTools&&tools)tools.hidden=true;
- if(hideTools&&box)box.removeAttribute('data-img-type');
- lbApplyView();
-}
-function extractPalette(img){
- if(!img||!img.complete||!img.naturalWidth)return[];
- try{
- const S=48,cv=document.createElement('canvas');cv.width=S;cv.height=S;
- const ctx=cv.getContext('2d',{willReadFrequently:true});
- ctx.drawImage(img,0,0,S,S);
- const d=ctx.getImageData(0,0,S,S).data;
- const map=new Map();
- for(let p=0;p<S*S;p++){
- const i=p*4,r=d[i],g=d[i+1],b=d[i+2],a=d[i+3];
- if(a<200)continue;
- if(r>242&&g>242&&b>242)continue;
- const x=p%S,y=(p/S)|0;
- const center=(x>=7&&x<=40&&y>=4&&y<=44)?1.8:0.25;
- const qr=Math.min(240,Math.round(r/16)*16),qg=Math.min(240,Math.round(g/16)*16),qb=Math.min(240,Math.round(b/16)*16);
- const max=Math.max(r,g,b),min=Math.min(r,g,b),sat=max?(max-min)/max:0;
- const w=(0.35+sat*4.5)*center;
- const key=(qr<<16)|(qg<<8)|qb;
- const cur=map.get(key);
- if(cur){cur.w+=w;cur.r+=r*w;cur.g+=g*w;cur.b+=b*w}
- else map.set(key,{w,r:r*w,g:g*w,b:b*w});
- }
- const buckets=[...map.values()].sort((a,b)=>b.w-a.w).map(x=>[Math.round(x.r/x.w),Math.round(x.g/x.w),Math.round(x.b/x.w)]);
- const out=[];
- for(const c of buckets){
- if(out.every(o=>Math.hypot(o[0]-c[0],o[1]-c[1],o[2]-c[2])>=44)){
- out.push(c);if(out.length>=5)break;
- }
- }
- return out.map(([r,g,b])=>'#'+[r,g,b].map(v=>v.toString(16).padStart(2,'0')).join('').toUpperCase());
- }catch{return[]}
-}
-function lbDrawPalette(it){
- const box=$('#lbPal'),img=$('#lbImg');
- if(!box||!it||it.type==='pose'||it.type==='depth'||it.ext){if(box)box.hidden=true;return}
- const paint=()=>{
- if(!box.isConnected||$('#lb').hidden||previewItem()!==it||img.classList.contains('lo'))return;
- const cols=extractPalette(img);
- if(cols.length<2){box.hidden=true;return}
- box.innerHTML=`<div class="lb-pal-h"><small>提取配色</small><small class="mu">点击复制</small></div><div class="lb-pal-sw">${cols.map(h=>`<button type="button" class="pal-sw" data-hex="${h}" style="--sw:${h}" title="复制 ${h}"><i></i><span>${h}</span></button>`).join('')}</div>`;
- box.hidden=false;
- };
- if(img.complete&&img.naturalWidth&&!img.classList.contains('lo'))paint();
- else img.addEventListener('load',paint,{once:true});
-}
-function lbSyncCompare(it){
- const btn=$('#lbTools [data-lt="cmp"]'),grayBtn=$('#lbTools [data-lt="gray"]'),mate=it&&poseCounterpart(it);
- const mono=it&&(it.type==='pose'||it.type==='depth');
- if(grayBtn)grayBtn.hidden=!!mono;
- if(mono&&lbV.gray){lbV.gray=false;lbApplyView()}
- if(btn)btn.hidden=!mate;
- if(!mate){if(lbV.cmp){lbV.cmp=false;lbApplyView()}return}
- if(lbV.cmp){
- const pImg=$('#lbPairImg'),view=mate.item.angles[mate.angle];
- pImg.referrerPolicy=mate.item.ref||'';
- pImg.src=view.i||view.t;
- $('#lbPairCmp').dataset.pairType=mate.item.type;
- }
-}
-function lbToggleTool(action){
- if(st.tab==='history'||$('#lb').hidden)return;
- const it=previewItem();if(!ok(it))return;
- if(action==='zoom'){
- if(lbV.cmp)lbV.cmp=false;
- lbV.zoom=lbV.zoom>1?1:2;lbV.x=0;lbV.y=0;
- }else if(action==='flip'){
- lbV.flip=!lbV.flip;
- }else if(action==='grid'){
- lbV.grid=(lbV.grid+1)%3;
- }else if(action==='gray'){
- if(it.type==='pose'||it.type==='depth')return;
- lbV.gray=!lbV.gray;
- }else if(action==='cmp'){
- const mate=poseCounterpart(it);
- if(!mate)return;
- lbV.cmp=!lbV.cmp;
- if(lbV.cmp){
- lbV.zoom=1;lbV.x=0;lbV.y=0;
- $('#lbStage').style.setProperty('--x','50%');$('#lbPairRange').value='50';
- lbSyncCompare(it);
- }
- }
- lbApplyView();
-}
-$('#lbTools')?.addEventListener('click',e=>{
- const b=e.target.closest('[data-lt]');if(b)lbToggleTool(b.dataset.lt);
-});
-$('#lbPairRange')?.addEventListener('input',e=>{
- $('#lbStage').style.setProperty('--x',e.target.value+'%');
-});
-{
- const stage=$('#lbStage');
- let drag=null;
- stage?.addEventListener('dblclick',e=>{
- if(st.tab==='history'||lbV.cmp||e.target.closest('#lbPairRange'))return;
- lbToggleTool('zoom');
- });
- stage?.addEventListener('pointerdown',e=>{
- if(lbV.zoom<=1||e.button!==0||e.target.closest('#lbPairRange'))return;
- drag={id:e.pointerId,sx:e.clientX,sy:e.clientY,ox:lbV.x,oy:lbV.y};
- stage.setPointerCapture(e.pointerId);stage.classList.add('panning');
- });
- stage?.addEventListener('pointermove',e=>{
- if(!drag||e.pointerId!==drag.id)return;
- const r=stage.getBoundingClientRect(),limX=r.width*0.42,limY=r.height*0.42;
- lbV.x=Math.max(-limX,Math.min(limX,drag.ox+(e.clientX-drag.sx)));
- lbV.y=Math.max(-limY,Math.min(limY,drag.oy+(e.clientY-drag.sy)));
- stage.style.setProperty('--lb-tx',lbV.x+'px');
- stage.style.setProperty('--lb-ty',lbV.y+'px');
- });
- const endDrag=e=>{if(drag&&e.pointerId===drag.id){drag=null;stage.classList.remove('panning')}};
- stage?.addEventListener('pointerup',endDrag);
- stage?.addEventListener('pointercancel',endDrag);
-}
-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>';
- lbSyncCompare(it);
- };
- 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;lbResetView();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;lbResetView(true);$('#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.dataset.imgType=it.type;
- box.classList.toggle('ext',!!it.ext);box.classList.remove('fail');const miss=$('#lbMiss');if(it.site)miss.href=it.site;
- if($('#lbTools'))$('#lbTools').hidden=false;
- lbSyncCompare(it);lbApplyView();
- 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');lbDrawPalette(it)}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 cpSvg='<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>';
- const zh=`<div class="pbox"><div class="pbox-h"><small>中文描述</small><button class="sm pbox-cp pri" data-c="zh">${cpSvg}<span>复制中文</span></button></div><p>${esc(prompt(it,'zh'))}</p></div>`,en=`<div class="pbox en"><div class="pbox-h"><small>英文提示词 · PROMPT</small><button class="sm pbox-cp" data-c="en">${cpSvg}<span>复制英文</span></button></div><p>${esc(prompt(it,'en'))}</p></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 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}<div id="lbPal" class="lb-pal" hidden></div>${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 lb-keys"><kbd>←</kbd><kbd>→</kbd>切换 ${ang?'<kbd>↑</kbd><kbd>↓</kbd>角度 ':''}<kbd>Z</kbd>缩放 <kbd>H</kbd>镜像 <kbd>G</kbd>参考线 ${P||D?'<kbd>V</kbd>对比 ':'<kbd>B</kbd>灰度 '}<kbd>F</kbd>收藏 <kbd>A</kbd>组合 <kbd>C</kbd>复制 <kbd>S</kbd>分享</p>${sourceCredit}`;if(P||D)drawPosePair(it,$('#lbPair'));else lbDrawPalette(it);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.hex){copy(t.dataset.hex,t.dataset.hex);t.classList.add('copied');clearTimeout(t._ct);t._ct=setTimeout(()=>t.classList.remove('copied'),1000);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'?'英文提示词':'中文描述');t.classList.add('copied');clearTimeout(t._ct);t._ct=setTimeout(()=>t.classList.remove('copied'),1200)}
- 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;lbResetView();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);
-
-// ---------- 速写定时练习(Gesture Drawing Studio) ----------
-const SK={open:false,dur:60,total:10,pool:[],deck:[],i:0,seen:[],rem:60,last:0,paused:false,sound:false,flip:false,grid:0,gray:false,pair:false,timer:null,actx:null,beeped:0,prevFocus:null};
-function skChime(freq=660,dur=.12){
- if(!SK.sound)return;
- try{
- const C=window.AudioContext||window.webkitAudioContext;if(!C)return;
- SK.actx||=new C();if(SK.actx.state==='suspended')SK.actx.resume();
- const o=SK.actx.createOscillator(),g=SK.actx.createGain();
- o.type='sine';o.frequency.value=freq;
- g.gain.setValueAtTime(.0001,SK.actx.currentTime);
- g.gain.exponentialRampToValueAtTime(.08,SK.actx.currentTime+.015);
- g.gain.exponentialRampToValueAtTime(.0001,SK.actx.currentTime+dur);
- o.connect(g);g.connect(SK.actx.destination);o.start();o.stop(SK.actx.currentTime+dur+.02);
- }catch{}
-}
-function skFmt(sec){const s=Math.max(0,Math.ceil(sec));return `${String(Math.floor(s/60)).padStart(2,'0')}:${String(s%60).padStart(2,'0')}`}
-function skCap(){return SK.total?Math.min(SK.total,SK.deck.length):0}
-function skRenderTools(){
- const it=SK.deck[SK.i],frame=$('#skFrame'),gridEl=$('#skGrid');
- if(frame){
- frame.classList.toggle('flipped',SK.flip);
- frame.classList.toggle('gray',SK.gray);
- }
- if(gridEl)gridEl.dataset.mode=['','thirds','cross'][SK.grid]||'';
- const set=(k,on)=>{const b=$(`#sketch [data-skt="${k}"]`);if(b){b.classList.toggle('on',!!on);b.setAttribute('aria-pressed',String(!!on))}};
- set('flip',SK.flip);set('grid',SK.grid>0);set('gray',SK.gray);set('pair',SK.pair);
- const favBtn=$('#sketch [data-skt="fav"]'),isF=it&&st.fav.has(it.k);
- if(favBtn){favBtn.classList.toggle('on',!!isF);favBtn.setAttribute('aria-pressed',String(!!isF));favBtn.textContent=isF?'♥ 已收藏':'♡ 收藏'}
- const pairBtn=$('#sketch [data-skt="pair"]'),mate=it&&poseCounterpart(it);
- if(pairBtn){pairBtn.hidden=!mate;if(mate)pairBtn.textContent=(SK.pair?mate.item.type:it.type)==='pose'?'深度图':'线稿'}
- const grayBtn=$('#sketch [data-skt="gray"]'),shown=SK.pair&&mate?mate.item:it;
- if(grayBtn)grayBtn.hidden=!shown||shown.type==='pose'||shown.type==='depth';
- const soundBtn=$('#skSound');
- if(soundBtn){soundBtn.classList.toggle('on',SK.sound);soundBtn.setAttribute('aria-pressed',String(SK.sound))}
-}
-function skShowCard(){
- const it=SK.deck[SK.i];if(!it)return;
- if(!SK.seen.includes(it))SK.seen.push(it);
- const mate=poseCounterpart(it),shown=SK.pair&&mate?mate.item:it;
- const src=SK.pair&&mate?(mate.item.angles[mate.angle].i||mate.item.angles[mate.angle].t):big(it);
- const img=$('#skImg'),stage=$('#skStage'),frame=$('#skFrame');
- $('#skDone').hidden=true;frame.hidden=false;
- stage.dataset.imgType=shown.type;
- img.referrerPolicy=shown.ref||'';img.src=src;img.alt=title(shown);
- const cap=skCap();
- $('#skStep').textContent=`${SK.i+1} / ${cap||'∞'}`;
- const ang=it.angles?.[it.ai]?.zh,angLoc=ang?(window.PWLocale?window.PWLocale.t(ang):ang):'';
- $('#skName').textContent=title(it)+(angLoc?' · '+angLoc:'');
- SK.rem=SK.dur;SK.beeped=0;SK.last=performance.now();
- $('#skTime').textContent=skFmt(SK.rem);
- $('#skProg').style.transform='scaleX(1)';
- const nextIt=SK.deck[SK.i+1];if(nextIt)preload(big(nextIt));
- if(counterpartType(it)&&!DATA[counterpartType(it)])load(counterpartType(it)).then(()=>SK.open&&skRenderTools(),()=>{});
- skRenderTools();
-}
-function skFinish(){
- clearInterval(SK.timer);SK.timer=null;SK.paused=true;
- $('#skFrame').hidden=true;$('#skDone').hidden=false;
- $('#skProg').style.transform='scaleX(0)';
- $('#skSummary').textContent=`已完成 ${SK.seen.length} 张参考练习(每张 ${SK.dur>=60?Math.round(SK.dur/60)+' 分钟':SK.dur+' 秒'})`;
- $('#skRecap').innerHTML=SK.seen.map(it=>`<button type="button" data-sk-open="${esc(it.k)}" title="${esc(title(it))}"><img src="${esc(thumb(it))}" alt="${esc(title(it))}"${it.ref?` referrerpolicy="${esc(it.ref)}"`:''}></button>`).join('');
- skChime(784,.25);
-}
-function skStep(d){
- const next=SK.i+d;
- if(next<0)return;
- if(SK.total&&next>=Math.min(SK.total,SK.deck.length))return skFinish();
- if(next>=SK.deck.length){const base=SK.pool.length?SK.pool:st.list.filter(ok);if(!base.length)return skFinish();SK.deck=SK.deck.concat(shuffle(base.slice()))}
- SK.i=next;SK.pair=false;skShowCard();
- if(d>0)skChime(659,.14);
-}
-function skTick(){
- if(!SK.open||SK.paused||document.hidden)return;
- const now=performance.now(),dt=Math.min(.5,(now-SK.last)/1000);SK.last=now;
- SK.rem=Math.max(0,SK.rem-dt);
- $('#skTime').textContent=skFmt(SK.rem);
- $('#skProg').style.transform=`scaleX(${Math.max(0,SK.rem/SK.dur)})`;
- const ceil=Math.ceil(SK.rem);
- if(ceil<=3&&ceil>=1&&SK.beeped!==ceil){SK.beeped=ceil;skChime(523,.07)}
- if(SK.rem<=0)skStep(1);
-}
-document.addEventListener('visibilitychange',()=>{if(SK.open&&!document.hidden)SK.last=performance.now()});
-function skTogglePause(force){
- SK.paused=force===undefined?!SK.paused:!!force;
- SK.last=performance.now();
- $('#skPause').textContent=SK.paused?'继续':'暂停';
-}
-async function sketchOpen(opts={}){
- if(opts.dur)SK.dur=opts.dur;
- if(opts.total!==undefined)SK.total=opts.total;
- let pool=st.list.filter(ok);
- if(pool.length<2){
- if(!DATA.pose)await load('pose');
- pool=(DATA.pose||[]).filter(ok);
- }
- if(!pool.length)return toast('当前没有可用于速写的素材');
- SK.prevFocus=document.activeElement;
- SK.pool=pool.slice();SK.deck=shuffle(pool.slice());SK.i=0;SK.seen=[];SK.flip=false;SK.grid=0;SK.gray=false;SK.pair=false;
- SK.open=true;SK.paused=false;
- $('#sketch').hidden=false;document.body.style.overflow='hidden';
- $$('#skDur button').forEach(b=>{const on=+b.dataset.sd===SK.dur;b.classList.toggle('on',on);b.setAttribute('aria-pressed',String(on))});
- $$('#skTotal button').forEach(b=>{const on=+b.dataset.sc===SK.total;b.classList.toggle('on',on);b.setAttribute('aria-pressed',String(on))});
- $('#skPause').textContent='暂停';
- skShowCard();
- clearInterval(SK.timer);SK.timer=setInterval(skTick,200);
- $('#skPause').focus({preventScroll:true});
-}
-function sketchClose(){
- if(!SK.open)return;
- SK.open=false;clearInterval(SK.timer);SK.timer=null;
- $('#sketch').hidden=true;$('#skImg').removeAttribute('src');
- document.body.style.overflow='';
- SK.prevFocus?.isConnected&&SK.prevFocus.focus({preventScroll:true});SK.prevFocus=null;
-}
-$('#sketchBtn')?.addEventListener('click',()=>sketchOpen());
-$('#skClose')?.addEventListener('click',sketchClose);
-$('#skExit')?.addEventListener('click',sketchClose);
-$('#skAgain')?.addEventListener('click',()=>sketchOpen());
-$('#skPause')?.addEventListener('click',()=>skTogglePause());
-$('#skPrev')?.addEventListener('click',()=>skStep(-1));
-$('#skNext')?.addEventListener('click',()=>skStep(1));
-$('#skSound')?.addEventListener('click',()=>{SK.sound=!SK.sound;skRenderTools();if(SK.sound)skChime(659,.1)});
-$('#skDur')?.addEventListener('click',e=>{
- const b=e.target.closest('[data-sd]');if(!b)return;
- SK.dur=+b.dataset.sd;SK.rem=SK.dur;SK.last=performance.now();SK.beeped=0;
- $$('#skDur button').forEach(x=>{const on=x===b;x.classList.toggle('on',on);x.setAttribute('aria-pressed',String(on))});
- if($('#skDone').hidden){$('#skTime').textContent=skFmt(SK.rem);$('#skProg').style.transform='scaleX(1)'}
-});
-$('#skTotal')?.addEventListener('click',e=>{
- const b=e.target.closest('[data-sc]');if(!b)return;
- SK.total=+b.dataset.sc;
- $$('#skTotal button').forEach(x=>{const on=x===b;x.classList.toggle('on',on);x.setAttribute('aria-pressed',String(on))});
- if($('#skDone').hidden)$('#skStep').textContent=`${SK.i+1} / ${skCap()||'∞'}`;
-});
-$('#sketch')?.addEventListener('click',e=>{
- const t=e.target.closest('[data-skt]');
- if(t){
- const a=t.dataset.skt,it=SK.deck[SK.i];
- if(a==='flip')SK.flip=!SK.flip;
- else if(a==='grid')SK.grid=(SK.grid+1)%3;
- else if(a==='gray')SK.gray=!SK.gray;
- else if(a==='pair'&&it&&poseCounterpart(it)){SK.pair=!SK.pair;skShowCard();return}
- else if(a==='fav'&&it)toggleFav(it.k);
- skRenderTools();return;
- }
- const rec=e.target.closest('[data-sk-open]');
- if(rec){
- const it=ITEMS[rec.dataset.skOpen];
- sketchClose();
- if(it)setTab(it.type,it.id);
- }
-});
-
-// ---------- 全局命令面板(⌘K / Ctrl+K) ----------
-let cmdPrevFocus=null,cmdIdx=0,cmdItems=[];
-function cmdCatalog(){
- const list=[
- {g:'快捷操作',id:'act:sketch',label:'开始速写定时练习(60s)',kw:'sketch gesture timer croquis 速写 计时 练习 クロッキー',hint:'60s',run:()=>sketchOpen({dur:60})},
- {g:'快捷操作',id:'act:shuffle',label:'工作台 · 随机一组参考搭配',kw:'studio shuffle random 工作台 灵感 随机 シャッフル スタジオ',run:async()=>{navigate('studio');await new Promise(r=>setTimeout(r,80));$('#wbShuffle')?.click()}},
- {g:'快捷操作',id:'act:dock',label:trayOpen?'收起悬浮创作台':'展开悬浮创作台',kw:'dock tray workspace 悬浮 创作台 パネル',run:()=>trayOpen?closeTray():openTray()},
- {g:'快捷操作',id:'act:theme',label:'切换深浅外观',kw:'theme dark light 外观 深色 浅色 ダーク ライト',hint:'T',run:()=>window.PoseWearTheme.toggle()},
- {g:'快捷操作',id:'act:lang',label:'切换素材描述语言(中 / 英)',kw:'language prompt en zh 语言 英文 中文 言語',hint:'L',run:()=>setLang(st.lang==='zh'?'en':'zh')},
- {g:'快捷操作',id:'act:cfg',label:'打开 API 与本机引擎设置',kw:'api key comfyui sd.cpp settings 设置 配置 ローカル',run:()=>window.WB?.cfgOpen?.()},
- ];
- if(st.tab==='studio'&&!$('#wbExportBoard')?.hidden){
- list.splice(1,0,{g:'快捷操作',id:'act:export',label:'导出参考画板拼图 PNG',kw:'export board moodboard png 导出 拼图 書き出し',run:()=>$('#wbExportBoard')?.click()});
- }
- const tabMeta=[
- ['pose','姿势库','pose sketch line 姿态 ポーズ'],['depth','深度姿势','depth 3d map 深度'],
- ['portrait','人像库','portrait face model 人像 人物'],['expr','表情库','expression emotion 表情'],
- ['hair','发型库','hairstyle hair 发型 髪型'],['costume','服装库','costume outfit dress 服装 穿搭 衣装'],
- ['anime','动画服装库','anime costume outfit 动画 二次元 アニメ衣装'],['dyn','历代服饰','dynasty historical hanfu 历代 汉服 時代衣装'],
- ['scene','场景库','scene background 场景 背景'],['light','光影库','lighting light 光影 布光 照明'],
- ['prop','道具库','prop item 道具 小道具'],['furn','家具库','furniture 家具'],
- ['studio','创作工作台','studio tryon generate 工作台 试穿 生图 スタジオ'],
- ['fav','我的收藏','favorite saved 收藏 お気に入り'],['recent','最近浏览','recent history 最近 履歴'],['history','生成记录','generation history 记录 生成履歴'],
- ];
- for(const [tab,label,kw] of tabMeta){
- const n=tab==='fav'?st.fav.size:tab==='recent'?st.rec.length:tab==='history'?$('#nHist')?.textContent:($(`#libraryMenu [data-tab="${tab}"] [data-stat]`)?.textContent||'');
- list.push({g:'跳转栏目',id:'tab:'+tab,tab,label,kw:kw+' '+label,hint:n?String(n):'',run:()=>navigate(tab)});
- }
- return list;
-}
-function cmdDraw(){
- const q=($('#cmdQ').value||'').trim().toLowerCase();
- const all=cmdCatalog(),tr=window.PWLocale?s=>window.PWLocale.t(s):s=>s;
- cmdItems=q?all.filter(x=>(x.label+' '+tr(x.label)+' '+x.kw).toLowerCase().includes(q)):all;
- if(q&&FDEF[st.tab]){
- cmdItems.unshift({g:'当前图库搜索',id:'search',label:`搜索「${$('#cmdQ').value.trim()}」`,kw:q,hint:TNAME[st.tab],run:()=>{const v=$('#cmdQ').value.trim();$('#q').value=v;st.q=v;$('#qx').hidden=!v;apply()}});
- }
- cmdIdx=Math.min(cmdIdx,Math.max(0,cmdItems.length-1));
- const el=$('#cmdList');
- if(!cmdItems.length){el.innerHTML='<div class="cmd-empty">没有找到匹配的命令或栏目</div>';return}
- let html='',lastG='';
- cmdItems.forEach((it,i)=>{
- if(it.g!==lastG){html+=`<div class="cmd-g">${esc(it.g)}</div>`;lastG=it.g}
- const dot=it.tab&&PFX[it.tab]?`<i class="cmd-dot" data-tab="${it.tab}" aria-hidden="true"></i>`:'';
- html+=`<button type="button" class="cmd-it ${i===cmdIdx?'on':''}" role="option" aria-selected="${i===cmdIdx}" data-ci="${i}">${dot}<span>${esc(it.label)}</span>${it.hint?`<small>${esc(it.hint)}</small>`:''}</button>`;
- });
- el.innerHTML=html;
- el.querySelector('.cmd-it.on')?.scrollIntoView({block:'nearest'});
-}
-function cmdOpen(){
- const box=$('#cmdPal');if(!box||!box.hidden)return;
- if(SK.open)sketchClose();
- cmdPrevFocus=document.activeElement;
- box.hidden=false;$('#cmdQ').value='';cmdIdx=0;cmdDraw();
- $('#cmdQ').focus({preventScroll:true});
-}
-function cmdClose(){
- const box=$('#cmdPal');if(!box||box.hidden)return;
- box.hidden=true;
- cmdPrevFocus?.isConnected&&cmdPrevFocus.focus({preventScroll:true});cmdPrevFocus=null;
-}
-function cmdRun(i){
- const it=cmdItems[i];if(!it)return;
- cmdClose();it.run();
-}
-$('#qKbd')?.addEventListener('click',cmdOpen);
-$('#cmdQ')?.addEventListener('input',()=>{cmdIdx=0;cmdDraw()});
-$('#cmdList')?.addEventListener('click',e=>{const b=e.target.closest('[data-ci]');if(b)cmdRun(+b.dataset.ci)});
-$('#cmdPal')?.addEventListener('click',e=>{if(e.target.id==='cmdPal')cmdClose()});
-
-addEventListener('keydown',e=>{
- const k=(e.key||'').toLowerCase();
- if((e.ctrlKey||e.metaKey)&&!e.altKey&&k==='k'){
- e.preventDefault();
- $('#cmdPal').hidden?cmdOpen():cmdClose();
- return;
- }
- if(!$('#cmdPal').hidden){
- if(e.key==='Escape'){e.preventDefault();cmdClose()}
- else if(e.key==='ArrowDown'){e.preventDefault();if(cmdItems.length){cmdIdx=(cmdIdx+1)%cmdItems.length;cmdDraw()}}
- else if(e.key==='ArrowUp'){e.preventDefault();if(cmdItems.length){cmdIdx=(cmdIdx-1+cmdItems.length)%cmdItems.length;cmdDraw()}}
- else if(e.key==='Enter'){e.preventDefault();cmdRun(cmdIdx)}
- else if(e.key==='Tab')trapTab(e,$('#cmdPal'));
- return;
- }
- if(SK.open){
- if(e.key==='Escape'){e.preventDefault();sketchClose()}
- else if(e.key===' '||e.code==='Space'){e.preventDefault();skTogglePause()}
- else if(e.key==='ArrowRight'){e.preventDefault();skStep(1)}
- else if(e.key==='ArrowLeft'){e.preventDefault();skStep(-1)}
- else if(k==='h'){SK.flip=!SK.flip;skRenderTools()}
- else if(k==='g'){SK.grid=(SK.grid+1)%3;skRenderTools()}
- else if(k==='b'){SK.gray=!SK.gray;skRenderTools()}
- else if(k==='v'){const it=SK.deck[SK.i];if(it&&poseCounterpart(it)){SK.pair=!SK.pair;skShowCard()}}
- else if(k==='f'){const it=SK.deck[SK.i];if(it){toggleFav(it.k);skRenderTools()}}
- else if(e.key==='Tab')trapTab(e,$('#sketch'));
- return;
- }
- 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}
- 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=='z')lbToggleTool('zoom');else if(k=='h')lbToggleTool('flip');else if(k=='g')lbToggleTool('grid');else if(k=='b')lbToggleTool('gray');else if(k=='v')lbToggleTool('cmp');else if(k=='t')window.PoseWearTheme.toggle();
- 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,tSkip=false;$('.lb-img').addEventListener('touchstart',e=>{tSkip=lbV.zoom>1||!!e.target.closest('#lbPairRange,#lbTools');tx=e.touches[0].clientX;ty=e.touches[0].clientY},{passive:true});$('.lb-img').addEventListener('touchend',e=>{if(tSkip)return;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 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();
- 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=()=>{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();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();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,counterpartType,poseCounterpart,cardFace,studioSlot,suggestions:SUGG,sendToStudio,ageAsk,toggleFav,toggleSel,lbOpen,lbClose,lbResetView,sketchOpen,sketchClose,cmdOpen,cmdClose,previewItem,apply,li:()=>li,load,ITEMS,DATA,thumb,big,ath,title,prompt,toast,esc,setTab:navigate,st,copy,copyBrief,needKeys};
+
+ // ---------- Routing ----------
+ 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));
+ }
+
+ // ---------- Adult Content Switch & Privacy Modal ----------
+ function ageSet(on, animate) {
+ 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 update = () => {
+ if (!FDEF[st.tab]) return;
+ drawFilters();
+ apply();
+ tray();
+ if (origin && !$('#lb').hidden && !closing) {
+ li = st.list.indexOf(origin);
+ if (li < 0) lbClose(false, true);
+ else lbDraw();
+ }
+ };
+ if (animate) viewT(update);
+ else update();
+ }
+ if (st.tab === 'studio') window.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 = () => {
+ closeDialog($('#ageBox'));
+ ageSet(true, !ageCb);
+ toast('已显示成人向内容,可用顶部开关关闭');
+ const cb = ageCb;
+ ageCb = null;
+ cb?.();
+ };
+ $('#ageN').onclick = $('#ageBox').onclick = e => {
+ if (e.target.id !== 'ageN' && e.target.id !== 'ageBox') return;
+ closeDialog($('#ageBox'));
+ ageCb = null;
+ };
+ document.addEventListener('click', e => {
+ if (!e.target.closest('[data-age]')) return;
+ if (st.adult) { ageSet(false); toast('已隐藏成人内容'); }
+ else ageAsk();
+ });
+ $('#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();
+ });
+
+ // ---------- Bootstrap & Public API ----------
+ 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,
+ counterpartType,
+ poseCounterpart,
+ cardFace,
+ studioSlot,
+ suggestions: SUGG,
+ sendToStudio,
+ ageAsk,
+ toggleFav,
+ toggleSel,
+ lbOpen,
+ lbClose,
+ lbResetView,
+ sketchOpen: opts => window.PoseWearSketch?.open(opts),
+ sketchClose: () => window.PoseWearSketch?.close(),
+ cmdOpen: () => window.PoseWearCommandPalette?.open(),
+ cmdClose: () => window.PoseWearCommandPalette?.close(),
+ openItem: (type, id) => setTab(type, id),
+ applySearch,
+ isTrayOpen: () => trayOpen,
+ openTray,
+ closeTray,
+ setLang,
+ trapTab,
+ preload,
+ previewItem,
+ apply,
+ li: () => li,
+ load,
+ ITEMS,
+ DATA,
+ thumb,
+ big,
+ ath,
+ title,
+ prompt,
+ toast,
+ esc,
+ setTab: navigate,
+ st,
+ copy,
+ copyBrief,
+ needKeys,
+ };
+})();
diff --git a/src/board-export.js b/src/board-export.js
new file mode 100644
index 0000000..ca55727
--- /dev/null
+++ b/src/board-export.js
@@ -0,0 +1,277 @@
+'use strict';
+(() => {
+ // Pure client-side HTML5 Canvas compositor for exporting the Studio reference board
+ // as a crisp 2x editorial moodboard PNG matching the active light/dark theme.
+ const C = window.PoseWearCatalog;
+ if (!C) return;
+ const { ACCENT, BOARD_LABELS } = C;
+
+ function roundRectPath(ctx, x, y, w, h, r) {
+ ctx.beginPath();
+ ctx.moveTo(x + r, y);
+ ctx.arcTo(x + w, y, x + w, y + h, r);
+ ctx.arcTo(x + w, y + h, x, y + h, r);
+ ctx.arcTo(x, y + h, x, y, r);
+ ctx.arcTo(x, y, x + w, y, r);
+ ctx.closePath();
+ }
+
+ function clipText(ctx, str, maxW) {
+ const s = String(str || '').replace(/\s+/g, ' ').trim();
+ if (!s || ctx.measureText(s).width <= maxW) return s;
+ let lo = 0;
+ let hi = s.length;
+ while (lo < hi) {
+ const mid = (lo + hi + 1) >> 1;
+ if (ctx.measureText(s.slice(0, mid) + '…').width <= maxW) lo = mid;
+ else hi = mid - 1;
+ }
+ return s.slice(0, lo) + '…';
+ }
+
+ function loadImage(ref, item) {
+ return new Promise(resolve => {
+ const img = new Image();
+ let src = '';
+ if (ref.blob || (ref.url && !item)) {
+ src = ref.url;
+ } else if (item && !item.ext) {
+ src = item.angles
+ ? (item.angles[ref.ai ?? item.ai]?.i || item.angles[ref.ai ?? item.ai]?.t)
+ : (item.m || item.i || item.t);
+ } else if (item?.ext) {
+ img.crossOrigin = 'anonymous';
+ if (item.ref) img.referrerPolicy = item.ref;
+ src = item.m || item.t;
+ }
+ if (!src) return resolve(null);
+ const done = ok => resolve(ok && img.naturalWidth ? img : null);
+ img.onload = () => done(true);
+ img.onerror = () => done(false);
+ img.src = src;
+ });
+ }
+
+ async function renderPng(chosen, { app, aspectRatio = 'auto', promptText = '' } = {}) {
+ if (!chosen.length) return { blob: null, extSkipped: 0 };
+ const t = s => (window.PWLocale ? window.PWLocale.t(s) : s);
+
+ const entries = await Promise.all(
+ chosen.map(async ([type, ref], idx) => {
+ const item = app.ITEMS[ref.k];
+ const material = item?.type || type;
+ const title = item ? app.title(item) : (ref.name || t('本地上传'));
+ const rawAngle = item?.angles?.[ref.ai ?? item.ai]?.zh || '';
+ const img = await loadImage(ref, item);
+ return {
+ idx: idx + 1,
+ material,
+ cat: t(BOARD_LABELS[material] || material),
+ title,
+ angle: rawAngle ? t(rawAngle) : '',
+ img,
+ ext: !!item?.ext,
+ };
+ })
+ );
+
+ const dark = document.documentElement.dataset.theme === 'dark';
+ const n = entries.length;
+ const cols = n <= 3 ? n : n === 4 ? 2 : n <= 6 ? 3 : 4;
+ const rows = Math.ceil(n / cols);
+ const cardW = 360;
+ const padImg = 12;
+ const imgW = cardW - padImg * 2;
+ const imgH = 448;
+ const capH = 68;
+ const cardH = padImg + imgH + capH;
+ const gap = 28;
+ const padX = 56;
+ const headH = 96;
+ const footH = 68;
+ const width = Math.max(840, padX * 2 + cols * cardW + (cols - 1) * gap);
+ const height = headH + rows * cardH + (rows - 1) * gap + footH;
+
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext('2d');
+ const sans = '-apple-system,BlinkMacSystemFont,"PingFang SC","Noto Sans SC","Helvetica Neue",Arial,sans-serif';
+
+ // Surface + subtle studio dot-grid
+ ctx.fillStyle = dark ? '#141416' : '#f7f7f8';
+ ctx.fillRect(0, 0, width, height);
+ ctx.fillStyle = dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.065)';
+ for (let y = 24; y < height; y += 24) {
+ for (let x = 24; x < width; x += 24) {
+ ctx.beginPath();
+ ctx.arc(x, y, 1, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ }
+
+ // Header brand mark + title + metadata
+ const ac = dark ? '#ff3b57' : '#ff2442';
+ const ink = dark ? '#f2f2f2' : '#111111';
+ const mu = dark ? '#9a9a9e' : '#666666';
+ const cardBg = dark ? '#1e1e22' : '#ffffff';
+ const lineCol = dark ? '#323236' : '#e4e4e7';
+
+ ctx.fillStyle = ac;
+ ctx.beginPath();
+ ctx.arc(padX + 14, 35, 4.2, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.strokeStyle = ac;
+ ctx.lineWidth = 3.2;
+ ctx.lineJoin = 'round';
+ ctx.beginPath();
+ ctx.moveTo(padX + 14, 42);
+ ctx.lineTo(padX + 3, 55);
+ ctx.lineTo(padX + 25, 55);
+ ctx.closePath();
+ ctx.stroke();
+
+ ctx.fillStyle = ink;
+ ctx.font = `700 22px ${sans}`;
+ ctx.textBaseline = 'middle';
+ ctx.fillText('PoseWear', padX + 36, 46);
+ const brandW = ctx.measureText('PoseWear').width;
+ ctx.fillStyle = mu;
+ ctx.font = `500 16px ${sans}`;
+ ctx.fillText('· ' + t('参考画板'), padX + 48 + brandW, 47);
+
+ const now = new Date();
+ const dateStamp = `${now.getFullYear()}.${String(now.getMonth() + 1).padStart(2, '0')}.${String(now.getDate()).padStart(2, '0')}`;
+ const unit = document.documentElement.lang === 'en' && n === 1 ? 'image' : t('张');
+ const metaParts = [`${n} ${unit}`, aspectRatio !== 'auto' ? aspectRatio : '', dateStamp].filter(Boolean).join(' · ');
+ ctx.textAlign = 'right';
+ ctx.font = `500 14px ${sans}`;
+ ctx.fillStyle = mu;
+ ctx.fillText(metaParts, width - padX, 47);
+ ctx.textAlign = 'left';
+
+ // Cards
+ let extSkipped = 0;
+ entries.forEach((entry, i) => {
+ const row = Math.floor(i / cols);
+ const col = i % cols;
+ const rowCount = row === rows - 1 ? n - row * cols : cols;
+ const rowW = rowCount * cardW + (rowCount - 1) * gap;
+ const startX = (width - rowW) / 2;
+ const x = startX + col * (cardW + gap);
+ const y = headH + row * (cardH + gap);
+ const edge = ACCENT[entry.material] || lineCol;
+
+ ctx.save();
+ ctx.shadowColor = dark ? 'rgba(0,0,0,0.45)' : 'rgba(0,0,0,0.08)';
+ ctx.shadowBlur = 22;
+ ctx.shadowOffsetY = 8;
+ roundRectPath(ctx, x, y, cardW, cardH, 18);
+ ctx.fillStyle = cardBg;
+ ctx.fill();
+ ctx.restore();
+
+ roundRectPath(ctx, x, y, cardW, cardH, 18);
+ ctx.strokeStyle = edge + '77';
+ ctx.lineWidth = 1.5;
+ ctx.stroke();
+
+ const ix = x + padImg;
+ const iy = y + padImg;
+ ctx.save();
+ roundRectPath(ctx, ix, iy, imgW, imgH, 12);
+ ctx.clip();
+ ctx.fillStyle = entry.material === 'depth'
+ ? '#141414'
+ : entry.material === 'pose'
+ ? '#f4f4f4'
+ : (dark ? '#26262a' : '#f3f3f5');
+ ctx.fillRect(ix, iy, imgW, imgH);
+
+ if (entry.img) {
+ const pad = entry.material === 'pose' ? 16 : 0;
+ const aw = imgW - pad * 2;
+ const ah = imgH - pad * 2;
+ const scale = Math.min(aw / entry.img.naturalWidth, ah / entry.img.naturalHeight);
+ const dw = entry.img.naturalWidth * scale;
+ const dh = entry.img.naturalHeight * scale;
+ if (entry.material === 'pose') ctx.globalCompositeOperation = 'multiply';
+ ctx.drawImage(entry.img, ix + pad + (aw - dw) / 2, iy + pad + (ah - dh) / 2, dw, dh);
+ ctx.globalCompositeOperation = 'source-over';
+ } else {
+ if (entry.ext) extSkipped++;
+ ctx.fillStyle = mu;
+ ctx.font = `600 15px ${sans}`;
+ ctx.textAlign = 'center';
+ ctx.fillText(entry.cat, ix + imgW / 2, iy + imgH / 2 - 16);
+ ctx.font = `400 13px ${sans}`;
+ ctx.fillText(clipText(ctx, entry.title, imgW - 36), ix + imgW / 2, iy + imgH / 2 + 8);
+ if (entry.ext) {
+ ctx.font = `400 12px ${sans}`;
+ ctx.fillText(t('在原站查看'), ix + imgW / 2, iy + imgH / 2 + 32);
+ }
+ ctx.textAlign = 'left';
+ }
+ ctx.restore();
+
+ // Send-order badge
+ roundRectPath(ctx, ix + 10, iy + 10, 28, 28, 8);
+ ctx.fillStyle = 'rgba(17,17,17,0.82)';
+ ctx.fill();
+ ctx.fillStyle = '#ffffff';
+ ctx.font = `700 14px ${sans}`;
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillText(String(entry.idx), ix + 24, iy + 24);
+ ctx.textAlign = 'left';
+
+ // Camera angle pill
+ if (entry.angle) {
+ ctx.font = `600 12px ${sans}`;
+ const pillW = ctx.measureText(entry.angle).width + 18;
+ roundRectPath(ctx, ix + imgW - pillW - 10, iy + imgH - 32, pillW, 22, 11);
+ ctx.fillStyle = 'rgba(17,17,17,0.78)';
+ ctx.fill();
+ ctx.fillStyle = '#ffffff';
+ ctx.textAlign = 'center';
+ ctx.fillText(entry.angle, ix + imgW - pillW / 2 - 10, iy + imgH - 21);
+ ctx.textAlign = 'left';
+ }
+
+ // Caption footer
+ const cy = iy + imgH + 22;
+ ctx.fillStyle = edge;
+ ctx.beginPath();
+ ctx.arc(x + 20, cy, 4.5, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.fillStyle = mu;
+ ctx.font = `600 13px ${sans}`;
+ ctx.fillText(entry.cat, x + 32, cy);
+ ctx.fillStyle = ink;
+ ctx.font = `600 15px ${sans}`;
+ ctx.fillText(clipText(ctx, entry.title, cardW - 36), x + 18, cy + 24);
+ });
+
+ // Footer colophon
+ const fy = height - footH + 24;
+ ctx.strokeStyle = lineCol;
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ ctx.moveTo(padX, fy - 14);
+ ctx.lineTo(width - padX, fy - 14);
+ ctx.stroke();
+
+ const promptSnippet = clipText(ctx, promptText, width - padX * 2 - 190);
+ ctx.fillStyle = mu;
+ ctx.font = `400 13px ${sans}`;
+ if (promptSnippet) ctx.fillText(promptSnippet, padX, fy + 12);
+ ctx.textAlign = 'right';
+ ctx.font = `600 13px ${sans}`;
+ ctx.fillText('posewear.pages.dev', width - padX, fy + 12);
+
+ const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
+ return { blob, extSkipped, now };
+ }
+
+ window.PoseWearBoardExport = { renderPng };
+})();
diff --git a/src/catalog.js b/src/catalog.js
new file mode 100644
index 0000000..94d5a78
--- /dev/null
+++ b/src/catalog.js
@@ -0,0 +1,286 @@
+'use strict';
+(() => {
+ // Single source of truth for PoseWear's 12 reference collections,
+ // filter metadata, studio slot routing, accent tokens, and shared DOM/storage helpers.
+ const COLLECTIONS = [
+ {
+ id: 'pose',
+ prefix: 'p:',
+ label: '姿势',
+ title: '姿势库',
+ file: 'poses.json',
+ statKey: 'pose',
+ slot: 'pose',
+ accent: '#849dbb',
+ filters: [['line', '系列'], ['cat', '分类'], ['ang', '角度']],
+ suggestions: ['站姿', '坐姿', '回头', '双手抱头', '可爱', '躺卧', '比心', '跪立'],
+ keywords: 'pose sketch line 姿态 ポーズ',
+ },
+ {
+ id: 'depth',
+ prefix: 'd:',
+ label: '深度姿势',
+ title: '深度姿势',
+ file: 'depths.json',
+ statKey: 'depth',
+ slot: 'pose',
+ accent: '#9689ae',
+ filters: [['line', '系列'], ['cat', '分类'], ['ang', '角度']],
+ suggestions: ['站姿', '坐姿', '上半身', '全身', '俯拍', '侧面', '可爱', '跪立'],
+ keywords: 'depth 3d map 深度',
+ },
+ {
+ id: 'costume',
+ prefix: 'c:',
+ label: '服装',
+ title: '服装库',
+ file: 'costumes.json',
+ statKey: 'cos',
+ slot: 'garment',
+ accent: '#be929a',
+ filters: [['cat', '分类'], ['col', '颜色'], ['item', '单品']],
+ suggestions: ['连衣裙', '黑色', '泳装', '针织', '蕾丝', '冬季', '牛仔', '高跟鞋'],
+ keywords: 'costume outfit dress 服装 穿搭 衣装',
+ },
+ {
+ id: 'anime',
+ prefix: 'a:',
+ label: '动画服装',
+ title: '动画服装库',
+ file: 'anime.json',
+ statKey: 'ani',
+ slot: 'garment',
+ accent: '#b08fad',
+ filters: [['cat', '分类'], ['col', '颜色'], ['item', '单品']],
+ suggestions: ['连衣裙', '黑色', '泳装', '针织', '蕾丝', '冬季', '牛仔', '制服'],
+ keywords: 'anime costume outfit 动画 二次元 アニメ衣装',
+ },
+ {
+ id: 'portrait',
+ prefix: 'r:',
+ label: '人像',
+ title: '人像库',
+ file: 'portraits.json',
+ statKey: 'por',
+ slot: 'portrait',
+ accent: '#c49a82',
+ filters: [['sec', '类型'], ['len', '发长'], ['st', '发型']],
+ suggestions: ['短发', '波波', '狼尾', '刘海', '卷', '奶茶', '黑发', '正脸'],
+ keywords: 'portrait face model 人像 人物',
+ },
+ {
+ id: 'expr',
+ prefix: 'e:',
+ label: '表情',
+ title: '表情库',
+ file: 'expressions.json',
+ statKey: 'exp',
+ slot: 'expr',
+ accent: '#a2778b',
+ filters: [['emo', '情绪'], ['int', '强度']],
+ suggestions: ['开心', '大笑', '愤怒', '害羞', '搞怪', '严肃'],
+ keywords: 'expression emotion 表情',
+ },
+ {
+ id: 'hair',
+ prefix: 'h:',
+ label: '发型',
+ title: '发型库',
+ file: 'hair.json',
+ statKey: 'hair',
+ slot: 'extra',
+ roleEn: 'Hairstyle',
+ accent: '#968071',
+ filters: [['cat', '分类']],
+ suggestions: ['长发', '双马尾', '刘海', '发饰', '瞳色'],
+ keywords: 'hairstyle hair 发型 髪型',
+ },
+ {
+ id: 'dyn',
+ prefix: 'y:',
+ label: '历代服饰',
+ title: '历代服饰',
+ file: 'dynasties.json',
+ statKey: 'dyn',
+ slot: 'garment',
+ accent: '#ab7870',
+ filters: [['era', '朝代'], ['ang', '角度']],
+ suggestions: ['唐', '宋', '明', '曲裾', '齐胸'],
+ keywords: 'dynasty historical hanfu 历代 汉服 時代衣装',
+ },
+ {
+ id: 'scene',
+ prefix: 's:',
+ label: '场景',
+ title: '场景库',
+ file: 'scenes.json',
+ statKey: 'scene',
+ slot: 'extra',
+ roleEn: 'Scene',
+ accent: '#88a48a',
+ filters: [['cat', '分类'], ['ang', '机位']],
+ suggestions: ['客厅', '庭院', '街道', '海岸'],
+ keywords: 'scene background 场景 背景',
+ },
+ {
+ id: 'light',
+ prefix: 'l:',
+ label: '光影',
+ title: '光影库',
+ file: 'lights.json',
+ statKey: 'light',
+ slot: 'extra',
+ roleEn: 'Lighting',
+ accent: '#a2b6bf',
+ filters: [['cat', '分类'], ['ang', '机位']],
+ suggestions: ['伦勃朗', '窗光', '黄昏', '夜景'],
+ keywords: 'lighting light 光影 布光 照明',
+ },
+ {
+ id: 'prop',
+ prefix: 't:',
+ label: '道具',
+ title: '道具库',
+ file: 'props.json',
+ statKey: 'prop',
+ slot: 'extra',
+ roleEn: 'Prop',
+ accent: '#739e9c',
+ filters: [['cat', '分类'], ['ang', '视角']],
+ suggestions: ['吉他', '油纸伞', '灯笼', '相机'],
+ keywords: 'prop item 道具 小道具',
+ },
+ {
+ id: 'furn',
+ prefix: 'f:',
+ label: '家具',
+ title: '家具库',
+ file: 'furniture.json',
+ statKey: 'furn',
+ slot: 'extra',
+ roleEn: 'Furniture',
+ accent: '#95928e',
+ filters: [['cat', '分类'], ['ang', '视角']],
+ suggestions: ['餐椅', '沙发', '造型台', '床榻'],
+ keywords: 'furniture 家具',
+ },
+ ];
+
+ const UTILITY_TABS = [
+ { id: 'studio', title: '工作台', cmdLabel: '创作工作台', keywords: 'studio tryon generate 工作台 试穿 生图 スタジオ' },
+ { id: 'fav', title: '我的收藏', cmdLabel: '我的收藏', keywords: 'favorite saved 收藏 お気に入り' },
+ { id: 'recent', title: '最近浏览', cmdLabel: '最近浏览', keywords: 'recent history 最近 履歴' },
+ { id: 'history', title: '生成记录', cmdLabel: '生成记录', keywords: 'generation history 记录 生成履歴' },
+ ];
+
+ const TABS = [...COLLECTIONS.map(c => c.id), ...UTILITY_TABS.map(t => t.id)];
+ const TNAME = Object.fromEntries([
+ ...COLLECTIONS.map(c => [c.id, c.title]),
+ ...UTILITY_TABS.map(t => [t.id, t.title]),
+ ]);
+ const PFX = Object.fromEntries(COLLECTIONS.map(c => [c.id, c.prefix]));
+ const KT = Object.fromEntries(COLLECTIONS.map(c => [c.prefix[0], c.id]));
+ const LABELS = Object.fromEntries(COLLECTIONS.map(c => [c.id, c.label]));
+ const BOARD_LABELS = { ...LABELS, portrait: '人物' };
+ const ACCENT = Object.fromEntries(COLLECTIONS.map(c => [c.id, c.accent]));
+ const FDEF = {
+ ...Object.fromEntries(COLLECTIONS.map(c => [c.id, c.filters])),
+ fav: [['type', '类型']],
+ recent: [['type', '类型']],
+ };
+ const SUGG = {
+ ...Object.fromEntries(COLLECTIONS.map(c => [c.id, c.suggestions])),
+ fav: [],
+ recent: [],
+ };
+ const STUDIO_SLOT = Object.fromEntries(
+ COLLECTIONS.filter(c => c.slot !== 'extra').map(c => [c.id, c.slot])
+ );
+ const GARMENT_TYPES = COLLECTIONS.filter(c => c.slot === 'garment').map(c => c.id);
+ const OTHER_TYPES = COLLECTIONS.filter(c => c.slot === 'expr' || c.slot === 'extra').map(c => c.id);
+ const MATERIAL_ROLES = Object.fromEntries(
+ COLLECTIONS.filter(c => c.slot === 'extra').map(c => [c.id, [c.label, c.roleEn]])
+ );
+
+ 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',
+ };
+
+ const COL_SWATCH = {
+ 黑: '#1c1c1e', 白: '#ffffff', 红: '#d92d46', 粉: '#f2a5b8', 蓝: '#3b7dd8', 藏青: '#223354',
+ 棕: '#80553a', 米: '#d8cab6', 象牙白: '#f5f1e6', 灰: '#8e8e93', 绿: '#478a5d', 黄: '#d8be6b',
+ 紫: '#8664b8', 金: '#b89e68', 银: '#c0c4ca', 卡其: '#b5a27e', 酒红: '#7c2237', 橙: '#df7a42',
+ 奶油: '#f3ebd8', 薄荷: '#8fd3be', 薰衣草: '#b8a5d6', 橄榄: '#687444',
+ };
+
+ const ITEMK = {
+ 连衣裙: 'dress', 半身裙: 'skirt', 短裤: 'shorts', 长裤: 'trousers', 牛仔裤: 'jeans',
+ 大衣: 'coat', 夹克: 'jacket', 开衫: 'cardigan', 衬衫: 'blouse', 毛衣: 'sweater',
+ 吊带: 'camisole', 文胸: 'bra', 泳衣: 'swimsuit', 靴子: 'boots', 高跟鞋: 'high heels',
+ 运动鞋: 'sneakers', 凉鞋: 'sandals', 连裤袜: 'tights', 长筒袜: 'stockings',
+ };
+
+ // Shared lightweight utilities (zero external dependencies)
+ const $ = (sel, root = document) => root.querySelector(sel);
+ const $$ = (sel, root = document) => root.querySelectorAll(sel);
+ const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
+ const readLS = key => { try { return JSON.parse(localStorage[key] || 'null'); } catch { return null; } };
+ const writeLS = (key, value) => { try { localStorage[key] = JSON.stringify(value); } catch {} };
+ const shuffle = list => {
+ for (let i = list.length - 1; i > 0; i--) {
+ const j = (Math.random() * (i + 1)) | 0;
+ [list[i], list[j]] = [list[j], list[i]];
+ }
+ return list;
+ };
+ const TL = item => LABELS[item.type];
+ const studioSlot = type => STUDIO_SLOT[type] || 'extra';
+
+ window.PoseWearCatalog = {
+ COLLECTIONS,
+ UTILITY_TABS,
+ TABS,
+ TNAME,
+ PFX,
+ KT,
+ LABELS,
+ BOARD_LABELS,
+ ACCENT,
+ FDEF,
+ FLAB,
+ SUGG,
+ STUDIO_SLOT,
+ GARMENT_TYPES,
+ OTHER_TYPES,
+ MATERIAL_ROLES,
+ COLS,
+ COL_SWATCH,
+ ITEMK,
+ TL,
+ studioSlot,
+ $,
+ $$,
+ esc,
+ readLS,
+ writeLS,
+ shuffle,
+ };
+})();
diff --git a/src/command-palette.js b/src/command-palette.js
new file mode 100644
index 0000000..16d9772
--- /dev/null
+++ b/src/command-palette.js
@@ -0,0 +1,234 @@
+'use strict';
+(() => {
+ // Global Command Palette (⌘K / Ctrl+K) backed by PoseWearCatalog.
+ const C = window.PoseWearCatalog;
+ if (!C) return;
+ const { $, esc, COLLECTIONS, UTILITY_TABS, PFX, FDEF, TNAME } = C;
+
+ let app = null;
+ let prevFocus = null;
+ let activeIndex = 0;
+ let visibleItems = [];
+
+ function buildCatalog() {
+ const list = [
+ {
+ g: '快捷操作',
+ id: 'act:sketch',
+ label: '开始速写定时练习(60s)',
+ kw: 'sketch gesture timer croquis 速写 计时 练习 クロッキー',
+ hint: '60s',
+ run: () => app.sketchOpen({ dur: 60 }),
+ },
+ {
+ g: '快捷操作',
+ id: 'act:shuffle',
+ label: '工作台 · 随机一组参考搭配',
+ kw: 'studio shuffle random 工作台 灵感 随机 シャッフル スタジオ',
+ run: async () => {
+ app.setTab('studio');
+ await new Promise(r => setTimeout(r, 80));
+ $('#wbShuffle')?.click();
+ },
+ },
+ {
+ g: '快捷操作',
+ id: 'act:dock',
+ label: app.isTrayOpen() ? '收起悬浮创作台' : '展开悬浮创作台',
+ kw: 'dock tray workspace 悬浮 创作台 パネル',
+ run: () => (app.isTrayOpen() ? app.closeTray() : app.openTray()),
+ },
+ {
+ g: '快捷操作',
+ id: 'act:theme',
+ label: '切换深浅外观',
+ kw: 'theme dark light 外观 深色 浅色 ダーク ライト',
+ hint: 'T',
+ run: () => window.PoseWearTheme.toggle(),
+ },
+ {
+ g: '快捷操作',
+ id: 'act:lang',
+ label: '切换素材描述语言(中 / 英)',
+ kw: 'language prompt en zh 语言 英文 中文 言語',
+ hint: 'L',
+ run: () => app.setLang(app.st.lang === 'zh' ? 'en' : 'zh'),
+ },
+ {
+ g: '快捷操作',
+ id: 'act:cfg',
+ label: '打开 API 与本机引擎设置',
+ kw: 'api key comfyui sd.cpp settings 设置 配置 ローカル',
+ run: () => window.WB?.cfgOpen?.(),
+ },
+ ];
+
+ if (app.st.tab === 'studio' && !$('#wbExportBoard')?.hidden) {
+ list.splice(1, 0, {
+ g: '快捷操作',
+ id: 'act:export',
+ label: '导出参考画板拼图 PNG',
+ kw: 'export board moodboard png 导出 拼图 書き出し',
+ run: () => $('#wbExportBoard')?.click(),
+ });
+ }
+
+ for (const col of COLLECTIONS) {
+ const count = $(`#libraryMenu [data-tab="${col.id}"] [data-stat]`)?.textContent || '';
+ list.push({
+ g: '跳转栏目',
+ id: 'tab:' + col.id,
+ tab: col.id,
+ label: col.title,
+ kw: `${col.keywords} ${col.title} ${col.label}`,
+ hint: count ? String(count) : '',
+ run: () => app.setTab(col.id),
+ });
+ }
+
+ for (const tab of UTILITY_TABS) {
+ const count = tab.id === 'fav'
+ ? app.st.fav.size
+ : tab.id === 'recent'
+ ? app.st.rec.length
+ : tab.id === 'history'
+ ? ($('#nHist')?.textContent || '')
+ : '';
+ list.push({
+ g: '跳转栏目',
+ id: 'tab:' + tab.id,
+ tab: tab.id,
+ label: tab.cmdLabel,
+ kw: `${tab.keywords} ${tab.cmdLabel}`,
+ hint: count ? String(count) : '',
+ run: () => app.setTab(tab.id),
+ });
+ }
+
+ return list;
+ }
+
+ function render() {
+ const rawQuery = ($('#cmdQ').value || '').trim();
+ const q = rawQuery.toLowerCase();
+ const all = buildCatalog();
+ const tr = window.PWLocale ? s => window.PWLocale.t(s) : s => s;
+
+ visibleItems = q
+ ? all.filter(item => `${item.label} ${tr(item.label)} ${item.kw}`.toLowerCase().includes(q))
+ : all;
+
+ if (q && FDEF[app.st.tab]) {
+ visibleItems.unshift({
+ g: '当前图库搜索',
+ id: 'search',
+ label: `搜索「${rawQuery}」`,
+ kw: q,
+ hint: TNAME[app.st.tab],
+ run: () => app.applySearch(rawQuery),
+ });
+ }
+
+ activeIndex = Math.min(activeIndex, Math.max(0, visibleItems.length - 1));
+ const listEl = $('#cmdList');
+ if (!visibleItems.length) {
+ listEl.innerHTML = '<div class="cmd-empty">没有找到匹配的命令或栏目</div>';
+ return;
+ }
+
+ let html = '';
+ let lastGroup = '';
+ visibleItems.forEach((item, index) => {
+ if (item.g !== lastGroup) {
+ html += `<div class="cmd-g">${esc(item.g)}</div>`;
+ lastGroup = item.g;
+ }
+ const dot = item.tab && PFX[item.tab]
+ ? `<i class="cmd-dot" data-tab="${item.tab}" aria-hidden="true"></i>`
+ : '';
+ const selected = index === activeIndex;
+ const hint = item.hint ? `<small>${esc(item.hint)}</small>` : '';
+ html += `<button type="button" class="cmd-it ${selected ? 'on' : ''}" role="option" aria-selected="${selected}" data-ci="${index}">${dot}<span>${esc(item.label)}</span>${hint}</button>`;
+ });
+
+ listEl.innerHTML = html;
+ listEl.querySelector('.cmd-it.on')?.scrollIntoView({ block: 'nearest' });
+ }
+
+ function open() {
+ const box = $('#cmdPal');
+ if (!box || !box.hidden || !app) return;
+ if (window.PoseWearSketch?.isOpen()) window.PoseWearSketch.close();
+ prevFocus = document.activeElement;
+ box.hidden = false;
+ $('#cmdQ').value = '';
+ activeIndex = 0;
+ render();
+ $('#cmdQ').focus({ preventScroll: true });
+ }
+
+ function close() {
+ const box = $('#cmdPal');
+ if (!box || box.hidden) return;
+ box.hidden = true;
+ if (prevFocus?.isConnected) prevFocus.focus({ preventScroll: true });
+ prevFocus = null;
+ }
+
+ function execute(index) {
+ const item = visibleItems[index];
+ if (!item) return;
+ close();
+ item.run();
+ }
+
+ function isOpen() {
+ const box = $('#cmdPal');
+ return !!(box && !box.hidden);
+ }
+
+ function handleKey(e) {
+ if (!isOpen()) return false;
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ close();
+ } else if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ if (visibleItems.length) {
+ activeIndex = (activeIndex + 1) % visibleItems.length;
+ render();
+ }
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ if (visibleItems.length) {
+ activeIndex = (activeIndex - 1 + visibleItems.length) % visibleItems.length;
+ render();
+ }
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ execute(activeIndex);
+ } else if (e.key === 'Tab') {
+ app.trapTab(e, $('#cmdPal'));
+ }
+ return true;
+ }
+
+ function init(appApi) {
+ app = appApi;
+ $('#qKbd')?.addEventListener('click', open);
+ $('#cmdQ')?.addEventListener('input', () => {
+ activeIndex = 0;
+ render();
+ });
+ $('#cmdList')?.addEventListener('click', e => {
+ const btn = e.target.closest('[data-ci]');
+ if (btn) execute(+btn.dataset.ci);
+ });
+ $('#cmdPal')?.addEventListener('click', e => {
+ if (e.target.id === 'cmdPal') close();
+ });
+ }
+
+ window.PoseWearCommandPalette = { init, open, close, isOpen, handleKey };
+ if (window.APP) init(window.APP);
+})();
diff --git a/src/extras.js b/src/extras.js
index 9791f84..d6cb79b 100644
--- a/src/extras.js
+++ b/src/extras.js
@@ -1,69 +1,451 @@
-// 衣姿 v8:动效与小功能
-(()=>{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(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=()=>$('#personalMenu summary');
-grid.addEventListener('click',e=>{const b=e.target.closest('[data-a]');const card=e.target.closest('.card');if(!card)return;
- 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();
-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);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'){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)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)});
-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(),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.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(!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.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(!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(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',()=>{$('#noticeReload').hidden=false});
- $('#noticeReload').onclick=()=>location.reload();
-}
+'use strict';
+// Gallery enhancements: micro-interactions, batch selection, search suggestions,
+// lightbox similar recommendations, image download/copy, and PWA update notice.
+(() => {
+ const A = window.APP;
+ const C = window.PoseWearCatalog;
+ if (!A || !C) return;
+ const { $, $$, readLS: LS, writeLS: SV } = C;
+ const motionPreference = matchMedia('(prefers-reduced-motion: reduce)');
+ const EZ = 'cubic-bezier(.16,1,.3,1)';
+ const grid = $('#grid');
+
+ 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 });
+
+ // ---------- Micro-interactions ----------
+ function burst(el) {
+ if (motionPreference.matches || !el) return;
+ const rect = el.getBoundingClientRect();
+ const cx = rect.left + rect.width / 2;
+ const cy = rect.top + rect.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 angle = (i / 8) * Math.PI * 2;
+ const dist = 18 + Math.random() * 10;
+ p.animate(
+ [
+ { transform: 'translate(-50%,-50%) scale(1)', opacity: 1 },
+ { transform: `translate(calc(-50% + ${Math.cos(angle) * dist}px),calc(-50% + ${Math.sin(angle) * dist}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();
+ const b = target.getBoundingClientRect();
+ if (!a.width) return;
+ const clone = img.cloneNode();
+ clone.className = 'flyimg';
+ clone.style.cssText = `left:${a.left}px;top:${a.top}px;width:${a.width}px;height:${a.height}px`;
+ document.body.append(clone);
+ const dx = b.left + b.width / 2 - (a.left + a.width / 2);
+ const dy = b.top + b.height / 2 - (a.top + a.height / 2);
+ clone.animate(
+ [
+ { transform: 'none', opacity: 1, borderRadius: '14px' },
+ { transform: `translate(${dx * 0.6}px,${dy * 0.6 - 40}px) scale(.35)`, opacity: 0.9, offset: 0.6 },
+ { transform: `translate(${dx}px,${dy}px) scale(.06)`, opacity: 0.2, borderRadius: '50%' },
+ ],
+ { duration: 640, easing: 'cubic-bezier(.5,0,.2,1)' }
+ ).finished.then(() => {
+ clone.remove();
+ pop(target);
+ });
+ }
+
+ X.fly = fly;
+ X.pop = pop;
+
+ const favTab = () => $('#personalMenu summary');
+
+ // ---------- Batch Selection Mode ----------
+ const selectedKeys = new Set();
+ X.batchPicked = k => selectedKeys.has(k);
+ X.filterBatch = items => {
+ if (!selectedKeys.size) return;
+ const valid = new Set(items.map(it => it.k));
+ for (const k of selectedKeys) {
+ if (!valid.has(k)) selectedKeys.delete(k);
+ }
+ updateBatchBar();
+ };
+
+ function togglePick(k) {
+ if (selectedKeys.has(k)) selectedKeys.delete(k);
+ else selectedKeys.add(k);
+ updateBatchBar();
+ }
+
+ grid.addEventListener('click', e => {
+ const btn = e.target.closest('[data-a]');
+ const card = e.target.closest('.card');
+ if (!card) return;
+ const key = card.dataset.show || card.dataset.k;
+
+ if (document.body.classList.contains('batch')) {
+ e.preventDefault();
+ e.stopPropagation();
+ togglePick(key);
+ grid.querySelectorAll('.card').forEach(c =>
+ c.classList.toggle('picked', selectedKeys.has(c.dataset.show || c.dataset.k))
+ );
+ return;
+ }
+
+ if (btn && btn.dataset.a === 'fav') {
+ const adding = !A.st.fav.has(key);
+ const img = card.querySelector('img');
+ requestAnimationFrame(() => {
+ const nextBtn = grid.querySelector(`.card[data-k="${CSS.escape(card.dataset.k)}"] [data-a=fav]`);
+ if (adding) {
+ pop(nextBtn);
+ burst(nextBtn);
+ fly(img, favTab());
+ }
+ });
+ }
+
+ if (btn && btn.dataset.a === 'sel' && !$('#trayFab').hidden && !A.st.sel.includes(key)) {
+ fly(card.querySelector('img'), $('#trayFab'));
+ }
+ }, true);
+
+ const toolbar = $('.tbar');
+ const batchBtn = document.createElement('button');
+ batchBtn.className = 'fbtn';
+ batchBtn.id = 'batchBtn';
+ batchBtn.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>批量';
+ toolbar.querySelector('.sp').after(batchBtn);
+
+ const batchBar = document.createElement('div');
+ batchBar.id = 'bbar';
+ batchBar.hidden = true;
+ batchBar.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(batchBar);
+
+ function setBatchMode(on) {
+ document.body.classList.toggle('batch', on);
+ batchBar.querySelector('[data-b=fav]').hidden = A.st.tab === 'fav';
+ batchBar.querySelector('[data-b=unfav]').hidden = A.st.tab !== 'fav';
+ batchBar.hidden = !on;
+ batchBtn.classList.toggle('on', on);
+ batchBtn.setAttribute('aria-pressed', String(on));
+ if (!on) {
+ selectedKeys.clear();
+ $$('.card.picked').forEach(c => c.classList.remove('picked'));
+ }
+ updateBatchBar();
+ }
+
+ function updateBatchBar() {
+ $('#bbN').textContent = '已选 ' + selectedKeys.size;
+ batchBar.querySelectorAll('[data-b]:not([data-b=x]):not([data-b=all])').forEach(b => {
+ b.disabled = !selectedKeys.size;
+ });
+ }
+
+ batchBtn.onclick = () => setBatchMode(!document.body.classList.contains('batch'));
+
+ batchBar.onclick = async e => {
+ const target = e.target.closest('[data-b]');
+ if (!target) return;
+ const items = [...selectedKeys].map(k => A.ITEMS[k]).filter(Boolean);
+ const mode = target.dataset.b;
+
+ if (mode === 'x') return setBatchMode(false);
+ if (mode === 'all') {
+ A.st.list.forEach(it => selectedKeys.add(A.cardFace(it).k));
+ $$('#grid .card').forEach(c => c.classList.add('picked'));
+ return updateBatchBar();
+ }
+ if (mode === 'fav') {
+ let added = 0;
+ items.forEach(it => {
+ if (!A.st.fav.has(it.k)) {
+ A.st.fav.add(it.k);
+ added++;
+ }
+ });
+ SV('fav', [...A.st.fav]);
+ $('#nFav').textContent = A.st.fav.size;
+ pop(favTab());
+ A.toast(`已收藏 ${added} 项`);
+ setBatchMode(false);
+ A.apply();
+ return;
+ }
+ if (mode === 'unfav') {
+ items.forEach(it => A.st.fav.delete(it.k));
+ SV('fav', [...A.st.fav]);
+ const removedCount = items.length;
+ const removedKeys = items.map(i => i.k);
+ setBatchMode(false);
+ A.apply();
+ $('#nFav').textContent = A.st.fav.size || '';
+ A.toast(`已取消 ${removedCount} 项收藏`, () => {
+ removedKeys.forEach(k => A.st.fav.add(k));
+ SV('fav', [...A.st.fav]);
+ $('#nFav').textContent = A.st.fav.size;
+ A.apply();
+ });
+ return;
+ }
+ if (mode === 'zip') {
+ const local = items.filter(it => !it.ext);
+ if (!local.length) return A.toast(items.length ? '这些图片在原站,请前往原站查看' : '先选几张');
+ if (!window.makeZip) return;
+ target.disabled = true;
+ target.textContent = '打包中…';
+ try {
+ const files = [];
+ for (const it of local.slice(0, 60)) {
+ const resp = await fetch(A.big(it));
+ if (!resp.ok) throw Error(resp.status);
+ files.push({ name: `posewear-${it.type}-${it.id}.webp`, blob: await resp.blob() });
+ }
+ window.X.dl(await makeZip(files), `posewear-${A.st.tab}-${files.length}.zip`);
+ A.toast(
+ `已打包 ${files.length} 张` +
+ (local.length > 60 ? '(单次最多 60 张)' : '') +
+ (local.length < items.length ? ',外链图片请到原站查看' : '')
+ );
+ } catch {
+ A.toast('打包失败,请重试');
+ }
+ target.disabled = false;
+ target.textContent = '打包下载';
+ return;
+ }
+ if (mode === 'cp') {
+ A.copyBrief(items.map(it => A.prompt(it, A.st.lang)).join('\n'), items, A.st.lang, `${items.length} 条提示词`);
+ return;
+ }
+ if (mode === 'stu') {
+ if (await A.sendToStudio(items, true)) setBatchMode(false);
+ }
+ };
+
+ addEventListener('keydown', e => {
+ if (e.key === 'Escape' && document.body.classList.contains('batch')) setBatchMode(false);
+ });
+ X.closeBatch = () => {
+ if (document.body.classList.contains('batch')) setBatchMode(false);
+ };
+
+ // ---------- Search Suggestions ----------
+ const searchInput = $('#q');
+ const suggestBox = document.createElement('div');
+ suggestBox.id = 'qsug';
+ suggestBox.hidden = true;
+ searchInput.parentNode.append(suggestBox);
+
+ function renderSuggestions() {
+ const history = LS('qh') || [];
+ const value = searchInput.value.trim();
+ const hot = (A.suggestions[A.st.tab] || []).filter(x => !value || x.includes(value));
+ const recentHtml =
+ history.length && !value
+ ? `<div class="sgh"><small>最近搜索</small><button data-clr>清除</button></div>` +
+ `<div class="sgc">${history.map(x => `<button data-q="${A.esc(x)}">${A.esc(x)}</button>`).join('')}</div>`
+ : '';
+ const hotHtml = 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>`
+ : '';
+ suggestBox.innerHTML = recentHtml + hotHtml;
+ suggestBox.hidden = !suggestBox.innerHTML;
+ }
+
+ const saveSearchQuery = () => {
+ const value = searchInput.value.trim();
+ if (value.length < 1) return;
+ SV('qh', [value, ...(LS('qh') || []).filter(x => x !== value)].slice(0, 8));
+ };
+
+ searchInput.addEventListener('focus', renderSuggestions);
+ searchInput.addEventListener('input', () => {
+ renderSuggestions();
+ clearTimeout(searchInput._h);
+ searchInput._h = setTimeout(saveSearchQuery, 1500);
+ });
+ searchInput.addEventListener('keydown', e => {
+ if (e.key === 'Enter') {
+ saveSearchQuery();
+ suggestBox.hidden = true;
+ searchInput.blur();
+ }
+ });
+ searchInput.parentNode.addEventListener('focusout', e => {
+ if (!searchInput.parentNode.contains(e.relatedTarget)) suggestBox.hidden = true;
+ });
+ searchInput.parentNode.addEventListener('keydown', e => {
+ if (e.key === 'Escape' && !suggestBox.hidden) {
+ e.stopPropagation();
+ searchInput.focus();
+ suggestBox.hidden = true;
+ }
+ });
+ suggestBox.addEventListener('mousedown', e => e.preventDefault());
+ suggestBox.onclick = e => {
+ const btn = e.target.closest('button');
+ if (!btn) return;
+ if (btn.dataset.clr != null) {
+ SV('qh', []);
+ return renderSuggestions();
+ }
+ searchInput.focus();
+ searchInput.value = btn.dataset.q;
+ searchInput.dispatchEvent(new Event('input'));
+ saveSearchQuery();
+ suggestBox.hidden = true;
+ };
+
+ // ---------- Result Count Animation ----------
+ const countEl = $('#count');
+ new MutationObserver(() => {
+ if (!motionPreference.matches) {
+ countEl.animate([{ opacity: 0.2, transform: 'translateY(4px)' }, { opacity: 1, transform: 'none' }], {
+ duration: 360,
+ easing: EZ,
+ });
+ }
+ }).observe(countEl, { childList: true, characterData: true, subtree: true });
+
+ // ---------- Lightbox Similar Recommendations / Download / Copy Image ----------
+ const COLOR_CHARS = /[黑白红粉蓝灰绿黄紫金银棕米]/g;
+ X.lb = it => {
+ const list = A.st.list;
+ const cols = new Set((it.zh || '').match(COLOR_CHARS) || []);
+ const score = candidate =>
+ it.type === 'portrait'
+ ? (candidate.len === it.len ? 2 : 0) + (candidate.st && candidate.st === it.st ? 4 : 0) + (candidate.sec === it.sec ? 1 : 0)
+ : (candidate.cat === it.cat ? 3 : 0) +
+ (candidate.line && candidate.line === it.line ? 1 : 0) +
+ ((candidate.zh || '').match(COLOR_CHARS) || []).filter(c => cols.has(c)).length;
+
+ const similar = list
+ .map((item, index) => [item, index])
+ .filter(([item]) => item.k !== it.k && item.type === it.type)
+ .map(([item, index]) => [item, index, score(item) + Math.random() * 0.5])
+ .sort((a, b) => b[2] - a[2])
+ .slice(0, 8);
+
+ const slot = $('#lbSim');
+ if (!slot) return;
+ slot.innerHTML = similar.length
+ ? `<small class="simh">相似推荐</small><div class="sim">${similar
+ .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 fetchCurrentBlob() {
+ const it = A.previewItem();
+ const resp = await fetch(A.big(it));
+ if (!resp.ok) throw Error(resp.status);
+ return [await resp.blob(), it];
+ }
+
+ $('#lbSide').addEventListener('click', async e => {
+ const btn = e.target.closest('button');
+ if (!btn) return;
+ if (btn.dataset.si) {
+ A.lbOpen(+btn.dataset.si);
+ if (!motionPreference.matches) {
+ $('#lbImg').animate([{ opacity: 0, transform: 'scale(.97)' }, { opacity: 1, transform: 'none' }], {
+ duration: 340,
+ easing: EZ,
+ });
+ }
+ return;
+ }
+ if (btn.dataset.x === 'dlx') {
+ try {
+ const [blob, it] = await fetchCurrentBlob();
+ dl(blob, `posewear-${it.type}-${it.id}.webp`);
+ A.toast('已开始下载');
+ } catch {
+ A.toast('下载失败');
+ }
+ return;
+ }
+ if (btn.dataset.x === 'cpimg') {
+ try {
+ const [blob] = await fetchCurrentBlob();
+ const bitmap = await createImageBitmap(blob);
+ const canvas = document.createElement('canvas');
+ canvas.width = bitmap.width;
+ canvas.height = bitmap.height;
+ canvas.getContext('2d').drawImage(bitmap, 0, 0);
+ const png = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })]);
+ A.toast('图片已复制到剪贴板');
+ } catch {
+ A.toast('当前浏览器不支持复制图片');
+ }
+ }
+ });
+
+ // ---------- Random Pick Card Riffle Animation ----------
+ const randBtn = $('#rand');
+ if (randBtn) {
+ randBtn.addEventListener('click', () => {
+ if (motionPreference.matches) return;
+ const cards = [...$$('#grid .card')]
+ .filter(c => {
+ const r = c.getBoundingClientRect();
+ return r.top < innerHeight && r.bottom > 0;
+ })
+ .slice(0, 12);
+ cards.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);
+ }
+
+ // ---------- Service Worker Update Notice ----------
+ if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
+ navigator.serviceWorker.addEventListener('controllerchange', () => {
+ $('#noticeReload').hidden = false;
+ });
+ $('#noticeReload').onclick = () => location.reload();
+ }
})();
diff --git a/src/index.html b/src/index.html
index 6d29734..31002c6 100644
--- a/src/index.html
+++ b/src/index.html
@@ -1,164 +1,947 @@
-<!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="衣姿 PoseWear:姿势、服装、人像参考图库,附中英文提示词,可上传照片试穿,也可在图库里直接生图。">
-<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{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>
-<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 type="button" id="qKbd" class="q-kbd" title="命令面板(⌘K / Ctrl+K)" aria-label="打开命令面板">⌘K</button><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="officialNotice"><strong>安全提醒</strong><p>唯一官网是 posewear.pages.dev,免费、无需注册账号、没有收费套餐。本项目没有 Windows / Android 客户端;冒充官网提供 exe / apk 下载、或要求登录付费的站点(如 posewear.cn、posewear.art)与本项目无关,请勿下载、登录、付款或在其中填写 API Key。</p></article><article id="releaseNotice"><strong>图库更新</strong><p>新增速写定时练习、大图灰度与实拍取色板、画板导出拼图 PNG 及 ⌘K 命令面板。</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" 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="sketchBtn" class="sm ghost" type="button" hidden title="速写练习(定时切换参考图)" aria-label="速写练习"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="13" r="7.5"/><path d="M12 9.5v4l2.5 1.5M9.5 3h5M12 3v2.5"/></svg><span>速写</span></button>
-<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>
-<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">
-<header class="studio-head"><h1 id="stT" tabindex="-1">创作工作台</h1><div class="studio-head-act"><button id="wbClearAll" class="sm ghost" type="button" hidden>清空素材</button><div class="seg modes" role="group" aria-label="工作模式"><button data-mode="tryon">试穿</button><button data-mode="gen">生图</button></div></div></header>
-<div class="st-app">
-<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 garment-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" aria-labelledby="wbCanvasTitle"><header class="canvas-head"><h2 id="wbCanvasTitle">参考画板</h2><div id="wbCanvasSwitch" class="seg sm" role="group" aria-label="画板视图" hidden><button type="button" data-cv="board" aria-pressed="false">参考画板</button><button type="button" data-cv="result" class="on" aria-pressed="true">生成结果</button></div><button id="wbExportBoard" class="sm ghost" type="button" hidden title="导出参考拼图 PNG">导出拼图</button><span id="wbCanvasRatio"></span></header>
-<div class="stage" id="wbStage"><div class="reference-board" id="wbPh0"><div class="board-cards" id="wbBoardCards"></div><div class="board-actions" id="wbBoardActions" hidden><button id="wbShuffle" type="button" class="board-use board-shuffle">换一组</button><button id="wbExample" type="button" class="board-use">使用这组参考</button></div></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><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>
-<div class="row out-act" id="wbOutAct" hidden><button class="sm" id="wbDl">下载</button><button class="sm" id="wbZip" hidden>全部打包</button><button class="sm" id="wbAgain">重来</button><button class="sm" id="wbUse">当原图</button><button class="sm ghost" id="wbCmpT">对比</button><span class="sp"></span><small id="wbMeta"></small></div>
-</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="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>
-<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></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 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-bar" id="pkBar" hidden><button type="button" id="pkFavOnly" class="chip" aria-pressed="false" hidden>仅看收藏</button><div class="pk-cats" id="pkCats" role="group" aria-label="分类筛选"></div></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>
-
-<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>直连时,浏览器将密钥和图片发给填写的地址;启用本站代理后经本站转发。http/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>
-<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><div class="dock-heading-tools"><button id="tgResetPrompt" class="sm ghost" type="button" hidden title="恢复自动提示词">重置</button><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></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"><div class="lb-stage" id="lbStage"><img id="lbImg" alt="" referrerpolicy="no-referrer"><div class="lb-pair-cmp" id="lbPairCmp" hidden><img id="lbPairImg" alt="" referrerpolicy="no-referrer"></div><div class="lb-pair-hdl" id="lbPairHdl" hidden><span></span></div><input type="range" id="lbPairRange" min="0" max="100" value="50" aria-label="线稿与深度图对比" hidden><div class="lb-grid" id="lbGrid" aria-hidden="true"></div></div><div class="lb-tools" id="lbTools" role="toolbar" aria-label="参考查看工具" hidden><button type="button" data-lt="zoom" aria-pressed="false" title="缩放(Z)"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="6.5"/><path d="m20 20-4.2-4.2M11 8v6M8 11h6"/></svg><span>2×</span></button><button type="button" data-lt="flip" aria-pressed="false" title="镜像翻转(H)"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v16M8 7 4 12l4 5V7zm8 0 4 5-4 5V7z"/></svg><span>镜像</span></button><button type="button" data-lt="grid" aria-pressed="false" title="构图参考线(G)"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="4" width="16" height="16" rx="2"/><path d="M9.5 4v16M14.5 4v16M4 9.5h16M4 14.5h16"/></svg><span>参考线</span></button><button type="button" data-lt="gray" aria-pressed="false" title="灰度明度检查(B)"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="8"/><path d="M12 4a8 8 0 0 1 0 16Z" fill="currentColor" stroke="none"/></svg><span>灰度</span></button><button type="button" data-lt="cmp" aria-pressed="false" title="线稿与深度图对比(V)" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="5" width="16" height="14" rx="2"/><path d="M12 3v18M8 10l-2 2 2 2m8-4 2 2-2 2"/></svg><span>透视对比</span></button></div><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-modal="true" aria-label="快捷键"><div class="hb"><h3>快捷键</h3><dl><dt><kbd>⌘K</kbd></dt><dd>命令面板</dd><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>Z</kbd></dt><dd>大图:缩放细节</dd><dt><kbd>H</kbd></dt><dd>大图:镜像翻转</dd><dt><kbd>G</kbd></dt><dd>大图:构图参考线</dd><dt><kbd>B</kbd></dt><dd>大图:灰度明度检查</dd><dt><kbd>V</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>
-<div class="hist-bar" id="histBar"><div class="tbar">
-<span id="histCount" aria-live="polite"></span>
-<div class="seg sm" id="histFilter" role="group" aria-label="筛选模式"><button type="button" data-hf="all" class="on" aria-pressed="true">全部</button><button type="button" data-hf="tryon" aria-pressed="false">试穿</button><button type="button" data-hf="gen" aria-pressed="false">生图</button></div>
-<input id="histQ" type="search" placeholder="搜索提示词或模型…" aria-label="搜索生成记录" autocomplete="off">
-<label class="hist-sel-all"><input type="checkbox" id="histSelAll"><span>全选</span></label>
-<span id="histSelN" hidden>已选 <b>0</b> 张</span>
-<span class="sp"></span>
-<button id="histZip" class="sm" disabled>打包下载</button>
-<button id="histExp" class="sm" disabled>导出 ZIP</button>
-<button id="histClr" class="sm ghost">清空</button>
-</div></div>
-<div id="histStats" class="hist-stats"></div>
-<main id="histGrid" class="grid hist-grid" aria-live="polite"></main>
-<div id="histEmpty" hidden><div class="emo" aria-hidden="true"><svg viewBox="0 0 24 24"><rect x="3.5" y="4.5" width="17" height="15" rx="3"/><path d="m7 15.5 3.3-3.5 2.4 2.4 2-2 2.3 2.6"/><circle cx="9" cy="9" r="1.4"/></svg></div><h3>还没有生成记录</h3><p>在工作台或悬浮创作台生成的图片会保存在这里</p><button class="pri sm" data-go="studio">打开工作台</button></div>
-</section>
-<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>:本站代理只转发图片生成接口请求,不转发到内网地址。接收方会收到凭据和图片,请选择可信服务。</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>
-<div id="sketch" hidden role="dialog" aria-modal="true" aria-label="速写练习">
-<div class="sk-prog" aria-hidden="true"><i id="skProg"></i></div>
-<header class="sk-top">
-<div class="sk-meta"><b id="skStep">1 / 10</b><span id="skName"></span></div>
-<div class="sk-timer-box"><span id="skTime">01:00</span><div class="seg sm" id="skDur" role="group" aria-label="每张时长"><button type="button" data-sd="30">30s</button><button type="button" data-sd="60" class="on" aria-pressed="true">60s</button><button type="button" data-sd="120">2m</button><button type="button" data-sd="300">5m</button></div><div class="seg sm" id="skTotal" role="group" aria-label="练习张数"><button type="button" data-sc="5">5张</button><button type="button" data-sc="10" class="on" aria-pressed="true">10张</button><button type="button" data-sc="20">20张</button><button type="button" data-sc="0">无限</button></div></div>
-<div class="sk-right"><button type="button" id="skSound" class="icon" aria-pressed="false" title="提示音" aria-label="提示音"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M11 5 6 9H3v6h3l5 4V5z"/><path class="sk-snd-on" d="M15.5 8.5a5 5 0 0 1 0 7M18.5 6a8.5 8.5 0 0 1 0 12"/><path class="sk-snd-off" d="m16 9 5 6m0-6-5 6"/></svg></button><button type="button" id="skClose" class="icon" title="结束速写(Esc)" aria-label="结束速写">✕</button></div>
-</header>
-<div class="sk-stage" id="skStage">
-<div class="sk-frame" id="skFrame"><img id="skImg" alt="" referrerpolicy="no-referrer"><div class="lb-grid" id="skGrid" aria-hidden="true"></div></div>
-<div class="sk-done" id="skDone" hidden><h3>本轮速写完成</h3><p id="skSummary"></p><div class="sk-recap" id="skRecap"></div><div class="sk-done-act"><button type="button" id="skAgain" class="pri">再来一轮</button><button type="button" id="skExit">返回图库</button></div></div>
-</div>
-<footer class="sk-foot">
-<div class="sk-ctrl"><button type="button" id="skPrev" title="上一张(←)" aria-label="上一张">‹</button><button type="button" id="skPause" class="pri" title="暂停或继续(空格)">暂停</button><button type="button" id="skNext" title="下一张(→)" aria-label="下一张">›</button></div>
-<div class="sk-tools" role="toolbar" aria-label="速写辅助工具"><button type="button" data-skt="flip" aria-pressed="false" title="镜像翻转(H)">镜像</button><button type="button" data-skt="grid" aria-pressed="false" title="构图参考线(G)">参考线</button><button type="button" data-skt="gray" aria-pressed="false" title="灰度明度检查(B)">灰度</button><button type="button" data-skt="pair" aria-pressed="false" title="切换线稿与深度图(V)" hidden>深度图</button><button type="button" data-skt="fav" aria-pressed="false" title="收藏当前(F)">♡ 收藏</button></div>
-</footer>
-</div>
-<div id="cmdPal" hidden role="dialog" aria-modal="true" aria-label="命令面板">
-<div class="cmd-box">
-<div class="cmd-in"><svg 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="cmdQ" type="search" placeholder="跳转素材库、搜索或执行命令…" autocomplete="off" aria-label="搜索命令或素材库"><kbd>Esc</kbd></div>
-<div class="cmd-list" id="cmdList" role="listbox"></div>
-<div class="cmd-foot"><span><kbd>↑</kbd><kbd>↓</kbd> 选择</span><span><kbd>↵</kbd> 执行</span><span><kbd>Esc</kbd> 关闭</span></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>
+<!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="衣姿 PoseWear:姿势、服装、人像参考图库,附中英文提示词,可上传照片试穿,也可在图库里直接生图。">
+ <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{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>
+
+ <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 type="button" id="qKbd" class="q-kbd" title="命令面板(⌘K / Ctrl+K)" aria-label="打开命令面板">⌘K</button>
+ <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="officialNotice">
+ <strong>安全提醒</strong>
+ <p>唯一官网是 posewear.pages.dev,免费、无需注册账号、没有收费套餐。本项目没有 Windows / Android 客户端;冒充官网提供 exe / apk 下载、或要求登录付费的站点(如 posewear.cn、posewear.art)与本项目无关,请勿下载、登录、付款或在其中填写 API Key。</p>
+ </article>
+ <article id="releaseNotice">
+ <strong>图库更新</strong>
+ <p>新增速写定时练习、大图灰度与实拍取色板、画板导出拼图 PNG 及 ⌘K 命令面板。</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" 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="sketchBtn" class="sm ghost" type="button" hidden title="速写练习(定时切换参考图)" aria-label="速写练习">
+ <svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="13" r="7.5"/><path d="M12 9.5v4l2.5 1.5M9.5 3h5M12 3v2.5"/></svg>
+ <span>速写</span>
+ </button>
+ <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>
+
+ <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>
+
+ <!-- Full Creative Studio -->
+ <section id="studio" hidden aria-labelledby="stT">
+ <header class="studio-head">
+ <h1 id="stT" tabindex="-1">创作工作台</h1>
+ <div class="studio-head-act">
+ <button id="wbClearAll" class="sm ghost" type="button" hidden>清空素材</button>
+ <div class="seg modes" role="group" aria-label="工作模式">
+ <button data-mode="tryon">试穿</button>
+ <button data-mode="gen">生图</button>
+ </div>
+ </div>
+ </header>
+
+ <div class="st-app">
+ <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 garment-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" aria-labelledby="wbCanvasTitle">
+ <header class="canvas-head">
+ <h2 id="wbCanvasTitle">参考画板</h2>
+ <div id="wbCanvasSwitch" class="seg sm" role="group" aria-label="画板视图" hidden>
+ <button type="button" data-cv="board" aria-pressed="false">参考画板</button>
+ <button type="button" data-cv="result" class="on" aria-pressed="true">生成结果</button>
+ </div>
+ <button id="wbExportBoard" class="sm ghost" type="button" hidden title="导出参考拼图 PNG">导出拼图</button>
+ <span id="wbCanvasRatio"></span>
+ </header>
+
+ <div class="stage" id="wbStage">
+ <div class="reference-board" id="wbPh0">
+ <div class="board-cards" id="wbBoardCards"></div>
+ <div class="board-actions" id="wbBoardActions" hidden>
+ <button id="wbShuffle" type="button" class="board-use board-shuffle">换一组</button>
+ <button id="wbExample" type="button" class="board-use">使用这组参考</button>
+ </div>
+ </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>
+ <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>
+ <div class="row out-act" id="wbOutAct" hidden>
+ <button class="sm" id="wbDl">下载</button>
+ <button class="sm" id="wbZip" hidden>全部打包</button>
+ <button class="sm" id="wbAgain">重来</button>
+ <button class="sm" id="wbUse">当原图</button>
+ <button class="sm ghost" id="wbCmpT">对比</button>
+ <span class="sp"></span>
+ <small id="wbMeta"></small>
+ </div>
+ </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="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>
+
+ <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></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>
+
+ <!-- Material Picker Dialog -->
+ <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-bar" id="pkBar" hidden>
+ <button type="button" id="pkFavOnly" class="chip" aria-pressed="false" hidden>仅看收藏</button>
+ <div class="pk-cats" id="pkCats" role="group" aria-label="分类筛选"></div>
+ </div>
+ <div class="pk-g" id="pkG"></div>
+ </div>
+ </div>
+
+ <!-- Provider & Local Engine Settings Dialog -->
+ <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>
+
+ <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>直连时,浏览器将密钥和图片发给填写的地址;启用本站代理后经本站转发。http/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>
+
+ <!-- Floating Workspace Dock -->
+ <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>
+ <div class="dock-heading-tools">
+ <button id="tgResetPrompt" class="sm ghost" type="button" hidden title="恢复自动提示词">重置</button>
+ <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>
+ </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>
+
+ <!-- Quick Result Viewer -->
+ <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>
+
+ <!-- Lightbox -->
+ <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">
+ <div class="lb-stage" id="lbStage">
+ <img id="lbImg" alt="" referrerpolicy="no-referrer">
+ <div class="lb-pair-cmp" id="lbPairCmp" hidden><img id="lbPairImg" alt="" referrerpolicy="no-referrer"></div>
+ <div class="lb-pair-hdl" id="lbPairHdl" hidden><span></span></div>
+ <input type="range" id="lbPairRange" min="0" max="100" value="50" aria-label="线稿与深度图对比" hidden>
+ <div class="lb-grid" id="lbGrid" aria-hidden="true"></div>
+ </div>
+ <div class="lb-tools" id="lbTools" role="toolbar" aria-label="参考查看工具" hidden>
+ <button type="button" data-lt="zoom" aria-pressed="false" title="缩放(Z)">
+ <svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="6.5"/><path d="m20 20-4.2-4.2M11 8v6M8 11h6"/></svg><span>2×</span>
+ </button>
+ <button type="button" data-lt="flip" aria-pressed="false" title="镜像翻转(H)">
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v16M8 7 4 12l4 5V7zm8 0 4 5-4 5V7z"/></svg><span>镜像</span>
+ </button>
+ <button type="button" data-lt="grid" aria-pressed="false" title="构图参考线(G)">
+ <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="4" width="16" height="16" rx="2"/><path d="M9.5 4v16M14.5 4v16M4 9.5h16M4 14.5h16"/></svg><span>参考线</span>
+ </button>
+ <button type="button" data-lt="gray" aria-pressed="false" title="灰度明度检查(B)">
+ <svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="8"/><path d="M12 4a8 8 0 0 1 0 16Z" fill="currentColor" stroke="none"/></svg><span>灰度</span>
+ </button>
+ <button type="button" data-lt="cmp" aria-pressed="false" title="线稿与深度图对比(V)" hidden>
+ <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="5" width="16" height="14" rx="2"/><path d="M12 3v18M8 10l-2 2 2 2m8-4 2 2-2 2"/></svg><span>透视对比</span>
+ </button>
+ </div>
+ <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>
+
+ <!-- Keyboard Shortcuts Dialog -->
+ <div id="helpBox" hidden role="dialog" aria-modal="true" aria-label="快捷键">
+ <div class="hb">
+ <h3>快捷键</h3>
+ <dl>
+ <dt><kbd>⌘K</kbd></dt><dd>命令面板</dd>
+ <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>Z</kbd></dt><dd>大图:缩放细节</dd>
+ <dt><kbd>H</kbd></dt><dd>大图:镜像翻转</dd>
+ <dt><kbd>G</kbd></dt><dd>大图:构图参考线</dd>
+ <dt><kbd>B</kbd></dt><dd>大图:灰度明度检查</dd>
+ <dt><kbd>V</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>
+
+ <!-- Generation History Section -->
+ <section id="histSec" hidden aria-labelledby="histSecT">
+ <h2 id="histSecT" class="vh">生成记录</h2>
+ <div class="hist-bar" id="histBar">
+ <div class="tbar">
+ <span id="histCount" aria-live="polite"></span>
+ <div class="seg sm" id="histFilter" role="group" aria-label="筛选模式">
+ <button type="button" data-hf="all" class="on" aria-pressed="true">全部</button>
+ <button type="button" data-hf="tryon" aria-pressed="false">试穿</button>
+ <button type="button" data-hf="gen" aria-pressed="false">生图</button>
+ </div>
+ <input id="histQ" type="search" placeholder="搜索提示词或模型…" aria-label="搜索生成记录" autocomplete="off">
+ <label class="hist-sel-all"><input type="checkbox" id="histSelAll"><span>全选</span></label>
+ <span id="histSelN" hidden>已选 <b>0</b> 张</span>
+ <span class="sp"></span>
+ <button id="histZip" class="sm" disabled>打包下载</button>
+ <button id="histExp" class="sm" disabled>导出 ZIP</button>
+ <button id="histClr" class="sm ghost">清空</button>
+ </div>
+ </div>
+ <div id="histStats" class="hist-stats"></div>
+ <main id="histGrid" class="grid hist-grid" aria-live="polite"></main>
+ <div id="histEmpty" hidden>
+ <div class="emo" aria-hidden="true">
+ <svg viewBox="0 0 24 24"><rect x="3.5" y="4.5" width="17" height="15" rx="3"/><path d="m7 15.5 3.3-3.5 2.4 2.4 2-2 2.3 2.6"/><circle cx="9" cy="9" r="1.4"/></svg>
+ </div>
+ <h3>还没有生成记录</h3>
+ <p>在工作台或悬浮创作台生成的图片会保存在这里</p>
+ <button class="pri sm" data-go="studio">打开工作台</button>
+ </div>
+ </section>
+
+ <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>
+
+ <!-- Age Confirmation Modal -->
+ <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>
+
+ <!-- Privacy Modal -->
+ <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>:站点部署者可以开启 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>
+
+ <!-- Gesture Drawing Studio -->
+ <div id="sketch" hidden role="dialog" aria-modal="true" aria-label="速写练习">
+ <div class="sk-prog" aria-hidden="true"><i id="skProg"></i></div>
+ <header class="sk-top">
+ <div class="sk-meta"><b id="skStep">1 / 10</b><span id="skName"></span></div>
+ <div class="sk-timer-box">
+ <span id="skTime">01:00</span>
+ <div class="seg sm" id="skDur" role="group" aria-label="每张时长">
+ <button type="button" data-sd="30">30s</button>
+ <button type="button" data-sd="60" class="on" aria-pressed="true">60s</button>
+ <button type="button" data-sd="120">2m</button>
+ <button type="button" data-sd="300">5m</button>
+ </div>
+ <div class="seg sm" id="skTotal" role="group" aria-label="练习张数">
+ <button type="button" data-sc="5">5张</button>
+ <button type="button" data-sc="10" class="on" aria-pressed="true">10张</button>
+ <button type="button" data-sc="20">20张</button>
+ <button type="button" data-sc="0">无限</button>
+ </div>
+ </div>
+ <div class="sk-right">
+ <button type="button" id="skSound" class="icon" aria-pressed="false" title="提示音" aria-label="提示音">
+ <svg viewBox="0 0 24 24" aria-hidden="true">
+ <path d="M11 5 6 9H3v6h3l5 4V5z"/>
+ <path class="sk-snd-on" d="M15.5 8.5a5 5 0 0 1 0 7M18.5 6a8.5 8.5 0 0 1 0 12"/>
+ <path class="sk-snd-off" d="m16 9 5 6m0-6-5 6"/>
+ </svg>
+ </button>
+ <button type="button" id="skClose" class="icon" title="结束速写(Esc)" aria-label="结束速写">✕</button>
+ </div>
+ </header>
+ <div class="sk-stage" id="skStage">
+ <div class="sk-frame" id="skFrame">
+ <img id="skImg" alt="" referrerpolicy="no-referrer">
+ <div class="lb-grid" id="skGrid" aria-hidden="true"></div>
+ </div>
+ <div class="sk-done" id="skDone" hidden>
+ <h3>本轮速写完成</h3>
+ <p id="skSummary"></p>
+ <div class="sk-recap" id="skRecap"></div>
+ <div class="sk-done-act">
+ <button type="button" id="skAgain" class="pri">再来一轮</button>
+ <button type="button" id="skExit">返回图库</button>
+ </div>
+ </div>
+ </div>
+ <footer class="sk-foot">
+ <div class="sk-ctrl">
+ <button type="button" id="skPrev" title="上一张(←)" aria-label="上一张">‹</button>
+ <button type="button" id="skPause" class="pri" title="暂停或继续(空格)">暂停</button>
+ <button type="button" id="skNext" title="下一张(→)" aria-label="下一张">›</button>
+ </div>
+ <div class="sk-tools" role="toolbar" aria-label="速写辅助工具">
+ <button type="button" data-skt="flip" aria-pressed="false" title="镜像翻转(H)">镜像</button>
+ <button type="button" data-skt="grid" aria-pressed="false" title="构图参考线(G)">参考线</button>
+ <button type="button" data-skt="gray" aria-pressed="false" title="灰度明度检查(B)">灰度</button>
+ <button type="button" data-skt="pair" aria-pressed="false" title="切换线稿与深度图(V)" hidden>深度图</button>
+ <button type="button" data-skt="fav" aria-pressed="false" title="收藏当前(F)">♡ 收藏</button>
+ </div>
+ </footer>
+ </div>
+
+ <!-- Global Command Palette -->
+ <div id="cmdPal" hidden role="dialog" aria-modal="true" aria-label="命令面板">
+ <div class="cmd-box">
+ <div class="cmd-in">
+ <svg 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="cmdQ" type="search" placeholder="跳转素材库、搜索或执行命令…" autocomplete="off" aria-label="搜索命令或素材库">
+ <kbd>Esc</kbd>
+ </div>
+ <div class="cmd-list" id="cmdList" role="listbox"></div>
+ <div class="cmd-foot">
+ <span><kbd>↑</kbd><kbd>↓</kbd> 选择</span>
+ <span><kbd>↵</kbd> 执行</span>
+ <span><kbd>Esc</kbd> 关闭</span>
+ </div>
+ </div>
+ </div>
+
+ <script src="i18n.js" defer></script>
+ <script src="catalog.js" defer></script>
+ <script src="references.js" defer></script>
+ <script src="palette.js" defer></script>
+ <script src="app.js" defer></script>
+ <script src="sketch.js" defer></script>
+ <script src="command-palette.js" defer></script>
+ <script src="zip.js" defer></script>
+ <script src="extras.js" defer></script>
+ <script src="image-providers.js" defer></script>
+ <script src="board-export.js" defer></script>
+ <script src="studio.js" defer></script>
+ <script src="history.js" defer></script>
+</body>
+</html>
diff --git a/src/palette.js b/src/palette.js
new file mode 100644
index 0000000..d9ffbe6
--- /dev/null
+++ b/src/palette.js
@@ -0,0 +1,94 @@
+'use strict';
+(() => {
+ // Real-time color palette extractor for color reference images in the lightbox.
+ // Samples the image into a 48x48 offscreen canvas with center-subject bias and
+ // saturation weighting so garment/subject tones outrank neutral studio backdrops.
+ function extract(img) {
+ if (!img || !img.complete || !img.naturalWidth) return [];
+ try {
+ const size = 48;
+ const canvas = document.createElement('canvas');
+ canvas.width = size;
+ canvas.height = size;
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ ctx.drawImage(img, 0, 0, size, size);
+ const data = ctx.getImageData(0, 0, size, size).data;
+
+ const bucketsMap = new Map();
+ for (let p = 0; p < size * size; p++) {
+ const i = p * 4;
+ const r = data[i];
+ const g = data[i + 1];
+ const b = data[i + 2];
+ const a = data[i + 3];
+ if (a < 200) continue;
+ if (r > 242 && g > 242 && b > 242) continue;
+
+ const x = p % size;
+ const y = (p / size) | 0;
+ const centerWeight = (x >= 7 && x <= 40 && y >= 4 && y <= 44) ? 1.8 : 0.25;
+ const qr = Math.min(240, Math.round(r / 16) * 16);
+ const qg = Math.min(240, Math.round(g / 16) * 16);
+ const qb = Math.min(240, Math.round(b / 16) * 16);
+ const max = Math.max(r, g, b);
+ const min = Math.min(r, g, b);
+ const sat = max ? (max - min) / max : 0;
+ const weight = (0.35 + sat * 4.5) * centerWeight;
+ const key = (qr << 16) | (qg << 8) | qb;
+
+ const cur = bucketsMap.get(key);
+ if (cur) {
+ cur.w += weight;
+ cur.r += r * weight;
+ cur.g += g * weight;
+ cur.b += b * weight;
+ } else {
+ bucketsMap.set(key, { w: weight, r: r * weight, g: g * weight, b: b * weight });
+ }
+ }
+
+ const ranked = [...bucketsMap.values()]
+ .sort((a, b) => b.w - a.w)
+ .map(x => [Math.round(x.r / x.w), Math.round(x.g / x.w), Math.round(x.b / x.w)]);
+
+ const chosen = [];
+ for (const rgb of ranked) {
+ if (chosen.every(o => Math.hypot(o[0] - rgb[0], o[1] - rgb[1], o[2] - rgb[2]) >= 44)) {
+ chosen.push(rgb);
+ if (chosen.length >= 5) break;
+ }
+ }
+
+ return chosen.map(([r, g, b]) =>
+ '#' + [r, g, b].map(v => v.toString(16).padStart(2, '0')).join('').toUpperCase()
+ );
+ } catch {
+ return [];
+ }
+ }
+
+ function render(box, img, item, isActive) {
+ if (!box || !item || item.type === 'pose' || item.type === 'depth' || item.ext) {
+ if (box) box.hidden = true;
+ return;
+ }
+ const paint = () => {
+ if (!box.isConnected || !isActive() || img.classList.contains('lo')) return;
+ const colors = extract(img);
+ if (colors.length < 2) {
+ box.hidden = true;
+ return;
+ }
+ const chips = colors
+ .map(hex => `<button type="button" class="pal-sw" data-hex="${hex}" style="--sw:${hex}" title="复制 ${hex}"><i></i><span>${hex}</span></button>`)
+ .join('');
+ box.innerHTML = `<div class="lb-pal-h"><small>提取配色</small><small class="mu">点击复制</small></div><div class="lb-pal-sw">${chips}</div>`;
+ box.hidden = false;
+ };
+
+ if (img.complete && img.naturalWidth && !img.classList.contains('lo')) paint();
+ else img.addEventListener('load', paint, { once: true });
+ }
+
+ window.PoseWearPalette = { extract, render };
+})();
diff --git a/src/sketch.js b/src/sketch.js
new file mode 100644
index 0000000..6bb9ad4
--- /dev/null
+++ b/src/sketch.js
@@ -0,0 +1,382 @@
+'use strict';
+(() => {
+ // Fullscreen Gesture Drawing Practice Studio (#sketch).
+ // Reuses the currently filtered gallery pool with configurable timer, count,
+ // gentle Web Audio chime, mirror/grid/grayscale/depth-flip study tools, and
+ // an end-of-session clickable recap contact sheet.
+ const C = window.PoseWearCatalog;
+ if (!C) return;
+ const { $, $$, esc, shuffle } = C;
+
+ const state = {
+ open: false,
+ dur: 60,
+ total: 10,
+ pool: [],
+ deck: [],
+ i: 0,
+ seen: [],
+ rem: 60,
+ last: 0,
+ paused: false,
+ sound: false,
+ flip: false,
+ grid: 0,
+ gray: false,
+ pair: false,
+ timer: null,
+ actx: null,
+ beeped: 0,
+ prevFocus: null,
+ };
+
+ let app = null;
+
+ function chime(freq = 660, duration = 0.12) {
+ if (!state.sound) return;
+ try {
+ const AudioCtx = window.AudioContext || window.webkitAudioContext;
+ if (!AudioCtx) return;
+ state.actx ||= new AudioCtx();
+ if (state.actx.state === 'suspended') state.actx.resume();
+ const osc = state.actx.createOscillator();
+ const gain = state.actx.createGain();
+ osc.type = 'sine';
+ osc.frequency.value = freq;
+ gain.gain.setValueAtTime(0.0001, state.actx.currentTime);
+ gain.gain.exponentialRampToValueAtTime(0.08, state.actx.currentTime + 0.015);
+ gain.gain.exponentialRampToValueAtTime(0.0001, state.actx.currentTime + duration);
+ osc.connect(gain);
+ gain.connect(state.actx.destination);
+ osc.start();
+ osc.stop(state.actx.currentTime + duration + 0.02);
+ } catch {}
+ }
+
+ function formatTime(sec) {
+ const s = Math.max(0, Math.ceil(sec));
+ return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
+ }
+
+ function sessionCap() {
+ return state.total ? Math.min(state.total, state.deck.length) : 0;
+ }
+
+ function renderTools() {
+ const it = state.deck[state.i];
+ const frame = $('#skFrame');
+ const gridEl = $('#skGrid');
+ if (frame) {
+ frame.classList.toggle('flipped', state.flip);
+ frame.classList.toggle('gray', state.gray);
+ }
+ if (gridEl) gridEl.dataset.mode = ['', 'thirds', 'cross'][state.grid] || '';
+
+ const setActive = (key, on) => {
+ const btn = $(`#sketch [data-skt="${key}"]`);
+ if (!btn) return;
+ btn.classList.toggle('on', !!on);
+ btn.setAttribute('aria-pressed', String(!!on));
+ };
+ setActive('flip', state.flip);
+ setActive('grid', state.grid > 0);
+ setActive('gray', state.gray);
+ setActive('pair', state.pair);
+
+ const favBtn = $('#sketch [data-skt="fav"]');
+ const isFav = !!(it && app.st.fav.has(it.k));
+ if (favBtn) {
+ favBtn.classList.toggle('on', isFav);
+ favBtn.setAttribute('aria-pressed', String(isFav));
+ favBtn.textContent = isFav ? '♥ 已收藏' : '♡ 收藏';
+ }
+
+ const pairBtn = $('#sketch [data-skt="pair"]');
+ const mate = it && app.poseCounterpart(it);
+ if (pairBtn) {
+ pairBtn.hidden = !mate;
+ if (mate) {
+ const shownType = state.pair ? mate.item.type : it.type;
+ pairBtn.textContent = shownType === 'pose' ? '深度图' : '线稿';
+ }
+ }
+
+ const grayBtn = $('#sketch [data-skt="gray"]');
+ const shown = state.pair && mate ? mate.item : it;
+ if (grayBtn) grayBtn.hidden = !shown || shown.type === 'pose' || shown.type === 'depth';
+
+ const soundBtn = $('#skSound');
+ if (soundBtn) {
+ soundBtn.classList.toggle('on', state.sound);
+ soundBtn.setAttribute('aria-pressed', String(state.sound));
+ }
+ }
+
+ function showCard() {
+ const it = state.deck[state.i];
+ if (!it) return;
+ if (!state.seen.includes(it)) state.seen.push(it);
+ const mate = app.poseCounterpart(it);
+ const shown = state.pair && mate ? mate.item : it;
+ const src = state.pair && mate
+ ? (mate.item.angles[mate.angle].i || mate.item.angles[mate.angle].t)
+ : app.big(it);
+
+ const img = $('#skImg');
+ const stage = $('#skStage');
+ const frame = $('#skFrame');
+ $('#skDone').hidden = true;
+ frame.hidden = false;
+ stage.dataset.imgType = shown.type;
+ img.referrerPolicy = shown.ref || '';
+ img.src = src;
+ img.alt = app.title(shown);
+
+ const cap = sessionCap();
+ $('#skStep').textContent = `${state.i + 1} / ${cap || '∞'}`;
+ const rawAng = it.angles?.[it.ai]?.zh;
+ const locAng = rawAng ? (window.PWLocale ? window.PWLocale.t(rawAng) : rawAng) : '';
+ $('#skName').textContent = app.title(it) + (locAng ? ' · ' + locAng : '');
+
+ state.rem = state.dur;
+ state.beeped = 0;
+ state.last = performance.now();
+ $('#skTime').textContent = formatTime(state.rem);
+ $('#skProg').style.transform = 'scaleX(1)';
+
+ const nextItem = state.deck[state.i + 1];
+ if (nextItem) app.preload(app.big(nextItem));
+
+ const pairType = app.counterpartType(it);
+ if (pairType && !app.DATA[pairType]) {
+ app.load(pairType).then(() => state.open && renderTools(), () => {});
+ }
+ renderTools();
+ }
+
+ function finish() {
+ clearInterval(state.timer);
+ state.timer = null;
+ state.paused = true;
+ $('#skFrame').hidden = true;
+ $('#skDone').hidden = false;
+ $('#skProg').style.transform = 'scaleX(0)';
+ const unit = state.dur >= 60 ? `${Math.round(state.dur / 60)} 分钟` : `${state.dur} 秒`;
+ $('#skSummary').textContent = `已完成 ${state.seen.length} 张参考练习(每张 ${unit})`;
+ $('#skRecap').innerHTML = state.seen
+ .map(it => `<button type="button" data-sk-open="${esc(it.k)}" title="${esc(app.title(it))}"><img src="${esc(app.thumb(it))}" alt="${esc(app.title(it))}"${it.ref ? ` referrerpolicy="${esc(it.ref)}"` : ''}></button>`)
+ .join('');
+ chime(784, 0.25);
+ }
+
+ function step(delta) {
+ const next = state.i + delta;
+ if (next < 0) return;
+ if (state.total && next >= Math.min(state.total, state.deck.length)) {
+ finish();
+ return;
+ }
+ if (next >= state.deck.length) {
+ const base = state.pool.length ? state.pool : app.st.list.filter(app.ok);
+ if (!base.length) {
+ finish();
+ return;
+ }
+ state.deck = state.deck.concat(shuffle(base.slice()));
+ }
+ state.i = next;
+ state.pair = false;
+ showCard();
+ if (delta > 0) chime(659, 0.14);
+ }
+
+ function tick() {
+ if (!state.open || state.paused || document.hidden) return;
+ const now = performance.now();
+ const dt = Math.min(0.5, (now - state.last) / 1000);
+ state.last = now;
+ state.rem = Math.max(0, state.rem - dt);
+ $('#skTime').textContent = formatTime(state.rem);
+ $('#skProg').style.transform = `scaleX(${Math.max(0, state.rem / state.dur)})`;
+ const ceil = Math.ceil(state.rem);
+ if (ceil <= 3 && ceil >= 1 && state.beeped !== ceil) {
+ state.beeped = ceil;
+ chime(523, 0.07);
+ }
+ if (state.rem <= 0) step(1);
+ }
+
+ function togglePause(force) {
+ state.paused = force === undefined ? !state.paused : !!force;
+ state.last = performance.now();
+ $('#skPause').textContent = state.paused ? '继续' : '暂停';
+ }
+
+ async function open(opts = {}) {
+ if (!app) return;
+ if (opts.dur) state.dur = opts.dur;
+ if (opts.total !== undefined) state.total = opts.total;
+ let pool = app.st.list.filter(app.ok);
+ if (pool.length < 2) {
+ if (!app.DATA.pose) await app.load('pose');
+ pool = (app.DATA.pose || []).filter(app.ok);
+ }
+ if (!pool.length) return app.toast('当前没有可用于速写的素材');
+
+ state.prevFocus = document.activeElement;
+ state.pool = pool.slice();
+ state.deck = shuffle(pool.slice());
+ state.i = 0;
+ state.seen = [];
+ state.flip = false;
+ state.grid = 0;
+ state.gray = false;
+ state.pair = false;
+ state.open = true;
+ state.paused = false;
+
+ $('#sketch').hidden = false;
+ document.body.style.overflow = 'hidden';
+ $$('#skDur button').forEach(b => {
+ const on = +b.dataset.sd === state.dur;
+ b.classList.toggle('on', on);
+ b.setAttribute('aria-pressed', String(on));
+ });
+ $$('#skTotal button').forEach(b => {
+ const on = +b.dataset.sc === state.total;
+ b.classList.toggle('on', on);
+ b.setAttribute('aria-pressed', String(on));
+ });
+ $('#skPause').textContent = '暂停';
+
+ showCard();
+ clearInterval(state.timer);
+ state.timer = setInterval(tick, 200);
+ $('#skPause').focus({ preventScroll: true });
+ }
+
+ function close() {
+ if (!state.open) return;
+ state.open = false;
+ clearInterval(state.timer);
+ state.timer = null;
+ $('#sketch').hidden = true;
+ $('#skImg').removeAttribute('src');
+ document.body.style.overflow = '';
+ if (state.prevFocus?.isConnected) state.prevFocus.focus({ preventScroll: true });
+ state.prevFocus = null;
+ }
+
+ function handleKey(e) {
+ if (!state.open) return false;
+ const k = (e.key || '').toLowerCase();
+ if (e.key === 'Escape') { e.preventDefault(); close(); }
+ else if (e.key === ' ' || e.code === 'Space') { e.preventDefault(); togglePause(); }
+ else if (e.key === 'ArrowRight') { e.preventDefault(); step(1); }
+ else if (e.key === 'ArrowLeft') { e.preventDefault(); step(-1); }
+ else if (k === 'h') { state.flip = !state.flip; renderTools(); }
+ else if (k === 'g') { state.grid = (state.grid + 1) % 3; renderTools(); }
+ else if (k === 'b') { state.gray = !state.gray; renderTools(); }
+ else if (k === 'v') {
+ const it = state.deck[state.i];
+ if (it && app.poseCounterpart(it)) {
+ state.pair = !state.pair;
+ showCard();
+ }
+ } else if (k === 'f') {
+ const it = state.deck[state.i];
+ if (it) {
+ app.toggleFav(it.k);
+ renderTools();
+ }
+ } else if (e.key === 'Tab') {
+ app.trapTab(e, $('#sketch'));
+ }
+ return true;
+ }
+
+ function init(appApi) {
+ app = appApi;
+ document.addEventListener('visibilitychange', () => {
+ if (state.open && !document.hidden) state.last = performance.now();
+ });
+
+ $('#sketchBtn')?.addEventListener('click', () => open());
+ $('#skClose')?.addEventListener('click', close);
+ $('#skExit')?.addEventListener('click', close);
+ $('#skAgain')?.addEventListener('click', () => open());
+ $('#skPause')?.addEventListener('click', () => togglePause());
+ $('#skPrev')?.addEventListener('click', () => step(-1));
+ $('#skNext')?.addEventListener('click', () => step(1));
+ $('#skSound')?.addEventListener('click', () => {
+ state.sound = !state.sound;
+ renderTools();
+ if (state.sound) chime(659, 0.1);
+ });
+
+ $('#skDur')?.addEventListener('click', e => {
+ const btn = e.target.closest('[data-sd]');
+ if (!btn) return;
+ state.dur = +btn.dataset.sd;
+ state.rem = state.dur;
+ state.last = performance.now();
+ state.beeped = 0;
+ $$('#skDur button').forEach(x => {
+ const on = x === btn;
+ x.classList.toggle('on', on);
+ x.setAttribute('aria-pressed', String(on));
+ });
+ if ($('#skDone').hidden) {
+ $('#skTime').textContent = formatTime(state.rem);
+ $('#skProg').style.transform = 'scaleX(1)';
+ }
+ });
+
+ $('#skTotal')?.addEventListener('click', e => {
+ const btn = e.target.closest('[data-sc]');
+ if (!btn) return;
+ state.total = +btn.dataset.sc;
+ $$('#skTotal button').forEach(x => {
+ const on = x === btn;
+ x.classList.toggle('on', on);
+ x.setAttribute('aria-pressed', String(on));
+ });
+ if ($('#skDone').hidden) $('#skStep').textContent = `${state.i + 1} / ${sessionCap() || '∞'}`;
+ });
+
+ $('#sketch')?.addEventListener('click', e => {
+ const tool = e.target.closest('[data-skt]');
+ if (tool) {
+ const action = tool.dataset.skt;
+ const it = state.deck[state.i];
+ if (action === 'flip') state.flip = !state.flip;
+ else if (action === 'grid') state.grid = (state.grid + 1) % 3;
+ else if (action === 'gray') state.gray = !state.gray;
+ else if (action === 'pair' && it && app.poseCounterpart(it)) {
+ state.pair = !state.pair;
+ showCard();
+ return;
+ } else if (action === 'fav' && it) {
+ app.toggleFav(it.k);
+ }
+ renderTools();
+ return;
+ }
+ const recap = e.target.closest('[data-sk-open]');
+ if (recap) {
+ const it = app.ITEMS[recap.dataset.skOpen];
+ close();
+ if (it) app.openItem(it.type, it.id);
+ }
+ });
+ }
+
+ window.PoseWearSketch = {
+ init,
+ open,
+ close,
+ isOpen: () => state.open,
+ handleKey,
+ };
+ if (window.APP) init(window.APP);
+})();
diff --git a/src/studio.js b/src/studio.js
index 9922d3a..fdb7337 100644
--- a/src/studio.js
+++ b/src/studio.js
@@ -1,1124 +1,2138 @@
'use strict';
-(()=>{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 {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 local-lg"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="18" height="12" rx="2.5"/><path d="M8 20h8m-4-4v4"/></svg></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','一位二十多岁的成年欧美女性,浅棕色波浪长发,自然妆容,匀称身材'],
- ['man','男性模特','an adult East Asian man in his late 20s, short black hair, clean-shaven, tall and lean','一位二十多岁的成年东亚男性,黑色短发,干净面容,高瘦身材'],
- ['anime','动漫角色','an adult anime-style girl, long silver hair, large expressive eyes, adult proportions, clean cel-shaded illustration','一位成年动漫风格女性角色,银色长发,大眼睛,成人身材比例,干净的赛璐璐上色插画'],
- ['custom','自定义','','']];
-const STYLES=[['keep','照片质感','photorealistic, matching the original photo quality','写实摄影质感,与原照片画质一致'],['studio','影棚大片','clean high-end fashion studio, soft key light, seamless light-grey backdrop, editorial lookbook photo','高端时尚影棚,柔和主光,浅灰无缝背景,杂志画册质感'],
- ['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 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,view:'board'};
-// 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 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 '';
- const allowHttp=settings.prov==='custom';
- try{const u=new URL(settings.base);if((u.protocol==='https:'||(allowHttp&&u.protocol==='http:'))&&!u.username&&!u.password)return ''}catch{}
- return allowHttp?'Base URL 需填写有效的 HTTP/HTTPS 地址,请勿在地址中包含账号或密码。':'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,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 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;
+(() => {
+ const A = window.APP;
+ const C = window.PoseWearCatalog;
+ if (!A || !C) return;
+ const {
+ $, $$, esc, readLS: LS, writeLS: SV,
+ BOARD_LABELS: boardLabels,
+ GARMENT_TYPES: garmentTypes,
+ OTHER_TYPES: otherTypes,
+ MATERIAL_ROLES,
+ } = C;
+ const toast = A.toast;
+
+ // ---------- Image Generation Providers ----------
+ 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 local-lg"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="18" height="12" rx="2.5"/><path d="M8 20h8m-4-4v4"/></svg></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 : {}) };
+
+ // ---------- Presets & Studio State ----------
+ 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', '一位二十多岁的成年欧美女性,浅棕色波浪长发,自然妆容,匀称身材'],
+ ['man', '男性模特', 'an adult East Asian man in his late 20s, short black hair, clean-shaven, tall and lean', '一位二十多岁的成年东亚男性,黑色短发,干净面容,高瘦身材'],
+ ['anime', '动漫角色', 'an adult anime-style girl, long silver hair, large expressive eyes, adult proportions, clean cel-shaded illustration', '一位成年动漫风格女性角色,银色长发,大眼睛,成人身材比例,干净的赛璐璐上色插画'],
+ ['custom', '自定义', '', ''],
+ ];
+
+ const STYLES = [
+ ['keep', '照片质感', 'photorealistic, matching the original photo quality', '写实摄影质感,与原照片画质一致'],
+ ['studio', '影棚大片', 'clean high-end fashion studio, soft key light, seamless light-grey backdrop, editorial lookbook photo', '高端时尚影棚,柔和主光,浅灰无缝背景,杂志画册质感'],
+ ['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 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,
+ view: 'board',
+ };
+
+ 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,
+ });
+ }
+
+ // ---------- Helpers ----------
+ 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 '';
+ const allowHttp = settings.prov === 'custom';
+ try {
+ const u = new URL(settings.base);
+ if ((u.protocol === 'https:' || (allowHttp && u.protocol === 'http:')) && !u.username && !u.password) return '';
+ } catch {}
+ return allowHttp
+ ? 'Base URL 需填写有效的 HTTP/HTTPS 地址,请勿在地址中包含账号或密码。'
+ : 'Base URL 需填写有效的 HTTPS 地址,请勿在地址中包含账号或密码。';
+ }
+
+ function loadImg(src) {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ img.onload = () => resolve(img);
+ img.onerror = () => reject(Error('图片读取失败'));
+ img.src = src;
+ });
+ }
+
+ async function toJpeg(src, max = 1536) {
+ const img = await loadImg(src);
+ let w = img.naturalWidth;
+ let h = img.naturalHeight;
+ const scale = Math.min(1, max / Math.max(w, h));
+ w = Math.round(w * scale);
+ h = Math.round(h * scale);
+ const canvas = document.createElement('canvas');
+ canvas.width = w;
+ canvas.height = h;
+ const ctx = canvas.getContext('2d');
+ ctx.fillStyle = '#fff';
+ ctx.fillRect(0, 0, w, h);
+ ctx.drawImage(img, 0, 0, w, h);
+ return new Promise(resolve => canvas.toBlob(blob => resolve({ blob, w, h }), 'image/jpeg', 0.92));
+ }
+
+ const libSrc = ref => {
+ const it = A.ITEMS[ref.k];
+ return it.angles ? it.angles[ref.ai ?? it.ai].i : it.i;
+ };
+
+ async function assetBlob(ref, signal) {
+ if (ref.blob) return ref.blob;
+ const src = ref.kind === 'portrait' ? A.ITEMS[ref.k].m : libSrc(ref);
+ const resp = await fetch(src, { signal, referrerPolicy: A.ITEMS[ref.k].ref || '' });
+ if (!resp.ok) throw Error(`素材下载失败(${resp.status})`);
+ const url = URL.createObjectURL(await resp.blob());
+ try {
+ return (await toJpeg(url, ref.kind === 'portrait' ? 1536 : 1280)).blob;
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+ }
+
+ const isGen = () => W.mode === 'gen';
+ const hasPerson = () => W.persons.length > 0;
+ const allSelectedCount = () => W.persons.length + W.garments.length + W.poses.length + W.exprs.length + W.extraRefs.length;
+
+ // ---------- Prompt Composition ----------
+ // Line art and depth maps represent the same pose only when sharing the same camera angle.
+ function poseGroups(poses) {
+ const groups = [];
+ for (const ref of poses) {
+ const item = A.ITEMS[ref.k];
+ const 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 poseDesc(ref, en) {
+ const it = A.ITEMS[ref.k];
+ if (!it) return '';
+ const angle = it.angles[ref.ai ?? it.ai];
+ const isTwoPerson = /2人|双人/.test(it.line);
+ if (en) {
+ return `${it.en} (${it.lineEn}, ${ANG_EN[angle.zh] || angle.en || angle.zh})` +
+ (isTwoPerson ? ' — a two-person pose: match the number of people and their relative positions' : '');
+ }
+ return `${it.zh}(${it.line},${angle.zh})` +
+ (isTwoPerson ? '——双人姿势,人数与相对位置需与参考图一致' : '');
+ }
+
+ function poseInstructions(groups, poseNumbers, en, sheet) {
+ const roleOf = ref => {
+ const depth = A.ITEMS[ref.k].type === 'depth';
+ const kind = en ? (depth ? 'depth map' : 'pose sketch') : (depth ? '深度图' : '姿势线稿');
+ return en ? `${poseNumbers.get(ref)} (${kind})` : `${poseNumbers.get(ref)}(${kind})`;
+ };
+ const details = groups.map((group, idx) => {
+ const refs = group.map(roleOf).join(en ? ' + ' : '+');
+ const desc = poseDesc(group[0], en);
+ const pairing = group.length === 2
+ ? (en ? ' together show the same pose and camera angle: ' : '对应同一动作和机位:')
+ : (en ? ': ' : ':');
+ return (sheet ? `(${idx + 1}) ` : '') + refs + pairing + desc;
+ });
+ 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 compose(poseSet, state = W) {
+ const en = state.pl === 'en';
+ const P = state.persons.length;
+ const G = state.garments.length;
+ const ps = poseSet || state.poses;
+ const groups = poseGroups(ps);
+ const np = groups.length;
+ const sheet = np > 1 && state.bm === 'sheet';
+ const style = STYLES.find(s => s[0] === state.style) || STYLES[0];
+ const ch = CHARS.find(c => c[0] === state.char) || CHARS[0];
+ const extra = state.extra ?? $('#wbExtra').value.trim();
+ const garmentItems = state.garments.map(g => g.kind === 'lib' && A.ITEMS[g.k]).filter(Boolean);
+
+ let seq = 0;
+ const rangeLabel = count => {
+ if (!count) return null;
+ const start = seq + 1;
+ const end = seq + count;
+ seq = end;
+ if (start === end) return en ? `image ${start}` : `第 ${start} 张`;
+ return en ? `images ${start}–${end}` : `第 ${start}–${end} 张`;
+ };
+
+ const E = state.exprs.length;
+ const exprItem = E ? A.ITEMS[state.exprs[0].k] : null;
+ const rP = rangeLabel(P);
+ const rG = rangeLabel(G);
+ const poseNumbers = new Map(ps.map(ref => [ref, rangeLabel(1)]));
+ const rE = rangeLabel(E);
+
+ const materials = state.extraRefs.map(ref => {
+ const it = A.ITEMS[ref.k];
+ const role = MATERIAL_ROLES[it.type][en ? 1 : 0];
+ const desc = A.prompt({ ...it, ai: ref.ai ?? it.ai }, state.pl);
+ return en ? `${role} (${rangeLabel(1)}): ${desc}` : `${role}(${rangeLabel(1)}):${desc}`;
+ });
+
+ if (!(P || G || np || E)) {
+ if (state.mode === 'gen' && state.char === 'custom' && state.charTxt.trim()) materials.unshift(state.charTxt.trim());
+ if (!materials.length) return extra;
+ if (state.dirtyStyle) materials.push(style[en ? 2 : 3]);
+ if (extra) materials.push(extra);
+ 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 hasHairRef = state.extraRefs.some(ref => A.ITEMS[ref.k].type === 'hair');
+ const lines = [];
+
+ if (en) {
+ lines.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.` : ''}`
+ );
+ lines.push(
+ P
+ ? `Subject: the person from the photo. Preserve their face, identity, ${hasHairRef ? '' : '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) {
+ const garmentText = garmentItems.length
+ ? ': ' + garmentItems.map(x => x.en.replace(/^[^,]*outfit,\s*/, '')).join('; ')
+ : '';
+ lines.push(`Outfit: dress the subject in the complete outfit from ${rG}, reproducing every garment faithfully — cut, color, fabric, pattern, layering, shoes and accessories${garmentText}. Replace the original clothing entirely. Never draw the mannequin or a blank body.`);
+ }
+ if (np) lines.push(poseInstructions(groups, poseNumbers, true, sheet));
+ else if (P) lines.push('Pose: keep the original pose, framing and camera angle.');
+ if (E && exprItem) {
+ lines.push(`Expression: ${rE} shows the target expression (${exprItem.en}). Transfer the expression only.${P ? ' Preserve the facial features and identity from the person photo.' : ''}`);
+ }
+ lines.push(...materials);
+ lines.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 (extra) lines.push('Additional: ' + extra);
+ } else {
+ lines.push(
+ P
+ ? `时尚${tryon ? '虚拟试穿' : '生图'},使用参考图。${rP}是人物照片(同一人)${G ? `;${rG}是放在隐形人台上的服装${G > 1 ? '(上装与下装)' : ''}` : ''}。`
+ : `根据参考图进行时尚生图。${G ? `${rG}是放在隐形人台上的服装。` : ''}`
+ );
+ lines.push(
+ P
+ ? `人物:照片中的人。严格保留其面部、身份特征、${hasHairRef ? '' : '发型、'}肤色与身材比例,必须一眼认出是同一位成年人。`
+ : `人物:${(state.char === 'custom' ? state.charTxt : ch[3]) || ch[3] || '一位成年模特'}。始终为成年人比例。`
+ );
+ if (G) {
+ const garmentText = garmentItems.length
+ ? ':' + garmentItems.map(x => x.zh.replace(/[。.]$/, '')).join(';')
+ : '';
+ lines.push(`服装:为人物换上${rG}中的整套服装,准确还原版型、颜色、面料、图案、叠穿、鞋袜与配饰${garmentText}。完全替换原有衣物,不要画出人台或空白身体。`);
+ }
+ if (np) lines.push(poseInstructions(groups, poseNumbers, false, sheet));
+ else if (P) lines.push('姿势:保持原照片的姿势、构图和拍摄角度。');
+ if (E && exprItem) {
+ lines.push(`表情:${rE} 展示目标表情(${exprItem.zh})。只迁移神态。${P ? '保留人物照片中的五官、脸型和身份。' : ''}`);
+ }
+ lines.push(...materials);
+ lines.push(`画面:${keepBackground ? '保留原照片的背景与光线;' : ''}${style[3]}。${G ? '衣物垂坠自然,褶皱阴影真实。' : ''}高细节。不要文字、水印或边框。`);
+ if (extra) lines.push('补充:' + extra);
+ }
+ return lines.join('\n');
+ }
+
+ function reprompt(force) {
+ if (force || !W.dirty) {
+ $('#wbPrompt').value = compose();
+ W.dirty = false;
+ }
+ }
+
+ // ---------- Board & Slot Rendering ----------
+ 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];
+ const type = it?.type || slot;
+ const name = it ? A.title(it) : ref.name || '自定义图片';
+ const angle = it?.angles?.[ref.ai ?? it.ai];
+ const 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];
+ $('#wbOtherPreview').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 syncCanvasView() {
+ const hasOut = W.results.length > 0;
+ const sw = $('#wbCanvasSwitch');
+ if (sw) {
+ sw.hidden = !hasOut;
+ sw.querySelectorAll('[data-cv]').forEach(b => {
+ const on = b.dataset.cv === W.view;
+ b.classList.toggle('on', on);
+ b.setAttribute('aria-pressed', String(on));
+ });
+ }
+ const showResult = hasOut && W.view === 'result';
+ $('#wbPh0').hidden = showResult;
+ $('#wbCmp').hidden = !showResult;
+ $('#wbRes').hidden = !showResult || W.results.length < 2;
+ $('#wbOutAct').hidden = !showResult;
+ const sent = $('#wbSentD');
+ if (sent) sent.hidden = !showResult || !W.results[W.ri]?.prompt;
+ const exportBtn = $('#wbExportBoard');
+ if (exportBtn) exportBtn.hidden = showResult || !allSelectedCount();
+ }
+
+ function chosenBoardRefs() {
+ return [
+ ...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 || 'other', ref]),
+ ];
+ }
+
+ function paintBoard() {
+ const hasOut = W.results.length > 0;
+ const output = hasOut && W.view === 'result';
+ const chosen = chosenBoardRefs();
+ const example = !chosen.length;
+ syncCanvasView();
+ $('#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], idx) => {
+ const item = A.ITEMS[ref.k];
+ const source = thumbnail(ref, item);
+ const material = item?.type || type;
+ const label = item ? A.title(item) : ref.name || boardLabels[type];
+ const angle = !example && item?.angles?.[ref.ai ?? item.ai]?.zh;
+ const idxBadge = example ? '' : `<i class="board-idx" aria-hidden="true">${idx + 1}</i>`;
+ const angBadge = angle ? `<em class="board-ang">${esc(angle)}</em>` : '';
+ return `<button class="board-card" data-pick="${material}" data-type="${material}"${item ? ` data-pk-key="${esc(item.k)}"` : ''} title="${esc(label)}">${idxBadge}<img src="${esc(source)}" alt="${esc(label)}"${item?.ref ? ` referrerpolicy="${esc(item.ref)}"` : ''}>${angBadge}<span>${boardLabels[material]}</span></button>`;
+ })
+ .join('');
+
+ const showActions = example && refs.length > 0;
+ if ($('#wbBoardActions')) $('#wbBoardActions').hidden = !showActions;
+ $('#wbExample').hidden = !showActions;
+ if ($('#wbShuffle')) $('#wbShuffle').hidden = !showActions;
+ }
+
+ async function exportBoardPng(opts = {}) {
+ const chosen = chosenBoardRefs();
+ if (!chosen.length || !window.PoseWearBoardExport) return null;
+ const btn = $('#wbExportBoard');
+ if (btn) btn.disabled = true;
+ try {
+ const { blob, extSkipped, now } = await window.PoseWearBoardExport.renderPng(chosen, {
+ app: A,
+ aspectRatio: $('#wbAR').value,
+ promptText: $('#wbPrompt')?.value || '',
+ });
+ if (!blob) throw Error('PNG 导出失败');
+ if (opts.download !== false && window.X?.dl) {
+ window.X.dl(blob, `posewear-board-${stamp(now)}.png`);
+ toast(extSkipped ? '已导出参考拼图 PNG(外链图已标出)' : '已导出参考拼图 PNG');
+ }
+ return blob;
+ } catch {
+ toast('导出参考拼图失败,请重试');
+ return null;
+ } finally {
+ if (btn) btn.disabled = false;
+ }
+ }
+ $('#wbExportBoard')?.addEventListener('click', () => exportBoardPng());
+
+ async function loadExample(randomize = false) {
+ if (!randomize && exampleRefs.length) return;
+ const types = ['portrait', 'costume', 'pose'];
+ const groups = await Promise.allSettled(types.map(A.load));
+ const prevKeys = new Set(exampleRefs.map(it => it.k));
+ exampleRefs = groups.flatMap(result => {
+ if (result.status !== 'fulfilled') return [];
+ const pool = result.value.filter(it => !it.a);
+ if (!pool.length) return [];
+ if (!randomize) return [pool[0]];
+ const fresh = pool.filter(it => !prevKeys.has(it.k));
+ const pickFrom = fresh.length ? fresh : pool;
+ return [pickFrom[(Math.random() * pickFrom.length) | 0]];
+ });
+ paintBoard();
+ if (randomize && !matchMedia('(prefers-reduced-motion: reduce)').matches) {
+ $$('#wbBoardCards .board-card').forEach((card, i) =>
+ card.animate([{ opacity: 0, transform: 'translateY(14px) scale(.94)' }, { opacity: 1 }], {
+ duration: 360,
+ delay: i * 55,
+ easing: 'cubic-bezier(.16,1,.3,1)',
+ })
+ );
+ }
+ }
+
+ $('#wbShuffle')?.addEventListener('click', () => loadExample(true));
+ $('#wbCanvasSwitch')?.addEventListener('click', e => {
+ const b = e.target.closest('[data-cv]');
+ if (!b || !W.results.length) return;
+ W.view = b.dataset.cv;
+ paintBoard();
+ if (W.view === 'board' && !allSelectedCount()) loadExample();
+ });
+ $('#wbClearAll')?.addEventListener('click', () => {
+ if (!allSelectedCount()) return;
+ const snap = {
+ persons: W.persons.slice(),
+ garments: W.garments.slice(),
+ poses: W.poses.slice(),
+ exprs: W.exprs.slice(),
+ extraRefs: W.extraRefs.slice(),
+ dirty: W.dirty,
+ prompt: $('#wbPrompt').value,
+ view: W.view,
+ };
+ W.persons = [];
+ W.garments = [];
+ W.poses = [];
+ W.exprs = [];
+ W.extraRefs = [];
+ W.dirty = false;
+ W.view = 'board';
+ saveDraft();
+ render();
+ loadExample();
+ toast('已清空素材', () => {
+ W.persons = snap.persons;
+ W.garments = snap.garments;
+ W.poses = snap.poses;
+ W.exprs = snap.exprs;
+ W.extraRefs = snap.extraRefs;
+ W.dirty = snap.dirty;
+ W.view = snap.view;
+ render();
+ if (snap.dirty) $('#wbPrompt').value = snap.prompt;
+ saveDraft();
+ });
+ });
+ $('#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 =
+ allSelectedCount() ||
+ $('#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';
+ }
+
+ const nJobs = () => (W.bm === 'each' ? Math.max(1, poseGroups(W.poses).length) : 1) * (+$('#wbN').value || 1);
+
+ 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></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();
+
+ if ($('#wbClearAll')) $('#wbClearAll').hidden = !allSelectedCount();
+ $('#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 = 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();
+ }
+
+ // ---------- Uploads & Slot Events ----------
+ const libPortrait = ref => ({ 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(fileList) {
+ const files = [...fileList].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 res = await toJpeg(u, 1536);
+ W.persons.push({ blob: res.blob, url: URL.createObjectURL(res.blob), w: res.w, h: res.h });
+ } catch {
+ toast('无法读取这张图片');
+ } finally {
+ URL.revokeObjectURL(u);
+ }
+ }
+ render();
+ }
+
+ async function addGarmentFiles(fileList) {
+ const files = [...fileList].filter(f => /^image\//.test(f.type));
+ if (!files.length) return toast('请选择图片文件');
+ 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();
+ }
+
+ const bindDrop = (el, fn) => {
+ if (!el) return;
+ ['dragenter', 'dragover'].forEach(evt => el.addEventListener(evt, e => { e.preventDefault(); el.classList.add('over'); }));
+ ['dragleave', 'drop'].forEach(evt => el.addEventListener(evt, e => { e.preventDefault(); el.classList.remove('over'); }));
+ el.addEventListener('drop', e => fn(e.dataTransfer.files));
+ };
+ bindDrop($('.person-step'), addPersons);
+ bindDrop($('.garment-step'), addGarmentFiles);
+
+ $('#wbFile').onchange = e => { addPersons(e.target.files); e.target.value = ''; };
+ $('#wbGFile').onchange = e => { addGarmentFiles(e.target.files); e.target.value = ''; };
+ for (const label of $$('.upload-link')) {
+ label.addEventListener('keydown', e => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ label.querySelector('input').click();
+ }
+ });
+ }
+ document.addEventListener('paste', e => {
+ if (document.body.classList.contains('studio') && !/INPUT|TEXTAREA/.test(document.activeElement.tagName)) {
+ const files = [...e.clipboardData.files].filter(f => /^image/.test(f.type));
+ if (files.length) addPersons(files);
+ }
+ });
+
+ $('#studio').addEventListener('click', e => {
+ const t = e.target;
+ let b;
+ 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);
+ const group = b.closest('.step,.material-extras');
+ const 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);
+ const [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 sel = e.target.closest('[data-ang]');
+ if (sel) {
+ const slot = sel.dataset.slot;
+ const index = sel.dataset.ang;
+ const refs = { pose: W.poses, expr: W.exprs, costume: W.garments, other: W.extraRefs }[slot];
+ refs[Number(index)].ai = Number(sel.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];
+ const it = A.ITEMS[p.k];
+ W.poses = it.angles.slice(0, 6).map((_, i) => ({ kind: 'lib', k: p.k, ai: i }));
+ toast(`已展开 ${W.poses.length} 个角度`);
+ render();
+ };
+ $('#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);
+ const 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);
+
+ // ---------- Material Picker Modal ----------
+ let pkType = 'costume';
+ let pkSink = null;
+ let pkItems = null;
+ let pkLastId = '';
+ let pkTimer;
+ let pkFav = false;
+ let pkCat = '';
+ let pkMatches = [];
+ let pkRendered = 0;
+
+ const poseType = type => type === 'pose' || type === 'depth';
+ const pkItemCat = it => it.cat || it.sec || it.era || it.emo || '';
+
+ 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 = '';
+ pkFav = false;
+ pkCat = '';
+ 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');
+ const view = grid.getBoundingClientRect();
+ const 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 };
+ }
+
+ function drawPkFilters() {
+ const bar = $('#pkBar');
+ const favBtn = $('#pkFavOnly');
+ const catsEl = $('#pkCats');
+ if (!bar || !pkItems) return;
+ const visible = pkItems.filter(A.ok);
+ const favCount = visible.filter(it => A.st.fav.has(it.k)).length;
+ if (!favCount) pkFav = false;
+ favBtn.hidden = !favCount;
+ favBtn.classList.toggle('on', pkFav);
+ favBtn.setAttribute('aria-pressed', String(pkFav));
+
+ const counts = new Map();
+ for (const it of visible) {
+ if (pkFav && !A.st.fav.has(it.k)) continue;
+ const cat = pkItemCat(it);
+ if (cat) counts.set(cat, (counts.get(cat) || 0) + 1);
+ }
+ if (pkCat && !counts.has(pkCat)) pkCat = '';
+ const entries = [...counts.entries()].sort((a, b) => b[1] - a[1]);
+ if (entries.length >= 2) {
+ catsEl.innerHTML =
+ `<button type="button" class="chip ${!pkCat ? 'on' : ''}" data-pk-cat="" aria-pressed="${!pkCat}">全部</button>` +
+ entries.map(([cat, n]) => `<button type="button" class="chip ${pkCat === cat ? 'on' : ''}" data-pk-cat="${esc(cat)}" aria-pressed="${pkCat === cat}">${esc(cat)}<i>${n}</i></button>`).join('');
+ catsEl.hidden = false;
+ } else {
+ catsEl.innerHTML = '';
+ catsEl.hidden = true;
+ }
+ bar.hidden = favBtn.hidden && catsEl.hidden;
+ }
+
+ async function showPickerType(type, anchor, initialKey) {
+ clearTimeout(pkTimer);
+ const prevPose = poseType(pkType) && poseType(type);
+ pkType = type;
+ pkItems = null;
+ if (!prevPose) { pkFav = false; pkCat = ''; }
+
+ 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));
+ }
+ }
+
+ if ($('#pkBar')) $('#pkBar').hidden = true;
+ $('#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));
+ }
+ drawPkFilters();
+ 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;
+ }
+
+ 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 (pkFav && !A.st.fav.has(it.k)) return false;
+ if (pkCat && pkItemCat(it) !== pkCat) 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();
+ const selected = new Set(refs.map(ref => ref.k));
+ const poses = poseType(pkType);
+ const angles = poses ? pickerPoseAngles(refs) : null;
+ const items = pkMatches.slice(pkRendered, pkRendered + count);
+ const markup = items
+ .map(it => {
+ const on = selected.has(it.k);
+ const label = esc(A.title(it));
+ const 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="${label}"><img loading="lazy" src="${esc(src)}"${it.ref ? ` referrerpolicy="${esc(it.ref)}"` : ''} alt=""><span>${label}</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');
+ const 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;
+ const 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();
+ if (e.target.closest('#pkFavOnly')) { pkFav = !pkFav; drawPkFilters(); drawPk(); return; }
+ const catBtn = e.target.closest('[data-pk-cat]');
+ if (catBtn) { pkCat = catBtn.dataset.pkCat; drawPkFilters(); drawPk(); return; }
+ 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;
+ const item = A.ITEMS[key];
+ const 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();
+ const 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;
+ };
+
+ // ---------- Neutral Wording Rewriter (reduces false safety flags without altering outfit/pose) ----------
+ const NEUTRAL = [
+ [/(?:胸部|臀部|腰臀|身材)(?:曲线|线条)?(?:突出|丰满|饱满|凸显)/g, ''],
+ [/凸显(?:身材|曲线|胸部|臀部)/g, ''],
+ [/火辣|撩人|诱惑|魅惑|勾人|性感/g, '时尚'],
+ [/紧身/g, '修身'],
+ [/露肩/g, '一字肩'],
+ [/露背/g, '开背设计'],
+ [/露脐/g, '短款'],
+ [/低胸/g, 'V 领'],
+ [/透视/g, '薄纱拼接'],
+ [/比基尼|泳装|泳衣/g, '泳池边时装'],
+ [/情趣内衣|内衣/g, '内搭'],
+ [/裸露|裸体|半裸/g, ''],
+ [/\b(?:emphasi[sz]ing|accentuating|showing off|highlighting) (?:her |his |the )?(?:curves|figure|body|bust|chest|hips|cleavage)\b/gi, ''],
+ [/\b(?:curvy|voluptuous|busty)\b/gi, ''],
+ [/\b(?:sexy|seductive|sultry|alluring|provocative|hot)\b/gi, 'stylish'],
+ [/\b(?:skin-?tight|bodycon)\b/gi, 'fitted'],
+ [/\btight\b/gi, 'fitted'],
+ [/\boff[- ]the[- ]shoulder\b/gi, 'off-shoulder neckline'],
+ [/\bbackless\b/gi, 'open-back design'],
+ [/\b(?:bikini|swimsuit|swimwear)\b/gi, 'swimwear fashion catalog piece'],
+ [/\b(?:lingerie|underwear|bra and panties)\b/gi, 'loungewear catalog set'],
+ [/\b(?:nude|naked|topless|cleavage|bust|busty)\b/gi, ''],
+ [/\bsee-?through\b/gi, 'sheer-panel'],
+ [/\blow-?cut\b/gi, 'V-neck'],
+ ];
+
+ 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 = (garments, set) =>
+ [...garments, ...set].some(g => g.kind === 'lib' && A.ITEMS[g.k] && A.ITEMS[g.k].a);
+
+ function neutralize(text, lang) {
+ let out = text;
+ for (const [pattern, replacement] of NEUTRAL) {
+ out = out.replace(pattern, replacement ? `\x01${replacement}\x01` : '\x02');
+ }
+ out = out
+ .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 isZh = /[\u4e00-\u9fa5]/.test(out.slice(0, 40)) && lang !== 'en';
+ return FRAME[isZh ? 'zh' : 'en'] + '\n' + out;
+ }
+
+ // ---------- Provider Settings Dialog ----------
+ let checkpoints = [];
+ let connectionCheck = null;
+
+ 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(settings) {
+ cancelConnectionCheck();
+ const preset = settings.prov === 'local' && localPreset;
+ $('#cfCheckpointW').hidden = !preset;
+ if (preset) {
+ const files = settings.checkpoint && !checkpoints.includes(settings.checkpoint)
+ ? [settings.checkpoint, ...checkpoints]
+ : checkpoints;
+ showCheckpoints(settings.checkpoint, files);
+ }
+ $('#cfg').classList.toggle('local-engine', settings.prov === 'local');
+ $$('[name=prov]').forEach(r => { r.checked = r.value === settings.prov; });
+ const P = PROV[settings.prov];
+ $('#cfBase').value = settings.base;
+ $('#cfBase').placeholder = P.base || 'https://你的中转地址/v1';
+ $('#cfKey').value = settings.key;
+ $('#cfKey').placeholder = settings.prov === 'gemini' ? 'AIza…' : 'sk-… / 方舟 API Key';
+ $('#cfModel').value = settings.model;
+ $('#cfModel').placeholder = P.model;
+ $('#cfModels').innerHTML = P.models.map(m => `<option value="${m}">`).join('');
+ $('#cfField').value = settings.field;
+ $('#cfProto').value = settings.proto;
+ $('#cfProtoW').hidden = settings.prov !== 'custom';
+ $('#cfFieldW').hidden = !(settings.prov === 'custom' && settings.proto === 'edits');
+ $('#cfProxy').checked = settings.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: '直连时,浏览器将密钥和图片发给填写的地址;启用本站代理后经本站转发。http/https 与任意端口均可。',
+ })[settings.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 WeakMap();
+ function openDialog(dialog, focusEl, opener = document.activeElement) {
+ dialogOpeners.set(dialog, opener);
+ dialog.hidden = false;
+ document.body.style.overflow = 'hidden';
+ focusEl.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('火山方舟接口不允许浏览器跨域,已开启本站代理');
+ };
});
- 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(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} 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?`时尚${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(poseInstructions(groups,poseNumbers,false,sheet));
- else if(P)L.push('姿势:保持原照片的姿势、构图和拍摄角度。');
- 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}}
-// ---------- 渲染 ----------
-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 syncCanvasView(){
- const hasOut=W.results.length>0;
- const sw=$('#wbCanvasSwitch');
- if(sw){
- sw.hidden=!hasOut;
- sw.querySelectorAll('[data-cv]').forEach(b=>{
- const on=b.dataset.cv===W.view;b.classList.toggle('on',on);b.setAttribute('aria-pressed',String(on));
+ $('#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 next = cfgRead();
+ const error = configError(next);
+ if (error) return msg(error, 1);
+ try {
+ localStorage.setItem('wbCfg', JSON.stringify(next));
+ } catch {
+ return msg('无法保存设置,请检查浏览器存储权限', 1);
+ }
+ Object.assign(cfg, next);
+ 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(text, bad) {
+ const m = $('#cfMsg');
+ m.textContent = text;
+ m.className = 'fine ' + (bad ? 'bad' : 'good');
+ }
+ $('#cfg').addEventListener('input', () => {
+ cancelConnectionCheck();
+ $('#cfMsg').textContent = '';
});
- }
- const showResult=hasOut&&W.view==='result';
- $('#wbPh0').hidden=showResult;
- $('#wbCmp').hidden=!showResult;
- $('#wbRes').hidden=!showResult||W.results.length<2;
- $('#wbOutAct').hidden=!showResult;
- const sent=$('#wbSentD');if(sent)sent.hidden=!showResult||!W.results[W.ri]?.prompt;
- const exportBtn=$('#wbExportBoard');
- if(exportBtn)exportBtn.hidden=showResult||!(W.persons.length||W.garments.length||W.poses.length||W.exprs.length||W.extraRefs.length);
-}
-function paintBoard(){
- const hasOut=W.results.length>0;
- const output=hasOut&&W.view==='result';
- 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;
- syncCanvasView();
- $('#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],idx)=>{
- 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];
- const angle=!example&&item?.angles?.[ref.ai??item.ai]?.zh;
- const idxBadge=example?'':`<i class="board-idx" aria-hidden="true">${idx+1}</i>`;
- const angBadge=angle?`<em class="board-ang">${esc(angle)}</em>`:'';
- return `<button class="board-card" data-pick="${material}" data-type="${material}"${item?` data-pk-key="${esc(item.k)}"`:''} title="${esc(label)}">${idxBadge}<img src="${esc(source)}" alt="${esc(label)}"${item?.ref?` referrerpolicy="${esc(item.ref)}"`:''}>${angBadge}<span>${boardLabels[material]}</span></button>`;
- }).join('');
- const showActions=example&&refs.length>0;
- if($('#wbBoardActions'))$('#wbBoardActions').hidden=!showActions;
- $('#wbExample').hidden=!showActions;
- if($('#wbShuffle'))$('#wbShuffle').hidden=!showActions;
-}
-const BOARD_ACCENT={pose:'#849dbb',depth:'#9689ae',costume:'#be929a',anime:'#b08fad',portrait:'#c49a82',expr:'#a2778b',hair:'#968071',dyn:'#ab7870',scene:'#88a48a',light:'#a2b6bf',prop:'#739e9c',furn:'#95928e'};
-function roundRectPath(ctx,x,y,w,h,r){
- ctx.beginPath();
- ctx.moveTo(x+r,y);ctx.arcTo(x+w,y,x+w,y+h,r);ctx.arcTo(x+w,y+h,x,y+h,r);
- ctx.arcTo(x,y+h,x,y,r);ctx.arcTo(x,y,x+w,y,r);ctx.closePath();
-}
-function clipText(ctx,str,maxW){
- const s=String(str||'').replace(/\s+/g,' ').trim();
- if(!s||ctx.measureText(s).width<=maxW)return s;
- let lo=0,hi=s.length;
- while(lo<hi){const mid=(lo+hi+1)>>1;if(ctx.measureText(s.slice(0,mid)+'…').width<=maxW)lo=mid;else hi=mid-1}
- return s.slice(0,lo)+'…';
-}
-function loadBoardImage(ref,item){
- return new Promise(resolve=>{
- const img=new Image();
- let src='';
- if(ref.blob||ref.url&&!item)src=ref.url;
- else if(item&&!item.ext)src=item.angles?(item.angles[ref.ai??item.ai]?.i||item.angles[ref.ai??item.ai]?.t):(item.m||item.i||item.t);
- else if(item?.ext){img.crossOrigin='anonymous';if(item.ref)img.referrerPolicy=item.ref;src=item.m||item.t}
- if(!src)return resolve(null);
- const done=ok=>resolve(ok&&img.naturalWidth?img:null);
- img.onload=()=>done(true);img.onerror=()=>done(false);
- img.src=src;
- });
-}
-async function exportBoardPng(opts={}){
- 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||'other',ref])];
- if(!chosen.length)return null;
- const btn=$('#wbExportBoard');if(btn)btn.disabled=true;
- const t=s=>window.PWLocale?window.PWLocale.t(s):s;
- try{
- const entries=await Promise.all(chosen.map(async([type,ref],idx)=>{
- const item=A.ITEMS[ref.k],material=item?.type||type;
- const title=item?A.title(item):(ref.name||t('本地上传'));
- const angle=item?.angles?.[ref.ai??item.ai]?.zh||'';
- const img=await loadBoardImage(ref,item);
- return {idx:idx+1,material,cat:t(boardLabels[material]||material),title,angle:angle?t(angle):'',img,ext:!!item?.ext};
- }));
- const dark=document.documentElement.dataset.theme==='dark';
- const n=entries.length,cols=n<=3?n:n===4?2:n<=6?3:4,rows=Math.ceil(n/cols);
- const cardW=360,padImg=12,imgW=cardW-padImg*2,imgH=448,capH=68,cardH=padImg+imgH+capH,gap=28,padX=56,headH=96,footH=68;
- const Wpx=Math.max(840,padX*2+cols*cardW+(cols-1)*gap);
- const Hpx=headH+rows*cardH+(rows-1)*gap+footH;
- const cv=document.createElement('canvas');cv.width=Wpx;cv.height=Hpx;
- const ctx=cv.getContext('2d');
- const sans='-apple-system,BlinkMacSystemFont,"PingFang SC","Noto Sans SC","Helvetica Neue",Arial,sans-serif';
- ctx.fillStyle=dark?'#141416':'#f7f7f8';ctx.fillRect(0,0,Wpx,Hpx);
- ctx.fillStyle=dark?'rgba(255,255,255,0.06)':'rgba(0,0,0,0.065)';
- for(let y=24;y<Hpx;y+=24)for(let x=24;x<Wpx;x+=24){ctx.beginPath();ctx.arc(x,y,1,0,Math.PI*2);ctx.fill()}
- // Header brand mark + title
- const ac=dark?'#ff3b57':'#ff2442',ink=dark?'#f2f2f2':'#111111',mu=dark?'#9a9a9e':'#666666',cardBg=dark?'#1e1e22':'#ffffff',lineCol=dark?'#323236':'#e4e4e7';
- ctx.fillStyle=ac;ctx.beginPath();ctx.arc(padX+14,35,4.2,0,Math.PI*2);ctx.fill();
- ctx.strokeStyle=ac;ctx.lineWidth=3.2;ctx.lineJoin='round';
- ctx.beginPath();ctx.moveTo(padX+14,42);ctx.lineTo(padX+3,55);ctx.lineTo(padX+25,55);ctx.closePath();ctx.stroke();
- ctx.fillStyle=ink;ctx.font=`700 22px ${sans}`;ctx.textBaseline='middle';
- ctx.fillText('PoseWear',padX+36,46);
- const brandW=ctx.measureText('PoseWear').width;
- ctx.fillStyle=mu;ctx.font=`500 16px ${sans}`;
- ctx.fillText('· '+t('参考画板'),padX+48+brandW,47);
- const now=new Date(),stamp=`${now.getFullYear()}.${String(now.getMonth()+1).padStart(2,'0')}.${String(now.getDate()).padStart(2,'0')}`;
- const ar=$('#wbAR').value,unit=document.documentElement.lang==='en'&&n===1?'image':t('张'),metaParts=[`${n} ${unit}`,ar!=='auto'?ar:'',stamp].filter(Boolean).join(' · ');
- ctx.textAlign='right';ctx.font=`500 14px ${sans}`;ctx.fillStyle=mu;
- ctx.fillText(metaParts,Wpx-padX,47);ctx.textAlign='left';
- let extSkipped=0;
- entries.forEach((e,i)=>{
- const r=Math.floor(i/cols),c=i%cols,rowCount=r===rows-1?n-r*cols:cols;
- const rowW=rowCount*cardW+(rowCount-1)*gap,startX=(Wpx-rowW)/2;
- const x=startX+c*(cardW+gap),y=headH+r*(cardH+gap),edge=BOARD_ACCENT[e.material]||lineCol;
- ctx.save();
- ctx.shadowColor=dark?'rgba(0,0,0,0.45)':'rgba(0,0,0,0.08)';ctx.shadowBlur=22;ctx.shadowOffsetY=8;
- roundRectPath(ctx,x,y,cardW,cardH,18);ctx.fillStyle=cardBg;ctx.fill();
- ctx.restore();
- roundRectPath(ctx,x,y,cardW,cardH,18);ctx.strokeStyle=edge+'77';ctx.lineWidth=1.5;ctx.stroke();
- const ix=x+padImg,iy=y+padImg;
- ctx.save();
- roundRectPath(ctx,ix,iy,imgW,imgH,12);ctx.clip();
- ctx.fillStyle=e.material==='depth'?'#141414':e.material==='pose'?'#f4f4f4':(dark?'#26262a':'#f3f3f5');
- ctx.fillRect(ix,iy,imgW,imgH);
- if(e.img){
- const pad=e.material==='pose'?16:0,aw=imgW-pad*2,ah=imgH-pad*2;
- const sc=Math.min(aw/e.img.naturalWidth,ah/e.img.naturalHeight);
- const dw=e.img.naturalWidth*sc,dh=e.img.naturalHeight*sc;
- if(e.material==='pose')ctx.globalCompositeOperation='multiply';
- ctx.drawImage(e.img,ix+pad+(aw-dw)/2,iy+pad+(ah-dh)/2,dw,dh);
- ctx.globalCompositeOperation='source-over';
- }else{
- if(e.ext)extSkipped++;
- ctx.fillStyle=mu;ctx.font=`600 15px ${sans}`;ctx.textAlign='center';
- ctx.fillText(e.cat,ix+imgW/2,iy+imgH/2-16);
- ctx.font=`400 13px ${sans}`;ctx.fillText(clipText(ctx,e.title,imgW-36),ix+imgW/2,iy+imgH/2+8);
- if(e.ext){ctx.font=`400 12px ${sans}`;ctx.fillText(t('在原站查看'),ix+imgW/2,iy+imgH/2+32)}
- ctx.textAlign='left';
- }
- ctx.restore();
- // Send-order badge
- roundRectPath(ctx,ix+10,iy+10,28,28,8);ctx.fillStyle='rgba(17,17,17,0.82)';ctx.fill();
- ctx.fillStyle='#ffffff';ctx.font=`700 14px ${sans}`;ctx.textAlign='center';ctx.textBaseline='middle';
- ctx.fillText(String(e.idx),ix+24,iy+24);ctx.textAlign='left';
- // Angle pill
- if(e.angle){
- ctx.font=`600 12px ${sans}`;const aw=ctx.measureText(e.angle).width+18;
- roundRectPath(ctx,ix+imgW-aw-10,iy+imgH-32,aw,22,11);ctx.fillStyle='rgba(17,17,17,0.78)';ctx.fill();
- ctx.fillStyle='#ffffff';ctx.textAlign='center';ctx.fillText(e.angle,ix+imgW-aw/2-10,iy+imgH-21);ctx.textAlign='left';
- }
- // Caption
- const cy=iy+imgH+22;
- ctx.fillStyle=edge;ctx.beginPath();ctx.arc(x+20,cy,4.5,0,Math.PI*2);ctx.fill();
- ctx.fillStyle=mu;ctx.font=`600 13px ${sans}`;ctx.fillText(e.cat,x+32,cy);
- ctx.fillStyle=ink;ctx.font=`600 15px ${sans}`;ctx.fillText(clipText(ctx,e.title,cardW-36),x+18,cy+24);
+
+ $('#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');
+ const stamp = d => `${d.getFullYear()}${p2(d.getMonth() + 1)}${p2(d.getDate())}-${p2(d.getHours())}${p2(d.getMinutes())}`;
+
+ // ---------- Generation Pipeline ----------
+ let tick;
+ let done = 0;
+ let total = 1;
+
+ const stage = text => { $('#wbStage1').textContent = text; };
+
+ function busy(on) {
+ const panel = $('#wbBusy');
+ const go = $('#wbGo');
+ const 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 }));
+ const garments = state.garments.map(g => ({ ...g }));
+ const 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];
+ const 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 };
+ const 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();
+ const failed = [];
+ const 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();
+ const cancel = () => request.abort();
+ signal.addEventListener('abort', cancel, { once: true });
+ let timedOut = false;
+ let result;
+ const timer = setTimeout(() => { timedOut = 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 (timedOut && !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;
+ const 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 action = f.dataset.ef;
+ if (action === 'prov') {
+ cfgOpen();
+ const p = $('#cfg .prov');
+ p.scrollIntoView({ block: 'start' });
+ p.classList.remove('hl');
+ void p.offsetWidth;
+ p.classList.add('hl');
+ const other = $('[name=prov]:not(:checked)');
+ other?.focus();
+ } else if (action === 'cos') {
+ picker('costume');
+ } else if (action === 'prompt') {
+ $('#wbPrompt').focus();
+ } else if (action === 'neutral') {
+ SV('wbNeutral', true);
+ $('#wbNeutral').checked = true;
+ run();
+ } else if (action === 'copy') {
+ A.copy(f.previousElementSibling.textContent);
+ }
+ return;
+ }
+ if (e.target.id === 'wbRetry' && retryBatch) run({ retry: retryBatch });
+ if (e.target.closest('[data-open-cfg]')) cfgOpen();
});
- // Footer colophon
- const fy=Hpx-footH+24;
- ctx.strokeStyle=lineCol;ctx.lineWidth=1;ctx.beginPath();ctx.moveTo(padX,fy-14);ctx.lineTo(Wpx-padX,fy-14);ctx.stroke();
- const promptSnippet=clipText(ctx,$('#wbPrompt')?.value||'',Wpx-padX*2-190);
- ctx.fillStyle=mu;ctx.font=`400 13px ${sans}`;
- if(promptSnippet)ctx.fillText(promptSnippet,padX,fy+12);
- ctx.textAlign='right';ctx.font=`600 13px ${sans}`;ctx.fillText('posewear.pages.dev',Wpx-padX,fy+12);
- const blob=await new Promise(r=>cv.toBlob(r,'image/png'));
- if(!blob)throw Error('PNG 导出失败');
- if(opts.download!==false&&window.X?.dl){
- const fstamp=`${now.getFullYear()}${String(now.getMonth()+1).padStart(2,'0')}${String(now.getDate()).padStart(2,'0')}-${String(now.getHours()).padStart(2,'0')}${String(now.getMinutes()).padStart(2,'0')}`;
- window.X.dl(blob,`posewear-board-${fstamp}.png`);
- toast(extSkipped?'已导出参考拼图 PNG(外链图已标出)':'已导出参考拼图 PNG');
- }
- return blob;
- }catch{
- toast('导出参考拼图失败,请重试');
- return null;
- }finally{if(btn)btn.disabled=false}
-}
-$('#wbExportBoard')?.addEventListener('click',()=>exportBoardPng());
-async function loadExample(randomize=false){
- if(!randomize&&exampleRefs.length)return;
- const types=['portrait','costume','pose'];
- const groups=await Promise.allSettled(types.map(A.load));
- const prevKeys=new Set(exampleRefs.map(it=>it.k));
- exampleRefs=groups.flatMap(result=>{
- if(result.status!=='fulfilled')return[];
- const pool=result.value.filter(it=>!it.a);
- if(!pool.length)return[];
- if(!randomize)return[pool[0]];
- const fresh=pool.filter(it=>!prevKeys.has(it.k));
- const pickFrom=fresh.length?fresh:pool;
- return[pickFrom[Math.random()*pickFrom.length|0]];
- });
- paintBoard();
- if(randomize&&!matchMedia('(prefers-reduced-motion: reduce)').matches){
- $$('#wbBoardCards .board-card').forEach((card,i)=>card.animate([
- {opacity:0,transform:'translateY(14px) scale(.94)'},
- {opacity:1}
- ],{duration:360,delay:i*55,easing:'cubic-bezier(.16,1,.3,1)'}));
- }
-}
-$('#wbShuffle')?.addEventListener('click',()=>loadExample(true));
-$('#wbCanvasSwitch')?.addEventListener('click',e=>{
- const b=e.target.closest('[data-cv]');if(!b||!W.results.length)return;
- W.view=b.dataset.cv;paintBoard();
- if(W.view==='board'&&!W.persons.length&&!W.garments.length&&!W.poses.length&&!W.exprs.length&&!W.extraRefs.length)loadExample();
-});
-$('#wbClearAll')?.addEventListener('click',()=>{
- const total=W.persons.length+W.garments.length+W.poses.length+W.exprs.length+W.extraRefs.length;
- if(!total)return;
- const snap={persons:W.persons.slice(),garments:W.garments.slice(),poses:W.poses.slice(),exprs:W.exprs.slice(),extraRefs:W.extraRefs.slice(),dirty:W.dirty,prompt:$('#wbPrompt').value,view:W.view};
- W.persons=[];W.garments=[];W.poses=[];W.exprs=[];W.extraRefs=[];W.dirty=false;W.view='board';
- saveDraft();render();loadExample();
- toast('已清空素材',()=>{
- W.persons=snap.persons;W.garments=snap.garments;W.poses=snap.poses;W.exprs=snap.exprs;W.extraRefs=snap.extraRefs;
- W.dirty=snap.dirty;W.view=snap.view;
- render();if(snap.dirty)$('#wbPrompt').value=snap.prompt;saveDraft();
- });
-});
-$('#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></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();
- const hasMaterials=W.persons.length+W.garments.length+W.poses.length+W.exprs.length+W.extraRefs.length>0;
- if($('#wbClearAll'))$('#wbClearAll').hidden=!hasMaterials;
- $('#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=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);
-// ---------- 上传 ----------
-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()}
-async function addGarmentFiles(files){files=[...files].filter(f=>/^image\//.test(f.type));if(!files.length)return toast('请选择图片文件');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()}
-const bindDrop=(el,fn)=>{if(!el)return;['dragenter','dragover'].forEach(t=>el.addEventListener(t,e=>{e.preventDefault();el.classList.add('over')}));['dragleave','drop'].forEach(t=>el.addEventListener(t,e=>{e.preventDefault();el.classList.remove('over')}));el.addEventListener('drop',e=>fn(e.dataTransfer.files))};
-bindDrop($('.person-step'),addPersons);bindDrop($('.garment-step'),addGarmentFiles);
-$('#wbFile').onchange=e=>{addPersons(e.target.files);e.target.value=''};
-for(const label of $$('.upload-link'))label.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();label.querySelector('input').click()}});
-$('#wbGFile').onchange=e=>{addGarmentFiles(e.target.files);e.target.value=''};
-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 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 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;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,pkItems=null,pkLastId='',pkTimer,pkFav=false,pkCat='';
-const poseType=type=>type==='pose'||type==='depth';
-const pkItemCat=it=>it.cat||it.sec||it.era||it.emo||'';
-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='';pkFav=false;pkCat='';
- 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};
-}
-function drawPkFilters(){
- const bar=$('#pkBar'),favBtn=$('#pkFavOnly'),catsEl=$('#pkCats');
- if(!bar||!pkItems)return;
- const visible=pkItems.filter(A.ok);
- const favCount=visible.filter(it=>A.st.fav.has(it.k)).length;
- if(!favCount)pkFav=false;
- favBtn.hidden=!favCount;
- favBtn.classList.toggle('on',pkFav);
- favBtn.setAttribute('aria-pressed',String(pkFav));
- const counts=new Map();
- for(const it of visible){
- if(pkFav&&!A.st.fav.has(it.k))continue;
- const cat=pkItemCat(it);
- if(cat)counts.set(cat,(counts.get(cat)||0)+1);
- }
- if(pkCat&&!counts.has(pkCat))pkCat='';
- const entries=[...counts.entries()].sort((a,b)=>b[1]-a[1]);
- if(entries.length>=2){
- catsEl.innerHTML=`<button type="button" class="chip ${!pkCat?'on':''}" data-pk-cat="" aria-pressed="${!pkCat}">全部</button>`+
- entries.map(([cat,n])=>`<button type="button" class="chip ${pkCat===cat?'on':''}" data-pk-cat="${esc(cat)}" aria-pressed="${pkCat===cat}">${esc(cat)}<i>${n}</i></button>`).join('');
- catsEl.hidden=false;
- }else{
- catsEl.innerHTML='';catsEl.hidden=true;
- }
- bar.hidden=favBtn.hidden&&catsEl.hidden;
-}
-async function showPickerType(type,anchor,initialKey){
- clearTimeout(pkTimer);const prevPose=poseType(pkType)&&poseType(type);pkType=type;pkItems=null;
- if(!prevPose){pkFav=false;pkCat=''}
- 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));
- }
- }
- if($('#pkBar'))$('#pkBar').hidden=true;
- $('#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));
- }
- drawPkFilters();
- 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(pkFav&&!A.st.fav.has(it.k))return false;
- if(pkCat&&pkItemCat(it)!==pkCat)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 favBtn=e.target.closest('#pkFavOnly');
- if(favBtn){pkFav=!pkFav;drawPkFilters();drawPk();return}
- const catBtn=e.target.closest('[data-pk-cat]');
- if(catBtn){pkCat=catBtn.dataset.pkCat;drawPkFilters();drawPk();return}
- 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;
-};
-// ---------- 设置 ----------
-
-// ---------- 减少误拦截:只改发送给服务商的措辞,不改服装、姿势 ----------
-// [匹配, 替换],按顺序执行;替换为空表示删掉
-const NEUTRAL=[
- [/(?:胸部|臀部|腰臀|身材)(?:曲线|线条)?(?:突出|丰满|饱满|凸显)/g,''],[/凸显(?:身材|曲线|胸部|臀部)/g,''],[/火辣|撩人|诱惑|魅惑|勾人|性感/g,'时尚'],
- [/紧身/g,'修身'],[/露肩/g,'一字肩'],[/露背/g,'开背设计'],[/露脐/g,'短款'],[/低胸/g,'V 领'],[/透视/g,'薄纱拼接'],
- [/比基尼|泳装|泳衣/g,'泳池边时装'],[/情趣内衣|内衣/g,'内搭'],[/裸露|裸体|半裸/g,''],
- [/\b(?:emphasi[sz]ing|accentuating|showing off|highlighting) (?:her |his |the )?(?:curves|figure|body|bust|chest|hips|cleavage)\b/gi,''],
- [/\b(?:curvy|voluptuous|busty)\b/gi,''],[/\b(?:sexy|seductive|sultry|alluring|provocative|hot)\b/gi,'stylish'],
- [/\b(?:skin-?tight|bodycon)\b/gi,'fitted'],[/\btight\b/gi,'fitted'],[/\boff[- ]the[- ]shoulder\b/gi,'off-shoulder neckline'],[/\bbackless\b/gi,'open-back design'],
- [/\b(?:bikini|swimsuit|swimwear)\b/gi,'swimwear fashion catalog piece'],[/\b(?:lingerie|underwear|bra and panties)\b/gi,'loungewear catalog set'],
- [/\b(?:nude|naked|topless|cleavage|bust|busty)\b/gi,''],[/\bsee-?through\b/gi,'sheer-panel'],[/\blow-?cut\b/gi,'V-neck'],
-];
-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=(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))&&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:'直连时,浏览器将密钥和图片发给填写的地址;启用本站代理后经本站转发。http/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();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')}
-$('#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())}`;
-// ---------- 进度 ----------
-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=='prompt')$('#wbPrompt').focus();if(k=='neutral'){SV('wbNeutral',true);$('#wbNeutral').checked=true;run()}if(k=='copy')A.copy(f.previousElementSibling.textContent);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();
-// ---------- 结果 ----------
-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;W.view='result';{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').classList.toggle('solo',!hasB||!W.cmp);$('#wbCmpT').hidden=!hasB;$('#wbCmpT').textContent=W.cmp?'关闭对比':'前后对比';
- syncCanvasView();$('#wbCanvasTitle').textContent='生成结果';$('#wbCanvasRatio').textContent='';$('#wbErr').hidden=true;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.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 notice='导出时包含 API Key 吗?\n确定 = 包含,取消 = 不含密钥';const withKey=confirm(window.PWLocale.t(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}];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){
- 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>`:'')):'';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()})};
-// ---------- 对外 ----------
-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('请核对当前服务商及模型');
- W.view='board';
- 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,exportBoardPng,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=>{
- 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);
+
+ $('#wbGo').onclick = () => run();
+ $('#wbAgain').onclick = () => run();
+ $('#wbStop').onclick = () => W.busy?.abort();
+
+ // ---------- Result Display & Comparison ----------
+ const ru = new Map();
+ const U = blob => {
+ if (!ru.has(blob)) ru.set(blob, URL.createObjectURL(blob));
+ return ru.get(blob);
+ };
+
+ function setX(x) {
+ $('#wbCmp').style.setProperty('--x', x + '%');
+ $('#wbRange').value = x;
+ }
+ $('#wbRange').oninput = e => setX(e.target.value);
+
+ function show(i, meta) {
+ const r = W.results[i];
+ if (!r) return;
+ W.view = 'result';
+ let details = $('#wbSentD');
+ if (!details) {
+ details = document.createElement('details');
+ details.id = 'wbSentD';
+ details.className = 'raw sent';
+ $('#wbOutAct').after(details);
+ }
+ details.hidden = !r.prompt;
+ details.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 afterUrl = U(r.after);
+ const hasBefore = !!r.before;
+ $('#wbAfter').src = afterUrl;
+ if (hasBefore) $('#wbBefore').src = U(r.before);
+ $('#wbCmp').classList.toggle('solo', !hasBefore || !W.cmp);
+ $('#wbCmpT').hidden = !hasBefore;
+ $('#wbCmpT').textContent = W.cmp ? '关闭对比' : '前后对比';
+ syncCanvasView();
+ $('#wbCanvasTitle').textContent = '生成结果';
+ $('#wbCanvasRatio').textContent = '';
+ $('#wbErr').hidden = true;
+ 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 (hasBefore && W.cmp && !W._wig) {
+ W._wig = 1;
+ const t0 = performance.now();
+ const wiggle = t => {
+ const p = (t - t0) / 1400;
+ if (p >= 1) return setX(50);
+ setX(50 + Math.sin(p * Math.PI * 2) * 12 * (1 - p));
+ requestAnimationFrame(wiggle);
+ };
+ setTimeout(() => requestAnimationFrame(wiggle), 500);
+ }
+ }
+
+ $('#wbMeta').textContent = meta || ((PROV[r.prov] || { name: r.prov }).name + ' · ' + r.model + (r.label ? ' · ' + r.label : ''));
+ $('#wbRes').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 rect = $('#wbStage').getBoundingClientRect();
+ if (rect.bottom < 0 || rect.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]'); if (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 files = 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(files), `posewear-tryon-${ts}.zip`);
+ toast(`已打包 ${files.length} 张`);
+ };
+ $('#cfExp').onclick = () => {
+ const notice = '导出时包含 API Key 吗?\n确定 = 包含,取消 = 不含密钥';
+ const withKey = confirm(window.PWLocale.t(notice));
+ const copyCfg = cfgRead();
+ if (!withKey) delete copyCfg.key;
+ window.X.dl(
+ new Blob([JSON.stringify({ app: '衣姿 PoseWear', type: 'api-config', cfg: copyCfg }, null, 2)], { type: 'application/json' }),
+ '衣姿-API设置.json'
+ );
+ msg('已导出设置' + (withKey ? '(含密钥,请妥善保管)' : '(不含密钥)'));
+ };
+ $('#cfImp').onclick = () => $('#cfImpF').click();
+ $('#cfImpF').onchange = async e => {
+ try {
+ const parsed = JSON.parse(await e.target.files[0].text());
+ const incoming = parsed.cfg || parsed;
+ if (!Object.hasOwn(PROV, incoming.prov) || ['base', 'key', 'model', 'checkpoint'].some(k => incoming[k] != null && typeof incoming[k] !== 'string')) {
+ throw Error();
+ }
+ cfgFill({ ...cfg, ...incoming, key: incoming.key || '' });
+ msg('已读入设置,点击保存后生效');
+ } catch {
+ msg('导入失败:文件格式不正确', 1);
+ }
+ e.target.value = '';
+ };
+ $('#wbDl').onclick = () => {
+ const r = W.results[W.ri];
+ if (!r) return;
+ const link = document.createElement('a');
+ link.href = U(r.after);
+ link.download = `posewear-${r.mode === 'gen' ? 'gen' : 'tryon'}-${stamp(new Date(r.t))}-${String(W.ri + 1).padStart(2, '0')}.png`;
+ link.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 }];
+ render();
+ toast('已将结果设为新的人物照片');
+ };
+
+ // ---------- IndexedDB Local History ----------
+ let dbPromise;
+ const openDB = () =>
+ (dbPromise ||= new Promise((resolve, reject) => {
+ const req = indexedDB.open('lk-studio', 1);
+ req.onupgradeneeded = () => req.result.createObjectStore('h', { keyPath: 't' });
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () => reject(req.error);
+ }));
+
+ const tx = async (mode, fn) => {
+ const db = await openDB();
+ return new Promise((resolve, reject) => {
+ const t = db.transaction('h', mode);
+ const store = t.objectStore('h');
+ const query = fn(store);
+ t.oncomplete = () => resolve(query && query.result);
+ t.onerror = () => reject(t.error);
+ });
+ };
+
+ 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 histUrls = [];
+ async function hist() {
+ let list;
+ try {
+ list = await tx('readonly', s => s.getAll());
+ } catch {
+ $('#wbHist').textContent = '无法读取生成记录,请检查浏览器存储权限';
+ return;
+ }
+ list.sort((a, b) => b.t - a.t);
+ histUrls.forEach(URL.revokeObjectURL);
+ histUrls = [];
+ const recent = list.slice(0, 30);
+ $('#wbHist').innerHTML = recent.length
+ ? recent
+ .map(r => {
+ const url = URL.createObjectURL(r.after);
+ histUrls.push(url);
+ const titleText = new Date(r.t).toLocaleString('zh-CN') + (r.label ? ' · ' + r.label : '');
+ const timeText = new Date(r.t).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
+ return `<button data-t="${r.t}" title="${esc(titleText)}"><img src="${url}" alt="历史结果"><span>${r.mode === 'gen' ? '生图' : '试穿'} · ${esc(timeText)}</span><i data-del="${r.t}" aria-label="删除">×</i></button>`;
+ })
+ .join('') +
+ (list.length > 30 ? `<button class="hist-more" data-go="history" title="查看全部 ${list.length} 条记录"><b>全部</b><small>${list.length}条 ↗</small></button>` : '')
+ : '';
+ W.hist = list;
+ }
+
+ $('#wbHist').onclick = async e => {
+ const delBtn = e.target.closest('[data-del]');
+ if (delBtn) {
+ e.stopPropagation();
+ const rec = (W.hist || []).find(x => x.t == delBtn.dataset.del);
+ await tx('readwrite', s => s.delete(+delBtn.dataset.del));
+ await hist();
+ if (rec) {
+ toast('已删除 1 条记录', async () => {
+ await tx('readwrite', s => s.put(rec));
+ hist();
+ });
+ }
+ return;
+ }
+ const card = e.target.closest('[data-t]');
+ if (!card) return;
+ const rec = W.hist.find(x => x.t == card.dataset.t);
+ if (rec) {
+ W.results = [rec];
+ show(0, `${(PROV[rec.prov] || { name: rec.prov }).name} · ${rec.model} · ${new Date(rec.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();
+ });
+ };
+
+ // ---------- Public Studio Integration API ----------
+ const libItem = ref => ({ kind: 'lib', k: ref.k, ai: ref.ai ?? A.ITEMS[ref.k]?.ai });
+ const fileItem = (blob, name) => ({ 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);
+ const 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.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 (garmentTypes.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;
+ const 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;
+ let 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('请核对当前服务商及模型');
+ W.view = 'board';
+ 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: opts => run({ ...opts, quick: true }),
+ cfgOpen,
+ exportBoardPng,
+ nice,
+ busy: () => !!W.busy,
+ stop: () => W.busy?.abort(),
+ configured,
+ provLabel,
+ setSel,
+ addSelection,
+ selectionPrompt: (sel, lang) => compose(undefined, selectionState(sel, lang)),
+ openPicker: (type, sink) => { pkSink = sink; picker(type); },
+ };
+
+ if (document.body.classList.contains('studio')) WB.show();
+ if (location.hash === '#studio') {
+ const resetScroll = () => scrollTo(0, 0);
+ requestAnimationFrame(resetScroll);
+ addEventListener('load', () => setTimeout(resetScroll, 0), { once: true });
+ }
+
+ addEventListener('keydown', e => {
+ const dialog = !$('#pk').hidden ? $('#pk') : !$('#cfg').hidden ? $('#cfg') : null;
+ if (!dialog) return;
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ if (dialog.id === 'pk') pkClose();
+ else 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];
+ const 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);
})();
diff --git a/src/style.css b/src/style.css
index 96cc418..aa3fe8e 100644
--- a/src/style.css
+++ b/src/style.css
@@ -1,1480 +1,7387 @@
-/* 衣姿 v6 · clean modern */
-:root{--sans:-apple-system,BlinkMacSystemFont,"PingFang SC","HarmonyOS Sans SC","Hiragino Sans GB","Microsoft YaHei","Helvetica Neue",Arial,sans-serif;
- --bg:#fff;--bg2:#fff;--sf:#f5f5f5;--sf2:#ebebeb;--tx:#111;--tx2:#555;--mu:#999;--line:#f0f0f0;--line2:#e3e3e3;--ac:#ff2442;--ac2:#e61e3a;--acs:rgba(255,36,66,.07);--ok:#21a366;--bad:#e5243b;
- --ph:#f3f3f3;--phw:#f4f4f4;--sh1:0 1px 3px rgba(0,0,0,.08);--sh2:0 4px 20px rgba(0,0,0,.08);--sh3:0 20px 60px rgba(0,0,0,.18);--out:cubic-bezier(.2,.7,.2,1);--r:14px;--w:1680px;color-scheme:light}
-[data-theme=dark]{--bg:#111;--bg2:#1b1b1b;--sf:#222;--sf2:#2c2c2c;--tx:#f2f2f2;--tx2:#bbb;--mu:#7a7a7a;--line:#262626;--line2:#333;--ac:#ff3b57;--ac2:#ff5a72;--acs:rgba(255,59,87,.12);--ph:#1e1e1e;--phw:#ececec;--sh2:0 4px 20px rgba(0,0,0,.5);--sh3:0 20px 60px rgba(0,0,0,.7);color-scheme:dark}
-*,*::before,*::after{box-sizing:border-box}html,body{overflow-x:clip}
-body{margin:0;background:var(--bg);color:var(--tx);font:14px/1.6 var(--sans);-webkit-font-smoothing:antialiased}
-::selection{background:var(--ac);color:#fff}
-h1,h2,h3,h4{font-weight:600;margin:0}a{color:inherit}img{max-width:100%}
-button,select,.btn{font:inherit;font-size:14px;font-weight:500;color:var(--tx);background:var(--sf);border:0;border-radius:99px;padding:9px 18px;cursor:pointer;transition:background .2s,color .2s,opacity .2s,transform .2s;white-space:nowrap;display:inline-flex;align-items:center;justify-content:center;gap:6px;line-height:1.3}
-button:hover,select:hover,.btn:hover{background:var(--sf2)}button:active{transform:scale(.97)}button:disabled{opacity:.45;cursor:default}
-:focus-visible{outline:2px solid var(--ac);outline-offset:2px}
-.sm{font-size:13px;padding:7px 14px}.pri{background:var(--ac);color:#fff}.pri:hover{background:var(--ac2)}
-.ghost{background:transparent;color:var(--tx2)}.ghost:hover{background:var(--sf);color:var(--tx)}
-.icon{width:40px;height:40px;padding:0;background:transparent;border-radius:50%}.icon:hover{background:var(--sf)}
-.icon svg,.fbtn svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
-.icon svg.gh{fill:currentColor;stroke:none}
-a.icon{display:inline-flex;align-items:center;justify-content:center;color:inherit;text-decoration:none}
-kbd{font:11px/1 ui-monospace,Menlo,monospace;background:var(--sf);border-radius:5px;padding:3px 6px;margin:0 2px;color:var(--tx2)}
-.skip{position:absolute;left:-999px;top:8px;z-index:200;background:var(--tx);color:var(--bg);padding:8px 14px}.skip:focus{left:12px}
-.sp{flex:1}.fine{font-size:12.5px;color:var(--mu);margin:8px 0 0}.fine.good{color:var(--ok)}.fine.bad{color:var(--bad);white-space:pre-line}
-.seg{display:inline-flex;background:var(--sf);border-radius:99px;padding:3px}.seg button{background:transparent;border-radius:99px;padding:5px 12px;font-size:12.5px;color:var(--tx2)}.seg button:hover{color:var(--tx)}.seg button.on{background:var(--bg2);color:var(--tx);box-shadow:var(--sh1)}.seg.sm button{padding:4px 11px}
-select{appearance:none;-webkit-appearance:none;padding-right:32px;background:var(--sf) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%23888' stroke-width='1.5'/%3E%3C/svg%3E") no-repeat right 13px center}
-select option{background:var(--bg2);color:var(--tx)}
-/* header */
-.top{position:sticky;top:0;z-index:30;display:flex;flex-wrap:wrap;align-items:center;gap:6px 12px;padding:10px max(24px,calc((100vw - var(--w))/2 + 24px)) 8px;background:var(--bg)}
-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}
-.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}
-
-.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}
-#q:hover{background:var(--sf2)}#q:focus{background:var(--bg2);border-color:var(--tx)}#q::placeholder{color:var(--mu)}#q::-webkit-search-cancel-button{display:none}
-.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}
-
-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 #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}
-#count{font-size:13px;color:var(--mu);margin-right:4px;white-space:nowrap}#count b{color:var(--tx);font-weight:600}
-#active{display:flex;gap:6px;overflow-x:auto;scrollbar-width:none}#active button{font-size:12.5px;padding:5px 12px;background:var(--acs);color:var(--ac)}
-#favTools{display:flex;gap:6px}
-.fbtn{font-size:13px;padding:7px 14px}.fbtn svg{width:16px;height:16px}.fbtn.on{background:var(--tx);color:var(--bg)}.fbtn b{font-weight:600;color:var(--ac)}.fbtn.on b{color:inherit}
-#sort{font-size:13px;padding:7px 32px 7px 14px}#rand{font-size:13px;padding:7px 16px}
-.filters{max-width:var(--w);margin:0 auto;padding:0 24px 14px;display:flex;flex-direction:column;gap:8px}
-.filters .frow{display:none}.filters .dh+.frow,.filters.open .frow{display:flex}
-.frow{display:flex;align-items:center;gap:8px;padding:3px 4px}
-.frow>*{flex-shrink:0}.frow label{font-size:13px;color:var(--mu);min-width:40px}
-.chip{font-size:13.5px;padding:8px 16px;background:var(--sf);color:var(--tx);font-weight:500}
-.chip:hover{background:var(--sf2)}.chip.on{background:var(--tx);color:var(--bg)}
-.chip i{font-style:normal;font-weight:400;font-size:12px;opacity:.5;margin-left:2px}
-.dh,#drawerBg{display:none!important}
-/* grid */
-.grid{max-width:var(--w);margin:0 auto;padding:6px 24px 40px;display:grid;grid-template-columns:repeat(auto-fill,minmax(232px,1fr));gap:28px 16px;transition:opacity .25s}
-.grid.fade{opacity:0}
-.card{display:flex;flex-direction:column;min-width:0;animation:rise .5s var(--out) both}
-@keyframes rise{from{opacity:0;transform:translateY(10px)}}
-.ph{position:relative;aspect-ratio:3/4;overflow:hidden;background:var(--ph);cursor:zoom-in;border-radius:16px;transition:transform .35s var(--out),box-shadow .35s}
-.card:hover .ph{transform:translateY(-2px);box-shadow:0 10px 28px rgba(0,0,0,.1)}
-.ph.pose{background:var(--phw)}
-.ph::before{content:"";position:absolute;inset:0;background:linear-gradient(100deg,transparent 30%,rgba(255,255,255,.5) 50%,transparent 70%) var(--ph);background-size:250% 100%;animation:sh 1.5s infinite linear}
-.ph.pose::before{background-color:var(--phw)}.ph.done::before{display:none}
-@keyframes sh{from{background-position:120% 0}to{background-position:-120% 0}}
-.ph img{position:relative;display:block;width:100%;height:100%;object-fit:cover;opacity:0;transition:opacity .5s,transform .6s var(--out)}
-.ph.pose img{object-fit:contain;padding:5% 4% 13%;mix-blend-mode:multiply}
-.ph img.ld{opacity:1}.card:hover .ph img.ld{transform:scale(1.02)}
-.ph.err::after{content:"加载失败 · 点击重试";position:absolute;inset:0;display:grid;place-items:center;color:var(--mu);font-size:13px}
-.badge{position:absolute;left:10px;top:10px;font-size:11.5px;font-weight:600;color:#666;background:rgba(255,255,255,.85);padding:2px 8px;border-radius:99px}
-.cbtns{position:absolute;right:10px;top:10px;display:flex;flex-direction:column;gap:8px;opacity:0;transform:scale(.9);transition:.25s var(--out)}
-.card:hover .cbtns,.cbtns:focus-within,.card.sel .cbtns{opacity:1;transform:none}
-.cbtns button{width:36px;height:36px;padding:0;background:#fff;color:#111;font-size:16px;box-shadow:0 2px 8px rgba(0,0,0,.12)}
-.cbtns button:hover{background:#fff;transform:scale(1.08)}.cbtns button.on{background:#111;color:#fff}.cbtns button[data-a=fav].on{background:#fff;color:var(--ac)}
-.try{position:absolute;left:10px;bottom:10px;background:var(--ac);color:#fff;font-size:13px;padding:8px 14px;opacity:0;transform:translateY(6px);transition:.25s var(--out);box-shadow:0 4px 12px rgba(255,36,66,.3)}
-.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 :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{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 */
-#empty{text-align:center;padding:60px 20px 100px;max-width:560px;margin:0 auto}
-.emo{font-size:40px;margin-bottom:10px}#empty h3{font-size:20px}#empty p{color:var(--tx2)}
-#sugg{display:flex;flex-wrap:wrap;gap:8px;justify-content:center;margin:18px 0 26px}
-/* tray */
-#tray{position:fixed;right:24px;bottom:24px;z-index:35;width:400px;background:var(--bg2);box-shadow:var(--sh3);border-radius:20px;animation:rise .4s var(--out);overflow:hidden}
-.tray-h{display:flex;align-items:center;gap:10px;padding:12px 12px 12px 20px}.tray-h b{font-size:15px;white-space:nowrap}.tray-h small{color:var(--mu);font-size:12px}
-#tray.min .tray-b{display:none}
-.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 [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}
-/* 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}}
-.lb-box{position:absolute;inset:32px;max-width:1320px;margin:0 auto;display:flex;background:var(--bg2);box-shadow:var(--sh3);overflow:hidden;border-radius:24px}
-.lb-img{flex:1;display:grid;place-items:center;background:var(--sf);min-width:0;position:relative;margin:12px;border-radius:16px;overflow:hidden}
-.lb-img img{max-width:100%;max-height:calc(100vh - 88px);object-fit:contain;transition:filter .3s,opacity .3s}.lb-img img.lo{filter:blur(8px)}
-[data-theme=light] .lb-img img,:root:not([data-theme=dark]) .lb-img img{mix-blend-mode:multiply}
-.spin{position:absolute;width:28px;height:28px;border:2px solid #ddd;border-top-color:var(--ac);border-radius:50%;animation:spin .8s linear infinite;opacity:0;transition:opacity .2s}.lb-img.loading .spin{opacity:1}
-@keyframes spin{to{transform:rotate(360deg)}}
-.lb-side{width:400px;flex:none;overflow:auto;padding:40px 32px 28px 20px}
-.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)}
-.acts{display:flex;flex-wrap:wrap;gap:8px;margin-top:20px}.acts a{text-decoration:none}
-.acts .pri{background:var(--tx);color:var(--bg)}.acts [data-x=try]{background:var(--ac);color:#fff;order:-1;flex:1 1 100%;padding:13px;font-size:15px}.acts [data-x=try]:hover{background:var(--ac2)}
-.lb-x{position:absolute;right:14px;top:12px;z-index:3;background:var(--sf)}.lb-nav{position:absolute;top:50%;z-index:3;font-size:24px;background:color-mix(in srgb,var(--bg2) 92%,transparent);color:var(--tx);border:1px solid var(--line2);box-shadow:var(--sh2);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);transform:translateY(-50%)}.lb-nav:hover{background:var(--bg2)}.prev{left:26px}.next{right:426px}
-/* misc */
-#toast{position:fixed;left:50%;bottom:32px;transform:translate(-50%,14px);opacity:0;background:rgba(17,17,17,.92);color:#fff;padding:11px 22px;border-radius:99px;transition:transform .35s var(--out),opacity .25s;z-index:99;pointer-events:none;font-size:13.5px;box-shadow:var(--sh2)}
-#toast.on{opacity:1;transform:translate(-50%,0)}body.tray:not(.studio) #toast{bottom:auto;top:calc(var(--hdr,72px) + 14px)}
-#toTop{position:fixed;left:24px;bottom:24px;z-index:25;background:var(--bg2);box-shadow:var(--sh2);opacity:0;pointer-events:none;transition:opacity .3s}#toTop.on{opacity:1;pointer-events:auto}
-#helpBox,#pk,#cfg{position:fixed;inset:0;z-index:70;display:grid;place-items:center;background:rgba(0,0,0,.45);padding:20px;animation:fade .2s both}
-#helpBox[hidden],#pk[hidden],#cfg[hidden],[hidden]{display:none!important}
-.hb{background:var(--bg2);padding:28px 30px;width:min(440px,100%);box-shadow:var(--sh3);border-radius:22px}.hb h3{font-size:20px;margin-bottom:14px}
-.hb dl{display:grid;grid-template-columns:auto 1fr;gap:9px 18px;margin:0 0 22px;font-size:13.5px}.hb dd{margin:0;color:var(--tx2)}.hb .pri{width:100%}
-.foot{margin-top:30px;padding:40px 24px 36px;background:var(--sf)}
-.foot p,.foot li{font-size:13px;color:var(--tx2);line-height:1.9}
-.foot h4{font-size:13px;color:var(--tx);margin-bottom:8px}.foot ul{list-style:none;padding:0;margin:0}.foot a{color:var(--tx);font-weight:500}
-::view-transition-old(root),::view-transition-new(root){animation-duration:.3s}
-/* ---------- studio ---------- */
-#studio{max-width:1320px;margin:0 auto;padding:20px 24px 40px}
-.modes{margin-top:16px}.modes button{padding:8px 20px;font-size:14px}
-.cfg{gap:10px;padding:10px 16px;background:var(--sf);flex:none}.cfg b{font-weight:600;color:var(--ac)}
-.dot{width:8px;height:8px;border-radius:50%;background:var(--mu)}.dot.on{background:var(--ok);box-shadow:0 0 0 3px rgba(33,163,102,.18)}
-.step{padding:20px;background:var(--bg2);border:1px solid var(--line);border-radius:20px;box-shadow:0 1px 2px rgba(0,0,0,.03)}
-.sh{display:flex;align-items:center;gap:10px;margin-bottom:14px}.sh i{width:24px;height:24px;flex:none;display:grid;place-items:center;border-radius:50%;background:var(--tx);color:var(--bg);font:700 12px/1 var(--sans);font-style:normal}
-.sh b{font-size:16px;font-weight:700}.sh small{font-size:12px;color:var(--mu);margin-left:auto;text-align:right}
-.row{display:flex;align-items:center;gap:8px;margin-top:12px;flex-wrap:wrap}
-.slot{display:flex;flex-direction:column;gap:8px}.slot .empty0{font-size:13px;color:var(--mu);padding:14px;background:var(--sf);border-radius:12px;text-align:center}
-.pick{display:flex;align-items:center;gap:12px;padding:8px;background:var(--sf);border-radius:14px}
-.pick img{width:56px;height:72px;object-fit:cover;background:var(--ph);border-radius:10px}.pick.pose img{object-fit:contain;background:var(--phw)}
-.pick div{flex:1;min-width:0}.pick b{display:block;font-size:14px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.pick small{color:var(--mu);font-size:12px}
-.pick button{background:var(--bg2)}.pick select{font-size:12px;padding:4px 26px 4px 10px;background-color:var(--bg2)}
-.btn input{display:none}
-textarea{width:100%;font:13.5px/1.7 var(--sans);color:var(--tx);background:var(--sf);border:1.5px solid transparent;border-radius:14px;padding:11px 14px;resize:vertical;margin-top:8px;outline:0;transition:border-color .2s,background .2s}textarea:focus{border-color:var(--tx);background:var(--bg2)}
-#wbPrompt{font-size:12.5px;color:var(--tx2)}
-.lab{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--tx2)}.lab select{font-size:13px;padding:7px 32px 7px 14px}
-.big{width:100%;padding:16px;font-size:16px;font-weight:600;margin-top:16px;border-radius:16px;box-shadow:0 8px 20px rgba(255,36,66,.25)}.big:hover{transform:translateY(-1px)}
-.stage{position:relative;min-height:600px;background:var(--sf);border-radius:14px;display:grid;place-items:center;overflow:hidden}
-.ph0{text-align:center;color:var(--mu)}.ph0 span{font-size:18px;font-weight:600;color:var(--tx2)}.ph0 span::before{content:"";display:block;width:56px;height:56px;margin:0 auto 14px;border-radius:16px;background:var(--bg2) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23ff2442' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='3' width='18' height='18' rx='4'/%3E%3Ccircle cx='9' cy='9' r='2'/%3E%3Cpath d='m21 15-5-5L5 21'/%3E%3C/svg%3E") no-repeat center/26px;box-shadow:var(--sh1)}.ph0 p{font-size:13px;margin:6px 0 0}
-.cmp{position:relative;--x:50%;width:100%;height:100%;min-height:600px;max-height:78vh;user-select:none}
-.cmp>img,.bef img{position:absolute;inset:0;width:100%;height:100%;object-fit:contain}
-.bef{position:absolute;inset:0;clip-path:inset(0 calc(100% - var(--x)) 0 0)}
-.hdl{position:absolute;top:0;bottom:0;left:var(--x);width:2px;background:#fff;pointer-events:none}
-.hdl span{position:absolute;top:50%;left:50%;width:40px;height:40px;transform:translate(-50%,-50%);border-radius:50%;background:#fff;box-shadow:var(--sh2)}
-.hdl span::before{content:"‹ ›";position:absolute;inset:0;display:grid;place-items:center;color:#111;font-size:15px;letter-spacing:2px}
-#wbRange{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:ew-resize;margin:0}
-.cmp em{position:absolute;top:14px;font-size:12px;font-style:normal;font-weight:600;color:#fff;background:rgba(0,0,0,.5);padding:4px 11px;border-radius:99px;pointer-events:none}.cmp em.l{left:14px}.cmp em.r{right:14px}
-.cmp.solo .bef,.cmp.solo .hdl,.cmp.solo input,.cmp.solo em{display:none}
-.busy{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;background:color-mix(in srgb,var(--sf) 85%,transparent);backdrop-filter:blur(6px);z-index:2}
-.busy b{font-size:16px;font-weight:600;margin-top:8px}.busy small{color:var(--mu);font-size:12.5px}.busy button{background:var(--bg2)}
-.err{position:absolute;inset:auto 16px 16px;background:var(--bg2);padding:14px 18px;z-index:3;border-radius:14px;box-shadow:var(--sh2)}.err b{color:var(--bad);font-size:15px}.err p{margin:6px 0 4px;font-size:13px;color:var(--tx2);line-height:1.7;word-break:break-word}
-.warn{margin-top:10px;font-size:12.5px;color:#b4501f;background:#fff4ea;padding:9px 14px;border-radius:12px}[data-theme=dark] .warn{background:#2a1f16;color:#f0a46a}
-.res{display:flex;gap:8px;margin-top:10px;overflow-x:auto;padding:3px}.res button{padding:0;width:64px;height:84px;flex:none;overflow:hidden;border-radius:12px}.res button.on{box-shadow:0 0 0 2.5px var(--ac)}.res img{width:100%;height:100%;object-fit:cover}
-.out-act{margin-top:12px}.out-act small{color:var(--mu);font-size:12px}#wbDl{background:var(--tx);color:var(--bg)}
-.hist{margin-top:18px;padding:4px 4px 2px}.hist .sh{margin-bottom:10px}.hist .sh b{font-size:14px}.hist .sh small{margin-left:0}.hl{display:flex;gap:8px;overflow-x:auto;padding-bottom:6px}.hl:empty::before{content:"还没有生成记录";font-size:12.5px;color:var(--mu)}
-.hl button{position:relative;flex:none;padding:0;width:80px;height:104px;overflow:hidden;background:var(--ph);border-radius:12px}.hl img{width:100%;height:100%;object-fit:cover}
-.hl span{position:absolute;left:0;right:0;bottom:0;font-size:10.5px;font-weight:400;background:rgba(0,0,0,.45);color:#fff}.hl i{position:absolute;right:4px;top:4px;width:18px;height:18px;border-radius:50%;background:rgba(0,0,0,.55);color:#fff;font-style:normal;font-size:12px;line-height:18px;display:none}.hl button:hover i{display:block}
-.persons{display:flex;gap:8px;flex-wrap:wrap}.persons:empty{display:none}
-.pp{position:relative;width:calc((100% - 16px)/3);aspect-ratio:3/4;background:var(--ph);border-radius:14px;overflow:hidden}.pp img{width:100%;height:100%;object-fit:cover}
-.pp small{position:absolute;left:6px;bottom:6px;font-size:10.5px;color:#fff;background:rgba(0,0,0,.45);padding:1px 7px;border-radius:99px}
-.x{position:absolute;right:6px;top:6px;width:24px;height:24px;padding:0;border-radius:50%;background:rgba(0,0,0,.55);color:#fff;font-size:14px}.x:hover{background:rgba(0,0,0,.75)}
-#wbChar{margin-top:14px}.sub0{font-size:12.5px;color:var(--mu);margin-bottom:8px}.chips{display:flex;flex-wrap:wrap;gap:6px}.chips .chip{font-size:13px;padding:7px 14px}
-.mt{margin:12px 0 4px}
-/* picker / settings */
-.pk-box,.cfg-box{background:var(--bg2);width:min(1000px,100%);max-height:86vh;display:flex;flex-direction:column;box-shadow:var(--sh3);border-radius:24px;overflow:hidden}
-.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:1.5px solid transparent;border-radius:99px;padding:9px 16px;outline:0;transition:border-color .18s,background .18s}
-#pkQ:focus{background:var(--bg2);border-color:var(--tx2)}
-#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{position:relative;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(auto-fit,minmax(96px,1fr));gap:8px}.prov label{cursor:pointer}.prov input{position:absolute;opacity:0}
-.prov span{display:block;background:var(--sf);border:2px solid transparent;padding:12px;border-radius:14px;height:100%;transition:.2s}.prov b{display:block;font-size:13.5px;font-weight:700}.prov small{font-size:11.5px;color:var(--mu)}
-.prov input:checked+span{border-color:var(--tx);background:var(--bg2)}.prov input:focus-visible+span{outline:2px solid var(--ac)}
-.fld{display:flex;flex-direction:column;gap:6px;font-size:13px;font-weight:600;color:var(--tx)}
-.fld input,.fld select{font:14px var(--sans);color:var(--tx);background-color:var(--sf);border:1.5px solid transparent;border-radius:12px;padding:10px 13px;outline:0;width:100%}.fld input:focus{border-color:var(--tx);background:var(--bg2)}
-.kw{display:flex;gap:6px}.kw input{flex:1}
-.tg{display:flex;gap:10px;align-items:flex-start;font-size:13px;cursor:pointer}.tg input{margin-top:3px;accent-color:var(--ac);width:16px;height:16px}.tg b{font-weight:600;display:block}.tg small{color:var(--mu);font-size:12px;line-height:1.6}
-.note{font-size:12.5px;line-height:1.75;color:var(--tx2);background:var(--sf);padding:12px 14px;border-radius:12px}.note b{display:block;color:var(--tx);font-weight:600}
-.cfg-f{display:flex;gap:8px;padding:14px 24px;border-top:1px solid var(--line)}
-/* responsive */
-@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}.lb-side{width:360px}.next{right:386px}}
-@media(max-width:860px){
- .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}
- .bar{padding:4px 12px 8px;gap:6px}.tbar{gap:6px;overflow-x:auto;scrollbar-width:none}.tbar::-webkit-scrollbar{display:none}.tbar>*{flex:none}#count{font-size:12px}.fbtn,#sort,#rand{font-size:12.5px;padding:6px 12px}#sort{padding-right:28px}
- .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: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}
- #studio{padding:14px 12px 30px}.modes{display:flex}.modes button{flex:1}
- .step{padding:16px;border-radius:18px}.stage,.cmp{min-height:420px}
- .prov{grid-template-columns:1fr 1fr}.prov label:last-child:nth-child(odd){grid-column:1/-1}.pk-g{grid-template-columns:repeat(3,1fr);padding:6px 14px 14px;gap:12px 8px}#pk,#cfg{padding:0;place-items:end stretch}.pk-box,.cfg-box{max-height:90vh;border-radius:22px 22px 0 0}
-}
-@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}
-body.studio .tools{margin-left:auto}
-.wm{display:flex;align-items:baseline;gap:7px}.wm small{font-size:12px;font-weight:600;color:var(--mu);letter-spacing:.02em}
-@media(max-width:860px){.wm small{display:none}.wm b{font-size:17px}}
-@media(max-width:360px){
- .top .wm{display:none}
- #q{padding-inline:32px}
- .sic{left:10px}
-}
-@media(max-width:860px){.wm small{display:none}.wm b{font-size:17px}}
-/* ---------- v7 studio polish ---------- */
-body.studio{background:#fafafa}[data-theme=dark] body.studio,body.studio[data-x]{background:var(--bg)}
-body.studio .top{background:#fafafa}[data-theme=dark] body.studio .top{background:var(--bg)}
-#studio{max-width:1360px;padding:12px 24px 40px}
-.modes{margin:0;background:#ececec;padding:3px}[data-theme=dark] .modes{background:var(--sf)}.modes button{padding:7px 18px;font-size:13.5px;font-weight:600}
-.cfg{background:var(--bg2);box-shadow:var(--sh1)}
-.step{border:0;box-shadow:0 1px 3px rgba(0,0,0,.05),0 0 0 1px rgba(0,0,0,.03);padding:18px;transition:box-shadow .25s}
-.step:hover{box-shadow:0 4px 16px rgba(0,0,0,.06),0 0 0 1px rgba(0,0,0,.03)}
-.sh{margin-bottom:12px}.sh i{background:var(--sf2);color:var(--tx2);transition:background .2s}
-.step.done .sh i{background:var(--ok);color:#fff;font-size:0}.step.done .sh i::before{content:"✓";font-size:13px;font-weight:700}
-.sh b{font-size:15px}
-.slot .empty0{display:flex;align-items:center;gap:12px;text-align:left;padding:12px 14px;border-radius:14px;color:var(--mu)}
-.pick{position:relative;padding:8px 10px 8px 8px;background:var(--sf);transition:background .2s}.pick:hover{background:var(--sf2)}
-.pick img{width:52px;height:68px;border-radius:10px;box-shadow:var(--sh1)}
-.rmx{width:26px;height:26px;padding:0;font-size:15px;background:var(--bg2);color:var(--tx2);box-shadow:var(--sh1);opacity:.55;transition:opacity .2s,background .2s}.pick:hover .rmx,.rmx:focus-visible{opacity:1}.rmx:hover{background:var(--ac);color:#fff}
-.persons .pp{box-shadow:var(--sh1)}
-/* 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}
-.cfgchip{font-size:12px;padding:6px 12px;gap:7px;background:var(--sf)}
-.gobar .big{margin:0;border-radius:14px;padding:15px}
-/* output */
-.stage{min-height:620px;background:var(--sf);border-radius:16px}
-.ph0 span{font-size:17px}.ph0 span::before{display:none}.ph0 p{line-height:1.8}
-.busy{background:var(--sf);backdrop-filter:none;z-index:2;isolation:isolate}
-.skel0{position:absolute;inset:24px;margin:auto;max-width:420px;border-radius:16px;background:linear-gradient(100deg,#ececec 30%,#f8f8f8 50%,#ececec 70%);background-size:250% 100%;animation:sh 1.4s infinite linear;z-index:-1;opacity:.9}
-[data-theme=dark] .skel0{background-image:linear-gradient(100deg,#222 30%,#2c2c2c 50%,#222 70%)}
-.busy b,.busy small,.busy button{position:relative}
-.busy b{background:var(--bg2);padding:8px 16px;border-radius:99px;font-size:14px;box-shadow:var(--sh1)}
-.res{display:grid;grid-template-columns:repeat(auto-fill,minmax(84px,1fr));gap:8px;margin-top:12px}.res button{width:auto;height:auto;aspect-ratio:3/4;transition:transform .2s}.res button:hover{transform:translateY(-2px)}
-.out-act{background:var(--sf);border-radius:14px;padding:8px}.out-act button{background:var(--bg2)}.out-act #wbDl{background:var(--tx);color:var(--bg)}
-.hist{margin-top:16px;border-top:1px solid var(--line);padding-top:14px}
-.hl button{width:72px;height:96px;transition:transform .2s}.hl button:hover{transform:translateY(-2px)}
-/* settings */
-.cfg-box{max-height:92vh}.cfg-b{gap:12px}
-.grp{font-size:12px;font-weight:700;color:var(--mu);letter-spacing:.04em;margin-top:6px}
-.prov span{display:flex;flex-direction:column;gap:2px;padding:12px 10px}.lg{width:30px;height:30px;border-radius:9px;display:grid;place-items:center;color:#fff;font-style:normal;font-size:15px;font-weight:700;margin-bottom:6px}
-.local-lg{background:var(--tx);color:var(--bg)}.local-lg svg{width:17px;height:17px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
-#cfHelp{margin:0;padding:10px 12px;background:var(--sf);border-radius:12px;color:var(--tx2)}#cfHelp a{color:var(--ac);font-weight:600;text-decoration:none}
-@media(max-width:1180px){.gobar{position:sticky}}
-@media(max-width:860px){
- body.studio{padding-bottom:0}#studio{padding:10px 12px 20px}.modes{width:100%}
- .gobar{position:fixed;left:0;right:0;bottom:0;border-radius:20px 20px 0 0;padding:10px 12px calc(10px + env(safe-area-inset-bottom));z-index:30}
- body.studio .foot{padding-bottom:180px}.stage,.cmp{min-height:440px}
-}
-/* ---------- v8 studio app layout ---------- */
-.vh{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}
-body.studio .foot,body.studio .seoc,body.studio #toTop{display:none!important}
-#studio{max-width:none;padding:0 16px 16px;height:calc(100dvh - var(--hdr,72px))}
-.st-app{display:grid;grid-template-columns:minmax(320px,360px) minmax(0,1fr) minmax(290px,320px);gap:14px;height:100%;max-width:1680px;margin:0 auto}
-.st-l,.st-r{display:flex;flex-direction:column;gap:10px;min-height:0;overflow:auto;scrollbar-width:thin;padding:2px}
-.st-c{display:flex;flex-direction:column;min-height:0;background:var(--bg2);border-radius:20px;padding:12px;box-shadow:0 1px 3px rgba(0,0,0,.05),0 0 0 1px rgba(0,0,0,.03)}
-.modes{display:flex;width:100%}.modes button{flex:1;padding:9px 8px;font-size:13.5px}
-.st-l .lead{margin:-2px 4px 0;font-size:12.5px;color:var(--mu);line-height:1.5}
-.st-l .step{padding:12px 14px 14px;border-radius:18px}
-.sh{margin-bottom:10px;gap:8px}.sh small{margin-left:0;font-size:11.5px}.sh i{width:22px;height:22px;font-size:11.5px}
-.lnk{background:transparent;color:var(--ac);font-size:12.5px;font-weight:600;padding:3px 6px;border-radius:8px}.lnk:hover{background:var(--acs)}
-.st-l .pp{width:calc((100% - 16px)/3);aspect-ratio:4/5}
-#wbChar{margin-top:0}.sub0{display:none}#wbChar .chips{gap:6px}#wbChar .chip{padding:7px 12px;font-size:12.5px}#wbCharTxt{font-size:12.5px}
-button.empty0{width:100%;display:flex;align-items:center;gap:12px;text-align:left;padding:12px;background:var(--sf);border:1.5px dashed #dcdcdc;border-radius:14px;min-height:72px;justify-content:flex-start;white-space:normal}
-button.empty0>span{flex:1;min-width:0}
-button.empty0:hover{border-color:var(--ac);background:var(--acs)}button.empty0 b{display:block;font-size:14px;color:var(--tx)}button.empty0 small{display:block;font-size:11.5px;color:var(--mu);font-weight:400;margin-top:1px}
-.slot{gap:6px}.st-l .pick{padding:6px 8px 6px 6px;gap:10px}.st-l .pick img{width:42px;height:54px;border-radius:8px}.st-l .pick b{font-size:13px}.st-l .pick small{font-size:11.5px}
-#wbPo{max-height:196px;overflow:auto}.r3{margin-top:8px}.r3:not(:has(:not([hidden]):not(.sp))){display:none}
-/* right column */
-.st-r .cfg{width:100%;justify-content:flex-start;padding:11px 14px;border-radius:14px}.st-r .cfg b{margin-left:auto}
-.quick,.adv,.st-r .hist{background:var(--bg2);border-radius:16px;padding:12px 14px;box-shadow:0 1px 3px rgba(0,0,0,.05),0 0 0 1px rgba(0,0,0,.03);margin:0;border:0}
-.lab0{font-size:12px;font-weight:700;color:var(--mu);margin-bottom:8px}.quick .chips .chip{padding:6px 11px;font-size:12.5px}
-.q2{margin-top:10px}.q2 .row{margin:0;gap:10px;flex-wrap:nowrap}.q2 .lab{font-size:12.5px}.q2 select{padding:6px 28px 6px 12px;font-size:12.5px}
-.adv summary{cursor:pointer;list-style:none;display:flex;align-items:center;gap:8px;font-size:13.5px;font-weight:700}.adv summary::-webkit-details-marker{display:none}
-.adv summary::after{content:"";margin-left:auto;width:7px;height:7px;border-right:1.8px solid var(--mu);border-bottom:1.8px solid var(--mu);transform:rotate(45deg) translateY(-2px);transition:transform .2s}.adv[open] summary::after{transform:rotate(-135deg)}
-.adv summary small{font-size:11.5px;color:var(--mu);font-weight:400}.adv-b{margin-top:10px}.adv-b .mt{margin:0 0 4px}.adv-b textarea{font-size:12.5px}#wbPrompt{max-height:180px}
-.st-r .hist .sh{margin-bottom:8px}.st-r .hist .sh small{display:none}.st-r .hl button{width:54px;height:72px;border-radius:10px}.st-r .hl:empty::before{content:"生成后会保存在这里(仅本机)"}
-.st-r>.sp{flex:1 1 0;min-height:0}
-.st-r .gobar{position:static;box-shadow:0 8px 30px rgba(0,0,0,.08),0 0 0 1px rgba(0,0,0,.04);background:var(--bg2)}
-.cfgchip{display:none}
-.gobar .big:disabled{background:#f1f1f1;color:#aaa;box-shadow:none;opacity:1;cursor:not-allowed}[data-theme=dark] .gobar .big:disabled{background:#2a2a2a;color:#666}
-/* center */
-.st-c .stage{flex:1;min-height:0;border-radius:14px}
-.st-c .cmp{min-height:0;max-height:none;height:100%}
-.st-c .res{display:flex;margin-top:10px;overflow-x:auto}.st-c .res button{width:56px;height:74px;flex:none;aspect-ratio:auto}
-.st-c .out-act{margin-top:10px}.st-c .warn{margin-top:10px}
-.ph0 p{font-size:12.5px}
-@media(max-width:1180px) and (min-width:861px){.st-app{grid-template-columns:300px minmax(0,1fr) 270px;gap:10px}#studio{padding:0 10px 10px}}
-@media(min-width:861px){body.studio{overflow:hidden}}
-@media(max-width:860px){
- #studio{height:auto;padding:6px 10px 150px}.st-app{grid-template-columns:1fr;height:auto}.st-l,.st-r{overflow:visible}.st-c{min-height:460px}.st-c .stage{min-height:420px}
- .st-r .gobar{position:fixed;left:0;right:0;bottom:0;z-index:30;border-radius:20px 20px 0 0;padding:10px 12px calc(10px + env(safe-area-inset-bottom))}.cfgchip{display:inline-flex}.st-r .cfg{display:none}
-}
-.st-r .hl span{display:none}
-@media(max-width:860px){.st-c{order:-1}.st-l{order:-2}}
-/* ===== v8 motion & features ===== */
-.pt{position:fixed;width:6px;height:6px;border-radius:50%;pointer-events:none;z-index:200}
-.flyimg{position:fixed;z-index:200;object-fit:cover;pointer-events:none;box-shadow:0 10px 30px rgba(0,0,0,.2);will-change:transform}
-.cbtns button,.chip,.fbtn,.seg button,button{transition:transform .18s cubic-bezier(.16,1,.3,1),background-color .2s,color .2s,box-shadow .2s,opacity .2s}
-button:active:not(:disabled){transform:scale(.96)}
-#top{transition:box-shadow .3s,background-color .3s}body.scrolled #top{box-shadow:0 1px 0 rgba(0,0,0,.06),0 8px 24px rgba(0,0,0,.04);background:rgba(255,255,255,.82);-webkit-backdrop-filter:saturate(180%) blur(16px);backdrop-filter:saturate(180%) blur(16px)}
-[data-theme=dark] body.scrolled #top{background:rgba(17,17,17,.8)}
-.ph img{transition:opacity .5s cubic-bezier(.16,1,.3,1),transform .7s cubic-bezier(.16,1,.3,1),filter .6s}.ph img:not(.ld){opacity:0;transform:scale(1.04);filter:blur(10px)}
-.ph:not(.done){background:linear-gradient(100deg,#f2f2f2 30%,#fafafa 50%,#f2f2f2 70%) 0 0/300% 100%;animation:shim 1.4s linear infinite}@keyframes shim{to{background-position:-150% 0}}
-/* batch */
-#batchBtn.on{background:#111;color:#fff}
-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{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)}}
-@media(max-width:760px){#bbar{left:8px;right:8px;transform:none;bottom:8px;overflow-x:auto;border-radius:18px}@keyframes bup{from{opacity:0;transform:translateY(24px)}}#bbar [data-b=all]{display:none}}
-/* 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: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: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}
-/* 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 */
-.step.done .sh i{animation:ck .5s cubic-bezier(.34,1.56,.64,1)}@keyframes ck{0%{transform:scale(.4)}100%{transform:none}}
-.st-l .pick,.st-l #wbPersons>*{animation:slotin .45s cubic-bezier(.16,1,.3,1) both}@keyframes slotin{from{opacity:0;transform:translateY(6px) scale(.96)}}
-#wbGo{position:relative;overflow:hidden}
-#wbGo .ring{display:inline-block;width:16px;height:16px;border-radius:50%;border:2px solid rgba(255,255,255,.35);border-top-color:#fff;margin-right:8px;vertical-align:-3px;animation:spin .8s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}
-@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}}
-body.batch .card .badge,body.batch .card .angs{display:none}
-@media(max-width:760px){#bbar{gap:4px;padding:6px 6px 6px 14px;overflow:visible}#bbar b{margin-right:2px;font-size:12.5px}#bbar button{padding:7px 9px;font-size:12px}#batchBtn{font-size:0;gap:0;padding:0 10px}#batchBtn svg{margin:0}}
-/* ===== v9 去 AI 味 ===== */
-.mark{background:none;color:var(--ac);width:30px;height:30px;border-radius:0}.mark svg{width:30px;height:30px;display:block}
-@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 :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}
-.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)}
-.ph img{aspect-ratio:3/4;height:auto}
-body.none0 #favTools,body.none0 #fBtn,body.none0 #sort,body.none0 #batchBtn,body.none0 #clrRec,body.none0 #active,body.none0 #count,body.none0 #filters{display:none!important}
-.mdl{position:fixed;inset:0;z-index:80;display:grid;place-items:center;background:rgba(0,0,0,.45);padding:20px;animation:fade .2s both}
-.mdl .hb p{color:var(--tx2);font-size:14px;line-height:1.75;margin:0 0 18px}.mdl .row{display:flex;gap:10px;justify-content:flex-end}.mdl .hb .pri{width:auto}
-.pl{margin:0 0 18px;padding-left:18px;font-size:13.5px;line-height:1.75;color:var(--tx2)}.pl li{margin-bottom:8px}.pl b{color:var(--tx)}
-.cnote{font-size:12.5px;color:var(--mu);margin:18px 0 0;text-align:center}
-.lnkb{background:none;border:0;padding:0 0 0 6px;color:var(--tx);text-decoration:underline;font-size:inherit;cursor:pointer}
-.badge.rk{background:#111;color:#fff}
-.badge.age{left:58px;background:var(--ac);color:#fff}
-.sub.dim{margin-top:1px}
-
-.ph.depth{background:#141414}
-.ph.depth img{object-fit:contain;mix-blend-mode:normal;padding:0;background:#141414}
-.ph .miss{display:none}
-.ph.err{position:relative;inset:auto;padding:0;background:var(--ph);box-shadow:none;z-index:auto}
-.ph.depth.err{background:#141414}
-.ph.depth.err::after{content: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: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)}
-.asw .trk{position:relative;width:30px;height:18px;border-radius:99px;background:#d6d6d6;transition:background .25s var(--out)}
-.asw .kn{position:absolute;left:2px;top:2px;width:14px;height:14px;border-radius:50%;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.25);transition:transform .3s var(--out)}
-.asw[aria-checked=true]{color:var(--ac);border-color:rgba(255,36,66,.35)}.asw[aria-checked=true] .trk{background:var(--ac)}.asw[aria-checked=true] .kn{transform:translateX(12px)}
-.asw:active .kn{width:17px}.asw[aria-checked=true]:active .kn{transform:translateX(9px)}
-[data-theme=dark] .asw .trk{background:#444}[data-theme=dark] .asw{border-color:#333}
-@media(max-width:760px){.asw{height:30px;padding:0 8px 0 5px;margin-right:2px;font-size:12px;gap:5px}.asw .trk{width:26px;height:16px}.asw .kn{width:12px;height:12px}.asw[aria-checked=true] .kn{transform:translateX(10px)}}
-/* v11: toast undo */
-#toast{display:flex;align-items:center;gap:14px}#toast.act{pointer-events:auto;padding-right:8px}
-#toast button{background:rgba(255,255,255,.14);color:#fff;border-radius:99px;padding:5px 12px;font-size:13px;font-weight:600;min-height:0}#toast button:hover{background:rgba(255,255,255,.24)}
-/* v11: recent groups / remove */
-.rgrp{grid-column:1/-1;margin:10px 0 -12px;font-size:13px;font-weight:600;color:var(--tx2);letter-spacing:.02em}.rgrp:first-child{margin-top:0}
-.unrec{position:absolute;left:8px;top:8px;z-index:3;width:28px;height:28px;padding:0;border-radius:50%;background:rgba(255,255,255,.92);color:#333;font-size:12px;box-shadow:0 2px 8px rgba(0,0,0,.12);opacity:0;transition:opacity .2s,transform .2s var(--out)}
-.card:hover .unrec,.unrec:focus-visible{opacity:1}.unrec:hover{transform:scale(1.08)}.unrec:active{transform:scale(.92)}
-@media(hover:none){.unrec{opacity:1}}
-/* v11: empty */
-.emo{display:flex;justify-content:center;margin-bottom:14px}.emo svg{width:44px;height:44px;fill:none;stroke:var(--mu);stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}
-.ego{display:flex;gap:8px;justify-content:center;flex-wrap:wrap;margin-top:22px}.ego:empty{display:none}
-/* v11: counts always visible for fav/recent */
-@media(max-width:1180px){.tabs button i#nFav,.tabs button i#nRec{display:inline}}
-/* v11: press states + focus */
-button:active:not(:disabled){transform:scale(.97)}.tabs button:active,.chip:active{transform:scale(.96)}
-:focus-visible{outline:2px solid var(--ac);outline-offset:2px}
-@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 */
-
-
-
-
-
-
-
-
-
-::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){
-
- .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}
- .chip{min-height:36px}
- #toast{max-width:calc(100vw - 32px);white-space:nowrap}
- .top{padding-left:max(12px,env(safe-area-inset-left));padding-right:max(12px,env(safe-area-inset-right))}
-}
-.mact{display:none}
-@media(max-width:760px){
-
- .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}
-}
-@media(max-width:760px){.asw{height:34px;position:relative}.asw::after,#theme::after{content:'';position:absolute;inset:-5px}#theme{position:relative}}
-.grid.gbusy{pointer-events:none}
-/* v13 */
-.cbtns button{width:40px;height:40px;font-size:18px}
-@media(max-width:760px){.cbtns button{width:36px;height:36px;font-size:15px}}
-.lb-side h2,.info h3{overflow-wrap:anywhere}
-.tray-items{max-height:132px;overflow:auto}
-#cfHelp:empty{display:none}
-#trayN{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
-#cfg:not([hidden])~#toast,body:has(#cfg:not([hidden])) #toast{bottom:calc(84px + env(safe-area-inset-bottom))}
-#wbErr .raw{margin-top:10px;font-size:12px;color:var(--tx2)}#wbErr .raw summary{cursor:pointer;width:max-content}
-#wbErr .raw pre{white-space:pre-wrap;overflow-wrap:anywhere;max-height:140px;overflow:auto;background:var(--sf);border-radius:10px;padding:8px 10px;margin:8px 0 6px;font-size:11.5px}
-#wbErr p+p.fine{margin-top:-4px}
-@keyframes hl{0%,60%{box-shadow:0 0 0 3px color-mix(in srgb,var(--ac) 35%,transparent)}100%{box-shadow:0 0 0 0 transparent}}
-#cfg .prov.hl{animation:hl 1.6s ease-out;border-radius:14px}
-#wbSentD{margin:8px 2px 0;font-size:12px;color:var(--tx2)}#wbSentD summary{cursor:pointer;width:max-content}
-#wbSentD pre{white-space:pre-wrap;overflow-wrap:anywhere;max-height:160px;overflow:auto;background:var(--sf);border-radius:10px;padding:8px 10px;margin:6px 0 0;font-size:11.5px}
-#wbHist em{position:absolute;left:4px;top:4px;font-style:normal;font-size:10px;background:rgba(0,0,0,.55);color:#fff;border-radius:6px;padding:0 4px}
-.hl button.hist-more{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:4px;font-size:11px;color:var(--mu);text-align:center;background:var(--sf);border:1px dashed var(--line2);cursor:pointer}
-.hl button.hist-more:hover{color:var(--tx);border-color:var(--ac);transform:none}
-.hl button.hist-more b{font-size:12px;display:block;color:var(--tx)}
-.hl button.hist-more small{font-size:10px;color:var(--mu);display:block}
-.grid:empty{min-height:0}
-
-.ssr .ssl{display:block;height:100%}.ssr .ph{cursor:pointer}.ssr h3 a{color:inherit;text-decoration:none}
-.seoc{max-width:var(--w);margin:0 auto;padding:28px 24px 8px;display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:18px;border-top:1px solid var(--line);font-size:13px}.seoc h4{margin:0 0 8px;font-size:13px;color:var(--mu);font-weight:600}.seoc a{display:inline-block;margin:0 12px 6px 0;color:inherit;text-decoration:none}.seoc a:hover{text-decoration:underline}
-/* ---------- history page ---------- */
-#histSec{max-width:var(--w);margin:0 auto;padding:6px 24px 60px;min-height:calc(100vh - 180px)}
-.hist-bar{position:sticky;top:calc(var(--hdr,72px) - 1px);z-index:20;padding:6px 0 10px;background:var(--bg);display:flex;align-items:center;gap:12px}
-.hist-bar .tbar{display:flex;align-items:center;gap:8px;flex:1;min-width:0}
-#histCount{font-size:13px;color:var(--mu);margin-right:4px;white-space:nowrap}#histCount b{color:var(--tx);font-weight:600}
-.hist-sel-all{display:flex;align-items:center;gap:6px;font-size:13px;color:var(--tx2);cursor:pointer;white-space:nowrap;user-select:none}
-.hist-sel-all input{width:16px;height:16px;accent-color:var(--ac);cursor:pointer}
-#histSelN{font-size:13px;color:var(--ac);font-weight:600;white-space:nowrap}#histSelN b{font-variant-numeric:tabular-nums}
-.hist-stats{font-size:12.5px;color:var(--mu);padding:0 0 10px;line-height:1.6}
-.hist-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(232px,1fr));gap:28px 16px;max-width:var(--w);margin:0;padding:0 0 40px}
-.hist-card{display:flex;flex-direction:column;min-width:0;animation:rise .5s var(--out) both}
-.hist-card .hph{position:relative;aspect-ratio:3/4;overflow:hidden;background:var(--ph);cursor:pointer;border-radius:16px;transition:transform .35s var(--out),box-shadow .35s}
-.hist-card:hover .hph{transform:translateY(-2px);box-shadow:0 10px 28px rgba(0,0,0,.1)}
-.hist-card .hph img{display:block;width:100%;height:100%;object-fit:cover;border-radius:inherit}
-.hist-card .hsel{position:absolute;left:10px;top:10px;z-index:2;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);cursor:pointer;transition:transform .25s var(--out),background .2s;appearance:none;-webkit-appearance:none}
-.hist-card .hsel:checked{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)}
-.hist-card.selected .hph{box-shadow:0 0 0 3px var(--ac)}
-.hist-card .hcbtns{position:absolute;right:10px;top:10px;display:flex;flex-direction:column;gap:8px;opacity:0;transform:scale(.9);transition:.25s var(--out);z-index:2}
-.hist-card:hover .hcbtns,.hcbtns:focus-within{opacity:1;transform:none}
-.hist-card .hcbtns button{width:36px;height:36px;padding:0;background:#fff;color:#111;font-size:16px;box-shadow:0 2px 8px rgba(0,0,0,.12);border-radius:50%}
-.hist-card .hcbtns button:hover{background:#fff;transform:scale(1.08)}
-.hist-card .hmode{position:absolute;left:10px;bottom:10px;font-size:11.5px;font-weight:600;color:#fff;background:rgba(0,0,0,.55);padding:2px 8px;border-radius:99px;z-index:1}
-.hist-card .hinfo{padding:10px 4px 0;min-width:0}
-.hist-card .hinfo h3{font-size:14.5px;font-weight:600;line-height:1.4;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
-.hist-card .hinfo .sub{font-size:12.5px;color:var(--mu);margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
-#histEmpty{text-align:center;padding:60px 20px 100px;max-width:560px;margin:0 auto}
-#histEmpty h3{font-size:20px}#histEmpty p{color:var(--tx2)}
-/* hist lightbox extras */
-.hlb-cmp{margin-top:16px;border-radius:14px;overflow:hidden;position:relative;--x:50%}
-.hlb-cmp img{display:block;width:100%;aspect-ratio:3/4;object-fit:cover}
-.hlb-cmp .hlb-bef{position:absolute;inset:0;clip-path:inset(0 calc(100% - var(--x)) 0 0)}
-.hlb-cmp .hlb-hdl{position:absolute;top:0;bottom:0;left:var(--x);width:2px;background:#fff;pointer-events:none}
-.hlb-cmp .hlb-hdl span{position:absolute;top:50%;left:50%;width:32px;height:32px;transform:translate(-50%,-50%);border-radius:50%;background:#fff;box-shadow:var(--sh2)}
-.hlb-cmp .hlb-hdl span::before{content:"‹ ›";position:absolute;inset:0;display:grid;place-items:center;color:#111;font-size:13px;letter-spacing:2px}
-.hlb-cmp input[type=range]{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:ew-resize;margin:0}
-.hlb-cmp em{position:absolute;top:10px;font-size:11px;font-style:normal;font-weight:600;color:#fff;background:rgba(0,0,0,.5);padding:3px 9px;border-radius:99px;pointer-events:none}.hlb-cmp em.l{left:10px}.hlb-cmp em.r{right:10px}
-@media(max-width:860px){
- #histSec{padding:4px 8px 30px}
- .hist-bar{padding:4px 0 8px}.hist-bar .tbar{gap:6px;flex-wrap:wrap}
- .hist-sel-all{font-size:12px}#histCount{font-size:12px}
- .hist-grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:16px 8px}
- .hist-card .hph{border-radius:12px}
- .hist-card .hcbtns{opacity:1;transform:none;right:6px;top:6px;gap:6px}.hist-card .hcbtns button{width:28px;height:28px;font-size:13px}
- .hist-card .hsel{opacity:1}
- .hist-card .hinfo{padding:7px 4px 0}.hist-card .hinfo h3{font-size:13.5px}.hist-card .hinfo .sub{font-size:11.5px}
-}
-
-/* v1.2:托盘高度上限 + 简易生图区 + 细节打磨 */
-#tray{max-height:calc(100vh - 110px);display:flex;flex-direction:column}
-#tray .tray-b{overflow-y:auto;overscroll-behavior:contain}
-.tgen{border-top:1px solid var(--line);margin-top:14px;padding-top:12px}
-.tgen-h{display:flex;align-items:center;gap:8px}.tgen-h b{font-size:14px}.tgen-h small{color:var(--mu);font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
-#tgPrompt{width:100%;box-sizing:border-box;margin-top:10px;font:13px/1.6 var(--sans);color:var(--tx);background:var(--sf);border:1px solid transparent;border-radius:12px;padding:10px 12px;resize:vertical;min-height:64px}
-#tgPrompt:focus{outline:none;border-color:var(--ac);background:var(--bg2)}
-.tgen-row{display:flex;align-items:center;gap:10px;margin-top:10px}.tgen-row label{font-size:12.5px;color:var(--mu);display:flex;align-items:center;gap:5px}
-.tgen-row select{font:13px var(--sans);color:var(--tx);background-color:var(--sf);background-position:right 10px center;border:1px solid var(--line2);border-radius:9px;padding:6px 28px 6px 10px}
-.tgen-row #tgGo{flex:1}
-.tgen-stat{font-size:12.5px;color:var(--tx2);margin:10px 0 0;line-height:1.55}
-.tgen-res{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.tgen-res:empty{margin-top:0}
-.tgen-res button{padding:0;border:0;background:none;cursor:pointer;border-radius:12px;overflow:hidden;box-shadow:0 0 0 1px rgba(0,0,0,.06)}
-.tgen-res img{width:76px;height:96px;object-fit:cover;display:block;background:var(--ph)}
-#tgView{position:fixed;inset:0;z-index:70;display:grid;place-items:center}
-#tgView[hidden]{display:none}
-#tgView .tgv-bg{position:absolute;inset:0;background:rgba(0,0,0,.6)}
-#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(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:悬浮工作台常驻入口 + 面板内添加素材 */
-#trayFab{position:fixed;right:24px;bottom:calc(24px + env(safe-area-inset-bottom));z-index:36;display:flex;align-items:center;gap:8px;font:600 13.5px var(--sans);color:var(--tx);background:var(--bg2);border:1px solid var(--line2);border-radius:999px;padding:11px 16px;box-shadow:var(--sh3);cursor:pointer}
-#trayFab:hover{border-color:var(--ac);color:var(--ac)}
-#trayFab em{font-style:normal;background:var(--ac);color:#fff;font-size:11.5px;font-weight:700;min-width:20px;height:20px;border-radius:999px;display:grid;place-items:center;padding:0 5px}
-#trayFab[hidden]{display:none}
-@media(max-width:760px){#trayFab{right:8px;bottom:calc(8px + env(safe-area-inset-bottom))}}
-.tg-add{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-bottom:10px}
-.tg-add span{font-size:12.5px;color:var(--mu);margin-right:2px}
-.tg-add button{font:12.5px var(--sans);color:var(--tx);background:var(--sf);border:1px solid var(--line2);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}
- #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),
+/* 衣姿 PoseWear · Stylesheet
+ * Single-source tokens, flattened component rules, unified responsive cascade.
+ */
+
+/* ==========================================================================
+ 1. Design Tokens & 12-Library Palette
+ ========================================================================== */
+
+:root {
+ --sans: -apple-system, BlinkMacSystemFont, "PingFang SC", "HarmonyOS Sans SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Arial, sans-serif;
+ --bg: #fff;
+ --bg2: #fff;
+ --sf: #f5f5f5;
+ --sf2: #ebebeb;
+ --tx: #111;
+ --tx2: #555;
+ --mu: #6e6e6e;
+ --line: #f0f0f0;
+ --line2: #e3e3e3;
+ --ac: #ff2442;
+ --ac2: #e61e3a;
+ --acs: rgba(255, 36, 66, .07);
+ --ok: #21a366;
+ --bad: #e5243b;
+ --ph: #f3f3f3;
+ --phw: #f4f4f4;
+ --sh1: 0 1px 3px rgba(0, 0, 0, .08);
+ --sh2: 0 4px 20px rgba(0, 0, 0, .08);
+ --sh3: 0 20px 60px rgba(0, 0, 0, .18);
+ --out: cubic-bezier(.2, .7, .2, 1);
+ --r: 14px;
+ --w: 1680px;
+ color-scheme: light;
+}
+
+[data-theme=dark] {
+ --bg: #111;
+ --bg2: #1b1b1b;
+ --sf: #222;
+ --sf2: #2c2c2c;
+ --tx: #f2f2f2;
+ --tx2: #bbb;
+ --mu: #9a9a9a;
+ --line: #262626;
+ --line2: #333;
+ --ac: #ff3b57;
+ --ac2: #ff5a72;
+ --acs: rgba(255, 59, 87, .12);
+ --ph: #1e1e1e;
+ --phw: #ececec;
+ --sh2: 0 4px 20px rgba(0, 0, 0, .5);
+ --sh3: 0 20px 60px rgba(0, 0, 0, .7);
+ color-scheme: dark;
+}
+
+/* Shared 12-library semantic accent palette (nav dots, command palette, dock/studio edges) */
+[data-type=pose], [data-tab=pose] { --cat-color: #849dbb; }
+[data-type=depth], [data-tab=depth] { --cat-color: #9689ae; }
+[data-type=costume], [data-tab=costume] { --cat-color: #be929a; }
+[data-type=anime], [data-tab=anime] { --cat-color: #b08fad; }
+[data-type=portrait], [data-tab=portrait] { --cat-color: #c49a82; }
+[data-type=expr], [data-tab=expr] { --cat-color: #a2778b; }
+[data-type=hair], [data-tab=hair] { --cat-color: #968071; }
+[data-type=dyn], [data-tab=dyn] { --cat-color: #ab7870; }
+[data-type=scene], [data-tab=scene] { --cat-color: #88a48a; }
+[data-type=light], [data-tab=light] { --cat-color: #a2b6bf; }
+[data-type=prop], [data-tab=prop] { --cat-color: #739e9c; }
+[data-type=furn], [data-tab=furn] { --cat-color: #95928e; }
+
+/* ==========================================================================
+ 2. Base Reset, Typography & Primitives
+ ========================================================================== */
+
+*, *::before, *::after {
+ box-sizing: border-box;
+}
+
+html, body {
+ overflow-x: clip;
+}
+
+body {
+ margin: 0;
+ background: var(--bg);
+ color: var(--tx);
+ font: 14px/1.6 var(--sans);
+ -webkit-font-smoothing: antialiased;
+ --dock-base: 18px;
+ --dock-edge: calc(var(--dock-base) + env(safe-area-inset-bottom));
+ --dock-limit: min(49dvh, 430px);
+}
+
+body.batch {
+ --dock-base: 82px;
+}
+
+::selection {
+ background: var(--ac);
+ color: #fff;
+}
+
+h1, h2, h3, h4 {
+ font-weight: 600;
+ margin: 0;
+}
+
+a {
+ color: inherit;
+}
+
+img {
+ max-width: 100%;
+}
+
+button, select, .btn {
+ font: inherit;
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--tx);
+ background: var(--sf);
+ border: 0;
+ border-radius: 99px;
+ padding: 9px 18px;
+ cursor: pointer;
+ transition: transform .18s cubic-bezier(.16, 1, .3, 1), background-color .2s, color .2s, box-shadow .2s, opacity .2s;
+ white-space: nowrap;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ line-height: 1.3;
+}
+
+button:hover, select:hover, .btn:hover {
+ background: var(--sf2);
+}
+
+button:active:not(:disabled) {
+ transform: scale(.97);
+}
+
+button:disabled {
+ opacity: .45;
+ cursor: default;
+}
+
+:focus-visible {
+ outline: 2px solid var(--ac);
+ outline-offset: 2px;
+}
+
+:is(#q, #pkQ, #tgPrompt, .fld input, .fld select, .phk, summary):focus-visible,
+button:focus-visible,
+a:focus-visible,
+select:focus-visible {
+ outline: 2px solid var(--tx);
+ outline-offset: 2px;
+}
+
+.sm {
+ font-size: 13px;
+ padding: 7px 14px;
+}
+
+.pri {
+ background: var(--ac);
+ color: #fff;
+}
+
+.pri:hover {
+ background: var(--ac2);
+}
+
+.ghost {
+ background: transparent;
+ color: var(--tx2);
+}
+
+.ghost:hover {
+ background: var(--sf);
+ color: var(--tx);
+}
+
+.icon {
+ width: 40px;
+ height: 40px;
+ padding: 0;
+ background: transparent;
+ border-radius: 50%;
+}
+
+.icon:hover {
+ background: var(--sf);
+}
+
+.icon svg, .fbtn svg {
+ width: 20px;
+ height: 20px;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.8;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+.icon svg.gh {
+ fill: currentColor;
+ stroke: none;
+}
+
+a.icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ color: inherit;
+ text-decoration: none;
+}
+
+kbd {
+ font: 11px/1 ui-monospace, Menlo, monospace;
+ background: var(--sf);
+ border-radius: 5px;
+ padding: 3px 6px;
+ margin: 0 2px;
+ color: var(--tx2);
+}
+
+.skip {
+ position: absolute;
+ left: -999px;
+ top: 8px;
+ z-index: 200;
+ background: var(--tx);
+ color: var(--bg);
+ padding: 8px 14px;
+}
+
+.skip:focus {
+ left: 12px;
+}
+
+.vh {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+}
+
+.sp {
+ flex: 1;
+}
+
+.fine {
+ font-size: 12.5px;
+ color: var(--mu);
+ margin: 8px 0 0;
+}
+
+.fine.good {
+ color: var(--ok);
+}
+
+.fine.bad {
+ color: var(--bad);
+ white-space: pre-line;
+}
+
+.seg {
+ display: inline-flex;
+ background: var(--sf);
+ border-radius: 99px;
+ padding: 3px;
+}
+
+.seg button {
+ background: transparent;
+ border-radius: 99px;
+ padding: 5px 12px;
+ font-size: 12.5px;
+ color: var(--tx2);
+}
+
+.seg button:hover {
+ color: var(--tx);
+}
+
+.seg button.on {
+ background: var(--bg2);
+ color: var(--tx);
+ box-shadow: var(--sh1);
+}
+
+.seg.sm button {
+ padding: 4px 11px;
+}
+
+select {
+ appearance: none;
+ -webkit-appearance: none;
+ padding-right: 32px;
+ background: var(--sf) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%23888' stroke-width='1.5'/%3E%3C/svg%3E") no-repeat right 13px center;
+}
+
+select option {
+ background: var(--bg2);
+ color: var(--tx);
+}
+
+textarea {
+ width: 100%;
+ font: 13.5px/1.7 var(--sans);
+ color: var(--tx);
+ background: var(--sf);
+ border: 1.5px solid transparent;
+ border-radius: 14px;
+ padding: 11px 14px;
+ resize: vertical;
+ margin-top: 8px;
+ outline: 0;
+ transition: border-color .2s, background .2s;
+}
+
+textarea:focus {
+ border-color: var(--tx);
+ background: var(--bg2);
+}
+
+.btn input {
+ display: none;
+}
+
+.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;
+}
+
+[hidden] {
+ display: none !important;
+}
+
+::view-transition-old(root),
+::view-transition-new(root) {
+ animation-duration: .16s !important;
+ animation-timing-function: cubic-bezier(.2, .7, .2, 1);
+}
+
+/* ==========================================================================
+ 3. Header, Navigation Popovers & Footer
+ ========================================================================== */
+
+.top {
+ position: sticky;
+ top: 0;
+ z-index: 30;
+ display: grid;
+ grid-template-columns: auto auto minmax(9rem, 1fr) auto;
+ grid-template-areas: "brand nav search tools";
+ align-items: center;
+ gap: 6px clamp(12px, 2.4vw, 40px);
+ padding: 12px max(24px, calc((100vw - var(--w)) / 2 + 24px));
+ background: var(--bg);
+ transition: box-shadow .3s, background-color .3s;
+}
+
+body.scrolled #top {
+ box-shadow: 0 1px 0 rgba(0, 0, 0, .06), 0 8px 24px rgba(0, 0, 0, .04);
+ background: rgba(255, 255, 255, .82);
+ -webkit-backdrop-filter: saturate(180%) blur(16px);
+ backdrop-filter: saturate(180%) blur(16px);
+}
+
+[data-theme=dark] body.scrolled #top {
+ background: rgba(17, 17, 17, .8);
+}
+
+.brand {
+ grid-area: brand;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ text-decoration: none;
+ flex: none;
+}
+
+.mark {
+ width: 30px;
+ height: 30px;
+ display: grid;
+ place-items: center;
+ background: none;
+ color: var(--ac);
+ border-radius: 0;
+}
+
+.mark svg {
+ width: 30px;
+ height: 30px;
+ display: block;
+}
+
+.wm {
+ display: flex;
+ align-items: baseline;
+ gap: 7px;
+}
+
+.wm b {
+ font-size: 18px;
+ font-weight: 700;
+ letter-spacing: .02em;
+}
+
+.wm small {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--mu);
+ letter-spacing: .02em;
+}
+
+.tabs {
+ grid-area: nav;
+ position: relative;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ overflow: visible;
+ padding: 0;
+ min-width: 0;
+}
+
+.tabs button {
+ background: transparent;
+ color: var(--tx2);
+ position: relative;
+ flex: none;
+}
+
+.tabs button:active,
+.chip:active {
+ transform: scale(.96);
+}
+
+.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,
+.tabs .current > .nav-trigger:hover,
+.tabs .nav-trigger.on:hover {
+ background: var(--tx);
+ color: var(--bg);
+}
+
+.tabs .nav-trigger:hover,
+.shell-menu[open] > .icon {
+ background: var(--sf);
+ color: var(--tx);
+}
+
+.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;
+}
+
+.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);
+}
+
+.library-menu button {
+ justify-content: flex-start;
+ gap: 8px;
+}
+
+.library-menu button::before {
+ content: "";
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ flex: none;
+ background: var(--cat-color, var(--line2));
+ opacity: .88;
+ transition: transform .18s var(--out), opacity .18s;
+}
+
+.library-menu button:hover::before,
+.library-menu button.on::before {
+ transform: scale(1.25);
+ opacity: 1;
+}
+
+.library-menu button > span:first-child {
+ margin-right: auto;
+}
+
+.tabs .shell-pop button:hover {
+ color: var(--tx);
+ background: var(--sf);
+}
+
+.tabs .shell-pop button.on {
+ background: var(--acs);
+ 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;
+ margin-left: 4px;
+}
+
+.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;
+}
+
+/* Search bar & suggestions */
+.top .search {
+ grid-area: search;
+ position: relative;
+ width: 100%;
+ max-width: 32rem;
+ 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 54px 11px 46px;
+ border-radius: 99px;
+ outline: 0;
+ transition: border-color .2s, background .2s;
+}
+
+#q:hover {
+ background: var(--sf2);
+}
+
+#q:focus {
+ background: var(--bg2);
+ border-color: var(--tx);
+}
+
+#q::placeholder {
+ color: var(--mu);
+}
+
+#q::-webkit-search-cancel-button {
+ display: none;
+}
+
+.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;
+}
+
+.q-kbd {
+ position: absolute;
+ right: 10px;
+ top: 50%;
+ transform: translateY(-50%);
+ height: 24px;
+ padding: 0 7px;
+ border-radius: 6px;
+ background: var(--bg2);
+ border: 1px solid var(--line2);
+ color: var(--mu);
+ font: 600 11px/1 ui-monospace, Menlo, monospace;
+ letter-spacing: .02em;
+ box-shadow: 0 1px 0 var(--line2);
+}
+
+.q-kbd:hover {
+ border-color: var(--tx2);
+ color: var(--tx);
+ background: var(--bg2);
+}
+
+.top .search:focus-within .q-kbd,
+.top .search:has(#q:not(:placeholder-shown)) .q-kbd {
+ display: none;
+}
+
+#qDone {
+ display: none;
+}
+
+#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: 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;
+}
+
+/* Header tools: 18+ switch, language, theme, notices */
+.tools {
+ grid-area: tools;
+ justify-self: end;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ flex: none;
+}
+
+body.studio .tools {
+ margin-left: auto;
+}
+
+.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);
+}
+
+.asw .trk {
+ position: relative;
+ width: 30px;
+ height: 18px;
+ border-radius: 99px;
+ background: #d6d6d6;
+ transition: background .25s var(--out);
+}
+
+.asw .kn {
+ position: absolute;
+ left: 2px;
+ top: 2px;
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: #fff;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, .25);
+ transition: transform .3s var(--out);
+}
+
+.asw[aria-checked=true] {
+ color: var(--ac);
+ border-color: rgba(255, 36, 66, .35);
+}
+
+.asw[aria-checked=true] .trk {
+ background: var(--ac);
+}
+
+.asw[aria-checked=true] .kn {
+ transform: translateX(12px);
+}
+
+.asw:active .kn {
+ width: 17px;
+}
+
+.asw[aria-checked=true]:active .kn {
+ transform: translateX(9px);
+}
+
+[data-theme=dark] .asw .trk {
+ background: #444;
+}
+
+[data-theme=dark] .asw {
+ border-color: #333;
+}
+
+.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;
+}
+
+.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);
+}
+
+[data-lang].on {
+ font-weight: 700;
+}
+
+#theme .moon {
+ display: none;
+}
+
+[data-theme=dark] #theme .sun {
+ display: none;
+}
+
+[data-theme=dark] #theme .moon {
+ display: block;
+}
+
+.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);
+}
+
+.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);
+}
+
+/* Body view visibility switches */
+body.studio .bar,
+body.studio .filters,
+body.studio #grid,
+body.studio #empty,
+body.studio #sentinel,
+body.studio .top .search,
+body.studio .foot,
+body.studio .seoc,
+body.studio #toTop,
+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;
+}
+
+body.none0 #favTools,
+body.none0 #fBtn,
+body.none0 #sort,
+body.none0 #batchBtn,
+body.none0 #clrRec,
+body.none0 #active,
+body.none0 #count,
+body.none0 #filters,
+body.none0 #sketchBtn {
+ display: none !important;
+}
+
+/* Footer & SEO index */
+.foot {
+ margin-top: 30px;
+ padding: 18px max(24px, calc((100vw - var(--w)) / 2 + 24px)) 32px;
+ border-top: 1px solid var(--line);
+ background: var(--bg);
+}
+
+.foot p, .foot li {
+ font-size: 13px;
+ color: var(--tx2);
+ line-height: 1.9;
+}
+
+.foot h4 {
+ font-size: 13px;
+ color: var(--tx);
+ margin-bottom: 8px;
+}
+
+.foot ul {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+}
+
+.foot a {
+ color: var(--tx);
+ font-weight: 500;
+}
+
+.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;
+}
+
+.seoc {
+ max-width: var(--w);
+ margin: 0 auto;
+ padding: 28px 24px 8px;
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+ gap: 18px;
+ border-top: 1px solid var(--line);
+ font-size: 13px;
+}
+
+.seoc h4 {
+ margin: 0 0 8px;
+ font-size: 13px;
+ color: var(--mu);
+ font-weight: 600;
+}
+
+.seoc a {
+ display: inline-block;
+ margin: 0 12px 6px 0;
+ color: inherit;
+ text-decoration: none;
+}
+
+.seoc a:hover {
+ text-decoration: underline;
+}
+
+.footer-index .seoc {
+ border: 0;
+ padding: 12px 0;
+}
+
+/* ==========================================================================
+ 4. Gallery Toolbar, Filter Bar, Card Grid & Batch Bar
+ ========================================================================== */
+
+.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;
+}
+
+#count {
+ font-size: 13px;
+ color: var(--mu);
+ margin-right: 4px;
+ white-space: nowrap;
+}
+
+#count b {
+ color: var(--tx);
+ font-weight: 600;
+}
+
+#active {
+ display: flex;
+ gap: 6px;
+ overflow-x: auto;
+ scrollbar-width: none;
+}
+
+#active button {
+ font-size: 12.5px;
+ padding: 5px 12px;
+ background: var(--acs);
+ color: var(--ac);
+}
+
+#favTools {
+ display: flex;
+ gap: 6px;
+}
+
+.fbtn {
+ font-size: 13px;
+ padding: 7px 14px;
+}
+
+.fbtn svg {
+ width: 16px;
+ height: 16px;
+}
+
+.fbtn.on {
+ background: var(--tx);
+ color: var(--bg);
+}
+
+.fbtn b {
+ font-weight: 600;
+ color: var(--ac);
+}
+
+.fbtn.on b {
+ color: inherit;
+}
+
+#sort {
+ font-size: 13px;
+ padding: 7px 32px 7px 14px;
+}
+
+#rand {
+ font-size: 13px;
+ padding: 7px 16px;
+ background: #d81b3a;
+}
+
+#rand:hover {
+ background: #c0142f;
+}
+
+#rand svg {
+ display: none;
+ width: 17px;
+ height: 17px;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.7;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+#sketchBtn {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 7px 13px;
+ font-size: 13px;
+ color: var(--tx);
+ background: var(--sf);
+ border: 1px solid transparent;
+}
+
+#sketchBtn:hover {
+ background: var(--sf2);
+ border-color: var(--line2);
+}
+
+#sketchBtn svg {
+ width: 15px;
+ height: 15px;
+ flex: none;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.8;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+#batchBtn.on {
+ background: #111;
+ color: #fff;
+}
+
+/* Filters */
+.filters {
+ max-width: var(--w);
+ margin: 0 auto;
+ padding: 0 24px 14px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.filters .frow {
+ display: none;
+}
+
+.filters .dh + .frow,
+.filters.open .frow {
+ display: flex;
+}
+
+.frow {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 3px 4px;
+ overflow-x: auto;
+ scrollbar-width: none;
+}
+
+.frow::-webkit-scrollbar {
+ display: none;
+}
+
+.frow > * {
+ flex-shrink: 0;
+}
+
+.frow label {
+ font-size: 13px;
+ color: var(--mu);
+ min-width: 40px;
+}
+
+.chip {
+ font-size: 13.5px;
+ padding: 8px 16px;
+ background: var(--sf);
+ color: var(--tx);
+ font-weight: 500;
+}
+
+.chip:hover {
+ background: var(--sf2);
+}
+
+.chip.on {
+ background: var(--tx);
+ color: var(--bg);
+}
+
+.chip i {
+ font-style: normal;
+ font-weight: 400;
+ font-size: 12px;
+ opacity: .75 !important;
+ color: inherit !important;
+ margin-left: 2px;
+}
+
+.chip:has(.csw) {
+ gap: 7px;
+}
+
+.csw {
+ width: 11px;
+ height: 11px;
+ border-radius: 50%;
+ flex: none;
+ background: var(--sw);
+ box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .16);
+}
+
+[data-theme=dark] .csw {
+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .22);
+}
+
+.chip.on .csw {
+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .45), 0 0 0 1px rgba(0, 0, 0, .15);
+}
+
+.dh, #drawerBg {
+ display: none !important;
+}
+
+/* Gallery Grid & Cards */
+.grid {
+ max-width: var(--w);
+ margin: 0 auto;
+ padding: 6px 24px 40px;
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(232px, 1fr));
+ align-content: start;
+ gap: 28px 16px;
+ min-height: calc(100vh - 120px);
+ transition: opacity .16s;
+}
+
+.grid.fade {
+ opacity: 0;
+}
+
+.grid.gbusy {
+ pointer-events: none;
+}
+
+.grid:empty {
+ min-height: 0;
+}
+
+.card {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ animation: rise .5s var(--out) both;
+}
+
+@keyframes rise {
+ from { opacity: 0; transform: translateY(10px); }
+}
+
+.ph {
+ position: relative;
+ aspect-ratio: 3 / 4;
+ overflow: hidden;
+ background: var(--ph);
+ cursor: zoom-in;
+ border-radius: 16px;
+ transition: transform .35s var(--out), box-shadow .35s;
+}
+
+.card:hover .ph {
+ transform: translateY(-2px);
+ box-shadow: 0 10px 28px rgba(0, 0, 0, .1);
+}
+
+.card.sel .ph {
+ box-shadow: 0 0 0 3px var(--ac);
+}
+
+.ph.pose {
+ background: var(--phw);
+}
+
+.ph.depth {
+ background: #141414;
+}
+
+.ph::before {
+ content: "";
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(100deg, transparent 30%, rgba(255, 255, 255, .5) 50%, transparent 70%) var(--ph);
+ background-size: 250% 100%;
+ animation: sh 1.5s infinite linear;
+}
+
+.ph.pose::before {
+ background-color: var(--phw);
+}
+
+.ph.done::before {
+ display: none;
+}
+
+.ph:not(.done) {
+ background: linear-gradient(100deg, #f2f2f2 30%, #fafafa 50%, #f2f2f2 70%) 0 0 / 300% 100%;
+ animation: shim 1.4s linear infinite;
+}
+
+@keyframes sh {
+ from { background-position: 120% 0; }
+ to { background-position: -120% 0; }
+}
+
+@keyframes shim {
+ to { background-position: -150% 0; }
+}
+
+.ph img {
+ position: relative;
+ display: block;
+ width: 100%;
+ height: auto;
+ aspect-ratio: 3 / 4;
+ object-fit: cover;
+ opacity: 0;
+ transition: opacity .5s cubic-bezier(.16, 1, .3, 1), transform .7s cubic-bezier(.16, 1, .3, 1), filter .6s;
+}
+
+.ph img:not(.ld) {
+ opacity: 0;
+ transform: scale(1.04);
+ filter: blur(10px);
+}
+
+.ph img.ld {
+ opacity: 1;
+}
+
+.card:hover .ph img.ld {
+ transform: scale(1.02);
+}
+
+.ph.pose img {
+ object-fit: contain;
+ padding: 5% 4% 13%;
+ mix-blend-mode: multiply;
+}
+
+.ph.depth img {
+ object-fit: contain;
+ mix-blend-mode: normal;
+ padding: 0;
+ background: #141414;
+}
+
+.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-offset: -3px;
+}
+
+.ph .badge,
+.ph .angs,
+.ph .cbtns,
+.ph .try {
+ z-index: 1;
+}
+
+.ph .miss,
+.ph .flip-previous {
+ display: none;
+}
+
+.ph.err {
+ position: relative;
+ inset: auto;
+ padding: 0;
+ background: var(--ph);
+ box-shadow: none;
+ z-index: auto;
+}
+
+.ph.err::after {
+ content: "加载失败 · 点击重试";
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ color: var(--mu);
+ font-size: 13px;
+}
+
+html:lang(en) .ph.err::after {
+ content: "Image unavailable · Retry";
+}
+
+html:lang(ja) .ph.err::after {
+ content: "画像を読み込めません · 再試行";
+}
+
+.ph.depth.err {
+ background: #141414;
+}
+
+.ph.depth.err::after {
+ content: 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, pose/depth flip & overlays */
+.badge {
+ position: absolute;
+ left: 10px;
+ top: 10px;
+ font-size: 11.5px;
+ font-weight: 600;
+ color: #666;
+ background: rgba(255, 255, 255, .85);
+ padding: 2px 8px;
+ border-radius: 99px;
+}
+
+.badge.rk {
+ background: #111;
+ color: #fff;
+}
+
+.badge.age {
+ left: 58px;
+ background: var(--ac);
+ color: #fff;
+}
+
+.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;
+}
+
+.card-flip .flip-hint {
+ display: none;
+ font-style: normal;
+ font-size: 11px;
+ font-weight: 600;
+ max-width: 0;
+ overflow: hidden;
+ opacity: 0;
+ transition: max-width .22s var(--out), opacity .18s;
+}
+
+.ph:has(.card-badges) .unrec {
+ top: 47px;
+}
+
+.cbtns {
+ position: absolute;
+ right: 10px;
+ top: 10px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ opacity: 0;
+ transform: scale(.9);
+ transition: .25s var(--out);
+}
+
+.card:hover .cbtns,
+.cbtns:focus-within,
+.card.sel .cbtns {
+ opacity: 1;
+ transform: none;
+}
+
+.cbtns button {
+ width: 40px;
+ height: 40px;
+ padding: 0;
+ background: #fff;
+ color: #111;
+ font-size: 18px;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, .12);
+}
+
+.cbtns button:hover {
+ background: #fff;
+ transform: scale(1.08);
+}
+
+.cbtns button.on {
+ background: #111;
+ color: #fff;
+}
+
+.cbtns button[data-a=fav].on {
+ background: #fff;
+ color: var(--ac);
+}
+
+.try {
+ position: absolute;
+ left: 10px;
+ bottom: 10px;
+ background: var(--ac);
+ color: #fff;
+ font-size: 13px;
+ padding: 8px 14px;
+ opacity: 0;
+ transform: translateY(6px);
+ transition: .25s var(--out);
+ box-shadow: 0 4px 12px rgba(255, 36, 66, .3);
+}
+
+.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: flex-start;
+ gap: 2px;
+ padding: 8px;
+ overflow-x: auto;
+ scrollbar-width: none;
+ overscroll-behavior-x: contain;
+}
+
+.angs::-webkit-scrollbar {
+ display: none;
+}
+
+.angs :is(span, button) {
+ flex: none;
+ font-size: 11.5px;
+ padding: 3px 9px;
+ color: #4b4b4b;
+ cursor: pointer;
+ border-radius: 99px;
+ background: rgba(255, 255, 255, .92);
+}
+
+.angs button {
+ min-width: 0;
+ min-height: 0;
+ font: inherit;
+ font-size: 11.5px;
+ border: 0;
+ line-height: 1.5;
+}
+
+.angs button:focus-visible {
+ outline-offset: -2px;
+}
+
+.angs :is(span, button):first-child {
+ margin-inline-start: auto;
+}
+
+.angs :is(span, button):last-child {
+ margin-inline-end: auto;
+}
+
+.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;
+ overflow-wrap: anywhere;
+}
+
+.info .sub {
+ font-size: 12.5px;
+ color: var(--mu);
+ margin-top: 2px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.sub.dim {
+ margin-top: 1px;
+}
+
+.tags {
+ display: none;
+}
+
+.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(--sf);
+ color: 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;
+}
+
+.ssr .ssl {
+ display: block;
+ height: 100%;
+}
+
+.ssr .ph {
+ cursor: pointer;
+}
+
+.ssr h3 a {
+ color: inherit;
+ text-decoration: none;
+}
+
+/* Recent date groups & remove button */
+.rgrp {
+ grid-column: 1 / -1;
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ margin: 14px 0 -10px;
+ font-size: 12.5px;
+ font-weight: 650;
+ color: var(--tx2);
+ letter-spacing: .03em;
+}
+
+.rgrp::after {
+ content: "";
+ flex: 1;
+ height: 1px;
+ background: var(--line);
+}
+
+.rgrp:first-child {
+ margin-top: 2px;
+}
+
+.unrec {
+ position: absolute;
+ left: 8px;
+ top: 8px;
+ z-index: 3;
+ width: 28px;
+ height: 28px;
+ padding: 0;
+ border-radius: 50%;
+ background: rgba(255, 255, 255, .92);
+ color: #333;
+ font-size: 12px;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, .12);
+ opacity: 0;
+ transition: opacity .2s, transform .2s var(--out);
+}
+
+.card:hover .unrec,
+.unrec:focus-visible {
+ opacity: 1;
+}
+
+.unrec:hover {
+ transform: scale(1.08);
+}
+
+.unrec:active {
+ transform: scale(.92);
+}
+
+/* Batch selection mode */
+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 {
+ display: none !important;
+}
+
+body.batch .card .badge,
+body.batch .card .angs,
+body.batch .card-badges {
+ display: none;
+}
+
+#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); }
+}
+
+/* Empty state */
+#empty {
+ text-align: center;
+ padding: 60px 20px 100px;
+ max-width: 560px;
+ margin: 0 auto;
+}
+
+.emo {
+ display: flex;
+ justify-content: center;
+ font-size: 40px;
+ margin-bottom: 14px;
+}
+
+.emo svg {
+ width: 44px;
+ height: 44px;
+ fill: none;
+ stroke: var(--mu);
+ stroke-width: 1.5;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+#empty h3 {
+ font-size: 20px;
+}
+
+#empty p {
+ color: var(--tx2);
+}
+
+#sugg {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ justify-content: center;
+ margin: 18px 0 26px;
+}
+
+.ego {
+ display: flex;
+ gap: 8px;
+ justify-content: center;
+ flex-wrap: wrap;
+ margin-top: 22px;
+}
+
+.ego:empty {
+ display: none;
+}
+
+.cta {
+ display: flex;
+ gap: 10px;
+ justify-content: center;
+ margin-top: 18px;
+}
+
+/* ==========================================================================
+ 5. Lightbox & Artist Inspection Studio
+ ========================================================================== */
+
+#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; }
+}
+
+.lb-box {
+ position: absolute;
+ inset: 32px;
+ max-width: 1320px;
+ margin: 0 auto;
+ display: flex;
+ background: var(--bg2);
+ box-shadow: var(--sh3);
+ overflow: hidden;
+ border-radius: 24px;
+}
+
+.lb-img {
+ flex: 1;
+ display: grid;
+ place-items: center;
+ background: var(--sf);
+ min-width: 0;
+ position: relative;
+ margin: 12px;
+ border-radius: 16px;
+ overflow: hidden;
+}
+
+.lb-img img {
+ max-width: 100%;
+ max-height: calc(100vh - 88px);
+ object-fit: contain;
+ transition: filter .3s, opacity .3s;
+}
+
+.lb-img img.lo {
+ filter: blur(8px);
+}
+
+[data-theme=light] .lb-img img,
+:root:not([data-theme=dark]) .lb-img img {
+ mix-blend-mode: multiply;
+}
+
+[data-theme=light] .lb-img.ext img,
+:root:not([data-theme=dark]) .lb-img.ext img,
+.lb-img.ext img {
+ mix-blend-mode: normal;
+}
+
+.lb-img[data-img-type=pose],
+.lb-img[data-img-type=pose] .lb-stage {
+ background: var(--phw);
+}
+
+:root .lb-img[data-img-type=pose] #lbImg {
+ mix-blend-mode: multiply;
+}
+
+.lb-img[data-img-type=depth],
+.lb-img[data-img-type=depth] .lb-stage {
+ background: #141414;
+}
+
+:root .lb-img[data-img-type=depth] #lbImg {
+ mix-blend-mode: normal;
+}
+
+.lb-stage {
+ position: relative;
+ display: inline-grid;
+ place-items: center;
+ max-width: 100%;
+ max-height: calc(100vh - 104px);
+ transform: translate(var(--lb-tx, 0px), var(--lb-ty, 0px)) scale(var(--lb-z, 1));
+ transform-origin: center;
+ transition: transform .24s var(--out);
+ user-select: none;
+ touch-action: pan-y;
+}
+
+.lb-stage.drag {
+ transition: none;
+ cursor: grabbing;
+}
+
+.lb-stage.zoomed:not(.drag) {
+ cursor: grab;
+ touch-action: none;
+}
+
+.lb-stage:not(.zoomed):not(.comparing) {
+ cursor: zoom-in;
+}
+
+.lb-stage #lbImg {
+ display: block;
+ max-width: 100%;
+ max-height: calc(100vh - 104px);
+ width: auto;
+ height: auto;
+ object-fit: contain;
+ transition: filter .3s, opacity .3s, transform .22s var(--out);
+}
+
+.lb-stage.flipped #lbImg,
+.lb-stage.flipped #lbPairImg {
+ transform: scaleX(-1);
+}
+
+#lbStage.gray #lbImg,
+#skFrame.gray #skImg {
+ filter: grayscale(1) contrast(1.06);
+}
+
+.lb-pair-cmp {
+ position: absolute;
+ inset: 0;
+ clip-path: inset(0 calc(100% - var(--x, 50%)) 0 0);
+ pointer-events: none;
+ overflow: hidden;
+ isolation: isolate;
+}
+
+.lb-pair-cmp[data-pair-type=depth] {
+ background: #141414;
+}
+
+.lb-pair-cmp[data-pair-type=pose] {
+ background: var(--phw);
+}
+
+.lb-pair-cmp img {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ max-height: none;
+ transition: transform .22s var(--out);
+}
+
+:root .lb-img .lb-pair-cmp[data-pair-type=depth] #lbPairImg {
+ mix-blend-mode: normal;
+}
+
+:root .lb-img .lb-pair-cmp[data-pair-type=pose] #lbPairImg {
+ mix-blend-mode: multiply;
+}
+
+.lb-pair-hdl {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: var(--x, 50%);
+ width: 2px;
+ background: rgba(255, 255, 255, .92);
+ box-shadow: 0 0 8px rgba(0, 0, 0, .45);
+ pointer-events: none;
+ z-index: 2;
+}
+
+.lb-pair-hdl span {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: 34px;
+ height: 34px;
+ transform: translate(-50%, -50%);
+ border-radius: 50%;
+ background: #fff;
+ box-shadow: 0 2px 12px rgba(0, 0, 0, .32);
+}
+
+.lb-pair-hdl span::before {
+ content: "‹ ›";
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ color: #111;
+ font-size: 13px;
+ font-weight: 700;
+ letter-spacing: 1px;
+}
+
+#lbPairRange {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ opacity: 0;
+ cursor: ew-resize;
+ z-index: 3;
+}
+
+.lb-grid {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ z-index: 2;
+ opacity: 0;
+ transition: opacity .18s;
+}
+
+.lb-grid[data-mode=thirds] {
+ opacity: 1;
+ background:
+ linear-gradient(
+ to right,
+ transparent calc(33.333% - .5px),
+ rgba(255, 255, 255, .55) calc(33.333% - .5px),
+ rgba(17, 17, 17, .38) calc(33.333% + .5px),
+ transparent calc(33.333% + 1px),
+ transparent calc(66.666% - .5px),
+ rgba(255, 255, 255, .55) calc(66.666% - .5px),
+ rgba(17, 17, 17, .38) calc(66.666% + .5px),
+ transparent calc(66.666% + 1px)
+ ),
+ linear-gradient(
+ to bottom,
+ transparent calc(33.333% - .5px),
+ rgba(255, 255, 255, .55) calc(33.333% - .5px),
+ rgba(17, 17, 17, .38) calc(33.333% + .5px),
+ transparent calc(33.333% + 1px),
+ transparent calc(66.666% - .5px),
+ rgba(255, 255, 255, .55) calc(66.666% - .5px),
+ rgba(17, 17, 17, .38) calc(66.666% + .5px),
+ transparent calc(66.666% + 1px)
+ );
+}
+
+.lb-grid[data-mode=cross] {
+ opacity: 1;
+ background:
+ linear-gradient(
+ to right,
+ transparent calc(50% - .75px),
+ rgba(255, 36, 66, .78) calc(50% - .75px),
+ rgba(255, 255, 255, .6) calc(50% + .75px),
+ transparent calc(50% + 1.5px)
+ ),
+ linear-gradient(
+ to bottom,
+ transparent calc(50% - .75px),
+ rgba(255, 36, 66, .78) calc(50% - .75px),
+ rgba(255, 255, 255, .6) calc(50% + .75px),
+ transparent calc(50% + 1.5px)
+ ),
+ linear-gradient(
+ to right,
+ transparent calc(25% - .5px),
+ rgba(128, 128, 128, .35) 25%,
+ transparent calc(25% + 1px),
+ transparent calc(75% - .5px),
+ rgba(128, 128, 128, .35) 75%,
+ transparent calc(75% + 1px)
+ ),
+ linear-gradient(
+ to bottom,
+ transparent calc(25% - .5px),
+ rgba(128, 128, 128, .35) 25%,
+ transparent calc(25% + 1px),
+ transparent calc(75% - .5px),
+ rgba(128, 128, 128, .35) 75%,
+ transparent calc(75% + 1px)
+ );
+}
+
+.lb-tools {
+ position: absolute;
+ left: 50%;
+ bottom: 14px;
+ transform: translateX(-50%);
+ z-index: 4;
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ padding: 4px;
+ border-radius: 99px;
+ background: rgba(24, 24, 28, .86);
+ border: 1px solid rgba(255, 255, 255, .14);
+ box-shadow: 0 8px 26px rgba(0, 0, 0, .24);
+ backdrop-filter: blur(10px);
+ -webkit-backdrop-filter: blur(10px);
+ max-width: calc(100% - 20px);
+}
+
+.lb-tools button {
+ min-height: 32px;
+ padding: 5px 11px;
+ border-radius: 99px;
+ background: transparent;
+ color: rgba(255, 255, 255, .86);
+ font-size: 12px;
+ font-weight: 550;
+ gap: 5px;
+}
+
+.lb-tools button svg {
+ width: 14px;
+ height: 14px;
+ flex: none;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.8;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+.lb-tools button:hover {
+ background: rgba(255, 255, 255, .14);
+ color: #fff;
+}
+
+.lb-tools button.on {
+ background: var(--ac);
+ color: #fff;
+}
+
+.lb-tools button:focus-visible {
+ outline-color: #fff;
+}
+
+.spin {
+ position: absolute;
+ width: 28px;
+ height: 28px;
+ border: 2px solid #ddd;
+ border-top-color: var(--ac);
+ border-radius: 50%;
+ animation: spin .8s linear infinite;
+ opacity: 0;
+ transition: opacity .2s;
+}
+
+.lb-img.loading .spin {
+ opacity: 1;
+}
+
+@keyframes spin {
+ to { transform: rotate(360deg); }
+}
+
+.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;
+}
+
+.lb-side {
+ width: 400px;
+ flex: none;
+ overflow: auto;
+ padding: 40px 32px 28px 20px;
+}
+
+.lb-side h2 {
+ font-size: 24px;
+ line-height: 1.35;
+ margin: 6px 0 4px;
+ font-weight: 700;
+ overflow-wrap: anywhere;
+}
+
+.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;
+}
+
+.lb-pal {
+ margin-top: 14px;
+ padding: 10px 12px 11px;
+ border-radius: 14px;
+ background: var(--sf);
+ border: 1px solid var(--line);
+}
+
+.lb-pal-h {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 8px;
+}
+
+.lb-pal-h small {
+ font-size: 11.5px;
+ font-weight: 600;
+ color: var(--tx2);
+}
+
+.lb-pal-h .mu {
+ font-weight: 400;
+ color: var(--mu);
+}
+
+.lb-pal-sw {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(56px, 1fr));
+ gap: 6px;
+}
+
+.pal-sw {
+ flex-direction: column;
+ gap: 5px;
+ padding: 5px 4px 6px;
+ border-radius: 10px;
+ background: var(--bg2);
+ border: 1px solid var(--line2);
+ transition: transform .16s var(--out), border-color .16s;
+}
+
+.pal-sw:hover {
+ transform: translateY(-2px);
+ border-color: var(--tx2);
+ background: var(--bg2);
+}
+
+.pal-sw i {
+ display: block;
+ width: 100%;
+ height: 26px;
+ border-radius: 7px;
+ background: var(--sw);
+ box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .1);
+}
+
+[data-theme=dark] .pal-sw i {
+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .14);
+}
+
+.pal-sw span {
+ font: 600 10.5px/1 ui-monospace, Menlo, monospace;
+ color: var(--tx2);
+ letter-spacing: -.01em;
+}
+
+.pal-sw.copied {
+ border-color: var(--ok);
+}
+
+.pal-sw.copied span {
+ color: var(--ok);
+}
+
+.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-h {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ margin-bottom: 8px;
+}
+
+.pbox-h small {
+ margin: 0;
+}
+
+.pbox p {
+ margin: 0 0 12px;
+ font-size: 13.5px;
+ line-height: 1.8;
+ color: var(--tx);
+}
+
+.pbox p:last-child {
+ margin-bottom: 0;
+}
+
+.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);
+}
+
+.pbox-cp {
+ padding: 4px 10px;
+ font-size: 12px;
+ gap: 5px;
+ min-height: 28px;
+}
+
+.pbox-cp svg {
+ width: 13px;
+ height: 13px;
+ flex: none;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.8;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+.pbox-cp.copied {
+ background: var(--ok) !important;
+ color: #fff !important;
+}
+
+.acts {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-top: 20px;
+}
+
+.acts a {
+ text-decoration: none;
+}
+
+.acts .pri {
+ background: var(--tx);
+ color: var(--bg);
+}
+
+.acts [data-x=try] {
+ order: -1;
+ flex: 1 1 100%;
+ padding: 13px;
+ font-size: 15px;
+}
+
+.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;
+}
+
+.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);
+}
+
+.lb-keys {
+ margin-top: 16px;
+ line-height: 1.85;
+ font-size: 11.5px;
+}
+
+.mact {
+ display: none;
+}
+
+.lb-x {
+ position: absolute;
+ right: 14px;
+ top: 12px;
+ z-index: 3;
+ background: var(--sf);
+}
+
+.lb-nav {
+ position: absolute;
+ top: 50%;
+ z-index: 3;
+ font-size: 24px;
+ background: color-mix(in srgb, var(--bg2) 92%, transparent);
+ color: var(--tx);
+ border: 1px solid var(--line2);
+ box-shadow: var(--sh2);
+ backdrop-filter: blur(8px);
+ -webkit-backdrop-filter: blur(8px);
+ transform: translateY(-50%);
+}
+
+.lb-nav:hover {
+ background: var(--bg2);
+}
+
+.prev {
+ left: 26px;
+}
+
+.next {
+ right: 426px;
+}
+
+/* ==========================================================================
+ 6. Floating Workspace Dock
+ ========================================================================== */
+
+:is(#workspaceDock, #studio) [data-type] {
+ --ref-edge: var(--cat-color);
+}
+
+:is(#workspaceDock, #studio) :is([data-type=pose], [data-type=depth]) {
+ object-fit: contain;
+}
+
+#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 [hidden] {
+ display: none !important;
+}
+
+#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;
+}
+
+#workspaceDock :is(#trayFab, .dock-foot button):focus-visible {
+ outline: 2px solid #ff526e;
+ outline-offset: 2px;
+}
+
+#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: 620 13px var(--sans);
+ box-shadow: 0 6px 20px rgba(0, 0, 0, .2), 0 1px 4px rgba(0, 0, 0, .11);
+ cursor: pointer;
+}
+
+#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;
+}
+
+#trayN {
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ min-width: 0;
+}
+
+#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;
+}
+
+#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);
+}
+
+.dock-heading-tools {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+}
+
+#trayClear {
+ font-size: 12px;
+ color: var(--tx2);
+ padding: 5px;
+}
+
+#tgResetPrompt {
+ padding: 4px 8px;
+ font-size: 11.5px;
+ min-height: 26px;
+ color: var(--tx2);
+}
+
+#tgResetPrompt:hover {
+ color: var(--tx);
+}
+
+.tray-items {
+ display: flex;
+ flex-wrap: nowrap;
+ align-items: center;
+ gap: 7px;
+ max-width: 100%;
+ max-height: 132px;
+ padding: 8px 6px 6px 1px;
+ overflow-x: auto;
+ overflow-y: hidden;
+ scroll-snap-type: x proximity;
+ scrollbar-width: thin;
+}
+
+.tray-items:empty {
+ display: none;
+}
+
+.tray-items > div {
+ position: relative;
+ flex: none;
+ scroll-snap-align: start;
+}
+
+.tray-items img {
+ width: 68px;
+ height: 86px;
+ object-fit: cover;
+ background: var(--ph);
+ display: block;
+ border: 1px solid var(--ref-edge);
+ border-radius: 9px;
+}
+
+.tray-items em {
+ position: absolute;
+ bottom: 1px;
+ left: 1px;
+ right: 1px;
+ font-size: 10px;
+ font-style: normal;
+ color: #fff;
+ 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] {
+ position: absolute;
+ right: -4px;
+ top: -5px;
+ width: 25px;
+ height: 25px;
+ padding: 0;
+ border: 2px solid var(--bg2);
+ border-radius: 50%;
+ background: var(--tx);
+ color: var(--bg);
+ font-size: 12px;
+ display: grid;
+ place-items: center;
+ cursor: pointer;
+}
+
+.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);
+}
+
+.tg-add {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ 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: 12px/1.2 var(--sans);
+ 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 {
+ white-space: pre-wrap;
+ font: 13px/1.7 var(--sans);
+ color: var(--tx2);
+ max-height: 90px;
+ overflow: auto;
+ margin: 6px 0;
+ padding: 12px 14px;
+ background: var(--sf);
+ border-radius: 12px;
+}
+
+.tray-act {
+ display: flex;
+ gap: 8px;
+ padding-bottom: 4px;
+}
+
+.tray-act .pri {
+ flex: 1;
+}
+
+#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;
+ width: 100%;
+ box-sizing: border-box;
+ margin: 3px 0 0;
+ min-height: 62px;
+ max-height: 200px;
+ font: 13px/1.6 var(--sans);
+ color: var(--tx);
+ border: 1px solid var(--line2);
+ border-radius: 12px;
+ padding: 10px 12px;
+ background: var(--sf);
+ resize: vertical;
+}
+
+#tgPrompt:focus {
+ border-color: var(--tx2);
+ background: var(--bg2);
+ outline: none;
+}
+
+.tgen-row {
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+ gap: 12px;
+ margin-top: 8px;
+}
+
+.tgen-row label {
+ font-size: 12.5px;
+ color: var(--mu);
+ display: flex;
+ align-items: center;
+ gap: 5px;
+}
+
+.tgen-row select {
+ font: 13px var(--sans);
+ color: var(--tx);
+ background-color: var(--sf);
+ background-position: right 10px center;
+ border: 1px solid var(--line2);
+ border-radius: 9px;
+ padding: 6px 28px 6px 10px;
+ min-height: 30px;
+}
+
+.tgen-stat {
+ font-size: 12.5px;
+ color: var(--tx2);
+ margin: 10px 0 0;
+ line-height: 1.55;
+}
+
+.tgen-res {
+ display: flex;
+ gap: 8px;
+ flex-wrap: nowrap;
+ overflow-x: auto;
+ margin-top: 10px;
+}
+
+.tgen-res:empty {
+ margin-top: 0;
+}
+
+.tgen-res button {
+ flex: none;
+ padding: 0;
+ border: 0;
+ background: none;
+ cursor: pointer;
+ border-radius: 12px;
+ overflow: hidden;
+ box-shadow: 0 0 0 1px rgba(0, 0, 0, .06);
+}
+
+#tgRes img {
+ width: 52px;
+ height: 64px;
+ object-fit: cover;
+ display: block;
+ background: var(--ph);
+}
+
+.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);
+}
+
+#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);
+}
+
+/* Quick result lightbox */
+#tgView {
+ position: fixed;
+ inset: 0;
+ z-index: 70;
+ display: grid;
+ place-items: center;
+}
+
+#tgView .tgv-bg {
+ position: absolute;
+ inset: 0;
+ background: rgba(0, 0, 0, .6);
+}
+
+#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;
+}
+
+/* ==========================================================================
+ 7. Full Studio Workspace (Reference Board & Generation)
+ ========================================================================== */
+
+body.studio {
+ background: #fafafa;
+}
+
+[data-theme=dark] body.studio,
+body.studio[data-x] {
+ background: var(--bg);
+}
+
+body.studio .top {
+ background: #fafafa;
+}
+
+[data-theme=dark] body.studio .top {
+ background: var(--bg);
+}
+
+#studio {
+ display: flex;
+ flex-direction: column;
+ max-width: none;
+ margin: 0 auto;
+ padding: 0 clamp(12px, 2.2vw, 36px) 20px;
+ height: calc(100dvh - var(--hdr, 72px));
+}
+
+.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-act {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-width: 0;
+}
+
+#wbClearAll {
+ padding: 6px 11px;
+ font-size: 12.5px;
+ color: var(--tx2);
+}
+
+#wbClearAll:hover {
+ color: var(--bad);
+ background: var(--acs);
+}
+
+.modes {
+ display: flex;
+ margin: 0;
+ background: var(--sf);
+ padding: 3px;
+ border-radius: 12px;
+}
+
+.modes button {
+ flex: auto;
+ border-radius: 9px;
+ padding: 8px 14px;
+ font-size: 13.5px;
+ font-weight: 600;
+ white-space: nowrap;
+}
+
+.st-app {
+ display: grid;
+ grid-template-columns: minmax(250px, .91fr) minmax(0, 1.82fr) clamp(230px, 20vw, 340px);
+ gap: clamp(12px, 1.4vw, 24px);
+ width: 100%;
+ max-width: 1680px;
+ margin: 0 auto;
+ flex: 1;
+ min-height: 0;
+}
+
+.st-l, .st-r {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ min-height: 0;
+ overflow: auto;
+ scrollbar-width: thin;
+ padding: 2px;
+}
+
+.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);
+}
+
+.sh {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 10px;
+}
+
+.st-l .sh {
+ flex-wrap: wrap;
+ gap: 4px 8px;
+ margin-bottom: 7px;
+ min-height: 28px;
+}
+
+.sh i {
+ width: 22px;
+ height: 22px;
+ flex: none;
+ display: grid;
+ place-items: center;
+ border-radius: 50%;
+ background: var(--sf2);
+ color: var(--tx2);
+ font: 700 11.5px/1 var(--sans);
+ font-style: normal;
+ transition: background .2s;
+}
+
+.step.done .sh i {
+ background: var(--ok);
+ color: #fff;
+ font-size: 0;
+ animation: ck .5s cubic-bezier(.34, 1.56, .64, 1);
+}
+
+.step.done .sh i::before {
+ content: "✓";
+ font-size: 13px;
+ font-weight: 700;
+}
+
+@keyframes ck {
+ 0% { transform: scale(.4); }
+ 100% { transform: none; }
+}
+
+.sh b {
+ font-size: 15px;
+ font-weight: 700;
+}
+
+.st-l .sh b,
+.material-extras > summary > b {
+ font-size: 14px;
+ font-weight: 650;
+}
+
+.sh small {
+ font-size: 11.5px;
+ color: var(--mu);
+ margin-left: 0;
+ text-align: right;
+}
+
+.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);
+}
+
+.lnk {
+ background: transparent;
+ color: var(--ac);
+ font-size: 12.5px;
+ font-weight: 600;
+ padding: 3px 6px;
+ border-radius: 8px;
+}
+
+.lnk:hover {
+ background: var(--acs);
+}
+
+.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);
+}
+
+.garment-step.over {
+ background: var(--acs);
+ border-radius: 10px;
+}
+
+.row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 12px;
+ flex-wrap: wrap;
+}
+
+.slot {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.primary-materials .empty0 {
+ width: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+ gap: 8px;
+ min-height: 43px;
+ padding: 8px 11px;
+ border: 1px solid transparent;
+ border-radius: 10px;
+ background: var(--sf);
+ color: var(--tx2);
+ text-align: left;
+ white-space: normal;
+}
+
+.primary-materials .empty0 > span {
+ flex: 1;
+ min-width: 0;
+}
+
+.primary-materials .empty0 b {
+ display: block;
+ font-size: 13px;
+ font-weight: 500;
+ color: inherit;
+}
+
+.primary-materials .empty0 small {
+ display: block;
+ font-size: 11.5px;
+ color: var(--mu);
+ font-weight: 400;
+ margin-top: 1px;
+}
+
+.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);
+}
+
+.pick {
+ position: relative;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ padding: 5px 7px 5px 5px;
+ background: var(--sf);
+ border-radius: 10px;
+ transition: background .2s;
+}
+
+.pick:hover {
+ background: var(--sf2);
+}
+
+.pick img {
+ width: 39px;
+ height: 48px;
+ object-fit: cover;
+ background: var(--ph);
+ border: 1px solid var(--ref-edge, var(--line2));
+ border-radius: 7px;
+ box-shadow: none;
+}
+
+.pick.pose img {
+ object-fit: contain;
+ background: var(--phw);
+}
+
+.pick div {
+ flex: 1;
+ min-width: 0;
+}
+
+.pick b {
+ display: block;
+ font-size: 13px;
+ font-weight: 600;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.pick small {
+ display: block;
+ color: var(--mu);
+ font-size: 11.5px;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+
+.pick button {
+ background: var(--bg2);
+}
+
+.pick select {
+ font-size: 12px;
+ min-width: 0;
+ max-width: 35%;
+ min-height: 30px;
+ padding: 4px 20px 4px 7px;
+ background-color: var(--bg2);
+ background-position: right 7px center;
+}
+
+.rmx {
+ flex: none;
+ width: 26px;
+ height: 26px;
+ padding: 0;
+ font-size: 15px;
+ background: var(--bg2);
+ color: var(--tx2);
+ box-shadow: none;
+ opacity: 1;
+ transition: opacity .2s, background .2s;
+}
+
+.rmx:hover {
+ background: var(--ac);
+ color: #fff;
+}
+
+.st-l .pick,
+.st-l #wbPersons > * {
+ animation: slotin .45s cubic-bezier(.16, 1, .3, 1) both;
+}
+
+@keyframes slotin {
+ from { opacity: 0; transform: translateY(6px) scale(.96); }
+}
+
+.persons {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+
+.persons:empty {
+ display: none;
+}
+
+.pp {
+ position: relative;
+ width: calc((100% - 16px) / 3);
+ aspect-ratio: 4 / 5;
+ background: var(--ph);
+ border-radius: 14px;
+ overflow: hidden;
+ box-shadow: var(--sh1);
+}
+
+.pp img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
+.pp small {
+ position: absolute;
+ left: 6px;
+ bottom: 6px;
+ font-size: 10.5px;
+ color: #fff;
+ background: rgba(0, 0, 0, .45);
+ padding: 1px 7px;
+ border-radius: 99px;
+}
+
+.x {
+ position: absolute;
+ right: 6px;
+ top: 6px;
+ width: 24px;
+ height: 24px;
+ padding: 0;
+ border-radius: 50%;
+ background: rgba(0, 0, 0, .55);
+ color: #fff;
+ font-size: 14px;
+}
+
+.x:hover {
+ background: rgba(0, 0, 0, .75);
+}
+
+#wbPo {
+ max-height: 196px;
+ overflow: auto;
+}
+
+.r3 {
+ margin-top: 8px;
+}
+
+.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;
+}
+
+.chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.chips .chip {
+ font-size: 13px;
+ padding: 7px 14px;
+}
+
+#wbChar .chip {
+ padding: 7px 12px;
+ font-size: 12.5px;
+}
+
+#wbCharTxt {
+ font-size: 12.5px;
+}
+
+/* Additional materials disclosure */
+.material-extras {
+ flex: none;
+ padding: 0 15px;
+}
+
+.material-extras[open] {
+ padding-bottom: 13px;
+}
+
+.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);
+ border: 1px solid var(--ref-edge, var(--line2));
+ border-radius: 7px;
+}
+
+.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 .slot:not(:empty) {
+ margin-top: 8px;
+}
+
+/* Studio center canvas & reference board */
+.st-c {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ background: var(--bg2);
+ 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;
+}
+
+.canvas-head #wbCanvasSwitch {
+ margin-right: auto;
+}
+
+#wbExportBoard {
+ padding: 5px 11px;
+ font-size: 12px;
+ border: 1px solid var(--line2);
+ background: var(--bg2);
+ color: var(--tx2);
+ margin-left: auto;
+}
+
+#wbExportBoard:hover {
+ color: var(--tx);
+ border-color: var(--tx2);
+ background: var(--sf);
+}
+
+.canvas-head #wbCanvasSwitch:not([hidden]) ~ #wbExportBoard {
+ margin-left: 0;
+}
+
+.stage {
+ position: relative;
+ display: grid;
+ place-items: center;
+ overflow: hidden;
+ background: var(--sf);
+}
+
+.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;
+}
+
+.st-c:has(#wbCmp:not([hidden])) #wbStage {
+ min-height: 240px;
+}
+
+.reference-board {
+ display: grid;
+ place-items: center;
+ align-content: center;
+ gap: 36px;
+ width: 100%;
+ min-width: 0;
+ padding: clamp(18px, 3.5%, 42px) clamp(18px, 4%, 48px) 68px;
+ 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 {
+ position: relative;
+ 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[data-type=pose] img {
+ background: var(--phw);
+}
+
+.board-card[data-type=depth] img {
+ background: #141414;
+}
+
+[data-theme=dark] .board-card[data-type=pose] img,
+[data-theme=dark] .pick.pose img,
+[data-theme=dark] .lb-img[data-img-type=pose] ~ .lb-side .sim img {
+ filter: brightness(.92);
+}
+
+.board-card span {
+ align-self: center;
+ padding: 6px 3px 1px;
+ color: var(--tx2);
+ font-size: 12px;
+ font-weight: 580;
+}
+
+.board-idx {
+ position: absolute;
+ top: 9px;
+ left: 9px;
+ z-index: 1;
+ min-width: 20px;
+ height: 20px;
+ padding: 0 5px;
+ border-radius: 6px;
+ background: rgba(17, 17, 17, .78);
+ color: #fff;
+ font: 700 11px/20px var(--sans);
+ font-style: normal;
+ text-align: center;
+ font-variant-numeric: tabular-nums;
+ backdrop-filter: blur(4px);
+ pointer-events: none;
+}
+
+.board-ang {
+ position: absolute;
+ right: 9px;
+ bottom: 32px;
+ z-index: 1;
+ max-width: calc(100% - 18px);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ padding: 1px 6px;
+ border-radius: 99px;
+ background: rgba(17, 17, 17, .72);
+ color: #fff;
+ font-size: 10px;
+ font-style: normal;
+ font-weight: 550;
+ pointer-events: none;
+}
+
+.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-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-actions {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+.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;
+}
+
+.board-shuffle::after {
+ content: "↻";
+ font-size: 14px;
+}
+
+/* Before/after comparison, busy & output controls */
+.cmp {
+ position: relative;
+ --x: 50%;
+ width: 100%;
+ height: 100%;
+ min-height: 0;
+ max-height: none;
+ background: var(--sf);
+ user-select: none;
+}
+
+.cmp > img,
+.bef img {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+}
+
+.bef {
+ position: absolute;
+ inset: 0;
+ clip-path: inset(0 calc(100% - var(--x)) 0 0);
+}
+
+.hdl {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: var(--x);
+ width: 2px;
+ background: #fff;
+ pointer-events: none;
+}
+
+.hdl span {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: 40px;
+ height: 40px;
+ transform: translate(-50%, -50%);
+ border-radius: 50%;
+ background: #fff;
+ box-shadow: var(--sh2);
+}
+
+.hdl span::before {
+ content: "‹ ›";
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ color: #111;
+ font-size: 15px;
+ letter-spacing: 2px;
+}
+
+#wbRange {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ opacity: 0;
+ cursor: ew-resize;
+ margin: 0;
+}
+
+#wbRange:focus-visible + em {
+ outline: 2px solid var(--ac);
+}
+
+.cmp em {
+ position: absolute;
+ top: 14px;
+ font-size: 12px;
+ font-style: normal;
+ font-weight: 600;
+ color: #fff;
+ background: rgba(0, 0, 0, .5);
+ padding: 4px 11px;
+ border-radius: 99px;
+ pointer-events: none;
+}
+
+.cmp em.l { left: 14px; }
+.cmp em.r { right: 14px; }
+
+.cmp.solo .bef,
+.cmp.solo .hdl,
+.cmp.solo input,
+.cmp.solo em {
+ display: none;
+}
+
+.busy {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ background: color-mix(in srgb, var(--bg2) 88%, transparent);
+ z-index: 2;
+ isolation: isolate;
+}
+
+.skel0 {
+ position: absolute;
+ inset: 24px;
+ margin: auto;
+ max-width: 420px;
+ border-radius: 16px;
+ background: linear-gradient(100deg, #ececec 30%, #f8f8f8 50%, #ececec 70%);
+ background-size: 250% 100%;
+ animation: sh 1.4s infinite linear;
+ z-index: -1;
+ opacity: .9;
+}
+
+[data-theme=dark] .skel0 {
+ background-image: linear-gradient(100deg, #222 30%, #2c2c2c 50%, #222 70%);
+}
+
+.busy b,
+.busy small,
+.busy button {
+ position: relative;
+}
+
+.busy b {
+ background: var(--bg2);
+ padding: 8px 16px;
+ border-radius: 99px;
+ font-size: 14px;
+ font-weight: 600;
+ margin-top: 8px;
+ box-shadow: var(--sh1);
+}
+
+.busy small {
+ color: var(--mu);
+ font-size: 12.5px;
+}
+
+.busy button {
+ background: var(--bg2);
+}
+
+#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; }
+}
+
+.err {
+ position: absolute;
+ inset: auto 16px 16px;
+ background: var(--bg2);
+ padding: 14px 18px;
+ z-index: 3;
+ border-radius: 14px;
+ box-shadow: var(--sh2);
+}
+
+.err b {
+ color: var(--bad);
+ font-size: 15px;
+}
+
+.err p {
+ margin: 6px 0 4px;
+ font-size: 13px;
+ color: var(--tx2);
+ line-height: 1.7;
+ word-break: break-word;
+}
+
+#wbErr .raw {
+ margin-top: 10px;
+ font-size: 12px;
+ color: var(--tx2);
+}
+
+#wbErr .raw summary,
+#wbSentD summary {
+ cursor: pointer;
+ width: max-content;
+}
+
+#wbErr .raw pre,
+#wbSentD pre {
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ max-height: 140px;
+ overflow: auto;
+ background: var(--sf);
+ border-radius: 10px;
+ padding: 8px 10px;
+ margin: 8px 0 6px;
+ font-size: 11.5px;
+}
+
+#wbSentD {
+ margin: 8px 2px 0;
+ font-size: 12px;
+ color: var(--tx2);
+}
+
+#wbSentD pre {
+ max-height: 160px;
+ margin: 6px 0 0;
+}
+
+#wbErr p + p.fine {
+ margin-top: -4px;
+}
+
+.warn {
+ margin-top: 10px;
+ font-size: 12.5px;
+ color: #b4501f;
+ background: #fff4ea;
+ padding: 9px 14px;
+ border-radius: 12px;
+}
+
+[data-theme=dark] .warn {
+ background: #2a1f16;
+ color: #f0a46a;
+}
+
+.st-c .out-act,
+.st-c .warn,
+.st-c .res,
+.st-c .sent {
+ margin: 8px 12px;
+}
+
+.res {
+ display: flex;
+ gap: 8px;
+ overflow-x: auto;
+ padding: 3px;
+}
+
+.res button {
+ padding: 0;
+ width: 56px;
+ height: 74px;
+ flex: none;
+ overflow: hidden;
+ border-radius: 12px;
+ transition: transform .2s;
+}
+
+.res button:hover {
+ transform: translateY(-2px);
+}
+
+.res button.on {
+ box-shadow: 0 0 0 2.5px var(--ac);
+}
+
+.res img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
+.out-act {
+ flex-wrap: wrap;
+ background: var(--sf);
+ border-radius: 14px;
+ padding: 8px;
+}
+
+.out-act small {
+ color: var(--mu);
+ font-size: 12px;
+ overflow-wrap: anywhere;
+}
+
+.out-act button {
+ background: var(--bg2);
+}
+
+.out-act #wbDl {
+ background: var(--tx);
+ color: var(--bg);
+}
+
+/* Studio right column: provider button, prompt, options, mini history, generate bar */
+.cfg {
+ gap: 10px;
+ padding: 11px 14px;
+ background: var(--bg2);
+ flex: none;
+}
+
+.cfg b {
+ font-weight: 600;
+ color: var(--ac);
+}
+
+.st-r .cfg {
+ width: 100%;
+ justify-content: flex-start;
+ border-radius: 14px;
+}
+
+.st-r .cfg b {
+ margin-left: auto;
+}
+
+.dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--mu);
+}
+
+.dot.on {
+ background: var(--ok);
+ box-shadow: 0 0 0 3px rgba(33, 163, 102, .18);
+}
+
+.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;
+}
+
+.quick,
+.adv,
+.st-r .hist {
+ background: var(--bg2);
+ padding: 12px 14px;
+ margin: 0;
+}
+
+.lab0 {
+ font-size: 12px;
+ font-weight: 700;
+ color: var(--mu);
+ margin-bottom: 8px;
+}
+
+.quick .chips .chip {
+ padding: 6px 11px;
+ font-size: 12.5px;
+}
+
+.q2 {
+ margin-top: 10px;
+}
+
+.q2 .row {
+ margin: 0;
+ gap: 10px;
+ flex-wrap: nowrap;
+}
+
+.lab {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 12.5px;
+ color: var(--tx2);
+}
+
+.q2 select {
+ padding: 6px 28px 6px 12px;
+ font-size: 12.5px;
+}
+
+.adv summary {
+ cursor: pointer;
+ list-style: none;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 13.5px;
+ font-weight: 700;
+}
+
+.adv summary::-webkit-details-marker {
+ display: none;
+}
+
+.adv summary::after {
+ content: "";
+ margin-left: auto;
+ width: 7px;
+ height: 7px;
+ border-right: 1.8px solid var(--mu);
+ border-bottom: 1.8px solid var(--mu);
+ transform: rotate(45deg) translateY(-2px);
+ transition: transform .2s;
+}
+
+.adv[open] summary::after {
+ transform: rotate(-135deg);
+}
+
+.adv summary small {
+ font-size: 11.5px;
+ color: var(--mu);
+ font-weight: 400;
+}
+
+.adv-b {
+ margin-top: 10px;
+}
+
+.adv-b .mt {
+ margin: 0 0 4px;
+}
+
+.adv-b textarea {
+ font-size: 12.5px;
+}
+
+.st-r .hist:has(.hl:empty) {
+ display: none;
+}
+
+.st-r .hist .sh {
+ margin-bottom: 8px;
+}
+
+.st-r .hist .sh b {
+ font-size: 14px;
+}
+
+.st-r .hist .sh small {
+ display: none;
+}
+
+.hl {
+ display: flex;
+ gap: 8px;
+ overflow-x: auto;
+ padding-bottom: 6px;
+}
+
+.st-r .hl:empty::before {
+ content: "生成后会保存在这里(仅本机)";
+ font-size: 12.5px;
+ color: var(--mu);
+}
+
+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: "生成した画像はこの端末に保存されます。";
+}
+
+.hl button {
+ position: relative;
+ flex: none;
+ padding: 0;
+ width: 54px;
+ height: 72px;
+ overflow: hidden;
+ background: var(--ph);
+ border-radius: 10px;
+ transition: transform .2s;
+}
+
+.hl button:hover {
+ transform: translateY(-2px);
+}
+
+.hl img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
+.st-r .hl span {
+ display: none;
+}
+
+.hl i {
+ position: absolute;
+ right: 4px;
+ top: 4px;
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ background: rgba(0, 0, 0, .55);
+ color: #fff;
+ font-style: normal;
+ font-size: 12px;
+ line-height: 18px;
+ display: none;
+}
+
+.hl button:hover i {
+ display: block;
+}
+
+#wbHist em {
+ position: absolute;
+ left: 4px;
+ top: 4px;
+ font-style: normal;
+ font-size: 10px;
+ background: rgba(0, 0, 0, .55);
+ color: #fff;
+ border-radius: 6px;
+ padding: 0 4px;
+}
+
+.hl button.hist-more {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 4px;
+ font-size: 11px;
+ color: var(--mu);
+ text-align: center;
+ background: var(--sf);
+ border: 1px dashed var(--line2);
+ cursor: pointer;
+}
+
+.hl button.hist-more:hover {
+ color: var(--tx);
+ border-color: var(--ac);
+ transform: none;
+}
+
+.hl button.hist-more b {
+ font-size: 12px;
+ display: block;
+ color: var(--tx);
+}
+
+.hl button.hist-more small {
+ font-size: 10px;
+ color: var(--mu);
+ display: block;
+}
+
+.st-r > .sp {
+ flex: 1 1 0;
+ min-height: 0;
+}
+
+.st-r .gobar {
+ position: sticky;
+ bottom: 0;
+ z-index: 5;
+ margin-top: auto;
+ border-radius: 20px;
+ padding: 12px;
+ background: var(--bg2);
+ box-shadow: 0 -5px 14px color-mix(in srgb, var(--bg) 75%, transparent);
+}
+
+.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;
+}
+
+.cfgchip {
+ display: none;
+ font-size: 12px;
+ padding: 6px 12px;
+ gap: 7px;
+ background: var(--sf);
+}
+
+.big {
+ width: 100%;
+ padding: 15px;
+ font-size: 16px;
+ font-weight: 600;
+ margin: 0;
+ border-radius: 14px;
+ box-shadow: none;
+}
+
+.big:hover {
+ transform: translateY(-1px);
+}
+
+.gobar .big:disabled {
+ background: #f1f1f1;
+ color: #aaa;
+ box-shadow: none;
+ opacity: 1;
+ cursor: not-allowed;
+}
+
+[data-theme=dark] .gobar .big:disabled {
+ background: #2a2a2a;
+ color: #666;
+}
+
+#wbGo {
+ position: relative;
+ overflow: hidden;
+}
+
+#wbGo .ring {
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ border: 2px solid rgba(255, 255, 255, .35);
+ border-top-color: #fff;
+ margin-right: 8px;
+ vertical-align: -3px;
+ animation: spin .8s linear infinite;
+}
+
+/* ==========================================================================
+ 8. Picker, Settings, Modals, Toast & Motion Effects
+ ========================================================================== */
+
+#helpBox, #pk, #cfg {
+ position: fixed;
+ inset: 0;
+ z-index: 70;
+ display: grid;
+ place-items: center;
+ background: rgba(0, 0, 0, .45);
+ padding: 20px;
+ animation: fade .2s both;
+}
+
+.mdl {
+ position: fixed;
+ inset: 0;
+ z-index: 80;
+ display: grid;
+ place-items: center;
+ background: rgba(0, 0, 0, .45);
+ padding: 20px;
+ animation: fade .2s both;
+}
+
+.hb {
+ background: var(--bg2);
+ padding: 28px 30px;
+ width: min(440px, 100%);
+ box-shadow: var(--sh3);
+ border-radius: 22px;
+}
+
+.hb h3 {
+ font-size: 20px;
+ margin-bottom: 14px;
+}
+
+.hb dl {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 9px 18px;
+ margin: 0 0 22px;
+ font-size: 13.5px;
+}
+
+.hb dd {
+ margin: 0;
+ color: var(--tx2);
+}
+
+.hb .pri {
+ width: 100%;
+}
+
+.mdl .hb p {
+ color: var(--tx2);
+ font-size: 14px;
+ line-height: 1.75;
+ margin: 0 0 18px;
+}
+
+.mdl .row {
+ display: flex;
+ gap: 10px;
+ justify-content: flex-end;
+}
+
+.mdl .hb .pri {
+ width: auto;
+}
+
+.pl {
+ margin: 0 0 18px;
+ padding-left: 18px;
+ font-size: 13.5px;
+ line-height: 1.75;
+ color: var(--tx2);
+}
+
+.pl li {
+ margin-bottom: 8px;
+}
+
+.pl b {
+ color: var(--tx);
+}
+
+.cnote {
+ font-size: 12.5px;
+ color: var(--mu);
+ margin: 18px 0 0;
+ text-align: center;
+}
+
+.lnkb {
+ background: none;
+ border: 0;
+ padding: 0 0 0 6px;
+ color: var(--tx);
+ text-decoration: underline;
+ font-size: inherit;
+ cursor: pointer;
+}
+
+/* Picker & provider settings modals */
+.pk-box, .cfg-box {
+ background: var(--bg2);
+ width: min(1000px, 100%);
+ max-height: 86vh;
+ display: flex;
+ flex-direction: column;
+ box-shadow: var(--sh3);
+ border-radius: 24px;
+ overflow: hidden;
+}
+
+.cfg-box {
+ width: min(580px, 100%);
+ max-height: 92vh;
+}
+
+.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;
+}
+
+#cfg .pk-h {
+ justify-content: space-between;
+}
+
+#pkQ {
+ flex: 1;
+ min-width: 0;
+ font: inherit;
+ background: var(--sf);
+ color: var(--tx);
+ border: 1.5px solid transparent;
+ border-radius: 99px;
+ padding: 9px 16px;
+ outline: 0;
+ transition: border-color .18s, background .18s;
+}
+
+#pkQ:focus {
+ background: var(--bg2);
+ border-color: var(--tx2);
+}
+
+#pkDone, #pkX, #cfgX {
+ flex: none;
+}
+
+#pkPoseTypes {
+ align-self: flex-start;
+ flex: none;
+ margin: 0 24px 10px;
+}
+
+#pkPoseTypes button {
+ min-height: 30px;
+ padding-inline: 14px;
+}
+
+.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);
+}
+
+.pk-bar {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0 24px 10px;
+ min-width: 0;
+}
+
+#pkFavOnly {
+ flex: none;
+ padding: 5px 12px;
+ font-size: 12.5px;
+ min-height: 30px;
+ border: 1px solid var(--line2);
+ background: var(--bg2);
+}
+
+#pkFavOnly.on {
+ background: var(--ac);
+ border-color: var(--ac);
+ color: #fff;
+}
+
+.pk-cats {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ overflow-x: auto;
+ scrollbar-width: none;
+ min-width: 0;
+ flex: 1;
+ padding: 1px 2px;
+}
+
+.pk-cats::-webkit-scrollbar {
+ display: none;
+}
+
+.pk-cats .chip {
+ flex: none;
+ padding: 5px 11px;
+ font-size: 12px;
+ min-height: 30px;
+}
+
+.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 {
+ position: relative;
+ 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.depth img {
+ object-fit: contain;
+}
+
+.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 button.on::after {
+ content: "";
+ position: absolute;
+ top: 7px;
+ right: 7px;
+ width: 22px;
+ height: 22px;
+ border-radius: 50%;
+ 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.2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 12 4 4 8-8'/%3E%3C/svg%3E") center / 13px no-repeat;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, .22);
+}
+
+.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: 12px;
+}
+
+.grp {
+ font-size: 12px;
+ font-weight: 700;
+ color: var(--mu);
+ letter-spacing: .04em;
+ margin-top: 6px;
+}
+
+.prov {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(96px, 1fr));
+ gap: 8px;
+}
+
+.prov label {
+ cursor: pointer;
+}
+
+.prov input {
+ position: absolute;
+ opacity: 0;
+}
+
+.prov span {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ background: var(--sf);
+ border: 2px solid transparent;
+ padding: 12px 10px;
+ border-radius: 14px;
+ height: 100%;
+ transition: .2s;
+}
+
+.prov b {
+ display: block;
+ font-size: 13.5px;
+ font-weight: 700;
+}
+
+.prov small {
+ font-size: 11.5px;
+ color: var(--mu);
+}
+
+.prov input:checked + span {
+ border-color: var(--tx);
+ background: var(--bg2);
+}
+
+.prov input:focus-visible + span {
+ outline: 2px solid var(--ac);
+}
+
+.lg {
+ width: 30px;
+ height: 30px;
+ border-radius: 9px;
+ display: grid;
+ place-items: center;
+ color: #fff;
+ font-style: normal;
+ font-size: 15px;
+ font-weight: 700;
+ margin-bottom: 6px;
+}
+
+.local-lg {
+ background: var(--tx);
+ color: var(--bg);
+}
+
+.local-lg svg {
+ width: 17px;
+ height: 17px;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.8;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+@keyframes hl {
+ 0%, 60% { box-shadow: 0 0 0 3px color-mix(in srgb, var(--ac) 35%, transparent); }
+ 100% { box-shadow: 0 0 0 0 transparent; }
+}
+
+#cfg .prov.hl {
+ animation: hl 1.6s ease-out;
+ border-radius: 14px;
+}
+
+.fld {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--tx);
+}
+
+.fld input,
+.fld select {
+ font: 14px var(--sans);
+ color: var(--tx);
+ background-color: var(--sf);
+ border: 1.5px solid transparent;
+ border-radius: 12px;
+ padding: 10px 13px;
+ outline: 0;
+ width: 100%;
+}
+
+.fld input:focus {
+ border-color: var(--tx);
+ background: var(--bg2);
+}
+
+.kw {
+ display: flex;
+ gap: 6px;
+}
+
+.kw input {
+ flex: 1;
+}
+
+.tg {
+ display: flex;
+ gap: 10px;
+ align-items: flex-start;
+ font-size: 13px;
+ cursor: pointer;
+}
+
+.tg input {
+ margin-top: 3px;
+ accent-color: var(--ac);
+ width: 16px;
+ height: 16px;
+}
+
+.tg b {
+ font-weight: 600;
+ display: block;
+}
+
+.tg small {
+ color: var(--mu);
+ font-size: 12px;
+ line-height: 1.6;
+}
+
+.note {
+ font-size: 12.5px;
+ line-height: 1.75;
+ color: var(--tx2);
+ background: var(--sf);
+ padding: 12px 14px;
+ border-radius: 12px;
+}
+
+.note b {
+ display: block;
+ color: var(--tx);
+ font-weight: 600;
+}
+
+#cfHelp {
+ margin: 0;
+ padding: 10px 12px;
+ background: var(--sf);
+ border-radius: 12px;
+ color: var(--tx2);
+}
+
+#cfHelp:empty {
+ display: none;
+}
+
+#cfHelp a {
+ color: var(--ac);
+ font-weight: 600;
+ text-decoration: 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(--sf);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}
-
-/* ---------- Craft & Artist Studio Polish ---------- */
-/* Gallery: color swatches, semantic library dots, recent date dividers, pose flip hint */
-.chip:has(.csw){gap:7px}
-.csw{width:11px;height:11px;border-radius:50%;flex:none;background:var(--sw);box-shadow:inset 0 0 0 1px rgba(0,0,0,.16)}
-[data-theme=dark] .csw{box-shadow:inset 0 0 0 1px rgba(255,255,255,.22)}
-.chip.on .csw{box-shadow:inset 0 0 0 1px rgba(255,255,255,.45),0 0 0 1px rgba(0,0,0,.15)}
-
-.library-menu button{justify-content:flex-start;gap:8px}
-.library-menu button::before{content:"";width:7px;height:7px;border-radius:50%;flex:none;background:var(--nav-dot,var(--line2));opacity:.88;transition:transform .18s var(--out),opacity .18s}
-.library-menu button:hover::before,.library-menu button.on::before{transform:scale(1.25);opacity:1}
-.library-menu button>span:first-child{margin-right:auto}
-.library-menu button[data-tab=pose]{--nav-dot:#849dbb}
-.library-menu button[data-tab=depth]{--nav-dot:#9689ae}
-.library-menu button[data-tab=costume]{--nav-dot:#be929a}
-.library-menu button[data-tab=anime]{--nav-dot:#b08fad}
-.library-menu button[data-tab=portrait]{--nav-dot:#c49a82}
-.library-menu button[data-tab=expr]{--nav-dot:#a2778b}
-.library-menu button[data-tab=hair]{--nav-dot:#968071}
-.library-menu button[data-tab=dyn]{--nav-dot:#ab7870}
-.library-menu button[data-tab=scene]{--nav-dot:#88a48a}
-.library-menu button[data-tab=light]{--nav-dot:#a2b6bf}
-.library-menu button[data-tab=prop]{--nav-dot:#739e9c}
-.library-menu button[data-tab=furn]{--nav-dot:#95928e}
-
-.grid{align-content:start}
-.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}
-.angs :is(span,button):first-child{margin-inline-start:auto}
-.angs :is(span,button):last-child{margin-inline-end:auto}
-.rgrp{grid-column:1/-1;display:flex;align-items:center;gap:12px;margin:14px 0 -10px;font-size:12.5px;font-weight:650;color:var(--tx2);letter-spacing:.03em}
-.rgrp::after{content:"";flex:1;height:1px;background:var(--line)}
-.rgrp:first-child{margin-top:2px}
-
-.card-flip .flip-hint{display:none;font-style:normal;font-size:11px;font-weight:600;max-width:0;overflow:hidden;opacity:0;transition:max-width .22s var(--out),opacity .18s}
-@media(hover:hover) and (pointer:fine){
- .card-flip .flip-hint{display:inline-block}
- .card-flip:is(:hover,:focus-visible) .flip-hint{max-width:44px;opacity:1}
- .card-flip .flip-hint::after{content:"深度"}
- .ph.depth .card-flip .flip-hint::after{content:"线稿"}
- html:lang(en) .card-flip .flip-hint::after{content:"Depth"}
- html:lang(en) .ph.depth .card-flip .flip-hint::after{content:"Line"}
- html:lang(ja) .card-flip .flip-hint::after{content:"深度"}
- html:lang(ja) .ph.depth .card-flip .flip-hint::after{content:"線画"}
-}
-
-/* Lightbox: Artist Inspection Studio (zoom/pan, flip, composition grid, split compare, prompt copy header) */
-.lb-img[data-img-type=pose],.lb-img[data-img-type=pose] .lb-stage{background:var(--phw)}
-:root .lb-img[data-img-type=pose] #lbImg{mix-blend-mode:multiply}
-.lb-img[data-img-type=depth],.lb-img[data-img-type=depth] .lb-stage{background:#141414}
-:root .lb-img[data-img-type=depth] #lbImg{mix-blend-mode:normal}
-.lb-stage{position:relative;display:inline-grid;place-items:center;max-width:100%;max-height:calc(100vh - 104px);transform:translate(var(--lb-tx,0px),var(--lb-ty,0px)) scale(var(--lb-z,1));transform-origin:center;transition:transform .24s var(--out);user-select:none;touch-action:pan-y}
-.lb-stage.drag{transition:none;cursor:grabbing}
-.lb-stage.zoomed:not(.drag){cursor:grab;touch-action:none}
-.lb-stage:not(.zoomed):not(.comparing){cursor:zoom-in}
-.lb-stage #lbImg{display:block;max-width:100%;max-height:calc(100vh - 104px);width:auto;height:auto;object-fit:contain;transition:filter .3s,opacity .3s,transform .22s var(--out)}
-.lb-stage.flipped #lbImg,.lb-stage.flipped #lbPairImg{transform:scaleX(-1)}
-.lb-pair-cmp{position:absolute;inset:0;clip-path:inset(0 calc(100% - var(--x,50%)) 0 0);pointer-events:none;overflow:hidden;isolation:isolate}
-.lb-pair-cmp[data-pair-type=depth]{background:#141414}
-.lb-pair-cmp[data-pair-type=pose]{background:var(--phw)}
-.lb-pair-cmp img{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;max-height:none;transition:transform .22s var(--out)}
-:root .lb-img .lb-pair-cmp[data-pair-type=depth] #lbPairImg{mix-blend-mode:normal}
-:root .lb-img .lb-pair-cmp[data-pair-type=pose] #lbPairImg{mix-blend-mode:multiply}
-.lb-pair-hdl{position:absolute;top:0;bottom:0;left:var(--x,50%);width:2px;background:rgba(255,255,255,.92);box-shadow:0 0 8px rgba(0,0,0,.45);pointer-events:none;z-index:2}
-.lb-pair-hdl span{position:absolute;top:50%;left:50%;width:34px;height:34px;transform:translate(-50%,-50%);border-radius:50%;background:#fff;box-shadow:0 2px 12px rgba(0,0,0,.32)}
-.lb-pair-hdl span::before{content:"‹ ›";position:absolute;inset:0;display:grid;place-items:center;color:#111;font-size:13px;font-weight:700;letter-spacing:1px}
-#lbPairRange{position:absolute;inset:0;width:100%;height:100%;margin:0;opacity:0;cursor:ew-resize;z-index:3}
-.lb-grid{position:absolute;inset:0;pointer-events:none;z-index:2;opacity:0;transition:opacity .18s}
-.lb-grid[data-mode=thirds]{opacity:1;background:linear-gradient(to right,transparent calc(33.333% - .5px),rgba(255,255,255,.55) calc(33.333% - .5px),rgba(17,17,17,.38) calc(33.333% + .5px),transparent calc(33.333% + 1px),transparent calc(66.666% - .5px),rgba(255,255,255,.55) calc(66.666% - .5px),rgba(17,17,17,.38) calc(66.666% + .5px),transparent calc(66.666% + 1px)),linear-gradient(to bottom,transparent calc(33.333% - .5px),rgba(255,255,255,.55) calc(33.333% - .5px),rgba(17,17,17,.38) calc(33.333% + .5px),transparent calc(33.333% + 1px),transparent calc(66.666% - .5px),rgba(255,255,255,.55) calc(66.666% - .5px),rgba(17,17,17,.38) calc(66.666% + .5px),transparent calc(66.666% + 1px))}
-.lb-grid[data-mode=cross]{opacity:1;background:linear-gradient(to right,transparent calc(50% - .75px),rgba(255,36,66,.78) calc(50% - .75px),rgba(255,255,255,.6) calc(50% + .75px),transparent calc(50% + 1.5px)),linear-gradient(to bottom,transparent calc(50% - .75px),rgba(255,36,66,.78) calc(50% - .75px),rgba(255,255,255,.6) calc(50% + .75px),transparent calc(50% + 1.5px)),linear-gradient(to right,transparent calc(25% - .5px),rgba(128,128,128,.35) 25%,transparent calc(25% + 1px),transparent calc(75% - .5px),rgba(128,128,128,.35) 75%,transparent calc(75% + 1px)),linear-gradient(to bottom,transparent calc(25% - .5px),rgba(128,128,128,.35) 25%,transparent calc(25% + 1px),transparent calc(75% - .5px),rgba(128,128,128,.35) 75%,transparent calc(75% + 1px))}
-.lb-tools{position:absolute;left:50%;bottom:14px;transform:translateX(-50%);z-index:4;display:inline-flex;align-items:center;gap:3px;padding:4px;border-radius:99px;background:rgba(24,24,28,.86);border:1px solid rgba(255,255,255,.14);box-shadow:0 8px 26px rgba(0,0,0,.24);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);max-width:calc(100% - 20px)}
-.lb-tools button{min-height:32px;padding:5px 11px;border-radius:99px;background:transparent;color:rgba(255,255,255,.86);font-size:12px;font-weight:550;gap:5px}
-.lb-tools button svg{width:14px;height:14px;flex:none;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
-.lb-tools button:hover{background:rgba(255,255,255,.14);color:#fff}
-.lb-tools button.on{background:var(--ac);color:#fff}
-.lb-tools button:focus-visible{outline-color:#fff}
-.pbox-h{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px}
-.pbox-h small{margin:0}
-.pbox p:last-child{margin-bottom:0}
-.pbox-cp{padding:4px 10px;font-size:12px;gap:5px;min-height:28px}
-.pbox-cp svg{width:13px;height:13px;flex:none;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
-.pbox-cp.copied{background:var(--ok)!important;color:#fff!important}
-.lb-keys{margin-top:16px;line-height:1.85;font-size:11.5px}
-
-/* Studio: head actions, board/result toggle, shuffle & badges, garment drop, picker filters */
-.studio-head-act{display:flex;align-items:center;gap:10px;min-width:0}
-.studio-head .modes{max-width:none}
-#wbClearAll{padding:6px 11px;font-size:12.5px;color:var(--tx2)}
-#wbClearAll:hover{color:var(--bad);background:var(--acs)}
-.garment-step.over{background:var(--acs);border-radius:10px}
-.canvas-head #wbCanvasSwitch{margin-right:auto}
-.reference-board{padding:clamp(18px,3.5%,42px) clamp(18px,4%,48px) 68px}
-.board-actions{display:flex;align-items:center;justify-content:center;flex-wrap:wrap;gap:8px}
-.board-shuffle::after{content:"↻";font-size:14px}
-.board-card{position:relative}
-.board-idx{position:absolute;top:9px;left:9px;z-index:1;min-width:20px;height:20px;padding:0 5px;border-radius:6px;background:rgba(17,17,17,.78);color:#fff;font:700 11px/20px var(--sans);font-style:normal;text-align:center;font-variant-numeric:tabular-nums;backdrop-filter:blur(4px);pointer-events:none}
-.board-ang{position:absolute;right:9px;bottom:32px;z-index:1;max-width:calc(100% - 18px);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:1px 6px;border-radius:99px;background:rgba(17,17,17,.72);color:#fff;font-size:10px;font-style:normal;font-weight:550;pointer-events:none}
-.board-card[data-type=pose] img{background:var(--phw)}
-[data-theme=dark] .board-card[data-type=pose] img,[data-theme=dark] .pick.pose img,[data-theme=dark] .lb-img[data-img-type=pose]~.lb-side .sim img{filter:brightness(.92)}
-@media(prefers-reduced-motion:no-preference){
- .board-cards .board-card{animation:boardIn .3s var(--out) both}
- .board-cards .board-card:nth-child(2){animation-delay:40ms}
- .board-cards .board-card:nth-child(3){animation-delay:80ms}
- .board-cards .board-card:nth-child(4){animation-delay:120ms}
- @keyframes boardIn{from{opacity:0;scale:.94}}
-}
-
-.pk-bar{display:flex;align-items:center;gap:8px;margin:0 24px 10px;min-width:0}
-#pkFavOnly{flex:none;padding:5px 12px;font-size:12.5px;min-height:30px;border:1px solid var(--line2);background:var(--bg2)}
-#pkFavOnly.on{background:var(--ac);border-color:var(--ac);color:#fff}
-.pk-cats{display:flex;align-items:center;gap:6px;overflow-x:auto;scrollbar-width:none;min-width:0;flex:1;padding:1px 2px}
-.pk-cats::-webkit-scrollbar{display:none}
-.pk-cats .chip{flex:none;padding:5px 11px;font-size:12px;min-height:30px}
-.pk-g button.on::after{content:"";position:absolute;top:7px;right:7px;width:22px;height:22px;border-radius:50%;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.2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 12 4 4 8-8'/%3E%3C/svg%3E") center/13px no-repeat;box-shadow:0 2px 6px rgba(0,0,0,.22)}
-
-/* Floating dock prompt reset */
-.dock-heading-tools{display:inline-flex;align-items:center;gap:4px}
-#tgResetPrompt{padding:4px 8px;font-size:11.5px;min-height:26px;color:var(--tx2)}
-#tgResetPrompt:hover{color:var(--tx)}
-
-/* History filters, search & lightbox reference strip */
-#histQ{width:200px;max-width:100%;font:inherit;font-size:13px;background:var(--sf);color:var(--tx);border:1.5px solid transparent;border-radius:99px;padding:6px 13px;outline:0;transition:border-color .18s,background .18s}
-#histQ:hover{background:var(--sf2)}
-#histQ:focus{background:var(--bg2);border-color:var(--tx2)}
-#histQ::placeholder{color:var(--mu)}
-.hist-nomatch{grid-column:1/-1;text-align:center;padding:54px 16px;color:var(--tx2)}
-.hist-nomatch p{margin:0 0 12px;font-size:14px}
-.hlb-refs{margin-top:16px}
-.hlb-refs-h{display:block;font-size:12px;font-weight:600;color:var(--tx2);margin-bottom:8px}
-.hlb-refs-row{display:flex;gap:8px;overflow-x:auto;padding-bottom:4px;scrollbar-width:thin}
-.hlb-ref{flex:none;width:54px;height:70px;border-radius:10px;overflow:hidden;background:var(--sf);border:1px solid var(--line2);display:block;transition:transform .18s var(--out),border-color .18s}
-a.hlb-ref:hover{transform:translateY(-2px);border-color:var(--ac)}
-.hlb-ref img{width:100%;height:100%;object-fit:cover;display:block}
-.hlb-del{color:var(--bad)}
-.hlb-del:hover{background:var(--acs);color:var(--bad)}
-
-@media(max-width:860px){
- .lb-stage,.lb-stage #lbImg{max-height:56vh}
- .lb-tools{bottom:8px;padding:3px;gap:2px}
- .lb-tools button{padding:5px 9px;min-height:34px;font-size:11.5px}
- .pk-bar{margin:0 14px 8px}
- .studio-head-act{gap:6px}
- #wbClearAll{padding:5px 8px;font-size:12px}
- .reference-board{padding:16px 12px}
- .board-idx{top:5px;left:5px;min-width:16px;height:16px;line-height:16px;font-size:10px}
- .board-ang{display:none}
- #histQ{width:150px;flex:1 1 130px;font-size:14px}
-}
-@media(max-width:520px){
- .studio-head{flex-wrap:wrap;row-gap:8px}
- .lb-tools button span{display:none}
- .lb-tools button{width:34px;padding:0;justify-content:center}
-}
-
-/* ---------- Signature Studio Touches (Gesture Sketch, Grayscale & Palette, Board Export, Command Palette) ---------- */
-#q{padding-inline-end:54px}
-.q-kbd{position:absolute;right:10px;top:50%;transform:translateY(-50%);height:24px;padding:0 7px;border-radius:6px;background:var(--bg2);border:1px solid var(--line2);color:var(--mu);font:600 11px/1 ui-monospace,Menlo,monospace;letter-spacing:.02em;box-shadow:0 1px 0 var(--line2)}
-.q-kbd:hover{border-color:var(--tx2);color:var(--tx);background:var(--bg2)}
-.top .search:focus-within .q-kbd,.top .search:has(#q:not(:placeholder-shown)) .q-kbd{display:none}
-
-#sketchBtn{display:inline-flex;align-items:center;gap:5px;padding:7px 13px;font-size:13px;color:var(--tx);background:var(--sf);border:1px solid transparent}
-#sketchBtn:hover{background:var(--sf2);border-color:var(--line2)}
-#sketchBtn svg{width:15px;height:15px;flex:none;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
-body.none0 #sketchBtn{display:none!important}
-
-#lbStage.gray #lbImg,#skFrame.gray #skImg{filter:grayscale(1) contrast(1.06)}
-.lb-pal{margin-top:14px;padding:10px 12px 11px;border-radius:14px;background:var(--sf);border:1px solid var(--line)}
-.lb-pal-h{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}
-.lb-pal-h small{font-size:11.5px;font-weight:600;color:var(--tx2)}
-.lb-pal-h .mu{font-weight:400;color:var(--mu)}
-.lb-pal-sw{display:grid;grid-template-columns:repeat(auto-fit,minmax(56px,1fr));gap:6px}
-.pal-sw{flex-direction:column;gap:5px;padding:5px 4px 6px;border-radius:10px;background:var(--bg2);border:1px solid var(--line2);transition:transform .16s var(--out),border-color .16s}
-.pal-sw:hover{transform:translateY(-2px);border-color:var(--tx2);background:var(--bg2)}
-.pal-sw i{display:block;width:100%;height:26px;border-radius:7px;background:var(--sw);box-shadow:inset 0 0 0 1px rgba(0,0,0,.1)}
-[data-theme=dark] .pal-sw i{box-shadow:inset 0 0 0 1px rgba(255,255,255,.14)}
-.pal-sw span{font:600 10.5px/1 ui-monospace,Menlo,monospace;color:var(--tx2);letter-spacing:-.01em}
-.pal-sw.copied{border-color:var(--ok)}
-.pal-sw.copied span{color:var(--ok)}
-
-#wbExportBoard{padding:5px 11px;font-size:12px;border:1px solid var(--line2);background:var(--bg2);color:var(--tx2);margin-left:auto}
-#wbExportBoard:hover{color:var(--tx);border-color:var(--tx2);background:var(--sf)}
-.canvas-head #wbCanvasSwitch:not([hidden]) ~ #wbExportBoard{margin-left:0}
-
-#sketch{position:fixed;inset:0;z-index:75;display:flex;flex-direction:column;background:var(--bg);color:var(--tx);animation:fade .2s both}
-.sk-prog{position:relative;height:3px;width:100%;background:var(--line);flex:none;overflow:hidden}
-.sk-prog i{display:block;height:100%;width:100%;background:var(--ac);transform-origin:left center;transition:transform .2s linear}
-.sk-top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 20px;border-bottom:1px solid var(--line);flex:none;flex-wrap:wrap}
-.sk-meta{display:flex;align-items:baseline;gap:10px;min-width:0;flex:1 1 160px}
-.sk-meta b{font-size:14px;font-variant-numeric:tabular-nums;color:var(--tx);flex:none}
-.sk-meta span{font-size:13px;color:var(--tx2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
-.sk-timer-box{display:flex;align-items:center;gap:10px;flex-wrap:wrap;justify-content:center}
-#skTime{font:700 22px/1 ui-monospace,Menlo,monospace;font-variant-numeric:tabular-nums;color:var(--tx);min-width:74px;text-align:center;letter-spacing:.03em}
-.sk-right{display:flex;align-items:center;gap:4px;flex:none}
-#skSound{color:var(--tx2)}
-#skSound .sk-snd-on{display:none}
-#skSound.on{background:var(--acs);color:var(--ac)}
-#skSound.on .sk-snd-on{display:block}
-#skSound.on .sk-snd-off{display:none}
-.sk-stage{flex:1;min-height:0;display:grid;place-items:center;padding:18px 24px;overflow:auto;background:var(--sf);position:relative}
-.sk-stage[data-img-type=pose],.sk-stage[data-img-type=pose] .sk-frame{background:var(--phw)}
-.sk-stage[data-img-type=depth],.sk-stage[data-img-type=depth] .sk-frame{background:#141414}
-.sk-frame{position:relative;display:inline-grid;place-items:center;max-width:100%;max-height:100%;border-radius:12px;overflow:hidden}
-.sk-frame img{display:block;max-width:min(92vw,1120px);max-height:calc(100dvh - 176px);width:auto;height:auto;object-fit:contain;transition:transform .22s var(--out),filter .22s}
-.sk-stage[data-img-type=pose] .sk-frame img{mix-blend-mode:multiply}
-.sk-frame.flipped img{transform:scaleX(-1)}
-.sk-done{text-align:center;max-width:680px;width:100%;padding:28px 24px;background:var(--bg2);border:1px solid var(--line2);border-radius:22px;box-shadow:var(--sh2)}
-.sk-done h3{font-size:22px;margin-bottom:6px}
-.sk-done p{margin:0 0 18px;color:var(--tx2);font-size:14px}
-.sk-recap{display:flex;flex-wrap:wrap;justify-content:center;gap:10px;max-height:44vh;overflow:auto;margin-bottom:20px;padding:2px}
-.sk-recap button{width:92px;flex:none;padding:0;border-radius:10px;overflow:hidden;aspect-ratio:3/4;background:var(--ph);border:1px solid var(--line2)}
-.sk-recap button:hover{border-color:var(--ac);transform:translateY(-2px)}
-.sk-recap img{width:100%;height:100%;object-fit:cover;display:block}
-.sk-done-act{display:flex;justify-content:center;gap:10px;flex-wrap:wrap}
-#sketch:has(#skDone:not([hidden])) .sk-foot{display:none}
-.sk-foot{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 20px calc(12px + env(safe-area-inset-bottom));border-top:1px solid var(--line);background:var(--bg);flex:none;flex-wrap:wrap}
-.sk-ctrl{display:flex;align-items:center;gap:8px}
-.sk-ctrl button{min-height:38px}
-#skPrev,#skNext{width:38px;padding:0;font-size:20px}
-#skPause{min-width:92px}
-.sk-tools{display:flex;align-items:center;gap:6px;flex-wrap:wrap}
-.sk-tools button{padding:7px 13px;font-size:13px;background:var(--sf);color:var(--tx2)}
-.sk-tools button:hover{background:var(--sf2);color:var(--tx)}
-.sk-tools button.on{background:var(--tx);color:var(--bg)}
-.sk-tools button[data-skt=fav].on{background:var(--acs);color:var(--ac)}
-
-#cmdPal{position:fixed;inset:0;z-index:85;display:grid;place-items:start center;padding:min(13vh,104px) 16px 20px;background:rgba(0,0,0,.46);backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);animation:fade .16s both}
-.cmd-box{width:min(540px,100%);max-height:min(70vh,560px);display:flex;flex-direction:column;background:var(--bg2);border:1px solid var(--line2);border-radius:18px;box-shadow:var(--sh3);overflow:hidden}
-.cmd-in{display:flex;align-items:center;gap:10px;padding:12px 14px;border-bottom:1px solid var(--line)}
-.cmd-in svg{width:18px;height:18px;flex:none;fill:none;stroke:var(--mu);stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
-#cmdQ{flex:1;min-width:0;border:0;outline:0;background:transparent;color:var(--tx);font:15px/1.4 var(--sans)}
-#cmdQ::placeholder{color:var(--mu)}
-#cmdQ::-webkit-search-cancel-button{display:none}
-.cmd-list{flex:1;min-height:0;overflow:auto;padding:6px;scrollbar-width:thin}
-.cmd-g{padding:8px 10px 4px;font-size:11.5px;font-weight:650;color:var(--mu);letter-spacing:.03em}
-.cmd-it{position:relative;width:100%;justify-content:flex-start;gap:10px;padding:9px 12px;border-radius:10px;background:transparent;color:var(--tx);font-size:13.5px;font-weight:500;text-align:left}
-.cmd-it:hover{background:var(--sf)}
-.cmd-it.on{background:var(--sf2);color:var(--tx)}
-.cmd-it.on::before{content:"";position:absolute;left:0;top:7px;bottom:7px;width:3px;border-radius:3px;background:var(--ac)}
-.cmd-it span{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis}
-.cmd-it small{font-size:11.5px;color:var(--mu);font-variant-numeric:tabular-nums;background:var(--sf);padding:2px 7px;border-radius:6px;flex:none}
-.cmd-it.on small{background:var(--bg2);color:var(--tx2)}
-.cmd-dot{width:8px;height:8px;border-radius:50%;flex:none;background:var(--nav-dot,var(--mu))}
-.cmd-dot[data-tab=pose]{--nav-dot:#849dbb}.cmd-dot[data-tab=depth]{--nav-dot:#9689ae}.cmd-dot[data-tab=costume]{--nav-dot:#be929a}.cmd-dot[data-tab=anime]{--nav-dot:#b08fad}.cmd-dot[data-tab=portrait]{--nav-dot:#c49a82}.cmd-dot[data-tab=expr]{--nav-dot:#a2778b}.cmd-dot[data-tab=hair]{--nav-dot:#968071}.cmd-dot[data-tab=dyn]{--nav-dot:#ab7870}.cmd-dot[data-tab=scene]{--nav-dot:#88a48a}.cmd-dot[data-tab=light]{--nav-dot:#a2b6bf}.cmd-dot[data-tab=prop]{--nav-dot:#739e9c}.cmd-dot[data-tab=furn]{--nav-dot:#95928e}
-.cmd-empty{padding:28px 16px;text-align:center;color:var(--mu);font-size:13.5px}
-.cmd-foot{display:flex;align-items:center;gap:14px;padding:8px 14px;border-top:1px solid var(--line);background:var(--sf);font-size:11.5px;color:var(--mu)}
-.cmd-foot kbd{background:var(--bg2);border:1px solid var(--line2);padding:2px 5px}
-
-@media(max-width:860px){
- .q-kbd{display:none}
- #q{padding-inline-end:38px}
- .sk-top{padding:8px 12px;gap:8px}
- .sk-meta{flex-basis:calc(100% - 92px)}
- .sk-timer-box{order:3;flex-basis:100%;justify-content:space-between;gap:6px}
- #skTime{font-size:18px;min-width:60px;text-align:left}
- .sk-stage{padding:10px}
- .sk-frame img{max-height:calc(100dvh - 230px)}
- .sk-foot{padding:10px 12px calc(10px + env(safe-area-inset-bottom));justify-content:center}
- .sk-tools{justify-content:center}
- .sk-tools button{padding:6px 10px;font-size:12px}
- #cmdPal{padding:8vh 10px 16px}
- .cmd-foot{display:none}
-}
-@media(max-width:760px){
- #sketchBtn{min-width:38px;min-height:38px;padding:6px 10px;font-size:12.5px}
-}
-@media(max-width:480px){
- #sketchBtn{width:38px;padding:0;justify-content:center}
- #sketchBtn span{display:none}
+#cfg.local-engine #cfClr {
+ display: none;
+}
+
+.cfg-f {
+ display: flex;
+ gap: 8px;
+ padding: 14px 24px;
+ border-top: 1px solid var(--line);
+}
+
+/* Toast, back-to-top & micro particles */
+#toast {
+ position: fixed;
+ left: 50%;
+ bottom: calc(32px + env(safe-area-inset-bottom));
+ transform: translate(-50%, 14px);
+ opacity: 0;
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ background: rgba(17, 17, 17, .92);
+ color: #fff;
+ padding: 11px 22px;
+ border-radius: 99px;
+ transition: transform .35s var(--out), opacity .25s;
+ z-index: 99;
+ pointer-events: none;
+ font-size: 13.5px;
+ box-shadow: var(--sh2);
+}
+
+#toast.on {
+ opacity: 1;
+ transform: translate(-50%, 0);
+ animation: tspr .5s cubic-bezier(.34, 1.56, .64, 1);
+}
+
+@keyframes tspr {
+ from { opacity: 0; transform: translate(-50%, 14px) scale(.96); }
+}
+
+#toast.act {
+ pointer-events: auto;
+ padding-right: 8px;
+}
+
+#toast button {
+ background: rgba(255, 255, 255, .14);
+ color: #fff;
+ border-radius: 99px;
+ padding: 5px 12px;
+ font-size: 13px;
+ font-weight: 600;
+ min-height: 0;
+}
+
+#toast button:hover {
+ background: rgba(255, 255, 255, .24);
+}
+
+body.tray:not(.studio) #toast {
+ bottom: auto;
+ top: calc(var(--hdr, 72px) + 14px);
+}
+
+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);
+}
+
+#cfg:not([hidden]) ~ #toast,
+body:has(#cfg:not([hidden])) #toast {
+ bottom: calc(84px + env(safe-area-inset-bottom));
+}
+
+#toTop {
+ position: fixed;
+ left: 24px;
+ bottom: 24px;
+ z-index: 25;
+ background: var(--bg2);
+ box-shadow: var(--sh2);
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity .3s;
+}
+
+#toTop.on {
+ opacity: 1;
+ pointer-events: auto;
+}
+
+.pt {
+ position: fixed;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ pointer-events: none;
+ z-index: 200;
+}
+
+.flyimg {
+ position: fixed;
+ z-index: 200;
+ object-fit: cover;
+ pointer-events: none;
+ box-shadow: 0 10px 30px rgba(0, 0, 0, .2);
+ will-change: transform;
+}
+
+/* ==========================================================================
+ 9. Generation History Page
+ ========================================================================== */
+
+#histSec {
+ max-width: var(--w);
+ margin: 0 auto;
+ padding: 6px 24px 60px;
+ min-height: calc(100vh - 180px);
+}
+
+.hist-bar {
+ position: sticky;
+ top: calc(var(--hdr, 72px) - 1px);
+ z-index: 20;
+ padding: 6px 0 10px;
+ background: var(--bg);
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.hist-bar .tbar {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex: 1;
+ min-width: 0;
+}
+
+#histCount {
+ font-size: 13px;
+ color: var(--mu);
+ margin-right: 4px;
+ white-space: nowrap;
+}
+
+#histCount b {
+ color: var(--tx);
+ font-weight: 600;
+}
+
+.hist-sel-all {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 13px;
+ color: var(--tx2);
+ cursor: pointer;
+ white-space: nowrap;
+ user-select: none;
+}
+
+.hist-sel-all input {
+ width: 16px;
+ height: 16px;
+ accent-color: var(--ac);
+ cursor: pointer;
+}
+
+#histSelN {
+ font-size: 13px;
+ color: var(--ac);
+ font-weight: 600;
+ white-space: nowrap;
+}
+
+#histSelN b {
+ font-variant-numeric: tabular-nums;
+}
+
+#histQ {
+ width: 200px;
+ max-width: 100%;
+ font: inherit;
+ font-size: 13px;
+ background: var(--sf);
+ color: var(--tx);
+ border: 1.5px solid transparent;
+ border-radius: 99px;
+ padding: 6px 13px;
+ outline: 0;
+ transition: border-color .18s, background .18s;
+}
+
+#histQ:hover {
+ background: var(--sf2);
+}
+
+#histQ:focus {
+ background: var(--bg2);
+ border-color: var(--tx2);
+}
+
+#histQ::placeholder {
+ color: var(--mu);
+}
+
+.hist-stats {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px 14px;
+ font-size: 12.5px;
+ color: var(--tx2);
+ padding: 0 0 10px;
+ line-height: 1.6;
+ 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;
+}
+
+.hist-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(232px, 1fr));
+ gap: 28px 16px;
+ max-width: var(--w);
+ margin: 0;
+ padding: 0 0 40px;
+}
+
+.hist-nomatch {
+ grid-column: 1 / -1;
+ text-align: center;
+ padding: 54px 16px;
+ color: var(--tx2);
+}
+
+.hist-nomatch p {
+ margin: 0 0 12px;
+ font-size: 14px;
+}
+
+.hist-card {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ animation: rise .5s var(--out) both;
+}
+
+.hist-card .hph {
+ position: relative;
+ aspect-ratio: 3 / 4;
+ overflow: hidden;
+ background: var(--ph);
+ cursor: pointer;
+ border-radius: 16px;
+ transition: transform .35s var(--out), box-shadow .35s;
+}
+
+.hist-card:hover .hph {
+ transform: translateY(-2px);
+ box-shadow: 0 10px 28px rgba(0, 0, 0, .1);
+}
+
+.hist-card .hph img {
+ display: block;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ border-radius: inherit;
}
+.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 .hsel {
+ position: absolute;
+ left: 10px;
+ top: 10px;
+ z-index: 2;
+ 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);
+ cursor: pointer;
+ transition: transform .25s var(--out), background .2s;
+ appearance: none;
+ -webkit-appearance: none;
+}
+
+.hist-card .hsel:checked {
+ 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);
+}
+
+.hist-card.selected .hph {
+ box-shadow: 0 0 0 3px var(--ac);
+}
+
+.hist-card .hcbtns {
+ position: absolute;
+ right: 10px;
+ top: 10px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ opacity: 0;
+ transform: scale(.9);
+ transition: .25s var(--out);
+ z-index: 2;
+}
+
+.hist-card:hover .hcbtns,
+.hcbtns:focus-within {
+ opacity: 1;
+ transform: none;
+}
+
+.hist-card .hcbtns button {
+ width: 36px;
+ height: 36px;
+ padding: 0;
+ background: #fff;
+ color: #111;
+ font-size: 16px;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, .12);
+ border-radius: 50%;
+}
+
+.hist-card .hcbtns button:hover {
+ background: #fff;
+ transform: scale(1.08);
+}
+
+.hist-card .hmode {
+ position: absolute;
+ left: 10px;
+ bottom: 10px;
+ font-size: 11.5px;
+ font-weight: 600;
+ color: #fff;
+ background: rgba(0, 0, 0, .55);
+ padding: 2px 8px;
+ border-radius: 99px;
+ z-index: 1;
+ pointer-events: none;
+}
+
+.hist-card .hinfo {
+ padding: 10px 4px 0;
+ min-width: 0;
+}
+
+.hist-card .hinfo h3 {
+ font-size: 14.5px;
+ font-weight: 600;
+ line-height: 1.4;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.hist-card .hinfo .sub {
+ font-size: 12.5px;
+ color: var(--mu);
+ margin-top: 2px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+#histEmpty {
+ text-align: center;
+ padding: 60px 20px 100px;
+ max-width: 560px;
+ margin: 0 auto;
+}
+
+#histEmpty h3 {
+ font-size: 20px;
+}
+
+#histEmpty p {
+ color: var(--tx2);
+}
+
+.hlb-cmp {
+ margin-top: 16px;
+ border-radius: 14px;
+ overflow: hidden;
+ position: relative;
+ --x: 50%;
+}
+
+.hlb-cmp img {
+ display: block;
+ width: 100%;
+ aspect-ratio: 3 / 4;
+ object-fit: cover;
+}
+
+.hlb-cmp .hlb-bef {
+ position: absolute;
+ inset: 0;
+ clip-path: inset(0 calc(100% - var(--x)) 0 0);
+}
+
+.hlb-cmp .hlb-hdl {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: var(--x);
+ width: 2px;
+ background: #fff;
+ pointer-events: none;
+}
+
+.hlb-cmp .hlb-hdl span {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: 32px;
+ height: 32px;
+ transform: translate(-50%, -50%);
+ border-radius: 50%;
+ background: #fff;
+ box-shadow: var(--sh2);
+}
+
+.hlb-cmp .hlb-hdl span::before {
+ content: "‹ ›";
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ color: #111;
+ font-size: 13px;
+ letter-spacing: 2px;
+}
+
+.hlb-cmp input[type=range] {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ opacity: 0;
+ cursor: ew-resize;
+ margin: 0;
+}
+
+.hlb-cmp em {
+ position: absolute;
+ top: 10px;
+ font-size: 11px;
+ font-style: normal;
+ font-weight: 600;
+ color: #fff;
+ background: rgba(0, 0, 0, .5);
+ padding: 3px 9px;
+ border-radius: 99px;
+ pointer-events: none;
+}
+
+.hlb-cmp em.l { left: 10px; }
+.hlb-cmp em.r { right: 10px; }
+
+.hlb-refs {
+ margin-top: 16px;
+}
+
+.hlb-refs-h {
+ display: block;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--tx2);
+ margin-bottom: 8px;
+}
+
+.hlb-refs-row {
+ display: flex;
+ gap: 8px;
+ overflow-x: auto;
+ padding-bottom: 4px;
+ scrollbar-width: thin;
+}
+
+.hlb-ref {
+ flex: none;
+ width: 54px;
+ height: 70px;
+ border-radius: 10px;
+ overflow: hidden;
+ background: var(--sf);
+ border: 1px solid var(--line2);
+ display: block;
+ transition: transform .18s var(--out), border-color .18s;
+}
+
+a.hlb-ref:hover {
+ transform: translateY(-2px);
+ border-color: var(--ac);
+}
+
+.hlb-ref img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+}
+
+.hlb-del {
+ color: var(--bad);
+}
+
+.hlb-del:hover {
+ background: var(--acs);
+ color: var(--bad);
+}
+
+/* ==========================================================================
+ 10. Gesture Sketch Studio
+ ========================================================================== */
+
+#sketch {
+ position: fixed;
+ inset: 0;
+ z-index: 75;
+ display: flex;
+ flex-direction: column;
+ background: var(--bg);
+ color: var(--tx);
+ animation: fade .2s both;
+}
+
+.sk-prog {
+ position: relative;
+ height: 3px;
+ width: 100%;
+ background: var(--line);
+ flex: none;
+ overflow: hidden;
+}
+
+.sk-prog i {
+ display: block;
+ height: 100%;
+ width: 100%;
+ background: var(--ac);
+ transform-origin: left center;
+ transition: transform .2s linear;
+}
+
+.sk-top {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 10px 20px;
+ border-bottom: 1px solid var(--line);
+ flex: none;
+ flex-wrap: wrap;
+}
+
+.sk-meta {
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+ min-width: 0;
+ flex: 1 1 160px;
+}
+
+.sk-meta b {
+ font-size: 14px;
+ font-variant-numeric: tabular-nums;
+ color: var(--tx);
+ flex: none;
+}
+
+.sk-meta span {
+ font-size: 13px;
+ color: var(--tx2);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.sk-timer-box {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex-wrap: wrap;
+ justify-content: center;
+}
+
+#skTime {
+ font: 700 22px/1 ui-monospace, Menlo, monospace;
+ font-variant-numeric: tabular-nums;
+ color: var(--tx);
+ min-width: 74px;
+ text-align: center;
+ letter-spacing: .03em;
+}
+
+.sk-right {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ flex: none;
+}
+
+#skSound {
+ color: var(--tx2);
+}
+
+#skSound .sk-snd-on {
+ display: none;
+}
+
+#skSound.on {
+ background: var(--acs);
+ color: var(--ac);
+}
+
+#skSound.on .sk-snd-on {
+ display: block;
+}
+
+#skSound.on .sk-snd-off {
+ display: none;
+}
+
+.sk-stage {
+ flex: 1;
+ min-height: 0;
+ display: grid;
+ place-items: center;
+ padding: 18px 24px;
+ overflow: auto;
+ background: var(--sf);
+ position: relative;
+}
+
+.sk-stage[data-img-type=pose],
+.sk-stage[data-img-type=pose] .sk-frame {
+ background: var(--phw);
+}
+
+.sk-stage[data-img-type=depth],
+.sk-stage[data-img-type=depth] .sk-frame {
+ background: #141414;
+}
+
+.sk-frame {
+ position: relative;
+ display: inline-grid;
+ place-items: center;
+ max-width: 100%;
+ max-height: 100%;
+ border-radius: 12px;
+ overflow: hidden;
+}
+
+.sk-frame img {
+ display: block;
+ max-width: min(92vw, 1120px);
+ max-height: calc(100dvh - 176px);
+ width: auto;
+ height: auto;
+ object-fit: contain;
+ transition: transform .22s var(--out), filter .22s;
+}
+
+.sk-stage[data-img-type=pose] .sk-frame img {
+ mix-blend-mode: multiply;
+}
+
+.sk-frame.flipped img {
+ transform: scaleX(-1);
+}
+
+.sk-done {
+ text-align: center;
+ max-width: 680px;
+ width: 100%;
+ padding: 28px 24px;
+ background: var(--bg2);
+ border: 1px solid var(--line2);
+ border-radius: 22px;
+ box-shadow: var(--sh2);
+}
+
+.sk-done h3 {
+ font-size: 22px;
+ margin-bottom: 6px;
+}
+
+.sk-done p {
+ margin: 0 0 18px;
+ color: var(--tx2);
+ font-size: 14px;
+}
+
+.sk-recap {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 10px;
+ max-height: 44vh;
+ overflow: auto;
+ margin-bottom: 20px;
+ padding: 2px;
+}
+
+.sk-recap button {
+ width: 92px;
+ flex: none;
+ padding: 0;
+ border-radius: 10px;
+ overflow: hidden;
+ aspect-ratio: 3 / 4;
+ background: var(--ph);
+ border: 1px solid var(--line2);
+}
+
+.sk-recap button:hover {
+ border-color: var(--ac);
+ transform: translateY(-2px);
+}
+
+.sk-recap img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+}
+
+.sk-done-act {
+ display: flex;
+ justify-content: center;
+ gap: 10px;
+ flex-wrap: wrap;
+}
+
+#sketch:has(#skDone:not([hidden])) .sk-foot {
+ display: none;
+}
+
+.sk-foot {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 12px 20px calc(12px + env(safe-area-inset-bottom));
+ border-top: 1px solid var(--line);
+ background: var(--bg);
+ flex: none;
+ flex-wrap: wrap;
+}
+
+.sk-ctrl {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.sk-ctrl button {
+ min-height: 38px;
+}
+
+#skPrev, #skNext {
+ width: 38px;
+ padding: 0;
+ font-size: 20px;
+}
+
+#skPause {
+ min-width: 92px;
+}
+
+.sk-tools {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-wrap: wrap;
+}
+
+.sk-tools button {
+ padding: 7px 13px;
+ font-size: 13px;
+ background: var(--sf);
+ color: var(--tx2);
+}
+
+.sk-tools button:hover {
+ background: var(--sf2);
+ color: var(--tx);
+}
+
+.sk-tools button.on {
+ background: var(--tx);
+ color: var(--bg);
+}
+
+.sk-tools button[data-skt=fav].on {
+ background: var(--acs);
+ color: var(--ac);
+}
+
+/* ==========================================================================
+ 11. Global Command Palette
+ ========================================================================== */
+
+#cmdPal {
+ position: fixed;
+ inset: 0;
+ z-index: 85;
+ display: grid;
+ place-items: start center;
+ padding: min(13vh, 104px) 16px 20px;
+ background: rgba(0, 0, 0, .46);
+ backdrop-filter: blur(4px);
+ -webkit-backdrop-filter: blur(4px);
+ animation: fade .16s both;
+}
+
+.cmd-box {
+ width: min(540px, 100%);
+ max-height: min(70vh, 560px);
+ display: flex;
+ flex-direction: column;
+ background: var(--bg2);
+ border: 1px solid var(--line2);
+ border-radius: 18px;
+ box-shadow: var(--sh3);
+ overflow: hidden;
+}
+
+.cmd-in {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 12px 14px;
+ border-bottom: 1px solid var(--line);
+}
+
+.cmd-in svg {
+ width: 18px;
+ height: 18px;
+ flex: none;
+ fill: none;
+ stroke: var(--mu);
+ stroke-width: 2;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+#cmdQ {
+ flex: 1;
+ min-width: 0;
+ border: 0;
+ outline: 0;
+ background: transparent;
+ color: var(--tx);
+ font: 15px/1.4 var(--sans);
+}
+
+#cmdQ::placeholder {
+ color: var(--mu);
+}
+
+#cmdQ::-webkit-search-cancel-button {
+ display: none;
+}
+
+.cmd-list {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ padding: 6px;
+ scrollbar-width: thin;
+}
+
+.cmd-g {
+ padding: 8px 10px 4px;
+ font-size: 11.5px;
+ font-weight: 650;
+ color: var(--mu);
+ letter-spacing: .03em;
+}
+
+.cmd-it {
+ position: relative;
+ width: 100%;
+ justify-content: flex-start;
+ gap: 10px;
+ padding: 9px 12px;
+ border-radius: 10px;
+ background: transparent;
+ color: var(--tx);
+ font-size: 13.5px;
+ font-weight: 500;
+ text-align: left;
+}
+
+.cmd-it:hover {
+ background: var(--sf);
+}
+
+.cmd-it.on {
+ background: var(--sf2);
+ color: var(--tx);
+}
+
+.cmd-it.on::before {
+ content: "";
+ position: absolute;
+ left: 0;
+ top: 7px;
+ bottom: 7px;
+ width: 3px;
+ border-radius: 3px;
+ background: var(--ac);
+}
+
+.cmd-it span {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.cmd-it small {
+ font-size: 11.5px;
+ color: var(--mu);
+ font-variant-numeric: tabular-nums;
+ background: var(--sf);
+ padding: 2px 7px;
+ border-radius: 6px;
+ flex: none;
+}
+
+.cmd-it.on small {
+ background: var(--bg2);
+ color: var(--tx2);
+}
+
+.cmd-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ flex: none;
+ background: var(--cat-color, var(--mu));
+}
+
+.cmd-empty {
+ padding: 28px 16px;
+ text-align: center;
+ color: var(--mu);
+ font-size: 13.5px;
+}
+
+.cmd-foot {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ padding: 8px 14px;
+ border-top: 1px solid var(--line);
+ background: var(--sf);
+ font-size: 11.5px;
+ color: var(--mu);
+}
+
+.cmd-foot kbd {
+ background: var(--bg2);
+ border: 1px solid var(--line2);
+ padding: 2px 5px;
+}
+
+/* ==========================================================================
+ 12. Responsive, Pointer & Motion Queries
+ ========================================================================== */
+
+@media (min-width: 1500px) {
+ .grid { grid-template-columns: repeat(6, minmax(0, 1fr)); }
+}
+
+@media (min-width: 861px) {
+ body.studio { overflow: hidden; }
+ 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 (min-width: 761px) {
+ .frow {
+ -webkit-mask-image: linear-gradient(90deg, #000 93%, transparent 99%);
+ mask-image: linear-gradient(90deg, #000 93%, transparent 99%);
+ }
+}
+
+@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; }
+}
+
+@media (max-width: 1180px) {
+ .lb-side { width: 360px; }
+ .next { right: 386px; }
+}
+
+@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: 860px) {
+ body { --dock-base: 10px; }
+ body.studio { --dock-base: 84px; padding-bottom: 0; }
+ body.batch { --dock-base: 65px; }
+
+ .top { padding-inline: 12px; }
+ .top:has(details[open]) { z-index: 42; }
+ .wm { display: none; }
+ .tools .seg { display: none; }
+ #q { padding: 9px 38px 9px 40px; font-size: 14px; }
+ .sic { left: 14px; width: 16px; height: 16px; }
+ .q-kbd { display: none; }
+
+ .bar { padding: 4px 12px 8px; gap: 6px; }
+ .tbar { gap: 6px; overflow-x: auto; scrollbar-width: none; }
+ .tbar::-webkit-scrollbar { display: none; }
+ .tbar > * { flex: none; }
+ #count { font-size: 12px; }
+ .fbtn, #sort, #rand { font-size: 12.5px; padding: 6px 12px; }
+ #sort { padding-right: 28px; }
+ .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: 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; }
+ .badge.age { left: 46px; }
+ .tray-act button { font-size: 12.5px; padding: 8px 10px; }
+
+ /* Lightbox mobile */
+ .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, .lb-stage, .lb-stage #lbImg { max-height: 56vh; }
+ .lb-tools { bottom: 8px; padding: 3px; gap: 2px; }
+ .lb-tools button { padding: 5px 9px; min-height: 34px; font-size: 11.5px; }
+ .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; }
+
+ /* Studio mobile */
+ #studio { height: auto; padding: 0 12px calc(128px + env(safe-area-inset-bottom)); }
+ .studio-head { padding: 12px 0; gap: 8px; }
+ .studio-head-act { gap: 6px; }
+ .studio-head .modes { max-width: 62%; }
+ .studio-head .modes button { padding: 7px 10px; font-size: 12px; }
+ #wbClearAll { padding: 5px 8px; font-size: 12px; }
+ .st-app { display: flex; flex-direction: column; gap: 12px; height: auto; }
+ .st-l, .st-r { display: flex; flex-direction: column; overflow: visible; min-width: 0; }
+ .st-l { order: -2; }
+ .st-c { order: -1; min-height: 0; min-width: 0; }
+ .st-r { order: 0; }
+ .st-c:has(#wbCmp:not([hidden]), #wbBusy:not([hidden]), #wbErr:not([hidden])) { order: -3; min-height: 0; }
+ .sh { min-width: 0; flex-wrap: wrap; row-gap: 4px; }
+ .primary-materials { padding-inline: 13px; }
+ .primary-materials .step { padding-block: 9px 12px; }
+ .material-extras { padding-inline: 13px; }
+ .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; }
+ .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); }
+ .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-idx { top: 5px; left: 5px; min-width: 16px; height: 16px; line-height: 16px; font-size: 10px; }
+ .board-ang { display: none; }
+ .board-use { min-height: 34px; padding: 6px 12px; }
+ .st-r .gobar {
+ position: fixed;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ z-index: 30;
+ margin: 0;
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ border-radius: 16px 16px 0 0;
+ padding: 10px 12px calc(10px + env(safe-area-inset-bottom));
+ }
+ .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 { display: inline-flex; background: none; min-height: 30px; padding: 2px 4px; }
+ .st-r .cfg { display: none; }
+ .gobar .big { width: auto; min-width: 100px; min-height: 44px; padding: 10px 16px; }
+
+ /* Picker & settings sheets */
+ .prov { grid-template-columns: 1fr 1fr; }
+ .prov label:last-child:nth-child(odd) { grid-column: 1 / -1; }
+ #pk, #cfg { padding: 0; place-items: end stretch; }
+ .cfg-box, .pk-box { width: 100%; max-height: 92dvh; border-radius: 22px 22px 0 0; }
+ .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, .pk-types, .pk-bar { margin: 0 14px 8px; }
+ #pkPoseTypes button { min-height: 36px; }
+ .pk-box .pk-g { min-width: 0; grid-template-columns: repeat(3, minmax(0, 1fr)); padding: 6px 14px 14px; gap: 12px 8px; }
+ .pk-g button { min-width: 0; }
+ #bbar { overflow-x: auto; max-width: 100%; }
+
+ /* History mobile */
+ #histSec { padding: 4px 8px 30px; }
+ .hist-bar { padding: 4px 0 8px; }
+ .hist-bar .tbar { gap: 6px; flex-wrap: wrap; }
+ .hist-sel-all, #histCount { font-size: 12px; }
+ #histQ { width: 150px; flex: 1 1 130px; font-size: 14px; }
+ .hist-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px 8px; }
+ .hist-card .hph { border-radius: 12px; }
+ .hist-card .hcbtns { opacity: 1; transform: none; right: 6px; top: 6px; gap: 6px; }
+ .hist-card .hcbtns button { width: 28px; height: 28px; font-size: 13px; }
+ .hist-card .hsel { opacity: 1; }
+ .hist-card .hinfo { padding: 7px 4px 0; }
+ .hist-card .hinfo h3 { font-size: 13.5px; }
+ .hist-card .hinfo .sub { font-size: 11.5px; }
+
+ /* Sketch & Command Palette mobile */
+ .sk-top { padding: 8px 12px; gap: 8px; }
+ .sk-meta { flex-basis: calc(100% - 92px); }
+ .sk-timer-box { order: 3; flex-basis: 100%; justify-content: space-between; gap: 6px; }
+ #skTime { font-size: 18px; min-width: 60px; text-align: left; }
+ .sk-stage { padding: 10px; }
+ .sk-frame img { max-height: calc(100dvh - 230px); }
+ .sk-foot { padding: 10px 12px calc(10px + env(safe-area-inset-bottom)); justify-content: center; }
+ .sk-tools { justify-content: center; }
+ .sk-tools button { padding: 6px 10px; font-size: 12px; }
+ #cmdPal { padding: 8vh 10px 16px; }
+ .cmd-foot { display: none; }
+}
+
+@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 (max-width: 760px) {
+ .top {
+ grid-template-rows: minmax(44px, auto) auto;
+ padding-inline: max(10px, env(safe-area-inset-left)) max(10px, env(safe-area-inset-right));
+ }
+ .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; }
+
+ .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; }
+ .notice-pop { max-width: calc(100vw - 20px); }
+ .foot { padding: 16px 12px 24px; }
+
+ .asw { position: relative; height: 34px; padding: 0 8px 0 5px; margin-right: 2px; font-size: 12px; gap: 5px; }
+ .asw .trk { width: 26px; height: 16px; }
+ .asw .kn { width: 12px; height: 12px; }
+ .asw[aria-checked=true] .kn { transform: translateX(10px); }
+ .asw::after, #theme::after { content: ""; position: absolute; inset: -5px; }
+ #theme { position: relative; }
+
+ .tbar { flex-wrap: wrap; row-gap: 8px; }
+ #bar .tbar { column-gap: 5px; row-gap: 4px; }
+ #bar .tbar .sp { flex: 1 0 0; height: 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; }
+ #sketchBtn { min-width: 38px; min-height: 38px; padding: 6px 10px; font-size: 12.5px; }
+ #batchBtn { font-size: 0; gap: 0; padding: 0 10px; width: 38px; height: 34px; justify-content: center; background: var(--sf, #f5f5f5); }
+ #batchBtn svg { margin: 0; width: 18px; height: 18px; }
+
+ .chip { min-height: 36px; }
+ .cbtns button { position: relative; width: 36px; height: 36px; font-size: 15px; }
+ .cbtns button::after, .unrec::after { content: ""; position: absolute; inset: -5px; }
+ .unrec { width: 34px; height: 34px; }
+ .angs { flex-wrap: nowrap; }
+ .angs :is(span, button) { white-space: nowrap; flex: none; padding: 3px 7px; font-size: 11px; min-height: 26px; }
+
+ #bbar { left: 8px; right: 8px; transform: none; bottom: 8px; border-radius: 18px; gap: 4px; padding: 6px 6px 6px 14px; overflow-x: auto; }
+ #bbar b { margin-right: 2px; font-size: 12.5px; }
+ #bbar button { padding: 7px 9px; font-size: 12px; }
+ #bbar [data-b=all] { display: none; }
+ @keyframes bup { from { opacity: 0; transform: translateY(24px); } }
+
+ .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; white-space: normal; }
+ .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; }
+
+ .mdl .hb, #helpBox .hb { max-height: calc(100dvh - 32px); overflow: auto; }
+ #toast { max-width: calc(100vw - 32px); white-space: normal; width: max-content; }
+ .cfg-f button, .tgen-row button { white-space: normal; }
+}
+
+@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: 520px) {
+ .studio-head { flex-wrap: wrap; row-gap: 8px; }
+ .lb-tools button span { display: none; }
+ .lb-tools button { width: 34px; padding: 0; justify-content: center; }
+}
+
+@media (max-width: 480px) {
+ .card-badges { flex-direction: column; align-items: flex-start; gap: 0; }
+ .ph:has(.card-badges .age) .unrec { top: 69px; }
+ #sketchBtn { width: 38px; padding: 0; justify-content: center; }
+ #sketchBtn span { display: none; }
+}
+
+@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; }
+ .lang-panel { right: -40px; }
+ .tgen-row { flex-wrap: wrap; }
+ html:lang(en) .studio-head .modes button,
+ html:lang(ja) .studio-head .modes button { white-space: normal; }
+}
+
+@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; }
+}
+
+@media (max-width: 365px) {
+ #rand { width: 38px; padding: 0; justify-content: center; }
+ #rand svg { display: block; }
+ #rand span { display: none; }
+}
+
+@media (max-width: 360px) {
+ #q { padding-inline-start: 32px; }
+ .sic { left: 10px; }
+ #trayMin { gap: 5px; }
+ #trayTitle { position: absolute; width: 1px; height: 1px; clip-path: inset(50%); overflow: hidden; }
+}
+
+@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; }
+}
+
+@media (min-width: 640px) and (max-width: 1024px) and (max-height: 530px) and (orientation: landscape) {
+ body { --dock-limit: 48dvh; }
+ body.studio { overflow: auto; --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; }
+ #studio { height: auto; padding: 6px 12px 70px; }
+ .studio-head h1 { font-size: 22px; }
+ .st-app { display: grid; height: auto; align-items: start; grid-template-columns: repeat(2, minmax(0, 1fr)); }
+ .st-l { grid-column: 1; grid-row: 1 / span 2; overflow: visible; }
+ .st-c { grid-column: 2; grid-row: 1; min-height: 0; }
+ .st-r { grid-column: 2; grid-row: 2; overflow: visible; }
+ .reference-board { padding: 16px; gap: 8px; }
+ .board-cards:not(.many) .board-card { width: 23%; }
+ .st-r .gobar {
+ position: fixed;
+ inset: auto 12px 0 auto;
+ z-index: 30;
+ margin: 0;
+ 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; }
+}
+
+@media (hover: hover) {
+ .theme-pop button:hover { background: var(--sf); color: var(--tx); }
+}
+
+@media (hover: hover) and (pointer: fine) {
+ .card-copy { opacity: 0; }
+ .card:hover .card-copy,
+ .card:focus-within .card-copy { opacity: 1; }
+ .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; }
+ .card-flip .flip-hint { display: inline-block; }
+ .card-flip:is(:hover, :focus-visible) .flip-hint { max-width: 44px; opacity: 1; }
+ .card-flip .flip-hint::after { content: "深度"; }
+ .ph.depth .card-flip .flip-hint::after { content: "线稿"; }
+ html:lang(en) .card-flip .flip-hint::after { content: "Depth"; }
+ html:lang(en) .ph.depth .card-flip .flip-hint::after { content: "Line"; }
+ html:lang(ja) .card-flip .flip-hint::after { content: "深度"; }
+ html:lang(ja) .ph.depth .card-flip .flip-hint::after { content: "線画"; }
+}
+
+@media (hover: none) {
+ .unrec { opacity: 1; }
+}
+
+@media (pointer: coarse) {
+ #lbPair button, .theme-pop button { min-height: 44px; }
+ .card-copy { width: 40px; height: 40px; }
+ .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 (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); } }
+
+ #themeMenu:focus-within #theme svg { animation: themeIconIn .22s var(--out); }
+ @keyframes themeIconIn { from { opacity: .5; transform: rotate(-16deg) scale(.84); } }
+
+ .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)); } }
+ #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; } }
+
+ .board-cards .board-card { animation: boardIn .3s var(--out) both; }
+ .board-cards .board-card:nth-child(2) { animation-delay: 40ms; }
+ .board-cards .board-card:nth-child(3) { animation-delay: 80ms; }
+ .board-cards .board-card:nth-child(4) { animation-delay: 120ms; }
+ @keyframes boardIn { from { opacity: 0; scale: .94; } }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ *, *::before, *::after {
+ animation: none !important;
+ animation-duration: .01ms !important;
+ animation-iteration-count: 1 !important;
+ transition: none !important;
+ transition-duration: .01ms !important;
+ }
+}
diff --git a/src/sw.js b/src/sw.js
index 3c28888..f07d44f 100644
--- a/src/sw.js
+++ b/src/sw.js
@@ -1,5 +1,5 @@
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'];
+const PRECACHE = ['./','index.html','theme.js','style.css','i18n.js','catalog.js','references.js','palette.js','app.js','sketch.js','command-palette.js','zip.js','extras.js','image-providers.js','board-export.js','studio.js','history.js','favicon.svg'];
self.addEventListener('install', event => {
event.waitUntil(caches.open(VERSION).then(cache => cache.addAll(PRECACHE)).then(() => self.skipWaiting()));
});
diff --git a/tests/build-post-regressions.mjs b/tests/build-post-regressions.mjs
new file mode 100644
index 0000000..8a8c570
--- /dev/null
+++ b/tests/build-post-regressions.mjs
@@ -0,0 +1,11 @@
+import { spawnSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+
+const script = fileURLToPath(new URL('./build-post-regressions.py', import.meta.url));
+const python = process.env.PYTHON || 'python3';
+const result = spawnSync(python, [script], { stdio: 'inherit' });
+if (result.error) {
+ console.error(result.error.message);
+ process.exit(1);
+}
+process.exit(result.status ?? 1);
diff --git a/tests/build-post-regressions.py b/tests/build-post-regressions.py
new file mode 100644
index 0000000..f420cfe
--- /dev/null
+++ b/tests/build-post-regressions.py
@@ -0,0 +1,340 @@
+"""Offline regression test for the build/post/seo/CSP pipeline (stdlib-only, no Pillow or raw archives required)."""
+
+import json
+import os
+from pathlib import Path
+import py_compile
+import re
+import shutil
+import sys
+import tempfile
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT))
+sys.path.insert(0, str(ROOT / 'tests'))
+
+import check_csp
+import post
+
+
+def _assert(cond, msg):
+ if not cond:
+ raise AssertionError(msg)
+
+
+def _check_static_invariants():
+ # 1. Compile all build pipeline modules (catches syntax errors even without Pillow installed)
+ for name in ('build.py', 'post.py', 'seo.py', 'tests/check_csp.py'):
+ py_compile.compile(str(ROOT / name), doraise=True)
+
+ # 2. Ensure exec() glue has been eliminated from build.py / post.py / seo.py
+ for name in ('build.py', 'post.py', 'seo.py'):
+ text = (ROOT / name).read_text()
+ _assert('exec(' not in text, f'{name} must not use exec() glue')
+
+ # 3. Every local script/stylesheet referenced by src/index.html must be in post.CLIENT_FILES and src/sw.js
+ index_html = (ROOT / 'src/index.html').read_text()
+ referenced = set(re.findall(r'<script\b[^>]*\bsrc="([^":/]+\.js)"', index_html))
+ referenced |= set(re.findall(r'<link\b[^>]*\brel="stylesheet"[^>]*\bhref="([^":/]+\.css)"', index_html))
+ client_set = set(post.CLIENT_FILES)
+ _assert(referenced == client_set, f'CLIENT_FILES mismatch with src/index.html: missing={referenced - client_set}, extra={client_set - referenced}')
+
+ sw_text = (ROOT / 'src/sw.js').read_text()
+ sw_precache = set(re.findall(r"'([^']+\.(?:js|css))'", sw_text))
+ _assert(client_set <= sw_precache, f'src/sw.js PRECACHE missing client files: {client_set - sw_precache}')
+
+
+def _synthetic_dataset():
+ poses_list = [
+ {
+ 'id': 'p_001',
+ 'no': 'P001',
+ 'line': '全身·标准',
+ 'cat': '站姿',
+ 'ja': '立ちポーズ1',
+ 'zh': '自然站姿',
+ 'en': 'standing pose',
+ 'lineEn': 'full body, solo',
+ 'angles': [
+ {'zh': '正面', 'en': 'front view', 't': 'p/t/p_001_f.webp', 'i': 'p/i/p_001_f.webp', 'o': 'o/p/p_001_f.png'},
+ {'zh': '侧面', 'en': 'side view', 't': 'p/t/p_001_s.webp', 'i': 'p/i/p_001_s.webp', 'o': 'o/p/p_001_s.png'},
+ ],
+ },
+ {
+ 'id': 'p_002',
+ 'no': 'P002',
+ 'line': '全身·性感',
+ 'cat': '性感·大胆',
+ 'ja': 'セクシー1',
+ 'zh': '性感站姿',
+ 'en': 'sexy standing pose',
+ 'lineEn': 'full body, solo, sexy',
+ 'a': 1,
+ 'angles': [
+ {'zh': '正面', 'en': 'front view', 't': 'p/t/p_002_f.webp', 'i': 'p/i/p_002_f.webp', 'o': 'o/p/p_002_f.png'},
+ ],
+ },
+ ]
+ poses = {p['id']: p for p in poses_list}
+
+ # 4 costumes with "dress" and "black" so tag threshold (>=4) triggers /tag/dress/ and /tag/black/
+ costumes = [
+ {
+ 'id': f'c_00{i}',
+ 'cat': '春季',
+ 'catEn': 'spring',
+ 'kw': 'black dress boots',
+ 'zh': f'黑色连衣裙搭配短靴穿搭 {i}。',
+ 'en': 'spring outfit, black dress, short boots',
+ 'ti': f'黑色连衣裙 {i}',
+ 't': f'c/t/c_00{i}.webp',
+ 'm': f'c/m/c_00{i}.webp',
+ 'i': f'c/i/c_00{i}.webp',
+ 'o': f'o/c/c_00{i}.png',
+ }
+ for i in range(1, 5)
+ ]
+
+ anime = [
+ {
+ 'id': 'a_001',
+ 'cat': '夏季',
+ 'catEn': 'summer',
+ 'kw': 'white dress',
+ 'zh': '白色连衣裙动画穿搭。',
+ 'en': 'summer anime outfit, white dress',
+ 'ti': '白色连衣裙',
+ 't': 'a/t/a_001.webp',
+ 'm': 'a/m/a_001.webp',
+ 'i': 'a/i/a_001.webp',
+ 'o': 'o/a/a_001.png',
+ },
+ {
+ 'id': 'cdb_001',
+ 'cat': '夏季',
+ 'catEn': 'summer',
+ 'kw': 'sailor uniform',
+ 'zh': '水手服。',
+ 'en': 'sailor uniform',
+ 'ti': '水手服',
+ 't': 'https://charadb-2fi.pages.dev/t/cdb_001.webp',
+ 'm': 'https://charadb-2fi.pages.dev/m/cdb_001.webp',
+ 'i': 'https://charadb-2fi.pages.dev/i/cdb_001.webp',
+ 'o': '',
+ 'ext': 1,
+ },
+ ]
+
+ portraits = [
+ {
+ 'id': 'r_001',
+ 'no': 'F001',
+ 'sec': '正脸',
+ 'len': '短发',
+ 'st': '自然清透',
+ 'ti': '自然清透',
+ 'zh': '一位亚洲年轻女性,短发,正脸参考。',
+ 'en': 'young Asian woman, short hair, front portrait',
+ 'ja': 'ショート',
+ 't': 'r/t/r_001.webp',
+ 'm': 'r/m/r_001.webp',
+ 'i': 'r/m/r_001.webp',
+ 'o': 'o/r/r_001.png',
+ 'w': 800,
+ 'h': 1000,
+ },
+ ]
+
+ depths = {
+ 'packs': [{'id': 'base', 'name': 'AI Pose Depth Gallery'}],
+ 'items': [
+ {
+ 'id': 'd_001',
+ 'no': 'D001',
+ 'line': '全身·标准',
+ 'cat': '站姿',
+ 'zh': '深度站姿',
+ 'en': 'depth standing pose',
+ 'lineEn': 'full body, solo',
+ 'angles': [
+ {
+ 'zh': '正面',
+ 'en': 'front view',
+ 't': 'https://pwimg.0vo.pro/d/thumbs/d_001.webp',
+ 'i': 'https://pwimg.0vo.pro/d/img/d_001.webp',
+ }
+ ],
+ }
+ ],
+ }
+
+ def view_item(prefix, item_id, title):
+ return {
+ 'id': item_id,
+ 'cat': '默认',
+ 'ti': title,
+ 'zh': title,
+ 'en': title,
+ 'ja': '',
+ 'line': '标准',
+ 'lineEn': 'standard',
+ 'no': item_id,
+ 'angles': [
+ {'zh': '正面', 'en': 'front view', 't': f'{prefix}/t/{item_id}_front.webp', 'i': f'{prefix}/i/{item_id}_front.webp', 'o': f'o/{prefix}/{item_id}_front.webp'}
+ ],
+ }
+
+ hair = [
+ {
+ 'id': 'h_001',
+ 'cat': '长发',
+ 'ti': '黑长直',
+ 'zh': '黑长直发型',
+ 'en': 'long straight black hair',
+ 't': 'https://charadb-2fi.pages.dev/hair/h_001.webp',
+ 'm': 'https://charadb-2fi.pages.dev/hair/h_001.webp',
+ 'i': 'https://charadb-2fi.pages.dev/hair/h_001.webp',
+ 'o': '',
+ 'ext': 1,
+ }
+ ]
+
+ dump = lambda obj: json.dumps(obj, ensure_ascii=False, separators=(',', ':'))
+ catalogs = {
+ 'poses.json': dump(poses_list),
+ 'costumes.json': dump(costumes),
+ 'anime.json': dump(anime),
+ 'portraits.json': dump(portraits),
+ 'depths.json': dump(depths),
+ 'expressions.json': dump([view_item('e', 'E01', '微笑')]),
+ 'hair.json': dump(hair),
+ 'dynasties.json': dump([view_item('y', 'Y01', '唐代襦裙')]),
+ 'scenes.json': dump([view_item('s', 'S01', '咖啡馆')]),
+ 'lights.json': dump([view_item('l', 'L01', '逆光')]),
+ 'props.json': dump([view_item('t', 'T01', '雨伞')]),
+ 'furniture.json': dump([view_item('f', 'F01', '木椅')]),
+ }
+ data = {
+ 'poses': poses,
+ 'poses_list': poses_list,
+ 'costumes': costumes,
+ 'anime': anime,
+ 'portraits': portraits,
+ }
+ return catalogs, data
+
+
+def _run_pipeline_regression():
+ catalogs, data = _synthetic_dataset()
+ with tempfile.TemporaryDirectory(prefix='posewear-post-test-') as tmp:
+ tmp_path = Path(tmp)
+ dist = tmp_path / 'dist'
+ dist.mkdir()
+ for entry in (ROOT / 'src').iterdir():
+ shutil.copy(entry, dist / entry.name)
+
+ ctx = {
+ 'raw_dir': str(tmp_path / 'raw-empty'),
+ 'dist_dir': str(dist),
+ 'src_dir': str(ROOT / 'src'),
+ 'functions_dir': str(ROOT / 'functions'),
+ 'site': 'https://posewear.pages.dev',
+ 'asset_host': 'https://pwimg.0vo.pro',
+ 'wa_token': 'test-wa-token-123',
+ 'urls_path': str(tmp_path / 'urls.txt'),
+ 'indexnow_key_path': str(tmp_path / 'indexnow.key'),
+ 'catalogs': catalogs,
+ 'data': data,
+ 'depth_origins': ['https://ai-pose-depth-gallery.pages.dev'],
+ 'hotlink_origins': ['https://charadb-2fi.pages.dev'],
+ }
+ result = post.run(ctx)
+
+ # 1. Official CSP & catalog check must pass with 0 issues
+ issues = check_csp.check(dist)
+ _assert(not issues, 'check_csp.check failed:\n' + '\n'.join(issues))
+
+ # 2. All 15 client files hashed into dist/assets/ and unhashed removed from dist/
+ assets = result['assets']
+ for name in post.CLIENT_FILES:
+ _assert(name in assets, f'Missing asset mapping for {name}')
+ _assert((dist / assets[name]).is_file(), f'Hashed file missing: {assets[name]}')
+ _assert(not (dist / name).exists(), f'Unhashed file was not removed: {name}')
+
+ # 3. Compiled app.js matches catalog-source.mjs discovery contracts
+ app_js = (dist / assets['app.js']).read_text()
+ _assert("const AH='https://pwimg.0vo.pro/';" in app_js, 'AH asset host injection failed')
+ discovered = set(re.findall(r'["\'](?:/assets/)?([a-z]+)\.[a-f0-9]{10}\.json["\']', app_js))
+ expected_catalogs = {f.removesuffix('.json') for f in post.CATALOG_FILES}
+ _assert(discovered == expected_catalogs, f'app.js catalog discovery mismatch: {expected_catalogs - discovered}')
+
+ # 4. index.html references all hashed client files, stats, SSR cards, footer index, WA beacon
+ idx = (dist / 'index.html').read_text()
+ for name in post.CLIENT_FILES:
+ _assert(f'"/{assets[name]}"' in idx, f'index.html missing hashed reference for {name}')
+ _assert('data-stat="pose" data-n="1" data-na="2"' in idx, 'pose stat counter mismatch')
+ _assert('data-stat="cos" data-n="4" data-na="4"' in idx, 'costume stat counter mismatch')
+ _assert('data-stat="ani" data-n="2" data-na="2"' in idx, 'anime stat counter mismatch')
+ _assert('class="card ssr"' in idx, 'SSR pose cards missing in index.html')
+ _assert('data-cf-beacon=\'{"token": "test-wa-token-123"}\'' in idx, 'Web Analytics beacon missing')
+
+ # 5. Service Worker precache updated with hashed files
+ sw = (dist / 'sw.js').read_text()
+ _assert("'posewear-development'" not in sw, 'sw.js version was not fingerprinted')
+ for name in post.CLIENT_FILES + ['poses.json', 'depths.json']:
+ _assert(f'"/{assets[name]}"' in sw, f'sw.js PRECACHE missing {name}')
+
+ # 6. _headers CSP allows WA beacon, hotlinks, asset host, and loopback http
+ headers = (dist / '_headers').read_text()
+ for token in (
+ 'https://static.cloudflareinsights.com',
+ 'https://pwimg.0vo.pro',
+ 'https://charadb-2fi.pages.dev',
+ 'https://ai-pose-depth-gallery.pages.dev',
+ 'http://localhost:*',
+ 'http://127.0.0.1:*',
+ "'sha256-",
+ '/en/*',
+ '/sitemap*',
+ ):
+ _assert(token in headers, f'_headers missing expected token: {token}')
+
+ # 7. Pages Functions copied into dist/functions/
+ _assert((dist / 'functions/api/proxy.js').is_file(), 'functions/api/proxy.js not copied into dist/')
+
+ # 8. Static SEO pages, sitemaps, robots.txt and IndexNow key generated
+ for rel in (
+ '404.html',
+ 'en/index.html',
+ 'pose/index.html',
+ 'en/pose/index.html',
+ 'pose/p_001/index.html',
+ 'en/pose/p_001/index.html',
+ 'costume/c_001/index.html',
+ 'en/costume/c_001/index.html',
+ 'anime/a_001/index.html',
+ 'portrait/r_001/index.html',
+ 'tag/dress/index.html',
+ 'en/tag/dress/index.html',
+ 'sitemap_index.xml',
+ 'sitemap.xml',
+ 'sitemap-pose.xml',
+ 'sitemap-pages.xml',
+ 'robots.txt',
+ ):
+ _assert((dist / rel).is_file(), f'Expected SEO output missing: {rel}')
+
+ # Adult pose must NOT leak into public static SEO detail pages
+ _assert(not (dist / 'pose/p_002/index.html').exists(), 'Adult pose leaked into public SEO page')
+ # CharaDB hotlink anime outfit must NOT generate static detail page
+ _assert(not (dist / 'anime/cdb_001/index.html').exists(), 'External hotlink anime item leaked into static detail page')
+
+ key = (tmp_path / 'indexnow.key').read_text().strip()
+ _assert((dist / f'{key}.txt').read_text().strip() == key, 'IndexNow key file mismatch')
+ _assert((tmp_path / 'urls.txt').read_text().strip().splitlines(), 'urls.txt is empty')
+
+
+if __name__ == '__main__':
+ _check_static_invariants()
+ _run_pipeline_regression()
+ print('PASS build/post/seo/CSP module pipeline regressions')
diff --git a/tests/run.mjs b/tests/run.mjs
index 981ca31..de6deca 100644
--- a/tests/run.mjs
+++ b/tests/run.mjs
@@ -5,6 +5,7 @@ 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 = [
+ 'build-post-regressions.mjs',
'gallery-regressions.js',
'locale-regressions.js',
'local-engine-regressions.mjs',