dsh-design-studio 0.9.0 → 0.10.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/picker.js CHANGED
@@ -58,6 +58,80 @@
58
58
  }
59
59
  }
60
60
 
61
+ // 拖着文件进了这一页(页面铺满右侧栏时,外面的右侧栏收不到拖动):告诉右侧栏亮出「松开打开 / 当参考图」的提示,
62
+ // 松手也在这里接住、把文件转给右侧栏。提示只是一层画、不挡事件:页面自己的上传区照样收得到后面的拖动
63
+ // 页面自己里面拖的(拖一下页面上的图、页面自己的拖放)不算:那不是要打开什么
64
+ // 用 drag 不用 dragstart:页面取消了 dragstart(轮播图常这么做)就不会有 drag,也就不会有 dragend 来清掉标记
65
+ let ownDrag = false
66
+ let dropOwn = false
67
+ addEventListener('drag', () => { ownDrag = true }, true)
68
+ addEventListener('dragend', () => { ownDrag = false }, true)
69
+ addEventListener('pointerup', () => { ownDrag = false }, true)
70
+ const hasFiles = (dt) => !!dt && [...(dt.types || [])].includes('Files')
71
+ // 页面自己接这次拖动:上传区在 dragover 上 preventDefault(或者拦住不让冒泡,见下面捕获阶段那个),或者落在 <input type=file> 上
72
+ const pageTakes = (e) => e.defaultPrevented || (typeof e.composedPath === 'function' ? e.composedPath() : [e.target]).some((n) => n && n.tagName === 'INPUT' && String(n.type).toLowerCase() === 'file')
73
+ let lastIn = 0
74
+ let took = false // 刚才那下是页面自己接的:收起提示,松手也归页面
75
+ const seen = new WeakSet() // 冒泡阶段见到过的 dragover(按事件记:页面忙时几个 dragover 会连着处理)
76
+ const pageTook = () => {
77
+ if (took) return
78
+ took = true
79
+ lastIn = 0
80
+ post({ type: 'dragOut' })
81
+ }
82
+ // 只看 dragover:同一个元素上拖第二次时浏览器不一定再给 dragenter;dragenter 时也还不知道页面接不接
83
+ // 挂在 window 冒泡阶段的最后,页面的处理先跑完;页面全局拦了 dragover 防误拖的就当页面接了(那种页面用「浏览…」或地址栏打开)
84
+ const onOver = (e) => {
85
+ seen.add(e)
86
+ const dt = e.dataTransfer
87
+ if (ownDrag || !hasFiles(dt)) return
88
+ if (pageTakes(e)) return pageTook()
89
+ took = false
90
+ e.preventDefault() // 这里能松手:不然浏览器把文件当网页打开(或者根本不给 drop)
91
+ dt.dropEffect = 'copy'
92
+ const now = Date.now()
93
+ if (now - lastIn < 200) return // 拖着时 dragover 一直来,隔一会儿报一次就够
94
+ lastIn = now
95
+ post({ type: 'dragIn', items: [...(dt.items || [])].slice(0, 20).map((x) => ({ kind: String(x.kind), type: String(x.type) })) })
96
+ }
97
+ const onDrop = (e) => {
98
+ const dt = e.dataTransfer
99
+ const own = dropOwn
100
+ dropOwn = false
101
+ if (own || !hasFiles(dt)) return
102
+ if (took || pageTakes(e)) { took = false; return }
103
+ e.preventDefault()
104
+ const files = []
105
+ for (const x of [...(dt.items || [])].slice(0, 20)) {
106
+ if (x.kind !== 'file') continue
107
+ // 文件夹只有 entry 分得出来,得在 drop 里同步取
108
+ let dir = false
109
+ try { const en = typeof x.webkitGetAsEntry === 'function' ? x.webkitGetAsEntry() : null; dir = !!(en && en.isDirectory) } catch { dir = false }
110
+ let f = null
111
+ try { f = x.getAsFile() } catch { f = null }
112
+ if (f) files.push({ f, dir })
113
+ }
114
+ // File 能直接跟着消息过去(桌面版照样拿得到它的真实路径)
115
+ post({ type: 'dropIn', files })
116
+ }
117
+ // 页面在 window 上挂的整页上传常常比这里晚注册(type=module 的脚本、框架挂载后):每次事件在捕获阶段把上面两个摘下来重挂,
118
+ // 排到 window 冒泡监听的最后,页面的处理(不管什么时候挂的)都先跑完,才看它接没接。
119
+ // 重挂放在 document 的捕获阶段:window 捕获阶段的监听(页面的也算)都跑过了才轮到它
120
+ const last = (type, fn) => { removeEventListener(type, fn); addEventListener(type, fn) }
121
+ last('dragover', onOver)
122
+ last('drop', onDrop)
123
+ document.addEventListener('dragover', () => last('dragover', onOver), true)
124
+ document.addEventListener('drop', () => last('drop', onDrop), true)
125
+ addEventListener('dragover', (e) => {
126
+ if (ownDrag || !hasFiles(e.dataTransfer)) return
127
+ // 上传区拦住 dragover 不让冒泡(stopPropagation)时上面那个收不到:这一轮事件发完还没见到它,就是页面接了
128
+ setTimeout(() => { if (!seen.has(e)) pageTook() }, 0)
129
+ }, true)
130
+ addEventListener('drop', () => {
131
+ dropOwn = ownDrag
132
+ ownDrag = false
133
+ }, true)
134
+
61
135
  // ── 描述一个元素 ──────────────────────────────────────────────────────────
