dsh-design-studio 0.13.1 → 0.14.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">`.
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.
46
46
  - **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.
47
47
  - **Your brand, and real code:** give a site URL to extract a brand design system and design with it from then on; turn a finished design into React / Vue / HTML (mini programs straight into uni-app or native WeChat code, HBuilderX projects included), compared screen by screen against the design.
48
48
 
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">`。
45
+ - **导出和手机上看**:导出展示图、PDF、PPT(屏和屏之间的跳转照样能点);扫码在手机上按真机尺寸看。页面比默认画幅大的幻灯片、海报,画幅自动跟页面走;也可以在类型后面跟 `宽x高` 指定,比如 `<meta name="dsh-design" content="slides 1440x810">`。导出选项里可以选版面(16:9、4:3、A3 横向、自定义)、每页取景(一屏、整页、指定高度)和每页拼 2 屏;有内容会被裁时,导出前先给一张清单,可以一键按内容改画幅。
46
46
  - **设计库和设计市场**:以前做过的设计、收的参考图和风格都在「设计库」里;市场里逛大家分享的模板、设计系统和风格卡,点「用这个开始」复制一份接着改。自己做的点「分享到设计市场」,查过打成 zip,在网页里交上去,审过就上架。市场目录从 npm 镜像取,签了名、核对过才用;不想让它联网,在插件页打开「设计库不联网」。
47
47
  - **照品牌风格做、转成代码**:给官网地址,提一套品牌设计系统,以后都照它做;做好的设计转成 React / Vue / HTML,小程序直接转成 uni-app 或原生小程序代码(HBuilderX 建的项目也认得出),逐屏和设计稿比对。
48
48
 
