dsh-design-studio 1.1.0 → 1.3.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/htmlpack.js CHANGED
@@ -12,14 +12,17 @@
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'
21
22
  export const PACK_MAX = 150 * 1024 * 1024 // 整个文件的上限(字符数):再大浏览器打开就很慢了
22
23
  export const PACK_SCREENS = 1000 // 画布只显示 60 屏,导出要全部(#29:有人的设计 400 多屏);真正拦的是 PACK_MAX
24
+ // 一屏内联的上限:字体库两款中文就有 6 MB 多(#31),再加一张大图远程看的 12 MB 不够;整个文件还有 PACK_MAX 兜着
25
+ const SCREEN_MAX = 48 * 1024 * 1024
23
26
  const ASSET_MIN = 2048 // 这么长以上的 data: 地址单独存一份(几屏共用的只存一次)
24
27
 
25
28
  // ── 和 client.js 同一份数(测试比着)────────────────────────────────────────
@@ -89,6 +92,9 @@ function storeShim(D) {
89
92
  try { void window[name].length } catch { broken = true }
90
93
  if (broken) { try { Object.defineProperty(window, name, { value: make(area), configurable: true }) } catch { /* 改不了就算了 */ } }
91
94
  }
95
+ // 模拟数据(#30):自己做的屏(和播放器同源、有真的 localStorage)和别人做的屏(沙盒、只有替身)存的地方不一样,
96
+ // 换屏会读不到上一屏改的。演示里的模拟数据一律存播放器手上这一份
97
+ try { Object.defineProperty(window, '__ddpMockStore', { value: make('m'), configurable: true }) } catch { /* 改不了就算了 */ }
92
98
  }
93
99
 
94
100
  /**
@@ -107,6 +113,8 @@ function navScript(C, ST) {
107
113
  const de = document.documentElement
108
114
  for (const [k, v] of Object.entries((C.tweak && C.tweak.vars) || {})) { try { de.style.setProperty(k, String(v), 'important') } catch { /* 不认的值 */ } }
109
115
  for (const [k, v] of Object.entries((C.tweak && C.tweak.attrs) || {})) { try { if (v == null || v === false) de.removeAttribute(k); else de.setAttribute(k, String(v)) } catch { /* 不认的名字 */ } }
116
+ const fonts = (C.tweak && C.tweak.fonts) || []
117
+ if (fonts.length) style(fonts.map((f) => `@font-face{font-family:"${f.family}";src:url("${f.url}") format("woff2");font-weight:${f.w};font-display:swap}`).join(''))
110
118
  // 一页多状态(#30):播放器放这一屏时给的状态(order.html?state=paid)写在 <html data-state> 上
111
119
  const STATE_RE = /^[A-Za-z0-9_-]{1,32}$/
112
120
  /** 这页 <meta name="dsh-states"> 里写了哪几个状态(不到两个当没写) */
@@ -120,7 +128,7 @@ function navScript(C, ST) {
120
128
  return out.length >= 2 ? out : []
121
129
  }
122
130
  // 播放器只在这屏写了这个状态时才给(老页面自己拿 ?state= 当参数的给 '',完全不碰 data-state)
123
- if (typeof ST === 'string' && STATE_RE.test(ST)) de.setAttribute('data-state', ST)
131
+ if (typeof ST === 'string' && STATE_RE.test(ST)) { de.setAttribute('data-state', ST); window.__dshState = ST } // 模拟数据认它:状态跟着数据走的页,这一屏临时当成这个状态
124
132
  const stateOf = (u) => { const v = u.searchParams.get('state') || ''; return STATE_RE.test(v) ? v : '' }
125
133
 
126
134
  /** 这个地址是不是跳到演示包里的别的屏:{ path, hash };同一页(只有锚点)给 { same, hash };站外给 { out } */
