dsh-design-studio 0.26.0 → 0.27.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/README.en.md CHANGED
@@ -42,7 +42,7 @@ If DSH can't reach the npm registry, it falls back to a mirror in China. To upda
42
42
  - **Open what you have:** click "Browse…" on the empty page to pick an HTML file, or drop an HTML file or folder onto the sidebar (desktop app); you can also type a path or a dev-server port.
43
43
  - **Design check:** one click finds overflowing text, low contrast, small tap targets and tiny text, marked right on the page. In Design mode the model also checks its own work and fixes what it finds.
44
44
  - **Versions and compare:** every turn is saved; drag a slider to compare, and go back to any version.
45
- - **Export and phone preview:** showcase images, PDF and PowerPoint (links between screens still work); scan a QR code to see it on your phone at real size. Slides and posters larger than the default canvas now use the page's real size. You can also set it by adding `WIDTHxHEIGHT` after the type, for example `<meta name="dsh-design" content="slides 1440x810">`. Export options let you pick the page size (16:9, 4:3, A3 landscape or custom), what each page shows (one screen, full page or a set height) and two screens per page. If anything would be cut off, you get a checklist first, with a one-click fix that fits the canvas to the content.
45
+ - **Export and phone preview:** showcase images, PDF and PowerPoint (links between screens still work), or a clickable HTML demo that opens with a double-click (device frame included, ready to send to a client); scan a QR code to see it on your phone at real size. Slides and posters larger than the default canvas now use the page's real size. You can also set it by adding `WIDTHxHEIGHT` after the type, for example `<meta name="dsh-design" content="slides 1440x810">`. Export options let you pick the page size (16:9, 4:3, A3 landscape or custom), what each page shows (one screen, full page or a set height) and two screens per page. If anything would be cut off, you get a checklist first, with a one-click fix that fits the canvas to the content.
46
46
  - **Diagrams:** mind maps, technical route charts (the kind in grant proposals and theses), product roadmaps and system architecture diagrams. Lines, branches and arrows are laid out for you and re-flow when you change text or add nodes; colors follow the design style, and a high-resolution PNG or PDF export drops straight into Word or PowerPoint. For grant-proposal and final-report frameworks, the model first lists how the parts relate (which problem maps to which task) for you to confirm, then draws labelled arrows between the blocks, in a bold 3D-gradient "proposal" style by default or after a reference image you give it.
47
47
  - **DSH plugins:** design a plugin inside the real DSH desktop frame (left sidebar entry, settings section, session tab or right sidebar panel, in light and dark). Only the plugin area is designed, so you see exactly how it looks once installed; the design check warns if the frame gets changed.
48
48
  - **Design library and gallery:** everything you've designed, plus saved references and styles, lives in the Library. Browse templates, design systems and style cards others shared, and "Start from this" copies one for you to keep editing. Share your own with "Share to the gallery": it's checked, zipped and submitted on a web page, and listed once reviewed. The gallery catalog comes from npm mirrors and is used only when its signature and checksums match; to keep it offline, turn on "Design library offline" on the Plugins page.
package/README.md CHANGED
@@ -42,7 +42,7 @@
42
42
  - **打开已有的页面**:首页输入框左边的「+」→「打开已有的 HTML…」选一个,或把 HTML 文件 / 文件夹拖进右侧栏就能预览(桌面版);也能输路径或开发服务器端口。
43
43
  - **设计体检**:一键查文字溢出、对比度不够、按钮太小、字太小,问题直接标在页面上;模型做完也会自己查一遍再改。
44
44
  - **版本和对比**:每轮自动存一版,左右拖动对比,随时回到任意一版。
45
- - **导出和手机上看**:导出展示图、PDF、PPT(屏和屏之间的跳转照样能点);扫码在手机上按真机尺寸看。页面比默认画幅大的幻灯片、海报,画幅自动跟页面走;也可以在类型后面跟 `宽x高` 指定,比如 `<meta name="dsh-design" content="slides 1440x810">`。导出选项里可以选版面(16:9、4:3、A3 横向、自定义)、每页取景(一屏、整页、指定高度)和每页拼 2 屏;有内容会被裁时,导出前先给一张清单,可以一键按内容改画幅。
45
+ - **导出和手机上看**:导出展示图、PDF、PPT(屏和屏之间的跳转照样能点),或一个双击就能开的 HTML 演示(带外壳、点得动,发给客户直接看);扫码在手机上按真机尺寸看。页面比默认画幅大的幻灯片、海报,画幅自动跟页面走;也可以在类型后面跟 `宽x高` 指定,比如 `<meta name="dsh-design" content="slides 1440x810">`。导出选项里可以选版面(16:9、4:3、A3 横向、自定义)、每页取景(一屏、整页、指定高度)和每页拼 2 屏;有内容会被裁时,导出前先给一张清单,可以一键按内容改画幅。
46
46
  - **图表**:思维导图、技术路线图(申报书、开题报告那种)、产品路线图、系统架构图。连线、分叉、箭头自动排好,改字、加节点自己重排;配色跟着设计风格走,导出高清 PNG 或 PDF 贴进 Word / PPT。申报书、结题报告的框架图先帮你理清「哪个问题对应哪项内容」请你确认再画,版块之间画出带关系词的箭头;默认是立体渐变的「申报书炫酷样式」,也能照你给的参考图画。
47
47
  - **DSH 插件**:给 DSH 做插件界面时,四周直接套上 DSH 桌面端的外框(左侧栏入口、设置分区、会话标签页、右侧栏面板四个位置,浅色、深色都有),只设计插件那一块,一眼看出装进 DSH 是什么样;外框被改了体检会提醒。
48
48
  - **设计库和设计市场**:以前做过的设计、收的参考图和风格都在「设计库」里;市场里逛大家分享的模板、设计系统和风格卡,点「用这个开始」复制一份接着改。自己做的点「分享到设计市场」,查过打成 zip,在网页里交上去,审过就上架。市场目录从 npm 镜像取,签了名、核对过才用;不想让它联网,在插件页打开「设计库不联网」。
