dsh-design-studio 1.0.2 → 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/picker.js CHANGED
@@ -1308,6 +1308,13 @@
1308
1308
  return de.scrollWidth > Math.max(innerWidth, right + scrollX) + 40 || de.scrollHeight > Math.max(innerHeight, bottom + scrollY) + 40 ? 0 : [w, h]
1309
1309
  }
1310
1310
 
1311
+ /** 这一屏写了哪几个状态(<meta name="dsh-states">,原样给右侧栏解析)、现在是哪个 */
1312
+ function statesNow() {
1313
+ const m = document.querySelector('meta[name="dsh-states"]')
1314
+ // 状态跟着模拟数据走的页:前面加一行「#mock」告诉右侧栏(解析状态时这行不算),点名第一个状态不能当成「没写」
1315
+ return m ? { states: ((m.hasAttribute('data-mock') ? '#mock\n' : '') + String(m.getAttribute('content') || '')).slice(0, 400), state: curState() } : {}
1316
+ }
1317
+
1311
1318
  function boot(seed) {
1312
1319
  if (booted) return
1313
1320
  booted = true
@@ -1322,6 +1329,7 @@
1322
1329
  err: err ? String(err.getAttribute('content') || 'missing').slice(0, 20) : '',
1323
1330
  href: here(),
1324
1331
  meta: meta ? String(meta.getAttribute('content') || '').slice(0, 80) : '',
1332
+ ...statesNow(),
1325
1333
  tokens: tokensOf(),
1326
1334
  links: firstLinks(),
1327
1335
  dark: hasDark(),
@@ -1634,6 +1642,8 @@
1634
1642
  const normWs = (x) => String(x || '').replace(/[\s\u00a0]+/g, ' ').trim()
1635
1643
  const NO_TEXT = /^(SCRIPT|STYLE|TEXTAREA|NOSCRIPT|TEMPLATE|TITLE)$/
1636
1644
  let textEdit = false
1645
+ // 模拟数据(mock.js)问:选取、改字、调样式开着时点页面是在选东西,别改数据
1646
+ try { Object.defineProperty(window, '__ddpBusy', { value: () => picking || textEdit || styleOn, configurable: true }) } catch { /* 页面占了 */ }
1637
1647
  let editUi = null
1638
1648
  let editing = null // { span, node, before, nth }
1639
1649
  let editLang = 'zh'
@@ -1825,20 +1835,60 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1825
1835
  const LINK_JS = /(?:location(?:\.href)?\s*=\s*|location\.(?:assign|replace)\(\s*)['"]([^'"]+)['"]/
1826
1836
  const MAX_LINKS = 60
1827
1837
 
1828
- /** 这个元素点了会跳到同一个站点的哪一页(路径);不是跳页的给 '' */
1829
- function linkPath(el) {
1838
+ // 一页多状态(#30):<html data-state="paid">,地址 order.html?state=paid 打开那个状态。状态名只认这种写法(和 serve.js 设状态的那段一样)
1839
+ const STATE_RE = /^[A-Za-z0-9_-]{1,32}$/
1840
+ const stateOfUrl = (u) => { const s = u.searchParams.get('state'); return s && STATE_RE.test(s) ? s : '' }
1841
+ const curState = () => document.documentElement.getAttribute('data-state') || ''
1842
+ /** 现在是不是在写了的状态里、又不是默认(第一个)那个 */
1843
+ const offDefault = () => { const d = declaredStates(); const c = curState(); return !!c && d.length > 0 && d.includes(c) && c !== d[0] }
1844
+ /** 这页 <meta name="dsh-states"> 里写了哪几个状态(不到两个当没写;和 states.js 的 parseStates 一个规矩) */
1845
+ const declaredStates = () => {
1846
+ const m = document.querySelector('meta[name="dsh-states"]')
1847
+ const out = []
1848
+ for (const part of String((m && m.getAttribute('content')) || '').split(/[,,;;\n]+/)) {
1849
+ const x = /^\s*([A-Za-z0-9_-]{1,32})/.exec(part)
1850
+ if (x && !out.includes(x[1])) out.push(x[1])
1851
+ if (out.length >= 8) break
1852
+ }
1853
+ return out.length >= 2 ? out : []
1854
+ }
1855
+
1856
+ /** 这个元素点了去哪:{ path, state, back };不是跳页的给 null。
1857
+ * path:同一个站点的哪一页;state:带了 ?state= 就是那个状态;同一页换个状态也算跳(返回能退回来)。
1858
+ * back:写了 data-back(返回上一屏:试用、远程看按走过的路退一步,没得退才去 href) */
1859
+ function linkTo(el) {
1830
1860
  let raw = el.getAttribute('href') || el.getAttribute('data-href') || el.getAttribute('data-to') || ''
1831
1861
  if (!raw && el.hasAttribute('onclick')) {
1832
1862
  const m = LINK_JS.exec(el.getAttribute('onclick') || '')
1833
1863
  if (m) raw = m[1]
1834
1864
  }
1835
1865
  raw = raw.trim()
1836
- if (!raw || raw.startsWith('#') || /^(javascript|mailto|tel|sms|data):/i.test(raw)) return ''
1866
+ const back = el.hasAttribute('data-back')
1867
+ if (!raw || raw.startsWith('#') || /^(javascript|mailto|tel|sms|data):/i.test(raw)) return back ? { path: '', state: '', back } : null
1837
1868
  let u
1838
- try { u = new URL(raw, here()) } catch { return '' }
1869
+ try { u = new URL(raw, here()) } catch { return back ? { path: '', state: '', back } : null }
1839
1870
  const me = hereUrl()
1840
- if (u.origin !== me.origin || u.pathname === me.pathname) return ''
1841
- try { return decodeURIComponent(u.pathname) } catch { return u.pathname }
1871
+ if (u.origin !== me.origin) return back ? { path: '', state: '', back } : null
1872
+ let state = stateOfUrl(u)
1873
+ // 同一页:换个这页写了的状态算跳(没写的:老页面自己拿 ?state= 当参数,和以前一样当本页链接);
1874
+ // 在别的状态里点指着本页、不带状态也不带锚点的链接(href="order.html")= 回默认状态,也算跳
1875
+ // 回默认状态只认什么参数都不带的(?page=2 这种是页面自己的参数,照常当本页链接)
1876
+ if (u.pathname === me.pathname) {
1877
+ if (state && !declaredStates().includes(state)) state = ''
1878
+ // 状态跟着模拟数据走的页:「回默认」= 去掉点名的状态、回到跟着数据——地址里点名了才算跳,没点名(已经跟着数据)当本页链接
1879
+ const follow = !!document.querySelector('meta[name="dsh-states"][data-mock]')
1880
+ if (state ? state === curState() : u.search || u.hash || /#$/.test(raw) || (follow ? !declaredStates().includes(me.searchParams ? stateOfUrl(me) : '') : !offDefault())) return back ? { path: '', state: '', back } : null
1881
+ }
1882
+ let path = u.pathname
1883
+ try { path = decodeURIComponent(u.pathname) } catch { /* 原样 */ }
1884
+ // more:除了 state 还带了别的参数(?state=paid&page=2)
1885
+ return { path, state, back, hash: u.hash, more: [...u.searchParams.keys()].some((k) => k !== 'state') }
1886
+ }
1887
+
1888
+ /** 这个元素点了会跳到同一个站点的哪一页(路径);不是跳页的给 '' */
1889
+ function linkPath(el) {
1890
+ const l = linkTo(el)
1891
+ return l ? l.path : ''
1842
1892
  }
1843
1893
 
1844
1894
  const LINK_SEL = 'a[href], [data-href], [data-to], [onclick]'
@@ -1860,7 +1910,8 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1860
1910
  for (const el of document.querySelectorAll(LINK_SEL)) {
1861
1911
  if (out.length >= MAX_LINKS) break
1862
1912
  if (host && host.contains(el)) continue
1863
- const p = linkPath(el)
1913
+ const lk = linkTo(el)
1914
+ const p = lk ? lk.path : ''
1864
1915
  if (!p) continue
1865
1916
  const r = el.getBoundingClientRect()
1866
1917
  if (r.width < 2 || r.height < 2) continue
@@ -1871,12 +1922,12 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1871
1922
  // 被固定的底栏 / 顶栏盖住的按钮(滚到它下面了)看不见,画布上别从它出线
1872
1923
  const top = shown ? document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2) : null
1873
1924
  if (top && top !== el && !el.contains(top) && !(host && host.contains(top))) continue
1874
- const k = p + '|' + Math.round(r.left / 8) + '|' + Math.round(r.top / 8)
1925
+ const k = p + '?' + lk.state + '|' + Math.round(r.left / 8) + '|' + Math.round(r.top / 8)
1875
1926
  if (seen.has(k)) continue
1876
1927
  seen.add(k)
1877
1928
  const text = clip(String(el.innerText || el.getAttribute('aria-label') || el.getAttribute('title') || '').replace(/\s+/g, ' ').trim(), 24)
1878
1929
  const barDy = bars && bars.size ? barDyOf(el, bars) : undefined
1879
- out.push({ path: p, x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.width), h: Math.round(r.height), text, ...(barDy === undefined ? null : { barDy }) })
1930
+ out.push({ path: p, x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.width), h: Math.round(r.height), text, ...(barDy === undefined ? null : { barDy }), ...(lk.state ? { state: lk.state } : null) })
1880
1931
  }
1881
1932
  return out
1882
1933
  }