@@ -140,7 +148,10 @@ function navScript(C, ST) {
140
148
  const raw0 = state
141
149
  if (u.pathname === here().pathname && state && !declared().includes(state)) state = ''
142
150
  // 回默认状态只认什么参数都不带的(?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) ? '#' : '') }
151
+ // 状态跟着模拟数据走的屏:播放器点名过状态(哪怕是第一个),不带状态的本页链接 = 去掉点名、回到跟着数据
152
+ const follow = !!document.querySelector('meta[name="dsh-states"][data-mock]')
153
+ const named = typeof ST === 'string' && ST && declared().includes(ST) && (follow || (ST === cur && ST !== declared()[0]))
154
+ 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
155
  return { path: p, hash: u.hash, state }
145
156
  }
146
157
  const rawOf = (el) => {
@@ -342,14 +353,18 @@ function player() {
342
353
  if (!assets.has(i)) { const el = $('ddp-a-' + i); assets.set(i, el ? JSON.parse(el.textContent) : '') }
343
354
  return assets.get(i)
344
355
  }
345
- const store = { l: {}, s: {} }
356
+ const store = { l: {}, s: {}, m: {} }
346
357
  const htmlOf = (i, state = '') => {
347
358
  if (!cache.has(i)) {
348
359
  cache.set(i, JSON.parse($('ddp-s-' + i).textContent).replace(assetRe, (m, n) => asset(Number(n))))
349
360
  if (cache.size > 8) cache.delete(cache.keys().next().value) // 屏多、图大:只留最近放过的几屏
350
361
  }
351
362
  // 存储的初始内容:每次放进去都是当时的(上一屏刚存的这一屏读得到);状态(#30)也是放的时候才定
352
- const out = cache.get(i).replace(C.storeMark, () => JSON.stringify(store).replace(/</g, '\\u003c'))
363
+ let out = cache.get(i).replace(C.storeMark, () => JSON.stringify(store).replace(/</g, '\\u003c'))
364
+ // 模拟数据(#30):整套只存一份,放进 iframe 时才填进这屏
365
+ const js = (v) => JSON.stringify(v).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')
366
+ if (C.mockMark) out = out.split(C.mockMark).join(js(C.mock || {}))
367
+ if (C.mockAMark) out = out.split(C.mockAMark).join(js(C.mockAssets || null))
353
368
  const ok = /^[A-Za-z0-9_-]{1,32}$/.test(state) && (C.screens[i].states || []).includes(state) // 这屏写了的状态才设
354
369
  return C.stateMark ? out.split(C.stateMark).join(JSON.stringify(ok ? state : '')) : out
355
370
  }
@@ -512,8 +527,9 @@ function player() {
512
527
  const k = h ? C.screens.findIndex((s) => s.key === (m ? m[1] : h)) : -1
513
528
  return k >= 0 ? { i: k, state: m ? normState(k, m[2]) : '' } : { i: 0, state: '' }
514
529
  }
515
- // 默认状态写不写都是同一屏(order.html 和 order.html?state=default):统一成不写,返回的路才对得上
516
- const normState = (i, state) => (state && !(C.screens[i].states && C.screens[i].states[0] === state) ? state : '')
530
+ // 默认状态写不写都是同一屏(order.html 和 order.html?state=default):统一成不写,返回的路才对得上。
531
+ // 状态跟着模拟数据走的屏除外:不写是数据里那个,点名第一个要留着
532
+ const normState = (i, state) => (state && !(C.screens[i].states && C.screens[i].states[0] === state && !C.screens[i].follow) ? state : '')
517
533
  const hashOf = (i, state) => '#' + encodeURIComponent(C.screens[i].key) + (normState(i, state) ? '?state=' + state : '')
518
534
  // 走到第几步,记在这一条浏览器历史记录上:页面里的「返回」(data-back)有得退就是浏览器后退一步,
519
535
  // 和浏览器自己的后退、前进是同一份路(后退再前进也对得上)。记不了的(沙盒不给改历史)照老办法按 trail 退
@@ -569,7 +585,7 @@ function player() {
569
585
  if (i < 0) i = C.screens.findIndex((s) => s.key === k + '.html')
570
586
  if (i < 0) say(T.notIn.replace('{p}', k))
571
587
  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')) {
588
+ } else if (d.type === 'store' && (d.area === 'l' || d.area === 's' || d.area === 'm')) {
573
589
  const m = store[d.area]
574
590
  if (d.op === 'set') m[String(d.k)] = String(d.v)
575
591
  else if (d.op === 'del') delete m[String(d.k)]
@@ -597,6 +613,20 @@ function player() {
597
613
  else document.documentElement.requestFullscreen().catch(() => {})
598
614
  })
599
615
  $('menu').addEventListener('click', () => document.body.classList.toggle('open'))
616
+ // 重置演示数据(有模拟数据才有这个按钮):演示里点过、填过的都回到开始,当前这屏重放一遍
617
+ if (C.mockMark) {
618
+ const rs = $('mreset')
619
+ rs.hidden = false
620
+ rs.addEventListener('click', () => {
621
+ const pfx = 'dsh-mock:' + C.mockScope + ':'
622
+ try { for (let i = localStorage.length - 1; i >= 0; i--) { const k = localStorage.key(i); if (k && k.startsWith(pfx)) localStorage.removeItem(k) } } catch { /* 存不了 */ }
623
+ for (const k of Object.keys(store.l)) if (k.startsWith(pfx)) delete store.l[k]
624
+ store.m = {}
625
+ document.body.classList.remove('open')
626
+ if (cur >= 0) show(cur, '', curState)
627
+ say(T.resetDone)
628
+ })
629
+ }
600
630
  document.addEventListener('fullscreenchange', () => { $('full').textContent = document.fullscreenElement ? T.exitFull : T.full })
601
631
  let wasCompact = compact()
602
632
  addEventListener('resize', () => {
@@ -608,8 +638,8 @@ function player() {
608
638
  }
609
639
 
610
640
  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' },
641
+ zh: { prev: '上一屏', next: '下一屏', shell: '外壳', shellTip: '套上手机 / 浏览器外壳', full: '全屏', exitFull: '退出全屏', of: '{i} / {n}', notIn: '这一屏不在演示里:{p}', menu: '换屏', screens: '选屏', reset: '重置数据', resetTip: '演示里点过、填过的都回到开始', resetDone: '数据回到开始了' },
642
+ 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
643
  }
614
644
 
615
645
  const CSS = `
@@ -677,24 +707,54 @@ body.compact #menu{display:block;position:fixed;left:50%;top:calc(4px + env(safe
677
707
  @media (max-width:560px){#bar .ttl{display:none}#bar .end{flex:none}}
678
708
  `
679
709
 
710
+ /**
711
+ * 外观面板里选了、还没存的字体库字体(#31):[{ family, w, url: data: 地址 }](libFont(id) → { family, weights, data } | null)。
712
+ * 写进每屏的配置里,打包时和别的 data: 地址一样整套只放一份
713
+ */
714
+ function tweakFonts(ids, libFont) {
715
+ const out = []
716
+ for (const id of Array.isArray(ids) ? ids.slice(0, 8) : []) {
717
+ let f = null
718
+ try { f = typeof id === 'string' ? libFont(id) : null } catch { f = null }
719
+ if (!f || !/^[A-Za-z0-9 ]{1,40}$/.test(f.family) || !Buffer.isBuffer(f.data)) continue
720
+ const w = Array.isArray(f.weights) && f.weights.length === 2 ? `${f.weights[0] | 0} ${f.weights[1] | 0}` : '100 900'
721
+ out.push({ family: f.family, w, url: `data:font/woff2;base64,${f.data.toString('base64')}` })
722
+ }
723
+ return out
724
+ }
725
+
680
726
  /**
681
727
  * 打一份演示包。
682
728
  * screens:[{ key, label, top }](top:顶栏是深色,外壳上的胶囊 / 窗口按钮画白的)
683
729
  * dark:右侧栏开着「深色」;scheme:右侧栏当时的系统深浅色('dark' / 'light'),没开「深色」时页面按它显示
684
730
  * read(rel):设计目录里的文件(Buffer,读不到 null);strictOf(page):这屏是不是别人做的(加硬规矩:只跑我们的脚本)
685
- * 回 { html, missing: [没读到的屏], count }
731
+ * libFont(id):外观面板里选了还没存的字体库字体 → { family, weights, data }
732
+ * 回 { html, missing: [没读到的屏], count, skipped: [有、但太大没放进去的文件] }
686
733
  */
687
- export function buildPack({ screens, read, strictOf = () => false, kind, w, h, os = '', dark = false, scheme = 'light', tweak = null, title = '', lang = 'zh', fit = false }) {
734
+ export function buildPack({ screens, read, bigOf = null, strictOf = () => false, kind, w, h, os = '', dark = false, scheme = 'light', tweak = null, title = '', lang = 'zh', fit = false, libFont = () => null }) {
688
735
  kind = FRAME[kind] ? kind : 'web'
689
736
  const S = STRINGS[lang === 'en' ? 'en' : 'zh']
690
737
  const token = 'ddpA' + crypto.randomBytes(5).toString('hex') + '_'
691
738
  const storeMark = `/*ddpS${token}*/null`
692
739
  const nonce = crypto.randomBytes(16).toString('base64')
693
- const navCfg = { origin: PACK_ORIGIN, sel: LINK_SEL, js: LINK_JS.source, pages: !!FIXED[kind], tweak: tweak && typeof tweak === 'object' ? { vars: tweak.vars || {}, attrs: tweak.attrs || {} } : null }
740
+ const navCfg = { origin: PACK_ORIGIN, sel: LINK_SEL, js: LINK_JS.source, pages: !!FIXED[kind], tweak: tweak && typeof tweak === 'object' ? { vars: tweak.vars || {}, attrs: tweak.attrs || {}, fonts: tweakFonts(tweak.fonts, libFont) } : null }
694
741
  const script = (src, strict) => `<script${strict ? ` nonce="${nonce}"` : ''}>${src.replace(/<\/(script)/gi, '<\\/$1').replace(/<!--/g, '<\\!--')}</script>`
695
742
  const shimSrc = `(${storeShim})(${storeMark});`
696
743
  const stateMark = `/*ddpT${token}*/''` // 放一屏时换成这屏的状态(#30)
697
744
  const navSrc = (strict) => `(${navScript})(${JSON.stringify({ ...navCfg, strict })}, ${stateMark});`
745
+ // 模拟数据(#30):设计目录里有 mock.json 就每屏放运行时(在存储替身后面、跳屏监听前面:点了又改数据又跳屏的先存好),
746
+ // 数据本身整套只放一份在播放器的配置里,放一屏时填进记号那里
747
+ const mk = mockOfBuf(read(MOCK_FILE), !!(bigOf && bigOf(MOCK_FILE)))
748
+ // mock.json 太大没读:导出来的演示点了不会变——报错不导出(不悄悄给一个丢了数据的演示)
749
+ if (mk && /^big/.test(mk.fp)) { const e = new Error('mockTooBig'); e.code = 'mockTooBig'; throw e }
750
+ const mockMark = mk ? `/*ddpM${token}*/null` : ''
751
+ const mockScope = token.slice(0, -1)
752
+ const mockAMark = mk ? `/*ddpMA${token}*/null` : ''
753
+ const mockSrc = mk ? `(${mockRuntime})(${mockExpr},${JSON.stringify({ v: mk.fp, scope: mockScope, err: mk.err })},${mockMark},${mockAMark});` : ''
754
+ // 数据里写的本地图片(头像、商品图):演示是单个文件,没有设计目录可读——换成 data: 地址的表,整套只放一份
755
+ const mockOver = []
756
+ const mockAssets = mk ? dataAssets(mk.data, read, 60 * 1024 * 1024, mockOver, bigOf) : null
757
+ if (mockOver.length) { const e = new Error('imgTooBig'); e.code = 'imgTooBig'; throw e } // 数据里绑的图换不下:不悄悄留成坏图
698
758
  const mode = dark ? 'dark' : scheme === 'dark' ? 'media' : 'light'
699
759
  const schemeSrc = `(${schemeScript})(${JSON.stringify(mode)});`
700
760
 
@@ -703,7 +763,9 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
703
763
  const parts = []
704
764
  const list = []
705
765
  const missing = []
706
- let total = 0
766
+ const skipped = new Set() // 有、但太大放不进去的文件(单个超过 12 MB、一屏加起来超过 SCREEN_MAX):导出照样出,但要告诉用户缺了哪些
767
+ const readPage = (rel) => { const b = read(rel); if (!b && bigOf && bigOf(rel)) skipped.add(rel); return b }
768
+ let total = mk ? JSON.stringify(mk.data).length + JSON.stringify(mockAssets).length : 0
707
769
  for (const s of screens.slice(0, PACK_SCREENS)) {
708
770
  const page = read(s.key)
709
771
  if (!page) { missing.push(s.key); continue }
@@ -712,9 +774,11 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
712
774
  const base = PACK_ORIGIN + '/' + s.key.split('/').map(encodeURIComponent).join('/')
713
775
  let out = bundle(strict ? defang(text) : text, {
714
776
  key: s.key,
715
- read,
777
+ read: readPage,
778
+ max: SCREEN_MAX,
779
+ onSkip: (rel) => skipped.add(rel),
716
780
  base,
717
- lead: (strict ? strictMeta(nonce) : '') + script(shimSrc + navSrc(strict), strict),
781
+ lead: (strict ? strictMeta(nonce) : '') + script(shimSrc + mockSrc + navSrc(strict), strict),
718
782
  tail: script(schemeSrc, strict),
719
783
  })
720
784
  // 大的 data: 地址(图片、字体、脚本)挪出来单独存,几屏共用的只存一份
@@ -728,7 +792,7 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
728
792
  if (total > PACK_MAX) { const e = new Error('tooBig'); e.code = 'tooBig'; throw e }
729
793
  parts.push(`<script type="application/json" id="ddp-s-${list.length}">${jsonTag(out)}</script>`)
730
794
  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) })
795
+ 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
796
  }
733
797
  if (!list.length) { const e = new Error('noScreens'); e.code = 'noScreens'; throw e }
734
798
 
@@ -740,6 +804,7 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
740
804
  // 网页默认不套浏览器框(铺满窗口),右侧栏开着「按画幅显示」的照它套着;手机、平板、桌面软件默认套着
741
805
  shellDefault: !!FRAMED[kind] && (kind !== 'web' || !!fit),
742
806
  screens: list, token, storeMark, stateMark, strings: S,
807
+ ...(mk ? { mockMark, mockAMark, mockScope, mock: mk.data, mockAssets } : null),
743
808
  }
