dsh-design-studio 1.4.1 → 2.0.0

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.
Files changed (197) hide show
  1. package/README.en.md +11 -10
  2. package/README.md +17 -16
  3. package/THIRD_PARTY_NOTICES.md +108 -0
  4. package/assets/art/README.md +102 -0
  5. package/assets/art/brand-mark.webp +0 -0
  6. package/assets/art/check-clean.webp +0 -0
  7. package/assets/art/coach-markup.webp +0 -0
  8. package/assets/art/drop-file.webp +0 -0
  9. package/assets/art/empty-components.webp +0 -0
  10. package/assets/art/empty-data.webp +0 -0
  11. package/assets/art/empty-error.webp +0 -0
  12. package/assets/art/empty-frames.webp +0 -0
  13. package/assets/art/empty-history.webp +0 -0
  14. package/assets/art/empty-market.webp +0 -0
  15. package/assets/art/empty-notes.webp +0 -0
  16. package/assets/art/empty-search.webp +0 -0
  17. package/assets/art/empty-tokens.webp +0 -0
  18. package/assets/art/empty-works.webp +0 -0
  19. package/assets/art/guide-icon.webp +0 -0
  20. package/assets/art/kind-app.webp +0 -0
  21. package/assets/art/kind-desktop.webp +0 -0
  22. package/assets/art/kind-diagram.webp +0 -0
  23. package/assets/art/kind-dshplugin.webp +0 -0
  24. package/assets/art/kind-email.webp +0 -0
  25. package/assets/art/kind-embedded.webp +0 -0
  26. package/assets/art/kind-framed.webp +0 -0
  27. package/assets/art/kind-miniprogram.webp +0 -0
  28. package/assets/art/kind-poster.webp +0 -0
  29. package/assets/art/kind-slides.webp +0 -0
  30. package/assets/art/kind-tablet.webp +0 -0
  31. package/assets/art/kind-web.webp +0 -0
  32. package/assets/art/placeholder-inspire-img.webp +0 -0
  33. package/assets/art/wait-creating.webp +0 -0
  34. package/assets/motion/ai-capsule.html +124 -0
  35. package/assets/motion/ai-glow-input.html +112 -0
  36. package/assets/motion/balance-odometer.html +112 -0
  37. package/assets/motion/bottom-sheet.html +149 -0
  38. package/assets/motion/brightness-pill.html +114 -0
  39. package/assets/motion/comet-ring.html +95 -0
  40. package/assets/motion/copy-morph.html +116 -0
  41. package/assets/motion/cube-grid.html +103 -0
  42. package/assets/motion/day-night.html +120 -0
  43. package/assets/motion/dial-knob.html +130 -0
  44. package/assets/motion/dock-magnify.html +118 -0
  45. package/assets/motion/download-ring.html +135 -0
  46. package/assets/motion/expand-card.html +137 -0
  47. package/assets/motion/flip-card.html +100 -0
  48. package/assets/motion/hold-pay.html +137 -0
  49. package/assets/motion/holo-card.html +130 -0
  50. package/assets/motion/keycap.html +92 -0
  51. package/assets/motion/like-jelly.html +88 -0
  52. package/assets/motion/liquid-progress.html +113 -0
  53. package/assets/motion/liquid-segment.html +127 -0
  54. package/assets/motion/live-capsule.html +144 -0
  55. package/assets/motion/marker-highlight.html +94 -0
  56. package/assets/motion/marquee-logos.html +110 -0
  57. package/assets/motion/otp-code.html +111 -0
  58. package/assets/motion/password-eye.html +136 -0
  59. package/assets/motion/ruler-slider.html +140 -0
  60. package/assets/motion/search-expand.html +81 -0
  61. package/assets/motion/send-fly.html +121 -0
  62. package/assets/motion/skeleton-shine.html +124 -0
  63. package/assets/motion/star-rate.html +98 -0
  64. package/assets/motion/success-check.html +114 -0
  65. package/assets/motion/suggest-chips.html +134 -0
  66. package/assets/motion/swipe-row.html +126 -0
  67. package/assets/motion/tabbar-bounce.html +92 -0
  68. package/assets/motion/tactile-controls.html +89 -0
  69. package/assets/motion/text-scramble.html +173 -0
  70. package/assets/motion/toast-stack.html +115 -0
  71. package/assets/motion/token-stream.html +106 -0
  72. package/assets/motion/voice-orb.html +144 -0
  73. package/assets/showcase/alley-noodles-1.webp +0 -0
  74. package/assets/showcase/alley-noodles-2.webp +0 -0
  75. package/assets/showcase/alley-noodles-3.webp +0 -0
  76. package/assets/showcase/autumn-sale-1.webp +0 -0
  77. package/assets/showcase/bold-folio-1.webp +0 -0
  78. package/assets/showcase/bold-folio-2.webp +0 -0
  79. package/assets/showcase/book-club-1.webp +0 -0
  80. package/assets/showcase/book-club-2.webp +0 -0
  81. package/assets/showcase/book-club-3.webp +0 -0
  82. package/assets/showcase/flower-order-1.webp +0 -0
  83. package/assets/showcase/little-painter-1.webp +0 -0
  84. package/assets/showcase/little-painter-2.webp +0 -0
  85. package/assets/showcase/moon-fair-1.webp +0 -0
  86. package/assets/showcase/nail-booking-1.webp +0 -0
  87. package/assets/showcase/nail-booking-2.webp +0 -0
  88. package/assets/showcase/nail-booking-3.webp +0 -0
  89. package/assets/showcase/night-run-1.webp +0 -0
  90. package/assets/showcase/paw-diary-1.webp +0 -0
  91. package/assets/showcase/paw-diary-2.webp +0 -0
  92. package/assets/showcase/paw-diary-3.webp +0 -0
  93. package/assets/showcase/pixel-planet-1.webp +0 -0
  94. package/assets/showcase/pixel-planet-2.webp +0 -0
  95. package/assets/showcase/pixel-planet-3.webp +0 -0
  96. package/assets/showcase/pocket-ledger-1.webp +0 -0
  97. package/assets/showcase/pocket-ledger-2.webp +0 -0
  98. package/assets/showcase/shiftloom-1.webp +0 -0
  99. package/assets/showcase/shiftloom-2.webp +0 -0
  100. package/assets/showcase/slow-breath-1.webp +0 -0
  101. package/assets/showcase/slow-breath-2.webp +0 -0
  102. package/assets/showcase/slow-breath-3.webp +0 -0
  103. package/assets/showcase/slow-trip-1.webp +0 -0
  104. package/assets/showcase/slow-trip-2.webp +0 -0
  105. package/assets/showcase/slow-trip-3.webp +0 -0
  106. package/assets/showcase/slow-weekly-1.webp +0 -0
  107. package/assets/showcase/stay-confirm-1.webp +0 -0
  108. package/assets/showcase/stove-recipes-1.webp +0 -0
  109. package/assets/showcase/stove-recipes-2.webp +0 -0
  110. package/assets/showcase/strobewatch-1.webp +0 -0
  111. package/assets/showcase/strobewatch-2.webp +0 -0
  112. package/assets/showcase/tapeworks-1.webp +0 -0
  113. package/assets/showcase/tapeworks-2.webp +0 -0
  114. package/assets/showcase/tea-brand-pitch-1.webp +0 -0
  115. package/assets/showcase/tea-brand-pitch-2.webp +0 -0
  116. package/assets/showcase/tea-brand-pitch-3.webp +0 -0
  117. package/assets/showcase/time-bookshop-1.webp +0 -0
  118. package/assets/showcase/time-bookshop-2.webp +0 -0
  119. package/assets/showcase/water-journey-1.webp +0 -0
  120. package/assets/showcase/water-journey-2.webp +0 -0
  121. package/assets/showcase/water-journey-3.webp +0 -0
  122. package/assets/showcase/weekend-go-1.webp +0 -0
  123. package/assets/showcase/weekend-go-2.webp +0 -0
  124. package/assets/showcase/weekend-go-3.webp +0 -0
  125. package/assets/showcase/winter-soup-1.webp +0 -0
  126. package/assets/showcase/year-review-1.webp +0 -0
  127. package/assets/showcase/year-review-2.webp +0 -0
  128. package/assets/showcase/year-review-3.webp +0 -0
  129. package/lib/annotations.js +1 -1
  130. package/lib/browser.js +3 -1
  131. package/lib/bundle.js +8 -3
  132. package/lib/canvthumb.js +9 -6
  133. package/lib/client.js +7623 -2788
  134. package/lib/components.js +4 -2
  135. package/lib/core.js +763 -133
  136. package/lib/design-page-settings.js +48 -0
  137. package/lib/design-scope.js +36 -0
  138. package/lib/design-transactions.js +259 -0
  139. package/lib/drop-folder.js +25 -0
  140. package/lib/edits.js +125 -8
  141. package/lib/embedded/lvgl_shot.c +133 -0
  142. package/lib/embedded/qml_shot.py +66 -0
  143. package/lib/embedded-shot.js +400 -0
  144. package/lib/embedded-trust.js +76 -0
  145. package/lib/fonts.js +30 -21
  146. package/lib/frames.js +23 -23
  147. package/lib/gallery/css.js +9 -2
  148. package/lib/gallery/market-routes.js +23 -7
  149. package/lib/gallery/pack.js +25 -8
  150. package/lib/gallery/policy.js +6 -4
  151. package/lib/gallery/routes.js +255 -83
  152. package/lib/gallery/submit.js +285 -57
  153. package/lib/gallery/use.js +13 -4
  154. package/lib/handoff-embedded.js +1182 -0
  155. package/lib/handoff.js +212 -71
  156. package/lib/history.js +393 -43
  157. package/lib/htmlpack.js +35 -14
  158. package/lib/impl.js +3 -0
  159. package/lib/index.js +662 -137
  160. package/lib/inspire.js +73 -26
  161. package/lib/kinds.js +11 -2
  162. package/lib/look.js +45 -25
  163. package/lib/mock.js +41 -4
  164. package/lib/motion.js +90 -0
  165. package/lib/page-settings.js +103 -0
  166. package/lib/picker.js +348 -70
  167. package/lib/rules.js +85 -0
  168. package/lib/serve.js +154 -15
  169. package/lib/showcase.json +22 -0
  170. package/lib/styles.js +16 -7
  171. package/lib/system.js +19 -8
  172. package/lib/tool.js +2 -1
  173. package/lib/tweaks.js +146 -9
  174. package/lib/works.js +151 -19
  175. package/locale/annotations/en.json +2 -2
  176. package/locale/annotations/zh.json +2 -2
  177. package/locale/auto/en.json +1 -1
  178. package/locale/auto/zh.json +1 -1
  179. package/locale/en.json +1 -1
  180. package/locale/offline/en.json +1 -1
  181. package/locale/offline/zh.json +2 -2
  182. package/locale/tool/zh.json +1 -1
  183. package/locale/zh.json +1 -1
  184. package/package.json +3 -2
  185. package/skills/ui-design/SKILL.md +59 -47
  186. package/skills/ui-design/frames/dsh/frame.json +1 -1
  187. package/skills/ui-design/references/app.md +29 -2
  188. package/skills/ui-design/references/components.md +1 -1
  189. package/skills/ui-design/references/desktop.md +1 -1
  190. package/skills/ui-design/references/dshplugin.md +12 -12
  191. package/skills/ui-design/references/embedded.md +40 -0
  192. package/skills/ui-design/references/frames.md +20 -20
  193. package/skills/ui-design/references/miniprogram.md +2 -2
  194. package/skills/ui-design/references/mock.md +16 -0
  195. package/skills/ui-design/references/poster.md +2 -1
  196. package/skills/ui-design/references/tweaks.md +17 -0
  197. package/skills/ui-design/tokens.css +19 -5
