dsh-design-studio 1.3.0 → 1.4.1

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
@@ -14,6 +14,7 @@ import { isLibFontRel, loadFontIndex } from './fonts.js'
14
14
  import fs from 'node:fs'
15
15
  import os from 'node:os'
16
16
  import path from 'node:path'
17
+ import { createHash, randomUUID } from 'node:crypto'
17
18
  import { pathToFileURL, fileURLToPath } from 'node:url'
18
19
  import { prepare } from './look.js'
19
20
  import { allScreens } from './core.js'
@@ -23,7 +24,10 @@ import { tokensOf } from './system.js'
23
24
  import { FRAMES_DIR } from './frames.js'
24
25
  import { FRAME_MAIN, SLOT_BOX } from './slot.js'
25
26
  import { statesOfHtml } from './states.js'
26
- import { mockOf } from './mock.js'
27
+ import { mockExpr, mockOf } from './mock.js'
28
+ import { componentFiles, dirReader, expandPreview } from './comp-io.js'
29
+ import { catalog as componentCatalog } from './components.js'
30
+ import { tokenize } from './gallery/html.js'
27
31
 
28
32
  /**
29
33
  * 交接文档里的「页面状态」:写了几个状态的屏,列出状态、各状态用到的样式条数、哪些按钮会切到哪个状态
@@ -48,7 +52,7 @@ export function statesMd(htmlByKey, css = '') {
48
52
  * 交接文档里的「模拟数据」(#30):设计目录里有 mock.json 才有。原型的数据都在这一份里、各屏用 data-mock-* 绑上;
49
53
  * 转代码时做成一份初始数据 + 全局状态,页面从状态里读、点了改状态
50
54
  */
51
- export function mockMd(htmlByKey, root) {
55
+ export function mockMd(htmlByKey, root, savedNotes = null) {
52
56
  const m = mockOf(root)
53
57
  if (!m) return []
54
58
  const top = Object.keys(m.data)
@@ -58,31 +62,40 @@ export function mockMd(htmlByKey, root) {
58
62
  ]
59
63
  const topSet = new Set(top)
60
64
  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} 处` : ''}`)
65
+ const notes = savedNotes || [...htmlByKey].map(([key, html]) => mockNotes(key, html, topSet))
66
+ for (const note of notes) {
67
+ if (!note) continue
68
+ if (note.line) out.push(note.line)
69
+ follow.push(...note.follow)
77
70
  }
78
71
  if (follow.length) out.push(`- 状态跟着数据走的屏:${follow.slice(0, 8).join('、')}——这几屏的状态别放在页面自己里,读全局状态的那个字段(一处改了所有页一起变)。`)
79
72
  return out
80
73
  }
81
74
 
75
+ function mockNotes(key, html, topSet) {
76
+ html = String(html)
77
+ const follow = []
78
+ for (const [tag] of html.matchAll(/<meta\b[^>]*>/gi)) {
79
+ if (!/\bname\s*=\s*["']?dsh-states["'\s/>]/i.test(tag)) continue
80
+ const d = /\bdata-mock\s*=\s*["']([^"']+)["']/i.exec(tag)
81
+ if (d) follow.push(`${key}(${d[1].trim()})`)
82
+ }
83
+ const used = new Set()
84
+ let sets = 0
85
+ for (const a of html.matchAll(/\sdata-mock-(text|show|each|set|model|class|attr)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)) {
86
+ if (a[1].toLowerCase() === 'set') sets++
87
+ const v = (a[2] !== undefined ? a[2] : a[3] || '').replace(/'[^']*'|"[^"]*"/g, ' ')
88
+ 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])
89
+ }
90
+ const fields = [...used].slice(0, 8).map((x) => '`' + x + '`').join('、')
91
+ const line = used.size || sets ? `- ${key}:用到 ${fields || '(只有改数据的按钮)'}${used.size > 8 ? ` 等 ${used.size} 个字段` : ''}${sets ? `;点了改数据 ${sets} 处` : ''}` : ''
92
+ return { line, follow }
93
+ }
94
+
82
95
  export const HANDOFF_DIR = 'handoff'
83
96
  /** 版本名里哪些是用户在右侧栏亲手改的(见 core.js:改字、调样式、调节滑块) */
84
97
  const TUNED = /^(改字「|调样式「|调节:)/
85
- const MAX_SCREENS = 12
98
+ export const HANDOFF_BATCH_SIZE = 12
86
99
  const MAX_PARTS = 3 // 每屏最多截几段
87
100
 
