dsh-design-studio 1.3.0 → 1.4.1
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/README.en.md +1 -0
- package/README.md +1 -0
- package/lib/bundle.js +13 -8
- package/lib/canvthumb.js +2 -2
- package/lib/client.js +109 -34
- package/lib/comp-io.js +248 -0
- package/lib/components.js +716 -0
- package/lib/core.js +31 -8
- package/lib/draft-page.js +2 -1
- package/lib/gallery/routes.js +15 -1
- package/lib/handoff.js +297 -62
- package/lib/history.js +6 -1
- package/lib/htmlpack.js +110 -4
- package/lib/index.js +164 -38
- package/lib/picker.js +23 -5
- package/lib/serve.js +64 -11
- package/lib/tunnel.js +65 -30
- package/package.json +1 -1
- package/skills/ui-design/SKILL.md +15 -1
- package/skills/ui-design/references/components.md +123 -0
package/lib/htmlpack.js
CHANGED
|
@@ -18,6 +18,8 @@ import { followsMock, statesOfHtml } from './states.js'
|
|
|
18
18
|
import { MOCK_FILE, mockExpr, mockOfBuf, mockRuntime } from './mock.js'
|
|
19
19
|
|
|
20
20
|
/** 每屏的 <base>:一个不存在的地址(.invalid 不会被解析),屏里的相对链接都落在它下面,小脚本据此认出「站内跳转」 */
|
|
21
|
+
import { expandFormal, compError } from './comp-io.js'
|
|
22
|
+
|
|
21
23
|
export const PACK_ORIGIN = 'https://ddp-pack.invalid'
|
|
22
24
|
export const PACK_MAX = 150 * 1024 * 1024 // 整个文件的上限(字符数):再大浏览器打开就很慢了
|
|
23
25
|
export const PACK_SCREENS = 1000 // 画布只显示 60 屏,导出要全部(#29:有人的设计 400 多屏);真正拦的是 PACK_MAX
|
|
@@ -723,13 +725,90 @@ function tweakFonts(ids, libFont) {
|
|
|
723
725
|
return out
|
|
724
726
|
}
|
|
725
727
|
|
|
728
|
+
/**
|
|
729
|
+
* 展开后的页面里 data-mock-attr 绑到 src / srcset / poster 的数据路径(照 dataAssets 的写法:acts[*].cover、photos[*]、profile.cover)。
|
|
730
|
+
* 列表别名还原成列表路径(data-mock-each="a in acts" → a.cover 是 acts[*].cover),["x"] 当 .x,数字和下标变量当 [*]
|
|
731
|
+
*/
|
|
732
|
+
function srcPaths(html) {
|
|
733
|
+
const dec = (v) => v.replace(/"/g, '"').replace(/�*39;|'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&')
|
|
734
|
+
// 注释掉的不算;脚本、样式里的 < 别当成标签
|
|
735
|
+
const text = String(html).replace(/<!--[\s\S]*?(?:-->|$)/g, '').replace(/<(script|style)\b(?:"[^"]*"|'[^']*'|[^'">])*>[\s\S]*?<\/\1\s*>/gi, '')
|
|
736
|
+
const ID = '[\\p{L}_$][\\p{L}\\p{N}_$]*' // 字段名、别名可以是中文
|
|
737
|
+
const EACH = new RegExp(`^\\s*(${ID})\\s*(?:,\\s*(${ID})\\s*)?\\s+in\\s+([\\s\\S]+?)\\s*$`, 'u')
|
|
738
|
+
const PATH = new RegExp(`${ID}(?:\\s*(?:\\.\\s*${ID}|\\[\\s*(?:\\d+|"[^"]*"|'[^']*'|${ID})\\s*\\]))*`, 'gu')
|
|
739
|
+
const VOID = /^(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/i
|
|
740
|
+
const TAG = /<(\/?)([A-Za-z][\w:.-]*)((?:"[^"]*"|'[^']*'|[^'">])*)>/g
|
|
741
|
+
const ATTR = /([^\s"'>\/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g
|
|
742
|
+
// 按位置找:每个 data-mock-each 的别名管它直属 <template> 的内容;别名在最里层那个列表里找
|
|
743
|
+
const eaches = [] // { start(each 元素在哪,列表表达式按它外面那层算), inner, end(模板内容的范围), alias, idx, list }
|
|
744
|
+
const binds = [] // { at, value }
|
|
745
|
+
const stack = []
|
|
746
|
+
for (const m of text.matchAll(TAG)) {
|
|
747
|
+
const name = m[2].toLowerCase()
|
|
748
|
+
if (m[1]) {
|
|
749
|
+
const i = stack.findLastIndex((s) => s.name === name)
|
|
750
|
+
if (i >= 0) for (const s of stack.splice(i)) if (s.scope) s.scope.end = m.index
|
|
751
|
+
continue
|
|
752
|
+
}
|
|
753
|
+
// 列表别名只在它直属的 <template> 里管用(预览只把模板内容按每一项克隆;<template> 外面的兄弟元素用外层数据)
|
|
754
|
+
const top = stack[stack.length - 1]
|
|
755
|
+
let scope = null
|
|
756
|
+
let inert = false
|
|
757
|
+
if (name === 'template' && top && top.each && !top.each.used) {
|
|
758
|
+
top.each.used = true
|
|
759
|
+
scope = { ...top.each, inner: m.index + m[0].length, end: text.length }
|
|
760
|
+
eaches.push(scope)
|
|
761
|
+
} else if (name === 'template') inert = true // 别的 <template>(列表里的备用模板等)不显示,里面绑的图不算
|
|
762
|
+
let each = null
|
|
763
|
+
for (const a of m[3].matchAll(ATTR)) {
|
|
764
|
+
const k = a[1].toLowerCase()
|
|
765
|
+
const v = dec(a[2] ?? a[3] ?? a[4] ?? '')
|
|
766
|
+
if (k === 'data-mock-each') { const e = EACH.exec(v); if (e) each = { start: m.index, alias: e[1], idx: e[2] || null, list: e[3] } }
|
|
767
|
+
else if (k === 'data-mock-attr' && !stack.some((x) => x.inert)) binds.push({ at: m.index, value: v })
|
|
768
|
+
}
|
|
769
|
+
if (!VOID.test(name) && !/\/\s*$/.test(m[3])) stack.push({ name, each, scope, inert })
|
|
770
|
+
}
|
|
771
|
+
const scopeOf = (head, at) => {
|
|
772
|
+
let best = null
|
|
773
|
+
for (const e of eaches) if (e.inner <= at && at < e.end && (e.alias === head || e.idx === head) && (!best || e.start > best.start)) best = e
|
|
774
|
+
return best
|
|
775
|
+
}
|
|
776
|
+
// 一个路径表达式 → 数据里的完整路径:别名还原成「列表[*]」,["键"] → .键(键里的空格留着),[0] 留着,变量下标 → [*]
|
|
777
|
+
const norm = (expr, at, depth) => {
|
|
778
|
+
if (depth > 8) return ''
|
|
779
|
+
const head = new RegExp(`^${ID}`, 'u').exec(expr)[0]
|
|
780
|
+
if (/^(?:null|undefined|true|false|NaN|Infinity)$/.test(head)) return ''
|
|
781
|
+
const SEG = new RegExp(`\\s*(?:\\.\\s*(${ID})|\\[\\s*(?:"([^"]*)"|'([^']*)'|(\\d+)|${ID})\\s*\\])`, 'uy')
|
|
782
|
+
SEG.lastIndex = head.length
|
|
783
|
+
let rest = ''
|
|
784
|
+
for (let m; (m = SEG.exec(expr));) rest += m[1] != null ? '.' + m[1] : (m[2] ?? m[3]) != null ? '.' + (m[2] ?? m[3]) : m[4] != null ? `[${+m[4]}]` : '[*]'
|
|
785
|
+
const e = scopeOf(head, at)
|
|
786
|
+
if (!e) return head + rest
|
|
787
|
+
if (e.idx === head && e.alias !== head) return '' // 下标别名:是个数字
|
|
788
|
+
const lm = String(e.list).match(PATH)
|
|
789
|
+
const b = lm ? norm(lm[0], e.start, depth + 1) : '' // 列表表达式按 each 元素外面那层算
|
|
790
|
+
return b ? b + '[*]' + rest : ''
|
|
791
|
+
}
|
|
792
|
+
const out = new Set()
|
|
793
|
+
for (const { at, value } of binds) {
|
|
794
|
+
for (const part of value.split(';')) {
|
|
795
|
+
const b = /^\s*(?:src|srcset|poster)\s*:\s*([\s\S]*)$/i.exec(part)
|
|
796
|
+
if (!b) continue
|
|
797
|
+
// 单独的字符串('' 之类)不是路径;["键"] 整段留着(连着几个也不拆)
|
|
798
|
+
const expr = b[1].replace(/\[\s*(?:"[^"]*"|'[^']*')\s*\]|(['"])(?:\\.|(?!\1)[^\\])*\1/g, (s, q) => (q ? '' : s))
|
|
799
|
+
for (const p of expr.match(PATH) || []) { const n = norm(p, at, 0); if (n) out.add(n) }
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
return out
|
|
803
|
+
}
|
|
804
|
+
|
|
726
805
|
/**
|
|
727
806
|
* 打一份演示包。
|
|
728
807
|
* screens:[{ key, label, top }](top:顶栏是深色,外壳上的胶囊 / 窗口按钮画白的)
|
|
729
808
|
* dark:右侧栏开着「深色」;scheme:右侧栏当时的系统深浅色('dark' / 'light'),没开「深色」时页面按它显示
|
|
730
809
|
* read(rel):设计目录里的文件(Buffer,读不到 null);strictOf(page):这屏是不是别人做的(加硬规矩:只跑我们的脚本)
|
|
731
810
|
* libFont(id):外观面板里选了还没存的字体库字体 → { family, weights, data }
|
|
732
|
-
* 回 { html, missing: [没读到的屏], count, skipped: [有、但太大没放进去的文件] }
|
|
811
|
+
* 回 { html, missing: [没读到的屏], count, skipped: [有、但太大没放进去的文件], gone: [mock.json 里写了、文件却没有的图] }
|
|
733
812
|
*/
|
|
734
813
|
export function buildPack({ screens, read, bigOf = null, strictOf = () => false, kind, w, h, os = '', dark = false, scheme = 'light', tweak = null, title = '', lang = 'zh', fit = false, libFont = () => null }) {
|
|
735
814
|
kind = FRAME[kind] ? kind : 'web'
|
|
@@ -753,7 +832,9 @@ export function buildPack({ screens, read, bigOf = null, strictOf = () => false,
|
|
|
753
832
|
const mockSrc = mk ? `(${mockRuntime})(${mockExpr},${JSON.stringify({ v: mk.fp, scope: mockScope, err: mk.err })},${mockMark},${mockAMark});` : ''
|
|
754
833
|
// 数据里写的本地图片(头像、商品图):演示是单个文件,没有设计目录可读——换成 data: 地址的表,整套只放一份
|
|
755
834
|
const mockOver = []
|
|
756
|
-
const
|
|
835
|
+
const mockGone = [] // 数据里写了、文件没有的图 { rel, keys }:组件绑到 src 的整份不出(下面),其余照样导出、结果里列出来
|
|
836
|
+
const bound = new Map() // 用了组件的屏里绑到 src 的数据路径 → [屏]
|
|
837
|
+
const mockAssets = mk ? dataAssets(mk.data, read, 60 * 1024 * 1024, mockOver, bigOf, mockGone) : null
|
|
757
838
|
if (mockOver.length) { const e = new Error('imgTooBig'); e.code = 'imgTooBig'; throw e } // 数据里绑的图换不下:不悄悄留成坏图
|
|
758
839
|
const mode = dark ? 'dark' : scheme === 'dark' ? 'media' : 'light'
|
|
759
840
|
const schemeSrc = `(${schemeScript})(${JSON.stringify(mode)});`
|
|
@@ -765,12 +846,24 @@ export function buildPack({ screens, read, bigOf = null, strictOf = () => false,
|
|
|
765
846
|
const missing = []
|
|
766
847
|
const skipped = new Set() // 有、但太大放不进去的文件(单个超过 12 MB、一屏加起来超过 SCREEN_MAX):导出照样出,但要告诉用户缺了哪些
|
|
767
848
|
const readPage = (rel) => { const b = read(rel); if (!b && bigOf && bigOf(rel)) skipped.add(rel); return b }
|
|
849
|
+
if (read.hasCompDir) readPage.hasCompDir = read.hasCompDir
|
|
768
850
|
let total = mk ? JSON.stringify(mk.data).length + JSON.stringify(mockAssets).length : 0
|
|
851
|
+
const compBad = [] // 组件有错的屏(#30)
|
|
769
852
|
for (const s of screens.slice(0, PACK_SCREENS)) {
|
|
770
853
|
const page = read(s.key)
|
|
771
854
|
if (!page) { missing.push(s.key); continue }
|
|
772
855
|
const strict = !!strictOf(page)
|
|
773
|
-
|
|
856
|
+
// 组件(#30):先展开;有错就整份不出(攒齐哪几屏有错,最后抛 compErr),不出带红框或缺块的演示
|
|
857
|
+
let text
|
|
858
|
+
try {
|
|
859
|
+
const ex = expandFormal(page.toString('utf8').replace(/^/, ''), readPage, s.key)
|
|
860
|
+
text = ex.html
|
|
861
|
+
if (ex.comp && mockGone.length) for (const k of srcPaths(text)) { if (!bound.has(k)) bound.set(k, []); bound.get(k).push(s.key) }
|
|
862
|
+
} catch (e) {
|
|
863
|
+
if (e.code !== 'compErr') throw e
|
|
864
|
+
compBad.push(...e.pages)
|
|
865
|
+
continue
|
|
866
|
+
}
|
|
774
867
|
const base = PACK_ORIGIN + '/' + s.key.split('/').map(encodeURIComponent).join('/')
|
|
775
868
|
let out = bundle(strict ? defang(text) : text, {
|
|
776
869
|
key: s.key,
|
|
@@ -794,6 +887,19 @@ export function buildPack({ screens, read, bigOf = null, strictOf = () => false,
|
|
|
794
887
|
const states = statesOfHtml(text).map((x) => x.name) // 这屏写了哪几个状态(#30):放这屏时只设写了的
|
|
795
888
|
list.push({ key: s.key, label: String(s.label || s.key).slice(0, 80), top: !!s.top, ...(strict ? { strict: true } : null), ...(states.length ? { states } : null), ...(states.length && mk && followsMock(text) ? { follow: true } : null) })
|
|
796
889
|
}
|
|
890
|
+
if (compBad.length) throw compError(compBad)
|
|
891
|
+
// 组件绑到 src 的图(:cover 这类)在设计目录里没有:整份不出,说哪张图、哪个字段、哪几屏(方案:正式导出不出坏图)
|
|
892
|
+
// 绑定路径里的 [*](列表别名、变量下标)对上任何下标;写死的 [0] 只对 [0]
|
|
893
|
+
const keys = [...bound.keys()].map((k) => ({ k, re: new RegExp('^' + k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\\\[\\\*\\\]/g, '\\[\\d+\\]') + '$') }))
|
|
894
|
+
const keyOf = (p) => (keys.find((x) => x.re.test(p)) || {}).k
|
|
895
|
+
const imgBad = mockGone.map((g) => ({ ...g, hits: g.paths.map((p) => [p, keyOf(p)]).filter((h) => h[1]) })).filter((g) => g.hits.length)
|
|
896
|
+
if (imgBad.length) {
|
|
897
|
+
const at = (g) => `${g.rel}(mock 里的 ${g.hits[0][0]},用在 ${[...new Set(bound.get(g.hits[0][1]))].slice(0, 3).join('、')})`
|
|
898
|
+
const e = new Error(`组件绑的图在设计目录里找不到:${imgBad.slice(0, 3).map(at).join(';')}${imgBad.length > 3 ? ` 等 ${imgBad.length} 张` : ''}`)
|
|
899
|
+
e.code = 'imgMissing'
|
|
900
|
+
e.files = imgBad.map((g) => g.rel)
|
|
901
|
+
throw e
|
|
902
|
+
}
|
|
797
903
|
if (!list.length) { const e = new Error('noScreens'); e.code = 'noScreens'; throw e }
|
|
798
904
|
|
|
799
905
|
const f = frameOf(kind, w, h)
|
|
@@ -824,5 +930,5 @@ export function buildPack({ screens, read, bigOf = null, strictOf = () => false,
|
|
|
824
930
|
+ assets.map((a, i) => `<script type="application/json" id="ddp-a-${i}">${jsonTag(a)}</script>`).join('')
|
|
825
931
|
+ `<script>(${player})()</script>`
|
|
826
932
|
+ '</body></html>\n'
|
|
827
|
-
return { html, missing, count: list.length, skipped: [...skipped] }
|
|
933
|
+
return { html, missing, count: list.length, skipped: [...skipped], gone: mockGone.map((g) => g.rel) }
|
|
828
934
|
}
|
package/lib/index.js
CHANGED
|
@@ -77,11 +77,12 @@ import { readTweaks, applyTweaks, lintTweaks, syncFonts, lintFonts, libFontsUsed
|
|
|
77
77
|
import { createFonts, loadFontIndex, loadFontPreviews, libFontOf, findFont, stackOf, syncFontBlock, fontBlockIds, fontPrefix, libFontIdOf, FONT_DIR } from './fonts.js'
|
|
78
78
|
import { readAnnotations, lintAnnotations, annotationFindings, annotationSection } from './annotations.js'
|
|
79
79
|
import { createImpl } from './impl.js'
|
|
80
|
-
import { FRAMEWORKS, detectProject, projectFor, defaultFramework, buildHandoff, compareScreens, implUrl, implServe, defaultDest, pickedDest, within, pinRoots, frameCss } from './handoff.js'
|
|
80
|
+
import { FRAMEWORKS, detectProject, projectFor, defaultFramework, HANDOFF_BATCH_SIZE, handoffScreens, findHandoffScreen, handoffBatch, buildHandoff, compareScreens, implUrl, implServe, defaultDest, pickedDest, within, pinRoots, frameCss } from './handoff.js'
|
|
81
81
|
import { editsNotice, noticeMessage, langOf } from './edits.js'
|
|
82
82
|
import { statesOfFile, expandStates, splitStateNames, withState } from './states.js'
|
|
83
|
-
import { MOCK_FILE, MOCK_MAX, mockOfBuf, mockScript, saveMock } from './mock.js'
|
|
83
|
+
import { MOCK_FILE, MOCK_MAX, mockOf, mockOfBuf, mockScript, saveMock } from './mock.js'
|
|
84
84
|
import { partDrift, formatDrift } from './drift.js'
|
|
85
|
+
import { expandPreview, precheckScreens, dirReader, versionReader, designComponents, formatComponents, pageUsesComponents, hasCompDir } from './comp-io.js'
|
|
85
86
|
|
|
86
87
|
export const name = 'dsh-design-studio'
|
|
87
88
|
export const inject = ['webServer']
|
|
@@ -89,6 +90,14 @@ export const inject = ['webServer']
|
|
|
89
90
|
const API = '/dsh-design-studio/api/'
|
|
90
91
|
const LOOPBACK = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1'])
|
|
91
92
|
const LOOPBACK_HOST = /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i
|
|
93
|
+
/**
|
|
94
|
+
* DSH 的 WebServer 准入(0.2.2 起,默认 auth: 'required')把验过登录与来源的 Peer 作为 handler 最后一个参数传进来。
|
|
95
|
+
* 拿到它说明这一条请求 DSH 已经放过了,不用再按「只认本机」挡一次——否则从局域网地址、反向代理、域名进来的
|
|
96
|
+
* 请求会被这一层挡掉(DSH 0.2.3 起 connection 的 requestRejection 也删了,老写法没有别的放行途径)。
|
|
97
|
+
* 只认主人(peer.principal.kind === 'owner',DSH 自己的共享接口也这么判):别的身份直接 403。
|
|
98
|
+
* 老版本 DSH 没有这个参数:req 上不会有这个标记,退回原来的 connection / loopback 判断。
|
|
99
|
+
*/
|
|
100
|
+
const ADMITTED = Symbol('dsh-design-studio:admitted-peer')
|
|
92
101
|
const MAX_BODY = 64 * 1024
|
|
93
102
|
const MAX_EXPORT = 48 * 1024 * 1024 // 导出图片的请求体(base64)
|
|
94
103
|
const MAX_DOC = 160 * 1024 * 1024 // 导出 PDF / PPT 的请求体(几十屏的 JPEG,base64)
|
|
@@ -116,7 +125,7 @@ export const studio = { tracker: null, impl: null, openPreview: null, autoOpen:
|
|
|
116
125
|
export const designSkill = {
|
|
117
126
|
name: 'ui-design',
|
|
118
127
|
description:
|
|
119
|
-
'做网页、App 界面、小程序、平板界面、桌面软件、海报 / 社媒图、幻灯片、邮件、图表(思维导图、技术路线图、产品路线图、架构图)、DSH
|
|
128
|
+
'做网页、App 界面、小程序、平板界面、桌面软件、海报 / 社媒图、幻灯片、邮件、图表(思维导图、技术路线图、产品路线图、架构图)、DSH 插件界面、组件这类设计之前先加载;改已有的设计、把几屏重复的部分抽成组件(components/ 写法)也先加载:' +
|
|
120
129
|
'配合右侧「设计工作台」画布的做法(一屏一个文件、设计变量、类型标记)、现代设计原则、中文排版、各类型画幅要点、避免 AI 味、设计自查清单。' +
|
|
121
130
|
'只是把回答做成一页给用户看或用(对比、表格、清单、数据图表、计算器这类,或者在对话里随手看一张导图)不算设计:有 show_page 工具就直接用它,不加载这个技能;' +
|
|
122
131
|
'要「设计」、做好看的、要导出成图片 / PDF / PPT 的思维导图、路线图、架构图才用这个技能。',
|
|
@@ -154,6 +163,7 @@ export const previewTool = {
|
|
|
154
163
|
'kind 说明是哪类设计,右侧按它的画幅显示(App 套手机外框、幻灯片 16:9 …)。' +
|
|
155
164
|
'动手设计前先加载 ui-design 技能(设计流程、规范和自查清单)。' +
|
|
156
165
|
'要做好几屏(App 的几个界面、网站的几个页面)时,每屏一个 HTML 文件放在同一个目录,右侧画布会按生成顺序并排显示,一屏一屏写就行。' +
|
|
166
|
+
'几屏重复的部分(标签栏、顶栏、卡片)抽成组件时:写 components/<名>.html,各屏用 <c-名> 引用,插件展开成普通 HTML(别自己写 JS 自定义元素或运行时注入);写法见 ui-design 技能的 references/components.md。' +
|
|
157
167
|
'用户在预览里点选的内容会以「〔选中元素〕」或「〔选中区域〕」开头出现在消息里,带 CSS 路径、HTML、关键样式,' +
|
|
158
168
|
'拿得到时还有组件和源码位置:照它找到源码里对应的地方再改。',
|
|
159
169
|
parameters: specToJsonSchema({
|
|
@@ -186,6 +196,10 @@ export const previewTool = {
|
|
|
186
196
|
const tracker = studio.tracker
|
|
187
197
|
if (!tracker) throw new Error('「设计工作台」在 DSH 的插件页里关着,打开后再预览')
|
|
188
198
|
const target = parseTarget(args.target, tracker.cwdOf(id))
|
|
199
|
+
// 组件文件(#30)不是一屏:单独打开只是一块碎片,还会把 components/ 当成整套设计
|
|
200
|
+
if (target.kind === 'file' && path.basename(path.dirname(target.file)) === 'components') {
|
|
201
|
+
return { text: `${path.basename(target.file)} 是组件文件,不单独预览:打开用到它的那一屏(设计目录里的页面,比如 ${path.join(path.dirname(path.dirname(target.file)), 'index.html')})。`, url: '' }
|
|
202
|
+
}
|
|
189
203
|
const opts = { source: 'tool' }
|
|
190
204
|
if (args.kind !== undefined) opts.kind = args.kind
|
|
191
205
|
if (args.size !== undefined) opts.size = args.size
|
|
@@ -195,7 +209,7 @@ export const previewTool = {
|
|
|
195
209
|
const many = target.kind === 'file' ? '同目录再写别的 HTML 文件,会作为新的一屏并排出现。' : ''
|
|
196
210
|
const over = st.hidden ? `右侧最多显示 ${st.screens.length} 屏,还有 ${st.hidden} 屏没显示。` : ''
|
|
197
211
|
return {
|
|
198
|
-
text: `已在右侧「设计工作台」打开 ${what}。${target.kind === 'file' ? '这个目录里的文件一改就自动刷新。' + many : '开发服务器的热更新照常生效。'}${over}`,
|
|
212
|
+
text: `已在右侧「设计工作台」打开 ${what}。${target.kind === 'file' ? '这个目录里的文件一改就自动刷新。' + many : '开发服务器的热更新照常生效。'}${over}${target.kind === 'file' ? compLine(id) : ''}`,
|
|
199
213
|
url: st.url,
|
|
200
214
|
}
|
|
201
215
|
},
|
|
@@ -234,6 +248,36 @@ function driftOf(id) {
|
|
|
234
248
|
}
|
|
235
249
|
const driftNotes = (id) => { const r = driftOf(id); return r ? formatDrift(r, r.total) : '' }
|
|
236
250
|
|
|
251
|
+
/** 组件(#30):这套设计(本地文件)各屏组件的错、提醒、没人用的组件;没组件给 null。各屏和组件都没改过就不重算 */
|
|
252
|
+
const compSeen = new Map() // 目录 → { stamp, r }
|
|
253
|
+
function compOf(id) {
|
|
254
|
+
const t = studio.tracker.snapshot(id).target
|
|
255
|
+
if (!t || t.kind !== 'file') return null
|
|
256
|
+
const root = t.root || path.dirname(t.file)
|
|
257
|
+
const keys = allScreens(root).slice(0, 600)
|
|
258
|
+
// 组件文件、mock.json,还有页面引的本地脚本(接不接管 <c-…> 要看它们有没有自己注册 c-*)
|
|
259
|
+
const files = [...keys, MOCK_FILE, ...(() => { try { return fs.readdirSync(path.join(root, 'components')).map((n) => 'components/' + n) } catch { return [] } })(),
|
|
260
|
+
...(() => { try { return fs.readdirSync(root).filter((n) => /\.m?js$/i.test(n)) } catch { return [] } })()]
|
|
261
|
+
const stamp = files.map((k) => { try { const s = fs.statSync(path.join(root, k)); return `${k}:${s.mtimeMs}:${s.size}` } catch { return '' } }).join('|')
|
|
262
|
+
const hit = compSeen.get(root)
|
|
263
|
+
if (hit && hit.stamp === stamp) return hit.r
|
|
264
|
+
let r = null
|
|
265
|
+
try {
|
|
266
|
+
let mock = null
|
|
267
|
+
try { const m = mockOf(root); mock = m && !m.err ? m.data : null } catch { mock = null } // 和预览同一套:软链接当没有、太大不读
|
|
268
|
+
r = designComponents(root, keys, dirReader(root), mock)
|
|
269
|
+
} catch (e) { studio.log(e); return null }
|
|
270
|
+
if (!r.items.length && !r.pages.length) r = null
|
|
271
|
+
compSeen.delete(root)
|
|
272
|
+
compSeen.set(root, { stamp, r })
|
|
273
|
+
if (compSeen.size > 8) compSeen.delete(compSeen.keys().next().value)
|
|
274
|
+
return r
|
|
275
|
+
}
|
|
276
|
+
/** 体检报告末尾:组件的问题(没有就空) */
|
|
277
|
+
const compNotes = (id) => { const r = compOf(id); const lines = r ? formatComponents(r) : []; return lines.length ? `\n\n组件(components/):\n${lines.join('\n')}` : '' }
|
|
278
|
+
/** preview_page / check_design 末尾一行短目录:长对话压缩后模型也知道有哪些组件、参数怎么传 */
|
|
279
|
+
const compLine = (id) => { const r = compOf(id); return r && r.line ? `\n${r.line}` : '' }
|
|
280
|
+
|
|
237
281
|
/** 一页多状态(#30):屏 → 它的文件里写了哪几个状态(不是本地文件的设计当没写) */
|
|
238
282
|
function statesOfScreen(id) {
|
|
239
283
|
const t = studio.tracker.snapshot(id).target
|
|
@@ -347,7 +391,7 @@ export const checkTool = {
|
|
|
347
391
|
if (want.more) text += `\n尺寸太多,只量了前 ${MAX_SIZES} 种`
|
|
348
392
|
if (ex.skipped) text += `\n状态太多,有 ${ex.skipped} 个状态没量:screens 写成 order.html?state=状态名 单量那个状态`
|
|
349
393
|
text += stateMisses(pick0.list, stOf, sn.only, '量的是这屏全部状态')
|
|
350
|
-
text += tweakNotes(id) + fontNotes(id) + annotationNotes(anAt, rows) + driftNotes(id)
|
|
394
|
+
text += tweakNotes(id) + fontNotes(id) + annotationNotes(anAt, rows) + driftNotes(id) + compNotes(id) + compLine(id)
|
|
351
395
|
return kept && kept.images ? { text, images: kept.images } : { text }
|
|
352
396
|
}
|
|
353
397
|
studio.log(new Error(`check_design 无头浏览器没量成:${rows[0] && rows[0].error}`))
|
|
@@ -356,12 +400,12 @@ export const checkTool = {
|
|
|
356
400
|
}
|
|
357
401
|
}
|
|
358
402
|
// 没有无头浏览器(或者它没量成):让右侧栏在显示着的页面上量
|
|
359
|
-
if (!studio.check) return { text: '这台电脑上没找到能用的 Chrome / Edge,「设计工作台」也没开着,量不了。照 ui-design 技能里的「自查」清单自己过一遍。' }
|
|
403
|
+
if (!studio.check) return { text: '这台电脑上没找到能用的 Chrome / Edge,「设计工作台」也没开着,量不了。照 ui-design 技能里的「自查」清单自己过一遍。' + compNotes(id) + compLine(id) }
|
|
360
404
|
const r = await studio.check(id)
|
|
361
405
|
const note = want.sizes.length || a.dark ? '(这台电脑上没找到能用的 Chrome / Edge,没法按指定尺寸 / 深色量;下面是右侧栏按它现在显示的尺寸量的)\n' : ''
|
|
362
|
-
if (!r) return { text: '右侧栏「设计工作台」现在没开着,量不了。照 ui-design 技能里的「自查」清单自己过一遍。' }
|
|
363
|
-
if (!r.error && !r.measured) return { text: '右侧栏开着,但预览页面没回应,这次没量成(可能还在加载)。过一会儿再调一次,或照 ui-design 技能里的「自查」清单自己过一遍。' }
|
|
364
|
-
return { text: note + (r.error || r.text) + tweakNotes(id) + fontNotes(id) + annotationNotes(anAt, null) + (r.error ? '' : driftNotes(id)) }
|
|
406
|
+
if (!r) return { text: '右侧栏「设计工作台」现在没开着,量不了。照 ui-design 技能里的「自查」清单自己过一遍。' + compNotes(id) + compLine(id) }
|
|
407
|
+
if (!r.error && !r.measured) return { text: '右侧栏开着,但预览页面没回应,这次没量成(可能还在加载)。过一会儿再调一次,或照 ui-design 技能里的「自查」清单自己过一遍。' + compNotes(id) + compLine(id) }
|
|
408
|
+
return { text: note + (r.error || r.text) + tweakNotes(id) + fontNotes(id) + annotationNotes(anAt, null) + (r.error ? '' : driftNotes(id)) + compNotes(id) + compLine(id) }
|
|
365
409
|
},
|
|
366
410
|
}
|
|
367
411
|
|
|
@@ -593,6 +637,13 @@ export const frameTool = {
|
|
|
593
637
|
let st = null
|
|
594
638
|
try { st = fs.statSync(src) } catch { /* 下面说 */ }
|
|
595
639
|
if (!st || !st.isDirectory()) return { text: `找不到文件夹:${src}` }
|
|
640
|
+
// 外框里用组件(#30):外框库存的是单个页面,认不了 components/,存了也是空标签
|
|
641
|
+
try {
|
|
642
|
+
const htmls = fs.readdirSync(src).filter((n) => /\.html?$/i.test(n)).slice(0, 500)
|
|
643
|
+
const rd = dirReader(src)
|
|
644
|
+
const hit = htmls.find((n) => { try { return pageUsesComponents(fs.readFileSync(path.join(src, n), 'utf8'), rd) } catch { return false } })
|
|
645
|
+
if (hit) return { text: `外框里不能用组件(<c-…>):${hit} 用了组件。外框存的是单个页面,把组件的内容直接写进外框页面再存。` }
|
|
646
|
+
} catch { /* 读不了:交给 saveFrame 报 */ }
|
|
596
647
|
let r
|
|
597
648
|
try {
|
|
598
649
|
r = await saveFrame({ browser: studio.browser, src })
|
|
@@ -625,23 +676,25 @@ export const handoffTool = {
|
|
|
625
676
|
name: 'handoff_design',
|
|
626
677
|
description:
|
|
627
678
|
'把右侧「设计工作台」里的设计(本地 HTML 那几屏)整理成交接包,准备做成真项目的代码:写好 <设计目录>/handoff/HANDOFF.md(每屏的文件、建议路由、跳转、设计变量、几屏共用该抽成组件的部分、交互和状态、调节滑块、素材、做法和验收),和每屏从上到下的截图。' +
|
|
679
|
+
'HANDOFF.md 一直列全部屏。截图和逐屏说明分批补齐,用 batch 继续下一批,或用 screens 指定要截的屏。' +
|
|
628
680
|
'用户说「转成代码」「做成真的项目」「用 React / Vue / uni-app 做出来」「做成小程序」时先调它,读 HANDOFF.md 照着做;每做完一屏用 compare_design 和设计稿比一遍,差异降到 3% 以下再做下一屏(原生小程序在浏览器里跑不起来,照 HANDOFF.md 说的请用户在微信开发者工具里看)。' +
|
|
629
681
|
'framework:same 跟目标目录现有项目一样(认得出框架时默认,uni-app(含 HBuilderX 建的、没有 package.json 的)、Taro、微信原生小程序也认得出)、react、vue、next、html、uniapp、weapp;dest:代码放哪个目录(不填:会话目录是项目就放进去,不是就新建 <设计名>-app)。要先用 preview_page 打开过设计。',
|
|
630
682
|
parameters: specToJsonSchema({
|
|
631
683
|
framework: { type: 'string', enum: ['same', ...Object.keys(FRAMEWORKS)], description: 'same 跟现有项目一样;react(React + Vite)、vue(Vue 3 + Vite)、next(Next.js)、html(纯 HTML / CSS)、uniapp(uni-app,出微信小程序和网页版)、weapp(微信原生小程序 WXML / WXSS)。不填:目标目录(或它所在的项目)认得出框架就 same,没有 package.json 的纯 HTML 站点 html,小程序的设计 uniapp,别的 react' },
|
|
632
684
|
dest: { type: 'string', description: '代码放哪:现有项目的目录(或它里面的子目录),或要新建的项目目录(绝对路径或相对会话目录)。不填:会话目录有 package.json 就放进去,没有就新建 <设计名>-app(设计目录在会话目录下就建在会话目录里,不然建在设计目录旁边)' },
|
|
633
|
-
|
|
685
|
+
batch: { type: 'integer', minimum: 1, description: `截图批次,从 1 开始,每批最多 ${HANDOFF_BATCH_SIZE} 屏,默认第 1 批。填了 screens 时按指定的屏截` },
|
|
686
|
+
screens: { type: 'array', items: { type: 'string' }, description: `按文件名指定本次要截图和补说明的屏,最多 ${HANDOFF_BATCH_SIZE} 屏` },
|
|
634
687
|
}),
|
|
635
688
|
output: {
|
|
636
689
|
schema: {
|
|
637
690
|
type: 'object',
|
|
638
691
|
additionalProperties: false,
|
|
639
|
-
properties: { text: { type: 'string' }
|
|
692
|
+
properties: { text: { type: 'string' } },
|
|
640
693
|
required: ['text'],
|
|
641
694
|
},
|
|
642
|
-
render: (_args, value) =>
|
|
695
|
+
render: (_args, value) => [{ type: 'text', text: value.text }],
|
|
643
696
|
},
|
|
644
|
-
async execute(args, exec
|
|
697
|
+
async execute(args, exec) {
|
|
645
698
|
const id = toolSession(exec, '转成代码')
|
|
646
699
|
const a = args || {}
|
|
647
700
|
const snap = studio.tracker.snapshot(id)
|
|
@@ -650,9 +703,10 @@ export const handoffTool = {
|
|
|
650
703
|
if (!t || t.kind !== 'file') return { text: '现在预览的是开发服务器上的页面,它已经是代码了:直接在那个项目里改;要比对设计稿就先用 preview_page 打开设计的 HTML 文件。' }
|
|
651
704
|
const design = designFor(id)
|
|
652
705
|
const { kind } = design
|
|
653
|
-
const
|
|
654
|
-
const pick =
|
|
655
|
-
if (
|
|
706
|
+
const catalog = handoffScreens(t.root, snap.origin)
|
|
707
|
+
const pick = handoffBatch(catalog, { batch: a.batch, names: a.screens })
|
|
708
|
+
if (pick.error) return { text: pick.error }
|
|
709
|
+
if (!pick.list.length) return { text: `没找到要转的屏${pick.missing.length ? ':' + pick.missing.join('、') : ''}。目录里有 ${catalog.length} 屏,可用 batch=1 查看交接清单。` }
|
|
656
710
|
const cwd = studio.tracker.cwdOf(id)
|
|
657
711
|
// 先定下最终放哪(没给就和右侧栏建议的一样),再按真实路径查是不是在设计目录里
|
|
658
712
|
const dest = typeof a.dest === 'string' && a.dest.trim() ? resolvePath(a.dest, cwd) : defaultDest(t.root, cwd, detectProject(cwd))
|
|
@@ -662,18 +716,37 @@ export const handoffTool = {
|
|
|
662
716
|
if (framework === 'same' && !project.framework) return { text: `${dest} 里没有认得出的前端项目(package.json 里没有 React / Vue / Next / uni-app …,也不是 HBuilderX 或微信原生小程序的项目):framework 选 react、vue、next、html、uniapp 或 weapp。` }
|
|
663
717
|
let r
|
|
664
718
|
try {
|
|
665
|
-
|
|
719
|
+
const b = studio.browser
|
|
720
|
+
const samples = a.screens?.length ? pick.list : pick.list.slice(0, 6)
|
|
721
|
+
const size = design.auto && b?.available() ? await fitSize(b, samples, kind, design.size) : design.size
|
|
722
|
+
r = await buildHandoff(b, { root: t.root, catalog, selection: pick, kind, size, framework, dest, project, system: systemOfDir(t.root), annotations: studio.annotations > 0 ? readAnnotations(t.root) : null, tuned: studio.tracker.versions(id) })
|
|
666
723
|
} catch (e) {
|
|
667
724
|
return { text: `没写成交接包:${String((e && e.message) || e).slice(0, 200)}` }
|
|
668
725
|
}
|
|
669
726
|
studio.tracker.markHandoff(id, t.root) // 右侧栏的步骤条:交接包写好了,模型在照着做
|
|
670
727
|
// 原生小程序跑不了网页版:比不了,照 HANDOFF.md 请用户在微信开发者工具里看
|
|
671
728
|
const native = framework === 'weapp' || (framework === 'same' && project.framework === 'weapp')
|
|
672
|
-
const
|
|
673
|
-
|
|
674
|
-
const
|
|
675
|
-
|
|
676
|
-
|
|
729
|
+
const verify = native ? '每屏做完请用户在微信开发者工具里看' : '每屏做完用 compare_design 比'
|
|
730
|
+
const batch = pick.batch ? `第 ${pick.batch} 批` : '本次指定'
|
|
731
|
+
const lines = [
|
|
732
|
+
`${batch} ${r.rows.length} 屏(${r.rows.map((row) => row.key).join('、')}),新增或更新 ${r.shots} 张截图。`,
|
|
733
|
+
`交接说明:${r.file}`,
|
|
734
|
+
`截图目录:${path.join(r.dir, 'shots')}`,
|
|
735
|
+
]
|
|
736
|
+
if (pick.missing.length) lines.push(`没找到指定的屏:${pick.missing.join('、')}。`)
|
|
737
|
+
for (const row of r.rows) if (row.error) lines.push(`没截成 ${row.key}:${row.error}`)
|
|
738
|
+
if (r.pending.length) {
|
|
739
|
+
// 这一批一张都没截成(没有能用的浏览器、屏一直截不了):别让模型反复调同一批空跑
|
|
740
|
+
const stuck = r.rows.length > 0 && r.rows.every((row) => row.error)
|
|
741
|
+
const rest = r.pending.filter((n) => n !== (pick.batch || 0))
|
|
742
|
+
if (stuck) lines.push('这一批一张截图也没截成(多半是这台电脑没有能用的 Chrome / Edge):先照 HANDOFF.md 写代码,截图以后再补,不用反复调。')
|
|
743
|
+
else if (rest.length) {
|
|
744
|
+
const next = rest.find((n) => n > (pick.batch || 0)) ?? rest[0]
|
|
745
|
+
lines.push(`第 ${rest.join('、')} 批还有待截或待重截的屏,调 handoff_design batch=${next} 继续。`)
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
lines.push(`读 HANDOFF.md,${verify}。`)
|
|
749
|
+
return { text: lines.join('\n') }
|
|
677
750
|
},
|
|
678
751
|
}
|
|
679
752
|
|
|
@@ -906,11 +979,11 @@ export const compareTool = {
|
|
|
906
979
|
|
|
907
980
|
/** 设计记在哪个名下:本地设计按目录,开发服务器的按端口 */
|
|
908
981
|
/** 填的本地文件就是设计稿自己的某一屏(设计目录里登记的那几个文件):不算做出来的 */
|
|
909
|
-
export const isDesignFile = (at, u) => {
|
|
982
|
+
export const isDesignFile = (at, u, catalog) => {
|
|
910
983
|
if (u.protocol !== 'file:' || !at.snap.target || at.snap.target.kind !== 'file') return false
|
|
911
984
|
try {
|
|
912
985
|
const rel = path.relative(path.resolve(at.root), fileURLToPath(u)).split(path.sep).join('/')
|
|
913
|
-
return
|
|
986
|
+
return catalog ? catalog.some((sc) => sc.key === rel) : allScreens(at.root).includes(rel)
|
|
914
987
|
} catch { return false }
|
|
915
988
|
}
|
|
916
989
|
export const implRoot = (snap) => (snap && snap.target ? (snap.target.kind === 'file' ? snap.target.root : `proxy:${snap.target.port}`) : '')
|
|
@@ -929,20 +1002,27 @@ async function runCompare(id, a) {
|
|
|
929
1002
|
if (!b || !b.available()) return { text: '这台电脑上没找到 Chrome / Edge(比对要用无头浏览器截图),比不了。' }
|
|
930
1003
|
const design = designFor(id)
|
|
931
1004
|
const { kind } = design
|
|
932
|
-
const
|
|
933
|
-
if (!want) return { text: `认不出尺寸「${String(a.size).slice(0, 20)}」:写成 375x667,或只写宽度 375。` }
|
|
1005
|
+
const catalog = snap.target?.kind === 'file' ? handoffScreens(root, snap.origin) : null
|
|
934
1006
|
// 指定了哪屏就只认那屏,找不到就说(别悄悄拿第一屏比,结果对不上号);没指定才用正在看的 / 第一屏
|
|
935
1007
|
const asked = typeof a.screen === 'string' && a.screen.trim()
|
|
936
|
-
const
|
|
937
|
-
|
|
938
|
-
|
|
1008
|
+
const sc = catalog
|
|
1009
|
+
? findHandoffScreen(catalog, asked || snap.focus) || (!asked && catalog[0])
|
|
1010
|
+
: pickScreens(snap, [asked || snap.focus], 1).list[0] || (!asked && pickScreens(snap, null, 1).list[0])
|
|
1011
|
+
if (!sc) {
|
|
1012
|
+
const all = catalog || snap.screens || []
|
|
1013
|
+
return { text: `没找到设计稿的这一屏:${asked || '(没有屏)'}。共 ${all.length} 屏:${all.slice(0, HANDOFF_BATCH_SIZE).map((x) => x.key).join('、')}${all.length > HANDOFF_BATCH_SIZE ? ' 等,可用 handoff_design 查看完整清单' : ''}。` }
|
|
1014
|
+
}
|
|
1015
|
+
const want = Array.isArray(a.size) ? a.size : a.size ? sizeOf(a.size, kind) : !catalog
|
|
1016
|
+
? await fitted(b, design, asked ? [a.screen] : null)
|
|
1017
|
+
: design.auto ? await fitSize(b, asked ? [sc] : catalog.slice(0, 6), kind, design.size) : design.size
|
|
1018
|
+
if (!want) return { text: `认不出尺寸「${String(a.size).slice(0, 20)}」:写成 375x667,或只写宽度 375。` }
|
|
939
1019
|
// 相对路径、本地 HTML 的预览根:先问 DSH 会话目录(和右侧栏填地址一样),问不到才用记着的
|
|
940
1020
|
let cwd = ''
|
|
941
1021
|
try { cwd = studio.sessionCwd ? await studio.sessionCwd(id) : '' } catch { cwd = '' }
|
|
942
1022
|
if (!cwd) cwd = studio.tracker.cwdOf(id)
|
|
943
1023
|
let impl
|
|
944
1024
|
try { impl = implUrl(a.url, cwd) } catch (e) { return { text: e.message } }
|
|
945
|
-
if ((snap.origin && impl.startsWith(snap.origin + '/')) || isDesignFile({ snap, root }, new URL(impl))) return { text: '这个地址是设计稿自己(设计工作台的预览或设计目录里的文件),给做出来的那个项目的地址。' }
|
|
1025
|
+
if ((snap.origin && impl.startsWith(snap.origin + '/')) || isDesignFile({ snap, root }, new URL(impl), catalog)) return { text: '这个地址是设计稿自己(设计工作台的预览或设计目录里的文件),给做出来的那个项目的地址。' }
|
|
946
1026
|
const opts = { at: a.at === 'bottom' ? 'bottom' : 'top', dark: !!a.dark, whole: a.whole === true }
|
|
947
1027
|
let r
|
|
948
1028
|
try {
|
|
@@ -1196,6 +1276,13 @@ export function apply(ctx) {
|
|
|
1196
1276
|
// ── 接口 ──────────────────────────────────────────────────────────────────
|
|
1197
1277
|
|
|
1198
1278
|
function admit(req, res) {
|
|
1279
|
+
const peer = req[ADMITTED]
|
|
1280
|
+
if (peer) {
|
|
1281
|
+
// DSH 的 WebServer 准入已经验过登录与来源(见 ADMITTED 的说明);设计台只给「主人」用:别的身份(以后 DSH 加的访客之类)一律不让进
|
|
1282
|
+
if (peer.principal && peer.principal.kind === 'owner') return true
|
|
1283
|
+
json(res, 403, { error: 'forbidden' })
|
|
1284
|
+
return false
|
|
1285
|
+
}
|
|
1199
1286
|
const conn = connectionOf(ctx)
|
|
1200
1287
|
if (conn) {
|
|
1201
1288
|
const rejected = conn.requestRejection(req)
|
|
@@ -1586,6 +1673,8 @@ export function apply(ctx) {
|
|
|
1586
1673
|
try {
|
|
1587
1674
|
// 输入框里写的相对路径按会话目录算(新会话也问 DSH 要)
|
|
1588
1675
|
const target = parseTarget(body.target, await sessionCwd(session))
|
|
1676
|
+
// 组件文件(#30)不是一屏:拖进来、选中它都不当整套设计开
|
|
1677
|
+
if (target.kind === 'file' && path.basename(path.dirname(target.file)) === 'components' && /\.html?$/i.test(target.file)) throw new Error(`${path.basename(target.file)} 是组件文件,不单独打开:打开用到它的那一屏`)
|
|
1589
1678
|
await tracker.setTarget(session, target, { source: 'user', popup: false })
|
|
1590
1679
|
// 换了设计,公网链接马上关(右侧栏要马上知道,不等下一次刷新)
|
|
1591
1680
|
json(res, 200, { ...tracker.snapshot(session), ...annotsField(session), pub: pub.status(session, { brief: true }) })
|
|
@@ -1625,7 +1714,7 @@ export function apply(ctx) {
|
|
|
1625
1714
|
function historyRoute(req, res) {
|
|
1626
1715
|
if (!admit(req, res)) return
|
|
1627
1716
|
const session = new URL(req.url, 'http://x').searchParams.get('session') || ''
|
|
1628
|
-
json(res, 200, { versions: tracker.versions(session) })
|
|
1717
|
+
json(res, 200, { versions: tracker.versions(session), skip: tracker.versionSkip ? tracker.versionSkip(session) : null })
|
|
1629
1718
|
}
|
|
1630
1719
|
|
|
1631
1720
|
async function restoreRoute(req, res) {
|
|
@@ -1830,6 +1919,8 @@ export function apply(ctx) {
|
|
|
1830
1919
|
function bundleFile(root, v, rel) {
|
|
1831
1920
|
let f = ''
|
|
1832
1921
|
if (v) f = history.fileOf(root, v, rel) || ''
|
|
1922
|
+
// 组件文件(#30):旧版本只认那一版快照里的,没有就是没有(不拿现在的顶上,不然旧版本会混进新组件)
|
|
1923
|
+
if (v && /^components\//.test(rel)) return f
|
|
1833
1924
|
// 模拟数据和预览一个规矩(serve.js versionMock / mockOf):旧版本只认那一版自己的 mock.json(那版没有就是没有,
|
|
1834
1925
|
// 不拿现在的顶上);现在的是软链接就当没有
|
|
1835
1926
|
if (rel === MOCK_FILE) {
|
|
@@ -1913,7 +2004,8 @@ export function apply(ctx) {
|
|
|
1913
2004
|
return s.isFile() && s.size <= BUNDLE_MAX ? fs.readFileSync(f) : null
|
|
1914
2005
|
}
|
|
1915
2006
|
// 别人做的设计(设计库来的、没改过):加硬规矩,右侧栏的沙盒也不放行表单
|
|
1916
|
-
|
|
2007
|
+
// 市场来的原版也算(和本地预览、正式打包同一套判定)
|
|
2008
|
+
const strictOf = (page) => library.strictHtml(page) || market.strictHtml(page) || (v > 0 && library.strictVersions(t.root))
|
|
1917
2009
|
const had = fresh ? null : bundleCache.get(name)
|
|
1918
2010
|
// 上次那份还能用:用到的文件一个都没动,地址没换(预览端口变了,里面的 <base> 就不一样了),
|
|
1919
2011
|
// 内联的 picker 没换,而且现在仍然不用加硬规矩——文件没动、信任却变了(退回旧版时记下了别人做的页面)
|
|
@@ -1939,6 +2031,7 @@ export function apply(ctx) {
|
|
|
1939
2031
|
if (!deps.has(rel)) { deps.add(rel); pre.set(rel, stampOf(t.root, v, rel)) }
|
|
1940
2032
|
return readRel(rel)
|
|
1941
2033
|
}
|
|
2034
|
+
if (!(v > 0)) read.hasCompDir = () => hasCompDir(t.root) // 旧版本:快照里有用到的组件文件才算(见 adopts)
|
|
1942
2035
|
try {
|
|
1943
2036
|
const page = read(key)
|
|
1944
2037
|
if (!page) return json(res, 404, { error: 'no-screen' })
|
|
@@ -1955,7 +2048,10 @@ export function apply(ctx) {
|
|
|
1955
2048
|
const mockErr = mk ? [mk.err, over.length ? `数据里的图太大,远程看时没带上:${over.slice(0, 3).join('、')}${over.length > 3 ? ' 等' : ''}` : ''].filter(Boolean).join(';') : ''
|
|
1956
2049
|
const mockTag = mk ? mockScript({ ...mk, assets: mockAssets, err: mockErr }, { scope: crypto.createHash('sha1').update(t.root).digest('hex').slice(0, 10) }) : ''
|
|
1957
2050
|
const lead = strict ? strictMeta(nonce) + (ERR_CATCHER + setState + mockTag).replaceAll('<script>', `<script nonce="${nonce}">`) : ERR_CATCHER + setState + mockTag
|
|
1958
|
-
|
|
2051
|
+
// 组件(#30):先展开(读组件也走 read:记进用到的文件,组件一改就重新打包);别人做的按原始字节认,展开后再去脚本
|
|
2052
|
+
let text = page.toString('utf8')
|
|
2053
|
+
try { text = expandPreview(text, read, key).html } catch (e) { log(e) }
|
|
2054
|
+
let html = bundle(strict ? defang(text) : text, { key, read, base: href, lead, tail: inlinePicker(fs.readFileSync(PICKER_FILE, 'utf8'), parent, href, nonce) })
|
|
1959
2055
|
// 打包后图片变成 data: 地址,文件名没了:把用到的 AI 示意图记在页面里,导出时照样提醒
|
|
1960
2056
|
const aiNames = [...deps].filter((x) => isPhotoAsset(x)).map((x) => path.basename(x))
|
|
1961
2057
|
if (aiNames.length) html = html.replace(lead, () => `${lead}<meta name="ddp-ai-photos" content="${aiNames.join(',').replace(/[^a-z0-9.,-]/gi, '')}">`)
|
|
@@ -2036,6 +2132,28 @@ export function apply(ctx) {
|
|
|
2036
2132
|
saveExport(res, String(body.session || ''), body.name, 'png', buf)
|
|
2037
2133
|
}
|
|
2038
2134
|
|
|
2135
|
+
/**
|
|
2136
|
+
* 导出图片 / PDF / PPT 前的组件预检(#30):截图不经打包,组件出错的红框会被当成正常画面存下来,所以先查。
|
|
2137
|
+
* POST { session, keys?, v? } → { pages: [{ page, errors }] }(只列有错的;某一版就从那一版的快照读)
|
|
2138
|
+
*/
|
|
2139
|
+
async function compCheckRoute(req, res) {
|
|
2140
|
+
if (!admit(req, res)) return
|
|
2141
|
+
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
|
|
2142
|
+
let body
|
|
2143
|
+
try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
|
|
2144
|
+
const st = tracker.stateOf(String(body.session || ''))
|
|
2145
|
+
const t = st && st.target
|
|
2146
|
+
if (!t || t.kind !== 'file') return json(res, 200, { pages: [] })
|
|
2147
|
+
const v = Math.max(0, Math.floor(Number(body.v) || 0))
|
|
2148
|
+
// 没挑屏 = 整套:某一版就按那一版存下的屏(后来删掉的屏旧版里还在,截图会截到)
|
|
2149
|
+
const verScreens = () => { const x = v > 0 ? tracker.versions(String(body.session || '')).find((y) => y.n === v) : null; return x ? x.screens : allScreens(t.root) }
|
|
2150
|
+
const keys = Array.isArray(body.keys) ? [...new Set(body.keys.filter((k) => typeof k === 'string').map((k) => k.replace(/^v\d+\|/, '').split(/[?#]/)[0]).filter((k) => /^[^/\\]+\.html?$/i.test(k)))].slice(0, 2000) : verScreens()
|
|
2151
|
+
const read = v > 0 ? versionReader(history, t.root, v) : dirReader(t.root)
|
|
2152
|
+
let pages = []
|
|
2153
|
+
try { pages = precheckScreens(keys, read) } catch (e) { log(e); return json(res, 500, { error: 'compcheck' }) } // 查不了不当成没错
|
|
2154
|
+
json(res, 200, { pages: pages.slice(0, 50).map((x) => ({ page: x.page, errors: x.errors.slice(0, 5).map((d) => ({ code: d.code, message: d.message, file: d.file, line: d.line, fix: d.fix })) })) })
|
|
2155
|
+
}
|
|
2156
|
+
|
|
2039
2157
|
/**
|
|
2040
2158
|
* 屏多过上限(#29):导出用的全部屏,按导出的先后(显示的照右侧栏的顺序,收起来的照设计清单 / 生成先后插回原位),带页面标题(导出的目录、演示的下拉里用)。
|
|
2041
2159
|
* 右侧栏导出前现问这一份,不靠它自己记的(刚加的屏、改了名的收起来的屏,它都还没轮询到)。没收起来的给空(右侧栏就用显示的这些)
|
|
@@ -2188,13 +2306,19 @@ export function apply(ctx) {
|
|
|
2188
2306
|
if (s.isFile() && s.size > BUNDLE_MAX) big.add(rel)
|
|
2189
2307
|
return s.isFile() && s.size <= BUNDLE_MAX ? fs.readFileSync(f) : null
|
|
2190
2308
|
}
|
|
2309
|
+
if (!(v > 0)) read.hasCompDir = () => hasCompDir(root) // 旧版本:快照里有用到的组件文件才算(见 adopts)
|
|
2191
2310
|
const strictOf = (page) => library.strictHtml(page) || market.strictHtml(page) || (v > 0 && library.strictVersions(root))
|
|
2192
2311
|
const libFont = (id) => {
|
|
2193
2312
|
const f = studio.fonts && studio.fonts.index.fonts.find((x) => x.id === id)
|
|
2194
2313
|
const p = f && studio.fonts.cached(id)
|
|
2195
2314
|
return p ? { family: f.family, weights: f.weights, data: fs.readFileSync(p) } : null
|
|
2196
2315
|
}
|
|
2197
|
-
|
|
2316
|
+
let pack
|
|
2317
|
+
try { pack = buildPack({ ...params, read, bigOf: (rel) => big.has(rel), strictOf, libFont }) } catch (e) {
|
|
2318
|
+
// 打不出来(比如组件有错、缺组件):带上这次读过和想读的文件,公网链接看着它们,改好了自己重打
|
|
2319
|
+
if (e && typeof e === 'object') e.deps = [...files]
|
|
2320
|
+
throw e
|
|
2321
|
+
}
|
|
2198
2322
|
return { pack, deps, files: [...files] }
|
|
2199
2323
|
}
|
|
2200
2324
|
|
|
@@ -2219,14 +2343,15 @@ export function apply(ctx) {
|
|
|
2219
2343
|
try {
|
|
2220
2344
|
;({ pack, deps } = packDesign(t.root, v, params))
|
|
2221
2345
|
} catch (e) {
|
|
2222
|
-
|
|
2346
|
+
// compErr(#30):哪几屏的组件有错,右侧栏列出来、能点过去
|
|
2347
|
+
return json(res, e.code ? 400 : 500, { error: e.code || e.message, ...(e.pages ? { pages: e.pages } : {}), ...(e.files ? { files: e.files.slice(0, 10), message: e.message } : {}) })
|
|
2223
2348
|
}
|
|
2224
2349
|
// 打包时会话换了设计:别把 A 的演示存进 B 的 exports/
|
|
2225
2350
|
if (targetMoved(res, session, body.target)) return
|
|
2226
2351
|
const ai = new Set([...deps].filter((x) => isPhotoAsset(x)).map((x) => path.basename(x)))
|
|
2227
2352
|
try {
|
|
2228
2353
|
const file = writeExport(session, body.name, 'html', Buffer.from(pack.html, 'utf8'))
|
|
2229
|
-
json(res, 200, { path: file, count: pack.count, missing: pack.missing, skipped: pack.skipped.slice(0, 20), skippedN: pack.skipped.length, ai: ai.size, bytes: pack.html.length })
|
|
2354
|
+
json(res, 200, { path: file, count: pack.count, missing: pack.missing, skipped: pack.skipped.slice(0, 20), skippedN: pack.skipped.length, gone: (pack.gone || []).slice(0, 20), goneN: (pack.gone || []).length, ai: ai.size, bytes: pack.html.length })
|
|
2230
2355
|
} catch (e) {
|
|
2231
2356
|
json(res, 500, { error: e.message })
|
|
2232
2357
|
}
|
|
@@ -2384,12 +2509,13 @@ export function apply(ctx) {
|
|
|
2384
2509
|
})
|
|
2385
2510
|
const mk = createMarketRoutes({ admit, readBody, json, tracker, library, market, open, systemsDir: SYSTEMS_DIR, log, sessionCwd })
|
|
2386
2511
|
|
|
2387
|
-
const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, verthumb: canvasThumbs.verRoute, pack: lib.pack, usezip: lib.usezip, ghauth: lib.ghauth, submit: lib.submit, inspire: lib.inspire, inspimg: lib.inspimg, ...mk, state, open: openRoute, view: viewRoute, close: closeRoute, history: historyRoute, restore: restoreRoute, hidden: hiddenRoute, edit: editRoute, style: styleRoute, sharecheck: shareCheckRoute, drift: driftRoute, states: statesRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, htmlpack: htmlPackRoute, pubshare: pubShareRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, fonts: fontsRoute, mocksave: mockSaveRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute, impl: implRoute, implcmp: implCmpRoute, implshot: implShotRoute }
|
|
2512
|
+
const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, verthumb: canvasThumbs.verRoute, pack: lib.pack, usezip: lib.usezip, ghauth: lib.ghauth, submit: lib.submit, inspire: lib.inspire, inspimg: lib.inspimg, ...mk, state, open: openRoute, view: viewRoute, close: closeRoute, history: historyRoute, restore: restoreRoute, hidden: hiddenRoute, edit: editRoute, style: styleRoute, sharecheck: shareCheckRoute, compcheck: compCheckRoute, drift: driftRoute, states: statesRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, htmlpack: htmlPackRoute, pubshare: pubShareRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, fonts: fontsRoute, mocksave: mockSaveRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute, impl: implRoute, implcmp: implCmpRoute, implshot: implShotRoute }
|
|
2388
2513
|
for (const [key, handler] of Object.entries(routes)) {
|
|
2389
2514
|
ctx.effect(() => ctx.webServer.register({
|
|
2390
2515
|
kind: 'exact',
|
|
2391
2516
|
path: API + key,
|
|
2392
|
-
handler: (req, res) => {
|
|
2517
|
+
handler: (req, res, peer) => {
|
|
2518
|
+
if (peer) req[ADMITTED] = peer // 新版 DSH 准入给的 Peer:admit() 认它,见 ADMITTED 的说明
|
|
2393
2519
|
Promise.resolve(handler(req, res)).catch((e) => {
|
|
2394
2520
|
log(e)
|
|
2395
2521
|
if (!res.headersSent) json(res, 500, { error: 'internal' })
|