dsh-design-studio 0.25.3 → 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/handoff.js CHANGED
@@ -13,13 +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
22
  import { FRAMES_DIR } from './frames.js'
23
+ import { FRAME_MAIN, SLOT_BOX } from './slot.js'
23
24
 
24
25
  export const HANDOFF_DIR = 'handoff'
25
26
  const MAX_SCREENS = 12
@@ -743,37 +744,6 @@ const IMPL_DARK = `new Promise((res) => {
743
744
  setTimeout(() => res(true), 400)
744
745
  })`
745
746
 
746
- // 套了外框的设计(DSH 插件、外框库):外框是宿主画的,做出来的只有槽位 main 那块 → 只截这块比(#25)
747
- // 返回整页坐标(截图 clip 用)和视口坐标(对元素块用);槽位太小或看不见给 null,照整屏比
748
- // 量的是内容那块:槽位自己的边框、内边距是宿主留的白(DSH 设置分区左右 24px),真插件的页面从内容那块开始
749
- // 外框根和体检一样认:第一个带 data-frame、里面有 data-slot 的元素,而且是登记过的(DSH 自带的四个,或页面里有外框库那段 <template id="dsh-frame">);
750
- // 普通设计里碰巧写了 data-frame 的包裹层(手机示意框之类)不算
751
- const FRAME_MAIN = `(() => {
752
- const f = [...document.querySelectorAll('[data-frame]')].find((x) => x.querySelector('[data-slot]'))
753
- if (!f) return null
754
- if (!/^dsh\\/(sidebar|settings|view|panel)$/.test(f.getAttribute('data-frame') || '') && !document.getElementById('dsh-frame')) return null
755
- return f.querySelector('[data-slot="main"]')
756
- })()`
757
- const SLOT_BOX = `(() => {
758
- const el = ${FRAME_MAIN}
759
- if (!el) return null
760
- const r = el.getBoundingClientRect()
761
- const s = getComputedStyle(el)
762
- const n = (k) => parseFloat(s[k]) || 0
763
- const left = r.left + n('borderLeftWidth') + n('paddingLeft'), top = r.top + n('borderTopWidth') + n('paddingTop')
764
- const right = r.left + n('borderLeftWidth') + el.clientWidth - n('paddingRight'), bottom = r.top + n('borderTopWidth') + el.clientHeight - n('paddingBottom')
765
- const vx = Math.max(0, Math.round(left)), vy = Math.max(0, Math.round(top))
766
- const w = Math.min(Math.round(right), innerWidth) - vx, h = Math.min(Math.round(bottom), innerHeight) - vy
767
- // 外框自己多大:页面开头类型标记里写的(外框库存的「framed 宽x高」),没写就量外框根元素(自带 DSH 外框固定 1280×800)
768
- const mm = /(\\d{3,4})\\s*[x×]\\s*(\\d{3,4})/.exec((document.querySelector('meta[name="dsh-design"]') || {}).content || '')
769
- const fr = el.closest('[data-frame]').getBoundingClientRect()
770
- const fw = mm ? +mm[1] : Math.round(fr.width), fh = mm ? +mm[2] : Math.round(fr.height)
771
- if (w < 40 || h < 40) return { hidden: true, fw, fh } // 认出了外框,但这个尺寸下槽位露不出来:别退回整屏比(会拿外框去比)
772
- // 开的尺寸装不下整个槽位(只露出一部分):照样比露出来的,但要说一声
773
- const part = w < Math.round(right - left) - 1 || h < Math.round(bottom - top) - 1
774
- return { x: vx + Math.round(scrollX), y: vy + Math.round(scrollY), vx, vy, w, h, part, fw, fh }
775
- })()`
776
-
777
747
  /** 做出来的页面只许开本机的:localhost / 127.0.0.1 / ::1 的 http(s)、本地文件(跳转、脚本改地址也一样查) */
