dsh-design-studio 0.28.0 → 1.0.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/core.js CHANGED
@@ -6,6 +6,7 @@
6
6
  * createTracker 每个会话的预览状态,以及从会话事件里自动发现「该预览什么」
7
7
  */
8
8
 
9
+ import crypto from 'node:crypto'
9
10
  import fs from 'node:fs'
10
11
  import os from 'node:os'
11
12
  import path from 'node:path'
@@ -81,6 +82,26 @@ export function listScreens(root, keep = '') {
81
82
  return inManifestOrder(root, kept)
82
83
  }
83
84
 
85
+ /**
86
+ * 导出用的全部屏(#29):右侧栏显示的(拖过顺序的照拖过的)+ 收起来的,照全部屏的顺序(order:设计清单 / 生成先后)把收起来的插回原位,
87
+ * 打开的是最早那屏(index)时它还排第一。不在 order 里的收起来的接在最后;同一屏只出一次
88
+ */
89
+ export function exportOrder(shown, hidden, order) {
90
+ const rank = new Map((order || []).map((k, i) => [k, i]))
91
+ const hid = [...new Set(hidden || [])]
92
+ const out = []
93
+ const seen = new Set()
94
+ const put = (k) => { if (!seen.has(k)) { seen.add(k); out.push(k) } }
95
+ let j = 0
96
+ for (const k of shown || []) {
97
+ const r = rank.get(k)
98
+ if (r !== undefined) while (j < hid.length && (rank.has(hid[j]) ? rank.get(hid[j]) : Infinity) < r) put(hid[j++])
99
+ put(k)
100
+ }
101
+ while (j < hid.length) put(hid[j++])
102
+ return out
103
+ }
104
+
84
105
  /** 目录里所有的屏。按文件名找、改全套的时候用这个,别漏掉收起来的 */
