dsh-design-studio 1.0.2 → 1.1.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/serve.js CHANGED
@@ -20,6 +20,7 @@ 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'
23
24
 
24
25
  export const INTERNAL = '/__dsh_design__/'
25
26
  const PICKER_FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), 'picker.js')
@@ -87,6 +88,17 @@ export const ERR_CATCHER = '<script>(()=>{if(window.__dshErrs)return;const L=win
87
88
  'else add({msg:String(e.message||"").slice(0,300),src:String(e.filename||"").slice(0,300),line:e.lineno||0})},true);' +
88
89
  'addEventListener("unhandledrejection",(e)=>{const r=e.reason;add({msg:String((r&&r.message)||r).slice(0,300),src:"",line:0})})})()</script>'
89
90
 
91
+ /**
92
+ * 一页多状态(#30):地址带 ?state=paid、页面 <meta name="dsh-states"> 里写了 paid → 开画前把 <html data-state> 设成它(不闪默认状态)。
93
+ * 页面没写这个状态(老页面自己拿 ?state= 当参数)给 '':完全不碰页面的 data-state
94
+ */
95
+ export function stateScript(html, url) {
96
+ let s = ''
97
+ try { s = new URL(String(url || ''), 'http://x').searchParams.get('state') || '' } catch { return '' }
98
+ if (!STATE_RE.test(s) || !statesOfHtml(html).some((x) => x.name === s)) return ''
99
+ return `<script>document.documentElement.setAttribute("data-state","${s}")</script>`
100
+ }
101
+
90
102
  /** 放进 <head> 最前面;没写 <head> 就放在 <html> / <!doctype> 后面(放到 doctype 前面页面会进怪异模式) */
