dsh-design-studio 1.0.2 → 1.1.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/index.js CHANGED
@@ -19,6 +19,8 @@
19
19
  * GET /dsh-design-studio/api/state?session= 右侧栏轮询:预览什么、有哪几屏、要不要弹出来、模型在不在干活、
20
20
  * 模型要不要体检(checkReq)
21
21
  * POST /dsh-design-studio/api/check 体检结果交给 check_design { session, id, text, measured } 或 { session, id, error }
22
+ * POST /dsh-design-studio/api/drift 共用部件各屏写得不一样(体检面板单独一组){ session } → { items, more, total }
23
+ * POST /dsh-design-studio/api/states 各屏写了哪几个状态(导出「每个状态各出一张」){ session } → { map: { key: [{ name, label }] } }
22
24
  * (measured = 0:一屏都没量到,先不收,等别的右侧栏)
23
25
  * POST /dsh-design-studio/api/open 地址栏输入新地址 { session, target }
24
26
  * POST /dsh-design-studio/api/view 改类型 / 尺寸 / 视图,或换到另一屏 { session, kind?, size?, view?, focus? }
@@ -49,7 +51,7 @@ import path from 'node:path'
49
51
  import { fileURLToPath } from 'node:url'
50
52
  import os from 'node:os'
51
53
  import { execFile } from 'node:child_process'
52
- import { createHub, webOrigins, trustedOrigins, resolveInRoot, ERR_CATCHER, defang } from './serve.js'
54
+ import { createHub, webOrigins, trustedOrigins, resolveInRoot, ERR_CATCHER, stateScript, defang } from './serve.js'
53
55
  import { bundle, inlinePicker, strictMeta, MAX_TOTAL as BUNDLE_MAX } from './bundle.js'
54
56
  import { buildPack, PACK_SCREENS } from './htmlpack.js'
55
57
  import { createLibrary } from './works.js'