744
809
  const docTitle = cfg.title || list[0].label
745
810
  const html = '<!doctype html>\n'
@@ -751,6 +816,7 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
751
816
  + `<select id="sel" aria-label="${escHtml(S.screens)}"></select>`
752
817
  + `<button id="next" class="arw" type="button" title="${escHtml(S.next)} (→)" aria-label="${escHtml(S.next)}">›</button><span id="count"></span></div>`
753
818
  + `<div class="end"><button id="shell" type="button" aria-pressed="false" title="${escHtml(S.shellTip)}">${escHtml(S.shell)}</button>`
819
+ + `<button id="mreset" type="button" hidden title="${escHtml(S.resetTip)}">${escHtml(S.reset)}</button>`
754
820
  + `<button id="full" type="button">${escHtml(S.full)}</button></div></header>`
755
821
  + `<main id="stage"></main><button id="menu" type="button" aria-label="${escHtml(S.menu)}">•••</button><div id="toast" role="status" hidden></div>`
756
822
  + `<script type="application/json" id="ddp-cfg">${jsonTag(cfg)}</script>`
@@ -758,5 +824,5 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
758
824
  + assets.map((a, i) => `<script type="application/json" id="ddp-a-${i}">${jsonTag(a)}</script>`).join('')
759
825
  + `<script>(${player})()</script>`
760
826
  + '</body></html>\n'
761
- return { html, missing, count: list.length }
827
+ return { html, missing, count: list.length, skipped: [...skipped] }
762
828
  }