dsh-design-studio 1.2.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
@@ -73,7 +73,8 @@ 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'
@@ -109,7 +110,7 @@ const SKILL_RANK = 600 // 和 DSH 自带的技能同一档;用户 / 项目里
109
110
  * 几行之间靠这个互通(同一个包里的模块 Node 只加载一次):工作台起来后放 tracker、无头浏览器(browser);
110
111
  * 「自动打开预览」那行开着时 autoOpen > 0
111
112
  */
112
- 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: () => {} }
113
114
 
114
115
  /** 设计技能:模型做界面设计时加载(DSH 的 skill 工具),也能让用户手动调 */
115
116
  export const designSkill = {
@@ -346,7 +347,7 @@ export const checkTool = {
346
347
  if (want.more) text += `\n尺寸太多,只量了前 ${MAX_SIZES} 种`
347
348
  if (ex.skipped) text += `\n状态太多,有 ${ex.skipped} 个状态没量:screens 写成 order.html?state=状态名 单量那个状态`
348
349
  text += stateMisses(pick0.list, stOf, sn.only, '量的是这屏全部状态')
349
- text += tweakNotes(id) + annotationNotes(anAt, rows) + driftNotes(id)
350
+ text += tweakNotes(id) + fontNotes(id) + annotationNotes(anAt, rows) + driftNotes(id)
350
351
  return kept && kept.images ? { text, images: kept.images } : { text }
351
352
  }
352
353
  studio.log(new Error(`check_design 无头浏览器没量成:${rows[0] && rows[0].error}`))
@@ -360,7 +361,7 @@ export const checkTool = {
360
361
  const note = want.sizes.length || a.dark ? '(这台电脑上没找到能用的 Chrome / Edge,没法按指定尺寸 / 深色量;下面是右侧栏按它现在显示的尺寸量的)\n' : ''
361
362
  if (!r) return { text: '右侧栏「设计工作台」现在没开着,量不了。照 ui-design 技能里的「自查」清单自己过一遍。' }
362
363
  if (!r.error && !r.measured) return { text: '右侧栏开着,但预览页面没回应,这次没量成(可能还在加载)。过一会儿再调一次,或照 ui-design 技能里的「自查」清单自己过一遍。' }
363
- 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)) }
364
365
  },
365
366
  }
366
367
 
@@ -395,6 +396,16 @@ function annotationNotes(at, rows) {
395
396
  return list.length ? `\n\n业务标注(annotations.json):\n${list.map((x) => `- ${x}`).join('\n')}` : ''
396
397
  }
397
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
+
398
409
  /** 调节滑块(tweaks.json)有没有真接上:check_design 末尾附上 */
399
410
  function tweakNotes(id) {
400
411
  let list = []
@@ -729,6 +740,110 @@ export const photoTool = {
729
740
  },
730
741
  }
731
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
+
732
847
  /** pick_style 工具:用户没定风格时按题材挑一张风格卡(模型自己定,消费类题目总落回米色暖调;给了具体配色它照做得很好) */