package/lib/client.js CHANGED
@@ -183,6 +183,39 @@ window.__ModuleLoader__.load({
183
183
  exShow: '整套展示图',
184
184
  exPdf: 'PDF · 每屏一页',
185
185
  exPptx: 'PPT · 每屏一页(整页图片)',
186
+ exOpts: '导出选项…',
187
+ exportedDocMiss: '已导出 {name}({n} 页,{miss} 屏没截到)',
188
+ xoTitle: '导出选项',
189
+ xoTip: '不动这里,导出的结果和直接导出一样。',
190
+ xoWarn: '有内容会被裁掉,先看一眼',
191
+ xoChecking: '正在量页面…',
192
+ xoClean: '没有会被裁掉的内容。',
193
+ xoOver: '{n} 个页面比画幅大,会被裁',
194
+ xoLong: '{n} 个页面是长页,只会截首屏',
195
+ xoLongPpt: '{n} 个页面是长页,PPT 只会截首屏',
196
+ xoLongH: '{n} 个页面比指定高度长,下面会被裁',
197
+ xoDead: '{n} 个链接点了可能没反应',
198
+ xoFail: '{n} 屏没量到,结果可能不全',
199
+ xoAgain: '重新检查',
200
+ xoGone: '设计换了,这次导出取消了',
201
+ xoResize: '按内容改画幅({size})',
202
+ xoFull: '取景改成整页',
203
+ xoLayout: '版面',
204
+ xoAuto: '跟随画幅',
205
+ xoA3: 'A3 横向',
206
+ xoCustom: '自定义',
207
+ xoCustomPh: '宽x高,比如 1920x1080',
208
+ xoView: '每页取景',
209
+ xoViewAuto: '自动',
210
+ xoViewOne: '一屏',
211
+ xoViewPage: '整页',
212
+ xoViewH: '指定高度',
213
+ xoViewHPh: '高度(像素),比如 1200',
214
+ xoCols: '拼版',
215
+ xoCols1: '每页 1 屏',
216
+ xoCols2: '每页 2 屏',
217
+ xoPdf: '导出 PDF',
218
+ xoPpt: '导出 PPT',
186
219
  exWhere: '存到设计目录的 exports/;图片还会复制到剪贴板',
187
220
  exportedDoc: '已导出 {name}({n} 页)',
188
221
  check: '设计体检',
@@ -952,6 +985,39 @@ window.__ModuleLoader__.load({
952
985
  exShow: 'Showcase of all screens',
953
986
  exPdf: 'PDF · one page per screen',
954
987
  exPptx: 'PowerPoint · one slide per screen (as images)',
988
+ exOpts: 'Export options…',
989
+ exportedDocMiss: 'Exported {name} ({n} pages, {miss} screens could not be captured)',
990
+ xoTitle: 'Export options',
991
+ xoTip: 'Leave these alone and the file comes out the same as a direct export.',
992
+ xoWarn: 'Some content would be cut off. Have a look first',
993
+ xoChecking: 'Measuring pages…',
994
+ xoClean: 'Nothing will be cut off.',
995
+ xoOver: '{n} page(s) are larger than the canvas and will be cut off',
996
+ xoLong: '{n} long page(s): only the first screen is captured',
997
+ xoLongPpt: '{n} long page(s): the PPT only captures the first screen',
998
+ xoLongH: '{n} page(s) are taller than the set height and will be cut off',
999
+ xoDead: '{n} link(s) may do nothing when clicked',
1000
+ xoFail: '{n} screen(s) could not be measured, so this may be incomplete',
1001
+ xoAgain: 'Check again',
1002
+ xoGone: 'The design changed, so this export was cancelled',
1003
+ xoResize: 'Fit canvas to content ({size})',
1004
+ xoFull: 'Switch to full page',
1005
+ xoLayout: 'Page size',
1006
+ xoAuto: 'Match canvas',
1007
+ xoA3: 'A3 landscape',
1008
+ xoCustom: 'Custom',
1009
+ xoCustomPh: 'WxH, e.g. 1920x1080',
1010
+ xoView: 'Each page shows',
1011
+ xoViewAuto: 'Auto',
1012
+ xoViewOne: 'One screen',
1013
+ xoViewPage: 'Full page',
1014
+ xoViewH: 'Set height',
1015
+ xoViewHPh: 'Height in px, e.g. 1200',
1016
+ xoCols: 'Per page',
1017
+ xoCols1: '1 screen',
1018
+ xoCols2: '2 screens',
1019
+ xoPdf: 'Export PDF',
1020
+ xoPpt: 'Export PPT',
955
1021
  exWhere: 'Saved to exports/ in the design folder; images are also copied to the clipboard',
956
1022
  exportedDoc: 'Exported {name} ({n} pages)',
957
1023
  check: 'Design check',
@@ -2325,6 +2391,17 @@ window.__ModuleLoader__.load({
2325
2391
  .ddp-lib .seg button:hover,.ddp-homebar .seg button:hover{color:var(--dsw-alias-label-primary)}
2326
2392
  .ddp-lib .seg button.on,.ddp-homebar .seg button.on{background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);box-shadow:0 1px 2px rgba(0,0,0,.12)}
2327
2393
  .ddp-lib>.bd{flex:1;min-height:0;overflow:auto;padding:14px}
2394
+ .ddp-xo .seg{display:flex;flex-wrap:wrap;gap:4px;margin:0 6px}
2395
+ .ddp-xo .seg button{height:26px;padding:0 9px;border:1px solid var(--dsw-alias-separator-primary,rgba(127,127,127,.3));border-radius:7px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;cursor:pointer}
2396
+ .ddp-xo .seg button:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12));color:var(--dsw-alias-label-primary)}
2397
+ .ddp-xo .seg button.on{border-color:${ACCENT};background:color-mix(in srgb,${ACCENT} 10%,transparent);color:var(--dsw-alias-label-primary)}
2398
+ .ddp-xo .chk{margin:4px 6px 0;padding:8px 10px;border-radius:10px;background:var(--dsw-alias-bg-layer-2);font-size:12px;line-height:1.55;color:var(--dsw-alias-label-secondary)}
2399
+ .ddp-xo .chk.warn{background:color-mix(in srgb,var(--dsw-alias-state-error-primary,#d54941) 9%,transparent);color:var(--dsw-alias-label-primary)}
2400
+ .ddp-xo .chk p{margin:0}
2401
+ .ddp-xo .chk p+p,.ddp-xo .chk .lk{margin-top:4px}
2402
+ .ddp-xo .chk .lk{display:block;text-align:left}
2403
+ .ddp-xo input.who.bad{border-color:var(--dsw-alias-state-error-primary,#d54941)}
2404
+ .ddp-ghost{position:fixed;left:0;top:0;width:100vw;height:100vh;overflow:hidden;opacity:0;pointer-events:none;z-index:-1}
2328
2405
  .ddp-pack .lk{border:0;padding:0;background:transparent;color:${ACCENT};font:inherit;cursor:pointer}
2329
2406
  .ddp-pack .lk:hover{text-decoration:underline;text-underline-offset:2px}
2330
2407
  .ddp-pack input.who{display:block;width:calc(100% - 16px);box-sizing:border-box;height:28px;margin:6px 8px 0;padding:0 9px;border:1px solid var(--dsw-alias-separator-primary,rgba(127,127,127,.3));border-radius:8px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font:12px inherit;outline:none}
@@ -3470,7 +3547,7 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
3470
3547
  const NOT_STYLE_FENG = /通风|台风|新风(系统|机|量)|风险|风控|风景|风扇|风味|风暴|风光|风速|风向|风筝|风铃|风车|吹风|防风|挡风|避风|屏风|旋风|狂风|微风|寒风|疾风|顺风|逆风|作风|中风|风湿|风水/g
3471
3548
  const SAID_STYLE = /风格|配色|色调|主色|色系|[^\s。,,、::;;((]风|\b(style|styled|aesthetic|vibe|palette|colou?r scheme|look and feel)\b/i
3472
3549
  // 「风格你定」「配色:随意」「any style」:等于没说(「配色定为蓝白」是说了)
3473
- const STYLE_FREE = /(风格|配色|色调|主色)[::]?\s?(你定|您定|你来定|您来定|你决定|你看着办|随意|随便|不限|都行|无所谓|自由发挥)|\b(any|whatever)\s(style|colou?rs?|palette)\b|\b(style|colou?rs?|palette)\s(is\s)?up\sto\syou\b/gi
3550
+ const STYLE_FREE = /(风格|配色|色调|主色)\s*(?:[::]\s*)?(你定|您定|你来定|您来定|你决定|你看着办|随意|随便|不限|都行|无所谓|自由发挥)|\b(any|whatever)\s(style|colou?rs?|palette)\b|\b(style|colou?rs?|palette)\s(is\s)?up\sto\syou\b/gi
3474
3551
  function autoStyle(text, kind) {
3475
3552
  const s = String(text || '')
3476
3553
  if (!s.trim()) return null
@@ -4319,7 +4396,7 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
4319
4396
  H = Math.max(H, h)
4320
4397
  }
4321
4398
  if (!W) return ''
4322
- // 一组屏共用一个画幅:别的屏量不出比默认大(正好默认大小的也报不出来),画幅不能比默认小,不然它们被裁
4399
+ // 一组屏共用一个画幅:别的屏量不出比默认大,画幅不能比默认小,不然它们被裁
4323
4400
  return list.length > 1 ? `${Math.max(W, dw)}x${Math.max(H, dh)}` : `${W}x${H}`
4324
4401
  }
4325
4402
 
@@ -5087,6 +5164,14 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
5087
5164
  postTo(curRef.current, { type: 'check', id, kind, quiet: !!quiet })
5088
5165
  setTimeout(() => { if (caps.current.has(id)) { caps.current.delete(id); reject(new Error('timeout')) } }, 15000)
5089
5166
  }),
5167
+ // 导出前预检:页面实际多大、有几个点了没反应的链接
5168
+ measure: () => new Promise((resolve, reject) => {
5169
+ if (!curRef.current) { reject(new Error('not loaded')); return }
5170
+ const id = `${Date.now()}-${++seq}`
5171
+ caps.current.set(id, { resolve, reject })
5172
+ postTo(curRef.current, { type: 'measure', id })
5173
+ setTimeout(() => { if (caps.current.has(id)) { caps.current.delete(id); reject(new Error('timeout')) } }, 8000)
5174
+ }),
5090
5175
  checkFocus: (i) => { if (curRef.current) postTo(curRef.current, { type: 'checkFocus', i }) },
5091
5176
  checkClear: () => { if (curRef.current) postTo(curRef.current, { type: 'checkClear' }) },
5092
5177
  unpin: () => { if (curRef.current) postTo(curRef.current, { type: 'unpin' }) }, // 去掉「已选」虚线框
@@ -5297,6 +5382,7 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
5297
5382
  if (isCur && p.onEditDone) p.onEditDone()
5298
5383
  break
5299
5384
  case 'checked':
5385
+ case 'measured':
5300
5386
  case 'captured': {
5301
5387
  const c = caps.current.get(d.id)
5302
5388
  if (c) {
@@ -6442,7 +6528,7 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
6442
6528
  items.push(['raw', I.image, t('exRaw', n)])
6443
6529
  if (kind !== 'poster' && kind !== 'slides') items.push(['long', I.long, t('exLong', n)]) // 海报、幻灯片画幅是定的,没有「整页」
6444
6530
  if (count > 1) items.push(['show', I.canvas, t('exShow')])
6445
- items.push(['pdf', I.pdf, t('exPdf')], ['pptx', I.deck, t('exPptx')])
6531
+ items.push(['pdf', I.pdf, t('exPdf')], ['pptx', I.deck, t('exPptx')], ['opts', I.sliders, t('exOpts')])
6446
6532
  return items
6447
6533
  }
6448
6534
 
@@ -7118,6 +7204,101 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
7118
7204
  }
7119
7205
 
7120
7206
  /** 打成 zip:选授权 → 检查 → 过了存到「下载」,没过列出来交给模型改 */
7207
+ /**
7208
+ * 导出前预检:list 是各屏量到的大小,limit 是每页取到多高(0 = 一屏,Infinity = 整页)。
7209
+ * over 比画幅大(横向永远会被裁;幻灯片、海报竖向也算);long 长页只截到一部分;dead 点了没反应的链接
7210
+ */
7211
+ function precheckOf(list, kind, limit) {
7212
+ const fixed = kind === 'slides' || kind === 'poster'
7213
+ const r = { over: 0, long: 0, dead: 0, fail: 0 }
7214
+ for (const m of list) {
7215
+ if (m.failed) { r.fail++; continue }
7216
+ const tall = m.pageH > (limit || m.h) + 2
7217
+ if (m.pageW > m.w + 2 || (fixed && tall)) r.over++
7218
+ if (!fixed && tall) r.long++
7219
+ const from = limit ? 0 : m.sy || 0 // 一屏:只看现在看得到的那段
7220
+ const to = limit || from + m.h
7221
+ r.dead += (Array.isArray(m.dead) ? m.dead : []).filter((y) => y >= from && y < to).length
7222
+ }
7223
+ return r
7224
+ }
7225
+
7226
+ /** 「按内容改画幅」改成多大:'宽x高',不用改或改不了返回 ''。幻灯片、海报按量到的版面,别的只把宽度加上去;竖着堆了好几页的不改高 */
7227
+ function fitCanvas(list, kind, size) {
7228
+ const fixed = kind === 'slides' || kind === 'poster'
7229
+ let [W, H] = size
7230
+ for (const m of list) {
7231
+ if (m.failed) continue
7232
+ if (fixed && Array.isArray(m.natural)) { W = Math.max(W, m.natural[0]); H = Math.max(H, m.natural[1]) } else if (m.pageW > m.w + 2) W = Math.max(W, m.pageW)
7233
+ }
7234
+ return (W === size[0] && H === size[1]) || W > 8000 || H > 8000 ? '' : `${W}x${H}`
7235
+ }
7236
+
7237
+ const layoutOk = (s) => { const m = /^\s*(\d{3,4})\s*[x×*]\s*(\d{3,4})\s*$/.exec(String(s || '')); return !!m && +m[1] >= 200 && +m[2] >= 200 && +m[1] <= 8000 && +m[2] <= 8000 }
7238
+ const fitHOk = (s) => /^\d{3,5}$/.test(String(s).trim()) && +s >= 200 && +s <= 30000
7239
+
7240
+ /** 按高度裁一张截图:h 是图对应的 CSS 高度 */
7241
+ function cropImg(img, h, maxH) {
7242
+ const c = document.createElement('canvas')
7243
+ c.width = img.width
7244
+ c.height = Math.round(img.height * maxH / h)
7245
+ c.getContext('2d').drawImage(img, 0, 0)
7246
+ return c
7247
+ }
7248
+
7249
+ function ExportPanel({ t, kind, size, opts, setOpts, screens, rev, measure, onResize, onExport, onClose }) {
7250
+ const [list, setList] = useState(null)
7251
+ const [working, setWorking] = useState(false)
7252
+ const [again, setAgain] = useState(0)
7253
+ const firstRun = useRef(true)
7254
+ useEffect(() => {
7255
+ let off = false
7256
+ setList(null)
7257
+ const first = firstRun.current
7258
+ firstRun.current = false
7259
+ // 页面刚改过:等它重新载入再量
7260
+ const timer = setTimeout(() => {
7261
+ measure().then((l) => { if (!off) setList(l) }, () => { if (!off) setList([{ failed: true }]) })
7262
+ }, first ? 0 : 900)
7263
+ return () => { off = true; clearTimeout(timer) }
7264
+ }, [size.join('x'), screens, rev, again])
7265
+ const limit = opts.fit === 'page' ? Infinity : opts.fit === 'height' && fitHOk(opts.fitH) ? +opts.fitH : 0
7266
+ const rep = list ? precheckOf(list, kind, limit) : null
7267
+ const canFit = list ? fitCanvas(list, kind, size) : ''
7268
+ const cut = rep && (rep.over || rep.long)
7269
+ const longKey = opts.fit === 'height' ? 'xoLongH' : !opts.fit && (kind === 'web' || kind === 'email') ? 'xoLongPpt' : 'xoLong'
7270
+ const seg = (k, items) => h('div', { className: 'seg', role: 'radiogroup' }, ...items.map(([v, label]) => h('button', { key: String(v), type: 'button', role: 'radio', 'aria-checked': opts[k] === v, className: opts[k] === v ? 'on' : '', onClick: () => setOpts({ ...opts, [k]: v }) }, label)))
7271
+ const bad = (opts.layout === 'custom' && !layoutOk(opts.custom)) || (opts.fit === 'height' && !fitHOk(opts.fitH))
7272
+ const go = async (format) => {
7273
+ setWorking(true)
7274
+ try { await onExport(format) } finally { setWorking(false) }
7275
+ }
7276
+ return h('div', { className: 'ddp-tokens ddp-pack ddp-xo', onPointerDown: (e) => e.stopPropagation() },
7277
+ h('header', null, h(I.sliders), h('b', null, t('xoTitle')), h('button', { className: 'ddp-btn', title: '×', onClick: onClose }, h(I.close))),
7278
+ h('p', { className: 'tip' }, t('xoTip')),
7279
+ h('div', { className: 'bd' },
7280
+ !rep ? h('div', { className: 'chk' }, h('p', null, t('xoChecking'))) : h('div', { className: 'chk' + (cut ? ' warn' : '') },
7281
+ rep.over ? h('p', null, t('xoOver', { n: rep.over })) : null,
7282
+ rep.long ? h('p', null, t(longKey, { n: rep.long })) : null,
7283
+ rep.dead ? h('p', null, t('xoDead', { n: rep.dead })) : null,
7284
+ rep.fail ? h('p', null, t('xoFail', { n: rep.fail })) : null,
7285
+ !cut && !rep.dead && !rep.fail ? h('p', null, t('xoClean')) : null,
7286
+ rep.over && canFit ? h('button', { className: 'lk', onClick: () => onResize(canFit) }, t('xoResize', { size: canFit.replace('x', '×') })) : null,
7287
+ rep.long && opts.fit !== 'page' ? h('button', { className: 'lk', onClick: () => setOpts({ ...opts, fit: 'page' }) }, t('xoFull')) : null,
7288
+ h('button', { className: 'lk', onClick: () => setAgain((n) => n + 1) }, t('xoAgain'))),
7289
+ h('h4', null, t('xoLayout')),
7290
+ seg('layout', [['auto', t('xoAuto')], ['16:9', '16:9'], ['4:3', '4:3'], ['a3', t('xoA3')], ['custom', t('xoCustom')]]),
7291
+ opts.layout === 'custom' ? h('input', { className: 'who' + (opts.custom && !layoutOk(opts.custom) ? ' bad' : ''), value: opts.custom, maxLength: 11, placeholder: t('xoCustomPh'), 'aria-label': t('xoCustom'), onChange: (e) => setOpts({ ...opts, custom: e.target.value }) }) : null,
7292
+ h('h4', null, t('xoView')),
7293
+ seg('fit', [['', t('xoViewAuto')], ['view', t('xoViewOne')], ['page', t('xoViewPage')], ['height', t('xoViewH')]]),
7294
+ opts.fit === 'height' ? h('input', { className: 'who' + (opts.fitH && !fitHOk(opts.fitH) ? ' bad' : ''), value: opts.fitH, maxLength: 5, inputMode: 'numeric', placeholder: t('xoViewHPh'), 'aria-label': t('xoViewH'), onChange: (e) => setOpts({ ...opts, fitH: e.target.value }) }) : null,
7295
+ h('h4', null, t('xoCols')),
7296
+ seg('cols', [[1, t('xoCols1')], [2, t('xoCols2')]])),
7297
+ h('footer', { className: 'row' },
7298
+ h('button', { disabled: working || bad, onClick: () => go('pptx') }, h('span', null, t('xoPpt'))),
7299
+ h('button', { className: 'go', disabled: working || bad, onClick: () => go('pdf') }, h('span', null, t('xoPdf')))))
7300
+ }
7301
+
7121
7302
  function PackPanel({ t, sid, root, onFix, onSay, onClose }) {
7122
7303
  const [lic, setLic] = useState('CC0-1.0')
7123
7304
  // CC BY 要署名:填过一次记住(只存在这台电脑的浏览器里)
@@ -7545,6 +7726,14 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
7545
7726
  const markRun = useRef(0) // 每开 / 关一次标注加一:发送途中关掉(或关了又开)的,旧的那次作废
7546
7727
  const [tw, setTw] = useState({}) // 拖过的滑块:id → 值(还没写进文件)
7547
7728
  const apis = useRef(new Map()) // 屏 → 截图用的接口
7729
+ const ghostApis = useRef(new Map()) // 单看时导出:在背后临时挂上的各屏
7730
+ const ghostN = useRef(0)
7731
+ const [backFrames, setBackFrames] = useState(null) // { list, size }:开始时的那些屏,途中换设计也不跟着变
7732
+ const designNow = useRef('') // 现在开着哪套设计
7733
+ const designSeq = useRef(0) // 换一次设计加一:导出途中换过(换回来也算)就不存了
7734
+ const [loadTick, setLoadTick] = useState(0) // 导出面板开着时页面又载入了一次:重新量
7735
+ const warned = useRef('') // 预检提醒过的结果:同样的结果只拦一次
7736
+ const [xo, setXo] = useState({ layout: 'auto', custom: '', fit: '', fitH: '', cols: 1 }) // 导出选项
7548
7737
  const cmpRef = useRef(null)
7549
7738
  const [box, setBox] = useState({ w: 0, h: 0 })
7550
7739
  const stageRef = useRef(null)
@@ -7793,10 +7982,11 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
7793
7982
  }
7794
7983
 
7795
7984
  const remember = (key, m, title, toks, dk, links, nat) => {
7985
+ if (pane === 'export') setLoadTick((n) => n + 1)
7796
7986
  const k = site + '|' + key
7797
7987
  const sig = JSON.stringify([toks || [], links || []])
7798
7988
  setInfo((cur) => {
7799
- const natural = nat || (cur[k] && cur[k].natural) || null // 画幅放大后页面不再比框大、报空:还按上回量的
7989
+ const natural = nat === 0 ? null : nat || (cur[k] && cur[k].natural) || null // 画幅放大后页面正好撑满、报空:还按上回量的;0 是这页不再是一整块:清掉
7800
7990
  return cur[k] && cur[k].meta === m && cur[k].title === title && cur[k].sig === sig && cur[k].dark === dk && String(cur[k].natural) === String(natural) ? cur
7801
7991
  : { ...cur, [k]: { meta: m, title, tokens: toks || [], links: links || [], sig, dark: dk, natural } }
7802
7992
  })
@@ -8108,49 +8298,95 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
8108
8298
  // ── 导出图片 ──
8109
8299
  // 截一屏:图片和它的 CSS 尺寸(PDF / PPT 按这个定页面大小)
8110
8300
  // 那一屏的接口(截图、体检);刚载入的等它就绪
8111
- const apiOf = async (sc) => {
8112
- let api = apis.current.get(ik(sc))
8113
- for (let i = 0; i < 40 && !(api && api.ready()); i++) {
8301
+ const apiOf = async (sc, map = apis.current) => {
8302
+ const tries = map === apis.current ? 40 : 120 // 背后现挂的要等它载完
8303
+ let api = map.get(ik(sc))
8304
+ for (let i = 0; i < tries && !(api && api.ready()); i++) {
8114
8305
  await new Promise((r) => setTimeout(r, 150))
8115
- api = apis.current.get(ik(sc))
8306
+ api = map.get(ik(sc))
8116
8307
  }
8117
8308
  if (!api) throw new Error('not loaded')
8118
8309
  return api
8119
8310
  }
8120
- const captureOf = async (sc, full) => {
8121
- const api = await apiOf(sc)
8122
- const r = await api.capture({ full: !!full, scale: 2 })
8311
+ const captureOf = async (sc, full, map, maxH) => {
8312
+ const api = await apiOf(sc, map)
8313
+ const r = await api.capture({ full: !!full, scale: 2, ...(maxH ? { maxH } : {}) })
8123
8314
  return { img: await loadImg(r.png), w: r.w, h: r.h, links: Array.isArray(r.links) ? r.links : [], top: typeof r.top === 'boolean' ? r.top : null }
8124
8315
  }
8125
8316
 
8317
+ const targetKey = st && st.target ? (st.target.kind === 'file' ? `file|${st.target.root}` : `proxy|${st.target.port}`) : ''
8126
8318
  const saveImage = async (name, blob) => {
8127
8319
  const png = await blobB64(blob)
8128
- const r = await post('export', { session: sid, name, png })
8320
+ const r = await post('export', { session: sid, name, png, target: targetKey })
8129
8321
  const copied = await copyImage(blob)
8130
8322
  const file = String(r.path || '').split(/[\\/]/).pop()
8131
8323
  say(t(copied ? 'exportedCopied' : 'exported', { name: file }), { label: t('reveal'), run: () => post('reveal', { path: r.path }).catch(() => {}) })
8132
8324
  }
8133
8325
 
8134
- const doExport = async (mode, key) => {
8326
+ const designId = JSON.stringify([sid, targetKey, ver ? ver.n : 0])
8327
+ if (designNow.current !== designId) { designNow.current = designId; designSeq.current++ }
8328
+ // 单看时只挂着正在看的那屏;要所有屏(PDF、PPT、拼图、预检)时按画幅大小在背后挂上,用完就撤
8329
+ const withFrames = async (fn) => {
8330
+ if (canvas || shown.length < 2) return fn(apis.current)
8331
+ // 网页单看时铺满右侧栏,和画幅不一样宽,都在背后重挂;别的类型正在看的那屏直接用(滚动位置、打开的弹窗都还在)
8332
+ const list = kind === 'web' ? shown : shown.filter((sc) => !apis.current.has(ik(sc)))
8333
+ const back = new Set(list.map(ik))
8334
+ ghostN.current++
8335
+ setBackFrames({ list, size })
8336
+ try { return await fn({ get: (k) => (back.has(k) ? ghostApis.current : apis.current).get(k) }) } finally { if (!--ghostN.current) setBackFrames(null) }
8337
+ }
8338
+ const measureAll = async (map) => {
8339
+ const list = []
8340
+ for (const sc of shown) {
8341
+ try { const api = await apiOf(sc, map); list.push(await api.measure()) } catch (e) { console.warn('[dsh-design-studio] 量页面失败', sc.key, e); list.push({ failed: true }) }
8342
+ }
8343
+ return list
8344
+ }
8345
+
8346
+ const doExport = async (mode, key, opts) => {
8135
8347
  setExMenu(false)
8348
+ if (mode === 'opts') { if (pane !== 'export') openPane('export'); return }
8136
8349
  if (mode === 'zip') return openPack(fileTarget ? st.target.root : '')
8137
8350
  if (mode === 'share') return openShare(fileTarget ? st.target.root : '')
8138
8351
  say(t('exporting'))
8352
+ const design = designNow.current
8353
+ const stamp = designSeq.current
8354
+ const gone = () => designSeq.current !== stamp
8139
8355
  try {
8140
8356
  const prefix = ver ? `v${ver.n}-` : ''
8141
8357
  const suffix = dark ? '-dark' : ''
8142
8358
  if (mode === 'pdf' || mode === 'pptx') {
8143
- // 每屏一页。PDF 里网页、邮件放整页长图(页面多高就多高);PPT 一张幻灯片一个画面
8144
- const long = mode === 'pdf' && (kind === 'web' || kind === 'email')
8359
+ // 每屏一页。PDF 里网页、邮件放整页长图(页面多高就多高);PPT 一张幻灯片一个画面。选项面板里可以改
8360
+ const fit = (opts && opts.fit) || ''
8361
+ const long = fit === 'page' || fit === 'height' || (!fit && mode === 'pdf' && (kind === 'web' || kind === 'email'))
8362
+ const maxH = fit === 'height' ? Number(opts.fitH) || 0 : 0
8363
+ let deadN = 0
8364
+ await withFrames(async (map) => {
8365
+ // 从菜单直接点:先量一遍,有内容会被裁就先给看清单(同样的结果只拦一次)
8366
+ if (!opts) {
8367
+ const seen = await measureAll(map)
8368
+ const rep = precheckOf(seen, kind, long ? Infinity : 0)
8369
+ deadN = rep.dead
8370
+ const sig = rep.over || rep.long ? [design, shown.map(ik).join(','), size.join('x'), long ? 1 : 0, seen.map((m) => (m.failed ? '-' : `${m.pageW}x${m.pageH}`)).join(',')].join('|') : ''
8371
+ if (sig && warned.current !== sig) {
8372
+ warned.current = sig
8373
+ say(t('xoWarn'))
8374
+ if (pane !== 'export') openPane('export')
8375
+ return
8376
+ }
8377
+ }
8145
8378
  const pages = []
8146
8379
  const keys = []
8147
8380
  for (const sc of shown) {
8381
+ if (gone()) break
8148
8382
  try {
8149
- const r = await captureOf(sc, long)
8150
- pages.push({ jpg: await jpegB64(r.img), w: r.w, h: r.h, title: labelOf(sc), links: r.links })
8383
+ const r = await captureOf(sc, long, map, maxH)
8384
+ const cut = maxH && r.h > maxH
8385
+ pages.push({ jpg: await jpegB64(cut ? cropImg(r.img, r.h, maxH) : r.img), w: r.w, h: cut ? maxH : r.h, title: labelOf(sc), links: r.links })
8151
8386
  keys.push(sc.key)
8152
8387
  } catch (e) { console.warn('[dsh-design-studio] 截图失败', sc.key, e) }
8153
8388
  }
8389
+ if (gone()) { say(t('xoGone')); return }
8154
8390
  if (!pages.length) throw new Error('no screens')
8155
8391
  // 原型里的跳转:路径换成第几页,PDF / PPT 里点了能跳过去
8156
8392
  for (const p of pages) {
@@ -8159,16 +8395,25 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
8159
8395
  const sp = splitTitles(pages.map((x) => x.title))
8160
8396
  const folder = st && st.target && st.target.kind === 'file' ? String(st.target.file).split(/[\\/]/).slice(-2, -1)[0] : ''
8161
8397
  const title = sp.brand || folder || st.label || ''
8162
- const r = await post('doc', { session: sid, format: mode, name: prefix + (title || 'design') + suffix, title, bg: hexOf(pickColors(tokens).bg), pages })
8398
+ const layout = opts ? (opts.layout === 'custom' ? opts.custom.trim() : opts.layout === 'auto' ? '' : opts.layout) : ''
8399
+ const cols = opts && opts.cols === 2 ? 2 : 1
8400
+ const r = await post('doc', { session: sid, format: mode, name: prefix + (title || 'design') + suffix, title, bg: hexOf(pickColors(tokens).bg), pages, layout, cols, target: targetKey })
8163
8401
  const file = String(r.path || '').split(/[\\/]/).pop()
8164
- say(t('exportedDoc', { name: file, n: pages.length }), { label: t('reveal'), run: () => post('reveal', { path: r.path }).catch(() => {}) })
8402
+ const miss = shown.length - pages.length
8403
+ const sheets = Math.ceil(pages.length / cols)
8404
+ say((miss ? t('exportedDocMiss', { name: file, n: sheets, miss }) : t('exportedDoc', { name: file, n: sheets })) + (deadN ? ' · ' + t('xoDead', { n: deadN }) : ''), { label: t('reveal'), run: () => post('reveal', { path: r.path }).catch(() => {}) })
8405
+ })
8165
8406
  return
8166
8407
  }
8167
8408
  if (mode === 'show') {
8168
8409
  const shots = []
8169
- for (const sc of shown) {
8170
- try { const c = await captureOf(sc, false); shots.push({ img: c.img, top: c.top, title: labelOf(sc) }) } catch (e) { console.warn('[dsh-design-studio] 截图失败', sc.key, e) }
8171
- }
8410
+ await withFrames(async (map) => {
8411
+ for (const sc of shown) {
8412
+ if (gone()) break
8413
+ try { const c = await captureOf(sc, false, map); shots.push({ img: c.img, top: c.top, title: labelOf(sc) }) } catch (e) { console.warn('[dsh-design-studio] 截图失败', sc.key, e) }
8414
+ }
8415
+ })
8416
+ if (gone()) { say(t('xoGone')); return }
8172
8417
  if (!shots.length) throw new Error('no screens')
8173
8418
  const sp = splitTitles(shots.map((x) => x.title))
8174
8419
  const colors = pickColors(tokens)
@@ -8200,7 +8445,7 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
8200
8445
  await saveImage(base + (mode === 'long' ? '-full' : ''), await canvasBlob(c))
8201
8446
  }
8202
8447
  } catch (e) {
8203
- say(t('exportFail', { msg: e.message }))
8448
+ say(e.message === 'designChanged' ? t('xoGone') : t('exportFail', { msg: e.message }))
8204
8449
  }
8205
8450
  }
8206
8451
 
@@ -8806,7 +9051,10 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
8806
9051
  }),
8807
9052
  toast ? h('div', { className: 'ddp-toast low' }, h('span', null, toast.text)) : null) : null
8808
9053
  // 开着设计时点「首页」:首页叠在画布上(设计库再叠在它上面)
8809
- const root = (...kids) => h('div', rootProps, ...kids, url && homeAt ? homeView(true) : null, libLayer, dropLayer, fileInput, pageFileInput)
9054
+ // 单看时导出:所有屏按画幅大小挂在背后(看不见、点不到,放在视口里是因为视口外的 iframe 浏览器会停掉它的绘制)
9055
+ const ghostLayer = backFrames ? h('div', { className: 'ddp-ghost', 'aria-hidden': true }, ...backFrames.list.map((sc) => h('div', { key: ik(sc), className: 'ddp-vp', style: { left: 0, top: 0, width: backFrames.size[0], height: backFrames.size[1] } },
9056
+ h(Screen, { t, remote, src: sc.url, label: labelOf(sc), dark, apis: ghostApis.current, apiKey: ik(sc), quietPick: true, zoom: 1, reloadSeq, tweak: sc.v ? null : tweak, styleSel: sty && sty.key === sc.key ? sty.selector : '', styleCss: sty && sty.key === sc.key ? sty.live : null })))) : null
9057
+ const root = (...kids) => h('div', rootProps, ...kids, url && homeAt ? homeView(true) : null, libLayer, dropLayer, fileInput, pageFileInput, ghostLayer)
8810
9058
 
8811
9059
  // ── 设计库:打成 zip、拖进来的设计包、存成我的风格 ──
8812
9060
  function openPack(dir) {
@@ -8925,6 +9173,9 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
8925
9173
  if (pane === 'zip' && zipIssues) {
8926
9174
  return h(ZipIssues, { t, issues: zipIssues, onClose: () => { setPane(''); setZipIssues(null) } })
8927
9175
  }
9176
+ if (pane === 'export') {
9177
+ return h(ExportPanel, { t, kind, size, opts: xo, setOpts: setXo, screens: shown.map(ik).join('|'), rev: `${st ? st.rev : 0}|${reloadSeq}|${loadTick}`, measure: () => withFrames(measureAll), onResize: (s) => change({ size: s }), onExport: (format) => doExport(format, undefined, xo), onClose: () => setPane('') })
9178
+ }
8928
9179
  if (pane === 'handoff') {
8929
9180
  return h(HandoffPanel, { t, sid, root: fileTarget ? st.target.root : '', fileTarget, count: screens.length, cur: (curScreen && curScreen.key) || focus, onGo: doHandoff, onSay: say, onClose: () => setPane('') })
8930
9181
  }
@@ -9397,7 +9648,7 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
9397
9648
  // 注意:这里是客户端**服务名**(短的),不是包名
9398
9649
  exports.inject = INJECT
9399
9650
  // 测试用
9400
- exports._test = { autoSize, pulseStep, MarketDetail, dragKind, droppedOf, pickInfo, pickLabel, pickRanges, pickRule, chipOf, chipRanges, makeT, ZH, EN, formatCheck, formatTweaks, markHit, markPath, STYLES, formatStyle, accentUse, autoStyle, styleLook, padInsert, pageOf, pxOf, styleChanges, formatStyleAsk, takesOf, formatCheckTool, poller, frameOf, paletteOf, formatRef, layoutRow, keyOfPath, flowsOf, flowLines, flowMarks, formatPick, whereOf, parseMeta, sizeOf, layoutGrid, fitCam, tokenKind, formatToken, splitTitles, pickColors, hhmm, formatTpl, formatPrep, styleFromTokens, myStyleOf, isZipFile }
9651
+ exports._test = { precheckOf, fitCanvas, layoutOk, fitHOk, autoSize, pulseStep, MarketDetail, dragKind, droppedOf, pickInfo, pickLabel, pickRanges, pickRule, chipOf, chipRanges, makeT, ZH, EN, formatCheck, formatTweaks, markHit, markPath, STYLES, formatStyle, accentUse, autoStyle, styleLook, padInsert, pageOf, pxOf, styleChanges, formatStyleAsk, takesOf, formatCheckTool, poller, frameOf, paletteOf, formatRef, layoutRow, keyOfPath, flowsOf, flowLines, flowMarks, formatPick, whereOf, parseMeta, sizeOf, layoutGrid, fitCam, tokenKind, formatToken, splitTitles, pickColors, hhmm, formatTpl, formatPrep, styleFromTokens, myStyleOf, isZipFile }
9401
9652
  return module.exports
9402
9653
  },
9403
9654
  })
package/lib/doc.js CHANGED
@@ -47,6 +47,45 @@ export function pageLinks(p, count, self) {
47
47
  return out
48
48
  }
49
49
 
50
+ // ── 版面和拼版 ───────────────────────────────────────────────────────────
51
+
52
+ /** 版面:空或 'auto' = 跟随画幅(返回 null);'16:9'、'4:3'、'a3'(A3 横向)、'宽x高'(CSS 像素)。别的写法当没写 */
53
+ export function layoutSize(layout) {
54
+ const s = String(layout || '').trim().toLowerCase()
55
+ if (s === '16:9') return [1280, 720]
56
+ if (s === '4:3') return [1280, 960]
57
+ if (s === 'a3') return [1587, 1123]
58
+ const m = /^(\d{3,4})\s*[x×*]\s*(\d{3,4})$/.exec(s)
59
+ if (!m) return null
60
+ const [w, h] = [+m[1], +m[2]]
61
+ return w >= 200 && h >= 200 && w <= 8000 && h <= 8000 ? [w, h] : null
62
+ }
63
+
64
+ /**
65
+ * 每页纸上放哪几屏:[{ W, H, items: [{ i, x, y, w, h, k }] }],i 是第几屏,x / y 是放在纸上的位置,k 是缩放(都是 CSS 像素)。
66
+ * 什么都不选:每屏一张纸、大小就是这一屏。选了版面:放大或缩小到整屏装得下,居中留边。每页 2 屏:左右各一格,单出来的一屏放左边。
67
+ */
68
+ export function sheetsOf(pages, { layout = '', cols = 1, gap = 24 } = {}) {
69
+ const box = layoutSize(layout)
70
+ const per = cols === 2 ? 2 : 1
71
+ const m = per === 2 ? gap : 0 // 一页一屏不留边
72
+ const maxW = Math.max(...pages.map((p) => p.w))
73
+ const maxH = Math.max(...pages.map((p) => p.h))
74
+ const sheets = []
75
+ for (let i = 0; i < pages.length; i += per) {
76
+ const W = box ? box[0] : per === 2 ? maxW * 2 + gap * 3 : pages[i].w
77
+ const H = box ? box[1] : per === 2 ? maxH + gap * 2 : pages[i].h
78
+ const cw = (W - m * (per + 1)) / per
79
+ const ch = H - m * 2
80
+ const items = pages.slice(i, i + per).map((p, j) => {
81
+ const k = box ? Math.min(cw / p.w, ch / p.h) : 1
82
+ return { i: i + j, x: m + j * (cw + m) + (cw - p.w * k) / 2, y: m + (ch - p.h * k) / 2, w: p.w, h: p.h, k }
83
+ })
84
+ sheets.push({ W, H, items })
85
+ }
86
+ return sheets
87
+ }
88
+
50
89
  // ── PDF ──────────────────────────────────────────────────────────────────
51
90
 
52
91
  /** PDF 文本串:纯 ASCII 用 ( ),带中文用 UTF-16BE 十六进制 */
@@ -61,36 +100,52 @@ function pdfText(s) {
61
100
  /**
62
101
  * pages: [{ jpg: Buffer, w, h, title?, links? }],w / h 是这一页的 CSS 像素(1px 按 0.75pt 算,和浏览器打印一样大)
63
102
  * 每页一张图铺满;有名字的页进书签,links 是点了跳到别的页的地方(见 pageLinks)。
103
+ * layout / cols 见 sheetsOf;选了它们时纸上空出来的地方铺 bg('RRGGBB')。不选就和原来一样
64
104
  */
65
- export function makePdf(pages, { title = '' } = {}) {
105
+ export function makePdf(pages, { title = '', layout = '', cols = 1, bg = '' } = {}) {
106
+ const sheets = sheetsOf(pages, { layout, cols })
107
+ const per = cols === 2 ? 2 : 1
108
+ const paper = (per === 2 || layoutSize(layout)) && /^[0-9a-f]{6}$/i.test(bg) ? [0, 2, 4].map((i) => (parseInt(bg.slice(i, i + 2), 16) / 255).toFixed(3)).join(' ') : ''
66
109
  const objs = [] // 下标 + 1 = 对象号
67
110
  const add = (parts) => { objs.push(parts); return objs.length }
68
111
  const catalog = add(null)
69
112
  const tree = add(null)
70
- const kids = pages.map(() => add(null)) // 页先占号:页上的链接要指到后面的页
71
- pages.forEach((p, i) => {
72
- const info = jpegInfo(p.jpg)
73
- if (!info) throw new Error('不是 JPEG')
74
- const cs = info.comps === 1 ? '/DeviceGray' : info.comps === 4 ? '/DeviceCMYK' : '/DeviceRGB'
75
- const W = +(p.w * 0.75).toFixed(2)
76
- const H = +(p.h * 0.75).toFixed(2)
77
- const img = add([`<< /Type /XObject /Subtype /Image /Width ${info.width} /Height ${info.height} /ColorSpace ${cs} /BitsPerComponent 8 /Filter /DCTDecode${info.comps === 4 ? ' /Decode [1 0 1 0 1 0 1 0]' : ''} /Length ${p.jpg.length} >>\nstream\n`, p.jpg, '\nendstream'])
78
- const draw = `q ${W} 0 0 ${H} 0 0 cm /Im0 Do Q`
113
+ const kids = sheets.map(() => add(null)) // 页先占号:页上的链接要指到后面的页
114
+ const pt = (v) => +(v * 0.75).toFixed(2)
115
+ sheets.forEach((s, si) => {
116
+ const W = pt(s.W)
117
+ const H = pt(s.H)
118
+ const placed = s.items.map((it, j) => {
119
+ const p = pages[it.i]
120
+ const info = jpegInfo(p.jpg)
121
+ if (!info) throw new Error('不是 JPEG')
122
+ const cs = info.comps === 1 ? '/DeviceGray' : info.comps === 4 ? '/DeviceCMYK' : '/DeviceRGB'
123
+ const img = add([`<< /Type /XObject /Subtype /Image /Width ${info.width} /Height ${info.height} /ColorSpace ${cs} /BitsPerComponent 8 /Filter /DCTDecode${info.comps === 4 ? ' /Decode [1 0 1 0 1 0 1 0]' : ''} /Length ${p.jpg.length} >>\nstream\n`, p.jpg, '\nendstream'])
124
+ return { img, draw: `q ${pt(it.w * it.k)} 0 0 ${pt(it.h * it.k)} ${pt(it.x)} ${pt(s.H - it.y - it.h * it.k)} cm /Im${j} Do Q` }
125
+ })
126
+ const draw = (paper ? `${paper} rg 0 0 ${W} ${H} re f ` : '') + placed.map((x) => x.draw).join(' ')
79
127
  const content = add([`<< /Length ${draw.length} >>\nstream\n${draw}\nendstream`])
80
- const pt = (v) => +(v * 0.75).toFixed(2)
81
- const annots = pageLinks(p, pages.length, i).map((l) =>
82
- add([`<< /Type /Annot /Subtype /Link /Rect [${pt(l.x)} ${pt(p.h - l.y - l.h)} ${pt(l.x + l.w)} ${pt(p.h - l.y)}] /Border [0 0 0] /Dest [${kids[l.to]} 0 R /Fit] >>`]))
83
- objs[kids[i] - 1] = [`<< /Type /Page /Parent ${tree} 0 R /MediaBox [0 0 ${W} ${H}] /Resources << /XObject << /Im0 ${img} 0 R >> >> /Contents ${content} 0 R` +
128
+ const annots = s.items.flatMap((it) => pageLinks(pages[it.i], pages.length, it.i)
129
+ .map((l) => ({ ...l, to: Math.floor(l.to / per) }))
130
+ .filter((l) => l.to !== si) // 拼到同一页上的两屏之间不用跳
131
+ .map((l) => {
132
+ const x = it.x + l.x * it.k
133
+ const y = it.y + l.y * it.k
134
+ const w = l.w * it.k
135
+ const ht = l.h * it.k
136
+ return add([`<< /Type /Annot /Subtype /Link /Rect [${pt(x)} ${pt(s.H - y - ht)} ${pt(x + w)} ${pt(s.H - y)}] /Border [0 0 0] /Dest [${kids[l.to]} 0 R /Fit] >>`])
137
+ }))
138
+ objs[kids[si] - 1] = [`<< /Type /Page /Parent ${tree} 0 R /MediaBox [0 0 ${W} ${H}] /Resources << /XObject << ${placed.map((x, j) => `/Im${j} ${x.img} 0 R`).join(' ')} >> >> /Contents ${content} 0 R` +
84
139
  `${annots.length ? ` /Annots [${annots.map((a) => `${a} 0 R`).join(' ')}]` : ''} >>`]
85
140
  })
86
141
  // 书签:每屏一条,名字是屏名(只有一页就不要了)
87
142
  const marks = pages.map((p, i) => ({ i, title: String(p.title || '').trim().slice(0, 120) })).filter((x) => x.title)
88
143
  let outlines = 0
89
- if (pages.length > 1 && marks.length) {
144
+ if (sheets.length > 1 && marks.length) {
90
145
  outlines = add(null)
91
146
  const items = marks.map(() => add(null))
92
147
  items.forEach((o, k) => {
93
- objs[o - 1] = [`<< /Title ${pdfText(marks[k].title)} /Parent ${outlines} 0 R${k ? ` /Prev ${items[k - 1]} 0 R` : ''}${k < items.length - 1 ? ` /Next ${items[k + 1]} 0 R` : ''} /Dest [${kids[marks[k].i]} 0 R /Fit] >>`]
148
+ objs[o - 1] = [`<< /Title ${pdfText(marks[k].title)} /Parent ${outlines} 0 R${k ? ` /Prev ${items[k - 1]} 0 R` : ''}${k < items.length - 1 ? ` /Next ${items[k + 1]} 0 R` : ''} /Dest [${kids[Math.floor(marks[k].i / per)]} 0 R /Fit] >>`]
94
149
  })
95
150
  objs[outlines - 1] = [`<< /Type /Outlines /First ${items[0]} 0 R /Last ${items[items.length - 1]} 0 R /Count ${items.length} >>`]
96
151
  }
@@ -221,8 +276,9 @@ function theme() {
221
276
  '</a:fmtScheme></a:themeElements><a:objectDefaults/><a:extraClrSchemeLst/></a:theme>'
222
277
  }
223
278
 
224
- /** 幻灯片尺寸:按第一屏的比例,长边 13.333 英寸(和 PowerPoint 默认 16:9 一样宽) */
225
- export function slideSize(w, h) {
279
+ /** 幻灯片尺寸:按第一屏的比例,长边 13.333 英寸(和 PowerPoint 默认 16:9 一样宽);A3 用它的实际大小(420×297 毫米) */
280
+ export function slideSize(w, h, layout = '') {
281
+ if (String(layout).trim().toLowerCase() === 'a3') return { cx: 15120000, cy: 10692000 }
226
282
  const LONG = 12192000
227
283
  let cx = w >= h ? LONG : Math.round(LONG * w / h)
228
284
  let cy = w >= h ? Math.round(LONG * h / w) : LONG
@@ -233,45 +289,61 @@ export function slideSize(w, h) {
233
289
 
234
290
  /**
235
291
  * pages: [{ jpg: Buffer, w, h, title, links? }];每张幻灯片一张图,按比例放进去居中(比例不一样的留边,边上铺 bg 色)。
236
- * links 上盖透明形状,放映时点了跳到那一张。bg: 'RRGGBB'
292
+ * links 上盖透明形状,放映时点了跳到那一张。bg: 'RRGGBB'。layout / cols 见 sheetsOf,不选就和原来一样
237
293
  */
238
- export function makePptx(pages, { title = '', bg = 'FFFFFF', date = new Date() } = {}) {
294
+ export function makePptx(pages, { title = '', bg = 'FFFFFF', date = new Date(), layout = '', cols = 1 } = {}) {
239
295
  if (!pages.length) throw new Error('没有页面')
240
- const { cx, cy } = slideSize(pages[0].w, pages[0].h)
296
+ const sheets = sheetsOf(pages, { layout, cols })
297
+ const per = cols === 2 ? 2 : 1
298
+ const { cx, cy } = slideSize(sheets[0].W, sheets[0].H, layout)
241
299
  const fill = /^[0-9a-f]{6}$/i.test(bg) ? bg.toUpperCase() : 'FFFFFF'
242
300
  const files = []
243
- const slides = pages.map((p, i) => {
244
- if (!jpegInfo(p.jpg)) throw new Error('不是 JPEG')
245
- const n = i + 1
246
- const k = Math.min(cx / p.w, cy / p.h)
247
- const w = Math.round(p.w * k)
248
- const ht = Math.round(p.h * k)
249
- const x = Math.round((cx - w) / 2)
250
- const y = Math.round((cy - ht) / 2)
251
- const name = xmlEsc(p.title || `Screen ${n}`)
252
- // 跳转:每个目标页一条关系(rId3 起),每个按钮一个透明形状
301
+ const slides = sheets.map((s, si) => {
302
+ const n = si + 1
303
+ const k = Math.min(cx / s.W, cy / s.H)
304
+ const left = (cx - Math.round(s.W * k)) / 2
305
+ const top = (cy - Math.round(s.H * k)) / 2
306
+ const count = s.items.length
307
+ const titleOf = (it) => pages[it.i].title || `Screen ${it.i + 1}`
308
+ // 跳转:每个目标页一条关系(排在图片后面),每个按钮一个透明形状
253
309
  const targets = []
254
- const hot = pageLinks(p, pages.length, i).map((l, j) => {
255
- let r = targets.indexOf(l.to)
256
- if (r < 0) { targets.push(l.to); r = targets.length - 1 }
257
- return `<p:sp><p:nvSpPr><p:cNvPr id="${j + 3}" name="Link ${j + 1}"><a:hlinkClick r:id="rId${r + 3}" action="ppaction://hlinksldjump"/></p:cNvPr><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` +
258
- `<p:spPr><a:xfrm><a:off x="${x + Math.round(l.x * k)}" y="${y + Math.round(l.y * k)}"/><a:ext cx="${Math.max(1, Math.round(l.w * k))}" cy="${Math.max(1, Math.round(l.h * k))}"/></a:xfrm>` +
259
- '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/><a:ln><a:noFill/></a:ln></p:spPr></p:sp>'
260
- }).join('')
261
- files.push({ name: `ppt/media/image${n}.jpeg`, data: p.jpg })
310
+ let hotN = 0
311
+ const placed = s.items.map((it, j) => {
312
+ const p = pages[it.i]
313
+ if (!jpegInfo(p.jpg)) throw new Error('不是 JPEG')
314
+ const x = Math.round(left + it.x * k)
315
+ const y = Math.round(top + it.y * k)
316
+ const w = Math.round(it.w * it.k * k)
317
+ const ht = Math.round(it.h * it.k * k)
318
+ const name = xmlEsc(titleOf(it))
319
+ const hot = pageLinks(p, pages.length, it.i).map((l) => ({ ...l, to: Math.floor(l.to / per) })).filter((l) => l.to !== si).map((l) => {
320
+ let r = targets.indexOf(l.to)
321
+ if (r < 0) { targets.push(l.to); r = targets.length - 1 }
322
+ const c = hotN++
323
+ const m = it.k * k
324
+ return `<p:sp><p:nvSpPr><p:cNvPr id="${c + 2 + count}" name="Link ${c + 1}"><a:hlinkClick r:id="rId${r + 2 + count}" action="ppaction://hlinksldjump"/></p:cNvPr><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` +
325
+ `<p:spPr><a:xfrm><a:off x="${x + Math.round(l.x * m)}" y="${y + Math.round(l.y * m)}"/><a:ext cx="${Math.max(1, Math.round(l.w * m))}" cy="${Math.max(1, Math.round(l.h * m))}"/></a:xfrm>` +
326
+ '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/><a:ln><a:noFill/></a:ln></p:spPr></p:sp>'
327
+ }).join('')
328
+ files.push({ name: `ppt/media/image${it.i + 1}.jpeg`, data: p.jpg })
329
+ return {
330
+ hot,
331
+ pic: `<p:pic><p:nvPicPr><p:cNvPr id="${j + 2}" name="${name}" descr="${name}"/><p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr><p:nvPr/></p:nvPicPr>` +
332
+ `<p:blipFill><a:blip r:embed="rId${j + 2}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
333
+ `<p:spPr><a:xfrm><a:off x="${x}" y="${y}"/><a:ext cx="${w}" cy="${ht}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>`,
334
+ }
335
+ })
262
336
  files.push({
263
337
  name: `ppt/slides/slide${n}.xml`,
264
- data: XML + `<p:sld xmlns:a="${NS_A}" xmlns:r="${NS_R}" xmlns:p="${NS_P}"><p:cSld name="${name}">` +
338
+ data: XML + `<p:sld xmlns:a="${NS_A}" xmlns:r="${NS_R}" xmlns:p="${NS_P}"><p:cSld name="${xmlEsc(s.items.map(titleOf).join(' / '))}">` +
265
339
  `<p:bg><p:bgPr><a:solidFill><a:srgbClr val="${fill}"/></a:solidFill><a:effectLst/></p:bgPr></p:bg>` +
266
- `<p:spTree>${EMPTY_TREE}<p:pic><p:nvPicPr><p:cNvPr id="2" name="${name}" descr="${name}"/><p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr><p:nvPr/></p:nvPicPr>` +
267
- `<p:blipFill><a:blip r:embed="rId2"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
268
- `<p:spPr><a:xfrm><a:off x="${x}" y="${y}"/><a:ext cx="${w}" cy="${ht}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>` +
269
- hot + '</p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>',
340
+ `<p:spTree>${EMPTY_TREE}${placed.map((x) => x.pic).join('')}${placed.map((x) => x.hot).join('')}</p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>`,
270
341
  })
271
342
  files.push({
272
343
  name: `ppt/slides/_rels/slide${n}.xml.rels`,
273
- data: rels([['rId1', `${REL}/slideLayout`, '../slideLayouts/slideLayout1.xml'], ['rId2', `${REL}/image`, `../media/image${n}.jpeg`],
274
- ...targets.map((to, r) => [`rId${r + 3}`, `${REL}/slide`, `slide${to + 1}.xml`])]),
344
+ data: rels([['rId1', `${REL}/slideLayout`, '../slideLayouts/slideLayout1.xml'],
345
+ ...s.items.map((it, j) => [`rId${j + 2}`, `${REL}/image`, `../media/image${it.i + 1}.jpeg`]),
346
+ ...targets.map((to, r) => [`rId${r + 2 + count}`, `${REL}/slide`, `slide${to + 1}.xml`])]),
275
347
  })
276
348
  return n
277
349
  })
package/lib/index.js CHANGED
@@ -1078,6 +1078,14 @@ export function apply(ctx) {
1078
1078
  }
1079
1079
  }
1080
1080
 
1081
+ /** 导出途中换了设计:还按开始时的那套比一下,对不上就不存(不然 A 的文件会落到 B 的 exports/ 里) */
1082
+ const targetKeyOf = (t) => (!t ? '' : t.kind === 'file' ? `file|${t.root}` : `proxy|${t.port}`)
1083
+ function targetMoved(res, session, expect) {
1084
+ if (typeof expect !== 'string' || !expect || expect === targetKeyOf(tracker.stateOf(session).target)) return false
1085
+ json(res, 409, { error: 'designChanged' })
1086
+ return true
1087
+ }
1088
+
1081
1089
  async function exportRoute(req, res) {
1082
1090
  if (!admit(req, res)) return
1083
1091
  if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
@@ -1085,6 +1093,7 @@ export function apply(ctx) {
1085
1093
  try { body = await readBody(req, MAX_EXPORT) } catch (e) { return json(res, 400, { error: e.message }) }
1086
1094
  const buf = Buffer.from(String(body.png || ''), 'base64')
1087
1095
  if (buf.length < 8 || buf.readUInt32BE(0) !== 0x89504e47) return json(res, 400, { error: '不是 PNG' })
1096
+ if (targetMoved(res, String(body.session || ''), body.target)) return
1088
1097
  saveExport(res, String(body.session || ''), body.name, 'png', buf)
1089
1098
  }
1090
1099
 
@@ -1112,10 +1121,13 @@ export function apply(ctx) {
1112
1121
  const title = String(body.title || '').slice(0, 120)
1113
1122
  let buf
1114
1123
  try {
1115
- buf = format === 'pdf' ? makePdf(pages, { title }) : makePptx(pages, { title, bg: String(body.bg || '') })
1124
+ const bg = String(body.bg || '')
1125
+ const opts = { layout: String(body.layout || '').slice(0, 20), cols: body.cols === 2 ? 2 : 1 }
1126
+ buf = format === 'pdf' ? makePdf(pages, { title, bg, ...opts }) : makePptx(pages, { title, bg, ...opts })
1116
1127
  } catch (e) {
1117
1128
  return json(res, 400, { error: e.message })
1118
1129
  }
1130
+ if (targetMoved(res, String(body.session || ''), body.target)) return
1119
1131
  saveExport(res, String(body.session || ''), body.name, format, buf)
1120
1132
  }
1121
1133
 
package/lib/picker.js CHANGED
@@ -993,33 +993,243 @@
993
993
 
994
994
  const seedNow = () => ({ href: here(), scroll: { x: scrollX, y: scrollY }, sig: snapshot().map })
995
995
 
996
+ /** 选择器列表按顶层逗号拆开(括号、方括号里的逗号不算) */
997
+ function splitSelectors(text) {
998
+ const out = []
999
+ let depth = 0
1000
+ let from = 0
1001
+ for (let i = 0; i < text.length; i++) {
1002
+ const c = text[i]
1003
+ if (c === '\\') i++
1004
+ else if (c === '(' || c === '[') depth++
1005
+ else if (c === ')' || c === ']') depth--
1006
+ else if (c === ',' && !depth) { out.push(text.slice(from, i)); from = i + 1 }
1007
+ }
1008
+ out.push(text.slice(from))
1009
+ return out
1010
+ }
1011
+
1012
+ /** 去掉 :where / :is / :not / :has(...),括号按配对找(可以套好几层);fn 收到名字和括号里的内容 */
1013
+ function stripFns(s, fn) {
1014
+ const re = /:(where|is|not|has|matches|-webkit-any)\(/g
1015
+ let out = ''
1016
+ let from = 0
1017
+ let m
1018
+ while ((m = re.exec(s))) {
1019
+ let depth = 1
1020
+ let j = re.lastIndex
1021
+ for (; j < s.length && depth; j++) { if (s[j] === '(') depth++; else if (s[j] === ')') depth-- }
1022
+ out += s.slice(from, m.index)
1023
+ fn(m[1], s.slice(re.lastIndex, j - 1))
1024
+ from = j
1025
+ re.lastIndex = j
1026
+ }
1027
+ return out + s.slice(from)
1028
+ }
1029
+
1030
+ /** 一个选择器的优先级 [id, 类 / 属性 / 伪类, 元素 / 伪元素];:where 不算,:is / :not / :has 按括号里最高的算 */
1031
+ function specificity(sel) {
1032
+ let [a, b, c] = [0, 0, 0]
1033
+ let s = stripFns(sel.replace(/\\./g, '_'), (name, inner) => {
1034
+ if (name === 'where') return
1035
+ const top = splitSelectors(inner).map(specificity).reduce((x, y) => (rankCmp(x, y) >= 0 ? x : y), [0, 0, 0])
1036
+ a += top[0]; b += top[1]; c += top[2]
1037
+ })
1038
+ s = s.replace(/\[[^\]]*\]/g, () => { b++; return '' })
1039
+ s = s.replace(/#[^\s.#:[\]>+~,()]+/g, () => { a++; return '' })
1040
+ s = s.replace(/\.[^\s.#:[\]>+~,()]+/g, () => { b++; return '' })
1041
+ s = s.replace(/::[\w-]+(?:\([^)]*\))?/g, () => { c++; return '' })
1042
+ s = s.replace(/:[\w-]+(?:\([^)]*\))?/g, () => { b++; return '' })
1043
+ s.replace(/[^\s>+~,*|()&]+/g, () => { c++; return '' })
1044
+ return [a, b, c]
1045
+ }
1046
+
1047
+ function rankCmp(x, y) {
1048
+ for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return x[i] - y[i]
1049
+ return 0
1050
+ }
1051
+
1052
+ const SIZE_PROPS = ['width', 'height', 'min-width', 'min-height', 'inline-size', 'block-size', 'min-inline-size', 'min-block-size', 'aspect-ratio', 'font-size']
1053
+ const LOGICAL = { 'inline-size': 'width', 'block-size': 'height', 'min-inline-size': 'min-width', 'min-block-size': 'min-height' } // 横排时逻辑尺寸就是宽高
1054
+ let declMemo = new Map() // 这一次测量里每个元素的声明:一个元素只扫一遍样式表
1055
+ let cssOpaque = false // 有读不了的布局样式表(别的源的字体表不算)
1056
+
1057
+ const noteOpaque = (sheet) => { if (!/font|typekit|icon/i.test(sheet.href || '')) cssOpaque = true }
1058
+
1059
+ /** 这个元素的几个尺寸属性最终用的是哪一条:!important、行内、@layer 的先后(!important 时反过来)、选择器优先级、靠后的,依次比 */
1060
+ function declaredOf(el) {
1061
+ if (declMemo.has(el)) return declMemo.get(el)
1062
+ const best = {}
1063
+ let seq = 0
1064
+ const layerRoots = new Map() // 层的树:每层记自己在同级里第几个出现(谁先出现谁优先级低)
1065
+ let anon = 0
1066
+ const layerOf = (name, up) => {
1067
+ let at = up
1068
+ for (const part of (name || `#${++anon}`).split('.')) {
1069
+ const sib = at ? at.kids : layerRoots
1070
+ if (!sib.has(part)) sib.set(part, { path: [...(at ? at.path : []), sib.size + 1], kids: new Map() })
1071
+ at = sib.get(part)
1072
+ }
1073
+ return at
1074
+ }
1075
+ const offer = (style, spec, layer, inline) => {
1076
+ for (let i = 0; i < style.length; i++) { // 按写的先后:同一条规则里后写的盖前写的(width 和 inline-size 互相盖)
1077
+ const name = style[i]
1078
+ if (!SIZE_PROPS.includes(name)) continue
1079
+ const value = style.getPropertyValue(name)
1080
+ const order = ++seq
1081
+ const prop = LOGICAL[name] || name
1082
+ const imp = style.getPropertyPriority(name) ? 1 : 0
1083
+ // 比层:普通声明直接写的压过子层、后出现的压过先出现的;!important 全反过来
1084
+ const lr = [0, 1, 2, 3, 4, 5, 6, 7].map((d) => { const n = layer && layer.path[d]; return n ? (imp ? -n : n) : (imp ? -1e6 : 1e6) })
1085
+ const rank = [imp, inline ? 1 : 0, ...lr, ...spec, order]
1086
+ if (!best[prop] || rankCmp(rank, best[prop].rank) > 0) best[prop] = { rank, value }
1087
+ }
1088
+ }
1089
+ const on = (r) => {
1090
+ if (r.media && r.media.mediaText && !matchMedia(r.media.mediaText).matches) return false
1091
+ if (typeof CSSSupportsRule !== 'undefined' && r instanceof CSSSupportsRule && !CSS.supports(r.conditionText)) return false
1092
+ if (typeof CSSContainerRule !== 'undefined' && r instanceof CSSContainerRule) return false // 容器查询算不出来生不生效:页面最外层很少这么写,当不生效
1093
+ return true
1094
+ }
1095
+ const isLayer = (r) => typeof CSSLayerBlockRule !== 'undefined' && r instanceof CSSLayerBlockRule
1096
+ const isLayerList = (r) => typeof CSSLayerStatementRule !== 'undefined' && r instanceof CSSLayerStatementRule
1097
+ const scan = (rules, layer, parent) => {
1098
+ for (const r of rules) {
1099
+ if (isLayerList(r)) { for (const n of r.nameList) layerOf(n, layer); continue }
1100
+ if (r.styleSheet) { // @import
1101
+ if (!on(r)) continue
1102
+ let sub
1103
+ try { sub = r.styleSheet.cssRules } catch { noteOpaque(r.styleSheet); continue }
1104
+ scan(sub, r.layerName != null ? layerOf(r.layerName, layer) : layer, '')
1105
+ continue
1106
+ }
1107
+ if (r.cssRules && !r.selectorText) {
1108
+ if (on(r)) scan(r.cssRules, isLayer(r) ? layerOf(r.name, layer) : layer, parent)
1109
+ continue
1110
+ }
1111
+ if (!r.style || !r.selectorText) continue
1112
+ // 嵌套写法:子规则的选择器接在父规则后面
1113
+ const full = parent ? splitSelectors(r.selectorText).map((p) => (p.includes('&') ? p.replace(/&/g, `:is(${parent})`) : `:is(${parent}) ${p}`)).join(',') : r.selectorText
1114
+ if (SIZE_PROPS.some((p) => r.style.getPropertyValue(p))) {
1115
+ const parts = splitSelectors(full).filter((p) => { try { return el.matches(p) } catch { return false } })
1116
+ if (parts.length) offer(r.style, parts.map(specificity).reduce((x, y) => (rankCmp(x, y) >= 0 ? x : y)), layer, false)
1117
+ }
1118
+ if (r.cssRules && r.cssRules.length) scan(r.cssRules, layer, full)
1119
+ }
1120
+ }
1121
+ for (const sheet of document.styleSheets) {
1122
+ if (sheet.disabled || (sheet.media && sheet.media.mediaText && !matchMedia(sheet.media.mediaText).matches)) continue
1123
+ let rules
1124
+ try { rules = sheet.cssRules } catch { noteOpaque(sheet); continue } // 别的源的样式表读不了
1125
+ scan(rules, null, '')
1126
+ }
1127
+ offer(el.style, [0, 0, 0], null, true)
1128
+ declMemo.set(el, best)
1129
+ return best
1130
+ }
1131
+
1132
+ const FLUID_UNIT = /[\d.](?:[sdl]?v[whib]|[sdl]?vmin|[sdl]?vmax)\b/
1133
+
1134
+ /** 声明的值,CSS 变量换成实际的 */
1135
+ function declaredValue(el, prop) {
1136
+ const d = declaredOf(el)[prop]
1137
+ return String((d && d.value) || '').trim().replace(/var\(\s*(--[\w-]+)\s*(?:,[^)]*)?\)/g, (m, n) => getComputedStyle(el).getPropertyValue(n).trim() || m).toLowerCase()
1138
+ }
1139
+
1140
+ /**
1141
+ * 这个元素的宽 / 高是怎么写的:'fixed' 写死;'floor' 有写死的下限(clamp、max);'fluid' 跟着窗口或没写死的父级;
1142
+ * '' 没写;'unknown' 没写但有读不了的样式表,说不准
1143
+ */
1144
+ function sizeKind(el, prop) {
1145
+ const v = declaredValue(el, prop)
1146
+ if (!v) return cssOpaque ? 'unknown' : ''
1147
+ if (/^(auto|fit-content|max-content|min-content|initial|unset|inherit|revert)$/.test(v)) return ''
1148
+ if (FLUID_UNIT.test(v)) return /^(?:clamp|max)\(\s*[\d.]+px\s*,/.test(v) ? 'floor' : 'fluid'
1149
+ if (/[\d.]rem\b/.test(v) && FLUID_UNIT.test(declaredValue(document.documentElement, 'font-size'))) return 'fluid'
1150
+ if (/[\d.]%/.test(v)) {
1151
+ const up = el.parentElement ? boxKind(el.parentElement, prop.replace('min-', '')) : ''
1152
+ return up === 'fixed' || up === 'floor' ? 'fixed' : up === 'minfluid' ? 'minfluid' : 'fluid'
1153
+ }
1154
+ return 'fixed'
1155
+ }
1156
+
1157
+ /** 宽 / 高连最小值一起看。'minfluid':跟窗口走,但有写死的最小值 */
1158
+ function boxKind(el, prop) {
1159
+ const m = sizeKind(el, `min-${prop}`)
1160
+ const hasMin = m === 'fixed' || m === 'floor'
1161
+ const k = sizeKind(el, prop)
1162
+ if (k === 'fluid' && hasMin) return 'minfluid'
1163
+ if ((!k || k === 'unknown') && hasMin) return m
1164
+ return k
1165
+ }
1166
+
1167
+ /** 写死的最小宽 / 高是多少像素(百分比的沿着父级找) */
1168
+ function minPx(el, prop) {
1169
+ for (let e = el; e; e = e.parentElement) {
1170
+ const floor = /^(?:clamp|max)\(\s*([\d.]+)px/.exec(declaredValue(e, prop)) // clamp(810px,…)、max(810px,…) 的下限
1171
+ if (floor) return parseFloat(floor[1])
1172
+ const min = getComputedStyle(e)[prop === 'width' ? 'minWidth' : 'minHeight']
1173
+ if (/px$/.test(min) && parseFloat(min)) return parseFloat(min)
1174
+ if (!/%/.test(declaredValue(e, prop)) && !/%/.test(min)) return 0
1175
+ }
1176
+ return 0
1177
+ }
1178
+
996
1179
  /**
997
1180
  * 最外层那块的实际大小 [宽, 高](幻灯片 / 海报常写死 1440×810,比框大的话画幅要跟它走)。
998
- * 正好和框一样大(自适应的,或画幅已经跟过来了)、几页竖着堆的、还有别的东西往外撑的:null
1181
+ * null:正好和框一样大、又不是写死的(自适应的);0:不是一整页(几页竖着堆、还有别的东西往外撑)
999
1182
  */
1000
1183
  function naturalSize() {
1001
1184
  const b = document.body
1002
1185
  if (!b) return null
1186
+ declMemo = new Map()
1187
+ cssOpaque = false
1003
1188
  const skip = (el) => el.hasAttribute('data-dsh-design') || /^(SCRIPT|STYLE|LINK|NOSCRIPT|TEMPLATE)$/.test(el.tagName)
1004
- let best = null
1189
+ const kidsOf = (el) => [...el.children].filter((k) => !skip(k))
1005
1190
  let box = null
1006
1191
  let area = 0
1007
- for (const el of [b, ...b.children]) {
1008
- if (skip(el)) continue
1192
+ for (const el of [...kidsOf(b), b]) { // 一样大时算里面那块
1009
1193
  const r = el.getBoundingClientRect()
1010
- if (r.width * r.height > area) { area = r.width * r.height; best = r; box = el }
1011
- }
1012
- if (!best) return null
1013
- // 一样大的几页竖着堆(一个文件里放了几张幻灯片 / 海报):不是一页
1014
- const kids = [...box.children].filter((k) => !skip(k)).map((k) => k.getBoundingClientRect()).filter((r) => r.width && r.height)
1015
- if (kids.length >= 2 && kids[0].height >= innerHeight * 0.8 && kids.every((r) => Math.abs(r.width - kids[0].width) < 2 && Math.abs(r.height - kids[0].height) < 2) && kids[1].top >= kids[0].bottom - 1) return null
1016
- const right = best.right + scrollX
1017
- const bottom = best.bottom + scrollY
1018
- const w = Math.ceil(Math.max(best.width, right))
1019
- const h = Math.ceil(Math.max(best.height, bottom))
1020
- if (Math.abs(w - innerWidth) <= 1 && Math.abs(h - innerHeight) <= 1) return null
1194
+ if (r.width * r.height > area) { area = r.width * r.height; box = el }
1195
+ }
1196
+ if (!box) return null
1197
+ // body 自己没写大小、里面只有一块:量那一块(窗口比它宽时 body 面积更大,但 body 的大小是窗口给的)
1198
+ const only = kidsOf(b)
1199
+ if (box === b && only.length === 1 && !['fixed', 'floor', 'minfluid', 'unknown'].includes(boxKind(b, 'width')) && !['fixed', 'floor', 'minfluid', 'unknown'].includes(boxKind(b, 'height')) && only[0].getBoundingClientRect().height) box = only[0]
1200
+ const wk = boxKind(box, 'width')
1201
+ let hk = boxKind(box, 'height')
1202
+ if ((!hk || hk === 'unknown') && /\d/.test(declaredValue(box, 'aspect-ratio'))) { // 高度没写:比例也算定了高度
1203
+ if (wk === 'fixed') hk = 'fixed'
1204
+ else if (wk === 'fluid' || wk === 'minfluid') hk = 'fluid'
1205
+ }
1206
+ const solid = (k) => k === 'fixed' || k === 'floor' || k === 'minfluid'
1207
+ const kids = kidsOf(box).map((k) => k.getBoundingClientRect()).filter((r) => r.width && r.height)
1208
+ const ratio = kids.length ? kids[0].width / kids[0].height : 0
1209
+ // 一样大的几页竖着堆(一个文件里放了几张幻灯片 / 海报):外层高度写死的是一页里分上下块;每块太扁的也不像一页
1210
+ if (!solid(hk) && kids.length >= 2 && kids[0].height >= 300 && ratio >= 0.45 && ratio <= 2.4 && kids.every((r) => Math.abs(r.width - kids[0].width) < 2 && Math.abs(r.height - kids[0].height) < 2) && kids[1].top >= kids[0].bottom - 1) return 0
1211
+ let { left, top, right, bottom } = box.getBoundingClientRect()
1212
+ // body 的宽高没写死:是窗口或内容给的,按里面的内容算
1213
+ if (box === b && kids.length && !solid(wk) && wk !== 'unknown') { left = Math.min(...kids.map((r) => r.left)); right = Math.max(...kids.map((r) => r.right)) }
1214
+ if (box === b && kids.length && !solid(hk) && hk !== 'unknown') { top = Math.min(...kids.map((r) => r.top)); bottom = Math.max(...kids.map((r) => r.bottom)) }
1215
+ const size = (a, z, view, scroll) => (Math.abs(a + z - view) <= 2 ? z - a : Math.max(z + scroll, z - a)) // 居中的只算它自己,靠左的连左边的空一起
1216
+ let w = Math.ceil(size(left, right, innerWidth, scrollX))
1217
+ let h = Math.ceil(size(top, bottom, innerHeight, scrollY))
1218
+ if (box !== b && wk === 'fluid') w = innerWidth // 按窗口算的(100vw、110vh):框放大了它跟着长,不能照着它放大
1219
+ if (box !== b && hk === 'fluid') h = innerHeight
1220
+ // 跟窗口走但有最小值的:只认最小值,别照着放大后的自己再放大(height:110vh 加 min-height)
1221
+ const follows = (k) => k === 'minfluid' || k === 'floor'
1222
+ const mw = follows(wk) ? minPx(box, 'width') : 0
1223
+ const mh = follows(hk) ? minPx(box, 'height') : 0
1224
+ if (follows(wk) && mw) w = Math.ceil(Math.max(innerWidth, mw))
1225
+ if (follows(hk) && mh) h = Math.ceil(Math.max(innerHeight, mh))
1226
+ // 宽高是内容撑出来的、比框小:那不是版面的大小,按框算(写死的小页面才照实报)
1227
+ if (!solid(wk) && w < innerWidth) w = innerWidth
1228
+ if (!solid(hk) && h < innerHeight) h = innerHeight
1229
+ const pinned = (k, min, view) => k === 'fixed' || (k === 'minfluid' && min >= view - 1) // 大小不随窗口变
1230
+ if (Math.abs(w - innerWidth) <= 1 && Math.abs(h - innerHeight) <= 1) return pinned(wk, mw, innerWidth) && pinned(hk, mh, innerHeight) ? [w, h] : null // 写死的正好装下也报:改稿后右侧栏才拿得到新大小
1021
1231
  const de = document.scrollingElement || document.documentElement
1022
- return de.scrollWidth > Math.max(innerWidth, right) + 40 || de.scrollHeight > Math.max(innerHeight, bottom) + 40 ? null : [w, h]
1232
+ return de.scrollWidth > Math.max(innerWidth, right + scrollX) + 40 || de.scrollHeight > Math.max(innerHeight, bottom + scrollY) + 40 ? 0 : [w, h]
1023
1233
  }
1024
1234
 
1025
1235
  function boot(seed) {
@@ -1823,7 +2033,7 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1823
2033
  const scale = Math.min(3, Math.max(1, Number(opts.scale) || 2))
1824
2034
  const de = document.documentElement
1825
2035
  const W = Math.ceil(de.clientWidth || innerWidth)
1826
- const H = Math.ceil(full ? Math.max(de.scrollHeight, document.body ? document.body.scrollHeight : 0, innerHeight) : innerHeight)
2036
+ const H = Math.ceil(full ? Math.min(Number(opts.maxH) || Infinity, Math.max(de.scrollHeight, document.body ? document.body.scrollHeight : 0, innerHeight)) : innerHeight) // maxH:指定高度,别先画一张超长的图
1827
2037
  const box = makeSandbox()
1828
2038
  const inline = makeInliner()
1829
2039
  // 只截看得到的这一屏(不是整页):页面滚过、里面的滚动区滚过、有贴住的(sticky)元素,画成图时都得照现在的样子摆
@@ -1918,7 +2128,8 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1918
2128
  const withUrls = []
1919
2129
  const def = box.defaults(el)
1920
2130
  let st = styleText(cs, def, withUrls)
1921
- if (el === de) st += 'overflow:hidden;'
2131
+ if (el === de) st += (full ? `height:${H}px;max-height:none;` : '') + 'overflow:hidden;' // 整页:根元素写了 height:100%、max-height 也要放得下整页
2132
+ if (full && el === document.body) st += 'max-height:none;'
1922
2133
  // iframe / 视频换成了 div:默认的 300×150、行内排列也得写明(和 iframe 默认一样的样式上面省掉了)
1923
2134
  if (tag === 'IFRAME' || tag === 'VIDEO' || tag === 'OBJECT' || tag === 'EMBED') {
1924
2135
  st += `display:${cs.display === 'inline' ? 'inline-block' : cs.display};width:${cs.width};height:${cs.height};box-sizing:${cs.boxSizing};vertical-align:${cs.verticalAlign};overflow:hidden;`
@@ -2302,6 +2513,36 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
2302
2513
  }
2303
2514
  }
2304
2515
 
2516
+ // 导出前预检:这一页实际多大、有几个点了没反应的链接(href="#"、指向不存在的文件)
2517
+ async function onMeasure(d) {
2518
+ try {
2519
+ if (document.readyState !== 'complete') await new Promise((r) => { addEventListener('load', r, { once: true }); setTimeout(r, 1500) })
2520
+ const de = document.documentElement
2521
+ const b = document.body
2522
+ const dead = [] // 每个死链接在页面上的纵坐标:导出的范围以外的不用报
2523
+ for (const a of document.querySelectorAll('a[href="#"],a[href=""]')) {
2524
+ if ((host && host.contains(a)) || a.hasAttribute('onclick') || a.hasAttribute('data-href') || a.hasAttribute('data-to')) continue
2525
+ const r = a.getBoundingClientRect()
2526
+ const seen = !a.checkVisibility || a.checkVisibility({ opacityProperty: true, visibilityProperty: true })
2527
+ if (seen && r.width >= 2 && r.height >= 2 && r.left < (de.clientWidth || innerWidth) && r.right > 0) dead.push(r.top + scrollY)
2528
+ }
2529
+ const found = linksOf().filter((l) => l.x < (de.clientWidth || innerWidth))
2530
+ const paths = found.map((l) => l.path)
2531
+ const gone = new Map()
2532
+ await Promise.all([...new Set(paths)].map(async (p) => {
2533
+ try {
2534
+ const r = await fetch(encodeURI(p), { cache: 'no-store' })
2535
+ gone.set(p, r.status === 404)
2536
+ if (r.body) r.body.cancel().catch(() => {})
2537
+ } catch { /* 查不了就不算 */ }
2538
+ }))
2539
+ for (const l of found) if (gone.get(l.path)) dead.push(l.y + scrollY)
2540
+ post({ type: 'measured', id: d.id, sy: scrollY, w: de.clientWidth || innerWidth, h: innerHeight, pageW: Math.max(de.scrollWidth, b ? b.scrollWidth : 0), pageH: Math.max(de.scrollHeight, b ? b.scrollHeight : 0), natural: naturalSize(), dead })
2541
+ } catch (e) {
2542
+ post({ type: 'measured', id: d.id, error: String((e && e.message) || e) })
2543
+ }
2544
+ }
2545
+
2305
2546
  // ── 设计体检:在画好的页面上实测常见毛病,标在页面上,报给右侧栏(给人看的文字由右侧栏按界面语言拼) ──
2306
2547
  //
2307
2548
  // hscroll 超出屏幕(会横向滚动 / 被切掉) · clipped 文字被截断 · overflow 文字超出框 · overlap 文字叠在一起
@@ -4004,6 +4245,7 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
4004
4245
  else if (d.type === 'unpin') unpin()
4005
4246
  else if (d.type === 'reload') selfReload()
4006
4247
  else if (d.type === 'capture') onCapture(d)
4248
+ else if (d.type === 'measure') onMeasure(d)
4007
4249
  else if (d.type === 'check') onCheck(d)
4008
4250
  else if (d.type === 'checkClear') { clearMarks(); lastIssues = [] }
4009
4251
  else if (d.type === 'checkFocus') focusIssue(Number(d.i))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-design-studio",
3
- "version": "0.13.1",
3
+ "version": "0.14.0",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1 test/*.mjs"