Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: blockCompile get correct version #964

Merged
merged 7 commits into from
Dec 31, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/block-compiler/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export interface IResultMap {
[key: string]: compiledItem
}

const resolveRelativeImport = (code: string, globalGetterName = 'getBlockComponentBlobUrl') => {
const resolveRelativeImport = (code: string, globalGetterName = 'loadBlockComponent') => {
const magicStr = new MagicString(code)
const ast = babelParse(code, { sourceType: 'module', plugins: ['jsx'] }).program.body

Expand Down Expand Up @@ -86,7 +86,7 @@ const resolveRelativeImport = (code: string, globalGetterName = 'getBlockCompone
// 声明异步组件 const Block = defineAsyncComponent(() => import(getBlockUrl(Block)))
magicStr.appendLeft(
node.start!,
`const ${defaultImportId} = defineAsyncComponent(() => import(window.${globalGetterName}('${fileName}')))`
`const ${defaultImportId} = defineAsyncComponent(async () => window.${globalGetterName}('${fileName}'))`
)

// 移除 import Block from './Block.vue' 语句
Expand Down
4 changes: 2 additions & 2 deletions packages/canvas/container/src/container.js
Original file line number Diff line number Diff line change
Expand Up @@ -822,8 +822,8 @@ export const canvasApi = {
getDocument,
canvasDispatch,
Builtin,
removeBlockCompsCacheByName: (...args) => {
return canvasState.renderer.removeBlockCompsCacheByName(...args)
removeBlockCompsCache: (...args) => {
return canvasState.renderer.removeBlockCompsCache(...args)
},
updateCanvas: (...args) => {
return canvasState.renderer.updateCanvas(...args)
Expand Down
4 changes: 2 additions & 2 deletions packages/canvas/render/src/RenderMain.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import renderer, {
setController,
globalNotify,
isStateAccessor,
removeBlockCompsCacheByName
removeBlockCompsCache
} from './render'
import { setContext, getContext, setCondition, context, getDesignMode, setDesignMode } from './context'
import CanvasEmpty from './CanvasEmpty.vue'
Expand Down Expand Up @@ -505,6 +505,6 @@ export const api = {
setRenderer,
getDesignMode,
setDesignMode,
removeBlockCompsCacheByName,
removeBlockCompsCache,
updateCanvas
}
77 changes: 32 additions & 45 deletions packages/canvas/render/src/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -254,65 +254,52 @@ const parseFunctionString = (fnStr) => {
return null
}

const blockComponentsMap = new Map()
const blockComponentsBlobUrlMap = new Map()

// TODO: 这里的全局 getter 方法名,可以做成配置化
window.getBlockComponentBlobUrl = (name) => blockComponentsBlobUrlMap.get(name)

const getBlockComponent = (name) => {
if (blockComponentsMap.has(name)) {
return blockComponentsMap.get(name)
}

const BlockComp = defineAsyncComponent(async () => {
try {
const blocksBlob = await getController().getBlockByName(name)
const loadBlockComponent = async (name) => {
try {
if (blockComponentsBlobUrlMap.has(name)) {
return import(/* @vite-ignore */ blockComponentsBlobUrlMap.get(name))
}

for (const [fileName, value] of Object.entries(blocksBlob)) {
// 注册异步组件
blockComponentsMap.set(
fileName,
defineAsyncComponent(() => import(/* @vite-ignore */ value.blobURL))
)
const blocksBlob = await getController().getBlockByName(name)

blockComponentsBlobUrlMap.set(fileName, value.blobURL)
for (const [fileName, value] of Object.entries(blocksBlob)) {
blockComponentsBlobUrlMap.set(fileName, value.blobURL)

if (!value.style) {
continue
}
if (!value.style) {
continue
}

// 注册 CSS,以区块为维度
const stylesheet = document.querySelector(`#${fileName}`)
// 注册 CSS,以区块为维度
const stylesheet = document.querySelector(`#${fileName}`)

if (stylesheet) {
stylesheet.innerHTML = value.style
} else {
const newStylesheet = document.createElement('style')
newStylesheet.innerHTML = value.style
document.head.appendChild(newStylesheet)
}
if (stylesheet) {
stylesheet.innerHTML = value.style
} else {
const newStylesheet = document.createElement('style')
newStylesheet.innerHTML = value.style
document.head.appendChild(newStylesheet)
}

return blockComponentsMap.get(name)
} catch (error) {
// 加载错误提示
return h(BlockLoadError, { name })
}
})

return BlockComp
return import(/* @vite-ignore */ blockComponentsBlobUrlMap.get(name))
} catch (error) {
// 加载错误提示
return h(BlockLoadError, { name })
}
}

// 移除区块缓存
export const removeBlockCompsCacheByName = (name) => {
if (blockComponentsMap.has(name)) {
blockComponentsMap.delete(name)
}
window.loadBlockComponent = loadBlockComponent

if (blockComponentsBlobUrlMap.has(name)) {
blockComponentsBlobUrlMap.delete(name)
}
const getBlockComponent = (name) => {
return defineAsyncComponent(async () => loadBlockComponent(name))
}

// 移除区块缓存
export const removeBlockCompsCache = () => {
blockComponentsBlobUrlMap.clear()
}

export const getComponent = (name) => {
Expand Down
63 changes: 39 additions & 24 deletions packages/plugins/materials/src/composable/block-compile.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,35 @@
import { getMetaApi, META_SERVICE, useMaterial, useResource, useCanvas } from '@opentiny/tiny-engine-meta-register'
import { compile as blockCompiler } from '@opentiny/tiny-engine-block-compiler'

const blockVersionMap = new Map()
const blockCompileCache = new Map()

// 获取所有区块分组下的所有区块
const getAllGroupBlocks = async () => {
const { fetchGroups, fetchGroupBlocksByIds } = getMetaApi('engine.plugins.materials.block')
const appId = getMetaApi(META_SERVICE.GlobalService).getBaseInfo().id

const groups = await fetchGroups(appId)

const groupIds = groups.map((groupItem) => groupItem.id)

const blocks = await fetchGroupBlocksByIds({ groupIds })

for (const blockItem of blocks) {
if (blockItem?.content?.fileName && blockItem?.current_version) {
blockVersionMap.set(blockItem.content.fileName, blockItem.current_version)
}
}
}

export const fetchBlockSchema = async (blockName) =>
getMetaApi(META_SERVICE.Http).get(`/material-center/api/block?label=${blockName}`)

// TODO: 待验证
export const updateBlockCompileCache = (name) => {
if (blockCompileCache.has(name)) {
blockCompileCache.delete(name)

useCanvas().canvasApi.value?.removeBlockCompsCacheByName(name)
}
export const updateBlockCompileCache = () => {
blockVersionMap.clear()
useCanvas().canvasApi.value?.removeBlockCompsCache()
blockCompileCache.clear()
}

// 预构建 block
Expand All @@ -26,26 +43,19 @@ export const getBlockCompileRes = async (schema) => {
}

const generateCodeService = getMetaApi('engine.service.generateCode')
const blocks = await generateCodeService.getAllNestedBlocksSchema(schema, fetchBlockSchema)
const componentsMap = useResource().appSchemaState.componentsMap

// 调用 api 得到页面出码结果
let blocksSourceCode = null
const blocksWithoutCache = blocks.filter((blockItem) => !blockCompileCache.has(blockItem.fileName))

// 需要出码的区块
blocksSourceCode = [schema, ...blocksWithoutCache].map((blockSchema) => {
const sourceCode = generateCodeService.generatePageCode(blockSchema, componentsMap || [], {
blockRelativePath: './'
})

return {
fileName: blockSchema.fileName,
sourceCode
}
const sourceCode = generateCodeService.generatePageCode(schema, componentsMap || [], {
blockRelativePath: './'
})

const compiledResult = blockCompiler(blocksSourceCode, {
const blocksSourceCode = {
fileName: schema.fileName,
sourceCode
}

const compiledResult = blockCompiler([blocksSourceCode], {
compileCache: blockCompileCache
})

Expand All @@ -54,6 +64,11 @@ export const getBlockCompileRes = async (schema) => {

// 获取 blockBlob
export const getBlockByName = async (name) => {
// version map 为空,获取所有区块的版本记录
if (blockVersionMap.size === 0) {
await getAllGroupBlocks()
}

// 找到对应区块的 schema
const block = await fetchBlockSchema(name)
const blockItem = block?.[0]
Expand All @@ -62,13 +77,13 @@ export const getBlockByName = async (name) => {
return
}

const historyId = blockItem?.current_history
const historySchema = blockItem?.histories?.find?.((historyItem) => historyItem?.id === historyId)
const historyVersion = blockVersionMap.get(name)
const historySchema = blockItem?.histories?.find?.((historyItem) => historyItem?.version === historyVersion)

let schemaContent = null

// 有指定的历史版本,优先选用历史版本
if (historyId && historySchema?.content) {
if (historyVersion && historySchema?.content) {
schemaContent = historySchema.content
} else {
schemaContent = blockItem?.content
Expand Down
5 changes: 3 additions & 2 deletions packages/plugins/materials/src/meta/block/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import entry from './src/Main.vue'
import metaData from './meta'
import { fetchGroups } from './src/http'
import { fetchGroups, fetchGroupBlocksByIds } from './src/http'

export default {
...metaData,
entry,
apis: {
fetchGroups
fetchGroups,
fetchGroupBlocksByIds
},
options: {
title: '区块'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,16 +88,9 @@ export default {
isRefresh.value = true
closePanel()
// 刷新缓存
useMaterial().updateBlockCompileCache(selectedRow.content?.fileName)
useMaterial().updateBlockCompileCache()
// 刷新画布
useCanvas().canvasApi.value?.updateCanvas()
// confirm({
// title: '切换区块版本成功',
// message: `${selectedBlock.value.label}区块,已切换为${selectedRow.version}版本,修改版本后需要刷新页面才生效,是否刷新页面?`,
// exec: () => {
// window.location.reload()
// }
// })
})
.catch((error) => {
message({
Expand Down
Loading