733
848
  export const styleTool = {
734
849
  name: 'pick_style',
@@ -984,6 +1099,7 @@ export function apply(ctx) {
984
1099
  history,
985
1100
  drafts,
986
1101
  skipAnnots: () => studio.annotations > 0, // 业务标注开着时这个文件只给右侧栏看,改了不刷新页面
1102
+ fontFile: (id) => (studio.fonts ? studio.fonts.cached(id) : null), // 字体库(#31):面板里试字体时页面从这里拿(还没存进设计)
987
1103
  strict: { html: (buf) => library.strictHtml(buf) || market.strictHtml(buf), root: (dir) => library.strictRoot(dir) || market.isStaging(dir), versions: (dir) => library.strictVersions(dir) },
988
1104
  // 桌面版的 dsh-app://app 是默认就认的;这里补上 DSH 网页端的地址,和 DSH 配置里声明的对外地址(反向代理 / 域名)
989
1105
  parents: () => {
@@ -1035,6 +1151,9 @@ export function apply(ctx) {
1035
1151
  const photoIndex = loadPhotoIndex()
1036
1152
  const photos = photoIndex ? createPhotos({ market, index: photoIndex, log }) : null
1037
1153
  studio.photos = photos
1154
+ const fontIndex = loadFontIndex()
1155
+ const fonts = fontIndex ? createFonts({ market, index: fontIndex, log }) : null
1156
+ studio.fonts = fonts
1038
1157
  studio.sessionCwd = sessionCwd
1039
1158
  studio.impl = implStore
1040
1159
  studio.openPreview = open
@@ -1044,6 +1163,7 @@ export function apply(ctx) {
1044
1163
  if (studio.tracker === tracker) { studio.tracker = null; studio.log = () => {} }
1045
1164
  if (studio.market === market) { market.abort(); studio.market = null }
1046
1165
  if (studio.photos === photos) studio.photos = null
1166
+ if (studio.fonts === fonts) studio.fonts = null
1047
1167
  if (studio.sessionCwd === sessionCwd) studio.sessionCwd = null
1048
1168
  }
1049
1169
  }, 'dsh-design-studio: tracker')
@@ -1177,13 +1297,67 @@ export function apply(ctx) {
1177
1297
  const values = body.values && typeof body.values === 'object' && !Array.isArray(body.values) ? body.values : {}
1178
1298
  try {
1179
1299
  const vars = body.vars && typeof body.vars === 'object' && !Array.isArray(body.vars) ? body.vars : null
1180
- 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)
1181
1329
  json(res, 200, r)
1182
1330
  } catch (e) {
1183
1331
  json(res, 500, { error: e.message })
1184
1332
  }
1185
1333
  }
1186
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
+
1187
1361
  /** 「数据」面板的「存成初始数据」(#30):POST { session, root, data, fp } → 写回 mock.json(记一版、告诉模型用户改了) */
1188
1362
  async function mockSaveRoute(req, res) {
1189
1363
  if (!admit(req, res)) return
@@ -1667,6 +1841,8 @@ export function apply(ctx) {
1667
1841
  const hit = resolveInRoot(root, '/' + rel.split('/').map(encodeURIComponent).join('/'))
1668
1842
  f = hit && hit.real ? hit.real : ''
1669
1843
  }
1844
+ // 字体库(#31):dsh-fonts/<库 id>.woff2 不进版本记录、也可能被手动删了,从字体库缓存拿(和 serve.js 历史预览一样)
1845
+ if (!f && studio.fonts && libFontIdOf(rel)) f = studio.fonts.cached(libFontIdOf(rel)) || ''
1670
1846
  return f
1671
1847
  }
1672
1848
 
@@ -1990,7 +2166,8 @@ export function apply(ctx) {
1990
2166
  os: body.os === 'win' ? 'win' : '',
1991
2167
  dark: body.dark === true,
1992
2168
  scheme: body.scheme === 'dark' ? 'dark' : 'light',
1993
- 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,
1994
2171
  title: String(body.title || '').slice(0, 120),
1995
2172
  lang: body.lang === 'en' ? 'en' : 'zh',
1996
2173
  fit: body.fit === true,
@@ -2012,7 +2189,12 @@ export function apply(ctx) {
2012
2189
  return s.isFile() && s.size <= BUNDLE_MAX ? fs.readFileSync(f) : null
2013
2190
  }
2014
2191
  const strictOf = (page) => library.strictHtml(page) || market.strictHtml(page) || (v > 0 && library.strictVersions(root))
2015
- const pack = buildPack({ ...params, read, bigOf: (rel) => big.has(rel), 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 })
2016
2198
  return { pack, deps, files: [...files] }
2017
2199
  }
2018
2200
 
@@ -2044,7 +2226,7 @@ export function apply(ctx) {
2044
2226
  const ai = new Set([...deps].filter((x) => isPhotoAsset(x)).map((x) => path.basename(x)))
2045
2227
  try {
2046
2228
  const file = writeExport(session, body.name, 'html', Buffer.from(pack.html, 'utf8'))
2047
- 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 })
2048
2230
  } catch (e) {
2049
2231
  json(res, 500, { error: e.message })
2050
2232
  }
@@ -2202,7 +2384,7 @@ export function apply(ctx) {
2202
2384
  })
2203
2385
  const mk = createMarketRoutes({ admit, readBody, json, tracker, library, market, open, systemsDir: SYSTEMS_DIR, log, sessionCwd })
2204
2386
 
