dsh-design-studio 0.10.0 → 0.12.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.
Files changed (98) hide show
  1. package/README.en.md +4 -3
  2. package/README.md +6 -5
  3. package/assets/demo.gif +0 -0
  4. package/assets/hero-sm.jpg +0 -0
  5. package/cordis.patch.yml +5 -0
  6. package/gallery-seed/d/orderg-x__alley-noodles/08e9e40834f9/_shots/menu.jpg +0 -0
  7. package/gallery-seed/d/orderg-x__alley-noodles/08e9e40834f9/app.css +64 -0
  8. package/gallery-seed/d/orderg-x__alley-noodles/08e9e40834f9/cart.html +120 -0
  9. package/gallery-seed/d/orderg-x__alley-noodles/08e9e40834f9/design.json +56 -0
  10. package/gallery-seed/d/orderg-x__alley-noodles/08e9e40834f9/menu.html +200 -0
  11. package/gallery-seed/d/orderg-x__alley-noodles/08e9e40834f9/order.html +135 -0
  12. package/gallery-seed/d/orderg-x__alley-noodles/08e9e40834f9/tokens.css +43 -0
  13. package/gallery-seed/d/orderg-x__autumn-sale/08e9e40834f9/_shots/email.jpg +0 -0
  14. package/gallery-seed/d/orderg-x__autumn-sale/08e9e40834f9/design.json +20 -0
  15. package/gallery-seed/d/orderg-x__autumn-sale/08e9e40834f9/email.html +268 -0
  16. package/gallery-seed/d/orderg-x__little-painter/08e9e40834f9/_shots/courses.jpg +0 -0
  17. package/gallery-seed/d/orderg-x__little-painter/08e9e40834f9/courses.html +364 -0
  18. package/gallery-seed/d/orderg-x__little-painter/08e9e40834f9/design.json +49 -0
  19. package/gallery-seed/d/orderg-x__little-painter/08e9e40834f9/lesson.html +196 -0
  20. package/gallery-seed/d/orderg-x__little-painter/08e9e40834f9/tokens.css +55 -0
  21. package/gallery-seed/d/orderg-x__little-painter/08e9e40834f9/ui.css +255 -0
  22. package/gallery-seed/d/orderg-x__moon-fair/08e9e40834f9/_shots/poster.jpg +0 -0
  23. package/gallery-seed/d/orderg-x__moon-fair/08e9e40834f9/design.json +21 -0
  24. package/gallery-seed/d/orderg-x__moon-fair/08e9e40834f9/poster.html +165 -0
  25. package/gallery-seed/d/orderg-x__moon-fair/08e9e40834f9/tokens.css +35 -0
  26. package/gallery-seed/d/orderg-x__paw-diary/08e9e40834f9/_shots/home.jpg +0 -0
  27. package/gallery-seed/d/orderg-x__paw-diary/08e9e40834f9/app.css +155 -0
  28. package/gallery-seed/d/orderg-x__paw-diary/08e9e40834f9/booking.html +232 -0
  29. package/gallery-seed/d/orderg-x__paw-diary/08e9e40834f9/design.json +57 -0
  30. package/gallery-seed/d/orderg-x__paw-diary/08e9e40834f9/health.html +221 -0
  31. package/gallery-seed/d/orderg-x__paw-diary/08e9e40834f9/home.html +225 -0
  32. package/gallery-seed/d/orderg-x__paw-diary/08e9e40834f9/tokens.css +54 -0
  33. package/gallery-seed/d/orderg-x__pocket-ledger/08e9e40834f9/_shots/overview.jpg +0 -0
  34. package/gallery-seed/d/orderg-x__pocket-ledger/08e9e40834f9/app.css +79 -0
  35. package/gallery-seed/d/orderg-x__pocket-ledger/08e9e40834f9/design.json +51 -0
  36. package/gallery-seed/d/orderg-x__pocket-ledger/08e9e40834f9/entries.html +161 -0
  37. package/gallery-seed/d/orderg-x__pocket-ledger/08e9e40834f9/icons.svg +30 -0
  38. package/gallery-seed/d/orderg-x__pocket-ledger/08e9e40834f9/overview.html +181 -0
  39. package/gallery-seed/d/orderg-x__pocket-ledger/08e9e40834f9/tokens.css +50 -0
  40. package/gallery-seed/d/orderg-x__time-bookshop/08e9e40834f9/_shots/home.jpg +0 -0
  41. package/gallery-seed/d/orderg-x__time-bookshop/08e9e40834f9/book.html +279 -0
  42. package/gallery-seed/d/orderg-x__time-bookshop/08e9e40834f9/design.json +21 -0
  43. package/gallery-seed/d/orderg-x__time-bookshop/08e9e40834f9/home.html +348 -0
  44. package/gallery-seed/d/orderg-x__time-bookshop/08e9e40834f9/style.css +297 -0
  45. package/gallery-seed/d/orderg-x__time-bookshop/08e9e40834f9/tokens.css +49 -0
  46. package/gallery-seed/d/orderg-x__year-review/08e9e40834f9/01-cover.html +133 -0
  47. package/gallery-seed/d/orderg-x__year-review/08e9e40834f9/02-highlights.html +67 -0
  48. package/gallery-seed/d/orderg-x__year-review/08e9e40834f9/03-growth.html +89 -0
  49. package/gallery-seed/d/orderg-x__year-review/08e9e40834f9/04-milestones.html +92 -0
  50. package/gallery-seed/d/orderg-x__year-review/08e9e40834f9/05-next.html +99 -0
  51. package/gallery-seed/d/orderg-x__year-review/08e9e40834f9/06-thanks.html +61 -0
  52. package/gallery-seed/d/orderg-x__year-review/08e9e40834f9/_shots/01-cover.jpg +0 -0
  53. package/gallery-seed/d/orderg-x__year-review/08e9e40834f9/deck.css +67 -0
  54. package/gallery-seed/d/orderg-x__year-review/08e9e40834f9/design.json +25 -0
  55. package/gallery-seed/d/orderg-x__year-review/08e9e40834f9/tokens.css +30 -0
  56. package/gallery-seed/index.json +1 -0
  57. package/gallery-seed/thumbs/orderg-x__alley-noodles.webp +0 -0
  58. package/gallery-seed/thumbs/orderg-x__autumn-sale.webp +0 -0
  59. package/gallery-seed/thumbs/orderg-x__little-painter.webp +0 -0
  60. package/gallery-seed/thumbs/orderg-x__moon-fair.webp +0 -0
  61. package/gallery-seed/thumbs/orderg-x__paw-diary.webp +0 -0
  62. package/gallery-seed/thumbs/orderg-x__pocket-ledger.webp +0 -0
  63. package/gallery-seed/thumbs/orderg-x__time-bookshop.webp +0 -0
  64. package/gallery-seed/thumbs/orderg-x__year-review.webp +0 -0
  65. package/lib/browser.js +23 -9
  66. package/lib/bundle.js +12 -3
  67. package/lib/client.js +3253 -483
  68. package/lib/core.js +231 -7
  69. package/lib/draft-page.js +763 -0
  70. package/lib/draft.js +151 -0
  71. package/lib/gallery/css.js +230 -0
  72. package/lib/gallery/html.js +313 -0
  73. package/lib/gallery/index.js +22 -0
  74. package/lib/gallery/market-routes.js +306 -0
  75. package/lib/gallery/market.js +623 -0
  76. package/lib/gallery/pack.js +311 -0
  77. package/lib/gallery/policy.js +1560 -0
  78. package/lib/gallery/qrfind.js +181 -0
  79. package/lib/gallery/render.js +148 -0
  80. package/lib/gallery/routes.js +360 -0
  81. package/lib/gallery/tar.js +118 -0
  82. package/lib/gallery/use.js +125 -0
  83. package/lib/gallery/zip.js +212 -0
  84. package/lib/handoff.js +190 -36
  85. package/lib/history.js +3 -1
  86. package/lib/index.js +123 -22
  87. package/lib/inspire.js +142 -0
  88. package/lib/offline.js +17 -0
  89. package/lib/picker.js +260 -1
  90. package/lib/serve.js +264 -11
  91. package/lib/tweaks.js +58 -24
  92. package/lib/works.js +238 -0
  93. package/locale/en.json +2 -1
  94. package/locale/offline/en.json +6 -0
  95. package/locale/offline/zh.json +6 -0
  96. package/locale/zh.json +2 -1
  97. package/package.json +9 -2
  98. package/skills/ui-design/SKILL.md +9 -0
