dsh-design-studio 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -52,7 +52,7 @@ import { fileURLToPath } from 'node:url'
52
52
  import os from 'node:os'
53
53
  import { execFile } from 'node:child_process'
54
54
  import { createHub, webOrigins, trustedOrigins, resolveInRoot, ERR_CATCHER, stateScript, defang } from './serve.js'
55
- import { bundle, inlinePicker, strictMeta, MAX_TOTAL as BUNDLE_MAX } from './bundle.js'
55
+ import { bundle, dataAssets, inlinePicker, strictMeta, MAX_TOTAL as BUNDLE_MAX } from './bundle.js'
56
56
  import { buildPack, PACK_SCREENS } from './htmlpack.js'
57
57
  import { createLibrary } from './works.js'
58
58
  import { createInspiration } from './inspire.js'
@@ -73,12 +73,14 @@ import { createCanvasThumbs, createDirRevs } from './canvthumb.js'
73
73
  import { designOf, fitSize, metaOfFile, sizeOf, pickScreens, measureAll, shootAll, cropIssues, formatMeasure, issueSnapshot, formatShots, whereOf, MAX_SCREENS, MAX_SIZES, MAX_SHOTS, MAX_CROPS } from './look.js'
74
74
  import { SYSTEMS_DIR, extractSystem, listSystems, setDefault, skillSection } from './system.js'
75
75
  import { saveFrame, listFrames, frameSection, frameDir, renameFrame, removeFrame } from './frames.js'
76
- import { readTweaks, applyTweaks, lintTweaks } from './tweaks.js'
76
+ import { readTweaks, applyTweaks, lintTweaks, syncFonts, lintFonts, libFontsUsed, setVarDecl, setVarInHtml } from './tweaks.js'
77
+ import { createFonts, loadFontIndex, loadFontPreviews, libFontOf, findFont, stackOf, syncFontBlock, fontBlockIds, fontPrefix, libFontIdOf, FONT_DIR } from './fonts.js'
77
78
  import { readAnnotations, lintAnnotations, annotationFindings, annotationSection } from './annotations.js'
78
79
  import { createImpl } from './impl.js'
79
80
  import { FRAMEWORKS, detectProject, projectFor, defaultFramework, buildHandoff, compareScreens, implUrl, implServe, defaultDest, pickedDest, within, pinRoots, frameCss } from './handoff.js'
80
81
  import { editsNotice, noticeMessage, langOf } from './edits.js'
81
82
  import { statesOfFile, expandStates, splitStateNames, withState } from './states.js'
83
+ import { MOCK_FILE, MOCK_MAX, mockOfBuf, mockScript, saveMock } from './mock.js'
82
84
  import { partDrift, formatDrift } from './drift.js'
83
85
 
84
86
  export const name = 'dsh-design-studio'
@@ -108,7 +110,7 @@ const SKILL_RANK = 600 // 和 DSH 自带的技能同一档;用户 / 项目里
108
110
  * 几行之间靠这个互通(同一个包里的模块 Node 只加载一次):工作台起来后放 tracker、无头浏览器(browser);
109
111
  * 「自动打开预览」那行开着时 autoOpen > 0
110
112
  */
111
- export const studio = { tracker: null, impl: null, openPreview: null, autoOpen: 0, offline: 0, annotations: 0, check: null, browser: null, market: null, photos: null, sessionCwd: null, log: () => {} }
113
+ export const studio = { tracker: null, impl: null, openPreview: null, autoOpen: 0, offline: 0, annotations: 0, check: null, browser: null, market: null, photos: null, fonts: null, sessionCwd: null, log: () => {} }
112
114
 
113
115
  /** 设计技能:模型做界面设计时加载(DSH 的 skill 工具),也能让用户手动调 */
