Files
image-workbench-desktop/scripts/build.js
T
qiqi 9b78535791 feat(gallery): v3.26.61 出图即入图库 + 插入落地本地副本(能标注)
用户报障:① 生图后图库不显示上游传来的图 ② 图库多个入口插入的是链接,画布不能标注。
用户裁定 B6 = 复制:多占空间可以接受,要求不丢数据。

出图即见
- handleCompletedJob 每张完成即 archiveEntryNow(串行队列 + 等缩略图),不再只在整轮结束写一次
- 宿主新增 IWBPluginGallery.emit / onChanged;图库插件订阅后 260ms 防抖重拉
  (此前只有「面板可见且距上次拉取 >5s」一个入口,生成时面板一直可见 ⇒ 永远不刷)

插入能标注
- insertOutputsToCanvas 取源改本地字节优先:原图档 → 清单 data → 缩略图 → 按需抓远程
  (桌面端走 Rust 请求不受 CORS)→ 按档缩尺寸 → {__blob} 引用(字节落 images/canvas/)
- 抓不到才保留原链接,节点 data.srcUrl 留痕 + toast 提示「可能无法标注」;图库拖入同一收口
- getNodeImage 候选补 data.localRef(远程参考图本地缓存字段):此前漏读它 ⇒ 缓存命中过,
  标注插件仍只看到 http 链接并判「远程图片不支持标注」,这是报障②的直接成因

批量插入不再叠图
- 旧实现循环里每张各自 findSpot,而 findSpot 只看已提交节点 ⇒ 同批全落一处;
  改为一次 commit + 4 列栅格铺开

gallery 1.7.0
- 格子「插入」补 insertK(此前忽略插入尺寸档,与右键/顶部不一致)
- 插入补「插入中…」状态;删除改为等宿主删完再重拉(固定 250ms 会拉到未删完的清单)

结构
- 新增 src/gallery-sync.js(约 200 行),app.js 只 attach 装配;新增 tests/gallery-sync-test.js(11 项)
- 行数棘轮 9095 → 9115:+13 行是注入表与 commit 分发(闭包组件内 state),+6 行是纠错注释;
  同时新增一个 src 模块 ⇒ 占比棘轮反而下降。理由已写入棘轮文件

口径纠错(用户要求把旧的不准确描述改掉)
- 图库/缩略图/原图档在桌面端是 images/thumbs、images/gallery 文件,不是 IndexedDB
- 1K 插入档降的是长边像素不是体积(PNG 源仍无损,1024 复杂图 ~500KB~1MB)
- docs/plans/gallery-insert-perf-v324.md 加时效注记(网页版时期口径)
2026-11-24 17:11:01 +08:00

