dsh-design-studio 1.1.0 → 1.2.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.
package/lib/core.js CHANGED
@@ -37,6 +37,7 @@ const MAX_ROUTES = 300 // 开发服务器的路由先都记着(只为算出收
37
37
 
38
38
  // 设计类型:决定右侧用什么画幅显示(网页框、手机、小程序、平板、桌面软件窗口、海报、幻灯片、邮件、图表)
39
39
  import { KINDS } from './kinds.js'
40
+ import { mockOf } from './mock.js'
40
41
  export { KINDS }
41
42
  const KIND_ALIAS = {
42
43
  website: 'web', site: 'web', page: 'web', landing: 'web', dashboard: 'web',
@@ -1489,6 +1490,11 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
1489
1490
  return r
1490
1491
  }
1491
1492
 
1493
+ /** 这套设计的模拟数据:{ fp, err },没有 mock.json 给 null */
1494
+ function mockInfo(root) {
1495
+ try { const m = mockOf(root); return m ? { fp: m.fp, err: m.err || '' } : null } catch { return null }
1496
+ }
1497
+
1492
1498
  /** 版本列表(新的在前);开发服务器没有版本(项目自己有 git) */
1493
1499
  function versions(id) {
1494
1500
  const st = states.get(id)
@@ -1565,6 +1571,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
1565
1571
  vrev: st.vrev,
1566
1572
  trust: file ? trust() : '', // 「哪些算别人做的」的指纹:所有会话共用,远程看的右侧栏按它作废留着的打包结果
1567
1573
  watch: file ? watchTag(target.root) : '', // 预览服务器有没有在监听这个目录(开始 / 停止监听就变):画布缩略图按它重新要(停了就得自己定时再要)
1574
+ mock: file ? mockInfo(target.root) : null, // 模拟数据(#30):有 mock.json 才有;fp 变了右侧栏的「数据」面板重新连
1568
1575
  focus: file ? path.basename(target.file) : target.path,
1569
1576
  hidden: st.hidden || 0, // 超过上限收起来的屏数
1570
1577
  maxScreens: MAX_SCREENS,
@@ -264,7 +264,8 @@ export function packDesign(root, { screens, version = '', license = '', author =
264
264
  // 不在画布上的顶层页面(方向稿删掉了、改名前的旧文件):不打包
265
265
  if (/\.html$/i.test(f.path) && !f.path.includes('/') && !screenSet.has(f.path.toLowerCase())) { skipped.push(f.path); continue }
266
266
  // 别的 JSON(设置、记录、导出的数据…):模板用不上(不能跑脚本),可能带着个人信息,不打包;只留调节滑块的 tweaks.json
267
- if (/\.json$/i.test(f.path) && f.path !== 'tweaks.json') { skipped.push(f.path); continue }
267
+ // 和模拟数据 mock.json(#30:原型的数据源,少了它页面上的绑定全是占位、几种状态一起露出来;JSON 整份查个人信息)
268
+ if (/\.json$/i.test(f.path) && f.path !== 'tweaks.json' && f.path !== 'mock.json') { skipped.push(f.path); continue }
268
269
  let data
269
270
  try {
270
271
  const st = fs.statSync(f.abs)
@@ -291,7 +292,8 @@ export function packDesign(root, { screens, version = '', license = '', author =
291
292
  }
292
293
  }
293
294
  // 自带照片库的图:找图时多拿的、页面没用上的不打包。宁可多带:页面里(解码后)提到这个文件名就留,注释里的不算
294
- const refText = files.filter((f) => /\.(html|css|svg)$/i.test(f.path)).map((f) => refsFold(Buffer.from(f.data).toString('utf8'))).join('\n')
295
+ // mock.json 也算(#30:头像、商品图写在模拟数据里,页面用 data-mock-attr 绑上)
296
+ const refText = files.filter((f) => /\.(html|css|svg)$/i.test(f.path) || f.path === 'mock.json').map((f) => refsFold(Buffer.from(f.data).toString('utf8'))).join('\n')
295
297
  const dropped = new Set()
296
298
  for (let i = files.length - 1; i >= 0; i--) {
297
299
  const f = files[i]
package/lib/handoff.js CHANGED
@@ -22,6 +22,7 @@ import { tokensOf } from './system.js'
22
22
  import { FRAMES_DIR } from './frames.js'
23
23
  import { FRAME_MAIN, SLOT_BOX } from './slot.js'
24
24
  import { statesOfHtml } from './states.js'
25
+ import { mockOf } from './mock.js'
25
26
 
26
27
  /**
27
28
  * 交接文档里的「页面状态」:写了几个状态的屏,列出状态、各状态用到的样式条数、哪些按钮会切到哪个状态
@@ -42,6 +43,41 @@ export function statesMd(htmlByKey, css = '') {
42
43
  return out
43
44
  }
44
45
 
46
+ /**
47
+ * 交接文档里的「模拟数据」(#30):设计目录里有 mock.json 才有。原型的数据都在这一份里、各屏用 data-mock-* 绑上;
48
+ * 转代码时做成一份初始数据 + 全局状态,页面从状态里读、点了改状态
49
+ */
50
+ export function mockMd(htmlByKey, root) {
51
+ const m = mockOf(root)
52
+ if (!m) return []
53
+ const top = Object.keys(m.data)
54
+ const out = [
55
+ `- 原型的数据都在设计目录的 \`mock.json\` 里${m.err ? `(现在读不出来:${m.err}——先修好再做)` : top.length ? `(顶层:${top.slice(0, 12).join('、')}${top.length > 12 ? ' 等' : ''})` : ''},各屏用 \`data-mock-*\` 绑在上面。照搬成项目里的一份初始数据 + 一个全局状态(Pinia / Zustand / Context / 小程序的全局 store 之类):页面上的值从状态里读,点了改状态,换页还在;以后接真接口只换状态的来源,页面不用动。`,
56
+ '- 写法对照:`data-mock-text` 显示值;`data-mock-show` 条件显示;`data-mock-each="x in list"` + `<template>` 是列表;`data-mock-class` / `data-mock-attr` 按条件加 class、属性;`data-mock-model` 双向绑定的输入框;`data-mock-set="a = …; b = …"` 点了改数据(做成点击事件);`data-mock-reset` 恢复初始数据(演示用)。',
57
+ ]
58
+ const topSet = new Set(top)
59
+ const follow = []
60
+ for (const [key, html] of htmlByKey) {
61
+ const src = String(html)
62
+ const st = /<meta\b[^>]*>/gi
63
+ for (const mm of src.matchAll(st)) {
64
+ if (!/\bname\s*=\s*["']?dsh-states["'\s/>]/i.test(mm[0])) continue
65
+ const d = /\bdata-mock\s*=\s*["']([^"']+)["']/i.exec(mm[0])
66
+ if (d) follow.push(`${key}(${d[1].trim()})`)
67
+ }
68
+ const used = new Set()
69
+ let sets = 0
70
+ for (const a of src.matchAll(/\sdata-mock-(text|show|each|set|model|class|attr)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)) {
71
+ if (a[1].toLowerCase() === 'set') sets++
72
+ const v = (a[2] !== undefined ? a[2] : a[3] || '').replace(/'[^']*'|"[^"]*"/g, ' ')
73
+ for (const p of v.matchAll(/[A-Za-z_$\u4e00-\u9fa5][\w$\u4e00-\u9fa5]*(?:\.[\w$\u4e00-\u9fa5]+|\[\d+\])*/g)) if (topSet.has(p[0].split(/[.[]/)[0])) used.add(p[0])
74
+ }
75
+ if (used.size || sets) out.push(`- ${key}:用到 ${[...used].slice(0, 8).map((x) => `\`${x}\``).join('、') || '(只有改数据的按钮)'}${used.size > 8 ? ` 等 ${used.size} 个字段` : ''}${sets ? `;点了改数据 ${sets} 处` : ''}`)
76
+ }
77
+ if (follow.length) out.push(`- 状态跟着数据走的屏:${follow.slice(0, 8).join('、')}——这几屏的状态别放在页面自己里,读全局状态的那个字段(一处改了所有页一起变)。`)
78
+ return out
79
+ }
80
+
45
81
  export const HANDOFF_DIR = 'handoff'
46
82
  /** 版本名里哪些是用户在右侧栏亲手改的(见 core.js:改字、调样式、调节滑块) */
47
83
  const TUNED = /^(改字「|调样式「|调节:)/
@@ -624,6 +660,7 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
624
660
  // 一页多状态(#30):同一个页面的几种样子写在一个文件里,转代码时是一个组件带状态,不是几个页面
625
661
  const stLines = statesMd(htmlByKey, [...sheets, 'tokens.css'].map((n) => { try { return fs.readFileSync(path.join(root, n), 'utf8') } catch { return '' } }).join('\n'))
626
662
  if (stLines.length) lines.push(...stLines)
663
+ lines.push(...mockMd(htmlByKey, root))
627
664
  if ([...htmlByKey.values()].some((h) => /\sdata-back\b/i.test(slotHtml(h)))) lines.push('- 写了 `data-back` 的返回按钮:做成「返回上一页」(router.back() / navigation.goBack()),没有上一页时才去它写的 href。')
628
665
  if (hover) lines.push(`- 悬停 / 聚焦 / 按下的样式 ${hover} 处:照搬,别丢。`)
629
666
  if ([...htmlByKey.values()].some((h) => /prefers-color-scheme\s*:\s*dark|data-theme=["']?dark/.test(h)) || /\[data-theme=["']?dark/.test(Object.keys(tok).length ? fs.readFileSync(path.join(root, 'tokens.css'), 'utf8') : '')) lines.push('- 有深色样式:项目里也要能切(跟系统,或 `<html data-theme="dark">`)。')
package/lib/htmlpack.js CHANGED
@@ -12,9 +12,10 @@
12
12
  */
13
13
 
14
14
  import crypto from 'node:crypto'
15
- import { bundle, strictMeta } from './bundle.js'
15
+ import { bundle, dataAssets, strictMeta } from './bundle.js'
16
16
  import { defang } from './serve.js'
17
- import { statesOfHtml } from './states.js'
17
+ import { followsMock, statesOfHtml } from './states.js'
18
+ import { MOCK_FILE, mockExpr, mockOfBuf, mockRuntime } from './mock.js'
18
19
 
19
20
  /** 每屏的 <base>:一个不存在的地址(.invalid 不会被解析),屏里的相对链接都落在它下面,小脚本据此认出「站内跳转」 */
20
21
  export const PACK_ORIGIN = 'https://ddp-pack.invalid'
@@ -89,6 +90,9 @@ function storeShim(D) {
89
90
  try { void window[name].length } catch { broken = true }
90
91
  if (broken) { try { Object.defineProperty(window, name, { value: make(area), configurable: true }) } catch { /* 改不了就算了 */ } }
91
92
  }
93
+ // 模拟数据(#30):自己做的屏(和播放器同源、有真的 localStorage)和别人做的屏(沙盒、只有替身)存的地方不一样,
94
+ // 换屏会读不到上一屏改的。演示里的模拟数据一律存播放器手上这一份
95
+ try { Object.defineProperty(window, '__ddpMockStore', { value: make('m'), configurable: true }) } catch { /* 改不了就算了 */ }
92
96
  }
93
97
 
94
98
  /**
@@ -120,7 +124,7 @@ function navScript(C, ST) {
120
124
  return out.length >= 2 ? out : []
121
125
  }
122
126
  // 播放器只在这屏写了这个状态时才给(老页面自己拿 ?state= 当参数的给 '',完全不碰 data-state)
123
- if (typeof ST === 'string' && STATE_RE.test(ST)) de.setAttribute('data-state', ST)
127
+ if (typeof ST === 'string' && STATE_RE.test(ST)) { de.setAttribute('data-state', ST); window.__dshState = ST } // 模拟数据认它:状态跟着数据走的页,这一屏临时当成这个状态
124
128
  const stateOf = (u) => { const v = u.searchParams.get('state') || ''; return STATE_RE.test(v) ? v : '' }
125
129
 
126
130
  /** 这个地址是不是跳到演示包里的别的屏:{ path, hash };同一页(只有锚点)给 { same, hash };站外给 { out } */
@@ -140,7 +144,10 @@ function navScript(C, ST) {
140
144
  const raw0 = state
141
145
  if (u.pathname === here().pathname && state && !declared().includes(state)) state = ''
142
146
  // 回默认状态只认什么参数都不带的(?page=2 是页面自己的参数);已经在默认状态(播放器给的 ST 是空的)就不用回
143
- if (u.pathname === here().pathname && (state ? state === cur : raw0 || u.search || u.hash || /#$/.test(u.href) || !(typeof ST === 'string' && ST && ST === cur && declared().includes(ST) && ST !== declared()[0]))) return { same: true, hash: u.hash || (/#$/.test(u.href) ? '#' : '') }
147
+ // 状态跟着模拟数据走的屏:播放器点名过状态(哪怕是第一个),不带状态的本页链接 = 去掉点名、回到跟着数据
148
+ const follow = !!document.querySelector('meta[name="dsh-states"][data-mock]')
149
+ const named = typeof ST === 'string' && ST && declared().includes(ST) && (follow || (ST === cur && ST !== declared()[0]))
150
+ if (u.pathname === here().pathname && (state ? state === cur : raw0 || u.search || u.hash || /#$/.test(u.href) || !named)) return { same: true, hash: u.hash || (/#$/.test(u.href) ? '#' : '') }
144
151
  return { path: p, hash: u.hash, state }
145
152
  }
146
153
  const rawOf = (el) => {
@@ -342,14 +349,18 @@ function player() {
342
349
  if (!assets.has(i)) { const el = $('ddp-a-' + i); assets.set(i, el ? JSON.parse(el.textContent) : '') }
343
350
  return assets.get(i)
344
351
  }
345
- const store = { l: {}, s: {} }
352
+ const store = { l: {}, s: {}, m: {} }
346
353
  const htmlOf = (i, state = '') => {
347
354
  if (!cache.has(i)) {
348
355
  cache.set(i, JSON.parse($('ddp-s-' + i).textContent).replace(assetRe, (m, n) => asset(Number(n))))
349
356
  if (cache.size > 8) cache.delete(cache.keys().next().value) // 屏多、图大:只留最近放过的几屏
350
357
  }
351
358
  // 存储的初始内容:每次放进去都是当时的(上一屏刚存的这一屏读得到);状态(#30)也是放的时候才定
352
- const out = cache.get(i).replace(C.storeMark, () => JSON.stringify(store).replace(/</g, '\\u003c'))
359
+ let out = cache.get(i).replace(C.storeMark, () => JSON.stringify(store).replace(/</g, '\\u003c'))
360
+ // 模拟数据(#30):整套只存一份,放进 iframe 时才填进这屏
361
+ const js = (v) => JSON.stringify(v).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')
362
+ if (C.mockMark) out = out.split(C.mockMark).join(js(C.mock || {}))
363
+ if (C.mockAMark) out = out.split(C.mockAMark).join(js(C.mockAssets || null))
353
364
  const ok = /^[A-Za-z0-9_-]{1,32}$/.test(state) && (C.screens[i].states || []).includes(state) // 这屏写了的状态才设
354
365
  return C.stateMark ? out.split(C.stateMark).join(JSON.stringify(ok ? state : '')) : out
355
366
  }
@@ -512,8 +523,9 @@ function player() {
512
523
  const k = h ? C.screens.findIndex((s) => s.key === (m ? m[1] : h)) : -1
513
524
  return k >= 0 ? { i: k, state: m ? normState(k, m[2]) : '' } : { i: 0, state: '' }
514
525
  }
515
- // 默认状态写不写都是同一屏(order.html 和 order.html?state=default):统一成不写,返回的路才对得上
516
- const normState = (i, state) => (state && !(C.screens[i].states && C.screens[i].states[0] === state) ? state : '')
526
+ // 默认状态写不写都是同一屏(order.html 和 order.html?state=default):统一成不写,返回的路才对得上。
527
+ // 状态跟着模拟数据走的屏除外:不写是数据里那个,点名第一个要留着
528
+ const normState = (i, state) => (state && !(C.screens[i].states && C.screens[i].states[0] === state && !C.screens[i].follow) ? state : '')
517
529
  const hashOf = (i, state) => '#' + encodeURIComponent(C.screens[i].key) + (normState(i, state) ? '?state=' + state : '')
518
530
  // 走到第几步,记在这一条浏览器历史记录上:页面里的「返回」(data-back)有得退就是浏览器后退一步,
519
531
  // 和浏览器自己的后退、前进是同一份路(后退再前进也对得上)。记不了的(沙盒不给改历史)照老办法按 trail 退
@@ -569,7 +581,7 @@ function player() {
569
581
  if (i < 0) i = C.screens.findIndex((s) => s.key === k + '.html')
570
582
  if (i < 0) say(T.notIn.replace('{p}', k))
571
583
  else go(i, typeof d.hash === 'string' ? d.hash : '', typeof d.state === 'string' && /^[A-Za-z0-9_-]{1,32}$/.test(d.state) ? d.state : '')
572
- } else if (d.type === 'store' && (d.area === 'l' || d.area === 's')) {
584
+ } else if (d.type === 'store' && (d.area === 'l' || d.area === 's' || d.area === 'm')) {
573
585
  const m = store[d.area]
574
586
  if (d.op === 'set') m[String(d.k)] = String(d.v)
575
587
  else if (d.op === 'del') delete m[String(d.k)]
@@ -597,6 +609,20 @@ function player() {
597
609
  else document.documentElement.requestFullscreen().catch(() => {})
598
610
  })
599
611
  $('menu').addEventListener('click', () => document.body.classList.toggle('open'))
612
+ // 重置演示数据(有模拟数据才有这个按钮):演示里点过、填过的都回到开始,当前这屏重放一遍
613
+ if (C.mockMark) {
614
+ const rs = $('mreset')
615
+ rs.hidden = false
616
+ rs.addEventListener('click', () => {
617
+ const pfx = 'dsh-mock:' + C.mockScope + ':'
618
+ try { for (let i = localStorage.length - 1; i >= 0; i--) { const k = localStorage.key(i); if (k && k.startsWith(pfx)) localStorage.removeItem(k) } } catch { /* 存不了 */ }
619
+ for (const k of Object.keys(store.l)) if (k.startsWith(pfx)) delete store.l[k]
620
+ store.m = {}
621
+ document.body.classList.remove('open')
622
+ if (cur >= 0) show(cur, '', curState)
623
+ say(T.resetDone)
624
+ })
625
+ }
600
626
  document.addEventListener('fullscreenchange', () => { $('full').textContent = document.fullscreenElement ? T.exitFull : T.full })
601
627
  let wasCompact = compact()
602
628
  addEventListener('resize', () => {
@@ -608,8 +634,8 @@ function player() {
608
634
  }
609
635
 
610
636
  const STRINGS = {
611
- zh: { prev: '上一屏', next: '下一屏', shell: '外壳', shellTip: '套上手机 / 浏览器外壳', full: '全屏', exitFull: '退出全屏', of: '{i} / {n}', notIn: '这一屏不在演示里:{p}', menu: '换屏', screens: '选屏' },
612
- en: { prev: 'Previous', next: 'Next', shell: 'Device frame', shellTip: 'Show the phone / browser frame', full: 'Full screen', exitFull: 'Exit full screen', of: '{i} / {n}', notIn: 'This screen isn\'t in the demo: {p}', menu: 'Screens', screens: 'Pick a screen' },
637
+ zh: { prev: '上一屏', next: '下一屏', shell: '外壳', shellTip: '套上手机 / 浏览器外壳', full: '全屏', exitFull: '退出全屏', of: '{i} / {n}', notIn: '这一屏不在演示里:{p}', menu: '换屏', screens: '选屏', reset: '重置数据', resetTip: '演示里点过、填过的都回到开始', resetDone: '数据回到开始了' },
638
+ en: { prev: 'Previous', next: 'Next', shell: 'Device frame', shellTip: 'Show the phone / browser frame', full: 'Full screen', exitFull: 'Exit full screen', of: '{i} / {n}', notIn: 'This screen isn\'t in the demo: {p}', menu: 'Screens', screens: 'Pick a screen', reset: 'Reset data', resetTip: 'Undo everything tapped and typed in this demo', resetDone: 'Data is back to the start' },
613
639
  }
614
640
 
615
641
  const CSS = `
@@ -684,7 +710,7 @@ body.compact #menu{display:block;position:fixed;left:50%;top:calc(4px + env(safe
684
710
  * read(rel):设计目录里的文件(Buffer,读不到 null);strictOf(page):这屏是不是别人做的(加硬规矩:只跑我们的脚本)
685
711
  * 回 { html, missing: [没读到的屏], count }
686
712
  */
687
- export function buildPack({ screens, read, strictOf = () => false, kind, w, h, os = '', dark = false, scheme = 'light', tweak = null, title = '', lang = 'zh', fit = false }) {
713
+ export function buildPack({ screens, read, bigOf = null, strictOf = () => false, kind, w, h, os = '', dark = false, scheme = 'light', tweak = null, title = '', lang = 'zh', fit = false }) {
688
714
  kind = FRAME[kind] ? kind : 'web'
689
715
  const S = STRINGS[lang === 'en' ? 'en' : 'zh']
690
716
  const token = 'ddpA' + crypto.randomBytes(5).toString('hex') + '_'
@@ -695,6 +721,19 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
695
721
  const shimSrc = `(${storeShim})(${storeMark});`
696
722
  const stateMark = `/*ddpT${token}*/''` // 放一屏时换成这屏的状态(#30)
697
723
  const navSrc = (strict) => `(${navScript})(${JSON.stringify({ ...navCfg, strict })}, ${stateMark});`
724
+ // 模拟数据(#30):设计目录里有 mock.json 就每屏放运行时(在存储替身后面、跳屏监听前面:点了又改数据又跳屏的先存好),
725
+ // 数据本身整套只放一份在播放器的配置里,放一屏时填进记号那里
726
+ const mk = mockOfBuf(read(MOCK_FILE), !!(bigOf && bigOf(MOCK_FILE)))
727
+ // mock.json 太大没读:导出来的演示点了不会变——报错不导出(不悄悄给一个丢了数据的演示)
728
+ if (mk && /^big/.test(mk.fp)) { const e = new Error('mockTooBig'); e.code = 'mockTooBig'; throw e }
729
+ const mockMark = mk ? `/*ddpM${token}*/null` : ''
730
+ const mockScope = token.slice(0, -1)
731
+ const mockAMark = mk ? `/*ddpMA${token}*/null` : ''
732
+ const mockSrc = mk ? `(${mockRuntime})(${mockExpr},${JSON.stringify({ v: mk.fp, scope: mockScope, err: mk.err })},${mockMark},${mockAMark});` : ''
733
+ // 数据里写的本地图片(头像、商品图):演示是单个文件,没有设计目录可读——换成 data: 地址的表,整套只放一份
734
+ const mockOver = []
735
+ const mockAssets = mk ? dataAssets(mk.data, read, 60 * 1024 * 1024, mockOver, bigOf) : null
736
+ if (mockOver.length) { const e = new Error('imgTooBig'); e.code = 'imgTooBig'; throw e } // 数据里绑的图换不下:不悄悄留成坏图
698
737
  const mode = dark ? 'dark' : scheme === 'dark' ? 'media' : 'light'
699
738
  const schemeSrc = `(${schemeScript})(${JSON.stringify(mode)});`
700
739
 
@@ -703,7 +742,7 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
703
742
  const parts = []
704
743
  const list = []
705
744
  const missing = []
706
- let total = 0
745
+ let total = mk ? JSON.stringify(mk.data).length + JSON.stringify(mockAssets).length : 0
707
746
  for (const s of screens.slice(0, PACK_SCREENS)) {
708
747
  const page = read(s.key)
709
748
  if (!page) { missing.push(s.key); continue }
@@ -714,7 +753,7 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
714
753
  key: s.key,
715
754
  read,
716
755
  base,
717
- lead: (strict ? strictMeta(nonce) : '') + script(shimSrc + navSrc(strict), strict),
756
+ lead: (strict ? strictMeta(nonce) : '') + script(shimSrc + mockSrc + navSrc(strict), strict),
718
757
  tail: script(schemeSrc, strict),
719
758
  })
720
759
  // 大的 data: 地址(图片、字体、脚本)挪出来单独存,几屏共用的只存一份
@@ -728,7 +767,7 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
728
767
  if (total > PACK_MAX) { const e = new Error('tooBig'); e.code = 'tooBig'; throw e }
729
768
  parts.push(`<script type="application/json" id="ddp-s-${list.length}">${jsonTag(out)}</script>`)
730
769
  const states = statesOfHtml(text).map((x) => x.name) // 这屏写了哪几个状态(#30):放这屏时只设写了的
731
- list.push({ key: s.key, label: String(s.label || s.key).slice(0, 80), top: !!s.top, ...(strict ? { strict: true } : null), ...(states.length ? { states } : null) })
770
+ list.push({ key: s.key, label: String(s.label || s.key).slice(0, 80), top: !!s.top, ...(strict ? { strict: true } : null), ...(states.length ? { states } : null), ...(states.length && mk && followsMock(text) ? { follow: true } : null) })
732
771
  }
733
772
  if (!list.length) { const e = new Error('noScreens'); e.code = 'noScreens'; throw e }
734
773
 
@@ -740,6 +779,7 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
740
779
  // 网页默认不套浏览器框(铺满窗口),右侧栏开着「按画幅显示」的照它套着;手机、平板、桌面软件默认套着
741
780
  shellDefault: !!FRAMED[kind] && (kind !== 'web' || !!fit),
742
781
  screens: list, token, storeMark, stateMark, strings: S,
782
+ ...(mk ? { mockMark, mockAMark, mockScope, mock: mk.data, mockAssets } : null),
743
783
  }
744
784
  const docTitle = cfg.title || list[0].label
745
785
  const html = '<!doctype html>\n'
@@ -751,6 +791,7 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
751
791
  + `<select id="sel" aria-label="${escHtml(S.screens)}"></select>`
752
792
  + `<button id="next" class="arw" type="button" title="${escHtml(S.next)} (→)" aria-label="${escHtml(S.next)}">›</button><span id="count"></span></div>`
753
793
  + `<div class="end"><button id="shell" type="button" aria-pressed="false" title="${escHtml(S.shellTip)}">${escHtml(S.shell)}</button>`
794
+ + `<button id="mreset" type="button" hidden title="${escHtml(S.resetTip)}">${escHtml(S.reset)}</button>`
754
795
  + `<button id="full" type="button">${escHtml(S.full)}</button></div></header>`
755
796
  + `<main id="stage"></main><button id="menu" type="button" aria-label="${escHtml(S.menu)}">•••</button><div id="toast" role="status" hidden></div>`
756
797
  + `<script type="application/json" id="ddp-cfg">${jsonTag(cfg)}</script>`
package/lib/index.js CHANGED
@@ -52,7 +52,7 @@ import { fileURLToPath } from 'node:url'
52
52
  import os from 'node:os'
53
53
  import { execFile } from 'node:child_process'
54
54
  import { createHub, webOrigins, trustedOrigins, resolveInRoot, ERR_CATCHER, stateScript, defang } from './serve.js'
55
- import { bundle, inlinePicker, strictMeta, MAX_TOTAL as BUNDLE_MAX } from './bundle.js'
55
+ import { bundle, dataAssets, inlinePicker, strictMeta, MAX_TOTAL as BUNDLE_MAX } from './bundle.js'
56
56
  import { buildPack, PACK_SCREENS } from './htmlpack.js'
57
57
  import { createLibrary } from './works.js'
58
58
  import { createInspiration } from './inspire.js'
@@ -79,6 +79,7 @@ import { createImpl } from './impl.js'
79
79
  import { FRAMEWORKS, detectProject, projectFor, defaultFramework, buildHandoff, compareScreens, implUrl, implServe, defaultDest, pickedDest, within, pinRoots, frameCss } from './handoff.js'
80
80
  import { editsNotice, noticeMessage, langOf } from './edits.js'
81
81
  import { statesOfFile, expandStates, splitStateNames, withState } from './states.js'
82
+ import { MOCK_FILE, MOCK_MAX, mockOfBuf, mockScript, saveMock } from './mock.js'
82
83
  import { partDrift, formatDrift } from './drift.js'
83
84
 
84
85
  export const name = 'dsh-design-studio'
@@ -1183,6 +1184,20 @@ export function apply(ctx) {
1183
1184
  }
1184
1185
  }
1185
1186
 
1187
+ /** 「数据」面板的「存成初始数据」(#30):POST { session, root, data, fp } → 写回 mock.json(记一版、告诉模型用户改了) */
1188
+ async function mockSaveRoute(req, res) {
1189
+ if (!admit(req, res)) return
1190
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1191
+ let body
1192
+ try { body = await readBody(req, MOCK_MAX + 64 * 1024) } catch (e) { return json(res, 400, { error: e.message }) }
1193
+ try {
1194
+ const r = tracker.editDir(String(body.session || ''), (root) => saveMock(root, body.data, typeof body.fp === 'string' ? body.fp : ''), () => '模拟数据:存成初始数据', String(body.root || ''))
1195
+ json(res, 200, r)
1196
+ } catch (e) {
1197
+ json(res, 500, { error: e.message })
1198
+ }
1199
+ }
1200
+
1186
1201
  // ── 和做出来的比(#25)────────────────────────────────────────────────────
1187
1202
 
1188
1203
  /** 这个会话正在看的设计里有这一屏:{ snap, root },没有给 null */
@@ -1641,6 +1656,13 @@ export function apply(ctx) {
1641
1656
  function bundleFile(root, v, rel) {
1642
1657
  let f = ''
1643
1658
  if (v) f = history.fileOf(root, v, rel) || ''
1659
+ // 模拟数据和预览一个规矩(serve.js versionMock / mockOf):旧版本只认那一版自己的 mock.json(那版没有就是没有,
1660
+ // 不拿现在的顶上);现在的是软链接就当没有
1661
+ if (rel === MOCK_FILE) {
1662
+ if (v) return f
1663
+ const p = path.join(root, MOCK_FILE)
1664
+ try { return fs.lstatSync(p).isFile() ? p : '' } catch { return '' }
1665
+ }
1644
1666
  if (!f) {
1645
1667
  const hit = resolveInRoot(root, '/' + rel.split('/').map(encodeURIComponent).join('/'))
1646
1668
  f = hit && hit.real ? hit.real : ''
@@ -1706,10 +1728,12 @@ export function apply(ctx) {
1706
1728
  // 打的是哪个目标:右侧栏拿它核对,请求发出后会话换了目录(或预览服务器换了端口)的回包不存进它的缓存
1707
1729
  const whose = { root: t.root, origin: st.origin || '' }
1708
1730
  // 先看大小,太大的不读(打包总量也封顶,见 bundle.js)
1731
+ const big = new Set() // 有、但太大没读的
1709
1732
  const readRel = (rel) => {
1710
1733
  const f = bundleFile(t.root, v, rel)
1711
1734
  if (!f) return null
1712
1735
  const s = fs.statSync(f)
1736
+ if (s.isFile() && s.size > BUNDLE_MAX) big.add(rel)
1713
1737
  return s.isFile() && s.size <= BUNDLE_MAX ? fs.readFileSync(f) : null
1714
1738
  }
1715
1739
  // 别人做的设计(设计库来的、没改过):加硬规矩,右侧栏的沙盒也不放行表单
@@ -1746,7 +1770,15 @@ export function apply(ctx) {
1746
1770
  const nonce = strict ? crypto.randomBytes(16).toString('base64') : ''
1747
1771
  // 页面写了这个状态才设(老页面自己拿 ?state= 当参数的不动)
1748
1772
  const setState = state ? stateScript(page.toString('utf8'), '?state=' + state) : ''
1749
- const lead = strict ? strictMeta(nonce) + (ERR_CATCHER + setState).replaceAll('<script>', `<script nonce="${nonce}">`) : ERR_CATCHER + setState
1773
+ // 模拟数据(#30):读 mock.json 也记进用到的文件(改了就重新打包);存的键按设计目录分开(右侧栏同一个源里放着几套设计)
1774
+ const mk = mockOfBuf(read(MOCK_FILE), big.has(MOCK_FILE)) // 太大的:和预览一样带上运行时、报「太大」
1775
+ // 数据里写的本地图片:远程那边够不着预览地址,和页面里的图一样换成 data: 地址
1776
+ const over = []
1777
+ const mockAssets = mk ? dataAssets(mk.data, read, BUNDLE_MAX, over, (rel) => big.has(rel)) : null
1778
+ // 换不下的图(太大):不悄悄留成坏图,报进这屏的页面错误(体检、屏上看得到)
1779
+ const mockErr = mk ? [mk.err, over.length ? `数据里的图太大,远程看时没带上:${over.slice(0, 3).join('、')}${over.length > 3 ? ' 等' : ''}` : ''].filter(Boolean).join(';') : ''
1780
+ const mockTag = mk ? mockScript({ ...mk, assets: mockAssets, err: mockErr }, { scope: crypto.createHash('sha1').update(t.root).digest('hex').slice(0, 10) }) : ''
1781
+ const lead = strict ? strictMeta(nonce) + (ERR_CATCHER + setState + mockTag).replaceAll('<script>', `<script nonce="${nonce}">`) : ERR_CATCHER + setState + mockTag
1750
1782
  let html = bundle(strict ? defang(page.toString('utf8')) : page.toString('utf8'), { key, read, base: href, lead, tail: inlinePicker(fs.readFileSync(PICKER_FILE, 'utf8'), parent, href, nonce) })
1751
1783
  // 打包后图片变成 data: 地址,文件名没了:把用到的 AI 示意图记在页面里,导出时照样提醒
1752
1784
  const aiNames = [...deps].filter((x) => isPhotoAsset(x)).map((x) => path.basename(x))
@@ -1969,16 +2001,18 @@ export function apply(ctx) {
1969
2001
  function packDesign(root, v, params) {
1970
2002
  const deps = new Set()
1971
2003
  const files = new Set()
2004
+ const big = new Set() // 有、但太大没读的(数据里绑的图读不了要报出来,不能当没有)
1972
2005
  const read = (rel) => {
1973
2006
  deps.add(rel)
1974
2007
  const f = bundleFile(root, v, rel)
1975
2008
  files.add(f || path.join(root, ...rel.split('/')))
1976
2009
  if (!f) return null
1977
2010
  const s = fs.statSync(f)
2011
+ if (s.isFile() && s.size > BUNDLE_MAX) big.add(rel)
1978
2012
  return s.isFile() && s.size <= BUNDLE_MAX ? fs.readFileSync(f) : null
1979
2013
  }
1980
2014
  const strictOf = (page) => library.strictHtml(page) || market.strictHtml(page) || (v > 0 && library.strictVersions(root))
1981
- const pack = buildPack({ ...params, read, strictOf })
2015
+ const pack = buildPack({ ...params, read, bigOf: (rel) => big.has(rel), strictOf })
1982
2016
  return { pack, deps, files: [...files] }
1983
2017
  }
1984
2018
 
@@ -2168,7 +2202,7 @@ export function apply(ctx) {
2168
2202
  })
2169
2203
  const mk = createMarketRoutes({ admit, readBody, json, tracker, library, market, open, systemsDir: SYSTEMS_DIR, log, sessionCwd })
2170
2204
 
2171
- const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, verthumb: canvasThumbs.verRoute, pack: lib.pack, usezip: lib.usezip, ghauth: lib.ghauth, submit: lib.submit, inspire: lib.inspire, inspimg: lib.inspimg, ...mk, state, open: openRoute, view: viewRoute, close: closeRoute, history: historyRoute, restore: restoreRoute, hidden: hiddenRoute, edit: editRoute, style: styleRoute, sharecheck: shareCheckRoute, drift: driftRoute, states: statesRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, htmlpack: htmlPackRoute, pubshare: pubShareRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute, impl: implRoute, implcmp: implCmpRoute, implshot: implShotRoute }
2205
+ const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, verthumb: canvasThumbs.verRoute, pack: lib.pack, usezip: lib.usezip, ghauth: lib.ghauth, submit: lib.submit, inspire: lib.inspire, inspimg: lib.inspimg, ...mk, state, open: openRoute, view: viewRoute, close: closeRoute, history: historyRoute, restore: restoreRoute, hidden: hiddenRoute, edit: editRoute, style: styleRoute, sharecheck: shareCheckRoute, drift: driftRoute, states: statesRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, htmlpack: htmlPackRoute, pubshare: pubShareRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, mocksave: mockSaveRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute, impl: implRoute, implcmp: implCmpRoute, implshot: implShotRoute }
2172
2206
  for (const [key, handler] of Object.entries(routes)) {
2173
2207
  ctx.effect(() => ctx.webServer.register({
2174
2208
  kind: 'exact',
package/lib/look.js CHANGED
@@ -420,7 +420,7 @@ export async function cropIssues(browser, rows, { screens, dark, kind = '', max
420
420
  const TYPE = {
421
421
  hscroll: '超出屏幕', clipped: '文字被截断', overflow: '文字超出框', overlap: '文字叠在一起', contrast: '对比度不够', tap: '点击区太小',
422
422
  tiny: '字太小', img: '图片没加载出来', fonts: '字号太杂', distort: '图片被拉变形', long: '一行太长', wrap: '文字被挤断行',
423
- covered: '被固定栏压住', tight: '离固定栏太近', jserr: '页面脚本报错', missing: '文件没载出来', deadlink: '跳到的页面不存在',
423
+ covered: '被固定栏压住', tight: '离固定栏太近', jserr: '页面脚本报错', missing: '文件没载出来', deadlink: '跳到的页面不存在', mockmiss: '模拟数据里没有这个字段',
424
424
  capsule: '被小程序胶囊挡住', island: '被灵动岛挡住', homebar: '伸进底部横条区', tabbar: '标签栏项太多', navbar: '没有导航栏',
425
425
  winctl: '被窗口按钮挡住', dgsize: '图比画幅大', dgli: '导图节点写法不对', dgmany: '一层放太多', dgbar: '横条超出时间轴', dgtext: '节点字太多', dgsmall: '字偏小', dglink: '箭头没对着模块', frame: '外框被改动',
426
426
  }
@@ -474,6 +474,7 @@ export function detailOf(it) {
474
474
  : `伸进左上角红绿灯 ${it.px}px(外框画的、盖在页面上面,在 x 20–72、y 20–32:工具栏 / 侧栏顶上左边空出 80px,标题、按钮从 x 80 以后放)`
475
475
  case 'jserr': return `${it.msg}${it.src ? `(${it.src}${it.line ? `:${it.line}` : ''})` : ''}`
476
476
  case 'missing': return `${WHAT[it.what] || '文件'} ${it.src} 载不出来(路径写错了,或者文件不在)`
477
+ case 'mockmiss': return `用到了 ${it.paths},mock.json 里没有(显示出来是空的):拼错了就改对,漏写了就补进 mock.json`
477
478
  case 'frame': {
478
479
  const dsh = /^dsh\//.test(String(it.frame || ''))
479
480
  const from = dsh ? '技能目录 frames/dsh/' : '外框库(~/.dsh/design-frames/)'