@@ -0,0 +1,48 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { portablePages, validDevices } from './page-settings.js'
4
+
5
+ export const PAGE_SETTINGS = 'page-settings.json'
6
+ export const SIDE_PAGE_SETTINGS = '.dsh-page-settings.json'
7
+ const FORMAT = 'dsh-design-studio/page-settings@1'
8
+
9
+ export function readPageSettingsBytes(bytes, { markedOnly = false, isProject = () => false } = {}) {
10
+ let doc
11
+ try { doc = JSON.parse(bytes?.toString('utf8')) } catch { return null }
12
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return null
13
+ const { format, screens, devices } = doc
14
+ if (format !== FORMAT && (markedOnly || Object.keys(doc).some(key => !['screens', 'devices'].includes(key)))) return null
15
+ if (screens === undefined && devices === undefined) return null
16
+ if (screens !== undefined && (!screens || typeof screens !== 'object' || Array.isArray(screens))) return null
17
+ if (devices !== undefined && !validDevices(devices)) return null
18
+ const keys = Object.keys(screens || {})
19
+ const portable = portablePages(doc, keys)
20
+ if (keys.some(key => !Object.hasOwn(portable.screens, key) || (screens[key].current !== undefined && !portable.screens[key].current))) return null
21
+ if (format !== FORMAT && isProject(bytes)) return null
22
+ delete doc.format
23
+ return doc
24
+ }
25
+
26
+ export const pageSettingsBytes = doc => Buffer.from(JSON.stringify({ ...doc, format: FORMAT }, null, 2) + '\n')
27
+
28
+ export function directoryPageSettings(root, { strict, isProject } = {}) {
29
+ function read(name, options) {
30
+ const file = path.join(root, name)
31
+ const st = fs.lstatSync(file, { throwIfNoEntry: false })
32
+ const settings = st?.isFile() && st.size <= 512 * 1024 ? readPageSettingsBytes(fs.readFileSync(file), options) : null
33
+ return { exists: !!st, settings }
34
+ }
35
+ try {
36
+ const side = read(SIDE_PAGE_SETTINGS, { markedOnly: true })
37
+ if (side.exists) {
38
+ if (strict && !side.settings) throw Error('页面设置文件格式有误')
39
+ return { file: SIDE_PAGE_SETTINGS, present: !!side.settings, settings: side.settings || {} }
40
+ }
41
+ const original = read(PAGE_SETTINGS, { isProject })
42
+ const file = original.exists && !original.settings ? SIDE_PAGE_SETTINGS : PAGE_SETTINGS
43
+ return { file, present: !!original.settings, settings: original.settings || {} }
44
+ } catch (e) {
45
+ if (strict) throw e
46
+ return { file: SIDE_PAGE_SETTINGS, present: false, settings: {} }
47
+ }
48
+ }
@@ -0,0 +1,36 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { createHash } from 'node:crypto'
4
+
5
+ const digest = value => createHash('sha1').update(value).digest('hex').slice(0, 16)
6
+
7
+ export function canonicalPath(value) {
8
+ try { return fs.realpathSync(value) } catch { return path.resolve(value) }
9
+ }
10
+
11
+ export const directoryId = root => 'directory-' + digest(path.resolve(root))
12
+ export const fileId = file => 'file-' + digest(path.resolve(file))
13
+
14
+ export function identifyTarget(target, { cwd = '', known } = {}) {
15
+ if (target.kind === 'proxy') {
16
+ const designId = 'proxy-' + digest(JSON.stringify([cwd, target.port]))
17
+ return { ...target, designId, targetKey: designId, scope: 'proxy' }
18
+ }
19
+ const root = path.resolve(target.root)
20
+ const file = target.file ? path.join(root, path.basename(target.file)) : ''
21
+ const scope = target.directory ? 'directory' : 'file'
22
+ const designId = known || (scope === 'directory' ? directoryId(canonicalPath(root)) : fileId(path.join(canonicalPath(root), path.basename(file))))
23
+ return { ...target, root, file, designId, targetKey: designId, scope }
24
+ }
25
+
26
+ export function matchesTarget(target, token) {
27
+ if (!target || typeof token !== 'string') return false
28
+ if (target.targetKey && token === target.targetKey) return true
29
+ if (target.kind === 'proxy') return token === 'proxy|' + target.port
30
+ return token.startsWith('file|') && path.isAbsolute(token.slice(5)) && canonicalPath(token.slice(5)) === canonicalPath(target.root)
31
+ }
32
+
33
+ export function fileEntry(target) {
34
+ const entry = target.file ? path.basename(target.file) : ''
35
+ try { return entry && fs.lstatSync(path.join(target.root, entry)).isFile() ? entry : '' } catch { return '' }
36
+ }
@@ -0,0 +1,259 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { AsyncLocalStorage } from 'node:async_hooks'
4
+ import { createHash, randomUUID } from 'node:crypto'
5
+ import { PAGE_SETTINGS, pageSettingsBytes, readPageSettingsBytes } from './design-page-settings.js'
6
+
7
+ export const designWriteScope = new AsyncLocalStorage()
8
+
9
+ const MAX_FILE = 8 * 1024 * 1024
10
+ const MAX_TOTAL = 64 * 1024 * 1024
11
+ export const fingerprint = value => createHash('sha256').update(value).digest('hex')
12
+ export const studioError = (code, message) => Object.assign(new Error(message), { code })
13
+ const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b)
14
+ const plain = value => value !== null && typeof value === 'object' && !Array.isArray(value)
15
+
16
+ function mergeReplay(current, from, to, key) {
17
+ if (equal(current, from)) return to
18
+ if (equal(from, to)) return current
19
+ if (![current, from, to].every(value => value == null || plain(value))) throw studioError('changed', key + ' 已更新')
20
+ const result = { ...current }
21
+ for (const part of new Set([...Object.keys(from || {}), ...Object.keys(to || {})])) {
22
+ const value = mergeReplay(current?.[part], from?.[part], to?.[part], key)
23
+ if (value === undefined) delete result[part]
24
+ else Object.defineProperty(result, part, { value, writable: true, enumerable: true, configurable: true })
25
+ }
26
+ return !Object.keys(result).length && to == null ? to : result
27
+ }
28
+
29
+ const asBytes = value => value == null ? null : Buffer.isBuffer(value) ? value : Buffer.from(value)
30
+
31
+ export function atomicWrite(file, data, mode = 0o600) {
32
+ const tmp = path.join(path.dirname(file), '.' + path.basename(file) + '.' + randomUUID() + '.tmp')
33
+ try {
34
+ fs.writeFileSync(tmp, data, { flag: 'wx', mode })
35
+ fs.renameSync(tmp, file)
36
+ } finally {
37
+ fs.rmSync(tmp, { force: true })
38
+ }
39
+ }
40
+
41
+ export function readItem(root, key) {
42
+ const parts = key.split('/')
43
+ if (parts.some(p => !p || p === '.' || p === '..' || /[\\:\0]/.test(p))) throw studioError('scope', key)
44
+ let file = root
45
+ for (const [index, part] of parts.entries()) {
46
+ file = path.join(file, part)
47
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false })
48
+ if (!stat) return { data: null, mode: 0, hash: null }
49
+ if (index < parts.length - 1 && stat.isDirectory()) continue
50
+ if (index < parts.length - 1 || !stat.isFile() || stat.nlink !== 1) throw studioError('changed', key + ' 无法安全写入')
51
+ if (stat.size > MAX_FILE) throw studioError('backup', key + ' 超过备份大小')
52
+ const data = fs.readFileSync(file)
53
+ return { data, mode: stat.mode & 0o777, hash: fingerprint(data) }
54
+ }
55
+ }
56
+
57
+ export function createTransactions({ base, log = () => {}, now = Date.now, write = atomicWrite }) {
58
+ const memory = new Map()
59
+ const folder = id => path.join(base, id)
60
+ const dbFile = id => path.join(folder(id), 'state.json')
61
+ const journal = id => path.join(folder(id), 'pending.json')
62
+ const objFile = (id, hash) => path.join(folder(id), 'objects', hash)
63
+ const blank = () => ({ records: {}, requests: {}, positions: {}, layoutRev: 0, edits: [], seen: {}, nextSeq: 1 })
64
+ const save = (id, value) => {
65
+ if (!base) { memory.set(id, structuredClone(value)); return }
66
+ fs.mkdirSync(folder(id), { recursive: true })
67
+ atomicWrite(dbFile(id), JSON.stringify(value))
68
+ }
69
+ function load(id) {
70
+ if (!base) return structuredClone(memory.get(id) || blank())
71
+ try { return JSON.parse(fs.readFileSync(dbFile(id), 'utf8')) }
72
+ catch (e) { if (e.code === 'ENOENT') return blank(); throw e }
73
+ }
74
+ const blobs = new Map()
75
+ function put(id, item) {
76
+ if (item.hash === null) return { hash: null, mode: 0 }
77
+ if (!base) blobs.set(item.hash, item.data)
78
+ else {
79
+ const file = objFile(id, item.hash)
80
+ fs.mkdirSync(path.dirname(file), { recursive: true })
81
+ if (!fs.existsSync(file)) atomicWrite(file, item.data)
82
+ }
83
+ get(id, item.hash)
84
+ return { hash: item.hash, mode: item.mode }
85
+ }
86
+ function get(id, hash) {
87
+ if (hash === null) return null
88
+ try {
89
+ if (!/^[0-9a-f]{64}$/.test(hash)) throw Error()
90
+ const data = base ? fs.readFileSync(objFile(id, hash)) : blobs.get(hash)
91
+ if (!data || fingerprint(data) !== hash) throw Error()
92
+ return data
93
+ } catch { throw studioError('backup', '事务备份无法读取或校验失败') }
94
+ }
95
+ function replace(id, root, key, state, writer) {
96
+ const data = get(id, state.hash)
97
+ const file = path.join(root, key)
98
+ if (data === null) fs.rmSync(file, { force: true })
99
+ else {
100
+ fs.mkdirSync(path.dirname(file), { recursive: true })
101
+ writer(file, data, state.mode || 0o644)
102
+ }
103
+ }
104
+ function rollback(id, root, items) {
105
+ for (const item of [...items].reverse()) {
106
+ const current = readItem(root, item.key)
107
+ if (current.hash === item.before.hash) continue
108
+ if (current.hash !== item.after.hash) throw studioError('changed', item.key + ' 有外部改动,无法恢复未完成的事务')
109
+ replace(id, root, item.key, item.before, atomicWrite)
110
+ }
111
+ }
112
+ function recover(target) {
113
+ if (!base) return
114
+ const id = target.designId
115
+ let pending
116
+ try { pending = JSON.parse(fs.readFileSync(journal(id), 'utf8')) }
117
+ catch (e) { if (e.code === 'ENOENT') return; throw e }
118
+ const db = load(id)
119
+ if (db.lastCommit !== pending.id) {
120
+ if (!target.root || fs.realpathSync(target.root) !== pending.root) throw studioError('moved', '待恢复事务的目录已变更')
121
+ rollback(id, target.root, pending.items)
122
+ }
123
+ fs.rmSync(journal(id), { force: true })
124
+ }
125
+ const requestKey = (op, token) => typeof token === 'string' && token.length > 0 && token.length <= 160 ? fingerprint(op + '\0' + token) : ''
126
+ const cached = (target, op, token) => {
127
+ recover(target)
128
+ return load(target.designId).requests[requestKey(op, token)]
129
+ }
130
+ function update(target, { kind, label, pages = [], rev, writes = new Map(), expected = new Map(), settingsFiles = [], metadata = {}, detail = {}, focus, beforeOrder, requestId, operation = kind, response = {}, replayOf = '', direction = '', beforeWrite }) {
131
+ recover(target)
132
+ const id = target.designId
133
+ const db = load(id)
134
+ const request = requestKey(operation, requestId)
135
+ if (request && db.requests[request]) return db.requests[request]
136
+ const items = []
137
+ let total = 0
138
+ for (const [key, value] of writes) {
139
+ const before = readItem(target.root, key)
140
+ if (expected.has(key) && expected.get(key) !== before.hash) throw studioError('changed', key + ' 已更新')
141
+ const wrapped = value && typeof value === 'object' && !Buffer.isBuffer(value)
142
+ const data = asBytes(wrapped ? value.data : value)
143
+ const hash = data === null ? null : fingerprint(data)
144
+ if (hash === before.hash) continue
145
+ if ((data?.length || 0) > MAX_FILE || (total += (data?.length || 0) + (before.data?.length || 0)) > MAX_TOTAL) throw studioError('backup', '事务超过备份大小')
146
+ items.push({ key, settings: settingsFiles.includes(key), before: put(id, before), after: put(id, { data, hash, mode: (wrapped ? value.mode : 0) || before.mode || 0o644 }) })
147
+ }
148
+ const attributes = Object.entries(metadata).map(([key, after]) => {
149
+ const before = key === 'screenOrder' && beforeOrder && !db.screenOrder?.length ? beforeOrder : db[key]
150
+ return { key, before: before ?? null, after: after ?? null }
151
+ }).filter(({ before, after }) => JSON.stringify(before) !== JSON.stringify(after))
152
+ if (!items.length && !attributes.length) return { ok: true, ...response }
153
+ const commitId = randomUUID()
154
+ const change = { id: replayOf || commitId, designId: id, kind, label, pages, beforeRev: rev, afterRev: rev + 1 }
155
+ if (kind === 'text' && detail.after) change.text = detail.after
156
+ if ((kind === 'style' || kind === 'rule') && detail.css) change.css = detail.css
157
+ const record = { change, items, attributes, focus, next: 'undo' }
158
+ if (replayOf) db.records[replayOf].next = direction === 'undo' ? 'redo' : 'undo'
159
+ else db.records[commitId] = record
160
+ for (const { key, after } of attributes) db[key] = after
161
+ if (attributes.some(a => a.key === 'positions')) db.layoutRev++
162
+ if (items.length || attributes.some(a => a.key === 'settings' || a.key === 'display')) {
163
+ db.edits.push({
164
+ ...detail, seq: db.nextSeq++, kind: replayOf ? 'replay' : (detail.kind || kind), label, pageKeys: pages,
165
+ files: items.map(i => i.key), expectedHashes: Object.fromEntries(items.map(i => [i.key, i.after.hash])),
166
+ settings: kind === 'settings' || attributes.some(a => a.key === 'settings' || a.key === 'display') || items.some(i => i.settings),
167
+ settingsFiles: items.filter(i => i.settings).map(i => i.key),
168
+ scope: target.scope, root: target.root, at: now(), ...(direction ? { direction } : {}),
169
+ })
170
+ }
171
+ const result = { ok: true, ...response, change, layoutRev: db.layoutRev, ...(focus ? { focus: { from: focus.before, to: focus.after } } : {}) }
172
+ if (request) db.requests[request] = result
173
+ db.lastCommit = commitId
174
+ if (base && items.length) atomicWrite(journal(id), JSON.stringify({ id: commitId, root: fs.realpathSync(target.root), items }))
175
+ const applied = []
176
+ let rollbackEffect
177
+ try {
178
+ for (const item of items) if (readItem(target.root, item.key).hash !== item.before.hash) throw studioError('changed', item.key + ' 已更新')
179
+ rollbackEffect = beforeWrite?.()
180
+ for (const item of items) {
181
+ if (readItem(target.root, item.key).hash !== item.before.hash) throw studioError('changed', item.key + ' 已更新')
182
+ replace(id, target.root, item.key, item.after, write)
183
+ applied.push(item)
184
+ }
185
+ save(id, db)
186
+ } catch (e) {
187
+ rollback(id, target.root, applied)
188
+ rollbackEffect?.()
189
+ if (base) fs.rmSync(journal(id), { force: true })
190
+ throw e
191
+ }
192
+ if (base) try { fs.rmSync(journal(id), { force: true }) } catch (e) { log(e) }
193
+ return result
194
+ }
195
+ function replay(target, { changeId, direction, requestId, rev, beforeWrite }) {
196
+ const old = cached(target, 'replay', requestId)
197
+ if (old) return old
198
+ const id = target.designId
199
+ const db = load(id)
200
+ const record = Object.hasOwn(db.records, changeId) && db.records[changeId]
201
+ if (!record) throw studioError('gone', '改动记录已不可用')
202
+ if (record.next !== direction) throw studioError('changed', '改动已重放')
203
+ const from = direction === 'undo' ? 'after' : 'before'
204
+ const to = direction === 'undo' ? 'before' : 'after'
205
+ const writes = new Map()
206
+ const expected = new Map()
207
+ const settingsFiles = []
208
+ for (const item of record.items) {
209
+ const current = readItem(target.root, item.key)
210
+ const next = get(id, item[to].hash)
211
+ const isSettings = item.settings ?? item.key === PAGE_SETTINGS
212
+ if (isSettings) settingsFiles.push(item.key)
213
+ expected.set(item.key, current.hash)
214
+ if (current.hash === item[from].hash) writes.set(item.key, next === null ? null : { data: next, mode: item[to].mode })
215
+ else if (isSettings) {
216
+ const parse = data => {
217
+ if (!data) return undefined
218
+ const doc = readPageSettingsBytes(data)
219
+ if (!doc) throw studioError('changed', item.key + ' 已更新')
220
+ return doc
221
+ }
222
+ const merged = mergeReplay(parse(current.data), parse(get(id, item[from].hash)), parse(next), item.key)
223
+ writes.set(item.key, merged === undefined ? null : pageSettingsBytes(merged))
224
+ } else throw studioError('changed', item.key + ' 已更新')
225
+ }
226
+ const metadata = {}
227
+ for (const attr of record.attributes) metadata[attr.key] = mergeReplay(db[attr.key] ?? null, attr[from], attr[to], attr.key)
228
+ return update(target, { ...record.change, writes, expected, settingsFiles, metadata, focus: record.focus ? { before: record.focus[from], after: record.focus[to] } : undefined, replayOf: changeId, direction, operation: 'replay', requestId, rev, beforeWrite: beforeWrite && (() => beforeWrite(writes)) })
229
+ }
230
+ function relocateFile(id, previous, next) {
231
+ if (!previous || !next || previous === next) return
232
+ const db = load(id)
233
+ if (db.fileEntry === next) return
234
+ const remap = key => key === previous ? next : key
235
+ const mapKeys = value => value && Object.fromEntries(Object.entries(value).map(([key, item]) => [remap(key), item]))
236
+ const settings = value => value?.screens ? { ...value, screens: mapKeys(value.screens) } : value
237
+ db.settings = settings(db.settings)
238
+ db.positions = mapKeys(db.positions)
239
+ for (const e of db.edits) {
240
+ e.files = e.files.map(remap)
241
+ e.pageKeys = e.pageKeys.map(remap)
242
+ e.expectedHashes = mapKeys(e.expectedHashes)
243
+ }
244
+ for (const record of Object.values(db.records)) {
245
+ record.change.pages = record.change.pages.map(remap)
246
+ for (const item of record.items) item.key = remap(item.key)
247
+ for (const attr of record.attributes) {
248
+ const mapper = attr.key === 'positions' ? mapKeys : attr.key === 'settings' ? settings : value => value
249
+ attr.before = mapper(attr.before)
250
+ attr.after = mapper(attr.after)
251
+ }
252
+ }
253
+ db.requests = {}
254
+ db.fileEntry = next
255
+ save(id, db)
256
+ }
257
+
258
+ return { load, save, recover, update, replay, cached, relocateFile }
259
+ }
@@ -0,0 +1,25 @@
1
+ // Shared by the sidebar and injected preview. FileSystemDirectoryReader returns batches.
2
+ export async function readDropFolder(folder) {
3
+ const files = []
4
+ let bytes = 0
5
+ async function visit(dir, prefix) {
6
+ const reader = dir.createReader()
7
+ for (;;) {
8
+ const batch = await new Promise((resolve, reject) => reader.readEntries(resolve, reject))
9
+ if (!batch.length) break
10
+ for (const entry of batch) {
11
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue
12
+ const path = prefix + entry.name
13
+ if (entry.isDirectory) await visit(entry, path + '/')
14
+ else {
15
+ const file = await new Promise((resolve, reject) => entry.file(resolve, reject))
16
+ bytes += file.size
17
+ if (files.length >= 1024 || bytes > 32 * 1024 * 1024) throw new Error('1024 files / 32 MB')
18
+ files.push({ path, file })
19
+ }
20
+ }
21
+ }
22
+ }
23
+ await visit(folder, '')
24
+ return files
25
+ }
package/lib/edits.js CHANGED
@@ -1,19 +1,87 @@
1
1
  /**
2
- * 用户在右侧栏亲手改了设计(调样式、改字、调节滑块、回到某一版)之后,模型下一步开始前插件补给它的一段说明。
2
+ * 用户在右侧栏亲手改了设计(调样式、改字、保存页面设置、回到某一版)之后,模型下一步开始前插件补给它的一段说明。
3
3
  *
4
4
  * 为什么要:模型记得的是自己上次写的内容,不一定重读文件;用户手调的颜色、字,它接着改或做进项目时会用回旧样子(#28)。
5
5
  * 走 DSH 的 agent/pre-step(和 DSH 自带的时间、操作卡片提醒一样),以「通知」的样子进对话:用户看得到一行,模型拿到全文。
6
6
  */
