Files
dacli/src/webapi/datascreen.ts
T
ssw c79169de06 P1-4 修复: bigscreen validProp 源改为 dicOption.dataList (2026-07-02)
FINDING-B5: validProp 源错, 旧版走 option/components/*.vue 目录扫描 (36 个)
  - 漏 code/imgList/imgTabs/rectangle (web 真实支持但 components/ 目录下没有)
  - 用户 --prop=code → 误报'不在 36 个有效列表里', 但 web 设计器完全允许
  - 反向逻辑: configData 当 prop 冲突黑名单, 实际是 mixins/index.js:35 的 config 顶层字段标识

修复:
- 新加 webapi/datascreen.ts:getValidProps() 函数
  - 读 jnpf-web-datascreen-vue3/src/option/config.js:268 dicOption.dataList
  - 正则提取 hardcoded 30 个 (含 code/imgList/imgTabs/rectangle)
  - 跳过后续 .concat(website.componentsList...) (需登录态)
- construct.ts: 优先 getValidProps(), 兜底 listComponentProps()
- testspace 验证: 29 个有效 prop (30 - img 重复), 旧版 36

审计: dacli/docs/cmd-review/v0.14-rollout-audit-2026-07-02.md §1.1 B5
2026-07-02 12:19:22 +08:00

598 lines
23 KiB
TypeScript

/**
* webapi/datascreen.ts — 镜像 jnpf-web-datascreen-vue3 独立大屏 webapp (v0.13+ jxcj 2026-07-01)
*
* 重要发现 (jxcj 2026-07-01):
* - jnpf 6.x 大屏 web 端是 **jnpf-web-datascreen-vue3 独立编译项目** (不是 jnpf-web-apps-main)
* - 路径: jnpf/前端/jnpf-web-datascreen-vue3/src/api/visual.js
* - 端点: <baseURL>/visual/save (POST), /visual/list (GET), /visual/detail (GET), /visual/update, /visual/remove
* - nginx 代理 /api/visual/* → 32000 (jnpf-datareport-univer 微服务, 跟大屏/报表同微服务)
* - 大屏 web 端 addObj body: { visual: {password, category, status, title}, config: {detail, component} }
*
* 镜像源: jnpf/前端/jnpf-web-datascreen-vue3/src/api/visual.js (整文件)
* export const addObj = (data) => request({ url: baseUrl + '/save', method: 'post', data: { visual: {...}, config: {...} } })
*
* 之前 dacli bigscreen create 走 /extend/BigData (jnpf "大数据测试" 端点, 错), 报 BS-新12 silent fail
* 现镜像 web 端 visual.js addObj 走 /api/visual/save
*
* 特殊处理: visual.js 用 `import request from '../axios'` (相对路径, 不是 defHttp),
* loadWebModule 默认规则不替换. 不用 loader, 直接读 + 手动 replace + dynamic import.
*/
import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, dirname, basename } from 'node:path'
import { pathToFileURL } from 'node:url'
import { JnpfClient } from '../core/client.ts'
import { initDatascreenShim } from './_datascreen_shim.ts'
const DATASCREEN_SRC = '/home/ubuntu/ccWorkDir/jnpf/前端/jnpf-web-datascreen-vue3/src/api/visual.js'
const DATASCREEN_OPTION_CONFIG_SRC = '/home/ubuntu/ccWorkDir/jnpf/前端/jnpf-web-datascreen-vue3/src/option/config.js'
const DATASCREEN_OPTION_COMPONENTS_DIR = '/home/ubuntu/ccWorkDir/jnpf/前端/jnpf-web-datascreen-vue3/src/option/components'
const SHIM_DIR = dirname(new URL(import.meta.url).pathname)
const DATASCREEN_SHIM_PATH = join(SHIM_DIR, '_datascreen_shim.ts')
let cached: any = null
/**
* 初始化 webapi 层: 读 + 替换 + dynamic import (跟 _loader.ts 一样的技巧, 但单独处理)
* - 替换 1: `import { url } from '@/config'` → 删掉 (我们不需要 baseURL, 走主 client)
* - 替换 2: `import { config } from '@/option/config'` → 删掉
* - 替换 3: `import request from '../axios'` → `import { request } from '<datascreen shim path>'`
* - 替换 4: `import { url } from '@/config'; import { config } from '@/option/config' const baseUrl = url + '/visual'`
* → 删掉, 但 baseUrl 在 visual.js 里被所有方法用. 我们需要保留 const baseUrl = '/visual' (path 形式)
* - 替换 5: `let header = window.$glob.header || {}; config.headers = Object.assign(config.headers, header);`
* → 注: shim 已有 headers, 删掉这几行避免 window.$glob 引用
* - 替换 6: `const token = localStorage.getItem("token") || ''` → 注: shim 不需 token
*/
export async function initWebapi(client: JnpfClient): Promise<void> {
if (cached) return
initDatascreenShim(client)
const code = readFileSync(DATASCREEN_SRC, 'utf-8')
const patched = code
// 替换 axios import 为 shim
.replace(
/import\s+request\s+from\s+['"]\.\.\/axios['"]/,
`import { request } from '${DATASCREEN_SHIM_PATH}'\nconst config = {}; // mock @/option/config (jnpf 大屏默认配置, 简化)`,
)
// 替换 baseUrl 定义 (web 端用 url + '/visual', 我们用 const baseUrl = '/visual' 简化)
.replace(
/const\s+baseUrl\s*=\s*url\s*\+\s*['"]\/visual['"]/,
`const baseUrl = '/visual'`,
)
// 删掉 web 端 import (axios 拦截器引用了 url/config/window/localStorage, 我们不需要)
.replace(
/import\s*\{[^}]*\}\s*from\s*['"]@\/config['"];?/g,
'',
)
.replace(
/import\s*\{[^}]*\}\s*from\s*['"]@\/option\/config['"];?/g,
'',
)
.replace(
/let\s+header\s*=\s*window\.\$glob\.[^;]+;[\s\S]*?config\.headers\s*=\s*Object\.assign[^;]+;?/g,
'',
)
.replace(
/const\s+token\s*=\s*localStorage\.[^;]+;?/g,
'',
)
.replace(
/config\.headers\['Authorization'\][^;]+;?/g,
'',
)
.replace(
/const\s+appCode\s*=[^;]+;?/g,
'',
)
.replace(
/config\.headers\['App-Code'\][^;]+;?/g,
'',
)
// 写 tmp file + dynamic import
const tmpDir = join(tmpdir(), 'dacli-datascreen-' + Date.now())
mkdirSync(tmpDir, { recursive: true })
const tmpFile = join(tmpDir, 'visual.mjs')
writeFileSync(tmpFile, patched)
cached = await import(pathToFileURL(tmpFile).href)
}
export function isWebapiLoaded(): boolean {
return cached !== null
}
export const loadDatascreen: any = new Proxy({} as any, {
get(_target, prop) {
if (!cached) {
throw new Error(`datascreen 模块未初始化, 请先 await initWebapi(client)`)
}
return cached[prop]
},
})
/** 创建大屏 (镜像 web visual.js: addObj) */
export async function addObj(params: {
title: string
category: string
status?: number
password?: string
width?: number
height?: number
config?: Record<string, unknown>
}): Promise<unknown> {
return loadDatascreen.addObj(params)
}
/** 大屏列表 (镜像 web visual.js: getList) */
export async function getList(params?: Record<string, unknown>): Promise<unknown> {
return loadDatascreen.getList(params)
}
/** 大屏详情 (镜像 web visual.js: getObj) */
export async function getObj(id: string): Promise<unknown> {
return loadDatascreen.getObj(id)
}
/** 大屏分类 (镜像 web visual.js: getCategory) */
export async function getCategory(params?: Record<string, unknown>): Promise<unknown> {
return loadDatascreen.getCategory(params)
}
/** 更新大屏 (镜像 web visual.js: updateObj) */
export async function updateObj(data: Record<string, unknown>): Promise<unknown> {
return loadDatascreen.updateObj(data)
}
/** 删除大屏 (镜像 web visual.js: delObj) */
export async function delObj(id: string): Promise<unknown> {
return loadDatascreen.delObj(id)
}
// =====================================================================
// Phase 1+2: 镜像 option/config.js (基础配置) + option/components/*.vue (组件元数据)
// 详见 dacli/docs/cmd-review/v0.13-webapi-form-workflow-refactor.md §8.2
// =====================================================================
/**
* Phase 1: 镜像 jnpf-web-datascreen-vue3/src/option/config.js 第 35-72 行的 `config` 对象.
*
* 用途: dacli bigscreen construct 命令构造 save payload 时, config.detail = JSON.stringify(this.config),
* 这个 this.config 必须跟 web 设计器初始值一致 (web 端 `result.vue:50` 也 import { config as defaultConfig })
* 跟 web 端 `result.vue:163` 的 `Object.assign(defaultConfig, json.detail)` 行为一致 —
* 即 defaultConfig 是基础模板, json.detail 是覆盖.
*
* 注: 38 组件 metadata (themeList/colorOption/tableOption/dicOption) 暂时省略, 那些是设计器面板的 dic data,
* 跟 save payload 无关 (save 只 save config + nav, 不 save 元数据).
* Phase 5+ 如果要镜像 `header.vue:200-211` 完整 formdata 构造, 还需要 themeList 等.
*
* 实现策略: 直接读 web 端 option/config.js, 提取 `export const config = { ... }` 字面量对象, 用 Function 解析.
* 跟 web 端 `result.vue:50` `import { config } from '@/option/config'` 行为一致 — 都是同一个对象.
*/
let cachedBaseConfig: Record<string, unknown> | null = null
export function getBaseConfig(): Record<string, unknown> {
if (cachedBaseConfig) return cachedBaseConfig
// 简化兜底: web 端 option/config.js 第 35-72 行的默认 config 对象 (跟 shim 保持一致)
const fallback: Record<string, unknown> = {
width: 1920,
height: 1080,
query: "function(){\n return window.$glob.params || {}\n}",
header: "function(){\n return window.$glob.params || {}\n}",
screen: 'x',
mark: {
show: false,
text: '',
fontSize: 20,
color: 'rgba(100,100,100,0.2)',
degree: -20
},
scale: 1,
backgroundImage: `/img/bg/bg.png`,
url: '',
group: [],
glob: [],
theme: {},
themeId: '',
filters: {},
style: '',
before: '',
overflow: false,
styles: {
show: false,
contrast: 100,
saturate: 100,
brightness: 100,
opacity: 100,
grayscale: 0,
hueRotate: 0,
invert: 0,
blur: 0
},
gradeShow: false,
gradeLen: 30,
}
if (!existsSync(DATASCREEN_OPTION_CONFIG_SRC)) {
cachedBaseConfig = fallback
return cachedBaseConfig
}
try {
const code = readFileSync(DATASCREEN_OPTION_CONFIG_SRC, 'utf-8')
// 提取 `export const config = { ... }` 字面量 (顶层 config 对象)
// 用括号配对法, 避免非贪婪 regex 在嵌套对象 (mark, styles) 处误终止
const startIdx = code.indexOf('export const config = {')
if (startIdx === -1) {
cachedBaseConfig = fallback
return cachedBaseConfig
}
let depth = 0
let bodyStart = -1
let bodyEnd = -1
for (let i = startIdx; i < code.length; i++) {
const ch = code[i]
if (ch === '{') {
if (depth === 0) bodyStart = i + 1
depth++
} else if (ch === '}') {
depth--
if (depth === 0) {
bodyEnd = i
break
}
}
}
if (bodyStart === -1 || bodyEnd === -1) {
cachedBaseConfig = fallback
return cachedBaseConfig
}
const body = code.slice(bodyStart, bodyEnd)
// 解析: `width: 1920, ...` 转成 JS 对象
// 注: web 端 config 引用了 `theme: themeList` (同级 export), Function 不会跨文件 import.
// 在 scope 里 mock 一下 themeList = {} 即可, theme 字段对 save payload 暂时不影响.
// eslint-disable-next-line no-new-func
const parsed = Function('themeList', `return ({${body}})`)({})
if (parsed && typeof parsed === 'object') {
cachedBaseConfig = parsed as Record<string, unknown>
} else {
cachedBaseConfig = fallback
}
} catch (err) {
console.warn('[datascreen] getBaseConfig 解析失败, 用 fallback:', err)
cachedBaseConfig = fallback
}
return cachedBaseConfig
}
/**
* Phase 2: 镜像 jnpf-web-datascreen-vue3/src/option/components/<prop>.vue 的 default data 段.
*
* 用途: dacli bigscreen construct 命令构造组件 entry (nav 数组元素) 时, 知道每个 prop 类型
* (bar/line/pie/text/map/...) 的 default data 形状 (data/option/component/group/index 等).
* web 端 `build.vue` 通过 `import.meta.globEager` 加载 38 个 .vue, 然后拖拽时调 `initData()`
* 派生一个 nav entry. dacli 端不能跑 vue compiler, 只能:
* 1. 列目录 (fs.readdirSync) 找 .vue 文件
* 2. 提取 `<script>` 段的 `data() { return { ... } }` 内容
* 3. 简化元数据: hasData, name, prop, filePath
* 详细的 data() 解析留给 Phase 3 (constructConfigDetail) + Phase 5 (dacli bigscreen construct 命令)
* 一起做, 避免 Phase 2 提前膨胀.
*
* 返回值 schema (Phase 2 简化版):
* {
* prop: 'bar',
* name: 'bar' | 'echart-bar' | 'avue-echart-bar', // vue component name
* filePath: '/.../option/components/bar.vue',
* hasData: boolean, // 是否有 data() { return { ... } } 段
* dataKeys?: string[], // hasData=true 时, 列出 data 对象第一层 key (name/code/api/...)
* isOptionConfig: true, // 这是 option/config 侧的配置 UI 组件, 不是 chart 组件本身
* }
* 找不到时返回 null.
*
* 注: web 端 option/components/ 下是 36 个配置文件 UI, 实际 chart 组件在 echart/packages/<name>/index.vue
* (33 个). nav 数组里放的 component.name 是 'echart-bar'/'echart-line'/'avue-echart-bar' 等.
* Phase 2 镜像的是 option/config 侧, 它定义了 nav entry 的 default shape (option 对象, 拖到 canvas 后
* 会渲染 echart/packages 里的实际 chart).
*/
let cachedComponentFiles: string[] | null = null
function listComponentFiles(): string[] {
if (cachedComponentFiles) return cachedComponentFiles
if (!existsSync(DATASCREEN_OPTION_COMPONENTS_DIR)) {
cachedComponentFiles = []
return cachedComponentFiles
}
cachedComponentFiles = readdirSync(DATASCREEN_OPTION_COMPONENTS_DIR)
.filter(f => f.endsWith('.vue'))
.map(f => f.replace(/\.vue$/, ''))
.sort()
return cachedComponentFiles
}
// 解析 .vue 文件的 <script> 段, 提取 default export 的 data() 段 (简化版: 只取 key 列表)
interface ParsedVueScript {
name: string
dataKeys: string[]
hasData: boolean
}
function parseVueScript(script: string): ParsedVueScript {
// 提取 name: 'xxx' 或 name: "xxx"
const nameMatch = script.match(/name\s*:\s*['"]([^'"]+)['"]/)
const name = nameMatch ? nameMatch[1] : ''
// 提取 data() { return { ... } } 段 (用括号配对避免嵌套误判)
const dataIdx = script.search(/data\s*\(\s*\)\s*\{/)
if (dataIdx === -1) {
return { name, dataKeys: [], hasData: false }
}
// 找到 data() 之后的第一个 {, 然后配对找 }
const openBrace = script.indexOf('{', dataIdx)
if (openBrace === -1) return { name, dataKeys: [], hasData: false }
let depth = 0
let dataBodyEnd = -1
for (let i = openBrace; i < script.length; i++) {
if (script[i] === '{') depth++
else if (script[i] === '}') {
depth--
if (depth === 0) { dataBodyEnd = i; break }
}
}
if (dataBodyEnd === -1) return { name, dataKeys: [], hasData: false }
// 在 data() body 内找 `return { ... }`, 然后列出 top-level key
const dataBody = script.slice(openBrace + 1, dataBodyEnd)
const returnIdx = dataBody.indexOf('return')
if (returnIdx === -1) return { name, dataKeys: [], hasData: false }
const returnOpen = dataBody.indexOf('{', returnIdx)
if (returnOpen === -1) return { name, dataKeys: [], hasData: false }
// 找 return { ... } 的对应 }
let rd = 0
let returnEnd = -1
for (let i = returnOpen; i < dataBody.length; i++) {
if (dataBody[i] === '{') rd++
else if (dataBody[i] === '}') {
rd--
if (rd === 0) { returnEnd = i; break }
}
}
if (returnEnd === -1) return { name, dataKeys: [], hasData: false }
const returnBody = dataBody.slice(returnOpen + 1, returnEnd)
// 列 top-level key
const keyRegex = /^\s*([a-zA-Z_$][\w$]*)\s*:/gm
const keys: string[] = []
let m: RegExpExecArray | null
while ((m = keyRegex.exec(returnBody)) !== null) {
if (!keys.includes(m[1])) keys.push(m[1])
}
return { name, dataKeys: keys, hasData: keys.length > 0 }
}
const componentFileCache = new Map<string, ParsedVueScript & { filePath: string }>()
export interface ComponentDefaults {
/** 组件 prop 名 (e.g. 'bar'/'line'/'text'/'pie'/'map'/'video'/'swiper'/'iframe'/'table') */
prop: string
/** .vue 文件里 `name: 'xxx'` 字段, web 端 `components.js:10` 用 `cmp.name + 'Option'` 做 component name */
name: string
/** 完整 .vue 文件路径 */
filePath: string
/** 是否有 `data() { return { ... } }` 段 */
hasData: boolean
/** hasData=true 时, 列出 data 对象 top-level key 列表 (e.g. ['api', 'code', 'dicOption']) */
dataKeys: string[]
/** 标记这是 option/config 侧的配置 UI 组件, 跟 echart/packages 侧的 chart 组件区分 */
isOptionConfig: true
}
export function getComponentDefaults(prop: string): ComponentDefaults | null {
if (!prop || typeof prop !== 'string') return null
if (componentFileCache.has(prop)) {
const cached = componentFileCache.get(prop)!
return { ...cached, prop, isOptionConfig: true as const }
}
const filePath = join(DATASCREEN_OPTION_COMPONENTS_DIR, prop + '.vue')
if (!existsSync(filePath)) return null
try {
const code = readFileSync(filePath, 'utf-8')
// 提取 <script>...</script> 段
const scriptMatch = code.match(/<script[^>]*>([\s\S]*?)<\/script>/)
if (!scriptMatch) return null
const { name, dataKeys, hasData } = parseVueScript(scriptMatch[1])
const result: ComponentDefaults = { prop, name, filePath, hasData, dataKeys, isOptionConfig: true }
componentFileCache.set(prop, result)
return result
} catch (err) {
console.warn(`[datascreen] getComponentDefaults(${prop}) 解析失败:`, err)
return null
}
}
/** 列出 option/components/ 下所有 prop 名 (e.g. ['audio', 'bar', 'borderBox', ...]) */
export function listComponentProps(): string[] {
return listComponentFiles()
}
/**
* v0.15+ (P1-4, 2026-07-02): 镜像 web 端 build.vue:1040-1042 validProp 真值源
*
* 镜像源: jnpf-web-datascreen-vue3/src/option/config.js:268 dicOption.dataList
* - 30 hardcoded props (含 code/imgList/imgTabs/rectangle 等 components/*.vue 目录里没有的)
* - + website.componentsList.filter(ele => ele.data === true).map(ele => ele.name)
*
* 旧版 listComponentProps() 走 option/components/*.vue 目录扫描, 漏 code/imgList/imgTabs/rectangle
* → 误报 "prop=code 不在 36 个有效列表里", 但 web 设计器完全允许
*
* 实现: 正则读 dicOption.dataList 数组字面量, 取 hardcoded 部分 (website.componentsList 需要登录态)
*
* @returns 30 个硬编码 valid props
*/
export function getValidProps(): string[] {
if (!existsSync(DATASCREEN_OPTION_CONFIG_SRC)) {
return listComponentFiles() // 兜底走旧逻辑
}
try {
const code = readFileSync(DATASCREEN_OPTION_CONFIG_SRC, 'utf-8')
// 找 dicOption.dataList 数组字面量
// 匹配: dataList: ['xxx', 'yyy', ...].concat(...)
const m = code.match(/dataList:\s*\[([^\]]+)\]/)
if (!m) return listComponentFiles()
// 提取 hardcoded 部分 ('xxx' 形式), 跳过后续 .concat(...)
const arr = m[1]
const props: string[] = []
const re = /'([^']+)'/g
let mm: RegExpExecArray | null
while ((mm = re.exec(arr)) !== null) {
props.push(mm[1])
}
// 去重
return Array.from(new Set(props))
} catch {
return listComponentFiles()
}
}
// =====================================================================
// Phase 3: 镜像 save 数据结构 (header.vue:200-211) → constructConfigDetail + constructComponentJson
// 详见 dacli/docs/cmd-review/v0.13-webapi-form-workflow-refactor.md §8.2.4 阶段 3
//
// 镜像源:
// - jnpf/前端/jnpf-web-datascreen-vue3/src/page/group/header.vue:200-211 (save 按钮 formdata)
// const formdata = {
// visual: { id, backgroundUrl },
// config: { id, visualId, detail: JSON.stringify(this.contain.config),
// component: JSON.stringify(this.contain.nav) }
// }
// updateComponent(formdata) // POST /visual/update
// - jnpf/前端/jnpf-web-datascreen-vue3/src/option/config.js (基础 config 对象)
// - jnpf/前端/jnpf-web-datascreen-vue3/src/option/components/<prop>.vue (组件元数据)
// =====================================================================
/**
* 构造 save formdata 的 visual + config 段 (镜像 header.vue:200-211)
*
* 用途: dacli bigscreen construct 命令构造 save payload 时, 把 baseConfig + nav 数组包装成
* web 端 updateComponent 期望的 formdata 结构. updateComponent = /api/visual/update.
*
* 参数:
* - baseConfig: 来自 getBaseConfig() 的基础 config 对象 (可被用户字段覆盖)
* - nav: 来自 constructComponentJson() 的组件列表数组
* - visualId: 已有大屏的 visual.id (新建时传 undefined)
*
* 返回:
* {
* visual: { id?, backgroundUrl },
* config: { visualId?, detail: JSON string, component: JSON string }
* }
*
* 注:
* - 镜像 web 端: config.id 不需要, 后端用 visualId 关联 visual + config 两表
* - backgroundUrl 在新建时是空字符串, 后续上传缩略图后才有
*/
export function constructConfigDetail(
baseConfig: Record<string, unknown>,
nav: Array<Record<string, unknown>>,
options: { visualId?: string; backgroundUrl?: string } = {},
): { visual: Record<string, unknown>; config: Record<string, unknown> } {
const visual: Record<string, unknown> = {}
if (options.visualId) visual.id = options.visualId
if (options.backgroundUrl !== undefined) visual.backgroundUrl = options.backgroundUrl
const config: Record<string, unknown> = {
detail: JSON.stringify(baseConfig),
component: JSON.stringify(nav),
}
if (options.visualId) config.visualId = options.visualId
return { visual, config }
}
/**
* 构造组件 nav 数组元素 (镜像 build.vue:705-709 + option/components/<prop>.vue)
*
* 镜像源: web 端 build.vue 的 nav 数组元素结构
* { index, name, display, lock, group, option, component: {prop}, data: {dataType, value, url, sql, ...}, children? }
*
* 参数 (c prop 来自 web 端 option/components/ 下的 36 个 .vue 文件):
* - prop: 组件类型 ('bar'/'line'/'text'/'map'/'video'/'table'/'iframe'/...)
* - x, y, w, h: 位置 + 尺寸 (默认 0/0/400/300)
* - dataType: 0-7 镜像 build.vue:666-689
* 0=static(无), 1=api(有 url), 2=sql(有 sql), 3=ws(有 url),
* 4=record(有 value), 5=public(有 url), 6=mqtt(有 url), 7=node
* - value: static/record 类型数据值
* - url: api/ws/public/mqtt 类型 URL
* - sql: sql 类型 SQL 语句
* - children: 文件夹/轮播子组件 (isFolder 判断)
*
* 返回: nav 数组元素, 含 index/name/display/lock/group/option/component/data/children
*
* 注:
* - index 用全局自增 id (web 端 build.vue 用 Date.now() 派生), 简单用时间戳 + 位置
* - option 用 getComponentDefaults() 拿 data() 第一层 key 作为 option 默认 shape
* (简化: 不深拷 data 体, 假设 option 字段列表够渲染配置面板用)
* - isFolder 镜像 build.vue:690-692: activeObj.children 存在即为文件夹 (轮播)
*/
export interface NavEntryInput {
prop: string
x?: number
y?: number
w?: number
h?: number
dataType?: number
value?: string | number
url?: string
sql?: string
/** 嵌套子组件 (文件夹/轮播) */
children?: NavEntryInput[]
/** web 端 index 字段, 缺省时用 Date.now() + random 派生 */
index?: number
}
export interface NavEntry {
index: number
name: string
display: boolean
lock: boolean
group: number
option: Record<string, unknown>
component: Record<string, unknown>
data: {
dataType: number
value?: string | number
url?: string
sql?: string
[key: string]: unknown
}
children?: NavEntry[]
}
let _navIndexSeed = Date.now() & 0xffffff
export function constructComponentJson(components: NavEntryInput[]): NavEntry[] {
return components.map((c, i) => {
const idx = c.index !== undefined ? c.index : (_navIndexSeed = (_navIndexSeed + 1) & 0xffffff)
const navEntry: NavEntry = {
index: idx,
name: c.prop,
display: true,
lock: false,
group: 0,
option: getComponentDefaults(c.prop) ? (getComponentDefaults(c.prop) as unknown as Record<string, unknown>) : {},
component: {
prop: c.prop,
x: c.x ?? 0,
y: c.y ?? i * 320, // 简单纵向堆叠, 避免组件重叠
w: c.w ?? 400,
h: c.h ?? 300,
},
data: {
dataType: c.dataType ?? 0,
...(c.value !== undefined ? { value: c.value } : {}),
...(c.url !== undefined ? { url: c.url } : {}),
...(c.sql !== undefined ? { sql: c.sql } : {}),
},
}
if (c.children && c.children.length > 0) {
navEntry.children = constructComponentJson(c.children)
}
return navEntry
})
}