@@ -1933,21 +1984,87 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1933
1984
  // 演示:点了跳页的地方,不在 iframe 里直接跳,告诉右侧栏换一屏(带过场动画)
1934
1985
  // 远程看也是:沙盒里的页面跳不过去(地址指着电脑本机),由右侧栏打包那一页换上来
1935
1986
  let demo = false
1987
+ // 单看时点了「同一页换个状态」的链接(#30):不在 iframe 里自己跳,告诉右侧栏换状态(屏名旁的「状态 ▾」跟着变)。
1988
+ // 右侧栏说了认这个(init 里 stateNav 是它让这一帧显示的那一页的路径)才拦:别的看法(对比、多尺寸)照常让页面自己跳;
1989
+ // 在这一帧里点链接去了别的页(单看时可以):那页不归顶栏的状态菜单管,也让页面自己跳。
1990
+ // 没写 dsh-states、或者写的状态里没有这个的(老页面自己拿 ?state= 当筛选参数):照常跳,不拦
1991
+ let stateNav = ''
1992
+ // 页面自己的点击处理先跑完(「没勾同意不让付款」会拦默认行为):排到 window 上最后一个再看,拦了就随页面
1993
+ let stateWant = null
1994
+ /** 这个链接是不是本页换状态、交给右侧栏换:{ to, def, hash };不是给 null。
1995
+ * 只认真的 <a href>(onclick / data-href 里的地址由页面自己的脚本决定跳不跳,猜不准就随页面),
1996
+ * 除了 state 还带别的参数的(?state=paid&page=2)也随页面——右侧栏换状态只认状态,别的参数会丢 */
1997
+ const stateLink = (el) => {
1998
+ // 开新窗口的(target="_blank")随页面:不是在这一帧里换
1999
+ const l = el && el.isConnected && el.matches('a[href]') && !(el.target && el.target !== '_self') ? linkTo(el) : null
2000
+ let me = hereUrl().pathname
2001
+ try { me = decodeURIComponent(me) } catch { /* 原样 */ }
2002
+ if (!l || l.back || l.more || l.path !== me || me !== stateNav) return null
2003
+ const hash = /^#[^\s#]{1,200}$/.test(l.hash || '') ? l.hash : ''
2004
+ const d = declaredStates()
2005
+ // 状态跟着模拟数据走的页:不带状态的链接(「首页」)= 回到跟着数据——右侧栏点名过状态就去掉(clear),没点名就随页面自己跳;
2006
+ // 点名第一个状态(?state=第一个)才是点名,不是「回默认」
2007
+ if (document.querySelector('meta[name="dsh-states"][data-mock]')) {
2008
+ if (!l.state) { let had = ''; try { had = hereUrl().searchParams.get('state') || '' } catch { had = '' } return had && d.includes(had) ? { to: '', def: true, clear: true, hash } : null }
2009
+ return d.includes(l.state) ? { to: l.state, def: false, hash } : null
2010
+ }
2011
+ // 换到写了的某个状态;在别的状态里点指着本页、什么都不带的链接 = 回默认状态(顶栏的状态标签也跟着回去)
2012
+ const to = l.state || (offDefault() ? d[0] : '')
2013
+ if (!to || !d.includes(to)) return null
2014
+ return { to, def: to === d[0], hash }
2015
+ }
2016
+ const stateLast = (e) => {
2017
+ removeEventListener('click', stateLast)
2018
+ const w = stateWant
2019
+ stateWant = null
2020
+ if (!w || w.e !== e || e.defaultPrevented) return
2021
+ // 页面的点击处理跑完再看一遍(「去结算」点的时候才改 href):按那时的地址
2022
+ const g = stateLink(w.el)
2023
+ if (!g) return
2024
+ e.preventDefault()
2025
+ // def:要的是默认状态(右侧栏没记默认那个的名字);hash:链接里的锚点(order.html?state=paid#receipt),换好状态滚过去
2026
+ post({ type: 'stateGo', state: g.to, def: g.def, ...(g.clear ? { clear: true } : null), ...(g.hash ? { hash: g.hash } : null) })
2027
+ }
2028
+ addEventListener('click', (e) => {
2029
+ stateWant = null
2030
+ if (!stateNav || demo || HERE || picking || textEdit || styleOn || !parentWin) return
2031
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return
2032
+ const el = e.target && e.target.closest ? e.target.closest('a[href]') : null
2033
+ if (!el || !stateLink(el)) return
2034
+ stateWant = { e, el }
2035
+ removeEventListener('click', stateLast)
2036
+ addEventListener('click', stateLast)
2037
+ }, true)
1936
2038
  addEventListener('click', (e) => {
1937
2039
  if ((!demo && !HERE) || picking) return
1938
- const el = e.target && e.target.closest ? e.target.closest(LINK_SEL) : null
2040
+ const el = e.target && e.target.closest ? e.target.closest(LINK_SEL + ', [data-back]') : null
1939
2041
  if (!el) return
1940
- const p = linkPath(el)
1941
- if (!p) {
2042
+ const l = linkTo(el)
2043
+ if (!l) {
1942
2044
  const raw = String(el.getAttribute('href') || '').trim()
1943
2045
  if (HERE && raw.startsWith('#')) { e.preventDefault(); jumpTo(raw) }
1944
2046
  return
1945
2047
  }
1946
2048
  e.preventDefault()
1947
2049
  e.stopPropagation()
1948
- post({ type: 'nav', path: p })
2050
+ post({ type: 'nav', path: l.path, ...(l.state ? { state: l.state } : null), ...(l.back ? { back: true } : null), ...(/^#[^\s#]{1,200}$/.test(l.hash || '') ? { hash: l.hash } : null) })
1949
2051
  }, true)
1950
2052
 
2053
+ // 手机扫码看、在浏览器里直接打开(没有右侧栏):返回(data-back)就是浏览器的后退——从哪来回哪去;
2054
+ // 没有上一页(扫码直接进的这一屏)才照 href 走。在别人的页面里嵌着时不动(别把人家的页面往回退)
2055
+ if (!parentWin && window.top === window) {
2056
+ addEventListener('click', (e) => {
2057
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return
2058
+ const el = e.target && e.target.closest ? e.target.closest('[data-back]') : null
2059
+ if (!el) return
2060
+ let prev = null
2061
+ try { prev = document.referrer ? new URL(document.referrer) : null } catch { prev = null }
2062
+ if (history.length < 2 || !prev || prev.origin !== location.origin) return
2063
+ e.preventDefault()
2064
+ history.back()
2065
+ })
2066
+ }
2067
+
1951
2068
  /** 页内锚点(远程看时 <base> 指着原地址,#xx 会被当成跳到别的页面) */
1952
2069
  function jumpTo(hash) {
1953
2070
  let id = String(hash || '').replace(/^#/, '')
@@ -1966,10 +2083,13 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1966
2083
  const me = hereUrl()
1967
2084
  if (u.origin !== me.origin) return // 外网地址:随它
1968
2085
  e.preventDefault()
1969
- if (u.pathname === me.pathname) { if (u.hash) jumpTo(u.hash); return }
2086
+ let state = stateOfUrl(u)
2087
+ // 同一页换个这页没写的状态(老页面自己拿 ?state= 当参数):和以前一样不动(不重新打包这一页)
2088
+ if (u.pathname === me.pathname && state && !declaredStates().includes(state)) state = ''
2089
+ if (u.pathname === me.pathname && (!state || state === curState())) { if (u.hash) jumpTo(u.hash); return }
1970
2090
  let p = u.pathname
1971
2091
  try { p = decodeURIComponent(p) } catch { /* 原样 */ }
1972
- post({ type: 'nav', path: p })
2092
+ post({ type: 'nav', path: p, ...(state ? { state } : null) })
1973
2093
  })
1974
2094
  }
1975
2095
 
@@ -2802,6 +2922,7 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
2802
2922
  // hscroll 超出屏幕(会横向滚动 / 被切掉) · clipped 文字被截断 · overflow 文字超出框 · overlap 文字叠在一起
2803
2923
  // contrast 对比度不够 · tap 点击区太小 · tiny 字太小 · img 图片没加载出来 · fonts 字号太杂
2804
2924
  // covered 被固定栏压住(滚到底也看不全) · tight 离固定栏太近 · jserr 页面脚本报错 · missing 样式表 / 脚本 / 字体没载出来
2925
+ // mockmiss 页面用到的字段模拟数据里没有
2805
2926
  // capsule 小程序右上角的胶囊(微信画的,页面盖不住)挡住了字或按钮
2806
2927
  // island 灵动岛挡住了字或按钮 · homebar 底栏里的字、图标伸进底部横条区 · tabbar 标签栏超过 5 项 · navbar 小程序这屏没有导航栏
2807
2928
  // winctl 桌面软件的窗口按钮(Mac 红绿灯 / Windows 右上角三个)挡住了字或按钮
@@ -3601,6 +3722,9 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
3601
3722
  add('jserr', null, { msg: String(e.msg || '').slice(0, 160), src: relOf(e.src || '') || '', line: e.line || 0 }, 2)
3602
3723
  }
3603
3724
  }
3725
+ // 12b. 模拟数据(#30):页面里用到、mock.json 里没有的字段(拼错了、漏写了;显示出来是空的)
3726
+ const miss = Array.isArray(window.__dshMockMissing) ? window.__dshMockMissing.filter((x) => typeof x === 'string').slice(0, 6) : []
3727
+ if (miss.length) add('mockmiss', null, { paths: miss.map((x) => x.slice(0, 60)).join('、') }, 1)
3604
3728
  try {
3605
3729
  for (const f of document.fonts || []) if (f.status === 'error') add('missing', null, { what: 'font', src: String(f.family || '').replace(/['"]/g, '') }, 1)
3606
3730
  } catch { /* 老浏览器 */ }
@@ -4075,6 +4199,8 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
4075
4199
  if (prop === 'transform') return String(b).startsWith('~') ? sameMatrix(a, String(b).slice(1), true) : sameMatrix(a, b)
4076
4200
  // 引用外部文件的(fill: url("assets/paint.svg#g")、filter: url("assets/fx.svg#f")):外框库和设计目录端口不一样,地址按路径 + 片段比
4077
4201
  if (/^(fill|stroke|filter|backdrop-filter|clip-path|marker-start|marker-mid|marker-end)$/.test(prop) && /url\(/.test(a + b)) return sameUrls(a, b)
4202
+ // 新版 Chrome 有时把 flex-end / flex-start 报成 flow-end / flow-start(同一个浏览器开两次都可能不一样):同一个意思
4203
+ if (/^(justify|align)-(content|items|self)$/.test(prop)) { const n = (v) => String(v).replace(/\bflow-(start|end)\b/g, 'flex-$1'); if (n(a) === n(b)) return true }
4078
4204
  if (/^(box-shadow|text-shadow|filter|backdrop-filter|clip-path|z-index|order|flex-grow|flex-shrink|scale|rotate)$/.test(prop)) return false // 阴影、滤镜里有颜色又有长度,照字比
4079
4205
  if (prop === 'fill' || prop === 'stroke') { if (/none|url\(/.test(a + b)) return false } else if (!/color$/.test(prop)) return samePx(a, b, prop)
4080
4206
  const tmp = document.createElement('dsh-design-norm')
@@ -5628,7 +5754,7 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
5628
5754
  if (!d || d.dshDesign !== 1) return
5629
5755
  if (d.type === 'pick') start(d.hint !== false)
5630
5756
  else if (d.type === 'cancel') { if (!styleOn) stop(true) }
5631
- else if (d.type === 'init') { if (d.relay) relay(); boot(d.seed || null) }
5757
+ else if (d.type === 'init') { if (d.relay) relay(); stateNav = typeof d.stateNav === 'string' ? d.stateNav : ''; boot(d.seed || null) }
5632
5758
  else if (d.type === 'files') { relay(); onFiles(String(d.file || ''), Array.isArray(d.files) ? d.files : null) }
5633
5759
  else if (d.type === 'reveal') reveal(d)
5634
5760
  else if (d.type === 'zoom') setK(1 / (Number(d.z) || 1))
package/lib/serve.js CHANGED
@@ -20,6 +20,8 @@ import path from 'node:path'
20
20
  import { fileURLToPath } from 'node:url'
21
21
  import { tokenize } from './gallery/html.js'
22
22
  import { FRAME_MAIN, SLOT_BOX } from './slot.js'
23
+ import { STATE_RE, statesOfHtml } from './states.js'
24
+ import { MOCK_FILE, MOCK_MAX, mockOf, mockScript, mockBridge, parseMock } from './mock.js'
23
25
 
24
26
  export const INTERNAL = '/__dsh_design__/'
25
27
  const PICKER_FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), 'picker.js')
@@ -87,6 +89,18 @@ export const ERR_CATCHER = '<script>(()=>{if(window.__dshErrs)return;const L=win
87
89
  'else add({msg:String(e.message||"").slice(0,300),src:String(e.filename||"").slice(0,300),line:e.lineno||0})},true);' +
88
90
  'addEventListener("unhandledrejection",(e)=>{const r=e.reason;add({msg:String((r&&r.message)||r).slice(0,300),src:"",line:0})})})()</script>'
89
91
 
92
+ /**
93
+ * 一页多状态(#30):地址带 ?state=paid、页面 <meta name="dsh-states"> 里写了 paid → 开画前把 <html data-state> 设成它(不闪默认状态)。
94
+ * 页面没写这个状态(老页面自己拿 ?state= 当参数)给 '':完全不碰页面的 data-state
95
+ */
96
+ export function stateScript(html, url) {
97
+ let s = ''
98
+ try { s = new URL(String(url || ''), 'http://x').searchParams.get('state') || '' } catch { return '' }
99
+ if (!STATE_RE.test(s) || !statesOfHtml(html).some((x) => x.name === s)) return ''
100
+ // window.__dshState:模拟数据(mock.js)认它——这页状态跟着数据走时,这一屏临时当成这个状态
101
+ return `<script>document.documentElement.setAttribute("data-state","${s}");window.__dshState="${s}"</script>`
102
+ }
103
+
90
104
  /** 放进 <head> 最前面;没写 <head> 就放在 <html> / <!doctype> 后面(放到 doctype 前面页面会进怪异模式) */
91
105
  export function headInsert(html, tag) {
92
106
  const m = /<head\b[^>]*>/i.exec(html) || /<html\b[^>]*>/i.exec(html) || /^\s*<!doctype\b[^>]*>/i.exec(html)
@@ -97,11 +111,13 @@ export function headInsert(html, tag) {
97
111
  * 在 </body> 前(没有就在末尾)插入选取脚本,<head> 最前面放报错记录。
98
112
  * nonce:别人做的设计(设计库来的)加了「只准带这个记号的脚本跑」的规矩,我们自己的两段脚本带上它;data-strict 让 picker 拦外链
99
113
  */
100
- export function injectPicker(html, { nonce = '' } = {}) {
114
+ export function injectPicker(html, { nonce = '', url = '', mock = null } = {}) {
101
115
  const n = nonce ? ` nonce="${nonce}"` : ''
102
116
  const tag = `<script src="${INTERNAL}picker.js"${n}${nonce ? ' data-strict="1"' : ''}></script>`
103
117
  const i = html.toLowerCase().lastIndexOf('</body>')
104
- return headInsert(i >= 0 ? html.slice(0, i) + tag + html.slice(i) : html + tag, nonce ? ERR_CATCHER.replace('<script>', `<script${n}>`) : ERR_CATCHER)
118
+ // 模拟数据(#30):设计目录里有 mock.json 就每屏都带上(数据里的 < 都转义了,替换 nonce 碰不到它)
119
+ const lead = ERR_CATCHER + stateScript(html, url) + mockScript(mock)
120
+ return headInsert(i >= 0 ? html.slice(0, i) + tag + html.slice(i) : html + tag, nonce ? lead.replaceAll('<script>', `<script${n}>`) : lead)
105
121
  }
106
122
 
107
123
  /**
@@ -315,13 +331,13 @@ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () =>
315
331
  const strictRoot = (dir) => { try { return !!(strict && strict.root && strict.root(dir)) } catch (e) { log(e); return true } }
316
332
  const strictVer = (dir) => { try { return !!(strict && strict.versions && strict.versions(dir)) } catch (e) { log(e); return true } }
317
333
 
318
- /** 发一份 HTML:别人做的加硬规矩(CSP + nonce),我们的脚本照常注入 */
319
- function sendHtml(res, req, buf, type, force = false) {
334
+ /** 发一份 HTML:别人做的加硬规矩(CSP + nonce),我们的脚本照常注入;mock:这个设计的模拟数据(没有给 null) */
335
+ function sendHtml(res, req, buf, type, force = false, mock = null) {
320
336
  if (force || strictHtml(buf)) {
321
337
  const nonce = crypto.randomBytes(16).toString('base64')
322
- return send(res, 200, req.method === 'HEAD' ? '' : injectPicker(defang(buf.toString('utf8')), { nonce }), { 'Content-Type': type, 'Content-Security-Policy': strictCsp(nonce), ...STRICT_HEADERS })
338
+ return send(res, 200, req.method === 'HEAD' ? '' : injectPicker(defang(buf.toString('utf8')), { nonce, url: req.url, mock }), { 'Content-Type': type, 'Content-Security-Policy': strictCsp(nonce), ...STRICT_HEADERS })
323
339
  }
324
- send(res, 200, req.method === 'HEAD' ? '' : injectPicker(buf.toString('utf8')), { 'Content-Type': type })
340
+ send(res, 200, req.method === 'HEAD' ? '' : injectPicker(buf.toString('utf8'), { url: req.url, mock }), { 'Content-Type': type })
325
341
  }
326
342
  const servers = new Map() // key → entry
327
343
 
@@ -443,6 +459,16 @@ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () =>
443
459
  })
444
460
  }
445
461
 
462
+ /** 「数据」面板背后的小页:只有运行时 + 转告右侧栏的那段(设计目录里没有 mock.json 就没有) */
463
+ function mockPage(req, res, entry) {
464
+ const m = entry.kind === 'file' ? mockOf(entry.root) : null
465
+ if (!m) return send(res, 404, 'no mock data')
466
+ const nonce = crypto.randomBytes(16).toString('base64')
467
+ const parents = JSON.stringify(parentOrigins()).replace(/</g, '\\u003c')
468
+ const html = `<!doctype html><html><head><meta charset="utf-8"><title>mock</title>${mockScript(m)}</head><body><script>(${mockBridge})(${parents})</script></body></html>`
469
+ send(res, 200, req.method === 'HEAD' ? '' : html.replaceAll('<script>', `<script nonce="${nonce}">`), { 'Content-Type': MIME['.html'], 'Content-Security-Policy': strictCsp(nonce), ...STRICT_HEADERS })
470
+ }
471
+
446
472
  // ── 本地文件 ──────────────────────────────────────────────────────────────
447
473
 
448
474
  function serveFile(req, res, entry, pathname) {
@@ -467,7 +493,7 @@ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () =>
467
493
  if (ext === '.html' || ext === '.htm') {
468
494
  fs.readFile(file, (err, buf) => {
469
495
  if (err) return send(res, 500, '读不了这个文件')
470
- sendHtml(res, req, buf, type)
496
+ sendHtml(res, req, buf, type, false, mockOf(entry.root))
471
497
  })
472
498
  return
473
499
  }
@@ -480,6 +506,17 @@ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () =>
480
506
  stream.pipe(res)
481
507
  }
482
508
 
509
+ /** 旧版本那时候的 mock.json(那一版没有就没有) */
510
+ function versionMock(root, v) {
511
+ try {
512
+ const f = history && history.fileOf(root, v, MOCK_FILE)
513
+ if (!f) return null
514
+ const st = fs.statSync(f)
515
+ // 旧版本的屏单独一份(scope v):开旧版本不会把现在点出来的数据当成「旧指纹」清掉
516
+ return st.size > MOCK_MAX ? null : { ...parseMock(fs.readFileSync(f, 'utf8')), scope: 'v' }
517
+ } catch { return null }
518
+ }
519
+
483
520
  /** 旧版本里的文件(只读;HTML 照样注入 picker,好在画布里显示和对比) */
484
521
  function serveVersion(req, res, entry, pathname) {
485
522
  const m = /^\/__dsh_design__\/v\/(\d+)\/(.*)$/.exec(pathname)
@@ -492,7 +529,7 @@ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () =>
492
529
  fs.readFile(file, (err, buf) => {
493
530
  if (err) return send(res, 404, 'no such version file')
494
531
  // 装好的别人的设计系统:旧版本里的页面一律加规矩
495
- if (ext === '.html' || ext === '.htm') return sendHtml(res, req, buf, type, strictVer(entry.root))
532
+ if (ext === '.html' || ext === '.htm') return sendHtml(res, req, buf, type, strictVer(entry.root), versionMock(entry.root, Number(m[1])))
496
533
  const extra = strictRoot(entry.root) ? { 'X-Content-Type-Options': 'nosniff', ...(ext === '.svg' ? { 'Content-Security-Policy': STRICT_SVG_CSP } : {}) } : {}
497
534
  res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-store', 'Cross-Origin-Resource-Policy': 'same-origin', ...extra })
498
535
  res.end(req.method === 'HEAD' ? undefined : buf)
@@ -627,7 +664,7 @@ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () =>
627
664
  delete h['content-security-policy'] // 会挡住注入的脚本和被嵌入
628
665
  delete h['transfer-encoding']
629
666
  res.writeHead(upRes.statusCode || 200, h)
630
- res.end(injectPicker(Buffer.concat(chunks).toString('utf8')))
667
+ res.end(injectPicker(Buffer.concat(chunks).toString('utf8'), { url: req.url }))
631
668
  }
632
669
  upRes.on('data', onData)
633
670
  upRes.on('end', onEnd)
@@ -693,6 +730,7 @@ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () =>
693
730
  try { pathname = new URL(req.url, 'http://x').pathname } catch { return send(res, 400, 'bad url') }
694
731
  if (pathname === INTERNAL + 'picker.js') return picker(res, entry)
695
732
  if (pathname === INTERNAL + 'draft.js') return draftJs(res)
733
+ if (pathname === INTERNAL + 'mock.html') return mockPage(req, res, entry)
696
734
  // 草稿就挂在这一屏自己的地址上(/menu.html?__ddp_draft=…),页面里的相对地址(tokens.css、图片)照常对得上
697
735
  if (entry.kind === 'file' && /[?&]__ddp_draft=/.test(req.url)) return serveDraft(req, res, entry, pathname)
698
736
  if (pathname === INTERNAL + 'events') {
package/lib/states.js ADDED
@@ -0,0 +1,148 @@
1
+ /**
2
+ * 一页多状态(#30):还是一屏一个 HTML 文件,同一个页面的几种样子(空列表 / 有数据 / 已付款)写在同一个文件里——
3
+ *
4
+ * <meta name="dsh-states" content="default:有数据, empty:空列表, paid:已付款"> 这屏有哪几个状态,第一个是默认
5
+ * <html data-state="default"> 文件里写着默认状态
6
+ * [data-state="empty"] .list { display: none } 差别全用 CSS
7
+ * <a href="order.html?state=paid"> 跳到某个状态
8
+ *
9
+ * 预览服务器打开 ?state=paid、页面写了这个状态时,在页面开画前把 <html data-state> 设好(serve.js 的 stateScript)。
10
+ * 服务端(体检、转代码、整套演示)用这里的;client.js 里有一份一样的 parseStates(浏览器里跑,test-client 比着)。
11
+ */
12
+ import fs from 'node:fs'
13
+
14
+ /** 状态名只认这种写法(英文、数字、- _):要放进地址、CSS 属性选择器,转代码时当枚举名 */
15
+ export const STATE_RE = /^[A-Za-z0-9_-]{1,32}$/
16
+ export const MAX_STATES = 8
17
+
18
+ /** meta 内容 → [{ name, label }](第一个是默认;名字后面可以跟「:中文名」);不到两个当没写 */
19
+ export function parseStates(raw) {
20
+ const out = []
21
+ for (const part of String(raw || '').split(/[,,;;\n]+/)) {
22
+ const m = /^\s*([A-Za-z0-9_-]{1,32})\s*(?:[::=]\s*(.*?))?\s*$/.exec(part)
23
+ if (!m || out.some((x) => x.name === m[1])) continue
24
+ out.push({ name: m[1], label: String(m[2] || '').trim().slice(0, 24) || m[1] })
25
+ if (out.length >= MAX_STATES) break
26
+ }
27
+ return out.length >= 2 ? out : []
28
+ }
29
+
30
+ /** HTML(开头那段就够)里写的状态(注释里的示例不算:浏览器里它不是 <meta>) */
31
+ /** 这页的状态跟着模拟数据走(<meta name="dsh-states" … data-mock="…">):不点名就是数据里那个,点名第一个不能省 */
32
+ export function followsMock(html) {
33
+ const s = String(html || '').replace(/<!--[\s\S]*?(?:-->|$)/g, '')
34
+ const re = /<meta\b[^>]*>/gi
35
+ let m
36
+ while ((m = re.exec(s))) if (/\bname\s*=\s*["']?dsh-states["'\s/>]/i.test(m[0])) return /\sdata-mock\s*=/i.test(m[0])
37
+ return false
38
+ }
39
+
40
+ export function statesOfHtml(html) {
41
+ const s = String(html || '').replace(/<!--[\s\S]*?(?:-->|$)/g, '')
42
+ const re = /<meta\b[^>]*>/gi
43
+ let m
44
+ while ((m = re.exec(s))) {
45
+ if (!/\bname\s*=\s*["']?dsh-states["'\s/>]/i.test(m[0])) continue
46
+ const c = /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(m[0])
47
+ return parseStates(c ? c[1] ?? c[2] : '')
48
+ }
49
+ return []
50
+ }
51
+
52
+ const HEAD_MAX = 512 * 1024 // 读到 </head> 为止,最多这么多(<head> 里塞了一大段内联 CSS 的,meta 可能在很后面)
53
+
54
+ /** 文件里写的状态(meta 在 <head> 里:一块一块读,读到 </head> 就停;没写 </head> 的读到上限) */
55
+ export function statesOfFile(file) {
56
+ let fd
57
+ try {
58
+ fd = fs.openSync(file, 'r')
59
+ const parts = []
60
+ let total = 0
61
+ const buf = Buffer.alloc(65536)
62
+ while (total < HEAD_MAX) {
63
+ const n = fs.readSync(fd, buf, 0, Math.min(buf.length, HEAD_MAX - total), total)
64
+ if (!n) break
65
+ parts.push(Buffer.from(buf.subarray(0, n)))
66
+ total += n
67
+ // 带上前一块的尾巴一起看,免得 </head> 正好被切在两块中间
68
+ if (/<\/head\s*>/i.test(Buffer.concat(parts.slice(-2)).toString('latin1'))) break
69
+ }
70
+ return statesOfHtml(Buffer.concat(parts).toString('utf8'))
71
+ } catch {
72
+ return []
73
+ } finally {
74
+ if (fd != null) try { fs.closeSync(fd) } catch { /* 关过了 */ }
75
+ }
76
+ }
77
+
78
+ /** 屏的地址换成某个状态(空 = 去掉 ?state=) */
79
+ export function withState(url, state) {
80
+ try {
81
+ const u = new URL(url)
82
+ if (state && STATE_RE.test(state)) u.searchParams.set('state', state)
83
+ else u.searchParams.delete('state')
84
+ return u.href
85
+ } catch {
86
+ return url
87
+ }
88
+ }
89
+
90
+ /**
91
+ * 要量的屏展开成「每屏 × 每个状态」:写了状态的屏,原来那一行就是默认状态(标上状态名),后面紧跟着其余状态各一行
92
+ * (key 是 order.html?state=paid,体检、截图、复查按它分开记)。
93
+ * perScreen:每屏最多量几个状态;extra:总共最多多量几行(屏多、状态多时别量太久)
94
+ * only(sc):这屏只量哪几个状态(Set,模型写了 order.html?state=paid);null = 全部。点名的状态不受 perScreen / extra 限制
95
+ * @returns { list, skipped 没量的状态数 }
96
+ */
97
+ export function expandStates(list, statesOf, { perScreen = 6, extra = 12, only = null } = {}) {
98
+ const out = []
99
+ let added = 0
100
+ let skipped = 0
101
+ // 默认那行 key 不变;地址也写明第一个状态(状态跟着模拟数据走的屏,不写就是数据里那个状态,会和后面某行重复)
102
+ const row = (sc, x, first) => first
103
+ ? { ...sc, url: withState(sc.url, x.name), base: sc.key, state: x.name, stateLabel: x.label }
104
+ : { ...sc, key: `${sc.key}?state=${x.name}`, url: withState(sc.url, x.name), base: sc.key, state: x.name, stateLabel: x.label }
105
+ for (const sc of list) {
106
+ const st = statesOf(sc) || []
107
+ if (st.length < 2) { out.push(sc); continue }
108
+ const want = only ? only(sc) : null
109
+ const named = want ? st.filter((x) => want.has(x.name)) : []
110
+ if (named.length) { for (const x of named) out.push(row(sc, x, x === st[0])); continue }
111
+ out.push(row(sc, st[0], true))
112
+ const rest = st.slice(1, perScreen)
113
+ skipped += st.length - 1 - rest.length
114
+ for (const x of rest) {
115
+ if (added >= extra) { skipped++; continue }
116
+ out.push(row(sc, x, false))
117
+ added++
118
+ }
119
+ }
120
+ return { list: out, skipped }
121
+ }
122
+
123
+ /**
124
+ * 工具的 screens 参数里可以写 order.html?state=paid(只量 / 只截这个状态):拆成屏名 + 每屏点了哪几个状态。
125
+ * pick(names) 是按屏名找屏的(look.js 的 pickScreens 绑好 snap);同一屏也写了不带状态的 → 全部状态
126
+ */
127
+ export function splitStateNames(names, pick) {
128
+ if (!Array.isArray(names)) return { names, only: null }
129
+ const bases = []
130
+ const want = new Map() // 屏 key → Set(状态);null = 全部
131
+ for (const n of names.slice(0, 40)) {
132
+ let m = /^(.+?)\?state=([A-Za-z0-9_-]{1,32})$/.exec(String(n ?? '').trim())
133
+ // 开发服务器的路由本来就带 ?state=(/stores?state=CA 是单独一屏):整个找到的屏和拆掉状态找到的不是同一屏 → 当屏名,不拆
134
+ if (m) { const whole = pick(n); const base = whole ? pick(m[1]) : null; if (whole && (!base || base.key !== whole.key)) m = null }
135
+ bases.push(m ? m[1] : n)
136
+ const hit = pick(m ? m[1] : n)
137
+ if (!hit) continue
138
+ if (!m) want.set(hit.key, null)
139
+ else if (want.get(hit.key) !== null) want.set(hit.key, (want.get(hit.key) || new Set()).add(m[2]))
140
+ }
141
+ return { names: bases, only: want.size ? (sc) => want.get(sc.key) || null : null }
142
+ }
143
+
144
+ /** 体检、转代码里怎么称呼某屏的某个状态:order.html(状态 paid「已付款」) */
145
+ export function stateName(base, state, label) {
146
+ if (!state) return base
147
+ return `${base}(状态 ${state}${label && label !== state ? `「${label}」` : ''})`
148
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-design-studio",
3
- "version": "1.0.2",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1 test/*.mjs"
@@ -44,9 +44,26 @@
44
44
  <meta name="dsh-design" content="app"> <!-- 类型;小程序写 miniprogram;Windows 软件写 desktop windows;海报可带尺寸:poster 1080x1920;图表写 diagram 1600x1000;DSH 插件写 dshplugin 1280x800;套外框照外框里写好的那行,别改 -->
45
45
  ```
46
46
 
47
- **几屏共用的东西只写一份**:样式放 `tokens.css` 和一个公共的 `app.css`;图标、书封这类 SVG 放进一个 `icons.svg`(每个图标一个 `<symbol id="…">`),页面里用 `<svg><use href="icons.svg#cart"></use></svg>` 引用——换风格时改一处所有屏一起变,不会漏改。状态栏、标签栏这种 HTML 结构每屏照抄一份,保持一模一样。
47
+ **几屏共用的东西只写一份**:样式放 `tokens.css` 和一个公共的 `app.css`;图标、书封这类 SVG 放进一个 `icons.svg`(每个图标一个 `<symbol id="…">`),页面里用 `<svg><use href="icons.svg#cart"></use></svg>` 引用——换风格时改一处所有屏一起变,不会漏改。状态栏、标签栏这种 HTML 结构每屏照抄一份,保持一模一样。卡片、按钮这类共用部件的样式写进 `app.css`,别在各屏自己的 `<style>` 里各写一份——屏一多就会写走样,`check_design` 会提醒「部件各屏写得不一样」。
48
48
 
49
- **几屏之间用真链接串起来**,让它成为点得动的原型:按钮、卡片、标签栏、返回箭头都写成 `<a href="detail.html">`(或 `data-href="detail.html"`)。返回也写具体去哪一屏(`<a href="home.html">`),不要用 `history.back()`。右侧画布会从按钮画一条连线到目标屏,「演示」时点按钮就跳过去(带过场动画),手机扫码看时也点得动。
49
+ **几屏之间用真链接串起来**,让它成为点得动的原型:按钮、卡片、标签栏、返回箭头都写成 `<a href="detail.html">`(或 `data-href="detail.html"`)。返回箭头写成 `<a href="home.html" data-back>`:演示、手机上看时回到上一屏(从哪来回哪去),`href` 是没有上一屏时去哪;不要用 `history.back()`。右侧画布会从按钮画一条连线到目标屏,「演示」时点按钮就跳过去(带过场动画),手机扫码看时也点得动。
50
+
51
+ **同一个页面的几种样子(空列表 / 有数据 / 已付款 / 出错)写成「状态」,别另做一屏**:`<head>` 里写 `<meta name="dsh-states" content="default:有数据, empty:空列表, paid:已付款">`(第一个是默认;冒号前是英文名,后面是给人看的名字;最多 8 个),`<html data-state="default">`,差别全用 CSS 写:`[data-state="empty"] .list { display: none }`。跳到某个状态就链接 `order.html?state=paid`,同一屏里换状态写 `<a href="?state=paid">`。画布上屏名旁边能切状态,`check_design` 每个状态都量。只有一种样子的屏不用写。
52
+
53
+ **点了会变、换页还在的原型,用「模拟数据」**(多角色 / 多阶段、有列表和表单、点按钮后内容要跟着变的 App 原型;只是静态展示的不用):在这套设计的目录里写一个 `mock.json`(一个对象,整套原型共用,用户名、阶段、列表、表单都放这里,写真实的样例内容),页面里不写 JS 就能用:
54
+
55
+ ```html
56
+ <span data-mock-text="user.name"></span> <!-- 显示;也可以拼:'¥' + order.total -->
57
+ <div data-mock-show="user.stage == 'onsite'">…</div> <!-- 条件不成立就藏起来;&& || ! 比较 三元都能写 -->
58
+ <button data-mock-set="user.stage = 'onsite'; unread = 0">接受邀约</button> <!-- 点了改数据,几句用 ; 隔开;也可以同时是链接 -->
59
+ <a data-mock-class="on: tab == 'home'" data-mock-set="tab = 'home'">首页</a> <!-- 按条件加 class -->
60
+ <button data-mock-attr="disabled: !form.agree">下一步</button> <!-- 按条件设属性 -->
61
+ <input data-mock-model="form.phone"> <!-- 输入框、勾选框和数据双向,填了换页还在 -->
62
+ <ul data-mock-each="app in applications"><template><li><b data-mock-text="app.title"></b><button data-mock-set="app.status = 'done'">完成</button></li></template></ul>
63
+ <button data-mock-reset>重置演示数据</button>
64
+ ```
65
+
66
+ 页面的状态可以跟着数据走:`<meta name="dsh-states" content="interviewing:面试中, onsite:在项" data-mock="user.stage">`——数据里 `user.stage` 是几,这页就是哪个状态;角色、阶段这种全局的东西这样写,一处改了所有页一起变,不用每种组合做一屏。改了的数据存在浏览器里,换页、刷新都还在;`mock.json` 一改就从新文件重新开始。复杂的逻辑写脚本:`mock.get('user.stage')`、`mock.set('cart.count', 2)`、`mock.push('cart.items', {…})`、`mock.remove('cart.items', 0)`、`mock.on((data) => …)`、`mock.reset()`——**不要自己用 localStorage 另写一套数据**。mock.json 里有的东西(名字、金额、状态),页面上显示它的地方都绑上,别这屏绑了、那屏写死——用户在右侧栏「数据」里改一处,所有屏要一起变。条件里只能写字段、字面量和运算,不能调函数。写错的条件、找不到的字段 `check_design` 会报出来。
50
67
 
51
68
  4. **写完第一屏就调 `preview_page`**(`target` 填这个文件,`kind` 填类型),用户从第一屏起就能看着它长出来;后面的屏写到同一目录会自动并排出现,不用再调。
52
69