778
748
  export function localOnly(u) {
779
749
  let x
@@ -898,26 +868,84 @@ export function blockAt(blocks, bx) {
898
868
 
899
869
  const describe = (b) => (b ? `${b.d}${b.t ? `「${b.t}」` : ''}` : '(空白处)')
900
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
+
901
902
  /** 做出来的页面地址:本机的 http(s),或本地 HTML 文件 */
902
903
  export function implUrl(input, cwd) {
903
904
  const s = String(input || '').trim()
904
- if (/^\d{2,5}$/.test(s)) return `http://localhost:${s}/`
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
+ }
905
911
  if (/^https?:\/\//i.test(s)) {
906
- const u = new URL(s)
912
+ const u = web(s)
907
913
  if (!/^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])$/i.test(u.hostname)) throw new Error('只比本机的页面(localhost 地址或本地 HTML 文件)')
908
914
  return u.href
909
915
  }
910
- if (/^(localhost|127\.0\.0\.1)(:\d+)?(\/|$)/i.test(s)) return 'http://' + s
911
- const p = path.resolve(cwd || '.', s)
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('只比这台电脑上的页面(网络共享里的文件不比)')
912
935
  if (!fs.existsSync(p)) throw new Error(`找不到 ${p}`)
913
- return pathToFileURL(p).href
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
914
942
  }
915
943
 
916
944
  /**
917
945
  * 比一屏:设计稿(预览服务器上的地址,带设计台脚本)vs 做出来的页面,同样尺寸、同样滚动位置。
918
946
  * @returns { pct, boxes: [{ x, y, w, h, design, impl }], jpg, text }
919
947
  */