2205
- 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, mocksave: mockSaveRoute, 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 }
2206
2388
  for (const [key, handler] of Object.entries(routes)) {
2207
2389
  ctx.effect(() => ctx.webServer.register({
2208
2390
  kind: 'exact',
package/lib/picker.js CHANGED
@@ -1344,10 +1344,35 @@
1344
1344
  // ── 设计变量::root / html 上的 CSS 自定义属性(取算出来的值),带出处样式表 ─────
1345
1345
  const MAX_TOKENS = 80
1346
1346
 
1347
+ /** 页面样式表里 @font-face 声明过的字体名(小写;面板试字体时插进去的不算) */
1348
+ function fontFaces() {
1349
+ const out = new Set()
1350
+ const scan = (rules, depth) => {
1351
+ for (const r of rules) {
1352
+ if (r.type === 5 && r.style) out.add(r.style.getPropertyValue('font-family').trim().replace(/^["']|["']$/g, '').toLowerCase())
1353
+ else if (depth < 4 && r.styleSheet) { try { scan(r.styleSheet.cssRules, depth + 1) } catch { /* 别的源 */ } }
1354
+ else if (depth < 4 && r.cssRules) scan(r.cssRules, depth + 1)
1355
+ }
1356
+ }
1357
+ for (const sheet of document.styleSheets) {
1358
+ if (sheet.ownerNode && sheet.ownerNode.getAttribute && sheet.ownerNode.getAttribute('data-dsh-design')) continue
1359
+ try { scan(sheet.cssRules, 0) } catch { /* 别的源的样式表读不了 */ }
1360
+ }
1361
+ return out
1362
+ }
1363
+
1347
1364
  function tokensOf() {
1348
1365
  const out = []
1349
1366
  const seen = new Set()
1350
1367
  const cs = getComputedStyle(document.documentElement)
1368
+ let faces = null
1369
+ // 字体变量:打头的字体有没有 @font-face(外观面板据此判断选字体库的同名字体要不要存)
1370
+ const face = (value) => {
1371
+ const m = /^\s*(?:"([^"]+)"|'([^']+)')/.exec(value)
1372
+ if (!m) return false
1373
+ if (!faces) faces = fontFaces()
1374
+ return faces.has((m[1] || m[2]).trim().toLowerCase())
1375
+ }
1351
1376
  for (const sheet of document.styleSheets) {
1352
1377
  let rules
1353
1378
  try { rules = sheet.cssRules } catch { continue } // 别的源的样式表读不了
@@ -1360,7 +1385,7 @@
1360
1385
  if (!name.startsWith('--') || seen.has(name)) continue
1361
1386
  seen.add(name)
1362
1387
  const value = (cs.getPropertyValue(name) || r.style.getPropertyValue(name)).trim()
1363
- if (value) out.push({ name, value: clip(value, 160), href })
1388
+ if (value) out.push({ name, value: clip(value, 160), href, ...(/^\s*["']/.test(value) && face(value) ? { face: true } : null) })
1364
1389
  }
1365
1390
  }
1366
1391
  }
@@ -5586,7 +5611,25 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
5586
5611
  // 属性直接改 <html> 上的;原来的行内值(连同优先级)、属性值都记着,撤掉时原样还原。不动文件
5587
5612
  const tweakVars = new Map() // 变量 → 原来的行内值 { v, p }(v 为空 = 原来没有)
5588
5613
  const tweakAttrs = new Map() // 属性 → 原来的值(null = 原来没有)
5589
- function applyTweak(vars, attrs) {
5614
+ // 字体库(#31):面板里试字体库的字体时(还没存进设计),@font-face 从预览服务器拿,放在这个 <style> 里
5615
+ let tweakFonts = null
5616
+ function applyTweakFonts(list) {
5617
+ const ok = (Array.isArray(list) ? list : []).filter((f) => f && /^[A-Za-z0-9 ]{1,40}$/.test(f.family) && /^[a-z0-9]+(-[a-z0-9]+)*$/.test(f.id)).slice(0, 8)
5618
+ const css = ok.map((f) => {
5619
+ const w = Array.isArray(f.weights) && f.weights.length === 2 && f.weights.every((x) => Number.isFinite(x)) ? `${f.weights[0]} ${f.weights[1]}` : '100 900'
5620
+ return `@font-face{font-family:"${f.family}";src:url("/__dsh_design__/font/${f.id}.woff2") format("woff2");font-weight:${w};font-display:swap}`
5621
+ }).join('\n')
5622
+ if (!css) { if (tweakFonts) { tweakFonts.remove(); tweakFonts = null } return }
5623
+ if (!tweakFonts) {
5624
+ tweakFonts = document.createElement('style')
5625
+ tweakFonts.setAttribute('data-dsh-design', 'fonts')
5626
+ ;(document.head || document.documentElement).appendChild(tweakFonts)
5627
+ }
5628
+ if (tweakFonts.textContent !== css) tweakFonts.textContent = css
5629
+ }
5630
+
5631
+ function applyTweak(vars, attrs, fonts) {
5632
+ applyTweakFonts(fonts)
5590
5633
  const de = document.documentElement
5591
5634
  const nv = vars && typeof vars === 'object' ? vars : {}
5592
5635
  const na = attrs && typeof attrs === 'object' ? attrs : {}
@@ -5597,7 +5640,7 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
5597
5640
  tweakVars.delete(k)
5598
5641
  }
5599
5642
  for (const [k, v] of Object.entries(nv)) {
5600
- if (!/^--[\w-]{1,60}$/.test(k) || v == null || String(v).length > 80) continue
5643
+ if (!/^--[\w-]{1,60}$/.test(k) || v == null || String(v).length > 200) continue
5601
5644
  if (!tweakVars.has(k)) tweakVars.set(k, { v: de.style.getPropertyValue(k), p: de.style.getPropertyPriority(k) })
5602
5645
  de.style.setProperty(k, String(v), 'important')
5603
5646
  }
@@ -5778,7 +5821,7 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
5778
5821
  else if (d.type === 'styleMode') setStyleMode(!!d.on)
5779
5822
  else if (d.type === 'styleSel') onStyleSel(d.selector)
5780
5823
  else if (d.type === 'style') { styleApply(d.css); queueTop() }
5781
- else if (d.type === 'tweak') { applyTweak(d.vars, d.attrs); queueTop() }
5824
+ else if (d.type === 'tweak') { applyTweak(d.vars, d.attrs, d.fonts); queueTop() }
5782
5825
  else if (d.type === 'sync') setSync(!!d.on, !!d.slot)
5783
5826
  else if (d.type === 'scrollTo') syncTo(d.x, d.y)
5784
5827
  })
package/lib/serve.js CHANGED
@@ -22,6 +22,7 @@ import { tokenize } from './gallery/html.js'
22
22
  import { FRAME_MAIN, SLOT_BOX } from './slot.js'
23
23
  import { STATE_RE, statesOfHtml } from './states.js'
24
24
  import { MOCK_FILE, MOCK_MAX, mockOf, mockScript, mockBridge, parseMock } from './mock.js'
25
+ import { libFontIdOf } from './fonts.js'
25
26
 
26
27
  export const INTERNAL = '/__dsh_design__/'
27
28
  const PICKER_FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), 'picker.js')
@@ -326,7 +327,7 @@ export function draftInjector(tag) {
326
327
  }
327
328
  }
328
329
 
329
- export function createHub({ log = () => {}, onChange = () => {}, onWatch = () => {}, onUnwatch = () => {}, history = null, parents = () => [], strict = null, drafts = null, skipAnnots = () => false } = {}) {
330
+ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () => {}, onUnwatch = () => {}, history = null, parents = () => [], strict = null, drafts = null, skipAnnots = () => false, fontFile = () => null } = {}) {
330
331
  const strictHtml = (buf) => { try { return !!(strict && strict.html && strict.html(buf)) } catch (e) { log(e); return true } }
331
332
  const strictRoot = (dir) => { try { return !!(strict && strict.root && strict.root(dir)) } catch (e) { log(e); return true } }
332
333
  const strictVer = (dir) => { try { return !!(strict && strict.versions && strict.versions(dir)) } catch (e) { log(e); return true } }
@@ -484,6 +485,19 @@ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () =>
484
485
  if (file && !inRoot(entry.root, file)) return send(res, 403, 'forbidden')
485
486
  }
486
487
  }
488
+ // 字体库的字体(#31):dsh-fonts/<库 id>.woff2 不在了(复制设计时漏了、手动删了),从字体库缓存给,和导出、历史预览一样
489
+ if (!file) {
490
+ const fm = /(?:^|\/)(dsh-fonts\/[a-z0-9-]+\.woff2)$/.exec(String(pathname))
491
+ const id = fm && libFontIdOf(fm[1])
492
+ if (id) { try { file = fontFile(id) } catch (e) { log(e) } }
493
+ if (file) {
494
+ return fs.readFile(file, (err, buf) => {
495
+ if (err) return send(res, 404, 'no such font')
496
+ res.writeHead(200, { 'Content-Type': 'font/woff2', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' })
497
+ res.end(req.method === 'HEAD' ? undefined : buf)
498
+ })
499
+ }
500
+ }
487
501
  if (!file) {
488
502
  const html = errorPage('找不到这个文件', String(pathname).replace(/[<>&]/g, ''), false, 'missing')
489
503
  return send(res, 404, html, { 'Content-Type': 'text/html; charset=utf-8' })
@@ -506,6 +520,23 @@ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () =>
506
520
  stream.pipe(res)
507
521
  }
508
522
 
523
+ /**
524
+ * 字体库的字体(#31):/__dsh_design__/font/<id>.woff2,面板里试字体、还没存进设计时页面从这里拿。
525
+ * 只给目录里列着、已经下载好的(fontFile 管);同源用,别的源拿不走
526
+ */
527
+ function libFont(req, res, pathname) {
528
+ if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, 'method not allowed')
529
+ const m = /^\/__dsh_design__\/font\/([a-z0-9]+(?:-[a-z0-9]+)*)\.woff2$/.exec(pathname)
530
+ let file = null
531
+ try { file = m ? fontFile(m[1]) : null } catch (e) { log(e) }
532
+ if (!file) return send(res, 404, 'no such font')
533
+ fs.readFile(file, (err, buf) => {
534
+ if (err) return send(res, 404, 'no such font')
535
+ res.writeHead(200, { 'Content-Type': 'font/woff2', 'Cache-Control': 'max-age=3600', 'Cross-Origin-Resource-Policy': 'same-origin', 'X-Content-Type-Options': 'nosniff' })
536
+ res.end(req.method === 'HEAD' ? undefined : buf)
537
+ })
538
+ }
539
+
509
540
  /** 旧版本那时候的 mock.json(那一版没有就没有) */
510
541
  function versionMock(root, v) {
511
542
  try {
@@ -522,7 +553,9 @@ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () =>
522
553
  const m = /^\/__dsh_design__\/v\/(\d+)\/(.*)$/.exec(pathname)
523
554
  let rel = ''
524
555
  try { rel = m ? decodeURIComponent(m[2]) : '' } catch { rel = '' }
525
- const file = m && history && !rel.split('/').includes('..') ? history.fileOf(entry.root, Number(m[1]), rel) : null
556
+ let file = m && history && !rel.split('/').includes('..') ? history.fileOf(entry.root, Number(m[1]), rel) : null
557
+ // 字体库的字体不进版本记录(#31):旧版本要的从字体库缓存拿(目录里列着、下载好了的才给)
558
+ if (!file && m && libFontIdOf(rel)) { try { file = fontFile(libFontIdOf(rel)) } catch (e) { log(e) } }
526
559
  if (!file) return send(res, 404, 'no such version file')
527
560
  const ext = path.extname(rel || 'index.html').toLowerCase()
528
561
  const type = MIME[ext] || 'application/octet-stream'
@@ -731,6 +764,7 @@ export function createHub({ log = () => {}, onChange = () => {}, onWatch = () =>
731
764
  if (pathname === INTERNAL + 'picker.js') return picker(res, entry)
732
765
  if (pathname === INTERNAL + 'draft.js') return draftJs(res)
733
766
  if (pathname === INTERNAL + 'mock.html') return mockPage(req, res, entry)
767
+ if (pathname.startsWith(INTERNAL + 'font/')) return libFont(req, res, pathname)
734
768
  // 草稿就挂在这一屏自己的地址上(/menu.html?__ddp_draft=…),页面里的相对地址(tokens.css、图片)照常对得上
735
769
  if (entry.kind === 'file' && /[?&]__ddp_draft=/.test(req.url)) return serveDraft(req, res, entry, pathname)
736
770
  if (pathname === INTERNAL + 'events') {
package/lib/tool.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * dsh-design-studio/tool:把 preview_page、check_design、look_design、extract_design_system、handoff_design、compare_design、find_photos、pick_style、save_frame 挂给模型。
2
+ * dsh-design-studio/tool:把 preview_page、check_design、look_design、extract_design_system、handoff_design、compare_design、find_photos、use_fonts、pick_style、save_frame 挂给模型。
3
3
  * 放在 bundle 顶层 → 所有模式都能用;放进设计模式 → 只挂在那个模式里。工具本身见 index.js
4
4
  */
5
- import { previewTool, checkTool, lookTool, systemTool, handoffTool, compareTool, photoTool, styleTool, frameTool } from './index.js'
5
+ import { previewTool, checkTool, lookTool, systemTool, handoffTool, compareTool, photoTool, fontTool, styleTool, frameTool } from './index.js'
6
6
 
7
7
  export const name = 'dsh-design-studio-tool'
8
8
  export const inject = ['tools']
@@ -16,6 +16,7 @@ export function apply(ctx) {
16
16
  ctx.tools.register({ ...handoffTool, execute: (args, exec) => handoffTool.execute(args, exec, ctx) })
17
17
  ctx.tools.register({ ...compareTool, execute: (args, exec) => compareTool.execute(args, exec, ctx) })
18
18
  ctx.tools.register({ ...photoTool })
19
+ ctx.tools.register({ ...fontTool })
19
20
  ctx.tools.register({ ...styleTool })
20
21
  ctx.tools.register({ ...frameTool, execute: (args, exec) => frameTool.execute(args, exec, ctx) })
21
22
  }