114
116
  export const designSkill = {
@@ -345,7 +347,7 @@ export const checkTool = {
345
347
  if (want.more) text += `\n尺寸太多,只量了前 ${MAX_SIZES} 种`
346
348
  if (ex.skipped) text += `\n状态太多,有 ${ex.skipped} 个状态没量:screens 写成 order.html?state=状态名 单量那个状态`
347
349
  text += stateMisses(pick0.list, stOf, sn.only, '量的是这屏全部状态')
348
- text += tweakNotes(id) + annotationNotes(anAt, rows) + driftNotes(id)
350
+ text += tweakNotes(id) + fontNotes(id) + annotationNotes(anAt, rows) + driftNotes(id)
349
351
  return kept && kept.images ? { text, images: kept.images } : { text }
350
352
  }
351
353
  studio.log(new Error(`check_design 无头浏览器没量成:${rows[0] && rows[0].error}`))
@@ -359,7 +361,7 @@ export const checkTool = {
359
361
  const note = want.sizes.length || a.dark ? '(这台电脑上没找到能用的 Chrome / Edge,没法按指定尺寸 / 深色量;下面是右侧栏按它现在显示的尺寸量的)\n' : ''
360
362
  if (!r) return { text: '右侧栏「设计工作台」现在没开着,量不了。照 ui-design 技能里的「自查」清单自己过一遍。' }
361
363
  if (!r.error && !r.measured) return { text: '右侧栏开着,但预览页面没回应,这次没量成(可能还在加载)。过一会儿再调一次,或照 ui-design 技能里的「自查」清单自己过一遍。' }
362
- return { text: note + (r.error || r.text) + tweakNotes(id) + annotationNotes(anAt, null) + (r.error ? '' : driftNotes(id)) }
364
+ return { text: note + (r.error || r.text) + tweakNotes(id) + fontNotes(id) + annotationNotes(anAt, null) + (r.error ? '' : driftNotes(id)) }
363
365
  },
364
366
  }
365
367
 
@@ -394,6 +396,16 @@ function annotationNotes(at, rows) {
394
396
  return list.length ? `\n\n业务标注(annotations.json):\n${list.map((x) => `- ${x}`).join('\n')}` : ''
395
397
  }
396
398
 
399
+ /** 字体库的字体有没有真放进来:check_design 末尾附上 */
400
+ function fontNotes(id) {
401
+ let list = []
402
+ try {
403
+ const t = studio.tracker.stateOf(id).target
404
+ if (t && t.kind === 'file' && studio.fonts) list = lintFonts(t.root, studio.fonts.index)
405
+ } catch (e) { studio.log(e) }
406
+ return list.length ? `\n\n字体库:\n${list.map((x) => `- ${x}`).join('\n')}` : ''
407
+ }
408
+
397
409
  /** 调节滑块(tweaks.json)有没有真接上:check_design 末尾附上 */
398
410
  function tweakNotes(id) {
399
411
  let list = []
@@ -728,6 +740,110 @@ export const photoTool = {
728
740
  },
729
741
  }
730
742
 