package/lib/browser.js CHANGED
@@ -265,6 +265,25 @@ export function createBrowser({ bin = findBrowser(), log = () => {}, idleMs = ID
265
265
  // 换深浅色媒体(prefers-color-scheme),不重开页面:存外框时浅色、深色都在真的媒体环境下量
266
266
  media: (dk) => c('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: dk ? 'dark' : 'light' }, { name: 'prefers-reduced-motion', value: 'reduce' }] }),
267
267
  mouse: (x, y) => c('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y }), // 把鼠标挪到页面上某处(测「鼠标停在外框上」用)
268
+ // 在页面里最后一个子 iframe 里跑一段(沙盒、不透明源的也行:开一个隔离环境,DOM 是同一份)。测 HTML 演示包用
269
+ frameEval: async (expression) => {
270
+ const { frameTree } = await c('Page.getFrameTree')
271
+ const kids = frameTree.childFrames || []
272
+ let r
273
+ if (kids.length) {
274
+ const { executionContextId } = await c('Page.createIsolatedWorld', { frameId: kids[kids.length - 1].frame.id, worldName: 'ddp-test' })
275
+ r = await c('Runtime.evaluate', { expression, contextId: executionContextId, awaitPromise: true, returnByValue: true })
276
+ } else {
277
+ // 沙盒 iframe 在单独的进程里(站点隔离):是另一个目标,连上去跑
278
+ const { targetInfos } = await call('Target.getTargets')
279
+ const fr = targetInfos.filter((x) => x.type === 'iframe')
280
+ if (!fr.length) throw new Error('no child frame')
281
+ const { sessionId: fs2 } = await call('Target.attachToTarget', { targetId: fr[fr.length - 1].targetId, flatten: true })
282
+ try { r = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, fs2) } finally { call('Target.detachFromTarget', { sessionId: fs2 }).catch(() => {}) }
283
+ }
284
+ if (r.exceptionDetails) throw new Error((r.exceptionDetails.exception && r.exceptionDetails.exception.description) || r.exceptionDetails.text || 'eval failed')
285
+ return r.result ? r.result.value : undefined
286
+ },
268
287
  eval: async (expression) => {
269
288
  const r = await c('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true })
270
289
  if (r.exceptionDetails) throw new Error((r.exceptionDetails.exception && r.exceptionDetails.exception.description) || r.exceptionDetails.text || 'eval failed')
package/lib/client.js CHANGED
@@ -200,6 +200,11 @@ window.__ModuleLoader__.load({
200
200
  exPptx: 'PPT · 每屏一页(整页图片)',
201
201
  exOpts: '导出选项…',
202
202
  exportedDocMiss: '已导出 {name}({n} 页,{miss} 屏没截到)',
203
+ exHtml: '整套 HTML 演示(双击就能开)',
204
+ exportedHtml: '已导出 {name}({n} 屏,发给别人双击就能看)',
205
+ exportedHtmlMiss: '已导出 {name}({n} 屏,{miss} 屏没读到)',
206
+ htmlTooBig: '图片太多,演示包超过 150 MB,没导出。少放几屏再试',
207
+ htmlNoScreens: '一屏都没读到(文件被挪走或删了?),没导出',
203
208
  xoTitle: '导出选项',
204
209
  xoTip: '不动这里,导出的结果和直接导出一样。',
205
210
  xoWarn: '有内容会被裁掉,先看一眼',
@@ -1128,6 +1133,11 @@ window.__ModuleLoader__.load({
1128
1133
  exPptx: 'PowerPoint · one slide per screen (as images)',
1129
1134
  exOpts: 'Export options…',
1130
1135
  exportedDocMiss: 'Exported {name} ({n} pages, {miss} screens could not be captured)',
1136
+ exHtml: 'Clickable HTML demo (opens with a double-click)',
1137
+ exportedHtml: 'Exported {name} ({n} screens; anyone can open it with a double-click)',
1138
+ exportedHtmlMiss: 'Exported {name} ({n} screens, {miss} could not be read)',
1139
+ htmlTooBig: 'Too many images: the demo would be over 150 MB, so nothing was exported. Try with fewer screens',
1140
+ htmlNoScreens: 'None of the screens could be read (moved or deleted?), so nothing was exported',
1131
1141
  xoTitle: 'Export options',
1132
1142
  xoTip: 'Leave these alone and the file comes out the same as a direct export.',
1133
1143
  xoWarn: 'Some content would be cut off. Have a look first',
@@ -9019,7 +9029,7 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
9019
9029
  // x:这一次画面的值(会话、状态、类型、画幅、几屏…)、几个 ref(各屏接口、背后挂的那批、设计序号)和面板里共用的 apiOf / targetKey
9020
9030
  // onWarn:预检发现会被裁时打开导出选项
9021
9031
  function makeExporter(x) {
9022
- const { sid, st, kind, size, dark, meta, tokens, t, say, canvas, focus, sel, shown, ik, labelOf, infoOf, fileTarget, ver, apis, designNow, designSeq, ghostApis, ghostBatch, ghostQueue, setBackFrames, warned, onWarn, apiOf, targetKey } = x
9032
+ const { sid, st, kind, size, dark, meta, tokens, t, say, canvas, focus, sel, shown, ik, labelOf, infoOf, fileTarget, ver, apis, designNow, designSeq, ghostApis, ghostBatch, ghostQueue, setBackFrames, warned, onWarn, apiOf, targetKey, tops, tweak, webFit } = x
9023
9033
  // 截一屏:图片和它的 CSS 尺寸(PDF / PPT 按这个定页面大小)
9024
9034
  // 这次导出截到的 AI 示意图(文件名去重):每种导出结束的提示里都带一句「上线前换成真实照片」
9025
9035
  const aiTail = (ai) => (ai && ai.size ? ' · ' + t('xoAi', { n: ai.size }) : '')
@@ -9187,7 +9197,40 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
9187
9197
  say(e.message === 'designChanged' ? t('xoGone') : t('exportFail', { msg: e.message }))
9188
9198
  }
9189
9199
  }
9190
- return { withFrames, measureAll, exportShots }
9200
+ // 整套 HTML 演示(#26):服务端把每屏连同样式、图片、图标打进一个 .html,不截图(几秒出来)。
9201
+ // 屏、版本、画幅、深浅色、调节滑块没存的值都按眼前的;外壳在演示页面里能开关
9202
+ const exportHtml = async () => {
9203
+ if (!fileTarget) return
9204
+ say(t('exporting'))
9205
+ try {
9206
+ const list = []
9207
+ const seen = new Set()
9208
+ for (const sc of shown) { // 看旧版本时 shown 就是那一版的几屏(都带 v)
9209
+ if (seen.has(sc.key)) continue
9210
+ seen.add(sc.key)
9211
+ list.push(sc)
9212
+ }
9213
+ const sp = splitTitles(list.map((sc) => (infoOf(ik(sc)) || {}).title || sc.label))
9214
+ const folder = st && st.target && st.target.kind === 'file' ? String(st.target.file).split(/[\\/]/).slice(-2, -1)[0] : ''
9215
+ const title = sp.brand || folder || st.label || ''
9216
+ const r = await post('htmlpack', {
9217
+ session: sid, target: targetKey, v: ver ? ver.n : 0,
9218
+ name: (ver ? `v${ver.n}-` : '') + (title || 'design') + (dark ? '-dark' : ''),
9219
+ title, lang: t('lang') === 'en' ? 'en' : 'zh', kind, w: size[0], h: size[1], os: meta.os || '', dark: !!dark, tweak: ver ? null : tweak || null, // 旧版本不套调节滑块的值(和画布上一样)
9220
+ // 没开「深色」时页面跟着系统深浅色走:记下右侧栏这会儿是哪种,演示里照这个显示(不跟看的人电脑走)
9221
+ scheme: typeof matchMedia === 'function' && matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light',
9222
+ fit: !!webFit, // 网页开着「按画幅显示」:演示里默认也套浏览器框、按画幅缩放
9223
+ screens: list.map((sc) => ({ key: sc.key, label: labelOf(sc), top: !!(tops && tops[ik(sc)]) })),
9224
+ })
9225
+ const file = String(r.path || '').split(/[\\/]/).pop()
9226
+ const miss = Array.isArray(r.missing) ? r.missing.length : 0
9227
+ say((miss ? t('exportedHtmlMiss', { name: file, n: r.count, miss }) : t('exportedHtml', { name: file, n: r.count })) + (r.ai ? ' · ' + t('xoAi', { n: r.ai }) : ''), { label: t('reveal'), run: () => post('reveal', { path: r.path }).catch(() => {}) })
9228
+ } catch (e) {
9229
+ const m = String((e && e.message) || '')
9230
+ say(m === 'designChanged' || m === 'not-file' ? t('xoGone') : m === 'tooBig' ? t('htmlTooBig') : m === 'noScreens' ? t('htmlNoScreens') : t('exportFail', { msg: m }))
9231
+ }
9232
+ }
9233
+ return { withFrames, measureAll, exportShots, exportHtml }
9191
9234
  }
9192
9235
 
9193
9236
  // ── 画笔标注(从预览面板里拆出来的):台面上看得到的几屏截图拼好、叠上画的,存进 refs/ 交给模型,或者复制
@@ -10305,7 +10348,7 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
10305
10348
  }
10306
10349
  // ── 导出图片(makeExporter)──
10307
10350
  // 在和做出来的比:导出的「这一屏」是比的那屏,画布没挂着(别的屏在背后挂)
10308
- const { withFrames, measureAll, exportShots } = makeExporter({ apiOf, targetKey, sid, st, kind, size, dark, meta, tokens, t, say, canvas: canvas && !implSc, focus: implSc ? implSc.key : focus, sel, shown, ik, labelOf, infoOf, fileTarget, ver, apis, designNow, designSeq, ghostApis, ghostBatch, ghostQueue, setBackFrames, warned,
10351
+ const { withFrames, measureAll, exportShots, exportHtml } = makeExporter({ apiOf, targetKey, sid, st, kind, size, dark, meta, tokens, t, say, canvas: canvas && !implSc, focus: implSc ? implSc.key : focus, sel, shown, ik, labelOf, infoOf, fileTarget, ver, apis, designNow, designSeq, ghostApis, ghostBatch, ghostQueue, setBackFrames, warned, tops, tweak, webFit,
10309
10352
  onWarn: () => { if (pane !== 'export') openPane('export') } })
10310
10353
  const designId = JSON.stringify([sid, targetKey, ver ? ver.n : 0])
10311
10354
  if (designNow.current !== designId) { designNow.current = designId; designSeq.current++ }
@@ -10314,6 +10357,7 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
10314
10357
  if (mode === 'opts') { if (pane !== 'export') openPane('export'); return }
10315
10358
  if (mode === 'zip') return openPack(fileTarget ? st.target.root : '')
10316
10359
  if (mode === 'share') return openShare(fileTarget ? st.target.root : '')
10360
+ if (mode === 'html') return exportHtml()
10317
10361
  return exportShots(mode, key, opts)
10318
10362
  }
10319
10363
 
@@ -10632,6 +10676,7 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
10632
10676
  ['', I.overlay, t('implCmp'), !!implSc, !!ver || !exSc || implFar, () => (implSc ? implClose() : implOpen(exSc.key))],
10633
10677
  'hd:' + t('exFiles'),
10634
10678
  ...exportItems(t, kind, shown.length, exName).map(([mode, Icon, label]) => ['', Icon, label, false, false, () => doExport(mode)]),
10679
+ fileTarget ? ['', I.web, t('exHtml'), false, false, () => doExport('html')] : null, // 只有本地文件的设计能打成 HTML(开发服务器的页面靠它跑)
10635
10680
  fileTarget ? 'hd:' + t('deliverShare') : null, // 只有本地的设计才能打包、分享
10636
10681
  fileTarget ? ['', I.box, t('exZip'), false, false, () => doExport('zip')] : null,
10637
10682
  fileTarget ? ['', I.share, t('exShare'), false, false, () => doExport('share')] : null,
package/lib/handoff.js CHANGED
@@ -971,9 +971,11 @@ export async function compareScreens(browser, { design, impl, shown = '', size,
971
971
  return { png, blocks, pageH, blocked: page.blocked ? page.blocked.slice() : [] }
972
972
  })
973
973
  // 一个接一个截:同时开两个页面时系统字体(中文)偶尔还没画好就截了,差异会虚高
974
- const A = await shoot(design.url, true, [w, h])
974
+ // 刚写完文件就比:预览服务器的「改了自动刷新」可能在截图途中把页面刷新一次(页面没了)→ 重截一次
975
+ const again = (fn) => fn().catch((e) => (!blocked.length && /navigated or closed/i.test(e.message) ? fn() : Promise.reject(e)))
976
+ const A = await again(() => shoot(design.url, true, [w, h]))
975
977
  if (slot && slot.hidden) return { pct: null, boxes: [], jpg: null, text: `没比:${design.label || design.key} 套了外框,按 ${w}×${h} 开时外框里的 main 槽位露不出来。size 填外框自己的尺寸 ${slot.fw}x${slot.fh} 再比。` }
976
- const B = await shoot(impl, false, slot ? [slot.w, slot.h] : [w, h]).catch((e) => {
978
+ const B = await again(() => shoot(impl, false, slot ? [slot.w, slot.h] : [w, h])).catch((e) => {
977
979
  // 页面自己跳到外网被拦下、截图时页面没了:说清楚是跳走了
978
980
  if (blocked.length) throw new Error(`做出来的页面跳到了本机以外的地址,拦下了:${blocked[0].slice(0, 120)}`)
979
981
  throw e
@@ -0,0 +1,693 @@
1
+ /**
2
+ * 导出「整套 HTML 演示」(#26):所有屏打成一个 .html,发给别人双击就能在浏览器里看、点得动、带外壳。
3
+ * 不联网、不用 AI,几秒出来。
4
+ *
5
+ * 每屏用 bundle.js 打成一整份(样式、脚本、图片、图标雪碧图都内联,和远程看同一套),塞进播放器页面;
6
+ * 播放器只把正在看的那屏放进沙盒 iframe 的 srcdoc。几屏共用的大图(AI 示意图、字体)只存一份。
7
+ * 屏里的跳转(<a href="detail.html">、data-href、onclick="location.href=…"、脚本跳转)由每屏带的小脚本
8
+ * 告诉播放器换屏,和设计台里「试用」一样;站外链接开新标签页。
9
+ *
10
+ * 外壳的尺寸(FRAME / CAP / LIGHTS / WINBTN)和认跳转的写法(LINK_SEL / LINK_JS)和 client.js、picker.js 是同一份数,
11
+ * 测试里逐项比着,改一边另一边会报。
12
+ */
13
+
14
+ import crypto from 'node:crypto'
15
+ import { bundle, strictMeta } from './bundle.js'
16
+ import { defang } from './serve.js'
17
+
18
+ /** 每屏的 <base>:一个不存在的地址(.invalid 不会被解析),屏里的相对链接都落在它下面,小脚本据此认出「站内跳转」 */
19
+ export const PACK_ORIGIN = 'https://ddp-pack.invalid'
20
+ export const PACK_MAX = 150 * 1024 * 1024 // 整个文件的上限(字符数):再大浏览器打开就很慢了
21
+ export const PACK_SCREENS = 60 // 和画布的屏数上限一样
22
+ const ASSET_MIN = 2048 // 这么长以上的 data: 地址单独存一份(几屏共用的只存一次)
23
+
24
+ // ── 和 client.js 同一份数(测试比着)────────────────────────────────────────
25
+ export const FRAME = {
26
+ web: { pad: 0, top: 34, r: 10, ir: 0 },
27
+ app: { pad: 11, top: 0, r: 55, ir: 44, island: 11 },
28
+ miniprogram: { pad: 11, top: 0, r: 55, ir: 44, island: 11, capsule: 1 },
29
+ tablet: { pad: 14, top: 0, r: 34, ir: 21 },
30
+ desktop: { pad: 0, top: 0, r: 12, ir: 12, win: 1 },
31
+ poster: { pad: 0, top: 0, r: 6, ir: 6 },
32
+ slides: { pad: 0, top: 0, r: 8, ir: 8 },
33
+ email: { pad: 0, top: 0, r: 10, ir: 10 },
34
+ diagram: { pad: 0, top: 0, r: 8, ir: 8 },
35
+ dshplugin: { pad: 0, top: 0, r: 10, ir: 10 },
36
+ framed: { pad: 0, top: 0, r: 10, ir: 10 },
37
+ }
38
+ export const CAP = { top: 48, right: 7, w: 87, h: 32 }
39
+ export const LIGHTS = { x: 20, y: 20, d: 12, gap: 8 }
40
+ export const WINBTN = { w: 46, h: 32 }
41
+ /** 有外壳可开关的类型(手机、平板、桌面软件、网页浏览器框) */
42
+ export const FRAMED = { app: 1, miniprogram: 1, tablet: 1, desktop: 1, web: 1 }
43
+ /** 画幅定死的类型:放映时可以放大铺满(幻灯片、海报) */
44
+ export const FIXED = { poster: 1, slides: 1, diagram: 1, dshplugin: 1, framed: 1 }
45
+
46
+ // ── 和 picker.js 同一份(测试比着):哪些元素点了会跳页 ─────────────────────────
47
+ export const LINK_SEL = 'a[href], [data-href], [data-to], [onclick]'
48
+ export const LINK_JS = /(?:location(?:\.href)?\s*=\s*|location\.(?:assign|replace)\(\s*)['"]([^'"]+)['"]/
49
+
50
+ /** 某个大小的外框:矮的手机没有灵动岛(和 client.js 的 frameOf 一样) */
51
+ export function frameOf(kind, w, h) {
52
+ const f = FRAME[kind] || FRAME.web
53
+ return f.island && w && h / w < 1.9 ? { ...f, island: 0 } : f
54
+ }
55
+
56
+ /** JSON 放进 <script type="application/json">:< 和两个行分隔符转义,</script> 断不了它 */
57
+ const jsonTag = (v) => JSON.stringify(v).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')
58
+ const escHtml = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
59
+
60
+ /**
61
+ * 每屏最前面:沙盒里的页面(不透明的源)一碰 localStorage / sessionStorage 就报错,
62
+ * 换成存在内存里的一份;存的东西告诉播放器,换到别的屏时带过去(登录页存的名字,下一屏读得到)。
63
+ * 初始内容由播放器在放进 iframe 前替换 STORE 那个记号
64
+ */
65
+ function storeShim(D) {
66
+ const send = (area, op, k, v) => { try { parent.postMessage({ ddpPack: 1, type: 'store', area, op, k, v }, '*') } catch { /* 没有外层 */ } }
67
+ const make = (area) => {
68
+ const m = new Map(Object.entries((D && D[area]) || {}))
69
+ const api = {
70
+ getItem: (k) => (m.has(String(k)) ? m.get(String(k)) : null),
71
+ setItem: (k, v) => { m.set(String(k), String(v)); send(area, 'set', String(k), String(v)) },
72
+ removeItem: (k) => { m.delete(String(k)); send(area, 'del', String(k)) },
73
+ clear: () => { m.clear(); send(area, 'clear') },
74
+ key: (i) => [...m.keys()][i] ?? null,
75
+ }
76
+ // localStorage.theme = 'dark'、localStorage.theme 这种写法也认
77
+ return new Proxy(api, {
78
+ get: (o, p) => (p === 'length' ? m.size : typeof p === 'symbol' || Object.hasOwn(o, p) ? o[p] : m.has(p) ? m.get(p) : undefined),
79
+ set: (o, p, v) => { if (typeof p === 'string') api.setItem(p, v); return true },
80
+ deleteProperty: (o, p) => { if (typeof p === 'string') api.removeItem(p); return true },
81
+ has: (o, p) => Object.hasOwn(o, p) || m.has(p),
82
+ ownKeys: () => [...m.keys()],
83
+ getOwnPropertyDescriptor: (o, p) => (m.has(p) ? { value: m.get(p), enumerable: true, configurable: true, writable: true } : undefined),
84
+ })
85
+ }
86
+ for (const [name, area] of [['localStorage', 'l'], ['sessionStorage', 's']]) {
87
+ let broken = false
88
+ try { void window[name].length } catch { broken = true }
89
+ if (broken) { try { Object.defineProperty(window, name, { value: make(area), configurable: true }) } catch { /* 改不了就算了 */ } }
90
+ }
91
+ }
92
+
93
+ /**
94
+ * 每屏最前面(页面脚本跑之前就装好):点了跳到别的屏 → 告诉播放器换屏;页内锚点自己滚;站外链接开新标签页。
95
+ * 和 picker.js 里「试用 / 远程看」的拦法一样(LINK_SEL、LINK_JS 同一份);再加上调节滑块的值、不画滚动条
96
+ */
97
+ function navScript(C) {
98
+ const SEL = C.sel
99
+ const JS = new RegExp(C.js)
100
+ const post = (m) => { try { parent.postMessage({ ddpPack: 1, ...m }, '*') } catch { /* 没有外层 */ } }
101
+ const here = () => new URL(document.baseURI)
102
+ const style = (css) => { const s = document.createElement('style'); s.textContent = css; (document.head || document.documentElement).appendChild(s) }
103
+ style('*{scrollbar-width:none}*::-webkit-scrollbar{display:none}')
104
+
105
+ // 调节滑块调过、还没存进文件的值(和 picker 的 applyTweak 一样写在 <html> 上)
106
+ const de = document.documentElement
107
+ for (const [k, v] of Object.entries((C.tweak && C.tweak.vars) || {})) { try { de.style.setProperty(k, String(v), 'important') } catch { /* 不认的值 */ } }
108
+ 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 { /* 不认的名字 */ } }
109
+
110
+ /** 这个地址是不是跳到演示包里的别的屏:{ path, hash };同一页(只有锚点)给 { same, hash };站外给 { out } */
111
+ const where = (raw) => {
112
+ raw = String(raw || '').trim()
113
+ if (!raw || /^(javascript|mailto|tel|sms|data|blob):/i.test(raw)) return null
114
+ let u
115
+ try { u = new URL(raw, document.baseURI) } catch { return null }
116
+ if (u.origin !== C.origin) return /^https?:$/.test(u.protocol) ? { out: u.href } : null
117
+ // href="#"(「全部」)的 u.hash 是空串:记成 '#',和「同一页、没锚点」(导航栏里指着本页)分开
118
+ if (u.pathname === here().pathname) return { same: true, hash: u.hash || (/#$/.test(u.href) ? '#' : '') }
119
+ let p = u.pathname
120
+ try { p = decodeURIComponent(p) } catch { /* 原样 */ }
121
+ return { path: p, hash: u.hash }
122
+ }
123
+ const rawOf = (el) => {
124
+ let raw = el.getAttribute('href') || el.getAttribute('data-href') || el.getAttribute('data-to') || ''
125
+ if (!raw && el.hasAttribute('onclick')) { const m = JS.exec(el.getAttribute('onclick') || ''); if (m) raw = m[1] }
126
+ return raw
127
+ }
128
+ // 页内锚点:照常改这一页的 #(页面里按 # 换内容的写法照样能用);<base> 指着别处,不能让链接自己跳
129
+ const jumpTo = (hash) => {
130
+ hash = String(hash || '')
131
+ if (hash && hash !== '#' && location.hash !== hash) { location.hash = hash; return }
132
+ // 点过「待配送」#tab2 再点「全部」href="#":清掉旧的 #(按 hashchange 换内容的页面回到默认),浏览器自己滚回顶上
133
+ if (hash === '#' && location.hash) { location.hash = ''; return }
134
+ let id = hash.replace(/^#/, '')
135
+ try { id = decodeURIComponent(id) } catch { /* 原样 */ }
136
+ const t = id ? document.getElementById(id) || document.getElementsByName(id)[0] : null
137
+ if (t) t.scrollIntoView({ block: 'start' })
138
+ else if (!id || id === 'top') scrollTo({ top: 0 })
139
+ }
140
+ const go = (w, e) => {
141
+ if (!w) return false
142
+ if (w.out) {
143
+ const a = e && e.target && e.target.closest ? e.target.closest('a[href]') : null
144
+ if (a && a.target && a.target !== '_self') return false // 本来就开新窗口:随它(沙盒放行了弹窗)
145
+ window.open(w.out, '_blank', 'noopener')
146
+ return true
147
+ }
148
+ if (w.same) { jumpTo(w.hash); return true }
149
+ post({ type: 'nav', path: w.path, hash: w.hash })
150
+ return true
151
+ }
152
+
153
+ // 跳到别的屏、站外。自己做的屏(收得到 navigate):<a href> 让浏览器照常跳,下面的 navigate 按最终地址接住——
154
+ // 页面自己的点击处理先跑完(「去结算」先存购物车、点的时候才改 href),拦了默认行为就不跳,和真浏览器一样;
155
+ // 地址只写在 onclick 里的(onclick="if (!同意) {…; return} location.href='x'"),页面真跳了 navigate 也接住;
156
+ // data-href / data-to 没有原生跳转:事件派发完(页面 stopPropagation 了也算)按那时的地址补一次。
157
+ // 收不到 navigate 的(别人做的屏不同源、很旧的浏览器):照设计台「试用」,点的那一下就拦(页面自己的点击处理就不跑了)
158
+ // 有 navigation 对象不等于发 navigate(文档源不透明时按规范不发,currentEntry 是 null):那种照老办法
159
+ const hasNav = !!(window.navigation && navigation.currentEntry && typeof navigation.addEventListener === 'function')
160
+ const early = !!C.strict || !hasNav
161
+ let pending = null
162
+ addEventListener('click', (e) => {
163
+ pending = null
164
+ // 冒泡那个排到页面在 window 上的点击监听后面(这一次点击里):页面「确定要离开吗」拦了,我们就不开外网
165
+ removeEventListener('click', after); addEventListener('click', after)
166
+ if (e.button !== 0) return
167
+ const el = e.target && e.target.closest ? e.target.closest(SEL) : null
168
+ if (!el) return
169
+ const a = el.closest('a[href], area[href]')
170
+ // 新窗口打开(target="_blank"、按着 ⌘ / Ctrl / Shift 点)指着包里别的屏:新窗口里开不了,还是在这儿换屏
171
+ const newWin = a && ((a.target && a.target !== '_self') || e.metaKey || e.ctrlKey || e.shiftKey)
172
+ if (!early && !newWin) {
173
+ if (a || (!el.getAttribute('data-href') && !el.getAttribute('data-to'))) return
174
+ // 只补「事件传到了 el」的:卡片(data-href)里的「收藏」按钮自己 stopPropagation,就是不想连带打开卡片
175
+ const mine = { el, e, reached: false }
176
+ const mark = () => { mine.reached = true }
177
+ el.addEventListener('click', mark, { once: true })
178
+ pending = mine
179
+ setTimeout(() => {
180
+ el.removeEventListener('click', mark)
181
+ if (pending === mine) { pending = null; if (mine.reached) finish(mine) }
182
+ }, 0)
183
+ return
184
+ }
185
+ const w = where(rawOf(el))
186
+ if (!w || w.same) return // 本页锚点(href="#"、"#tab2"):页面自己的点击处理照跑,见下面
187
+ if (w.out && (!a || newWin)) return // 外网:新窗口的随它开(沙盒放行了弹窗);data-href / onclick 指着外网的交给 navigate
188
+ if (go(w, e)) { e.preventDefault(); e.stopPropagation() }
189
+ }, true)
190
+ const finish = ({ el, e }) => {
191
+ if (e.defaultPrevented) return
192
+ const w = where(el.getAttribute('data-href') || el.getAttribute('data-to') || '')
193
+ if (!w || w.out) return // 外网:页面自己跳了由 navigate 接住
194
+ if (w.same) { if (w.hash && w.hash !== '#') jumpTo(w.hash); return } // data-href="#" 占位:不动
195
+ go(w, e)
196
+ }
197
+ // 页面自己处理完、没拦默认行为(每次点击都排到 window 上最后一个):
198
+ // 本页锚点(收不到 navigate 时)替它滚过去(<base> 指着别处,链接自己跳就离开这一屏了);收得到 navigate 的让浏览器照常跳,
199
+ // 由 navigate 按最终地址接住(href="#" 占位、点的时候页面才改成别的屏);
200
+ // 本页锚点要开新窗口的(页脚 <a href="#" target="_blank">、按着 ⌘ 点 #tab2):新窗口里是假地址,留在这儿滚
201
+ // 外网链接(没写 target)在点击里就开新标签页:放到 navigate 回调里开,Safari 可能当成弹窗拦掉
202
+ const after = (e) => {
203
+ if (e.defaultPrevented || e.button !== 0) return
204
+ const a = e.target && e.target.closest ? e.target.closest('a[href], area[href]') : null
205
+ const w = a ? where(a.getAttribute('href')) : null
206
+ if (!w) return
207
+ const newWin = (a.target && a.target !== '_self') || e.metaKey || e.ctrlKey || e.shiftKey
208
+ if (w.same && (early || newWin)) { e.preventDefault(); jumpTo(w.hash) }
209
+ else if (w.out && !early && !newWin) { e.preventDefault(); window.open(w.out, '_blank', 'noopener') }
210
+ }
211
+
212
+ // 脚本里跳页(location.href = 'x.html'、表单提交):有 Navigation API 的浏览器(Chrome、Edge、新的 Safari / Firefox)也拦下来
213
+ if (hasNav) {
214
+ navigation.addEventListener('navigate', (e) => {
215
+ if (!e.cancelable || e.navigationType === 'traverse' || e.downloadRequest) return
216
+ const dest = (e.destination && e.destination.url) || ''
217
+ // 没写 action 的表单(搜索框按回车)交给这一页自己(about:srcdoc?…):留在这一屏,不然这屏就没了
218
+ if (!e.hashChange && /^about:srcdoc/i.test(dest) && (e.formData || /^about:srcdoc\?/i.test(dest))) { e.preventDefault(); return }
219
+ const w = where(dest)
220
+ if (!w) return
221
+ e.preventDefault()
222
+ pending = null // 点击里页面自己跳了:冒泡那边不再换一次
223
+ if (w.out && e.formData) return // 往外网交表单:不交
224
+ go(w)
225
+ })
226
+ }
227
+
228
+ // 播放器让滚到某个锚点(从别的屏跳过来带着 #xx)
229
+ addEventListener('message', (e) => {
230
+ if (e.source !== parent) return
231
+ const d = e.data
232
+ if (d && d.ddpPack === 1 && d.type === 'jump') jumpTo(d.hash)
233
+ })
234
+
235
+ // ← → 换屏(点进页面以后键盘在页面里):页面自己没用、也不是在输入框里才交给播放器。
236
+ // PageUp / PageDown 在能滚的页面里是往下看:只有画幅定死的(幻灯片、海报…)才拿来换屏
237
+ const KEYS = C.pages ? /^(ArrowLeft|ArrowRight|PageUp|PageDown)$/ : /^(ArrowLeft|ArrowRight)$/
238
+ addEventListener('keydown', (e) => {
239
+ if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || !KEYS.test(e.key)) return
240
+ const t = e.target
241
+ if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return
242
+ post({ type: 'key', key: e.key })
243
+ })
244
+ }
245
+
246
+ /**
247
+ * 每屏最后(样式表都读进来了):深浅色按导出那一刻右侧栏的样子定死,不跟看的人电脑的深浅色走。
248
+ * dark:右侧栏开着「深色」——和 picker 的 setDark 一样,<html> 上三种写法都打上,深色的媒体条件当成立
249
+ * media:没开「深色」,但右侧栏当时就是深色环境(页面跟着系统变深)——深色的媒体条件当成立
250
+ * light:浅色环境——浅色的当成立、深色的当不成立,对方电脑是深色也照浅色显示
251
+ * 只改媒体条件里 prefers-color-scheme 那一项(「深色且窄屏」这种别的条件照旧),样式的先后不动
252
+ */
253
+ function schemeScript(mode) {
254
+ const de = document.documentElement
255
+ if (mode === 'dark') {
256
+ de.setAttribute('data-theme', 'dark')
257
+ de.setAttribute('data-mode', 'dark')
258
+ de.classList.add('dark')
259
+ }
260
+ const dark = mode !== 'light'
261
+ const YES = '(min-width: 0px)'
262
+ const NO = '(min-width: 99999px)'
263
+ const fix = (ml) => {
264
+ try {
265
+ const t = ml && ml.mediaText
266
+ if (t && /prefers-color-scheme/i.test(t)) ml.mediaText = t.replace(/\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)/gi, (m, v) => ((v.toLowerCase() === 'dark') === dark ? YES : NO))
267
+ } catch { /* 改不了 */ }
268
+ }
269
+ const walk = (list) => {
270
+ for (const r of list) {
271
+ if (r.media) fix(r.media)
272
+ if (r.cssRules) { try { walk(r.cssRules) } catch { /* 读不了 */ } }
273
+ }
274
+ }
275
+ for (const sh of document.styleSheets) {
276
+ fix(sh.media) // <style media="(prefers-color-scheme: dark)">
277
+ try { walk(sh.cssRules) } catch { /* 读不了 */ }
278
+ }
279
+ // 表单控件、滚动区的底色:开着「深色」、浅色环境都定死;深色环境只在页面自己声明了支持深色时定
280
+ let cs = mode === 'light' ? 'light' : mode === 'dark' ? 'dark' : ''
281
+ // 页面自己声明的:CSS 的 color-scheme,没写(normal)再看 <meta name="color-scheme">
282
+ let own = getComputedStyle(de).colorScheme || ''
283
+ if (!own || own === 'normal') { const m = document.querySelector('meta[name="color-scheme" i]'); own = (m && m.getAttribute('content')) || '' }
284
+ if (mode === 'media' && /dark/.test(own)) cs = 'dark'
285
+ if (mode === 'light' && /dark/.test(own) && !/light/.test(own)) cs = '' // 页面只做了深色(color-scheme: dark):控件照它的深色
286
+ if (cs) {
287
+ const s = document.createElement('style')
288
+ s.textContent = `:root{color-scheme:${cs}}`
289
+ ;(document.head || de).appendChild(s)
290
+ }
291
+ }
292
+
293
+ /** 播放器(外面那层):换屏、外壳、缩放、全屏;数据都在页面里的 JSON 里 */
294
+ function player() {
295
+ const $ = (id) => document.getElementById(id)
296
+ const C = JSON.parse($('ddp-cfg').textContent)
297
+ const T = C.strings
298
+ const N = C.screens.length
299
+ const cache = new Map()
300
+ const assetRe = new RegExp(C.token + '(\\d+)_', 'g')
301
+ const assets = new Map()
302
+ const asset = (i) => {
303
+ if (!assets.has(i)) { const el = $('ddp-a-' + i); assets.set(i, el ? JSON.parse(el.textContent) : '') }
304
+ return assets.get(i)
305
+ }
306
+ const store = { l: {}, s: {} }
307
+ const htmlOf = (i) => {
308
+ if (!cache.has(i)) {
309
+ cache.set(i, JSON.parse($('ddp-s-' + i).textContent).replace(assetRe, (m, n) => asset(Number(n))))
310
+ if (cache.size > 8) cache.delete(cache.keys().next().value) // 屏多、图大:只留最近放过的几屏
311
+ }
312
+ // 存储的初始内容:每次放进去都是当时的(上一屏刚存的这一屏读得到)
313
+ return cache.get(i).replace(C.storeMark, () => JSON.stringify(store).replace(/</g, '\\u003c'))
314
+ }
315
+ let shell = !!C.shellDefault
316
+ // 看的人开关过外壳就记着(每份演示自己记:别的演示点过不影响这份导出时定的默认)
317
+ const SHELL_KEY = 'ddp-pack-shell-' + C.token // 每份演示自己记(直接双击打开的本地文件共用一份 localStorage)
318
+ try { const v = localStorage.getItem(SHELL_KEY); if (C.framed && (v === '1' || v === '0')) shell = v === '1' } catch { /* 存不了 */ }
319
+ let cur = -1
320
+ let seq = 0
321
+ let pendingHash = ''
322
+ const stage = $('stage')
323
+ const bar = $('bar')
324
+ const sel = $('sel')
325
+ const count = $('count')
326
+ const toast = $('toast')
327
+
328
+ C.screens.forEach((s, i) => { const o = document.createElement('option'); o.value = String(i); o.textContent = `${i + 1}. ${s.label}`; sel.appendChild(o) })
329
+ if (!C.framed) $('shell').hidden = true
330
+ if (N < 2) { $('prev').hidden = true; $('next').hidden = true; sel.disabled = true }
331
+ if (!document.fullscreenEnabled) $('full').hidden = true
332
+
333
+ // 小屏幕看手机的设计(在手机上打开):不套外壳、铺满,工具条收成顶上正中一个小按钮
334
+ // (放在页面假状态栏那条上:那里没有能点的东西;底栏、右下角都是 App 自己的导航)
335
+ const compact = () => (C.kind === 'app' || C.kind === 'miniprogram') && innerWidth <= 600
336
+ // 网页不开外壳:铺满窗口(和设计台单看一样,宽度跟着窗口)
337
+ const fills = () => compact() || (C.kind === 'web' && !shell)
338
+
339
+ let toastTimer = 0
340
+ const say = (msg) => { toast.textContent = msg; toast.hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => { toast.hidden = true }, 2600) }
341
+
342
+ const svg = (tag, attrs, kids = []) => {
343
+ const el = document.createElementNS('http://www.w3.org/2000/svg', tag)
344
+ for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, String(v))
345
+ for (const c of kids) el.appendChild(c)
346
+ return el
347
+ }
348
+ const capsule = (f, white) => {
349
+ const { w, h } = C.cap
350
+ const el = svg('svg', { class: 'cap' + (white ? ' w' : ''), viewBox: `0 0 ${w} ${h}`, 'aria-hidden': 'true' }, [
351
+ svg('rect', { class: 'pl', x: 0.25, y: 0.25, width: w - 0.5, height: h - 0.5, rx: h / 2 - 0.25 }),
352
+ svg('circle', { cx: 20.5, cy: 16, r: 2.2 }), svg('circle', { cx: 28, cy: 16, r: 3.1 }), svg('circle', { cx: 35.5, cy: 16, r: 2.2 }),
353
+ svg('path', { class: 'sp', d: 'M43.5 9v14' }),
354
+ svg('circle', { class: 'rg', cx: 65, cy: 16, r: 7.5 }), svg('circle', { cx: 65, cy: 16, r: 2.6 }),
355
+ ])
356
+ el.style.top = (f.pad || 0) + C.cap.top + 'px'
357
+ el.style.right = (f.pad || 0) + C.cap.right + 'px'
358
+ return el
359
+ }
360
+ const winCtl = (white) => {
361
+ if (C.os === 'win') {
362
+ const { w: W, h: H } = C.winbtn
363
+ const el = svg('svg', { class: 'win' + (white ? ' w' : ''), viewBox: `0 0 ${W * 3} ${H}`, 'aria-hidden': 'true' }, [
364
+ svg('path', { class: 'x', d: `M${W / 2 - 5} ${H / 2 + 0.5}h10` }),
365
+ svg('rect', { class: 'x', x: W * 1.5 - 4.5, y: H / 2 - 4.5, width: 9, height: 9, rx: 1 }),
366
+ svg('path', { class: 'x', d: `M${W * 2.5 - 5} ${H / 2 - 5}l10 10M${W * 2.5 + 5} ${H / 2 - 5}l-10 10` }),
367
+ ])
368
+ Object.assign(el.style, { top: '0px', right: '0px', width: W * 3 + 'px', height: H + 'px' })
369
+ return el
370
+ }
371
+ const { x, y, d, gap } = C.lights
372
+ const el = svg('svg', { class: 'win', viewBox: `0 0 ${d * 3 + gap * 2} ${d}`, 'aria-hidden': 'true' },
373
+ ['#FF5F57', '#FEBC2E', '#28C840'].map((c, i) => svg('circle', { cx: d / 2 + i * (d + gap), cy: d / 2, r: d / 2 - 0.25, fill: c, stroke: 'rgba(0,0,0,.12)', 'stroke-width': 0.5 })))
374
+ Object.assign(el.style, { left: x + 'px', top: y + 'px', width: d * 3 + gap * 2 + 'px', height: d + 'px' })
375
+ return el
376
+ }
377
+
378
+ let dev = null
379
+ let vp = null
380
+ let box = null
381
+ let deco = [] // 跟着这一屏变的外壳零件(胶囊、窗口按钮的深浅)
382
+ /** 搭外框:开关外壳、手机上横竖转换时重搭(里面的 iframe 也重放);换屏只换 iframe */
383
+ function build() {
384
+ const fill = fills()
385
+ document.body.classList.toggle('compact', compact())
386
+ const f = fill || (C.framed && !shell) ? { pad: 0, top: 0, r: 0, ir: 0 } : C.frame
387
+ stage.textContent = ''
388
+ box = document.createElement('div')
389
+ box.className = 'fit' + (fill ? ' all' : '')
390
+ dev = document.createElement('div')
391
+ dev.className = `dev k-${C.kind}` + (fill ? ' fill' : '') + (C.framed && !shell && !fill ? ' bare' : '')
392
+ if (!fill) Object.assign(dev.style, { width: C.w + f.pad * 2 + 'px', height: C.h + f.pad * 2 + f.top + 'px', borderRadius: f.r + 'px' })
393
+ dev.dataset.pad = String(f.pad || 0)
394
+ if (f.top) {
395
+ const ch = document.createElement('div')
396
+ ch.className = 'chrome'
397
+ ch.style.height = f.top + 'px'
398
+ ch.innerHTML = '<i></i><i></i><i></i><span></span>'
399
+ dev.appendChild(ch)
400
+ }
401
+ vp = document.createElement('div')
402
+ vp.className = 'vp' + (C.dark ? ' dk' : '')
403
+ if (!fill) Object.assign(vp.style, { left: f.pad + 'px', top: f.pad + f.top + 'px', width: C.w + 'px', height: C.h + 'px', borderRadius: f.ir + 'px' })
404
+ dev.appendChild(vp)
405
+ if (f.island) { const is = document.createElement('div'); is.className = 'island'; is.style.top = (f.pad || 0) + f.island + 'px'; dev.appendChild(is) }
406
+ dev._f = f
407
+ deco = []
408
+ box.appendChild(dev)
409
+ stage.appendChild(box)
410
+ fit()
411
+ $('shell').setAttribute('aria-pressed', shell ? 'true' : 'false')
412
+ }
413
+ /** 外壳上跟着这一屏的:浏览器栏里的标题、胶囊 / 窗口按钮(顶栏深色时画白的) */
414
+ function decorate() {
415
+ const s = C.screens[cur]
416
+ const f = dev._f
417
+ const sp = dev.querySelector('.chrome span')
418
+ if (sp) sp.textContent = s.label
419
+ for (const d of deco) d.remove()
420
+ deco = []
421
+ if (f.capsule) deco.push(capsule(f, !!s.top))
422
+ if (f.win) deco.push(winCtl(!!s.top))
423
+ for (const d of deco) dev.appendChild(d)
424
+ }
425
+ /** 按窗口大小缩放:手机、网页、平板最大到原大;画幅定死的(幻灯片、海报)可以放大铺满 */
426
+ function fit() {
427
+ if (!dev || dev.classList.contains('fill')) return
428
+ const W = dev.offsetWidth, H = dev.offsetHeight
429
+ const r = stage.getBoundingClientRect()
430
+ const pad = r.width < 600 ? 12 : 32
431
+ let z = Math.min((r.width - pad * 2) / W, (r.height - pad * 2) / H)
432
+ if (!C.fixed) z = Math.min(z, 1)
433
+ z = Math.max(0.05, z)
434
+ Object.assign(box.style, { width: W * z + 'px', height: H * z + 'px' })
435
+ dev.style.transform = `scale(${z})`
436
+ }
437
+
438
+ /** 放一屏:新 iframe 在后面载好了再换上来(不白一下) */
439
+ function show(i, hash = '') {
440
+ const me = ++seq
441
+ const s = C.screens[i]
442
+ const fr = document.createElement('iframe')
443
+ fr.className = 'nx'
444
+ fr.title = s.label
445
+ // 自己做的屏和播放器同源(allow-same-origin):不同源(不透明)的文档里浏览器不发 navigate 事件,
446
+ // 脚本里 location.href = 'x.html' 就拦不住、整屏跳到假地址的报错页。别人做的屏页面脚本本来就跑不了(CSP),只给 allow-scripts
447
+ fr.setAttribute('sandbox', s.strict ? 'allow-scripts' : 'allow-scripts allow-same-origin allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox')
448
+ fr.setAttribute('referrerpolicy', 'no-referrer')
449
+ fr.style.colorScheme = C.dark ? 'dark' : 'light'
450
+ let done = false
451
+ const swap = () => {
452
+ if (done || me !== seq || !fr.isConnected) return
453
+ done = true
454
+ fr.classList.remove('nx')
455
+ for (const old of [...vp.querySelectorAll('iframe')]) if (old !== fr) setTimeout(() => old.remove(), 160)
456
+ if (hash) setTimeout(() => { try { fr.contentWindow.postMessage({ ddpPack: 1, type: 'jump', hash }, '*') } catch { /* 已经换掉了 */ } }, 60)
457
+ }
458
+ fr.addEventListener('load', swap)
459
+ setTimeout(swap, 2500) // 页面里有载不完的东西:别一直等
460
+ fr.srcdoc = htmlOf(i)
461
+ vp.appendChild(fr)
462
+ }
463
+
464
+ const indexOfHash = () => {
465
+ let h = ''
466
+ try { h = decodeURIComponent(location.hash.replace(/^#/, '')) } catch { h = '' }
467
+ const k = h ? C.screens.findIndex((s) => s.key === h) : -1
468
+ return k >= 0 ? k : 0
469
+ }
470
+ function render() {
471
+ const i = indexOfHash()
472
+ if (i === cur && dev) return
473
+ cur = i
474
+ sel.value = String(i)
475
+ count.textContent = T.of.replace('{i}', String(i + 1)).replace('{n}', String(N))
476
+ $('prev').disabled = i === 0
477
+ $('next').disabled = i === N - 1
478
+ const s = C.screens[i]
479
+ document.title = C.title && C.title !== s.label ? `${s.label} · ${C.title}` : s.label
480
+ if (!dev) build()
481
+ decorate()
482
+ const hash = pendingHash
483
+ pendingHash = ''
484
+ show(i, hash)
485
+ }
486
+ /** 外框重搭(开关外壳、横竖屏换了):当前这屏重放 */
487
+ const rebuild = () => { build(); decorate(); show(cur) }
488
+ const go = (i, hash = '') => {
489
+ if (i < 0 || i >= N) return
490
+ if (i === cur) { if (hash) { const fr = vp && [...vp.querySelectorAll('iframe:not(.nx)')].pop(); if (fr) fr.contentWindow.postMessage({ ddpPack: 1, type: 'jump', hash }, '*') } return }
491
+ pendingHash = hash
492
+ location.hash = '#' + encodeURIComponent(C.screens[i].key)
493
+ }
494
+ const keyOf = (p) => { let k = String(p || '').replace(/^\/+/, ''); if (!k || k.endsWith('/')) k += 'index.html'; return k }
495
+
496
+ addEventListener('message', (e) => {
497
+ const d = e.data
498
+ if (!d || d.ddpPack !== 1 || !vp || ![...vp.querySelectorAll('iframe')].some((f) => f.contentWindow === e.source)) return
499
+ if (d.type === 'nav') {
500
+ const k = keyOf(d.path)
501
+ let i = C.screens.findIndex((s) => s.key === k)
502
+ if (i < 0) i = C.screens.findIndex((s) => s.key === k + '.html')
503
+ if (i < 0) say(T.notIn.replace('{p}', k))
504
+ else go(i, typeof d.hash === 'string' ? d.hash : '')
505
+ } else if (d.type === 'store' && (d.area === 'l' || d.area === 's')) {
506
+ const m = store[d.area]
507
+ if (d.op === 'set') m[String(d.k)] = String(d.v)
508
+ else if (d.op === 'del') delete m[String(d.k)]
509
+ else if (d.op === 'clear') store[d.area] = {}
510
+ } else if (d.type === 'key') key(d.key)
511
+ })
512
+ const key = (k) => {
513
+ if (k === 'ArrowLeft' || k === 'PageUp') go(cur - 1)
514
+ else if (k === 'ArrowRight' || k === 'PageDown') go(cur + 1)
515
+ }
516
+ addEventListener('keydown', (e) => {
517
+ if (e.altKey || e.ctrlKey || e.metaKey || e.target === sel) return
518
+ if (/^(ArrowLeft|ArrowRight|PageUp|PageDown)$/.test(e.key)) { e.preventDefault(); key(e.key) }
519
+ })
520
+ $('prev').addEventListener('click', () => go(cur - 1))
521
+ $('next').addEventListener('click', () => go(cur + 1))
522
+ sel.addEventListener('change', () => { document.body.classList.remove('open'); go(Number(sel.value)) })
523
+ $('shell').addEventListener('click', () => {
524
+ shell = !shell
525
+ try { localStorage.setItem(SHELL_KEY, shell ? '1' : '0') } catch { /* 存不了 */ }
526
+ rebuild()
527
+ })
528
+ $('full').addEventListener('click', () => {
529
+ if (document.fullscreenElement) document.exitFullscreen().catch(() => {})
530
+ else document.documentElement.requestFullscreen().catch(() => {})
531
+ })
532
+ $('menu').addEventListener('click', () => document.body.classList.toggle('open'))
533
+ document.addEventListener('fullscreenchange', () => { $('full').textContent = document.fullscreenElement ? T.exitFull : T.full })
534
+ let wasCompact = compact()
535
+ addEventListener('resize', () => {
536
+ if (compact() !== wasCompact) { wasCompact = compact(); rebuild() } else fit()
537
+ })
538
+ addEventListener('hashchange', render)
539
+ bar.hidden = false // 先把工具条放出来再量舞台(不然第一次缩放按没有工具条的高度算)
540
+ render()
541
+ }
542
+
543
+ const STRINGS = {
544
+ zh: { prev: '上一屏', next: '下一屏', shell: '外壳', shellTip: '套上手机 / 浏览器外壳', full: '全屏', exitFull: '退出全屏', of: '{i} / {n}', notIn: '这一屏不在演示里:{p}', menu: '换屏', screens: '选屏' },
545
+ 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' },
546
+ }
547
+
548
+ const CSS = `
549
+ :root{--stage:#e8e9ed;--bar:#fbfbfc;--fg:#1d1d22;--mute:#6b6b74;--line:rgba(0,0,0,.09);--btn:#f0f0f3;--btn-h:#e4e4e9;--acc:#4d6bfe;color-scheme:light}
550
+ @media (prefers-color-scheme:dark){:root{--stage:#141417;--bar:#1d1d21;--fg:#ececf1;--mute:#9a9aa6;--line:rgba(255,255,255,.08);--btn:#29292f;--btn-h:#33333a;color-scheme:dark}}
551
+ *{box-sizing:border-box}
552
+ [hidden]{display:none!important}
553
+ html,body{margin:0;height:100%;overflow:hidden}
554
+ body{background:var(--stage);color:var(--fg);font:14px/1.4 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei","Segoe UI",sans-serif;display:flex;flex-direction:column}
555
+ #bar{flex:none;display:flex;align-items:center;gap:8px;height:48px;padding:0 max(14px,env(safe-area-inset-right)) 0 max(14px,env(safe-area-inset-left));background:var(--bar);border-bottom:1px solid var(--line)}
556
+ #bar .ttl{flex:1 1 0;min-width:0;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
557
+ #bar .mid{flex:none;display:flex;align-items:center;gap:6px}
558
+ #bar .end{flex:1 1 0;display:flex;justify-content:flex-end;gap:6px;min-width:0}
559
+ #bar button,#bar select{height:30px;border:0;border-radius:8px;background:var(--btn);color:var(--fg);font:inherit;font-size:13px;padding:0 11px;cursor:pointer}
560
+ #bar button:hover:not(:disabled),#bar select:hover{background:var(--btn-h)}
561
+ #bar button:disabled{opacity:.4;cursor:default}
562
+ #bar button:focus-visible,#bar select:focus-visible{outline:2px solid var(--acc);outline-offset:1px}
563
+ #bar .arw{width:30px;padding:0;font-size:16px;line-height:30px}
564
+ #bar select{max-width:min(42vw,280px);padding-right:8px}
565
+ #count{color:var(--mute);font-size:12px;font-variant-numeric:tabular-nums;min-width:44px;text-align:center}
566
+ #shell[aria-pressed=true]{background:var(--acc);color:#fff}
567
+ #stage{flex:1;min-height:0;position:relative;display:flex;align-items:center;justify-content:center;overflow:hidden}
568
+ .fit{position:relative;flex:none}
569
+ .dev{position:absolute;left:0;top:0;transform-origin:0 0;background:#fff;box-shadow:0 0 0 .5px rgba(0,0,0,.14),0 18px 48px rgba(0,0,0,.2)}
570
+ .dev.fill{position:absolute;inset:0;box-shadow:none;border-radius:0}
571
+ .dev.k-app,.dev.k-miniprogram,.dev.k-tablet{background:#0e0e12;box-shadow:inset 0 0 0 1.5px #2b2b33,0 0 0 1px rgba(0,0,0,.45),0 24px 60px rgba(0,0,0,.3)}
572
+ .dev.bare,.dev.fill.k-app,.dev.fill.k-miniprogram,.dev.fill.k-tablet{background:#fff;box-shadow:0 0 0 .5px rgba(0,0,0,.14),0 18px 48px rgba(0,0,0,.2)}
573
+ .dev.fill.k-app,.dev.fill.k-miniprogram,.dev.fill.k-tablet{box-shadow:none}
574
+ .dev.k-desktop{box-shadow:0 0 0 .5px rgba(0,0,0,.3),0 22px 60px rgba(0,0,0,.28)}
575
+ .dev.fill.k-desktop{box-shadow:none}
576
+ .fit.all{position:absolute;inset:0}
577
+ .vp{position:absolute;overflow:hidden;background:#fff;isolation:isolate}
578
+ .dev.fill .vp{inset:0}
579
+ .vp.dk{background:#111}
580
+ .vp iframe{position:absolute;inset:0;width:100%;height:100%;border:0;display:block;background:transparent;transition:opacity .15s}
581
+ .vp iframe.nx{opacity:0;pointer-events:none}
582
+ .chrome{position:absolute;left:0;right:0;top:0;display:flex;align-items:center;gap:7px;padding:0 13px;background:#ebebef;border-bottom:1px solid rgba(0,0,0,.07);border-radius:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;overflow:hidden}
583
+ .chrome i{width:11px;height:11px;border-radius:50%;background:#ff5f57;flex:none}
584
+ .chrome i:nth-child(2){background:#febc2e}
585
+ .chrome i:nth-child(3){background:#28c840}
586
+ .chrome span{flex:1;min-width:0;margin:0 60px 0 18px;height:20px;border-radius:6px;background:rgba(0,0,0,.05);color:#6b6b74;font:12px/20px -apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
587
+ .island{position:absolute;left:50%;width:118px;height:34px;margin-left:-59px;border-radius:20px;background:#000;z-index:4;pointer-events:none}
588
+ .cap{position:absolute;width:87px;height:32px;z-index:4;pointer-events:none;overflow:visible;fill:#000}
589
+ .cap .pl{fill:rgba(255,255,255,.6);stroke:rgba(0,0,0,.08);stroke-width:.5}
590
+ .cap .sp{stroke:rgba(0,0,0,.15);stroke-width:.5}
591
+ .cap .rg{fill:none;stroke:#000;stroke-width:2}
592
+ .cap.w{fill:#fff}
593
+ .cap.w .pl{fill:rgba(0,0,0,.15);stroke:rgba(255,255,255,.25)}
594
+ .cap.w .sp{stroke:rgba(255,255,255,.25)}
595
+ .cap.w .rg{stroke:#fff}
596
+ .win{position:absolute;z-index:4;pointer-events:none;overflow:visible}
597
+ .win .x{fill:none;stroke:#1f1f1f;stroke-width:1}
598
+ .win.w .x{stroke:#fff}
599
+ #toast{position:fixed;left:50%;bottom:calc(24px + env(safe-area-inset-bottom));transform:translateX(-50%);max-width:calc(100% - 32px);padding:9px 14px;border-radius:10px;background:rgba(20,20,24,.92);color:#fff;font-size:13px;z-index:20;box-shadow:0 6px 24px rgba(0,0,0,.25)}
600
+ #menu{display:none}
601
+ body.compact #bar{position:fixed;left:8px;right:8px;top:calc(34px + env(safe-area-inset-top));bottom:auto;height:auto;flex-wrap:wrap;padding:10px;border-radius:14px;border:1px solid var(--line);box-shadow:0 10px 40px rgba(0,0,0,.25);z-index:15;display:none}
602
+ body.compact.open #bar{display:flex}
603
+ body.compact #bar .ttl{flex-basis:100%}
604
+ body.compact #bar .mid{flex:1 1 100%;min-width:0}
605
+ body.compact #shell{display:none}
606
+ body.compact #bar select{flex:1;min-width:0;max-width:none;text-overflow:ellipsis}
607
+ body.compact #bar .arw,body.compact #count{flex:none}
608
+ body.compact #bar .end{flex:none;margin-left:auto}
609
+ body.compact #menu{display:block;position:fixed;left:50%;top:calc(4px + env(safe-area-inset-top));transform:translateX(-50%);width:64px;height:24px;padding:0;border-radius:12px;border:0;background:rgba(20,20,24,.5);color:#fff;font-size:13px;line-height:24px;z-index:16;backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px)}
610
+ @media (max-width:560px){#bar .ttl{display:none}#bar .end{flex:none}}
611
+ `
612
+
613
+ /**
614
+ * 打一份演示包。
615
+ * screens:[{ key, label, top }](top:顶栏是深色,外壳上的胶囊 / 窗口按钮画白的)
616
+ * dark:右侧栏开着「深色」;scheme:右侧栏当时的系统深浅色('dark' / 'light'),没开「深色」时页面按它显示
617
+ * read(rel):设计目录里的文件(Buffer,读不到 null);strictOf(page):这屏是不是别人做的(加硬规矩:只跑我们的脚本)
618
+ * 回 { html, missing: [没读到的屏], count }
619
+ */
620
+ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, os = '', dark = false, scheme = 'light', tweak = null, title = '', lang = 'zh', fit = false }) {
621
+ kind = FRAME[kind] ? kind : 'web'
622
+ const S = STRINGS[lang === 'en' ? 'en' : 'zh']
623
+ const token = 'ddpA' + crypto.randomBytes(5).toString('hex') + '_'
624
+ const storeMark = `/*ddpS${token}*/null`
625
+ const nonce = crypto.randomBytes(16).toString('base64')
626
+ 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 }
627
+ const script = (src, strict) => `<script${strict ? ` nonce="${nonce}"` : ''}>${src.replace(/<\/(script)/gi, '<\\/$1').replace(/<!--/g, '<\\!--')}</script>`
628
+ const shimSrc = `(${storeShim})(${storeMark});`
629
+ const navSrc = (strict) => `(${navScript})(${JSON.stringify({ ...navCfg, strict })});`
630
+ const mode = dark ? 'dark' : scheme === 'dark' ? 'media' : 'light'
631
+ const schemeSrc = `(${schemeScript})(${JSON.stringify(mode)});`
632
+
633
+ const assets = []
634
+ const index = new Map()
635
+ const parts = []
636
+ const list = []
637
+ const missing = []
638
+ let total = 0
639
+ for (const s of screens.slice(0, PACK_SCREENS)) {
640
+ const page = read(s.key)
641
+ if (!page) { missing.push(s.key); continue }
642
+ const strict = !!strictOf(page)
643
+ const text = page.toString('utf8').replace(/^/, '')
644
+ const base = PACK_ORIGIN + '/' + s.key.split('/').map(encodeURIComponent).join('/')
645
+ let out = bundle(strict ? defang(text) : text, {
646
+ key: s.key,
647
+ read,
648
+ base,
649
+ lead: (strict ? strictMeta(nonce) : '') + script(shimSrc + navSrc(strict), strict),
650
+ tail: script(schemeSrc, strict),
651
+ })
652
+ // 大的 data: 地址(图片、字体、脚本)挪出来单独存,几屏共用的只存一份
653
+ out = out.replace(/data:[a-z0-9.+-]+\/[a-z0-9.+-]+(?:;[a-z0-9.+=-]+)*;base64,[A-Za-z0-9+/]+={0,2}/gi, (m) => {
654
+ if (m.length < ASSET_MIN) return m
655
+ let i = index.get(m)
656
+ if (i === undefined) { i = assets.length; assets.push(m); index.set(m, i); total += m.length }
657
+ return token + i + '_'
658
+ })
659
+ total += out.length
660
+ if (total > PACK_MAX) { const e = new Error('tooBig'); e.code = 'tooBig'; throw e }
661
+ parts.push(`<script type="application/json" id="ddp-s-${list.length}">${jsonTag(out)}</script>`)
662
+ list.push({ key: s.key, label: String(s.label || s.key).slice(0, 80), top: !!s.top, ...(strict ? { strict: true } : null) })
663
+ }
664
+ if (!list.length) { const e = new Error('noScreens'); e.code = 'noScreens'; throw e }
665
+
666
+ const f = frameOf(kind, w, h)
667
+ const cfg = {
668
+ kind, w, h, os: os === 'win' ? 'win' : '', dark: !!dark || scheme === 'dark', title: String(title || '').slice(0, 120),
669
+ frame: f, cap: CAP, lights: LIGHTS, winbtn: WINBTN,
670
+ framed: !!FRAMED[kind], fixed: !!FIXED[kind],
671
+ // 网页默认不套浏览器框(铺满窗口),右侧栏开着「按画幅显示」的照它套着;手机、平板、桌面软件默认套着
672
+ shellDefault: !!FRAMED[kind] && (kind !== 'web' || !!fit),
673
+ screens: list, token, storeMark, strings: S,
674
+ }
675
+ const docTitle = cfg.title || list[0].label
676
+ const html = '<!doctype html>\n'
677
+ + `<html lang="${lang === 'en' ? 'en' : 'zh-CN'}"><head><meta charset="utf-8">`
678
+ + '<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">'
679
+ + `<meta name="generator" content="DSH Design Studio"><title>${escHtml(docTitle)}</title><style>${CSS}</style></head><body>`
680
+ + `<header id="bar" hidden><div class="ttl">${escHtml(cfg.title)}</div>`
681
+ + `<div class="mid"><button id="prev" class="arw" type="button" title="${escHtml(S.prev)} (←)" aria-label="${escHtml(S.prev)}">‹</button>`
682
+ + `<select id="sel" aria-label="${escHtml(S.screens)}"></select>`
683
+ + `<button id="next" class="arw" type="button" title="${escHtml(S.next)} (→)" aria-label="${escHtml(S.next)}">›</button><span id="count"></span></div>`
684
+ + `<div class="end"><button id="shell" type="button" aria-pressed="false" title="${escHtml(S.shellTip)}">${escHtml(S.shell)}</button>`
685
+ + `<button id="full" type="button">${escHtml(S.full)}</button></div></header>`
686
+ + `<main id="stage"></main><button id="menu" type="button" aria-label="${escHtml(S.menu)}">•••</button><div id="toast" role="status" hidden></div>`
687
+ + `<script type="application/json" id="ddp-cfg">${jsonTag(cfg)}</script>`
688
+ + parts.join('')
689
+ + assets.map((a, i) => `<script type="application/json" id="ddp-a-${i}">${jsonTag(a)}</script>`).join('')
690
+ + `<script>(${player})()</script>`
691
+ + '</body></html>\n'
692
+ return { html, missing, count: list.length }
693
+ }
package/lib/index.js CHANGED
@@ -48,6 +48,7 @@ import os from 'node:os'
48
48
  import { execFile } from 'node:child_process'
49
49
  import { createHub, webOrigins, trustedOrigins, resolveInRoot, ERR_CATCHER, defang } from './serve.js'
50
50
  import { bundle, inlinePicker, strictMeta, MAX_TOTAL as BUNDLE_MAX } from './bundle.js'
51
+ import { buildPack, PACK_SCREENS } from './htmlpack.js'
51
52
  import { createLibrary } from './works.js'
52
53
  import { createInspiration } from './inspire.js'
53
54
  import { pickStyleText } from './styles.js'
@@ -1584,16 +1585,22 @@ export function apply(ctx) {
1584
1585
  }
1585
1586
 
1586
1587
  /** 存进导出目录:文件名只留字母数字中文和 -,同名不覆盖(加 -2、-3 …) */
1587
- function saveExport(res, session, name, ext, buf) {
1588
+ function writeExport(session, name, ext, buf) {
1588
1589
  const base = String(name || 'design').replace(new RegExp(`\\.${ext}$`, 'i'), '').replace(/[^\w\u4e00-\u9fff-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'design'
1589
1590
  const dir = exportDir(session)
1590
- try {
1591
- fs.mkdirSync(dir, { recursive: true })
1592
- let file = path.join(dir, `${base}.${ext}`)
1593
- for (let i = 2; fs.existsSync(file) && i < 1000; i++) file = path.join(dir, `${base}-${i}.${ext}`)
1594
- fs.writeFileSync(file, buf)
1591
+ fs.mkdirSync(dir, { recursive: true })
1592
+ // 独占创建(wx):查名和写入之间别人刚好建了同名文件,也不会盖掉它,换下一个名字
1593
+ for (let i = 1; i < 1000; i++) {
1594
+ const file = path.join(dir, i === 1 ? `${base}.${ext}` : `${base}-${i}.${ext}`)
1595
+ try { fs.writeFileSync(file, buf, { flag: 'wx' }) } catch (e) { if (e.code === 'EEXIST') continue; throw e }
1595
1596
  exported.add(file)
1596
- json(res, 200, { path: file })
1597
+ return file
1598
+ }
1599
+ throw new Error('too many files with this name')
1600
+ }
1601
+ function saveExport(res, session, name, ext, buf) {
1602
+ try {
1603
+ json(res, 200, { path: writeExport(session, name, ext, buf) })
1597
1604
  } catch (e) {
1598
1605
  json(res, 500, { error: e.message })
1599
1606
  }
@@ -1652,6 +1659,70 @@ export function apply(ctx) {
1652
1659
  saveExport(res, String(body.session || ''), body.name, format, buf)
1653
1660
  }
1654
1661
 
1662
+ /**
1663
+ * 整套 HTML 演示(#26):本地文件的设计,所有屏打进一个 .html(见 htmlpack.js),存进 exports/。
1664
+ * 屏、版本、画幅、深浅色、外壳、调节滑块还没存的值都按右侧栏眼前的来;不截图,几秒出来
1665
+ */
1666
+ async function htmlPackRoute(req, res) {
1667
+ if (!admit(req, res)) return
1668
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1669
+ let body
1670
+ try { body = await readBody(req, 1024 * 1024) } catch (e) { return json(res, 400, { error: e.message }) }
1671
+ const session = String(body.session || '')
1672
+ const st = tracker.stateOf(session)
1673
+ const t = st && st.target
1674
+ if (!t || t.kind !== 'file') return json(res, 400, { error: 'not-file' })
1675
+ if (targetMoved(res, session, body.target)) return
1676
+ const v = Math.max(0, Math.floor(Number(body.v) || 0))
1677
+ const okKey = (k) => typeof k === 'string' && /^[^\\]+\.html?$/i.test(k) && !k.split('/').some((p) => !p || p === '.' || p === '..')
1678
+ const seen = new Set()
1679
+ const screens = []
1680
+ for (const s of Array.isArray(body.screens) ? body.screens.slice(0, PACK_SCREENS) : []) {
1681
+ if (!s || !okKey(s.key) || seen.has(s.key)) continue
1682
+ seen.add(s.key)
1683
+ screens.push({ key: s.key, label: String(s.label || s.key).slice(0, 80), top: s.top === true })
1684
+ }
1685
+ if (!screens.length) return json(res, 400, { error: 'noScreens' })
1686
+ const kind = typeof body.kind === 'string' ? body.kind : 'web'
1687
+ const dim = (x, d) => (Number.isFinite(+x) && +x >= 100 && +x <= 8000 ? Math.round(+x) : d)
1688
+ const w = dim(body.w, 1280), h = dim(body.h, 800)
1689
+ const deps = new Set()
1690
+ const read = (rel) => {
1691
+ deps.add(rel)
1692
+ const f = bundleFile(t.root, v, rel)
1693
+ if (!f) return null
1694
+ const s = fs.statSync(f)
1695
+ return s.isFile() && s.size <= BUNDLE_MAX ? fs.readFileSync(f) : null
1696
+ }
1697
+ const strictOf = (page) => library.strictHtml(page) || market.strictHtml(page) || (v > 0 && library.strictVersions(t.root))
1698
+ const tw = body.tweak && typeof body.tweak === 'object' ? body.tweak : null
1699
+ const plain = (o) => Object.fromEntries(Object.entries(o && typeof o === 'object' ? o : {}).filter(([k, x]) => typeof k === 'string' && k.length < 80 && (typeof x === 'string' || typeof x === 'number' || x === null || typeof x === 'boolean')).slice(0, 200))
1700
+ let pack
1701
+ try {
1702
+ pack = buildPack({
1703
+ screens, read, strictOf, kind, w, h,
1704
+ os: body.os === 'win' ? 'win' : '',
1705
+ dark: body.dark === true,
1706
+ scheme: body.scheme === 'dark' ? 'dark' : 'light',
1707
+ tweak: tw ? { vars: plain(tw.vars), attrs: plain(tw.attrs) } : null,
1708
+ title: String(body.title || '').slice(0, 120),
1709
+ lang: body.lang === 'en' ? 'en' : 'zh',
1710
+ fit: body.fit === true,
1711
+ })
1712
+ } catch (e) {
1713
+ return json(res, e.code ? 400 : 500, { error: e.code || e.message })
1714
+ }
1715
+ // 打包时会话换了设计:别把 A 的演示存进 B 的 exports/
1716
+ if (targetMoved(res, session, body.target)) return
1717
+ const ai = new Set([...deps].filter((x) => isPhotoAsset(x)).map((x) => path.basename(x)))
1718
+ try {
1719
+ const file = writeExport(session, body.name, 'html', Buffer.from(pack.html, 'utf8'))
1720
+ json(res, 200, { path: file, count: pack.count, missing: pack.missing, ai: ai.size, bytes: pack.html.length })
1721
+ } catch (e) {
1722
+ json(res, 500, { error: e.message })
1723
+ }
1724
+ }
1725
+
1655
1726
  /** 图片格式看文件头,不信文件名 */
1656
1727
  function imageExt(buf) {
1657
1728
  if (buf.length < 12) return ''
@@ -1764,7 +1835,7 @@ export function apply(ctx) {
1764
1835
  })
1765
1836
  const mk = createMarketRoutes({ admit, readBody, json, tracker, library, market, open, systemsDir: SYSTEMS_DIR, log, sessionCwd })
1766
1837
 
1767
- const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, 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, edit: editRoute, style: styleRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute, impl: implRoute, implcmp: implCmpRoute, implshot: implShotRoute }
1838
+ const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, 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, edit: editRoute, style: styleRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, htmlpack: htmlPackRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute, impl: implRoute, implcmp: implCmpRoute, implshot: implShotRoute }
1768
1839
  for (const [key, handler] of Object.entries(routes)) {
1769
1840
  ctx.effect(() => ctx.webServer.register({
1770
1841
  kind: 'exact',
package/lib/serve.js CHANGED
@@ -67,7 +67,7 @@ export const MIME = {
67
67
  }
68
68
 
69
69
  // 改动通知里不算的:版本库、依赖、系统垃圾
70
- const EXPORTS = /^(exports([\\/][^\\/]+\.(png|pdf|pptx))?|refs([\\/][^\\/]+\.(png|jpe?g|gif|webp))?)$/i // 导出的图片 / PDF / PPT、参考图(和第一次建的 exports / refs 目录):不算设计改了
70
+ const EXPORTS = /^(exports([\\/][^\\/]+\.(png|pdf|pptx|html))?|refs([\\/][^\\/]+\.(png|jpe?g|gif|webp))?)$/i // 导出的图片 / PDF / PPT / HTML 演示、参考图(和第一次建的 exports / refs 目录):不算设计改了
71
71
  const IGNORED = /(^|[\\/])(\.git|node_modules|\.DS_Store|\.next|\.cache|\.turbo)([\\/]|$)/
72
72
  const ANNOTATIONS = /^annotations\.json(\.[0-9a-z]+\.tmp)?$/i // 业务标注(DSH 写文件时先写 .tmp 再改名):右侧栏靠轮询跟上,页面用不到它,别一改就整屏刷新
73
73
  const HANDOFF = /^handoff([\\/]|$)/i // 转成代码的交接包(说明和截图):不算设计改了,也别在截图时把页面刷掉
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-design-studio",
3
- "version": "0.26.0",
3
+ "version": "0.27.0",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1 test/*.mjs"