package/lib/picker.js CHANGED
@@ -36,6 +36,9 @@
36
36
  s.textContent = '*{scrollbar-width:none}*::-webkit-scrollbar{display:none}'
37
37
  ;(document.head || document.documentElement).appendChild(s)
38
38
  }
39
+ // 别人做的设计(设计库来的、没改过):服务端在脚本标签上标了 data-strict(远程看时在 cfg 里)。
40
+ // 点站外链接不跳(页面本来就跑不了脚本、交不出表单,这里再挡住「点一下跳到别的网站」),告诉右侧栏拦下了
41
+ const STRICT = !!cfg.strict || !!(document.currentScript && document.currentScript.getAttribute('data-strict') === '1')
39
42
  const SEED_KEY = '__dsh_design_seed__'
40
43
  // 远程看(右侧栏把这一屏打包放进沙盒 iframe 的 srcdoc,location 是 about:srcdoc):这一屏原本的地址由右侧栏给
41
44
  const HERE = cfg.remote && typeof cfg.href === 'string' ? cfg.href : ''
@@ -602,6 +605,27 @@
602
605
  .scan::after{content:"";position:absolute;left:0;right:0;bottom:8%;height:2px;
603
606
  background:linear-gradient(90deg,transparent,#8ea2ff 20%,#c4b5fd 50%,#5eead4 80%,transparent);box-shadow:0 0 14px 3px rgba(124,140,255,.55)}
604
607
  @keyframes scan{0%{opacity:0;transform:translateY(-38vh)}12%{opacity:1}82%{opacity:1}100%{opacity:0;transform:translateY(100vh)}}
608
+ /* 生成动画:带名字的鼠标把版面框出来,再由上往下显出整屏 */
609
+ .bmask{position:fixed;inset:0;background:var(--bg,#fff);clip-path:inset(0 0 0 0)}
610
+ .bmask.go{transition:clip-path var(--dur,900ms) cubic-bezier(.55,.05,.25,1);clip-path:inset(100% 0 0 0)}
611
+ .bbox{position:fixed;box-sizing:border-box;width:0;height:0;border:calc(1.5px * var(--k, 1)) dashed var(--c);border-radius:calc(8px * var(--k, 1));
612
+ background:color-mix(in srgb,var(--c) 6%,transparent);overflow:hidden;
613
+ transition:width var(--d,340ms) cubic-bezier(.3,.7,.2,1),height var(--d,340ms) cubic-bezier(.3,.7,.2,1),opacity .3s ease,background .3s ease,border-color .3s ease}
614
+ .bbox::after{content:"";position:absolute;inset:0;transform:translateX(-100%);opacity:0;background:linear-gradient(90deg,transparent,color-mix(in srgb,var(--c) 22%,transparent),transparent)}
615
+ .bbox.fill{border-style:solid;border-color:color-mix(in srgb,var(--c) 42%,transparent);background:color-mix(in srgb,var(--c) 9%,transparent)}
616
+ .bbox.fill::after{opacity:1;animation:bshine 1.2s ease-in-out infinite}
617
+ .bbox b{position:absolute;left:calc(7px * var(--k, 1));top:calc(5px * var(--k, 1));opacity:0;transition:opacity .25s ease;
618
+ font:600 calc(10.5px * var(--k, 1))/1.45 -apple-system,BlinkMacSystemFont,"PingFang SC","Segoe UI","Microsoft YaHei",sans-serif;letter-spacing:.02em;color:var(--c);white-space:nowrap}
619
+ .bbox.fill b{opacity:1}
620
+ .bcur.flip span{left:auto;right:calc(100% - 4px * var(--k, 1));border-radius:calc(8px * var(--k, 1)) calc(4px * var(--k, 1)) calc(8px * var(--k, 1)) calc(8px * var(--k, 1))}
621
+ .bcur.up span{top:auto;bottom:calc(100% - 2px * var(--k, 1))}
622
+ @keyframes bshine{to{transform:translateX(100%)}}
623
+ .bcur{position:fixed;left:0;top:0;z-index:2;opacity:0;will-change:transform;transition:opacity .25s ease}
624
+ .bcur.on{opacity:1}
625
+ .bcur svg{display:block;width:calc(17px * var(--k, 1));height:calc(21px * var(--k, 1));overflow:visible;filter:drop-shadow(0 1px 2px rgba(0,0,0,.28))}
626
+ .bcur span{position:absolute;left:calc(13px * var(--k, 1));top:calc(17px * var(--k, 1));padding:calc(2px * var(--k, 1)) calc(7px * var(--k, 1));
627
+ border-radius:calc(4px * var(--k, 1)) calc(8px * var(--k, 1)) calc(8px * var(--k, 1)) calc(8px * var(--k, 1));background:var(--c);color:#fff;
628
+ font:600 calc(11px * var(--k, 1))/1.35 -apple-system,BlinkMacSystemFont,"PingFang SC","Segoe UI","Microsoft YaHei",sans-serif;white-space:nowrap;box-shadow:0 2px 6px rgba(0,0,0,.18)}
605
629
  `
606
630
  let fx = null
607
631
 
@@ -721,6 +745,211 @@
721
745
  setTimeout(() => { if (linkSig) resendLinks() }, DUR + 800) // 动画时按钮挪了一点,播完按最终位置补报
722
746
  }
723
747
 
748
+ // ── 生成动画 2:几只带名字的鼠标(排版 / 配色 / 文案)轮流把版面框出来,框里闪骨架,再由上往下显出整屏 ──
749
+ //
750
+ // 框的是页面里几大块的真实位置(这屏已经写好了,先量),所以动画和最后的画面对得上。
751
+ // 系统开了「减少动态效果」就直接显示;点一下、滚一下、按个键就跳过。播完不留任何东西。
752
+
753
+ const BUILD_TX = {
754
+ zh: { cur: ['排版', '配色', '文案'], top: '顶栏', bottom: '底栏', side: '侧栏', img: '图片', title: '标题', list: '列表', form: '表单', card: '卡片', block: '内容' },
755
+ en: { cur: ['Layout', 'Color', 'Copy'], top: 'Header', bottom: 'Footer', side: 'Sidebar', img: 'Image', title: 'Title', list: 'List', form: 'Form', card: 'Card', block: 'Section' },
756
+ }
757
+ const BUILD_C = ['#4d6bfe', '#e8590c', '#0ca678']
758
+ const ARROW = '<svg viewBox="0 0 17 21"><path d="M1.2 1.2v15.6l4.3-4 3 6.6 2.9-1.3-3-6.5h6z" fill="var(--c)" stroke="#fff" stroke-width="1.5" stroke-linejoin="round"/></svg>'
759
+ let building = null
760
+
761
+ /** 页面里几大块(视口里看得见的部分):外壳 div 一层层钻进去,太高的一块再拆一层,最多 7 块 */
762
+ function buildBlocks() {
763
+ const vw = innerWidth
764
+ const vh = innerHeight
765
+ const rectOf = (c) => {
766
+ if (SIG_SKIP.has(c.tagName)) return null
767
+ const r = c.getBoundingClientRect()
768
+ if (r.width < 8 || r.height < 8 || r.bottom <= 0 || r.top >= vh || r.right <= 0 || r.left >= vw) return null
769
+ const cs = getComputedStyle(c)
770
+ if (cs.visibility === 'hidden' || cs.display === 'contents' || Number(cs.opacity) === 0) return null
771
+ return r
772
+ }
773
+ const kidsOf = (el) => [...el.children].map((c) => ({ el: c, r: rectOf(c) })).filter((x) => x.r)
774
+ const seen = (r) => Math.max(0, Math.min(r.bottom, vh) - Math.max(r.top, 0)) * Math.max(0, Math.min(r.right, vw) - Math.max(r.left, 0))
775
+ let kids = document.body ? kidsOf(document.body) : []
776
+ for (let d = 0; kids.length === 1 && d < 8; d++) kids = kidsOf(kids[0].el)
777
+ const min = vw * vh * 0.012
778
+ const split = (k) => {
779
+ let sub = kidsOf(k.el)
780
+ for (let d = 0; sub.length === 1 && d < 6; d++) sub = kidsOf(sub[0].el)
781
+ return sub.filter((x) => seen(x.r) >= min)
782
+ }
783
+ // 太高的一块(整个内容区)往里拆,最多两层
784
+ const expand = (k, depth) => {
785
+ if (depth < 2 && k.r.height > vh * 0.55) {
786
+ const sub = split(k)
787
+ if (sub.length >= 2 && sub.length <= 6) return sub.flatMap((x) => expand(x, depth + 1))
788
+ }
789
+ return [k]
790
+ }
791
+ let out = kids.filter((k) => seen(k.r) >= min).flatMap((k) => expand(k, 0))
792
+ const box = (r) => ({ top: r.top, bottom: r.bottom, left: r.left, right: r.right })
793
+ for (const k of out) {
794
+ k.b = box(k.r)
795
+ const pos = getComputedStyle(k.el).position
796
+ k.fixed = pos === 'fixed' || pos === 'sticky'
797
+ }
798
+ // 浮在上面的条(购物车条、底部导航):底下那块的框截到它上面,免得两个框叠在一起
799
+ const wide = (a, b) => Math.max(0, Math.min(a.right, b.right) - Math.max(a.left, b.left)) > (a.right - a.left) * 0.6
800
+ for (const k of out) {
801
+ if (k.fixed) continue
802
+ for (const f of out) {
803
+ if (!f.fixed || f === k || !wide(k.b, f.b)) continue
804
+ if (f.b.top > k.b.top + vh * 0.1 && f.b.top < k.b.bottom) k.b.bottom = f.b.top - 6
805
+ else if (f.b.bottom < k.b.bottom - vh * 0.1 && f.b.bottom > k.b.top) k.b.top = f.b.bottom + 6
806
+ }
807
+ }
808
+ // 还叠着的(一层套一层)只留看得见更多的那个
809
+ const inter = (a, b) => Math.max(0, Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top)) * Math.max(0, Math.min(a.right, b.right) - Math.max(a.left, b.left))
810
+ out = out.filter((k) => k.b.bottom - k.b.top >= 12 && seen(k.b) >= min * 0.6)
811
+ out.sort((a, b) => seen(b.b) - seen(a.b))
812
+ out = out.filter((k, i) => !out.slice(0, i).some((o) => inter(k.b, o.b) > seen(k.b) * 0.5))
813
+ if (out.length > 7) out = out.slice(0, 7)
814
+ out.sort((a, b) => a.b.top - b.b.top || a.b.left - b.b.left)
815
+ const pad = 2
816
+ return out.map((k) => {
817
+ const x = Math.max(pad, k.b.left)
818
+ const y = Math.max(pad, k.b.top)
819
+ return { el: k.el, r: k.r, x, y, w: Math.max(12, Math.min(vw - pad, k.b.right) - x), h: Math.max(12, Math.min(vh - pad, k.b.bottom) - y) }
820
+ })
821
+ }
822
+
823
+ /** 这块大概是什么:顶栏 / 底栏 / 图片 / 表单 / 列表 / 标题 / 卡片 */
824
+ function blockName(el, r, N) {
825
+ const vh = innerHeight
826
+ const tag = el.tagName.toLowerCase()
827
+ const role = el.getAttribute('role') || ''
828
+ const low = r.top > vh * 0.6
829
+ if (tag === 'footer' || ((tag === 'nav' || role === 'tablist' || role === 'navigation') && low) || (r.bottom >= vh * 0.94 && r.height < vh * 0.16)) return N.bottom
830
+ if (tag === 'header' || tag === 'nav' || role === 'banner' || (r.top <= vh * 0.06 && r.height < vh * 0.16)) return N.top
831
+ if (el.querySelector('input:not([type=hidden]),textarea,select')) return N.form
832
+ let media = 0
833
+ for (const m of el.querySelectorAll('img,picture,video,canvas,svg')) {
834
+ const q = m.getBoundingClientRect()
835
+ if (q.width * q.height > 400) media += q.width * q.height
836
+ }
837
+ if (media > r.width * r.height * 0.45) return N.img
838
+ if (r.width < innerWidth * 0.36 && r.height > vh * 0.3) return N.side
839
+ const kids = [...el.children].filter((c) => c.getBoundingClientRect().height > 8)
840
+ const tags = new Map()
841
+ for (const c of kids) tags.set(c.tagName, (tags.get(c.tagName) || 0) + 1)
842
+ const most = Math.max(0, ...tags.values())
843
+ if (/^(ul|ol|table)$/.test(tag) || (kids.length >= 3 && kids.every((c) => Math.abs(c.getBoundingClientRect().height - kids[0].getBoundingClientRect().height) < 12)) ||
844
+ (most >= 3 && most >= kids.length * 0.6)) return N.list
845
+ if (el.matches('h1,h2,h3') || (el.querySelector('h1,h2') && r.height < vh * 0.3)) return N.title
846
+ return r.height > vh * 0.4 ? N.block : N.card
847
+ }
848
+
849
+ function pageBg() {
850
+ for (const el of [document.body, document.documentElement]) {
851
+ if (!el) continue
852
+ const c = getComputedStyle(el).backgroundColor
853
+ if (c && c !== 'transparent' && !/rgba\(.*,\s*0\)$/.test(c)) return c
854
+ }
855
+ return '#fff'
856
+ }
857
+
858
+ function build(lang) {
859
+ stopBuild()
860
+ if (!document.body || (window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches)) return
861
+ const blocks = buildBlocks()
862
+ if (!blocks.length) return buildIn()
863
+ const N = BUILD_TX[lang] || BUILD_TX.zh
864
+ const { root } = fxRoot()
865
+ const vw = innerWidth
866
+ const vh = innerHeight
867
+ const nodes = []
868
+ const timers = []
869
+ const at = (ms, f) => timers.push(setTimeout(f, ms))
870
+ const add = (el) => { root.append(el); nodes.push(el); return el }
871
+ const mask = add(document.createElement('div'))
872
+ mask.className = 'bmask'
873
+ mask.style.setProperty('--bg', pageBg())
874
+ // 三只鼠标从下面进来
875
+ const curs = BUILD_C.map((c, i) => {
876
+ const d = add(document.createElement('div'))
877
+ d.className = 'bcur'
878
+ d.style.setProperty('--c', c)
879
+ d.innerHTML = ARROW
880
+ const tag = document.createElement('span')
881
+ tag.textContent = N.cur[i]
882
+ d.append(tag)
883
+ d.style.transform = `translate(${vw * (0.3 + i * 0.2)}px, ${vh + 10}px)`
884
+ return { d, free: 0 }
885
+ })
886
+ const move = (cur, x, y, ms) => {
887
+ x = Math.min(x, vw - 4)
888
+ cur.d.classList.toggle('flip', x > vw - 84 * K)
889
+ cur.d.classList.toggle('up', y > vh - 40 * K && y <= vh)
890
+ cur.d.style.transition = `transform ${ms}ms cubic-bezier(.3,.7,.2,1), opacity .25s ease`
891
+ cur.d.style.transform = `translate(${x}px, ${y}px)`
892
+ }
893
+ at(16, () => curs.forEach((c) => c.d.classList.add('on')))
894
+ const MOVE = 260
895
+ const DRAG = 330
896
+ let end = 0
897
+ const boxes = blocks.map((b, i) => {
898
+ const cur = curs[i % curs.length]
899
+ const t0 = Math.max(80 + i * 170, cur.free)
900
+ cur.free = t0 + MOVE + DRAG + 60
901
+ end = Math.max(end, cur.free)
902
+ const box = add(document.createElement('div'))
903
+ box.className = 'bbox'
904
+ box.style.setProperty('--c', BUILD_C[i % BUILD_C.length])
905
+ box.style.setProperty('--d', DRAG + 'ms')
906
+ box.style.left = b.x + 'px'
907
+ box.style.top = b.y + 'px'
908
+ box.style.opacity = '0'
909
+ const label = document.createElement('b')
910
+ label.textContent = blockName(b.el, b.r, N)
911
+ box.append(label)
912
+ at(t0, () => move(cur, b.x, b.y, MOVE))
913
+ at(t0 + MOVE, () => {
914
+ box.style.opacity = '1'
915
+ box.style.width = b.w + 'px'
916
+ box.style.height = b.h + 'px'
917
+ move(cur, b.x + b.w, b.y + b.h, DRAG)
918
+ })
919
+ at(t0 + MOVE + DRAG, () => box.classList.add('fill'))
920
+ return { box, b }
921
+ })
922
+ // 框完了:停一下,再由上往下显出整屏(元素按从上到下浮现、扫描光带一起走),框跟着光带淡掉,鼠标散开
923
+ const SHOW = end + 220
924
+ const DUR = 950
925
+ at(SHOW, () => {
926
+ mask.style.setProperty('--dur', DUR + 'ms')
927
+ mask.classList.add('go')
928
+ for (const { box, b } of boxes) setTimeout(() => { box.style.opacity = '0' }, Math.round((Math.max(0, b.y) / vh) * DUR * 0.7))
929
+ curs.forEach((c, i) => { move(c, vw * (0.25 + i * 0.25), vh + 30, 520); setTimeout(() => c.d.classList.remove('on'), 260) })
930
+ buildIn()
931
+ })
932
+ const done = () => stopBuild()
933
+ at(SHOW + DUR + 380, done)
934
+ // 用户动了(点、滚、按键):直接跳过,别挡着
935
+ const skip = () => { if (building && !building.shown) done() }
936
+ addEventListener('pointerdown', skip, true)
937
+ addEventListener('wheel', skip, { capture: true, passive: true })
938
+ addEventListener('keydown', skip, true)
939
+ building = { nodes, timers, skip, shown: false }
940
+ at(SHOW, () => { if (building) building.shown = true })
941
+ }
942
+
943
+ function stopBuild() {
944
+ if (!building) return
945
+ for (const t of building.timers) clearTimeout(t)
946
+ for (const n of building.nodes) n.remove()
947
+ removeEventListener('pointerdown', building.skip, true)
948
+ removeEventListener('wheel', building.skip, { capture: true })
949
+ removeEventListener('keydown', building.skip, true)
950
+ building = null
951
+ }
952
+
724
953
  // 选中后留一个虚线框,直到下次选择 / 页面刷新
725
954
  let pinned = null
726
955
 
@@ -1262,6 +1491,36 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1262
1491
  post({ type: 'links', links })
1263
1492
  }
1264
1493
 
1494
+ if (STRICT) {
1495
+ const offsite = (raw) => {
1496
+ const v = String(raw || '').trim()
1497
+ if (!v || v.startsWith('#')) return ''
1498
+ let u
1499
+ try { u = new URL(v, here()) } catch { return v.slice(0, 200) }
1500
+ return u.origin === hereUrl().origin ? '' : u.href.slice(0, 200)
1501
+ }
1502
+ addEventListener('click', (e) => {
1503
+ const a = e.target && e.target.closest ? e.target.closest('a[href], area[href]') : null
1504
+ if (!a) return
1505
+ const dl = a.hasAttribute('download')
1506
+ const out = offsite(a.getAttribute('href'))
1507
+ // 下载、开新窗口沙盒本来就不让;站外的地址这里直接挡(带 download 的按「下载」报)
1508
+ if (!out && !dl) return
1509
+ e.preventDefault()
1510
+ e.stopImmediatePropagation()
1511
+ post({ type: 'blocked', href: dl ? 'download' : out })
1512
+ }, true)
1513
+ if (window.navigation && typeof navigation.addEventListener === 'function') {
1514
+ navigation.addEventListener('navigate', (e) => {
1515
+ if (!e.cancelable || e.navigationType === 'traverse') return
1516
+ const out = offsite(e.destination && e.destination.url)
1517
+ if (!out && !e.downloadRequest) return
1518
+ e.preventDefault()
1519
+ post({ type: 'blocked', href: out || 'download' })
1520
+ })
1521
+ }
1522
+ }
1523
+
1265
1524
  // 演示:点了跳页的地方,不在 iframe 里直接跳,告诉右侧栏换一屏(带过场动画)
1266
1525
  // 远程看也是:沙盒里的页面跳不过去(地址指着电脑本机),由右侧栏打包那一页换上来
1267
1526
  let demo = false
@@ -1310,7 +1569,7 @@ background:rgba(20,20,22,.86);color:#e8e8ea;font:12px/18px -apple-system,system-
1310
1569
  shown = true
1311
1570
  const c = pending
1312
1571
  pending = null
1313
- if (opts && opts.build) buildIn()
1572
+ if (opts && opts.build) build(opts.lang === 'en' ? 'en' : 'zh')
1314
1573
  else if (c && c.els.length) setTimeout(() => play(c.els), 60)
1315
1574
  watchHmr()
1316
1575
  }
package/lib/serve.js CHANGED
@@ -12,14 +12,24 @@
12
12
  * 每个 HTML 页面都注入 /__dsh_design__/picker.js:负责点选 / 框选,用 postMessage 和右侧栏通信。
13
13
  */
14
14
 
15
+ import crypto from 'node:crypto'
15
16
  import fs from 'node:fs'
16
17
  import http from 'node:http'
17
18
  import net from 'node:net'
18
19
  import path from 'node:path'
19
20
  import { fileURLToPath } from 'node:url'
21
+ import { tokenize } from './gallery/html.js'
20
22
 
21
23
  export const INTERNAL = '/__dsh_design__/'
22
24
  const PICKER_FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), 'picker.js')
25
+ const DRAFT_JS = path.join(path.dirname(fileURLToPath(import.meta.url)), 'draft-page.js')
26
+ // 草稿往外吐:模型一点点流的时候来多少吐多少(不拖后腿,右侧栏中途才来看也是先把写到的一口气给);
27
+ // 整页一下子到的(模型服务把参数憋到最后一块给:一块 DRAFT_LUMP 字以上、紧跟着就写完了,或者来看时已经写完、draft.js 记着是整段到的)才排队,
28
+ // 每 50ms 一截、约 60 拍(3 秒)放完,一截至少 100 字
29
+ const DRAFT_TICK = 50
30
+ const DRAFT_STEP = 100
31
+ const DRAFT_SPREAD = 60
32
+ const DRAFT_LUMP = 1500
23
33
  const MAX_SERVERS = 8
24
34
  const MAX_HTML = 8 * 1024 * 1024 // 要注入脚本的 HTML 最多读这么大
25
35
  const UP_HOSTS = ['127.0.0.1', '::1'] // 开发服务器可能只听其中一个
@@ -71,7 +81,7 @@ export function hostOk(host, port) {
71
81
  * picker 在 </body> 前,等它装上,前面脚本的报错早过去了
72
82
  */
73
83
  export const ERR_CATCHER = '<script>(()=>{if(window.__dshErrs)return;const L=window.__dshErrs=[];const add=(x)=>{if(L.length<30)L.push(x)};' +
74
- 'addEventListener("error",(e)=>{const t=e.target;if(t&&t!==window&&t.tagName){add({res:1,tag:t.tagName.toLowerCase(),src:String(t.currentSrc||t.src||t.href||"").slice(0,300)})}' +
84
+ 'addEventListener("error",(e)=>{const t=e.target;if(t&&t!==window&&t.tagName){const h=t.href;add({res:1,tag:t.tagName.toLowerCase(),src:String(t.currentSrc||t.src||(h&&typeof h.baseVal==="string"?h.baseVal:h)||"").slice(0,300)})}' +
75
85
  'else add({msg:String(e.message||"").slice(0,300),src:String(e.filename||"").slice(0,300),line:e.lineno||0})},true);' +
76
86
  'addEventListener("unhandledrejection",(e)=>{const r=e.reason;add({msg:String((r&&r.message)||r).slice(0,300),src:"",line:0})})})()</script>'
77
87
 
@@ -81,13 +91,72 @@ export function headInsert(html, tag) {
81
91
  return m ? html.slice(0, m.index + m[0].length) + tag + html.slice(m.index + m[0].length) : tag + html
82
92
  }
83
93
 
84
- /** 在 </body> 前(没有就在末尾)插入选取脚本,<head> 最前面放报错记录 */
85
- export function injectPicker(html) {
86
- const tag = `<script src="${INTERNAL}picker.js"></script>`
94
+ /**
95
+ * 在 </body> 前(没有就在末尾)插入选取脚本,<head> 最前面放报错记录。
96
+ * nonce:别人做的设计(设计库来的)加了「只准带这个记号的脚本跑」的规矩,我们自己的两段脚本带上它;data-strict 让 picker 拦外链
97
+ */
98
+ export function injectPicker(html, { nonce = '' } = {}) {
99
+ const n = nonce ? ` nonce="${nonce}"` : ''
100
+ const tag = `<script src="${INTERNAL}picker.js"${n}${nonce ? ' data-strict="1"' : ''}></script>`
87
101
  const i = html.toLowerCase().lastIndexOf('</body>')
88
- return headInsert(i >= 0 ? html.slice(0, i) + tag + html.slice(i) : html + tag, ERR_CATCHER)
102
+ return headInsert(i >= 0 ? html.slice(0, i) + tag + html.slice(i) : html + tag, nonce ? ERR_CATCHER.replace('<script>', `<script${n}>`) : ERR_CATCHER)
103
+ }
104
+
105
+ /**
106
+ * 别人做的设计(设计库市场来的、拖进来的 zip,且没被改过)预览时的硬规矩:
107
+ * 只有带 nonce 的脚本(我们注入的 picker)能跑;不联网(样式、图片、字体只能是自己这个预览地址或 data:);
108
+ * 表单交不出去;不能嵌别的页面、不能改 <base>
109
+ */
110
+ export function strictCsp(nonce) {
111
+ return [
112
+ "default-src 'none'",
113
+ `script-src 'nonce-${nonce}'`,
114
+ "style-src 'self' 'unsafe-inline'",
115
+ "img-src 'self' data: blob:",
116
+ "font-src 'self' data:",
117
+ "media-src 'self' data: blob:",
118
+ "connect-src 'self'",
119
+ "frame-src 'none'",
120
+ "child-src 'none'",
121
+ "worker-src 'none'",
122
+ "manifest-src 'none'",
123
+ "object-src 'none'",
124
+ "form-action 'none'",
125
+ "base-uri 'none'",
126
+ ].join('; ')
127
+ }
128
+
129
+ /** 硬规矩预览的其他响应头 */
130
+ export const STRICT_HEADERS = {
131
+ 'X-Content-Type-Options': 'nosniff',
132
+ 'Referrer-Policy': 'no-referrer',
133
+ 'X-DNS-Prefetch-Control': 'off',
134
+ 'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), clipboard-read=(), payment=(), usb=(), serial=(), hid=(), bluetooth=(), display-capture=()',
135
+ }
136
+ /**
137
+ * 硬规矩预览前再拆掉 CSP 管不到的几样:<meta http-equiv>(自动跳走)、<link rel="preconnect / dns-prefetch / prerender …">(偷偷连外网)、
138
+ * a[ping]。只改属性名(data-dsh-off-…),不改别的字。正常的设计库内容本来就没有这些(检查规则拒收),这里是兜底
139
+ */
140
+ export function defang(html) {
141
+ const edits = []
142
+ for (const tk of tokenize(html)) {
143
+ if (tk.type !== 'tag') continue
144
+ const t = tk.tag
145
+ for (const a of t.attrs) {
146
+ const off = (t.name === 'meta' && a.name === 'http-equiv')
147
+ || (t.name === 'link' && a.name === 'rel' && !/^\s*(stylesheet|icon|shortcut icon|apple-touch-icon)\s*$/i.test(a.value))
148
+ || a.name === 'ping'
149
+ if (off) edits.push(a.start)
150
+ }
151
+ }
152
+ let out = html
153
+ for (const at of edits.sort((a, b) => b - a)) out = out.slice(0, at) + 'data-dsh-off-' + out.slice(at)
154
+ return out
89
155
  }
90
156
 
157
+ // 别人做的 SVG 被当页面直接打开时:不准跑任何脚本
158
+ const STRICT_SVG_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:"
159
+
91
160
  /** 真实路径在不在根目录(也取真实路径)里面 */
92
161
  function inRoot(root, real) {
93
162
  const realRoot = fs.realpathSync(root)
@@ -99,7 +168,10 @@ export function resolveInRoot(root, pathname) {
99
168
  let rel
100
169
  try { rel = decodeURIComponent(pathname) } catch { return null }
101
170
  if (rel.includes('\0')) return null
171
+ if (path.sep === '\\') rel = rel.replace(/\\/g, '/') // Windows:反斜杠也是分隔符,先换成 / 再去掉 ..(不然 ..\ 绕得出去)
102
172
  const abs = path.resolve(root, '.' + path.posix.normalize('/' + rel))
173
+ const base = path.resolve(root)
174
+ if (abs !== base && !abs.startsWith(base + path.sep)) return null // 文件还不存在(正在写的草稿)也不许出根目录
103
175
  let real
104
176
  try { real = fs.realpathSync(abs) } catch { return { abs, real: null } }
105
177
  if (!inRoot(root, real)) return null
@@ -161,8 +233,91 @@ export function trustedOrigins(hosts) {
161
233
  * @param opts.onChange (key, file, files) 目录里有文件改了(file 目标;files:这一批的相对路径)
162
234
  * @param opts.history 设计版本(lib/history.js):/__dsh_design__/v/<版本>/<文件> 给出那一版的文件
163
235
  * @param opts.parents () → 还有哪些 DSH 页面的源能嵌预览(DSH 网页端的地址)
236
+ * @param opts.strict { html(buf) → 这份 HTML 是别人做的、没改过吗, root(dir) → 这个目录是别人做的设计吗 }:是就加硬规矩
164
237
  */
165
- export function createHub({ log = () => {}, onChange = () => {}, history = null, parents = () => [] } = {}) {
238
+ /**
239
+ * 草稿页往外吐的时候,在 doctype 后面插上草稿脚本(插在 doctype 前面会进怪异模式)。
240
+ * 开头可能被切成好几块:攒到能判断为止。
241
+ */
242
+ export function draftInjector(tag) {
243
+ const LIMIT = 4096
244
+ let buf = ''
245
+ let done = false
246
+ let mid = false // 开头的注释太长:已经先吐出去一截,buf 接着在注释里面
247
+ let open = false // 看到 buf 末尾时还在一段没收尾的注释里
248
+ return {
249
+ push(text) {
250
+ if (done) return text
251
+ buf += text
252
+ let out = ''
253
+ let inCmt = mid
254
+ let i = inCmt ? 0 : /^\uFEFF?\s*/.exec(buf)[0].length // buf[0, i) 看过了:空白、完整的注释
255
+ const at = (k) => {
256
+ done = true
257
+ const s = out + buf.slice(0, k) + tag + buf.slice(k)
258
+ buf = ''
259
+ return s
260
+ }
261
+ // 还得等:攒太多了就先把看过的(注释里的也行,留两个字防 --> 被切开)吐出去,接着等 doctype
262
+ const hold = () => {
263
+ open = inCmt
264
+ if (buf.length <= LIMIT) return out
265
+ const k = inCmt ? Math.max(i, buf.length - 2) : i
266
+ out += buf.slice(0, k)
267
+ buf = buf.slice(k)
268
+ mid = inCmt
269
+ return out
270
+ }
271
+ // 开头的注释跳过去(<!-- license --> 后面才是 doctype);doctype 后面插,没有 doctype 就插在注释后面
272
+ for (;;) {
273
+ if (inCmt) {
274
+ const e = buf.indexOf('-->', i)
275
+ if (e < 0) return hold()
276
+ inCmt = false
277
+ i = e + 3
278
+ i += /^\s*/.exec(buf.slice(i))[0].length
279
+ continue
280
+ }
281
+ const rest = buf.slice(i)
282
+ if (!rest) return hold()
283
+ if (rest.startsWith('<!--')) {
284
+ inCmt = true
285
+ i += 4
286
+ continue
287
+ }
288
+ if (rest.length < 9 && ('<!doctype'.startsWith(rest.toLowerCase()) || '<!--'.startsWith(rest))) return hold() // 还没到全
289
+ if (/^<!doctype/i.test(rest)) {
290
+ const e = buf.indexOf('>', i)
291
+ if (e >= 0) return at(e + 1)
292
+ return rest.length > LIMIT ? at(i) : hold() // 这么长还没完:不像 doctype,不等了
293
+ }
294
+ return at(i)
295
+ }
296
+ },
297
+ flush() {
298
+ if (done) return ''
299
+ done = true
300
+ // 停在一段没写完的注释里:先把注释收上,脚本才会跑
301
+ const out = open ? buf + '-->' + tag : mid ? buf + tag : tag + buf
302
+ buf = ''
303
+ return out
304
+ },
305
+ }
306
+ }
307
+
308
+ export function createHub({ log = () => {}, onChange = () => {}, history = null, parents = () => [], strict = null, drafts = null } = {}) {
309
+ const strictHtml = (buf) => { try { return !!(strict && strict.html && strict.html(buf)) } catch (e) { log(e); return true } }
310
+ const strictRoot = (dir) => { try { return !!(strict && strict.root && strict.root(dir)) } catch (e) { log(e); return true } }
311
+ const strictVer = (dir) => { try { return !!(strict && strict.versions && strict.versions(dir)) } catch (e) { log(e); return true } }
312
+
313
+ /** 发一份 HTML:别人做的加硬规矩(CSP + nonce),我们的脚本照常注入 */
314
+ function sendHtml(res, req, buf, type, force = false) {
315
+ if (force || strictHtml(buf)) {
316
+ const nonce = crypto.randomBytes(16).toString('base64')
317
+ return send(res, 200, req.method === 'HEAD' ? '' : injectPicker(defang(buf.toString('utf8')), { nonce }), { 'Content-Type': type, 'Content-Security-Policy': strictCsp(nonce), ...STRICT_HEADERS })
318
+ }
319
+ send(res, 200, req.method === 'HEAD' ? '' : injectPicker(buf.toString('utf8')), { 'Content-Type': type })
320
+ }
166
321
  const servers = new Map() // key → entry
167
322
 
168
323
  function touch(entry) {
@@ -183,6 +338,97 @@ export function createHub({ log = () => {}, onChange = () => {}, history = null,
183
338
  return [...new Set([DESKTOP_ORIGIN, ...more.filter((o) => typeof o === 'string' && o)])]
184
339
  }
185
340
 
341
+ function draftJs(res) {
342
+ fs.readFile(DRAFT_JS, 'utf8', (err, src) => {
343
+ if (err) return send(res, 500, 'draft script missing')
344
+ send(res, 200, src, { 'Content-Type': MIME['.js'] })
345
+ })
346
+ }
347
+
348
+ /** 正在写的那一页(地址带 ?__ddp_draft=):先吐出已经写到的,之后来一截吐一截,写完收尾(浏览器边收边画) */
349
+ function serveDraft(req, res, entry, pathname) {
350
+ if (entry.kind !== 'file' || !drafts || strictRoot(entry.root)) return send(res, 404, 'not found')
351
+ if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, 'method not allowed')
352
+ const hit = resolveInRoot(entry.root, pathname)
353
+ if (!hit) return send(res, 403, 'forbidden')
354
+ let want = ''
355
+ try { want = new URL(req.url, 'http://x').searchParams.get('__ddp_draft') || '' } catch { /* route 里已经验过 */ }
356
+ const got = drafts.get(hit.abs)
357
+ // 地址里的编号对得上才给:同一个文件又开始重写(别的会话、或下一次写)时,旧框子拿到的是真文件,不串到新的那份
358
+ const d = got && String(got.id) === want ? got : null
359
+ if (!d) return serveFile(req, res, entry, pathname) // 已经写完收走了:给真文件
360
+ res.writeHead(200, { 'Content-Type': MIME['.html'], 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' })
361
+ if (req.method === 'HEAD') return res.end()
362
+ const inj = draftInjector(`<script src="${INTERNAL}draft.js"></script>`)
363
+ let off = () => {}
364
+ let ended = false
365
+ // 一大段一下子到:排着队一截截放,看着还是一段段长出来的;<head> 里的样式看不见,一口气给。
366
+ // step 是 0 = 没在排队,来多少吐多少
367
+ const q = { buf: '', body: false, src: false, timer: null, step: 0, big: false }
368
+ const spread = (len) => Math.max(DRAFT_STEP, Math.ceil(len / DRAFT_SPREAD))
369
+ const stop = () => {
370
+ ended = true
371
+ clearTimeout(q.timer)
372
+ off()
373
+ }
374
+ const pump = () => {
375
+ q.timer = null
376
+ if (ended) return
377
+ if (q.big) {
378
+ q.big = false
379
+ if (q.src) q.step = Math.max(q.step, spread(q.buf.length)) // 一大块到了紧跟着就写完了:整页憋到最后给的,慢放
380
+ }
381
+ let n = q.buf.length
382
+ if (!q.body) {
383
+ const m = /<body\b[^>]*>/i.exec(q.buf) || /<\/head\s*>/i.exec(q.buf)
384
+ if (m) {
385
+ q.body = true
386
+ n = m.index + m[0].length
387
+ if (q.step) q.step = spread(q.buf.length - n) // 剩下的正文按原来的时长放
388
+ } else if (q.src) q.body = true // 写完了也没找到 <body>:整页都按拍子放
389
+ }
390
+ if (q.body && q.step && n === q.buf.length) n = Math.min(n, q.step)
391
+ if (n < q.buf.length && /[\ud800-\udbff]/.test(q.buf[n - 1] || '')) n++ // 别把表情切成两半
392
+ const s = inj.push(q.buf.slice(0, n))
393
+ q.buf = q.buf.slice(n)
394
+ try { if (s) res.write(s) } catch (e) { log(e) }
395
+ if (q.buf) q.timer = setTimeout(pump, DRAFT_TICK)
396
+ else if (!q.src) q.step = 0 // 放完了:之后又是一点点流的,来多少吐多少
397
+ else {
398
+ stop()
399
+ try { res.end(inj.flush()) } catch (e) { log(e) }
400
+ }
401
+ }
402
+ // how:'lump' 慢放;'now' 一口气给;不填 = 流过来的一块,一大块的话等这一下过完看是不是紧跟着就写完了
403
+ const out = (text, how) => {
404
+ if (ended) return
405
+ if (text) {
406
+ q.buf += text
407
+ if (how === 'lump') q.step = Math.max(q.step, spread(q.buf.length))
408
+ else if (!how && text.length >= DRAFT_LUMP) q.big = true
409
+ }
410
+ if (q.big) {
411
+ if (!q.timer) q.timer = setTimeout(pump, 0)
412
+ return
413
+ }
414
+ if (!q.timer) pump()
415
+ }
416
+ const finish = () => {
417
+ q.src = true
418
+ out('')
419
+ }
420
+ off = drafts.sub(hit.abs, (ev) => {
421
+ if (ev.text) out(ev.text)
422
+ if (ev.done) finish()
423
+ })
424
+ res.on('close', stop)
425
+ res.on('error', stop)
426
+ // 来看时已经写到的:整段一下子到、已经写完的补放一遍;别的(还在写,或一路流着写完、右侧栏换了个框重新打开的)一口气给
427
+ if (d.done) q.src = true // 先记下已经写完(找不到 <body> 的页面靠它整页按拍子放)
428
+ out(d.text, d.done && d.lump ? 'lump' : 'now')
429
+ if (d.done) finish()
430
+ }
431
+
186
432
  function picker(res, entry) {
187
433
  fs.readFile(PICKER_FILE, 'utf8', (err, src) => {
188
434
  if (err) return send(res, 500, 'picker missing')
@@ -213,14 +459,15 @@ export function createHub({ log = () => {}, onChange = () => {}, history = null,
213
459
  const ext = path.extname(file).toLowerCase()
214
460
  const type = MIME[ext] || 'application/octet-stream'
215
461
  if (ext === '.html' || ext === '.htm') {
216
- fs.readFile(file, 'utf8', (err, html) => {
462
+ fs.readFile(file, (err, buf) => {
217
463
  if (err) return send(res, 500, '读不了这个文件')
218
- send(res, 200, req.method === 'HEAD' ? '' : injectPicker(html), { 'Content-Type': type })
464
+ sendHtml(res, req, buf, type)
219
465
  })
220
466
  return
221
467
  }
222
468
  // 别的源不能把这里的文件当子资源拿走
223
- res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-store', 'Cross-Origin-Resource-Policy': 'same-origin' })
469
+ const extra = strictRoot(entry.root) ? { 'X-Content-Type-Options': 'nosniff', ...(ext === '.svg' ? { 'Content-Security-Policy': STRICT_SVG_CSP } : {}) } : {}
470
+ res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-store', 'Cross-Origin-Resource-Policy': 'same-origin', ...extra })
224
471
  if (req.method === 'HEAD') return res.end()
225
472
  const stream = fs.createReadStream(file)
226
473
  stream.on('error', () => res.destroy())
@@ -238,8 +485,10 @@ export function createHub({ log = () => {}, onChange = () => {}, history = null,
238
485
  const type = MIME[ext] || 'application/octet-stream'
239
486
  fs.readFile(file, (err, buf) => {
240
487
  if (err) return send(res, 404, 'no such version file')
241
- if (ext === '.html' || ext === '.htm') return send(res, 200, req.method === 'HEAD' ? '' : injectPicker(buf.toString('utf8')), { 'Content-Type': type })
242
- res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-store', 'Cross-Origin-Resource-Policy': 'same-origin' })
488
+ // 装好的别人的设计系统:旧版本里的页面一律加规矩
489
+ if (ext === '.html' || ext === '.htm') return sendHtml(res, req, buf, type, strictVer(entry.root))
490
+ const extra = strictRoot(entry.root) ? { 'X-Content-Type-Options': 'nosniff', ...(ext === '.svg' ? { 'Content-Security-Policy': STRICT_SVG_CSP } : {}) } : {}
491
+ res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-store', 'Cross-Origin-Resource-Policy': 'same-origin', ...extra })
243
492
  res.end(req.method === 'HEAD' ? undefined : buf)
244
493
  })
245
494
  }
@@ -427,6 +676,9 @@ export function createHub({ log = () => {}, onChange = () => {}, history = null,
427
676
  let pathname
428
677
  try { pathname = new URL(req.url, 'http://x').pathname } catch { return send(res, 400, 'bad url') }
429
678
  if (pathname === INTERNAL + 'picker.js') return picker(res, entry)
679
+ if (pathname === INTERNAL + 'draft.js') return draftJs(res)
680
+ // 草稿就挂在这一屏自己的地址上(/menu.html?__ddp_draft=…),页面里的相对地址(tokens.css、图片)照常对得上
681
+ if (entry.kind === 'file' && /[?&]__ddp_draft=/.test(req.url)) return serveDraft(req, res, entry, pathname)
430
682
  if (pathname === INTERNAL + 'events') {
431
683
  if (entry.kind === 'file') return events(req, res, entry)
432
684
  return send(res, 204, '')
@@ -457,6 +709,7 @@ export function createHub({ log = () => {}, onChange = () => {}, history = null,
457
709
  if (have) {
458
710
  touch(have)
459
711
  await have.ready
712
+ if (have.kind === 'file' && !have.watcher) watch(have) // 先开的时候目录还没建(边写边看的第一屏):现在补上监听
460
713
  return { key, origin: have.origin }
461
714
  }
462
715
  evict()