62
136
 
63
137
  const esc = (s) => (window.CSS && CSS.escape ? CSS.escape(s) : String(s).replace(/[^\w-]/g, '\\$&'))
@@ -107,7 +181,7 @@
107
181
  }
108
182
  const full = el.outerHTML.replace(/\s+/g, ' ')
109
183
  if (full.length <= max) return full
110
- const open = shallow.outerHTML.replace(/<\/[^>]+>$/, '')
184
+ const open = shallow.outerHTML.replace(/<\/[^>]+>$/, '').replace(/\s+/g, ' ')
111
185
  const kids = el.children.length
112
186
  const txt = textOf(el)
113
187
  const inner = kids ? ` …${kids} 个子元素… ` : clip(txt, 60)
@@ -1385,17 +1459,27 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1385
1459
  const URL_RE = /url\(\s*(['"]?)([^'")]+)\1\s*\)/g
1386
1460
 
1387
1461
  /** 把一段 CSS 值里的 url(...) 都换成 data URL */
1388
- async function inlineUrls(value, base, inline) {
1462
+ async function inlineUrls(value, base, inline, idp = '') {
1389
1463
  if (!value || value.indexOf('url(') < 0) return value
1464
+ // 指着这一页里的东西(SVG 的渐变、裁剪、滤镜:url(#area)):留成页内引用,别当文件去下载
1465
+ const page = String(base || '').split('#')[0]
1466
+ const local = new Map()
1390
1467
  const jobs = []
1391
- value.replace(URL_RE, (m, q, u) => { jobs.push(u); return m })
1468
+ value.replace(URL_RE, (m, q, u) => {
1469
+ if (u.startsWith('#')) local.set(u, '#' + idp + u.slice(1))
1470
+ else {
1471
+ try { const a = new URL(u, base); if (a.hash && a.href.split('#')[0] === page) local.set(u, '#' + idp + a.hash.slice(1)) } catch { /* 怪地址 */ }
1472
+ }
1473
+ if (!local.has(u)) jobs.push(u)
1474
+ return m
1475
+ })
1392
1476
  const map = new Map()
1393
1477
  await Promise.all(jobs.map(async (u) => {
1394
1478
  let abs = u
1395
1479
  try { abs = new URL(u, base).href } catch { /* 原样 */ }
1396
1480
  map.set(u, await inline(abs))
1397
1481
  }))
1398
- return value.replace(URL_RE, (m, q, u) => (map.get(u) ? `url("${map.get(u)}")` : 'none'))
1482
+ return value.replace(URL_RE, (m, q, u) => (local.has(u) ? `url("${local.get(u)}")` : map.get(u) ? `url("${map.get(u)}")` : 'none'))
1399
1483
  }
1400
1484
 
1401
1485
  function styleText(cs, def, out) {
@@ -1416,7 +1500,7 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1416
1500
  let text = false
1417
1501
  for (const n of el.childNodes) if (n.nodeType === 3 && n.nodeValue.trim()) { text = true; break }
1418
1502
  if (!text) return false
1419
- const r = document.createRange()
1503
+ const r = el.ownerDocument.createRange()
1420
1504
  r.selectNodeContents(el)
1421
1505
  const rects = [...r.getClientRects()].filter((x) => x.width && x.height)
1422
1506
  if (!rects.length || rects.length > 40) return false
@@ -1453,6 +1537,24 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1453
1537
  const H = Math.ceil(full ? Math.max(de.scrollHeight, document.body ? document.body.scrollHeight : 0, innerHeight) : innerHeight)
1454
1538
  const box = makeSandbox()
1455
1539
  const inline = makeInliner()
1540
+ // 只截看得到的这一屏(不是整页):页面滚过、里面的滚动区滚过、有贴住的(sticky)元素,画成图时都得照现在的样子摆
1541
+ const view = !full
1542
+ const stuck = view ? stickyShift(document) : new Map()
1543
+ // 页面滚过时 body 整体往上挪(transform),body 就成了里面固定元素的定位基准:跟着窗口走的固定元素按 body 的位置换算回去,还贴在窗口原来的地方
1544
+ const lift = view && !!(scrollX || scrollY) && !!document.body
1545
+ let bodyAt = null
1546
+ if (lift) {
1547
+ const br = document.body.getBoundingClientRect()
1548
+ const bcs = getComputedStyle(document.body)
1549
+ bodyAt = { l: br.left + (parseFloat(bcs.borderLeftWidth) || 0), t: br.top + (parseFloat(bcs.borderTopWidth) || 0) }
1550
+ }
1551
+ // 怪异模式下 body.scrollTop 就是页面滚动;内嵌页面的根元素滚过(它自己的页面滚动)也照样往回挪
1552
+ // 内嵌页面画的总是它现在看得到的那块:里面的滚动(整页导出时也算)都补
1553
+ const ownScroll = (el) => el.ownerDocument !== document || (view && el !== de && (el !== document.body || document.compatMode === 'CSS1Compat'))
1554
+ // 资源地址按元素所在的那页算(内嵌页面有自己的地址)
1555
+ const baseOf = (el) => { const b = el.ownerDocument.baseURI || ''; return /^https?:/.test(b) ? b : here() }
1556
+ // 子树里还在找定位基准的绝对 / 固定定位(a / f):滚动区的孩子要是改成相对定位,会把这些绝对定位抢过来(换了基准、还被滚动区裁掉)
1557
+ const openOf = new Map()
1456
1558
  const pseudoRules = []
1457
1559
  const families = new Set()
1458
1560
  const jobs = []
@@ -1487,10 +1589,14 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1487
1589
  return p
1488
1590
  }
1489
1591
 
1490
- function walk(node) {
1592
+ // ctx:往下传「以哪个滚过的滚动区为定位基准」——a:绝对定位的后代该往回挪多少,f:固定定位的(滚动区有变换时)
1593
+ const NO_SHIFT = { a: [0, 0], f: [0, 0] }
1594
+ const idPre = new Map([[document, '']])
1595
+ function walk(node, ctx = NO_SHIFT) {
1491
1596
  if (node.nodeType === 3) return document.createTextNode(node.nodeValue)
1492
1597
  if (node.nodeType !== 1) return null
1493
1598
  const el = node
1599
+ const idp = idPre.get(el.ownerDocument) || ''
1494
1600
  if (SKIP_TAGS.has(el.tagName.toUpperCase())) return null
1495
1601
  if (el.tagName === 'STYLE' && el.namespaceURI !== SVGNS) return null
1496
1602
  const cs = getComputedStyle(el)
@@ -1508,7 +1614,14 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1508
1614
  for (const a of el.attributes) {
1509
1615
  if (a.name === 'style' || a.name.startsWith('on') || a.name === 'class' && el.namespaceURI !== SVGNS) continue
1510
1616
  if (a.name === 'srcset' || a.name === 'sizes' || a.name === 'loading') continue
1511
- try { c.setAttributeNS(a.namespaceURI, a.name, a.value) } catch { /* 怪属性名 */ }
1617
+ let v = a.value
1618
+ // 内嵌页面的 id 和页内引用加上这一页的前缀:几页里同名的渐变、裁剪不会串
1619
+ if (idp) {
1620
+ if (a.name === 'id') v = idp + v
1621
+ else if (/(^|:)href$/.test(a.name) && v.startsWith('#')) v = '#' + idp + v.slice(1)
1622
+ else if (v.indexOf('url(') >= 0) v = v.replace(/url\(\s*(['"]?)#([^'")]+)\1\s*\)/g, (m, q, id) => `url(#${idp}${id})`)
1623
+ }
1624
+ try { c.setAttributeNS(a.namespaceURI, a.name, v) } catch { /* 怪属性名 */ }
1512
1625
  }
1513
1626
  }
1514
1627
  if (el.namespaceURI === SVGNS && el.getAttribute('class')) c.setAttribute('class', el.getAttribute('class'))
@@ -1517,17 +1630,31 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1517
1630
  const def = box.defaults(el)
1518
1631
  let st = styleText(cs, def, withUrls)
1519
1632
  if (el === de) st += 'overflow:hidden;'
1633
+ // iframe / 视频换成了 div:默认的 300×150、行内排列也得写明(和 iframe 默认一样的样式上面省掉了)
1634
+ if (tag === 'IFRAME' || tag === 'VIDEO' || tag === 'OBJECT' || tag === 'EMBED') {
1635
+ st += `display:${cs.display === 'inline' ? 'inline-block' : cs.display};width:${cs.width};height:${cs.height};box-sizing:${cs.boxSizing};vertical-align:${cs.verticalAlign};overflow:hidden;`
1636
+ }
1637
+ // 贴住了:画成图时没有滚动,按量出来的偏移摆回现在的位置
1638
+ if (stuck.has(el)) { const [dx, dy] = stuck.get(el); st += `position:relative;inset:auto;left:${dx}px;top:${dy}px;` }
1639
+ // 以滚过的滚动区为基准的绝对 / 固定定位:跟着内容滚,往回挪(不管隔了几层)
1640
+ const owe = el.namespaceURI === SVGNS ? null : cs.position === 'absolute' ? ctx.a : cs.position === 'fixed' ? ctx.f : null
1641
+ if (owe && (owe[0] || owe[1])) st += shiftCss(cs, owe[0], owe[1])
1642
+ if (lift && cs.position === 'fixed' && el.namespaceURI !== SVGNS && el.ownerDocument === document && document.body.contains(el) && !fixedHeld(el)) {
1643
+ const x = parseFloat(cs.left)
1644
+ const y = parseFloat(cs.top)
1645
+ if (Number.isFinite(x) && Number.isFinite(y)) st += `left:${x - bodyAt.l}px;top:${y - bodyAt.t}px;right:auto;bottom:auto;`
1646
+ }
1520
1647
  // 原来一行放得下的字,画成图时也别折行(宽度是定死的,字体渲染差一丁点就会挤到第二行)
1521
1648
  if (el.namespaceURI !== SVGNS && cs.whiteSpace !== 'nowrap' && oneLine(el)) st += 'white-space:nowrap;'
1522
1649
  c.setAttribute('style', st)
1523
1650
  families.add(cs.fontFamily)
1524
1651
  if (withUrls.length) {
1652
+ // 等图片转好再换进去;换的时候读那一刻的 style(滚动区补的偏移是后来加上的,别盖掉)
1653
+ const vals = withUrls.map((p) => cs.getPropertyValue(p))
1525
1654
  jobs.push((async () => {
1655
+ const done = await Promise.all(vals.map((v) => inlineUrls(v, baseOf(el), inline, idp)))
1526
1656
  let s = c.getAttribute('style')
1527
- for (const p of withUrls) {
1528
- const v = cs.getPropertyValue(p)
1529
- s = s.replace(`${p}:${v};`, `${p}:${await inlineUrls(v, here(), inline)};`)
1530
- }
1657
+ withUrls.forEach((p, i) => { s = s.replace(`${p}:${vals[i]};`, `${p}:${done[i]};`) })
1531
1658
  c.setAttribute('style', s)
1532
1659
  })())
1533
1660
  }
@@ -1538,12 +1665,12 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1538
1665
  }
1539
1666
  if (el.namespaceURI === SVGNS && el.localName === 'image') {
1540
1667
  const href = el.getAttribute('href') || el.getAttributeNS('http://www.w3.org/1999/xlink', 'href')
1541
- if (href) jobs.push(inline(new URL(href, here()).href).then((d) => { if (d) c.setAttribute('href', d) }))
1668
+ if (href) jobs.push(inline(new URL(href, baseOf(el)).href).then((d) => { if (d) c.setAttribute('href', d) }))
1542
1669
  }
1543
1670
  if (el.namespaceURI === SVGNS && el.localName === 'use') {
1544
1671
  const href = el.getAttribute('href') || el.getAttributeNS('http://www.w3.org/1999/xlink', 'href') || ''
1545
1672
  let abs = ''
1546
- try { abs = href && !href.startsWith('#') ? new URL(href, here()).href : '' } catch { /* 怪地址 */ }
1673
+ try { abs = href && !href.startsWith('#') ? new URL(href, baseOf(el)).href : '' } catch { /* 怪地址 */ }
1547
1674
  if (abs && abs.includes('#')) {
1548
1675
  jobs.push(spriteOf(abs).then((id) => {
1549
1676
  if (!id) return
@@ -1558,7 +1685,9 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1558
1685
  if (tag === 'TEXTAREA') c.textContent = el.value
1559
1686
  if (tag === 'SELECT') c.setAttribute('data-v', el.value)
1560
1687
 
1561
- // ::before / ::after
1688
+ // ::before / ::after(绝对 / 固定定位的:跟着它的定位基准滚,也算还在往外找基准的)
1689
+ let pa = false
1690
+ let pf = false
1562
1691
  if (el.namespaceURI !== SVGNS) {
1563
1692
  const pes = (tag === 'INPUT' || tag === 'TEXTAREA') && el.getAttribute('placeholder') ? ['::before', '::after', '::placeholder'] : ['::before', '::after']
1564
1693
  for (const pe of pes) {
@@ -1568,18 +1697,82 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1568
1697
  const cls = 'ddpx' + (++seq)
1569
1698
  c.setAttribute('class', ((c.getAttribute('class') || '') + ' ' + cls).trim())
1570
1699
  const urls = []
1571
- const body = styleText(ps, box.defaults(el, pe), urls)
1700
+ let body = styleText(ps, box.defaults(el, pe), urls)
1701
+ const pp = ps.position
1702
+ if (pp === 'absolute' || pp === 'fixed') {
1703
+ const mine = pp === 'absolute' ? holds(cs) : holds(cs, true)
1704
+ const owe = mine ? (ownScroll(el) ? [el.scrollLeft, el.scrollTop] : [0, 0]) : pp === 'absolute' ? ctx.a : ctx.f
1705
+ if (owe[0] || owe[1]) body += shiftCss(ps, owe[0], owe[1])
1706
+ if (!mine) { if (pp === 'absolute') pa = true; else pf = true }
1707
+ // 贴着窗口的(比如 body::before 铺的固定背景):页面滚过、body 整体挪了,按 body 的位置换算回去
1708
+ if (pp === 'fixed' && !mine && lift && el.ownerDocument === document && document.body.contains(el) && !fixedHeld(el)) {
1709
+ const x = parseFloat(ps.left)
1710
+ const y = parseFloat(ps.top)
1711
+ if (Number.isFinite(x) && Number.isFinite(y)) body += `left:${x - bodyAt.l}px;top:${y - bodyAt.t}px;right:auto;bottom:auto;`
1712
+ }
1713
+ }
1572
1714
  const i = pseudoRules.length
1573
1715
  pseudoRules.push(`.${cls}${pe}{${body}}`)
1574
- if (urls.length) jobs.push(inlineUrls(pseudoRules[i], here(), inline).then((t) => { pseudoRules[i] = t }))
1716
+ if (urls.length) jobs.push(inlineUrls(pseudoRules[i], baseOf(el), inline, idp).then((t) => { pseudoRules[i] = t }))
1575
1717
  }
1576
1718
  }
1577
1719
 
1578
- if (tag === 'IFRAME' || tag === 'CANVAS' || tag === 'VIDEO' || tag === 'TEXTAREA') return c
1720
+ // 下面这几种不往里走:自己是绝对 / 固定定位的也得记上(外层滚动区挪的时候要知道)
1721
+ if ((tag === 'IFRAME' || tag === 'CANVAS' || tag === 'VIDEO' || tag === 'TEXTAREA') && (cs.position === 'absolute' || cs.position === 'fixed')) {
1722
+ openOf.set(el, { a: cs.position === 'absolute', f: cs.position === 'fixed' })
1723
+ }
1724
+ if (tag === 'IFRAME') {
1725
+ // 同源的内嵌页面:把它的页面也复制进来(框住、按它自己的滚动摆);拿不到的(跨域)铺一层浅灰,看得出这里有东西没截到
1726
+ let doc = null
1727
+ try { doc = el.contentDocument } catch { doc = null }
1728
+ let inner = null
1729
+ if (doc && doc.documentElement && depth < 3) {
1730
+ depth++
1731
+ try { inner = walkIn(doc) } finally { depth-- }
1732
+ }
1733
+ // 里面固定定位的元素以这一框为准:框自己没变换的,补一个不动的变换
1734
+ if (inner) {
1735
+ c.setAttribute('style', c.getAttribute('style') + 'overflow:hidden;' + (cs.transform !== 'none' ? '' : 'transform:translate(0,0);'))
1736
+ c.appendChild(inner)
1737
+ } else c.setAttribute('style', c.getAttribute('style') + 'background-color:rgba(127,127,127,.15);')
1738
+ return c
1739
+ }
1740
+ if (tag === 'CANVAS' || tag === 'VIDEO' || tag === 'TEXTAREA') return c
1741
+ // 自己滚过的滚动区:里面的东西按滚动距离往回挪(图里没有滚动)
1742
+ const ox = el.namespaceURI !== SVGNS && ownScroll(el) ? el.scrollLeft : 0
1743
+ const oy = el.namespaceURI !== SVGNS && ownScroll(el) ? el.scrollTop : 0
1744
+ // 跟着内容滚的背景(background-attachment: local)也往回挪
1745
+ if ((ox || oy) && /local/.test(cs.backgroundAttachment)) {
1746
+ const att = cs.backgroundAttachment.split(',').map((x) => x.trim())
1747
+ const pos = cs.backgroundPosition.split(',').map((p, i) => {
1748
+ if (att[i % att.length] !== 'local') return p.trim()
1749
+ const [x = '0%', y = '0%'] = splitTop(p.trim())
1750
+ return `calc(${x} - ${ox}px) calc(${y} - ${oy}px)`
1751
+ })
1752
+ c.setAttribute('style', c.getAttribute('style') + `background-position:${pos.join(', ')};`)
1753
+ }
1754
+ let oa = false
1755
+ let of = false
1756
+ const kids = []
1757
+ // 自己是定位基准的:它的后代按它的滚动挪;不是的,接着用外面传进来的
1758
+ const hF = holds(cs, true)
1759
+ const hA = hF || cs.position !== 'static' // 和 holds(cs) 一样,少算一遍
1760
+ const sub = hA || hF ? { a: hA ? [ox, oy] : ctx.a, f: hF ? [ox, oy] : ctx.f } : ctx
1579
1761
  for (const child of el.childNodes) {
1580
- const k = walk(child)
1581
- if (k) c.appendChild(k)
1762
+ const k = walk(child, sub)
1763
+ if (k) kids.push([child, k])
1764
+ const o = child.nodeType === 1 && openOf.get(child)
1765
+ if (o) { oa = oa || o.a; of = of || o.f }
1582
1766
  }
1767
+ if (ox || oy) scrollBack(kids, cs, ox, oy, stuck, openOf)
1768
+ for (const [, k] of kids) c.appendChild(k)
1769
+ if (hA) oa = false
1770
+ if (hF) of = false
1771
+ if (pa) oa = true
1772
+ if (pf) of = true
1773
+ if (cs.position === 'absolute') oa = true
1774
+ if (cs.position === 'fixed') of = true
1775
+ if (oa || of) openOf.set(el, { a: oa, f: of })
1583
1776
  if (tag === 'SELECT') {
1584
1777
  const o = el.selectedOptions && el.selectedOptions[0]
1585
1778
  c.textContent = ''
@@ -1589,6 +1782,20 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1589
1782
  }
1590
1783
  return c
1591
1784
  }
1785
+ // 内嵌页面的那一份:它自己的根元素也当滚动区(滚过就往回挪),不算外层页面的根
1786
+ let depth = 0
1787
+ const docs = new Set([document])
1788
+ function walkIn(doc) {
1789
+ // 内嵌页面里贴住的元素也按它现在的样子摆
1790
+ for (const [el, v] of stickyShift(doc)) stuck.set(el, v)
1791
+ docs.add(doc)
1792
+ if (!idPre.has(doc)) idPre.set(doc, `ddpf${++seq}-`)
1793
+ const r = doc.documentElement
1794
+ // 以整页为准的绝对定位跟着这一页滚
1795
+ const k = walk(r, { a: [r.scrollLeft, r.scrollTop], f: [0, 0] })
1796
+ if (k) k.setAttribute('style', (k.getAttribute('style') || '') + 'overflow:hidden;')
1797
+ return k
1798
+ }
1592
1799
 
1593
1800
  try {
1594
1801
  const top = topDark() // 和复制页面同一刻量(后面等图片、字体时页面可能又变了)
@@ -1596,19 +1803,23 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1596
1803
  // 字体:页面样式表里的 @font-face,只带用到的字族
1597
1804
  const faces = []
1598
1805
  const used = [...families].join(',').toLowerCase()
1599
- for (const sheet of document.styleSheets) {
1600
- let rules
1601
- try { rules = sheet.cssRules } catch { continue }
1602
- const base = sheetHref(sheet)
1603
- const scan = (list) => {
1604
- for (const r of list) {
1605
- if (r.cssRules && !(r instanceof CSSFontFaceRule)) { try { scan(r.cssRules) } catch { /* 读不了 */ } continue }
1606
- if (!(r instanceof CSSFontFaceRule)) continue
1607
- const fam = (r.style.getPropertyValue('font-family') || '').replace(/['"]/g, '').trim().toLowerCase()
1608
- if (fam && used.includes(fam)) faces.push(inlineUrls(r.cssText, base, inline))
1806
+ // 内嵌页面的规则是它那个窗口的类,instanceof 认不出来,按 type 认(5 = @font-face)
1807
+ const isFace = (r) => r.type === 5 || r instanceof CSSFontFaceRule
1808
+ for (const d of docs) {
1809
+ for (const sheet of d.styleSheets) {
1810
+ let rules
1811
+ try { rules = sheet.cssRules } catch { continue }
1812
+ const base = d === document ? sheetHref(sheet) : sheet.href || d.baseURI
1813
+ const scan = (list) => {
1814
+ for (const r of list) {
1815
+ if (r.cssRules && !isFace(r)) { try { scan(r.cssRules) } catch { /* 读不了 */ } continue }
1816
+ if (!isFace(r)) continue
1817
+ const fam = (r.style.getPropertyValue('font-family') || '').replace(/['"]/g, '').trim().toLowerCase()
1818
+ if (fam && used.includes(fam)) faces.push(inlineUrls(r.cssText, base, inline))
1819
+ }
1609
1820
  }
1821
+ scan(rules)
1610
1822
  }
1611
- scan(rules)
1612
1823
  }
1613
1824
  await Promise.all(jobs)
1614
1825
  const fontCss = (await Promise.all(faces)).join('\n')
@@ -1618,7 +1829,10 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1618
1829
  ;(body || root).insertBefore(style, (body || root).firstChild)
1619
1830
  if (sprites.childNodes.length) (body || root).appendChild(sprites)
1620
1831
  if (!full && (scrollX || scrollY) && body) {
1621
- body.setAttribute('style', body.getAttribute('style') + `transform:translate(${-scrollX}px,${-scrollY}px);`)
1832
+ // 用 translate 属性挪:它在 transform / scale / rotate 外面一层,body 自己缩放旋转过也照样整体挪滚动距离
1833
+ const t0 = String(getComputedStyle(document.body).translate || 'none')
1834
+ const [tx = '0px', ty = '0px', tz = ''] = t0 === 'none' ? [] : splitTop(t0)
1835
+ body.setAttribute('style', body.getAttribute('style') + `translate:calc(${tx} - ${scrollX}px) calc(${ty} - ${scrollY}px)${tz ? ' ' + tz : ''};`)
1622
1836
  }
1623
1837
  const xml = new XMLSerializer().serializeToString(root)
1624
1838
  const svg = `<svg xmlns="${SVGNS}" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}"><foreignObject x="0" y="0" width="100%" height="100%">${xml}</foreignObject></svg>`
@@ -1641,13 +1855,159 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1641
1855
  }
1642
1856
  }
1643
1857
 
1858
+ /** 贴住的(sticky)元素现在被贴偏了多少:量现在的位置,临时取消贴住再量一次,差就是偏移(同一刻改回去,不重画) */
1859
+ function stickyShift(doc) {
1860
+ const out = new Map()
1861
+ const list = []
1862
+ for (const el of doc.querySelectorAll('body *')) {
1863
+ if (getComputedStyle(el).position === 'sticky') list.push(el)
1864
+ if (list.length >= 400) break
1865
+ }
1866
+ if (!list.length) return out
1867
+ const live = list.map((el) => [el.offsetLeft, el.offsetTop])
1868
+ const st = doc.createElement('style')
1869
+ st.textContent = '[data-dsh-unstick]{position:relative!important;inset:auto!important}'
1870
+ doc.documentElement.appendChild(st)
1871
+ try {
1872
+ for (const el of list) el.setAttribute('data-dsh-unstick', '')
1873
+ // 按排版坐标量(offsetLeft / offsetTop 不受缩放、旋转影响;相对最近的定位祖先,外层也贴住了的那份不会重复算)
1874
+ list.forEach((el, i) => {
1875
+ const dx = live[i][0] - el.offsetLeft
1876
+ const dy = live[i][1] - el.offsetTop
1877
+ if (dx || dy) out.set(el, [dx, dy])
1878
+ })
1879
+ } finally {
1880
+ for (const el of list) el.removeAttribute('data-dsh-unstick')
1881
+ st.remove()
1882
+ }
1883
+ return out
1884
+ }
1885
+
1886
+ /** 固定元素是不是被某个祖先(transform、filter 之类)接管了位置:接管了就跟着那个祖先走,不用挪 */
1887
+ function fixedHeld(el) {
1888
+ for (let a = el.parentElement; a; a = a.parentElement) if (holds(getComputedStyle(a), true)) return true
1889
+ return false
1890
+ }
1891
+
1892
+ /**
1893
+ * 滚过的滚动区:里面的东西按滚动距离往回挪(图里没有滚动)。kids:[原节点, 复制出来的] 按顺序,挪的时候可能换掉复制出来的那个。
1894
+ * 能不动定位就不动(改成相对定位会打乱上下层、把往外找基准的绝对定位框进来):
1895
+ * 竖着滚的块容器 / 竖排 flex,给第一个在文档流里的块加负的上边距,后面的跟着往上走;横着滚的横排 flex 同理加左边距,块容器给每个块加左边距。
1896
+ * 别的排法(grid 之类)退回一个个用相对定位挪;绝对 / 固定定位的(以滚动区为准的)改它自己的 left / top
1897
+ */
1898
+ function scrollBack(kids, pcs, ox, oy, stuck, openOf) {
1899
+ const flex = /flex/.test(pcs.display)
1900
+ const grid = /grid/.test(pcs.display)
1901
+ const dir = String(pcs.flexDirection || 'row')
1902
+ const row = flex && dir === 'row'
1903
+ const col = flex && dir === 'column'
1904
+ const rtl = pcs.direction === 'rtl'
1905
+ const add = (k, css) => k.setAttribute('style', (k.getAttribute('style') || '') + css)
1906
+ const info = kids.map(([child, k]) => {
1907
+ if (child.nodeType !== 1) return { child, k, flow: true, text: !!(child.nodeValue || '').trim(), blank: !(child.nodeValue || '').trim() }
1908
+ const ccs = getComputedStyle(child)
1909
+ const out = ccs.position === 'absolute' || ccs.position === 'fixed'
1910
+ return { child, k, ccs, flow: !out, inline: !flex && !grid && /^inline/.test(ccs.display) }
1911
+ })
1912
+ const flow = info.filter((x) => x.flow && !x.blank)
1913
+ const first = flow[0]
1914
+ // 负边距能整列带着走的:普通的块(不浮动、不是 display:contents)
1915
+ const block = (x) => x && !x.text && !x.inline && x.ccs.float === 'none' && x.ccs.display !== 'contents'
1916
+ const floats = flow.some((x) => x.ccs && x.ccs.float !== 'none')
1917
+ // flex 主轴不是从头排的(居中、两端对齐……):加了负边距会重新排,退回一个个挪
1918
+ const startish = (v) => /^(normal|flex-start|start|left|stretch)$/.test(String(v || 'normal'))
1919
+ let fy = oy
1920
+ let fx = ox
1921
+ let spacer = null
1922
+ if (oy && block(first) && !floats && !flex && !grid) {
1923
+ // 块容器:前面垫一个高 0、上边距为负的块(自己是 BFC,边距不和后面的叠),后面的照原来的边距(包括往里叠的)往下排
1924
+ spacer = document.createElementNS(XHTML, 'div')
1925
+ spacer.setAttribute('style', `display:flow-root;height:0;margin:-${oy}px 0 0;padding:0;border:0`)
1926
+ fy = 0
1927
+ } else if (oy && block(first) && col && startish(pcs.justifyContent)) {
1928
+ // flex 里边距不叠:直接给第一个加
1929
+ add(first.k, `margin-top:${(parseFloat(first.ccs.marginTop) || 0) - oy}px;`)
1930
+ fy = 0
1931
+ }
1932
+ if (ox && !rtl && block(first) && row && startish(pcs.justifyContent)) {
1933
+ add(first.k, `margin-left:${(parseFloat(first.ccs.marginLeft) || 0) - ox}px;`)
1934
+ fx = 0
1935
+ } else if (ox && !rtl && !flex && !grid && !floats && flow.length && flow.every(block)) {
1936
+ // 块是一个个摆的,横着各挪各的(宽度已经按原来的定死,不会被负边距撑宽)
1937
+ for (const x of flow) add(x.k, `margin-left:${(parseFloat(x.ccs.marginLeft) || 0) - ox}px;`)
1938
+ fx = 0
1939
+ }
1940
+ // 绝对 / 固定定位的在 walk 里按定位基准挪过了;剩下没挪成的一个个挪
1941
+ for (const x of info) {
1942
+ if (x.blank || !x.flow) continue
1943
+ if (fx || fy) x.k = scrolledKid(x.k, x.child, pcs, fx, fy, stuck, openOf.get(x.child))
1944
+ }
1945
+ info.forEach((x, i) => { kids[i][1] = x.k })
1946
+ if (spacer) kids.splice(kids.findIndex(([c]) => c === first.child), 0, [null, spacer])
1947
+ }
1948
+
1949
+ /** 按空格拆一个 CSS 值(括号里的空格不拆:calc()、clamp() 整个算一段) */
1950
+ function splitTop(v) {
1951
+ const out = []
1952
+ let cur = ''
1953
+ let depth = 0
1954
+ for (const ch of String(v)) {
1955
+ if (ch === '(') depth++
1956
+ else if (ch === ')') depth = Math.max(0, depth - 1)
1957
+ if (/\s/.test(ch) && !depth) { if (cur) out.push(cur); cur = '' } else cur += ch
1958
+ }
1959
+ if (cur) out.push(cur)
1960
+ return out
1961
+ }
1962
+
1963
+ /** 定位元素往回挪 (dx, dy):只动挪了的那个方向;从右往左排的横向按 right 挪 */
1964
+ function shiftCss(cs, dx, dy) {
1965
+ let css = ''
1966
+ if (dy) { const y = parseFloat(cs.top); if (Number.isFinite(y)) css += `top:${y - dy}px;bottom:auto;` }
1967
+ if (dx) {
1968
+ if (cs.direction === 'rtl') { const r = parseFloat(cs.right); if (Number.isFinite(r)) css += `right:${r + dx}px;left:auto;` } else { const x = parseFloat(cs.left); if (Number.isFinite(x)) css += `left:${x - dx}px;right:auto;` }
1969
+ }
1970
+ return css
1971
+ }
1972
+
1973
+ /**
1974
+ * 滚过的滚动区里的一个孩子,用相对定位往回挪。
1975
+ * 不跟着滚的不挪:固定定位(滚动区没接管它)、包含块在滚动区外面的绝对定位。
1976
+ * 本来没定位、里面又有还在往外找基准的绝对定位的(比如以外层为准的弹层):改成相对定位会把它们框进来,这一块宁可不挪
1977
+ */
1978
+ function scrolledKid(k, child, pcs, ox, oy, stuck, open) {
1979
+ if (child.nodeType === 3) {
1980
+ if (!child.nodeValue.trim()) return k
1981
+ const s = document.createElementNS(XHTML, 'span')
1982
+ s.setAttribute('style', `position:relative;left:${-ox}px;top:${-oy}px;`)
1983
+ s.appendChild(k)
1984
+ return s
1985
+ }
1986
+ if (child.nodeType !== 1) return k
1987
+ const ccs = getComputedStyle(child)
1988
+ const pos = ccs.position
1989
+ if ((pos === 'fixed' && !holds(pcs, true)) || (pos === 'absolute' && !holds(pcs))) return k
1990
+ if (pos === 'static' && open && open.a) return k
1991
+ let x = 0
1992
+ let y = 0
1993
+ if (stuck.has(child)) [x, y] = stuck.get(child)
1994
+ else if (pos !== 'static' && pos !== 'sticky') { x = parseFloat(ccs.left) || 0; y = parseFloat(ccs.top) || 0 }
1995
+ const keep = pos === 'absolute' || pos === 'fixed'
1996
+ // 从右往左排的:右边的偏移才算数
1997
+ const hx = ccs.direction === 'rtl' && !stuck.has(child) && pos !== 'static' && pos !== 'sticky'
1998
+ ? `right:${(parseFloat(ccs.right) || 0) + ox}px;left:auto;`
1999
+ : `left:${x - ox}px;right:auto;`
2000
+ k.setAttribute('style', (k.getAttribute('style') || '') + `position:${keep ? pos : 'relative'};${ox ? hx : ''}${oy ? `top:${y - oy}px;bottom:auto;` : ''}`)
2001
+ return k
2002
+ }
2003
+
1644
2004
  async function onCapture(d) {
1645
2005
  try {
1646
2006
  const r = await capture(d)
1647
2007
  // 整页图从文档顶上画起,链接加上滚动距离;只截视口时就是视口里的位置
1648
2008
  const links = linksOf().map((l) => (d.full ? { ...l, x: l.x + scrollX, y: l.y + scrollY } : l))
1649
2009
  .filter((l) => l.x < r.w && l.y < r.h && l.x + l.w > 0 && l.y + l.h > 0)
1650
- post({ type: 'captured', id: d.id, png: r.png, w: r.w, h: r.h, scale: r.scale, title: document.title, links, top: r.top })
2010
+ post({ type: 'captured', id: d.id, png: r.png, w: r.w, h: r.h, scale: r.scale, title: document.title, links, top: r.top, href: here() })
1651
2011
  } catch (e) {
1652
2012
  post({ type: 'captured', id: d.id, error: String((e && e.message) || e) })
1653
2013
  }
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Design Studio",
4
- "description": "A design workbench in the right sidebar: web, app, mini program and poster screens generate on a canvas inside device frames; click an element to have the model change it, drag sliders to tweak design tokens across every screen, compare and roll back versions, extract a brand's design system from a website, turn a design into React / Vue / HTML code and diff it pixel by pixel, export share-ready images, and scan a QR code to view it on your phone."
4
+ "description": "A design workbench in the right sidebar: web, app, mini program and poster screens generate on a canvas inside device frames; click an element or circle it with the brush to have the model change it, open existing HTML pages to keep working on them, drag sliders to tweak design tokens across every screen, compare and roll back versions, extract a brand's design system from a website, turn a design into React / Vue / HTML code and diff it pixel by pixel, export share-ready images, and scan a QR code to view it on your phone."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "设计工作台",
4
- "description": "右侧栏的设计工作台:网页、App、小程序、海报一屏屏生成在画布上,套好外框;点一下元素就让模型改那里,拖滑块调设计变量全屏一起变,版本能对比回退;能从网站提取品牌设计系统,也能把设计转成 React / Vue / HTML 代码并逐像素对比;一键导出好看的展示图,扫码就能在手机上看。"
4
+ "description": "右侧栏的设计工作台:网页、App、小程序、海报一屏屏生成在画布上,套好外框;点一下元素或用画笔圈出来就让模型改那里,已有的 HTML 页面也能打开接着改;拖滑块调设计变量全屏一起变,版本能对比回退;能从网站提取品牌设计系统,也能把设计转成 React / Vue / HTML 代码并逐像素对比;一键导出好看的展示图,扫码就能在手机上看。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "dsh-design-studio",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1 test/*.mjs"
7
7
  },
8
- "description": "Design workbench in the DeepSeek Harness right sidebar: watch web / app / mini program / poster screens generate on a canvas with device frames, click an element to send it to the chat, tweak design tokens with sliders, compare versions, extract a brand's design system from a site, turn a design into React / Vue / HTML code checked pixel by pixel, export share-ready images and scan to view on your phone.",
8
+ "description": "Design workbench in the DeepSeek Harness right sidebar: watch web / app / mini program / poster screens generate on a canvas with device frames, click an element or mark it up with a brush to send it to the chat, open existing HTML pages, tweak design tokens with sliders, compare versions, extract a brand's design system from a site, turn a design into React / Vue / HTML code checked pixel by pixel, export share-ready images and scan to view on your phone.",
9
9
  "license": "MIT",
10
10
  "repository": {
11
11
  "type": "git",