85
106
  export function allScreens(root) {
86
107
  return inManifestOrder(root, screensByBirth(root))
@@ -280,14 +301,18 @@ export function devServerIn(command, text, skipPorts = new Set()) {
280
301
  /** 命令输出里最后一个本机地址(开发服务器常常先打 Local: 再打 Network:,取 localhost 那个) */
281
302
  // ── 预览里直接改字:在 HTML 源码的文字部分里找到那一处换掉 ──────────────────────
282
303
 
304
+ /** 一份文件内容的指纹(撤销改字时核对文件后来没被别处改过) */
305
+ const sigOf = (text) => crypto.createHash('sha1').update(String(text)).digest('hex').slice(0, 16)
306
+
283
307
  /** 标签、注释、脚本 / 样式这类不算文字的块;剩下的就是页面上看得到的字 */
284
308
  const NOT_TEXT = /<!--[\s\S]*?-->|<(script|style|textarea|noscript|template|title)\b[^>]*>[\s\S]*?<\/\1\s*>|<[^>]*>/gi
309
+ // 转义写法放前面:「Research &」在源码里是「Research &amp;」,先试 & 会只吃掉一个 &、把 amp; 留在原地(撤销改字时写坏)
285
310
  const ENT = {
286
- '&': '(?:&|&amp;|&#0*38;|&#x0*26;)',
287
- '<': '(?:<|&lt;|&#0*60;|&#x0*3c;)',
288
- '>': '(?:>|&gt;|&#0*62;|&#x0*3e;)',
289
- '"': '(?:"|&quot;|&#0*34;|&#x0*22;)',
290
- "'": "(?:'|&apos;|&#0*39;|&#x0*27;)",
311
+ '&': '(?:&amp;|&#0*38;|&#x0*26;|&)',
312
+ '<': '(?:&lt;|&#0*60;|&#x0*3c;|<)',
313
+ '>': '(?:&gt;|&#0*62;|&#x0*3e;|>)',
314
+ '"': '(?:&quot;|&#0*34;|&#x0*22;|")',
315
+ "'": "(?:&apos;|&#0*39;|&#x0*27;|')",
291
316
  }
292
317
  const WS_SRC = '(?:\\s|&nbsp;|&#0*160;|&#x0*a0;)+'
293
318
  const escHtml = (x) => x.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
@@ -307,7 +332,24 @@ function textPattern(text) {
307
332
  * before / after 是页面上看到的样子(空白合并过);after 会转义成 HTML。
308
333
  * @returns {{ ok: true, html } | { ok: false, reason: 'empty' | 'not-found' }}
309
334
  */
310
- export function replaceText(html, before, after, nth = 0) {
335
+ /** 源码文字部分里,pos 之前一共有几处 text(和 replaceText 一样数法:样式、脚本、注释、属性里的不算) */
336
+ function textCountBefore(html, text, pos) {
337
+ const re = textPattern(text)
338
+ let n = 0
339
+ let last = 0
340
+ NOT_TEXT.lastIndex = 0
341
+ for (let m = NOT_TEXT.exec(html); ; m = NOT_TEXT.exec(html)) {
342
+ const end = m ? m.index : html.length
343
+ const seg = html.slice(last, end)
344
+ re.lastIndex = 0
345
+ for (let t = re.exec(seg); t && last + t.index < pos; t = re.exec(seg)) n++
346
+ if (!m || end >= pos) break
347
+ last = m.index + m[0].length
348
+ }
349
+ return n
350
+ }
351
+
352
+ export function replaceText(html, before, after, nth = 0, raw = '') {
311
353
  const norm = (x) => String(x || '').replace(/[\s\u00a0]+/g, ' ').trim()
312
354
  const from = norm(before)
313
355
  const to = norm(after)
@@ -323,7 +365,13 @@ export function replaceText(html, before, after, nth = 0) {
323
365
  for (let t = re.exec(seg); t; t = re.exec(seg)) {
324
366
  if (seen++ === nth) {
325
367
  const at = last + t.index
326
- return { ok: true, html: html.slice(0, at) + escHtml(to) + html.slice(at + t[0].length) }
368
+ // raw:撤销时照改之前源码里的原样写回(&nbsp;、实体、换行、缩进、字面的 > 都留着);只收不带 <、而且确实就是 after 这段字的写法。
369
+ // 给了 raw 却对不上就不写(照转义写回会丢 &nbsp; / <pre> 里的换行,却显示撤销成功),当成文件被改过
370
+ const rawOk = typeof raw === 'string' && raw && !raw.includes('<') && new RegExp(`^(?:${textPattern(to).source})$`, 'i').test(raw)
371
+ if (typeof raw === 'string' && raw && !rawOk) return { ok: false, reason: 'changed' }
372
+ const put = rawOk ? raw : escHtml(to)
373
+ const out = html.slice(0, at) + put + html.slice(at + t[0].length)
374
+ return { ok: true, html: out, nth: textCountBefore(out, to, at), orig: t[0] } // nth:新字在改完的源码里是第几处;orig:被换掉的那段原样(撤销时照它换回去)
327
375
  }
328
376
  }
329
377
  if (!m) break
@@ -400,12 +448,7 @@ function splitDecls(s) {
400
448
  * 写 background 时去掉 background-color / -image(不然前后打架)。自定义属性(--x)区分大小写,原样留着。
401
449
  */
402
450
  export function mergeStyle(style, css) {
403
- const decls = splitDecls(String(style || '')).map((d) => {
404
- const i = d.indexOf(':')
405
- if (i <= 0) return null
406
- const p = d.slice(0, i).trim()
407
- return [p.startsWith('--') ? p : p.toLowerCase(), d.slice(i + 1).trim()]
408
- }).filter(Boolean)
451
+ const decls = declsOf(style)
409
452
  for (const [k, v] of Object.entries(css || {})) {
410
453
  const prop = k.toLowerCase()
411
454
  if (prop === 'background') for (let i = decls.length - 1; i >= 0; i--) if (/^background-(color|image)$/.test(decls[i][0])) decls.splice(i, 1)
@@ -446,9 +489,18 @@ const normSel = (s) => String(s || '').replace(/["']/g, '').replace(/::/g, ':').
446
489
  * n:同样选择器的第几条(源码顺序,@media 里的也算)。找不到给 0
447
490
  */
448
491
  export function findRule(text, sel, n = 0) {
492
+ const r = ruleAt(text, sel, n)
493
+ return r ? r.src.slice(0, r.at).split('\n').length : 0
494
+ }
495
+
496
+ /** 注释换成空格(位置、行号不变),找规则、拆声明时用它,改的时候照位置改原文 */
497
+ const blankComments = (text) => String(text || '').replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '))
498
+
499
+ /** 第 n 条选择器是 sel 的规则:{ at: 选择器开头, brace: 「{」的位置, src: 去掉注释的全文 };找不到给 null */
500
+ function ruleAt(text, sel, n = 0) {
449
501
  const want = normSel(sel)
450
- if (!want || want.length > 400) return 0
451
- const src = String(text || '').replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')) // 注释换成空格(位置、行号不变)
502
+ if (!want || want.length > 400) return null
503
+ const src = blankComments(text)
452
504
  // HTML 只看 <style> 里面(脚本、正文里像 CSS 的字不算)
453
505
  const regions = []
454
506
  if (/<style\b/i.test(src)) {
@@ -464,6 +516,8 @@ export function findRule(text, sel, n = 0) {
464
516
  let k = 0
465
517
  for (const [from, to] of regions) {
466
518
  let start = from
519
+ // 外面套着的是 @规则(@media、@layer…,里面的照常数)还是样式规则(.dark { .btn {} } 这种嵌套的:右侧栏不数,这里也不数,不然第 n 条对不上、改错规则)
520
+ const stack = []
467
521
  for (let i = from; i < to; i++) {
468
522
  const ch = src[i]
469
523
  if (ch === '"' || ch === "'") { // 字符串里的 { } ; 不算
@@ -472,34 +526,241 @@ export function findRule(text, sel, n = 0) {
472
526
  i = j
473
527
  } else if (ch === '{') {
474
528
  const pre = src.slice(start, i)
475
- if (normSel(pre) === want && k++ === n) {
476
- const at = start + (pre.length - pre.trimStart().length)
477
- return src.slice(0, at).split('\n').length
478
- }
529
+ const at = pre.trimStart().startsWith('@')
530
+ if (!at && !stack.includes('s') && normSel(pre) === want && k++ === n) return { at: start + (pre.length - pre.trimStart().length), brace: i, src }
531
+ stack.push(at ? 'a' : 's')
479
532
  start = i + 1
480
- } else if (ch === '}' || ch === ';') start = i + 1
533
+ } else if (ch === '}') { stack.pop(); start = i + 1 } else if (ch === ';') start = i + 1
481
534
  }
482
535
  }
483
- return 0
536
+ return null
537
+ }
538
+
539
+ /** 从 i(引号)跳到字符串结尾 */
540
+ function skipString(src, i, to) {
541
+ const q = src[i]
542
+ let j = i + 1
543
+ while (j < to && src[j] !== q && src[j] !== '\n') j += src[j] === '\\' ? 2 : 1
544
+ return j
545
+ }
546
+
547
+ /** 从「{」跳到配对的「}」;没配上给 -1 */
548
+ function closeOf(src, brace) {
549
+ let depth = 0
550
+ for (let i = brace; i < src.length; i++) {
551
+ const ch = src[i]
552
+ if (ch === '"' || ch === "'") i = skipString(src, i, src.length)
553
+ else if (ch === '{') depth++
554
+ else if (ch === '}' && !--depth) return i
555
+ }
556
+ return -1
557
+ }
558
+
559
+ /** 写 background 时一起去掉的(和 mergeStyle 一样:不然前后打架) */
560
+ const killsOf = (props) => new Set(props.flatMap((p) => (p === 'background' ? ['background', 'background-color', 'background-image'] : [p])))
561
+
562
+ /** 行内 style 写了这些,就会盖过样式表里的 p(简写、分写都算) */
563
+ const CORNERS = ['border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius']
564
+ const OVERRIDERS = {
565
+ background: ['background', 'background-color', 'background-image'],
566
+ 'font-size': ['font-size', 'font'],
567
+ 'font-weight': ['font-weight', 'font'],
568
+ 'border-radius': ['border-radius', ...CORNERS],
569
+ gap: ['gap', 'grid-gap', 'row-gap', 'column-gap', 'grid-row-gap', 'grid-column-gap'],
570
+ 'padding-top': ['padding-top', 'padding', 'padding-block', 'padding-block-start'],
571
+ 'padding-right': ['padding-right', 'padding', 'padding-inline', 'padding-inline-end'],
572
+ 'padding-bottom': ['padding-bottom', 'padding', 'padding-block', 'padding-block-end'],
573
+ 'padding-left': ['padding-left', 'padding', 'padding-inline', 'padding-inline-start'],
574
+ }
575
+ /** 逻辑内边距(跟书写方向走):拆不准,行内写了就别改共用规则 */
576
+ const LOGICAL_PAD = /^padding-(block|inline)(-start|-end)?$/
577
+ const overridersOf = (props) => new Set(props.flatMap((p) => OVERRIDERS[p] || [p]))
578
+
579
+ /** padding 简写拆成上右下左四个值(括号里的空格不拆);用了 var()/env()、个数不对:null(拆不准) */
580
+ function expandBox(v) {
581
+ let s = String(v || '').trim()
582
+ const imp = /!\s*important\s*$/i.test(s)
583
+ if (imp) s = s.replace(/!\s*important\s*$/i, '').trim()
584
+ if (/\b(var|env|attr)\s*\(/i.test(s)) return null
585
+ const t = []
586
+ let depth = 0
587
+ let cur = ''
588
+ for (const ch of s) {
589
+ if (ch === '(') depth++
590
+ else if (ch === ')') depth = Math.max(0, depth - 1)
591
+ if (/\s/.test(ch) && !depth) { if (cur) t.push(cur); cur = '' } else cur += ch
592
+ }
593
+ if (cur) t.push(cur)
594
+ if (t.length < 1 || t.length > 4) return null
595
+ const [a, b = a, c = a, d = b] = t
596
+ return [a, b, c, d].map((x) => (imp ? `${x} !important` : x))
597
+ }
598
+
599
+ /** 拆好的行内 style:[[属性, 值], …](属性小写,--x 原样) */
600
+ const declsOf = (style) => splitDecls(String(style || '')).map((d) => {
601
+ const i = d.indexOf(':')
602
+ if (i <= 0) return null
603
+ const p = d.slice(0, i).trim()
604
+ return [p.startsWith('--') ? p : p.toLowerCase(), d.slice(i + 1).trim()]
605
+ }).filter(Boolean)
606
+
607
+ /** 把新的 style 文字(已解开实体)写回 x 这个开头标签;空的就去掉 style 属性 */
608
+ function putStyle(html, x, a, style) {
609
+ const next = String(style || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;')
610
+ let attrs
611
+ if (a) attrs = (next ? x.attrs.slice(0, a.at) + `style="${next}"` : x.attrs.slice(0, a.at).replace(/\s+$/, '')) + x.attrs.slice(a.at + a.len)
612
+ // 自闭合的 / 前面得是空白或引号(src=a.png/ 里的 / 是属性值的一部分)
613
+ else if (next) attrs = /(^|["'\s])\/\s*$/.test(x.attrs) ? x.attrs.replace(/\s*\/\s*$/, ` style="${next}" /`) : x.attrs + ` style="${next}"`
614
+ else attrs = x.attrs
615
+ return html.slice(0, x.start) + `<${x.name}${attrs}>` + html.slice(x.end)
616
+ }
617
+
618
+ /**
619
+ * 共用规则改了 props 以后,页面上那个元素(loc,见 findTag)行内 style 里会盖过它的都去掉(见 OVERRIDERS),不然改了规则这里看着没变。
620
+ * 行内 padding 简写只改了其中几边:拆成四边,只去掉改了的那几边,别的边照旧。
621
+ * 拆不了(简写里用了 var()、个数不对),或行内写了 font 简写又改了字号 / 粗细:{ ok: false, reason: 'inline' },调用方别改共用规则(改了这里也看不出变化)。
622
+ * 找不到元素、行内没写:原样给回。
623
+ * @returns {{ ok: true, html } | { ok: false, reason: 'inline' }}
624
+ */
625
+ export function clearInline(html, loc, props) {
626
+ const x = findTag(html, loc || {})
627
+ const a = x && attrsOf(x.attrs).style
628
+ if (!a) return { ok: true, html }
629
+ const style = unAttr(a.v)
630
+ const decls = declsOf(style)
631
+ const has = (p) => decls.some(([q]) => q === p)
632
+ const list = (Array.isArray(props) ? props : []).map((p) => String(p).toLowerCase())
633
+ if (list.some((p) => p === 'font-size' || p === 'font-weight') && has('font')) return { ok: false, reason: 'inline' }
634
+ if (list.some((p) => p.startsWith('padding-')) && decls.some(([q]) => LOGICAL_PAD.test(q))) return { ok: false, reason: 'inline' }
635
+ const css = {}
636
+ const sides = ['top', 'right', 'bottom', 'left']
637
+ const changed = sides.filter((s) => list.includes(`padding-${s}`))
638
+ if (changed.length && has('padding')) {
639
+ // 照先后算出每一边实际的值(后写的赢),简写拆掉、没改的那几边写成分写
640
+ // 带 !important 的不让后面不带的盖掉(padding: 8px !important; padding-top: 2px → 上边还是 8px)
641
+ const eff = {}
642
+ const imp = (v) => /!\s*important\s*$/i.test(v)
643
+ const take = (side, v) => { if (eff[side] && imp(eff[side]) && !imp(v)) return; eff[side] = v }
644
+ for (const [p, v] of decls) {
645
+ if (p === 'padding') { const four = expandBox(v); if (!four) return { ok: false, reason: 'inline' }; sides.forEach((s, i) => take(s, four[i])) }
646
+ else if (/^padding-(top|right|bottom|left)$/.test(p)) take(p.slice(8), v)
647
+ }
648
+ css.padding = ''
649
+ for (const s of sides) css[`padding-${s}`] = changed.includes(s) ? '' : eff[s] || ''
650
+ }
651
+ for (const q of overridersOf(list)) if (q !== 'padding' && q !== 'font' && !(q in css)) css[q] = ''
652
+ const next = mergeStyle(style, css)
653
+ if (next === mergeStyle(style, {})) return { ok: true, html }
654
+ return { ok: true, html: putStyle(html, x, a, next) }
655
+ }
656
+
657
+ /**
658
+ * 把 css(调样式面板那几项)写进样式表里第 n 条选择器是 sel 的规则:这条规则里同名的先删掉(写 background 时连 background-color / -image),
659
+ * 新的放在规则最后(同一条规则里后写的赢)。原来那条带 !important 的,新的也带上。嵌套的子规则(&:hover {…})、注释、字符串里的 ; { } 都不动;
660
+ * 缩进、换行(CRLF)照这条规则原来的样子。
661
+ * @returns {{ ok: true, text } | { ok: false, reason: 'empty' | 'not-found' }}
662
+ */
663
+ export function setRuleProps(text, sel, n, css) {
664
+ const clean = cleanCss(css)
665
+ if (!clean) return { ok: false, reason: 'empty' }
666
+ const orig = String(text || '')
667
+ const r = ruleAt(orig, sel, Math.max(0, Math.floor(Number(n) || 0)))
668
+ if (!r) return { ok: false, reason: 'not-found' }
669
+ const { src, brace } = r
670
+ const close = closeOf(src, brace)
671
+ if (close < 0) return { ok: false, reason: 'not-found' }
672
+ const kills = killsOf(Object.keys(clean))
673
+ // 这条规则里顶层的一段段:声明(含结尾的 ;,和它前面的空白)/ 嵌套的子规则
674
+ const segs = []
675
+ let start = brace + 1
676
+ let depth = 0
677
+ for (let i = brace + 1; i < close; i++) {
678
+ const ch = src[i]
679
+ if (ch === '"' || ch === "'") { i = skipString(src, i, close); continue }
680
+ if (ch === '(') depth++
681
+ else if (ch === ')') depth = Math.max(0, depth - 1)
682
+ else if (ch === ';' && !depth) { segs.push({ s: start, e: i + 1, semi: true }); start = i + 1 }
683
+ else if (ch === '{' && !depth) { const c = closeOf(src, i); if (c < 0 || c > close) return { ok: false, reason: 'not-found' }; segs.push({ s: start, e: c + 1, nested: true }); i = c; start = c + 1 }
684
+ }
685
+ // 最后一条没写分号:它后面的空白(「}」前的换行)留给 tail
686
+ let tail = start
687
+ if (src.slice(start, close).trim()) { tail = start + src.slice(start, close).trimEnd().length; segs.push({ s: start, e: tail, semi: false }) }
688
+ // 这条规则里会盖过新写的那项的(同名的、简写:padding 盖 padding-left、font 盖 font-size……)带 !important:新的那项也带上,不然白写
689
+ const important = new Set()
690
+ let indent = ''
691
+ let multi = false
692
+ const kept = []
693
+ for (const g of segs) {
694
+ if (g.nested) { kept.push(g); continue }
695
+ const body = src.slice(g.s, g.e)
696
+ if (!indent) { const m = /\n([ \t]*)\S/.exec(body); if (m) { indent = m[1]; multi = true } }
697
+ const i = body.indexOf(':')
698
+ const prop = i > 0 ? body.slice(0, i).trim().toLowerCase() : ''
699
+ if (prop && /!\s*important/i.test(body)) for (const p of Object.keys(clean)) if (overridersOf([p]).has(prop) || killsOf([p]).has(prop)) important.add(p)
700
+ if (prop && kills.has(prop)) continue
701
+ kept.push(g)
702
+ }
703
+ const eol = orig.includes('\r\n') ? '\r\n' : '\n'
704
+ if (!multi && /\n/.test(src.slice(brace + 1, close))) { multi = true; indent = ' ' }
705
+ let out = orig.slice(0, brace + 1)
706
+ let last = null
707
+ for (const g of kept) { out += orig.slice(g.s, g.e); last = g }
708
+ if (last && !last.nested && !last.semi) out += ';'
709
+ const decls = Object.entries(clean).filter(([, v]) => v).map(([p, v]) => `${p}: ${v}${important.has(p) ? ' !important' : ''};`)
710
+ // 最后一段和「}」之间:注释照原样留着,新的写在注释后面、「}」前的空白前面
711
+ const mid = orig.slice(tail, close)
712
+ const ws = mid.slice(mid.trimEnd().length)
713
+ out += mid.slice(0, mid.length - ws.length)
714
+ out += multi ? decls.map((d) => `${eol}${indent}${d}`).join('') : ' ' + decls.join(' ')
715
+ out += multi ? (/\n/.test(ws) ? ws : eol) : (ws || ' ')
716
+ out += orig.slice(close)
717
+ return { ok: true, text: out, imp: [...important] }
718
+ }
719
+
720
+ /** 像状态的 class(is-active、on、selected……):比「是不是同一种元素」时不算(和 picker 的 STATE_CLS 一字不差) */
721
+ const STATE_CLS = /^(is-|has-)|^(active|on|sel|selected|current|hidden|show|open|disabled|checked|focus|hover)$/
722
+
723
+ /** 这份 HTML 里带 class cls 的元素各是哪种:「标签大写|去掉状态 class 后排好的 class」,和 picker 的 sharedOf 一样算 */
724
+ export function classSigs(html, cls) {
725
+ const out = new Set()
726
+ if (!cls) return out
727
+ for (const m of String(html || '').matchAll(/<([a-z][a-z0-9-]*)\b([^>]*)>/gi)) {
728
+ const a = attrsOf(m[2])
729
+ if (!a.class) continue
730
+ const list = [...new Set(unAttr(a.class.v).split(/\s+/).filter(Boolean))]
731
+ if (!list.includes(cls)) continue
732
+ out.add(m[1].toUpperCase() + '|' + list.filter((c) => !STATE_CLS.test(c)).sort().join(' '))
733
+ }
734
+ return out
735
+ }
736
+
737
+ /** 这份 HTML 里有几个元素带着 class cls、行内 style 又写了 props 里的哪一项(之前「直接保存」写的,盖过样式表) */
738
+ export function inlineOverrides(html, cls, props) {
739
+ if (!cls) return 0
740
+ const kills = overridersOf(props)
741
+ let n = 0
742
+ for (const m of String(html || '').matchAll(/<[a-z][a-z0-9-]*\b([^>]*)>/gi)) {
743
+ const a = attrsOf(m[1])
744
+ if (!a.class || !a.style || !unAttr(a.class.v).split(/\s+/).includes(cls)) continue
745
+ if (splitDecls(unAttr(a.style.v)).some((d) => kills.has(d.slice(0, d.indexOf(':')).trim().toLowerCase()))) n++
746
+ }
747
+ return n
484
748
  }
485
749
 
486
750
  /**
487
751
  * 把 css 写进页面上那个元素(loc,见 findTag)在源码里的 style 属性。
488
752
  * @returns {{ ok: true, html } | { ok: false, reason: 'empty' | 'not-found' }}
489
753
  */
490
- export function setStyle(html, loc, css) {
754
+ export function setStyle(html, loc, css, imp = []) {
491
755
  const clean = cleanCss(css)
492
756
  if (!clean) return { ok: false, reason: 'empty' }
493
757
  const x = findTag(html, loc)
494
758
  if (!x) return { ok: false, reason: 'not-found' }
495
759
  const a = attrsOf(x.attrs).style
496
- const next = mergeStyle(a ? unAttr(a.v) : '', clean).replace(/&/g, '&amp;').replace(/"/g, '&quot;')
497
- let attrs
498
- if (a) attrs = x.attrs.slice(0, a.at) + (next ? `style="${next}"` : '') + x.attrs.slice(a.at + a.len)
499
- // 自闭合的 / 前面得是空白或引号(src=a.png/ 里的 / 是属性值的一部分)
500
- else if (next) attrs = /(^|["'\s])\/\s*$/.test(x.attrs) ? x.attrs.replace(/\s*\/\s*$/, ` style="${next}" /`) : x.attrs + ` style="${next}"`
501
- else attrs = x.attrs
502
- return { ok: true, html: html.slice(0, x.start) + `<${x.name}${attrs}>` + html.slice(x.end) }
760
+ // imp:盖着它的规则带 !important 的那几项,行内也带上(不然白写)
761
+ const hi = new Set(Array.isArray(imp) ? imp.map((p) => String(p).toLowerCase()) : [])
762
+ const vals = Object.fromEntries(Object.entries(clean).map(([k, v]) => [k, v && hi.has(k) ? `${v} !important` : v]))
763
+ return { ok: true, html: putStyle(html, x, a, mergeStyle(a ? unAttr(a.v) : '', vals)) }
503
764
  }
504
765
 
505
766
  export function serverUrlIn(text, skipPorts = new Set()) {
@@ -768,9 +1029,32 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
768
1029
  // 最近几批改动(递增序号):远程看的右侧栏两次轮询之间可能来了好几批,按序号取并集,别只看最后一批
769
1030
  st.changeN = (st.changeN || 0) + 1
770
1031
  st.changes = [...(st.changes || []), { n: st.changeN, files: st.changedFiles }].slice(-CHANGE_LOG)
1032
+ const had = new Set(st.screens) // 这一批之前画布上有哪几屏(下面认「原版是不是这一批刚改名出来的」)
771
1033
  const before = st.screens.join('\n')
772
1034
  refreshScreens(st)
773
1035
  if (st.screens.join('\n') !== before) persist(id, st)
1036
+ // 正开着的那个方向被挪走了(「用这版」:home-a 挪进 drafts、选中的改名成 home):同名的原版已经在了就换过去,
1037
+ // 别在画布上留一格「这一屏打不开」等模型下回预览
1038
+ // 只认「用这版」的挪法:开着的那个这一批挪进了 drafts/(原版已经在,或这一批之前就不在画布上),
1039
+ // 或者原版是这一批刚出现的(选中的就是开着的这个、直接改名成原版)。
1040
+ // 用户自己把 guide-a 改成别的名字、顺手改了早就在的 guide.html,或者 drafts/ 里有上一回的同名旧稿时,都别跳。
1041
+ // 这一批改了哪些不知道(太多、列表空的)就不换:留着出错卡,用户点一下重试 / 让模型改
1042
+ const v = list.length && !fs.existsSync(st.target.file) && /^(.+)-[a-z](\.html?)$/i.exec(path.basename(st.target.file))
1043
+ const dir = v ? path.dirname(st.target.file) : ''
1044
+ const base = v && path.join(dir, v[1] + v[2])
1045
+ if (base && fs.existsSync(base)) {
1046
+ const rel = (f) => path.relative(root, f).split(path.sep).join('/')
1047
+ const drafted = path.join(dir, 'drafts', path.basename(st.target.file))
1048
+ const moved = list.includes(rel(drafted)) && fs.existsSync(drafted)
1049
+ // 原版这一批刚出现;或者老的原版这一批挪进了 drafts/、选中的这个改名顶上(单看着 login-b 时「用这版」;
1050
+ // drafts 里已有同名旧稿时模型可能另起名字,比如 drafts/login-previous.html,所以只看这一批有没有东西进了 drafts/)
1051
+ const draftsRel = rel(path.join(dir, 'drafts')) + '/'
1052
+ // 这一批画布上多出了别的屏(开着的这个被改名成别的名字了)就不是「用这版」:别跳到原版。
1053
+ // 只算画布认的屏(和 allScreens 同一套筛法):模型顺手写的 _probe.html、隐藏文件不算
1054
+ const renamed = allScreens(dir).some((n) => n !== path.basename(base) && !had.has(rel(path.join(dir, n))) && list.includes(rel(path.join(dir, n))))
1055
+ const fresh = list.includes(rel(base)) && (!had.has(rel(base)) || list.some((f) => f.startsWith(draftsRel) && fs.existsSync(path.join(root, f))))
1056
+ if (!renamed && (moved || fresh)) setTarget(id, { kind: 'file', file: base, root }, { source: st.source, popup: false }).catch((e) => log(e))
1057
+ }
774
1058
  }
775
1059
  }
776
1060
  }
@@ -956,6 +1240,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
956
1240
  case 'turn/start':
957
1241
  if (live) {
958
1242
  st.turn = true
1243
+ st.end = ''
959
1244
  st.turnAt = now() // 右侧栏的状态条从这里开始计时
960
1245
  st.tool = ''
961
1246
  keepVersion(st, '')
@@ -963,6 +1248,8 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
963
1248
  break
964
1249
  case 'turn/end':
965
1250
  st.turn = false
1251
+ // 这一轮怎么结束的(completed / aborted / error / max-tokens…):状态胶囊别把出错、被停当成「做好了」
1252
+ if (live) st.end = String((d && d.reason && d.reason.kind) || '') // 没带原因(老版 DSH)就空着:右侧栏照用户点没点停下说
966
1253
  st.turnAt = 0
967
1254
  st.tool = ''
968
1255
  st.writing = ''
@@ -973,7 +1260,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
973
1260
  if (!(st.draft && st.draft.file && fs.existsSync(st.draft.file))) st.draft = null
974
1261
  st.asking = false
975
1262
  if (live) {
976
- keepVersion(st, st.ask)
1263
+ keepVersion(st, st.ask, 'ai')
977
1264
  st.turns = (st.turns || 0) + 1 // 右侧栏靠它知道「又干完一轮」(很快的一轮轮询看不到 turn 变 true)
978
1265
  }
979
1266
  st.ask = '' // 用过就清:下一轮不是用户发起的(没有新的一句话)就不借这一句当名字
@@ -1057,24 +1344,92 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
1057
1344
  }
1058
1345
 
1059
1346
  /** 本地文件预览:存一版(和上一版一样就不存);存了就让右侧栏刷新版本列表 */
1060
- function keepVersion(st, label) {
1347
+ function keepVersion(st, label, by = '') {
1061
1348
  if (!history || !st.target || st.target.kind !== 'file') return null
1062
- const v = history.snapshot(st.target.root, label)
1349
+ const v = history.snapshot(st.target.root, label, by)
1063
1350
  if (v) st.vrev++
1064
1351
  return v
1065
1352
  }
1066
1353
 
1067
1354
  /** 预览里直接改字:在这一屏(key = 文件名)的 HTML 里把第 nth 处 before 换成 after,改前改后各存一版 */
1068
- function editText(id, { key, before, after, nth = 0 } = {}) {
1355
+ function editText(id, { key, before, after, nth = 0, sig = '', raw = '' } = {}) {
1069
1356
  const short = String(after).replace(/\s+/g, ' ').trim()
1070
- return rewrite(id, key, (html) => replaceText(html, before, after, Math.max(0, Math.floor(Number(nth) || 0))),
1071
- `改字「${short.length > 16 ? short.slice(0, 16) + '…' : short}」`)
1357
+ // sig:撤销时带上改完那一刻文件的样子;之后文件又被别处改过(编辑器、模型)就不撤,免得按旧的「第几处」换错地方
1358
+ return rewrite(id, key, (html) => (sig && sigOf(html) !== String(sig) ? { ok: false, reason: 'changed' } : replaceText(html, before, after, Math.max(0, Math.floor(Number(nth) || 0)), typeof raw === 'string' ? raw : '')),
1359
+ `改字「${short.length > 16 ? short.slice(0, 16) + '…' : short}」`,
1360
+ { kind: 'text', before: String(before).replace(/\s+/g, ' ').trim().slice(0, 60), after: short.slice(0, 60) })
1072
1361
  }
1073
1362
 
1074
1363
  /** 预览里调样式:把 css 写进这一屏(key)里那个元素(loc,见 findTag)的 style 属性,改前改后各存一版 */
1075
- function editStyle(id, { key, loc, css, name } = {}) {
1364
+ function editStyle(id, { key, loc, css, name, imp } = {}) {
1076
1365
  const short = String(name || (loc && loc.tag) || '').trim()
1077
- return rewrite(id, key, (html) => setStyle(html, loc || {}, css), `调样式「${short.length > 24 ? short.slice(0, 24) + '…' : short}」`)
1366
+ const clean = cleanCss(css)
1367
+ return rewrite(id, key, (html) => setStyle(html, loc || {}, css, imp), `调样式「${short.length > 24 ? short.slice(0, 24) + '…' : short}」`,
1368
+ { kind: 'style', name: short, css: clean || {}, inline: true })
1369
+ }
1370
+
1371
+ /**
1372
+ * 调样式写进共用的样式表(各屏一起变):file 是设计目录里的 .css(调用方已核对过在目录里),把 css 写进第 n 条 sel 规则;
1373
+ * 这一屏(key)那个元素(loc)行内 style 里同名的几项去掉(不然盖过样式表,看着没变)。改前改后各存一版。
1374
+ * cls:选择器里元素带的那个 class,数一数别的屏还有几处行内写着自己的值(之前直接保存的),告诉用户没跟着变。
1375
+ */
1376
+ function editRule(id, { key, loc, file, sel, n = 0, css, name, cls = '' } = {}) {
1377
+ const st = states.get(id)
1378
+ const t = st && st.target
1379
+ if (!t || t.kind !== 'file') return { ok: false, reason: 'not-file' }
1380
+ if (busyRoot(t.root)) return { ok: false, reason: 'busy' }
1381
+ const rootReal = fs.realpathSync(t.root)
1382
+ let real = ''
1383
+ try { real = fs.realpathSync(String(file || '')) } catch { real = '' }
1384
+ if (!real || !real.startsWith(rootReal + path.sep) || !/\.css$/i.test(real)) return { ok: false, reason: 'no-rule' }
1385
+ const stat = fs.statSync(real)
1386
+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024) return { ok: false, reason: 'no-rule' }
1387
+ const r = setRuleProps(fs.readFileSync(real, 'utf8'), sel, n, css)
1388
+ if (!r.ok) return r
1389
+ const props = Object.keys(cleanCss(css) || {})
1390
+ // 这一屏那个元素行内同名的去掉(找不到元素、没写过行内就不动)
1391
+ const screen = String(key || path.basename(t.file))
1392
+ const sfile = path.join(t.root, screen)
1393
+ let html = null
1394
+ try {
1395
+ const sreal = fs.realpathSync(sfile)
1396
+ if (path.dirname(sfile) === t.root && HTML_EXT.test(screen) && sreal.startsWith(rootReal + path.sep)) {
1397
+ const cur = fs.readFileSync(sfile, 'utf8')
1398
+ const x = clearInline(cur, loc || {}, props)
1399
+ if (!x.ok) return x // 行内写法拆不开:共用规则不改,调用方退回只改这一处
1400
+ if (x.html !== cur) html = x.html
1401
+ }
1402
+ } catch { html = null }
1403
+ keepVersion(st, '', 'pre')
1404
+ fs.writeFileSync(real, r.text)
1405
+ if (html != null) fs.writeFileSync(sfile, html)
1406
+ const rel = path.relative(rootReal, real).split(path.sep).join('/')
1407
+ const short = String(name || (loc && loc.tag) || '').trim()
1408
+ keepVersion(st, `调样式「${short.length > 20 ? short.slice(0, 20) + '…' : short}」→ ${path.basename(rel)}`, 'me')
1409
+ let others = 0
1410
+ for (const k of allScreens(t.root)) {
1411
+ if (k === screen) continue
1412
+ try { if (inlineOverrides(fs.readFileSync(path.join(t.root, k), 'utf8'), cls, props)) others++ } catch { /* 读不了不算 */ }
1413
+ }
1414
+ noteEdit(st, { kind: 'rule', files: html != null ? [rel, screen] : [rel], name: short, css: cleanCss(css) || {}, sel: String(sel || '').slice(0, 120), file: rel })
1415
+ return { ok: true, file: rel, sel: String(sel || ''), others, imp: r.imp || [] }
1416
+ }
1417
+
1418
+ /**
1419
+ * 用户在右侧栏亲手改了设计文件(调样式、改字、调节滑块、回到某一版):记在会话上,模型下一步开始前由插件告诉它(见 index.js 的 agent/pre-step),
1420
+ * 免得它凭自己之前写的内容接着改、或做进项目时用旧样子。只留最近 20 条
1421
+ */
1422
+ function noteEdit(st, e) {
1423
+ st.edits = [...(st.edits || []), { at: now(), root: st.target && st.target.root, ...e }].slice(-20)
1424
+ }
1425
+
1426
+ /** 取走这个会话攒着的手改记录(取了就清) */
1427
+ function takeEdits(id) {
1428
+ const st = states.get(id)
1429
+ if (!st || !st.edits || !st.edits.length) return []
1430
+ const out = st.edits
1431
+ st.edits = []
1432
+ return out
1078
1433
  }
1079
1434
 
1080
1435
  /**
@@ -1082,7 +1437,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
1082
1437
  * 开发服务器的页面源码在项目里、不一定是这份 HTML,不在这里改(右侧栏改成让模型去改)。
1083
1438
  * 模型正在干活时不改:它可能正整份重写这个文件,改了也会被盖掉。
1084
1439
  */
1085
- function rewrite(id, key, fn, label) {
1440
+ function rewrite(id, key, fn, label, detail = null) {
1086
1441
  const st = states.get(id)
1087
1442
  const t = st && st.target
1088
1443
  if (!t || t.kind !== 'file') return { ok: false, reason: 'not-file' }
@@ -1094,12 +1449,14 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
1094
1449
  let real = ''
1095
1450
  try { real = fs.realpathSync(file) } catch { real = '' }
1096
1451
  if (!real.startsWith(fs.realpathSync(t.root) + path.sep)) return { ok: false, reason: 'no-screen' }
1097
- const r = fn(fs.readFileSync(file, 'utf8'))
1452
+ const was = fs.readFileSync(file, 'utf8')
1453
+ const r = fn(was)
1098
1454
  if (!r.ok) return r
1099
- keepVersion(st, '')
1455
+ keepVersion(st, '', 'pre')
1100
1456
  fs.writeFileSync(file, r.html)
1101
- keepVersion(st, label)
1102
- return { ok: true, file: name }
1457
+ keepVersion(st, label, 'me')
1458
+ if (detail) noteEdit(st, { ...detail, files: [name] })
1459
+ return { ok: true, file: name, prev: sigOf(was), sig: sigOf(r.html), ...(typeof r.nth === 'number' ? { nth: r.nth } : {}), ...(typeof r.orig === 'string' ? { orig: r.orig } : {}) } // prev / sig:改前 / 改后文件的指纹(撤销改字核对用)
1103
1460
  }
1104
1461
 
1105
1462
  /** 这个目录有没有会话的模型正在干活(它可能正整份重写文件,这时改了会被盖掉);经软链接打开的同一个目录也算 */
@@ -1121,9 +1478,13 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
1121
1478
  // 右侧栏发请求时看的是哪套设计:这期间换了设计就别写,免得写进另一套
1122
1479
  if (expectRoot !== undefined && t.root !== expectRoot) return { ok: false, reason: 'moved' }
1123
1480
  if (busyRoot(t.root)) return { ok: false, reason: 'busy' }
1124
- keepVersion(st, '')
1481
+ keepVersion(st, '', 'pre')
1125
1482
  const r = fn(t.root)
1126
- if (r && r.ok && r.files && r.files.length) keepVersion(st, typeof label === 'function' ? label(r) : label)
1483
+ if (r && r.ok && r.files && r.files.length) {
1484
+ const name = typeof label === 'function' ? label(r) : label
1485
+ keepVersion(st, name, 'me')
1486
+ noteEdit(st, { kind: 'dir', label: String(name || ''), files: r.files.map(String).slice(0, 8), more: Math.max(0, r.files.length - 8) })
1487
+ }
1127
1488
  return r
1128
1489
  }
1129
1490
 
@@ -1135,12 +1496,16 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
1135
1496
  }
1136
1497
 
1137
1498
  /** 回到某一版:现在的先存一版,再写回那一版的文件(目录监听会让预览自己刷新) */
1138
- function restoreVersion(id, n) {
1499
+ function restoreVersion(id, n, want = {}) {
1139
1500
  const st = states.get(id)
1140
1501
  if (!history || !st || !st.target || st.target.kind !== 'file') throw new Error('这个预览没有版本记录')
1141
1502
  const root = st.target.root
1503
+ // 右侧栏说的是哪个项目、哪一次存的版:换过项目以后再点旧消息上的「重试」,别把同号的版本写进现在这个项目
1504
+ if (want.root && want.root !== root) throw new Error('已经换了项目,这一版不在现在开着的项目里')
1505
+ if (want.at && !history.list(root).some((x) => x.n === Number(n) && Number(x.at) === Number(want.at))) throw new Error('这一版已经不在了')
1142
1506
  const r = history.restore(root, n, { before: (html) => beforeRestore(root, html) })
1143
1507
  st.vrev++
1508
+ if (r && r.restored) noteEdit(st, { kind: 'restore', n: Number(n), count: r.restored })
1144
1509
  return r
1145
1510
  }
1146
1511
 
@@ -1169,7 +1534,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
1169
1534
  if (!(st && st.target)) restore(id)
1170
1535
  else if (st.origin && !alive(st.origin)) revive(id, st)
1171
1536
  const turnFor = st && st.turn && st.turnAt ? Math.max(0, now() - st.turnAt) : 0
1172
- if (!st || !st.target) return { target: null, rev: st ? st.rev : 0, openRev: st ? st.openRev : 0, turn: st ? st.turn : false, turnFor, tool: (st && st.turn && st.tool) || '', turns: st ? st.turns || 0 : 0, asking: !!(st && st.asking), writing: (st && st.turn && st.writing) || '', lines: (st && st.turn && st.lines) || 0, draft: draftOf(st), hint: st && st.hint && fs.existsSync(st.hint) ? st.hint : '', loading: restoring.has(id) }
1537
+ if (!st || !st.target) return { target: null, rev: st ? st.rev : 0, openRev: st ? st.openRev : 0, turn: st ? st.turn : false, turnFor, tool: (st && st.turn && st.tool) || '', turns: st ? st.turns || 0 : 0, end: (st && st.end) || '', asking: !!(st && st.asking), writing: (st && st.turn && st.writing) || '', lines: (st && st.turn && st.lines) || 0, draft: draftOf(st), hint: st && st.hint && fs.existsSync(st.hint) ? st.hint : '', loading: restoring.has(id) }
1173
1538
  const { target, url, label, source, rev, openRev, turn, writing, changedAt, kind, size, view, origin } = st
1174
1539
  const file = target.kind === 'file'
1175
1540
  return {
@@ -1183,6 +1548,7 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
1183
1548
  turnFor,
1184
1549
  tool: (turn && st.tool) || '',
1185
1550
  turns: st.turns || 0,
1551
+ end: st.end || '',
1186
1552
  asking: !!st.asking,
1187
1553
  writing,
1188
1554
  lines: (turn && st.lines) || 0,
@@ -1208,5 +1574,17 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
1208
1574
  }
1209
1575
  }
1210
1576
 
1211
- return { observe, stream, setTarget, setView, clear, changed, snapshot, cwdOf, stateOf, versions, restoreVersion, editText, editStyle, editDir, keepVersion: (id, label) => keepVersion(stateOf(id), label) }
1577
+ /**
1578
+ * 右侧栏收起来没显示的那几屏(屏多过上限时最早的那些,#29):按设计清单 / 创建顺序,导出全部屏时接在显示的前面。
1579
+ * 不是本地文件的设计、没收起来的给 []
1580
+ */
1581
+ function hiddenScreens(id) {
1582
+ const st = states.get(id)
1583
+ const t = st && st.target
1584
+ if (!t || t.kind !== 'file') return [] // 不看 st.hidden:刚加的屏目录监听还没报上来时,现扫的才准
1585
+ const on = new Set(st.screens)
1586
+ return allScreens(t.root).filter((k) => !on.has(k))
1587
+ }
1588
+
1589
+ return { observe, stream, setTarget, setView, clear, changed, snapshot, cwdOf, stateOf, versions, restoreVersion, editText, editStyle, editRule, editDir, takeEdits, hiddenScreens, keepVersion: (id, label) => keepVersion(stateOf(id), label) }
1212
1590
  }