Files
image-workbench-desktop/src/storage-workspace.js
T

44 lines
2.4 KiB
JavaScript

;(function (global) {
'use strict'
const result = global.IWBStorageResult
const unwrap = (value) => value && value.ok === true && Object.prototype.hasOwnProperty.call(value, 'value') ? value.value : value
const create = (options) => {
const config = options || {}
const local = config.local
const key = config.key || 'iwb_web_workspaces'
const migrations = config.migrations || global.IWBStorageMigrations
const migrate = (value) => migrations && migrations.migrateWorkspace ? migrations.migrateWorkspace(value) : { ok: true, changed: false, value }
return {
read(fallback) {
try {
const rawResult = local.get(key, fallback)
const raw = unwrap(rawResult)
if (rawResult && rawResult.ok === false) return rawResult
if (raw === undefined || raw === null) return result.ok(fallback)
const migrated = migrate(raw)
if (!migrated.ok) return result.fail(result.error(migrated.code === 'unsupported-schema' ? 'unsupported' : 'validation', migrated.code || 'invalid-workspace', migrated.error || '工作台数据格式无效', false))
if (migrated.changed) local.set(key, migrated.value)
return result.ok(migrated.value, { changed: !!migrated.changed })
} catch (e) { return result.fail(result.from(e, 'unavailable'), { degraded: true }) }
},
write(value) {
try {
const migrated = migrate(value)
if (!migrated.ok) return result.fail(result.error(migrated.code === 'unsupported-schema' ? 'unsupported' : 'validation', migrated.code || 'invalid-workspace', migrated.error || '工作台数据格式无效', false))
const stored = local.set(key, migrated.value)
if (stored && stored.ok === false) return stored
return result.ok(true, { value: migrated.value, changed: !!migrated.changed })
} catch (e) { return result.fail(result.from(e, 'unavailable'), { degraded: true }) }
},
active(fallback) {
const read = this.read(fallback)
if (!read.ok) return read
const value = read.value || {}
const active = (value.workspaces || []).find((item) => item.id === value.activeId) || (value.workspaces || [])[0] || null
return result.ok(active, { root: value })
},
}
}
global.IWBStorageWorkspace = { create }
})(typeof window !== 'undefined' ? window : globalThis)