743
+ const FONT_CAT = { sans: '黑体 / 无衬线', serif: '宋体 / 衬线', display: '标题', hand: '书法手写', mono: '等宽' }
744
+ /** 工具说明里列字体库(名字 + 说明),模型不用先调一次才知道有什么 */
745
+ const fontMenu = () => {
746
+ const idx = loadFontIndex()
747
+ if (!idx) return ''
748
+ const zh = idx.fonts.filter((f) => f.lang === 'zh').map((f) => `${f.zh}(${FONT_CAT[f.cat]},${f.nzh})`)
749
+ const en = idx.fonts.filter((f) => f.lang !== 'zh').map((f) => `${f.en}(${f.nzh})`)
750
+ return `中文:${zh.join(';')}。英文(只有英文和数字):${en.join(';')}。`
751
+ }
752
+
753
+ /** use_fonts 工具(#31):从字体库把一款字体放进设计(复制文件 + 写 @font-face),给了 var 就顺便把变量换成它 */
754
+ export const fontTool = {
755
+ name: 'use_fonts',
756
+ description:
757
+ '把设计台字体库(免费可商用,SIL OFL)里的一款字体放进这套设计:字体文件复制进设计目录的 dsh-fonts/,tokens.css 里写好 @font-face,给了 var 就顺便把那个变量换成这款字体的字体栈。' +
758
+ '用户点名要某种字体(思源宋体、毛笔字、手写、得意黑…),或这套设计要系统字体给不了的气质(国风书法标题、潮流海报、手账手写)时用;普通界面用系统字体栈就够,不用调。一次放一款,标题和正文各要一款就调两次。' +
759
+ fontMenu(),
760
+ parameters: specToJsonSchema({
761
+ font: { type: 'string', required: true, description: '字体名,中文名、英文名都行,如「思源宋体」「Smiley Sans」「马善政毛笔楷书」' },
762
+ var: { type: 'string', description: '顺便换成这款字体的 CSS 变量,如 --font-display(tokens.css 的 :root 里要已经有它);不填只放字体,自己写 font-family' },
763
+ file: { type: 'string', description: '写 @font-face 和变量的样式文件(相对设计目录),默认 tokens.css;变量写在页面 <style> 里时填那个 .html' },
764
+ dir: { type: 'string', description: '这套设计的文件夹(绝对路径或相对会话目录)。不填用正在预览的设计目录' },
765
+ }),
766
+ output: {
767
+ schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string' } }, required: ['text'] },
768
+ render: (_args, value) => [{ type: 'text', text: value.text }],
769
+ },
770
+ async execute(args, exec) {
771
+ const id = toolSession(exec, '放字体')
772
+ const a = args || {}
773
+ const lib = studio.fonts
774
+ if (!lib) return { text: '这个版本的设计台没带字体库。用系统字体栈。' }
775
+ const f = findFont(lib.index, typeof a.font === 'string' ? a.font : '')
776
+ if (!f) return { text: `字体库里没有「${String(a.font || '').slice(0, 40)}」。有这些:${fontMenu()}没有合适的就用系统字体栈。` }
777
+ const cwd = studio.sessionCwd ? await studio.sessionCwd(id) : studio.tracker.cwdOf(id)
778
+ const t = studio.tracker.stateOf(id).target
779
+ const root = t && t.kind === 'file' ? t.root : ''
780
+ const dir = typeof a.dir === 'string' && a.dir.trim() ? resolvePath(a.dir, cwd) : root
781
+ if (!dir) return { text: '不知道放哪:先建好这套设计的文件夹,把路径写进 dir。' }
782
+ const allowed = pinRoots([cwd, root])
783
+ if (!allowed(dir)) return { text: `${dir} 不在会话目录(${cwd})里,字体不能放那儿。放进这套设计自己的文件夹。` }
784
+ const rel = (typeof a.file === 'string' && a.file.trim() ? a.file.trim() : 'tokens.css').replace(/\\/g, '/').replace(/^\.\//, '')
785
+ if (!/\.(css|html?)$/i.test(rel) || rel.split('/').includes('..') || path.isAbsolute(rel)) return { text: 'file 要填设计目录里的 .css 或 .html(相对路径)。' }
786
+ const file = path.join(dir, rel)
787
+ // 要改的文件得是这套设计自己的:真实位置在设计文件夹里(中间哪层是指到别处的软链接也不行)
788
+ const own = () => {
789
+ try {
790
+ if (!fs.lstatSync(file).isFile()) return 'none'
791
+ const realDir = fs.realpathSync(dir)
792
+ return fs.realpathSync(file).startsWith(realDir + path.sep) ? '' : 'out'
793
+ } catch { return 'none' }
794
+ }
795
+ const bad = own()
796
+ if (bad === 'none') return { text: `${file} 不存在:先建好 ${rel}(设计变量写在里面),再调 use_fonts。` }
797
+ if (bad === 'out') return { text: `${file} 指向了这套设计外面(软链接),不能改。把 @font-face 写进这套设计自己的样式文件。` }
798
+ const v = typeof a.var === 'string' ? a.var.trim() : ''
799
+ if (v && !/^--[A-Za-z0-9_-]{1,60}$/.test(v)) return { text: 'var 要写 CSS 变量名,如 --font-display。' }
800
+ try {
801
+ await lib.provide(dir, [f], allowed)
802
+ } catch (e) {
803
+ studio.log(e)
804
+ if (e && e.code === 'off') return { text: '「设计库不联网」开着,字体库下载不了。这次用系统字体栈,并告诉用户:关掉这个开关就能用字体库。' }
805
+ if (e && e.code === 'link') return { text: `${path.join(dir, FONT_DIR)} 指向了这个文件夹外面,字体不能放那儿。` }
806
+ if (e && /^(EACCES|EPERM|EROFS|ENOTDIR|EEXIST|ENOSPC)$/.test(e.code || '')) return { text: `${path.join(dir, FONT_DIR)} 写不进去(${e.code})。这次用系统字体栈。` }
807
+ return { text: '字体库这会儿下载不了(网络问题)。这次先用系统字体栈,稍后可以再试。' }
808
+ }
809
+ // 下载完再读(第一次要下好一会儿,这期间文件可能被改过);从这里到写回不再等别的,几次调用不会互相盖掉
810
+ if (own()) return { text: `${file} 读不了。` }
811
+ let text
812
+ try { text = fs.readFileSync(file, 'utf8') } catch { return { text: `${file} 读不了。` } }
813
+ const isHtml = /\.html?$/i.test(rel)
814
+ const stack = stackOf(f)
815
+ let varNote = ''
816
+ const before = v ? libFontsUsed(dir, lib.index) : null
817
+ if (v) {
818
+ const next = isHtml ? (setVarInHtml(text, v, stack) ?? setVarInHtml(text, v, stack, true)) : (setVarDecl(text, v, stack) ?? setVarDecl(text, v, stack, true))
819
+ if (next === null) varNote = `${rel} 的 :root 里没有 ${v},没改变量:自己把要用的变量写成 ${stack}。\n`
820
+ else { text = next; varNote = `${v} 已经换成:${stack}\n` }
821
+ }
822
+ // 这次把变量原来的库字体换走了、整套设计都不再写它的名字:那段里去掉它(别的一概只加不减)
823
+ const after = before ? libFontsUsed(dir, lib.index, { [rel]: text }) : null
824
+ const drop = before && !before.partial && !after.partial ? [...before].filter((x) => !after.has(x) && x !== f.id) : []
825
+ const synced = syncFontBlock(text, [f.id], lib.index, { prefix: fontPrefix(rel), isHtml, drop })
826
+ if (synced !== null) text = synced
827
+ if (!fontBlockIds(text).includes(f.id)) {
828
+ return { text: isHtml ? `${rel} 里没有 <style>,@font-face 放不进去,什么都没改(字体文件已经放进 ${FONT_DIR}/)。file 改填这页引用的 .css(如 tokens.css),或者先在这页 <head> 里加一个 <style>。` : `${rel} 里没能写进 @font-face,什么都没改。` }
829
+ }
830
+ try { fs.writeFileSync(file, text) } catch (e) { return { text: `${file} 写不进去(${e.code || e.message})。` } }
831
+ const one = !Array.isArray(f.weights)
832
+ const notes = [
833
+ one ? '这款只有一种粗细:标题写 700、800 也不会变粗(已经让浏览器别硬描粗),要对比就靠字号。' : '',
834
+ f.lang !== 'zh' ? '这款只有英文和数字,中文由字体栈后面的系统字体显示。' : '只带了常用的 6763 个汉字,生僻字由字体栈后面的系统字体显示。',
835
+ ].filter(Boolean).join('')
836
+ return {
837
+ text:
838
+ `已放进 ${path.join(dir, FONT_DIR, `${f.id}.woff2`)}(${f.zh},${(f.size / 1024 / 1024).toFixed(1)} MB),${rel} 开头写好了 @font-face(「dsh-fonts」那段由设计台管,别改)。\n` +
839
+ varNote +
840
+ (v ? '' : `用法:font-family 写 ${stack}\n`) +
841
+ notes + '\n' +
842
+ `之后改 ${rel} 用局部修改,别整个重写(重写了那段会丢,再调一次 use_fonts)。免费可商用(SIL OFL 1.1),可以告诉用户。`,
843
+ }
844
+ },
845
+ }
846
+
731
847
  /** pick_style 工具:用户没定风格时按题材挑一张风格卡(模型自己定,消费类题目总落回米色暖调;给了具体配色它照做得很好) */
732
848
  export const styleTool = {
733
849
  name: 'pick_style',
@@ -983,6 +1099,7 @@ export function apply(ctx) {
983
1099
  history,
984
1100
  drafts,
985
1101
  skipAnnots: () => studio.annotations > 0, // 业务标注开着时这个文件只给右侧栏看,改了不刷新页面
1102
+ fontFile: (id) => (studio.fonts ? studio.fonts.cached(id) : null), // 字体库(#31):面板里试字体时页面从这里拿(还没存进设计)
986
1103
  strict: { html: (buf) => library.strictHtml(buf) || market.strictHtml(buf), root: (dir) => library.strictRoot(dir) || market.isStaging(dir), versions: (dir) => library.strictVersions(dir) },
987
1104
  // 桌面版的 dsh-app://app 是默认就认的;这里补上 DSH 网页端的地址,和 DSH 配置里声明的对外地址(反向代理 / 域名)
988
1105
  parents: () => {
@@ -1034,6 +1151,9 @@ export function apply(ctx) {
1034
1151
  const photoIndex = loadPhotoIndex()
1035
1152
  const photos = photoIndex ? createPhotos({ market, index: photoIndex, log }) : null
1036
1153
  studio.photos = photos
1154
+ const fontIndex = loadFontIndex()
1155
+ const fonts = fontIndex ? createFonts({ market, index: fontIndex, log }) : null
1156
+ studio.fonts = fonts
1037
1157
  studio.sessionCwd = sessionCwd
1038
1158
  studio.impl = implStore
1039
1159
  studio.openPreview = open
@@ -1043,6 +1163,7 @@ export function apply(ctx) {
1043
1163
  if (studio.tracker === tracker) { studio.tracker = null; studio.log = () => {} }
1044
1164
  if (studio.market === market) { market.abort(); studio.market = null }
1045
1165
  if (studio.photos === photos) studio.photos = null
1166
+ if (studio.fonts === fonts) studio.fonts = null
1046
1167
  if (studio.sessionCwd === sessionCwd) studio.sessionCwd = null
1047
1168
  }
1048
1169
  }, 'dsh-design-studio: tracker')
@@ -1176,7 +1297,75 @@ export function apply(ctx) {
1176
1297
  const values = body.values && typeof body.values === 'object' && !Array.isArray(body.values) ? body.values : {}
1177
1298
  try {
1178
1299
  const vars = body.vars && typeof body.vars === 'object' && !Array.isArray(body.vars) ? body.vars : null
1179
- const r = tracker.editDir(String(body.session || ''), (root) => applyTweaks(root, values, vars), (x) => `调节:${x.changed.map((c) => `${c.label} ${c.to}`).join('、')}`.slice(0, 60), String(body.root || ''))
1300
+ const session = String(body.session || '')
1301
+ const want = String(body.root || '')
1302
+ // 字体库(#31):换成字体库的字体要先下载好、复制进设计的 dsh-fonts/(只往右侧栏正看着的这套设计里放)
1303
+ const lib = studio.fonts
1304
+ const picks = lib && vars ? [...new Set(Object.values(vars).map((v) => libFontOf(lib.index, v)).filter(Boolean))] : []
1305
+ if (picks.length) {
1306
+ const t = tracker.stateOf(session).target
1307
+ if (!t || t.kind !== 'file') return json(res, 200, { ok: false, reason: 'not-file' })
1308
+ if (t.root !== want) return json(res, 200, { ok: false, reason: 'moved' })
1309
+ try {
1310
+ await lib.provide(t.root, picks, pinRoots([t.root]))
1311
+ } catch (e) {
1312
+ log(e)
1313
+ return json(res, 200, { ok: false, reason: e && e.code === 'off' ? 'font-off' : e && /^(link|EACCES|EPERM|EROFS|ENOTDIR|ENOSPC)$/.test(e.code || '') ? 'font-write' : 'font-net' })
1314
+ }
1315
+ }
1316
+ const r = tracker.editDir(session, (root) => {
1317
+ // 只在这次改了字体栈时才扫整套设计(只改颜色、拖滑块不用读一遍所有文件)
1318
+ const fontish = (v) => /["']/.test(String(v)) || /(?:^|,)\s*(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-[\w-]+)\s*(?:,|$)/i.test(String(v))
1319
+ const before = lib && vars && Object.values(vars).some(fontish) ? libFontsUsed(root, lib.index) : null
1320
+ const x = applyTweaks(root, values, vars)
1321
+ // 变量写进了哪些样式,那里的 @font-face 那段跟着变:选了字体库的加上;这次换走了、整套设计都不再写名字的去掉(别的不动)
1322
+ if (x.ok && x.files.length && lib) {
1323
+ const after = before ? libFontsUsed(root, lib.index) : null
1324
+ const drop = before && !before.partial && !after.partial ? [...before].filter((id) => !after.has(id)) : []
1325
+ x.files = [...new Set([...x.files, ...syncFonts(root, x.files, picks.map((f) => f.id), lib.index, { drop })])]
1326
+ }
1327
+ return x
1328
+ }, (x) => `调节:${x.changed.map((c) => `${c.label} ${c.to}`).join('、')}`.slice(0, 60), want)
1329
+ json(res, 200, r)
1330
+ } catch (e) {
1331
+ json(res, 500, { error: e.message })
1332
+ }
1333
+ }
1334
+
1335
+ /**
1336
+ * 字体库(#31):GET → 列表(名字、分类、说明、字体栈、预览图形)和下载好了没有;
1337
+ * POST → 下载(第一次点字体库的字体时,好在页面上马上换给用户看)
1338
+ */
1339
+ async function fontsRoute(req, res) {
1340
+ if (!admit(req, res)) return
1341
+ const lib = studio.fonts
1342
+ if (!lib) return json(res, 200, { fonts: [], ready: false, none: true })
1343
+ if (req.method === 'POST') {
1344
+ try { await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
1345
+ try {
1346
+ await lib.ensure()
1347
+ } catch (e) {
1348
+ return json(res, 200, { ok: false, reason: e && e.code === 'off' ? 'off' : 'net' })
1349
+ }
1350
+ return json(res, 200, { ok: true, ready: true })
1351
+ }
1352
+ const pv = fontPreviews || (fontPreviews = loadFontPreviews())
1353
+ json(res, 200, {
1354
+ ready: lib.ready(),
1355
+ size: lib.index.fonts.reduce((n, f) => n + f.size, 0),
1356
+ fonts: lib.index.fonts.map((f) => ({ id: f.id, family: f.family, zh: f.zh, en: f.en, cat: f.cat, lang: f.lang, nzh: f.nzh, nen: f.nen, size: f.size, stack: stackOf(f), weights: f.weights, pv: pv[f.id] || null })),
1357
+ })
1358
+ }
1359
+ let fontPreviews = null
1360
+
1361
+ /** 「数据」面板的「存成初始数据」(#30):POST { session, root, data, fp } → 写回 mock.json(记一版、告诉模型用户改了) */
1362
+ async function mockSaveRoute(req, res) {
1363
+ if (!admit(req, res)) return
1364
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1365
+ let body
1366
+ try { body = await readBody(req, MOCK_MAX + 64 * 1024) } catch (e) { return json(res, 400, { error: e.message }) }
1367
+ try {
1368
+ const r = tracker.editDir(String(body.session || ''), (root) => saveMock(root, body.data, typeof body.fp === 'string' ? body.fp : ''), () => '模拟数据:存成初始数据', String(body.root || ''))
1180
1369
  json(res, 200, r)
1181
1370
  } catch (e) {
1182
1371
  json(res, 500, { error: e.message })
@@ -1641,10 +1830,19 @@ export function apply(ctx) {
1641
1830
  function bundleFile(root, v, rel) {
1642
1831
  let f = ''
1643
1832
  if (v) f = history.fileOf(root, v, rel) || ''
1833
+ // 模拟数据和预览一个规矩(serve.js versionMock / mockOf):旧版本只认那一版自己的 mock.json(那版没有就是没有,
1834
+ // 不拿现在的顶上);现在的是软链接就当没有
1835
+ if (rel === MOCK_FILE) {
1836
+ if (v) return f
1837
+ const p = path.join(root, MOCK_FILE)
1838
+ try { return fs.lstatSync(p).isFile() ? p : '' } catch { return '' }
1839
+ }
1644
1840
  if (!f) {
1645
1841
  const hit = resolveInRoot(root, '/' + rel.split('/').map(encodeURIComponent).join('/'))
1646
1842
  f = hit && hit.real ? hit.real : ''
1647
1843
  }
1844
+ // 字体库(#31):dsh-fonts/<库 id>.woff2 不进版本记录、也可能被手动删了,从字体库缓存拿(和 serve.js 历史预览一样)
1845
+ if (!f && studio.fonts && libFontIdOf(rel)) f = studio.fonts.cached(libFontIdOf(rel)) || ''
1648
1846
  return f
1649
1847
  }
1650
1848
 
@@ -1706,10 +1904,12 @@ export function apply(ctx) {
1706
1904
  // 打的是哪个目标:右侧栏拿它核对,请求发出后会话换了目录(或预览服务器换了端口)的回包不存进它的缓存
1707
1905
  const whose = { root: t.root, origin: st.origin || '' }
1708
1906
  // 先看大小,太大的不读(打包总量也封顶,见 bundle.js)
1907
+ const big = new Set() // 有、但太大没读的
1709
1908
  const readRel = (rel) => {
1710
1909
  const f = bundleFile(t.root, v, rel)
1711
1910
  if (!f) return null
1712
1911
  const s = fs.statSync(f)
1912
+ if (s.isFile() && s.size > BUNDLE_MAX) big.add(rel)
1713
1913
  return s.isFile() && s.size <= BUNDLE_MAX ? fs.readFileSync(f) : null
1714
1914
  }
1715
1915
  // 别人做的设计(设计库来的、没改过):加硬规矩,右侧栏的沙盒也不放行表单
@@ -1746,7 +1946,15 @@ export function apply(ctx) {
1746
1946
  const nonce = strict ? crypto.randomBytes(16).toString('base64') : ''
1747
1947
  // 页面写了这个状态才设(老页面自己拿 ?state= 当参数的不动)
1748
1948
  const setState = state ? stateScript(page.toString('utf8'), '?state=' + state) : ''
1749
- const lead = strict ? strictMeta(nonce) + (ERR_CATCHER + setState).replaceAll('<script>', `<script nonce="${nonce}">`) : ERR_CATCHER + setState
1949
+ // 模拟数据(#30):读 mock.json 也记进用到的文件(改了就重新打包);存的键按设计目录分开(右侧栏同一个源里放着几套设计)
1950
+ const mk = mockOfBuf(read(MOCK_FILE), big.has(MOCK_FILE)) // 太大的:和预览一样带上运行时、报「太大」
1951
+ // 数据里写的本地图片:远程那边够不着预览地址,和页面里的图一样换成 data: 地址
1952
+ const over = []
1953
+ const mockAssets = mk ? dataAssets(mk.data, read, BUNDLE_MAX, over, (rel) => big.has(rel)) : null
1954
+ // 换不下的图(太大):不悄悄留成坏图,报进这屏的页面错误(体检、屏上看得到)
1955
+ const mockErr = mk ? [mk.err, over.length ? `数据里的图太大,远程看时没带上:${over.slice(0, 3).join('、')}${over.length > 3 ? ' 等' : ''}` : ''].filter(Boolean).join(';') : ''
1956
+ const mockTag = mk ? mockScript({ ...mk, assets: mockAssets, err: mockErr }, { scope: crypto.createHash('sha1').update(t.root).digest('hex').slice(0, 10) }) : ''
1957
+ const lead = strict ? strictMeta(nonce) + (ERR_CATCHER + setState + mockTag).replaceAll('<script>', `<script nonce="${nonce}">`) : ERR_CATCHER + setState + mockTag
1750
1958
  let html = bundle(strict ? defang(page.toString('utf8')) : page.toString('utf8'), { key, read, base: href, lead, tail: inlinePicker(fs.readFileSync(PICKER_FILE, 'utf8'), parent, href, nonce) })
1751
1959
  // 打包后图片变成 data: 地址,文件名没了:把用到的 AI 示意图记在页面里,导出时照样提醒
1752
1960
  const aiNames = [...deps].filter((x) => isPhotoAsset(x)).map((x) => path.basename(x))
@@ -1958,7 +2166,8 @@ export function apply(ctx) {
1958
2166
  os: body.os === 'win' ? 'win' : '',
1959
2167
  dark: body.dark === true,
1960
2168
  scheme: body.scheme === 'dark' ? 'dark' : 'light',
1961
- tweak: tw ? { vars: plain(tw.vars), attrs: plain(tw.attrs) } : null,
2169
+ // fonts:外观面板里选了、还没存的字体库字体(只要 id,打包时从字体库缓存读)
2170
+ tweak: tw ? { vars: plain(tw.vars), attrs: plain(tw.attrs), fonts: Array.isArray(tw.fonts) ? [...new Set(tw.fonts.map((x) => (x && typeof x === 'object' ? x.id : x)).filter((x) => typeof x === 'string' && /^[a-z0-9-]{1,40}$/.test(x)))].slice(0, 8) : [] } : null,
1962
2171
  title: String(body.title || '').slice(0, 120),
1963
2172
  lang: body.lang === 'en' ? 'en' : 'zh',
1964
2173
  fit: body.fit === true,
@@ -1969,16 +2178,23 @@ export function apply(ctx) {
1969
2178
  function packDesign(root, v, params) {
1970
2179
  const deps = new Set()
1971
2180
  const files = new Set()
2181
+ const big = new Set() // 有、但太大没读的(数据里绑的图读不了要报出来,不能当没有)
1972
2182
  const read = (rel) => {
1973
2183
  deps.add(rel)
1974
2184
  const f = bundleFile(root, v, rel)
1975
2185
  files.add(f || path.join(root, ...rel.split('/')))
1976
2186
  if (!f) return null
1977
2187
  const s = fs.statSync(f)
2188
+ if (s.isFile() && s.size > BUNDLE_MAX) big.add(rel)
1978
2189
  return s.isFile() && s.size <= BUNDLE_MAX ? fs.readFileSync(f) : null
1979
2190
  }
1980
2191
  const strictOf = (page) => library.strictHtml(page) || market.strictHtml(page) || (v > 0 && library.strictVersions(root))
1981
- const pack = buildPack({ ...params, read, strictOf })
2192
+ const libFont = (id) => {
2193
+ const f = studio.fonts && studio.fonts.index.fonts.find((x) => x.id === id)
2194
+ const p = f && studio.fonts.cached(id)
2195
+ return p ? { family: f.family, weights: f.weights, data: fs.readFileSync(p) } : null
2196
+ }
2197
+ const pack = buildPack({ ...params, read, bigOf: (rel) => big.has(rel), strictOf, libFont })
1982
2198
  return { pack, deps, files: [...files] }
1983
2199
  }
1984
2200
 
@@ -2010,7 +2226,7 @@ export function apply(ctx) {
2010
2226
  const ai = new Set([...deps].filter((x) => isPhotoAsset(x)).map((x) => path.basename(x)))
2011
2227
  try {
2012
2228
  const file = writeExport(session, body.name, 'html', Buffer.from(pack.html, 'utf8'))
2013
- json(res, 200, { path: file, count: pack.count, missing: pack.missing, ai: ai.size, bytes: pack.html.length })
2229
+ json(res, 200, { path: file, count: pack.count, missing: pack.missing, skipped: pack.skipped.slice(0, 20), skippedN: pack.skipped.length, ai: ai.size, bytes: pack.html.length })
2014
2230
  } catch (e) {
2015
2231
  json(res, 500, { error: e.message })
2016
2232
  }
@@ -2168,7 +2384,7 @@ export function apply(ctx) {
2168
2384
  })
2169
2385
  const mk = createMarketRoutes({ admit, readBody, json, tracker, library, market, open, systemsDir: SYSTEMS_DIR, log, sessionCwd })
2170
2386
 
2171
- const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, verthumb: canvasThumbs.verRoute, 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, hidden: hiddenRoute, edit: editRoute, style: styleRoute, sharecheck: shareCheckRoute, drift: driftRoute, states: statesRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, htmlpack: htmlPackRoute, pubshare: pubShareRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute, impl: implRoute, implcmp: implCmpRoute, implshot: implShotRoute }
2387
+ const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, verthumb: canvasThumbs.verRoute, 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, hidden: hiddenRoute, edit: editRoute, style: styleRoute, sharecheck: shareCheckRoute, drift: driftRoute, states: statesRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, htmlpack: htmlPackRoute, pubshare: pubShareRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, fonts: fontsRoute, mocksave: mockSaveRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute, impl: implRoute, implcmp: implCmpRoute, implshot: implShotRoute }
2172
2388
  for (const [key, handler] of Object.entries(routes)) {
2173
2389
  ctx.effect(() => ctx.webServer.register({
2174
2390
  kind: 'exact',
package/lib/look.js CHANGED
@@ -420,7 +420,7 @@ export async function cropIssues(browser, rows, { screens, dark, kind = '', max
420
420
  const TYPE = {
421
421
  hscroll: '超出屏幕', clipped: '文字被截断', overflow: '文字超出框', overlap: '文字叠在一起', contrast: '对比度不够', tap: '点击区太小',
422
422
  tiny: '字太小', img: '图片没加载出来', fonts: '字号太杂', distort: '图片被拉变形', long: '一行太长', wrap: '文字被挤断行',
423
- covered: '被固定栏压住', tight: '离固定栏太近', jserr: '页面脚本报错', missing: '文件没载出来', deadlink: '跳到的页面不存在',
423
+ covered: '被固定栏压住', tight: '离固定栏太近', jserr: '页面脚本报错', missing: '文件没载出来', deadlink: '跳到的页面不存在', mockmiss: '模拟数据里没有这个字段',
424
424
  capsule: '被小程序胶囊挡住', island: '被灵动岛挡住', homebar: '伸进底部横条区', tabbar: '标签栏项太多', navbar: '没有导航栏',
425
425
  winctl: '被窗口按钮挡住', dgsize: '图比画幅大', dgli: '导图节点写法不对', dgmany: '一层放太多', dgbar: '横条超出时间轴', dgtext: '节点字太多', dgsmall: '字偏小', dglink: '箭头没对着模块', frame: '外框被改动',
426
426
  }
@@ -474,6 +474,7 @@ export function detailOf(it) {
474
474
  : `伸进左上角红绿灯 ${it.px}px(外框画的、盖在页面上面,在 x 20–72、y 20–32:工具栏 / 侧栏顶上左边空出 80px,标题、按钮从 x 80 以后放)`
475
475
  case 'jserr': return `${it.msg}${it.src ? `(${it.src}${it.line ? `:${it.line}` : ''})` : ''}`
476
476
  case 'missing': return `${WHAT[it.what] || '文件'} ${it.src} 载不出来(路径写错了,或者文件不在)`
477
+ case 'mockmiss': return `用到了 ${it.paths},mock.json 里没有(显示出来是空的):拼错了就改对,漏写了就补进 mock.json`
477
478
  case 'frame': {
478
479
  const dsh = /^dsh\//.test(String(it.frame || ''))
479
480
  const from = dsh ? '技能目录 frames/dsh/' : '外框库(~/.dsh/design-frames/)'