7
7
 
8
8
 
9
+ import { designOf, metaOfFile, originalOf } from './look.js'
10
+ import path from 'node:path'
11
+
12
+ export const designKey = target => target?.targetKey || (!target ? '' : target.kind === 'file' ? 'file|' + target.root : 'proxy|' + target.port)
13
+
14
+ export function latestUser(messages) {
15
+ return (messages || []).findLast(m => m?.source?.kind === 'user')
16
+ }
17
+
18
+ function messageText(m) {
19
+ const c = m?.content
20
+ return typeof c === 'string' ? c : Array.isArray(c) ? c.filter(b => b?.type === 'text').map(b => b.text).join('\n') : ''
21
+ }
22
+
23
+ export function startsNewDesign(message) {
24
+ return /^\s*(?:〔(?:新设计|用设计系统新建)〕|\[(?:New design|New design system project)\]|(?:请|帮我)?(?:新建|新做|从零设计)(?:一套|一个|一份|设计)|(?:please\s+)?(?:start|create)\s+(?:a\s+)?new\s+(?:design|project))/im.test(messageText(message))
25
+ }
26
+
27
+ const DESIGN_TAG = /〔(?:选中元素|选中区域|设计变量|参考图|设计屏|再出两版|设计交接|标注)〕|\[(?:Selected (?:element|area)|Design (?:screen|variable|handoff)|Reference image)\]/i
28
+ const PAGE_REQUEST = /(?:改|调整|优化|完善|继续|交接|做进|检查|导出|按).{0,26}(?:设计|界面|画布|首页|详情|页面|当前屏|这屏|原型|选中)|(?:设计|界面|画布|首页|详情|页面|这屏|原型).{0,20}(?:改|调整|优化|完善|继续|交接|做进|检查|导出)|\b(?:edit|update|tweak|change|continue|handoff|implement|export|check)\b.{0,45}\b(?:design|screen|page|canvas|prototype|home|selection)\b/i
29
+ const DESIGN_TOOLS = new Set(['preview_page', 'check_design', 'look_design', 'compare_design', 'handoff_design', 'read_design_changes'])
30
+
31
+ export function relevantDesign(user, snap, messages = []) {
32
+ if (!snap.target || startsNewDesign(user)) return false
33
+ const text = messageText(user)
34
+ const claimed = [...text.matchAll(/(?:targetKey|designId)\s*[:=]\s*["']?((?:directory|file|proxy)-[a-f0-9]{16})/gi)].map(match => match[1])
35
+ if (claimed.length && !claimed.includes(snap.designId)) return false
36
+ if (/另一套|另一个设计|别的设计|different design|another design/i.test(text) && !claimed.length) return false
37
+ const explicit = [...text.matchAll(/(?:^|[\s\x60"'::])((?:[A-Za-z]:[\\/]|\/)[^\r\n\x60"'<>]*?\.html?)(?=$|[\s\x60"',。])/g)].map(match => match[1])
38
+ if (snap.target.kind === 'file' && explicit.length) {
39
+ const allowed = new Set((snap.pages || [snap.focus]).map(key => path.join(snap.target.root, key)))
40
+ if (!explicit.some(file => allowed.has(path.resolve(file)))) return false
41
+ }
42
+ if (claimed.length || DESIGN_TAG.test(text) || PAGE_REQUEST.test(text)) return true
43
+ if ((snap.pages || []).some(page => text.includes(page)) && /改|继续|调整|edit|change|continue/i.test(text)) return true
44
+ const afterUser = messages.slice(messages.lastIndexOf(user) + 1)
45
+ return afterUser.some(message => message.content?.some?.(item => item?.type === 'tool-call' && DESIGN_TOOLS.has(item.name || item.toolName)))
46
+ }
47
+
48
+ const pageSize = (p, fallback, zh) => [p?.kind || fallback?.kind, p?.size || fallback?.size].filter(Boolean).join(' / ') || (zh ? '按页面原始设置' : 'page defaults')
49
+ const deviceSizes = (devices, zh) => devices?.join(zh ? '、' : ', ') || (zh ? '未开启多设备' : 'multi-device off')
50
+
51
+ /** 只传当前设计和指定屏的设置,历史项目或对话草稿不会混进来。 */
52
+ export function designNotice(snap, lang) {
53
+ if (!snap.target) return null
54
+ const zh = lang !== 'en'
55
+ const { target, focus, pageSettings: pages = {} } = snap
56
+ const location = target.kind === 'file' ? target.scope === 'file' ? target.file : target.root : `http://localhost:${target.port}${target.path}`
57
+ const settings = Object.entries(pages.screens || {}).filter(([key, value]) => key === focus || value.current || value.followSource)
58
+ const effectivePage = (key, row) => {
59
+ if (row?.current) return row.current
60
+ const meta = target.kind === 'file' ? () => metaOfFile(path.join(target.root, key)) : () => ''
61
+ const original = row?.original
62
+ const defaults = { kind: snap.kind || original?.kind, size: snap.size || original?.size }
63
+ const p = row?.followSource ? originalOf(defaults, meta()) : designOf(defaults, meta)
64
+ return { kind: p.kind, size: p.auto ? '' : p.size.join('x') }
65
+ }
66
+ if (!settings.some(([key]) => key === focus)) settings.unshift([focus, null])
67
+ const lines = settings.map(([key, row]) => `- ${key}: ${pageSize(effectivePage(key, row), null, zh)}`)
68
+ const text = zh
69
+ ? [`〔设计工作台〕当前设计:${location}。当前屏:${focus}。`, ...lines,
70
+ ...(pages.devices === undefined ? [] : [`适配设备(CSS px):${deviceSizes(pages.devices, zh)}。`]),
71
+ '这条请求若是继续编辑或交接当前设计,请以以上设置为准,先读对应文件,再继续。'].join('\n')
72
+ : [`[Design Studio] Current design: ${location}. Current screen: ${focus}.`, ...lines,
73
+ ...(pages.devices === undefined ? [] : [`Device viewports (CSS px): ${deviceSizes(pages.devices, zh)}.`]),
74
+ 'If this request edits or hands off the current design, use these settings and first re-read the relevant files.'].join('\n')
75
+ return { text, summary: zh ? `当前设计:${focus}` : `Current design: ${focus}` }
76
+ }
77
+
9
78
  const CJK = /[㐀-鿿豈-﫿]/
10
79
 
11
80
  /** 用户这一轮说的话里有中文就用中文写说明,否则英文(DSH 没告诉插件界面语言) */
12
81
  export function langOf(messages) {
13
82
  for (const m of [...(messages || [])].reverse()) {
14
83
  if (!m || !m.source || m.source.kind !== 'user') continue
15
- const c = m.content
16
- const text = typeof c === 'string' ? c : Array.isArray(c) ? c.filter((b) => b && b.type === 'text').map((b) => b.text).join('\n') : ''
84
+ const text = messageText(m)
17
85
  if (text.trim()) return CJK.test(text) ? 'zh' : 'en'
18
86
  }
19
87
  return 'zh'
@@ -22,9 +90,55 @@ export function langOf(messages) {
22
90
  const cssText = (css) => Object.entries(css || {}).map(([k, v]) => `${k}: ${v || '(去掉)'}`).join('; ')
23
91
  const cssTextEn = (css) => Object.entries(css || {}).map(([k, v]) => `${k}: ${v || '(removed)'}`).join('; ')
24
92
 
93
+ const roles = {
94
+ button:['按钮','Button'], a:['链接','Link'], h:['标题','Heading'], p:['段落','Paragraph'], img:['图片','Image'],
95
+ input:['输入框','Input'], li:['列表项','List item'], ul:['列表','List'], nav:['导航','Navigation'],
96
+ header:['顶栏','Header'], footer:['底栏','Footer'], text:['文字','Text'], box:['区块','Block'],
97
+ }
98
+ export function styleElement(name, lang = 'zh') {
99
+ const value = String(name || '')
100
+ const tag = value.toLowerCase().match(/^[a-z][a-z0-9]*/)?.[0]
101
+ const key = /btn|button/i.test(value) ? 'button' : /^h[1-6]$/.test(tag) ? 'h'
102
+ : /^(textarea|select)$/.test(tag) ? 'input' : /^(picture|video)$/.test(tag) ? 'img'
103
+ : tag === 'ol' ? 'ul' : /^(span|b|strong|em|label|time|small)$/.test(tag) ? 'text' : tag
104
+ const role = Object.values(roles).find(([zh]) => zh === value) || (Object.hasOwn(roles, key) ? roles[key] : roles.box)
105
+ return role[lang === 'en' ? 1 : 0]
106
+ }
107
+ const actionNames = {
108
+ '页面设置':'Page settings', '移除屏幕':'Remove screens', '粘贴屏幕':'Paste screens', '移动屏幕':'Move screens',
109
+ '模拟数据:存成初始数据':'Save initial mock data', '改项目规矩(rules.md)':'Edit project rules (rules.md)',
110
+ }
111
+ function actionNameEn(label) {
112
+ if (!label) return ''
113
+ if (Object.hasOwn(actionNames, label)) return actionNames[label]
114
+ if (label.startsWith('调节:')) return 'Adjust: ' + label.slice(3).split('、').join(', ')
115
+ return label.replace(/^回到第 (\d+) 版$/, 'Return to version $1')
116
+ .replace(/^改字「(.*)」$/, 'Edit text “$1”').replace(/^调样式「(.*?)」/, (_, name) => 'Edit style “' + styleElement(name, 'en') + '”')
117
+ .replace(/^换风格:/, 'Apply style: ')
118
+ }
119
+ export function versionAction(v) {
120
+ if (v.by !== 'me' || !v.label) return {}
121
+ const replay = /^(撤销|重做)[::]\s*(.+)$/.exec(v.label)
122
+ const action = (replay ? replay[2] : v.label).replace(/^调样式「(.*?)」/, (_, name) => '调样式「' + styleElement(name) + '」')
123
+ return { action, labelEn:actionNameEn(action), ...(replay && { direction:replay[1] === '撤销' ? 'undo' : 'redo' }) }
124
+ }
125
+
25
126
  /** 一条手改记录说成一行 */
26
127
  function line(e, zh) {
128
+ const label = String(e.label || '').replaceAll(' · ', zh ? ',' : ', ')
27
129
  const files = (e.files || []).join(zh ? '、' : ', ') + (e.more ? (zh ? ` 等 ${e.files.length + e.more} 个文件` : ` and ${e.more} more`) : '')
130
+ if (e.kind === 'replay') {
131
+ const verb = e.direction === 'undo' ? (zh ? '撤销了' : 'Undid') : (zh ? '重做了' : 'Redid')
132
+ return `- ${verb} ${zh ? label : actionNameEn(label)}${files ? (zh ? ',' : ', ') + files : ''}`
133
+ }
134
+ if (e.kind === 'settings') {
135
+ const parts = []
136
+ if (e.screen) parts.push(`${e.screen}: ${pageSize(e.page, null, zh)}`)
137
+ if (e.devices !== undefined) parts.push(`${zh ? '适配设备' : 'Device viewports'}: ${deviceSizes(e.devices, zh)}`)
138
+ if (typeof e.display?.dark === 'boolean') parts.push(e.display.dark ? (zh ? '深色' : 'dark') : (zh ? '浅色' : 'light'))
139
+ if (typeof e.display?.fit === 'boolean') parts.push(e.display.fit ? (zh ? '按画幅显示' : 'fit viewport') : (zh ? '铺满' : 'fill'))
140
+ return [zh ? '- 保存页面设置' : '- Saved page settings', ...parts].join(zh ? ',' : ', ')
141
+ }
28
142
  if (e.kind === 'style') return zh
29
143
  ? `- ${files}:调样式「${e.name}」→ ${cssText(e.css)}(写在这个元素的行内 style 上)`
30
144
  : `- ${files}: restyled "${e.name}" → ${cssTextEn(e.css)} (written as an inline style on that element)`
@@ -37,14 +151,14 @@ function line(e, zh) {
37
151
  if (e.kind === 'restore') return zh
38
152
  ? `- 整套设计回到了第 ${e.n} 版(${e.count} 个文件换回那一版的内容)`
39
153
  : `- The whole design was restored to version ${e.n} (${e.count} files now hold that version's content)`
40
- return zh ? `- ${files}:${e.label || '改了'}` : `- ${files}: ${e.label || 'edited'}`
154
+ return zh ? `- ${files}:${label || '改了'}` : `- ${files}: ${label || 'edited'}`
41
155
  }
42
156
 
43
157
  /**
44
158
  * @param edits 核心记下的手改(见 core.js 的 noteEdit),旧的在前
45
159
  * @returns {{ text, summary } | null}
46
160
  */
47
- export function editsNotice(edits, lang = 'zh') {
161
+ export function editsNotice(edits, lang = 'zh', targetKey = '') {
48
162
  const list = (edits || []).filter(Boolean)
49
163
  if (!list.length) return null
50
164
  const zh = lang !== 'en'
@@ -52,13 +166,16 @@ export function editsNotice(edits, lang = 'zh') {
52
166
  const where = roots.length ? roots.map((r) => `\`${r}\``).join(zh ? '、' : ', ') : ''
53
167
  const lines = list.map((e) => line(e, zh))
54
168
  const text = zh
55
- ? [`〔设计工作台〕你上次写完之后,用户自己在右侧设计工作台里改了设计${where ? `(${where})` : ''},这些就是用户要的样子:`, ...lines,
169
+ ? [`〔设计工作台〕你上次写完之后,用户自己在右侧设计工作台里改了设计${where ? `(${where})` : ''},操作按时间排列:`, ...lines,
56
170
  '接着改这套设计、或者把它做进项目里之前:先重新读上面这些文件,以文件现在的内容为准,别照你之前写的内容来,也别把这些改回去(除非用户这次就是要你改)。行内 style 上的值是用户手调的:做成组件时把它并进组件的样式。'].join('\n')
57
- : [`[Design Studio] Since you last wrote, the user edited the design by hand in the Design Studio sidebar${where ? ` (${where})` : ''}. This is how the user wants it:`, ...lines,
171
+ : [`[Design Studio] Since you last wrote, the user edited the design by hand in the Design Studio sidebar${where ? ` (${where})` : ''}. Changes in chronological order:`, ...lines,
58
172
  'Before you change this design again or build it into a project: re-read the files above and treat their current content as the truth. Do not go by what you wrote earlier, and do not undo these edits (unless the user asks for that now). Values in inline styles were tuned by the user: when you turn the element into a component, carry those values into the component\'s styles.'].join('\n')
173
+ const instruction = targetKey ? (zh
174
+ ? '\n先调用 read_design_changes,targetKey 为 ' + targetKey + ',从序号 ' + list[0].seq + ' 开始。按工具返回的文件内容、移除状态和有效设置继续;还有记录时继续读。'
175
+ : '\nFirst call read_design_changes with targetKey ' + targetKey + ' starting at sequence ' + list[0].seq + '. Use the returned file contents, removals and effective settings, and read any further entries.') : ''
59
176
  const n = list.length
60
177
  const summary = zh ? `用户在设计工作台里手改了 ${n} 处` : `The user hand-edited the design (${n} ${n === 1 ? 'edit' : 'edits'})`
61
- return { text, summary }
178
+ return { text: text + instruction, summary }
62
179
  }
63
180
 
64
181
  /** 给 DSH 的一条「通知」消息(和 @deepseek-ai/dsh-llm 的 createUserMessage 出来的一样:有 id、冻住) */