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/README.en.md +2 -0
- package/README.md +2 -0
- package/lib/browser.js +4 -1
- package/lib/bundle.js +65 -15
- package/lib/client.js +519 -26
- package/lib/core.js +7 -0
- package/lib/fonts-index.json +320 -0
- package/lib/fonts-preview.json +1 -0
- package/lib/fonts.js +352 -0
- package/lib/gallery/pack.js +11 -2
- package/lib/handoff.js +44 -0
- package/lib/history.js +2 -0
- package/lib/htmlpack.js +85 -19
- package/lib/index.js +227 -11
- package/lib/look.js +2 -1
- package/lib/mock.js +793 -0
- package/lib/picker.js +68 -9
- package/lib/serve.js +70 -11
- package/lib/states.js +11 -1
- package/lib/tool.js +3 -2
- package/lib/tweaks.js +135 -4
- package/package.json +1 -1
- package/skills/ui-design/SKILL.md +18 -1
package/lib/fonts.js
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 字体库(issue #31):免费可商用(SIL OFL 1.1)的网页字体。面板里点选、模型调 use_fonts,字体文件复制进设计目录的 dsh-fonts/
|
|
3
|
+
* (设计台专用的文件夹:不和设计自己放字体的 fonts/ 撞名),变量所在的样式里加一段设计台管的 @font-face。
|
|
4
|
+
*
|
|
5
|
+
* - 目录 fonts-index.json 随插件发(名字、分类、sha256),预览 fonts-preview.json 是名字画成的 SVG 路径(图形,不是字体)。
|
|
6
|
+
* - 字体在 npm 包 dsh-design-fonts 里,第一次用到才下载;每个文件按目录里钉死的 sha256 核对。「设计库不联网」开着就不下载。
|
|
7
|
+
* - @font-face 那段只认明确选过的(面板「存下」、use_fonts):开头标记里记着 id。旧设计的字体栈里本来就写着 "Noto Serif SC"
|
|
8
|
+
* 这类当系统字体的后备,不能因为名字对上就去下载、复制、改样子。
|
|
9
|
+
* - 那段里的只在「这次操作把它换走了、整套设计里一处都不再写它的名字」时去掉(drop);别的时候只加不减。
|
|
10
|
+
*/
|
|
11
|
+
import crypto from 'node:crypto'
|
|
12
|
+
import fs from 'node:fs'
|
|
13
|
+
import os from 'node:os'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import { fileURLToPath } from 'node:url'
|
|
16
|
+
|
|
17
|
+
export const FONTS_CACHE = process.env.DSH_DESIGN_FONTS_CACHE || path.join(os.homedir(), '.dsh', 'cache', 'dsh-design-studio', 'fonts')
|
|
18
|
+
export const FONT_DIR = 'dsh-fonts'
|
|
19
|
+
export const MAX_FONTS = 4 // use_fonts 一次最多几款
|
|
20
|
+
const INDEX_FILE = fileURLToPath(new URL('./fonts-index.json', import.meta.url))
|
|
21
|
+
const PREVIEW_FILE = fileURLToPath(new URL('./fonts-preview.json', import.meta.url))
|
|
22
|
+
const ID_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/
|
|
23
|
+
const CAP = 30 * 1024 * 1024
|
|
24
|
+
const LIMITS = { files: 100, file: 6 * 1024 * 1024, total: 40 * 1024 * 1024 }
|
|
25
|
+
const RETRY_MS = 60e3
|
|
26
|
+
const TIMING = { stagger: 8000, each: 60000, total: 120000 }
|
|
27
|
+
const CATS = new Set(['sans', 'serif', 'display', 'hand', 'mono'])
|
|
28
|
+
|
|
29
|
+
const sha256 = (b) => crypto.createHash('sha256').update(b).digest('hex')
|
|
30
|
+
// 版本号比大小(和 gallery/market.js 的 vcmp 一样;这里不引它,版本记录也要用这个文件,免得绕成环)
|
|
31
|
+
const vcmp = (a, b) => {
|
|
32
|
+
const pa = String(a || '0').split(/[.+-]/).slice(0, 3).map((n) => parseInt(n, 10) || 0)
|
|
33
|
+
const pb = String(b || '0').split(/[.+-]/).slice(0, 3).map((n) => parseInt(n, 10) || 0)
|
|
34
|
+
for (let i = 0; i < 3; i++) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) > (pb[i] || 0) ? 1 : -1
|
|
35
|
+
return 0
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 每类后面跟的系统字体:字体库只裁了常用字,不在里面的字、没下载到时由它们顶上(Mac / Windows 成对写) */
|
|
39
|
+
export const FALLBACK = {
|
|
40
|
+
sans: '"PingFang SC", "Microsoft YaHei", system-ui, sans-serif',
|
|
41
|
+
serif: '"Songti SC", "SimSun", serif',
|
|
42
|
+
display: '"PingFang SC", "Microsoft YaHei", system-ui, sans-serif',
|
|
43
|
+
hand: '"Kaiti SC", "KaiTi", serif',
|
|
44
|
+
mono: 'Menlo, Consolas, "PingFang SC", "Microsoft YaHei", monospace',
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 读目录;格式不对的条目不要 */
|
|
48
|
+
export function loadFontIndex(file = INDEX_FILE) {
|
|
49
|
+
let raw
|
|
50
|
+
try { raw = JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
|
|
51
|
+
if (!raw || raw.format !== 1 || typeof raw.package !== 'string' || typeof raw.version !== 'string' || !Array.isArray(raw.fonts)) return null
|
|
52
|
+
const fonts = raw.fonts.filter((f) => f && ID_RE.test(String(f.id)) && /^[0-9a-f]{64}$/.test(String(f.sha256)) && f.size > 0 && CATS.has(f.cat) &&
|
|
53
|
+
typeof f.family === 'string' && /^[A-Za-z0-9 ]{1,40}$/.test(f.family) && f.file === `fonts/${f.id}.woff2`)
|
|
54
|
+
return { ...raw, fonts }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 预览:{ id: { w, h, d } }(d 是 SVG 路径,字体单位、y 向下) */
|
|
58
|
+
export function loadFontPreviews(file = PREVIEW_FILE) {
|
|
59
|
+
try {
|
|
60
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
61
|
+
return raw && typeof raw === 'object' ? raw : {}
|
|
62
|
+
} catch { return {} }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const stackOf = (f) => `"${f.family}", ${FALLBACK[f.cat] || FALLBACK.sans}`
|
|
66
|
+
|
|
67
|
+
const norm = (s) => String(s || '').normalize('NFKC').toLowerCase().replace(/["'\s_-]+/g, '')
|
|
68
|
+
|
|
69
|
+
/** 字体栈里的第一个名字(去引号) */
|
|
70
|
+
export function firstFamily(stack) {
|
|
71
|
+
const m = /^\s*(?:"([^"]*)"|'([^']*)'|([^,]*))/.exec(String(stack || ''))
|
|
72
|
+
return m ? (m[1] ?? m[2] ?? m[3] ?? '').trim() : ''
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 字体栈打头的是不是字体库里的(是就给那款) */
|
|
76
|
+
export function libFontOf(index, stack) {
|
|
77
|
+
if (!index) return null
|
|
78
|
+
const fam = firstFamily(stack).toLowerCase()
|
|
79
|
+
return (fam && index.fonts.find((f) => f.family.toLowerCase() === fam)) || null
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 按名字找:id、CSS 名、中文名、英文名都认(大小写、空格、引号不计) */
|
|
83
|
+
export function findFont(index, name) {
|
|
84
|
+
const n = norm(name)
|
|
85
|
+
if (!index || !n) return null
|
|
86
|
+
return index.fonts.find((f) => [f.id, f.family, f.zh, f.en].some((x) => norm(x) === n)) || null
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ── 设计台管的 @font-face 那段 ──────────────────────────────────────────────
|
|
90
|
+
// /* dsh-fonts: noto-serif-sc inter | 设计台字体库 …(这段由设计台管,别手改)*/ … /* /dsh-fonts */
|
|
91
|
+
|
|
92
|
+
const BLOCK_RE = /\/\*\s*dsh-fonts:([^*]*?)\|[^*]*\*\/[\s\S]*?\/\*\s*\/dsh-fonts\s*\*\/[ \t]*(?:\r?\n)?/g
|
|
93
|
+
const BLOCK_HEAD_RE = /\/\*\s*dsh-fonts:([^*|]*)\|/
|
|
94
|
+
|
|
95
|
+
/** 文件里那段记着的 id(没有那段给 []) */
|
|
96
|
+
export function fontBlockIds(text) {
|
|
97
|
+
const m = BLOCK_HEAD_RE.exec(String(text || ''))
|
|
98
|
+
return m ? [...new Set(m[1].trim().split(/\s+/).filter((x) => ID_RE.test(x)))] : []
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 去掉那段(分享包、版本比较用) */
|
|
102
|
+
export const stripFontBlock = (text) => String(text).replace(BLOCK_RE, '')
|
|
103
|
+
|
|
104
|
+
/** 那段的文字:prefix 是这个文件到 fonts/ 的相对路径(「fonts」「../fonts」),nl 用文件自己的换行 */
|
|
105
|
+
export function fontBlock(fonts, prefix = FONT_DIR, nl = '\n') {
|
|
106
|
+
if (!fonts.length) return ''
|
|
107
|
+
const lines = [`/* dsh-fonts: ${fonts.map((f) => f.id).join(' ')} | 设计台字体库(SIL OFL 1.1,免费可商用),文件在 ${FONT_DIR}/。这段由设计台管,别手改 */`]
|
|
108
|
+
for (const f of fonts) {
|
|
109
|
+
// 只有一个字重的也写成 100 900:标题要 700、800 时浏览器就不会自己把它描粗(毛笔字、站酷那几款描粗了很难看)
|
|
110
|
+
const w = Array.isArray(f.weights) && f.weights.length === 2 ? `${f.weights[0]} ${f.weights[1]}` : '100 900'
|
|
111
|
+
lines.push(`@font-face { font-family: "${f.family}"; src: url("${prefix}/${f.id}.woff2") format("woff2"); font-weight: ${w}; font-display: swap; }`)
|
|
112
|
+
}
|
|
113
|
+
lines.push('/* /dsh-fonts */')
|
|
114
|
+
return lines.join(nl) + nl
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* CSS 文字里放那段的位置:开头的 BOM、注释、@charset、@layer 声明(不带大括号的)、@import 之后(@import 必须在最前面),接在那一行后面。
|
|
119
|
+
* @import 的网址可能不带引号、里面有 ;(Google Fonts css2 的 wght@400;700),url(…) 整个跳过
|
|
120
|
+
*/
|
|
121
|
+
function cssInsertAt(css) {
|
|
122
|
+
const re = /\s*(?:\/\*[\s\S]*?\*\/|@charset\b[^;]*;|@layer\b[^;{}]*;|@import\b(?:url\(\s*(?:"[^"]*"|'[^']*'|[^)"']*)\s*\)|"[^"]*"|'[^']*'|(?!url\()[^;'"])*;)/y
|
|
123
|
+
const bom = css.charCodeAt(0) === 0xfeff ? 1 : 0
|
|
124
|
+
let at = bom
|
|
125
|
+
for (;;) {
|
|
126
|
+
re.lastIndex = at
|
|
127
|
+
if (!re.exec(css)) break
|
|
128
|
+
at = re.lastIndex
|
|
129
|
+
}
|
|
130
|
+
if (at === bom) return bom
|
|
131
|
+
const nlAt = css.indexOf('\n', at)
|
|
132
|
+
return nlAt === -1 || css.slice(at, nlAt).trim() ? at : nlAt + 1
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const blank = (m) => m.replace(/[^\n]/g, ' ')
|
|
136
|
+
const STYLE_TAG = /<style\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi // 属性值里的 > 不算结束(media="(width >= 900px)")
|
|
137
|
+
const WRAP_ATTR = 'data-dsh-fonts' // 设计台自己加的那个 <style>(页面里没有对整个屏幕生效的 <style> 时)
|
|
138
|
+
|
|
139
|
+
/** HTML 里所有真的 <style> 开头标签(注释、脚本里的不算):[{ index, tag, screen: 对屏幕整个生效(没写 media、all、screen) }] */
|
|
140
|
+
function styleTags(html) {
|
|
141
|
+
// <noscript> 里的是关了脚本才用的备用样式,不算
|
|
142
|
+
const masked = html.replace(/<!--[\s\S]*?-->/g, blank).replace(/<(script|noscript)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, blank)
|
|
143
|
+
const out = []
|
|
144
|
+
STYLE_TAG.lastIndex = 0
|
|
145
|
+
for (let m; (m = STYLE_TAG.exec(masked));) {
|
|
146
|
+
const media = /\smedia\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(m[0])
|
|
147
|
+
const v = media ? (media[1] ?? media[2] ?? media[3]).trim().toLowerCase() : ''
|
|
148
|
+
out.push({ index: m.index, tag: m[0], screen: !v || v === 'all' || v === 'screen' })
|
|
149
|
+
}
|
|
150
|
+
return out
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
154
|
+
const famRes = new Map()
|
|
155
|
+
/** 文字里写没写这个字体名:带引号的,或者不带引号、前后是字体栈的分隔(var(--x, Inter)、style="font-family: Inter" 都算;Inter 不算 pointer、interface 里的) */
|
|
156
|
+
export function namesFamily(text, family) {
|
|
157
|
+
let re = famRes.get(family)
|
|
158
|
+
if (!re) {
|
|
159
|
+
const words = family.trim().split(/\s+/).map(escRe).join('\\s+')
|
|
160
|
+
re = new RegExp(`["']\\s*${words}\\s*["']|(?:^|[\\s,:(])${words}(?=\\s*(?:[,;!})"']|$))`, 'im')
|
|
161
|
+
famRes.set(family, re)
|
|
162
|
+
}
|
|
163
|
+
return re.test(String(text || ''))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 文字里(那段以外、注释以外)写着名字的字体库 id */
|
|
167
|
+
export function libIdsNamed(text, index) {
|
|
168
|
+
const rest = stripFontBlock(String(text || '')).replace(/\/\*[\s\S]*?\*\//g, ' ')
|
|
169
|
+
return index ? index.fonts.filter((f) => namesFamily(rest, f.family)).map((f) => f.id) : []
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* 那段改成:原来记着的 + add,再去掉 drop 里(这次被换走、整套设计都不再写它名字的)且这个文件里也不写它名字的。没变给 null
|
|
174
|
+
* isHtml:放进第一个对屏幕整个生效的 <style>;只有按尺寸 / 打印的 <style> 时在前面加一个设计台自己的;一个 <style> 都没有给 null(不自己加:只许外链样式的页面会悄悄拦掉)
|
|
175
|
+
*/
|
|
176
|
+
export function syncFontBlock(text, add, index, { prefix = FONT_DIR, isHtml = false, drop = [] } = {}) {
|
|
177
|
+
const src = String(text)
|
|
178
|
+
const cur = fontBlockIds(src)
|
|
179
|
+
const all = [...new Set([...cur, ...add])]
|
|
180
|
+
const named = new Set(drop.length ? libIdsNamed(src, index) : [])
|
|
181
|
+
const want = all.filter((id) => add.includes(id) || !drop.includes(id) || named.has(id))
|
|
182
|
+
const fonts = want.map((id) => index.fonts.find((f) => f.id === id)).filter(Boolean)
|
|
183
|
+
const nl = /\r\n/.test(src) ? '\r\n' : '\n'
|
|
184
|
+
const block = fontBlock(fonts, prefix, nl)
|
|
185
|
+
const had = BLOCK_RE.test(src)
|
|
186
|
+
BLOCK_RE.lastIndex = 0
|
|
187
|
+
let body = src.replace(BLOCK_RE, '')
|
|
188
|
+
// 设计台自己加的 <style> 空了就拿掉
|
|
189
|
+
if (isHtml) body = body.replace(new RegExp(`<style\\b[^>]*\\b${WRAP_ATTR}\\b[^>]*>\\s*</style\\s*>(?:\\r?\\n)?`, 'gi'), '')
|
|
190
|
+
let out
|
|
191
|
+
if (!block) out = body
|
|
192
|
+
else if (!isHtml) {
|
|
193
|
+
const at = cssInsertAt(body)
|
|
194
|
+
out = body.slice(0, at) + (at > 0 && !/[\n\ufeff]/.test(body[at - 1]) ? nl : '') + block + body.slice(at)
|
|
195
|
+
} else {
|
|
196
|
+
// @font-face 放在哪个 <style> 都对整页生效——前提是那个 <style> 对屏幕整个生效(media 限了尺寸、打印的,字体也跟着只在那时有)
|
|
197
|
+
const tags = styleTags(body)
|
|
198
|
+
const m = tags.find((x) => x.screen)
|
|
199
|
+
if (m) {
|
|
200
|
+
// <style> 里开头的 @import、@charset 要留在最前面(放到它们前面 @import 就不算了)
|
|
201
|
+
const start = m.index + m.tag.length
|
|
202
|
+
const close = body.slice(start).search(/<\/style\s*>/i)
|
|
203
|
+
const ins = cssInsertAt(body.slice(start, close < 0 ? body.length : start + close))
|
|
204
|
+
if (!ins) out = body.slice(0, start) + nl + block + body.slice(start).replace(/^\r?\n/, '')
|
|
205
|
+
else {
|
|
206
|
+
const at = start + ins
|
|
207
|
+
out = body.slice(0, at) + (body[at - 1] !== '\n' ? nl : '') + block + body.slice(at)
|
|
208
|
+
}
|
|
209
|
+
} else if (tags.length) {
|
|
210
|
+
// 只有按尺寸 / 打印的 <style>:在第一个前面自己加一个(带上页面 <style> 的 nonce,严格 CSP 也认)
|
|
211
|
+
const nonce = tags.map((x) => /\snonce\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(x.tag)).find(Boolean)
|
|
212
|
+
const attr = nonce ? ` nonce="${String(nonce[1] ?? nonce[2] ?? nonce[3]).replace(/["<>&]/g, '')}"` : ''
|
|
213
|
+
const at = tags[0].index
|
|
214
|
+
out = body.slice(0, at) + `<style ${WRAP_ATTR}${attr}>` + nl + block + '</style>' + nl + body.slice(at)
|
|
215
|
+
} else return null // 没有 <style>:不自己加(页面可能只许外链样式,加了会被悄悄拦掉)
|
|
216
|
+
}
|
|
217
|
+
if (out === src || (!had && !block)) return null
|
|
218
|
+
return out
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** 设计目录里的文件 rel 到 fonts/ 的相对路径 */
|
|
222
|
+
export const fontPrefix = (rel) => {
|
|
223
|
+
const d = path.posix.dirname(String(rel).replace(/\\/g, '/'))
|
|
224
|
+
return d === '.' ? FONT_DIR : path.posix.relative(d, FONT_DIR)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** dsh-fonts/<id>.woff2 是字体库复制进来的就给 id,不是给 ''(版本记录不存它们:从库里随时能再拿) */
|
|
228
|
+
export function libFontIdOf(rel, index = defaultIndex()) {
|
|
229
|
+
const m = /^dsh-fonts\/([a-z0-9-]+)\.woff2$/.exec(String(rel).replace(/\\/g, '/'))
|
|
230
|
+
return m && index && index.fonts.some((f) => f.id === m[1]) ? m[1] : ''
|
|
231
|
+
}
|
|
232
|
+
export const isLibFontRel = (rel, index) => !!libFontIdOf(rel, index)
|
|
233
|
+
|
|
234
|
+
let cachedIndex
|
|
235
|
+
function defaultIndex() {
|
|
236
|
+
if (cachedIndex === undefined) cachedIndex = loadFontIndex()
|
|
237
|
+
return cachedIndex
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ── 下载、复制 ───────────────────────────────────────────────────────────────
|
|
241
|
+
|
|
242
|
+
export function createFonts({ market, index = loadFontIndex(), cacheDir = FONTS_CACHE, log = () => {}, now = Date.now } = {}) {
|
|
243
|
+
let inflight = null
|
|
244
|
+
let failedAt = -Infinity
|
|
245
|
+
let lastErr = null
|
|
246
|
+
const dirOf = () => path.join(cacheDir, index.version)
|
|
247
|
+
const fileOf = (f) => path.join(dirOf(), `${f.id}.woff2`)
|
|
248
|
+
const okFile = (f) => {
|
|
249
|
+
try { return sha256(fs.readFileSync(fileOf(f))) === f.sha256 } catch { return false }
|
|
250
|
+
}
|
|
251
|
+
const has = (f) => { try { return fs.statSync(fileOf(f)).size === f.size } catch { return false } }
|
|
252
|
+
const ready = () => index.fonts.every(has)
|
|
253
|
+
|
|
254
|
+
async function download() {
|
|
255
|
+
const files = await market.fetchPackage(index.package, index.version, {
|
|
256
|
+
cap: CAP,
|
|
257
|
+
limits: LIMITS,
|
|
258
|
+
timing: TIMING,
|
|
259
|
+
check: (list) => {
|
|
260
|
+
const by = new Map(list.map((x) => [x.path, x.data]))
|
|
261
|
+
return index.fonts.map((f) => {
|
|
262
|
+
const data = by.get(f.file)
|
|
263
|
+
if (!data || sha256(data) !== f.sha256) { const e = new Error('font mismatch'); e.code = 'mismatch'; throw e }
|
|
264
|
+
return { f, data }
|
|
265
|
+
})
|
|
266
|
+
},
|
|
267
|
+
})
|
|
268
|
+
fs.mkdirSync(dirOf(), { recursive: true })
|
|
269
|
+
for (const { f, data } of files) {
|
|
270
|
+
const tmp = `${fileOf(f)}.${process.pid}.tmp`
|
|
271
|
+
fs.writeFileSync(tmp, data)
|
|
272
|
+
fs.renameSync(tmp, fileOf(f))
|
|
273
|
+
}
|
|
274
|
+
for (const n of fs.readdirSync(cacheDir)) {
|
|
275
|
+
if (/^\d+\.\d+\.\d+/.test(n) && vcmp(n, index.version) < 0) try { fs.rmSync(path.join(cacheDir, n), { recursive: true, force: true }) } catch (e) { log(e) }
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** 保证字体都在缓存里;失败抛错(err.code:off = 不联网开着) */
|
|
280
|
+
function ensure() {
|
|
281
|
+
if (ready()) return Promise.resolve()
|
|
282
|
+
if (inflight) return inflight
|
|
283
|
+
if (now() - failedAt < RETRY_MS && lastErr) return Promise.reject(lastErr)
|
|
284
|
+
inflight = download().then(
|
|
285
|
+
() => { failedAt = -Infinity; lastErr = null; inflight = null },
|
|
286
|
+
(e) => { inflight = null; log(e); if (e && e.code === 'off') { failedAt = -Infinity; lastErr = null } else { failedAt = now(); lastErr = e } throw e },
|
|
287
|
+
)
|
|
288
|
+
return inflight
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** 预览服务器用:这个 id 的缓存文件(在、大小对才给) */
|
|
292
|
+
const cached = (id) => {
|
|
293
|
+
const f = index.fonts.find((x) => x.id === id)
|
|
294
|
+
return f && has(f) ? fileOf(f) : null
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* 把 fonts 复制进 <dir>/dsh-fonts/(同步;真实路径写之前核对)。已经在且内容对的不动,不对的换掉(字体库管这些文件名)。
|
|
299
|
+
* allowed(真实路径) 说这个目录能不能写;fonts 指到外面就不写。
|
|
300
|
+
*/
|
|
301
|
+
function place(dir, fonts, allowed = () => true) {
|
|
302
|
+
const denied = () => Object.assign(new Error('outside'), { code: 'link' })
|
|
303
|
+
let probe = path.resolve(dir)
|
|
304
|
+
while (!fs.existsSync(probe)) {
|
|
305
|
+
const up = path.dirname(probe)
|
|
306
|
+
if (up === probe) break
|
|
307
|
+
probe = up
|
|
308
|
+
}
|
|
309
|
+
if (!allowed(fs.realpathSync(probe))) throw denied()
|
|
310
|
+
const sub = path.join(dir, FONT_DIR)
|
|
311
|
+
fs.mkdirSync(sub, { recursive: true })
|
|
312
|
+
const realDir = fs.realpathSync(dir)
|
|
313
|
+
const realSub = fs.realpathSync(sub)
|
|
314
|
+
if (!allowed(realDir) || realSub !== path.join(realDir, FONT_DIR)) throw denied()
|
|
315
|
+
for (const f of fonts) {
|
|
316
|
+
if (!okFile(f)) {
|
|
317
|
+
try { fs.rmSync(fileOf(f), { force: true }) } catch (e) { log(e) }
|
|
318
|
+
throw Object.assign(new Error(`bad cached font ${f.id}`), { code: 'mismatch' })
|
|
319
|
+
}
|
|
320
|
+
const to = path.join(realSub, `${f.id}.woff2`)
|
|
321
|
+
let same = false
|
|
322
|
+
try {
|
|
323
|
+
const st = fs.lstatSync(to)
|
|
324
|
+
if (!st.isFile()) throw denied() // 软链接、文件夹:不往里写
|
|
325
|
+
same = st.size === f.size && sha256(fs.readFileSync(to)) === f.sha256
|
|
326
|
+
} catch (e) {
|
|
327
|
+
if (e && e.code === 'link') throw e
|
|
328
|
+
}
|
|
329
|
+
if (same) continue
|
|
330
|
+
// 临时文件独占新建(同名的东西已经在了——哪怕是软链接——就先删掉它本身再建,不顺着它写出去)
|
|
331
|
+
const tmp = `${to}.${process.pid}.tmp`
|
|
332
|
+
try {
|
|
333
|
+
fs.copyFileSync(fileOf(f), tmp, fs.constants.COPYFILE_EXCL)
|
|
334
|
+
} catch (e) {
|
|
335
|
+
if (!e || e.code !== 'EEXIST') throw e
|
|
336
|
+
fs.rmSync(tmp, { force: true })
|
|
337
|
+
fs.copyFileSync(fileOf(f), tmp, fs.constants.COPYFILE_EXCL)
|
|
338
|
+
}
|
|
339
|
+
fs.renameSync(tmp, to)
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** 下载 → 复制;缓存里有坏文件时重下一次 */
|
|
344
|
+
async function provide(dir, fonts, allowed) {
|
|
345
|
+
await ensure()
|
|
346
|
+
try { return place(dir, fonts, allowed) } catch (e) { if (!e || e.code !== 'mismatch') throw e }
|
|
347
|
+
await ensure()
|
|
348
|
+
return place(dir, fonts, allowed)
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
return { index, ready, ensure, place, provide, cached }
|
|
352
|
+
}
|
package/lib/gallery/pack.js
CHANGED
|
@@ -13,6 +13,7 @@ import path from 'node:path'
|
|
|
13
13
|
import { cleanPath, checkPack, normalizeHtml, titleOf, metaKind, message, LIMITS, capsOf, FORMAT, pctBytes, imageInfo } from './policy.js'
|
|
14
14
|
import { writeZip } from './zip.js'
|
|
15
15
|
import { isPhotoAsset } from '../photos.js'
|
|
16
|
+
import { stripFontBlock } from '../fonts.js'
|
|
16
17
|
import { decodeEntities } from './html.js'
|
|
17
18
|
|
|
18
19
|
/** 页面文本 → 去掉注释、解开各种转义、全小写,用来判断提没提到某个文件 */
|
|
@@ -264,7 +265,8 @@ export function packDesign(root, { screens, version = '', license = '', author =
|
|
|
264
265
|
// 不在画布上的顶层页面(方向稿删掉了、改名前的旧文件):不打包
|
|
265
266
|
if (/\.html$/i.test(f.path) && !f.path.includes('/') && !screenSet.has(f.path.toLowerCase())) { skipped.push(f.path); continue }
|
|
266
267
|
// 别的 JSON(设置、记录、导出的数据…):模板用不上(不能跑脚本),可能带着个人信息,不打包;只留调节滑块的 tweaks.json
|
|
267
|
-
|
|
268
|
+
// 和模拟数据 mock.json(#30:原型的数据源,少了它页面上的绑定全是占位、几种状态一起露出来;JSON 整份查个人信息)
|
|
269
|
+
if (/\.json$/i.test(f.path) && f.path !== 'tweaks.json' && f.path !== 'mock.json') { skipped.push(f.path); continue }
|
|
268
270
|
let data
|
|
269
271
|
try {
|
|
270
272
|
const st = fs.statSync(f.abs)
|
|
@@ -272,6 +274,12 @@ export function packDesign(root, { screens, version = '', license = '', author =
|
|
|
272
274
|
data = fs.readFileSync(f.abs)
|
|
273
275
|
} catch { continue }
|
|
274
276
|
const ext = f.path.slice(f.path.lastIndexOf('.') + 1).toLowerCase()
|
|
277
|
+
// 字体库(#31):字体文件不进包(市场只收系统字体),设计台管的 @font-face 那段去掉,字体栈后面的系统字体顶上
|
|
278
|
+
if (ext === 'html' || ext === 'css') {
|
|
279
|
+
const raw = data.toString('utf8')
|
|
280
|
+
const bare = stripFontBlock(raw)
|
|
281
|
+
if (bare !== raw) { notes.push({ code: 'fontLib', x: f.path }); data = Buffer.from(bare, 'utf8') }
|
|
282
|
+
}
|
|
275
283
|
if (ext === 'html') {
|
|
276
284
|
const r = normalizeHtml(data.toString('utf8'), { file: f.path })
|
|
277
285
|
if (r.changes.length) notes.push(...r.changes)
|
|
@@ -291,7 +299,8 @@ export function packDesign(root, { screens, version = '', license = '', author =
|
|
|
291
299
|
}
|
|
292
300
|
}
|
|
293
301
|
// 自带照片库的图:找图时多拿的、页面没用上的不打包。宁可多带:页面里(解码后)提到这个文件名就留,注释里的不算
|
|
294
|
-
|
|
302
|
+
// mock.json 也算(#30:头像、商品图写在模拟数据里,页面用 data-mock-attr 绑上)
|
|
303
|
+
const refText = files.filter((f) => /\.(html|css|svg)$/i.test(f.path) || f.path === 'mock.json').map((f) => refsFold(Buffer.from(f.data).toString('utf8'))).join('\n')
|
|
295
304
|
const dropped = new Set()
|
|
296
305
|
for (let i = files.length - 1; i >= 0; i--) {
|
|
297
306
|
const f = files[i]
|
package/lib/handoff.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import { PHOTO_PREFIX, isPhotoAsset } from './photos.js'
|
|
13
|
+
import { isLibFontRel, loadFontIndex } from './fonts.js'
|
|
13
14
|
import fs from 'node:fs'
|
|
14
15
|
import os from 'node:os'
|
|
15
16
|
import path from 'node:path'
|
|
@@ -22,6 +23,7 @@ import { tokensOf } from './system.js'
|
|
|
22
23
|
import { FRAMES_DIR } from './frames.js'
|
|
23
24
|
import { FRAME_MAIN, SLOT_BOX } from './slot.js'
|
|
24
25
|
import { statesOfHtml } from './states.js'
|
|
26
|
+
import { mockOf } from './mock.js'
|
|
25
27
|
|
|
26
28
|
/**
|
|
27
29
|
* 交接文档里的「页面状态」:写了几个状态的屏,列出状态、各状态用到的样式条数、哪些按钮会切到哪个状态
|
|
@@ -42,6 +44,41 @@ export function statesMd(htmlByKey, css = '') {
|
|
|
42
44
|
return out
|
|
43
45
|
}
|
|
44
46
|
|
|
47
|
+
/**
|
|
48
|
+
* 交接文档里的「模拟数据」(#30):设计目录里有 mock.json 才有。原型的数据都在这一份里、各屏用 data-mock-* 绑上;
|
|
49
|
+
* 转代码时做成一份初始数据 + 全局状态,页面从状态里读、点了改状态
|
|
50
|
+
*/
|
|
51
|
+
export function mockMd(htmlByKey, root) {
|
|
52
|
+
const m = mockOf(root)
|
|
53
|
+
if (!m) return []
|
|
54
|
+
const top = Object.keys(m.data)
|
|
55
|
+
const out = [
|
|
56
|
+
`- 原型的数据都在设计目录的 \`mock.json\` 里${m.err ? `(现在读不出来:${m.err}——先修好再做)` : top.length ? `(顶层:${top.slice(0, 12).join('、')}${top.length > 12 ? ' 等' : ''})` : ''},各屏用 \`data-mock-*\` 绑在上面。照搬成项目里的一份初始数据 + 一个全局状态(Pinia / Zustand / Context / 小程序的全局 store 之类):页面上的值从状态里读,点了改状态,换页还在;以后接真接口只换状态的来源,页面不用动。`,
|
|
57
|
+
'- 写法对照:`data-mock-text` 显示值;`data-mock-show` 条件显示;`data-mock-each="x in list"` + `<template>` 是列表;`data-mock-class` / `data-mock-attr` 按条件加 class、属性;`data-mock-model` 双向绑定的输入框;`data-mock-set="a = …; b = …"` 点了改数据(做成点击事件);`data-mock-reset` 恢复初始数据(演示用)。',
|
|
58
|
+
]
|
|
59
|
+
const topSet = new Set(top)
|
|
60
|
+
const follow = []
|
|
61
|
+
for (const [key, html] of htmlByKey) {
|
|
62
|
+
const src = String(html)
|
|
63
|
+
const st = /<meta\b[^>]*>/gi
|
|
64
|
+
for (const mm of src.matchAll(st)) {
|
|
65
|
+
if (!/\bname\s*=\s*["']?dsh-states["'\s/>]/i.test(mm[0])) continue
|
|
66
|
+
const d = /\bdata-mock\s*=\s*["']([^"']+)["']/i.exec(mm[0])
|
|
67
|
+
if (d) follow.push(`${key}(${d[1].trim()})`)
|
|
68
|
+
}
|
|
69
|
+
const used = new Set()
|
|
70
|
+
let sets = 0
|
|
71
|
+
for (const a of src.matchAll(/\sdata-mock-(text|show|each|set|model|class|attr)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)) {
|
|
72
|
+
if (a[1].toLowerCase() === 'set') sets++
|
|
73
|
+
const v = (a[2] !== undefined ? a[2] : a[3] || '').replace(/'[^']*'|"[^"]*"/g, ' ')
|
|
74
|
+
for (const p of v.matchAll(/[A-Za-z_$\u4e00-\u9fa5][\w$\u4e00-\u9fa5]*(?:\.[\w$\u4e00-\u9fa5]+|\[\d+\])*/g)) if (topSet.has(p[0].split(/[.[]/)[0])) used.add(p[0])
|
|
75
|
+
}
|
|
76
|
+
if (used.size || sets) out.push(`- ${key}:用到 ${[...used].slice(0, 8).map((x) => `\`${x}\``).join('、') || '(只有改数据的按钮)'}${used.size > 8 ? ` 等 ${used.size} 个字段` : ''}${sets ? `;点了改数据 ${sets} 处` : ''}`)
|
|
77
|
+
}
|
|
78
|
+
if (follow.length) out.push(`- 状态跟着数据走的屏:${follow.slice(0, 8).join('、')}——这几屏的状态别放在页面自己里,读全局状态的那个字段(一处改了所有页一起变)。`)
|
|
79
|
+
return out
|
|
80
|
+
}
|
|
81
|
+
|
|
45
82
|
export const HANDOFF_DIR = 'handoff'
|
|
46
83
|
/** 版本名里哪些是用户在右侧栏亲手改的(见 core.js:改字、调样式、调节滑块) */
|
|
47
84
|
const TUNED = /^(改字「|调样式「|调节:)/
|
|
@@ -624,6 +661,7 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
|
|
|
624
661
|
// 一页多状态(#30):同一个页面的几种样子写在一个文件里,转代码时是一个组件带状态,不是几个页面
|
|
625
662
|
const stLines = statesMd(htmlByKey, [...sheets, 'tokens.css'].map((n) => { try { return fs.readFileSync(path.join(root, n), 'utf8') } catch { return '' } }).join('\n'))
|
|
626
663
|
if (stLines.length) lines.push(...stLines)
|
|
664
|
+
lines.push(...mockMd(htmlByKey, root))
|
|
627
665
|
if ([...htmlByKey.values()].some((h) => /\sdata-back\b/i.test(slotHtml(h)))) lines.push('- 写了 `data-back` 的返回按钮:做成「返回上一页」(router.back() / navigation.goBack()),没有上一页时才去它写的 href。')
|
|
628
666
|
if (hover) lines.push(`- 悬停 / 聚焦 / 按下的样式 ${hover} 处:照搬,别丢。`)
|
|
629
667
|
if ([...htmlByKey.values()].some((h) => /prefers-color-scheme\s*:\s*dark|data-theme=["']?dark/.test(h)) || /\[data-theme=["']?dark/.test(Object.keys(tok).length ? fs.readFileSync(path.join(root, 'tokens.css'), 'utf8') : '')) lines.push('- 有深色样式:项目里也要能切(跟系统,或 `<html data-theme="dark">`)。')
|
|
@@ -652,6 +690,12 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
|
|
|
652
690
|
lines.push(assets.length ? `- ${assets.slice(0, 30).map((a) => `\`${a}\``).join('、')}${assets.length > 30 ? ' …' : ''}:照原样复制进项目的静态资源目录(${mini ? (uni ? `\`${at}static/\`` : taro ? `\`${at}assets/\`` : `\`${at}images/\` 之类`) : 'public/ 或 src/assets/'})` : '- 没有单独的图片、字体文件(图形都写在 HTML / SVG 里)。')
|
|
653
691
|
const aiPhotos = assets.filter((x) => isPhotoAsset(x))
|
|
654
692
|
if (aiPhotos.length) lines.push(`- 文件名带 \`${PHOTO_PREFIX}\` 的 ${aiPhotos.length} 张是 AI 生成的示意图:先照常接上,做完提醒用户上线前换成真实照片。`)
|
|
693
|
+
const libFonts = assets.filter((x) => isLibFontRel(x))
|
|
694
|
+
if (libFonts.length) {
|
|
695
|
+
const idx = loadFontIndex()
|
|
696
|
+
const names = libFonts.map((x) => { const id = path.posix.basename(x, '.woff2'); const f = idx && idx.fonts.find((y) => y.id === id); return f ? `${f.zh}(${f.source})` : id })
|
|
697
|
+
lines.push(`- \`dsh-fonts/\` 里的 ${libFonts.length} 款是设计台字体库的字体(SIL OFL 1.1,可商用;中文只裁了常用 6763 字的网页版):先照原样接上(样式里的 @font-face 跟着搬,路径按新位置改),提醒用户上线前可以换官方完整版:${names.join(';')}。`)
|
|
698
|
+
}
|
|
655
699
|
if (mini) lines.push(`- 小程序主包不能超过 2MB:大图放服务器用网址;字体文件要用 \`${api}.loadFontFace\` 从网址加载,加载不了就用系统字体。`)
|
|
656
700
|
lines.push('')
|
|
657
701
|
|
package/lib/history.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import fs from 'node:fs'
|
|
11
11
|
import path from 'node:path'
|
|
12
12
|
import crypto from 'node:crypto'
|
|
13
|
+
import { isLibFontRel } from './fonts.js'
|
|
13
14
|
|
|
14
15
|
const KEEP_EXT = /\.(html?|css|m?js|json|svg|txt|md|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf)$/i
|
|
15
16
|
const SKIP_DIR = /^(node_modules|\.git|\.next|\.cache|\.turbo|dist|build|exports|refs|handoff)$|^\./
|
|
@@ -62,6 +63,7 @@ export function collect(root) {
|
|
|
62
63
|
continue
|
|
63
64
|
}
|
|
64
65
|
if (!d.isFile() || d.name.startsWith('.') || !KEEP_EXT.test(d.name)) continue
|
|
66
|
+
if (isLibFontRel(r)) continue // 字体库复制进来的字体(#31):库里随时能再拿,不占版本记录的空间
|
|
65
67
|
let st
|
|
66
68
|
try { st = fs.statSync(abs) } catch { continue }
|
|
67
69
|
if (st.size > MAX_FILE) continue
|