920
- export async function compareScreens(browser, { design, impl, size, at = 'top', dark = false, whole = false }) {
948
+ export async function compareScreens(browser, { design, impl, shown = '', size, at = 'top', dark = false, whole = false }) {
921
949
  const [w, h] = size
922
950
  // 两边一样准备:等画好 → 深色 → 滚到同一个位置(页面和里面能滚的区域都滚)→ 无损截图
923
951
  // 设计稿套了外框(whole 没要整屏):只截槽位 main,做出来的页面按槽位的尺寸开
@@ -954,7 +982,7 @@ export async function compareScreens(browser, { design, impl, size, at = 'top',
954
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)})`))
955
983
  const boxes = r.boxes.map((bx) => ({ ...bx, design: blockAt(A.blocks, bx), impl: blockAt(B.blocks, bx) }))
956
984
  const where = slot ? `只比外框里的 main 槽位 ${slot.w}×${slot.h},做出来的页面按这个尺寸开;外框是宿主画的,不算差异` : `${w}×${h}`
957
- const lines = [`${design.label || design.key}(${where}${at === 'bottom' ? ',滚到底' : ',顶上一屏'}):设计稿 vs ${impl}`]
985
+ const lines = [`${design.label || design.key}(${where}${at === 'bottom' ? ',滚到底' : ',顶上一屏'}):设计稿 vs ${shown || impl}`]
958
986
  if (slot && slot.part) lines.push(`注意:这个尺寸(${w}×${h})装不下整个外框,槽位只露出 ${slot.w}×${slot.h},做出来的页面也只按这么大开;size 填外框自己的尺寸 ${slot.fw}x${slot.fh} 再比。`)
959
987
  lines.push(`差异 ${r.pct.toFixed(1)}%(逐像素无损比)${r.pct < 3 ? ':基本一致' : r.pct < 10 ? ':大体对上了,下面几块要改' : ':差得比较多'}`)
960
988
  if (B.blocked.length) lines.push(`做出来的页面想跳到本机以外的地址,拦下了:${B.blocked.slice(0, 3).join('、')}`)
@@ -964,5 +992,6 @@ export async function compareScreens(browser, { design, impl, size, at = 'top',
964
992
  boxes.forEach((b, i) => lines.push(`${i + 1}. 位置 ${b.x},${b.y}(${b.w}×${b.h}):设计稿是 ${describe(b.design)},做出来的是 ${describe(b.impl)}`))
965
993
  lines.push('整块挪了位置先查上面的间距和高度;颜色不对查设计变量;字的宽度不一样查字体、字号、字重。')
966
994
  } else lines.push('没有成片的差异。')
967
- return { pct: r.pct, boxes, jpg: Buffer.from(r.jpg, 'base64'), text: lines.join('\n') }
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 }
968
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
+ }
package/lib/index.js CHANGED
@@ -68,7 +68,8 @@ import { SYSTEMS_DIR, extractSystem, listSystems, setDefault, skillSection } fro
68
68
  import { saveFrame, listFrames, frameSection } from './frames.js'
69
69
  import { readTweaks, applyTweaks, lintTweaks } from './tweaks.js'
70
70
  import { readAnnotations, lintAnnotations, annotationFindings, annotationSection } from './annotations.js'
71
- import { FRAMEWORKS, detectProject, projectFor, defaultFramework, buildHandoff, compareScreens, implUrl, defaultDest, pickedDest, within, pinRoots } from './handoff.js'
71
+ import { createImpl } from './impl.js'
72
+ import { FRAMEWORKS, detectProject, projectFor, defaultFramework, buildHandoff, compareScreens, implUrl, implServe, defaultDest, pickedDest, within, pinRoots } from './handoff.js'
72
73
 
73
74
  export const name = 'dsh-design-studio'
74
75
  export const inject = ['webServer']
@@ -94,7 +95,7 @@ const SKILL_RANK = 600 // 和 DSH 自带的技能同一档;用户 / 项目里
94
95
  * 几行之间靠这个互通(同一个包里的模块 Node 只加载一次):工作台起来后放 tracker、无头浏览器(browser);
95
96
  * 「自动打开预览」那行开着时 autoOpen > 0
96
97
  */
97
- export const studio = { tracker: null, autoOpen: 0, offline: 0, annotations: 0, check: null, browser: null, market: null, photos: null, sessionCwd: null, log: () => {} }
98
+ 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: () => {} }
98
99
 
99
100
  /** 设计技能:模型做界面设计时加载(DSH 的 skill 工具),也能让用户手动调 */
100
101
  export const designSkill = {
@@ -698,35 +699,93 @@ export const compareTool = {
698
699
  async execute(args, exec, ctx) {
699
700
  const id = toolSession(exec, '比对')
700
701
  const a = args || {}
701
- const snap = studio.tracker.snapshot(id)
702
- if (!snap.url) return { text: '还没有在预览的设计稿:先用 preview_page 打开设计文件,再比。' }
703
- const b = studio.browser
704
- if (!b || !b.available()) return { text: '这台电脑上没找到 Chrome / Edge(比对要用无头浏览器截图),比不了。' }
705
- const design = designFor(id)
706
- const { kind } = design
707
- const want = a.size ? sizeOf(a.size, kind) : await fitted(b, design, typeof a.screen === 'string' && a.screen.trim() ? [a.screen] : null)
708
- if (!want) return { text: `认不出尺寸「${String(a.size).slice(0, 20)}」:写成 375x667,或只写宽度 375。` }
709
- // 指定了哪屏就只认那屏,找不到就说(别悄悄拿第一屏比,结果对不上号);没指定才用正在看的 / 第一屏
710
- const asked = typeof a.screen === 'string' && a.screen.trim()
711
- const pick = pickScreens(snap, asked ? [a.screen] : [snap.focus], 1)
712
- const sc = pick.list[0] || (asked ? null : pickScreens(snap, null, 1).list[0])
713
- if (!sc) return { text: `没找到设计稿的这一屏:${asked ? a.screen : '(没有屏)'}。现在有:${(snap.screens || []).map((x) => x.key).join('、')}` }
714
- let impl
715
- try { impl = implUrl(a.url, studio.tracker.cwdOf(id)) } catch (e) { return { text: e.message } }
716
- if (snap.origin && impl.startsWith(snap.origin + '/')) return { text: '这个地址是设计稿自己(设计工作台的预览),给做出来的那个项目的地址。' }
717
- let r
718
- try {
719
- r = await compareScreens(b, { design: sc, impl, size: want, at: a.at === 'bottom' ? 'bottom' : 'top', dark: !!a.dark, whole: a.whole === true })
720
- } catch (e) {
721
- return { text: `没比成:${String((e && e.message) || e).slice(0, 200)}(做出来的页面打得开吗?开发服务器起来了吗?)` }
722
- }
723
- if (!r.jpg) return { text: r.text } // 没截图就停下了(套了外框但槽位露不出来)
724
- const kept = await keepImages(ctx, id, [{ key: `compare-${sc.key}`, jpg: r.jpg }], true)
725
- if (kept.images) return { text: r.text, images: kept.images }
726
- return { text: `${r.text}\n(这个 DSH 版本没法把图直接给你,存成了文件:${kept.files.join('、')})` }
702
+ const out = await runCompare(id, a)
703
+ if (!out.r) return { text: out.text }
704
+ keepImpl(id, out, 'model', !!a.size)
705
+ if (!out.r.jpg) return { text: out.r.text } // 没截图就停下了(套了外框但槽位露不出来)
706
+ const kept = await keepImages(ctx, id, [{ key: `compare-${out.sc.key}`, jpg: out.r.jpg }], true)
707
+ if (kept.images) return { text: out.r.text, images: kept.images }
708
+ return { text: `${out.r.text}\n(这个 DSH 版本没法把图直接给你,存成了文件:${kept.files.join('、')})` }
727
709
  },
728
710
  }
729
711
 
712
+ /** 设计记在哪个名下:本地设计按目录,开发服务器的按端口 */
713
+ /** 填的本地文件就是设计稿自己的某一屏(设计目录里登记的那几个文件):不算做出来的 */
714
+ export const isDesignFile = (at, u) => {
715
+ if (u.protocol !== 'file:' || !at.snap.target || at.snap.target.kind !== 'file') return false
716
+ try {
717
+ const rel = path.relative(path.resolve(at.root), fileURLToPath(u)).split(path.sep).join('/')
718
+ return !rel.startsWith('..') && (at.snap.screens || []).some((x) => x.key === rel)
719
+ } catch { return false }
720
+ }
721
+ export const implRoot = (snap) => (snap && snap.target ? (snap.target.kind === 'file' ? snap.target.root : `proxy:${snap.target.port}`) : '')
722
+
723
+ /**
724
+ * 比一屏(compare_design 和右侧栏「和做出来的比」里的「重新比」共用)
725
+ * a: { url, screen, size, at, dark, whole }
726
+ * @returns { text } 没比成;{ r, sc, impl, want, opts, root } 比完了(r.jpg 为空 = 套了外框但槽位露不出来,r.text 说了怎么办;
727
+ * root:开始比时在看的设计,比的时候换了设计也记回这一份)
728
+ */
729
+ async function runCompare(id, a) {
730
+ const snap = studio.tracker.snapshot(id)
731
+ const root = implRoot(snap)
732
+ if (!snap.url) return { text: '还没有在预览的设计稿:先用 preview_page 打开设计文件,再比。' }
733
+ const b = studio.browser
734
+ if (!b || !b.available()) return { text: '这台电脑上没找到 Chrome / Edge(比对要用无头浏览器截图),比不了。' }
735
+ const design = designFor(id)
736
+ const { kind } = design
737
+ const want = Array.isArray(a.size) ? a.size : a.size ? sizeOf(a.size, kind) : await fitted(b, design, typeof a.screen === 'string' && a.screen.trim() ? [a.screen] : null)
738
+ if (!want) return { text: `认不出尺寸「${String(a.size).slice(0, 20)}」:写成 375x667,或只写宽度 375。` }
739
+ // 指定了哪屏就只认那屏,找不到就说(别悄悄拿第一屏比,结果对不上号);没指定才用正在看的 / 第一屏
740
+ const asked = typeof a.screen === 'string' && a.screen.trim()
741
+ const pick = pickScreens(snap, asked ? [a.screen] : [snap.focus], 1)
742
+ const sc = pick.list[0] || (asked ? null : pickScreens(snap, null, 1).list[0])
743
+ if (!sc) return { text: `没找到设计稿的这一屏:${asked ? a.screen : '(没有屏)'}。现在有:${(snap.screens || []).map((x) => x.key).join('、')}` }
744
+ // 相对路径、本地 HTML 的预览根:先问 DSH 会话目录(和右侧栏填地址一样),问不到才用记着的
745
+ let cwd = ''
746
+ try { cwd = studio.sessionCwd ? await studio.sessionCwd(id) : '' } catch { cwd = '' }
747
+ if (!cwd) cwd = studio.tracker.cwdOf(id)
748
+ let impl
749
+ try { impl = implUrl(a.url, cwd) } catch (e) { return { text: e.message } }
750
+ if ((snap.origin && impl.startsWith(snap.origin + '/')) || isDesignFile({ snap, root }, new URL(impl))) return { text: '这个地址是设计稿自己(设计工作台的预览或设计目录里的文件),给做出来的那个项目的地址。' }
751
+ const opts = { at: a.at === 'bottom' ? 'bottom' : 'top', dark: !!a.dark, whole: a.whole === true }
752
+ let r
753
+ try {
754
+ // 本地 HTML 经预览服务器(http)打开再截:直接开 file:// 时 Vite 这类打包出来的模块脚本、/assets 这种根路径都载不出来(和右侧栏里看到的一样)
755
+ let shotUrl = impl
756
+ if (/^file:/i.test(impl) && studio.openPreview) {
757
+ const u = new URL(impl)
758
+ const s = implServe(fileURLToPath(u), cwd)
759
+ const p = await studio.openPreview({ kind: 'file', root: s.root })
760
+ shotUrl = `${p.origin}${s.rel}${u.search}${u.hash}`
761
+ }
762
+ r = await compareScreens(b, { design: sc, impl: shotUrl, shown: impl, size: want, ...opts })
763
+ } catch (e) {
764
+ return { text: `没比成:${String((e && e.message) || e).slice(0, 200)}(做出来的页面打得开吗?开发服务器起来了吗?)` }
765
+ }
766
+ return { r, sc, impl, want, opts, root }
767
+ }
768
+
769
+ /** 比完记一笔(右侧栏「和做出来的比」显示分数、标红框);by:model 模型比的 / user 右侧栏点的 */
770
+ function keepImpl(id, out, by, sizeGiven) {
771
+ const store = studio.impl
772
+ const root = out.root
773
+ if (!store || !root || !out.sc) return null
774
+ const { r } = out
775
+ // 这次没比成分数(套了外框、槽位露不出来):地址没变就不动原来的记录(旧分数别标成这次比的)
776
+ if (typeof r.pct !== 'number') {
777
+ const cur = store.get(root, out.sc.key)
778
+ if (cur && cur.url === out.impl) return cur
779
+ return store.set(root, out.sc.key, { url: out.impl, ...out.opts, by })
780
+ }
781
+ const rec = store.set(root, out.sc.key, {
782
+ url: out.impl, ...out.opts, by, size: sizeGiven ? out.want : undefined,
783
+ ...(typeof r.pct === 'number' ? { pct: r.pct, boxes: r.boxes, cmp: r.cmp, slot: r.slot } : {}),
784
+ })
785
+ if (r.jpg) store.shot(root, out.sc.key, r.jpg)
786
+ return rec
787
+ }
788
+
730
789
  /** 工具结果显示成:文字 + 一张张图 */
731
790
  function withImages(value) {
732
791
  const blocks = [{ type: 'text', text: value.text }]
@@ -888,6 +947,7 @@ export function apply(ctx) {
888
947
  },
889
948
  })
890
949
  ctx.effect(() => () => { drafts.clear(); hub.closeAll() }, 'dsh-design-studio: preview servers')
950
+ const implStore = createImpl({ log }) // 「和做出来的比」:每屏对应的页面地址、上次比对的分数
891
951
  ctx.effect(() => {
892
952
  studio.tracker = tracker
893
953
  studio.log = log
@@ -896,7 +956,11 @@ export function apply(ctx) {
896
956
  const photos = photoIndex ? createPhotos({ market, index: photoIndex, log }) : null
897
957
  studio.photos = photos
898
958
  studio.sessionCwd = sessionCwd
959
+ studio.impl = implStore
960
+ studio.openPreview = open
899
961
  return () => {
962
+ if (studio.impl === implStore) { implStore.flush(); studio.impl = null }
963
+ if (studio.openPreview === open) studio.openPreview = null
900
964
  if (studio.tracker === tracker) { studio.tracker = null; studio.log = () => {} }
901
965
  if (studio.market === market) { market.abort(); studio.market = null }
902
966
  if (studio.photos === photos) studio.photos = null
@@ -982,7 +1046,7 @@ export function apply(ctx) {
982
1046
  let tweaks = null
983
1047
  if (t && t.kind === 'file') { try { tweaks = readTweaks(t.root) } catch (e) { log(e) } }
984
1048
  const snap = tracker.snapshot(session)
985
- json(res, 200, { ...snap, strict: strictScreens(snap), phone: { on: ph.on, seen: ph.seen || 0 }, tweaks, ...annotsField(session, new URL(req.url, 'http://x').searchParams.get('an')), ...(c ? { checkReq: c.id } : {}) })
1049
+ json(res, 200, { ...snap, impl: implStore.list(implRoot(snap)), strict: strictScreens(snap), phone: { on: ph.on, seen: ph.seen || 0 }, tweaks, ...annotsField(session, new URL(req.url, 'http://x').searchParams.get('an')), ...(c ? { checkReq: c.id } : {}) })
986
1050
  }
987
1051
 
988
1052
  /** 正在看的几屏里,哪些是别人做的、没改过的(地址列表):右侧栏给它们的 iframe 加沙盒、不给剪贴板 */
@@ -1026,6 +1090,108 @@ export function apply(ctx) {
1026
1090
  }
1027
1091
  }
1028
1092
 
1093
+ // ── 和做出来的比(#25)────────────────────────────────────────────────────
1094
+
1095
+ /** 这个会话正在看的设计里有这一屏:{ snap, root },没有给 null */
1096
+ const implScreen = (session, key) => {
1097
+ const snap = tracker.snapshot(session)
1098
+ const root = implRoot(snap)
1099
+ if (!root || !key || !(snap.screens || []).some((x) => x.key === key)) return null
1100
+ return { snap, root }
1101
+ }
1102
+ /** 填的本地文件就是设计稿里的某一屏(拿设计稿和自己比) */
1103
+
1104
+ /**
1105
+ * POST { session, screen, url?, whole? } → { url, live, rec }
1106
+ * 填了地址(或改了整屏 / 只比槽位)先记下;再按记着的地址开一个预览服务器(开发服务器走代理、热更新照常;本地 HTML 按目录开),
1107
+ * 页面里注入设计台脚本(两边滚动同步)。地址只认本机的,不能是设计稿自己
1108
+ */
1109
+ async function implRoute(req, res) {
1110
+ if (!admit(req, res)) return
1111
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1112
+ let body
1113
+ try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
1114
+ const session = String(body.session || '')
1115
+ const key = String(body.screen || '')
1116
+ const at = implScreen(session, key)
1117
+ if (!at) return json(res, 404, { error: 'no-screen' })
1118
+ let rec = implStore.get(at.root, key)
1119
+ let url = rec ? rec.url : ''
1120
+ // 相对路径按会话目录算(新会话也问 DSH 要,和「打开本地设计」一样);本地 HTML 的预览根也不出会话目录
1121
+ // 用户填的:按 DSH 里这个会话的目录算(模型可能在子目录跑过工具,记着的不一定是会话目录)
1122
+ let cwd = ''
1123
+ try { cwd = await dshCwd(session) } catch { cwd = '' }
1124
+ if (!cwd) cwd = tracker.cwdOf(session)
1125
+ if (typeof body.url === 'string' && body.url.trim()) {
1126
+ try { url = implUrl(body.url.trim().slice(0, 2000), cwd) } catch (e) { return json(res, 400, { error: 'bad-url', msg: e.message }) }
1127
+ }
1128
+ if (!url) return json(res, 404, { error: 'no-url' })
1129
+ let u = null
1130
+ try { u = new URL(url) } catch { /* 记录文件被手改坏了 */ }
1131
+ if (!u || !/^(https?|file):$/.test(u.protocol)) return json(res, 400, { error: 'bad-url', msg: '' })
1132
+ const port = Number(u.port || (u.protocol === 'https:' ? 443 : 80))
1133
+ // 设计稿自己(预览地址、或设计目录里的那几屏文件)、设计台别的预览页、DSH 自己的网页:都不是做出来的项目
1134
+ const own = Number(ownHost(ctx).split(':')[1]) || 0
1135
+ if ((at.snap.origin && url.startsWith(at.snap.origin + '/')) || (u.protocol !== 'file:' && (previewPorts.has(port) || port === own)) || isDesignFile(at, u)) return json(res, 400, { error: 'self' })
1136
+ if (u.protocol === 'https:') return json(res, 400, { error: 'https' }) // 代理只会接 http 的开发服务器
1137
+ if (url !== (rec && rec.url) || (typeof body.whole === 'boolean' && body.whole !== (rec && rec.whole))) {
1138
+ rec = implStore.set(at.root, key, { url, by: 'user', ...(typeof body.whole === 'boolean' ? { whole: body.whole } : {}) })
1139
+ }
1140
+ let live
1141
+ try {
1142
+ if (u.protocol === 'file:') {
1143
+ const s = implServe(fileURLToPath(u), cwd)
1144
+ const r = await open({ kind: 'file', root: s.root })
1145
+ live = `${r.origin}${s.rel}${u.search}${u.hash}`
1146
+ } else {
1147
+ const r = await open({ kind: 'proxy', port })
1148
+ live = r.origin + u.pathname + u.search + u.hash
1149
+ }
1150
+ } catch (e) {
1151
+ log(e)
1152
+ return json(res, 500, { error: 'open', msg: String((e && e.message) || e).slice(0, 200) })
1153
+ }
1154
+ json(res, 200, { url, live, rec })
1155
+ }
1156
+
1157
+ /** POST { session, screen, size, dark } → 照记着的地址在无头浏览器里比一次(和 compare_design 一样),记下分数 → { rec, text } */
1158
+ async function implCmpRoute(req, res) {
1159
+ if (!admit(req, res)) return
1160
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1161
+ let body
1162
+ try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
1163
+ const session = String(body.session || '')
1164
+ const key = String(body.screen || '')
1165
+ const at = implScreen(session, key)
1166
+ if (!at) return json(res, 404, { error: 'no-screen' })
1167
+ const rec = implStore.get(at.root, key)
1168
+ if (!rec) return json(res, 404, { error: 'no-url' })
1169
+ // 眼前看的不是记录里的地址了(模型刚换了地址、画面还没跟上):不比,等画面换过去
1170
+ if (typeof body.url === 'string' && body.url && body.url !== rec.url) return json(res, 200, { error: 'stale' })
1171
+ // 画幅能设 100–8000(自定义画幅):照眼前的比,不走模型那边 200 起的尺寸规矩
1172
+ const m = typeof body.size === 'string' ? /^(\d{2,5})x(\d{2,5})$/.exec(body.size) : null
1173
+ const size = m && +m[1] >= 100 && +m[2] >= 100 && +m[1] <= 8000 && +m[2] <= 8000 ? [+m[1], +m[2]] : rec.size ? rec.size.join('x') : ''
1174
+ const out = await runCompare(session, { url: rec.url, screen: key, size, at: rec.at, dark: typeof body.dark === 'boolean' ? body.dark : rec.dark, whole: rec.whole })
1175
+ if (!out.r) return json(res, 200, { error: 'failed', text: out.text })
1176
+ // 比的这会儿换了设计、或这屏改填了别的地址:这次的分数不算数,别写回去
1177
+ const now = implStore.get(at.root, key)
1178
+ if (out.root !== at.root || implRoot(tracker.snapshot(session)) !== at.root || !now || now.url !== rec.url) return json(res, 200, { error: 'stale' })
1179
+ const next = keepImpl(session, out, 'user', !!size)
1180
+ json(res, 200, { rec: next, text: out.r.text, ok: !!out.r.jpg })
1181
+ }
1182
+
1183
+ /** GET ?session=&screen= → 最近一次比对的拼图(设计稿 | 做出来的 | 差异) */
1184
+ function implShotRoute(req, res) {
1185
+ if (!admit(req, res)) return
1186
+ const q = new URL(req.url, 'http://x').searchParams
1187
+ const key = q.get('screen') || ''
1188
+ const at = implScreen(q.get('session') || '', key)
1189
+ const jpg = at ? implStore.shot(at.root, key) : null
1190
+ if (!jpg) return json(res, 404, { error: 'none' })
1191
+ res.writeHead(200, { 'Content-Type': 'image/jpeg', 'Content-Length': jpg.length, 'Cache-Control': 'no-store' })
1192
+ res.end(jpg)
1193
+ }
1194
+
1029
1195
  /** 外框库:GET 列出来(首页「套外框」下面挑外框用) */
1030
1196
  function framesRoute(req, res) {
1031
1197
  if (!admit(req, res)) return
@@ -1563,6 +1729,10 @@ export function apply(ctx) {
1563
1729
  async function sessionCwd(id) {
1564
1730
  const known = tracker.cwdOf(id)
1565
1731
  if (known && path.resolve(known) !== path.resolve(os.homedir())) return known
1732
+ return (await dshCwd(id)) || known
1733
+ }
1734
+ /** DSH 里这个会话的目录(会话头里记的);问不到回空 */
1735
+ async function dshCwd(id) {
1566
1736
  const ok = (c) => typeof c === 'string' && path.isAbsolute(c) ? c : ''
1567
1737
  try {
1568
1738
  const ss = ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : null
@@ -1578,7 +1748,7 @@ export function apply(ctx) {
1578
1748
  if (c) return c
1579
1749
  }
1580
1750
  } catch (e) { log(e) }
1581
- return known
1751
+ return ''
1582
1752
  }
1583
1753
  const lib = createLibraryRoutes({ admit, readBody, json, tracker, library, inspiration, studio, open, storeLoad: fileStore.load, version: VERSION, exported, log, sessionCwd, vocab: () => market.vocab() })
1584
1754
  // 画布上睡着的屏的缩略图(issue #17)
@@ -1594,7 +1764,7 @@ export function apply(ctx) {
1594
1764
  })
1595
1765
  const mk = createMarketRoutes({ admit, readBody, json, tracker, library, market, open, systemsDir: SYSTEMS_DIR, log, sessionCwd })
1596
1766
 
1597
- const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, 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, edit: editRoute, style: styleRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute }
1767
+ const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, 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, edit: editRoute, style: styleRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute, impl: implRoute, implcmp: implCmpRoute, implshot: implShotRoute }
1598
1768
  for (const [key, handler] of Object.entries(routes)) {
1599
1769
  ctx.effect(() => ctx.webServer.register({
1600
1770
  kind: 'exact',