/** * Bricks JSON 解析引擎 * 将 bricks JSON 解析为小程序可渲染的数据结构 */ class BricksParser { constructor() { this.widgetTree = null } /** * 解析 JSON 字符串 */ parse(jsonString) { try { const obj = JSON.parse(jsonString) this.widgetTree = this._parseNode(obj) return this.widgetTree } catch (e) { console.error('[Bricks] Parse error:', e) return null } } /** * 递归解析节点 */ _parseNode(obj) { if (!obj || typeof obj !== 'object') return null const node = { widgettype: obj.widgettype || 'Text', options: obj.options || {}, binds: obj.binds || [], subwidgets: [], // 扁平化事件数据,方便 WXML 绑定 _hasBind: (obj.binds && obj.binds.length > 0), _bindData: obj.binds ? obj.binds.map(b => ({ event: b.event || 'tap', actiontype: b.actiontype, target: b.target, methodname: b.methodname || b.method, params: b.params, url: b.url || (b.options && b.options.url), script: b.script })) : [], _primaryBind: obj.binds && obj.binds.length > 0 ? { event: obj.binds[0].event || 'tap', actiontype: obj.binds[0].actiontype, target: obj.binds[0].target, methodname: obj.binds[0].methodname || obj.binds[0].method, params: obj.binds[0].params, url: obj.binds[0].url || (obj.binds[0].options && obj.binds[0].options.url), script: obj.binds[0].script } : null } // 递归处理子组件 if (obj.subwidgets && Array.isArray(obj.subwidgets)) { node.subwidgets = obj.subwidgets.map(child => this._parseNode(child)) } return node } /** * 解析多个 JSON(如分页加载) */ parseList(jsonArray) { return jsonArray.map(json => { if (typeof json === 'string') return this.parse(json) return this._parseNode(json) }) } } module.exports = { BricksParser }