vue-mod-page/src/components/Receiver.ts

137 lines
4.1 KiB
TypeScript
Raw Normal View History

2024-12-19 13:51:07 +08:00
import { defineComponent, nextTick, onMounted, ref, getCurrentInstance, isVue3, h } from 'vue-demi';
import { hh } from './DemiHelper';
import SlotTester from '../SlotTester.vue';
console.log('receiver-loaded');
function renderContext(item: object | Array<any>, toSlot: boolean = false) {
/**
*
* # { tag: 'div', attrs: undefined, children: 'hhh' } => h('span', undefined, 'hhh')
*/
if (typeof item === 'string')
return item;
/**
*
* # { tag: 'div', attrs: undefined, children: () => 'hhh' } => h('span', undefined, 'hhh')
*/
if (typeof (item) === "function") {
// return item;
return item();
}
/**
*
* # { tag: 'div', attrs: undefined, [ { tag: 'span', attrs: undefined, 'hhh' } ] } => h('div', undefined, [ h('span', undefined, 'hhh') ])
*/
if (Array.isArray(item)) {
const list = item.map(i => {
if (isVue3) {
// const comp = resolveComponent(i.tag);
return hh(i.tag, i.attrs, i.children);
// return hDemi(comp, i.attrs, renderContext(i.children, typeof (comp) !== 'string') as any); // vue3
}
// const { attrs, listeners, ref } = splitAttrs(i.attrs);
const slots = renderContext(i.children);
if (typeof (slots) === "object") {
return hh(i.tag, {
attrs: i.attrs
// attrs,
// on: listeners,
// scopedSlots: slots,
// ref
});
}
return hh(i.tag, {
attrs: i.attrs,
}, slots);
});
if (toSlot) {
return () => list;
}
return list;
}
/**
*
* #
*/
const children: Record<string, any> = {};
for (const key in item) {
children[key] = function (scope) {
const child = item[key](scope);
if (isVue3) {
return hh(child.tag, child.attrs, renderContext(child.children, true));
}
if (Array.isArray(child)) {
const slots = renderContext(child);
return slots;
} else {
// const { attrs, listeners, ref } = splitAttrs(child.attrs);
const slots = renderContext(child.children);
return hh(child.tag, {
attrs: child.attrs
// attrs,
// on: listeners,
// ref
}, slots);
}
};
}
return children;
}
export default defineComponent({
name: 'Receiver',
props: {
parentId: {
type: [Number, String],
default: () => 0
}
},
setup(props) {
const instance = getCurrentInstance();
let invokerContext: any = null;
const renderVersion = ref(0);
if (window.parent != window) {
const invoker = window.parent['MES_MOD_INVOKERS'][props.parentId];
invokerContext = invoker;
}
onMounted(() => {
nextTick().then(() => {
console.log('mounted-finish');
if (!invokerContext['modContext']) {
invokerContext.initFinish(instance?.proxy);
}
});
});
return () => {
try {
console.log('receiver-update', renderVersion.value);
if (renderVersion.value < 0) return;
if (invokerContext.getRenderContext) {
const itemList = invokerContext.getRenderContext();
// const list = renderContext(itemList);
// console.log('item-list', list);
return hh('div', undefined, itemList);
}
return hh('div');
}
catch (e) {
console.error("[Receiver] 渲染节点过程中出现错误", e);
}
};
}
});