dsh-design-studio 0.25.2 → 0.26.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/client.js +615 -42
- package/lib/handoff.js +169 -24
- package/lib/impl.js +123 -0
- package/lib/index.js +204 -31
- package/lib/picker.js +136 -0
- package/lib/serve.js +3 -1
- package/lib/slot.js +37 -0
- package/package.json +1 -1
package/lib/handoff.js
CHANGED
|
@@ -13,12 +13,14 @@ import { PHOTO_PREFIX, isPhotoAsset } from './photos.js'
|
|
|
13
13
|
import fs from 'node:fs'
|
|
14
14
|
import os from 'node:os'
|
|
15
15
|
import path from 'node:path'
|
|
16
|
-
import { pathToFileURL } from 'node:url'
|
|
16
|
+
import { pathToFileURL, fileURLToPath } from 'node:url'
|
|
17
17
|
import { prepare } from './look.js'
|
|
18
18
|
import { allScreens } from './core.js'
|
|
19
19
|
import { readTweaks, shownValue } from './tweaks.js'
|
|
20
20
|
import { annotationsMd } from './annotations.js'
|
|
21
21
|
import { tokensOf } from './system.js'
|
|
22
|
+
import { FRAMES_DIR } from './frames.js'
|
|
23
|
+
import { FRAME_MAIN, SLOT_BOX } from './slot.js'
|
|
22
24
|
|
|
23
25
|
export const HANDOFF_DIR = 'handoff'
|
|
24
26
|
const MAX_SCREENS = 12
|
|
@@ -266,10 +268,57 @@ export function pagePathOf(key, target = 'uniapp') {
|
|
|
266
268
|
|
|
267
269
|
const CLASS_TAGS = /^(header|nav|footer|aside|section|div|a|button|ul|ol|li|form|article|main|figure)$/
|
|
268
270
|
|
|
269
|
-
/**
|
|
271
|
+
/** 页面套了登记过的外框:DSH 自带的四个(data-frame="dsh/…"),或带外框库那段 <template id="dsh-frame">;还得有槽位。和体检、compare_design 一个认法 */
|
|
272
|
+
export const isFramed = (html) => {
|
|
273
|
+
const s = String(html || '')
|
|
274
|
+
return /\sdata-slot\s*=/i.test(s) && (/\bdata-frame\s*=\s*["']?dsh\/(sidebar|settings|view|panel)["'\s>]/i.test(s) || /<template\b[^>]*\bid\s*=\s*["']?dsh-frame["'\s>]/i.test(s))
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** 页面套了外框就只留各个 data-slot 里面的(外框是宿主画的,不用做,也不算「几屏共用的部分」);没套原样给 */
|
|
278
|
+
export function slotHtml(html) {
|
|
279
|
+
const s = String(html || '')
|
|
280
|
+
if (!isFramed(s)) return s
|
|
281
|
+
const out = []
|
|
282
|
+
const open = /<([a-z][a-z0-9-]*)\b[^>]*?\sdata-slot\s*=[^>]*>/gi
|
|
283
|
+
let m
|
|
284
|
+
while ((m = open.exec(s))) {
|
|
285
|
+
// 找配对的结束标签:同名标签数层数(槽位里的槽位跟着一起拿走,不重复)
|
|
286
|
+
const close = new RegExp(`<(/?)${m[1]}\\b[^>]*>`, 'gi')
|
|
287
|
+
close.lastIndex = open.lastIndex
|
|
288
|
+
let depth = 1
|
|
289
|
+
let end = s.length
|
|
290
|
+
let x
|
|
291
|
+
while ((x = close.exec(s))) {
|
|
292
|
+
if (!x[1] && /\/\s*>$/.test(x[0])) continue
|
|
293
|
+
depth += x[1] ? -1 : 1
|
|
294
|
+
if (!depth) { end = x.index; break }
|
|
295
|
+
}
|
|
296
|
+
out.push(s.slice(open.lastIndex, end))
|
|
297
|
+
open.lastIndex = end
|
|
298
|
+
}
|
|
299
|
+
return out.join('\n')
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** 设计目录里哪些样式表是外框的:自带 DSH 外框是 dsh-shell.css;外框库的照库里 frame.json 写的 css(库里没有这个外框就认不出) */
|
|
303
|
+
export function frameCss(root, htmls) {
|
|
304
|
+
const ids = new Set()
|
|
305
|
+
for (const h of htmls) for (const m of String(h).matchAll(/\bdata-frame\s*=\s*["']?([a-z0-9][a-z0-9-]*)\//gi)) ids.add(m[1].toLowerCase())
|
|
306
|
+
const names = new Set()
|
|
307
|
+
for (const id of ids) {
|
|
308
|
+
if (id === 'dsh') { names.add('dsh-shell.css'); continue }
|
|
309
|
+
try {
|
|
310
|
+
const m = JSON.parse(fs.readFileSync(path.join(FRAMES_DIR, id, 'frame.json'), 'utf8').replace(/^\uFEFF/, ''))
|
|
311
|
+
for (const c of [].concat(m.css || [])) if (typeof c === 'string') names.add(c.toLowerCase())
|
|
312
|
+
} catch { /* 库里没有 */ }
|
|
313
|
+
}
|
|
314
|
+
try { return fs.readdirSync(root).filter((n) => names.has(n.toLowerCase())) } catch { return [] }
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** 几屏共用的 class(≥ 2 屏都有,多半该抽成组件):[{ cls, n, screens }];套了外框的页面只看槽位里的 */
|
|
270
318
|
export function sharedParts(htmlByKey) {
|
|
271
319
|
const seen = new Map()
|
|
272
|
-
for (const [key,
|
|
320
|
+
for (const [key, raw] of htmlByKey) {
|
|
321
|
+
const html = slotHtml(raw)
|
|
273
322
|
const mine = new Set()
|
|
274
323
|
for (const m of String(html).matchAll(/<([a-z][a-z0-9-]*)\b[^>]*?\bclass\s*=\s*("([^"]*)"|'([^']*)')/gi)) {
|
|
275
324
|
if (!CLASS_TAGS.test(m[1].toLowerCase())) continue
|
|
@@ -450,6 +499,23 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
|
|
|
450
499
|
lines.push('- 整个窗口不滚,侧栏、列表、详情各自滚(`overflow: auto`);最小窗口尺寸照设计里最小的那种(多尺寸里的 1024×680)设。', '')
|
|
451
500
|
}
|
|
452
501
|
|
|
502
|
+
// 套了外框(DSH 插件、外框库):外框是宿主画的,只做槽位里的(#25)
|
|
503
|
+
const framedKeys = [...(htmlByKey || new Map())].filter(([, x]) => isFramed(x)).map(([k]) => k)
|
|
504
|
+
const plainKeys = [...(htmlByKey || new Map()).keys()].filter((k) => !framedKeys.includes(k))
|
|
505
|
+
const framedHtml = framedKeys.map((k) => htmlByKey.get(k))
|
|
506
|
+
const frameSheets = frameCss(root, framedHtml)
|
|
507
|
+
const fsNames = frameSheets.map((n) => `\`${n}\``).join('、')
|
|
508
|
+
if (framedHtml.length) { // 按这次交接的屏里真有外框才写(DSH 插件项目里只交接普通欢迎页就不写)
|
|
509
|
+
const dsh = kind === 'dshplugin' || framedHtml.some((x) => /\bdata-frame\s*=\s*["']?dsh\//i.test(x))
|
|
510
|
+
const host = dsh ? 'DSH 桌面端' : '那个软件 / 浏览器'
|
|
511
|
+
lines.push('## 外框要点', '')
|
|
512
|
+
const short = (ks) => ks.map((k) => k.replace(/\.html?$/i, '')).join('、')
|
|
513
|
+
const which = framedKeys.length && plainKeys.length ? `${short(framedKeys)} 这几屏` : '这几屏'
|
|
514
|
+
lines.push(`- ${which}套了${dsh ? ' DSH 插件的' : '外框库里的'}外框:外框(${dsh ? '侧栏、标题栏、设置弹窗这些' : '窗口、工具栏这些'})是${host}自己画的,**不用做**。只做每屏 \`data-slot\` 里面的:\`main\` 是主体,做成页面 / 组件;\`entry-icon\`、\`entry-label\`、\`tab-label\` 这类小槽位是${host}入口上的图标和字,照${dsh ? ' DSH 插件的注册接口' : '它的插件清单 / 配置'}填,不做成页面。${framedKeys.length && plainKeys.length ? `别的屏(${short(plainKeys)})没套外框,照常整页做。` : ''}`)
|
|
515
|
+
lines.push(`- 外框的样式表(${fsNames || '从外框库复制来的那几个'}):外框部件的样式(外框自己的 class)和外框用的图不搬;但里面的变量(\`--\` 开头的,浅色、深色两段)和槽位 \`main\` 的基础样式(字号、字色、背景)要带进项目——槽位里的内容用着它们(真插件里也可以换成宿主自己的同名变量)。tokens.css 有的话照搬。`)
|
|
516
|
+
lines.push('- 开发服务器上的页面就是 `main` 这一块本身,铺满窗口,别自己再画一圈外框。`compare_design` 会自动只截设计稿里 `main` 那块,按它的尺寸打开你的页面来比;只有项目里自己也套了同一个外框、整屏和设计稿一样大时,才传 `whole: true` 整屏比。', '')
|
|
517
|
+
}
|
|
518
|
+
|
|
453
519
|
lines.push(mini ? '## 屏幕和页面' : '## 屏幕和路由', '', `| 屏 | 设计文件 | ${mini ? '页面路径' : '建议路由'} | 截图(handoff/shots/) | 跳到 |`, '| --- | --- | --- | --- | --- |')
|
|
454
520
|
for (const r of rows) {
|
|
455
521
|
const to = [...new Set((r.links || []).map((l) => keyOfLink(l.path)).filter((k) => k && k !== r.key))]
|
|
@@ -473,8 +539,13 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
|
|
|
473
539
|
? '- 把 tokens.css 原样放进项目的全局样式并在入口引入;Tailwind 的 theme.extend 里把颜色、圆角、字号、阴影映射到这些变量(如 `primary: \'var(--color-primary)\'`),类名里别写死色值。'
|
|
474
540
|
: '- 把 tokens.css 原样放进项目的全局样式(如 `src/styles/tokens.css`)并在入口引入;组件样式里一律用 `var(--…)`,别写死色值、字号。')
|
|
475
541
|
} else if (hasTokens) lines.push('- `tokens.css` 的第一段 `:root` 里没读到变量:先打开看看,把各屏用到的颜色、字号收成 `:root` 上的变量再动手。')
|
|
476
|
-
else
|
|
477
|
-
|
|
542
|
+
else {
|
|
543
|
+
if (frameSheets.length) lines.push(`- 没有 tokens.css:套外框的屏用的是外框样式表(${fsNames})里的变量,照上面「外框要点」带进项目。`)
|
|
544
|
+
// 没套外框的屏(或者认不出外框样式表):页面里自己写的变量照旧收
|
|
545
|
+
if (!frameSheets.length || plainKeys.length) lines.push(`- 设计目录里没有 tokens.css:先把${frameSheets.length ? '没套外框那几屏' : '各屏'} \`<style>\` 里 \`:root\` 上的变量收成一份 tokens.css 再动手。`)
|
|
546
|
+
}
|
|
547
|
+
// 外框的样式表不算公共样式(上面「外框要点」说了怎么带)
|
|
548
|
+
const sheets = (() => { try { return fs.readdirSync(root).filter((n) => /\.css$/i.test(n) && n !== 'tokens.css' && !frameSheets.includes(n)) } catch { return [] } })()
|
|
478
549
|
if (sheets.length) lines.push(`- 别的样式表:${sheets.map((n) => `\`${n}\``).join('、')}(公共样式,拆进对应组件或全局样式)`)
|
|
479
550
|
lines.push('')
|
|
480
551
|
|
|
@@ -504,12 +575,14 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
|
|
|
504
575
|
for (const n of [...sheets, 'tokens.css']) { try { hover += (fs.readFileSync(path.join(root, n), 'utf8').match(/:(hover|focus-visible|focus|active)\b/g) || []).length } catch { /* 没有 */ } }
|
|
505
576
|
for (const [key, html] of htmlByKey) {
|
|
506
577
|
const scripts = [...html.matchAll(/<script\b(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi)].filter((m) => m[1].trim()).length
|
|
507
|
-
|
|
578
|
+
// 套了外框的屏:输入框、跳转只数槽位里的(外框上的搜索框之类是宿主的);脚本常写在页尾,照整页数
|
|
579
|
+
const inner = slotHtml(html)
|
|
580
|
+
const forms = (inner.match(/<(input|textarea|select)\b/gi) || []).length
|
|
508
581
|
hover += (html.match(/:(hover|focus-visible|focus|active)\b/g) || []).length
|
|
509
582
|
const bits = []
|
|
510
583
|
if (scripts) bits.push(`${scripts} 段脚本(改成框架里的状态和事件)`)
|
|
511
584
|
if (forms) bits.push(`${forms} 个输入控件(做成受控组件、加校验和出错状态)`)
|
|
512
|
-
if (/data-href=/.test(
|
|
585
|
+
if (/data-href=/.test(inner)) bits.push('用 data-href 跳转的元素(改成路由跳转)')
|
|
513
586
|
if (bits.length) inter.push(`- ${key}:${bits.join(';')}`)
|
|
514
587
|
}
|
|
515
588
|
lines.push(...(inter.length ? inter : ['- 设计稿里没有脚本和表单,纯展示。']))
|
|
@@ -558,7 +631,9 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
|
|
|
558
631
|
const sub = fw && fw.create ? fw.create.replace('{name}', 'web') : ''
|
|
559
632
|
const mono = !create && !fresh && !!(project && project.mono)
|
|
560
633
|
const keep = project && project.empty === false ? ';目录里已经有文件:别覆盖现有的页面,重名的先问用户' : ''
|
|
561
|
-
const tokTail = mini ? `;tokens.css 里的变量搬进全局样式的 \`${taro ? 'page, .taro_page' : 'page'} { }\`${sheets.length ? ',公共样式表也拆进去' : ''}`
|
|
634
|
+
const tokTail = (mini ? `;tokens.css 里的变量搬进全局样式的 \`${taro ? 'page, .taro_page' : 'page'} { }\`${sheets.length ? ',公共样式表也拆进去' : ''}`
|
|
635
|
+
: hasTokens || !frameSheets.length ? `;把 tokens.css${sheets.length ? '(和公共样式表)' : ''}搬进去` : sheets.length ? ';把公共样式表搬进去' : '')
|
|
636
|
+
+ (frameSheets.length ? `;外框样式表(${fsNames})里的变量和槽位基础样式照「外框要点」带进去` : '')
|
|
562
637
|
const step1 = create ? `新建项目 \`${create}\`${fresh ? `(在 \`${path.dirname(dest)}\` 里跑)` : ''},${pm ? `用 ${pm} ` : ''}装好依赖${fwNew.router ? `和 ${fwNew.router}` : ''}${uni ? '(GitHub 连不上就从 gitee 下载模板压缩包 `https://gitee.com/dcloud/uni-preset-vue/repository/archive/vite-ts.zip`,解开当项目目录)' : ''}`
|
|
563
638
|
: framework === 'html' ? `整理成一个静态站点目录(每屏一个页面,公共样式一份)${keep}`
|
|
564
639
|
: fresh ? `在这个空文件夹里新建一个 ${fwLabel.replace('(跟项目一样)', '')} 子项目,照仓库里别的子包怎么搭的来(monorepo 记得加进 workspace)${pm ? `,用 ${pm} 装依赖` : ''}`
|
|
@@ -592,10 +667,11 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
|
|
|
592
667
|
// ── compare_design:设计稿 vs 做出来的页面 ─────────────────────────────────────
|
|
593
668
|
|
|
594
669
|
// 页面上看得见的「块」(有字的、图片、按钮、有底色或边框的),差异区域按它说是哪个元素
|
|
595
|
-
const
|
|
670
|
+
const blocksIn = (root) => `(() => {
|
|
596
671
|
const out = []
|
|
597
672
|
const W = innerWidth, H = innerHeight
|
|
598
|
-
|
|
673
|
+
const root = ${root}
|
|
674
|
+
for (const el of root ? root.querySelectorAll('*') : []) {
|
|
599
675
|
if (out.length >= 600) break
|
|
600
676
|
const r = el.getBoundingClientRect()
|
|
601
677
|
if (r.width < 4 || r.height < 4 || r.bottom < 0 || r.top > H || r.right < 0 || r.left > W) continue
|
|
@@ -614,6 +690,7 @@ const BLOCKS = `(() => {
|
|
|
614
690
|
}
|
|
615
691
|
return out
|
|
616
692
|
})()`
|
|
693
|
+
const BLOCKS = blocksIn('document.body')
|
|
617
694
|
|
|
618
695
|
// 等单页应用画出东西来:body 里有字 / 有图,最多等 4 秒;再等字体
|
|
619
696
|
const SETTLE = `new Promise((res) => {
|
|
@@ -791,30 +868,90 @@ export function blockAt(blocks, bx) {
|
|
|
791
868
|
|
|
792
869
|
const describe = (b) => (b ? `${b.d}${b.t ? `「${b.t}」` : ''}` : '(空白处)')
|
|
793
870
|
|
|
871
|
+
/**
|
|
872
|
+
* 本地 HTML 经预览服务器开时,服务器的根放哪、页面在根下的地址。
|
|
873
|
+
* 默认就是 HTML 所在的文件夹(Vite 打包的 /assets 根路径要这样才对);
|
|
874
|
+
* 页面引用了上级目录(../css/app.css)就往上提几层,最多 3 层,不然那些资源 404、页面没样式。
|
|
875
|
+
* 往上提有边:只在会话目录里提、不出会话目录(会话目录外的 HTML 不提);无论如何不提到家目录(及更上面)——预览服务器能读的范围别一下变大。
|
|
876
|
+
* @returns { root, rel } rel 已按段编码,以 / 开头
|
|
877
|
+
*/
|
|
878
|
+
export function implServe(file, limit = '') {
|
|
879
|
+
let up = 0
|
|
880
|
+
try {
|
|
881
|
+
if (fs.lstatSync(file).isSymbolicLink()) throw new Error('link') // 软链接不读(可能指到目录外面):按所在文件夹
|
|
882
|
+
const fd = fs.openSync(file, 'r')
|
|
883
|
+
let html = ''
|
|
884
|
+
try { const buf = Buffer.alloc(1024 * 1024); html = buf.toString('utf8', 0, fs.readSync(fd, buf, 0, buf.length, 0)) } finally { fs.closeSync(fd) }
|
|
885
|
+
const re = /(?:\b(?:src|href|srcset|poster|data)\s*=\s*["']?|url\(\s*["']?|\bimport\s*(?:[^'"]*from\s*)?["']|\bimport\(\s*["'])((?:\.\.\/)+)/gi
|
|
886
|
+
let m
|
|
887
|
+
while ((m = re.exec(html))) up = Math.max(up, m[1].length / 3)
|
|
888
|
+
} catch { /* 读不了就按所在文件夹 */ }
|
|
889
|
+
let root = path.dirname(file)
|
|
890
|
+
const home = os.homedir()
|
|
891
|
+
const cap = limit && within(file, limit) ? limit : ''
|
|
892
|
+
if (!cap) up = 0
|
|
893
|
+
for (let i = 0; i < Math.min(up, 3); i++) {
|
|
894
|
+
const p = path.dirname(root)
|
|
895
|
+
if (p === root || within(home, p) || (cap && !within(p, cap))) break
|
|
896
|
+
root = p
|
|
897
|
+
}
|
|
898
|
+
const rel = path.relative(root, file).split(path.sep).map(encodeURIComponent).join('/')
|
|
899
|
+
return { root, rel: '/' + rel }
|
|
900
|
+
}
|
|
901
|
+
|
|
794
902
|
/** 做出来的页面地址:本机的 http(s),或本地 HTML 文件 */
|
|
795
903
|
export function implUrl(input, cwd) {
|
|
796
904
|
const s = String(input || '').trim()
|
|
797
|
-
|
|
905
|
+
const bad = () => new Error(`认不出这个地址:${s.slice(0, 80)}(端口是 1–65535 的数)`)
|
|
906
|
+
const web = (x) => { try { return new URL(x) } catch { throw bad() } }
|
|
907
|
+
if (/^\d{2,5}$/.test(s)) {
|
|
908
|
+
if (Number(s) < 1 || Number(s) > 65535) throw bad()
|
|
909
|
+
return `http://localhost:${Number(s)}/`
|
|
910
|
+
}
|
|
798
911
|
if (/^https?:\/\//i.test(s)) {
|
|
799
|
-
const u =
|
|
912
|
+
const u = web(s)
|
|
800
913
|
if (!/^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])$/i.test(u.hostname)) throw new Error('只比本机的页面(localhost 地址或本地 HTML 文件)')
|
|
801
914
|
return u.href
|
|
802
915
|
}
|
|
803
|
-
if (/^(localhost|127\.0\.0\.1)(:\d+)?(\/|$)/i.test(s)) return 'http://' + s
|
|
804
|
-
|
|
916
|
+
if (/^(localhost|127\.0\.0\.1)(:\d+)?(\/|$)/i.test(s)) return web('http://' + s).href
|
|
917
|
+
// 本地 HTML:路径(相对的按会话目录算,~/ 是家目录)或记下来的 file:// 地址;给文件夹就用里面的 index.html
|
|
918
|
+
// 网络共享(\\server\share、//server/share)不比:只比这台电脑上的
|
|
919
|
+
if (/^(\\\\|\/\/)/.test(s) || /^file:\/\/[^/]/i.test(s)) throw new Error('只比这台电脑上的页面(网络共享里的文件不比)')
|
|
920
|
+
let p
|
|
921
|
+
let tail = '' // file:// 地址带的 ?参数 和 #路由:原样留着
|
|
922
|
+
try {
|
|
923
|
+
if (/^file:\/\//i.test(s)) {
|
|
924
|
+
const u = new URL(s)
|
|
925
|
+
tail = u.search + u.hash
|
|
926
|
+
p = fileURLToPath(u)
|
|
927
|
+
} else {
|
|
928
|
+
p = path.resolve(cwd || '.', s.replace(/^~(?=[\\/]|$)/, os.homedir()))
|
|
929
|
+
// 路径后面带了 #路由 / ?参数(dist/index.html#/login):文件按前半截找
|
|
930
|
+
const m = !fs.existsSync(p) && s.match(/^([^?#]+)([?#].*)$/)
|
|
931
|
+
if (m) { p = path.resolve(cwd || '.', m[1].replace(/^~(?=[\\/]|$)/, os.homedir())); tail = m[2] }
|
|
932
|
+
}
|
|
933
|
+
} catch { throw new Error(`认不出这个地址:${s.slice(0, 80)}`) }
|
|
934
|
+
if (process.platform === 'win32' && /^\\\\/.test(p)) throw new Error('只比这台电脑上的页面(网络共享里的文件不比)')
|
|
805
935
|
if (!fs.existsSync(p)) throw new Error(`找不到 ${p}`)
|
|
806
|
-
|
|
936
|
+
if (fs.statSync(p).isDirectory()) {
|
|
937
|
+
const idx = path.join(p, 'index.html')
|
|
938
|
+
if (!fs.existsSync(idx)) throw new Error(`${p} 是文件夹,里面没有 index.html:给页面的 HTML 文件或开发服务器地址`)
|
|
939
|
+
p = idx
|
|
940
|
+
} else if (!/\.html?$/i.test(p)) throw new Error(`只比网页:给 .html 文件或开发服务器地址(${path.basename(p)} 不是)`)
|
|
941
|
+
return pathToFileURL(p).href + tail
|
|
807
942
|
}
|
|
808
943
|
|
|
809
944
|
/**
|
|
810
945
|
* 比一屏:设计稿(预览服务器上的地址,带设计台脚本)vs 做出来的页面,同样尺寸、同样滚动位置。
|
|
811
946
|
* @returns { pct, boxes: [{ x, y, w, h, design, impl }], jpg, text }
|
|
812
947
|
*/
|
|
813
|
-
export async function compareScreens(browser, { design, impl, size, at = 'top', dark = false }) {
|
|
948
|
+
export async function compareScreens(browser, { design, impl, shown = '', size, at = 'top', dark = false, whole = false }) {
|
|
814
949
|
const [w, h] = size
|
|
815
950
|
// 两边一样准备:等画好 → 深色 → 滚到同一个位置(页面和里面能滚的区域都滚)→ 无损截图
|
|
951
|
+
// 设计稿套了外框(whole 没要整屏):只截槽位 main,做出来的页面按槽位的尺寸开
|
|
816
952
|
let blocked = []
|
|
817
|
-
|
|
953
|
+
let slot = null
|
|
954
|
+
const shoot = (url, isDesign, [vw, vh]) => browser.withPage({ url, w: vw, h: vh, dark, allow: isDesign ? null : localOnly }, async (page) => {
|
|
818
955
|
if (!isDesign && page.blocked) blocked = page.blocked
|
|
819
956
|
if (isDesign) await prepare(page, dark)
|
|
820
957
|
else {
|
|
@@ -824,14 +961,19 @@ export async function compareScreens(browser, { design, impl, size, at = 'top',
|
|
|
824
961
|
if (dark) await page.eval(IMPL_DARK)
|
|
825
962
|
}
|
|
826
963
|
if (at === 'bottom') await page.eval(SCROLL_END)
|
|
827
|
-
|
|
828
|
-
const
|
|
829
|
-
const
|
|
964
|
+
if (isDesign && !whole) slot = await page.eval(SLOT_BOX).catch(() => null)
|
|
965
|
+
const cut = isDesign && slot && !slot.hidden
|
|
966
|
+
const png = await page.shot({ format: 'png', ...(cut ? { clip: { x: slot.x, y: slot.y, width: slot.w, height: slot.h } } : {}) })
|
|
967
|
+
// 套了外框只收槽位里面的元素(外框、被弹窗压在底下的都不算),挪成以槽位左上角为原点
|
|
968
|
+
let blocks = await page.eval(cut ? blocksIn(FRAME_MAIN) : BLOCKS).catch(() => [])
|
|
969
|
+
if (cut) blocks = blocks.filter((b) => b.x < slot.vx + slot.w && b.x + b.w > slot.vx && b.y < slot.vy + slot.h && b.y + b.h > slot.vy).map((b) => ({ ...b, x: b.x - slot.vx, y: b.y - slot.vy }))
|
|
970
|
+
const pageH = cut ? 0 : await page.eval('Math.max(document.documentElement.scrollHeight, innerHeight)').catch(() => 0)
|
|
830
971
|
return { png, blocks, pageH, blocked: page.blocked ? page.blocked.slice() : [] }
|
|
831
972
|
})
|
|
832
973
|
// 一个接一个截:同时开两个页面时系统字体(中文)偶尔还没画好就截了,差异会虚高
|
|
833
|
-
const A = await shoot(design.url, true)
|
|
834
|
-
|
|
974
|
+
const A = await shoot(design.url, true, [w, h])
|
|
975
|
+
if (slot && slot.hidden) return { pct: null, boxes: [], jpg: null, text: `没比:${design.label || design.key} 套了外框,按 ${w}×${h} 开时外框里的 main 槽位露不出来。size 填外框自己的尺寸 ${slot.fw}x${slot.fh} 再比。` }
|
|
976
|
+
const B = await shoot(impl, false, slot ? [slot.w, slot.h] : [w, h]).catch((e) => {
|
|
835
977
|
// 页面自己跳到外网被拦下、截图时页面没了:说清楚是跳走了
|
|
836
978
|
if (blocked.length) throw new Error(`做出来的页面跳到了本机以外的地址,拦下了:${blocked[0].slice(0, 120)}`)
|
|
837
979
|
throw e
|
|
@@ -839,7 +981,9 @@ export async function compareScreens(browser, { design, impl, size, at = 'top',
|
|
|
839
981
|
const labels = ['设计稿', '做出来的', '差异 {pct}%']
|
|
840
982
|
const r = await browser.withPage({ url: 'about:blank', w: 200, h: 200 }, (page) => page.eval(`(${diffIn})(${JSON.stringify(A.png.toString('base64'))}, ${JSON.stringify(B.png.toString('base64'))}, ${JSON.stringify(labels)})`))
|
|
841
983
|
const boxes = r.boxes.map((bx) => ({ ...bx, design: blockAt(A.blocks, bx), impl: blockAt(B.blocks, bx) }))
|
|
842
|
-
const
|
|
984
|
+
const where = slot ? `只比外框里的 main 槽位 ${slot.w}×${slot.h},做出来的页面按这个尺寸开;外框是宿主画的,不算差异` : `${w}×${h}`
|
|
985
|
+
const lines = [`${design.label || design.key}(${where}${at === 'bottom' ? ',滚到底' : ',顶上一屏'}):设计稿 vs ${shown || impl}`]
|
|
986
|
+
if (slot && slot.part) lines.push(`注意:这个尺寸(${w}×${h})装不下整个外框,槽位只露出 ${slot.w}×${slot.h},做出来的页面也只按这么大开;size 填外框自己的尺寸 ${slot.fw}x${slot.fh} 再比。`)
|
|
843
987
|
lines.push(`差异 ${r.pct.toFixed(1)}%(逐像素无损比)${r.pct < 3 ? ':基本一致' : r.pct < 10 ? ':大体对上了,下面几块要改' : ':差得比较多'}`)
|
|
844
988
|
if (B.blocked.length) lines.push(`做出来的页面想跳到本机以外的地址,拦下了:${B.blocked.slice(0, 3).join('、')}`)
|
|
845
989
|
if (A.pageH && B.pageH && Math.abs(A.pageH - B.pageH) > 24) lines.push(`页面高度:设计稿 ${A.pageH}px,做出来的 ${B.pageH}px(差 ${B.pageH - A.pageH > 0 ? '+' : ''}${B.pageH - A.pageH}px,多半是间距 / 字号 / 行高不一样)`)
|
|
@@ -848,5 +992,6 @@ export async function compareScreens(browser, { design, impl, size, at = 'top',
|
|
|
848
992
|
boxes.forEach((b, i) => lines.push(`${i + 1}. 位置 ${b.x},${b.y}(${b.w}×${b.h}):设计稿是 ${describe(b.design)},做出来的是 ${describe(b.impl)}`))
|
|
849
993
|
lines.push('整块挪了位置先查上面的间距和高度;颜色不对查设计变量;字的宽度不一样查字体、字号、字重。')
|
|
850
994
|
} else lines.push('没有成片的差异。')
|
|
851
|
-
|
|
995
|
+
// cmp:比的那块多大(套了外框是槽位);slot:只比了槽位。右侧栏「和做出来的比」按它把红框标回去
|
|
996
|
+
return { pct: r.pct, boxes, jpg: Buffer.from(r.jpg, 'base64'), text: lines.join('\n'), cmp: slot ? [slot.w, slot.h] : [w, h], slot: !!slot }
|
|
852
997
|
}
|
package/lib/impl.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「和做出来的比」(#25):设计稿的每一屏对应做出来的哪个页面、上次比对差了多少
|
|
3
|
+
*
|
|
4
|
+
* - 模型调 compare_design、用户在右侧栏填地址 / 点「重新比」都记一笔:地址、整屏还是只比槽位、深色、尺寸、差异 %、红框
|
|
5
|
+
* - 按设计目录分开记,存在 ~/.dsh/cache/dsh-design-studio/impl.json(重开 DSH 还在);最近的拼图只留在内存里
|
|
6
|
+
* - 右侧栏轮询的状态里带上正在看的设计那份(list),对比视图据此打开真页面、显示分数
|
|
7
|
+
*/
|
|
8
|
+
import fs from 'node:fs'
|
|
9
|
+
import os from 'node:os'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
|
|
12
|
+
export const IMPL_FILE = path.join(os.homedir(), '.dsh', 'cache', 'dsh-design-studio', 'impl.json')
|
|
13
|
+
const MAX_ROOTS = 100 // 最多记这么多个设计目录(最久没碰的先丢)
|
|
14
|
+
const MAX_KEYS = 60 // 一个设计最多这么多屏(和屏数上限一样)
|
|
15
|
+
const MAX_SHOTS = 24 // 内存里留几张拼图
|
|
16
|
+
|
|
17
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)
|
|
18
|
+
const box = (b) => (b && typeof b === 'object' ? { x: Math.round(num(b.x) || 0), y: Math.round(num(b.y) || 0), w: Math.round(num(b.w) || 0), h: Math.round(num(b.h) || 0) } : null)
|
|
19
|
+
|
|
20
|
+
/** 一屏的记录:只留认得的字段(文件可能被手改过) */
|
|
21
|
+
export function cleanRec(r) {
|
|
22
|
+
if (!r || typeof r !== 'object' || typeof r.url !== 'string' || !r.url || r.url.length > 2000) return null
|
|
23
|
+
const out = { url: r.url, whole: r.whole === true, dark: r.dark === true, at: r.at === 'bottom' ? 'bottom' : 'top', by: r.by === 'user' ? 'user' : 'model', when: num(r.when) || 0 }
|
|
24
|
+
if (Array.isArray(r.size) && r.size.length === 2 && r.size.every((n) => Number.isInteger(n) && n > 0 && n < 20000)) out.size = [r.size[0], r.size[1]]
|
|
25
|
+
if (num(r.pct) != null) {
|
|
26
|
+
out.pct = Math.round(r.pct * 10) / 10
|
|
27
|
+
out.boxes = (Array.isArray(r.boxes) ? r.boxes : []).slice(0, 6).map(box).filter((b) => b && b.w > 0 && b.h > 0)
|
|
28
|
+
if (Array.isArray(r.cmp) && r.cmp.length === 2 && r.cmp.every((n) => Number.isInteger(n) && n > 0)) out.cmp = [r.cmp[0], r.cmp[1]] // 比的那块多大(套了外框是槽位)
|
|
29
|
+
out.slot = r.slot === true
|
|
30
|
+
}
|
|
31
|
+
return out
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function createImpl({ file = IMPL_FILE, log = () => {}, now = Date.now } = {}) {
|
|
35
|
+
let data = null // { [设计目录]: { used, screens: { [屏]: 记录 } } }
|
|
36
|
+
const shots = new Map() // `${目录}\n${屏}` → jpg(Buffer)
|
|
37
|
+
let timer = null
|
|
38
|
+
|
|
39
|
+
function load() {
|
|
40
|
+
if (data) return data
|
|
41
|
+
try { data = JSON.parse(fs.readFileSync(file, 'utf8')) } catch { data = {} }
|
|
42
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) data = {}
|
|
43
|
+
return data
|
|
44
|
+
}
|
|
45
|
+
function flush() {
|
|
46
|
+
clearTimeout(timer)
|
|
47
|
+
timer = null
|
|
48
|
+
if (!data) return
|
|
49
|
+
try {
|
|
50
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
51
|
+
const tmp = `${file}.${process.pid}.tmp`
|
|
52
|
+
fs.writeFileSync(tmp, JSON.stringify(data))
|
|
53
|
+
fs.renameSync(tmp, file)
|
|
54
|
+
} catch (e) { log(e) }
|
|
55
|
+
}
|
|
56
|
+
function save() {
|
|
57
|
+
clearTimeout(timer)
|
|
58
|
+
timer = setTimeout(flush, 400)
|
|
59
|
+
if (timer && typeof timer.unref === 'function') timer.unref()
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 这个设计每屏记着的(只读的拷贝,认不出的不给) */
|
|
63
|
+
function list(root) {
|
|
64
|
+
const d = load()[root]
|
|
65
|
+
if (!d || !d.screens || typeof d.screens !== 'object') return {}
|
|
66
|
+
const out = {}
|
|
67
|
+
for (const [k, r] of Object.entries(d.screens)) {
|
|
68
|
+
const c = cleanRec(r)
|
|
69
|
+
if (c) out[k] = c
|
|
70
|
+
}
|
|
71
|
+
return out
|
|
72
|
+
}
|
|
73
|
+
const get = (root, key) => list(root)[key] || null
|
|
74
|
+
|
|
75
|
+
/** 记一笔:patch 合进去;换了地址就把旧分数清掉(那是别的页面的分) */
|
|
76
|
+
function set(root, key, patch) {
|
|
77
|
+
if (!root || !key || typeof key !== 'string' || key.length > 300) return null
|
|
78
|
+
const all = load()
|
|
79
|
+
const d = all[root] && typeof all[root] === 'object' ? all[root] : { screens: {} }
|
|
80
|
+
if (!d.screens || typeof d.screens !== 'object') d.screens = {}
|
|
81
|
+
const was = cleanRec(d.screens[key])
|
|
82
|
+
let next = { ...(was || {}), ...patch, when: now() }
|
|
83
|
+
if (was && patch.url && patch.url !== was.url && patch.pct === undefined) {
|
|
84
|
+
next = { ...next }
|
|
85
|
+
delete next.pct
|
|
86
|
+
delete next.boxes
|
|
87
|
+
delete next.cmp
|
|
88
|
+
delete next.slot
|
|
89
|
+
// 整屏比、比到底是给原来那个页面定的(比如原来的页面连外框一起做了):换了页面回到默认,除非这次说了
|
|
90
|
+
if (patch.whole === undefined) next.whole = false
|
|
91
|
+
if (patch.at === undefined) next.at = 'top'
|
|
92
|
+
shots.delete(`${root}\n${key}`)
|
|
93
|
+
}
|
|
94
|
+
const rec = cleanRec(next)
|
|
95
|
+
if (!rec) return null
|
|
96
|
+
d.screens[key] = rec
|
|
97
|
+
const keys = Object.keys(d.screens)
|
|
98
|
+
if (keys.length > MAX_KEYS) {
|
|
99
|
+
keys.sort((a, b) => (d.screens[a].when || 0) - (d.screens[b].when || 0))
|
|
100
|
+
for (const k of keys.slice(0, keys.length - MAX_KEYS)) delete d.screens[k]
|
|
101
|
+
}
|
|
102
|
+
d.used = now()
|
|
103
|
+
all[root] = d
|
|
104
|
+
const roots = Object.keys(all)
|
|
105
|
+
if (roots.length > MAX_ROOTS) {
|
|
106
|
+
roots.sort((a, b) => (all[a].used || 0) - (all[b].used || 0))
|
|
107
|
+
for (const r of roots.slice(0, roots.length - MAX_ROOTS)) delete all[r]
|
|
108
|
+
}
|
|
109
|
+
save()
|
|
110
|
+
return rec
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function shot(root, key, jpg) {
|
|
114
|
+
const k = `${root}\n${key}`
|
|
115
|
+
if (jpg === undefined) return shots.get(k) || null
|
|
116
|
+
shots.delete(k)
|
|
117
|
+
if (jpg) shots.set(k, jpg)
|
|
118
|
+
while (shots.size > MAX_SHOTS) shots.delete(shots.keys().next().value)
|
|
119
|
+
return jpg
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return { list, get, set, shot, flush }
|
|
123
|
+
}
|