@@ -76,6 +78,8 @@ import { readAnnotations, lintAnnotations, annotationFindings, annotationSection
76
78
  import { createImpl } from './impl.js'
77
79
  import { FRAMEWORKS, detectProject, projectFor, defaultFramework, buildHandoff, compareScreens, implUrl, implServe, defaultDest, pickedDest, within, pinRoots, frameCss } from './handoff.js'
78
80
  import { editsNotice, noticeMessage, langOf } from './edits.js'
81
+ import { statesOfFile, expandStates, splitStateNames, withState } from './states.js'
82
+ import { partDrift, formatDrift } from './drift.js'
79
83
 
80
84
  export const name = 'dsh-design-studio'
81
85
  export const inject = ['webServer']
@@ -208,6 +212,53 @@ function designFor(id) {
208
212
  return { snap, ...designOf(snap, () => metaOfFile(focus) || (first && first !== focus ? metaOfFile(first) : '')) }
209
213
  }
210
214
 
215
+ /** 共用部件各屏写得不一样(#30 第 1 步):这套设计(本地文件)所有屏比一遍;没有就是 null */
216
+ const driftSeen = new Map() // 目录 → { stamp, r }:各屏没改过就不再读一遍
217
+ function driftOf(id) {
218
+ const t = studio.tracker.snapshot(id).target
219
+ if (!t || t.kind !== 'file') return null
220
+ const root = t.root || path.dirname(t.file)
221
+ const keys = allScreens(root)
222
+ if (keys.length < 2) return null
223
+ const stamp = keys.slice(0, 600).map((k) => { try { const s = fs.statSync(path.join(root, k)); return `${k}:${s.mtimeMs}:${s.size}` } catch { return '' } }).join('|')
224
+ const hit = driftSeen.get(root)
225
+ if (hit && hit.stamp === stamp) return hit.r
226
+ let r = null
227
+ try { r = { ...partDrift(root, keys), total: keys.length } } catch (e) { studio.log(e); return null }
228
+ driftSeen.delete(root)
229
+ driftSeen.set(root, { stamp, r })
230
+ if (driftSeen.size > 8) driftSeen.delete(driftSeen.keys().next().value)
231
+ return r
232
+ }
233
+ const driftNotes = (id) => { const r = driftOf(id); return r ? formatDrift(r, r.total) : '' }
234
+
235
+ /** 一页多状态(#30):屏 → 它的文件里写了哪几个状态(不是本地文件的设计当没写) */
236
+ function statesOfScreen(id) {
237
+ const t = studio.tracker.snapshot(id).target
238
+ if (!t || t.kind !== 'file') return () => []
239
+ const root = t.root || path.dirname(t.file)
240
+ return (sc) => {
241
+ const hit = sc && typeof sc.key === 'string' ? resolveInRoot(root, sc.key) : null
242
+ return hit && hit.real ? statesOfFile(hit.real) : []
243
+ }
244
+ }
245
+
246
+ /** screens 里点名的状态这屏没写:说出来(这屏有哪几个),别当量过 / 截过了。all:那屏一个都没对上时怎么办的 */
247
+ function stateMisses(list, stOf, only, all) {
248
+ if (!only) return ''
249
+ const out = []
250
+ for (const sc of list) {
251
+ const want = only(sc)
252
+ if (!want) continue
253
+ const st = stOf(sc)
254
+ const bad = [...want].filter((n) => !st.some((x) => x.name === n))
255
+ if (!bad.length) continue
256
+ const none = bad.length === want.size
257
+ out.push(`${sc.key} 没有状态 ${bad.join('、')}(${st.length ? `这屏有:${st.map((x) => x.name).join('、')}` : '这屏没写状态'})${none ? `,${all}` : ''}`)
258
+ }
259
+ return out.length ? `\n点名的状态没找到:${out.join(';')}` : ''
260
+ }
261
+
211
262
  /** 工具参数里的尺寸:'375x667' / 375 / ['375', '430x932'] → [[w, h]],认不出的记下来 */
212
263
  function sizesFrom(v, kind) {
213
264
  const list = Array.isArray(v) ? v : v == null || v === '' ? [] : [v]
@@ -240,7 +291,7 @@ export const checkTool = {
240
291
  `严重的问题(被栏压住、文字叠在一起 / 被截断 / 超出框、超出屏幕、图片没出来、对比度很低)自动附上那一块的局部截图(最多 ${MAX_CROPS} 张,红框圈出元素)。` +
241
292
  '要先用 preview_page 打开过页面。',
242
293
  parameters: specToJsonSchema({
243
- screens: { type: 'array', items: { type: 'string' }, description: '量哪几屏:文件名(home.html 或 home)或开发服务器的路由;不填量全部' },
294
+ screens: { type: 'array', items: { type: 'string' }, description: '量哪几屏:文件名(home.html 或 home)或开发服务器的路由;不填量全部。写了几个状态的屏每个状态都量,只量某个状态写 order.html?state=paid' },
244
295
  sizes: { type: 'array', items: { type: 'string' }, description: '按哪几种尺寸量,如 ["375x667", "390x844", "430x932"],或只写宽度 ["320", "375"](高按机型);不填按设计的尺寸。最多 4 种' },
245
296
  dark: { type: 'boolean', description: '切到深色量(页面带深色样式时)' },
246
297
  images: { type: 'boolean', description: `严重问题附局部截图(默认附,最多 ${MAX_CROPS} 张);false 只要文字` },
@@ -265,9 +316,14 @@ export const checkTool = {
265
316
  const anAt = annotationsAt(id) // 开始量时的设计目录和标注:量的过程中换了设计也不串
266
317
  if (b && b.available()) {
267
318
  try {
268
- const pick = pickScreens(snap, a.screens, MAX_SCREENS)
269
- if (!pick.list.length) return { text: `没找到要量的屏:${pick.missing.join('、')}。现在有:${(snap.screens || []).map((x) => x.key).join('、') || snap.focus}` }
270
- const sizes = want.sizes.length ? want.sizes : [await fitted(b, design, a.screens)]
319
+ // 一页多状态(#30):写了几个状态的屏,每个状态各量一遍;screens 里写了 order.html?state=paid 的只量那个状态
320
+ const sn = splitStateNames(a.screens, (n) => pickScreens(snap, [n], 1).list[0])
321
+ const pick0 = pickScreens(snap, sn.names, MAX_SCREENS)
322
+ if (!pick0.list.length) return { text: `没找到要量的屏:${pick0.missing.join('、')}。现在有:${(snap.screens || []).map((x) => x.key).join('、') || snap.focus}` }
323
+ const stOf = statesOfScreen(id)
324
+ const ex = expandStates(pick0.list, stOf, { only: sn.only })
325
+ const pick = { ...pick0, list: ex.list }
326
+ const sizes = want.sizes.length ? want.sizes : [await fitted(b, design, sn.names)]
271
327
  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) })
272
328
  if (rows.some((r) => !r.error)) {
273
329
  // 同一个会话上次量的结果:这次比一比修好了几个、新出了几个
@@ -287,7 +343,9 @@ export const checkTool = {
287
343
  while (lastChecks.size > 20) lastChecks.delete(lastChecks.keys().next().value)
288
344
  if (want.bad.length) text += `\n认不出的尺寸(没量):${want.bad.join('、')},写成 375x667 或 375`
289
345
  if (want.more) text += `\n尺寸太多,只量了前 ${MAX_SIZES} 种`
290
- text += tweakNotes(id) + annotationNotes(anAt, rows)
346
+ if (ex.skipped) text += `\n状态太多,有 ${ex.skipped} 个状态没量:screens 写成 order.html?state=状态名 单量那个状态`
347
+ text += stateMisses(pick0.list, stOf, sn.only, '量的是这屏全部状态')
348
+ text += tweakNotes(id) + annotationNotes(anAt, rows) + driftNotes(id)
291
349
  return kept && kept.images ? { text, images: kept.images } : { text }
292
350
  }
293
351
  studio.log(new Error(`check_design 无头浏览器没量成:${rows[0] && rows[0].error}`))
@@ -301,7 +359,7 @@ export const checkTool = {
301
359
  const note = want.sizes.length || a.dark ? '(这台电脑上没找到能用的 Chrome / Edge,没法按指定尺寸 / 深色量;下面是右侧栏按它现在显示的尺寸量的)\n' : ''
302
360
  if (!r) return { text: '右侧栏「设计工作台」现在没开着,量不了。照 ui-design 技能里的「自查」清单自己过一遍。' }
303
361
  if (!r.error && !r.measured) return { text: '右侧栏开着,但预览页面没回应,这次没量成(可能还在加载)。过一会儿再调一次,或照 ui-design 技能里的「自查」清单自己过一遍。' }
304
- return { text: note + (r.error || r.text) + tweakNotes(id) + annotationNotes(anAt, null) }
362
+ return { text: note + (r.error || r.text) + tweakNotes(id) + annotationNotes(anAt, null) + (r.error ? '' : driftNotes(id)) }
305
363
  },
306
364
  }
307
365
 
@@ -403,7 +461,7 @@ export const lookTool = {
403
461
  '默认每屏截顶上一屏;at=bottom 滚到底(看底栏有没有压住内容)、at=full 从上到下每屏一张;selector 只截一个元素;size 换尺寸(如 375x667 或 375);dark 看深色。' +
404
462
  `一次最多 ${MAX_SHOTS} 张。自己检查视觉效果(层次、留白、配色、图片、整体观感)用这个;要问题清单和数字用 check_design。要先用 preview_page 打开过页面。`,
405
463
  parameters: specToJsonSchema({
406
- screens: { type: 'array', items: { type: 'string' }, description: `截哪几屏:文件名(home.html 或 home)或开发服务器的路由;不填截全部(最多 ${MAX_SHOTS} 屏)` },
464
+ screens: { type: 'array', items: { type: 'string' }, description: `截哪几屏:文件名(home.html 或 home)或开发服务器的路由;不填截全部(最多 ${MAX_SHOTS} 屏)。看某个状态写 order.html?state=paid` },
407
465
  size: { type: 'string', description: '尺寸,如 375x667,或只写宽度 375(高按机型);不填按设计的尺寸' },
408
466
  at: { type: 'string', enum: ['top', 'bottom', 'full'], description: 'top 顶上一屏(默认)、bottom 滚到底、full 从上到下每屏一张' },
409
467
  selector: { type: 'string', description: '只截这个元素(CSS 选择器),如 .tabbar、#hero' },
@@ -426,14 +484,25 @@ export const lookTool = {
426
484
  if (!b || !b.available()) return { text: '这台电脑上没找到 Chrome / Edge(无头浏览器截图要用),看不了。用 check_design 拿测量数字,或者让用户看右侧栏。' }
427
485
  const design = designFor(id)
428
486
  const { snap, kind } = design
429
- const want = a.size ? sizeOf(a.size, kind) : await fitted(b, design, a.screens)
487
+ const sn = splitStateNames(a.screens, (n) => pickScreens(snap, [n], 1).list[0])
488
+ let miss = ''
489
+ const want = a.size ? sizeOf(a.size, kind) : await fitted(b, design, sn.names)
430
490
  if (!want) return { text: `认不出尺寸「${String(a.size).slice(0, 20)}」:写成 375x667,或只写宽度 375。` }
431
491
  const at = ['top', 'bottom', 'full'].includes(a.at) ? a.at : 'top'
432
- const pick = pickScreens(snap, a.screens, MAX_SHOTS)
492
+ const pick = pickScreens(snap, sn.names, MAX_SHOTS)
493
+ if (sn.only) { // 看某个状态:那一屏换成带 ?state= 的地址(文件里没写这个状态的照原样截)
494
+ const stOf = statesOfScreen(id)
495
+ miss = stateMisses(pick.list, stOf, sn.only, '截的是默认状态')
496
+ pick.list = pick.list.flatMap((sc) => {
497
+ const want = sn.only(sc)
498
+ const has = want ? stOf(sc).filter((x) => want.has(x.name)) : []
499
+ return has.length ? has.map((x) => ({ ...sc, key: `${sc.key}?state=${x.name}`, url: withState(sc.url, x.name), label: `${sc.label || sc.key}(${x.label})` })) : [sc]
500
+ }).slice(0, MAX_SHOTS)
501
+ }
433
502
  if (!pick.list.length) return { text: `没找到要截的屏:${pick.missing.join('、')}。现在有:${(snap.screens || []).map((x) => x.key).join('、') || snap.focus}` }
434
503
  const shots = await shootAll(b, { screens: pick.list, size: want, at, selector: a.selector, dark: !!a.dark, kind, max: MAX_SHOTS })
435
504
  const good = shots.filter((s) => s.jpg).slice(0, MAX_SHOTS)
436
- const text = formatShots(shots, { where: whereOf(snap), missing: pick.missing, more: pick.more, kind })
505
+ const text = formatShots(shots, { where: whereOf(snap), missing: pick.missing, more: pick.more, kind }) + miss
437
506
  if (!good.length) return { text }
438
507
  const kept = await keepImages(ctx, id, good, true)
439
508
  if (kept.images) return { text, images: kept.images }
@@ -1441,6 +1510,33 @@ export function apply(ctx) {
1441
1510
  * 按目录 + class 记一下(各屏的修改时间、大小都没变就不重读),点来点去不用每次全读
1442
1511
  */
1443
1512
  const shareSeen = new Map() // `${root}|${cls}` → { stamp, sigs: Set(sig) },只留最近 20 个
1513
+ /** 体检面板里「部件各屏写得不一样」那一组(#30):{ session } → { items, more, total }(不是本地文件 / 不到两屏:items 空) */
1514
+ async function driftRoute(req, res) {
1515
+ if (!admit(req, res)) return
1516
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1517
+ let body
1518
+ try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
1519
+ const r = driftOf(String(body.session || ''))
1520
+ json(res, 200, r || { items: [], more: 0, total: 0 })
1521
+ }
1522
+
1523
+ /** 导出「每个状态各出一张」(#30):各屏写了哪几个状态 { session } → { map: { key: [{ name, label }] } }(只列写了的屏) */
1524
+ async function statesRoute(req, res) {
1525
+ if (!admit(req, res)) return
1526
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1527
+ let body
1528
+ try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
1529
+ const st = tracker.stateOf(String(body.session || ''))
1530
+ const t = st && st.target
1531
+ if (!t || t.kind !== 'file') return json(res, 200, { map: {} })
1532
+ const map = {}
1533
+ for (const k of allScreens(t.root).slice(0, MAX_PAGES)) {
1534
+ const list = statesOfFile(path.join(t.root, k))
1535
+ if (list.length) map[k] = list
1536
+ }
1537
+ json(res, 200, { map })
1538
+ }
1539
+
1444
1540
  async function shareCheckRoute(req, res) {
1445
1541
  if (!admit(req, res)) return
1446
1542
  if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
@@ -1599,8 +1695,10 @@ export function apply(ctx) {
1599
1695
  const v = Math.max(0, Math.floor(Number(q.get('v')) || 0))
1600
1696
  let parent = ''
1601
1697
  try { const u = new URL(q.get('parent') || ''); if (u.protocol === 'http:' || u.protocol === 'https:') parent = u.origin } catch { parent = '' }
1602
- const href = st.origin ? `${st.origin}/${v ? `__dsh_design__/v/${v}/` : ''}${key.split('/').map(encodeURIComponent).join('/')}` : ''
1603
- const name = `${q.get('session') || ''}|${t.root}|${v}|${key}`
1698
+ // 一页多状态(#30):?state=paid 打包时就把 <html data-state> 设好(沙盒里的 srcdoc 没有地址参数,设状态那段读不到)
1699
+ const state = /^[A-Za-z0-9_-]{1,32}$/.test(q.get('state') || '') ? q.get('state') : ''
1700
+ const href = st.origin ? `${st.origin}/${v ? `__dsh_design__/v/${v}/` : ''}${key.split('/').map(encodeURIComponent).join('/')}${state ? '?state=' + state : ''}` : ''
1701
+ const name = `${q.get('session') || ''}|${t.root}|${v}|${key}|${state}`
1604
1702
  // fresh=1:右侧栏要求「真的重取」(刷新按钮、目录里刚改过、失败重试)。这种情况下服务端必须重新打包,
1605
1703
  // 不能拿印记去复用——mtime 精度粗的盘(HFS+ 1s、FAT32 2s、部分网络盘)上,同一刻度里改两次、
1606
1704
  // 大小又没变,印记一模一样,光靠标记永远换不出新内容
@@ -1646,7 +1744,9 @@ export function apply(ctx) {
1646
1744
  if (!page) return json(res, 404, { error: 'no-screen' })
1647
1745
  const strict = strictOf(page)
1648
1746
  const nonce = strict ? crypto.randomBytes(16).toString('base64') : ''
1649
- const lead = strict ? strictMeta(nonce) + ERR_CATCHER.replace('<script>', `<script nonce="${nonce}">`) : ERR_CATCHER
1747
+ // 页面写了这个状态才设(老页面自己拿 ?state= 当参数的不动)
1748
+ const setState = state ? stateScript(page.toString('utf8'), '?state=' + state) : ''
1749
+ const lead = strict ? strictMeta(nonce) + (ERR_CATCHER + setState).replaceAll('<script>', `<script nonce="${nonce}">`) : ERR_CATCHER + setState
1650
1750
  let html = bundle(strict ? defang(page.toString('utf8')) : page.toString('utf8'), { key, read, base: href, lead, tail: inlinePicker(fs.readFileSync(PICKER_FILE, 'utf8'), parent, href, nonce) })
1651
1751
  // 打包后图片变成 data: 地址,文件名没了:把用到的 AI 示意图记在页面里,导出时照样提醒
1652
1752
  const aiNames = [...deps].filter((x) => isPhotoAsset(x)).map((x) => path.basename(x))
@@ -1810,7 +1910,9 @@ export function apply(ctx) {
1810
1910
  pages = j.pages
1811
1911
  // 链接:目标屏的 key 换成第几页(没截上的屏不算)
1812
1912
  const at = new Map(pages.map((p, i) => [p.key, i]))
1813
- for (const p of pages) p.links = p.links.map((l) => (l && typeof l.key === 'string' ? { x: l.x, y: l.y, w: l.w, h: l.h, to: at.has(l.key) ? at.get(l.key) : -1 } : l)).filter((l) => l && l.to >= 0)
1913
+ // 跳到某个状态(order.html?state=paid):这次没按状态各出一页就跳到那屏
1914
+ const toOf = (k) => (at.has(k) ? at.get(k) : at.has(k.split('?')[0]) ? at.get(k.split('?')[0]) : -1)
1915
+ for (const p of pages) p.links = p.links.map((l) => (l && typeof l.key === 'string' ? { x: l.x, y: l.y, w: l.w, h: l.h, to: toOf(l.key) } : l)).filter((l) => l && l.to >= 0)
1814
1916
  } else {
1815
1917
  for (const p of Array.isArray(body.pages) ? body.pages.slice(0, MAX_PAGES) : []) {
1816
1918
  const pg = docPage(p)
@@ -2066,7 +2168,7 @@ export function apply(ctx) {
2066
2168
  })
2067
2169
  const mk = createMarketRoutes({ admit, readBody, json, tracker, library, market, open, systemsDir: SYSTEMS_DIR, log, sessionCwd })
2068
2170
 
2069
- const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, verthumb: canvasThumbs.verRoute, 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, hidden: hiddenRoute, edit: editRoute, style: styleRoute, sharecheck: shareCheckRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, htmlpack: htmlPackRoute, pubshare: pubShareRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute, impl: implRoute, implcmp: implCmpRoute, implshot: implShotRoute }
2171
+ const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, verthumb: canvasThumbs.verRoute, 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, hidden: hiddenRoute, edit: editRoute, style: styleRoute, sharecheck: shareCheckRoute, drift: driftRoute, states: statesRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, htmlpack: htmlPackRoute, pubshare: pubShareRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute, impl: implRoute, implcmp: implCmpRoute, implshot: implShotRoute }
2070
2172
  for (const [key, handler] of Object.entries(routes)) {
2071
2173
  ctx.effect(() => ctx.webServer.register({
2072
2174
  kind: 'exact',
package/lib/look.js CHANGED
@@ -9,6 +9,7 @@
9
9
  import fs from 'node:fs'
10
10
  import path from 'node:path'
11
11
  import { KIND_SIZE, KINDS as KIND_LIST, META_ALIAS } from './kinds.js'
12
+ import { stateName } from './states.js'
12
13
  export { KIND_SIZE }
13
14
 
14
15
  // 体检一次最多几个页面任务一起跑(#21:12 屏 × 4 尺寸一下全铺开会挤满事件循环;浏览器那边本来也只开 3 个页面)
@@ -174,7 +175,7 @@ export async function measureAll(browser, { screens, sizes, kind, dark, fetcher
174
175
  return gone.get(url)
175
176
  }
176
177
  const rows = await mapLimit(jobs, LOOK_PAR, async ({ sc, w, h }, i) => {
177
- const row = { key: sc.key, label: sc.label || sc.key, w, h, issues: [], metrics: null, error: '' }
178
+ const row = { key: sc.key, label: sc.label || sc.key, w, h, issues: [], metrics: null, error: '', ...(sc.state ? { base: sc.base || sc.key, state: sc.state, stateLabel: sc.stateLabel || '' } : null) }
178
179
  try {
179
180
  await browser.withPage({ url: sc.url, w, h, dark }, async (page) => {
180
181
  const { info, darkOk } = await prepare(page, dark)
@@ -213,21 +214,29 @@ export async function measureAll(browser, { screens, sizes, kind, dark, fetcher
213
214
  withRule.forEach((it, i) => { if (found[i] && found[i].file) Object.assign(it.rule, { file: found[i].file, line: found[i].line || 0 }) })
214
215
  }
215
216
  }
216
- // 跳到不存在的页面(404):算在这一屏每种尺寸上(不是某个尺寸才有的问题)
217
+ // 跳到不存在的页面(404):算在这一屏每种尺寸上(不是某个尺寸才有的问题)。
218
+ // 一页多状态(#30):同一屏的几个状态里同一个坏链接只报在头一个报出它的状态上
219
+ const deadOf = new Map() // 屏 → 报过的坏链接
217
220
  for (const sc of screens) {
218
221
  const first = rows.find((r) => r.key === sc.key && Array.isArray(r.links))
219
222
  if (!first) continue
220
223
  const dead = []
221
224
  const seen = new Set()
225
+ const base = sc.base || sc.key
226
+ if (!deadOf.has(base)) deadOf.set(base, new Set())
227
+ const told = deadOf.get(base)
228
+ let again = 0
222
229
  for (const l of first.links.slice(0, 40)) {
223
230
  if (!l || typeof l.path !== 'string' || seen.has(l.path)) continue
224
231
  seen.add(l.path)
232
+ if (told.has(l.path)) { again++; continue }
225
233
  let url
226
234
  try { url = new URL(l.path.split('/').map(encodeURIComponent).join('/'), sc.url).href } catch { continue }
227
- if (await isGone(url)) dead.push({ type: 'deadlink', sel: '', text: String(l.text || '').slice(0, 24), src: l.path.replace(/^\//, '') })
235
+ if (await isGone(url)) { told.add(l.path); dead.push({ type: 'deadlink', sel: '', text: String(l.text || '').slice(0, 24), src: l.path.replace(/^\//, '') }) }
228
236
  }
229
237
  for (const r of rows) if (r.key === sc.key && !r.error) r.issues.push(...dead)
230
238
  first.linkCount = seen.size // 查了几个跳转(没问题也让模型知道查过)
239
+ if (again) first.deadAgain = again // 前面那个状态已经报过的坏链接(这里不再列,但别说「都能打开」)
231
240
  }
232
241
  for (const r of rows) delete r.links
233
242
  return rows
@@ -486,7 +495,7 @@ export function detailOf(it) {
486
495
  }
487
496
 
488
497
  const sizeText = (w, h) => `${w}×${h}`
489
- const nameOf = (r) => `${r.key}${r.title && r.title !== r.key ? `「${r.title}」` : ''}`
498
+ const nameOf = (r) => `${r.state ? stateName(r.base || r.key, r.state, r.stateLabel) : r.key}${r.title && r.title !== r.key ? `「${r.title}」` : ''}`
490
499
 
491
500
  /** 一种尺寸下这一屏量出来的样子:页面多高、固定栏多高、离内容多远 */
492
501
  function metricsLine(m) {
@@ -543,6 +552,14 @@ export function formatMeasure(rows, { sizes, where, missing = [], more = 0, dark
543
552
  const unsure = new Set() // 上次有、这次这个尺寸没量成:不知道还在不在
544
553
  const nowThere = new Set(rows.flatMap((r) => r.issues.map((it) => `${r.key}|${compareKey(it)}`)))
545
554
  let compared = 0
555
+ // 一页多状态(#30):同一屏的坏链接只报在头一个状态上;这次和上次量的状态不一样时它会换个状态报,不算修好 / 新出
556
+ const baseOf = (r) => r.base || r.key
557
+ const deadMoved = (r, k, wasBefore) => {
558
+ if (!k.startsWith('deadlink|') || !r.state) return false
559
+ if (wasBefore) return rows.some((x) => !x.error && baseOf(x) === baseOf(r) && x.issues.some((it) => compareKey(it) === k))
560
+ const size = rowKey(r, dark).slice(r.key.length)
561
+ return [...prev].some(([pk, set]) => pk.endsWith(size) && pk.slice(0, -size.length).replace(/\?state=[A-Za-z0-9_-]+$/, '') === baseOf(r) && set.has(k))
562
+ }
546
563
  if (prev) {
547
564
  for (const r of rows) {
548
565
  const before = prev.get(rowKey(r, dark))
@@ -551,8 +568,8 @@ export function formatMeasure(rows, { sizes, where, missing = [], more = 0, dark
551
568
  if (r.error) continue
552
569
  compared++
553
570
  const now = new Set(r.issues.map(compareKey))
554
- for (const k of before) if (!now.has(k)) gone.add(`${r.key}|${k}`)
555
- for (const k of now) if (!before.has(k)) fresh.add(`${r.key}|${k}`)
571
+ for (const k of before) if (!now.has(k) && !deadMoved(r, k, true)) gone.add(`${r.key}|${k}`)
572
+ for (const k of now) if (!before.has(k) && !deadMoved(r, k, false)) fresh.add(`${r.key}|${k}`)
556
573
  }
557
574
  }
558
575
  // 和「发现 N 个」同一个单位:一个问题在几种尺寸上都出现算一个。这屏别的尺寸上还在的不算修好,换了个尺寸出现的也不算新出
@@ -609,7 +626,9 @@ export function formatMeasure(rows, { sizes, where, missing = [], more = 0, dark
609
626
  const lc = mine.find((r) => typeof r.linkCount === 'number')
610
627
  if (lc && lc.linkCount) {
611
628
  const dead = [...seen.values()].filter(({ it }) => it.type === 'deadlink').length
612
- lines.push(` 跳转:查了 ${lc.linkCount} 个,${dead ? `${dead} 个打不开(见上)` : '都能打开'}`)
629
+ const again = lc.deadAgain || 0
630
+ const why = [dead ? '见上' : '', again ? `${again} 个前面的状态里报过了` : ''].filter(Boolean).join(';')
631
+ lines.push(` 跳转:查了 ${lc.linkCount} 个,${dead + again ? `${dead + again} 个打不开(${why})` : '都能打开'}`)
613
632
  }
614
633
  }
615
634
  return lines.join('\n') + '\n'
package/lib/picker.js CHANGED
@@ -1308,6 +1308,12 @@
1308
1308
  return de.scrollWidth > Math.max(innerWidth, right + scrollX) + 40 || de.scrollHeight > Math.max(innerHeight, bottom + scrollY) + 40 ? 0 : [w, h]
1309
1309
  }
1310
1310
 
1311
+ /** 这一屏写了哪几个状态(<meta name="dsh-states">,原样给右侧栏解析)、现在是哪个 */
1312
+ function statesNow() {
1313
+ const m = document.querySelector('meta[name="dsh-states"]')
1314
+ return m ? { states: String(m.getAttribute('content') || '').slice(0, 400), state: curState() } : {}
1315
+ }
1316
+
1311
1317
  function boot(seed) {
1312
1318
  if (booted) return
1313
1319
  booted = true
@@ -1322,6 +1328,7 @@
1322
1328
  err: err ? String(err.getAttribute('content') || 'missing').slice(0, 20) : '',
1323
1329
  href: here(),
1324
1330
  meta: meta ? String(meta.getAttribute('content') || '').slice(0, 80) : '',
1331
+ ...statesNow(),
1325
1332
  tokens: tokensOf(),
1326
1333
  links: firstLinks(),
1327
1334
  dark: hasDark(),
@@ -1825,20 +1832,58 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1825
1832
  const LINK_JS = /(?:location(?:\.href)?\s*=\s*|location\.(?:assign|replace)\(\s*)['"]([^'"]+)['"]/
1826
1833
  const MAX_LINKS = 60
1827
1834
 
1828
- /** 这个元素点了会跳到同一个站点的哪一页(路径);不是跳页的给 '' */
1829
- function linkPath(el) {
1835
+ // 一页多状态(#30):<html data-state="paid">,地址 order.html?state=paid 打开那个状态。状态名只认这种写法(和 serve.js 设状态的那段一样)
1836
+ const STATE_RE = /^[A-Za-z0-9_-]{1,32}$/
1837
+ const stateOfUrl = (u) => { const s = u.searchParams.get('state'); return s && STATE_RE.test(s) ? s : '' }
1838
+ const curState = () => document.documentElement.getAttribute('data-state') || ''
1839
+ /** 现在是不是在写了的状态里、又不是默认(第一个)那个 */
1840
+ const offDefault = () => { const d = declaredStates(); const c = curState(); return !!c && d.length > 0 && d.includes(c) && c !== d[0] }
1841
+ /** 这页 <meta name="dsh-states"> 里写了哪几个状态(不到两个当没写;和 states.js 的 parseStates 一个规矩) */
1842
+ const declaredStates = () => {
1843
+ const m = document.querySelector('meta[name="dsh-states"]')
1844
+ const out = []
1845
+ for (const part of String((m && m.getAttribute('content')) || '').split(/[,,;;\n]+/)) {
1846
+ const x = /^\s*([A-Za-z0-9_-]{1,32})/.exec(part)
1847
+ if (x && !out.includes(x[1])) out.push(x[1])
1848
+ if (out.length >= 8) break
1849
+ }
1850
+ return out.length >= 2 ? out : []
1851
+ }
1852
+
1853
+ /** 这个元素点了去哪:{ path, state, back };不是跳页的给 null。
1854
+ * path:同一个站点的哪一页;state:带了 ?state= 就是那个状态;同一页换个状态也算跳(返回能退回来)。
1855
+ * back:写了 data-back(返回上一屏:试用、远程看按走过的路退一步,没得退才去 href) */
1856
+ function linkTo(el) {
1830
1857
  let raw = el.getAttribute('href') || el.getAttribute('data-href') || el.getAttribute('data-to') || ''
1831
1858
  if (!raw && el.hasAttribute('onclick')) {
1832
1859
  const m = LINK_JS.exec(el.getAttribute('onclick') || '')
1833
1860
  if (m) raw = m[1]
1834
1861
  }
1835
1862
  raw = raw.trim()
1836
- if (!raw || raw.startsWith('#') || /^(javascript|mailto|tel|sms|data):/i.test(raw)) return ''
1863
+ const back = el.hasAttribute('data-back')
1864
+ if (!raw || raw.startsWith('#') || /^(javascript|mailto|tel|sms|data):/i.test(raw)) return back ? { path: '', state: '', back } : null
1837
1865
  let u
1838
- try { u = new URL(raw, here()) } catch { return '' }
1866
+ try { u = new URL(raw, here()) } catch { return back ? { path: '', state: '', back } : null }
1839
1867
  const me = hereUrl()
1840
- if (u.origin !== me.origin || u.pathname === me.pathname) return ''
1841
- try { return decodeURIComponent(u.pathname) } catch { return u.pathname }
1868
+ if (u.origin !== me.origin) return back ? { path: '', state: '', back } : null
1869
+ let state = stateOfUrl(u)
1870
+ // 同一页:换个这页写了的状态算跳(没写的:老页面自己拿 ?state= 当参数,和以前一样当本页链接);
1871
+ // 在别的状态里点指着本页、不带状态也不带锚点的链接(href="order.html")= 回默认状态,也算跳
1872
+ // 回默认状态只认什么参数都不带的(?page=2 这种是页面自己的参数,照常当本页链接)
1873
+ if (u.pathname === me.pathname) {
1874
+ if (state && !declaredStates().includes(state)) state = ''
1875
+ if (state ? state === curState() : u.search || u.hash || /#$/.test(raw) || !offDefault()) return back ? { path: '', state: '', back } : null
1876
+ }
1877
+ let path = u.pathname
1878
+ try { path = decodeURIComponent(u.pathname) } catch { /* 原样 */ }
1879
+ // more:除了 state 还带了别的参数(?state=paid&page=2)
1880
+ return { path, state, back, hash: u.hash, more: [...u.searchParams.keys()].some((k) => k !== 'state') }
1881
+ }
1882
+
1883
+ /** 这个元素点了会跳到同一个站点的哪一页(路径);不是跳页的给 '' */
1884
+ function linkPath(el) {
1885
+ const l = linkTo(el)
1886
+ return l ? l.path : ''
1842
1887
  }
1843
1888
 
1844
1889
  const LINK_SEL = 'a[href], [data-href], [data-to], [onclick]'
@@ -1860,7 +1905,8 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1860
1905
  for (const el of document.querySelectorAll(LINK_SEL)) {
1861
1906
  if (out.length >= MAX_LINKS) break
1862
1907
  if (host && host.contains(el)) continue
1863
- const p = linkPath(el)
1908
+ const lk = linkTo(el)
1909
+ const p = lk ? lk.path : ''
1864
1910
  if (!p) continue
1865
1911
  const r = el.getBoundingClientRect()
1866
1912
  if (r.width < 2 || r.height < 2) continue
@@ -1871,12 +1917,12 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1871
1917
  // 被固定的底栏 / 顶栏盖住的按钮(滚到它下面了)看不见,画布上别从它出线
1872
1918
  const top = shown ? document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2) : null
1873
1919
  if (top && top !== el && !el.contains(top) && !(host && host.contains(top))) continue
1874
- const k = p + '|' + Math.round(r.left / 8) + '|' + Math.round(r.top / 8)
1920
+ const k = p + '?' + lk.state + '|' + Math.round(r.left / 8) + '|' + Math.round(r.top / 8)
1875
1921
  if (seen.has(k)) continue
1876
1922
  seen.add(k)
1877
1923
  const text = clip(String(el.innerText || el.getAttribute('aria-label') || el.getAttribute('title') || '').replace(/\s+/g, ' ').trim(), 24)
1878
1924
  const barDy = bars && bars.size ? barDyOf(el, bars) : undefined
1879
- out.push({ path: p, x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.width), h: Math.round(r.height), text, ...(barDy === undefined ? null : { barDy }) })
1925
+ out.push({ path: p, x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.width), h: Math.round(r.height), text, ...(barDy === undefined ? null : { barDy }), ...(lk.state ? { state: lk.state } : null) })
1880
1926
  }
1881
1927
  return out
1882
1928
  }
@@ -1933,21 +1979,80 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1933
1979
  // 演示:点了跳页的地方,不在 iframe 里直接跳,告诉右侧栏换一屏(带过场动画)
1934
1980
  // 远程看也是:沙盒里的页面跳不过去(地址指着电脑本机),由右侧栏打包那一页换上来
1935
1981
  let demo = false
1982
+ // 单看时点了「同一页换个状态」的链接(#30):不在 iframe 里自己跳,告诉右侧栏换状态(屏名旁的「状态 ▾」跟着变)。
1983
+ // 右侧栏说了认这个(init 里 stateNav 是它让这一帧显示的那一页的路径)才拦:别的看法(对比、多尺寸)照常让页面自己跳;
1984
+ // 在这一帧里点链接去了别的页(单看时可以):那页不归顶栏的状态菜单管,也让页面自己跳。
1985
+ // 没写 dsh-states、或者写的状态里没有这个的(老页面自己拿 ?state= 当筛选参数):照常跳,不拦
1986
+ let stateNav = ''
1987
+ // 页面自己的点击处理先跑完(「没勾同意不让付款」会拦默认行为):排到 window 上最后一个再看,拦了就随页面
1988
+ let stateWant = null
1989
+ /** 这个链接是不是本页换状态、交给右侧栏换:{ to, def, hash };不是给 null。
1990
+ * 只认真的 <a href>(onclick / data-href 里的地址由页面自己的脚本决定跳不跳,猜不准就随页面),
1991
+ * 除了 state 还带别的参数的(?state=paid&page=2)也随页面——右侧栏换状态只认状态,别的参数会丢 */
1992
+ const stateLink = (el) => {
1993
+ // 开新窗口的(target="_blank")随页面:不是在这一帧里换
1994
+ const l = el && el.isConnected && el.matches('a[href]') && !(el.target && el.target !== '_self') ? linkTo(el) : null
1995
+ let me = hereUrl().pathname
1996
+ try { me = decodeURIComponent(me) } catch { /* 原样 */ }
1997
+ if (!l || l.back || l.more || l.path !== me || me !== stateNav) return null
1998
+ // 换到写了的某个状态;在别的状态里点指着本页、什么都不带的链接 = 回默认状态(顶栏的状态标签也跟着回去)
1999
+ const d = declaredStates()
2000
+ const to = l.state || (offDefault() ? d[0] : '')
2001
+ if (!to || !d.includes(to)) return null
2002
+ return { to, def: to === d[0], hash: /^#[^\s#]{1,200}$/.test(l.hash || '') ? l.hash : '' }
2003
+ }
2004
+ const stateLast = (e) => {
2005
+ removeEventListener('click', stateLast)
2006
+ const w = stateWant
2007
+ stateWant = null
2008
+ if (!w || w.e !== e || e.defaultPrevented) return
2009
+ // 页面的点击处理跑完再看一遍(「去结算」点的时候才改 href):按那时的地址
2010
+ const g = stateLink(w.el)
2011
+ if (!g) return
2012
+ e.preventDefault()
2013
+ // def:要的是默认状态(右侧栏没记默认那个的名字);hash:链接里的锚点(order.html?state=paid#receipt),换好状态滚过去
2014
+ post({ type: 'stateGo', state: g.to, def: g.def, ...(g.hash ? { hash: g.hash } : null) })
2015
+ }
2016
+ addEventListener('click', (e) => {
2017
+ stateWant = null
2018
+ if (!stateNav || demo || HERE || picking || textEdit || styleOn || !parentWin) return
2019
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return
2020
+ const el = e.target && e.target.closest ? e.target.closest('a[href]') : null
2021
+ if (!el || !stateLink(el)) return
2022
+ stateWant = { e, el }
2023
+ removeEventListener('click', stateLast)
2024
+ addEventListener('click', stateLast)
2025
+ }, true)
1936
2026
  addEventListener('click', (e) => {
1937
2027
  if ((!demo && !HERE) || picking) return
1938
- const el = e.target && e.target.closest ? e.target.closest(LINK_SEL) : null
2028
+ const el = e.target && e.target.closest ? e.target.closest(LINK_SEL + ', [data-back]') : null
1939
2029
  if (!el) return
1940
- const p = linkPath(el)
1941
- if (!p) {
2030
+ const l = linkTo(el)
2031
+ if (!l) {
1942
2032
  const raw = String(el.getAttribute('href') || '').trim()
1943
2033
  if (HERE && raw.startsWith('#')) { e.preventDefault(); jumpTo(raw) }
1944
2034
  return
1945
2035
  }
1946
2036
  e.preventDefault()
1947
2037
  e.stopPropagation()
1948
- post({ type: 'nav', path: p })
2038
+ post({ type: 'nav', path: l.path, ...(l.state ? { state: l.state } : null), ...(l.back ? { back: true } : null), ...(/^#[^\s#]{1,200}$/.test(l.hash || '') ? { hash: l.hash } : null) })
1949
2039
  }, true)
1950
2040
 
2041
+ // 手机扫码看、在浏览器里直接打开(没有右侧栏):返回(data-back)就是浏览器的后退——从哪来回哪去;
2042
+ // 没有上一页(扫码直接进的这一屏)才照 href 走。在别人的页面里嵌着时不动(别把人家的页面往回退)
2043
+ if (!parentWin && window.top === window) {
2044
+ addEventListener('click', (e) => {
2045
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return
2046
+ const el = e.target && e.target.closest ? e.target.closest('[data-back]') : null
2047
+ if (!el) return
2048
+ let prev = null
2049
+ try { prev = document.referrer ? new URL(document.referrer) : null } catch { prev = null }
2050
+ if (history.length < 2 || !prev || prev.origin !== location.origin) return
2051
+ e.preventDefault()
2052
+ history.back()
2053
+ })
2054
+ }
2055
+
1951
2056
  /** 页内锚点(远程看时 <base> 指着原地址,#xx 会被当成跳到别的页面) */
1952
2057
  function jumpTo(hash) {
1953
2058
  let id = String(hash || '').replace(/^#/, '')
@@ -1966,10 +2071,13 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1966
2071
  const me = hereUrl()
1967
2072
  if (u.origin !== me.origin) return // 外网地址:随它
1968
2073
  e.preventDefault()
1969
- if (u.pathname === me.pathname) { if (u.hash) jumpTo(u.hash); return }
2074
+ let state = stateOfUrl(u)
2075
+ // 同一页换个这页没写的状态(老页面自己拿 ?state= 当参数):和以前一样不动(不重新打包这一页)
2076
+ if (u.pathname === me.pathname && state && !declaredStates().includes(state)) state = ''
2077
+ if (u.pathname === me.pathname && (!state || state === curState())) { if (u.hash) jumpTo(u.hash); return }
1970
2078
  let p = u.pathname
1971
2079
  try { p = decodeURIComponent(p) } catch { /* 原样 */ }
1972
- post({ type: 'nav', path: p })
2080
+ post({ type: 'nav', path: p, ...(state ? { state } : null) })
1973
2081
  })
1974
2082
  }
1975
2083
 
@@ -4075,6 +4183,8 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
4075
4183
  if (prop === 'transform') return String(b).startsWith('~') ? sameMatrix(a, String(b).slice(1), true) : sameMatrix(a, b)
4076
4184
  // 引用外部文件的(fill: url("assets/paint.svg#g")、filter: url("assets/fx.svg#f")):外框库和设计目录端口不一样,地址按路径 + 片段比
4077
4185
  if (/^(fill|stroke|filter|backdrop-filter|clip-path|marker-start|marker-mid|marker-end)$/.test(prop) && /url\(/.test(a + b)) return sameUrls(a, b)
4186
+ // 新版 Chrome 有时把 flex-end / flex-start 报成 flow-end / flow-start(同一个浏览器开两次都可能不一样):同一个意思
4187
+ if (/^(justify|align)-(content|items|self)$/.test(prop)) { const n = (v) => String(v).replace(/\bflow-(start|end)\b/g, 'flex-$1'); if (n(a) === n(b)) return true }
4078
4188
  if (/^(box-shadow|text-shadow|filter|backdrop-filter|clip-path|z-index|order|flex-grow|flex-shrink|scale|rotate)$/.test(prop)) return false // 阴影、滤镜里有颜色又有长度,照字比
4079
4189
  if (prop === 'fill' || prop === 'stroke') { if (/none|url\(/.test(a + b)) return false } else if (!/color$/.test(prop)) return samePx(a, b, prop)
4080
4190
  const tmp = document.createElement('dsh-design-norm')
@@ -5628,7 +5738,7 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
5628
5738
  if (!d || d.dshDesign !== 1) return
5629
5739
  if (d.type === 'pick') start(d.hint !== false)
5630
5740
  else if (d.type === 'cancel') { if (!styleOn) stop(true) }
5631
- else if (d.type === 'init') { if (d.relay) relay(); boot(d.seed || null) }
5741
+ else if (d.type === 'init') { if (d.relay) relay(); stateNav = typeof d.stateNav === 'string' ? d.stateNav : ''; boot(d.seed || null) }
5632
5742
  else if (d.type === 'files') { relay(); onFiles(String(d.file || ''), Array.isArray(d.files) ? d.files : null) }
5633
5743
  else if (d.type === 'reveal') reveal(d)
5634
5744
  else if (d.type === 'zoom') setK(1 / (Number(d.z) || 1))