91
103
  export function headInsert(html, tag) {
92
104
  const m = /<head\b[^>]*>/i.exec(html) || /<html\b[^>]*>/i.exec(html) || /^\s*<!doctype\b[^>]*>/i.exec(html)
@@ -97,11 +109,12 @@ export function headInsert(html, tag) {
97
109
  * 在 </body> 前(没有就在末尾)插入选取脚本,<head> 最前面放报错记录。
98
110
  * nonce:别人做的设计(设计库来的)加了「只准带这个记号的脚本跑」的规矩,我们自己的两段脚本带上它;data-strict 让 picker 拦外链
99
111
  */
100
- export function injectPicker(html, { nonce = '' } = {}) {
112
+ export function injectPicker(html, { nonce = '', url = '' } = {}) {
101
113
  const n = nonce ? ` nonce="${nonce}"` : ''
102
114
  const tag = `<script src="${INTERNAL}picker.js"${n}${nonce ? ' data-strict="1"' : ''}></script>`
103
115
  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)
116
+ const lead = ERR_CATCHER + stateScript(html, url)
117
+ return headInsert(i >= 0 ? html.slice(0, i) + tag + html.slice(i) : html + tag, nonce ? lead.replaceAll('<script>', `<script${n}>`) : lead)
105
118
  }
106
119
 
107
120
  /**
@@ -319,9 +332,9 @@ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () =>
319
332
  function sendHtml(res, req, buf, type, force = false) {
320
333
  if (force || strictHtml(buf)) {
321
334
  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 })
335
+ return send(res, 200, req.method === 'HEAD' ? '' : injectPicker(defang(buf.toString('utf8')), { nonce, url: req.url }), { 'Content-Type': type, 'Content-Security-Policy': strictCsp(nonce), ...STRICT_HEADERS })
323
336
  }
324
- send(res, 200, req.method === 'HEAD' ? '' : injectPicker(buf.toString('utf8')), { 'Content-Type': type })
337
+ send(res, 200, req.method === 'HEAD' ? '' : injectPicker(buf.toString('utf8'), { url: req.url }), { 'Content-Type': type })
325
338
  }
326
339
  const servers = new Map() // key → entry
327
340
 
@@ -627,7 +640,7 @@ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () =>
627
640
  delete h['content-security-policy'] // 会挡住注入的脚本和被嵌入
628
641
  delete h['transfer-encoding']
629
642
  res.writeHead(upRes.statusCode || 200, h)
630
- res.end(injectPicker(Buffer.concat(chunks).toString('utf8')))
643
+ res.end(injectPicker(Buffer.concat(chunks).toString('utf8'), { url: req.url }))
631
644
  }
632
645
  upRes.on('data', onData)
633
646
  upRes.on('end', onEnd)
package/lib/states.js ADDED
@@ -0,0 +1,138 @@
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
+ export function statesOfHtml(html) {
32
+ const s = String(html || '').replace(/<!--[\s\S]*?(?:-->|$)/g, '')
33
+ const re = /<meta\b[^>]*>/gi
34
+ let m
35
+ while ((m = re.exec(s))) {
36
+ if (!/\bname\s*=\s*["']?dsh-states["'\s/>]/i.test(m[0])) continue
37
+ const c = /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(m[0])
38
+ return parseStates(c ? c[1] ?? c[2] : '')
39
+ }
40
+ return []
41
+ }
42
+
43
+ const HEAD_MAX = 512 * 1024 // 读到 </head> 为止,最多这么多(<head> 里塞了一大段内联 CSS 的,meta 可能在很后面)
44
+
45
+ /** 文件里写的状态(meta 在 <head> 里:一块一块读,读到 </head> 就停;没写 </head> 的读到上限) */
46
+ export function statesOfFile(file) {
47
+ let fd
48
+ try {
49
+ fd = fs.openSync(file, 'r')
50
+ const parts = []
51
+ let total = 0
52
+ const buf = Buffer.alloc(65536)
53
+ while (total < HEAD_MAX) {
54
+ const n = fs.readSync(fd, buf, 0, Math.min(buf.length, HEAD_MAX - total), total)
55
+ if (!n) break
56
+ parts.push(Buffer.from(buf.subarray(0, n)))
57
+ total += n
58
+ // 带上前一块的尾巴一起看,免得 </head> 正好被切在两块中间
59
+ if (/<\/head\s*>/i.test(Buffer.concat(parts.slice(-2)).toString('latin1'))) break
60
+ }
61
+ return statesOfHtml(Buffer.concat(parts).toString('utf8'))
62
+ } catch {
63
+ return []
64
+ } finally {
65
+ if (fd != null) try { fs.closeSync(fd) } catch { /* 关过了 */ }
66
+ }
67
+ }
68
+
69
+ /** 屏的地址换成某个状态(空 = 去掉 ?state=) */
70
+ export function withState(url, state) {
71
+ try {
72
+ const u = new URL(url)
73
+ if (state && STATE_RE.test(state)) u.searchParams.set('state', state)
74
+ else u.searchParams.delete('state')
75
+ return u.href
76
+ } catch {
77
+ return url
78
+ }
79
+ }
80
+
81
+ /**
82
+ * 要量的屏展开成「每屏 × 每个状态」:写了状态的屏,原来那一行就是默认状态(标上状态名),后面紧跟着其余状态各一行
83
+ * (key 是 order.html?state=paid,体检、截图、复查按它分开记)。
84
+ * perScreen:每屏最多量几个状态;extra:总共最多多量几行(屏多、状态多时别量太久)
85
+ * only(sc):这屏只量哪几个状态(Set,模型写了 order.html?state=paid);null = 全部。点名的状态不受 perScreen / extra 限制
86
+ * @returns { list, skipped 没量的状态数 }
87
+ */
88
+ export function expandStates(list, statesOf, { perScreen = 6, extra = 12, only = null } = {}) {
89
+ const out = []
90
+ let added = 0
91
+ let skipped = 0
92
+ const row = (sc, x, first) => first
93
+ ? { ...sc, base: sc.key, state: x.name, stateLabel: x.label }
94
+ : { ...sc, key: `${sc.key}?state=${x.name}`, url: withState(sc.url, x.name), base: sc.key, state: x.name, stateLabel: x.label }
95
+ for (const sc of list) {
96
+ const st = statesOf(sc) || []
97
+ if (st.length < 2) { out.push(sc); continue }
98
+ const want = only ? only(sc) : null
99
+ const named = want ? st.filter((x) => want.has(x.name)) : []
100
+ if (named.length) { for (const x of named) out.push(row(sc, x, x === st[0])); continue }
101
+ out.push(row(sc, st[0], true))
102
+ const rest = st.slice(1, perScreen)
103
+ skipped += st.length - 1 - rest.length
104
+ for (const x of rest) {
105
+ if (added >= extra) { skipped++; continue }
106
+ out.push(row(sc, x, false))
107
+ added++
108
+ }
109
+ }
110
+ return { list: out, skipped }
111
+ }
112
+
113
+ /**
114
+ * 工具的 screens 参数里可以写 order.html?state=paid(只量 / 只截这个状态):拆成屏名 + 每屏点了哪几个状态。
115
+ * pick(names) 是按屏名找屏的(look.js 的 pickScreens 绑好 snap);同一屏也写了不带状态的 → 全部状态
116
+ */
117
+ export function splitStateNames(names, pick) {
118
+ if (!Array.isArray(names)) return { names, only: null }
119
+ const bases = []
120
+ const want = new Map() // 屏 key → Set(状态);null = 全部
121
+ for (const n of names.slice(0, 40)) {
122
+ let m = /^(.+?)\?state=([A-Za-z0-9_-]{1,32})$/.exec(String(n ?? '').trim())
123
+ // 开发服务器的路由本来就带 ?state=(/stores?state=CA 是单独一屏):整个找到的屏和拆掉状态找到的不是同一屏 → 当屏名,不拆
124
+ if (m) { const whole = pick(n); const base = whole ? pick(m[1]) : null; if (whole && (!base || base.key !== whole.key)) m = null }
125
+ bases.push(m ? m[1] : n)
126
+ const hit = pick(m ? m[1] : n)
127
+ if (!hit) continue
128
+ if (!m) want.set(hit.key, null)
129
+ else if (want.get(hit.key) !== null) want.set(hit.key, (want.get(hit.key) || new Set()).add(m[2]))
130
+ }
131
+ return { names: bases, only: want.size ? (sc) => want.get(sc.key) || null : null }
132
+ }
133
+
134
+ /** 体检、转代码里怎么称呼某屏的某个状态:order.html(状态 paid「已付款」) */
135
+ export function stateName(base, state, label) {
136
+ if (!state) return base
137
+ return `${base}(状态 ${state}${label && label !== state ? `「${label}」` : ''})`
138
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-design-studio",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1 test/*.mjs"
@@ -44,9 +44,11 @@
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` 每个状态都量。只有一种样子的屏不用写。
50
52
 
51
53
  4. **写完第一屏就调 `preview_page`**(`target` 填这个文件,`kind` 填类型),用户从第一屏起就能看着它长出来;后面的屏写到同一目录会自动并排出现,不用再调。
52
54