dsh-design-studio 1.5.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +6 -5
- package/README.md +7 -6
- package/THIRD_PARTY_NOTICES.md +108 -0
- package/assets/art/README.md +102 -0
- package/assets/art/brand-mark.webp +0 -0
- package/assets/art/check-clean.webp +0 -0
- package/assets/art/coach-markup.webp +0 -0
- package/assets/art/drop-file.webp +0 -0
- package/assets/art/empty-components.webp +0 -0
- package/assets/art/empty-data.webp +0 -0
- package/assets/art/empty-error.webp +0 -0
- package/assets/art/empty-frames.webp +0 -0
- package/assets/art/empty-history.webp +0 -0
- package/assets/art/empty-market.webp +0 -0
- package/assets/art/empty-notes.webp +0 -0
- package/assets/art/empty-search.webp +0 -0
- package/assets/art/empty-tokens.webp +0 -0
- package/assets/art/empty-works.webp +0 -0
- package/assets/art/guide-icon.webp +0 -0
- package/assets/art/kind-app.webp +0 -0
- package/assets/art/kind-desktop.webp +0 -0
- package/assets/art/kind-diagram.webp +0 -0
- package/assets/art/kind-dshplugin.webp +0 -0
- package/assets/art/kind-email.webp +0 -0
- package/assets/art/kind-embedded.webp +0 -0
- package/assets/art/kind-framed.webp +0 -0
- package/assets/art/kind-miniprogram.webp +0 -0
- package/assets/art/kind-poster.webp +0 -0
- package/assets/art/kind-slides.webp +0 -0
- package/assets/art/kind-tablet.webp +0 -0
- package/assets/art/kind-web.webp +0 -0
- package/assets/art/placeholder-inspire-img.webp +0 -0
- package/assets/art/wait-creating.webp +0 -0
- package/assets/motion/ai-capsule.html +124 -0
- package/assets/motion/ai-glow-input.html +112 -0
- package/assets/motion/balance-odometer.html +112 -0
- package/assets/motion/bottom-sheet.html +149 -0
- package/assets/motion/brightness-pill.html +114 -0
- package/assets/motion/comet-ring.html +95 -0
- package/assets/motion/copy-morph.html +116 -0
- package/assets/motion/cube-grid.html +103 -0
- package/assets/motion/day-night.html +120 -0
- package/assets/motion/dial-knob.html +130 -0
- package/assets/motion/dock-magnify.html +118 -0
- package/assets/motion/download-ring.html +135 -0
- package/assets/motion/expand-card.html +137 -0
- package/assets/motion/flip-card.html +100 -0
- package/assets/motion/hold-pay.html +137 -0
- package/assets/motion/holo-card.html +130 -0
- package/assets/motion/keycap.html +92 -0
- package/assets/motion/like-jelly.html +88 -0
- package/assets/motion/liquid-progress.html +113 -0
- package/assets/motion/liquid-segment.html +127 -0
- package/assets/motion/live-capsule.html +144 -0
- package/assets/motion/marker-highlight.html +94 -0
- package/assets/motion/marquee-logos.html +110 -0
- package/assets/motion/otp-code.html +111 -0
- package/assets/motion/password-eye.html +136 -0
- package/assets/motion/ruler-slider.html +140 -0
- package/assets/motion/search-expand.html +81 -0
- package/assets/motion/send-fly.html +121 -0
- package/assets/motion/skeleton-shine.html +124 -0
- package/assets/motion/star-rate.html +98 -0
- package/assets/motion/success-check.html +114 -0
- package/assets/motion/suggest-chips.html +134 -0
- package/assets/motion/swipe-row.html +126 -0
- package/assets/motion/tabbar-bounce.html +92 -0
- package/assets/motion/tactile-controls.html +89 -0
- package/assets/motion/text-scramble.html +173 -0
- package/assets/motion/toast-stack.html +115 -0
- package/assets/motion/token-stream.html +106 -0
- package/assets/motion/voice-orb.html +144 -0
- package/assets/showcase/alley-noodles-1.webp +0 -0
- package/assets/showcase/alley-noodles-2.webp +0 -0
- package/assets/showcase/alley-noodles-3.webp +0 -0
- package/assets/showcase/autumn-sale-1.webp +0 -0
- package/assets/showcase/bold-folio-1.webp +0 -0
- package/assets/showcase/bold-folio-2.webp +0 -0
- package/assets/showcase/book-club-1.webp +0 -0
- package/assets/showcase/book-club-2.webp +0 -0
- package/assets/showcase/book-club-3.webp +0 -0
- package/assets/showcase/flower-order-1.webp +0 -0
- package/assets/showcase/little-painter-1.webp +0 -0
- package/assets/showcase/little-painter-2.webp +0 -0
- package/assets/showcase/moon-fair-1.webp +0 -0
- package/assets/showcase/nail-booking-1.webp +0 -0
- package/assets/showcase/nail-booking-2.webp +0 -0
- package/assets/showcase/nail-booking-3.webp +0 -0
- package/assets/showcase/night-run-1.webp +0 -0
- package/assets/showcase/paw-diary-1.webp +0 -0
- package/assets/showcase/paw-diary-2.webp +0 -0
- package/assets/showcase/paw-diary-3.webp +0 -0
- package/assets/showcase/pixel-planet-1.webp +0 -0
- package/assets/showcase/pixel-planet-2.webp +0 -0
- package/assets/showcase/pixel-planet-3.webp +0 -0
- package/assets/showcase/pocket-ledger-1.webp +0 -0
- package/assets/showcase/pocket-ledger-2.webp +0 -0
- package/assets/showcase/shiftloom-1.webp +0 -0
- package/assets/showcase/shiftloom-2.webp +0 -0
- package/assets/showcase/slow-breath-1.webp +0 -0
- package/assets/showcase/slow-breath-2.webp +0 -0
- package/assets/showcase/slow-breath-3.webp +0 -0
- package/assets/showcase/slow-trip-1.webp +0 -0
- package/assets/showcase/slow-trip-2.webp +0 -0
- package/assets/showcase/slow-trip-3.webp +0 -0
- package/assets/showcase/slow-weekly-1.webp +0 -0
- package/assets/showcase/stay-confirm-1.webp +0 -0
- package/assets/showcase/stove-recipes-1.webp +0 -0
- package/assets/showcase/stove-recipes-2.webp +0 -0
- package/assets/showcase/strobewatch-1.webp +0 -0
- package/assets/showcase/strobewatch-2.webp +0 -0
- package/assets/showcase/tapeworks-1.webp +0 -0
- package/assets/showcase/tapeworks-2.webp +0 -0
- package/assets/showcase/tea-brand-pitch-1.webp +0 -0
- package/assets/showcase/tea-brand-pitch-2.webp +0 -0
- package/assets/showcase/tea-brand-pitch-3.webp +0 -0
- package/assets/showcase/time-bookshop-1.webp +0 -0
- package/assets/showcase/time-bookshop-2.webp +0 -0
- package/assets/showcase/water-journey-1.webp +0 -0
- package/assets/showcase/water-journey-2.webp +0 -0
- package/assets/showcase/water-journey-3.webp +0 -0
- package/assets/showcase/weekend-go-1.webp +0 -0
- package/assets/showcase/weekend-go-2.webp +0 -0
- package/assets/showcase/weekend-go-3.webp +0 -0
- package/assets/showcase/winter-soup-1.webp +0 -0
- package/assets/showcase/year-review-1.webp +0 -0
- package/assets/showcase/year-review-2.webp +0 -0
- package/assets/showcase/year-review-3.webp +0 -0
- package/lib/browser.js +3 -1
- package/lib/bundle.js +8 -3
- package/lib/canvthumb.js +9 -6
- package/lib/client.js +7427 -2624
- package/lib/components.js +4 -2
- package/lib/core.js +762 -132
- package/lib/design-page-settings.js +48 -0
- package/lib/design-scope.js +36 -0
- package/lib/design-transactions.js +259 -0
- package/lib/drop-folder.js +25 -0
- package/lib/edits.js +125 -8
- package/lib/embedded/lvgl_shot.c +133 -0
- package/lib/embedded/qml_shot.py +66 -0
- package/lib/embedded-shot.js +400 -0
- package/lib/embedded-trust.js +76 -0
- package/lib/fonts.js +30 -21
- package/lib/frames.js +23 -23
- package/lib/gallery/css.js +9 -2
- package/lib/gallery/market-routes.js +23 -7
- package/lib/gallery/pack.js +25 -8
- package/lib/gallery/policy.js +6 -4
- package/lib/gallery/routes.js +255 -83
- package/lib/gallery/submit.js +285 -57
- package/lib/gallery/use.js +13 -4
- package/lib/handoff-embedded.js +1182 -0
- package/lib/handoff.js +212 -71
- package/lib/history.js +393 -43
- package/lib/htmlpack.js +34 -13
- package/lib/impl.js +3 -0
- package/lib/index.js +661 -136
- package/lib/inspire.js +73 -26
- package/lib/kinds.js +11 -2
- package/lib/look.js +45 -25
- package/lib/mock.js +41 -4
- package/lib/motion.js +90 -0
- package/lib/page-settings.js +103 -0
- package/lib/picker.js +348 -70
- package/lib/rules.js +85 -0
- package/lib/serve.js +154 -15
- package/lib/showcase.json +22 -0
- package/lib/styles.js +16 -7
- package/lib/system.js +19 -8
- package/lib/tool.js +2 -1
- package/lib/tweaks.js +146 -9
- package/lib/works.js +151 -19
- package/locale/auto/en.json +1 -1
- package/locale/auto/zh.json +1 -1
- package/locale/en.json +1 -1
- package/locale/offline/en.json +1 -1
- package/locale/offline/zh.json +2 -2
- package/locale/zh.json +1 -1
- package/package.json +3 -2
- package/skills/ui-design/SKILL.md +56 -46
- package/skills/ui-design/frames/dsh/frame.json +1 -1
- package/skills/ui-design/references/app.md +29 -2
- package/skills/ui-design/references/components.md +1 -1
- package/skills/ui-design/references/desktop.md +1 -1
- package/skills/ui-design/references/dshplugin.md +12 -12
- package/skills/ui-design/references/embedded.md +40 -0
- package/skills/ui-design/references/frames.md +20 -20
- package/skills/ui-design/references/miniprogram.md +2 -2
- package/skills/ui-design/references/mock.md +16 -0
- package/skills/ui-design/references/poster.md +2 -1
- package/skills/ui-design/references/tweaks.md +17 -0
- package/skills/ui-design/tokens.css +19 -5
package/lib/index.js
CHANGED
|
@@ -47,6 +47,7 @@
|
|
|
47
47
|
|
|
48
48
|
import crypto from 'node:crypto'
|
|
49
49
|
import fs from 'node:fs'
|
|
50
|
+
import { readDropFolder } from './drop-folder.js'
|
|
50
51
|
import path from 'node:path'
|
|
51
52
|
import { fileURLToPath } from 'node:url'
|
|
52
53
|
import os from 'node:os'
|
|
@@ -57,29 +58,36 @@ import { buildPack, PACK_SCREENS } from './htmlpack.js'
|
|
|
57
58
|
import { createLibrary } from './works.js'
|
|
58
59
|
import { createInspiration } from './inspire.js'
|
|
59
60
|
import { pickStyleText } from './styles.js'
|
|
61
|
+
import { baseFor, freshDir, slugOf } from './gallery/use.js'
|
|
60
62
|
import { createLibraryRoutes } from './gallery/routes.js'
|
|
61
63
|
import { createMarket } from './gallery/market.js'
|
|
62
64
|
import { createMarketRoutes } from './gallery/market-routes.js'
|
|
63
65
|
import { createPhotos, loadPhotoIndex, searchPhotos, onlyByTheme, ratioNote, isPhotoAsset, orientOf, MAX_PHOTOS } from './photos.js'
|
|
64
|
-
import { createTracker, parseTarget, findRule, allScreens, classSigs, exportOrder, KINDS } from './core.js'
|
|
66
|
+
import { scopeFor, sigOf, createTracker, parseTarget, findRule, allScreens, classSigs, exportOrder, KINDS } from './core.js'
|
|
65
67
|
import { createDrafts } from './draft.js'
|
|
66
68
|
import { createHistory } from './history.js'
|
|
69
|
+
import { canonicalPath, matchesTarget } from './design-scope.js'
|
|
67
70
|
import { createPhone } from './phone.js'
|
|
68
71
|
import { createPublicShare } from './tunnel.js'
|
|
69
72
|
import { qrMatrix } from './qr.js'
|
|
70
73
|
import { makePdf, makePptx, jpegInfo } from './doc.js'
|
|
71
74
|
import { createBrowser } from './browser.js'
|
|
72
75
|
import { createCanvasThumbs, createDirRevs } from './canvthumb.js'
|
|
73
|
-
import {
|
|
76
|
+
import { adaptive, readPages, validDevices } from './page-settings.js'
|
|
77
|
+
import { originalOf, designOf, fitSize, metaOfFile, parseMeta, sizeOf, pickScreens, measureAll, shootAll, cropIssues, formatMeasure, issueSnapshot, formatShots, whereOf, MAX_SCREENS, MAX_SIZES, MAX_SHOTS, MAX_CROPS } from './look.js'
|
|
74
78
|
import { SYSTEMS_DIR, extractSystem, listSystems, setDefault, skillSection } from './system.js'
|
|
75
79
|
import { saveFrame, listFrames, frameSection, frameDir, renameFrame, removeFrame } from './frames.js'
|
|
76
|
-
import {
|
|
80
|
+
import { readRules, saveRules, rulesNotice, RULES_MAX } from './rules.js'
|
|
81
|
+
import { listMotion, motionFile, MOTION_DIR } from './motion.js'
|
|
82
|
+
import { readTweaks, applyTweaks, lintTweaks, syncFonts, lintFonts, libFontsUsed, setVarDecl, setVarInHtml, hardColors } from './tweaks.js'
|
|
77
83
|
import { createFonts, loadFontIndex, loadFontPreviews, libFontOf, findFont, stackOf, syncFontBlock, fontBlockIds, fontPrefix, libFontIdOf, FONT_DIR } from './fonts.js'
|
|
78
84
|
import { readAnnotations, lintAnnotations, annotationFindings, annotationSection } from './annotations.js'
|
|
79
85
|
import { createImpl } from './impl.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
|
-
import { editsNotice, noticeMessage, langOf } from './edits.js'
|
|
82
|
-
import { statesOfFile, expandStates, splitStateNames, withState } from './states.js'
|
|
86
|
+
import { FRAMEWORKS, detectProject, projectFor, defaultFramework, HANDOFF_BATCH_SIZE, handoffScreens, findHandoffScreen, handoffBatch, buildHandoff, compareScreens, implUrl, implServe, IMAGE_FILE, IMAGE_MAX, defaultDest, pickedDest, within, pinRoots, frameCss } from './handoff.js'
|
|
87
|
+
import { designKey, designNotice, editsNotice, latestUser, noticeMessage, langOf, relevantDesign, startsNewDesign } from './edits.js'
|
|
88
|
+
import { statesOfFile, expandStates, splitStateNames, withState, STATE_RE } from './states.js'
|
|
89
|
+
import { createRenderConsent, projectDirectory } from './embedded-trust.js'
|
|
90
|
+
import { renderEmbedded, SHOT_DIR, CONFIRM_RENDER } from './embedded-shot.js'
|
|
83
91
|
import { MOCK_FILE, MOCK_MAX, mockOf, mockOfBuf, mockScript, saveMock } from './mock.js'
|
|
84
92
|
import { partDrift, formatDrift } from './drift.js'
|
|
85
93
|
import { expandPreview, precheckScreens, dirReader, versionReader, designComponents, formatComponents, pageUsesComponents, hasCompDir } from './comp-io.js'
|
|
@@ -113,6 +121,10 @@ const REFS_DIR = path.join(os.homedir(), '.dsh', 'cache', 'dsh-design-studio', '
|
|
|
113
121
|
const STORE_FILE = path.join(os.homedir(), '.dsh', 'cache', 'dsh-design-studio.json')
|
|
114
122
|
const SKILL_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'skills', 'ui-design')
|
|
115
123
|
const PICKER_FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), 'picker.js')
|
|
124
|
+
// 首页风格墙(2.0):每套风格几屏成品样板(tools/showcase-shots.mjs 从设计市场的模板截的),随插件发
|
|
125
|
+
const SHOWCASE_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'assets', 'showcase')
|
|
126
|
+
const ART_DIR = fileURLToPath(new URL('../assets/art/', import.meta.url))
|
|
127
|
+
const SHOWCASE_LIST = path.join(path.dirname(fileURLToPath(import.meta.url)), 'showcase.json')
|
|
116
128
|
const SKILL_RANK = 600 // 和 DSH 自带的技能同一档;用户 / 项目里同名的技能优先
|
|
117
129
|
|
|
118
130
|
/**
|
|
@@ -160,7 +172,7 @@ export const previewTool = {
|
|
|
160
172
|
'做网页、App 界面、小程序、海报、幻灯片、邮件、图表(思维导图、路线图、架构图)、DSH 插件界面这类设计时用:写好第一个 HTML 文件、或启动开发服务器后调一次就行,之后改文件会自动刷新,不用再调。' +
|
|
161
173
|
'只是把回答做成一页(对比、表格、清单、数据图表、计算器)给用户看或用时,有 show_page 工具就用它,不用这里。' +
|
|
162
174
|
'本地 HTML 写文件路径;开发服务器写地址或端口(如 http://localhost:5173)。只能预览本机页面。' +
|
|
163
|
-
'kind 说明是哪类设计,右侧按它的画幅显示(App
|
|
175
|
+
'kind 说明是哪类设计,右侧按它的画幅显示(App 套手机设备框、幻灯片 16:9 …)。' +
|
|
164
176
|
'动手设计前先加载 ui-design 技能(设计流程、规范和自查清单)。' +
|
|
165
177
|
'要做好几屏(App 的几个界面、网站的几个页面)时,每屏一个 HTML 文件放在同一个目录,右侧画布会按生成顺序并排显示,一屏一屏写就行。' +
|
|
166
178
|
'几屏重复的部分(标签栏、顶栏、卡片)抽成组件时:写 components/<名>.html,各屏用 <c-名> 引用,插件展开成普通 HTML(别自己写 JS 自定义元素或运行时注入);写法见 ui-design 技能的 references/components.md。' +
|
|
@@ -171,13 +183,14 @@ export const previewTool = {
|
|
|
171
183
|
kind: {
|
|
172
184
|
type: 'string',
|
|
173
185
|
enum: KINDS,
|
|
174
|
-
description: '设计类型:web 网页(默认)、app 手机 App 界面(390×844)、miniprogram 微信小程序(375×812
|
|
186
|
+
description: '设计类型:web 网页(默认)、app 手机 App 界面(390×844)、miniprogram 微信小程序(375×812,设备框带右上角胶囊)、tablet 平板、desktop 桌面软件(1280×800 的 Mac 窗口;Windows 软件在页面 meta 写 desktop windows)、embedded 嵌入式屏幕(单片机 LVGL / 嵌入式 Linux QML 的设备屏,默认 800×480,整屏不滚动,常见 480x272、1024x600 用 size 写,竖屏宽高对调如 480x800,小屏最小 64;先读 references/embedded.md)、poster 海报 / 社媒图(1080×1350)、slides 幻灯片(16:9)、email 邮件、diagram 路线图与导图(界面上的叫法;技术路线图 / 申报书、研究框架图、架构图、思维导图、产品路线图,默认 1600×1000,图多大画幅跟着多大)、dshplugin DSH 插件(1280×800,套 DSH 桌面端外壳,只设计插件那块:左侧栏入口 / 设置分区 / 会话标签页 / 右侧栏面板)、framed 自定义外壳(外壳库里用户自己的外壳;画幅跟外壳走,只设计槽位里那块)',
|
|
175
187
|
},
|
|
176
188
|
size: { type: 'string', description: '画幅尺寸,可选,如 1080x1920;不填按类型的默认尺寸' },
|
|
189
|
+
devices: { type: 'array', items: { type: 'string' }, description: '用户为这套设计选中的设备视口,CSS px,如 ["390x844","884x1104","820x1180"];用于初始化,已有设备设置以用户保存的为准。' },
|
|
177
190
|
screens: {
|
|
178
191
|
type: 'array',
|
|
179
192
|
items: { type: 'string' },
|
|
180
|
-
description: '开发服务器上要并排显示的几个路由,可选,如 ["/", "/login", "/settings"]。本地 HTML
|
|
193
|
+
description: '开发服务器上要并排显示的几个路由,可选,如 ["/", "/login", "/settings"]。本地 HTML 不用填:模型通知的设计目录同目录各屏并排,用户手动打开的单页保持范围',
|
|
181
194
|
},
|
|
182
195
|
}),
|
|
183
196
|
output: {
|
|
@@ -200,17 +213,37 @@ export const previewTool = {
|
|
|
200
213
|
if (target.kind === 'file' && path.basename(path.dirname(target.file)) === 'components') {
|
|
201
214
|
return { text: `${path.basename(target.file)} 是组件文件,不单独预览:打开用到它的那一屏(设计目录里的页面,比如 ${path.join(path.dirname(path.dirname(target.file)), 'index.html')})。`, url: '' }
|
|
202
215
|
}
|
|
203
|
-
const opts = { source: 'tool' }
|
|
216
|
+
const opts = { source: 'tool', model: true }
|
|
204
217
|
if (args.kind !== undefined) opts.kind = args.kind
|
|
205
218
|
if (args.size !== undefined) opts.size = args.size
|
|
206
219
|
if (args.screens !== undefined) opts.routes = args.screens
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
const
|
|
210
|
-
const
|
|
220
|
+
if (args.devices !== undefined && !validDevices(args.devices)) throw Error('设备尺寸要写成 390x844')
|
|
221
|
+
await tracker.setTarget(id, target, opts)
|
|
222
|
+
const opened = tracker.snapshot(id)
|
|
223
|
+
const actual = opened.target
|
|
224
|
+
if (target.kind === 'file' && actual?.scope === 'file' &&
|
|
225
|
+
(target.directory || canonicalPath(target.file) !== canonicalPath(actual.file))) {
|
|
226
|
+
const menu = `左上角「${path.basename(actual.file)}」菜单 →「更多」`
|
|
227
|
+
const next = target.directory ? `点「打开设计文件夹」,选择 ${target.root}。`
|
|
228
|
+
: `点「打开 HTML…」,选择 ${target.file}。要同时查看多屏,可在同一菜单点「打开设计文件夹」,选择 ${target.root}。`
|
|
229
|
+
return { text: `右侧「设计工作台」仍停在 ${actual.file},没有切换到 ${target.directory ? target.root : target.file}。请让用户在${menu}${next}`, url: opened.url }
|
|
230
|
+
}
|
|
231
|
+
const key = opened.targetKey
|
|
232
|
+
const saved = opened.pageSettings?.devices
|
|
233
|
+
const requested = args.devices === undefined ? undefined : [...new Set(args.devices)]
|
|
234
|
+
if (requested !== undefined && saved === undefined) {
|
|
235
|
+
await tracker.setView(id, { initialSettings: true, settings: { target: key, devices: requested } })
|
|
236
|
+
}
|
|
237
|
+
const devices = tracker.snapshot(id).pageSettings?.devices
|
|
238
|
+
const conflict = requested && saved && JSON.stringify(requested) !== JSON.stringify(saved)
|
|
239
|
+
? `传入的设备与设计已保存的设置不同,已保留用户设置${saved.length ? `(${saved.join('、')} CSS px)` : '(未开启多设备)'}。请按此设置继续,若需更改,请让用户在右侧「多设备」里更新。`
|
|
240
|
+
: ''
|
|
241
|
+
const what = actual.kind === 'file' ? actual.file : `localhost:${actual.port}${actual.path}`
|
|
242
|
+
const many = actual.scope === 'directory' ? '同目录再写别的 HTML 文件,会作为新的一屏并排出现。' : ''
|
|
243
|
+
const over = opened.hidden ? `右侧最多显示 ${opened.screens.length} 屏,还有 ${opened.hidden} 屏没显示。` : ''
|
|
211
244
|
return {
|
|
212
|
-
text: `已在右侧「设计工作台」打开 ${what}。${target.kind === 'file' ? '这个目录里的文件一改就自动刷新。' + many : '开发服务器的热更新照常生效。'}${over}${target.kind === 'file' ? compLine(id) : ''}`,
|
|
213
|
-
url:
|
|
245
|
+
text: `已在右侧「设计工作台」打开 ${what}。${target.kind === 'file' ? (actual.scope === 'file' ? '这个文件一改就自动刷新。' : '这个目录里的文件一改就自动刷新。' + many) : '开发服务器的热更新照常生效。'}${over}${conflict}${devices?.length ? '适配设备:'+devices.join('、')+' CSS px。' : ''}${target.kind === 'file' ? compLine(id) : ''}`,
|
|
246
|
+
url: opened.url,
|
|
214
247
|
}
|
|
215
248
|
},
|
|
216
249
|
}
|
|
@@ -225,7 +258,9 @@ function designFor(id) {
|
|
|
225
258
|
const sc0 = (snap.screens || [])[0]
|
|
226
259
|
const first = t && t.kind === 'file' ? path.join(path.dirname(t.file), (sc0 && sc0.key) || path.basename(t.file)) : ''
|
|
227
260
|
const focus = t && t.kind === 'file' ? t.file : ''
|
|
228
|
-
|
|
261
|
+
const row = snap.pageSettings?.screens?.[snap.focus]
|
|
262
|
+
const declared = () => metaOfFile(focus) || (row?.original ? row.original.kind + ' ' + row.original.size : '') || (first && first !== focus ? metaOfFile(first) : '')
|
|
263
|
+
return { snap, ...(row?.followSource ? originalOf(snap, declared()) : designOf({ ...snap, ...row?.current }, declared)) }
|
|
229
264
|
}
|
|
230
265
|
|
|
231
266
|
/** 共用部件各屏写得不一样(#30 第 1 步):这套设计(本地文件)所有屏比一遍;没有就是 null */
|
|
@@ -234,7 +269,7 @@ function driftOf(id) {
|
|
|
234
269
|
const t = studio.tracker.snapshot(id).target
|
|
235
270
|
if (!t || t.kind !== 'file') return null
|
|
236
271
|
const root = t.root || path.dirname(t.file)
|
|
237
|
-
const keys =
|
|
272
|
+
const keys = scopeFor(t).pages
|
|
238
273
|
if (keys.length < 2) return null
|
|
239
274
|
const stamp = keys.slice(0, 600).map((k) => { try { const s = fs.statSync(path.join(root, k)); return `${k}:${s.mtimeMs}:${s.size}` } catch { return '' } }).join('|')
|
|
240
275
|
const hit = driftSeen.get(root)
|
|
@@ -254,7 +289,7 @@ function compOf(id) {
|
|
|
254
289
|
const t = studio.tracker.snapshot(id).target
|
|
255
290
|
if (!t || t.kind !== 'file') return null
|
|
256
291
|
const root = t.root || path.dirname(t.file)
|
|
257
|
-
const keys =
|
|
292
|
+
const keys = scopeFor(t).pages.slice(0, 600)
|
|
258
293
|
// 组件文件、mock.json,还有页面引的本地脚本(接不接管 <c-…> 要看它们有没有自己注册 c-*)
|
|
259
294
|
const files = [...keys, MOCK_FILE, ...(() => { try { return fs.readdirSync(path.join(root, 'components')).map((n) => 'components/' + n) } catch { return [] } })(),
|
|
260
295
|
...(() => { try { return fs.readdirSync(root).filter((n) => /\.m?js$/i.test(n)) } catch { return [] } })()]
|
|
@@ -327,10 +362,30 @@ const toolSession = (exec, what) => {
|
|
|
327
362
|
}
|
|
328
363
|
|
|
329
364
|
/** check_design 工具:在无头浏览器里按真实尺寸量每一屏(没有浏览器就让右侧栏量),问题清单和测量数字交回给模型 */
|
|
365
|
+
export const readDesignChangesTool = {
|
|
366
|
+
name: 'read_design_changes',
|
|
367
|
+
description: '读取当前会话中指定设计的未读手改。收到设计工作台通知时,继续设计、交接或写入之前先调用。返回当前文件内容、移除状态和页面设置。返回 more 时继续读取。',
|
|
368
|
+
parameters: specToJsonSchema({
|
|
369
|
+
targetKey: { type: 'string', required: true, description: '当前设计工作台通知中的 targetKey' },
|
|
370
|
+
from: { type: 'integer', minimum: 1, description: '开始序号,默认从最早的未读记录开始' },
|
|
371
|
+
limit: { type: 'integer', minimum: 1, maximum: 10, description: '每批最多读取的记录数' },
|
|
372
|
+
}),
|
|
373
|
+
output: {
|
|
374
|
+
schema: { type: 'object' },
|
|
375
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
|
|
376
|
+
},
|
|
377
|
+
async execute(args, exec) {
|
|
378
|
+
const id = exec?.agent?.session?.id
|
|
379
|
+
if (!id || !studio.tracker || !args.targetKey) throw Error('缺少已打开的设计范围')
|
|
380
|
+
await studio.tracker.readySnapshot(id)
|
|
381
|
+
return studio.tracker.readChanges(id, args)
|
|
382
|
+
},
|
|
383
|
+
}
|
|
384
|
+
|
|
330
385
|
export const checkTool = {
|
|
331
386
|
name: 'check_design',
|
|
332
387
|
description:
|
|
333
|
-
'
|
|
388
|
+
'量一下右侧「设计工作台」里的设计(默认逐屏检查所选的全部设备,sizes 可指定设备尺寸):文字被截断 / 超出框、文字叠在一起、对比度不够、点击区太小、字太小、字号太杂、超出屏幕、图片被拉变形 / 没加载出来、一行太长、短字断行、' +
|
|
334
389
|
'固定的顶栏 / 底栏压住内容(滚到底也看不全)或贴得太近、页面脚本报错、样式表 / 脚本 / 字体没载出来、跳到不存在的页面。' +
|
|
335
390
|
'在电脑上用无头浏览器按真实尺寸打开每一屏量,和右侧栏怎么显示无关;返回量了哪几屏、每种尺寸下页面多高、固定栏离内容多远,和问题清单(哪一屏、哪个元素的 CSS 选择器、具体数字)。' +
|
|
336
391
|
'写完一批屏、或改完之后调一次,照清单改源文件;要看小屏 / 大屏就给 sizes(如 ["375x667", "430x932"],或只写宽度)。比另开浏览器截图自查准,也省得多;要看长什么样用 look_design。' +
|
|
@@ -338,7 +393,7 @@ export const checkTool = {
|
|
|
338
393
|
'要先用 preview_page 打开过页面。',
|
|
339
394
|
parameters: specToJsonSchema({
|
|
340
395
|
screens: { type: 'array', items: { type: 'string' }, description: '量哪几屏:文件名(home.html 或 home)或开发服务器的路由;不填量全部。写了几个状态的屏每个状态都量,只量某个状态写 order.html?state=paid' },
|
|
341
|
-
sizes: { type: 'array', items: { type: 'string' }, description: '按哪几种尺寸量,如 ["375x667", "390x844", "430x932"],或只写宽度 ["320", "375"]
|
|
396
|
+
sizes: { type: 'array', items: { type: 'string' }, description: '按哪几种尺寸量,如 ["375x667", "390x844", "430x932"],或只写宽度 ["320", "375"](高按机型);不填检查页面设置选中的全部设备。显式指定最多 4 种' },
|
|
342
397
|
dark: { type: 'boolean', description: '切到深色量(页面带深色样式时)' },
|
|
343
398
|
images: { type: 'boolean', description: `严重问题附局部截图(默认附,最多 ${MAX_CROPS} 张);false 只要文字` },
|
|
344
399
|
}),
|
|
@@ -370,7 +425,19 @@ export const checkTool = {
|
|
|
370
425
|
const ex = expandStates(pick0.list, stOf, { only: sn.only })
|
|
371
426
|
const pick = { ...pick0, list: ex.list }
|
|
372
427
|
const sizes = want.sizes.length ? want.sizes : [await fitted(b, design, sn.names)]
|
|
373
|
-
const
|
|
428
|
+
const pages = snap.pageSettings || {}
|
|
429
|
+
const targets = pick.list.map(sc => {
|
|
430
|
+
const key = sc.base || sc.key
|
|
431
|
+
const row = pages.screens?.[key]
|
|
432
|
+
const root = snap.target?.kind === 'file' && (snap.target.root || path.dirname(snap.target.file))
|
|
433
|
+
const declared = parseMeta(root && path.basename(key) === key ? metaOfFile(path.join(root, key)) : '')
|
|
434
|
+
const type = row?.current?.kind || snap.kind || declared.kind || row?.original?.kind || kind
|
|
435
|
+
const devices = adaptive(type) && validDevices(pages.devices) && pages.devices.length ? pages.devices : null
|
|
436
|
+
const configured = [row?.current?.size, snap.size, declared.size, row?.original?.size].find(v => sizeOf(v, type))
|
|
437
|
+
const viewports = devices ? devices.map(s => s.split('x').map(Number)) : configured ? [configured.split('x').map(Number)] : sizes
|
|
438
|
+
return { ...sc, checkKind: type, checkSizes: want.sizes.length ? sizes : viewports }
|
|
439
|
+
})
|
|
440
|
+
const rows = await measureAll(b, { screens: targets, sizes, kind, dark: !!a.dark, annots: annotsByPage(anAt.ann), locate: (items) => locateRules(studio.tracker.stateOf(id), items) })
|
|
374
441
|
if (rows.some((r) => !r.error)) {
|
|
375
442
|
// 同一个会话上次量的结果:这次比一比修好了几个、新出了几个
|
|
376
443
|
const prev = lastChecks.get(id) || null
|
|
@@ -381,7 +448,7 @@ export const checkTool = {
|
|
|
381
448
|
}
|
|
382
449
|
const kept = crops.length ? await keepImages(ctx, id, crops) : null
|
|
383
450
|
if (kept && !kept.images) crops = [] // 存进附件库失败:不提图
|
|
384
|
-
let text = formatMeasure(rows, { sizes, where: whereOf(snap), missing: pick.missing, more: pick.more, dark: !!a.dark, prev, crops })
|
|
451
|
+
let text = formatMeasure(rows, { sizes: [...new Map(targets.flatMap(sc => sc.checkSizes).map(s => [s.join('x'), s])).values()], where: whereOf(snap), missing: pick.missing, more: pick.more, dark: !!a.dark, prev, crops })
|
|
385
452
|
const next = new Map(prev || [])
|
|
386
453
|
for (const [k, v] of issueSnapshot(rows, !!a.dark)) next.set(k, v)
|
|
387
454
|
lastChecks.delete(id)
|
|
@@ -612,11 +679,11 @@ export const systemTool = {
|
|
|
612
679
|
export const frameTool = {
|
|
613
680
|
name: 'save_frame',
|
|
614
681
|
description:
|
|
615
|
-
'
|
|
616
|
-
'用户要给某个软件 / 浏览器插件 /
|
|
617
|
-
'它检查 frame.json
|
|
682
|
+
'把写好的「外壳」存进用户的外壳库(~/.dsh/design-frames/<id>/),以后做设计原样套上、只改槽位。' +
|
|
683
|
+
'用户要给某个软件 / 浏览器插件 / 平台做界面、说「照这张截图做个外壳」「套上 XX 的外壳」时:先读 ui-design 技能的 references/frames.md,在一个文件夹里写好 frame.json、每个位置一个 HTML(根元素 data-frame="<id>/<位置>",槽位 data-slot,必须有 main)和样式,再调它。' +
|
|
684
|
+
'它检查 frame.json 和槽位对不对,用无头浏览器打开每个位置(浅色、深色)算外壳指纹(体检「外壳被改动」靠它),截图回给你核对;同 id 再存一次就覆盖。',
|
|
618
685
|
parameters: specToJsonSchema({
|
|
619
|
-
dir: { type: 'string', required: true, description: '
|
|
686
|
+
dir: { type: 'string', required: true, description: '写好外壳的文件夹(里面有 frame.json),绝对路径或相对会话目录' },
|
|
620
687
|
}),
|
|
621
688
|
output: {
|
|
622
689
|
schema: {
|
|
@@ -631,7 +698,7 @@ export const frameTool = {
|
|
|
631
698
|
const session = exec && exec.agent && exec.agent.session
|
|
632
699
|
const id = (session && session.id) || ''
|
|
633
700
|
const a = args || {}
|
|
634
|
-
if (typeof a.dir !== 'string' || !a.dir.trim()) return { text: '没给 dir
|
|
701
|
+
if (typeof a.dir !== 'string' || !a.dir.trim()) return { text: '没给 dir:写好外壳的文件夹(里面有 frame.json)。' }
|
|
635
702
|
const cwd = studio.tracker && id ? studio.tracker.cwdOf(id) : os.homedir()
|
|
636
703
|
const src = resolvePath(a.dir, cwd)
|
|
637
704
|
let st = null
|
|
@@ -642,13 +709,13 @@ export const frameTool = {
|
|
|
642
709
|
const htmls = fs.readdirSync(src).filter((n) => /\.html?$/i.test(n)).slice(0, 500)
|
|
643
710
|
const rd = dirReader(src)
|
|
644
711
|
const hit = htmls.find((n) => { try { return pageUsesComponents(fs.readFileSync(path.join(src, n), 'utf8'), rd) } catch { return false } })
|
|
645
|
-
if (hit) return { text:
|
|
712
|
+
if (hit) return { text: `外壳里不能用组件(<c-…>):${hit} 用了组件。外壳存的是单个页面,把组件的内容直接写进外壳页面再存。` }
|
|
646
713
|
} catch { /* 读不了:交给 saveFrame 报 */ }
|
|
647
714
|
let r
|
|
648
715
|
try {
|
|
649
716
|
r = await saveFrame({ browser: studio.browser, src })
|
|
650
717
|
} catch (e) {
|
|
651
|
-
return { text:
|
|
718
|
+
return { text: `外壳没存:${String((e && e.message) || e).slice(0, 300)}` }
|
|
652
719
|
}
|
|
653
720
|
if (!r.images.length) return { text: r.text }
|
|
654
721
|
const kept = await keepImages(ctx, id || 'frame', r.images, true)
|
|
@@ -674,13 +741,13 @@ const resolvePath = (p, cwd) => path.resolve(cwd, String(p).trim().replace(/^~(?
|
|
|
674
741
|
/** handoff_design 工具:把设计整理成交接包(说明 + 每屏截图),照它做成真项目的代码 */
|
|
675
742
|
export const handoffTool = {
|
|
676
743
|
name: 'handoff_design',
|
|
677
|
-
description:
|
|
744
|
+
description: '列出设计已选择的响应式设备及逐屏验收尺寸。' +
|
|
678
745
|
'把右侧「设计工作台」里的设计(本地 HTML 那几屏)整理成交接包,准备做成真项目的代码:写好 <设计目录>/handoff/HANDOFF.md(每屏的文件、建议路由、跳转、设计变量、几屏共用该抽成组件的部分、交互和状态、调节滑块、素材、做法和验收),和每屏从上到下的截图。' +
|
|
679
746
|
'HANDOFF.md 一直列全部屏。截图和逐屏说明分批补齐,用 batch 继续下一批,或用 screens 指定要截的屏。' +
|
|
680
|
-
'用户说「转成代码」「做成真的项目」「用 React / Vue / uni-app
|
|
681
|
-
'framework:same 跟目标目录现有项目一样(认得出框架时默认,uni-app(含 HBuilderX 建的、没有 package.json 的)、Taro
|
|
747
|
+
'用户说「转成代码」「做成真的项目」「用 React / Vue / uni-app 做出来」「做成小程序」「转成 LVGL / QML」「做到单片机 / 板子上」时先调它,读 HANDOFF.md 照着做;每做完一屏用 compare_design 和设计稿比一遍,差异降到 3% 以下再做下一屏(原生小程序在浏览器里跑不起来,照 HANDOFF.md 说的请用户在微信开发者工具里看;LVGL / QML 的 url 填工程目录,插件自己在电脑上编、出图再比,照 HANDOFF.md 先写好切屏入口)。' +
|
|
748
|
+
'framework:same 跟目标目录现有项目一样(认得出框架时默认,uni-app(含 HBuilderX 建的、没有 package.json 的)、Taro、微信原生小程序、LVGL 工程(读得出版本)、Qt Quick 工程也认得出)、react、vue、next、html、uniapp、weapp、lvgl、qml;dest:代码放哪个目录(不填:会话目录是项目就放进去,不是就新建 <设计名>-app)。要先用 preview_page 打开过设计。',
|
|
682
749
|
parameters: specToJsonSchema({
|
|
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' },
|
|
750
|
+
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)、lvgl(LVGL C 代码,STM32 等单片机)、qml(Qt Quick / QML,嵌入式 Linux)。不填:目标目录(或它所在的项目)认得出框架就 same,没有 package.json 的纯 HTML 站点 html,小程序的设计 uniapp,嵌入式屏幕的设计 lvgl,别的 react' },
|
|
684
751
|
dest: { type: 'string', description: '代码放哪:现有项目的目录(或它里面的子目录),或要新建的项目目录(绝对路径或相对会话目录)。不填:会话目录有 package.json 就放进去,没有就新建 <设计名>-app(设计目录在会话目录下就建在会话目录里,不然建在设计目录旁边)' },
|
|
685
752
|
batch: { type: 'integer', minimum: 1, description: `截图批次,从 1 开始,每批最多 ${HANDOFF_BATCH_SIZE} 屏,默认第 1 批。填了 screens 时按指定的屏截` },
|
|
686
753
|
screens: { type: 'array', items: { type: 'string' }, description: `按文件名指定本次要截图和补说明的屏,最多 ${HANDOFF_BATCH_SIZE} 屏` },
|
|
@@ -703,7 +770,7 @@ export const handoffTool = {
|
|
|
703
770
|
if (!t || t.kind !== 'file') return { text: '现在预览的是开发服务器上的页面,它已经是代码了:直接在那个项目里改;要比对设计稿就先用 preview_page 打开设计的 HTML 文件。' }
|
|
704
771
|
const design = designFor(id)
|
|
705
772
|
const { kind } = design
|
|
706
|
-
const catalog = handoffScreens(t.root, snap.origin)
|
|
773
|
+
const catalog = handoffScreens(t.root, snap.origin, scopeFor(t).pages)
|
|
707
774
|
const pick = handoffBatch(catalog, { batch: a.batch, names: a.screens })
|
|
708
775
|
if (pick.error) return { text: pick.error }
|
|
709
776
|
if (!pick.list.length) return { text: `没找到要转的屏${pick.missing.length ? ':' + pick.missing.join('、') : ''}。目录里有 ${catalog.length} 屏,可用 batch=1 查看交接清单。` }
|
|
@@ -713,20 +780,23 @@ export const handoffTool = {
|
|
|
713
780
|
if (within(dest, t.root)) return { text: `代码别放进设计目录(${t.root})里:设计稿留着做对比。换一个目录。` }
|
|
714
781
|
const project = projectFor(dest)
|
|
715
782
|
const framework = typeof a.framework === 'string' && (a.framework === 'same' || FRAMEWORKS[a.framework]) ? a.framework : defaultFramework(project, kind)
|
|
716
|
-
if (framework === 'same' &&
|
|
783
|
+
if (kind === 'embedded' && !(framework === 'lvgl' || framework === 'qml' || (framework === 'same' && (project.framework === 'lvgl' || project.framework === 'qml')))) return { text: `这套是嵌入式屏幕的设计,只能转成 LVGL(单片机)或 QML(嵌入式 Linux):framework 选 lvgl 或 qml${framework === 'same' && project.framework ? `(${dest} 是 ${project.label || project.framework} 项目,跟它一样不行)` : ''}。` }
|
|
784
|
+
if (framework === 'same' && !project.framework) return { text: `${dest} 里没有认得出的项目(package.json 里没有 React / Vue / Next / uni-app …,也不是 HBuilderX、微信原生小程序、LVGL 或 Qt Quick 的工程):framework 选 react、vue、next、html、uniapp、weapp、lvgl 或 qml。` }
|
|
717
785
|
let r
|
|
718
786
|
try {
|
|
719
787
|
const b = studio.browser
|
|
720
788
|
const samples = a.screens?.length ? pick.list : pick.list.slice(0, 6)
|
|
721
789
|
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) })
|
|
790
|
+
r = await buildHandoff(b, { pageSettings: snap.pageSettings, root: t.root, output: t.scope === 'file' ? path.join(REFS_DIR, '..', 'handoff', t.designId) : undefined, catalog, selection: pick, kind, size, framework, dest, project, system: t.directory ? systemOfDir(t.root) : '', annotations: studio.annotations > 0 ? readAnnotations(t.root) : null, tuned: studio.tracker.versions(id) })
|
|
723
791
|
} catch (e) {
|
|
724
792
|
return { text: `没写成交接包:${String((e && e.message) || e).slice(0, 200)}` }
|
|
725
793
|
}
|
|
726
794
|
studio.tracker.markHandoff(id, t.root) // 右侧栏的步骤条:交接包写好了,模型在照着做
|
|
727
795
|
// 原生小程序跑不了网页版:比不了,照 HANDOFF.md 请用户在微信开发者工具里看
|
|
728
|
-
const
|
|
729
|
-
const verify =
|
|
796
|
+
const target = framework === 'same' ? project.framework : framework
|
|
797
|
+
const verify = target === 'weapp' ? '每屏做完请用户在微信开发者工具里看'
|
|
798
|
+
: target === 'lvgl' || target === 'qml' ? `每屏做完 compare_design 的 url 填工程目录 ${dest}(插件自己编、出图;先照 HANDOFF.md 写好${target === 'lvgl' ? ' ui/tools/ui_dev.c 里的 ui_dev_show' : ' Main.qml 里的 devShow'})`
|
|
799
|
+
: '每屏做完用 compare_design 比'
|
|
730
800
|
const batch = pick.batch ? `第 ${pick.batch} 批` : '本次指定'
|
|
731
801
|
const lines = [
|
|
732
802
|
`${batch} ${r.rows.length} 屏(${r.rows.map((row) => row.key).join('、')}),新增或更新 ${r.shots} 张截图。`,
|
|
@@ -805,7 +875,7 @@ export const photoTool = {
|
|
|
805
875
|
}
|
|
806
876
|
} catch (e) {
|
|
807
877
|
studio.log(e)
|
|
808
|
-
if (e && e.code === 'off') return { text: '
|
|
878
|
+
if (e && e.code === 'off') return { text: '「素材库不联网」开着,照片库下载不了。这次用 CSS / SVG 画,并告诉用户:关掉这个开关就能用自带照片。' }
|
|
809
879
|
if (e && e.code === 'link') return { text: `${path.join(dir, 'assets')} 指向了这个文件夹外面,图不能放那儿。` }
|
|
810
880
|
if (e && /^(EACCES|EPERM|EROFS|ENOTDIR|EEXIST|ENOSPC)$/.test(e.code || '')) return { text: `${path.join(dir, 'assets')} 写不进去(${e.code})。换一个文件夹,或者这次用 CSS / SVG 画。` }
|
|
811
881
|
return { text: '照片库这会儿下载不了(网络问题)。这次先用 CSS / SVG 画,并告诉用户这里需要一张什么样的照片,稍后可以再试。' }
|
|
@@ -874,7 +944,7 @@ export const fontTool = {
|
|
|
874
944
|
await lib.provide(dir, [f], allowed)
|
|
875
945
|
} catch (e) {
|
|
876
946
|
studio.log(e)
|
|
877
|
-
if (e && e.code === 'off') return { text: '
|
|
947
|
+
if (e && e.code === 'off') return { text: '「素材库不联网」开着,字体库下载不了。这次用系统字体栈,并告诉用户:关掉这个开关就能用字体库。' }
|
|
878
948
|
if (e && e.code === 'link') return { text: `${path.join(dir, FONT_DIR)} 指向了这个文件夹外面,字体不能放那儿。` }
|
|
879
949
|
if (e && /^(EACCES|EPERM|EROFS|ENOTDIR|EEXIST|ENOSPC)$/.test(e.code || '')) return { text: `${path.join(dir, FONT_DIR)} 写不进去(${e.code})。这次用系统字体栈。` }
|
|
880
950
|
return { text: '字体库这会儿下载不了(网络问题)。这次先用系统字体栈,稍后可以再试。' }
|
|
@@ -946,14 +1016,16 @@ export const compareTool = {
|
|
|
946
1016
|
description:
|
|
947
1017
|
'把做出来的页面和右侧「设计工作台」里的设计稿比一比:按同样尺寸在无头浏览器里各截一张,逐像素比,回一张「设计稿 | 做出来的 | 差异」拼图(差得多的地方红框标号)、差了百分之几,和每块差异在两边分别是哪个元素。' +
|
|
948
1018
|
'照设计稿写代码时每做完一屏调一次(url 给开发服务器上那一页的地址,如 http://localhost:5173/login),照差异改到 3% 以下。at=bottom 比滚到底的样子。要先用 preview_page 打开过设计。' +
|
|
949
|
-
'
|
|
1019
|
+
'LVGL、QML:url 填工程目录(HANDOFF.md 所在、有 ui/ 或 qml/ 的那个),插件自己在电脑上编一遍、出图再比(LVGL 要电脑上有 gcc / clang,QML 要 Python 装了 PySide6);电脑上出不了图时,url 填一张和屏幕一样大的截图文件(PNG / BMP,模拟器或板子上截的)。' +
|
|
1020
|
+
'设计稿套了外壳(DSH 插件、外壳库)时只比外壳里的 main 槽位:外壳是宿主画的,做出来的页面就是槽位那块本身,会按槽位的尺寸打开。',
|
|
950
1021
|
parameters: specToJsonSchema({
|
|
951
|
-
url: { type: 'string', required: true, description: '做出来的页面:本机地址(http://localhost:5173/login,或端口 5173
|
|
1022
|
+
url: { type: 'string', required: true, description: '做出来的页面:本机地址(http://localhost:5173/login,或端口 5173)、本地 HTML 文件;LVGL / QML 填工程目录(插件自己编、出图),或一张截图文件(PNG / BMP / JPG)' },
|
|
952
1023
|
screen: { type: 'string', description: '和设计稿的哪一屏比(文件名,如 login 或 login.html);不填用右侧正在看的那屏' },
|
|
1024
|
+
state: { type: 'string', description: '这屏写了几个状态(<meta name="dsh-states">)时比哪个状态:设计稿切到这个状态;LVGL / QML 工程也按这个状态出图(传给 ui_dev_show / devShow)。不填是默认状态' },
|
|
953
1025
|
size: { type: 'string', description: '尺寸,如 375x667 或只写宽度;不填按设计的尺寸' },
|
|
954
1026
|
at: { type: 'string', enum: ['top', 'bottom'], description: 'top 顶上一屏(默认)、bottom 滚到底' },
|
|
955
1027
|
dark: { type: 'boolean', description: '比深色' },
|
|
956
|
-
whole: { type: 'boolean', description: '
|
|
1028
|
+
whole: { type: 'boolean', description: '设计稿套了外壳时默认只比 main 槽位;做出来的页面自己也套了同一个外壳(整屏和设计稿一样大)才填 true,整屏比' },
|
|
957
1029
|
}),
|
|
958
1030
|
output: {
|
|
959
1031
|
schema: {
|
|
@@ -967,7 +1039,7 @@ export const compareTool = {
|
|
|
967
1039
|
async execute(args, exec, ctx) {
|
|
968
1040
|
const id = toolSession(exec, '比对')
|
|
969
1041
|
const a = args || {}
|
|
970
|
-
const out = await runCompare(id, a)
|
|
1042
|
+
const out = await runCompare(id, a, { exec, approval: ctx?.get?.('approval') })
|
|
971
1043
|
if (!out.r) return { text: out.text }
|
|
972
1044
|
keepImpl(id, out, 'model', !!a.size)
|
|
973
1045
|
if (!out.r.jpg) return { text: out.r.text } // 没截图就停下了(套了外框但槽位露不出来)
|
|
@@ -982,11 +1054,12 @@ export const compareTool = {
|
|
|
982
1054
|
export const isDesignFile = (at, u, catalog) => {
|
|
983
1055
|
if (u.protocol !== 'file:' || !at.snap.target || at.snap.target.kind !== 'file') return false
|
|
984
1056
|
try {
|
|
985
|
-
const
|
|
986
|
-
|
|
1057
|
+
const target = at.snap.target
|
|
1058
|
+
const rel = path.relative(path.resolve(target.root || at.root), fileURLToPath(u)).split(path.sep).join('/')
|
|
1059
|
+
return catalog ? catalog.some((sc) => sc.key === rel) : scopeFor(target).pages.includes(rel)
|
|
987
1060
|
} catch { return false }
|
|
988
1061
|
}
|
|
989
|
-
export const implRoot = (snap) => (snap && snap.target ? (snap.target.kind === 'file' ? snap.target.root : `proxy:${snap.target.port}`) : '')
|
|
1062
|
+
export const implRoot = (snap) => (snap && snap.target ? (snap.target.kind === 'file' ? (snap.target.scope === 'file' ? snap.target.designId : snap.target.root) : `proxy:${snap.target.port}`) : '')
|
|
990
1063
|
|
|
991
1064
|
/**
|
|
992
1065
|
* 比一屏(compare_design 和右侧栏「和做出来的比」里的「重新比」共用)
|
|
@@ -994,7 +1067,8 @@ export const implRoot = (snap) => (snap && snap.target ? (snap.target.kind === '
|
|
|
994
1067
|
* @returns { text } 没比成;{ r, sc, impl, want, opts, root } 比完了(r.jpg 为空 = 套了外框但槽位露不出来,r.text 说了怎么办;
|
|
995
1068
|
* root:开始比时在看的设计,比的时候换了设计也记回这一份)
|
|
996
1069
|
*/
|
|
997
|
-
|
|
1070
|
+
const renderConsent = createRenderConsent()
|
|
1071
|
+
async function runCompare(id, a, access = {}) {
|
|
998
1072
|
const snap = studio.tracker.snapshot(id)
|
|
999
1073
|
const root = implRoot(snap)
|
|
1000
1074
|
if (!snap.url) return { text: '还没有在预览的设计稿:先用 preview_page 打开设计文件,再比。' }
|
|
@@ -1002,7 +1076,7 @@ async function runCompare(id, a) {
|
|
|
1002
1076
|
if (!b || !b.available()) return { text: '这台电脑上没找到 Chrome / Edge(比对要用无头浏览器截图),比不了。' }
|
|
1003
1077
|
const design = designFor(id)
|
|
1004
1078
|
const { kind } = design
|
|
1005
|
-
const catalog = snap.target?.kind === 'file' ? handoffScreens(root, snap.origin) : null
|
|
1079
|
+
const catalog = snap.target?.kind === 'file' ? handoffScreens(snap.target.root, snap.origin, scopeFor(snap.target).pages) : null
|
|
1006
1080
|
// 指定了哪屏就只认那屏,找不到就说(别悄悄拿第一屏比,结果对不上号);没指定才用正在看的 / 第一屏
|
|
1007
1081
|
const asked = typeof a.screen === 'string' && a.screen.trim()
|
|
1008
1082
|
const sc = catalog
|
|
@@ -1012,7 +1086,7 @@ async function runCompare(id, a) {
|
|
|
1012
1086
|
const all = catalog || snap.screens || []
|
|
1013
1087
|
return { text: `没找到设计稿的这一屏:${asked || '(没有屏)'}。共 ${all.length} 屏:${all.slice(0, HANDOFF_BATCH_SIZE).map((x) => x.key).join('、')}${all.length > HANDOFF_BATCH_SIZE ? ' 等,可用 handoff_design 查看完整清单' : ''}。` }
|
|
1014
1088
|
}
|
|
1015
|
-
const want = Array.isArray(a.size) ? a.size : a.size
|
|
1089
|
+
const want = a.size ? sizeOf(Array.isArray(a.size) ? a.size.join('x') : a.size, kind) : !catalog
|
|
1016
1090
|
? await fitted(b, design, asked ? [a.screen] : null)
|
|
1017
1091
|
: design.auto ? await fitSize(b, asked ? [sc] : catalog.slice(0, 6), kind, design.size) : design.size
|
|
1018
1092
|
if (!want) return { text: `认不出尺寸「${String(a.size).slice(0, 20)}」:写成 375x667,或只写宽度 375。` }
|
|
@@ -1021,24 +1095,116 @@ async function runCompare(id, a) {
|
|
|
1021
1095
|
try { cwd = studio.sessionCwd ? await studio.sessionCwd(id) : '' } catch { cwd = '' }
|
|
1022
1096
|
if (!cwd) cwd = studio.tracker.cwdOf(id)
|
|
1023
1097
|
let impl
|
|
1024
|
-
try { impl = implUrl(a.url, cwd) } catch (e) { return { text: e.message } }
|
|
1098
|
+
try { impl = implUrl(a.url, cwd, kind) } catch (e) { return { text: e.message } }
|
|
1025
1099
|
if ((snap.origin && impl.startsWith(snap.origin + '/')) || isDesignFile({ snap, root }, new URL(impl), catalog)) return { text: '这个地址是设计稿自己(设计工作台的预览或设计目录里的文件),给做出来的那个项目的地址。' }
|
|
1026
|
-
|
|
1100
|
+
// 状态:设计稿那屏切过去;嵌入式工程出图时也传过去
|
|
1101
|
+
const st = typeof a.state === 'string' ? a.state.trim() : ''
|
|
1102
|
+
if (st) {
|
|
1103
|
+
if (!STATE_RE.test(st)) return { text: `状态名「${st.slice(0, 40)}」不对:只认英文、数字、- _(照设计里 <meta name="dsh-states"> 写的)。` }
|
|
1104
|
+
const states = snap.target?.kind === 'file' ? statesOfFile(path.join(root, sc.key)).map((x) => x.name) : null
|
|
1105
|
+
if (states && !states.includes(st)) return { text: states.length ? `${sc.key} 没有「${st}」这个状态,写了的是:${states.join('、')}。` : `${sc.key} 没写状态(<meta name="dsh-states">),不用填 state。` }
|
|
1106
|
+
}
|
|
1107
|
+
const opts = { at: a.at === 'bottom' ? 'bottom' : 'top', dark: !!a.dark, whole: a.whole === true, state: st }
|
|
1108
|
+
// LVGL / QML 工程目录:在电脑上编一遍出图(图放系统临时目录,不往工程里写),再拿图比
|
|
1109
|
+
let rendered = null
|
|
1110
|
+
const implDir = /^file:/i.test(impl) ? fileURLToPath(new URL(impl)) : ''
|
|
1111
|
+
if (implDir && fs.statSync(implDir, { throwIfNoEntry: false })?.isDirectory()) {
|
|
1112
|
+
const name = sc.key.replace(/\.html?$/i, '')
|
|
1113
|
+
// 每次出图用自己的文件名:中文屏名、「home」的 alarm 状态和「home-alarm」屏都不会撞名,同时比也不会互相覆盖
|
|
1114
|
+
const shotDir = path.join(SHOT_DIR, crypto.createHash('sha1').update(implDir).digest('hex').slice(0, 12))
|
|
1115
|
+
const prefix = (name.replace(/[^\w.-]+/g, '_').slice(0, 40) || 'screen') + '-' + crypto.createHash('sha1').update(sc.key + '\0' + st).digest('hex').slice(0, 8) + '-'
|
|
1116
|
+
const out = path.join(shotDir, prefix + Date.now().toString(36) + crypto.randomBytes(3).toString('hex'))
|
|
1117
|
+
const workspace = await studio.workspaceOf?.(id) || access.exec?.agent?.session?.header?.cwd
|
|
1118
|
+
rendered = await oneAtATime(implDir, () => renderEmbedded({ dir: implDir, w: want[0], h: want[1], screen: name, state: st, out }, {
|
|
1119
|
+
workspace, authorize: async (project, commands) => {
|
|
1120
|
+
const scope = [id, root, sc.key]
|
|
1121
|
+
const consent = renderConsent(project, scope, access.panel ? access.ticket : undefined)
|
|
1122
|
+
if (consent.allowed) return consent
|
|
1123
|
+
const prompt = { dir: project.dir, commands, ticket: consent.ticket }
|
|
1124
|
+
if (access.panel) return { prompt }
|
|
1125
|
+
if (access.approval?.request && access.exec?.agent) {
|
|
1126
|
+
const { agent, callId, signal } = access.exec
|
|
1127
|
+
const reason = [`在本机编译或运行工程:${project.dir}`, ...commands].join('\n')
|
|
1128
|
+
const outcome = await access.approval.request({ agent, callId, signal, toolName: 'compare_design', reason })
|
|
1129
|
+
if (outcome === 'allowed-once' && !signal?.aborted) return { allowed: true }
|
|
1130
|
+
if (outcome !== 'unavailable' || signal?.aborted) return { allowed: false }
|
|
1131
|
+
}
|
|
1132
|
+
// Older hosts and sessions without an answerer surface the same decision in the panel.
|
|
1133
|
+
studio.queueRender?.(id, root, { url: impl, screen: sc.key, size: want, ...opts }, prompt)
|
|
1134
|
+
return { allowed: false }
|
|
1135
|
+
},
|
|
1136
|
+
}))
|
|
1137
|
+
if (rendered.error) return { text: rendered.error === CONFIRM_RENDER ? CONFIRM_RENDER : `在电脑上出图没成功:\n${rendered.error}`, prompt: rendered.prompt }
|
|
1138
|
+
pruneShots(shotDir, prefix, rendered.file)
|
|
1139
|
+
}
|
|
1140
|
+
// 截图文件(板子、模拟器、Qt 窗口截的)或刚出的图:直接拿图比
|
|
1141
|
+
let implImage = null
|
|
1142
|
+
if (rendered) {
|
|
1143
|
+
try { implImage = fs.readFileSync(rendered.file) } catch (e) { return { text: `出的图读不出来:${String((e && e.message) || e).slice(0, 120)}` } }
|
|
1144
|
+
}
|
|
1145
|
+
if (/^file:/i.test(impl) && IMAGE_FILE.test(new URL(impl).pathname)) {
|
|
1146
|
+
const file = fileURLToPath(new URL(impl))
|
|
1147
|
+
try {
|
|
1148
|
+
if (fs.statSync(file).size > IMAGE_MAX) return { text: `截图 ${path.basename(file)} 太大(超过 40 MB):存成 PNG、按屏幕原尺寸截。` }
|
|
1149
|
+
implImage = fs.readFileSync(file)
|
|
1150
|
+
} catch (e) { return { text: `截图读不出来:${String((e && e.message) || e).slice(0, 120)}` } }
|
|
1151
|
+
}
|
|
1027
1152
|
let r
|
|
1028
1153
|
try {
|
|
1029
1154
|
// 本地 HTML 经预览服务器(http)打开再截:直接开 file:// 时 Vite 这类打包出来的模块脚本、/assets 这种根路径都载不出来(和右侧栏里看到的一样)
|
|
1030
1155
|
let shotUrl = impl
|
|
1031
|
-
if (/^file:/i.test(impl) && studio.openPreview) {
|
|
1156
|
+
if (/^file:/i.test(impl) && studio.openPreview && !implImage) {
|
|
1032
1157
|
const u = new URL(impl)
|
|
1033
1158
|
const s = implServe(fileURLToPath(u), cwd)
|
|
1034
1159
|
const p = await studio.openPreview({ kind: 'file', root: s.root })
|
|
1035
1160
|
shotUrl = `${p.origin}${s.rel}${u.search}${u.hash}`
|
|
1036
1161
|
}
|
|
1037
|
-
|
|
1162
|
+
const design = st ? { ...sc, url: withState(sc.url, st) } : sc
|
|
1163
|
+
r = await compareScreens(b, { design, impl: shotUrl, shown: rendered ? rendered.file : implImage ? fileURLToPath(new URL(impl)) : impl, size: want, ...opts, implImage })
|
|
1038
1164
|
} catch (e) {
|
|
1039
1165
|
return { text: `没比成:${String((e && e.message) || e).slice(0, 200)}(做出来的页面打得开吗?开发服务器起来了吗?)` }
|
|
1040
1166
|
}
|
|
1041
|
-
|
|
1167
|
+
if (rendered && r) {
|
|
1168
|
+
r.text = `在电脑上编好出了图(${(rendered.ms / 1000).toFixed(1)} 秒${rendered.built ? ',第一次要先编 LVGL 库,之后快' : ''}):${rendered.file}\n` +
|
|
1169
|
+
(rendered.warnings ? `QML 加载时的提示:\n${rendered.warnings}\n` : '') + r.text
|
|
1170
|
+
}
|
|
1171
|
+
return { r, sc, impl, want, opts, root, rendered }
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
/** 同一个工程同时只编一次(模型和右侧栏「重新比」撞上时排队,免得两边同时写一个出图程序) */
|
|
1175
|
+
const busyDirs = new Map()
|
|
1176
|
+
/** 面板要看工程目录出的图、但图已被清掉时重比一次:照上次比的设置补(尺寸、深浅色、整页、对齐、状态都沿用;谁比的也不改) */
|
|
1177
|
+
export function implRefill(rec, url, key, state = '') {
|
|
1178
|
+
const same = !!rec && rec.url === url
|
|
1179
|
+
const size = same && Array.isArray(rec.size) ? rec.size : '' // 直接传数组:128×128 这类小屏不走文字尺寸的下限
|
|
1180
|
+
return {
|
|
1181
|
+
args: { url, screen: key, size, at: same ? rec.at : undefined, dark: same ? rec.dark : undefined, whole: same ? rec.whole : undefined, state },
|
|
1182
|
+
by: same && rec.by === 'model' ? 'model' : 'user',
|
|
1183
|
+
sizeGiven: !!size,
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
/** 出图目录收拾:同一屏同一状态 10 分钟前的旧图、任何 14 天前的图删掉(面板记的图没了会重新出) */
|
|
1188
|
+
function pruneShots(dir, prefix, keep) {
|
|
1189
|
+
let names = []
|
|
1190
|
+
try { names = fs.readdirSync(dir) } catch { return }
|
|
1191
|
+
const now = Date.now()
|
|
1192
|
+
for (const n of names) {
|
|
1193
|
+
const f = path.join(dir, n)
|
|
1194
|
+
if (f === keep) continue
|
|
1195
|
+
try {
|
|
1196
|
+
const age = now - fs.statSync(f).mtimeMs
|
|
1197
|
+
if (age > 14 * 86400000 || n.startsWith(prefix) && age > 600000) fs.rmSync(f, { force: true })
|
|
1198
|
+
} catch {}
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
function oneAtATime(key, fn) {
|
|
1203
|
+
const prev = busyDirs.get(key) || Promise.resolve()
|
|
1204
|
+
const next = prev.catch(() => {}).then(fn)
|
|
1205
|
+
busyDirs.set(key, next)
|
|
1206
|
+
next.finally(() => { if (busyDirs.get(key) === next) busyDirs.delete(key) }).catch(() => {})
|
|
1207
|
+
return next
|
|
1042
1208
|
}
|
|
1043
1209
|
|
|
1044
1210
|
/** 比完记一笔(右侧栏「和做出来的比」显示分数、标红框);by:model 模型比的 / user 右侧栏点的 */
|
|
@@ -1054,7 +1220,7 @@ function keepImpl(id, out, by, sizeGiven) {
|
|
|
1054
1220
|
return store.set(root, out.sc.key, { url: out.impl, ...out.opts, by })
|
|
1055
1221
|
}
|
|
1056
1222
|
const rec = store.set(root, out.sc.key, {
|
|
1057
|
-
url: out.impl, ...out.opts, by, size: sizeGiven ? out.want : undefined,
|
|
1223
|
+
url: out.impl, ...out.opts, by, size: sizeGiven ? out.want : undefined, img: out.rendered ? out.rendered.file : '',
|
|
1058
1224
|
...(typeof r.pct === 'number' ? { pct: r.pct, boxes: r.boxes, cmp: r.cmp, slot: r.slot } : {}),
|
|
1059
1225
|
})
|
|
1060
1226
|
if (r.jpg) store.shot(root, out.sc.key, r.jpg)
|
|
@@ -1165,13 +1331,23 @@ export function apply(ctx) {
|
|
|
1165
1331
|
}
|
|
1166
1332
|
const previewPorts = new Set()
|
|
1167
1333
|
let tracker = null
|
|
1168
|
-
const
|
|
1169
|
-
|
|
1170
|
-
const library = createLibrary({ log })
|
|
1334
|
+
const library = createLibrary({ log, beforeMove: (work, to) => history.validateMove({ root: work.dir, designId: work.designId }, to, work.scope) })
|
|
1335
|
+
const history = createHistory({ base: HISTORY_DIR, log, findDesign: root => library.get(root)?.designId })
|
|
1171
1336
|
// 设计市场:目录和批次包从 npm 镜像来,验过签名、逐个文件核对过才用;市场上的页面原样预览时也加硬规矩
|
|
1172
1337
|
const seedDir = fileURLToPath(new URL('../gallery-seed', import.meta.url))
|
|
1173
1338
|
// 「设计库不联网」那行开着:市场不访问任何网址
|
|
1174
1339
|
const market = createMarket({ version: VERSION, log, seedDir: fs.existsSync(path.join(seedDir, 'index.json')) ? seedDir : '', online: () => studio.offline === 0 })
|
|
1340
|
+
/**
|
|
1341
|
+
* 2.0 项目规矩是不是别人写的(这套设计导入时包里带的、原样没改;市场里还没装、正在看的):
|
|
1342
|
+
* 右侧栏的提示和给模型的通知都用它。没有规矩时也要调(旧版本装的设计第一次看到时记一笔);判断出错时按别人写的算
|
|
1343
|
+
*/
|
|
1344
|
+
const rulesForeign = (root, text) => {
|
|
1345
|
+
try {
|
|
1346
|
+
const buf = text ? Buffer.from(text, 'utf8') : null
|
|
1347
|
+
const own = library.rulesFromPackage(root, buf)
|
|
1348
|
+
return !!text && (own || market.isStaging(root))
|
|
1349
|
+
} catch (e) { log(e); return !!text }
|
|
1350
|
+
}
|
|
1175
1351
|
const drafts = createDrafts({ log }) // 正在写的页面(边写边看):tracker 往里推,预览服务器往外吐
|
|
1176
1352
|
const thumbDirs = createDirRevs() // 画布缩略图(issue #17):各目录的资源修订号,预览服务器报改动时更新
|
|
1177
1353
|
const hub = createHub({
|
|
@@ -1198,22 +1374,26 @@ export function apply(ctx) {
|
|
|
1198
1374
|
onUnwatch: (key) => { if (key.startsWith('file:')) thumbDirs.unwatched(key.slice(5)) },
|
|
1199
1375
|
})
|
|
1200
1376
|
const open = async (target, opts) => {
|
|
1201
|
-
const r = await hub.open(target
|
|
1377
|
+
const r = await hub.open(target, opts)
|
|
1202
1378
|
previewPorts.add(Number(new URL(r.origin).port))
|
|
1203
1379
|
return r
|
|
1204
1380
|
}
|
|
1381
|
+
const proxyRoot = (cwd, port) => path.join(path.dirname(STORE_FILE), 'dev-pages', crypto.createHash('sha256').update(JSON.stringify([cwd, port])).digest('hex'))
|
|
1205
1382
|
tracker = createTracker({
|
|
1206
1383
|
open,
|
|
1384
|
+
proxyRoot,
|
|
1207
1385
|
watchTag: (root) => thumbDirs.tag(root),
|
|
1208
1386
|
drafts,
|
|
1209
1387
|
log,
|
|
1210
1388
|
history,
|
|
1389
|
+
transactionBase: path.join(path.dirname(library.file), 'transactions'),
|
|
1390
|
+
resolveDesign: library.resolveTarget,
|
|
1211
1391
|
// 记会话的同时,在做的设计目录补进「我的作品」
|
|
1212
1392
|
store: { load: fileStore.load, save: (data) => { fileStore.save(data); try { library.sync(data) } catch (e) { log(e) } } },
|
|
1213
1393
|
alive: (origin) => hub.alive(origin),
|
|
1214
1394
|
autoOpen: () => studio.autoOpen > 0,
|
|
1215
1395
|
// 装好的别人的设计系统退回旧版:退回来的页面先记成别人做的(预览照样加规矩)
|
|
1216
|
-
beforeRestore:
|
|
1396
|
+
beforeRestore: library.stagePast,
|
|
1217
1397
|
trust: () => { try { return library.trustRev() } catch (e) { log(e); return '' } },
|
|
1218
1398
|
skipPorts: () => {
|
|
1219
1399
|
const s = new Set(previewPorts)
|
|
@@ -1223,6 +1403,18 @@ export function apply(ctx) {
|
|
|
1223
1403
|
},
|
|
1224
1404
|
})
|
|
1225
1405
|
ctx.effect(() => () => { drafts.clear(); hub.closeAll() }, 'dsh-design-studio: preview servers')
|
|
1406
|
+
const pendingRenders = new Map()
|
|
1407
|
+
function queueRender(id, root, args, prompt) {
|
|
1408
|
+
// Pending prompts belong to this plugin instance and to the design that created them.
|
|
1409
|
+
for (const [key, old] of pendingRenders) if (old.expires <= Date.now()) pendingRenders.delete(key)
|
|
1410
|
+
pendingRenders.set(id, { id: crypto.randomUUID(), root, args, prompt, expires: Date.now() + 10 * 60000 })
|
|
1411
|
+
}
|
|
1412
|
+
function renderFor(id, root) {
|
|
1413
|
+
const pending = pendingRenders.get(id)
|
|
1414
|
+
if (pending?.root === root && pending.expires > Date.now()) return pending
|
|
1415
|
+
pendingRenders.delete(id)
|
|
1416
|
+
return null
|
|
1417
|
+
}
|
|
1226
1418
|
const implStore = createImpl({ log }) // 「和做出来的比」:每屏对应的页面地址、上次比对的分数
|
|
1227
1419
|
ctx.effect(() => {
|
|
1228
1420
|
studio.tracker = tracker
|
|
@@ -1234,6 +1426,8 @@ export function apply(ctx) {
|
|
|
1234
1426
|
const fontIndex = loadFontIndex()
|
|
1235
1427
|
const fonts = fontIndex ? createFonts({ market, index: fontIndex, log }) : null
|
|
1236
1428
|
studio.fonts = fonts
|
|
1429
|
+
studio.queueRender = queueRender
|
|
1430
|
+
studio.workspaceOf = dshCwd
|
|
1237
1431
|
studio.sessionCwd = sessionCwd
|
|
1238
1432
|
studio.impl = implStore
|
|
1239
1433
|
studio.openPreview = open
|
|
@@ -1244,7 +1438,7 @@ export function apply(ctx) {
|
|
|
1244
1438
|
if (studio.market === market) { market.abort(); studio.market = null }
|
|
1245
1439
|
if (studio.photos === photos) studio.photos = null
|
|
1246
1440
|
if (studio.fonts === fonts) studio.fonts = null
|
|
1247
|
-
if (studio.sessionCwd === sessionCwd) studio.sessionCwd = null
|
|
1441
|
+
if (studio.sessionCwd === sessionCwd) { studio.queueRender = null; pendingRenders.clear(); studio.workspaceOf = null; studio.sessionCwd = null }
|
|
1248
1442
|
}
|
|
1249
1443
|
}, 'dsh-design-studio: tracker')
|
|
1250
1444
|
// check_design / look_design 用的无头浏览器:用到时才开,闲置自己关,这一行停用时关掉
|
|
@@ -1261,7 +1455,7 @@ export function apply(ctx) {
|
|
|
1261
1455
|
// 公网链接(#27):只放整套 HTML 演示,每次有人打开按现在的文件打包(文件没改就用上次的)
|
|
1262
1456
|
const pub = createPublicShare({
|
|
1263
1457
|
build: (p) => {
|
|
1264
|
-
const { pack, files } = packDesign(p.root, 0, p)
|
|
1458
|
+
const { pack, files } = packDesign(p.target || p.root, 0, p)
|
|
1265
1459
|
return { html: pack.html, deps: files }
|
|
1266
1460
|
},
|
|
1267
1461
|
// 这个会话换了设计(或关了):关掉,别把不在眼前的设计一直开在公网上(插件自己每 5 秒看一眼,不靠右侧栏开着)
|
|
@@ -1345,9 +1539,10 @@ export function apply(ctx) {
|
|
|
1345
1539
|
// 调节滑块:tweaks.json 改了(模型写的 / 写回的)右侧栏跟着变
|
|
1346
1540
|
const t = tracker.stateOf(session).target
|
|
1347
1541
|
let tweaks = null
|
|
1348
|
-
if (t
|
|
1542
|
+
if (t?.directory) { try { tweaks = readTweaks(t.root) } catch (e) { log(e) } }
|
|
1349
1543
|
const snap = tracker.snapshot(session)
|
|
1350
|
-
|
|
1544
|
+
const pending = renderFor(session, implRoot(snap))
|
|
1545
|
+
json(res, 200, { ...snap, ...(pending ? { renderRequest: { id: pending.id, dir: pending.prompt.dir, commands: pending.prompt.commands } } : {}), impl: implStore.list(implRoot(snap)), strict: strictScreens(snap), phone: { on: ph.on, seen: ph.seen || 0 }, pub: pub.status(session, { brief: true }), tweaks, ...annotsField(session, new URL(req.url, 'http://x').searchParams.get('an')), ...(c ? { checkReq: c.id } : {}) })
|
|
1351
1546
|
}
|
|
1352
1547
|
|
|
1353
1548
|
/** 正在看的几屏里,哪些是别人做的、没改过的(地址列表):右侧栏给它们的 iframe 加沙盒、不给剪贴板 */
|
|
@@ -1386,6 +1581,7 @@ export function apply(ctx) {
|
|
|
1386
1581
|
const vars = body.vars && typeof body.vars === 'object' && !Array.isArray(body.vars) ? body.vars : null
|
|
1387
1582
|
const session = String(body.session || '')
|
|
1388
1583
|
const want = String(body.root || '')
|
|
1584
|
+
const style = typeof body.label === 'string' ? body.label.replace(/[\x00-\x1f]/g, ' ').trim().slice(0, 30) : ''
|
|
1389
1585
|
// 字体库(#31):换成字体库的字体要先下载好、复制进设计的 dsh-fonts/(只往右侧栏正看着的这套设计里放)
|
|
1390
1586
|
const lib = studio.fonts
|
|
1391
1587
|
const picks = lib && vars ? [...new Set(Object.values(vars).map((v) => libFontOf(lib.index, v)).filter(Boolean))] : []
|
|
@@ -1394,7 +1590,7 @@ export function apply(ctx) {
|
|
|
1394
1590
|
if (!t || t.kind !== 'file') return json(res, 200, { ok: false, reason: 'not-file' })
|
|
1395
1591
|
if (t.root !== want) return json(res, 200, { ok: false, reason: 'moved' })
|
|
1396
1592
|
try {
|
|
1397
|
-
await lib.
|
|
1593
|
+
await lib.ensure()
|
|
1398
1594
|
} catch (e) {
|
|
1399
1595
|
log(e)
|
|
1400
1596
|
return json(res, 200, { ok: false, reason: e && e.code === 'off' ? 'font-off' : e && /^(link|EACCES|EPERM|EROFS|ENOTDIR|ENOSPC)$/.test(e.code || '') ? 'font-write' : 'font-net' })
|
|
@@ -1404,7 +1600,13 @@ export function apply(ctx) {
|
|
|
1404
1600
|
// 只在这次改了字体栈时才扫整套设计(只改颜色、拖滑块不用读一遍所有文件)
|
|
1405
1601
|
const fontish = (v) => /["']/.test(String(v)) || /(?:^|,)\s*(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-[\w-]+)\s*(?:,|$)/i.test(String(v))
|
|
1406
1602
|
const before = lib && vars && Object.values(vars).some(fontish) ? libFontsUsed(root, lib.index) : null
|
|
1407
|
-
const x = applyTweaks(root, values, vars
|
|
1603
|
+
const x = applyTweaks(root, values, vars, {
|
|
1604
|
+
where: body.where && typeof body.where === 'object' && !Array.isArray(body.where) ? body.where : undefined,
|
|
1605
|
+
beforeWrite: picks.length ? () => {
|
|
1606
|
+
try { lib.place(root, picks, pinRoots([root])) }
|
|
1607
|
+
catch (cause) { throw Object.assign(new Error('font placement failed', { cause }), { code: 'studioFontWrite' }) }
|
|
1608
|
+
} : undefined,
|
|
1609
|
+
})
|
|
1408
1610
|
// 变量写进了哪些样式,那里的 @font-face 那段跟着变:选了字体库的加上;这次换走了、整套设计都不再写名字的去掉(别的不动)
|
|
1409
1611
|
if (x.ok && x.files.length && lib) {
|
|
1410
1612
|
const after = before ? libFontsUsed(root, lib.index) : null
|
|
@@ -1412,9 +1614,14 @@ export function apply(ctx) {
|
|
|
1412
1614
|
x.files = [...new Set([...x.files, ...syncFonts(root, x.files, picks.map((f) => f.id), lib.index, { drop })])]
|
|
1413
1615
|
}
|
|
1414
1616
|
return x
|
|
1415
|
-
|
|
1617
|
+
// 试穿风格「就用这个」(2.0)带着风格名:版本里写「换风格:温暖手作」,比一串变量名好认
|
|
1618
|
+
}, (x) => (style ? `换风格:${style}` : `调节:${x.changed.map((c) => `${c.label} ${c.to}`).join('、')}`).slice(0, 60), want, Number.isSafeInteger(body.expectedRev) ? body.expectedRev : undefined, { targetKey: body.targetKey, requestId: body.requestId })
|
|
1416
1619
|
json(res, 200, r)
|
|
1417
1620
|
} catch (e) {
|
|
1621
|
+
if (e.code === 'studioFontWrite') {
|
|
1622
|
+
log(e.cause)
|
|
1623
|
+
return json(res, 200, { ok: false, reason: 'font-write' })
|
|
1624
|
+
}
|
|
1418
1625
|
json(res, 500, { error: e.message })
|
|
1419
1626
|
}
|
|
1420
1627
|
}
|
|
@@ -1452,7 +1659,7 @@ export function apply(ctx) {
|
|
|
1452
1659
|
let body
|
|
1453
1660
|
try { body = await readBody(req, MOCK_MAX + 64 * 1024) } catch (e) { return json(res, 400, { error: e.message }) }
|
|
1454
1661
|
try {
|
|
1455
|
-
const r = tracker.editDir(String(body.session || ''), (root) => saveMock(root, body.data, typeof body.fp === 'string' ? body.fp : ''), () => '模拟数据:存成初始数据', String(body.root || ''))
|
|
1662
|
+
const r = tracker.editDir(String(body.session || ''), (root) => saveMock(root, body.data, typeof body.fp === 'string' ? body.fp : ''), () => '模拟数据:存成初始数据', String(body.root || ''), undefined, { targetKey: body.targetKey, requestId: body.requestId })
|
|
1456
1663
|
json(res, 200, r)
|
|
1457
1664
|
} catch (e) {
|
|
1458
1665
|
json(res, 500, { error: e.message })
|
|
@@ -1492,7 +1699,7 @@ export function apply(ctx) {
|
|
|
1492
1699
|
try { cwd = await dshCwd(session) } catch { cwd = '' }
|
|
1493
1700
|
if (!cwd) cwd = tracker.cwdOf(session)
|
|
1494
1701
|
if (typeof body.url === 'string' && body.url.trim()) {
|
|
1495
|
-
try { url = implUrl(body.url.trim().slice(0, 2000), cwd) } catch (e) { return json(res, 400, { error: 'bad-url', msg: e.message }) }
|
|
1702
|
+
try { url = implUrl(body.url.trim().slice(0, 2000), cwd, designFor(session).kind) } catch (e) { return json(res, 400, { error: 'bad-url', msg: e.message }) }
|
|
1496
1703
|
}
|
|
1497
1704
|
if (!url) return json(res, 404, { error: 'no-url' })
|
|
1498
1705
|
let u = null
|
|
@@ -1503,12 +1710,30 @@ export function apply(ctx) {
|
|
|
1503
1710
|
const own = Number(ownHost(ctx).split(':')[1]) || 0
|
|
1504
1711
|
if ((at.snap.origin && url.startsWith(at.snap.origin + '/')) || (u.protocol !== 'file:' && (previewPorts.has(port) || port === own)) || isDesignFile(at, u)) return json(res, 400, { error: 'self' })
|
|
1505
1712
|
if (u.protocol === 'https:') return json(res, 400, { error: 'https' }) // 代理只会接 http 的开发服务器
|
|
1713
|
+
const before = rec // 换地址前的记录:补图时只有同一个地址才沿用上次比的设置
|
|
1506
1714
|
if (url !== (rec && rec.url) || (typeof body.whole === 'boolean' && body.whole !== (rec && rec.whole))) {
|
|
1507
1715
|
rec = implStore.set(at.root, key, { url, by: 'user', ...(typeof body.whole === 'boolean' ? { whole: body.whole } : {}) })
|
|
1508
1716
|
}
|
|
1509
1717
|
let live
|
|
1510
1718
|
try {
|
|
1511
|
-
|
|
1719
|
+
const dir = u.protocol === 'file:' ? fileURLToPath(u) : ''
|
|
1720
|
+
if (dir && fs.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) {
|
|
1721
|
+
// LVGL / QML 工程:右侧栏看的是最近一次在电脑上出的图;还没出过就现在出一张(顺便比一次)
|
|
1722
|
+
await projectDirectory(dir, await dshCwd(session))
|
|
1723
|
+
const state = String(body.state || '')
|
|
1724
|
+
let img = rec && rec.url === url && (rec.state || '') === state && rec.img && fs.existsSync(rec.img) ? rec.img : ''
|
|
1725
|
+
if (!img) {
|
|
1726
|
+
const again = implRefill(before, url, key, state)
|
|
1727
|
+
const out = await runCompare(session, again.args, { panel: true, ticket: body.ticket })
|
|
1728
|
+
if (out.prompt) return json(res, 200, { url, prompt: out.prompt })
|
|
1729
|
+
if (!out.r || !out.rendered) return json(res, 500, { error: 'open', msg: String(out.text || '').slice(0, 600) })
|
|
1730
|
+
if (implRoot(tracker.snapshot(session)) !== at.root || implStore.get(at.root, key)?.url !== url) return json(res, 409, { error: 'stale' })
|
|
1731
|
+
rec = keepImpl(session, out, again.by, again.sizeGiven) || rec
|
|
1732
|
+
img = out.rendered.file
|
|
1733
|
+
}
|
|
1734
|
+
const r = await open({ kind: 'file', root: path.dirname(img) })
|
|
1735
|
+
live = `${r.origin}/${encodeURIComponent(path.basename(img))}?t=${Math.round(fs.statSync(img).mtimeMs)}`
|
|
1736
|
+
} else if (u.protocol === 'file:') {
|
|
1512
1737
|
const s = implServe(fileURLToPath(u), cwd)
|
|
1513
1738
|
const r = await open({ kind: 'file', root: s.root })
|
|
1514
1739
|
live = `${r.origin}${s.rel}${u.search}${u.hash}`
|
|
@@ -1523,6 +1748,27 @@ export function apply(ctx) {
|
|
|
1523
1748
|
json(res, 200, { url, live, rec })
|
|
1524
1749
|
}
|
|
1525
1750
|
|
|
1751
|
+
async function renderReplyRoute(req, res) {
|
|
1752
|
+
if (!admit(req, res)) return
|
|
1753
|
+
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
|
|
1754
|
+
let body
|
|
1755
|
+
try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
|
|
1756
|
+
const session = String(body.session || '')
|
|
1757
|
+
const pending = renderFor(session, implRoot(tracker.snapshot(session)))
|
|
1758
|
+
if (!pending || body.id !== pending.id) return json(res, 409, { error: 'stale' })
|
|
1759
|
+
pendingRenders.delete(session)
|
|
1760
|
+
if (body.run !== true) return json(res, 200, { ok: true })
|
|
1761
|
+
const out = await runCompare(session, pending.args, { panel: true, ticket: pending.prompt.ticket })
|
|
1762
|
+
if (out.prompt) {
|
|
1763
|
+
queueRender(session, pending.root, pending.args, out.prompt)
|
|
1764
|
+
return json(res, 200, { pending: true })
|
|
1765
|
+
}
|
|
1766
|
+
if (!out.r || !out.rendered) return json(res, 200, { error: 'failed', text: out.text })
|
|
1767
|
+
if (implRoot(tracker.snapshot(session)) !== pending.root) return json(res, 409, { error: 'stale' })
|
|
1768
|
+
const rec = keepImpl(session, out, 'user', true)
|
|
1769
|
+
return json(res, 200, { ok: true, rec })
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1526
1772
|
/** POST { session, screen, size, dark } → 照记着的地址在无头浏览器里比一次(和 compare_design 一样),记下分数 → { rec, text } */
|
|
1527
1773
|
async function implCmpRoute(req, res) {
|
|
1528
1774
|
if (!admit(req, res)) return
|
|
@@ -1537,10 +1783,10 @@ export function apply(ctx) {
|
|
|
1537
1783
|
if (!rec) return json(res, 404, { error: 'no-url' })
|
|
1538
1784
|
// 眼前看的不是记录里的地址了(模型刚换了地址、画面还没跟上):不比,等画面换过去
|
|
1539
1785
|
if (typeof body.url === 'string' && body.url && body.url !== rec.url) return json(res, 200, { error: 'stale' })
|
|
1540
|
-
// 画幅能设
|
|
1541
|
-
const
|
|
1542
|
-
const
|
|
1543
|
-
|
|
1786
|
+
// 画幅能设 64–8000(自定义画幅;嵌入式小屏 64 起):照眼前的比,不走模型那边 200 起的尺寸规矩
|
|
1787
|
+
const size = body.size || rec.size || ''
|
|
1788
|
+
const out = await runCompare(session, { url: rec.url, screen: key, size, at: rec.at, dark: typeof body.dark === 'boolean' ? body.dark : rec.dark, whole: rec.whole, state: String(body.state || '') }, { panel: true, ticket: body.ticket })
|
|
1789
|
+
if (out.prompt) return json(res, 200, { url: rec.url, prompt: out.prompt })
|
|
1544
1790
|
if (!out.r) return json(res, 200, { error: 'failed', text: out.text })
|
|
1545
1791
|
// 比的这会儿换了设计、或这屏改填了别的地址:这次的分数不算数,别写回去
|
|
1546
1792
|
const now = implStore.get(at.root, key)
|
|
@@ -1555,7 +1801,9 @@ export function apply(ctx) {
|
|
|
1555
1801
|
const q = new URL(req.url, 'http://x').searchParams
|
|
1556
1802
|
const key = q.get('screen') || ''
|
|
1557
1803
|
const at = implScreen(q.get('session') || '', key)
|
|
1558
|
-
const
|
|
1804
|
+
const rec = at && implStore.get(at.root, key)
|
|
1805
|
+
const matches = rec && (!q.has('state') || (rec.state || '') === q.get('state')) && (!q.has('v') || String(rec.when) === q.get('v'))
|
|
1806
|
+
const jpg = matches ? implStore.shot(at.root, key) : null
|
|
1559
1807
|
if (!jpg) return json(res, 404, { error: 'none' })
|
|
1560
1808
|
res.writeHead(200, { 'Content-Type': 'image/jpeg', 'Content-Length': jpg.length, 'Cache-Control': 'no-store' })
|
|
1561
1809
|
res.end(jpg)
|
|
@@ -1663,6 +1911,52 @@ export function apply(ctx) {
|
|
|
1663
1911
|
json(res, 200, { ok: true })
|
|
1664
1912
|
}
|
|
1665
1913
|
|
|
1914
|
+
function dropReaderRoute(req, res) {
|
|
1915
|
+
if (!admit(req, res)) return
|
|
1916
|
+
res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8' })
|
|
1917
|
+
res.end('export ' + readDropFolder.toString())
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
// Browsers expose file contents instead of OS paths. Import into a fresh directory.
|
|
1921
|
+
async function importHtmlRoute(req, res) {
|
|
1922
|
+
if (!admit(req, res)) return
|
|
1923
|
+
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
|
|
1924
|
+
let dest
|
|
1925
|
+
try {
|
|
1926
|
+
const { files, name, session, directory } = await readBody(req, MAX_EXPORT)
|
|
1927
|
+
if (!session || !Array.isArray(files) || !files.length || files.length > 1024) throw new Error('Invalid file list')
|
|
1928
|
+
let total = 0
|
|
1929
|
+
const entries = files.map(({ path: rel, data }) => {
|
|
1930
|
+
if (typeof rel !== 'string' || rel.length > 4096 || rel.split('/').some(part =>
|
|
1931
|
+
!part || part.startsWith('.') || part === 'node_modules' || /[\\:\x00-\x1f]/.test(part)) ||
|
|
1932
|
+
typeof data !== 'string') throw new Error('Invalid file')
|
|
1933
|
+
const buf = Buffer.from(data, 'base64')
|
|
1934
|
+
total += buf.length
|
|
1935
|
+
if (total > 32 * 1024 * 1024) throw new Error('32 MB')
|
|
1936
|
+
return { rel, buf }
|
|
1937
|
+
})
|
|
1938
|
+
const pages = entries.map(f => f.rel).filter(rel => /\.html?$/i.test(rel) && !rel.startsWith('components/'))
|
|
1939
|
+
if (!pages.length) throw new Error('未找到 HTML 文件 / No HTML file')
|
|
1940
|
+
const base = baseFor(await sessionCwd(session))
|
|
1941
|
+
fs.mkdirSync(base, { recursive: true })
|
|
1942
|
+
const fresh = freshDir(fs.realpathSync(base), slugOf(name, 'design'))
|
|
1943
|
+
fs.mkdirSync(fresh)
|
|
1944
|
+
dest = fresh
|
|
1945
|
+
for (const { rel, buf } of entries) {
|
|
1946
|
+
const file = path.join(dest, rel)
|
|
1947
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
1948
|
+
fs.writeFileSync(file, buf, { flag: 'wx' })
|
|
1949
|
+
}
|
|
1950
|
+
// Let the normal open route resolve the root and screen order.
|
|
1951
|
+
const target = pages.length === 1 ? path.join(dest, pages[0]) : pages.some(p => !p.includes('/')) ? dest
|
|
1952
|
+
: path.join(dest, pages.sort((a, b) => a.split('/').length - b.split('/').length)[0])
|
|
1953
|
+
json(res, 200, { target: directory === true && target !== dest ? path.dirname(target) : target })
|
|
1954
|
+
} catch (e) {
|
|
1955
|
+
if (dest) fs.rmSync(dest, { recursive: true, force: true })
|
|
1956
|
+
json(res, 400, { error: e.message })
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1666
1960
|
async function openRoute(req, res) {
|
|
1667
1961
|
if (!admit(req, res)) return
|
|
1668
1962
|
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
|
|
@@ -1672,10 +1966,16 @@ export function apply(ctx) {
|
|
|
1672
1966
|
if (!session) return json(res, 400, { error: '缺 session' })
|
|
1673
1967
|
try {
|
|
1674
1968
|
// 输入框里写的相对路径按会话目录算(新会话也问 DSH 要)
|
|
1675
|
-
const
|
|
1969
|
+
const cwd = await sessionCwd(session)
|
|
1970
|
+
const work = typeof body.workId === 'string' && library.list().find(w => w.workId === body.workId && !w.hidden)
|
|
1971
|
+
if (body.workId && !work) throw Error('找不到这份作品')
|
|
1972
|
+
const target = work ? { kind: 'file', root: work.dir, file: work.file || '', directory: work.scope === 'directory', designId: work.designId }
|
|
1973
|
+
: parseTarget(body.target, cwd)
|
|
1974
|
+
if (work?.scope === 'directory' && !fs.existsSync(work.dir)) throw Error('找不到设计文件夹')
|
|
1676
1975
|
// 组件文件(#30)不是一屏:拖进来、选中它都不当整套设计开
|
|
1677
1976
|
if (target.kind === 'file' && path.basename(path.dirname(target.file)) === 'components' && /\.html?$/i.test(target.file)) throw new Error(`${path.basename(target.file)} 是组件文件,不单独打开:打开用到它的那一屏`)
|
|
1678
1977
|
await tracker.setTarget(session, target, { source: 'user', popup: false })
|
|
1978
|
+
designSelection.delete(session)
|
|
1679
1979
|
// 换了设计,公网链接马上关(右侧栏要马上知道,不等下一次刷新)
|
|
1680
1980
|
json(res, 200, { ...tracker.snapshot(session), ...annotsField(session), pub: pub.status(session, { brief: true }) })
|
|
1681
1981
|
} catch (e) {
|
|
@@ -1683,6 +1983,23 @@ export function apply(ctx) {
|
|
|
1683
1983
|
}
|
|
1684
1984
|
}
|
|
1685
1985
|
|
|
1986
|
+
const designSelection = new Map()
|
|
1987
|
+
function selectDesignScreen(session, snap, target, screen) {
|
|
1988
|
+
if (!tracker.accepts(snap.target, target)) return
|
|
1989
|
+
if (screen === '') designSelection.delete(session)
|
|
1990
|
+
else if (typeof screen === 'string' && snap.screens?.some(s => s.key === screen)) designSelection.set(session, { target: designKey(snap.target), from: snap.focus, screen })
|
|
1991
|
+
}
|
|
1992
|
+
|
|
1993
|
+
async function modelSnapshot(session) {
|
|
1994
|
+
const snap = await tracker.readySnapshot(session)
|
|
1995
|
+
const selection = designSelection.get(session)
|
|
1996
|
+
if (selection?.target === designKey(snap.target) && selection.from === snap.focus && snap.screens?.some(s => s.key === selection.screen)) {
|
|
1997
|
+
return { ...snap, focus: selection.screen }
|
|
1998
|
+
}
|
|
1999
|
+
if (selection) designSelection.delete(session)
|
|
2000
|
+
return snap
|
|
2001
|
+
}
|
|
2002
|
+
|
|
1686
2003
|
async function viewRoute(req, res) {
|
|
1687
2004
|
if (!admit(req, res)) return
|
|
1688
2005
|
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
|
|
@@ -1690,13 +2007,20 @@ export function apply(ctx) {
|
|
|
1690
2007
|
try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
|
|
1691
2008
|
const session = String(body.session || '')
|
|
1692
2009
|
if (!session) return json(res, 400, { error: '缺 session' })
|
|
1693
|
-
const patch = {}
|
|
2010
|
+
const patch = body.settings ? { settings: body.settings } : {}
|
|
2011
|
+
if (body.display && typeof body.display === 'object') patch.display = body.display
|
|
1694
2012
|
for (const k of ['kind', 'size', 'view', 'focus']) if (typeof body[k] === 'string') patch[k] = body[k]
|
|
1695
2013
|
try {
|
|
1696
|
-
|
|
1697
|
-
|
|
2014
|
+
const result = (!body.selection || Object.keys(patch).length)
|
|
2015
|
+
? await tracker.setView(session, { ...patch, targetKey: body.targetKey, requestId: body.requestId }) : null
|
|
2016
|
+
const after = tracker.snapshot(session)
|
|
2017
|
+
if (patch.focus) designSelection.delete(session)
|
|
2018
|
+
if (body.selection || patch.settings?.page) selectDesignScreen(session, after,
|
|
2019
|
+
body.selection?.targetKey || body.selection?.target || body.targetKey || patch.settings?.target,
|
|
2020
|
+
body.selection?.screen ?? patch.settings?.page)
|
|
2021
|
+
json(res, 200, { ...after, ok: true, ...(result?.change ? { change: result.change, state: after } : {}), ...annotsField(session), pub: pub.status(session, { brief: true }) })
|
|
1698
2022
|
} catch (e) {
|
|
1699
|
-
json(res, 400, { error: e.message })
|
|
2023
|
+
json(res, 400, { ok: false, reason: e.code || 'changed', error: e.message })
|
|
1700
2024
|
}
|
|
1701
2025
|
}
|
|
1702
2026
|
|
|
@@ -1706,11 +2030,125 @@ export function apply(ctx) {
|
|
|
1706
2030
|
let body
|
|
1707
2031
|
try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
|
|
1708
2032
|
tracker.clear(String(body.session || ''))
|
|
2033
|
+
designSelection.delete(String(body.session || ''))
|
|
1709
2034
|
phone.stop(String(body.session || ''))
|
|
1710
2035
|
pub.stop(String(body.session || ''))
|
|
1711
2036
|
json(res, 200, tracker.snapshot(String(body.session || '')))
|
|
1712
2037
|
}
|
|
1713
2038
|
|
|
2039
|
+
/**
|
|
2040
|
+
* 项目规矩(2.0):GET ?session= → { text, fp, exists };POST { session, root, text, fp } 存回 rules.md(存一版、模型知道你改了)。
|
|
2041
|
+
* fp 对不上(这期间模型改过)不写,回包带上现在那份,右侧栏换成它
|
|
2042
|
+
*/
|
|
2043
|
+
async function rulesRoute(req, res) {
|
|
2044
|
+
if (!admit(req, res)) return
|
|
2045
|
+
if (req.method === 'GET') {
|
|
2046
|
+
const session = new URL(req.url, 'http://x').searchParams.get('session') || ''
|
|
2047
|
+
const t = tracker.stateOf(session).target
|
|
2048
|
+
if (!t || t.kind !== 'file') return json(res, 200, { ok: false, reason: 'not-file' })
|
|
2049
|
+
const r = readRules(t.root)
|
|
2050
|
+
if (!r) return json(res, 200, { ok: false, reason: 'not-own' })
|
|
2051
|
+
// 导入的模板原样带来的:右侧栏说一句「这是模板带来的,AI 只当参考」(和给模型的通知用同一个判断)
|
|
2052
|
+
return json(res, 200, { ok: true, root: t.root, ...r, foreign: rulesForeign(t.root, r.text) })
|
|
2053
|
+
}
|
|
2054
|
+
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
|
|
2055
|
+
let body
|
|
2056
|
+
try { body = await readBody(req, RULES_MAX * 4 + 4096) } catch (e) { return json(res, 400, { error: e.message }) }
|
|
2057
|
+
try {
|
|
2058
|
+
const r = tracker.editDir(String(body.session || ''), root => saveRules(root, body.text, typeof body.fp === 'string' ? body.fp : ''),
|
|
2059
|
+
'改项目规矩(rules.md)', String(body.root || ''), undefined, {
|
|
2060
|
+
targetKey: body.targetKey, requestId: body.requestId,
|
|
2061
|
+
effect: root => { try { library.adoptRules(root) } catch (e) { log(e) } },
|
|
2062
|
+
})
|
|
2063
|
+
json(res, 200, r)
|
|
2064
|
+
} catch (e) {
|
|
2065
|
+
json(res, 500, { error: e.message })
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2069
|
+
/** 组件墙(2.0):GET ?session= → 组件目录(名字、参数、有没有插槽、错在哪、被哪几屏用了)。画面由预览端口的 <屏>?__ddp_comp=<名> 出 */
|
|
2070
|
+
function compsRoute(req, res) {
|
|
2071
|
+
if (!admit(req, res)) return
|
|
2072
|
+
const session = new URL(req.url, 'http://x').searchParams.get('session') || ''
|
|
2073
|
+
const t = tracker.stateOf(session).target
|
|
2074
|
+
if (!t || t.kind !== 'file') return json(res, 200, { ok: false, items: [] })
|
|
2075
|
+
const r = compOf(session)
|
|
2076
|
+
const items = r ? r.items.map((x) => ({ name: x.name, params: x.params.map((p) => ({ name: p.name, required: !!p.required, def: p.def })), slot: !!x.slot, error: x.error || '', usedBy: (r.usedBy.get(x.name) || []).slice(0, 50), usedN: (r.usedBy.get(x.name) || []).length })) : [] // usedBy 只给前 50 屏,屏数另给全的
|
|
2077
|
+
json(res, 200, { ok: true, items })
|
|
2078
|
+
}
|
|
2079
|
+
|
|
2080
|
+
/** GET ?session= → 设计目录里写死的颜色有多少(试穿风格「就用这个」之后提示:这些不跟着变)、有没有深色版 */
|
|
2081
|
+
// GET motion → 组件库清单(带源码在哪,「放进对话」时告诉模型);GET motion?f=like-jelly.html → 那个组件(只认清单里的 id)。
|
|
2082
|
+
// 组件是我们自己写的,但会跑脚本:响应头 CSP sandbox 让它是不透明来源,直接在标签页打开也碰不到 DSH 的登录和接口
|
|
2083
|
+
function motionRoute(req, res) {
|
|
2084
|
+
if (!admit(req, res)) return
|
|
2085
|
+
const f = new URL(req.url, 'http://x').searchParams.get('f')
|
|
2086
|
+
if (f == null) return json(res, 200, { list: listMotion().map((c) => ({ ...c, file: path.join(MOTION_DIR, c.id + '.html') })) })
|
|
2087
|
+
const code = /^[a-z][a-z0-9-]{1,40}\.html$/.test(f) ? motionFile(f.slice(0, -5)) : null
|
|
2088
|
+
if (code == null) return json(res, 404, { error: 'no such component' })
|
|
2089
|
+
const buf = Buffer.from(code, 'utf8')
|
|
2090
|
+
res.writeHead(200, {
|
|
2091
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
2092
|
+
'Content-Length': buf.length,
|
|
2093
|
+
'Cache-Control': 'private, max-age=3600',
|
|
2094
|
+
'X-Content-Type-Options': 'nosniff',
|
|
2095
|
+
'Content-Security-Policy': "sandbox allow-scripts; default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data:; font-src data:; frame-ancestors 'self'",
|
|
2096
|
+
})
|
|
2097
|
+
res.end(buf)
|
|
2098
|
+
}
|
|
2099
|
+
|
|
2100
|
+
// GET showcase → 风格墙清单(每套风格几份成品样板,每份几屏截图);GET showcase?f=alley-noodles-1.webp → 那张图(只认清单里的名字)
|
|
2101
|
+
let showcaseCache = null
|
|
2102
|
+
function showcaseRoute(req, res) {
|
|
2103
|
+
if (!admit(req, res)) return
|
|
2104
|
+
if (!showcaseCache) {
|
|
2105
|
+
try {
|
|
2106
|
+
const files = new Set()
|
|
2107
|
+
const ok = (x) => x && typeof x === 'object'
|
|
2108
|
+
const list = JSON.parse(fs.readFileSync(SHOWCASE_LIST, 'utf8')).filter((x) => ok(x) && /^[a-z][\w-]{0,40}$/.test(x.id) && Array.isArray(x.samples)).map((x) => ({
|
|
2109
|
+
id: x.id,
|
|
2110
|
+
vibe: x.vibe || '',
|
|
2111
|
+
samples: x.samples.filter((m) => ok(m) && /^[\w-]{1,80}$/.test(m.tpl || '') && Array.isArray(m.screens)).map((m) => {
|
|
2112
|
+
const base = m.tpl.replace(/^orderg-x__/, '')
|
|
2113
|
+
const shots = m.screens.map((sc, i) => `${base}-${i + 1}.webp`).filter((f) => fs.existsSync(path.join(SHOWCASE_DIR, f)))
|
|
2114
|
+
shots.forEach((f) => files.add(f))
|
|
2115
|
+
return { tpl: m.tpl, kind: m.kind || 'app', title: m.title || {}, biz: m.biz || {}, total: m.total || shots.length, ar: /^\d+\/\d+$/.test(m.ar || '') ? m.ar : '', screens: m.screens.slice(0, shots.length), shots }
|
|
2116
|
+
}).filter((m) => m.shots.length),
|
|
2117
|
+
})).filter((x) => x.samples.length)
|
|
2118
|
+
showcaseCache = { list, files }
|
|
2119
|
+
} catch (e) {
|
|
2120
|
+
log(e)
|
|
2121
|
+
showcaseCache = { list: [], files: new Set() }
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
const f = new URL(req.url, 'http://x').searchParams.get('f')
|
|
2125
|
+
if (f == null) return json(res, 200, { list: showcaseCache.list })
|
|
2126
|
+
if (!showcaseCache.files.has(f)) return json(res, 404, { error: 'no such shot' })
|
|
2127
|
+
sendWebp(res, path.join(SHOWCASE_DIR, f))
|
|
2128
|
+
}
|
|
2129
|
+
|
|
2130
|
+
function artRoute(req, res) {
|
|
2131
|
+
if (!admit(req, res)) return
|
|
2132
|
+
const file = new URL(req.url, 'http://x').searchParams.get('f') || ''
|
|
2133
|
+
if (!/^[a-z][a-z0-9-]{0,48}\.webp$/.test(file)) return json(res, 404, { error: 'no such art' })
|
|
2134
|
+
sendWebp(res, path.join(ART_DIR, file))
|
|
2135
|
+
}
|
|
2136
|
+
|
|
2137
|
+
function sendWebp(res, file) {
|
|
2138
|
+
let buf
|
|
2139
|
+
try { buf = fs.readFileSync(file) } catch { return json(res, 404, { error: 'no such shot' }) }
|
|
2140
|
+
res.writeHead(200, { 'Content-Type': 'image/webp', 'Content-Length': buf.length, 'Cache-Control': 'private, max-age=86400', 'X-Content-Type-Options': 'nosniff' })
|
|
2141
|
+
res.end(buf)
|
|
2142
|
+
}
|
|
2143
|
+
|
|
2144
|
+
function colorsRoute(req, res) {
|
|
2145
|
+
if (!admit(req, res)) return
|
|
2146
|
+
const session = new URL(req.url, 'http://x').searchParams.get('session') || ''
|
|
2147
|
+
const t = tracker.stateOf(session).target
|
|
2148
|
+
if (!t || t.kind !== 'file') return json(res, 200, { n: 0, files: [], dark: false })
|
|
2149
|
+
json(res, 200, hardColors(t.root))
|
|
2150
|
+
}
|
|
2151
|
+
|
|
1714
2152
|
function historyRoute(req, res) {
|
|
1715
2153
|
if (!admit(req, res)) return
|
|
1716
2154
|
const session = new URL(req.url, 'http://x').searchParams.get('session') || ''
|
|
@@ -1723,13 +2161,21 @@ export function apply(ctx) {
|
|
|
1723
2161
|
let body
|
|
1724
2162
|
try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
|
|
1725
2163
|
try {
|
|
1726
|
-
const r = tracker.restoreVersion(String(body.session || ''), Number(body.n), { root: typeof body.root === 'string' ? body.root : '', at: Number(body.at) || 0 })
|
|
2164
|
+
const r = tracker.restoreVersion(String(body.session || ''), Number(body.n), { targetKey: body.targetKey, op: body.op, planId: body.planId, requestId: body.requestId, root: typeof body.root === 'string' ? body.root : '', at: Number(body.at) || 0 })
|
|
1727
2165
|
json(res, 200, { ...r, versions: tracker.versions(String(body.session || '')) })
|
|
1728
2166
|
} catch (e) {
|
|
1729
|
-
json(res, 400, { error: e.message })
|
|
2167
|
+
json(res, 400, { ok: false, reason: e.code || 'backup', error: e.message })
|
|
1730
2168
|
}
|
|
1731
2169
|
}
|
|
1732
2170
|
|
|
2171
|
+
const transactionRoute = operation => async (req, res) => {
|
|
2172
|
+
if (!admit(req, res)) return
|
|
2173
|
+
if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
|
|
2174
|
+
let body
|
|
2175
|
+
try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
|
|
2176
|
+
json(res, 200, tracker[operation](String(body.session || ''), body))
|
|
2177
|
+
}
|
|
2178
|
+
|
|
1733
2179
|
/** 预览里直接改字:写回这一屏的 HTML;找不到那段字就告诉右侧栏(它会改成让模型去改) */
|
|
1734
2180
|
async function editRoute(req, res) {
|
|
1735
2181
|
if (!admit(req, res)) return
|
|
@@ -1737,7 +2183,8 @@ export function apply(ctx) {
|
|
|
1737
2183
|
let body
|
|
1738
2184
|
try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
|
|
1739
2185
|
try {
|
|
1740
|
-
|
|
2186
|
+
if (body.scope && body.scope !== body.device) return json(res, 200, { ok: false, reason: 'scope' })
|
|
2187
|
+
json(res, 200, tracker.editText(String(body.session || ''), { targetKey: String(body.targetKey || body.target || ''), requestId: body.requestId, key: body.key, before: body.before, after: body.after, nth: body.nth, sig: typeof body.sig === 'string' ? body.sig : '', raw: typeof body.raw === 'string' ? body.raw : '' }))
|
|
1741
2188
|
} catch (e) {
|
|
1742
2189
|
json(res, 500, { error: e.message })
|
|
1743
2190
|
}
|
|
@@ -1752,10 +2199,10 @@ export function apply(ctx) {
|
|
|
1752
2199
|
try {
|
|
1753
2200
|
const id = String(body.session || '')
|
|
1754
2201
|
// 右侧栏点的时候是哪套设计:中途换了(这次保存晚到)就不写,免得写进另一套同名的屏
|
|
1755
|
-
if (
|
|
2202
|
+
if ((body.targetKey || body.target) && !tracker.accepts(tracker.stateOf(id).target, body.targetKey || body.target)) return json(res, 200, { ok: false, reason: 'moved' })
|
|
1756
2203
|
const rule = body.rule && typeof body.rule === 'object' ? body.rule : null
|
|
1757
2204
|
if (rule) return json(res, 200, styleToRule(id, body, rule))
|
|
1758
|
-
json(res, 200, tracker.editStyle(id, { key: body.key, loc: body.loc, css: body.css, name: body.name, imp: Array.isArray(body.imp) ? body.imp.slice(0, 20) : [] }))
|
|
2205
|
+
json(res, 200, tracker.editStyle(id, { key: body.key, loc: body.loc, css: body.css, name: body.name, requestId: body.requestId, imp: Array.isArray(body.imp) ? body.imp.slice(0, 20) : [] }))
|
|
1759
2206
|
} catch (e) {
|
|
1760
2207
|
json(res, 500, { error: e.message })
|
|
1761
2208
|
}
|
|
@@ -1776,10 +2223,10 @@ export function apply(ctx) {
|
|
|
1776
2223
|
if (!hit || !hit.real) return { ok: false, reason: 'no-rule' }
|
|
1777
2224
|
const key = String(body.key || path.basename(t.file))
|
|
1778
2225
|
let html = ''
|
|
1779
|
-
try { html = fs.readFileSync(path.join(t.root, path.basename(key)), 'utf8') } catch { /*
|
|
2226
|
+
try { html = fs.readFileSync(path.join(t.root, path.basename(key)), 'utf8') } catch { /* 读不了就当没套外壳 */ }
|
|
1780
2227
|
const locked = new Set(frameCss(t.root, [html]).map((x) => x.toLowerCase()))
|
|
1781
2228
|
if (locked.has(path.basename(hit.abs).toLowerCase())) return { ok: false, reason: 'frame' }
|
|
1782
|
-
return tracker.editRule(id, { key, loc: body.loc, file: hit.abs, sel: String(rule.sel || '').slice(0, 400), n: Math.max(0, Math.floor(Number(rule.n) || 0)), css: body.css, name: body.name, cls: String(rule.cls || '').slice(0, 80) })
|
|
2229
|
+
return tracker.editRule(id, { key, loc: body.loc, file: hit.abs, sel: String(rule.sel || '').slice(0, 400), n: Math.max(0, Math.floor(Number(rule.n) || 0)), css: body.css, name: body.name, requestId: body.requestId, cls: String(rule.cls || '').slice(0, 80) })
|
|
1783
2230
|
}
|
|
1784
2231
|
|
|
1785
2232
|
/**
|
|
@@ -1808,7 +2255,7 @@ export function apply(ctx) {
|
|
|
1808
2255
|
const t = st && st.target
|
|
1809
2256
|
if (!t || t.kind !== 'file') return json(res, 200, { map: {} })
|
|
1810
2257
|
const map = {}
|
|
1811
|
-
for (const k of
|
|
2258
|
+
for (const k of tracker.scopeFor(t).pages.slice(0, MAX_PAGES)) {
|
|
1812
2259
|
const list = statesOfFile(path.join(t.root, k))
|
|
1813
2260
|
if (list.length) map[k] = list
|
|
1814
2261
|
}
|
|
@@ -1825,7 +2272,7 @@ export function apply(ctx) {
|
|
|
1825
2272
|
const cls = String(body.cls || '')
|
|
1826
2273
|
const sig = String(body.sig || '')
|
|
1827
2274
|
if (!t || t.kind !== 'file' || !/^-?[_a-zA-Z][\w-]{0,79}$/.test(cls) || !sig) return json(res, 200, { same: false })
|
|
1828
|
-
const files =
|
|
2275
|
+
const files = tracker.scopeFor(t).pages.slice(0, MAX_PAGES)
|
|
1829
2276
|
const stats = files.map((k) => { try { return fs.statSync(path.join(t.root, k)) } catch { return null } })
|
|
1830
2277
|
const stamp = files.map((k, i) => (stats[i] ? `${k}:${stats[i].mtimeMs}:${stats[i].size}` : '')).join('|')
|
|
1831
2278
|
const ck = `${t.root}|${cls}`
|
|
@@ -1901,9 +2348,9 @@ export function apply(ctx) {
|
|
|
1901
2348
|
* 一个文件现在的样子。inode 也看:编辑器常写临时文件再换名,mtime 可能没变但文件已经换了。
|
|
1902
2349
|
* 读不到记 '-',后来才建出来的文件会让判断从 '-' 变成新值,缓存自然失效。
|
|
1903
2350
|
*/
|
|
1904
|
-
function stampOf(
|
|
2351
|
+
function stampOf(ref, v, rel) {
|
|
1905
2352
|
try {
|
|
1906
|
-
const f = bundleFile(
|
|
2353
|
+
const f = bundleFile(ref, v, rel)
|
|
1907
2354
|
if (!f) return '-'
|
|
1908
2355
|
const s = fs.statSync(f)
|
|
1909
2356
|
return `${s.mtimeMs}:${s.size}:${s.ino}`
|
|
@@ -1916,9 +2363,10 @@ export function apply(ctx) {
|
|
|
1916
2363
|
* 打包时这个文件从哪读。打包(read)、印记(stampOf)、命中时重算 strict 都走这一套:
|
|
1917
2364
|
* 旧版本里没有这个文件时,都退回目录里的当前文件,不然退回的那份改了、缓存却不会失效
|
|
1918
2365
|
*/
|
|
1919
|
-
function bundleFile(
|
|
2366
|
+
function bundleFile(ref, v, rel) {
|
|
2367
|
+
const root = typeof ref === 'string' ? ref : ref.root
|
|
1920
2368
|
let f = ''
|
|
1921
|
-
if (v) f = history.fileOf(
|
|
2369
|
+
if (v) f = history.fileOf(ref, v, rel) || ''
|
|
1922
2370
|
// 组件文件(#30):旧版本只认那一版快照里的,没有就是没有(不拿现在的顶上,不然旧版本会混进新组件)
|
|
1923
2371
|
if (v && /^components\//.test(rel)) return f
|
|
1924
2372
|
// 模拟数据和预览一个规矩(serve.js versionMock / mockOf):旧版本只认那一版自己的 mock.json(那版没有就是没有,
|
|
@@ -1928,7 +2376,7 @@ export function apply(ctx) {
|
|
|
1928
2376
|
const p = path.join(root, MOCK_FILE)
|
|
1929
2377
|
try { return fs.lstatSync(p).isFile() ? p : '' } catch { return '' }
|
|
1930
2378
|
}
|
|
1931
|
-
if (!f) {
|
|
2379
|
+
if (!f && !v) {
|
|
1932
2380
|
const hit = resolveInRoot(root, '/' + rel.split('/').map(encodeURIComponent).join('/'))
|
|
1933
2381
|
f = hit && hit.real ? hit.real : ''
|
|
1934
2382
|
}
|
|
@@ -1982,6 +2430,10 @@ export function apply(ctx) {
|
|
|
1982
2430
|
const key = q.get('key') || path.basename(t.file)
|
|
1983
2431
|
if (!/^[^\\]+\.html?$/i.test(key) || key.split('/').some((p) => !p || p === '.' || p === '..')) return json(res, 400, { error: 'bad key' })
|
|
1984
2432
|
const v = Math.max(0, Math.floor(Number(q.get('v')) || 0))
|
|
2433
|
+
const at = q.get('at')
|
|
2434
|
+
if (q.get('targetKey') && !matchesTarget(t, q.get('targetKey'))) return json(res, 409, { error: 'moved' })
|
|
2435
|
+
const row = v > 0 ? tracker.versions(q.get('session') || '').find(x => x.n === v && (!at || Number(at) === x.at)) : null
|
|
2436
|
+
if (!(v > 0 ? row?.screens : tracker.scopeFor(t).pages)?.includes(key)) return json(res, 404, { error: 'no-screen' })
|
|
1985
2437
|
let parent = ''
|
|
1986
2438
|
try { const u = new URL(q.get('parent') || ''); if (u.protocol === 'http:' || u.protocol === 'https:') parent = u.origin } catch { parent = '' }
|
|
1987
2439
|
// 一页多状态(#30):?state=paid 打包时就把 <html data-state> 设好(沙盒里的 srcdoc 没有地址参数,设状态那段读不到)
|
|
@@ -1993,11 +2445,11 @@ export function apply(ctx) {
|
|
|
1993
2445
|
// 大小又没变,印记一模一样,光靠标记永远换不出新内容
|
|
1994
2446
|
const fresh = q.get('fresh') === '1'
|
|
1995
2447
|
// 打的是哪个目标:右侧栏拿它核对,请求发出后会话换了目录(或预览服务器换了端口)的回包不存进它的缓存
|
|
1996
|
-
const whose = { root: t.root, origin: st.origin || '' }
|
|
2448
|
+
const whose = { targetKey: t.targetKey, root: t.root, origin: st.origin || '' }
|
|
1997
2449
|
// 先看大小,太大的不读(打包总量也封顶,见 bundle.js)
|
|
1998
2450
|
const big = new Set() // 有、但太大没读的
|
|
1999
2451
|
const readRel = (rel) => {
|
|
2000
|
-
const f = bundleFile(t
|
|
2452
|
+
const f = bundleFile(t, v, rel)
|
|
2001
2453
|
if (!f) return null
|
|
2002
2454
|
const s = fs.statSync(f)
|
|
2003
2455
|
if (s.isFile() && s.size > BUNDLE_MAX) big.add(rel)
|
|
@@ -2013,7 +2465,7 @@ export function apply(ctx) {
|
|
|
2013
2465
|
let hit = false
|
|
2014
2466
|
try {
|
|
2015
2467
|
hit = !!had && had.href === href && had.parent === parent && had.v === v && had.picker === pickerStamp()
|
|
2016
|
-
&& [...had.stamps].every(([rel, stamp]) => stampOf(t
|
|
2468
|
+
&& [...had.stamps].every(([rel, stamp]) => stampOf(t, v, rel) === stamp)
|
|
2017
2469
|
if (hit) { const page = readRel(key); hit = !!page && !strictOf(page) }
|
|
2018
2470
|
} catch {
|
|
2019
2471
|
hit = false
|
|
@@ -2028,7 +2480,7 @@ export function apply(ctx) {
|
|
|
2028
2480
|
const deps = new Set() // 这一屏用到的文件(含没找到的):右侧栏看到这些改了才重新打包
|
|
2029
2481
|
const pre = new Map() // 读之前的印记:和读完后的对不上(打包这段时间里被改、被删)就不进缓存
|
|
2030
2482
|
const read = (rel) => {
|
|
2031
|
-
if (!deps.has(rel)) { deps.add(rel); pre.set(rel, stampOf(t
|
|
2483
|
+
if (!deps.has(rel)) { deps.add(rel); pre.set(rel, stampOf(t, v, rel)) }
|
|
2032
2484
|
return readRel(rel)
|
|
2033
2485
|
}
|
|
2034
2486
|
if (!(v > 0)) read.hasCompDir = () => hasCompDir(t.root) // 旧版本:快照里有用到的组件文件才算(见 adopts)
|
|
@@ -2046,12 +2498,12 @@ export function apply(ctx) {
|
|
|
2046
2498
|
const mockAssets = mk ? dataAssets(mk.data, read, BUNDLE_MAX, over, (rel) => big.has(rel)) : null
|
|
2047
2499
|
// 换不下的图(太大):不悄悄留成坏图,报进这屏的页面错误(体检、屏上看得到)
|
|
2048
2500
|
const mockErr = mk ? [mk.err, over.length ? `数据里的图太大,远程看时没带上:${over.slice(0, 3).join('、')}${over.length > 3 ? ' 等' : ''}` : ''].filter(Boolean).join(';') : ''
|
|
2049
|
-
const mockTag = mk ? mockScript({ ...mk, assets: mockAssets, err: mockErr }, { scope:
|
|
2501
|
+
const mockTag = mk ? mockScript({ ...mk, assets: mockAssets, err: mockErr }, { scope: t.designId }) : ''
|
|
2050
2502
|
const lead = strict ? strictMeta(nonce) + (ERR_CATCHER + setState + mockTag).replaceAll('<script>', `<script nonce="${nonce}">`) : ERR_CATCHER + setState + mockTag
|
|
2051
2503
|
// 组件(#30):先展开(读组件也走 read:记进用到的文件,组件一改就重新打包);别人做的按原始字节认,展开后再去脚本
|
|
2052
2504
|
let text = page.toString('utf8')
|
|
2053
2505
|
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) })
|
|
2506
|
+
let html = bundle(strict ? defang(text) : text, { key, read, base: href, lead, tail: inlinePicker(`window.__DSH_READ_FOLDER__=${readDropFolder};\n` + fs.readFileSync(PICKER_FILE, 'utf8'), parent, href, nonce, sigOf(page)) })
|
|
2055
2507
|
// 打包后图片变成 data: 地址,文件名没了:把用到的 AI 示意图记在页面里,导出时照样提醒
|
|
2056
2508
|
const aiNames = [...deps].filter((x) => isPhotoAsset(x)).map((x) => path.basename(x))
|
|
2057
2509
|
if (aiNames.length) html = html.replace(lead, () => `${lead}<meta name="ddp-ai-photos" content="${aiNames.join(',').replace(/[^a-z0-9.,-]/gi, '')}">`)
|
|
@@ -2059,7 +2511,7 @@ export function apply(ctx) {
|
|
|
2059
2511
|
if (deps.size > 200) return json(res, 200, { html, deps: null, strict, ...whose })
|
|
2060
2512
|
// strict 那一份里带的是这次现生成的随机 nonce:不复用,也就不进缓存
|
|
2061
2513
|
if (strict) return json(res, 200, { html, deps: [...deps], strict, ...whose })
|
|
2062
|
-
const stamps = new Map([...deps].map((rel) => [rel, stampOf(t
|
|
2514
|
+
const stamps = new Map([...deps].map((rel) => [rel, stampOf(t, v, rel)]))
|
|
2063
2515
|
const body = JSON.stringify({ html, deps: [...deps], strict, ...whose })
|
|
2064
2516
|
// 这几种情况不进缓存:打包这段时间里有文件变了(读之前和读完后的印记对不上:被改、被换、被删,
|
|
2065
2517
|
// 可能是半新半旧),picker 换了,或者某个文件刚刚才写过(2 秒内的 mtime 说明它还在被反复改,
|
|
@@ -2087,7 +2539,7 @@ export function apply(ctx) {
|
|
|
2087
2539
|
/** 导出的图片存哪:本地文件预览存设计目录的 exports/,开发服务器存「下载」 */
|
|
2088
2540
|
function exportDir(session) {
|
|
2089
2541
|
const st = tracker.stateOf(session)
|
|
2090
|
-
if (st.target
|
|
2542
|
+
if (st.target?.directory) return path.join(st.target.root, 'exports')
|
|
2091
2543
|
return path.join(os.homedir(), 'Downloads')
|
|
2092
2544
|
}
|
|
2093
2545
|
|
|
@@ -2114,9 +2566,9 @@ export function apply(ctx) {
|
|
|
2114
2566
|
}
|
|
2115
2567
|
|
|
2116
2568
|
/** 导出途中换了设计:还按开始时的那套比一下,对不上就不存(不然 A 的文件会落到 B 的 exports/ 里) */
|
|
2117
|
-
const targetKeyOf =
|
|
2569
|
+
const targetKeyOf = designKey
|
|
2118
2570
|
function targetMoved(res, session, expect) {
|
|
2119
|
-
if (typeof expect !== 'string' || !expect ||
|
|
2571
|
+
if (typeof expect !== 'string' || !expect || tracker.accepts(tracker.stateOf(session).target, expect)) return false
|
|
2120
2572
|
json(res, 409, { error: 'designChanged' })
|
|
2121
2573
|
return true
|
|
2122
2574
|
}
|
|
@@ -2128,7 +2580,7 @@ export function apply(ctx) {
|
|
|
2128
2580
|
try { body = await readBody(req, MAX_EXPORT) } catch (e) { return json(res, 400, { error: e.message }) }
|
|
2129
2581
|
const buf = Buffer.from(String(body.png || ''), 'base64')
|
|
2130
2582
|
if (buf.length < 8 || buf.readUInt32BE(0) !== 0x89504e47) return json(res, 400, { error: '不是 PNG' })
|
|
2131
|
-
if (targetMoved(res, String(body.session || ''), body.target)) return
|
|
2583
|
+
if (targetMoved(res, String(body.session || ''), (body.targetKey || body.target))) return
|
|
2132
2584
|
saveExport(res, String(body.session || ''), body.name, 'png', buf)
|
|
2133
2585
|
}
|
|
2134
2586
|
|
|
@@ -2146,9 +2598,14 @@ export function apply(ctx) {
|
|
|
2146
2598
|
if (!t || t.kind !== 'file') return json(res, 200, { pages: [] })
|
|
2147
2599
|
const v = Math.max(0, Math.floor(Number(body.v) || 0))
|
|
2148
2600
|
// 没挑屏 = 整套:某一版就按那一版存下的屏(后来删掉的屏旧版里还在,截图会截到)
|
|
2149
|
-
|
|
2150
|
-
const
|
|
2151
|
-
|
|
2601
|
+
if (targetMoved(res, String(body.session || ''), body.targetKey || body.target)) return
|
|
2602
|
+
const version = v > 0 ? history.find(t, v, body.at) : null
|
|
2603
|
+
if (v > 0 && !version) return json(res, 404, { error: 'gone' })
|
|
2604
|
+
const allowed = version ? tracker.versions(String(body.session || '')).find(row => row.n === v).screens : tracker.scopeFor(t).pages
|
|
2605
|
+
const keys = Array.isArray(body.keys) ? [...new Set(body.keys.filter(k => typeof k === 'string').map(k => k.replace(/^v\d+\|/, '').split(/[?#]/)[0]))].slice(0, 2000) : allowed
|
|
2606
|
+
const missing = keys.filter(key => !allowed.includes(key))
|
|
2607
|
+
if (missing.length) return json(res, 409, { error: 'scope', files: missing })
|
|
2608
|
+
const read = v > 0 ? versionReader(history, t, v) : dirReader(t.root)
|
|
2152
2609
|
let pages = []
|
|
2153
2610
|
try { pages = precheckScreens(keys, read) } catch (e) { log(e); return json(res, 500, { error: 'compcheck' }) } // 查不了不当成没错
|
|
2154
2611
|
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 })) })) })
|
|
@@ -2169,7 +2626,7 @@ export function apply(ctx) {
|
|
|
2169
2626
|
const hid = tracker.hiddenScreens(session)
|
|
2170
2627
|
if (!hid.length) return json(res, 200, { target: targetKeyOf(t), list: [] })
|
|
2171
2628
|
const on = new Set(hid)
|
|
2172
|
-
const all = exportOrder(st.screens, hid,
|
|
2629
|
+
const all = exportOrder(st.screens, hid, tracker.scopeFor(t).pages)
|
|
2173
2630
|
const keys = all.slice(0, MAX_PAGES) // 一次最多导出这么多屏,多的(排在最后的)右侧栏提示没导出
|
|
2174
2631
|
const list = keys.map((key) => {
|
|
2175
2632
|
let title = ''
|
|
@@ -2258,7 +2715,7 @@ export function apply(ctx) {
|
|
|
2258
2715
|
} catch (e) {
|
|
2259
2716
|
return json(res, 400, { error: e.message })
|
|
2260
2717
|
}
|
|
2261
|
-
if (targetMoved(res, session, body.target)) return
|
|
2718
|
+
if (targetMoved(res, session, (body.targetKey || body.target))) return
|
|
2262
2719
|
saveExport(res, session, body.name, format, buf)
|
|
2263
2720
|
}
|
|
2264
2721
|
|
|
@@ -2273,7 +2730,7 @@ export function apply(ctx) {
|
|
|
2273
2730
|
screens.push({ key: s.key, label: String(s.label || s.key).slice(0, 80), top: s.top === true })
|
|
2274
2731
|
}
|
|
2275
2732
|
if (!screens.length) return null
|
|
2276
|
-
const dim = (x, d) => (Number.isFinite(+x) && +x >=
|
|
2733
|
+
const dim = (x, d) => (Number.isFinite(+x) && +x >= 64 && +x <= 8000 ? Math.round(+x) : d)
|
|
2277
2734
|
const tw = body.tweak && typeof body.tweak === 'object' ? body.tweak : null
|
|
2278
2735
|
const plain = (o) => Object.fromEntries(Object.entries(o && typeof o === 'object' ? o : {}).filter(([k, x]) => typeof k === 'string' && k.length < 80 && (typeof x === 'string' || typeof x === 'number' || x === null || typeof x === 'boolean')).slice(0, 200))
|
|
2279
2736
|
return {
|
|
@@ -2293,13 +2750,27 @@ export function apply(ctx) {
|
|
|
2293
2750
|
}
|
|
2294
2751
|
|
|
2295
2752
|
/** 打包一个设计目录(v 是历史版本,0 = 现在的文件):deps 是读过的相对路径,files 是对应的文件(公网链接按它们判断要不要重新打包) */
|
|
2296
|
-
function packDesign(
|
|
2753
|
+
function packDesign(ref, v, params) {
|
|
2754
|
+
const root = typeof ref === 'string' ? ref : ref.root
|
|
2755
|
+
const version = v > 0 && history.find(ref, v, params.at)
|
|
2756
|
+
if (v > 0) {
|
|
2757
|
+
if (!version) throw Object.assign(Error('这一版已经不在了'), { code: 'gone' })
|
|
2758
|
+
history.contents(ref, version)
|
|
2759
|
+
}
|
|
2760
|
+
if (typeof ref === 'object') {
|
|
2761
|
+
const allowed = version ? history.list(ref).find(row => row.n === v).screens : tracker.scopeFor(ref).pages
|
|
2762
|
+
const absent = params.screens.map(s => s.key).filter(key => !allowed.includes(key))
|
|
2763
|
+
if (absent.length) throw Object.assign(Error('设计范围已更新'), { code: 'scope', files: absent })
|
|
2764
|
+
}
|
|
2297
2765
|
const deps = new Set()
|
|
2298
2766
|
const files = new Set()
|
|
2299
2767
|
const big = new Set() // 有、但太大没读的(数据里绑的图读不了要报出来,不能当没有)
|
|
2768
|
+
const versionRow = version ? history.list(ref).find(row => row.n === v) : null
|
|
2769
|
+
const settings = versionRow?.settings || params.pageSettings
|
|
2300
2770
|
const read = (rel) => {
|
|
2771
|
+
if (rel === 'page-settings.json' && settings) return Buffer.from(JSON.stringify(settings))
|
|
2301
2772
|
deps.add(rel)
|
|
2302
|
-
const f = bundleFile(
|
|
2773
|
+
const f = bundleFile(ref, v, rel)
|
|
2303
2774
|
files.add(f || path.join(root, ...rel.split('/')))
|
|
2304
2775
|
if (!f) return null
|
|
2305
2776
|
const s = fs.statSync(f)
|
|
@@ -2313,8 +2784,10 @@ export function apply(ctx) {
|
|
|
2313
2784
|
const p = f && studio.fonts.cached(id)
|
|
2314
2785
|
return p ? { family: f.family, weights: f.weights, data: fs.readFileSync(p) } : null
|
|
2315
2786
|
}
|
|
2787
|
+
const viewport = versionRow?.viewports?.[params.screens[0]?.key]
|
|
2788
|
+
const overall = viewport ? { kind: viewport.kind, w: viewport.w, h: viewport.h, os: viewport.os, dark: !!version.display?.dark, fit: !!version.display?.fit, tweak: null } : {}
|
|
2316
2789
|
let pack
|
|
2317
|
-
try { pack = buildPack({ ...params, read, bigOf: (rel) => big.has(rel), strictOf, libFont }) } catch (e) {
|
|
2790
|
+
try { pack = buildPack({ ...params, ...overall, viewports: versionRow?.viewports, read, bigOf: (rel) => big.has(rel), strictOf, libFont }) } catch (e) {
|
|
2318
2791
|
// 打不出来(比如组件有错、缺组件):带上这次读过和想读的文件,公网链接看着它们,改好了自己重打
|
|
2319
2792
|
if (e && typeof e === 'object') e.deps = [...files]
|
|
2320
2793
|
throw e
|
|
@@ -2335,23 +2808,24 @@ export function apply(ctx) {
|
|
|
2335
2808
|
const st = tracker.stateOf(session)
|
|
2336
2809
|
const t = st && st.target
|
|
2337
2810
|
if (!t || t.kind !== 'file') return json(res, 400, { error: 'not-file' })
|
|
2338
|
-
if (targetMoved(res, session, body.target)) return
|
|
2339
|
-
const v = Math.max(0, Math.floor(Number(body.v) || 0))
|
|
2811
|
+
if (targetMoved(res, session, (body.targetKey || body.target))) return
|
|
2812
|
+
const v = Math.max(0, Math.floor(Number(body.n || body.v) || 0))
|
|
2813
|
+
if (v && body.targetKey && !body.at) return json(res, 400, { error: 'gone' })
|
|
2340
2814
|
const params = packParams(body)
|
|
2341
2815
|
if (!params) return json(res, 400, { error: 'noScreens' })
|
|
2342
2816
|
let pack, deps
|
|
2343
2817
|
try {
|
|
2344
|
-
;({ pack, deps } = packDesign(t
|
|
2818
|
+
;({ pack, deps } = packDesign(t, v, { ...params, at: body.at, pageSettings: tracker.snapshot(session).pageSettings, ...(v ? { title: (params.title || path.basename(t.root)) + ' (v' + v + ')' } : {}) }))
|
|
2345
2819
|
} catch (e) {
|
|
2346
2820
|
// compErr(#30):哪几屏的组件有错,右侧栏列出来、能点过去
|
|
2347
2821
|
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 } : {}) })
|
|
2348
2822
|
}
|
|
2349
2823
|
// 打包时会话换了设计:别把 A 的演示存进 B 的 exports/
|
|
2350
|
-
if (targetMoved(res, session, body.target)) return
|
|
2824
|
+
if (targetMoved(res, session, (body.targetKey || body.target))) return
|
|
2351
2825
|
const ai = new Set([...deps].filter((x) => isPhotoAsset(x)).map((x) => path.basename(x)))
|
|
2352
2826
|
try {
|
|
2353
|
-
const file = writeExport(session, body.name, 'html', Buffer.from(pack.html, 'utf8'))
|
|
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 })
|
|
2827
|
+
const file = writeExport(session, v && !new RegExp('(?:^|-)v' + v + '(?:-|$)').test(String(body.name || '')) ? String(body.name || 'design') + '-v' + v : body.name, 'html', Buffer.from(pack.html, 'utf8'))
|
|
2828
|
+
json(res, 200, { path: file, ...(v ? { n: v, at: history.find(t, v, body.at)?.at } : {}), 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 })
|
|
2355
2829
|
} catch (e) {
|
|
2356
2830
|
json(res, 500, { error: e.message })
|
|
2357
2831
|
}
|
|
@@ -2376,16 +2850,19 @@ export function apply(ctx) {
|
|
|
2376
2850
|
const buf = Buffer.from(String(body.data || ''), 'base64')
|
|
2377
2851
|
const ext = imageExt(buf)
|
|
2378
2852
|
if (!ext) return json(res, 400, { error: '不是图片' })
|
|
2379
|
-
const
|
|
2853
|
+
const session = String(body.session || '')
|
|
2854
|
+
const st = tracker.stateOf(session)
|
|
2380
2855
|
// 画笔标注带着画的那份设计的目录来:这期间换了设计,别把旧图存进新设计
|
|
2856
|
+
if (targetMoved(res, session, body.targetKey)) return
|
|
2381
2857
|
if (typeof body.root === 'string' && !(st.target && st.target.kind === 'file' && st.target.root === body.root)) return json(res, 409, { error: 'moved' })
|
|
2382
|
-
const dir =
|
|
2858
|
+
const dir = !body.newDesign && st.target?.directory ? path.join(st.target.root, 'refs')
|
|
2859
|
+
: !body.newDesign && st.target?.scope === 'file' ? path.join(REFS_DIR, st.target.designId) : REFS_DIR
|
|
2383
2860
|
const base = String(body.name || 'ref').replace(/\.[a-z0-9]{2,5}$/i, '').replace(/[^\w\u4e00-\u9fff-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'ref'
|
|
2384
2861
|
try {
|
|
2385
2862
|
fs.mkdirSync(dir, { recursive: true })
|
|
2386
2863
|
let file = path.join(dir, `${base}.${ext}`)
|
|
2387
2864
|
for (let i = 2; fs.existsSync(file) && i < 1000; i++) file = path.join(dir, `${base}-${i}.${ext}`)
|
|
2388
|
-
fs.writeFileSync(file, buf)
|
|
2865
|
+
fs.writeFileSync(file, buf, { flag: 'wx' })
|
|
2389
2866
|
json(res, 200, { path: file })
|
|
2390
2867
|
} catch (e) {
|
|
2391
2868
|
json(res, 500, { error: e.message })
|
|
@@ -2414,7 +2891,18 @@ export function apply(ctx) {
|
|
|
2414
2891
|
try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
|
|
2415
2892
|
const session = String(body.session || '')
|
|
2416
2893
|
if (!session) return json(res, 400, { error: '缺 session' })
|
|
2417
|
-
if (
|
|
2894
|
+
if (targetMoved(res, session, body.targetKey || body.target)) return
|
|
2895
|
+
const target = tracker.stateOf(session).target
|
|
2896
|
+
const acceptsPage = value => {
|
|
2897
|
+
if (target?.kind !== 'file') return true
|
|
2898
|
+
if (!value.startsWith('/') || value.startsWith('//')) return false
|
|
2899
|
+
try {
|
|
2900
|
+
const pathname = new URL(value, 'http://localhost').pathname
|
|
2901
|
+
const key = decodeURIComponent(pathname.slice(1))
|
|
2902
|
+
return scopeFor(target).pages.includes(key)
|
|
2903
|
+
} catch { return false }
|
|
2904
|
+
}
|
|
2905
|
+
if (typeof body.follow === 'string') return json(res, acceptsPage(body.follow) ? 200 : 409, { ok: acceptsPage(body.follow) && phone.follow(session, body.follow) })
|
|
2418
2906
|
if (body.on === false) {
|
|
2419
2907
|
phone.stop(session)
|
|
2420
2908
|
return json(res, 200, phone.status(session))
|
|
@@ -2422,7 +2910,11 @@ export function apply(ctx) {
|
|
|
2422
2910
|
if (!tracker.snapshot(session).origin) return json(res, 400, { error: '还没有在预览的页面' })
|
|
2423
2911
|
// keep:右侧栏只是换了一屏,入口已经关了(别处点了停止、闲着自动关)就别重开
|
|
2424
2912
|
if (body.keep === true && !phone.status(session).on) return json(res, 200, phone.status(session))
|
|
2425
|
-
const
|
|
2913
|
+
const requested = typeof body.path === 'string' && body.path.startsWith('/') ? body.path : '/'
|
|
2914
|
+
const entry = scopeFor(target).entry
|
|
2915
|
+
const show = target?.kind === 'file' && requested === '/' && entry ? '/' + encodeURIComponent(entry) : requested
|
|
2916
|
+
if (!acceptsPage(show)) return json(res, 409, { error: 'scope' })
|
|
2917
|
+
const st = await phone.start(session, show)
|
|
2426
2918
|
// 二维码一行一串 0 / 1,右侧栏画成 SVG
|
|
2427
2919
|
json(res, 200, st.on ? { ...st, qr: qrMatrix(st.url).map((row) => row.map((c) => (c ? 1 : 0)).join('')) } : st)
|
|
2428
2920
|
}
|
|
@@ -2453,10 +2945,11 @@ export function apply(ctx) {
|
|
|
2453
2945
|
}
|
|
2454
2946
|
const t = tracker.stateOf(session).target
|
|
2455
2947
|
if (!t || t.kind !== 'file') return json(res, 400, { error: 'not-file' })
|
|
2456
|
-
if (targetMoved(res, session, body.target)) return
|
|
2948
|
+
if (targetMoved(res, session, (body.targetKey || body.target))) return
|
|
2457
2949
|
const params = packParams(body)
|
|
2458
2950
|
if (!params) return json(res, 400, { error: 'noScreens' })
|
|
2459
|
-
|
|
2951
|
+
if (params.screens.some(screen => !tracker.scopeFor(t).pages.includes(screen.key))) return json(res, 409, { error: 'scope' })
|
|
2952
|
+
const p = { root: t.root, target: t, pageSettings: tracker.snapshot(session).pageSettings, ...params }
|
|
2460
2953
|
// 右侧栏换了屏、画幅、深浅色:开着就跟着换,没开不新开(开要人点)
|
|
2461
2954
|
if (body.update === true) return json(res, 200, { ok: pub.update(session, p) })
|
|
2462
2955
|
const r = await pub.start(session, p, { name: params.title || path.basename(t.root) })
|
|
@@ -2495,7 +2988,7 @@ export function apply(ctx) {
|
|
|
2495
2988
|
} catch (e) { log(e) }
|
|
2496
2989
|
return ''
|
|
2497
2990
|
}
|
|
2498
|
-
const lib = createLibraryRoutes({ admit, readBody, json, tracker, library, inspiration, studio, open, storeLoad: fileStore.load, version: VERSION, exported, log, sessionCwd, vocab: () => market.vocab() })
|
|
2991
|
+
const lib = createLibraryRoutes({ admit, readBody, json, tracker, library, history, inspiration, studio, open, storeLoad: fileStore.load, version: VERSION, exported, log, sessionCwd, vocab: () => market.vocab(), catalog: () => market.view() })
|
|
2499
2992
|
// 画布上睡着的屏的缩略图(issue #17)
|
|
2500
2993
|
const canvasThumbs = createCanvasThumbs({
|
|
2501
2994
|
tracker,
|
|
@@ -2507,9 +3000,9 @@ export function apply(ctx) {
|
|
|
2507
3000
|
json,
|
|
2508
3001
|
log,
|
|
2509
3002
|
})
|
|
2510
|
-
const mk = createMarketRoutes({ admit, readBody, json, tracker, library, market, open, systemsDir: SYSTEMS_DIR, log, sessionCwd })
|
|
3003
|
+
const mk = createMarketRoutes({ admit, readBody, json, tracker, library, market, open, systemsDir: SYSTEMS_DIR, renderMarketThumb: lib.renderMarketThumb, log, sessionCwd })
|
|
2511
3004
|
|
|
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 }
|
|
3005
|
+
const routes = { dropreader: dropReaderRoute, importhtml: importHtmlRoute, 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, colors: colorsRoute, showcase: showcaseRoute, art: artRoute, motion: motionRoute, rules: rulesRoute, comps: compsRoute, restore: restoreRoute, replay: transactionRoute('replay'), layout: transactionRoute('layout'), screenop: transactionRoute('screenop'), 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, renderreply: renderReplyRoute, implshot: implShotRoute }
|
|
2513
3006
|
for (const [key, handler] of Object.entries(routes)) {
|
|
2514
3007
|
ctx.effect(() => ctx.webServer.register({
|
|
2515
3008
|
kind: 'exact',
|
|
@@ -2543,6 +3036,20 @@ export function apply(ctx) {
|
|
|
2543
3036
|
log(e)
|
|
2544
3037
|
}
|
|
2545
3038
|
}, { global: true })
|
|
3039
|
+
// 项目规矩(2.0):这个会话第一次干活、rules.md 改了以后,开工前给模型一份(同一份不重复给)
|
|
3040
|
+
const rulesSent = new Map()
|
|
3041
|
+
const designSent = new Map()
|
|
3042
|
+
const rulesNote = (id, lang, t) => {
|
|
3043
|
+
if (!t || t.kind !== 'file' || t.scope === 'file') return null
|
|
3044
|
+
const r = readRules(t.root)
|
|
3045
|
+
const prev = rulesSent.get(id)
|
|
3046
|
+
const foreign = rulesForeign(t.root, r ? r.text : '') // 没有规矩也先判断一次:旧版本装的设计这时记下「包里没带」
|
|
3047
|
+
if (!r || !r.text.trim()) { if (prev) rulesSent.delete(id); return null }
|
|
3048
|
+
const key = t.root + '\0' + r.fp
|
|
3049
|
+
if (prev === key) return null
|
|
3050
|
+
rulesSent.set(id, key)
|
|
3051
|
+
return rulesNotice(r.text, t.root, lang, !!prev && prev.startsWith(t.root + '\0'), foreign)
|
|
3052
|
+
}
|
|
2546
3053
|
// 用户在右侧栏亲手改了设计:模型下一步开始前补一条说明(DSH 自带的时间、操作卡片提醒也是这么加的),
|
|
2547
3054
|
// 免得它凭自己之前写的内容接着改、做进项目时用回旧样子(#28)。老版本 DSH 没有这个事件,就只是收不到
|
|
2548
3055
|
ctx.on('agent/pre-step', async (payload, next) => {
|
|
@@ -2551,10 +3058,28 @@ export function apply(ctx) {
|
|
|
2551
3058
|
if (!decision || decision.kind !== 'enter' || !Array.isArray(decision.messages) || (payload && payload.signal && payload.signal.aborted)) return decision
|
|
2552
3059
|
const id = payload && payload.agent && payload.agent.session && payload.agent.session.id
|
|
2553
3060
|
if (!id) return decision
|
|
2554
|
-
const
|
|
2555
|
-
const
|
|
2556
|
-
if (!
|
|
2557
|
-
|
|
3061
|
+
const sid = String(id)
|
|
3062
|
+
const user = latestUser(decision.messages)
|
|
3063
|
+
if (!user || startsNewDesign(user)) return decision
|
|
3064
|
+
const lang = langOf(decision.messages)
|
|
3065
|
+
const snap = await modelSnapshot(sid)
|
|
3066
|
+
const key = designKey(snap.target)
|
|
3067
|
+
if (!key || !relevantDesign(user, snap, decision.messages)) return decision
|
|
3068
|
+
const edits = tracker.unreadEdits(sid).slice(0, 20)
|
|
3069
|
+
const design = designNotice(snap, lang)
|
|
3070
|
+
const last = designSent.get(sid)
|
|
3071
|
+
const userId = user.id || user
|
|
3072
|
+
const current = (snap.source === 'user' || edits.length || snap.pageSettings?.devices !== undefined
|
|
3073
|
+
|| Object.values(snap.pageSettings?.screens || {}).some(p => p.current || p.followSource)) && design
|
|
3074
|
+
const note = editsNotice(edits, lang, key)
|
|
3075
|
+
if (note) note.id = 'studio-edits-' + crypto.createHash('sha256').update(JSON.stringify([sid, key, edits[0].seq, edits.at(-1).seq])).digest('hex').slice(0, 24)
|
|
3076
|
+
const notes = [
|
|
3077
|
+
note, current && (last?.userId !== userId || last?.text !== current.text) ? current : null, rulesNote(sid, lang, snap.target),
|
|
3078
|
+
].filter(n => n && !decision.messages.some(message => message.id === n.id))
|
|
3079
|
+
if (current) designSent.set(sid, { userId, text: current.text })
|
|
3080
|
+
else designSent.delete(sid)
|
|
3081
|
+
if (!notes.length) return decision
|
|
3082
|
+
return { ...decision, messages: [...decision.messages, ...notes.map((n) => noticeMessage(n, n.id || crypto.randomUUID()))] }
|
|
2558
3083
|
} catch (e) {
|
|
2559
3084
|
log(e)
|
|
2560
3085
|
return decision
|