import { defineComponent, h, ref, onMounted } from 'vue'
import { getController } from '../canvas-function'
import RenderMain from '../RenderMain'
import { handleScopedCss } from './handle-scoped-css'
import { utils } from '@opentiny/tiny-engine-utils'
const { objectCssToString } = utils
const pageSchema: Record<string, any> = {}
async function fetchPageSchema(pageId: string) {
return getController()
.getPageById(pageId)
.then((res: any) => {
return res.page_content
})
}
export function initStyle(key: string, content: string | object) {
if (!content) {
return
}
let styleSheet = document.querySelector(`#${key}`)
if (!styleSheet) {
styleSheet = document.createElement('style')
styleSheet.setAttribute('id', key)
if (getController().enableTailwindCSS) {
styleSheet.setAttribute('type', 'text/tailwindcss')
}
document.head.appendChild(styleSheet)
}
handleScopedCss(key, objectCssToString(content)).then((scopedCss) => {
styleSheet.textContent = scopedCss.css
})
}
export const wrapPageComponent = (pageId: string) => {
const key = `data-te-page-${pageId}`
const asyncData = ref(null)
const updateSchema = () => {
fetchPageSchema(pageId).then((data) => {
asyncData.value = data
})
}
updateSchema()
pageSchema[pageId] = defineComponent({
name: `page-${pageId}`,
setup() {
const active = ref(pageId === getController().getBaseInfo().pageId)
onMounted(() => {
updateSchema()
})
return () => {
if (active.value || asyncData.value) {
return h(RenderMain, {
cssScopeId: key,
renderSchema: asyncData.value as any,
active: active.value,
pageId: pageId,
entry: false
})
}
return null
}
}
})
return pageSchema[pageId]
}
export const getPage = (pageId: string) => {
return pageSchema[pageId] || wrapPageComponent(pageId)
}
export async function getPageAncestors(pageId?: string) {
if (!pageId) {
return []
}
if (!getController().getPageAncestors) {
return [pageId]
}
const pageChain = await getController().getPageAncestors(pageId)
return [...pageChain.map((id: number | string) => String(id)), pageId]
}