dsh-design-studio 0.16.1 → 0.17.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
@@ -17,6 +17,7 @@ import { pathToFileURL } 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
+ import { annotationsMd } from './annotations.js'
20
21
  import { tokensOf } from './system.js'
21
22
 
22
23
  export const HANDOFF_DIR = 'handoff'
@@ -333,7 +334,7 @@ export function unlinkIfLink(file) {
333
334
  * 生成交接包。screens:[{ key, url, label }](预览服务器上的地址);root:设计目录。
334
335
  * @returns { file, dir, md, shots, rows }
335
336
  */
336
- export async function buildHandoff(browser, { root, screens, kind = 'web', size = [1280, 800], framework = 'react', dest = '', project = null, system = '', now = new Date() }) {
337
+ export async function buildHandoff(browser, { root, screens, kind = 'web', size = [1280, 800], framework = 'react', dest = '', project = null, system = '', annotations = null, now = new Date() }) {
337
338
  const dir = path.join(root, HANDOFF_DIR)
338
339
  const shotDir = path.join(dir, 'shots')
339
340
  // handoff/、handoff/shots/ 得是设计目录里真的文件夹:是软链接就可能删到、写到别处去
@@ -347,7 +348,7 @@ export async function buildHandoff(browser, { root, screens, kind = 'web', size
347
348
  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,没截图' }))
348
349
  const htmlByKey = new Map()
349
350
  for (const sc of list) { try { htmlByKey.set(sc.key, fs.readFileSync(path.join(root, sc.key), 'utf8')) } catch { /* 读不了 */ } }
350
- const md = handoffMd({ root, rows, kind, size, framework, dest, project, system, htmlByKey, more: Math.max(0, screens.length - MAX_SCREENS), now })
351
+ const md = handoffMd({ root, rows, kind, size, framework, dest, project, system, annotations, htmlByKey, more: Math.max(0, screens.length - MAX_SCREENS), now })
351
352
  const file = path.join(dir, 'HANDOFF.md')
352
353
  unlinkIfLink(file)
353
354
  fs.writeFileSync(file, md)
@@ -355,7 +356,7 @@ export async function buildHandoff(browser, { root, screens, kind = 'web', size
355
356
  }
356
357
 
357
358
  /** 交接说明 */
358
- export function handoffMd({ root, rows, kind, size, framework, dest, project, system, htmlByKey, more = 0, now = new Date() }) {
359
+ export function handoffMd({ root, rows, kind, size, framework, dest, project, system, annotations = null, htmlByKey, more = 0, now = new Date() }) {
359
360
  const fw = FRAMEWORKS[framework] || null
360
361
  const same = framework === 'same' && project && project.framework
361
362
  const fwLabel = same ? `${project.label}(跟项目一样)` : fw ? fw.label : framework
@@ -518,6 +519,9 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
518
519
  if (tw && tw.list.length) lines.push(`- 调节滑块(tweaks.json):${tw.list.map((k) => `${k.label}(${k.var || k.attr},现在是 ${shownValue(k, k.value)})`).join('、')}。最终值已经写在样式里;要在产品里留着可调,就做成主题设置(改同一个 CSS 变量 / <html> 属性)。`)
519
520
  lines.push('')
520
521
 
522
+ // 业务规则(业务标注开着才有)
523
+ lines.push(...annotationsMd(annotations, new Set(htmlByKey.keys()), annotations ? new Set(allScreens(root)) : null))
524
+
521
525
  // 素材
522
526
  const assets = []
523
527
  const walk = (d, rel, depth) => {
package/lib/index.js CHANGED
@@ -50,10 +50,11 @@ import { createHub, webOrigins, trustedOrigins, resolveInRoot, ERR_CATCHER, defa
50
50
  import { bundle, inlinePicker, strictMeta, MAX_TOTAL as BUNDLE_MAX } from './bundle.js'
51
51
  import { createLibrary } from './works.js'
52
52
  import { createInspiration } from './inspire.js'
53
+ import { pickStyleText } from './styles.js'
53
54
  import { createLibraryRoutes } from './gallery/routes.js'
54
55
  import { createMarket } from './gallery/market.js'
55
56
  import { createMarketRoutes } from './gallery/market-routes.js'
56
- import { createPhotos, loadPhotoIndex, searchPhotos, onlyByTheme, isPhotoAsset, orientOf, MAX_PHOTOS } from './photos.js'
57
+ import { createPhotos, loadPhotoIndex, searchPhotos, onlyByTheme, ratioNote, isPhotoAsset, orientOf, MAX_PHOTOS } from './photos.js'
57
58
  import { createTracker, parseTarget, findRule, KINDS } from './core.js'
58
59
  import { createDrafts } from './draft.js'
59
60
  import { createHistory } from './history.js'
@@ -64,6 +65,7 @@ import { createBrowser } from './browser.js'
64
65
  import { designOf, fitSize, metaOfFile, sizeOf, pickScreens, measureAll, shootAll, cropIssues, formatMeasure, issueSnapshot, formatShots, whereOf, MAX_SCREENS, MAX_SIZES, MAX_SHOTS, MAX_CROPS } from './look.js'
65
66
  import { SYSTEMS_DIR, extractSystem, listSystems, setDefault, skillSection } from './system.js'
66
67
  import { readTweaks, applyTweaks, lintTweaks } from './tweaks.js'
68
+ import { readAnnotations, lintAnnotations, annotationFindings, annotationSection } from './annotations.js'
67
69
  import { FRAMEWORKS, detectProject, projectFor, defaultFramework, buildHandoff, compareScreens, implUrl, defaultDest, pickedDest, within, pinRoots } from './handoff.js'
68
70
 
69
71
  export const name = 'dsh-design-studio'
@@ -90,7 +92,7 @@ const SKILL_RANK = 600 // 和 DSH 自带的技能同一档;用户 / 项目里
90
92
  * 几行之间靠这个互通(同一个包里的模块 Node 只加载一次):工作台起来后放 tracker、无头浏览器(browser);
91
93
  * 「自动打开预览」那行开着时 autoOpen > 0
92
94
  */
93
- export const studio = { tracker: null, autoOpen: 0, offline: 0, check: null, browser: null, market: null, photos: null, sessionCwd: null, log: () => {} }
95
+ export const studio = { tracker: null, autoOpen: 0, offline: 0, annotations: 0, check: null, browser: null, market: null, photos: null, sessionCwd: null, log: () => {} }
94
96
 
95
97
  /** 设计技能:模型做界面设计时加载(DSH 的 skill 工具),也能让用户手动调 */
96
98
  export const designSkill = {
@@ -116,6 +118,7 @@ export const skillProvider = {
116
118
  // 用户的设计系统(默认用哪套、库里有哪些)每次现读,提了新的下次加载技能就知道
117
119
  let extra = ''
118
120
  try { extra = skillSection() } catch (e) { studio.log(e) }
121
+ if (studio.annotations > 0) extra += annotationSection()
119
122
  return { name, description, whenToUse, invocation, provider, source, resourceBase, content: (await fs.promises.readFile(designSkill.locator, 'utf8')) + extra }
120
123
  },
121
124
  }
@@ -245,12 +248,13 @@ export const checkTool = {
245
248
  const { snap, kind } = design
246
249
  const want = sizesFrom(a.sizes, kind)
247
250
  const b = studio.browser
251
+ const anAt = annotationsAt(id) // 开始量时的设计目录和标注:量的过程中换了设计也不串
248
252
  if (b && b.available()) {
249
253
  try {
250
254
  const pick = pickScreens(snap, a.screens, MAX_SCREENS)
251
255
  if (!pick.list.length) return { text: `没找到要量的屏:${pick.missing.join('、')}。现在有:${(snap.screens || []).map((x) => x.key).join('、') || snap.focus}` }
252
256
  const sizes = want.sizes.length ? want.sizes : [await fitted(b, design, a.screens)]
253
- const rows = await measureAll(b, { screens: pick.list, sizes, kind, dark: !!a.dark, locate: (items) => locateRules(studio.tracker.stateOf(id), items) })
257
+ const rows = await measureAll(b, { screens: pick.list, sizes, kind, dark: !!a.dark, annots: annotsByPage(anAt.ann), locate: (items) => locateRules(studio.tracker.stateOf(id), items) })
254
258
  if (rows.some((r) => !r.error)) {
255
259
  // 同一个会话上次量的结果:这次比一比修好了几个、新出了几个
256
260
  const prev = lastChecks.get(id) || null
@@ -269,7 +273,7 @@ export const checkTool = {
269
273
  while (lastChecks.size > 20) lastChecks.delete(lastChecks.keys().next().value)
270
274
  if (want.bad.length) text += `\n认不出的尺寸(没量):${want.bad.join('、')},写成 375x667 或 375`
271
275
  if (want.more) text += `\n尺寸太多,只量了前 ${MAX_SIZES} 种`
272
- text += tweakNotes(id)
276
+ text += tweakNotes(id) + annotationNotes(anAt, rows)
273
277
  return kept && kept.images ? { text, images: kept.images } : { text }
274
278
  }
275
279
  studio.log(new Error(`check_design 无头浏览器没量成:${rows[0] && rows[0].error}`))
@@ -283,10 +287,41 @@ export const checkTool = {
283
287
  const note = want.sizes.length || a.dark ? '(这台电脑上没找到能用的 Chrome / Edge,没法按指定尺寸 / 深色量;下面是右侧栏按它现在显示的尺寸量的)\n' : ''
284
288
  if (!r) return { text: '右侧栏「设计工作台」现在没开着,量不了。照 ui-design 技能里的「自查」清单自己过一遍。' }
285
289
  if (!r.error && !r.measured) return { text: '右侧栏开着,但预览页面没回应,这次没量成(可能还在加载)。过一会儿再调一次,或照 ui-design 技能里的「自查」清单自己过一遍。' }
286
- return { text: note + (r.error || r.text) + tweakNotes(id) }
290
+ return { text: note + (r.error || r.text) + tweakNotes(id) + annotationNotes(anAt, null) }
287
291
  },
288
292
  }
289
293
 
294
+ /** 这个会话现在的设计目录和里面的业务标注(开关关着、不是本地文件时 root 是 '') */
295
+ function annotationsAt(id) {
296
+ if (!(studio.annotations > 0)) return { root: '', ann: null }
297
+ try {
298
+ const t = studio.tracker.stateOf(id).target
299
+ if (t && t.kind === 'file') return { root: t.root, ann: readAnnotations(t.root) }
300
+ } catch (e) { studio.log(e) }
301
+ return { root: '', ann: null }
302
+ }
303
+
304
+ /** 按屏分好的业务标注:无头浏览器量的时候顺手核对定位 */
305
+ function annotsByPage(r) {
306
+ if (!r || !r.list.length) return null
307
+ const m = new Map()
308
+ for (const a of r.list) { if (!m.has(a.page)) m.set(a.page, []); m.get(a.page).push({ id: a.id, selector: a.selector, fallbackText: a.fallbackText }) }
309
+ return m
310
+ }
311
+
312
+ /** 业务标注写坏的、定位不到的:check_design 末尾附上(at:开始量时的目录和标注;rows:无头浏览器量的结果,没量成是 null) */
313
+ function annotationNotes(at, rows) {
314
+ if (!at.root) return ''
315
+ let list = []
316
+ try {
317
+ list = lintAnnotations(at.root)
318
+ const r = at.ann
319
+ if (r && rows) list.push(...annotationFindings(r.list, rows.filter((x) => Array.isArray(x.annots)).map((x) => ({ page: x.key, list: x.annots }))))
320
+ else if (r && r.list.length) list.push('这次没有无头浏览器,选择器定位不到的情况没核对;右侧栏「业务标注」面板里能看到')
321
+ } catch (e) { studio.log(e) }
322
+ return list.length ? `\n\n业务标注(annotations.json):\n${list.map((x) => `- ${x}`).join('\n')}` : ''
323
+ }
324
+
290
325
  /** 调节滑块(tweaks.json)有没有真接上:check_design 末尾附上 */
291
326
  function tweakNotes(id) {
292
327
  let list = []
@@ -490,7 +525,7 @@ export const handoffTool = {
490
525
  if (framework === 'same' && !project.framework) return { text: `${dest} 里没有认得出的前端项目(package.json 里没有 React / Vue / Next / uni-app …,也不是 HBuilderX 或微信原生小程序的项目):framework 选 react、vue、next、html、uniapp 或 weapp。` }
491
526
  let r
492
527
  try {
493
- r = await buildHandoff(studio.browser, { root: t.root, screens: pick.list, kind, size, framework, dest, project, system: systemOfDir(t.root) })
528
+ r = await buildHandoff(studio.browser, { root: t.root, screens: pick.list, kind, size, framework, dest, project, system: systemOfDir(t.root), annotations: studio.annotations > 0 ? readAnnotations(t.root) : null })
494
529
  } catch (e) {
495
530
  return { text: `没写成交接包:${String((e && e.message) || e).slice(0, 200)}` }
496
531
  }
@@ -552,7 +587,7 @@ export const photoTool = {
552
587
  const list = placed.map(({ p, rel }, i) => `${i + 1}. ${rel}(${ORIENT[orientOf(p.w, p.h)]} ${p.w}×${p.h})alt:${p.alt} / ${p.altEn}`)
553
588
  return {
554
589
  text:
555
- `${broad ? `按题材找到 ${placed.length} 张(没有和「${query}」里具体画面对得上的标签,看描述合不合适再用;不合适就用 CSS / SVG 画,并告诉用户这里需要什么样的照片)` : `找到 ${placed.length} 张`},已放进 ${path.join(dir, 'assets')}:\n${list.join('\n')}\n${few}` +
590
+ `${broad ? `按题材找到 ${placed.length} 张(没有和「${query}」里具体画面对得上的标签,看描述合不合适再用;不合适就用 CSS / SVG 画,并告诉用户这里需要什么样的照片)` : `找到 ${placed.length} 张`},已放进 ${path.join(dir, 'assets')}:\n${list.join('\n')}\n${few}${ratioNote(placed.map((x) => x.p), ratio)}` +
556
591
  '这是按关键词找的,先看上面的描述和需求对不对得上,对不上的别用(没用上的图不会进分享包)。\n' +
557
592
  '用法:<img src="assets/文件名" alt="…"> 配 object-fit: cover;alt 按界面语言选一个;HTML 不在这个文件夹时改相对路径。\n' +
558
593
  '这些是 AI 生成的示意图,不是用户真实的店铺或产品:别写「实拍」,也别把图上的场景当事实写进文案;做完告诉用户上线前换成真实照片。',
@@ -567,6 +602,29 @@ export const photoTool = {
567
602
  },
568
603
  }
569
604
 
605
+ /** pick_style 工具:用户没定风格时按题材挑一张风格卡(模型自己定,消费类题目总落回米色暖调;给了具体配色它照做得很好) */
606
+ export const styleTool = {
607
+ name: 'pick_style',
608
+ description:
609
+ '新做一套设计、用户没定风格时,开工前先调这个:按题材挑一张风格卡,返回整套配色、字体、圆角阴影和要点,照它定进 tokens.css。' +
610
+ '用户点了风格卡(消息里有〔风格〕)、自己定了具体的风格或配色、或有默认的品牌设计系统时不用调;只说「你定」「帮我推荐一个」「出几个风格挑」算没定,要调。',
611
+ parameters: specToJsonSchema({
612
+ subject: { type: 'string', required: true, description: '这次要做什么,直接写用户的原话' },
613
+ kind: { type: 'string', enum: ['web', 'app', 'miniprogram', 'tablet', 'desktop', 'poster', 'slides', 'email'], description: '设计类型' },
614
+ count: { type: 'number', description: '要几个方向,1–3,默认 1;要先出三个方向时填 3,每个方向一张不同的卡' },
615
+ }),
616
+ output: {
617
+ schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string' } }, required: ['text'] },
618
+ render: (_args, value) => [{ type: 'text', text: value.text }],
619
+ },
620
+ async execute(args) {
621
+ const a = args || {}
622
+ const subject = typeof a.subject === 'string' ? a.subject.trim() : ''
623
+ if (!subject) return { text: 'subject 不能空:写这次要做什么,用用户的原话。' }
624
+ return { text: pickStyleText(subject, typeof a.kind === 'string' ? a.kind : '', a.count) }
625
+ },
626
+ }
627
+
570
628
  /** compare_design 工具:设计稿的一屏和做出来的页面按同样尺寸截图,逐像素比 */
571
629
  export const compareTool = {
572
630
  name: 'compare_design',
@@ -736,6 +794,7 @@ export function apply(ctx) {
736
794
  log,
737
795
  history,
738
796
  drafts,
797
+ skipAnnots: () => studio.annotations > 0, // 业务标注开着时这个文件只给右侧栏看,改了不刷新页面
739
798
  strict: { html: (buf) => library.strictHtml(buf) || market.strictHtml(buf), root: (dir) => library.strictRoot(dir) || market.isStaging(dir), versions: (dir) => library.strictVersions(dir) },
740
799
  // 桌面版的 dsh-app://app 是默认就认的;这里补上 DSH 网页端的地址,和 DSH 配置里声明的对外地址(反向代理 / 域名)
741
800
  parents: () => {
@@ -844,6 +903,18 @@ export function apply(ctx) {
844
903
  }
845
904
  }, 'dsh-design-studio: check')
846
905
 
906
+ /** 业务标注:开关开着才有这个键(null = 还没有文件)。an 是右侧栏手上那份的签名,没变就不再传一遍(一份可能上百 KB,轮询很勤) */
907
+ function annotsField(session, an = '') {
908
+ const t = tracker.stateOf(session).target
909
+ if (!(studio.annotations > 0) || !t || t.kind !== 'file') return {}
910
+ let annotations = null
911
+ try {
912
+ const r = readAnnotations(t.root)
913
+ annotations = r && an && r.sig === an ? { sig: r.sig, same: true } : r
914
+ } catch (e) { log(e) }
915
+ return { annotations }
916
+ }
917
+
847
918
  function state(req, res) {
848
919
  if (!admit(req, res)) return
849
920
  const session = new URL(req.url, 'http://x').searchParams.get('session') || ''
@@ -854,7 +925,7 @@ export function apply(ctx) {
854
925
  let tweaks = null
855
926
  if (t && t.kind === 'file') { try { tweaks = readTweaks(t.root) } catch (e) { log(e) } }
856
927
  const snap = tracker.snapshot(session)
857
- json(res, 200, { ...snap, strict: strictScreens(snap), phone: { on: ph.on, seen: ph.seen || 0 }, tweaks, ...(c ? { checkReq: c.id } : {}) })
928
+ 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 } : {}) })
858
929
  }
859
930
 
860
931
  /** 正在看的几屏里,哪些是别人做的、没改过的(地址列表):右侧栏给它们的 iframe 加沙盒、不给剪贴板 */
@@ -988,7 +1059,7 @@ export function apply(ctx) {
988
1059
  // 输入框里写的相对路径按会话目录算(新会话也问 DSH 要)
989
1060
  const target = parseTarget(body.target, await sessionCwd(session))
990
1061
  await tracker.setTarget(session, target, { source: 'user', popup: false })
991
- json(res, 200, tracker.snapshot(session))
1062
+ json(res, 200, { ...tracker.snapshot(session), ...annotsField(session) })
992
1063
  } catch (e) {
993
1064
  json(res, 400, { error: e.message })
994
1065
  }
@@ -1005,7 +1076,7 @@ export function apply(ctx) {
1005
1076
  for (const k of ['kind', 'size', 'view', 'focus']) if (typeof body[k] === 'string') patch[k] = body[k]
1006
1077
  try {
1007
1078
  await tracker.setView(session, patch)
1008
- json(res, 200, tracker.snapshot(session))
1079
+ json(res, 200, { ...tracker.snapshot(session), ...annotsField(session) })
1009
1080
  } catch (e) {
1010
1081
  json(res, 400, { error: e.message })
1011
1082
  }
package/lib/look.js CHANGED
@@ -147,7 +147,7 @@ export async function fitSize(browser, screens, kind, size) {
147
147
  const RULE_PROP = { contrast: 'color', tiny: 'font-size' }
148
148
  const MAX_RULES = 12
149
149
 
150
- export async function measureAll(browser, { screens, sizes, kind, dark, fetcher = globalThis.fetch, locate = null }) {
150
+ export async function measureAll(browser, { screens, sizes, kind, dark, fetcher = globalThis.fetch, locate = null, annots = null }) {
151
151
  const jobs = []
152
152
  for (const sc of screens) for (const [w, h] of sizes) jobs.push({ sc, w, h })
153
153
  const gone = new Map() // 地址 → Promise<是不是 404>(几屏、几种尺寸指着同一页只问一次)
@@ -185,6 +185,8 @@ export async function measureAll(browser, { screens, sizes, kind, dark, fetcher
185
185
  }
186
186
  }
187
187
  // 跳转:每屏只在第一种尺寸上收一次(几种尺寸下链接一样)
188
+ // 业务标注定位得到吗:也只在第一种尺寸上核对(annots:屏的文件名 → 这一屏的标注;关着是 null)
189
+ if (i % sizes.length === 0 && annots && annots.has(sc.key)) row.annots = await page.eval(`window.__dshDesign.annots ? window.__dshDesign.annots(${JSON.stringify(annots.get(sc.key))}) : null`).catch(() => null)
188
190
  if (i % sizes.length === 0 && fetcher) row.links = await page.eval('window.__dshDesign.links ? window.__dshDesign.links() : []').catch(() => [])
189
191
  })
190
192
  } catch (e) {
package/lib/photos.js CHANGED
@@ -113,6 +113,15 @@ export function searchPhotos(index, opts = {}) {
113
113
  return scan(index, opts).rows.slice(0, n).map((r) => r.p)
114
114
  }
115
115
 
116
+ const ORIENT_NAME = { landscape: '横图', portrait: '竖图', square: '方图' }
117
+
118
+ /** 要的比例不够、补了别的比例时照实说(每个题材横图只有四张,一套设计很容易用完) */
119
+ export function ratioNote(list, ratio) {
120
+ const off = ratio ? list.filter((p) => orientOf(p.w, p.h) !== ratio).length : 0
121
+ const name = ORIENT_NAME[ratio]
122
+ return off ? `其中 ${off} 张不是${name}(对得上又没用过的${name}不够):用 object-fit: cover 裁,看好主体别被裁掉;也可以接着用 assets 里已有的${name}。\n` : ''
123
+ }
124
+
116
125
  /** 这次只命中了题材、没有对得上的具体画面(工具要照实告诉模型,让它看描述再决定用不用) */
117
126
  export const onlyByTheme = (index, opts) => { const r = scan(index, opts); return r.rows.length > 0 && !r.specific }
118
127
 
package/lib/picker.js CHANGED
@@ -318,6 +318,7 @@
318
318
  if (fx) fx.host.style.setProperty('--k', K)
319
319
  if (editUi) editUi.host.style.setProperty('--k', K)
320
320
  placePin()
321
+ if (anMarks.length) placeAnnots()
321
322
  }
322
323
 
323
324
  function mount(hint) {
@@ -593,6 +594,14 @@
593
594
  transform:scale(var(--k, 1));transform-origin:0 0;box-shadow:0 2px 6px rgba(0,0,0,.25)}
594
595
  .ck.hi b{background:#e5484d}
595
596
  .ck.on{animation:ck-on 1.2s ease-out}
597
+ .an{position:absolute;pointer-events:none;border-radius:4px}
598
+ .an.sel{outline:calc(2px * var(--k, 1)) solid #4d6bfe;outline-offset:calc(1px * var(--k, 1));background:rgba(77,107,254,.07)}
599
+ .an b{position:absolute;left:calc((var(--i, 0) * 21px - 9px) * var(--k, 1));top:calc(-9px * var(--k, 1));min-width:18px;height:18px;padding:0 4px;box-sizing:border-box;border-radius:9px;
600
+ border:1.5px solid #4d6bfe;background:#fff;color:#4d6bfe;font:700 11px/15px -apple-system,BlinkMacSystemFont,system-ui,sans-serif;text-align:center;
601
+ transform:scale(var(--k, 1));transform-origin:0 0;box-shadow:0 2px 6px rgba(0,0,0,.25);pointer-events:auto;cursor:pointer}
602
+ .an.sel b{background:#4d6bfe;color:#fff}
603
+ .an.fl{animation:an-fl 1.2s ease-out}
604
+ @keyframes an-fl{0%,40%{box-shadow:0 0 0 calc(6px * var(--k, 1)) rgba(77,107,254,.35)}100%{box-shadow:0 0 0 0 rgba(77,107,254,0)}}
596
605
  .cut{position:absolute;pointer-events:none;border:calc(2px * var(--k, 1)) solid #e5484d;border-radius:4px;box-shadow:0 0 0 1px rgba(255,255,255,.85)}
597
606
  .cut.alt{border-color:#f59e0b;border-style:dashed}
598
607
  .cut b{position:absolute;left:calc(-2px * var(--k, 1));bottom:100%;margin-bottom:calc(3px * var(--k, 1));padding:0 6px;border-radius:4px;background:#e5484d;color:#fff;
@@ -4221,6 +4230,10 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
4221
4230
  try {
4222
4231
  goScrollHome('instant') // 量的时候要滚动,别把闪改动的回位打断、停在半路
4223
4232
  await settle()
4233
+ // 刚换上来的帧,ready 可能早于第一次排版(视口还是 0×0,量出来是空清单):等排好版再量,等不到就照实说没量成,别当成「没问题」
4234
+ const laidOut = () => innerWidth > 0 && innerHeight > 0 && document.documentElement.clientWidth > 0 && document.documentElement.getClientRects().length > 0
4235
+ for (let i = 0; i < 60 && !laidOut(); i++) await new Promise((res) => setTimeout(res, 50))
4236
+ if (!laidOut()) throw new Error('layout')
4224
4237
  r = runCheck(String(d.kind || 'web'))
4225
4238
  } catch (e) {
4226
4239
  // 量的时候出错了:照实说没量成,别当成「没问题」
@@ -4236,6 +4249,233 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
4236
4249
  post({ type: 'checked', id: d.id, issues: r.issues.map(({ el, ...rest }) => rest), metrics: r.metrics, width: r.metrics.w })
4237
4250
  }
4238
4251
 
4252
+ // ── 业务标注:编号圆点、选中才描框、点编号回报。内容(annotations.json)由右侧栏发来,全当数据:选择器只进 querySelector,文字只用 textContent ──
4253
+ let anMarks = [] // { a, el, node, dot }
4254
+ let anSel = ''
4255
+ let anRaf = 0
4256
+ let anMo = null
4257
+ let anRo = null
4258
+ let anReT = 0
4259
+ let anReGap = 250
4260
+ let anLast = ''
4261
+
4262
+ const flatText = (s) => String(s || '').replace(/\s+/g, '').toLowerCase()
4263
+ const shownBox = (el) => {
4264
+ const r = el.getBoundingClientRect()
4265
+ if (r.width <= 0 && r.height <= 0) return false
4266
+ return !hiddenChain(el) // 自己或祖先 display:none、visibility:hidden、完全透明
4267
+ }
4268
+
4269
+ /** el 里看得见的字:藏着的、完全透明的文字节点不算 */
4270
+ function seenText(el) {
4271
+ let s = ''
4272
+ const w = document.createTreeWalker(el, NodeFilter.SHOW_TEXT)
4273
+ for (let n = w.nextNode(); n; n = w.nextNode()) if (n.parentElement && !hiddenChain(n.parentElement)) s += n.nodeValue
4274
+ return s
4275
+ }
4276
+
4277
+ /** 文字里含这段字、看得见、最小的那个元素(一段字被 <a> 切开也认) */
4278
+ function annotByText(text) {
4279
+ const want = flatText(text)
4280
+ if (!want || !document.body) return null
4281
+ let best = null
4282
+ let bestLen = Infinity
4283
+ for (const el of document.body.querySelectorAll('*')) {
4284
+ if (SKIP_TAGS.has(el.tagName) || el.tagName === 'STYLE' || el.tagName === 'DSH-DESIGN-EDIT') continue
4285
+ const tx = flatText(el.textContent)
4286
+ if (tx.length > bestLen || !tx.includes(want)) continue
4287
+ if (tx.length === bestLen && !(best && best.contains(el))) continue // 一样长:子元素比父元素准,别的地方的同样文字不抢第一处
4288
+ if (!shownBox(el) || !flatText(el.innerText ?? el.textContent).includes(want) || !flatText(seenText(el)).includes(want)) continue // 容器看得见、字在藏着、折叠或透明的子元素里:不算
4289
+ best = el
4290
+ bestLen = tx.length
4291
+ }
4292
+ return best
4293
+ }
4294
+
4295
+ /** 一条标注对应页面上哪个元素 → { el, how: selector / text / page(整屏的说明)/ ''(定位不到), count: 选择器匹配到几个 } */
4296
+ function findAnnot(a) {
4297
+ const selector = String((a && a.selector) || '')
4298
+ const text = String((a && a.fallbackText) || '')
4299
+ if (!selector && !text) return { el: document.body, how: 'page', count: 0 } // 整屏的说明:编号放在页面左上角
4300
+ let count = 0
4301
+ let el = null
4302
+ if (selector) {
4303
+ try {
4304
+ const all = document.querySelectorAll(selector)
4305
+ count = all.length
4306
+ el = all[0] || null
4307
+ } catch { /* 选择器写法不对:当作没找到 */ }
4308
+ if (el) return { el, how: 'selector', count }
4309
+ }
4310
+ el = annotByText(text)
4311
+ return { el, how: el ? 'text' : '', count }
4312
+ }
4313
+
4314
+ /** 元素没被能滚、能裁的容器挡住的那块(视口坐标);全挡住了是 null:编号别飘在外面 */
4315
+ function annotVisible(el) {
4316
+ const r = el.getBoundingClientRect()
4317
+ const box = { left: r.left, top: r.top, right: r.right, bottom: r.bottom }
4318
+ let mode = getComputedStyle(el).position
4319
+ for (let p = el.parentElement; p && p !== document.body && p !== document.documentElement; p = p.parentElement) {
4320
+ const o = getComputedStyle(p)
4321
+ if ((mode === 'absolute' && !holds(o, false)) || (mode === 'fixed' && !holds(o, true))) continue // 这层不是它的包含块,裁不到它
4322
+ mode = o.position
4323
+ if (o.overflowX === 'visible' && o.overflowY === 'visible') continue
4324
+ const c = p.getBoundingClientRect()
4325
+ if (o.overflowX !== 'visible') { box.left = Math.max(box.left, c.left); box.right = Math.min(box.right, c.right) }
4326
+ if (o.overflowY !== 'visible') { box.top = Math.max(box.top, c.top); box.bottom = Math.min(box.bottom, c.bottom) }
4327
+ if ((r.width > 0 && box.right <= box.left) || (r.height > 0 && box.bottom <= box.top)) return null
4328
+ }
4329
+ // 再和视口取交集(整个在视口外就按版面位置算,滚到了自然对)
4330
+ const vp = { left: Math.max(box.left, 0), top: Math.max(box.top, 0), right: Math.min(box.right, innerWidth), bottom: Math.min(box.bottom, innerHeight) }
4331
+ const seen = vp.right > vp.left && vp.bottom > vp.top ? vp : box
4332
+ return { ...seen, partial: seen.left > r.left + 1 || seen.top > r.top + 1 || seen.right < r.right - 1 || seen.bottom < r.bottom - 1 }
4333
+ }
4334
+
4335
+ function placeAnnots() {
4336
+ for (const m of anMarks) {
4337
+ const vis = m.el && m.el.isConnected && shownBox(m.el) ? annotVisible(m.el) : null
4338
+ if (!vis) { m.node.style.display = 'none'; continue }
4339
+ const r = docRect(m.el)
4340
+ Object.assign(m.node.style, { display: '', left: r.left + 'px', top: r.top + 'px', width: r.width + 'px', height: r.height + 'px' })
4341
+ // 编号放在露出来的那块的左上角;贴着页面边的往里挪,描框位置不变
4342
+ const b = m.el.getBoundingClientRect()
4343
+ const inset = (hid, at) => (hid > 1 ? hid + 9 * K : Math.max(0, 9 * K - at))
4344
+ const ml = inset(vis.left - b.left, r.left)
4345
+ const mt = inset(vis.top - b.top, r.top)
4346
+ m.dot.style.marginLeft = ml ? `${ml}px` : ''
4347
+ m.dot.style.marginTop = mt ? `${mt}px` : ''
4348
+ }
4349
+ }
4350
+ const queueAnnots = () => { if (!anRaf) anRaf = requestAnimationFrame(() => { anRaf = 0; placeAnnots() }) }
4351
+
4352
+ // 同一个元素上的几条:编号往右排开
4353
+ function spreadDots() {
4354
+ const perEl = new Map()
4355
+ for (const m of anMarks) {
4356
+ if (!m.el) continue
4357
+ const i = perEl.get(m.el) || 0
4358
+ perEl.set(m.el, i + 1)
4359
+ m.dot.style.setProperty('--i', i)
4360
+ }
4361
+ }
4362
+ const postAnnotState = () => post({ type: 'annotState', list: anMarks.map((m) => ({ id: m.a.id, how: m.how, count: m.count })) })
4363
+
4364
+ /** 页面内容变了(切标签、脚本重画):每条重新对一遍,后冒出来的补上编号、选择器换了对象跟过去、状态报回右侧栏。这一轮太费时就放慢 */
4365
+ function relocateAnnots() {
4366
+ anReT = 0
4367
+ const t0 = performance.now()
4368
+ let moved = false
4369
+ let state = false
4370
+ for (const m of anMarks) {
4371
+ const f = findAnnot(m.a)
4372
+ if (f.el !== m.el) { m.el = f.el; moved = true }
4373
+ if (f.how !== m.how || f.count !== m.count) { m.how = f.how; m.count = f.count; state = true }
4374
+ }
4375
+ if (moved) spreadDots()
4376
+ if (moved || state) placeAnnots()
4377
+ if (state) postAnnotState()
4378
+ anReGap = Math.min(3000, Math.max(250, (performance.now() - t0) * 20))
4379
+ }
4380
+ const onAnnotDom = () => { queueAnnots(); if (!anReT) anReT = setTimeout(relocateAnnots, anReGap) }
4381
+
4382
+ function watchAnnots(on) {
4383
+ if (on && !anMo) {
4384
+ addEventListener('scroll', queueAnnots, true) // 捕获:里面能滚的区域也算
4385
+ addEventListener('resize', queueAnnots)
4386
+ document.addEventListener('load', onAnnotDom, true) // 图片晚到把版面推走(load 到不了 window,捕获挂在 document)
4387
+ addEventListener('change', onAnnotDom, true) // 纯 CSS 的切换(:checked 换标签内容)没有 DOM 变化
4388
+ addEventListener('input', onAnnotDom, true)
4389
+ addEventListener('transitionend', queueAnnots, true)
4390
+ addEventListener('animationend', queueAnnots, true)
4391
+ anMo = new MutationObserver(onAnnotDom)
4392
+ if (document.body) anMo.observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true })
4393
+ anMo.observe(document.documentElement, { attributes: true }) // 根节点上切 class / data-view 换内容
4394
+ if (typeof ResizeObserver === 'function') {
4395
+ anRo = new ResizeObserver(queueAnnots) // 区域展开、字体换行,页面整体变高
4396
+ anRo.observe(document.documentElement)
4397
+ if (document.body) anRo.observe(document.body)
4398
+ }
4399
+ } else if (!on && anMo) {
4400
+ removeEventListener('scroll', queueAnnots, true)
4401
+ removeEventListener('resize', queueAnnots)
4402
+ document.removeEventListener('load', onAnnotDom, true)
4403
+ removeEventListener('change', onAnnotDom, true)
4404
+ removeEventListener('input', onAnnotDom, true)
4405
+ removeEventListener('transitionend', queueAnnots, true)
4406
+ removeEventListener('animationend', queueAnnots, true)
4407
+ anMo.disconnect()
4408
+ anMo = null
4409
+ if (anRo) anRo.disconnect()
4410
+ anRo = null
4411
+ }
4412
+ }
4413
+
4414
+ function clearAnnots() {
4415
+ for (const m of anMarks) m.node.remove()
4416
+ anMarks = []
4417
+ clearTimeout(anReT)
4418
+ anReT = 0
4419
+ watchAnnots(false)
4420
+ }
4421
+
4422
+ function setAnnotSel(id) {
4423
+ anSel = String(id || '')
4424
+ for (const m of anMarks) m.node.classList.toggle('sel', m.a.id === anSel)
4425
+ }
4426
+
4427
+ const pickAnnot = (m) => { setAnnotSel(m.a.id); post({ type: 'annotPick', id: m.a.id }) }
4428
+
4429
+ function showAnnots(list, sel) {
4430
+ clearAnnots()
4431
+ const items = Array.isArray(list) ? list.slice(0, 200) : []
4432
+ if (!items.length) { anSel = ''; return }
4433
+ const { root } = fxRoot()
4434
+ for (const a of items) {
4435
+ const f = findAnnot(a) // 这会儿定位不到的也留着:页面后面长出来时补上编号
4436
+ const node = document.createElement('div')
4437
+ node.className = 'an'
4438
+ const dot = document.createElement('b')
4439
+ dot.textContent = String(a.n)
4440
+ const m = { a, el: f.el, how: f.how, count: f.count, node, dot }
4441
+ dot.addEventListener('click', (e) => { e.stopPropagation(); e.preventDefault(); pickAnnot(m) })
4442
+ node.append(dot)
4443
+ root.append(node)
4444
+ anMarks.push(m)
4445
+ }
4446
+ spreadDots()
4447
+ setAnnotSel(sel)
4448
+ placeAnnots()
4449
+ watchAnnots(true)
4450
+ postAnnotState()
4451
+ // 字体、图片晚到会把版面推走
4452
+ setTimeout(placeAnnots, 400)
4453
+ if (document.fonts && document.fonts.ready) document.fonts.ready.then(placeAnnots).catch(() => {})
4454
+ }
4455
+
4456
+ /** 右侧栏点了这张卡片:滚过去,描框,闪一下 */
4457
+ function focusAnnot(id) {
4458
+ anLast = String(id || '')
4459
+ setAnnotSel(id)
4460
+ const m = anMarks.find((x) => x.a.id === id)
4461
+ if (!m || !m.el || !m.el.isConnected) return
4462
+ const go = () => { m.node.classList.remove('fl'); void m.node.offsetWidth; m.node.classList.add('fl') }
4463
+ if (m.how === 'page') { scrollAll(scrollAreas(), false); placeAnnots(); go(); return }
4464
+ const vis = annotVisible(m.el)
4465
+ if (inView(m.el) && vis && !vis.partial) { go(); return }
4466
+ try { m.el.scrollIntoView({ behavior: 'smooth', block: 'center' }) } catch { m.el.scrollIntoView() }
4467
+ setTimeout(() => { placeAnnots(); go() }, 450)
4468
+ }
4469
+
4470
+ /** 画布上每屏盖着一层挡板,点不到页面:右侧栏把点的位置告诉页面,点中编号就算点了它 */
4471
+ function hitAnnot(x, y) {
4472
+ for (const m of [...anMarks].reverse()) {
4473
+ if (m.node.style.display === 'none') continue
4474
+ const r = m.dot.getBoundingClientRect()
4475
+ if (x >= r.left - 3 && x <= r.right + 3 && y >= r.top - 3 && y <= r.bottom + 3) { pickAnnot(m); return }
4476
+ }
4477
+ }
4478
+
4239
4479
  // ── 深色模式:页面带了深色样式([data-theme="dark"] / .dark / prefers-color-scheme: dark)就能切 ──
4240
4480
 
4241
4481
  let darkOn = false
@@ -4344,6 +4584,10 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
4344
4584
  else if (d.type === 'check') onCheck(d)
4345
4585
  else if (d.type === 'checkClear') { clearMarks(); lastIssues = [] }
4346
4586
  else if (d.type === 'checkFocus') { holdScroll(); focusIssue(Number(d.i)) } // 用户点了别的地方要看,别再滚回去
4587
+ else if (d.type === 'annots') showAnnots(d.list, d.sel)
4588
+ else if (d.type === 'annotSel') setAnnotSel(d.id)
4589
+ else if (d.type === 'annotFocus') { holdScroll(); focusAnnot(String(d.id || '')) }
4590
+ else if (d.type === 'annotHit') hitAnnot(Number(d.x), Number(d.y))
4347
4591
  else if (d.type === 'theme') { setDark(d.dark); postTop(); setTimeout(postTop, 400) }
4348
4592
  else if (d.type === 'demo') demo = !!d.on
4349
4593
  else if (d.type === 'edit') setTextEdit(!!d.on, d.hint !== false)
@@ -4374,6 +4618,15 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
4374
4618
  /** 调节滑块的值套到页面上(和右侧栏拖的时候一样) */
4375
4619
  tweak: (vars, attrs) => { applyTweak(vars, attrs); return true },
4376
4620
  settle: () => settle().then(() => true),
4621
+ /** 业务标注定位得到吗(只找,不画):[{ id, how, count }] */
4622
+ annots: async (list) => {
4623
+ await settle()
4624
+ return (Array.isArray(list) ? list.slice(0, 200) : []).map((a) => { const f = findAnnot(a); return { id: a.id, how: f.how, count: f.count } })
4625
+ },
4626
+ /** 页面上现在画着哪几条业务标注的编号(id) */
4627
+ annotMarks: () => anMarks.filter((m) => m.node.isConnected && m.node.style.display !== 'none').map((m) => m.a.id),
4628
+ /** 最后被右侧栏定位的是哪条 */
4629
+ annotLast: () => anLast,
4377
4630
  /** 跳到别的屏的地方(路径和按钮上的字),量完查一下目标在不在 */
4378
4631
  links: () => linksOf().map(({ path, text }) => ({ path, text })),
4379
4632
  info: () => {
package/lib/serve.js CHANGED
@@ -68,6 +68,7 @@ export const MIME = {
68
68
  // 改动通知里不算的:版本库、依赖、系统垃圾
69
69
  const EXPORTS = /^(exports([\\/][^\\/]+\.(png|pdf|pptx))?|refs([\\/][^\\/]+\.(png|jpe?g|gif|webp))?)$/i // 导出的图片 / PDF / PPT、参考图(和第一次建的 exports / refs 目录):不算设计改了
70
70
  const IGNORED = /(^|[\\/])(\.git|node_modules|\.DS_Store|\.next|\.cache|\.turbo)([\\/]|$)/
71
+ const ANNOTATIONS = /^annotations\.json(\.[0-9a-z]+\.tmp)?$/i // 业务标注(DSH 写文件时先写 .tmp 再改名):右侧栏靠轮询跟上,页面用不到它,别一改就整屏刷新
71
72
  const HANDOFF = /^handoff([\\/]|$)/i // 转成代码的交接包(说明和截图):不算设计改了,也别在截图时把页面刷掉
72
73
 
73
74
  /** 只认本机名 + 自己的端口(防 DNS 重绑定:外站把域名解析到 127.0.0.1 也进不来) */
@@ -305,7 +306,7 @@ export function draftInjector(tag) {
305
306
  }
306
307
  }
307
308
 
308
- export function createHub({ log = () => {}, onChange = () => {}, history = null, parents = () => [], strict = null, drafts = null } = {}) {
309
+ export function createHub({ log = () => {}, onChange = () => {}, history = null, parents = () => [], strict = null, drafts = null, skipAnnots = () => false } = {}) {
309
310
  const strictHtml = (buf) => { try { return !!(strict && strict.html && strict.html(buf)) } catch (e) { log(e); return true } }
310
311
  const strictRoot = (dir) => { try { return !!(strict && strict.root && strict.root(dir)) } catch (e) { log(e); return true } }
311
312
  const strictVer = (dir) => { try { return !!(strict && strict.versions && strict.versions(dir)) } catch (e) { log(e); return true } }
@@ -521,7 +522,7 @@ export function createHub({ log = () => {}, onChange = () => {}, history = null,
521
522
  try {
522
523
  entry.watcher = fs.watch(entry.root, { recursive: true }, (_type, name) => {
523
524
  const rel = String(name || '')
524
- if (IGNORED.test(rel) || /(^|[\\/])\./.test(rel) || EXPORTS.test(rel) || HANDOFF.test(rel)) return
525
+ if (IGNORED.test(rel) || /(^|[\\/])\./.test(rel) || EXPORTS.test(rel) || HANDOFF.test(rel) || (skipAnnots() && ANNOTATIONS.test(rel))) return
525
526
  last = rel
526
527
  batch.add(rel.split(path.sep).join('/'))
527
528
  clearTimeout(timer)