feat(storage): 资料目录落盘(data.json + images/ 内容寻址)+ IndexedDB 图片一次性迁移

This commit is contained in:
qiqi committed 2026-11-16 22:02:55 +08:00
1 parent eadd5f3d65
commit 135589cd6f
9 files changed
+345 -6

No files matched your search

+2
View File
@@ -39,6 +39,8 @@
| P16 | `app.js` | 自动保存生成的图片 | 桌面端没有 File System Access API ⇒ 改为写入默认下载文件夹(plugin-http 取字节) |
| P17 | `app.js` + 设置面板 | 保存链路 | 「批量保存不再逐个弹框」(互斥:会话内授权失效时自动回退对话框) |
| P18 | 设置面板各页 | 文案 | 去掉浏览器语义(localStorage 5MB / CORS / KV / 标签页 / 刷新),桌面端显示对应真实含义 |
| P19 | 新增 `src/storage-file.js` | 存储底座 | 资料目录:data.json(全部 localStorage 键)+ images/<sha16>.<ext>(图片字节);启动装载 → 内存 → 异步原子落盘;IndexedDB 旧图片一次性迁移 |
| P20 | `src-tauri/src/lib.rs` | 命令 | `grant_dir`:把资料目录加进本次运行的 fs scope(fs 授权是会话级,重启由此补授权) |
新增的配套文件(都不碰业务逻辑):
+16 -3
View File
@@ -2,8 +2,15 @@
* 依赖: vendor/react + vendor/react-dom(离线 UMD)
* 后端 API: /api/config /api/generate /api/graph /api/prompts /api/outputs
*/
(function () {
(async function () {
'use strict'
// 桌面端:启动时先把「资料目录」读进内存(异步),之后所有同步存储调用都走内存 + 异步落盘。
// 网页版没有 IWBStorageFile ⇒ 这段整体跳过,行为与原来完全一致。
try {
if (typeof window !== 'undefined' && window.IWBStorageFile && window.IWBStorageFile.enabled()) {
await window.IWBStorageFile.ready()
}
} catch (e) { console.error('[iwb][file-store] 启动装载失败,回退浏览器存储', e) }
const el = React.createElement
const { useState, useEffect, useLayoutEffect, useRef } = React
// 生成结果精简/合并模块(src/generation-results-store.js)。⚠️ 必须在 IIFE 最顶部取:
@@ -118,7 +125,13 @@
// ========== 浏览器本地模式(Cloudflare Pages 免费版)==========
// 数据层:localStorage + IndexedDB;网络层:直连兼容 API(CORS 已验证允许)
function storageRuntime() { return typeof window !== 'undefined' && window.IWBStorageRuntime }
function storageRuntime() {
if (typeof window === 'undefined') return false
// 桌面端:资料目录就绪后一律走文件底座(内存表 + 异步落盘);否则用原来的 localStorage 实现
const fileStore = window.IWBStorageFile
if (fileStore && fileStore.enabled && fileStore.enabled()) return fileStore.runtime
return window.IWBStorageRuntime
}
function lsGet(k, fb) {
const runtime = storageRuntime()
if (runtime) return runtime.get(k, fb)
@@ -183,7 +196,7 @@
// 统一的本地存储适配器:业务层不直接依赖 JSON 序列化细节。
const SchemaVersions = Object.assign({ workspace: 1, canvas: 1, backup: 2, groups: 1 }, StorageContract.schema || {})
const ModularLocalStore = typeof window !== 'undefined' && window.IWBStorageLocal && typeof window.IWBStorageLocal.create === 'function'
? window.IWBStorageLocal.create({ storage: window.localStorage })
? window.IWBStorageLocal.create({ storage: (typeof window !== 'undefined' && window.IWBStorageFile && window.IWBStorageFile.enabled()) ? window.IWBStorageFile.storage() : window.localStorage })
: null
const unwrapStorageResult = (value, fallback) => value && value.ok === false ? fallback : (value && value.ok === true && Object.prototype.hasOwnProperty.call(value, 'value') ? value.value : value)
const LocalStore = {
+1
View File
@@ -42,6 +42,7 @@ const sourceModules = [
'canvas-actions.js',
'canvas-node-factory.js',
'storage-contract.js',
'storage-file.js',
'storage-runtime.js',
'storage-migrations.js',
'storage-result.js',
+10 -1
View File
@@ -1,14 +1,23 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "主窗口最小能力集:原生另存为 + 写文件 + 白名单取图",
"description": "主窗口最小能力集:资料目录读写(路径运行时授权)+ 原生另存为 + 白名单取图",
"windows": [
"main"
],
"permissions": [
"fs:allow-write-text-file",
"fs:allow-read-text-file",
"core:default",
"dialog:default",
"fs:allow-read-file",
"fs:allow-write-file",
"fs:allow-read-dir",
"fs:allow-mkdir",
"fs:allow-remove",
"fs:allow-rename",
"fs:allow-stat",
"fs:allow-exists",
{
"identifier": "http:default",
"allow": [
+18 -1
View File
@@ -2,6 +2,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use tauri::menu::{Menu, MenuItem};
use tauri::tray::TrayIconBuilder;
use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, WebviewWindow, WindowEvent};
use tauri_plugin_fs::FsExt; // 提供 fs_scope():运行时给「资料目录」授权
// 「是否正在真正退出」:托盘菜单的「退出」或 Cmd+Q 才会置位,
// 其余情况点窗口关闭按钮只是收进托盘,进程继续跑(后台生图不中断)。
@@ -124,6 +125,22 @@ fn build_tray(app: &AppHandle) -> tauri::Result<()> {
Ok(())
}
// 把「资料目录」加进本次运行的 fs scope。
// 为什么需要它:tauri-plugin-fs 的路径白名单是**运行时**的,重启就没了;而资料目录是用户
// 在设置里选的、存在应用配置里 ⇒ 启动时由这里重新授权一次,之后 fs 插件的读写才允许。
#[tauri::command]
fn grant_dir(app: AppHandle, dir: String) -> Result<String, String> {
let p = std::path::PathBuf::from(&dir);
if !p.is_absolute() {
return Err("资料目录必须是绝对路径".into());
}
std::fs::create_dir_all(&p).map_err(|e| e.to_string())?;
app.fs_scope()
.allow_directory(&p, true)
.map_err(|e| e.to_string())?;
Ok(p.to_string_lossy().to_string())
}
// 打开应用数据目录(设置里的「打开数据目录」按钮用;macOS 访达 / Windows 资源管理器 / Linux xdg-open)
#[tauri::command]
fn open_app_data_dir(app: AppHandle) -> Result<String, String> {
@@ -149,7 +166,7 @@ pub fn run() {
.plugin(tauri_plugin_http::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_dialog::init())
.invoke_handler(tauri::generate_handler![open_app_data_dir])
.invoke_handler(tauri::generate_handler![open_app_data_dir, grant_dir])
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
+1 -1
View File
@@ -42,4 +42,4 @@
"icons/icon.ico"
]
}
}
}
+295
View File
@@ -0,0 +1,295 @@
/* storage-file.js —— 桌面端「资料目录」存储底座(2026-11-16)
*
* 目标:数据不再只躺在 WebView 私有存储里,而是落在一个你指定的普通目录:
* <资料目录>/data.json 所有 localStorage 键(设置/提示词/画布/图库索引…)
* <资料目录>/images/<hash>.<ext> 所有图片字节(按内容哈希去重,真实二进制,无 base64)
*
* 实现要点(为什么能不加异步改造就跑起来):
* localStorage 是同步 API,文件 IO 是异步的 ⇒ 启动时一次性把 data.json 读进内存,
* 之后读写都是同步的内存操作,写盘走 debounce(800ms)异步刷盘;关窗前 flush 一次。
*
* 只在 Tauri 里启用;网页版 enabled() 恒为 false,调用方原样走浏览器存储。
*/
;(function (global) {
'use strict'
const PTR_KEY = 'iwb.dataDir' // 资料目录指针:必须住在 WebView 存储里(否则找不到 data.json)
const DATA_FILE = 'data.json'
const IMG_DIR = 'images'
const SCHEMA = 1
let tauri = null
let dir = ''
let mem = {} // key -> 原始字符串(与 localStorage 一一对应)
let assets = {} // key -> { f: 'images/xxx.png', k: 'blob' | 'dataurl' }
let small = {} // 小文本 KV(日志等):key -> 字符串
let loaded = false
let timer = null
let writing = null
// 惰性取 __TAURI__:模块加载时它未必已注入,但每个调用点都要能拿到
const tk = () => { if (!tauri) { try { tauri = global.__TAURI__ || null } catch (e) { tauri = null } } return tauri }
const fs = () => { const T = tk(); return (T && T.fs) || null }
const path = () => { const T = tk(); return (T && T.path) || null }
const core = () => { const T = tk(); return (T && T.core) || null }
const enabled = () => { const T = tk(); return !!(T && T.core && T.fs && T.path) }
const join = async (...p) => {
const P = path()
if (!P || !P.join) return p.join('/')
return await P.join.apply(null, p.map(String))
}
const bytes = () => {
let n = 0
try { for (const k of Object.keys(mem)) n += (k.length + String(mem[k] || '').length) * 2 } catch (e) { /* ignore */ }
return n
}
const schedule = () => {
if (!enabled()) return
if (timer) clearTimeout(timer)
timer = setTimeout(() => { timer = null; flush().catch(() => {}) }, 800)
}
const snapshot = () => JSON.stringify({ v: SCHEMA, at: Date.now(), keys: mem, assets, small })
// 原子写:先写 .tmp 再 rename,避免断电/崩溃留下半个 JSON
const flush = async () => {
if (!enabled() || !dir) return Promise.resolve(false)
if (writing) return writing
const body = snapshot()
const target = await join(dir, DATA_FILE)
writing = (async () => {
try {
const tmp = await join(dir, DATA_FILE + '.tmp')
await fs().writeTextFile(tmp, body)
await fs().rename(tmp, target)
return true
} catch (e) {
try { await fs().writeTextFile(target, body) } catch (e2) { /* ignore */ }
return false
} finally { writing = null }
})()
return writing
}
// 图片:内容哈希(SHA-256 前 16 位)→ images/<hash>.<ext>,同图只存一份
const extOf = (mime) => {
const m = String(mime || '').toLowerCase()
if (m.indexOf('jpeg') >= 0 || m.indexOf('jpg') >= 0) return 'jpg'
if (m.indexOf('webp') >= 0) return 'webp'
if (m.indexOf('gif') >= 0) return 'gif'
if (m.indexOf('svg') >= 0) return 'svg'
if (m.indexOf('avif') >= 0) return 'avif'
return 'png'
}
const sha16 = async (buf) => {
try {
const d = await global.crypto.subtle.digest('SHA-256', buf)
return Array.from(new Uint8Array(d)).slice(0, 8).map((b) => b.toString(16).padStart(2, '0')).join('')
} catch (e) {
let h = 2166136261
const u = new Uint8Array(buf)
for (let i = 0; i < u.length; i++) { h ^= u[i]; h = Math.imul(h, 16777619) >>> 0 }
return 'f' + (h >>> 0).toString(16)
}
}
const dataUrlToBytes = (s) => {
const m = /^data:([^;,]+)?(;base64)?,/i.exec(String(s || ''))
if (!m) return null
const bin = global.atob(String(s).slice(m[0].length))
const u = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i)
return { mime: m[1] || 'image/png', bytes: u }
}
const bytesToDataUrl = (mime, u8) => {
let bin = ''
const CH = 0x8000
for (let i = 0; i < u8.length; i += CH) bin += String.fromCharCode.apply(null, u8.subarray(i, i + CH))
return 'data:' + (mime || 'image/png') + ';base64,' + global.btoa(bin)
}
// ── 对外:legacy IndexedDB 同形接口(app.js 的 IDB 就是拿这个)──
const kv = {
async put(key, value) {
try {
if (!enabled() || !dir) return false
if (value && typeof value === 'object' && typeof value.size === 'number' && value.type !== undefined) {
// Blob:直接取二进制落盘
const buf = await value.arrayBuffer()
const hash = await sha16(buf)
const rel = IMG_DIR + '/' + hash + '.' + extOf(value.type)
const abs = await join(dir, rel)
await fs().writeFile(abs, new Uint8Array(buf))
assets[String(key)] = { f: rel, k: 'blob', m: value.type || 'application/octet-stream' }
schedule()
return true
}
const s = String(value)
if (s.indexOf('data:') === 0) {
const dec = dataUrlToBytes(s)
if (dec) {
const hash = await sha16(dec.bytes)
const rel = IMG_DIR + '/' + hash + '.' + extOf(dec.mime)
const abs = await join(dir, rel)
await fs().writeFile(abs, dec.bytes)
assets[String(key)] = { f: rel, k: 'dataurl', m: dec.mime }
schedule()
return true
}
}
small[String(key)] = s
schedule()
return true
} catch (e) {
try { global.IWBMetricsSwallow && global.IWBMetricsSwallow('file-kv-put', e) } catch (e2) { /* ignore */ }
return false
}
},
async get(key) {
try {
const a = assets[String(key)]
if (a) {
const abs = await join(dir, a.f)
const u8 = await fs().readFile(abs)
if (a.k === 'dataurl') return bytesToDataUrl(a.m, u8)
return new Blob([u8], { type: a.m || 'application/octet-stream' })
}
return Object.prototype.hasOwnProperty.call(small, String(key)) ? small[String(key)] : null
} catch (e) { return null }
},
async getBlob(key) {
try {
const a = assets[String(key)]
if (!a) return null
const abs = await join(dir, a.f)
const u8 = await fs().readFile(abs)
return new Blob([u8], { type: a.m || 'application/octet-stream' })
} catch (e) { return null }
},
async del(key) {
try {
const k = String(key)
const had = !!assets[k] || Object.prototype.hasOwnProperty.call(small, k)
delete assets[k]; delete small[k]
schedule()
return had
} catch (e) { return false }
},
async keys() { try { return Object.keys(assets).concat(Object.keys(small)) } catch (e) { return [] } },
async logPut(id, entry) { return kv.put('log:' + id, JSON.stringify(entry)) },
async logAll() {
const out = []
for (const k of Object.keys(small)) if (k.indexOf('log:') === 0) { try { out.push(JSON.parse(small[k])) } catch (e) { /* ignore */ } }
return out
},
async kvGet(key) { return kv.get(key) },
async kvPut(key, value) { return kv.put(key, typeof value === 'string' ? value : JSON.stringify(value)) },
}
// ── 对外:localStorage 同形的内存表(供 IWBStorageLocal / lsGet 使用)──
const storage = {
getItem(k) { return Object.prototype.hasOwnProperty.call(mem, String(k)) ? mem[String(k)] : null },
setItem(k, v) { mem[String(k)] = String(v); schedule() },
removeItem(k) { delete mem[String(k)]; schedule() },
clear() { mem = {}; schedule() },
key(i) { return Object.keys(mem)[i] || null },
get length() { return Object.keys(mem).length },
}
const runtime = {
get(key, fallback) { try { const v = storage.getItem(key); return v === null ? fallback : JSON.parse(v) } catch (e) { return fallback } },
set(key, value) { try { storage.setItem(key, JSON.stringify(value)); return true } catch (e) { return false } },
remove(key) { try { storage.removeItem(key); return true } catch (e) { return false } },
rawGet(key, fallback) { const v = storage.getItem(key); return v === null ? fallback : v },
rawSet(key, value) { try { storage.setItem(key, String(value)); return true } catch (e) { return false } },
bytes,
indexedDb: kv,
}
async function loadInto() {
// data.json 不存在 ⇒ 把当前 WebView 里的数据迁过去(只做一次)
const target = await join(dir, DATA_FILE)
let parsed = null
try { const txt = await fs().readTextFile(target); parsed = JSON.parse(txt) } catch (e) { parsed = null }
if (parsed && parsed.keys) {
mem = parsed.keys || {}
assets = parsed.assets || {}
small = parsed.small || {}
return 'loaded'
}
mem = {}
try {
for (let i = 0; i < global.localStorage.length; i++) {
const k = global.localStorage.key(i)
if (k) mem[k] = global.localStorage.getItem(k)
}
} catch (e) { /* ignore */ }
return 'migrated'
}
// 一次性迁移:把老版本存在 IndexedDB 里的图片字节搬到 images/ 下(跑过一次就写标记文件)
const blog = async (m) => { try { await fs().writeTextFile(await join(dir, '_boot.log'), new Date().toISOString() + ' ' + m + '\n', { append: true }) } catch (e) { /* ignore */ } }
async function migrateBlobs() {
try {
await blog('migrate:start dir=' + dir)
// 注意:Tauri fs 默认禁dotfile(.xxx),标记文件用普通名字
const marker = await join(dir, 'migrated.flag')
const has = await fs().exists(marker)
await blog('migrate:marker exists=' + has)
if (has) return 0
const C = global.IWBStorageContract || {}
const store = (global.IWBStorageIndexedDB && global.IWBStorageIndexedDB.create)
? global.IWBStorageIndexedDB.create({ contract: C.indexedDb })
: null
await blog('migrate:store=' + !!store + ' imagesAll=' + !!(store && store.imagesAll))
if (!store || typeof store.imagesAll !== 'function') { await fs().writeTextFile(marker, 'no-idb'); return 0 }
const r = await store.imagesAll()
await blog('migrate:result ok=' + (r && r.ok) + ' n=' + (r && r.value && r.value.length))
const list = (r && r.ok && Array.isArray(r.value)) ? r.value : []
let n = 0
for (const it of list) {
if (!it || it.key === undefined) continue
try { if (await kv.put(it.key, it.value)) n++ } catch (e) { /* 单条失败不影响其它 */ }
}
await flush()
await fs().writeTextFile(marker, String(n))
await blog('migrate:done n=' + n)
return n
} catch (e) { await blog('migrate:ERR ' + (e && (e.message || e))); return 0 }
}
async function init(opts) {
const o = opts || {}
tauri = global.__TAURI__ || null
if (!enabled()) return false
if (loaded) return true
let want = o.dir || ''
try { want = want || global.localStorage.getItem(PTR_KEY) || '' } catch (e) { /* ignore */ }
if (!want) {
// 默认目录:~/Documents/ImageWorkbench
try { const doc = await path().documentDir(); want = await join(doc, 'ImageWorkbench') } catch (e) { want = '' }
}
if (!want) return false
// 授权(fs scope 是运行时授权,重启后由这里补一次)
try { await core().invoke('grant_dir', { dir: want }) } catch (e) { console.error('[iwb][file-store] 授权失败', e); return false }
dir = want
try { global.localStorage.setItem(PTR_KEY, dir) } catch (e) { /* ignore */ }
try { await fs().mkdir(await join(dir, IMG_DIR), { recursive: true }) } catch (e) { /* 已存在 */ }
await loadInto()
loaded = true
// 首次迁移要立刻落盘,别等 debounce
await flush()
// 老版本图片在 IndexedDB 里 ⇒ 搬到 images/(带标记,只跑一次)
try { await migrateBlobs() } catch (e) { /* 迁移失败不阻塞启动 */ }
return true
}
global.IWBStorageFile = {
enabled, ready: init, flush, runtime,
storage: () => storage,
kv: () => kv,
dir: () => dir,
setDir: async (next) => { dir = String(next || ''); await flush();},
stats: () => ({ dir, keys: Object.keys(mem).length, images: Object.keys(assets).length }),
__internals: { snapshot, loadInto, sha16, extOf, dataUrlToBytes, bytesToDataUrl },
}
// 关窗/收托盘前强制刷盘(beforeunload 在桌面端不保证,但能救一次是一次)
try { global.addEventListener('beforeunload', () => { try { flush() } catch (e) { /* ignore */ } }) } catch (e) { /* ignore */ }
})(typeof window !== 'undefined' ? window : globalThis)
+1
View File
@@ -43,6 +43,7 @@
"IWBStorageConfigShape",
"IWBStorageContract",
"IWBStorageFallbackIndexeddb",
"IWBStorageFile",
"IWBStorageGroups",
"IWBStorageHealth",
"IWBStorageIndexedDB",
+1
View File
@@ -14,6 +14,7 @@
"canvas-actions.js",
"canvas-node-factory.js",
"storage-contract.js",
"storage-file.js",
"storage-runtime.js",
"storage-migrations.js",
"storage-result.js",