diff --git a/.gitignore b/.gitignore index a0673c0..f057649 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ dist/ *.log .omo/ .workbuddy/ +style-source/tools/shot-*.png diff --git a/style-source/README.md b/style-source/README.md new file mode 100644 index 0000000..914b331 --- /dev/null +++ b/style-source/README.md @@ -0,0 +1,83 @@ +# 风格库(style-source) + +资源库面板里的 AI 绘画风格浏览器。310 个风格、12 个分类,点到哪个风格就能把**预览图**插进画布(`ref` 节点)或把**提示词**插进画布(`prompt` 节点)。 + +风格数据来自开源项目 [style-source](https://github.com/malongan/style-source),插件直连它的 GitHub Pages 静态资源,无后端、无 Key。 + +## 能力 + +| 声明 | 用途 | +|---|---| +| `panels` | 注册「风格库」标签页到资源库面板 | +| `canvas` | `getNodes` / `getSelectedNode`(算插入坐标) | +| `canvasWrite` | `createImageNode`(插参考图)/ `createNode('prompt', …)`(插提示词) | + +## 交互 + +- **搜索**:匹配名称 / 编号 / id / 分类 / 摘要 / 标签 / 触发词,150ms 防抖。 +- **分类**:单行横向滚动的 chips,按数量降序,记住上次选的分类。 +- **网格**:分批渲染(每批 90 个),滚到底自动续渲染;缩略图原生懒加载。 +- **详情**:窄面板铺满覆盖层,宽面板变右侧栏;大图 + 标签 + 摘要 + 提示词 + 变量表单。 +- **变量替换**:提示词里的 `{角色描述}` 这类占位符给输入框,填了就替换,**留空的保留 `{原占位符}`**(换成空串会把提示词结构弄丢)。未填数量实时提示。 +- **插入参考图**:`fetch` 大图 → blob → dataURL → `createImageNode`(宿主只认 `data:` URL)。 +- **插入提示词**:插到当前选中节点右侧;没选中时插到最右节点的右侧;空画布落 `(80, 80)`。 + +## 面板宽度自适应(重要) + +资源库面板宽度不是固定的:侧栏 240–560 可拖、放大窗口 920×600 可八向缩放、还有 embedded 嵌入形态。所以: + +- 网格列数交给 `repeat(auto-fill, minmax(112px, 1fr))`,不写死。 +- 详情用 **480px 一个拐点**切两种形态(窄=覆盖层 / 宽=右侧栏),**同一个 DOM 只换定位** —— 切档时变量输入和滚动位置不丢。 +- 判定用 `ResizeObserver` 而不是 `@media`:拖侧栏时视口没变,`@media` 完全不响应。 +- 面板容器 `.iwb-full-panel-plugin` 在宿主 `style.css` 里**没有任何样式定义**(裸 div),所以根元素必须自带 `width/height:100%; min-height:0; display:flex`,否则撑不开或双滚动条。 + +> 侧栏 ↔ 放大窗口是两个不同的 React 位置,同一个插件会被 `mount` 两次(不同 DOM 节点)。DOM 每次重建,但数据 / 图片 blob / 选中项 / 搜索词 / 变量输入都在模块级缓存里,切形态不会重拉 1.1MB JSON、不重下预览图、不丢选中。 + +## 设置项 + +| 键 | 说明 | +|---|---| +| `dataUrl` | styles.json 地址,默认 `https://malongan.github.io/style-source/data/styles.json`。国内访问慢可自行镜像后改这里。 | + +插图默认用 `preview_webp`(大图,清晰)。详情里勾「插图用缩略图」改用 `*.thumb.webp`,省画布体积(dataURL 会让存档膨胀约 33%)。 + +## 不需要改宿主 CSP + +数据与图片都是公网 `https://`,宿主 `_headers` 的 `img-src … https:` / `connect-src … https:` 已经放行。对比 `ai-chat`(连本机 `http://127.0.0.1:3425`)必须单独加端口。 + +## 发布 + +`src/index.js` 是手写单文件 IIFE,不构建,直接发布: + +```bash +cp src/index.js /tmp/plugin-style-source.js +cd ../image-workbench-web +node scripts/plugins-publish.mjs /tmp/plugin-<其余插件>.js /tmp/plugin-style-source.js --upload --version style-source=1.0.0 +``` + +图标:宿主 `app.js` 的 `PLUGIN_ICONS` 可加 `'style-source': 'palette'`(不加则用面板 manifest 自带的 `palette`,效果一致)。 + +## 数据结构(上游 styles.json) + +```jsonc +{ + "meta": { "total": 310, "categories": ["brand_kv", "creative", …] }, + "styles": [{ + "id": "y3k_cool_girl_portrait", + "code": "ST0001", + "name": "Y3K 酷酷女孩", + "category": "creative", + "tags": ["Y3K", "赛博朋克"], + "triggers": ["Y3K", "酷女孩"], + "ratio": "9:21", + "summary": "……", + "features": ["……"], + "prompt": "……一个3D风格的虚拟{角色描述}半身肖像……", + "variables": { "画面-角色": "角色描述", "画面-诗词": "{诗词}" }, // value 可能自带花括号 + "preview_webp": "https://…/xxx.webp", + "preview_webp_thumb": "https://…/xxx.thumb.webp", + "source_url": "https://jimeng.jianying.com/…", + "source_author": "卢西西" + }] +} +``` diff --git a/style-source/package.json b/style-source/package.json new file mode 100644 index 0000000..7c8aad5 --- /dev/null +++ b/style-source/package.json @@ -0,0 +1,11 @@ +{ + "name": "@iwb-plugin/style-source", + "private": true, + "version": "1.0.0", + "description": "风格库:资源库面板里浏览 310 个 AI 绘画风格(12 分类 / 搜索 / 变量替换),一键把预览图插入画布 ref 节点、把提示词插入 prompt 节点", + "ibwPlugin": { + "id": "style-source", + "entry": "src/index.js", + "apiVersion": 1 + } +} diff --git a/style-source/src/index.js b/style-source/src/index.js new file mode 100644 index 0000000..b53bbd6 --- /dev/null +++ b/style-source/src/index.js @@ -0,0 +1,849 @@ +// iwb-plugin: 风格库 —— 资源库面板里浏览 310 个 AI 绘画风格,一键把预览图插入画布(ref 节点)或把提示词插入画布(prompt 节点)。 +// 数据与图片来自 https://malongan.github.io/style-source (GitHub Pages,CORS 为 *),插件直连,无后端。 +// +// 面板宽度可变(侧栏 240~560 拖动、放大窗口 920×600 八向缩放、embedded 嵌入),所以布局不能写死两栏: +// 网格列数交给 CSS auto-fill;详情用 480px 一个拐点切两态(窄=覆盖 body / 宽=右侧栏),同一个 DOM 只换定位。 +// 判定用 ResizeObserver 而不是 @media —— 拖侧栏时视口没变,@media 完全不响应。 +// +// ⚠️ 宿主 ui-lib-sidebar.js 里侧栏和放大窗口可以同时渲染同一个插件面板(两处都调 mount,容器是不同的 DOM 节点), +// 所以这里按「一个容器一个实例」组织:每个实例有自己的 DOM 引用和 ResizeObserver,数据/图片/选中项走模块级共享。 +// 早期版本用单个全局 dom 指针,第二个容器一挂载就把第一个容器的 RO 断了,旧容器再也不响应宽度变化。 +// +// 面板容器 .iwb-full-panel-plugin 在宿主 style.css 里没有任何样式定义(裸 div), +// 宽高必须由插件根自己保证,否则在 flex 父级里撑不开或溢出双滚动条。 +;(function (global) { + 'use strict' + + if (!global.IWBPluginHost) return + + const DEFAULT_DATA = 'https://malongan.github.io/style-source/data/styles.json' + const PAGE_SIZE = 90 // 网格分批渲染,避免一次建 310 个 DOM + const WIDE_MIN = 480 // 详情从「覆盖 body」切到「右侧栏」的宽度拐点 + const PREF_KEY = 'iwb.style-source.prefs.v1' + + // 分类中文名:取自项目自带的 gallery/src/gallery.js(去掉 emoji,与宿主面板风格统一) + const CAT_NAMES = { + social_media: '社交媒体', brand_kv: '品牌视觉', 'e-commerce': '电商', science: '科研', + print: '印刷品', ip_character: 'IP 角色', travel: '旅行', fashion: '时尚', + creative: '创意', vigo_cookbook: 'Cookbook', typography: '字体设计', editorial: '编辑画册', + } + + // ---------------- 模块级共享缓存 ---------------- + // 多容器共用:切侧栏/放大窗口时不重拉 1.1MB JSON、不重下预览图、不丢选中项与变量输入。 + const CACHE = { + data: null, // { meta, styles:[...] } + loading: null, // Promise + blobs: {}, // url -> Promise + selId: null, + selOpen: false, + query: '', + cat: 'all', + vars: {}, // styleId -> { 占位符名: 用户输入 } + } + + // host 元素 -> 实例。容器被 React 卸载后随 WeakMap 自动释放 + const INSTANCES = new WeakMap() + + // ---------------- 小工具 ---------------- + + function el(tag, attrs, kids) { + const node = document.createElement(tag) + if (attrs) { + for (const key in attrs) { + const value = attrs[key] + if (value === null || value === undefined) continue + if (key === 'class') node.className = value + else if (key === 'text') node.textContent = String(value) + else if (key.slice(0, 2) === 'on') node.addEventListener(key.slice(2).toLowerCase(), value) + // checked/disabled 是布尔属性:setAttribute('disabled','false') 依然是「有值」⇒ 仍然禁用,必须走 property + else if (key === 'checked' || key === 'disabled' || key === 'selected') node[key] = Boolean(value) + else node.setAttribute(key, String(value)) + } + } + if (kids !== null && kids !== undefined) { + const arr = Array.isArray(kids) ? kids : [kids] + for (const kid of arr) { + if (kid === null || kid === undefined || kid === false) continue + node.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid) + } + } + return node + } + + function prefAll() { + try { + const raw = global.localStorage.getItem(PREF_KEY) + return raw ? JSON.parse(raw) || {} : {} + } catch (error) { return {} } + } + + function prefSet(key, value) { + try { + const all = prefAll() + all[key] = value + global.localStorage.setItem(PREF_KEY, JSON.stringify(all)) + } catch (error) { /* 隐私模式下写不了,忽略 */ } + } + + function readErr(error) { + const msg = String((error && (error.message || error)) || '未知错误') + if (/Failed to fetch|NetworkError|Load failed/i.test(msg)) { + return '网络请求失败(可能被断网/代理拦截,或数据源 CORS 变了)' + } + return msg + } + + // ---------------- 样式 ---------------- + + const CSS = ` +.iwb-ss-root { + position: relative; + display: flex; + flex-direction: column; + width: 100%; + height: 100%; + min-width: 0; + min-height: 0; + overflow: hidden; + background: var(--iwb-panel, #fff); + color: var(--iwb-text, #1c2333); + font-size: var(--fs-md, 12px); + line-height: 1.5; +} +.iwb-ss-root *, .iwb-ss-root *::before, .iwb-ss-root *::after { box-sizing: border-box; } + +.iwb-ss-tools { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; padding: 8px 10px 6px; } +.iwb-ss-search { + flex: 1 1 auto; min-width: 0; height: 28px; padding: 0 9px; + border: 1px solid var(--iwb-border, #d5d9e0); border-radius: var(--rd-sm, 6px); + background: var(--iwb-layer2, #fff); color: inherit; font-size: var(--fs-md, 12px); + outline: none; font-family: inherit; +} +.iwb-ss-search::placeholder { color: var(--iwb-text2, #4d5668); opacity: .55; } +.iwb-ss-search:focus { border-color: var(--iwb-brand, #6b7280); } +.iwb-ss-btn { + flex: 0 0 auto; height: 28px; padding: 0 10px; + border: 1px solid var(--iwb-border, #d5d9e0); border-radius: var(--rd-sm, 6px); + background: var(--iwb-layer2, #fff); color: inherit; font-size: var(--fs-md, 12px); + cursor: pointer; white-space: nowrap; font-family: inherit; +} +.iwb-ss-btn:hover:not(:disabled) { border-color: var(--iwb-border2, #b9bfca); background: var(--iwb-layer, #f0f1f4); } +.iwb-ss-btn:disabled { opacity: .45; cursor: not-allowed; } +.iwb-ss-btn.is-key { border-color: var(--iwb-brand, #6b7280); } +.iwb-ss-btn.is-key:hover:not(:disabled) { background: var(--iwb-brand, #6b7280); color: var(--iwb-panel, #fff); } + +/* 分类 chips:单行横向滚动。窄面板下如果换行会直接吃掉半屏高度 */ +.iwb-ss-chips { + flex: 0 0 auto; display: flex; gap: 4px; padding: 0 10px 7px; + overflow-x: auto; overflow-y: hidden; scrollbar-width: none; +} +.iwb-ss-chips::-webkit-scrollbar { display: none; } +.iwb-ss-chip { + flex: 0 0 auto; height: 22px; padding: 0 9px; + border: 1px solid var(--iwb-border, #d5d9e0); border-radius: 11px; + background: transparent; color: var(--iwb-text2, #4d5668); + font-size: var(--fs-sm, 11px); cursor: pointer; white-space: nowrap; font-family: inherit; +} +.iwb-ss-chip:hover { border-color: var(--iwb-border2, #b9bfca); } +.iwb-ss-chip.is-on { background: var(--iwb-brand, #6b7280); border-color: var(--iwb-brand, #6b7280); color: var(--iwb-panel, #fff); } + +.iwb-ss-body { flex: 1 1 auto; min-height: 0; min-width: 0; display: flex; position: relative; } + +.iwb-ss-grid { + flex: 1 1 auto; min-width: 0; min-height: 0; overflow-y: auto; + display: grid; grid-template-columns: repeat(auto-fill, minmax(112px, 1fr)); + /* ⚠️ grid-auto-rows 必须显式 max-content:默认 auto 时,图片还没加载出固有尺寸(naturalWidth=0), + 行高会塌到「一行文字」的高度(实测 18.89px),卡片被 overflow:hidden 裁成一条横杠,名称也看不见。 */ + grid-auto-rows: max-content; + gap: 8px; padding: 2px 10px 10px; align-content: start; +} +.iwb-ss-card { + position: relative; display: flex; flex-direction: column; min-width: 0; + border: 1px solid var(--iwb-border, #d5d9e0); border-radius: var(--rd, 8px); + overflow: hidden; background: var(--iwb-layer2, #fff); cursor: pointer; +} +.iwb-ss-card:hover { border-color: var(--iwb-border2, #b9bfca); } +.iwb-ss-card.is-sel { border-color: var(--iwb-brand, #6b7280); box-shadow: inset 0 0 0 1px var(--iwb-brand, #6b7280); } +.iwb-ss-thumb { display: block; width: 100%; aspect-ratio: 3 / 4; object-fit: cover; background: var(--iwb-layer, #f0f1f4); } +.iwb-ss-nothumb { + width: 100%; aspect-ratio: 3 / 4; display: flex; align-items: center; justify-content: center; + background: var(--iwb-layer, #f0f1f4); color: var(--iwb-text2, #4d5668); opacity: .5; font-size: var(--fs-xs, 10px); +} +.iwb-ss-cardmeta { padding: 3px 6px 5px; min-width: 0; } +.iwb-ss-cardname { + font-size: var(--fs-sm, 11px); line-height: 1.35; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +} +.iwb-ss-cardcode { font-size: var(--fs-xs, 10px); color: var(--iwb-text2, #4d5668); opacity: .7; } + +/* 详情:一个 DOM 两种形态。窄档覆盖 .iwb-ss-body(保留顶部搜索/分类,便于边看边换) */ +.iwb-ss-detail { + display: none; flex-direction: column; min-width: 0; min-height: 0; + background: var(--iwb-panel, #fff); +} +.iwb-ss-root[data-layout="narrow"] .iwb-ss-detail.is-open { display: flex; position: absolute; inset: 0; z-index: 5; } +.iwb-ss-root[data-layout="wide"] .iwb-ss-detail { display: flex; flex: 0 0 46%; max-width: 380px; border-left: 1px solid var(--iwb-border, #d5d9e0); } + +.iwb-ss-dhead { + flex: 0 0 auto; display: flex; align-items: center; gap: 6px; + padding: 7px 10px; border-bottom: 1px solid var(--iwb-border, #d5d9e0); +} +.iwb-ss-dtitle { + flex: 1 1 auto; min-width: 0; font-size: var(--fs-lg, 13px); font-weight: 500; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +} +.iwb-ss-dclose { + flex: 0 0 auto; width: 24px; height: 24px; padding: 0; line-height: 1; + border: 1px solid var(--iwb-border, #d5d9e0); border-radius: var(--rd-sm, 6px); + background: transparent; color: inherit; cursor: pointer; font-size: 13px; font-family: inherit; +} +.iwb-ss-dbody { + flex: 1 1 auto; min-height: 0; overflow-y: auto; + padding: 10px; display: flex; flex-direction: column; gap: 10px; +} +.iwb-ss-dfoot { + flex: 0 0 auto; display: flex; gap: 6px; + padding: 8px 10px; border-top: 1px solid var(--iwb-border, #d5d9e0); +} +.iwb-ss-dfoot .iwb-ss-btn { flex: 1 1 0; height: 30px; } + +/* 预览图比例差异极大(9:21 竖图到 21:9 横图都有)。不限高的话竖图会撑满详情栏,变量和提示词全被挤到折叠以下。 + 用 contain 而不是 cover:宁可两侧留底色,也不裁掉画面 —— 用户是来参考构图的。 */ +.iwb-ss-big { + display: block; width: 100%; max-height: 320px; object-fit: contain; + border-radius: var(--rd, 8px); border: 1px solid var(--iwb-border, #d5d9e0); background: var(--iwb-layer, #f0f1f4); +} +.iwb-ss-tagrow { display: flex; flex-wrap: wrap; gap: 4px; } +.iwb-ss-tag { + font-size: var(--fs-xs, 10px); padding: 1px 7px; border-radius: 9px; + background: var(--iwb-layer, #f0f1f4); color: var(--iwb-text2, #4d5668); +} +.iwb-ss-label { + font-size: var(--fs-sm, 11px); color: var(--iwb-text2, #4d5668); + display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 4px; +} +.iwb-ss-summary { font-size: var(--fs-md, 12px); color: var(--iwb-text2, #4d5668); line-height: 1.6; } +.iwb-ss-text { + font-size: var(--fs-md, 12px); line-height: 1.7; white-space: pre-wrap; word-break: break-word; + background: var(--iwb-layer, #f0f1f4); padding: 8px; border-radius: var(--rd-sm, 6px); + max-height: 150px; overflow-y: auto; +} +.iwb-ss-root[data-layout="narrow"] .iwb-ss-big { max-height: 240px; } +.iwb-ss-root[data-layout="narrow"] .iwb-ss-text { max-height: 240px; } +.iwb-ss-var { display: flex; align-items: center; gap: 6px; margin-bottom: 5px; } +.iwb-ss-varlabel { + flex: 0 0 auto; font-size: var(--fs-sm, 11px); color: var(--iwb-text2, #4d5668); + max-width: 44%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +} +.iwb-ss-varinput { + flex: 1 1 auto; min-width: 0; height: 24px; padding: 0 7px; + border: 1px solid var(--iwb-border, #d5d9e0); border-radius: var(--rd-sm, 6px); + background: var(--iwb-layer2, #fff); color: inherit; font-size: var(--fs-sm, 11px); + outline: none; font-family: inherit; +} +.iwb-ss-varinput:focus { border-color: var(--iwb-brand, #6b7280); } +.iwb-ss-check { display: flex; align-items: center; gap: 6px; font-size: var(--fs-sm, 11px); color: var(--iwb-text2, #4d5668); cursor: pointer; } +.iwb-ss-check input { margin: 0; } + +.iwb-ss-status { + flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; + padding: 4px 10px 6px; font-size: var(--fs-sm, 11px); + color: var(--iwb-text2, #4d5668); opacity: .8; +} +.iwb-ss-empty { grid-column: 1 / -1; padding: 26px 14px; text-align: center; color: var(--iwb-text2, #4d5668); font-size: var(--fs-md, 12px); line-height: 1.9; opacity: .75; } + +.iwb-ss-toast { + position: absolute; left: 50%; bottom: 46px; z-index: 20; + transform: translateX(-50%) translateY(6px); + max-width: 88%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + background: rgba(22, 26, 34, .9); color: #fff; + font-size: var(--fs-md, 12px); padding: 6px 12px; border-radius: 14px; + opacity: 0; pointer-events: none; transition: opacity .18s ease, transform .18s ease; +} +.iwb-ss-toast.is-show { opacity: 1; transform: translateX(-50%) translateY(0); } +` + + function ensureStyle() { + const id = 'iwb-ss-style' + if (document.getElementById(id)) return + try { + ;(document.head || document.documentElement).appendChild(el('style', { id: id, text: CSS })) + } catch (error) { /* 样式注入失败不影响功能,只是丑一点 */ } + } + + // ---------------- 数据 ---------------- + + function dataUrlOf(ctx) { + let value = '' + try { value = String(ctx.settings.get('dataUrl') || '') } catch (error) { value = '' } + return value.trim() || DEFAULT_DATA + } + + function loadData(ctx, force) { + if (CACHE.data && !force) return Promise.resolve(CACHE.data) + if (CACHE.loading) return CACHE.loading + const url = dataUrlOf(ctx) + // credentials: 'omit' —— 公共静态文件,别把宿主的 cookie 带过去 + CACHE.loading = fetch(url, { mode: 'cors', credentials: 'omit' }) + .then((resp) => { + if (!resp.ok) throw new Error('HTTP ' + resp.status + '(' + url + ')') + return resp.json() + }) + .then((json) => { + const list = json && json.styles + if (!Array.isArray(list) || !list.length) throw new Error('数据格式不对:没有 styles 数组') + CACHE.data = { meta: json.meta || {}, styles: list } + CACHE.loading = null + return CACHE.data + }) + .catch((error) => { + CACHE.loading = null + throw error + }) + return CACHE.loading + } + + function thumbOf(style) { + return style.preview_webp_thumb || style.preview_webp || + (Array.isArray(style.preview_urls) && style.preview_urls[0]) || '' + } + + function bigOf(style) { + return style.preview_webp || (Array.isArray(style.preview_urls) && style.preview_urls[0]) || thumbOf(style) + } + + function catName(key) { return CAT_NAMES[key] || key } + + function filtered() { + const list = (CACHE.data && CACHE.data.styles) || [] + const q = CACHE.query.trim().toLowerCase() + return list.filter((s) => { + if (CACHE.cat !== 'all' && s.category !== CACHE.cat) return false + if (!q) return true + const hay = [ + s.name, s.code, s.id, s.category, s.summary, + (s.tags || []).join(' '), (s.triggers || []).join(' '), + ].join(' ').toLowerCase() + return hay.indexOf(q) >= 0 + }) + } + + function styleById(id) { + const list = (CACHE.data && CACHE.data.styles) || [] + for (const s of list) if (s.id === id) return s + return null + } + + // ---------------- 变量 ---------------- + + // variables 的 value 有两种写法:'角色描述' 和 '{诗词}'(自带花括号),统一剥成占位符名 + function varKeys(style) { + const vars = style && style.variables + if (!vars || typeof vars !== 'object') return [] + const seen = {} + const out = [] + for (const label of Object.keys(vars)) { + const raw = String(vars[label] || '').trim() + const name = raw.replace(/^\{+/, '').replace(/\}+$/, '').trim() || label + if (!name || seen[name]) continue + seen[name] = true + out.push({ label: label, name: name }) + } + return out + } + + // 留空的变量保留 {原占位符} 原样 —— 替换成空串会把提示词结构弄丢,用户后面根本看不出漏了什么 + function applyVars(style, values) { + let text = String((style && style.prompt) || '') + for (const item of varKeys(style)) { + const val = String((values && values[item.name]) || '').trim() + if (!val) continue + // 用 split/join 而不是正则:占位符名里可能出现正则元字符 + text = text.split('{' + item.name + '}').join(val) + } + return text + } + + function unfilledCount(style, values) { + return varKeys(style).filter((item) => !String((values && values[item.name]) || '').trim()).length + } + + // ---------------- 取图 ---------------- + + function loadBlob(url) { + if (CACHE.blobs[url]) return CACHE.blobs[url] + const promise = fetch(url, { mode: 'cors', credentials: 'omit' }).then((resp) => { + if (!resp.ok) throw new Error('图片 HTTP ' + resp.status) + return resp.blob() + }) + CACHE.blobs[url] = promise + promise.catch(() => { delete CACHE.blobs[url] }) // 失败不缓存,下次还能重试 + return promise + } + + function blobToDataUrl(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader() + reader.onload = () => resolve(String(reader.result || '')) + reader.onerror = () => reject(new Error('读取图片失败')) + reader.readAsDataURL(blob) + }) + } + + // ---------------- 插画布 ---------------- + + // getNodes 里没有节点宽度,用经验值估:prompt 节点约 320 宽,留 60 间距 + const GAP_X = 380 + function nextSpot(ctx) { + let nodes = [] + let sel = null + try { nodes = ctx.canvas.getNodes() || [] } catch (error) { nodes = [] } + try { sel = ctx.canvas.getSelectedNode() } catch (error) { sel = null } + if (sel && sel.id) { + for (const n of nodes) { + if (n.id === sel.id) return { x: Math.round((Number(n.x) || 0) + GAP_X), y: Math.round(Number(n.y) || 0) } + } + } + if (!nodes.length) return { x: 80, y: 80 } + let best = nodes[0] + let maxX = -Infinity + for (const n of nodes) { + const x = Number(n.x) || 0 + if (x > maxX) { maxX = x; best = n } + } + return { x: Math.round(maxX + GAP_X), y: Math.round(Number(best.y) || 0) } + } + + function useThumb() { + return prefAll().thumbOnly === true + } + + // ---------------- 面板实例 ---------------- + // 每个 mount 容器一个实例:独立 DOM 引用 + 独立 ResizeObserver,数据走 CACHE 共享。 + + function mount(host, ctx) { + const prev = INSTANCES.get(host) + if (prev) { + try { prev.destroy() } catch (error) { /* 忽略 */ } + INSTANCES.delete(host) + } + + ensureStyle() + host.innerHTML = '' + + const ui = { + root: null, search: null, chips: null, grid: null, detail: null, status: null, toastEl: null, + btnRef: null, btnPrompt: null, busy: false, timer: null, seq: 0, + } + const view = { list: [], count: 0 } + + const root = el('div', { class: 'iwb-ss-root' }) + root.setAttribute('data-layout', 'narrow') + + const search = el('input', { + class: 'iwb-ss-search', type: 'search', + placeholder: '搜索风格 / 编号 / 标签', value: CACHE.query, + }) + const refreshBtn = el('button', { + class: 'iwb-ss-btn', text: '刷新', title: '重新拉取风格数据', + onClick: () => { + CACHE.data = null + CACHE.loading = null + CACHE.blobs = {} + ensureData() + }, + }) + const chips = el('div', { class: 'iwb-ss-chips' }) + const grid = el('div', { class: 'iwb-ss-grid' }) + const detail = el('div', { class: 'iwb-ss-detail' }) + const body = el('div', { class: 'iwb-ss-body' }, [grid, detail]) + const status = el('div', { class: 'iwb-ss-status' }) + const toastEl = el('div', { class: 'iwb-ss-toast' }) + + root.appendChild(el('div', { class: 'iwb-ss-tools' }, [search, refreshBtn])) + root.appendChild(chips) + root.appendChild(body) + root.appendChild(status) + root.appendChild(toastEl) + host.appendChild(root) + + ui.root = root + ui.search = search + ui.chips = chips + ui.grid = grid + ui.detail = detail + ui.status = status + ui.toastEl = toastEl + + // ---- 交互反馈 ---- + + function toast(text) { + if (!ui.toastEl) return + ui.toastEl.textContent = text + ui.toastEl.classList.add('is-show') + global.setTimeout(() => { + if (ui.toastEl) ui.toastEl.classList.remove('is-show') + }, 2200) + } + + function busy(on, text) { + ui.busy = Boolean(on) + if (ui.btnRef) { + ui.btnRef.disabled = Boolean(on) + ui.btnRef.textContent = on ? (text || '处理中…') : '插入参考图' + } + if (ui.btnPrompt) ui.btnPrompt.disabled = Boolean(on) + } + + // ---- 插入动作 ---- + + async function insertImage(style) { + const api = ctx.canvas + if (!api || typeof api.createImageNode !== 'function') { toast('当前宿主不支持插入图片(缺 canvasWrite 能力)'); return } + const url = useThumb() ? thumbOf(style) : bigOf(style) + if (!url) { toast('这条风格没有预览图'); return } + try { + busy(true, '正在取图…') + const blob = await loadBlob(url) + const dataUrl = await blobToDataUrl(blob) + // createImageNode 只认 data: URL(宿主 app.js 里 /^data:/i 校验),必须 blob → base64 + const id = api.createImageNode({ + dataUrl: dataUrl, + name: String(style.code || 'style') + '_' + String(style.name || ''), + }) + if (!id) throw new Error('画布拒绝了这张图(data URL 无效)') + toast('已插入参考图') + } catch (error) { + toast('插图失败:' + readErr(error)) + } finally { + busy(false) + } + } + + function insertPrompt(style) { + const api = ctx.canvas + if (!api || typeof api.createNode !== 'function') { toast('当前宿主不支持插入节点(缺 canvasWrite 能力)'); return } + const values = CACHE.vars[style.id] || {} + const text = applyVars(style, values).trim() + if (!text) { toast('这条风格没有提示词'); return } + const spot = nextSpot(ctx) + // createNode 不会自己避让,坐标必须插件算好(createImageNode 内部才走 findSpot 自动排布) + const id = api.createNode('prompt', spot.x, spot.y, { text: text }) + if (!id) { toast('插入失败:prompt 节点类型未注册'); return } + const left = unfilledCount(style, values) + toast(left ? '已插入提示词(还有 ' + left + ' 个变量没填)' : '已插入提示词') + } + + // ---- 渲染 ---- + + function renderChips() { + const all = (CACHE.data && CACHE.data.styles) || [] + const counts = {} + for (const s of all) counts[s.category] = (counts[s.category] || 0) + 1 + const keys = Object.keys(counts).sort((a, b) => counts[b] - counts[a]) + ui.chips.innerHTML = '' + ui.chips.appendChild(el('button', { + class: 'iwb-ss-chip' + (CACHE.cat === 'all' ? ' is-on' : ''), + text: '全部 ' + all.length, + onClick: () => { CACHE.cat = 'all'; prefSet('cat', 'all'); renderAll() }, + })) + for (const key of keys) { + ui.chips.appendChild(el('button', { + class: 'iwb-ss-chip' + (CACHE.cat === key ? ' is-on' : ''), + text: catName(key) + ' ' + counts[key], + title: key, + onClick: () => { CACHE.cat = key; prefSet('cat', key); renderAll() }, + })) + } + } + + function cardNode(style) { + const isSel = CACHE.selId === style.id + const thumb = thumbOf(style) + const media = thumb + ? el('img', { + class: 'iwb-ss-thumb', src: thumb, alt: String(style.name || ''), + loading: 'lazy', decoding: 'async', referrerpolicy: 'no-referrer', + }) + : el('div', { class: 'iwb-ss-nothumb', text: String(style.code || '') }) + return el('div', { + class: 'iwb-ss-card' + (isSel ? ' is-sel' : ''), + title: String(style.name || '') + (style.summary ? '\n' + style.summary : ''), + onClick: () => selectStyle(style.id), + }, [ + media, + el('div', { class: 'iwb-ss-cardmeta' }, [ + el('div', { class: 'iwb-ss-cardname', text: String(style.name || '未命名') }), + el('div', { class: 'iwb-ss-cardcode', text: String(style.code || '') }), + ]), + ]) + } + + function appendCards(from, to) { + const frag = document.createDocumentFragment() + for (let i = from; i < to; i++) frag.appendChild(cardNode(view.list[i])) + ui.grid.appendChild(frag) + view.count = to + } + + function renderGrid() { + ui.grid.innerHTML = '' + view.count = 0 + if (!view.list.length) { + ui.grid.appendChild(el('div', { class: 'iwb-ss-empty', text: '没有匹配的风格,换个关键词或分类试试' })) + return + } + appendCards(0, Math.min(view.list.length, PAGE_SIZE)) + } + + function renderStatus() { + const total = (CACHE.data && CACHE.data.styles.length) || 0 + const shown = view.list.length + const left = Math.max(0, shown - view.count) + ui.status.textContent = '' + ui.status.appendChild(el('span', { + text: (CACHE.query.trim() || CACHE.cat !== 'all') + ? '找到 ' + shown + ' 个 / 共 ' + total + : '共 ' + total + ' 个风格', + })) + ui.status.appendChild(el('span', { text: left > 0 ? '下滑加载更多(还剩 ' + left + ')' : '' })) + } + + function selectStyle(id) { + CACHE.selId = id + CACHE.selOpen = true + prefSet('selId', id) + const cards = ui.grid.querySelectorAll('.iwb-ss-card') + for (let i = 0; i < cards.length; i++) cards[i].classList.remove('is-sel') + const idx = view.list.findIndex((s) => s.id === id) + if (idx >= 0 && idx < view.count && cards[idx]) cards[idx].classList.add('is-sel') + renderDetail() + } + + function renderDetail() { + const style = CACHE.selId ? styleById(CACHE.selId) : null + + if (!style) { + ui.detail.classList.remove('is-open') + ui.detail.innerHTML = '' + ui.detail.appendChild(el('div', { class: 'iwb-ss-empty', text: '从左边点一个风格,这里显示大图、提示词和变量' })) + return + } + + ui.detail.classList.toggle('is-open', CACHE.selOpen) + ui.detail.innerHTML = '' + + const big = bigOf(style) + const values = CACHE.vars[style.id] || (CACHE.vars[style.id] = {}) + const keys = varKeys(style) + + const head = el('div', { class: 'iwb-ss-dhead' }, [ + el('div', { class: 'iwb-ss-dtitle', text: String(style.name || '未命名') }), + el('button', { + class: 'iwb-ss-dclose', text: '✕', title: '关闭详情', + onClick: () => { + CACHE.selOpen = false + ui.detail.classList.remove('is-open') + }, + }), + ]) + + const bodyEl = el('div', { class: 'iwb-ss-dbody' }) + + if (big) { + bodyEl.appendChild(el('img', { + class: 'iwb-ss-big', src: big, alt: String(style.name || ''), + loading: 'lazy', decoding: 'async', referrerpolicy: 'no-referrer', + })) + } + + const tagRow = el('div', { class: 'iwb-ss-tagrow' }) + if (style.code) tagRow.appendChild(el('span', { class: 'iwb-ss-tag', text: String(style.code) })) + if (style.ratio) tagRow.appendChild(el('span', { class: 'iwb-ss-tag', text: String(style.ratio) })) + for (const t of (style.tags || []).slice(0, 8)) tagRow.appendChild(el('span', { class: 'iwb-ss-tag', text: String(t) })) + bodyEl.appendChild(tagRow) + + if (style.summary) bodyEl.appendChild(el('div', { class: 'iwb-ss-summary', text: String(style.summary) })) + + // 变量区:改输入只更新预览文本,不重建 DOM(否则每敲一个字就丢焦点) + const preview = el('div', { class: 'iwb-ss-text' }) + const unfilled = el('span', { class: 'iwb-ss-tag', text: '' }) + const refreshPreview = () => { + preview.textContent = applyVars(style, values) + const left = unfilledCount(style, values) + unfilled.textContent = left ? left + ' 个未填' : '已全部填好' + } + + if (keys.length) { + bodyEl.appendChild(el('div', { class: 'iwb-ss-label' }, [el('span', { text: '变量' }), unfilled])) + const varBox = el('div', {}) + for (const item of keys) { + varBox.appendChild(el('div', { class: 'iwb-ss-var' }, [ + el('span', { class: 'iwb-ss-varlabel', text: item.label, title: item.label + ' → {' + item.name + '}' }), + el('input', { + class: 'iwb-ss-varinput', type: 'text', + placeholder: item.name, value: String(values[item.name] || ''), + onInput: (event) => { values[item.name] = event.target.value; refreshPreview() }, + }), + ])) + } + bodyEl.appendChild(varBox) + } + + bodyEl.appendChild(el('div', { class: 'iwb-ss-label' }, [el('span', { text: '提示词' })])) + bodyEl.appendChild(preview) + refreshPreview() + + bodyEl.appendChild(el('label', { class: 'iwb-ss-check' }, [ + el('input', { + type: 'checkbox', checked: useThumb(), + onChange: (event) => { prefSet('thumbOnly', event.target.checked) }, + }), + el('span', { text: '插图用缩略图(更省画布体积)' }), + ])) + + if (style.source_url) { + bodyEl.appendChild(el('div', { class: 'iwb-ss-label' }, [ + el('span', { text: '来源:' + String(style.source_author || '未知') }), + el('a', { + href: String(style.source_url), target: '_blank', rel: 'noopener noreferrer', + text: '打开原帖', style: 'color: inherit; text-decoration: underline;', + }), + ])) + } + + ui.btnRef = el('button', { + class: 'iwb-ss-btn', text: '插入参考图', + onClick: () => insertImage(style), + }) + ui.btnPrompt = el('button', { + class: 'iwb-ss-btn is-key', text: '插入提示词', + onClick: () => insertPrompt(style), + }) + + ui.detail.appendChild(head) + ui.detail.appendChild(bodyEl) + ui.detail.appendChild(el('div', { class: 'iwb-ss-dfoot' }, [ui.btnRef, ui.btnPrompt])) + } + + function renderAll() { + renderChips() + view.list = filtered() + renderGrid() + renderStatus() + renderDetail() + } + + function renderHint(text, retry) { + ui.grid.innerHTML = '' + ui.grid.appendChild(el('div', { class: 'iwb-ss-empty' }, [ + el('div', { text: text }), + retry ? el('div', { style: 'margin-top:10px;' }, [ + el('button', { class: 'iwb-ss-btn', text: '重试', onClick: retry }), + ]) : null, + ])) + } + + function ensureData() { + if (CACHE.data) { renderAll(); return } + const seq = ++ui.seq + ui.status.textContent = '正在加载风格数据…' + renderHint('正在加载风格数据…') + loadData(ctx) + .then(() => { + if (seq !== ui.seq || !root.isConnected) return + renderAll() + }) + .catch((error) => { + if (seq !== ui.seq || !root.isConnected) return + ui.status.textContent = '加载失败' + renderHint('风格数据加载失败:' + readErr(error), () => { + CACHE.data = null + CACHE.loading = null + ensureData() + }) + }) + } + + // ---- 事件 ---- + + // 搜索防抖 150ms:310 条同步过滤很快,但每键都重排网格会闪 + search.addEventListener('input', () => { + if (ui.timer) global.clearTimeout(ui.timer) + ui.timer = global.setTimeout(() => { + CACHE.query = search.value + view.list = filtered() + renderGrid() + renderStatus() + }, 150) + }) + + // 滚到底自动续渲染 + grid.addEventListener('scroll', () => { + if (ui.busy) return + if (view.count >= view.list.length) return + if (grid.scrollTop + grid.clientHeight < grid.scrollHeight - 240) return + appendCards(view.count, Math.min(view.list.length, view.count + PAGE_SIZE)) + renderStatus() + }) + + // 宽度自适应:拖侧栏/缩放放大窗口时视口不变,@media 不响应,必须观察元素自身 + // 先同步判一次:RO 回调要等下一帧,宽容器否则会先闪一帧窄布局 + const startW = Math.max(host.clientWidth || 0, root.getBoundingClientRect().width || 0) + if (startW) root.setAttribute('data-layout', startW >= WIDE_MIN ? 'wide' : 'narrow') + + let ro = null + if (typeof global.ResizeObserver === 'function') { + ro = new global.ResizeObserver((entries) => { + if (!root.isConnected) return + const width = entries && entries[0] ? entries[0].contentRect.width : 0 + root.setAttribute('data-layout', width >= WIDE_MIN ? 'wide' : 'narrow') + }) + ro.observe(root) + } else { + root.setAttribute('data-layout', 'wide') + } + + const instance = { + destroy() { + if (ro) { try { ro.disconnect() } catch (error) { /* 忽略 */ } ro = null } + if (ui.timer) { global.clearTimeout(ui.timer); ui.timer = null } + ui.seq++ + }, + } + INSTANCES.set(host, instance) + + ensureData() + } + + // ---------------- 注册 ---------------- + + global.IWBPluginHost.register({ + id: 'style-source', + name: '风格库', + version: '1.0.0', + apiVersion: 1, + capabilities: ['panels', 'canvas', 'canvasWrite'], + settings: { + dataUrl: { + type: 'text', + label: '风格数据地址', + desc: 'styles.json 的地址。默认直连 GitHub Pages;国内慢可自行镜像后改这里。', + default: DEFAULT_DATA, + }, + }, + }, function (ctx) { + const prefs = prefAll() + if (prefs.cat && typeof prefs.cat === 'string') CACHE.cat = prefs.cat + if (prefs.selId && typeof prefs.selId === 'string') CACHE.selId = prefs.selId + + ctx.ui.registerPanel({ + id: 'style-panel', + title: '风格库', + icon: 'palette', + mount: (host) => mount(host, ctx), + }) + + return {} + }) +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/style-source/tools/e2e-real.mjs b/style-source/tools/e2e-real.mjs new file mode 100644 index 0000000..bc42cac --- /dev/null +++ b/style-source/tools/e2e-real.mjs @@ -0,0 +1,137 @@ +// 风格库真实网络冒烟(开发用,不进 CI)。 +// +// harness.mjs 用 page.route 把资源和图片都本地化了 —— 好处是离线可复现,坏处是**掩盖了 CORS**。 +// 这个脚本不拦截任何请求,直接打真实 GitHub Pages,验证: +// 1) 线上 styles.json 能拉到 310 条(含真实体积 1.1MB) +// 2) 缩略图真的能在 里解码出来(naturalWidth > 0,说明 CORS + referrerpolicy 没问题) +// 3) 「插入参考图」能把真实 webp 转成 dataURL 交给画布(长度 > 5KB,说明不是空图) +// +// 运行:node style-source/tools/e2e-real.mjs +// 需要外网(走系统代理时给 Chromium 传 proxy 即可;脚本会自动读 HTTP(S)_PROXY) +import { createRequire } from 'node:module' +import { createServer } from 'node:http' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const HERE = path.dirname(fileURLToPath(import.meta.url)) +const REPO = path.resolve(HERE, '../..') +const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web' +const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js') + +let chromium = null +for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) { + try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ } +} +if (!chromium) { + console.error('✗ 找不到 playwright,设置 IWB_PLAYWRIGHT_ROOT 指向含 node_modules 的目录') + process.exit(2) +} + +let failed = 0 +const check = (name, ok, detail) => { + if (!ok) failed++ + console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : '')) +} +const poll = async (fn, timeout = 40000, step = 250) => { + const end = Date.now() + timeout + for (;;) { + const v = await fn() + if (v) return v + if (Date.now() > end) return null + await new Promise((r) => setTimeout(r, step)) + } +} + +const HTML = ` + +
` + +async function main() { + const server = createServer((req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(HTML) }) + await new Promise((r) => server.listen(0, '127.0.0.1', r)) + const port = server.address().port + + const proxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy + const browser = await chromium.launch(proxy ? { proxy: { server: proxy } } : {}) + const page = await browser.newPage({ viewport: { width: 1280, height: 900 } }) + + const netFail = [] + page.on('requestfailed', (req) => { + if (req.url().includes('malongan.github.io')) netFail.push(req.url().slice(-40) + ' ' + (req.failure() || {}).errorText) + }) + const errors = [] + page.on('pageerror', (e) => errors.push(String(e))) + + await page.goto(`http://127.0.0.1:${port}/`) + await page.evaluate(() => { + window.__calls = { panels: [], images: [], nodes: [] } + window.__nodes = [{ id: 'n1', type: 'prompt', x: 100, y: 100, data: { text: 'x' } }] + window.__sel = { id: 'n1', type: 'prompt', name: 'x' } + window.IWBPluginHost = { register(m, s) { window.__m = m; window.__s = s } } + }) + await page.addScriptTag({ path: PLUGIN_ENTRY }) + + await page.evaluate(() => { + const ctx = { + id: window.__m.id, + settings: { get: (k) => (window.__m.settings[k] || {}).default }, + storage: null, + ui: { registerPanel: (p) => window.__calls.panels.push(p) }, + canvas: { + getNodes: () => window.__nodes, + getSelectedNode: () => window.__sel, + createNode: (t, x, y, d) => { window.__calls.nodes.push({ t, x, y, d }); return 'n_new' }, + createImageNode: (p) => { window.__calls.images.push(p); return 'n_img' }, + }, + } + window.__s(ctx) + const host = document.createElement('div') + host.id = 'h' + host.style.cssText = 'width:980px;height:720px;display:flex;min-width:0' + document.getElementById('stage').appendChild(host) + window.__calls.panels[0].mount(host) + }) + + const gotData = await poll(async () => { + const n = await page.locator('#h .iwb-ss-card').count() + return n > 0 ? n : null + }) + check('真实网络拉到数据并渲染卡片', Boolean(gotData), 'cards=' + gotData) + + const status = await page.locator('#h .iwb-ss-status').innerText().catch(() => '') + check('总数显示 310', /310/.test(status), status.replace(/\n/g, ' ')) + + // 真实缩略图必须真的解码出来 + const decoded = await poll(async () => { + const n = await page.evaluate(() => { + const imgs = Array.from(document.querySelectorAll('#h .iwb-ss-thumb')) + return imgs.filter((i) => i.complete && i.naturalWidth > 0).length + }) + return n >= 3 ? n : null + }, 45000) + check('缩略图真实解码成功(≥3 张 naturalWidth>0)', Boolean(decoded), 'decoded=' + decoded) + + // 真实 webp → dataURL + await page.locator('#h .iwb-ss-card').first().click() + await page.waitForTimeout(300) + await page.locator('#h .iwb-ss-dfoot .iwb-ss-btn').first().click() + const img = await poll(() => page.evaluate(() => window.__calls.images[0] || null), 30000) + check('真实图插入画布(createImageNode 被调用)', Boolean(img)) + check('dataURL 是真实内容而非空图', Boolean(img) && String(img.dataUrl).length > 5000, + img ? 'len=' + String(img.dataUrl).length + ' head=' + String(img.dataUrl).slice(0, 22) : '') + + check('无 GitHub 资源请求失败', netFail.length === 0, netFail.slice(0, 2).join(' | ')) + check('无页面 JS 异常', errors.length === 0, errors.slice(0, 2).join(' | ')) + + const shot = path.resolve(HERE, 'shot-real.png') + await page.locator('#h').screenshot({ path: shot }).catch(() => {}) + console.log('· 真实截图:' + shot) + + await browser.close() + server.close() + console.log('') + console.log(failed === 0 ? '全部通过' : failed + ' 项失败') + process.exit(failed === 0 ? 0 : 1) +} + +main().catch((e) => { console.error('崩溃:', e); process.exit(1) }) diff --git a/style-source/tools/harness.mjs b/style-source/tools/harness.mjs new file mode 100644 index 0000000..3d6ce59 --- /dev/null +++ b/style-source/tools/harness.mjs @@ -0,0 +1,372 @@ +// 风格库插件本地端到端(开发用,不进 CI)。 +// +// 为什么需要它:面板布局随宽度变化、变量替换、插图(blob → dataURL → createImageNode)都是浏览器行为,node 侧测不了。 +// 这里装一个合成宿主(可注入的 ctx + 面板容器),addScriptTag 加载插件源码本体,在真实 Chromium 里验证: +// 注册 / 面板注册 / 数据加载 / 分批渲染 / 窄宽两态布局 / ResizeObserver 切档 / 搜索 / 分类 / 变量替换 / 两个插入动作 / 重复 mount 幂等 +// +// 网络完全本地化:page.route 拦截 GitHub Pages,styles.json 读本地文件,预览图返回 1×1 PNG。 +// 所以这里测不到真实 CORS(数据源是 *,已在方案阶段用 curl 实测过)。 +// +// 运行: +// node style-source/tools/harness.mjs +// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定) +import { createRequire } from 'node:module' +import { readFileSync } from 'node:fs' +import { createServer } from 'node:http' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const HERE = path.dirname(fileURLToPath(import.meta.url)) // /style-source/tools +const REPO = path.resolve(HERE, '../..') +const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web' +const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js') +const STYLES_JSON = '/Users/qiqi/open/github/style-source/data/styles.json' + +let chromium = null +for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) { + try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ } +} +if (!chromium) { + console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT:') + console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node style-source/tools/harness.mjs') + process.exit(2) +} + +let failed = 0 +const check = (name, ok, detail) => { + if (!ok) failed++ + console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : '')) +} +const poll = async (fn, timeout = 15000, step = 80) => { + const end = Date.now() + timeout + for (;;) { + const v = await fn() + if (v) return v + if (Date.now() > end) return null + await new Promise((r) => setTimeout(r, step)) + } +} + +const PNG_1PX = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', + 'base64', +) + +const PAGE_HTML = ` + +
` + +async function main() { + const stylesRaw = readFileSync(STYLES_JSON, 'utf8') + const stylesCount = JSON.parse(stylesRaw).styles.length + console.log('· 本地 styles.json:' + stylesCount + ' 条') + + const server = createServer((req, res) => { + if (req.url === '/' || req.url.startsWith('/?')) { + res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }) + res.end(PAGE_HTML) + return + } + res.writeHead(404); res.end('not found') + }) + await new Promise((r) => server.listen(0, '127.0.0.1', r)) + const port = server.address().port + + const browser = await chromium.launch() + const page = await browser.newPage({ viewport: { width: 1280, height: 900 } }) + + let dataHits = 0 + // 拦截上游静态资源:json 用本地文件,图片用 1×1 png(保证离线可复现) + await page.route('https://malongan.github.io/style-source/**', async (route) => { + const url = route.request().url() + const cors = { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD', + 'cache-control': 'no-store', + } + if (url.includes('/data/styles.json')) { + dataHits++ + await route.fulfill({ status: 200, headers: { ...cors, 'content-type': 'application/json' }, body: stylesRaw }) + return + } + await route.fulfill({ status: 200, headers: { ...cors, 'content-type': 'image/png' }, body: PNG_1PX }) + }) + + const errors = [] + page.on('pageerror', (e) => errors.push(String(e))) + + await page.goto(`http://127.0.0.1:${port}/`) + + // ---- 合成宿主 ---- + await page.evaluate(() => { + window.__calls = { nodes: [], images: [], panels: [], manifests: [], setups: 0 } + window.__nodes = [ + { id: 'n_prompt', type: 'prompt', x: 100, y: 120, data: { text: '原有提示词' } }, + { id: 'n_ref', type: 'ref', x: 520, y: 120, data: { name: '参考图' } }, + ] + window.__sel = { id: 'n_prompt', type: 'prompt', name: '原有提示词' } + window.IWBPluginHost = { + register(manifest, setup) { + window.__calls.manifests.push(manifest) + window.__calls.setups++ + window.__manifest = manifest + window.__setup = setup + }, + } + }) + + await page.addScriptTag({ path: PLUGIN_ENTRY }) + + const registered = await page.evaluate(() => Boolean(window.__setup)) + check('插件调用 IWBPluginHost.register', registered) + if (!registered) { await finish(); return } + + const manifest = await page.evaluate(() => { + const m = window.__manifest + return { id: m.id, name: m.name, version: m.version, apiVersion: m.apiVersion, caps: m.capabilities, hasDataUrl: Boolean(m.settings && m.settings.dataUrl) } + }) + check('manifest id/version 正确', manifest.id === 'style-source' && manifest.version === '1.0.0', JSON.stringify({ id: manifest.id, version: manifest.version })) + check('capabilities 含 panels+canvas+canvasWrite', + ['panels', 'canvas', 'canvasWrite'].every((c) => manifest.caps.includes(c)), manifest.caps.join(',')) + check('settings 暴露 dataUrl', manifest.hasDataUrl) + + // ---- 建面板(窄:320) ---- + const mounted = await page.evaluate(() => { + const ctx = { + id: window.__manifest.id, + settings: { get: (k) => (window.__manifest.settings[k] || {}).default }, + storage: null, + ui: { registerPanel: (p) => { window.__calls.panels.push(p) } }, + canvas: { + getNodes: () => window.__nodes, + getSelectedNode: () => window.__sel, + createNode: (type, x, y, data) => { window.__calls.nodes.push({ type, x, y, data }); return 'n_new_' + window.__calls.nodes.length }, + createImageNode: (payload) => { window.__calls.images.push(payload); return 'n_img_' + window.__calls.images.length }, + }, + } + window.__setup(ctx) + const panel = window.__calls.panels[0] + const stage = document.getElementById('stage') + const host = document.createElement('div') + host.id = 'hostA' + host.style.cssText = 'width:320px;height:640px;display:flex;min-width:0' + stage.appendChild(host) + panel.mount(host) + window.__hostA = host + return { panelId: panel && panel.id, title: panel && panel.title, icon: panel && panel.icon } + }) + + check('注册面板「风格库」+ palette 图标', mounted.title === '风格库' && mounted.icon === 'palette', JSON.stringify(mounted)) + + // ---- 数据加载 ---- + const loaded = await poll(async () => { + const txt = await page.locator('.iwb-ss-status').innerText().catch(() => '') + return /共 \d+ 个风格/.test(txt) ? txt : null + }) + check('数据加载完成并显示总数', Boolean(loaded), loaded || '超时') + check('styles.json 只拉了一次', dataHits === 1, 'hits=' + dataHits) + + const cards = await page.locator('#hostA .iwb-ss-card').count() + check('分批渲染首批卡片(' + cards + ' 张,应为 PAGE_SIZE=90)', cards === 90, 'cards=' + cards) + + const chipCount = await page.locator('#hostA .iwb-ss-chip').count() + check('分类 chips = 全部 + 12 类', chipCount === 13, 'chips=' + chipCount) + + // 回归守门:grid-auto-rows 默认 auto 会让图片未加载时的行高塌成一行文字,卡片被裁成横杠 + const geom = await page.evaluate(() => { + const card = document.querySelector('#hostA .iwb-ss-card') + const img = card.querySelector('.iwb-ss-thumb') + const name = card.querySelector('.iwb-ss-cardname') + const h = (e) => Math.round(e.getBoundingClientRect().height) + return { cardH: h(card), imgH: h(img), nameH: h(name), name: name.textContent } + }) + check('卡片高度容纳图片 + 文字(grid-auto-rows 守门)', geom.cardH >= geom.imgH + 20, + 'card=' + geom.cardH + ' img=' + geom.imgH) + check('卡片名称可见', geom.nameH >= 10 && geom.name.length > 0, geom.name + ' / h=' + geom.nameH) + + // ---- 默认窄档 ---- + const layoutNarrow = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout')) + check('320px 初始为 narrow', layoutNarrow === 'narrow', String(layoutNarrow)) + + // ---- 选中第一张卡:窄档详情应为覆盖层 ---- + await page.locator('#hostA .iwb-ss-card').first().click() + await page.waitForTimeout(120) + const narrowDetail = await page.evaluate(() => { + const root = window.__hostA.querySelector('.iwb-ss-root') + const d = root.querySelector('.iwb-ss-detail') + const cs = getComputedStyle(d) + const rb = root.getBoundingClientRect() + const db = d.getBoundingClientRect() + return { open: d.classList.contains('is-open'), position: cs.position, display: cs.display, coverW: Math.round(db.width), rootW: Math.round(rb.width) } + }) + check('窄档选中后详情为覆盖层', narrowDetail.open && narrowDetail.position === 'absolute' && narrowDetail.display === 'flex', + JSON.stringify(narrowDetail)) + check('覆盖层宽度等于面板宽度', Math.abs(narrowDetail.coverW - narrowDetail.rootW) <= 1, narrowDetail.coverW + ' vs ' + narrowDetail.rootW) + + // ---- 变量替换 ---- + const varResult = await page.evaluate(() => { + const inputs = Array.from(window.__hostA.querySelectorAll('.iwb-ss-varinput')) + if (!inputs.length) return { hasVars: false } + const first = inputs[0] + const name = first.getAttribute('placeholder') + first.value = '测试角色ABC' + first.dispatchEvent(new Event('input', { bubbles: true })) + const preview = window.__hostA.querySelector('.iwb-ss-text').textContent + return { hasVars: true, name, preview, replaced: preview.includes('测试角色ABC'), stillHasPlaceholder: preview.includes('{' + name + '}') } + }) + check('详情渲染变量输入框', varResult.hasVars, varResult.name ? '第一个变量:{' + varResult.name + '}' : '') + check('填变量后预览实时替换', Boolean(varResult.replaced)) + check('已填变量不再残留占位符', varResult.hasVars && !varResult.stillHasPlaceholder) + + // ---- 插提示词 ---- + await page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').nth(1).click() + await page.waitForTimeout(120) + const promptCall = await page.evaluate(() => window.__calls.nodes[0] || null) + check('插入提示词调用 createNode', Boolean(promptCall) && promptCall.type === 'prompt', promptCall ? 'type=' + promptCall.type : '未调用') + check('提示词带变量替换结果', Boolean(promptCall) && String(promptCall.data.text).includes('测试角色ABC')) + check('提示词插在选中节点右侧', Boolean(promptCall) && promptCall.x === 480 && promptCall.y === 120, + promptCall ? '(' + promptCall.x + ',' + promptCall.y + ') 期望 (480,120)' : '') + + // ---- 插参考图(blob → dataURL) ---- + await page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').first().click() + const imgCall = await poll(() => page.evaluate(() => window.__calls.images[0] || null), 8000) + check('插入参考图调用 createImageNode', Boolean(imgCall)) + check('传入的是 data: URL(宿主只认这个)', Boolean(imgCall) && /^data:image\//.test(String(imgCall.dataUrl)), imgCall ? String(imgCall.dataUrl).slice(0, 24) + '…' : '') + check('节点名带风格编号', Boolean(imgCall) && /^ST\d+_/.test(String(imgCall.name)), imgCall ? imgCall.name : '') + + // ---- 拉宽到 980:详情应切成右侧栏 ---- + await page.evaluate(() => { window.__hostA.style.width = '980px' }) + const wideLayout = await poll(async () => { + const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout')) + return v === 'wide' ? v : null + }) + check('拉宽到 980 后 data-layout=wide(ResizeObserver 生效)', Boolean(wideLayout)) + + const wideDetail = await page.evaluate(() => { + const root = window.__hostA.querySelector('.iwb-ss-root') + const d = root.querySelector('.iwb-ss-detail') + const cs = getComputedStyle(d) + const rb = root.getBoundingClientRect() + const db = d.getBoundingClientRect() + return { position: cs.position, flexBasis: cs.flexBasis, ratio: db.width / rb.width, cols: getComputedStyle(root.querySelector('.iwb-ss-grid')).gridTemplateColumns.split(' ').length } + }) + check('宽档详情为右侧栏(非 absolute)', wideDetail.position !== 'absolute', wideDetail.position) + check('宽档详情占比约 46%', wideDetail.ratio > 0.3 && wideDetail.ratio < 0.5, wideDetail.ratio.toFixed(2)) + check('宽档网格列数增加', wideDetail.cols >= 4, 'cols=' + wideDetail.cols) + + // ---- 恢复窄档,测边界:479/480 ---- + await page.evaluate(() => { window.__hostA.style.width = '479px' }) + const at479 = await poll(async () => { + const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout')) + return v === 'narrow' ? v : null + }) + await page.evaluate(() => { window.__hostA.style.width = '480px' }) + const at480 = await poll(async () => { + const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout')) + return v === 'wide' ? v : null + }) + check('拐点精确:479=narrow / 480=wide', Boolean(at479) && Boolean(at480)) + + // ---- 搜索 ---- + await page.evaluate(() => { window.__hostA.style.width = '320px' }) + await page.locator('#hostA .iwb-ss-search').fill('Y3K') + await page.waitForTimeout(320) + const searchState = await page.evaluate(() => ({ + status: window.__hostA.querySelector('.iwb-ss-status').firstChild.textContent, + cards: window.__hostA.querySelectorAll('.iwb-ss-card').length, + })) + check('搜索「Y3K」过滤生效', /找到 \d+ 个/.test(searchState.status) && searchState.cards > 0 && searchState.cards < 90, + searchState.status + ' / ' + searchState.cards + ' 张') + + // ---- 分类筛选 ---- + await page.locator('#hostA .iwb-ss-search').fill('') + await page.waitForTimeout(280) + const clickCat = await page.evaluate(() => { + const chips = Array.from(window.__hostA.querySelectorAll('.iwb-ss-chip')) + const target = chips.find((c) => c.textContent.startsWith('电商')) + if (!target) return null + target.click() + return target.textContent + }) + await page.waitForTimeout(160) + const catState = await page.evaluate(() => ({ + on: (window.__hostA.querySelector('.iwb-ss-chip.is-on') || {}).textContent || '', + status: window.__hostA.querySelector('.iwb-ss-status').firstChild.textContent, + })) + check('点分类「电商」后 chips 高亮切换', Boolean(clickCat) && catState.on.startsWith('电商'), clickCat + ' → ' + catState.on) + check('分类筛选改变了结果数', /找到 \d+ 个/.test(catState.status), catState.status) + + // ---- 多容器并存(宿主侧栏 + 放大窗口可能同时渲染同一插件面板) ---- + // 早期版本用单个全局 dom 指针,第二个容器一挂载就把第一个容器的 RO 断掉 —— 这里专门守住这条 + const dual = await page.evaluate(() => { + const stage = document.getElementById('stage') + const hostB = document.createElement('div') + hostB.id = 'hostB' + hostB.style.cssText = 'width:920px;height:600px;display:flex;min-width:0' + stage.appendChild(hostB) + window.__calls.panels[0].mount(hostB) + window.__hostB = hostB + return { + rootsA: window.__hostA.querySelectorAll('.iwb-ss-root').length, + rootsB: hostB.querySelectorAll('.iwb-ss-root').length, + cardsB: hostB.querySelectorAll('.iwb-ss-card').length, + layoutB: hostB.querySelector('.iwb-ss-root').getAttribute('data-layout'), + } + }) + check('两个容器各有且仅有一份根节点', dual.rootsA === 1 && dual.rootsB === 1, JSON.stringify({ a: dual.rootsA, b: dual.rootsB })) + check('第二个容器复用缓存(不重拉就有卡片)', dual.cardsB > 0, 'cards=' + dual.cardsB) + // 首帧同步判定,第二容器应该挂载即 wide(不该先闪一帧 narrow) + check('第二个容器 920px 挂载即判定 wide', dual.layoutB === 'wide', String(dual.layoutB)) + check('styles.json 总计仍只请求过一次', dataHits === 1, 'hits=' + dataHits) + + // hostB 挂载后,hostA 的 ResizeObserver 必须仍然有效(这是被抢指针时最先坏掉的地方) + await page.evaluate(() => { window.__hostA.style.width = '700px' }) + const aStillAlive = await poll(async () => { + const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout')) + return v === 'wide' ? v : null + }) + check('hostB 存在时 hostA 仍响应宽度变化', Boolean(aStillAlive)) + + // ---- 截图留档(先移除 hostB,否则 flex 会把 hostA 压缩、截不到真实宽度) ---- + const shotWide = path.resolve(HERE, 'shot-wide.png') + const shotNarrow = path.resolve(HERE, 'shot-narrow.png') + await page.evaluate(() => { + if (window.__hostB) window.__hostB.remove() + window.__hostA.style.width = '980px' + window.__hostA.style.height = '720px' + }) + const shotLayout = await poll(async () => { + const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout')) + return v === 'wide' ? v : null + }) + check('截图前 hostA 已回到 wide', Boolean(shotLayout)) + await page.waitForTimeout(400) + await page.locator('#hostA').screenshot({ path: shotWide }).catch(() => {}) + await page.evaluate(() => { window.__hostA.style.width = '320px'; window.__hostA.style.height = '640px' }) + await poll(async () => { + const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout')) + return v === 'narrow' ? v : null + }) + await page.waitForTimeout(400) + await page.locator('#hostA').screenshot({ path: shotNarrow }).catch(() => {}) + console.log('· 截图:' + shotWide) + console.log('· 截图:' + shotNarrow) + + check('无页面 JS 异常', errors.length === 0, errors.slice(0, 2).join(' | ')) + + await finish() + + async function finish() { + await browser.close() + server.close() + console.log('') + console.log(failed === 0 ? '全部通过' : failed + ' 项失败') + process.exit(failed === 0 ? 0 : 1) + } +} + +main().catch(async (error) => { + console.error('harness 崩溃:', error) + process.exit(1) +})