88
101
  export const FRAMEWORKS = {
@@ -325,6 +338,88 @@ export function pagePathOf(key, target = 'uniapp') {
325
338
  return `pages/${b}/${target === 'taro' ? 'index' : b}`
326
339
  }
327
340
 
341
+ /** 交接和比对共用设计清单,顺序跟 allScreens(设计清单 / 创建顺序)一致。 */
342
+ export function handoffScreens(root, origin = '') {
343
+ const keys = allScreens(root)
344
+ const stems = keys.map((key) => key.replace(/\.html?$/i, ''))
345
+ const counts = new Map()
346
+ for (const stem of stems) counts.set(stem.toLowerCase(), (counts.get(stem.toLowerCase()) || 0) + 1)
347
+ return keys.map((key, i) => {
348
+ const label = stems[i]
349
+ // 同名的 .htm / .html 各有自己的截图,保留其他屏的旧文件名。
350
+ const shotStem = label.startsWith('~') || counts.get(label.toLowerCase()) > 1 ? '~' + createHash('sha1').update(key).digest('hex') : label
351
+ const url = origin ? `${origin}/${encodeURIComponent(key)}` : pathToFileURL(path.join(root, key)).href
352
+ return { key, label, url, route: routeOf(key), shotStem, batch: Math.floor(i / HANDOFF_BATCH_SIZE) + 1 }
353
+ })
354
+ }
355
+
356
+ export function findHandoffScreen(screens, name) {
357
+ const raw = String(name ?? '').trim()
358
+ const key = raw.replace(/^\.?\//, '')
359
+ const norm = key.replace(/\.html?$/i, '').toLowerCase()
360
+ return screens.find((sc) => sc.key === key) || (norm && screens.find((sc) => sc.key.replace(/\.html?$/i, '').toLowerCase() === norm || sc.label?.toLowerCase() === norm)) || screens.find((sc) => raw && sc.route === raw)
361
+ }
362
+
363
+ export function handoffBatch(catalog, { batch = 1, names } = {}) {
364
+ const total = Math.ceil(catalog.length / HANDOFF_BATCH_SIZE)
365
+ if (Array.isArray(names) && names.length) {
366
+ const chosen = new Set()
367
+ const missing = []
368
+ for (const name of names) {
369
+ const sc = findHandoffScreen(catalog, name)
370
+ if (sc) chosen.add(sc)
371
+ else missing.push(String(name).slice(0, 60))
372
+ }
373
+ if (chosen.size > HANDOFF_BATCH_SIZE) return { error: `一次最多截 ${HANDOFF_BATCH_SIZE} 屏。请减少 screens,或用 batch 按批截图(共 ${total} 批)。` }
374
+ return { list: [...chosen], missing }
375
+ }
376
+ if (!Number.isSafeInteger(batch) || batch < 1 || (total && batch > total)) return { error: `batch 要填 1 到 ${total || 1} 的整数。` }
377
+ return { list: catalog.filter((sc) => sc.batch === batch), missing: [], batch }
378
+ }
379
+
380
+ /** 未截图也能列出源码里的静态跳转。截图时再补运行页面产生的链接。 */
381
+ function sourceRow(sc, raw) {
382
+ const html = String(raw || '').replace(/<!--[\s\S]*?-->|<(script|style|textarea)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, '')
383
+ const title = /<title\b[^>]*>([^<]*)<\/title\s*>/i.exec(html)?.[1].trim().slice(0, 40) || ''
384
+ const pageUrl = new URL(sc.url)
385
+ const here = pageUrl.protocol === 'file:' ? new URL('http://localhost/' + encodeURIComponent(sc.key)) : pageUrl
386
+ const links = new Set()
387
+ for (const [tag, tagName] of html.matchAll(/<([a-z][\w-]*)\b(?:[^"'>]|"[^"]*"|'[^']*')*>/gi)) {
388
+ const attrs = new Map()
389
+ for (const [, key, a, b, c] of tag.slice(tagName.length + 1, -1).matchAll(/([^\s=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g)) attrs.set(key.toLowerCase(), a ?? b ?? c)
390
+ const js = /(?:location(?:\.href)?\s*=\s*|location\.(?:assign|replace)\(\s*)['"]([^'"]+)['"]/.exec(attrs.get('onclick') || '')
391
+ const rawLink = ((tagName.toLowerCase() === 'a' && attrs.get('href')) || attrs.get('data-href') || attrs.get('data-to') || js?.[1] || '').trim()
392
+ if (!rawLink || rawLink.startsWith('#')) continue
393
+ try {
394
+ const url = new URL(rawLink.replace(/&amp;/gi, '&'), here)
395
+ if (url.origin !== here.origin || url.protocol !== here.protocol) continue
396
+ links.add(decodeURIComponent(url.pathname))
397
+ } catch { /* 不是可识别的页面地址 */ }
398
+ }
399
+ return { title, links: [...links].map((path) => ({ path })) }
400
+ }
401
+
402
+ const mockPaths = mockExpr()
403
+
404
+ /** 从页面调用处取动态参数,组件定义自身的 mock 字段另由组件清单提供。 */
405
+ function collectInstancePaths(raw, contracts) {
406
+ for (const t of tokenize(raw)) {
407
+ if (t.type !== 'tag' || !t.tag.name.startsWith('c-')) continue
408
+ const contract = contracts.get(t.tag.name.slice(2))
409
+ if (!contract) continue
410
+ for (const a of t.tag.attrs) {
411
+ if (!a.name.startsWith(':') || !contract.params.has(a.name.slice(1))) continue
412
+ const value = a.value.trim()
413
+ try {
414
+ const ast = mockPaths.parse(value)
415
+ if (ast.t === 'path' && ast.segs.every((s) => s.t === 'lit' &&
416
+ ['number', 'string'].includes(typeof s.v) && !mockPaths.BAD.has(String(s.v))) &&
417
+ !mockPaths.lex(value).some((token) => token.k === 'op' && ['(', ')'].includes(token.v))) contract.paths.add(value)
418
+ } catch { /* 无效绑定交给组件体检 */ }
419
+ }
420
+ }
421
+ }
422
+
328
423
  const CLASS_TAGS = /^(header|nav|footer|aside|section|div|a|button|ul|ol|li|form|article|main|figure)$/
329
424
 
330
425
  /** 页面套了登记过的外框:DSH 自带的四个(data-frame="dsh/…"),或带外框库那段 <template id="dsh-frame">;还得有槽位。和体检、compare_design 一个认法 */
@@ -393,6 +488,8 @@ export function sharedParts(htmlByKey) {
393
488
  }
394
489
 
395
490
  const pascal = (s) => s.replace(/(^|[-_]+)([a-z0-9])/gi, (_m, _a, c) => c.toUpperCase())
491
+ const shotName = (sc, part) => `${sc.shotStem}-${part}.jpg`
492
+ const desktopShots = (sc) => Array.from({ length: MAX_PARTS }, (_, i) => shotName(sc, i + 1))
396
493
 
397
494
  /** 截图 + 每屏的标题、跳转:每屏在无头浏览器里按设计尺寸开一次,从上到下截几段 */
398
495
  async function shootScreens(browser, screens, size, kind, dir) {
@@ -410,7 +507,7 @@ async function shootScreens(browser, screens, size, kind, dir) {
410
507
  const of = Math.min(MAX_PARTS, (s0 && s0.of) || 1)
411
508
  for (let p = 0; p < of; p++) {
412
509
  if (p) await page.eval(`window.__dshDesign.scroll(${p})`)
413
- const name = `${sc.key.replace(/\.html?$/i, '')}-${p + 1}.jpg`
510
+ const name = shotName(sc, p + 1)
414
511
  fs.writeFileSync(path.join(dir, name), await page.shot())
415
512
  row.shots.push(name)
416
513
  }
@@ -420,13 +517,16 @@ async function shootScreens(browser, screens, size, kind, dir) {
420
517
  if (kind === 'web' && w > 600) {
421
518
  await browser.withPage({ url: sc.url, w: 390, h: 844 }, async (page) => {
422
519
  await prepare(page, false)
423
- const name = `${sc.key.replace(/\.html?$/i, '')}-mobile.jpg`
520
+ const name = shotName(sc, 'mobile')
424
521
  fs.writeFileSync(path.join(dir, name), await page.shot())
425
522
  row.mobile = name
426
523
  })
427
524
  }
428
525
  } catch (e) {
429
526
  row.error = String((e && e.message) || e).slice(0, 120)
527
+ row.shots = []
528
+ delete row.mobile
529
+ delete row.more
430
530
  }
431
531
  out[i] = row
432
532
  }))
@@ -438,11 +538,55 @@ export function unlinkIfLink(file) {
438
538
  try { if (fs.lstatSync(file).isSymbolicLink()) fs.unlinkSync(file) } catch { /* 没有 */ }
439
539
  }
440
540
 
541
+ function writeHandoffFile(file, text) {
542
+ const temp = path.join(path.dirname(file), `.handoff-${randomUUID()}`)
543
+ try {
544
+ fs.writeFileSync(temp, text, { flag: 'wx' })
545
+ unlinkIfLink(file)
546
+ fs.renameSync(temp, file)
547
+ } finally {
548
+ fs.rmSync(temp, { force: true })
549
+ }
550
+ }
551
+
552
+ function styleSheets(root, frames = []) {
553
+ try { return fs.readdirSync(root).filter((n) => /\.css$/i.test(n) && n !== 'tokens.css' && !frames.includes(n)) } catch { return [] }
554
+ }
555
+
556
+ function screenStyles(root, sheets) {
557
+ return [...sheets, 'tokens.css'].map((n) => readText(path.join(root, n)) || '').join('\n')
558
+ }
559
+
560
+ function screenNotes(key, html, css, mockData) {
561
+ const scripts = [...html.matchAll(/<script\b(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi)].filter((m) => m[1].trim()).length
562
+ // 外框上的表单、跳转由宿主负责,页面脚本仍按整页数。
563
+ const inner = slotHtml(html)
564
+ const forms = (inner.match(/<(input|textarea|select)\b/gi) || []).length
565
+ const inter = []
566
+ if (scripts) inter.push(`${scripts} 段脚本(改成框架里的状态和事件)`)
567
+ if (forms) inter.push(`${forms} 个输入控件(做成受控组件、加校验和出错状态)`)
568
+ if (/data-href=/.test(inner)) inter.push('用 data-href 跳转的元素(改成路由跳转)')
569
+ return {
570
+ inter: inter.length ? `- ${key}:${inter.join(';')}` : '',
571
+ states: statesMd(new Map([[key, html]]), css),
572
+ mock: mockData ? mockNotes(key, html, new Set(Object.keys(mockData.data))) : null,
573
+ back: /\sdata-back\b/i.test(inner),
574
+ hover: (html.match(/:(hover|focus-visible|focus|active)\b/g) || []).length,
575
+ }
576
+ }
577
+
441
578
  /**
442
- * 生成交接包。screens:[{ key, url, label }](预览服务器上的地址);root:设计目录。
443
- * @returns { file, dir, md, shots, rows }
579
+ * 生成交接包。catalog / selection 共用工具选出的完整清单和本批;screens 兼容旧调用的截图 URL。
444
580
  */
445
- export async function buildHandoff(browser, { root, screens, kind = 'web', size = [1280, 800], framework = 'react', dest = '', project = null, system = '', annotations = null, tuned = [], now = new Date() }) {
581
+ export async function buildHandoff(browser, { root, catalog = handoffScreens(root), selection, screens, batch, kind = 'web', size = [1280, 800], framework = 'react', dest = '', project = null, system = '', annotations = null, tuned = [], now = new Date() }) {
582
+ const overrides = new Map((screens || []).filter((sc) => typeof sc === 'object' && sc).map((sc) => [sc.key, sc]))
583
+ const withPreview = (sc) => {
584
+ const custom = overrides.get(sc.key)
585
+ return custom ? { ...sc, url: custom.url || sc.url, label: custom.label || sc.label } : sc
586
+ }
587
+ const pick = selection || handoffBatch(catalog, { batch, names: screens?.map((sc) => typeof sc === 'string' ? sc : sc?.key) })
588
+ if (pick.error) throw new Error(pick.error)
589
+ const list = pick.list.map(withPreview)
446
590
  const dir = path.join(root, HANDOFF_DIR)
447
591
  const shotDir = path.join(dir, 'shots')
448
592
  // handoff/、handoff/shots/ 得是设计目录里真的文件夹:是软链接就可能删到、写到别处去
@@ -451,25 +595,104 @@ export async function buildHandoff(browser, { root, screens, kind = 'web', size
451
595
  try { st = fs.lstatSync(d) } catch { fs.mkdirSync(d) }
452
596
  if (st && !st.isDirectory()) throw new Error(`${path.relative(root, d)} 不是普通文件夹(是软链接或文件),先挪走再交接`)
453
597
  }
454
- for (const f of fs.readdirSync(shotDir)) if (/\.jpg$/i.test(f)) fs.rmSync(path.join(shotDir, f), { force: true })
455
- const list = screens.slice(0, MAX_SCREENS)
456
- const rows = browser && browser.available() ? await shootScreens(browser, list, size, kind, shotDir) : list.map((sc) => ({ key: sc.key, label: sc.label, title: '', links: [], shots: [], error: '没有 Chrome / Edge,没截图' }))
457
598
  const htmlByKey = new Map()
458
- for (const sc of list) { try { htmlByKey.set(sc.key, fs.readFileSync(path.join(root, sc.key), 'utf8')) } catch { /* 读不了 */ } }
459
- const md = handoffMd({ root, rows, kind, size, framework, dest, project, system, annotations, tuned, htmlByKey, more: Math.max(0, screens.length - MAX_SCREENS), now })
460
- const file = path.join(dir, 'HANDOFF.md')
461
- unlinkIfLink(file)
462
- fs.writeFileSync(file, md)
463
- return { file, dir, md, shots: rows.reduce((m, r) => m + r.shots.length + (r.mobile ? 1 : 0), 0), rows }
599
+ const source = new Map()
600
+ const readFile = dirReader(root)
601
+ const compFiles = new Map()
602
+ const readComponent = (rel) => {
603
+ if (!compFiles.has(rel)) {
604
+ const buf = readFile(rel)
605
+ compFiles.set(rel, { buf, hash: buf ? createHash('sha256').update(buf).digest('hex') : null })
606
+ }
607
+ return compFiles.get(rel).buf
608
+ }
609
+ readComponent.hasCompDir = readFile.hasCompDir // 接不接管 <c-…> 和预览同一套(见 comp-io adopts)
610
+ const components = componentCatalog(readComponent, componentFiles(root)).filter((c) => !c.error)
611
+ const contracts = new Map(components.map((c) => [c.name, {
612
+ screens: [], params: new Set(c.params.map((p) => p.name)), paths: new Set(c.mockPaths),
613
+ }]))
614
+ for (const screen of catalog) {
615
+ const sc = withPreview(screen)
616
+ const raw = readText(path.join(root, sc.key)) ?? ''
617
+ const expanded = expandPreview(raw, readComponent, sc.key)
618
+ if (expanded.comp) {
619
+ for (const name of expanded.used) contracts.get(name)?.screens.push(sc.key)
620
+ collectInstancePaths(raw, contracts)
621
+ }
622
+ const deps = expanded.deps.map((rel) => [rel, compFiles.get(rel)?.hash ?? null])
623
+ const fingerprint = createHash('sha256').update(raw).update('\0').update(JSON.stringify(deps)).digest('hex')
624
+ htmlByKey.set(sc.key, expanded.html)
625
+ source.set(sc.key, { ...sc, ...sourceRow(sc, expanded.html), fingerprint })
626
+ }
627
+ for (const c of components) {
628
+ const contract = contracts.get(c.name)
629
+ c.screens = contract.screens
630
+ c.mockPaths = [...contract.paths].sort()
631
+ }
632
+ const available = !!(list.length && browser?.available())
633
+ const staged = available ? fs.mkdtempSync(path.join(dir, '.shots-')) : ''
634
+ try {
635
+ const rows = available ? await shootScreens(browser, list, size, kind, staged) : list.map((sc) => ({
636
+ ...sc, shots: [], error: '没有 Chrome / Edge,没截图',
637
+ }))
638
+ // 截图完成后再读最新记录,合并到同一份文档。不同批次同时结束也能各自补进去。
639
+ const stateFile = path.join(dir, '.screens.json')
640
+ const state = fs.lstatSync(stateFile, { throwIfNoEntry: false })?.isFile() ? readObj(stateFile) : null
641
+ const saved = new Map(Object.entries(state || {}).filter(([, row]) => row && Array.isArray(row.links) && Array.isArray(row.shots) && Array.isArray(row.notes?.states)))
642
+ const frames = frameCss(root, [...htmlByKey.values()].filter(isFramed))
643
+ const css = screenStyles(root, styleSheets(root, frames))
644
+ const mockData = mockOf(root)
645
+ for (const row of rows) {
646
+ const sc = list.find((x) => x.key === row.key)
647
+ const prior = saved.get(row.key)
648
+ const base = source.get(row.key)
649
+ const notes = screenNotes(row.key, htmlByKey.get(row.key) || '', css, mockData)
650
+ if (row.error) {
651
+ saved.set(row.key, { ...prior, links: prior?.links || [], shots: prior?.shots || [], error: row.error, notes })
652
+ continue
653
+ }
654
+ row.links = [...new Map([...base.links, ...row.links].map((link) => [link.path, link])).values()]
655
+ row.title ||= base.title
656
+ const files = [...row.shots, row.mobile].filter(Boolean)
657
+ for (const shot of files) fs.renameSync(path.join(staged, shot), path.join(shotDir, shot))
658
+ for (const old of [...desktopShots(sc), shotName(sc, 'mobile')]) {
659
+ if (!files.includes(old)) fs.rmSync(path.join(shotDir, old), { force: true })
660
+ }
661
+ saved.set(row.key, {
662
+ title: row.title, links: row.links, shots: row.shots, mobile: row.mobile, more: row.more, notes, fingerprint: base.fingerprint,
663
+ })
664
+ }
665
+ const previousShots = new Set(fs.readdirSync(shotDir, { withFileTypes: true }).filter((f) => f.isFile()).map((f) => f.name))
666
+ const all = catalog.map((sc) => {
667
+ const base = source.get(sc.key)
668
+ const past = saved.get(sc.key)
669
+ const shots = desktopShots(sc).filter((f) => previousShots.has(f))
670
+ const mobile = shotName(sc, 'mobile')
671
+ const fresh = past?.fingerprint === base.fingerprint
672
+ const notes = fresh ? past.notes : past || shots.length ? screenNotes(sc.key, htmlByKey.get(sc.key) || '', css, mockData) : null
673
+ return { ...base, shots, mobile: previousShots.has(mobile) ? mobile : '', notes,
674
+ ...(fresh ? { title: past.title, links: past.links, more: past.more } : {}),
675
+ stale: shots.length > 0 && !fresh, error: past?.error,
676
+ }
677
+ })
678
+ const md = handoffMd({ root, rows: all, kind, size, framework, dest, project, system, annotations, tuned, htmlByKey, batched: true, components, now })
679
+ const file = path.join(dir, 'HANDOFF.md')
680
+ writeHandoffFile(stateFile, JSON.stringify(Object.fromEntries(catalog.filter((sc) => saved.has(sc.key)).map((sc) => [sc.key, saved.get(sc.key)]))))
681
+ writeHandoffFile(file, md)
682
+ const pending = [...new Set(all.filter((sc) => !sc.shots.length || sc.stale || sc.error).map((sc) => sc.batch))]
683
+ return { file, dir, md, shots: rows.reduce((m, r) => m + r.shots.length + (r.mobile ? 1 : 0), 0), rows, pending }
684
+ } finally {
685
+ if (staged) fs.rmSync(staged, { recursive: true, force: true })
686
+ }
464
687
  }
465
688
 
466
689
  /** 交接说明 */
467
- export function handoffMd({ root, rows, kind, size, framework, dest, project, system, annotations = null, tuned = [], htmlByKey, more = 0, now = new Date() }) {
690
+ export function handoffMd({ root, rows, kind, size, framework, dest, project, system, annotations = null, tuned = [], htmlByKey, batched = false, components = [], now = new Date() }) {
468
691
  const fw = FRAMEWORKS[framework] || null
469
692
  const same = framework === 'same' && project && project.framework
470
693
  const fwLabel = same ? `${project.label}(跟项目一样)` : fw ? fw.label : framework
471
694
  const name = path.basename(root)
472
- const keys = rows.map((r) => r.key)
695
+ const keys = new Set(rows.map((r) => r.key))
473
696
  // 做成什么:跟项目一样就是项目的框架;小程序的写法(uni-app / 原生 / Taro)按小程序的规矩写
474
697
  const target = framework === 'same' ? (project && project.framework) || '' : framework
475
698
  const uni = target === 'uniapp'
@@ -487,12 +710,13 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
487
710
  const cfgFile = uni ? `${at}pages.json` : wx ? `${at}app.json` : `${at}app.config`
488
711
  const api = uni ? 'uni' : taro ? 'Taro' : 'wx'
489
712
  const route = (k) => (mini ? pagePathOf(k, target) : routeOf(k))
490
- const keyOfLink = (p) => String(p || '').replace(/^\/+/, '').split(/[?#]/)[0]
713
+ const keyOfLink = (p) => p === '/' && keys.has('index.html') ? 'index.html' : String(p || '').replace(/^\/+/, '').split(/[?#]/)[0]
714
+ const cell = (s) => String(s).replace(/[\r\n]+/g, ' ').replace(/\|/g, '\\|')
491
715
  const lines = []
492
716
  lines.push(`# 交接:${name} → ${fwLabel}`, '')
493
717
  lines.push(`> 给写代码的模型看:照这份把设计稿做成真页面。设计稿就是源码——每屏一个 HTML,样式在 tokens.css 等样式表里;元素上的行内 \`style="…"\` 多半是用户在工作台里手调的,值以它为准(做成组件时并进组件的样式)。先读源文件(现在的,别照你之前写过的内容),截图只用来对照,别凭截图猜数值。`, '')
494
718
  lines.push('## 做什么', '')
495
- lines.push(`- 设计目录:\`${root}\`(${rows.length} 屏${more ? `,另有 ${more} 屏没列进来` : ''},${kind} ${size[0]}×${size[1]})`)
719
+ lines.push(`- 设计目录:\`${root}\`(${rows.length} 屏,${kind} ${size[0]}×${size[1]})`)
496
720
  // 目录里已经有别的东西、又不是 Node 项目(别的语言的仓库、后端……):别在原地或旁边跑脚手架
497
721
  // (纯 HTML 站点再做成纯 HTML 不算:就加在这个站点里,下面第 1 步提醒别覆盖现有页面)
498
722
  const occupied = !!(project && !known && project.empty === false) && !(project.site && framework === 'html')
@@ -578,8 +802,11 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
578
802
  lines.push(mini ? '## 屏幕和页面' : '## 屏幕和路由', '', `| 屏 | 设计文件 | ${mini ? '页面路径' : '建议路由'} | 截图(handoff/shots/) | 跳到 |`, '| --- | --- | --- | --- | --- |')
579
803
  for (const r of rows) {
580
804
  const to = [...new Set((r.links || []).map((l) => keyOfLink(l.path)).filter((k) => k && k !== r.key))]
581
- const shots = r.error ? `没截成(${r.error})` : [...r.shots, r.mobile].filter(Boolean).join('、') + (r.more ? `(还有 ${r.more} 段没截)` : '')
582
- lines.push(`| ${r.title || r.label} | ${r.key} | \`${route(r.key)}\` | ${shots} | ${to.map((k) => (keys.includes(k) ? k.replace(/\.html?$/i, '') : `${k}(没有这一屏)`)).join('、') || '—'} |`)
805
+ const files = [...r.shots, r.mobile].filter(Boolean).join('、')
806
+ const waiting = batched && r.stale ? `截图已过期,第 ${r.batch} 批重截` : batched && !r.shots.length ? `第 ${r.batch} 批截` : ''
807
+ const shots = [files, waiting, r.error ? `没截成(${r.error})` : '', r.more ? `(还有 ${r.more} 段没截)` : ''].filter(Boolean).join(' · ')
808
+ const links = to.map((k) => (keys.has(k) ? k.replace(/\.html?$/i, '') : `${k}(没有这一屏)`)).join('、') || '—'
809
+ lines.push(`| ${cell(r.title || r.label || r.key)} | ${cell(r.key)} | \`${mini ? route(r.key) : r.route ?? route(r.key)}\` | ${cell(shots)} | ${cell(links)} |`)
583
810
  }
584
811
  lines.push('')
585
812
 
@@ -604,7 +831,7 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
604
831
  if (!frameSheets.length || plainKeys.length) lines.push(`- 设计目录里没有 tokens.css:先把${frameSheets.length ? '没套外框那几屏' : '各屏'} \`<style>\` 里 \`:root\` 上的变量收成一份 tokens.css 再动手。`)
605
832
  }
606
833
  // 外框的样式表不算公共样式(上面「外框要点」说了怎么带)
607
- const sheets = (() => { try { return fs.readdirSync(root).filter((n) => /\.css$/i.test(n) && n !== 'tokens.css' && !frameSheets.includes(n)) } catch { return [] } })()
834
+ const sheets = styleSheets(root, frameSheets)
608
835
  if (sheets.length) lines.push(`- 别的样式表:${sheets.map((n) => `\`${n}\``).join('、')}(公共样式,拆进对应组件或全局样式)`)
609
836
  lines.push('')
610
837
 
@@ -627,6 +854,24 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
627
854
  }
628
855
  lines.push('')
629
856
 
857
+ if (components.length) {
858
+ lines.push('## 组件', '', '- 每个组件实现为一个代码文件,多个路由引用同一个组件文件,别每屏复制。', '')
859
+ const listed = (values = []) => values.map((v) => `\`${v}\``).join('、') || '无'
860
+ for (const c of components) {
861
+ const code = pascal(c.name)
862
+ const file = wx ? `components/${c.name}/${c.name}.js` : `components/${code}.${uni || target === 'vue' ? 'vue' : target === 'html' ? 'js' : 'tsx'}`
863
+ const params = (c.params || []).map((p) => `\`${p.name}\`(${p.required ? '必填' : '选填'}${p.def != null ? `,默认 \`${JSON.stringify(p.def)}\`` : ''})`)
864
+ lines.push(`### ${code}`, '',
865
+ `- 设计文件 \`${c.file}\` → ${wx ? '小程序 component 入口' : '组件文件'} \`${file}\``,
866
+ `- 参数 ${params.join('、') || '无'}`,
867
+ `- 插槽 ${c.slot ? '一个默认插槽' : '无'}`,
868
+ `- \`data-status\` ${listed(c.statuses)}`,
869
+ `- \`data-variant\` ${listed(c.variants)}`,
870
+ `- 用在 ${listed(c.screens)}`,
871
+ `- 读取 mock 字段 ${listed(c.mockPaths)}`, '')
872
+ }
873
+ }
874
+
630
875
  // 用户在工作台里亲手改过的(#28):模型做组件时常照样式表里的那条规则来,手调写在行内的值就丢了
631
876
  const hand = (tuned || []).filter((v) => v && TUNED.test(String(v.label || ''))).slice(0, 12)
632
877
  if (hand.length) {
@@ -642,27 +887,16 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
642
887
 
643
888
  // 交互和状态
644
889
  lines.push('## 交互和状态', '')
645
- const inter = []
646
- let hover = 0
647
- 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 { /* 没有 */ } }
648
- for (const [key, html] of htmlByKey) {
649
- const scripts = [...html.matchAll(/<script\b(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi)].filter((m) => m[1].trim()).length
650
- // 套了外框的屏:输入框、跳转只数槽位里的(外框上的搜索框之类是宿主的);脚本常写在页尾,照整页数
651
- const inner = slotHtml(html)
652
- const forms = (inner.match(/<(input|textarea|select)\b/gi) || []).length
653
- hover += (html.match(/:(hover|focus-visible|focus|active)\b/g) || []).length
654
- const bits = []
655
- if (scripts) bits.push(`${scripts} 段脚本(改成框架里的状态和事件)`)
656
- if (forms) bits.push(`${forms} 个输入控件(做成受控组件、加校验和出错状态)`)
657
- if (/data-href=/.test(inner)) bits.push('用 data-href 跳转的元素(改成路由跳转)')
658
- if (bits.length) inter.push(`- ${key}:${bits.join(';')}`)
659
- }
660
- lines.push(...(inter.length ? inter : ['- 设计稿里没有脚本和表单,纯展示。']))
661
- // 一页多状态(#30):同一个页面的几种样子写在一个文件里,转代码时是一个组件带状态,不是几个页面
662
- const stLines = statesMd(htmlByKey, [...sheets, 'tokens.css'].map((n) => { try { return fs.readFileSync(path.join(root, n), 'utf8') } catch { return '' } }).join('\n'))
663
- if (stLines.length) lines.push(...stLines)
664
- lines.push(...mockMd(htmlByKey, root))
665
- if ([...htmlByKey.values()].some((h) => /\sdata-back\b/i.test(slotHtml(h)))) lines.push('- 写了 `data-back` 的返回按钮:做成「返回上一页」(router.back() / navigation.goBack()),没有上一页时才去它写的 href。')
890
+ const css = screenStyles(root, sheets)
891
+ const mock = mockOf(root)
892
+ const notes = batched ? rows.map((r) => r.notes).filter(Boolean) : [...htmlByKey].map(([key, html]) => screenNotes(key, html, css, mock))
893
+ const inter = notes.map((n) => n.inter).filter(Boolean)
894
+ if (inter.length) lines.push(...inter)
895
+ else lines.push(batched && notes.length < rows.length ? '- 已分析的屏没有脚本和表单。' : '- 设计稿里没有脚本和表单,纯展示。')
896
+ lines.push(...notes.flatMap((n) => n.states))
897
+ lines.push(...mockMd(htmlByKey, root, notes.map((n) => n.mock)))
898
+ if (notes.some((n) => n.back)) lines.push('- 写了 `data-back` 的返回按钮:做成「返回上一页」(router.back() / navigation.goBack()),没有上一页时才去它写的 href。')
899
+ const hover = (css.match(/:(hover|focus-visible|focus|active)\b/g) || []).length + notes.reduce((sum, n) => sum + n.hover, 0)
666
900
  if (hover) lines.push(`- 悬停 / 聚焦 / 按下的样式 ${hover} 处:照搬,别丢。`)
667
901
  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">`)。')
668
902
  const tw = readTweaks(root)
@@ -670,7 +904,8 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
670
904
  lines.push('')
671
905
 
672
906
  // 业务规则(业务标注开着才有)
673
- lines.push(...annotationsMd(annotations, new Set(htmlByKey.keys()), annotations ? new Set(allScreens(root)) : null))
907
+ const knownScreens = annotations ? (batched ? keys : new Set(allScreens(root))) : null
908
+ lines.push(...annotationsMd(annotations, new Set(htmlByKey.keys()), knownScreens))
674
909
 
675
910
  // 素材
676
911
  const assets = []
package/lib/history.js CHANGED
@@ -90,6 +90,7 @@ export function diffFiles(a = {}, b = {}) {
90
90
  export function createHistory({ base, now = Date.now, log = () => {} }) {
91
91
  const dirOf = (root) => path.join(base, sha1(path.resolve(root)).slice(0, 16))
92
92
  const sigs = new Map() // root → 上次存的时候各文件的大小 + 修改时间(没变就不用再读一遍算哈希)
93
+ const skips = new Map() // root → { at }:最近一次因为目录太大没存成(存成了 / 没改动就清掉),版本面板据此提示
93
94
 
94
95
  function load(root) {
95
96
  try {
@@ -132,8 +133,10 @@ export function createHistory({ base, now = Date.now, log = () => {} }) {
132
133
  /** snapshot 的本体:出错直接抛;strict 时目录太大(存不下)也抛 */
133
134
  function take(root, label, strict, by = '') {
134
135
  const found = collect(root)
136
+ if (!found) skips.set(path.resolve(root), { at: now() })
135
137
  if (!found && strict) throw new Error('目录太大(多半是整个项目),存不了现在的样子')
136
138
  if (!found || !Object.keys(found).length) return null
139
+ skips.delete(path.resolve(root))
137
140
  let sig = ''
138
141
  for (const [rel, abs] of Object.entries(found)) {
139
142
  try { const st = fs.statSync(abs); sig += `${rel}:${st.size}:${st.mtimeMs}\n` } catch { /* 刚删 */ }
@@ -246,5 +249,7 @@ export function createHistory({ base, now = Date.now, log = () => {} }) {
246
249
  return { restored, saved }
247
250
  }
248
251
 
249
- return { snapshot, list, fileOf, restore, dirOf }
252
+ /** 最近一次没存成(目录超过 300 个文件 / 30 MB):{ at, files, total };没有给 null */
253
+ const skipped = (root) => { const s = skips.get(path.resolve(root)); return s ? { ...s, files: MAX_FILES, mb: MAX_TOTAL / 1024 / 1024 } : null }
254
+ return { snapshot, list, fileOf, restore, dirOf, skipped }
250
255
  }