261 lines
10 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
'use strict'
const fs = require('fs')
const path = require('path')
const cp = require('child_process')
const { transformSync } = require('esbuild')
const root = path.resolve(__dirname, '..')
const dist = path.join(root, 'dist')
const run = (cmd) => cp.execFileSync(cmd[0], cmd.slice(1), { cwd: root, encoding: 'utf8' }).trim()
const gitSha = (() => {
try { return run(['git', 'rev-parse', '--short=7', 'HEAD']) } catch (e) { return 'local' }
})()
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
const version = `v${pkg.version}+${gitSha}`
const minifyJs = (code) => transformSync(code, {
loader: 'js',
minify: true,
target: 'es2020',
charset: 'utf8',
legalComments: 'none',
}).code
fs.rmSync(dist, { recursive: true, force: true })
fs.mkdirSync(path.join(dist, 'vendor'), { recursive: true })
// 顺序即加载序(各模块通过 window.IWB* 在运行时互相依赖),切勿排序/改动
const sourceModules = [
'runtime-desktop-bridge.js',
'image-format.js',
'image-admit.js',
'image-dedupe.js',
'clipboard-graph.js',
'clipboard-kind.js',
'clipboard-paste.js',
'clipboard-copy.js',
'clipboard-paste-once.js',
'clipboard-native.js',
'generation-size-policy.js',
'generation-request-shape.js',
'image-preview-derive.js',
'canvas-actions.js',
'canvas-node-factory.js',
'storage-contract.js',
'storage-file.js',
'storage-runtime.js',
'storage-migrations.js',
'storage-result.js',
'storage-local.js',
'runtime-error.js',
'runtime-lifecycle.js',
'runtime-fetch.js',
'runtime-channel.js',
'runtime-boundary.js',
'runtime-record.js',
'runtime-recovery.js',
'runtime-run-context.js',
'runtime-execution-context.js',
'runtime-diagnostic-record.js',
'runtime-metrics.js',
'image-blob-store.js',
'runtime-crash-log.js',
'storage-health.js',
'storage-config-shape.js',
'storage-indexeddb.js',
'storage-workspace.js',
'storage-groups.js',
'storage-outputs.js',
'storage-backup.js',
'storage-zip.js',
'plugin-archive.js',
'plugin-promptlib-backup.js',
'runtime-constants.js',
'canvas-store.js',
'generation-scheduler.js',
'generation-state.js',
'runtime-diagnostics.js',
'gallery-query.js',
'gallery-hydration.js',
'ui-components.js',
'plugin-data.js',
'plugin-api-gallery.js',
'plugin-api-grouplib.js',
'plugin-api-promptlib.js',
'plugin-host.js',
'image-compress.js',
'storage-fallback-indexeddb.js',
'canvas-normalize.js',
'canvas-geometry.js',
'canvas-history.js',
'canvas-ops.js',
'canvas-text.js',
'generation-task-graph.js',
'generation-results-store.js',
'ui-dock-sanitize.js',
'ui-dock.js',
'ui-minimap-fit.js',
'ui-dock-panels.js',
'theme-tokens.js',
'canvas-grid.js',
'image-display-thumb.js',
'image-remote-cache.js',
'gallery-sync.js',
'image-thumb-pick.js',
'ui-modal-drag.js',
'ui-nav-rail.js',
'ui-plugin-page.js',
'ui-hotkey-help.js',
'ui-desktop-shell.js',
'ui-appearance.js',
'runtime-download-auto.js',
'ui-workspace-tabs.js',
'ui-app-chrome.js',
'ui-workbench-hooks.js',
'storage-autobackup.js',
'canvas-history-store.js',
'workspace-sessions-store.js',
'workspace-list.js',
'workspace-purge.js',
'generation-provider-ping.js',
'runtime-plugin-loader.js',
'runtime-plugin-market.js',
'runtime-plugin-backup.js',
'ui-canvas-view.js',
'ui-confirm.js',
'ui-settings-sections.js',
'ui-settings-tab-diag.js',
'ui-settings-modal.js',
'ui-node-card.js',
'ui-node-bodies.js',
'runtime-workbench-logic.js',
'ui-backup-modal.js',
'ui-connect-menu.js',
'ui-gen-config-panel.js',
'canvas-webview.js',
'plugin-files-policy.js',
'image-prompt-cover.js',
]
// 插件自动发现(2026-10-17):src/plugin-*.js 中**未被上面显式登记**的,按文件名排序追加到末尾。
// 契约:插件之间不得依赖彼此的加载顺序(各自只依赖 window.IWBPluginHost 与自身闭包)。
// ⇒ 合入一个插件 = 只往 src/ 放一个 plugin-<id>.js,不需要改本文件、不需要重生成顺序快照。
const explicitModules = new Set(sourceModules)
const discoveredPlugins = fs.readdirSync(path.join(root, 'src'))
.filter((name) => /^plugin-.+\.js$/.test(name) && !explicitModules.has(name))
.sort()
const orderedModules = sourceModules.concat(discoveredPlugins)
// 每个文件独立 minify(绝不 bundle):模块间仅通过 window.IWB* 属性访问耦合,
// 无裸标识符跨文件引用,故逐文件压缩后再做纯文本拼接是安全的。
const minifiedModules = orderedModules.map((file) => {
const code = fs.readFileSync(path.join(root, 'src', file), 'utf8')
return minifyJs(code)
})
// 注入构建版本号(在 minify 之前执行),保持与历史行为一致。
const appSource = fs.readFileSync(path.join(root, 'app.js'), 'utf8')
const appWithBuildMeta = appSource.replace(/const APP_VERSION = '[^']*'/, "const APP_VERSION = '" + version + "'")
if (appWithBuildMeta === appSource) throw new Error('APP_VERSION marker not found in app.js')
const minifiedApp = minifyJs(appWithBuildMeta)
let appBundle = minifiedModules.join('\n;\n') + '\n;\n' + minifiedApp
// 可选外部 sourcemap(默认关闭):IWB_SOURCEMAP=1 时额外产出 dist/app.js.map 并追加引用注释。
const sourcemap = process.env.IWB_SOURCEMAP === '1'
if (sourcemap) {
const mapper = transformSync(appBundle, {
loader: 'js',
minify: false,
target: 'es2020',
charset: 'utf8',
legalComments: 'none',
sourcemap: 'external',
sourcefile: 'app.js',
})
appBundle = mapper.code
fs.writeFileSync(path.join(dist, 'app.js.map'), mapper.map)
appBundle += '\n//# sourceMappingURL=app.js.map\n'
}
// Banner 在 minify 之后前置,避免被压缩器移除。
appBundle = '/*! IWB ' + version + ' */\n' + appBundle
fs.writeFileSync(path.join(dist, 'app.js'), appBundle)
/* 设计 token 必须排在最前:src/design-tokens.css 是生成的静态快照(:root / .theme-dark),
* 组件规则靠它里面的变量。Tauri 的 CSP 不做 @import 兜底,所以这里是**拼接**而不是 @import ——
* 顺序 = design-tokens.css → style.css,改顺序会让静态快照失效(首帧变量全空)。
* 顺带做两件事:① 校验它没和 derive() 漂移(漂了就 build 失败,杜绝发出去的包用旧色板);
* ② 把 DTCG 版 token 写到 dist/tokens.json 供设计工具导入。 */
const { build: buildTokens } = require('./gen-tokens')
const tokensBuilt = buildTokens()
const tokensCssPath = path.join(root, 'src/design-tokens.css')
// Windows 检出可能是 CRLF(core.autocrlf=true):内容一致时不应让构建失败
const tokensCss = fs.readFileSync(tokensCssPath, 'utf8').replace(/\r\n/g, '\n')
if (tokensCss !== tokensBuilt.css) {
console.error('FAIL src/design-tokens.css 与 src/theme-tokens.js 的 derive() 不一致')
console.error(' → 先跑 npm run tokens:write(改了配色公式/种子却没重新生成快照)')
process.exit(1)
}
fs.writeFileSync(path.join(dist, 'tokens.json'), tokensBuilt.json)
const cssSources = ['src/design-tokens.css', 'style.css']
const cssRaw = cssSources.map((f) => fs.readFileSync(path.join(root, f), 'utf8')).join('\n')
const minifiedCss = transformSync(cssRaw, {
loader: 'css',
minify: true,
target: ['chrome100', 'firefox100', 'safari15'],
charset: 'utf8',
}).code
fs.writeFileSync(path.join(dist, 'style.css'), minifiedCss)
fs.copyFileSync(path.join(root, 'favicon.svg'), path.join(dist, 'favicon.svg'))
// PWA(2026-11-07):可安装 —— manifest + 图标(iOS 额外要 apple-touch-icon 的 PNG)
for (const f of ['manifest.webmanifest', 'icon-192.png', 'icon-512.png', 'apple-touch-icon.png']) {
fs.copyFileSync(path.join(root, f), path.join(dist, f))
}
// 第三方许可随部署产物一起分发(MIT 要求随软件保留版权与许可声明)
fs.copyFileSync(path.join(root, 'THIRD_PARTY_NOTICES.md'), path.join(dist, 'THIRD_PARTY_NOTICES.md'))
fs.copyFileSync(path.join(root, 'vendor/react.production.min.js'), path.join(dist, 'vendor/react.production.min.js'))
fs.copyFileSync(path.join(root, 'vendor/react-dom.production.min.js'), path.join(dist, 'vendor/react-dom.production.min.js'))
// Service Worker:注入版本号(使每次发版 sw.js 内容变化,从而触发浏览器检测到新版本)+ 拷入 dist
const swSource = fs.readFileSync(path.join(root, 'sw.js'), 'utf8')
const swWithVersion = swSource.replace(/__IWB_VERSION__/, version)
if (swWithVersion === swSource) throw new Error('__IWB_VERSION__ marker not found in sw.js')
fs.writeFileSync(path.join(dist, 'sw.js'), swWithVersion)
const html = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>无限画布</title>
<link rel="icon" type="image/svg+xml" href="favicon.svg">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="manifest.webmanifest">
<meta name="theme-color" content="#2563eb">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="无限画布">
<link rel="stylesheet" href="style.css?v=${version}">
</head>
<body>
<div id="root"></div>
<script src="vendor/react.production.min.js"></script>
<script src="vendor/react-dom.production.min.js"></script>
<script src="app.js?v=${version}"></script>
</body>
</html>
`
fs.writeFileSync(path.join(dist, 'index.html'), html)
fs.writeFileSync(path.join(dist, 'version.json'), JSON.stringify({ version, packageVersion: pkg.version, commit: gitSha }, null, 2) + '\n')
// 导航 logo 用真实应用图标(v3.25.61;缺失不阻塞构建)
try { fs.copyFileSync(path.join(root, 'src-tauri', 'icons', 'icon.png'), path.join(dist, 'nav-logo.png')) } catch (e) { /* ignore */ }
const appBytes = fs.statSync(path.join(dist, 'app.js')).size
const cssBytes = fs.statSync(path.join(dist, 'style.css')).size
console.log(`Built ${version} -> dist/`)
console.log(` app.js ${appBytes} bytes`)
console.log(` style.css ${cssBytes} bytes`)
console.log(` plugins ${discoveredPlugins.length ? discoveredPlugins.join(', ') : '(none)'}`)