dsh-design-studio 1.5.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +6 -5
- package/README.md +7 -6
- package/THIRD_PARTY_NOTICES.md +108 -0
- package/assets/art/README.md +102 -0
- package/assets/art/brand-mark.webp +0 -0
- package/assets/art/check-clean.webp +0 -0
- package/assets/art/coach-markup.webp +0 -0
- package/assets/art/drop-file.webp +0 -0
- package/assets/art/empty-components.webp +0 -0
- package/assets/art/empty-data.webp +0 -0
- package/assets/art/empty-error.webp +0 -0
- package/assets/art/empty-frames.webp +0 -0
- package/assets/art/empty-history.webp +0 -0
- package/assets/art/empty-market.webp +0 -0
- package/assets/art/empty-notes.webp +0 -0
- package/assets/art/empty-search.webp +0 -0
- package/assets/art/empty-tokens.webp +0 -0
- package/assets/art/empty-works.webp +0 -0
- package/assets/art/guide-icon.webp +0 -0
- package/assets/art/kind-app.webp +0 -0
- package/assets/art/kind-desktop.webp +0 -0
- package/assets/art/kind-diagram.webp +0 -0
- package/assets/art/kind-dshplugin.webp +0 -0
- package/assets/art/kind-email.webp +0 -0
- package/assets/art/kind-embedded.webp +0 -0
- package/assets/art/kind-framed.webp +0 -0
- package/assets/art/kind-miniprogram.webp +0 -0
- package/assets/art/kind-poster.webp +0 -0
- package/assets/art/kind-slides.webp +0 -0
- package/assets/art/kind-tablet.webp +0 -0
- package/assets/art/kind-web.webp +0 -0
- package/assets/art/placeholder-inspire-img.webp +0 -0
- package/assets/art/wait-creating.webp +0 -0
- package/assets/demo.gif +0 -0
- package/assets/hero-sm.jpg +0 -0
- package/assets/motion/ai-capsule.html +124 -0
- package/assets/motion/ai-glow-input.html +112 -0
- package/assets/motion/balance-odometer.html +112 -0
- package/assets/motion/bottom-sheet.html +149 -0
- package/assets/motion/brightness-pill.html +114 -0
- package/assets/motion/comet-ring.html +95 -0
- package/assets/motion/copy-morph.html +116 -0
- package/assets/motion/cube-grid.html +103 -0
- package/assets/motion/day-night.html +120 -0
- package/assets/motion/dial-knob.html +130 -0
- package/assets/motion/dock-magnify.html +118 -0
- package/assets/motion/download-ring.html +135 -0
- package/assets/motion/expand-card.html +137 -0
- package/assets/motion/flip-card.html +100 -0
- package/assets/motion/hold-pay.html +137 -0
- package/assets/motion/holo-card.html +130 -0
- package/assets/motion/keycap.html +92 -0
- package/assets/motion/like-jelly.html +88 -0
- package/assets/motion/liquid-progress.html +113 -0
- package/assets/motion/liquid-segment.html +127 -0
- package/assets/motion/live-capsule.html +144 -0
- package/assets/motion/marker-highlight.html +94 -0
- package/assets/motion/marquee-logos.html +110 -0
- package/assets/motion/otp-code.html +111 -0
- package/assets/motion/password-eye.html +136 -0
- package/assets/motion/ruler-slider.html +140 -0
- package/assets/motion/search-expand.html +81 -0
- package/assets/motion/send-fly.html +121 -0
- package/assets/motion/skeleton-shine.html +124 -0
- package/assets/motion/star-rate.html +98 -0
- package/assets/motion/success-check.html +114 -0
- package/assets/motion/suggest-chips.html +134 -0
- package/assets/motion/swipe-row.html +126 -0
- package/assets/motion/tabbar-bounce.html +92 -0
- package/assets/motion/tactile-controls.html +89 -0
- package/assets/motion/text-scramble.html +173 -0
- package/assets/motion/toast-stack.html +115 -0
- package/assets/motion/token-stream.html +106 -0
- package/assets/motion/voice-orb.html +144 -0
- package/assets/showcase/alley-noodles-1.webp +0 -0
- package/assets/showcase/alley-noodles-2.webp +0 -0
- package/assets/showcase/alley-noodles-3.webp +0 -0
- package/assets/showcase/autumn-sale-1.webp +0 -0
- package/assets/showcase/bold-folio-1.webp +0 -0
- package/assets/showcase/bold-folio-2.webp +0 -0
- package/assets/showcase/book-club-1.webp +0 -0
- package/assets/showcase/book-club-2.webp +0 -0
- package/assets/showcase/book-club-3.webp +0 -0
- package/assets/showcase/flower-order-1.webp +0 -0
- package/assets/showcase/little-painter-1.webp +0 -0
- package/assets/showcase/little-painter-2.webp +0 -0
- package/assets/showcase/moon-fair-1.webp +0 -0
- package/assets/showcase/nail-booking-1.webp +0 -0
- package/assets/showcase/nail-booking-2.webp +0 -0
- package/assets/showcase/nail-booking-3.webp +0 -0
- package/assets/showcase/night-run-1.webp +0 -0
- package/assets/showcase/paw-diary-1.webp +0 -0
- package/assets/showcase/paw-diary-2.webp +0 -0
- package/assets/showcase/paw-diary-3.webp +0 -0
- package/assets/showcase/pixel-planet-1.webp +0 -0
- package/assets/showcase/pixel-planet-2.webp +0 -0
- package/assets/showcase/pixel-planet-3.webp +0 -0
- package/assets/showcase/pocket-ledger-1.webp +0 -0
- package/assets/showcase/pocket-ledger-2.webp +0 -0
- package/assets/showcase/shiftloom-1.webp +0 -0
- package/assets/showcase/shiftloom-2.webp +0 -0
- package/assets/showcase/slow-breath-1.webp +0 -0
- package/assets/showcase/slow-breath-2.webp +0 -0
- package/assets/showcase/slow-breath-3.webp +0 -0
- package/assets/showcase/slow-trip-1.webp +0 -0
- package/assets/showcase/slow-trip-2.webp +0 -0
- package/assets/showcase/slow-trip-3.webp +0 -0
- package/assets/showcase/slow-weekly-1.webp +0 -0
- package/assets/showcase/stay-confirm-1.webp +0 -0
- package/assets/showcase/stove-recipes-1.webp +0 -0
- package/assets/showcase/stove-recipes-2.webp +0 -0
- package/assets/showcase/strobewatch-1.webp +0 -0
- package/assets/showcase/strobewatch-2.webp +0 -0
- package/assets/showcase/tapeworks-1.webp +0 -0
- package/assets/showcase/tapeworks-2.webp +0 -0
- package/assets/showcase/tea-brand-pitch-1.webp +0 -0
- package/assets/showcase/tea-brand-pitch-2.webp +0 -0
- package/assets/showcase/tea-brand-pitch-3.webp +0 -0
- package/assets/showcase/time-bookshop-1.webp +0 -0
- package/assets/showcase/time-bookshop-2.webp +0 -0
- package/assets/showcase/water-journey-1.webp +0 -0
- package/assets/showcase/water-journey-2.webp +0 -0
- package/assets/showcase/water-journey-3.webp +0 -0
- package/assets/showcase/weekend-go-1.webp +0 -0
- package/assets/showcase/weekend-go-2.webp +0 -0
- package/assets/showcase/weekend-go-3.webp +0 -0
- package/assets/showcase/winter-soup-1.webp +0 -0
- package/assets/showcase/year-review-1.webp +0 -0
- package/assets/showcase/year-review-2.webp +0 -0
- package/assets/showcase/year-review-3.webp +0 -0
- package/lib/browser.js +3 -1
- package/lib/bundle.js +8 -3
- package/lib/canvthumb.js +9 -6
- package/lib/client.js +7428 -2624
- package/lib/components.js +4 -2
- package/lib/core.js +762 -132
- package/lib/design-page-settings.js +48 -0
- package/lib/design-scope.js +36 -0
- package/lib/design-transactions.js +259 -0
- package/lib/drop-folder.js +25 -0
- package/lib/edits.js +125 -8
- package/lib/embedded/lvgl_shot.c +133 -0
- package/lib/embedded/qml_shot.py +66 -0
- package/lib/embedded-shot.js +400 -0
- package/lib/embedded-trust.js +76 -0
- package/lib/fonts.js +30 -21
- package/lib/frames.js +23 -23
- package/lib/gallery/css.js +9 -2
- package/lib/gallery/market-routes.js +23 -7
- package/lib/gallery/pack.js +25 -8
- package/lib/gallery/policy.js +6 -4
- package/lib/gallery/routes.js +255 -83
- package/lib/gallery/submit.js +285 -57
- package/lib/gallery/use.js +13 -4
- package/lib/handoff-embedded.js +1182 -0
- package/lib/handoff.js +212 -71
- package/lib/history.js +393 -43
- package/lib/htmlpack.js +34 -13
- package/lib/impl.js +3 -0
- package/lib/index.js +661 -136
- package/lib/inspire.js +73 -26
- package/lib/kinds.js +11 -2
- package/lib/look.js +45 -25
- package/lib/mock.js +41 -4
- package/lib/motion.js +90 -0
- package/lib/page-settings.js +103 -0
- package/lib/picker.js +348 -70
- package/lib/rules.js +85 -0
- package/lib/serve.js +154 -15
- package/lib/showcase.json +22 -0
- package/lib/styles.js +16 -7
- package/lib/system.js +19 -8
- package/lib/tool.js +2 -1
- package/lib/tweaks.js +146 -9
- package/lib/works.js +151 -19
- package/locale/auto/en.json +1 -1
- package/locale/auto/zh.json +1 -1
- package/locale/en.json +1 -1
- package/locale/offline/en.json +1 -1
- package/locale/offline/zh.json +2 -2
- package/locale/zh.json +1 -1
- package/package.json +3 -2
- package/skills/ui-design/SKILL.md +56 -46
- package/skills/ui-design/frames/dsh/frame.json +1 -1
- package/skills/ui-design/references/app.md +29 -2
- package/skills/ui-design/references/components.md +1 -1
- package/skills/ui-design/references/desktop.md +1 -1
- package/skills/ui-design/references/dshplugin.md +12 -12
- package/skills/ui-design/references/embedded.md +40 -0
- package/skills/ui-design/references/frames.md +20 -20
- package/skills/ui-design/references/miniprogram.md +2 -2
- package/skills/ui-design/references/mock.md +16 -0
- package/skills/ui-design/references/poster.md +2 -1
- package/skills/ui-design/references/tweaks.md +17 -0
- package/skills/ui-design/tokens.css +19 -5
package/lib/core.js
CHANGED
|
@@ -6,11 +6,19 @@
|
|
|
6
6
|
* createTracker 每个会话的预览状态,以及从会话事件里自动发现「该预览什么」
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
+
import { styleElement } from './edits.js'
|
|
10
|
+
import { designWriteScope } from './history.js'
|
|
11
|
+
import { identifyTarget, canonicalPath, matchesTarget, fileEntry } from './design-scope.js'
|
|
12
|
+
import { atomicWrite, createTransactions, fingerprint, readItem, studioError } from './design-transactions.js'
|
|
13
|
+
import { directoryPageSettings, pageSettingsBytes } from './design-page-settings.js'
|
|
14
|
+
import { originalOf, metaOfFile } from './look.js'
|
|
15
|
+
import { readPages, savePages, patchPages, recoverOriginal, fileOriginal } from './page-settings.js'
|
|
9
16
|
import crypto from 'node:crypto'
|
|
10
17
|
import fs from 'node:fs'
|
|
11
18
|
import os from 'node:os'
|
|
12
19
|
import path from 'node:path'
|
|
13
20
|
import { fileURLToPath } from 'node:url'
|
|
21
|
+
import { tokensOf } from './system.js'
|
|
14
22
|
import { createJsonStringDecoder } from './draft.js'
|
|
15
23
|
|
|
16
24
|
const HTML_EXT = /\.html?$/i
|
|
@@ -35,8 +43,8 @@ const BG_JOB = /\bbackground job\s+`?([\w.:-]{3,})/i
|
|
|
35
43
|
const MAX_SCREENS = 60 // 右侧最多显示几屏,再多的收起来并提示(画布同时只挂 24 屏,见 client.js 的 LIVE_MAX)
|
|
36
44
|
const MAX_ROUTES = 300 // 开发服务器的路由先都记着(只为算出收起了几屏);再多就是写飞了
|
|
37
45
|
|
|
38
|
-
//
|
|
39
|
-
import { KINDS } from './kinds.js'
|
|
46
|
+
// 设计类型:决定右侧用什么画幅显示(网页框、手机、小程序、平板、桌面软件窗口、嵌入式屏幕、海报、幻灯片、邮件、图表)
|
|
47
|
+
import { KINDS, sizeFits } from './kinds.js'
|
|
40
48
|
import { mockOf } from './mock.js'
|
|
41
49
|
import { pageUsesComponents, dirReader } from './comp-io.js'
|
|
42
50
|
export { KINDS }
|
|
@@ -46,10 +54,11 @@ const KIND_ALIAS = {
|
|
|
46
54
|
mini: 'miniprogram', miniapp: 'miniprogram', weapp: 'miniprogram', wechat: 'miniprogram', 小程序: 'miniprogram',
|
|
47
55
|
pad: 'tablet', ipad: 'tablet',
|
|
48
56
|
pc: 'desktop', electron: 'desktop', tauri: 'desktop', mac: 'desktop', macos: 'desktop', windows: 'desktop', win: 'desktop', 桌面: 'desktop', 桌面软件: 'desktop',
|
|
57
|
+
hmi: 'embedded', mcu: 'embedded', stm32: 'embedded', lvgl: 'embedded', qml: 'embedded', qt: 'embedded', 嵌入式: 'embedded', 嵌入式屏幕: 'embedded', 工控屏: 'embedded', 中控屏: 'embedded', 'embedded screen': 'embedded',
|
|
49
58
|
social: 'poster', image: 'poster', banner: 'poster', card: 'poster', flyer: 'poster', cover: 'poster',
|
|
50
59
|
slide: 'slides', deck: 'slides', ppt: 'slides', presentation: 'slides',
|
|
51
60
|
mail: 'email', newsletter: 'email', edm: 'email',
|
|
52
|
-
mindmap: 'diagram', 'mind-map': 'diagram', roadmap: 'diagram', architecture: 'diagram', arch: 'diagram', flowchart: 'diagram', 思维导图: 'diagram', 导图: 'diagram', 脑图: 'diagram', 路线图: 'diagram', 技术路线图: 'diagram', 架构图: 'diagram', 图表: 'diagram', '路线图·导图': 'diagram',
|
|
61
|
+
mindmap: 'diagram', 'mind-map': 'diagram', roadmap: 'diagram', architecture: 'diagram', arch: 'diagram', flowchart: 'diagram', 思维导图: 'diagram', 导图: 'diagram', 脑图: 'diagram', 路线图: 'diagram', 技术路线图: 'diagram', 架构图: 'diagram', 图表: 'diagram', 路线图与导图: 'diagram', '路线图·导图': 'diagram',
|
|
53
62
|
dsh: 'dshplugin', 'dsh-plugin': 'dshplugin', dshplug: 'dshplugin', harness: 'dshplugin', dsh插件: 'dshplugin', 'dsh 插件': 'dshplugin',
|
|
54
63
|
frame: 'framed', 外框: 'framed', 自定外框: 'framed', 套外框: 'framed', 外壳: 'framed', 自定义外壳: 'framed',
|
|
55
64
|
}
|
|
@@ -68,7 +77,8 @@ export function parseSize(input) {
|
|
|
68
77
|
if (!m) return ''
|
|
69
78
|
const w = Number(m[1])
|
|
70
79
|
const h = Number(m[2])
|
|
71
|
-
|
|
80
|
+
// 64 起:嵌入式小屏(160×80、128×64);别的类型太小的到 look.js / 右侧栏会退回默认画幅
|
|
81
|
+
if (w < 64 || h < 64 || w > 8000 || h > 8000) return ''
|
|
72
82
|
return `${w}x${h}`
|
|
73
83
|
}
|
|
74
84
|
|
|
@@ -78,7 +88,7 @@ const inCompDir = (abs) => path.basename(path.dirname(String(abs || ''))) === 'c
|
|
|
78
88
|
/** 下一页正文先到时草稿挂在哪个文件夹:写的是组件(components/x.html)就挂在设计根目录,不挂进 components/ */
|
|
79
89
|
const draftDirOf = (abs) => (inCompDir(abs) ? path.dirname(path.dirname(abs)) : path.dirname(abs))
|
|
80
90
|
|
|
81
|
-
export function listScreens(root, keep = '') {
|
|
91
|
+
export function listScreens(root, keep = '', order = manifestOrder(root)) {
|
|
82
92
|
const born = screensByBirth(root)
|
|
83
93
|
let kept = born.slice(-MAX_SCREENS)
|
|
84
94
|
if (keep && !kept.includes(keep)) {
|
|
@@ -86,7 +96,7 @@ export function listScreens(root, keep = '') {
|
|
|
86
96
|
// 按创建顺序放回原位(打开文件夹取的是最早的一屏,别排到最后);不在顶层的(一般不会有)放最后
|
|
87
97
|
kept = born.includes(keep) ? born.filter((x) => x === keep || kept.includes(x)) : [...kept, keep]
|
|
88
98
|
}
|
|
89
|
-
return inManifestOrder(
|
|
99
|
+
return inManifestOrder(kept, order)
|
|
90
100
|
}
|
|
91
101
|
|
|
92
102
|
/**
|
|
@@ -110,8 +120,8 @@ export function exportOrder(shown, hidden, order) {
|
|
|
110
120
|
}
|
|
111
121
|
|
|
112
122
|
/** 目录里所有的屏。按文件名找、改全套的时候用这个,别漏掉收起来的 */
|
|
113
|
-
export function allScreens(root) {
|
|
114
|
-
return inManifestOrder(
|
|
123
|
+
export function allScreens(root, order = manifestOrder(root)) {
|
|
124
|
+
return inManifestOrder(screensByBirth(root), order)
|
|
115
125
|
}
|
|
116
126
|
|
|
117
127
|
/** 顶层的 HTML 文件,按创建时间(= 模型生成的顺序)排 */
|
|
@@ -134,22 +144,45 @@ function screensByBirth(root) {
|
|
|
134
144
|
}
|
|
135
145
|
|
|
136
146
|
/** 有设计清单(design.json,从设计库来的模板 / 分享过的设计):按清单里的顺序排,清单外的(模型后加的)按创建时间排在后面 */
|
|
137
|
-
function inManifestOrder(
|
|
138
|
-
const order = manifestOrder(root)
|
|
147
|
+
function inManifestOrder(names, order) {
|
|
139
148
|
if (!order.length) return names
|
|
140
149
|
const rank = new Map(order.map((f, i) => [f.toLowerCase(), i]))
|
|
141
150
|
const listed = names.filter((x) => rank.has(x.toLowerCase())).sort((a, b) => rank.get(a.toLowerCase()) - rank.get(b.toLowerCase()))
|
|
142
151
|
return [...listed, ...names.filter((x) => !rank.has(x.toLowerCase()))]
|
|
143
152
|
}
|
|
144
153
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
154
|
+
function readDesignManifest(root) {
|
|
155
|
+
try {
|
|
156
|
+
const file = path.join(root, 'design.json')
|
|
157
|
+
const st = fs.lstatSync(file)
|
|
158
|
+
if (!st.isFile() || st.size > 256 * 1024) return null
|
|
159
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
160
|
+
} catch { return null }
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function designAccent(root, manifest) {
|
|
164
|
+
if (typeof manifest?.accent === 'string' && manifest.accent.length <= 128 && manifest.accent.trim()) return manifest.accent.trim()
|
|
148
165
|
try {
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
166
|
+
const file = path.join(root, 'tokens.css')
|
|
167
|
+
const st = fs.lstatSync(file)
|
|
168
|
+
if (!st.isFile() || st.size > 256 * 1024) return ''
|
|
169
|
+
const vars = tokensOf(fs.readFileSync(file, 'utf8'))
|
|
170
|
+
const names = Object.keys(vars).filter(n => !/ink|text|fg|on-|soft|veil|line|muted|bg/i.test(n))
|
|
171
|
+
let key = names.find(n => /(?:^|-)(?:primary|brand)(?:-(?:500|base|main|default))?$/i.test(n)) || names.find(n => /primary|brand|accent/i.test(n))
|
|
172
|
+
const seen = new Set()
|
|
173
|
+
while (key && !seen.has(key)) {
|
|
174
|
+
seen.add(key)
|
|
175
|
+
const value = vars[key]?.trim() || ''
|
|
176
|
+
const alias = /^var\(\s*(--[\w-]+)\s*\)$/.exec(value)
|
|
177
|
+
if (!alias) return value.length <= 128 ? value : ''
|
|
178
|
+
key = alias[1]
|
|
179
|
+
}
|
|
180
|
+
} catch { /* A first draft can precede its stylesheet. */ }
|
|
181
|
+
return ''
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** design.json 里 screens 的文件名(读不了、写错了都当没有) */
|
|
185
|
+
export function manifestOrder(root, m = readDesignManifest(root)) {
|
|
153
186
|
if (!m || !Array.isArray(m.screens)) return []
|
|
154
187
|
return m.screens.map((s) => (s && typeof s.file === 'string' ? s.file : typeof s === 'string' ? s : '')).filter((f) => f && !/[\\/]/.test(f) && HTML_EXT.test(f)).slice(0, MAX_SCREENS)
|
|
155
188
|
}
|
|
@@ -222,7 +255,7 @@ export function parseTarget(input, cwd = os.homedir()) {
|
|
|
222
255
|
} else if (!HTML_EXT.test(p)) {
|
|
223
256
|
throw new Error(`只能预览 .html 文件:${p}`)
|
|
224
257
|
}
|
|
225
|
-
return { kind: 'file', file: p, root: path.dirname(p) }
|
|
258
|
+
return { kind: 'file', file: p, root: path.dirname(p), ...(st.isDirectory() ? { directory: true } : {}) }
|
|
226
259
|
}
|
|
227
260
|
|
|
228
261
|
function proxyTarget(port, pathname) {
|
|
@@ -309,7 +342,7 @@ export function devServerIn(command, text, skipPorts = new Set()) {
|
|
|
309
342
|
// ── 预览里直接改字:在 HTML 源码的文字部分里找到那一处换掉 ──────────────────────
|
|
310
343
|
|
|
311
344
|
/** 一份文件内容的指纹(撤销改字时核对文件后来没被别处改过) */
|
|
312
|
-
const sigOf = (text) => crypto.createHash('sha1').update(String(text)).digest('hex').slice(0, 16)
|
|
345
|
+
export const sigOf = (text) => crypto.createHash('sha1').update(String(text)).digest('hex').slice(0, 16)
|
|
313
346
|
|
|
314
347
|
/** 标签、注释、脚本 / 样式这类不算文字的块;剩下的就是页面上看得到的字 */
|
|
315
348
|
const NOT_TEXT = /<!--[\s\S]*?-->|<(script|style|textarea|noscript|template|title)\b[^>]*>[\s\S]*?<\/\1\s*>|<[^>]*>/gi
|
|
@@ -833,23 +866,116 @@ export function askOf(data) {
|
|
|
833
866
|
words = words || l
|
|
834
867
|
}
|
|
835
868
|
const sub = subjects.slice(0, 2).join('、') + (subjects.length > 2 ? ' 等' : '')
|
|
836
|
-
const line = sub && words ?
|
|
869
|
+
const line = sub && words ? sub + (/[\u3400-\u9fff]/.test(words) ? ',' : ', ') + words : sub ? (sub === '参考图' ? '照参考图改' : `改${sub}`) : words
|
|
837
870
|
return line.length > 40 ? line.slice(0, 40) + '…' : line
|
|
838
871
|
}
|
|
839
872
|
|
|
840
873
|
/**
|
|
841
874
|
* @param opts.alive (origin) → 这个预览服务器还开着吗(开的太多时旧的会被关掉;发现没了就重开)
|
|
842
875
|
*/
|
|
843
|
-
export function
|
|
876
|
+
export function scopeFor(target) {
|
|
877
|
+
if (!target) return { pages: [], writableKeys: [], entry: '', assetRoot: '' }
|
|
878
|
+
if (target.kind === 'proxy') return { pages: [], writableKeys: [], entry: target.path, assetRoot: '' }
|
|
879
|
+
const entry = fileEntry(target)
|
|
880
|
+
const pages = target.directory ? allScreens(target.root) : entry ? [entry] : []
|
|
881
|
+
return { scope: target.scope, pages, entry: pages.includes(entry) ? entry : pages[0] || '', writableKeys: pages, assetRoot: target.root }
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
export function createTracker({ open, drafts = null, skipPorts = () => new Set(), now = Date.now, log = () => {}, store = null, proxyRoot = null, history = null, alive = () => true, autoOpen = () => true, beforeRestore = () => {}, transactionBase = null, transactionWrite, resolveDesign = () => null, trust = () => '', watchTag = () => '' }) {
|
|
844
885
|
const states = new Map() // sessionId → state
|
|
845
886
|
const cwds = new Map() // sessionId → 最近一次工具的工作目录
|
|
846
887
|
let saved = {}
|
|
847
888
|
try { saved = (store && store.load()) || {} } catch (e) { log(e) }
|
|
848
889
|
const restoring = new Set()
|
|
890
|
+
const restoreJobs = new Map()
|
|
891
|
+
const transactions = createTransactions({ base: transactionBase, log, now, write: transactionWrite })
|
|
892
|
+
const restorePlans = new Map()
|
|
893
|
+
const clips = new Map()
|
|
894
|
+
const opening = new Map()
|
|
895
|
+
const knownTargets = new Map()
|
|
896
|
+
|
|
897
|
+
function accepts(target, key) {
|
|
898
|
+
if (!matchesTarget(target, key)) return false
|
|
899
|
+
if (key === target.targetKey || target.kind !== 'file') return true
|
|
900
|
+
return (knownTargets.get(canonicalPath(target.root))?.size || 0) < 2
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
function metadataFor(id, st) {
|
|
904
|
+
const target = st.target
|
|
905
|
+
const scope = scopeFor(target)
|
|
906
|
+
const db = transactions.load(target.designId)
|
|
907
|
+
const first = db.initialOwned || st.initialScreens || []
|
|
908
|
+
const manifest = readDesignManifest(target.root)
|
|
909
|
+
const archive = history?.latest?.(target)
|
|
910
|
+
const current = new Set([scope.entry, ...first, ...manifestOrder(target.root, manifest), ...(db.owned || []), ...(st.writtenPages || [])])
|
|
911
|
+
const written = db.edits.flatMap(edit => edit.files)
|
|
912
|
+
const managed = [...new Set([...(archive?.managed || []), ...written, ...(st.writtenAssets || []),
|
|
913
|
+
...(Array.isArray(manifest?.assets) ? manifest.assets.map(asset => typeof asset === 'string' ? asset : asset?.path).filter(Boolean) : []),
|
|
914
|
+
])]
|
|
915
|
+
const directory = target.directory ? directorySettings(target, true) : null
|
|
916
|
+
const saved = directory?.settings || {}
|
|
917
|
+
for (const key of archive?.owned || []) current.add(key)
|
|
918
|
+
for (const key of Object.keys(saved.screens || {})) current.add(key)
|
|
919
|
+
for (const key of scope.pages) if (isDesignHtml(path.join(target.root, key))) current.add(key)
|
|
920
|
+
const owned = scope.pages.filter(key => current.has(key))
|
|
921
|
+
const available = new Set(scope.pages)
|
|
922
|
+
const shown = st.screens.filter(key => available.has(key))
|
|
923
|
+
const visible = new Set(shown)
|
|
924
|
+
const pages = target.directory ? exportOrder(shown, scope.pages.filter(key => !visible.has(key)), scope.pages) : scope.pages
|
|
925
|
+
return { ...scope, pages, owned, managed, initial: first, settingsPresent: directory?.present, settingsFile: directory?.file,
|
|
926
|
+
settings: directory ? saved : pageMetadata(id, st, true), kind: st.kind, size: st.size, view: st.view, display: db.display }
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
function changeScope(id, targetKey) {
|
|
930
|
+
const st = states.get(id)
|
|
931
|
+
const t = st?.target
|
|
932
|
+
if (!t || targetKey !== undefined && !accepts(t, targetKey)) throw studioError('moved', '设计已切换')
|
|
933
|
+
return [st, t]
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
function publishChange(st, result, { version = true } = {}) {
|
|
937
|
+
if (!result.change || result.change.afterRev !== st.rev + 1) return result
|
|
938
|
+
for (const [id, other] of states) {
|
|
939
|
+
if (other.target?.designId !== st.target.designId) continue
|
|
940
|
+
other.rev++
|
|
941
|
+
if (version) other.vrev++
|
|
942
|
+
refreshScreens(other)
|
|
943
|
+
const scope = scopeFor(other.target)
|
|
944
|
+
if (other.target.directory && other.target.file !== (scope.entry ? path.join(other.target.root, scope.entry) : '')) {
|
|
945
|
+
other.target = { ...other.target, file: scope.entry ? path.join(other.target.root, scope.entry) : '' }
|
|
946
|
+
other.url = scope.entry ? urlFor(other.target, other.origin) : ''
|
|
947
|
+
other.label = labelOf(other.target)
|
|
948
|
+
}
|
|
949
|
+
persist(id, other)
|
|
950
|
+
}
|
|
951
|
+
return result
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
function commit(id, st, change, options = {}) {
|
|
955
|
+
const result = transactions.update(st.target, { ...change, rev: st.rev })
|
|
956
|
+
updateFocus(st, result.focus)
|
|
957
|
+
return publishChange(st, result, options)
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
function updateFocus(st, focus) {
|
|
961
|
+
if (!focus || !st.target?.directory || path.basename(st.target.file || '') !== focus.from || focus.to === focus.from) return
|
|
962
|
+
const file = focus.to ? path.join(st.target.root, focus.to) : ''
|
|
963
|
+
st.target = { ...st.target, file }
|
|
964
|
+
st.url = file ? urlFor(st.target, st.origin) : ''
|
|
965
|
+
st.label = labelOf(st.target)
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
const resultState = (id, result) => result.ok && result.change ? { ...result, state: snapshot(id) } : result
|
|
969
|
+
function writeResult(fn) {
|
|
970
|
+
try { return fn() } catch (e) {
|
|
971
|
+
log(e)
|
|
972
|
+
return { ok: false, reason: e.code || 'backup', error: e.message }
|
|
973
|
+
}
|
|
974
|
+
}
|
|
849
975
|
|
|
850
976
|
function persist(id, st) {
|
|
851
977
|
if (!store) return
|
|
852
|
-
if (st.target) saved[id] = { target: st.target, source: st.source, design: st.design, kind: st.kind, size: st.size, view: st.view, routes: st.routes, order: st.target.kind === 'file' ? st.screens : undefined, cwd: cwds.get(id) || (saved[id] && saved[id].cwd) || undefined, at: now() }
|
|
978
|
+
if (st.target) saved[id] = { target: st.target, source: st.source, design: st.design, kind: st.kind, size: st.size, view: st.view, routes: st.routes, proxyDesigns: st.proxyDesigns, initialScreens: st.initialScreens, legacyFitTarget: st.legacyFitTarget || undefined, order: st.target.kind === 'file' ? st.screens : undefined, cwd: cwds.get(id) || (saved[id] && saved[id].cwd) || undefined, at: now() }
|
|
853
979
|
else delete saved[id]
|
|
854
980
|
// 只留最近 200 个会话
|
|
855
981
|
const ids = Object.keys(saved)
|
|
@@ -863,15 +989,47 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
863
989
|
function restore(id) {
|
|
864
990
|
const rec = saved[id]
|
|
865
991
|
if (!rec || !rec.target || restoring.has(id)) return
|
|
866
|
-
const
|
|
867
|
-
|
|
992
|
+
const retained = rec.target
|
|
993
|
+
let input = retained
|
|
994
|
+
if (retained.kind === 'file' && retained.scope !== 'directory') {
|
|
995
|
+
const entry = path.basename(retained.file || '')
|
|
996
|
+
const hadSiblings = [rec.order, rec.initialScreens].some(keys => Array.isArray(keys) && keys.includes(entry) && keys.some(key => key !== entry))
|
|
997
|
+
// Explicit user-opened single files can live beside a folder with its own history.
|
|
998
|
+
// Tool/auto openings created by this version always start as folders.
|
|
999
|
+
if (hadSiblings || ((!retained.scope || rec.source === 'tool' || rec.source === 'auto') &&
|
|
1000
|
+
(history?.legacyEntry?.(retained.root, entry) || typeof readDesignManifest(retained.root)?.from?.zip === 'string'))) {
|
|
1001
|
+
input = { kind: 'file', root: retained.root, file: retained.file, directory: true }
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
let t = resolveDesign(input, { restore: true }) || input
|
|
1005
|
+
if (t.kind === 'file') t = { ...t, legacyViewport: retained.legacyViewport || { kind: rec.kind || '', size: rec.size || '' } }
|
|
1006
|
+
if (t.kind === 'file' && !t.directory && t.designId && t.file !== retained.file) {
|
|
1007
|
+
transactions.relocateFile(t.designId, path.basename(retained.file || ''), path.basename(t.file || ''))
|
|
1008
|
+
}
|
|
1009
|
+
if (t.kind === 'file' && !fileEntry(t)) {
|
|
1010
|
+
stateOf(id).missingTarget = t.file
|
|
1011
|
+
stateOf(id).missingDesignId = t.designId || ''
|
|
1012
|
+
if (!t.directory) return
|
|
1013
|
+
const next = allScreens(t.root)[0]
|
|
1014
|
+
if (!next && !fs.existsSync(t.root)) return
|
|
1015
|
+
t = { ...t, file: next ? path.join(t.root, next) : '' }
|
|
1016
|
+
}
|
|
868
1017
|
// 以前不分是不是在做设计、自动打开的(比如别的项目的端口):不是设计稿就不再接着显示
|
|
869
1018
|
if (rec.source === 'auto' && !rec.design && !(t.kind === 'file' && isDesignHtml(t.file))) return
|
|
870
1019
|
stateOf(id).design = stateOf(id).design || !!rec.design
|
|
1020
|
+
stateOf(id).proxyDesigns = rec.proxyDesigns || (rec.proxyPages && t.kind === 'proxy' ? { [t.port]: rec.proxyPages } : {})
|
|
1021
|
+
const legacyFitTarget = rec.legacyFitTarget || ((!retained.scope || input !== retained || retained.scope === 'directory') && (retained.kind === 'file' ? 'file|' + retained.root : 'proxy|' + retained.port))
|
|
871
1022
|
restoring.add(id)
|
|
872
|
-
setTarget(id, t, { source: rec.source || 'auto', popup: false, kind: rec.kind || '', size: rec.size || '', view: rec.view || '', routes: rec.routes || null, order: rec.order })
|
|
1023
|
+
const job = setTarget(id, t, { source: rec.source || 'auto', popup: false, kind: rec.kind || '', size: rec.size || '', view: rec.view || '', routes: rec.routes || null, order: rec.order, initial: rec.initialScreens, legacyFitTarget, legacyRoot: retained.root, restore: true })
|
|
873
1024
|
.catch((e) => log(e))
|
|
874
|
-
.finally(() => restoring.delete(id))
|
|
1025
|
+
.finally(() => { restoring.delete(id); restoreJobs.delete(id) })
|
|
1026
|
+
restoreJobs.set(id, job)
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
async function readySnapshot(id) {
|
|
1030
|
+
snapshot(id)
|
|
1031
|
+
await restoreJobs.get(id)
|
|
1032
|
+
return snapshot(id)
|
|
875
1033
|
}
|
|
876
1034
|
|
|
877
1035
|
/** 预览服务器被关了(开的太多,没人连着的旧服务器先关):照原样重开一个,先试原来的端口(地址不变,右侧栏不用重载) */
|
|
@@ -933,14 +1091,26 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
933
1091
|
st.hidden = 0
|
|
934
1092
|
if (!t) { st.screens = []; return }
|
|
935
1093
|
if (t.kind === 'file') {
|
|
936
|
-
const
|
|
937
|
-
|
|
938
|
-
const
|
|
1094
|
+
const manifest = readDesignManifest(t.root)
|
|
1095
|
+
st.zipPages = typeof manifest?.from?.zip === 'string'
|
|
1096
|
+
const order = manifestOrder(t.root, manifest)
|
|
1097
|
+
st.accent = designAccent(t.root, manifest)
|
|
1098
|
+
const scope = scopeFor(t)
|
|
1099
|
+
const all = scope.pages
|
|
1100
|
+
const me = scope.entry
|
|
1101
|
+
const found = t.directory ? listScreens(t.root, me, order) : all
|
|
1102
|
+
const preferred = transactions.load(t.designId).screenOrder
|
|
1103
|
+
if (preferred) st.screens = preferred.filter(key => found.includes(key))
|
|
939
1104
|
// 已经排好的几屏位置不动:编辑器改文件常是写临时文件再换名,创建时间会变,按它重排画布会乱跳
|
|
940
1105
|
const list = st.screens.filter((k) => found.includes(k))
|
|
941
|
-
for (const k of found)
|
|
1106
|
+
for (const k of found) {
|
|
1107
|
+
if (list.includes(k)) continue
|
|
1108
|
+
const later = found.slice(found.indexOf(k) + 1).find(key => list.includes(key))
|
|
1109
|
+
if (found.length === MAX_SCREENS && later && all.includes(k)) list.splice(list.indexOf(later), 0, k)
|
|
1110
|
+
else placeScreen(list, k)
|
|
1111
|
+
}
|
|
942
1112
|
st.screens = list
|
|
943
|
-
st.hidden = Math.max(0, all.length
|
|
1113
|
+
st.hidden = Math.max(0, all.length - list.length)
|
|
944
1114
|
} else {
|
|
945
1115
|
const list = st.routes ? [...st.routes] : []
|
|
946
1116
|
if (!list.includes(t.path)) list.unshift(t.path)
|
|
@@ -954,31 +1124,88 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
954
1124
|
/** 和现在预览的是不是同一个目录 / 同一个开发服务器(是的话类型、视图这些设置留着) */
|
|
955
1125
|
function sameRoot(a, b) {
|
|
956
1126
|
if (!a || !b || a.kind !== b.kind) return false
|
|
957
|
-
return a.
|
|
1127
|
+
return a.designId === b.designId
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
/**
|
|
1131
|
+
* 换了类型、画幅没一起改:记着的画幅新类型收不下(嵌入式 160×80 切到平板)就清掉,回到页面写的;收得下的(网页 180×320 切 App)留着。
|
|
1132
|
+
* 右侧栏的类型菜单和模型的 preview_page 都走这里
|
|
1133
|
+
*/
|
|
1134
|
+
function dropUnfitSize(st, kind, size) {
|
|
1135
|
+
if (kind !== undefined && size === undefined && st.size && st.kind && !sizeFits(st.size, st.kind)) st.size = ''
|
|
958
1136
|
}
|
|
959
1137
|
|
|
960
1138
|
/** 设预览目标并开服务器;popup 为真时让右侧栏弹出来。kind / size / view / routes 不传就沿用(换了目录就清掉) */
|
|
961
|
-
async function setTarget(id,
|
|
1139
|
+
async function setTarget(id, input, { source, popup = true, kind, size, view, routes, order, initial, legacyFitTarget, legacyRoot, restore = false, model = source === 'tool' } = {}) {
|
|
962
1140
|
const st = stateOf(id)
|
|
1141
|
+
const local = input.kind === 'file'
|
|
1142
|
+
const active = st.target
|
|
1143
|
+
if (model && local && active?.scope === 'file' && canonicalPath(input.root) === canonicalPath(active.root)) {
|
|
1144
|
+
input = active
|
|
1145
|
+
source = st.source
|
|
1146
|
+
} else if (local && !restore && !input.designId && (source === 'auto' || model)) {
|
|
1147
|
+
input = { ...input, directory: true }
|
|
1148
|
+
}
|
|
1149
|
+
const known = resolveDesign(input, { restore }) || input
|
|
1150
|
+
const target = identifyTarget(known, { cwd: cwdOf(id), known: known.designId })
|
|
1151
|
+
if (target.kind === 'file' && target.designId === active?.designId && !target.legacyViewport && active.legacyViewport) target.legacyViewport = active.legacyViewport
|
|
1152
|
+
if (target.directory && !target.file) {
|
|
1153
|
+
const next = scopeFor(target).entry
|
|
1154
|
+
if (next) target.file = path.join(target.root, next)
|
|
1155
|
+
}
|
|
1156
|
+
if (target.kind === 'file') {
|
|
1157
|
+
if (!scopeFor(target).entry && !target.directory) throw studioError('gone', '找不到这份设计文件')
|
|
1158
|
+
transactions.recover(target)
|
|
1159
|
+
if (target.directory) {
|
|
1160
|
+
if (legacyRoot && canonicalPath(legacyRoot) === canonicalPath(target.root)) history?.migrateLegacy?.(legacyRoot, target)
|
|
1161
|
+
const db = transactions.load(target.designId)
|
|
1162
|
+
if (!db.initialOwned) {
|
|
1163
|
+
const archived = history?.latest?.(target)
|
|
1164
|
+
const manifest = manifestOrder(target.root)
|
|
1165
|
+
const keys = Array.isArray(initial) ? initial : archived ? archived.owned || [scopeFor(target).entry] :
|
|
1166
|
+
manifest.length ? manifest : scopeFor(target).pages
|
|
1167
|
+
transactions.save(target.designId, { ...db, initialOwned: keys.filter(Boolean) })
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
if (model && active?.scope === 'file' && input === active) return st
|
|
1172
|
+
const ticket = Symbol()
|
|
1173
|
+
opening.set(id, ticket)
|
|
963
1174
|
const { origin } = await open(target)
|
|
964
|
-
|
|
1175
|
+
if (opening.get(id) !== ticket) throw studioError('moved', '设计已切换')
|
|
1176
|
+
opening.delete(id)
|
|
1177
|
+
const changed = !sameTarget(st.target, target) || !sameRoot(st.target, target)
|
|
965
1178
|
if (!sameRoot(st.target, target)) {
|
|
1179
|
+
st.legacyFitTarget = legacyFitTarget || ''
|
|
1180
|
+
st.proxyPages = target.kind === 'proxy' ? st.proxyDesigns?.[target.port] || {} : {}
|
|
966
1181
|
st.kind = ''
|
|
967
1182
|
st.size = ''
|
|
968
1183
|
st.view = ''
|
|
969
1184
|
st.routes = null
|
|
970
1185
|
st.screens = []
|
|
1186
|
+
st.initialScreens = Array.isArray(initial) ? initial : target.kind === 'file' && scopeFor(target).entry ? [scopeFor(target).entry] : []
|
|
1187
|
+
st.writtenPages = new Set()
|
|
1188
|
+
st.writtenAssets = new Set()
|
|
971
1189
|
}
|
|
972
1190
|
if (Array.isArray(order)) st.screens = order.filter((k) => typeof k === 'string')
|
|
973
1191
|
if (kind !== undefined) st.kind = parseKind(kind)
|
|
974
1192
|
if (size !== undefined) st.size = parseSize(size)
|
|
1193
|
+
dropUnfitSize(st, kind, size)
|
|
975
1194
|
if (view !== undefined) st.view = view === 'canvas' || view === 'single' ? view : ''
|
|
976
1195
|
if (routes !== undefined) st.routes = normRoutes(routes)
|
|
977
1196
|
// 换到别的目录了:正在写的草稿是原来那套的,不再报(不然新设计里同名的那屏会被它挡住)
|
|
978
1197
|
if (st.draft && !(target.kind === 'file' && st.draft.root === target.root)) st.draft = null
|
|
1198
|
+
st.missingTarget = ''
|
|
1199
|
+
st.missingDesignId = ''
|
|
1200
|
+
if (target.kind === 'file') {
|
|
1201
|
+
const root = canonicalPath(target.root)
|
|
1202
|
+
const identities = knownTargets.get(root) || new Set()
|
|
1203
|
+
identities.add(target.designId)
|
|
1204
|
+
knownTargets.set(root, identities)
|
|
1205
|
+
}
|
|
979
1206
|
st.target = target
|
|
980
1207
|
st.origin = origin
|
|
981
|
-
st.url = urlFor(target, origin)
|
|
1208
|
+
st.url = target.kind === 'file' && !target.file ? '' : urlFor(target, origin)
|
|
982
1209
|
st.label = labelOf(target)
|
|
983
1210
|
st.source = source
|
|
984
1211
|
if (source === 'tool' || source === 'user') st.design = true // 模型调了预览工具 / 用户自己打开:这个会话就是在做设计
|
|
@@ -987,34 +1214,132 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
987
1214
|
if (changed) st.rev++
|
|
988
1215
|
if (popup) st.openRev++
|
|
989
1216
|
refreshScreens(st)
|
|
1217
|
+
if (target.kind === 'file' && target.file && (source === 'tool' || source === 'user')) {
|
|
1218
|
+
const key = path.basename(target.file)
|
|
1219
|
+
try {
|
|
1220
|
+
const doc = pageMetadata(id, st, true)
|
|
1221
|
+
if (doc.screens?.[key]) {
|
|
1222
|
+
const repaired = target.directory ? recoverOriginal(doc, target.root, key, st, history, target) : doc
|
|
1223
|
+
if (repaired !== doc) writeBaseline(id, st, repaired)
|
|
1224
|
+
} else {
|
|
1225
|
+
const meta = metaOfFile(target.file)
|
|
1226
|
+
if (meta || st.kind || st.size) {
|
|
1227
|
+
const first = originalOf(st, meta)
|
|
1228
|
+
// Fixed artworks without a declared size need the live page's content measurement.
|
|
1229
|
+
if (!first.auto) writeBaseline(id, st, patchPages(doc, st.screens, {
|
|
1230
|
+
originals: { [key]: { kind: first.kind, size: first.size.join('x') } }
|
|
1231
|
+
}))
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
} catch (e) { log(e) }
|
|
1235
|
+
}
|
|
990
1236
|
persist(id, st)
|
|
991
1237
|
return st
|
|
992
1238
|
}
|
|
993
1239
|
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
1240
|
+
function directorySettings(target, strict) {
|
|
1241
|
+
return directoryPageSettings(target.root, { strict, isProject: bytes => history?.legacyProjectSettings?.(target, bytes) })
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
function pageMetadata(id, st, strict = false) {
|
|
1245
|
+
const target = st.target
|
|
1246
|
+
const stored = transactions.load(target.designId).settings
|
|
1247
|
+
if (target.kind === 'file') return target.directory ? directorySettings(target, strict).settings : stored || {}
|
|
1248
|
+
if (stored) return stored
|
|
1249
|
+
if (proxyRoot) {
|
|
1250
|
+
const shared = readPages(proxyRoot(cwdOf(id), target.port), strict)
|
|
1251
|
+
if (shared.screens || shared.devices) return shared
|
|
1252
|
+
}
|
|
1253
|
+
return st.proxyPages || {}
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
function writeBaseline(id, st, next) {
|
|
1257
|
+
const target = st.target
|
|
1258
|
+
if (target.directory) atomicWrite(path.join(target.root, directorySettings(target, true).file), pageSettingsBytes(next), 0o644)
|
|
1259
|
+
else {
|
|
1260
|
+
const db = transactions.load(target.designId)
|
|
1261
|
+
transactions.save(target.designId, { ...db, settings: next })
|
|
1262
|
+
if (!transactionBase && target.kind === 'proxy' && proxyRoot) {
|
|
1263
|
+
const root = proxyRoot(cwdOf(id), target.port)
|
|
1264
|
+
fs.mkdirSync(root, { recursive: true })
|
|
1265
|
+
savePages(root, next)
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
async function setView(id, { kind, size, view, focus, settings, targetKey, requestId, display, initialSettings = false } = {}) {
|
|
1271
|
+
const [st, target] = changeScope(id, targetKey ?? settings?.target)
|
|
1272
|
+
if (settings && !targetKey && !settings.target) throw studioError('moved', '设计已切换')
|
|
1273
|
+
if (focus && target.kind === 'file' && !scopeFor(target).pages.includes(focus)) throw studioError('scope', `没有这一屏:${focus}`)
|
|
1274
|
+
if (focus && target.kind === 'proxy' && !String(focus).startsWith('/')) throw studioError('scope', `路由要以 / 开头:${focus}`)
|
|
1275
|
+
let result = { ok: true }
|
|
1276
|
+
if (settings || display !== undefined) {
|
|
1277
|
+
const cached = transactions.cached(target, 'settings', requestId)
|
|
1278
|
+
if (cached) return resultState(id, cached)
|
|
1279
|
+
const old = pageMetadata(id, st, true)
|
|
1280
|
+
const keys = target.kind === 'file' ? scopeFor(target).pages : st.screens
|
|
1281
|
+
if (settings && target.kind === 'file' && settings.originals) {
|
|
1282
|
+
const originals = { ...settings.originals }
|
|
1283
|
+
for (const key of Object.keys(originals)) {
|
|
1284
|
+
if (keys.includes(key) && !old.screens?.[key]) originals[key] = fileOriginal(target.root, key, st, originals[key])
|
|
1285
|
+
}
|
|
1286
|
+
settings = { ...settings, originals }
|
|
1287
|
+
}
|
|
1288
|
+
const next = settings ? patchPages(old, keys, settings) : old
|
|
1289
|
+
const changed = JSON.stringify(next) !== JSON.stringify(old)
|
|
1290
|
+
const formal = settings?.page || settings?.devices !== undefined || display !== undefined
|
|
1291
|
+
if (changed && !formal) {
|
|
1292
|
+
writeBaseline(id, st, next)
|
|
1293
|
+
} else if ((changed && formal) || display !== undefined) {
|
|
1294
|
+
// Model initialization of device choices is a baseline, not a manual transaction.
|
|
1295
|
+
const initializing = initialSettings && settings.devices !== undefined && old.devices === undefined
|
|
1296
|
+
if (initializing) {
|
|
1297
|
+
writeBaseline(id, st, next)
|
|
1298
|
+
} else {
|
|
1299
|
+
if (target.kind === 'file' && busyRoot(target.root)) throw studioError('busy', '模型正在写这个设计')
|
|
1300
|
+
const writes = new Map()
|
|
1301
|
+
const metadata = {}
|
|
1302
|
+
if (changed && target.directory) writes.set(directorySettings(target, true).file, pageSettingsBytes(next))
|
|
1303
|
+
else if (changed) metadata.settings = next
|
|
1304
|
+
if (display !== undefined) {
|
|
1305
|
+
const clean = Object.fromEntries(Object.entries(display || {}).filter(([key, value]) => ['dark', 'fit'].includes(key) && typeof value === 'boolean'))
|
|
1306
|
+
metadata.display = { ...transactions.load(target.designId).display, ...clean }
|
|
1307
|
+
}
|
|
1308
|
+
keepVersion(st, '', 'pre', id)
|
|
1309
|
+
const screen = settings?.page
|
|
1310
|
+
const row = next.screens?.[screen]
|
|
1311
|
+
const detail = { screen, page: row?.current || row?.original, ...(settings?.devices !== undefined ? { devices: next.devices } : {}), ...(display !== undefined ? { display: metadata.display } : {}) }
|
|
1312
|
+
result = commit(id, st, { detail, kind: 'settings', label: '页面设置', pages: settings?.page ? [settings.page] : [], writes, settingsFiles: [...writes.keys()], metadata, requestId })
|
|
1313
|
+
if (result.change) {
|
|
1314
|
+
if (!transactionBase && target.kind === 'proxy' && proxyRoot && changed) writeBaseline(id, st, next)
|
|
1315
|
+
keepVersion(st, '页面设置', 'me', id)
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
998
1320
|
if (kind !== undefined) st.kind = parseKind(kind)
|
|
999
1321
|
if (size !== undefined) st.size = parseSize(size)
|
|
1322
|
+
dropUnfitSize(st, kind, size)
|
|
1000
1323
|
if (view !== undefined) st.view = view === 'canvas' || view === 'single' ? view : ''
|
|
1001
1324
|
if (focus) {
|
|
1002
1325
|
const t = st.target
|
|
1003
1326
|
const key = String(focus)
|
|
1004
1327
|
if (t.kind === 'file') {
|
|
1005
|
-
|
|
1006
|
-
await setTarget(id, { kind: 'file', file: path.join(t.root, key), root: t.root }, { source: st.source, popup: false })
|
|
1328
|
+
await setTarget(id, { ...t, file: path.join(t.root, key) }, { source: st.source, popup: false })
|
|
1007
1329
|
} else {
|
|
1008
1330
|
if (!key.startsWith('/')) throw new Error(`路由要以 / 开头:${key}`)
|
|
1009
1331
|
await setTarget(id, { kind: 'proxy', port: t.port, path: key }, { source: st.source, popup: false })
|
|
1010
1332
|
}
|
|
1011
1333
|
}
|
|
1012
1334
|
persist(id, st)
|
|
1013
|
-
return st
|
|
1335
|
+
return { ...st, ...resultState(id, result) }
|
|
1014
1336
|
}
|
|
1015
1337
|
|
|
1016
1338
|
function clear(id) {
|
|
1017
1339
|
const st = stateOf(id)
|
|
1340
|
+
opening.delete(id)
|
|
1341
|
+
st.missingTarget = ''
|
|
1342
|
+
st.missingDesignId = ''
|
|
1018
1343
|
st.target = null
|
|
1019
1344
|
st.draft = null
|
|
1020
1345
|
st.url = ''
|
|
@@ -1027,11 +1352,14 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1027
1352
|
/** 预览服务器报告某个目录里有文件改了:用到这个目录的会话都 rev+1(files:改了哪些,远程看的右侧栏按它决定哪几屏重新打包) */
|
|
1028
1353
|
function changed(root, files) {
|
|
1029
1354
|
for (const [id, st] of states) {
|
|
1030
|
-
if (st.target && st.target.kind === 'file' && st.target.root === root) {
|
|
1355
|
+
if (st.target && st.target.kind === 'file' && canonicalPath(st.target.root) === canonicalPath(root)) {
|
|
1031
1356
|
st.rev++
|
|
1032
1357
|
st.changedAt = now()
|
|
1358
|
+
if (st.turn) st.progressAt = st.changedAt
|
|
1033
1359
|
// 文件太多(预览服务器那边已经截断了)就不列:空的 = 不知道改了啥,右侧栏整屏刷新
|
|
1034
|
-
const
|
|
1360
|
+
const original = Array.isArray(files) ? files.filter(f => typeof f === 'string') : []
|
|
1361
|
+
const list = st.target.directory ? original : original.filter(key => key === path.basename(st.target.file) || !/^[^/]+\.html?$/i.test(key))
|
|
1362
|
+
if (original.length && !list.length) { st.rev--; continue }
|
|
1035
1363
|
st.changedFiles = list.length > 50 ? [] : list
|
|
1036
1364
|
// 最近几批改动(递增序号):远程看的右侧栏两次轮询之间可能来了好几批,按序号取并集,别只看最后一批
|
|
1037
1365
|
st.changeN = (st.changeN || 0) + 1
|
|
@@ -1039,6 +1367,11 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1039
1367
|
const had = new Set(st.screens) // 这一批之前画布上有哪几屏(下面认「原版是不是这一批刚改名出来的」)
|
|
1040
1368
|
const before = st.screens.join('\n')
|
|
1041
1369
|
refreshScreens(st)
|
|
1370
|
+
if (st.target.directory && !st.target.file && st.screens.length) {
|
|
1371
|
+
st.target = { ...st.target, file: path.join(st.target.root, st.screens[0]) }
|
|
1372
|
+
st.url = urlFor(st.target, st.origin)
|
|
1373
|
+
st.label = labelOf(st.target)
|
|
1374
|
+
}
|
|
1042
1375
|
if (st.screens.join('\n') !== before) persist(id, st)
|
|
1043
1376
|
// 正开着的那个方向被挪走了(「用这版」:home-a 挪进 drafts、选中的改名成 home):同名的原版已经在了就换过去,
|
|
1044
1377
|
// 别在画布上留一格「这一屏打不开」等模型下回预览
|
|
@@ -1046,7 +1379,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1046
1379
|
// 或者原版是这一批刚出现的(选中的就是开着的这个、直接改名成原版)。
|
|
1047
1380
|
// 用户自己把 guide-a 改成别的名字、顺手改了早就在的 guide.html,或者 drafts/ 里有上一回的同名旧稿时,都别跳。
|
|
1048
1381
|
// 这一批改了哪些不知道(太多、列表空的)就不换:留着出错卡,用户点一下重试 / 让模型改
|
|
1049
|
-
const v = list.length && !fs.existsSync(st.target.file) && /^(.+)-[a-z](\.html?)$/i.exec(path.basename(st.target.file))
|
|
1382
|
+
const v = st.target.directory && list.length && !fs.existsSync(st.target.file) && /^(.+)-[a-z](\.html?)$/i.exec(path.basename(st.target.file))
|
|
1050
1383
|
const dir = v ? path.dirname(st.target.file) : ''
|
|
1051
1384
|
const base = v && path.join(dir, v[1] + v[2])
|
|
1052
1385
|
if (base && fs.existsSync(base)) {
|
|
@@ -1060,7 +1393,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1060
1393
|
// 只算画布认的屏(和 allScreens 同一套筛法):模型顺手写的 _probe.html、隐藏文件不算
|
|
1061
1394
|
const renamed = allScreens(dir).some((n) => n !== path.basename(base) && !had.has(rel(path.join(dir, n))) && list.includes(rel(path.join(dir, n))))
|
|
1062
1395
|
const fresh = list.includes(rel(base)) && (!had.has(rel(base)) || list.some((f) => f.startsWith(draftsRel) && fs.existsSync(path.join(root, f))))
|
|
1063
|
-
if (!renamed && (moved || fresh)) setTarget(id, {
|
|
1396
|
+
if (!renamed && (moved || fresh)) setTarget(id, { ...st.target, file: base }, { source: st.source, popup: false }).catch((e) => log(e))
|
|
1064
1397
|
}
|
|
1065
1398
|
}
|
|
1066
1399
|
}
|
|
@@ -1072,7 +1405,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1072
1405
|
|
|
1073
1406
|
const absOf = (sessionId, p) => path.resolve(cwdOf(sessionId), p.replace(/^~(?=\/|$)/, os.homedir()))
|
|
1074
1407
|
// 状态条说「正在写 x」的文件:在现在这套设计的文件夹里;还没有设计时,写什么都算(第一屏还在路上)
|
|
1075
|
-
const ownsFile = (st, abs) => !st.target || (st.target.kind === 'file' && (abs === st.target.file || abs.startsWith(st.target.root + path.sep)))
|
|
1408
|
+
const ownsFile = (st, abs) => !st.target || (st.target.kind === 'file' && (abs === st.target.file || st.target.directory && abs.startsWith(st.target.root + path.sep)))
|
|
1076
1409
|
|
|
1077
1410
|
/**
|
|
1078
1411
|
* 模型边说边推的流(DSH 的 agent/assistant-stream)。写文件时参数要流好几分钟才到 tool/call,
|
|
@@ -1081,6 +1414,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1081
1414
|
function stream(sessionId, frame) {
|
|
1082
1415
|
const st = sessionId && frame ? states.get(sessionId) : null
|
|
1083
1416
|
if (!st || !st.turn) return
|
|
1417
|
+
if (frame.type === 'chunk' || frame.type === 'start' || frame.type === 'end') st.progressAt = now()
|
|
1084
1418
|
if (frame.type === 'start' || frame.type === 'end') {
|
|
1085
1419
|
// 这一次说完了:没写完的页面收尾(在看的 iframe 停在写到的地方)
|
|
1086
1420
|
if (st.parts) for (const part of st.parts.values()) if (part.draft && drafts) drafts.end(part.draft, part.did)
|
|
@@ -1209,6 +1543,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1209
1543
|
part.draft = serve
|
|
1210
1544
|
part.prov = known ? '' : root // 挂在临时名字上的:记着它属于哪个文件夹,名字到了自己核对(不管这时右侧栏在看哪份)
|
|
1211
1545
|
draft = { file: known ? part.abs : '', serve, root, id: drafts.begin(serve), origin: st.target ? st.origin : '' }
|
|
1546
|
+
if (!st.target) draft.accent = designAccent(root, readDesignManifest(root))
|
|
1212
1547
|
part.did = draft.id // 草稿编号:之后推、收尾、作废都核对它(同一个文件又开始重写时,旧的不碰新的)
|
|
1213
1548
|
st.draft = draft
|
|
1214
1549
|
}
|
|
@@ -1244,11 +1579,23 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1244
1579
|
if (userLoadedSkill(d)) st.design = true
|
|
1245
1580
|
break
|
|
1246
1581
|
}
|
|
1582
|
+
case 'assistant/message': {
|
|
1583
|
+
if (!live || !st.turn) break
|
|
1584
|
+
const blocks = d.message?.content
|
|
1585
|
+
if (Array.isArray(blocks)) {
|
|
1586
|
+
const text = blocks.filter(b => b?.type === 'text').map(b => b.text).join('').trimEnd()
|
|
1587
|
+
st.textQuestion = !blocks.some(b => b?.type === 'tool-call') && /[??][”"’'))]*$/.test(text)
|
|
1588
|
+
st.progressAt = now()
|
|
1589
|
+
}
|
|
1590
|
+
break
|
|
1591
|
+
}
|
|
1247
1592
|
case 'turn/start':
|
|
1248
1593
|
if (live) {
|
|
1594
|
+
st.textQuestion = false
|
|
1249
1595
|
st.turn = true
|
|
1596
|
+
st.waitingAccent = ''
|
|
1250
1597
|
st.end = ''
|
|
1251
|
-
st.turnAt = now() // 右侧栏的状态条从这里开始计时
|
|
1598
|
+
st.progressAt = st.turnAt = now() // 右侧栏的状态条从这里开始计时
|
|
1252
1599
|
st.tool = ''
|
|
1253
1600
|
keepVersion(st, '')
|
|
1254
1601
|
}
|
|
@@ -1274,6 +1621,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1274
1621
|
st.ask = '' // 用过就清:下一轮不是用户发起的(没有新的一句话)就不借这一句当名字
|
|
1275
1622
|
break
|
|
1276
1623
|
case 'tool/call': {
|
|
1624
|
+
if (live) st.progressAt = now()
|
|
1277
1625
|
// 加载了设计技能 / 调了预览工具:这个会话在做设计(重放历史时也认,DSH 重启后不丢)
|
|
1278
1626
|
if (d.name === 'skill' && argsOf(d.arguments).name === DESIGN_SKILL) st.design = true
|
|
1279
1627
|
if (d.name === 'preview_page') st.design = true
|
|
@@ -1298,6 +1646,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1298
1646
|
break
|
|
1299
1647
|
}
|
|
1300
1648
|
case 'tool/result': {
|
|
1649
|
+
if (live && st.turn) st.progressAt = now()
|
|
1301
1650
|
if (d.meta && typeof d.meta.cwd === 'string' && d.meta.cwd) {
|
|
1302
1651
|
cwds.set(sessionId, d.meta.cwd)
|
|
1303
1652
|
if (st.target && saved[sessionId] && saved[sessionId].cwd !== d.meta.cwd) persist(sessionId, st)
|
|
@@ -1311,6 +1660,27 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1311
1660
|
const callId = (d.message && (d.message.toolCallId || (d.message.source && d.message.source.callId))) || d.callId || ''
|
|
1312
1661
|
const call = callId ? st.calls.get(callId) : null
|
|
1313
1662
|
if (callId) st.calls.delete(callId)
|
|
1663
|
+
if (!st.target && st.turn && call && !d.message?.isError) {
|
|
1664
|
+
const written = writtenPath(call.name, call.args)
|
|
1665
|
+
if (written && /^(tokens\.css|design\.json)$/.test(path.basename(written))) {
|
|
1666
|
+
const root = path.dirname(absOf(sessionId, written))
|
|
1667
|
+
st.waitingAccent = designAccent(root, readDesignManifest(root))
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
if (call && !d.message?.isError && st.target?.directory) {
|
|
1671
|
+
const written = writtenPath(call.name, call.args)
|
|
1672
|
+
const abs = written && absOf(sessionId, written)
|
|
1673
|
+
if (abs) {
|
|
1674
|
+
const key = path.relative(canonicalPath(st.target.root), path.join(canonicalPath(path.dirname(abs)), path.basename(abs))).split(path.sep).join('/')
|
|
1675
|
+
if (key && !key.startsWith('../')) {
|
|
1676
|
+
if (!key.includes('/') && HTML_EXT.test(key)) st.writtenPages?.add(key)
|
|
1677
|
+
else st.writtenAssets?.add(key)
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
if (call?.name === 'read_design_changes' && !d.message?.isError && !d.cancelled && !d.message?.cancelled) {
|
|
1682
|
+
confirmRead(sessionId, call.args, d.message?.content)
|
|
1683
|
+
}
|
|
1314
1684
|
if (!call || call.name === ASK_TOOL) st.asking = false
|
|
1315
1685
|
if (pending && fs.existsSync(pending) && (!st.target || st.source === 'auto') && !(st.target && st.target.file === pending)) {
|
|
1316
1686
|
// 只有在做设计(加载了设计技能、或页面写了设计类型标记)才自动打开;别的任务写的网页只记下来,不弹
|
|
@@ -1353,30 +1723,36 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1353
1723
|
}
|
|
1354
1724
|
|
|
1355
1725
|
/** 本地文件预览:存一版(和上一版一样就不存);存了就让右侧栏刷新版本列表 */
|
|
1356
|
-
function keepVersion(st, label, by = '') {
|
|
1726
|
+
function keepVersion(st, label, by = '', id = [...states].find(([, value]) => value === st)?.[0]) {
|
|
1357
1727
|
if (!history || !st.target || st.target.kind !== 'file') return null
|
|
1358
|
-
const was = history.skipped ? history.skipped(st.target
|
|
1359
|
-
|
|
1360
|
-
|
|
1728
|
+
const was = history.skipped ? history.skipped(st.target) : null
|
|
1729
|
+
let v = null
|
|
1730
|
+
try { v = history.snapshot(st.target, label, by, metadataFor(id, st)) } catch (e) { log(e) }
|
|
1731
|
+
const now = history.skipped ? history.skipped(st.target) : null
|
|
1361
1732
|
if (v || !was !== !now) st.vrev++ // 存上了、刚变成没存成、或没存成的提示该收起:都重拉
|
|
1362
1733
|
return v
|
|
1363
1734
|
}
|
|
1364
1735
|
|
|
1365
1736
|
/** 预览里直接改字:在这一屏(key = 文件名)的 HTML 里把第 nth 处 before 换成 after,改前改后各存一版 */
|
|
1366
|
-
function editText(id, { key, before, after, nth = 0, sig = '', raw = '' } = {}) {
|
|
1737
|
+
function editText(id, { target, targetKey = target, requestId, key, before, after, nth = 0, sig = '', raw = '' } = {}) {
|
|
1738
|
+
if (targetKey !== undefined) {
|
|
1739
|
+
const active = states.get(id)?.target
|
|
1740
|
+
if (!active || active.kind !== 'file' || !accepts(active, targetKey)) return { ok: false, reason: 'moved' }
|
|
1741
|
+
if (!key || !/^[a-f0-9]{16}$/.test(sig)) return { ok: false, reason: 'changed' }
|
|
1742
|
+
}
|
|
1367
1743
|
const short = String(after).replace(/\s+/g, ' ').trim()
|
|
1368
1744
|
// sig:撤销时带上改完那一刻文件的样子;之后文件又被别处改过(编辑器、模型)就不撤,免得按旧的「第几处」换错地方
|
|
1369
1745
|
return rewrite(id, key, (html) => (sig && sigOf(html) !== String(sig) ? { ok: false, reason: 'changed' } : replaceText(html, before, after, Math.max(0, Math.floor(Number(nth) || 0)), typeof raw === 'string' ? raw : '')),
|
|
1370
1746
|
`改字「${short.length > 16 ? short.slice(0, 16) + '…' : short}」`,
|
|
1371
|
-
{ kind: 'text', before: String(before).replace(/\s+/g, ' ').trim().slice(0, 60), after: short.slice(0, 60) })
|
|
1747
|
+
{ kind: 'text', before: String(before).replace(/\s+/g, ' ').trim().slice(0, 60), after: short.slice(0, 60) }, requestId)
|
|
1372
1748
|
}
|
|
1373
1749
|
|
|
1374
1750
|
/** 预览里调样式:把 css 写进这一屏(key)里那个元素(loc,见 findTag)的 style 属性,改前改后各存一版 */
|
|
1375
|
-
function editStyle(id, { key, loc, css, name, imp } = {}) {
|
|
1751
|
+
function editStyle(id, { key, loc, css, name, imp, requestId } = {}) {
|
|
1376
1752
|
const short = String(name || (loc && loc.tag) || '').trim()
|
|
1377
1753
|
const clean = cleanCss(css)
|
|
1378
|
-
return rewrite(id, key, (html) => setStyle(html, loc || {}, css, imp), `调样式「${short
|
|
1379
|
-
{ kind: 'style', name: short, css: clean || {}, inline: true })
|
|
1754
|
+
return rewrite(id, key, (html) => loc?.sig && sigOf(html) !== loc.sig ? { ok: false, reason: 'changed' } : setStyle(html, loc || {}, css, imp), `调样式「${styleElement(short)}」`,
|
|
1755
|
+
{ kind: 'style', name: short, css: clean || {}, inline: true }, requestId)
|
|
1380
1756
|
}
|
|
1381
1757
|
|
|
1382
1758
|
/**
|
|
@@ -1384,69 +1760,115 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1384
1760
|
* 这一屏(key)那个元素(loc)行内 style 里同名的几项去掉(不然盖过样式表,看着没变)。改前改后各存一版。
|
|
1385
1761
|
* cls:选择器里元素带的那个 class,数一数别的屏还有几处行内写着自己的值(之前直接保存的),告诉用户没跟着变。
|
|
1386
1762
|
*/
|
|
1387
|
-
function editRule(id, { key, loc, file, sel, n = 0, css, name, cls = '' } = {}) {
|
|
1763
|
+
function editRule(id, { key, loc, file, sel, n = 0, css, name, cls = '', requestId } = {}) {
|
|
1388
1764
|
const st = states.get(id)
|
|
1389
1765
|
const t = st && st.target
|
|
1390
1766
|
if (!t || t.kind !== 'file') return { ok: false, reason: 'not-file' }
|
|
1391
1767
|
if (busyRoot(t.root)) return { ok: false, reason: 'busy' }
|
|
1768
|
+
if (t.scope !== 'directory') return { ok: false, reason: 'scope' }
|
|
1769
|
+
const previous = transactions.cached(t, 'rule', requestId)
|
|
1770
|
+
if (previous) return resultState(id, previous)
|
|
1392
1771
|
const rootReal = fs.realpathSync(t.root)
|
|
1393
1772
|
let real = ''
|
|
1394
1773
|
try { real = fs.realpathSync(String(file || '')) } catch { real = '' }
|
|
1395
1774
|
if (!real || !real.startsWith(rootReal + path.sep) || !/\.css$/i.test(real)) return { ok: false, reason: 'no-rule' }
|
|
1396
1775
|
const stat = fs.statSync(real)
|
|
1776
|
+
if (Number.isFinite(loc?.pickedAt) && Math.floor(stat.mtimeMs) > loc.pickedAt) return { ok: false, reason: 'changed' }
|
|
1397
1777
|
if (!stat.isFile() || stat.size > 2 * 1024 * 1024) return { ok: false, reason: 'no-rule' }
|
|
1398
1778
|
const screen = String(key || path.basename(t.file))
|
|
1779
|
+
if (!scopeFor(t).writableKeys.includes(screen)) return { ok: false, reason: 'changed' }
|
|
1399
1780
|
const sfile = path.join(t.root, screen)
|
|
1400
|
-
|
|
1401
|
-
// 先核对这屏真在设计目录里(软链接指到外面的不读),再看用没用组件
|
|
1781
|
+
let source
|
|
1402
1782
|
try {
|
|
1403
|
-
const
|
|
1404
|
-
if (path.dirname(sfile)
|
|
1405
|
-
|
|
1406
|
-
|
|
1783
|
+
const screenReal = fs.realpathSync(sfile)
|
|
1784
|
+
if (path.dirname(sfile) !== t.root || !HTML_EXT.test(screen) || !screenReal.startsWith(rootReal + path.sep) || fs.statSync(screenReal).size > 8 * 1024 * 1024) return { ok: false, reason: 'changed' }
|
|
1785
|
+
source = fs.readFileSync(screenReal, 'utf8')
|
|
1786
|
+
} catch { return { ok: false, reason: 'changed' } }
|
|
1787
|
+
if (loc?.sig && sigOf(source) !== loc.sig) return { ok: false, reason: 'changed' }
|
|
1788
|
+
if (pageUsesComponents(source, dirReader(t.root))) return { ok: false, reason: 'comp' }
|
|
1789
|
+
const cssBefore = fs.readFileSync(real, 'utf8')
|
|
1790
|
+
const r = setRuleProps(cssBefore, sel, n, css)
|
|
1407
1791
|
if (!r.ok) return r
|
|
1408
1792
|
const props = Object.keys(cleanCss(css) || {})
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
const sreal = fs.realpathSync(sfile)
|
|
1413
|
-
if (path.dirname(sfile) === t.root && HTML_EXT.test(screen) && sreal.startsWith(rootReal + path.sep)) {
|
|
1414
|
-
const cur = fs.readFileSync(sfile, 'utf8')
|
|
1415
|
-
const x = clearInline(cur, loc || {}, props)
|
|
1416
|
-
if (!x.ok) return x // 行内写法拆不开:共用规则不改,调用方退回只改这一处
|
|
1417
|
-
if (x.html !== cur) html = x.html
|
|
1418
|
-
}
|
|
1419
|
-
} catch { html = null }
|
|
1420
|
-
keepVersion(st, '', 'pre')
|
|
1421
|
-
fs.writeFileSync(real, r.text)
|
|
1422
|
-
if (html != null) fs.writeFileSync(sfile, html)
|
|
1793
|
+
const cleaned = clearInline(source, loc || {}, props)
|
|
1794
|
+
if (!cleaned.ok) return cleaned
|
|
1795
|
+
const html = cleaned.html !== source ? cleaned.html : null
|
|
1423
1796
|
const rel = path.relative(rootReal, real).split(path.sep).join('/')
|
|
1424
1797
|
const short = String(name || (loc && loc.tag) || '').trim()
|
|
1425
|
-
|
|
1798
|
+
const label = `调样式「${styleElement(short)}」→ ${path.basename(rel)}`
|
|
1799
|
+
const writes = new Map([[rel, r.text], ...(html === null ? [] : [[screen, html]])])
|
|
1426
1800
|
let others = 0
|
|
1427
|
-
for (const k of
|
|
1801
|
+
for (const k of scopeFor(t).pages) {
|
|
1428
1802
|
if (k === screen) continue
|
|
1429
1803
|
try { if (inlineOverrides(fs.readFileSync(path.join(t.root, k), 'utf8'), cls, props)) others++ } catch { /* 读不了不算 */ }
|
|
1430
1804
|
}
|
|
1431
|
-
|
|
1432
|
-
|
|
1805
|
+
return writeResult(() => {
|
|
1806
|
+
keepVersion(st, '', 'pre', id)
|
|
1807
|
+
if (!history?.verifyBackup?.(t, [...writes.keys()])) return { ok: false, reason: 'backup' }
|
|
1808
|
+
const response = { sig: html === null ? loc?.sig : sigOf(html), file: rel, sel: String(sel || ''), others, imp: r.imp || [] }
|
|
1809
|
+
const expected = new Map([[rel, fingerprint(cssBefore)], ...(html === null ? [] : [[screen, fingerprint(source)]])])
|
|
1810
|
+
const result = commit(id, st, { kind: 'rule', label, pages: [screen], writes, expected, requestId, response,
|
|
1811
|
+
detail: { name: short, css: cleanCss(css) || {}, sel: String(sel || '').slice(0, 120), file: rel } })
|
|
1812
|
+
if (result.change) keepVersion(st, label, 'me', id)
|
|
1813
|
+
return resultState(id, result)
|
|
1814
|
+
})
|
|
1433
1815
|
}
|
|
1434
1816
|
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
function noteEdit(st, e) {
|
|
1440
|
-
st.edits = [...(st.edits || []), { at: now(), root: st.target && st.target.root, ...e }].slice(-20)
|
|
1817
|
+
function unreadEdits(id, target = states.get(id)?.target) {
|
|
1818
|
+
if (!target?.designId) return []
|
|
1819
|
+
const db = transactions.load(target.designId)
|
|
1820
|
+
return db.edits.filter(event => event.seq > (db.seen[id] || 0))
|
|
1441
1821
|
}
|
|
1442
1822
|
|
|
1443
|
-
|
|
1444
|
-
function
|
|
1445
|
-
const st =
|
|
1446
|
-
|
|
1447
|
-
const
|
|
1448
|
-
|
|
1449
|
-
|
|
1823
|
+
const readReceipts = new Map()
|
|
1824
|
+
function readChanges(id, { targetKey, from, limit } = {}) {
|
|
1825
|
+
const [st, target] = changeScope(id, targetKey)
|
|
1826
|
+
const entries = unreadEdits(id).map(event => ({ ...event, root: target.root }))
|
|
1827
|
+
const batch = entries.filter(event => !from || event.seq >= from).slice(0, Math.min(10, Math.max(1, Number(limit) || 10)))
|
|
1828
|
+
if (!batch.length) return { entries: [], more: false }
|
|
1829
|
+
const paths = [...new Set(batch.flatMap(event => event.files.filter(key => !(event.settingsFiles || ['page-settings.json']).includes(key))))]
|
|
1830
|
+
let total = 0
|
|
1831
|
+
const fileRows = {}
|
|
1832
|
+
let completeThrough = batch.at(-1).seq
|
|
1833
|
+
for (const key of paths) {
|
|
1834
|
+
try {
|
|
1835
|
+
const item = readItem(target.root, key)
|
|
1836
|
+
const size = item.data?.length || 0
|
|
1837
|
+
const text = item.data?.toString('utf8') ?? null
|
|
1838
|
+
if (size + total > 3 * 1024 * 1024) throw Error()
|
|
1839
|
+
const isText = text === null || Buffer.from(text).equals(item.data)
|
|
1840
|
+
fileRows[key] = { ...(isText ? { text } : { base64: item.data.toString('base64') }), exists: item.hash !== null, hash: item.hash }
|
|
1841
|
+
total += size
|
|
1842
|
+
} catch {
|
|
1843
|
+
fileRows[key] = { unavailable: true }
|
|
1844
|
+
completeThrough = Math.min(completeThrough, batch.find(event => event.files.includes(key)).seq - 1)
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
const receipt = crypto.randomUUID()
|
|
1848
|
+
readReceipts.set(receipt, { id, designId: target.designId, root: target.root, from: batch[0].seq, through: completeThrough, expires: now() + 120000 })
|
|
1849
|
+
if (readReceipts.size > 1000) readReceipts.delete(readReceipts.keys().next().value)
|
|
1850
|
+
const db = transactions.load(target.designId)
|
|
1851
|
+
return { receipt, designId: target.designId, targetKey: target.targetKey, entries: batch, more: entries.at(-1).seq > batch.at(-1).seq,
|
|
1852
|
+
files: fileRows, settings: pageMetadata(id, st, true), screens: scopeFor(target).pages, display: db.display || {} }
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
function confirmRead(id, args, content) {
|
|
1856
|
+
const target = states.get(id)?.target
|
|
1857
|
+
if (!target || !matchesTarget(target, args.targetKey)) return
|
|
1858
|
+
const texts = textsOf(content)
|
|
1859
|
+
for (const text of texts) {
|
|
1860
|
+
let output
|
|
1861
|
+
try { output = JSON.parse(text) } catch { continue }
|
|
1862
|
+
const seen = readReceipts.get(output.receipt)
|
|
1863
|
+
if (!seen || seen.id !== id || seen.designId !== target.designId || seen.root !== target.root || now() > seen.expires) continue
|
|
1864
|
+
readReceipts.delete(output.receipt)
|
|
1865
|
+
const db = transactions.load(target.designId)
|
|
1866
|
+
const last = db.seen[id] || 0
|
|
1867
|
+
if (seen.from <= last + 1 && seen.through > last) {
|
|
1868
|
+
db.seen[id] = seen.through
|
|
1869
|
+
transactions.save(target.designId, db)
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1450
1872
|
}
|
|
1451
1873
|
|
|
1452
1874
|
/**
|
|
@@ -1454,12 +1876,15 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1454
1876
|
* 开发服务器的页面源码在项目里、不一定是这份 HTML,不在这里改(右侧栏改成让模型去改)。
|
|
1455
1877
|
* 模型正在干活时不改:它可能正整份重写这个文件,改了也会被盖掉。
|
|
1456
1878
|
*/
|
|
1457
|
-
function rewrite(id, key, fn, label, detail = null) {
|
|
1879
|
+
function rewrite(id, key, fn, label, detail = null, requestId) {
|
|
1458
1880
|
const st = states.get(id)
|
|
1459
1881
|
const t = st && st.target
|
|
1460
1882
|
if (!t || t.kind !== 'file') return { ok: false, reason: 'not-file' }
|
|
1883
|
+
const previous = transactions.cached(t, detail.kind, requestId)
|
|
1884
|
+
if (previous) return resultState(id, previous)
|
|
1461
1885
|
if (busyRoot(t.root)) return { ok: false, reason: 'busy' }
|
|
1462
1886
|
const name = String(key || path.basename(t.file))
|
|
1887
|
+
if (!scopeFor(t).writableKeys.includes(name)) return { ok: false, reason: 'no-screen' }
|
|
1463
1888
|
const file = path.join(t.root, name)
|
|
1464
1889
|
if (path.dirname(file) !== t.root || !HTML_EXT.test(name) || !fs.existsSync(file)) return { ok: false, reason: 'no-screen' }
|
|
1465
1890
|
// 软链接指到目录外的不读也不写
|
|
@@ -1468,14 +1893,18 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1468
1893
|
if (!real.startsWith(fs.realpathSync(t.root) + path.sep)) return { ok: false, reason: 'no-screen' }
|
|
1469
1894
|
const was = fs.readFileSync(file, 'utf8')
|
|
1470
1895
|
// 用了组件的屏(#30):画面上的字和元素是展开出来的,按「第几处」写回会写到页面别处,交给模型改
|
|
1471
|
-
if (pageUsesComponents(was, dirReader(t.root))) return { ok: false, reason: 'comp' }
|
|
1896
|
+
if (pageUsesComponents(was, dirReader(t.root))) return { ok: false, reason: 'comp', sig: sigOf(was) }
|
|
1472
1897
|
const r = fn(was)
|
|
1473
1898
|
if (!r.ok) return r
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1899
|
+
const response = { file: name, prev: sigOf(was), sig: sigOf(r.html), ...(typeof r.nth === 'number' ? { nth: r.nth } : {}), ...(typeof r.orig === 'string' ? { orig: r.orig } : {}) }
|
|
1900
|
+
if (was === r.html) return { ok: true, ...response }
|
|
1901
|
+
return writeResult(() => {
|
|
1902
|
+
keepVersion(st, '', 'pre', id)
|
|
1903
|
+
if ((detail?.kind === 'style' || history?.verifyBackup) && !history?.verifyBackup?.(t, [name])) return { ok: false, reason: 'backup' }
|
|
1904
|
+
const result = commit(id, st, { kind: detail.kind, label, pages: [name], detail, writes: new Map([[name, r.html]]), expected: new Map([[name, fingerprint(was)]]), requestId, response })
|
|
1905
|
+
if (result.change) keepVersion(st, label, 'me', id)
|
|
1906
|
+
return resultState(id, result)
|
|
1907
|
+
})
|
|
1479
1908
|
}
|
|
1480
1909
|
|
|
1481
1910
|
/** 这个目录有没有会话的模型正在干活(它可能正整份重写文件,这时改了会被盖掉);经软链接打开的同一个目录也算 */
|
|
@@ -1490,21 +1919,40 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1490
1919
|
* 改设计目录里的几个文件(调节滑块写回:tokens.css、每屏 <html> 上的属性、tweaks.json):fn(目录) → { ok, files, … };
|
|
1491
1920
|
* 改前改后各存一版。开发服务器的页面、模型正在干活时不改;给了 expectRoot 而现在看的不是它也不改
|
|
1492
1921
|
*/
|
|
1493
|
-
function editDir(id, fn, label, expectRoot) {
|
|
1922
|
+
function editDir(id, fn, label, expectRoot, expectedRev, { targetKey, requestId, effect } = {}) {
|
|
1494
1923
|
const st = states.get(id)
|
|
1495
|
-
const t = st
|
|
1924
|
+
const t = st?.target
|
|
1496
1925
|
if (!t || t.kind !== 'file') return { ok: false, reason: 'not-file' }
|
|
1497
|
-
|
|
1498
|
-
if (
|
|
1926
|
+
if (expectRoot !== undefined && (expectRoot || !targetKey) && (!expectRoot || canonicalPath(expectRoot) !== canonicalPath(t.root)) || targetKey && !accepts(t, targetKey)) return { ok: false, reason: 'moved' }
|
|
1927
|
+
if (!t.directory) return { ok: false, reason: 'scope' }
|
|
1928
|
+
const previous = transactions.cached(t, 'dir', requestId)
|
|
1929
|
+
if (previous) return resultState(id, previous)
|
|
1930
|
+
if (expectedRev !== undefined && expectedRev !== st.rev) return { ok: false, reason: 'changed' }
|
|
1499
1931
|
if (busyRoot(t.root)) return { ok: false, reason: 'busy' }
|
|
1500
|
-
|
|
1501
|
-
const
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1932
|
+
const writes = new Map()
|
|
1933
|
+
const expected = new Map()
|
|
1934
|
+
keepVersion(st, '', 'pre', id)
|
|
1935
|
+
const remember = key => { if (!expected.has(key)) expected.set(key, readItem(t.root, key).hash) }
|
|
1936
|
+
const planning = {
|
|
1937
|
+
root: t.root,
|
|
1938
|
+
verify: files => {
|
|
1939
|
+
if (!history?.verifyBackup?.(t, files)) return false
|
|
1940
|
+
for (const key of files) remember(key)
|
|
1941
|
+
return true
|
|
1942
|
+
},
|
|
1943
|
+
put: (key, value) => { remember(key); writes.set(key, value) },
|
|
1944
|
+
read: key => writes.has(key) ? writes.get(key) : readItem(t.root, key).data,
|
|
1506
1945
|
}
|
|
1507
|
-
|
|
1946
|
+
const r = designWriteScope.run(planning, () => fn(t.root))
|
|
1947
|
+
if (!r?.ok || !writes.size) return r
|
|
1948
|
+
const name = typeof label === 'function' ? label(r) : label
|
|
1949
|
+
const pages = scopeFor(t).pages.filter(key => writes.has(key))
|
|
1950
|
+
const result = commit(id, st, { kind: 'dir', label: String(name || ''), pages, writes, expected, requestId, response: r })
|
|
1951
|
+
if (result.change) {
|
|
1952
|
+
effect?.(t.root)
|
|
1953
|
+
keepVersion(st, name, 'me', id)
|
|
1954
|
+
}
|
|
1955
|
+
return resultState(id, result)
|
|
1508
1956
|
}
|
|
1509
1957
|
|
|
1510
1958
|
/** 这套设计的模拟数据:{ fp, err },没有 mock.json 给 null */
|
|
@@ -1516,27 +1964,198 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1516
1964
|
function versions(id) {
|
|
1517
1965
|
const st = states.get(id)
|
|
1518
1966
|
if (!history || !st || !st.target || st.target.kind !== 'file') return []
|
|
1519
|
-
return history.list(st.target
|
|
1967
|
+
return history.list(st.target)
|
|
1520
1968
|
}
|
|
1521
1969
|
/** 最近一次版本没存成的原因(目录太大);没有给 null */
|
|
1522
1970
|
function versionSkip(id) {
|
|
1523
1971
|
const st = states.get(id)
|
|
1524
1972
|
if (!history || !history.skipped || !st || !st.target || st.target.kind !== 'file') return null
|
|
1525
|
-
return history.skipped(st.target
|
|
1973
|
+
return history.skipped(st.target)
|
|
1526
1974
|
}
|
|
1527
1975
|
|
|
1528
1976
|
/** 回到某一版:现在的先存一版,再写回那一版的文件(目录监听会让预览自己刷新) */
|
|
1529
1977
|
function restoreVersion(id, n, want = {}) {
|
|
1530
|
-
const st =
|
|
1531
|
-
if (!history ||
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
if (
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
if (
|
|
1539
|
-
|
|
1978
|
+
const [st, t] = changeScope(id, want.targetKey)
|
|
1979
|
+
if (!history || t.kind !== 'file') throw studioError('scope', '这个预览没有版本记录')
|
|
1980
|
+
if (want.root && canonicalPath(want.root) !== canonicalPath(t.root)) throw studioError('moved', '已经换了项目')
|
|
1981
|
+
if (want.targetKey && (!Number.isFinite(Number(want.at)) || !Number(want.at))) throw studioError('gone', '缺少版本时间')
|
|
1982
|
+
const cached = want.op !== 'plan' && transactions.cached(t, 'restore', want.requestId)
|
|
1983
|
+
if (cached) return resultState(id, cached)
|
|
1984
|
+
if (busyRoot(t.root)) throw studioError('busy', '模型正在写这个设计,请稍后还原')
|
|
1985
|
+
const version = history.find(t, n, want.at || undefined)
|
|
1986
|
+
if (!version) throw studioError('gone', '这一版已经不在了')
|
|
1987
|
+
const scope = metadataFor(id, st)
|
|
1988
|
+
const plan = history.plan(t, version, scope)
|
|
1989
|
+
const db = transactions.load(t.designId)
|
|
1990
|
+
const metadata = { display: plan.display }
|
|
1991
|
+
const focus = path.basename(t.file || '')
|
|
1992
|
+
const fallback = !plan.screens.includes(focus) ? plan.screens[0] || '' : focus
|
|
1993
|
+
if (!t.directory) metadata.settings = plan.settings
|
|
1994
|
+
if (t.directory && JSON.stringify(scope.pages) !== JSON.stringify(plan.screens)) metadata.screenOrder = plan.screens
|
|
1995
|
+
const signature = fingerprint(JSON.stringify([t.designId, canonicalPath(t.root), version.n, version.at, scope.pages, scope.owned,
|
|
1996
|
+
scope.settings, db.display, scope.pages.map(key => [key, readItem(t.root, key).hash]), plan.hashes, plan.skipped, plan.missing]))
|
|
1997
|
+
if (want.op === 'plan') {
|
|
1998
|
+
const planId = crypto.randomUUID()
|
|
1999
|
+
restorePlans.set(planId, { id, signature, expires: now() + 300000 })
|
|
2000
|
+
if (restorePlans.size > 200) restorePlans.delete(restorePlans.keys().next().value)
|
|
2001
|
+
const { overwrite, add, archive } = plan
|
|
2002
|
+
return { ok: true, planId, overwrite, add, archive, settingsFiles: plan.settingsFiles, skipped: plan.skipped, missing: plan.missing, screens: plan.screens,
|
|
2003
|
+
displayChanged: JSON.stringify(db.display ?? null) !== JSON.stringify(plan.display),
|
|
2004
|
+
settingsChanged: !t.directory && JSON.stringify(db.settings ?? null) !== JSON.stringify(plan.settings) }
|
|
2005
|
+
}
|
|
2006
|
+
if (want.targetKey || want.planId) {
|
|
2007
|
+
const approved = restorePlans.get(want.planId)
|
|
2008
|
+
if (!approved || approved.id !== id || approved.signature !== signature || now() > approved.expires) throw studioError('changed', '还原范围已更新,请重新预览')
|
|
2009
|
+
}
|
|
2010
|
+
let saved
|
|
2011
|
+
try {
|
|
2012
|
+
saved = history.take(t, '回退前', true, '', scope)
|
|
2013
|
+
const originals = [...plan.writes.keys()].filter(key => readItem(t.root, key).data !== null)
|
|
2014
|
+
if (!history.verifyBackup(t, originals)) throw Error('备份校验失败')
|
|
2015
|
+
} catch (e) { throw studioError('backup', '还原前无法存档:' + e.message) }
|
|
2016
|
+
const hashes = history.versionHtmlHashes(t, version)
|
|
2017
|
+
if (!plan.writes.size && Object.entries(metadata).every(([key, value]) => JSON.stringify(db[key] ?? null) === JSON.stringify(value))) {
|
|
2018
|
+
beforeRestore(t.root, hashes)
|
|
2019
|
+
return { ok: true, restored: 0, skipped: plan.skipped, missing: plan.missing, saved }
|
|
2020
|
+
}
|
|
2021
|
+
const result = commit(id, st, { kind: 'restore', label: `回到第 ${n} 版`, pages: plan.screens, writes: plan.writes, settingsFiles: plan.settingsFiles, expected: new Map(plan.hashes.map(([key, before]) => [key, before])), metadata,
|
|
2022
|
+
beforeOrder: scope.pages, detail: { n, count: plan.writes.size }, focus: { before: focus, after: fallback }, response: { restored: plan.writes.size, skipped: plan.skipped, missing: plan.missing, saved }, requestId: want.requestId,
|
|
2023
|
+
beforeWrite: () => beforeRestore(t.root, hashes) })
|
|
2024
|
+
if (result.change) keepVersion(st, `回到第 ${n} 版`, 'me', id)
|
|
2025
|
+
return resultState(id, result)
|
|
2026
|
+
}
|
|
2027
|
+
|
|
2028
|
+
function replay(id, body) {
|
|
2029
|
+
return writeResult(() => {
|
|
2030
|
+
const [st, t] = changeScope(id, body.targetKey || '')
|
|
2031
|
+
const cached = transactions.cached(t, 'replay', body.requestId)
|
|
2032
|
+
if (cached) return resultState(id, cached)
|
|
2033
|
+
if (t.kind === 'file' && busyRoot(t.root)) throw studioError('busy', '模型正在写这个设计')
|
|
2034
|
+
if (!['undo', 'redo'].includes(body.direction)) throw studioError('scope', '无效的重放方向')
|
|
2035
|
+
const result = transactions.replay(t, { ...body, rev: st.rev, beforeWrite: writes => t.kind === 'file' ?
|
|
2036
|
+
beforeRestore(t.root, [...writes].filter(([key, value]) => value && HTML_EXT.test(key)).map(([, value]) => fingerprint(value.data || value))) : undefined })
|
|
2037
|
+
updateFocus(st, result.focus)
|
|
2038
|
+
publishChange(st, result)
|
|
2039
|
+
if (result.change && result.change.kind !== 'layout') keepVersion(st, (body.direction === 'undo' ? '撤销:' : '重做:') + result.change.label, 'me', id)
|
|
2040
|
+
return resultState(id, result)
|
|
2041
|
+
})
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
function position(value) {
|
|
2045
|
+
if (!value || !Number.isFinite(value.x) || !Number.isFinite(value.y) || Math.abs(value.x) > 1000000 || Math.abs(value.y) > 1000000) throw studioError('scope', '无效的屏幕位置')
|
|
2046
|
+
return { x: value.x, y: value.y }
|
|
2047
|
+
}
|
|
2048
|
+
|
|
2049
|
+
function layout(id, body) {
|
|
2050
|
+
return writeResult(() => {
|
|
2051
|
+
const [st, t] = changeScope(id, body.targetKey || '')
|
|
2052
|
+
const cached = transactions.cached(t, 'layout', body.requestId)
|
|
2053
|
+
if (cached) return resultState(id, cached)
|
|
2054
|
+
if (body.version || t.scope === 'proxy' || t.kind !== 'file') throw studioError('scope', '这份排布只读')
|
|
2055
|
+
const db = transactions.load(t.designId)
|
|
2056
|
+
if (body.expectedLayoutRev !== db.layoutRev) throw studioError('changed', '画布排布已更新')
|
|
2057
|
+
const accepted = scopeFor(t).pages
|
|
2058
|
+
const positions = { ...db.positions }
|
|
2059
|
+
const pages = Object.keys(body.positions || {})
|
|
2060
|
+
for (const key of pages) {
|
|
2061
|
+
if (!accepted.includes(key)) throw studioError('scope', '找不到这一屏:' + key)
|
|
2062
|
+
if (body.positions[key] === null) delete positions[key]
|
|
2063
|
+
else positions[key] = position(body.positions[key])
|
|
2064
|
+
}
|
|
2065
|
+
return resultState(id, commit(id, st, { kind: 'layout', label: '移动屏幕', pages, metadata: { positions }, requestId: body.requestId }, { version: false }))
|
|
2066
|
+
})
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2069
|
+
function screenop(id, body) {
|
|
2070
|
+
return writeResult(() => {
|
|
2071
|
+
const [st, t] = changeScope(id, body.targetKey || '')
|
|
2072
|
+
const operation = 'screen-' + body.op
|
|
2073
|
+
const cached = transactions.cached(t, operation, body.requestId)
|
|
2074
|
+
if (cached) return resultState(id, cached)
|
|
2075
|
+
if (body.version || body.v || t.kind !== 'file' || !['copy', 'paste', 'remove'].includes(body.op)) throw studioError('scope', '这一屏只读')
|
|
2076
|
+
if (body.expectedRev !== st.rev) throw studioError('changed', '设计已更新')
|
|
2077
|
+
const scope = metadataFor(id, st)
|
|
2078
|
+
const keys = Array.isArray(body.keys) ? [...new Set(body.keys)] : []
|
|
2079
|
+
if (keys.some(key => !scope.pages.includes(key))) throw studioError('scope', '选择中有不可用的屏')
|
|
2080
|
+
if (body.op !== 'paste' && !keys.length) throw studioError('scope', '请先选择屏')
|
|
2081
|
+
const db = transactions.load(t.designId)
|
|
2082
|
+
if (body.op === 'copy') {
|
|
2083
|
+
const clipId = crypto.randomUUID()
|
|
2084
|
+
const rows = scope.pages.filter(key => keys.includes(key)).map(key => ({ key, hash: readItem(t.root, key).hash, position: db.positions[key] }))
|
|
2085
|
+
clips.set(clipId, { designId: t.designId, rows, expires: now() + 30 * 60 * 1000 })
|
|
2086
|
+
if (clips.size > 200) clips.delete(clips.keys().next().value)
|
|
2087
|
+
return { ok: true, clipId, keys: rows.map(row => row.key), designId: t.designId }
|
|
2088
|
+
}
|
|
2089
|
+
if (!t.directory) throw studioError('scope', '请先打开设计文件夹')
|
|
2090
|
+
if (busyRoot(t.root)) throw studioError('busy', '模型正在写这个设计')
|
|
2091
|
+
const settings = { ...scope.settings, screens: { ...scope.settings.screens } }
|
|
2092
|
+
const positions = { ...db.positions }
|
|
2093
|
+
const writes = new Map()
|
|
2094
|
+
const expected = new Map()
|
|
2095
|
+
const newKeys = []
|
|
2096
|
+
if (body.op === 'remove') {
|
|
2097
|
+
for (const key of keys) {
|
|
2098
|
+
if (!scope.owned.includes(key)) throw studioError('scope', '无法确认文件归属:' + key)
|
|
2099
|
+
const original = readItem(t.root, key)
|
|
2100
|
+
if (!original.data) throw studioError('changed', key + ' 已移除')
|
|
2101
|
+
expected.set(key, original.hash)
|
|
2102
|
+
writes.set(key, null)
|
|
2103
|
+
delete settings.screens[key]
|
|
2104
|
+
delete positions[key]
|
|
2105
|
+
}
|
|
2106
|
+
} else {
|
|
2107
|
+
const clip = clips.get(body.clipId)
|
|
2108
|
+
if (!clip || clip.designId !== t.designId || clip.expires < now()) throw studioError('gone', '剪贴板里的屏已失效')
|
|
2109
|
+
for (const row of clip.rows) {
|
|
2110
|
+
const source = readItem(t.root, row.key)
|
|
2111
|
+
if (source.hash !== row.hash || !source.data) throw studioError('changed', row.key + ' 已更新')
|
|
2112
|
+
const ext = path.extname(row.key)
|
|
2113
|
+
const name = row.key.slice(0, -ext.length)
|
|
2114
|
+
let num = 1
|
|
2115
|
+
let key
|
|
2116
|
+
do { key = name + '-copy' + (num === 1 ? '' : '-' + num) + ext; num++ }
|
|
2117
|
+
while (writes.has(key) || fs.lstatSync(path.join(t.root, key), { throwIfNoEntry: false }))
|
|
2118
|
+
expected.set(key, null)
|
|
2119
|
+
writes.set(key, { data: source.data, mode: source.mode })
|
|
2120
|
+
if (settings.screens[row.key]) settings.screens[key] = settings.screens[row.key]
|
|
2121
|
+
if (row.position) positions[key] = { x: row.position.x + 32, y: row.position.y + 32 }
|
|
2122
|
+
newKeys.push(key)
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
const settingsFiles = []
|
|
2126
|
+
if (JSON.stringify(settings.screens) !== JSON.stringify(scope.settings.screens || {})) {
|
|
2127
|
+
writes.set(scope.settingsFile, pageSettingsBytes(settings))
|
|
2128
|
+
settingsFiles.push(scope.settingsFile)
|
|
2129
|
+
}
|
|
2130
|
+
const screenOrder = [...scope.pages.filter(key => writes.get(key) !== null), ...newKeys]
|
|
2131
|
+
const owned = [...new Set([...(db.owned || []), ...scope.owned, ...newKeys])]
|
|
2132
|
+
keepVersion(st, '', 'pre', id)
|
|
2133
|
+
const originals = [...writes.keys()].filter(key => readItem(t.root, key).data !== null)
|
|
2134
|
+
if (!history?.verifyBackup?.(t, originals)) throw studioError('backup', '屏文件备份校验失败')
|
|
2135
|
+
const oldFocus = path.basename(t.file || '')
|
|
2136
|
+
const nextFocus = screenOrder.includes(oldFocus) ? oldFocus : screenOrder[0] || ''
|
|
2137
|
+
const change = commit(id, st, { kind: operation, label: newKeys.length ? '粘贴屏幕' : '移除屏幕', pages: newKeys.length ? newKeys : keys,
|
|
2138
|
+
writes, settingsFiles, expected, beforeOrder: scope.pages, metadata: { screenOrder, owned, positions }, focus: { before: oldFocus, after: nextFocus }, requestId: body.requestId, response: { newKeys } })
|
|
2139
|
+
if (change.change) keepVersion(st, change.change.label, 'me', id)
|
|
2140
|
+
return resultState(id, change)
|
|
2141
|
+
})
|
|
2142
|
+
}
|
|
2143
|
+
|
|
2144
|
+
async function relocate(moved, location) {
|
|
2145
|
+
if (moved.file) transactions.relocateFile(moved.designId, path.basename(location || ''), path.basename(moved.file))
|
|
2146
|
+
for (const [id, rec] of Object.entries(saved)) {
|
|
2147
|
+
if (rec.target?.designId !== moved.designId && !moved.aliases?.includes(rec.target?.directory ? rec.target.root : rec.target?.file)) continue
|
|
2148
|
+
const target = resolveDesign(rec.target, { restore: true })
|
|
2149
|
+
if (!target) continue
|
|
2150
|
+
saved[id] = { ...rec, target }
|
|
2151
|
+
const st = states.get(id)
|
|
2152
|
+
if (st?.target?.designId === moved.designId) {
|
|
2153
|
+
await setTarget(id, target, { source: st.source, popup: false, restore: true })
|
|
2154
|
+
st.rev++
|
|
2155
|
+
st.vrev++
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
if (store) store.save(saved)
|
|
1540
2159
|
}
|
|
1541
2160
|
|
|
1542
2161
|
/** 正在写的那页:预览服务器上的草稿地址 + 它在设计里的名字(和 screens 的 key 一样) */
|
|
@@ -1556,26 +2175,36 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1556
2175
|
const mt = rec && /<meta\b[^>]*\bname\s*=\s*["']?dsh-design\b[^>]*>/i.exec(rec.text.slice(0, 6000))
|
|
1557
2176
|
const mc = mt && /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(mt[0])
|
|
1558
2177
|
// lump:写完了、而且是整段一下子到的(右侧栏放完这份再换真文件;一路流着写的落地就换)
|
|
1559
|
-
return { key: d.file ? relOf(d.file) : '', url: `${d.origin}/${sv.split('/').map(encodeURIComponent).join('/')}?__ddp_draft=${d.id}`, live, lump: !!(live && rec.done && rec.lump), meta: mc ? (mc[1] ?? mc[2] ?? '').slice(0, 80) : '' }
|
|
2178
|
+
return { ...(d.accent ? { accent: d.accent } : {}), key: d.file ? relOf(d.file) : '', url: `${d.origin}/${sv.split('/').map(encodeURIComponent).join('/')}?__ddp_draft=${d.id}`, live, lump: !!(live && rec.done && rec.lump), meta: mc ? (mc[1] ?? mc[2] ?? '').slice(0, 80) : '' }
|
|
1560
2179
|
}
|
|
1561
2180
|
|
|
1562
2181
|
function snapshot(id) {
|
|
1563
2182
|
const st = states.get(id)
|
|
1564
2183
|
if (!(st && st.target)) restore(id)
|
|
1565
2184
|
else if (st.origin && !alive(st.origin)) revive(id, st)
|
|
2185
|
+
const progressAt = st?.progressAt || st?.turnAt || 0
|
|
1566
2186
|
const turnFor = st && st.turn && st.turnAt ? Math.max(0, now() - st.turnAt) : 0
|
|
1567
|
-
if (!st || !st.target) return { target: null, rev: st ? st.rev : 0, openRev: st ? st.openRev : 0, turn: st ? st.turn : false, turnFor, tool: (st && st.turn && st.tool) || '', turns: st ? st.turns || 0 : 0, end: (st && st.end) || '', ho: (st && st.ho) || null, asking: !!(st && st.asking), writing: (st && st.turn && st.writing) || '', lines: (st && st.turn && st.lines) || 0, draft: draftOf(st), hint: st && st.hint && fs.existsSync(st.hint) ? st.hint : '', loading: restoring.has(id) }
|
|
2187
|
+
if (!st || !st.target) return { ...(st?.turn && st.waitingAccent && !st.draft ? { accent: st.waitingAccent } : {}), missingTarget: states.get(id)?.missingTarget || '', missingDesignId: st?.missingDesignId || '', target: null, rev: st ? st.rev : 0, openRev: st ? st.openRev : 0, turn: st ? st.turn : false, turnFor, progressAt, textQuestion: !!st?.textQuestion, tool: (st && st.turn && st.tool) || '', turns: st ? st.turns || 0 : 0, end: (st && st.end) || '', ho: (st && st.ho) || null, asking: !!(st && st.asking), writing: (st && st.turn && st.writing) || '', lines: (st && st.turn && st.lines) || 0, draft: draftOf(st), hint: st && st.hint && fs.existsSync(st.hint) ? st.hint : '', loading: restoring.has(id) }
|
|
1568
2188
|
const { target, url, label, source, rev, openRev, turn, writing, changedAt, kind, size, view, origin } = st
|
|
1569
2189
|
const file = target.kind === 'file'
|
|
2190
|
+
const db = transactions.load(target.designId)
|
|
2191
|
+
const scope = scopeFor(target)
|
|
1570
2192
|
return {
|
|
1571
|
-
|
|
2193
|
+
pageSettings: pageMetadata(id, st),
|
|
2194
|
+
designId: target.designId, targetKey: target.targetKey, scope: target.scope, legacyFitTarget: st.legacyFitTarget || undefined,
|
|
2195
|
+
layoutRev: db.layoutRev, positions: db.positions, display: db.display || {},
|
|
2196
|
+
pages: scope.pages, entry: scope.entry, assetRoot: scope.assetRoot, writableKeys: scope.writableKeys,
|
|
2197
|
+
zipPages: file && !!st.zipPages,
|
|
2198
|
+
rootBusy: file && busyRoot(target.root),
|
|
2199
|
+
...(file && st.accent ? { accent: st.accent } : {}),
|
|
2200
|
+
target: file ? { kind: 'file', file: target.file, root: target.root, designId: target.designId, targetKey: target.targetKey, scope: target.scope, ...(target.directory ? { directory: true } : {}) } : { kind: 'proxy', port: target.port, path: target.path, designId: target.designId, targetKey: target.targetKey, scope: target.scope },
|
|
1572
2201
|
url,
|
|
1573
2202
|
label,
|
|
1574
2203
|
source,
|
|
1575
2204
|
rev,
|
|
1576
2205
|
openRev,
|
|
1577
2206
|
turn,
|
|
1578
|
-
turnFor,
|
|
2207
|
+
turnFor, progressAt, textQuestion: !!st.textQuestion,
|
|
1579
2208
|
tool: (turn && st.tool) || '',
|
|
1580
2209
|
turns: st.turns || 0,
|
|
1581
2210
|
end: st.end || '',
|
|
@@ -1595,7 +2224,8 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1595
2224
|
trust: file ? trust() : '', // 「哪些算别人做的」的指纹:所有会话共用,远程看的右侧栏按它作废留着的打包结果
|
|
1596
2225
|
watch: file ? watchTag(target.root) : '', // 预览服务器有没有在监听这个目录(开始 / 停止监听就变):画布缩略图按它重新要(停了就得自己定时再要)
|
|
1597
2226
|
mock: file ? mockInfo(target.root) : null, // 模拟数据(#30):有 mock.json 才有;fp 变了右侧栏的「数据」面板重新连
|
|
1598
|
-
focus: file ? path.basename(target.file) : target.path,
|
|
2227
|
+
focus: file ? (target.file ? path.basename(target.file) : '') : target.path,
|
|
2228
|
+
missingTarget: file && !target.directory && !scope.entry ? target.file : '',
|
|
1599
2229
|
hidden: st.hidden || 0, // 超过上限收起来的屏数
|
|
1600
2230
|
maxScreens: MAX_SCREENS,
|
|
1601
2231
|
screens: st.screens.map((key) => ({
|
|
@@ -1615,7 +2245,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1615
2245
|
const t = st && st.target
|
|
1616
2246
|
if (!t || t.kind !== 'file') return [] // 不看 st.hidden:刚加的屏目录监听还没报上来时,现扫的才准
|
|
1617
2247
|
const on = new Set(st.screens)
|
|
1618
|
-
return
|
|
2248
|
+
return scopeFor(t).pages.filter((k) => !on.has(k))
|
|
1619
2249
|
}
|
|
1620
2250
|
|
|
1621
2251
|
/** handoff_design 真写好了交接包:记下是哪套设计(步骤条:这轮还在跑就是「模型在做」) */
|
|
@@ -1624,5 +2254,5 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
|
|
|
1624
2254
|
st.ho = { root: String(root || ''), at: now(), end: st.turn ? null : 'done' }
|
|
1625
2255
|
}
|
|
1626
2256
|
|
|
1627
|
-
return { observe, stream, setTarget, setView, clear, changed, snapshot, cwdOf, stateOf, versions, versionSkip, markHandoff, restoreVersion, editText, editStyle, editRule, editDir,
|
|
2257
|
+
return { scopeFor, accepts, readySnapshot, relocate, unreadEdits, readChanges, replay, layout, screenop, observe, stream, setTarget, setView, clear, changed, snapshot, cwdOf, stateOf, versions, versionSkip, markHandoff, restoreVersion, editText, editStyle, editRule, editDir, hiddenScreens, keepVersion: (id, label) => keepVersion(stateOf(id), label) }
|
|
1628
2258
|
}
|