Files
image-workbench-desktop/src/ui-dock.js
T
qiqi 9df38163ea fix(canvas): 复制落点扣除停靠栏;暗色自定义底色改近黑文字
缺陷 1(复制落点):Ctrl+D 复制节点时 copyOffset 用整窗画布尺寸算可放范围,
未扣停靠栏 ⇒ 允许把副本放到屏幕左侧。实测原节点 x=398,副本落在 x=78(整块被 318px 左栏盖住)。
- copyOffset 的 bounds 改用 canvasSafeInsets(与 doFit 同口径)
- findSpot 的浮层禁区补 .iwb-dock(新建/粘贴节点同一类问题)

缺陷 2(暗色可读性):暗色主题的节点文字已是浅色 #e3e3e3,但自定义底色的暗色令牌仍是
中灰(yellow #c7bf9a)⇒ 实测对比度 1.4(要求 ≥7),文字几乎不可读。
- 新增 .theme-dark .iwb-node[data-bg] { --iwb-node-text: #1d1d1f }(实测对比度 ≈9.4)
- 修正 style.css 里「暗色=中灰底+近黑字」的过时注释

顺带加固(同一类:启动时停靠栏还没挂载):
- ui-dock 写入 --iwb-dock-l/-r 后广播 iwb:dock-insets
- Workbench 监听:仅当视口仍是「自动适应」的产物(用户没缩放/平移过)才按新占位重新适应
  ⇒ 修掉「首帧算错后不纠正」,且不会覆盖用户早期的缩放操作

棘轮:app.js 8315→8326、Workbench 2169→2180(+11,见 commit 说明);文档数字已 sync。
验证:verify:ci 全绿;视觉基线 24/24 无 diff。
2026-11-27 00:29:35 +08:00

408 lines
19 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.
/* 左右停靠栏(v3.25.35)
*
* 结构(对齐 Obsidian):
* [左栏] 头部:开关图标 + 各面板图标(横排,可点击切换 / 拖动排序 / 拖到另一栏)
* 主体:当前面板
* 右缘:拖宽手柄
* [右栏] 头部:各面板图标(横排)+ 开关图标(最右)
* 主体:当前面板
* 左缘:拖宽手柄
* 折叠后:窗口边缘保留 14px 窄条(上面的开关图标 = 展开入口)
*
* 约束(用户裁定):
* - 画布不动;只有工具栏/小地图按 --iwb-dock-l / --iwb-dock-r 让位(CSS 负责)
* - 宽度自由拖动、无上限;最小 100px
* - 每栏至少保留一个面板(拖走最后一个 → 阻止并提示)
* - 状态(开合/宽度/面板顺序/当前面板)持久化到 localStorage
*/
;(function (global) {
'use strict'
const React = global.React
const el = React.createElement
const useState = React.useState
const useEffect = React.useEffect
const useLayoutEffect = React.useLayoutEffect || React.useEffect
const useRef = React.useRef
const MIN_W = 100
const STRIP_W = 14
const DEFAULT_KEY = 'iwb.dock.v1'
// 存储统一走 IWBStorageLocal 门面(src 内不得直调 localStorage)
const _store = () => (global.IWBStorageLocal && typeof global.IWBStorageLocal.getStore === 'function') ? global.IWBStorageLocal.getStore() : null
function normalizeSide (side, def) {
const s = side && typeof side === 'object' ? side : {}
const list = Array.isArray(s.list) && s.list.length ? s.list.map(String) : def.list.slice()
const removedIds = Array.isArray(s.removed) ? s.removed.map(String) : []
const active = list.indexOf(String(s.active || '')) >= 0 ? String(s.active) : (list.indexOf(def.active) >= 0 ? def.active : list[0])
return {
open: s.open === undefined ? def.open !== false : !!s.open,
w: Math.max(MIN_W, Number(s.w) || def.w || 300),
list,
removed: removedIds,
active,
}
}
function loadState (key, defaults) {
const def = {
left: normalizeSide(defaults && defaults.left, { open: true, w: 318, list: [], active: '' }),
right: normalizeSide(defaults && defaults.right, { open: true, w: 330, list: [], active: '' }),
}
try {
const st = _store()
const raw = st ? st.rawGet(key, null) : null
if (!raw) return def
const v = JSON.parse(raw)
return { left: normalizeSide(v && v.left, def.left), right: normalizeSide(v && v.right, def.right) }
} catch (e) {
return def
}
}
function saveState (key, s) {
try { const st = _store(); if (st) st.rawSet(key, JSON.stringify(s)) } catch (e) { /* ignore */ }
}
// 插件面板宿主:只在激活时挂载(切走即卸载)。挂载失败不影响其它面板。
// v3.25.51:挂载失败可回退(gallery 这类核心面板装插件后仍要有保底)
function PluginBox (props) {
const ref = useRef(null)
const [failed, setFailed] = useState(false)
const mount = props.mount
useEffect(() => {
const node = ref.current
if (!node || typeof mount !== 'function') { setFailed(true); return undefined }
try { mount(node); setFailed(false) } catch (e) { setFailed(true) }
return undefined
}, [mount])
if (failed && props.fallback) return props.fallback
return el('div', { className: 'iwb-dock-plugin', ref })
}
function IWBDockArea (props) {
const panels = props.panels || {}
const renderIcon = props.renderIcon || function () { return null }
const key = props.storageKey || DEFAULT_KEY
const defaults = props.defaults || { left: { open: true, w: 318, list: [], active: '' }, right: { open: true, w: 330, list: [], active: '' } }
const [dock, setDock] = useState(function () { return loadState(key, defaults) })
const [dropInfo, setDropInfo] = useState(null) // { side, index }
const [ghost, setGhost] = useState(null) // { id, x, y }
const dragRef = useRef(null)
const dropRef = useRef(null)
const rootRef = useRef(null)
// 顶部栏/Esc 控制右栏开合;外部 tab 变化时同步右栏激活面板
useEffect(function () {
if (props.rightOpen === undefined) return
setDock(function (d) { return d.right.open === !!props.rightOpen ? d : { left: d.left, right: Object.assign({}, d.right, { open: !!props.rightOpen }) } })
}, [props.rightOpen])
useEffect(function () {
if (!props.rightActive) return
setDock(function (d) { return d.right.active === props.rightActive ? d : { left: d.left, right: Object.assign({}, d.right, { active: props.rightActive }) } })
}, [props.rightActive])
// 面板注册可能是异步的(插件稍后注册):订阅插件宿主,注册后重渲染
const PluginHost = props.PluginHost
const [rev, setRev] = useState(0)
useEffect(function () {
if (!PluginHost || typeof PluginHost.on !== 'function') return undefined
return PluginHost.on(function () { setRev(function (v) { return v + 1 }) })
}, [PluginHost])
// 面板可用性兜底:插件是异步注册的,先给 1.2s 窗口;仍不可用才切到本栏第一个可用面板
useEffect(function () {
const ok = function (id) {
const p = panels[id]
if (!p) return false
if (p.node) return true
return !!(p.pluginId && props.pluginMount && props.pluginMount(p.pluginId))
}
const t = setTimeout(function () {
setDock(function (d) {
let changed = false
const next = { left: Object.assign({}, d.left), right: Object.assign({}, d.right) }
;['left', 'right'].forEach(function (side) {
const s = next[side]
if (!ok(s.active)) {
const first = s.list.find(ok)
if (first) { s.active = first; changed = true }
}
})
// v3.26.12:同一面板同时出现在左右两侧 → 只保留左侧(老数据重复注册的残留)
const dup = next.left.list.filter(function (id) { return next.right.list.indexOf(id) >= 0 })
if (dup.length) {
next.right = Object.assign({}, next.right, { list: next.right.list.filter(function (id) { return dup.indexOf(id) < 0 }) })
if (dup.indexOf(next.right.active) >= 0) next.right.active = next.right.list[0] || ''
changed = true
}
return changed ? next : d
})
}, 1200)
return function () { clearTimeout(t) }
}, [rev, panels])
useEffect(function () {
// v3.26.22:插件面板还没注册时不要写盘 —— 否则会把用户的面板摆放覆盖成空/默认
if (!Object.keys(panels || {}).length) return undefined
// 拖宽时每帧都会变:节流写盘,避免 localStorage 同步写造成卡顿
const t = setTimeout(function () { saveState(key, dock) }, 180)
return function () { clearTimeout(t) }
}, [dock, panels])
// v3.26.21:整理逻辑抽到 src/ui-dock-sanitize.js(纯函数,带单测)
useEffect(function () {
setDock(function (d) {
const S = global.IWBUiDockSanitize
return (S && typeof S.sanitize === 'function') ? S.sanitize(d, panels, props.defaults) : d
})
}, [panels])
// 把两侧实际占位宽度写给 CSS(画布不动,只让其它浮层让位)
// v3.26.108:改 useLayoutEffect —— 必须在父组件 useEffect(启动 fit/doFit 读 --iwb-dock-l)之前写入,
// 否则首帧读到的占位是 0,初始视口仍会把节点放到停靠栏底下。
useLayoutEffect(function () {
const r = global.document && global.document.documentElement
if (!r) return
// 一级导航常驻在窗口最左(52px):左停靠栏整体右移,工具栏居中基准也要含它
const NAV_W = 52
const lw = dock.left.open ? (NAV_W + dock.left.w) : NAV_W
const rw = dock.right.open ? dock.right.w : 0
r.style.setProperty('--iwb-dock-l', lw + 'px')
r.style.setProperty('--iwb-dock-r', rw + 'px')
// 2026-11-27:占位变化通知宿主 —— 启动 doFit 若在停靠栏就绪前跑过,需要按新占位重新适应一次
try { global.dispatchEvent(new global.CustomEvent('iwb:dock-insets', { detail: { left: lw, right: rw } })) } catch (err) { /* ignore */ }
return function () { r.style.setProperty('--iwb-dock-l', '0px'); r.style.setProperty('--iwb-dock-r', '0px') }
}, [dock.left.open, dock.left.w, dock.right.open, dock.right.w])
const setSide = function (side, patch) {
setDock(function (d) {
const next = { left: Object.assign({}, d.left), right: Object.assign({}, d.right) }
next[side] = Object.assign({}, next[side], patch)
return next
})
}
const toggle = function (side) {
const next = !dock[side].open
setSide(side, { open: next })
if (side === 'right' && typeof props.onRightOpen === 'function') props.onRightOpen(next)
}
// 顶栏的左右开关通过事件驱动(顶栏在 app.js 的另一棵子树里)
useEffect(function () {
const onToggle = function (e) {
const side = e && e.detail && e.detail.side
if (side === 'left') { const next = !dock.left.open; setSide('left', { open: next }) }
if (side === 'right') { const next = !dock.right.open; setSide('right', { open: next }); if (typeof props.onRightOpen === 'function') props.onRightOpen(next) }
}
global.addEventListener('iwb:dock-toggle', onToggle)
// v3.25.82:显式激活某侧面板(右侧栏不再由宿主强行指定 active,避免「图库旁边冒出提示词库」)
const onActivate = function (e) {
const det = e && e.detail
if (!det || (det.side !== 'left' && det.side !== 'right') || !det.id || !panels[det.id]) return
setDock(function (d) {
const side = d[det.side]
if (side.active === det.id) return d
const next = Object.assign({}, d)
next[det.side] = Object.assign({}, side, { active: det.id })
return next
})
}
global.addEventListener('iwb:dock-activate', onActivate)
return function () { global.removeEventListener('iwb:dock-toggle', onToggle); global.removeEventListener('iwb:dock-activate', onActivate) }
}, [dock.left.open, dock.right.open, props.onRightOpen])
// ---- 拖宽(内缘手柄) ----
const startResize = function (side, e) {
e.preventDefault()
e.stopPropagation()
const startX = e.clientX
const startW = dock[side].w
// v3.25.88: 拖动过程只改 DOM 宽度(不走 React setState),松手才提交
const dockEl = (rootRef.current && rootRef.current.querySelector) ? rootRef.current.querySelector('.iwb-dock[data-side="' + side + '"]') : null
let pendingW = startW
let raf = 0
const NAV_W = 52
const flush = function () {
raf = 0
if (dockEl) { try { dockEl.style.width = pendingW + 'px' } catch (err) { /* ignore */ } }
// v3.26.13:拖动过程中同步 --iwb-dock-l/r,工具栏/小地图实时跟着让位(以前只在松手时提交,图标会"飘"过去)
try {
const r = global.document && global.document.documentElement
if (r) {
if (side === 'left') r.style.setProperty('--iwb-dock-l', (NAV_W + pendingW) + 'px')
else r.style.setProperty('--iwb-dock-r', pendingW + 'px')
}
} catch (err) { /* ignore */ }
}
const move = function (ev) {
const dx = ev.clientX - startX
const w = side === 'left' ? startW + dx : startW - dx
pendingW = Math.max(MIN_W, Math.round(w))
if (!raf) raf = global.requestAnimationFrame(flush)
}
// v3.25.88:拖宽期间通知宿主暂停原生 webview 同步(消除卡顿)
try { global.dispatchEvent(new CustomEvent('iwb:dock-resizing', { detail: { active: true, side: side } })) } catch (err) { /* ignore */ }
const up = function () {
global.removeEventListener('pointermove', move)
global.removeEventListener('pointerup', up)
try { global.dispatchEvent(new CustomEvent('iwb:dock-resizing', { detail: { active: false, side: side } })) } catch (err) { /* ignore */ }
if (raf) { try { global.cancelAnimationFrame(raf) } catch (err) { /* ignore */ } raf = 0 }
setSide(side, { w: pendingW })
}
global.addEventListener('pointermove', move)
global.addEventListener('pointerup', up)
}
// ---- 图标拖拽:同栏排序 + 跨栏移动(按鼠标位置插入) ----
const iconCenters = function (side) {
const root = rootRef.current
if (!root) return []
const nodes = root.querySelectorAll('.iwb-dock[data-side="' + side + '"] .iwb-dock-btn')
const out = []
for (let i = 0; i < nodes.length; i++) {
const r = nodes[i].getBoundingClientRect()
out.push({ id: nodes[i].getAttribute('data-panel'), x: r.left + r.width / 2 })
}
return out
}
const indexForX = function (side, x) {
const arr = iconCenters(side)
for (let i = 0; i < arr.length; i++) if (x < arr[i].x) return i
return arr.length
}
const onIconPointerDown = function (side, id, e) {
if (e.button !== 0) return
e.preventDefault()
e.stopPropagation()
const sx = e.clientX
const sy = e.clientY
let started = false
dragRef.current = { side, id }
const move = function (ev) {
if (!started) {
if (Math.abs(ev.clientX - sx) < 4 && Math.abs(ev.clientY - sy) < 4) return
started = true
dragRef.current = { side, id, dragging: true }
}
const rect = rootRef.current ? rootRef.current.getBoundingClientRect() : { left: 0, width: global.innerWidth || 0 }
const mid = rect.left + rect.width / 2
let target = ev.clientX < mid ? 'left' : 'right'
if (!dock[target].open) target = target === 'left' ? 'right' : 'left'
const info = { side: target, index: indexForX(target, ev.clientX) }
dropRef.current = info
setGhost({ id, x: ev.clientX, y: ev.clientY })
setDropInfo(info)
}
const up = function () {
global.removeEventListener('pointermove', move)
global.removeEventListener('pointerup', up)
const d = dragRef.current
dragRef.current = null
setGhost(null)
const info = dropRef.current
dropRef.current = null
setDropInfo(null)
if (!d || !d.dragging || !info) return
commitMove(d.side, d.id, info.side, info.index)
}
global.addEventListener('pointermove', move)
global.addEventListener('pointerup', up)
}
const commitMove = function (fromSide, id, toSide, toIndex) {
if (fromSide === toSide && dock[fromSide].list.length === 1) return
if (fromSide !== toSide && dock[fromSide].list.length === 1) {
if (props.onReject) props.onReject('该栏至少保留一个面板')
return
}
setDock(function (d) {
const next = { left: Object.assign({}, d.left, { list: d.left.list.slice() }), right: Object.assign({}, d.right, { list: d.right.list.slice() }) }
const src = next[fromSide].list
const at = src.indexOf(id)
if (at >= 0) src.splice(at, 1)
let idx = Math.max(0, Math.min(toIndex, next[toSide].list.length))
if (fromSide === toSide && at >= 0 && at < idx) idx -= 1
next[toSide].list.splice(idx, 0, id)
next[toSide].active = id
if (!next[fromSide].list.length) next[fromSide].list.push(id) // 双保险:绝不留空栏
if (next[fromSide].list.indexOf(next[fromSide].active) < 0) next[fromSide].active = next[fromSide].list[0]
return next
})
}
const renderHead = function (side) {
const s = dock[side]
const isLeft = side === 'left'
// v3.25.84:只画「当前可用」的面板(插件关掉后不再残留图标)
const icons = s.list.filter(function (id) { return !!panels[id] }).map(function (id) {
const p = panels[id]
return el('button', {
key: id,
className: 'iwb-dock-btn' + (s.active === id ? ' on' : ''),
'data-panel': id,
'aria-label': (p && p.title) || id,
onPointerDown: function (e) { onIconPointerDown(side, id, e) },
onClick: function (e) { e.stopPropagation(); if (!dragRef.current) setSide(side, { active: id }) },
}, renderIcon((p && p.icon) || 'panel'))
})
return el('div', { className: 'iwb-dock-head' }, icons)
}
const renderBody = function (side) {
const s = dock[side]
const p = panels[s.active]
if (!p) return el('div', { className: 'iwb-dock-empty' }, '面板加载中…')
if (p.node) return p.node
if (p.pluginId) {
const mount = (props.pluginMount && props.pluginMount(p.pluginId)) || null
if (!mount) return el('div', { className: 'iwb-dock-empty' }, p.hint || ((p.title || '插件') + ' 未加载'))
return el(PluginBox, { mount, fallback: p.fallback || null })
}
return el('div', { className: 'iwb-dock-empty' }, '面板不可用')
}
const renderDock = function (side) {
const s = dock[side]
// v3.25.82:插件被关掉后该侧没有可用面板 → 整侧不渲染(连折叠窄条都不画)
const usable = (s.list || []).filter(function (id) { return !!panels[id] })
if (!usable.length) return null
if (!s.open) return null
return el('div', {
key: side,
className: 'iwb-dock ' + side,
'data-side': side,
style: { width: s.w },
onWheel: function (e) { e.stopPropagation() },
onPointerDown: function (e) { e.stopPropagation() },
onContextMenu: function (e) { e.stopPropagation() },
},
renderHead(side),
el('div', { className: 'iwb-dock-body', 'data-panel': s.active }, renderBody(side)),
el('div', { className: 'iwb-dock-resize', onPointerDown: function (e) { startResize(side, e) } }),
(dropInfo && dropInfo.side === side) ? el('div', {
className: 'iwb-dock-drop',
style: { left: (8 + dropInfo.index * 30) + 'px' },
}) : null
)
}
return el('div', { className: 'iwb-dockarea', ref: rootRef, onWheel: function (e) { e.stopPropagation() } },
renderDock('left'),
renderDock('right'),
ghost ? el('div', { className: 'iwb-dock-ghost', style: { left: ghost.x + 12, top: ghost.y + 12 } },
renderIcon((panels[ghost.id] && panels[ghost.id].icon) || 'panel'),
el('span', null, (panels[ghost.id] && panels[ghost.id].title) || '')
) : null
)
}
global.IWBDockArea = IWBDockArea
})(typeof window !== 'undefined' ? window : globalThis)